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