Add retry option to clamd and spamd. Bug 392
[exim.git] / src / src / malware.c
1 /*************************************************
2 *     Exim - an Internet mail transport agent    *
3 *************************************************/
4
5 /* Copyright (c) Tom Kistner <tom@duncanthrax.net> 2003-2014 */
6 /* License: GPL */
7
8 /* Code for calling virus (malware) scanners. Called from acl.c. */
9
10 #include "exim.h"
11 #ifdef WITH_CONTENT_SCAN
12
13 typedef enum {M_FPROTD, M_DRWEB, M_AVES, M_FSEC, M_KAVD, M_CMDL,
14                 M_SOPHIE, M_CLAMD, M_SOCK, M_MKSD, M_AVAST} scanner_t;
15 typedef enum {MC_NONE, MC_TCP, MC_UNIX, MC_STRM} contype_t;
16 static struct scan
17 {
18   scanner_t     scancode;
19   const uschar * name;
20   const uschar * options_default;
21   contype_t     conn;
22 } m_scans[] =
23 {
24   { M_FPROTD,   US"f-protd",    US"localhost 10200-10204",            MC_TCP },
25   { M_DRWEB,    US"drweb",      US"/usr/local/drweb/run/drwebd.sock", MC_STRM },
26   { M_AVES,     US"aveserver",  US"/var/run/aveserver",               MC_UNIX },
27   { M_FSEC,     US"fsecure",    US"/var/run/.fsav",                   MC_UNIX },
28   { M_KAVD,     US"kavdaemon",  US"/var/run/AvpCtl",                  MC_UNIX },
29   { M_CMDL,     US"cmdline",    NULL,                                 MC_NONE },
30   { M_SOPHIE,   US"sophie",     US"/var/run/sophie",                  MC_UNIX },
31   { M_CLAMD,    US"clamd",      US"/tmp/clamd",                       MC_NONE },
32   { M_SOCK,     US"sock",       US"/tmp/malware.sock",                MC_STRM },
33   { M_MKSD,     US"mksd",       NULL,                                 MC_NONE },
34   { M_AVAST,    US"avast",      US"/var/run/avast/scan.sock",         MC_STRM },
35   { -1,         NULL,           NULL, MC_NONE }         /* end-marker */
36 };
37
38 /* The maximum number of clamd servers that are supported in the configuration */
39 #define MAX_CLAMD_SERVERS 32
40 #define MAX_CLAMD_SERVERS_S "32"
41
42 typedef struct clamd_address {
43   uschar * hostspec;
44   unsigned tcp_port;
45   unsigned retry;
46 } clamd_address;
47
48 #ifndef nelements
49 # define nelements(arr) (sizeof(arr) / sizeof(arr[0]))
50 #endif
51
52
53 #define MALWARE_TIMEOUT 120     /* default timeout, seconds */
54
55
56 #define DRWEBD_SCAN_CMD             (1)     /* scan file, buffer or diskfile */
57 #define DRWEBD_RETURN_VIRUSES       (1<<0)   /* ask daemon return to us viruses names from report */
58 #define DRWEBD_IS_MAIL              (1<<19)  /* say to daemon that format is "archive MAIL" */
59
60 #define DERR_READ_ERR               (1<<0)   /* read error */
61 #define DERR_NOMEMORY               (1<<2)   /* no memory */
62 #define DERR_TIMEOUT                (1<<9)   /* scan timeout has run out */
63 #define DERR_BAD_CALL               (1<<15)  /* wrong command */
64
65
66 static const uschar * malware_regex_default = US ".+";
67 static const pcre * malware_default_re = NULL;
68
69 static const uschar * drweb_re_str = US "infected\\swith\\s*(.+?)$";
70 static const pcre * drweb_re = NULL;
71
72 static const uschar * fsec_re_str = US "\\S{0,5}INFECTED\\t[^\\t]*\\t([^\\t]+)\\t\\S*$";
73 static const pcre * fsec_re = NULL;
74
75 static const uschar * kav_re_sus_str = US "suspicion:\\s*(.+?)\\s*$";
76 static const uschar * kav_re_inf_str = US "infected:\\s*(.+?)\\s*$";
77 static const pcre * kav_re_sus = NULL;
78 static const pcre * kav_re_inf = NULL;
79
80 static const uschar * ava_re_clean_str = US "(?!\\\\)\\t\\[\\+\\]";
81 static const uschar * ava_re_virus_str = US "(?!\\\\)\\t\\[L\\]\\d\\.\\d\\t\\d\\s(.*)";
82 static const pcre * ava_re_clean = NULL;
83 static const pcre * ava_re_virus = NULL;
84
85
86
87 /******************************************************************************/
88
89 /* Routine to check whether a system is big- or little-endian.
90    Ripped from http://www.faqs.org/faqs/graphics/fileformats-faq/part4/section-7.html
91    Needed for proper kavdaemon implementation. Sigh. */
92 #define BIG_MY_ENDIAN      0
93 #define LITTLE_MY_ENDIAN   1
94 static int test_byte_order(void);
95 static inline int
96 test_byte_order()
97 {
98   short int word = 0x0001;
99   char *byte = (char *) &word;
100   return(byte[0] ? LITTLE_MY_ENDIAN : BIG_MY_ENDIAN);
101 }
102
103 BOOL malware_ok = FALSE;
104
105 /* Gross hacks for the -bmalware option; perhaps we should just create
106 the scan directory normally for that case, but look into rigging up the
107 needed header variables if not already set on the command-line? */
108 extern int spool_mbox_ok;
109 extern uschar spooled_message_id[17];
110
111
112
113 static inline int
114 malware_errlog_defer(const uschar * str)
115 {
116 log_write(0, LOG_MAIN|LOG_PANIC, "malware acl condition: %s", str);
117 return DEFER;
118 }
119
120 static int
121 m_errlog_defer(struct scan * scanent, const uschar * str)
122 {
123 return malware_errlog_defer(string_sprintf("%s: %s", scanent->name, str));
124 }
125 static int
126 m_errlog_defer_3(struct scan * scanent, const uschar * str,
127         int fd_to_close)
128 {
129 (void) close(fd_to_close);
130 return m_errlog_defer(scanent, str);
131 }
132
133 /*************************************************/
134
135 /* Only used by the Clamav code, which is working from a list of servers and
136 uses the returned in_addr to get a second connection to the same system.
137 */
138 static inline int
139 m_tcpsocket(const uschar * hostname, unsigned int port,
140         host_item * host, uschar ** errstr)
141 {
142 return ip_connectedsocket(SOCK_STREAM, hostname, port, port, 5, host, errstr);
143 }
144
145 static int
146 m_sock_send(int sock, uschar * buf, int cnt, uschar ** errstr)
147 {
148 if (send(sock, buf, cnt, 0) < 0)
149   {
150   int err = errno;
151   (void)close(sock);
152   *errstr = string_sprintf("unable to send to socket (%s): %s",
153          buf, strerror(err));
154   return -1;
155   }
156 return sock;
157 }
158
159 static const pcre *
160 m_pcre_compile(const uschar * re, uschar ** errstr)
161 {
162 const uschar * rerror;
163 int roffset;
164 const pcre * cre;
165
166 cre = pcre_compile(CS re, PCRE_COPT, (const char **)&rerror, &roffset, NULL);
167 if (!cre)
168   *errstr= string_sprintf("regular expression error in '%s': %s at offset %d",
169       re, rerror, roffset);
170 return cre;
171 }
172
173 uschar *
174 m_pcre_exec(const pcre * cre, uschar * text)
175 {
176 int ovector[10*3];
177 int i = pcre_exec(cre, NULL, CS text, Ustrlen(text), 0, 0,
178               ovector, nelements(ovector));
179 uschar * substr = NULL;
180 if (i >= 2)                             /* Got it */
181   pcre_get_substring(CS text, ovector, i, 1, (const char **) &substr);
182 return substr;
183 }
184
185 static const pcre *
186 m_pcre_nextinlist(const uschar ** list, int * sep,
187  char * listerr, uschar ** errstr)
188 {
189 const uschar * list_ele;
190 const pcre * cre = NULL;
191
192 if (!(list_ele = string_nextinlist(list, sep, NULL, 0)))
193   *errstr = US listerr;
194 else
195   cre = m_pcre_compile(CUS list_ele, errstr);
196 return cre;
197 }
198
199 /*
200  Simple though inefficient wrapper for reading a line.  Drop CRs and the
201  trailing newline. Can return early on buffer full. Null-terminate.
202  Apply initial timeout if no data ready.
203
204  Return: number of chars - zero for an empty line
205          -1 on EOF
206          -2 on timeout or error
207 */
208 static int
209 recv_line(int fd, uschar * buffer, int bsize, int tmo)
210 {
211 uschar * p = buffer;
212 ssize_t rcv;
213 BOOL ok = FALSE;
214
215 if (!fd_ready(fd, tmo-time(NULL)))
216   return -2;
217
218 /*XXX tmo handling assumes we always get a whole line */
219 /* read until \n */
220 errno = 0;
221 while ((rcv = read(fd, p, 1)) > 0)
222   {
223   ok = TRUE;
224   if (p-buffer > bsize-2) break;
225   if (*p == '\n') break;
226   if (*p != '\r') p++;
227   }
228 if (!ok)
229   {
230   DEBUG(D_acl) debug_printf("Malware scan: read %s (%s)\n",
231                 rcv==0 ? "EOF" : "error", strerror(errno));
232   return rcv==0 ? -1 : -2;
233   }
234 *p = '\0';
235
236 DEBUG(D_acl) debug_printf("Malware scan: read '%s'\n", buffer);
237 return p - buffer;
238 }
239
240 /* return TRUE iff size as requested */
241 static BOOL
242 recv_len(int sock, void * buf, int size, int tmo)
243 {
244 return fd_ready(sock, tmo-time(NULL))
245   ? recv(sock, buf, size, 0) == size
246   : FALSE;
247 }
248
249
250
251 /* ============= private routines for the "mksd" scanner type ============== */
252
253 #include <sys/uio.h>
254
255 static inline int
256 mksd_writev (int sock, struct iovec * iov, int iovcnt)
257 {
258 int i;
259
260 for (;;)
261   {
262   do
263     i = writev (sock, iov, iovcnt);
264   while (i < 0 && errno == EINTR);
265   if (i <= 0)
266     {
267     (void) malware_errlog_defer(
268             US"unable to write to mksd UNIX socket (/var/run/mksd/socket)");
269     return -1;
270     }
271   for (;;)      /* check for short write */
272     if (i >= iov->iov_len)
273       {
274       if (--iovcnt == 0)
275         return 0;
276       i -= iov->iov_len;
277       iov++;
278       }
279     else
280       {
281       iov->iov_len -= i;
282       iov->iov_base = CS iov->iov_base + i;
283       break;
284       }
285   }
286 }
287
288 static inline int
289 mksd_read_lines (int sock, uschar *av_buffer, int av_buffer_size, int tmo)
290 {
291 int offset = 0;
292 int i;
293
294 do
295   {
296   i = ip_recv(sock, av_buffer+offset, av_buffer_size-offset, tmo-time(NULL));
297   if (i <= 0)
298     {
299     (void) malware_errlog_defer(US"unable to read from mksd UNIX socket (/var/run/mksd/socket)");
300     return -1;
301     }
302
303   offset += i;
304   /* offset == av_buffer_size -> buffer full */
305   if (offset == av_buffer_size)
306     {
307     (void) malware_errlog_defer(US"malformed reply received from mksd");
308     return -1;
309     }
310   } while (av_buffer[offset-1] != '\n');
311
312 av_buffer[offset] = '\0';
313 return offset;
314 }
315
316 static inline int
317 mksd_parse_line(struct scan * scanent, char * line)
318 {
319 char *p;
320
321 switch (*line)
322   {
323   case 'O': /* OK */
324     return OK;
325
326   case 'E':
327   case 'A': /* ERR */
328     if ((p = strchr (line, '\n')) != NULL)
329       *p = '\0';
330     return m_errlog_defer(scanent,
331       string_sprintf("scanner failed: %s", line));
332
333   default: /* VIR */
334     if ((p = strchr (line, '\n')) != NULL)
335       {
336       *p = '\0';
337       if (  p-line > 5
338          && line[3] == ' '
339          && (p = strchr(line+4, ' ')) != NULL
340          && p-line > 4
341          )
342         {
343         *p = '\0';
344         malware_name = string_copy(US line+4);
345         return OK;
346         }
347       }
348     return m_errlog_defer(scanent,
349       string_sprintf("malformed reply received: %s", line));
350   }
351 }
352
353 static int
354 mksd_scan_packed(struct scan * scanent, int sock, const uschar * scan_filename,
355   int tmo)
356 {
357 struct iovec iov[3];
358 const char *cmd = "MSQ\n";
359 uschar av_buffer[1024];
360
361 iov[0].iov_base = (void *) cmd;
362 iov[0].iov_len = 3;
363 iov[1].iov_base = (void *) scan_filename;
364 iov[1].iov_len = Ustrlen(scan_filename);
365 iov[2].iov_base = (void *) (cmd + 3);
366 iov[2].iov_len = 1;
367
368 if (mksd_writev (sock, iov, 3) < 0)
369   return DEFER;
370
371 if (mksd_read_lines (sock, av_buffer, sizeof (av_buffer), tmo) < 0)
372   return DEFER;
373
374 return mksd_parse_line (scanent, CS av_buffer);
375 }
376
377
378 static int
379 clamd_option(clamd_address * cd, const uschar * optstr, int * subsep)
380 {
381 uschar * s;
382
383 cd->retry = 0;
384 while ((s = string_nextinlist(&optstr, subsep, NULL, 0)))
385   {
386   if (Ustrncmp(s, "retry=", 6) == 0)
387     {
388     int sec = readconf_readtime((s += 6), '\0', FALSE);
389     if (sec < 0)
390       return FAIL;
391     cd->retry = sec;
392     }
393   else
394     return FAIL;
395   }
396 }
397
398 /*************************************************
399 *          Scan content for malware              *
400 *************************************************/
401
402 /* This is an internal interface for scanning an email; the normal interface
403 is via malware(), or there's malware_in_file() used for testing/debugging.
404
405 Arguments:
406   malware_re    match condition for "malware="
407   eml_filename  the file holding the email to be scanned
408   timeout       if nonzero, non-default timeoutl
409   faking        whether or not we're faking this up for the -bmalware test
410
411 Returns:        Exim message processing code (OK, FAIL, DEFER, ...)
412                 where true means malware was found (condition applies)
413 */
414 static int
415 malware_internal(const uschar * malware_re, const uschar * eml_filename,
416   int timeout, BOOL faking)
417 {
418 int sep = 0;
419 const uschar *av_scanner_work = av_scanner;
420 uschar *scanner_name;
421 unsigned long mbox_size;
422 FILE *mbox_file;
423 const pcre *re;
424 uschar * errstr;
425 struct scan * scanent;
426 const uschar * scanner_options;
427 int sock = -1;
428 time_t tmo;
429
430 /* make sure the eml mbox file is spooled up */
431 if (!(mbox_file = spool_mbox(&mbox_size, faking ? eml_filename : NULL)))
432   return malware_errlog_defer(US"error while creating mbox spool file");
433
434 /* none of our current scanners need the mbox
435    file as a stream, so we can close it right away */
436 (void)fclose(mbox_file);
437
438 if (!malware_re)
439   return FAIL;          /* empty means "don't match anything" */
440
441 /* parse 1st option */
442   if ( (strcmpic(malware_re, US"false") == 0) ||
443      (Ustrcmp(malware_re,"0") == 0) )
444   return FAIL;          /* explicitly no matching */
445
446 /* special cases (match anything except empty) */
447 if (  strcmpic(malware_re,US"true") == 0
448    || Ustrcmp(malware_re,"*") == 0
449    || Ustrcmp(malware_re,"1") == 0
450    )
451   {
452   if (  !malware_default_re
453      && !(malware_default_re = m_pcre_compile(malware_regex_default, &errstr)))
454     return malware_errlog_defer(errstr);
455   malware_re = malware_regex_default;
456   re = malware_default_re;
457   }
458
459 /* compile the regex, see if it works */
460 else if (!(re = m_pcre_compile(malware_re, &errstr)))
461   return malware_errlog_defer(errstr);
462
463 /* Reset sep that is set by previous string_nextinlist() call */
464 sep = 0;
465
466 /* if av_scanner starts with a dollar, expand it first */
467 if (*av_scanner == '$')
468   {
469   if (!(av_scanner_work = expand_string(av_scanner)))
470     return malware_errlog_defer(
471          string_sprintf("av_scanner starts with $, but expansion failed: %s",
472          expand_string_message));
473
474   DEBUG(D_acl)
475     debug_printf("Expanded av_scanner global: %s\n", av_scanner_work);
476   /* disable result caching in this case */
477   malware_name = NULL;
478   malware_ok = FALSE;
479   }
480
481 /* Do not scan twice (unless av_scanner is dynamic). */
482 if (!malware_ok)
483   {
484   /* find the scanner type from the av_scanner option */
485   if (!(scanner_name = string_nextinlist(&av_scanner_work, &sep, NULL, 0)))
486     return malware_errlog_defer(US"av_scanner configuration variable is empty");
487   if (!timeout) timeout = MALWARE_TIMEOUT;
488   tmo = time(NULL) + timeout;
489
490   for (scanent = m_scans; ; scanent++)
491     {
492     if (!scanent->name)
493       return malware_errlog_defer(string_sprintf("unknown scanner type '%s'",
494         scanner_name));
495     if (strcmpic(scanner_name, US scanent->name) != 0)
496       continue;
497     if (!(scanner_options = string_nextinlist(&av_scanner_work, &sep, NULL, 0)))
498       scanner_options = scanent->options_default;
499     if (scanent->conn == MC_NONE)
500       break;
501     switch(scanent->conn)
502     {
503     case MC_TCP:  sock = ip_tcpsocket(scanner_options, &errstr, 5);       break;
504     case MC_UNIX: sock = ip_unixsocket(scanner_options, &errstr);         break;
505     case MC_STRM: sock = ip_streamsocket(scanner_options, &errstr, 5);  break;
506     default: /* compiler quietening */ break;
507     }
508     if (sock < 0)
509       return m_errlog_defer(scanent, errstr);
510     break;
511   }
512   DEBUG(D_acl) debug_printf("Malware scan: %s tmo %s\n", scanner_name, readconf_printtime(timeout));
513
514   switch (scanent->scancode)
515     {
516     case M_FPROTD: /* "f-protd" scanner type -------------------------------- */
517       {
518       uschar *fp_scan_option;
519       unsigned int detected=0, par_count=0;
520       uschar * scanrequest;
521       uschar buf[32768], *strhelper, *strhelper2;
522       uschar * malware_name_internal = NULL;
523       int len;
524
525       scanrequest = string_sprintf("GET %s", eml_filename);
526
527       while ((fp_scan_option = string_nextinlist(&av_scanner_work, &sep,
528                             NULL, 0)))
529         {
530         scanrequest = string_sprintf("%s%s%s", scanrequest,
531                                   par_count ? "%20" : "?", fp_scan_option);
532         par_count++;
533         }
534       scanrequest = string_sprintf("%s HTTP/1.0\r\n\r\n", scanrequest);
535       DEBUG(D_acl) debug_printf("Malware scan: issuing %s: %s\n",
536         scanner_name, scanrequest);
537
538       /* send scan request */
539       if (m_sock_send(sock, scanrequest, Ustrlen(scanrequest)+1, &errstr) < 0)
540         return m_errlog_defer(scanent, errstr);
541
542       while ((len = recv_line(sock, buf, sizeof(buf), tmo)) >= 0)
543         if (len > 0)
544           {
545           if (Ustrstr(buf, US"<detected type=\"") != NULL)
546             detected = 1;
547           else if (detected && (strhelper = Ustrstr(buf, US"<name>")))
548             {
549             if ((strhelper2 = Ustrstr(buf, US"</name>")) != NULL)
550               {
551               *strhelper2 = '\0';
552               malware_name_internal = string_copy(strhelper+6);
553               }
554             }
555           else if (Ustrstr(buf, US"<summary code=\""))
556             {
557             malware_name = Ustrstr(buf, US"<summary code=\"11\">")
558                 ? malware_name_internal : NULL;
559             break;
560             }
561           }
562       if (len < -1)
563         {
564         (void)close(sock);
565         return DEFER;
566         }
567       break;
568       } /* f-protd */
569
570     case M_DRWEB: /* "drweb" scanner type ----------------------------------- */
571   /* v0.1 - added support for tcp sockets          */
572   /* v0.0 - initial release -- support for unix sockets      */
573       {
574       int result;
575       off_t fsize;
576       unsigned int fsize_uint;
577       uschar * tmpbuf, *drweb_fbuf;
578       int drweb_rc, drweb_cmd, drweb_flags = 0x0000, drweb_fd,
579           drweb_vnum, drweb_slen, drweb_fin = 0x0000;
580
581       /* prepare variables */
582       drweb_cmd = htonl(DRWEBD_SCAN_CMD);
583       drweb_flags = htonl(DRWEBD_RETURN_VIRUSES | DRWEBD_IS_MAIL);
584
585       if (*scanner_options != '/')
586         {
587         /* calc file size */
588         if ((drweb_fd = open(CCS eml_filename, O_RDONLY)) == -1)
589           return m_errlog_defer_3(scanent,
590             string_sprintf("can't open spool file %s: %s",
591               eml_filename, strerror(errno)),
592             sock);
593
594         if ((fsize = lseek(drweb_fd, 0, SEEK_END)) == -1)
595           {
596           int err = errno;
597           (void)close(drweb_fd);
598           return m_errlog_defer_3(scanent,
599             string_sprintf("can't seek spool file %s: %s",
600               eml_filename, strerror(err)),
601             sock);
602           }
603         fsize_uint = (unsigned int) fsize;
604         if ((off_t)fsize_uint != fsize)
605           {
606           (void)close(drweb_fd);
607           return m_errlog_defer_3(scanent,
608             string_sprintf("seeking spool file %s, size overflow",
609               eml_filename),
610             sock);
611           }
612         drweb_slen = htonl(fsize);
613         lseek(drweb_fd, 0, SEEK_SET);
614
615         DEBUG(D_acl) debug_printf("Malware scan: issuing %s remote scan [%s]\n",
616             scanner_name, scanner_options);
617
618         /* send scan request */
619         if ((send(sock, &drweb_cmd, sizeof(drweb_cmd), 0) < 0) ||
620             (send(sock, &drweb_flags, sizeof(drweb_flags), 0) < 0) ||
621             (send(sock, &drweb_fin, sizeof(drweb_fin), 0) < 0) ||
622             (send(sock, &drweb_slen, sizeof(drweb_slen), 0) < 0))
623           {
624           (void)close(drweb_fd);
625           return m_errlog_defer_3(scanent, string_sprintf(
626             "unable to send commands to socket (%s)", scanner_options),
627             sock);
628           }
629
630         if (!(drweb_fbuf = (uschar *) malloc (fsize_uint)))
631           {
632           (void)close(drweb_fd);
633           return m_errlog_defer_3(scanent,
634             string_sprintf("unable to allocate memory %u for file (%s)",
635               fsize_uint, eml_filename),
636             sock);
637           }
638
639         if ((result = read (drweb_fd, drweb_fbuf, fsize)) == -1)
640           {
641           int err = errno;
642           (void)close(drweb_fd);
643           free(drweb_fbuf);
644           return m_errlog_defer_3(scanent,
645             string_sprintf("can't read spool file %s: %s",
646               eml_filename, strerror(err)),
647             sock);
648           }
649         (void)close(drweb_fd);
650
651         /* send file body to socket */
652         if (send(sock, drweb_fbuf, fsize, 0) < 0)
653           {
654           free(drweb_fbuf);
655           return m_errlog_defer_3(scanent, string_sprintf(
656             "unable to send file body to socket (%s)", scanner_options),
657             sock);
658           }
659         (void)close(drweb_fd);
660         }
661       else
662         {
663         drweb_slen = htonl(Ustrlen(eml_filename));
664
665         DEBUG(D_acl) debug_printf("Malware scan: issuing %s local scan [%s]\n",
666             scanner_name, scanner_options);
667
668         /* send scan request */
669         if ((send(sock, &drweb_cmd, sizeof(drweb_cmd), 0) < 0) ||
670             (send(sock, &drweb_flags, sizeof(drweb_flags), 0) < 0) ||
671             (send(sock, &drweb_slen, sizeof(drweb_slen), 0) < 0) ||
672             (send(sock, eml_filename, Ustrlen(eml_filename), 0) < 0) ||
673             (send(sock, &drweb_fin, sizeof(drweb_fin), 0) < 0))
674           return m_errlog_defer_3(scanent, string_sprintf(
675             "unable to send commands to socket (%s)", scanner_options),
676             sock);
677         }
678
679       /* wait for result */
680       if (!recv_len(sock, &drweb_rc, sizeof(drweb_rc), tmo))
681         return m_errlog_defer_3(scanent,
682                     US"unable to read return code", sock);
683       drweb_rc = ntohl(drweb_rc);
684
685       if (!recv_len(sock, &drweb_vnum, sizeof(drweb_vnum), tmo))
686         return m_errlog_defer_3(scanent,
687                             US"unable to read the number of viruses", sock);
688       drweb_vnum = ntohl(drweb_vnum);
689
690       /* "virus(es) found" if virus number is > 0 */
691       if (drweb_vnum)
692         {
693         int i;
694
695         /* setup default virus name */
696         malware_name = US"unknown";
697
698         /* set up match regex */
699         if (!drweb_re)
700           drweb_re = m_pcre_compile(drweb_re_str, &errstr);
701
702         /* read and concatenate virus names into one string */
703         for (i = 0; i < drweb_vnum; i++)
704           {
705           int size = 0, off = 0, ovector[10*3];
706           /* read the size of report */
707           if (!recv_len(sock, &drweb_slen, sizeof(drweb_slen), tmo))
708             return m_errlog_defer_3(scanent,
709                               US"cannot read report size", sock);
710           drweb_slen = ntohl(drweb_slen);
711           tmpbuf = store_get(drweb_slen);
712
713           /* read report body */
714           if (!recv_len(sock, tmpbuf, drweb_slen, tmo))
715             return m_errlog_defer_3(scanent,
716                               US"cannot read report string", sock);
717           tmpbuf[drweb_slen] = '\0';
718
719           /* try matcher on the line, grab substring */
720           result = pcre_exec(drweb_re, NULL, CS tmpbuf, Ustrlen(tmpbuf), 0, 0,
721                                   ovector, nelements(ovector));
722           if (result >= 2)
723             {
724             const char * pre_malware_nb;
725
726             pcre_get_substring(CS tmpbuf, ovector, result, 1, &pre_malware_nb);
727
728             if (i==0)   /* the first name we just copy to malware_name */
729               malware_name = string_append(NULL, &size, &off,
730                                           1, pre_malware_nb);
731
732             else        /* concatenate each new virus name to previous */
733               malware_name = string_append(malware_name, &size, &off,
734                                           2, "/", pre_malware_nb);
735
736             pcre_free_substring(pre_malware_nb);
737             }
738           }
739         }
740       else
741         {
742         const char *drweb_s = NULL;
743
744         if (drweb_rc & DERR_READ_ERR) drweb_s = "read error";
745         if (drweb_rc & DERR_NOMEMORY) drweb_s = "no memory";
746         if (drweb_rc & DERR_TIMEOUT)  drweb_s = "timeout";
747         if (drweb_rc & DERR_BAD_CALL) drweb_s = "wrong command";
748         /* retcodes DERR_SYMLINK, DERR_NO_REGFILE, DERR_SKIPPED.
749          * DERR_TOO_BIG, DERR_TOO_COMPRESSED, DERR_SPAM,
750          * DERR_CRC_ERROR, DERR_READSOCKET, DERR_WRITE_ERR
751          * and others are ignored */
752         if (drweb_s)
753           return m_errlog_defer_3(scanent,
754             string_sprintf("drweb daemon retcode 0x%x (%s)", drweb_rc, drweb_s),
755             sock);
756
757         /* no virus found */
758         malware_name = NULL;
759         }
760       break;
761       } /* drweb */
762
763     case M_AVES: /* "aveserver" scanner type -------------------------------- */
764       {
765       uschar buf[32768];
766       int result;
767
768       /* read aveserver's greeting and see if it is ready (2xx greeting) */
769       buf[0] = 0;
770       recv_line(sock, buf, sizeof(buf), tmo);
771
772       if (buf[0] != '2')                /* aveserver is having problems */
773         return m_errlog_defer_3(scanent,
774           string_sprintf("unavailable (Responded: %s).",
775                           ((buf[0] != 0) ? buf : (uschar *)"nothing") ),
776           sock);
777
778       /* prepare our command */
779       (void)string_format(buf, sizeof(buf), "SCAN bPQRSTUW %s\r\n",
780                                                 eml_filename);
781
782       /* and send it */
783       DEBUG(D_acl) debug_printf("Malware scan: issuing %s %s\n",
784         scanner_name, buf);
785       if (m_sock_send(sock, buf, Ustrlen(buf), &errstr) < 0)
786         return m_errlog_defer(scanent, errstr);
787
788       malware_name = NULL;
789       result = 0;
790       /* read response lines, find malware name and final response */
791       while (recv_line(sock, buf, sizeof(buf), tmo) > 0)
792         {
793         if (buf[0] == '2')
794           break;
795         if (buf[0] == '5')              /* aveserver is having problems */
796           {
797           result = m_errlog_defer(scanent,
798              string_sprintf("unable to scan file %s (Responded: %s).",
799                              eml_filename, buf));
800           break;
801           }
802         if (Ustrncmp(buf,"322",3) == 0)
803           {
804           uschar *p = Ustrchr(&buf[4], ' ');
805           *p = '\0';
806           malware_name = string_copy(&buf[4]);
807           }
808         }
809
810       if (m_sock_send(sock, US"quit\r\n", 6, &errstr) < 0)
811         return m_errlog_defer(scanent, errstr);
812
813       /* read aveserver's greeting and see if it is ready (2xx greeting) */
814       buf[0] = 0;
815       recv_line(sock, buf, sizeof(buf), tmo);
816
817       if (buf[0] != '2')                /* aveserver is having problems */
818         return m_errlog_defer_3(scanent,
819           string_sprintf("unable to quit dialogue (Responded: %s).",
820                         ((buf[0] != 0) ? buf : (uschar *)"nothing") ),
821           sock);
822
823       if (result == DEFER)
824         {
825         (void)close(sock);
826         return DEFER;
827         }
828       break;
829       } /* aveserver */
830
831     case M_FSEC: /* "fsecure" scanner type ---------------------------------- */
832       {
833       int i, j, bread = 0;
834       uschar * file_name;
835       uschar av_buffer[1024];
836       static uschar *cmdopt[] = { US"CONFIGURE\tARCHIVE\t1\n",
837                                       US"CONFIGURE\tTIMEOUT\t0\n",
838                                       US"CONFIGURE\tMAXARCH\t5\n",
839                                       US"CONFIGURE\tMIME\t1\n" };
840
841       malware_name = NULL;
842
843       DEBUG(D_acl) debug_printf("Malware scan: issuing %s scan [%s]\n",
844           scanner_name, scanner_options);
845       /* pass options */
846       memset(av_buffer, 0, sizeof(av_buffer));
847       for (i = 0; i != nelements(cmdopt); i++)
848         {
849
850         if (m_sock_send(sock, cmdopt[i], Ustrlen(cmdopt[i]), &errstr) < 0)
851           return m_errlog_defer(scanent, errstr);
852
853         bread = ip_recv(sock, av_buffer, sizeof(av_buffer), tmo-time(NULL));
854         if (bread > 0) av_buffer[bread]='\0';
855         if (bread < 0)
856           return m_errlog_defer_3(scanent,
857             string_sprintf("unable to read answer %d (%s)", i, strerror(errno)),
858             sock);
859         for (j = 0; j < bread; j++)
860           if (av_buffer[j] == '\r' || av_buffer[j] == '\n')
861             av_buffer[j] ='@';
862         }
863
864       /* pass the mailfile to fsecure */
865       file_name = string_sprintf("SCAN\t%s\n", eml_filename);
866
867       if (m_sock_send(sock, file_name, Ustrlen(file_name), &errstr) < 0)
868         return m_errlog_defer(scanent, errstr);
869
870       /* set up match */
871       /* todo also SUSPICION\t */
872       if (!fsec_re)
873         fsec_re = m_pcre_compile(fsec_re_str, &errstr);
874
875       /* read report, linewise. Apply a timeout as the Fsecure daemon
876       sometimes wants an answer to "PING" but they won't tell us what */
877         {
878         uschar * p = av_buffer;
879         uschar * q;
880
881         for (;;)
882           {
883           errno = ETIME;
884           i =  av_buffer+sizeof(av_buffer)-p;
885           if ((bread= ip_recv(sock, p, i-1, tmo-time(NULL))) < 0)
886             return m_errlog_defer_3(scanent,
887               string_sprintf("unable to read result (%s)", strerror(errno)),
888               sock);
889
890           for (p[bread] = '\0'; q = strchr(p, '\n'); p = q+1)
891             {
892             *q = '\0';
893
894             /* Really search for virus again? */
895             if (!malware_name)
896               /* try matcher on the line, grab substring */
897               malware_name = m_pcre_exec(fsec_re, p);
898
899             if (Ustrstr(p, "OK\tScan ok."))
900               goto fsec_found;
901             }
902
903           /* copy down the trailing partial line then read another chunk */
904           i =  av_buffer+sizeof(av_buffer)-p;
905           memmove(av_buffer, p, i);
906           p = av_buffer+i;
907           }
908         }
909
910       fsec_found:
911         break;
912       } /* fsecure */
913
914     case M_KAVD: /* "kavdaemon" scanner type -------------------------------- */
915       {
916       time_t t;
917       uschar tmpbuf[1024];
918       uschar * scanrequest;
919       int kav_rc;
920       unsigned long kav_reportlen, bread;
921       const pcre *kav_re;
922       uschar *p;
923
924       /* get current date and time, build scan request */
925       time(&t);
926       /* pdp note: before the eml_filename parameter, this scanned the
927       directory; not finding documentation, so we'll strip off the directory.
928       The side-effect is that the test framework scanning may end up in
929       scanning more than was requested, but for the normal interface, this is
930       fine. */
931
932       strftime(CS tmpbuf, sizeof(tmpbuf), "%d %b %H:%M:%S", localtime(&t));
933       scanrequest = string_sprintf("<0>%s:%s", CS tmpbuf, eml_filename);
934       p = Ustrrchr(scanrequest, '/');
935       if (p)
936         *p = '\0';
937
938       DEBUG(D_acl) debug_printf("Malware scan: issuing %s scan [%s]\n",
939           scanner_name, scanner_options);
940
941       /* send scan request */
942       if (m_sock_send(sock, scanrequest, Ustrlen(scanrequest)+1, &errstr) < 0)
943         return m_errlog_defer(scanent, errstr);
944
945       /* wait for result */
946       if (!recv_len(sock, tmpbuf, 2, tmo))
947         return m_errlog_defer_3(scanent,
948                             US"unable to read 2 bytes from socket.", sock);
949
950       /* get errorcode from one nibble */
951       kav_rc = tmpbuf[ test_byte_order()==LITTLE_MY_ENDIAN ? 0 : 1 ] & 0x0F;
952       switch(kav_rc)
953       {
954       case 5: case 6: /* improper kavdaemon configuration */
955         return m_errlog_defer_3(scanent,
956                 US"please reconfigure kavdaemon to NOT disinfect or remove infected files.",
957                 sock);
958       case 1:
959         return m_errlog_defer_3(scanent,
960                 US"reported 'scanning not completed' (code 1).", sock);
961       case 7:
962         return m_errlog_defer_3(scanent,
963                 US"reported 'kavdaemon damaged' (code 7).", sock);
964       }
965
966       /* code 8 is not handled, since it is ambigous. It appears mostly on
967       bounces where part of a file has been cut off */
968
969       /* "virus found" return codes (2-4) */
970       if (kav_rc > 1 && kav_rc < 5)
971         {
972         int report_flag = 0;
973
974         /* setup default virus name */
975         malware_name = US"unknown";
976
977         report_flag = tmpbuf[ test_byte_order() == LITTLE_MY_ENDIAN ? 1 : 0 ];
978
979         /* read the report, if available */
980         if (report_flag == 1)
981           {
982           /* read report size */
983           if (!recv_len(sock, &kav_reportlen, 4, tmo))
984             return m_errlog_defer_3(scanent,
985                   US"cannot read report size", sock);
986
987           /* it's possible that avp returns av_buffer[1] == 1 but the
988           reportsize is 0 (!?) */
989           if (kav_reportlen > 0)
990             {
991             /* set up match regex, depends on retcode */
992             if (kav_rc == 3)
993               {
994               if (!kav_re_sus) kav_re_sus = m_pcre_compile(kav_re_sus_str, &errstr);
995               kav_re = kav_re_sus;
996               }
997             else
998               {
999               if (!kav_re_inf) kav_re_inf = m_pcre_compile(kav_re_inf_str, &errstr);
1000               kav_re = kav_re_inf;
1001               }
1002
1003             /* read report, linewise */
1004             while (kav_reportlen > 0)
1005               {
1006               if ((bread = recv_line(sock, tmpbuf, sizeof(tmpbuf), tmo)) < 0)
1007                 break;
1008               kav_reportlen -= bread+1;
1009
1010               /* try matcher on the line, grab substring */
1011               if ((malware_name = m_pcre_exec(kav_re, tmpbuf)))
1012                 break;
1013               }
1014             }
1015           }
1016         }
1017       else /* no virus found */
1018         malware_name = NULL;
1019
1020       break;
1021       }
1022
1023     case M_CMDL: /* "cmdline" scanner type ---------------------------------- */
1024       {
1025       const uschar *cmdline_scanner = scanner_options;
1026       const pcre *cmdline_trigger_re;
1027       const pcre *cmdline_regex_re;
1028       uschar * file_name;
1029       uschar * commandline;
1030       void (*eximsigchld)(int);
1031       void (*eximsigpipe)(int);
1032       FILE *scanner_out = NULL;
1033       int scanner_fd;
1034       FILE *scanner_record = NULL;
1035       uschar linebuffer[32767];
1036       int rcnt;
1037       int trigger = 0;
1038       uschar *p;
1039
1040       if (!cmdline_scanner)
1041         return m_errlog_defer(scanent, errstr);
1042
1043       /* find scanner output trigger */
1044       cmdline_trigger_re = m_pcre_nextinlist(&av_scanner_work, &sep,
1045                                 "missing trigger specification", &errstr);
1046       if (!cmdline_trigger_re)
1047         return m_errlog_defer(scanent, errstr);
1048
1049       /* find scanner name regex */
1050       cmdline_regex_re = m_pcre_nextinlist(&av_scanner_work, &sep,
1051                           "missing virus name regex specification", &errstr);
1052       if (!cmdline_regex_re)
1053         return m_errlog_defer(scanent, errstr);
1054
1055       /* prepare scanner call; despite the naming, file_name holds a directory
1056       name which is documented as the value given to %s. */
1057
1058       file_name = string_copy(eml_filename);
1059       p = Ustrrchr(file_name, '/');
1060       if (p)
1061         *p = '\0';
1062       commandline = string_sprintf(CS cmdline_scanner, file_name);
1063
1064       /* redirect STDERR too */
1065       commandline = string_sprintf("%s 2>&1", commandline);
1066
1067       DEBUG(D_acl) debug_printf("Malware scan: issuing %s scan [%s]\n",
1068               scanner_name, commandline);
1069
1070       /* store exims signal handlers */
1071       eximsigchld = signal(SIGCHLD,SIG_DFL);
1072       eximsigpipe = signal(SIGPIPE,SIG_DFL);
1073
1074       if (!(scanner_out = popen(CS commandline,"r")))
1075         {
1076         int err = errno;
1077         signal(SIGCHLD,eximsigchld); signal(SIGPIPE,eximsigpipe);
1078         return m_errlog_defer(scanent,
1079           string_sprintf("call (%s) failed: %s.", commandline, strerror(err)));
1080         }
1081       scanner_fd = fileno(scanner_out);
1082
1083       file_name = string_sprintf("%s/scan/%s/%s_scanner_output",
1084                                 spool_directory, message_id, message_id);
1085
1086       if (!(scanner_record = modefopen(file_name, "wb", SPOOL_MODE)))
1087         {
1088         int err = errno;
1089         (void) pclose(scanner_out);
1090         signal(SIGCHLD,eximsigchld); signal(SIGPIPE,eximsigpipe);
1091         return m_errlog_defer(scanent, string_sprintf(
1092             "opening scanner output file (%s) failed: %s.",
1093             file_name, strerror(err)));
1094         }
1095
1096       /* look for trigger while recording output */
1097       while ((rcnt = recv_line(scanner_fd, linebuffer,
1098                       sizeof(linebuffer), tmo)))
1099         {
1100         if (rcnt < 0)
1101           if (rcnt == -1)
1102             break;
1103           else
1104             {
1105             int err = errno;
1106             (void) pclose(scanner_out);
1107             signal(SIGCHLD,eximsigchld); signal(SIGPIPE,eximsigpipe);
1108             return m_errlog_defer(scanent, string_sprintf(
1109                 "unable to read from scanner (%s): %s",
1110                 commandline, strerror(err)));
1111             }
1112
1113         if (Ustrlen(linebuffer) > fwrite(linebuffer, 1, Ustrlen(linebuffer), scanner_record))
1114           {
1115           /* short write */
1116           (void) pclose(scanner_out);
1117           signal(SIGCHLD,eximsigchld); signal(SIGPIPE,eximsigpipe);
1118           return m_errlog_defer(scanent, string_sprintf(
1119             "short write on scanner output file (%s).", file_name));
1120           }
1121         putc('\n', scanner_record);
1122         /* try trigger match */
1123         if (  !trigger
1124            && regex_match_and_setup(cmdline_trigger_re, linebuffer, 0, -1)
1125            )
1126           trigger = 1;
1127         }
1128
1129       (void)fclose(scanner_record);
1130       sep = pclose(scanner_out);
1131       signal(SIGCHLD,eximsigchld); signal(SIGPIPE,eximsigpipe);
1132       if (sep != 0)
1133           return m_errlog_defer(scanent,
1134               sep == -1
1135               ? string_sprintf("running scanner failed: %s", strerror(sep))
1136               : string_sprintf("scanner returned error code: %d", sep));
1137
1138       if (trigger)
1139         {
1140         uschar * s;
1141         /* setup default virus name */
1142         malware_name = US"unknown";
1143
1144         /* re-open the scanner output file, look for name match */
1145         scanner_record = fopen(CS file_name, "rb");
1146         while (fgets(CS linebuffer, sizeof(linebuffer), scanner_record))
1147           {
1148           /* try match */
1149           if ((s = m_pcre_exec(cmdline_regex_re, linebuffer)))
1150             malware_name = s;
1151           }
1152         (void)fclose(scanner_record);
1153         }
1154       else /* no virus found */
1155         malware_name = NULL;
1156       break;
1157       } /* cmdline */
1158
1159     case M_SOPHIE: /* "sophie" scanner type --------------------------------- */
1160       {
1161       int bread = 0;
1162       uschar *p;
1163       uschar * file_name;
1164       uschar av_buffer[1024];
1165
1166       /* pass the scan directory to sophie */
1167       file_name = string_copy(eml_filename);
1168       if ((p = Ustrrchr(file_name, '/')))
1169         *p = '\0';
1170
1171       DEBUG(D_acl) debug_printf("Malware scan: issuing %s scan [%s]\n",
1172           scanner_name, scanner_options);
1173
1174       if (  write(sock, file_name, Ustrlen(file_name)) < 0
1175          || write(sock, "\n", 1) != 1
1176          )
1177         return m_errlog_defer_3(scanent,
1178           string_sprintf("unable to write to UNIX socket (%s)", scanner_options),
1179           sock);
1180
1181       /* wait for result */
1182       memset(av_buffer, 0, sizeof(av_buffer));
1183       if ((bread = ip_recv(sock, av_buffer, sizeof(av_buffer), tmo-time(NULL))) <= 0)
1184         return m_errlog_defer_3(scanent,
1185           string_sprintf("unable to read from UNIX socket (%s)", scanner_options),
1186           sock);
1187
1188       /* infected ? */
1189       if (av_buffer[0] == '1') {
1190         uschar * s = Ustrchr(av_buffer, '\n');
1191         if (s)
1192           *s = '\0';
1193         malware_name = string_copy(&av_buffer[2]);
1194       }
1195       else if (!strncmp(CS av_buffer, "-1", 2))
1196         return m_errlog_defer_3(scanent, US"scanner reported error", sock);
1197       else /* all ok, no virus */
1198         malware_name = NULL;
1199
1200       break;
1201       }
1202
1203     case M_CLAMD: /* "clamd" scanner type ----------------------------------- */
1204       {
1205 /* This code was originally contributed by David Saez */
1206 /* There are three scanning methods available to us:
1207 *  (1) Use the SCAN command, pointing to a file in the filesystem
1208 *  (2) Use the STREAM command, send the data on a separate port
1209 *  (3) Use the zINSTREAM command, send the data inline
1210 * The zINSTREAM command was introduced with ClamAV 0.95, which marked
1211 * STREAM deprecated; see: http://wiki.clamav.net/bin/view/Main/UpgradeNotes095
1212 * In Exim, we use SCAN if using a Unix-domain socket or explicitly told that
1213 * the TCP-connected daemon is actually local; otherwise we use zINSTREAM unless
1214 * WITH_OLD_CLAMAV_STREAM is defined.
1215 * See Exim bug 926 for details.  */
1216
1217       uschar *p, *vname, *result_tag, *response_end;
1218       int bread=0;
1219       uschar * file_name;
1220       uschar av_buffer[1024];
1221       uschar *hostname = US"";
1222       host_item connhost;
1223       uschar *clamav_fbuf;
1224       int clam_fd, result;
1225       off_t fsize;
1226       unsigned int fsize_uint;
1227       BOOL use_scan_command = FALSE;
1228       clamd_address * cv[MAX_CLAMD_SERVERS];
1229       int num_servers = 0;
1230 #ifdef WITH_OLD_CLAMAV_STREAM
1231       unsigned int port;
1232       uschar av_buffer2[1024];
1233       int sockData;
1234 #else
1235       uint32_t send_size, send_final_zeroblock;
1236 #endif
1237
1238       /*XXX if unixdomain socket, only one server supported. Needs fixing;
1239       there's no reason we should not mix local and remote servers */
1240
1241       if (*scanner_options == '/')
1242         {
1243         clamd_address * cd;
1244         const uschar * sublist;
1245         int subsep = ' ';
1246
1247         /* Local file; so we def want to use_scan_command and don't want to try
1248          * passing IP/port combinations */
1249         use_scan_command = TRUE;
1250         cd = (clamd_address *) store_get(sizeof(clamd_address));
1251
1252         /* extract socket-path part */
1253         sublist = scanner_options;
1254         cd->hostspec = string_nextinlist(&sublist, &subsep, NULL, 0);
1255
1256         /* parse options */
1257         if (clamd_option(cd, sublist, &subsep) != OK)
1258           return m_errlog_defer(scanent,
1259             string_sprintf("bad option '%s'", scanner_options));
1260         cv[0] = cd;
1261         }
1262       else
1263         {
1264         /* Go through the rest of the list of host/port and construct an array
1265          * of servers to try. The first one is the bit we just passed from
1266          * scanner_options so process that first and then scan the remainder of
1267          * the address buffer */
1268         do
1269           {
1270           clamd_address * cd;
1271           const uschar * sublist;
1272           int subsep = ' ';
1273           uschar * s;
1274
1275           /* The 'local' option means use the SCAN command over the network
1276            * socket (ie common file storage in use) */
1277           /*XXX we could accept this also as a local option? */
1278           if (strcmpic(scanner_options, US"local") == 0)
1279             {
1280             use_scan_command = TRUE;
1281             continue;
1282             }
1283
1284           cd = (clamd_address *) store_get(sizeof(clamd_address));
1285
1286           /* extract host and port part */
1287           sublist = scanner_options;
1288           if (!(cd->hostspec = string_nextinlist(&sublist, &subsep, NULL, 0)))
1289             {
1290             (void) m_errlog_defer(scanent,
1291                       string_sprintf("missing address: '%s'", scanner_options));
1292             continue;
1293             }
1294           if (!(s = string_nextinlist(&sublist, &subsep, NULL, 0)))
1295             {
1296             (void) m_errlog_defer(scanent,
1297                       string_sprintf("missing port: '%s'", scanner_options));
1298             continue;
1299             }
1300           cd->tcp_port = atoi(s);
1301
1302           /* parse options */
1303           /*XXX should these options be common over scanner types? */
1304           if (clamd_option(cd, sublist, &subsep) != OK)
1305             {
1306             return m_errlog_defer(scanent,
1307               string_sprintf("bad option '%s'", scanner_options));
1308             continue;
1309             }
1310
1311           cv[num_servers++] = cd;
1312           if (num_servers >= MAX_CLAMD_SERVERS)
1313             {
1314             (void) m_errlog_defer(scanent,
1315                   US"More than " MAX_CLAMD_SERVERS_S " clamd servers "
1316                   "specified; only using the first " MAX_CLAMD_SERVERS_S );
1317             break;
1318             }
1319           } while ((scanner_options = string_nextinlist(&av_scanner_work, &sep,
1320                                         NULL, 0)));
1321
1322         /* check if we have at least one server */
1323         if (!num_servers)
1324           return m_errlog_defer(scanent,
1325             US"no useable server addresses in malware configuration option.");
1326         }
1327
1328       /* See the discussion of response formats below to see why we really
1329       don't like colons in filenames when passing filenames to ClamAV. */
1330       if (use_scan_command && Ustrchr(eml_filename, ':'))
1331         return m_errlog_defer(scanent,
1332           string_sprintf("local/SCAN mode incompatible with" \
1333             " : in path to email filename [%s]", eml_filename));
1334
1335       /* We have some network servers specified */
1336       if (num_servers)
1337         {
1338         /* Confirmed in ClamAV source (0.95.3) that the TCPAddr option of clamd
1339          * only supports AF_INET, but we should probably be looking to the
1340          * future and rewriting this to be protocol-independent anyway. */
1341
1342         while (num_servers > 0)
1343           {
1344           int i = random_number( num_servers );
1345           clamd_address * cd = cv[i];
1346
1347           DEBUG(D_acl) debug_printf("trying server name %s, port %u\n",
1348                          cd->hostspec, cd->tcp_port);
1349
1350           /* Lookup the host. This is to ensure that we connect to the same IP
1351            * on both connections (as one host could resolve to multiple ips) */
1352           for (;;)
1353             {
1354             sock= m_tcpsocket(cd->hostspec, cd->tcp_port, &connhost, &errstr);
1355             if (sock >= 0)
1356               {
1357               /* Connection successfully established with a server */
1358               hostname = cd->hostspec;
1359               break;
1360               }
1361             if (cd->retry <= 0) break;
1362             while (cd->retry > 0) cd->retry = sleep(cd->retry);
1363             }
1364           if (sock >= 0)
1365             break;
1366
1367           log_write(0, LOG_MAIN, "malware acl condition: %s: %s",
1368             scanent->name, errstr);
1369
1370           /* Remove the server from the list. XXX We should free the memory */
1371           num_servers--;
1372           for (; i < num_servers; i++)
1373             cv[i] = cv[i+1];
1374           }
1375
1376         if (num_servers == 0)
1377           return m_errlog_defer(scanent, US"all servers failed");
1378         }
1379       else
1380         for (;;)
1381           {
1382           if ((sock = ip_unixsocket(cv[0]->hostspec, &errstr)) >= 0)
1383             {
1384             hostname = cv[0]->hostspec;
1385             break;
1386             }
1387           if (cv[0]->retry <= 0)
1388             return m_errlog_defer(scanent, errstr);
1389           while (cv[0]->retry > 0) cv[0]->retry = sleep(cv[0]->retry);
1390           }
1391
1392       /* have socket in variable "sock"; command to use is semi-independent of
1393        * the socket protocol.  We use SCAN if is local (either Unix/local
1394        * domain socket, or explicitly told local) else we stream the data.
1395        * How we stream the data depends upon how we were built.  */
1396
1397       if (!use_scan_command)
1398         {
1399 #ifdef WITH_OLD_CLAMAV_STREAM
1400         /* "STREAM\n" command, get back a "PORT <N>\n" response, send data to
1401          * that port on a second connection; then in the scan-method-neutral
1402          * part, read the response back on the original connection. */
1403
1404         DEBUG(D_acl) debug_printf(
1405             "Malware scan: issuing %s old-style remote scan (PORT)\n",
1406             scanner_name);
1407
1408         /* Pass the string to ClamAV (7 = "STREAM\n") */
1409         if (m_sock_send(sock, US"STREAM\n", 7, &errstr) < 0)
1410           return m_errlog_defer(scanent, errstr);
1411
1412         memset(av_buffer2, 0, sizeof(av_buffer2));
1413         bread = ip_recv(sock, av_buffer2, sizeof(av_buffer2), tmo-time(NULL));
1414
1415         if (bread < 0)
1416           return m_errlog_defer_3(scanent,
1417             string_sprintf("unable to read PORT from socket (%s)",
1418                 strerror(errno)),
1419             sock);
1420
1421         if (bread == sizeof(av_buffer2))
1422           return m_errlog_defer_3(scanent, "buffer too small", sock);
1423
1424         if (!(*av_buffer2))
1425           return m_errlog_defer_3(scanent, "ClamAV returned null", sock);
1426
1427         av_buffer2[bread] = '\0';
1428         if( sscanf(CS av_buffer2, "PORT %u\n", &port) != 1 )
1429           return m_errlog_defer_3(scanent,
1430             string_sprintf("Expected port information from clamd, got '%s'",
1431               av_buffer2),
1432             sock);
1433
1434         sockData = m_tcpsocket(connhost.address, port, NULL, &errstr);
1435         if (sockData < 0)
1436           return m_errlog_defer_3(scanent, errstr, sock);
1437
1438 # define CLOSE_SOCKDATA (void)close(sockData)
1439 #else /* WITH_OLD_CLAMAV_STREAM not defined */
1440         /* New protocol: "zINSTREAM\n" followed by a sequence of <length><data>
1441         chunks, <n> a 4-byte number (network order), terminated by a zero-length
1442         chunk. */
1443
1444         DEBUG(D_acl) debug_printf(
1445             "Malware scan: issuing %s new-style remote scan (zINSTREAM)\n",
1446             scanner_name);
1447
1448         /* Pass the string to ClamAV (10 = "zINSTREAM\0") */
1449         if (send(sock, "zINSTREAM", 10, 0) < 0)
1450           return m_errlog_defer_3(scanent,
1451             string_sprintf("unable to send zINSTREAM to socket (%s)",
1452               strerror(errno)),
1453             sock);
1454
1455 # define CLOSE_SOCKDATA /**/
1456 #endif
1457
1458         /* calc file size */
1459         if ((clam_fd = open(CS eml_filename, O_RDONLY)) < 0)
1460           {
1461           int err = errno;
1462           CLOSE_SOCKDATA;
1463           return m_errlog_defer_3(scanent,
1464             string_sprintf("can't open spool file %s: %s",
1465               eml_filename, strerror(err)),
1466             sock);
1467           }
1468         if ((fsize = lseek(clam_fd, 0, SEEK_END)) < 0)
1469           {
1470           int err = errno;
1471           CLOSE_SOCKDATA; (void)close(clam_fd);
1472           return m_errlog_defer_3(scanent,
1473             string_sprintf("can't seek spool file %s: %s",
1474               eml_filename, strerror(err)),
1475             sock);
1476           }
1477         fsize_uint = (unsigned int) fsize;
1478         if ((off_t)fsize_uint != fsize)
1479           {
1480           CLOSE_SOCKDATA; (void)close(clam_fd);
1481           return m_errlog_defer_3(scanent,
1482             string_sprintf("seeking spool file %s, size overflow",
1483               eml_filename),
1484             sock);
1485           }
1486         lseek(clam_fd, 0, SEEK_SET);
1487
1488         if (!(clamav_fbuf = (uschar *) malloc (fsize_uint)))
1489           {
1490           CLOSE_SOCKDATA; (void)close(clam_fd);
1491           return m_errlog_defer_3(scanent,
1492             string_sprintf("unable to allocate memory %u for file (%s)",
1493               fsize_uint, eml_filename),
1494             sock);
1495           }
1496
1497         if ((result = read(clam_fd, clamav_fbuf, fsize_uint)) < 0)
1498           {
1499           int err = errno;
1500           free(clamav_fbuf); CLOSE_SOCKDATA; (void)close(clam_fd);
1501           return m_errlog_defer_3(scanent,
1502             string_sprintf("can't read spool file %s: %s",
1503               eml_filename, strerror(err)),
1504             sock);
1505           }
1506         (void)close(clam_fd);
1507
1508         /* send file body to socket */
1509 #ifdef WITH_OLD_CLAMAV_STREAM
1510         if (send(sockData, clamav_fbuf, fsize_uint, 0) < 0)
1511           {
1512           free(clamav_fbuf); CLOSE_SOCKDATA;
1513           return m_errlog_defer_3(scanent,
1514             string_sprintf("unable to send file body to socket (%s:%u)",
1515               hostname, port),
1516             sock);
1517           }
1518 #else
1519         send_size = htonl(fsize_uint);
1520         send_final_zeroblock = 0;
1521         if ((send(sock, &send_size, sizeof(send_size), 0) < 0) ||
1522             (send(sock, clamav_fbuf, fsize_uint, 0) < 0) ||
1523             (send(sock, &send_final_zeroblock, sizeof(send_final_zeroblock), 0) < 0))
1524           {
1525           free(clamav_fbuf);
1526           return m_errlog_defer_3(scanent,
1527             string_sprintf("unable to send file body to socket (%s)", hostname),
1528             sock);
1529           }
1530 #endif
1531
1532         free(clamav_fbuf);
1533
1534         CLOSE_SOCKDATA;
1535 #undef CLOSE_SOCKDATA
1536         }
1537       else
1538         { /* use scan command */
1539         /* Send a SCAN command pointing to a filename; then in the then in the
1540          * scan-method-neutral part, read the response back */
1541
1542 /* ================================================================= */
1543
1544         /* Prior to the reworking post-Exim-4.72, this scanned a directory,
1545         which dates to when ClamAV needed us to break apart the email into the
1546         MIME parts (eg, with the now deprecated demime condition coming first).
1547         Some time back, ClamAV gained the ability to deconstruct the emails, so
1548         doing this would actually have resulted in the mail attachments being
1549         scanned twice, in the broken out files and from the original .eml.
1550         Since ClamAV now handles emails (and has for quite some time) we can
1551         just use the email file itself. */
1552         /* Pass the string to ClamAV (7 = "SCAN \n" + \0) */
1553         file_name = string_sprintf("SCAN %s\n", eml_filename);
1554
1555         DEBUG(D_acl) debug_printf(
1556             "Malware scan: issuing %s local-path scan [%s]\n",
1557             scanner_name, scanner_options);
1558
1559         if (send(sock, file_name, Ustrlen(file_name), 0) < 0)
1560           return m_errlog_defer_3(scanent,
1561             string_sprintf("unable to write to socket (%s)", strerror(errno)),
1562             sock);
1563
1564         /* Do not shut down the socket for writing; a user report noted that
1565          * clamd 0.70 does not react well to this. */
1566         }
1567       /* Commands have been sent, no matter which scan method or connection
1568        * type we're using; now just read the result, independent of method. */
1569
1570       /* Read the result */
1571       memset(av_buffer, 0, sizeof(av_buffer));
1572       bread = ip_recv(sock, av_buffer, sizeof(av_buffer), tmo-time(NULL));
1573       (void)close(sock);
1574       sock = -1;
1575
1576       if (bread <= 0)
1577         return m_errlog_defer(scanent,
1578           string_sprintf("unable to read from socket (%s)",
1579           errno == 0 ? "EOF" : strerror(errno)));
1580
1581       if (bread == sizeof(av_buffer))
1582         return m_errlog_defer(scanent, US"buffer too small");
1583       /* We're now assured of a NULL at the end of av_buffer */
1584
1585       /* Check the result. ClamAV returns one of two result formats.
1586       In the basic mode, the response is of the form:
1587         infected: -> "<filename>: <virusname> FOUND"
1588         not-infected: -> "<filename>: OK"
1589         error: -> "<filename>: <errcode> ERROR
1590       If the ExtendedDetectionInfo option has been turned on, then we get:
1591         "<filename>: <virusname>(<virushash>:<virussize>) FOUND"
1592       for the infected case.  Compare:
1593 /tmp/eicar.com: Eicar-Test-Signature FOUND
1594 /tmp/eicar.com: Eicar-Test-Signature(44d88612fea8a8f36de82e1278abb02f:68) FOUND
1595
1596       In the streaming case, clamd uses the filename "stream" which you should
1597       be able to verify with { ktrace clamdscan --stream /tmp/eicar.com }.  (The
1598       client app will replace "stream" with the original filename before returning
1599       results to stdout, but the trace shows the data).
1600
1601       We will assume that the pathname passed to clamd from Exim does not contain
1602       a colon.  We will have whined loudly above if the eml_filename does (and we're
1603       passing a filename to clamd). */
1604
1605       if (!(*av_buffer))
1606         return m_errlog_defer(scanent, US"ClamAV returned null");
1607
1608       /* strip newline at the end (won't be present for zINSTREAM)
1609       (also any trailing whitespace, which shouldn't exist, but we depend upon
1610       this below, so double-check) */
1611       p = av_buffer + Ustrlen(av_buffer) - 1;
1612       if (*p == '\n') *p = '\0';
1613
1614       DEBUG(D_acl) debug_printf("Malware response: %s\n", av_buffer);
1615
1616       while (isspace(*--p) && (p > av_buffer))
1617         *p = '\0';
1618       if (*p) ++p;
1619       response_end = p;
1620
1621       /* colon in returned output? */
1622       if((p = Ustrchr(av_buffer,':')) == NULL)
1623         return m_errlog_defer(scanent, string_sprintf(
1624                   "ClamAV returned malformed result (missing colon): %s",
1625                   av_buffer));
1626
1627       /* strip filename */
1628       while (*p && isspace(*++p)) /**/;
1629       vname = p;
1630
1631       /* It would be bad to encounter a virus with "FOUND" in part of the name,
1632       but we should at least be resistant to it. */
1633       p = Ustrrchr(vname, ' ');
1634       result_tag = p ? p+1 : vname;
1635
1636       if (Ustrcmp(result_tag, "FOUND") == 0)
1637         {
1638         /* p should still be the whitespace before the result_tag */
1639         while (isspace(*p)) --p;
1640         *++p = '\0';
1641         /* Strip off the extended information too, which will be in parens
1642         after the virus name, with no intervening whitespace. */
1643         if (*--p == ')')
1644           {
1645           /* "(hash:size)", so previous '(' will do; if not found, we have
1646           a curious virus name, but not an error. */
1647           p = Ustrrchr(vname, '(');
1648           if (p)
1649             *p = '\0';
1650           }
1651         malware_name = string_copy(vname);
1652         DEBUG(D_acl) debug_printf("Malware found, name \"%s\"\n", malware_name);
1653
1654         }
1655       else if (Ustrcmp(result_tag, "ERROR") == 0)
1656         return m_errlog_defer(scanent,
1657           string_sprintf("ClamAV returned: %s", av_buffer));
1658
1659       else if (Ustrcmp(result_tag, "OK") == 0)
1660         {
1661         /* Everything should be OK */
1662         malware_name = NULL;
1663         DEBUG(D_acl) debug_printf("Malware not found\n");
1664
1665         }
1666       else
1667         return m_errlog_defer(scanent,
1668           string_sprintf("unparseable response from ClamAV: {%s}", av_buffer));
1669
1670       break;
1671       } /* clamd */
1672
1673     case M_SOCK: /* "sock" scanner type ------------------------------------- */
1674     /* This code was derived by Martin Poole from the clamd code contributed
1675        by David Saez and the cmdline code
1676     */
1677       {
1678       int bread;
1679       uschar * commandline;
1680       uschar av_buffer[1024];
1681       uschar * linebuffer;
1682       uschar * sockline_scanner;
1683       uschar sockline_scanner_default[] = "%s\n";
1684       const pcre *sockline_trig_re;
1685       const pcre *sockline_name_re;
1686
1687       /* find scanner command line */
1688       if ((sockline_scanner = string_nextinlist(&av_scanner_work, &sep,
1689                                           NULL, 0)))
1690       { /* check for no expansions apart from one %s */
1691         uschar * s = Ustrchr(sockline_scanner, '%');
1692         if (s++)
1693           if ((*s != 's' && *s != '%') || Ustrchr(s+1, '%'))
1694             return m_errlog_defer_3(scanent,
1695                                   US"unsafe sock scanner call spec", sock);
1696       }
1697       else
1698         sockline_scanner = sockline_scanner_default;
1699
1700       /* find scanner output trigger */
1701       sockline_trig_re = m_pcre_nextinlist(&av_scanner_work, &sep,
1702                                 "missing trigger specification", &errstr);
1703       if (!sockline_trig_re)
1704         return m_errlog_defer_3(scanent, errstr, sock);
1705
1706       /* find virus name regex */
1707       sockline_name_re = m_pcre_nextinlist(&av_scanner_work, &sep,
1708                           "missing virus name regex specification", &errstr);
1709       if (!sockline_name_re)
1710         return m_errlog_defer_3(scanent, errstr, sock);
1711
1712       /* prepare scanner call - security depends on expansions check above */
1713       commandline = string_sprintf("%s/scan/%s/%s.eml", spool_directory, message_id, message_id);
1714       commandline = string_sprintf( CS sockline_scanner, CS commandline);
1715
1716
1717       /* Pass the command string to the socket */
1718       if (m_sock_send(sock, commandline, Ustrlen(commandline), &errstr) < 0)
1719         return m_errlog_defer(scanent, errstr);
1720
1721       /* Read the result */
1722       bread = ip_recv(sock, av_buffer, sizeof(av_buffer), tmo-time(NULL));
1723
1724       if (bread <= 0)
1725         return m_errlog_defer_3(scanent,
1726           string_sprintf("unable to read from socket (%s)", strerror(errno)),
1727           sock);
1728
1729       if (bread == sizeof(av_buffer))
1730         return m_errlog_defer_3(scanent, US"buffer too small", sock);
1731       av_buffer[bread] = '\0';
1732       linebuffer = string_copy(av_buffer);
1733
1734       /* try trigger match */
1735       if (regex_match_and_setup(sockline_trig_re, linebuffer, 0, -1))
1736         {
1737         if (!(malware_name = m_pcre_exec(sockline_name_re, av_buffer)))
1738           malware_name = US "unknown";
1739         }
1740       else /* no virus found */
1741         malware_name = NULL;
1742       break;
1743       }
1744
1745     case M_MKSD: /* "mksd" scanner type ------------------------------------- */
1746       {
1747       char *mksd_options_end;
1748       int mksd_maxproc = 1;  /* default, if no option supplied */
1749       int retval;
1750
1751       if (scanner_options)
1752         {
1753         mksd_maxproc = (int)strtol(CS scanner_options, &mksd_options_end, 10);
1754         if (  *scanner_options == '\0'
1755            || *mksd_options_end != '\0'
1756            || mksd_maxproc < 1
1757            || mksd_maxproc > 32
1758            )
1759           return m_errlog_defer(scanent,
1760             string_sprintf("invalid option '%s'", scanner_options));
1761         }
1762
1763       if((sock = ip_unixsocket(US "/var/run/mksd/socket", &errstr)) < 0)
1764         return m_errlog_defer(scanent, errstr);
1765
1766       malware_name = NULL;
1767
1768       DEBUG(D_acl) debug_printf("Malware scan: issuing %s scan\n", scanner_name);
1769
1770       if ((retval = mksd_scan_packed(scanent, sock, eml_filename, tmo)) != OK)
1771         {
1772         close (sock);
1773         return retval;
1774         }
1775       break;
1776       }
1777
1778     case M_AVAST: /* "avast" scanner type ----------------------------------- */
1779       {
1780       int ovector[1*3];
1781       uschar buf[1024];
1782       uschar * scanrequest;
1783       enum {AVA_HELO, AVA_OPT, AVA_RSP, AVA_DONE} avast_stage;
1784       int nread;
1785
1786       /* According to Martin Tuma @avast the protocol uses "escaped
1787       whitespace", that is, every embedded whitespace is backslash
1788       escaped, as well as backslash is protected by backslash.
1789       The returned lines contain the name of the scanned file, a tab
1790       and the [ ] marker.
1791       [+] - not infected
1792       [L] - infected
1793       [E] - some error occured
1794       Such marker follows the first non-escaped TAB.  */
1795       if (  (  !ava_re_clean
1796             && !(ava_re_clean = m_pcre_compile(ava_re_clean_str, &errstr)))
1797          || (  !ava_re_virus
1798             && !(ava_re_virus = m_pcre_compile(ava_re_virus_str, &errstr)))
1799          )
1800         return malware_errlog_defer(errstr);
1801
1802       /* wait for result */
1803       for (avast_stage = AVA_HELO;
1804            (nread = recv_line(sock, buf, sizeof(buf), tmo)) > 0;
1805           )
1806         {
1807         int slen = Ustrlen(buf);
1808         if (slen >= 1) 
1809           {
1810           DEBUG(D_acl) debug_printf("got from avast: %s\n", buf);
1811           switch (avast_stage)
1812             {
1813             case AVA_HELO:
1814               if (Ustrncmp(buf, "220", 3) != 0)
1815                 goto endloop;                   /* require a 220 */
1816               goto sendreq;
1817
1818             case AVA_OPT:
1819               if (Ustrncmp(buf, "210", 3) == 0)
1820                 break;                          /* ignore 210 responses */
1821               if (Ustrncmp(buf, "200", 3) != 0)
1822                 goto endloop;                   /* require a 200 */
1823
1824             sendreq:
1825               {
1826               int len;
1827               /* Check for another option to send. Newline-terminate it. */
1828               if ((scanrequest = string_nextinlist(&av_scanner_work, &sep,
1829                                 NULL, 0)))
1830                 {
1831                 scanrequest = string_sprintf("%s\n", scanrequest);
1832                 avast_stage = AVA_OPT;          /* just sent option */
1833                 }
1834               else
1835                 {
1836                 scanrequest = string_sprintf("SCAN %s/scan/%s\n",
1837                     spool_directory, message_id);
1838                 avast_stage = AVA_RSP;          /* just sent command */
1839                 }
1840
1841               /* send config-cmd or scan-request to socket */
1842               len = Ustrlen(scanrequest);
1843               if (send(sock, scanrequest, len, 0) < 0)
1844                 {
1845                 scanrequest[len-1] = '\0';
1846                 return m_errlog_defer_3(scanent, string_sprintf(
1847                       "unable to send request '%s' to socket (%s): %s",
1848                       scanrequest, scanner_options, strerror(errno)), sock);
1849                 }
1850               break;
1851               }
1852
1853             case AVA_RSP:
1854               if (Ustrncmp(buf, "210", 3) == 0)
1855                 break;  /* ignore the "210 SCAN DATA" message */
1856
1857               if (pcre_exec(ava_re_clean, NULL, CS buf, slen,
1858                     0, 0, ovector, nelements(ovector)) > 0)
1859                 break;
1860
1861               if ((malware_name = m_pcre_exec(ava_re_virus, buf)))
1862                 { /* remove backslash in front of [whitespace|backslash] */
1863                 uschar * p, * p0;
1864                 for (p = malware_name; *p; ++p) 
1865                   if (*p == '\\' && (isspace(p[1]) || p[1] == '\\'))
1866                     for (p0 = p; *p0; ++p0) *p0 = p0[1];
1867                 
1868                 avast_stage = AVA_DONE;
1869                 goto endloop;
1870                 }
1871
1872               if (Ustrncmp(buf, "200 SCAN OK", 11) == 0) 
1873                 { /* we're done finally */
1874                 if (send(sock, "QUIT\n", 5, 0) < 0) /* courtesy */
1875                   return m_errlog_defer_3(scanent, string_sprintf(
1876                               "unable to send quit request to socket (%s): %s",
1877                               scanner_options, strerror(errno)),
1878                               sock);
1879                 malware_name = NULL;
1880                 avast_stage = AVA_DONE;
1881                 goto endloop;
1882                 }
1883
1884               /* here for any unexpected response from the scanner */
1885               goto endloop;
1886             }
1887           }
1888         }
1889       endloop:
1890
1891       switch(avast_stage)
1892         {
1893         case AVA_HELO:  
1894         case AVA_OPT:
1895         case AVA_RSP:   return m_errlog_defer_3(scanent,
1896                             nread >= 0
1897                             ? string_sprintf(
1898                                 "invalid response from scanner: '%s'", buf)
1899                             : nread == -1
1900                             ? US"EOF from scanner"
1901                             : US"timeout from scanner",
1902                           sock);
1903         default:        break;
1904         }
1905       }
1906       break;
1907   }     /* scanner type switch */
1908
1909   if (sock >= 0)
1910     (void) close (sock);
1911   malware_ok = TRUE;                    /* set "been here, done that" marker */
1912   }
1913
1914 /* match virus name against pattern (caseless ------->----------v) */
1915 if (malware_name && regex_match_and_setup(re, malware_name, 0, -1))
1916   {
1917   DEBUG(D_acl) debug_printf(
1918       "Matched regex to malware [%s] [%s]\n", malware_re, malware_name);
1919   return OK;
1920   }
1921 else
1922   return FAIL;
1923 }
1924
1925
1926 /*************************************************
1927 *          Scan an email for malware             *
1928 *************************************************/
1929
1930 /* This is the normal interface for scanning an email, which doesn't need a
1931 filename; it's a wrapper around the malware_file function.
1932
1933 Arguments:
1934   malware_re  match condition for "malware="
1935   timeout     if nonzero, timeout in seconds
1936
1937 Returns:      Exim message processing code (OK, FAIL, DEFER, ...)
1938               where true means malware was found (condition applies)
1939 */
1940 int
1941 malware(const uschar * malware_re, int timeout)
1942 {
1943   uschar * scan_filename;
1944   int ret;
1945
1946   scan_filename = string_sprintf("%s/scan/%s/%s.eml",
1947                     spool_directory, message_id, message_id);
1948   ret = malware_internal(malware_re, scan_filename, timeout, FALSE);
1949   if (ret == DEFER) av_failed = TRUE;
1950
1951   return ret;
1952 }
1953
1954
1955 /*************************************************
1956 *          Scan a file for malware               *
1957 *************************************************/
1958
1959 /* This is a test wrapper for scanning an email, which is not used in
1960 normal processing.  Scan any file, using the Exim scanning interface.
1961 This function tampers with various global variables so is unsafe to use
1962 in any other context.
1963
1964 Arguments:
1965   eml_filename  a file holding the message to be scanned
1966
1967 Returns:        Exim message processing code (OK, FAIL, DEFER, ...)
1968                 where true means malware was found (condition applies)
1969 */
1970 int
1971 malware_in_file(uschar *eml_filename)
1972 {
1973   uschar message_id_buf[64];
1974   int ret;
1975
1976   /* spool_mbox() assumes various parameters exist, when creating
1977   the relevant directory and the email within */
1978   (void) string_format(message_id_buf, sizeof(message_id_buf),
1979       "dummy-%d", vaguely_random_number(INT_MAX));
1980   message_id = message_id_buf;
1981   sender_address = US"malware-sender@example.net";
1982   return_path = US"";
1983   recipients_list = NULL;
1984   receive_add_recipient(US"malware-victim@example.net", -1);
1985   enable_dollar_recipients = TRUE;
1986
1987   ret = malware_internal(US"*", eml_filename, 0,  TRUE);
1988
1989   Ustrncpy(spooled_message_id, message_id, sizeof(spooled_message_id));
1990   spool_mbox_ok = 1;
1991   /* don't set no_mbox_unspool; at present, there's no way for it to become
1992   set, but if that changes, then it should apply to these tests too */
1993   unspool_mbox();
1994
1995   /* silence static analysis tools */
1996   message_id = NULL;
1997
1998   return ret;
1999 }
2000
2001
2002 void
2003 malware_init(void)
2004 {
2005 if (!malware_default_re)
2006   malware_default_re = regex_must_compile(malware_regex_default, FALSE, TRUE);
2007 if (!drweb_re)
2008   drweb_re = regex_must_compile(drweb_re_str, FALSE, TRUE);
2009 if (!fsec_re)
2010   fsec_re = regex_must_compile(fsec_re_str, FALSE, TRUE);
2011 if (!kav_re_sus)
2012   kav_re_sus = regex_must_compile(kav_re_sus_str, FALSE, TRUE);
2013 if (!kav_re_inf)
2014   kav_re_inf = regex_must_compile(kav_re_inf_str, FALSE, TRUE);
2015 if (!ava_re_clean)
2016   ava_re_clean = regex_must_compile(ava_re_clean_str, FALSE, TRUE);
2017 if (!ava_re_virus)
2018   ava_re_virus = regex_must_compile(ava_re_virus_str, FALSE, TRUE);
2019 }
2020
2021 #endif /*WITH_CONTENT_SCAN*/
2022 /*
2023  * vi: aw ai sw=2
2024  */