fa92f0da9f5e46d4f2cbc5e3a597ffd86f6bc506
[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 "threads.h"
41 #include "tokens.h"
42
43 #define DAEMON_NAME             "postlicyd"
44
45 enum smtp_state {
46     SMTP_UNKNOWN,
47     SMTP_CONNECT,
48     SMTP_EHLO,
49     SMTP_HELO = SMTP_EHLO,
50     SMTP_MAIL,
51     SMTP_RCPT,
52     SMTP_DATA,
53     SMTP_END_OF_MESSAGE,
54     SMTP_VRFY,
55     SMTP_ETRN,
56 };
57
58 /* \see http://www.postfix.org/SMTPD_POLICY_README.html */
59 typedef struct query_t {
60     unsigned state : 4;
61     unsigned esmtp : 1;
62
63     const char *helo_name;
64     const char *queue_id;
65     const char *sender;
66     const char *recipient;
67     const char *recipient_count;
68     const char *client_address;
69     const char *client_name;
70     const char *rclient_name;
71     const char *instance;
72
73     /* postfix 2.2+ */
74     const char *sasl_method;
75     const char *sasl_username;
76     const char *sasl_sender;
77     const char *size;
78     const char *ccert_subject;
79     const char *ccert_issuer;
80     const char *ccsert_fingerprint;
81
82     /* postfix 2.3+ */
83     const char *encryption_protocol;
84     const char *encryption_cipher;
85     const char *encryption_keysize;
86     const char *etrn_domain;
87
88     buffer_t data;
89 } query_t;
90
91 static query_t *query_init(query_t *rq) {
92     memset(rq, 0, offsetof(query_t, data));
93     buffer_init(&rq->data);
94     return rq;
95 }
96 static void query_wipe(query_t *rq) {
97     buffer_wipe(&rq->data);
98 }
99
100 static int postfix_parsejob(query_t *query)
101 {
102 #define PARSE_CHECK(expr, error, ...)                                        \
103     do {                                                                     \
104         if (!(expr)) {                                                       \
105             syslog(LOG_ERR, error, ##__VA_ARGS__);                           \
106             return -1;                                                       \
107         }                                                                    \
108     } while (0)
109
110     char *p = vskipspaces(query->data.data);
111
112     memset(query, 0, offsetof(query_t, data));
113     while (p[0] != '\r' || p[1] != '\n') {
114         char *k, *v;
115         int klen, vlen, vtk;
116
117         while (isblank(*p))
118             p++;
119         p = strchr(k = p, '=');
120         PARSE_CHECK(p, "could not find '=' in line");
121         for (klen = p - k; klen && isblank(k[klen]); klen--);
122         p += 1; /* skip = */
123
124         while (isblank(*p))
125             p++;
126         p = strstr(v = p, "\r\n");
127         PARSE_CHECK(p, "could not find final \\r\\n in line");
128         for (vlen = p - v; vlen && isblank(v[vlen]); vlen--);
129         p += 2; /* skip \r\n */
130
131         vtk = tokenize(v, vlen);
132         switch (tokenize(k, klen)) {
133 #define CASE(up, low)  case PTK_##up: query->low = v; v[vlen] = '\0'; break;
134             CASE(HELO_NAME,           helo_name);
135             CASE(QUEUE_ID,            queue_id);
136             CASE(SENDER,              sender);
137             CASE(RECIPIENT,           recipient);
138             CASE(RECIPIENT_COUNT,     recipient_count);
139             CASE(CLIENT_ADDRESS,      client_address);
140             CASE(CLIENT_NAME,         client_name);
141             CASE(RCLIENT_NAME,        rclient_name);
142             CASE(INSTANCE,            instance);
143             CASE(SASL_METHOD,         sasl_method);
144             CASE(SASL_USERNAME,       sasl_username);
145             CASE(SASL_SENDER,         sasl_sender);
146             CASE(SIZE,                size);
147             CASE(CCERT_SUBJECT,       ccert_subject);
148             CASE(CCERT_ISSUER,        ccert_issuer);
149             CASE(CCSERT_FINGERPRINT,  ccsert_fingerprint);
150             CASE(ENCRYPTION_PROTOCOL, encryption_protocol);
151             CASE(ENCRYPTION_CIPHER,   encryption_cipher);
152             CASE(ENCRYPTION_KEYSIZE,  encryption_keysize);
153             CASE(ETRN_DOMAIN,         etrn_domain);
154 #undef CASE
155
156           case PTK_REQUEST:
157             PARSE_CHECK(vtk == PTK_SMTPD_ACCESS_POLICY,
158                         "unexpected `request' value: %.*s", vlen, v);
159             break;
160
161           case PTK_PROTOCOL_NAME:
162             PARSE_CHECK(vtk == PTK_SMTP || vtk == PTK_ESMTP,
163                         "unexpected `protocol_name' value: %.*s", vlen, v);
164             query->esmtp = vtk == PTK_ESMTP;
165             break;
166
167           case PTK_PROTOCOL_STATE:
168             switch (vtk) {
169 #define CASE(name)  case PTK_##name: query->state = SMTP_##name; break;
170                 CASE(CONNECT);
171                 CASE(EHLO);
172                 CASE(HELO);
173                 CASE(MAIL);
174                 CASE(RCPT);
175                 CASE(DATA);
176                 CASE(END_OF_MESSAGE);
177                 CASE(VRFY);
178                 CASE(ETRN);
179               default:
180                 PARSE_CHECK(false, "unexpected `protocol_state` value: %.*s",
181                             vlen, v);
182 #undef CASE
183             }
184             break;
185
186           default:
187             syslog(LOG_WARNING, "unexpected key, skipped: %.*s", klen, k);
188             break;
189         }
190     }
191
192     return query->state == SMTP_UNKNOWN ? -1 : 0;
193 #undef PARSE_CHECK
194 }
195
196 static void *policy_run(int fd, void *data)
197 {
198     query_t q;
199     query_init(&q);
200
201     for (;;) {
202         int nb = buffer_read(&q.data, fd, -1);
203         const char *eoq;
204
205         if (nb < 0) {
206             if (errno == EAGAIN || errno == EINTR)
207                 continue;
208             UNIXERR("read");
209             break;
210         }
211         if (nb == 0) {
212             if (q.data.len)
213                 syslog(LOG_ERR, "unexpected end of data");
214             break;
215         }
216
217         eoq = strstr(q.data.data + MAX(0, q.data.len - 3), "\r\n\r\n");
218         if (!eoq)
219             continue;
220
221         if (postfix_parsejob(&q) < 0)
222             break;
223
224         buffer_consume(&q.data, eoq + strlen("\r\n\r\n") - q.data.data);
225         if (xwrite(fd, "DUNNO\r\n", strlen("DUNNO\r\n"))) {
226             UNIXERR("write");
227             break;
228         }
229     }
230
231     query_wipe(&q);
232     close(fd);
233     return NULL;
234 }
235
236 static int main_loop(void)
237 {
238     int exitcode = EXIT_SUCCESS;
239     int sock = -1;
240
241     while (!sigint) {
242         int fd = accept(sock, NULL, 0);
243         if (fd < 0) {
244             if (errno != EINTR || errno != EAGAIN)
245                 UNIXERR("accept");
246             continue;
247         }
248
249         thread_launch(policy_run, fd, NULL);
250         threads_join();
251     }
252
253     close(sock);
254     return exitcode;
255 }
256
257 /* administrivia {{{ */
258
259 static int main_initialize(void)
260 {
261     openlog("postlicyd", LOG_PID, LOG_MAIL);
262     signal(SIGPIPE, SIG_IGN);
263     signal(SIGINT,  &common_sighandler);
264     signal(SIGTERM, &common_sighandler);
265     signal(SIGSEGV, &common_sighandler);
266     syslog(LOG_INFO, "Starting...");
267     return 0;
268 }
269
270 static void main_shutdown(void)
271 {
272     closelog();
273 }
274
275 module_init(main_initialize);
276 module_exit(main_shutdown);
277
278 void usage(void)
279 {
280     fputs("usage: "DAEMON_NAME" [options] config\n"
281           "\n"
282           "Options:\n"
283           "    -p <pidfile> file to write our pid to\n"
284          , stderr);
285 }
286
287 /* }}} */
288
289 int main(int argc, char *argv[])
290 {
291     const char *pidfile = NULL;
292     int res;
293
294     for (int c = 0; (c = getopt(argc, argv, "h" "p:")) >= 0; ) {
295         switch (c) {
296           case 'p':
297             pidfile = optarg;
298             break;
299           default:
300             usage();
301             return EXIT_FAILURE;
302         }
303     }
304
305     if (argc - optind != 1) {
306         usage();
307         return EXIT_FAILURE;
308     }
309
310     if (pidfile_open(pidfile) < 0) {
311         syslog(LOG_CRIT, "unable to write pidfile %s", pidfile);
312         return EXIT_FAILURE;
313     }
314
315     if (daemon_detach() < 0) {
316         syslog(LOG_CRIT, "unable to fork");
317         return EXIT_FAILURE;
318     }
319
320     pidfile_refresh();
321     res = main_loop();
322     syslog(LOG_INFO, "Stopping...");
323     return res;
324 }