Reload strlist and iplist resource-files only when needed.
[apps/pfixtools.git] / postlicyd / config.c
1 /******************************************************************************/
2 /*          pfixtools: a collection of postfix related tools                  */
3 /*          ~~~~~~~~~                                                         */
4 /*  ________________________________________________________________________  */
5 /*                                                                            */
6 /*  Redistribution and use in source and binary forms, with or without        */
7 /*  modification, are permitted provided that the following conditions        */
8 /*  are met:                                                                  */
9 /*                                                                            */
10 /*  1. Redistributions of source code must retain the above copyright         */
11 /*     notice, this list of conditions and the following disclaimer.          */
12 /*  2. Redistributions in binary form must reproduce the above copyright      */
13 /*     notice, this list of conditions and the following disclaimer in the    */
14 /*     documentation and/or other materials provided with the distribution.   */
15 /*  3. The names of its contributors may not be used to endorse or promote    */
16 /*     products derived from this software without specific prior written     */
17 /*     permission.                                                            */
18 /*                                                                            */
19 /*  THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND   */
20 /*  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE     */
21 /*  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR        */
22 /*  PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS    */
23 /*  BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR    */
24 /*  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF      */
25 /*  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS  */
26 /*  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN   */
27 /*  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)   */
28 /*  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF    */
29 /*  THE POSSIBILITY OF SUCH DAMAGE.                                           */
30 /******************************************************************************/
31
32 /*
33  * Copyright © 2008 Florent Bruneau
34  */
35
36 #include "file.h"
37 #include "config.h"
38 #include "str.h"
39 #include "resources.h"
40
41 #define config_param_register(Param)
42
43 /* Filter to execute on "CONNECT"
44  */
45 config_param_register("client_filter");
46
47 /* Filter to execute on "MAIL FROM"
48  */
49 config_param_register("sender_filter");
50
51 /* Filter to execute on "RCPT TO"
52  */
53 config_param_register("recipient_filter");
54
55 /* Filter to execute on "DATA"
56  */
57 config_param_register("data_filter");
58
59 /* Filter to execute on "END-OF-DATA"
60  */
61 config_param_register("end_of_data_filter");
62
63 /* Filter to execute on "ETRN"
64  */
65 config_param_register("etrn_filter");
66
67 /* Filter to execute on "HELO"
68  */
69 config_param_register("helo_filter");
70 config_param_register("ehlo_filter");
71
72 /* Filter to execute on "VRFY"
73  */
74 config_param_register("verify_filter");
75
76
77 /* Where to bind the server.
78  */
79 config_param_register("port");
80
81
82 static config_t *global_config = NULL;
83
84 static inline config_t *config_new(void)
85 {
86     config_t *config = p_new(config_t, 1);
87     global_config = config;
88     return config;
89 }
90
91 static void config_close(config_t *config)
92 {
93     for (int i = 0 ; i < SMTP_count ; ++i) {
94         config->entry_points[i] = -1;
95     }
96     array_deep_wipe(config->filters, filter_wipe);
97     array_deep_wipe(config->params, filter_params_wipe);
98 }
99
100 void config_delete(config_t **config)
101 {
102     if (*config) {
103         config_close(*config);
104         p_delete(config);
105         global_config = NULL;
106     }
107 }
108
109 static void config_exit()
110 {
111     if (global_config) {
112         config_delete(&global_config);
113     }
114 }
115 module_exit(config_exit);
116
117
118 static bool config_parse(config_t *config)
119 {
120     filter_t filter;
121     file_map_t map;
122     const char *p;
123     int line = 0;
124     const char *linep;
125     bool in_section = false;
126     bool end_of_section = false;
127
128     char key[BUFSIZ];
129     char value[BUFSIZ];
130     int key_len, value_len;
131
132     if (!file_map_open(&map, config->filename, false)) {
133         return false;
134     }
135
136     filter_init(&filter);
137     linep = p = map.map;
138
139 #define READ_LOG(Lev, Fmt, ...)                                                \
140     __log(LOG_ ## Lev, "config file %s:%d:%d: " Fmt, config->filename,         \
141            line + 1, (int)(p - linep + 1), ##__VA_ARGS__)
142 #define READ_ERROR(Fmt, ...)                                                   \
143     do {                                                                       \
144         READ_LOG(ERR, Fmt, ##__VA_ARGS__);                                     \
145         goto error;                                                            \
146     } while (0)
147 #define ADD_IN_BUFFER(Buffer, Len, Char)                                       \
148     do {                                                                       \
149         if ((Len) >= BUFSIZ - 1) {                                             \
150             READ_ERROR("unreasonnable long line");                             \
151         }                                                                      \
152         (Buffer)[(Len)++] = (Char);                                            \
153         (Buffer)[(Len)]   = '\0';                                              \
154     } while (0)
155 #define READ_NEXT                                                              \
156     do {                                                                       \
157         if (*p == '\n') {                                                      \
158             ++line;                                                            \
159             linep = p + 1;                                                     \
160         }                                                                      \
161         if (++p >= map.end) {                                                  \
162             if (!end_of_section) {                                             \
163                 if (in_section) {                                              \
164                     goto badeof;                                               \
165                 } else {                                                       \
166                     goto ok;                                                   \
167                 }                                                              \
168             }                                                                  \
169         }                                                                      \
170     } while (0)
171 #define READ_BLANK                                                             \
172     do {                                                                       \
173         bool in_comment = false;                                               \
174         while (in_comment || isspace(*p) || *p == '#') {                       \
175             if (*p == '\n') {                                                  \
176                 in_comment = false;                                            \
177             } else if (*p == '#') {                                            \
178                 in_comment = true;                                             \
179             }                                                                  \
180             READ_NEXT;                                                         \
181         }                                                                      \
182     } while (0)
183 #define READ_TOKEN(Name, Buffer, Len)                                          \
184     do {                                                                       \
185         (Len) = 0;                                                             \
186         (Buffer)[0] = '\0';                                                    \
187         if (!isalpha(*p)) {                                                    \
188             READ_ERROR("invalid %s, unexpected character '%c'", Name, *p);     \
189         }                                                                      \
190         do {                                                                   \
191             ADD_IN_BUFFER(Buffer, Len, *p);                                    \
192             READ_NEXT;                                                         \
193         } while (isalnum(*p) || *p == '_');                                    \
194     } while (0)
195 #define READ_STRING(Name, Buffer, Len, Ignore)                                 \
196     do {                                                                       \
197         (Len) = 0;                                                             \
198         (Buffer)[0] = '\0';                                                    \
199         if (*p == '"') {                                                       \
200             bool escaped = false;                                              \
201             while (*p == '"') {                                                \
202                 READ_NEXT;                                                     \
203                 while (true) {                                                 \
204                     if (*p == '\n') {                                          \
205                         READ_ERROR("string must not contain EOL");             \
206                     } else if (escaped) {                                      \
207                         ADD_IN_BUFFER(Buffer, Len, *p);                        \
208                         escaped = false;                                       \
209                     } else if (*p == '\\') {                                   \
210                         escaped = true;                                        \
211                     } else if (*p == '"') {                                    \
212                         READ_NEXT;                                \
213                         break;                                                 \
214                     } else {                                                   \
215                         ADD_IN_BUFFER(Buffer, Len, *p);                        \
216                     }                                                          \
217                     READ_NEXT;                                                 \
218                 }                                                              \
219                 READ_BLANK;                                                    \
220             }                                                                  \
221             if (*p != ';') {                                                   \
222                 READ_ERROR("%s must end with a ';'", Name);                    \
223             }                                                                  \
224         } else {                                                               \
225             bool escaped = false;                                              \
226             while (*p != ';' && isascii(*p) && (isprint(*p) || isspace(*p))) { \
227                 if (escaped) {                                                 \
228                     if (*p == '\r' || *p == '\n') {                            \
229                         READ_BLANK;                                            \
230                     } else {                                                   \
231                         ADD_IN_BUFFER(Buffer, Len, '\\');                      \
232                     }                                                          \
233                     escaped = false;                                           \
234                 }                                                              \
235                 if (*p == '\\') {                                              \
236                     escaped = true;                                            \
237                 } else if (*p == '\r' || *p == '\n') {                         \
238                     READ_ERROR("%s must not contain EOL", Name);               \
239                 } else {                                                       \
240                     ADD_IN_BUFFER(Buffer, Len, *p);                            \
241                 }                                                              \
242                 READ_NEXT;                                                     \
243             }                                                                  \
244             if (escaped) {                                                     \
245                 ADD_IN_BUFFER(Buffer, Len, '\\');                              \
246             }                                                                  \
247             while ((Len) > 0 && isspace((Buffer)[(Len) - 1])) {                \
248                 (Buffer)[--(Len)] = '\0';                                      \
249             }                                                                  \
250         }                                                                      \
251         end_of_section = Ignore;                                               \
252         READ_NEXT;                                                             \
253     } while(0)
254
255
256 read_section:
257     if (p >= map.end) {
258         goto ok;
259     }
260
261     value[0] = key[0] = '\0';
262     value_len = key_len = 0;
263
264     in_section = end_of_section = false;
265     READ_BLANK;
266     in_section = true;
267     READ_TOKEN("section name", key, key_len);
268     READ_BLANK;
269     switch (*p) {
270       case '=':
271         READ_NEXT;
272         goto read_param_value;
273       case '{':
274         READ_NEXT;
275         goto read_filter;
276       default:
277         READ_ERROR("invalid character '%c', expected '=' or '{'", *p);
278     }
279
280 read_param_value:
281     READ_BLANK;
282     READ_STRING("parameter value", value, value_len, true);
283     {
284         filter_param_t param;
285         param.type  = param_tokenize(key, key_len);
286         if (param.type != ATK_UNKNOWN) {
287             param.value     = p_dupstr(value, value_len);
288             param.value_len = value_len;
289             array_add(config->params, param);
290         } else {
291             READ_LOG(INFO, "unknown parameter %.*s", key_len, key);
292         }
293     }
294     goto read_section;
295
296 read_filter:
297     filter_set_name(&filter, key, key_len);
298     READ_BLANK;
299     while (*p != '}') {
300         READ_TOKEN("filter parameter name", key, key_len);
301         READ_BLANK;
302         if (*p != '=') {
303             READ_ERROR("invalid character '%c', expected '='", *p);
304         }
305         READ_NEXT;
306         READ_BLANK;
307         READ_STRING("filter parameter value", value, value_len, false);
308         READ_BLANK;
309         if (strcmp(key, "type") == 0) {
310             if (!filter_set_type(&filter, value, value_len)) {
311                 READ_ERROR("unknow filter type (%s) for filter %s",
312                            value, filter.name);
313             }
314         } else if (key_len > 3 && strncmp(key, "on_", 3) == 0) {
315             if (!filter_add_hook(&filter, key + 3, key_len - 3,
316                                  value, value_len)) {
317                 READ_ERROR("hook %s not supported by filter %s",
318                            key + 3, filter.name);
319             }
320         } else {
321             /* filter_add_param failure mean unknown type or unsupported type.
322              * this are non-fatal errors.
323              */
324             (void)filter_add_param(&filter, key, key_len, value, value_len);
325         }
326     }
327     end_of_section = true;
328     READ_NEXT;
329     array_add(config->filters, filter);
330     filter_init(&filter);
331     goto read_section;
332
333 ok:
334     file_map_close(&map);
335     return true;
336
337 badeof:
338     err("Unexpected end of file");
339
340 error:
341     if (filter.name) {
342         filter_wipe(&filter);
343     }
344     file_map_close(&map);
345     return false;
346 }
347
348 static bool config_build_structure(config_t *config)
349 {
350     bool ok = true;
351     if (config->filters.len > 0) {
352 #       define QSORT_TYPE filter_t
353 #       define QSORT_BASE config->filters.data
354 #       define QSORT_NELT config->filters.len
355 #       define QSORT_LT(a,b) strcmp(a->name, b->name) < 0
356 #       include "qsort.c"
357     }
358
359     foreach (filter_t *filter, config->filters) {
360         if (!filter_update_references(filter, &config->filters)) {
361             ok = false;
362             break;
363         }
364     }}
365     if (!ok) {
366         return false;
367     }
368     if (!filter_check_safety(&config->filters)) {
369         return false;
370     }
371
372     ok = false;
373 #define PARSE_CHECK(Expr, Fmt, ...)                                            \
374     if (!(Expr)) {                                                             \
375         err(Fmt, ##__VA_ARGS__);                                               \
376         return false;                                                          \
377     }
378     foreach (filter_param_t *param, config->params) {
379         switch (param->type) {
380 #define   CASE(Param, State)                                                   \
381             case ATK_ ## Param ## _FILTER:                                     \
382               ok = true;                                                       \
383               config->entry_points[SMTP_ ## State]                             \
384                   = filter_find_with_name(&config->filters, param->value);     \
385               PARSE_CHECK(config->entry_points[SMTP_ ## State] >= 0,           \
386                           "invalid filter name %s", param->value);             \
387               break;
388           CASE(CLIENT,      CONNECT)
389           CASE(EHLO,        EHLO)
390           CASE(HELO,        HELO)
391           CASE(SENDER,      MAIL)
392           CASE(RECIPIENT,   RCPT)
393           CASE(DATA,        DATA)
394           CASE(END_OF_DATA, END_OF_MESSAGE)
395           CASE(VERIFY,      VRFY)
396           CASE(ETRN,        ETRN)
397 #undef    CASE
398           FILTER_PARAM_PARSE_INT(PORT, config->port);
399           default: break;
400         }
401     }}
402     array_deep_wipe(config->params, filter_params_wipe);
403
404     if (!ok) {
405         err("no entry point defined");
406     }
407     return ok;
408 }
409
410 static bool config_build_filters(config_t *config)
411 {
412     foreach (filter_t *filter, config->filters) {
413         if (!filter_build(filter)) {
414             return false;
415         }
416     }}
417
418     return true;
419 }
420
421 static bool config_load(config_t *config) {
422     config_close(config);
423
424     if (!config_parse(config)) {
425         err("Invalid configuration: cannot parse configuration file \"%s\"", config->filename);
426         return false;
427     }
428     if (!config_build_structure(config)) {
429         err("Invalid configuration: inconsistent filter structure");
430         return false;
431     }
432     if (!config_build_filters(config)) {
433         err("Invalid configuration: invalid filter");
434         return false;
435     }
436
437     resource_garbage_collect();
438     return true;
439 }
440
441 bool config_reload(config_t *config)
442 {
443     return config_load(config);
444 }
445
446 config_t *config_read(const char *file)
447 {
448     config_t *config = config_new();
449     config->filename = file;
450     if (!config_reload(config)) {
451         config_delete(&config);
452         return NULL;
453     }
454     return config;
455 }
456
457 bool config_check(const char *file)
458 {
459     config_t *config = config_new();
460     config->filename = file;
461
462     bool ret = config_parse(config) && config_build_structure(config);
463
464     config_delete(&config);
465     return ret;
466 }