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