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