Add comments to the greylist algorithm.
[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  * Copyright © 2008 Florent Bruneau
35  */
36
37 #include <getopt.h>
38
39 #include "buffer.h"
40 #include "common.h"
41 #include "epoll.h"
42 #include "tokens.h"
43 #include "server.h"
44
45 #define DAEMON_NAME             "postlicyd"
46 #define DEFAULT_PORT            10000
47 #define RUNAS_USER              "nobody"
48 #define RUNAS_GROUP             "nogroup"
49
50 DECLARE_MAIN
51
52 enum smtp_state {
53     SMTP_UNKNOWN,
54     SMTP_CONNECT,
55     SMTP_EHLO,
56     SMTP_HELO = SMTP_EHLO,
57     SMTP_MAIL,
58     SMTP_RCPT,
59     SMTP_DATA,
60     SMTP_END_OF_MESSAGE,
61     SMTP_VRFY,
62     SMTP_ETRN,
63 };
64
65 /* \see http://www.postfix.org/SMTPD_POLICY_README.html */
66 typedef struct query_t {
67     unsigned state : 4;
68     unsigned esmtp : 1;
69
70     const char *helo_name;
71     const char *queue_id;
72     const char *sender;
73     const char *recipient;
74     const char *recipient_count;
75     const char *client_address;
76     const char *client_name;
77     const char *reverse_client_name;
78     const char *instance;
79
80     /* postfix 2.2+ */
81     const char *sasl_method;
82     const char *sasl_username;
83     const char *sasl_sender;
84     const char *size;
85     const char *ccert_subject;
86     const char *ccert_issuer;
87     const char *ccsert_fingerprint;
88
89     /* postfix 2.3+ */
90     const char *encryption_protocol;
91     const char *encryption_cipher;
92     const char *encryption_keysize;
93     const char *etrn_domain;
94
95     const char *eoq;
96 } query_t;
97
98 static query_t *query_new(void)
99 {
100     return p_new(query_t, 1);
101 }
102
103 static void query_delete(query_t **query)
104 {
105     if (*query) {
106         p_delete(query);
107     }
108 }
109
110 static void *query_starter(server_t* server)
111 {
112     return query_new();
113 }
114
115 static int postfix_parsejob(query_t *query, char *p)
116 {
117 #define PARSE_CHECK(expr, error, ...)                                        \
118     do {                                                                     \
119         if (!(expr)) {                                                       \
120             syslog(LOG_ERR, error, ##__VA_ARGS__);                           \
121             return -1;                                                       \
122         }                                                                    \
123     } while (0)
124
125     p_clear(query, 1);
126     while (*p != '\n') {
127         char *k, *v;
128         int klen, vlen, vtk;
129
130         while (isblank(*p))
131             p++;
132         p = strchr(k = p, '=');
133         PARSE_CHECK(p, "could not find '=' in line");
134         for (klen = p - k; klen && isblank(k[klen]); klen--);
135         p += 1; /* skip = */
136
137         while (isblank(*p))
138             p++;
139         p = strchr(v = p, '\n');
140         PARSE_CHECK(p, "could not find final \\n in line");
141         for (vlen = p - v; vlen && isblank(v[vlen]); vlen--);
142         p += 1; /* skip \n */
143
144         vtk = tokenize(v, vlen);
145         switch (tokenize(k, klen)) {
146 #define CASE(up, low)  case PTK_##up: query->low = v; v[vlen] = '\0'; break;
147             CASE(HELO_NAME,           helo_name);
148             CASE(QUEUE_ID,            queue_id);
149             CASE(SENDER,              sender);
150             CASE(RECIPIENT,           recipient);
151             CASE(RECIPIENT_COUNT,     recipient_count);
152             CASE(CLIENT_ADDRESS,      client_address);
153             CASE(CLIENT_NAME,         client_name);
154             CASE(REVERSE_CLIENT_NAME, reverse_client_name);
155             CASE(INSTANCE,            instance);
156             CASE(SASL_METHOD,         sasl_method);
157             CASE(SASL_USERNAME,       sasl_username);
158             CASE(SASL_SENDER,         sasl_sender);
159             CASE(SIZE,                size);
160             CASE(CCERT_SUBJECT,       ccert_subject);
161             CASE(CCERT_ISSUER,        ccert_issuer);
162             CASE(CCSERT_FINGERPRINT,  ccsert_fingerprint);
163             CASE(ENCRYPTION_PROTOCOL, encryption_protocol);
164             CASE(ENCRYPTION_CIPHER,   encryption_cipher);
165             CASE(ENCRYPTION_KEYSIZE,  encryption_keysize);
166             CASE(ETRN_DOMAIN,         etrn_domain);
167 #undef CASE
168
169           case PTK_REQUEST:
170             PARSE_CHECK(vtk == PTK_SMTPD_ACCESS_POLICY,
171                         "unexpected `request' value: %.*s", vlen, v);
172             break;
173
174           case PTK_PROTOCOL_NAME:
175             PARSE_CHECK(vtk == PTK_SMTP || vtk == PTK_ESMTP,
176                         "unexpected `protocol_name' value: %.*s", vlen, v);
177             query->esmtp = vtk == PTK_ESMTP;
178             break;
179
180           case PTK_PROTOCOL_STATE:
181             switch (vtk) {
182 #define CASE(name)  case PTK_##name: query->state = SMTP_##name; break;
183                 CASE(CONNECT);
184                 CASE(EHLO);
185                 CASE(HELO);
186                 CASE(MAIL);
187                 CASE(RCPT);
188                 CASE(DATA);
189                 CASE(END_OF_MESSAGE);
190                 CASE(VRFY);
191                 CASE(ETRN);
192               default:
193                 PARSE_CHECK(false, "unexpected `protocol_state` value: %.*s",
194                             vlen, v);
195 #undef CASE
196             }
197             break;
198
199           default:
200             syslog(LOG_WARNING, "unexpected key, skipped: %.*s", klen, k);
201             break;
202         }
203     }
204
205     return query->state == SMTP_UNKNOWN ? -1 : 0;
206 #undef PARSE_CHECK
207 }
208
209 __attribute__((format(printf,2,0)))
210 static void policy_answer(server_t *pcy, const char *fmt, ...)
211 {
212     va_list args;
213     va_start(args, fmt);
214     buffer_addvf(&pcy->obuf, fmt, args);
215     va_end(args);
216     buffer_addstr(&pcy->obuf, "\n\n");
217     buffer_consume(&pcy->ibuf, ((query_t*)(pcy->data))->eoq - pcy->ibuf.data);
218     epoll_modify(pcy->fd, EPOLLIN | EPOLLOUT, pcy);
219 }
220
221 static void policy_process(server_t *pcy)
222 {
223     policy_answer(pcy, "DUNNO");
224 }
225
226 static int policy_run(server_t *pcy, void* config)
227 {
228     ssize_t search_offs = MAX(0, pcy->ibuf.len - 1);
229     int nb = buffer_read(&pcy->ibuf, pcy->fd, -1);
230     const char *eoq;
231
232     if (nb < 0) {
233         if (errno == EAGAIN || errno == EINTR)
234             return 0;
235         UNIXERR("read");
236         return -1;
237     }
238     if (nb == 0) {
239         if (pcy->ibuf.len)
240             syslog(LOG_ERR, "unexpected end of data");
241         return -1;
242     }
243
244     if (!(eoq = strstr(pcy->ibuf.data + search_offs, "\n\n")))
245         return 0;
246
247     if (postfix_parsejob(pcy->data, pcy->ibuf.data) < 0)
248         return -1;
249     ((query_t*)pcy->data)->eoq = eoq + strlen("\n\n");
250     epoll_modify(pcy->fd, 0, pcy);
251     policy_process(pcy);
252     return 0;
253 }
254
255 int start_listener(int port)
256 {
257     return start_server(port, NULL, NULL);
258 }
259
260 /* administrivia {{{ */
261
262 void usage(void)
263 {
264     fputs("usage: "DAEMON_NAME" [options] config\n"
265           "\n"
266           "Options:\n"
267           "    -l <port>    port to listen to\n"
268           "    -p <pidfile> file to write our pid to\n"
269           "    -f           stay in foreground\n"
270          , stderr);
271 }
272
273 /* }}} */
274
275 int main(int argc, char *argv[])
276 {
277     bool unsafe = false;
278     const char *pidfile = NULL;
279     bool daemonize = true;
280     int port = DEFAULT_PORT;
281
282     for (int c = 0; (c = getopt(argc, argv, "hf" "l:p:")) >= 0; ) {
283         switch (c) {
284           case 'p':
285             pidfile = optarg;
286             break;
287           case 'u':
288             unsafe = true;
289             break;
290           case 'l':
291             port = atoi(optarg);
292             break;
293           case 'f':
294             daemonize = false;
295             break;
296           default:
297             usage();
298             return EXIT_FAILURE;
299         }
300     }
301
302     if (argc - optind != 1) {
303         usage();
304         return EXIT_FAILURE;
305     }
306
307     if (common_setup(pidfile, false, RUNAS_USER, RUNAS_GROUP,
308                      daemonize) != EXIT_SUCCESS
309         || start_listener(port) < 0) {
310         return EXIT_FAILURE;
311     }
312     return server_loop(query_starter, (delete_client_t)query_delete,
313                        policy_run, NULL);
314 }