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