libclamav/scanners.c
e3aaff8e
 /*
2023340a
  *  Copyright (C) 2007-2008 Sourcefire, Inc.
c7543866
  *
2023340a
  *  Authors: Tomasz Kojm
e3aaff8e
  *
  *  This program is free software; you can redistribute it and/or modify
bb34cb31
  *  it under the terms of the GNU General Public License version 2 as
  *  published by the Free Software Foundation.
e3aaff8e
  *
  *  This program is distributed in the hope that it will be useful,
  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  *  GNU General Public License for more details.
  *
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
48b7b4a7
  *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
  *  MA 02110-1301, USA.
e3aaff8e
  */
 
6d6e8271
 #if HAVE_CONFIG_H
 #include "clamav-config.h"
 #endif
 
517f7b7a
 #ifndef _WIN32
ee1b2a6c
 #include <sys/time.h>
517f7b7a
 #endif
e3aaff8e
 #include <stdio.h>
 #include <string.h>
 #include <stdlib.h>
0a80bd02
 #include <errno.h>
e3aaff8e
 #include <sys/types.h>
 #include <sys/stat.h>
b58fdfc2
 #ifdef	HAVE_UNISTD_H
a7f5fd00
 #include <unistd.h>
b58fdfc2
 #endif
 #ifdef	HAVE_SYS_PARAM_H
15edd45f
 #include <sys/param.h>
b58fdfc2
 #endif
e3aaff8e
 #include <fcntl.h>
 #include <dirent.h>
63feb6cd
 #ifdef HAVE_SYS_TIMES_H
 #include <sys/times.h>
 #endif
888f5794
 
bc93eda0
 #define DCONF_ARCH  ctx->dconf->archive
 #define DCONF_DOC   ctx->dconf->doc
 #define DCONF_MAIL  ctx->dconf->mail
 #define DCONF_OTHER ctx->dconf->other
 
e3aaff8e
 #include "clamav.h"
 #include "others.h"
bc93eda0
 #include "dconf.h"
85dd8460
 #include "scanners.h"
8000d078
 #include "matcher-ac.h"
 #include "matcher-bm.h"
e3aaff8e
 #include "matcher.h"
47bbbc56
 #include "ole2_extract.h"
 #include "vba_extract.h"
341e5433
 #include "msexpand.h"
8d3aca30
 #include "mbox.h"
a5373b64
 #include "chmunpack.h"
a9082ea2
 #include "pe.h"
8d3aca30
 #include "elf.h"
888f5794
 #include "filetypes.h"
 #include "htmlnorm.h"
2b259453
 #include "untar.h"
c3a3be2d
 #include "special.h"
6a31c2b4
 #include "binhex.h"
8d3aca30
 /* #include "uuencode.h" */
7bbd5f7f
 #include "tnef.h"
bf45bf13
 #include "sis.h"
2c313298
 #include "pdf.h"
bd988961
 #include "str.h"
24fd05e1
 #include "mspack.h"
 #include "cab.h"
52c2a8bd
 #include "rtf.h"
9d96e4b6
 #include "unarj.h"
517f7b7a
 #include "nsis/nulsft.h"
ed93f138
 #include "autoit.h"
015ce4a8
 #include "textnorm.h"
e3aaff8e
 #include <zlib.h>
f133da7a
 #include "unzip.h"
a6e38800
 #include "dlp.h"
c4934f41
 #include "default.h"
85885226
 #include "cpio.h"
89c14869
 #include "macho.h"
7ebede9b
 #include "ishield.h"
0e605501
 #include "7z_iface.h"
998bcfa7
 #include "fmap.h"
511c2e79
 #include "cache.h"
b33354e5
 #include "events.h"
1fb9e80c
 #include "swf.h"
 #include "jpeg.h"
419a9d3d
 #include "png.h"
583cd65f
 #include "iso9660.h"
ca019d6d
 #include "dmg.h"
 #include "xar.h"
e3aaff8e
 
 #ifdef HAVE_BZLIB_H
 #include <bzlib.h>
 #endif
 
2bb229f6
 #if defined(HAVE_READDIR_R_3) || defined(HAVE_READDIR_R_2)
 #include <limits.h>
88794204
 #include <stddef.h>
2bb229f6
 #endif
 
3c91998b
 static int cli_scanfile(const char *filename, cli_ctx *ctx);
4048c4f6
 
cb680655
 static int cli_scandir(const char *dirname, cli_ctx *ctx)
c7543866
 {
 	DIR *dd;
 	struct dirent *dent;
 #if defined(HAVE_READDIR_R_3) || defined(HAVE_READDIR_R_2)
 	union {
 	    struct dirent d;
 	    char b[offsetof(struct dirent, d_name) + NAME_MAX + 1];
 	} result;
 #endif
a2a004df
 	STATBUF statbuf;
c7543866
 	char *fname;
6ad45a29
 	unsigned int viruses_found = 0;
c7543866
 
     if((dd = opendir(dirname)) != NULL) {
 #ifdef HAVE_READDIR_R_3
 	while(!readdir_r(dd, &result.d, &dent) && dent) {
 #elif defined(HAVE_READDIR_R_2)
 	while((dent = (struct dirent *) readdir_r(dd, &result.d))) {
 #else
 	while((dent = readdir(dd))) {
 #endif
 	    if(dent->d_ino)
 	    {
 		if(strcmp(dent->d_name, ".") && strcmp(dent->d_name, "..")) {
 		    /* build the full name */
 		    fname = cli_malloc(strlen(dirname) + strlen(dent->d_name) + 2);
 		    if(!fname) {
 			closedir(dd);
241e7eb1
             cli_dbgmsg("cli_scandir: Unable to allocate memory for filename\n");
c7543866
 			return CL_EMEM;
 		    }
 
58481352
 		    sprintf(fname, "%s"PATHSEP"%s", dirname, dent->d_name);
c7543866
 
 		    /* stat the file */
a2a004df
 		    if(LSTAT(fname, &statbuf) != -1) {
c7543866
 			if(S_ISDIR(statbuf.st_mode) && !S_ISLNK(statbuf.st_mode)) {
cb680655
 			    if(cli_scandir(fname, ctx) == CL_VIRUS) {
c7543866
 				free(fname);
6ad45a29
 
 				if (SCAN_ALL) {
 				    viruses_found++;
 				    continue;
 				}
 
                                 closedir(dd);
                                 return CL_VIRUS;
  			    }
c7543866
 			} else {
 			    if(S_ISREG(statbuf.st_mode)) {
 				if(cli_scanfile(fname, ctx) == CL_VIRUS) {
 				    free(fname);
6ad45a29
 
 				    if (SCAN_ALL) {
 					viruses_found++;
 					continue;
 				    }
 
                                     closedir(dd);
                                     return CL_VIRUS;
  				}
c7543866
 			    }
 			}
 		    }
 		    free(fname);
 		}
 	    }
6ad45a29
 	} 
c7543866
     } else {
 	cli_dbgmsg("cli_scandir: Can't open directory %s.\n", dirname);
 	return CL_EOPEN;
     }
 
     closedir(dd);
6ad45a29
     if (SCAN_ALL && viruses_found)
 	return CL_VIRUS;
c7543866
     return CL_CLEAN;
 }
 
5ca7fd18
 static int cli_unrar_scanmetadata(int desc, unrar_metadata_t *metadata, cli_ctx *ctx, unsigned int files, uint32_t* sfx_check)
e3aaff8e
 {
133538e0
 	int ret = CL_SUCCESS;
e3aaff8e
 
133538e0
     if(files == 1 && sfx_check) {
 	if(*sfx_check == metadata->crc)
 	    return CL_BREAK;/* break extract loop */
 	else
 	    *sfx_check = metadata->crc;
e3aaff8e
     }
 
d91ab809
     cli_dbgmsg("RAR: %s, crc32: 0x%x, encrypted: %u, compressed: %u, normal: %u, method: %u, ratio: %u\n",
794f3f23
 	metadata->filename, metadata->crc, metadata->encrypted, (unsigned int) metadata->pack_size,
 	(unsigned int) metadata->unpack_size, metadata->method,
d91ab809
 	metadata->pack_size ? (unsigned int) (metadata->unpack_size / metadata->pack_size) : 0);
a62ae54f
 
570b1d00
     if(cli_matchmeta(ctx, metadata->filename, metadata->pack_size, metadata->unpack_size, metadata->encrypted, files, metadata->crc, NULL) == CL_VIRUS)
6416cdef
 	return CL_VIRUS;
a62ae54f
 
133538e0
     if(DETECT_ENCRYPTED && metadata->encrypted) {
 	cli_dbgmsg("RAR: Encrypted files found in archive.\n");
ffa9b060
 	ret = cli_scandesc(desc, ctx, 0, 0, NULL, AC_SCAN_VIR, NULL);
133538e0
 	if(ret != CL_VIRUS) {
6ad45a29
 	    cli_append_virus(ctx, "Heuristics.Encrypted.RAR");
133538e0
 	    return CL_VIRUS;
a62ae54f
 	}
133538e0
     }
a62ae54f
 
2dbcf700
     return ret;
 }
 
133538e0
 static int cli_scanrar(int desc, cli_ctx *ctx, off_t sfx_offset, uint32_t *sfx_check)
 {
 	int ret = CL_CLEAN;
5ca7fd18
 	unrar_metadata_t *metadata, *metadata_tmp;
133538e0
 	char *dir;
5ca7fd18
 	unrar_state_t rar_state;
6ad45a29
 	unsigned int viruses_found = 0;
133538e0
 
     cli_dbgmsg("in scanrar()\n");
 
2b459819
     if(sfx_offset)
 	if(lseek(desc, sfx_offset, SEEK_SET) == -1)
871177cd
 	    return CL_ESEEK;
2b459819
 
133538e0
     /* generate the temporary directory */
33068e09
     if(!(dir = cli_gentemp(ctx->engine->tmpdir)))
5fc380f1
 	return CL_EMEM;
 
133538e0
     if(mkdir(dir, 0700)) {
 	cli_dbgmsg("RAR: Can't create temporary directory %s\n", dir);
 	free(dir);
 	return CL_ETMPDIR;
     }
 
bb7bd3ab
     if((ret = cli_unrar_open(desc, dir, &rar_state)) != UNRAR_OK) {
33068e09
 	if(!ctx->engine->keeptmp)
133538e0
 	    cli_rmdirs(dir);
 	free(dir);
06fd4ce9
 	if(ret == UNRAR_PASSWD) {
 	    cli_dbgmsg("RAR: Encrypted main header\n");
 	    if(DETECT_ENCRYPTED) {
96914546
 		if (lseek(desc, 0, SEEK_SET) == -1) {
             cli_dbgmsg("RAR: call to lseek() failed\n");
             return CL_ESEEK;
         }
ffa9b060
 		ret = cli_scandesc(desc, ctx, 0, 0, NULL, AC_SCAN_VIR, NULL);
06fd4ce9
 		if(ret != CL_VIRUS)
6ad45a29
 		    cli_append_virus(ctx, "Heuristics.Encrypted.RAR");
06fd4ce9
 		return CL_VIRUS;
 	    }
 	    return CL_CLEAN;
 	} if(ret == UNRAR_EMEM) {
5ca7fd18
 	    return CL_EMEM;
06fd4ce9
 	} else {
871177cd
 	    return CL_EUNPACK;
06fd4ce9
 	}
133538e0
     }
 
     do {
 	int rc;
5ca7fd18
 	rar_state.ofd = -1;
bb7bd3ab
 	ret = cli_unrar_extract_next_prepare(&rar_state,dir);
5ca7fd18
 	if(ret != UNRAR_OK) {
 	    if(ret == UNRAR_BREAK)
 		ret = CL_BREAK;
 	    else if(ret == UNRAR_EMEM)
 		ret = CL_EMEM;
 	    else
871177cd
 		ret = CL_EUNPACK;
2dbcf700
 	    break;
5ca7fd18
 	}
f009e241
 	if(ctx->engine->maxscansize && ctx->scansize >= ctx->engine->maxscansize) {
49dca2e3
 	    free(rar_state.file_header->filename);
 	    free(rar_state.file_header);
2dbcf700
 	    ret = CL_CLEAN;
f009e241
 	    break;
2dbcf700
 	}
f009e241
 	if(ctx->engine->maxscansize && ctx->scansize + ctx->engine->maxfilesize >= ctx->engine->maxscansize)
 	    rar_state.maxfilesize = ctx->engine->maxscansize - ctx->scansize;
 	else
 	    rar_state.maxfilesize = ctx->engine->maxfilesize;
 
bb7bd3ab
 	ret = cli_unrar_extract_next(&rar_state,dir);
5ca7fd18
 	if(ret == UNRAR_OK)
 	    ret = CL_SUCCESS;
 	else if(ret == UNRAR_EMEM)
 	    ret = CL_EMEM;
 	else
871177cd
 	    ret = CL_EFORMAT;
5ca7fd18
 
 	if(rar_state.ofd > 0) {
96914546
 	    if (lseek(rar_state.ofd,0,SEEK_SET) == -1) {
             cli_dbgmsg("RAR: Call to lseek() failed\n");
             ret = CL_ESEEK;
         }
5ca7fd18
 	    rc = cli_magic_scandesc(rar_state.ofd,ctx);
 	    close(rar_state.ofd);
33068e09
 	    if(!ctx->engine->keeptmp) 
871177cd
 		if (cli_unlink(rar_state.filename)) ret = CL_EUNLINK;
133538e0
 	    if(rc == CL_VIRUS ) {
6ad45a29
 		cli_dbgmsg("RAR: infected with %s\n", cli_get_last_virus(ctx));
133538e0
 		ret = CL_VIRUS;
6ad45a29
 		viruses_found++;
e3aaff8e
 	    }
 	}
 
6ad45a29
 	if(ret == CL_VIRUS) {
 	    if(SCAN_ALL)
 		ret = CL_SUCCESS;
 	    else
 		break;
 	}
 
133538e0
 	if(ret == CL_SUCCESS)
44c3b2c8
 	    ret = cli_unrar_scanmetadata(desc,rar_state.metadata_tail, ctx, rar_state.file_count, sfx_check);
133538e0
 
     } while(ret == CL_SUCCESS);
 
     if(ret == CL_BREAK)
 	ret = CL_CLEAN;
 
     metadata = metadata_tmp = rar_state.metadata; 
 
cb680655
     if(cli_scandir(rar_state.comment_dir, ctx) == CL_VIRUS)
133538e0
 	ret = CL_VIRUS;
e3aaff8e
 
bb7bd3ab
     cli_unrar_close(&rar_state);
cf68af72
 
33068e09
     if(!ctx->engine->keeptmp)
478ce4b2
         cli_rmdirs(dir);
e3aaff8e
 
478ce4b2
     free(dir);
133538e0
 
478ce4b2
     metadata = metadata_tmp;
     while (metadata) {
     	metadata_tmp = metadata->next;
     	free(metadata->filename);
     	free(metadata);
     	metadata = metadata_tmp;
e3aaff8e
     }
2b259453
     cli_dbgmsg("RAR: Exit code: %d\n", ret);
7761c6eb
 
6ad45a29
     if (SCAN_ALL && viruses_found)
 	return CL_VIRUS;
e3aaff8e
     return ret;
 }
 
3f065bbe
 static int cli_scanarj(cli_ctx *ctx, off_t sfx_offset, uint32_t *sfx_check)
9d96e4b6
 {
570b1d00
 	int ret = CL_CLEAN, rc, file = 0;
9d96e4b6
 	arj_metadata_t metadata;
 	char *dir;
 
     cli_dbgmsg("in cli_scanarj()\n");
 
      /* generate the temporary directory */
33068e09
     if(!(dir = cli_gentemp(ctx->engine->tmpdir)))
5fc380f1
 	return CL_EMEM;
 
9d96e4b6
     if(mkdir(dir, 0700)) {
b865e44a
 	cli_dbgmsg("ARJ: Can't create temporary directory %s\n", dir);
9d96e4b6
 	free(dir);
 	return CL_ETMPDIR;
     }
 
3f065bbe
     ret = cli_unarj_open(*ctx->fmap, dir, &metadata, sfx_offset);
9d96e4b6
     if (ret != CL_SUCCESS) {
33068e09
 	if(!ctx->engine->keeptmp)
9d96e4b6
 	    cli_rmdirs(dir);
 	free(dir);
 	cli_dbgmsg("ARJ: Error: %s\n", cl_strerror(ret));
 	return ret;
     }
     
    do {
fc355be4
         metadata.filename = NULL;
3f065bbe
 	ret = cli_unarj_prepare_file(dir, &metadata);
9d96e4b6
 	if (ret != CL_SUCCESS) {
05fa206e
 	   cli_dbgmsg("ARJ: cli_unarj_prepare_file Error: %s\n", cl_strerror(ret));
9d96e4b6
 	   break;
 	}
570b1d00
 	file++;
 	if(cli_matchmeta(ctx, metadata.filename, metadata.comp_size, metadata.orig_size, metadata.encrypted, file, 0, NULL) == CL_VIRUS)
 	    return CL_VIRUS;
 
d91ab809
 	if ((ret = cli_checklimits("ARJ", ctx, metadata.orig_size, metadata.comp_size, 0))!=CL_CLEAN) {
 	    ret = CL_SUCCESS;
fc355be4
 	    if (metadata.filename)
 		free(metadata.filename);
d91ab809
 	    continue;
9d96e4b6
 	}
3f065bbe
 	ret = cli_unarj_extract_file(dir, &metadata);
05fa206e
 	if (ret != CL_SUCCESS) {
 	   cli_dbgmsg("ARJ: cli_unarj_extract_file Error: %s\n", cl_strerror(ret));
 	}
9d96e4b6
 	if (metadata.ofd >= 0) {
96914546
 	    if (lseek(metadata.ofd, 0, SEEK_SET) == -1) {
             cli_dbgmsg("ARJ: call to lseek() failed\n");
         }
9d96e4b6
 	    rc = cli_magic_scandesc(metadata.ofd, ctx);
 	    close(metadata.ofd);
 	    if (rc == CL_VIRUS) {
6ad45a29
 		cli_dbgmsg("ARJ: infected with %s\n", cli_get_last_virus(ctx));
9d96e4b6
 		ret = CL_VIRUS;
fc355be4
 		if (metadata.filename) {
 		    free(metadata.filename);
 		    metadata.filename = NULL;
 		}
9d96e4b6
 		break;
 	    }
 	}
 	if (metadata.filename) {
 		free(metadata.filename);
 		metadata.filename = NULL;
 	}
 
     } while(ret == CL_SUCCESS);
     
33068e09
     if(!ctx->engine->keeptmp)
9d96e4b6
 	cli_rmdirs(dir);
 
     free(dir);
     if (metadata.filename) {
 	free(metadata.filename);
     }
 
     cli_dbgmsg("ARJ: Exit code: %d\n", ret);
9f851a24
     if (ret == CL_BREAK)
 	ret = CL_CLEAN;
9d96e4b6
 
     return ret;
 }
e3aaff8e
 
5a72fce6
 
 static int cli_scangzip_with_zib_from_the_80s(cli_ctx *ctx, unsigned char *buff) {
     int fd, ret, outsize = 0, bytes;
     fmap_t *map = *ctx->fmap;
     char *tmpname;
     gzFile gz;
 
0b3b2924
     ret = fmap_fd(map);
     if(ret < 0)
 	return CL_EDUP;
     fd = dup(ret);
5a72fce6
     if(fd < 0)
 	return CL_EDUP;
 
     if(!(gz = gzdopen(fd, "rb"))) {
 	close(fd);
 	return CL_EOPEN;
     }
 
     if((ret = cli_gentempfd(ctx->engine->tmpdir, &tmpname, &fd)) != CL_SUCCESS) {
 	cli_dbgmsg("GZip: Can't generate temporary file.\n");
 	gzclose(gz);
bebd86a6
 	close(fd);
5a72fce6
 	return ret;
     }
     
     while((bytes = gzread(gz, buff, FILEBUFF)) > 0) {
 	outsize += bytes;
 	if(cli_checklimits("GZip", ctx, outsize, 0, 0)!=CL_CLEAN)
 	    break;
 	if(cli_writen(fd, buff, bytes) != bytes) {
 	    close(fd);
 	    gzclose(gz);
 	    if(cli_unlink(tmpname)) {
 		free(tmpname);
 		return CL_EUNLINK;
 	    }
 	    free(tmpname);
 	    return CL_EWRITE;
 	}
     }
 
     gzclose(gz);
 
     if((ret = cli_magic_scandesc(fd, ctx)) == CL_VIRUS) {
6ad45a29
 	cli_dbgmsg("GZip: Infected with %s\n", cli_get_last_virus(ctx));
5a72fce6
 	close(fd);
 	if(!ctx->engine->keeptmp) {
 	    if (cli_unlink(tmpname)) {
 	    	free(tmpname);
 		return CL_EUNLINK;
 	    }
 	}
 	free(tmpname);
 	return CL_VIRUS;
     }
     close(fd);
     if(!ctx->engine->keeptmp)
 	if (cli_unlink(tmpname)) ret = CL_EUNLINK;
     free(tmpname);
     return ret;
 }
 
686ed348
 static int cli_scangzip(cli_ctx *ctx)
e3aaff8e
 {
686ed348
 	int fd, ret = CL_CLEAN;
 	unsigned char buff[FILEBUFF];
0e621e7d
 	char *tmpname;
686ed348
 	z_stream z;
5a72fce6
 	size_t at = 0, outsize = 0;
49cc1e3c
 	fmap_t *map = *ctx->fmap;
686ed348
  	
fc56deed
     cli_dbgmsg("in cli_scangzip()\n");
 
686ed348
     memset(&z, 0, sizeof(z));
be2f94dd
     if((ret = inflateInit2(&z, MAX_WBITS + 16)) != Z_OK) {
 	cli_dbgmsg("GZip: InflateInit failed: %d\n", ret);
5a72fce6
 	return cli_scangzip_with_zib_from_the_80s(ctx, buff);
e3aaff8e
     }
 
686ed348
     if((ret = cli_gentempfd(ctx->engine->tmpdir, &tmpname, &fd)) != CL_SUCCESS) {
2b259453
 	cli_dbgmsg("GZip: Can't generate temporary file.\n");
686ed348
 	inflateEnd(&z);
a7ac5978
 	return ret;
e3aaff8e
     }
 
686ed348
     while (at < map->len) {
 	unsigned int bytes = MIN(map->len - at, map->pgsz);
f304dc68
 	if(!(z.next_in = (void*)fmap_need_off_once(map, at, bytes))) {
686ed348
 	    cli_dbgmsg("GZip: Can't read %u bytes @ %lu.\n", bytes, (long unsigned)at);
 	    inflateEnd(&z);
 	    close(fd);
 	    if (cli_unlink(tmpname)) {
 		free(tmpname);
871177cd
 		return CL_EUNLINK;
997a0e0b
 	    }
686ed348
 	    free(tmpname);
 	    return CL_EREAD;
997a0e0b
 	}
686ed348
 	at += bytes;
 	z.avail_in = bytes;
 	do {
 	    int inf;
 	    z.avail_out = sizeof(buff);
             z.next_out = buff;
 	    inf = inflate(&z, Z_NO_FLUSH);
 	    if(inf != Z_OK && inf != Z_STREAM_END && inf != Z_BUF_ERROR) {
 		cli_dbgmsg("GZip: Bad stream.\n");
 		at = map->len;
 		break;
 	    }
 	    if(cli_writen(fd, buff, sizeof(buff) - z.avail_out) < 0) {
 		inflateEnd(&z);	    
 		close(fd);
 		if (cli_unlink(tmpname)) {
997a0e0b
 		    free(tmpname);
871177cd
 		    return CL_EUNLINK;
997a0e0b
 		}
5a72fce6
 		free(tmpname);
 		return CL_EWRITE;
 	    }
 	    outsize += sizeof(buff) - z.avail_out;
 	    if(cli_checklimits("GZip", ctx, outsize, 0, 0)!=CL_CLEAN) {
 		at = map->len;
 		break;
997a0e0b
 	    }
786766eb
 	    if(inf == Z_STREAM_END) {
 		at -= z.avail_in;
 		inflateReset(&z);
 		break;
 	    }
686ed348
 	} while (z.avail_out == 0);
e3aaff8e
     }
 
686ed348
     inflateEnd(&z);	    
985d9958
 
5a72fce6
     if((ret = cli_magic_scandesc(fd, ctx)) == CL_VIRUS) {
6ad45a29
 	cli_dbgmsg("GZip: Infected with %s\n", cli_get_last_virus(ctx));
a7ac5978
 	close(fd);
33068e09
 	if(!ctx->engine->keeptmp) {
997a0e0b
 	    if (cli_unlink(tmpname)) {
 	    	free(tmpname);
871177cd
 		return CL_EUNLINK;
997a0e0b
 	    }
 	}
686ed348
 	free(tmpname);
e3aaff8e
 	return CL_VIRUS;
     }
a7ac5978
     close(fd);
33068e09
     if(!ctx->engine->keeptmp)
871177cd
 	if (cli_unlink(tmpname)) ret = CL_EUNLINK;
686ed348
     free(tmpname);
e3aaff8e
     return ret;
 }
 
de472237
 #ifndef HAVE_BZLIB_H
6b89f8e8
 static int cli_scanbzip(cli_ctx *ctx) {
de472237
     cli_warnmsg("cli_scanbzip: bzip2 support not compiled in\n");
     return CL_CLEAN;
 }
 
 #else
e3aaff8e
 
 #ifdef NOBZ2PREFIX
6b89f8e8
 #define BZ2_bzDecompressInit bzDecompressInit
 #define BZ2_bzDecompress bzDecompress
 #define BZ2_bzDecompressEnd bzDecompressEnd
e3aaff8e
 #endif
 
6b89f8e8
 static int cli_scanbzip(cli_ctx *ctx)
e3aaff8e
 {
6b89f8e8
     int ret = CL_CLEAN, fd, rc;
     unsigned long int size = 0;
     char *tmpname;
     bz_stream strm;
     size_t off = 0;
     size_t avail;
     char buf[FILEBUFF];
 
     memset(&strm, 0, sizeof(strm));
     strm.next_out = buf;
     strm.avail_out = sizeof(buf);
     rc = BZ2_bzDecompressInit(&strm, 0, 0);
     if (BZ_OK != rc) {
 	cli_dbgmsg("Bzip: DecompressInit failed: %d\n", rc);
871177cd
 	return CL_EOPEN;
e3aaff8e
     }
 
33068e09
     if((ret = cli_gentempfd(ctx->engine->tmpdir, &tmpname, &fd))) {
2b259453
 	cli_dbgmsg("Bzip: Can't generate temporary file.\n");
6b89f8e8
 	BZ2_bzDecompressEnd(&strm);
a7ac5978
 	return ret;
e3aaff8e
     }
 
6b89f8e8
     do {
 	if (!strm.avail_in) {
 	    strm.next_in = (void*)fmap_need_off_once_len(*ctx->fmap, off, FILEBUFF, &avail);
 	    strm.avail_in = avail;
 	    off += avail;
 	    if (!strm.avail_in) {
 		cli_dbgmsg("Bzip: premature end of compressed stream\n");
 		break;
997a0e0b
 	    }
 	}
e3aaff8e
 
6b89f8e8
 	rc = BZ2_bzDecompress(&strm);
 	if (BZ_OK != rc && BZ_STREAM_END != rc) {
 	    cli_dbgmsg("Bzip: decompress error: %d\n", rc);
d91ab809
 	    break;
6b89f8e8
 	}
e3aaff8e
 
6b89f8e8
 	if (!strm.avail_out || BZ_STREAM_END == rc) {
 	    size += sizeof(buf) - strm.avail_out;
 
 	    if(cli_checklimits("Bzip", ctx, size + FILEBUFF, 0, 0)!=CL_CLEAN)
 		break;
 
 	    if(cli_writen(fd, buf, sizeof(buf) - strm.avail_out) != sizeof(buf) - strm.avail_out) {
 		cli_dbgmsg("Bzip: Can't write to file.\n");
 		BZ2_bzDecompressEnd(&strm);
 		close(fd);
 		if(!ctx->engine->keeptmp) {
 		    if (cli_unlink(tmpname)) {
 			free(tmpname);
 			return CL_EUNLINK;
 		    }
997a0e0b
 		}
6b89f8e8
 		free(tmpname);
 		return CL_EWRITE;
997a0e0b
 	    }
6b89f8e8
 	    strm.next_out = buf;
 	    strm.avail_out = sizeof(buf);
e3aaff8e
 	}
6b89f8e8
     } while (BZ_STREAM_END != rc);
e3aaff8e
 
6b89f8e8
     BZ2_bzDecompressEnd(&strm);
985d9958
 
     if(ret == CL_VIRUS) {
a7ac5978
 	close(fd);
33068e09
 	if(!ctx->engine->keeptmp)
871177cd
 	    if (cli_unlink(tmpname)) ret = CL_EUNLINK;
6b89f8e8
 	free(tmpname);
985d9958
 	return ret;
     }
 
3c91998b
     if((ret = cli_magic_scandesc(fd, ctx)) == CL_VIRUS ) {
6ad45a29
 	cli_dbgmsg("Bzip: Infected with %s\n", cli_get_last_virus(ctx));
e3aaff8e
     }
a7ac5978
     close(fd);
33068e09
     if(!ctx->engine->keeptmp)
871177cd
 	if (cli_unlink(tmpname)) ret = CL_EUNLINK;
6b89f8e8
     free(tmpname);
e3aaff8e
 
     return ret;
 }
 #endif
 
786a7e91
 static int cli_scanszdd(cli_ctx *ctx)
341e5433
 {
6e47a652
 	int ofd, ret;
0e621e7d
 	char *tmpname;
341e5433
 
2b259453
 
5da612a4
     cli_dbgmsg("in cli_scanszdd()\n");
 
33068e09
     if((ret = cli_gentempfd(ctx->engine->tmpdir, &tmpname, &ofd))) {
6e47a652
 	cli_dbgmsg("MSEXPAND: Can't generate temporary file/descriptor\n");
 	return ret;
341e5433
     }
 
786a7e91
     ret = cli_msexpand(ctx, ofd);
341e5433
 
6e47a652
     if(ret != CL_SUCCESS) { /* CL_VIRUS or some error */
 	close(ofd);
33068e09
 	if(!ctx->engine->keeptmp)
871177cd
 	    if (cli_unlink(tmpname)) ret = CL_EUNLINK;
0e621e7d
 	free(tmpname);	
6e47a652
 	return ret;
341e5433
     }
 
6e47a652
     cli_dbgmsg("MSEXPAND: Decompressed into %s\n", tmpname);
     ret = cli_magic_scandesc(ofd, ctx);
     close(ofd);
33068e09
     if(!ctx->engine->keeptmp)
871177cd
 	if (cli_unlink(tmpname)) ret = CL_EUNLINK;
0e621e7d
     free(tmpname);	
6e47a652
 
341e5433
     return ret;
 }
 
5914844a
 static int cli_scanmscab(cli_ctx *ctx, off_t sfx_offset)
414abe87
 {
 	char *tempname;
24fd05e1
 	int ret;
 	unsigned int files = 0;
 	struct cab_archive cab;
 	struct cab_file *file;
c6b9d863
 	unsigned int corrupted_input;
6ad45a29
 	unsigned int viruses_found = 0;
414abe87
 
     cli_dbgmsg("in cli_scanmscab()\n");
 
70f20eb8
     if((ret = cab_open(*ctx->fmap, sfx_offset, &cab)))
24fd05e1
 	return ret;
414abe87
 
24fd05e1
     for(file = cab.files; file; file = file->next) {
 	files++;
52ab3176
 
570b1d00
 	if(cli_matchmeta(ctx, file->name, 0, file->length, 0, files, 0, NULL) == CL_VIRUS) {
6ad45a29
 	    if (!SCAN_ALL) {
 		ret = CL_VIRUS;
 		break;
 	    }
 	    viruses_found++;
5fc380f1
 	}
8df99a92
 
 	if(ctx->engine->maxscansize && ctx->scansize >= ctx->engine->maxscansize) {
 	    ret = CL_CLEAN;
 	    break;
 	}
570b1d00
 
 	if(!(tempname = cli_gentemp(ctx->engine->tmpdir))) {
 	    ret = CL_EMEM;
 	    break;
 	}
 
8df99a92
 	if(ctx->engine->maxscansize && ctx->scansize + ctx->engine->maxfilesize >= ctx->engine->maxscansize)
 	    file->max_size = ctx->engine->maxscansize - ctx->scansize;
24fd05e1
 	else
81c1e5f5
 	    file->max_size = ctx->engine->maxfilesize ? ctx->engine->maxfilesize : 0xffffffff;
24fd05e1
 
8df99a92
 	cli_dbgmsg("CAB: Extracting file %s to %s, size %u, max_size: %u\n", file->name, tempname, file->length, (unsigned int) file->max_size);
 	file->written_size = 0;
 	if((ret = cab_extract(file, tempname))) {
 	    cli_dbgmsg("CAB: Failed to extract file: %s\n", cl_strerror(ret));
 	} else {
c6b9d863
 	    corrupted_input = ctx->corrupted_input;
 	    if(file->length != file->written_size) {
8df99a92
 		cli_dbgmsg("CAB: Length from header %u but wrote %u bytes\n", (unsigned int) file->length, (unsigned int) file->written_size);
c6b9d863
 		ctx->corrupted_input = 1;
 	    }
8df99a92
 	    ret = cli_scanfile(tempname, ctx);
c6b9d863
 	    ctx->corrupted_input = corrupted_input;
8df99a92
 	}
33068e09
 	if(!ctx->engine->keeptmp) {
fd45238e
 	    if (!access(tempname, R_OK) && cli_unlink(tempname)) {
997a0e0b
 	    	free(tempname);
871177cd
 		ret = CL_EUNLINK;
997a0e0b
 		break;
 	    }
 	}
24fd05e1
 	free(tempname);
6ad45a29
 	if(ret == CL_VIRUS) {
 	    if (SCAN_ALL)
 		viruses_found++;
 	    else
 		break;
 	}
414abe87
     }
 
24fd05e1
     cab_free(&cab);
6ad45a29
     if (viruses_found)
 	return CL_VIRUS;
414abe87
     return ret;
 }
 
d020ad3f
 static int vba_scandata(const unsigned char *data, unsigned int len, cli_ctx *ctx)
 {
 	struct cli_matcher *groot = ctx->engine->root[0];
 	struct cli_matcher *troot = ctx->engine->root[2];
 	struct cli_ac_data gmdata, tmdata;
 	struct cli_ac_data *mdata[2];
 	int ret;
6ad45a29
 	unsigned int viruses_found = 0;
d020ad3f
 
     if((ret = cli_ac_initdata(&tmdata, troot->ac_partsigs, troot->ac_lsigs, troot->ac_reloff_num, CLI_DEFAULT_AC_TRACKLEN)))
 	return ret;
 
     if((ret = cli_ac_initdata(&gmdata, groot->ac_partsigs, groot->ac_lsigs, groot->ac_reloff_num, CLI_DEFAULT_AC_TRACKLEN))) {
 	cli_ac_freedata(&tmdata);
 	return ret;
     }
     mdata[0] = &tmdata;
     mdata[1] = &gmdata;
 
     ret = cli_scanbuff(data, len, 0, ctx, CL_TYPE_MSOLE2, mdata);
ec5f4a47
     if (ret == CL_VIRUS)
9b6914ee
 	viruses_found++;
d020ad3f
 
9b6914ee
     if (ret == CL_CLEAN || (ret == CL_VIRUS && SCAN_ALL)) {
d020ad3f
 	ret = cli_lsig_eval(ctx, troot, &tmdata, NULL, NULL);
ec5f4a47
 	if (ret == CL_VIRUS)
 	    viruses_found++;
 
9b6914ee
 	if (ret == CL_CLEAN || (ret == CL_VIRUS && SCAN_ALL))
d020ad3f
 	    ret = cli_lsig_eval(ctx, groot, &gmdata, NULL, NULL);
     }
     cli_ac_freedata(&tmdata);
     cli_ac_freedata(&gmdata);
 
9b6914ee
     return (ret != CL_CLEAN)?ret:viruses_found?CL_VIRUS:CL_CLEAN;
d020ad3f
 }
 
72ce4b70
 static int cli_vba_scandir(const char *dirname, cli_ctx *ctx, struct uniq *U)
e3aaff8e
 {
6bee45b3
 	int ret = CL_CLEAN, i, j, fd, data_len, hasmacros = 0;
467f8b1e
 	vba_project_t *vba_project;
e3aaff8e
 	DIR *dd;
 	struct dirent *dent;
72a1b240
 #if defined(HAVE_READDIR_R_3) || defined(HAVE_READDIR_R_2)
88794204
 	union {
 	    struct dirent d;
 	    char b[offsetof(struct dirent, d_name) + NAME_MAX + 1];
 	} result;
2bb229f6
 #endif
a2a004df
 	STATBUF statbuf;
72ce4b70
 	char *fullname, vbaname[1024];
467f8b1e
 	unsigned char *data;
937ade08
 	char *hash;
 	uint32_t hashcnt;
6ad45a29
 	unsigned int viruses_found = 0;
467f8b1e
 
2b259453
 
     cli_dbgmsg("VBADir: %s\n", dirname);
72ce4b70
     hashcnt = uniq_get(U, "_vba_project", 12, NULL);
     while(hashcnt--) {
 	if(!(vba_project = (vba_project_t *)cli_vba_readdir(dirname, U, hashcnt))) continue;
e3aaff8e
 
467f8b1e
 	for(i = 0; i < vba_project->count; i++) {
937ade08
 	    for(j = 0; (unsigned int)j < vba_project->colls[i]; j++) {
58481352
 		snprintf(vbaname, 1024, "%s"PATHSEP"%s_%u", vba_project->dir, vba_project->name[i], j);
72ce4b70
 		vbaname[sizeof(vbaname)-1] = '\0';
 		fd = open(vbaname, O_RDONLY|O_BINARY);
 		if(fd == -1) continue;
937ade08
 		cli_dbgmsg("VBADir: Decompress VBA project '%s_%u'\n", vba_project->name[i], j);
72ce4b70
 		data = (unsigned char *)cli_vba_inflate(fd, vba_project->offset[i], &data_len);
 		close(fd);
6bee45b3
 		hasmacros++;
72ce4b70
 		if(!data) {
937ade08
 		    cli_dbgmsg("VBADir: WARNING: VBA project '%s_%u' decompressed to NULL\n", vba_project->name[i], j);
72ce4b70
 		} else {
 		    /* cli_dbgmsg("Project content:\n%s", data); */
 		    if(ctx->scanned)
 			*ctx->scanned += data_len / CL_COUNT_PRECISION;
d020ad3f
 		    if(vba_scandata(data, data_len, ctx) == CL_VIRUS) {
6ad45a29
 			if (SCAN_ALL) 
 			    viruses_found++;
 			else {
 			    free(data);
 			    ret = CL_VIRUS;
 			    break;
 			}
72ce4b70
 		    }
467f8b1e
 		    free(data);
 		}
 	    }
 	}
 
 	free(vba_project->name);
72ce4b70
 	free(vba_project->colls);
467f8b1e
 	free(vba_project->dir);
 	free(vba_project->offset);
 	free(vba_project);
6ad45a29
 	if (ret == CL_VIRUS && !SCAN_ALL)
 	    break;
72ce4b70
     }
 
6ad45a29
     if((ret == CL_CLEAN || (ret == CL_VIRUS && SCAN_ALL)) && 
 	(hashcnt = uniq_get(U, "powerpoint document", 19, &hash))) {
72ce4b70
 	while(hashcnt--) {
58481352
 	    snprintf(vbaname, 1024, "%s"PATHSEP"%s_%u", dirname, hash, hashcnt);
72ce4b70
 	    vbaname[sizeof(vbaname)-1] = '\0';
 	    fd = open(vbaname, O_RDONLY|O_BINARY);
 	    if (fd == -1) continue;
33068e09
 	    if ((fullname = cli_ppt_vba_read(fd, ctx))) {
cb680655
 		if(cli_scandir(fullname, ctx) == CL_VIRUS) {
72ce4b70
 		    ret = CL_VIRUS;
6ad45a29
 		    viruses_found++;
2e53806b
 		}
33068e09
 		if(!ctx->engine->keeptmp)
72ce4b70
 		    cli_rmdirs(fullname);
2e53806b
 		free(fullname);
72ce4b70
 	    }
 	    close(fd);
 	}
     }
 
6ad45a29
     if ((ret == CL_CLEAN || (ret == CL_VIRUS && SCAN_ALL)) && 
 	(hashcnt = uniq_get(U, "worddocument", 12, &hash))) {
72ce4b70
 	while(hashcnt--) {
58481352
 	    snprintf(vbaname, sizeof(vbaname), "%s"PATHSEP"%s_%u", dirname, hash, hashcnt);
72ce4b70
 	    vbaname[sizeof(vbaname)-1] = '\0';
 	    fd = open(vbaname, O_RDONLY|O_BINARY);
 	    if (fd == -1) continue;
 	    
 	    if (!(vba_project = (vba_project_t *)cli_wm_readdir(fd))) {
2e53806b
 		close(fd);
72ce4b70
 		continue;
 	    }
 
 	    for (i = 0; i < vba_project->count; i++) {
 		cli_dbgmsg("VBADir: Decompress WM project macro:%d key:%d length:%d\n", i, vba_project->key[i], vba_project->length[i]);
 		data = (unsigned char *)cli_wm_decrypt_macro(fd, vba_project->offset[i], vba_project->length[i], vba_project->key[i]);
2e53806b
 		if(!data) {
2b259453
 			cli_dbgmsg("VBADir: WARNING: WM project '%s' macro %d decrypted to NULL\n", vba_project->name[i], i);
2e53806b
 		} else {
72ce4b70
 			cli_dbgmsg("Project content:\n%s", data);
3c91998b
 			if(ctx->scanned)
 			    *ctx->scanned += vba_project->length[i] / CL_COUNT_PRECISION;
d020ad3f
 			if(vba_scandata(data, vba_project->length[i], ctx) == CL_VIRUS) {
6ad45a29
 			    if (SCAN_ALL)
 				viruses_found++;
 			    else {
2e53806b
 				free(data);
 				ret = CL_VIRUS;
 				break;
6ad45a29
 			    }
2e53806b
 			}
 			free(data);
 		}
72ce4b70
 	    }
 
 	    close(fd);
 	    free(vba_project->name);
 	    free(vba_project->colls);
 	    free(vba_project->dir);
 	    free(vba_project->offset);
 	    free(vba_project->key);
 	    free(vba_project->length);
 	    free(vba_project);
6ad45a29
 	    if(ret == CL_VIRUS) {
 		if (SCAN_ALL)
 		    viruses_found++;
 		else
 		    break;
 	    }
2e53806b
 	}
467f8b1e
     }
cd69cf20
 
6ad45a29
     if(ret != CL_CLEAN && !(ret == CL_VIRUS && SCAN_ALL))
467f8b1e
     	return ret;
e3aaff8e
 
892d2f56
     /* Check directory for embedded OLE objects */
72ce4b70
     hashcnt = uniq_get(U, "_1_ole10native", 14, &hash);
     while(hashcnt--) {
58481352
 	snprintf(vbaname, sizeof(vbaname), "%s"PATHSEP"%s_%u", dirname, hash, hashcnt);
72ce4b70
 	vbaname[sizeof(vbaname)-1] = '\0';
 
 	fd = open(vbaname, O_RDONLY|O_BINARY);
 	if (fd >= 0) {
 	    ret = cli_scan_ole10(fd, ctx);
 	    close(fd);
6ad45a29
 	    if(ret != CL_CLEAN && !(ret == CL_VIRUS && SCAN_ALL))
72ce4b70
 		return ret;
892d2f56
 	}
     }
 
72ce4b70
 
     /* ACAB: since we now hash filenames and handle collisions we
      * could avoid recursion by removing the block below and by
      * flattening the paths in ole2_walk_property_tree (case 1) */
 
e3aaff8e
     if((dd = opendir(dirname)) != NULL) {
72a1b240
 #ifdef HAVE_READDIR_R_3
88794204
 	while(!readdir_r(dd, &result.d, &dent) && dent) {
72a1b240
 #elif defined(HAVE_READDIR_R_2)
88794204
 	while((dent = (struct dirent *) readdir_r(dd, &result.d))) {
72a1b240
 #else
e3aaff8e
 	while((dent = readdir(dd))) {
72a1b240
 #endif
feeaa333
 	    if(dent->d_ino)
 	    {
e3aaff8e
 		if(strcmp(dent->d_name, ".") && strcmp(dent->d_name, "..")) {
 		    /* build the full name */
72ce4b70
 		    fullname = cli_malloc(strlen(dirname) + strlen(dent->d_name) + 2);
 		    if(!fullname) {
241e7eb1
                 cli_dbgmsg("cli_vba_scandir: Unable to allocate memory for fullname\n");
cd69cf20
 			ret = CL_EMEM;
 			break;
 		    }
58481352
 		    sprintf(fullname, "%s"PATHSEP"%s", dirname, dent->d_name);
e3aaff8e
 
 		    /* stat the file */
a2a004df
 		    if(LSTAT(fullname, &statbuf) != -1) {
e3aaff8e
 			if(S_ISDIR(statbuf.st_mode) && !S_ISLNK(statbuf.st_mode))
72ce4b70
 			  if (cli_vba_scandir(fullname, ctx, U) == CL_VIRUS) {
6ad45a29
 			      if (SCAN_ALL)
 				  viruses_found++;
 			      else {
 				  ret = CL_VIRUS;
 				  free(fullname);
 				  break;
 			      }
 			  }
e3aaff8e
 		    }
72ce4b70
 		    free(fullname);
e3aaff8e
 		}
 	    }
 	}
     } else {
2b259453
 	cli_dbgmsg("VBADir: Can't open directory %s.\n", dirname);
e3aaff8e
 	return CL_EOPEN;
     }
 
     closedir(dd);
6bee45b3
     if(BLOCK_MACROS && hasmacros) {
6ad45a29
 	cli_append_virus(ctx, "Heuristics.OLE2.ContainsMacros");
6bee45b3
 	ret = CL_VIRUS;
6ad45a29
 	viruses_found++;
6bee45b3
     }
6ad45a29
     if (SCAN_ALL && viruses_found)
 	return CL_VIRUS;
467f8b1e
     return ret;
 }
 
084d19aa
 static int cli_scanhtml(cli_ctx *ctx)
a92110df
 {
b2726a53
     char *tempname, fullname[1024];
     int ret=CL_CLEAN, fd;
     fmap_t *map = *ctx->fmap;
     unsigned int viruses_found = 0;
     uint64_t curr_len = map->len;
a92110df
 
     cli_dbgmsg("in cli_scanhtml()\n");
 
b2726a53
     /* CL_ENGINE_MAX_HTMLNORMALIZE */
     if(curr_len > ctx->engine->maxhtmlnormalize) {
 	cli_dbgmsg("cli_scanhtml: exiting (file larger than MaxHTMLNormalize)\n");
572a986c
 	return CL_CLEAN;
     }
 
33068e09
     if(!(tempname = cli_gentemp(ctx->engine->tmpdir)))
5fc380f1
 	return CL_EMEM;
 
a92110df
     if(mkdir(tempname, 0700)) {
572a986c
         cli_errmsg("cli_scanhtml: Can't create temporary directory %s\n", tempname);
f0bc32bd
 	free(tempname);
a92110df
         return CL_ETMPDIR;
     }
 
5f2fa151
     cli_dbgmsg("cli_scanhtml: using tempdir %s\n", tempname);
 
084d19aa
     html_normalise_map(map, tempname, NULL, ctx->dconf);
58481352
     snprintf(fullname, 1024, "%s"PATHSEP"nocomment.html", tempname);
b58fdfc2
     fd = open(fullname, O_RDONLY|O_BINARY);
a92110df
     if (fd >= 0) {
6ad45a29
 	if ((ret = cli_scandesc(fd, ctx, CL_TYPE_HTML, 0, NULL, AC_SCAN_VIR, NULL)) == CL_VIRUS)
 	    viruses_found++;
 	close(fd);
a92110df
     }
 
b2726a53
     if(ret == CL_CLEAN || (ret == CL_VIRUS && SCAN_ALL)) {
         /* CL_ENGINE_MAX_HTMLNOTAGS */
         curr_len = map->len;
         if (curr_len > ctx->engine->maxhtmlnotags) {
 	    /* we're not interested in scanning large files in notags form */
             /* TODO: don't even create notags if file is over limit */
             cli_dbgmsg("cli_scanhtml: skipping notags (normalized size over MaxHTMLNoTags)\n");
 	}
         else {
             snprintf(fullname, 1024, "%s"PATHSEP"notags.html", tempname);
             fd = open(fullname, O_RDONLY|O_BINARY);
             if(fd >= 0) {
                 if ((ret = cli_scandesc(fd, ctx, CL_TYPE_HTML, 0, NULL, AC_SCAN_VIR, NULL)) == CL_VIRUS) 
                     viruses_found++;
                 close(fd);
             }
         }
a92110df
     }
 
6ad45a29
     if(ret == CL_CLEAN || (ret == CL_VIRUS && SCAN_ALL)) {
58481352
 	    snprintf(fullname, 1024, "%s"PATHSEP"javascript", tempname);
8be1d5a4
 	    fd = open(fullname, O_RDONLY|O_BINARY);
 	    if(fd >= 0) {
6ad45a29
 		if ((ret = cli_scandesc(fd, ctx, CL_TYPE_HTML, 0, NULL, AC_SCAN_VIR, NULL)) == CL_VIRUS)
 		    viruses_found++;
 		if (ret == CL_CLEAN || (ret == CL_VIRUS && SCAN_ALL)) {
 		    if ((ret = cli_scandesc(fd, ctx, CL_TYPE_TEXT_ASCII, 0, NULL, AC_SCAN_VIR, NULL)) == CL_VIRUS)
 			viruses_found++;
 		}
 		close(fd);
8be1d5a4
 	    }
     }
 
6ad45a29
     if (ret == CL_CLEAN || (ret == CL_VIRUS && SCAN_ALL)) {
58481352
 	snprintf(fullname, 1024, "%s"PATHSEP"rfc2397", tempname);
cb680655
 	ret = cli_scandir(fullname, ctx);
a92110df
     }
 
33068e09
     if(!ctx->engine->keeptmp)
a92110df
         cli_rmdirs(tempname);
 
     free(tempname);
6ad45a29
     if (SCAN_ALL && viruses_found)
 	return CL_VIRUS;
a92110df
     return ret;
 }
 
ee1b2a6c
 static int cli_scanscript(cli_ctx *ctx)
015ce4a8
 {
b2726a53
     const unsigned char *buff;
     unsigned char* normalized;
     struct text_norm_state state;
     char *tmpname = NULL;
     int ofd = -1, ret;
     struct cli_matcher *troot;
     uint32_t maxpatlen, offset = 0;
     struct cli_matcher *groot;
     struct cli_ac_data gmdata, tmdata;
     struct cli_ac_data *mdata[2];
0b3b2924
     fmap_t *map;
b2726a53
     size_t at = 0;
     unsigned int viruses_found = 0;
0b3b2924
     uint64_t curr_len;
015ce4a8
 
b0d2122c
     if (!ctx || !ctx->engine->root)
         return CL_ENULLARG;
 
0b3b2924
     map = *ctx->fmap;
     curr_len = map->len;
b0d2122c
     groot = ctx->engine->root[0];
     troot = ctx->engine->root[7];
     maxpatlen = troot ? troot->maxpatlen : 0;
 
b2726a53
     cli_dbgmsg("in cli_scanscript()\n");
015ce4a8
 
b2726a53
     /* CL_ENGINE_MAX_SCRIPTNORMALIZE */
     if(curr_len > ctx->engine->maxscriptnormalize) {
         cli_dbgmsg("cli_scanscript: exiting (file larger than MaxScriptSize)\n");
         return CL_CLEAN;
     }
015ce4a8
 
 	/* dump to disk only if explicitly asked to,
 	 * otherwise we can process just in-memory */
33068e09
 	if(ctx->engine->keeptmp) {
 		if((ret = cli_gentempfd(ctx->engine->tmpdir, &tmpname, &ofd))) {
015ce4a8
 			cli_dbgmsg("cli_scanscript: Can't generate temporary file/descriptor\n");
 			return ret;
 		}
22a16acb
 		cli_dbgmsg("cli_scanscript: saving normalized file to %s\n", tmpname);
015ce4a8
 	}
 
2865ac2b
 	if(!(normalized = cli_malloc(SCANBUFF + maxpatlen))) {
2a138cc5
 		cli_dbgmsg("cli_scanscript: Unable to malloc %u bytes\n", SCANBUFF);
 		return CL_EMEM;
 	}
 
2865ac2b
 	text_normalize_init(&state, normalized, SCANBUFF + maxpatlen);
015ce4a8
 	ret = CL_CLEAN;
 
da121bee
 	if ((ret = cli_ac_initdata(&tmdata, troot?troot->ac_partsigs:0, troot?troot->ac_lsigs:0, troot?troot->ac_reloff_num:0, CLI_DEFAULT_AC_TRACKLEN))) 
c4934f41
 	    return ret;
 
aca9ea82
 	if ((ret = cli_ac_initdata(&gmdata, groot->ac_partsigs, groot->ac_lsigs, groot->ac_reloff_num, CLI_DEFAULT_AC_TRACKLEN))) {
c4934f41
 	    cli_ac_freedata(&tmdata);
 	    return ret;
 	}
 	mdata[0] = &tmdata;
 	mdata[1] = &gmdata;
 
ee1b2a6c
 	while(1) {
 	    size_t len = MIN(map->pgsz, map->len - at);
 	    buff = fmap_need_off_once(map, at, len);
 	    at += len;
 	    if(!buff || !len || state.out_pos + len > state.out_len) {
 		/* flush if error/EOF, or too little buffer space left */
 		if((ofd != -1) && (write(ofd, state.out, state.out_pos) == -1)) {
 		    cli_errmsg("cli_scanscript: can't write to file %s\n",tmpname);
 		    close(ofd);
 		    ofd = -1;
 		    /* we can continue to scan in memory */
015ce4a8
 		}
ee1b2a6c
 		/* when we flush the buffer also scan */
 		if(cli_scanbuff(state.out, state.out_pos, offset, ctx, CL_TYPE_TEXT_ASCII, mdata) == CL_VIRUS) {
6ad45a29
 		    if (SCAN_ALL)
 			viruses_found++;
 		    else {
 			ret = CL_VIRUS;
 			break;
 		    }
015ce4a8
 		}
ee1b2a6c
 		if(ctx->scanned)
 		    *ctx->scanned += state.out_pos / CL_COUNT_PRECISION;
 		offset += state.out_pos;
 		/* carry over maxpatlen from previous buffer */
 		if (state.out_pos > maxpatlen)
 		    memmove(state.out, state.out + state.out_pos - maxpatlen, maxpatlen); 
 		text_normalize_reset(&state);
 		state.out_pos = maxpatlen;
 	    }
 	    if(!len) break;
b0d2122c
 	    if(!buff || text_normalize_buffer(&state, buff, len) != len) {
ee1b2a6c
 		cli_dbgmsg("cli_scanscript: short read during normalizing\n");
 	    }
 	}
33068e09
 	if(ctx->engine->keeptmp) {
015ce4a8
 		free(tmpname);
 		close(ofd);
 	}
2a138cc5
 	free(normalized);
6ad45a29
 	if(ret != CL_VIRUS || SCAN_ALL)  {
 	    if ((ret = cli_lsig_eval(ctx, troot, &tmdata, NULL, NULL)) == CL_VIRUS)
 		viruses_found++;
 	    if(ret != CL_VIRUS || SCAN_ALL)
 		if ((ret = cli_lsig_eval(ctx, groot, &gmdata, NULL, NULL)) == CL_VIRUS)
 		    viruses_found++;
60dbee52
 	}
 	cli_ac_freedata(&tmdata);
 	cli_ac_freedata(&gmdata);
015ce4a8
 
6ad45a29
 	if (SCAN_ALL && viruses_found)
 	    return CL_VIRUS;
015ce4a8
 	return ret;
 }
 
084d19aa
 static int cli_scanhtml_utf16(cli_ctx *ctx)
bd988961
 {
f304dc68
 	char *tempname, *decoded;
 	const char *buff;
bd988961
 	int ret = CL_CLEAN, fd, bytes;
084d19aa
 	size_t at = 0;
49cc1e3c
 	fmap_t *map = *ctx->fmap;
bd988961
 
     cli_dbgmsg("in cli_scanhtml_utf16()\n");
 
33068e09
     if(!(tempname = cli_gentemp(ctx->engine->tmpdir)))
5fc380f1
 	return CL_EMEM;
 
bd988961
     if((fd = open(tempname, O_RDWR|O_CREAT|O_TRUNC|O_BINARY, S_IRWXU)) < 0) {
 	cli_errmsg("cli_scanhtml_utf16: Can't create file %s\n", tempname);
 	free(tempname);
871177cd
 	return CL_EOPEN;
bd988961
     }
 
5f2fa151
     cli_dbgmsg("cli_scanhtml_utf16: using tempfile %s\n", tempname);
 
084d19aa
     while(at < map->len) {
017bbfbf
 	bytes = MIN(map->len - at, map->pgsz * 16);
084d19aa
 	if(!(buff = fmap_need_off_once(map, at, bytes))) {
 	    close(fd);
 	    cli_unlink(tempname);
 	    free(tempname);
 	    return CL_EREAD;
 	}
017bbfbf
 	at += bytes;
bd988961
 	decoded = cli_utf16toascii(buff, bytes);
 	if(decoded) {
020ba3ce
 	    if(write(fd, decoded, bytes / 2) == -1) {
bd988961
 		cli_errmsg("cli_scanhtml_utf16: Can't write to file %s\n", tempname);
 		free(decoded);
401ea243
 		close(fd);
c0a95e0c
 		cli_unlink(tempname);
bd988961
 		free(tempname);
871177cd
 		return CL_EWRITE;
bd988961
 	    }
 	    free(decoded);
 	}
     }
 
084d19aa
     *ctx->fmap = fmap(fd, 0, 0);
     if(*ctx->fmap) {
 	ret = cli_scanhtml(ctx);
49cc1e3c
 	funmap(*ctx->fmap);
084d19aa
     } else
 	cli_errmsg("cli_scanhtml_utf16: fmap of %s failed\n", tempname);
 
     *ctx->fmap = map;
bd988961
     close(fd);
 
33068e09
     if(!ctx->engine->keeptmp) {
871177cd
 	if (cli_unlink(tempname)) ret = CL_EUNLINK;
62ae31f3
     } else
bd988961
 	cli_dbgmsg("cli_scanhtml_utf16: Decoded HTML data saved in %s\n", tempname);
     free(tempname);
 
     return ret;
 }
 
034c02fd
 static int cli_scanole2(cli_ctx *ctx)
467f8b1e
 {
56bfccb2
 	char *dir;
 	int ret = CL_CLEAN;
72ce4b70
 	struct uniq *vba = NULL;
2b259453
 
467f8b1e
     cli_dbgmsg("in cli_scanole2()\n");
 
724b2bf7
     if(ctx->engine->maxreclevel && ctx->recursion >= ctx->engine->maxreclevel)
bbd6ca3f
         return CL_EMAXREC;
 
467f8b1e
     /* generate the temporary directory */
33068e09
     if(!(dir = cli_gentemp(ctx->engine->tmpdir)))
5fc380f1
 	return CL_EMEM;
 
467f8b1e
     if(mkdir(dir, 0700)) {
2b259453
 	cli_dbgmsg("OLE2: Can't create temporary directory %s\n", dir);
f0bc32bd
 	free(dir);
467f8b1e
 	return CL_ETMPDIR;
     }
 
034c02fd
     ret = cli_ole2_extract(dir, ctx, &vba);
72ce4b70
     if(ret!=CL_CLEAN && ret!=CL_VIRUS) {
2b259453
 	cli_dbgmsg("OLE2: %s\n", cl_strerror(ret));
33068e09
 	if(!ctx->engine->keeptmp)
8d5e0ac0
 	    cli_rmdirs(dir);
467f8b1e
 	free(dir);
 	return ret;
     }
 
72ce4b70
     if (vba) {
         ctx->recursion++;
bbd6ca3f
 
72ce4b70
 	ret = cli_vba_scandir(dir, ctx, vba);
53321a4c
 	uniq_free(vba);
72ce4b70
 	if(ret != CL_VIRUS)
cb680655
 	    if(cli_scandir(dir, ctx) == CL_VIRUS)
72ce4b70
 	        ret = CL_VIRUS;
 	ctx->recursion--;
467f8b1e
     }
 
33068e09
     if(!ctx->engine->keeptmp)
8d5e0ac0
 	cli_rmdirs(dir);
467f8b1e
     free(dir);
     return ret;
e3aaff8e
 }
 
a91f6d95
 static int cli_scantar(cli_ctx *ctx, unsigned int posix)
2b259453
 {
 	char *dir;
 	int ret = CL_CLEAN;
 
 
     cli_dbgmsg("in cli_scantar()\n");
 
     /* generate temporary directory */
33068e09
     if(!(dir = cli_gentemp(ctx->engine->tmpdir)))
5fc380f1
 	return CL_EMEM;
 
2b259453
     if(mkdir(dir, 0700)) {
 	cli_errmsg("Tar: Can't create temporary directory %s\n", dir);
f0bc32bd
 	free(dir);
2b259453
 	return CL_ETMPDIR;
     }
 
a91f6d95
     ret = cli_untar(dir, posix, ctx);
2b259453
 
33068e09
     if(!ctx->engine->keeptmp)
2b259453
 	cli_rmdirs(dir);
 
     free(dir);
     return ret;
 }
 
24ab4ad5
 static int cli_scanmschm(cli_ctx *ctx)
a5373b64
 {
b865e44a
 	int ret = CL_CLEAN, rc;
 	chm_metadata_t metadata;
 	char *dir;
6ad45a29
 	unsigned int viruses_found = 0;
a5373b64
 
b865e44a
     cli_dbgmsg("in cli_scanmschm()\n");
a5373b64
 
b865e44a
      /* generate the temporary directory */
33068e09
     if(!(dir = cli_gentemp(ctx->engine->tmpdir)))
5fc380f1
 	return CL_EMEM;
 
b865e44a
     if(mkdir(dir, 0700)) {
 	cli_dbgmsg("CHM: Can't create temporary directory %s\n", dir);
 	free(dir);
a5373b64
 	return CL_ETMPDIR;
     }
 
24ab4ad5
     ret = cli_chm_open(dir, &metadata, ctx);
b865e44a
     if (ret != CL_SUCCESS) {
33068e09
 	if(!ctx->engine->keeptmp)
b865e44a
 	    cli_rmdirs(dir);
 	free(dir);
 	cli_dbgmsg("CHM: Error: %s\n", cl_strerror(ret));
 	return ret;
     }
 
    do {
8bcbfe4a
 	ret = cli_chm_prepare_file(&metadata);
b865e44a
 	if (ret != CL_SUCCESS) {
 	   break;
 	}
8bcbfe4a
 	ret = cli_chm_extract_file(dir, &metadata, ctx);
b865e44a
 	if (ret == CL_SUCCESS) {
 	    rc = cli_magic_scandesc(metadata.ofd, ctx);
 	    close(metadata.ofd);
 	    if (rc == CL_VIRUS) {
6ad45a29
 		cli_dbgmsg("CHM: infected with %s\n", cli_get_last_virus(ctx));
 		if (SCAN_ALL)
 		    viruses_found++;
 		else {
 		    ret = CL_VIRUS;
 		    break;
 		}
b865e44a
 	    }
 	}
a5373b64
 
b865e44a
     } while(ret == CL_SUCCESS);
3c9e2d22
 
     cli_chm_close(&metadata);
    
33068e09
     if(!ctx->engine->keeptmp)
b865e44a
 	cli_rmdirs(dir);
 
     free(dir);
 
     cli_dbgmsg("CHM: Exit code: %d\n", ret);
     if (ret == CL_BREAK)
 	ret = CL_CLEAN;
a5373b64
 
6ad45a29
     if (SCAN_ALL && viruses_found)
 	return CL_VIRUS;
a5373b64
     return ret;
 }
 
32f7e1d7
 static int cli_scanscrenc(cli_ctx *ctx)
e57fa318
 {
 	char *tempname;
 	int ret = CL_CLEAN;
 
     cli_dbgmsg("in cli_scanscrenc()\n");
 
33068e09
     if(!(tempname = cli_gentemp(ctx->engine->tmpdir)))
5fc380f1
 	return CL_EMEM;
 
e57fa318
     if(mkdir(tempname, 0700)) {
 	cli_dbgmsg("CHM: Can't create temporary directory %s\n", tempname);
f0bc32bd
 	free(tempname);
e57fa318
 	return CL_ETMPDIR;
     }
 
32f7e1d7
     if (html_screnc_decode(*ctx->fmap, tempname))
cb680655
 	ret = cli_scandir(tempname, ctx);
e57fa318
 
33068e09
     if(!ctx->engine->keeptmp)
e57fa318
 	cli_rmdirs(tempname);
 
     free(tempname);
     return ret;
 }
015e31e1
 
bad8bbc7
 static int cli_scanriff(cli_ctx *ctx)
eb308794
 {
 	int ret = CL_CLEAN;
 
bad8bbc7
     if(cli_check_riff_exploit(ctx) == 2) {
6416cdef
 	ret = CL_VIRUS;
6ad45a29
 	cli_append_virus(ctx, "Heuristics.Exploit.W32.MS05-002");
eb308794
     }
 
     return ret;
 }
 
32d37729
 static int cli_scanjpeg(cli_ctx *ctx)
7afdc309
 {
 	int ret = CL_CLEAN;
 
32d37729
 	if(cli_check_jpeg_exploit(ctx, 0) == 1) {
6416cdef
 	ret = CL_VIRUS;
6ad45a29
 	cli_append_virus(ctx, "Heuristics.Exploit.W32.MS04-028");
7afdc309
     }
 
     return ret;
 }
 
0c9b8840
 static int cli_scancryptff(cli_ctx *ctx)
2c6f9d57
 {
e12c29d2
 	int ret = CL_CLEAN, ndesc;
0c9b8840
 	unsigned int i;
 	const unsigned char *src;
 	unsigned char *dest = NULL;
2c6f9d57
 	char *tempfile;
0c9b8840
 	size_t pos;
ec591c0a
 	size_t bread;
2c6f9d57
 
 
     /* Skip the CryptFF file header */
0c9b8840
     pos = 0x10;
2c6f9d57
 
0c9b8840
     if((dest = (unsigned char *) cli_malloc(FILEBUFF)) == NULL) {
2c6f9d57
 	cli_dbgmsg("CryptFF: Can't allocate memory\n");
         return CL_EMEM;
     }
 
33068e09
     if(!(tempfile = cli_gentemp(ctx->engine->tmpdir))) {
5fc380f1
 	free(dest);
 	return CL_EMEM;
     }
 
b58fdfc2
     if((ndesc = open(tempfile, O_RDWR|O_CREAT|O_TRUNC|O_BINARY, S_IRWXU)) < 0) {
2c6f9d57
 	cli_errmsg("CryptFF: Can't create file %s\n", tempfile);
 	free(dest);
 	free(tempfile);
871177cd
 	return CL_ECREAT;
2c6f9d57
     }
 
98626d62
     for(; (src = fmap_need_off_once_len(*ctx->fmap, pos, FILEBUFF, &bread)) && bread; pos += bread) {
0c9b8840
 	for (i=0;i<bread;i++)
 	    dest[i] = src[i] ^ (unsigned char) 0xff;
 	if(cli_writen(ndesc, dest, bread) == -1) {
 	    cli_dbgmsg("CryptFF: Can't write to descriptor %d\n", ndesc);
 	    free(dest);
 	    close(ndesc);
 	    free(tempfile);
 	    return CL_EWRITE;
 	}
2c6f9d57
     }
 
     free(dest);
 
 
     cli_dbgmsg("CryptFF: Scanning decrypted data\n");
 
3c91998b
     if((ret = cli_magic_scandesc(ndesc, ctx)) == CL_VIRUS)
6ad45a29
 	cli_dbgmsg("CryptFF: Infected with %s\n", cli_get_last_virus(ctx));
2c6f9d57
 
     close(ndesc);
 
33068e09
     if(ctx->engine->keeptmp)
2c6f9d57
 	cli_dbgmsg("CryptFF: Decompressed data saved in %s\n", tempfile);
     else
871177cd
 	if (cli_unlink(tempfile)) ret = CL_EUNLINK;
2c6f9d57
 
     free(tempfile);
     return ret;
 }
 
2d5dbc37
 static int cli_scanpdf(cli_ctx *ctx, off_t offset)
798308de
 {
 	int ret;
33068e09
 	char *dir = cli_gentemp(ctx->engine->tmpdir);
798308de
 
5fc380f1
     if(!dir)
 	return CL_EMEM;
798308de
 
     if(mkdir(dir, 0700)) {
 	cli_dbgmsg("Can't create temporary directory for PDF file %s\n", dir);
 	free(dir);
 	return CL_ETMPDIR;
     }
 
2d5dbc37
     ret = cli_pdf(dir, ctx, offset);
798308de
 
33068e09
     if(!ctx->engine->keeptmp)
798308de
 	cli_rmdirs(dir);
 
     free(dir);
     return ret;
 }
 
3d8c1fc7
 static int cli_scantnef(cli_ctx *ctx)
f0bc32bd
 {
 	int ret;
33068e09
 	char *dir = cli_gentemp(ctx->engine->tmpdir);
f0bc32bd
 
5fc380f1
     if(!dir)
 	return CL_EMEM;
f0bc32bd
 
     if(mkdir(dir, 0700)) {
 	cli_dbgmsg("Can't create temporary directory for tnef file %s\n", dir);
 	free(dir);
 	return CL_ETMPDIR;
     }
 
3d8c1fc7
     ret = cli_tnef(dir, ctx);
f0bc32bd
 
     if(ret == CL_CLEAN)
cb680655
 	ret = cli_scandir(dir, ctx);
f0bc32bd
 
33068e09
     if(!ctx->engine->keeptmp)
f0bc32bd
 	cli_rmdirs(dir);
 
     free(dir);
     return ret;
 }
 
ee1b2a6c
 static int cli_scanuuencoded(cli_ctx *ctx)
3953039b
 {
 	int ret;
33068e09
 	char *dir = cli_gentemp(ctx->engine->tmpdir);
3953039b
 
5fc380f1
     if(!dir)
 	return CL_EMEM;
 
3953039b
     if(mkdir(dir, 0700)) {
 	cli_dbgmsg("Can't create temporary directory for uuencoded file %s\n", dir);
 	free(dir);
 	return CL_ETMPDIR;
     }
 
ee1b2a6c
     ret = cli_uuencode(dir, *ctx->fmap);
3953039b
 
     if(ret == CL_CLEAN)
cb680655
 	ret = cli_scandir(dir, ctx);
3953039b
 
33068e09
     if(!ctx->engine->keeptmp)
3953039b
 	cli_rmdirs(dir);
 
     free(dir);
     return ret;
 }
 
2df29bde
 static int cli_scanmail(cli_ctx *ctx)
e3aaff8e
 {
 	char *dir;
 	int ret;
6ad45a29
 	unsigned int viruses_found = 0;
e3aaff8e
 
d91ab809
     cli_dbgmsg("Starting cli_scanmail(), recursion = %u\n", ctx->recursion);
e3aaff8e
 
0c7019c5
     /* generate the temporary directory */
33068e09
     if(!(dir = cli_gentemp(ctx->engine->tmpdir)))
5fc380f1
 	return CL_EMEM;
 
0c7019c5
     if(mkdir(dir, 0700)) {
 	cli_dbgmsg("Mail: Can't create temporary directory %s\n", dir);
 	free(dir);
 	return CL_ETMPDIR;
     }
e3aaff8e
 
0c7019c5
     /*
      * Extract the attachments into the temporary directory
      */
2df29bde
     if((ret = cli_mbox(dir, ctx))) {
6ad45a29
 	if (ret == CL_VIRUS && SCAN_ALL)
 	    viruses_found++;
 	else {
 	    if(!ctx->engine->keeptmp)
 		cli_rmdirs(dir);
 	    free(dir);
 	    return ret;
 	}
0c7019c5
     }
 
cb680655
     ret = cli_scandir(dir, ctx);
0c7019c5
 
33068e09
     if(!ctx->engine->keeptmp)
0c7019c5
 	cli_rmdirs(dir);
 
     free(dir);
6ad45a29
     if (SCAN_ALL && viruses_found)
 	return CL_VIRUS;
0c7019c5
     return ret;
e3aaff8e
 }
 
1b4b5675
 static int cli_scan_structured(cli_ctx *ctx)
a6e38800
 {
 	char buf[8192];
 	int result = 0;
 	unsigned int cc_count = 0;
 	unsigned int ssn_count = 0;
 	int done = 0;
b0d2122c
 	fmap_t *map;
1b4b5675
 	size_t pos = 0;
a6e38800
 	int (*ccfunc)(const unsigned char *buffer, int length);
 	int (*ssnfunc)(const unsigned char *buffer, int length);
b81cbc26
 	unsigned int viruses_found = 0;
a6e38800
 
724b2bf7
     if(ctx == NULL)
a6e38800
 	return CL_ENULLARG;
 
e664809d
     map = *ctx->fmap;
b0d2122c
 
724b2bf7
     if(ctx->engine->min_cc_count == 1)
a6e38800
 	ccfunc = dlp_has_cc;
     else
 	ccfunc = dlp_get_cc_count;
 
26fbf6bd
     switch((ctx->options & CL_SCAN_STRUCTURED_SSN_NORMAL) | (ctx->options & CL_SCAN_STRUCTURED_SSN_STRIPPED)) {
a6e38800
 
26fbf6bd
 	case (CL_SCAN_STRUCTURED_SSN_NORMAL | CL_SCAN_STRUCTURED_SSN_STRIPPED):
724b2bf7
 	    if(ctx->engine->min_ssn_count == 1)
a6e38800
 		ssnfunc = dlp_has_ssn;
 	    else
 		ssnfunc = dlp_get_ssn_count;
 	    break;
 
26fbf6bd
 	case CL_SCAN_STRUCTURED_SSN_NORMAL:
724b2bf7
 	    if(ctx->engine->min_ssn_count == 1)
a6e38800
 		ssnfunc = dlp_has_normal_ssn;
 	    else
 		ssnfunc = dlp_get_normal_ssn_count;
 	    break;
 
26fbf6bd
 	case CL_SCAN_STRUCTURED_SSN_STRIPPED:
724b2bf7
 	    if(ctx->engine->min_ssn_count == 1)
a6e38800
 		ssnfunc = dlp_has_stripped_ssn;
 	    else
 		ssnfunc = dlp_get_stripped_ssn_count;
 	    break;
26fbf6bd
 
 	default:
 	    ssnfunc = NULL;
a6e38800
     }
 
1b4b5675
     while(!done && ((result = fmap_readn(map, buf, pos, 8191)) > 0)) {
 	pos += result;
724b2bf7
 	if((cc_count += ccfunc((const unsigned char *)buf, result)) >= ctx->engine->min_cc_count)
a6e38800
 	    done = 1;
26fbf6bd
 
724b2bf7
 	if(ssnfunc && ((ssn_count += ssnfunc((const unsigned char *)buf, result)) >= ctx->engine->min_ssn_count))
a6e38800
 	    done = 1;
     }
 
724b2bf7
     if(cc_count != 0 && cc_count >= ctx->engine->min_cc_count) {
a6e38800
 	cli_dbgmsg("cli_scan_structured: %u credit card numbers detected\n", cc_count);
6ad45a29
 	cli_append_virus(ctx,"Heuristics.Structured.CreditCardNumber");
 	if (SCAN_ALL)
 	    viruses_found++;
 	else
 	    return CL_VIRUS;
a6e38800
     }
 
724b2bf7
     if(ssn_count != 0 && ssn_count >= ctx->engine->min_ssn_count) {
a6e38800
 	cli_dbgmsg("cli_scan_structured: %u social security numbers detected\n", ssn_count);
6ad45a29
 	cli_append_virus(ctx,"Heuristics.Structured.SSN");
 	if (SCAN_ALL)
 	    viruses_found++;
 	else
 	    return CL_VIRUS;
a6e38800
     }
 
6ad45a29
     if (SCAN_ALL && viruses_found)
 	return CL_VIRUS;
a6e38800
     return CL_CLEAN;
 }
 
822160b5
 static int cli_scanembpe(cli_ctx *ctx, off_t offset)
ee99255a
 {
 	int fd, bytes, ret = CL_CLEAN;
822160b5
 	unsigned long int size = 0, todo;
f304dc68
 	const char *buff;
ee99255a
 	char *tmpname;
822160b5
 	fmap_t *map = *ctx->fmap;
cfe6b4a2
 	unsigned int corrupted_input;
ee99255a
 
33068e09
     tmpname = cli_gentemp(ctx->engine->tmpdir);
ee99255a
     if(!tmpname)
 	return CL_EMEM;
 
     if((fd = open(tmpname, O_RDWR|O_CREAT|O_TRUNC|O_BINARY, S_IRWXU)) < 0) {
 	cli_errmsg("cli_scanembpe: Can't create file %s\n", tmpname);
 	free(tmpname);
871177cd
 	return CL_ECREAT;
ee99255a
     }
 
822160b5
     todo = map->len - offset;
     while(1) {
 	bytes = MIN(todo, map->pgsz);
 	if(!bytes)
 	    break;
 
 	if(!(buff = fmap_need_off_once(map, offset + size, bytes))) {
 	    close(fd);
 	    if(!ctx->engine->keeptmp) {
 		if (cli_unlink(tmpname)) {
 		    free(tmpname);
 		    return CL_EUNLINK;
 		}
 	    }
 	    free(tmpname);
 	    return CL_EREAD;
 	}
ee99255a
 	size += bytes;
822160b5
 	todo -= bytes;
ee99255a
 
822160b5
 	if(cli_checklimits("cli_scanembpe", ctx, size, 0, 0)!=CL_CLEAN)
ee99255a
 	    break;
 
 	if(cli_writen(fd, buff, bytes) != bytes) {
 	    cli_dbgmsg("cli_scanembpe: Can't write to temporary file\n");
 	    close(fd);
33068e09
 	    if(!ctx->engine->keeptmp) {
997a0e0b
 		if (cli_unlink(tmpname)) {
 		    free(tmpname);
871177cd
 		    return CL_EUNLINK;
997a0e0b
 		}
 	    }
822160b5
 	    free(tmpname);
871177cd
 	    return CL_EWRITE;
ee99255a
 	}
     }
 
f0f7f92f
     ctx->recursion++;
cfe6b4a2
     corrupted_input = ctx->corrupted_input;
     ctx->corrupted_input = 1;
     ret = cli_magic_scandesc(fd, ctx);
     ctx->corrupted_input = corrupted_input;
     if(ret == CL_VIRUS) {
6ad45a29
 	cli_dbgmsg("cli_scanembpe: Infected with %s\n", cli_get_last_virus(ctx));
ee99255a
 	close(fd);
33068e09
 	if(!ctx->engine->keeptmp) {
997a0e0b
 	    if (cli_unlink(tmpname)) {
 	    	free(tmpname);
871177cd
 		return CL_EUNLINK;
997a0e0b
 	    }
 	}
ee99255a
 	free(tmpname);	
 	return CL_VIRUS;
     }
f0f7f92f
     ctx->recursion--;
ee99255a
 
     close(fd);
33068e09
     if(!ctx->engine->keeptmp) {
997a0e0b
 	if (cli_unlink(tmpname)) {
 	    free(tmpname);
871177cd
 	    return CL_EUNLINK;
997a0e0b
 	}
     }
ee99255a
     free(tmpname);
 
     /* intentionally ignore possible errors from cli_magic_scandesc */
     return CL_CLEAN;
 }
 
63feb6cd
 
 #if defined(_WIN32) || defined(C_LINUX)
 #define PERF_MEASURE
 #endif
 
 #ifdef PERF_MEASURE
 
 static struct {
     enum perfev id;
     const char *name;
     enum ev_type type;
 } perf_events[] = {
     {PERFT_SCAN, "full scan", ev_time},
     {PERFT_PRECB, "prescan cb", ev_time},
     {PERFT_POSTCB, "postscan cb", ev_time},
     {PERFT_CACHE, "cache", ev_time},
     {PERFT_FT, "filetype", ev_time},
     {PERFT_CONTAINER, "container", ev_time},
     {PERFT_SCRIPT, "script", ev_time},
     {PERFT_PE, "pe", ev_time},
     {PERFT_RAW, "raw", ev_time},
     {PERFT_RAWTYPENO, "raw container", ev_time},
     {PERFT_MAP, "map", ev_time},
     {PERFT_BYTECODE,"bytecode", ev_time},
     {PERFT_KTIME,"kernel", ev_int},
     {PERFT_UTIME,"user", ev_int}
 };
 
 static void get_thread_times(uint64_t *kt, uint64_t *ut)
 {
 #ifdef _WIN32
87791cc9
     FILETIME c,e,k,u;
63feb6cd
     ULARGE_INTEGER kl,ul;
     if (!GetThreadTimes(GetCurrentThread(), &c, &e, &k, &u)) {
 	*kt = *ut = 0;
 	return;
     }
     kl.LowPart = k.dwLowDateTime;
     kl.HighPart = k.dwHighDateTime;
     ul.LowPart = u.dwLowDateTime;
     ul.HighPart = u.dwHighDateTime;
     *kt = kl.QuadPart / 10;
     *ut = ul.QuadPart / 10;
 #else
     struct tms tbuf;
     if (times(&tbuf) != -1) {
 	clock_t tck = sysconf(_SC_CLK_TCK);
59a60382
 	*kt = ((uint64_t)1000000)*tbuf.tms_stime / tck;
 	*ut = ((uint64_t)1000000)*tbuf.tms_utime / tck;
63feb6cd
     } else {
 	*kt = *ut = 0;
     }
 #endif
 }
 
 static inline void perf_init(cli_ctx *ctx)
 {
     uint64_t kt,ut;
     unsigned i;
 
     if (!(ctx->options & CL_SCAN_PERFORMANCE_INFO))
 	return;
 
     ctx->perf = cli_events_new(PERFT_LAST);
     for (i=0;i<sizeof(perf_events)/sizeof(perf_events[0]);i++) {
 	if (cli_event_define(ctx->perf, perf_events[i].id, perf_events[i].name,
 			     perf_events[i].type, multiple_sum) == -1)
 	    continue;
     }
     cli_event_time_start(ctx->perf, PERFT_SCAN);
     get_thread_times(&kt, &ut);
     cli_event_int(ctx->perf, PERFT_KTIME, -kt);
     cli_event_int(ctx->perf, PERFT_UTIME, -ut);
 }
 
 static inline void perf_done(cli_ctx* ctx)
 {
     char timestr[512];
     char *p;
     unsigned i;
     uint64_t kt,ut;
b724f199
     char *pend;
63feb6cd
     cli_events_t *perf = ctx->perf;
 
     if (!perf)
 	return;
 
     p = timestr;
b724f199
     pend = timestr + sizeof(timestr) - 1;
63feb6cd
     *pend = 0;
 
     cli_event_time_stop(perf, PERFT_SCAN);
     get_thread_times(&kt, &ut);
     cli_event_int(perf, PERFT_KTIME, kt);
     cli_event_int(perf, PERFT_UTIME, ut);
 
     for (i=0;i<sizeof(perf_events)/sizeof(perf_events[0]);i++) {
 	union ev_val val;
 	unsigned count;
 
 	cli_event_get(perf, perf_events[i].id, &val, &count);
 	if (p < pend)
 	    p += snprintf(p, pend - p, "%s: %d.%03ums, ", perf_events[i].name,
 			  (signed)(val.v_int / 1000),
 			  (unsigned)(val.v_int % 1000));
     }
     *p = 0;
     cli_infomsg(ctx, "performance: %s\n", timestr);
 
 
     cli_events_free(perf);
     ctx->perf = NULL;
 }
 
 static inline void perf_start(cli_ctx* ctx, int id)
 {
     cli_event_time_start(ctx->perf, id);
 }
 
 static inline void perf_stop(cli_ctx* ctx, int id)
 {
     cli_event_time_stop(ctx->perf, id);
 }
 
 static inline void perf_nested_start(cli_ctx* ctx, int id, int nestedid)
 {
     cli_event_time_nested_start(ctx->perf, id, nestedid);
 }
 
 static inline void perf_nested_stop(cli_ctx* ctx, int id, int nestedid)
 {
     cli_event_time_nested_stop(ctx->perf, id, nestedid);
 }
 
 
 #else
e039c93c
 static inline void perf_init(cli_ctx* ctx) {}
63feb6cd
 static inline void perf_start(cli_ctx* ctx, int id){}
 static inline void perf_stop(cli_ctx* ctx, int id){}
6205d4ea
 static inline void perf_nested_start(cli_ctx* ctx, int id, int nestedid){}
 static inline void perf_nested_stop(cli_ctx* ctx, int id, int nestedid){}
e039c93c
 static inline void perf_done(cli_ctx* ctx){}
63feb6cd
 #endif
 
 
548b55be
 static int cli_scanraw(cli_ctx *ctx, cli_file_t type, uint8_t typercg, cli_file_t *dettype, unsigned char *refhash)
555c5390
 {
6191ee2c
 	int ret = CL_CLEAN, nret = CL_CLEAN;
555c5390
 	struct cli_matched_type *ftoffset = NULL, *fpt;
583cd65f
 	uint32_t lastrar;
ee99255a
 	struct cli_exe_info peinfo;
6038397e
 	unsigned int acmode = AC_SCAN_VIR, break_loop = 0;
49cc1e3c
 	fmap_t *map = *ctx->fmap;
a5b0f84b
 	cli_file_t current_container_type = ctx->container_type;
 	size_t current_container_size = ctx->container_size;
555c5390
 
 
8df99a92
     if(ctx->engine->maxreclevel && ctx->recursion >= ctx->engine->maxreclevel)
         return CL_EMAXREC;
 
63feb6cd
     perf_start(ctx, PERFT_RAW);
8df99a92
     if(typercg)
 	acmode |= AC_SCAN_FT;
555c5390
 
ffa9b060
     ret = cli_fmap_scandesc(ctx, type == CL_TYPE_TEXT_ASCII ? 0 : type, 0, &ftoffset, acmode, NULL, refhash);
63feb6cd
     perf_stop(ctx, PERFT_RAW);
555c5390
 
c8b0d9a2
     if(ret >= CL_TYPENO) {
63feb6cd
 	perf_nested_start(ctx, PERFT_RAWTYPENO, PERFT_SCAN);
8df99a92
 	ctx->recursion++;
6ad45a29
 	if(nret != CL_VIRUS) { //TODO: don't need this test: nret == CL_CLEAN
583cd65f
 	    lastrar = 0xdeadbeef;
d68a73d1
 	    fpt = ftoffset;
 	    while(fpt) {
8df99a92
 		if(fpt->offset) switch(fpt->type) {
d68a73d1
 		    case CL_TYPE_RARSFX:
09b29e1e
 			if(type != CL_TYPE_RAR && have_rar && SCAN_ARCHIVE && (DCONF_ARCH & ARCH_CONF_RAR)) {
a5b0f84b
 			    ctx->container_type = CL_TYPE_RAR;
 			    ctx->container_size = map->len - fpt->offset; /* not precise */
8df99a92
 			    cli_dbgmsg("RAR/RAR-SFX signature found at %u\n", (unsigned int) fpt->offset);
b4d884d9
 			    nret = cli_scanrar(fmap_fd(map), ctx, fpt->offset, &lastrar);
d68a73d1
 			}
 			break;
555c5390
 
d68a73d1
 		    case CL_TYPE_ZIPSFX:
09b29e1e
 			if(type != CL_TYPE_ZIP && SCAN_ARCHIVE && (DCONF_ARCH & ARCH_CONF_ZIP)) {
a5b0f84b
 			    ctx->container_type = CL_TYPE_ZIP;
 			    ctx->container_size = map->len - fpt->offset; /* not precise */
8df99a92
 			    cli_dbgmsg("ZIP/ZIP-SFX signature found at %u\n", (unsigned int) fpt->offset);
2d5dbc37
 			    nret = cli_unzip_single(ctx, fpt->offset);
d68a73d1
 			}
 			break;
d8a5c616
 
d68a73d1
 		    case CL_TYPE_CABSFX:
09b29e1e
 			if(type != CL_TYPE_MSCAB && SCAN_ARCHIVE && (DCONF_ARCH & ARCH_CONF_CAB)) {
a5b0f84b
 			    ctx->container_type = CL_TYPE_MSCAB;
 			    ctx->container_size = map->len - fpt->offset; /* not precise */
8df99a92
 			    cli_dbgmsg("CAB/CAB-SFX signature found at %u\n", (unsigned int) fpt->offset);
5914844a
 			    nret = cli_scanmscab(ctx, fpt->offset);
555c5390
 			}
d68a73d1
 			break;
9d96e4b6
 		    case CL_TYPE_ARJSFX:
09b29e1e
 			if(type != CL_TYPE_ARJ && SCAN_ARCHIVE && (DCONF_ARCH & ARCH_CONF_ARJ)) {
a5b0f84b
 			    ctx->container_type = CL_TYPE_ARJ;
 			    ctx->container_size = map->len - fpt->offset; /* not precise */
9d96e4b6
 			    cli_dbgmsg("ARJ-SFX signature found at %u\n", (unsigned int) fpt->offset);
3f065bbe
 			    nret = cli_scanarj(ctx, fpt->offset, &lastrar);
9d96e4b6
 			}
 			break;
555c5390
 
9a47aa20
 		    case CL_TYPE_7ZSFX:
 			if(type != CL_TYPE_7Z && SCAN_ARCHIVE && (DCONF_ARCH & ARCH_CONF_7Z)) {
 			    ctx->container_type = CL_TYPE_7Z;
 			    ctx->container_size = map->len - fpt->offset; /* not precise */
 			    cli_dbgmsg("7Zip-SFX signature found at %u\n", (unsigned int) fpt->offset);
 			    nret = cli_7unz(ctx, fpt->offset);
583cd65f
 			}
 			break;
 
 		    case CL_TYPE_ISO9660:
 			if(SCAN_ARCHIVE && (DCONF_ARCH & ARCH_CONF_ISO9660)) {
 			    ctx->container_type = CL_TYPE_ISO9660;
 			    ctx->container_size = map->len - fpt->offset; /* not precise */
 			    cli_dbgmsg("ISO9660 signature found at %u\n", (unsigned int) fpt->offset);
 			    nret = cli_scaniso(ctx, fpt->offset);
9d96e4b6
 			}
 			break;
555c5390
 
faaf436a
 		    case CL_TYPE_NULSFT:
8fb8d069
 		        if(SCAN_ARCHIVE && type == CL_TYPE_MSEXE && (DCONF_ARCH & ARCH_CONF_NSIS) && fpt->offset > 4) {
a5b0f84b
 			    ctx->container_type = CL_TYPE_NULSFT;
 			    ctx->container_size = map->len - fpt->offset; /* not precise */
faaf436a
 			    cli_dbgmsg("NSIS signature found at %u\n", (unsigned int) fpt->offset-4);
43a6aed5
 			    nret = cli_scannulsft(ctx, fpt->offset - 4);
faaf436a
 			}
 			break;
 
ed93f138
 		    case CL_TYPE_AUTOIT:
7c06afc6
 		        if(SCAN_ARCHIVE && type == CL_TYPE_MSEXE && (DCONF_ARCH & ARCH_CONF_AUTOIT)) {
a5b0f84b
 			    ctx->container_type = CL_TYPE_AUTOIT;
 			    ctx->container_size = map->len - fpt->offset; /* not precise */
ed93f138
 			    cli_dbgmsg("AUTOIT signature found at %u\n", (unsigned int) fpt->offset);
ac867aad
 			    nret = cli_scanautoit(ctx, fpt->offset + 23);
ed93f138
 			}
 			break;
 
cadaa703
 		    case CL_TYPE_ISHIELD_MSI:
9981dfc4
 		        if(SCAN_ARCHIVE && type == CL_TYPE_MSEXE && (DCONF_ARCH & ARCH_CONF_ISHIELD)) {
a5b0f84b
 			    ctx->container_type = CL_TYPE_AUTOIT;
 			    ctx->container_size = map->len - fpt->offset; /* not precise */
cadaa703
 			    cli_dbgmsg("ISHIELD-MSI signature found at %u\n", (unsigned int) fpt->offset);
9a4da6af
 			    nret = cli_scanishield_msi(ctx, fpt->offset + 14);
cadaa703
 			}
 			break;
 
ca019d6d
 		    case CL_TYPE_DMG:
 			if(SCAN_ARCHIVE && (DCONF_ARCH & ARCH_CONF_DMG)) {
 			    ctx->container_type = CL_TYPE_DMG;
 			    nret = cli_scandmg(ctx);
 			    cli_dbgmsg("DMG signature found at %u\n", (unsigned int) fpt->offset);
 			}
 			break;
 
72ce4b70
 		    case CL_TYPE_PDF:
8df99a92
 			if(type != CL_TYPE_PDF && SCAN_PDF && (DCONF_DOC & DOC_CONF_PDF)) {
a5b0f84b
 			    ctx->container_type = CL_TYPE_PDF;
 			    ctx->container_size = map->len - fpt->offset; /* not precise */
72ce4b70
 			    cli_dbgmsg("PDF signature found at %u\n", (unsigned int) fpt->offset);
2d5dbc37
 			    nret = cli_scanpdf(ctx, fpt->offset);
72ce4b70
 			}
 			break;
 
d68a73d1
 		    case CL_TYPE_MSEXE:
8df99a92
  			if(SCAN_PE && (type == CL_TYPE_MSEXE || type == CL_TYPE_ZIP || type == CL_TYPE_MSOLE2) && ctx->dconf->pe) {
b2726a53
 			    uint64_t curr_len = map->len;
 			    /* CL_ENGINE_MAX_EMBEDDED_PE */
 			    if(curr_len > ctx->engine->maxembeddedpe) {
 				cli_dbgmsg("cli_scanraw: MaxEmbeddedPE exceeded\n");
198c851c
 				break;
b2726a53
 			    }
a5b0f84b
 			    ctx->container_type = CL_TYPE_MSEXE; /* PE is a container for another executable here */
 			    ctx->container_size = map->len - fpt->offset; /* not precise */
ee99255a
 			    memset(&peinfo, 0, sizeof(struct cli_exe_info));
 			    peinfo.offset = fpt->offset;
048d7677
 			    if(cli_peheader(map, &peinfo) == 0) {
198c851c
 				cli_dbgmsg("*** Detected embedded PE file at %u ***\n", (unsigned int) fpt->offset);
ee99255a
 				if(peinfo.section)
 				    free(peinfo.section);
5ba28e73
 				cli_hashset_destroy(&peinfo.vinfo);
ee99255a
 
822160b5
 				nret = cli_scanembpe(ctx, fpt->offset);
d68a73d1
 				break_loop = 1; /* we can stop here and other
 						 * embedded executables will
 						 * be found recursively
 						 * through the above call
 						 */
ee99255a
 			    }
 			}
d68a73d1
 			break;
 
 		    default:
 			cli_warnmsg("cli_scanraw: Type %u not handled in fpt loop\n", fpt->type);
ee99255a
 		}
d68a73d1
 
 		if(nret == CL_VIRUS || break_loop)
 		    break;
 
 		fpt = fpt->next;
 	    }
a5b0f84b
 	    ctx->container_type = current_container_type;
 	    ctx->container_size = current_container_size;
d68a73d1
 	}
 
 	if(nret != CL_VIRUS) switch(ret) {
 	    case CL_TYPE_HTML:
a810ba50
 		if(SCAN_HTML && type == CL_TYPE_TEXT_ASCII && (DCONF_DOC & DOC_CONF_HTML)) {
 		    *dettype = CL_TYPE_HTML;
084d19aa
 		    nret = cli_scanhtml(ctx);
a810ba50
 		}
d68a73d1
 		break;
 
 	    case CL_TYPE_MAIL:
a5b0f84b
 		ctx->container_type = CL_TYPE_MAIL;
 		ctx->container_size = map->len;
ee50848a
 		if(SCAN_MAIL && type == CL_TYPE_TEXT_ASCII && (DCONF_MAIL & MAIL_CONF_MBOX)) {
 		    *dettype = CL_TYPE_MAIL;
2df29bde
 		    nret = cli_scanmail(ctx);
ee50848a
 		}
a5b0f84b
 		ctx->container_type = current_container_type;
 		ctx->container_size = current_container_size;
ee99255a
 		break;
 
555c5390
 	    default:
 		break;
 	}
63feb6cd
 	perf_nested_stop(ctx, PERFT_RAWTYPENO, PERFT_SCAN);
d91ab809
 	ctx->recursion--;
6191ee2c
 	ret = nret;
555c5390
     }
 
c8b0d9a2
     while(ftoffset) {
 	fpt = ftoffset;
 	ftoffset = ftoffset->next;
 	free(fpt);
     }
 
     if(ret == CL_VIRUS)
6ad45a29
 	cli_dbgmsg("%s found\n", cli_get_last_virus(ctx));
c8b0d9a2
 
555c5390
     return ret;
 }
 
aef8d4ac
 
742b3a0e
 static void emax_reached(cli_ctx *ctx) {
     fmap_t **ctx_fmap = ctx->fmap;
b6c03fb9
     if (!ctx_fmap)
 	return;
742b3a0e
     while(*ctx_fmap) {
 	fmap_t *map = *ctx_fmap;
 	map->dont_cache_flag = 1;
 	ctx_fmap--;
     }
     cli_dbgmsg("emax_reached: marked parents as non cacheable\n");
 }
 
aef8d4ac
 #define LINESTR(x) #x
 #define LINESTR2(x) LINESTR(x)
 #define __AT__  " at line "LINESTR2(__LINE__)
60af015e
 
6ad45a29
 #define early_ret_from_magicscan(retcode)				\
     do {								\
 	cli_dbgmsg("cli_magic_scandesc: returning %d %s (no post, no cache)\n", retcode, __AT__); \
 	return retcode;							\
60af015e
     } while(0)
 
6ad45a29
 #define ret_from_magicscan(retcode)					\
     do {								\
 	cli_dbgmsg("cli_magic_scandesc: returning %d %s\n", retcode, __AT__); \
 	if(ctx->engine->cb_post_scan) {					\
 	    perf_start(ctx, PERFT_POSTCB);				\
b81cbc26
 	    switch(ctx->engine->cb_post_scan(fmap_fd(*ctx->fmap), retcode, retcode == CL_VIRUS ? cli_get_last_virus(ctx) : NULL, ctx->cb_ctx)) { \
a217d9a7
 	    case CL_BREAK:									\
 		cli_dbgmsg("cli_magic_scandesc: file whitelisted by post_scan callback\n"); 	\
 		perf_stop(ctx, PERFT_POSTCB);							\
 		return CL_CLEAN;								\
 	    case CL_VIRUS:									\
 		cli_dbgmsg("cli_magic_scandesc: file blacklisted by post_scan callback\n");	\
6ad45a29
 		cli_append_virus(ctx, "Detected.By.Callback");					\
a217d9a7
 		perf_stop(ctx, PERFT_POSTCB);							\
c86a1d4b
 		if (retcode != CL_VIRUS)                                                        \
 		    return cli_checkfp(hash, hashed_size, ctx);                                 \
a217d9a7
 		return CL_VIRUS;								\
 	    case CL_CLEAN:									\
 		break;										\
 	    default:										\
 		cli_warnmsg("cli_magic_scandesc: ignoring bad return code from post_scan callback\n");	\
 	    }											\
 	    perf_stop(ctx, PERFT_POSTCB);							\
eb422a03
 	}											\
60af015e
 	if (retcode == CL_CLEAN && cache_clean) {                                               \
 	    perf_start(ctx, PERFT_CACHE);                                                       \
 	    cache_add(hash, hashed_size, ctx);                                                  \
 	    perf_stop(ctx, PERFT_CACHE);							\
 	}											\
a217d9a7
 	return retcode;										\
aef8d4ac
     } while(0)
742b3a0e
 
c27d4056
 
a217d9a7
 #define CALL_PRESCAN_CB(scanfn)	                                                     \
     if(ctx->engine->scanfn) {				\
c27d4056
 	perf_start(ctx, PERFT_PRECB);                                                        \
dd64326e
 	switch(ctx->engine->scanfn(fmap_fd(*ctx->fmap), filetype, ctx->cb_ctx)) {            \
c27d4056
 	case CL_BREAK:                                                                       \
a217d9a7
 	    cli_dbgmsg("cli_magic_scandesc: file whitelisted by "#scanfn" callback\n");                \
c27d4056
 	    perf_stop(ctx, PERFT_PRECB);                                                     \
dd64326e
 	    ctx->hook_lsig_matches = old_hook_lsig_matches;                                  \
c27d4056
 	    ret_from_magicscan(CL_CLEAN);                                                    \
 	case CL_VIRUS:                                                                       \
a217d9a7
 	    cli_dbgmsg("cli_magic_scandesc: file blacklisted by "#scanfn" callback\n");                \
6ad45a29
 	    cli_append_virus(ctx, "Detected.By.Callback");		                     \
c27d4056
 	    perf_stop(ctx, PERFT_PRECB);                                                     \
dd64326e
 	    ctx->hook_lsig_matches = old_hook_lsig_matches;                                  \
 	    ret_from_magicscan(cli_checkfp(hash, hashed_size, ctx));                         \
c27d4056
 	case CL_CLEAN:                                                                       \
 	    break;                                                                           \
 	default:                                                                             \
a217d9a7
 	    cli_warnmsg("cli_magic_scandesc: ignoring bad return code from callback\n");     \
c27d4056
 	}                                                                                    \
 	perf_stop(ctx, PERFT_PRECB);                                                         \
     }
 
 
 
b7ae31f1
 static int magic_scandesc(cli_ctx *ctx, cli_file_t type)
e3aaff8e
 {
7bbd5f7f
 	int ret = CL_CLEAN;
7770d314
 	cli_file_t dettype = 0;
ded60d81
 	uint8_t typercg = 1;
a5b0f84b
 	cli_file_t current_container_type = ctx->container_type;
52f52931
 	size_t current_container_size = ctx->container_size, hashed_size;
511c2e79
 	unsigned char hash[16];
f4e34215
 	bitset_t *old_hook_lsig_matches;
a217d9a7
 	const char *filetype;
ed98fae7
 	int cache_clean = 0, res;
6ad45a29
 	unsigned int viruses_found = 0;
a7f5fd00
 
3c91998b
     if(!ctx->engine) {
5612732c
 	cli_errmsg("CRITICAL: engine == NULL\n");
60af015e
 	early_ret_from_magicscan(CL_ENULLARG);
b3df93db
     }
 
     if(!(ctx->engine->dboptions & CL_DB_COMPILED)) {
 	cli_errmsg("CRITICAL: engine not compiled\n");
60af015e
 	early_ret_from_magicscan(CL_EMALFDB);
e3aaff8e
     }
 
b2726a53
     if(ctx->engine->maxreclevel && ctx->recursion > ctx->engine->maxreclevel) {
         cli_dbgmsg("cli_magic_scandesc: Archive recursion limit exceeded (%u, max: %u)\n", ctx->recursion, ctx->engine->maxreclevel);
 	emax_reached(ctx);
 	early_ret_from_magicscan(CL_CLEAN);
     }
 
b7ae31f1
     if(cli_updatelimits(ctx, (*ctx->fmap)->len)!=CL_CLEAN) {
742b3a0e
 	emax_reached(ctx);
60af015e
         early_ret_from_magicscan(CL_CLEAN);
998bcfa7
     }
dd64326e
     old_hook_lsig_matches = ctx->hook_lsig_matches;
1d1c4b15
     if(type == CL_TYPE_PART_ANY) {
 	typercg = 0;
     }
998bcfa7
 
a217d9a7
     perf_start(ctx, PERFT_FT);
1d1c4b15
     if((type == CL_TYPE_ANY) || type == CL_TYPE_PART_ANY)
 	type = cli_filetype2(*ctx->fmap, ctx->engine, type);
a217d9a7
     perf_stop(ctx, PERFT_FT);
     if(type == CL_TYPE_ERROR) {
 	cli_dbgmsg("cli_magic_scandesc: cli_filetype2 returned CL_TYPE_ERROR\n");
60af015e
 	early_ret_from_magicscan(CL_EREAD);
a0eb7910
     }
a217d9a7
     filetype = cli_ftname(type);
c86a1d4b
     hashed_size = 0;
a217d9a7
     CALL_PRESCAN_CB(cb_pre_cache);
a0eb7910
 
63feb6cd
     perf_start(ctx, PERFT_CACHE);
ed98fae7
     res = cache_check(hash, ctx);
     if(res != CL_VIRUS) {
63feb6cd
 	perf_stop(ctx, PERFT_CACHE);
ed98fae7
 	early_ret_from_magicscan(res);
60b21251
     }
ed98fae7
 
63feb6cd
     perf_stop(ctx, PERFT_CACHE);
52f52931
     hashed_size = (*ctx->fmap)->len;
f4e34215
     ctx->hook_lsig_matches = NULL;
52f52931
 
6ad45a29
     if(!(ctx->options&~CL_SCAN_ALLMATCHES) || (ctx->recursion == ctx->engine->maxreclevel)) { /* raw mode (stdin, etc.) or last level of recursion */
8df99a92
 	if(ctx->recursion == ctx->engine->maxreclevel)
 	    cli_dbgmsg("cli_magic_scandesc: Hit recursion limit, only scanning raw file\n");
 	else
 	    cli_dbgmsg("Raw mode: No support for special files\n");
ea6f1300
 
a217d9a7
 	CALL_PRESCAN_CB(cb_pre_scan);
60af015e
 	/* ret_from_magicscan can be used below here*/
ffa9b060
 	if((ret = cli_fmap_scandesc(ctx, 0, 0, NULL, AC_SCAN_VIR, NULL, hash)) == CL_VIRUS)
6ad45a29
 	    cli_dbgmsg("%s found in descriptor %d\n", cli_get_last_virus(ctx), fmap_fd(*ctx->fmap));
aef8d4ac
 	else if(ret == CL_CLEAN) {
 	    if(ctx->recursion != ctx->engine->maxreclevel)
60af015e
 		cache_clean = 1; /* Only cache if limits are not reached */
6b89f8e8
 	    else
742b3a0e
 		emax_reached(ctx);
aef8d4ac
 	}
 
17c20e12
 	ctx->hook_lsig_matches = old_hook_lsig_matches;
aef8d4ac
 	ret_from_magicscan(ret);
d91ab809
     }
e3aaff8e
 
a217d9a7
     CALL_PRESCAN_CB(cb_pre_scan);
60af015e
     /* ret_from_magicscan can be used below here*/
c27d4056
 
16b28d07
 #ifdef HAVE__INTERNAL__SHA_COLLECT
     if(!ctx->sha_collect && type==CL_TYPE_MSEXE) ctx->sha_collect = 1;
 #endif
6d6e8271
 
f4e34215
     ctx->hook_lsig_matches = cli_bitset_init();
17c20e12
     if (!ctx->hook_lsig_matches) {
 	ctx->hook_lsig_matches = old_hook_lsig_matches;
aef8d4ac
 	ret_from_magicscan(CL_EMEM);
17c20e12
     }
f4e34215
 
7021b545
     if(type != CL_TYPE_IGNORED && ctx->engine->sdb) {
548b55be
 	if((ret = cli_scanraw(ctx, type, 0, &dettype, hash)) == CL_VIRUS) {
32b1e04e
 	    ret = cli_checkfp(hash, hashed_size, ctx);
f4e34215
 	    cli_bitset_free(ctx->hook_lsig_matches);
 	    ctx->hook_lsig_matches = old_hook_lsig_matches;
aef8d4ac
 	    ret_from_magicscan(ret);
998bcfa7
 	}
555c5390
     }
 
d91ab809
     ctx->recursion++;
63feb6cd
     perf_nested_start(ctx, PERFT_CONTAINER, PERFT_SCAN);
b7ae31f1
     ctx->container_size = (*ctx->fmap)->len;
467f8b1e
     switch(type) {
7021b545
 	case CL_TYPE_IGNORED:
 	    break;
 
3805ebcb
 	case CL_TYPE_RAR:
55094a9c
 	    ctx->container_type = CL_TYPE_RAR;
5611c67f
 	    if(have_rar && SCAN_ARCHIVE && (DCONF_ARCH & ARCH_CONF_RAR)) {
 		char *tmpname = NULL;
 		int desc = fmap_fd(*ctx->fmap);
 		if (desc == -1) {
 		    size_t pos = 0, len;
 
 		    cli_dbgmsg("fmap not backed by file, dumping ...\n");
 		    if ((ret = cli_gentempfd(((cli_ctx*)ctx)->engine->tmpdir, &tmpname, &desc)) != CL_SUCCESS) {
 			cli_dbgmsg("fmap_fd: failed to generate temporary file.\n");
 			break;
 		    }
 		    do {
f304dc68
 			const char *b;
5611c67f
 
 			len = 0;
 			b = fmap_need_off_once_len(*ctx->fmap, pos, BUFSIZ, &len);
 			pos += len;
 			if (b && len > 0) {
 			    if (cli_writen(desc, b, len) != len) {
 				close(desc);
 				unlink(tmpname);
 				cli_warnmsg("fmap_fd_dump: write failed\n");
 				ret = CL_EWRITE;
 				break;
 			    }
 			}
 		    } while (len > 0);
96914546
 		    if (lseek(desc, 0, SEEK_SET) == -1) {
                 cli_dbgmsg("magic_scandesc: call to lseek() failed\n");
             }
5611c67f
 		}
994ae437
 		ret = cli_scanrar(desc, ctx, 0, NULL);
5611c67f
 		if (tmpname) {
 		    close(desc);
 		    unlink(tmpname);
 		    free(tmpname);
 		}
 	    }
467f8b1e
 	    break;
6d6e8271
 
3805ebcb
 	case CL_TYPE_ZIP:
55094a9c
 	    ctx->container_type = CL_TYPE_ZIP;
bc93eda0
 	    if(SCAN_ARCHIVE && (DCONF_ARCH & ARCH_CONF_ZIP))
bd7f7684
 		ret = cli_unzip(ctx);
467f8b1e
 	    break;
6d6e8271
 
3805ebcb
 	case CL_TYPE_GZ:
bc93eda0
 	    if(SCAN_ARCHIVE && (DCONF_ARCH & ARCH_CONF_GZ))
686ed348
 		ret = cli_scangzip(ctx);
467f8b1e
 	    break;
6d6e8271
 
3805ebcb
 	case CL_TYPE_BZ:
bc93eda0
 	    if(SCAN_ARCHIVE && (DCONF_ARCH & ARCH_CONF_BZ))
6b89f8e8
 		ret = cli_scanbzip(ctx);
467f8b1e
 	    break;
55094a9c
 
9d96e4b6
 	case CL_TYPE_ARJ:
55094a9c
 	    ctx->container_type = CL_TYPE_ARJ;
9d96e4b6
 	    if(SCAN_ARCHIVE && (DCONF_ARCH & ARCH_CONF_ARJ))
3f065bbe
 		ret = cli_scanarj(ctx, 0, NULL);
9d96e4b6
 	    break;
6d6e8271
 
faaf436a
         case CL_TYPE_NULSFT:
55094a9c
 	    ctx->container_type = CL_TYPE_NULSFT;
 	    if(SCAN_ARCHIVE && (DCONF_ARCH & ARCH_CONF_NSIS))
43a6aed5
 		ret = cli_scannulsft(ctx, 0);
faaf436a
 	    break;
ed93f138
 
         case CL_TYPE_AUTOIT:
55094a9c
 	    ctx->container_type = CL_TYPE_AUTOIT;
ffa6230b
 	    if(SCAN_ARCHIVE && (DCONF_ARCH & ARCH_CONF_AUTOIT))
ac867aad
 		ret = cli_scanautoit(ctx, 23);
ed93f138
 	    break;
6e47a652
 
3805ebcb
 	case CL_TYPE_MSSZDD:
bc93eda0
 	    if(SCAN_ARCHIVE && (DCONF_ARCH & ARCH_CONF_SZDD))
786a7e91
 		ret = cli_scanszdd(ctx);
341e5433
 	    break;
6e47a652
 
3805ebcb
 	case CL_TYPE_MSCAB:
55094a9c
 	    ctx->container_type = CL_TYPE_MSCAB;
bc93eda0
 	    if(SCAN_ARCHIVE && (DCONF_ARCH & ARCH_CONF_CAB))
5914844a
 		ret = cli_scanmscab(ctx, 0);
414abe87
 	    break;
 
bd988961
 	case CL_TYPE_HTML:
bc93eda0
 	    if(SCAN_HTML && (DCONF_DOC & DOC_CONF_HTML))
084d19aa
 		ret = cli_scanhtml(ctx);
bd988961
 	    break;
 
 	case CL_TYPE_HTML_UTF16:
bc93eda0
 	    if(SCAN_HTML && (DCONF_DOC & DOC_CONF_HTML))
084d19aa
 		ret = cli_scanhtml_utf16(ctx);
bd988961
 	    break;
 
015ce4a8
 	case CL_TYPE_SCRIPT:
a810ba50
 	    if((DCONF_DOC & DOC_CONF_SCRIPT) && dettype != CL_TYPE_HTML)
ee1b2a6c
 	        ret = cli_scanscript(ctx);
015ce4a8
 	    break;
 
44a3e21a
 	case CL_TYPE_SWF:
1e41fdba
 	    if(SCAN_SWF && (DCONF_DOC & DOC_CONF_SWF))
47762e70
 		ret = cli_scanswf(ctx);
44a3e21a
 	    break;
 
52c2a8bd
 	case CL_TYPE_RTF:
55094a9c
 	    ctx->container_type = CL_TYPE_RTF;
d91ab809
 	    if(SCAN_ARCHIVE && (DCONF_DOC & DOC_CONF_RTF))
362b5bca
 		ret = cli_scanrtf(ctx);
52c2a8bd
 	    break;
 
3805ebcb
 	case CL_TYPE_MAIL:
55094a9c
 	    ctx->container_type = CL_TYPE_MAIL;
bc93eda0
 	    if(SCAN_MAIL && (DCONF_MAIL & MAIL_CONF_MBOX))
2df29bde
 		ret = cli_scanmail(ctx);
467f8b1e
 	    break;
6d6e8271
 
846e4186
 	case CL_TYPE_TNEF:
bc93eda0
 	    if(SCAN_MAIL && (DCONF_MAIL & MAIL_CONF_TNEF))
3d8c1fc7
 		ret = cli_scantnef(ctx);
846e4186
 	    break;
 
3953039b
 	case CL_TYPE_UUENCODED:
bc93eda0
 	    if(DCONF_OTHER & OTHER_CONF_UUENC)
ee1b2a6c
 		ret = cli_scanuuencoded(ctx);
3953039b
 	    break;
 
3805ebcb
 	case CL_TYPE_MSCHM:
55094a9c
 	    ctx->container_type = CL_TYPE_MSCHM;
bc93eda0
 	    if(SCAN_ARCHIVE && (DCONF_ARCH & ARCH_CONF_CHM))
24ab4ad5
 		ret = cli_scanmschm(ctx);
a5373b64
 	    break;
 
3805ebcb
 	case CL_TYPE_MSOLE2:
55094a9c
 	    ctx->container_type = CL_TYPE_MSOLE2;
bc93eda0
 	    if(SCAN_OLE2 && (DCONF_ARCH & ARCH_CONF_OLE2))
034c02fd
 		ret = cli_scanole2(ctx);
467f8b1e
 	    break;
6d6e8271
 
81fded11
 	case CL_TYPE_7Z:
55094a9c
 	    ctx->container_type = CL_TYPE_7Z;
81fded11
 	    if(SCAN_ARCHIVE && (DCONF_ARCH & ARCH_CONF_7Z))
9a47aa20
 		ret = cli_7unz(ctx, 0);
81fded11
 	    break;
 
a7f5fd00
 	case CL_TYPE_POSIX_TAR:
55094a9c
 	    ctx->container_type = CL_TYPE_POSIX_TAR;
bc93eda0
 	    if(SCAN_ARCHIVE && (DCONF_ARCH & ARCH_CONF_TAR))
a91f6d95
 		ret = cli_scantar(ctx, 1);
a7f5fd00
 	    break;
 
 	case CL_TYPE_OLD_TAR:
55094a9c
 	    ctx->container_type = CL_TYPE_OLD_TAR;
bc93eda0
 	    if(SCAN_ARCHIVE && (DCONF_ARCH & ARCH_CONF_TAR))
a91f6d95
 		ret = cli_scantar(ctx, 0);
667ab9c6
 	    break;
 
75e46945
 	case CL_TYPE_CPIO_OLD:
55094a9c
 	    ctx->container_type = CL_TYPE_CPIO_OLD;
75e46945
 	    if(SCAN_ARCHIVE && (DCONF_ARCH & ARCH_CONF_CPIO))
87af1d57
 		ret = cli_scancpio_old(ctx);
75e46945
 	    break;
 
 	case CL_TYPE_CPIO_ODC:
55094a9c
 	    ctx->container_type = CL_TYPE_CPIO_ODC;
75e46945
 	    if(SCAN_ARCHIVE && (DCONF_ARCH & ARCH_CONF_CPIO))
87af1d57
 		ret = cli_scancpio_odc(ctx);
75e46945
 	    break;
 
 	case CL_TYPE_CPIO_NEWC:
55094a9c
 	    ctx->container_type = CL_TYPE_CPIO_NEWC;
75e46945
 	    if(SCAN_ARCHIVE && (DCONF_ARCH & ARCH_CONF_CPIO))
87af1d57
 		ret = cli_scancpio_newc(ctx, 0);
75e46945
 	    break;
 
 	case CL_TYPE_CPIO_CRC:
55094a9c
 	    ctx->container_type = CL_TYPE_CPIO_CRC;
75e46945
 	    if(SCAN_ARCHIVE && (DCONF_ARCH & ARCH_CONF_CPIO))
87af1d57
 		ret = cli_scancpio_newc(ctx, 1);
75e46945
 	    break;
 
667ab9c6
 	case CL_TYPE_BINHEX:
bc93eda0
 	    if(SCAN_ARCHIVE && (DCONF_ARCH & ARCH_CONF_BINHEX))
124ba12d
 		ret = cli_binhex(ctx);
2b259453
 	    break;
 
3805ebcb
 	case CL_TYPE_SCRENC:
bc93eda0
 	    if(DCONF_OTHER & OTHER_CONF_SCRENC)
32f7e1d7
 		ret = cli_scanscrenc(ctx);
eb308794
 	    break;
 
 	case CL_TYPE_RIFF:
bc93eda0
 	    if(SCAN_ALGO && (DCONF_OTHER & OTHER_CONF_RIFF))
bad8bbc7
 		ret = cli_scanriff(ctx);
e57fa318
 	    break;
 
7afdc309
 	case CL_TYPE_GRAPHICS:
bc93eda0
 	    if(SCAN_ALGO && (DCONF_OTHER & OTHER_CONF_JPEG))
32d37729
 		ret = cli_scanjpeg(ctx);
b44fb658
 
 	    if(ctx->img_validate && SCAN_ALGO && ret != CL_VIRUS)
 		ret = cli_parsejpeg(ctx);
419a9d3d
 
 	    if(ctx->img_validate && SCAN_ALGO && ret != CL_VIRUS && ret != CL_EPARSE)
 		ret = cli_parsepng(ctx);
ac47dac7
 
 	    if(ctx->img_validate && SCAN_ALGO && ret != CL_VIRUS && ret != CL_EPARSE)
 		ret = cli_parsegif(ctx);
7afdc309
 	    break;
 
d070d475
         case CL_TYPE_PDF: /* FIXMELIMITS: pdf should be an archive! */
55094a9c
 	    ctx->container_type = CL_TYPE_PDF;
c5107e70
 	    if(SCAN_PDF && (DCONF_DOC & DOC_CONF_PDF))
2d5dbc37
 		ret = cli_scanpdf(ctx, 0);
798308de
 	    break;
 
2c6f9d57
 	case CL_TYPE_CRYPTFF:
bc93eda0
 	    if(DCONF_OTHER & OTHER_CONF_CRYPTFF)
0c9b8840
 		ret = cli_scancryptff(ctx);
2c6f9d57
 	    break;
 
3f97a1e7
 	case CL_TYPE_ELF:
bc93eda0
 	    if(SCAN_ELF && ctx->dconf->elf)
90b75c27
 		ret = cli_scanelf(ctx);
094116b2
 	    break;
 
89c14869
 	case CL_TYPE_MACHO:
 	    if(ctx->dconf->macho)
f4363389
 		ret = cli_scanmacho(ctx, NULL);
89c14869
 	    break;
 
3222a096
 	case CL_TYPE_MACHO_UNIBIN:
 	    if(ctx->dconf->macho)
f4363389
 		ret = cli_scanmacho_unibin(ctx);
89c14869
 	    break;
 
bf45bf13
 	case CL_TYPE_SIS:
55094a9c
 	    ctx->container_type = CL_TYPE_SIS;
bc93eda0
 	    if(SCAN_ARCHIVE && (DCONF_ARCH & ARCH_CONF_SIS))
ef82f5ab
 		ret = cli_scansis(ctx);
bf45bf13
 	    break;
 
5e56b827
 	case CL_TYPE_XAR:
 	    ctx->container_type = CL_TYPE_XAR;
 	    if(SCAN_ARCHIVE && (DCONF_ARCH & ARCH_CONF_XAR))
 		ret = cli_scanxar(ctx);
 	    break;
 
1d1c4b15
 	case CL_TYPE_PART_HFSPLUS:
 	    ctx->container_type = CL_TYPE_PART_HFSPLUS;
 	    if(SCAN_ARCHIVE && (DCONF_ARCH & ARCH_CONF_HFSPLUS))
 		ret = cli_scanhfsplus(ctx);
 	    break;
 
c8f2d060
 	case CL_TYPE_BINARY_DATA:
bad8bbc7
 	case CL_TYPE_TEXT_UTF16BE:
3f81d93a
 	    if(SCAN_ALGO && (DCONF_OTHER & OTHER_CONF_MYDOOMLOG))
d0e17a28
 		ret = cli_check_mydoom_log(ctx);
467f8b1e
 	    break;
216a697f
 
a6e38800
 	case CL_TYPE_TEXT_ASCII:
26fbf6bd
 	    if(SCAN_STRUCTURED && (DCONF_OTHER & OTHER_CONF_DLP))
a6e38800
 		/* TODO: consider calling this from cli_scanscript() for
 		 * a normalised text
 		 */
1b4b5675
 		ret = cli_scan_structured(ctx);
a6e38800
 	    break;
 
216a697f
 	default:
 	    break;
e3aaff8e
     }
63feb6cd
     perf_nested_stop(ctx, PERFT_CONTAINER, PERFT_SCAN);
d91ab809
     ctx->recursion--;
55094a9c
     ctx->container_type = current_container_type;
     ctx->container_size = current_container_size;
467f8b1e
 
998bcfa7
     if(ret == CL_VIRUS) {
32b1e04e
 	ret = cli_checkfp(hash, hashed_size, ctx);
f4e34215
 	cli_bitset_free(ctx->hook_lsig_matches);
 	ctx->hook_lsig_matches = old_hook_lsig_matches;
aef8d4ac
 	ret_from_magicscan(ret);
998bcfa7
     }
a6e38800
 
ded60d81
     if(type == CL_TYPE_ZIP && SCAN_ARCHIVE && (DCONF_ARCH & ARCH_CONF_ZIP)) {
b2726a53
 	/* CL_ENGINE_MAX_ZIPTYPERCG */
 	uint64_t curr_len = (*ctx->fmap)->len;
 	if(curr_len > ctx->engine->maxziptypercg) {
 	    cli_dbgmsg("cli_magic_scandesc: Not checking for embedded PEs (zip file > MaxZipTypeRcg)\n");
ded60d81
 	    typercg = 0;
 	}
     }
 
08f0150f
     /* CL_TYPE_HTML: raw HTML files are not scanned, unless safety measure activated via DCONF */
a6e38800
     if(type != CL_TYPE_IGNORED && (type != CL_TYPE_HTML || !(DCONF_DOC & DOC_CONF_HTML_SKIPRAW)) && !ctx->engine->sdb) {
ed98fae7
 	res = cli_scanraw(ctx, type, typercg, &dettype, hash);
 	if(res != CL_CLEAN) {
9ba8b8ca
 	    switch(res) {
1e2696b0
 		/* List of scan halts, runtime errors only! */
 		case CL_EUNLINK:
 		case CL_ESTAT:
9ba8b8ca
 		case CL_ESEEK:
1e2696b0
 		case CL_EWRITE:
 		case CL_EDUP:
 		case CL_ETMPFILE:
 		case CL_ETMPDIR:
9ba8b8ca
 		case CL_EMEM:
1e2696b0
 		case CL_ETIMEOUT:
9ba8b8ca
 		    cli_dbgmsg("Descriptor[%d]: cli_scanraw error %s\n", fmap_fd(*ctx->fmap), cl_strerror(res));
 		    cli_bitset_free(ctx->hook_lsig_matches);
 		    ctx->hook_lsig_matches = old_hook_lsig_matches;
 		    ret_from_magicscan(res);
 		/* CL_VIRUS = malware found, check FP and report */
 		case CL_VIRUS:
 		    ret = cli_checkfp(hash, hashed_size, ctx);
6ad45a29
 		    if (SCAN_ALL)
 			break;
9ba8b8ca
 		    cli_bitset_free(ctx->hook_lsig_matches);
 		    ctx->hook_lsig_matches = old_hook_lsig_matches;
 		    ret_from_magicscan(ret);
 		/* "MAX" conditions should still fully scan the current file */
cdbe2779
 		case CL_EMAXREC:
 		case CL_EMAXSIZE:
 		case CL_EMAXFILES:
9ba8b8ca
 		    ret = res;
 		    cli_dbgmsg("Descriptor[%d]: Continuing after cli_scanraw reached %s\n",
 			fmap_fd(*ctx->fmap), cl_strerror(res));
 		    break;
087e7fc3
 		/* Other errors must not block further scans below
 		 * This specifically includes CL_EFORMAT & CL_EREAD & CL_EUNPACK
 		 * Malformed/truncated files could report as any of these three.
 		 */
cdbe2779
 		default:
9ba8b8ca
 		    ret = res;
 		    cli_dbgmsg("Descriptor[%d]: Continuing after cli_scanraw error %s\n",
 			fmap_fd(*ctx->fmap), cl_strerror(res));
cdbe2779
 	    }
998bcfa7
 	}
46c2e927
     }
e3aaff8e
 
d91ab809
     ctx->recursion++;
77e4bb11
     switch(type) {
f4e34215
 	/* bytecode hooks triggered by a lsig must be a hook
 	 * called from one of the functions here */
a810ba50
 	case CL_TYPE_TEXT_ASCII:
2582d3ed
 	case CL_TYPE_TEXT_UTF16BE:
 	case CL_TYPE_TEXT_UTF16LE:
 	case CL_TYPE_TEXT_UTF8:
63feb6cd
 	    perf_nested_start(ctx, PERFT_SCRIPT, PERFT_SCAN);
6ad45a29
 	    if((DCONF_DOC & DOC_CONF_SCRIPT) && dettype != CL_TYPE_HTML && ret != CL_VIRUS)
ee1b2a6c
 	        ret = cli_scanscript(ctx);
ee50848a
 	    if(SCAN_MAIL && (DCONF_MAIL & MAIL_CONF_MBOX) && ret != CL_VIRUS && (ctx->container_type == CL_TYPE_MAIL || dettype == CL_TYPE_MAIL)) {
1423dffc
 		ret = cli_fmap_scandesc(ctx, CL_TYPE_MAIL, 0, NULL, AC_SCAN_VIR, NULL, NULL);
7e65889c
 	    }
63feb6cd
 	    perf_nested_stop(ctx, PERFT_SCRIPT, PERFT_SCAN);
a810ba50
 	    break;
77e4bb11
 	/* Due to performance reasons all executables were first scanned
 	 * in raw mode. Now we will try to unpack them
 	 */
3805ebcb
 	case CL_TYPE_MSEXE:
63feb6cd
 	    perf_nested_start(ctx, PERFT_PE, PERFT_SCAN);
50177b5c
 	    if(SCAN_PE && ctx->dconf->pe) {
 		unsigned int corrupted_input = ctx->corrupted_input;
453d8180
 		ret = cli_scanpe(ctx);
50177b5c
 		ctx->corrupted_input = corrupted_input;
 	    }
63feb6cd
 	    perf_nested_stop(ctx, PERFT_PE, PERFT_SCAN);
77e4bb11
 	    break;
8000d078
 	default:
 	    break;
77e4bb11
     }
2587dbab
 
     if(ret == CL_VIRUS)
 	ret = cli_checkfp(hash, hashed_size, ctx);
d91ab809
     ctx->recursion--;
f4e34215
     cli_bitset_free(ctx->hook_lsig_matches);
     ctx->hook_lsig_matches = old_hook_lsig_matches;
77e4bb11
 
d59d41b9
     switch(ret) {
087e7fc3
 	/* Malformed file cases */
d59d41b9
 	case CL_EFORMAT:
087e7fc3
 	case CL_EREAD:
 	case CL_EUNPACK:
 	/* Limits exceeded */
d59d41b9
 	case CL_EMAXREC:
 	case CL_EMAXSIZE:
 	case CL_EMAXFILES:
5611c67f
 	    cli_dbgmsg("Descriptor[%d]: %s\n", fmap_fd(*ctx->fmap), cl_strerror(ret));
087e7fc3
 	    ret_from_magicscan(CL_CLEAN);
54e6b31f
 	case CL_CLEAN:
60af015e
 	    cache_clean = 1;
aef8d4ac
 	    ret_from_magicscan(CL_CLEAN);
d59d41b9
 	default:
aef8d4ac
 	    ret_from_magicscan(ret);
322bfd03
     }
e3aaff8e
 }
 
1d1c4b15
 static int cli_base_scandesc(int desc, cli_ctx *ctx, cli_file_t type)
7770d314
 {
a2a004df
     STATBUF sb;
b7ae31f1
     int ret;
 
 #ifdef HAVE__INTERNAL__SHA_COLLECT
     if(ctx->sha_collect>0) ctx->sha_collect = 0;
 #endif
     cli_dbgmsg("in cli_magic_scandesc (reclevel: %u/%u)\n", ctx->recursion, ctx->engine->maxreclevel);
a2a004df
     if(FSTAT(desc, &sb) == -1) {
b7ae31f1
 	cli_errmsg("magic_scandesc: Can't fstat descriptor %d\n", desc);
60af015e
 	early_ret_from_magicscan(CL_ESTAT);
b7ae31f1
     }
     if(sb.st_size <= 5) {
 	cli_dbgmsg("Small data (%u bytes)\n", (unsigned int) sb.st_size);
60af015e
 	early_ret_from_magicscan(CL_CLEAN);
b7ae31f1
     }
 
     ctx->fmap++;
     perf_start(ctx, PERFT_MAP);
     if(!(*ctx->fmap = fmap(desc, 0, sb.st_size))) {
 	cli_errmsg("CRITICAL: fmap() failed\n");
 	ctx->fmap--;
 	perf_stop(ctx, PERFT_MAP);
60af015e
 	early_ret_from_magicscan(CL_EMEM);
b7ae31f1
     }
     perf_stop(ctx, PERFT_MAP);
 
1d1c4b15
     ret = magic_scandesc(ctx, type);
b7ae31f1
 
     funmap(*ctx->fmap);
     ctx->fmap--;
     return ret;
7770d314
 }
 
1d1c4b15
 int cli_magic_scandesc(int desc, cli_ctx *ctx)
 {
     return cli_base_scandesc(desc, ctx, CL_TYPE_ANY);
 }
 
 /* Have to keep partition typing separate */
 int cli_partition_scandesc(int desc, cli_ctx *ctx)
 {
     return cli_base_scandesc(desc, ctx, CL_TYPE_PART_ANY);
 }
 
b7ae31f1
 int cli_magic_scandesc_type(cli_ctx *ctx, cli_file_t type)
7770d314
 {
b7ae31f1
     return magic_scandesc(ctx, type);
7770d314
 }
 
edbba730
 int cl_scandesc(int desc, const char **virname, unsigned long int *scanned, const struct cl_engine *engine, unsigned int scanoptions)
 {
769f37a6
     return cl_scandesc_callback(desc, virname, scanned, engine, scanoptions, NULL);
edbba730
 }
 
87f76399
 /* length = 0, till the end */
 int cli_map_scandesc(cl_fmap_t *map, off_t offset, size_t length, cli_ctx *ctx)
c06374fe
 {
87f76399
     off_t old_off = map->nested_offset;
     size_t old_len = map->len;
c647912b
     size_t old_real_len = map->real_len;
1e2696b0
     int ret = CL_CLEAN;
c06374fe
 
0b3b2924
     cli_dbgmsg("cli_map_scandesc: [%ld, +%lu), [%ld, +%lu)\n",
 	       (long)old_off, (unsigned long)old_len,
 	       (long)offset, (unsigned long)length);
fefb3c36
     if (offset < 0 || offset >= old_len) {
87f76399
 	cli_dbgmsg("Invalid offset: %ld\n", (long)offset);
 	return CL_CLEAN;
     }
 
     if (!length) length = old_len - offset;
     if (length > old_len - offset) {
0b3b2924
 	cli_dbgmsg("Data truncated: %lu -> %lu\n",
 		   (unsigned long)length, old_len - offset);
87f76399
 	length = old_len - offset;
     }
 
     if (length <= 5) {
 	cli_dbgmsg("Small data (%u bytes)\n", (unsigned int) length);
c06374fe
 	return CL_CLEAN;
     }
     ctx->fmap++;
     *ctx->fmap = map;
87f76399
     /* can't change offset because then we'd have to discard/move cached
      * data, instead use another offset to reuse the already cached data */
     map->nested_offset += offset;
     map->len = length;
     map->real_len = map->nested_offset + length;
     if (CLI_ISCONTAINED(old_off, old_len, map->nested_offset, map->len)) {
 	ret = magic_scandesc(ctx, CL_TYPE_ANY);
     } else {
0b3b2924
 	long long len1, len2;
 	len1 = old_off + old_len;
         len2 = map->nested_offset + map->len;
 	cli_warnmsg("internal map error: %ld, %lld; %ld, %lld\n", old_off,
 		    len1, map->offset, len2);
87f76399
     }
c06374fe
 
81e57728
     ctx->fmap--;
87f76399
     map->nested_offset = old_off;
     map->len = old_len;
c647912b
     map->real_len = old_real_len;
c06374fe
     return ret;
 }
 
b3a8f998
 int cli_mem_scandesc(const void *buffer, size_t length, cli_ctx *ctx)
 {
     int ret;
     fmap_t *map = cl_fmap_open_memory(buffer, length);
     if (!map) {
 	return CL_EMAP;
     }
     ret = cli_map_scandesc(map, 0, length, ctx);
     cl_fmap_close(map);
     return ret;
 }
 
c06374fe
 static int scan_common(int desc, cl_fmap_t *map, const char **virname, unsigned long int *scanned, const struct cl_engine *engine, unsigned int scanoptions, void *context)
aa7380df
 {
     cli_ctx ctx;
     int rc;
 
     memset(&ctx, '\0', sizeof(cli_ctx));
     ctx.engine = engine;
     ctx.virname = virname;
     ctx.scanned = scanned;
     ctx.options = scanoptions;
6ad45a29
 #if 0 /* for development testing only */
     ctx.options |= CL_SCAN_ALLMATCHES;
 #endif
aa7380df
     ctx.found_possibly_unwanted = 0;
     ctx.container_type = CL_TYPE_ANY;
     ctx.container_size = 0;
     ctx.dconf = (struct cli_dconf *) engine->dconf;
     ctx.cb_ctx = context;
     ctx.fmap = cli_calloc(sizeof(fmap_t *), ctx.engine->maxreclevel + 2);
     if(!ctx.fmap)
 	return CL_EMEM;
     if (!(ctx.hook_lsig_matches = cli_bitset_init())) {
 	free(ctx.fmap);
 	return CL_EMEM;
     }
63feb6cd
     perf_init(&ctx);
aa7380df
 
 #ifdef HAVE__INTERNAL__SHA_COLLECT
     if(scanoptions & CL_SCAN_INTERNAL_COLLECT_SHA) {
 	char link[32];
 	ssize_t linksz;
 
6ad45a29
 
aa7380df
 	snprintf(link, sizeof(link), "/proc/self/fd/%u", desc);
 	link[sizeof(link)-1]='\0';
d1bfe559
 	if((linksz=readlink(link, ctx.entry_filename, sizeof(ctx.entry_filename)-1))==-1) {
aa7380df
 	    cli_errmsg("failed to resolve filename for descriptor %d (%s)\n", desc, link);
 	    strcpy(ctx.entry_filename, "NO_IDEA");
 	} else
 	    ctx.entry_filename[linksz]='\0';
     } while(0);
 #endif
 
769f37a6
     cli_logg_setup(&ctx);
87f76399
     rc = map ? cli_map_scandesc(map, 0, map->len, &ctx) : cli_magic_scandesc(desc, &ctx);
aa7380df
 
6ad45a29
     if (ctx.options & CL_SCAN_ALLMATCHES) {
 	*virname = (char *)ctx.virname; /* temp hack for scanall mode until api augmentation */
 	if (rc == CL_CLEAN && ctx.num_viruses)
 	    rc = CL_VIRUS;
     }
 
aa7380df
     cli_bitset_free(ctx.hook_lsig_matches);
     free(ctx.fmap);
     if(rc == CL_CLEAN && ctx.found_possibly_unwanted)
0d79b7dc
 	rc = CL_VIRUS;
4aa7baf1
     cli_logg_unsetup();
63feb6cd
     perf_done(&ctx);
aa7380df
     return rc;
 }
 
c06374fe
 int cl_scandesc_callback(int desc, const char **virname, unsigned long int *scanned, const struct cl_engine *engine, unsigned int scanoptions, void *context)
 {
     return scan_common(desc, NULL, virname, scanned, engine, scanoptions, context);
 }
 
 int cl_scanmap_callback(cl_fmap_t *map, const char **virname, unsigned long int *scanned, const struct cl_engine *engine, unsigned int scanoptions, void *context)
 {
     return scan_common(-1, map, virname, scanned, engine, scanoptions, context);
 }
 
7f0d1148
 int cli_found_possibly_unwanted(cli_ctx* ctx)
 {
6ad45a29
     if(cli_get_last_virus(ctx)) {
 	cli_dbgmsg("found Possibly Unwanted: %s\n", cli_get_last_virus(ctx));
 	if(ctx->options & CL_SCAN_HEURISTIC_PRECEDENCE) {
 	    /* we found a heuristic match, don't scan further,
 	     * but consider it a virus. */
 	    cli_dbgmsg("cli_found_possibly_unwanted: CL_VIRUS\n");
 	    return CL_VIRUS;
7f0d1148
 	}
6ad45a29
 	/* heuristic scan isn't taking precedence, keep scanning.
 	 * If this is part of an archive, and 
 	 * we find a real malware we report that instead of the 
 	 * heuristic match */
 	ctx->found_possibly_unwanted = 1;
     } else {
 	cli_warnmsg("cli_found_possibly_unwanted called, but virname is not set\n");
     }
     emax_reached(ctx);
     return CL_CLEAN;
7f0d1148
 }
 
3c91998b
 static int cli_scanfile(const char *filename, cli_ctx *ctx)
21cf4aeb
 {
 	int fd, ret;
 
22275b15
     /* internal version of cl_scanfile with arec/mrec preserved */
6e246c11
     if((fd = safe_open(filename, O_RDONLY|O_BINARY)) == -1)
21cf4aeb
 	return CL_EOPEN;
 
3c91998b
     ret = cli_magic_scandesc(fd, ctx);
21cf4aeb
 
     close(fd);
     return ret;
 }
 
2accc66f
 int cl_scanfile(const char *filename, const char **virname, unsigned long int *scanned, const struct cl_engine *engine, unsigned int scanoptions)
e3aaff8e
 {
769f37a6
     return cl_scanfile_callback(filename, virname, scanned, engine, scanoptions, NULL);
e3aaff8e
 }
72ce4b70
 
769f37a6
 int cl_scanfile_callback(const char *filename, const char **virname, unsigned long int *scanned, const struct cl_engine *engine, unsigned int scanoptions, void *context)
edbba730
 {
 	int fd, ret;
8f66206b
 	const char *fname = cli_to_utf8_maybe_alloc(filename);
edbba730
 
8ab47ebe
     if(!fname)
d564f5d5
 	    return CL_EARG;
8ab47ebe
 
     if((fd = safe_open(fname, O_RDONLY|O_BINARY)) == -1)
edbba730
 	return CL_EOPEN;
 
8ab47ebe
     if(fname != filename)
8f66206b
 	free((void*)fname);
8ab47ebe
 
769f37a6
     ret = cl_scandesc_callback(fd, virname, scanned, engine, scanoptions, context);
edbba730
     close(fd);
 
     return ret;
 }
 
72ce4b70
 /*
 Local Variables:
    c-basic-offset: 4
 End:
 */