static char const rcsid[] = "$Id: binhex.c,v 1.14 2005/03/10 08:51:30 nigelhorne Exp $";
#include "clamav.h"
#if HAVE_CONFIG_H
#include "clamav-config.h"
#endif
#ifndef CL_DEBUG
#define NDEBUG
#endif
#ifdef CL_THREAD_SAFE
#ifndef _REENTRANT
#define _REENTRANT
#endif
#endif
#if HAVE_MMAP
#if HAVE_SYS_MMAN_H
#include <sys/mman.h>
#else
#undef HAVE_MMAP
#endif
#endif
#include <stdio.h>
#include <memory.h>
#include <sys/stat.h>
#include "line.h"
#include "mbox.h"
#include "table.h"
#include "blob.h"
#include "text.h"
#include "binhex.h"
#include "others.h"
int
cli_binhex(const char *dir, int desc)
{
#ifndef HAVE_MMAP
cli_warnmsg("File not decoded - binhex decoding needs mmap() (for now)\n");
return CL_CLEAN;
#else
struct stat statb;
char *buf, *start, *line;
size_t size;
long bytesleft;
message *m;
fileblob *fb;
if(fstat(desc, &statb) < 0)
return CL_EOPEN;
size = (size_t)statb.st_size;
if(size == 0)
return CL_CLEAN;
m = messageCreate();
if(m == NULL)
return CL_EMEM;
start = buf = mmap(NULL, size, PROT_READ, MAP_SHARED, desc, 0);
if(buf == MAP_FAILED) {
messageDestroy(m);
return CL_EMEM;
}
cli_dbgmsg("mmap'ed binhex file\n");
bytesleft = (int)size;
line = NULL;
while(bytesleft > 0) {
int length = 0;
char *ptr;
for(ptr = buf; bytesleft && (*ptr != '\n') && (*ptr != '\r'); ptr++) {
length++;
--bytesleft;
}
line = cli_realloc(line, (size_t)(length + 1));
memcpy(line, buf, length);
line[length] = '\0';
if(messageAddStr(m, line) < 0)
break;
if((bytesleft > 0) && (*ptr == '\r')) {
ptr++;
bytesleft--;
}
buf = ++ptr;
bytesleft--;
}
munmap(start, size);
if(line)
free(line);
if(binhexBegin(m) == NULL) {
messageDestroy(m);
cli_errmsg("No binhex line found\n");
return CL_EFORMAT;
}
messageSetEncoding(m, "x-binhex");
fb = messageToFileblob(m, dir);
if(fb) {
cli_dbgmsg("Binhex file decoded to %s\n", fileblobGetFilename(fb));
fileblobDestroy(fb);
} else
cli_errmsg("Couldn't decode binhex file to %s\n", dir);
messageDestroy(m);
if(fb)
return CL_CLEAN;
return CL_EOPEN;
#endif
}