Read the port from the configuration file.
[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
40 #define config_param_register(Param)
41
42 /* Filter to execute on "CONNECT"
43  */
44 config_param_register("client_filter");
45
46 /* Filter to execute on "MAIL FROM"
47  */
48 config_param_register("sender_filter");
49
50 /* Filter to execute on "RCPT TO"
51  */
52 config_param_register("recipient_filter");
53
54 /* Filter to execute on "DATA"
55  */
56 config_param_register("data_filter");
57
58 /* Filter to execute on "END-OF-DATA"
59  */
60 config_param_register("end_of_data_filter");
61
62 /* Filter to execute on "ETRN"
63  */
64 config_param_register("etrn_filter");
65
66 /* Filter to execute on "HELO"
67  */
68 config_param_register("helo_filter");
69 config_param_register("ehlo_filter");
70
71 /* Filter to execute on "VRFY"
72  */
73 config_param_register("verify_filter");
74
75
76 /* Where to bind the server.
77  */
78 config_param_register("port");
79
80 static inline config_t *config_new(void)
81 {
82     config_t *config = p_new(config_t, 1);
83     return config;
84 }
85
86 static void config_close(config_t *config)
87 {
88     for (int i = 0 ; i < SMTP_count ; ++i) {
89         config->entry_points[i] = -1;
90     }
91     array_deep_wipe(config->filters, filter_wipe);
92     array_deep_wipe(config->params, filter_params_wipe);
93 }
94
95 void config_delete(config_t **config)
96 {
97     if (*config) {
98         config_close(*config);
99         p_delete(config);
100     }
101 }
102
103
104 static bool config_second_pass(config_t *config)
105 {
106     bool ok = true;
107     if (config->filters.len > 0) {
108 #       define QSORT_TYPE filter_t
109 #       define QSORT_BASE config->filters.data
110 #       define QSORT_NELT config->filters.len
111 #       define QSORT_LT(a,b) strcmp(a->name, b->name) < 0
112 #       include "qsort.c"
113     }
114
115     foreach (filter_t *filter, config->filters) {
116         if (!filter_update_references(filter, &config->filters)) {
117             ok = false;
118             break;
119         }
120     }}
121     if (!ok) {
122         return false;
123     }
124     if (!filter_check_safety(&config->filters)) {
125         return false;
126     }
127
128     ok = false;
129 #define PARSE_CHECK(Expr, Fmt, ...)                                            \
130     if (!(Expr)) {                                                             \
131         syslog(LOG_ERR, Fmt, ##__VA_ARGS__);                                   \
132         return false;                                                          \
133     }
134     foreach (filter_param_t *param, config->params) {
135         switch (param->type) {
136 #define   CASE(Param, State)                                                   \
137             case ATK_ ## Param ## _FILTER:                                     \
138               ok = true;                                                       \
139               config->entry_points[SMTP_ ## State]                             \
140                   = filter_find_with_name(&config->filters, param->value);     \
141               PARSE_CHECK(config->entry_points[SMTP_ ## State] >= 0,           \
142                           "invalid filter name %s", param->value);             \
143               break;
144           CASE(CLIENT,      CONNECT)
145           CASE(EHLO,        EHLO)
146           CASE(HELO,        HELO)
147           CASE(SENDER,      MAIL)
148           CASE(RECIPIENT,   RCPT)
149           CASE(DATA,        DATA)
150           CASE(END_OF_DATA, END_OF_MESSAGE)
151           CASE(VERIFY,      VRFY)
152           CASE(ETRN,        ETRN)
153 #undef    CASE
154           FILTER_PARAM_PARSE_INT(PORT, config->port);
155           default: break;
156         }
157     }}
158     array_deep_wipe(config->params, filter_params_wipe);
159
160     if (!ok) {
161         syslog(LOG_ERR, "no entry point defined");
162     }
163
164     return ok;
165 }
166
167 static bool config_load(config_t *config)
168 {
169     filter_t filter;
170     file_map_t map;
171     const char *p;
172     int line = 0;
173     const char *linep;
174     bool in_section = false;
175     bool end_of_section = false;
176
177     char key[BUFSIZ];
178     char value[BUFSIZ];
179     ssize_t key_len, value_len;
180
181     if (!file_map_open(&map, config->filename, false)) {
182         return false;
183     }
184
185     config_close(config);
186     filter_init(&filter);
187     linep = p = map.map;
188
189 #define READ_LOG(Lev, Fmt, ...)                                                \
190     syslog(LOG_ ## Lev, "config file %s:%d:%d: " Fmt, config->filename,        \
191            line + 1, p - linep + 1, ##__VA_ARGS__)
192 #define READ_ERROR(Fmt, ...)                                                   \
193     do {                                                                       \
194         READ_LOG(ERR, Fmt, ##__VA_ARGS__);                                     \
195         goto error;                                                            \
196     } while (0)
197 #define ADD_IN_BUFFER(Buffer, Len, Char)                                       \
198     do {                                                                       \
199         if ((Len) >= BUFSIZ - 1) {                                             \
200             READ_ERROR("unreasonnable long line");                             \
201         }                                                                      \
202         (Buffer)[(Len)++] = (Char);                                            \
203         (Buffer)[(Len)]   = '\0';                                              \
204     } while (0)
205 #define READ_NEXT                                                              \
206     do {                                                                       \
207         if (*p == '\n') {                                                      \
208             ++line;                                                            \
209             linep = p + 1;                                                     \
210         }                                                                      \
211         if (++p >= map.end) {                                                  \
212             if (!end_of_section) {                                             \
213                 if (in_section) {                                              \
214                     goto badeof;                                               \
215                 } else {                                                       \
216                     goto ok;                                                   \
217                 }                                                              \
218             }                                                                  \
219         }                                                                      \
220     } while (0)
221 #define READ_BLANK                                                             \
222     do {                                                                       \
223         bool in_comment = false;                                               \
224         while (in_comment || isspace(*p) || *p == '#') {                       \
225             if (*p == '\n') {                                                  \
226                 in_comment = false;                                            \
227             } else if (*p == '#') {                                            \
228                 in_comment = true;                                             \
229             }                                                                  \
230             READ_NEXT;                                                         \
231         }                                                                      \
232     } while (0)
233 #define READ_TOKEN(Name, Buffer, Len)                                          \
234     do {                                                                       \
235         (Len) = 0;                                                             \
236         (Buffer)[0] = '\0';                                                    \
237         if (!isalpha(*p)) {                                                    \
238             READ_ERROR("invalid %s, unexpected character '%c'", Name, *p);     \
239         }                                                                      \
240         do {                                                                   \
241             ADD_IN_BUFFER(Buffer, Len, *p);                                    \
242             READ_NEXT;                                                         \
243         } while (isalnum(*p) || *p == '_');                                    \
244     } while (0)
245 #define READ_STRING(Name, Buffer, Len, Ignore)                                 \
246     do {                                                                       \
247         (Len) = 0;                                                             \
248         (Buffer)[0] = '\0';                                                    \
249         if (*p == '"') {                                                       \
250             bool escaped = false;                                              \
251             while (*p == '"') {                                                \
252                 READ_NEXT;                                                     \
253                 while (true) {                                                 \
254                     if (*p == '\n') {                                          \
255                         READ_ERROR("string must not contain EOL");             \
256                     } else if (escaped) {                                      \
257                         ADD_IN_BUFFER(Buffer, Len, *p);                        \
258                         escaped = false;                                       \
259                     } else if (*p == '\\') {                                   \
260                         escaped = true;                                        \
261                     } else if (*p == '"') {                                    \
262                         READ_NEXT;                                \
263                         break;                                                 \
264                     } else {                                                   \
265                         ADD_IN_BUFFER(Buffer, Len, *p);                        \
266                     }                                                          \
267                     READ_NEXT;                                                 \
268                 }                                                              \
269                 READ_BLANK;                                                    \
270             }                                                                  \
271             if (*p != ';') {                                                   \
272                 READ_ERROR("%s must end with a ';'", Name);                    \
273             }                                                                  \
274         } else {                                                               \
275             bool escaped = false;                                              \
276             while (*p != ';' && isascii(*p) && (isprint(*p) || isspace(*p))) { \
277                 if (escaped) {                                                 \
278                     if (*p == '\r' || *p == '\n') {                            \
279                         READ_BLANK;                                            \
280                     } else {                                                   \
281                         ADD_IN_BUFFER(Buffer, Len, '\\');                      \
282                     }                                                          \
283                     escaped = false;                                           \
284                 }                                                              \
285                 if (*p == '\\') {                                              \
286                     escaped = true;                                            \
287                 } else if (*p == '\r' || *p == '\n') {                         \
288                     READ_ERROR("%s must not contain EOL", Name);               \
289                 } else {                                                       \
290                     ADD_IN_BUFFER(Buffer, Len, *p);                            \
291                 }                                                              \
292                 READ_NEXT;                                                     \
293             }                                                                  \
294             if (escaped) {                                                     \
295                 ADD_IN_BUFFER(Buffer, Len, '\\');                              \
296             }                                                                  \
297             while ((Len) > 0 && isspace((Buffer)[(Len) - 1])) {                \
298                 (Buffer)[--(Len)] = '\0';                                      \
299             }                                                                  \
300         }                                                                      \
301         end_of_section = Ignore;                                               \
302         READ_NEXT;                                                             \
303     } while(0)
304
305
306 read_section:
307     if (p >= map.end) {
308         goto ok;
309     }
310
311     value[0] = key[0] = '\0';
312     value_len = key_len = 0;
313
314     in_section = end_of_section = false;
315     READ_BLANK;
316     in_section = true;
317     READ_TOKEN("section name", key, key_len);
318     READ_BLANK;
319     switch (*p) {
320       case '=':
321         READ_NEXT;
322         goto read_param_value;
323       case '{':
324         READ_NEXT;
325         goto read_filter;
326       default:
327         READ_ERROR("invalid character '%c', expected '=' or '{'", *p);
328     }
329
330 read_param_value:
331     READ_BLANK;
332     READ_STRING("parameter value", value, value_len, true);
333     {
334         filter_param_t param;
335         param.type  = param_tokenize(key, key_len);
336         if (param.type != ATK_UNKNOWN) {
337             param.value     = p_dupstr(value, value_len);
338             param.value_len = value_len;
339             array_add(config->params, param);
340         } else {
341             READ_LOG(INFO, "unknown parameter %.*s", key_len, key);
342         }
343     }
344     goto read_section;
345
346 read_filter:
347     filter_set_name(&filter, key, key_len);
348     READ_BLANK;
349     while (*p != '}') {
350         READ_TOKEN("filter parameter name", key, key_len);
351         READ_BLANK;
352         if (*p != '=') {
353             READ_ERROR("invalid character '%c', expected '='", *p);
354         }
355         READ_NEXT;
356         READ_BLANK;
357         READ_STRING("filter parameter value", value, value_len, false);
358         READ_BLANK;
359         if (strcmp(key, "type") == 0) {
360             if (!filter_set_type(&filter, value, value_len)) {
361                 READ_ERROR("unknow filter type (%s) for filter %s",
362                            value, filter.name);
363             }
364         } else if (key_len > 3 && strncmp(key, "on_", 3) == 0) {
365             if (!filter_add_hook(&filter, key + 3, key_len - 3,
366                                  value, value_len)) {
367                 READ_ERROR("hook %s not supported by filter %s",
368                            key + 3, filter.name);
369             }
370         } else {
371             /* filter_add_param failure mean unknown type or unsupported type.
372              * this are non-fatal errors.
373              */
374             (void)filter_add_param(&filter, key, key_len, value, value_len);
375         }
376     }
377     end_of_section = true;
378     READ_NEXT;
379     if (!filter_build(&filter)) {
380         READ_ERROR("invalid filter %s", filter.name);
381     }
382     array_add(config->filters, filter);
383     filter_init(&filter);
384     goto read_section;
385
386 ok:
387     if (!config_second_pass(config)) {
388         goto error;
389     }
390     file_map_close(&map);
391     return true;
392
393 badeof:
394     syslog(LOG_ERR, "Unexpected end of file");
395
396 error:
397     if (filter.name) {
398         filter_wipe(&filter);
399     }
400     file_map_close(&map);
401     return false;
402 }
403
404 bool config_reload(config_t *config)
405 {
406     return config_load(config);
407 }
408
409 config_t *config_read(const char *file)
410 {
411     config_t *config = config_new();
412     config->filename = file;
413     if (!config_reload(config)) {
414         p_delete(&config);
415         return NULL;
416     }
417     return config;
418 }