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 - 2018
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_failed = FALSE;
34 spamd->weight = SPAMD_WEIGHT;
35 spamd->timeout = SPAMD_TIMEOUT;
43 spamd_param(const uschar * param, spamd_address_container * spamd)
45 static int timesinceday = -1;
49 /*XXX more clever parsing could discard embedded spaces? */
51 if (sscanf(CCS param, "pri=%u", &spamd->priority))
54 if (sscanf(CCS param, "weight=%u", &spamd->weight))
56 if (spamd->weight == 0) /* this server disabled: skip it */
61 if (Ustrncmp(param, "time=", 5) == 0)
63 unsigned int start_h = 0, start_m = 0, start_s = 0;
64 unsigned int end_h = 24, end_m = 0, end_s = 0;
65 unsigned int time_start, time_end;
66 const uschar * end_string;
70 if ((end_string = Ustrchr(s, '-')))
73 if ( sscanf(CS end_string, "%u.%u.%u", &end_h, &end_m, &end_s) == 0
74 || sscanf(CS s, "%u.%u.%u", &start_h, &start_m, &start_s) == 0
83 time_t now = time(NULL);
84 struct tm *tmp = localtime(&now);
85 timesinceday = tmp->tm_hour*3600 + tmp->tm_min*60 + tmp->tm_sec;
88 time_start = start_h*3600 + start_m*60 + start_s;
89 time_end = end_h*3600 + end_m*60 + end_s;
91 if (timesinceday < time_start || timesinceday >= time_end)
92 return 1; /* skip spamd server */
97 if (Ustrcmp(param, "variant=rspamd") == 0)
99 spamd->is_rspamd = TRUE;
103 if (Ustrncmp(param, "tmo=", 4) == 0)
105 int sec = readconf_readtime((s = param+4), '\0', FALSE);
109 spamd->timeout = sec;
113 if (Ustrncmp(param, "retry=", 6) == 0)
115 int sec = readconf_readtime((s = param+6), '\0', FALSE);
123 log_write(0, LOG_MAIN, "%s warning - invalid spamd parameter: '%s'",
125 return -1; /* syntax error */
128 log_write(0, LOG_MAIN,
129 "%s warning - invalid spamd %s value: '%s'", loglabel, name, s);
130 return -1; /* syntax error */
135 spamd_get_server(spamd_address_container ** spamds, int num_servers)
138 spamd_address_container * sd;
141 static BOOL srandomed = FALSE;
143 /* speedup, if we have only 1 server */
144 if (num_servers == 1)
145 return (spamds[0]->is_failed ? -1 : 0);
151 gettimeofday(&tv, NULL);
152 srandom((unsigned int)(tv.tv_usec/1000));
156 /* scan for highest pri */
157 for (pri = 0, i = 0; i < num_servers; i++)
160 if (!sd->is_failed && sd->priority > pri) pri = sd->priority;
163 /* get sum of weights */
164 for (weights = 0, i = 0; i < num_servers; i++)
167 if (!sd->is_failed && sd->priority == pri) weights += sd->weight;
169 if (weights == 0) /* all servers failed */
172 for (rnd = random() % weights, i = 0; i < num_servers; i++)
175 if (!sd->is_failed && sd->priority == pri)
176 if ((rnd -= sd->weight) <= 0)
180 log_write(0, LOG_MAIN|LOG_PANIC,
181 "%s unknown error (memory/cpu corruption?)", loglabel);
187 spam(const uschar **listptr)
190 const uschar *list = *listptr;
192 uschar user_name_buffer[128];
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,
222 sizeof(user_name_buffer))) == NULL)
224 /* no username given, this means no scanning should be done */
228 /* if username is "0" or "false", do not scan */
229 if ( (Ustrcmp(user_name,"0") == 0) ||
230 (strcmpic(user_name,US"false") == 0) )
233 /* if there is an additional option, check if it is "true" */
234 if (strcmpic(list,US"true") == 0)
235 /* in that case, always return true later */
238 /* expand spamd_address if needed */
239 if (*spamd_address == '$')
241 spamd_address_work = expand_string(spamd_address);
242 if (spamd_address_work == NULL)
244 log_write(0, LOG_MAIN|LOG_PANIC,
245 "%s spamd_address starts with $, but expansion failed: %s",
246 loglabel, expand_string_message);
251 spamd_address_work = spamd_address;
253 DEBUG(D_acl) debug_printf_indent("spamd: addrlist '%s'\n", spamd_address_work);
255 /* check if previous spamd_address was expanded and has changed. dump cached results if so */
257 && prev_spamd_address_work != NULL
258 && Ustrcmp(prev_spamd_address_work, spamd_address_work) != 0
262 /* if we scanned for this username last time, just return */
263 if (spam_ok && Ustrcmp(prev_user_name, user_name) == 0)
264 return override ? OK : spam_rc;
266 /* make sure the eml mbox file is spooled up */
268 if (!(mbox_file = spool_mbox(&mbox_size, NULL, NULL)))
269 { /* error while spooling */
270 log_write(0, LOG_MAIN|LOG_PANIC,
271 "%s error while creating mbox spool file", loglabel);
281 const uschar * spamd_address_list_ptr = spamd_address_work;
282 spamd_address_container * spamd_address_vector[32];
284 /* Check how many spamd servers we have
285 and register their addresses */
286 sep = 0; /* default colon-sep */
287 while ((address = string_nextinlist(&spamd_address_list_ptr, &sep, NULL, 0)))
289 const uschar * sublist;
290 int sublist_sep = -(int)' '; /* default space-sep */
294 DEBUG(D_acl) debug_printf_indent("spamd: addr entry '%s'\n", address);
295 sd = (spamd_address_container *)store_get(sizeof(spamd_address_container));
297 for (sublist = address, args = 0, spamd_param_init(sd);
298 (s = string_nextinlist(&sublist, &sublist_sep, NULL, 0));
302 DEBUG(D_acl) debug_printf_indent("spamd: addr parm '%s'\n", s);
305 case 0: sd->hostspec = s;
306 if (*s == '/') args++; /* local; no port */
308 case 1: sd->hostspec = string_sprintf("%s %s", sd->hostspec, s);
310 default: spamd_param(s, sd);
316 log_write(0, LOG_MAIN,
317 "%s warning - invalid spamd address: '%s'", loglabel, address);
321 spamd_address_vector[num_servers] = sd;
322 if (++num_servers > 31)
326 /* check if we have at least one server */
329 log_write(0, LOG_MAIN|LOG_PANIC,
330 "%s no useable spamd server addresses in spamd_address configuration option.",
335 current_server = spamd_get_server(spamd_address_vector, num_servers);
336 sd = spamd_address_vector[current_server];
341 DEBUG(D_acl) debug_printf_indent("spamd: trying server %s\n", sd->hostspec);
345 /*XXX could potentially use TFO early-data here */
346 if ( (spamd_cctx.sock = ip_streamsocket(sd->hostspec, &errstr, 5)) >= 0
350 DEBUG(D_acl) debug_printf_indent("spamd: server %s: retry conn\n", sd->hostspec);
351 while (sd->retry > 0) sd->retry = sleep(sd->retry);
353 if (spamd_cctx.sock >= 0)
356 log_write(0, LOG_MAIN, "%s spamd: %s", loglabel, errstr);
357 sd->is_failed = TRUE;
359 current_server = spamd_get_server(spamd_address_vector, num_servers);
360 if (current_server < 0)
362 log_write(0, LOG_MAIN|LOG_PANIC, "%s all spamd servers failed", loglabel);
365 sd = spamd_address_vector[current_server];
369 (void)fcntl(spamd_cctx.sock, F_SETFL, O_NONBLOCK);
370 /* now we are connected to spamd on spamd_cctx.sock */
372 { /* rspamd variant */
377 req_str = string_sprintf("CHECK RSPAMC/1.3\r\nContent-length: %lu\r\n"
378 "Queue-Id: %s\r\nFrom: <%s>\r\nRecipient-Number: %d\r\n",
379 mbox_size, message_id, sender_address, recipients_count);
380 for (i = 0; i < recipients_count; i ++)
381 req_str = string_sprintf("%sRcpt: <%s>\r\n", req_str, recipients_list[i].address);
382 if ((helo = expand_string(US"$sender_helo_name")) != NULL && *helo != '\0')
383 req_str = string_sprintf("%sHelo: %s\r\n", req_str, helo);
384 if ((fcrdns = expand_string(US"$sender_host_name")) != NULL && *fcrdns != '\0')
385 req_str = string_sprintf("%sHostname: %s\r\n", req_str, fcrdns);
386 if (sender_host_address != NULL)
387 req_str = string_sprintf("%sIP: %s\r\n", req_str, sender_host_address);
388 req_str = string_sprintf("%s\r\n", req_str);
389 wrote = send(spamd_cctx.sock, req_str->s, req_str->ptr, 0);
392 { /* spamassassin variant */
393 (void)string_format(spamd_buffer,
394 sizeof(spamd_buffer),
395 "REPORT SPAMC/1.2\r\nUser: %s\r\nContent-length: %ld\r\n\r\n",
398 /* send our request */
399 wrote = send(spamd_cctx.sock, spamd_buffer, Ustrlen(spamd_buffer), 0);
403 (void)close(spamd_cctx.sock);
404 log_write(0, LOG_MAIN|LOG_PANIC,
405 "%s spamd %s send failed: %s", loglabel, callout_address, strerror(errno));
409 /* now send the file */
410 /* spamd sometimes accepts connections but doesn't read data off
411 * the connection. We make the file descriptor non-blocking so
412 * that the write will only write sufficient data without blocking
413 * and we poll the descriptor to make sure that we can write without
414 * blocking. Short writes are gracefully handled and if the whole
415 * transaction takes too long it is aborted.
416 * Note: poll() is not supported in OSX 10.2 and is reported to be
417 * broken in more recent versions (up to 10.4).
420 pollfd.fd = spamd_cctx.sock;
421 pollfd.events = POLLOUT;
423 (void)fcntl(spamd_cctx.sock, F_SETFL, O_NONBLOCK);
426 read = fread(spamd_buffer,1,sizeof(spamd_buffer),mbox_file);
432 result = poll(&pollfd, 1, 1000);
434 /* Patch posted by Erik ? for OS X and applied by PH */
436 select_tv.tv_sec = 1;
437 select_tv.tv_usec = 0;
439 FD_SET(spamd_cctx.sock, &select_fd);
440 result = select(spamd_cctx.sock+1, NULL, &select_fd, NULL, &select_tv);
442 /* End Erik's patch */
444 if (result == -1 && errno == EINTR)
449 log_write(0, LOG_MAIN|LOG_PANIC,
450 "%s %s on spamd %s socket", loglabel, callout_address, strerror(errno));
453 if (time(NULL) - start < sd->timeout)
455 log_write(0, LOG_MAIN|LOG_PANIC,
456 "%s timed out writing spamd %s, socket", loglabel, callout_address);
458 (void)close(spamd_cctx.sock);
462 wrote = send(spamd_cctx.sock,spamd_buffer + offset,read - offset,0);
465 log_write(0, LOG_MAIN|LOG_PANIC,
466 "%s %s on spamd %s socket", loglabel, callout_address, strerror(errno));
467 (void)close(spamd_cctx.sock);
470 if (offset + wrote != read)
477 while (!feof(mbox_file) && !ferror(mbox_file));
479 if (ferror(mbox_file))
481 log_write(0, LOG_MAIN|LOG_PANIC,
482 "%s error reading spool file: %s", loglabel, strerror(errno));
483 (void)close(spamd_cctx.sock);
487 (void)fclose(mbox_file);
489 /* we're done sending, close socket for writing */
491 shutdown(spamd_cctx.sock, SHUT_WR);
493 /* read spamd response using what's left of the timeout. */
494 memset(spamd_buffer, 0, sizeof(spamd_buffer));
496 while ((i = ip_recv(&spamd_cctx,
497 spamd_buffer + offset,
498 sizeof(spamd_buffer) - offset - 1,
499 sd->timeout - time(NULL) + start)) > 0)
501 spamd_buffer[offset] = '\0'; /* guard byte */
504 if (i <= 0 && errno != 0)
506 log_write(0, LOG_MAIN|LOG_PANIC,
507 "%s error reading from spamd %s, socket: %s", loglabel, callout_address, strerror(errno));
508 (void)close(spamd_cctx.sock);
513 (void)close(spamd_cctx.sock);
516 { /* rspamd variant of reply */
518 if ( (r = sscanf(CS spamd_buffer,
519 "RSPAMD/%7s 0 EX_OK\r\nMetric: default; %7s %lf / %lf / %lf\r\n%n",
520 spamd_version, spamd_short_result, &spamd_score, &spamd_threshold,
521 &spamd_reject_score, &spamd_report_offset)) != 5
522 || spamd_report_offset >= offset /* verify within buffer */
525 log_write(0, LOG_MAIN|LOG_PANIC,
526 "%s cannot parse spamd %s, output: %d", loglabel, callout_address, r);
529 /* now parse action */
530 p = &spamd_buffer[spamd_report_offset];
532 if (Ustrncmp(p, "Action: ", sizeof("Action: ") - 1) == 0)
534 p += sizeof("Action: ") - 1;
535 q = &spam_action_buffer[0];
536 while (*p && *p != '\r' && (q - spam_action_buffer) < sizeof(spam_action_buffer) - 1)
543 /* dig in the spamd output and put the report in a multiline header,
545 if (sscanf(CS spamd_buffer,
546 "SPAMD/%7s 0 EX_OK\r\nContent-length: %*u\r\n\r\n%lf/%lf\r\n%n",
547 spamd_version,&spamd_score,&spamd_threshold,&spamd_report_offset) != 3)
549 /* try to fall back to pre-2.50 spamd output */
550 if (sscanf(CS spamd_buffer,
551 "SPAMD/%7s 0 EX_OK\r\nSpam: %*s ; %lf / %lf\r\n\r\n%n",
552 spamd_version,&spamd_score,&spamd_threshold,&spamd_report_offset) != 3)
554 log_write(0, LOG_MAIN|LOG_PANIC,
555 "%s cannot parse spamd %s output", loglabel, callout_address);
560 Ustrcpy(spam_action_buffer,
561 spamd_score >= spamd_threshold ? "reject" : "no action");
564 /* Create report. Since this is a multiline string,
565 we must hack it into shape first */
566 p = &spamd_buffer[spamd_report_offset];
567 q = spam_report_buffer;
579 /* add an extra space after the newline to ensure
580 that it is treated as a header continuation line */
586 /* cut off trailing leftovers */
590 spam_report = spam_report_buffer;
591 spam_action = spam_action_buffer;
593 /* create spam bar */
594 spamd_score_char = spamd_score > 0 ? '+' : '-';
595 j = abs((int)(spamd_score));
598 while ((i < j) && (i <= MAX_SPAM_BAR_CHARS))
599 spam_bar_buffer[i++] = spamd_score_char;
602 spam_bar_buffer[0] = '/';
605 spam_bar_buffer[i] = '\0';
606 spam_bar = spam_bar_buffer;
608 /* create "float" spam score */
609 (void)string_format(spam_score_buffer, sizeof(spam_score_buffer),
610 "%.1f", spamd_score);
611 spam_score = spam_score_buffer;
613 /* create "int" spam score */
614 j = (int)((spamd_score + 0.001)*10);
615 (void)string_format(spam_score_int_buffer, sizeof(spam_score_int_buffer),
617 spam_score_int = spam_score_int_buffer;
619 /* compare threshold against score */
620 spam_rc = spamd_score >= spamd_threshold
621 ? OK /* spam as determined by user's threshold */
622 : FAIL; /* not spam */
624 /* remember expanded spamd_address if needed */
625 if (spamd_address_work != spamd_address)
626 prev_spamd_address_work = string_copy(spamd_address_work);
628 /* remember user name and "been here" for it */
629 Ustrcpy(prev_user_name, user_name);
633 ? OK /* always return OK, no matter what the score */
637 (void)fclose(mbox_file);