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