70389bfb41d9b013b600914663635fa55d828adb
[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.2"
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         warn("request client=%s, from=<%s>, to=<%s>: aborted",
115              query->client_name,
116              query->sender == NULL ? "undefined" : query->sender,
117              query->recipient == NULL ? "undefined" : query->recipient);
118         *ok = false;
119         return NULL;
120     } else if (hook->async) {
121         debug("request client=%s, from=<%s>, to=<%s>: "
122               "asynchronous filter from filter %s",
123                query->client_name,
124                query->sender == NULL ? "undefined" : query->sender,
125                query->recipient == NULL ? "undefined" : query->recipient,
126                filter->name);
127         *ok = true;
128         return NULL;
129     } else if (hook->postfix) {
130         info("request client=%s, from=<%s>, to=<%s>: "
131              "awswer %s from filter %s: \"%s\"",
132              query->client_name,
133              query->sender == NULL ? "undefined" : query->sender,
134              query->recipient == NULL ? "undefined" : query->recipient,
135              htokens[hook->type], filter->name, hook->value);
136         policy_answer(pcy, hook->value);
137         *ok = true;
138         return NULL;
139     } else {
140         debug("request client=%s, from=<%s>, to=<%s>: "
141                "awswer %s from filter %s: next filter %s",
142                query->client_name,
143                query->sender == NULL ? "undefined" : query->sender,
144                query->recipient == NULL ? "undefined" : query->recipient,
145                htokens[hook->type], filter->name,
146                (array_ptr(config->filters, hook->filter_id))->name);
147         return array_ptr(config->filters, hook->filter_id);
148     }
149 }
150
151 static bool policy_process(server_t *pcy, const config_t *mconfig)
152 {
153     query_context_t *context = pcy->data;
154     const query_t* query = &context->query;
155     const filter_t *filter;
156     if (mconfig->entry_points[query->state] == -1) {
157         warn("no filter defined for current protocol_state (%d)", query->state);
158         return false;
159     }
160     if (context->context.current_filter != NULL) {
161         filter = context->context.current_filter;
162     } else {
163         filter = array_ptr(mconfig->filters, mconfig->entry_points[query->state]);
164     }
165     context->context.current_filter = NULL;
166     while (true) {
167         bool  ok = false;
168         const filter_hook_t *hook = filter_run(filter, query, &context->context);
169         filter = next_filter(pcy, filter, query, hook, &ok);
170         if (filter == NULL) {
171             return ok;
172         }
173     }
174 }
175
176 static int policy_run(server_t *pcy, void* vconfig)
177 {
178     if (sighup) {
179         return 0;
180     }
181
182     int search_offs = MAX(0, (int)(pcy->ibuf.len - 1));
183     int nb = buffer_read(&pcy->ibuf, pcy->fd, -1);
184     const char *eoq;
185     query_context_t *context = pcy->data;
186     query_t  *query  = &context->query;
187     context->server = pcy;
188     const config_t *mconfig = vconfig;
189
190     if (nb < 0) {
191         if (errno == EAGAIN || errno == EINTR)
192             return 0;
193         UNIXERR("read");
194         return -1;
195     }
196     if (nb == 0) {
197         if (pcy->ibuf.len)
198             err("unexpected end of data");
199         return -1;
200     }
201
202     if (!(eoq = strstr(pcy->ibuf.data + search_offs, "\n\n")))
203         return 0;
204
205     if (!query_parse(pcy->data, pcy->ibuf.data))
206         return -1;
207     query->eoq = eoq + strlen("\n\n");
208     epoll_modify(pcy->fd, 0, pcy);
209     return policy_process(pcy, mconfig) ? 0 : -1;
210 }
211
212 static void policy_async_handler(filter_context_t *context,
213                                  const filter_hook_t *hook)
214 {
215     bool ok = false;
216     const filter_t *filter = context->current_filter;
217     query_context_t *qctx  = context->data;
218     query_t         *query = &qctx->query;
219     server_t        *server = qctx->server;
220
221     context->current_filter = next_filter(server, filter, query, hook, &ok);
222     if (context->current_filter != NULL) {
223         ok = policy_process(server, config);
224     }
225     if (!ok) {
226         server_release(server);
227     }
228 }
229
230 static int postlicyd_init(void)
231 {
232     filter_async_handler_register(policy_async_handler);
233     return 0;
234 }
235 module_init(postlicyd_init);
236
237 int start_listener(int port)
238 {
239     return start_server(port, NULL, NULL);
240 }
241
242 /* administrivia {{{ */
243
244 void usage(void)
245 {
246     fputs("usage: "DAEMON_NAME" [options] config\n"
247           "\n"
248           "Options:\n"
249           "    -l <port>    port to listen to\n"
250           "    -p <pidfile> file to write our pid to\n"
251           "    -f           stay in foreground\n"
252           "    -d           grow logging level\n"
253           "    -u           unsafe mode (don't drop privileges)\n"
254          , stderr);
255 }
256
257 /* }}} */
258
259 int main(int argc, char *argv[])
260 {
261     bool unsafe = false;
262     const char *pidfile = NULL;
263     bool daemonize = true;
264     int port = DEFAULT_PORT;
265     bool port_from_cli = false;
266
267     for (int c = 0; (c = getopt(argc, argv, "ufd" "l:p:")) >= 0; ) {
268         switch (c) {
269           case 'p':
270             pidfile = optarg;
271             break;
272           case 'u':
273             unsafe = true;
274             break;
275           case 'l':
276             port = atoi(optarg);
277             port_from_cli = true;
278             break;
279           case 'f':
280             daemonize = false;
281             break;
282           case 'd':
283             ++log_level;
284             break;
285           default:
286             usage();
287             return EXIT_FAILURE;
288         }
289     }
290
291     if (!daemonize) {
292         log_syslog = false;
293     }
294
295     if (argc - optind != 1) {
296         usage();
297         return EXIT_FAILURE;
298     }
299
300     info("starting %s v%s...", DAEMON_NAME, DAEMON_VERSION);
301
302     if (pidfile_open(pidfile) < 0) {
303         crit("unable to write pidfile %s", pidfile);
304         return EXIT_FAILURE;
305     }
306
307     if (drop_privileges(RUNAS_USER, RUNAS_GROUP) < 0) {
308         crit("unable to drop privileges");
309         return EXIT_FAILURE;
310     }
311
312     config = config_read(argv[optind]);
313     if (config == NULL) {
314         return EXIT_FAILURE;
315     }
316     if (port_from_cli || config->port == 0) {
317         config->port = port;
318     }
319
320     if (daemonize && daemon_detach() < 0) {
321         crit("unable to fork");
322         return EXIT_FAILURE;
323     }
324
325     pidfile_refresh();
326
327     if (start_listener(config->port) < 0) {
328         return EXIT_FAILURE;
329     } else {
330         return server_loop(query_starter, query_stopper,
331                            policy_run, config_refresh, config);
332     }
333 }