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