Use a conveniency library.
[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 #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 } query_t;
91
92 static int postfix_parsejob(query_t *query, char *p)
93 {
94 #define PARSE_CHECK(expr, error, ...)                                        \
95     do {                                                                     \
96         if (!(expr)) {                                                       \
97             syslog(LOG_ERR, error, ##__VA_ARGS__);                           \
98             return -1;                                                       \
99         }                                                                    \
100     } while (0)
101
102     p_clear(query, 1);
103     while (*p != '\n') {
104         char *k, *v;
105         int klen, vlen, vtk;
106
107         while (isblank(*p))
108             p++;
109         p = strchr(k = p, '=');
110         PARSE_CHECK(p, "could not find '=' in line");
111         for (klen = p - k; klen && isblank(k[klen]); klen--);
112         p += 1; /* skip = */
113
114         while (isblank(*p))
115             p++;
116         p = strchr(v = p, '\n');
117         PARSE_CHECK(p, "could not find final \\n in line");
118         for (vlen = p - v; vlen && isblank(v[vlen]); vlen--);
119         p += 1; /* skip \n */
120
121         vtk = tokenize(v, vlen);
122         switch (tokenize(k, klen)) {
123 #define CASE(up, low)  case PTK_##up: query->low = v; v[vlen] = '\0'; break;
124             CASE(HELO_NAME,           helo_name);
125             CASE(QUEUE_ID,            queue_id);
126             CASE(SENDER,              sender);
127             CASE(RECIPIENT,           recipient);
128             CASE(RECIPIENT_COUNT,     recipient_count);
129             CASE(CLIENT_ADDRESS,      client_address);
130             CASE(CLIENT_NAME,         client_name);
131             CASE(REVERSE_CLIENT_NAME, reverse_client_name);
132             CASE(INSTANCE,            instance);
133             CASE(SASL_METHOD,         sasl_method);
134             CASE(SASL_USERNAME,       sasl_username);
135             CASE(SASL_SENDER,         sasl_sender);
136             CASE(SIZE,                size);
137             CASE(CCERT_SUBJECT,       ccert_subject);
138             CASE(CCERT_ISSUER,        ccert_issuer);
139             CASE(CCSERT_FINGERPRINT,  ccsert_fingerprint);
140             CASE(ENCRYPTION_PROTOCOL, encryption_protocol);
141             CASE(ENCRYPTION_CIPHER,   encryption_cipher);
142             CASE(ENCRYPTION_KEYSIZE,  encryption_keysize);
143             CASE(ETRN_DOMAIN,         etrn_domain);
144 #undef CASE
145
146           case PTK_REQUEST:
147             PARSE_CHECK(vtk == PTK_SMTPD_ACCESS_POLICY,
148                         "unexpected `request' value: %.*s", vlen, v);
149             break;
150
151           case PTK_PROTOCOL_NAME:
152             PARSE_CHECK(vtk == PTK_SMTP || vtk == PTK_ESMTP,
153                         "unexpected `protocol_name' value: %.*s", vlen, v);
154             query->esmtp = vtk == PTK_ESMTP;
155             break;
156
157           case PTK_PROTOCOL_STATE:
158             switch (vtk) {
159 #define CASE(name)  case PTK_##name: query->state = SMTP_##name; break;
160                 CASE(CONNECT);
161                 CASE(EHLO);
162                 CASE(HELO);
163                 CASE(MAIL);
164                 CASE(RCPT);
165                 CASE(DATA);
166                 CASE(END_OF_MESSAGE);
167                 CASE(VRFY);
168                 CASE(ETRN);
169               default:
170                 PARSE_CHECK(false, "unexpected `protocol_state` value: %.*s",
171                             vlen, v);
172 #undef CASE
173             }
174             break;
175
176           default:
177             syslog(LOG_WARNING, "unexpected key, skipped: %.*s", klen, k);
178             break;
179         }
180     }
181
182     return query->state == SMTP_UNKNOWN ? -1 : 0;
183 #undef PARSE_CHECK
184 }
185
186 static void *policy_run(int fd, void *data)
187 {
188     buffer_t buf;
189
190     buffer_init(&buf);
191     for (;;) {
192         ssize_t search_offs = MAX(0, buf.len - 1);
193         int nb = buffer_read(&buf, fd, -1);
194         const char *eoq;
195         query_t q;
196
197         if (nb < 0) {
198             if (errno == EAGAIN || errno == EINTR)
199                 continue;
200             UNIXERR("read");
201             break;
202         }
203         if (nb == 0) {
204             if (buf.len)
205                 syslog(LOG_ERR, "unexpected end of data");
206             break;
207         }
208
209         eoq = strstr(buf.data + search_offs, "\n\n");
210         if (!eoq)
211             continue;
212
213         if (postfix_parsejob(&q, buf.data) < 0)
214             break;
215
216         buffer_consume(&buf, eoq + strlen("\n\n") - buf.data);
217         if (xwrite(fd, "DUNNO\n\n", strlen("DUNNO\n\n"))) {
218             UNIXERR("write");
219             break;
220         }
221     }
222     buffer_wipe(&buf);
223
224     close(fd);
225     return NULL;
226 }
227
228 /* administrivia {{{ */
229
230 static int main_initialize(void)
231 {
232     openlog("postlicyd", LOG_PID, LOG_MAIL);
233     signal(SIGPIPE, SIG_IGN);
234     signal(SIGINT,  &common_sighandler);
235     signal(SIGTERM, &common_sighandler);
236     signal(SIGHUP,  &common_sighandler);
237     signal(SIGSEGV, &common_sighandler);
238     syslog(LOG_INFO, "Starting...");
239     return 0;
240 }
241
242 static void main_shutdown(void)
243 {
244     closelog();
245 }
246
247 module_init(main_initialize);
248 module_exit(main_shutdown);
249
250 void usage(void)
251 {
252     fputs("usage: "DAEMON_NAME" [options] config\n"
253           "\n"
254           "Options:\n"
255           "    -l <port>    port to listen to\n"
256           "    -p <pidfile> file to write our pid to\n"
257           "    -f           stay in foreground\n"
258          , stderr);
259 }
260
261 /* }}} */
262
263 int main(int argc, char *argv[])
264 {
265     struct sockaddr_in addr = {
266         .sin_family = AF_INET,
267         .sin_addr   = { htonl(INADDR_LOOPBACK) },
268     };
269     const char *pidfile = NULL;
270     bool daemonize = true;
271     int port = DEFAULT_PORT;
272     int sock = -1;
273
274     for (int c = 0; (c = getopt(argc, argv, "hf" "l:p:")) >= 0; ) {
275         switch (c) {
276           case 'p':
277             pidfile = optarg;
278             break;
279           case 'l':
280             port = atoi(optarg);
281             break;
282           case 'f':
283             daemonize = false;
284             break;
285           default:
286             usage();
287             return EXIT_FAILURE;
288         }
289     }
290
291     if (argc - optind != 1) {
292         usage();
293         return EXIT_FAILURE;
294     }
295
296     if (pidfile_open(pidfile) < 0) {
297         syslog(LOG_CRIT, "unable to write pidfile %s", pidfile);
298         return EXIT_FAILURE;
299     }
300
301     if (drop_privileges(RUNAS_USER, RUNAS_GROUP) < 0) {
302         syslog(LOG_CRIT, "unable to drop privileges");
303         return EXIT_FAILURE;
304     }
305
306     if (daemonize && daemon_detach() < 0) {
307         syslog(LOG_CRIT, "unable to fork");
308         return EXIT_FAILURE;
309     }
310
311     pidfile_refresh();
312
313     addr.sin_port = htons(port);
314     sock = tcp_listen_nonblock((struct sockaddr *)&addr, sizeof(addr));
315     if (sock < 0)
316         return EXIT_FAILURE;
317
318     while (!sigint) {
319         fd_set rfd;
320         struct timeval tv = { 1, 0 };
321         int res;
322
323         FD_SET(sock, &rfd);
324         res = select(sock + 1, &rfd, NULL, NULL, &tv);
325
326         if (res < 0) {
327             if (errno != EINTR && errno != EAGAIN) {
328                 UNIXERR("select");
329                 return EXIT_FAILURE;
330             }
331         }
332         if (res > 0) {
333             int fd = accept(sock, NULL, 0);
334             if (fd < 0) {
335                 if (errno != EINTR && errno != EAGAIN) {
336                     UNIXERR("accept");
337                     return EXIT_FAILURE;
338                 }
339                 continue;
340             }
341             thread_launch(policy_run, fd, NULL);
342         }
343         threads_join();
344     }
345
346     close(sock);
347     syslog(LOG_INFO, "Stopping...");
348     return EXIT_SUCCESS;
349 }