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