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 = NULL;
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;
38 spamd->priority = SPAMD_PRIORITY;
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;
143 /* speedup, if we have only 1 server */
144 if (num_servers == 1)
145 return (spamds[0]->is_failed ? -1 : 0);
147 /* scan for highest pri */
148 for (pri = 0, i = 0; i < num_servers; i++)
151 if (!sd->is_failed && sd->priority > pri) pri = sd->priority;
154 /* get sum of weights */
155 for (weights = 0, i = 0; i < num_servers; i++)
158 if (!sd->is_failed && sd->priority == pri) weights += sd->weight;
160 if (weights == 0) /* all servers failed */
163 for (long rnd = random_number(weights), i = 0; i < num_servers; i++)
166 if (!sd->is_failed && sd->priority == pri)
167 if ((rnd -= sd->weight) < 0)
171 log_write(0, LOG_MAIN|LOG_PANIC,
172 "%s unknown error (memory/cpu corruption?)", loglabel);
178 spam(const uschar **listptr)
181 const uschar *list = *listptr;
183 unsigned long mbox_size;
185 client_conn_ctx spamd_cctx = {.sock = -1};
186 uschar spamd_buffer[32600];
187 int i, j, offset, result;
188 uschar spamd_version[8];
189 uschar spamd_short_result[8];
190 uschar spamd_score_char;
191 double spamd_threshold, spamd_score, spamd_reject_score;
192 int spamd_report_offset;
198 struct pollfd pollfd;
199 #else /* Patch posted by Erik ? for OS X */
200 struct timeval select_tv; /* and applied by PH */
203 uschar *spamd_address_work;
204 spamd_address_container * sd;
206 /* stop compiler warning */
209 /* find the username from the option list */
210 if (!(user_name = string_nextinlist(&list, &sep, NULL, 0)))
212 /* no username given, this means no scanning should be done */
216 /* if username is "0" or "false", do not scan */
217 if (Ustrcmp(user_name, "0") == 0 || strcmpic(user_name, US"false") == 0)
220 /* if there is an additional option, check if it is "true" */
221 if (strcmpic(list,US"true") == 0)
222 /* in that case, always return true later */
225 /* expand spamd_address if needed */
226 if (*spamd_address != '$')
227 spamd_address_work = spamd_address;
228 else if (!(spamd_address_work = expand_string(spamd_address)))
230 log_write(0, LOG_MAIN|LOG_PANIC,
231 "%s spamd_address starts with $, but expansion failed: %s",
232 loglabel, expand_string_message);
236 DEBUG(D_acl) debug_printf_indent("spamd: addrlist '%s'\n", spamd_address_work);
238 /* check if previous spamd_address was expanded and has changed. dump cached results if so */
240 && prev_spamd_address_work != NULL
241 && Ustrcmp(prev_spamd_address_work, spamd_address_work) != 0
245 /* if we scanned for this username last time, just return */
246 if (spam_ok && Ustrcmp(prev_user_name, user_name) == 0)
247 return override ? OK : spam_rc;
249 /* make sure the eml mbox file is spooled up */
251 if (!(mbox_file = spool_mbox(&mbox_size, NULL, NULL)))
252 { /* error while spooling */
253 log_write(0, LOG_MAIN|LOG_PANIC,
254 "%s error while creating mbox spool file", loglabel);
264 const uschar * spamd_address_list_ptr = spamd_address_work;
265 spamd_address_container * spamd_address_vector[32];
267 /* Check how many spamd servers we have
268 and register their addresses */
269 sep = 0; /* default colon-sep */
270 while ((address = string_nextinlist(&spamd_address_list_ptr, &sep, NULL, 0)))
272 const uschar * sublist;
273 int sublist_sep = -(int)' '; /* default space-sep */
277 DEBUG(D_acl) debug_printf_indent("spamd: addr entry '%s'\n", address);
278 sd = store_get(sizeof(spamd_address_container), FALSE);
280 for (sublist = address, args = 0, spamd_param_init(sd);
281 (s = string_nextinlist(&sublist, &sublist_sep, NULL, 0));
285 DEBUG(D_acl) debug_printf_indent("spamd: addr parm '%s'\n", s);
288 case 0: sd->hostspec = s;
289 if (*s == '/') args++; /* local; no port */
291 case 1: sd->hostspec = string_sprintf("%s %s", sd->hostspec, s);
293 default: spamd_param(s, sd);
299 log_write(0, LOG_MAIN,
300 "%s warning - invalid spamd address: '%s'", loglabel, address);
304 spamd_address_vector[num_servers] = sd;
305 if (++num_servers > 31)
309 /* check if we have at least one server */
312 log_write(0, LOG_MAIN|LOG_PANIC,
313 "%s no useable spamd server addresses in spamd_address configuration option.",
318 current_server = spamd_get_server(spamd_address_vector, num_servers);
319 sd = spamd_address_vector[current_server];
324 DEBUG(D_acl) debug_printf_indent("spamd: trying server %s\n", sd->hostspec);
328 /*XXX could potentially use TFO early-data here */
329 if ( (spamd_cctx.sock = ip_streamsocket(sd->hostspec, &errstr, 5, NULL)) >= 0
333 DEBUG(D_acl) debug_printf_indent("spamd: server %s: retry conn\n", sd->hostspec);
334 while (sd->retry > 0) sd->retry = sleep(sd->retry);
336 if (spamd_cctx.sock >= 0)
339 log_write(0, LOG_MAIN, "%s spamd: %s", loglabel, errstr);
340 sd->is_failed = TRUE;
342 current_server = spamd_get_server(spamd_address_vector, num_servers);
343 if (current_server < 0)
345 log_write(0, LOG_MAIN|LOG_PANIC, "%s all spamd servers failed", loglabel);
348 sd = spamd_address_vector[current_server];
352 (void)fcntl(spamd_cctx.sock, F_SETFL, O_NONBLOCK);
353 /* now we are connected to spamd on spamd_cctx.sock */
359 req_str = string_append(NULL, 8,
360 "CHECK RSPAMC/1.3\r\nContent-length: ", string_sprintf("%lu\r\n", mbox_size),
361 "Queue-Id: ", message_id,
362 "\r\nFrom: <", sender_address,
363 ">\r\nRecipient-Number: ", string_sprintf("%d\r\n", recipients_count));
365 for (int i = 0; i < recipients_count; i++)
366 req_str = string_append(req_str, 3,
367 "Rcpt: <", recipients_list[i].address, ">\r\n");
368 if ((s = expand_string(US"$sender_helo_name")) && *s)
369 req_str = string_append(req_str, 3, "Helo: ", s, "\r\n");
370 if ((s = expand_string(US"$sender_host_name")) && *s)
371 req_str = string_append(req_str, 3, "Hostname: ", s, "\r\n");
372 if (sender_host_address)
373 req_str = string_append(req_str, 3, "IP: ", sender_host_address, "\r\n");
374 if ((s = expand_string(US"$authenticated_id")) && *s)
375 req_str = string_append(req_str, 3, "User: ", s, "\r\n");
376 req_str = string_catn(req_str, US"\r\n", 2);
377 wrote = send(spamd_cctx.sock, req_str->s, req_str->ptr, 0);
380 { /* spamassassin variant */
382 uschar * s = string_sprintf(
383 "REPORT SPAMC/1.2\r\nUser: %s\r\nContent-length: %ld\r\n\r\n%n",
384 user_name, mbox_size, &n);
385 /* send our request */
386 wrote = send(spamd_cctx.sock, s, n, 0);
391 (void)close(spamd_cctx.sock);
392 log_write(0, LOG_MAIN|LOG_PANIC,
393 "%s spamd %s send failed: %s", loglabel, callout_address, strerror(errno));
397 /* now send the file */
398 /* spamd sometimes accepts connections but doesn't read data off
399 * the connection. We make the file descriptor non-blocking so
400 * that the write will only write sufficient data without blocking
401 * and we poll the descriptor to make sure that we can write without
402 * blocking. Short writes are gracefully handled and if the whole
403 * transaction takes too long it is aborted.
404 * Note: poll() is not supported in OSX 10.2 and is reported to be
405 * broken in more recent versions (up to 10.4).
408 pollfd.fd = spamd_cctx.sock;
409 pollfd.events = POLLOUT;
411 (void)fcntl(spamd_cctx.sock, F_SETFL, O_NONBLOCK);
414 read = fread(spamd_buffer,1,sizeof(spamd_buffer),mbox_file);
420 result = poll(&pollfd, 1, 1000);
422 /* Patch posted by Erik ? for OS X and applied by PH */
424 select_tv.tv_sec = 1;
425 select_tv.tv_usec = 0;
427 FD_SET(spamd_cctx.sock, &select_fd);
428 result = select(spamd_cctx.sock+1, NULL, &select_fd, NULL, &select_tv);
430 /* End Erik's patch */
432 if (result == -1 && errno == EINTR)
437 log_write(0, LOG_MAIN|LOG_PANIC,
438 "%s %s on spamd %s socket", loglabel, callout_address, strerror(errno));
441 if (time(NULL) - start < sd->timeout)
443 log_write(0, LOG_MAIN|LOG_PANIC,
444 "%s timed out writing spamd %s, socket", loglabel, callout_address);
446 (void)close(spamd_cctx.sock);
450 wrote = send(spamd_cctx.sock,spamd_buffer + offset,read - offset,0);
453 log_write(0, LOG_MAIN|LOG_PANIC,
454 "%s %s on spamd %s socket", loglabel, callout_address, strerror(errno));
455 (void)close(spamd_cctx.sock);
458 if (offset + wrote != read)
465 while (!feof(mbox_file) && !ferror(mbox_file));
467 if (ferror(mbox_file))
469 log_write(0, LOG_MAIN|LOG_PANIC,
470 "%s error reading spool file: %s", loglabel, strerror(errno));
471 (void)close(spamd_cctx.sock);
475 (void)fclose(mbox_file);
477 /* we're done sending, close socket for writing */
479 shutdown(spamd_cctx.sock,SHUT_WR);
481 /* read spamd response using what's left of the timeout. */
482 memset(spamd_buffer, 0, sizeof(spamd_buffer));
484 while ((i = ip_recv(&spamd_cctx,
485 spamd_buffer + offset,
486 sizeof(spamd_buffer) - offset - 1,
487 sd->timeout + start)) > 0)
489 spamd_buffer[offset] = '\0'; /* guard byte */
492 if (i <= 0 && errno != 0)
494 log_write(0, LOG_MAIN|LOG_PANIC,
495 "%s error reading from spamd %s, socket: %s", loglabel, callout_address, strerror(errno));
496 (void)close(spamd_cctx.sock);
501 (void)close(spamd_cctx.sock);
504 { /* rspamd variant of reply */
506 if ( (r = sscanf(CS spamd_buffer,
507 "RSPAMD/%7s 0 EX_OK\r\nMetric: default; %7s %lf / %lf / %lf\r\n%n",
508 spamd_version, spamd_short_result, &spamd_score, &spamd_threshold,
509 &spamd_reject_score, &spamd_report_offset)) != 5
510 || spamd_report_offset >= offset /* verify within buffer */
513 log_write(0, LOG_MAIN|LOG_PANIC,
514 "%s cannot parse spamd %s, output: %d", loglabel, callout_address, r);
517 /* now parse action */
518 p = &spamd_buffer[spamd_report_offset];
520 if (Ustrncmp(p, "Action: ", sizeof("Action: ") - 1) == 0)
522 p += sizeof("Action: ") - 1;
523 q = &spam_action_buffer[0];
524 while (*p && *p != '\r' && (q - spam_action_buffer) < sizeof(spam_action_buffer) - 1)
531 /* dig in the spamd output and put the report in a multiline header,
533 if (sscanf(CS spamd_buffer,
534 "SPAMD/%7s 0 EX_OK\r\nContent-length: %*u\r\n\r\n%lf/%lf\r\n%n",
535 spamd_version,&spamd_score,&spamd_threshold,&spamd_report_offset) != 3)
537 /* try to fall back to pre-2.50 spamd output */
538 if (sscanf(CS spamd_buffer,
539 "SPAMD/%7s 0 EX_OK\r\nSpam: %*s ; %lf / %lf\r\n\r\n%n",
540 spamd_version,&spamd_score,&spamd_threshold,&spamd_report_offset) != 3)
542 log_write(0, LOG_MAIN|LOG_PANIC,
543 "%s cannot parse spamd %s output", loglabel, callout_address);
548 Ustrcpy(spam_action_buffer,
549 spamd_score >= spamd_threshold ? US"reject" : US"no action");
552 /* Create report. Since this is a multiline string,
553 we must hack it into shape first */
554 p = &spamd_buffer[spamd_report_offset];
555 q = spam_report_buffer;
567 /* add an extra space after the newline to ensure
568 that it is treated as a header continuation line */
574 /* cut off trailing leftovers */
578 spam_report = spam_report_buffer;
579 spam_action = spam_action_buffer;
581 /* create spam bar */
582 spamd_score_char = spamd_score > 0 ? '+' : '-';
583 j = abs((int)(spamd_score));
586 while ((i < j) && (i <= MAX_SPAM_BAR_CHARS))
587 spam_bar_buffer[i++] = spamd_score_char;
590 spam_bar_buffer[0] = '/';
593 spam_bar_buffer[i] = '\0';
594 spam_bar = spam_bar_buffer;
596 /* create "float" spam score */
597 (void)string_format(spam_score_buffer, sizeof(spam_score_buffer),
598 "%.1f", spamd_score);
599 spam_score = spam_score_buffer;
601 /* create "int" spam score */
602 j = (int)((spamd_score + 0.001)*10);
603 (void)string_format(spam_score_int_buffer, sizeof(spam_score_int_buffer),
605 spam_score_int = spam_score_int_buffer;
607 /* compare threshold against score */
608 spam_rc = spamd_score >= spamd_threshold
609 ? OK /* spam as determined by user's threshold */
610 : FAIL; /* not spam */
612 /* remember expanded spamd_address if needed */
613 if (spamd_address_work != spamd_address)
614 prev_spamd_address_work = string_copy(spamd_address_work);
616 /* remember user name and "been here" for it */
617 prev_user_name = user_name;
621 ? OK /* always return OK, no matter what the score */
625 (void)fclose(mbox_file);