751ff5a3783a31b592dbbf9cc4492084b19913a1
[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 "query.h"
45 #include "config.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 void *query_starter(server_t* server)
56 {
57     return query_new();
58 }
59
60 static bool config_refresh(void *config)
61 {
62     return config_reload(config);
63 }
64
65 __attribute__((format(printf,2,0)))
66 static void policy_answer(server_t *pcy, const char *fmt, ...)
67 {
68     va_list args;
69     const query_t* query = pcy->data;
70
71     buffer_addstr(&pcy->obuf, "action=");
72     va_start(args, fmt);
73     buffer_addvf(&pcy->obuf, fmt, args);
74     va_end(args);
75     buffer_addstr(&pcy->obuf, "\n\n");
76     buffer_consume(&pcy->ibuf, query->eoq - pcy->ibuf.data);
77     epoll_modify(pcy->fd, EPOLLIN | EPOLLOUT, pcy);
78 }
79
80 static bool policy_process(server_t *pcy, const config_t *config)
81 {
82     const query_t* query = pcy->data;
83     const filter_t *filter;
84     if (config->entry_points[query->state] == -1) {
85         warn("no filter defined for current protocol_state (%d)", query->state);
86         return false;
87     }
88     filter = array_ptr(config->filters, config->entry_points[query->state]);
89     while (true) {
90         const filter_hook_t *hook = filter_run(filter, query);
91         if (hook == NULL) {
92             warn("request client=%s, from=<%s>, to=<%s>: aborted",
93                  query->client_name,
94                  query->sender == NULL ? "undefined" : query->sender,
95                  query->recipient == NULL ? "undefined" : query->recipient);
96             return false;
97         } else if (hook->postfix) {
98             info("request client=%s, from=<%s>, to=<%s>: "
99                  "awswer %s from filter %s: \"%s\"",
100                  query->client_name,
101                  query->sender == NULL ? "undefined" : query->sender,
102                  query->recipient == NULL ? "undefined" : query->recipient,
103                  htokens[hook->type], filter->name, hook->value);
104             policy_answer(pcy, "%s", hook->value);
105             return true;
106         } else {
107             notice("request client=%s, from=<%s>, to=<%s>: "
108                    "awswer %s from filter %s: next filter %s",
109                    query->client_name,
110                    query->sender == NULL ? "undefined" : query->sender,
111                    query->recipient == NULL ? "undefined" : query->recipient,
112                    htokens[hook->type], filter->name,
113                    (array_ptr(config->filters, hook->filter_id))->name);
114             filter = array_ptr(config->filters, hook->filter_id);
115         }
116     }
117 }
118
119 static int policy_run(server_t *pcy, void* vconfig)
120 {
121     int search_offs = MAX(0, (int)(pcy->ibuf.len - 1));
122     int nb = buffer_read(&pcy->ibuf, pcy->fd, -1);
123     const char *eoq;
124     query_t  *query  = pcy->data;
125     const config_t *config = vconfig;
126
127     if (nb < 0) {
128         if (errno == EAGAIN || errno == EINTR)
129             return 0;
130         UNIXERR("read");
131         return -1;
132     }
133     if (nb == 0) {
134         if (pcy->ibuf.len)
135             err("unexpected end of data");
136         return -1;
137     }
138
139     if (!(eoq = strstr(pcy->ibuf.data + search_offs, "\n\n")))
140         return 0;
141
142     if (!query_parse(pcy->data, pcy->ibuf.data))
143         return -1;
144     query->eoq = eoq + strlen("\n\n");
145     epoll_modify(pcy->fd, 0, pcy);
146     return policy_process(pcy, config) ? 0 : -1;
147 }
148
149 int start_listener(int port)
150 {
151     return start_server(port, NULL, NULL);
152 }
153
154 /* administrivia {{{ */
155
156 void usage(void)
157 {
158     fputs("usage: "DAEMON_NAME" [options] config\n"
159           "\n"
160           "Options:\n"
161           "    -l <port>    port to listen to\n"
162           "    -p <pidfile> file to write our pid to\n"
163           "    -f           stay in foreground\n"
164           "    -d           grow logging level\n"
165           "    -u           unsafe mode (don't drop privileges)\n"
166          , stderr);
167 }
168
169 /* }}} */
170
171 int main(int argc, char *argv[])
172 {
173     bool unsafe = false;
174     const char *pidfile = NULL;
175     bool daemonize = true;
176     int port = DEFAULT_PORT;
177     bool port_from_cli = false;
178
179     for (int c = 0; (c = getopt(argc, argv, "ufd" "l:p:")) >= 0; ) {
180         switch (c) {
181           case 'p':
182             pidfile = optarg;
183             break;
184           case 'u':
185             unsafe = true;
186             break;
187           case 'l':
188             port = atoi(optarg);
189             port_from_cli = true;
190             break;
191           case 'f':
192             daemonize = false;
193             break;
194           case 'd':
195             ++log_level;
196             break;
197           default:
198             usage();
199             return EXIT_FAILURE;
200         }
201     }
202
203     if (!daemonize) {
204         log_syslog = false;
205     }
206
207     if (argc - optind != 1) {
208         usage();
209         return EXIT_FAILURE;
210     }
211
212     info("starting %s v%s...", DAEMON_NAME, DAEMON_VERSION);
213
214     if (pidfile_open(pidfile) < 0) {
215         crit("unable to write pidfile %s", pidfile);
216         return EXIT_FAILURE;
217     }
218
219     if (drop_privileges(RUNAS_USER, RUNAS_GROUP) < 0) {
220         crit("unable to drop privileges");
221         return EXIT_FAILURE;
222     }
223
224     config_t *config = config_read(argv[optind]);
225     if (config == NULL) {
226         return EXIT_FAILURE;
227     }
228     if (port_from_cli || config->port == 0) {
229         config->port = port;
230     }
231
232     if (daemonize && daemon_detach() < 0) {
233         crit("unable to fork");
234         return EXIT_FAILURE;
235     }
236
237     pidfile_refresh();
238
239     if (start_listener(config->port) < 0) {
240         return EXIT_FAILURE;
241     } else {
242         return server_loop(query_starter, (delete_client_t)query_delete,
243                            policy_run, config_refresh, config);
244     }
245 }