5f46e76e2377171cd1d242f6e3976fcccdb1c4f1
[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 DEFAULT_PORT            10000
49 #define RUNAS_USER              "nobody"
50 #define RUNAS_GROUP             "nogroup"
51
52 DECLARE_MAIN
53
54 static void *query_starter(server_t* server)
55 {
56     return query_new();
57 }
58
59 static bool config_refresh(void *config)
60 {
61     return config_reload(config);
62 }
63
64 static int postfix_parsejob(query_t *query, char *p)
65 {
66 #define PARSE_CHECK(expr, error, ...)                                        \
67     do {                                                                     \
68         if (!(expr)) {                                                       \
69             syslog(LOG_ERR, error, ##__VA_ARGS__);                           \
70             return -1;                                                       \
71         }                                                                    \
72     } while (0)
73
74     p_clear(query, 1);
75     query->state = SMTP_UNKNOWN;
76     while (*p != '\n') {
77         char *k, *v;
78         int klen, vlen, vtk;
79
80         while (isblank(*p))
81             p++;
82         p = strchr(k = p, '=');
83         PARSE_CHECK(p, "could not find '=' in line");
84         for (klen = p - k; klen && isblank(k[klen]); klen--);
85         p += 1; /* skip = */
86
87         while (isblank(*p))
88             p++;
89         p = strchr(v = p, '\n');
90         PARSE_CHECK(p, "could not find final \\n in line");
91         for (vlen = p - v; vlen && isblank(v[vlen]); vlen--);
92         p += 1; /* skip \n */
93
94         vtk = policy_tokenize(v, vlen);
95         switch (policy_tokenize(k, klen)) {
96 #define CASE(up, low)  case PTK_##up: query->low = v; v[vlen] = '\0'; syslog(LOG_DEBUG, "%s = %s", ptokens[PTK_##up], query->low); break;
97             CASE(HELO_NAME,           helo_name);
98             CASE(QUEUE_ID,            queue_id);
99             CASE(SENDER,              sender);
100             CASE(RECIPIENT,           recipient);
101             CASE(RECIPIENT_COUNT,     recipient_count);
102             CASE(CLIENT_ADDRESS,      client_address);
103             CASE(CLIENT_NAME,         client_name);
104             CASE(REVERSE_CLIENT_NAME, reverse_client_name);
105             CASE(INSTANCE,            instance);
106             CASE(SASL_METHOD,         sasl_method);
107             CASE(SASL_USERNAME,       sasl_username);
108             CASE(SASL_SENDER,         sasl_sender);
109             CASE(SIZE,                size);
110             CASE(CCERT_SUBJECT,       ccert_subject);
111             CASE(CCERT_ISSUER,        ccert_issuer);
112             CASE(CCERT_FINGERPRINT,   ccert_fingerprint);
113             CASE(ENCRYPTION_PROTOCOL, encryption_protocol);
114             CASE(ENCRYPTION_CIPHER,   encryption_cipher);
115             CASE(ENCRYPTION_KEYSIZE,  encryption_keysize);
116             CASE(ETRN_DOMAIN,         etrn_domain);
117             CASE(STRESS,              stress);
118 #undef CASE
119
120           case PTK_REQUEST:
121             PARSE_CHECK(vtk == PTK_SMTPD_ACCESS_POLICY,
122                         "unexpected `request' value: %.*s", vlen, v);
123             break;
124
125           case PTK_PROTOCOL_NAME:
126             PARSE_CHECK(vtk == PTK_SMTP || vtk == PTK_ESMTP,
127                         "unexpected `protocol_name' value: %.*s", vlen, v);
128             query->esmtp = vtk == PTK_ESMTP;
129             break;
130
131           case PTK_PROTOCOL_STATE:
132             switch (vtk) {
133 #define CASE(name)  case PTK_##name: query->state = SMTP_##name; break;
134                 CASE(CONNECT);
135                 CASE(EHLO);
136                 CASE(HELO);
137                 CASE(MAIL);
138                 CASE(RCPT);
139                 CASE(DATA);
140                 CASE(END_OF_MESSAGE);
141                 CASE(VRFY);
142                 CASE(ETRN);
143               default:
144                 PARSE_CHECK(false, "unexpected `protocol_state` value: %.*s",
145                             vlen, v);
146 #undef CASE
147             }
148             break;
149
150           default:
151             syslog(LOG_WARNING, "unexpected key, skipped: %.*s", klen, k);
152             continue;
153         }
154     }
155
156     return query->state == SMTP_UNKNOWN ? -1 : 0;
157 #undef PARSE_CHECK
158 }
159
160 __attribute__((format(printf,2,0)))
161 static void policy_answer(server_t *pcy, const char *fmt, ...)
162 {
163     va_list args;
164     const query_t* query = pcy->data;
165
166     buffer_addstr(&pcy->obuf, "action=");
167     va_start(args, fmt);
168     buffer_addvf(&pcy->obuf, fmt, args);
169     va_end(args);
170     buffer_addstr(&pcy->obuf, "\n\n");
171     buffer_consume(&pcy->ibuf, query->eoq - pcy->ibuf.data);
172     epoll_modify(pcy->fd, EPOLLIN | EPOLLOUT, pcy);
173 }
174
175 static bool policy_process(server_t *pcy, const config_t *config)
176 {
177     const query_t* query = pcy->data;
178     const filter_t *filter;
179     if (config->entry_points[query->state] == -1) {
180         syslog(LOG_WARNING, "no filter defined for current protocol_state (%d)", query->state);
181         return false;
182     }
183     filter = array_ptr(config->filters, config->entry_points[query->state]);
184     while (true) {
185         const filter_hook_t *hook = filter_run(filter, query);
186         if (hook == NULL) {
187             syslog(LOG_WARNING, "request aborted");
188             return false;
189         } else if (hook->postfix) {
190             policy_answer(pcy, "%s", hook->value);
191             return true;
192         } else {
193             filter = array_ptr(config->filters, hook->filter_id);
194         }
195     }
196 }
197
198 static int policy_run(server_t *pcy, void* vconfig)
199 {
200     ssize_t search_offs = MAX(0, (ssize_t)(pcy->ibuf.len - 1));
201     int nb = buffer_read(&pcy->ibuf, pcy->fd, -1);
202     const char *eoq;
203     query_t  *query  = pcy->data;
204     const config_t *config = vconfig;
205
206     if (nb < 0) {
207         if (errno == EAGAIN || errno == EINTR)
208             return 0;
209         UNIXERR("read");
210         return -1;
211     }
212     if (nb == 0) {
213         if (pcy->ibuf.len)
214             syslog(LOG_ERR, "unexpected end of data");
215         return -1;
216     }
217
218     if (!(eoq = strstr(pcy->ibuf.data + search_offs, "\n\n")))
219         return 0;
220
221     if (postfix_parsejob(pcy->data, pcy->ibuf.data) < 0)
222         return -1;
223     query->eoq = eoq + strlen("\n\n");
224     epoll_modify(pcy->fd, 0, pcy);
225     return policy_process(pcy, config) ? 0 : -1;
226 }
227
228 int start_listener(int port)
229 {
230     return start_server(port, NULL, NULL);
231 }
232
233 /* administrivia {{{ */
234
235 void usage(void)
236 {
237     fputs("usage: "DAEMON_NAME" [options] config\n"
238           "\n"
239           "Options:\n"
240           "    -l <port>    port to listen to\n"
241           "    -p <pidfile> file to write our pid to\n"
242           "    -f           stay in foreground\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, "hf" "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           default:
272             usage();
273             return EXIT_FAILURE;
274         }
275     }
276
277     if (argc - optind != 1) {
278         usage();
279         return EXIT_FAILURE;
280     }
281
282     config_t *config = config_read(argv[optind]);
283     if (config == NULL) {
284         return EXIT_FAILURE;
285     }
286     if (port_from_cli || config->port == 0) {
287         config->port = port;
288     }
289
290     if (common_setup(pidfile, false, RUNAS_USER, RUNAS_GROUP,
291                      daemonize) != EXIT_SUCCESS
292         || start_listener(config->port) < 0) {
293         config_delete(&config);
294         return EXIT_FAILURE;
295     }
296     {
297         int res = server_loop(query_starter, (delete_client_t)query_delete,
298                               policy_run, config_refresh, config);
299         config_delete(&config);
300         return res;
301     }
302 }