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