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