1 /*************************************************
2 * Exim - an Internet mail transport agent *
3 *************************************************/
5 /* Copyright (c) Tom Kistner <tom@duncanthrax.net> 2003 - 2015
7 * Copyright (c) The Exim Maintainers 2016 - 2020
10 /* Code for calling spamassassin's spamd. Called from acl.c. */
13 #ifdef WITH_CONTENT_SCAN
16 uschar spam_score_buffer[16];
17 uschar spam_score_int_buffer[16];
18 uschar spam_bar_buffer[128];
19 uschar spam_action_buffer[32];
20 uschar spam_report_buffer[32600];
21 uschar prev_user_name[128] = "";
24 uschar *prev_spamd_address_work = NULL;
26 static const uschar * loglabel = US"spam acl condition:";
30 spamd_param_init(spamd_address_container *spamd)
32 /* default spamd server weight, time and priority value */
33 spamd->is_rspamd = FALSE;
34 spamd->is_failed = FALSE;
35 spamd->weight = SPAMD_WEIGHT;
36 spamd->timeout = SPAMD_TIMEOUT;
44 spamd_param(const uschar * param, spamd_address_container * spamd)
46 static int timesinceday = -1;
50 /*XXX more clever parsing could discard embedded spaces? */
52 if (sscanf(CCS param, "pri=%u", &spamd->priority))
55 if (sscanf(CCS param, "weight=%u", &spamd->weight))
57 if (spamd->weight == 0) /* this server disabled: skip it */
62 if (Ustrncmp(param, "time=", 5) == 0)
64 unsigned int start_h = 0, start_m = 0, start_s = 0;
65 unsigned int end_h = 24, end_m = 0, end_s = 0;
66 unsigned int time_start, time_end;
67 const uschar * end_string;
71 if ((end_string = Ustrchr(s, '-')))
74 if ( sscanf(CS end_string, "%u.%u.%u", &end_h, &end_m, &end_s) == 0
75 || sscanf(CS s, "%u.%u.%u", &start_h, &start_m, &start_s) == 0
84 time_t now = time(NULL);
85 struct tm *tmp = localtime(&now);
86 timesinceday = tmp->tm_hour*3600 + tmp->tm_min*60 + tmp->tm_sec;
89 time_start = start_h*3600 + start_m*60 + start_s;
90 time_end = end_h*3600 + end_m*60 + end_s;
92 if (timesinceday < time_start || timesinceday >= time_end)
93 return 1; /* skip spamd server */
98 if (Ustrcmp(param, "variant=rspamd") == 0)
100 spamd->is_rspamd = TRUE;
104 if (Ustrncmp(param, "tmo=", 4) == 0)
106 int sec = readconf_readtime((s = param+4), '\0', FALSE);
110 spamd->timeout = sec;
114 if (Ustrncmp(param, "retry=", 6) == 0)
116 int sec = readconf_readtime((s = param+6), '\0', FALSE);
124 log_write(0, LOG_MAIN, "%s warning - invalid spamd parameter: '%s'",
126 return -1; /* syntax error */
129 log_write(0, LOG_MAIN,
130 "%s warning - invalid spamd %s value: '%s'", loglabel, name, s);
131 return -1; /* syntax error */
136 spamd_get_server(spamd_address_container ** spamds, int num_servers)
139 spamd_address_container * sd;
142 static BOOL srandomed = FALSE;
144 /* speedup, if we have only 1 server */
145 if (num_servers == 1)
146 return (spamds[0]->is_failed ? -1 : 0);
152 gettimeofday(&tv, NULL);
153 srandom((unsigned int)(tv.tv_usec/1000));
157 /* scan for highest pri */
158 for (pri = 0, i = 0; i < num_servers; i++)
161 if (!sd->is_failed && sd->priority > pri) pri = sd->priority;
164 /* get sum of weights */
165 for (weights = 0, i = 0; i < num_servers; i++)
168 if (!sd->is_failed && sd->priority == pri) weights += sd->weight;
170 if (weights == 0) /* all servers failed */
173 for (long rnd = random() % weights, i = 0; i < num_servers; i++)
176 if (!sd->is_failed && sd->priority == pri)
177 if ((rnd -= sd->weight) <= 0)
181 log_write(0, LOG_MAIN|LOG_PANIC,
182 "%s unknown error (memory/cpu corruption?)", loglabel);
188 spam(const uschar **listptr)
191 const uschar *list = *listptr;
193 unsigned long mbox_size;
195 client_conn_ctx spamd_cctx = {.sock = -1};
196 uschar spamd_buffer[32600];
197 int i, j, offset, result;
198 uschar spamd_version[8];
199 uschar spamd_short_result[8];
200 uschar spamd_score_char;
201 double spamd_threshold, spamd_score, spamd_reject_score;
202 int spamd_report_offset;
208 struct pollfd pollfd;
209 #else /* Patch posted by Erik ? for OS X */
210 struct timeval select_tv; /* and applied by PH */
213 uschar *spamd_address_work;
214 spamd_address_container * sd;
216 /* stop compiler warning */
219 /* find the username from the option list */
220 if (!(user_name = string_nextinlist(&list, &sep, NULL, 0)))
222 /* no username given, this means no scanning should be done */
226 /* if username is "0" or "false", do not scan */
227 if (Ustrcmp(user_name, "0") == 0 || strcmpic(user_name, US"false") == 0)
230 /* if there is an additional option, check if it is "true" */
231 if (strcmpic(list,US"true") == 0)
232 /* in that case, always return true later */
235 /* expand spamd_address if needed */
236 if (*spamd_address != '$')
237 spamd_address_work = spamd_address;
238 else if (!(spamd_address_work = expand_string(spamd_address)))
240 log_write(0, LOG_MAIN|LOG_PANIC,
241 "%s spamd_address starts with $, but expansion failed: %s",
242 loglabel, expand_string_message);
246 DEBUG(D_acl) debug_printf_indent("spamd: addrlist '%s'\n", spamd_address_work);
248 /* check if previous spamd_address was expanded and has changed. dump cached results if so */
250 && prev_spamd_address_work != NULL
251 && Ustrcmp(prev_spamd_address_work, spamd_address_work) != 0
255 /* if we scanned for this username last time, just return */
256 if (spam_ok && Ustrcmp(prev_user_name, user_name) == 0)
257 return override ? OK : spam_rc;
259 /* make sure the eml mbox file is spooled up */
261 if (!(mbox_file = spool_mbox(&mbox_size, NULL, NULL)))
262 { /* error while spooling */
263 log_write(0, LOG_MAIN|LOG_PANIC,
264 "%s error while creating mbox spool file", loglabel);
274 const uschar * spamd_address_list_ptr = spamd_address_work;
275 spamd_address_container * spamd_address_vector[32];
277 /* Check how many spamd servers we have
278 and register their addresses */
279 sep = 0; /* default colon-sep */
280 while ((address = string_nextinlist(&spamd_address_list_ptr, &sep, NULL, 0)))
282 const uschar * sublist;
283 int sublist_sep = -(int)' '; /* default space-sep */
287 DEBUG(D_acl) debug_printf_indent("spamd: addr entry '%s'\n", address);
288 sd = store_get(sizeof(spamd_address_container), FALSE);
290 for (sublist = address, args = 0, spamd_param_init(sd);
291 (s = string_nextinlist(&sublist, &sublist_sep, NULL, 0));
295 DEBUG(D_acl) debug_printf_indent("spamd: addr parm '%s'\n", s);
298 case 0: sd->hostspec = s;
299 if (*s == '/') args++; /* local; no port */
301 case 1: sd->hostspec = string_sprintf("%s %s", sd->hostspec, s);
303 default: spamd_param(s, sd);
309 log_write(0, LOG_MAIN,
310 "%s warning - invalid spamd address: '%s'", loglabel, address);
314 spamd_address_vector[num_servers] = sd;
315 if (++num_servers > 31)
319 /* check if we have at least one server */
322 log_write(0, LOG_MAIN|LOG_PANIC,
323 "%s no useable spamd server addresses in spamd_address configuration option.",
328 current_server = spamd_get_server(spamd_address_vector, num_servers);
329 sd = spamd_address_vector[current_server];
334 DEBUG(D_acl) debug_printf_indent("spamd: trying server %s\n", sd->hostspec);
338 /*XXX could potentially use TFO early-data here */
339 if ( (spamd_cctx.sock = ip_streamsocket(sd->hostspec, &errstr, 5, NULL)) >= 0
343 DEBUG(D_acl) debug_printf_indent("spamd: server %s: retry conn\n", sd->hostspec);
344 while (sd->retry > 0) sd->retry = sleep(sd->retry);
346 if (spamd_cctx.sock >= 0)
349 log_write(0, LOG_MAIN, "%s spamd: %s", loglabel, errstr);
350 sd->is_failed = TRUE;
352 current_server = spamd_get_server(spamd_address_vector, num_servers);
353 if (current_server < 0)
355 log_write(0, LOG_MAIN|LOG_PANIC, "%s all spamd servers failed", loglabel);
358 sd = spamd_address_vector[current_server];
362 (void)fcntl(spamd_cctx.sock, F_SETFL, O_NONBLOCK);
363 /* now we are connected to spamd on spamd_cctx.sock */
369 req_str = string_append(NULL, 8,
370 "CHECK RSPAMC/1.3\r\nContent-length: ", string_sprintf("%lu\r\n", mbox_size),
371 "Queue-Id: ", message_id,
372 "\r\nFrom: <", sender_address,
373 ">\r\nRecipient-Number: ", string_sprintf("%d\r\n", recipients_count));
375 for (int i = 0; i < recipients_count; i++)
376 req_str = string_append(req_str, 3,
377 "Rcpt: <", recipients_list[i].address, ">\r\n");
378 if ((s = expand_string(US"$sender_helo_name")) && *s)
379 req_str = string_append(req_str, 3, "Helo: ", s, "\r\n");
380 if ((s = expand_string(US"$sender_host_name")) && *s)
381 req_str = string_append(req_str, 3, "Hostname: ", s, "\r\n");
382 if (sender_host_address)
383 req_str = string_append(req_str, 3, "IP: ", sender_host_address, "\r\n");
384 if ((s = expand_string(US"$authenticated_id")) && *s)
385 req_str = string_append(req_str, 3, "User: ", s, "\r\n");
386 req_str = string_catn(req_str, US"\r\n", 2);
387 wrote = send(spamd_cctx.sock, req_str->s, req_str->ptr, 0);
390 { /* spamassassin variant */
391 (void)string_format(spamd_buffer,
392 sizeof(spamd_buffer),
393 "REPORT SPAMC/1.2\r\nUser: %s\r\nContent-length: %ld\r\n\r\n",
396 /* send our request */
397 wrote = send(spamd_cctx.sock, spamd_buffer, Ustrlen(spamd_buffer), 0);
402 (void)close(spamd_cctx.sock);
403 log_write(0, LOG_MAIN|LOG_PANIC,
404 "%s spamd %s send failed: %s", loglabel, callout_address, strerror(errno));
408 /* now send the file */
409 /* spamd sometimes accepts connections but doesn't read data off
410 * the connection. We make the file descriptor non-blocking so
411 * that the write will only write sufficient data without blocking
412 * and we poll the descriptor to make sure that we can write without
413 * blocking. Short writes are gracefully handled and if the whole
414 * transaction takes too long it is aborted.
415 * Note: poll() is not supported in OSX 10.2 and is reported to be
416 * broken in more recent versions (up to 10.4).
419 pollfd.fd = spamd_cctx.sock;
420 pollfd.events = POLLOUT;
422 (void)fcntl(spamd_cctx.sock, F_SETFL, O_NONBLOCK);
425 read = fread(spamd_buffer,1,sizeof(spamd_buffer),mbox_file);
431 result = poll(&pollfd, 1, 1000);
433 /* Patch posted by Erik ? for OS X and applied by PH */
435 select_tv.tv_sec = 1;
436 select_tv.tv_usec = 0;
438 FD_SET(spamd_cctx.sock, &select_fd);
439 result = select(spamd_cctx.sock+1, NULL, &select_fd, NULL, &select_tv);
441 /* End Erik's patch */
443 if (result == -1 && errno == EINTR)
448 log_write(0, LOG_MAIN|LOG_PANIC,
449 "%s %s on spamd %s socket", loglabel, callout_address, strerror(errno));
452 if (time(NULL) - start < sd->timeout)
454 log_write(0, LOG_MAIN|LOG_PANIC,
455 "%s timed out writing spamd %s, socket", loglabel, callout_address);
457 (void)close(spamd_cctx.sock);
461 wrote = send(spamd_cctx.sock,spamd_buffer + offset,read - offset,0);
464 log_write(0, LOG_MAIN|LOG_PANIC,
465 "%s %s on spamd %s socket", loglabel, callout_address, strerror(errno));
466 (void)close(spamd_cctx.sock);
469 if (offset + wrote != read)
476 while (!feof(mbox_file) && !ferror(mbox_file));
478 if (ferror(mbox_file))
480 log_write(0, LOG_MAIN|LOG_PANIC,
481 "%s error reading spool file: %s", loglabel, strerror(errno));
482 (void)close(spamd_cctx.sock);
486 (void)fclose(mbox_file);
488 /* we're done sending, close socket for writing */
490 shutdown(spamd_cctx.sock,SHUT_WR);
492 /* read spamd response using what's left of the timeout. */
493 memset(spamd_buffer, 0, sizeof(spamd_buffer));
495 while ((i = ip_recv(&spamd_cctx,
496 spamd_buffer + offset,
497 sizeof(spamd_buffer) - offset - 1,
498 sd->timeout + start)) > 0)
500 spamd_buffer[offset] = '\0'; /* guard byte */
503 if (i <= 0 && errno != 0)
505 log_write(0, LOG_MAIN|LOG_PANIC,
506 "%s error reading from spamd %s, socket: %s", loglabel, callout_address, strerror(errno));
507 (void)close(spamd_cctx.sock);
512 (void)close(spamd_cctx.sock);
515 { /* rspamd variant of reply */
517 if ( (r = sscanf(CS spamd_buffer,
518 "RSPAMD/%7s 0 EX_OK\r\nMetric: default; %7s %lf / %lf / %lf\r\n%n",
519 spamd_version, spamd_short_result, &spamd_score, &spamd_threshold,
520 &spamd_reject_score, &spamd_report_offset)) != 5
521 || spamd_report_offset >= offset /* verify within buffer */
524 log_write(0, LOG_MAIN|LOG_PANIC,
525 "%s cannot parse spamd %s, output: %d", loglabel, callout_address, r);
528 /* now parse action */
529 p = &spamd_buffer[spamd_report_offset];
531 if (Ustrncmp(p, "Action: ", sizeof("Action: ") - 1) == 0)
533 p += sizeof("Action: ") - 1;
534 q = &spam_action_buffer[0];
535 while (*p && *p != '\r' && (q - spam_action_buffer) < sizeof(spam_action_buffer) - 1)
542 /* dig in the spamd output and put the report in a multiline header,
544 if (sscanf(CS spamd_buffer,
545 "SPAMD/%7s 0 EX_OK\r\nContent-length: %*u\r\n\r\n%lf/%lf\r\n%n",
546 spamd_version,&spamd_score,&spamd_threshold,&spamd_report_offset) != 3)
548 /* try to fall back to pre-2.50 spamd output */
549 if (sscanf(CS spamd_buffer,
550 "SPAMD/%7s 0 EX_OK\r\nSpam: %*s ; %lf / %lf\r\n\r\n%n",
551 spamd_version,&spamd_score,&spamd_threshold,&spamd_report_offset) != 3)
553 log_write(0, LOG_MAIN|LOG_PANIC,
554 "%s cannot parse spamd %s output", loglabel, callout_address);
559 Ustrcpy(spam_action_buffer,
560 spamd_score >= spamd_threshold ? US"reject" : US"no action");
563 /* Create report. Since this is a multiline string,
564 we must hack it into shape first */
565 p = &spamd_buffer[spamd_report_offset];
566 q = spam_report_buffer;
578 /* add an extra space after the newline to ensure
579 that it is treated as a header continuation line */
585 /* cut off trailing leftovers */
589 spam_report = spam_report_buffer;
590 spam_action = spam_action_buffer;
592 /* create spam bar */
593 spamd_score_char = spamd_score > 0 ? '+' : '-';
594 j = abs((int)(spamd_score));
597 while ((i < j) && (i <= MAX_SPAM_BAR_CHARS))
598 spam_bar_buffer[i++] = spamd_score_char;
601 spam_bar_buffer[0] = '/';
604 spam_bar_buffer[i] = '\0';
605 spam_bar = spam_bar_buffer;
607 /* create "float" spam score */
608 (void)string_format(spam_score_buffer, sizeof(spam_score_buffer),
609 "%.1f", spamd_score);
610 spam_score = spam_score_buffer;
612 /* create "int" spam score */
613 j = (int)((spamd_score + 0.001)*10);
614 (void)string_format(spam_score_int_buffer, sizeof(spam_score_int_buffer),
616 spam_score_int = spam_score_int_buffer;
618 /* compare threshold against score */
619 spam_rc = spamd_score >= spamd_threshold
620 ? OK /* spam as determined by user's threshold */
621 : FAIL; /* not spam */
623 /* remember expanded spamd_address if needed */
624 if (spamd_address_work != spamd_address)
625 prev_spamd_address_work = string_copy(spamd_address_work);
627 /* remember user name and "been here" for it */
628 Ustrcpy(prev_user_name, user_name);
632 ? OK /* always return OK, no matter what the score */
636 (void)fclose(mbox_file);