7a5630ebec1d556f86f1821c2e1232d1f19be26a
[apps/pfixtools.git] / 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  */
35
36 #include <getopt.h>
37
38 #include "buffer.h"
39 #include "common.h"
40 #include "epoll.h"
41 #include "threads.h"
42 #include "tokens.h"
43
44 #define DAEMON_NAME             "postlicyd"
45 #define DEFAULT_PORT            10000
46 #define RUNAS_USER              "nobody"
47 #define RUNAS_GROUP             "nogroup"
48
49 enum smtp_state {
50     SMTP_UNKNOWN,
51     SMTP_CONNECT,
52     SMTP_EHLO,
53     SMTP_HELO = SMTP_EHLO,
54     SMTP_MAIL,
55     SMTP_RCPT,
56     SMTP_DATA,
57     SMTP_END_OF_MESSAGE,
58     SMTP_VRFY,
59     SMTP_ETRN,
60 };
61
62 /* \see http://www.postfix.org/SMTPD_POLICY_README.html */
63 typedef struct query_t {
64     unsigned state : 4;
65     unsigned esmtp : 1;
66
67     const char *helo_name;
68     const char *queue_id;
69     const char *sender;
70     const char *recipient;
71     const char *recipient_count;
72     const char *client_address;
73     const char *client_name;
74     const char *reverse_client_name;
75     const char *instance;
76
77     /* postfix 2.2+ */
78     const char *sasl_method;
79     const char *sasl_username;
80     const char *sasl_sender;
81     const char *size;
82     const char *ccert_subject;
83     const char *ccert_issuer;
84     const char *ccsert_fingerprint;
85
86     /* postfix 2.3+ */
87     const char *encryption_protocol;
88     const char *encryption_cipher;
89     const char *encryption_keysize;
90     const char *etrn_domain;
91
92     const char *eoq;
93 } query_t;
94
95 typedef struct plicyd_t {
96     unsigned listener : 1;
97     int fd;
98     buffer_t ibuf;
99     buffer_t obuf;
100     query_t q;
101 } plicyd_t;
102
103
104 static plicyd_t *plicyd_new(void)
105 {
106     plicyd_t *plicyd = p_new(plicyd_t, 1);
107     plicyd->fd = -1;
108     return plicyd;
109 }
110
111 static void plicyd_delete(plicyd_t **plicyd)
112 {
113     if (*plicyd) {
114         if ((*plicyd)->fd >= 0)
115             close((*plicyd)->fd);
116         buffer_wipe(&(*plicyd)->ibuf);
117         buffer_wipe(&(*plicyd)->obuf);
118         p_delete(plicyd);
119     }
120 }
121
122 static int postfix_parsejob(query_t *query, char *p)
123 {
124 #define PARSE_CHECK(expr, error, ...)                                        \
125     do {                                                                     \
126         if (!(expr)) {                                                       \
127             syslog(LOG_ERR, error, ##__VA_ARGS__);                           \
128             return -1;                                                       \
129         }                                                                    \
130     } while (0)
131
132     p_clear(query, 1);
133     while (*p != '\n') {
134         char *k, *v;
135         int klen, vlen, vtk;
136
137         while (isblank(*p))
138             p++;
139         p = strchr(k = p, '=');
140         PARSE_CHECK(p, "could not find '=' in line");
141         for (klen = p - k; klen && isblank(k[klen]); klen--);
142         p += 1; /* skip = */
143
144         while (isblank(*p))
145             p++;
146         p = strchr(v = p, '\n');
147         PARSE_CHECK(p, "could not find final \\n in line");
148         for (vlen = p - v; vlen && isblank(v[vlen]); vlen--);
149         p += 1; /* skip \n */
150
151         vtk = tokenize(v, vlen);
152         switch (tokenize(k, klen)) {
153 #define CASE(up, low)  case PTK_##up: query->low = v; v[vlen] = '\0'; break;
154             CASE(HELO_NAME,           helo_name);
155             CASE(QUEUE_ID,            queue_id);
156             CASE(SENDER,              sender);
157             CASE(RECIPIENT,           recipient);
158             CASE(RECIPIENT_COUNT,     recipient_count);
159             CASE(CLIENT_ADDRESS,      client_address);
160             CASE(CLIENT_NAME,         client_name);
161             CASE(REVERSE_CLIENT_NAME, reverse_client_name);
162             CASE(INSTANCE,            instance);
163             CASE(SASL_METHOD,         sasl_method);
164             CASE(SASL_USERNAME,       sasl_username);
165             CASE(SASL_SENDER,         sasl_sender);
166             CASE(SIZE,                size);
167             CASE(CCERT_SUBJECT,       ccert_subject);
168             CASE(CCERT_ISSUER,        ccert_issuer);
169             CASE(CCSERT_FINGERPRINT,  ccsert_fingerprint);
170             CASE(ENCRYPTION_PROTOCOL, encryption_protocol);
171             CASE(ENCRYPTION_CIPHER,   encryption_cipher);
172             CASE(ENCRYPTION_KEYSIZE,  encryption_keysize);
173             CASE(ETRN_DOMAIN,         etrn_domain);
174 #undef CASE
175
176           case PTK_REQUEST:
177             PARSE_CHECK(vtk == PTK_SMTPD_ACCESS_POLICY,
178                         "unexpected `request' value: %.*s", vlen, v);
179             break;
180
181           case PTK_PROTOCOL_NAME:
182             PARSE_CHECK(vtk == PTK_SMTP || vtk == PTK_ESMTP,
183                         "unexpected `protocol_name' value: %.*s", vlen, v);
184             query->esmtp = vtk == PTK_ESMTP;
185             break;
186
187           case PTK_PROTOCOL_STATE:
188             switch (vtk) {
189 #define CASE(name)  case PTK_##name: query->state = SMTP_##name; break;
190                 CASE(CONNECT);
191                 CASE(EHLO);
192                 CASE(HELO);
193                 CASE(MAIL);
194                 CASE(RCPT);
195                 CASE(DATA);
196                 CASE(END_OF_MESSAGE);
197                 CASE(VRFY);
198                 CASE(ETRN);
199               default:
200                 PARSE_CHECK(false, "unexpected `protocol_state` value: %.*s",
201                             vlen, v);
202 #undef CASE
203             }
204             break;
205
206           default:
207             syslog(LOG_WARNING, "unexpected key, skipped: %.*s", klen, k);
208             break;
209         }
210     }
211
212     return query->state == SMTP_UNKNOWN ? -1 : 0;
213 #undef PARSE_CHECK
214 }
215
216 __attribute__((format(printf,2,0)))
217 static void policy_answer(plicyd_t *pcy, const char *fmt, ...)
218 {
219     va_list args;
220     va_start(args, fmt);
221     buffer_addvf(&pcy->obuf, fmt, args);
222     va_end(args);
223     buffer_addstr(&pcy->obuf, "\n\n");
224     buffer_consume(&pcy->ibuf, pcy->q.eoq - pcy->ibuf.data);
225     epoll_modify(pcy->fd, EPOLLIN | EPOLLOUT, pcy);
226 }
227
228 static void policy_process(plicyd_t *pcy)
229 {
230     policy_answer(pcy, "DUNNO");
231 }
232
233 static int policy_run(plicyd_t *pcy)
234 {
235     ssize_t search_offs = MAX(0, pcy->ibuf.len - 1);
236     int nb = buffer_read(&pcy->ibuf, pcy->fd, -1);
237     const char *eoq;
238
239     if (nb < 0) {
240         if (errno == EAGAIN || errno == EINTR)
241             return 0;
242         UNIXERR("read");
243         return -1;
244     }
245     if (nb == 0) {
246         if (pcy->ibuf.len)
247             syslog(LOG_ERR, "unexpected end of data");
248         return -1;
249     }
250
251     if (!(eoq = strstr(pcy->ibuf.data + search_offs, "\n\n")))
252         return 0;
253
254     if (postfix_parsejob(&pcy->q, pcy->ibuf.data) < 0)
255         return -1;
256     pcy->q.eoq = eoq + strlen("\n\n");
257     epoll_modify(pcy->fd, 0, pcy);
258     policy_process(pcy);
259     return 0;
260 }
261
262 int start_listener(int port)
263 {
264     struct sockaddr_in addr = {
265         .sin_family = AF_INET,
266         .sin_addr   = { htonl(INADDR_LOOPBACK) },
267     };
268     plicyd_t *tmp;
269     int sock;
270
271     addr.sin_port = htons(port);
272     sock = tcp_listen_nonblock((const struct sockaddr *)&addr, sizeof(addr));
273     if (sock < 0) {
274         return -1;
275     }
276
277     tmp           = plicyd_new();
278     tmp->fd       = sock;
279     tmp->listener = true;
280     epoll_register(sock, EPOLLIN, tmp);
281     return 0;
282 }
283
284 void start_client(plicyd_t *d)
285 {
286     plicyd_t *tmp;
287     int sock;
288
289     sock = accept_nonblock(d->fd);
290     if (sock < 0) {
291         UNIXERR("accept");
292         return;
293     }
294
295     tmp     = plicyd_new();
296     tmp->fd = sock;
297     epoll_register(sock, EPOLLIN, tmp);
298 }
299
300 /* administrivia {{{ */
301
302 static int main_initialize(void)
303 {
304     openlog("postlicyd", LOG_PID, LOG_MAIL);
305     signal(SIGPIPE, SIG_IGN);
306     signal(SIGINT,  &common_sighandler);
307     signal(SIGTERM, &common_sighandler);
308     signal(SIGHUP,  &common_sighandler);
309     signal(SIGSEGV, &common_sighandler);
310     syslog(LOG_INFO, "Starting...");
311     return 0;
312 }
313
314 static void main_shutdown(void)
315 {
316     closelog();
317 }
318
319 module_init(main_initialize);
320 module_exit(main_shutdown);
321
322 void usage(void)
323 {
324     fputs("usage: "DAEMON_NAME" [options] config\n"
325           "\n"
326           "Options:\n"
327           "    -l <port>    port to listen to\n"
328           "    -p <pidfile> file to write our pid to\n"
329           "    -f           stay in foreground\n"
330          , stderr);
331 }
332
333 /* }}} */
334
335 int main(int argc, char *argv[])
336 {
337     const char *pidfile = NULL;
338     bool daemonize = true;
339     int port = DEFAULT_PORT;
340
341     for (int c = 0; (c = getopt(argc, argv, "hf" "l:p:")) >= 0; ) {
342         switch (c) {
343           case 'p':
344             pidfile = optarg;
345             break;
346           case 'l':
347             port = atoi(optarg);
348             break;
349           case 'f':
350             daemonize = false;
351             break;
352           default:
353             usage();
354             return EXIT_FAILURE;
355         }
356     }
357
358     if (argc - optind != 1) {
359         usage();
360         return EXIT_FAILURE;
361     }
362
363     if (pidfile_open(pidfile) < 0) {
364         syslog(LOG_CRIT, "unable to write pidfile %s", pidfile);
365         return EXIT_FAILURE;
366     }
367
368     if (drop_privileges(RUNAS_USER, RUNAS_GROUP) < 0) {
369         syslog(LOG_CRIT, "unable to drop privileges");
370         return EXIT_FAILURE;
371     }
372
373     if (daemonize && daemon_detach() < 0) {
374         syslog(LOG_CRIT, "unable to fork");
375         return EXIT_FAILURE;
376     }
377
378     pidfile_refresh();
379
380     if (start_listener(port) < 0)
381         return EXIT_FAILURE;
382
383     while (!sigint) {
384         struct epoll_event evts[1024];
385         int n;
386
387         n = epoll_select(evts, countof(evts), -1);
388         if (n < 0) {
389             if (errno != EAGAIN && errno != EINTR) {
390                 UNIXERR("epoll_wait");
391                 return EXIT_FAILURE;
392             }
393             continue;
394         }
395
396         while (--n >= 0) {
397             plicyd_t *d = evts[n].data.ptr;
398
399             if (d->listener) {
400                 start_client(d);
401                 continue;
402             }
403
404             if (evts[n].events & EPOLLIN) {
405                 if (policy_run(d) < 0) {
406                     plicyd_delete(&d);
407                     continue;
408                 }
409             }
410
411             if ((evts[n].events & EPOLLOUT) && d->obuf.len) {
412                 if (buffer_write(&d->obuf, d->fd) < 0) {
413                     plicyd_delete(&d);
414                     continue;
415                 }
416                 if (!d->obuf.len) {
417                     epoll_modify(d->fd, EPOLLIN, d);
418                 }
419             }
420         }
421     }
422
423     syslog(LOG_INFO, "Stopping...");
424     return EXIT_SUCCESS;
425 }