make-config.sh: test for -Wl,--as-needed
[s-mailx.git] / spam.c
blobb7c08582f37a44f51afbbc2008ed40ac9e1b81f0
1 /*@ S-nail - a mail user agent derived from Berkeley Mail.
2 *@ Spam related facilities.
4 * Copyright (c) 2013 - 2018 Steffen (Daode) Nurpmeso <steffen@sdaoden.eu>.
6 * Permission to use, copy, modify, and/or distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18 #undef n_FILE
19 #define n_FILE spam
21 #ifndef HAVE_AMALGAMATION
22 # include "nail.h"
23 #endif
25 EMPTY_FILE()
26 #ifdef HAVE_SPAM
28 #ifdef HAVE_SPAM_SPAMD
29 # include <sys/socket.h>
30 # include <sys/un.h>
31 #endif
33 /* This is chosen rather arbitrarily.
34 * It must be able to swallow the first line of a rate response,
35 * and an entire CHECK/TELL spamd(1) response */
36 #if BUFFER_SIZE < 1024
37 # error *spam-interface* BUFFER_SIZE constraints are not matched
38 #endif
40 #ifdef HAVE_SPAM_SPAMD
41 # define SPAMD_IDENT "SPAMC/1.5"
42 # ifndef SUN_LEN
43 # define SUN_LEN(SUP) \
44 (sizeof(*(SUP)) - sizeof((SUP)->sun_path) + strlen((SUP)->sun_path))
45 # endif
46 #endif
48 #ifdef HAVE_SPAM_FILTER
49 /* n_NELEM() of regmatch_t groups */
50 # define SPAM_FILTER_MATCHES 32u
51 #endif
53 enum spam_action {
54 _SPAM_RATE,
55 _SPAM_HAM,
56 _SPAM_SPAM,
57 _SPAM_FORGET
60 #if defined HAVE_SPAM_SPAMC || defined HAVE_SPAM_FILTER
61 struct spam_cf {
62 char const *cf_cmd;
63 char *cf_result; /* _SPAM_RATE: first response line */
64 int cf_waitstat;
65 ui8_t __pad[3];
66 bool_t cf_useshell;
67 /* .cf_cmd may be adjusted for each call (`spamforget')... */
68 char const *cf_acmd;
69 char const *cf_a0;
70 char const *cf_env[4];
71 sighandler_type cf_otstp;
72 sighandler_type cf_ottin;
73 sighandler_type cf_ottou;
74 sighandler_type cf_ohup;
75 sighandler_type cf_opipe;
76 sighandler_type cf_oint;
77 sighandler_type cf_oquit;
79 #endif
81 #ifdef HAVE_SPAM_SPAMC
82 struct spam_spamc {
83 struct spam_cf c_super;
84 char const *c_cmd_arr[9];
86 #endif
88 #ifdef HAVE_SPAM_SPAMD
89 struct spam_spamd {
90 struct str d_user;
91 sighandler_type d_otstp;
92 sighandler_type d_ottin;
93 sighandler_type d_ottou;
94 sighandler_type d_ohup;
95 sighandler_type d_opipe;
96 sighandler_type d_oint;
97 sighandler_type d_oquit;
98 struct sockaddr_un d_sun;
100 #endif
102 #ifdef HAVE_SPAM_FILTER
103 struct spam_filter {
104 struct spam_cf f_super;
105 char const *f_cmd_nospam; /* Working relative to current message.. */
106 char const *f_cmd_noham;
107 # ifdef HAVE_REGEX
108 ui8_t __pad[4];
109 ui32_t f_score_grpno; /* 0 for not set */
110 regex_t f_score_regex;
111 # endif
113 #endif
115 struct spam_vc {
116 enum spam_action vc_action;
117 bool_t vc_verbose; /* Verbose output */
118 bool_t vc_progress; /* "Progress meter" (mutual verbose) */
119 ui8_t __pad[2];
120 bool_t (*vc_act)(struct spam_vc *);
121 void (*vc_dtor)(struct spam_vc *);
122 char *vc_buffer; /* I/O buffer, BUFFER_SIZE bytes */
123 size_t vc_mno; /* Current message number */
124 struct message *vc_mp; /* Current message */
125 FILE *vc_ifp; /* Input stream on .vc_mp */
126 union {
127 #ifdef HAVE_SPAM_SPAMC
128 struct spam_spamc spamc;
129 #endif
130 #ifdef HAVE_SPAM_SPAMD
131 struct spam_spamd spamd;
132 #endif
133 #ifdef HAVE_SPAM_FILTER
134 struct spam_filter filter;
135 #endif
136 #if defined HAVE_SPAM_SPAMC || defined HAVE_SPAM_FILTER
137 struct spam_cf cf;
138 #endif
139 } vc_t;
140 char const *vc_esep; /* Error separator for progress mode */
143 /* Indices according to enum spam_action */
144 static char const _spam_cmds[][16] = {
145 "spamrate", "spamham", "spamspam", "spamforget"
148 /* Shared action setup */
149 static bool_t _spam_action(enum spam_action sa, int *ip);
151 /* *spam-interface*=spamc: initialize, communicate */
152 #ifdef HAVE_SPAM_SPAMC
153 static bool_t _spamc_setup(struct spam_vc *vcp);
154 static bool_t _spamc_interact(struct spam_vc *vcp);
155 static void _spamc_dtor(struct spam_vc *vcp);
156 #endif
158 /* *spam-interface*=spamd: initialize, communicate */
159 #ifdef HAVE_SPAM_SPAMD
160 static bool_t _spamd_setup(struct spam_vc *vcp);
161 static bool_t _spamd_interact(struct spam_vc *vcp);
162 #endif
164 /* *spam-interface*=filter: initialize, communicate */
165 #ifdef HAVE_SPAM_FILTER
166 static bool_t _spamfilter_setup(struct spam_vc *vcp);
167 static bool_t _spamfilter_interact(struct spam_vc *vcp);
168 static void _spamfilter_dtor(struct spam_vc *vcp);
169 #endif
171 /* *spam-interface*=(spamc|filter): create child + communication */
172 #if defined HAVE_SPAM_SPAMC || defined HAVE_SPAM_FILTER
173 static void _spam_cf_setup(struct spam_vc *vcp, bool_t useshell);
174 static bool_t _spam_cf_interact(struct spam_vc *vcp);
175 #endif
177 /* Convert a floating-point spam rate into message.m_spamscore */
178 #if defined HAVE_SPAM_SPAMC || defined HAVE_SPAM_SPAMD ||\
179 (defined HAVE_SPAM_FILTER && defined HAVE_REGEX)
180 static void _spam_rate2score(struct spam_vc *vcp, char *buf);
181 #endif
183 static bool_t
184 _spam_action(enum spam_action sa, int *ip)
186 struct spam_vc vc;
187 size_t maxsize, skipped, cnt, curr;
188 char const *cp;
189 bool_t ok = FAL0;
190 NYD_ENTER;
192 memset(&vc, 0, sizeof vc);
193 vc.vc_action = sa;
194 vc.vc_verbose = ((n_poption & n_PO_VERB) != 0);
195 vc.vc_progress = (!vc.vc_verbose && ((n_psonce & n_PSO_INTERACTIVE) != 0));
196 vc.vc_esep = vc.vc_progress ? "\n" : n_empty;
198 /* Check and setup the desired spam interface */
199 if ((cp = ok_vlook(spam_interface)) == NULL) {
200 n_err(_("`%s': no *spam-interface* set\n"), _spam_cmds[sa]);
201 goto jleave;
202 #ifdef HAVE_SPAM_SPAMC
203 } else if (!asccasecmp(cp, "spamc")) {
204 if (!_spamc_setup(&vc))
205 goto jleave;
206 #endif
207 #ifdef HAVE_SPAM_SPAMD
208 } else if (!asccasecmp(cp, "spamd")) { /* TODO v15: remove */
209 n_OBSOLETE(_("*spam-interface*=spamd is obsolete, please use =spamc"));
210 if (!_spamd_setup(&vc))
211 goto jleave;
212 #endif
213 #ifdef HAVE_SPAM_FILTER
214 } else if (!asccasecmp(cp, "filter")) {
215 if (!_spamfilter_setup(&vc))
216 goto jleave;
217 #endif
218 } else {
219 n_err(_("`%s': unknown / unsupported *spam-interface*: %s\n"),
220 _spam_cmds[sa], cp);
221 goto jleave;
224 /* *spam-maxsize* we do handle ourselfs instead */
225 if ((cp = ok_vlook(spam_maxsize)) == NULL ||
226 (n_idec_ui32_cp(&maxsize, cp, 0, NULL), maxsize) == 0)
227 maxsize = SPAM_MAXSIZE;
229 /* Finally get an I/O buffer */
230 vc.vc_buffer = n_autorec_alloc(BUFFER_SIZE);
232 skipped = cnt = 0;
233 if (vc.vc_progress) {
234 while (ip[cnt] != 0)
235 ++cnt;
237 for (curr = 0, ok = TRU1; *ip != 0; --cnt, ++curr, ++ip) {
238 vc.vc_mno = (size_t)*ip;
239 vc.vc_mp = message + vc.vc_mno - 1;
240 if (sa == _SPAM_RATE)
241 vc.vc_mp->m_spamscore = 0;
243 if (vc.vc_mp->m_size > maxsize) {
244 if (vc.vc_verbose)
245 n_err(_("`%s': message %lu exceeds maxsize (%lu > %lu), skip\n"),
246 _spam_cmds[sa], (ul_i)vc.vc_mno, (ul_i)(size_t)vc.vc_mp->m_size,
247 (ul_i)maxsize);
248 else if (vc.vc_progress) {
249 fprintf(n_stdout, "\r%s: !%-6" PRIuZ " %6" PRIuZ "/%-6" PRIuZ,
250 _spam_cmds[sa], vc.vc_mno, cnt, curr);
251 fflush(n_stdout);
253 ++skipped;
254 } else {
255 if (vc.vc_verbose)
256 n_err(_("`%s': message %lu\n"), _spam_cmds[sa], (ul_i)vc.vc_mno);
257 else if (vc.vc_progress) {
258 fprintf(n_stdout, "\r%s: .%-6" PRIuZ " %6" PRIuZ "/%-6" PRIuZ,
259 _spam_cmds[sa], vc.vc_mno, cnt, curr);
260 fflush(n_stdout);
263 setdot(vc.vc_mp);
264 if ((vc.vc_ifp = setinput(&mb, vc.vc_mp, NEED_BODY)) == NULL) {
265 n_err(_("%s`%s': cannot load message %lu: %s\n"),
266 vc.vc_esep, _spam_cmds[sa], (ul_i)vc.vc_mno,
267 n_err_to_doc(n_err_no));
268 ok = FAL0;
269 break;
272 if (!(ok = (*vc.vc_act)(&vc)))
273 break;
276 if (vc.vc_progress) {
277 if (curr > 0)
278 fprintf(n_stdout, _(" %s (%" PRIuZ "/%" PRIuZ " all/skipped)\n"),
279 (ok ? _("done") : V_(n_error)), curr, skipped);
280 fflush(n_stdout);
283 if (vc.vc_dtor != NULL)
284 (*vc.vc_dtor)(&vc);
285 jleave:
286 NYD_LEAVE;
287 return !ok;
290 #ifdef HAVE_SPAM_SPAMC
291 static bool_t
292 _spamc_setup(struct spam_vc *vcp)
294 struct spam_spamc *sscp;
295 struct str str;
296 char const **args, *cp;
297 bool_t rv = FAL0;
298 NYD2_ENTER;
300 sscp = &vcp->vc_t.spamc;
301 args = sscp->c_cmd_arr;
303 if ((cp = ok_vlook(spamc_command)) == NULL) {
304 # ifdef SPAM_SPAMC_PATH
305 cp = SPAM_SPAMC_PATH;
306 # else
307 n_err(_("`%s': *spamc-command* is not set\n"),
308 _spam_cmds[vcp->vc_action]);
309 goto jleave;
310 # endif
312 *args++ = cp;
314 switch (vcp->vc_action) {
315 case _SPAM_RATE:
316 *args = "-c";
317 break;
318 case _SPAM_HAM:
319 args[1] = "ham";
320 goto jlearn;
321 case _SPAM_SPAM:
322 args[1] = "spam";
323 goto jlearn;
324 case _SPAM_FORGET:
325 args[1] = "forget";
326 jlearn:
327 *args = "-L";
328 ++args;
329 break;
331 ++args;
333 *args++ = "-l"; /* --log-to-stderr */
334 *args++ = "-x"; /* No "safe callback", we need to react on errors! */
336 if ((cp = ok_vlook(spamc_arguments)) != NULL)
337 *args++ = cp;
339 if ((cp = ok_vlook(spamc_user)) != NULL) {
340 if (*cp == '\0')
341 cp = ok_vlook(LOGNAME);
342 *args++ = "-u";
343 *args++ = cp;
345 assert(PTR2SIZE(args - sscp->c_cmd_arr) <= n_NELEM(sscp->c_cmd_arr));
347 *args = NULL;
348 sscp->c_super.cf_cmd = str_concat_cpa(&str, sscp->c_cmd_arr, " ")->s;
349 if (vcp->vc_verbose)
350 n_err(_("spamc(1) via %s\n"),
351 n_shexp_quote_cp(sscp->c_super.cf_cmd, FAL0));
353 _spam_cf_setup(vcp, FAL0);
355 vcp->vc_act = &_spamc_interact;
356 vcp->vc_dtor = &_spamc_dtor;
357 rv = TRU1;
358 # ifndef SPAM_SPAMC_PATH
359 jleave:
360 # endif
361 NYD2_LEAVE;
362 return rv;
365 static bool_t
366 _spamc_interact(struct spam_vc *vcp)
368 bool_t rv;
369 NYD2_ENTER;
371 if (!(rv = _spam_cf_interact(vcp)))
372 goto jleave;
374 vcp->vc_mp->m_flag &= ~(MSPAM | MSPAMUNSURE);
375 if (vcp->vc_action != _SPAM_RATE) {
376 if (vcp->vc_action == _SPAM_SPAM)
377 vcp->vc_mp->m_flag |= MSPAM;
378 } else {
379 char *buf, *cp;
381 switch (WEXITSTATUS(vcp->vc_t.spamc.c_super.cf_waitstat)) {
382 case 1:
383 vcp->vc_mp->m_flag |= MSPAM;
384 /* FALLTHRU */
385 case 0:
386 break;
387 default:
388 rv = FAL0;
389 goto jleave;
392 if ((cp = strchr(buf = vcp->vc_t.spamc.c_super.cf_result, '/')) != NULL)
393 buf[PTR2SIZE(cp - buf)] = '\0';
394 _spam_rate2score(vcp, buf);
396 jleave:
397 NYD2_LEAVE;
398 return rv;
401 static void
402 _spamc_dtor(struct spam_vc *vcp)
404 NYD2_ENTER;
405 if (vcp->vc_t.spamc.c_super.cf_result != NULL)
406 n_free(vcp->vc_t.spamc.c_super.cf_result);
407 NYD2_LEAVE;
409 #endif /* HAVE_SPAM_SPAMC */
411 #ifdef HAVE_SPAM_SPAMD
412 static bool_t
413 _spamd_setup(struct spam_vc *vcp)
415 struct spam_spamd *ssdp;
416 char const *cp;
417 size_t l;
418 bool_t rv = FAL0;
419 NYD2_ENTER;
421 ssdp = &vcp->vc_t.spamd;
423 if ((cp = ok_vlook(spamd_user)) != NULL) {
424 if (*cp == '\0')
425 cp = ok_vlook(LOGNAME);
426 ssdp->d_user.l = strlen(ssdp->d_user.s = n_UNCONST(cp));
429 if ((cp = ok_vlook(spamd_socket)) == NULL) {
430 n_err(_("`%s': required *spamd-socket* is not set\n"),
431 _spam_cmds[vcp->vc_action]);
432 goto jleave;
434 if ((l = strlen(cp) +1) >= sizeof(ssdp->d_sun.sun_path)) {
435 n_err(_("`%s': *spamd-socket* too long: %s\n"),
436 _spam_cmds[vcp->vc_action], n_shexp_quote_cp(cp, FAL0));
437 goto jleave;
439 ssdp->d_sun.sun_family = AF_UNIX;
440 memcpy(ssdp->d_sun.sun_path, cp, l);
442 vcp->vc_act = &_spamd_interact;
443 rv = TRU1;
444 jleave:
445 NYD2_LEAVE;
446 return rv;
449 static sigjmp_buf __spamd_actjmp; /* TODO oneday, we won't need it no more */
450 static int volatile __spamd_sig; /* TODO oneday, we won't need it no more */
451 static void
452 __spamd_onsig(int sig) /* TODO someday, we won't need it no more */
454 NYD_X; /* Signal handler */
455 __spamd_sig = sig;
456 siglongjmp(__spamd_actjmp, 1);
459 static bool_t
460 _spamd_interact(struct spam_vc *vcp)
462 struct spam_spamd *ssdp;
463 size_t size, i;
464 char *lp, *cp, * volatile headbuf = NULL;
465 int volatile dsfd = -1;
466 bool_t volatile rv = FAL0;
467 NYD2_ENTER;
469 ssdp = &vcp->vc_t.spamd;
471 __spamd_sig = 0;
472 hold_sigs();
473 ssdp->d_otstp = safe_signal(SIGTSTP, SIG_DFL);
474 ssdp->d_ottin = safe_signal(SIGTTIN, SIG_DFL);
475 ssdp->d_ottou = safe_signal(SIGTTOU, SIG_DFL);
476 ssdp->d_opipe = safe_signal(SIGPIPE, SIG_IGN);
477 ssdp->d_ohup = safe_signal(SIGHUP, &__spamd_onsig);
478 ssdp->d_oint = safe_signal(SIGINT, &__spamd_onsig);
479 ssdp->d_oquit = safe_signal(SIGQUIT, &__spamd_onsig);
480 if (sigsetjmp(__spamd_actjmp, 1)) {
481 if (*vcp->vc_esep != '\0')
482 n_err(vcp->vc_esep);
483 goto jleave;
485 rele_sigs();
487 if ((dsfd = socket(PF_UNIX, SOCK_STREAM, 0)) == -1) {
488 n_err(_("%s`%s': can't create unix(4) socket: %s\n"),
489 vcp->vc_esep, _spam_cmds[vcp->vc_action], n_err_to_doc(n_err_no));
490 goto jleave;
493 if (connect(dsfd, (struct sockaddr*)&ssdp->d_sun, SUN_LEN(&ssdp->d_sun)) ==
494 -1) {
495 n_err(_("%s`%s': can't connect to *spam-socket*: %s\n"),
496 vcp->vc_esep, _spam_cmds[vcp->vc_action], n_err_to_doc(n_err_no));
497 close(dsfd);
498 dsfd = -1;
499 goto jleave;
502 /* The command header, finalized with an empty line.
503 * This needs to be written in a single write(2)! */
504 # undef _X
505 # define _X(X) do {memcpy(lp, X, sizeof(X) -1); lp += sizeof(X) -1;} while (0)
507 i = ((cp = ssdp->d_user.s) != NULL) ? ssdp->d_user.l : 0;
508 size = sizeof(NETLINE("A_VERY_LONG_COMMAND " SPAMD_IDENT)) +
509 sizeof(NETLINE("Content-length: 9223372036854775807")) +
510 ((cp != NULL) ? sizeof("User: ") + i + sizeof(NETNL) : 0) +
511 sizeof(NETLINE("Message-class: spam")) +
512 sizeof(NETLINE("Set: local")) +
513 sizeof(NETLINE("Remove: local")) +
514 sizeof(NETNL) /*+1*/;
515 lp = headbuf = n_lofi_alloc(size);
517 switch (vcp->vc_action) {
518 case _SPAM_RATE:
519 _X(NETLINE("CHECK " SPAMD_IDENT));
520 break;
521 case _SPAM_HAM:
522 case _SPAM_SPAM:
523 case _SPAM_FORGET:
524 _X(NETLINE("TELL " SPAMD_IDENT));
525 break;
528 lp += snprintf(lp, size, NETLINE("Content-length: %" PRIuZ),
529 (size_t)vcp->vc_mp->m_size);
531 if (cp != NULL) {
532 _X("User: ");
533 memcpy(lp, cp, i);
534 lp += i;
535 _X(NETNL);
538 switch (vcp->vc_action) {
539 case _SPAM_RATE:
540 _X(NETNL);
541 break;
542 case _SPAM_HAM:
543 _X(NETLINE("Message-class: ham")
544 NETLINE("Set: local")
545 NETNL);
546 break;
547 case _SPAM_SPAM:
548 _X(NETLINE("Message-class: spam")
549 NETLINE("Set: local")
550 NETNL);
551 break;
552 case _SPAM_FORGET:
553 if (vcp->vc_mp->m_flag & MSPAM)
554 _X(NETLINE("Message-class: spam"));
555 else
556 _X(NETLINE("Message-class: ham"));
557 _X(NETLINE("Remove: local")
558 NETNL);
559 break;
561 # undef _X
563 i = PTR2SIZE(lp - headbuf);
564 if (n_poption & n_PO_VERBVERB)
565 n_err(">>> %.*s <<<\n", (int)i, headbuf);
566 if (i != (size_t)write(dsfd, headbuf, i))
567 goto jeso;
569 /* Then simply pass through the message "as-is" */
570 for (size = vcp->vc_mp->m_size; size > 0;) {
571 i = fread(vcp->vc_buffer, sizeof *vcp->vc_buffer,
572 n_MIN(size, BUFFER_SIZE), vcp->vc_ifp);
573 if (i == 0) {
574 if (ferror(vcp->vc_ifp))
575 goto jeso;
576 break;
578 size -= i;
580 if (i != (size_t)write(dsfd, vcp->vc_buffer, i)) {
581 jeso:
582 n_err(_("%s`%s': I/O on *spamd-socket* failed: %s\n"),
583 vcp->vc_esep, _spam_cmds[vcp->vc_action], n_err_to_doc(n_err_no));
584 goto jleave;
588 /* We are finished, say so */
589 shutdown(dsfd, SHUT_WR);
591 /* Be aware on goto: i will be a line counter after this loop! */
592 for (size = 0, i = BUFFER_SIZE -1;;) {
593 ssize_t j = read(dsfd, vcp->vc_buffer + size, i);
594 if (j == -1)
595 goto jeso;
596 if (j == 0)
597 break;
598 size += j;
599 /* For the current way of doing things a single read will suffice.
600 * Note we'll be "penaltized" when awaiting EOF on the socket, at least
601 * in blocking mode, so do avoid that and break off */
602 break;
604 i = 0;
605 vcp->vc_buffer[size] = '\0';
607 if (size == 0 || size == BUFFER_SIZE) {
608 jebogus:
609 n_err(_("%s`%s': bogus spamd(1) I/O interaction (%lu)\n"),
610 vcp->vc_esep, _spam_cmds[vcp->vc_action], (ul_i)i);
611 # ifdef HAVE_DEVEL
612 if (n_poption & n_PO_VERBVERB)
613 n_err(">>> BUFFER: %s <<<\n", vcp->vc_buffer);
614 # endif
615 goto jleave;
618 /* From the response, read those lines that interest us */
619 for (lp = vcp->vc_buffer; size > 0; ++i) {
620 cp = lp;
621 lp = strchr(lp, NETNL[0]);
622 if (lp == NULL)
623 goto jebogus;
624 lp[0] = '\0';
625 if (lp[1] != NETNL[1])
626 goto jebogus;
627 lp += 2;
628 size -= PTR2SIZE(lp - cp);
630 if (i == 0) {
631 if (!strncmp(cp, "SPAMD/1.1 0 EX_OK", sizeof("SPAMD/1.1 0 EX_OK") -1))
632 continue;
633 if (vcp->vc_action != _SPAM_RATE ||
634 strstr(cp, "Service Unavailable") == NULL)
635 goto jebogus;
636 else {
637 /* Unfortunately a missing --allow-tell drops connection.. */
638 n_err(_("%s`%s': service not available in spamd(1) instance\n"),
639 vcp->vc_esep, _spam_cmds[vcp->vc_action]);
640 goto jleave;
642 } else if (i == 1) {
643 switch (vcp->vc_action) {
644 case _SPAM_RATE:
645 if (strncmp(cp, "Spam: ", sizeof("Spam: ") -1))
646 goto jebogus;
647 cp += sizeof("Spam: ") -1;
649 if (!strncmp(cp, "False", sizeof("False") -1)) {
650 cp += sizeof("False") -1;
651 vcp->vc_mp->m_flag &= ~(MSPAM | MSPAMUNSURE);
652 } else if (!strncmp(cp, "True", sizeof("True") -1)) {
653 cp += sizeof("True") -1;
654 vcp->vc_mp->m_flag &= ~(MSPAM | MSPAMUNSURE);
655 vcp->vc_mp->m_flag |= MSPAM;
656 } else
657 goto jebogus;
659 while (blankspacechar(*cp))
660 ++cp;
662 if (*cp++ != ';')
663 goto jebogus;
664 else {
665 char *xcp = strchr(cp, '/');
666 if (xcp != NULL) {
667 size = PTR2SIZE(xcp - cp);
668 cp[size] = '\0';
670 _spam_rate2score(vcp, cp);
672 goto jdone;
674 case _SPAM_HAM:
675 case _SPAM_SPAM:
676 /* Empty response means ok but "did nothing" */
677 if (*cp != '\0' &&
678 strncmp(cp, "DidSet: local", sizeof("DidSet: local") -1))
679 goto jebogus;
680 if (*cp == '\0' && vcp->vc_verbose)
681 n_err(_("\tBut spamd(1) \"did nothing\" for message\n"));
682 vcp->vc_mp->m_flag &= ~(MSPAM | MSPAMUNSURE);
683 if (vcp->vc_action == _SPAM_SPAM)
684 vcp->vc_mp->m_flag |= MSPAM;
685 goto jdone;
687 case _SPAM_FORGET:
688 if (*cp != '\0' &&
689 strncmp(cp, "DidRemove: local", sizeof("DidSet: local") -1))
690 goto jebogus;
691 if (*cp == '\0' && vcp->vc_verbose)
692 n_err(_("\tBut spamd(1) \"did nothing\" for message\n"));
693 vcp->vc_mp->m_flag &= ~(MSPAM | MSPAMUNSURE);
694 goto jdone;
699 jdone:
700 rv = TRU1;
701 jleave:
702 if (headbuf != NULL)
703 n_lofi_free(headbuf);
704 if (dsfd >= 0)
705 close(dsfd);
707 safe_signal(SIGQUIT, ssdp->d_oquit);
708 safe_signal(SIGINT, ssdp->d_oint);
709 safe_signal(SIGHUP, ssdp->d_ohup);
710 safe_signal(SIGPIPE, ssdp->d_opipe);
711 safe_signal(SIGTSTP, ssdp->d_otstp);
712 safe_signal(SIGTTIN, ssdp->d_ottin);
713 safe_signal(SIGTTOU, ssdp->d_ottou);
715 NYD2_LEAVE;
716 if (__spamd_sig != 0) {
717 sigset_t cset;
718 sigemptyset(&cset);
719 sigaddset(&cset, __spamd_sig);
720 sigprocmask(SIG_UNBLOCK, &cset, NULL);
721 n_raise(__spamd_sig);
722 assert(rv == FAL0);
724 return rv;
726 #endif /* HAVE_SPAM_SPAMD */
728 #ifdef HAVE_SPAM_FILTER
729 static bool_t
730 _spamfilter_setup(struct spam_vc *vcp)
732 struct spam_filter *sfp;
733 char const *cp, *var;
734 bool_t rv = FAL0;
735 NYD2_ENTER;
737 sfp = &vcp->vc_t.filter;
739 switch (vcp->vc_action) {
740 case _SPAM_RATE:
741 cp = ok_vlook(spamfilter_rate);
742 var = "spam-filter-rate";
743 goto jonecmd;
744 case _SPAM_HAM:
745 cp = ok_vlook(spamfilter_ham);
746 var = "spam-filter-ham";
747 goto jonecmd;
748 case _SPAM_SPAM:
749 cp = ok_vlook(spamfilter_spam);
750 var = "spam-filter-spam";
751 jonecmd:
752 if (cp == NULL) {
753 jecmd:
754 n_err(_("`%s': *%s* is not set\n"), _spam_cmds[vcp->vc_action], var);
755 goto jleave;
757 sfp->f_super.cf_cmd = savestr(cp);
758 break;
759 case _SPAM_FORGET:
760 var = "spam-filter-nospam";
761 if ((cp = ok_vlook(spamfilter_nospam)) == NULL)
762 goto jecmd;
763 sfp->f_cmd_nospam = savestr(cp);
764 if ((cp = ok_vlook(spamfilter_noham)) == NULL)
765 goto jecmd;
766 sfp->f_cmd_noham = savestr(cp);
767 break;
770 # ifdef HAVE_REGEX
771 if (vcp->vc_action == _SPAM_RATE &&
772 (cp = ok_vlook(spamfilter_rate_scanscore)) != NULL) {
773 int s;
774 char const *bp;
776 var = strchr(cp, ';');
777 if (var == NULL) {
778 n_err(_("`%s': *spamfilter-rate-scanscore*: missing semicolon;: %s\n"),
779 _spam_cmds[vcp->vc_action], cp);
780 goto jleave;
782 bp = &var[1];
784 if((n_idec_buf(&sfp->f_score_grpno, cp, PTR2SIZE(var - cp), 0,
785 n_IDEC_MODE_LIMIT_32BIT, NULL
786 ) & (n_IDEC_STATE_EMASK | n_IDEC_STATE_CONSUMED)
787 ) != n_IDEC_STATE_CONSUMED){
788 n_err(_("`%s': *spamfilter-rate-scanscore*: bad group: %s\n"),
789 _spam_cmds[vcp->vc_action], cp);
790 goto jleave;
792 if (sfp->f_score_grpno >= SPAM_FILTER_MATCHES) {
793 n_err(_("`%s': *spamfilter-rate-scanscore*: "
794 "group %u excesses limit %u\n"),
795 _spam_cmds[vcp->vc_action], sfp->f_score_grpno,
796 SPAM_FILTER_MATCHES);
797 goto jleave;
800 if ((s = regcomp(&sfp->f_score_regex, bp, REG_EXTENDED | REG_ICASE))
801 != 0) {
802 n_err(_("`%s': invalid *spamfilter-rate-scanscore* regex: %s: %s\n"),
803 _spam_cmds[vcp->vc_action], n_shexp_quote_cp(cp, FAL0),
804 n_regex_err_to_doc(NULL, s));
805 goto jleave;
807 if (sfp->f_score_grpno > sfp->f_score_regex.re_nsub) {
808 regfree(&sfp->f_score_regex);
809 n_err(_("`%s': *spamfilter-rate-scanscore*: no group %u: %s\n"),
810 _spam_cmds[vcp->vc_action], sfp->f_score_grpno, cp);
811 goto jleave;
814 # endif /* HAVE_REGEX */
816 _spam_cf_setup(vcp, TRU1);
818 vcp->vc_act = &_spamfilter_interact;
819 vcp->vc_dtor = &_spamfilter_dtor;
820 rv = TRU1;
821 jleave:
822 NYD2_LEAVE;
823 return rv;
826 static bool_t
827 _spamfilter_interact(struct spam_vc *vcp)
829 # ifdef HAVE_REGEX
830 regmatch_t rem[SPAM_FILTER_MATCHES], *remp;
831 struct spam_filter *sfp;
832 char *cp;
833 # endif
834 bool_t rv;
835 NYD2_ENTER;
837 if (vcp->vc_action == _SPAM_FORGET)
838 vcp->vc_t.cf.cf_cmd = (vcp->vc_mp->m_flag & MSPAM)
839 ? vcp->vc_t.filter.f_cmd_nospam : vcp->vc_t.filter.f_cmd_noham;
841 if (!(rv = _spam_cf_interact(vcp)))
842 goto jleave;
844 vcp->vc_mp->m_flag &= ~(MSPAM | MSPAMUNSURE);
845 if (vcp->vc_action != _SPAM_RATE) {
846 if (vcp->vc_action == _SPAM_SPAM)
847 vcp->vc_mp->m_flag |= MSPAM;
848 goto jleave;
849 } else switch (WEXITSTATUS(vcp->vc_t.filter.f_super.cf_waitstat)) {
850 case 2:
851 vcp->vc_mp->m_flag |= MSPAMUNSURE;
852 /* FALLTHRU */
853 case 1:
854 break;
855 case 0:
856 vcp->vc_mp->m_flag |= MSPAM;
857 break;
858 default:
859 rv = FAL0;
860 goto jleave;
863 # ifdef HAVE_REGEX
864 sfp = &vcp->vc_t.filter;
866 if (sfp->f_score_grpno == 0)
867 goto jleave;
868 if (sfp->f_super.cf_result == NULL) {
869 n_err(_("`%s': *spamfilter-rate-scanscore*: filter does not "
870 "produce output!\n"));
871 goto jleave;
874 remp = rem + sfp->f_score_grpno;
876 if (regexec(&sfp->f_score_regex, sfp->f_super.cf_result, n_NELEM(rem), rem,
877 0) == REG_NOMATCH || (remp->rm_so | remp->rm_eo) < 0) {
878 n_err(_("`%s': *spamfilter-rate-scanscore* "
879 "does not match filter output!\n"),
880 _spam_cmds[vcp->vc_action]);
881 sfp->f_score_grpno = 0;
882 goto jleave;
885 cp = sfp->f_super.cf_result;
886 cp[remp->rm_eo] = '\0';
887 cp += remp->rm_so;
888 _spam_rate2score(vcp, cp);
889 # endif /* HAVE_REGEX */
891 jleave:
892 NYD2_LEAVE;
893 return rv;
896 static void
897 _spamfilter_dtor(struct spam_vc *vcp)
899 struct spam_filter *sfp;
900 NYD2_ENTER;
902 sfp = &vcp->vc_t.filter;
904 if (sfp->f_super.cf_result != NULL)
905 n_free(sfp->f_super.cf_result);
906 # ifdef HAVE_REGEX
907 if (sfp->f_score_grpno > 0)
908 regfree(&sfp->f_score_regex);
909 # endif
910 NYD2_LEAVE;
912 #endif /* HAVE_SPAM_FILTER */
914 #if defined HAVE_SPAM_SPAMC || defined HAVE_SPAM_FILTER
915 static void
916 _spam_cf_setup(struct spam_vc *vcp, bool_t useshell)
918 struct str s;
919 char const *cp;
920 struct spam_cf *scfp;
921 NYD2_ENTER;
922 n_LCTA(2 < n_NELEM(scfp->cf_env), "Preallocated buffer too small");
924 scfp = &vcp->vc_t.cf;
926 if ((scfp->cf_useshell = useshell)) {
927 scfp->cf_acmd = ok_vlook(SHELL);
928 scfp->cf_a0 = "-c";
931 /* MAILX_FILENAME_GENERATED *//* TODO pathconf NAME_MAX; but user can create
932 * TODO a file wherever he wants! *Do* create a zero-size temporary file
933 * TODO and give *that* path as MAILX_FILENAME_TEMPORARY, clean it up once
934 * TODO the pipe returns? Like this we *can* verify path/name issues! */
935 cp = n_random_create_cp(n_MIN(NAME_MAX / 4, 16), NULL);
936 scfp->cf_env[0] = str_concat_csvl(&s,
937 n_PIPEENV_FILENAME_GENERATED, "=", cp, NULL)->s;
938 /* v15 compat NAIL_ environments vanish! */
939 scfp->cf_env[1] = str_concat_csvl(&s,
940 "NAIL_FILENAME_GENERATED", "=", cp, NULL)->s;
941 scfp->cf_env[2] = NULL;
942 NYD2_LEAVE;
945 static sigjmp_buf __spam_cf_actjmp; /* TODO someday, we won't need it */
946 static int volatile __spam_cf_sig; /* TODO someday, we won't need it */
947 static void
948 __spam_cf_onsig(int sig) /* TODO someday, we won't need it no more */
950 NYD_X; /* Signal handler */
951 __spam_cf_sig = sig;
952 siglongjmp(__spam_cf_actjmp, 1);
955 static bool_t
956 _spam_cf_interact(struct spam_vc *vcp)
958 struct spam_cf *scfp;
959 int p2c[2], c2p[2];
960 sigset_t cset;
961 char const *cp;
962 size_t size;
963 pid_t volatile pid;
964 enum {
965 _NONE = 0,
966 _SIGHOLD = 1<<0,
967 _P2C_0 = 1<<1,
968 _P2C_1 = 1<<2,
969 _P2C = _P2C_0 | _P2C_1,
970 _C2P_0 = 1<<3,
971 _C2P_1 = 1<<4,
972 _C2P = _C2P_0 | _C2P_1,
973 _JUMPED = 1<<5,
974 _RUNNING = 1<<6,
975 _GOODRUN = 1<<7,
976 _ERRORS = 1<<8
977 } volatile state = _NONE;
978 NYD2_ENTER;
980 scfp = &vcp->vc_t.cf;
981 if (scfp->cf_result != NULL) {
982 n_free(scfp->cf_result);
983 scfp->cf_result = NULL;
986 /* TODO Avoid that we jump away; yet necessary signal mess */
987 /*__spam_cf_sig = 0;*/
988 hold_sigs();
989 state |= _SIGHOLD;
990 scfp->cf_otstp = safe_signal(SIGTSTP, SIG_DFL);
991 scfp->cf_ottin = safe_signal(SIGTTIN, SIG_DFL);
992 scfp->cf_ottou = safe_signal(SIGTTOU, SIG_DFL);
993 scfp->cf_opipe = safe_signal(SIGPIPE, SIG_IGN);
994 scfp->cf_ohup = safe_signal(SIGHUP, &__spam_cf_onsig);
995 scfp->cf_oint = safe_signal(SIGINT, &__spam_cf_onsig);
996 scfp->cf_oquit = safe_signal(SIGQUIT, &__spam_cf_onsig);
997 /* Keep sigs blocked */
998 pid = 0; /* cc uninit */
1000 if (!pipe_cloexec(p2c)) {
1001 n_err(_("%s`%s': cannot create parent communication pipe: %s\n"),
1002 vcp->vc_esep, _spam_cmds[vcp->vc_action], n_err_to_doc(n_err_no));
1003 goto jtail;
1005 state |= _P2C;
1007 if (!pipe_cloexec(c2p)) {
1008 n_err(_("%s`%s': cannot create child pipe: %s\n"),
1009 vcp->vc_esep, _spam_cmds[vcp->vc_action], n_err_to_doc(n_err_no));
1010 goto jtail;
1012 state |= _C2P;
1014 if (sigsetjmp(__spam_cf_actjmp, 1)) {
1015 if (*vcp->vc_esep != '\0')
1016 n_err(vcp->vc_esep);
1017 state |= _JUMPED;
1018 goto jtail;
1020 rele_sigs();
1021 state &= ~_SIGHOLD;
1023 /* Start our command as requested */
1024 sigemptyset(&cset);
1025 if ((pid = n_child_start(
1026 (scfp->cf_acmd != NULL ? scfp->cf_acmd : scfp->cf_cmd),
1027 &cset, p2c[0], c2p[1],
1028 scfp->cf_a0, (scfp->cf_acmd != NULL ? scfp->cf_cmd : NULL), NULL,
1029 scfp->cf_env)) < 0) {
1030 state |= _ERRORS;
1031 goto jtail;
1033 state |= _RUNNING;
1034 close(p2c[0]);
1035 state &= ~_P2C_0;
1037 /* Yes, we could sendmp(SEND_MBOX), but simply passing through the MBOX
1038 * content does the same in effect, however much more efficiently.
1039 * XXX NOTE: this may mean we pass a message without From_ line! */
1040 for (size = vcp->vc_mp->m_size; size > 0;) {
1041 size_t i;
1043 i = fread(vcp->vc_buffer, 1, n_MIN(size, BUFFER_SIZE), vcp->vc_ifp);
1044 if (i == 0) {
1045 if (ferror(vcp->vc_ifp))
1046 state |= _ERRORS;
1047 break;
1049 size -= i;
1050 if (i != (size_t)write(p2c[1], vcp->vc_buffer, i)) {
1051 state |= _ERRORS;
1052 break;
1056 jtail:
1057 /* TODO Quite racy -- block anything for a while? */
1058 if (state & _SIGHOLD) {
1059 state &= ~_SIGHOLD;
1060 rele_sigs();
1063 if (state & _P2C_0) {
1064 state &= ~_P2C_0;
1065 close(p2c[0]);
1067 if (state & _C2P_1) {
1068 state &= ~_C2P_1;
1069 close(c2p[1]);
1071 /* And cause EOF for the reader */
1072 if (state & _P2C_1) {
1073 state &= ~_P2C_1;
1074 close(p2c[1]);
1077 if (state & _RUNNING) {
1078 if (!(state & _ERRORS) &&
1079 vcp->vc_action == _SPAM_RATE && !(state & (_JUMPED | _ERRORS))) {
1080 ssize_t i = read(c2p[0], vcp->vc_buffer, BUFFER_SIZE - 1);
1081 if (i > 0) {
1082 vcp->vc_buffer[i] = '\0';
1083 if ((cp = strchr(vcp->vc_buffer, NETNL[0])) == NULL &&
1084 (cp = strchr(vcp->vc_buffer, NETNL[1])) == NULL) {
1085 n_err(_("%s`%s': program generates too much output: %s\n"),
1086 vcp->vc_esep, _spam_cmds[vcp->vc_action],
1087 n_shexp_quote_cp(scfp->cf_cmd, FAL0));
1088 state |= _ERRORS;
1089 } else {
1090 scfp->cf_result = sbufdup(vcp->vc_buffer,
1091 PTR2SIZE(cp - vcp->vc_buffer));
1092 /* FIXME consume child output until EOF??? */
1094 } else if (i != 0)
1095 state |= _ERRORS;
1098 state &= ~_RUNNING;
1099 n_child_wait(pid, &scfp->cf_waitstat);
1100 if (WIFEXITED(scfp->cf_waitstat))
1101 state |= _GOODRUN;
1104 if (state & _C2P_0) {
1105 state &= ~_C2P_0;
1106 close(c2p[0]);
1109 safe_signal(SIGQUIT, scfp->cf_oquit);
1110 safe_signal(SIGINT, scfp->cf_oint);
1111 safe_signal(SIGHUP, scfp->cf_ohup);
1112 safe_signal(SIGPIPE, scfp->cf_opipe);
1113 safe_signal(SIGTSTP, scfp->cf_otstp);
1114 safe_signal(SIGTTIN, scfp->cf_ottin);
1115 safe_signal(SIGTTOU, scfp->cf_ottou);
1117 NYD2_LEAVE;
1118 if (state & _JUMPED) {
1119 assert(vcp->vc_dtor != NULL);
1120 (*vcp->vc_dtor)(vcp);
1122 sigemptyset(&cset);
1123 sigaddset(&cset, __spam_cf_sig);
1124 sigprocmask(SIG_UNBLOCK, &cset, NULL);
1125 n_raise(__spam_cf_sig);
1127 return !(state & (_JUMPED | _ERRORS));
1129 #endif /* HAVE_SPAM_SPAMC || HAVE_SPAM_FILTER */
1131 #if defined HAVE_SPAM_SPAMC || defined HAVE_SPAM_SPAMD ||\
1132 (defined HAVE_SPAM_FILTER && defined HAVE_REGEX)
1133 static void
1134 _spam_rate2score(struct spam_vc *vcp, char *buf){
1135 ui32_t m, s;
1136 enum n_idec_state ids;
1137 NYD2_ENTER;
1139 /* C99 */{ /* Overcome ISO C / compiler weirdness */
1140 char const *cp;
1142 cp = buf;
1143 ids = n_idec_ui32_cp(&m, buf, 10, &cp);
1144 if((ids & n_IDEC_STATE_EMASK) & ~n_IDEC_STATE_EBASE)
1145 goto jleave;
1146 buf = n_UNCONST(cp);
1149 s = 0;
1150 if(!(ids & n_IDEC_STATE_CONSUMED)){
1151 /* Floating-point rounding for non-mathematicians */
1152 char c1, c2, c3;
1154 ++buf; /* '.' */
1155 if((c1 = buf[0]) != '\0' && (c2 = buf[1]) != '\0' &&
1156 (c3 = buf[2]) != '\0'){
1157 buf[2] = '\0';
1158 if(c3 >= '5'){
1159 if(c2 == '9'){
1160 if(c1 == '9'){
1161 ++m;
1162 goto jscore_ok;
1163 }else
1164 buf[0] = ++c1;
1165 c2 = '0';
1166 }else
1167 ++c2;
1168 buf[1] = c2;
1172 ids = n_idec_ui32_cp(&s, buf, 10, NULL);
1173 if((ids & (n_IDEC_STATE_EMASK | n_IDEC_STATE_CONSUMED)
1174 ) != n_IDEC_STATE_CONSUMED)
1175 goto jleave;
1178 jscore_ok:
1179 vcp->vc_mp->m_spamscore = (m << 8) | s;
1180 jleave:
1181 NYD2_LEAVE;
1183 #endif /* _SPAM_SPAMC || _SPAM_SPAMD || (_SPAM_FILTER && HAVE_REGEX) */
1185 FL int
1186 c_spam_clear(void *v)
1188 int *ip;
1189 NYD_ENTER;
1191 for (ip = v; *ip != 0; ++ip)
1192 message[(size_t)*ip - 1].m_flag &= ~(MSPAM | MSPAMUNSURE);
1193 NYD_LEAVE;
1194 return 0;
1197 FL int
1198 c_spam_set(void *v)
1200 int *ip;
1201 NYD_ENTER;
1203 for (ip = v; *ip != 0; ++ip) {
1204 message[(size_t)*ip - 1].m_flag &= ~(MSPAM | MSPAMUNSURE);
1205 message[(size_t)*ip - 1].m_flag |= MSPAM;
1207 NYD_LEAVE;
1208 return 0;
1211 FL int
1212 c_spam_forget(void *v)
1214 int rv;
1215 NYD_ENTER;
1217 rv = _spam_action(_SPAM_FORGET, (int*)v) ? OKAY : STOP;
1218 NYD_LEAVE;
1219 return rv;
1222 FL int
1223 c_spam_ham(void *v)
1225 int rv;
1226 NYD_ENTER;
1228 rv = _spam_action(_SPAM_HAM, (int*)v) ? OKAY : STOP;
1229 NYD_LEAVE;
1230 return rv;
1233 FL int
1234 c_spam_rate(void *v)
1236 int rv;
1237 NYD_ENTER;
1239 rv = _spam_action(_SPAM_RATE, (int*)v) ? OKAY : STOP;
1240 NYD_LEAVE;
1241 return rv;
1244 FL int
1245 c_spam_spam(void *v)
1247 int rv;
1248 NYD_ENTER;
1250 rv = _spam_action(_SPAM_SPAM, (int*)v) ? OKAY : STOP;
1251 NYD_LEAVE;
1252 return rv;
1254 #endif /* HAVE_SPAM */
1256 /* s-it-mode */