Support `vput' for `cwd'
[s-mailx.git] / spam.c
blob6dadef4a74af2db6a640a1684556f83d0333da4c
1 /*@ S-nail - a mail user agent derived from Berkeley Mail.
2 *@ Spam related facilities.
4 * Copyright (c) 2013 - 2017 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
27 #if defined HAVE_SPAM_SPAMC || defined HAVE_SPAM_FILTER
28 # include <sys/wait.h>
29 #endif
31 #ifdef HAVE_SPAM_SPAMD
32 # include <sys/socket.h>
33 # include <sys/un.h>
34 #endif
36 /* This is chosen rather arbitrarily.
37 * It must be able to swallow the first line of a rate response,
38 * and an entire CHECK/TELL spamd(1) response */
39 #if BUFFER_SIZE < 1024
40 # error *spam-interface* BUFFER_SIZE constraints are not matched
41 #endif
43 #ifdef HAVE_SPAM_SPAMD
44 # define SPAMD_IDENT "SPAMC/1.5"
45 # ifndef SUN_LEN
46 # define SUN_LEN(SUP) \
47 (sizeof(*(SUP)) - sizeof((SUP)->sun_path) + strlen((SUP)->sun_path))
48 # endif
49 #endif
51 #ifdef HAVE_SPAM_FILTER
52 /* n_NELEM() of regmatch_t groups */
53 # define SPAM_FILTER_MATCHES 32u
54 #endif
56 enum spam_action {
57 _SPAM_RATE,
58 _SPAM_HAM,
59 _SPAM_SPAM,
60 _SPAM_FORGET
63 #if defined HAVE_SPAM_SPAMC || defined HAVE_SPAM_FILTER
64 struct spam_cf {
65 char const *cf_cmd;
66 char *cf_result; /* _SPAM_RATE: first response line */
67 int cf_waitstat;
68 ui8_t __pad[3];
69 bool_t cf_useshell;
70 /* .cf_cmd may be adjusted for each call (`spamforget')... */
71 char const *cf_acmd;
72 char const *cf_a0;
73 char const *cf_env[4];
74 sighandler_type cf_otstp;
75 sighandler_type cf_ottin;
76 sighandler_type cf_ottou;
77 sighandler_type cf_ohup;
78 sighandler_type cf_opipe;
79 sighandler_type cf_oint;
80 sighandler_type cf_oquit;
82 #endif
84 #ifdef HAVE_SPAM_SPAMC
85 struct spam_spamc {
86 struct spam_cf c_super;
87 char const *c_cmd_arr[8];
89 #endif
91 #ifdef HAVE_SPAM_SPAMD
92 struct spam_spamd {
93 struct str d_user;
94 sighandler_type d_otstp;
95 sighandler_type d_ottin;
96 sighandler_type d_ottou;
97 sighandler_type d_ohup;
98 sighandler_type d_opipe;
99 sighandler_type d_oint;
100 sighandler_type d_oquit;
101 struct sockaddr_un d_sun;
103 #endif
105 #ifdef HAVE_SPAM_FILTER
106 struct spam_filter {
107 struct spam_cf f_super;
108 char const *f_cmd_nospam; /* Working relative to current message.. */
109 char const *f_cmd_noham;
110 # ifdef HAVE_REGEX
111 ui8_t __pad[4];
112 ui32_t f_score_grpno; /* 0 for not set */
113 regex_t f_score_regex;
114 # endif
116 #endif
118 struct spam_vc {
119 enum spam_action vc_action;
120 bool_t vc_verbose; /* Verbose output */
121 bool_t vc_progress; /* "Progress meter" (mutual verbose) */
122 ui8_t __pad[2];
123 bool_t (*vc_act)(struct spam_vc *);
124 void (*vc_dtor)(struct spam_vc *);
125 char *vc_buffer; /* I/O buffer, BUFFER_SIZE bytes */
126 size_t vc_mno; /* Current message number */
127 struct message *vc_mp; /* Current message */
128 FILE *vc_ifp; /* Input stream on .vc_mp */
129 union {
130 #ifdef HAVE_SPAM_SPAMC
131 struct spam_spamc spamc;
132 #endif
133 #ifdef HAVE_SPAM_SPAMD
134 struct spam_spamd spamd;
135 #endif
136 #ifdef HAVE_SPAM_FILTER
137 struct spam_filter filter;
138 #endif
139 #if defined HAVE_SPAM_SPAMC || defined HAVE_SPAM_FILTER
140 struct spam_cf cf;
141 #endif
142 } vc_t;
143 char const *vc_esep; /* Error separator for progress mode */
146 /* Indices according to enum spam_action */
147 static char const _spam_cmds[][16] = {
148 "spamrate", "spamham", "spamspam", "spamforget"
151 /* Shared action setup */
152 static bool_t _spam_action(enum spam_action sa, int *ip);
154 /* *spam-interface*=spamc: initialize, communicate */
155 #ifdef HAVE_SPAM_SPAMC
156 static bool_t _spamc_setup(struct spam_vc *vcp);
157 static bool_t _spamc_interact(struct spam_vc *vcp);
158 static void _spamc_dtor(struct spam_vc *vcp);
159 #endif
161 /* *spam-interface*=spamd: initialize, communicate */
162 #ifdef HAVE_SPAM_SPAMD
163 static bool_t _spamd_setup(struct spam_vc *vcp);
164 static bool_t _spamd_interact(struct spam_vc *vcp);
165 #endif
167 /* *spam-interface*=filter: initialize, communicate */
168 #ifdef HAVE_SPAM_FILTER
169 static bool_t _spamfilter_setup(struct spam_vc *vcp);
170 static bool_t _spamfilter_interact(struct spam_vc *vcp);
171 static void _spamfilter_dtor(struct spam_vc *vcp);
172 #endif
174 /* *spam-interface*=(spamc|filter): create child + communication */
175 #if defined HAVE_SPAM_SPAMC || defined HAVE_SPAM_FILTER
176 static void _spam_cf_setup(struct spam_vc *vcp, bool_t useshell);
177 static bool_t _spam_cf_interact(struct spam_vc *vcp);
178 #endif
180 /* Convert a floating-point spam rate into message.m_spamscore */
181 #if defined HAVE_SPAM_SPAMC || defined HAVE_SPAM_SPAMD ||\
182 (defined HAVE_SPAM_FILTER && defined HAVE_REGEX)
183 static void _spam_rate2score(struct spam_vc *vcp, char *buf);
184 #endif
186 static bool_t
187 _spam_action(enum spam_action sa, int *ip)
189 struct spam_vc vc;
190 size_t maxsize, skipped, cnt, curr;
191 char const *cp;
192 bool_t ok = FAL0;
193 NYD_ENTER;
195 memset(&vc, 0, sizeof vc);
196 vc.vc_action = sa;
197 vc.vc_verbose = ((n_poption & n_PO_VERB) != 0);
198 vc.vc_progress = (!vc.vc_verbose && ((n_psonce & n_PSO_INTERACTIVE) != 0));
199 vc.vc_esep = vc.vc_progress ? "\n" : n_empty;
201 /* Check and setup the desired spam interface */
202 if ((cp = ok_vlook(spam_interface)) == NULL) {
203 n_err(_("`%s': no *spam-interface* set\n"), _spam_cmds[sa]);
204 goto jleave;
205 #ifdef HAVE_SPAM_SPAMC
206 } else if (!asccasecmp(cp, "spamc")) {
207 if (!_spamc_setup(&vc))
208 goto jleave;
209 #endif
210 #ifdef HAVE_SPAM_SPAMD
211 } else if (!asccasecmp(cp, "spamd")) { /* TODO v15: remove */
212 n_OBSOLETE(_("*spam-interface*=spamd is obsolete, please use =spamc"));
213 if (!_spamd_setup(&vc))
214 goto jleave;
215 #endif
216 #ifdef HAVE_SPAM_FILTER
217 } else if (!asccasecmp(cp, "filter")) {
218 if (!_spamfilter_setup(&vc))
219 goto jleave;
220 #endif
221 } else {
222 n_err(_("`%s': unknown / unsupported *spam-interface*: %s\n"),
223 _spam_cmds[sa], cp);
224 goto jleave;
227 /* *spam-maxsize* we do handle ourselfs instead */
228 if ((cp = ok_vlook(spam_maxsize)) == NULL ||
229 (n_idec_ui32_cp(&maxsize, cp, 0, NULL), maxsize) == 0)
230 maxsize = SPAM_MAXSIZE;
232 /* Finally get an I/O buffer */
233 vc.vc_buffer = salloc(BUFFER_SIZE);
235 skipped = cnt = 0;
236 if (vc.vc_progress) {
237 while (ip[cnt] != 0)
238 ++cnt;
240 for (curr = 0, ok = TRU1; *ip != 0; --cnt, ++curr, ++ip) {
241 vc.vc_mno = (size_t)*ip;
242 vc.vc_mp = message + vc.vc_mno - 1;
243 if (sa == _SPAM_RATE)
244 vc.vc_mp->m_spamscore = 0;
246 if (vc.vc_mp->m_size > maxsize) {
247 if (vc.vc_verbose)
248 n_err(_("`%s': message %lu exceeds maxsize (%lu > %lu), skip\n"),
249 _spam_cmds[sa], (ul_i)vc.vc_mno, (ul_i)(size_t)vc.vc_mp->m_size,
250 (ul_i)maxsize);
251 else if (vc.vc_progress) {
252 fprintf(n_stdout, "\r%s: !%-6" PRIuZ " %6" PRIuZ "/%-6" PRIuZ,
253 _spam_cmds[sa], vc.vc_mno, cnt, curr);
254 fflush(n_stdout);
256 ++skipped;
257 } else {
258 if (vc.vc_verbose)
259 n_err(_("`%s': message %lu\n"), _spam_cmds[sa], (ul_i)vc.vc_mno);
260 else if (vc.vc_progress) {
261 fprintf(n_stdout, "\r%s: .%-6" PRIuZ " %6" PRIuZ "/%-6" PRIuZ,
262 _spam_cmds[sa], vc.vc_mno, cnt, curr);
263 fflush(n_stdout);
266 setdot(vc.vc_mp);
267 if ((vc.vc_ifp = setinput(&mb, vc.vc_mp, NEED_BODY)) == NULL) {
268 n_err(_("%s`%s': cannot load message %lu: %s\n"),
269 vc.vc_esep, _spam_cmds[sa], (ul_i)vc.vc_mno, strerror(errno));
270 ok = FAL0;
271 break;
274 if (!(ok = (*vc.vc_act)(&vc)))
275 break;
278 if (vc.vc_progress) {
279 if (curr > 0)
280 fprintf(n_stdout, _(" %s (%" PRIuZ "/%" PRIuZ " all/skipped)\n"),
281 (ok ? _("done") : V_(n_error)), curr, skipped);
282 fflush(n_stdout);
285 if (vc.vc_dtor != NULL)
286 (*vc.vc_dtor)(&vc);
287 jleave:
288 NYD_LEAVE;
289 return !ok;
292 #ifdef HAVE_SPAM_SPAMC
293 static bool_t
294 _spamc_setup(struct spam_vc *vcp)
296 struct spam_spamc *sscp;
297 struct str str;
298 char const **args, *cp;
299 bool_t rv = FAL0;
300 NYD2_ENTER;
302 sscp = &vcp->vc_t.spamc;
303 args = sscp->c_cmd_arr;
305 if ((cp = ok_vlook(spamc_command)) == NULL) {
306 # ifdef SPAM_SPAMC_PATH
307 cp = SPAM_SPAMC_PATH;
308 # else
309 n_err(_("`%s': *spamc-command* is not set\n"),
310 _spam_cmds[vcp->vc_action]);
311 goto jleave;
312 # endif
314 *args++ = cp;
316 switch (vcp->vc_action) {
317 case _SPAM_RATE:
318 *args = "-c";
319 break;
320 case _SPAM_HAM:
321 args[1] = "ham";
322 goto jlearn;
323 case _SPAM_SPAM:
324 args[1] = "spam";
325 goto jlearn;
326 case _SPAM_FORGET:
327 args[1] = "forget";
328 jlearn:
329 *args = "-L";
330 ++args;
331 break;
333 ++args;
335 *args++ = "-l"; /* --log-to-stderr */
336 *args++ = "-x"; /* No "safe callback", we need to react on errors! */
338 if ((cp = ok_vlook(spamc_arguments)) != NULL)
339 *args++ = cp;
341 if ((cp = ok_vlook(spamc_user)) != NULL) {
342 if (*cp == '\0')
343 cp = ok_vlook(LOGNAME);
344 *args++ = "-u";
345 *args++ = cp;
347 assert(PTR2SIZE(args - sscp->c_cmd_arr) <= n_NELEM(sscp->c_cmd_arr));
349 *args = NULL;
350 sscp->c_super.cf_cmd = str_concat_cpa(&str, sscp->c_cmd_arr, " ")->s;
351 if (vcp->vc_verbose)
352 n_err(_("spamc(1) via %s\n"),
353 n_shexp_quote_cp(sscp->c_super.cf_cmd, FAL0));
355 _spam_cf_setup(vcp, FAL0);
357 vcp->vc_act = &_spamc_interact;
358 vcp->vc_dtor = &_spamc_dtor;
359 rv = TRU1;
360 # ifndef SPAM_SPAMC_PATH
361 jleave:
362 # endif
363 NYD2_LEAVE;
364 return rv;
367 static bool_t
368 _spamc_interact(struct spam_vc *vcp)
370 bool_t rv;
371 NYD2_ENTER;
373 if (!(rv = _spam_cf_interact(vcp)))
374 goto jleave;
376 vcp->vc_mp->m_flag &= ~(MSPAM | MSPAMUNSURE);
377 if (vcp->vc_action != _SPAM_RATE) {
378 if (vcp->vc_action == _SPAM_SPAM)
379 vcp->vc_mp->m_flag |= MSPAM;
380 } else {
381 char *buf, *cp;
383 switch (WEXITSTATUS(vcp->vc_t.spamc.c_super.cf_waitstat)) {
384 case 1:
385 vcp->vc_mp->m_flag |= MSPAM;
386 /* FALLTHRU */
387 case 0:
388 break;
389 default:
390 rv = FAL0;
391 goto jleave;
394 if ((cp = strchr(buf = vcp->vc_t.spamc.c_super.cf_result, '/')) != NULL)
395 buf[PTR2SIZE(cp - buf)] = '\0';
396 _spam_rate2score(vcp, buf);
398 jleave:
399 NYD2_LEAVE;
400 return rv;
403 static void
404 _spamc_dtor(struct spam_vc *vcp)
406 NYD2_ENTER;
407 if (vcp->vc_t.spamc.c_super.cf_result != NULL)
408 free(vcp->vc_t.spamc.c_super.cf_result);
409 NYD2_LEAVE;
411 #endif /* HAVE_SPAM_SPAMC */
413 #ifdef HAVE_SPAM_SPAMD
414 static bool_t
415 _spamd_setup(struct spam_vc *vcp)
417 struct spam_spamd *ssdp;
418 char const *cp;
419 size_t l;
420 bool_t rv = FAL0;
421 NYD2_ENTER;
423 ssdp = &vcp->vc_t.spamd;
425 if ((cp = ok_vlook(spamd_user)) != NULL) {
426 if (*cp == '\0')
427 cp = ok_vlook(LOGNAME);
428 ssdp->d_user.l = strlen(ssdp->d_user.s = n_UNCONST(cp));
431 if ((cp = ok_vlook(spamd_socket)) == NULL) {
432 n_err(_("`%s': required *spamd-socket* is not set\n"),
433 _spam_cmds[vcp->vc_action]);
434 goto jleave;
436 if ((l = strlen(cp) +1) >= sizeof(ssdp->d_sun.sun_path)) {
437 n_err(_("`%s': *spamd-socket* too long: %s\n"),
438 _spam_cmds[vcp->vc_action], n_shexp_quote_cp(cp, FAL0));
439 goto jleave;
441 ssdp->d_sun.sun_family = AF_UNIX;
442 memcpy(ssdp->d_sun.sun_path, cp, l);
444 vcp->vc_act = &_spamd_interact;
445 rv = TRU1;
446 jleave:
447 NYD2_LEAVE;
448 return rv;
451 static sigjmp_buf __spamd_actjmp; /* TODO oneday, we won't need it no more */
452 static int volatile __spamd_sig; /* TODO oneday, we won't need it no more */
453 static void
454 __spamd_onsig(int sig) /* TODO someday, we won't need it no more */
456 NYD_X; /* Signal handler */
457 __spamd_sig = sig;
458 siglongjmp(__spamd_actjmp, 1);
461 static bool_t
462 _spamd_interact(struct spam_vc *vcp)
464 struct spam_spamd *ssdp;
465 size_t size, i;
466 char *lp, *cp, * volatile headbuf = NULL;
467 int volatile dsfd = -1;
468 bool_t volatile rv = FAL0;
469 NYD2_ENTER;
471 ssdp = &vcp->vc_t.spamd;
473 __spamd_sig = 0;
474 hold_sigs();
475 ssdp->d_otstp = safe_signal(SIGTSTP, SIG_DFL);
476 ssdp->d_ottin = safe_signal(SIGTTIN, SIG_DFL);
477 ssdp->d_ottou = safe_signal(SIGTTOU, SIG_DFL);
478 ssdp->d_opipe = safe_signal(SIGPIPE, SIG_IGN);
479 ssdp->d_ohup = safe_signal(SIGHUP, &__spamd_onsig);
480 ssdp->d_oint = safe_signal(SIGINT, &__spamd_onsig);
481 ssdp->d_oquit = safe_signal(SIGQUIT, &__spamd_onsig);
482 if (sigsetjmp(__spamd_actjmp, 1)) {
483 if (*vcp->vc_esep != '\0')
484 n_err(vcp->vc_esep);
485 goto jleave;
487 rele_sigs();
489 if ((dsfd = socket(PF_UNIX, SOCK_STREAM, 0)) == -1) {
490 n_err(_("%s`%s': can't create unix(4) socket: %s\n"),
491 vcp->vc_esep, _spam_cmds[vcp->vc_action], strerror(errno));
492 goto jleave;
495 if (connect(dsfd, (struct sockaddr*)&ssdp->d_sun, SUN_LEN(&ssdp->d_sun)) ==
496 -1) {
497 n_err(_("%s`%s': can't connect to *spam-socket*: %s\n"),
498 vcp->vc_esep, _spam_cmds[vcp->vc_action], strerror(errno));
499 close(dsfd);
500 goto jleave;
503 /* The command header, finalized with an empty line.
504 * This needs to be written in a single write(2)! */
505 # undef _X
506 # define _X(X) do {memcpy(lp, X, sizeof(X) -1); lp += sizeof(X) -1;} while (0)
508 i = ((cp = ssdp->d_user.s) != NULL) ? ssdp->d_user.l : 0;
509 lp = headbuf = ac_alloc(
510 sizeof(NETLINE("A_VERY_LONG_COMMAND " SPAMD_IDENT)) +
511 sizeof(NETLINE("Content-length: 9223372036854775807")) +
512 ((cp != NULL) ? sizeof("User: ") + i + sizeof(NETNL) : 0) +
513 sizeof(NETLINE("Message-class: spam")) +
514 sizeof(NETLINE("Set: local")) +
515 sizeof(NETLINE("Remove: local")) +
516 sizeof(NETNL) /*+1*/);
518 switch (vcp->vc_action) {
519 case _SPAM_RATE:
520 _X(NETLINE("CHECK " SPAMD_IDENT));
521 break;
522 case _SPAM_HAM:
523 case _SPAM_SPAM:
524 case _SPAM_FORGET:
525 _X(NETLINE("TELL " SPAMD_IDENT));
526 break;
529 lp += snprintf(lp, 0x7FFF, NETLINE("Content-length: %" PRIuZ),
530 (size_t)vcp->vc_mp->m_size);
532 if (cp != NULL) {
533 _X("User: ");
534 memcpy(lp, cp, i);
535 lp += i;
536 _X(NETNL);
539 switch (vcp->vc_action) {
540 case _SPAM_RATE:
541 _X(NETNL);
542 break;
543 case _SPAM_HAM:
544 _X(NETLINE("Message-class: ham")
545 NETLINE("Set: local")
546 NETNL);
547 break;
548 case _SPAM_SPAM:
549 _X(NETLINE("Message-class: spam")
550 NETLINE("Set: local")
551 NETNL);
552 break;
553 case _SPAM_FORGET:
554 if (vcp->vc_mp->m_flag & MSPAM)
555 _X(NETLINE("Message-class: spam"));
556 else
557 _X(NETLINE("Message-class: ham"));
558 _X(NETLINE("Remove: local")
559 NETNL);
560 break;
562 # undef _X
564 i = PTR2SIZE(lp - headbuf);
565 if (n_poption & n_PO_VERBVERB)
566 n_err(">>> %.*s <<<\n", (int)i, headbuf);
567 if (i != (size_t)write(dsfd, headbuf, i))
568 goto jeso;
570 /* Then simply pass through the message "as-is" */
571 for (size = vcp->vc_mp->m_size; size > 0;) {
572 i = fread(vcp->vc_buffer, sizeof *vcp->vc_buffer,
573 n_MIN(size, BUFFER_SIZE), vcp->vc_ifp);
574 if (i == 0) {
575 if (ferror(vcp->vc_ifp))
576 goto jeso;
577 break;
579 size -= i;
581 if (i != (size_t)write(dsfd, vcp->vc_buffer, i)) {
582 jeso:
583 n_err(_("%s`%s': I/O on *spamd-socket* failed: %s\n"),
584 vcp->vc_esep, _spam_cmds[vcp->vc_action], strerror(errno));
585 goto jleave;
589 /* We are finished, say so */
590 shutdown(dsfd, SHUT_WR);
592 /* Be aware on goto: i will be a line counter after this loop! */
593 for (size = 0, i = BUFFER_SIZE -1;;) {
594 ssize_t j = read(dsfd, vcp->vc_buffer + size, i);
595 if (j == -1)
596 goto jeso;
597 if (j == 0)
598 break;
599 size += j;
600 i -= j;
601 /* For the current way of doing things a single read will suffice.
602 * Note we'll be "penaltized" when awaiting EOF on the socket, at least
603 * in blocking mode, so do avoid that and break off */
604 break;
606 i = 0;
607 vcp->vc_buffer[size] = '\0';
609 if (size == 0 || size == BUFFER_SIZE) {
610 jebogus:
611 n_err(_("%s`%s': bogus spamd(1) I/O interaction (%lu)\n"),
612 vcp->vc_esep, _spam_cmds[vcp->vc_action], (ul_i)i);
613 # ifdef HAVE_DEVEL
614 if (n_poption & n_PO_VERBVERB)
615 n_err(">>> BUFFER: %s <<<\n", vcp->vc_buffer);
616 # endif
617 goto jleave;
620 /* From the response, read those lines that interest us */
621 for (lp = vcp->vc_buffer; size > 0; ++i) {
622 cp = lp;
623 lp = strchr(lp, NETNL[0]);
624 if (lp == NULL)
625 goto jebogus;
626 lp[0] = '\0';
627 if (lp[1] != NETNL[1])
628 goto jebogus;
629 lp += 2;
630 size -= PTR2SIZE(lp - cp);
632 if (i == 0) {
633 if (!strncmp(cp, "SPAMD/1.1 0 EX_OK", sizeof("SPAMD/1.1 0 EX_OK") -1))
634 continue;
635 if (vcp->vc_action != _SPAM_RATE ||
636 strstr(cp, "Service Unavailable") == NULL)
637 goto jebogus;
638 else {
639 /* Unfortunately a missing --allow-tell drops connection.. */
640 n_err(_("%s`%s': service not available in spamd(1) instance\n"),
641 vcp->vc_esep, _spam_cmds[vcp->vc_action]);
642 goto jleave;
644 } else if (i == 1) {
645 switch (vcp->vc_action) {
646 case _SPAM_RATE:
647 if (strncmp(cp, "Spam: ", sizeof("Spam: ") -1))
648 goto jebogus;
649 cp += sizeof("Spam: ") -1;
651 if (!strncmp(cp, "False", sizeof("False") -1)) {
652 cp += sizeof("False") -1;
653 vcp->vc_mp->m_flag &= ~(MSPAM | MSPAMUNSURE);
654 } else if (!strncmp(cp, "True", sizeof("True") -1)) {
655 cp += sizeof("True") -1;
656 vcp->vc_mp->m_flag &= ~(MSPAM | MSPAMUNSURE);
657 vcp->vc_mp->m_flag |= MSPAM;
658 } else
659 goto jebogus;
661 while (blankspacechar(*cp))
662 ++cp;
664 if (*cp++ != ';')
665 goto jebogus;
666 else {
667 char *xcp = strchr(cp, '/');
668 if (xcp != NULL) {
669 size = PTR2SIZE(xcp - cp);
670 cp[size] = '\0';
672 _spam_rate2score(vcp, cp);
674 goto jdone;
676 case _SPAM_HAM:
677 case _SPAM_SPAM:
678 /* Empty response means ok but "did nothing" */
679 if (*cp != '\0' &&
680 strncmp(cp, "DidSet: local", sizeof("DidSet: local") -1))
681 goto jebogus;
682 if (*cp == '\0' && vcp->vc_verbose)
683 n_err(_("\tBut spamd(1) \"did nothing\" for message\n"));
684 vcp->vc_mp->m_flag &= ~(MSPAM | MSPAMUNSURE);
685 if (vcp->vc_action == _SPAM_SPAM)
686 vcp->vc_mp->m_flag |= MSPAM;
687 goto jdone;
689 case _SPAM_FORGET:
690 if (*cp != '\0' &&
691 strncmp(cp, "DidRemove: local", sizeof("DidSet: local") -1))
692 goto jebogus;
693 if (*cp == '\0' && vcp->vc_verbose)
694 n_err(_("\tBut spamd(1) \"did nothing\" for message\n"));
695 vcp->vc_mp->m_flag &= ~(MSPAM | MSPAMUNSURE);
696 goto jdone;
701 jdone:
702 rv = TRU1;
703 jleave:
704 if (headbuf != NULL)
705 ac_free(headbuf);
706 if (dsfd >= 0)
707 close(dsfd);
709 safe_signal(SIGQUIT, ssdp->d_oquit);
710 safe_signal(SIGINT, ssdp->d_oint);
711 safe_signal(SIGHUP, ssdp->d_ohup);
712 safe_signal(SIGPIPE, ssdp->d_opipe);
713 safe_signal(SIGTSTP, ssdp->d_otstp);
714 safe_signal(SIGTTIN, ssdp->d_ottin);
715 safe_signal(SIGTTOU, ssdp->d_ottou);
717 NYD2_LEAVE;
718 if (__spamd_sig != 0) {
719 sigset_t cset;
720 sigemptyset(&cset);
721 sigaddset(&cset, __spamd_sig);
722 sigprocmask(SIG_UNBLOCK, &cset, NULL);
723 n_raise(__spamd_sig);
724 assert(rv == FAL0);
726 return rv;
728 #endif /* HAVE_SPAM_SPAMD */
730 #ifdef HAVE_SPAM_FILTER
731 static bool_t
732 _spamfilter_setup(struct spam_vc *vcp)
734 struct spam_filter *sfp;
735 char const *cp, *var;
736 bool_t rv = FAL0;
737 NYD2_ENTER;
739 sfp = &vcp->vc_t.filter;
741 switch (vcp->vc_action) {
742 case _SPAM_RATE:
743 cp = ok_vlook(spamfilter_rate);
744 var = "spam-filter-rate";
745 goto jonecmd;
746 case _SPAM_HAM:
747 cp = ok_vlook(spamfilter_ham);
748 var = "spam-filter-ham";
749 goto jonecmd;
750 case _SPAM_SPAM:
751 cp = ok_vlook(spamfilter_spam);
752 var = "spam-filter-spam";
753 jonecmd:
754 if (cp == NULL) {
755 jecmd:
756 n_err(_("`%s': *%s* is not set\n"), _spam_cmds[vcp->vc_action], var);
757 goto jleave;
759 sfp->f_super.cf_cmd = savestr(cp);
760 break;
761 case _SPAM_FORGET:
762 var = "spam-filter-nospam";
763 if ((cp = ok_vlook(spamfilter_nospam)) == NULL)
764 goto jecmd;
765 sfp->f_cmd_nospam = savestr(cp);
766 if ((cp = ok_vlook(spamfilter_noham)) == NULL)
767 goto jecmd;
768 sfp->f_cmd_noham = savestr(cp);
769 break;
772 # ifdef HAVE_REGEX
773 if (vcp->vc_action == _SPAM_RATE &&
774 (cp = ok_vlook(spamfilter_rate_scanscore)) != NULL) {
775 int s;
776 char const *bp;
778 var = strchr(cp, ';');
779 if (var == NULL) {
780 n_err(_("`%s': *spamfilter-rate-scanscore*: missing semicolon;: %s\n"),
781 _spam_cmds[vcp->vc_action], cp);
782 goto jleave;
784 bp = &var[1];
786 if((n_idec_buf(&sfp->f_score_grpno, cp, PTR2SIZE(var - cp), 0,
787 n_IDEC_MODE_LIMIT_32BIT, NULL
788 ) & (n_IDEC_STATE_EMASK | n_IDEC_STATE_CONSUMED)
789 ) != n_IDEC_STATE_CONSUMED){
790 n_err(_("`%s': *spamfilter-rate-scanscore*: bad group: %s\n"),
791 _spam_cmds[vcp->vc_action], cp);
792 goto jleave;
794 if (sfp->f_score_grpno >= SPAM_FILTER_MATCHES) {
795 n_err(_("`%s': *spamfilter-rate-scanscore*: "
796 "group %u excesses limit %u\n"),
797 _spam_cmds[vcp->vc_action], sfp->f_score_grpno,
798 SPAM_FILTER_MATCHES);
799 goto jleave;
802 if ((s = regcomp(&sfp->f_score_regex, bp, REG_EXTENDED | REG_ICASE))
803 != 0) {
804 n_err(_("`%s': invalid *spamfilter-rate-scanscore* regex: %s: %s\n"),
805 _spam_cmds[vcp->vc_action], n_shexp_quote_cp(cp, FAL0),
806 n_regex_err_to_str(&sfp->f_score_regex, s));
807 goto jleave;
809 if (sfp->f_score_grpno > sfp->f_score_regex.re_nsub) {
810 regfree(&sfp->f_score_regex);
811 n_err(_("`%s': *spamfilter-rate-scanscore*: no group %u: %s\n"),
812 _spam_cmds[vcp->vc_action], sfp->f_score_grpno, cp);
813 goto jleave;
816 # endif /* HAVE_REGEX */
818 _spam_cf_setup(vcp, TRU1);
820 vcp->vc_act = &_spamfilter_interact;
821 vcp->vc_dtor = &_spamfilter_dtor;
822 rv = TRU1;
823 jleave:
824 NYD2_LEAVE;
825 return rv;
828 static bool_t
829 _spamfilter_interact(struct spam_vc *vcp)
831 # ifdef HAVE_REGEX
832 regmatch_t rem[SPAM_FILTER_MATCHES], *remp;
833 struct spam_filter *sfp;
834 char *cp;
835 # endif
836 bool_t rv;
837 NYD2_ENTER;
839 if (vcp->vc_action == _SPAM_FORGET)
840 vcp->vc_t.cf.cf_cmd = (vcp->vc_mp->m_flag & MSPAM)
841 ? vcp->vc_t.filter.f_cmd_nospam : vcp->vc_t.filter.f_cmd_noham;
843 if (!(rv = _spam_cf_interact(vcp)))
844 goto jleave;
846 vcp->vc_mp->m_flag &= ~(MSPAM | MSPAMUNSURE);
847 if (vcp->vc_action != _SPAM_RATE) {
848 if (vcp->vc_action == _SPAM_SPAM)
849 vcp->vc_mp->m_flag |= MSPAM;
850 goto jleave;
851 } else switch (WEXITSTATUS(vcp->vc_t.filter.f_super.cf_waitstat)) {
852 case 2:
853 vcp->vc_mp->m_flag |= MSPAMUNSURE;
854 /* FALLTHRU */
855 case 1:
856 break;
857 case 0:
858 vcp->vc_mp->m_flag |= MSPAM;
859 break;
860 default:
861 rv = FAL0;
862 goto jleave;
865 # ifdef HAVE_REGEX
866 sfp = &vcp->vc_t.filter;
868 if (sfp->f_score_grpno == 0)
869 goto jleave;
871 assert(sfp->f_super.cf_result != NULL);
872 remp = rem + sfp->f_score_grpno;
874 if (regexec(&sfp->f_score_regex, sfp->f_super.cf_result, n_NELEM(rem), rem,
875 0) == REG_NOMATCH || (remp->rm_so | remp->rm_eo) < 0) {
876 n_err(_("`%s': *spamfilter-rate-scanscore* "
877 "doesn't match filter output!\n"),
878 _spam_cmds[vcp->vc_action]);
879 sfp->f_score_grpno = 0;
880 goto jleave;
883 cp = sfp->f_super.cf_result;
884 cp[remp->rm_eo] = '\0';
885 cp += remp->rm_so;
886 _spam_rate2score(vcp, cp);
887 # endif /* HAVE_REGEX */
889 jleave:
890 NYD2_LEAVE;
891 return rv;
894 static void
895 _spamfilter_dtor(struct spam_vc *vcp)
897 struct spam_filter *sfp;
898 NYD2_ENTER;
900 sfp = &vcp->vc_t.filter;
902 if (sfp->f_super.cf_result != NULL)
903 free(sfp->f_super.cf_result);
904 # ifdef HAVE_REGEX
905 if (sfp->f_score_grpno > 0)
906 regfree(&sfp->f_score_regex);
907 # endif
908 NYD2_LEAVE;
910 #endif /* HAVE_SPAM_FILTER */
912 #if defined HAVE_SPAM_SPAMC || defined HAVE_SPAM_FILTER
913 static void
914 _spam_cf_setup(struct spam_vc *vcp, bool_t useshell)
916 struct str s;
917 char const *cp;
918 struct spam_cf *scfp;
919 NYD2_ENTER;
920 n_LCTA(2 < n_NELEM(scfp->cf_env), "Preallocated buffer too small");
922 scfp = &vcp->vc_t.cf;
924 if ((scfp->cf_useshell = useshell)) {
925 scfp->cf_acmd = ok_vlook(SHELL);
926 scfp->cf_a0 = "-c";
929 /* MAILX_FILENAME_GENERATED *//* TODO pathconf NAME_MAX; but user can create
930 * TODO a file wherever he wants! *Do* create a zero-size temporary file
931 * TODO and give *that* path as MAILX_FILENAME_TEMPORARY, clean it up once
932 * TODO the pipe returns? Like this we *can* verify path/name issues! */
933 cp = getrandstring(n_MIN(NAME_MAX / 4, 16));
934 scfp->cf_env[0] = str_concat_csvl(&s,
935 n_PIPEENV_FILENAME_GENERATED, "=", cp, NULL)->s;
936 /* v15 compat NAIL_ environments vanish! */
937 scfp->cf_env[1] = str_concat_csvl(&s,
938 "NAIL_FILENAME_GENERATED", "=", cp, NULL)->s;
939 scfp->cf_env[2] = NULL;
940 NYD2_LEAVE;
943 static sigjmp_buf __spam_cf_actjmp; /* TODO someday, we won't need it */
944 static int volatile __spam_cf_sig; /* TODO someday, we won't need it */
945 static void
946 __spam_cf_onsig(int sig) /* TODO someday, we won't need it no more */
948 NYD_X; /* Signal handler */
949 __spam_cf_sig = sig;
950 siglongjmp(__spam_cf_actjmp, 1);
953 static bool_t
954 _spam_cf_interact(struct spam_vc *vcp)
956 struct spam_cf *scfp;
957 int p2c[2], c2p[2];
958 sigset_t cset;
959 char const *cp;
960 size_t size;
961 pid_t volatile pid;
962 enum {
963 _NONE = 0,
964 _SIGHOLD = 1<<0,
965 _P2C_0 = 1<<1,
966 _P2C_1 = 1<<2,
967 _P2C = _P2C_0 | _P2C_1,
968 _C2P_0 = 1<<3,
969 _C2P_1 = 1<<4,
970 _C2P = _C2P_0 | _C2P_1,
971 _JUMPED = 1<<5,
972 _RUNNING = 1<<6,
973 _GOODRUN = 1<<7,
974 _ERRORS = 1<<8
975 } volatile state = _NONE;
976 NYD2_ENTER;
978 scfp = &vcp->vc_t.cf;
979 if (scfp->cf_result != NULL) {
980 free(scfp->cf_result);
981 scfp->cf_result = NULL;
984 /* TODO Avoid that we jump away; yet necessary signal mess */
985 /*__spam_cf_sig = 0;*/
986 hold_sigs();
987 state |= _SIGHOLD;
988 scfp->cf_otstp = safe_signal(SIGTSTP, SIG_DFL);
989 scfp->cf_ottin = safe_signal(SIGTTIN, SIG_DFL);
990 scfp->cf_ottou = safe_signal(SIGTTOU, SIG_DFL);
991 scfp->cf_opipe = safe_signal(SIGPIPE, SIG_IGN);
992 scfp->cf_ohup = safe_signal(SIGHUP, &__spam_cf_onsig);
993 scfp->cf_oint = safe_signal(SIGINT, &__spam_cf_onsig);
994 scfp->cf_oquit = safe_signal(SIGQUIT, &__spam_cf_onsig);
995 /* Keep sigs blocked */
996 pid = 0; /* cc uninit */
998 if (!pipe_cloexec(p2c)) {
999 n_err(_("%s`%s': cannot create parent pipe: %s\n"),
1000 vcp->vc_esep, _spam_cmds[vcp->vc_action], strerror(errno));
1001 goto jtail;
1003 state |= _P2C;
1005 if (!pipe_cloexec(c2p)) {
1006 n_err(_("%s`%s': cannot create child pipe: %s\n"),
1007 vcp->vc_esep, _spam_cmds[vcp->vc_action], strerror(errno));
1008 goto jtail;
1010 state |= _C2P;
1012 if (sigsetjmp(__spam_cf_actjmp, 1)) {
1013 if (*vcp->vc_esep != '\0')
1014 n_err(vcp->vc_esep);
1015 state |= _JUMPED;
1016 goto jtail;
1018 rele_sigs();
1019 state &= ~_SIGHOLD;
1021 /* Start our command as requested */
1022 sigemptyset(&cset);
1023 if ((pid = start_command(
1024 (scfp->cf_acmd != NULL ? scfp->cf_acmd : scfp->cf_cmd),
1025 &cset, p2c[0], c2p[1],
1026 scfp->cf_a0, (scfp->cf_acmd != NULL ? scfp->cf_cmd : NULL), NULL,
1027 scfp->cf_env)) < 0) {
1028 state |= _ERRORS;
1029 goto jtail;
1031 state |= _RUNNING;
1032 close(p2c[0]);
1033 state &= ~_P2C_0;
1035 /* Yes, we could sendmp(SEND_MBOX), but simply passing through the MBOX
1036 * content does the same in effect, however much more efficiently.
1037 * XXX NOTE: this may mean we pass a message without From_ line! */
1038 for (size = vcp->vc_mp->m_size; size > 0;) {
1039 size_t i;
1041 i = fread(vcp->vc_buffer, 1, n_MIN(size, BUFFER_SIZE), vcp->vc_ifp);
1042 if (i == 0) {
1043 if (ferror(vcp->vc_ifp))
1044 state |= _ERRORS;
1045 break;
1047 size -= i;
1048 if (i != (size_t)write(p2c[1], vcp->vc_buffer, i)) {
1049 state |= _ERRORS;
1050 break;
1054 jtail:
1055 /* TODO Quite racy -- block anything for a while? */
1056 if (state & _SIGHOLD) {
1057 state &= ~_SIGHOLD;
1058 rele_sigs();
1061 if (state & _P2C_0) {
1062 state &= ~_P2C_0;
1063 close(p2c[0]);
1065 if (state & _C2P_1) {
1066 state &= ~_C2P_1;
1067 close(c2p[1]);
1069 /* And cause EOF for the reader */
1070 if (state & _P2C_1) {
1071 state &= ~_P2C_1;
1072 close(p2c[1]);
1075 if (state & _RUNNING) {
1076 if (!(state & _ERRORS) &&
1077 vcp->vc_action == _SPAM_RATE && !(state & (_JUMPED | _ERRORS))) {
1078 ssize_t i = read(c2p[0], vcp->vc_buffer, BUFFER_SIZE - 1);
1079 if (i > 0) {
1080 vcp->vc_buffer[i] = '\0';
1081 if ((cp = strchr(vcp->vc_buffer, NETNL[0])) == NULL &&
1082 (cp = strchr(vcp->vc_buffer, NETNL[1])) == NULL) {
1083 n_err(_("%s`%s': program generates too much output: %s\n"),
1084 vcp->vc_esep, _spam_cmds[vcp->vc_action],
1085 n_shexp_quote_cp(scfp->cf_cmd, FAL0));
1086 state |= _ERRORS;
1087 } else {
1088 scfp->cf_result = sbufdup(vcp->vc_buffer,
1089 PTR2SIZE(cp - vcp->vc_buffer));
1090 /* FIXME consume child output until EOF??? */
1092 } else if (i != 0)
1093 state |= _ERRORS;
1096 state &= ~_RUNNING;
1097 wait_child(pid, &scfp->cf_waitstat);
1098 if (WIFEXITED(scfp->cf_waitstat))
1099 state |= _GOODRUN;
1102 if (state & _C2P_0) {
1103 state &= ~_C2P_0;
1104 close(c2p[0]);
1107 safe_signal(SIGQUIT, scfp->cf_oquit);
1108 safe_signal(SIGINT, scfp->cf_oint);
1109 safe_signal(SIGHUP, scfp->cf_ohup);
1110 safe_signal(SIGPIPE, scfp->cf_opipe);
1111 safe_signal(SIGTSTP, scfp->cf_otstp);
1112 safe_signal(SIGTTIN, scfp->cf_ottin);
1113 safe_signal(SIGTTOU, scfp->cf_ottou);
1115 NYD2_LEAVE;
1116 if (state & _JUMPED) {
1117 assert(vcp->vc_dtor != NULL);
1118 (*vcp->vc_dtor)(vcp);
1120 sigemptyset(&cset);
1121 sigaddset(&cset, __spam_cf_sig);
1122 sigprocmask(SIG_UNBLOCK, &cset, NULL);
1123 n_raise(__spam_cf_sig);
1125 return !(state & (_JUMPED | _ERRORS));
1127 #endif /* HAVE_SPAM_SPAMC || HAVE_SPAM_FILTER */
1129 #if defined HAVE_SPAM_SPAMC || defined HAVE_SPAM_SPAMD ||\
1130 (defined HAVE_SPAM_FILTER && defined HAVE_REGEX)
1131 static void
1132 _spam_rate2score(struct spam_vc *vcp, char *buf){
1133 ui32_t m, s;
1134 enum n_idec_state ids;
1135 NYD2_ENTER;
1137 /* C99 */{ /* Overcome ISO C / compiler weirdness */
1138 char const *cp;
1140 cp = buf;
1141 ids = n_idec_ui32_cp(&m, buf, 10, &cp);
1142 if((ids & n_IDEC_STATE_EMASK) & ~n_IDEC_STATE_EBASE)
1143 goto jleave;
1144 buf = n_UNCONST(cp);
1147 s = 0;
1148 if(!(ids & n_IDEC_STATE_CONSUMED)){
1149 /* Floating-point rounding for non-mathematicians */
1150 char c1, c2, c3;
1152 ++buf; /* '.' */
1153 if((c1 = buf[0]) != '\0' && (c2 = buf[1]) != '\0' &&
1154 (c3 = buf[2]) != '\0'){
1155 buf[2] = '\0';
1156 if(c3 >= '5'){
1157 if(c2 == '9'){
1158 if(c1 == '9'){
1159 ++m;
1160 goto jscore_ok;
1161 }else
1162 buf[0] = ++c1;
1163 c2 = '0';
1164 }else
1165 ++c2;
1166 buf[1] = c2;
1170 ids = n_idec_ui32_cp(&s, buf, 10, NULL);
1171 if((ids & (n_IDEC_STATE_EMASK | n_IDEC_STATE_CONSUMED)
1172 ) != n_IDEC_STATE_CONSUMED)
1173 goto jleave;
1176 jscore_ok:
1177 vcp->vc_mp->m_spamscore = (m << 8) | s;
1178 jleave:
1179 NYD2_LEAVE;
1181 #endif /* _SPAM_SPAMC || _SPAM_SPAMD || (_SPAM_FILTER && HAVE_REGEX) */
1183 FL int
1184 c_spam_clear(void *v)
1186 int *ip;
1187 NYD_ENTER;
1189 for (ip = v; *ip != 0; ++ip)
1190 message[(size_t)*ip - 1].m_flag &= ~(MSPAM | MSPAMUNSURE);
1191 NYD_LEAVE;
1192 return 0;
1195 FL int
1196 c_spam_set(void *v)
1198 int *ip;
1199 NYD_ENTER;
1201 for (ip = v; *ip != 0; ++ip) {
1202 message[(size_t)*ip - 1].m_flag &= ~(MSPAM | MSPAMUNSURE);
1203 message[(size_t)*ip - 1].m_flag |= MSPAM;
1205 NYD_LEAVE;
1206 return 0;
1209 FL int
1210 c_spam_forget(void *v)
1212 int rv;
1213 NYD_ENTER;
1215 rv = _spam_action(_SPAM_FORGET, (int*)v) ? OKAY : STOP;
1216 NYD_LEAVE;
1217 return rv;
1220 FL int
1221 c_spam_ham(void *v)
1223 int rv;
1224 NYD_ENTER;
1226 rv = _spam_action(_SPAM_HAM, (int*)v) ? OKAY : STOP;
1227 NYD_LEAVE;
1228 return rv;
1231 FL int
1232 c_spam_rate(void *v)
1234 int rv;
1235 NYD_ENTER;
1237 rv = _spam_action(_SPAM_RATE, (int*)v) ? OKAY : STOP;
1238 NYD_LEAVE;
1239 return rv;
1242 FL int
1243 c_spam_spam(void *v)
1245 int rv;
1246 NYD_ENTER;
1248 rv = _spam_action(_SPAM_SPAM, (int*)v) ? OKAY : STOP;
1249 NYD_LEAVE;
1250 return rv;
1252 #endif /* HAVE_SPAM */
1254 /* s-it-mode */