1 /*************************************************
2 * Exim - an Internet mail transport agent *
3 *************************************************/
5 /* Copyright (c) Tom Kistner <tom@duncanthrax.net> 2003-???? */
8 /* Code for calling spamassassin's spamd. Called from acl.c. */
11 #ifdef WITH_CONTENT_SCAN
14 uschar spam_score_buffer[16];
15 uschar spam_score_int_buffer[16];
16 uschar spam_bar_buffer[128];
17 uschar spam_action_buffer[32];
18 uschar spam_report_buffer[32600];
19 uschar prev_user_name[128] = "";
22 uschar *prev_spamd_address_work = NULL;
24 static const uschar * loglabel = US"spam acl condition:";
28 spamd_param_init(spamd_address_container *spamd)
30 /* default spamd server weight, time and backup value */
31 spamd->is_failed = FALSE;
32 spamd->is_backup = FALSE;
33 spamd->weight = SPAMD_WEIGHT;
34 spamd->timeout = SPAMD_TIMEOUT;
41 spamd_param(const uschar *param, spamd_address_container *spamd)
43 static int timesinceday = -1;
47 /* check backup parameter */
48 if (Ustrcmp(param, "backup") == 0)
50 spamd->is_backup = TRUE;
54 /*XXX more clever parsing could discard embedded spaces? */
56 /* check weight parameter */
57 if (sscanf(param, "weight=%u", &spamd->weight))
59 if (spamd->weight == 0) /* this server disabled: skip it */
64 /* check time parameter */
65 if (Ustrncmp(param, "time=", 5) == 0)
67 unsigned int start_h = 0, start_m = 0, start_s = 0;
68 unsigned int end_h = 24, end_m = 0, end_s = 0;
69 unsigned int time_start, time_end;
70 const uschar * end_string;
74 if ((end_string = Ustrchr(s, '-')))
77 if ( sscanf(CS end_string, "%u.%u.%u", &end_h, &end_m, &end_s) == 0
78 || sscanf(CS s, "%u.%u.%u", &start_h, &start_m, &start_s) == 0
87 time_t now = time(NULL);
88 struct tm *tmp = localtime(&now);
89 timesinceday = tmp->tm_hour*3600 + tmp->tm_min*60 + tmp->tm_sec;
92 time_start = start_h*3600 + start_m*60 + start_s;
93 time_end = end_h*3600 + end_m*60 + end_s;
95 if (timesinceday < time_start || timesinceday >= time_end)
96 return 1; /* skip spamd server */
101 if (Ustrcmp(param, "variant=rspamd") == 0)
103 spamd->is_rspamd = TRUE;
107 if (Ustrncmp(param, "tmo=", 4) == 0)
109 int sec = readconf_readtime((s = param+4), '\0', FALSE);
113 spamd->timeout = sec;
117 if (Ustrncmp(param, "retry=", 6) == 0)
119 int sec = readconf_readtime((s = param+6), '\0', FALSE);
127 log_write(0, LOG_MAIN, "%s warning - invalid spamd parameter: '%s'",
129 return -1; /* syntax error */
132 log_write(0, LOG_MAIN,
133 "%s warning - invalid spamd %s value: '%s'", loglabel, name, s);
134 return -1; /* syntax error */
139 spamd_get_server(spamd_address_container **spamds, int num_servers)
142 long rnd, weights = 0;
143 static BOOL srandomed = 0;
144 BOOL usebackup = FALSE;
148 /* seedup, if we have only 1 server */
149 if (num_servers == 1)
150 return (spamds[0]->is_failed ? -1 : 0);
156 gettimeofday(&tv, NULL);
157 srandom((unsigned int)(tv.tv_usec/1000));
161 /* get sum of all weights */
162 for (i = 0; i < num_servers; i++)
163 if (!spamds[i]->is_failed && spamds[i]->is_backup == usebackup)
164 weights += spamds[i]->weight;
168 if (usebackup) /* all servers failed (backups too) */
173 rnd = random() % weights;
175 for (i = 0; i < num_servers; i++)
176 if (!spamds[i]->is_failed && spamds[i]->is_backup == usebackup)
177 if ((rnd -= spamds[i]->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;
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;
207 struct sockaddr_un server;
209 struct pollfd pollfd;
210 #else /* Patch posted by Erik ? for OS X */
211 struct timeval select_tv; /* and applied by PH */
214 uschar *spamd_address_work;
215 spamd_address_container * sd;
217 /* stop compiler warning */
220 /* find the username from the option list */
221 if ((user_name = string_nextinlist(&list, &sep,
223 sizeof(user_name_buffer))) == NULL)
225 /* no username given, this means no scanning should be done */
229 /* if username is "0" or "false", do not scan */
230 if ( (Ustrcmp(user_name,"0") == 0) ||
231 (strcmpic(user_name,US"false") == 0) )
234 /* if there is an additional option, check if it is "true" */
235 if (strcmpic(list,US"true") == 0)
236 /* in that case, always return true later */
239 /* expand spamd_address if needed */
240 if (*spamd_address == '$')
242 spamd_address_work = expand_string(spamd_address);
243 if (spamd_address_work == NULL)
245 log_write(0, LOG_MAIN|LOG_PANIC,
246 "%s spamd_address starts with $, but expansion failed: %s",
247 loglabel, expand_string_message);
252 spamd_address_work = spamd_address;
254 HDEBUG(D_acl) debug_printf("spamd: addrlist '%s'\n", spamd_address_work);
256 /* check if previous spamd_address was expanded and has changed. dump cached results if so */
258 && prev_spamd_address_work != NULL
259 && Ustrcmp(prev_spamd_address_work, spamd_address_work) != 0
263 /* if we scanned for this username last time, just return */
264 if (spam_ok && Ustrcmp(prev_user_name, user_name) == 0)
265 return override ? OK : spam_rc;
267 /* make sure the eml mbox file is spooled up */
268 mbox_file = spool_mbox(&mbox_size, NULL);
270 if (mbox_file == NULL)
272 /* error while spooling */
273 log_write(0, LOG_MAIN|LOG_PANIC,
274 "%s error while creating mbox spool file", loglabel);
284 const uschar *spamd_address_list_ptr = spamd_address_work;
285 spamd_address_container * spamd_address_vector[32];
287 /* Check how many spamd servers we have
288 and register their addresses */
289 while ((address = string_nextinlist(&spamd_address_list_ptr, &sep,
292 const uschar * sublist;
293 int sublist_sep = -(int)' '; /* default space-sep */
297 HDEBUG(D_acl) debug_printf("spamd: addr entry '%s'\n", address);
298 sd = (spamd_address_container *)store_get(sizeof(spamd_address_container));
300 for (sublist = address, args = 0, spamd_param_init(sd);
301 s = string_nextinlist(&sublist, &sublist_sep, NULL, 0);
305 HDEBUG(D_acl) debug_printf("spamd: addr parm '%s'\n", s);
308 case 0: sd->hostspec = s;
309 if (*s == '/') args++; /* local; no port */
311 case 1: sd->hostspec = string_sprintf("%s %s", sd->hostspec, s);
313 default: spamd_param(s, sd);
319 log_write(0, LOG_MAIN,
320 "%s warning - invalid spamd address: '%s'", loglabel, address);
324 spamd_address_vector[num_servers] = sd;
325 if (++num_servers > 31)
329 /* check if we have at least one server */
332 log_write(0, LOG_MAIN|LOG_PANIC,
333 "%s no useable spamd server addresses in spamd_address configuration option.",
338 current_server = spamd_get_server(spamd_address_vector, num_servers);
339 sd = spamd_address_vector[current_server];
344 debug_printf("trying server %s\n", sd->hostspec);
348 if ( (spamd_sock = ip_streamsocket(sd->hostspec, &errstr, 5)) >= 0
352 debug_printf("server %s: retry conn\n", sd->hostspec);
353 while (sd->retry > 0) sd->retry = sleep(sd->retry);
358 log_write(0, LOG_MAIN, "%s spamd: %s", loglabel, errstr);
359 sd->is_failed = TRUE;
361 current_server = spamd_get_server(spamd_address_vector, num_servers);
362 if (current_server < 0)
364 log_write(0, LOG_MAIN|LOG_PANIC, "%s all spamd servers failed", loglabel);
367 sd = spamd_address_vector[current_server];
371 if (spamd_sock == -1)
373 log_write(0, LOG_MAIN|LOG_PANIC,
374 "programming fault, spamd_sock unexpectedly unset");
378 (void)fcntl(spamd_sock, F_SETFL, O_NONBLOCK);
379 /* now we are connected to spamd on spamd_sock */
381 { /* rspamd variant */
384 const uschar * fcrdns;
385 const uschar * authid;
387 req_str = string_sprintf("CHECK RSPAMC/1.3\r\nContent-length: %lu\r\n"
388 "Queue-Id: %s\r\nFrom: <%s>\r\nRecipient-Number: %d\r\n", mbox_size,
389 message_id, sender_address, recipients_count);
390 for (i = 0; i < recipients_count; i ++)
391 req_str = string_sprintf("%sRcpt: <%s>\r\n", req_str, recipients_list[i].address);
392 if ((helo = expand_string(US"$sender_helo_name")) != NULL && *helo != '\0')
393 req_str = string_sprintf("%sHelo: %s\r\n", req_str, helo);
394 if ((fcrdns = expand_string(US"$sender_host_name")) != NULL && *fcrdns != '\0')
395 req_str = string_sprintf("%sHostname: %s\r\n", req_str, fcrdns);
396 if (sender_host_address != NULL)
397 req_str = string_sprintf("%sIP: %s\r\n", req_str, sender_host_address);
398 if ((authid = expand_string(US"$authenticated_id")) != NULL && *authid != '\0')
399 req_str = string_sprintf("%sUser: %s\r\n", req_str, authid);
400 req_str = string_sprintf("%s\r\n", req_str);
401 wrote = send(spamd_sock, req_str, Ustrlen(req_str), 0);
404 { /* spamassassin variant */
405 (void)string_format(spamd_buffer,
406 sizeof(spamd_buffer),
407 "REPORT SPAMC/1.2\r\nUser: %s\r\nContent-length: %ld\r\n\r\n",
410 /* send our request */
411 wrote = send(spamd_sock, spamd_buffer, Ustrlen(spamd_buffer), 0);
416 (void)close(spamd_sock);
417 log_write(0, LOG_MAIN|LOG_PANIC,
418 "%s spamd send failed: %s", loglabel, strerror(errno));
422 /* now send the file */
423 /* spamd sometimes accepts conections but doesn't read data off
424 * the connection. We make the file descriptor non-blocking so
425 * that the write will only write sufficient data without blocking
426 * and we poll the desciptor to make sure that we can write without
427 * blocking. Short writes are gracefully handled and if the whole
428 * trasaction takes too long it is aborted.
429 * Note: poll() is not supported in OSX 10.2 and is reported to be
430 * broken in more recent versions (up to 10.4).
433 pollfd.fd = spamd_sock;
434 pollfd.events = POLLOUT;
436 (void)fcntl(spamd_sock, F_SETFL, O_NONBLOCK);
439 read = fread(spamd_buffer,1,sizeof(spamd_buffer),mbox_file);
445 result = poll(&pollfd, 1, 1000);
447 /* Patch posted by Erik ? for OS X and applied by PH */
449 select_tv.tv_sec = 1;
450 select_tv.tv_usec = 0;
452 FD_SET(spamd_sock, &select_fd);
453 result = select(spamd_sock+1, NULL, &select_fd, NULL, &select_tv);
455 /* End Erik's patch */
457 if (result == -1 && errno == EINTR)
462 log_write(0, LOG_MAIN|LOG_PANIC,
463 "%s %s on spamd socket", loglabel, strerror(errno));
466 if (time(NULL) - start < sd->timeout)
468 log_write(0, LOG_MAIN|LOG_PANIC,
469 "%s timed out writing spamd socket", loglabel);
471 (void)close(spamd_sock);
475 wrote = send(spamd_sock,spamd_buffer + offset,read - offset,0);
478 log_write(0, LOG_MAIN|LOG_PANIC,
479 "%s %s on spamd socket", loglabel, strerror(errno));
480 (void)close(spamd_sock);
483 if (offset + wrote != read)
490 while (!feof(mbox_file) && !ferror(mbox_file));
492 if (ferror(mbox_file))
494 log_write(0, LOG_MAIN|LOG_PANIC,
495 "%s error reading spool file: %s", loglabel, strerror(errno));
496 (void)close(spamd_sock);
500 (void)fclose(mbox_file);
502 /* we're done sending, close socket for writing */
503 shutdown(spamd_sock,SHUT_WR);
505 /* read spamd response using what's left of the timeout. */
506 memset(spamd_buffer, 0, sizeof(spamd_buffer));
508 while ((i = ip_recv(spamd_sock,
509 spamd_buffer + offset,
510 sizeof(spamd_buffer) - offset - 1,
511 sd->timeout - time(NULL) + start)) > 0 )
515 if (i <= 0 && errno != 0)
517 log_write(0, LOG_MAIN|LOG_PANIC,
518 "%s error reading from spamd socket: %s", loglabel, strerror(errno));
519 (void)close(spamd_sock);
524 (void)close(spamd_sock);
527 { /* rspamd variant of reply */
529 if ((r = sscanf(CS spamd_buffer,
530 "RSPAMD/%7s 0 EX_OK\r\nMetric: default; %7s %lf / %lf / %lf\r\n%n",
531 spamd_version, spamd_short_result, &spamd_score, &spamd_threshold,
532 &spamd_reject_score, &spamd_report_offset)) != 5)
534 log_write(0, LOG_MAIN|LOG_PANIC,
535 "%s cannot parse spamd output: %d", loglabel, r);
538 /* now parse action */
539 p = &spamd_buffer[spamd_report_offset];
541 if (Ustrncmp(p, "Action: ", sizeof("Action: ") - 1) == 0)
543 p += sizeof("Action: ") - 1;
544 q = &spam_action_buffer[0];
545 while (*p && *p != '\r' && (q - spam_action_buffer) < sizeof(spam_action_buffer) - 1)
552 /* dig in the spamd output and put the report in a multiline header,
554 if (sscanf(CS spamd_buffer,
555 "SPAMD/%7s 0 EX_OK\r\nContent-length: %*u\r\n\r\n%lf/%lf\r\n%n",
556 spamd_version,&spamd_score,&spamd_threshold,&spamd_report_offset) != 3)
558 /* try to fall back to pre-2.50 spamd output */
559 if (sscanf(CS spamd_buffer,
560 "SPAMD/%7s 0 EX_OK\r\nSpam: %*s ; %lf / %lf\r\n\r\n%n",
561 spamd_version,&spamd_score,&spamd_threshold,&spamd_report_offset) != 3)
563 log_write(0, LOG_MAIN|LOG_PANIC,
564 "%s cannot parse spamd output", loglabel);
569 Ustrcpy(spam_action_buffer,
570 spamd_score >= spamd_threshold ? "reject" : "no action");
573 /* Create report. Since this is a multiline string,
574 we must hack it into shape first */
575 p = &spamd_buffer[spamd_report_offset];
576 q = spam_report_buffer;
588 /* add an extra space after the newline to ensure
589 that it is treated as a header continuation line */
595 /* cut off trailing leftovers */
599 spam_report = spam_report_buffer;
600 spam_action = spam_action_buffer;
602 /* create spam bar */
603 spamd_score_char = spamd_score > 0 ? '+' : '-';
604 j = abs((int)(spamd_score));
607 while ((i < j) && (i <= MAX_SPAM_BAR_CHARS))
608 spam_bar_buffer[i++] = spamd_score_char;
611 spam_bar_buffer[0] = '/';
614 spam_bar_buffer[i] = '\0';
615 spam_bar = spam_bar_buffer;
617 /* create "float" spam score */
618 (void)string_format(spam_score_buffer, sizeof(spam_score_buffer),
619 "%.1f", spamd_score);
620 spam_score = spam_score_buffer;
622 /* create "int" spam score */
623 j = (int)((spamd_score + 0.001)*10);
624 (void)string_format(spam_score_int_buffer, sizeof(spam_score_int_buffer),
626 spam_score_int = spam_score_int_buffer;
628 /* compare threshold against score */
629 spam_rc = spamd_score >= spamd_threshold
630 ? OK /* spam as determined by user's threshold */
631 : FAIL; /* not spam */
633 /* remember expanded spamd_address if needed */
634 if (spamd_address_work != spamd_address)
635 prev_spamd_address_work = string_copy(spamd_address_work);
637 /* remember user name and "been here" for it */
638 Ustrcpy(prev_user_name, user_name);
642 ? OK /* always return OK, no matter what the score */
646 (void)fclose(mbox_file);