Use random_number rather than random, for external server distribution. Bug 2694
[exim.git] / src / src / spam.c
1 /*************************************************
2 *     Exim - an Internet mail transport agent    *
3 *************************************************/
4
5 /* Copyright (c) Tom Kistner <tom@duncanthrax.net> 2003 - 2015
6  * License: GPL
7  * Copyright (c) The Exim Maintainers 2016 - 2020
8  */
9
10 /* Code for calling spamassassin's spamd. Called from acl.c. */
11
12 #include "exim.h"
13 #ifdef WITH_CONTENT_SCAN
14 #include "spam.h"
15
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;
22 int spam_ok = 0;
23 int spam_rc = 0;
24 uschar *prev_spamd_address_work = NULL;
25
26 static const uschar * loglabel = US"spam acl condition:";
27
28
29 static int
30 spamd_param_init(spamd_address_container *spamd)
31 {
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;
37 spamd->retry = 0;
38 spamd->priority = 1;
39 return 0;
40 }
41
42
43 static int
44 spamd_param(const uschar * param, spamd_address_container * spamd)
45 {
46 static int timesinceday = -1;
47 const uschar * s;
48 const uschar * name;
49
50 /*XXX more clever parsing could discard embedded spaces? */
51
52 if (sscanf(CCS param, "pri=%u", &spamd->priority))
53   return 0; /* OK */
54
55 if (sscanf(CCS param, "weight=%u", &spamd->weight))
56   {
57   if (spamd->weight == 0) /* this server disabled: skip it */
58     return 1;
59   return 0; /* OK */
60   }
61
62 if (Ustrncmp(param, "time=", 5) == 0)
63   {
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;
68
69   name = US"time";
70   s = param+5;
71   if ((end_string = Ustrchr(s, '-')))
72     {
73     end_string++;
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
76        )
77       goto badval;
78     }
79   else
80     goto badval;
81
82   if (timesinceday < 0)
83     {
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;
87     }
88
89   time_start = start_h*3600 + start_m*60 + start_s;
90   time_end = end_h*3600 + end_m*60 + end_s;
91
92   if (timesinceday < time_start || timesinceday >= time_end)
93     return 1; /* skip spamd server */
94
95   return 0; /* OK */
96   }
97
98 if (Ustrcmp(param, "variant=rspamd") == 0)
99   {
100   spamd->is_rspamd = TRUE;
101   return 0;
102   }
103
104 if (Ustrncmp(param, "tmo=", 4) == 0)
105   {
106   int sec = readconf_readtime((s = param+4), '\0', FALSE);
107   name = US"timeout";
108   if (sec < 0)
109     goto badval;
110   spamd->timeout = sec;
111   return 0;
112   }
113
114 if (Ustrncmp(param, "retry=", 6) == 0)
115   {
116   int sec = readconf_readtime((s = param+6), '\0', FALSE);
117   name = US"retry";
118   if (sec < 0)
119     goto badval;
120   spamd->retry = sec;
121   return 0;
122   }
123
124 log_write(0, LOG_MAIN, "%s warning - invalid spamd parameter: '%s'",
125   loglabel, param);
126 return -1; /* syntax error */
127
128 badval:
129   log_write(0, LOG_MAIN,
130     "%s warning - invalid spamd %s value: '%s'", loglabel, name, s);
131   return -1; /* syntax error */
132 }
133
134
135 static int
136 spamd_get_server(spamd_address_container ** spamds, int num_servers)
137 {
138 unsigned int i;
139 spamd_address_container * sd;
140 long weights;
141 unsigned pri;
142
143 /* speedup, if we have only 1 server */
144 if (num_servers == 1)
145   return (spamds[0]->is_failed ? -1 : 0);
146
147 /* scan for highest pri */
148 for (pri = 0, i = 0; i < num_servers; i++)
149   {
150   sd = spamds[i];
151   if (!sd->is_failed && sd->priority > pri) pri = sd->priority;
152   }
153
154 /* get sum of weights */
155 for (weights = 0, i = 0; i < num_servers; i++)
156   {
157   sd = spamds[i];
158   if (!sd->is_failed && sd->priority == pri) weights += sd->weight;
159   }
160 if (weights == 0)       /* all servers failed */
161   return -1;
162
163 for (long rnd = random_number(weights), i = 0; i < num_servers; i++)
164   {
165   sd = spamds[i];
166   if (!sd->is_failed && sd->priority == pri)
167     if ((rnd -= sd->weight) < 0)
168       return i;
169   }
170
171 log_write(0, LOG_MAIN|LOG_PANIC,
172   "%s unknown error (memory/cpu corruption?)", loglabel);
173 return -1;
174 }
175
176
177 int
178 spam(const uschar **listptr)
179 {
180 int sep = 0;
181 const uschar *list = *listptr;
182 uschar *user_name;
183 unsigned long mbox_size;
184 FILE *mbox_file;
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;
193 uschar *p,*q;
194 int override = 0;
195 time_t start;
196 size_t read, wrote;
197 #ifndef NO_POLL_H
198 struct pollfd pollfd;
199 #else                               /* Patch posted by Erik ? for OS X */
200 struct timeval select_tv;         /* and applied by PH */
201 fd_set select_fd;
202 #endif
203 uschar *spamd_address_work;
204 spamd_address_container * sd;
205
206 /* stop compiler warning */
207 result = 0;
208
209 /* find the username from the option list */
210 if (!(user_name = string_nextinlist(&list, &sep, NULL, 0)))
211   {
212   /* no username given, this means no scanning should be done */
213   return FAIL;
214   }
215
216 /* if username is "0" or "false", do not scan */
217 if (Ustrcmp(user_name, "0") == 0 || strcmpic(user_name, US"false") == 0)
218   return FAIL;
219
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 */
223   override = 1;
224
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)))
229   {
230   log_write(0, LOG_MAIN|LOG_PANIC,
231     "%s spamd_address starts with $, but expansion failed: %s",
232     loglabel, expand_string_message);
233   return DEFER;
234   }
235
236 DEBUG(D_acl) debug_printf_indent("spamd: addrlist '%s'\n", spamd_address_work);
237
238 /* check if previous spamd_address was expanded and has changed. dump cached results if so */
239 if (  spam_ok
240    && prev_spamd_address_work != NULL
241    && Ustrcmp(prev_spamd_address_work, spamd_address_work) != 0
242    )
243   spam_ok = 0;
244
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;
248
249 /* make sure the eml mbox file is spooled up */
250
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);
255   return DEFER;
256   }
257
258 start = time(NULL);
259
260   {
261   int num_servers = 0;
262   int current_server;
263   uschar * address;
264   const uschar * spamd_address_list_ptr = spamd_address_work;
265   spamd_address_container * spamd_address_vector[32];
266
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)))
271     {
272     const uschar * sublist;
273     int sublist_sep = -(int)' ';        /* default space-sep */
274     unsigned args;
275     uschar * s;
276
277     DEBUG(D_acl) debug_printf_indent("spamd: addr entry '%s'\n", address);
278     sd = store_get(sizeof(spamd_address_container), FALSE);
279
280     for (sublist = address, args = 0, spamd_param_init(sd);
281          (s = string_nextinlist(&sublist, &sublist_sep, NULL, 0));
282          args++
283          )
284       {
285         DEBUG(D_acl) debug_printf_indent("spamd:  addr parm '%s'\n", s);
286         switch (args)
287         {
288         case 0:   sd->hostspec = s;
289                   if (*s == '/') args++;        /* local; no port */
290                   break;
291         case 1:   sd->hostspec = string_sprintf("%s %s", sd->hostspec, s);
292                   break;
293         default:  spamd_param(s, sd);
294                   break;
295         }
296       }
297     if (args < 2)
298       {
299       log_write(0, LOG_MAIN,
300         "%s warning - invalid spamd address: '%s'", loglabel, address);
301       continue;
302       }
303
304     spamd_address_vector[num_servers] = sd;
305     if (++num_servers > 31)
306       break;
307     }
308
309   /* check if we have at least one server */
310   if (!num_servers)
311     {
312     log_write(0, LOG_MAIN|LOG_PANIC,
313        "%s no useable spamd server addresses in spamd_address configuration option.",
314        loglabel);
315     goto defer;
316     }
317
318   current_server = spamd_get_server(spamd_address_vector, num_servers);
319   sd = spamd_address_vector[current_server];
320   for(;;)
321     {
322     uschar * errstr;
323
324     DEBUG(D_acl) debug_printf_indent("spamd: trying server %s\n", sd->hostspec);
325
326     for (;;)
327       {
328       /*XXX could potentially use TFO early-data here */
329       if (  (spamd_cctx.sock = ip_streamsocket(sd->hostspec, &errstr, 5, NULL)) >= 0
330          || sd->retry <= 0
331          )
332         break;
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);
335       }
336     if (spamd_cctx.sock >= 0)
337       break;
338
339     log_write(0, LOG_MAIN, "%s spamd: %s", loglabel, errstr);
340     sd->is_failed = TRUE;
341
342     current_server = spamd_get_server(spamd_address_vector, num_servers);
343     if (current_server < 0)
344       {
345       log_write(0, LOG_MAIN|LOG_PANIC, "%s all spamd servers failed", loglabel);
346       goto defer;
347       }
348     sd = spamd_address_vector[current_server];
349     }
350   }
351
352 (void)fcntl(spamd_cctx.sock, F_SETFL, O_NONBLOCK);
353 /* now we are connected to spamd on spamd_cctx.sock */
354 if (sd->is_rspamd)
355   {
356   gstring * req_str;
357   const uschar * s;
358
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));
364
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);
378   }
379 else
380   {                             /* spamassassin variant */
381   int n;
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);
387   }
388
389 if (wrote == -1)
390   {
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));
394   goto defer;
395   }
396
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).
406  */
407 #ifndef NO_POLL_H
408 pollfd.fd = spamd_cctx.sock;
409 pollfd.events = POLLOUT;
410 #endif
411 (void)fcntl(spamd_cctx.sock, F_SETFL, O_NONBLOCK);
412 do
413   {
414   read = fread(spamd_buffer,1,sizeof(spamd_buffer),mbox_file);
415   if (read > 0)
416     {
417     offset = 0;
418 again:
419 #ifndef NO_POLL_H
420     result = poll(&pollfd, 1, 1000);
421
422 /* Patch posted by Erik ? for OS X and applied by PH */
423 #else
424     select_tv.tv_sec = 1;
425     select_tv.tv_usec = 0;
426     FD_ZERO(&select_fd);
427     FD_SET(spamd_cctx.sock, &select_fd);
428     result = select(spamd_cctx.sock+1, NULL, &select_fd, NULL, &select_tv);
429 #endif
430 /* End Erik's patch */
431
432     if (result == -1 && errno == EINTR)
433       goto again;
434     else if (result < 1)
435       {
436       if (result == -1)
437         log_write(0, LOG_MAIN|LOG_PANIC,
438           "%s %s on spamd %s socket", loglabel, callout_address, strerror(errno));
439       else
440         {
441         if (time(NULL) - start < sd->timeout)
442           goto again;
443         log_write(0, LOG_MAIN|LOG_PANIC,
444           "%s timed out writing spamd %s, socket", loglabel, callout_address);
445         }
446       (void)close(spamd_cctx.sock);
447       goto defer;
448       }
449
450     wrote = send(spamd_cctx.sock,spamd_buffer + offset,read - offset,0);
451     if (wrote == -1)
452       {
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);
456       goto defer;
457       }
458     if (offset + wrote != read)
459       {
460       offset += wrote;
461       goto again;
462       }
463     }
464   }
465 while (!feof(mbox_file) && !ferror(mbox_file));
466
467 if (ferror(mbox_file))
468   {
469   log_write(0, LOG_MAIN|LOG_PANIC,
470     "%s error reading spool file: %s", loglabel, strerror(errno));
471   (void)close(spamd_cctx.sock);
472   goto defer;
473   }
474
475 (void)fclose(mbox_file);
476
477 /* we're done sending, close socket for writing */
478 if (!sd->is_rspamd)
479   shutdown(spamd_cctx.sock,SHUT_WR);
480
481 /* read spamd response using what's left of the timeout.  */
482 memset(spamd_buffer, 0, sizeof(spamd_buffer));
483 offset = 0;
484 while ((i = ip_recv(&spamd_cctx,
485                    spamd_buffer + offset,
486                    sizeof(spamd_buffer) - offset - 1,
487                    sd->timeout + start)) > 0)
488   offset += i;
489 spamd_buffer[offset] = '\0';    /* guard byte */
490
491 /* error handling */
492 if (i <= 0 && errno != 0)
493   {
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);
497   return DEFER;
498   }
499
500 /* reading done */
501 (void)close(spamd_cctx.sock);
502
503 if (sd->is_rspamd)
504   {                             /* rspamd variant of reply */
505   int r;
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 */
511      )
512     {
513     log_write(0, LOG_MAIN|LOG_PANIC,
514               "%s cannot parse spamd %s, output: %d", loglabel, callout_address, r);
515     return DEFER;
516     }
517   /* now parse action */
518   p = &spamd_buffer[spamd_report_offset];
519
520   if (Ustrncmp(p, "Action: ", sizeof("Action: ") - 1) == 0)
521     {
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)
525       *q++ = *p++;
526     *q = '\0';
527     }
528   }
529 else
530   {                             /* spamassassin */
531   /* dig in the spamd output and put the report in a multiline header,
532   if requested */
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)
536     {
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)
541         {
542         log_write(0, LOG_MAIN|LOG_PANIC,
543                   "%s cannot parse spamd %s output", loglabel, callout_address);
544         return DEFER;
545         }
546     }
547
548   Ustrcpy(spam_action_buffer,
549     spamd_score >= spamd_threshold ? US"reject" : US"no action");
550   }
551
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;
556 while (*p != '\0')
557   {
558   /* skip \r */
559   if (*p == '\r')
560     {
561     p++;
562     continue;
563     }
564   *q++ = *p;
565   if (*p++ == '\n')
566     {
567     /* add an extra space after the newline to ensure
568     that it is treated as a header continuation line */
569     *q++ = ' ';
570     }
571   }
572 /* NULL-terminate */
573 *q-- = '\0';
574 /* cut off trailing leftovers */
575 while (*q <= ' ')
576   *q-- = '\0';
577
578 spam_report = spam_report_buffer;
579 spam_action = spam_action_buffer;
580
581 /* create spam bar */
582 spamd_score_char = spamd_score > 0 ? '+' : '-';
583 j = abs((int)(spamd_score));
584 i = 0;
585 if (j != 0)
586   while ((i < j) && (i <= MAX_SPAM_BAR_CHARS))
587      spam_bar_buffer[i++] = spamd_score_char;
588 else
589   {
590   spam_bar_buffer[0] = '/';
591   i = 1;
592   }
593 spam_bar_buffer[i] = '\0';
594 spam_bar = spam_bar_buffer;
595
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;
600
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),
604         "%d", j);
605 spam_score_int = spam_score_int_buffer;
606
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 */
611
612 /* remember expanded spamd_address if needed */
613 if (spamd_address_work != spamd_address)
614   prev_spamd_address_work = string_copy(spamd_address_work);
615
616 /* remember user name and "been here" for it */
617 prev_user_name = user_name;
618 spam_ok = 1;
619
620 return override
621   ? OK          /* always return OK, no matter what the score */
622   : spam_rc;
623
624 defer:
625   (void)fclose(mbox_file);
626   return DEFER;
627 }
628
629 #endif
630 /* vi: aw ai sw=2
631 */