コード例 #1
0
ファイル: clamavengine.cpp プロジェクト: amd00/meduzzza
	qint32 ClamavEngine::dbAge() const
	{
		QDir db_dir(m_p -> dbPath());
		QStringList files = db_dir.entryList(QStringList() << "*.cvd" << "*.cld", QDir::Files | QDir::Hidden | QDir::NoSymLinks);
		QDateTime res, tmp;
		foreach(QString file, files)
		{
			cl_cvd *cvd = cl_cvdhead(db_dir.absoluteFilePath(file).toLocal8Bit().data());
			if(!cvd)
				continue;
			tmp.setTime_t(cvd -> stime);
			cl_cvdfree(cvd);
			if(res.isNull() || tmp > res)
				res = tmp;
		}
コード例 #2
0
ファイル: virusscan.cpp プロジェクト: gfoudree/usbninja
cl_cvd VirusScan::getCVDInfo(char *file)
{
    cl_cvd ret;
    struct cl_cvd *cc;
    cc = cl_cvdhead(file);

    ret.builder = cc->builder;
    ret.dsig = cc->dsig;
    ret.fl = cc->fl;
    ret.md5 = cc->md5;
    ret.sigs = cc->sigs;
    ret.stime = cc->stime;
    ret.time = cc->time;
    ret.version = cc->version;

    cl_cvdfree(cc);
    return ret;
}
コード例 #3
0
ファイル: manager.c プロジェクト: OPSF/uClinux
static struct cl_cvd *currentdb(const char *dbname, char *localname)
{
	char db[32];
	struct cl_cvd *cvd = NULL;


    snprintf(db, sizeof(db), "%s.cvd", dbname);
    if(localname)
	strcpy(localname, db);

    if(access(db, R_OK) == -1) {
	snprintf(db, sizeof(db), "%s.cld", dbname);
	if(localname)
	    strcpy(localname, db);
    }

    if(!access(db, R_OK))
	cvd = cl_cvdhead(db);

    return cvd;
}
コード例 #4
0
int command(int desc, const struct cl_node *root, const struct cl_limits *limits, int options, const struct cfgstruct *copt, int timeout)
{
	char buff[1025];
	int bread, opt, retval;
	struct cfgstruct *cpt;


    retval = poll_fd(desc, timeout);
    switch (retval) {
    case 0: /* timeout */
	return -2;
    case -1:
	mdprintf(desc, "ERROR\n");
	logg("!Command: poll_fd failed.\n");
	return -1;
    }

    while((bread = readsock(desc, buff, 1024)) == -1 && errno == EINTR);

    if(bread == 0) {
	/* Connection closed */
	return -1;
    }

    if(bread < 0) {
	logg("!Command parser: read() failed.\n");
	/* at least try to display this error message */
	/* mdprintf(desc, "ERROR: Command parser: read() failed.\n"); */
	return -1;
    }

    buff[bread] = 0;
    cli_chomp(buff);

    if(!strncmp(buff, CMD1, strlen(CMD1))) { /* SCAN */
	if(scan(buff + strlen(CMD1) + 1, NULL, root, limits, options, copt, desc, 0) == -2)
	    if(cfgopt(copt, "ExitOnOOM"))
		return COMMAND_SHUTDOWN;

    } else if(!strncmp(buff, CMD2, strlen(CMD2))) { /* RAWSCAN */
	opt = options & ~CL_SCAN_ARCHIVE;
	if(scan(buff + strlen(CMD2) + 1, NULL, root, NULL, opt, copt, desc, 0) == -2)
	    if(cfgopt(copt, "ExitOnOOM"))
		return COMMAND_SHUTDOWN;

    } else if(!strncmp(buff, CMD3, strlen(CMD3))) { /* QUIT */
	return COMMAND_SHUTDOWN;

    } else if(!strncmp(buff, CMD4, strlen(CMD4))) { /* RELOAD */
	mdprintf(desc, "RELOADING\n");
	return COMMAND_RELOAD;

    } else if(!strncmp(buff, CMD5, strlen(CMD5))) { /* PING */
	mdprintf(desc, "PONG\n");

    } else if(!strncmp(buff, CMD6, strlen(CMD6))) { /* CONTSCAN */
	if(scan(buff + strlen(CMD6) + 1, NULL, root, limits, options, copt, desc, 1) == -2)
	    if(cfgopt(copt, "ExitOnOOM"))
		return COMMAND_SHUTDOWN;

    } else if(!strncmp(buff, CMD7, strlen(CMD7))) { /* VERSION */
	    const char *dbdir;
	    char *path;
	    struct cl_cvd *daily;

	if((cpt = cfgopt(copt, "DatabaseDirectory")) || (cpt = cfgopt(copt, "DataDirectory")))
	    dbdir = cpt->strarg;
	else
	    dbdir = cl_retdbdir();

	if(!(path = mmalloc(strlen(dbdir) + 11))) {
	    mdprintf(desc, "Memory allocation error - SHUTDOWN forced\n");
	    return COMMAND_SHUTDOWN;
	}

	sprintf(path, "%s/daily.cvd", dbdir);

	if((daily = cl_cvdhead(path))) {
		time_t t = (time_t) daily->stime;

	    pthread_mutex_lock(&ctime_mutex);
	    mdprintf(desc, "ClamAV "VERSION"/%d/%s", daily->version, ctime(&t));
	    pthread_mutex_unlock(&ctime_mutex);
	    cl_cvdfree(daily);
	} else {
	    mdprintf(desc, "ClamAV "VERSION"\n");
	}

	free(path);

    } else if(!strncmp(buff, CMD8, strlen(CMD8))) { /* STREAM */
	if(scanstream(desc, NULL, root, limits, options, copt) == CL_EMEM)
	    if(cfgopt(copt, "ExitOnOOM"))
		return COMMAND_SHUTDOWN;

    } else if(!strncmp(buff, CMD9, strlen(CMD9))) { /* SESSION */
	return COMMAND_SESSION;

    } else if(!strncmp(buff, CMD10, strlen(CMD10))) { /* END */
	return COMMAND_END;

    } else if(!strncmp(buff, CMD11, strlen(CMD11))) { /* SHUTDOWN */
	return COMMAND_SHUTDOWN;

    } else if(!strncmp(buff, CMD12, strlen(CMD12))) { /* FD */
	    int fd = atoi(buff + strlen(CMD12) + 1);

	scanfd(fd, NULL, root, limits, options, copt, desc, 0);
	close(fd); /* FIXME: should we close it here? */

    } else {
	mdprintf(desc, "UNKNOWN COMMAND\n");
    }

    return 0; /* no error and no 'special' command executed */
}
コード例 #5
0
ファイル: srv_clamav.c プロジェクト: p1rate5s/c-icap
int init_virusdb()
{
     int ret;
     unsigned int no = 0;
     virusdb = malloc(sizeof(struct virus_db));
     memset(virusdb, 0, sizeof(struct virus_db));
     if (!virusdb)
          return 0;
#ifdef HAVE_LIBCLAMAV_095
     if((ret = cl_init(CL_INIT_DEFAULT))) {
        ci_debug_printf(1, "!Can't initialize libclamav: %s\n", cl_strerror(ret));
        return 0;
    }

     if(!(virusdb->db = cl_engine_new())) {
	 ci_debug_printf(1, "Clamav DB load: Cannot create new clamav engine\n");
	 return 0;
     }

     if ((ret = cl_load(cl_retdbdir(), virusdb->db, &no, CL_DB_STDOPT))) {
          ci_debug_printf(1, "Clamav DB load: cl_load failed: %s\n",
                          cl_strerror(ret));
#elif defined(HAVE_LIBCLAMAV_09X)
     if ((ret = cl_load(cl_retdbdir(), &(virusdb->db), &no, CL_DB_STDOPT))) {
          ci_debug_printf(1, "Clamav DB load: cl_load failed: %s\n",
                          cl_strerror(ret));
#else
     if ((ret = cl_loaddbdir(cl_retdbdir(), &(virusdb->db), &no))) {
          ci_debug_printf(1, "cl_loaddbdir: %s\n", cl_perror(ret));
#endif
          return 0;
     }
#ifdef HAVE_LIBCLAMAV_095
     if ((ret = cl_engine_compile(virusdb->db))) {
#else
     if ((ret = cl_build(virusdb->db))) {
#endif
          ci_debug_printf(1, "Database initialization error: %s\n",
                          cl_strerror(ret));
#ifdef HAVE_LIBCLAMAV_095
	  cl_engine_free(virusdb->db);
#else
          cl_free(virusdb->db);
#endif
          free(virusdb);
          virusdb = NULL;
          return 0;
     }
     ci_thread_mutex_init(&db_mutex);
     virusdb->refcount = 1;
     old_virusdb = NULL;
     return 1;
}

/*
  Instead of using struct virus_db and refcount's someone can use the cl_dup function
  of clamav library, but it is  undocumented so I did not use it.
  The following implementation we are starting to reload clamav db while threads are 
  scanning for virus but we are not allow any child to start a new scan until we are 
  loading DB.
*/
/*#define DB_NO_FULL_LOCK 1*/
#undef DB_NO_FULL_LOCK
int reload_virusdb()
{
     struct virus_db *vdb = NULL;
     int ret;
     unsigned int no = 0;
     ci_thread_mutex_lock(&db_mutex);
     if (old_virusdb) {
          ci_debug_printf(1, "Clamav DB reload pending, cancelling.\n");
          ci_thread_mutex_unlock(&db_mutex);
          return 0;
     }
#ifdef DB_NO_FULL_LOCK
     ci_thread_mutex_unlock(&db_mutex);
#endif
     vdb = malloc(sizeof(struct virus_db));
     if (!vdb)
          return 0;
     memset(vdb, 0, sizeof(struct virus_db));
     ci_debug_printf(9, "db_reload going to load db\n");
#ifdef HAVE_LIBCLAMAV_095
     if(!(vdb->db = cl_engine_new())) {
	 ci_debug_printf(1, "Clamav DB load: Cannot create new clamav engine\n");
	 return 0;
     }
     if ((ret = cl_load(cl_retdbdir(), vdb->db, &no, CL_DB_STDOPT))) {
          ci_debug_printf(1, "Clamav DB reload: cl_load failed: %s\n",
                          cl_strerror(ret));
#elif defined(HAVE_LIBCLAMAV_09X)
     if ((ret = cl_load(cl_retdbdir(), &(vdb->db), &no, CL_DB_STDOPT))) {
          ci_debug_printf(1, "Clamav DB reload: cl_load failed: %s\n",
                          cl_strerror(ret));
#else
     if ((ret = cl_loaddbdir(cl_retdbdir(), &(vdb->db), &no))) {
          ci_debug_printf(1, "Clamav DB reload: cl_loaddbdir failed: %s\n",
                          cl_perror(ret));
#endif
          return 0;
     }
     ci_debug_printf(9, "loaded. Going to build\n");
#ifdef HAVE_LIBCLAMAV_095
     if ((ret = cl_engine_compile(vdb->db))) {
#else
     if ((ret = cl_build(vdb->db))) {
#endif
          ci_debug_printf(1,
                          "Clamav DB reload: Database initialization error: %s\n",
                          cl_strerror(ret));
#ifdef HAVE_LIBCLAMAV_095
	  cl_engine_free(vdb->db);
#else
          cl_free(vdb->db);
#endif
          free(vdb);
          vdb = NULL;
#ifdef DB_NO_FULL_LOCK
          /*no lock needed */
#else
          ci_thread_mutex_unlock(&db_mutex);
#endif
          return 0;
     }
     ci_debug_printf(9, "Done releasing.....\n");
#ifdef DB_NO_FULL_LOCK
     ci_thread_mutex_lock(&db_mutex);
#endif
     old_virusdb = virusdb;
     old_virusdb->refcount--;
     ci_debug_printf(9, "Old VirusDB refcount:%d\n", old_virusdb->refcount);
     if (old_virusdb->refcount <= 0) {
#ifdef HAVE_LIBCLAMAV_095
	  cl_engine_free(old_virusdb->db);
#else
          cl_free(old_virusdb->db);
#endif
          free(old_virusdb);
          old_virusdb = NULL;
     }
     virusdb = vdb;
     virusdb->refcount = 1;
     ci_thread_mutex_unlock(&db_mutex);
     return 1;
}

CL_ENGINE *get_virusdb()
{
     struct virus_db *vdb;
     ci_thread_mutex_lock(&db_mutex);
     vdb = virusdb;
     vdb->refcount++;
     ci_thread_mutex_unlock(&db_mutex);
     return vdb->db;
}

void release_virusdb(CL_ENGINE * db)
{
     ci_thread_mutex_lock(&db_mutex);
     if (virusdb && db == virusdb->db)
          virusdb->refcount--;
     else if (old_virusdb && (db == old_virusdb->db)) {
          old_virusdb->refcount--;
          ci_debug_printf(9, "Old VirusDB refcount: %d\n",
                          old_virusdb->refcount);
          if (old_virusdb->refcount <= 0) {
#ifdef HAVE_LIBCLAMAV_095
	      cl_engine_free(old_virusdb->db);
#else
               cl_free(old_virusdb->db);
#endif
               free(old_virusdb);
               old_virusdb = NULL;
          }
     }
     else {
          ci_debug_printf(1,
                          "BUG in srv_clamav service! please contact the author\n");
     }
     ci_thread_mutex_unlock(&db_mutex);
}

void destroy_virusdb()
{
     if (virusdb) {
#ifdef HAVE_LIBCLAMAV_095
	  cl_engine_free(virusdb->db);
#else
          cl_free(virusdb->db);
#endif
          free(virusdb);
          virusdb = NULL;
     }
     if (old_virusdb) {
#ifdef HAVE_LIBCLAMAV_095
	  cl_engine_free(old_virusdb->db);
#else
          cl_free(old_virusdb->db);
#endif
          free(old_virusdb);
          old_virusdb = NULL;
     }
}

void set_istag(ci_service_xdata_t * srv_xdata)
{
     char istag[SERVICE_ISTAG_SIZE + 1];
     char str_version[64];
     char *daily_path;
     char *s1, *s2;
     struct cl_cvd *d1;
     int version = 0, cfg_version = 0;
     struct stat daily_stat;

     /*instead of 128 should be strlen("/daily.inc/daily.info")+1*/
     daily_path = malloc(strlen(cl_retdbdir()) + 128);
     if (!daily_path)           /*???????? */
          return;
     sprintf(daily_path, "%s/daily.cvd", cl_retdbdir());
     
     if(stat(daily_path,&daily_stat) != 0){
	 /* if the clamav_lib_path/daily.cvd does not exists
	  */
	 sprintf(daily_path, "%s/daily.cld", cl_retdbdir());
     
	 if(stat(daily_path,&daily_stat) != 0){
	     /*
	       else try to use the clamav_lib_path/daily.inc/daly.info file instead" */
	     sprintf(daily_path, "%s/daily.inc/daily.info", cl_retdbdir());
	 }
     }

     if ((d1 = cl_cvdhead(daily_path))) {
          version = d1->version;
          free(d1);
     }
     free(daily_path);

     s1 = (char *) cl_retver();
     s2 = str_version;
     while (*s1 != '\0' && s2 - str_version < 64) {
          if (*s1 != '.') {
               *s2 = *s1;
               s2++;
          }
          s1++;
     }
     *s2 = '\0';
     /*cfg_version maybe must set by user when he is changing 
        the srv_clamav configuration.... */
     snprintf(istag, SERVICE_ISTAG_SIZE, "-%.3d-%s-%d%d",
              cfg_version, str_version, cl_retflevel(), version);
     istag[SERVICE_ISTAG_SIZE] = '\0';
     ci_service_set_istag(srv_xdata, istag);
}
コード例 #6
0
ファイル: manager.c プロジェクト: OPSF/uClinux
/*
 * TODO:
 * - strptime() is most likely not portable enough
 */
int submitstats(const char *clamdcfg, const struct optstruct *opts)
{
	int fd, sd, bread, lread = 0, cnt, ret;
	char post[SUBMIT_MIN_ENTRIES * 256 + 512];
	char query[SUBMIT_MIN_ENTRIES * 256];
	char buff[512], statsdat[512], newstatsdat[512], uastr[128];
	char logfile[256], fbuff[FILEBUFF];
	char *pt, *pt2, *auth = NULL;
	const char *line, *country = NULL, *user, *proxy = NULL;
	struct optstruct *clamdopt;
	const struct optstruct *opt;
	struct stat sb;
	struct tm tms;
	time_t epoch;
	unsigned int qcnt, entries, submitted = 0, permfail = 0, port = 0;


    if((opt = optget(opts, "DetectionStatsCountry"))->enabled) {
	if(strlen(opt->strarg) != 2 || !isalpha(opt->strarg[0]) || !isalpha(opt->strarg[1])) {
	    logg("!SubmitDetectionStats: DetectionStatsCountry requires a two-letter country code\n");
	    return 56;
	}
	country = opt->strarg;
    }

    if(!(clamdopt = optparse(clamdcfg, 0, NULL, 1, OPT_CLAMD, 0, NULL))) {
	logg("!SubmitDetectionStats: Can't open or parse configuration file %s\n", clamdcfg);
	return 56;
    }

    if(!(opt = optget(clamdopt, "LogFile"))->enabled) {
	logg("!SubmitDetectionStats: LogFile needs to be enabled in %s\n", clamdcfg);
	optfree(clamdopt);
	return 56;
    }
    strncpy(logfile, opt->strarg, sizeof(logfile));
    logfile[sizeof(logfile) - 1] = 0;

    if(!optget(clamdopt, "LogTime")->enabled) {
	logg("!SubmitDetectionStats: LogTime needs to be enabled in %s\n", clamdcfg);
	optfree(clamdopt);
	return 56;
    }
    optfree(clamdopt);

    if((fd = open("stats.dat", O_RDONLY)) != -1) {
	if((bread = read(fd, statsdat, sizeof(statsdat) - 1)) == -1) {
	    logg("^SubmitDetectionStats: Can't read stats.dat\n");
	    bread = 0;
	}
	statsdat[bread] = 0;
	close(fd);
    } else {
	*statsdat = 0;
    }

    if((fd = open(logfile, O_RDONLY)) == -1) {
	logg("!SubmitDetectionStats: Can't open %s for reading\n", logfile);
	return 56;
    }

    if(fstat(fd, &sb) == -1) {
	logg("!SubmitDetectionStats: fstat() failed\n");
	close(fd);
	return 56;
    }

    while((line = readbline(fd, fbuff, FILEBUFF, sb.st_size, &lread)))
	if(strlen(line) >= 32 && !strcmp(&line[strlen(line) - 6], " FOUND"))
	    break;

    if(!line) {
	logg("SubmitDetectionStats: No detection records found\n");
	close(fd);
	return 1;
    }

    if(*statsdat && !strcmp(line, statsdat)) {
	logg("SubmitDetectionStats: No new detection records found\n");
	close(fd);
	return 1;
    } else {
	strncpy(newstatsdat, line, sizeof(newstatsdat));
    }

    if((opt = optget(opts, "HTTPUserAgent"))->enabled)
	strncpy(uastr, opt->strarg, sizeof(uastr));
    else
	snprintf(uastr, sizeof(uastr), PACKAGE"/%s (OS: "TARGET_OS_TYPE", ARCH: "TARGET_ARCH_TYPE", CPU: "TARGET_CPU_TYPE")%s%s", get_version(), country ? ":" : "", country ? country : "");
    uastr[sizeof(uastr) - 1] = 0;

    if((opt = optget(opts, "HTTPProxyServer"))->enabled) {
	proxy = opt->strarg;
	if(!strncasecmp(proxy, "http://", 7))
	    proxy += 7;

	if((opt = optget(opts, "HTTPProxyUsername"))->enabled) {
	    user = opt->strarg;
	    if(!(opt = optget(opts, "HTTPProxyPassword"))->enabled) {
		logg("!SubmitDetectionStats: HTTPProxyUsername requires HTTPProxyPassword\n");
		close(fd);
		return 56;
	    }
	    auth = proxyauth(user, opt->strarg);
	    if(!auth) {
		close(fd);
		return 56;
	    }
	}

	if((opt = optget(opts, "HTTPProxyPort"))->enabled)
	    port = opt->numarg;

	logg("*Connecting via %s\n", proxy);
    }

    ret = 0;
    memset(query, 0, sizeof(query));
    qcnt = 0;
    entries = 0;
    do {
	if(strlen(line) < 32 || strcmp(&line[strlen(line) - 6], " FOUND"))
	    continue;

	if(*statsdat && !strcmp(line, statsdat))
	    break;

	strncpy(buff, line, sizeof(buff));
	buff[sizeof(buff) - 1] = 0;

	if(!(pt = strstr(buff, " -> "))) {
	    logg("*SubmitDetectionStats: Skipping detection entry logged without time\b");
	    continue;
	}
	*pt = 0;
	pt += 4;

	if(!strptime(buff, "%a %b  %d %H:%M:%S %Y", &tms) || (epoch = mktime(&tms)) == -1) {
	    logg("!SubmitDetectionStats: Failed to convert date string\n");
	    ret = 1;
	    break;
	}

	pt2 = &pt[strlen(pt) - 6];
	*pt2 = 0;

	if(!(pt2 = strrchr(pt, ':'))) {
	    logg("!SubmitDetectionStats: Incorrect format of the log file (1)\n");
	    ret = 1;
	    break;
	}
	*pt2 = 0;
	pt2 += 2;

#ifdef C_WINDOWS
	if((pt = strrchr(pt, '\\')))
#else
	if((pt = strrchr(pt, '/')))
#endif
	    *pt++ = 0;
	if(!pt)
	    pt = (char*) "NOFNAME";

	qcnt += snprintf(&query[qcnt], sizeof(query) - qcnt, "ts[]=%u&fname[]=%s&virus[]=%s&", (unsigned int) epoch, pt, pt2);
	entries++;

	if(entries == SUBMIT_MIN_ENTRIES) {
	    sd = wwwconnect("stats.clamav.net", proxy, port, NULL, optget(opts, "LocalIPAddress")->strarg, optget(opts, "ConnectTimeout")->numarg, NULL, 0, 0);
	    if(sd == -1) {
		logg("!SubmitDetectionStats: Can't connect to server\n");
		ret = 52;
		break;
	    }

	    query[sizeof(query) - 1] = 0;
	    snprintf(post, sizeof(post),
		"POST http://stats.clamav.net/submit.php HTTP/1.0\r\n"
		"Host: stats.clamav.net\r\n%s"
		"Content-Type: application/x-www-form-urlencoded\r\n"
		"User-Agent: %s\r\n"
		"Content-Length: %u\r\n\n"
		"%s",
	    auth ? auth : "", uastr, (unsigned int) strlen(query), query);

	    if(send(sd, post, strlen(post), 0) < 0) {
		logg("!SubmitDetectionStats: Can't write to socket\n");
		ret = 52;
		closesocket(sd);
		break;
	    }

	    pt = post;
	    cnt = sizeof(post) - 1;
#ifdef SO_ERROR
	    while((bread = wait_recv(sd, pt, cnt, 0, optget(opts, "ReceiveTimeout")->numarg)) > 0) {
#else
	    while((bread = recv(sd, pt, cnt, 0)) > 0) {
#endif
		pt += bread;
		cnt -= bread;
		if(cnt <= 0)
		    break;
	    }
	    *pt = 0;
	    closesocket(sd);

	    if(bread < 0) {
		logg("!SubmitDetectionStats: Can't read from socket\n");
		ret = 52;
		break;
	    }

	    if(strstr(post, "SUBMIT_OK")) {
		submitted += entries;
		if(submitted + SUBMIT_MIN_ENTRIES > SUBMIT_MAX_ENTRIES)
		    break;
		qcnt = 0;
		entries = 0;
		memset(query, 0, sizeof(query));
		continue;
	    }

	    ret = 52;
	    if((pt = strstr(post, "SUBMIT_PERMANENT_FAILURE"))) {
		if(!submitted) {
		    permfail = 1;
		    if((pt + 32 <= post + sizeof(post)) && pt[24] == ':')
			logg("!SubmitDetectionStats: Remote server reported permanent failure: %s\n", &pt[25]);
		    else
			logg("!SubmitDetectionStats: Remote server reported permanent failure\n");
		}
	    } else if((pt = strstr(post, "SUBMIT_TEMPORARY_FAILURE"))) {
		if(!submitted) {
		    if((pt + 32 <= post + sizeof(post)) && pt[24] == ':')
			logg("!SubmitDetectionStats: Remote server reported temporary failure: %s\n", &pt[25]);
		    else
			logg("!SubmitDetectionStats: Remote server reported temporary failure\n");
		}
	    } else {
		if(!submitted)
		    logg("!SubmitDetectionStats: Incorrect answer from server\n");
	    }

	    break;
	}

    } while((line = readbline(fd, fbuff, FILEBUFF, sb.st_size, &lread)));

    close(fd);
    if(auth)
	free(auth);

    if(submitted || permfail) {
	if((fd = open("stats.dat", O_WRONLY | O_CREAT | O_TRUNC, 0600)) == -1) {
	    logg("^SubmitDetectionStats: Can't open stats.dat for writing\n");
	} else {
	    if((bread = write(fd, newstatsdat, sizeof(newstatsdat))) != sizeof(newstatsdat))
		logg("^SubmitDetectionStats: Can't write to stats.dat\n");
	    close(fd);
	}
    }

    if(ret == 0) {
	if(!submitted)
	    logg("SubmitDetectionStats: Not enough recent data for submission\n");
	else
	    logg("SubmitDetectionStats: Submitted %u records\n", submitted);
    }

    return ret;
}

static int Rfc2822DateTime(char *buf, time_t mtime)
{
	struct tm *gmt;

    gmt = gmtime(&mtime);
    return strftime(buf, 36, "%a, %d %b %Y %X GMT", gmt);
}

static struct cl_cvd *remote_cvdhead(const char *cvdfile, const char *localfile, const char *hostname, char *ip, const char *localip, const char *proxy, int port, const char *user, const char *pass, const char *uas, int *ims, int ctimeout, int rtimeout, struct mirdat *mdat, int logerr, unsigned int can_whitelist)
{
	char cmd[512], head[513], buffer[FILEBUFF], ipaddr[46], *ch, *tmp;
	int bread, cnt, sd;
	unsigned int i, j;
	char *remotename = NULL, *authorization = NULL;
	struct cl_cvd *cvd;
	char last_modified[36], uastr[128];


    if(proxy) {
        remotename = malloc(strlen(hostname) + 8);
	if(!remotename) {
	    logg("!remote_cvdhead: Can't allocate memory for 'remotename'\n");
	    return NULL;
	}
        sprintf(remotename, "http://%s", hostname);

	if(user) {
	    authorization = proxyauth(user, pass);
	    if(!authorization) {
		free(remotename);
		return NULL;
	    }
	}
    }

    if(!access(localfile, R_OK)) {
	cvd = cl_cvdhead(localfile);
	if(!cvd) {
	    logg("!remote_cvdhead: Can't parse file %s\n", localfile);
	    free(remotename);
	    free(authorization);
	    return NULL;
	}
	Rfc2822DateTime(last_modified, (time_t) cvd->stime);
	cl_cvdfree(cvd);
    } else {
	    time_t mtime = 1104119530;

	Rfc2822DateTime(last_modified, mtime);
	logg("*Assuming modification time in the past\n");
    }

    logg("*If-Modified-Since: %s\n", last_modified);

    logg("Reading CVD header (%s): ", cvdfile);

    if(uas)
	strncpy(uastr, uas, sizeof(uastr));
    else
	snprintf(uastr, sizeof(uastr), PACKAGE"/%s (OS: "TARGET_OS_TYPE", ARCH: "TARGET_ARCH_TYPE", CPU: "TARGET_CPU_TYPE")", get_version());
    uastr[sizeof(uastr) - 1] = 0;

    snprintf(cmd, sizeof(cmd),
	"GET %s/%s HTTP/1.0\r\n"
	"Host: %s\r\n%s"
	"User-Agent: %s\r\n"
	"Connection: close\r\n"
	"Range: bytes=0-511\r\n"
        "If-Modified-Since: %s\r\n"
        "\r\n", (remotename != NULL) ? remotename : "", cvdfile, hostname, (authorization != NULL) ? authorization : "", uastr, last_modified);

    free(remotename);
    free(authorization);

    memset(ipaddr, 0, sizeof(ipaddr));

    if(ip[0]) /* use ip to connect */
	sd = wwwconnect(ip, proxy, port, ipaddr, localip, ctimeout, mdat, logerr, can_whitelist);
    else
	sd = wwwconnect(hostname, proxy, port, ipaddr, localip, ctimeout, mdat, logerr, can_whitelist);

    if(sd < 0) {
	return NULL;
    } else {
	logg("*Connected to %s (IP: %s).\n", hostname, ipaddr);
	logg("*Trying to retrieve CVD header of http://%s/%s\n", hostname, cvdfile);
    }

    if(!ip[0])
	strcpy(ip, ipaddr);

    if(send(sd, cmd, strlen(cmd), 0) < 0) {
	logg("%cremote_cvdhead: write failed\n", logerr ? '!' : '^');
	closesocket(sd);
	return NULL;
    }

    tmp = buffer;
    cnt = FILEBUFF;
#ifdef SO_ERROR
    while((bread = wait_recv(sd, tmp, cnt, 0, rtimeout)) > 0) {
#else
    while((bread = recv(sd, tmp, cnt, 0)) > 0) {
#endif
	tmp += bread;
	cnt -= bread;
	if(cnt <= 0)
	    break;
    }
    closesocket(sd);

    if(bread == -1) {
	logg("%cremote_cvdhead: Error while reading CVD header from %s\n", logerr ? '!' : '^', hostname);
	mirman_update(mdat->currip, mdat->af, mdat, 1);
	return NULL;
    }

    if((strstr(buffer, "HTTP/1.1 404")) != NULL || (strstr(buffer, "HTTP/1.0 404")) != NULL) { 
	logg("%cCVD file not found on remote server\n", logerr ? '!' : '^');
	mirman_update(mdat->currip, mdat->af, mdat, 2);
	return NULL;
    }

    /* check whether the resource is up-to-date */
    if((strstr(buffer, "HTTP/1.1 304")) != NULL || (strstr(buffer, "HTTP/1.0 304")) != NULL) { 
	*ims = 0;
	logg("OK (IMS)\n");
	mirman_update(mdat->currip, mdat->af, mdat, 0);
	return NULL;
    } else {
	*ims = 1;
    }

    if(!strstr(buffer, "HTTP/1.1 200") && !strstr(buffer, "HTTP/1.0 200") &&
       !strstr(buffer, "HTTP/1.1 206") && !strstr(buffer, "HTTP/1.0 206")) {
	logg("%cUnknown response from remote server\n", logerr ? '!' : '^');
	mirman_update(mdat->currip, mdat->af, mdat, 1);
	return NULL;
    }

    i = 3;
    ch = buffer + i;
    while(i < sizeof(buffer)) {
	if (*ch == '\n' && *(ch - 1) == '\r' && *(ch - 2) == '\n' && *(ch - 3) == '\r') {
	    ch++;
	    i++;
	    break;
	}
	ch++;
	i++;
    }

    if(sizeof(buffer) - i < 512) {
	logg("%cremote_cvdhead: Malformed CVD header (too short)\n", logerr ? '!' : '^');
	mirman_update(mdat->currip, mdat->af, mdat, 1);
	return NULL;
    }

    memset(head, 0, sizeof(head));

    for(j = 0; j < 512; j++) {
	if(!ch || (ch && !*ch) || (ch && !isprint(ch[j]))) {
	    logg("%cremote_cvdhead: Malformed CVD header (bad chars)\n", logerr ? '!' : '^');
	    mirman_update(mdat->currip, mdat->af, mdat, 1);
	    return NULL;
	}
	head[j] = ch[j];
    }

    if(!(cvd = cl_cvdparse(head))) {
	logg("%cremote_cvdhead: Malformed CVD header (can't parse)\n", logerr ? '!' : '^');
	mirman_update(mdat->currip, mdat->af, mdat, 1);
    } else {
	logg("OK\n");
	mirman_update(mdat->currip, mdat->af, mdat, 0);
    }

    return cvd;
}

static int getfile(const char *srcfile, const char *destfile, const char *hostname, char *ip, const char *localip, const char *proxy, int port, const char *user, const char *pass, const char *uas, int ctimeout, int rtimeout, struct mirdat *mdat, int logerr, unsigned int can_whitelist)
{
	char cmd[512], uastr[128], buffer[FILEBUFF], *ch;
	int bread, fd, totalsize = 0,  rot = 0, totaldownloaded = 0,
	    percentage = 0, sd;
	unsigned int i;
	char *remotename = NULL, *authorization = NULL, *headerline, ipaddr[46];
	const char *rotation = "|/-\\";
#ifdef FILTER_RULES
	pid_t pid = -1;
#endif


    if(proxy) {
        remotename = malloc(strlen(hostname) + 8);
	if(!remotename) {
	    logg("!getfile: Can't allocate memory for 'remotename'\n");
	    return 75; /* FIXME */
	}
        sprintf(remotename, "http://%s", hostname);

	if(user) {
	    authorization = proxyauth(user, pass);
	    if(!authorization) {
		free(remotename);
		return 75; /* FIXME */
	    }
	}
    }

    if(uas)
	strncpy(uastr, uas, sizeof(uastr));
    else
	snprintf(uastr, sizeof(uastr), PACKAGE"/%s (OS: "TARGET_OS_TYPE", ARCH: "TARGET_ARCH_TYPE", CPU: "TARGET_CPU_TYPE")", get_version());
    uastr[sizeof(uastr) - 1] = 0;

    snprintf(cmd, sizeof(cmd),
	"GET %s/%s HTTP/1.0\r\n"
	"Host: %s\r\n%s"
	"User-Agent: %s\r\n"
#ifdef FRESHCLAM_NO_CACHE
	"Cache-Control: no-cache\r\n"
#endif
	"Connection: close\r\n"
	"\r\n", (remotename != NULL) ? remotename : "", srcfile, hostname, (authorization != NULL) ? authorization : "", uastr);

    if(remotename)
	free(remotename);

    if(authorization)
	free(authorization);

    memset(ipaddr, 0, sizeof(ipaddr));
    if(ip[0]) /* use ip to connect */
	sd = wwwconnect(ip, proxy, port, ipaddr, localip, ctimeout, mdat, logerr, can_whitelist);
    else
	sd = wwwconnect(hostname, proxy, port, ipaddr, localip, ctimeout, mdat, logerr, can_whitelist);

    if(sd < 0) {
	return 52;
    } else {
	logg("*Trying to download http://%s/%s (IP: %s)\n", hostname, srcfile, ipaddr);
    }

    if(!ip[0])
	strcpy(ip, ipaddr);

    if(send(sd, cmd, strlen(cmd), 0) < 0) {
	logg("%cgetfile: Can't write to socket\n", logerr ? '!' : '^');
	closesocket(sd);
	return 52;
    }

    /* read http headers */
    ch = buffer;
    i = 0;
    while(1) {
	/* recv one byte at a time, until we reach \r\n\r\n */
#ifdef SO_ERROR
	if((i >= sizeof(buffer) - 1) || wait_recv(sd, buffer + i, 1, 0, rtimeout) == -1) {
#else
	if((i >= sizeof(buffer) - 1) || recv(sd, buffer + i, 1, 0) == -1) {
#endif
	    logg("%cgetfile: Error while reading database from %s (IP: %s)\n", logerr ? '!' : '^', hostname, ipaddr);
	    mirman_update(mdat->currip, mdat->af, mdat, 1);
	    closesocket(sd);
	    return 52;
	}

	if(i > 2 && *ch == '\n' && *(ch - 1) == '\r' && *(ch - 2) == '\n' && *(ch - 3) == '\r') {
	    i++;
	    break;
	}
	ch++;
	i++;
    }

    buffer[i] = 0;

    /* check whether the resource actually existed or not */
    if((strstr(buffer, "HTTP/1.1 404")) != NULL || (strstr(buffer, "HTTP/1.0 404")) != NULL) { 
	logg("^getfile: %s not found on remote server (IP: %s)\n", srcfile, ipaddr);
	mirman_update(mdat->currip, mdat->af, mdat, 2);
	closesocket(sd);
	return 58;
    }

    if(!strstr(buffer, "HTTP/1.1 200") && !strstr(buffer, "HTTP/1.0 200") &&
       !strstr(buffer, "HTTP/1.1 206") && !strstr(buffer, "HTTP/1.0 206")) {
	logg("%cgetfile: Unknown response from remote server (IP: %s)\n", logerr ? '!' : '^', ipaddr);
	mirman_update(mdat->currip, mdat->af, mdat, 1);
	closesocket(sd);
	return 58;
    }

    /* get size of resource */
    for(i = 0; (headerline = cli_strtok(buffer, i, "\n")); i++){
        if(strstr(headerline, "Content-Length:")) { 
	    if((ch = cli_strtok(headerline, 1, ": "))) {
		totalsize = atoi(ch);
		free(ch);
	    } else {
		totalsize = 0;
	    }
        }
	free(headerline);
    }

#ifdef FILTER_RULES
    {
        int pfd[2];

    	if (pipe(pfd) == -1) {
	    logg("!getfile: Can't create pipe to filter\n");
	    closesocket(sd);
	    return 57;
	}
	pid = fork();
	if (pid == -1) {
	    logg("!getfile: Can't filter fork failed\n");
	    closesocket(sd);
	    return 57;
	}
	if (pid == 0) {
	    /* Child */
	    close(pfd[1]);
	    dup2(pfd[0], 0);
	    close(pfd[0]);
	    execl("/bin/clamfilter", "clamfilter", destfile, NULL);
	    _exit(1);
	}
	/* Parent */
	close(pfd[0]);
	fd = pfd[1];
	destfile = "clam-filter";
    }
#else
    if((fd = open(destfile, O_WRONLY|O_CREAT|O_EXCL|O_BINARY, 0644)) == -1) {
	    char currdir[512];

	if(getcwd(currdir, sizeof(currdir)))
	    logg("!getfile: Can't create new file %s in %s\n", destfile, currdir);
	else
	    logg("!getfile: Can't create new file %s in the current directory\n", destfile);

	logg("Hint: The database directory must be writable for UID %d or GID %d\n", getuid(), getgid());
	closesocket(sd);
	return 57;
    }
#endif

#ifdef SO_ERROR
    while((bread = wait_recv(sd, buffer, FILEBUFF, 0, rtimeout)) > 0) {
#else
    while((bread = recv(sd, buffer, FILEBUFF, 0)) > 0) {
#endif
        if(write(fd, buffer, bread) != bread) {
	    logg("getfile: Can't write %d bytes to %s\n", bread, destfile);
#ifdef FILTER_RULES
//	    if (pid == -1)
//	        unlink(destfile);
#else
	    unlink(destfile);
#endif
	    close(fd);
	    closesocket(sd);
	    return 57; /* FIXME */
	}

        if(totalsize > 0) {
	    totaldownloaded += bread;
            percentage = (int) (100 * (float) totaldownloaded / totalsize);
	}

        if(!mprintf_quiet) {
            if(totalsize > 0) {
                mprintf("Downloading %s [%3i%%]\r", srcfile, percentage);
            } else {
                mprintf("Downloading %s [%c]\r", srcfile, rotation[rot]);
                rot++;
                rot %= 4;
            }
            fflush(stdout);
        }
    }
    closesocket(sd);
    close(fd);

#ifdef FILTER_RULES
    /*if (pid != -1)*/ {
	    int status;

	waitpid(pid, &status, 0);
	if (! WIFEXITED(status) || WEXITSTATUS(status) != 0) {
	    logg("!getfile: Filter failed\n");
	    return 57;
	}
    }
#endif

    if(totalsize > 0)
        logg("Downloading %s [%i%%]\n", srcfile, percentage);
    else
        logg("Downloading %s [*]\n", srcfile);

    mirman_update(mdat->currip, mdat->af, mdat, 0);
    return 0;
}

static int getcvd(const char *cvdfile, const char *newfile, const char *hostname, char *ip, const char *localip, const char *proxy, int port, const char *user, const char *pass, const char *uas, unsigned int newver, int ctimeout, int rtimeout, struct mirdat *mdat, int logerr, unsigned int can_whitelist)
{
	struct cl_cvd *cvd;
	int ret;


    logg("*Retrieving http://%s/%s\n", hostname, cvdfile);
    if((ret = getfile(cvdfile, newfile, hostname, ip, localip, proxy, port, user, pass, uas, ctimeout, rtimeout, mdat, logerr, can_whitelist))) {
        logg("%cCan't download %s from %s\n", logerr ? '!' : '^', cvdfile, hostname);
        unlink(newfile);
        return ret;
    }

    if((ret = cl_cvdverify(newfile))) {
        logg("!Verification: %s\n", cl_strerror(ret));
        unlink(newfile);
        return 54;
    }

    if(!(cvd = cl_cvdhead(newfile))) {
	logg("!Can't read CVD header of new %s database.\n", cvdfile);
	unlink(newfile);
	return 54;
    }

    if(cvd->version < newver) {
	logg("^Mirror %s is not synchronized.\n", ip);
	mirman_update(mdat->currip, mdat->af, mdat, 2);
    	cl_cvdfree(cvd);
	unlink(newfile);
	return 59;
    }

    cl_cvdfree(cvd);
    return 0;
}

static int chdir_tmp(const char *dbname, const char *tmpdir)
{
	char cvdfile[32];


    if(access(tmpdir, R_OK|W_OK) == -1) {
	sprintf(cvdfile, "%s.cvd", dbname);
	if(access(cvdfile, R_OK) == -1) {
	    sprintf(cvdfile, "%s.cld", dbname);
	    if(access(cvdfile, R_OK) == -1) {
		logg("!chdir_tmp: Can't access local %s database\n", dbname);
		return -1;
	    }
	}

	if(mkdir(tmpdir, 0755) == -1) {
	    logg("!chdir_tmp: Can't create directory %s\n", tmpdir);
	    return -1;
	}

	if(cli_cvdunpack(cvdfile, tmpdir) == -1) {
	    logg("!chdir_tmp: Can't unpack %s into %s\n", cvdfile, tmpdir);
	    cli_rmdirs(tmpdir);
	    return -1;
	}
    }

    if(chdir(tmpdir) == -1) {
	logg("!chdir_tmp: Can't change directory to %s\n", tmpdir);
	return -1;
    }

    return 0;
}

static int getpatch(const char *dbname, const char *tmpdir, int version, const char *hostname, char *ip, const char *localip, const char *proxy, int port, const char *user, const char *pass, const char *uas, int ctimeout, int rtimeout, struct mirdat *mdat, int logerr, unsigned int can_whitelist)
{
	char *tempname, patch[32], olddir[512];
	int ret, fd;


    if(!getcwd(olddir, sizeof(olddir))) {
	logg("!getpatch: Can't get path of current working directory\n");
	return 50; /* FIXME */
    }

    if(chdir_tmp(dbname, tmpdir) == -1)
	return 50;

    tempname = cli_gentemp(".");
    snprintf(patch, sizeof(patch), "%s-%d.cdiff", dbname, version);

    logg("*Retrieving http://%s/%s\n", hostname, patch);
    if((ret = getfile(patch, tempname, hostname, ip, localip, proxy, port, user, pass, uas, ctimeout, rtimeout, mdat, logerr, can_whitelist))) {
        logg("%cgetpatch: Can't download %s from %s\n", logerr ? '!' : '^', patch, hostname);
        unlink(tempname);
        free(tempname);
	CHDIR_ERR(olddir);
        return ret;
    }

    if((fd = open(tempname, O_RDONLY|O_BINARY)) == -1) {
	logg("!getpatch: Can't open %s for reading\n", tempname);
        unlink(tempname);
        free(tempname);
	CHDIR_ERR(olddir);
	return 55;
    }

    if(cdiff_apply(fd, 1) == -1) {
	logg("!getpatch: Can't apply patch\n");
	close(fd);
        unlink(tempname);
        free(tempname);
	CHDIR_ERR(olddir);
	return 70; /* FIXME */
    }

    close(fd);
    unlink(tempname);
    free(tempname);
    if(chdir(olddir) == -1) {
	logg("!getpatch: Can't chdir to %s\n", olddir);
	return 50; /* FIXME */
    }
    return 0;
}
コード例 #7
0
ファイル: manager.c プロジェクト: OPSF/uClinux
static int updatedb(const char *dbname, const char *hostname, char *ip, int *signo, const struct optstruct *opts, const char *dnsreply, char *localip, int outdated, struct mirdat *mdat, int logerr)
{
	struct cl_cvd *current, *remote;
	const struct optstruct *opt;
	unsigned int nodb = 0, currver = 0, newver = 0, port = 0, i, j;
	int ret, ims = -1;
	char *pt, cvdfile[32], localname[32], *tmpdir = NULL, *newfile, newdb[32], cwd[512];
	const char *proxy = NULL, *user = NULL, *pass = NULL, *uas = NULL;
	unsigned int flevel = cl_retflevel(), remote_flevel = 0, maxattempts;
	unsigned int can_whitelist = 0;
	int ctimeout, rtimeout;


    snprintf(cvdfile, sizeof(cvdfile), "%s.cvd", dbname);

    if(!(current = currentdb(dbname, localname))) {
	nodb = 1;
    } else {
	mdat->dbflevel = current->fl;
    }

    if(!nodb && dnsreply) {
	    int field = 0;

	if(!strcmp(dbname, "main")) {
	    field = 1;
	} else if(!strcmp(dbname, "daily")) {
	    field = 2;
	} else if(!strcmp(dbname, "safebrowsing")) {
	    field = 6;
	} else {
	    logg("!updatedb: Unknown database name (%s) passed.\n", dbname);
	    cl_cvdfree(current);
	    return 70;
	}

	if(field && (pt = cli_strtok(dnsreply, field, ":"))) {
	    if(!cli_isnumber(pt)) {
		logg("^Broken database version in TXT record.\n");
	    } else {
		newver = atoi(pt);
		logg("*%s version from DNS: %d\n", cvdfile, newver);
	    }
	    free(pt);
	} else {
	    logg("^Invalid DNS reply. Falling back to HTTP mode.\n");
	}
    }

    if(dnsreply) {
	if((pt = cli_strtok(dnsreply, 5, ":"))) {
	    remote_flevel = atoi(pt);
	    free(pt);
	    if(remote_flevel && (remote_flevel - flevel < 4))
		can_whitelist = 1;
	}
    }

    /* Initialize proxy settings */
    if((opt = optget(opts, "HTTPProxyServer"))->enabled) {
	proxy = opt->strarg;
	if(strncasecmp(proxy, "http://", 7) == 0)
	    proxy += 7;

	if((opt = optget(opts, "HTTPProxyUsername"))->enabled) {
	    user = opt->strarg;
	    if((opt = optget(opts, "HTTPProxyPassword"))->enabled) {
		pass = opt->strarg;
	    } else {
		logg("HTTPProxyUsername requires HTTPProxyPassword\n");
		if(current)
		    cl_cvdfree(current);
		return 56;
	    }
	}

	if((opt = optget(opts, "HTTPProxyPort"))->enabled)
	    port = opt->numarg;

	logg("Connecting via %s\n", proxy);
    }

    if((opt = optget(opts, "HTTPUserAgent"))->enabled)
	uas = opt->strarg;

    ctimeout = optget(opts, "ConnectTimeout")->numarg;
    rtimeout = optget(opts, "ReceiveTimeout")->numarg;

    if(!nodb && !newver) {

	remote = remote_cvdhead(cvdfile, localname, hostname, ip, localip, proxy, port, user, pass, uas, &ims, ctimeout, rtimeout, mdat, logerr, can_whitelist);

	if(!nodb && !ims) {
	    logg("%s is up to date (version: %d, sigs: %d, f-level: %d, builder: %s)\n", localname, current->version, current->sigs, current->fl, current->builder);
	    *signo += current->sigs;
	    cl_cvdfree(current);
	    return 1;
	}

	if(!remote) {
	    logg("^Can't read %s header from %s (IP: %s)\n", cvdfile, hostname, ip);
	    cl_cvdfree(current);
	    return 58;
	}

	newver = remote->version;
	cl_cvdfree(remote);
    }

    if(!nodb && (current->version >= newver)) {
	logg("%s is up to date (version: %d, sigs: %d, f-level: %d, builder: %s)\n", localname, current->version, current->sigs, current->fl, current->builder);

	if(!outdated && flevel < current->fl) {
	    /* display warning even for already installed database */
	    logg("^Current functionality level = %d, recommended = %d\n", flevel, current->fl);
	    logg("Please check if ClamAV tools are linked against the proper version of libclamav\n");
	    logg("DON'T PANIC! Read http://www.clamav.net/support/faq\n");
	}

	*signo += current->sigs;
	cl_cvdfree(current);
	return 1;
    }


    if(current) {
	currver = current->version;
	cl_cvdfree(current);
    }

    /*
    if(ipaddr[0]) {
	hostfd = wwwconnect(ipaddr, proxy, port, NULL, localip);
    } else {
	hostfd = wwwconnect(hostname, proxy, port, ipaddr, localip);
	if(!ip[0])
	    strcpy(ip, ipaddr);
    }

    if(hostfd < 0) {
	if(ipaddr[0])
	    logg("Connection with %s (IP: %s) failed.\n", hostname, ipaddr);
	else
	    logg("Connection with %s failed.\n", hostname);
	return 52;
    };
    */

    if(!optget(opts, "ScriptedUpdates")->enabled)
	nodb = 1;

    if(!getcwd(cwd, sizeof(cwd))) {
	logg("!updatedb: Can't get path of current working directory\n");
	return 50; /* FIXME */
    }
    newfile = cli_gentemp(cwd);

    if(nodb) {
	ret = getcvd(cvdfile, newfile, hostname, ip, localip, proxy, port, user, pass, uas, newver, ctimeout, rtimeout, mdat, logerr, can_whitelist);
	if(ret) {
	    memset(ip, 0, 16);
	    free(newfile);
	    return ret;
	}
	snprintf(newdb, sizeof(newdb), "%s.cvd", dbname);

    } else {
	ret = 0;

	tmpdir = cli_gentemp(".");
	maxattempts = optget(opts, "MaxAttempts")->numarg;
	for(i = currver + 1; i <= newver; i++) {
	    for(j = 0; j < maxattempts; j++) {
		    int llogerr = logerr;
		if(logerr)
		    llogerr = (j == maxattempts - 1);
		ret = getpatch(dbname, tmpdir, i, hostname, ip, localip, proxy, port, user, pass, uas, ctimeout, rtimeout, mdat, llogerr, can_whitelist);
		if(ret == 52 || ret == 58) {
		    memset(ip, 0, 16);
		    continue;
		} else {
		    break;
		}
	    }
	    if(ret)
		break;
	}

	if(ret) {
	    cli_rmdirs(tmpdir);
	    free(tmpdir);
	    logg("^Incremental update failed, trying to download %s\n", cvdfile);
	    mirman_whitelist(mdat, 2);
	    ret = getcvd(cvdfile, newfile, hostname, ip, localip, proxy, port, user, pass, uas, newver, ctimeout, rtimeout, mdat, logerr, can_whitelist);
	    if(ret) {
		free(newfile);
		return ret;
	    }
	    snprintf(newdb, sizeof(newdb), "%s.cvd", dbname);
	} else {
	    if(buildcld(tmpdir, dbname, newfile, optget(opts, "CompressLocalDatabase")->enabled) == -1) {
		logg("!Can't create local database\n");
		cli_rmdirs(tmpdir);
		free(tmpdir);
		free(newfile);
		return 70; /* FIXME */
	    }
	    snprintf(newdb, sizeof(newdb), "%s.cld", dbname);
	    cli_rmdirs(tmpdir);
	    free(tmpdir);
	}
    }

    if(!(current = cl_cvdhead(newfile))) {
	logg("!Can't parse new database %s\n", newfile);
	unlink(newfile);
	free(newfile);
	return 55; /* FIXME */
    }

    if(!nodb && !access(localname, R_OK) && unlink(localname)) {
	logg("!Can't unlink %s. Please fix it and try again.\n", localname);
	unlink(newfile);
	free(newfile);
	return 53;
    }

#ifdef C_WINDOWS
    if(!access(newdb, R_OK) && unlink(newdb)) {
	logg("!Can't unlink %s. Please fix the problem manually and try again.\n", newdb);
	unlink(newfile);
	free(newfile);
	return 53;
    }
#endif

    if(rename(newfile, newdb) == -1) {
	logg("!Can't rename %s to %s: %s\n", newfile, newdb, strerror(errno));
	unlink(newfile);
	free(newfile);
	return 57;
    }
    free(newfile);

    logg("%s updated (version: %d, sigs: %d, f-level: %d, builder: %s)\n", newdb, current->version, current->sigs, current->fl, current->builder);

    if(flevel < current->fl) {
	logg("Your ClamAV installation is out of date.\n");
	logg("Current functionality level = %d, recommended = %d\n", flevel, current->fl);
	logg("A firmware upgrade might resolve this issue.\n");
	logg("Also read http://sgkb.securecomputing.com/article.asp?article=11282&p=2\n");
    }

    *signo += current->sigs;
    cl_cvdfree(current);
    return 0;
}