No need for the +x mode on configuration files.
[apps/pfixtools.git] / postlicyd / main-postlicyd.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 © 2006-2007 Pierre Habouzit
34  * Copyright © 2008 Florent Bruneau
35  */
36
37 #include <getopt.h>
38
39 #include "buffer.h"
40 #include "common.h"
41 #include "policy_tokens.h"
42 #include "server.h"
43 #include "config.h"
44 #include "postlicyd.h"
45
46 #define DAEMON_NAME             "postlicyd"
47 #define DAEMON_VERSION          "0.3"
48 #define DEFAULT_PORT            10000
49 #define RUNAS_USER              "nobody"
50 #define RUNAS_GROUP             "nogroup"
51
52 DECLARE_MAIN
53
54 static config_t *config  = NULL;
55 static bool refresh      = false;
56 static PA(server_t) busy = ARRAY_INIT;
57
58 static void *query_starter(server_t* server)
59 {
60     query_context_t *context = p_new(query_context_t, 1);
61     filter_context_prepare(&context->context, context);
62     return context;
63 }
64
65 static void query_stopper(void *data)
66 {
67     query_context_t **context = data;
68     if (*context) {
69         filter_context_wipe(&(*context)->context);
70         p_delete(context);
71     }
72 }
73
74 static bool config_refresh(void *mconfig)
75 {
76     refresh = true;
77     if (filter_running > 0) {
78         return true;
79     }
80     bool ret = config_reload(mconfig);
81     foreach (server_t **server, busy) {
82         server_ro(*server);
83     }}
84     array_len(busy) = 0;
85     refresh = false;
86     return ret;
87 }
88
89 static void policy_answer(server_t *pcy, const char *message)
90 {
91     query_context_t *context = pcy->data;
92     const query_t* query = &context->query;
93
94     buffer_addstr(&pcy->obuf, "action=");
95     buffer_ensure(&pcy->obuf, m_strlen(message) + 64);
96
97     ssize_t size = array_size(pcy->obuf) - array_len(pcy->obuf);
98     ssize_t format_size = query_format(array_ptr(pcy->obuf, array_len(pcy->obuf)),
99                                        size, message, query);
100     if (format_size == -1) {
101         buffer_addstr(&pcy->obuf, message);
102     } else if (format_size > size) {
103         buffer_ensure(&pcy->obuf, format_size + 1);
104         query_format(array_ptr(pcy->obuf, array_len(pcy->obuf)),
105                      array_size(pcy->obuf) - array_len(pcy->obuf),
106                      message, query);
107         array_len(pcy->obuf) += format_size;
108     } else {
109         array_len(pcy->obuf) += format_size;
110     }
111     buffer_addstr(&pcy->obuf, "\n\n");
112     buffer_consume(&pcy->ibuf, query->eoq - pcy->ibuf.data);
113     server_rw(pcy);
114 }
115
116 static const filter_t *next_filter(server_t *pcy, const filter_t *filter,
117                                    const query_t *query, const filter_hook_t *hook, bool *ok) {
118     if (hook != NULL) {
119         query_context_t *context = pcy->data;
120         if (hook->counter >= 0 && hook->counter < MAX_COUNTERS && hook->cost > 0) {
121             context->context.counters[hook->counter] += hook->cost;
122             debug("request client=%s, from=<%s>, to=<%s>: added %d to counter %d (now %u)",
123                   query->client_name,
124                   query->sender == NULL ? "undefined" : query->sender,
125                   query->recipient == NULL ? "undefined" : query->recipient,
126                   hook->cost, hook->counter, context->context.counters[hook->counter]);
127         }
128     }
129     if (hook == NULL) {
130         warn("request client=%s, from=<%s>, to=<%s>: aborted",
131              query->client_name,
132              query->sender == NULL ? "undefined" : query->sender,
133              query->recipient == NULL ? "undefined" : query->recipient);
134         *ok = false;
135         return NULL;
136     } else if (hook->async) {
137         debug("request client=%s, from=<%s>, to=<%s>: "
138               "asynchronous filter from filter %s",
139                query->client_name,
140                query->sender == NULL ? "undefined" : query->sender,
141                query->recipient == NULL ? "undefined" : query->recipient,
142                filter->name);
143         *ok = true;
144         return NULL;
145     } else if (hook->postfix) {
146         info("request client=%s, from=<%s>, to=<%s>: "
147              "awswer %s from filter %s: \"%s\"",
148              query->client_name,
149              query->sender == NULL ? "undefined" : query->sender,
150              query->recipient == NULL ? "undefined" : query->recipient,
151              htokens[hook->type], filter->name, hook->value);
152         policy_answer(pcy, hook->value);
153         *ok = true;
154         return NULL;
155     } else {
156         debug("request client=%s, from=<%s>, to=<%s>: "
157                "awswer %s from filter %s: next filter %s",
158                query->client_name,
159                query->sender == NULL ? "undefined" : query->sender,
160                query->recipient == NULL ? "undefined" : query->recipient,
161                htokens[hook->type], filter->name,
162                (array_ptr(config->filters, hook->filter_id))->name);
163         return array_ptr(config->filters, hook->filter_id);
164     }
165 }
166
167 static bool policy_process(server_t *pcy, const config_t *mconfig)
168 {
169     query_context_t *context = pcy->data;
170     const query_t* query = &context->query;
171     const filter_t *filter;
172     if (mconfig->entry_points[query->state] == -1) {
173         warn("no filter defined for current protocol_state (%d)", query->state);
174         return false;
175     }
176     if (context->context.current_filter != NULL) {
177         filter = context->context.current_filter;
178     } else {
179         filter = array_ptr(mconfig->filters, mconfig->entry_points[query->state]);
180     }
181     context->context.current_filter = NULL;
182     while (true) {
183         bool  ok = false;
184         const filter_hook_t *hook = filter_run(filter, query, &context->context);
185         filter = next_filter(pcy, filter, query, hook, &ok);
186         if (filter == NULL) {
187             return ok;
188         }
189     }
190 }
191
192 static int policy_run(server_t *pcy, void* vconfig)
193 {
194     if (refresh) {
195         array_add(busy, pcy);
196         return 0;
197     }
198
199     int search_offs = MAX(0, (int)(pcy->ibuf.len - 1));
200     int nb = buffer_read(&pcy->ibuf, pcy->fd, -1);
201     const char *eoq;
202     query_context_t *context = pcy->data;
203     query_t  *query  = &context->query;
204     context->server = pcy;
205     const config_t *mconfig = vconfig;
206
207     if (nb < 0) {
208         if (errno == EAGAIN || errno == EINTR)
209             return 0;
210         UNIXERR("read");
211         return -1;
212     }
213     if (nb == 0) {
214         if (pcy->ibuf.len)
215             err("unexpected end of data");
216         return -1;
217     }
218
219     if (!(eoq = strstr(pcy->ibuf.data + search_offs, "\n\n")))
220         return 0;
221
222     if (!query_parse(pcy->data, pcy->ibuf.data))
223         return -1;
224     query->eoq = eoq + strlen("\n\n");
225     if (query->instance == NULL || strcmp(context->context.instance, query->instance) != 0) {
226         filter_context_clean(&context->context);
227         m_strcat(context->context.instance, 64, query->instance);
228     }
229     server_none(pcy);
230     return policy_process(pcy, mconfig) ? 0 : -1;
231 }
232
233 static void policy_async_handler(filter_context_t *context,
234                                  const filter_hook_t *hook)
235 {
236     bool ok = false;
237     const filter_t *filter = context->current_filter;
238     query_context_t *qctx  = context->data;
239     query_t         *query = &qctx->query;
240     server_t        *server = qctx->server;
241
242     context->current_filter = next_filter(server, filter, query, hook, &ok);
243     if (context->current_filter != NULL) {
244         ok = policy_process(server, config);
245     }
246     if (!ok) {
247         server_release(server);
248     }
249     if (refresh && filter_running == 0) {
250         config_refresh(config);
251     }
252 }
253
254 static int postlicyd_init(void)
255 {
256     filter_async_handler_register(policy_async_handler);
257     return 0;
258 }
259
260 static void postlicyd_shutdown(void)
261 {
262     array_deep_wipe(busy, server_delete);
263 }
264 module_init(postlicyd_init);
265 module_exit(postlicyd_shutdown);
266
267 int start_listener(int port)
268 {
269     return start_server(port, NULL, NULL);
270 }
271
272 /* administrivia {{{ */
273
274 void usage(void)
275 {
276     fputs("usage: "DAEMON_NAME" [options] config\n"
277           "\n"
278           "Options:\n"
279           "    -l <port>    port to listen to\n"
280           "    -p <pidfile> file to write our pid to\n"
281           "    -f           stay in foreground\n"
282           "    -d           grow logging level\n"
283           "    -u           unsafe mode (don't drop privileges)\n"
284          , stderr);
285 }
286
287 /* }}} */
288
289 int main(int argc, char *argv[])
290 {
291     bool unsafe = false;
292     const char *pidfile = NULL;
293     bool daemonize = true;
294     int port = DEFAULT_PORT;
295     bool port_from_cli = false;
296
297     for (int c = 0; (c = getopt(argc, argv, "ufd" "l:p:")) >= 0; ) {
298         switch (c) {
299           case 'p':
300             pidfile = optarg;
301             break;
302           case 'u':
303             unsafe = true;
304             break;
305           case 'l':
306             port = atoi(optarg);
307             port_from_cli = true;
308             break;
309           case 'f':
310             daemonize = false;
311             break;
312           case 'd':
313             ++log_level;
314             break;
315           default:
316             usage();
317             return EXIT_FAILURE;
318         }
319     }
320
321     if (!daemonize) {
322         log_syslog = false;
323     }
324
325     if (argc - optind != 1) {
326         usage();
327         return EXIT_FAILURE;
328     }
329
330     info("starting %s v%s...", DAEMON_NAME, DAEMON_VERSION);
331
332     if (pidfile_open(pidfile) < 0) {
333         crit("unable to write pidfile %s", pidfile);
334         return EXIT_FAILURE;
335     }
336
337     if (drop_privileges(RUNAS_USER, RUNAS_GROUP) < 0) {
338         crit("unable to drop privileges");
339         return EXIT_FAILURE;
340     }
341
342     config = config_read(argv[optind]);
343     if (config == NULL) {
344         return EXIT_FAILURE;
345     }
346     if (port_from_cli || config->port == 0) {
347         config->port = port;
348     }
349
350     if (daemonize && daemon_detach() < 0) {
351         crit("unable to fork");
352         return EXIT_FAILURE;
353     }
354
355     pidfile_refresh();
356
357     if (start_listener(config->port) < 0) {
358         return EXIT_FAILURE;
359     } else {
360         return server_loop(query_starter, query_stopper,
361                            policy_run, config_refresh, config);
362     }
363 }