Add retry option to clamd and spamd. Bug 392
[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-???? */
6 /* License: GPL */
7
8 /* Code for calling spamassassin's spamd. Called from acl.c. */
9
10 #include "exim.h"
11 #ifdef WITH_CONTENT_SCAN
12 #include "spam.h"
13
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] = "";
20 int spam_ok = 0;
21 int spam_rc = 0;
22 uschar *prev_spamd_address_work = NULL;
23
24 static const uschar * loglabel = US"spam acl condition:";
25
26
27 static int
28 spamd_param_init(spamd_address_container *spamd)
29 {
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;
35 spamd->retry = 0;
36 return 0;
37 }
38
39
40 static int
41 spamd_param(const uschar *param, spamd_address_container *spamd)
42 {
43 static int timesinceday = -1;
44 const uschar * s;
45 const uschar * name;
46
47 /* check backup parameter */
48 if (Ustrcmp(param, "backup") == 0)
49   {
50   spamd->is_backup = TRUE;
51   return 0; /* OK */
52   }
53
54 /*XXX more clever parsing could discard embedded spaces? */
55
56 /* check weight parameter */
57 if (sscanf(param, "weight=%u", &spamd->weight))
58   {
59   if (spamd->weight == 0) /* this server disabled: skip it */
60     return 1;
61   return 0; /* OK */
62   }
63
64 /* check time parameter */
65 if (Ustrncmp(param, "time=", 5) == 0)
66   {
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;
71
72   name = US"time";
73   s = param+5;
74   if ((end_string = Ustrchr(s, '-')))
75     {
76     end_string++;
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
79        )
80       goto badval;
81     }
82   else
83     goto badval;
84
85   if (timesinceday < 0)
86     {
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;
90     }
91
92   time_start = start_h*3600 + start_m*60 + start_s;
93   time_end = end_h*3600 + end_m*60 + end_s;
94
95   if (timesinceday < time_start || timesinceday >= time_end)
96     return 1; /* skip spamd server */
97
98   return 0; /* OK */
99   }
100
101 if (Ustrcmp(param, "variant=rspamd") == 0)
102   {
103   spamd->is_rspamd = TRUE;
104   return 0;
105   }
106
107 if (Ustrncmp(param, "tmo=", 4) == 0)
108   {
109   int sec = readconf_readtime((s = param+4), '\0', FALSE);
110   name = US"timeout";
111   if (sec < 0)
112     goto badval;
113   spamd->timeout = sec;
114   return 0;
115   }
116
117 if (Ustrncmp(param, "retry=", 6) == 0)
118   {
119   int sec = readconf_readtime((s = param+6), '\0', FALSE);
120   name = US"retry";
121   if (sec < 0)
122     goto badval;
123   spamd->retry = sec;
124   return 0;
125   }
126
127 log_write(0, LOG_MAIN, "%s warning - invalid spamd parameter: '%s'",
128   loglabel, param);
129 return -1; /* syntax error */
130
131 badval:
132   log_write(0, LOG_MAIN,
133     "%s warning - invalid spamd %s value: '%s'", loglabel, name, s);
134   return -1; /* syntax error */
135 }
136
137
138 static int
139 spamd_get_server(spamd_address_container **spamds, int num_servers)
140 {
141 unsigned int i;
142 long rnd, weights = 0;
143 static BOOL srandomed = 0;
144 BOOL usebackup = FALSE;
145
146 for (;;)
147   {
148   /* seedup, if we have only 1 server */
149   if (num_servers == 1)
150     return (spamds[0]->is_failed ? -1 : 0);
151
152   /* init ranmod */
153   if (!srandomed)
154     {
155     struct timeval tv;
156     gettimeofday(&tv, NULL);
157     srandom((unsigned int)(tv.tv_usec/1000));
158     srandomed = TRUE;
159     }
160
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;
165
166   if (weights != 0)
167     break;
168   if (usebackup)        /* all servers failed (backups too) */
169     return -1;
170   usebackup = TRUE;
171   }
172
173 rnd = random() % weights;
174
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)
178       return i;
179
180 log_write(0, LOG_MAIN|LOG_PANIC,
181   "%s unknown error (memory/cpu corruption?)", loglabel);
182 return -1;
183 }
184
185
186 int
187 spam(const uschar **listptr)
188 {
189 int sep = 0;
190 const uschar *list = *listptr;
191 uschar *user_name;
192 uschar user_name_buffer[128];
193 unsigned long mbox_size;
194 FILE *mbox_file;
195 int spamd_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;
203 uschar *p,*q;
204 int override = 0;
205 time_t start;
206 size_t read, wrote;
207 struct sockaddr_un server;
208 #ifndef NO_POLL_H
209 struct pollfd pollfd;
210 #else                               /* Patch posted by Erik ? for OS X */
211 struct timeval select_tv;         /* and applied by PH */
212 fd_set select_fd;
213 #endif
214 uschar *spamd_address_work;
215 spamd_address_container * sd;
216
217 /* stop compiler warning */
218 result = 0;
219
220 /* find the username from the option list */
221 if ((user_name = string_nextinlist(&list, &sep,
222                                    user_name_buffer,
223                                    sizeof(user_name_buffer))) == NULL)
224   {
225   /* no username given, this means no scanning should be done */
226   return FAIL;
227   }
228
229 /* if username is "0" or "false", do not scan */
230 if ( (Ustrcmp(user_name,"0") == 0) ||
231      (strcmpic(user_name,US"false") == 0) )
232   return FAIL;
233
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 */
237   override = 1;
238
239 /* expand spamd_address if needed */
240 if (*spamd_address == '$')
241   {
242   spamd_address_work = expand_string(spamd_address);
243   if (spamd_address_work == NULL)
244     {
245     log_write(0, LOG_MAIN|LOG_PANIC,
246       "%s spamd_address starts with $, but expansion failed: %s",
247       loglabel, expand_string_message);
248     return DEFER;
249     }
250   }
251 else
252   spamd_address_work = spamd_address;
253
254 HDEBUG(D_acl) debug_printf("spamd: addrlist '%s'\n", spamd_address_work);
255
256 /* check if previous spamd_address was expanded and has changed. dump cached results if so */
257 if (  spam_ok
258    && prev_spamd_address_work != NULL
259    && Ustrcmp(prev_spamd_address_work, spamd_address_work) != 0
260    )
261   spam_ok = 0;
262
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;
266
267 /* make sure the eml mbox file is spooled up */
268 mbox_file = spool_mbox(&mbox_size, NULL);
269
270 if (mbox_file == NULL)
271   {
272   /* error while spooling */
273   log_write(0, LOG_MAIN|LOG_PANIC,
274          "%s error while creating mbox spool file", loglabel);
275   return DEFER;
276   }
277
278 start = time(NULL);
279
280   {
281   int num_servers = 0;
282   int current_server;
283   uschar *address;
284   const uschar *spamd_address_list_ptr = spamd_address_work;
285   spamd_address_container * spamd_address_vector[32];
286
287   /* Check how many spamd servers we have
288      and register their addresses */
289   while ((address = string_nextinlist(&spamd_address_list_ptr, &sep,
290                                       NULL, 0)) != NULL)
291     {
292     const uschar * sublist;
293     int sublist_sep = -(int)' ';        /* default space-sep */
294     unsigned args;
295     uschar * s;
296
297     HDEBUG(D_acl) debug_printf("spamd: addr entry '%s'\n", address);
298     sd = (spamd_address_container *)store_get(sizeof(spamd_address_container));
299
300     for (sublist = address, args = 0, spamd_param_init(sd);
301          s = string_nextinlist(&sublist, &sublist_sep, NULL, 0);
302          args++
303          )
304       {
305         HDEBUG(D_acl) debug_printf("spamd:  addr parm '%s'\n", s);
306         switch (args)
307         {
308         case 0:   sd->hostspec = s;
309                   if (*s == '/') args++;        /* local; no port */
310                   break;
311         case 1:   sd->hostspec = string_sprintf("%s %s", sd->hostspec, s);
312                   break;
313         default:  spamd_param(s, sd);
314                   break;
315         }
316       }
317     if (args < 2)
318       {
319       log_write(0, LOG_MAIN,
320         "%s warning - invalid spamd address: '%s'", loglabel, address);
321       continue;
322       }
323
324     spamd_address_vector[num_servers] = sd;
325     if (++num_servers > 31)
326       break;
327     }
328
329   /* check if we have at least one server */
330   if (!num_servers)
331     {
332     log_write(0, LOG_MAIN|LOG_PANIC,
333        "%s no useable spamd server addresses in spamd_address configuration option.",
334        loglabel);
335     goto defer;
336     }
337
338   current_server = spamd_get_server(spamd_address_vector, num_servers);
339   sd = spamd_address_vector[current_server];
340   for(;;)
341     {
342     uschar * errstr;
343
344     debug_printf("trying server %s\n", sd->hostspec);
345
346     for (;;)
347       {
348       if (  (spamd_sock = ip_streamsocket(sd->hostspec, &errstr, 5)) >= 0
349          || sd->retry <= 0
350          )
351         break;
352       debug_printf("server %s: retry conn\n", sd->hostspec);
353       while (sd->retry > 0) sd->retry = sleep(sd->retry);
354       }
355     if (spamd_sock >= 0)
356       break;
357
358     log_write(0, LOG_MAIN, "%s spamd: %s", loglabel, errstr);
359     sd->is_failed = TRUE;
360
361     current_server = spamd_get_server(spamd_address_vector, num_servers);
362     if (current_server < 0)
363       {
364       log_write(0, LOG_MAIN|LOG_PANIC, "%s all spamd servers failed", loglabel);
365       goto defer;
366       }
367     sd = spamd_address_vector[current_server];
368     }
369   }
370
371 if (spamd_sock == -1)
372   {
373   log_write(0, LOG_MAIN|LOG_PANIC,
374       "programming fault, spamd_sock unexpectedly unset");
375   goto defer;
376   }
377
378 (void)fcntl(spamd_sock, F_SETFL, O_NONBLOCK);
379 /* now we are connected to spamd on spamd_sock */
380 if (sd->is_rspamd)
381   {                             /* rspamd variant */
382   uschar *req_str;
383   const char *helo;
384   const char *fcrdns;
385
386   req_str = string_sprintf("CHECK RSPAMC/1.3\r\nContent-length: %lu\r\n"
387     "Queue-Id: %s\r\nFrom: <%s>\r\nRecipient-Number: %d\r\n", mbox_size,
388     message_id, sender_address, recipients_count);
389   for (i = 0; i < recipients_count; i ++)
390     req_str = string_sprintf("%sRcpt: <%s>\r\n", req_str, recipients_list[i].address);
391   if ((helo = expand_string(US"$sender_helo_name")) != NULL && *helo != '\0')
392     req_str = string_sprintf("%sHelo: %s\r\n", req_str, helo);
393   if ((fcrdns = expand_string(US"$sender_host_name")) != NULL && *fcrdns != '\0')
394     req_str = string_sprintf("%sHostname: %s\r\n", req_str, fcrdns);
395   if (sender_host_address != NULL)
396     req_str = string_sprintf("%sIP: %s\r\n", req_str, sender_host_address);
397   req_str = string_sprintf("%s\r\n", req_str);
398   wrote = send(spamd_sock, req_str, Ustrlen(req_str), 0); 
399   }
400   else
401   {                             /* spamassassin variant */
402   (void)string_format(spamd_buffer,
403           sizeof(spamd_buffer),
404           "REPORT SPAMC/1.2\r\nUser: %s\r\nContent-length: %ld\r\n\r\n",
405           user_name,
406           mbox_size);
407   /* send our request */
408   wrote = send(spamd_sock, spamd_buffer, Ustrlen(spamd_buffer), 0);
409   }
410 if (wrote == -1)
411   {
412   (void)close(spamd_sock);
413   log_write(0, LOG_MAIN|LOG_PANIC,
414        "%s spamd send failed: %s", loglabel, strerror(errno));
415   goto defer;
416   }
417
418 /* now send the file */
419 /* spamd sometimes accepts conections but doesn't read data off
420  * the connection.  We make the file descriptor non-blocking so
421  * that the write will only write sufficient data without blocking
422  * and we poll the desciptor to make sure that we can write without
423  * blocking.  Short writes are gracefully handled and if the whole
424  * trasaction takes too long it is aborted.
425  * Note: poll() is not supported in OSX 10.2 and is reported to be
426  *       broken in more recent versions (up to 10.4).
427  */
428 #ifndef NO_POLL_H
429 pollfd.fd = spamd_sock;
430 pollfd.events = POLLOUT;
431 #endif
432 (void)fcntl(spamd_sock, F_SETFL, O_NONBLOCK);
433 do
434   {
435   read = fread(spamd_buffer,1,sizeof(spamd_buffer),mbox_file);
436   if (read > 0)
437     {
438     offset = 0;
439 again:
440 #ifndef NO_POLL_H
441     result = poll(&pollfd, 1, 1000);
442
443 /* Patch posted by Erik ? for OS X and applied by PH */
444 #else
445     select_tv.tv_sec = 1;
446     select_tv.tv_usec = 0;
447     FD_ZERO(&select_fd);
448     FD_SET(spamd_sock, &select_fd);
449     result = select(spamd_sock+1, NULL, &select_fd, NULL, &select_tv);
450 #endif
451 /* End Erik's patch */
452
453     if (result == -1 && errno == EINTR)
454       goto again;
455     else if (result < 1)
456       {
457       if (result == -1)
458         log_write(0, LOG_MAIN|LOG_PANIC,
459           "%s %s on spamd socket", loglabel, strerror(errno));
460       else
461         {
462         if (time(NULL) - start < sd->timeout)
463           goto again;
464         log_write(0, LOG_MAIN|LOG_PANIC,
465           "%s timed out writing spamd socket", loglabel);
466         }
467       (void)close(spamd_sock);
468       goto defer;
469       }
470
471     wrote = send(spamd_sock,spamd_buffer + offset,read - offset,0);
472     if (wrote == -1)
473       {
474       log_write(0, LOG_MAIN|LOG_PANIC,
475           "%s %s on spamd socket", loglabel, strerror(errno));
476       (void)close(spamd_sock);
477       goto defer;
478       }
479     if (offset + wrote != read)
480       {
481       offset += wrote;
482       goto again;
483       }
484     }
485   }
486 while (!feof(mbox_file) && !ferror(mbox_file));
487
488 if (ferror(mbox_file))
489   {
490   log_write(0, LOG_MAIN|LOG_PANIC,
491     "%s error reading spool file: %s", loglabel, strerror(errno));
492   (void)close(spamd_sock);
493   goto defer;
494   }
495
496 (void)fclose(mbox_file);
497
498 /* we're done sending, close socket for writing */
499 shutdown(spamd_sock,SHUT_WR);
500
501 /* read spamd response using what's left of the timeout.  */
502 memset(spamd_buffer, 0, sizeof(spamd_buffer));
503 offset = 0;
504 while ((i = ip_recv(spamd_sock,
505                    spamd_buffer + offset,
506                    sizeof(spamd_buffer) - offset - 1,
507                    sd->timeout - time(NULL) + start)) > 0 )
508   offset += i;
509
510 /* error handling */
511 if (i <= 0 && errno != 0)
512   {
513   log_write(0, LOG_MAIN|LOG_PANIC,
514        "%s error reading from spamd socket: %s", loglabel, strerror(errno));
515   (void)close(spamd_sock);
516   return DEFER;
517   }
518
519 /* reading done */
520 (void)close(spamd_sock);
521
522 if (sd->is_rspamd)
523   {                             /* rspamd variant of reply */
524   int r;
525   if ((r = sscanf(CS spamd_buffer,
526           "RSPAMD/%7s 0 EX_OK\r\nMetric: default; %7s %lf / %lf / %lf\r\n%n",
527           spamd_version, spamd_short_result, &spamd_score, &spamd_threshold,
528           &spamd_reject_score, &spamd_report_offset)) != 5)
529     {
530       log_write(0, LOG_MAIN|LOG_PANIC,
531                 "%s cannot parse spamd output: %d", loglabel, r);
532       return DEFER;
533     }
534   /* now parse action */
535   p = &spamd_buffer[spamd_report_offset];
536
537   if (Ustrncmp(p, "Action: ", sizeof("Action: ") - 1) == 0)
538     {
539     p += sizeof("Action: ") - 1;
540     q = &spam_action_buffer[0];
541     while (*p && *p != '\r' && (q - spam_action_buffer) < sizeof(spam_action_buffer) - 1)
542       *q++ = *p++;
543     *q = '\0';
544     }
545   }
546 else
547   {                             /* spamassassin */
548   /* dig in the spamd output and put the report in a multiline header,
549   if requested */
550   if (sscanf(CS spamd_buffer,
551        "SPAMD/%7s 0 EX_OK\r\nContent-length: %*u\r\n\r\n%lf/%lf\r\n%n",
552        spamd_version,&spamd_score,&spamd_threshold,&spamd_report_offset) != 3)
553     {
554       /* try to fall back to pre-2.50 spamd output */
555       if (sscanf(CS spamd_buffer,
556            "SPAMD/%7s 0 EX_OK\r\nSpam: %*s ; %lf / %lf\r\n\r\n%n",
557            spamd_version,&spamd_score,&spamd_threshold,&spamd_report_offset) != 3)
558         {
559         log_write(0, LOG_MAIN|LOG_PANIC,
560                   "%s cannot parse spamd output", loglabel);
561         return DEFER;
562         }
563     }
564
565   Ustrcpy(spam_action_buffer,
566     spamd_score >= spamd_threshold ? "reject" : "no action");
567   }
568
569 /* Create report. Since this is a multiline string,
570 we must hack it into shape first */
571 p = &spamd_buffer[spamd_report_offset];
572 q = spam_report_buffer;
573 while (*p != '\0')
574   {
575   /* skip \r */
576   if (*p == '\r')
577     {
578     p++;
579     continue;
580     }
581   *q++ = *p;
582   if (*p++ == '\n')
583     {
584     /* add an extra space after the newline to ensure
585     that it is treated as a header continuation line */
586     *q++ = ' ';
587     }
588   }
589 /* NULL-terminate */
590 *q-- = '\0';
591 /* cut off trailing leftovers */
592 while (*q <= ' ')
593   *q-- = '\0';
594
595 spam_report = spam_report_buffer;
596 spam_action = spam_action_buffer;
597
598 /* create spam bar */
599 spamd_score_char = spamd_score > 0 ? '+' : '-';
600 j = abs((int)(spamd_score));
601 i = 0;
602 if (j != 0)
603   while ((i < j) && (i <= MAX_SPAM_BAR_CHARS))
604      spam_bar_buffer[i++] = spamd_score_char;
605 else
606   {
607   spam_bar_buffer[0] = '/';
608   i = 1;
609   }
610 spam_bar_buffer[i] = '\0';
611 spam_bar = spam_bar_buffer;
612
613 /* create "float" spam score */
614 (void)string_format(spam_score_buffer, sizeof(spam_score_buffer),
615         "%.1f", spamd_score);
616 spam_score = spam_score_buffer;
617
618 /* create "int" spam score */
619 j = (int)((spamd_score + 0.001)*10);
620 (void)string_format(spam_score_int_buffer, sizeof(spam_score_int_buffer),
621         "%d", j);
622 spam_score_int = spam_score_int_buffer;
623
624 /* compare threshold against score */
625 spam_rc = spamd_score >= spamd_threshold
626   ? OK  /* spam as determined by user's threshold */
627   : FAIL;       /* not spam */
628
629 /* remember expanded spamd_address if needed */
630 if (spamd_address_work != spamd_address)
631   prev_spamd_address_work = string_copy(spamd_address_work);
632
633 /* remember user name and "been here" for it */
634 Ustrcpy(prev_user_name, user_name);
635 spam_ok = 1;
636
637 return override
638   ? OK          /* always return OK, no matter what the score */
639   : spam_rc;
640
641 defer:
642   (void)fclose(mbox_file);
643   return DEFER;
644 }
645
646 #endif
647 /* vi: aw ai sw=2
648 */