diff --git a/CMakeLists.txt b/CMakeLists.txt index 4f65e24ab4..4949e36c40 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -138,6 +138,47 @@ if(MAINTAINER_MODE) endif() find_package(Rust REQUIRED) +if(DEFINED CLANG_TIDY) + # Clang-tidy may be used to check for code style issues. + # It is not required to build ClamAV. See: https://clang.llvm.org/docs/ClangTidy.html + + # To enable clang-tidy, set the CMake variable CLANG_TIDY to your clang-tidy executable. + # E.g. `-D CLANG_TIDY=clang-tidy-16` + + # After a build, you may also wish to try to auto-fix some of the issues. + # To do this, run the following from the source directory: + # ```bash + # clang-apply-replacements --format --style-config=(pwd) ./build/ + # ``` + + if(NOT DEFINED CLANG_TIDY_OPTIONS) + set(CLANG_TIDY_OPTIONS + "readability-braces-around-statements" + # "readability-else-after-return" + # "readability-function-size" + # "readability-magic-numbers" + # "readability-redundant-string-cstr" + # "readability-redundant-string-init" + # "modernize-*" + # "performance-*" + # "bugprone-*" + ) + endif() + + string(REPLACE ";" "," CLANG_TIDY_OPTIONS "${CLANG_TIDY_OPTIONS}") + set(CLANG_TIDY_PROPERTY "${CLANG_TIDY};-checks=${CLANG_TIDY_OPTIONS}") + + set(CMAKE_C_CLANG_TIDY_EXPORT_FIXES_DIR "${CMAKE_BINARY_DIR}/clang-tidy-fixes") + + # Example of how to set clang-tidy for a target: + # + # if(CLANG_TIDY) + # set_target_properties( clamav PROPERTIES + # C_CLANG_TIDY "${CLANG_TIDY_PROPERTY}" + # C_CLANG_TIDY_EXPORT_FIXES_DIR "${CMAKE_BINARY_DIR}/clang-tidy-fixes" ) + # endif() +endif() + if(ENABLE_FUZZ) # We'd like the fuzz targets to be statically linked set(ENABLE_STATIC_LIB ON) @@ -1133,6 +1174,11 @@ ${b} Rust toolchain: ${e}${cargo_EXECUTABLE} (${cargo_VERSION}) ${b} CFLAGS: ${e}${CMAKE_C_FLAGS_${_build_type}} ${CMAKE_C_FLAGS} ${b} CXXFLAGS: ${e}${CMAKE_CXX_FLAGS_${_build_type}} ${CMAKE_CXX_FLAGS} ${b} WARNCFLAGS: ${e}${WARNCFLAGS}") +if(DEFINED CLANG_TIDY) +message("\ +${b} clang-tidy: ${e}${CLANG_TIDY} +${b} clang-tidy options: ${e}${CLANG_TIDY_OPTIONS}") +endif() if(VCPKG_TOOLCHAIN) message("\ ${c} Using vcpkg: ${e} diff --git a/clam-format b/clam-format index bf12baaba1..65113598e9 100755 --- a/clam-format +++ b/clam-format @@ -76,6 +76,9 @@ git checkout libclamav/inflate64.h git checkout libclamav/inflate64.c git checkout libclamav/inflate64_priv.h git checkout libclamav/queue.h +git checkout libclamav/nsis/bzlib.c +git checkout libclamav/nsis/infblock.c +git checkout libclamav/strlcat.c git checkout clamonacc/c-thread-pool/thpool.c git checkout clamonacc/c-thread-pool/thpool.h git checkout clamonacc/misc/fts.c diff --git a/clamav-milter/CMakeLists.txt b/clamav-milter/CMakeLists.txt index e9c0ff3cab..2dcfeae5ab 100644 --- a/clamav-milter/CMakeLists.txt +++ b/clamav-milter/CMakeLists.txt @@ -18,6 +18,12 @@ target_include_directories( clamav-milter ) set_target_properties( clamav-milter PROPERTIES COMPILE_FLAGS "${WARNCFLAGS}" ) +if(CLANG_TIDY) + set_target_properties( clamav-milter PROPERTIES + C_CLANG_TIDY "${CLANG_TIDY_PROPERTY}" + C_CLANG_TIDY_EXPORT_FIXES_DIR "${CMAKE_BINARY_DIR}/clang-tidy-fixes" ) +endif() + if (APPLE AND CLAMAV_SIGN_FILE) set_target_properties( clamav-milter PROPERTIES XCODE_ATTRIBUTE_CODE_SIGN_IDENTITY ${CODE_SIGN_IDENTITY} diff --git a/clamav-milter/allow_list.c b/clamav-milter/allow_list.c index d44244c7eb..a28922e5dd 100644 --- a/clamav-milter/allow_list.c +++ b/clamav-milter/allow_list.c @@ -79,21 +79,27 @@ int allow_list_init(const char *fname) char *ptr = buf; int len; - if (*buf == '#' || *buf == ':' || *buf == '!') + if (*buf == '#' || *buf == ':' || *buf == '!') { continue; + } if (!strncasecmp("From:", buf, 5)) { ptr += 5; addto = &wfrom; - } else if (!strncasecmp("To:", buf, 3)) + } else if (!strncasecmp("To:", buf, 3)) { ptr += 3; + } len = strlen(ptr) - 1; for (; len >= 0; len--) { - if (ptr[len] != '\n' && ptr[len] != '\r') break; + if (ptr[len] != '\n' && ptr[len] != '\r') { + break; + } ptr[len] = '\0'; } - if (!len) continue; + if (!len) { + continue; + } if (!(w = (struct WHLST *)malloc(sizeof(*w)))) { logg(LOGG_ERROR, "Out of memory loading allow list file\n"); allow_list_free(); @@ -117,14 +123,16 @@ int allowed(const char *addr, int from) { struct WHLST *w; - if (from) + if (from) { w = wfrom; - else + } else { w = wto; + } while (w) { - if (!cli_regexec(&w->preg, addr, 0, NULL, 0)) + if (!cli_regexec(&w->preg, addr, 0, NULL, 0)) { return 1; + } w = w->next; } return 0; @@ -147,14 +155,19 @@ int smtpauth_init(const char *r) int len; char *ptr; - if (*buf == '#' || *buf == ':' || *buf == '!') + if (*buf == '#' || *buf == ':' || *buf == '!') { continue; + } len = strlen(buf) - 1; for (; len >= 0; len--) { - if (buf[len] != '\n' && buf[len] != '\r') break; + if (buf[len] != '\n' && buf[len] != '\r') { + break; + } buf[len] = '\0'; } - if (len <= 0) continue; + if (len <= 0) { + continue; + } if (len * 3 + 1 > rxavail) { ptr = regex; char *temp = realloc(regex, rxsize + 2048); @@ -206,18 +219,23 @@ int smtpauth_init(const char *r) if (cli_regcomp(&authreg, r, REG_ICASE | REG_NOSUB | REG_EXTENDED)) { logg(LOGG_ERROR, "Failed to compile regex '%s' for SkipAuthenticated\n", r); - if (regex) free(regex); + if (regex) { + free(regex); + } return 1; } - if (regex) free(regex); + if (regex) { + free(regex); + } skipauth = 1; return 0; } int smtpauthed(const char *login) { - if (skipauth && !cli_regexec(&authreg, login, 0, NULL, 0)) + if (skipauth && !cli_regexec(&authreg, login, 0, NULL, 0)) { return 1; + } return 0; } diff --git a/clamav-milter/clamav-milter.c b/clamav-milter/clamav-milter.c index 8e2f40ede0..6b70eb5d87 100644 --- a/clamav-milter/clamav-milter.c +++ b/clamav-milter/clamav-milter.c @@ -66,10 +66,11 @@ static void milter_exit(int sig) #ifndef _WIN32 if ((opt = optget(opts, "MilterSocket"))) { - if (unlink(opt->strarg) == -1) + if (unlink(opt->strarg) == -1) { logg(LOGG_ERROR, "Can't unlink the socket file %s\n", opt->strarg); - else + } else { logg(LOGG_INFO, "Socket file removed.\n"); + } } #endif @@ -137,8 +138,9 @@ int main(int argc, char **argv) if (opts->filename) { int x; - for (x = 0; opts->filename[x]; x++) + for (x = 0; opts->filename[x]; x++) { mprintf(LOGG_WARNING, "Ignoring option %s\n", opts->filename[x]); + } } if (optget(opts, "version")->enabled) { @@ -233,12 +235,15 @@ int main(int argc, char **argv) /* set group ownership and perms on the local socket */ char *sock_name = my_socket; mode_t sock_mode; - if (!strncmp(my_socket, "unix:", 5)) + if (!strncmp(my_socket, "unix:", 5)) { sock_name += 5; - if (!strncmp(my_socket, "local:", 6)) + } + if (!strncmp(my_socket, "local:", 6)) { sock_name += 6; - if (*my_socket == ':') + } + if (*my_socket == ':') { sock_name++; + } if (optget(opts, "MilterSocketGroup")->enabled) { char *gname = optget(opts, "MilterSocketGroup")->strarg, *end; @@ -288,8 +293,9 @@ int main(int argc, char **argv) optfree(opts); return 1; } - } else + } else { sock_mode = 0777 & ~umsk; + } if (chmod(sock_name, sock_mode & 0666)) { logg(LOGG_ERROR, "Cannot set milter socket permission to %s\n", optget(opts, "MilterSocketMode")->strarg); @@ -303,8 +309,9 @@ int main(int argc, char **argv) logg_time = optget(opts, "LogTime")->enabled; logg_size = optget(opts, "LogFileMaxSize")->numarg; logg_verbose = mprintf_verbose = optget(opts, "LogVerbose")->enabled; - if (logg_size) + if (logg_size) { logg_rotate = optget(opts, "LogRotate")->enabled; + } if ((opt = optget(opts, "LogFile"))->enabled) { logg_file = opt->strarg; @@ -314,8 +321,9 @@ int main(int argc, char **argv) optfree(opts); return 1; } - } else + } else { logg_file = NULL; + } #if defined(USE_SYSLOG) && !defined(C_AIX) if (optget(opts, "LogSyslog")->enabled) { @@ -341,8 +349,9 @@ int main(int argc, char **argv) optfree(opts); return 1; } - if ((opt = optget(opts, "TemporaryDirectory"))->enabled) + if ((opt = optget(opts, "TemporaryDirectory"))->enabled) { tempdir = opt->strarg; + } if (localnets_init(opts) || init_actions(opts)) { logg_close(); diff --git a/clamav-milter/clamfi.c b/clamav-milter/clamfi.c index fbf8509929..0172fbf44d 100644 --- a/clamav-milter/clamfi.c +++ b/clamav-milter/clamfi.c @@ -99,21 +99,29 @@ struct CLAMFI { static void add_x_header(SMFICTX *ctx, char *st, unsigned int scanned, unsigned int status) { if (addxvirus == 1) { /* Replace/Yes */ - while (scanned) - if (smfi_chgheader(ctx, (char *)"X-Virus-Scanned", scanned--, NULL) != MI_SUCCESS) + while (scanned) { + if (smfi_chgheader(ctx, (char *)"X-Virus-Scanned", scanned--, NULL) != MI_SUCCESS) { logg(LOGG_WARNING, "Failed to remove existing X-Virus-Scanned header\n"); - while (status) - if (smfi_chgheader(ctx, (char *)"X-Virus-Status", status--, NULL) != MI_SUCCESS) + } + } + while (status) { + if (smfi_chgheader(ctx, (char *)"X-Virus-Status", status--, NULL) != MI_SUCCESS) { logg(LOGG_WARNING, "Failed to remove existing X-Virus-Status header\n"); - if (smfi_addheader(ctx, (char *)"X-Virus-Scanned", xvirushdr) != MI_SUCCESS) + } + } + if (smfi_addheader(ctx, (char *)"X-Virus-Scanned", xvirushdr) != MI_SUCCESS) { logg(LOGG_WARNING, "Failed to add X-Virus-Scanned header\n"); - if (smfi_addheader(ctx, (char *)"X-Virus-Status", st) != MI_SUCCESS) + } + if (smfi_addheader(ctx, (char *)"X-Virus-Status", st) != MI_SUCCESS) { logg(LOGG_WARNING, "Failed to add X-Virus-Status header\n"); + } } else { /* Add */ - if (smfi_insheader(ctx, 1, (char *)"X-Virus-Scanned", xvirushdr) != MI_SUCCESS) + if (smfi_insheader(ctx, 1, (char *)"X-Virus-Scanned", xvirushdr) != MI_SUCCESS) { logg(LOGG_WARNING, "Failed to insert X-Virus-Scanned header\n"); - if (smfi_insheader(ctx, 1, (char *)"X-Virus-Status", st) != MI_SUCCESS) + } + if (smfi_insheader(ctx, 1, (char *)"X-Virus-Status", st) != MI_SUCCESS) { logg(LOGG_WARNING, "Failed to insert X-Virus-Status header\n"); + } } } @@ -128,10 +136,13 @@ enum CFWHAT { static const char *makesanehdr(char *hdr) { char *ret = hdr; - if (!hdr) return HDR_UNAVAIL; + if (!hdr) { + return HDR_UNAVAIL; + } while (*hdr) { - if (*hdr == '\'' || *hdr == '\t' || *hdr == '\r' || *hdr == '\n' || !isprint(*hdr)) + if (*hdr == '\'' || *hdr == '\t' || *hdr == '\r' || *hdr == '\n' || !isprint(*hdr)) { *hdr = ' '; + } hdr++; } return ret; @@ -139,13 +150,21 @@ static const char *makesanehdr(char *hdr) static void nullify(SMFICTX *ctx, struct CLAMFI *cf, enum CFWHAT closewhat) { - if (closewhat & CF_MAIN || ((closewhat & CF_ANY) && cf->main >= 0)) + if (closewhat & CF_MAIN || ((closewhat & CF_ANY) && cf->main >= 0)) { close(cf->main); - if (closewhat & CF_ALT || ((closewhat & CF_ANY) && cf->alt >= 0)) + } + if (closewhat & CF_ALT || ((closewhat & CF_ANY) && cf->alt >= 0)) { close(cf->alt); - if (cf->msg_subj) free(cf->msg_subj); - if (cf->msg_date) free(cf->msg_date); - if (cf->msg_id) free(cf->msg_id); + } + if (cf->msg_subj) { + free(cf->msg_subj); + } + if (cf->msg_date) { + free(cf->msg_date); + } + if (cf->msg_id) { + free(cf->msg_id); + } if (multircpt && cf->nrecipients) { while (cf->nrecipients) { cf->nrecipients--; @@ -158,8 +177,9 @@ static void nullify(SMFICTX *ctx, struct CLAMFI *cf, enum CFWHAT closewhat) static sfsistat sendchunk(struct CLAMFI *cf, unsigned char *bodyp, size_t len, SMFICTX *ctx) { - if (cf->totsz >= maxfilesize || len == 0) + if (cf->totsz >= maxfilesize || len == 0) { return SMFIS_CONTINUE; + } if (!cf->totsz) { sfsistat ret; @@ -169,13 +189,15 @@ static sfsistat sendchunk(struct CLAMFI *cf, unsigned char *bodyp, size_t len, S return FailAction; } cf->totsz = 1; /* do not infloop */ - if ((ret = sendchunk(cf, (unsigned char *)"From clamav-milter\n", 19, ctx)) != SMFIS_CONTINUE) + if ((ret = sendchunk(cf, (unsigned char *)"From clamav-milter\n", 19, ctx)) != SMFIS_CONTINUE) { return ret; + } cf->totsz -= 1; } - if (cf->totsz + len > maxfilesize) + if (cf->totsz + len > maxfilesize) { len = maxfilesize - cf->totsz; + } cf->totsz += len; if (cf->local) { @@ -206,8 +228,9 @@ static sfsistat sendchunk(struct CLAMFI *cf, unsigned char *bodyp, size_t len, S } else { uint32_t sendmetoo = htonl(len); cf->sendme = htonl(cf->bufsz); - if ((cf->bufsz && nc_send(cf->main, &cf->sendme, cf->bufsz + 4)) || nc_send(cf->main, &sendmetoo, 4) || nc_send(cf->main, bodyp, len)) + if ((cf->bufsz && nc_send(cf->main, &cf->sendme, cf->bufsz + 4)) || nc_send(cf->main, &sendmetoo, 4) || nc_send(cf->main, bodyp, len)) { sendfailed = 1; + } cf->bufsz = 0; } if (sendfailed) { @@ -224,8 +247,9 @@ sfsistat clamfi_header(SMFICTX *ctx, char *headerf, char *headerv) struct CLAMFI *cf; sfsistat ret; - if (!(cf = (struct CLAMFI *)smfi_getpriv(ctx))) + if (!(cf = (struct CLAMFI *)smfi_getpriv(ctx))) { return SMFIS_CONTINUE; /* whatever */ + } if (!cf->totsz && cf->all_allowed) { logg(LOGG_DEBUG, "Skipping scan (all destinations allowed)\n"); @@ -234,20 +258,29 @@ sfsistat clamfi_header(SMFICTX *ctx, char *headerf, char *headerv) return SMFIS_ACCEPT; } - if (!headerf) return SMFIS_CONTINUE; /* just in case */ + if (!headerf) { + return SMFIS_CONTINUE; /* just in case */ + } if ((loginfected & (LOGINF_FULL | LOGCLN_FULL)) || viraction) { - if (!cf->msg_subj && !strcasecmp(headerf, "Subject")) + if (!cf->msg_subj && !strcasecmp(headerf, "Subject")) { cf->msg_subj = strdup(headerv ? headerv : ""); - if (!cf->msg_date && !strcasecmp(headerf, "Date")) + } + if (!cf->msg_date && !strcasecmp(headerf, "Date")) { cf->msg_date = strdup(headerv ? headerv : ""); - if (!cf->msg_id && !strcasecmp(headerf, "Message-ID")) + } + if (!cf->msg_id && !strcasecmp(headerf, "Message-ID")) { cf->msg_id = strdup(headerv ? headerv : ""); + } } if (addxvirus == 1) { - if (!strcasecmp(headerf, "X-Virus-Scanned")) cf->scanned_count++; - if (!strcasecmp(headerf, "X-Virus-Status")) cf->status_count++; + if (!strcasecmp(headerf, "X-Virus-Scanned")) { + cf->scanned_count++; + } + if (!strcasecmp(headerf, "X-Virus-Status")) { + cf->status_count++; + } } if ((ret = sendchunk(cf, (unsigned char *)headerf, strlen(headerf), ctx)) != SMFIS_CONTINUE) { @@ -263,8 +296,9 @@ sfsistat clamfi_header(SMFICTX *ctx, char *headerf, char *headerv) return ret; } ret = sendchunk(cf, (unsigned char *)"\r\n", 2, ctx); - if (ret != SMFIS_CONTINUE) + if (ret != SMFIS_CONTINUE) { free(cf); + } return ret; } @@ -273,8 +307,9 @@ sfsistat clamfi_body(SMFICTX *ctx, unsigned char *bodyp, size_t len) struct CLAMFI *cf; sfsistat ret; - if (!(cf = (struct CLAMFI *)smfi_getpriv(ctx))) + if (!(cf = (struct CLAMFI *)smfi_getpriv(ctx))) { return SMFIS_CONTINUE; /* whatever */ + } if (!cf->gotbody) { ret = sendchunk(cf, (unsigned char *)"\r\n", 2, ctx); @@ -286,8 +321,9 @@ sfsistat clamfi_body(SMFICTX *ctx, unsigned char *bodyp, size_t len) } ret = sendchunk(cf, bodyp, len, ctx); - if (ret != SMFIS_CONTINUE) + if (ret != SMFIS_CONTINUE) { free(cf); + } return ret; } @@ -309,8 +345,9 @@ sfsistat clamfi_eom(SMFICTX *ctx) int len, ret; unsigned int crcpt; - if (!(cf = (struct CLAMFI *)smfi_getpriv(ctx))) + if (!(cf = (struct CLAMFI *)smfi_getpriv(ctx))) { return SMFIS_CONTINUE; /* whatever */ + } if (!cf->totsz) { /* got no headers and no body */ @@ -343,8 +380,9 @@ sfsistat clamfi_eom(SMFICTX *ctx) reply = nc_recv(cf->main); - if (cf->local) + if (cf->local) { close(cf->alt); + } cf->alt = -1; @@ -357,7 +395,9 @@ sfsistat clamfi_eom(SMFICTX *ctx) len = strlen(reply); if (len > 5 && !strcmp(reply + len - 5, ": OK\n")) { - if (addxvirus) add_x_header(ctx, "Clean", cf->scanned_count, cf->status_count); + if (addxvirus) { + add_x_header(ctx, "Clean", cf->scanned_count, cf->status_count); + } if (loginfected & LOGCLN_FULL) { const char *id = smfi_getsymval(ctx, "{i}"); const char *from = smfi_getsymval(ctx, "{mail_addr}"); @@ -365,8 +405,9 @@ sfsistat clamfi_eom(SMFICTX *ctx) const char *msg_date = makesanehdr(cf->msg_date); const char *msg_id = makesanehdr(cf->msg_id); if (multircpt && cf->nrecipients) { - for (crcpt = 0; crcpt < cf->nrecipients; crcpt++) + for (crcpt = 0; crcpt < cf->nrecipients; crcpt++) { logg(LOGG_INFO, "Clean message %s from <%s> to <%s> with subject '%s' message-id '%s' date '%s'\n", id, from, cf->recipients[crcpt], msg_subj, msg_id, msg_date); + } } else { const char *to = smfi_getsymval(ctx, "{rcpt_addr}"); logg(LOGG_INFO, "Clean message %s from <%s> to <%s> with subject '%s' message-id '%s' date '%s'\n", id, from, to ? to : HDR_UNAVAIL, msg_subj, msg_id, msg_date); @@ -374,8 +415,9 @@ sfsistat clamfi_eom(SMFICTX *ctx) } else if (loginfected & LOGCLN_BASIC) { const char *from = smfi_getsymval(ctx, "{mail_addr}"); if (multircpt && cf->nrecipients) { - for (crcpt = 0; crcpt < cf->nrecipients; crcpt++) + for (crcpt = 0; crcpt < cf->nrecipients; crcpt++) { logg(LOGG_INFO, "Clean message from <%s> to <%s>\n", from, cf->recipients[crcpt]); + } } else { const char *to = smfi_getsymval(ctx, "{rcpt_addr}"); logg(LOGG_INFO, "Clean message from <%s> to <%s>\n", from, to ? to : HDR_UNAVAIL); @@ -394,8 +436,9 @@ sfsistat clamfi_eom(SMFICTX *ctx) unsigned int lst_rcpt = (have_multi * (cf->nrecipients - 1)) + 1; vir++; - if (rejectfmt) + if (rejectfmt) { cf->virusname = vir; + } if (addxvirus) { char msg[255]; @@ -409,18 +452,25 @@ sfsistat clamfi_eom(SMFICTX *ctx) const char *from = smfi_getsymval(ctx, "{mail_addr}"); const char *to = have_multi ? cf->recipients[crcpt] : smfi_getsymval(ctx, "{rcpt_addr}"); - if (!from) from = HDR_UNAVAIL; - if (!to) to = HDR_UNAVAIL; + if (!from) { + from = HDR_UNAVAIL; + } + if (!to) { + to = HDR_UNAVAIL; + } if ((loginfected & LOGINF_FULL) || viraction) { const char *id = smfi_getsymval(ctx, "{i}"); const char *msg_subj = makesanehdr(cf->msg_subj); const char *msg_date = makesanehdr(cf->msg_date); const char *msg_id = makesanehdr(cf->msg_id); - if (!id) id = HDR_UNAVAIL; + if (!id) { + id = HDR_UNAVAIL; + } - if (loginfected & LOGINF_FULL) + if (loginfected & LOGINF_FULL) { logg(LOGG_INFO, "Message %s from <%s> to <%s> with subject '%s' message-id '%s' date '%s' infected by %s\n", id, from, to, msg_subj, msg_id, msg_date, vir); + } if (viraction) { char er[256]; @@ -451,16 +501,19 @@ sfsistat clamfi_eom(SMFICTX *ctx) } else if (pid > 0) { int wret; pthread_mutex_unlock(&virusaction_lock); - while ((wret = waitpid(pid, &ret, 0)) == -1 && errno == EINTR) continue; - if (wret < 0) + while ((wret = waitpid(pid, &ret, 0)) == -1 && errno == EINTR) { + continue; + } + if (wret < 0) { logg(LOGG_ERROR, "VirusEvent: waitpid() failed: %s\n", cli_strerror(errno, er, sizeof(er))); - else { - if (WIFEXITED(ret)) + } else { + if (WIFEXITED(ret)) { logg(LOGG_DEBUG, "VirusEvent: child exited with code %d\n", WEXITSTATUS(ret)); - else if (WIFSIGNALED(ret)) + } else if (WIFSIGNALED(ret)) { logg(LOGG_DEBUG, "VirusEvent: child killed by signal %d\n", WTERMSIG(ret)); - else + } else { logg(LOGG_DEBUG, "VirusEvent: child lost\n"); + } } } else { logg(LOGG_ERROR, "VirusEvent: fork failed: %s\n", cli_strerror(errno, er, sizeof(er))); @@ -473,8 +526,9 @@ sfsistat clamfi_eom(SMFICTX *ctx) free(e_msg_id); } } - if (loginfected & LOGINF_BASIC) + if (loginfected & LOGINF_BASIC) { logg(LOGG_INFO, "Message from <%s> to <%s> infected by %s\n", from, to, vir); + } } } } @@ -504,8 +558,9 @@ sfsistat clamfi_connect(_UNUSED_ SMFICTX *ctx, char *hostname, _SOCK_ADDR *hosta } break; } - if (!strcasecmp(hostname, "localhost")) + if (!strcasecmp(hostname, "localhost")) { hostname = NULL; + } if (islocalnet_name(hostname)) { logg(LOGG_DEBUG, "Skipping scan for %s (in LocalNet)\n", hostname ? hostname : "local"); return SMFIS_ACCEPT; @@ -517,16 +572,21 @@ sfsistat clamfi_connect(_UNUSED_ SMFICTX *ctx, char *hostname, _SOCK_ADDR *hosta static int parse_action(char *action) { - if (!strcasecmp(action, "Accept")) + if (!strcasecmp(action, "Accept")) { return 0; - if (!strcasecmp(action, "Defer")) + } + if (!strcasecmp(action, "Defer")) { return 1; - if (!strcasecmp(action, "Reject")) + } + if (!strcasecmp(action, "Reject")) { return 2; - if (!strcasecmp(action, "Blackhole")) + } + if (!strcasecmp(action, "Blackhole")) { return 3; - if (!strcasecmp(action, "Quarantine")) + } + if (!strcasecmp(action, "Quarantine")) { return 4; + } logg(LOGG_ERROR, "Unknown action %s\n", action); return -1; } @@ -561,8 +621,9 @@ static sfsistat action_reject_msg(SMFICTX *ctx) struct CLAMFI *cf; char buf[1024]; - if (!rejectfmt || !(cf = (struct CLAMFI *)smfi_getpriv(ctx))) + if (!rejectfmt || !(cf = (struct CLAMFI *)smfi_getpriv(ctx))) { return SMFIS_REJECT; + } snprintf(buf, sizeof(buf), rejectfmt, cf->virusname); buf[sizeof(buf) - 1] = '\0'; @@ -574,30 +635,31 @@ int init_actions(struct optstruct *opts) { const struct optstruct *opt; - if (!(opt = optget(opts, "LogInfected"))->enabled || !strcasecmp(opt->strarg, "Off")) + if (!(opt = optget(opts, "LogInfected"))->enabled || !strcasecmp(opt->strarg, "Off")) { loginfected = LOGINF_NONE; - else if (!strcasecmp(opt->strarg, "Basic")) + } else if (!strcasecmp(opt->strarg, "Basic")) { loginfected = LOGINF_BASIC; - else if (!strcasecmp(opt->strarg, "Full")) + } else if (!strcasecmp(opt->strarg, "Full")) { loginfected = LOGINF_FULL; - else { + } else { logg(LOGG_ERROR, "Invalid setting %s for option LogInfected\n", opt->strarg); return 1; } if ((opt = optget(opts, "LogClean"))->enabled) { - if (!strcasecmp(opt->strarg, "Basic")) + if (!strcasecmp(opt->strarg, "Basic")) { loginfected |= LOGCLN_BASIC; - else if (!strcasecmp(opt->strarg, "Full")) + } else if (!strcasecmp(opt->strarg, "Full")) { loginfected |= LOGCLN_FULL; - else if (strcasecmp(opt->strarg, "Off")) { + } else if (strcasecmp(opt->strarg, "Off")) { logg(LOGG_ERROR, "Invalid setting %s for option LogClean\n", opt->strarg); return 1; } } - if ((opt = optget(opts, "VirusAction"))->enabled) + if ((opt = optget(opts, "VirusAction"))->enabled) { viraction = strdup(opt->strarg); + } if ((opt = optget(opts, "OnFail"))->enabled) { switch (parse_action(opt->strarg)) { @@ -614,8 +676,9 @@ int init_actions(struct optstruct *opts) logg(LOGG_ERROR, "Invalid action %s for option OnFail\n", opt->strarg); return 1; } - } else + } else { FailAction = SMFIS_TEMPFAIL; + } if ((opt = optget(opts, "OnClean"))->enabled) { switch (parse_action(opt->strarg)) { @@ -638,8 +701,9 @@ int init_actions(struct optstruct *opts) logg(LOGG_ERROR, "Invalid action %s for option OnClean\n", opt->strarg); return 1; } - } else + } else { CleanAction = action_accept; + } if ((opt = optget(opts, "OnInfected"))->enabled) { switch (parse_action(opt->strarg)) { @@ -697,8 +761,9 @@ int init_actions(struct optstruct *opts) logg(LOGG_ERROR, "Invalid action %s for option OnInfected\n", opt->strarg); return 1; } - } else + } else { InfectedAction = action_quarantine; + } return 0; } @@ -744,11 +809,13 @@ sfsistat clamfi_envrcpt(SMFICTX *ctx, char **argv) { struct CLAMFI *cf; - if (!(cf = (struct CLAMFI *)smfi_getpriv(ctx))) + if (!(cf = (struct CLAMFI *)smfi_getpriv(ctx))) { return SMFIS_CONTINUE; /* whatever */ + } - if (cf->all_allowed) + if (cf->all_allowed) { cf->all_allowed &= allowed(argv[0], 0); + } if (multircpt) { void *new_rcpt = realloc(cf->recipients, (cf->nrecipients + 1) * sizeof(*(cf->recipients))); diff --git a/clamav-milter/connpool.c b/clamav-milter/connpool.c index 0e241ffee2..caeff0ae64 100644 --- a/clamav-milter/connpool.c +++ b/clamav-milter/connpool.c @@ -92,7 +92,9 @@ static int cpool_addunix(char *path) cpe->server = (struct sockaddr *)srv; cpe->socklen = sizeof(*srv); SETGAI(cpe, NULL); - if (!cp->local_cpe) cp->local_cpe = cpe; + if (!cp->local_cpe) { + cp->local_cpe = cpe; + } logg(LOGG_DEBUG, "Local socket unix:%s added to the pool (slot %d)\n", srv->sun_path, cp->entries); return 0; } @@ -101,7 +103,9 @@ static int islocal(struct sockaddr *sa, socklen_t addrlen) { int s = socket(sa->sa_family, SOCK_STREAM, 0); int ret; - if (s < 0) return 0; + if (s < 0) { + return 0; + } ret = (bind(s, sa, addrlen) == 0); close(s); return ret; @@ -130,8 +134,9 @@ static int cpool_addtcp(char *addr, char *port) if (!getaddrinfo(addr, NULL, &hints, &res2)) { cpe->local = islocal(res2->ai_addr, res2->ai_addrlen); freeaddrinfo(res2); - } else + } else { cpe->local = 0; + } cpe->last_poll = 0; cpe->server = res->ai_addr; cpe->socklen = res->ai_addrlen; @@ -149,8 +154,9 @@ static int addslot(void) cpool_free(); return 1; } - if (cp->local_cpe) + if (cp->local_cpe) { cp->local_cpe = (struct CP_ENTRY *)((char *)cp->local_cpe + ((char *)cpe - (char *)cp->pool)); + } memset(&cpe[cp->entries], 0, sizeof(*cpe)); cp->pool = cpe; cp->entries++; @@ -180,8 +186,9 @@ static void cpool_probe(void) } cp->alive = cp->entries - dead; - if (!cp->alive) + if (!cp->alive) { logg(LOGG_WARNING, "No clamd server appears to be available\n"); + } } static void *cpool_mon(_UNUSED_ void *v) @@ -220,7 +227,9 @@ void cpool_init(struct optstruct *opts) while (opt) { char *socktype = opt->strarg; - if (addslot()) return; + if (addslot()) { + return; + } if (!strncasecmp(socktype, "unix:", 5)) { failed = cpool_addunix(socktype + 5); } else if (!strncasecmp(socktype, "tcp:", 4)) { @@ -234,7 +243,9 @@ void cpool_init(struct optstruct *opts) logg(LOGG_ERROR, "Failed to parse ClamdSocket directive '%s'\n", socktype); failed = 1; } - if (failed) break; + if (failed) { + break; + } opt = opt->nextarg; } if (failed) { @@ -284,9 +295,12 @@ struct CP_ENTRY *cpool_get_rand(int *s) start = rand() % cp->entries; for (i = 0; i < cp->entries; i++) { cpe = &cp->pool[(i + start) % cp->entries]; - if (cpe->dead) continue; - if (cpe->local && cp->local_cpe && !cp->local_cpe->dead) + if (cpe->dead) { + continue; + } + if (cpe->local && cp->local_cpe && !cp->local_cpe->dead) { cpe = cp->local_cpe; + } if ((*s = nc_connect_entry(cpe)) == -1) { cpe->dead = 1; continue; diff --git a/clamav-milter/netcode.c b/clamav-milter/netcode.c index 52cc4561e6..13db0032b9 100644 --- a/clamav-milter/netcode.c +++ b/clamav-milter/netcode.c @@ -110,7 +110,9 @@ static int nc_connect(int s, struct CP_ENTRY *cpe) struct timeval tv; char er[256]; - if (!res) return 0; + if (!res) { + return 0; + } if (errno != EINPROGRESS) { strerror_print(LOGG_DEBUG, "connect failed"); close(s); @@ -255,8 +257,9 @@ char *nc_recv(int s) res = select(s + 1, &fds, NULL, NULL, readtimeout ? &tv : NULL); if (res < 1) { - if (res != -1 || errno != EINTR) + if (res != -1 || errno != EINTR) { timeout = 0; + } continue; } @@ -268,14 +271,17 @@ char *nc_recv(int s) } if (res == -1) { char er[256]; - if (errno == EAGAIN) + if (errno == EAGAIN) { continue; + } strerror_print(LOGG_ERROR, "recv failed after successful select"); close(s); return NULL; } len += res; - if (len && buf[len - 1] == '\n') break; + if (len && buf[len - 1] == '\n') { + break; + } if (len >= sizeof(buf)) { logg(LOGG_ERROR, "Overlong reply from clamd\n"); close(s); @@ -295,7 +301,9 @@ char *nc_recv(int s) int nc_connect_entry(struct CP_ENTRY *cpe) { int s = nc_socket(cpe); - if (s == -1) return -1; + if (s == -1) { + return -1; + } return nc_connect(s, cpe) ? -1 : s; } @@ -320,7 +328,9 @@ int nc_connect_rand(int *main, int *alt, int *local) { struct CP_ENTRY *cpe = cpool_get_rand(main); - if (!cpe) return 1; + if (!cpe) { + return 1; + } *local = (cpe->server->sa_family == AF_UNIX); if (*local) { char *unlinkme; @@ -414,10 +424,11 @@ static struct LOCALNET *localnet(char *name, char *mask) return l; } - if (!mask || !*mask) + if (!mask || !*mask) { nmask = 32 + 96 * (l->family == INET6_HOST); - else + } else { nmask = atoi(mask); + } if ((l->family == INET6_HOST && nmask > 128) || (l->family == INET_HOST && nmask > 32)) { logg(LOGG_ERROR, "Bad netmask '/%s' for LocalNet %s\n", mask, name); @@ -426,8 +437,9 @@ static struct LOCALNET *localnet(char *name, char *mask) } l->mask[0] = l->mask[1] = l->mask[2] = l->mask[3] = 0; - for (i = 0; i < nmask; i++) + for (i = 0; i < nmask; i++) { l->mask[i >> 5] |= 1 << (31 - (i & 31)); + } l->basehost[0] &= l->mask[0]; l->basehost[1] &= l->mask[1]; @@ -441,12 +453,16 @@ static int islocalnet(uint32_t family, uint32_t *host) { struct LOCALNET *l = lnet; - if (!l) return 0; + if (!l) { + return 0; + } while (l) { if ( (l->family == family) && (l->basehost[0] == (host[0] & l->mask[0])) && (l->basehost[1] == (host[1] & l->mask[1])) && - (l->basehost[2] == (host[2] & l->mask[2])) && (l->basehost[3] == (host[3] & l->mask[3]))) return 1; + (l->basehost[2] == (host[2] & l->mask[2])) && (l->basehost[3] == (host[3] & l->mask[3]))) { + return 1; + } l = l->next; } return 0; @@ -456,7 +472,9 @@ int islocalnet_name(char *name) { uint32_t host[4], family; - if (!lnet) return 0; + if (!lnet) { + return 0; + } if (resolve(name, &family, host)) { logg(LOGG_DEBUG, "Cannot resolv %s\n", name); return 0; @@ -469,7 +487,9 @@ int islocalnet_sock(struct sockaddr *sa) uint32_t host[4] = {0}; uint32_t family; - if (!lnet) return 0; + if (!lnet) { + return 0; + } if (sa->sa_family == AF_INET) { struct sockaddr_in *sa4 = (struct sockaddr_in *)sa; @@ -489,8 +509,9 @@ int islocalnet_sock(struct sockaddr *sa) j = u = 0; } } - } else + } else { return 0; + } return islocalnet(family, host); } @@ -518,7 +539,9 @@ int localnets_init(struct optstruct *opts) *mask = '\0'; mask++; } - if (!strcasecmp(lnetname, "local")) lnetname = NULL; + if (!strcasecmp(lnetname, "local")) { + lnetname = NULL; + } if ((l = localnet(lnetname, mask)) == NULL) { localnets_free(); return 1; diff --git a/clambc/CMakeLists.txt b/clambc/CMakeLists.txt index c5d831db96..15da18b656 100644 --- a/clambc/CMakeLists.txt +++ b/clambc/CMakeLists.txt @@ -23,6 +23,12 @@ target_include_directories( clambc ) set_target_properties( clambc PROPERTIES COMPILE_FLAGS "${WARNCFLAGS}" ) +if(CLANG_TIDY) + set_target_properties( clambc PROPERTIES + C_CLANG_TIDY "${CLANG_TIDY_PROPERTY}" + C_CLANG_TIDY_EXPORT_FIXES_DIR "${CMAKE_BINARY_DIR}/clang-tidy-fixes" ) +endif() + if (APPLE AND CLAMAV_SIGN_FILE) set_target_properties( clambc PROPERTIES XCODE_ATTRIBUTE_CODE_SIGN_IDENTITY ${CODE_SIGN_IDENTITY} diff --git a/clambc/bcrun.c b/clambc/bcrun.c index 3cb683181e..8de7277a5b 100644 --- a/clambc/bcrun.c +++ b/clambc/bcrun.c @@ -89,8 +89,9 @@ static struct dbg_state { static void tracehook(struct cli_bc_ctx *ctx, unsigned event) { dbg_state.directory = ctx->directory; - if (*ctx->file == '?') + if (*ctx->file == '?') { return; + } switch (event) { case trace_func: fprintf(stderr, "[trace] %s:%u:%u -> %s:%u:%u Entered function %s\n", @@ -109,11 +110,12 @@ static void tracehook(struct cli_bc_ctx *ctx, unsigned event) break; case trace_line: case trace_col: - if (dbg_state.showline) + if (dbg_state.showline) { cli_bytecode_debug_printsrc(ctx); - else + } else { fprintf(stderr, "[trace] %s:%u:%u\n", dbg_state.file, dbg_state.line, dbg_state.col); + } break; default: break; @@ -165,8 +167,9 @@ static void print_src(const char *file) } } } while (!found && (nread == sizeof(buf))); - if (debug_flag) + if (debug_flag) { printf("[clambc] Source code:"); + } do { for (; i + 1 < nread; i++) { if (buf[i] == 'S' || buf[i] == '\n') { @@ -176,8 +179,9 @@ static void print_src(const char *file) putc(((buf[i] & 0xf) | ((buf[i + 1] & 0xf) << 4)), stdout); i++; } - if (i == nread - 1 && nread != 1) + if (i == nread - 1 && nread != 1) { fseek(f, -1, SEEK_CUR); + } i = 0; nread = fread(buf, 1, sizeof(buf), f); } while (nread > 0); @@ -262,8 +266,9 @@ int main(int argc, char *argv[]) int fd = -1; unsigned tracelevel; - if (check_flevel()) + if (check_flevel()) { exit(1); + } opts = optparse(NULL, argc, argv, 1, OPT_CLAMBC, 0, NULL); if (!opts) { @@ -308,10 +313,13 @@ int main(int argc, char *argv[]) } dbgargc = 1; - while (opts->filename[dbgargc]) dbgargc++; + while (opts->filename[dbgargc]) { + dbgargc++; + } - if (dbgargc > 1) + if (dbgargc > 1) { cli_bytecode_debug(dbgargc, opts->filename); + } if (optget(opts, "force-interpreter")->enabled) { bcs.engine = NULL; @@ -329,8 +337,9 @@ int main(int argc, char *argv[]) if ((opt = optget(opts, "statistics"))->enabled) { while (opt) { - if (!strcasecmp(opt->strarg, "bytecode")) + if (!strcasecmp(opt->strarg, "bytecode")) { bc_stats = 1; + } opt = opt->nextarg; } } @@ -346,8 +355,9 @@ int main(int argc, char *argv[]) fprintf(stderr, "bytecode load skipped\n"); exit(0); } - if (debug_flag) + if (debug_flag) { printf("[clambc] Bytecode loaded\n"); + } if (optget(opts, "info")->enabled) { cli_bytecode_describe(bc); } else if (optget(opts, "printsrc")->enabled) { @@ -386,8 +396,9 @@ int main(int argc, char *argv[]) optfree(opts); exit(4); } - if (debug_flag) + if (debug_flag) { printf("[clambc] Bytecode prepared\n"); + } ctx = cli_bytecode_context_alloc(); if (!ctx) { @@ -428,8 +439,9 @@ int main(int argc, char *argv[]) funcid = atoi(opts->filename[1]); } cli_bytecode_context_setfuncid(ctx, bc, funcid); - if (debug_flag) + if (debug_flag) { printf("[clambc] Running bytecode function :%u\n", funcid); + } if (opts->filename[1]) { i = 2; @@ -469,15 +481,18 @@ int main(int argc, char *argv[]) fprintf(stderr, "Unable to run bytecode: %s\n", cl_strerror(rc)); } else { uint64_t v; - if (debug_flag) + if (debug_flag) { printf("[clambc] Bytecode run finished\n"); + } v = cli_bytecode_context_getresult_int(ctx); - if (debug_flag) + if (debug_flag) { printf("[clambc] Bytecode returned: 0x%llx\n", (long long)v); + } } cli_bytecode_context_destroy(ctx); - if (map) + if (map) { funmap(map); + } cl_engine_free(engine); free(cctx.recursion_stack); evidence_free(cctx.evidence); @@ -486,10 +501,12 @@ int main(int argc, char *argv[]) cli_bytecode_done(&bcs); free(bc); optfree(opts); - if (fd != -1) + if (fd != -1) { close(fd); - if (debug_flag) + } + if (debug_flag) { printf("[clambc] Exiting\n"); + } return 0; } diff --git a/clamconf/CMakeLists.txt b/clamconf/CMakeLists.txt index 9d48889c92..3fd5610998 100644 --- a/clamconf/CMakeLists.txt +++ b/clamconf/CMakeLists.txt @@ -23,6 +23,12 @@ target_include_directories( clamconf ) set_target_properties( clamconf PROPERTIES COMPILE_FLAGS "${WARNCFLAGS}" ) +if(CLANG_TIDY) + set_target_properties( clamconf PROPERTIES + C_CLANG_TIDY "${CLANG_TIDY_PROPERTY}" + C_CLANG_TIDY_EXPORT_FIXES_DIR "${CMAKE_BINARY_DIR}/clang-tidy-fixes" ) +endif() + if (APPLE AND CLAMAV_SIGN_FILE) set_target_properties( clamconf PROPERTIES XCODE_ATTRIBUTE_CODE_SIGN_IDENTITY ${CODE_SIGN_IDENTITY} diff --git a/clamconf/clamconf.c b/clamconf/clamconf.c index efe0d1454e..8639c5e0b7 100644 --- a/clamconf/clamconf.c +++ b/clamconf/clamconf.c @@ -78,8 +78,9 @@ static void printopts(struct optstruct *opts, int nondef) continue; } if (clam_options[opts->idx].owner & OPT_DEPRECATED) { - if (opts->active) + if (opts->active) { printf("*** %s is DEPRECATED ***\n", opts->name); + } opts = opts->next; continue; } @@ -87,15 +88,16 @@ static void printopts(struct optstruct *opts, int nondef) opts = opts->next; continue; } - if (!opts->enabled) + if (!opts->enabled) { printf("%s disabled\n", opts->name); - else + } else { switch (clam_options[opts->idx].argtype) { case CLOPT_TYPE_STRING: printf("%s = \"%s\"", opts->name, opts->strarg); opt = opts; - while ((opt = opt->nextarg)) + while ((opt = opt->nextarg)) { printf(", \"%s\"", opt->strarg); + } printf("\n"); break; @@ -104,8 +106,9 @@ static void printopts(struct optstruct *opts, int nondef) case CLOPT_TYPE_SIZE64: printf("%s = \"%lld\"", opts->name, opts->numarg); opt = opts; - while ((opt = opt->nextarg)) + while ((opt = opt->nextarg)) { printf(", \"%lld\"", opt->numarg); + } printf("\n"); break; @@ -116,6 +119,7 @@ static void printopts(struct optstruct *opts, int nondef) default: printf("!!! %s: UNKNOWN INTERNAL TYPE !!!\n", opts->name); } + } opts = opts->next; } } @@ -135,8 +139,9 @@ static int printconf(const char *name) } if (!tool) { printf("ERROR: Unknown config file\nAvailable options:"); - for (i = 0; cfgfile[i].name; i++) + for (i = 0; cfgfile[i].name; i++) { printf(" %s", cfgfile[i].name); + } printf("\n"); return 1; } @@ -151,38 +156,43 @@ static int printconf(const char *name) buffer[sizeof(buffer) - 1] = 0; tokens_count = cli_strtokenize(buffer, '\n', 128, tokens); printf("\n"); - for (j = 0; j < tokens_count; j++) + for (j = 0; j < tokens_count; j++) { printf("# %s\n", tokens[j]); + } switch (cpt->argtype) { case CLOPT_TYPE_STRING: - if (cpt->strarg) + if (cpt->strarg) { printf("# Default: %s\n", cpt->strarg); - else + } else { printf("# Default: disabled\n"); + } break; case CLOPT_TYPE_NUMBER: - if (cpt->numarg != -1) + if (cpt->numarg != -1) { printf("# Default: %lld\n", cpt->numarg); - else + } else { printf("# Default: disabled\n"); + } break; case CLOPT_TYPE_SIZE: case CLOPT_TYPE_SIZE64: printf("# You may use 'G' or 'g' for gigabytes (1G = 1g = 1,073,741,824 bytes)\n# 'M' or 'm' for megabytes (1M = 1m = 1048576 bytes)\n# and 'K' or 'k' for kilobytes (1K = 1k = 1024 bytes). To specify the size\n# in bytes just don't use modifiers.\n"); - if (cpt->numarg != -1) + if (cpt->numarg != -1) { printf("# Default: %lld\n", cpt->numarg); - else + } else { printf("# Default: disabled\n"); + } break; case CLOPT_TYPE_BOOL: - if (cpt->numarg != -1) + if (cpt->numarg != -1) { printf("# Default: %s\n", cpt->numarg ? "yes" : "no"); - else + } else { printf("# Default: disabled\n"); + } break; default: @@ -193,8 +203,9 @@ static int printconf(const char *name) strncpy(buffer, cpt->suggested, sizeof(buffer) - 1); buffer[sizeof(buffer) - 1] = 0; tokens_count = cli_strtokenize(buffer, '\n', 128, tokens); - for (j = 0; j < tokens_count; j++) + for (j = 0; j < tokens_count; j++) { printf("#%s %s\n", cpt->name, tokens[j]); + } } else { printf("#%s %s\n", cpt->name, cpt->suggested ? cpt->suggested : "ARG"); } @@ -250,8 +261,9 @@ static void print_platform(struct cli_environment *env) } #endif - if (strcmp(ZLIB_VERSION, zlibVersion())) + if (strcmp(ZLIB_VERSION, zlibVersion())) { printf("WARNING: zlib version mismatch: %s (%s)\n", ZLIB_VERSION, zlibVersion()); + } #ifdef ZLIB_VERNUM printf("zlib version: %s (%s), compile flags: %02lx\n", ZLIB_VERSION, zlibVersion(), zlibCompileFlags()); @@ -261,10 +273,12 @@ static void print_platform(struct cli_environment *env) ZLIB_VERSION, zlibVersion()); #endif - if (env->triple[0]) + if (env->triple[0]) { printf("Triple: %s\n", env->triple); - if (env->cpu[0]) + } + if (env->cpu[0]) { printf("CPU: %s, %s\n", env->cpu, env->big_endian ? "Big-endian" : "Little-endian"); + } printf("platform id: 0x%08x%08x%08x\n", env->platform_id_a, env->platform_id_b, @@ -302,13 +316,14 @@ static void print_build(struct cli_environment *env) default: name = NULL; } - if (name) + if (name) { printf("%s: %s%s(%u.%u.%u)\n", name, version ? version : "", version ? " " : "", env->c_version >> 16, (env->c_version >> 8) & 0xff, (env->c_version) & 0xff); + } cli_printcxxver(); #if defined(BUILD_CPPFLAGS) && defined(BUILD_CFLAGS) && defined(BUILD_CXXFLAGS) && defined(BUILD_LDFLAGS) && defined(BUILD_CONFIGURE_FLAGS) printf("CPPFLAGS: %s\nCFLAGS: %s\nCXXFLAGS: %s\nLDFLAGS: %s\nConfigure: %s\n", @@ -352,8 +367,9 @@ static void print_dbs(const char *dir) const time_t t = cvd->stime; printf("%s: version %u, sigs: %u, built on %s", dent->d_name, cvd->version, cvd->sigs, ctime(&t)); sigs += cvd->sigs; - if (cvd->fl > flevel) + if (cvd->fl > flevel) { printf("%s: WARNING: This database requires f-level %u (current f-level: %u)\n", dent->d_name, cvd->fl, flevel); + } cl_cvdfree(cvd); } } else if (cli_strbcasestr(dbfile, ".cbc")) { @@ -417,12 +433,14 @@ int main(int argc, char **argv) continue; } printf("\nConfig file: %s\n", cfgfile[i].name); - for (j = 0; j < strlen(cfgfile[i].name) + 13; j++) + for (j = 0; j < strlen(cfgfile[i].name) + 13; j++) { printf("-"); + } printf("\n"); toolopts = optparse(path, 0, NULL, 1, cfgfile[i].tool | OPT_DEPRECATED, 0, NULL); - if (!toolopts) + if (!toolopts) { continue; + } printopts(toolopts, optget(opts, "non-default")->enabled); if (cfgfile[i].tool == OPT_FRESHCLAM) { opt = optget(toolopts, "DatabaseDirectory"); @@ -439,8 +457,9 @@ int main(int argc, char **argv) printf("\nSoftware settings\n-----------------\n"); printf("Version: %s\n", cl_retver()); - if (strcmp(cl_retver(), get_version())) + if (strcmp(cl_retver(), get_version())) { printf("WARNING: Version mismatch: libclamav=%s, clamconf=%s\n", cl_retver(), get_version()); + } cl_init(CL_INIT_DEFAULT); printf("Optional features supported: "); #ifdef USE_MPOOL @@ -453,17 +472,20 @@ int main(int argc, char **argv) printf("FRESHCLAM_DNS_FIX "); #endif #ifndef _WIN32 - if (get_fpu_endian() != FPU_ENDIAN_UNKNOWN) + if (get_fpu_endian() != FPU_ENDIAN_UNKNOWN) { #endif printf("AUTOIT_EA06 "); + } #ifdef HAVE_ICONV printf("ICONV "); #endif - if (have_rar) + if (have_rar) { printf("RAR "); - if (have_clamjit()) + } + if (have_clamjit()) { printf("JIT"); + } printf("\n"); if (!strlen(dbdir)) { @@ -479,8 +501,9 @@ int main(int argc, char **argv) printf("\nDatabase information\n--------------------\n"); printf("Database directory: %s\n", dbdir); - if (strcmp(dbdir, clamd_dbdir)) + if (strcmp(dbdir, clamd_dbdir)) { printf("WARNING: freshclam.conf and clamd.conf point to different database directories\n"); + } print_dbs(dbdir); cli_detect_environment(&env); diff --git a/clamd/CMakeLists.txt b/clamd/CMakeLists.txt index 0ad1050652..0b45a743cc 100644 --- a/clamd/CMakeLists.txt +++ b/clamd/CMakeLists.txt @@ -41,6 +41,12 @@ target_include_directories( clamd ) set_target_properties( clamd PROPERTIES COMPILE_FLAGS "${WARNCFLAGS}" ) +if(CLANG_TIDY) + set_target_properties( clamd PROPERTIES + C_CLANG_TIDY "${CLANG_TIDY_PROPERTY}" + C_CLANG_TIDY_EXPORT_FIXES_DIR "${CMAKE_BINARY_DIR}/clang-tidy-fixes" ) +endif() + if (APPLE AND CLAMAV_SIGN_FILE) set_target_properties( clamd PROPERTIES XCODE_ATTRIBUTE_CODE_SIGN_IDENTITY ${CODE_SIGN_IDENTITY} diff --git a/clamd/clamd.c b/clamd/clamd.c index 4feeee82ba..1dccfeec1a 100644 --- a/clamd/clamd.c +++ b/clamd/clamd.c @@ -174,8 +174,9 @@ int main(int argc, char **argv) char *cvdcertsdir = NULL; STATBUF statbuf; - if (check_flevel()) + if (check_flevel()) { exit(1); + } #ifndef _WIN32 memset(&sa, 0, sizeof(sa)); @@ -202,8 +203,9 @@ int main(int argc, char **argv) #if defined(C_LINUX) /* njh@bandsman.co.uk: create a dump if needed */ rlim.rlim_cur = rlim.rlim_max = RLIM_INFINITY; - if (setrlimit(RLIMIT_CORE, &rlim) < 0) + if (setrlimit(RLIMIT_CORE, &rlim) < 0) { perror("setrlimit"); + } #endif debug_mode = 1; } @@ -256,8 +258,9 @@ int main(int argc, char **argv) logok = optget(opts, "LogClean")->enabled; logg_size = optget(opts, "LogFileMaxSize")->numarg; logg_verbose = mprintf_verbose = optget(opts, "LogVerbose")->enabled; - if (logg_size) + if (logg_size) { logg_rotate = optget(opts, "LogRotate")->enabled; + } mprintf_send_timeout = optget(opts, "SendBufTimeout")->numarg; if ((opt = optget(opts, "LogFile"))->enabled) { @@ -384,8 +387,9 @@ int main(int argc, char **argv) do { /* logger initialized */ - if (optget(opts, "DevLiblog")->enabled) + if (optget(opts, "DevLiblog")->enabled) { cl_set_clcb_msg(msg_callback); + } if ((ret = cl_init(CL_INIT_DEFAULT))) { logg(LOGG_ERROR, "Can't initialize libclamav: %s\n", cl_strerror(ret)); @@ -417,17 +421,20 @@ int main(int argc, char **argv) #ifdef C_LINUX procdev = 0; - if (CLAMSTAT("/proc", &sb) != -1 && !sb.st_size) + if (CLAMSTAT("/proc", &sb) != -1 && !sb.st_size) { procdev = sb.st_dev; + } #endif /* check socket type */ - if (optget(opts, "TCPSocket")->enabled) + if (optget(opts, "TCPSocket")->enabled) { tcpsock = 1; + } - if (optget(opts, "LocalSocket")->enabled) + if (optget(opts, "LocalSocket")->enabled) { localsock = 1; + } logg(LOGG_INFO_NF, "Received %d file descriptor(s) from systemd.\n", num_fd); @@ -440,8 +447,9 @@ int main(int argc, char **argv) logg(LOGG_INFO_NF, "clamd daemon %s (OS: " TARGET_OS_TYPE ", ARCH: " TARGET_ARCH_TYPE ", CPU: " TARGET_CPU_TYPE ")\n", get_version()); #ifndef _WIN32 - if (user) + if (user) { logg(LOGG_INFO_NF, "Running as user %s (UID %u, GID %u)\n", user->pw_name, user->pw_uid, user->pw_gid); + } #endif #if defined(RLIMIT_DATA) && defined(C_BSD) @@ -462,10 +470,11 @@ int main(int argc, char **argv) } #endif - if (logg_size) + if (logg_size) { logg(LOGG_INFO_NF, "Log file size limited to %lld bytes.\n", (long long int)logg_size); - else + } else { logg(LOGG_INFO_NF, "Log file size limit disabled.\n"); + } min_port = optget(opts, "StreamMinPort")->numarg; max_port = optget(opts, "StreamMaxPort")->numarg; @@ -481,10 +490,12 @@ int main(int argc, char **argv) break; } - if ((opt = optget(opts, "cache-size"))->enabled) + if ((opt = optget(opts, "cache-size"))->enabled) { cl_engine_set_num(engine, CL_ENGINE_CACHE_SIZE, opt->numarg); - if (optget(opts, "disable-cache")->enabled) + } + if (optget(opts, "disable-cache")->enabled) { cl_engine_set_num(engine, CL_ENGINE_DISABLE_CACHE, 1); + } /* load the database(s) */ dbdir = optget(opts, "DatabaseDirectory")->strarg; @@ -514,8 +525,9 @@ int main(int argc, char **argv) opt = opt->nextarg; } - if (ret) + if (ret) { break; + } logg(LOGG_INFO_NF, "\n"); pua_cats[i] = '.'; @@ -548,8 +560,9 @@ int main(int argc, char **argv) opt = opt->nextarg; } - if (ret) + if (ret) { break; + } logg(LOGG_INFO_NF, "\n"); pua_cats[i] = '.'; @@ -614,16 +627,19 @@ int main(int argc, char **argv) cl_engine_set_clcb_virus_found(engine, clamd_virus_found_cb); - if (optget(opts, "LeaveTemporaryFiles")->enabled) + if (optget(opts, "LeaveTemporaryFiles")->enabled) { cl_engine_set_num(engine, CL_ENGINE_KEEPTMP, 1); + } - if (optget(opts, "ForceToDisk")->enabled) + if (optget(opts, "ForceToDisk")->enabled) { cl_engine_set_num(engine, CL_ENGINE_FORCETODISK, 1); + } - if (optget(opts, "PhishingSignatures")->enabled) + if (optget(opts, "PhishingSignatures")->enabled) { dboptions |= CL_DB_PHISHING; - else + } else { logg(LOGG_INFO_NF, "Not loading phishing signatures.\n"); + } if (optget(opts, "Bytecode")->enabled) { dboptions |= CL_DB_BYTECODE; @@ -657,14 +673,15 @@ int main(int argc, char **argv) if ((opt = optget(opts, "BytecodeMode"))->enabled) { enum bytecode_mode mode; - if (!strcmp(opt->strarg, "ForceJIT")) + if (!strcmp(opt->strarg, "ForceJIT")) { mode = CL_BYTECODE_MODE_JIT; - else if (!strcmp(opt->strarg, "ForceInterpreter")) + } else if (!strcmp(opt->strarg, "ForceInterpreter")) { mode = CL_BYTECODE_MODE_INTERPRETER; - else if (!strcmp(opt->strarg, "Test")) + } else if (!strcmp(opt->strarg, "Test")) { mode = CL_BYTECODE_MODE_TEST; - else + } else { mode = CL_BYTECODE_MODE_AUTO; + } cl_engine_set_num(engine, CL_ENGINE_BYTECODE_MODE, mode); } @@ -675,10 +692,11 @@ int main(int argc, char **argv) logg(LOGG_INFO_NF, "Bytecode support disabled.\n"); } - if (optget(opts, "PhishingScanURLs")->enabled) + if (optget(opts, "PhishingScanURLs")->enabled) { dboptions |= CL_DB_PHISHING_URLS; - else + } else { logg(LOGG_INFO_NF, "Disabling URL based phishing detection.\n"); + } if (optget(opts, "DevACOnly")->enabled) { logg(LOGG_INFO_NF, "Only using the A-C matcher.\n"); @@ -715,8 +733,9 @@ int main(int argc, char **argv) break; } - if (optget(opts, "DisableCertCheck")->enabled) + if (optget(opts, "DisableCertCheck")->enabled) { cl_engine_set_num(engine, CL_ENGINE_DISABLE_PE_CERTS, 1); + } logg(LOGG_INFO_NF, "Loaded %u signatures.\n", sigs); @@ -760,8 +779,9 @@ int main(int argc, char **argv) opt = opt->nextarg; } - if (breakout) + if (breakout) { break; + } } else { if (tcpserver(&lsockets, &nlsockets, NULL, opts) == -1) { ret = 1; @@ -898,10 +918,11 @@ int main(int argc, char **argv) if (nlsockets && localsock) { opt = optget(opts, "LocalSocket"); - if (unlink(opt->strarg) == -1) + if (unlink(opt->strarg) == -1) { logg(LOGG_ERROR, "Can't unlink the socket file %s\n", opt->strarg); - else + } else { logg(LOGG_INFO, "Socket file removed.\n"); + } } #endif } diff --git a/clamd/clamd_others.c b/clamd/clamd_others.c index 9cb477eddf..8eb1b82d57 100644 --- a/clamd/clamd_others.c +++ b/clamd/clamd_others.c @@ -84,8 +84,9 @@ static pthread_mutex_t virusaction_lock = PTHREAD_MUTEX_INITIALIZER; static void xfree(void *p) { - if (p) + if (p) { free(p); + } } #ifdef _WIN32 @@ -113,8 +114,9 @@ void virusaction(const char *filename, const char *virname, size_t i, j, v = 0, f = 0, len; char *env[4]; - if (!(opt = optget(opts, "VirusEvent"))->enabled) + if (!(opt = optget(opts, "VirusEvent"))->enabled) { return; + } path = getenv("PATH"); env[0] = path ? strdup(path) : NULL; @@ -149,8 +151,9 @@ void virusaction(const char *filename, const char *virname, buffer_cmd = (char *)calloc(len + v * strlen(virname) + f * strlen(FILENAME_DISABLED_MESSAGE) + 1, sizeof(char)); if (!buffer_cmd) { - if (path) + if (path) { xfree(env[0]); + } xfree(buffer_file); xfree(buffer_vir); @@ -177,13 +180,16 @@ void virusaction(const char *filename, const char *virname, _exit(execle("/bin/sh", "sh", "-c", buffer_cmd, NULL, env)); } else if (pid > 0) { /* parent */ pthread_mutex_unlock(&virusaction_lock); - while (waitpid(pid, NULL, 0) == -1 && errno == EINTR) continue; + while (waitpid(pid, NULL, 0) == -1 && errno == EINTR) { + continue; + } } else { pthread_mutex_unlock(&virusaction_lock); logg(LOGG_ERROR, "VirusEvent: fork failed.\n"); } - if (path) + if (path) { xfree(env[0]); + } xfree(buffer_cmd); xfree(buffer_file); @@ -222,10 +228,12 @@ static int realloc_polldata(struct fd_data *data) { #ifdef HAVE_POLL - if (data->poll_data_nfds == data->nfds) + if (data->poll_data_nfds == data->nfds) { return 0; - if (data->poll_data) + } + if (data->poll_data) { free(data->poll_data); + } data->poll_data = malloc(data->nfds * sizeof(*data->poll_data)); if (!data->poll_data) { logg(LOGG_ERROR, "realloc_polldata: Memory allocation failed for poll_data\n"); @@ -241,8 +249,9 @@ int poll_fd(int fd, int timeout_sec, int check_signals) int ret; struct fd_data fds = FDS_INIT(NULL); - if (fds_add(&fds, fd, 1, timeout_sec) == -1) + if (fds_add(&fds, fd, 1, timeout_sec) == -1) { return -1; + } do { ret = fds_poll_recv(&fds, timeout_sec, check_signals, NULL); } while (ret == -1 && errno == EINTR); @@ -257,27 +266,32 @@ void fds_cleanup(struct fd_data *data) for (i = 0, j = 0; i < data->nfds; i++) { if (data->buf[i].fd < 0) { - if (data->buf[i].buffer) + if (data->buf[i].buffer) { free(data->buf[i].buffer); + } continue; } - if (i != j) + if (i != j) { data->buf[j] = data->buf[i]; + } j++; } - if (j == data->nfds) + if (j == data->nfds) { return; - for (i = j; i < data->nfds; i++) + } + for (i = j; i < data->nfds; i++) { data->buf[i].fd = -1; + } data->nfds = j; logg(LOGG_DEBUG_NV, "Number of file descriptors polled: %u fds\n", (unsigned)data->nfds); /* Shrink buffer */ newbuf = realloc(data->buf, j * sizeof(*newbuf)); - if (!j) + if (!j) { data->buf = NULL; - else if (newbuf) + } else if (newbuf) { data->buf = newbuf; /* non-fatal if shrink fails */ + } } static int @@ -286,16 +300,18 @@ read_fd_data(struct fd_buf *buf) ssize_t n; buf->got_newdata = 1; - if (!buf->buffer) /* listen-only socket */ + if (!buf->buffer) { /* listen-only socket */ return 1; + } - if (buf->off >= buf->bufsize) + if (buf->off >= buf->bufsize) { return -1; + } - /* Read the pending packet, it may contain more than one command, but - * that is to the cmdparser to handle. - * It will handle 1st command, and then move leftover to beginning of buffer - */ + /* Read the pending packet, it may contain more than one command, but + * that is to the cmdparser to handle. + * It will handle 1st command, and then move leftover to beginning of buffer + */ #ifdef HAVE_FD_PASSING { struct msghdr msg; @@ -320,22 +336,24 @@ read_fd_data(struct fd_buf *buf) msg.msg_controllen = sizeof(b.buff); n = recvmsg(buf->fd, &msg, 0); - if (n < 0) + if (n < 0) { return -1; + } if (msg.msg_flags & MSG_TRUNC) { logg(LOGG_WARNING, "Message truncated at %d bytes\n", (int)n); return -1; } if (msg.msg_flags & MSG_CTRUNC) { - if (msg.msg_controllen > 0) + if (msg.msg_controllen > 0) { logg(LOGG_WARNING, "Control message truncated at %d bytes, %d data read\n", (int)msg.msg_controllen, (int)n); - else + } else { logg(LOGG_WARNING, "Control message truncated, no control data received, %d bytes read" #ifdef C_LINUX "(Is SELinux/AppArmor enabled, and blocking file descriptor passing?)" #endif "\n", (int)n); + } return -1; } if (msg.msg_controllen) { @@ -388,8 +406,9 @@ buf_init(struct fd_buf *buf, int listen_only, int timeout) } } } else { - if (buf->buffer) + if (buf->buffer) { free(buf->buffer); + } buf->bufsize = 0; buf->buffer = NULL; } @@ -412,13 +431,15 @@ int fds_add(struct fd_data *data, int fd, int listen_only, int timeout) } /* we may already have this fd, if * the old FD got closed, and the kernel reused the FD */ - for (n = 0; n < data->nfds; n++) + for (n = 0; n < data->nfds; n++) { if (data->buf[n].fd == fd) { /* clear stale data in buffer */ - if (buf_init(&data->buf[n], listen_only, timeout) < 0) + if (buf_init(&data->buf[n], listen_only, timeout) < 0) { return -1; + } return 0; } + } n++; buf = realloc(data->buf, n * sizeof(*buf)); @@ -429,8 +450,9 @@ int fds_add(struct fd_data *data, int fd, int listen_only, int timeout) data->buf = buf; data->nfds = n; data->buf[n - 1].buffer = NULL; - if (buf_init(&data->buf[n - 1], listen_only, timeout) < 0) + if (buf_init(&data->buf[n - 1], listen_only, timeout) < 0) { return -1; + } data->buf[n - 1].fd = fd; return 0; } @@ -438,15 +460,17 @@ int fds_add(struct fd_data *data, int fd, int listen_only, int timeout) static inline void fds_lock(struct fd_data *data) { - if (data->buf_mutex) + if (data->buf_mutex) { pthread_mutex_lock(data->buf_mutex); + } } static inline void fds_unlock(struct fd_data *data) { - if (data->buf_mutex) + if (data->buf_mutex) { pthread_mutex_unlock(data->buf_mutex); + } } void fds_remove(struct fd_data *data, int fd) @@ -487,18 +511,20 @@ int fds_poll_recv(struct fd_data *data, int timeout, int check_signals, /* we must have at least one fd, the control fd! */ fds_cleanup(data); #ifndef _WIN32 - if (!data->nfds) + if (!data->nfds) { return 0; + } #endif for (i = 0; i < data->nfds; i++) { data->buf[i].got_newdata = 0; } time(&now); - if (timeout > 0) + if (timeout > 0) { closest_timeout = now + timeout; - else + } else { closest_timeout = 0; + } for (i = 0; i < data->nfds; i++) { time_t timeout_at = data->buf[i].timeout_at; if (timeout_at && timeout_at < now) { @@ -507,18 +533,21 @@ int fds_poll_recv(struct fd_data *data, int timeout, int check_signals, /* we must return immediately from poll/select, we have a timeout! */ closest_timeout = now; } else { - if (!closest_timeout) + if (!closest_timeout) { closest_timeout = timeout_at; - else if (timeout_at && timeout_at < closest_timeout) + } else if (timeout_at && timeout_at < closest_timeout) { closest_timeout = timeout_at; + } } } - if (closest_timeout) + if (closest_timeout) { timeout = closest_timeout - now; - else + } else { timeout = -1; - if (timeout > 0) + } + if (timeout > 0) { logg(LOGG_DEBUG_NV, "fds_poll_recv: timeout after %d seconds\n", timeout); + } #ifdef HAVE_POLL /* Use poll() if available, preferred because: * - can poll any number of FDs @@ -528,8 +557,9 @@ int fds_poll_recv(struct fd_data *data, int timeout, int check_signals, * recv() may still block according to the manpage */ - if (realloc_polldata(data) == -1) + if (realloc_polldata(data) == -1) { return -1; + } if (timeout > 0) { /* seconds to ms */ timeout *= 1000; @@ -556,8 +586,9 @@ int fds_poll_recv(struct fd_data *data, int timeout, int check_signals, * poll_data_nfds */ for (i = 0; i < data->poll_data_nfds; i++) { short revents; - if (data->buf[i].fd < 0) + if (data->buf[i].fd < 0) { continue; + } if (data->buf[i].fd != data->poll_data[i].fd) { /* should never happen */ logg(LOGG_ERROR, "poll_recv_fds FD mismatch\n"); @@ -572,17 +603,19 @@ int fds_poll_recv(struct fd_data *data, int timeout, int check_signals, if (revents & POLLHUP) { /* avoid SHUT_WR problem on Mac OS X */ int ret = send(data->poll_data[i].fd, &n, 0, 0); - if (!ret || (ret == -1 && errno == EINTR)) + if (!ret || (ret == -1 && errno == EINTR)) { revents &= ~POLLHUP; + } } #endif if (revents & POLLIN) { int ret = read_fd_data(&data->buf[i]); /* Data available to be read */ - if (ret == -1) + if (ret == -1) { revents |= POLLERR; - else if (!ret) + } else if (!ret) { revents = POLLHUP; + } } if (revents & (POLLHUP | POLLERR | POLLNVAL)) { @@ -711,11 +744,13 @@ void fds_free(struct fd_data *data) free(data->buf[i].buffer); } } - if (data->buf) + if (data->buf) { free(data->buf); + } #ifdef HAVE_POLL - if (data->poll_data) + if (data->poll_data) { free(data->poll_data); + } #endif data->buf = NULL; data->nfds = 0; diff --git a/clamd/scanner.c b/clamd/scanner.c index 50e18bc1fd..247815cf92 100644 --- a/clamd/scanner.c +++ b/clamd/scanner.c @@ -100,8 +100,9 @@ void hash_callback(int fd, unsigned long long size, const unsigned char *md5, co UNUSEDPARAM(fd); UNUSEDPARAM(virname); - if (!c) + if (!c) { return; + } c->virsize = size; strncpy(c->virhash, (const char *)md5, 32); c->virhash[32] = '\0'; @@ -115,20 +116,24 @@ void clamd_virus_found_cb(int fd, const char *virname, void *ctx) UNUSEDPARAM(fd); - if (d == NULL) + if (d == NULL) { return; - if (!(d->options->general & CL_SCAN_GENERAL_ALLMATCHES) && !(d->options->general & CL_SCAN_GENERAL_HEURISTIC_PRECEDENCE)) + } + if (!(d->options->general & CL_SCAN_GENERAL_ALLMATCHES) && !(d->options->general & CL_SCAN_GENERAL_HEURISTIC_PRECEDENCE)) { return; - if (virname == NULL) + } + if (virname == NULL) { return; + } fname = (c && c->filename) ? c->filename : "(filename not set)"; if (virname) { d->infected++; conn_reply_virus(d->conn, fname, virname); - if (c->virsize > 0 && optget(d->opts, "ExtendedDetectionInfo")->enabled) + if (c->virsize > 0 && optget(d->opts, "ExtendedDetectionInfo")->enabled) { logg(LOGG_INFO, "%s: %s(%s:%llu) FOUND\n", fname, virname, c->virhash, c->virsize); + } logg(LOGG_INFO, "%s: %s FOUND\n", fname, virname); } @@ -161,25 +166,28 @@ cl_error_t scan_callback(STATBUF *sb, char *filename, const char *msg, enum cli_ if (send(scandata->conn->sd, &ret, 0, 0) == -1 && errno != EINTR) { logg(LOGG_DEBUG_NV, "Client disconnected while command was active!\n"); thrmgr_group_terminate(scandata->conn->group); - if (reason == visit_file) + if (reason == visit_file) { free(filename); + } return CL_BREAK; } if (thrmgr_group_need_terminate(scandata->conn->group)) { logg(LOGG_WARNING, "Client disconnected while scanjob was active\n"); - if (reason == visit_file) + if (reason == visit_file) { free(filename); + } return CL_BREAK; } scandata->total++; switch (reason) { case error_mem: - if (msg) + if (msg) { logg(LOGG_ERROR, "Memory allocation failed during cli_ftw() on %s\n", msg); - else + } else { logg(LOGG_ERROR, "Memory allocation failed during cli_ftw()\n"); + } scandata->errors++; free(filename); return CL_EMEM; @@ -198,8 +206,9 @@ cl_error_t scan_callback(STATBUF *sb, char *filename, const char *msg, enum cli_ free(filename); return CL_SUCCESS; case warning_skipped_special: - if (msg == scandata->toplevel_path) + if (msg == scandata->toplevel_path) { conn_reply(scandata->conn, msg, "Not supported file type", "ERROR"); + } logg(LOGG_DEBUG, "Not supported file type: %s\n", msg); free(filename); return CL_SUCCESS; @@ -219,8 +228,9 @@ cl_error_t scan_callback(STATBUF *sb, char *filename, const char *msg, enum cli_ #endif if (sb && sb->st_size == 0) { /* empty file */ - if (msg == scandata->toplevel_path) + if (msg == scandata->toplevel_path) { conn_reply_single(scandata->conn, filename, "Empty file"); + } free(filename); return CL_SUCCESS; } @@ -310,10 +320,11 @@ cl_error_t scan_callback(STATBUF *sb, char *filename, const char *msg, enum cli_ prelude_logging(filename, virname, context.virhash, context.virsize); } - if (context.virsize && optget(scandata->opts, "ExtendedDetectionInfo")->enabled) + if (context.virsize && optget(scandata->opts, "ExtendedDetectionInfo")->enabled) { logg(LOGG_INFO, "%s: %s(%s:%llu) FOUND\n", filename, virname, context.virhash, context.virsize); - else + } else { logg(LOGG_INFO, "%s: %s FOUND\n", filename, virname); + } } } else if (ret != CL_CLEAN) { scandata->errors++; @@ -328,8 +339,9 @@ cl_error_t scan_callback(STATBUF *sb, char *filename, const char *msg, enum cli_ free(filename); - if (ret == CL_EMEM) /* stop scanning */ + if (ret == CL_EMEM) { /* stop scanning */ return ret; + } if (type == TYPE_SCAN) { /* virus -> break */ @@ -349,8 +361,9 @@ int scan_pathchk(const char *path, struct cli_ftw_cbdata *data) if ((opt = optget(scandata->opts, "ExcludePath"))->enabled) { while (opt) { if (match_regex(path, opt->strarg) == 1) { - if (scandata->type != TYPE_MULTISCAN) + if (scandata->type != TYPE_MULTISCAN) { conn_reply_single(scandata->conn, path, "Excluded"); + } return 1; } opt = (const struct optstruct *)opt->nextarg; @@ -360,8 +373,9 @@ int scan_pathchk(const char *path, struct cli_ftw_cbdata *data) if (!optget(scandata->opts, "CrossFilesystems")->enabled) { if (CLAMSTAT(path, &statbuf) == 0) { if (statbuf.st_dev != scandata->dev) { - if (scandata->type != TYPE_MULTISCAN) + if (scandata->type != TYPE_MULTISCAN) { conn_reply_single(scandata->conn, path, "Excluded (another filesystem)"); + } return 1; } } @@ -395,10 +409,11 @@ cl_error_t scanfd( if (stream) { struct sockaddr_in sa; socklen_t salen = sizeof(sa); - if (getpeername(conn->sd, (struct sockaddr *)&sa, &salen) || salen > sizeof(sa) || sa.sin_family != AF_INET) + if (getpeername(conn->sd, (struct sockaddr *)&sa, &salen) || salen > sizeof(sa) || sa.sin_family != AF_INET) { strncpy(fdstr, "instream(local)", sizeof(fdstr)); - else + } else { snprintf(fdstr, sizeof(fdstr), "instream(%s@%u)", inet_ntoa(sa.sin_addr), ntohs(sa.sin_port)); + } reply_fdstr = "stream"; } else { snprintf(fdstr, sizeof(fdstr), "fd[%d]", fd); @@ -438,21 +453,26 @@ cl_error_t scanfd( if (ret == CL_VIRUS) { virusaction(log_filename, virname, opts); - if (conn_reply_virus(conn, reply_fdstr, virname) == -1) + if (conn_reply_virus(conn, reply_fdstr, virname) == -1) { ret = CL_ETIMEOUT; - if (context.virsize && optget(opts, "ExtendedDetectionInfo")->enabled) + } + if (context.virsize && optget(opts, "ExtendedDetectionInfo")->enabled) { logg(LOGG_INFO, "%s: %s(%s:%llu) FOUND\n", log_filename, virname, context.virhash, context.virsize); - else + } else { logg(LOGG_INFO, "%s: %s FOUND\n", log_filename, virname); + } } else if (ret != CL_CLEAN) { - if (conn_reply(conn, reply_fdstr, cl_strerror(ret), "ERROR") == -1) + if (conn_reply(conn, reply_fdstr, cl_strerror(ret), "ERROR") == -1) { ret = CL_ETIMEOUT; + } logg(LOGG_INFO, "%s: %s ERROR\n", log_filename, cl_strerror(ret)); } else { - if (conn_reply_single(conn, reply_fdstr, "OK") == CL_ETIMEOUT) + if (conn_reply_single(conn, reply_fdstr, "OK") == CL_ETIMEOUT) { ret = CL_ETIMEOUT; - if (logok) + } + if (logok) { logg(LOGG_INFO, "%s: OK\n", log_filename); + } } done: @@ -499,12 +519,13 @@ int scanstream( server.sin_port = htons(min_port + port); server.sin_addr.s_addr = htonl(INADDR_ANY); - if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) + if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) { continue; + } - if (bind(sockfd, (struct sockaddr *)&server, (socklen_t)sizeof(struct sockaddr_in)) == -1) + if (bind(sockfd, (struct sockaddr *)&server, (socklen_t)sizeof(struct sockaddr_in)) == -1) { closesocket(sockfd); - else { + } else { bound = 1; break; } @@ -571,8 +592,9 @@ int scanstream( break; /* Scan what we have */ } bread = recv(acceptd, buff, btread, 0); - if (bread <= 0) + if (bread <= 0) { break; + } quota -= bread; @@ -583,8 +605,9 @@ int scanstream( mdprintf(odesc, "Temporary file -> write ERROR%c", term); logg(LOGG_ERROR, "ScanStream(%s@%u): Can't write to temporary file.\n", peer_addr, port); close(tmpd); - if (!optget(opts, "LeaveTemporaryFiles")->enabled) + if (!optget(opts, "LeaveTemporaryFiles")->enabled) { unlink(tmpname); + } free(tmpname); return -1; } @@ -613,8 +636,9 @@ int scanstream( ret = -1; } close(tmpd); - if (!optget(opts, "LeaveTemporaryFiles")->enabled) + if (!optget(opts, "LeaveTemporaryFiles")->enabled) { unlink(tmpname); + } free(tmpname); closesocket(acceptd); @@ -636,8 +660,9 @@ int scanstream( } } else { mdprintf(odesc, "stream: OK%c", term); - if (logok) + if (logok) { logg(LOGG_INFO, "stream(%s@%u): OK\n", peer_addr, port); + } } return ret; diff --git a/clamd/server-th.c b/clamd/server-th.c index 486103fbd1..152b2b4bd6 100644 --- a/clamd/server-th.c +++ b/clamd/server-th.c @@ -130,13 +130,15 @@ static void scanner_thread(void *arg) progexit = 1; pthread_mutex_unlock(&exit_mutex); errors = 1; - } else + } else { errors = ret; + } thrmgr_setactiveengine(NULL); - if (conn->filename) + if (conn->filename) { free(conn->filename); + } logg(LOGG_DEBUG_NV, "Finished scanthread\n"); enum thrmgr_exit exit_code; if (virus != 0) { @@ -187,9 +189,11 @@ void sighandler_th(int sig) break; /* Take no action on other signals - e.g. SIGPIPE */ } /* a signal doesn't always wake poll(), for example on FreeBSD */ - if (action && syncpipe_wake_recv_w != -1) - if (write(syncpipe_wake_recv_w, "", 1) != 1) + if (action && syncpipe_wake_recv_w != -1) { + if (write(syncpipe_wake_recv_w, "", 1) != 1) { logg(LOGG_DEBUG_NV, "Failed to write to syncpipe\n"); + } + } } static int need_db_reload(void) @@ -285,9 +289,11 @@ static void *reload_th(void *arg) #ifdef _WIN32 SetEvent(event_wake_recv); #else - if (syncpipe_wake_recv_w != -1) - if (write(syncpipe_wake_recv_w, "", 1) != 1) + if (syncpipe_wake_recv_w != -1) { + if (write(syncpipe_wake_recv_w, "", 1) != 1) { logg(LOGG_DEBUG_NV, "Failed to write to syncpipe\n"); + } + } #endif return NULL; @@ -377,8 +383,9 @@ static cl_error_t reload_db(struct cl_engine **engine, unsigned int dboptions, c } retval = pthread_create(&th, &th_attr, reload_th, rldata); - if (pthread_attr_destroy(&th_attr)) + if (pthread_attr_destroy(&th_attr)) { logg(LOGG_WARNING, "Failed to release reload thread attributes\n"); + } if (retval) { logg(LOGG_ERROR, "Failed to spawn reload thread\n"); goto done; @@ -470,8 +477,9 @@ static const char *get_cmd(struct fd_buf *buf, size_t off, size_t *len, char *te return buf->buffer + off + 1; default: /* one packet = one command */ - if (off) + if (off) { return NULL; + } pos = memchr(buf->buffer, '\n', buf->off); if (pos) { *len = pos - buf->buffer; @@ -548,8 +556,9 @@ static void *acceptloop_th(void *arg) /* accept() loop */ for (i = 0; i < fds->nfds && new_sd >= 0; i++) { struct fd_buf *buf = &fds->buf[i]; - if (!buf->got_newdata) + if (!buf->got_newdata) { continue; + } #ifndef _WIN32 if (buf->fd == data->syncpipe_wake_accept[0]) { /* dummy sync pipe, just to wake us */ @@ -647,8 +656,9 @@ static void *acceptloop_th(void *arg) if (sd_listen_fds(0) == 0) { /* only close the sockets, when not using systemd socket activation */ for (i = 0; i < fds->nfds; i++) { - if (fds->buf[i].fd == -1) + if (fds->buf[i].fd == -1) { continue; + } logg(LOGG_DEBUG_NV, "Shutdown: closed fd %d\n", fds->buf[i].fd); shutdown(fds->buf[i].fd, 2); closesocket(fds->buf[i].fd); @@ -797,12 +807,14 @@ static const char *parse_dispatch_cmd(client_conn_t *conn, struct fd_buf *buf, s if (pos < buf->off) { memmove(buf->buffer, &buf->buffer[pos], buf->off - pos); buf->off -= pos; - } else + } else { buf->off = 0; - if (buf->off) + } + if (buf->off) { logg(LOGG_DEBUG_NV, "Moved partial command: %lu\n", (unsigned long)buf->off); - else + } else { logg(LOGG_DEBUG_NV, "Consumed entire command\n"); + } /* adjust pos to account for the buffer shuffle */ pos = 0; } @@ -836,8 +848,9 @@ static int handle_stream(client_conn_t *conn, struct fd_buf *buf, const struct o conn->term = buf->term; buf->dumpfd = -1; buf->mode = buf->group ? MODE_COMMAND : MODE_WAITREPLY; - if (buf->mode == MODE_WAITREPLY) + if (buf->mode == MODE_WAITREPLY) { buf->fd = -1; + } logg(LOGG_DEBUG_NV, "Chunks complete\n"); buf->dumpname = NULL; if ((rc = execute_or_dispatch_command(conn, COMMAND_INSTREAMSCAN, NULL)) < 0) { @@ -875,10 +888,11 @@ static int handle_stream(client_conn_t *conn, struct fd_buf *buf, const struct o return -1; } } - if (pos + buf->chunksize < buf->off) + if (pos + buf->chunksize < buf->off) { cmdlen = buf->chunksize; - else + } else { cmdlen = buf->off - pos; + } buf->chunksize -= cmdlen; if (cli_writen(buf->dumpfd, buf->buffer + pos, cmdlen) == (size_t)-1) { conn_reply_error(conn, "Error writing to temporary file"); @@ -939,10 +953,11 @@ int recvloop(int *socketds, unsigned nsockets, struct cl_engine *engine, unsigne } } val = cl_engine_get_num(engine, CL_ENGINE_MAX_SCANTIME, NULL); - if (val) + if (val) { logg(LOGG_INFO, "Limits: Global time limit set to %llu milliseconds.\n", val); - else + } else { logg(LOGG_WARNING, "Limits: Global time limit protection disabled.\n"); + } if ((opt = optget(opts, "MaxScanSize"))->active) { if ((ret = cl_engine_set_num(engine, CL_ENGINE_MAX_SCANSIZE, opt->numarg))) { @@ -952,10 +967,11 @@ int recvloop(int *socketds, unsigned nsockets, struct cl_engine *engine, unsigne } } val = cl_engine_get_num(engine, CL_ENGINE_MAX_SCANSIZE, NULL); - if (val) + if (val) { logg(LOGG_INFO, "Limits: Global size limit set to %llu bytes.\n", val); - else + } else { logg(LOGG_WARNING, "Limits: Global size limit protection disabled.\n"); + } if ((opt = optget(opts, "MaxFileSize"))->active) { if ((ret = cl_engine_set_num(engine, CL_ENGINE_MAX_FILESIZE, opt->numarg))) { @@ -965,17 +981,20 @@ int recvloop(int *socketds, unsigned nsockets, struct cl_engine *engine, unsigne } } val = cl_engine_get_num(engine, CL_ENGINE_MAX_FILESIZE, NULL); - if (val) + if (val) { logg(LOGG_INFO, "Limits: File size limit set to %llu bytes.\n", val); - else + } else { logg(LOGG_WARNING, "Limits: File size limit protection disabled.\n"); + } #ifndef _WIN32 if (getrlimit(RLIMIT_FSIZE, &rlim) == 0) { - if (rlim.rlim_cur < (rlim_t)cl_engine_get_num(engine, CL_ENGINE_MAX_FILESIZE, NULL)) + if (rlim.rlim_cur < (rlim_t)cl_engine_get_num(engine, CL_ENGINE_MAX_FILESIZE, NULL)) { logg(LOGG_WARNING, "System limit for file size is lower than engine->maxfilesize\n"); - if (rlim.rlim_cur < (rlim_t)cl_engine_get_num(engine, CL_ENGINE_MAX_SCANSIZE, NULL)) + } + if (rlim.rlim_cur < (rlim_t)cl_engine_get_num(engine, CL_ENGINE_MAX_SCANSIZE, NULL)) { logg(LOGG_WARNING, "System limit for file size is lower than engine->maxscansize\n"); + } } else { logg(LOGG_WARNING, "Cannot obtain resource limits for file size\n"); } @@ -995,10 +1014,11 @@ int recvloop(int *socketds, unsigned nsockets, struct cl_engine *engine, unsigne } } val = cl_engine_get_num(engine, CL_ENGINE_MAX_RECURSION, NULL); - if (val) + if (val) { logg(LOGG_INFO, "Limits: Recursion level limit set to %u.\n", (unsigned int)val); - else + } else { logg(LOGG_WARNING, "Limits: Recursion level limit protection disabled.\n"); + } if ((opt = optget(opts, "MaxFiles"))->active) { if ((ret = cl_engine_set_num(engine, CL_ENGINE_MAX_FILES, opt->numarg))) { @@ -1008,10 +1028,11 @@ int recvloop(int *socketds, unsigned nsockets, struct cl_engine *engine, unsigne } } val = cl_engine_get_num(engine, CL_ENGINE_MAX_FILES, NULL); - if (val) + if (val) { logg(LOGG_INFO, "Limits: Files limit set to %u.\n", (unsigned int)val); - else + } else { logg(LOGG_WARNING, "Limits: Files limit protection disabled.\n"); + } #ifndef _WIN32 if (getrlimit(RLIMIT_CORE, &rlim) == 0) { @@ -1359,8 +1380,9 @@ int recvloop(int *socketds, unsigned nsockets, struct cl_engine *engine, unsigne val = cl_engine_get_num(engine, CL_ENGINE_MIN_CC_COUNT, NULL); logg(LOGG_INFO, "Structured: Minimum Credit Card Number Count set to %u\n", (unsigned int)val); - if (optget(opts, "StructuredCCOnly")->enabled) + if (optget(opts, "StructuredCCOnly")->enabled) { options.heuristic |= CL_SCAN_HEURISTIC_STRUCTURED_CC; + } if ((opt = optget(opts, "StructuredMinSSNCount"))->enabled) { if ((ret = cl_engine_set_num(engine, CL_ENGINE_MIN_SSN_COUNT, opt->numarg))) { @@ -1372,11 +1394,13 @@ int recvloop(int *socketds, unsigned nsockets, struct cl_engine *engine, unsigne val = cl_engine_get_num(engine, CL_ENGINE_MIN_SSN_COUNT, NULL); logg(LOGG_INFO, "Structured: Minimum Social Security Number Count set to %u\n", (unsigned int)val); - if (optget(opts, "StructuredSSNFormatNormal")->enabled) + if (optget(opts, "StructuredSSNFormatNormal")->enabled) { options.heuristic |= CL_SCAN_HEURISTIC_STRUCTURED_SSN_NORMAL; + } - if (optget(opts, "StructuredSSNFormatStripped")->enabled) + if (optget(opts, "StructuredSSNFormatStripped")->enabled) { options.heuristic |= CL_SCAN_HEURISTIC_STRUCTURED_SSN_STRIPPED; + } } #ifdef HAVE__INTERNAL__SHA_COLLECT @@ -1385,8 +1409,9 @@ int recvloop(int *socketds, unsigned nsockets, struct cl_engine *engine, unsigne #endif /* JSON check to prevent engine loading if specified without libjson-c */ - if (optget(opts, "GenerateMetadataJson")->enabled) + if (optget(opts, "GenerateMetadataJson")->enabled) { options.general |= CL_SCAN_GENERAL_COLLECT_METADATA; + } selfchk = optget(opts, "SelfCheck")->numarg; if (!selfchk) { @@ -1464,8 +1489,9 @@ int recvloop(int *socketds, unsigned nsockets, struct cl_engine *engine, unsigne max_max_queue = rlim.rlim_cur - maxrec * max_threads - clamdfiles + max_threads; if (max_queue < max_threads) { max_queue = max_threads; - if (warn) + if (warn) { logg(LOGG_WARNING, "MaxQueue value too low, increasing to: %d\n", max_queue); + } } if (max_max_queue < max_threads) { logg(LOGG_WARNING, "MaxThreads * MaxRecursion is too high: %d, open file descriptor limit is: %lu\n", @@ -1474,12 +1500,14 @@ int recvloop(int *socketds, unsigned nsockets, struct cl_engine *engine, unsigne } if (max_queue > max_max_queue) { max_queue = max_max_queue; - if (warn) + if (warn) { logg(LOGG_WARNING, "MaxQueue value too high, lowering to: %d\n", max_queue); + } } else if (max_queue < 2 * max_threads && max_queue < max_max_queue) { max_queue = 2 * max_threads; - if (max_queue > max_max_queue) + if (max_queue > max_max_queue) { max_queue = max_max_queue; + } /* always warn here */ logg(LOGG_WARNING, "MaxQueue is lower than twice MaxThreads, increasing to: %d\n", max_queue); } @@ -1526,12 +1554,13 @@ int recvloop(int *socketds, unsigned nsockets, struct cl_engine *engine, unsigne idletimeout = optget(opts, "IdleTimeout")->numarg; - for (i = 0; i < nsockets; i++) + for (i = 0; i < nsockets; i++) { if (fds_add(&acceptdata.fds, socketds[i], 1, 0) == -1) { logg(LOGG_ERROR, "fds_add failed\n"); cl_engine_free(engine); return 1; } + } #ifdef _WIN32 event_wake_accept = CreateEvent(NULL, TRUE, FALSE, NULL); event_wake_recv = CreateEvent(NULL, TRUE, FALSE, NULL); @@ -1569,8 +1598,9 @@ int recvloop(int *socketds, unsigned nsockets, struct cl_engine *engine, unsigne pthread_mutex_lock(fds->buf_mutex); fds_cleanup(fds); /* signal that we can accept more connections */ - if (fds->nfds <= (unsigned)max_queue) + if (fds->nfds <= (unsigned)max_queue) { pthread_cond_signal(&acceptdata.cond_nfds); + } new_sd = fds_poll_recv(fds, selfchk ? (int)selfchk : -1, 1, event_wake_recv); #ifdef _WIN32 ResetEvent(event_wake_recv); @@ -1592,13 +1622,16 @@ int recvloop(int *socketds, unsigned nsockets, struct cl_engine *engine, unsigne pthread_mutex_unlock(&exit_mutex); } - if (fds->nfds) i = (rr_last + 1) % fds->nfds; + if (fds->nfds) { + i = (rr_last + 1) % fds->nfds; + } for (j = 0; j < fds->nfds && new_sd >= 0; j++, i = (i + 1) % fds->nfds) { size_t pos = 0; int error = 0; struct fd_buf *buf = &fds->buf[i]; - if (!buf->got_newdata) + if (!buf->got_newdata) { continue; + } #ifndef _WIN32 if (buf->fd == acceptdata.syncpipe_wake_recv[0]) { @@ -1658,8 +1691,9 @@ int recvloop(int *socketds, unsigned nsockets, struct cl_engine *engine, unsigne /* Parse & dispatch command */ cmd = parse_dispatch_cmd(&conn, buf, &pos, &error, opts, readtimeout); - if (conn.mode == MODE_COMMAND && !cmd) + if (conn.mode == MODE_COMMAND && !cmd) { break; + } if (!error) { if (buf->mode == MODE_WAITREPLY && buf->off) { /* Client is not supposed to send anything more */ @@ -1669,10 +1703,11 @@ int recvloop(int *socketds, unsigned nsockets, struct cl_engine *engine, unsigne error = 1; } else if (buf->mode == MODE_STREAM) { rc = handle_stream(&conn, buf, opts, &error, &pos, readtimeout); - if (rc == -1) + if (rc == -1) { break; - else + } else { continue; + } } } if (error && error != CL_ETIMEOUT) { @@ -1697,8 +1732,9 @@ int recvloop(int *socketds, unsigned nsockets, struct cl_engine *engine, unsigne shutdown(buf->fd, 2); closesocket(buf->fd); } - } else + } else { logg(LOGG_DEBUG_NV, "Socket not shut down due to active tasks\n"); + } buf->fd = -1; } } @@ -1712,8 +1748,9 @@ int recvloop(int *socketds, unsigned nsockets, struct cl_engine *engine, unsigne if (sd_listen_fds(0) == 0) { /* only close the sockets, when not using systemd socket activation */ for (i = 0; i < fds->nfds; i++) { - if (fds->buf[i].fd == -1) + if (fds->buf[i].fd == -1) { continue; + } thrmgr_group_terminate(fds->buf[i].group); if (thrmgr_group_finished(fds->buf[i].group, EXIT_ERROR)) { logg(LOGG_DEBUG_NV, "Shutdown closed fd %d\n", fds->buf[i].fd); @@ -1733,8 +1770,9 @@ int recvloop(int *socketds, unsigned nsockets, struct cl_engine *engine, unsigne logg(LOGG_INFO, "SIGHUP caught: re-opening log file.\n"); logg_close(); sighup = 0; - if (!logg_file && (opt = optget(opts, "LogFile"))->enabled) + if (!logg_file && (opt = optget(opts, "LogFile"))->enabled) { logg_file = opt->strarg; + } } /* SelfCheck */ @@ -1831,20 +1869,23 @@ int recvloop(int *socketds, unsigned nsockets, struct cl_engine *engine, unsigne close(acceptdata.syncpipe_wake_accept[1]); close(acceptdata.syncpipe_wake_recv[1]); #endif - if (dbstat.entries) + if (dbstat.entries) { cl_statfree(&dbstat); + } if (sd_listen_fds(0) == 0) { /* only close the sockets, when not using systemd socket activation */ logg(LOGG_DEBUG, "Shutting down the main socket%s.\n", (nsockets > 1) ? "s" : ""); - for (i = 0; i < nsockets; i++) + for (i = 0; i < nsockets; i++) { shutdown(socketds[i], 2); + } } if ((opt = optget(opts, "PidFile"))->enabled) { - if (unlink(opt->strarg) == -1) + if (unlink(opt->strarg) == -1) { logg(LOGG_ERROR, "Can't unlink the pid file %s\n", opt->strarg); - else + } else { logg(LOGG_INFO, "Pid file removed.\n"); + } } time(¤t_time); diff --git a/clamd/session.c b/clamd/session.c index 53706dcbec..1b14e3ea8b 100644 --- a/clamd/session.c +++ b/clamd/session.c @@ -133,12 +133,14 @@ enum commands parse_command(const char *cmd, const char **argument, int oldstyle int conn_reply_single(const client_conn_t *conn, const char *path, const char *status) { if (conn->id) { - if (path) + if (path) { return mdprintf(conn->sd, "%u: %s: %s%c", conn->id, path, status, conn->term); + } return mdprintf(conn->sd, "%u: %s%c", conn->id, status, conn->term); } - if (path) + if (path) { return mdprintf(conn->sd, "%s: %s%c", path, status, conn->term); + } return mdprintf(conn->sd, "%s%c", status, conn->term); } @@ -146,14 +148,16 @@ int conn_reply(const client_conn_t *conn, const char *path, const char *msg, const char *status) { if (conn->id) { - if (path) + if (path) { return mdprintf(conn->sd, "%u: %s: %s %s%c", conn->id, path, msg, status, conn->term); + } return mdprintf(conn->sd, "%u: %s %s%c", conn->id, msg, status, conn->term); } - if (path) + if (path) { return mdprintf(conn->sd, "%s: %s %s%c", path, msg, status, conn->term); + } return mdprintf(conn->sd, "%s %s%c", msg, status, conn->term); } @@ -208,8 +212,9 @@ int command(client_conn_t *conn, int *virus) if (thrmgr_group_need_terminate(conn->group)) { logg(LOGG_DEBUG_NV, "Client disconnected while command was active\n"); - if (conn->scanfd != -1) + if (conn->scanfd != -1) { close(conn->scanfd); + } return 1; } thrmgr_setactiveengine(engine); @@ -249,9 +254,9 @@ int command(client_conn_t *conn, int *virus) pthread_mutex_lock(&conn->thrpool->pool_mutex); multiscan = conn->thrpool->thr_multiscan; max = conn->thrpool->thr_max; - if (multiscan + 1 < max) + if (multiscan + 1 < max) { conn->thrpool->thr_multiscan = multiscan + 1; - else { + } else { alive = conn->thrpool->thr_alive; ret = -1; } @@ -270,10 +275,11 @@ int command(client_conn_t *conn, int *virus) type = TYPE_MULTISCAN; scandata.group = group = thrmgr_group_new(); if (!group) { - if (optget(opts, "ExitOnOOM")->enabled) + if (optget(opts, "ExitOnOOM")->enabled) { return -1; - else + } else { return 1; + } } break; } @@ -303,15 +309,17 @@ int command(client_conn_t *conn, int *virus) *virus = 1; ret = 0; } else if (ret == CL_EMEM) { - if (optget(opts, "ExitOnOOM")->enabled) + if (optget(opts, "ExitOnOOM")->enabled) { ret = -1; - else + } else { ret = 1; + } } else if (ret == CL_ETIMEOUT) { thrmgr_group_terminate(conn->group); ret = 1; - } else + } else { ret = 0; + } logg(LOGG_DEBUG_NV, "Closed fd %d\n", conn->scanfd); close(conn->scanfd); } @@ -323,8 +331,9 @@ int command(client_conn_t *conn, int *virus) #endif case COMMAND_STATS: thrmgr_setactivetask(NULL, "STATS"); - if (conn->group) + if (conn->group) { mdprintf(desc, "%u: ", conn->id); + } thrmgr_printstats(desc, conn->term); return 0; case COMMAND_INSTREAMSCAN: @@ -334,15 +343,17 @@ int command(client_conn_t *conn, int *virus) *virus = 1; ret = 0; } else if (ret == CL_EMEM) { - if (optget(opts, "ExitOnOOM")->enabled) + if (optget(opts, "ExitOnOOM")->enabled) { ret = -1; - else + } else { ret = 1; + } } else if (ret == CL_ETIMEOUT) { thrmgr_group_terminate(conn->group); ret = 1; - } else + } else { ret = 0; + } if (ftruncate(conn->scanfd, 0) == -1) { /* not serious, we're going to close it and unlink it anyway */ logg(LOGG_DEBUG, "ftruncate failed: %d\n", errno); @@ -368,21 +379,26 @@ int command(client_conn_t *conn, int *virus) scandata.type = type; maxdirrec = optget(opts, "MaxDirectoryRecursion")->numarg; - if (optget(opts, "FollowDirectorySymlinks")->enabled) + if (optget(opts, "FollowDirectorySymlinks")->enabled) { flags |= CLI_FTW_FOLLOW_DIR_SYMLINK; - if (optget(opts, "FollowFileSymlinks")->enabled) + } + if (optget(opts, "FollowFileSymlinks")->enabled) { flags |= CLI_FTW_FOLLOW_FILE_SYMLINK; + } - if (!optget(opts, "CrossFilesystems")->enabled) - if (CLAMSTAT(conn->filename, &sb) == 0) + if (!optget(opts, "CrossFilesystems")->enabled) { + if (CLAMSTAT(conn->filename, &sb) == 0) { scandata.dev = sb.st_dev; + } + } ret = cli_ftw(conn->filename, flags, maxdirrec ? maxdirrec : INT_MAX, scan_callback, &data, scan_pathchk); if (ret == CL_EMEM) { - if (optget(opts, "ExitOnOOM")->enabled) + if (optget(opts, "ExitOnOOM")->enabled) { return -1; - else + } else { return 1; + } } if (scandata.group && type == TYPE_MULTISCAN) { thrmgr_group_waitforall(group, &ok, &error, &total); @@ -396,13 +412,15 @@ int command(client_conn_t *conn, int *virus) } if (ok + error == total && (error != total)) { - if (conn_reply_single(conn, conn->filename, "OK") == -1) + if (conn_reply_single(conn, conn->filename, "OK") == -1) { ret = CL_ETIMEOUT; + } } *virus = total - (ok + error); - if (ret == CL_ETIMEOUT) + if (ret == CL_ETIMEOUT) { thrmgr_group_terminate(conn->group); + } return error; } @@ -459,8 +477,9 @@ static int dispatch_command(client_conn_t *conn, enum commands cmd, const char * ret = -2; break; } - if (!dup_conn->group) + if (!dup_conn->group) { bulk = 0; + } if (!ret && !thrmgr_group_dispatch(dup_conn->thrpool, dup_conn->group, dup_conn, bulk)) { logg(LOGG_ERROR, "thread dispatch failed\n"); ret = -2; @@ -564,20 +583,23 @@ int execute_or_dispatch_command(client_conn_t *conn, enum commands cmd, const ch * connection */ return 1; case COMMAND_PING: - if (conn->group) + if (conn->group) { mdprintf(desc, "%u: PONG%c", conn->id, term); - else + } else { mdprintf(desc, "PONG%c", term); + } return conn->group ? 0 : 1; case COMMAND_VERSION: { - if (conn->group) + if (conn->group) { mdprintf(desc, "%u: ", conn->id); + } print_ver(desc, conn->term, engine); return conn->group ? 0 : 1; } case COMMAND_COMMANDS: { - if (conn->group) + if (conn->group) { mdprintf(desc, "%u: ", conn->id); + } print_commands(desc, conn->term, engine); return conn->group ? 0 : 1; } @@ -608,8 +630,9 @@ int execute_or_dispatch_command(client_conn_t *conn, enum commands cmd, const ch return dispatch_command(conn, cmd, argument); case COMMAND_IDSESSION: conn->group = thrmgr_group_new(); - if (!conn->group) + if (!conn->group) { return CL_EMEM; + } return 0; case COMMAND_END: if (!conn->group) { diff --git a/clamd/tcpserver.c b/clamd/tcpserver.c index 26fc058e23..40e1dd59b1 100644 --- a/clamd/tcpserver.c +++ b/clamd/tcpserver.c @@ -124,8 +124,9 @@ int tcpserver(int **lsockets, unsigned int *nlsockets, char *ipaddr, const struc for (p = info; p != NULL; p = p->ai_next, i++) { t = realloc(sockets, sizeof(int) * (*nlsockets + 1)); if (!(t)) { - for (i = 0; i < *nlsockets; i++) + for (i = 0; i < *nlsockets; i++) { close(sockets[i]); + } freeaddrinfo(info); return -1; @@ -161,8 +162,9 @@ int tcpserver(int **lsockets, unsigned int *nlsockets, char *ipaddr, const struc if (ipaddr) { strncpy(host, ipaddr, sizeof(host)); host[sizeof(host) - 1] = '\0'; - } else + } else { host[0] = '\0'; + } snprintf(serv, sizeof(serv), "%u", (unsigned int)(optget(opts, "TCPSocket")->numarg)); #endif if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) { diff --git a/clamd/thrmgr.c b/clamd/thrmgr.c index ac9f2e711c..3f5b01b97c 100644 --- a/clamd/thrmgr.c +++ b/clamd/thrmgr.c @@ -147,10 +147,12 @@ static void remove_frompools(threadpool_t *t) pthread_mutex_unlock(&pools_lock); return; } - if (prev) + if (prev) { prev->nxt = l->nxt; - if (l == pools) + } + if (l == pools) { pools = l->nxt; + } free(l); desc = t->tasks; while (desc) { @@ -168,8 +170,9 @@ static void print_queue(int f, work_queue_t *queue, struct timeval *tv_now) unsigned invalids = 0, cnt = 0; work_item_t *q; - if (!queue->head) + if (!queue->head) { return; + } for (q = queue->head; q; q = q->next) { long delta; delta = tv_now->tv_usec - q->time_queued.tv_usec; @@ -178,20 +181,24 @@ static void print_queue(int f, work_queue_t *queue, struct timeval *tv_now) invalids++; continue; } - if (delta > umax) + if (delta > umax) { umax = delta; - if (delta < umin) + } + if (delta < umin) { umin = delta; + } usum += delta; ++cnt; } mdprintf(f, " min_wait: %.6f max_wait: %.6f avg_wait: %.6f", umin / 1e6, umax / 1e6, usum / (1e6 * cnt)); - if (invalids) + if (invalids) { mdprintf(f, " (INVALID timestamps: %u)", invalids); - if (cnt + invalids != (unsigned)queue->item_count) + } + if (cnt + invalids != (unsigned)queue->item_count) { mdprintf(f, " (ERROR: %u != %u)", cnt + invalids, (unsigned)queue->item_count); + } } int thrmgr_printstats(int f, char term) @@ -204,7 +211,9 @@ int thrmgr_printstats(int f, char term) int has_libc_memstats = 0; pthread_mutex_lock(&pools_lock); - for (cnt = 0, l = pools; l; l = l->nxt) cnt++; + for (cnt = 0, l = pools; l; l = l->nxt) { + cnt++; + } mdprintf(f, "POOLS: %u\n\n", cnt); for (l = pools; l && !error_flag; l = l->nxt) { threadpool_t *pool = l->pool; @@ -258,8 +267,9 @@ int thrmgr_printstats(int f, char term) * search is good enough */ size_t i; for (i = 0; i < seen_cnt; i++) { - if (seen[i] == task->engine) + if (seen[i] == task->engine) { break; + } } /* we need to count the memusage from the same * engine only once */ @@ -300,13 +310,14 @@ int thrmgr_printstats(int f, char term) if (error_flag) { mdprintf(f, "ERROR: error encountered while formatting statistics\n"); } else { - if (has_libc_memstats) + if (has_libc_memstats) { mdprintf(f, "MEMSTATS: heap %.3fM mmap %.3fM used %.3fM free %.3fM releasable %.3fM pools %u pools_used %.3fM pools_total %.3fM\n", mem_heap, mem_mmap, mem_used, mem_free, mem_releasable, pool_cnt, pool_used / (1024 * 1024.0), pool_total / (1024 * 1024.0)); - else + } else { mdprintf(f, "MEMSTATS: heap N/A mmap N/A used N/A free N/A releasable N/A pools %u pools_used %.3fM pools_total %.3fM\n", pool_cnt, pool_used / (1024 * 1024.0), pool_total / (1024 * 1024.0)); + } } mdprintf(f, "END%c", term); pthread_mutex_unlock(&pools_lock); @@ -546,12 +557,14 @@ void thrmgr_setactivetask(const char *filename, const char *cmd) struct task_desc *desc; pthread_once(&stats_tls_key_once, stats_tls_key_alloc); desc = pthread_getspecific(stats_tls_key); - if (!desc) + if (!desc) { return; + } desc->filename = filename; if (cmd) { - if (cmd == IDLE_TASK && desc->command == cmd) + if (cmd == IDLE_TASK && desc->command == cmd) { return; + } desc->command = cmd; gettimeofday(&desc->tv, NULL); } @@ -562,8 +575,9 @@ void thrmgr_setactiveengine(const struct cl_engine *engine) struct task_desc *desc; pthread_once(&stats_tls_key_once, stats_tls_key_alloc); desc = pthread_getspecific(stats_tls_key); - if (!desc) + if (!desc) { return; + } desc->engine = engine; } @@ -571,13 +585,14 @@ void thrmgr_setactiveengine(const struct cl_engine *engine) static void stats_init(threadpool_t *pool) { struct task_desc *desc = calloc(1, sizeof(*desc)); - if (!desc) + if (!desc) { return; + } pthread_once(&stats_tls_key_once, stats_tls_key_alloc); pthread_setspecific(stats_tls_key, desc); - if (!pool->tasks) + if (!pool->tasks) { pool->tasks = desc; - else { + } else { desc->nxt = pool->tasks; pool->tasks->prv = desc; pool->tasks = desc; @@ -588,15 +603,19 @@ static void stats_init(threadpool_t *pool) static void stats_destroy(threadpool_t *pool) { struct task_desc *desc = pthread_getspecific(stats_tls_key); - if (!desc) + if (!desc) { return; + } pthread_mutex_lock(&pools_lock); - if (desc->prv) + if (desc->prv) { desc->prv->nxt = desc->nxt; - if (desc->nxt) + } + if (desc->nxt) { desc->nxt->prv = desc->prv; - if (pool->tasks == desc) + } + if (pool->tasks == desc) { pool->tasks = desc->nxt; + } free(desc); pthread_setspecific(stats_tls_key, NULL); pthread_mutex_unlock(&pools_lock); @@ -606,8 +625,9 @@ static inline int thrmgr_contended(threadpool_t *pool, int bulk) { /* don't allow bulk items to exceed 50% of queue, so that * non-bulk items get a chance to be in the queue */ - if (bulk && pool->bulk_queue->item_count >= pool->queue_max / 2) + if (bulk && pool->bulk_queue->item_count >= pool->queue_max / 2) { return 1; + } return pool->bulk_queue->item_count + pool->single_queue->item_count + pool->thr_alive - pool->thr_idle >= pool->queue_max; } @@ -635,13 +655,15 @@ static void *thrmgr_pop(threadpool_t *pool) task = work_queue_pop(first); if (task) { - if (++first->popped == ratio) + if (++first->popped == ratio) { second->popped = 0; + } } else { task = work_queue_pop(second); if (task) { - if (++second->popped == ratio) + if (++second->popped == ratio) { first->popped = 0; + } } } @@ -840,10 +862,12 @@ int thrmgr_group_finished(jobgroup_t *group, enum thrmgr_exit exitc) if (group->jobs) { if (!--group->jobs) { ret = 1; - } else + } else { logg(LOGG_DEBUG_NV, "THRMGR: active jobs for %p: %d\n", group, group->jobs); - if (group->jobs == 1) + } + if (group->jobs == 1) { pthread_cond_signal(&group->only); + } } pthread_mutex_unlock(&group->mutex); if (ret) { @@ -864,8 +888,9 @@ void thrmgr_group_waitforall(jobgroup_t *group, unsigned *ok, unsigned *error, u pthread_mutex_lock(&exit_mutex); needexit = progexit; pthread_mutex_unlock(&exit_mutex); - if (needexit) + if (needexit) { break; + } /* wake to check progexit */ timeout.tv_sec = time(NULL) + 5; timeout.tv_nsec = 0; @@ -874,10 +899,11 @@ void thrmgr_group_waitforall(jobgroup_t *group, unsigned *ok, unsigned *error, u *ok = group->exit_ok; *error = group->exit_error + needexit; *total = group->exit_total; - if (!--group->jobs) + if (!--group->jobs) { needfree = 1; - else + } else { logg(LOGG_DEBUG_NV, "THRMGR: active jobs for %p: %d\n", group, group->jobs); + } pthread_mutex_unlock(&group->mutex); if (needfree) { logg(LOGG_DEBUG_NV, "THRMGR: group finished freeing %p\n", group); @@ -890,8 +916,9 @@ jobgroup_t *thrmgr_group_new(void) jobgroup_t *group; group = malloc(sizeof(*group)); - if (!group) + if (!group) { return NULL; + } group->jobs = 1; group->exit_ok = group->exit_error = group->exit_total = group->force_exit = 0; if (pthread_mutex_init(&group->mutex, NULL)) { @@ -916,8 +943,9 @@ int thrmgr_group_need_terminate(jobgroup_t *group) pthread_mutex_lock(&group->mutex); ret = group->force_exit; pthread_mutex_unlock(&group->mutex); - } else + } else { ret = 0; + } pthread_mutex_lock(&exit_mutex); ret |= progexit; pthread_mutex_unlock(&exit_mutex); diff --git a/clamdscan/CMakeLists.txt b/clamdscan/CMakeLists.txt index 048bb16c53..24ee3c9a10 100644 --- a/clamdscan/CMakeLists.txt +++ b/clamdscan/CMakeLists.txt @@ -30,6 +30,12 @@ target_include_directories( clamdscan ) set_target_properties( clamdscan PROPERTIES COMPILE_FLAGS "${WARNCFLAGS}" ) +if(CLANG_TIDY) + set_target_properties( clamdscan PROPERTIES + C_CLANG_TIDY "${CLANG_TIDY_PROPERTY}" + C_CLANG_TIDY_EXPORT_FIXES_DIR "${CMAKE_BINARY_DIR}/clang-tidy-fixes" ) +endif() + if (APPLE AND CLAMAV_SIGN_FILE) set_target_properties( clamdscan PROPERTIES XCODE_ATTRIBUTE_CODE_SIGN_IDENTITY ${CODE_SIGN_IDENTITY} diff --git a/clamdscan/clamdscan.c b/clamdscan/clamdscan.c index 761b43c093..620d5d7b84 100644 --- a/clamdscan/clamdscan.c +++ b/clamdscan/clamdscan.c @@ -93,11 +93,13 @@ int main(int argc, char **argv) logg_verbose = 1; } - if (optget(opts, "quiet")->enabled) + if (optget(opts, "quiet")->enabled) { mprintf_quiet = 1; + } - if (optget(opts, "stdout")->enabled) + if (optget(opts, "stdout")->enabled) { mprintf_stdout = 1; + } if (optget(opts, "version")->enabled) { print_server_version(opts); @@ -124,8 +126,9 @@ int main(int argc, char **argv) exit(ret); } - if (optget(opts, "infected")->enabled) + if (optget(opts, "infected")->enabled) { printinfected = 1; + } /* initialize logger */ @@ -137,8 +140,9 @@ int main(int argc, char **argv) optfree(clamdopts); exit(2); } - } else + } else { logg_file = NULL; + } if (optget(opts, "reload")->enabled) { ret = reload_clamd_database(opts); @@ -181,8 +185,9 @@ int main(int argc, char **argv) dms += (dms < 0) ? (1000000) : (0); logg(LOGG_INFO, "\n----------- SCAN SUMMARY -----------\n"); logg(LOGG_INFO, "Infected files: %d\n", infected); - if (err) + if (err) { logg(LOGG_INFO, "Total errors: %d\n", err); + } if (notremoved) { logg(LOGG_INFO, "Not removed: %d\n", notremoved); } diff --git a/clamdscan/client.c b/clamdscan/client.c index 54f28c2252..453262aba2 100644 --- a/clamdscan/client.c +++ b/clamdscan/client.c @@ -96,16 +96,18 @@ static int isremote(const struct optstruct *opts) return 0; } #endif - if (!(opt = optget(clamdopts, "TCPSocket"))->enabled) + if (!(opt = optget(clamdopts, "TCPSocket"))->enabled) { return 0; + } snprintf(port, sizeof(port), "%lld", optget(clamdopts, "TCPSocket")->numarg); opt = optget(clamdopts, "TCPAddr"); while (opt) { ipaddr = NULL; - if (opt->strarg) + if (opt->strarg) { ipaddr = (!strcmp(opt->strarg, "any") ? NULL : opt->strarg); + } memset(&hints, 0x00, sizeof(struct addrinfo)); hints.ai_family = AF_UNSPEC; @@ -238,15 +240,17 @@ int16_t ping_clamd(const struct optstruct *opts) if (i + 1 < attempts) { if (optget(opts, "wait")->enabled) { - if (interval == 1) + if (interval == 1) { logg(LOGG_DEBUG, "Could not connect, will try again in %lu second\n", interval); - else + } else { logg(LOGG_DEBUG, "Could not connect, will try again in %lu seconds\n", interval); + } } else { - if (interval == 1) + if (interval == 1) { logg(LOGG_INFO, "Could not connect, will PING again in %lu second\n", interval); - else + } else { logg(LOGG_INFO, "Could not connect, will PING again in %lu seconds\n", interval); + } } sleep(interval); } @@ -326,12 +330,14 @@ static int client_scan(const char *file, int scantype, int *infected, int *err, fullpath = real_path; } - if (!fullpath) + if (!fullpath) { return 0; - if (!session) + } + if (!session) { ret = serial_client_scan(fullpath, scantype, infected, err, maxlevel, flags); - else + } else { ret = parallel_client_scan(fullpath, scantype, infected, err, maxlevel, flags); + } free(fullpath); return ret; } @@ -344,7 +350,9 @@ int get_clamd_version(const struct optstruct *opts) const char zVERSION[] = "zVERSION"; isremote(opts); - if ((sockd = dconnect(clamdopts)) < 0) return 2; + if ((sockd = dconnect(clamdopts)) < 0) { + return 2; + } recvlninit(&rcv, sockd); if (sendln(sockd, zVERSION, sizeof(zVERSION))) { @@ -372,7 +380,9 @@ int reload_clamd_database(const struct optstruct *opts) const char zRELOAD[] = "zRELOAD"; isremote(opts); - if ((sockd = dconnect(clamdopts)) < 0) return 2; + if ((sockd = dconnect(clamdopts)) < 0) { + return 2; + } recvlninit(&rcv, sockd); if (sendln(sockd, zRELOAD, sizeof(zRELOAD))) { @@ -417,19 +427,22 @@ int client(const struct optstruct *opts, int *infected, int *err) if (remote || scandash) { scantype = STREAM; session = optget(opts, "multiscan")->enabled; - } else if (optget(opts, "multiscan")->enabled) + } else if (optget(opts, "multiscan")->enabled) { scantype = MULTI; - else if (optget(opts, "allmatch")->enabled) + } else if (optget(opts, "allmatch")->enabled) { scantype = ALLMATCH; - else + } else { scantype = CONT; + } maxrec = optget(clamdopts, "MaxDirectoryRecursion")->numarg; maxstream = optget(clamdopts, "StreamMaxLength")->numarg; - if (optget(clamdopts, "FollowDirectorySymlinks")->enabled) + if (optget(clamdopts, "FollowDirectorySymlinks")->enabled) { flags |= CLI_FTW_FOLLOW_DIR_SYMLINK; - if (optget(clamdopts, "FollowFileSymlinks")->enabled) + } + if (optget(clamdopts, "FollowFileSymlinks")->enabled) { flags |= CLI_FTW_FOLLOW_FILE_SYMLINK; + } flags |= CLI_FTW_TRIM_SLASHES; *infected = 0; @@ -442,15 +455,21 @@ int client(const struct optstruct *opts, int *infected, int *err) opts->filename[0], strerror(errno)); return 2; } - if ((sb.st_mode & S_IFMT) != S_IFREG) scantype = STREAM; - if ((sockd = dconnect(clamdopts)) >= 0 && (ret = dsresult(sockd, scantype, NULL, &ret, NULL, clamdopts)) >= 0) + if ((sb.st_mode & S_IFMT) != S_IFREG) { + scantype = STREAM; + } + if ((sockd = dconnect(clamdopts)) >= 0 && (ret = dsresult(sockd, scantype, NULL, &ret, NULL, clamdopts)) >= 0) { *infected = ret; - else + } else { errors = 1; - if (sockd >= 0) closesocket(sockd); + } + if (sockd >= 0) { + closesocket(sockd); + } } else if (opts->filename || optget(opts, "file-list")->enabled) { - if (opts->filename && optget(opts, "file-list")->enabled) + if (opts->filename && optget(opts, "file-list")->enabled) { logg(LOGG_WARNING, "Only scanning files from --file-list (files passed at cmdline are ignored)\n"); + } while ((fname = filelist(opts, NULL))) { if (!strcmp(fname, "-")) { diff --git a/clamdscan/proto.c b/clamdscan/proto.c index ade4efd2f4..596e873ee7 100644 --- a/clamdscan/proto.c +++ b/clamdscan/proto.c @@ -188,8 +188,9 @@ int serial_client_scan(char *file, int scantype, int *infected, int *err, int ma *err += cdata.errors; if (!cdata.errors && (ftw == CL_SUCCESS || ftw == CL_BREAK)) { - if (cdata.printok) + if (cdata.printok) { logg(LOGG_INFO, "%s: OK\n", file); + } return 0; } else if (!cdata.files) { logg(LOGG_INFO, "%s: No files scanned\n", file); @@ -229,15 +230,23 @@ static int dspresult(struct client_parallel_data *c) recvlninit(&rcv, c->sockd); do { len = recvln(&rcv, &bol, &eol); - if (len < 0) return 1; - if (!len) return 2; + if (len < 0) { + return 1; + } + if (!len) { + return 2; + } if ((rid = atoi(bol))) { id = &c->ids; while (*id) { - if ((*id)->id == rid) break; + if ((*id)->id == rid) { + break; + } id = &((*id)->next); } - if (!*id) id = NULL; + if (!*id) { + id = NULL; + } } if (!id) { logg(LOGG_ERROR, "Bogus session id from clamd\n"); @@ -254,7 +263,9 @@ static int dspresult(struct client_parallel_data *c) c->infected++; c->printok = 0; logg(LOGG_INFO, "%s%s\n", filename, colon); - if (action) action(filename); + if (action) { + action(filename); + } } else if (!memcmp(eol - 7, " ERROR", 6)) { c->errors++; c->printok = 0; @@ -338,7 +349,9 @@ static cl_error_t parallel_callback(STATBUF *sb, char *filename, const char *pat FD_ZERO(&wfds); FD_SET(c->sockd, &wfds); if (select(c->sockd + 1, &rfds, &wfds, NULL, NULL) < 0) { - if (errno == EINTR) continue; + if (errno == EINTR) { + continue; + } logg(LOGG_ERROR, "select() failed during session: %s\n", strerror(errno)); status = CL_BREAK; goto done; @@ -347,10 +360,13 @@ static cl_error_t parallel_callback(STATBUF *sb, char *filename, const char *pat if (dspresult(c)) { status = CL_BREAK; goto done; - } else + } else { continue; + } + } + if (FD_ISSET(c->sockd, &wfds)) { + break; } - if (FD_ISSET(c->sockd, &wfds)) break; } switch (c->scantype) { @@ -404,8 +420,9 @@ int parallel_client_scan(char *file, int scantype, int *infected, int *err, int const char zIDSESSION[] = "zIDSESSION"; const char zEND[] = "zEND"; - if ((cdata.sockd = dconnect(clamdopts)) < 0) + if ((cdata.sockd = dconnect(clamdopts)) < 0) { return 1; + } if (sendln(cdata.sockd, zIDSESSION, sizeof(zIDSESSION))) { closesocket(cdata.sockd); @@ -431,7 +448,9 @@ int parallel_client_scan(char *file, int scantype, int *infected, int *err, int } sendln(cdata.sockd, zEND, sizeof(zEND)); - while (cdata.ids && !dspresult(&cdata)) continue; + while (cdata.ids && !dspresult(&cdata)) { + continue; + } closesocket(cdata.sockd); *infected += cdata.infected; @@ -441,13 +460,16 @@ int parallel_client_scan(char *file, int scantype, int *infected, int *err, int logg(LOGG_ERROR, "Clamd closed the connection before scanning all files.\n"); return 1; } - if (cdata.errors) + if (cdata.errors) { return 1; + } - if (!cdata.files) + if (!cdata.files) { return 0; + } - if (cdata.printok) + if (cdata.printok) { logg(LOGG_INFO, "%s: OK\n", file); + } return 0; } diff --git a/clamdtop/CMakeLists.txt b/clamdtop/CMakeLists.txt index 6fdd359af9..7c103418a3 100644 --- a/clamdtop/CMakeLists.txt +++ b/clamdtop/CMakeLists.txt @@ -23,6 +23,12 @@ target_include_directories( clamdtop ) set_target_properties( clamdtop PROPERTIES COMPILE_FLAGS "${WARNCFLAGS}" ) +if(CLANG_TIDY) + set_target_properties( clamdtop PROPERTIES + C_CLANG_TIDY "${CLANG_TIDY_PROPERTY}" + C_CLANG_TIDY_EXPORT_FIXES_DIR "${CMAKE_BINARY_DIR}/clang-tidy-fixes" ) +endif() + if (APPLE AND CLAMAV_SIGN_FILE) set_target_properties( clamdtop PROPERTIES XCODE_ATTRIBUTE_CODE_SIGN_IDENTITY ${CODE_SIGN_IDENTITY} diff --git a/clamdtop/clamdtop.c b/clamdtop/clamdtop.c index 9721ed6491..8b06efee0b 100644 --- a/clamdtop/clamdtop.c +++ b/clamdtop/clamdtop.c @@ -232,11 +232,13 @@ static void resize(void) queue_header[maxx] = '\0'; clamd_header[maxx] = '\0'; p = queue_header + strlen(queue_header); - while (p < queue_header + maxx) + while (p < queue_header + maxx) { *p++ = ' '; + } p = clamd_header + strlen(clamd_header); - while (p < clamd_header + maxx) + while (p < clamd_header + maxx) { *p++ = ' '; + } if (global.num_clamd > 1) { free(multi_queue_header); multi_queue_header = malloc(maxx + 1); @@ -245,8 +247,9 @@ static void resize(void) strncpy(multi_queue_header, CMDHEAD2, maxx); multi_queue_header[maxx] = '\0'; p = multi_queue_header + strlen(multi_queue_header); - while (p < multi_queue_header + maxx) + while (p < multi_queue_header + maxx) { *p++ = ' '; + } } } @@ -318,8 +321,9 @@ static void init_ncurses(int num_clamd, int use_default) halfdelay(UPDATE_INTERVAL * 10); /* timeout of 2s when waiting for input*/ noecho(); /* don't echo input */ curs_set(0); /* turn off cursor */ - if (use_default) + if (use_default) { use_default_colors(); + } init_pair(header_color, COLOR_BLACK, COLOR_WHITE); init_pair(version_color, default_fg, default_bg); @@ -346,12 +350,14 @@ static void print_colored(WINDOW *win, const char *p) { while (*p) { wattron(win, DESCR_ATTR); - while (*p && !isdigit(*p)) + while (*p && !isdigit(*p)) { waddch(win, *p++); + } wattroff(win, DESCR_ATTR); wattron(win, VALUE_ATTR); - while (*p && isdigit(*p)) + while (*p && isdigit(*p)) { waddch(win, *p++); + } wattroff(win, VALUE_ATTR); } } @@ -377,8 +383,9 @@ static void header(void) werase(status_bar_window); for (i = 0; i < sizeof(status_bar_keys) / sizeof(status_bar_keys[0]); i++) { const char *s = status_bar_keys[i]; - if (!s) + if (!s) { continue; + } wattron(status_bar_window, A_REVERSE); if (s[0] == '^') { mvwaddch(status_bar_window, 0, x, ACS_UARROW); @@ -409,15 +416,18 @@ static void show_bar(WINDOW *win, size_t i, unsigned live, unsigned idle, assert(activ + 2 < len && activ + dim + 2 < len && activ + dim + rem + 2 < len && "Invalid values"); mvwaddch(win, i, start, '[' | A_BOLD); wattron(win, A_BOLD | COLOR_PAIR(activ_color)); - for (i = 0; i < activ; i++) + for (i = 0; i < activ; i++) { waddch(win, '|'); + } wattroff(win, A_BOLD | COLOR_PAIR(activ_color)); wattron(win, A_DIM | COLOR_PAIR(dim_color)); - for (i = 0; i < dim; i++) + for (i = 0; i < dim; i++) { waddch(win, '|'); + } wattroff(win, A_DIM | COLOR_PAIR(dim_color)); - for (i = 0; i < rem; i++) + for (i = 0; i < rem; i++) { waddch(win, ' '); + } waddch(win, ']' | A_BOLD); if (blink) { getyx(win, y, x); @@ -466,14 +476,21 @@ static void cleanup(void) free(global.all_stats); free(global.conn); free(queue_header); - if (global.num_clamd > 1) + if (global.num_clamd > 1) { free(multi_queue_header); + } free(clamd_header); if (!normal_exit) { fprintf(stderr, "Abnormal program termination"); - if (exit_reason) fprintf(stderr, ": %s", exit_reason); - if (exit_func) fprintf(stderr, " in %s", exit_func); - if (exit_line) fprintf(stderr, " at line %u", exit_line); + if (exit_reason) { + fprintf(stderr, ": %s", exit_reason); + } + if (exit_func) { + fprintf(stderr, " in %s", exit_func); + } + if (exit_line) { + fprintf(stderr, " at line %u", exit_line); + } fputc('\n', stderr); } } @@ -521,10 +538,12 @@ static int tasks_compare(const void *a, const void *b) { const struct task *ta = a; const struct task *tb = b; - if (ta->tim < tb->tim) + if (ta->tim < tb->tim) { return 1; - if (ta->tim > tb->tim) + } + if (ta->tim > tb->tim) { return -1; + } return 0; } @@ -542,8 +561,9 @@ static void print_con_info(conn_t *conn, const char *fmt, ...) OOM_CHECK(buf); memset(buf, ' ', maxx + 1); vsnprintf(buf, maxx + 1, fmt, ap); - if ((nl = strrchr(buf, '\n')) != NULL) + if ((nl = strrchr(buf, '\n')) != NULL) { *nl = ' '; + } buf[strlen(buf)] = ' '; buf[maxx] = '\0'; wattron(stats_head_window, ERROR_ATTR); @@ -551,8 +571,9 @@ static void print_con_info(conn_t *conn, const char *fmt, ...) wattroff(stats_head_window, ERROR_ATTR); wrefresh(stats_head_window); free(buf); - } else + } else { vfprintf(stdout, fmt, ap); + } va_end(ap); } @@ -573,8 +594,9 @@ char *get_ip(const char *ip) */ dupip = strdup(ip); - if (!(dupip)) + if (!(dupip)) { return NULL; + } if (dupip[0] == '[') { /* IPv6 */ @@ -613,11 +635,13 @@ char *get_port(const char *ip) unsigned int offset = 0; dupip = get_ip(ip); - if (!(dupip)) + if (!(dupip)) { return NULL; + } - if (ip[0] == '[') + if (ip[0] == '[') { offset += 2; + } p = (char *)ip + strlen(dupip) + offset; if (*p == ':') { @@ -647,8 +671,9 @@ char *make_ip(const char *host, const char *port) len += (ipv6 ? 4 : 3); ip = calloc(1, len); - if (!(ip)) + if (!(ip)) { return NULL; + } snprintf(ip, len, "%s%s%s:%s", ipv6 ? "[" : "", host, ipv6 ? "]" : "", port); @@ -795,23 +820,27 @@ static int make_connection(const char *soname, conn_t *conn) return -1; } - if ((rc = make_connection_real(soname, conn))) + if ((rc = make_connection_real(soname, conn))) { return rc; + } send_string(conn, "nIDSESSION\nnVERSION\n"); free(conn->version); conn->version = NULL; - if (!read_version(conn)) + if (!read_version(conn)) { return 0; + } /* clamd < 0.95 */ - if ((rc = make_connection_real(soname, conn))) + if ((rc = make_connection_real(soname, conn))) { return rc; + } send_string(conn, "nSESSION\nnVERSION\n"); conn->version = NULL; - if (!read_version(conn)) + if (!read_version(conn)) { return 0; + } return -1; } @@ -859,8 +888,9 @@ static int recv_line(conn_t *conn, char *buf, size_t len) assert(buf); len--; - if (!len || conn->sd == -1) + if (!len || conn->sd == -1) { return 0; + } assert(conn->sd > 0); while (len > 0) { ssize_t nread = recv(conn->sd, buf, len, MSG_PEEK); @@ -879,19 +909,21 @@ static int recv_line(conn_t *conn, char *buf, size_t len) char *p = memchr(buf, '\n', nread); if (p) { len = p - buf + 1; - } else + } else { len = nread; + } assert(len > 0); assert(len <= (size_t)nread); nread = recv(conn->sd, buf, len, 0); - if (nread == -1) + if (nread == -1) { reconnect(conn); - else { + } else { assert(nread > 0 && (size_t)nread == len); buf += nread; } - if (p) + if (p) { break; + } } } *buf = '\0'; @@ -912,16 +944,19 @@ static void output_queue(size_t line, ssize_t max) } wattron(stats_window, COLOR_PAIR(queue_header_color)); - if (detail_selected == -1 && global.num_clamd > 1) + if (detail_selected == -1 && global.num_clamd > 1) { mvwprintw(stats_window, line, 0, "%s", multi_queue_header); - else + } else { mvwprintw(stats_window, line, 0, "%s", queue_header); + } wattroff(stats_window, COLOR_PAIR(queue_header_color)); if (max < j) { --max; tasks_truncd = 1; } - if (max < 0) max = 0; + if (max < 0) { + max = 0; + } for (i = 0; i < j && i < max; i++) { char *cmde; assert(tasks); @@ -931,24 +966,28 @@ static void output_queue(size_t line, ssize_t max) const char *filstart = strchr(cmde + 1, ' '); strncpy(cmd, filtered_tasks[i].line, sizeof(cmd) - 1); cmd[15] = '\0'; - if (filtered_tasks[i].line + 15 > cmde) + if (filtered_tasks[i].line + 15 > cmde) { cmd[cmde - filtered_tasks[i].line] = '\0'; + } if (filstart) { size_t oldline = ++line; char *nl = strrchr(++filstart, '\n'); - if (nl != NULL) + if (nl != NULL) { *nl = '\0'; + } wattron(stats_window, A_BOLD); - if (detail_selected == -1 && global.num_clamd > 1) + if (detail_selected == -1 && global.num_clamd > 1) { mvwprintw(stats_window, line, 0, "%2u %s", filtered_tasks[i].clamd_no, cmd + 1); - else + } else { mvwprintw(stats_window, line, 0, " %s", cmd + 1); + } wattroff(stats_window, A_BOLD); mvwprintw(stats_window, line, 15, "%10.03fs", filtered_tasks[i].tim); mvwprintw(stats_window, line, 30, "%s", filstart); line = getcury(stats_window); - if (line > oldline) + if (line > oldline) { max -= line - oldline; + } if (!tasks_truncd && max < j) { --max; tasks_truncd = 1; @@ -972,10 +1011,12 @@ static void parse_queue(conn_t *conn, char *buf, size_t len, unsigned idx) do { double tim; const char *t = strchr(buf, ' '); - if (!t) + if (!t) { continue; - if (sscanf(t, "%lf", &tim) != 1) + } + if (sscanf(t, "%lf", &tim) != 1) { continue; + } ++global.n; global.tasks = realloc(global.tasks, sizeof(*global.tasks) * global.n); OOM_CHECK(global.tasks); @@ -998,20 +1039,22 @@ static void output_memstats(struct stats *stats) if (stats->mem > 0 || (stats->mem >= 0 && (stats->pools_total > 0))) { box(mem_window, 0, 0); - if (stats->mem > 0) + if (stats->mem > 0) { snprintf(buf, sizeof(buf), "heap %4.0fM mmap %4.0fM unused%4.0fM", stats->heapu, stats->mmapu, stats->releasable); - else + } else { snprintf(buf, sizeof(buf), "heap N/A mmap N/A unused N/A"); + } mvwprintw(mem_window, 1, 1, "Mem: "); print_colored(mem_window, buf); mvwprintw(mem_window, 2, 1, "Libc: "); - if (stats->mem > 0) + if (stats->mem > 0) { snprintf(buf, sizeof(buf), "used %4.0fM free %4.0fM total %4.0fM", stats->totalu, stats->totalf, stats->totalu + stats->totalf); - else + } else { snprintf(buf, sizeof(buf), "used N/A free N/A total N/A"); + } print_colored(mem_window, buf); mvwprintw(mem_window, 3, 1, "Pool: "); @@ -1075,12 +1118,13 @@ static int output_stats(struct stats *stats, unsigned idx) c = 'M'; s = stats->mem; } - if (s >= 99.95) + if (s >= 99.95) { format = "%.0f%c"; - else if (s >= 9.995) + } else if (s >= 9.995) { format = "%.1f%c"; - else + } else { format = "%.2f%c"; + } snprintf(mem, sizeof(mem), format, s, c); mem[sizeof(mem) - 1] = '\0'; @@ -1090,12 +1134,13 @@ static int output_stats(struct stats *stats, unsigned idx) if (!stats->db_time.tm_year) { strncpy(timbuf, "N/A", sizeof(timbuf)); timbuf[sizeof(timbuf) - 1] = '\0'; - } else + } else { snprintf(timbuf, sizeof(timbuf), "%04u-%02u-%02uT%02u", 1900 + stats->db_time.tm_year, stats->db_time.tm_mon + 1, stats->db_time.tm_mday, stats->db_time.tm_hour); + } memset(line, ' ', maxx + 1); if (!stats->stats_unsupp) { @@ -1172,8 +1217,9 @@ static void output_all(void) wattroff(stats_head_window, COLOR_PAIR(queue_header_color)); for (i = 0; i < global.num_clamd; i++) { unsigned j = output_stats(&global.all_stats[i], i); - if (j > stats_line) + if (j > stats_line) { stats_line = j; + } } output_queue(stats_line, maxystats - stats_line - 1); wrefresh(stats_head_window); @@ -1193,10 +1239,11 @@ static void parse_stats(conn_t *conn, struct stats *stats, unsigned idx) int primary = 0; const char *pstart, *p, *vstart; - if (conn->tcp) + if (conn->tcp) { stats->remote = conn->remote; - else + } else { stats->remote = "local"; + } if (!conn->version) { stats->engine_version = strdup("???"); @@ -1210,16 +1257,21 @@ static void parse_stats(conn_t *conn, struct stats *stats, unsigned idx) return; } /* find digit in version */ - while (*p && !isdigit(*p)) + while (*p && !isdigit(*p)) { p++; + } /* rewind to first space or dash */ - while (p > pstart && *p && *p != ' ' && *p != '-') + while (p > pstart && *p && *p != ' ' && *p != '-') { p--; - if (*p) p++; + } + if (*p) { + p++; + } /* keep only base version, and cut -exp, and -gittags */ pstart = p; - while (*p && *p != ' ' && *p != '-' && *p != '/') + while (*p && *p != ' ' && *p != '-' && *p != '/') { p++; + } stats->engine_version = malloc(p - pstart + 1); OOM_CHECK(stats->engine_version); @@ -1234,13 +1286,16 @@ static void parse_stats(conn_t *conn, struct stats *stats, unsigned idx) } else { pstart++; p = strchr(pstart, '/'); - if (!p) + if (!p) { p = pstart + strlen(pstart); + } stats->db_version = malloc(p - pstart + 1); OOM_CHECK(stats->db_version); memcpy(stats->db_version, pstart, p - pstart); stats->db_version[p - pstart] = '\0'; - if (*p) p++; + if (*p) { + p++; + } if (!*p || !strptime(p, "%a %b %d %H:%M:%S %Y", &stats->db_time)) { memset(&stats->db_time, 0, sizeof(stats->db_time)); } @@ -1267,8 +1322,9 @@ static void parse_stats(conn_t *conn, struct stats *stats, unsigned idx) if (buf[0] == '\t') { parse_queue(conn, buf, sizeof(buf) - 1, idx); continue; - } else if (val) + } else if (val) { *val++ = '\0'; + } if (!strcmp("MEMSTATS", buf)) { parse_memstats(val, stats); continue; @@ -1277,8 +1333,9 @@ static void parse_stats(conn_t *conn, struct stats *stats, unsigned idx) stats->stats_unsupp = 1; break; } - for (j = 1; j < strlen(buf); j++) + for (j = 1; j < strlen(buf); j++) { buf[j] = tolower(buf[j]); + } /* mvwprintw(win, i, 0, "%s", buf); if(!val) { @@ -1300,8 +1357,9 @@ static void parse_stats(conn_t *conn, struct stats *stats, unsigned idx) } if (!strcmp("Threads", buf)) { unsigned live, idle, max; - if (sscanf(val, " live %u idle %u max %u", &live, &idle, &max) != 3) + if (sscanf(val, " live %u idle %u max %u", &live, &idle, &max) != 3) { continue; + } if (primary) { stats->prim_live = live; stats->prim_idle = idle; @@ -1313,8 +1371,9 @@ static void parse_stats(conn_t *conn, struct stats *stats, unsigned idx) stats->max += max; } else if (!strcmp("Queue", buf)) { unsigned len; - if (sscanf(val, "%u", &len) != 1) + if (sscanf(val, "%u", &len) != 1) { continue; + } stats->current_q += len; } } @@ -1324,16 +1383,20 @@ static int read_version(conn_t *conn) { char buf[1024]; unsigned i; - if (!recv_line(conn, buf, sizeof(buf))) + if (!recv_line(conn, buf, sizeof(buf))) { return -1; - if (!strcmp(buf, "UNKNOWN COMMAND\n")) + } + if (!strcmp(buf, "UNKNOWN COMMAND\n")) { return -2; + } conn->version = strdup(buf); OOM_CHECK(conn->version); - for (i = 0; i < strlen(conn->version); i++) - if (conn->version[i] == '\n') + for (i = 0; i < strlen(conn->version); i++) { + if (conn->version[i] == '\n') { conn->version[i] = ' '; + } + } return 0; } @@ -1390,8 +1453,9 @@ static void setup_connections(int argc, char *argv[]) exit(0); } - if (optget(opts, "defaultcolors")->enabled) + if (optget(opts, "defaultcolors")->enabled) { default_colors = 1; + } memset(&global, 0, sizeof(global)); if (!opts->filename || !opts->filename[0]) { @@ -1567,25 +1631,28 @@ int main(int argc, char *argv[]) break; case 'R': case 'r': - for (i = 0; i < global.num_clamd; i++) + for (i = 0; i < global.num_clamd; i++) { global.all_stats[i].biggest_queue = 1; + } biggest_mem = 0; break; case KEY_UP: if (global.num_clamd > 1) { - if (detail_selected == -1) + if (detail_selected == -1) { detail_selected = global.num_clamd - 1; - else + } else { --detail_selected; + } } break; case KEY_DOWN: if (global.num_clamd > 1) { - if (detail_selected == -1) + if (detail_selected == -1) { detail_selected = 0; - else { - if ((unsigned)++detail_selected >= global.num_clamd) + } else { + if ((unsigned)++detail_selected >= global.num_clamd) { detail_selected = -1; + } } } break; @@ -1597,22 +1664,25 @@ int main(int argc, char *argv[]) for (i = 0; i < global.num_clamd; i++) { unsigned biggest_q; struct stats *stats = &global.all_stats[i]; - if (global.conn[i].sd != -1) + if (global.conn[i].sd != -1) { send_string(&global.conn[i], "nSTATS\n"); + } biggest_q = stats->biggest_queue; memset(stats, 0, sizeof(*stats)); stats->biggest_queue = biggest_q; parse_stats(&global.conn[i], stats, i); } - if (global.tasks) + if (global.tasks) { qsort(global.tasks, global.n, sizeof(*global.tasks), tasks_compare); + } tv_last = tv; } /* always show, so that screen resizes take effect instantly*/ output_all(); for (i = 0; i < global.num_clamd; i++) { - if (global.conn[i].sd == -1) + if (global.conn[i].sd == -1) { reconnect(&global.conn[i]); + } } } while (toupper(ch = getch()) != 'Q'); free_global_stats(); diff --git a/clamonacc/CMakeLists.txt b/clamonacc/CMakeLists.txt index 091340abcf..226140abf1 100644 --- a/clamonacc/CMakeLists.txt +++ b/clamonacc/CMakeLists.txt @@ -45,6 +45,12 @@ target_include_directories( clamonacc set_target_properties( clamonacc PROPERTIES COMPILE_FLAGS "${WARNCFLAGS}" ) +if(CLANG_TIDY) + set_target_properties( clamonacc PROPERTIES + C_CLANG_TIDY "${CLANG_TIDY_PROPERTY}" + C_CLANG_TIDY_EXPORT_FIXES_DIR "${CMAKE_BINARY_DIR}/clang-tidy-fixes" ) +endif() + target_link_libraries( clamonacc PRIVATE ClamAV::libclamav diff --git a/clamonacc/client/client.c b/clamonacc/client/client.c index 316a2ac67c..3c0f3151fe 100644 --- a/clamonacc/client/client.c +++ b/clamonacc/client/client.c @@ -253,15 +253,17 @@ int16_t onas_ping_clamd(struct onas_context **ctx) if (i + 1 < attempts) { if (optget((*ctx)->opts, "wait")->enabled) { - if (interval == 1) + if (interval == 1) { logg(LOGG_DEBUG, "Will try again in %lu second\n", interval); - else + } else { logg(LOGG_DEBUG, "Will try again in %lu seconds\n", interval); + } } else { - if (interval == 1) + if (interval == 1) { logg(LOGG_INFO, "PINGing again in %lu second\n", interval); - else + } else { logg(LOGG_INFO, "PINGing again in %lu seconds\n", interval); + } } sleep(interval); } diff --git a/clamonacc/client/communication.c b/clamonacc/client/communication.c index 22436f676f..7fb3b05724 100644 --- a/clamonacc/client/communication.c +++ b/clamonacc/client/communication.c @@ -272,10 +272,11 @@ int onas_fd_recvln(struct onas_rcvln *rcv_data, char **ret_bol, char **ret_eol, } if (rcv_data->retlen || rcv_data->curr != rcv_data->buf) { *rcv_data->curr = '\0'; - if (strcmp(rcv_data->buf, "UNKNOWN COMMAND\n")) + if (strcmp(rcv_data->buf, "UNKNOWN COMMAND\n")) { logg(LOGG_ERROR, "Communication error\n"); - else + } else { logg(LOGG_ERROR, "Command rejected by clamd (wrong clamd version?)\n"); + } return -1; } return 0; @@ -286,12 +287,15 @@ int onas_fd_recvln(struct onas_rcvln *rcv_data, char **ret_bol, char **ret_eol, eol++; rcv_data->retlen -= eol - rcv_data->curr; *ret_bol = rcv_data->lnstart; - if (ret_eol) *ret_eol = eol; + if (ret_eol) { + *ret_eol = eol; + } ret = eol - rcv_data->lnstart; - if (rcv_data->retlen) + if (rcv_data->retlen) { rcv_data->lnstart = rcv_data->curr = eol; - else + } else { rcv_data->lnstart = rcv_data->curr = rcv_data->buf; + } return ret; } rcv_data->retlen += rcv_data->curr - rcv_data->lnstart; diff --git a/clamonacc/client/socket.c b/clamonacc/client/socket.c index d15cc8b638..38427c6405 100644 --- a/clamonacc/client/socket.c +++ b/clamonacc/client/socket.c @@ -80,9 +80,9 @@ int onas_get_sockd() int sockd = 0; if (onas_sock.written && (sockd = socket(AF_UNIX, SOCK_STREAM, 0)) >= 0) { - if (connect(sockd, (struct sockaddr *)&onas_sock.sock, sizeof(onas_sock.sock)) == 0) + if (connect(sockd, (struct sockaddr *)&onas_sock.sock, sizeof(onas_sock.sock)) == 0) { return sockd; - else { + } else { logg(LOGG_ERROR, "ClamSock: Could not connect to clamd on LocalSocket \n"); closesocket(sockd); } diff --git a/clamonacc/inotif/hash.c b/clamonacc/inotif/hash.c index 1f83b74c01..c1dba85743 100644 --- a/clamonacc/inotif/hash.c +++ b/clamonacc/inotif/hash.c @@ -134,10 +134,14 @@ static inline int onas_hash(const char *key, size_t keylen, uint32_t size) int onas_ht_init(struct onas_ht **ht, uint32_t size) { - if (size == 0 || (size & (~size + 1)) != size) return CL_EARG; + if (size == 0 || (size & (~size + 1)) != size) { + return CL_EARG; + } *ht = (struct onas_ht *)malloc(sizeof(struct onas_ht)); - if (!(*ht)) return CL_EMEM; + if (!(*ht)) { + return CL_EMEM; + } **ht = (struct onas_ht){ .htable = NULL, @@ -158,7 +162,9 @@ int onas_ht_init(struct onas_ht **ht, uint32_t size) void onas_free_ht(struct onas_ht *ht) { - if (!ht || ht->size == 0) return; + if (!ht || ht->size == 0) { + return; + } if (!ht->htable) { free(ht); @@ -183,7 +189,9 @@ static struct onas_bucket *onas_bucket_init() { struct onas_bucket *bckt = (struct onas_bucket *)malloc(sizeof(struct onas_bucket)); - if (!bckt) return NULL; + if (!bckt) { + return NULL; + } *bckt = (struct onas_bucket){ .size = 0, @@ -196,7 +204,9 @@ static struct onas_bucket *onas_bucket_init() static void onas_free_bucket(struct onas_bucket *bckt) { - if (!bckt) return; + if (!bckt) { + return; + } uint32_t i = 0; struct onas_element *curr = NULL; @@ -219,7 +229,9 @@ struct onas_element *onas_element_init(struct onas_hnode *value, const char *key { struct onas_element *elem = (struct onas_element *)malloc(sizeof(struct onas_element)); - if (!elem) return NULL; + if (!elem) { + return NULL; + } *elem = (struct onas_element){ .key = key, @@ -234,7 +246,9 @@ struct onas_element *onas_element_init(struct onas_hnode *value, const char *key void onas_free_element(struct onas_element *elem) { - if (!elem) return; + if (!elem) { + return; + } onas_free_hashnode(elem->data); @@ -249,7 +263,9 @@ void onas_free_element(struct onas_element *elem) int onas_ht_insert(struct onas_ht *ht, struct onas_element *elem) { - if (!ht || !elem || !elem->key) return CL_ENULLARG; + if (!ht || !elem || !elem->key) { + return CL_ENULLARG; + } int idx = onas_hash(elem->key, elem->klen, ht->size); struct onas_bucket *bckt = ht->htable[idx]; @@ -278,16 +294,20 @@ int onas_ht_insert(struct onas_ht *ht, struct onas_element *elem) bsize = bckt->size; ret = onas_bucket_insert(bckt, elem); - if (ret == CL_SUCCESS) - if (bsize < bckt->size) + if (ret == CL_SUCCESS) { + if (bsize < bckt->size) { ht->nbckts++; + } + } return ret; } static int onas_bucket_insert(struct onas_bucket *bckt, struct onas_element *elem) { - if (!bckt || !elem) return CL_ENULLARG; + if (!bckt || !elem) { + return CL_ENULLARG; + } if (bckt->size == 0) { bckt->head = elem; @@ -314,13 +334,19 @@ static int onas_bucket_insert(struct onas_bucket *bckt, struct onas_element *ele int onas_ht_get(struct onas_ht *ht, const char *key, size_t klen, struct onas_element **elem) { - if (elem) *elem = NULL; + if (elem) { + *elem = NULL; + } - if (!ht || !key || klen <= 0) return CL_ENULLARG; + if (!ht || !key || klen <= 0) { + return CL_ENULLARG; + } struct onas_bucket *bckt = ht->htable[onas_hash(key, klen, ht->size)]; - if (!bckt || bckt->size == 0) return CL_EARG; + if (!bckt || bckt->size == 0) { + return CL_EARG; + } struct onas_element *curr = bckt->head; @@ -328,9 +354,13 @@ int onas_ht_get(struct onas_ht *ht, const char *key, size_t klen, struct onas_el curr = curr->next; } - if (!curr) return CL_EARG; + if (!curr) { + return CL_EARG; + } - if (elem) *elem = curr; + if (elem) { + *elem = curr; + } return CL_SUCCESS; } @@ -340,27 +370,37 @@ int onas_ht_get(struct onas_ht *ht, const char *key, size_t klen, struct onas_el */ int onas_ht_remove(struct onas_ht *ht, const char *key, size_t klen, struct onas_element **relem) { - if (!ht || !key || klen <= 0) return CL_ENULLARG; + if (!ht || !key || klen <= 0) { + return CL_ENULLARG; + } struct onas_bucket *bckt = ht->htable[onas_hash(key, klen, ht->size)]; - if (!bckt) return CL_EARG; + if (!bckt) { + return CL_EARG; + } struct onas_element *elem = NULL; onas_ht_get(ht, key, klen, &elem); - if (!elem) return CL_EARG; + if (!elem) { + return CL_EARG; + } int ret = onas_bucket_remove(bckt, elem); - if (relem) *relem = elem; + if (relem) { + *relem = elem; + } return ret; } static int onas_bucket_remove(struct onas_bucket *bckt, struct onas_element *elem) { - if (!bckt || !elem) return CL_ENULLARG; + if (!bckt || !elem) { + return CL_ENULLARG; + } struct onas_element *curr = bckt->head; @@ -368,16 +408,22 @@ static int onas_bucket_remove(struct onas_bucket *bckt, struct onas_element *ele curr = curr->next; } - if (!curr) return CL_EARG; + if (!curr) { + return CL_EARG; + } if (bckt->head == elem) { bckt->head = elem->next; - if (bckt->head) bckt->head->prev = NULL; + if (bckt->head) { + bckt->head->prev = NULL; + } elem->next = NULL; } else if (bckt->tail == elem) { bckt->tail = elem->prev; - if (bckt->tail) bckt->tail->next = NULL; + if (bckt->tail) { + bckt->tail->next = NULL; + } elem->prev = NULL; } else { @@ -460,7 +506,9 @@ static struct onas_lnode *onas_listnode_init(void) */ void onas_free_hashnode(struct onas_hnode *hnode) { - if (!hnode) return; + if (!hnode) { + return; + } onas_free_dirlist(hnode->childhead); hnode->childhead = NULL; @@ -481,7 +529,9 @@ void onas_free_hashnode(struct onas_hnode *hnode) */ void onas_free_dirlist(struct onas_lnode *head) { - if (!head) return; + if (!head) { + return; + } struct onas_lnode *curr = head; struct onas_lnode *tmp = curr; @@ -499,7 +549,9 @@ void onas_free_dirlist(struct onas_lnode *head) */ void onas_free_listnode(struct onas_lnode *lnode) { - if (!lnode) return; + if (!lnode) { + return; + } lnode->next = NULL; lnode->prev = NULL; @@ -517,10 +569,14 @@ void onas_free_listnode(struct onas_lnode *lnode) */ static int onas_add_hashnode_child(struct onas_hnode *node, const char *dirname) { - if (!node || !dirname) return CL_ENULLARG; + if (!node || !dirname) { + return CL_ENULLARG; + } struct onas_lnode *child = onas_listnode_init(); - if (!child) return CL_EMEM; + if (!child) { + return CL_EMEM; + } size_t n = strlen(dirname); child->dirname = CLI_STRNDUP(dirname, n); @@ -535,7 +591,9 @@ static int onas_add_hashnode_child(struct onas_hnode *node, const char *dirname) */ int onas_add_listnode(struct onas_lnode *tail, struct onas_lnode *node) { - if (!tail || !node) return CL_ENULLARG; + if (!tail || !node) { + return CL_ENULLARG; + } struct onas_lnode *tmp = tail->prev; @@ -553,7 +611,9 @@ int onas_add_listnode(struct onas_lnode *tail, struct onas_lnode *node) */ cl_error_t onas_rm_listnode(struct onas_lnode *head, const char *dirname) { - if (!dirname || !head) return CL_ENULLARG; + if (!dirname || !head) { + return CL_ENULLARG; + } struct onas_lnode *curr = head; size_t n = strlen(dirname); @@ -563,10 +623,12 @@ cl_error_t onas_rm_listnode(struct onas_lnode *head, const char *dirname) logg(LOGG_DEBUG, "ClamHash: node's directory name is NULL!\n"); return CL_ERROR; } else if (!strncmp(curr->dirname, dirname, n)) { - if (curr->next != NULL) + if (curr->next != NULL) { curr->next->prev = curr->prev; - if (curr->prev != NULL) + } + if (curr->prev != NULL) { curr->prev->next = curr->next; + } onas_free_listnode(curr); return CL_SUCCESS; @@ -583,7 +645,9 @@ cl_error_t onas_rm_listnode(struct onas_lnode *head, const char *dirname) */ inline static char *onas_get_parent(const char *pathname, size_t len) { - if (!pathname || len <= 1) return NULL; + if (!pathname || len <= 1) { + return NULL; + } int idx = len - 2; char *ret = NULL; @@ -610,7 +674,9 @@ inline static char *onas_get_parent(const char *pathname, size_t len) */ inline static int onas_get_dirname_idx(const char *pathname, size_t len) { - if (!pathname || len <= 1) return -1; + if (!pathname || len <= 1) { + return -1; + } int idx = len - 2; @@ -618,8 +684,9 @@ inline static int onas_get_dirname_idx(const char *pathname, size_t len) idx--; } - if (pathname[idx] == '/') + if (pathname[idx] == '/') { return idx + 1; + } return idx; } @@ -636,16 +703,22 @@ inline static int onas_get_dirname_idx(const char *pathname, size_t len) int onas_ht_rm_child(struct onas_ht *ht, const char *prntpath, size_t prntlen, const char *childpath, size_t childlen) { - if (!ht || !prntpath || prntlen <= 0 || !childpath || childlen <= 1) return CL_ENULLARG; + if (!ht || !prntpath || prntlen <= 0 || !childpath || childlen <= 1) { + return CL_ENULLARG; + } struct onas_element *elem = NULL; struct onas_hnode *hnode = NULL; int idx = onas_get_dirname_idx(childpath, childlen); int ret = 0; - if (idx <= 0) return CL_SUCCESS; + if (idx <= 0) { + return CL_SUCCESS; + } - if (onas_ht_get(ht, prntpath, prntlen, &elem) != CL_SUCCESS) return CL_EARG; + if (onas_ht_get(ht, prntpath, prntlen, &elem) != CL_SUCCESS) { + return CL_EARG; + } hnode = elem->data; @@ -667,15 +740,21 @@ int onas_ht_rm_child(struct onas_ht *ht, const char *prntpath, size_t prntlen, c */ int onas_ht_add_child(struct onas_ht *ht, const char *prntpath, size_t prntlen, const char *childpath, size_t childlen) { - if (!ht || !prntpath || prntlen <= 0 || !childpath || childlen <= 1) return CL_ENULLARG; + if (!ht || !prntpath || prntlen <= 0 || !childpath || childlen <= 1) { + return CL_ENULLARG; + } struct onas_element *elem = NULL; struct onas_hnode *hnode = NULL; int idx = onas_get_dirname_idx(childpath, childlen); - if (idx <= 0) return CL_SUCCESS; + if (idx <= 0) { + return CL_SUCCESS; + } - if (onas_ht_get(ht, prntpath, prntlen, &elem)) return CL_EARG; + if (onas_ht_get(ht, prntpath, prntlen, &elem)) { + return CL_EARG; + } hnode = elem->data; return onas_add_hashnode_child(hnode, &(childpath[idx])); @@ -688,7 +767,9 @@ int onas_ht_add_child(struct onas_ht *ht, const char *prntpath, size_t prntlen, */ int onas_ht_add_hierarchy(struct onas_ht *ht, const char *pathname) { - if (!ht || !pathname) return CL_ENULLARG; + if (!ht || !pathname) { + return CL_ENULLARG; + } int ret = 0; FTS *ftsp = NULL; @@ -698,7 +779,9 @@ int onas_ht_add_hierarchy(struct onas_ht *ht, const char *pathname) size_t len = strlen(pathname); char *prnt = onas_get_parent(pathname, len); - if (prnt) onas_ht_add_child(ht, prnt, strlen(prnt), pathname, len); + if (prnt) { + onas_ht_add_child(ht, prnt, strlen(prnt), pathname, len); + } free(prnt); char *const pathargv[] = {(char *)pathname, NULL}; @@ -725,10 +808,11 @@ int onas_ht_add_hierarchy(struct onas_ht *ht, const char *pathname) hnode->pathname = CLI_STRNDUP(curr->fts_path, hnode->pathlen); hnode->prnt_pathname = onas_get_parent(hnode->pathname, hnode->pathlen); - if (hnode->prnt_pathname) + if (hnode->prnt_pathname) { hnode->prnt_pathlen = strlen(hnode->prnt_pathname); - else + } else { hnode->prnt_pathlen = 0; + } break; default: continue; @@ -780,21 +864,27 @@ int onas_ht_add_hierarchy(struct onas_ht *ht, const char *pathname) */ int onas_ht_rm_hierarchy(struct onas_ht *ht, const char *pathname, size_t len, int level) { - if (!ht || !pathname || len <= 0) return CL_ENULLARG; + if (!ht || !pathname || len <= 0) { + return CL_ENULLARG; + } struct onas_hnode *hnode = NULL; struct onas_element *elem = NULL; char *prntname = NULL; size_t prntlen = 0; - if (onas_ht_get(ht, pathname, len, &elem)) return CL_EARG; + if (onas_ht_get(ht, pathname, len, &elem)) { + return CL_EARG; + } hnode = elem->data; struct onas_lnode *curr = hnode->childhead; if (level == 0) { - if (!(prntname = onas_get_parent(pathname, len))) return CL_EARG; + if (!(prntname = onas_get_parent(pathname, len))) { + return CL_EARG; + } prntlen = strlen(prntname); if (onas_ht_rm_child(ht, prntname, prntlen, pathname, len)) { @@ -810,12 +900,14 @@ int onas_ht_rm_hierarchy(struct onas_ht *ht, const char *pathname, size_t len, i size_t size = len + strlen(curr->dirname) + 2; char *child_path = (char *)malloc(size); - if (child_path == NULL) + if (child_path == NULL) { return CL_EMEM; - if (hnode->pathname[len - 1] == '/') + } + if (hnode->pathname[len - 1] == '/') { snprintf(child_path, size, "%s%s", hnode->pathname, curr->dirname); - else + } else { snprintf(child_path, size, "%s/%s", hnode->pathname, curr->dirname); + } onas_ht_rm_hierarchy(ht, child_path, size, level + 1); free(child_path); } diff --git a/clamonacc/inotif/inotif.c b/clamonacc/inotif/inotif.c index c8576d09ac..37088c15a9 100644 --- a/clamonacc/inotif/inotif.c +++ b/clamonacc/inotif/inotif.c @@ -91,8 +91,9 @@ extern pthread_t ddd_pid; static int onas_ddd_init_ht(uint32_t ht_size) { - if (ht_size <= 0) + if (ht_size <= 0) { ht_size = ONAS_DEFAULT_HT_SIZE; + } return onas_ht_init(&ddd_ht, ht_size); } @@ -103,10 +104,14 @@ static int onas_ddd_init_ht(uint32_t ht_size) static int onas_ddd_init_wdlt(uint64_t nwatches) { - if (nwatches <= 0) return CL_EARG; + if (nwatches <= 0) { + return CL_EARG; + } wdlt = (char **)calloc(nwatches << 1, sizeof(char *)); - if (!wdlt) return CL_EMEM; + if (!wdlt) { + return CL_EMEM; + } wdlt_len = nwatches << 1; @@ -147,11 +152,15 @@ int onas_ddd_init(uint64_t nwatches, size_t ht_size) nwatches = 0; nwfd = open(nwatch_file, O_RDONLY); - if (nwfd < 0) return CL_EOPEN; + if (nwfd < 0) { + return CL_EOPEN; + } ret = read(nwfd, nwatch_str, MAX_WATCH_LEN); close(nwfd); - if (ret < 0) return CL_EREAD; + if (ret < 0) { + return CL_EREAD; + } tmp = strtol(nwatch_str, &p, 10); if (tmp < 0 || tmp == LONG_MAX) { @@ -162,10 +171,14 @@ int onas_ddd_init(uint64_t nwatches, size_t ht_size) } ret = onas_ddd_init_wdlt(nwatches); - if (ret) return ret; + if (ret) { + return ret; + } ret = onas_ddd_init_ht(ht_size); - if (ret) return ret; + if (ret) { + return ret; + } return CL_SUCCESS; } @@ -175,16 +188,22 @@ int onas_ddd_init(uint64_t nwatches, size_t ht_size) */ static int onas_ddd_watch(const char *pathname, int fan_fd, uint64_t fan_mask, int in_fd, uint64_t in_mask) { - if (!pathname || fan_fd <= 0 || in_fd <= 0) return CL_ENULLARG; + if (!pathname || fan_fd <= 0 || in_fd <= 0) { + return CL_ENULLARG; + } int ret = CL_SUCCESS; size_t len = strlen(pathname); ret = onas_ddd_watch_hierarchy(pathname, len, in_fd, in_mask, ONAS_IN); - if (ret) return ret; + if (ret) { + return ret; + } ret = onas_ddd_watch_hierarchy(pathname, len, fan_fd, fan_mask, ONAS_FAN); - if (ret) return ret; + if (ret) { + return ret; + } return CL_SUCCESS; } @@ -201,9 +220,13 @@ static int onas_ddd_watch(const char *pathname, int fan_fd, uint64_t fan_mask, i static int onas_ddd_watch_hierarchy(const char *pathname, size_t len, int fd, uint64_t mask, uint32_t type) { - if (!pathname || fd <= 0 || !type) return CL_ENULLARG; + if (!pathname || fd <= 0 || !type) { + return CL_ENULLARG; + } - if (type == (ONAS_IN | ONAS_FAN)) return CL_EARG; + if (type == (ONAS_IN | ONAS_FAN)) { + return CL_EARG; + } struct onas_hnode *hnode = NULL; struct onas_element *elem = NULL; @@ -256,10 +279,11 @@ static int onas_ddd_watch_hierarchy(const char *pathname, size_t len, int fd, ui return CL_EMEM; } - if (hnode->pathname[len - 1] == '/') + if (hnode->pathname[len - 1] == '/') { snprintf(child_path, --size, "%s%s", hnode->pathname, curr->dirname); - else + } else { snprintf(child_path, size, "%s/%s", hnode->pathname, curr->dirname); + } if (onas_ddd_watch_hierarchy(child_path, strlen(child_path), fd, mask, type)) { logg(LOGG_ERROR, "ClamInotif: issue when adding watch for %s\n", child_path); @@ -276,16 +300,22 @@ static int onas_ddd_watch_hierarchy(const char *pathname, size_t len, int fd, ui */ static int onas_ddd_unwatch(const char *pathname, int fan_fd, int in_fd) { - if (!pathname || fan_fd <= 0 || in_fd <= 0) return CL_ENULLARG; + if (!pathname || fan_fd <= 0 || in_fd <= 0) { + return CL_ENULLARG; + } int ret = CL_SUCCESS; size_t len = strlen(pathname); ret = onas_ddd_unwatch_hierarchy(pathname, len, in_fd, ONAS_IN); - if (ret) return ret; + if (ret) { + return ret; + } ret = onas_ddd_unwatch_hierarchy(pathname, len, fan_fd, ONAS_FAN); - if (ret) return ret; + if (ret) { + return ret; + } return CL_SUCCESS; } @@ -301,22 +331,30 @@ static int onas_ddd_unwatch(const char *pathname, int fan_fd, int in_fd) static int onas_ddd_unwatch_hierarchy(const char *pathname, size_t len, int fd, uint32_t type) { - if (!pathname || fd <= 0 || !type) return CL_ENULLARG; + if (!pathname || fd <= 0 || !type) { + return CL_ENULLARG; + } - if (type == (ONAS_IN | ONAS_FAN)) return CL_EARG; + if (type == (ONAS_IN | ONAS_FAN)) { + return CL_EARG; + } struct onas_hnode *hnode = NULL; struct onas_element *elem = NULL; int wd = 0; - if (onas_ht_get(ddd_ht, pathname, len, &elem)) return CL_EARG; + if (onas_ht_get(ddd_ht, pathname, len, &elem)) { + return CL_EARG; + } hnode = elem->data; if (type & ONAS_IN) { wd = hnode->wd; - if (!inotify_rm_watch(fd, wd) && errno != ENOENT) return CL_EARG; + if (!inotify_rm_watch(fd, wd) && errno != ENOENT) { + return CL_EARG; + } /* Unlink the hash node from the watch descriptor lookup table */ hnode->wd = 0; @@ -324,7 +362,9 @@ static int onas_ddd_unwatch_hierarchy(const char *pathname, size_t len, int fd, hnode->watched = ONAS_STOPWATCH; } else if (type & ONAS_FAN) { - if (fanotify_mark(fd, FAN_MARK_REMOVE, 0, AT_FDCWD, hnode->pathname) < 0) return CL_EARG; + if (fanotify_mark(fd, FAN_MARK_REMOVE, 0, AT_FDCWD, hnode->pathname) < 0) { + return CL_EARG; + } hnode->watched = ONAS_STOPWATCH; } else { return CL_EARG; @@ -338,12 +378,14 @@ static int onas_ddd_unwatch_hierarchy(const char *pathname, size_t len, int fd, size_t size = len + strlen(curr->dirname) + 2; char *child_path = (char *)malloc(size); - if (child_path == NULL) + if (child_path == NULL) { return CL_EMEM; - if (hnode->pathname[len - 1] == '/') + } + if (hnode->pathname[len - 1] == '/') { snprintf(child_path, --size, "%s%s", hnode->pathname, curr->dirname); - else + } else { snprintf(child_path, size, "%s/%s", hnode->pathname, curr->dirname); + } onas_ddd_unwatch_hierarchy(child_path, strlen(child_path), fd, type); free(child_path); @@ -365,7 +407,9 @@ cl_error_t onas_enable_inotif_ddd(struct onas_context **ctx) if ((*ctx)->ddd_enabled) { do { - if (pthread_attr_init(&ddd_attr)) break; + if (pthread_attr_init(&ddd_attr)) { + break; + } pthread_attr_setdetachstate(&ddd_attr, PTHREAD_CREATE_JOINABLE); thread_started = pthread_create(&ddd_pid, &ddd_attr, onas_ddd_th, *ctx); } while (0); @@ -679,10 +723,11 @@ void *onas_ddd_th(void *arg) event = (const struct inotify_event *)p; wd = event->wd; - if (wd >= 0) + if (wd >= 0) { path = wdlt[wd]; - else + } else { path = NULL; + } child = event->name; if (path == NULL) { @@ -744,8 +789,12 @@ static void onas_ddd_handle_in_delete(struct onas_context *ctx, { struct stat s; - if (stat(child_path, &s) == 0 && S_ISREG(s.st_mode)) return; - if (!(event->mask & IN_ISDIR)) return; + if (stat(child_path, &s) == 0 && S_ISREG(s.st_mode)) { + return; + } + if (!(event->mask & IN_ISDIR)) { + return; + } logg(LOGG_DEBUG, "ClamInotif: DELETE - removing %s from %s with wd:%d\n", child_path, path, wd); onas_ddd_unwatch(child_path, ctx->fan_fd, onas_in_fd); @@ -759,8 +808,12 @@ static void onas_ddd_handle_in_moved_from(struct onas_context *ctx, { struct stat s; - if (stat(child_path, &s) == 0 && S_ISREG(s.st_mode)) return; - if (!(event->mask & IN_ISDIR)) return; + if (stat(child_path, &s) == 0 && S_ISREG(s.st_mode)) { + return; + } + if (!(event->mask & IN_ISDIR)) { + return; + } logg(LOGG_DEBUG, "ClamInotif: MOVED_FROM - removing %s from %s with wd:%d\n", child_path, path, wd); onas_ddd_unwatch(child_path, ctx->fan_fd, onas_in_fd); @@ -818,8 +871,12 @@ static void onas_ddd_handle_in_moved_to(struct onas_context *ctx, onas_ddd_watch(child_path, ctx->fan_fd, ctx->fan_mask, onas_in_fd, in_mask); } } else { - if (stat(child_path, &s) == 0 && S_ISREG(s.st_mode)) return; - if (!(event->mask & IN_ISDIR)) return; + if (stat(child_path, &s) == 0 && S_ISREG(s.st_mode)) { + return; + } + if (!(event->mask & IN_ISDIR)) { + return; + } logg(LOGG_DEBUG, "ClamInotif: MOVED_TO - adding %s to %s with wd:%d\n", child_path, path, wd); onas_ht_add_hierarchy(ddd_ht, child_path); diff --git a/clamonacc/misc/utils.c b/clamonacc/misc/utils.c index 9d394b309e..1c8d90034b 100644 --- a/clamonacc/misc/utils.c +++ b/clamonacc/misc/utils.c @@ -71,8 +71,9 @@ int onas_fan_checkowner(int pid, const struct optstruct *opts) opt_uname = optget(opts, "OnAccessExcludeUname"); /* we can return immediately if no uid exclusions were requested */ - if (!(opt->enabled || opt_root->enabled || opt_uname->enabled)) + if (!(opt->enabled || opt_root->enabled || opt_uname->enabled)) { return CHK_CLEAN; + } /* perform exclusion checks if we can stat OK */ snprintf(path, sizeof(path), "/proc/%u", pid); @@ -80,8 +81,9 @@ int onas_fan_checkowner(int pid, const struct optstruct *opts) /* check all our non-root UIDs first */ if (opt->enabled) { while (opt) { - if (opt->numarg == (long long)sb.st_uid) + if (opt->numarg == (long long)sb.st_uid) { return CHK_FOUND; + } opt = opt->nextarg; } } @@ -132,8 +134,9 @@ int onas_fan_checkowner(int pid, const struct optstruct *opts) } /* finally check root UID */ if (opt_root->enabled) { - if (0 == (long long)sb.st_uid) + if (0 == (long long)sb.st_uid) { return CHK_FOUND; + } } } else if (errno == EACCES) { logg(LOGG_DEBUG, "ClamMisc: permission denied to stat /proc/%d to exclude UIDs... perhaps SELinux denial?\n", pid); diff --git a/clamonacc/scan/onas_queue.c b/clamonacc/scan/onas_queue.c index 9d61e292e1..316917be29 100644 --- a/clamonacc/scan/onas_queue.c +++ b/clamonacc/scan/onas_queue.c @@ -223,8 +223,9 @@ static int onas_consume_event(threadpool thpool) cl_error_t onas_queue_event(struct onas_scan_event *event_data) { struct onas_event_queue_node *node = NULL; - if (CL_EMEM == onas_new_event_queue_node(&node)) + if (CL_EMEM == onas_new_event_queue_node(&node)) { return CL_EMEM; + } pthread_mutex_lock(&onas_queue_lock); node->next = g_onas_event_queue_tail; diff --git a/clamscan/CMakeLists.txt b/clamscan/CMakeLists.txt index 64608c0df7..0487e32922 100644 --- a/clamscan/CMakeLists.txt +++ b/clamscan/CMakeLists.txt @@ -29,6 +29,12 @@ target_include_directories( clamscan ) set_target_properties( clamscan PROPERTIES COMPILE_FLAGS "${WARNCFLAGS}" ) +if(CLANG_TIDY) + set_target_properties( clamscan PROPERTIES + C_CLANG_TIDY "${CLANG_TIDY_PROPERTY}" + C_CLANG_TIDY_EXPORT_FIXES_DIR "${CMAKE_BINARY_DIR}/clang-tidy-fixes" ) +endif() + if (APPLE AND CLAMAV_SIGN_FILE) set_target_properties( clamscan PROPERTIES XCODE_ATTRIBUTE_CODE_SIGN_IDENTITY ${CODE_SIGN_IDENTITY} diff --git a/clamscan/clamscan.c b/clamscan/clamscan.c index 00402c7515..045120846a 100644 --- a/clamscan/clamscan.c +++ b/clamscan/clamscan.c @@ -74,8 +74,9 @@ int main(int argc, char **argv) struct optstruct *opts; const struct optstruct *opt; - if (check_flevel()) + if (check_flevel()) { exit(2); + } #if !defined(_WIN32) if (!setlocale(LC_CTYPE, "")) { @@ -100,11 +101,13 @@ int main(int argc, char **argv) logg_verbose = 1; } - if (optget(opts, "quiet")->enabled) + if (optget(opts, "quiet")->enabled) { mprintf_quiet = 1; + } - if (optget(opts, "stdout")->enabled) + if (optget(opts, "stdout")->enabled) { mprintf_stdout = 1; + } if (optget(opts, "debug")->enabled) { #if defined(C_LINUX) @@ -112,8 +115,9 @@ int main(int argc, char **argv) struct rlimit rlim; rlim.rlim_cur = rlim.rlim_max = RLIM_INFINITY; - if (setrlimit(RLIMIT_CORE, &rlim) < 0) + if (setrlimit(RLIMIT_CORE, &rlim) < 0) { perror("setrlimit"); + } #endif cl_debug(); /* enable debug messages */ } @@ -134,17 +138,21 @@ int main(int argc, char **argv) return 0; } - if (optget(opts, "recursive")->enabled) + if (optget(opts, "recursive")->enabled) { recursion = 1; + } - if (optget(opts, "infected")->enabled) + if (optget(opts, "infected")->enabled) { printinfected = 1; + } - if (optget(opts, "suppress-ok-results")->enabled) + if (optget(opts, "suppress-ok-results")->enabled) { printclean = 0; + } - if (optget(opts, "bell")->enabled) + if (optget(opts, "bell")->enabled) { bell = 1; + } /* initialize logger */ if ((opt = optget(opts, "log"))->enabled) { @@ -154,8 +162,9 @@ int main(int argc, char **argv) optfree(opts); return 2; } - } else + } else { logg_file = NULL; + } if (actsetup(opts)) { optfree(opts); @@ -185,8 +194,9 @@ int main(int argc, char **argv) logg(LOGG_INFO, "Scanned directories: %u\n", info.dirs); logg(LOGG_INFO, "Scanned files: %u\n", info.files); logg(LOGG_INFO, "Infected files: %u\n", info.ifiles); - if (info.errors) + if (info.errors) { logg(LOGG_INFO, "Total errors: %u\n", info.errors); + } if (notremoved) { logg(LOGG_INFO, "Not removed: %u\n", notremoved); } diff --git a/clamscan/manager.c b/clamscan/manager.c index 17c1cbe853..72b58e7a62 100644 --- a/clamscan/manager.c +++ b/clamscan/manager.c @@ -106,18 +106,21 @@ static int checkaccess(const char *path, const char *username, int mode) exit(0); } - if (access(path, mode)) + if (access(path, mode)) { exit(0); - else + } else { exit(1); + } default: wait(&status); - if (WIFEXITED(status) && WEXITSTATUS(status) == 1) + if (WIFEXITED(status) && WEXITSTATUS(status) == 1) { ret = 1; + } } } else { - if (!access(path, mode)) + if (!access(path, mode)) { ret = 1; + } } return ret; @@ -145,12 +148,14 @@ static cl_error_t pre(int fd, const char *type, void *context) UNUSEDPARAM(fd); UNUSEDPARAM(type); - if (!(context)) + if (!(context)) { return CL_CLEAN; + } d = (struct clamscan_cb_data *)context; c = d->chain; - if (c == NULL) + if (c == NULL) { return CL_CLEAN; + } c->level++; @@ -165,11 +170,13 @@ static int print_chain(struct metachain *c, char *str, size_t len) for (i = 0; i < c->nchains - 1; i++) { size_t n = strlen(c->chains[i]); - if (na) + if (na) { str[na++] = '!'; + } - if (n + na + 2 > len) + if (n + na + 2 > len) { break; + } memcpy(str + na, c->chains[i], n); na += n; @@ -190,21 +197,25 @@ static cl_error_t post(int fd, int result, const char *virname, void *context) UNUSEDPARAM(fd); UNUSEDPARAM(result); - if (d != NULL) + if (d != NULL) { c = d->chain; + } if (c && c->nchains) { print_chain(c, str, sizeof(str)); - if (c->level == c->lastadd && !virname) + if (c->level == c->lastadd && !virname) { free(c->chains[--c->nchains]); + } - if (virname && !c->lastvir) + if (virname && !c->lastvir) { c->lastvir = c->level; + } } - if (c) + if (c) { c->level--; + } return CL_CLEAN; } @@ -226,26 +237,30 @@ static cl_error_t meta(const char *container_type, unsigned long fsize_container UNUSEDPARAM(is_encrypted); UNUSEDPARAM(filepos_container); - if (!(context)) + if (!(context)) { return CL_CLEAN; + } d = (struct clamscan_cb_data *)context; c = d->chain; type = (strncmp(container_type, "CL_TYPE_", 8) == 0 ? container_type + 8 : container_type); n = strlen(type) + strlen(filename) + 2; - if (!c) + if (!c) { return CL_CLEAN; + } chain = malloc(n); - if (!chain) + if (!chain) { return CL_CLEAN; + } - if (!strcmp(type, "ANY")) + if (!strcmp(type, "ANY")) { snprintf(chain, n, "%s", filename); - else + } else { snprintf(chain, n, "%s:%s", type, filename); + } if (c->lastadd != c->level) { n = c->nchains + 1; @@ -260,8 +275,9 @@ static cl_error_t meta(const char *container_type, unsigned long fsize_container c->nchains = n; c->lastadd = c->level; } else { - if (c->nchains > 0) + if (c->nchains > 0) { free(c->chains[c->nchains - 1]); + } } if (c->nchains > 0) { @@ -282,12 +298,14 @@ static void clamscan_virus_found_cb(int fd, const char *virname, void *context) UNUSEDPARAM(fd); - if (data == NULL) + if (data == NULL) { return; - if (data->filename != NULL) + } + if (data->filename != NULL) { filename = data->filename; - else + } else { filename = "(filename not set)"; + } logg(LOGG_INFO, "%s: %s FOUND\n", filename, virname); return; } @@ -322,8 +340,9 @@ static void scanfile(const char *filename, struct cl_engine *engine, const struc if ((opt = optget(opts, "exclude"))->enabled) { while (opt) { if (match_regex(filename, opt->strarg) == 1) { - if (!printinfected) + if (!printinfected) { logg(LOGG_INFO, "%s: Excluded\n", filename); + } goto done; } @@ -345,8 +364,9 @@ static void scanfile(const char *filename, struct cl_engine *engine, const struc } if (!included) { - if (!printinfected) + if (!printinfected) { logg(LOGG_INFO, "%s: Excluded\n", filename); + } goto done; } @@ -356,15 +376,17 @@ static void scanfile(const char *filename, struct cl_engine *engine, const struc if (CLAMSTAT(filename, &sb) != -1) { #ifdef C_LINUX if (procdev && sb.st_dev == procdev) { - if (!printinfected) + if (!printinfected) { logg(LOGG_INFO, "%s: Excluded (/proc)\n", filename); + } goto done; } #endif if (!sb.st_size) { - if (!printinfected) + if (!printinfected) { logg(LOGG_INFO, "%s: Empty file\n", filename); + } goto done; } @@ -375,8 +397,9 @@ static void scanfile(const char *filename, struct cl_engine *engine, const struc #ifndef _WIN32 if (geteuid()) { if (checkaccess(filename, NULL, R_OK) != 1) { - if (!printinfected) + if (!printinfected) { logg(LOGG_INFO, "%s: Access denied\n", filename); + } info.errors++; goto done; @@ -423,28 +446,33 @@ static void scanfile(const char *filename, struct cl_engine *engine, const struc info.files++; info.ifiles++; - if (bell) + if (bell) { fprintf(stderr, "\007"); + } } else if (ret == CL_CLEAN) { - if (!printinfected && printclean) + if (!printinfected && printclean) { mprintf(LOGG_INFO, "%s: OK\n", filename); + } info.files++; } else { - if (!printinfected) + if (!printinfected) { logg(LOGG_INFO, "%s: %s ERROR\n", filename, cl_strerror(ret)); + } info.errors++; } - for (i = 0; i < chain.nchains; i++) + for (i = 0; i < chain.nchains; i++) { free(chain.chains[i]); + } free(chain.chains); close(fd); - if (ret == CL_VIRUS && action) + if (ret == CL_VIRUS && action) { action(filename); + } done: if (NULL != real_filename) { @@ -466,8 +494,9 @@ static void scandirs(const char *dirname, struct cl_engine *engine, const struct if ((opt = optget(opts, "exclude-dir"))->enabled) { while (opt) { if (match_regex(dirname, opt->strarg) == 1) { - if (!printinfected) + if (!printinfected) { logg(LOGG_INFO, "%s: Excluded\n", dirname); + } return; } @@ -488,15 +517,17 @@ static void scandirs(const char *dirname, struct cl_engine *engine, const struct } if (!included) { - if (!printinfected) + if (!printinfected) { logg(LOGG_INFO, "%s: Excluded\n", dirname); + } return; } } - if (depth > (unsigned int)optget(opts, "max-dir-recursion")->numarg) + if (depth > (unsigned int)optget(opts, "max-dir-recursion")->numarg) { return; + } dirlnk = optget(opts, "follow-dir-symlinks")->numarg; filelnk = optget(opts, "follow-file-symlinks")->numarg; @@ -514,17 +545,19 @@ static void scandirs(const char *dirname, struct cl_engine *engine, const struct break; } - if (!strcmp(dirname, PATHSEP)) + if (!strcmp(dirname, PATHSEP)) { sprintf(fname, PATHSEP "%s", dent->d_name); - else + } else { sprintf(fname, "%s" PATHSEP "%s", dirname, dent->d_name); + } /* stat the file */ if (LSTAT(fname, &sb) != -1) { if (!optget(opts, "cross-fs")->enabled) { if (sb.st_dev != dev) { - if (!printinfected) + if (!printinfected) { logg(LOGG_INFO, "%s: Excluded\n", fname); + } free(fname); continue; @@ -532,17 +565,20 @@ static void scandirs(const char *dirname, struct cl_engine *engine, const struct } if (S_ISLNK(sb.st_mode)) { if (dirlnk != 2 && filelnk != 2) { - if (!printinfected) + if (!printinfected) { logg(LOGG_INFO, "%s: Symbolic link\n", fname); + } } else if (CLAMSTAT(fname, &sb) != -1) { if (S_ISREG(sb.st_mode) && filelnk == 2) { scanfile(fname, engine, opts, options); } else if (S_ISDIR(sb.st_mode) && dirlnk == 2) { - if (recursion) + if (recursion) { scandirs(fname, engine, opts, options, depth, dev); + } } else { - if (!printinfected) + if (!printinfected) { logg(LOGG_INFO, "%s: Symbolic link\n", fname); + } } } } else if (S_ISREG(sb.st_mode)) { @@ -558,8 +594,9 @@ static void scandirs(const char *dirname, struct cl_engine *engine, const struct } closedir(dd); } else { - if (!printinfected) + if (!printinfected) { logg(LOGG_INFO, "%s: Can't open directory.\n", dirname); + } info.errors++; } @@ -619,14 +656,17 @@ static int scanstdin(const struct cl_engine *engine, struct cl_scan_options *opt if ((ret = cl_scanfile_callback(file, &virname, &info.blocks, engine, options, &data)) == CL_VIRUS) { info.ifiles++; - if (bell) + if (bell) { fprintf(stderr, "\007"); + } } else if (ret == CL_CLEAN) { - if (!printinfected) + if (!printinfected) { mprintf(LOGG_INFO, "stdin: OK\n"); + } } else { - if (!printinfected) + if (!printinfected) { logg(LOGG_INFO, "stdin: %s ERROR\n", cl_strerror(ret)); + } info.errors++; } @@ -1074,24 +1114,29 @@ int scanmanager(const struct optstruct *opts) if (optget(opts, "yara-rules")->enabled) { char *p = optget(opts, "yara-rules")->strarg; if (strcmp(p, "yes")) { - if (!strcmp(p, "only")) + if (!strcmp(p, "only")) { dboptions |= CL_DB_YARA_ONLY; - else if (!strcmp(p, "no")) + } else if (!strcmp(p, "no")) { dboptions |= CL_DB_YARA_EXCLUDE; + } } } - if (optget(opts, "phishing-sigs")->enabled) + if (optget(opts, "phishing-sigs")->enabled) { dboptions |= CL_DB_PHISHING; + } - if (optget(opts, "official-db-only")->enabled) + if (optget(opts, "official-db-only")->enabled) { dboptions |= CL_DB_OFFICIAL_ONLY; + } - if (optget(opts, "phishing-scan-urls")->enabled) + if (optget(opts, "phishing-scan-urls")->enabled) { dboptions |= CL_DB_PHISHING_URLS; + } - if (optget(opts, "bytecode")->enabled) + if (optget(opts, "bytecode")->enabled) { dboptions |= CL_DB_BYTECODE; + } if ((ret = cl_init(CL_INIT_DEFAULT))) { logg(LOGG_ERROR, "Can't initialize libclamav: %s\n", cl_strerror(ret)); @@ -1120,10 +1165,12 @@ int scanmanager(const struct optstruct *opts) #endif } - if ((opt = optget(opts, "cache-size"))->enabled) + if ((opt = optget(opts, "cache-size"))->enabled) { cl_engine_set_num(engine, CL_ENGINE_CACHE_SIZE, opt->numarg); - if (optget(opts, "disable-cache")->enabled) + } + if (optget(opts, "disable-cache")->enabled) { cl_engine_set_num(engine, CL_ENGINE_DISABLE_CACHE, 1); + } if (optget(opts, "detect-pua")->enabled) { dboptions |= CL_DB_PUA; @@ -1190,41 +1237,50 @@ int scanmanager(const struct optstruct *opts) } } - if (optget(opts, "dev-ac-only")->enabled) + if (optget(opts, "dev-ac-only")->enabled) { cl_engine_set_num(engine, CL_ENGINE_AC_ONLY, 1); + } - if (optget(opts, "dev-ac-depth")->enabled) + if (optget(opts, "dev-ac-depth")->enabled) { cl_engine_set_num(engine, CL_ENGINE_AC_MAXDEPTH, optget(opts, "dev-ac-depth")->numarg); + } - if (optget(opts, "leave-temps")->enabled) + if (optget(opts, "leave-temps")->enabled) { cl_engine_set_num(engine, CL_ENGINE_KEEPTMP, 1); + } - if (optget(opts, "force-to-disk")->enabled) + if (optget(opts, "force-to-disk")->enabled) { cl_engine_set_num(engine, CL_ENGINE_FORCETODISK, 1); + } - if (optget(opts, "bytecode-unsigned")->enabled) + if (optget(opts, "bytecode-unsigned")->enabled) { dboptions |= CL_DB_BYTECODE_UNSIGNED; + } - if ((opt = optget(opts, "bytecode-timeout"))->enabled) + if ((opt = optget(opts, "bytecode-timeout"))->enabled) { cl_engine_set_num(engine, CL_ENGINE_BYTECODE_TIMEOUT, opt->numarg); + } - if (optget(opts, "nocerts")->enabled) + if (optget(opts, "nocerts")->enabled) { cl_engine_set_num(engine, CL_ENGINE_DISABLE_PE_CERTS, 1); + } - if (optget(opts, "dumpcerts")->enabled) + if (optget(opts, "dumpcerts")->enabled) { cl_engine_set_num(engine, CL_ENGINE_PE_DUMPCERTS, 1); + } if ((opt = optget(opts, "bytecode-mode"))->enabled) { enum bytecode_mode mode; - if (!strcmp(opt->strarg, "ForceJIT")) + if (!strcmp(opt->strarg, "ForceJIT")) { mode = CL_BYTECODE_MODE_JIT; - else if (!strcmp(opt->strarg, "ForceInterpreter")) + } else if (!strcmp(opt->strarg, "ForceInterpreter")) { mode = CL_BYTECODE_MODE_INTERPRETER; - else if (!strcmp(opt->strarg, "Test")) + } else if (!strcmp(opt->strarg, "Test")) { mode = CL_BYTECODE_MODE_TEST; - else + } else { mode = CL_BYTECODE_MODE_AUTO; + } cl_engine_set_num(engine, CL_ENGINE_BYTECODE_MODE, mode); } @@ -1240,8 +1296,9 @@ int scanmanager(const struct optstruct *opts) } } - if (optget(opts, "gen-json")->enabled) + if (optget(opts, "gen-json")->enabled) { options.general |= CL_SCAN_GENERAL_COLLECT_METADATA; + } if ((opt = optget(opts, "tempdir"))->enabled) { if ((ret = cl_engine_set_str(engine, CL_ENGINE_TMPDIR, opt->strarg))) { @@ -1394,10 +1451,12 @@ int scanmanager(const struct optstruct *opts) #ifndef _WIN32 if (getrlimit(RLIMIT_FSIZE, &rlim) == 0) { - if (rlim.rlim_cur < (rlim_t)cl_engine_get_num(engine, CL_ENGINE_MAX_FILESIZE, NULL)) + if (rlim.rlim_cur < (rlim_t)cl_engine_get_num(engine, CL_ENGINE_MAX_FILESIZE, NULL)) { logg(LOGG_WARNING, "System limit for file size is lower than engine->maxfilesize\n"); - if (rlim.rlim_cur < (rlim_t)cl_engine_get_num(engine, CL_ENGINE_MAX_SCANSIZE, NULL)) + } + if (rlim.rlim_cur < (rlim_t)cl_engine_get_num(engine, CL_ENGINE_MAX_SCANSIZE, NULL)) { logg(LOGG_WARNING, "System limit for file size is lower than engine->maxscansize\n"); + } } else { logg(LOGG_WARNING, "Cannot obtain resource limits for file size\n"); } @@ -1507,24 +1566,29 @@ int scanmanager(const struct optstruct *opts) /* TODO: Remove deprecated option in a future feature release */ if ((optget(opts, "phishing-ssl")->enabled) || - (optget(opts, "alert-phishing-ssl")->enabled)) + (optget(opts, "alert-phishing-ssl")->enabled)) { options.heuristic |= CL_SCAN_HEURISTIC_PHISHING_SSL_MISMATCH; + } /* TODO: Remove deprecated option in a future feature release */ if ((optget(opts, "phishing-cloak")->enabled) || - (optget(opts, "alert-phishing-cloak")->enabled)) + (optget(opts, "alert-phishing-cloak")->enabled)) { options.heuristic |= CL_SCAN_HEURISTIC_PHISHING_CLOAK; + } /* TODO: Remove deprecated option in a future feature release */ if ((optget(opts, "partition-intersection")->enabled) || - (optget(opts, "alert-partition-intersection")->enabled)) + (optget(opts, "alert-partition-intersection")->enabled)) { options.heuristic |= CL_SCAN_HEURISTIC_PARTITION_INTXN; + } - if (optget(opts, "heuristic-scan-precedence")->enabled) + if (optget(opts, "heuristic-scan-precedence")->enabled) { options.general |= CL_SCAN_GENERAL_HEURISTIC_PRECEDENCE; + } - if (optget(opts, "scan-archive")->enabled) + if (optget(opts, "scan-archive")->enabled) { options.parse |= CL_SCAN_PARSE_ARCHIVE; + } /* TODO: Remove deprecated option in a future feature release */ if ((optget(opts, "detect-broken")->enabled) || @@ -1543,11 +1607,13 @@ int scanmanager(const struct optstruct *opts) options.heuristic |= CL_SCAN_HEURISTIC_ENCRYPTED_DOC; } - if (optget(opts, "alert-encrypted-archive")->enabled) + if (optget(opts, "alert-encrypted-archive")->enabled) { options.heuristic |= CL_SCAN_HEURISTIC_ENCRYPTED_ARCHIVE; + } - if (optget(opts, "alert-encrypted-doc")->enabled) + if (optget(opts, "alert-encrypted-doc")->enabled) { options.heuristic |= CL_SCAN_HEURISTIC_ENCRYPTED_DOC; + } /* TODO: Remove deprecated option in a future feature release */ if ((optget(opts, "block-macros")->enabled) || @@ -1555,41 +1621,53 @@ int scanmanager(const struct optstruct *opts) options.heuristic |= CL_SCAN_HEURISTIC_MACROS; } - if (optget(opts, "scan-pe")->enabled) + if (optget(opts, "scan-pe")->enabled) { options.parse |= CL_SCAN_PARSE_PE; + } - if (optget(opts, "scan-elf")->enabled) + if (optget(opts, "scan-elf")->enabled) { options.parse |= CL_SCAN_PARSE_ELF; + } - if (optget(opts, "scan-ole2")->enabled) + if (optget(opts, "scan-ole2")->enabled) { options.parse |= CL_SCAN_PARSE_OLE2; + } - if (optget(opts, "scan-pdf")->enabled) + if (optget(opts, "scan-pdf")->enabled) { options.parse |= CL_SCAN_PARSE_PDF; + } - if (optget(opts, "scan-swf")->enabled) + if (optget(opts, "scan-swf")->enabled) { options.parse |= CL_SCAN_PARSE_SWF; + } - if (optget(opts, "scan-html")->enabled && optget(opts, "normalize")->enabled) + if (optget(opts, "scan-html")->enabled && optget(opts, "normalize")->enabled) { options.parse |= CL_SCAN_PARSE_HTML; + } - if (optget(opts, "scan-mail")->enabled) + if (optget(opts, "scan-mail")->enabled) { options.parse |= CL_SCAN_PARSE_MAIL; + } - if (optget(opts, "scan-xmldocs")->enabled) + if (optget(opts, "scan-xmldocs")->enabled) { options.parse |= CL_SCAN_PARSE_XMLDOCS; + } - if (optget(opts, "scan-hwp3")->enabled) + if (optget(opts, "scan-hwp3")->enabled) { options.parse |= CL_SCAN_PARSE_HWP3; + } - if (optget(opts, "scan-onenote")->enabled) + if (optget(opts, "scan-onenote")->enabled) { options.parse |= CL_SCAN_PARSE_ONENOTE; + } - if (optget(opts, "scan-image")->enabled) + if (optget(opts, "scan-image")->enabled) { options.parse |= CL_SCAN_PARSE_IMAGE; + } - if (optget(opts, "scan-image-fuzzy-hash")->enabled) + if (optget(opts, "scan-image-fuzzy-hash")->enabled) { options.parse |= CL_SCAN_PARSE_IMAGE_FUZZY_HASH; + } /* TODO: Remove deprecated option in a future feature release */ if ((optget(opts, "algorithmic-detection")->enabled) && /* && used due to default-yes for both options */ @@ -1612,8 +1690,9 @@ int scanmanager(const struct optstruct *opts) options.dev |= CL_SCAN_DEV_COLLECT_SHA; #endif - if (optget(opts, "dev-performance")->enabled) + if (optget(opts, "dev-performance")->enabled) { options.dev |= CL_SCAN_DEV_COLLECT_PERFORMANCE_INFO; + } if (optget(opts, "detect-structured")->enabled) { options.heuristic |= CL_SCAN_HEURISTIC_STRUCTURED; @@ -1724,10 +1803,11 @@ int scanmanager(const struct optstruct *opts) cl_engine_free(engine); /* overwrite return code - infection takes priority */ - if (info.ifiles) + if (info.ifiles) { ret = 1; - else if (info.errors) + } else if (info.errors) { ret = 2; + } return ret; } diff --git a/clamsubmit/CMakeLists.txt b/clamsubmit/CMakeLists.txt index 9a9f51ee60..0f11167ca6 100644 --- a/clamsubmit/CMakeLists.txt +++ b/clamsubmit/CMakeLists.txt @@ -23,6 +23,12 @@ target_include_directories( clamsubmit ) set_target_properties( clamsubmit PROPERTIES COMPILE_FLAGS "${WARNCFLAGS}" ) +if(CLANG_TIDY) + set_target_properties( clamsubmit PROPERTIES + C_CLANG_TIDY "${CLANG_TIDY_PROPERTY}" + C_CLANG_TIDY_EXPORT_FIXES_DIR "${CMAKE_BINARY_DIR}/clang-tidy-fixes" ) +endif() + if (APPLE AND CLAMAV_SIGN_FILE) set_target_properties( clamscan PROPERTIES XCODE_ATTRIBUTE_CODE_SIGN_IDENTITY ${CODE_SIGN_IDENTITY} diff --git a/clamsubmit/clamsubmit.c b/clamsubmit/clamsubmit.c index ec4a4ccb16..22bd616a06 100644 --- a/clamsubmit/clamsubmit.c +++ b/clamsubmit/clamsubmit.c @@ -107,8 +107,9 @@ size_t header_cb(char *ptr, size_t size, size_t nmemb, void *userdata) int clen = strlen(set_cookie); if (len > clen) { - if (strncmp(ptr, set_cookie, clen)) + if (strncmp(ptr, set_cookie, clen)) { return len; + } sp = ptr + clen + 1; ep = strchr(sp, ';'); if (ep == NULL) { @@ -122,9 +123,9 @@ size_t header_cb(char *ptr, size_t size, size_t nmemb, void *userdata) } memcpy(mem, sp, ep - sp); mem[ep - sp] = '\0'; - if (!strncmp(mem, "_clamav-net_session", strlen("_clamav-net_session"))) + if (!strncmp(mem, "_clamav-net_session", strlen("_clamav-net_session"))) { hd->session = mem; - else { + } else { logg(LOGG_ERROR, "header_cb(): unrecognized cookie\n"); free(mem); } @@ -234,13 +235,15 @@ int main(int argc, char *argv[]) name = optarg; break; case 'p': - if (setURL) + if (setURL) { usage(argv[0]); + } filename = optarg; break; case 'n': - if (setURL) + if (setURL) { usage(argv[0]); + } malware = true; filename = optarg; break; @@ -257,8 +260,9 @@ int main(int argc, char *argv[]) } } - if (!(name) || !(email) || !(filename)) + if (!(name) || !(email) || !(filename)) { usage(argv[0]); + } if (malware == false && fpvname == NULL) { logg(LOGG_ERROR, "Detected virus name(-V) required for false positive submissions.\n"); diff --git a/common/CMakeLists.txt b/common/CMakeLists.txt index 4d48050109..c8a8e1c79d 100644 --- a/common/CMakeLists.txt +++ b/common/CMakeLists.txt @@ -81,4 +81,10 @@ if(WIN32) set_target_properties(common PROPERTIES WINDOWS_EXPORT_ALL_SYMBOLS ON) endif() +if(CLANG_TIDY) + set_target_properties( common PROPERTIES + C_CLANG_TIDY "${CLANG_TIDY_PROPERTY}" + C_CLANG_TIDY_EXPORT_FIXES_DIR "${CMAKE_BINARY_DIR}/clang-tidy-fixes" ) +endif() + add_library( ClamAV::common ALIAS common ) diff --git a/common/actions.c b/common/actions.c index 6e48172c2d..da8dff204f 100644 --- a/common/actions.c +++ b/common/actions.c @@ -84,7 +84,9 @@ static int getdest(const char *fullpath, char **newname) free(tmps); return fd; } - if (errno != EEXIST) break; + if (errno != EEXIST) { + break; + } sprintf(*newname, "%s" PATHSEP "%s.%03u", actarget, filename, i); } free(tmps); @@ -633,18 +635,27 @@ static void action_move(const char *filename) #endif logg(LOGG_ERROR, "Can't move file %s to %s\n", filename, nuname); notmoved++; - if (nuname) traverse_unlink(nuname); + if (nuname) { + traverse_unlink(nuname); + } } else { - if (copied && (0 != traverse_unlink(filename))) + if (copied && (0 != traverse_unlink(filename))) { logg(LOGG_ERROR, "Can't unlink '%s' after copy: %s\n", filename, strerror(errno)); - else + } else { logg(LOGG_INFO, "%s: moved to '%s'\n", filename, nuname); + } } done: - if (NULL != real_filename) free(real_filename); - if (fd >= 0) close(fd); - if (NULL != nuname) free(nuname); + if (NULL != real_filename) { + free(real_filename); + } + if (fd >= 0) { + close(fd); + } + if (NULL != nuname) { + free(nuname); + } return; } @@ -656,12 +667,19 @@ static void action_copy(const char *filename) if (fd < 0 || filecopy(filename, nuname)) { logg(LOGG_ERROR, "Can't copy file '%s'\n", filename); notmoved++; - if (nuname) traverse_unlink(nuname); - } else + if (nuname) { + traverse_unlink(nuname); + } + } else { logg(LOGG_INFO, "%s: copied to '%s'\n", filename, nuname); + } - if (fd >= 0) close(fd); - if (nuname) free(nuname); + if (fd >= 0) { + close(fd); + } + if (nuname) { + free(nuname); + } } static void action_remove(const char *filename) @@ -680,7 +698,9 @@ static void action_remove(const char *filename) } done: - if (NULL != real_filename) free(real_filename); + if (NULL != real_filename) { + free(real_filename); + } return; } @@ -713,10 +733,13 @@ int actsetup(const struct optstruct *opts) return 0; } #endif - if (!isdir()) return 1; + if (!isdir()) { + return 1; + } action = move ? action_move : action_copy; targlen = strlen(actarget); - } else if (optget(opts, "remove")->enabled) + } else if (optget(opts, "remove")->enabled) { action = action_remove; + } return 0; } diff --git a/common/cert_util.c b/common/cert_util.c index 4dac043388..5668880c79 100644 --- a/common/cert_util.c +++ b/common/cert_util.c @@ -226,12 +226,14 @@ static cl_error_t x509_cert_name_cmp(X509 *cert_a, X509 *cert_b, int *cmp_out) BUF_MEM *biomem_b; bio_out_a = BIO_new(BIO_s_mem()); - if (!bio_out_a) + if (!bio_out_a) { goto done; + } bio_out_b = BIO_new(BIO_s_mem()); - if (!bio_out_b) + if (!bio_out_b) { goto done; + } a = X509_get_subject_name(cert_a); @@ -253,10 +255,12 @@ static cl_error_t x509_cert_name_cmp(X509 *cert_a, X509 *cert_b, int *cmp_out) status = CL_SUCCESS; done: - if (NULL != bio_out_a) + if (NULL != bio_out_a) { BIO_free(bio_out_a); - if (NULL != bio_out_b) + } + if (NULL != bio_out_b) { BIO_free(bio_out_b); + } return status; } @@ -278,8 +282,9 @@ cl_error_t x509_get_cert_name(X509 *cert, char **name) *name = NULL; bio_out = BIO_new(BIO_s_mem()); - if (!bio_out) + if (!bio_out) { goto done; + } a = X509_get_subject_name(cert); @@ -302,8 +307,9 @@ cl_error_t x509_get_cert_name(X509 *cert, char **name) status = CL_SUCCESS; done: - if (NULL != bio_out) + if (NULL != bio_out) { BIO_free(bio_out); + } return status; } @@ -365,8 +371,9 @@ cl_error_t cert_store_export_pem(char **cert_data, if (CL_SUCCESS == x509_cert_name_cmp(_cert_store.system_certs.certificates[i], additional_ca_cert, &cmp)) { - if (0 == cmp) + if (0 == cmp) { add_additional_ca_cert = false; + } } } #else @@ -399,8 +406,9 @@ cl_error_t cert_store_export_pem(char **cert_data, if (CL_SUCCESS == x509_cert_name_cmp(_cert_store.trusted_certs.certificates[i], additional_ca_cert, &cmp)) { - if (0 == cmp) + if (0 == cmp) { add_additional_ca_cert = false; + } } } #else diff --git a/common/clamdcom.c b/common/clamdcom.c index 2c7653efdd..38dbf90132 100644 --- a/common/clamdcom.c +++ b/common/clamdcom.c @@ -59,7 +59,9 @@ int sendln(int sockd, const char *line, unsigned int len) while (len) { int sent = send(sockd, line, len, 0); if (sent <= 0) { - if (sent && errno == EINTR) continue; + if (sent && errno == EINTR) { + continue; + } logg(LOGG_ERROR, "Can't send to clamd: %s\n", strerror(errno)); return 1; } @@ -100,10 +102,11 @@ int recvln(struct RCVLN *s, char **rbol, char **reol) } if (s->r || s->cur != s->buf) { *s->cur = '\0'; - if (strcmp(s->buf, "UNKNOWN COMMAND\n")) + if (strcmp(s->buf, "UNKNOWN COMMAND\n")) { logg(LOGG_ERROR, "Communication error\n"); - else + } else { logg(LOGG_ERROR, "Command rejected by clamd (wrong clamd version?)\n"); + } return -1; } return 0; @@ -114,12 +117,15 @@ int recvln(struct RCVLN *s, char **rbol, char **reol) eol++; s->r -= eol - s->cur; *rbol = s->bol; - if (reol) *reol = eol; + if (reol) { + *reol = eol; + } ret = eol - s->bol; - if (s->r) + if (s->r) { s->bol = s->cur = eol; - else + } else { s->bol = s->cur = s->buf; + } return ret; } s->r += s->cur - s->bol; @@ -187,8 +193,9 @@ int send_fdpass(int sockd, const char *filename) logg(LOGG_INFO, "%s: Failed to open file\n", filename); return 0; } - } else + } else { fd = 0; + } if (sendln(sockd, zFILDES, sizeof(zFILDES))) { close(fd); return -1; @@ -241,7 +248,9 @@ int send_stream(int sockd, const char *filename, struct optstruct *clamdopts) } while ((len = read(fd, &buf[1], sizeof(buf) - sizeof(uint32_t))) > 0) { - if ((unsigned int)len > todo) len = todo; + if ((unsigned int)len > todo) { + len = todo; + } buf[0] = htonl(len); if (sendln(sockd, (const char *)buf, len + sizeof(uint32_t))) { close(fd); @@ -277,9 +286,9 @@ int dconnect(struct optstruct *clamdopts) opt = optget(clamdopts, "LocalSocket"); if (opt->enabled) { if ((sockd = socket(AF_UNIX, SOCK_STREAM, 0)) >= 0) { - if (connect(sockd, (struct sockaddr *)&nixsock, sizeof(nixsock)) == 0) + if (connect(sockd, (struct sockaddr *)&nixsock, sizeof(nixsock)) == 0) { return sockd; - else { + } else { logg(LOGG_ERROR, "Could not connect to clamd on LocalSocket %s: %s\n", opt->strarg, strerror(errno)); close(sockd); } @@ -293,8 +302,9 @@ int dconnect(struct optstruct *clamdopts) while (opt) { if (opt->enabled) { ipaddr = NULL; - if (opt->strarg) + if (opt->strarg) { ipaddr = (!strcmp(opt->strarg, "any") ? NULL : opt->strarg); + } memset(&hints, 0x00, sizeof(struct addrinfo)); hints.ai_family = AF_UNSPEC; @@ -386,10 +396,12 @@ int dsresult(int sockd, int scantype, const char *filename, int *printok, int *e } if (len <= 0) { - if (printok) + if (printok) { *printok = 0; - if (errors) + } + if (errors) { (*errors)++; + } infected = len; goto done; } @@ -400,31 +412,36 @@ int dsresult(int sockd, int scantype, const char *filename, int *printok, int *e goto done; } beenthere = 1; - if (!filename) logg(LOGG_INFO, "%s\n", bol); + if (!filename) { + logg(LOGG_INFO, "%s\n", bol); + } if (len > 7) { char *colon = strrchr(bol, ':'); if (colon && colon[1] != ' ') { char *br; *colon = 0; br = strrchr(bol, '('); - if (br) + if (br) { *br = 0; + } colon = strrchr(bol, ':'); } if (!colon) { char *unkco = "UNKNOWN COMMAND"; - if (!strncmp(bol, unkco, sizeof(unkco) - 1)) + if (!strncmp(bol, unkco, sizeof(unkco) - 1)) { logg(LOGG_INFO, "clamd replied \"UNKNOWN COMMAND\". Command was %s\n", (scantype < 0 || scantype > MAX_SCANTYPE) ? "unidentified" : scancmd[scantype]); - else + } else { logg(LOGG_INFO, "Failed to parse reply: \"%s\"\n", bol); + } infected = -1; goto done; } else if (!memcmp(eol - 7, " FOUND", 6)) { static char last_filename[PATH_MAX + 1] = {'\0'}; *(eol - 7) = 0; - if (printok) + if (printok) { *printok = 0; + } if (scantype != ALLMATCH) { infected++; } else { @@ -437,24 +454,30 @@ int dsresult(int sockd, int scantype, const char *filename, int *printok, int *e if (filename) { if (scantype >= STREAM) { logg(LOGG_INFO, "%s%s FOUND\n", filename, colon); - if (action) action(filename); + if (action) { + action(filename); + } } else { logg(LOGG_INFO, "%s FOUND\n", bol); *colon = '\0'; - if (action) + if (action) { action(bol); + } } } } else if (!memcmp(eol - 7, " ERROR", 6)) { - if (errors) + if (errors) { (*errors)++; - if (printok) + } + if (printok) { *printok = 0; + } if (filename) { - if (scantype >= STREAM) + if (scantype >= STREAM) { logg(LOGG_INFO, "%s%s\n", filename, colon); - else + } else { logg(LOGG_INFO, "%s\n", bol); + } } } } diff --git a/common/getopt.c b/common/getopt.c index 7c4d02c42a..fbd724a747 100644 --- a/common/getopt.c +++ b/common/getopt.c @@ -60,20 +60,23 @@ int my_getopt(int argc, char *argvc[], const char *opts) char mode, colon_mode; int off = 0, opt = -1; - if (getenv("POSIXLY_CORRECT")) + if (getenv("POSIXLY_CORRECT")) { colon_mode = mode = '+'; - else { - if ((colon_mode = *opts) == ':') off++; + } else { + if ((colon_mode = *opts) == ':') { + off++; + } if (((mode = opts[off]) == '+') || (mode == '-')) { off++; - if ((colon_mode != ':') && ((colon_mode = opts[off]) == ':')) + if ((colon_mode != ':') && ((colon_mode = opts[off]) == ':')) { off++; + } } } optarg = 0; if (charind) { optopt = argv[optind][charind]; - for (s = opts + off; *s; s++) + for (s = opts + off; *s; s++) { if (optopt == *s) { charind++; if ((*(++s) == ':') || ((optopt == 'W') && (*s == ';'))) { @@ -83,9 +86,11 @@ int my_getopt(int argc, char *argvc[], const char *opts) } else if (*(++s) != ':') { charind = 0; if (++optind >= argc) { - if (opterr) fprintf(stderr, - "%s: option requires an argument -- %c\n", - argv[0], optopt); + if (opterr) { + fprintf(stderr, + "%s: option requires an argument -- %c\n", + argv[0], optopt); + } opt = (colon_mode == ':') ? ':' : '?'; goto getopt_ok; } @@ -95,9 +100,12 @@ int my_getopt(int argc, char *argvc[], const char *opts) opt = optopt; goto getopt_ok; } - if (opterr) fprintf(stderr, - "%s: illegal option -- %c\n", - argv[0], optopt); + } + if (opterr) { + fprintf(stderr, + "%s: illegal option -- %c\n", + argv[0], optopt); + } opt = '?'; if (argv[optind][++charind] == '\0') { optind++; @@ -119,32 +127,39 @@ int my_getopt(int argc, char *argvc[], const char *opts) char *tmp; int i, j, k; - if (mode == '+') + if (mode == '+') { opt = -1; - else if (mode == '-') { + } else if (mode == '-') { optarg = argv[optind++]; charind = 0; opt = 1; } else { - for (i = j = optind; i < argc; i++) + for (i = j = optind; i < argc; i++) { if ((argv[i][0] == '-') && (argv[i][1] != '\0')) { optind = i; opt = my_getopt(argc, argv, opts); while (i > j) { tmp = argv[--i]; - for (k = i; k + 1 < optind; k++) argv[k] = argv[k + 1]; + for (k = i; k + 1 < optind; k++) { + argv[k] = argv[k + 1]; + } argv[--optind] = tmp; } break; } - if (i == argc) opt = -1; + } + if (i == argc) { + opt = -1; + } } } else { charind++; opt = my_getopt(argc, argv, opts); } - if (optind > argc) optind = argc; + if (optind > argc) { + optind = argc; + } return opt; } @@ -163,11 +178,14 @@ static int _getopt_internal(int argc, char *argv[], const char *shortopts, if (getenv("POSIXLY_CORRECT")) { colon_mode = mode = '+'; } else { - if ((colon_mode = *shortopts) == ':') shortoff++; + if ((colon_mode = *shortopts) == ':') { + shortoff++; + } if (((mode = shortopts[shortoff]) == '+') || (mode == '-')) { shortoff++; - if ((colon_mode != ':') && ((colon_mode = shortopts[shortoff]) == ':')) + if ((colon_mode != ':') && ((colon_mode = shortopts[shortoff]) == ':')) { shortoff++; + } } } optarg = 0; @@ -183,13 +201,13 @@ static int _getopt_internal(int argc, char *argv[], const char *shortopts, int i, j, k; opt = -1; - if (mode == '+') + if (mode == '+') { return -1; - else if (mode == '-') { + } else if (mode == '-') { optarg = argv[optind++]; return 1; } - for (i = j = optind; i < argc; i++) + for (i = j = optind; i < argc; i++) { if ((argv[i][0] == '-') && (argv[i][1] != '\0')) { optind = i; @@ -199,15 +217,17 @@ static int _getopt_internal(int argc, char *argv[], const char *shortopts, long_only); while (i > j) { tmp = argv[--i]; - for (k = i; k + 1 < optind; k++) + for (k = i; k + 1 < optind; k++) { argv[k] = argv[k + 1]; + } argv[--optind] = tmp; } break; } - } else if ((!long_only) && (argv[optind][1] != '-')) + } + } else if ((!long_only) && (argv[optind][1] != '-')) { opt = my_getopt(argc, argv, shortopts); - else { + } else { int charind, offset; int found = 0, ind, hits = 0; @@ -218,36 +238,47 @@ static int _getopt_internal(int argc, char *argv[], const char *shortopts, while ((c = shortopts[ind++])) { if (((shortopts[ind] == ':') || ((c == 'W') && (shortopts[ind] == ';'))) && - (shortopts[++ind] == ':')) + (shortopts[++ind] == ':')) { ind++; - if (optopt == c) return my_getopt(argc, argv, shortopts); + } + if (optopt == c) { + return my_getopt(argc, argv, shortopts); + } } } offset = 2 - (argv[optind][1] != '-'); for (charind = offset; (argv[optind][charind] != '\0') && (argv[optind][charind] != '='); - charind++) + charind++) { ; - for (ind = 0; longopts[ind].name && !hits; ind++) + } + for (ind = 0; longopts[ind].name && !hits; ind++) { if ((strlen(longopts[ind].name) == (size_t)(charind - offset)) && (strncmp(longopts[ind].name, - argv[optind] + offset, charind - offset) == 0)) + argv[optind] + offset, charind - offset) == 0)) { found = ind, hits++; - if (!hits) - for (ind = 0; longopts[ind].name; ind++) + } + } + if (!hits) { + for (ind = 0; longopts[ind].name; ind++) { if (strncmp(longopts[ind].name, - argv[optind] + offset, charind - offset) == 0) + argv[optind] + offset, charind - offset) == 0) { found = ind, hits++; + } + } + } if (hits == 1) { opt = 0; if (argv[optind][charind] == '=') { if (longopts[found].has_arg == 0) { opt = '?'; - if (opterr) fprintf(stderr, - "%s: option `--%s' doesn't allow an argument\n", - argv[0], longopts[found].name); + if (opterr) { + fprintf(stderr, + "%s: option `--%s' doesn't allow an argument\n", + argv[0], longopts[found].name); + } } else { optarg = argv[optind] + ++charind; // charind = 0; // Never used again past here @@ -255,37 +286,49 @@ static int _getopt_internal(int argc, char *argv[], const char *shortopts, } else if (longopts[found].has_arg == 1) { if (++optind >= argc) { opt = (colon_mode == ':') ? ':' : '?'; - if (opterr) fprintf(stderr, - "%s: option `--%s' requires an argument\n", - argv[0], longopts[found].name); - } else + if (opterr) { + fprintf(stderr, + "%s: option `--%s' requires an argument\n", + argv[0], longopts[found].name); + } + } else { optarg = argv[optind]; + } } if (!opt) { - if (longind) *longind = found; - if (!longopts[found].flag) + if (longind) { + *longind = found; + } + if (!longopts[found].flag) { opt = longopts[found].val; - else + } else { *(longopts[found].flag) = longopts[found].val; + } } optind++; } else if (!hits) { - if (offset == 1) + if (offset == 1) { opt = my_getopt(argc, argv, shortopts); - else { + } else { opt = '?'; - if (opterr) fprintf(stderr, - "%s: unrecognized option `%s'\n", - argv[0], argv[optind++]); + if (opterr) { + fprintf(stderr, + "%s: unrecognized option `%s'\n", + argv[0], argv[optind++]); + } } } else { opt = '?'; - if (opterr) fprintf(stderr, - "%s: option `%s' is ambiguous\n", - argv[0], argv[optind++]); + if (opterr) { + fprintf(stderr, + "%s: option `%s' is ambiguous\n", + argv[0], argv[optind++]); + } } } - if (optind > argc) optind = argc; + if (optind > argc) { + optind = argc; + } return opt; } diff --git a/common/hostid.c b/common/hostid.c index 0acfa94304..9dc9cf4dff 100644 --- a/common/hostid.c +++ b/common/hostid.c @@ -31,19 +31,24 @@ int is_valid_hostid(void) { int count, i; - if (strlen(hostid) != 36) + if (strlen(hostid) != 36) { return 0; + } count = 0; - for (i = 0; i < 36; i++) - if (hostid[i] == '-') + for (i = 0; i < 36; i++) { + if (hostid[i] == '-') { count++; + } + } - if (count != 4) + if (count != 4) { return 0; + } - if (hostid[8] != '-' || hostid[13] != '-' || hostid[18] != '-' || hostid[23] != '-') + if (hostid[8] != '-' || hostid[13] != '-' || hostid[18] != '-' || hostid[23] != '-') { return 0; + } return 1; } @@ -52,11 +57,13 @@ char *get_hostid(void *cbdata) { UNUSEDPARAM(cbdata); - if (!strcmp(hostid, "none")) + if (!strcmp(hostid, "none")) { return NULL; + } - if (!is_valid_hostid()) + if (!is_valid_hostid()) { return strdup(STATS_ANON_UUID); + } logg(LOGG_INFO, "HostID is valid: %s\n", hostid); diff --git a/common/misc.c b/common/misc.c index 7312835ef0..399fdaf286 100644 --- a/common/misc.c +++ b/common/misc.c @@ -91,18 +91,21 @@ char *freshdbdir(void) return NULL; } sprintf(daily, "%s" PATHSEP "daily.cvd", opt->strarg); - if (access(daily, R_OK)) + if (access(daily, R_OK)) { sprintf(daily, "%s" PATHSEP "daily.cld", opt->strarg); + } if (!access(daily, R_OK) && (d1 = cl_cvdhead(daily))) { sprintf(daily, "%s" PATHSEP "daily.cvd", dbdir); - if (access(daily, R_OK)) + if (access(daily, R_OK)) { sprintf(daily, "%s" PATHSEP "daily.cld", dbdir); + } if (!access(daily, R_OK) && (d2 = cl_cvdhead(daily))) { free(daily); - if (d1->version > d2->version) + if (d1->version > d2->version) { dbdir = opt->strarg; + } cl_cvdfree(d2); } else { free(daily); @@ -118,8 +121,9 @@ char *freshdbdir(void) retdir = strdup(dbdir); - if (opts) + if (opts) { optfree(opts); + } return retdir; } @@ -132,10 +136,11 @@ void print_version(const char *dbdir) time_t db_time; unsigned int db_version = 0; - if (dbdir) + if (dbdir) { pt = dbdir; - else + } else { pt = fdbdir = freshdbdir(); + } if (!pt) { printf("ClamAV %s\n", get_version()); @@ -143,8 +148,9 @@ void print_version(const char *dbdir) } if (!(path = malloc(strlen(pt) + 11))) { - if (!dbdir) + if (!dbdir) { free(fdbdir); + } return; } @@ -170,8 +176,9 @@ void print_version(const char *dbdir) } } - if (!dbdir) + if (!dbdir) { free(fdbdir); + } if (db_version) { printf("ClamAV %s/%u/%s", get_version(), db_version, ctime(&db_time)); @@ -204,8 +211,9 @@ const char *filelist(const struct optstruct *opts, int *err) fs = fopen(opt->strarg, "r"); if (!fs) { fprintf(stderr, "ERROR: --file-list: Can't open file %s\n", opt->strarg); - if (err) + if (err) { *err = 54; + } return NULL; } } @@ -218,8 +226,9 @@ const char *filelist(const struct optstruct *opts, int *err) return NULL; } len--; - while (len && ((buff[len] == '\n') || (buff[len] == '\r'))) + while (len && ((buff[len] == '\n') || (buff[len] == '\r'))) { buff[len--] = '\0'; + } return buff; } else { fclose(fs); @@ -267,25 +276,31 @@ int close_std_descriptors() fds[2] = open("/dev/null", O_WRONLY); if (fds[0] == -1 || fds[1] == -1 || fds[2] == -1) { fputs("Can't open /dev/null\n", stderr); - for (i = 0; i <= 2; i++) - if (fds[i] != -1) + for (i = 0; i <= 2; i++) { + if (fds[i] != -1) { close(fds[i]); + } + } return -1; } for (i = 0; i <= 2; i++) { if (dup2(fds[i], i) == -1) { fprintf(stderr, "dup2(%d, %d) failed\n", fds[i], i); /* may not be printed */ - for (i = 0; i <= 2; i++) - if (fds[i] != -1) + for (i = 0; i <= 2; i++) { + if (fds[i] != -1) { close(fds[i]); + } + } return -1; } } - for (i = 0; i <= 2; i++) - if (fds[i] > 2) + for (i = 0; i <= 2; i++) { + if (fds[i] > 2) { close(fds[i]); + } + } return 0; } @@ -443,8 +458,9 @@ int match_regex(const char *filename, const char *pattern) #ifdef _WIN32 flags |= REG_ICASE; /* case insensitive on Windows */ #endif - if (cli_regcomp(®, pattern, flags) != 0) + if (cli_regcomp(®, pattern, flags) != 0) { return 2; + } if (pattern[strlen(pattern) - 1] == *PATHSEP) { snprintf(fname, 511, "%s" PATHSEP, filename); @@ -475,18 +491,25 @@ unsigned int countlines(const char *filename) char buff[1024]; unsigned int lines = 0; - if ((fh = fopen(filename, "r")) == NULL) + if ((fh = fopen(filename, "r")) == NULL) { return 0; + } while (fgets(buff, sizeof(buff), fh)) { // ignore comments - if (buff[0] == '#') continue; + if (buff[0] == '#') { + continue; + } // ignore empty lines in CR/LF format - if (buff[0] == '\r' && buff[1] == '\n') continue; + if (buff[0] == '\r' && buff[1] == '\n') { + continue; + } // ignore empty lines in LF format - if (buff[0] == '\n') continue; + if (buff[0] == '\n') { + continue; + } lines++; } diff --git a/common/optparser.c b/common/optparser.c index fc79554148..008797392d 100644 --- a/common/optparser.c +++ b/common/optparser.c @@ -756,8 +756,9 @@ static void fix_paths(void) const struct optstruct *optget(const struct optstruct *opts, const char *name) { while (opts) { - if ((opts->name && !strcmp(opts->name, name)) || (opts->cmd && !strcmp(opts->cmd, name))) + if ((opts->name && !strcmp(opts->name, name)) || (opts->cmd && !strcmp(opts->cmd, name))) { return opts; + } opts = opts->next; } return NULL; @@ -766,8 +767,9 @@ const struct optstruct *optget(const struct optstruct *opts, const char *name) static struct optstruct *optget_i(struct optstruct *opts, const char *name) { while (opts) { - if ((opts->name && !strcmp(opts->name, name)) || (opts->cmd && !strcmp(opts->cmd, name))) + if ((opts->name && !strcmp(opts->name, name)) || (opts->cmd && !strcmp(opts->cmd, name))) { return opts; + } opts = opts->next; } return NULL; @@ -802,8 +804,9 @@ static int optadd(struct optstruct **opts, struct optstruct **opts_last, const c newnode = (struct optstruct *)malloc(sizeof(struct optstruct)); - if (!newnode) + if (!newnode) { return -1; + } if (name) { newnode->name = strdup(name); @@ -840,8 +843,9 @@ static int optadd(struct optstruct **opts, struct optstruct **opts_last, const c newnode->enabled = 0; } newnode->numarg = numarg; - if (numarg && numarg != -1) + if (numarg && numarg != -1) { newnode->enabled = 1; + } newnode->nextarg = NULL; newnode->next = NULL; newnode->active = 0; @@ -896,13 +900,15 @@ static int optaddarg(struct optstruct *opts, const char *name, const char *strar } new->numarg = numarg; h = pt; - while (h->nextarg) + while (h->nextarg) { h = h->nextarg; + } h->nextarg = new; } } else { - if (pt->active) + if (pt->active) { return 0; + } if (strarg) { free(pt->strarg); @@ -916,10 +922,11 @@ static int optaddarg(struct optstruct *opts, const char *name, const char *strar } pt->active = 1; - if (pt->strarg || (pt->numarg && pt->numarg != -1)) + if (pt->strarg || (pt->numarg && pt->numarg != -1)) { pt->enabled = 1; - else + } else { pt->enabled = 0; + } return 0; } @@ -930,8 +937,9 @@ void optfree(struct optstruct *opts) int i; if (opts && opts->filename) { - for (i = 0; opts->filename[i]; i++) + for (i = 0; opts->filename[i]; i++) { free(opts->filename[i]); + } free(opts->filename); } @@ -981,14 +989,16 @@ struct optstruct *optparse(const char *cfgfile, int argc, char **argv, int verbo } #endif - if (oldopts) + if (oldopts) { opts = oldopts; + } shortopts[sc++] = ':'; for (i = 0;; i++) { optentry = &clam_options[i]; - if (!optentry->name && !optentry->longopt) + if (!optentry->name && !optentry->longopt) { break; + } if (((optentry->owner & toolmask) && ((optentry->owner & toolmask) != OPT_DEPRECATED)) || (ignore && (optentry->owner & ignore))) { if (!oldopts && optadd(&opts, &opts_last, optentry->name, optentry->longopt, optentry->strarg, optentry->numarg, optentry->flags, i) < 0) { @@ -1005,10 +1015,11 @@ struct optstruct *optparse(const char *cfgfile, int argc, char **argv, int verbo return NULL; } longopts[lc].name = optentry->longopt; - if (!(optentry->flags & FLAG_REQUIRED) && (optentry->argtype == CLOPT_TYPE_BOOL || optentry->strarg)) + if (!(optentry->flags & FLAG_REQUIRED) && (optentry->argtype == CLOPT_TYPE_BOOL || optentry->strarg)) { longopts[lc].has_arg = 2; - else + } else { longopts[lc].has_arg = 1; + } longopts[lc].flag = NULL; longopts[lc++].val = optentry->shortopt; } @@ -1021,8 +1032,9 @@ struct optstruct *optparse(const char *cfgfile, int argc, char **argv, int verbo shortopts[sc++] = optentry->shortopt; if (optentry->argtype != CLOPT_TYPE_BOOL) { shortopts[sc++] = ':'; - if (!(optentry->flags & FLAG_REQUIRED) && optentry->strarg) + if (!(optentry->flags & FLAG_REQUIRED) && optentry->strarg) { shortopts[sc++] = ':'; + } } } } @@ -1050,40 +1062,48 @@ struct optstruct *optparse(const char *cfgfile, int argc, char **argv, int verbo while (1) { if (cfgfile) { - if (!fgets(buffer, sizeof(buffer), fs)) + if (!fgets(buffer, sizeof(buffer), fs)) { break; + } buff = buffer; - for (i = 0; i < (int)strlen(buff) - 1 && (buff[i] == ' ' || buff[i] == '\t'); i++) + for (i = 0; i < (int)strlen(buff) - 1 && (buff[i] == ' ' || buff[i] == '\t'); i++) { ; + } buff += i; line++; - if (strlen(buff) <= 2 || buff[0] == '#') + if (strlen(buff) <= 2 || buff[0] == '#') { continue; + } if (!strncmp("Example", buff, 7)) { - if (verbose) + if (verbose) { fprintf(stderr, "ERROR: Please edit the example config file %s\n", cfgfile); + } err = 1; break; } if (!(pt = strpbrk(buff, " \t"))) { - if (verbose) + if (verbose) { fprintf(stderr, "ERROR: Missing argument for option at %s:%d\n", cfgfile, line); + } err = 1; break; } name = buff; *pt++ = 0; - for (i = 0; i < (int)strlen(pt) - 1 && (pt[i] == ' ' || pt[i] == '\t'); i++) + for (i = 0; i < (int)strlen(pt) - 1 && (pt[i] == ' ' || pt[i] == '\t'); i++) { ; + } pt += i; - for (i = strlen(pt); i >= 1 && (pt[i - 1] == ' ' || pt[i - 1] == '\t' || pt[i - 1] == '\n'); i--) + for (i = strlen(pt); i >= 1 && (pt[i - 1] == ' ' || pt[i - 1] == '\t' || pt[i - 1] == '\n'); i--) { ; + } if (!i) { - if (verbose) + if (verbose) { fprintf(stderr, "ERROR: Missing argument for option at %s:%d\n", cfgfile, line); + } err = 1; break; } @@ -1094,15 +1114,17 @@ struct optstruct *optparse(const char *cfgfile, int argc, char **argv, int verbo pt++; pt = strrchr(pt, '"'); if (!pt) { - if (verbose) + if (verbose) { fprintf(stderr, "ERROR: Missing closing parenthesis in option %s at %s:%d\n", name, cfgfile, line); + } err = 1; break; } *pt = 0; if (!strlen(arg)) { - if (verbose) + if (verbose) { fprintf(stderr, "ERROR: Empty argument for option %s at %s:%d\n", name, cfgfile, line); + } err = 1; break; } @@ -1111,8 +1133,9 @@ struct optstruct *optparse(const char *cfgfile, int argc, char **argv, int verbo } else { opt_index = 0; ret = my_getopt_long(argc, argv, shortopts, longopts, &opt_index); - if (ret == -1) + if (ret == -1) { break; + } if (ret == ':') { fprintf(stderr, "ERROR: Incomplete option passed (missing argument)\n"); @@ -1152,8 +1175,9 @@ struct optstruct *optparse(const char *cfgfile, int argc, char **argv, int verbo opt = optget_i(opts, name); if (!opt) { if (cfgfile) { - if (verbose) + if (verbose) { fprintf(stderr, "ERROR: Parse error at %s:%d: Unknown option %s\n", cfgfile, line, name); + } } err = 1; break; @@ -1162,14 +1186,16 @@ struct optstruct *optparse(const char *cfgfile, int argc, char **argv, int verbo if (ignore && (optentry->owner & ignore) && !(optentry->owner & toolmask)) { if (cfgfile) { - if (verbose) + if (verbose) { fprintf(stderr, "WARNING: Ignoring unsupported option %s at %s:%d\n", opt->name, cfgfile, line); + } } else { if (verbose) { - if (optentry->shortopt) + if (optentry->shortopt) { fprintf(stderr, "WARNING: Ignoring unsupported option --%s (-%c)\n", optentry->longopt, optentry->shortopt); - else + } else { fprintf(stderr, "WARNING: Ignoring unsupported option --%s\n", optentry->longopt); + } } } continue; @@ -1178,23 +1204,26 @@ struct optstruct *optparse(const char *cfgfile, int argc, char **argv, int verbo if (optentry->owner & OPT_DEPRECATED) { if (toolmask & OPT_DEPRECATED) { if (optaddarg(opts, name, "foo", 1) < 0) { - if (cfgfile) + if (cfgfile) { fprintf(stderr, "ERROR: Can't register argument for option %s\n", name); - else + } else { fprintf(stderr, "ERROR: Can't register argument for option --%s\n", optentry->longopt); + } err = 1; break; } } else { if (cfgfile) { - if (verbose) + if (verbose) { fprintf(stderr, "WARNING: Ignoring deprecated option %s at %s:%d\n", opt->name, cfgfile, line); + } } else { if (verbose) { - if (optentry->shortopt) + if (optentry->shortopt) { fprintf(stderr, "WARNING: Ignoring deprecated option --%s (-%c)\n", optentry->longopt, optentry->shortopt); - else + } else { fprintf(stderr, "WARNING: Ignoring deprecated option --%s\n", optentry->longopt); + } } } } @@ -1204,8 +1233,9 @@ struct optstruct *optparse(const char *cfgfile, int argc, char **argv, int verbo if (!cfgfile && !arg && optentry->argtype == CLOPT_TYPE_BOOL) { arg = "yes"; /* default to yes */ } else if (optentry->regex) { - if (!(optentry->flags & FLAG_REG_CASE)) + if (!(optentry->flags & FLAG_REG_CASE)) { regflags |= REG_ICASE; + } if (cli_regcomp(®ex, optentry->regex, regflags)) { fprintf(stderr, "ERROR: optparse: Can't compile regular expression %s for option %s\n", optentry->regex, name); @@ -1218,10 +1248,11 @@ struct optstruct *optparse(const char *cfgfile, int argc, char **argv, int verbo if (cfgfile) { fprintf(stderr, "ERROR: Incorrect argument format for option %s\n", name); } else { - if (optentry->shortopt) + if (optentry->shortopt) { fprintf(stderr, "ERROR: Incorrect argument format for option --%s (-%c)\n", optentry->longopt, optentry->shortopt); - else + } else { fprintf(stderr, "ERROR: Incorrect argument format for option --%s\n", optentry->longopt); + } } err = 1; break; @@ -1231,39 +1262,43 @@ struct optstruct *optparse(const char *cfgfile, int argc, char **argv, int verbo numarg = -1; switch (optentry->argtype) { case CLOPT_TYPE_STRING: - if (!arg) + if (!arg) { arg = optentry->strarg; + } if (!cfgfile && !strlen(arg)) { - if (optentry->shortopt) + if (optentry->shortopt) { fprintf(stderr, "ERROR: Option --%s (-%c) requires a non-empty string argument\n", optentry->longopt, optentry->shortopt); - else + } else { fprintf(stderr, "ERROR: Option --%s requires a non-empty string argument\n", optentry->longopt); + } err = 1; break; } break; case CLOPT_TYPE_NUMBER: - if (arg) + if (arg) { numarg = atoi(arg); - else + } else { numarg = 0; + } arg = NULL; break; case CLOPT_TYPE_SIZE: case CLOPT_TYPE_SIZE64: - if (optentry->argtype == CLOPT_TYPE_SIZE64) + if (optentry->argtype == CLOPT_TYPE_SIZE64) { /* guaranteed to be "long long" (64 bit but possibly signed) further down the line */ lnumlimit = LLONG_MAX; - else + } else { /* probably mostly "unsigned long int" (32 or 64 bit unsigned depending on platform), * but may be expected to fit into a "long long" (64-bit signed) */ lnumlimit = LLONG_MAX < ULONG_MAX ? LLONG_MAX : ULONG_MAX; + } errno = 0; - if (arg) + if (arg) { lnumarg = strtoll(arg, &buff, 0); - else { + } else { numarg = 0; break; } @@ -1271,24 +1306,27 @@ struct optstruct *optparse(const char *cfgfile, int argc, char **argv, int verbo switch (*buff) { case 'G': case 'g': - if (lnumarg <= lnumlimit / (1024 * 1024 * 1024)) + if (lnumarg <= lnumlimit / (1024 * 1024 * 1024)) { lnumarg *= 1024 * 1024 * 1024; - else + } else { errno = ERANGE; + } break; case 'M': case 'm': - if (lnumarg <= lnumlimit / (1024 * 1024)) + if (lnumarg <= lnumlimit / (1024 * 1024)) { lnumarg *= 1024 * 1024; - else + } else { errno = ERANGE; + } break; case 'K': case 'k': - if (lnumarg <= lnumlimit / 1024) + if (lnumarg <= lnumlimit / 1024) { lnumarg *= 1024; - else + } else { errno = ERANGE; + } break; case '\0': break; @@ -1296,25 +1334,29 @@ struct optstruct *optparse(const char *cfgfile, int argc, char **argv, int verbo if (cfgfile) { fprintf(stderr, "ERROR: Can't parse numerical argument for option %s\n", name); } else { - if (optentry->shortopt) + if (optentry->shortopt) { fprintf(stderr, "ERROR: Can't parse numerical argument for option --%s (-%c)\n", optentry->longopt, optentry->shortopt); - else + } else { fprintf(stderr, "ERROR: Can't parse numerical argument for option --%s\n", optentry->longopt); + } } err = 1; } } arg = NULL; - if (err) break; + if (err) { + break; + } if (errno == ERANGE) { if (cfgfile) { fprintf(stderr, "WARNING: Numerical value for option %s too high, resetting to %lld\n", name, lnumlimit); } else { - if (optentry->shortopt) + if (optentry->shortopt) { fprintf(stderr, "WARNING: Numerical value for option --%s (-%c) too high, resetting to %lld\n", optentry->longopt, optentry->shortopt, lnumlimit); - else + } else { fprintf(stderr, "WARNING: Numerical value for option %s too high, resetting to %lld\n", optentry->longopt, lnumlimit); + } } lnumarg = lnumlimit; } @@ -1323,30 +1365,34 @@ struct optstruct *optparse(const char *cfgfile, int argc, char **argv, int verbo break; case CLOPT_TYPE_BOOL: - if (!strcasecmp(arg, "yes") || !strcmp(arg, "1") || !strcasecmp(arg, "true")) + if (!strcasecmp(arg, "yes") || !strcmp(arg, "1") || !strcasecmp(arg, "true")) { numarg = 1; - else + } else { numarg = 0; + } arg = NULL; break; } - if (err) + if (err) { break; + } if (optaddarg(opts, name, arg, numarg) < 0) { - if (cfgfile) + if (cfgfile) { fprintf(stderr, "ERROR: Can't register argument for option %s\n", name); - else + } else { fprintf(stderr, "ERROR: Can't register argument for option --%s\n", optentry->longopt); + } err = 1; break; } } - if (fs) + if (fs) { fclose(fs); + } if (err) { optfree(opts); @@ -1386,13 +1432,15 @@ struct optstruct *optadditem(const char *name, const char *arg, int verbose, int int regflags = REG_EXTENDED | REG_NOSUB; const struct clam_option *optentry = NULL; - if (oldopts) + if (oldopts) { opts = oldopts; + } for (i = 0;; i++) { optentry = &clam_options[i]; - if (!optentry->name && !optentry->longopt) + if (!optentry->name && !optentry->longopt) { break; + } if (((optentry->owner & toolmask) && ((optentry->owner & toolmask) != OPT_DEPRECATED)) || (ignore && (optentry->owner & ignore))) { if (!oldopts && optadd(&opts, &opts_last, optentry->name, optentry->longopt, optentry->strarg, optentry->numarg, optentry->flags, i) < 0) { @@ -1418,16 +1466,18 @@ struct optstruct *optadditem(const char *name, const char *arg, int verbose, int opt = optget_i(opts, name); if (!opt) { - if (verbose) + if (verbose) { fprintf(stderr, "ERROR: Parse error: Unknown option %s\n", name); + } err = 1; break; } optentry = &clam_options[opt->idx]; if (ignore && (optentry->owner & ignore) && !(optentry->owner & toolmask)) { - if (verbose) + if (verbose) { fprintf(stderr, "WARNING: Ignoring unsupported option %s\n", opt->name); + } continue; } @@ -1439,15 +1489,17 @@ struct optstruct *optadditem(const char *name, const char *arg, int verbose, int break; } } else { - if (verbose) + if (verbose) { fprintf(stderr, "WARNING: Ignoring deprecated option %s\n", opt->name); + } } continue; } if (optentry->regex) { - if (!(optentry->flags & FLAG_REG_CASE)) + if (!(optentry->flags & FLAG_REG_CASE)) { regflags |= REG_ICASE; + } if (cli_regcomp(®ex, optentry->regex, regflags)) { fprintf(stderr, "ERROR: optparse: Can't compile regular expression %s for option %s\n", optentry->regex, name); @@ -1466,32 +1518,35 @@ struct optstruct *optadditem(const char *name, const char *arg, int verbose, int numarg = -1; switch (optentry->argtype) { case CLOPT_TYPE_STRING: - if (!arg) + if (!arg) { arg = optentry->strarg; + } break; case CLOPT_TYPE_NUMBER: - if (arg) + if (arg) { numarg = atoi(arg); - else + } else { numarg = 0; + } arg = NULL; break; case CLOPT_TYPE_SIZE: case CLOPT_TYPE_SIZE64: - if (optentry->argtype == CLOPT_TYPE_SIZE64) + if (optentry->argtype == CLOPT_TYPE_SIZE64) { /* guaranteed to be "long long" (64 bit but possibly signed) further down the line */ lnumlimit = LLONG_MAX; - else + } else { /* probably mostly "unsigned long int" (32 or 64 bit unsigned depending on platform), * but may be expected to fit into a "long long" (64-bit signed) */ lnumlimit = LLONG_MAX < ULONG_MAX ? LLONG_MAX : ULONG_MAX; + } errno = 0; - if (arg) + if (arg) { lnumarg = strtoll(arg, &buff, 0); - else { + } else { numarg = 0; break; } @@ -1499,24 +1554,27 @@ struct optstruct *optadditem(const char *name, const char *arg, int verbose, int switch (*buff) { case 'G': case 'g': - if (lnumarg <= lnumlimit / (1024 * 1024 * 1024)) + if (lnumarg <= lnumlimit / (1024 * 1024 * 1024)) { lnumarg *= 1024 * 1024 * 1024; - else + } else { errno = ERANGE; + } break; case 'M': case 'm': - if (lnumarg <= lnumlimit / (1024 * 1024)) + if (lnumarg <= lnumlimit / (1024 * 1024)) { lnumarg *= 1024 * 1024; - else + } else { errno = ERANGE; + } break; case 'K': case 'k': - if (lnumarg <= lnumlimit / 1024) + if (lnumarg <= lnumlimit / 1024) { lnumarg *= 1024; - else + } else { errno = ERANGE; + } break; case '\0': break; @@ -1527,7 +1585,9 @@ struct optstruct *optadditem(const char *name, const char *arg, int verbose, int } arg = NULL; - if (err) break; + if (err) { + break; + } if (errno == ERANGE) { fprintf(stderr, "WARNING: Numerical value for option %s too high, resetting to 4G\n", name); lnumarg = UINT_MAX; @@ -1537,17 +1597,19 @@ struct optstruct *optadditem(const char *name, const char *arg, int verbose, int break; case CLOPT_TYPE_BOOL: - if (!strcasecmp(arg, "yes") || !strcmp(arg, "1") || !strcasecmp(arg, "true")) + if (!strcasecmp(arg, "yes") || !strcmp(arg, "1") || !strcasecmp(arg, "true")) { numarg = 1; - else + } else { numarg = 0; + } arg = NULL; break; } - if (err) + if (err) { break; + } if (optaddarg(opts, name, arg, numarg) < 0) { fprintf(stderr, "ERROR: Can't register argument for option --%s\n", optentry->longopt); diff --git a/common/output.c b/common/output.c index 0c7ccdba1c..4f2047e274 100644 --- a/common/output.c +++ b/common/output.c @@ -156,12 +156,14 @@ int mdprintf(int desc, const char *str, ...) buff[len - 1] = 0; if (bytes < 0) { - if (len > sizeof(buffer)) + if (len > sizeof(buffer)) { free(abuffer); + } return bytes; } - if ((size_t)bytes >= len) + if ((size_t)bytes >= len) { bytes = len - 1; + } todo = bytes; #ifdef CL_THREAD_SAFE @@ -173,9 +175,10 @@ int mdprintf(int desc, const char *str, ...) ret = send(desc, buff, bytes, 0); if (ret < 0) { struct timeval tv; - if (errno != EWOULDBLOCK) + if (errno != EWOULDBLOCK) { break; - /* didn't send anything yet */ + } + /* didn't send anything yet */ #ifdef CL_THREAD_SAFE pthread_mutex_unlock(&mdprintf_mutex); #endif @@ -204,8 +207,9 @@ int mdprintf(int desc, const char *str, ...) pthread_mutex_unlock(&mdprintf_mutex); #endif - if (len > sizeof(buffer)) + if (len > sizeof(buffer)) { free(abuffer); + } return ret < 0 ? -1 : bytes; } @@ -229,8 +233,9 @@ static int rename_logg(STATBUF *sb) rotate_file_len = strlen(logg_file) + strlen("-YYYY-MM-DD_HH:MM:SS.log"); rotate_file = calloc(1, rotate_file_len + 1); if (!rotate_file) { - if (logg_fp) + if (logg_fp) { fprintf(logg_fp, "Need to rotate log file due to size but ran out of memory.\n"); + } return -1; } @@ -242,8 +247,9 @@ static int rename_logg(STATBUF *sb) #else if (!localtime_r(&t, &tmp)) { #endif - if (logg_fp) + if (logg_fp) { fprintf(logg_fp, "Need to rotate log file due to size but could not get local time.\n"); + } free(rotate_file); return -1; @@ -275,12 +281,17 @@ static int logg_open(void) { STATBUF sb; - if (logg_file) - if (logg_size > 0) - if (CLAMSTAT(logg_file, &sb) != -1) - if (sb.st_size > logg_size) - if (rename_logg(&sb)) + if (logg_file) { + if (logg_size > 0) { + if (CLAMSTAT(logg_file, &sb) != -1) { + if (sb.st_size > logg_size) { + if (rename_logg(&sb)) { return -1; + } + } + } + } + } return 0; } @@ -288,8 +299,9 @@ static int logg_open(void) void logg_close(void) { #if defined(USE_SYSLOG) && !defined(C_AIX) - if (logg_syslog) + if (logg_syslog) { closelog(); + } #endif #ifdef CL_THREAD_SAFE @@ -315,8 +327,9 @@ int logg(loglevel_t loglevel, const char *str, ...) #endif if ((loglevel == LOGG_DEBUG_NV && logg_verbose < 2) || - (loglevel == LOGG_DEBUG && !logg_verbose)) + (loglevel == LOGG_DEBUG && !logg_verbose)) { return 0; + } ARGLEN(args, str, len); if (len <= sizeof(buffer)) { @@ -354,8 +367,9 @@ int logg(loglevel_t loglevel, const char *str, ...) #ifdef CL_THREAD_SAFE pthread_mutex_unlock(&logg_mutex); #endif - if (abuffer) + if (abuffer) { free(abuffer); + } return -1; } @@ -369,8 +383,9 @@ int logg(loglevel_t loglevel, const char *str, ...) #ifdef CL_THREAD_SAFE pthread_mutex_unlock(&logg_mutex); #endif - if (abuffer) + if (abuffer) { free(abuffer); + } return -1; } @@ -380,9 +395,9 @@ int logg(loglevel_t loglevel, const char *str, ...) fl.l_type = F_WRLCK; if (fcntl(fileno(logg_fp), F_SETLK, &fl) == -1) { #ifdef EOPNOTSUPP - if (errno == EOPNOTSUPP) + if (errno == EOPNOTSUPP) { printf("WARNING: File locking not supported (NFS?)\n"); - else + } else #endif { char errbuf[128]; @@ -394,8 +409,9 @@ int logg(loglevel_t loglevel, const char *str, ...) #endif fclose(logg_fp); logg_fp = NULL; - if (abuffer) + if (abuffer) { free(abuffer); + } return -1; } } @@ -421,18 +437,21 @@ int logg(loglevel_t loglevel, const char *str, ...) fprintf(logg_fp, "ERROR: %s", buff); flush = 1; } else if (loglevel == LOGG_WARNING) { - if (!logg_nowarn) + if (!logg_nowarn) { fprintf(logg_fp, "WARNING: %s", buff); + } flush = 1; } else if (loglevel == LOGG_DEBUG || loglevel == LOGG_DEBUG_NV) { fprintf(logg_fp, "%s", buff); } else if (loglevel == LOGG_INFO_NF || loglevel == LOGG_INFO) { fprintf(logg_fp, "%s", buff); - } else + } else { fprintf(logg_fp, "%s", buff); + } - if (flush) + if (flush) { fflush(logg_fp); + } } if (logg_foreground) { @@ -456,12 +475,14 @@ int logg(loglevel_t loglevel, const char *str, ...) if (loglevel == LOGG_ERROR) { syslog(LOG_ERR, "%s", buff); } else if (loglevel == LOGG_WARNING) { - if (!logg_nowarn) + if (!logg_nowarn) { syslog(LOG_WARNING, "%s", buff); + } } else if (loglevel == LOGG_DEBUG || loglevel == LOGG_DEBUG_NV) { syslog(LOG_DEBUG, "%s", buff); - } else + } else { syslog(LOG_INFO, "%s", buff); + } } #endif @@ -469,8 +490,9 @@ int logg(loglevel_t loglevel, const char *str, ...) pthread_mutex_unlock(&logg_mutex); #endif - if (abuffer) + if (abuffer) { free(abuffer); + } return 0; } @@ -482,8 +504,9 @@ void mprintf(loglevel_t loglevel, const char *str, ...) char buffer[512], *abuffer = NULL, *buff; size_t len; - if (mprintf_disabled) + if (mprintf_disabled) { return; + } fd = stdout; @@ -535,30 +558,36 @@ void mprintf(loglevel_t loglevel, const char *str, ...) } while (0); #endif if (loglevel == LOGG_ERROR) { - if (!mprintf_stdout) + if (!mprintf_stdout) { fd = stderr; + } fprintf(fd, "ERROR: %s", buff); } else if (!mprintf_quiet) { if (loglevel == LOGG_WARNING) { if (!mprintf_nowarn) { - if (!mprintf_stdout) + if (!mprintf_stdout) { fd = stderr; + } fprintf(fd, "WARNING: %s", buff); } } else if (loglevel == LOGG_DEBUG) { - if (mprintf_verbose) + if (mprintf_verbose) { fprintf(fd, "%s", buff); + } } else if (loglevel == LOGG_INFO) { fprintf(fd, "%s", buff); - } else + } else { fprintf(fd, "%s", buff); + } } - if (fd == stdout) + if (fd == stdout) { fflush(stdout); + } - if (len > sizeof(buffer)) + if (len > sizeof(buffer)) { free(abuffer); + } } struct facstruct { @@ -637,9 +666,11 @@ int logg_facility(const char *name) { int i; - for (i = 0; facilitymap[i].name; i++) - if (!strcmp(facilitymap[i].name, name)) + for (i = 0; facilitymap[i].name; i++) { + if (!strcmp(facilitymap[i].name, name)) { return facilitymap[i].code; + } + } return -1; } diff --git a/common/tar.c b/common/tar.c index d62c90f535..31140b6e12 100644 --- a/common/tar.c +++ b/common/tar.c @@ -61,8 +61,9 @@ int tar_addfile(int fd, gzFile gzs, const char *file) unsigned char buff[FILEBUFF], *pt; unsigned int i, chksum = 0; - if ((s = open(file, O_RDONLY | O_BINARY)) == -1) + if ((s = open(file, O_RDONLY | O_BINARY)) == -1) { return -1; + } if (FSTAT(s, &sb) == -1) { close(s); @@ -74,8 +75,9 @@ int tar_addfile(int fd, gzFile gzs, const char *file) hdr.name[99] = '\0'; snprintf(hdr.size, 12, "%o", (unsigned int)sb.st_size); pt = (unsigned char *)&hdr; - for (i = 0; i < TARBLK; i++) + for (i = 0; i < TARBLK; i++) { chksum += *pt++; + } snprintf(hdr.chksum, 8, "%06o", chksum + 256); if (gzs) { @@ -108,11 +110,13 @@ int tar_addfile(int fd, gzFile gzs, const char *file) if (sb.st_size % TARBLK) { memset(&hdr, 0, TARBLK); if (gzs) { - if (!gzwrite(gzs, &hdr, TARBLK - (sb.st_size % TARBLK))) + if (!gzwrite(gzs, &hdr, TARBLK - (sb.st_size % TARBLK))) { return -1; + } } else { - if (write(fd, &hdr, TARBLK - (sb.st_size % TARBLK)) == -1) + if (write(fd, &hdr, TARBLK - (sb.st_size % TARBLK)) == -1) { return -1; + } } } diff --git a/freshclam/CMakeLists.txt b/freshclam/CMakeLists.txt index 1aad53091e..92df8d75e1 100644 --- a/freshclam/CMakeLists.txt +++ b/freshclam/CMakeLists.txt @@ -27,6 +27,12 @@ if(WIN32) endif() set_target_properties( freshclam-bin PROPERTIES COMPILE_FLAGS "${WARNCFLAGS}" ) +if(CLANG_TIDY) + set_target_properties( freshclam-bin PROPERTIES + C_CLANG_TIDY "${CLANG_TIDY_PROPERTY}" + C_CLANG_TIDY_EXPORT_FIXES_DIR "${CMAKE_BINARY_DIR}/clang-tidy-fixes" ) +endif() + if (APPLE AND CLAMAV_SIGN_FILE) set_target_properties( freshclam-bin PROPERTIES XCODE_ATTRIBUTE_CODE_SIGN_IDENTITY ${CODE_SIGN_IDENTITY} diff --git a/freshclam/execute.c b/freshclam/execute.c index c343e93276..0b18567f0f 100644 --- a/freshclam/execute.c +++ b/freshclam/execute.c @@ -46,8 +46,9 @@ void execute(const char *type, const char *text, int bDaemonized) logg(LOGG_DEBUG, "%s: EXIT_%d\n", type, ret); exit(ret); } - if (system(text) == -1) + if (system(text) == -1) { logg(LOGG_INFO, "%s: system(%s) failed\n", type, text); + } return; } diff --git a/freshclam/freshclam.c b/freshclam/freshclam.c index cf4965acce..49920004cd 100644 --- a/freshclam/freshclam.c +++ b/freshclam/freshclam.c @@ -89,8 +89,9 @@ sighandler(int sig) switch (sig) { #ifdef SIGCHLD case SIGCHLD: - if (g_sigchildWait) + if (g_sigchildWait) { waitpid(-1, NULL, WNOHANG); + } g_active_children--; break; #endif @@ -115,10 +116,12 @@ sighandler(int sig) break; #endif default: - if (*g_freshclamTempDirectory) + if (*g_freshclamTempDirectory) { cli_rmdirs(g_freshclamTempDirectory); - if (g_pidfile) + } + if (g_pidfile) { unlink(g_pidfile); + } logg(LOGG_INFO, "Update process terminated\n"); exit(0); } @@ -371,8 +374,9 @@ fc_error_t download_complete_callback(const char *dbFilename, void *context) firstline[0] = 0; lastline[0] = 0; do { - if (!fgets(firstline, sizeof(firstline), pipeHandle)) + if (!fgets(firstline, sizeof(firstline), pipeHandle)) { break; + } /* ignore warning messages, otherwise the outdated warning will * make us miss the important part of the error message */ } while (!strncmp(firstline, "LibClamAV Warning:", 18)); @@ -388,8 +392,9 @@ fc_error_t download_complete_callback(const char *dbFilename, void *context) continue; } - if ((waitpidret == -1) && (errno != ECHILD)) + if ((waitpidret == -1) && (errno != ECHILD)) { logg(LOGG_WARNING, "waitpid() failed: %s\n", strerror(errno)); + } /* Strip trailing whitespace from child error output */ cli_chomp(firstline); @@ -408,8 +413,9 @@ fc_error_t download_complete_callback(const char *dbFilename, void *context) goto done; } - if (firstline[0]) + if (firstline[0]) { logg(LOGG_WARNING, "Database successfully loaded, but there is stderr output\n"); + } } else if (WIFSIGNALED(stat_loc)) { logg(LOGG_ERROR, "Database load killed by signal %d\n", WTERMSIG(stat_loc)); @@ -866,8 +872,9 @@ static fc_error_t initialize(struct optstruct *opts) /* Set libclamav Message and [file-based] Logging option flags. mprintf and logg options are also directly set, as they are also used in freshclam (not only used in libfreshclam) */ - if (optget(opts, "Debug")->enabled || optget(opts, "debug")->enabled) + if (optget(opts, "Debug")->enabled || optget(opts, "debug")->enabled) { fcConfig.msgFlags |= FC_CONFIG_MSG_DEBUG; + } if ((optget(opts, "verbose")->enabled) || (optget(opts, "LogVerbose")->enabled)) { @@ -903,8 +910,9 @@ static fc_error_t initialize(struct optstruct *opts) if (optget(opts, "LogFileMaxSize")->numarg && optget(opts, "LogRotate")->enabled) { fcConfig.logFlags |= FC_CONFIG_LOG_ROTATE; } - if (optget(opts, "LogSyslog")->enabled) + if (optget(opts, "LogSyslog")->enabled) { fcConfig.logFlags |= FC_CONFIG_LOG_SYSLOG; + } logFileOpt = optget(opts, "UpdateLogFile"); if (logFileOpt->enabled) { @@ -922,8 +930,9 @@ static fc_error_t initialize(struct optstruct *opts) } #endif - if ((optget(opts, "LocalIPAddress"))->enabled) + if ((optget(opts, "LocalIPAddress"))->enabled) { fcConfig.localIP = (optget(opts, "LocalIPAddress"))->strarg; + } /* Select a path for the temp directory: databaseDirectory/tmp */ tempDirectory = cli_gentemp_with_prefix(fcConfig.databaseDirectory, "tmp"); @@ -960,8 +969,9 @@ static fc_error_t initialize(struct optstruct *opts) /* Initialize proxy settings */ if (optget(opts, "HTTPProxyServer")->enabled) { fcConfig.proxyServer = optget(opts, "HTTPProxyServer")->strarg; - if (strncasecmp(fcConfig.proxyServer, "http://", strlen("http://")) == 0) + if (strncasecmp(fcConfig.proxyServer, "http://", strlen("http://")) == 0) { fcConfig.proxyServer += strlen("http://"); + } if (optget(opts, "HTTPProxyUsername")->enabled) { fcConfig.proxyUsername = optget(opts, "HTTPProxyUsername")->strarg; @@ -973,8 +983,9 @@ static fc_error_t initialize(struct optstruct *opts) goto done; } } - if (optget(opts, "HTTPProxyPort")->enabled) + if (optget(opts, "HTTPProxyPort")->enabled) { fcConfig.proxyPort = (uint16_t)optget(opts, "HTTPProxyPort")->numarg; + } logg(LOGG_INFO, "Connecting via %s\n", fcConfig.proxyServer); } @@ -1677,8 +1688,9 @@ int main(int argc, char **argv) int i; pid_t parentPid = getpid(); - if (check_flevel()) + if (check_flevel()) { exit(FC_EINIT); + } if ((opts = optparse(NULL, argc, argv, 1, OPT_FRESHCLAM, 0, NULL)) == NULL) { mprintf(LOGG_ERROR, "Can't parse command line options\n"); @@ -2099,11 +2111,13 @@ int main(int argc, char **argv) #endif if (ret > FC_UPTODATE) { - if ((opt = optget(opts, "OnErrorExecute"))->enabled) + if ((opt = optget(opts, "OnErrorExecute"))->enabled) { arg = opt->strarg; + } - if (arg) + if (arg) { execute("OnErrorExecute", arg, optget(opts, "daemon")->enabled); + } arg = NULL; @@ -2160,8 +2174,9 @@ int main(int argc, char **argv) done: if ((status > FC_UPTODATE) && (NULL != opts)) { - if ((opt = optget(opts, "OnErrorExecute"))->enabled) + if ((opt = optget(opts, "OnErrorExecute"))->enabled) { execute("OnErrorExecute", opt->strarg, optget(opts, "daemon")->enabled); + } } logg_close(); diff --git a/freshclam/notify.c b/freshclam/notify.c index fb30b545d9..f5d72325fc 100644 --- a/freshclam/notify.c +++ b/freshclam/notify.c @@ -152,8 +152,9 @@ int notify(const char *cfgfile) char buff[20]; int sockd, bread; - if ((sockd = clamd_connect(cfgfile, "NotifyClamd")) < 0) + if ((sockd = clamd_connect(cfgfile, "NotifyClamd")) < 0) { return 1; + } if (sendln(sockd, "RELOAD", 7) < 0) { logg(LOGG_ERROR, "NotifyClamd: Could not write to clamd socket: %s\n", strerror(errno)); diff --git a/libclamav/7z_iface.c b/libclamav/7z_iface.c index 2d964d154e..1baa9f0355 100644 --- a/libclamav/7z_iface.c +++ b/libclamav/7z_iface.c @@ -42,8 +42,9 @@ static SRes FileInStream_fmap_Read(void *pp, void *buf, size_t *size) CFileInStream *p = (CFileInStream *)pp; size_t read_sz; - if (*size == 0) + if (*size == 0) { return 0; + } read_sz = fmap_readn(p->file.fmap, buf, p->s.curpos, *size); if (read_sz == (size_t)-1) { @@ -100,8 +101,9 @@ int cli_7unz(cli_ctx *ctx, size_t offset) LookToRead_CreateVTable(&lookStream, False); - if (archiveStream.s.Seek(&archiveStream.s, &begin_of_archive, SZ_SEEK_SET) != 0) + if (archiveStream.s.Seek(&archiveStream.s, &begin_of_archive, SZ_SEEK_SET) != 0) { return CL_CLEAN; + } lookStream.realStream = &archiveStream.s; LookToRead_Init(&lookStream); @@ -127,23 +129,27 @@ int cli_7unz(cli_ctx *ctx, size_t offset) int newnamelen, fd; // abort if we would exceed max files or max scan time. - if ((found = cli_checklimits("7unz", ctx, 0, 0, 0))) + if ((found = cli_checklimits("7unz", ctx, 0, 0, 0))) { break; + } - if (f->IsDir) + if (f->IsDir) { continue; + } // skip this file if we would exceed max file size or max scan size. (we already checked for the max files and max scan time) - if (cli_checklimits("7unz", ctx, f->Size, 0, 0)) + if (cli_checklimits("7unz", ctx, f->Size, 0, 0)) { continue; + } - if (!db.FileNameOffsets) + if (!db.FileNameOffsets) { newnamelen = 0; /* no filename */ - else { + } else { newnamelen = SzArEx_GetFileNameUtf16(&db, i, NULL); if (newnamelen > namelen) { - if (namelen > UTFBUFSZ) + if (namelen > UTFBUFSZ) { free(utf16name); + } utf16name = cli_max_malloc(newnamelen * 2); if (!utf16name) { found = CL_EMEM; @@ -155,8 +161,9 @@ int cli_7unz(cli_ctx *ctx, size_t offset) } name = (char *)utf16name; - for (j = 0; j < (size_t)newnamelen; j++) /* FIXME */ + for (j = 0; j < (size_t)newnamelen; j++) { /* FIXME */ name[j] = utf16name[j]; + } name[j] = 0; cli_dbgmsg("cli_7unz: extracting %s\n", name); @@ -175,13 +182,14 @@ int cli_7unz(cli_ctx *ctx, size_t offset) found = CL_VIRUS; break; } - if (res != SZ_OK) + if (res != SZ_OK) { cli_dbgmsg("cli_unz: extraction failed with %d\n", res); - else if ((outBuffer == NULL) || (outSizeProcessed == 0)) { + } else if ((outBuffer == NULL) || (outSizeProcessed == 0)) { cli_dbgmsg("cli_unz: extracted empty file\n"); } else { - if ((found = cli_gentempfd(ctx->sub_tmpdir, &tmp_name, &fd))) + if ((found = cli_gentempfd(ctx->sub_tmpdir, &tmp_name, &fd))) { break; + } cli_dbgmsg("cli_7unz: Saving to %s\n", tmp_name); if (cli_writen(fd, outBuffer + offset, outSizeProcessed) != outSizeProcessed) { @@ -191,32 +199,36 @@ int cli_7unz(cli_ctx *ctx, size_t offset) found = cli_magic_scan_desc(fd, tmp_name, ctx, name, LAYER_ATTRIBUTES_NONE); close(fd); - if (!ctx->engine->keeptmp && cli_unlink(tmp_name)) + if (!ctx->engine->keeptmp && cli_unlink(tmp_name)) { found = CL_EUNLINK; + } free(tmp_name); - if (found != CL_SUCCESS) + if (found != CL_SUCCESS) { break; + } } } IAlloc_Free(&allocImp, outBuffer); } SzArEx_Free(&db, &allocImp); - if (namelen > UTFBUFSZ) + if (namelen > UTFBUFSZ) { free(utf16name); + } - if (res == SZ_OK) + if (res == SZ_OK) { cli_dbgmsg("cli_7unz: completed successfully\n"); - else if (res == SZ_ERROR_UNSUPPORTED) + } else if (res == SZ_ERROR_UNSUPPORTED) { cli_dbgmsg("cli_7unz: unsupported\n"); - else if (res == SZ_ERROR_MEM) + } else if (res == SZ_ERROR_MEM) { cli_dbgmsg("cli_7unz: oom\n"); - else if (res == SZ_ERROR_CRC) + } else if (res == SZ_ERROR_CRC) { cli_dbgmsg("cli_7unz: crc mismatch\n"); - else if (res == SZ_ERROR_ENCRYPTED) + } else if (res == SZ_ERROR_ENCRYPTED) { cli_dbgmsg("cli_7unz: encrypted\n"); - else + } else { cli_dbgmsg("cli_7unz: error %d\n", res); + } return found; } diff --git a/libclamav/CMakeLists.txt b/libclamav/CMakeLists.txt index a59975f4dc..99a23bda4a 100644 --- a/libclamav/CMakeLists.txt +++ b/libclamav/CMakeLists.txt @@ -178,6 +178,12 @@ else() bytecode.h ) set_target_properties( bytecode_runtime PROPERTIES COMPILE_FLAGS "${WARNCFLAGS}" ) + + if(CLANG_TIDY) + set_target_properties( bytecode_runtime PROPERTIES + C_CLANG_TIDY "${CLANG_TIDY_PROPERTY}" + C_CLANG_TIDY_EXPORT_FIXES_DIR "${CMAKE_BINARY_DIR}/clang-tidy-fixes" ) + endif() endif() target_include_directories( bytecode_runtime PRIVATE ${CMAKE_BINARY_DIR} @@ -462,6 +468,12 @@ if(ENABLE_SHARED_LIB) COMPILE_FLAGS "${WARNCFLAGS}" VERSION ${LIBCLAMAV_VERSION} SOVERSION ${LIBCLAMAV_SOVERSION} ) + if(CLANG_TIDY) + set_target_properties( clamav PROPERTIES + C_CLANG_TIDY "${CLANG_TIDY_PROPERTY}" + C_CLANG_TIDY_EXPORT_FIXES_DIR "${CMAKE_BINARY_DIR}/clang-tidy-fixes" ) + endif() + if (APPLE AND CLAMAV_SIGN_FILE) set_target_properties( clamav PROPERTIES XCODE_ATTRIBUTE_CODE_SIGN_IDENTITY ${CODE_SIGN_IDENTITY} diff --git a/libclamav/arc4.c b/libclamav/arc4.c index db9523632c..ed8ed10bb0 100644 --- a/libclamav/arc4.c +++ b/libclamav/arc4.c @@ -33,13 +33,15 @@ bool arc4_init(struct arc4_state *a, const uint8_t *key, unsigned keylength) uint8_t j; uint32_t *S; - if (NULL == a || NULL == key || 0 == keylength) + if (NULL == a || NULL == key || 0 == keylength) { return false; + } S = &a->S[0]; - for (i = 0; i < 256; i++) + for (i = 0; i < 256; i++) { S[i] = i; + } for (i = 0, j = 0; i < 256; i++) { uint8_t tmp = S[i]; j = j + S[i] + key[i % keylength]; diff --git a/libclamav/asn1.c b/libclamav/asn1.c index 48b628237a..cf567a5f08 100644 --- a/libclamav/asn1.c +++ b/libclamav/asn1.c @@ -284,8 +284,9 @@ static int asn1_get_obj(fmap_t *map, const void *asn1data, unsigned int *asn1len obj->size |= *data; data++; } - } else + } else { obj->size = i; + } asn1_sz -= data - (uint8_t *)asn1data; if (obj->size > asn1_sz) { @@ -294,10 +295,11 @@ static int asn1_get_obj(fmap_t *map, const void *asn1data, unsigned int *asn1len } obj->content = data; - if (obj->size == asn1_sz) + if (obj->size == asn1_sz) { obj->next = NULL; - else + } else { obj->next = data + obj->size; + } *asn1len = asn1_sz - obj->size; return 0; } @@ -305,8 +307,9 @@ static int asn1_get_obj(fmap_t *map, const void *asn1data, unsigned int *asn1len static int asn1_expect_objtype(fmap_t *map, const void *asn1data, unsigned int *asn1len, struct cli_asn1 *obj, uint8_t type) { int ret = asn1_get_obj(map, asn1data, asn1len, obj); - if (ret) + if (ret) { return ret; + } if (obj->type != type) { cli_dbgmsg("asn1_expect_objtype: expected type %02x, got %02x\n", type, obj->type); return 1; @@ -318,8 +321,9 @@ static int asn1_expect_obj(fmap_t *map, const void **asn1data, unsigned int *asn { struct cli_asn1 obj; int ret = asn1_expect_objtype(map, *asn1data, asn1len, &obj, type); - if (ret) + if (ret) { return ret; + } if (obj.size != size) { cli_dbgmsg("asn1_expect_obj: expected size %u, got %u\n", size, obj.size); return 1; @@ -343,13 +347,15 @@ static int asn1_expect_algo(fmap_t *map, const void **asn1data, unsigned int *as struct cli_asn1 obj; unsigned int avail; int ret; - if ((ret = asn1_expect_objtype(map, *asn1data, asn1len, &obj, ASN1_TYPE_SEQUENCE))) /* SEQUENCE */ + if ((ret = asn1_expect_objtype(map, *asn1data, asn1len, &obj, ASN1_TYPE_SEQUENCE))) { /* SEQUENCE */ return ret; + } avail = obj.size; *asn1data = obj.next; - if ((ret = asn1_expect_obj(map, &obj.content, &avail, ASN1_TYPE_OBJECT_ID, algo_size, algo))) /* ALGO */ + if ((ret = asn1_expect_obj(map, &obj.content, &avail, ASN1_TYPE_OBJECT_ID, algo_size, algo))) { /* ALGO */ return ret; + } // The specification says that the NULL is a required parameter for this // data type, but in practice it doesn't always exist in the ASN1. If @@ -535,14 +541,15 @@ static int asn1_get_time(fmap_t *map, const void **asn1data, unsigned int *size, struct tm t; int n; - if (ret) + if (ret) { return ret; + } - if (obj.type == 0x17) /* UTCTime - YYMMDDHHMMSSZ */ + if (obj.type == 0x17) { /* UTCTime - YYMMDDHHMMSSZ */ len = 13; - else if (obj.type == 0x18) /* GeneralizedTime - YYYYMMDDHHMMSSZ */ + } else if (obj.type == 0x18) { /* GeneralizedTime - YYYYMMDDHHMMSSZ */ len = 15; - else { + } else { cli_dbgmsg("asn1_get_time: expected UTCTime or GeneralizedTime, got %02x\n", obj.type); return 1; } @@ -556,21 +563,25 @@ static int asn1_get_time(fmap_t *map, const void **asn1data, unsigned int *size, ptr = (char *)obj.content; if (obj.type == 0x18) { t.tm_year = asn1_getnum(ptr) * 100; - if (t.tm_year < 0) + if (t.tm_year < 0) { return 1; + } n = asn1_getnum(ptr); - if (n < 0) + if (n < 0) { return 1; + } t.tm_year += n; ptr += 4; } else { n = asn1_getnum(ptr); - if (n < 0) + if (n < 0) { return 1; - if (n >= 50) + } + if (n >= 50) { t.tm_year = 1900 + n; - else + } else { t.tm_year = 2000 + n; + } ptr += 2; } t.tm_year -= 1900; @@ -645,8 +656,9 @@ static int asn1_get_rsa_pubkey(fmap_t *map, const void **asn1data, unsigned int struct cli_asn1 obj; unsigned int avail, avail2; - if (asn1_expect_objtype(map, *asn1data, size, &obj, ASN1_TYPE_SEQUENCE)) /* subjectPublicKeyInfo */ + if (asn1_expect_objtype(map, *asn1data, size, &obj, ASN1_TYPE_SEQUENCE)) { /* subjectPublicKeyInfo */ return 1; + } *asn1data = obj.next; avail = obj.size; @@ -655,8 +667,9 @@ static int asn1_get_rsa_pubkey(fmap_t *map, const void **asn1data, unsigned int return 1; } - if (asn1_expect_objtype(map, obj.content, &avail, &obj, ASN1_TYPE_BIT_STRING)) /* BIT STRING - subjectPublicKey */ + if (asn1_expect_objtype(map, obj.content, &avail, &obj, ASN1_TYPE_BIT_STRING)) { /* BIT STRING - subjectPublicKey */ return 1; + } if (avail) { cli_dbgmsg("asn1_get_rsa_pubkey: found unexpected extra data in subjectPublicKeyInfo\n"); return 1; @@ -675,16 +688,18 @@ static int asn1_get_rsa_pubkey(fmap_t *map, const void **asn1data, unsigned int avail = obj.size - 1; obj.content = ((uint8_t *)obj.content) + 1; - if (asn1_expect_objtype(map, obj.content, &avail, &obj, ASN1_TYPE_SEQUENCE)) /* SEQUENCE */ + if (asn1_expect_objtype(map, obj.content, &avail, &obj, ASN1_TYPE_SEQUENCE)) { /* SEQUENCE */ return 1; + } if (avail) { cli_dbgmsg("asn1_get_rsa_pubkey: found unexpected extra data in public key content\n"); return 1; } avail = obj.size; - if (asn1_expect_objtype(map, obj.content, &avail, &obj, ASN1_TYPE_INTEGER)) /* INTEGER - mod */ + if (asn1_expect_objtype(map, obj.content, &avail, &obj, ASN1_TYPE_INTEGER)) { /* INTEGER - mod */ return 1; + } if (obj.size < 1024 / 8 || obj.size > 4096 / 8 + 1) { cli_dbgmsg("asn1_get_rsa_pubkey: modulus has got an unsupported length (%u)\n", obj.size * 8); return 1; @@ -695,11 +710,13 @@ static int asn1_get_rsa_pubkey(fmap_t *map, const void **asn1data, unsigned int return 1; } - if (!BN_bin2bn(obj.content, avail2, x509->n)) + if (!BN_bin2bn(obj.content, avail2, x509->n)) { return 1; + } - if (asn1_expect_objtype(map, obj.next, &avail, &obj, ASN1_TYPE_INTEGER)) /* INTEGER - exp */ + if (asn1_expect_objtype(map, obj.next, &avail, &obj, ASN1_TYPE_INTEGER)) { /* INTEGER - exp */ return 1; + } if (avail) { cli_dbgmsg("asn1_get_rsa_pubkey: found unexpected extra data after exp\n"); return 1; @@ -713,8 +730,9 @@ static int asn1_get_rsa_pubkey(fmap_t *map, const void **asn1data, unsigned int return 1; } - if (!BN_bin2bn(obj.content, obj.size, x509->e)) + if (!BN_bin2bn(obj.content, obj.size, x509->e)) { return 1; + } return 0; } @@ -811,10 +829,12 @@ static int asn1_get_x509(fmap_t *map, const void **asn1data, unsigned int *size, break; } - if (map_raw(map, obj.content, obj.size, x509.raw_serial)) + if (map_raw(map, obj.content, obj.size, x509.raw_serial)) { break; - if (map_sha1(map, obj.content, obj.size, x509.serial)) + } + if (map_sha1(map, obj.content, obj.size, x509.serial)) { break; + } if (asn1_expect_rsa(map, &obj.next, &tbs.size, &hashtype1)) { /* algo - Ex: sha1WithRSAEncryption */ cli_dbgmsg("asn1_get_x509: unable to parse AlgorithmIdentifier\n"); @@ -856,10 +876,12 @@ static int asn1_get_x509(fmap_t *map, const void **asn1data, unsigned int *size, cli_dbgmsg("asn1_get_x509: expected SEQUENCE when parsing cert subject\n"); break; } - if (map_raw(map, obj.content, obj.size, x509.raw_subject)) + if (map_raw(map, obj.content, obj.size, x509.raw_subject)) { break; - if (map_sha1(map, obj.content, obj.size, x509.subject)) + } + if (map_sha1(map, obj.content, obj.size, x509.subject)) { break; + } if (asn1_get_rsa_pubkey(map, &obj.next, &tbs.size, &x509)) { /* subjectPublicKeyInfo */ cli_dbgmsg("asn1_get_x509: failed to get RSA public key\n"); break; @@ -931,8 +953,9 @@ static int asn1_get_x509(fmap_t *map, const void **asn1data, unsigned int *size, exts.size = 1; break; } - if (id.size != 3) + if (id.size != 3) { continue; + } if (!fmap_need_ptr_once(map, id.content, 3)) { exts.size = 1; @@ -958,8 +981,9 @@ static int asn1_get_x509(fmap_t *map, const void **asn1data, unsigned int *size, break; } usage = keyusage[3]; - if (value.size == 4) + if (value.size == 4) { usage &= ~((1 << keyusage[2]) - 1); + } x509.certSign = ((usage & 4) != 0); continue; } @@ -982,18 +1006,20 @@ static int asn1_get_x509(fmap_t *map, const void **asn1data, unsigned int *size, exts.size = 1; break; } - if (ext.size != 8 && ext.size != 10) + if (ext.size != 8 && ext.size != 10) { continue; + } if (!fmap_need_ptr_once(map, ext.content, ext.size)) { exts.size = 1; break; } - if (!memcmp("\x2b\x06\x01\x05\x05\x07\x03\x03", ext.content, 8)) /* id_kp_codeSigning */ + if (!memcmp("\x2b\x06\x01\x05\x05\x07\x03\x03", ext.content, 8)) { /* id_kp_codeSigning */ x509.codeSign = 1; - else if (!memcmp("\x2b\x06\x01\x05\x05\x07\x03\x08", ext.content, 8)) /* id_kp_timeStamping */ + } else if (!memcmp("\x2b\x06\x01\x05\x05\x07\x03\x08", ext.content, 8)) { /* id_kp_timeStamping */ x509.timeSign = 1; - else if (!memcmp("\x2b\x06\x01\x04\x01\x82\x37\x0a\x03\x0d", ext.content, 10)) /* id_kp_lifetimeSigning */ + } else if (!memcmp("\x2b\x06\x01\x04\x01\x82\x37\x0a\x03\x0d", ext.content, 10)) { /* id_kp_lifetimeSigning */ cli_dbgmsg("asn1_get_x509: lifetime signing specified but enforcing this is not currently supported\n"); + } } continue; } @@ -1008,9 +1034,9 @@ static int asn1_get_x509(fmap_t *map, const void **asn1data, unsigned int *size, exts.size = 1; break; } - if (!constr.size) + if (!constr.size) { x509.certSign = 0; - else { + } else { if (asn1_get_obj(map, constr.content, &constr.size, &ext)) { exts.size = 1; break; @@ -1054,8 +1080,9 @@ static int asn1_get_x509(fmap_t *map, const void **asn1data, unsigned int *size, * For time stamping, the doc says the EKU must be present, and * makes no exception for EKUs being missing. * TODO Should we not set timeSign = 1 in this case, then? */ - if (!have_ext_key) + if (!have_ext_key) { x509.codeSign = x509.timeSign = 1; + } /* RFC 3280 section 4.2.1.3 says that if a certificate is * used to validate digital signatures on other public key @@ -1066,8 +1093,9 @@ static int asn1_get_x509(fmap_t *map, const void **asn1data, unsigned int *size, * chain validate successfully. * TODO Flip the certSign bit for now, but revisit if * a clarification on this becomes available */ - if (!have_key_usage) + if (!have_key_usage) { x509.certSign = 1; + } } } if (tbs.size) { @@ -1079,13 +1107,16 @@ static int asn1_get_x509(fmap_t *map, const void **asn1data, unsigned int *size, cli_dbgmsg("asn1_get_x509: encountered a certificate with no cert, code, or time signing capabilities\n"); } - if (map_raw(map, issuer, issuersize, x509.raw_issuer)) + if (map_raw(map, issuer, issuersize, x509.raw_issuer)) { break; - if (map_sha1(map, issuer, issuersize, x509.issuer)) + } + if (map_sha1(map, issuer, issuersize, x509.issuer)) { break; + } - if (asn1_expect_rsa(map, &tbs.next, &crt.size, &hashtype2)) /* signature algo - Ex: sha1WithRSAEncryption */ + if (asn1_expect_rsa(map, &tbs.next, &crt.size, &hashtype2)) { /* signature algo - Ex: sha1WithRSAEncryption */ break; + } if (hashtype1 != hashtype2) { cli_dbgmsg("asn1_get_x509: found conflicting RSA hash types\n"); @@ -1112,8 +1143,9 @@ static int asn1_get_x509(fmap_t *map, const void **asn1data, unsigned int *size, break; } - if (!BN_bin2bn(obj.content, obj.size, x509.sig)) + if (!BN_bin2bn(obj.content, obj.size, x509.sig)) { break; + } if (crt.size) { cli_dbgmsg("asn1_get_x509: found unexpected extra data in signature\n"); @@ -1125,8 +1157,9 @@ static int asn1_get_x509(fmap_t *map, const void **asn1data, unsigned int *size, break; } - if (crtmgr_add(crts, &x509)) + if (crtmgr_add(crts, &x509)) { break; + } cli_crt_clear(&x509); return ASN1_GET_X509_SUCCESS; } while (0); @@ -1247,22 +1280,24 @@ static int asn1_parse_countersignature(fmap_t *map, const void **asn1data, unsig dsize = 1; break; } - if (deeper.size != lenof(OID_contentType)) /* lenof(contentType) = lenof(messageDigest) = lenof(signingTime) = 9 */ + if (deeper.size != lenof(OID_contentType)) { /* lenof(contentType) = lenof(messageDigest) = lenof(signingTime) = 9 */ continue; + } if (!fmap_need_ptr_once(map, deeper.content, lenof(OID_contentType))) { cli_dbgmsg("asn1_parse_countersignature: failed to read counterSignature authenticated attribute\n"); dsize = 1; break; } - if (!memcmp(deeper.content, OID_contentType, lenof(OID_contentType))) + if (!memcmp(deeper.content, OID_contentType, lenof(OID_contentType))) { content = 0; /* contentType */ - else if (!memcmp(deeper.content, OID_messageDigest, lenof(OID_messageDigest))) + } else if (!memcmp(deeper.content, OID_messageDigest, lenof(OID_messageDigest))) { content = 1; /* messageDigest */ - else if (!memcmp(deeper.content, OID_signingTime, lenof(OID_signingTime))) + } else if (!memcmp(deeper.content, OID_signingTime, lenof(OID_signingTime))) { content = 2; /* signingTime */ - else + } else { continue; + } if (result & (1 << content)) { cli_dbgmsg("asn1_parse_countersignature: duplicate field in countersignature\n"); dsize = 1; @@ -1298,16 +1333,18 @@ static int asn1_parse_countersignature(fmap_t *map, const void **asn1data, unsig } } - if (deep.size) + if (deep.size) { cli_dbgmsg("asn1_parse_countersignature: extra data in countersignature content-type\n"); + } break; } case 1: /* messageDigest */ if (asn1_expect_obj(map, &deeper.content, &deep.size, ASN1_TYPE_OCTET_STRING, hashsize, md)) { deep.size = 1; cli_dbgmsg("asn1_parse_countersignature: countersignature hash mismatch\n"); - } else if (deep.size) + } else if (deep.size) { cli_dbgmsg("asn1_parse_countersignature: extra data in countersignature message-digest\n"); + } break; case 2: /* signingTime */ { @@ -1315,9 +1352,9 @@ static int asn1_parse_countersignature(fmap_t *map, const void **asn1data, unsig if (asn1_get_time(map, &deeper.content, &deep.size, &sigdate)) { cli_dbgmsg("asn1_parse_countersignature: an error occurred when getting the time\n"); deep.size = 1; - } else if (deep.size) + } else if (deep.size) { cli_dbgmsg("asn1_parse_countersignature: extra data in countersignature signing-time\n"); - else if (sigdate < not_before || sigdate > not_after) { + } else if (sigdate < not_before || sigdate > not_after) { cli_dbgmsg("asn1_parse_countersignature: countersignature timestamp outside cert validity\n"); deep.size = 1; } @@ -1329,8 +1366,9 @@ static int asn1_parse_countersignature(fmap_t *map, const void **asn1data, unsig break; } } - if (dsize) + if (dsize) { break; + } if (result != 7) { cli_dbgmsg("asn1_parse_countersignature: some important attributes are missing in countersignature\n"); break; @@ -1573,12 +1611,15 @@ static cl_error_t asn1_parse_mscat(struct cl_engine *engine, fmap_t *map, size_t memset(raw_issuer, 0, CRT_RAWMAXLEN * 2 + 1); memset(raw_subject, 0, CRT_RAWMAXLEN * 2 + 1); memset(raw_serial, 0, CRT_RAWMAXLEN * 2 + 1); - for (j = 0; j < x509->raw_issuer[0]; j++) + for (j = 0; j < x509->raw_issuer[0]; j++) { sprintf(&raw_issuer[j * 2], "%02x", x509->raw_issuer[j + 1]); - for (j = 0; j < x509->raw_subject[0]; j++) + } + for (j = 0; j < x509->raw_subject[0]; j++) { sprintf(&raw_subject[j * 2], "%02x", x509->raw_subject[j + 1]); - for (j = 0; j < x509->raw_serial[0]; j++) + } + for (j = 0; j < x509->raw_serial[0]; j++) { sprintf(&raw_serial[j * 3], "%02x%c", x509->raw_serial[j + 1], (j != x509->raw_serial[0] - 1) ? ':' : '\0'); + } for (j = 0; j < SHA1_HASH_SIZE; j++) { sprintf(&issuer[j * 2], "%02x", x509->issuer[j]); sprintf(&subject[j * 2], "%02x", x509->subject[j]); @@ -1736,8 +1777,9 @@ static cl_error_t asn1_parse_mscat(struct cl_engine *engine, fmap_t *map, size_t crtmgr_free(&newcerts); break; } - if (newcerts.items) + if (newcerts.items) { cli_dbgmsg("asn1_parse_mscat: %u certificates did not verify\n", newcerts.items); + } crtmgr_free(&newcerts); } } @@ -1871,19 +1913,21 @@ static cl_error_t asn1_parse_mscat(struct cl_engine *engine, fmap_t *map, size_t dsize = 1; break; } - if (deeper.size != lenof(OID_contentType)) + if (deeper.size != lenof(OID_contentType)) { continue; + } if (!fmap_need_ptr_once(map, deeper.content, lenof(OID_contentType))) { cli_dbgmsg("asn1_parse_mscat: failed to read authenticated attribute\n"); dsize = 1; break; } - if (!memcmp(deeper.content, OID_contentType, lenof(OID_contentType))) + if (!memcmp(deeper.content, OID_contentType, lenof(OID_contentType))) { content = 0; /* contentType */ - else if (!memcmp(deeper.content, OID_messageDigest, lenof(OID_messageDigest))) + } else if (!memcmp(deeper.content, OID_messageDigest, lenof(OID_messageDigest))) { content = 1; /* messageDigest */ - else + } else { continue; + } if (asn1_expect_objtype(map, deeper.next, &deep.size, &deeper, ASN1_TYPE_SET)) { /* set - contents */ cli_dbgmsg("asn1_parse_mscat: expected 'set - contents' for authenticated attribute\n"); dsize = 1; @@ -1936,8 +1980,9 @@ static cl_error_t asn1_parse_mscat(struct cl_engine *engine, fmap_t *map, size_t break; } } - if (dsize) + if (dsize) { break; + } if (result != 3) { cli_dbgmsg("asn1_parse_mscat: contentType or messageDigest are missing\n"); break; @@ -2135,8 +2180,9 @@ static cl_error_t asn1_parse_mscat(struct cl_engine *engine, fmap_t *map, size_t break; } } - if (dsize) + if (dsize) { break; + } cli_dbgmsg("asn1_parse_mscat: unauthenticatedAttributes successfully parsed\n"); @@ -2182,38 +2228,48 @@ int asn1_load_mscat(fmap_t *map, struct cl_engine *engine) // TODO Since we pass engine->cmgr directly here, the whole chain of trust // for this .cat file will get added to the global trust store assuming it // verifies successfully. Is this a bug for a feature? - if (CL_CLEAN != asn1_parse_mscat(engine, map, 0, map->len, &engine->cmgr, 0, &c.next, &size, NULL)) + if (CL_CLEAN != asn1_parse_mscat(engine, map, 0, map->len, &engine->cmgr, 0, &c.next, &size, NULL)) { return 1; + } - if (asn1_expect_objtype(map, c.next, &size, &c, ASN1_TYPE_SEQUENCE)) + if (asn1_expect_objtype(map, c.next, &size, &c, ASN1_TYPE_SEQUENCE)) { return 1; - if (asn1_expect_obj(map, &c.content, &c.size, ASN1_TYPE_OBJECT_ID, lenof(OID_szOID_CATALOG_LIST), OID_szOID_CATALOG_LIST)) + } + if (asn1_expect_obj(map, &c.content, &c.size, ASN1_TYPE_OBJECT_ID, lenof(OID_szOID_CATALOG_LIST), OID_szOID_CATALOG_LIST)) { return 1; + } if (c.size) { cli_dbgmsg("asn1_load_mscat: found extra data in szOID_CATALOG_LIST content\n"); return 1; } - if (asn1_expect_objtype(map, c.next, &size, &c, 0x4)) /* List ID */ + if (asn1_expect_objtype(map, c.next, &size, &c, 0x4)) { /* List ID */ return 1; - if (asn1_expect_objtype(map, c.next, &size, &c, 0x17)) /* Effective date - WTF?! */ + } + if (asn1_expect_objtype(map, c.next, &size, &c, 0x17)) { /* Effective date - WTF?! */ return 1; + } - if (asn1_expect_list_member(map, &c.next, &size)) /* szOID_CATALOG_LIST_MEMBER or szOID_CATALOG_LIST_MEMBER2 */ + if (asn1_expect_list_member(map, &c.next, &size)) { /* szOID_CATALOG_LIST_MEMBER or szOID_CATALOG_LIST_MEMBER2 */ return 1; - if (asn1_expect_objtype(map, c.next, &size, &c, ASN1_TYPE_SEQUENCE)) /* hashes here */ + } + if (asn1_expect_objtype(map, c.next, &size, &c, ASN1_TYPE_SEQUENCE)) { /* hashes here */ return 1; + } /* [0] is next but we don't care as it's really descriptives stuff */ size = c.size; c.next = c.content; while (size) { struct cli_asn1 tag; - if (asn1_expect_objtype(map, c.next, &size, &c, ASN1_TYPE_SEQUENCE)) + if (asn1_expect_objtype(map, c.next, &size, &c, ASN1_TYPE_SEQUENCE)) { return 1; - if (asn1_expect_objtype(map, c.content, &c.size, &tag, ASN1_TYPE_OCTET_STRING)) /* TAG NAME */ + } + if (asn1_expect_objtype(map, c.content, &c.size, &tag, ASN1_TYPE_OCTET_STRING)) { /* TAG NAME */ return 1; - if (asn1_expect_objtype(map, tag.next, &c.size, &tag, ASN1_TYPE_SET)) /* set */ + } + if (asn1_expect_objtype(map, tag.next, &c.size, &tag, ASN1_TYPE_SET)) { /* set */ return 1; + } if (c.size) { cli_dbgmsg("asn1_load_mscat: found extra data in tag\n"); return 1; @@ -2225,41 +2281,49 @@ int asn1_load_mscat(fmap_t *map, struct cl_engine *engine) cli_hash_type_t hm_hashtype; unsigned int hashsize; - if (asn1_expect_objtype(map, tag.content, &tag.size, &tagval1, ASN1_TYPE_SEQUENCE)) + if (asn1_expect_objtype(map, tag.content, &tag.size, &tagval1, ASN1_TYPE_SEQUENCE)) { return 1; + } tag.content = tagval1.next; - if (asn1_expect_objtype(map, tagval1.content, &tagval1.size, &tagval2, ASN1_TYPE_OBJECT_ID)) + if (asn1_expect_objtype(map, tagval1.content, &tagval1.size, &tagval2, ASN1_TYPE_OBJECT_ID)) { return 1; - if (tagval2.size != lenof(OID_SPC_INDIRECT_DATA_OBJID)) + } + if (tagval2.size != lenof(OID_SPC_INDIRECT_DATA_OBJID)) { continue; + } if (!fmap_need_ptr_once(map, tagval2.content, lenof(OID_SPC_INDIRECT_DATA_OBJID))) { cli_dbgmsg("asn1_load_mscat: cannot read SPC_INDIRECT_DATA\n"); return 1; } - if (memcmp(tagval2.content, OID_SPC_INDIRECT_DATA_OBJID, lenof(OID_SPC_INDIRECT_DATA_OBJID))) + if (memcmp(tagval2.content, OID_SPC_INDIRECT_DATA_OBJID, lenof(OID_SPC_INDIRECT_DATA_OBJID))) { continue; /* stuff like CAT_NAMEVALUE_OBJID(1.3.6.1.4.1.311.12.2.1) and CAT_MEMBERINFO_OBJID(.2).. */ + } - if (asn1_expect_objtype(map, tagval2.next, &tagval1.size, &tagval2, ASN1_TYPE_SET)) + if (asn1_expect_objtype(map, tagval2.next, &tagval1.size, &tagval2, ASN1_TYPE_SET)) { return 1; + } if (tagval1.size) { cli_dbgmsg("asn1_load_mscat: found extra data in tag value\n"); return 1; } - if (asn1_expect_objtype(map, tagval2.content, &tagval2.size, &tagval1, ASN1_TYPE_SEQUENCE)) + if (asn1_expect_objtype(map, tagval2.content, &tagval2.size, &tagval1, ASN1_TYPE_SEQUENCE)) { return 1; + } if (tagval2.size) { cli_dbgmsg("asn1_load_mscat: found extra data in SPC_INDIRECT_DATA_OBJID tag\n"); return 1; } - if (asn1_expect_objtype(map, tagval1.content, &tagval1.size, &tagval2, ASN1_TYPE_SEQUENCE)) + if (asn1_expect_objtype(map, tagval1.content, &tagval1.size, &tagval2, ASN1_TYPE_SEQUENCE)) { return 1; + } - if (asn1_expect_objtype(map, tagval2.content, &tagval2.size, &tagval3, ASN1_TYPE_OBJECT_ID)) /* shall have an obj 1.3.6.1.4.1.311.2.1.15 or 1.3.6.1.4.1.311.2.1.25 inside */ + if (asn1_expect_objtype(map, tagval2.content, &tagval2.size, &tagval3, ASN1_TYPE_OBJECT_ID)) { /* shall have an obj 1.3.6.1.4.1.311.2.1.15 or 1.3.6.1.4.1.311.2.1.25 inside */ return 1; + } if (tagval3.size != lenof(OID_SPC_PE_IMAGE_DATA_OBJID)) { /* lenof(OID_SPC_PE_IMAGE_DATA_OBJID) = lenof(OID_SPC_CAB_DATA_OBJID) = 10*/ cli_dbgmsg("asn1_load_mscat: bad hash type size\n"); return 1; @@ -2268,17 +2332,18 @@ int asn1_load_mscat(fmap_t *map, struct cl_engine *engine) cli_dbgmsg("asn1_load_mscat: cannot read hash type\n"); return 1; } - if (!memcmp(tagval3.content, OID_SPC_PE_IMAGE_DATA_OBJID, lenof(OID_SPC_PE_IMAGE_DATA_OBJID))) + if (!memcmp(tagval3.content, OID_SPC_PE_IMAGE_DATA_OBJID, lenof(OID_SPC_PE_IMAGE_DATA_OBJID))) { hashed_obj_type = 2; - else if (!memcmp(tagval3.content, OID_SPC_CAB_DATA_OBJID, lenof(OID_SPC_CAB_DATA_OBJID))) + } else if (!memcmp(tagval3.content, OID_SPC_CAB_DATA_OBJID, lenof(OID_SPC_CAB_DATA_OBJID))) { hashed_obj_type = 1; - else { + } else { cli_dbgmsg("asn1_load_mscat: unexpected hash type\n"); return 1; } - if (asn1_expect_objtype(map, tagval2.next, &tagval1.size, &tagval2, ASN1_TYPE_SEQUENCE)) + if (asn1_expect_objtype(map, tagval2.next, &tagval1.size, &tagval2, ASN1_TYPE_SEQUENCE)) { return 1; + } if (tagval1.size) { cli_dbgmsg("asn1_load_mscat: found extra data after hash\n"); return 1; @@ -2299,8 +2364,9 @@ int asn1_load_mscat(fmap_t *map, struct cl_engine *engine) return 1; } - if (asn1_expect_objtype(map, tagval2.content, &tagval2.size, &tagval3, ASN1_TYPE_OCTET_STRING)) + if (asn1_expect_objtype(map, tagval2.content, &tagval2.size, &tagval3, ASN1_TYPE_OCTET_STRING)) { return 1; + } if (tagval2.size) { cli_dbgmsg("asn1_load_mscat: found extra data in hash\n"); return 1; @@ -2316,8 +2382,9 @@ int asn1_load_mscat(fmap_t *map, struct cl_engine *engine) if (cli_debug_flag) { char sha[SHA256_HASH_SIZE * 2 + 1] = {0}; - for (i = 0; i < hashsize; i++) + for (i = 0; i < hashsize; i++) { sprintf(&sha[i * 2], "%02x", ((uint8_t *)(tagval3.content))[i]); + } cli_dbgmsg("asn1_load_mscat: got hash %s (%s)\n", sha, (hashed_obj_type == 2) ? "PE" : "CAB"); } if (!engine->hm_fp) { @@ -2373,8 +2440,9 @@ cl_error_t asn1_check_mscat(struct cl_engine *engine, fmap_t *map, size_t offset } ret = asn1_parse_mscat(engine, map, offset, size, &certs, 1, &content, &content_size, ctx); crtmgr_free(&certs); - if (CL_CLEAN != ret) + if (CL_CLEAN != ret) { return ret; + } if (asn1_expect_objtype(map, content, &content_size, &c, ASN1_TYPE_SEQUENCE)) { cli_dbgmsg("asn1_check_mscat: expected SEQUENCE at top level of hash container\n"); @@ -2425,8 +2493,9 @@ cl_error_t asn1_check_mscat(struct cl_engine *engine, fmap_t *map, size_t offset if (cli_debug_flag) { char hashtxt[MAX_HASH_SIZE * 2 + 1]; - for (i = 0; i < hashsize; i++) + for (i = 0; i < hashsize; i++) { sprintf(&hashtxt[i * 2], "%02x", hash[i]); + } cli_dbgmsg("Authenticode: %s\n", hashtxt); } diff --git a/libclamav/aspack.c b/libclamav/aspack.c index 67e8f38934..bca8284152 100644 --- a/libclamav/aspack.c +++ b/libclamav/aspack.c @@ -71,7 +71,9 @@ struct ASPK { static inline int readstream(struct ASPK *stream) { while (stream->bitpos >= 8) { - if (stream->input >= stream->iend) return 0; + if (stream->input >= stream->iend) { + return 0; + } stream->hash = (stream->hash << 8) | *stream->input; stream->input++; stream->bitpos -= 8; @@ -88,33 +90,41 @@ static uint32_t getdec(struct ASPK *stream, uint8_t which, int *err) *err = 1; - if (!readstream(stream)) return 0; + if (!readstream(stream)) { + return 0; + } ret = (stream->hash >> (8 - stream->bitpos)) & 0xfffe00; if (ret < d3[8]) { - if ((ret >> 16) >= 0x100) return 0; - if (!(pos = stream->dict_helper[which].ends[ret >> 16]) || pos >= 24) return 0; /* 0> 16) >= 0x100) { + return 0; + } + if (!(pos = stream->dict_helper[which].ends[ret >> 16]) || pos >= 24) { + return 0; /* 0bitpos += pos; ret = ((ret - d3[pos - 1]) >> (24 - pos)) + d4[pos]; - if (ret >= stream->dict_helper[which].size) return 0; + if (ret >= stream->dict_helper[which].size) { + return 0; + } ret = stream->dict_helper[which].starts[ret]; *err = 0; @@ -143,7 +155,9 @@ static uint8_t build_decrypt_array(struct ASPK *stream, uint8_t *array, uint8_t for (i = 0; i < stream->dict_helper[which].size; i++) { /* within bounds - see comments in build_decrypt_dictionaries */ - if (array[i] > 17) return 0; + if (array[i] > 17) { + return 0; + } bus[array[i]]++; } @@ -153,7 +167,9 @@ static uint8_t build_decrypt_array(struct ASPK *stream, uint8_t *array, uint8_t i = 0; while (counter >= 9) { /* 0<=i<=14 */ sum += (bus[i + 1] << counter); - if (sum > 0x1000000) return 0; + if (sum > 0x1000000) { + return 0; + } d3[i + 1] = sum; d4[i + 1] = dict[i + 1] = bus[i] + d4[i]; @@ -162,7 +178,9 @@ static uint8_t build_decrypt_array(struct ASPK *stream, uint8_t *array, uint8_t uint32_t old = endoff; endoff = d3[i + 1] >> 0x10; if (endoff - old) { - if (!CLI_ISCONTAINED(stream->dict_helper[which].ends, 0x100, stream->dict_helper[which].ends + old, endoff - old)) return 0; + if (!CLI_ISCONTAINED(stream->dict_helper[which].ends, 0x100, stream->dict_helper[which].ends + old, endoff - old)) { + return 0; + } memset((stream->dict_helper[which].ends + old), i + 1, endoff - old); } } @@ -171,13 +189,19 @@ static uint8_t build_decrypt_array(struct ASPK *stream, uint8_t *array, uint8_t counter--; } - if (sum != 0x1000000) return 0; + if (sum != 0x1000000) { + return 0; + } i = 0; for (i = 0; i < stream->dict_helper[which].size; i++) { if (array[i]) { /* within bounds - see above */ - if (array[i] > 17) return 0; - if (dict[array[i]] >= stream->dict_helper[which].size) return 0; + if (array[i] > 17) { + return 0; + } + if (dict[array[i]] >= stream->dict_helper[which].size) { + return 0; + } stream->dict_helper[which].starts[dict[array[i]]] = i; dict[array[i]]++; } @@ -208,38 +232,57 @@ static int build_decrypt_dictionaries(struct ASPK *stream) uint32_t ret; int oob; - if (!getbits(stream, 1, &oob)) memset(stream->decrypt_dict, 0, 0x2f5); - if (oob) return 0; + if (!getbits(stream, 1, &oob)) { + memset(stream->decrypt_dict, 0, 0x2f5); + } + if (oob) { + return 0; + } for (counter = 0; counter < 19; counter++) { stream->array1[counter] = getbits(stream, 4, &oob); - if (oob) return 0; + if (oob) { + return 0; + } } - if (!build_decrypt_array(stream, stream->array1, 3)) return 0; /* array1[19] - [3].size=19 */ + if (!build_decrypt_array(stream, stream->array1, 3)) { + return 0; /* array1[19] - [3].size=19 */ + } counter = 0; while (counter < 757) { ret = getdec(stream, 3, &oob); - if (oob) return 0; + if (oob) { + return 0; + } if (ret >= 16) { if (ret != 16) { - if (ret == 17) + if (ret == 17) { ret = 3 + getbits(stream, 3, &oob); - else + } else { ret = 11 + getbits(stream, 7, &oob); - if (oob) return 0; + } + if (oob) { + return 0; + } while (ret) { - if (counter >= 757) break; + if (counter >= 757) { + break; + } stream->array2[1 + counter] = 0; counter++; ret--; } } else { ret = 3 + getbits(stream, 2, &oob); - if (oob) return 0; + if (oob) { + return 0; + } while (ret) { - if (counter >= 757) break; + if (counter >= 757) { + break; + } stream->array2[1 + counter] = stream->array2[counter]; counter++; ret--; @@ -251,7 +294,9 @@ static int build_decrypt_dictionaries(struct ASPK *stream) } } - if (!build_decrypt_array(stream, &stream->array2[1], 0) /* array2[758-1=757] - [0].size=721 */ || !build_decrypt_array(stream, &stream->array2[722], 1) /* array2[758-722=36] - [1].size=28 */ || !build_decrypt_array(stream, &stream->array2[750], 2) /* array2[758-750=8] - [2].size=8 */) return 0; + if (!build_decrypt_array(stream, &stream->array2[1], 0) /* array2[758-1=757] - [0].size=721 */ || !build_decrypt_array(stream, &stream->array2[722], 1) /* array2[758-722=36] - [1].size=28 */ || !build_decrypt_array(stream, &stream->array2[750], 2) /* array2[758-750=8] - [2].size=8 */) { + return 0; + } stream->dict_ok = 0; for (counter = 0; counter < 8; counter++) { @@ -276,14 +321,18 @@ static int decrypt(struct ASPK *stream, uint8_t *stuff, uint32_t size, uint8_t * cli_dbgmsg("Aspack: decrypt size:%x\n", size); while (counter < size) { gen = getdec(stream, 0, &oob); - if (oob) return 0; + if (oob) { + return 0; + } if (gen < 256) { /* implied within bounds */ output[counter] = (uint8_t)gen; counter++; continue; } if (gen >= 720) { - if (!build_decrypt_dictionaries(stream)) return 0; + if (!build_decrypt_dictionaries(stream)) { + return 0; + } continue; } backbytes = (gen - 256) >> 3; @@ -294,9 +343,13 @@ static int decrypt(struct ASPK *stream, uint8_t *stuff, uint32_t size, uint8_t * if ((backsize - 2) == 7) { uint8_t hlp; gen = getdec(stream, 1, &oob); - if (oob || gen >= 0x56) return 0; + if (oob || gen >= 0x56) { + return 0; + } hlp = stuff[gen + 0x1c]; - if (!readstream(stream)) return 0; + if (!readstream(stream)) { + return 0; + } backsize += stuff[gen] + (((stream->hash >> (8 - stream->bitpos)) & 0xffffff) >> (0x18 - hlp)); stream->bitpos += hlp; } @@ -305,16 +358,22 @@ static int decrypt(struct ASPK *stream, uint8_t *stuff, uint32_t size, uint8_t * gen = stuff[backbytes + 0x38]; if (!stream->dict_ok || gen < 3) { - if (!readstream(stream)) return 0; + if (!readstream(stream)) { + return 0; + } useold += ((stream->hash >> (8 - stream->bitpos)) & 0xffffff) >> (24 - gen); stream->bitpos += gen; } else { gen -= 3; - if (!readstream(stream)) return 0; + if (!readstream(stream)) { + return 0; + } useold += ((((stream->hash >> (8 - stream->bitpos)) & 0xffffff) >> (24 - gen)) * 8); stream->bitpos += gen; useold += getdec(stream, 2, &oob); - if (oob) return 0; + if (oob) { + return 0; + } } if (useold < 3) { @@ -331,7 +390,9 @@ static int decrypt(struct ASPK *stream, uint8_t *stuff, uint32_t size, uint8_t * backbytes++; - if (!backbytes || backbytes > counter || backsize > size - counter) return 0; + if (!backbytes || backbytes > counter || backsize > size - counter) { + return 0; + } while (backsize--) { output[counter] = output[counter - backbytes]; counter++; @@ -347,7 +408,9 @@ static int decomp_block(struct ASPK *stream, uint32_t size, uint8_t *stuff, uint memset(stream->decarray4, 0, sizeof(stream->decarray4)); memset(stream->decrypt_dict, 0, 757); stream->bitpos = 0x20; - if (!build_decrypt_dictionaries(stream)) return 0; + if (!build_decrypt_dictionaries(stream)) { + return 0; + } return decrypt(stream, stuff, size, output); } @@ -441,8 +504,9 @@ int unaspack(uint8_t *image, unsigned int size, struct cli_exe_section *sections cli_dbgmsg("Aspack: decomp_block failed\n"); free(wrkbuf); break; - } else + } else { cli_dbgmsg("Aspack: decomp block succeed\n"); + } free(wrkbuf); diff --git a/libclamav/autoit.c b/libclamav/autoit.c index fabc073f5b..d3684e3d4b 100644 --- a/libclamav/autoit.c +++ b/libclamav/autoit.c @@ -507,8 +507,9 @@ static unsigned int u2a(uint8_t *dest, unsigned int len) uint8_t *src = dest; unsigned int i, j; - if (len < 2) + if (len < 2) { return len; + } if (len > 4 && src[0] == 0xff && src[1] == 0xfe && src[2]) { len -= 2; @@ -517,17 +518,20 @@ static unsigned int u2a(uint8_t *dest, unsigned int len) unsigned int cnt = 0; j = (len > 20) ? 20 : (len & ~1); - for (i = 0; i < j; i += 2) + for (i = 0; i < j; i += 2) { cnt += (src[i] != 0 && src[i + 1] == 0); + } - if (cnt * 4 < j) + if (cnt * 4 < j) { return len; + } } j = len; len >>= 1; - for (i = 0; i < j; i += 2) + for (i = 0; i < j; i += 2) { *dest++ = src[i]; + } return len; } @@ -553,10 +557,12 @@ static uint8_t MT_getnext(struct MT *MT) MT->items = 624; MT->next = mt; - for (i = 0; i < 227; i++) + for (i = 0; i < 227; i++) { mt[i] = ((((mt[i] ^ mt[i + 1]) & 0x7ffffffe) ^ mt[i]) >> 1) ^ ((0 - (mt[i + 1] & 1)) & 0x9908b0df) ^ mt[i + 397]; - for (; i < 623; i++) + } + for (; i < 623; i++) { mt[i] = ((((mt[i] ^ mt[i + 1]) & 0x7ffffffe) ^ mt[i]) >> 1) ^ ((0 - (mt[i + 1] & 1)) & 0x9908b0df) ^ mt[i - 227]; + } mt[623] = ((((mt[623] ^ mt[0]) & 0x7ffffffe) ^ mt[623]) >> 1) ^ ((0 - (mt[0] & 1)) & 0x9908b0df) ^ mt[i - 227]; } @@ -575,13 +581,15 @@ static void MT_decrypt(uint8_t *buf, unsigned int size, uint32_t seed) uint32_t *mt = MT.mt; *mt = seed; - for (i = 1; i < 624; i++) + for (i = 1; i < 624; i++) { mt[i] = i + 0x6c078965 * ((mt[i - 1] >> 30) ^ mt[i - 1]); + } MT.items = 1; MT.next = MT.mt; - while (size--) + while (size--) { *buf++ ^= MT_getnext(&MT); + } } /********************* @@ -656,8 +664,9 @@ static cl_error_t ea05(cli_ctx *ctx, const uint8_t *base, char *tmpd) goto done; } - for (i = 0; i < 16; i++) + for (i = 0; i < 16; i++) { m4sum += *base++; + } // While we have not exceeded the max files limit or the max time limit... while (CL_SUCCESS == (status = cli_checklimits("autoit", ctx, 0, 0, 0))) { @@ -960,8 +969,12 @@ static double LAME_fpusht(struct LAME *l) l->grp1[l->c0] = rolled; - if (!l->c0--) l->c0 = 16; - if (!l->c1--) l->c1 = 16; + if (!l->c0--) { + l->c0 = 16; + } + if (!l->c1--) { + l->c1 = 16; + } /* if (l->grp1[l->c0] == l->grp2[0]) { */ /* if (!memcmp(l->grp1, (uint32_t *)l + 0x24 - l->c0, 0x44)) */ @@ -991,8 +1004,9 @@ static void LAME_srand(struct LAME *l, uint32_t seed) l->c0 = 0; l->c1 = 10; - for (i = 0; i < 9; i++) + for (i = 0; i < 9; i++) { LAME_fpusht(l); + } } static uint8_t LAME_getnext(struct LAME *l) @@ -1002,10 +1016,11 @@ static uint8_t LAME_getnext(struct LAME *l) LAME_fpusht(l); x = LAME_fpusht(l) * 256.0; - if ((int32_t)x < 256) + if ((int32_t)x < 256) { ret = (uint8_t)x; - else + } else { ret = 0xff; + } return ret; } @@ -1015,8 +1030,9 @@ static void LAME_decrypt(uint8_t *cypher, uint32_t size, uint16_t seed) /* mt_srand_timewrap(struct srand_struc bufDC); */ LAME_srand(&lame, (uint32_t)seed); - while (size--) + while (size--) { *cypher++ ^= LAME_getnext(&lame); + } } /********************* @@ -1419,7 +1435,7 @@ static int ea06(cli_ctx *ctx, const uint8_t *base, char *tmpd) if (fpu_words == FPU_ENDIAN_LITTLE) { snprintf((char *)&buf[UNP.cur_output], 39, "%g ", *(double *)&UNP.outputbuf[UNP.cur_input]); - } else + } else { do { double x; uint8_t *j = (uint8_t *)&x; @@ -1431,6 +1447,7 @@ static int ea06(cli_ctx *ctx, const uint8_t *base, char *tmpd) snprintf((char *)&buf[UNP.cur_output], 39, "%g ", x); /* FIXME: check */ } while (0); + } buf[UNP.cur_output + 38] = ' '; buf[UNP.cur_output + 39] = '\0'; UNP.cur_output += strlen((char *)&buf[UNP.cur_output]); @@ -1635,32 +1652,37 @@ cl_error_t cli_scanautoit(cli_ctx *ctx, off_t offset) cli_dbgmsg("in scanautoit()\n"); - if (!(version = fmap_need_off_once(map, offset, sizeof(*version)))) + if (!(version = fmap_need_off_once(map, offset, sizeof(*version)))) { return CL_EREAD; + } - if (!(tmpd = cli_gentemp_with_prefix(ctx->sub_tmpdir, "autoit-tmp"))) + if (!(tmpd = cli_gentemp_with_prefix(ctx->sub_tmpdir, "autoit-tmp"))) { return CL_ETMPDIR; + } if (mkdir(tmpd, 0700)) { cli_dbgmsg("autoit: Can't create temporary directory %s\n", tmpd); free(tmpd); return CL_ETMPDIR; } - if (ctx->engine->keeptmp) + if (ctx->engine->keeptmp) { cli_dbgmsg("autoit: Extracting files to %s\n", tmpd); + } switch (*version) { case 0x35: status = ea05(ctx, version + 1, tmpd); break; case 0x36: - if (fpu_words == FPU_ENDIAN_INITME) + if (fpu_words == FPU_ENDIAN_INITME) { fpu_words = get_fpu_endian(); + } if (fpu_words == FPU_ENDIAN_UNKNOWN) { cli_dbgmsg("autoit: EA06 support not available" "(cannot extract ea06 doubles, unknown floating double representation).\n"); status = CL_CLEAN; - } else + } else { status = ea06(ctx, version + 1, tmpd); + } break; default: /* NOT REACHED */ @@ -1668,8 +1690,9 @@ cl_error_t cli_scanautoit(cli_ctx *ctx, off_t offset) status = CL_CLEAN; } - if (!ctx->engine->keeptmp) + if (!ctx->engine->keeptmp) { cli_rmdirs(tmpd); + } free(tmpd); return status; diff --git a/libclamav/binhex.c b/libclamav/binhex.c index 4394db0ffd..c412ec2a73 100644 --- a/libclamav/binhex.c +++ b/libclamav/binhex.c @@ -66,14 +66,19 @@ int cli_binhex(cli_ctx *ctx) char *dname, *rname; cli_dbgmsg("in cli_binhex\n"); - if (!map->len) return CL_CLEAN; + if (!map->len) { + return CL_CLEAN; + } - if ((ret = cli_gentempfd(ctx->sub_tmpdir, &dname, &datafd)) != CL_SUCCESS) + if ((ret = cli_gentempfd(ctx->sub_tmpdir, &dname, &datafd)) != CL_SUCCESS) { return ret; + } if ((ret = cli_gentempfd(ctx->sub_tmpdir, &rname, &resfd)) != CL_SUCCESS) { close(datafd); - if (cli_unlink(dname)) ret = CL_EUNLINK; + if (cli_unlink(dname)) { + ret = CL_EUNLINK; + } free(dname); return ret; } @@ -98,10 +103,12 @@ int cli_binhex(cli_ctx *ctx) cli_dbgmsg("cli_binhex: file too short for header\n"); break; } - if ((ret = cli_checklimits("cli_binhex(data)", ctx, datalen, 0, 0)) != CL_CLEAN) + if ((ret = cli_checklimits("cli_binhex(data)", ctx, datalen, 0, 0)) != CL_CLEAN) { break; - if (cli_checklimits("cli_binhex(resources)", ctx, reslen, 0, 0) != CL_CLEAN) + } + if (cli_checklimits("cli_binhex(resources)", ctx, reslen, 0, 0) != CL_CLEAN) { reslen = 0; + } cli_dbgmsg("cli_binhex: decoding '%s' - %u bytes of data to %s - %u bytes or resources to %s\n", decoded + 1, datalen, dname, reslen, rname); memmove(decoded, &decoded[hdrlen], dec_done - hdrlen); dec_done -= hdrlen; @@ -127,8 +134,9 @@ int cli_binhex(cli_ctx *ctx) break; } } - if (dec_done) + if (dec_done) { memmove(decoded, &decoded[todo], dec_done); + } } if (dec_done && write_phase == IN_LIMBO1) { if (dec_done > 1) { @@ -138,13 +146,15 @@ int cli_binhex(cli_ctx *ctx) } dec_done -= 2; write_phase += 2; - if (dec_done) + if (dec_done) { memmove(decoded, &decoded[2], dec_done); + } } else { dec_done--; write_phase++; - if (dec_done) + if (dec_done) { memmove(decoded, &decoded[1], dec_done); + } } } if (dec_done && write_phase == IN_LIMBO2) { @@ -153,8 +163,9 @@ int cli_binhex(cli_ctx *ctx) break; } write_phase++; - if (--dec_done) + if (--dec_done) { memmove(decoded, &decoded[1], dec_done); + } } if (dec_done && write_phase == IN_RES) { unsigned int todo = MIN(dec_done, reslen); @@ -217,7 +228,9 @@ int cli_binhex(cli_ctx *ctx) in_data = 1; continue; } - if (!in_data) continue; + if (!in_data) { + continue; + } if (write_phase == IN_BANNER) { if ((char)b != ':') { cli_dbgmsg("cli_binhex: broken file (missing stream start identifier)\n"); @@ -225,8 +238,9 @@ int cli_binhex(cli_ctx *ctx) } write_phase++; } - if ((char)b == ':') + if ((char)b == ':') { continue; + } if (b > 0x7f || (b = hqxtbl[b]) == 0xff) { cli_dbgmsg("cli_binhex: Invalid character (%02x)\n", encoded[chunkoff - 1]); break; @@ -249,11 +263,12 @@ int cli_binhex(cli_ctx *ctx) if (in_run) { in_run = 0; - if (!this_byte) + if (!this_byte) { this_byte = 0x90; - else { - while (--this_byte) + } else { + while (--this_byte) { decoded[dec_done++] = last_byte; + } continue; } } else if (this_byte == 0x90) { @@ -267,8 +282,12 @@ int cli_binhex(cli_ctx *ctx) close(datafd); close(resfd); if (!ctx->engine->keeptmp) { - if (cli_unlink(dname) && ret != CL_VIRUS) ret = CL_EUNLINK; - if (cli_unlink(rname) && ret != CL_VIRUS) ret = CL_EUNLINK; + if (cli_unlink(dname) && ret != CL_VIRUS) { + ret = CL_EUNLINK; + } + if (cli_unlink(rname) && ret != CL_VIRUS) { + ret = CL_EUNLINK; + } } free(dname); free(rname); diff --git a/libclamav/blob.c b/libclamav/blob.c index 77e8e889f0..5e2721ba1f 100644 --- a/libclamav/blob.c +++ b/libclamav/blob.c @@ -88,10 +88,12 @@ void blobDestroy(blob *b) assert(b->magic == BLOBCLASS); #endif - if (b->name) + if (b->name) { free(b->name); - if (b->data) + } + if (b->data) { free(b->data); + } #ifdef CL_DEBUG b->magic = INVALIDCLASS; #endif @@ -125,10 +127,12 @@ blobToMem(blob *b) assert(b->magic == BLOBCLASS); #endif - if (!b->isClosed) + if (!b->isClosed) { blobClose(b); - if (b->name) + } + if (b->name) { free(b->name); + } #ifdef CL_DEBUG b->magic = INVALIDCLASS; #endif @@ -151,13 +155,15 @@ void blobSetFilename(blob *b, const char *dir, const char *filename) cli_dbgmsg("blobSetFilename: %s\n", filename); - if (b->name) + if (b->name) { free(b->name); + } b->name = cli_safer_strdup(filename); - if (b->name) + if (b->name) { sanitiseName(b->name); + } } static const char * @@ -187,8 +193,9 @@ int blobAddData(blob *b, const unsigned char *data, size_t len) #endif assert(data != NULL); - if (len == 0) + if (len == 0) { return 0; + } if (b->isClosed) { /* @@ -210,12 +217,14 @@ int blobAddData(blob *b, const unsigned char *data, size_t len) #if HAVE_CLI_GETPAGESIZE if (pagesize == 0) { pagesize = cli_getpagesize(); - if (pagesize <= 0) + if (pagesize <= 0) { pagesize = 4096; + } } growth = pagesize; - if (len >= (size_t)pagesize) + if (len >= (size_t)pagesize) { growth = ((len / pagesize) + 1) * pagesize; + } /*cli_dbgmsg("blobGrow: b->size %lu, b->len %lu, len %lu, growth = %u\n", b->size, b->len, len, growth);*/ @@ -233,8 +242,9 @@ int blobAddData(blob *b, const unsigned char *data, size_t len) } else if (b->size < b->len + (off_t)len) { unsigned char *p = cli_max_realloc(b->data, b->size + growth); - if (p == NULL) + if (p == NULL) { return -1; + } b->size += growth; b->data = p; @@ -279,8 +289,9 @@ blobGetData(const blob *b) assert(b->magic == BLOBCLASS); #endif - if (b->len == 0) + if (b->len == 0) { return NULL; + } return b->data; } @@ -345,17 +356,20 @@ int blobcmp(const blob *b1, const blob *b2) assert(b1 != NULL); assert(b2 != NULL); - if (b1 == b2) + if (b1 == b2) { return 0; + } s1 = blobGetDataSize(b1); s2 = blobGetDataSize(b2); - if (s1 != s2) + if (s1 != s2) { return 1; + } - if ((s1 == 0) && (s2 == 0)) + if ((s1 == 0) && (s2 == 0)) { return 0; + } return memcmp(blobGetData(b1), blobGetData(b2), s1); } @@ -370,8 +384,9 @@ int blobGrow(blob *b, size_t len) assert(b->magic == BLOBCLASS); #endif - if (len == 0) + if (len == 0) { return CL_SUCCESS; + } if (b->isClosed) { /* @@ -386,8 +401,9 @@ int blobGrow(blob *b, size_t len) assert(b->size == 0); b->data = cli_max_malloc(len); - if (b->data) + if (b->data) { b->size = (off_t)len; + } } else { unsigned char *ptr = cli_max_realloc(b->data, b->size + len); @@ -441,8 +457,9 @@ void fileblobDestructiveDestroy(fileblob *fb) if (fb->fp && fb->fullname) { fclose(fb->fp); cli_dbgmsg("fileblobDestructiveDestroy: %s\n", fb->fullname); - if (!fb->ctx || !fb->ctx->engine->keeptmp) + if (!fb->ctx || !fb->ctx->engine->keeptmp) { cli_unlink(fb->fullname); + } free(fb->fullname); fb->fp = NULL; fb->fullname = NULL; @@ -483,12 +500,14 @@ void fileblobDestroy(fileblob *fb) cli_errmsg("fileblobDestroy: %s not saved: report to https://github.com/Cisco-Talos/clamav/issues\n", (fb->fullname) ? fb->fullname : fb->b.name); free(fb->b.name); - } else + } else { cli_errmsg("fileblobDestroy: file not saved (%lu bytes): report to https://github.com/Cisco-Talos/clamav/issues\n", (unsigned long)fb->b.len); + } } - if (fb->fullname) + if (fb->fullname) { free(fb->fullname); + } #ifdef CL_DEBUG fb->b.magic = INVALIDCLASS; #endif @@ -499,8 +518,9 @@ void fileblobPartialSet(fileblob *fb, const char *fullname, const char *arg) { UNUSEDPARAM(arg); - if (fb->b.name) + if (fb->b.name) { return; + } assert(fullname != NULL); @@ -519,13 +539,14 @@ void fileblobPartialSet(fileblob *fb, const char *fullname, const char *arg) return; } blobSetFilename(&fb->b, fb->ctx ? fb->ctx->sub_tmpdir : NULL, fullname); - if (fb->b.data) + if (fb->b.data) { if (fileblobAddData(fb, fb->b.data, fb->b.len) == 0) { free(fb->b.data); fb->b.data = NULL; fb->b.len = fb->b.size = 0; fb->isNotEmpty = 1; } + } fb->fullname = cli_safer_strdup(fullname); } @@ -533,8 +554,9 @@ void fileblobSetFilename(fileblob *fb, const char *dir, const char *filename) { char *fullname; - if (fb->b.name) + if (fb->b.name) { return; + } assert(filename != NULL); assert(dir != NULL); @@ -549,7 +571,9 @@ void fileblobSetFilename(fileblob *fb, const char *dir, const char *filename) assert(filename != NULL); - if (cli_gentempfd(dir, &fullname, &fb->fd) != CL_SUCCESS) return; + if (cli_gentempfd(dir, &fullname, &fb->fd) != CL_SUCCESS) { + return; + } cli_dbgmsg("fileblobSetFilename: file %s saved to %s\n", filename, fullname); @@ -561,20 +585,22 @@ void fileblobSetFilename(fileblob *fb, const char *dir, const char *filename) free(fullname); return; } - if (fb->b.data) + if (fb->b.data) { if (fileblobAddData(fb, fb->b.data, fb->b.len) == 0) { free(fb->b.data); fb->b.data = NULL; fb->b.len = fb->b.size = 0; fb->isNotEmpty = 1; } + } fb->fullname = fullname; } int fileblobAddData(fileblob *fb, const unsigned char *data, size_t len) { - if (len == 0) + if (len == 0) { return 0; + } assert(data != NULL); @@ -637,8 +663,9 @@ cl_error_t fileblobScan(const fileblob *fb) cl_error_t rc; STATBUF sb; - if (fb->isInfected) + if (fb->isInfected) { return CL_VIRUS; + } if (fb->fp == NULL || fb->fullname == NULL) { /* shouldn't happen, scan called before fileblobSetFilename */ cli_warnmsg("fileblobScan, fullname == NULL\n"); diff --git a/libclamav/bytecode.c b/libclamav/bytecode.c index 684a10d83f..462869bd13 100644 --- a/libclamav/bytecode.c +++ b/libclamav/bytecode.c @@ -87,16 +87,21 @@ static const struct cli_pe_hook_data nopedata; static void context_safe(struct cli_bc_ctx *ctx) { /* make sure these are never NULL */ - if (!ctx->hooks.kind) + if (!ctx->hooks.kind) { ctx->hooks.kind = &nokind; - if (!ctx->hooks.match_counts) + } + if (!ctx->hooks.match_counts) { ctx->hooks.match_counts = nomatch; - if (!ctx->hooks.match_offsets) + } + if (!ctx->hooks.match_offsets) { ctx->hooks.match_offsets = nooffsets; - if (!ctx->hooks.filesize) + } + if (!ctx->hooks.filesize) { ctx->hooks.filesize = &nofilesize; - if (!ctx->hooks.pedata) + } + if (!ctx->hooks.pedata) { ctx->hooks.pedata = &nopedata; + } } /** @@ -144,9 +149,9 @@ static void bytecode_context_reset(struct cli_bc_ctx *ctx) ret = cli_scan_desc(fd, cctx, CL_TYPE_HTML, false, NULL, AC_SCAN_VIR, NULL, NULL, LAYER_ATTRIBUTES_NORMALIZED); if (ret == CL_CLEAN) { - if (lseek(fd, 0, SEEK_SET) == -1) + if (lseek(fd, 0, SEEK_SET) == -1) { cli_dbgmsg("cli_bytecode: call to lseek() has failed\n"); - else { + } else { ret = cli_scan_desc(fd, cctx, CL_TYPE_TEXT_ASCII, false, NULL, AC_SCAN_VIR, NULL, NULL, LAYER_ATTRIBUTES_NORMALIZED); } @@ -180,45 +185,52 @@ static void bytecode_context_reset(struct cli_bc_ctx *ctx) #else /*TODO: implement for no-mmap case too*/ #endif - for (i = 0; i < ctx->ninflates; i++) + for (i = 0; i < ctx->ninflates; i++) { cli_bcapi_inflate_done(ctx, i); + } free(ctx->inflates); ctx->inflates = NULL; ctx->ninflates = 0; - for (i = 0; i < ctx->nlzmas; i++) + for (i = 0; i < ctx->nlzmas; i++) { cli_bcapi_lzma_done(ctx, i); + } free(ctx->lzmas); ctx->lzmas = NULL; ctx->nlzmas = 0; - for (i = 0; i < ctx->nbzip2s; i++) + for (i = 0; i < ctx->nbzip2s; i++) { cli_bcapi_bzip2_done(ctx, i); + } free(ctx->bzip2s); ctx->bzip2s = NULL; ctx->nbzip2s = 0; - for (i = 0; i < ctx->nbuffers; i++) + for (i = 0; i < ctx->nbuffers; i++) { cli_bcapi_buffer_pipe_done(ctx, i); + } free(ctx->buffers); ctx->buffers = NULL; ctx->nbuffers = 0; - for (i = 0; i < ctx->nhashsets; i++) + for (i = 0; i < ctx->nhashsets; i++) { cli_bcapi_hashset_done(ctx, i); + } free(ctx->hashsets); ctx->hashsets = NULL; ctx->nhashsets = 0; - for (i = 0; i < ctx->njsnorms; i++) + for (i = 0; i < ctx->njsnorms; i++) { cli_bcapi_jsnorm_done(ctx, i); + } free(ctx->jsnorms); ctx->jsnorms = NULL; ctx->njsnorms = 0; ctx->jsnormdir = NULL; - for (i = 0; i < ctx->nmaps; i++) + for (i = 0; i < ctx->nmaps; i++) { cli_bcapi_map_done(ctx, i); + } free(ctx->maps); ctx->maps = NULL; ctx->nmaps = 0; @@ -279,24 +291,31 @@ static unsigned typesize(const struct cli_bc *bc, uint16_t type) unsigned j; type &= 0x7fff; - if (!type) + if (!type) { return 0; - if (type <= 8) + } + if (type <= 8) { return 1; - if (type <= 16) + } + if (type <= 16) { return 2; - if (type <= 32) + } + if (type <= 32) { return 4; - if (type <= 64) + } + if (type <= 64) { return 8; + } ty = &bc->types[type - 65]; - if (ty->size) + if (ty->size) { return ty->size; + } switch (ty->kind) { case 2: case 3: - for (j = 0; j < ty->numElements; j++) + for (j = 0; j < ty->numElements; j++) { ty->size += typesize(bc, ty->containedTypes[j]); + } break; case 4: ty->size = ty->numElements * typesize(bc, ty->containedTypes[0]); @@ -516,19 +535,21 @@ static inline operand_t readOperand(struct cli_bc_func *func, unsigned char *p, /* This is a global variable */ return 0x80000000 | v; } - if (ty <= 8) + if (ty <= 8) { *(uint8_t *)dest = v; - else if (ty <= 16) + } else if (ty <= 16) { *(uint16_t *)dest = v; - else if (ty <= 32) + } else if (ty <= 32) { *(uint32_t *)dest = v; - else + } else { *dest = v; + } return func->numValues + func->numConstants++; } v = readNumber(p, off, len, ok); - if (!*ok) + if (!*ok) { return MAX_OP; + } if (v >= func->numValues) { cli_errmsg("Operand index exceeds bounds: %u >= %u!\n", (unsigned)v, (unsigned)func->numValues); *ok = false; @@ -708,8 +729,9 @@ static uint16_t readTypeID(struct cli_bc *bc, unsigned char *buffer, unsigned *offset, unsigned len, bool *ok) { uint64_t t = readNumber(buffer, offset, len, ok); - if (!ok) + if (!ok) { return ~0; + } if (t >= bc->num_types + bc->start_tid) { cli_errmsg("Invalid type id: %llu\n", (unsigned long long)t); *ok = false; @@ -881,10 +903,12 @@ static bool types_equal(const struct cli_bc *bc, uint16_t *apity2ty, uint16_t ti ty->containedTypes[i], apity->containedTypes[i]); return false; } - } else if (!types_equal(bc, apity2ty, ty->containedTypes[i], apity->containedTypes[i] - BC_START_TID)) + } else if (!types_equal(bc, apity2ty, ty->containedTypes[i], apity->containedTypes[i] - BC_START_TID)) { return false; - if (ty->kind == DArrayType) + } + if (ty->kind == DArrayType) { break; /* validated the contained type already */ + } } return true; } @@ -901,15 +925,17 @@ static cl_error_t parseApis(struct cli_bc *bc, unsigned char *buffer) } maxapi = readNumber(buffer, &offset, len, &ok); - if (!ok) + if (!ok) { return CL_EMALFDB; + } if (maxapi > cli_apicall_maxapi) { cli_dbgmsg("bytecode using API %u, but highest API known to libclamav is %u, skipping\n", maxapi, cli_apicall_maxapi); return CL_BREAK; } calls = readNumber(buffer, &offset, len, &ok); - if (!ok) + if (!ok) { return CL_EMALFDB; + } if (calls > maxapi) { cli_errmsg("bytecode: attempting to describe more APIs than max: %u > %u\n", calls, maxapi); return CL_EMALFDB; @@ -963,8 +989,9 @@ static uint16_t type_components(struct cli_bc *bc, uint16_t id, bool *ok) { unsigned i, sum = 0; const struct cli_bc_type *ty; - if (id <= 64) + if (id <= 64) { return 1; + } ty = &bc->types[id - 65]; /* TODO: protect against recursive types */ switch (ty->kind) { @@ -1045,21 +1072,25 @@ static cl_error_t parseGlobals(struct cli_bc *bc, unsigned char *buffer) return CL_EMEM; } bc->num_globals = numglobals; - if (!ok) + if (!ok) { return CL_EMALFDB; + } for (i = 0; i < numglobals; i++) { unsigned comp; bc->globaltys[i] = readTypeID(bc, buffer, &offset, len, &ok); comp = type_components(bc, bc->globaltys[i], &ok); - if (!ok) + if (!ok) { return CL_EMALFDB; + } bc->globals[i] = malloc(sizeof(*bc->globals[0]) * comp); - if (!bc->globals[i]) + if (!bc->globals[i]) { return CL_EMEM; + } readConstant(bc, i, comp, buffer, &offset, len, &ok); } - if (!ok) + if (!ok) { return CL_EMALFDB; + } if (offset != len) { cli_errmsg("Trailing garbage in globals: %d extra bytes\n", len - offset); @@ -1073,8 +1104,9 @@ static cl_error_t parseMD(struct cli_bc *bc, unsigned char *buffer) unsigned offset = 1, len = strlen((const char *)buffer); unsigned numMD, i, b; bool ok = true; - if (buffer[0] != 'D') + if (buffer[0] != 'D') { return CL_EMALFDB; + } numMD = readNumber(buffer, &offset, len, &ok); if (!ok) { cli_errmsg("Unable to parse number of MD nodes\n"); @@ -1083,8 +1115,9 @@ static cl_error_t parseMD(struct cli_bc *bc, unsigned char *buffer) b = bc->dbgnode_cnt; bc->dbgnode_cnt += numMD; bc->dbgnodes = cli_safer_realloc(bc->dbgnodes, bc->dbgnode_cnt * sizeof(*bc->dbgnodes)); - if (!bc->dbgnodes) + if (!bc->dbgnodes) { return CL_EMEM; + } for (i = 0; i < numMD; i++) { unsigned j; struct cli_bc_dbgnode_element *elts; @@ -1095,23 +1128,28 @@ static cl_error_t parseMD(struct cli_bc *bc, unsigned char *buffer) } bc->dbgnodes[b + i].numelements = el; bc->dbgnodes[b + i].elements = elts = calloc(el, sizeof(*elts)); - if (!elts) + if (!elts) { return CL_EMEM; + } for (j = 0; j < el; j++) { if (buffer[offset] == '|') { elts[j].string = readData(buffer, &offset, len, &ok, &elts[j].len); - if (!ok) + if (!ok) { return CL_EMALFDB; + } } else { elts[j].len = readNumber(buffer, &offset, len, &ok); - if (!ok) + if (!ok) { return CL_EMALFDB; + } if (elts[j].len) { elts[j].constant = readNumber(buffer, &offset, len, &ok); - } else + } else { elts[j].nodeid = readNumber(buffer, &offset, len, &ok); - if (!ok) + } + if (!ok) { return CL_EMALFDB; + } } } } @@ -1162,8 +1200,9 @@ static cl_error_t parseFunctionHeader(struct cli_bc *bc, unsigned fn, unsigned c } for (i = 0; i < all_locals; i++) { func->types[i] = readNumber(buffer, &offset, len, &ok); - if (readFixedNumber(buffer, &offset, len, &ok, 1)) + if (readFixedNumber(buffer, &offset, len, &ok, 1)) { func->types[i] |= 0x8000; + } } if (!ok) { cli_errmsg("Invalid local types\n"); @@ -1207,8 +1246,9 @@ static bbid_t readBBID(struct cli_bc_func *func, const unsigned char *buffer, un cli_errmsg("Basic block ID out of range: %u\n", id); *ok = false; } - if (!*ok) + if (!*ok) { return ~0; + } return id; } @@ -1221,8 +1261,9 @@ static uint16_t get_type(struct cli_bc_func *func, operand_t op) }*/ static int16_t get_optype(const struct cli_bc_func *bcfunc, operand_t op) { - if (op >= bcfunc->numArgs + bcfunc->numLocals) + if (op >= bcfunc->numArgs + bcfunc->numLocals) { return 0; + } return bcfunc->types[op] & 0x7fff; } @@ -1302,10 +1343,11 @@ static cl_error_t parseBB(struct cli_bc *bc, unsigned func, unsigned bb, unsigne return CL_EMEM; } } - if (inst.opcode == OP_BC_CALL_DIRECT) + if (inst.opcode == OP_BC_CALL_DIRECT) { inst.u.ops.funcid = readFuncID(bc, buffer, &offset, len, &ok); - else + } else { inst.u.ops.funcid = readAPIFuncID(bc, buffer, &offset, len, &ok); + } for (i = 0; i < numOp; i++) { inst.u.ops.ops[i] = readOperand(bcfunc, buffer, &offset, len, &ok); } @@ -1316,19 +1358,21 @@ static cl_error_t parseBB(struct cli_bc *bc, unsigned func, unsigned bb, unsigne case OP_BC_TRUNC: inst.u.cast.source = readOperand(bcfunc, buffer, &offset, len, &ok); inst.u.cast.mask = bcfunc->types[inst.u.cast.source]; - if (inst.u.cast.mask == 1) + if (inst.u.cast.mask == 1) { inst.u.cast.size = 0; - else if (inst.u.cast.mask <= 8) + } else if (inst.u.cast.mask <= 8) { inst.u.cast.size = 1; - else if (inst.u.cast.mask <= 16) + } else if (inst.u.cast.mask <= 16) { inst.u.cast.size = 2; - else if (inst.u.cast.mask <= 32) + } else if (inst.u.cast.mask <= 32) { inst.u.cast.size = 3; - else if (inst.u.cast.mask <= 64) + } else if (inst.u.cast.mask <= 64) { inst.u.cast.size = 4; + } /* calculate mask */ - if (inst.opcode != OP_BC_SEXT) + if (inst.opcode != OP_BC_SEXT) { inst.u.cast.mask = inst.u.cast.mask != 64 ? (1ull << inst.u.cast.mask) - 1 : ~0ull; + } break; case OP_BC_GEP1: case OP_BC_GEPZ: @@ -1347,8 +1391,9 @@ static cl_error_t parseBB(struct cli_bc *bc, unsigned func, unsigned bb, unsigne return CL_EMEM; } inst.u.ops.ops[0] = readNumber(buffer, &offset, len, &ok); - for (i = 1; i < numOp + 2; i++) + for (i = 1; i < numOp + 2; i++) { inst.u.ops.ops[i] = readOperand(bcfunc, buffer, &offset, len, &ok); + } } break; case OP_BC_STORE: @@ -1428,15 +1473,15 @@ static cl_error_t parseBB(struct cli_bc *bc, unsigned func, unsigned bb, unsigne inst.interp_op = inst.opcode * 5; if (inst.type > 1) { - if (inst.type <= 8) + if (inst.type <= 8) { inst.interp_op += 1; - else if (inst.type <= 16) + } else if (inst.type <= 16) { inst.interp_op += 2; - else if (inst.type <= 32) + } else if (inst.type <= 32) { inst.interp_op += 3; - else if (inst.type <= 65) + } else if (inst.type <= 65) { inst.interp_op += 4; - else { + } else { cli_dbgmsg("unknown inst type: %d\n", inst.type); } } @@ -1452,11 +1497,13 @@ static cl_error_t parseBB(struct cli_bc *bc, unsigned func, unsigned bb, unsigne if (buffer[offset] == 'D') { uint32_t num; offset += 3; - if (offset >= len) + if (offset >= len) { return CL_EMALFDB; + } num = (uint32_t)readNumber(buffer, &offset, len, &ok); - if (!ok) + if (!ok) { return CL_EMALFDB; + } if (num != bcfunc->numInsts) { cli_errmsg("invalid number of dbg nodes, expected: %u, got: %u\n", bcfunc->numInsts, num); return CL_EMALFDB; @@ -1468,8 +1515,9 @@ static cl_error_t parseBB(struct cli_bc *bc, unsigned func, unsigned bb, unsigne } for (i = 0; (uint32_t)i < num; i++) { bcfunc->dbgnodes[i] = readNumber(buffer, &offset, len, &ok); - if (!ok) + if (!ok) { return CL_EMALFDB; + } } } if (offset != len) { @@ -1524,16 +1572,19 @@ void cli_sigperf_print() const char *name = cli_event_get_name(g_sigevents, i * BC_EVENTS_PER_SIG); cli_event_get(g_sigevents, i * BC_EVENTS_PER_SIG, &val, &count); if (!count) { - if (name) + if (name) { cli_dbgmsg("No event triggered for %s\n", name); + } continue; } - if (name) + if (name) { name_len = (int)strlen(name); - else + } else { name_len = 0; - if (name_len > max_name_len) + } + if (name_len > max_name_len) { max_name_len = name_len; + } elem->bc_name = name ? name : "\"noname\""; elem->usecs = val.v_int; elem->run_count = count; @@ -1542,8 +1593,9 @@ void cli_sigperf_print() elem++; elems++; } - if (max_name_len < (int)strlen("Bytecode name")) + if (max_name_len < (int)strlen("Bytecode name")) { max_name_len = (int)strlen("Bytecode name"); + } cli_qsort(stats, elems, sizeof(struct sigperf_elem), sigelem_comp); @@ -1566,8 +1618,9 @@ static void sigperf_events_init(struct cli_bc *bc) int ret; char *bc_name; - if (!g_sigevents) + if (!g_sigevents) { g_sigevents = cli_events_new(MAX_BC_SIGEVENT_ID); + } if (!g_sigevents) { cli_errmsg("No memory for events table\n"); @@ -1642,8 +1695,9 @@ cl_error_t cli_bytecode_load(struct cli_bc *bc, FILE *f, struct cli_dbio *dbio, if (!linelength) { linelength = len ? atoi(len + 1) : 4096; } - if (linelength < 4096) + if (linelength < 4096) { linelength = 4096; + } cli_dbgmsg("line: %d\n", linelength); state = PARSE_SKIP; rc = CL_SUCCESS; @@ -1763,8 +1817,9 @@ DEAD CODE case PARSE_SKIP: /* stop at S (source code), readdb.c knows how to skip this one * */ - if (buffer[0] == 'S') + if (buffer[0] == 'S') { end = 1; + } /* noop parse, but we need to use dbgets with dynamic buffer, * otherwise we get 'Line too long for provided buffer' */ break; @@ -1772,8 +1827,9 @@ DEAD CODE } free(buffer); cli_dbgmsg("Parsed %d functions\n", current_func); - if (sigperf) + if (sigperf) { sigperf_events_init(bc); + } if (current_func != bc->num_func && bc->state != bc_skip) { cli_errmsg("Loaded less functions than declared: %u vs. %u\n", current_func, bc->num_func); @@ -1809,8 +1865,9 @@ static int register_events(cli_events_t *ev) size_t i; for (i = 0; i < sizeof(bc_events) / sizeof(bc_events[0]); i++) { if (cli_event_define(ev, bc_events[i].id, bc_events[i].name, bc_events[i].type, - bc_events[i].multiple) == -1) + bc_events[i].multiple) == -1) { return -1; + } } return 0; } @@ -1825,13 +1882,16 @@ cl_error_t cli_bytecode_run(const struct cli_all_bc *bcs, const struct cli_bc *b bool test_mode = 0; cli_ctx *cctx = (cli_ctx *)ctx->ctx; - if (!ctx || !ctx->bc || !ctx->func) + if (!ctx || !ctx->bc || !ctx->func) { return CL_ENULLARG; - if (ctx->numParams && (!ctx->values || !ctx->operands)) + } + if (ctx->numParams && (!ctx->values || !ctx->operands)) { return CL_ENULLARG; + } - if (cctx && cctx->engine->bytecode_mode == CL_BYTECODE_MODE_TEST) + if (cctx && cctx->engine->bytecode_mode == CL_BYTECODE_MODE_TEST) { test_mode = true; + } if (bc->state == bc_loaded) { cli_errmsg("bytecode has to be prepared either for interpreter or JIT!\n"); @@ -1841,8 +1901,9 @@ cl_error_t cli_bytecode_run(const struct cli_all_bc *bcs, const struct cli_bc *b cli_dbgmsg("bytecode triggered but running bytecodes is disabled\n"); return CL_SUCCESS; } - if (cctx) + if (cctx) { cli_event_time_start(cctx->perf, PERFT_BYTECODE); + } ctx->env = &bcs->env; context_safe(ctx); if (test_mode) { @@ -1890,8 +1951,9 @@ cl_error_t cli_bytecode_run(const struct cli_all_bc *bcs, const struct cli_bc *b cli_event_string(interp_ev, BCEV_VIRUSNAME, ctx->virname); /* need to be called here to catch any extracted but not yet scanned files */ - if (ctx->outfd && (ret != CL_VIRUS)) + if (ctx->outfd && (ret != CL_VIRUS)) { cli_bcapi_extract_new(ctx, -1); + } } if (bc->state == bc_jit || test_mode) { if (test_mode) { @@ -1909,12 +1971,14 @@ cl_error_t cli_bytecode_run(const struct cli_all_bc *bcs, const struct cli_bc *b cli_event_string(jit_ev, BCEV_VIRUSNAME, ctx->virname); /* need to be called here to catch any extracted but not yet scanned files */ - if (ctx->outfd && (ret != CL_VIRUS)) + if (ctx->outfd && (ret != CL_VIRUS)) { cli_bcapi_extract_new(ctx, -1); + } } cli_event_time_stop(g_sigevents, bc->sigtime_id); - if (ctx->virname) + if (ctx->virname) { cli_event_count(g_sigevents, bc->sigmatch_id); + } if (test_mode) { unsigned interp_errors = cli_event_errors(interp_ev); @@ -1958,8 +2022,9 @@ cl_error_t cli_bytecode_run(const struct cli_all_bc *bcs, const struct cli_bc *b } cli_events_free(jit_ev); cli_events_free(interp_ev); - if (cctx) + if (cctx) { cli_event_time_stop(cctx->perf, PERFT_BYTECODE); + } return ret; } @@ -1977,8 +2042,9 @@ void cli_bytecode_destroy(struct cli_bc *bc) if (bc->funcs) { for (i = 0; i < bc->num_func; i++) { struct cli_bc_func *f = &bc->funcs[i]; - if (!f) + if (!f) { continue; + } free(f->types); for (j = 0; j < f->numBB; j++) { @@ -2000,8 +2066,9 @@ void cli_bytecode_destroy(struct cli_bc *bc) } if (bc->types) { for (i = NUM_STATIC_TYPES; i < bc->num_types; i++) { - if (bc->types[i].containedTypes) + if (bc->types[i].containedTypes) { free(bc->types[i].containedTypes); + } } free(bc->types); } @@ -2016,15 +2083,17 @@ void cli_bytecode_destroy(struct cli_bc *bc) for (i = 0; i < bc->dbgnode_cnt; i++) { for (j = 0; j < bc->dbgnodes[i].numelements; j++) { struct cli_bc_dbgnode_element *el = &bc->dbgnodes[i].elements[j]; - if (el && el->string) + if (el && el->string) { free(el->string); + } } } free(bc->dbgnodes); } free(bc->globaltys); - if (bc->uses_apis) + if (bc->uses_apis) { cli_bitset_free(bc->uses_apis); + } free(bc->lsig); free(bc->hook_name); free(bc->globalBytes); @@ -2107,8 +2176,9 @@ static int calc_gepz(struct cli_bc *bc, struct cli_bc_func *func, uint16_t tid, return -1; } ty = &bc->types[ty->containedTypes[0] - 65]; - if (ty->kind != DStructType && ty->kind != DPackedStructType) + if (ty->kind != DStructType && ty->kind != DPackedStructType) { return 0; + } gepoff = (uint32_t *)&func->constants[op - func->numValues]; if (*gepoff >= ty->numElements) { cli_errmsg("bytecode: gep offset out of range: %d >= %d\n", (uint32_t)*gepoff, ty->numElements); @@ -2148,13 +2218,15 @@ static cl_error_t cli_bytecode_prepare_interpreter(struct cli_bc *bc) free(gmap); return CL_EMEM; } - } else + } else { bc->globalBytes = NULL; + } for (j = 0; j < bc->num_globals; j++) { struct cli_bc_type *ty; - if (bc->globaltys[j] < 65) + if (bc->globaltys[j] < 65) { continue; + } ty = &bc->types[bc->globaltys[j] - 65]; switch (ty->kind) { case DPointerType: { @@ -2163,8 +2235,9 @@ static cl_error_t cli_bytecode_prepare_interpreter(struct cli_bc *bc) ptr = ptr_compose(bc->globals[j][1] - _FIRST_GLOBAL + 1, bc->globals[j][0]); } else { - if (bc->globals[j][1] > bc->num_globals) + if (bc->globals[j][1] > bc->num_globals) { continue; + } ptr = ptr_compose(bcglobalid, gmap[bc->globals[j][1]] + bc->globals[j][0]); } @@ -2177,20 +2250,24 @@ static cl_error_t cli_bytecode_prepare_interpreter(struct cli_bc *bc) elsize = typesize(bc, ty->containedTypes[0]); switch (elsize) { case 1: - for (i = 0; i < ty->numElements; i++) + for (i = 0; i < ty->numElements; i++) { bc->globalBytes[off + i] = bc->globals[j][i]; + } break; case 2: - for (i = 0; i < ty->numElements; i++) + for (i = 0; i < ty->numElements; i++) { *(uint16_t *)&bc->globalBytes[off + i * 2] = bc->globals[j][i]; + } break; case 4: - for (i = 0; i < ty->numElements; i++) + for (i = 0; i < ty->numElements; i++) { *(uint32_t *)&bc->globalBytes[off + i * 4] = bc->globals[j][i]; + } break; case 8: - for (i = 0; i < ty->numElements; i++) + for (i = 0; i < ty->numElements; i++) { *(uint64_t *)&bc->globalBytes[off + i * 8] = bc->globals[j][i]; + } break; default: cli_dbgmsg("interpreter: unsupported elsize: %u\n", elsize); @@ -2199,8 +2276,9 @@ static cl_error_t cli_bytecode_prepare_interpreter(struct cli_bc *bc) } default: /*TODO*/ - if (!bc->globals[j][1]) + if (!bc->globals[j][1]) { continue; /* null */ + } break; } } @@ -2301,8 +2379,9 @@ static cl_error_t cli_bytecode_prepare_interpreter(struct cli_bc *bc) ret = CL_EBYTECODE; } } - if (ret != CL_SUCCESS) + if (ret != CL_SUCCESS) { break; + } if (inst->u.ops.numOps > 0) { inst->u.ops.opsizes = malloc(sizeof(*inst->u.ops.opsizes) * inst->u.ops.numOps); if (!inst->u.ops.opsizes) { @@ -2316,10 +2395,11 @@ static cl_error_t cli_bytecode_prepare_interpreter(struct cli_bc *bc) } for (k = 0; k < inst->u.ops.numOps; k++) { MAPPTR(inst->u.ops.ops[k]); - if (inst->opcode == OP_BC_CALL_DIRECT) + if (inst->opcode == OP_BC_CALL_DIRECT) { inst->u.ops.opsizes[k] = typesize(bc, target->types[k]); - else + } else { inst->u.ops.opsizes[k] = 32; /*XXX*/ + } } break; } @@ -2332,26 +2412,31 @@ static cl_error_t cli_bytecode_prepare_interpreter(struct cli_bc *bc) cli_errmsg("bytecode: gep1 of alloca is not allowed\n"); ret = CL_EBYTECODE; } - if (ret != CL_SUCCESS) + if (ret != CL_SUCCESS) { break; + } MAP(inst->u.three[1]); MAP(inst->u.three[2]); inst->u.three[0] = get_geptypesize(bc, inst->u.three[0]); - if ((int)(inst->u.three[0]) == -1) + if ((int)(inst->u.three[0]) == -1) { ret = CL_EBYTECODE; + } break; case OP_BC_GEPZ: /*three[0] is the type*/ if (inst->u.three[1] & 0x80000000 || - bcfunc->types[inst->u.three[1]] & 0x8000) + bcfunc->types[inst->u.three[1]] & 0x8000) { inst->interp_op = 5 * (inst->interp_op / 5); - else + } else { inst->interp_op = 5 * (inst->interp_op / 5) + 3; + } MAP(inst->u.three[1]); - if (calc_gepz(bc, bcfunc, inst->u.three[0], inst->u.three[2]) == -1) + if (calc_gepz(bc, bcfunc, inst->u.three[0], inst->u.three[2]) == -1) { ret = CL_EBYTECODE; - if (ret == CL_SUCCESS) + } + if (ret == CL_SUCCESS) { MAP(inst->u.three[2]); + } break; /* case OP_BC_GEPN: *TODO @@ -2386,8 +2471,9 @@ static cl_error_t cli_bytecode_prepare_interpreter(struct cli_bc *bc) ret = CL_EBYTECODE; } } - if (map) + if (map) { free(map); + } } free(gmap); bc->state = bc_interp; @@ -2543,10 +2629,12 @@ static cl_error_t selfcheck(bool jit, struct cli_bcengine *engine) } else { rc = cli_bytecode_prepare_interpreter(bcs.all_bcs); } - if (rc == CL_SUCCESS) + if (rc == CL_SUCCESS) { rc = run_selfcheck(&bcs); - if (rc == CL_BREAK) + } + if (rc == CL_BREAK) { rc = CL_SUCCESS; + } } cli_bytecode_destroy(bcs.all_bcs); free(bcs.all_bcs); @@ -2560,8 +2648,9 @@ static cl_error_t selfcheck(bool jit, struct cli_bcengine *engine) static int set_mode(struct cl_engine *engine, enum bytecode_mode mode) { - if (engine->bytecode_mode == mode) + if (engine->bytecode_mode == mode) { return 0; + } if (engine->bytecode_mode == CL_BYTECODE_MODE_OFF) { cli_errmsg("bytecode: already turned off, can't turn it on again!\n"); return -1; @@ -2593,11 +2682,13 @@ static cl_error_t run_builtin_or_loaded(struct cli_all_bc *bcs, uint8_t kind, co for (i = 0; i < bcs->count; i++) { bc = &bcs->all_bcs[i]; - if (bc->kind == kind) + if (bc->kind == kind) { break; + } } - if (i == bcs->count) + if (i == bcs->count) { bc = NULL; + } if (!bc) { /* no loaded bytecode found, load the builtin one! */ struct cli_dbio dbio; @@ -2670,29 +2761,33 @@ cl_error_t cli_bytecode_prepare2(struct cl_engine *engine, struct cli_all_bc *bc case arch_x86_64: if (!(dconfmask & BYTECODE_JIT_X86)) { cli_dbgmsg("Bytecode: disabled on X86 via DCONF\n"); - if (set_mode(engine, CL_BYTECODE_MODE_INTERPRETER) == -1) + if (set_mode(engine, CL_BYTECODE_MODE_INTERPRETER) == -1) { return CL_EBYTECODE_TESTFAIL; + } } break; case arch_ppc32: case arch_ppc64: if (!(dconfmask & BYTECODE_JIT_PPC)) { cli_dbgmsg("Bytecode: disabled on PPC via DCONF\n"); - if (set_mode(engine, CL_BYTECODE_MODE_INTERPRETER) == -1) + if (set_mode(engine, CL_BYTECODE_MODE_INTERPRETER) == -1) { return CL_EBYTECODE_TESTFAIL; + } } break; case arch_arm: if (!(dconfmask & BYTECODE_JIT_ARM)) { cli_dbgmsg("Bytecode: disabled on ARM via DCONF\n"); - if (set_mode(engine, CL_BYTECODE_MODE_INTERPRETER) == -1) + if (set_mode(engine, CL_BYTECODE_MODE_INTERPRETER) == -1) { return CL_EBYTECODE_TESTFAIL; + } } break; default: cli_dbgmsg("Bytecode: JIT not supported on this architecture, falling back\n"); - if (set_mode(engine, CL_BYTECODE_MODE_INTERPRETER) == -1) + if (set_mode(engine, CL_BYTECODE_MODE_INTERPRETER) == -1) { return CL_EBYTECODE_TESTFAIL; + } break; } cli_dbgmsg("Bytecode: mode is %d\n", engine->bytecode_mode); @@ -2716,18 +2811,21 @@ cl_error_t cli_bytecode_prepare2(struct cl_engine *engine, struct cli_all_bc *bc if (context_result != (uint64_t)0xda7aba5e) { cli_warnmsg("Bytecode: selftest failed with code " STDx64 ". Please report to https://github.com/Cisco-Talos/clamav/issues\n", context_result); - if (engine->bytecode_mode == CL_BYTECODE_MODE_TEST) + if (engine->bytecode_mode == CL_BYTECODE_MODE_TEST) { return CL_EBYTECODE_TESTFAIL; + } } } switch (ctx->bytecode_disable_status) { case 1: - if (set_mode(engine, CL_BYTECODE_MODE_INTERPRETER) == -1) + if (set_mode(engine, CL_BYTECODE_MODE_INTERPRETER) == -1) { return CL_EBYTECODE_TESTFAIL; + } break; case 2: - if (set_mode(engine, CL_BYTECODE_MODE_OFF) == -1) + if (set_mode(engine, CL_BYTECODE_MODE_OFF) == -1) { return CL_EBYTECODE_TESTFAIL; + } break; default: break; @@ -2740,8 +2838,9 @@ cl_error_t cli_bytecode_prepare2(struct cl_engine *engine, struct cli_all_bc *bc rc = cli_bytecode_prepare_jit(bcs); if (rc == CL_SUCCESS) { cli_dbgmsg("Bytecode: %u bytecode prepared with JIT\n", bcs->count); - if (engine->bytecode_mode != CL_BYTECODE_MODE_TEST) + if (engine->bytecode_mode != CL_BYTECODE_MODE_TEST) { return CL_SUCCESS; + } } if (engine->bytecode_mode == CL_BYTECODE_MODE_JIT) { cli_errmsg("Bytecode: JIT required, but not all bytecodes could be prepared with JIT\n"); @@ -2757,13 +2856,15 @@ cl_error_t cli_bytecode_prepare2(struct cl_engine *engine, struct cli_all_bc *bc if (!(dconfmask & BYTECODE_INTERPRETER)) { cli_dbgmsg("Bytecode: needs interpreter, but interpreter is disabled\n"); - if (set_mode(engine, CL_BYTECODE_MODE_OFF) == -1) + if (set_mode(engine, CL_BYTECODE_MODE_OFF) == -1) { return CL_EBYTECODE_TESTFAIL; + } } if (engine->bytecode_mode == CL_BYTECODE_MODE_OFF) { - for (i = 0; i < bcs->count; i++) + for (i = 0; i < bcs->count; i++) { bcs->all_bcs[i].state = bc_disabled; + } cli_dbgmsg("Bytecode: ALL bytecodes disabled\n"); return CL_SUCCESS; } @@ -2772,8 +2873,9 @@ cl_error_t cli_bytecode_prepare2(struct cl_engine *engine, struct cli_all_bc *bc struct cli_bc *bc = &bcs->all_bcs[i]; if (bc->state == bc_jit) { jitcount++; - if (engine->bytecode_mode != CL_BYTECODE_MODE_TEST) + if (engine->bytecode_mode != CL_BYTECODE_MODE_TEST) { continue; + } } if (bc->state == bc_interp) { interp++; @@ -2828,8 +2930,9 @@ cl_error_t cli_bytecode_runlsig(cli_ctx *cctx, struct cli_target_info *tinfo, struct cli_pe_hook_data pehookdata; const char *bc_name = NULL; - if (bc_idx == 0) + if (bc_idx == 0) { return CL_ENULLARG; + } if (NULL != bc->lsig) { bc_name = bc->lsig; @@ -2857,8 +2960,9 @@ cl_error_t cli_bytecode_runlsig(cli_ctx *cctx, struct cli_target_info *tinfo, cli_dbgmsg("hook lsig id %d matched (bc %d)\n", bc->hook_lsig_id, bc->id); /* this is a bytecode for a hook, defer running it until hook is * executed, so that it has all the info for the hook */ - if (cctx->hook_lsig_matches) + if (cctx->hook_lsig_matches) { cli_bitset_set(cctx->hook_lsig_matches, bc->hook_lsig_id - 1); + } /* save match counts */ memcpy(&ctx.lsigcnt, lsigcnt, 64 * 4); memcpy(&ctx.lsigoff, lsigsuboff, 64 * 4); @@ -2902,8 +3006,9 @@ cl_error_t cli_bytecode_runhook(cli_ctx *cctx, const struct cl_engine *engine, s cl_error_t ret; unsigned executed = 0, breakflag = 0, errorflag = 0; - if (!cctx) + if (!cctx) { return CL_ENULLARG; + } cli_dbgmsg("Bytecode executing hook id %u (%u hooks)\n", id, hooks_cnt); /* restore match counts */ @@ -2914,8 +3019,9 @@ cl_error_t cli_bytecode_runhook(cli_ctx *cctx, const struct cl_engine *engine, s const struct cli_bc *bc = &engine->bcs.all_bcs[hooks[i]]; if (bc->lsig) { if (!cctx->hook_lsig_matches || - !cli_bitset_test(cctx->hook_lsig_matches, bc->hook_lsig_id - 1)) + !cli_bitset_test(cctx->hook_lsig_matches, bc->hook_lsig_id - 1)) { continue; + } cli_dbgmsg("Bytecode: executing bytecode %u (lsig matched)\n", bc->id); } cli_bytecode_context_setfuncid(ctx, bc, 0); @@ -2993,13 +3099,15 @@ cl_error_t cli_bytecode_runhook(cli_ctx *cctx, const struct cl_engine *engine, s } bytecode_context_reset(ctx); } - if (executed) + if (executed) { cli_dbgmsg("Bytecode: executed %u bytecodes for this hook\n", executed); - else + } else { cli_dbgmsg("Bytecode: no logical signature matched, no bytecode executed\n"); + } - if (errorflag && cctx->engine->bytecode_mode == CL_BYTECODE_MODE_TEST) + if (errorflag && cctx->engine->bytecode_mode == CL_BYTECODE_MODE_TEST) { return CL_EBYTECODE_TESTFAIL; + } return breakflag ? CL_BREAK : CL_CLEAN; } @@ -3102,37 +3210,42 @@ void cli_bytecode_describe(const struct cli_bc *bc) puts("files matching logical signature"); break; case BC_PE_UNPACKER: - if (bc->lsig) + if (bc->lsig) { puts("PE files matching logical signature (unpacked)"); - else + } else { puts("all PE files! (unpacked)"); + } break; case BC_PDF: puts("PDF files"); break; case BC_PE_ALL: - if (bc->lsig) + if (bc->lsig) { puts("PE files matching logical signature"); - else + } else { puts("all PE files!"); + } break; case BC_PRECLASS: - if (bc->lsig) + if (bc->lsig) { puts("PRECLASS files matching logical signature"); - else + } else { puts("all PRECLASS files!"); + } break; case BC_ELF_UNPACKER: - if (bc->lsig) + if (bc->lsig) { puts("ELF files matching logical signature (unpacked)"); - else + } else { puts("all ELF files! (unpacked)"); + } break; case BC_MACHO_UNPACKER: - if (bc->lsig) + if (bc->lsig) { puts("Mach-O files matching logical signature (unpacked)"); - else + } else { puts("all Mach-O files! (unpacked)"); + } break; default: puts("N/A (unknown type)\n"); @@ -3148,8 +3261,9 @@ void cli_bytecode_describe(const struct cli_bc *bc) for (i = 0; i < cli_apicall_maxapi; i++) { if (cli_bitset_test(bc->uses_apis, i)) { unsigned len = strlen(cli_apicalls[i].name); - if (had) + if (had) { printf(","); + } if (len > (unsigned int)cols) { printf("\n\t"); cols = 72; @@ -3332,8 +3446,9 @@ void cli_bytevalue_describe(const struct cli_bc *bc, unsigned funcid) for (i = 0; i < func->numValues; ++i) { printf("%3u [%3u]: ", i, total++); cli_bytetype_helper(bc, func->types[i]); - if (i < func->numArgs) + if (i < func->numArgs) { printf(" argument"); + } printf("\n"); } printf("------------------------------------------------------------------------\n"); diff --git a/libclamav/bytecode_api.c b/libclamav/bytecode_api.c index 03099f261b..f87071cc0d 100644 --- a/libclamav/bytecode_api.c +++ b/libclamav/bytecode_api.c @@ -157,8 +157,9 @@ uint32_t cli_bcapi_debug_print_uint(struct cli_bc_ctx *ctx, uint32_t a) cli_event_int(EV, BCEV_DBG_INT, a); // cli_dbgmsg("bytecode debug: %d\n", a); // return 0; - if (!cli_debug_flag) + if (!cli_debug_flag) { return 0; + } return cli_eprintf("%d", a); } @@ -187,10 +188,11 @@ uint32_t cli_bcapi_disasm_x86(struct cli_bc_ctx *ctx, struct DISASM_RESULT *res, * When we'll support mmx/sse instructions this should be updated! */ n = MIN(32, ctx->fmap->len - ctx->off); buf = fmap_need_off_once(ctx->fmap, ctx->off, n); - if (buf) + if (buf) { next = cli_disasm_one(buf, n, res, 0); - else + } else { next = NULL; + } if (!next) { cli_dbgmsg("bcapi_disasm: failed\n"); cli_event_count(EV, BCEV_DISASM_FAIL); @@ -232,10 +234,13 @@ int32_t cli_bcapi_write(struct cli_bc_ctx *ctx, uint8_t *data, int32_t len) } cli_event_fastdata(ctx->bc_events, BCEV_WRITE, data, len); - if (cli_checklimits("bytecode api", cctx, ctx->written + len, 0, 0)) + if (cli_checklimits("bytecode api", cctx, ctx->written + len, 0, 0)) { return -1; + } res = cli_writen(ctx->outfd, data, (size_t)len); - if (res > 0) ctx->written += res; + if (res > 0) { + ctx->written += res; + } if (res == (size_t)-1) { cli_warnmsg("Bytecode API: write failed: %s\n", cli_strerror(errno, err, sizeof(err))); cli_event_error_str(EV, "cli_bcapi_write: write failed"); @@ -258,8 +263,9 @@ void cli_bytecode_context_set_trace(struct cli_bc_ctx *ctx, unsigned level, uint32_t cli_bcapi_trace_scope(struct cli_bc_ctx *ctx, const uint8_t *scope, uint32_t scopeid) { - if (LIKELY(!ctx->trace_level)) + if (LIKELY(!ctx->trace_level)) { return 0; + } if (ctx->scope != (const char *)scope) { ctx->scope = (const char *)scope ? (const char *)scope : "?"; ctx->scopeid = scopeid; @@ -274,16 +280,18 @@ uint32_t cli_bcapi_trace_scope(struct cli_bc_ctx *ctx, const uint8_t *scope, uin uint32_t cli_bcapi_trace_directory(struct cli_bc_ctx *ctx, const uint8_t *dir, uint32_t dummy) { UNUSEDPARAM(dummy); - if (LIKELY(!ctx->trace_level)) + if (LIKELY(!ctx->trace_level)) { return 0; + } ctx->directory = (const char *)dir ? (const char *)dir : ""; return 0; } uint32_t cli_bcapi_trace_source(struct cli_bc_ctx *ctx, const uint8_t *file, uint32_t line) { - if (LIKELY(ctx->trace_level < trace_line)) + if (LIKELY(ctx->trace_level < trace_line)) { return 0; + } if (ctx->file != (const char *)file || ctx->line != line) { ctx->col = 0; ctx->file = (const char *)file ? (const char *)file : "??"; @@ -294,55 +302,65 @@ uint32_t cli_bcapi_trace_source(struct cli_bc_ctx *ctx, const uint8_t *file, uin uint32_t cli_bcapi_trace_op(struct cli_bc_ctx *ctx, const uint8_t *op, uint32_t col) { - if (LIKELY(ctx->trace_level < trace_col)) + if (LIKELY(ctx->trace_level < trace_col)) { return 0; + } if (ctx->trace_level & 0xc0) { ctx->col = col; /* func/scope changed and they needed param/location event */ ctx->trace(ctx, (ctx->trace_level & 0x80) ? trace_func : trace_scope); ctx->trace_level &= ~0xc0; } - if (LIKELY(ctx->trace_level < trace_col)) + if (LIKELY(ctx->trace_level < trace_col)) { return 0; + } if (ctx->col != col) { ctx->col = col; ctx->trace(ctx, trace_col); } else { ctx->trace(ctx, trace_line); } - if (LIKELY(ctx->trace_level < trace_op)) + if (LIKELY(ctx->trace_level < trace_op)) { return 0; - if (ctx->trace_op && op) + } + if (ctx->trace_op && op) { ctx->trace_op(ctx, (const char *)op); + } return 0; } uint32_t cli_bcapi_trace_value(struct cli_bc_ctx *ctx, const uint8_t *name, uint32_t value) { - if (LIKELY(ctx->trace_level < trace_val)) + if (LIKELY(ctx->trace_level < trace_val)) { return 0; + } if (ctx->trace_level & 0x80) { - if ((ctx->trace_level & 0x7f) < trace_param) + if ((ctx->trace_level & 0x7f) < trace_param) { return 0; + } ctx->trace(ctx, trace_param); } - if (ctx->trace_val && name) + if (ctx->trace_val && name) { ctx->trace_val(ctx, (const char *)name, value); + } return 0; } uint32_t cli_bcapi_trace_ptr(struct cli_bc_ctx *ctx, const uint8_t *ptr, uint32_t dummy) { UNUSEDPARAM(dummy); - if (LIKELY(ctx->trace_level < trace_val)) + if (LIKELY(ctx->trace_level < trace_val)) { return 0; + } if (ctx->trace_level & 0x80) { - if ((ctx->trace_level & 0x7f) < trace_param) + if ((ctx->trace_level & 0x7f) < trace_param) { return 0; + } ctx->trace(ctx, trace_param); } - if (ctx->trace_ptr) + if (ctx->trace_ptr) { ctx->trace_ptr(ctx, ptr); + } return 0; } @@ -370,18 +388,21 @@ static inline const char *cli_memmem(const char *haystack, unsigned hlen, return NULL; } c = *needle++; - if (nlen == 1) + if (nlen == 1) { return memchr(haystack, c, hlen); + } while (hlen >= nlen) { p = haystack; haystack = memchr(haystack, c, hlen - nlen + 1); - if (!haystack) + if (!haystack) { return NULL; + } hlen -= haystack + 1 - p; p = haystack + 1; - if (!memcmp(p, needle, nlen - 1)) + if (!memcmp(p, needle, nlen - 1)) { return haystack; + } haystack = p; } return NULL; @@ -427,11 +448,13 @@ int32_t cli_bcapi_file_find_limit(struct cli_bc_ctx *ctx, const uint8_t *data, u } } n = fmap_readn(map, buf, off, readlen); - if ((n < len) || (n == (size_t)-1)) + if ((n < len) || (n == (size_t)-1)) { return -1; + } p = cli_memmem(buf, n, data, len); - if (p) + if (p) { return off + (p - buf); + } off += n; } return -1; @@ -477,8 +500,9 @@ uint8_t *cli_bcapi_malloc(struct cli_bc_ctx *ctx, uint32_t size) cli_errmsg("cli_bcapi_malloc not implemented for systems without mmap yet!\n"); v = cli_max_malloc(size); #endif - if (!v) + if (!v) { cli_event_error_oom(EV, size); + } return v; } @@ -538,10 +562,12 @@ int32_t cli_bcapi_extract_new(struct cli_bc_ctx *ctx, int32_t id) cli_event_count(EV, BCEV_EXTRACTED); cli_dbgmsg("previous tempfile had %u bytes\n", ctx->written); - if (!ctx->written) + if (!ctx->written) { return 0; - if (ctx->ctx && cli_updatelimits(ctx->ctx, ctx->written)) + } + if (ctx->ctx && cli_updatelimits(ctx->ctx, ctx->written)) { return -1; + } ctx->written = 0; if (lseek(ctx->outfd, 0, SEEK_SET) == -1) { cli_dbgmsg("bytecode: call to lseek() has failed\n"); @@ -578,16 +604,18 @@ int32_t cli_bcapi_read_number(struct cli_bc_ctx *ctx, uint32_t radix) const char *p; int32_t result; - if ((radix != 10 && radix != 16) || !ctx->fmap) + if ((radix != 10 && radix != 16) || !ctx->fmap) { return -1; + } cli_event_int(EV, BCEV_OFFSET, ctx->off); while ((p = fmap_need_off_once(ctx->fmap, ctx->off, BUF))) { for (i = 0; i < BUF; i++) { if ((p[i] >= '0' && p[i] <= '9') || (radix == 16 && ((p[i] >= 'a' && p[i] <= 'f') || (p[i] >= 'A' && p[i] <= 'F')))) { char *endptr; p = fmap_need_ptr_once(ctx->fmap, p + i, 16); - if (!p) + if (!p) { return -1; + } result = strtoul(p, &endptr, radix); ctx->off += i + (endptr - p); return result; @@ -625,24 +653,27 @@ static struct cli_hashset *get_hashset(struct cli_bc_ctx *ctx, int32_t id) int32_t cli_bcapi_hashset_add(struct cli_bc_ctx *ctx, int32_t id, uint32_t key) { struct cli_hashset *s = get_hashset(ctx, id); - if (!s) + if (!s) { return -1; + } return cli_hashset_addkey(s, key) == CL_SUCCESS ? 0 : -1; } int32_t cli_bcapi_hashset_remove(struct cli_bc_ctx *ctx, int32_t id, uint32_t key) { struct cli_hashset *s = get_hashset(ctx, id); - if (!s) + if (!s) { return -1; + } return cli_hashset_removekey(s, key) == CL_SUCCESS ? 0 : -1; } int32_t cli_bcapi_hashset_contains(struct cli_bc_ctx *ctx, int32_t id, uint32_t key) { struct cli_hashset *s = get_hashset(ctx, id); - if (!s) + if (!s) { return -1; + } return cli_hashset_contains(s, key); } @@ -655,8 +686,9 @@ int32_t cli_bcapi_hashset_empty(struct cli_bc_ctx *ctx, int32_t id) int32_t cli_bcapi_hashset_done(struct cli_bc_ctx *ctx, int32_t id) { struct cli_hashset *s = get_hashset(ctx, id); - if (!s) + if (!s) { return -1; + } cli_hashset_destroy(s); if ((unsigned int)id == ctx->nhashsets - 1) { ctx->nhashsets--; @@ -665,8 +697,9 @@ int32_t cli_bcapi_hashset_done(struct cli_bc_ctx *ctx, int32_t id) ctx->hashsets = NULL; } else { s = cli_max_realloc(ctx->hashsets, ctx->nhashsets * sizeof(*s)); - if (s) + if (s) { ctx->hashsets = s; + } } } return 0; @@ -679,8 +712,9 @@ int32_t cli_bcapi_buffer_pipe_new(struct cli_bc_ctx *ctx, uint32_t size) unsigned n = ctx->nbuffers + 1; data = cli_max_calloc(1, size); - if (!data) + if (!data) { return -1; + } b = cli_max_realloc(ctx->buffers, sizeof(*ctx->buffers) * n); if (!b) { free(data); @@ -701,8 +735,9 @@ int32_t cli_bcapi_buffer_pipe_new_fromfile(struct cli_bc_ctx *ctx, uint32_t at) struct bc_buffer *b; unsigned n = ctx->nbuffers + 1; - if (at >= ctx->file_size) + if (at >= ctx->file_size) { return -1; + } b = cli_max_realloc(ctx->buffers, sizeof(*ctx->buffers) * n); if (!b) { @@ -732,45 +767,55 @@ static struct bc_buffer *get_buffer(struct cli_bc_ctx *ctx, int32_t id) uint32_t cli_bcapi_buffer_pipe_read_avail(struct cli_bc_ctx *ctx, int32_t id) { struct bc_buffer *b = get_buffer(ctx, id); - if (!b) + if (!b) { return 0; + } if (b->data) { - if (b->write_cursor <= b->read_cursor) + if (b->write_cursor <= b->read_cursor) { return 0; + } return b->write_cursor - b->read_cursor; } - if (!ctx->fmap || b->read_cursor >= ctx->file_size) + if (!ctx->fmap || b->read_cursor >= ctx->file_size) { return 0; - if (b->read_cursor + BUFSIZ <= ctx->file_size) + } + if (b->read_cursor + BUFSIZ <= ctx->file_size) { return BUFSIZ; + } return ctx->file_size - b->read_cursor; } const uint8_t *cli_bcapi_buffer_pipe_read_get(struct cli_bc_ctx *ctx, int32_t id, uint32_t size) { struct bc_buffer *b = get_buffer(ctx, id); - if (!b || size > cli_bcapi_buffer_pipe_read_avail(ctx, id) || !size) + if (!b || size > cli_bcapi_buffer_pipe_read_avail(ctx, id) || !size) { return NULL; - if (b->data) + } + if (b->data) { return b->data + b->read_cursor; + } return fmap_need_off(ctx->fmap, b->read_cursor, size); } int32_t cli_bcapi_buffer_pipe_read_stopped(struct cli_bc_ctx *ctx, int32_t id, uint32_t amount) { struct bc_buffer *b = get_buffer(ctx, id); - if (!b) + if (!b) { return -1; + } if (b->data) { - if (b->write_cursor <= b->read_cursor) + if (b->write_cursor <= b->read_cursor) { return -1; - if (b->read_cursor + amount > b->write_cursor) + } + if (b->read_cursor + amount > b->write_cursor) { b->read_cursor = b->write_cursor; - else + } else { b->read_cursor += amount; + } if (b->read_cursor >= b->size && - b->write_cursor >= b->size) + b->write_cursor >= b->size) { b->read_cursor = b->write_cursor = 0; + } return 0; } b->read_cursor += amount; @@ -780,42 +825,50 @@ int32_t cli_bcapi_buffer_pipe_read_stopped(struct cli_bc_ctx *ctx, int32_t id, u uint32_t cli_bcapi_buffer_pipe_write_avail(struct cli_bc_ctx *ctx, int32_t id) { struct bc_buffer *b = get_buffer(ctx, id); - if (!b) + if (!b) { return 0; - if (!b->data) + } + if (!b->data) { return 0; - if (b->write_cursor >= b->size) + } + if (b->write_cursor >= b->size) { return 0; + } return b->size - b->write_cursor; } uint8_t *cli_bcapi_buffer_pipe_write_get(struct cli_bc_ctx *ctx, int32_t id, uint32_t size) { struct bc_buffer *b = get_buffer(ctx, id); - if (!b || size > cli_bcapi_buffer_pipe_write_avail(ctx, id) || !size) + if (!b || size > cli_bcapi_buffer_pipe_write_avail(ctx, id) || !size) { return NULL; - if (!b->data) + } + if (!b->data) { return NULL; + } return b->data + b->write_cursor; } int32_t cli_bcapi_buffer_pipe_write_stopped(struct cli_bc_ctx *ctx, int32_t id, uint32_t size) { struct bc_buffer *b = get_buffer(ctx, id); - if (!b || !b->data) + if (!b || !b->data) { return -1; - if (b->write_cursor + size >= b->size) + } + if (b->write_cursor + size >= b->size) { b->write_cursor = b->size; - else + } else { b->write_cursor += size; + } return 0; } int32_t cli_bcapi_buffer_pipe_done(struct cli_bc_ctx *ctx, int32_t id) { struct bc_buffer *b = get_buffer(ctx, id); - if (!b) + if (!b) { return -1; + } free(b->data); b->data = NULL; return -0; @@ -866,8 +919,9 @@ int32_t cli_bcapi_inflate_init(struct cli_bc_ctx *ctx, int32_t from, int32_t to, static struct bc_inflate *get_inflate(struct cli_bc_ctx *ctx, int32_t id) { - if (id < 0 || (unsigned int)id >= ctx->ninflates || !ctx->inflates) + if (id < 0 || (unsigned int)id >= ctx->ninflates || !ctx->inflates) { return NULL; + } return &ctx->inflates[id]; } @@ -876,8 +930,9 @@ int32_t cli_bcapi_inflate_process(struct cli_bc_ctx *ctx, int32_t id) int ret; unsigned avail_in_orig, avail_out_orig; struct bc_inflate *b = get_inflate(ctx, id); - if (!b || b->from == -1 || b->to == -1) + if (!b || b->from == -1 || b->to == -1) { return -1; + } b->stream.avail_in = avail_in_orig = cli_bcapi_buffer_pipe_read_avail(ctx, b->from); @@ -891,8 +946,9 @@ int32_t cli_bcapi_inflate_process(struct cli_bc_ctx *ctx, int32_t id) b->stream.next_out = cli_bcapi_buffer_pipe_write_get(ctx, b->to, b->stream.avail_out); - if (!b->stream.avail_in || !b->stream.avail_out || !b->stream.next_in || !b->stream.next_out) + if (!b->stream.avail_in || !b->stream.avail_out || !b->stream.next_in || !b->stream.next_out) { return -1; + } /* try hard to extract data, skipping over corrupted data */ do { if (!b->needSync) { @@ -935,11 +991,13 @@ int32_t cli_bcapi_inflate_done(struct cli_bc_ctx *ctx, int32_t id) { int ret; struct bc_inflate *b = get_inflate(ctx, id); - if (!b || b->from == -1 || b->to == -1) + if (!b || b->from == -1 || b->to == -1) { return -1; + } ret = inflateEnd(&b->stream); - if (ret == Z_STREAM_ERROR) + if (ret == Z_STREAM_ERROR) { cli_dbgmsg("bytecode api: inflateEnd: %s\n", b->stream.msg); + } b->from = b->to = -1; return ret; } @@ -991,8 +1049,9 @@ int32_t cli_bcapi_lzma_init(struct cli_bc_ctx *ctx, int32_t from, int32_t to) static struct bc_lzma *get_lzma(struct cli_bc_ctx *ctx, int32_t id) { - if (id < 0 || (unsigned int)id >= ctx->nlzmas || !ctx->lzmas) + if (id < 0 || (unsigned int)id >= ctx->nlzmas || !ctx->lzmas) { return NULL; + } return &ctx->lzmas[id]; } @@ -1001,8 +1060,9 @@ int32_t cli_bcapi_lzma_process(struct cli_bc_ctx *ctx, int32_t id) int ret; unsigned avail_in_orig, avail_out_orig; struct bc_lzma *b = get_lzma(ctx, id); - if (!b || b->from == -1 || b->to == -1) + if (!b || b->from == -1 || b->to == -1) { return -1; + } b->stream.avail_in = avail_in_orig = cli_bcapi_buffer_pipe_read_avail(ctx, b->from); @@ -1015,8 +1075,9 @@ int32_t cli_bcapi_lzma_process(struct cli_bc_ctx *ctx, int32_t id) b->stream.next_out = (uint8_t *)cli_bcapi_buffer_pipe_write_get(ctx, b->to, b->stream.avail_out); - if (!b->stream.avail_in || !b->stream.avail_out || !b->stream.next_in || !b->stream.next_out) + if (!b->stream.avail_in || !b->stream.avail_out || !b->stream.next_in || !b->stream.next_out) { return -1; + } ret = cli_LzmaDecode(&b->stream); cli_bcapi_buffer_pipe_read_stopped(ctx, b->from, avail_in_orig - b->stream.avail_in); @@ -1033,8 +1094,9 @@ int32_t cli_bcapi_lzma_process(struct cli_bc_ctx *ctx, int32_t id) int32_t cli_bcapi_lzma_done(struct cli_bc_ctx *ctx, int32_t id) { struct bc_lzma *b = get_lzma(ctx, id); - if (!b || b->from == -1 || b->to == -1) + if (!b || b->from == -1 || b->to == -1) { return -1; + } cli_LzmaShutdown(&b->stream); b->from = b->to = -1; return 0; @@ -1083,8 +1145,9 @@ int32_t cli_bcapi_bzip2_init(struct cli_bc_ctx *ctx, int32_t from, int32_t to) static struct bc_bzip2 *get_bzip2(struct cli_bc_ctx *ctx, int32_t id) { - if (id < 0 || (unsigned int)id >= ctx->nbzip2s || !ctx->bzip2s) + if (id < 0 || (unsigned int)id >= ctx->nbzip2s || !ctx->bzip2s) { return NULL; + } return &ctx->bzip2s[id]; } @@ -1093,8 +1156,9 @@ int32_t cli_bcapi_bzip2_process(struct cli_bc_ctx *ctx, int32_t id) int ret; unsigned avail_in_orig, avail_out_orig; struct bc_bzip2 *b = get_bzip2(ctx, id); - if (!b || b->from == -1 || b->to == -1) + if (!b || b->from == -1 || b->to == -1) { return -1; + } b->stream.avail_in = avail_in_orig = cli_bcapi_buffer_pipe_read_avail(ctx, b->from); @@ -1108,8 +1172,9 @@ int32_t cli_bcapi_bzip2_process(struct cli_bc_ctx *ctx, int32_t id) b->stream.next_out = (char *)cli_bcapi_buffer_pipe_write_get(ctx, b->to, b->stream.avail_out); - if (!b->stream.avail_in || !b->stream.avail_out || !b->stream.next_in || !b->stream.next_out) + if (!b->stream.avail_in || !b->stream.avail_out || !b->stream.next_in || !b->stream.next_out) { return -1; + } /* try hard to extract data, skipping over corrupted data */ ret = BZ2_bzDecompress(&b->stream); cli_bcapi_buffer_pipe_read_stopped(ctx, b->from, avail_in_orig - b->stream.avail_in); @@ -1127,8 +1192,9 @@ int32_t cli_bcapi_bzip2_process(struct cli_bc_ctx *ctx, int32_t id) int32_t cli_bcapi_bzip2_done(struct cli_bc_ctx *ctx, int32_t id) { struct bc_bzip2 *b = get_bzip2(ctx, id); - if (!b || b->from == -1 || b->to == -1) + if (!b || b->from == -1 || b->to == -1) { return -1; + } BZ2_bzDecompressEnd(&b->stream); b->from = b->to = -1; return 0; @@ -1153,8 +1219,9 @@ int32_t cli_bcapi_jsnorm_init(struct cli_bc_ctx *ctx, int32_t from) return -1; } state = cli_js_init(); - if (!state) + if (!state) { return -1; + } b = cli_max_realloc(ctx->jsnorms, sizeof(*ctx->jsnorms) * n); if (!b) { cli_js_destroy(state); @@ -1181,8 +1248,9 @@ int32_t cli_bcapi_jsnorm_init(struct cli_bc_ctx *ctx, int32_t from) static struct bc_jsnorm *get_jsnorm(struct cli_bc_ctx *ctx, int32_t id) { - if (id < 0 || (unsigned int)id >= ctx->njsnorms || !ctx->jsnorms) + if (id < 0 || (unsigned int)id >= ctx->njsnorms || !ctx->jsnorms) { return NULL; + } return &ctx->jsnorms[id]; } @@ -1192,15 +1260,18 @@ int32_t cli_bcapi_jsnorm_process(struct cli_bc_ctx *ctx, int32_t id) const unsigned char *in; cli_ctx *cctx = ctx->ctx; struct bc_jsnorm *b = get_jsnorm(ctx, id); - if (!b || b->from == -1 || !b->state) + if (!b || b->from == -1 || !b->state) { return -1; + } avail = cli_bcapi_buffer_pipe_read_avail(ctx, b->from); in = cli_bcapi_buffer_pipe_read_get(ctx, b->from, avail); - if (!avail || !in) + if (!avail || !in) { return -1; - if (cctx && cli_checklimits("bytecode js api", cctx, ctx->jsnormwritten + avail, 0, 0)) + } + if (cctx && cli_checklimits("bytecode js api", cctx, ctx->jsnormwritten + avail, 0, 0)) { return -1; + } cli_bcapi_buffer_pipe_read_stopped(ctx, b->from, avail); cli_js_process_buffer(b->state, (char *)in, avail); return 0; @@ -1209,10 +1280,12 @@ int32_t cli_bcapi_jsnorm_process(struct cli_bc_ctx *ctx, int32_t id) int32_t cli_bcapi_jsnorm_done(struct cli_bc_ctx *ctx, int32_t id) { struct bc_jsnorm *b = get_jsnorm(ctx, id); - if (!b || b->from == -1) + if (!b || b->from == -1) { return -1; - if (ctx->ctx && cli_updatelimits(ctx->ctx, ctx->jsnormwritten)) + } + if (ctx->ctx && cli_updatelimits(ctx->ctx, ctx->jsnormwritten)) { return -1; + } ctx->jsnormwritten = 0; cli_js_parse_done(b->state); cli_js_output(b->state, ctx->jsnormdir); @@ -1223,8 +1296,9 @@ int32_t cli_bcapi_jsnorm_done(struct cli_bc_ctx *ctx, int32_t id) static inline double myround(double a) { - if (a < 0) + if (a < 0) { return a - 0.5; + } return a + 0.5; } @@ -1232,8 +1306,9 @@ int32_t cli_bcapi_ilog2(struct cli_bc_ctx *ctx, uint32_t a, uint32_t b) { double f; UNUSEDPARAM(ctx); - if (!b) + if (!b) { return 0x7fffffff; + } /* log(a/b) is -32..32, so 2^26*32=2^31 covers the entire range of int32 */ f = (1 << 26) * log((double)a / b) / log(2); return (int32_t)myround(f); @@ -1242,8 +1317,9 @@ int32_t cli_bcapi_ilog2(struct cli_bc_ctx *ctx, uint32_t a, uint32_t b) int32_t cli_bcapi_ipow(struct cli_bc_ctx *ctx, int32_t a, int32_t b, int32_t c) { UNUSEDPARAM(ctx); - if (!a && b < 0) + if (!a && b < 0) { return 0x7fffffff; + } return (int32_t)myround(c * pow(a, b)); } @@ -1251,8 +1327,9 @@ uint32_t cli_bcapi_iexp(struct cli_bc_ctx *ctx, int32_t a, int32_t b, int32_t c) { double f; UNUSEDPARAM(ctx); - if (!b) + if (!b) { return 0x7fffffff; + } f = c * exp((double)a / b); return (uint32_t)myround(f); } @@ -1261,8 +1338,9 @@ int32_t cli_bcapi_isin(struct cli_bc_ctx *ctx, int32_t a, int32_t b, int32_t c) { double f; UNUSEDPARAM(ctx); - if (!b) + if (!b) { return 0x7fffffff; + } f = c * sin((double)a / b); return (int32_t)myround(f); } @@ -1271,8 +1349,9 @@ int32_t cli_bcapi_icos(struct cli_bc_ctx *ctx, int32_t a, int32_t b, int32_t c) { double f; UNUSEDPARAM(ctx); - if (!b) + if (!b) { return 0x7fffffff; + } f = c * cos((double)a / b); return (int32_t)myround(f); } @@ -1288,8 +1367,9 @@ int32_t cli_bcapi_memstr(struct cli_bc_ctx *ctx, const uint8_t *h, int32_t hs, cli_event_fastdata(EV, BCEV_MEM_1, h, hs); cli_event_fastdata(EV, BCEV_MEM_2, n, ns); s = (const uint8_t *)cli_memstr((const char *)h, hs, (const char *)n, ns); - if (!s) + if (!s) { return -1; + } return s - h; } @@ -1302,8 +1382,9 @@ int32_t cli_bcapi_hex2ui(struct cli_bc_ctx *ctx, uint32_t ah, uint32_t bh) in[0] = ah; in[1] = bh; - if (cli_hex2str_to((const char *)in, &result, 2) == -1) + if (cli_hex2str_to((const char *)in, &result, 2) == -1) { return -1; + } return result; } @@ -1313,16 +1394,24 @@ int32_t cli_bcapi_atoi(struct cli_bc_ctx *ctx, const uint8_t *str, int32_t len) const uint8_t *end = str + len; UNUSEDPARAM(ctx); - while (isspace(*str) && str < end) str++; - if (str == end) + while (isspace(*str) && str < end) { + str++; + } + if (str == end) { return -1; /* all spaces */ - if (*str == '+') str++; - if (str == end) + } + if (*str == '+') { + str++; + } + if (str == end) { return -1; /* all spaces and +*/ - if (*str == '-') + } + if (*str == '-') { return -1; /* only positive numbers */ - if (!isdigit(*str)) + } + if (!isdigit(*str)) { return -1; + } while (isdigit(*str) && str < end) { number = number * 10 + (*str - '0'); } @@ -1333,8 +1422,9 @@ uint32_t cli_bcapi_debug_print_str_start(struct cli_bc_ctx *ctx, const uint8_t * { UNUSEDPARAM(ctx); - if (!s || len <= 0) + if (!s || len <= 0) { return -1; + } cli_event_fastdata(EV, BCEV_DBG_STR, s, len); cli_dbgmsg("bytecode debug: %.*s", len, s); return 0; @@ -1344,10 +1434,12 @@ uint32_t cli_bcapi_debug_print_str_nonl(struct cli_bc_ctx *ctx, const uint8_t *s { UNUSEDPARAM(ctx); - if (!s || len <= 0) + if (!s || len <= 0) { return -1; - if (!cli_debug_flag) + } + if (!cli_debug_flag) { return 0; + } return fwrite(s, 1, len, stderr); } @@ -1360,16 +1452,18 @@ uint32_t cli_bcapi_entropy_buffer(struct cli_bc_ctx *ctx, uint8_t *s, int32_t le UNUSEDPARAM(ctx); - if (!s || len <= 0) + if (!s || len <= 0) { return -1; + } memset(probTable, 0, sizeof(probTable)); for (i = 0; i < (unsigned int)len; i++) { probTable[s[i]]++; } for (i = 0; i < 256; i++) { double p; - if (!probTable[i]) + if (!probTable[i]) { continue; + } p = (double)probTable[i] / len; entropy += -p * log(p) / log2; } @@ -1381,11 +1475,13 @@ int32_t cli_bcapi_map_new(struct cli_bc_ctx *ctx, int32_t keysize, int32_t value { unsigned n = ctx->nmaps + 1; struct cli_map *s; - if (!keysize) + if (!keysize) { return -1; + } s = cli_max_realloc(ctx->maps, sizeof(*ctx->maps) * n); - if (!s) + if (!s) { return -1; + } ctx->maps = s; ctx->nmaps = n; s = &s[n - 1]; @@ -1395,8 +1491,9 @@ int32_t cli_bcapi_map_new(struct cli_bc_ctx *ctx, int32_t keysize, int32_t value static struct cli_map *get_hashtab(struct cli_bc_ctx *ctx, int32_t id) { - if (id < 0 || (unsigned int)id >= ctx->nmaps || !ctx->maps) + if (id < 0 || (unsigned int)id >= ctx->nmaps || !ctx->maps) { return NULL; + } return &ctx->maps[id]; } @@ -1404,8 +1501,9 @@ int32_t cli_bcapi_map_addkey(struct cli_bc_ctx *ctx, const uint8_t *key, int32_t { cl_error_t ret; struct cli_map *s = get_hashtab(ctx, id); - if (!s) + if (!s) { return -1; + } ret = cli_map_addkey(s, key, keysize); switch (ret) { @@ -1427,8 +1525,9 @@ int32_t cli_bcapi_map_addkey(struct cli_bc_ctx *ctx, const uint8_t *key, int32_t int32_t cli_bcapi_map_setvalue(struct cli_bc_ctx *ctx, const uint8_t *value, int32_t valuesize, int32_t id) { struct cli_map *s = get_hashtab(ctx, id); - if (!s) + if (!s) { return -1; + } return cli_map_setvalue(s, value, valuesize) == CL_SUCCESS ? 0 : -1; } @@ -1436,8 +1535,9 @@ int32_t cli_bcapi_map_remove(struct cli_bc_ctx *ctx, const uint8_t *key, int32_t { cl_error_t ret; struct cli_map *s = get_hashtab(ctx, id); - if (!s) + if (!s) { return -1; + } ret = cli_map_removekey(s, key, keysize); switch (ret) { @@ -1460,8 +1560,9 @@ int32_t cli_bcapi_map_find(struct cli_bc_ctx *ctx, const uint8_t *key, int32_t k { cl_error_t ret; struct cli_map *s = get_hashtab(ctx, id); - if (!s) + if (!s) { return -1; + } ret = cli_map_find(s, key, keysize); switch (ret) { @@ -1483,26 +1584,30 @@ int32_t cli_bcapi_map_find(struct cli_bc_ctx *ctx, const uint8_t *key, int32_t k int32_t cli_bcapi_map_getvaluesize(struct cli_bc_ctx *ctx, int32_t id) { struct cli_map *s = get_hashtab(ctx, id); - if (!s) + if (!s) { return -1; + } return cli_map_getvalue_size(s); } uint8_t *cli_bcapi_map_getvalue(struct cli_bc_ctx *ctx, int32_t id, int32_t valuesize) { struct cli_map *s = get_hashtab(ctx, id); - if (!s) + if (!s) { return NULL; - if (cli_map_getvalue_size(s) != valuesize) + } + if (cli_map_getvalue_size(s) != valuesize) { return NULL; + } return (uint8_t *)cli_map_getvalue(s); } int32_t cli_bcapi_map_done(struct cli_bc_ctx *ctx, int32_t id) { struct cli_map *s = get_hashtab(ctx, id); - if (!s) + if (!s) { return -1; + } cli_map_delete(s); if ((unsigned int)id == ctx->nmaps - 1) { ctx->nmaps--; @@ -1511,8 +1616,9 @@ int32_t cli_bcapi_map_done(struct cli_bc_ctx *ctx, int32_t id) ctx->maps = NULL; } else { s = cli_max_realloc(ctx->maps, ctx->nmaps * (sizeof(*s))); - if (s) + if (s) { ctx->maps = s; + } } } return 0; @@ -1535,67 +1641,94 @@ uint32_t cli_bcapi_engine_scan_options(struct cli_bc_ctx *ctx) cli_ctx *cctx = (cli_ctx *)ctx->ctx; uint32_t options = CL_SCAN_RAW; - if (cctx->options->general & CL_SCAN_GENERAL_ALLMATCHES) + if (cctx->options->general & CL_SCAN_GENERAL_ALLMATCHES) { options |= CL_SCAN_ALLMATCHES; - if (cctx->options->general & CL_SCAN_GENERAL_HEURISTICS) + } + if (cctx->options->general & CL_SCAN_GENERAL_HEURISTICS) { options |= CL_SCAN_ALGORITHMIC; - if (cctx->options->general & CL_SCAN_GENERAL_COLLECT_METADATA) + } + if (cctx->options->general & CL_SCAN_GENERAL_COLLECT_METADATA) { options |= CL_SCAN_FILE_PROPERTIES; - if (cctx->options->general & CL_SCAN_GENERAL_HEURISTIC_PRECEDENCE) + } + if (cctx->options->general & CL_SCAN_GENERAL_HEURISTIC_PRECEDENCE) { options |= CL_SCAN_HEURISTIC_PRECEDENCE; + } - if (cctx->options->parse & CL_SCAN_PARSE_ARCHIVE) + if (cctx->options->parse & CL_SCAN_PARSE_ARCHIVE) { options |= CL_SCAN_ARCHIVE; - if (cctx->options->parse & CL_SCAN_PARSE_ELF) + } + if (cctx->options->parse & CL_SCAN_PARSE_ELF) { options |= CL_SCAN_ELF; - if (cctx->options->parse & CL_SCAN_PARSE_PDF) + } + if (cctx->options->parse & CL_SCAN_PARSE_PDF) { options |= CL_SCAN_PDF; - if (cctx->options->parse & CL_SCAN_PARSE_SWF) + } + if (cctx->options->parse & CL_SCAN_PARSE_SWF) { options |= CL_SCAN_SWF; - if (cctx->options->parse & CL_SCAN_PARSE_HWP3) + } + if (cctx->options->parse & CL_SCAN_PARSE_HWP3) { options |= CL_SCAN_HWP3; - if (cctx->options->parse & CL_SCAN_PARSE_XMLDOCS) + } + if (cctx->options->parse & CL_SCAN_PARSE_XMLDOCS) { options |= CL_SCAN_XMLDOCS; - if (cctx->options->parse & CL_SCAN_PARSE_MAIL) + } + if (cctx->options->parse & CL_SCAN_PARSE_MAIL) { options |= CL_SCAN_MAIL; - if (cctx->options->parse & CL_SCAN_PARSE_OLE2) + } + if (cctx->options->parse & CL_SCAN_PARSE_OLE2) { options |= CL_SCAN_OLE2; - if (cctx->options->parse & CL_SCAN_PARSE_HTML) + } + if (cctx->options->parse & CL_SCAN_PARSE_HTML) { options |= CL_SCAN_HTML; - if (cctx->options->parse & CL_SCAN_PARSE_PE) + } + if (cctx->options->parse & CL_SCAN_PARSE_PE) { options |= CL_SCAN_PE; + } // if (cctx->options->parse & CL_SCAN_MAIL_URL) // options |= CL_SCAN_MAILURL; /* deprecated circa 2009 */ - if (cctx->options->heuristic & CL_SCAN_HEURISTIC_BROKEN) + if (cctx->options->heuristic & CL_SCAN_HEURISTIC_BROKEN) { options |= CL_SCAN_BLOCKBROKEN; - if (cctx->options->heuristic & CL_SCAN_HEURISTIC_EXCEEDS_MAX) + } + if (cctx->options->heuristic & CL_SCAN_HEURISTIC_EXCEEDS_MAX) { options |= CL_SCAN_BLOCKMAX; - if (cctx->options->heuristic & CL_SCAN_HEURISTIC_PHISHING_SSL_MISMATCH) + } + if (cctx->options->heuristic & CL_SCAN_HEURISTIC_PHISHING_SSL_MISMATCH) { options |= CL_SCAN_PHISHING_BLOCKSSL; - if (cctx->options->heuristic & CL_SCAN_HEURISTIC_PHISHING_CLOAK) + } + if (cctx->options->heuristic & CL_SCAN_HEURISTIC_PHISHING_CLOAK) { options |= CL_SCAN_PHISHING_BLOCKCLOAK; - if (cctx->options->heuristic & CL_SCAN_HEURISTIC_MACROS) + } + if (cctx->options->heuristic & CL_SCAN_HEURISTIC_MACROS) { options |= CL_SCAN_BLOCKMACROS; + } if ((cctx->options->heuristic & CL_SCAN_HEURISTIC_ENCRYPTED_ARCHIVE) || - (cctx->options->heuristic & CL_SCAN_HEURISTIC_ENCRYPTED_DOC)) + (cctx->options->heuristic & CL_SCAN_HEURISTIC_ENCRYPTED_DOC)) { options |= CL_SCAN_BLOCKENCRYPTED; - if (cctx->options->heuristic & CL_SCAN_HEURISTIC_PARTITION_INTXN) + } + if (cctx->options->heuristic & CL_SCAN_HEURISTIC_PARTITION_INTXN) { options |= CL_SCAN_PARTITION_INTXN; - if (cctx->options->heuristic & CL_SCAN_HEURISTIC_STRUCTURED) + } + if (cctx->options->heuristic & CL_SCAN_HEURISTIC_STRUCTURED) { options |= CL_SCAN_STRUCTURED; - if (cctx->options->heuristic & CL_SCAN_HEURISTIC_STRUCTURED_SSN_NORMAL) + } + if (cctx->options->heuristic & CL_SCAN_HEURISTIC_STRUCTURED_SSN_NORMAL) { options |= CL_SCAN_STRUCTURED_SSN_NORMAL; - if (cctx->options->heuristic & CL_SCAN_HEURISTIC_STRUCTURED_SSN_STRIPPED) + } + if (cctx->options->heuristic & CL_SCAN_HEURISTIC_STRUCTURED_SSN_STRIPPED) { options |= CL_SCAN_STRUCTURED_SSN_STRIPPED; + } - if (cctx->options->mail & CL_SCAN_MAIL_PARTIAL_MESSAGE) + if (cctx->options->mail & CL_SCAN_MAIL_PARTIAL_MESSAGE) { options |= CL_SCAN_PARTIAL_MESSAGE; + } - if (cctx->options->dev & CL_SCAN_DEV_COLLECT_SHA) + if (cctx->options->dev & CL_SCAN_DEV_COLLECT_SHA) { options |= CL_SCAN_INTERNAL_COLLECT_SHA; - if (cctx->options->dev & CL_SCAN_DEV_COLLECT_PERFORMANCE_INFO) + } + if (cctx->options->dev & CL_SCAN_DEV_COLLECT_PERFORMANCE_INFO) { options |= CL_SCAN_PERFORMANCE_INFO; + } return options; } @@ -1704,8 +1837,9 @@ uint32_t cli_bcapi_engine_scan_options_ex(struct cli_bc_ctx *ctx, const uint8_t done: - if (NULL != option_name_l) + if (NULL != option_name_l) { free(option_name_l); + } return result; } @@ -1718,8 +1852,9 @@ uint32_t cli_bcapi_engine_db_options(struct cli_bc_ctx *ctx) int32_t cli_bcapi_extract_set_container(struct cli_bc_ctx *ctx, uint32_t ftype) { - if (ftype > CL_TYPE_IGNORED) + if (ftype > CL_TYPE_IGNORED) { return -1; + } ctx->containertype = ftype; return 0; } @@ -1794,12 +1929,14 @@ uint32_t cli_bcapi_disable_bytecode_if(struct cli_bc_ctx *ctx, const int8_t *rea cli_dbgmsg("Bytecode must be BC_STARTUP to call disable_bytecode_if\n"); return -1; } - if (!cond) + if (!cond) { return ctx->bytecode_disable_status; - if (*reason == '^') + } + if (*reason == '^') { cli_warnmsg("Bytecode: disabling completely because %s\n", reason + 1); - else + } else { cli_dbgmsg("Bytecode: disabling completely because %s\n", reason); + } ctx->bytecode_disable_status = 2; return ctx->bytecode_disable_status; } @@ -1811,14 +1948,17 @@ uint32_t cli_bcapi_disable_jit_if(struct cli_bc_ctx *ctx, const int8_t *reason, cli_dbgmsg("Bytecode must be BC_STARTUP to call disable_jit_if\n"); return -1; } - if (!cond) + if (!cond) { return ctx->bytecode_disable_status; - if (*reason == '^') + } + if (*reason == '^') { cli_warnmsg("Bytecode: disabling JIT because %s\n", reason + 1); - else + } else { cli_dbgmsg("Bytecode: disabling JIT because %s\n", reason); - if (ctx->bytecode_disable_status != 2) /* no reenabling */ + } + if (ctx->bytecode_disable_status != 2) { /* no reenabling */ ctx->bytecode_disable_status = 1; + } return ctx->bytecode_disable_status; } @@ -1834,22 +1974,30 @@ int32_t cli_bcapi_version_compare(struct cli_bc_ctx *ctx, const uint8_t *lhs, ui i++; j++; } - if (i == lhs_len && j == rhs_len) + if (i == lhs_len && j == rhs_len) { return 0; - if (i == lhs_len) + } + if (i == lhs_len) { return -1; - if (j == rhs_len) + } + if (j == rhs_len) { return 1; - if (!isdigit(lhs[i]) || !isdigit(rhs[j])) + } + if (!isdigit(lhs[i]) || !isdigit(rhs[j])) { return lhs[i] < rhs[j] ? -1 : 1; - while (isdigit(lhs[i]) && i < lhs_len) + } + while (isdigit(lhs[i]) && i < lhs_len) { li = 10 * li + (lhs[i++] - '0'); - while (isdigit(rhs[j]) && j < rhs_len) + } + while (isdigit(rhs[j]) && j < rhs_len) { ri = 10 * ri + (rhs[j++] - '0'); - if (li < ri) + } + if (li < ri) { return -1; - if (li > ri) + } + if (li > ri) { return 1; + } } while (1); } @@ -1858,8 +2006,9 @@ static int check_bits(uint32_t query, uint32_t value, uint8_t shift, uint8_t mas uint8_t q = (query >> shift) & mask; uint8_t v = (value >> shift) & mask; /* q == mask -> ANY */ - if (q == v || q == mask) + if (q == v || q == mask) { return 1; + } return 0; } @@ -1888,22 +2037,25 @@ uint32_t cli_bcapi_check_platform(struct cli_bc_ctx *ctx, uint32_t a, uint32_t b int32_t cli_bcapi_pdf_get_obj_num(struct cli_bc_ctx *ctx) { - if (!ctx->pdf_phase) + if (!ctx->pdf_phase) { return -1; + } return ctx->pdf_nobjs; } int32_t cli_bcapi_pdf_get_flags(struct cli_bc_ctx *ctx) { - if (!ctx->pdf_phase) + if (!ctx->pdf_phase) { return -1; + } return *ctx->pdf_flags; } int32_t cli_bcapi_pdf_set_flags(struct cli_bc_ctx *ctx, int32_t flags) { - if (!ctx->pdf_phase) + if (!ctx->pdf_phase) { return -1; + } cli_dbgmsg("cli_pdf: bytecode set_flags %08x -> %08x\n", *ctx->pdf_flags, flags); @@ -1914,11 +2066,13 @@ int32_t cli_bcapi_pdf_set_flags(struct cli_bc_ctx *ctx, int32_t flags) int32_t cli_bcapi_pdf_lookupobj(struct cli_bc_ctx *ctx, uint32_t objid) { unsigned i; - if (!ctx->pdf_phase) + if (!ctx->pdf_phase) { return -1; + } for (i = 0; i < ctx->pdf_nobjs; i++) { - if (ctx->pdf_objs[i]->id == objid) + if (ctx->pdf_objs[i]->id == objid) { return i; + } } return -1; } @@ -1928,42 +2082,48 @@ uint32_t cli_bcapi_pdf_getobjsize(struct cli_bc_ctx *ctx, int32_t objidx) if (!ctx->pdf_phase || (uint32_t)objidx >= ctx->pdf_nobjs || ctx->pdf_phase == PDF_PHASE_POSTDUMP /* map is obj itself, no access to pdf anymore */ - ) + ) { return 0; - if ((uint32_t)(objidx + 1) == ctx->pdf_nobjs) + } + if ((uint32_t)(objidx + 1) == ctx->pdf_nobjs) { return ctx->pdf_size - ctx->pdf_objs[objidx]->start; + } return ctx->pdf_objs[objidx + 1]->start - ctx->pdf_objs[objidx]->start - 4; } const uint8_t *cli_bcapi_pdf_getobj(struct cli_bc_ctx *ctx, int32_t objidx, uint32_t amount) { uint32_t size = cli_bcapi_pdf_getobjsize(ctx, objidx); - if (amount > size) + if (amount > size) { return NULL; + } return fmap_need_off(ctx->fmap, ctx->pdf_objs[objidx]->start, amount); } int32_t cli_bcapi_pdf_getobjid(struct cli_bc_ctx *ctx, int32_t objidx) { if (!ctx->pdf_phase || - (uint32_t)objidx >= ctx->pdf_nobjs) + (uint32_t)objidx >= ctx->pdf_nobjs) { return -1; + } return ctx->pdf_objs[objidx]->id; } int32_t cli_bcapi_pdf_getobjflags(struct cli_bc_ctx *ctx, int32_t objidx) { if (!ctx->pdf_phase || - (uint32_t)objidx >= ctx->pdf_nobjs) + (uint32_t)objidx >= ctx->pdf_nobjs) { return -1; + } return ctx->pdf_objs[objidx]->flags; } int32_t cli_bcapi_pdf_setobjflags(struct cli_bc_ctx *ctx, int32_t objidx, int32_t flags) { if (!ctx->pdf_phase || - (uint32_t)objidx >= ctx->pdf_nobjs) + (uint32_t)objidx >= ctx->pdf_nobjs) { return -1; + } cli_dbgmsg("cli_pdf: bytecode setobjflags %08x -> %08x\n", ctx->pdf_objs[objidx]->flags, flags); @@ -1974,8 +2134,9 @@ int32_t cli_bcapi_pdf_setobjflags(struct cli_bc_ctx *ctx, int32_t objidx, int32_ int32_t cli_bcapi_pdf_get_offset(struct cli_bc_ctx *ctx, int32_t objidx) { if (!ctx->pdf_phase || - (uint32_t)objidx >= ctx->pdf_nobjs) + (uint32_t)objidx >= ctx->pdf_nobjs) { return -1; + } return ctx->pdf_startoff + ctx->pdf_objs[objidx]->start; } @@ -1986,8 +2147,9 @@ int32_t cli_bcapi_pdf_get_phase(struct cli_bc_ctx *ctx) int32_t cli_bcapi_pdf_get_dumpedobjid(struct cli_bc_ctx *ctx) { - if (ctx->pdf_phase != PDF_PHASE_POSTDUMP) + if (ctx->pdf_phase != PDF_PHASE_POSTDUMP) { return -1; + } return ctx->pdf_dumpedid; } @@ -2059,11 +2221,13 @@ int32_t cli_bcapi_json_get_object(struct cli_bc_ctx *ctx, const int8_t *name, in n = ctx->njsonobjs + 1; jobj = jobjs[objid]; - if (!jobj) /* shouldn't be possible */ + if (!jobj) { /* shouldn't be possible */ return -1; + } namep = (char *)cli_max_malloc(sizeof(char) * (name_len + 1)); - if (!namep) + if (!namep) { return -1; + } strncpy(namep, (char *)name, name_len); namep[name_len] = '\0'; @@ -2157,8 +2321,9 @@ int32_t cli_bcapi_json_get_array_idx(struct cli_bc_ctx *ctx, int32_t idx, int32_ } jarr = jobjs[objid]; - if (!jarr) /* shouldn't be possible */ + if (!jarr) { /* shouldn't be possible */ return -1; + } type = json_object_get_type(jarr); if (type != json_type_array) { @@ -2205,8 +2370,9 @@ int32_t cli_bcapi_json_get_string_length(struct cli_bc_ctx *ctx, int32_t objid) } jobj = jobjs[objid]; - if (!jobj) /* shouldn't be possible */ + if (!jobj) { /* shouldn't be possible */ return -1; + } type = json_object_get_type(jobj); if (type != json_type_string) { @@ -2235,8 +2401,9 @@ int32_t cli_bcapi_json_get_string(struct cli_bc_ctx *ctx, int8_t *str, int32_t s } jobj = jobjs[objid]; - if (!jobj) /* shouldn't be possible */ + if (!jobj) { /* shouldn't be possible */ return -1; + } type = json_object_get_type(jobj); if (type != json_type_string) { diff --git a/libclamav/bytecode_detect.c b/libclamav/bytecode_detect.c index f645c1364b..5579d4d244 100644 --- a/libclamav/bytecode_detect.c +++ b/libclamav/bytecode_detect.c @@ -88,13 +88,15 @@ static int detect_PaX(void) char line[128]; int pax = 0; FILE *f = fopen("/proc/self/status", "r"); - if (!f) + if (!f) { return 0; + } while (fgets(line, sizeof(line), f)) { if (!memcmp(line, "PaX:", 4)) { pax = 1; - if (!strchr(line, 'm')) + if (!strchr(line, 'm')) { pax = 2; + } break; } } @@ -110,11 +112,13 @@ static int detect_SELinux(void) FILE *f = fopen("/proc/filesystems", "r"); if (!f) { f = fopen("/selinux/enforce", "r"); - if (!f && errno == EACCES) + if (!f && errno == EACCES) { return 2; + } if (f) { - if (fscanf(f, "%d", &enforce) == 1) + if (fscanf(f, "%d", &enforce) == 1) { selinux = 2; + } fclose(f); } return selinux; @@ -126,16 +130,19 @@ static int detect_SELinux(void) } } fclose(f); - if (!selinux) + if (!selinux) { return 0; + } f = fopen("/selinux/enforce", "r"); if (f) { if (fscanf(f, "%d", &enforce) == 1) { - if (enforce == 1) + if (enforce == 1) { selinux = 2; - if (enforce == -1) + } + if (enforce == -1) { selinux = 0; + } } fclose(f); } @@ -192,9 +199,18 @@ void cli_detect_environment(struct cli_environment *env) /* -- Detect arch -- */ CHECK_ARCH(i386); else CHECK_ARCH(x86_64); - else if (!strcmp(TARGET_ARCH_TYPE, "amd64")) env->arch = arch_x86_64; - else if (!strcmp(TARGET_ARCH_TYPE, "AMD64")) env->arch = arch_x86_64; - else if (!strcmp(TARGET_ARCH_TYPE, "ppc")) env->arch = arch_ppc32; /* llvm will fix ppc64 */ + else if (!strcmp(TARGET_ARCH_TYPE, "amd64")) + { + env->arch = arch_x86_64; + } + else if (!strcmp(TARGET_ARCH_TYPE, "AMD64")) + { + env->arch = arch_x86_64; + } + else if (!strcmp(TARGET_ARCH_TYPE, "ppc")) + { + env->arch = arch_ppc32; /* llvm will fix ppc64 */ + } else CHECK_ARCH(arm); else CHECK_ARCH(sparc); else CHECK_ARCH(sparc64); diff --git a/libclamav/bytecode_nojit.c b/libclamav/bytecode_nojit.c index 96cfdb82ed..b2bb2d6521 100644 --- a/libclamav/bytecode_nojit.c +++ b/libclamav/bytecode_nojit.c @@ -33,8 +33,9 @@ cl_error_t cli_bytecode_prepare_jit(struct cli_all_bc *bcs) { unsigned i; for (i = 0; i < bcs->count; i++) { - if (bcs->all_bcs[i].state == bc_skip) + if (bcs->all_bcs[i].state == bc_skip) { continue; + } if (bcs->all_bcs[i].state != bc_loaded && bcs->all_bcs[i].kind != BC_STARTUP) { cli_warnmsg("Cannot prepare for JIT, because it has already been converted to interpreter\n"); diff --git a/libclamav/bytecode_vm.c b/libclamav/bytecode_vm.c index 706ad397e5..a00d4f03f7 100644 --- a/libclamav/bytecode_vm.c +++ b/libclamav/bytecode_vm.c @@ -241,8 +241,9 @@ static always_inline struct stack_entry *allocate_stack(struct stack *stack, { char *values; struct stack_entry *entry = cli_stack_alloc(stack, sizeof(*entry) + sizeof(*values) * func->numBytes); - if (!entry) + if (!entry) { return NULL; + } entry->prev = prev; entry->func = func_old; entry->ret = ret; @@ -598,8 +599,9 @@ static inline int64_t ptr_register_stack(struct ptr_infos *infos, unsigned n = infos->nstacks + 1; struct ptr_info *sinfos = cli_safer_realloc(infos->stack_infos, sizeof(*sinfos) * n); - if (!sinfos) + if (!sinfos) { return 0; + } infos->stack_infos = sinfos; infos->nstacks = n; sinfos = &sinfos[n - 1]; @@ -614,15 +616,17 @@ static inline int64_t ptr_register_glob_fixedid(struct ptr_infos *infos, struct ptr_info *sinfos; if (n > infos->nglobs) { sinfos = cli_safer_realloc(infos->glob_infos, sizeof(*sinfos) * n); - if (!sinfos) + if (!sinfos) { return 0; + } memset(sinfos + infos->nglobs, 0, (n - infos->nglobs) * sizeof(*sinfos)); infos->glob_infos = sinfos; infos->nglobs = n; } sinfos = &infos->glob_infos[n - 1]; - if (!values) + if (!values) { size = 0; + } sinfos->base = values; sinfos->size = size; cli_dbgmsg("bytecode: registered ctx variable at %p (+%u) id %u\n", values, @@ -633,8 +637,9 @@ static inline int64_t ptr_register_glob_fixedid(struct ptr_infos *infos, static inline int64_t ptr_register_glob(struct ptr_infos *infos, void *values, uint32_t size) { - if (!values) + if (!values) { return 0; + } return ptr_register_glob_fixedid(infos, values, size, infos->nglobs + 1); } @@ -684,10 +689,12 @@ static always_inline int check_sdivops(int64_t op0, int64_t op1) static unsigned globaltypesize(uint16_t id) { const struct cli_bc_type *ty; - if (id <= 64) + if (id <= 64) { return (id + 7) / 8; - if (id < 69) + } + if (id < 69) { return 8; /* ptr */ + } ty = &cli_apicall_types[id - 69]; switch (ty->kind) { case DArrayType: @@ -695,8 +702,9 @@ static unsigned globaltypesize(uint16_t id) case DStructType: case DPackedStructType: { unsigned i, s = 0; - for (i = 0; i < ty->numElements; i++) + for (i = 0; i < ty->numElements; i++) { s += globaltypesize(ty->containedTypes[i]); + } return s; } default: @@ -735,8 +743,9 @@ cl_error_t cli_vm_execute(const struct cli_bc *bc, struct cli_bc_ctx *ctx, const uint32_t size; const struct cli_apiglobal *g = &cli_globals[i]; void **apiglobal = (void **)(((char *)ctx) + g->offset); - if (!apiglobal) + if (!apiglobal) { continue; + } apiptr = *apiglobal; size = globaltypesize(g->type); ptr_register_glob_fixedid(&ptrinfos, apiptr, size, g->globalid - _FIRST_GLOBAL + 1); @@ -1262,24 +1271,27 @@ cl_error_t cli_vm_execute(const struct cli_bc *bc, struct cli_bc_ctx *ctx, const DEFINE_OP(OP_BC_PTRDIFF32) { int64_t ptr1, ptr2; - if (BINOP(0) & 0x40000000) + if (BINOP(0) & 0x40000000) { ptr1 = ptr_compose(stackid, BINOP(0) & 0xbfffffff); - else + } else { READ64(ptr1, BINOP(0)); - if (BINOP(1) & 0x40000000) + } + if (BINOP(1) & 0x40000000) { ptr2 = ptr_compose(stackid, BINOP(1) & 0xbfffffff); - else + } else { READ64(ptr2, BINOP(1)); + } WRITE32(inst->dest, ptr_diff32(ptr1, ptr2)); break; } DEFINE_OP(OP_BC_PTRTOINT64) { int64_t ptr; - if (inst->u.unaryop & 0x40000000) + if (inst->u.unaryop & 0x40000000) { ptr = ptr_compose(stackid, inst->u.unaryop & 0xbfffffff); - else + } else { READ64(ptr, BINOP(0)); + } WRITE64(inst->dest, ptr); break; } diff --git a/libclamav/cache.c b/libclamav/cache.c index 60bfeb9360..0cdd12b41a 100644 --- a/libclamav/cache.c +++ b/libclamav/cache.c @@ -92,8 +92,9 @@ static int cacheset_init(struct cache_set *cs, mpool_t *mempool, uint32_t nodes_ cs->data = MPOOL_CALLOC(mempool, nodes_per_tree, sizeof(*cs->data)); cs->root = NULL; - if (!cs->data) + if (!cs->data) { return 1; + } for (i = 1; i < nodes_per_tree; i++) { cs->data[i - 1].next = &cs->data[i]; @@ -120,12 +121,24 @@ static inline void cacheset_destroy(struct cache_set *cs, mpool_t *mempool) /* The left/right chooser for the splay tree */ static inline int cmp(int64_t *a, ssize_t sa, int64_t *b, ssize_t sb) { - if (a[1] < b[1]) return -1; - if (a[1] > b[1]) return 1; - if (a[0] < b[0]) return -1; - if (a[0] > b[0]) return 1; - if (sa < sb) return -1; - if (sa > sb) return 1; + if (a[1] < b[1]) { + return -1; + } + if (a[1] > b[1]) { + return 1; + } + if (a[0] < b[0]) { + return -1; + } + if (a[0] > b[0]) { + return 1; + } + if (sa < sb) { + return -1; + } + if (sa > sb) { + return 1; + } return 0; } @@ -270,36 +283,49 @@ static int splay(int64_t *md5, size_t len, struct cache_set *cs) struct node next = {{0, 0}, NULL, NULL, NULL, NULL, NULL, 0, 0}, *right = &next, *left = &next, *temp, *root = cs->root; int comp, found = 0; - if (!root) + if (!root) { return 0; + } while (1) { comp = cmp(md5, len, root->digest, root->size); if (comp < 0) { - if (!root->left) break; + if (!root->left) { + break; + } if (cmp(md5, len, root->left->digest, root->left->size) < 0) { temp = root->left; root->left = temp->right; - if (temp->right) temp->right->up = root; + if (temp->right) { + temp->right->up = root; + } temp->right = root; root->up = temp; root = temp; - if (!root->left) break; + if (!root->left) { + break; + } } right->left = root; root->up = right; right = root; root = root->left; } else if (comp > 0) { - if (!root->right) break; + if (!root->right) { + break; + } if (cmp(md5, len, root->right->digest, root->right->size) > 0) { temp = root->right; root->right = temp->left; - if (temp->left) temp->left->up = root; + if (temp->left) { + temp->left->up = root; + } temp->left = root; root->up = temp; root = temp; - if (!root->right) break; + if (!root->right) { + break; + } } left->right = root; root->up = left; @@ -312,13 +338,21 @@ static int splay(int64_t *md5, size_t len, struct cache_set *cs) } left->right = root->left; - if (root->left) root->left->up = left; + if (root->left) { + root->left->up = left; + } right->left = root->right; - if (root->right) root->right->up = right; + if (root->right) { + root->right->up = right; + } root->left = next.right; - if (next.right) next.right->up = root; + if (next.right) { + next.right->up = root; + } root->right = next.left; - if (next.left) next.left->up = root; + if (next.left) { + next.left->up = root; + } root->up = NULL; cs->root = root; return found; @@ -337,10 +371,11 @@ static inline int cacheset_lookup(struct cache_set *cs, unsigned char *md5, size printchain("before", cs); #endif if (q) { - if (o) + if (o) { o->next = q; - else + } else { cs->first = q; + } q->prev = o; cs->last->next = p; p->prev = cs->last; @@ -358,8 +393,9 @@ static inline int cacheset_lookup(struct cache_set *cs, unsigned char *md5, size // ├── file1 -> file2 -> file3 -> file4 -> file5 // └── file3 -> file4 -> file5 // See: https://bugzilla.clamav.net/show_bug.cgi?id=1856 - if (recursion_level >= p->minrec) + if (recursion_level >= p->minrec) { return 1; + } } return 0; } @@ -374,8 +410,9 @@ static inline const char *cacheset_add(struct cache_set *cs, unsigned char *md5, memcpy(hash, md5, 16); if (splay(hash, size, cs)) { - if (cs->root->minrec > recursion_level) + if (cs->root->minrec > recursion_level) { cs->root->minrec = recursion_level; + } return NULL; /* Already there */ } @@ -386,8 +423,9 @@ static inline const char *cacheset_add(struct cache_set *cs, unsigned char *md5, newnode = cs->first; while (newnode) { - if (!newnode->right && !newnode->left) + if (!newnode->right && !newnode->left) { break; + } if (newnode->next) { if (newnode == newnode->next) { return "cacheset_add: cache chain in a bad state"; @@ -401,17 +439,21 @@ static inline const char *cacheset_add(struct cache_set *cs, unsigned char *md5, return "cacheset_add: tree has got no end nodes"; } if (newnode->up) { - if (newnode->up->left == newnode) + if (newnode->up->left == newnode) { newnode->up->left = NULL; - else + } else { newnode->up->right = NULL; + } } - if (newnode->prev) + if (newnode->prev) { newnode->prev->next = newnode->next; - if (newnode->next) + } + if (newnode->next) { newnode->next->prev = newnode->prev; - if (cs->first == newnode) + } + if (cs->first == newnode) { cs->first = newnode->next; + } newnode->prev = cs->last; newnode->next = NULL; @@ -436,8 +478,12 @@ static inline const char *cacheset_add(struct cache_set *cs, unsigned char *md5, newnode->left = cs->root; cs->root->right = NULL; } - if (newnode->left) newnode->left->up = newnode; - if (newnode->right) newnode->right->up = newnode; + if (newnode->left) { + newnode->left->up = newnode; + } + if (newnode->right) { + newnode->right->up = newnode; + } } newnode->digest[0] = hash[0]; newnode->digest[1] = hash[1]; @@ -477,8 +523,9 @@ static inline void cacheset_remove(struct cache_set *cs, unsigned char *md5, siz if (targetnode->left == NULL) { /* At left edge so prune */ cs->root = targetnode->right; - if (cs->root) + if (cs->root) { cs->root->up = NULL; + } } else { /* new root will come from leftside tree */ cs->root = targetnode->left; @@ -489,8 +536,9 @@ static inline void cacheset_remove(struct cache_set *cs, unsigned char *md5, siz if (targetnode->right) { /* reattach right tree to clean right-side attach point */ reattachnode = cs->root; - while (reattachnode->right) + while (reattachnode->right) { reattachnode = reattachnode->right; /* shouldn't happen, but safer in case of dupe */ + } reattachnode->right = targetnode->right; targetnode->right->up = reattachnode; } @@ -503,18 +551,22 @@ static inline void cacheset_remove(struct cache_set *cs, unsigned char *md5, siz targetnode->right = NULL; /* Tree is fixed, so now fix chain around targetnode */ - if (targetnode->prev) + if (targetnode->prev) { targetnode->prev->next = targetnode->next; - if (targetnode->next) + } + if (targetnode->next) { targetnode->next->prev = targetnode->prev; - if (cs->last == targetnode) + } + if (cs->last == targetnode) { cs->last = targetnode->prev; + } /* Put targetnode at front of chain, if not there already */ if (cs->first != targetnode) { targetnode->next = cs->first; - if (cs->first) + if (cs->first) { cs->first->prev = targetnode; + } cs->first = targetnode; } targetnode->prev = NULL; @@ -594,16 +646,24 @@ int clean_cache_init(struct cl_engine *engine) #ifdef CL_THREAD_SAFE if (pthread_mutex_init(&cache[i].mutex, NULL)) { cli_errmsg("clean_cache_init: mutex init fail\n"); - for (j = 0; j < i; j++) cacheset_destroy(&cache[j].cacheset, engine->mempool); - for (j = 0; j < i; j++) pthread_mutex_destroy(&cache[j].mutex); + for (j = 0; j < i; j++) { + cacheset_destroy(&cache[j].cacheset, engine->mempool); + } + for (j = 0; j < i; j++) { + pthread_mutex_destroy(&cache[j].mutex); + } MPOOL_FREE(engine->mempool, cache); return 1; } #endif if (cacheset_init(&cache[i].cacheset, engine->mempool, cache->nodes_per_tree)) { - for (j = 0; j < i; j++) cacheset_destroy(&cache[j].cacheset, engine->mempool); + for (j = 0; j < i; j++) { + cacheset_destroy(&cache[j].cacheset, engine->mempool); + } #ifdef CL_THREAD_SAFE - for (j = 0; j <= i; j++) pthread_mutex_destroy(&cache[j].mutex); + for (j = 0; j <= i; j++) { + pthread_mutex_destroy(&cache[j].mutex); + } #endif MPOOL_FREE(engine->mempool, cache); return 1; @@ -618,8 +678,9 @@ void clean_cache_destroy(struct cl_engine *engine) struct CACHE *cache; unsigned int i; - if (!engine || !(cache = engine->cache)) + if (!engine || !(cache = engine->cache)) { return; + } if (engine->engine_options & ENGINE_OPTIONS_DISABLE_CACHE) { return; @@ -642,8 +703,9 @@ void clean_cache_add(unsigned char *md5, size_t size, cli_ctx *ctx) uint32_t level; struct CACHE *c; - if (!ctx || !ctx->engine || !ctx->engine->cache) + if (!ctx || !ctx->engine || !ctx->engine->cache) { return; + } if (ctx->engine->engine_options & ENGINE_OPTIONS_DISABLE_CACHE) { cli_dbgmsg("clean_cache_add: Caching disabled. Not adding sample to cache.\n"); @@ -706,8 +768,9 @@ void clean_cache_remove(unsigned char *md5, size_t size, const struct cl_engine unsigned int key = 0; struct CACHE *c; - if (!engine || !engine->cache) + if (!engine || !engine->cache) { return; + } if (engine->engine_options & ENGINE_OPTIONS_DISABLE_CACHE) { cli_dbgmsg("clean_cache_remove: Caching disabled.\n"); @@ -742,8 +805,9 @@ cl_error_t clean_cache_check(unsigned char *md5, size_t size, cli_ctx *ctx) { int ret; - if (!ctx || !ctx->engine || !ctx->engine->cache) + if (!ctx || !ctx->engine || !ctx->engine->cache) { return CL_VIRUS; + } if (SCAN_COLLECT_METADATA) { // Don't cache when using the "collect metadata" feature. diff --git a/libclamav/conv.c b/libclamav/conv.c index 5947660b5d..41564897ec 100644 --- a/libclamav/conv.c +++ b/libclamav/conv.c @@ -51,11 +51,13 @@ static size_t base64_len(const char *data, size_t len) int padding = 0; size_t i; - if (!len) + if (!len) { return 0; + } - for (i = len - 1; i > 0 && data[i] == '='; i--) + for (i = len - 1; i > 0 && data[i] == '='; i--) { padding++; + } return (size_t)((3 * len) / 4 - padding); } @@ -73,13 +75,15 @@ void *cl_base64_decode(char *data, size_t len, void *obuf, size_t *olen, int one void *buf; buf = (obuf) ? obuf : malloc(base64_len(data, len) + 1); - if (!(buf)) + if (!(buf)) { return NULL; + } b64 = BIO_new(BIO_f_base64()); if (!(b64)) { - if (!(obuf)) + if (!(obuf)) { free(buf); + } return NULL; } @@ -87,15 +91,17 @@ void *cl_base64_decode(char *data, size_t len, void *obuf, size_t *olen, int one bio = BIO_new_mem_buf(data, len); if (!(bio)) { BIO_free(b64); - if (!(obuf)) + if (!(obuf)) { free(buf); + } return NULL; } bio = BIO_push(b64, bio); - if (oneline) + if (oneline) { BIO_set_flags(bio, BIO_FLAGS_BASE64_NO_NL); + } *olen = BIO_read(bio, buf, base64_len(data, len)); @@ -116,8 +122,9 @@ char *cl_base64_encode(void *data, size_t len) size_t elen; b64 = BIO_new(BIO_f_base64()); - if (!(b64)) + if (!(b64)) { return NULL; + } bio = BIO_new(BIO_s_mem()); if (!(bio)) { BIO_free(b64); diff --git a/libclamav/cpio.c b/libclamav/cpio.c index fc0950c6eb..638bff0c5c 100644 --- a/libclamav/cpio.c +++ b/libclamav/cpio.c @@ -89,8 +89,9 @@ struct cpio_hdr_newc { static void sanitname(char *name) { while (*name) { - if (!isascii(*name) || strchr("%\\\t\n\r", *name)) + if (!isascii(*name) || strchr("%\\\t\n\r", *name)) { *name = '_'; + } name++; } } @@ -156,8 +157,9 @@ cl_error_t cli_scancpio_old(cli_ctx *ctx) } filesize = (uint32_t)((uint32_t)EC16(hdr_old.filesize[0], conv) << 16 | EC16(hdr_old.filesize[1], conv)); cli_dbgmsg("CPIO: Filesize: %u\n", filesize); - if (!filesize) + if (!filesize) { continue; + } status = cli_matchmeta(ctx, name, filesize, filesize, 0, file, 0); if (status != CL_SUCCESS) { diff --git a/libclamav/crtmgr.c b/libclamav/crtmgr.c index f80b5e8450..4be1d84617 100644 --- a/libclamav/crtmgr.c +++ b/libclamav/crtmgr.c @@ -250,8 +250,9 @@ bool crtmgr_add(crtmgr *m, cli_crt *x509) if (x509->name) { i->name = strdup(x509->name); - if (!i->name) + if (!i->name) { goto done; + } } else { i->name = NULL; } @@ -303,15 +304,18 @@ void crtmgr_del(crtmgr *m, cli_crt *x509) cli_crt *i; for (i = m->crts; i; i = i->next) { if (i == x509) { - if (i->prev) + if (i->prev) { i->prev->next = i->next; - else + } else { m->crts = i->next; - if (i->next) + } + if (i->next) { i->next->prev = i->prev; + } cli_crt_clear(x509); - if ((x509->name)) + if ((x509->name)) { free(x509->name); + } free(x509); m->items--; return; @@ -321,8 +325,9 @@ void crtmgr_del(crtmgr *m, cli_crt *x509) void crtmgr_free(crtmgr *m) { - while (m->items) + while (m->items) { crtmgr_del(m, m->crts); + } } static cl_error_t _padding_check_PKCS1_type_1(uint8_t **to, int *tlen, @@ -341,8 +346,9 @@ static cl_error_t _padding_check_PKCS1_type_1(uint8_t **to, int *tlen, * D - data. */ - if (num < 11) /* RSA_PKCS1_PADDING_SIZE */ + if (num < 11) { /* RSA_PKCS1_PADDING_SIZE */ return CL_EPARSE; + } /* Accept inputs with and without the leading 0-byte. */ if (num == flen) { @@ -408,12 +414,14 @@ static cl_error_t crtmgr_get_recov_data(BIGNUM *sig, cli_crt *x509, keylen = BN_num_bytes(x509->n); bnctx = BN_CTX_new(); - if (!bnctx) + if (!bnctx) { goto done; + } x = BN_new(); - if (!x) + if (!x) { goto done; + } CLI_MALLOC_OR_GOTO_DONE(d, keylen); @@ -474,8 +482,9 @@ static int crtmgr_rsa_verify(cli_crt *x509, BIGNUM *sig, cli_crt_hashtype hashty } ret = crtmgr_get_recov_data(sig, x509, &buff, &d, &len); - if (ret != CL_SUCCESS) + if (ret != CL_SUCCESS) { return 1; + } do { j = 0; @@ -606,8 +615,9 @@ cli_crt *crtmgr_verify_crt(crtmgr *m, cli_crt *x509) !memcmp(i->subject, x509->issuer, sizeof(i->subject)) && !crtmgr_rsa_verify(i, x509->sig, x509->hashtype, x509->tbshash)) { int curscore; - if ((x509->codeSign & i->codeSign) == x509->codeSign && (x509->timeSign & i->timeSign) == x509->timeSign) + if ((x509->codeSign & i->codeSign) == x509->codeSign && (x509->timeSign & i->timeSign) == x509->timeSign) { return i; + } possible++; curscore = (x509->codeSign & i->codeSign) + (x509->timeSign & i->timeSign); if (curscore > score) { @@ -636,16 +646,19 @@ cli_crt *crtmgr_verify_pkcs7(crtmgr *m, const uint8_t *issuer, const uint8_t *se } sig = BN_new(); - if (!sig) + if (!sig) { return NULL; + } BN_bin2bn(signature, signature_len, sig); for (i = m->crts; i; i = i->next) { - if (vrfytype == VRFY_CODE && !i->codeSign) + if (vrfytype == VRFY_CODE && !i->codeSign) { continue; - if (vrfytype == VRFY_TIME && !i->timeSign) + } + if (vrfytype == VRFY_TIME && !i->timeSign) { continue; + } if (!memcmp(i->issuer, issuer, sizeof(i->issuer)) && !memcmp(i->serial, serial, sizeof(i->serial))) { if (!crtmgr_rsa_verify(i, sig, hashtype, refhash)) { diff --git a/libclamav/crypto.c b/libclamav/crypto.c index e4824fdb79..f296fcde6d 100644 --- a/libclamav/crypto.c +++ b/libclamav/crypto.c @@ -171,19 +171,22 @@ unsigned char *cl_hash_data(const char *alg, const void *buf, size_t len, unsign int winres = 0; md = EVP_get_digestbyname(alg); - if (!(md)) + if (!(md)) { return NULL; + } mdsz = EVP_MD_size(md); ret = (obuf != NULL) ? obuf : (unsigned char *)malloc(mdsz); - if (!(ret)) + if (!(ret)) { return NULL; + } ctx = EVP_MD_CTX_create(); if (!(ctx)) { - if (!(obuf)) + if (!(obuf)) { free(ret); + } return NULL; } @@ -194,11 +197,13 @@ unsigned char *cl_hash_data(const char *alg, const void *buf, size_t len, unsign #endif if (!EVP_DigestInit_ex(ctx, md, NULL)) { - if (!(obuf)) + if (!(obuf)) { free(ret); + } - if ((olen)) + if ((olen)) { *olen = 0; + } EVP_MD_CTX_destroy(ctx); return NULL; @@ -210,11 +215,13 @@ unsigned char *cl_hash_data(const char *alg, const void *buf, size_t len, unsign EXCEPTION_PREAMBLE if (!EVP_DigestUpdate(ctx, (void *)(((unsigned char *)buf) + cur), todo)) { - if (!(obuf)) + if (!(obuf)) { free(ret); + } - if ((olen)) + if ((olen)) { *olen = 0; + } EVP_MD_CTX_destroy(ctx); return NULL; @@ -222,11 +229,13 @@ unsigned char *cl_hash_data(const char *alg, const void *buf, size_t len, unsign EXCEPTION_POSTAMBLE if (winres) { - if (!(obuf)) + if (!(obuf)) { free(ret); + } - if ((olen)) + if ((olen)) { *olen = 0; + } EVP_MD_CTX_destroy(ctx); return NULL; @@ -236,11 +245,13 @@ unsigned char *cl_hash_data(const char *alg, const void *buf, size_t len, unsign } if (!EVP_DigestFinal_ex(ctx, ret, &i)) { - if (!(obuf)) + if (!(obuf)) { free(ret); + } - if ((olen)) + if ((olen)) { *olen = 0; + } EVP_MD_CTX_destroy(ctx); return NULL; @@ -248,8 +259,9 @@ unsigned char *cl_hash_data(const char *alg, const void *buf, size_t len, unsign EVP_MD_CTX_destroy(ctx); - if ((olen)) + if ((olen)) { *olen = i; + } return ret; } @@ -261,12 +273,14 @@ unsigned char *cl_hash_file_fd(int fd, const char *alg, unsigned int *olen) unsigned char *res; md = EVP_get_digestbyname(alg); - if (!(md)) + if (!(md)) { return NULL; + } ctx = EVP_MD_CTX_create(); - if (!(ctx)) + if (!(ctx)) { return NULL; + } #ifdef EVP_MD_CTX_FLAG_NON_FIPS_ALLOW /* we will be using MD5, which is not allowed under FIPS */ @@ -353,8 +367,9 @@ unsigned char *cl_hash_file_fd_ctx(EVP_MD_CTX *ctx, int fd, unsigned int *olen) return NULL; } - if ((olen)) + if ((olen)) { *olen = hashlen; + } free(buf); @@ -393,12 +408,14 @@ int cl_verify_signature_hash(EVP_PKEY *pkey, const char *alg, unsigned char *sig size_t mdsz; md = EVP_get_digestbyname(alg); - if (!(md)) + if (!(md)) { return -1; + } ctx = EVP_MD_CTX_create(); - if (!(ctx)) + if (!(ctx)) { return -1; + } mdsz = EVP_MD_size(md); @@ -434,8 +451,9 @@ int cl_verify_signature_fd(EVP_PKEY *pkey, const char *alg, unsigned char *sig, unsigned char *digest; digest = cl_hash_file_fd(fd, alg, NULL); - if (!(digest)) + if (!(digest)) { return -1; + } md = EVP_get_digestbyname(alg); if (!(md)) { @@ -491,8 +509,9 @@ int cl_verify_signature(EVP_PKEY *pkey, const char *alg, unsigned char *sig, uns size_t newsiglen; newsig = (unsigned char *)cl_base64_decode((char *)sig, siglen, NULL, &newsiglen, 1); - if (!(newsig)) + if (!(newsig)) { return -1; + } sig = newsig; siglen = newsiglen; @@ -500,8 +519,9 @@ int cl_verify_signature(EVP_PKEY *pkey, const char *alg, unsigned char *sig, uns digest = cl_hash_data(alg, data, datalen, NULL, NULL); if (!(digest)) { - if (decode) + if (decode) { free(sig); + } return -1; } @@ -509,8 +529,9 @@ int cl_verify_signature(EVP_PKEY *pkey, const char *alg, unsigned char *sig, uns md = EVP_get_digestbyname(alg); if (!(md)) { free(digest); - if (decode) + if (decode) { free(sig); + } return -1; } @@ -520,8 +541,9 @@ int cl_verify_signature(EVP_PKEY *pkey, const char *alg, unsigned char *sig, uns ctx = EVP_MD_CTX_create(); if (!(ctx)) { free(digest); - if (decode) + if (decode) { free(sig); + } return -1; } @@ -533,8 +555,9 @@ int cl_verify_signature(EVP_PKEY *pkey, const char *alg, unsigned char *sig, uns if (!EVP_VerifyInit_ex(ctx, md, NULL)) { free(digest); - if (decode) + if (decode) { free(sig); + } EVP_MD_CTX_destroy(ctx); return -1; @@ -542,8 +565,9 @@ int cl_verify_signature(EVP_PKEY *pkey, const char *alg, unsigned char *sig, uns if (!EVP_VerifyUpdate(ctx, digest, mdsz)) { free(digest); - if (decode) + if (decode) { free(sig); + } EVP_MD_CTX_destroy(ctx); return -1; @@ -551,15 +575,17 @@ int cl_verify_signature(EVP_PKEY *pkey, const char *alg, unsigned char *sig, uns if (EVP_VerifyFinal(ctx, sig, siglen, pkey) <= 0) { free(digest); - if (decode) + if (decode) { free(sig); + } EVP_MD_CTX_destroy(ctx); return -1; } - if (decode) + if (decode) { free(sig); + } free(digest); EVP_MD_CTX_destroy(ctx); @@ -650,8 +676,9 @@ int cl_verify_signature_hash_x509(X509 *x509, const char *alg, unsigned char *si int res; pkey = X509_get_pubkey(x509); - if (!(pkey)) + if (!(pkey)) { return -1; + } res = cl_verify_signature_hash(pkey, alg, sig, siglen, digest); @@ -666,8 +693,9 @@ int cl_verify_signature_fd_x509(X509 *x509, const char *alg, unsigned char *sig, int res; pkey = X509_get_pubkey(x509); - if (!(pkey)) + if (!(pkey)) { return -1; + } res = cl_verify_signature_fd(pkey, alg, sig, siglen, fd); @@ -682,8 +710,9 @@ int cl_verify_signature_x509(X509 *x509, const char *alg, unsigned char *sig, un int res; pkey = X509_get_pubkey(x509); - if (!(pkey)) + if (!(pkey)) { return -1; + } res = cl_verify_signature(pkey, alg, sig, siglen, data, datalen, decode); @@ -726,12 +755,14 @@ unsigned char *cl_sign_data(EVP_PKEY *pkey, const char *alg, unsigned char *hash unsigned char *sig; md = EVP_get_digestbyname(alg); - if (!(md)) + if (!(md)) { return NULL; + } ctx = EVP_MD_CTX_create(); - if (!(ctx)) + if (!(ctx)) { return NULL; + } sig = (unsigned char *)calloc(1, EVP_PKEY_size(pkey)); if (!(sig)) { @@ -807,8 +838,9 @@ EVP_PKEY *cl_get_pkey_file(char *keypath) FILE *fp; fp = fopen(keypath, "r"); - if (!(fp)) + if (!(fp)) { return NULL; + } if (!(pkey = PEM_read_PrivateKey(fp, NULL, NULL, NULL))) { fclose(fp); @@ -826,8 +858,9 @@ X509 *cl_get_x509_from_mem(void *data, unsigned int len) BIO *cbio; cbio = BIO_new_mem_buf(data, len); - if (!(cbio)) + if (!(cbio)) { return NULL; + } cert = PEM_read_bio_X509(cbio, NULL, 0, NULL); BIO_free(cbio); @@ -844,21 +877,25 @@ int cl_validate_certificate_chain_ts_dir(char *tsdir, char *certpath) struct dirent *dirent; dp = opendir(tsdir); - if (!(dp)) + if (!(dp)) { return CL_EOPEN; + } while ((dirent = readdir(dp))) { - if (dirent->d_name[0] == '.') + if (dirent->d_name[0] == '.') { continue; + } - if (!cli_strbcasestr(dirent->d_name, ".crt")) + if (!cli_strbcasestr(dirent->d_name, ".crt")) { continue; + } t = (char **)realloc(authorities, sizeof(char **) * (nauths + 1)); if (!(t)) { if (nauths) { - while (nauths > 0) + while (nauths > 0) { free(authorities[--nauths]); + } free(authorities); } @@ -870,8 +907,9 @@ int cl_validate_certificate_chain_ts_dir(char *tsdir, char *certpath) authorities[nauths] = (char *)malloc(strlen(tsdir) + strlen(dirent->d_name) + 2); if (!authorities[nauths]) { if (nauths) { - while (nauths > 0) + while (nauths > 0) { free(authorities[nauths--]); + } free(authorities[0]); } @@ -889,8 +927,9 @@ int cl_validate_certificate_chain_ts_dir(char *tsdir, char *certpath) t = (char **)realloc(authorities, sizeof(char **) * (nauths + 1)); if (!(t)) { if (nauths) { - while (nauths > 0) + while (nauths > 0) { free(authorities[--nauths]); + } free(authorities); } @@ -902,8 +941,9 @@ int cl_validate_certificate_chain_ts_dir(char *tsdir, char *certpath) res = cl_validate_certificate_chain(authorities, NULL, certpath); - while (nauths > 0) + while (nauths > 0) { free(authorities[--nauths]); + } free(authorities); @@ -957,10 +997,12 @@ int cl_validate_certificate_chain(char **authorities, char *crlpath, char *certp for (i = 0; authorities[i]; i++) { if (!X509_LOOKUP_load_file(lookup, authorities[i], X509_FILETYPE_PEM)) { X509_STORE_free(store); - if ((crl)) + if ((crl)) { X509_CRL_free(crl); - if ((param)) + } + if ((param)) { X509_VERIFY_PARAM_free(param); + } return -1; } } @@ -968,10 +1010,12 @@ int cl_validate_certificate_chain(char **authorities, char *crlpath, char *certp lookup = X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir()); if (!(lookup)) { X509_STORE_free(store); - if ((crl)) + if ((crl)) { X509_CRL_free(crl); - if ((param)) + } + if ((param)) { X509_VERIFY_PARAM_free(param); + } return -1; } @@ -980,10 +1024,12 @@ int cl_validate_certificate_chain(char **authorities, char *crlpath, char *certp store_ctx = X509_STORE_CTX_new(); if (!(store_ctx)) { X509_STORE_free(store); - if ((crl)) + if ((crl)) { X509_CRL_free(crl); - if ((param)) + } + if ((param)) { X509_VERIFY_PARAM_free(param); + } return -1; } @@ -991,10 +1037,12 @@ int cl_validate_certificate_chain(char **authorities, char *crlpath, char *certp if (!(cert)) { X509_STORE_CTX_free(store_ctx); X509_STORE_free(store); - if ((crl)) + if ((crl)) { X509_CRL_free(crl); - if ((param)) + } + if ((param)) { X509_VERIFY_PARAM_free(param); + } return -1; } @@ -1002,10 +1050,12 @@ int cl_validate_certificate_chain(char **authorities, char *crlpath, char *certp if (!X509_STORE_CTX_init(store_ctx, store, cert, NULL)) { X509_STORE_CTX_free(store_ctx); X509_STORE_free(store); - if ((crl)) + if ((crl)) { X509_CRL_free(crl); - if ((param)) + } + if ((param)) { X509_VERIFY_PARAM_free(param); + } X509_free(cert); @@ -1015,11 +1065,13 @@ int cl_validate_certificate_chain(char **authorities, char *crlpath, char *certp res = X509_verify_cert(store_ctx); X509_STORE_CTX_free(store_ctx); - if ((crl)) + if ((crl)) { X509_CRL_free(crl); + } - if ((param)) + if ((param)) { X509_VERIFY_PARAM_free(param); + } X509_STORE_free(store); @@ -1034,8 +1086,9 @@ X509 *cl_load_cert(const char *certpath) BIO *bio; bio = BIO_new(BIO_s_file()); - if (!(bio)) + if (!(bio)) { return NULL; + } if (BIO_read_filename(bio, certpath) != 1) { BIO_free(bio); @@ -1061,16 +1114,19 @@ struct tm *cl_ASN1_GetTimeT(ASN1_TIME *timeobj) struct tm localtm; #endif - if (!(timeobj) || !(timeobj->data)) + if (!(timeobj) || !(timeobj->data)) { return NULL; + } str = (char *)(timeobj->data); - if (strlen(str) < 12) + if (strlen(str) < 12) { return NULL; + } t = (struct tm *)calloc(1, sizeof(struct tm)); - if (!(t)) + if (!(t)) { return NULL; + } if (timeobj->type == V_ASN1_UTCTIME) { /* two digit year */ @@ -1119,12 +1175,14 @@ X509_CRL *cl_load_crl(const char *file) X509_CRL *x = NULL; FILE *fp; - if (!(file)) + if (!(file)) { return NULL; + } fp = fopen(file, "r"); - if (!(fp)) + if (!(fp)) { return NULL; + } x = PEM_read_X509_CRL(fp, NULL, NULL, NULL); @@ -1149,8 +1207,9 @@ void *cl_hash_init(const char *alg) const EVP_MD *md; md = EVP_get_digestbyname(alg); - if (!(md)) + if (!(md)) { return NULL; + } ctx = EVP_MD_CTX_create(); if (!(ctx)) { @@ -1174,16 +1233,19 @@ int cl_update_hash(void *ctx, const void *data, size_t sz) { int winres = 0; - if (!(ctx) || !(data)) + if (!(ctx) || !(data)) { return -1; + } EXCEPTION_PREAMBLE - if (!EVP_DigestUpdate((EVP_MD_CTX *)ctx, data, sz)) + if (!EVP_DigestUpdate((EVP_MD_CTX *)ctx, data, sz)) { return -1; + } EXCEPTION_POSTAMBLE - if (winres) + if (winres) { return -1; + } return 0; } @@ -1192,11 +1254,13 @@ int cl_finish_hash(void *ctx, void *buf) { int res = 0; - if (!(ctx) || !(buf)) + if (!(ctx) || !(buf)) { return -1; + } - if (!EVP_DigestFinal_ex((EVP_MD_CTX *)ctx, (unsigned char *)buf, NULL)) + if (!EVP_DigestFinal_ex((EVP_MD_CTX *)ctx, (unsigned char *)buf, NULL)) { res = -1; + } EVP_MD_CTX_destroy((EVP_MD_CTX *)ctx); @@ -1205,8 +1269,9 @@ int cl_finish_hash(void *ctx, void *buf) void cl_hash_destroy(void *ctx) { - if (!(ctx)) + if (!(ctx)) { return; + } EVP_MD_CTX_destroy((EVP_MD_CTX *)ctx); } diff --git a/libclamav/cvd.c b/libclamav/cvd.c index f68a99512c..3b4118f6cd 100644 --- a/libclamav/cvd.c +++ b/libclamav/cvd.c @@ -115,11 +115,13 @@ static int cli_tgzload(cvd_t *cvd, struct cl_engine *engine, unsigned int *signo return CL_ESEEK; } - if (cli_readn(fd, block, 7) != 7) + if (cli_readn(fd, block, 7) != 7) { return CL_EFORMAT; /* truncated file? */ + } - if (!strncmp(block, "COPYING", 7)) + if (!strncmp(block, "COPYING", 7)) { compr = 0; + } if (lseek(fd, 512, SEEK_SET) < 0) { return CL_ESEEK; @@ -133,16 +135,18 @@ static int cli_tgzload(cvd_t *cvd, struct cl_engine *engine, unsigned int *signo if (compr) { if ((dbio->gzs = gzdopen(fdd, "rb")) == NULL) { cli_errmsg("cli_tgzload: Can't gzdopen() descriptor %d, errno = %d\n", fdd, errno); - if (fdd > -1) + if (fdd > -1) { close(fdd); + } return CL_EOPEN; } dbio->fs = NULL; } else { if ((dbio->fs = fdopen(fdd, "rb")) == NULL) { cli_errmsg("cli_tgzload: Can't fdopen() descriptor %d, errno = %d\n", fdd, errno); - if (fdd > -1) + if (fdd > -1) { close(fdd); + } return CL_EOPEN; } dbio->gzs = NULL; @@ -161,13 +165,15 @@ static int cli_tgzload(cvd_t *cvd, struct cl_engine *engine, unsigned int *signo while (1) { - if (compr) + if (compr) { nread = gzread(dbio->gzs, block, TAR_BLOCKSIZE); - else + } else { nread = fread(block, 1, TAR_BLOCKSIZE, dbio->fs); + } - if (!nread) + if (!nread) { break; + } if (nread != TAR_BLOCKSIZE) { cli_errmsg("cli_tgzload: Incomplete block read\n"); @@ -175,8 +181,9 @@ static int cli_tgzload(cvd_t *cvd, struct cl_engine *engine, unsigned int *signo return CL_EMALFDB; } - if (block[0] == '\0') /* We're done */ + if (block[0] == '\0') { /* We're done */ break; + } strncpy(name, block, 100); name[100] = '\0'; @@ -225,10 +232,11 @@ static int cli_tgzload(cvd_t *cvd, struct cl_engine *engine, unsigned int *signo dbio->bread = 0; /* cli_dbgmsg("cli_tgzload: Loading %s, size: %u\n", name, size); */ - if (compr) + if (compr) { off = (off_t)gzseek(dbio->gzs, 0, SEEK_CUR); - else + } else { off = ftell(dbio->fs); + } if ((!dbinfo && cli_strbcasestr(name, ".info")) || (dbinfo && CLI_DBEXT(name))) { ret = cli_load(name, engine, signo, options, dbio, sign_verifier); @@ -242,8 +250,9 @@ static int cli_tgzload(cvd_t *cvd, struct cl_engine *engine, unsigned int *signo return CL_SUCCESS; } else { db = dbinfo; - while (db && strcmp(db->name, name)) + while (db && strcmp(db->name, name)) { db = db->next; + } if (!db) { cli_errmsg("cli_tgzload: File %s not found in .info\n", name); cli_tgzload_cleanup(compr, dbio, fdd); @@ -271,15 +280,17 @@ static int cli_tgzload(cvd_t *cvd, struct cl_engine *engine, unsigned int *signo } pad = size % TAR_BLOCKSIZE ? (TAR_BLOCKSIZE - (size % TAR_BLOCKSIZE)) : 0; if (compr) { - if (off == gzseek(dbio->gzs, 0, SEEK_CUR)) + if (off == gzseek(dbio->gzs, 0, SEEK_CUR)) { gzseek(dbio->gzs, size + pad, SEEK_CUR); - else if (pad) + } else if (pad) { gzseek(dbio->gzs, pad, SEEK_CUR); + } } else { - if (off == ftell(dbio->fs)) + if (off == ftell(dbio->fs)) { fseek(dbio->fs, size + pad, SEEK_CUR); - else if (pad) + } else if (pad) { fseek(dbio->fs, pad, SEEK_CUR); + } } } @@ -391,11 +402,13 @@ struct cl_cvd *cl_cvdhead(const char *file) fclose(fs); head[bread] = 0; - if ((pt = strpbrk(head, "\n\r"))) + if ((pt = strpbrk(head, "\n\r"))) { *pt = 0; + } - for (i = bread - 1; i > 0 && (head[i] == ' ' || head[i] == '\n' || head[i] == '\r'); head[i] = 0, i--) + for (i = bread - 1; i > 0 && (head[i] == ' ' || head[i] == '\n' || head[i] == '\r'); head[i] = 0, i--) { ; + } return cl_cvdparse(head); } @@ -616,8 +629,9 @@ cl_error_t cli_cvdload(struct cl_engine *engine, unsigned int *signo, unsigned i engine->dbinfo = dbinfo->next; MPOOL_FREE(engine->mempool, dbinfo->name); MPOOL_FREE(engine->mempool, dbinfo->hash); - if (dbinfo->cvd) + if (dbinfo->cvd) { cl_cvdfree(dbinfo->cvd); + } MPOOL_FREE(engine->mempool, dbinfo); } @@ -882,19 +896,23 @@ cl_error_t cl_cvdgetage(const char *path, time_t *age_seconds) char fname[1024] = {0}; time_t file_age; - if (!dent->d_ino) + if (!dent->d_ino) { continue; + } - if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, "..")) + if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, "..")) { continue; + } - if (!CLI_DBEXT_SIGNATURE(dent->d_name)) + if (!CLI_DBEXT_SIGNATURE(dent->d_name)) { continue; + } - if (ends_with_sep) + if (ends_with_sep) { snprintf(fname, sizeof(fname) - 1, "%s%s", path, dent->d_name); - else + } else { snprintf(fname, sizeof(fname) - 1, "%s" PATHSEP "%s", path, dent->d_name); + } if ((status = cvdgetfileage(fname, &file_age)) != CL_SUCCESS) { cli_errmsg("cl_cvdgetage: cvdgetfileage() failed for %s\n", fname); @@ -910,8 +928,9 @@ cl_error_t cl_cvdgetage(const char *path, time_t *age_seconds) } done: - if (dd) + if (dd) { closedir(dd); + } return status; } diff --git a/libclamav/dconf.c b/libclamav/dconf.c index 9778631b16..cc7dd9f22d 100644 --- a/libclamav/dconf.c +++ b/libclamav/dconf.c @@ -168,43 +168,55 @@ struct cli_dconf *cli_dconf_init(void) struct cli_dconf *dconf; dconf = (struct cli_dconf *)MPOOL_CALLOC(mempool, sizeof(struct cli_dconf), 1); - if (!dconf) + if (!dconf) { return NULL; + } for (i = 0; modules[i].mname; i++) { if (!strcmp(modules[i].mname, "PE")) { - if (modules[i].state) + if (modules[i].state) { dconf->pe |= modules[i].bflag; + } } else if (!strcmp(modules[i].mname, "ELF")) { - if (modules[i].state) + if (modules[i].state) { dconf->elf |= modules[i].bflag; + } } else if (!strcmp(modules[i].mname, "MACHO")) { - if (modules[i].state) + if (modules[i].state) { dconf->macho |= modules[i].bflag; + } } else if (!strcmp(modules[i].mname, "ARCHIVE")) { - if (modules[i].state) + if (modules[i].state) { dconf->archive |= modules[i].bflag; + } } else if (!strcmp(modules[i].mname, "DOCUMENT")) { - if (modules[i].state) + if (modules[i].state) { dconf->doc |= modules[i].bflag; + } } else if (!strcmp(modules[i].mname, "MAIL")) { - if (modules[i].state) + if (modules[i].state) { dconf->mail |= modules[i].bflag; + } } else if (!strcmp(modules[i].mname, "OTHER")) { - if (modules[i].state) + if (modules[i].state) { dconf->other |= modules[i].bflag; + } } else if (!strcmp(modules[i].mname, "PHISHING")) { - if (modules[i].state) + if (modules[i].state) { dconf->phishing |= modules[i].bflag; + } } else if (!strcmp(modules[i].mname, "BYTECODE")) { - if (modules[i].state) + if (modules[i].state) { dconf->bytecode |= modules[i].bflag; + } } else if (!strcmp(modules[i].mname, "STATS")) { - if (modules[i].state) + if (modules[i].state) { dconf->stats |= modules[i].bflag; + } } else if (!strcmp(modules[i].mname, "PCRE")) { - if (modules[i].state) + if (modules[i].state) { dconf->pcre |= modules[i].bflag; + } } } @@ -226,10 +238,11 @@ void cli_dconf_print(struct cli_dconf *dconf) pe = 1; } - if (dconf->pe) + if (dconf->pe) { cli_dbgmsg(" * Submodule %10s:\t%s\n", modules[i].sname, (dconf->pe & modules[i].bflag) ? "On" : "** Off **"); - else + } else { continue; + } } else if (!strcmp(modules[i].mname, "ELF")) { if (!elf) { cli_dbgmsg("Module ELF: %s\n", dconf->elf ? "On" : "Off"); @@ -246,80 +259,88 @@ void cli_dconf_print(struct cli_dconf *dconf) arch = 1; } - if (dconf->archive) + if (dconf->archive) { cli_dbgmsg(" * Submodule %10s:\t%s\n", modules[i].sname, (dconf->archive & modules[i].bflag) ? "On" : "** Off **"); - else + } else { continue; + } } else if (!strcmp(modules[i].mname, "DOCUMENT")) { if (!doc) { cli_dbgmsg("Module DOCUMENT: %s\n", dconf->doc ? "On" : "Off"); doc = 1; } - if (dconf->doc) + if (dconf->doc) { cli_dbgmsg(" * Submodule %10s:\t%s\n", modules[i].sname, (dconf->doc & modules[i].bflag) ? "On" : "** Off **"); - else + } else { continue; + } } else if (!strcmp(modules[i].mname, "MAIL")) { if (!mail) { cli_dbgmsg("Module MAIL: %s\n", dconf->mail ? "On" : "Off"); mail = 1; } - if (dconf->mail) + if (dconf->mail) { cli_dbgmsg(" * Submodule %10s:\t%s\n", modules[i].sname, (dconf->mail & modules[i].bflag) ? "On" : "** Off **"); - else + } else { continue; + } } else if (!strcmp(modules[i].mname, "OTHER")) { if (!other) { cli_dbgmsg("Module OTHER: %s\n", dconf->other ? "On" : "Off"); other = 1; } - if (dconf->other) + if (dconf->other) { cli_dbgmsg(" * Submodule %10s:\t%s\n", modules[i].sname, (dconf->other & modules[i].bflag) ? "On" : "** Off **"); - else + } else { continue; + } } else if (!strcmp(modules[i].mname, "PHISHING")) { if (!phishing) { cli_dbgmsg("Module PHISHING %s\n", dconf->phishing ? "On" : "Off"); phishing = 1; } - if (dconf->phishing) + if (dconf->phishing) { cli_dbgmsg(" * Submodule %10s:\t%s\n", modules[i].sname, (dconf->phishing & modules[i].bflag) ? "On" : "** Off **"); - else + } else { continue; + } } else if (!strcmp(modules[i].mname, "BYTECODE")) { if (!bytecode) { cli_dbgmsg("Module BYTECODE %s\n", dconf->bytecode ? "On" : "Off"); bytecode = 1; } - if (dconf->bytecode) + if (dconf->bytecode) { cli_dbgmsg(" * Submodule %10s:\t%s\n", modules[i].sname, (dconf->bytecode & modules[i].bflag) ? "On" : "** Off **"); - else + } else { continue; + } } else if (!strcmp(modules[i].mname, "STATS")) { if (!stats) { cli_dbgmsg("Module STATS %s\n", dconf->stats ? "On" : "Off"); stats = 1; } - if (dconf->stats) + if (dconf->stats) { cli_dbgmsg(" * Submodule %10s:\t%s\n", modules[i].sname, (dconf->stats & modules[i].bflag) ? "On" : "** Off **"); - else + } else { continue; + } } else if (!strcmp(modules[i].mname, "PCRE")) { if (!pcre) { cli_dbgmsg("Module PCRE %s\n", dconf->pcre ? "On" : "Off"); pcre = 1; } - if (dconf->pcre) + if (dconf->pcre) { cli_dbgmsg(" * Submodule %10s:\t%s\n", modules[i].sname, (dconf->pcre & modules[i].bflag) ? "On" : "** Off **"); - else + } else { continue; + } } } } diff --git a/libclamav/disasm.c b/libclamav/disasm.c index 44e57d358d..67cadd9c0b 100644 --- a/libclamav/disasm.c +++ b/libclamav/disasm.c @@ -1205,10 +1205,11 @@ static void spam_x86(struct DISASMED *s, char *hr) break; case ACCESS_IMM: case ACCESS_REL: - if (s->args[i].arg.rq >= 0) + if (s->args[i].arg.rq >= 0) { hr += sprintf(hr, "%s %lx", comma, (long)s->args[i].arg.q); - else + } else { hr += sprintf(hr, "%s -%x", comma, -(int)s->args[i].arg.rq); + } break; case ACCESS_REG: hr += sprintf(hr, "%s %s", comma, x86regs[s->args[i].reg]); @@ -1216,7 +1217,9 @@ static void spam_x86(struct DISASMED *s, char *hr) case ACCESS_MEM: { const char *gotstuff = ""; hr += sprintf(hr, "%s %s ptr ", comma, dis_size[s->args[i].size]); - if (s->segment) hr += sprintf(hr, "%s:", x86regs[s->segment]); + if (s->segment) { + hr += sprintf(hr, "%s:", x86regs[s->segment]); + } *hr++ = '['; *hr = '\0'; if (s->args[i].arg.marg.r1 != X86_REG_INVALID) { @@ -1237,10 +1240,11 @@ static void spam_x86(struct DISASMED *s, char *hr) gotstuff = "+"; } if (s->args[i].arg.marg.disp) { - if (*gotstuff == '+' && s->args[i].arg.marg.disp < 0) + if (*gotstuff == '+' && s->args[i].arg.marg.disp < 0) { hr += sprintf(hr, "-%x", -s->args[i].arg.marg.disp); - else + } else { hr += sprintf(hr, "%s%x", gotstuff, s->args[i].arg.marg.disp); + } } *hr++ = ']'; *hr = '\0'; @@ -1370,7 +1374,9 @@ static const uint8_t *disasm_x86(const uint8_t *command, unsigned int len, struc } s->args[0].arg.marg.r2 = X86_REG_INVALID; } - if (mod == 2) mod += mod; + if (mod == 2) { + mod += mod; + } for (i = 0; i < mod; i++) { GETBYTE(b); s->args[0].arg.marg.disp += b << (i * 8); @@ -1519,8 +1525,9 @@ static const uint8_t *disasm_x86(const uint8_t *command, unsigned int len, struc if ((s->args[reversed ^ 1].reg = p[s->args[reversed].size][rop]) == X86_REG_INVALID) INVALIDATE; /* MOVZX size fixxup */ - if (s->real_op == OP_MOVZX || s->real_op == OP_MOVSX) + if (s->real_op == OP_MOVZX || s->real_op == OP_MOVSX) { s->args[reversed].size = SIZEB + (s->table_op & 1); + } if (mod == 3) { if (x86ops[table][s->table_op].dmethod == ADDR_MRM_GEN_GM || x86ops[table][s->table_op].dmethod == ADDR_MRM_EXTRA_1A_M) INVALIDATE; @@ -1538,8 +1545,9 @@ static const uint8_t *disasm_x86(const uint8_t *command, unsigned int len, struc s->state = STATE_FINALIZE; continue; } - } else + } else { s->cur++; + } s->state = STATE_CHECKSTYPE; continue; } @@ -1573,7 +1581,9 @@ static const uint8_t *disasm_x86(const uint8_t *command, unsigned int len, struc } s->args[reversed].arg.marg.r2 = X86_REG_INVALID; } - if (mod == 2) mod += mod; + if (mod == 2) { + mod += mod; + } for (i = 0; i < mod; i++) { GETBYTE(b); shiftme += b << (i * 8); @@ -1581,8 +1591,9 @@ static const uint8_t *disasm_x86(const uint8_t *command, unsigned int len, struc if (mod) { shiftme <<= ((8 - mod) * 8); s->args[reversed].arg.marg.disp = shiftme >> ((8 - mod) * 8); - } else + } else { s->args[reversed].arg.marg.disp = 0; + } } else { if (mod == 0 && rm == 6) { s->args[reversed].arg.marg.r1 = X86_REG_INVALID; @@ -1610,8 +1621,9 @@ static const uint8_t *disasm_x86(const uint8_t *command, unsigned int len, struc s->state = STATE_FINALIZE; continue; } - } else + } else { s->cur++; + } s->state = STATE_CHECKSTYPE; continue; } @@ -1725,8 +1737,9 @@ const uint8_t *cli_disasm_one(const uint8_t *buff, unsigned int len, memset(&w->extra[0], 0, sizeof(w->extra)); buff = disasm_x86(buff, len, &s); - if (!buff) + if (!buff) { return NULL; + } if (spam) { char hr[128]; spam_x86(&s, hr); diff --git a/libclamav/dlp.c b/libclamav/dlp.c index f62dfbdfa9..0968e22f4f 100644 --- a/libclamav/dlp.c +++ b/libclamav/dlp.c @@ -160,8 +160,9 @@ static const struct iin_map_struct *get_iin(char *digits, int cc_only) int i = 0; while (iin_map[i].iin_start != 0) { - if (iin < iin_map[i].iin_start) + if (iin < iin_map[i].iin_start) { break; + } if (iin <= iin_map[i].iin_end && (cc_only == 0 || iin_map[i].is_cc == 1)) { cli_dbgmsg("Credit card IIN %s matched range for %s\n", digits, iin_map[i].iin_name); return &iin_map[i]; @@ -184,68 +185,81 @@ int dlp_is_valid_cc(const unsigned char *buffer, size_t length, int cc_only) size_t pad_allowance = MAX_CC_BREAKS; const struct iin_map_struct *iin; - if (buffer == NULL || length < 13) + if (buffer == NULL || length < 13) { return 0; + } /* if the first digit is greater than 6 it isn't one of the major * credit cards * reference => http://www.beachnet.com/~hstiles/cardtype.html */ - if (!isdigit(buffer[0]) || buffer[0] > '6' || buffer[0] == 2) + if (!isdigit(buffer[0]) || buffer[0] > '6' || buffer[0] == 2) { return 0; + } - if (length > 19 + pad_allowance) /* max credit card length is 19, with allowance for punctuation */ + if (length > 19 + pad_allowance) { /* max credit card length is 19, with allowance for punctuation */ length = 19 + pad_allowance; + } /* Look for possible 6 digit IIN */ for (i = 0; i < length && digits < IIN_SIZE; i++) { if (isdigit(buffer[i]) == 0) { - if (buffer[i] == ' ' || buffer[i] == '-') - if (pad_allowance-- > 0) + if (buffer[i] == ' ' || buffer[i] == '-') { + if (pad_allowance-- > 0) { continue; + } + } break; } cc_digits[digits] = buffer[i]; digits++; } - if (digits == IIN_SIZE) + if (digits == IIN_SIZE) { cc_digits[digits] = 0; - else + } else { return 0; + } /* See if it is a valid IIN. */ iin = get_iin(cc_digits, cc_only); - if (iin == NULL) + if (iin == NULL) { return 0; + } /* Look for the remaining needed digits. */ for (/*same 'i' from previous for-loop*/; i < length && digits < iin->card_max; i++) { if (isdigit(buffer[i]) == 0) { - if (buffer[i] == ' ' || buffer[i] == '-') - if (pad_allowance-- > 0) + if (buffer[i] == ' ' || buffer[i] == '-') { + if (pad_allowance-- > 0) { continue; + } + } break; } cc_digits[digits] = buffer[i]; digits++; } - if (digits < iin->card_min || (i < length && isdigit(buffer[i]))) + if (digits < iin->card_min || (i < length && isdigit(buffer[i]))) { return 0; + } j = (ssize_t)i; // figure out luhn digits for (j = digits - 1; j >= 0; j--) { val = cc_digits[j] - '0'; if (mult) { - if ((val *= 2) > 9) val -= 9; + if ((val *= 2) > 9) { + val -= 9; + } } mult = !mult; sum += val; } - if (sum % 10) + if (sum % 10) { return 0; + } cli_dbgmsg("Luhn algorithm successful for %s\n", cc_digits); @@ -268,9 +282,9 @@ static int contains_cc(const unsigned char *buffer, size_t length, int detmode, while (idx < end) { if (isdigit(*idx)) { if ((idx == buffer || !isdigit(idx[-1])) && dlp_is_valid_cc(idx, length - (idx - buffer), cc_only) == 1) { - if (detmode == DETECT_MODE_DETECT) + if (detmode == DETECT_MODE_DETECT) { return 1; - else { + } else { count++; /* if we got a valid match we should increment the idx ptr * to gain a little performance @@ -304,16 +318,19 @@ int dlp_is_valid_ssn(const unsigned char *buffer, size_t length, int format) int retval = 1; char numbuf[12]; - if (buffer == NULL) + if (buffer == NULL) { return 0; + } minlength = (format == SSN_FORMAT_HYPHENS ? 11 : 9); - if (length < minlength) + if (length < minlength) { return 0; + } - if ((length > minlength) && isdigit(buffer[minlength])) + if ((length > minlength) && isdigit(buffer[minlength])) { return 0; + } strncpy(numbuf, (const char *)buffer, minlength); numbuf[minlength] = 0; @@ -321,8 +338,9 @@ int dlp_is_valid_ssn(const unsigned char *buffer, size_t length, int format) /* sscanf parses and (basically) validates the string for us */ switch (format) { case SSN_FORMAT_HYPHENS: - if (numbuf[3] != '-' || numbuf[6] != '-') + if (numbuf[3] != '-' || numbuf[6] != '-') { return 0; + } if (sscanf((const char *)numbuf, "%3d-%2d-%4d", @@ -333,8 +351,9 @@ int dlp_is_valid_ssn(const unsigned char *buffer, size_t length, int format) } break; case SSN_FORMAT_STRIPPED: - if (!cli_isnumber(numbuf)) + if (!cli_isnumber(numbuf)) { return 0; + } if (sscanf((const char *)numbuf, "%3d%2d%4d", @@ -359,20 +378,23 @@ int dlp_is_valid_ssn(const unsigned char *buffer, size_t length, int format) group_number <= 0 || group_number > 99 || serial_number <= 0 || - serial_number > 9999) + serial_number > 9999) { retval = 0; + } if (area_number == 987 && group_number == 65) { - if (serial_number >= 4320 && serial_number <= 4329) + if (serial_number >= 4320 && serial_number <= 4329) { retval = 0; + } } /* if(group_number > ssn_max_group[area_number]) retval = 0; */ - if (retval) + if (retval) { cli_dbgmsg("dlp_is_valid_ssn: SSN_%s: %s\n", format == SSN_FORMAT_HYPHENS ? "HYPHENS" : "STRIPPED", numbuf); + } return retval; } @@ -383,8 +405,9 @@ static int contains_ssn(const unsigned char *buffer, size_t length, int format, const unsigned char *end; int count = 0; - if (buffer == NULL || length < 9) + if (buffer == NULL || length < 9) { return 0; + } end = buffer + length; idx = buffer; @@ -567,14 +590,19 @@ int cdn_ctn_is_valid(const char *buffer, size_t length) int i; int bank_code = 0; /* last three digits of Canada RTN/MICR is Bank I.D. */ - if (buffer == NULL || length < 9) /* if the buffer is empty or */ - return 0; /* the length is less than 9, it's not valid */ + if (buffer == NULL || length < 9) { /* if the buffer is empty or */ + return 0; /* the length is less than 9, it's not valid */ + } - if (buffer[5] != '-') return 0; /* if the 6th char isn't a '-', not a valid RTN */ + if (buffer[5] != '-') { + return 0; /* if the 6th char isn't a '-', not a valid RTN */ + } - for (i = 0; i < 5; i++) - if (isdigit(buffer[i]) == 0) + for (i = 0; i < 5; i++) { + if (isdigit(buffer[i]) == 0) { return 0; + } + } /* Check the various branch codes which are listed, but there */ /* may be more valid codes which could be added as well... */ @@ -582,8 +610,9 @@ int cdn_ctn_is_valid(const char *buffer, size_t length) /* convert last three elements in buffer to a numeric value */ for (i = 6; i < 9; i++) { - if (isdigit(buffer[i]) == 0) + if (isdigit(buffer[i]) == 0) { return 0; + } bank_code = (bank_code * 10) + (buffer[i] - '0'); } @@ -606,25 +635,32 @@ int cdn_eft_is_valid(const char *buffer, size_t length) int bank_code = 0; int i; - if (buffer == NULL || length < 9) /* if the buffer is empty or */ - return 0; /* the length is less than 9, it's not valid */ + if (buffer == NULL || length < 9) { /* if the buffer is empty or */ + return 0; /* the length is less than 9, it's not valid */ + } - if (buffer[0] != '0') return 0; /* if the 1st char isn't a '0', not a valid EFT */ + if (buffer[0] != '0') { + return 0; /* if the 1st char isn't a '0', not a valid EFT */ + } for (i = 1; i < 4; i++) { - if (isdigit(buffer[i]) == 0) + if (isdigit(buffer[i]) == 0) { return 0; + } bank_code = (bank_code * 10) + (buffer[i] - '0'); } /* Check the various branch codes which are listed, but there */ /* may be more valid codes which could be added as well... */ - if (!is_bank_code_valid(bank_code)) + if (!is_bank_code_valid(bank_code)) { return 0; + } - for (i = 4; i < 9; i++) - if (isdigit(buffer[i]) == 0) + for (i = 4; i < 9; i++) { + if (isdigit(buffer[i]) == 0) { return 0; + } + } return 1; } @@ -635,14 +671,16 @@ int us_micr_is_valid(const char *buffer, size_t length) int i; unsigned char micr_digits[9]; - if (buffer == NULL || length < 9) /* if the buffer is empty or */ - return 0; /* the length is < 9, it's not valid */ + if (buffer == NULL || length < 9) { /* if the buffer is empty or */ + return 0; /* the length is < 9, it's not valid */ + } /* loop and make sure all the characters are actually digits */ for (i = 0; i < 9; i++) { - if (isdigit(buffer[i]) == 0) + if (isdigit(buffer[i]) == 0) { return 0; + } micr_digits[i] = buffer[i]; } @@ -659,7 +697,8 @@ int us_micr_is_valid(const char *buffer, size_t length) sum = sum1 + sum2 + sum3; result = sum % 10; - if (result == (micr_digits[8] - '0')) + if (result == (micr_digits[8] - '0')) { return 1; /* last digit of MICR matches result */ - return 0; /* MICR number isn't valid */ + } + return 0; /* MICR number isn't valid */ } diff --git a/libclamav/dmg.c b/libclamav/dmg.c index 2f35fe538c..7c44187f9c 100644 --- a/libclamav/dmg.c +++ b/libclamav/dmg.c @@ -173,8 +173,9 @@ int cli_scandmg(cli_ctx *ctx) ctx, CL_TYPE_ANY, NULL, LAYER_ATTRIBUTES_NONE); if (ret != CL_CLEAN) { cli_dbgmsg("cli_scandmg: retcode from scanning TOC xml: %s\n", cl_strerror(ret)); - if (!ctx->engine->keeptmp) + if (!ctx->engine->keeptmp) { cli_rmdirs(dirname); + } free(dirname); return ret; } @@ -183,8 +184,9 @@ int cli_scandmg(cli_ctx *ctx) outdata = fmap_need_off_once_len(ctx->fmap, hdr.xmlOffset, hdr.xmlLength, &nread); if (!outdata || (nread != hdr.xmlLength)) { cli_errmsg("cli_scandmg: Failed getting XML from map, len %d\n", (int)hdr.xmlLength); - if (!ctx->engine->keeptmp) + if (!ctx->engine->keeptmp) { cli_rmdirs(dirname); + } free(dirname); return CL_EMAP; } @@ -199,8 +201,9 @@ int cli_scandmg(cli_ctx *ctx) reader = xmlReaderForMemory(outdata, (int)hdr.xmlLength, "toc.xml", NULL, DMG_XML_PARSE_OPTS); if (!reader) { cli_dbgmsg("cli_scandmg: Failed parsing XML!\n"); - if (!ctx->engine->keeptmp) + if (!ctx->engine->keeptmp) { cli_rmdirs(dirname); + } free(dirname); return CL_EFORMAT; } @@ -229,8 +232,9 @@ int cli_scandmg(cli_ctx *ctx) break; } nodeName = xmlTextReaderLocalName(reader); - if (!nodeName) + if (!nodeName) { continue; + } dmg_parsemsg("read: name %s depth %d\n", nodeName, depth); if ((state == DMG_FIND_DATA_MISH) && (depth == stateDepth[state - 1])) { @@ -440,8 +444,9 @@ int cli_scandmg(cli_ctx *ctx) mish_list = mish_list->next; free(mish_list_tail); } - if (!ctx->engine->keeptmp) + if (!ctx->engine->keeptmp) { cli_rmdirs(dirname); + } free(dirname); return ret; } @@ -466,8 +471,9 @@ static int dmg_decode_mish(cli_ctx *ctx, unsigned int *mishblocknum, xmlChar *mi buff_size = 3 * base64_len / 4 + 4; dmg_parsemsg("dmg_decode_mish: buffer for mish block %u is %lu\n", *mishblocknum, (unsigned long)buff_size); decoded = cli_max_malloc(buff_size); - if (!decoded) + if (!decoded) { return CL_EMEM; + } if (sf_base64decode((uint8_t *)mish_base64, base64_len, decoded, buff_size - 1, &decoded_len)) { cli_dbgmsg("dmg_decode_mish: failed base64 decoding on mish block %u\n", *mishblocknum); @@ -593,8 +599,9 @@ static int dmg_stripe_zeroes(cli_ctx *ctx, int fd, uint32_t index, struct dmg_mi UNUSEDPARAM(ctx); cli_dbgmsg("dmg_stripe_zeroes: stripe " STDu32 "\n", index); - if (len == 0) + if (len == 0) { return CL_CLEAN; + } memset(obuf, 0, sizeof(obuf)); while (len > sizeof(obuf)) { @@ -629,8 +636,9 @@ static int dmg_stripe_store(cli_ctx *ctx, int fd, uint32_t index, struct dmg_mis size_t written; cli_dbgmsg("dmg_stripe_store: stripe " STDu32 "\n", index); - if (len == 0) + if (len == 0) { return CL_CLEAN; + } obuf = (void *)fmap_need_off_once(ctx->fmap, off, len); if (!obuf) { @@ -661,8 +669,9 @@ static int dmg_stripe_adc(cli_ctx *ctx, int fd, uint32_t index, struct dmg_mish_ cli_dbgmsg("dmg_stripe_adc: stripe " STDu32 " initial len " STDu64 " expected len " STDu64 "\n", index, (uint64_t)len, (uint64_t)expected_len); - if (len == 0) + if (len == 0) { return CL_CLEAN; + } memset(&strm, 0, sizeof(strm)); strm.next_in = (uint8_t *)fmap_need_off_once(ctx->fmap, off, len); @@ -714,8 +723,9 @@ static int dmg_stripe_adc(cli_ctx *ctx, int fd, uint32_t index, struct dmg_mish_ strm.next_out = obuf; strm.avail_out = sizeof(obuf); } - if (adcret == ADC_STREAM_END) + if (adcret == ADC_STREAM_END) { break; + } cli_dbgmsg("dmg_stripe_adc: after writing " STDu64 " bytes, " "got error %d decompressing stripe " STDu32 "\n", size_so_far, adcret, index); @@ -743,8 +753,9 @@ static int dmg_stripe_inflate(cli_ctx *ctx, int fd, uint32_t index, struct dmg_m uint8_t obuf[BUFSIZ]; cli_dbgmsg("dmg_stripe_inflate: stripe " STDu32 "\n", index); - if (len == 0) + if (len == 0) { return CL_CLEAN; + } memset(&strm, 0, sizeof(strm)); strm.next_in = (void *)fmap_need_off_once(ctx->fmap, off, len); @@ -795,17 +806,19 @@ static int dmg_stripe_inflate(cli_ctx *ctx, int fd, uint32_t index, struct dmg_m size_so_far += written; strm.next_out = (Bytef *)obuf; strm.avail_out = sizeof(obuf); - if (zstat == Z_STREAM_END) + if (zstat == Z_STREAM_END) { break; + } } - if (strm.msg) + if (strm.msg) { cli_dbgmsg("dmg_stripe_inflate: after writing " STDu64 " bytes, " "got error \"%s\" inflating stripe " STDu32 "\n", size_so_far, strm.msg, index); - else + } else { cli_dbgmsg("dmg_stripe_inflate: after writing " STDu64 " bytes, " "got error %d inflating stripe " STDu32 "\n", size_so_far, zstat, index); + } inflateEnd(&strm); return CL_EFORMAT; } @@ -904,8 +917,9 @@ static int dmg_stripe_bzip(cli_ctx *ctx, int fd, uint32_t index, struct dmg_mish strm.next_out = (char *)obuf; strm.avail_out = sizeof(obuf); - if (rc == BZ_OK) + if (rc == BZ_OK) { rc = BZ2_bzDecompress(&strm); + } if ((rc != BZ_OK) && (rc != BZ_STREAM_END)) { cli_dbgmsg("dmg_stripe_bzip: decompress error: %d\n", rc); ret = CL_EFORMAT; @@ -1052,8 +1066,11 @@ static int dmg_handle_mish(cli_ctx *ctx, unsigned int mishblocknum, char *dir, } close(ofd); - if (!ctx->engine->keeptmp) - if (cli_unlink(outfile)) return CL_EUNLINK; + if (!ctx->engine->keeptmp) { + if (cli_unlink(outfile)) { + return CL_EUNLINK; + } + } return ret; } diff --git a/libclamav/dsig.c b/libclamav/dsig.c index 579b4df2c7..1146ca01e6 100644 --- a/libclamav/dsig.c +++ b/libclamav/dsig.c @@ -73,9 +73,11 @@ static char cli_ndecode(unsigned char value) '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'}; - for (i = 0; i < 64; i++) - if (ncodec[i] == value) + for (i = 0; i < 64; i++) { + if (ncodec[i] == value) { return i; + } + } cli_errmsg("cli_ndecode: value out of range\n"); return -1; @@ -230,12 +232,13 @@ char *cli_getdsig(const char *host, const char *user, const unsigned char *data, } memset(cmd, 0, sizeof(cmd)); - if (mode == 1) + if (mode == 1) { snprintf(cmd, sizeof(cmd) - datalen, "ClamSign:%s:%s:", user, pass); - else if (mode == 2) + } else if (mode == 2) { snprintf(cmd, sizeof(cmd) - datalen, "ClamSignPSS:%s:%s:", user, pass); - else + } else { snprintf(cmd, sizeof(cmd) - datalen, "ClamSignPSS2:%s:%s:", user, pass); + } len = strlen(cmd); pt = cmd + len; @@ -285,19 +288,23 @@ cl_error_t cli_versig(const char *md5, const char *dsig) ret = CL_EMEM; n = BN_new(); - if (!n) + if (!n) { goto done; + } e = BN_new(); - if (!e) + if (!e) { goto done; + } ret = CL_EVERIFY; - if (!BN_dec2bn(&e, CLI_ESTR)) + if (!BN_dec2bn(&e, CLI_ESTR)) { goto done; + } - if (!BN_dec2bn(&n, CLI_NSTR)) + if (!BN_dec2bn(&n, CLI_NSTR)) { goto done; + } if (strlen(md5) != 32 || !isalnum(md5[0])) { /* someone is trying to fool us with empty/malformed MD5 ? */ @@ -305,8 +312,9 @@ cl_error_t cli_versig(const char *md5, const char *dsig) goto done; } - if (!(pt = (char *)cli_decodesig(dsig, 16, e, n))) + if (!(pt = (char *)cli_decodesig(dsig, 16, e, n))) { goto done; + } pt2 = cli_str2hex(pt, 16); @@ -351,11 +359,13 @@ int cli_versig2(const unsigned char *sha256, const char *dsig_str, const char *n } ret = CL_EVERIFY; - if (!BN_dec2bn(&e, e_str)) + if (!BN_dec2bn(&e, e_str)) { goto done; + } - if (!BN_dec2bn(&n, n_str)) + if (!BN_dec2bn(&n, n_str)) { goto done; + } decoded = cli_decodesig(dsig_str, PAD_LEN, e, n); if (!decoded) { @@ -385,36 +395,42 @@ int cli_versig2(const unsigned char *sha256, const char *dsig_str, const char *n c[3] = (unsigned char)i; ctx = cl_hash_init("sha256"); - if (!(ctx)) + if (!(ctx)) { return CL_EMEM; + } cl_update_hash(ctx, digest2, HASH_LEN); cl_update_hash(ctx, c, 4); cl_finish_hash(ctx, digest3); - if (i + 1 == rounds) + if (i + 1 == rounds) { memcpy(&data[i * 32], digest3, BLK_LEN - i * HASH_LEN); - else + } else { memcpy(&data[i * 32], digest3, HASH_LEN); + } } - for (i = 0; i < BLK_LEN; i++) + for (i = 0; i < BLK_LEN; i++) { data[i] ^= mask[i]; + } data[0] &= (0xff >> 1); - if (!(salt = memchr(data, 0x01, BLK_LEN))) + if (!(salt = memchr(data, 0x01, BLK_LEN))) { return CL_EVERIFY; + } salt++; - if (data + BLK_LEN - salt != SALT_LEN) + if (data + BLK_LEN - salt != SALT_LEN) { return CL_EVERIFY; + } memset(final, 0, 8); memcpy(&final[8], sha256, HASH_LEN); memcpy(&final[8 + HASH_LEN], salt, SALT_LEN); ctx = cl_hash_init("sha256"); - if (!(ctx)) + if (!(ctx)) { return CL_EMEM; + } cl_update_hash(ctx, final, sizeof(final)); cl_finish_hash(ctx, digest1); diff --git a/libclamav/egg.c b/libclamav/egg.c index 428b21b105..af1ef33b13 100644 --- a/libclamav/egg.c +++ b/libclamav/egg.c @@ -1023,8 +1023,9 @@ static void print_posix_info_mode(uint32_t mode) printf("-"); } /* Sticky Bit */ - if (mode & POSIX_INFO_MODE_STICKY_BIT) + if (mode & POSIX_INFO_MODE_STICKY_BIT) { printf("t"); + } printf("\n"); } @@ -1112,20 +1113,23 @@ static cl_error_t egg_parse_file_extra_field(egg_handle* handle, egg_file* eggFi goto done; } - if (extraField->bit_flag & FILENAME_HEADER_FLAGS_ENCRYPT) + if (extraField->bit_flag & FILENAME_HEADER_FLAGS_ENCRYPT) { cli_dbgmsg("egg_parse_file_extra_field: filename_header->bit_flag: encrypted\n"); - else + } else { cli_dbgmsg("egg_parse_file_extra_field: filename_header->bit_flag: not encrypted\n"); + } - if (extraField->bit_flag & FILENAME_HEADER_FLAGS_RELATIVE_PATH_INSTEAD_OF_ABSOLUTE) + if (extraField->bit_flag & FILENAME_HEADER_FLAGS_RELATIVE_PATH_INSTEAD_OF_ABSOLUTE) { cli_dbgmsg("egg_parse_file_extra_field: filename_header->bit_flag: relative-path\n"); - else + } else { cli_dbgmsg("egg_parse_file_extra_field: filename_header->bit_flag: absolute-path\n"); + } - if (extraField->bit_flag & FILENAME_HEADER_FLAGS_MULTIBYTE_CODEPAGE_INSTEAD_OF_UTF8) + if (extraField->bit_flag & FILENAME_HEADER_FLAGS_MULTIBYTE_CODEPAGE_INSTEAD_OF_UTF8) { cli_dbgmsg("egg_parse_file_extra_field: filename_header->bit_flag: Windows Multibyte + codepage\n"); - else + } else { cli_dbgmsg("egg_parse_file_extra_field: filename_header->bit_flag: UTF-8\n"); + } if (extraField->bit_flag & FILENAME_HEADER_FLAGS_MULTIBYTE_CODEPAGE_INSTEAD_OF_UTF8) { /* Utf-8 - header will include locale */ @@ -1802,10 +1806,11 @@ cl_error_t cli_egg_open(fmap_t* map, void** hArchive, char*** comments, uint32_t if (CL_SUCCESS != retval) { if (CL_BREAK == retval) { /* End of archive. */ - if ((handle->bSplit) && (handle->splitInfo->next_file_id != 0)) + if ((handle->bSplit) && (handle->splitInfo->next_file_id != 0)) { cli_warnmsg("cli_egg_open: Abrupt end to EGG volume!\n"); - else + } else { cli_dbgmsg("cli_egg_open: End of EGG volume in split archive.\n"); + } } else { /* Something went wrong. */ cli_warnmsg("cli_egg_open: Failed to parse file headers!\n"); @@ -1900,13 +1905,15 @@ cl_error_t cli_egg_peek_file_header(void* hArchive, cl_egg_metadata* file_metada file_metadata->filename = strdup(currFile->filename.name_utf8); - if (NULL != currFile->encrypt) + if (NULL != currFile->encrypt) { file_metadata->encrypted = 1; + } - if (currFile->posixFileInformation && currFile->posixFileInformation->mode & POSIX_INFO_MODE_DIRECTORY) + if (currFile->posixFileInformation && currFile->posixFileInformation->mode & POSIX_INFO_MODE_DIRECTORY) { file_metadata->is_dir = 1; - else if (currFile->windowsFileInformation && currFile->windowsFileInformation->attribute & WINDOWS_INFO_ATTRIBUTE_DIRECTORY) + } else if (currFile->windowsFileInformation && currFile->windowsFileInformation->attribute & WINDOWS_INFO_ATTRIBUTE_DIRECTORY) { file_metadata->is_dir = 1; + } status = CL_SUCCESS; done: @@ -2002,12 +2009,13 @@ cl_error_t cli_egg_deflate_decompress(char* compressed, size_t compressed_size, case Z_DATA_ERROR: case Z_MEM_ERROR: default: - if (stream.msg) + if (stream.msg) { cli_dbgmsg("cli_egg_deflate_decompress: after decompressing %lu bytes, got error \"%s\"\n", (unsigned long)declen, stream.msg); - else + } else { cli_dbgmsg("cli_egg_deflate_decompress: after decompressing %lu bytes, got error %d\n", (unsigned long)declen, zstat); + } if (declen == 0) { cli_dbgmsg("cli_egg_deflate_decompress: no bytes were decompressed.\n"); diff --git a/libclamav/elf.c b/libclamav/elf.c index 951b1c7a8c..f6a1b09d7d 100644 --- a/libclamav/elf.c +++ b/libclamav/elf.c @@ -136,8 +136,9 @@ static cl_error_t cli_elf_fileheader(cli_ctx *ctx, fmap_t *map, union elf_file_h /* Need to know to endian convert */ if (file_hdr->hdr64.e_ident[5] == 1) { #if WORDS_BIGENDIAN == 0 - if (ctx) + if (ctx) { cli_dbgmsg("ELF: File is little-endian - conversion not required\n"); + } conv = 0; #else if (ctx) @@ -146,8 +147,9 @@ static cl_error_t cli_elf_fileheader(cli_ctx *ctx, fmap_t *map, union elf_file_h #endif } else { #if WORDS_BIGENDIAN == 0 - if (ctx) + if (ctx) { cli_dbgmsg("ELF: File is big-endian - data conversion enabled\n"); + } conv = 1; #else if (ctx) @@ -256,8 +258,9 @@ static int cli_elf_ph32(cli_ctx *ctx, fmap_t *map, struct cli_exe_info *elfinfo, for (i = 0; i < phnum; i++) { err = 0; - if (fmap_readn(map, &program_hdr[i], phoff, sizeof(struct elf_program_hdr32)) != sizeof(struct elf_program_hdr32)) + if (fmap_readn(map, &program_hdr[i], phoff, sizeof(struct elf_program_hdr32)) != sizeof(struct elf_program_hdr32)) { err = 1; + } phoff += sizeof(struct elf_program_hdr32); if (err) { @@ -356,8 +359,9 @@ static cl_error_t cli_elf_ph64(cli_ctx *ctx, fmap_t *map, struct cli_exe_info *e for (i = 0; i < phnum; i++) { err = 0; - if (fmap_readn(map, &program_hdr[i], phoff, sizeof(struct elf_program_hdr64)) != sizeof(struct elf_program_hdr64)) + if (fmap_readn(map, &program_hdr[i], phoff, sizeof(struct elf_program_hdr64)) != sizeof(struct elf_program_hdr64)) { err = 1; + } phoff += sizeof(struct elf_program_hdr64); if (err) { @@ -441,8 +445,9 @@ static int cli_elf_sh32(cli_ctx *ctx, fmap_t *map, struct cli_exe_info *elfinfo, } shoff = file_hdr->e_shoff; - if (ctx) + if (ctx) { cli_dbgmsg("ELF: Section header table offset: %d\n", shoff); + } if (elfinfo) { elfinfo->sections = (struct cli_exe_section *)cli_max_calloc(shnum, sizeof(struct cli_exe_section)); @@ -540,8 +545,9 @@ static int cli_elf_sh64(cli_ctx *ctx, fmap_t *map, struct cli_exe_info *elfinfo, } shoff = file_hdr->e_shoff; - if (ctx) + if (ctx) { cli_dbgmsg("ELF: Section header table offset: " STDu64 "\n", shoff); + } if (elfinfo) { elfinfo->sections = (struct cli_exe_section *)cli_max_calloc(shnum, sizeof(struct cli_exe_section)); @@ -661,14 +667,17 @@ static void cli_elf_sectionlog(uint32_t sh_type, uint32_t sh_flags) cli_dbgmsg("ELF: Section type: Unknown\n"); } - if (sh_flags & ELF_SHF_WRITE) + if (sh_flags & ELF_SHF_WRITE) { cli_dbgmsg("ELF: Section contains writable data\n"); + } - if (sh_flags & ELF_SHF_ALLOC) + if (sh_flags & ELF_SHF_ALLOC) { cli_dbgmsg("ELF: Section occupies memory\n"); + } - if (sh_flags & ELF_SHF_EXECINSTR) + if (sh_flags & ELF_SHF_EXECINSTR) { cli_dbgmsg("ELF: Section contains executable code\n"); + } } /* Scan function for ELF */ diff --git a/libclamav/entconv.c b/libclamav/entconv.c index 37770cbf95..8d19306556 100644 --- a/libclamav/entconv.c +++ b/libclamav/entconv.c @@ -486,20 +486,25 @@ static char* normalize_encoding(const unsigned char* enc) char* norm; size_t i, len; - if (!enc) + if (!enc) { return NULL; + } len = strlen((const char*)enc); - if (len > 32) + if (len > 32) { return NULL; + } for (i = 0; i < len; i++) { - if (!encname_chars[enc[i]]) + if (!encname_chars[enc[i]]) { return NULL; + } } norm = cli_max_malloc(len + 1); - if (!norm) + if (!norm) { return NULL; - for (i = 0; i < len; i++) + } + for (i = 0; i < len; i++) { norm[i] = toupper(enc[i]); + } norm[len] = '\0'; return norm; } @@ -747,7 +752,9 @@ static int in_iconv_u16(const m_area_t* in_m_area, iconv_t* iconv_struct, m_area inleft, outleft, input - (char*)in_m_area->buffer, out - (char*)out_m_area->buffer);*/ /* output raw byte, and resume at next byte */ - if (outleft < 2) break; + if (outleft < 2) { + break; + } outleft -= 2; *out++ = 0; *out++ = *input++; @@ -858,14 +865,16 @@ cl_error_t cli_codepage_to_utf8(char* in, size_t in_size, uint16_t codepage, cha /* locate the start of the last character */ for (byte_count = 1; (track != out_utf8); track--, byte_count++) { - if (((uint8_t)*track & 0xC0) != 0x80) + if (((uint8_t)*track & 0xC0) != 0x80) { break; + } } /* count number of set (1) significant bits */ for (sigbit_count = 0; sigbit_count < (int)(sizeof(uint8_t) * 8); sigbit_count++) { - if (((uint8_t)*track & (0x80 >> sigbit_count)) == 0) + if (((uint8_t)*track & (0x80 >> sigbit_count)) == 0) { break; + } } if (byte_count != sigbit_count) { @@ -1136,11 +1145,13 @@ char* cli_utf16toascii(const char* str, unsigned int length) return NULL; } - if (length % 2) + if (length % 2) { length--; + } - if (!(decoded = cli_max_calloc(length / 2 + 1, sizeof(char)))) + if (!(decoded = cli_max_calloc(length / 2 + 1, sizeof(char)))) { return NULL; + } for (i = 0, j = 0; i < length; i += 2, j++) { decoded[j] = ((unsigned char)str[i + 1]) << 4; @@ -1159,32 +1170,36 @@ char* cli_utf16_to_utf8(const char* utf16, size_t length, encoding_t type) size_t needed = length * 3 / 2 + 2; char* s2; - if (length < 2) + if (length < 2) { return cli_safer_strdup(""); + } if (length % 2) { cli_warnmsg("utf16 length is not multiple of two: %lu\n", (long)length); length--; } s2 = cli_max_malloc(needed); - if (!s2) + if (!s2) { return NULL; + } i = 0; if ((utf16[0] == '\xff' && utf16[1] == '\xfe') || (utf16[0] == '\xfe' && utf16[1] == '\xff')) { i += 2; - if (type == E_UTF16) + if (type == E_UTF16) { type = (utf16[0] == '\xff') ? E_UTF16_LE : E_UTF16_BE; + } } else if (type == E_UTF16) { type = E_UTF16_BE; } for (j = 0; i < length && j < needed; i += 2) { uint16_t c = cli_readint16(&utf16[i]); - if (type == E_UTF16_BE) + if (type == E_UTF16_BE) { c = cbswap16(c); + } if (c < 0x80) { s2[j++] = c; } else if (c < 0x800) { @@ -1216,8 +1231,9 @@ char* cli_utf16_to_utf8(const char* utf16, size_t length, encoding_t type) s2[j++] = 0xbd; } } - if (j >= needed) + if (j >= needed) { j = needed - 1; + } s2[j] = '\0'; return s2; } @@ -1254,11 +1270,13 @@ int cli_isutf8(const char* buf, unsigned int len) } for (j = 0; j < following; j++) { - if (++i >= len) + if (++i >= len) { return 0; + } - if ((buf[i] & 0x80) == 0 || (buf[i] & 0x40)) + if ((buf[i] & 0x80) == 0 || (buf[i] & 0x40)) { return 0; + } /* c = (c << 6) + (buf[i] & 0x3f); */ } diff --git a/libclamav/events.c b/libclamav/events.c index 982682aa59..0c9a1f4e81 100644 --- a/libclamav/events.c +++ b/libclamav/events.c @@ -51,8 +51,9 @@ struct cli_events { cli_events_t *cli_events_new(unsigned max_event) { struct cli_events *ev = calloc(1, sizeof(*ev)); - if (!ev) + if (!ev) { return NULL; + } ev->max = max_event; ev->events = calloc(max_event, sizeof(*ev->events)); if (!ev->events) { @@ -76,13 +77,15 @@ void cli_events_free(cli_events_t *ev) void cli_event_error_oom(cli_events_t *ctx, uint32_t amount) { - if (!ctx) + if (!ctx) { return; + } ctx->oom_total += amount; ctx->oom_count++; /* amount == 0 means error already reported, just increment count */ - if (amount) + if (amount) { cli_errmsg("events: out of memory allocating %u bytes\n", amount); + } } int cli_event_define(cli_events_t *ctx, unsigned id, @@ -111,15 +114,17 @@ int cli_event_define(cli_events_t *ctx, unsigned id, ev->name = name; ev->type = type; ev->multiple = multiple; - if (type == ev_data_fast) + if (type == ev_data_fast) { ev->u.v_int = CRC_INIT_VAL; + } return 0; } static inline struct cli_event *get_event(cli_events_t *ctx, unsigned id) { - if (!ctx) + if (!ctx) { return NULL; + } if (id >= ctx->max) { cli_event_error_str(ctx, "event id out of range"); return NULL; @@ -145,16 +150,18 @@ static inline void ev_chain(cli_events_t *ctx, struct cli_event *ev, union ev_va const char *cli_event_get_name(cli_events_t *ctx, unsigned id) { struct cli_event *ev = get_event(ctx, id); - if (!ev) + if (!ev) { return NULL; + } return ev->name; } void cli_event_int(cli_events_t *ctx, unsigned id, uint64_t arg) { struct cli_event *ev = get_event(ctx, id); - if (!ev) + if (!ev) { return; + } if (ev->type != ev_int) { cli_event_error_str(ctx, "cli_event_int must be called with ev_int type"); return; @@ -184,8 +191,9 @@ void cli_event_time_start(cli_events_t *ctx, unsigned id) { struct timeval tv; struct cli_event *ev = get_event(ctx, id); - if (!ev) + if (!ev) { return; + } if (ev->type != ev_time) { cli_event_error_str(ctx, "cli_event_time* must be called with ev_time type"); return; @@ -200,8 +208,9 @@ void cli_event_time_nested_start(cli_events_t *ctx, unsigned id, unsigned nested struct timeval tv; struct cli_event *ev = get_event(ctx, id); struct cli_event *evnested = get_event(ctx, nestedid); - if (!ev || !evnested) + if (!ev || !evnested) { return; + } if (ev->type != ev_time || evnested->type != ev_time) { cli_event_error_str(ctx, "cli_event_time* must be called with ev_time type"); return; @@ -216,8 +225,9 @@ void cli_event_time_stop(cli_events_t *ctx, unsigned id) { struct timeval tv; struct cli_event *ev = get_event(ctx, id); - if (!ev) + if (!ev) { return; + } if (ev->type != ev_time) { cli_event_error_str(ctx, "cli_event_time* must be called with ev_time type"); return; @@ -231,8 +241,9 @@ void cli_event_time_nested_stop(cli_events_t *ctx, unsigned id, unsigned nestedi struct timeval tv; struct cli_event *ev = get_event(ctx, id); struct cli_event *evnested = get_event(ctx, nestedid); - if (!ev || !evnested) + if (!ev || !evnested) { return; + } if (ev->type != ev_time || evnested->type != ev_time) { cli_event_error_str(ctx, "cli_event_time* must be called with ev_time type"); return; @@ -244,8 +255,9 @@ void cli_event_time_nested_stop(cli_events_t *ctx, unsigned id, unsigned nestedi static void event_string(cli_events_t *ctx, struct cli_event *ev, const char *str) { - if (!str) + if (!str) { str = ""; + } switch (ev->multiple) { case multiple_last: ev->u.v_string = str; @@ -265,8 +277,9 @@ static void event_string(cli_events_t *ctx, struct cli_event *ev, const char *st void cli_event_error_str(cli_events_t *ctx, const char *str) { - if (!ctx) + if (!ctx) { return; + } cli_warnmsg("events: %s\n", str); event_string(ctx, &ctx->errors, str); } @@ -274,8 +287,9 @@ void cli_event_error_str(cli_events_t *ctx, const char *str) void cli_event_string(cli_events_t *ctx, unsigned id, const char *str) { struct cli_event *ev = get_event(ctx, id); - if (!ev) + if (!ev) { return; + } if (ev->type != ev_string) { cli_event_error_str(ctx, "cli_event_string must be called with ev_string type"); return; @@ -286,8 +300,9 @@ void cli_event_string(cli_events_t *ctx, unsigned id, const char *str) void cli_event_data(cli_events_t *ctx, unsigned id, const void *data, uint32_t len) { struct cli_event *ev = get_event(ctx, id); - if (!ev) + if (!ev) { return; + } if (ev->type != ev_data) { cli_event_error_str(ctx, "cli_event_string must be called with ev_data type"); return; @@ -324,8 +339,9 @@ void cli_event_data(cli_events_t *ctx, unsigned id, const void *data, uint32_t l void cli_event_fastdata(cli_events_t *ctx, unsigned id, const void *data, uint32_t len) { struct cli_event *ev = get_event(ctx, id); - if (!ev) + if (!ev) { return; + } if (ev->type != ev_data_fast) { cli_event_error_str(ctx, "cli_event_fastdata must be called with ev_data_fast"); return; @@ -344,8 +360,9 @@ void cli_event_count(cli_events_t *ctx, unsigned id) void cli_event_get(cli_events_t *ctx, unsigned id, union ev_val *val, uint32_t *count) { struct cli_event *ev = get_event(ctx, id); - if (!ev) + if (!ev) { return; + } memcpy(val, &ev->u, sizeof(*val)); *count = ev->count; } @@ -401,14 +418,16 @@ void cli_event_debug(cli_events_t *ctx, unsigned id) { const char *tstr; struct cli_event *ev = get_event(ctx, id); - if (!ev) + if (!ev) { return; + } tstr = evtype(ev->type); if (ev->multiple == multiple_chain && ev->type != ev_data) { unsigned i; cli_dbgmsg("%s: ev_chain %u %s\n", ev->name, ev->count, tstr); - for (i = 0; i < ev->count; i++) + for (i = 0; i < ev->count; i++) { ev_debug(ev->type, &ev->u.v_chain[i], i); + } } else { cli_dbgmsg("%s: %s\n", ev->name, tstr); ev_debug(ev->type, &ev->u, ev->count); @@ -419,8 +438,9 @@ void cli_event_debug_all(cli_events_t *ctx) { unsigned i; for (i = 0; i < ctx->max; i++) { - if (ctx->events[i].count) + if (ctx->events[i].count) { cli_event_debug(ctx, i); + } } } @@ -449,8 +469,9 @@ int cli_event_diff(cli_events_t *ctx1, cli_events_t *ctx2, unsigned id) struct cli_event *ev1, *ev2; ev1 = get_event(ctx1, id); ev2 = get_event(ctx2, id); - if (!ev1 || !ev2) + if (!ev1 || !ev2) { return 1; + } if (ev1->type != ev2->type || ev1->multiple != ev2->multiple || ev1->name != ev2->name) { @@ -467,8 +488,9 @@ int cli_event_diff(cli_events_t *ctx1, cli_events_t *ctx2, unsigned id) for (i = 0; i < ev1->count; i++) { unsigned di = ev_diff(ev1->type, &ev1->u.v_chain[i], &ev2->u.v_chain[i], ev1->count); if (di) { - if (!diff) + if (!diff) { cli_dbgmsg("diff: %s\n", ev1->name); + } ev_debug(ev1->type, &ev1->u.v_chain[i], i); ev_debug(ev2->type, &ev2->u.v_chain[i], i); } @@ -482,8 +504,9 @@ int cli_event_diff(cli_events_t *ctx1, cli_events_t *ctx2, unsigned id) ev_debug(ev2->type, &ev2->u, ev2->count); } } - if (!diff) + if (!diff) { return 0; + } return 1; } @@ -497,8 +520,9 @@ int cli_event_diff_all(cli_events_t *ctx1, cli_events_t *ctx2, compare_filter_t } for (i = 0; i < ctx1->max; i++) { struct cli_event *ev1 = &ctx1->events[i]; - if (filter && filter(i, ev1->type)) + if (filter && filter(i, ev1->type)) { continue; + } diff += cli_event_diff(ctx1, ctx2, i); } return diff ? 1 : 0; @@ -506,7 +530,8 @@ int cli_event_diff_all(cli_events_t *ctx1, cli_events_t *ctx2, compare_filter_t int cli_event_errors(cli_events_t *ctx) { - if (!ctx) + if (!ctx) { return 0; + } return ctx->errors.count + ctx->oom_count; } diff --git a/libclamav/explode.c b/libclamav/explode.c index f221231113..ecbc4310fa 100644 --- a/libclamav/explode.c +++ b/libclamav/explode.c @@ -60,7 +60,9 @@ static void bs(uint8_t *k, uint8_t *v, unsigned int elements) stop = 0; } } - if (stop) break; + if (stop) { + break; + } r--; i--; for (; i > l; i--) { @@ -86,7 +88,9 @@ static int unpack_tree(struct xplstate *X, uint32_t *tree, unsigned int expected packsz = *cur++; - for (i = 0; i < expected; i++) order[i] = i; + for (i = 0; i < expected; i++) { + order[i] = i; + } i = expected; @@ -95,13 +99,18 @@ static int unpack_tree(struct xplstate *X, uint32_t *tree, unsigned int expected values = *cur++; len = (values & 15) + 1; values = (values >> 4) + 1; - if (values > i) return 1; + if (values > i) { + return 1; + } i -= values; - while (values--) + while (values--) { *ttree++ = len; + } } while (packsz--); - if (i) return 1; + if (i) { + return 1; + } bs(order, temptree, expected - 1); @@ -123,8 +132,11 @@ static int lookup_tree(uint32_t *tree, unsigned int size, uint16_t code, uint8_t { uint32_t lookup = ((uint32_t)(len + 1)) << 16 | code; unsigned int i; - for (i = 0; i < size; i++) - if (tree[i] == lookup) return i; + for (i = 0; i < size; i++) { + if (tree[i] == lookup) { + return i; + } + } return -1; } @@ -260,9 +272,13 @@ int explode(struct xplstate *X) case EXPLODE_LITCODES: GETBIT; X->backsize |= val << (15 - X->got); - if ((temp = lookup_tree(X->lit_tree, 256, X->backsize, X->got)) != -1) break; + if ((temp = lookup_tree(X->lit_tree, 256, X->backsize, X->got)) != -1) { + break; + } + } + if (temp == -1) { + return EXPLODE_ESTREAM; } - if (temp == -1) return EXPLODE_ESTREAM; X->got = temp; } else { SETCASE(EXPLODE_LITS); @@ -270,7 +286,9 @@ int explode(struct xplstate *X) X->got = val; } SETCASE(EXPLODE_WBYTE); - if (!X->avail_out) return EXPLODE_EBUFF; + if (!X->avail_out) { + return EXPLODE_EBUFF; + } X->avail_out--; *X->next_out = X->window[X->cur & X->mask] = X->got; X->cur++; @@ -285,9 +303,13 @@ int explode(struct xplstate *X) case EXPLODE_DECODEDISTS: GETBIT; X->backsize |= val << (15 - X->got); - if ((temp = lookup_tree(X->dist_tree, 64, X->backsize, X->got)) != -1) break; + if ((temp = lookup_tree(X->dist_tree, 64, X->backsize, X->got)) != -1) { + break; + } + } + if (temp == -1) { + return EXPLODE_ESTREAM; } - if (temp == -1) return EXPLODE_ESTREAM; X->backbytes |= temp << (6 + X->largewin); X->backbytes++; X->backsize = 0; @@ -296,9 +318,13 @@ int explode(struct xplstate *X) case EXPLODE_DECODELENS: GETBIT; X->backsize |= val << (15 - X->got); - if ((temp = lookup_tree(X->len_tree, 64, X->backsize, X->got)) != -1) break; + if ((temp = lookup_tree(X->len_tree, 64, X->backsize, X->got)) != -1) { + break; + } + } + if (temp == -1) { + return EXPLODE_ESTREAM; } - if (temp == -1) return EXPLODE_ESTREAM; if (temp == 63) { SETCASE(EXPLODE_DECODEEXTRA); @@ -309,12 +335,15 @@ int explode(struct xplstate *X) X->state = EXPLODE_BACKCOPY; while (X->backsize--) { case EXPLODE_BACKCOPY: - if (!X->avail_out) return EXPLODE_EBUFF; + if (!X->avail_out) { + return EXPLODE_EBUFF; + } X->avail_out--; - if (X->cur >= X->backbytes) + if (X->cur >= X->backbytes) { *X->next_out = X->window[X->cur & X->mask] = X->window[(X->cur - X->backbytes) & X->mask]; - else + } else { *X->next_out = X->window[X->cur & X->mask] = 0; + } X->cur++; X->next_out++; } diff --git a/libclamav/filetypes.c b/libclamav/filetypes.c index a31006a91a..29e5b92358 100644 --- a/libclamav/filetypes.c +++ b/libclamav/filetypes.c @@ -151,9 +151,11 @@ cli_file_t cli_ftcode(const char *name) { unsigned int i; - for (i = 0; ftmap[i].name; i++) - if (!strcmp(ftmap[i].name, name)) + for (i = 0; ftmap[i].name; i++) { + if (!strcmp(ftmap[i].name, name)) { return ftmap[i].code; + } + } return CL_TYPE_ERROR; } @@ -162,9 +164,11 @@ const char *cli_ftname(cli_file_t code) { unsigned int i; - for (i = 0; ftmap[i].name; i++) - if (ftmap[i].code == code) + for (i = 0; ftmap[i].name; i++) { + if (ftmap[i].code == code) { return ftmap[i].name; + } + } return NULL; } @@ -412,11 +416,13 @@ cli_file_t cli_determine_fmap_type(fmap_t *map, const struct cl_engine *engine, * misidentified as BINARY_DATA by cli_compare_ftm_file() */ root = engine->root[0]; - if (!root) + if (!root) { return ret; + } - if (cli_ac_initdata(&mdata, root->ac_partsigs, root->ac_lsigs, root->ac_reloff_num, CLI_DEFAULT_AC_TRACKLEN)) + if (cli_ac_initdata(&mdata, root->ac_partsigs, root->ac_lsigs, root->ac_reloff_num, CLI_DEFAULT_AC_TRACKLEN)) { return ret; + } scan_ret = (cli_file_t)cli_ac_scanbuff(buff, bread, NULL, NULL, NULL, engine->root[0], &mdata, 0, ret, NULL, AC_SCAN_FT, NULL); @@ -432,15 +438,17 @@ cli_file_t cli_determine_fmap_type(fmap_t *map, const struct cl_engine *engine, (scan_ret != CL_TYPE_7ZSFX))) { ret = scan_ret; } else { - if (cli_ac_initdata(&mdata, root->ac_partsigs, root->ac_lsigs, root->ac_reloff_num, CLI_DEFAULT_AC_TRACKLEN)) + if (cli_ac_initdata(&mdata, root->ac_partsigs, root->ac_lsigs, root->ac_reloff_num, CLI_DEFAULT_AC_TRACKLEN)) { return ret; + } decoded = (unsigned char *)cli_utf16toascii((char *)buff, bread); if (decoded) { scan_ret = (cli_file_t)cli_ac_scanbuff(decoded, bread / 2, NULL, NULL, NULL, engine->root[0], &mdata, 0, CL_TYPE_TEXT_ASCII, NULL, AC_SCAN_FT, NULL); free(decoded); - if (scan_ret == CL_TYPE_HTML) + if (scan_ret == CL_TYPE_HTML) { ret = CL_TYPE_HTML_UTF16; + } } cli_ac_freedata(&mdata); @@ -468,8 +476,9 @@ cli_file_t cli_determine_fmap_type(fmap_t *map, const struct cl_engine *engine, * However when detecting whether a file is HTML or not, we need exact conversion. * (just eliminating zeros and matching would introduce false positives */ if (encoding_normalize_toascii(&in_area, encoding, &out_area) >= 0 && out_area.length > 0) { - if (cli_ac_initdata(&mdata, root->ac_partsigs, root->ac_lsigs, root->ac_reloff_num, CLI_DEFAULT_AC_TRACKLEN)) + if (cli_ac_initdata(&mdata, root->ac_partsigs, root->ac_lsigs, root->ac_reloff_num, CLI_DEFAULT_AC_TRACKLEN)) { return ret; + } if (out_area.length > 0) { scan_ret = (cli_file_t)cli_ac_scanbuff(decodedbuff, out_area.length, NULL, NULL, NULL, engine->root[0], &mdata, 0, 0, NULL, AC_SCAN_FT, NULL); /* FIXME: can we use CL_TYPE_TEXT_ASCII instead of 0? */ diff --git a/libclamav/filtering.c b/libclamav/filtering.c index 290f6b8365..c97198d8e5 100644 --- a/libclamav/filtering.c +++ b/libclamav/filtering.c @@ -198,27 +198,33 @@ int filter_add_static(struct filter *m, const unsigned char *pattern, unsigned l if (len > MAXPATLEN) { len = MAXPATLEN; } - if (len < 2) + if (len < 2) { return -1; + } /* we want subsigs to be as long as possible */ if (len > 4) { maxlen = len - 4; - if (maxlen == 1) maxlen = 2; - } else + if (maxlen == 1) { + maxlen = 2; + } + } else { maxlen = 2; + } for (j = 0; (best < 100 && j < MAX_CHOICES) || (j < maxlen); j++) { uint32_t num = MAXSOPATLEN; uint8_t k; - if ((unsigned long)(j + 2) > len) + if ((unsigned long)(j + 2) > len) { break; + } for (k = j; k < len - 1 && (k - j < MAXSOPATLEN); k++) { q = cli_readint16(&pattern[k]); /* we want to favor subsigs that add as little as * possible to the filter */ num += filter_isset(m, k - j, q) ? 0 : MAXSOPATLEN - (k - j); - if ((k == j || k == j + 1) && (q == 0x0000 || q == 0xffff)) + if ((k == j || k == j + 1) && (q == 0x0000 || q == 0xffff)) { num += k == j ? 10000 : 1000; /* bad */ + } } /* it is very important to keep the end set small */ num += 10 * (filter_end_isset(m, k - j - 1, q) ? 0 : 1); @@ -226,8 +232,9 @@ int filter_add_static(struct filter *m, const unsigned char *pattern, unsigned l * */ num += 5 * (MAXSOPATLEN - (k - j)); /* if we are lower length than threshold penalize */ - if (k - j + 1 < 4) + if (k - j + 1 < 4) { num += 200; + } /* favour longer patterns */ num -= (2 * MAXSOPATLEN - (k + 1 + j)) * (k - j) / 2; @@ -332,16 +339,18 @@ static inline void get_score(enum badness badness, unsigned i, const struct filt base = -0x7fffff; break; case avoid_first: - if (!i) + if (!i) { base = -0x700000; - else + } else { base = 0; + } break; case avoid_anywhere: - if (!i) + if (!i) { base = -0x720000; - else + } else { base = -0x1000; + } break; case dontlike: base = 0; @@ -389,10 +398,12 @@ static inline void add_choice(struct choice *choices, unsigned *cnt, unsigned i, struct choice *choice; int i_neg = -1; assert(ie < MAXPATLEN); - if (ie < i + 1) + if (ie < i + 1) { return; - if (*cnt >= MAX_CHOICES) + } + if (*cnt >= MAX_CHOICES) { return; + } if (badness > avoid_first && *cnt >= (MAX_CHOICES >> 1)) { unsigned j; /* replace very bad picks if we're full */ @@ -419,8 +430,9 @@ static inline int32_t spec_iter(const struct char_spec *spec) unsigned count; assert(spec->step); count = (spec->step + spec->end - spec->start) / spec->step; - if (spec->negative) /* all chars except itself are added */ + if (spec->negative) { /* all chars except itself are added */ count *= 254; + } return count; } @@ -446,8 +458,9 @@ int filter_add_acpatt(struct filter *m, const struct cli_ac_patt *pat) j = MIN(prefix_len + pat->length[0], MAXPATLEN); for (i = 0; i < j; i++) { const uint16_t p = i < prefix_len ? pat->prefix[i] : pat->pattern[i - prefix_len]; - if ((p & CLI_MATCH_METADATA) != CLI_MATCH_CHAR) + if ((p & CLI_MATCH_METADATA) != CLI_MATCH_CHAR) { break; + } patc[i] = (uint8_t)p; } if (i == j) { @@ -460,8 +473,9 @@ int filter_add_acpatt(struct filter *m, const struct cli_ac_patt *pat) if (!prefix_len) { while ((pat->pattern[i] & CLI_MATCH_METADATA) == CLI_MATCH_SPECIAL) { /* we support only ALT_CHAR, skip the rest */ - if (pat->special_table[altcnt]->type == 1) + if (pat->special_table[altcnt]->type == 1) { break; + } altcnt++; i++; } @@ -529,13 +543,16 @@ int filter_add_acpatt(struct filter *m, const struct cli_ac_patt *pat) return -1; } } - if (stop) --speci; + if (stop) { + --speci; + } j = speci; if (j < 2) { - if (stop) + if (stop) { cli_warnmsg("Don't know how to create filter for: %s\n", pat->virname); - else + } else { cli_warnmsg("Subpattern too short: %s\n", pat->virname); + } return -1; } @@ -547,10 +564,11 @@ int filter_add_acpatt(struct filter *m, const struct cli_ac_patt *pat) num_iter = spec_iter(spec0) * spec_iter(spec1); if (num_iter >= 0x100) { - if (num_iter == 0x10000) + if (num_iter == 0x10000) { char_badness[i] = reject; - else + } else { char_badness[i] = avoid_anywhere; + } } else { int8_t binary = 0; enum badness scor = acceptable; @@ -570,8 +588,9 @@ int filter_add_acpatt(struct filter *m, const struct cli_ac_patt *pat) scor = dontlike; break; } - if ((c0 < 32 || c0 > 127) && (c1 < 32 || c1 > 127)) + if ((c0 < 32 || c0 > 127) && (c1 < 32 || c1 > 127)) { binary = 1; + } } } if (scor == acceptable && binary) { @@ -595,12 +614,16 @@ int filter_add_acpatt(struct filter *m, const struct cli_ac_patt *pat) * first negative, and one we stop at last positive, but never * include reject */ assert(kend - 1 < j - 1); - if (char_badness[i] == reject) + if (char_badness[i] == reject) { continue; - if ((char_badness[i] == avoid_anywhere || char_badness[i] == avoid_first) && choices_cnt > 0) + } + if ((char_badness[i] == avoid_anywhere || char_badness[i] == avoid_first) && choices_cnt > 0) { /* if we have another choice don't choose this */ continue; - while ((kend > i + 3) && char_badness[kend - 1] == reject) kend--; + } + while ((kend > i + 3) && char_badness[kend - 1] == reject) { + kend--; + } for (k = i; k < kend; k++) { enum badness badness = char_badness[k]; if (badness < acceptable) { @@ -609,16 +632,20 @@ int filter_add_acpatt(struct filter *m, const struct cli_ac_patt *pat) kend = k; break; } - if (badness == avoid_first && k != i) + if (badness == avoid_first && k != i) { badness = dontlike; - if (k == i && badness == avoid_anywhere) + } + if (k == i && badness == avoid_anywhere) { badness = avoid_first; - if (ki == -0xff) + } + if (ki == -0xff) { ki = k; + } } base0 = MIN(base0, badness); - if (ki == -0xff) + if (ki == -0xff) { base1 = MIN(base1, badness); + } } add_choice(choices, &choices_cnt, i, kend, base0); if (ki > (int)i) { @@ -722,7 +749,9 @@ __hot__ int filter_search_ext(const struct filter *m, const unsigned char *data, const uint8_t *B = m->B; const uint8_t *End = m->end; - if (len < 2) return -1; + if (len < 2) { + return -1; + } /* look for first match */ for (j = 0; j < len - 1; j++) { uint8_t match_state_end; @@ -751,7 +780,9 @@ long filter_search(const struct filter *m, const unsigned char *data, unsigned l const uint8_t *End = m->end; /* we use 2-grams, must be higher than 1 */ - if (len < 2) return -1; + if (len < 2) { + return -1; + } /* Shift-Or like search algorithm */ for (j = 0; j < len - 1; j++) { const uint16_t q0 = cli_readint16(&data[j]); diff --git a/libclamav/fmap.c b/libclamav/fmap.c index 1bf11fcbac..778a92f0b4 100644 --- a/libclamav/fmap.c +++ b/libclamav/fmap.c @@ -119,7 +119,9 @@ fmap_t *fmap_check_empty(int fd, off_t offset, size_t len, int *empty, const cha return NULL; } - if (!len) len = st.st_size - offset; /* bound checked later */ + if (!len) { + len = st.st_size - offset; /* bound checked later */ + } if (!len) { cli_dbgmsg("fmap: attempted void mapping\n"); *empty = 1; @@ -130,8 +132,9 @@ fmap_t *fmap_check_empty(int fd, off_t offset, size_t len, int *empty, const cha return NULL; } m = cl_fmap_open_handle((void *)(ssize_t)fd, offset, len, pread_cb, 1); - if (!m) + if (!m) { return NULL; + } m->mtime = (uint64_t)st.st_mtime; if (NULL != name) { @@ -448,7 +451,9 @@ extern cl_fmap_t *cl_fmap_open_handle(void *handle, size_t offset, size_t len, static void fmap_aging(fmap_t *m) { #ifdef ANONYMOUS_MAP - if (!m->aging) return; + if (!m->aging) { + return; + } if (m->paged * m->pgsz > UNPAGE_THRSHLD_HI) { /* we alloc'd too much */ uint64_t i, avail = 0, freeme[2048], maxavail = MIN(sizeof(freeme) / sizeof(*freeme), m->paged - UNPAGE_THRSHLD_LO / m->pgsz) - 1; @@ -456,7 +461,9 @@ static void fmap_aging(fmap_t *m) uint64_t s = fmap_bitmap[i]; if ((s & (FM_MASK_PAGED | FM_MASK_LOCKED)) == FM_MASK_PAGED) { /* page is paged and not locked: dec age */ - if (s & FM_MASK_COUNT) fmap_bitmap[i]--; + if (s & FM_MASK_COUNT) { + fmap_bitmap[i]--; + } /* and make it available for unpaging */ if (!avail) { @@ -468,10 +475,14 @@ static void fmap_aging(fmap_t *m) if (avail <= maxavail || (fmap_bitmap[freeme[maxavail]] & FM_MASK_COUNT) > age) { while ((fmap_bitmap[freeme[insert_to]] & FM_MASK_COUNT) > age) { freeme[insert_to + 1] = freeme[insert_to]; - if (!insert_to--) break; + if (!insert_to--) { + break; + } } freeme[insert_to + 1] = i; - if (avail <= maxavail) avail++; + if (avail <= maxavail) { + avail++; + } } } } @@ -495,16 +506,18 @@ static void fmap_aging(fmap_t *m) continue; } fmap_lock; - if (mmap(firstpage, lastpage - firstpage, PROT_READ | PROT_WRITE, MAP_FIXED | MAP_PRIVATE | ANONYMOUS_MAP, -1, 0) == MAP_FAILED) + if (mmap(firstpage, lastpage - firstpage, PROT_READ | PROT_WRITE, MAP_FIXED | MAP_PRIVATE | ANONYMOUS_MAP, -1, 0) == MAP_FAILED) { cli_dbgmsg("fmap_aging: kernel hates you\n"); + } fmap_unlock; firstpage = pptr; lastpage = pptr + m->pgsz; } if (lastpage) { fmap_lock; - if (mmap(firstpage, lastpage - firstpage, PROT_READ | PROT_WRITE, MAP_FIXED | MAP_PRIVATE | ANONYMOUS_MAP, -1, 0) == MAP_FAILED) + if (mmap(firstpage, lastpage - firstpage, PROT_READ | PROT_WRITE, MAP_FIXED | MAP_PRIVATE | ANONYMOUS_MAP, -1, 0) == MAP_FAILED) { cli_dbgmsg("fmap_aging: kernel hates you\n"); + } fmap_unlock; } m->paged -= avail; @@ -541,11 +554,14 @@ static int fmap_readpage(fmap_t *m, uint64_t first_page, uint64_t count, uint64_ if (lock_count) { lock_count--; lock = 1; - } else + } else { lock = 0; + } if (i == count) { /* we count one page too much to flush pending reads */ - if (!pptr) return 0; /* if we have any */ + if (!pptr) { + return 0; /* if we have any */ + } force_read = 1; } else if ((sbitmap = fmap_bitmap[page]) & FM_MASK_PAGED) { /* page already paged */ @@ -560,8 +576,9 @@ static int fmap_readpage(fmap_t *m, uint64_t first_page, uint64_t count, uint64_ } /* acceptable lock count: inc lock count */ fmap_bitmap[page]++; - } else /* page not currently locked: set lock count = 1 */ + } else { /* page not currently locked: set lock count = 1 */ fmap_bitmap[page] = 1 | FM_MASK_LOCKED | FM_MASK_PAGED; + } } else { /* we don't want locking */ if (!(sbitmap & FM_MASK_LOCKED)) { @@ -569,7 +586,9 @@ static int fmap_readpage(fmap_t *m, uint64_t first_page, uint64_t count, uint64_ fmap_bitmap[page] = FM_MASK_PAGED | FM_MASK_COUNT; } } - if (!pptr) continue; + if (!pptr) { + continue; + } force_read = 1; } @@ -602,8 +621,9 @@ static int fmap_readpage(fmap_t *m, uint64_t first_page, uint64_t count, uint64_ uint64_t target_offset = eintr_off + m->offset + (first_page * m->pgsz); got = m->pread_cb(m->handle, pptr, readsz, target_offset); - if (got < 0 && errno == EINTR) + if (got < 0 && errno == EINTR) { continue; + } if (got > 0) { pptr += got; @@ -633,14 +653,16 @@ static int fmap_readpage(fmap_t *m, uint64_t first_page, uint64_t count, uint64_ pptr = (char *)m->data + page * m->pgsz; first_page = page; } - if ((page == m->pages - 1) && (m->real_len % m->pgsz)) + if ((page == m->pages - 1) && (m->real_len % m->pgsz)) { readsz += m->real_len % m->pgsz; - else + } else { readsz += m->pgsz; - if (lock) /* lock requested: set paged, lock page and set lock count to 1 */ + } + if (lock) { /* lock requested: set paged, lock page and set lock count to 1 */ fmap_bitmap[page] = FM_MASK_PAGED | FM_MASK_LOCKED | 1; - else /* no locking: set paged and set aging to max */ + } else { /* no locking: set paged and set aging to max */ fmap_bitmap[page] = FM_MASK_PAGED | FM_MASK_COUNT; + } m->paged++; } return 0; @@ -651,12 +673,14 @@ static const void *handle_need(fmap_t *m, size_t at, size_t len, int lock) uint64_t first_page, last_page, lock_count; char *ret; - if (!len) + if (!len) { return NULL; + } at += m->nested_offset; - if (!CLI_ISCONTAINED(m->nested_offset, m->len, at, len)) + if (!CLI_ISCONTAINED(m->nested_offset, m->len, at, len)) { return NULL; + } fmap_aging(m); @@ -668,8 +692,9 @@ static const void *handle_need(fmap_t *m, size_t at, size_t len, int lock) if (last_page >= m->pages) last_page = m->pages - 1; #endif - if (fmap_readpage(m, first_page, last_page - first_page + 1, lock_count)) + if (fmap_readpage(m, first_page, last_page - first_page + 1, lock_count)) { return NULL; + } ret = (char *)m->data + at; return (void *)ret; @@ -682,12 +707,13 @@ static void fmap_unneed_page(fmap_t *m, uint64_t page) if ((s & (FM_MASK_PAGED | FM_MASK_LOCKED)) == (FM_MASK_PAGED | FM_MASK_LOCKED)) { /* page is paged and locked: check lock count */ s &= FM_MASK_COUNT; - if (s > 1) /* locked more than once: dec lock count */ + if (s > 1) { /* locked more than once: dec lock count */ fmap_bitmap[page]--; - else if (s == 1) /* only one lock left: unlock and begin aging */ + } else if (s == 1) { /* only one lock left: unlock and begin aging */ fmap_bitmap[page] = FM_MASK_COUNT | FM_MASK_PAGED; - else + } else { cli_errmsg("fmap_unneed: inconsistent map state\n"); + } return; } cli_warnmsg("fmap_unneed: unneed on a unlocked page\n"); @@ -697,7 +723,9 @@ static void fmap_unneed_page(fmap_t *m, uint64_t page) static void handle_unneed_off(fmap_t *m, size_t at, size_t len) { uint64_t i, first_page, last_page; - if (!m->aging) return; + if (!m->aging) { + return; + } if (!len) { cli_warnmsg("fmap_unneed: attempted void unneed\n"); return; @@ -722,8 +750,9 @@ static void unmap_mmap(fmap_t *m) #ifdef ANONYMOUS_MAP size_t len = m->pages * m->pgsz; fmap_lock; - if (munmap((void *)m->data, len) == -1) /* munmap() failed */ + if (munmap((void *)m->data, len) == -1) { /* munmap() failed */ cli_warnmsg("funmap: unable to unmap memory segment at address: %p with length: %zu\n", (void *)m->data, len); + } fmap_unlock; #else UNUSEDPARAM(m); @@ -748,11 +777,13 @@ static const void *handle_need_offstr(fmap_t *m, size_t at, size_t len_hint) at += m->nested_offset; ptr = (void *)((char *)m->data + at); - if (!len_hint || len_hint > m->real_len - at) + if (!len_hint || len_hint > m->real_len - at) { len_hint = m->real_len - at; + } - if (!CLI_ISCONTAINED(m->nested_offset, m->len, at, len_hint)) + if (!CLI_ISCONTAINED(m->nested_offset, m->len, at, len_hint)) { return NULL; + } fmap_aging(m); @@ -775,11 +806,13 @@ static const void *handle_need_offstr(fmap_t *m, size_t at, size_t len_hint) scansz = MIN(len_hint, m->pgsz); } len_hint -= scansz; - if (memchr(&thispage[scanat], 0, scansz)) + if (memchr(&thispage[scanat], 0, scansz)) { return ptr; + } } - for (i = first_page; i <= last_page; i++) + for (i = first_page; i <= last_page; i++) { fmap_unneed_page(m, i); + } return NULL; } @@ -791,8 +824,9 @@ static const void *handle_gets(fmap_t *m, char *dst, size_t *at, size_t max_len) size_t len = MIN(max_len - 1, m->len - *at); size_t fullen = len; - if (!len || !CLI_ISCONTAINED_0_TO(m->len, *at, len)) + if (!len || !CLI_ISCONTAINED_0_TO(m->len, *at, len)) { return NULL; + } fmap_aging(m); @@ -803,8 +837,9 @@ static const void *handle_gets(fmap_t *m, char *dst, size_t *at, size_t max_len) char *thispage = (char *)m->data + i * m->pgsz; uint64_t scanat, scansz; - if (fmap_readpage(m, i, 1, 0)) + if (fmap_readpage(m, i, 1, 0)) { return NULL; + } if (i == first_page) { scanat = (m->nested_offset + *at) % m->pgsz; @@ -918,14 +953,17 @@ static const void *mem_need_offstr(fmap_t *m, size_t at, size_t len_hint) at += m->nested_offset; ptr = (char *)m->data + at; - if (!len_hint || len_hint > m->real_len - at) + if (!len_hint || len_hint > m->real_len - at) { len_hint = m->real_len - at; + } - if (!CLI_ISCONTAINED(m->nested_offset, m->len, at, len_hint)) + if (!CLI_ISCONTAINED(m->nested_offset, m->len, at, len_hint)) { return NULL; + } - if (memchr(ptr, 0, len_hint)) + if (memchr(ptr, 0, len_hint)) { return (void *)ptr; + } return NULL; } @@ -935,8 +973,9 @@ static const void *mem_gets(fmap_t *m, char *dst, size_t *at, size_t max_len) char *endptr = NULL; size_t len = MIN(max_len - 1, m->len - *at); - if (!len || !CLI_ISCONTAINED_0_TO(m->len, *at, len)) + if (!len || !CLI_ISCONTAINED_0_TO(m->len, *at, len)) { return NULL; + } if ((endptr = memchr(src, '\n', len))) { endptr++; diff --git a/libclamav/fsg.c b/libclamav/fsg.c index 17ccdb1b01..609b71ed87 100644 --- a/libclamav/fsg.c +++ b/libclamav/fsg.c @@ -51,7 +51,9 @@ int unfsg_200(const char *source, char *dest, int ssize, int dsize, uint32_t rva { struct cli_exe_section section; /* Yup, just one ;) */ - if (cli_unfsg(source, dest, ssize, dsize, NULL, NULL)) return -1; + if (cli_unfsg(source, dest, ssize, dsize, NULL, NULL)) { + return -1; + } section.raw = 0; section.rsz = dsize; @@ -73,8 +75,9 @@ int unfsg_133(const char *source, char *dest, int ssize, int dsize, struct cli_e for (i = 0; i <= sectcount; i++) { char *startd = tdst; - if (cli_unfsg(tsrc, tdst, ssize - (tsrc - source), dsize - (tdst - dest), &tsrc, &tdst) == -1) + if (cli_unfsg(tsrc, tdst, ssize - (tsrc - source), dsize - (tdst - dest), &tsrc, &tdst) == -1) { return -1; + } /* RVA has been filled already in pe.c */ sections[i].raw = offs; @@ -89,8 +92,9 @@ int unfsg_133(const char *source, char *dest, int ssize, int dsize, struct cli_e for (i = 0; i < sectcount; i++) { uint32_t trva, trsz, traw; - if (sections[i].rva <= sections[i + 1].rva) + if (sections[i].rva <= sections[i + 1].rva) { continue; + } trva = sections[i].rva; traw = sections[i].raw; trsz = sections[i].rsz; @@ -109,8 +113,9 @@ int unfsg_133(const char *source, char *dest, int ssize, int dsize, struct cli_e if (i != sectcount) { sections[i].vsz = sections[i + 1].rva - sections[i].rva; lastsz -= sections[i + 1].rva - sections[i].rva; - } else + } else { sections[i].vsz = lastsz; + } cli_dbgmsg("FSG: .SECT%d RVA:%x VSize:%x ROffset: %x, RSize:%x\n", i, sections[i].rva, sections[i].vsz, sections[i].raw, sections[i].rsz); } diff --git a/libclamav/gpt.c b/libclamav/gpt.c index 8a4b8748cc..0f6d504f3e 100644 --- a/libclamav/gpt.c +++ b/libclamav/gpt.c @@ -76,24 +76,36 @@ size_t gpt_detect_size(fmap_t *map) unsigned char *buff; buff = (unsigned char *)fmap_need_off_once(map, 512, 8); - if (!buff) return 0; - if (0 == strncmp((const char *)buff, GPT_SIGNATURE_STR, 8)) + if (!buff) { + return 0; + } + if (0 == strncmp((const char *)buff, GPT_SIGNATURE_STR, 8)) { return 512; + } buff = (unsigned char *)fmap_need_off_once(map, 1024, 8); - if (!buff) return 0; - if (0 == strncmp((const char *)buff, GPT_SIGNATURE_STR, 8)) + if (!buff) { + return 0; + } + if (0 == strncmp((const char *)buff, GPT_SIGNATURE_STR, 8)) { return 1024; + } buff = (unsigned char *)fmap_need_off_once(map, 2048, 8); - if (!buff) return 0; - if (0 == strncmp((const char *)buff, GPT_SIGNATURE_STR, 8)) + if (!buff) { + return 0; + } + if (0 == strncmp((const char *)buff, GPT_SIGNATURE_STR, 8)) { return 2048; + } buff = (unsigned char *)fmap_need_off_once(map, 4096, 8); - if (!buff) return 0; - if (0 == strncmp((const char *)buff, GPT_SIGNATURE_STR, 8)) + if (!buff) { + return 0; + } + if (0 == strncmp((const char *)buff, GPT_SIGNATURE_STR, 8)) { return 4096; + } return 0; } diff --git a/libclamav/hashtab.c b/libclamav/hashtab.c index 1e4dadf6cf..0abd93a408 100644 --- a/libclamav/hashtab.c +++ b/libclamav/hashtab.c @@ -174,8 +174,9 @@ static inline void PROFILE_REPORT(const struct cli_hashtable *s) cl_error_t cli_hashtab_init(struct cli_hashtable *s, size_t capacity) { - if (!s) + if (!s) { return CL_ENULLARG; + } PROFILE_INIT(s); @@ -196,8 +197,9 @@ cl_error_t cli_htu32_init(struct cli_htu32 *s, size_t capacity, mpool_t *mempool UNUSEDPARAM(mempool); #endif - if (!s) + if (!s) { return CL_ENULLARG; + } PROFILE_INIT(s); @@ -252,8 +254,9 @@ struct cli_element *cli_hashtab_find(const struct cli_hashtable *s, const char * size_t tries = 1; size_t idx; - if (!s) + if (!s) { return NULL; + } PROFILE_CALC_HASH(s); PROFILE_FIND_ELEMENT(s); idx = hash((const unsigned char *)key, len, s->capacity); @@ -280,8 +283,9 @@ const struct cli_htu32_element *cli_htu32_find(const struct cli_htu32 *s, uint32 size_t tries = 1; size_t idx; - if (!s) + if (!s) { return NULL; + } PROFILE_CALC_HASH(s); PROFILE_FIND_ELEMENT(s); idx = hash_htu32(key, s->capacity); @@ -305,22 +309,25 @@ const struct cli_htu32_element *cli_htu32_find(const struct cli_htu32 *s, uint32 const struct cli_htu32_element *cli_htu32_next(const struct cli_htu32 *s, const struct cli_htu32_element *current) { size_t ncur; - if (!s || !s->capacity) + if (!s || !s->capacity) { return NULL; + } - if (!current) + if (!current) { ncur = 0; - else { + } else { ncur = current - s->htable; - if (ncur >= s->capacity) + if (ncur >= s->capacity) { return NULL; + } ncur++; } for (; ncur < s->capacity; ncur++) { const struct cli_htu32_element *item = &s->htable[ncur & (s->capacity - 1)]; - if (item->key && item->key != DELETED_HTU32_KEY) + if (item->key && item->key != DELETED_HTU32_KEY) { return item; + } } return NULL; } @@ -388,8 +395,9 @@ static cl_error_t cli_htu32_grow(struct cli_htu32 *s, mpool_t *mempool) struct cli_htu32_element *htable = MPOOL_CALLOC(mempool, new_capacity, sizeof(*s->htable)); size_t i, idx, used = 0; cli_dbgmsg("hashtab.c: new capacity: %zu\n", new_capacity); - if (new_capacity == s->capacity || !htable) + if (new_capacity == s->capacity || !htable) { return CL_EMEM; + } PROFILE_GROW_START(s); @@ -433,8 +441,9 @@ const struct cli_element *cli_hashtab_insert(struct cli_hashtable *s, const char struct cli_element *deleted_element = NULL; size_t tries = 1; size_t idx; - if (!s) + if (!s) { return NULL; + } if (s->used > s->maxfill) { cli_dbgmsg("hashtab.c:Growing hashtable %p, because it has exceeded maxfill, old size: %zu\n", (void *)s, s->capacity); cli_hashtab_grow(s); @@ -499,8 +508,9 @@ cl_error_t cli_htu32_insert(struct cli_htu32 *s, const struct cli_htu32_element UNUSEDPARAM(mempool); #endif - if (!s) + if (!s) { return CL_ENULLARG; + } if (s->used > s->maxfill) { cli_dbgmsg("hashtab.c:Growing hashtable %p, because it has exceeded maxfill, old size: %zu\n", (void *)s, s->capacity); cli_htu32_grow(s, mempool); @@ -546,8 +556,9 @@ cl_error_t cli_htu32_insert(struct cli_htu32 *s, const struct cli_htu32_element void cli_hashtab_delete(struct cli_hashtable *s, const char *key, const size_t len) { struct cli_element *el = cli_hashtab_find(s, key, len); - if (!el || el->key == DELETED_KEY) + if (!el || el->key == DELETED_KEY) { return; + } free((void *)el->key); el->key = DELETED_KEY; } @@ -555,8 +566,9 @@ void cli_hashtab_delete(struct cli_hashtable *s, const char *key, const size_t l void cli_htu32_delete(struct cli_htu32 *s, uint32_t key) { struct cli_htu32_element *el = (struct cli_htu32_element *)cli_htu32_find(s, key); - if (el) + if (el) { el->key = DELETED_HTU32_KEY; + } } void cli_hashtab_clear(struct cli_hashtable *s) @@ -564,19 +576,22 @@ void cli_hashtab_clear(struct cli_hashtable *s) size_t i; PROFILE_HASH_CLEAR(s); for (i = 0; i < s->capacity; i++) { - if (s->htable[i].key && s->htable[i].key != DELETED_KEY) + if (s->htable[i].key && s->htable[i].key != DELETED_KEY) { free((void *)s->htable[i].key); + } } - if (s->htable) + if (s->htable) { memset(s->htable, 0, s->capacity * sizeof(*s->htable)); + } s->used = 0; } void cli_htu32_clear(struct cli_htu32 *s) { PROFILE_HASH_CLEAR(s); - if (s->htable) + if (s->htable) { memset(s->htable, 0, s->capacity * sizeof(struct cli_htu32_element)); + } s->used = 0; } @@ -601,7 +616,9 @@ void cli_htu32_free(struct cli_htu32 *s, mpool_t *mempool) size_t cli_htu32_numitems(struct cli_htu32 *s) { - if (!s) return 0; + if (!s) { + return 0; + } return s->capacity; } @@ -625,12 +642,13 @@ cl_error_t cli_hashtab_generate_c(const struct cli_hashtable *s, const char *nam printf("static struct cli_element %s_elements[] = {\n", name); for (i = 0; i < s->capacity; i++) { const struct cli_element *e = &s->htable[i]; - if (!e->key) + if (!e->key) { printf("\t{NULL,0,0},\n"); - else if (e->key == DELETED_KEY) + } else if (e->key == DELETED_KEY) { printf("\t{DELETED_KEY,0,0},\n"); - else + } else { printf("\t{\"%s\", %zu, %zu},\n", e->key, (size_t)e->data, e->len); + } } printf("};\n"); printf("const struct cli_hashtable %s = {\n", name); diff --git a/libclamav/hfsplus.c b/libclamav/hfsplus.c index c479027c31..4419b861d6 100644 --- a/libclamav/hfsplus.c +++ b/libclamav/hfsplus.c @@ -121,8 +121,9 @@ static void forkdata_print(const char *pfx, hfsPlusForkData *fork) cli_dbgmsg("%s logicalSize " STDu64 " clumpSize " STDu32 " totalBlocks " STDu32 "\n", pfx, fork->logicalSize, fork->clumpSize, fork->totalBlocks); for (i = 0; i < 8; i++) { - if (fork->extents[i].startBlock == 0) + if (fork->extents[i].startBlock == 0) { break; + } cli_dbgmsg("%s extent[%d] startBlock " STDu32 " blockCount " STDu32 "\n", pfx, i, fork->extents[i].startBlock, fork->extents[i].blockCount); } diff --git a/libclamav/hostid_internal.c b/libclamav/hostid_internal.c index bb4d09db86..9df5375d8a 100644 --- a/libclamav/hostid_internal.c +++ b/libclamav/hostid_internal.c @@ -82,8 +82,9 @@ struct device *get_device_entry(struct device *devices, size_t *ndevices, const if (!found) { p = realloc(devices, sizeof(struct device) * (*ndevices + 1)); if (!(p)) { - for (i = 0; i < *ndevices; i++) + for (i = 0; i < *ndevices; i++) { free(devices[i].name); + } free(devices); return NULL; } @@ -94,14 +95,16 @@ struct device *get_device_entry(struct device *devices, size_t *ndevices, const } } else { devices = calloc(1, sizeof(struct device)); - if (!(devices)) + if (!(devices)) { return NULL; + } *ndevices = 1; } - if (*ndevices && !(devices[*ndevices - 1].name) && name) + if (*ndevices && !(devices[*ndevices - 1].name) && name) { devices[*ndevices - 1].name = strdup(name); + } return devices; } @@ -251,8 +254,9 @@ char *internal_get_host_id(void) void *ctx; devices = get_devices(); - if (!(devices)) + if (!(devices)) { return NULL; + } printable_md5 = calloc(1, 37); if (!(printable_md5)) { @@ -262,8 +266,9 @@ char *internal_get_host_id(void) ctx = cl_hash_init("md5"); if (!(ctx)) { - for (i = 0; devices[i].name != NULL; i++) + for (i = 0; devices[i].name != NULL; i++) { free(devices[i].name); + } free(devices); free(printable_md5); @@ -271,13 +276,15 @@ char *internal_get_host_id(void) return NULL; } - for (i = 0; devices[i].name != NULL; i++) + for (i = 0; devices[i].name != NULL; i++) { cl_update_hash(ctx, devices[i].mac, sizeof(devices[i].mac)); + } cl_finish_hash(ctx, raw_md5); - for (i = 0; devices[i].name != NULL; i++) + for (i = 0; devices[i].name != NULL; i++) { free(devices[i].name); + } free(devices); for (i = 0; i < sizeof(raw_md5); i++) { diff --git a/libclamav/htmlnorm.c b/libclamav/htmlnorm.c index 0c70f00dfe..96df695ae6 100644 --- a/libclamav/htmlnorm.c +++ b/libclamav/htmlnorm.c @@ -197,10 +197,11 @@ static unsigned char *cli_readchunk(FILE *stream, m_area_t *m_area, unsigned int free(chunk); return NULL; } - if (m_area->map) + if (m_area->map) { ptr = (unsigned char *)fmap_need_off_once(m_area->map, m_area->offset, chunk_len); - else + } else { ptr = m_area->buffer + m_area->offset; + } start = ptr; end = ptr - m_area->offset + m_area->length; @@ -228,8 +229,9 @@ static unsigned char *cli_readchunk(FILE *stream, m_area_t *m_area, unsigned int chunk_len = 0; ptr = start; } - if (m_area->map) + if (m_area->map) { ptr = (unsigned char *)fmap_need_ptr_once(m_area->map, ptr, end - ptr); + } if (!ptr) { cli_warnmsg("fmap inconsistency\n"); ptr = end; @@ -435,8 +437,9 @@ void html_tag_arg_add(tag_arguments_t *tags, } for (i = 0; i < contentCnt; i++) { if (tags->contents) { - if (tags->contents[i]) + if (tags->contents[i]) { free(tags->contents[i]); + } } } if (tags->tag) { @@ -445,8 +448,9 @@ void html_tag_arg_add(tag_arguments_t *tags, if (tags->value) { free(tags->value); } - if (tags->contents) + if (tags->contents) { free(tags->contents); + } tags->contents = NULL; tags->tag = tags->value = NULL; tags->count = 0; @@ -483,9 +487,11 @@ void html_tag_arg_free(tag_arguments_t *tags) if (tags->value[i]) { free(tags->value[i]); } - if (tags->contents) - if (tags->contents[i]) + if (tags->contents) { + if (tags->contents[i]) { free(tags->contents[i]); + } + } } if (tags->tag) { free(tags->tag); @@ -493,8 +499,9 @@ void html_tag_arg_free(tag_arguments_t *tags) if (tags->value) { free(tags->value); } - if (tags->contents) + if (tags->contents) { free(tags->contents); + } tags->contents = NULL; tags->tag = tags->value = NULL; tags->count = 0; @@ -507,8 +514,9 @@ static inline void html_tag_contents_append(struct tag_contents *cont, const uns { size_t i; uint32_t mbchar = 0; - if (!begin || !end) + if (!begin || !end) { return; + } for (i = cont->pos; i < MAX_TAG_CONTENTS_LENGTH && (begin < end); i++) { uint8_t c = *begin++; if (mbchar && (c < 0x80 || mbchar >= 0x10000)) { @@ -524,20 +532,24 @@ static inline void html_tag_contents_append(struct tag_contents *cont, const uns uint8_t c0 = mbchar >> 16; uint8_t c1 = (mbchar >> 8) & 0xff; uint8_t c2 = (mbchar & 0xff); - if (c0 && i + 1 < MAX_TAG_CONTENTS_LENGTH) + if (c0 && i + 1 < MAX_TAG_CONTENTS_LENGTH) { cont->contents[i++] = c0; - if ((c0 || c1) && i + 1 < MAX_TAG_CONTENTS_LENGTH) + } + if ((c0 || c1) && i + 1 < MAX_TAG_CONTENTS_LENGTH) { cont->contents[i++] = c1; - if (i + 1 < MAX_TAG_CONTENTS_LENGTH) + } + if (i + 1 < MAX_TAG_CONTENTS_LENGTH) { cont->contents[i++] = c2; + } } mbchar = 0; } if (c >= 0x80) { mbchar = (mbchar << 8) | c; --i; - } else + } else { cont->contents[i] = c; + } } cont->pos = i; } @@ -568,8 +580,9 @@ static void screnc_decode(unsigned char *ptr, struct screnc_state *s) uint8_t value; unsigned char *dst = ptr; - if (!ptr || !s) + if (!ptr || !s) { return; + } while (s->length > 0 && *ptr) { if ((*ptr == '\n') || (*ptr == '\r')) { ptr++; @@ -651,10 +664,12 @@ static void screnc_decode(unsigned char *ptr, struct screnc_state *s) static void js_process(struct parser_state *js_state, const unsigned char *js_begin, const unsigned char *js_end, const unsigned char *line, const unsigned char *ptr, tag_type in_tag, const char *dirname) { - if (!js_begin) + if (!js_begin) { js_begin = line; - if (!js_end) + } + if (!js_end) { js_end = ptr; + } if (js_end > js_begin && CLI_ISCONTAINED(line, 8192, js_begin, 1) && CLI_ISCONTAINED(line, 8192, js_end, 1)) { @@ -826,8 +841,9 @@ static bool cli_html_normalise(cli_ctx *ctx, int fd, m_area_t *m_area, const cha ptr = line = cli_readchunk(stream_in, m_area, 8192); while (line) { - if (href_contents_begin) + if (href_contents_begin) { href_contents_begin = ptr; /*start of a new line, last line already appended to contents see below*/ + } while (*ptr && isspace(*ptr)) { ptr++; } @@ -943,7 +959,9 @@ static bool cli_html_normalise(cli_ctx *ctx, int fd, m_area_t *m_area, const cha } else { unsigned char c = tolower(*ptr); /* normalize ' to " for scripts */ - if (in_tag != TAG_DONT_EXTRACT && c == '\'') c = '"'; + if (in_tag != TAG_DONT_EXTRACT && c == '\'') { + c = '"'; + } html_output_c(file_buff_o2, c); if (in_tag == TAG_DONT_EXTRACT) { if (*ptr < 0x20) { @@ -1170,8 +1188,9 @@ static bool cli_html_normalise(cli_ctx *ctx, int fd, m_area_t *m_area, const cha if (mbchar2 == 0xE38082 || mbchar2 == 0xEFBC8E || mbchar2 == 0xEFB992 || (mbchar2 == 0xA1 && (*ptr == 0x43 || *ptr == 0x44 || *ptr == 0x4F))) { html_output_c(file_buff_o2, '.'); - if (tag_val_length < HTML_STR_LENGTH) + if (tag_val_length < HTML_STR_LENGTH) { tag_val[tag_val_length++] = '.'; + } if (mbchar2 == 0xA1) { ptr++; mbchar2 = 0; @@ -1181,23 +1200,28 @@ static bool cli_html_normalise(cli_ctx *ctx, int fd, m_area_t *m_area, const cha uint8_t c0 = mbchar2 >> 16; uint8_t c1 = (mbchar2 >> 8) & 0xff; uint8_t c2 = (mbchar2 & 0xff); - if (c0) + if (c0) { html_output_c(file_buff_o2, c0); - if (c0 || c1) + } + if (c0 || c1) { html_output_c(file_buff_o2, c1); + } html_output_c(file_buff_o2, c2); - if (c0 && tag_val_length < HTML_STR_LENGTH) + if (c0 && tag_val_length < HTML_STR_LENGTH) { tag_val[tag_val_length++] = c0; - if ((c0 || c1) && tag_val_length < HTML_STR_LENGTH) + } + if ((c0 || c1) && tag_val_length < HTML_STR_LENGTH) { tag_val[tag_val_length++] = c1; - if (tag_val_length < HTML_STR_LENGTH) + } + if (tag_val_length < HTML_STR_LENGTH) { tag_val[tag_val_length++] = c2; + } } mbchar2 = 0; } - if (*ptr >= 0x80) + if (*ptr >= 0x80) { mbchar2 = (mbchar2 << 8) | *ptr; - else { + } else { html_output_c(file_buff_o2, tolower(*ptr)); if (tag_val_length < HTML_STR_LENGTH) { tag_val[tag_val_length++] = *ptr; @@ -1217,7 +1241,9 @@ static bool cli_html_normalise(cli_ctx *ctx, int fd, m_area_t *m_area, const cha unsigned char c = tolower(*ptr); /* dump script to nocomment.html, since we no longer have * comment.html/script.html */ - if (c == '\'') c = '"'; + if (c == '\'') { + c = '"'; + } html_output_c(file_buff_o2, c); } if (*ptr == '>') { @@ -1327,15 +1353,16 @@ static bool cli_html_normalise(cli_ctx *ctx, int fd, m_area_t *m_area, const cha state = HTML_LOOKFOR_SCRENC; } } else if (hrefs) { - if (in_ahref && !href_contents_begin) + if (in_ahref && !href_contents_begin) { href_contents_begin = ptr; + } if (strcmp(tag, "a") == 0) { arg_value = html_tag_arg_value(&tag_args, "href"); if (arg_value && strlen((const char *)arg_value) > 0) { if (hrefs->scanContents) { char *arg_value_title = html_tag_arg_value(&tag_args, "title"); /*beginning of an tag*/ - if (in_ahref) + if (in_ahref) { /*we encountered nested tags, pretend previous closed*/ if (href_contents_begin) { html_tag_contents_append(&contents, href_contents_begin, ptrend); @@ -1343,6 +1370,7 @@ static bool cli_html_normalise(cli_ctx *ctx, int fd, m_area_t *m_area, const cha html_tag_contents_done(hrefs, in_ahref, &contents); in_ahref = 0; } + } if (arg_value_title) { /* title is a 'displayed link'*/ html_tag_arg_add(hrefs, "href_title", arg_value_title); @@ -1381,9 +1409,10 @@ static bool cli_html_normalise(cli_ctx *ctx, int fd, m_area_t *m_area, const cha arg_value = html_tag_arg_value(&tag_args, "src"); if (arg_value && strlen(arg_value) > 0) { html_tag_arg_add(hrefs, "src", arg_value); - if (hrefs->scanContents && in_ahref) + if (hrefs->scanContents && in_ahref) { /* "contents" of an img tag, is the URL of its parent tag */ hrefs->contents[hrefs->count - 1] = (unsigned char *)cli_safer_strdup((const char *)hrefs->value[in_ahref - 1]); + } if (in_form_action) { /* form action is the real URL, and href is the 'displayed' */ html_tag_arg_add(hrefs, "form", arg_value); @@ -1396,9 +1425,10 @@ static bool cli_html_normalise(cli_ctx *ctx, int fd, m_area_t *m_area, const cha arg_value = html_tag_arg_value(&tag_args, "dynsrc"); if (arg_value && strlen(arg_value) > 0) { html_tag_arg_add(hrefs, "dynsrc", arg_value); - if (hrefs->scanContents && in_ahref) + if (hrefs->scanContents && in_ahref) { /* see above */ hrefs->contents[hrefs->count - 1] = (unsigned char *)cli_safer_strdup((const char *)hrefs->value[in_ahref - 1]); + } if (in_form_action) { /* form action is the real URL, and href is the 'displayed' */ html_tag_arg_add(hrefs, "form", arg_value); @@ -1412,9 +1442,10 @@ static bool cli_html_normalise(cli_ctx *ctx, int fd, m_area_t *m_area, const cha arg_value = html_tag_arg_value(&tag_args, "src"); if (arg_value && strlen(arg_value) > 0) { html_tag_arg_add(hrefs, "iframe", arg_value); - if (hrefs->scanContents && in_ahref) + if (hrefs->scanContents && in_ahref) { /* see above */ hrefs->contents[hrefs->count - 1] = (unsigned char *)cli_safer_strdup((const char *)hrefs->value[in_ahref - 1]); + } if (in_form_action) { /* form action is the real URL, and href is the 'displayed' */ html_tag_arg_add(hrefs, "form", arg_value); @@ -1428,9 +1459,10 @@ static bool cli_html_normalise(cli_ctx *ctx, int fd, m_area_t *m_area, const cha arg_value = html_tag_arg_value(&tag_args, "href"); if (arg_value && strlen(arg_value) > 0) { html_tag_arg_add(hrefs, "area", arg_value); - if (hrefs->scanContents && in_ahref) + if (hrefs->scanContents && in_ahref) { /* see above */ hrefs->contents[hrefs->count - 1] = (unsigned char *)cli_safer_strdup((const char *)hrefs->value[in_ahref - 1]); + } if (in_form_action) { /* form action is the real URL, and href is the 'displayed' */ html_tag_arg_add(hrefs, "form", arg_value); @@ -1467,9 +1499,9 @@ static bool cli_html_normalise(cli_ctx *ctx, int fd, m_area_t *m_area, const cha state = HTML_CHAR_REF_DECODE; ptr++; } else { - if (dconf_entconv) + if (dconf_entconv) { state = HTML_ENTITY_REF_DECODE; - else { + } else { if (next_state == HTML_TAG_ARG_VAL && tag_val_length < HTML_STR_LENGTH) { tag_val[tag_val_length++] = '&'; } @@ -1547,17 +1579,18 @@ static bool cli_html_normalise(cli_ctx *ctx, int fd, m_area_t *m_area, const cha } if (dconf_entconv) { - if (value < 0x80) + if (value < 0x80) { html_output_c(file_buff_o2, tolower(value)); - else { + } else { unsigned char buff[10]; unsigned char *out = u16_normalize_tobuffer(value, buff, 10); if (out && out > buff) { html_output_str(file_buff_o2, buff, out - buff - 1); } } - } else + } else { html_output_c(file_buff_o2, tolower(value & 0xff)); + } state = next_state; next_state = HTML_BAD_STATE; ptr++; @@ -1878,9 +1911,10 @@ static bool cli_html_normalise(cli_ctx *ctx, int fd, m_area_t *m_area, const cha break; } } - if (hrefs && hrefs->scanContents && in_ahref && href_contents_begin) + if (hrefs && hrefs->scanContents && in_ahref && href_contents_begin) { /* end of line, append contents now, resume on next line */ html_tag_contents_append(&contents, href_contents_begin, ptr); + } ptrend = NULL; if (js_state) { @@ -1964,13 +1998,15 @@ static bool cli_html_normalise(cli_ctx *ctx, int fd, m_area_t *m_area, const cha entity_val[entity_val_length] = '\0'; normalized = entity_norm(&conv, entity_val); if (normalized) { - for (i = 0; i < strlen(normalized); i++) + for (i = 0; i < strlen(normalized); i++) { html_output_c(file_buff_o2, normalized[i] & 0xff); + } } else { if (entity_val_length) { html_output_c(file_buff_o2, '&'); - for (i = 0; i < entity_val_length; i++) + for (i = 0; i < entity_val_length; i++) { html_output_c(file_buff_o2, tolower(entity_val[i])); + } } } } @@ -1978,13 +2014,15 @@ static bool cli_html_normalise(cli_ctx *ctx, int fd, m_area_t *m_area, const cha retval = true; done: - if (line) /* only needed for done case */ + if (line) { /* only needed for done case */ free(line); + } if (in_form_action) { free(in_form_action); } - if (in_ahref) /* tag not closed, force closing */ + if (in_ahref) { /* tag not closed, force closing */ html_tag_contents_done(hrefs, in_ahref, &contents); + } if (js_state) { /* output script so far */ @@ -1999,14 +2037,16 @@ static bool cli_html_normalise(cli_ctx *ctx, int fd, m_area_t *m_area, const cha } if (file_buff_o2) { html_output_flush(file_buff_o2); - if (file_buff_o2->fd != -1) + if (file_buff_o2->fd != -1) { close(file_buff_o2->fd); + } free(file_buff_o2); } if (file_buff_text) { html_output_flush(file_buff_text); - if (file_buff_text->fd != -1) + if (file_buff_text->fd != -1) { close(file_buff_text->fd); + } free(file_buff_text); file_buff_text = NULL; } @@ -2103,8 +2143,9 @@ bool html_screnc_decode(fmap_t *map, const char *dirname) goto done; } } - if (count < 6) + if (count < 6) { tmpstr[count] = *ptr; + } count++; ptr++; } while (count < 8); @@ -2129,8 +2170,9 @@ bool html_screnc_decode(fmap_t *map, const char *dirname) } } cli_writen(ofd, "", strlen("")); - if (screnc_state.length) + if (screnc_state.length) { cli_dbgmsg("html_screnc_decode: missing %u bytes\n", screnc_state.length); + } retval = true; done: diff --git a/libclamav/hwp.c b/libclamav/hwp.c index 2a52722f09..920a7be5ad 100644 --- a/libclamav/hwp.c +++ b/libclamav/hwp.c @@ -80,11 +80,13 @@ static cl_error_t decompress_and_callback(cli_ctx *ctx, fmap_t *input, size_t at char *tmpname; unsigned char inbuf[FILEBUFF], outbuf[FILEBUFF]; - if (!ctx || !input || !cb) + if (!ctx || !input || !cb) { return CL_ENULLARG; + } - if (len) + if (len) { remain = len; + } /* reserve tempfile for output and callback */ if ((ret = cli_gentempfd(ctx->sub_tmpdir, &tmpname, &ofd)) != CL_SUCCESS) { @@ -120,12 +122,14 @@ static cl_error_t decompress_and_callback(cli_ctx *ctx, fmap_t *input, size_t at ret = CL_EUNPACK; goto dc_end; } - if (!in) + if (!in) { break; + } if (len) { - if (remain < in) + if (remain < in) { in = remain; + } remain -= in; } zstrm.avail_in = in; @@ -134,8 +138,9 @@ static cl_error_t decompress_and_callback(cli_ctx *ctx, fmap_t *input, size_t at zret = inflate(&zstrm, Z_SYNC_FLUSH); count = FILEBUFF - zstrm.avail_out; if (count) { - if ((ret = cli_checklimits("HWP", ctx, outsize + count, 0, 0)) != CL_SUCCESS) + if ((ret = cli_checklimits("HWP", ctx, outsize + count, 0, 0)) != CL_SUCCESS) { break; + } if (cli_writen(ofd, outbuf, count) != count) { cli_errmsg("%s: Can't write to file %s\n", parent, tmpname); @@ -163,8 +168,9 @@ static cl_error_t decompress_and_callback(cli_ctx *ctx, fmap_t *input, size_t at /* check for limits exceeded or zlib failure */ if (ret == CL_SUCCESS && (zret == Z_STREAM_END || zret == Z_OK)) { - if (len && remain > 0) + if (len && remain > 0) { cli_infomsg(ctx, "%s: Error decompressing stream. Not all requested input was converted\n", parent); + } /* scanning inflated stream */ ret = cb(cbdata, ofd, tmpname, ctx); @@ -178,13 +184,16 @@ static cl_error_t decompress_and_callback(cli_ctx *ctx, fmap_t *input, size_t at zret = inflateEnd(&zstrm); if (zret != Z_OK) { cli_errmsg("%s: Error closing zlib inflation stream\n", parent); - if (ret == CL_SUCCESS) + if (ret == CL_SUCCESS) { ret = CL_EUNPACK; + } } close(ofd); - if (!ctx->engine->keeptmp) - if (cli_unlink(tmpname)) + if (!ctx->engine->keeptmp) { + if (cli_unlink(tmpname)) { ret = CL_EUNLINK; + } + } free(tmpname); return ret; } @@ -254,10 +263,11 @@ static char *convert_hstr_to_utf8(const char *begin, size_t sz, const char *pare memcpy(tmpbuf, begin, sz); res = (char *)cl_base64_encode(tmpbuf, sz); - if (res) + if (res) { rc = CL_VIRUS; /* used as placeholder */ - else + } else { rc = CL_EMEM; + } free(tmpbuf); } else { @@ -283,10 +293,11 @@ cl_error_t cli_scanhwpole2(cli_ctx *ctx) return CL_EREAD; } - if (usize != asize) + if (usize != asize) { cli_warnmsg("HWPOLE2: Mismatched uncompressed prefix and size: %u != %u\n", usize, asize); - else + } else { cli_dbgmsg("HWPOLE2: Matched uncompressed prefix and size: %u == %u\n", usize, asize); + } return cli_magic_scan_nested_fmap_type(map, 4, 0, ctx, CL_TYPE_ANY, NULL, LAYER_ATTRIBUTES_NONE); @@ -296,8 +307,9 @@ cl_error_t cli_scanhwpole2(cli_ctx *ctx) cl_error_t cli_hwp5header(cli_ctx *ctx, hwp5_header_t *hwp5) { - if (!ctx || !hwp5) + if (!ctx || !hwp5) { return CL_ENULLARG; + } if (SCAN_COLLECT_METADATA) { json_object *header, *flags; @@ -365,8 +377,9 @@ static cl_error_t hwp5_cb(void *cbdata, int fd, const char *filepath, cli_ctx *c { UNUSEDPARAM(cbdata); - if (fd < 0 || !ctx) + if (fd < 0 || !ctx) { return CL_ENULLARG; + } return cli_magic_scan_desc(fd, filepath, ctx, NULL, LAYER_ATTRIBUTES_NONE); } @@ -421,8 +434,9 @@ cl_error_t cli_scanhwp5_stream(cli_ctx *ctx, hwp5_header_t *hwp5, char *name, in if (name && !strncmp(name, "_5_hwpsummaryinformation", 24)) { cli_dbgmsg("HWP5.x: Detected a '_5_hwpsummaryinformation' stream\n"); /* JSONOLE2 - what to do if something breaks? */ - if (cli_ole2_summary_json(ctx, fd, 2) == CL_ETIMEOUT) + if (cli_ole2_summary_json(ctx, fd, 2) == CL_ETIMEOUT) { return CL_ETIMEOUT; + } } } } @@ -557,11 +571,13 @@ static inline cl_error_t parsehwp3_docinfo(cli_ctx *ctx, size_t offset, struct h /* Printed File Name */ str = convert_hstr_to_utf8((char *)(hwp3_ptr + DI_PNAME), 40, "HWP3.x", &iret); - if (!str) + if (!str) { return CL_EMEM; + } - if (iret == CL_VIRUS) + if (iret == CL_VIRUS) { cli_jsonbool(header, "PrintName_base64", 1); + } hwp3_debug("HWP3.x: di_pname: %s\n", str); cli_jsonstr(header, "PrintName", str); @@ -569,11 +585,13 @@ static inline cl_error_t parsehwp3_docinfo(cli_ctx *ctx, size_t offset, struct h /* Annotation */ str = convert_hstr_to_utf8((char *)(hwp3_ptr + DI_ANNOTE), 24, "HWP3.x", &iret); - if (!str) + if (!str) { return CL_EMEM; + } - if (iret == CL_VIRUS) + if (iret == CL_VIRUS) { cli_jsonbool(header, "Annotation_base64", 1); + } hwp3_debug("HWP3.x: di_annote: %s\n", str); cli_jsonstr(header, "Annotation", str); @@ -592,8 +610,9 @@ static inline cl_error_t parsehwp3_docsummary(cli_ctx *ctx, size_t offset) json_object *summary; - if (!SCAN_COLLECT_METADATA) + if (!SCAN_COLLECT_METADATA) { return CL_SUCCESS; + } if (!(hwp3_ptr = fmap_need_off_once(ctx->fmap, offset, HWP3_DOCSUMMARY_SIZE))) { cli_errmsg("HWP3.x: Failed to read fmap for hwp docinfo\n"); @@ -608,8 +627,9 @@ static inline cl_error_t parsehwp3_docsummary(cli_ctx *ctx, size_t offset) for (i = 0; i < NUM_DOCSUMMARY_FIELDS; i++) { str = convert_hstr_to_utf8((char *)(hwp3_ptr + hwp3_docsummary_fields[i].offset), 112, "HWP3.x", &iret); - if (!str) + if (!str) { return CL_EMEM; + } if (iret == CL_VIRUS) { char *b64; @@ -628,8 +648,9 @@ static inline cl_error_t parsehwp3_docsummary(cli_ctx *ctx, size_t offset) hwp3_debug("HWP3.x: %s, %s\n", hwp3_docsummary_fields[i].name, str); ret = cli_jsonstr(summary, hwp3_docsummary_fields[i].name, str); free(str); - if (ret != CL_SUCCESS) + if (ret != CL_SUCCESS) { return ret; + } } return CL_SUCCESS; @@ -683,24 +704,29 @@ static inline cl_error_t parsehwp3_paragraph(cli_ctx *ctx, fmap_t *map, int p, u hwp3_debug("HWP3.x: recursion level: %u\n", level); hwp3_debug("HWP3.x: Paragraph[%u, %d] starts @ offset %zu\n", level, p, offset); - if (level >= ctx->engine->maxrechwp3) + if (level >= ctx->engine->maxrechwp3) { return CL_EMAXREC; + } - if (fmap_readn(map, &ppfs, offset + PI_PPFS, sizeof(ppfs)) != sizeof(ppfs)) + if (fmap_readn(map, &ppfs, offset + PI_PPFS, sizeof(ppfs)) != sizeof(ppfs)) { return CL_EREAD; + } - if (fmap_readn(map, &nchars, offset + PI_NCHARS, sizeof(nchars)) != sizeof(nchars)) + if (fmap_readn(map, &nchars, offset + PI_NCHARS, sizeof(nchars)) != sizeof(nchars)) { return CL_EREAD; + } nchars = le16_to_host(nchars); - if (fmap_readn(map, &nlines, offset + PI_NLINES, sizeof(nlines)) != sizeof(nlines)) + if (fmap_readn(map, &nlines, offset + PI_NLINES, sizeof(nlines)) != sizeof(nlines)) { return CL_EREAD; + } nlines = le16_to_host(nlines); - if (fmap_readn(map, &ifsc, offset + PI_IFSC, sizeof(ifsc)) != sizeof(ifsc)) + if (fmap_readn(map, &ifsc, offset + PI_IFSC, sizeof(ifsc)) != sizeof(ifsc)) { return CL_EREAD; + } hwp3_debug("HWP3.x: Paragraph[%u, %d]: ppfs %u\n", level, p, ppfs); hwp3_debug("HWP3.x: Paragraph[%u, %d]: nchars %u\n", level, p, nchars); @@ -735,12 +761,13 @@ static inline cl_error_t parsehwp3_paragraph(cli_ctx *ctx, fmap_t *map, int p, u return CL_SUCCESS; } - if (ppfs) + if (ppfs) { offset += HWP3_PARAINFO_SIZE_S; - else + } else { offset += HWP3_PARAINFO_SIZE_L; + } - /* line information blocks */ + /* line information blocks */ #if HWP3_DEBUG for (i = 0; (i < nlines) && (offset < map->len); i++) { hwp3_debug("HWP3.x: Paragraph[%u, %d]: Line %d information starts @ offset %zu\n", level, p, i, offset); @@ -777,14 +804,16 @@ static inline cl_error_t parsehwp3_paragraph(cli_ctx *ctx, fmap_t *map, int p, u offset = new_offset; #endif - if (offset >= map->len) + if (offset >= map->len) { return CL_EFORMAT; + } if (ifsc) { for (i = 0, c = 0; i < nchars; i++) { /* examine byte for cs data type */ - if (fmap_readn(map, &cfsb, offset, sizeof(cfsb)) != sizeof(cfsb)) + if (fmap_readn(map, &cfsb, offset, sizeof(cfsb)) != sizeof(cfsb)) { return CL_EREAD; + } offset += sizeof(cfsb); @@ -829,8 +858,9 @@ static inline cl_error_t parsehwp3_paragraph(cli_ctx *ctx, fmap_t *map, int p, u while ((!term) && (offset < map->len)) { - if (fmap_readn(map, &content, offset, sizeof(content)) != sizeof(content)) + if (fmap_readn(map, &content, offset, sizeof(content)) != sizeof(content)) { return CL_EREAD; + } content = le16_to_host(content); @@ -861,8 +891,9 @@ static inline cl_error_t parsehwp3_paragraph(cli_ctx *ctx, fmap_t *map, int p, u /* id block verification (only on HWP3_VERIFY) */ HWP3_PSPECIAL_VERIFY(map, offset, 6, content, match); - if (fmap_readn(map, &length, offset + 2, sizeof(length)) != sizeof(length)) + if (fmap_readn(map, &length, offset + 2, sizeof(length)) != sizeof(length)) { return CL_EREAD; + } length = le32_to_host(length); new_offset = offset + (8 + length); @@ -894,8 +925,9 @@ static inline cl_error_t parsehwp3_paragraph(cli_ctx *ctx, fmap_t *map, int p, u /* id block verification (only on HWP3_VERIFY) */ HWP3_PSPECIAL_VERIFY(map, offset, 6, content, match); - if (fmap_readn(map, &length, offset + 2, sizeof(length)) != sizeof(length)) + if (fmap_readn(map, &length, offset + 2, sizeof(length)) != sizeof(length)) { return CL_EREAD; + } length = le32_to_host(length); new_offset = offset + (8 + length); @@ -1032,8 +1064,9 @@ static inline cl_error_t parsehwp3_paragraph(cli_ctx *ctx, fmap_t *map, int p, u #endif /* ncells is located at offset 80 of box information */ - if (fmap_readn(map, &ncells, offset + 80, sizeof(ncells)) != sizeof(ncells)) + if (fmap_readn(map, &ncells, offset + 80, sizeof(ncells)) != sizeof(ncells)) { return CL_EREAD; + } ncells = le16_to_host(ncells); offset += 84; @@ -1054,17 +1087,23 @@ static inline cl_error_t parsehwp3_paragraph(cli_ctx *ctx, fmap_t *map, int p, u hwp3_debug("HWP3.x: Paragraph[%u, %d]: box cell paragraph list starts @ %zu\n", level, p, offset); for (i = 0; i < ncells; i++) { l = 0; - while (!l && ((ret = parsehwp3_paragraph(ctx, map, sp++, level + 1, &offset, &l)) == CL_SUCCESS)) continue; - if (ret != CL_SUCCESS) + while (!l && ((ret = parsehwp3_paragraph(ctx, map, sp++, level + 1, &offset, &l)) == CL_SUCCESS)) { + continue; + } + if (ret != CL_SUCCESS) { return ret; + } } /* box caption paragraph list */ hwp3_debug("HWP3.x: Paragraph[%u, %d]: box cell caption paragraph list starts @ %zu\n", level, p, offset); l = 0; - while (!l && ((ret = parsehwp3_paragraph(ctx, map, sp++, level + 1, &offset, &l)) == CL_SUCCESS)) continue; - if (ret != CL_SUCCESS) + while (!l && ((ret = parsehwp3_paragraph(ctx, map, sp++, level + 1, &offset, &l)) == CL_SUCCESS)) { + continue; + } + if (ret != CL_SUCCESS) { return ret; + } break; } case 11: /* drawing */ @@ -1083,8 +1122,9 @@ static inline cl_error_t parsehwp3_paragraph(cli_ctx *ctx, fmap_t *map, int p, u /* Drawing Info Block is 328+n bytes with n = size of image */ /* n is located at offset 0 of info block */ - if (fmap_readn(map, &size, offset, sizeof(size)) != sizeof(size)) + if (fmap_readn(map, &size, offset, sizeof(size)) != sizeof(size)) { return CL_EREAD; + } hwp3_debug("HWP3.x: Paragraph[%u, %d]: drawing is %u additional bytes\n", level, p, size); @@ -1099,9 +1139,12 @@ static inline cl_error_t parsehwp3_paragraph(cli_ctx *ctx, fmap_t *map, int p, u /* caption paragraph list */ hwp3_debug("HWP3.x: Paragraph[%u, %d]: drawing caption paragraph list starts @ %zu\n", level, p, offset); l = 0; - while (!l && ((ret = parsehwp3_paragraph(ctx, map, sp++, level + 1, &offset, &l)) == CL_SUCCESS)) continue; - if (ret != CL_SUCCESS) + while (!l && ((ret = parsehwp3_paragraph(ctx, map, sp++, level + 1, &offset, &l)) == CL_SUCCESS)) { + continue; + } + if (ret != CL_SUCCESS) { return ret; + } break; } case 13: /* end-of-paragraph marker - treated identically as character */ @@ -1144,9 +1187,12 @@ static inline cl_error_t parsehwp3_paragraph(cli_ctx *ctx, fmap_t *map, int p, u /* hidden description paragraph list */ hwp3_debug("HWP3.x: Paragraph[%u, %d]: hidden description paragraph list starts @ %zu\n", level, p, offset); l = 0; - while (!l && ((ret = parsehwp3_paragraph(ctx, map, sp++, level + 1, &offset, &l)) == CL_SUCCESS)) continue; - if (ret != CL_SUCCESS) + while (!l && ((ret = parsehwp3_paragraph(ctx, map, sp++, level + 1, &offset, &l)) == CL_SUCCESS)) { + continue; + } + if (ret != CL_SUCCESS) { return ret; + } break; } case 16: /* header/footer */ @@ -1186,9 +1232,12 @@ static inline cl_error_t parsehwp3_paragraph(cli_ctx *ctx, fmap_t *map, int p, u /* content paragraph list */ hwp3_debug("HWP3.x: Paragraph[%u, %d]: header/footer paragraph list starts @ %zu\n", level, p, offset); l = 0; - while (!l && ((ret = parsehwp3_paragraph(ctx, map, sp++, level + 1, &offset, &l)) == CL_SUCCESS)) continue; - if (ret != CL_SUCCESS) + while (!l && ((ret = parsehwp3_paragraph(ctx, map, sp++, level + 1, &offset, &l)) == CL_SUCCESS)) { + continue; + } + if (ret != CL_SUCCESS) { return ret; + } break; } case 17: /* footnote/endnote */ @@ -1214,9 +1263,12 @@ static inline cl_error_t parsehwp3_paragraph(cli_ctx *ctx, fmap_t *map, int p, u /* content paragraph list */ hwp3_debug("HWP3.x: Paragraph[%u, %d]: footnote/endnote paragraph list starts @ %zu\n", level, p, offset); l = 0; - while (!l && ((ret = parsehwp3_paragraph(ctx, map, sp++, level + 1, &offset, &l)) == CL_SUCCESS)) continue; - if (ret != CL_SUCCESS) + while (!l && ((ret = parsehwp3_paragraph(ctx, map, sp++, level + 1, &offset, &l)) == CL_SUCCESS)) { + continue; + } + if (ret != CL_SUCCESS) { return ret; + } break; } case 18: /* paste code number */ @@ -1438,8 +1490,9 @@ static inline cl_error_t parsehwp3_paragraph(cli_ctx *ctx, fmap_t *map, int p, u /* id block verification (only on HWP3_VERIFY) */ HWP3_PSPECIAL_VERIFY(map, offset, 6, content, match); - if (fmap_readn(map, &length, offset + 2, sizeof(length)) != sizeof(length)) + if (fmap_readn(map, &length, offset + 2, sizeof(length)) != sizeof(length)) { return CL_EREAD; + } length = le32_to_host(length); new_offset = offset + (8 + length); @@ -1557,8 +1610,9 @@ static inline cl_error_t parsehwp3_infoblk_1(cli_ctx *ctx, fmap_t *dmap, size_t if (infoid == 5) { hwp3_debug("HWP3.x: Information Block[%llu]: TYPE: Booking Information\n", infoloc); - if (SCAN_COLLECT_METADATA) + if (SCAN_COLLECT_METADATA) { cli_jsonstr(entry, "Type", "Booking Information"); + } return CL_SUCCESS; } @@ -1589,10 +1643,13 @@ static inline cl_error_t parsehwp3_infoblk_1(cli_ctx *ctx, fmap_t *dmap, size_t if (infolen == 0) { hwp3_debug("HWP3.x: Information Block[%llu]: TYPE: Terminating Entry\n", infoloc); - if (SCAN_COLLECT_METADATA) + if (SCAN_COLLECT_METADATA) { cli_jsonstr(entry, "Type", "Terminating Entry"); + } - if (last) *last = 1; + if (last) { + *last = 1; + } return CL_SUCCESS; } else { cli_errmsg("HWP3.x: Information Block[%llu]: TYPE: Invalid Terminating Entry\n", infoloc); @@ -1601,8 +1658,9 @@ static inline cl_error_t parsehwp3_infoblk_1(cli_ctx *ctx, fmap_t *dmap, size_t case 1: /* Image Data */ hwp3_debug("HWP3.x: Information Block[%llu]: TYPE: Image Data\n", infoloc); - if (SCAN_COLLECT_METADATA) + if (SCAN_COLLECT_METADATA) { cli_jsonstr(entry, "Type", "Image Data"); + } #if HWP3_DEBUG /* additional fields can be added */ memset(field, 0, HWP3_FIELD_LENGTH); @@ -1620,19 +1678,22 @@ static inline cl_error_t parsehwp3_infoblk_1(cli_ctx *ctx, fmap_t *dmap, size_t hwp3_debug("HWP3.x: Information Block[%llu]: FORM: %s\n", infoloc, field); #endif /* 32 bytes for extra data fields */ - if (infolen > 0) + if (infolen > 0) { ret = cli_magic_scan_nested_fmap_type(map, *offset + 32, infolen - 32, ctx, CL_TYPE_ANY, NULL, LAYER_ATTRIBUTES_NONE); + } break; case 2: /* OLE2 Data */ hwp3_debug("HWP3.x: Information Block[%llu]: TYPE: OLE2 Data\n", infoloc); - if (SCAN_COLLECT_METADATA) + if (SCAN_COLLECT_METADATA) { cli_jsonstr(entry, "Type", "OLE2 Data"); + } - if (infolen > 0) + if (infolen > 0) { ret = cli_magic_scan_nested_fmap_type(map, *offset, infolen, ctx, CL_TYPE_ANY, NULL, LAYER_ATTRIBUTES_NONE); + } break; case 3: /* Hypertext/Hyperlink Information */ hwp3_debug("HWP3.x: Information Block[%llu]: TYPE: Hypertext/Hyperlink Information\n", infoloc); @@ -1666,8 +1727,9 @@ static inline cl_error_t parsehwp3_infoblk_1(cli_ctx *ctx, fmap_t *dmap, size_t case 4: /* Presentation Information */ hwp3_debug("HWP3.x: Information Block[%llu]: TYPE: Presentation Information\n", infoloc); - if (SCAN_COLLECT_METADATA) + if (SCAN_COLLECT_METADATA) { cli_jsonstr(entry, "Type", "Presentation Information"); + } /* contains nothing of interest to scan */ break; @@ -1675,8 +1737,9 @@ static inline cl_error_t parsehwp3_infoblk_1(cli_ctx *ctx, fmap_t *dmap, size_t /* should never run this as it is short-circuited above */ hwp3_debug("HWP3.x: Information Block[%llu]: TYPE: Booking Information\n", infoloc); - if (SCAN_COLLECT_METADATA) + if (SCAN_COLLECT_METADATA) { cli_jsonstr(entry, "Type", "Booking Information"); + } break; case 6: /* Background Image Data */ @@ -1696,31 +1759,35 @@ static inline cl_error_t parsehwp3_infoblk_1(cli_ctx *ctx, fmap_t *dmap, size_t hwp3_debug("HWP3.x: Information Block[%llu]: NAME: %s\n", infoloc, field); #endif /* 324 bytes for extra data fields */ - if (infolen > 0) + if (infolen > 0) { ret = cli_magic_scan_nested_fmap_type(map, *offset + 324, infolen - 324, ctx, CL_TYPE_ANY, NULL, LAYER_ATTRIBUTES_NONE); + } break; case 0x100: /* Table Extension */ hwp3_debug("HWP3.x: Information Block[%llu]: TYPE: Table Extension\n", infoloc); - if (SCAN_COLLECT_METADATA) + if (SCAN_COLLECT_METADATA) { cli_jsonstr(entry, "Type", "Table Extension"); + } /* contains nothing of interest to scan */ break; case 0x101: /* Press Frame Information Field Name */ hwp3_debug("HWP3.x: Information Block[%llu]: TYPE: Press Frame Information Field Name\n", infoloc); - if (SCAN_COLLECT_METADATA) + if (SCAN_COLLECT_METADATA) { cli_jsonstr(entry, "Type", "Press Frame Information Field Name"); + } /* contains nothing of interest to scan */ break; default: cli_warnmsg("HWP3.x: Information Block[%llu]: TYPE: UNKNOWN(%u)\n", infoloc, infoid); - if (infolen > 0) + if (infolen > 0) { ret = cli_magic_scan_nested_fmap_type(map, *offset, infolen, ctx, CL_TYPE_ANY, NULL, LAYER_ATTRIBUTES_NONE); + } } *offset += infolen; @@ -1766,28 +1833,32 @@ static cl_error_t hwp3_cb(void *cbdata, int fd, const char *filepath, cli_ctx *c } /* Fonts - 7 entries of 2 + (n x 40) bytes where n is the first 2 bytes of the entry */ - if (SCAN_COLLECT_METADATA) + if (SCAN_COLLECT_METADATA) { fonts = cli_jsonarray(ctx->wrkproperty, "FontCounts"); + } for (i = 0; i < 7; i++) { uint16_t nfonts; if (fmap_readn(map, &nfonts, offset, sizeof(nfonts)) != sizeof(nfonts)) { - if (dmap) + if (dmap) { funmap(dmap); + } return CL_EREAD; } nfonts = le16_to_host(nfonts); - if (SCAN_COLLECT_METADATA) + if (SCAN_COLLECT_METADATA) { cli_jsonint(fonts, NULL, nfonts); + } hwp3_debug("HWP3.x: Font Entry %d with %u entries @ offset %zu\n", i + 1, nfonts, offset); new_offset = offset + (2 + nfonts * 40); if ((new_offset <= offset) || (new_offset >= map->len)) { cli_errmsg("HWP3.x: Font Entry: number of fonts is too high, invalid. %u\n", nfonts); - if (dmap) + if (dmap) { funmap(dmap); + } return CL_EPARSE; } offset = new_offset; @@ -1795,21 +1866,24 @@ static cl_error_t hwp3_cb(void *cbdata, int fd, const char *filepath, cli_ctx *c /* Styles - 2 + (n x 238) bytes where n is the first 2 bytes of the section */ if (fmap_readn(map, &nstyles, offset, sizeof(nstyles)) != sizeof(nstyles)) { - if (dmap) + if (dmap) { funmap(dmap); + } return CL_EREAD; } nstyles = le16_to_host(nstyles); - if (SCAN_COLLECT_METADATA) + if (SCAN_COLLECT_METADATA) { cli_jsonint(ctx->wrkproperty, "StyleCount", nstyles); + } hwp3_debug("HWP3.x: %u Styles @ offset %zu\n", nstyles, offset); new_offset = offset + (2 + nstyles * 238); if ((new_offset <= offset) || (new_offset >= map->len)) { cli_errmsg("HWP3.x: Font Entry: number of font styles is too high, invalid. %u\n", nstyles); - if (dmap) + if (dmap) { funmap(dmap); + } return CL_EPARSE; } offset += (2 + nstyles * 238); @@ -1817,20 +1891,26 @@ static cl_error_t hwp3_cb(void *cbdata, int fd, const char *filepath, cli_ctx *c last = 0; /* Paragraphs - variable */ /* Paragraphs - are terminated with 0x0d00[13(CR) as hchar], empty paragraph marks end of section and do NOT end with 0x0d00 */ - while (!last && ((ret = parsehwp3_paragraph(ctx, map, p++, 0, &offset, &last)) == CL_SUCCESS)) continue; + while (!last && ((ret = parsehwp3_paragraph(ctx, map, p++, 0, &offset, &last)) == CL_SUCCESS)) { + continue; + } /* return is never a virus */ if (ret != CL_SUCCESS) { - if (dmap) + if (dmap) { funmap(dmap); + } return ret; } - if (SCAN_COLLECT_METADATA) + if (SCAN_COLLECT_METADATA) { cli_jsonint(ctx->wrkproperty, "ParagraphCount", p); + } last = 0; /* 'additional information block #1's - attachments and media */ - while (!last && ((ret = parsehwp3_infoblk_1(ctx, map, &offset, &last)) == CL_SUCCESS)) continue; + while (!last && ((ret = parsehwp3_infoblk_1(ctx, map, &offset, &last)) == CL_SUCCESS)) { + continue; + } /* scan the uncompressed stream - both compressed and uncompressed cases [ALLMATCH] */ if (ret == CL_SUCCESS) { @@ -1839,8 +1919,9 @@ static cl_error_t hwp3_cb(void *cbdata, int fd, const char *filepath, cli_ctx *c ret = cli_magic_scan_nested_fmap_type(map, start, dlen, ctx, CL_TYPE_ANY, NULL, LAYER_ATTRIBUTES_NONE); } - if (dmap) + if (dmap) { funmap(dmap); + } return ret; } @@ -1858,13 +1939,15 @@ cl_error_t cli_scanhwp3(cli_ctx *ctx) */ offset += HWP3_IDENTITY_INFO_SIZE; - if ((ret = parsehwp3_docinfo(ctx, offset, &docinfo)) != CL_SUCCESS) + if ((ret = parsehwp3_docinfo(ctx, offset, &docinfo)) != CL_SUCCESS) { return ret; + } offset += HWP3_DOCINFO_SIZE; - if ((ret = parsehwp3_docsummary(ctx, offset)) != CL_SUCCESS) + if ((ret = parsehwp3_docsummary(ctx, offset)) != CL_SUCCESS) { return ret; + } offset += HWP3_DOCSUMMARY_SIZE; @@ -1884,13 +1967,15 @@ cl_error_t cli_scanhwp3(cli_ctx *ctx) offset = new_offset; } - if (docinfo.di_compressed) + if (docinfo.di_compressed) { ret = decompress_and_callback(ctx, ctx->fmap, offset, 0, "HWP3.x", hwp3_cb, NULL); - else + } else { ret = hwp3_cb(&offset, 0, ctx->sub_filepath, ctx); + } - if (ret != CL_SUCCESS) + if (ret != CL_SUCCESS) { return ret; + } /* OPTIONAL TODO: HANDLE OPTIONAL ADDITIONAL INFORMATION BLOCK #2's FOR PRECLASS*/ @@ -1938,8 +2023,9 @@ static cl_error_t hwpml_scan_cb(void *cbdata, int fd, const char *filepath, cli_ { UNUSEDPARAM(cbdata); - if (fd < 0 || !ctx) + if (fd < 0 || !ctx) { return CL_ENULLARG; + } return cli_magic_scan_desc(fd, filepath, ctx, NULL, LAYER_ATTRIBUTES_NONE); } @@ -1956,19 +2042,21 @@ static cl_error_t hwpml_binary_cb(int fd, const char *filepath, cli_ctx *ctx, in /* check attributes for compression and encoding */ for (i = 0; i < num_attribs; i++) { if (!strcmp(attribs[i].key, "Compress")) { - if (!strcmp(attribs[i].value, "true")) + if (!strcmp(attribs[i].value, "true")) { com = 1; - else if (!strcmp(attribs[i].value, "false")) + } else if (!strcmp(attribs[i].value, "false")) { com = 0; - else + } else { com = -1; + } } if (!strcmp(attribs[i].key, "Encoding")) { - if (!strcmp(attribs[i].value, "Base64")) + if (!strcmp(attribs[i].value, "Base64")) { enc = 1; - else + } else { enc = -1; + } } } @@ -2065,8 +2153,9 @@ static cl_error_t hwpml_binary_cb(int fd, const char *filepath, cli_ctx *ctx, in hwpml_end: if (df) { close(df); - if (!(ctx->engine->keeptmp)) + if (!(ctx->engine->keeptmp)) { cli_unlink(tempfile); + } free(tempfile); } return ret; @@ -2082,8 +2171,9 @@ cl_error_t cli_scanhwpml(cli_ctx *ctx) cli_dbgmsg("in cli_scanhwpml()\n"); - if (!ctx) + if (!ctx) { return CL_ENULLARG; + } memset(&cbdata, 0, sizeof(cbdata)); cbdata.map = ctx->fmap; diff --git a/libclamav/is_tar.c b/libclamav/is_tar.c index 9e006b0afd..69b24316c4 100644 --- a/libclamav/is_tar.c +++ b/libclamav/is_tar.c @@ -34,8 +34,9 @@ int is_tar(const unsigned char *buf, unsigned int nbytes) int sum, recsum; char *p; - if (nbytes < sizeof(union record)) + if (nbytes < sizeof(union record)) { return 0; + } recsum = from_oct(8, header->header.chksum); @@ -50,15 +51,18 @@ int is_tar(const unsigned char *buf, unsigned int nbytes) } /* Adjust checksum to count the "chksum" field as blanks. */ - for (i = sizeof(header->header.chksum); --i >= 0;) + for (i = sizeof(header->header.chksum); --i >= 0;) { sum -= 0xFF & header->header.chksum[i]; + } sum += ' ' * sizeof header->header.chksum; - if (sum != recsum) + if (sum != recsum) { return 0; /* Not a tar archive */ + } - if (0 == strcmp(header->header.magic, TMAGIC)) + if (0 == strcmp(header->header.magic, TMAGIC)) { return 2; /* Unix Standard tar archive */ + } return 1; /* Old fashioned tar archive */ } @@ -74,8 +78,9 @@ static int from_oct(int digs, char *where) while (isspace((unsigned char)*where)) { /* Skip spaces */ where++; - if (--digs <= 0) + if (--digs <= 0) { return -1; /* All blank field */ + } } value = 0; while (digs > 0 && isodigit(*where)) { /* Scan til nonoctal */ @@ -83,8 +88,9 @@ static int from_oct(int digs, char *where) --digs; } - if (digs > 0 && *where && !isspace((unsigned char)*where)) + if (digs > 0 && *where && !isspace((unsigned char)*where)) { return -1; /* Ended on non-space/nul */ + } return value; } diff --git a/libclamav/ishield.c b/libclamav/ishield.c index afce32eca9..561f083061 100644 --- a/libclamav/ishield.c +++ b/libclamav/ishield.c @@ -382,19 +382,27 @@ cl_error_t cli_scanishield(cli_ctx *ctx, off_t off, size_t sz) while (ret == CL_SUCCESS) { fname = fmap_need_offstr(map, coff, 2048); - if (!fname) break; + if (!fname) { + break; + } coff += strlen(fname) + 1; path = fmap_need_offstr(map, coff, 2048); - if (!path) break; + if (!path) { + break; + } coff += strlen(path) + 1; version = fmap_need_offstr(map, coff, 2048); - if (!version) break; + if (!version) { + break; + } coff += strlen(version) + 1; strsz = fmap_need_offstr(map, coff, 2048); - if (!strsz) break; + if (!strsz) { + break; + } coff += strlen(strsz) + 1; data = &strsz[strlen(strsz) + 1]; @@ -403,7 +411,9 @@ cl_error_t cli_scanishield(cli_ctx *ctx, off_t off, size_t sz) if (fsize < 0 || fsize == LONG_MAX || !*strsz || !eostr || eostr == strsz || *eostr || (unsigned long)fsize >= sz || - (size_t)(data - fname) >= sz - fsize) break; + (size_t)(data - fname) >= sz - fsize) { + break; + } cli_dbgmsg("ishield: @%lx found file %s (%s) - version %s - size %lu\n", (unsigned long int)coff, fname, path, version, (unsigned long int)fsize); if (CL_SUCCESS != cli_matchmeta(ctx, fname, fsize, fsize, 0, fc++, 0)) { @@ -627,11 +637,13 @@ static cl_error_t is_parse_hdr(cli_ctx *ctx, struct IS_CABSTUFF *c) md5str((uint8_t *)hash); if (fmap_need_ptr_once(map, &hdr[dir_rel], 4)) { dir_rel = cli_readint32(&hdr[dir_rel]) + h1_data_off + objs_dirs_off; - if (fmap_need_str(map, &hdr[dir_rel], c->hdrsz - dir_rel)) + if (fmap_need_str(map, &hdr[dir_rel], c->hdrsz - dir_rel)) { dir_name = &hdr[dir_rel]; + } } - if (fmap_need_str(map, &hdr[file_rel], c->hdrsz - file_rel)) + if (fmap_need_str(map, &hdr[file_rel], c->hdrsz - file_rel)) { file_name = &hdr[file_rel]; + } file_stream_off = le64_to_host(file->stream_off); file_size = le64_to_host(file->size); @@ -652,9 +664,9 @@ static cl_error_t is_parse_hdr(cli_ctx *ctx, struct IS_CABSTUFF *c) file_name, (long long)file_size, (long long)file_csize, hash, (long long)file_stream_off, cabno, file->unk13, file->unk14, file->unk15); - if (file->flag_has_dup & 1) + if (file->flag_has_dup & 1) { cli_dbgmsg("is_parse_hdr: not scanned (dup)\n"); - else { + } else { if (file_size) { unsigned int j; cl_error_t cabret = CL_SUCCESS; @@ -671,10 +683,12 @@ static cl_error_t is_parse_hdr(cli_ctx *ctx, struct IS_CABSTUFF *c) scanned++; if (ctx->engine->maxfiles && scanned >= ctx->engine->maxfiles) { cli_dbgmsg("is_parse_hdr: File limit reached (max: %u)\n", ctx->engine->maxfiles); - if (file_name != emptyname) + if (file_name != emptyname) { fmap_unneed_ptr(map, (void *)file_name, strlen(file_name) + 1); - if (dir_name != emptyname) + } + if (dir_name != emptyname) { fmap_unneed_ptr(map, (void *)dir_name, strlen(dir_name) + 1); + } return CL_EMAXFILES; } cabret = is_extract_cab(ctx, file_stream_off + c->cabs[j].off, file_size, file_csize); @@ -691,10 +705,12 @@ static cl_error_t is_parse_hdr(cli_ctx *ctx, struct IS_CABSTUFF *c) cabret = CL_SUCCESS; } if (cabret != CL_SUCCESS) { - if (file_name != emptyname) + if (file_name != emptyname) { fmap_unneed_ptr(map, (void *)file_name, strlen(file_name) + 1); - if (dir_name != emptyname) + } + if (dir_name != emptyname) { fmap_unneed_ptr(map, (void *)dir_name, strlen(dir_name) + 1); + } return cabret; } } else { @@ -705,10 +721,12 @@ static cl_error_t is_parse_hdr(cli_ctx *ctx, struct IS_CABSTUFF *c) default: cli_dbgmsg("is_parse_hdr: skipped unknown file entry %u\n", i); } - if (file_name != emptyname) + if (file_name != emptyname) { fmap_unneed_ptr(map, (void *)file_name, strlen(file_name) + 1); - if (dir_name != emptyname) + } + if (dir_name != emptyname) { fmap_unneed_ptr(map, (void *)dir_name, strlen(dir_name) + 1); + } fmap_unneed_ptr(map, file, sizeof(*file)); } else { ret = CL_SUCCESS; @@ -801,8 +819,9 @@ static cl_error_t is_extract_cab(cli_ctx *ctx, uint64_t off, uint64_t size, uint zret = inflate(&z, 0); if (zret == Z_OK || zret == Z_STREAM_END || zret == Z_BUF_ERROR) { unsigned int umpd = IS_CABBUFSZ - z.avail_out; - if (cli_writen(ofd, outbuf, umpd) != umpd) + if (cli_writen(ofd, outbuf, umpd) != umpd) { break; + } outsz += umpd; if (zret == Z_STREAM_END || z.avail_out == IS_CABBUFSZ /* FIXMEISHIELD: is the latter ok? */) { success = 1; @@ -820,22 +839,29 @@ static cl_error_t is_extract_cab(cli_ctx *ctx, uint64_t off, uint64_t size, uint break; } inflateEnd(&z); - if (!success) break; + if (!success) { + break; + } } free(outbuf); if (success) { - if (outsz != size) + if (outsz != size) { cli_dbgmsg("is_extract_cab: extracted %llu bytes to %s, expected %llu, scanning anyway.\n", (long long)outsz, tempfile, (long long)size); - else + } else { cli_dbgmsg("is_extract_cab: extracted to %s\n", tempfile); - if (lseek(ofd, 0, SEEK_SET) == -1) + } + if (lseek(ofd, 0, SEEK_SET) == -1) { cli_dbgmsg("is_extract_cab: call to lseek() failed\n"); + } ret = cli_magic_scan_desc(ofd, tempfile, ctx, NULL, LAYER_ATTRIBUTES_NONE); } close(ofd); - if (!ctx->engine->keeptmp) - if (cli_unlink(tempfile)) ret = CL_EUNLINK; + if (!ctx->engine->keeptmp) { + if (cli_unlink(tempfile)) { + ret = CL_EUNLINK; + } + } free(tempfile); return success ? ret : CL_BREAK; } diff --git a/libclamav/iso9660.c b/libclamav/iso9660.c index a94d0573ed..b0c5186891 100644 --- a/libclamav/iso9660.c +++ b/libclamav/iso9660.c @@ -45,12 +45,14 @@ static const void *needblock(const iso9660_t *iso, unsigned int block, int temp) cli_ctx *ctx = iso->ctx; size_t loff; unsigned int blocks_per_sect = (2048 / iso->blocksz); - if (block > ((ctx->fmap->len - iso->base_offset) / iso->sectsz) * blocks_per_sect) - return NULL; /* Block is out of file */ + if (block > ((ctx->fmap->len - iso->base_offset) / iso->sectsz) * blocks_per_sect) { + return NULL; /* Block is out of file */ + } loff = (block / blocks_per_sect) * iso->sectsz; /* logical sector */ loff += (block % blocks_per_sect) * iso->blocksz; /* logical block within the sector */ - if (temp) + if (temp) { return fmap_need_off_once(ctx->fmap, iso->base_offset + loff, iso->blocksz); + } return fmap_need_off(ctx->fmap, iso->base_offset + loff, iso->blocksz); } @@ -103,8 +105,9 @@ static char *iso_string(iso9660_t *iso, const void *src, unsigned int len) if (iso->joliet) { char *utf8; const char *uutf8; - if (len > (sizeof(iso->buf) - 2)) + if (len > (sizeof(iso->buf) - 2)) { len = sizeof(iso->buf) - 2; + } memcpy(iso->buf, src, len); iso->buf[len] = '\0'; iso->buf[len + 1] = '\0'; @@ -156,8 +159,9 @@ static cl_error_t iso_parse_dir(iso9660_t *iso, unsigned int block, unsigned int unsigned int entrysz = *dir, fileoff, filesz; char *sep; - if (!dirsz || !entrysz) /* continuing on next block, if any */ + if (!dirsz || !entrysz) { /* continuing on next block, if any */ break; + } if (entrysz > dirsz) { /* record size overlaps onto the next sector, no point in looking in there */ cli_dbgmsg("iso_parse_dir: Directory entry overflow, breaking out %u %u\n", entrysz, dirsz); len = 0; @@ -182,10 +186,11 @@ static cl_error_t iso_parse_dir(iso9660_t *iso, unsigned int block, unsigned int } iso_string(iso, &dir[33], filesz); sep = memchr(iso->buf, ';', filesz); - if (sep) + if (sep) { *sep = '\0'; - else + } else { iso->buf[filesz] = '\0'; + } fileoff = cli_readint32(dir + 2); fileoff += dir[1]; filesz = cli_readint32(dir + 10); @@ -196,9 +201,9 @@ static cl_error_t iso_parse_dir(iso9660_t *iso, unsigned int block, unsigned int break; } - if (dir[26] || dir[27]) + if (dir[26] || dir[27]) { cli_dbgmsg("iso_parse_dir: Skipping interleaved file\n"); - else { + } else { /* TODO Handle multi-extent ? */ if (dir[25] & 2) { ret = iso_parse_dir(iso, fileoff, filesz); @@ -255,25 +260,31 @@ cl_error_t cli_scaniso(cli_ctx *ctx, size_t offset) } iso.blocksz = cli_readint32(privol + 128) & 0xffff; - if (iso.blocksz != 512 && iso.blocksz != 1024 && iso.blocksz != 2048) + if (iso.blocksz != 512 && iso.blocksz != 1024 && iso.blocksz != 2048) { /* Likely not a cdrom image */ goto done; + } iso.base_offset = offset - iso.sectsz * 16; iso.joliet = 0; for (i = 16; i < 32; i++) { /* scan for a joliet secondary volume descriptor */ next = fmap_need_off_once(ctx->fmap, iso.base_offset + i * iso.sectsz, 2048); - if (!next) + if (!next) { break; /* Out of disk */ - if (*next == 0xff || memcmp(next + 1, "CD001", 5)) + } + if (*next == 0xff || memcmp(next + 1, "CD001", 5)) { break; /* Not a volume descriptor */ - if (*next != 2) + } + if (*next != 2) { continue; /* Not a secondary volume descriptor */ - if (next[88] != 0x25 || next[89] != 0x2f) + } + if (next[88] != 0x25 || next[89] != 0x2f) { continue; /* Not a joliet descriptor */ - if (next[156 + 26] || next[156 + 27]) + } + if (next[156 + 26] || next[156 + 27]) { continue; /* Root is interleaved so we fallback to the primary descriptor */ + } switch (next[90]) { case 0x40: /* Level 1 */ iso.joliet = 1; @@ -336,8 +347,9 @@ cl_error_t cli_scaniso(cli_ctx *ctx, size_t offset) cli_dbgmsg("cli_scaniso: Opt MSB Path Table: 0x%x\n", cbswap32(cli_readint32(privol + 152))); cli_dbgmsg("cli_scaniso: File Structure Version: %u\n", privol[881]); - if (iso.joliet) + if (iso.joliet) { cli_dbgmsg("cli_scaniso: Joliet level %u\n", iso.joliet); + } } if (privol[156 + 26] || privol[156 + 27]) { diff --git a/libclamav/jpeg.c b/libclamav/jpeg.c index 284f6ac337..9dc61046c6 100644 --- a/libclamav/jpeg.c +++ b/libclamav/jpeg.c @@ -364,8 +364,9 @@ cl_error_t cli_parsejpeg(cli_ctx *ctx) } marker = (jpeg_marker_t)marker_u8; - if (prev_marker == JPEG_MARKER_NOT_A_MARKER_0xFF && marker != JPEG_MARKER_NOT_A_MARKER_0xFF) + if (prev_marker == JPEG_MARKER_NOT_A_MARKER_0xFF && marker != JPEG_MARKER_NOT_A_MARKER_0xFF) { break; + } prev_marker = marker; } if (i == 16) { @@ -573,8 +574,9 @@ cl_error_t cli_parsejpeg(cli_ctx *ctx) do { old_offset = photoshop_data_offset; status = jpeg_check_photoshop_8bim(ctx, &photoshop_data_offset); - if (photoshop_data_offset <= old_offset) + if (photoshop_data_offset <= old_offset) { break; + } } while (status == CL_CLEAN); if (status == CL_BREAK) { diff --git a/libclamav/json_api.c b/libclamav/json_api.c index be5a66e548..4f6a842fee 100644 --- a/libclamav/json_api.c +++ b/libclamav/json_api.c @@ -48,8 +48,9 @@ cl_error_t cli_json_parse_error(json_object *root, const char *errstr) { json_object *perr; - if (!root) + if (!root) { return CL_SUCCESS; /* CL_ENULLARG? */ + } perr = cli_jsonarray(root, "ParseErrors"); if (perr == NULL) { @@ -113,10 +114,11 @@ cl_error_t cli_jsonstr(json_object *obj, const char *key, const char *s) return CL_EMEM; } - if (objty == json_type_object) + if (objty == json_type_object) { json_object_object_add(obj, key, fpobj); - else if (objty == json_type_array) + } else if (objty == json_type_array) { json_object_array_add(obj, fpobj); + } return CL_SUCCESS; } @@ -151,10 +153,11 @@ cl_error_t cli_jsonstrlen(json_object *obj, const char *key, const char *s, int return CL_EMEM; } - if (objty == json_type_object) + if (objty == json_type_object) { json_object_object_add(obj, key, fpobj); - else if (objty == json_type_array) + } else if (objty == json_type_array) { json_object_array_add(obj, fpobj); + } return CL_SUCCESS; } @@ -184,10 +187,11 @@ cl_error_t cli_jsonint(json_object *obj, const char *key, int32_t i) return CL_EMEM; } - if (objty == json_type_object) + if (objty == json_type_object) { json_object_object_add(obj, key, fpobj); - else if (objty == json_type_array) + } else if (objty == json_type_array) { json_object_array_add(obj, fpobj); + } return CL_SUCCESS; } @@ -217,10 +221,11 @@ cl_error_t cli_jsonint64(json_object *obj, const char *key, int64_t i) return CL_EMEM; } - if (objty == json_type_object) + if (objty == json_type_object) { json_object_object_add(obj, key, fpobj); - else if (objty == json_type_array) + } else if (objty == json_type_array) { json_object_array_add(obj, fpobj); + } return CL_SUCCESS; } @@ -250,10 +255,11 @@ cl_error_t cli_jsonbool(json_object *obj, const char *key, int i) return CL_EMEM; } - if (objty == json_type_object) + if (objty == json_type_object) { json_object_object_add(obj, key, fpobj); - else if (objty == json_type_array) + } else if (objty == json_type_array) { json_object_array_add(obj, fpobj); + } return CL_SUCCESS; } @@ -283,10 +289,11 @@ cl_error_t cli_jsondouble(json_object *obj, const char *key, double d) return CL_EMEM; } - if (objty == json_type_object) + if (objty == json_type_object) { json_object_object_add(obj, key, fpobj); - else if (objty == json_type_array) + } else if (objty == json_type_array) { json_object_array_add(obj, fpobj); + } return CL_SUCCESS; } @@ -302,16 +309,18 @@ json_object *cli_jsonarray(json_object *obj, const char *key) } newobj = json_object_new_array(); - if (!(newobj)) + if (!(newobj)) { return NULL; + } if (obj) { objty = json_object_get_type(obj); if (key && objty == json_type_object) { json_object_object_add(obj, key, newobj); - if (!json_object_object_get_ex(obj, key, &newobj)) + if (!json_object_object_get_ex(obj, key, &newobj)) { return NULL; + } } else if (objty == json_type_array) { json_object_array_add(obj, newobj); } @@ -330,20 +339,23 @@ json_object *cli_jsonobj(json_object *obj, const char *key) json_type objty; json_object *newobj; - if (obj && key && json_object_object_get_ex(obj, key, &newobj)) + if (obj && key && json_object_object_get_ex(obj, key, &newobj)) { return json_object_is_type(newobj, json_type_object) ? newobj : NULL; + } newobj = json_object_new_object(); - if (!(newobj)) + if (!(newobj)) { return NULL; + } if (obj) { objty = json_object_get_type(obj); if (key && objty == json_type_object) { json_object_object_add(obj, key, newobj); - if (!json_object_object_get_ex(obj, key, &newobj)) + if (!json_object_object_get_ex(obj, key, &newobj)) { return NULL; + } } else if (objty == json_type_array) { json_object_array_add(obj, newobj); } @@ -385,8 +397,9 @@ cl_error_t cli_json_delowner(json_object *owner, const char *key, int idx) /* allocate the empty object to replace target object */ empty = cli_jsonobj(NULL, NULL); - if (NULL == empty) + if (NULL == empty) { return CL_EMEM; + } if (0 != json_object_array_put_idx(owner, idx, empty)) { /* this shouldn't be possible */ diff --git a/libclamav/jsparse/js-norm.c b/libclamav/jsparse/js-norm.c index e42e8fef46..3e2b973ef8 100644 --- a/libclamav/jsparse/js-norm.c +++ b/libclamav/jsparse/js-norm.c @@ -118,8 +118,9 @@ static struct scope *scope_new(struct parser_state *state) { struct scope *parent = state->current; struct scope *s = calloc(1, sizeof(*s)); - if (!s) + if (!s) { return NULL; + } if (cli_hashtab_init(&s->id_map, 10) < 0) { free(s); return NULL; @@ -288,8 +289,9 @@ static cl_error_t tokens_ensure_capacity(struct tokens *tokens, size_t cap) cap += 1024; /* Keep old data if OOM */ data = cli_max_realloc(tokens->data, cap * sizeof(*tokens->data)); - if (!data) + if (!data) { return CL_EMEM; + } tokens->data = data; tokens->capacity = cap; } @@ -298,8 +300,9 @@ static cl_error_t tokens_ensure_capacity(struct tokens *tokens, size_t cap) static int add_token(struct parser_state *state, const yystype *token) { - if (tokens_ensure_capacity(&state->tokens, state->tokens.cnt + 1)) + if (tokens_ensure_capacity(&state->tokens, state->tokens.cnt + 1)) { return -1; + } state->tokens.data[state->tokens.cnt++] = *token; return 0; } @@ -313,8 +316,9 @@ struct buf { static inline cl_error_t buf_outc(char c, struct buf *buf) { if (buf->pos >= sizeof(buf->buf)) { - if (write(buf->outfd, buf->buf, sizeof(buf->buf)) != sizeof(buf->buf)) + if (write(buf->outfd, buf->buf, sizeof(buf->buf)) != sizeof(buf->buf)) { return CL_EWRITE; + } buf->pos = 0; } buf->buf[buf->pos++] = c; @@ -329,15 +333,17 @@ static inline cl_error_t buf_outs(const char *s, struct buf *buf) i = buf->pos; while (*s) { while (i < buf_len && *s) { - if (isspace(*s & 0xff)) + if (isspace(*s & 0xff)) { buf->buf[i++] = ' '; - else + } else { buf->buf[i++] = tolower((unsigned char)(*s)); + } ++s; } if (i == buf_len) { - if (write(buf->outfd, buf->buf, buf_len) < 0) + if (write(buf->outfd, buf->buf, buf_len) < 0) { return CL_EWRITE; + } i = 0; } } @@ -347,8 +353,9 @@ static inline cl_error_t buf_outs(const char *s, struct buf *buf) static inline void output_space(char last, char current, struct buf *out) { - if (isalnum(last) && isalnum(current)) + if (isalnum(last) && isalnum(current)) { buf_outc(' ', out); + } } /* return class of last character */ @@ -544,13 +551,15 @@ static cl_error_t replace_token_range(struct tokens *dst, size_t start, size_t e size_t i; cli_dbgmsg(MODULE "Replacing tokens %lu - %lu with %lu tokens\n", (unsigned long)start, (unsigned long)end, (unsigned long)len); - if (start >= dst->cnt || end > dst->cnt) + if (start >= dst->cnt || end > dst->cnt) { return CL_EARG; + } for (i = start; i < end; i++) { free_token(&dst->data[i]); } - if (tokens_ensure_capacity(dst, dst->cnt - (end - start) + len)) + if (tokens_ensure_capacity(dst, dst->cnt - (end - start) + len)) { return CL_EMEM; + } memmove(&dst->data[start + len], &dst->data[end], (dst->cnt - end) * sizeof(dst->data[0])); if (with && len > 0) { memcpy(&dst->data[start], with->data, len * sizeof(dst->data[0])); @@ -561,10 +570,12 @@ static cl_error_t replace_token_range(struct tokens *dst, size_t start, size_t e static cl_error_t append_tokens(struct tokens *dst, const struct tokens *src) { - if (!dst || !src) + if (!dst || !src) { return CL_ENULLARG; - if (tokens_ensure_capacity(dst, dst->cnt + src->cnt)) + } + if (tokens_ensure_capacity(dst, dst->cnt + src->cnt)) { return CL_EMEM; + } cli_dbgmsg(MODULE "Appending %lu tokens\n", (unsigned long)(src->cnt)); memcpy(&dst->data[dst->cnt], src->data, src->cnt * sizeof(dst->data[0])); dst->cnt += src->cnt; @@ -584,10 +595,14 @@ static void decode_de(yystype *params[], struct text_buffer *txtbuf) const char *o; const char **tokens; - if (!p || !k) + if (!p || !k) { return; - for (o = k; *o; o++) - if (*o == '|') nsplit++; + } + for (o = k; *o; o++) { + if (*o == '|') { + nsplit++; + } + } nsplit++; tokens = malloc(sizeof(char *) * nsplit); if (!tokens) { @@ -597,31 +612,37 @@ static void decode_de(yystype *params[], struct text_buffer *txtbuf) do { while (*p && !isalnum(*p)) { - if (*p == '\\' && (p[1] == '\'' || p[1] == '\"')) + if (*p == '\\' && (p[1] == '\'' || p[1] == '\"')) { p++; - else + } else { textbuffer_putc(txtbuf, *p++); + } + } + if (!*p) { + break; } - if (!*p) break; val = 0; o = p; while (*p && isalnum(*p)) { unsigned x; unsigned char v = *p++; /* TODO: use a table here */ - if (v >= 'a') + if (v >= 'a') { x = 10 + v - 'a'; - else if (v >= 'A') + } else if (v >= 'A') { x = 36 + v - 'A'; - else + } else { x = v - '0'; + } val = val * a + x; } - if (val >= nsplit || !tokens[val] || !tokens[val][0]) - while (o != p) + if (val >= nsplit || !tokens[val] || !tokens[val][0]) { + while (o != p) { textbuffer_putc(txtbuf, *o++); - else + } + } else { textbuffer_append(txtbuf, tokens[val]); + } } while (*p); free((void *)tokens); textbuffer_append(txtbuf, "\0"); @@ -646,16 +667,19 @@ static void handle_de(yystype *tokens, size_t start, const size_t cnt, const cha for (i = start; i < cnt; i++) { if (tokens[i].type == TOK_FUNCTION) { - if (TOKEN_GET(&tokens[i], scope)) + if (TOKEN_GET(&tokens[i], scope)) { nesting++; - else + } else { nesting--; - if (!nesting) + } + if (!nesting) { break; + } } } - if (nesting) + if (nesting) { return; + } memset(parameters, 0, sizeof(parameters)); if (name) { /* find call to function */ @@ -669,10 +693,15 @@ static void handle_de(yystype *tokens, size_t start, const size_t cnt, const cha i += 2; for (j = 0; j < parameters_cnt && i < cnt; j++) { parameters[j] = &tokens[i++]; - if (j != parameters_cnt - 1) - while (i < cnt && tokens[i].type != TOK_COMMA) i++; - else - while (i < cnt && tokens[i].type != TOK_PAR_CLOSE) i++; + if (j != parameters_cnt - 1) { + while (i < cnt && tokens[i].type != TOK_COMMA) { + i++; + } + } else { + while (i < cnt && tokens[i].type != TOK_PAR_CLOSE) { + i++; + } + } i++; } if (j == parameters_cnt) { @@ -686,16 +715,25 @@ static void handle_de(yystype *tokens, size_t start, const size_t cnt, const cha } } } else { - while (i < cnt && tokens[i].type != TOK_PAR_OPEN) i++; + while (i < cnt && tokens[i].type != TOK_PAR_OPEN) { + i++; + } ++i; - if (i >= cnt) return; + if (i >= cnt) { + return; + } /* TODO: move this v to another func */ for (j = 0; j < parameters_cnt && i < cnt; j++) { parameters[j] = &tokens[i++]; - if (j != parameters_cnt - 1) - while (i < cnt && tokens[i].type != TOK_COMMA) i++; - else - while (i < cnt && tokens[i].type != TOK_PAR_CLOSE) i++; + if (j != parameters_cnt - 1) { + while (i < cnt && tokens[i].type != TOK_COMMA) { + i++; + } + } else { + while (i < cnt && tokens[i].type != TOK_PAR_CLOSE) { + i++; + } + } i++; } if (j == parameters_cnt) { @@ -759,14 +797,17 @@ static void handle_df(const yystype *tokens, size_t start, struct decode_result unsigned char clast; char *R; - if (tokens[start].type != TOK_StringLiteral) + if (tokens[start].type != TOK_StringLiteral) { return; + } str = TOKEN_GET(&tokens[start], string); - if (!str) + if (!str) { return; + } len = strlen(str); - if (!len) + if (!len) { return; + } clast = str[len - 1] - '0'; str[len - 1] = '\0'; @@ -788,8 +829,9 @@ static void handle_eval(struct tokens *tokens, size_t start, struct decode_resul { res->txtbuf.data = TOKEN_GET(&tokens->data[start], string); - if (start + 1 >= tokens->cnt) + if (start + 1 >= tokens->cnt) { return; + } if (res->txtbuf.data && tokens->data[start + 1].type == TOK_PAR_CLOSE) { TOKEN_SET(&tokens->data[start], string, NULL); @@ -822,8 +864,9 @@ static inline int state_update_scope(struct parser_state *state, const yystype * state->current = scope; } else { /* dummy token marking function end */ - if (state->current->parent) + if (state->current->parent) { state->current = state->current->parent; + } /* don't output this token, it is just a dummy marker */ return 0; } @@ -870,14 +913,15 @@ static void run_decoders(struct parser_state *state) } if (res.pos_end > res.pos_begin) { struct tokens parent_tokens; - if (res.pos_end < tokens->cnt && tokens->data[res.pos_end].type == TOK_SEMICOLON) + if (res.pos_end < tokens->cnt && tokens->data[res.pos_end].type == TOK_SEMICOLON) { res.pos_end++; + } parent_tokens = state->tokens; /* save current tokens */ /* initialize embedded context */ memset(&state->tokens, 0, sizeof(state->tokens)); - if (++state->rec > 16) + if (++state->rec > 16) { cli_dbgmsg(MODULE "recursion limit reached\n"); - else { + } else { cli_js_process_buffer(state, res.txtbuf.data, res.txtbuf.pos); --state->rec; } @@ -924,14 +968,16 @@ void cli_js_parse_done(struct parser_state *state) default: /* make gcc happy */ break; } - if (end != '\0') + if (end != '\0') { cli_js_process_buffer(state, &end, 1); + } /* close remaining parenthesis */ for (i = 0; i < tokens->cnt; i++) { - if (tokens->data[i].type == TOK_PAR_OPEN) + if (tokens->data[i].type == TOK_PAR_OPEN) { par_balance++; - else if (tokens->data[i].type == TOK_PAR_CLOSE && par_balance > 0) + } else if (tokens->data[i].type == TOK_PAR_CLOSE && par_balance > 0) { par_balance--; + } } if (par_balance > 0) { memset(&val, 0, sizeof(val)); @@ -974,12 +1020,14 @@ void cli_js_output(struct parser_state *state, const char *tempdir) buf_outs("", 9)) + if (buf.pos < 9 || memcmp(buf.buf + buf.pos - 9, "", 9)) { buf_outs("", &buf); + } if (write(buf.outfd, buf.buf, buf.pos) < 0) { cli_dbgmsg(MODULE "I/O error\n"); } @@ -990,16 +1038,18 @@ void cli_js_output(struct parser_state *state, const char *tempdir) void cli_js_destroy(struct parser_state *state) { size_t i; - if (!state) + if (!state) { return; + } scope_free_all(state->list); for (i = 0; i < state->tokens.cnt; i++) { free_token(&state->tokens.data[i]); } free(state->tokens.data); /* detect use after free */ - if (state->scanner) + if (state->scanner) { yylex_destroy(state->scanner); + } memset(state, 0x55, sizeof(*state)); free(state); cli_dbgmsg(MODULE "cli_js_destroy() done\n"); @@ -1116,10 +1166,11 @@ void cli_js_process_buffer(struct parser_state *state, const char *buf, size_t n } break; case TOK_CURLY_BRACE_CLOSE: - if (current->blocks > 0) + if (current->blocks > 0) { current->blocks--; - else + } else { state->syntax_errors++; + } if (!current->blocks) { if (current->parent) { /* add dummy FUNCTION token to @@ -1140,10 +1191,11 @@ void cli_js_process_buffer(struct parser_state *state, const char *buf, size_t n current->brackets++; break; case TOK_BRACKET_CLOSE: - if (current->brackets > 0) + if (current->brackets > 0) { current->brackets--; - else + } else { state->syntax_errors++; + } break; case TOK_COMMA: if (current->fsm_state == InsideInitializer && current->brackets == 0 && current->blocks == 0) { @@ -1182,8 +1234,9 @@ void cli_js_process_buffer(struct parser_state *state, const char *buf, size_t n free_token(&state->tokens.data[--state->tokens.cnt]); str = cli_max_realloc(str, str_len + leng + 1); - if (!str) + if (!str) { break; + } strncpy(str + str_len, text, leng); str[str_len + leng] = '\0'; TOKEN_SET(prev_string, string, str); @@ -1210,8 +1263,9 @@ void cli_js_process_buffer(struct parser_state *state, const char *buf, size_t n struct parser_state *cli_js_init(void) { struct parser_state *state = calloc(1, sizeof(*state)); - if (!state) + if (!state) { return NULL; + } if (!scope_new(state)) { free(state); return NULL; @@ -1554,8 +1608,9 @@ static void textbuf_clean(struct text_buffer *buf) { if (buf->capacity > BUF_KEEP_SIZE) { char *data = cli_max_realloc(buf->data, BUF_KEEP_SIZE); - if (data) + if (data) { buf->data = data; + } buf->capacity = BUF_KEEP_SIZE; } buf->pos = 0; @@ -1576,10 +1631,11 @@ static inline int parseString(YYSTYPE *lvalp, yyscan_t scanner, const char q, } break; } while (1); - if (end && end >= start) + if (end && end >= start) { len = end - start; - else + } else { len = scanner->insize - scanner->pos; + } cli_textbuffer_append_normalize(&scanner->buf, start, len); if (end) { char *str; @@ -1641,8 +1697,9 @@ static inline int parseNumber(YYSTYPE *lvalp, yyscan_t scanner) scanner->pos--; textbuffer_putc(&scanner->buf, '\0'); scanner->state = Initial; - if (!scanner->buf.data) + if (!scanner->buf.data) { return 0; + } if (is_float) { TOKEN_SET(lvalp, dval, atof(scanner->buf.data)); return TOK_NumericFloat; @@ -1845,8 +1902,9 @@ static int yylex(YYSTYPE *lvalp, yyscan_t scanner) while (scanner->pos < scanner->insize) { /* htmlnorm converts \n to space, so * stop on space too */ - if (in[scanner->pos] == '\n' || in[scanner->pos] == ' ') + if (in[scanner->pos] == '\n' || in[scanner->pos] == ' ') { break; + } scanner->pos++; } scanner->state = Initial; diff --git a/libclamav/libmspack.c b/libclamav/libmspack.c index 8773316d06..ef827e8d36 100644 --- a/libclamav/libmspack.c +++ b/libclamav/libmspack.c @@ -117,12 +117,15 @@ static void mspack_fmap_close(struct mspack_file *file) { struct mspack_handle *mspack_handle = (struct mspack_handle *)file; - if (!mspack_handle) + if (!mspack_handle) { return; + } - if (mspack_handle->type == FILETYPE_FILENAME) - if (mspack_handle->f) + if (mspack_handle->type == FILETYPE_FILENAME) { + if (mspack_handle->f) { fclose(mspack_handle->f); + } + } memset(mspack_handle, 0, (sizeof(*mspack_handle))); free(mspack_handle); @@ -191,12 +194,14 @@ static int mspack_fmap_write(struct mspack_file *file, void *buffer, int bytes) return -1; } - if (!bytes) + if (!bytes) { return 0; + } max_size = mspack_handle->max_size; - if (!max_size) + if (!max_size) { return bytes; + } max_size = max_size < (uint64_t)bytes ? max_size : (uint64_t)bytes; @@ -268,11 +273,13 @@ static off_t mspack_fmap_tell(struct mspack_file *file) { struct mspack_handle *mspack_handle = (struct mspack_handle *)file; - if (!mspack_handle) + if (!mspack_handle) { return -1; + } - if (mspack_handle->type == FILETYPE_FMAP) + if (mspack_handle->type == FILETYPE_FMAP) { return mspack_handle->offset; + } return (off_t)ftell(mspack_handle->f); } diff --git a/libclamav/lzma_iface.c b/libclamav/lzma_iface.c index 3240991461..70cb1953c3 100644 --- a/libclamav/lzma_iface.c +++ b/libclamav/lzma_iface.c @@ -76,27 +76,35 @@ int cli_LzmaInit(struct CLI_LZMA *L, uint64_t size_override) L->usize = 0; } L->init = 1; - } else if (size_override) + } else if (size_override) { cli_warnmsg("cli_LzmaInit: ignoring late size override\n"); + } - if (L->freeme) return LZMA_RESULT_OK; + if (L->freeme) { + return LZMA_RESULT_OK; + } while (L->p_cnt) { L->header[LZMA_PROPS_SIZE - L->p_cnt] = lzma_getbyte(L, &fail); - if (fail) return LZMA_RESULT_OK; + if (fail) { + return LZMA_RESULT_OK; + } L->p_cnt--; } while (L->s_cnt) { uint64_t c = (uint64_t)lzma_getbyte(L, &fail); - if (fail) return LZMA_RESULT_OK; + if (fail) { + return LZMA_RESULT_OK; + } L->usize |= c << (8 * (8 - L->s_cnt)); L->s_cnt--; } LzmaDec_Construct(&L->state); - if (LzmaDec_Allocate(&L->state, L->header, LZMA_PROPS_SIZE, &g_Alloc) != SZ_OK) + if (LzmaDec_Allocate(&L->state, L->header, LZMA_PROPS_SIZE, &g_Alloc) != SZ_OK) { return LZMA_RESULT_DATA_ERROR; + } LzmaDec_Init(&L->state); L->freeme = 1; @@ -105,8 +113,9 @@ int cli_LzmaInit(struct CLI_LZMA *L, uint64_t size_override) void cli_LzmaShutdown(struct CLI_LZMA *L) { - if (L->freeme) + if (L->freeme) { LzmaDec_Free(&L->state, &g_Alloc); + } return; } @@ -117,7 +126,9 @@ int cli_LzmaDecode(struct CLI_LZMA *L) ELzmaStatus status; ELzmaFinishMode finish; - if (!L->freeme) return cli_LzmaInit(L, 0); + if (!L->freeme) { + return cli_LzmaInit(L, 0); + } inbytes = L->avail_in; if (~L->usize && L->avail_out > L->usize) { @@ -132,10 +143,14 @@ int cli_LzmaDecode(struct CLI_LZMA *L) L->next_in += inbytes; L->avail_out -= outbytes; L->next_out += outbytes; - if (~L->usize) L->usize -= outbytes; - if (res != SZ_OK) + if (~L->usize) { + L->usize -= outbytes; + } + if (res != SZ_OK) { return LZMA_RESULT_DATA_ERROR; - if (!L->usize || status == LZMA_STATUS_FINISHED_WITH_MARK) + } + if (!L->usize || status == LZMA_STATUS_FINISHED_WITH_MARK) { return LZMA_STREAM_END; + } return LZMA_RESULT_OK; } diff --git a/libclamav/lzw/lzwdec.c b/libclamav/lzw/lzwdec.c index 788b140898..567c6c5257 100644 --- a/libclamav/lzw/lzwdec.c +++ b/libclamav/lzw/lzwdec.c @@ -212,8 +212,9 @@ int lzwInflate(lzw_streamp strm) uint32_t flags; if (strm == NULL || strm->state == NULL || strm->next_out == NULL || - (strm->next_in == NULL && strm->avail_in != 0)) + (strm->next_in == NULL && strm->avail_in != 0)) { return LZW_STREAM_ERROR; + } /* load state */ to = strm->next_out; @@ -237,8 +238,9 @@ int lzwInflate(lzw_streamp strm) cext = flags & LZW_FLAG_EXTNCODE; free_code = free_entp - &state->dec_codetab[0]; - if (oldcodep == &state->dec_codetab[CODE_EOI]) + if (oldcodep == &state->dec_codetab[CODE_EOI]) { return LZW_STREAM_END; + } /* * Restart interrupted output operation. @@ -282,8 +284,9 @@ int lzwInflate(lzw_streamp strm) if (left > 0 && (oldcodep == &state->dec_codetab[CODE_CLEAR])) { code = CODE_CLEAR; CodeClear(code); - if (ret != LZW_OK) + if (ret != LZW_OK) { goto inf_end; + } } while (left > 0) { @@ -294,8 +297,9 @@ int lzwInflate(lzw_streamp strm) } if (code == CODE_CLEAR) { CodeClear(code); - if (ret != LZW_OK) + if (ret != LZW_OK) { break; + } continue; } codep = state->dec_codetab + code; @@ -305,10 +309,11 @@ int lzwInflate(lzw_streamp strm) /* non-earlychange bit expansion */ if (!echg && free_entp > maxcodep) { if (++nbits > BITS_VALID) { - if (!cext) + if (!cext) { nbits = BITS_VALID; - else if (nbits > BITS_MAX) + } else if (nbits > BITS_MAX) { nbits = BITS_MAX; + } } nbitsmask = MAXCODE(nbits); maxcodep = state->dec_codetab + nbitsmask - 1; @@ -331,19 +336,22 @@ int lzwInflate(lzw_streamp strm) /* earlychange bit expansion */ if (echg && free_entp > maxcodep) { if (++nbits > BITS_VALID) { - if (!cext) + if (!cext) { nbits = BITS_VALID; - else if (nbits > BITS_MAX) + } else if (nbits > BITS_MAX) { nbits = BITS_MAX; + } } nbitsmask = MAXCODE(nbits); maxcodep = state->dec_codetab + nbitsmask - 1; } - if (free_code++ > CODE_VALID) + if (free_code++ > CODE_VALID) { flags |= LZW_FLAG_EXTNCODEUSE; + } oldcodep = codep; - } else + } else { flags |= LZW_FLAG_FULLDICT; + } if (code >= CODE_BASIC) { /* check if code is valid */ if (code >= free_code) { @@ -383,8 +391,9 @@ int lzwInflate(lzw_streamp strm) *--wp = codep->value; codep = codep->next; } while (codep != NULL); - } else + } else { *to++ = code, left--; + } } inf_end: diff --git a/libclamav/macho.c b/libclamav/macho.c index 3f53dc9f97..fc08cac901 100644 --- a/libclamav/macho.c +++ b/libclamav/macho.c @@ -246,39 +246,47 @@ cl_error_t cli_scanmacho(cli_ctx *ctx, struct cli_exe_info *fileinfo) switch (EC32(hdr.cpu_type, conv)) { case 7: - if (!get_fileinfo) + if (!get_fileinfo) { cli_dbgmsg("MACHO: CPU Type: Intel 32-bit\n"); + } arch = 1; break; case 7 | 0x1000000: - if (!get_fileinfo) + if (!get_fileinfo) { cli_dbgmsg("MACHO: CPU Type: Intel 64-bit\n"); + } break; case 12: - if (!get_fileinfo) + if (!get_fileinfo) { cli_dbgmsg("MACHO: CPU Type: ARM\n"); + } break; case 14: - if (!get_fileinfo) + if (!get_fileinfo) { cli_dbgmsg("MACHO: CPU Type: SPARC\n"); + } break; case 18: - if (!get_fileinfo) + if (!get_fileinfo) { cli_dbgmsg("MACHO: CPU Type: POWERPC 32-bit\n"); + } arch = 2; break; case 18 | 0x1000000: - if (!get_fileinfo) + if (!get_fileinfo) { cli_dbgmsg("MACHO: CPU Type: POWERPC 64-bit\n"); + } arch = 3; break; default: - if (!get_fileinfo) + if (!get_fileinfo) { cli_dbgmsg("MACHO: CPU Type: ** UNKNOWN ** (%u)\n", EC32(hdr.cpu_type, conv)); + } break; } - if (!get_fileinfo) switch (EC32(hdr.filetype, conv)) { + if (!get_fileinfo) { + switch (EC32(hdr.filetype, conv)) { case 0x1: /* MH_OBJECT */ cli_dbgmsg("MACHO: Filetype: Relocatable object file\n"); break; @@ -309,14 +317,16 @@ cl_error_t cli_scanmacho(cli_ctx *ctx, struct cli_exe_info *fileinfo) default: cli_dbgmsg("MACHO: Filetype: ** UNKNOWN ** (0x%x)\n", EC32(hdr.filetype, conv)); } + } if (!get_fileinfo) { cli_dbgmsg("MACHO: Number of load commands: %u\n", EC32(hdr.ncmds, conv)); cli_dbgmsg("MACHO: Size of load commands: %u\n", EC32(hdr.sizeofcmds, conv)); } - if (m64) + if (m64) { at += 4; + } hdr.ncmds = EC32(hdr.ncmds, conv); if (!hdr.ncmds || hdr.ncmds > 1024) { @@ -371,8 +381,9 @@ cl_error_t cli_scanmacho(cli_ctx *ctx, struct cli_exe_info *fileinfo) RETURN_BROKEN; } if (!nsects) { - if (!get_fileinfo) + if (!get_fileinfo) { cli_dbgmsg("MACHO: ------------------\n"); + } continue; } sections = (struct cli_exe_section *)cli_max_realloc_or_free(sections, (sect + nsects) * sizeof(struct cli_exe_section)); @@ -422,13 +433,15 @@ cl_error_t cli_scanmacho(cli_ctx *ctx, struct cli_exe_info *fileinfo) cli_dbgmsg("MACHO: Virtual address: 0x%x\n", (unsigned int)sections[sect].rva); cli_dbgmsg("MACHO: Virtual size: %u\n", (unsigned int)sections[sect].vsz); cli_dbgmsg("MACHO: Raw size: %u\n", (unsigned int)sections[sect].rsz); - if (sections[sect].raw) + if (sections[sect].raw) { cli_dbgmsg("MACHO: File offset: %u\n", (unsigned int)sections[sect].raw); + } } sect++; } - if (!get_fileinfo) + if (!get_fileinfo) { cli_dbgmsg("MACHO: ------------------\n"); + } } else if (arch && (load_cmd.cmd == 0x4 || load_cmd.cmd == 0x5)) { /* LC_(UNIX)THREAD */ at += 8; @@ -479,14 +492,16 @@ cl_error_t cli_scanmacho(cli_ctx *ctx, struct cli_exe_info *fileinfo) return CL_EARG; } } else { - if (EC32(load_cmd.cmdsize, conv) > sizeof(load_cmd)) + if (EC32(load_cmd.cmdsize, conv) > sizeof(load_cmd)) { at += EC32(load_cmd.cmdsize, conv) - sizeof(load_cmd); + } } } if (ep) { - if (!get_fileinfo) + if (!get_fileinfo) { cli_dbgmsg("Entry Point: 0x%x\n", ep); + } if (sections) { ep = cli_rawaddr(ep, sections, sect, &err); if (err) { @@ -494,8 +509,9 @@ cl_error_t cli_scanmacho(cli_ctx *ctx, struct cli_exe_info *fileinfo) free(sections); return CL_EFORMAT; } - if (!get_fileinfo) + if (!get_fileinfo) { cli_dbgmsg("Entry Point file offset: %u\n", ep); + } } } @@ -540,8 +556,9 @@ cl_error_t cli_scanmacho_unibin(cli_ctx *ctx) } fat_header.nfats = EC32(fat_header.nfats, conv); - if ((fat_header.nfats & 0xffff) >= 39) /* Java Bytecode */ + if ((fat_header.nfats & 0xffff) >= 39) { /* Java Bytecode */ return CL_CLEAN; + } if (fat_header.nfats > 32) { cli_dbgmsg("cli_scanmacho_unibin: Invalid number of architectures\n"); diff --git a/libclamav/matcher-ac.c b/libclamav/matcher-ac.c index 77cc331c7a..072f8206ec 100644 --- a/libclamav/matcher-ac.c +++ b/libclamav/matcher-ac.c @@ -151,8 +151,9 @@ static int patt_cmp_fn(const struct cli_ac_patt *a, const struct cli_ac_patt *b) } RETURN_RES_IF_NE(a->special, b->special); - if (!a->special && !b->special) + if (!a->special && !b->special) { return 0; + } for (i = 0; i < a->special; i++) { struct cli_ac_special *spcl_a = a->special_table[i], *spcl_b = b->special_table[i]; @@ -163,20 +164,26 @@ static int patt_cmp_fn(const struct cli_ac_patt *a, const struct cli_ac_patt *b) if (spcl_a->type == AC_SPECIAL_ALT_CHAR) { res = memcmp((spcl_a->alt).byte, (spcl_b->alt).byte, spcl_a->num); - if (res) return res; + if (res) { + return res; + } } else if (spcl_a->type == AC_SPECIAL_ALT_STR_FIXED) { unsigned int j; RETURN_RES_IF_NE(spcl_a->len[0], spcl_b->len[0]); for (j = 0; j < spcl_a->num; j++) { res = memcmp((spcl_a->alt).f_str[j], (spcl_b->alt).f_str[j], spcl_a->len[0]); - if (res) return res; + if (res) { + return res; + } } } else if (spcl_a->type == AC_SPECIAL_ALT_STR) { struct cli_alt_node *alt_a = (spcl_a->alt).v_str, *alt_b = (spcl_b->alt).v_str; while (alt_a && alt_b) { RETURN_RES_IF_NE(alt_a->len, alt_b->len); res = memcmp(alt_a->str, alt_b->str, alt_a->len); - if (res) return res; + if (res) { + return res; + } alt_a = alt_a->next; alt_b = alt_b->next; } @@ -201,8 +208,9 @@ static int sort_list_fn(const void *a, const void *b) /* 2. Group together equal pattern in a node * (this is for building the next_same list) */ res = patt_cmp_fn(patt_a, patt_b); - if (res) + if (res) { return res; + } /* 3. Sort equal patterns in a node by partno in ascending order * (this is required by the matcher) */ @@ -231,12 +239,14 @@ static int sort_heads_by_partno_fn(const void *a, const void *b) while (1) { if (!list_a->next_same) { - if (!list_b->next_same) + if (!list_b->next_same) { break; + } return +1; } - if (!list_b->next_same) + if (!list_b->next_same) { return -1; + } list_a = list_a->next_same; list_b = list_b->next_same; } @@ -277,8 +287,9 @@ static inline void link_node_lists(struct cli_ac_list **listtable, unsigned int /* Link heads in the next list */ node->list = listtable[0]; - for (i = 1; i < nheads; i++) + for (i = 1; i < nheads; i++) { listtable[i - 1]->next = listtable[i]; + } listtable[nheads - 1]->next = NULL; } @@ -287,8 +298,9 @@ static void link_lists(struct cli_matcher *root) struct cli_ac_node *curnode; unsigned int i, grouplen; - if (!root->ac_lists) + if (!root->ac_lists) { return; + } /* Group the list by owning node, pattern equality and sort by partno */ cli_qsort(root->ac_listtable, root->ac_lists, sizeof(root->ac_listtable[0]), sort_list_fn); @@ -387,8 +399,9 @@ static inline struct cli_ac_node *add_new_node(struct cli_matcher *root, uint16_ if (!newtable) { root->ac_nodes--; cli_errmsg("cli_ac_addpatt: Can't realloc ac_nodetable\n"); - if (new->trans) + if (new->trans) { MPOOL_FREE(root->mempool, new->trans); + } MPOOL_FREE(root->mempool, new); return NULL; } @@ -427,25 +440,30 @@ static int cli_ac_addpatt_recursive(struct cli_matcher *root, struct cli_ac_patt */ if ((pattern->sigopts & ACPATT_OPTION_NOCASE) && (pattern->pattern[i] & 0xff) < 0x80 && isalpha((unsigned char)(pattern->pattern[i] & 0xff))) { next = pt->trans[CLI_NOCASEI((unsigned char)(pattern->pattern[i] & 0xff))]; - if (!next) + if (!next) { next = add_new_node(root, i, len); - if (!next) + } + if (!next) { return CL_EMEM; - else + } else { pt->trans[CLI_NOCASEI((unsigned char)(pattern->pattern[i] & 0xff))] = next; + } - if ((ret = cli_ac_addpatt_recursive(root, pattern, next, i + 1, len)) != CL_SUCCESS) + if ((ret = cli_ac_addpatt_recursive(root, pattern, next, i + 1, len)) != CL_SUCCESS) { return ret; + } } /* normal transition, also enumerates the 'normal' nocase */ next = pt->trans[(unsigned char)(pattern->pattern[i] & 0xff)]; - if (!next) + if (!next) { next = add_new_node(root, i, len); - if (!next) + } + if (!next) { return CL_EMEM; - else + } else { pt->trans[(unsigned char)(pattern->pattern[i] & 0xff)] = next; + } return cli_ac_addpatt_recursive(root, pattern, next, i + 1, len); } @@ -524,8 +542,9 @@ static struct cli_ac_node *bfs_dequeue(struct bfs_list **bfs, struct bfs_list ** *bfs = (*bfs)->next; pt = lpt->node; - if (lpt == *last) + if (lpt == *last) { *last = NULL; + } free(lpt); return pt; @@ -544,8 +563,9 @@ static int ac_maketrans(struct cli_matcher *root) ac_root->trans[i] = ac_root; } else { node->fail = ac_root; - if ((ret = bfs_enqueue(&bfs, &bfs_last, node))) + if ((ret = bfs_enqueue(&bfs, &bfs_last, node))) { return ret; + } } } @@ -553,11 +573,13 @@ static int ac_maketrans(struct cli_matcher *root) if (IS_LEAF(node)) { struct cli_ac_node *failtarget = node->fail; - while (NULL != failtarget && (IS_LEAF(failtarget) || !IS_FINAL(failtarget))) + while (NULL != failtarget && (IS_LEAF(failtarget) || !IS_FINAL(failtarget))) { failtarget = failtarget->fail; + } - if (NULL != failtarget) + if (NULL != failtarget) { node->fail = failtarget; + } continue; } @@ -567,13 +589,15 @@ static int ac_maketrans(struct cli_matcher *root) if (child) { fail = node->fail; - while (IS_LEAF(fail) || !fail->trans[i]) + while (IS_LEAF(fail) || !fail->trans[i]) { fail = fail->fail; + } child->fail = fail->trans[i]; - if ((ret = bfs_enqueue(&bfs, &bfs_last, child)) != 0) + if ((ret = bfs_enqueue(&bfs, &bfs_last, child)) != 0) { return ret; + } } } } @@ -582,21 +606,24 @@ static int ac_maketrans(struct cli_matcher *root) for (i = 0; i < 256; i++) { node = ac_root->trans[i]; if (node != ac_root) { - if ((ret = bfs_enqueue(&bfs, &bfs_last, node))) + if ((ret = bfs_enqueue(&bfs, &bfs_last, node))) { return ret; + } } } while ((node = bfs_dequeue(&bfs, &bfs_last))) { - if (IS_LEAF(node)) + if (IS_LEAF(node)) { continue; + } for (i = 0; i < 256; i++) { child = node->trans[i]; if (!child || (!IS_FINAL(child) && IS_LEAF(child))) { struct cli_ac_node *failtarget = node->fail; - while (IS_LEAF(failtarget) || !failtarget->trans[i]) + while (IS_LEAF(failtarget) || !failtarget->trans[i]) { failtarget = failtarget->fail; + } failtarget = failtarget->trans[i]; node->trans[i] = failtarget; @@ -605,8 +632,9 @@ static int ac_maketrans(struct cli_matcher *root) list = child->list; if (list) { - while (list->next) + while (list->next) { list = list->next; + } list->next = child->fail->list; } else { @@ -615,8 +643,9 @@ static int ac_maketrans(struct cli_matcher *root) child->trans = child->fail->trans; } else { - if ((ret = bfs_enqueue(&bfs, &bfs_last, child)) != 0) + if ((ret = bfs_enqueue(&bfs, &bfs_last, child)) != 0) { return ret; + } } } } @@ -626,16 +655,18 @@ static int ac_maketrans(struct cli_matcher *root) cl_error_t cli_ac_buildtrie(struct cli_matcher *root) { - if (!root) + if (!root) { return CL_EMALFDB; + } if (!(root->ac_root)) { cli_dbgmsg("cli_ac_buildtrie: AC pattern matcher is not initialised\n"); return CL_SUCCESS; } - if (root->filter) + if (root->filter) { cli_dbgmsg("Using filter for trie %d\n", root->type); + } link_lists(root); @@ -690,16 +721,18 @@ static void ac_free_special(struct cli_ac_patt *p) struct cli_ac_special *a1; struct cli_alt_node *b1, *b2; - if (!p->special) + if (!p->special) { return; + } for (i = 0; i < p->special; i++) { a1 = p->special_table[i]; if (a1->type == AC_SPECIAL_ALT_CHAR) { MPOOL_FREE(mempool, (a1->alt).byte); } else if (a1->type == AC_SPECIAL_ALT_STR_FIXED) { - for (j = 0; j < a1->num; j++) + for (j = 0; j < a1->num; j++) { MPOOL_FREE(mempool, (a1->alt).f_str[j]); + } MPOOL_FREE(mempool, (a1->alt).f_str); } else if (a1->type == AC_SPECIAL_ALT_STR) { b1 = (a1->alt).v_str; @@ -816,8 +849,9 @@ int cli_ac_chklsig(const char *expr, const char *end, uint32_t *lsigcnt, unsigne } } - if (op) + if (op) { break; + } if (op1 && !pth) { blkend = i; @@ -825,22 +859,25 @@ int cli_ac_chklsig(const char *expr, const char *end, uint32_t *lsigcnt, unsigne blkmod = expr[i + 1]; ret = sscanf(&expr[i + 2], "%u,%u", &modval1, &modval2); - if (ret != 2) + if (ret != 2) { ret = sscanf(&expr[i + 2], "%u", &modval1); + } if (!ret || ret == EOF) { cli_errmsg("chklexpr: Syntax error: Missing number after '%c'\n", expr[i + 1]); return -1; } - for (i += 2; i + 1 < len && (isdigit(expr[i + 1]) || expr[i + 1] == ','); i++) + for (i += 2; i + 1 < len && (isdigit(expr[i + 1]) || expr[i + 1] == ','); i++) { ; + } } - if (&expr[i + 1] == rend) + if (&expr[i + 1] == rend) { break; - else + } else { blkmod = 0; + } } } @@ -850,8 +887,9 @@ int cli_ac_chklsig(const char *expr, const char *end, uint32_t *lsigcnt, unsigne } if (!op && !op1) { - if (expr[0] == '(') + if (expr[0] == '(') { return cli_ac_chklsig(++expr, --end, lsigcnt, cnt, ids, parse_only); + } ret = sscanf(expr, "%u", &id); if (!ret || ret == EOF) { @@ -859,10 +897,11 @@ int cli_ac_chklsig(const char *expr, const char *end, uint32_t *lsigcnt, unsigne return -1; } - if (parse_only) + if (parse_only) { val = id; - else + } else { val = lsigcnt[id]; + } if (mod) { pt = expr + modoff + 1; @@ -875,16 +914,19 @@ int cli_ac_chklsig(const char *expr, const char *end, uint32_t *lsigcnt, unsigne if (!parse_only) { switch (mod) { case '=': - if (val != modval1) + if (val != modval1) { return 0; + } break; case '<': - if (val >= modval1) + if (val >= modval1) { return 0; + } break; case '>': - if (val <= modval1) + if (val <= modval1) { return 0; + } break; default: return 0; @@ -981,16 +1023,19 @@ int cli_ac_chklsig(const char *expr, const char *end, uint32_t *lsigcnt, unsigne switch (blkmod) { case '=': - if (tcnt != modval1) + if (tcnt != modval1) { return 0; + } break; case '<': - if (tcnt >= modval1) + if (tcnt >= modval1) { return 0; + } break; case '>': - if (tcnt <= modval1) + if (tcnt <= modval1) { return 0; + } break; default: return 0; @@ -1003,8 +1048,9 @@ int cli_ac_chklsig(const char *expr, const char *end, uint32_t *lsigcnt, unsigne tids >>= 1; } - if (val < modval2) + if (val < modval2) { return 0; + } } *cnt += tcnt; @@ -1118,19 +1164,22 @@ inline static int ac_findmatch_special(const unsigned char *buffer, uint32_t off if (cmp == 0) { match = !special->negative; break; - } else if (cmp < 0) + } else if (cmp < 0) { break; + } } break; case AC_SPECIAL_ALT_STR_FIXED: /* fixed length multi-byte */ if (!rev) { - if (bp + special->len[0] > length) + if (bp + special->len[0] > length) { break; + } subbp = bp; } else { - if (bp < (uint32_t)(special->len[0] - 1)) + if (bp < (uint32_t)(special->len[0] - 1)) { break; + } subbp = bp - (uint32_t)(special->len[0] - 1); } @@ -1140,8 +1189,9 @@ inline static int ac_findmatch_special(const unsigned char *buffer, uint32_t off if (cmp == 0) { match = (!special->negative) * special->len[0]; break; - } else if (cmp < 0) + } else if (cmp < 0) { break; + } } break; @@ -1166,8 +1216,9 @@ inline static int ac_findmatch_special(const unsigned char *buffer, uint32_t off match = 1; for (j = 0; j < alt->len; j++) { AC_MATCH_CHAR2(alt->str[j], buffer[subbp + j]); - if (!match) + if (!match) { break; + } } if (match) { /* if match is unique (has no derivatives), we can pass it directly back */ @@ -1176,12 +1227,14 @@ inline static int ac_findmatch_special(const unsigned char *buffer, uint32_t off break; } /* branch for backtracking */ - if (!rev) + if (!rev) { match = ac_forward_match_branch(buffer, subbp + alt->len, offset, fileoffset, length, pattern, pp + 1, specialcnt + 1, start, end); - else + } else { match = ac_backward_match_branch(buffer, subbp - 1, offset, fileoffset, length, pattern, pp - 1, specialcnt - 1, start, end); - if (match) + } + if (match) { return -1; /* alerts caller that match has been resolved in child callee */ + } } alt = alt->next; @@ -1189,20 +1242,23 @@ inline static int ac_findmatch_special(const unsigned char *buffer, uint32_t off break; case AC_SPECIAL_LINE_MARKER: - if (b == '\n') + if (b == '\n') { match = !special->negative; - else if (b == '\r' && (bp + 1 < length && buffer[bp + 1] == '\n')) + } else if (b == '\r' && (bp + 1 < length && buffer[bp + 1] == '\n')) { match = (!special->negative) * 2; + } break; case AC_SPECIAL_BOUNDARY: - if (boundary[b]) + if (boundary[b]) { match = !special->negative; + } break; case AC_SPECIAL_WORD_MARKER: - if (!isalnum(b)) + if (!isalnum(b)) { match = !special->negative; + } break; default: @@ -1228,12 +1284,14 @@ static int ac_backward_match_branch(const unsigned char *buffer, uint32_t bp, ui for (i = pp; 1; i--) { AC_MATCH_CHAR(pattern->prefix[i], buffer[bp], 1); - if (!match) + if (!match) { return 0; + } /* needs to perform check before decrement due to unsignedness */ - if (i == 0 || bp == 0) + if (i == 0 || bp == 0) { break; + } bp--; } @@ -1249,57 +1307,69 @@ static int ac_backward_match_branch(const unsigned char *buffer, uint32_t bp, ui /* left-side special checks, bp = start */ if (pattern->boundary & AC_BOUNDARY_LEFT) { match = !!(pattern->boundary & AC_BOUNDARY_LEFT_NEGATIVE); - if (!filestart || (bp && (boundary[buffer[bp - 1]] == 1 || boundary[buffer[bp - 1]] == 3))) + if (!filestart || (bp && (boundary[buffer[bp - 1]] == 1 || boundary[buffer[bp - 1]] == 3))) { match = !match; + } - if (!match) + if (!match) { return 0; + } } if (pattern->boundary & AC_LINE_MARKER_LEFT) { match = !!(pattern->boundary & AC_LINE_MARKER_LEFT_NEGATIVE); - if (!filestart || (bp && (buffer[bp - 1] == '\n'))) + if (!filestart || (bp && (buffer[bp - 1] == '\n'))) { match = !match; + } - if (!match) + if (!match) { return 0; + } } if (pattern->boundary & AC_WORD_MARKER_LEFT) { match = !!(pattern->boundary & AC_WORD_MARKER_LEFT_NEGATIVE); - if (!filestart) + if (!filestart) { match = !match; - else if (pattern->sigopts & ACPATT_OPTION_WIDE) { - if (filestart - 1 == 0) + } else if (pattern->sigopts & ACPATT_OPTION_WIDE) { + if (filestart - 1 == 0) { match = !match; - if (bp - 1 && bp && !(isalnum(buffer[bp - 2]) && buffer[bp - 1] == '\0')) + } + if (bp - 1 && bp && !(isalnum(buffer[bp - 2]) && buffer[bp - 1] == '\0')) { match = !match; - } else if (bp && !isalnum(buffer[bp - 1])) + } + } else if (bp && !isalnum(buffer[bp - 1])) { match = !match; + } - if (!match) + if (!match) { return 0; + } } /* bp is shifted for left anchor check, thus invalidated as pattern start */ if (!(pattern->ch[0] & CLI_MATCH_IGNORE)) { - if (pattern->ch_mindist[0] + (uint32_t)1 > bp) + if (pattern->ch_mindist[0] + (uint32_t)1 > bp) { return 0; + } bp -= pattern->ch_mindist[0] + 1; for (i = pattern->ch_mindist[0]; i <= pattern->ch_maxdist[0]; i++) { match = 1; AC_MATCH_CHAR(pattern->ch[0], buffer[bp], 1); - if (match) + if (match) { break; + } - if (!bp) + if (!bp) { return 0; - else + } else { bp--; + } } - if (!match) + if (!match) { return 0; + } } return 1; @@ -1318,8 +1388,9 @@ static int ac_forward_match_branch(const unsigned char *buffer, uint32_t bp, uin /* forward (pattern) validation; determines end */ for (i = pp; i < pattern->length[0] && bp < length; i++) { AC_MATCH_CHAR(pattern->pattern[i], buffer[bp], 0); - if (!match) + if (!match) { return 0; + } bp++; } @@ -1328,36 +1399,43 @@ static int ac_forward_match_branch(const unsigned char *buffer, uint32_t bp, uin /* right-side special checks, bp = end */ if (pattern->boundary & AC_BOUNDARY_RIGHT) { match = !!(pattern->boundary & AC_BOUNDARY_RIGHT_NEGATIVE); - if ((length <= SCANBUFF) && (bp == length || boundary[buffer[bp]] >= 2)) + if ((length <= SCANBUFF) && (bp == length || boundary[buffer[bp]] >= 2)) { match = !match; + } - if (!match) + if (!match) { return 0; + } } if (pattern->boundary & AC_LINE_MARKER_RIGHT) { match = !!(pattern->boundary & AC_LINE_MARKER_RIGHT_NEGATIVE); - if ((length <= SCANBUFF) && (bp == length || buffer[bp] == '\n' || (buffer[bp] == '\r' && bp + 1 < length && buffer[bp + 1] == '\n'))) + if ((length <= SCANBUFF) && (bp == length || buffer[bp] == '\n' || (buffer[bp] == '\r' && bp + 1 < length && buffer[bp + 1] == '\n'))) { match = !match; + } - if (!match) + if (!match) { return 0; + } } if (pattern->boundary & AC_WORD_MARKER_RIGHT) { match = !!(pattern->boundary & AC_WORD_MARKER_RIGHT_NEGATIVE); if (length <= SCANBUFF) { - if (bp == length) + if (bp == length) { match = !match; - else if ((pattern->sigopts & ACPATT_OPTION_WIDE) && (bp + 1 < length)) { - if (!(isalnum(buffer[bp]) && buffer[bp + 1] == '\0')) + } else if ((pattern->sigopts & ACPATT_OPTION_WIDE) && (bp + 1 < length)) { + if (!(isalnum(buffer[bp]) && buffer[bp + 1] == '\0')) { match = !match; - } else if (!isalnum(buffer[bp])) + } + } else if (!isalnum(buffer[bp])) { match = !match; + } } - if (!match) + if (!match) { return 0; + } } /* bp is shifted for right anchor check, thus invalidated as pattern right-side */ @@ -1365,19 +1443,22 @@ static int ac_forward_match_branch(const unsigned char *buffer, uint32_t bp, uin bp += pattern->ch_mindist[1]; for (i = pattern->ch_mindist[1]; i <= pattern->ch_maxdist[1]; i++) { - if (bp >= length) + if (bp >= length) { return 0; + } match = 1; AC_MATCH_CHAR(pattern->ch[1], buffer[bp], 0); - if (match) + if (match) { break; + } bp++; } - if (!match) + if (!match) { return 0; + } } return ac_backward_match_branch(buffer, offset - 1, offset, fileoffset, length, pattern, pattern->prefix_length[0] - 1, pattern->special_pattern - 1, start, end); @@ -1389,12 +1470,14 @@ inline static int ac_findmatch(const unsigned char *buffer, uint32_t offset, uin uint16_t specialcnt = pattern->special_pattern; /* minimal check as the maximum variable length may exceed the buffer */ - if ((offset + pattern->length[1] > length) || (pattern->prefix_length[1] > offset)) + if ((offset + pattern->length[1] > length) || (pattern->prefix_length[1] > offset)) { return 0; + } match = ac_forward_match_branch(buffer, offset + pattern->depth, offset, fileoffset, length, pattern, pattern->depth, specialcnt, start, end); - if (match) + if (match) { return 1; + } return 0; } @@ -1417,8 +1500,9 @@ cl_error_t cli_ac_initdata(struct cli_ac_data *data, uint32_t partsigs, uint32_t cli_errmsg("cli_ac_init: Can't allocate memory for data->offset\n"); return CL_EMEM; } - for (i = 0; i < reloffsigs * 2; i += 2) + for (i = 0; i < reloffsigs * 2; i += 2) { data->offset[i] = CLI_OFF_NONE; + } } data->partsigs = partsigs; @@ -1427,8 +1511,9 @@ cl_error_t cli_ac_initdata(struct cli_ac_data *data, uint32_t partsigs, uint32_t if (!data->offmatrix) { cli_errmsg("cli_ac_init: Can't allocate memory for data->offmatrix\n"); - if (reloffsigs) + if (reloffsigs) { free(data->offset); + } return CL_EMEM; } @@ -1438,11 +1523,13 @@ cl_error_t cli_ac_initdata(struct cli_ac_data *data, uint32_t partsigs, uint32_t if (lsigs) { data->lsigcnt = (uint32_t **)malloc(lsigs * sizeof(uint32_t *)); if (!data->lsigcnt) { - if (partsigs) + if (partsigs) { free(data->offmatrix); + } - if (reloffsigs) + if (reloffsigs) { free(data->offset); + } cli_errmsg("cli_ac_init: Can't allocate memory for data->lsigcnt\n"); return CL_EMEM; @@ -1450,26 +1537,31 @@ cl_error_t cli_ac_initdata(struct cli_ac_data *data, uint32_t partsigs, uint32_t data->lsigcnt[0] = (uint32_t *)calloc(lsigs * 64, sizeof(uint32_t)); if (!data->lsigcnt[0]) { free(data->lsigcnt); - if (partsigs) + if (partsigs) { free(data->offmatrix); + } - if (reloffsigs) + if (reloffsigs) { free(data->offset); + } cli_errmsg("cli_ac_init: Can't allocate memory for data->lsigcnt[0]\n"); return CL_EMEM; } - for (i = 1; i < lsigs; i++) + for (i = 1; i < lsigs; i++) { data->lsigcnt[i] = data->lsigcnt[0] + 64 * i; + } data->yr_matches = (uint8_t *)calloc(lsigs, sizeof(uint8_t)); if (data->yr_matches == NULL) { free(data->lsigcnt[0]); free(data->lsigcnt); - if (partsigs) + if (partsigs) { free(data->offmatrix); + } - if (reloffsigs) + if (reloffsigs) { free(data->offset); + } return CL_EMEM; } @@ -1479,11 +1571,13 @@ cl_error_t cli_ac_initdata(struct cli_ac_data *data, uint32_t partsigs, uint32_t free(data->yr_matches); free(data->lsigcnt[0]); free(data->lsigcnt); - if (partsigs) + if (partsigs) { free(data->offmatrix); + } - if (reloffsigs) + if (reloffsigs) { free(data->offset); + } cli_errmsg("cli_ac_init: Can't allocate memory for data->lsig_matches\n"); return CL_EMEM; @@ -1497,11 +1591,13 @@ cl_error_t cli_ac_initdata(struct cli_ac_data *data, uint32_t partsigs, uint32_t free(data->yr_matches); free(data->lsigcnt[0]); free(data->lsigcnt); - if (partsigs) + if (partsigs) { free(data->offmatrix); + } - if (reloffsigs) + if (reloffsigs) { free(data->offset); + } cli_errmsg("cli_ac_init: Can't allocate memory for data->lsigsuboff_(last|first)\n"); return CL_EMEM; @@ -1517,11 +1613,13 @@ cl_error_t cli_ac_initdata(struct cli_ac_data *data, uint32_t partsigs, uint32_t free(data->yr_matches); free(data->lsigcnt[0]); free(data->lsigcnt); - if (partsigs) + if (partsigs) { free(data->offmatrix); + } - if (reloffsigs) + if (reloffsigs) { free(data->offset); + } cli_errmsg("cli_ac_init: Can't allocate memory for data->lsigsuboff_(last|first)[0]\n"); return CL_EMEM; @@ -1539,8 +1637,9 @@ cl_error_t cli_ac_initdata(struct cli_ac_data *data, uint32_t partsigs, uint32_t } } } - for (i = 0; i < 32; i++) + for (i = 0; i < 32; i++) { data->macro_lastmatch[i] = CLI_OFF_NONE; + } data->min_partno = 1; @@ -1553,8 +1652,9 @@ cl_error_t cli_ac_caloff(const struct cli_matcher *root, struct cli_ac_data *dat unsigned int i; struct cli_ac_patt *patt; - if (info) + if (info) { data->vinfo = &info->exeinfo.vinfo; + } for (i = 0; i < root->ac_reloff_num; i++) { patt = root->ac_reloff[i]; @@ -1575,8 +1675,9 @@ void cli_ac_freedata(struct cli_ac_data *data) { uint32_t i; - if (!data) + if (!data) { return; + } if (data->partsigs) { for (i = 0; i < data->partsigs; i++) { @@ -1631,8 +1732,9 @@ inline static int ac_addtype(struct cli_matched_type **list, cli_file_t type, of struct cli_matched_type *tnode, *tnode_last; if (type == CL_TYPE_ZIPSFX) { - if (*list && ctx && ctx->engine->maxfiles && (*list)->cnt > ctx->engine->maxfiles) + if (*list && ctx && ctx->engine->maxfiles && (*list)->cnt > ctx->engine->maxfiles) { return CL_SUCCESS; + } } else if (*list && (*list)->cnt >= MAX_EMBEDDED_OBJ) { return CL_SUCCESS; } @@ -1646,13 +1748,15 @@ inline static int ac_addtype(struct cli_matched_type **list, cli_file_t type, of tnode->offset = offset; tnode_last = *list; - while (tnode_last && tnode_last->next) + while (tnode_last && tnode_last->next) { tnode_last = tnode_last->next; + } - if (tnode_last) + if (tnode_last) { tnode_last->next = tnode; - else + } else { *list = tnode; + } (*list)->cnt++; return CL_SUCCESS; @@ -1796,8 +1900,9 @@ cl_error_t cli_ac_chkmacro(struct cli_matcher *root, struct cli_ac_data *data, u * macro matched at a correct distance */ for (i = 0; i < tdb->subsigs; i++) { rc = lsig_sub_matched(root, data, lsig_id, i, CLI_OFF_NONE, 0); - if (rc != CL_SUCCESS) + if (rc != CL_SUCCESS) { return rc; + } } return CL_SUCCESS; } @@ -1828,8 +1933,9 @@ cl_error_t cli_ac_scanbuff( cl_error_t rc; cl_error_t ret; - if (!root->ac_root) + if (!root->ac_root) { return CL_CLEAN; + } if (!mdata && (root->ac_partsigs || root->ac_lsigs || root->ac_reloff_num)) { cli_errmsg("cli_ac_scanbuff: mdata == NULL\n"); @@ -1876,8 +1982,9 @@ cl_error_t cli_ac_scanbuff( if (ac_findmatch(buffer, bp, offset + bp, length, patt, &matchstart, &matchend)) { while (ptN) { pt = ptN->me; - if (pt->partno > mdata->min_partno) + if (pt->partno > mdata->min_partno) { break; + } if ((pt->type && !(mode & AC_SCAN_FT)) || (!pt->type && !(mode & AC_SCAN_VIR))) { ptN = ptN->next_same; @@ -1921,8 +2028,9 @@ cl_error_t cli_ac_scanbuff( continue; } - if ((uint32_t)(pt->partno + 1) > mdata->min_partno) + if ((uint32_t)(pt->partno + 1) > mdata->min_partno) { mdata->min_partno = pt->partno + 1; + } /* sparsely populated matrix, so allocate and initialize if NULL */ if (!mdata->offmatrix[pt->sigid - 1]) { @@ -1952,19 +2060,25 @@ cl_error_t cli_ac_scanbuff( if (pt->partno != 1) { for (j = 1; (j <= CLI_DEFAULT_AC_TRACKLEN + 1) && (offmatrix[pt->partno - 2][j] != (uint32_t)-1); j++) { found = j; - if (realoff < offmatrix[pt->partno - 2][j]) + if (realoff < offmatrix[pt->partno - 2][j]) { found = 0; + } - if (found && pt->maxdist) - if (realoff - offmatrix[pt->partno - 2][j] > pt->maxdist) + if (found && pt->maxdist) { + if (realoff - offmatrix[pt->partno - 2][j] > pt->maxdist) { found = 0; + } + } - if (found && pt->mindist) - if (realoff - offmatrix[pt->partno - 2][j] < pt->mindist) + if (found && pt->mindist) { + if (realoff - offmatrix[pt->partno - 2][j] < pt->mindist) { found = 0; + } + } - if (found) + if (found) { break; + } } } @@ -1981,18 +2095,21 @@ cl_error_t cli_ac_scanbuff( } if (pt->partno == 1 || (found && (pt->partno != pt->parts))) { - if (offmatrix[pt->partno - 1][0] == CLI_DEFAULT_AC_TRACKLEN + 1) + if (offmatrix[pt->partno - 1][0] == CLI_DEFAULT_AC_TRACKLEN + 1) { offmatrix[pt->partno - 1][0] = 1; /* wrap, ends up at 2 */ + } offmatrix[pt->partno - 1][0]++; offmatrix[pt->partno - 1][offmatrix[pt->partno - 1][0]] = offset + matchend; - if (pt->partno == 1) /* save realoff for the first part */ + if (pt->partno == 1) { /* save realoff for the first part */ offmatrix[pt->parts - 1][offmatrix[pt->partno - 1][0]] = realoff; + } } else if (found && pt->partno == pt->parts) { if (pt->type) { - if (pt->type == CL_TYPE_IGNORED && (!pt->rtype || ftype == pt->rtype)) + if (pt->type == CL_TYPE_IGNORED && (!pt->rtype || ftype == pt->rtype)) { return CL_TYPE_IGNORED; + } if ((pt->type > type || pt->type >= CL_TYPE_SFX || pt->type == CL_TYPE_MSEXE) && (pt->rtype == CL_TYPE_ANY || ftype == pt->rtype)) { @@ -2004,21 +2121,25 @@ cl_error_t cli_ac_scanbuff( /* FIXME: the first offset in the array is most likely the correct one but * it may happen it is not */ - for (j = 1; j <= CLI_DEFAULT_AC_TRACKLEN + 1 && offmatrix[0][j] != (uint32_t)-1; j++) - if (ac_addtype(ftoffset, type, offmatrix[pt->parts - 1][j], ctx)) + for (j = 1; j <= CLI_DEFAULT_AC_TRACKLEN + 1 && offmatrix[0][j] != (uint32_t)-1; j++) { + if (ac_addtype(ftoffset, type, offmatrix[pt->parts - 1][j], ctx)) { return CL_EMEM; + } + } } memset(offmatrix[0], (uint32_t)-1, pt->parts * (CLI_DEFAULT_AC_TRACKLEN + 2) * sizeof(uint32_t)); - for (j = 0; j < pt->parts; j++) + for (j = 0; j < pt->parts; j++) { offmatrix[j][0] = 0; + } } } else { /* !pt->type */ if (pt->lsigid[0]) { rc = lsig_sub_matched(root, mdata, pt->lsigid[1], pt->lsigid[2], offmatrix[pt->parts - 1][1], 1); - if (rc != CL_SUCCESS) + if (rc != CL_SUCCESS) { return rc; + } ptN = ptN->next_same; continue; } @@ -2044,12 +2165,15 @@ cl_error_t cli_ac_scanbuff( viruses_found = 1; } } - if (virname) + if (virname) { *virname = pt->virname; - if (customdata) + } + if (customdata) { *customdata = pt->customdata; - if (!ctx || !SCAN_ALLMATCHES) + } + if (!ctx || !SCAN_ALLMATCHES) { return CL_VIRUS; + } ptN = ptN->next_same; continue; } @@ -2058,8 +2182,9 @@ cl_error_t cli_ac_scanbuff( } else { /* old type signature */ if (pt->type) { - if (pt->type == CL_TYPE_IGNORED && (pt->rtype == CL_TYPE_ANY || ftype == pt->rtype)) + if (pt->type == CL_TYPE_IGNORED && (pt->rtype == CL_TYPE_ANY || ftype == pt->rtype)) { return CL_TYPE_IGNORED; + } if ((pt->type > type || pt->type >= CL_TYPE_SFX || pt->type == CL_TYPE_MSEXE) && (pt->rtype == CL_TYPE_ANY || ftype == pt->rtype)) { @@ -2069,15 +2194,17 @@ cl_error_t cli_ac_scanbuff( if ((ftoffset != NULL) && ((*ftoffset == NULL) || (*ftoffset)->cnt < MAX_EMBEDDED_OBJ || type == CL_TYPE_ZIPSFX) && (type == CL_TYPE_MBR || type >= CL_TYPE_SFX || ((ftype == CL_TYPE_MSEXE || ftype == CL_TYPE_ZIP || ftype == CL_TYPE_MSOLE2) && type == CL_TYPE_MSEXE))) { - if (ac_addtype(ftoffset, type, realoff, ctx)) + if (ac_addtype(ftoffset, type, realoff, ctx)) { return CL_EMEM; + } } } } else { if (pt->lsigid[0]) { rc = lsig_sub_matched(root, mdata, pt->lsigid[1], pt->lsigid[2], realoff, 0); - if (rc != CL_SUCCESS) + if (rc != CL_SUCCESS) { return rc; + } ptN = ptN->next_same; continue; } @@ -2104,14 +2231,17 @@ cl_error_t cli_ac_scanbuff( } } - if (virname) + if (virname) { *virname = pt->virname; + } - if (customdata) + if (customdata) { *customdata = pt->customdata; + } - if (!ctx || !SCAN_ALLMATCHES) + if (!ctx || !SCAN_ALLMATCHES) { return CL_VIRUS; + } ptN = ptN->next_same; continue; @@ -2126,8 +2256,9 @@ cl_error_t cli_ac_scanbuff( } } - if (viruses_found) + if (viruses_found) { return CL_VIRUS; + } return (mode & AC_SCAN_FT) ? type : CL_CLEAN; } @@ -2187,8 +2318,9 @@ inline static int ac_analyze_expr(char *hexstr, int *fixed_len, int *sub_len) slen = len; } else if (len != slen) { flen = 0; - if (len > slen) + if (len > slen) { slen = len; + } } break; } @@ -2199,14 +2331,16 @@ inline static int ac_analyze_expr(char *hexstr, int *fixed_len, int *sub_len) slen = len; } else if (len != slen) { flen = 0; - if (len > slen) + if (len > slen) { slen = len; + } } len = 0; numexpr++; } else { - if (hexstr[i] == '?') + if (hexstr[i] == '?') { flen = 0; + } len++; } } @@ -2214,14 +2348,17 @@ inline static int ac_analyze_expr(char *hexstr, int *fixed_len, int *sub_len) slen = len; } else if (len != slen) { flen = 0; - if (len > slen) + if (len > slen) { slen = len; + } } - if (sub_len) + if (sub_len) { *sub_len = slen; - if (fixed_len) + } + if (fixed_len) { *fixed_len = flen; + } return numexpr; } @@ -2318,12 +2455,14 @@ inline static int ac_uicmp(uint16_t *a, size_t alen, uint16_t *b, size_t blen, i } /* both sides contain a wildcard that contains the other, therefore unique by wildcards */ - if (side_wild == 3) + if (side_wild == 3) { return 1; + } } - if (wild) + if (wild) { *wild = side_wild; + } return 0; } @@ -2360,11 +2499,12 @@ inline static int ac_addspecial_add_alt_node(const char *subexpr, uint8_t sigopt /* setting nocase match */ if (sigopts & ACPATT_OPTION_NOCASE) { - for (i = 0; i < newnode->len; ++i) + for (i = 0; i < newnode->len; ++i) { if ((newnode->str[i] & CLI_MATCH_METADATA) == CLI_MATCH_CHAR) { newnode->str[i] = CLI_NOCASE(newnode->str[i] & 0xff); newnode->str[i] += CLI_MATCH_NOCASE; } + } } /* search for uniqueness, TODO: directed acyclic word graph */ @@ -2389,10 +2529,12 @@ inline static int ac_addspecial_add_alt_node(const char *subexpr, uint8_t sigopt *prev = newnode; newnode->next = ins; - if ((special->num == 0) || (newnode->len < special->len[0])) + if ((special->num == 0) || (newnode->len < special->len[0])) { special->len[0] = newnode->len; - if ((special->num == 0) || (newnode->len > special->len[1])) + } + if ((special->num == 0) || (newnode->len > special->len[1])) { special->len[1] = newnode->len; + } special->num++; return CL_SUCCESS; } @@ -2412,8 +2554,9 @@ static int ac_special_altexpand(char *hexpr, char *subexpr, uint16_t maxlen, int /* while there are expressions to resolve */ while (scnt < numexpr) { scnt++; - while ((*ept != '(') && (*ept != '|') && (*ept != ')') && (*ept != '\0')) + while ((*ept != '(') && (*ept != '|') && (*ept != ')') && (*ept != '\0')) { ept++; + } /* check for invalid negation */ term = *ept; @@ -2436,8 +2579,9 @@ static int ac_special_altexpand(char *hexpr, char *subexpr, uint16_t maxlen, int if (term == '|') { if (lvl == 0) { - if ((ret = ac_addspecial_add_alt_node(subexpr, sigopts, special, root)) != CL_SUCCESS) + if ((ret = ac_addspecial_add_alt_node(subexpr, sigopts, special, root)) != CL_SUCCESS) { return ret; + } } else { find_paren_end(ept, &end); if (!end) { @@ -2446,8 +2590,9 @@ static int ac_special_altexpand(char *hexpr, char *subexpr, uint16_t maxlen, int } end++; - if ((ret = ac_special_altexpand(end, subexpr, maxlen, lvl - 1, lvl, sigopts, special, root)) != CL_SUCCESS) + if ((ret = ac_special_altexpand(end, subexpr, maxlen, lvl - 1, lvl, sigopts, special, root)) != CL_SUCCESS) { return ret; + } } *fp = 0; @@ -2457,8 +2602,9 @@ static int ac_special_altexpand(char *hexpr, char *subexpr, uint16_t maxlen, int return CL_EPARSE; } - if ((ret = ac_special_altexpand(ept, subexpr, maxlen, lvl - 1, lvl, sigopts, special, root)) != CL_SUCCESS) + if ((ret = ac_special_altexpand(ept, subexpr, maxlen, lvl - 1, lvl, sigopts, special, root)) != CL_SUCCESS) { return ret; + } break; } else if (term == '(') { int inner, found; @@ -2469,8 +2615,9 @@ static int ac_special_altexpand(char *hexpr, char *subexpr, uint16_t maxlen, int } end++; - if ((ret = ac_special_altexpand(ept, subexpr, maxlen, lvl + 1, lvl + 1, sigopts, special, root)) != CL_SUCCESS) + if ((ret = ac_special_altexpand(ept, subexpr, maxlen, lvl + 1, lvl + 1, sigopts, special, root)) != CL_SUCCESS) { return ret; + } /* move ept to end of current alternate expression (recursive call already populates them) */ ept = end; @@ -2479,8 +2626,9 @@ static int ac_special_altexpand(char *hexpr, char *subexpr, uint16_t maxlen, int while (!found && *ept != '\0') { switch (*ept) { case '|': - if (!inner) + if (!inner) { found = 1; + } break; case '(': inner++; @@ -2491,19 +2639,22 @@ static int ac_special_altexpand(char *hexpr, char *subexpr, uint16_t maxlen, int } ept++; } - if (*ept == '|') + if (*ept == '|') { ept++; + } sexpr = ept; *fp = 0; } else if (term == '\0') { - if ((ret = ac_addspecial_add_alt_node(subexpr, sigopts, special, root)) != CL_SUCCESS) + if ((ret = ac_addspecial_add_alt_node(subexpr, sigopts, special, root)) != CL_SUCCESS) { return ret; + } break; } - if (lvl != maxlvl) + if (lvl != maxlvl) { return CL_SUCCESS; + } } if (scnt != numexpr) { cli_errmsg("ac_addspecial: Mismatch in parsed and expected signature\n"); @@ -2573,11 +2724,13 @@ inline static int ac_special_altstr(const char *hexpr, uint8_t sigopts, struct c special->num++; } /* sorting byte alternates */ - if (special->num > 1 && special->type == AC_SPECIAL_ALT_CHAR) + if (special->num > 1 && special->type == AC_SPECIAL_ALT_CHAR) { cli_qsort((special->alt).byte, special->num, sizeof(unsigned char), qcompare_byte); + } /* sorting str alternates */ - if (special->num > 1 && special->type == AC_SPECIAL_ALT_STR_FIXED) + if (special->num > 1 && special->type == AC_SPECIAL_ALT_STR_FIXED) { cli_qsort_r((special->alt).f_str, special->num, sizeof(unsigned char *), qcompare_fstr, &(special->len)); + } } else { /* generic alternates */ char *subexpr; if (special->negative) { @@ -2627,8 +2780,9 @@ cl_error_t cli_ac_addsig(struct cli_matcher *root, const char *virname, const ch return CL_EMALFDB; } - if ((new = (struct cli_ac_patt *)MPOOL_CALLOC(root->mempool, 1, sizeof(struct cli_ac_patt))) == NULL) + if ((new = (struct cli_ac_patt *)MPOOL_CALLOC(root->mempool, 1, sizeof(struct cli_ac_patt))) == NULL) { return CL_EMEM; + } new->rtype = rtype; new->type = type; @@ -2655,8 +2809,9 @@ cl_error_t cli_ac_addsig(struct cli_matcher *root, const char *virname, const ch for (i = 0; i < 2; i++) { unsigned int n, n1, n2; - if (!(pt = strchr(hex, '['))) + if (!(pt = strchr(hex, '['))) { break; + } *pt++ = 0; @@ -2695,10 +2850,11 @@ cl_error_t cli_ac_addsig(struct cli_matcher *root, const char *virname, const ch break; } - if ((sigopts & ACPATT_OPTION_NOCASE) && ((*dec & CLI_MATCH_METADATA) == CLI_MATCH_CHAR)) + if ((sigopts & ACPATT_OPTION_NOCASE) && ((*dec & CLI_MATCH_METADATA) == CLI_MATCH_CHAR)) { new->ch[i] = CLI_NOCASE(*dec) | CLI_MATCH_NOCASE; - else + } else { new->ch[i] = *dec; + } free(dec); new->ch_mindist[i] = n1; new->ch_maxdist[i] = n2; @@ -2711,10 +2867,11 @@ cl_error_t cli_ac_addsig(struct cli_matcher *root, const char *virname, const ch break; } - if ((sigopts & ACPATT_OPTION_NOCASE) && ((*dec & CLI_MATCH_METADATA) == CLI_MATCH_CHAR)) + if ((sigopts & ACPATT_OPTION_NOCASE) && ((*dec & CLI_MATCH_METADATA) == CLI_MATCH_CHAR)) { new->ch[i] = CLI_NOCASE(*dec) | CLI_MATCH_NOCASE; - else + } else { new->ch[i] = *dec; + } free(dec); new->ch_mindist[i] = n1; new->ch_maxdist[i] = n2; @@ -2812,42 +2969,48 @@ cl_error_t cli_ac_addsig(struct cli_matcher *root, const char *virname, const ch if (!strcmp(pt, "B")) { if (!*start) { new->boundary |= AC_BOUNDARY_RIGHT; - if (newspecial->negative) + if (newspecial->negative) { new->boundary |= AC_BOUNDARY_RIGHT_NEGATIVE; + } MPOOL_FREE(root->mempool, newspecial); continue; } else if (pt - 1 == hexcpy) { new->boundary |= AC_BOUNDARY_LEFT; - if (newspecial->negative) + if (newspecial->negative) { new->boundary |= AC_BOUNDARY_LEFT_NEGATIVE; + } MPOOL_FREE(root->mempool, newspecial); continue; } } else if (!strcmp(pt, "L")) { if (!*start) { new->boundary |= AC_LINE_MARKER_RIGHT; - if (newspecial->negative) + if (newspecial->negative) { new->boundary |= AC_LINE_MARKER_RIGHT_NEGATIVE; + } MPOOL_FREE(root->mempool, newspecial); continue; } else if (pt - 1 == hexcpy) { new->boundary |= AC_LINE_MARKER_LEFT; - if (newspecial->negative) + if (newspecial->negative) { new->boundary |= AC_LINE_MARKER_LEFT_NEGATIVE; + } MPOOL_FREE(root->mempool, newspecial); continue; } } else if (!strcmp(pt, "W")) { if (!*start) { new->boundary |= AC_WORD_MARKER_RIGHT; - if (newspecial->negative) + if (newspecial->negative) { new->boundary |= AC_WORD_MARKER_RIGHT_NEGATIVE; + } MPOOL_FREE(root->mempool, newspecial); continue; } else if (pt - 1 == hexcpy) { new->boundary |= AC_WORD_MARKER_LEFT; - if (newspecial->negative) + if (newspecial->negative) { new->boundary |= AC_WORD_MARKER_LEFT_NEGATIVE; + } MPOOL_FREE(root->mempool, newspecial); continue; } @@ -2879,8 +3042,9 @@ cl_error_t cli_ac_addsig(struct cli_matcher *root, const char *virname, const ch } } - if (start) + if (start) { cli_strlcat(hexnew, start, hexnewsz); + } hex = hexnew; free(hexcpy); @@ -2900,8 +3064,9 @@ cl_error_t cli_ac_addsig(struct cli_matcher *root, const char *virname, const ch */ new->pattern = CLI_MPOOL_HEX2UI(root->mempool, hex ? hex : hexsig); if (new->pattern == NULL) { - if (new->special) + if (new->special) { mpool_ac_free_special(root->mempool, new); + } MPOOL_FREE(root->mempool, new); free(hex); @@ -2911,8 +3076,9 @@ cl_error_t cli_ac_addsig(struct cli_matcher *root, const char *virname, const ch new->length[0] = (uint16_t)strlen(hex ? hex : hexsig) / 2; if (new->length[0] < root->ac_mindepth) { cli_errmsg("cli_ac_addsig: Subpattern in signature is shorter than the minimum depth of the AC trie. (%u < %u)\n", new->length[0], root->ac_mindepth); - if (new->special) + if (new->special) { mpool_ac_free_special(root->mempool, new); + } MPOOL_FREE(root->mempool, new->pattern); MPOOL_FREE(root->mempool, new); @@ -2936,11 +3102,12 @@ cl_error_t cli_ac_addsig(struct cli_matcher *root, const char *virname, const ch new->sigopts = sigopts; /* setting nocase match */ if (sigopts & ACPATT_OPTION_NOCASE) { - for (i = 0; i < new->length[0]; i++) + for (i = 0; i < new->length[0]; i++) { if ((new->pattern[i] & CLI_MATCH_METADATA) == CLI_MATCH_CHAR) { new->pattern[i] = CLI_NOCASE(new->pattern[i] & 0xff); new->pattern[i] += CLI_MATCH_NOCASE; } + } } /* TODO - sigopts affect on filters? */ @@ -3051,8 +3218,9 @@ cl_error_t cli_ac_addsig(struct cli_matcher *root, const char *virname, const ch // The "prefix" length is the number of bytes before the starting position of the pattern that goes in the AC Trie. new->prefix_length[0] = ppos; for (i = 0, j = 0; i < new->prefix_length[0]; i++) { - if ((new->prefix[i] & CLI_MATCH_WILDCARD) == CLI_MATCH_SPECIAL) + if ((new->prefix[i] & CLI_MATCH_WILDCARD) == CLI_MATCH_SPECIAL) { new->special_pattern++; + } if ((new->prefix[i] & CLI_MATCH_METADATA) == CLI_MATCH_SPECIAL) { new->prefix_length[1] += new->special_table[j]->len[0]; diff --git a/libclamav/matcher-bm.c b/libclamav/matcher-bm.c index 7d02978044..af71af58db 100644 --- a/libclamav/matcher-bm.c +++ b/libclamav/matcher-bm.c @@ -57,10 +57,11 @@ cl_error_t cli_bm_addpatt(struct cli_matcher *root, struct cli_bm_patt *pattern, return ret; } if (pattern->offdata[0] != CLI_OFF_ANY) { - if (pattern->offdata[0] == CLI_OFF_ABSOLUTE) + if (pattern->offdata[0] == CLI_OFF_ABSOLUTE) { root->bm_absoff_num++; - else + } else { root->bm_reloff_num++; + } } /* bm_offmode doesn't use the prefilter for BM signatures anyway, so @@ -101,16 +102,18 @@ cl_error_t cli_bm_addpatt(struct cli_matcher *root, struct cli_bm_patt *pattern, prev = next = root->bm_suffix[idx]; while (next) { - if (pt[0] >= next->pattern0) + if (pt[0] >= next->pattern0) { break; + } prev = next; next = next->next; } if (next == root->bm_suffix[idx]) { pattern->next = root->bm_suffix[idx]; - if (root->bm_suffix[idx]) + if (root->bm_suffix[idx]) { pattern->cnt = root->bm_suffix[idx]->cnt; + } root->bm_suffix[idx] = pattern; } else { pattern->next = prev->next; @@ -126,8 +129,9 @@ cl_error_t cli_bm_addpatt(struct cli_matcher *root, struct cli_bm_patt *pattern, return CL_EMEM; } root->bm_pattab[root->bm_patterns] = pattern; - if (pattern->offdata[0] != CLI_OFF_ABSOLUTE) + if (pattern->offdata[0] != CLI_OFF_ABSOLUTE) { pattern->offset_min = root->bm_patterns; + } } root->bm_patterns++; @@ -141,16 +145,18 @@ cl_error_t cli_bm_init(struct cli_matcher *root) assert(root->mempool && "mempool must be initialized"); #endif - if (!(root->bm_shift = (uint8_t *)MPOOL_CALLOC(root->mempool, size, sizeof(uint8_t)))) + if (!(root->bm_shift = (uint8_t *)MPOOL_CALLOC(root->mempool, size, sizeof(uint8_t)))) { return CL_EMEM; + } if (!(root->bm_suffix = (struct cli_bm_patt **)MPOOL_CALLOC(root->mempool, size, sizeof(struct cli_bm_patt *)))) { MPOOL_FREE(root->mempool, root->bm_shift); return CL_EMEM; } - for (i = 0; i < size; i++) + for (i = 0; i < size; i++) { root->bm_shift[i] = BM_MIN_LENGTH - BM_BLOCK_SIZE + 1; + } return CL_SUCCESS; } @@ -183,8 +189,9 @@ cl_error_t cli_bm_initoff(const struct cli_matcher *root, struct cli_bm_off *dat patt = root->bm_pattab[i]; if (patt->offdata[0] == CLI_OFF_ABSOLUTE) { data->offtab[data->cnt] = patt->offset_min + patt->prefix_length; - if (data->offtab[data->cnt] >= info->fsize) + if (data->offtab[data->cnt] >= info->fsize) { continue; + } data->cnt++; } else if (CL_SUCCESS != (ret = cli_caloff(NULL, info, root->type, patt->offdata, &data->offset[patt->offset_min], NULL))) { cli_errmsg("cli_bm_initoff: Can't calculate relative offset in signature for %s\n", patt->virname); @@ -194,8 +201,9 @@ cl_error_t cli_bm_initoff(const struct cli_matcher *root, struct cli_bm_off *dat } else if ((data->offset[patt->offset_min] != CLI_OFF_NONE) && (data->offset[patt->offset_min] + patt->length <= info->fsize)) { if (!data->cnt || (data->offset[patt->offset_min] + patt->prefix_length != data->offtab[data->cnt - 1])) { data->offtab[data->cnt] = data->offset[patt->offset_min] + patt->prefix_length; - if (data->offtab[data->cnt] >= info->fsize) + if (data->offtab[data->cnt] >= info->fsize) { continue; + } data->cnt++; } } @@ -218,11 +226,13 @@ void cli_bm_free(struct cli_matcher *root) struct cli_bm_patt *patt, *prev; uint16_t i, size = HASH(255, 255, 255) + 1; - if (root->bm_shift) + if (root->bm_shift) { MPOOL_FREE(root->mempool, root->bm_shift); + } - if (root->bm_pattab) + if (root->bm_pattab) { MPOOL_FREE(root->mempool, root->bm_pattab); + } if (root->bm_suffix) { for (i = 0; i < size; i++) { @@ -230,12 +240,14 @@ void cli_bm_free(struct cli_matcher *root) while (patt) { prev = patt; patt = patt->next; - if (prev->prefix) + if (prev->prefix) { MPOOL_FREE(root->mempool, prev->prefix); - else + } else { MPOOL_FREE(root->mempool, prev->pattern); - if (prev->virname) + } + if (prev->virname) { MPOOL_FREE(root->mempool, prev->virname); + } MPOOL_FREE(root->mempool, prev); } } @@ -254,24 +266,31 @@ cl_error_t cli_bm_scanbuff(const unsigned char *buffer, uint32_t length, const c cl_error_t ret; int viruses_found = 0; - if (!root || !root->bm_shift) + if (!root || !root->bm_shift) { return CL_CLEAN; + } - if (length < BM_MIN_LENGTH) + if (length < BM_MIN_LENGTH) { return CL_CLEAN; + } i = BM_MIN_LENGTH - BM_BLOCK_SIZE; if (offdata) { - if (!offdata->cnt) + if (!offdata->cnt) { return CL_CLEAN; - if (offdata->pos == offdata->cnt) + } + if (offdata->pos == offdata->cnt) { offdata->pos--; - for (; offdata->pos && offdata->offtab[offdata->pos] > offset; offdata->pos--) + } + for (; offdata->pos && offdata->offtab[offdata->pos] > offset; offdata->pos--) { ; - if (offdata->offtab[offdata->pos] < offset) + } + if (offdata->offtab[offdata->pos] < offset) { offdata->pos++; - if (offdata->pos >= offdata->cnt) + } + if (offdata->pos >= offdata->cnt) { return CL_CLEAN; + } i += offdata->offtab[offdata->pos] - offset; } for (; i < length - BM_BLOCK_SIZE + 1;) { @@ -284,11 +303,13 @@ cl_error_t cli_bm_scanbuff(const unsigned char *buffer, uint32_t length, const c if (p && p->cnt == 1 && p->pattern0 != prefix) { if (offdata) { off = offset + i - BM_MIN_LENGTH + BM_BLOCK_SIZE; - for (; offdata->pos < offdata->cnt && off >= offdata->offtab[offdata->pos]; offdata->pos++) + for (; offdata->pos < offdata->cnt && off >= offdata->offtab[offdata->pos]; offdata->pos++) { ; + } if (offdata->pos == offdata->cnt || off >= offdata->offtab[offdata->pos]) { - if (viruses_found) + if (viruses_found) { return CL_VIRUS; + } return CL_CLEAN; } i += offdata->offtab[offdata->pos] - off; @@ -300,12 +321,14 @@ cl_error_t cli_bm_scanbuff(const unsigned char *buffer, uint32_t length, const c pchain = 0; while (p) { if (p->pattern0 != prefix) { - if (pchain) + if (pchain) { break; + } p = p->next; continue; - } else + } else { pchain = 1; + } off = i - BM_MIN_LENGTH + BM_BLOCK_SIZE; bp = buffer + off; @@ -392,11 +415,13 @@ cl_error_t cli_bm_scanbuff(const unsigned char *buffer, uint32_t length, const c } } - if (patt) + if (patt) { *patt = p; + } - if (ctx != NULL && !SCAN_ALLMATCHES) + if (ctx != NULL && !SCAN_ALLMATCHES) { return CL_VIRUS; + } } p = p->next; } @@ -405,8 +430,9 @@ cl_error_t cli_bm_scanbuff(const unsigned char *buffer, uint32_t length, const c if (offdata) { off = offset + i - BM_MIN_LENGTH + BM_BLOCK_SIZE; - for (; offdata->pos < offdata->cnt && off >= offdata->offtab[offdata->pos]; offdata->pos++) + for (; offdata->pos < offdata->cnt && off >= offdata->offtab[offdata->pos]; offdata->pos++) { ; + } if (offdata->pos == offdata->cnt || off >= offdata->offtab[offdata->pos]) { if (viruses_found > 0) { return CL_VIRUS; diff --git a/libclamav/matcher-hash.c b/libclamav/matcher-hash.c index 1d7f9c8ad4..5230c63d79 100644 --- a/libclamav/matcher-hash.c +++ b/libclamav/matcher-hash.c @@ -84,7 +84,9 @@ int hm_addhash_bin(struct cli_matcher *root, const void *binhash, cli_hash_type_ ht = &root->hm.sizehashes[type]; if (!root->hm.sizehashes[type].capacity) { i = CLI_HTU32_INIT(ht, 64, root->mempool); - if (i) return i; + if (i) { + return i; + } } item = cli_htu32_find(ht, size); @@ -104,8 +106,9 @@ int hm_addhash_bin(struct cli_matcher *root, const void *binhash, cli_hash_type_ MPOOL_FREE(root->mempool, szh); return i; } - } else + } else { szh = (struct cli_sz_hash *)item->data.as_ptr; + } } else { /* size 0 = wildcard */ szh = &root->hwild.hashes[type]; @@ -140,8 +143,9 @@ static inline int hm_cmp(const uint8_t *itm, const uint8_t *ref, unsigned int ke { #if WORDS_BIGENDIAN == 0 uint32_t i = *(uint32_t *)itm, r = *(uint32_t *)ref; - if (i != r) + if (i != r) { return (i < r) * 2 - 1; + } return memcmp(&itm[4], &ref[4], keylen - 4); #else return memcmp(itm, ref, keylen); @@ -155,8 +159,9 @@ static void hm_sort(struct cli_sz_hash *szh, size_t l, size_t r, unsigned int ke const char *tmpv; - if (l + 1 >= r) + if (l + 1 >= r) { return; + } l1 = l + 1, r1 = r; @@ -164,15 +169,18 @@ static void hm_sort(struct cli_sz_hash *szh, size_t l, size_t r, unsigned int ke while (l1 < r1) { if (hm_cmp(&szh->hash_array[keylen * l1], piv, keylen) > 0) { r1--; - if (l1 == r1) break; + if (l1 == r1) { + break; + } memcpy(tmph, &szh->hash_array[keylen * l1], keylen); tmpv = szh->virusnames[l1]; memcpy(&szh->hash_array[keylen * l1], &szh->hash_array[keylen * r1], keylen); szh->virusnames[l1] = szh->virusnames[r1]; memcpy(&szh->hash_array[keylen * r1], tmph, keylen); szh->virusnames[r1] = tmpv; - } else + } else { l1++; + } } l1--; @@ -196,23 +204,26 @@ void hm_flush(struct cli_matcher *root) unsigned int keylen; struct cli_sz_hash *szh; - if (!root) + if (!root) { return; + } for (type = CLI_HASH_MD5; type < CLI_HASH_AVAIL_TYPES; type++) { struct cli_htu32 *ht = &root->hm.sizehashes[type]; const struct cli_htu32_element *item = NULL; szh = NULL; - if (!root->hm.sizehashes[type].capacity) + if (!root->hm.sizehashes[type].capacity) { continue; + } while ((item = cli_htu32_next(ht, item))) { szh = (struct cli_sz_hash *)item->data.as_ptr; keylen = hashlen[type]; - if (szh->items > 1) + if (szh->items > 1) { hm_sort(szh, 0, szh->items, keylen); + } } } @@ -220,8 +231,9 @@ void hm_flush(struct cli_matcher *root) szh = &root->hwild.hashes[type]; keylen = hashlen[type]; - if (szh->items > 1) + if (szh->items > 1) { hm_sort(szh, 0, szh->items, keylen); + } } } @@ -245,8 +257,9 @@ static int hm_scan(const unsigned char *digest, const char **virname, const stru unsigned int keylen; size_t l, r; - if (!digest || !szh || !szh->items) + if (!digest || !szh || !szh->items) { return CL_CLEAN; + } keylen = hashlen[type]; @@ -257,14 +270,16 @@ static int hm_scan(const unsigned char *digest, const char **virname, const stru int res = hm_cmp(digest, &szh->hash_array[keylen * c], keylen); if (res < 0) { - if (!c) + if (!c) { break; + } r = c - 1; - } else if (res > 0) + } else if (res > 0) { l = c + 1; - else { - if (virname) + } else { + if (virname) { *virname = szh->virusnames[c]; + } return CL_VIRUS; } } @@ -277,12 +292,14 @@ int cli_hm_scan(const unsigned char *digest, uint32_t size, const char **virname const struct cli_htu32_element *item; struct cli_sz_hash *szh; - if (!digest || !size || size == 0xffffffff || !root || !root->hm.sizehashes[type].capacity) + if (!digest || !size || size == 0xffffffff || !root || !root->hm.sizehashes[type].capacity) { return CL_CLEAN; + } item = cli_htu32_find(&root->hm.sizehashes[type], size); - if (!item) + if (!item) { return CL_CLEAN; + } szh = (struct cli_sz_hash *)item->data.as_ptr; @@ -292,8 +309,9 @@ int cli_hm_scan(const unsigned char *digest, uint32_t size, const char **virname /* cli_hm_scan_wild will scan only size-agnostic hashes, if any */ int cli_hm_scan_wild(const unsigned char *digest, const char **virname, const struct cli_matcher *root, cli_hash_type_t type) { - if (!digest || !root || !root->hwild.hashes[type].items) + if (!digest || !root || !root->hwild.hashes[type].items) { return CL_CLEAN; + } return hm_scan(digest, virname, &root->hwild.hashes[type], type); } @@ -303,22 +321,25 @@ void hm_free(struct cli_matcher *root) { cli_hash_type_t type; - if (!root) + if (!root) { return; + } for (type = CLI_HASH_MD5; type < CLI_HASH_AVAIL_TYPES; type++) { struct cli_htu32 *ht = &root->hm.sizehashes[type]; const struct cli_htu32_element *item = NULL; - if (!root->hm.sizehashes[type].capacity) + if (!root->hm.sizehashes[type].capacity) { continue; + } while ((item = cli_htu32_next(ht, item))) { struct cli_sz_hash *szh = (struct cli_sz_hash *)item->data.as_ptr; MPOOL_FREE(root->mempool, szh->hash_array); - while (szh->items) + while (szh->items) { MPOOL_FREE(root->mempool, (void *)szh->virusnames[--szh->items]); + } MPOOL_FREE(root->mempool, (void *)szh->virusnames); MPOOL_FREE(root->mempool, szh); } @@ -328,12 +349,14 @@ void hm_free(struct cli_matcher *root) for (type = CLI_HASH_MD5; type < CLI_HASH_AVAIL_TYPES; type++) { struct cli_sz_hash *szh = &root->hwild.hashes[type]; - if (!szh->items) + if (!szh->items) { continue; + } MPOOL_FREE(root->mempool, szh->hash_array); - while (szh->items) + while (szh->items) { MPOOL_FREE(root->mempool, (void *)szh->virusnames[--szh->items]); + } MPOOL_FREE(root->mempool, (void *)szh->virusnames); } } diff --git a/libclamav/matcher-pcre.c b/libclamav/matcher-pcre.c index 8715dd2389..37491a6ca5 100644 --- a/libclamav/matcher-pcre.c +++ b/libclamav/matcher-pcre.c @@ -143,16 +143,19 @@ void cli_pcre_perf_print() const char *name = cli_event_get_name(p_sigevents, i * PCRE_EVENTS_PER_SIG); cli_event_get(p_sigevents, i * PCRE_EVENTS_PER_SIG, &val, &count); if (!count) { - if (name) + if (name) { cli_dbgmsg("No event triggered for %s\n", name); + } continue; } - if (name) + if (name) { name_len = (int)strlen(name); - else + } else { name_len = 0; - if (name_len > max_name_len) + } + if (name_len > max_name_len) { max_name_len = name_len; + } elem->name = name ? name : "\"noname\""; elem->usecs = val.v_int; elem->run_count = count; @@ -161,8 +164,9 @@ void cli_pcre_perf_print() elem++; elems++; } - if (max_name_len < (int)strlen("PCRE Expression")) + if (max_name_len < (int)strlen("PCRE Expression")) { max_name_len = (int)strlen("PCRE Expression"); + } cli_qsort(stats, elems, sizeof(struct sigperf_elem), sigelem_comp); @@ -287,10 +291,11 @@ cl_error_t cli_pcre_addpatt(struct cli_matcher *root, const char *virname, const return ret; } if (pm->offdata[0] != CLI_OFF_ANY) { - if (pm->offdata[0] == CLI_OFF_ABSOLUTE) + if (pm->offdata[0] == CLI_OFF_ABSOLUTE) { root->pcre_absoff_num++; - else + } else { root->pcre_reloff_num++; + } } /* parse and add options, also totally not from snort */ @@ -344,8 +349,9 @@ cl_error_t cli_pcre_addpatt(struct cli_matcher *root, const char *virname, const } /* add metadata to the performance tracker */ - if (options & CL_DB_PCRE_STATS) + if (options & CL_DB_PCRE_STATS) { pcre_perf_events_init(pm, virname); + } /* add pcre data to root after reallocation */ pcre_count = root->pcre_metas + 1; @@ -373,8 +379,9 @@ cl_error_t cli_pcre_build(struct cli_matcher *root, long long unsigned match_lim struct cli_pcre_meta *pm = NULL; int disable_all = 0; - if (dconf && !(dconf->pcre & PCRE_CONF_SUPPORT)) + if (dconf && !(dconf->pcre & PCRE_CONF_SUPPORT)) { disable_all = 1; + } for (i = 0; i < root->pcre_metas; ++i) { pm = root->pcre_metatable[i]; @@ -516,8 +523,9 @@ void cli_pcre_freeoff(struct cli_pcre_off *data) int cli_pcre_qoff(struct cli_pcre_meta *pm, uint32_t length, uint32_t *adjbuffer, uint32_t *adjshift) { - if (!pm) + if (!pm) { return CL_ENULLARG; + } /* default to scanning whole buffer but try to use existing offdata */ if (pm->offdata[0] == CLI_OFF_NONE) { @@ -557,8 +565,9 @@ cl_error_t cli_pcre_scanbuf(const unsigned char *buffer, uint32_t length, const int options = 0; uint32_t offset = 0; - if ((root->pcre_metas == 0) || (!root->pcre_metatable) || (ctx && ctx->dconf && !(ctx->dconf->pcre & PCRE_CONF_SUPPORT))) + if ((root->pcre_metas == 0) || (!root->pcre_metatable) || (ctx && ctx->dconf && !(ctx->dconf->pcre & PCRE_CONF_SUPPORT))) { return CL_SUCCESS; + } memset(&p_res, 0, sizeof(p_res)); @@ -583,10 +592,12 @@ cl_error_t cli_pcre_scanbuf(const unsigned char *buffer, uint32_t length, const if (pm->lsigid[0]) { pm_dbgmsg("cli_pcre_scanbuf: checking %s; running regex /%s/\n", pm->trigger, pd->expression); #ifdef PCRE_BYPASS - if (strcmp(pm->trigger, PCRE_BYPASS)) + if (strcmp(pm->trigger, PCRE_BYPASS)) { #endif - if (cli_ac_chklsig(pm->trigger, pm->trigger + strlen(pm->trigger), mdata->lsigcnt[pm->lsigid[1]], &evalcnt, &evalids, 0) != 1) + if (cli_ac_chklsig(pm->trigger, pm->trigger + strlen(pm->trigger), mdata->lsigcnt[pm->lsigid[1]], &evalcnt, &evalids, 0) != 1) { continue; + } + } } else { cli_dbgmsg("cli_pcre_scanbuf: skipping %s check due to uninitialized lsigid\n", pm->trigger); /* fall-through to unconditional execution - sigtool-only */ @@ -602,30 +613,34 @@ cl_error_t cli_pcre_scanbuf(const unsigned char *buffer, uint32_t length, const /* adjust the buffer sent to cli_pcre_match for offset and maxshift */ if (!data) { - if (cli_pcre_qoff(pm, length, &adjbuffer, &adjshift) != CL_SUCCESS) + if (cli_pcre_qoff(pm, length, &adjbuffer, &adjshift) != CL_SUCCESS) { continue; + } } else { adjbuffer = data->offset[i]; adjshift = data->shift[i]; } /* check for need to anchoring */ - if (!rolling && !adjshift && (adjbuffer != CLI_OFF_ANY)) + if (!rolling && !adjshift && (adjbuffer != CLI_OFF_ANY)) { options |= PCRE2_ANCHORED; - else + } else { options = 0; + } - if (adjbuffer == CLI_OFF_ANY) + if (adjbuffer == CLI_OFF_ANY) { adjbuffer = 0; + } /* check the offset bounds */ if (adjbuffer < length) { /* handle encompass flag */ if (encompass && adjshift != 0 && adjshift != CLI_OFF_NONE) { - if (adjbuffer + adjshift > length) + if (adjbuffer + adjshift > length) { adjlength = length - adjbuffer; - else + } else { adjlength = adjshift; + } } else { /* NOTE - if using non-encompass method 2, alter shift universally */ /* TODO - limitations on non-encompassed buffers? */ @@ -648,16 +663,18 @@ cl_error_t cli_pcre_scanbuf(const unsigned char *buffer, uint32_t length, const } /* reset the match results */ - if ((ret = cli_pcre_results_reset(&p_res, pd)) != CL_SUCCESS) + if ((ret = cli_pcre_results_reset(&p_res, pd)) != CL_SUCCESS) { break; + } /* performance metrics */ cli_event_time_start(p_sigevents, pm->sigtime_id); rc = cli_pcre_match(pd, buffer + adjbuffer, adjlength, offset, options, &p_res); cli_event_time_stop(p_sigevents, pm->sigtime_id); /* if debug, generate a match report */ - if (cli_debug_flag) + if (cli_debug_flag) { cli_pcre_report(pd, buffer + adjbuffer, adjlength, rc, &p_res); + } /* matched, rc shouldn't be >0 unless a full match occurs */ if (rc > 0) { @@ -742,8 +759,9 @@ cl_error_t cli_pcre_scanbuf(const unsigned char *buffer, uint32_t length, const void cli_pcre_freemeta(struct cli_matcher *root, struct cli_pcre_meta *pm) { - if (!pm) + if (!pm) { return; + } #ifndef USE_MPOOL UNUSEDPARAM(root); diff --git a/libclamav/matcher.c b/libclamav/matcher.c index dfe014508c..2af6485fc8 100644 --- a/libclamav/matcher.c +++ b/libclamav/matcher.c @@ -121,13 +121,17 @@ static inline cl_error_t matcher_run(const struct cli_matcher *root, if (filter_search_ext(root->filter, buffer, length, &info) == -1) { /* for safety always scan last maxpatlen bytes */ pos = length - root->maxpatlen - 1; - if (pos < 0) pos = 0; + if (pos < 0) { + pos = 0; + } perf_log_filter(pos, length, root->type); } else { /* must not cut buffer for 64[4-4]6161, because we must be able to check * 64! */ pos = info.first_match - root->maxpatlen - 1; - if (pos < 0) pos = 0; + if (pos < 0) { + pos = 0; + } perf_log_filter(pos, length, root->type); } } else { @@ -151,13 +155,15 @@ static inline cl_error_t matcher_run(const struct cli_matcher *root, ret = cli_bm_scanbuff(buffer, length, virname, NULL, root, offset, tinfo, offdata, ctx); } if (ret != CL_SUCCESS) { - if (ret != CL_VIRUS) + if (ret != CL_VIRUS) { return ret; + } /* else (ret == CL_VIRUS) */ ret = cli_append_virus(ctx, *virname); - if (ret != CL_SUCCESS) + if (ret != CL_SUCCESS) { return ret; + } } } perf_log_tries(acmode, 0, length); @@ -165,8 +171,9 @@ static inline cl_error_t matcher_run(const struct cli_matcher *root, if (ret != CL_SUCCESS) { if (ret == CL_VIRUS) { ret = cli_append_virus(ctx, *virname); - if (ret != CL_SUCCESS) + if (ret != CL_SUCCESS) { return ret; + } } else if (ret > CL_TYPENO && acmode & AC_SCAN_VIR) { saved_ret = ret; } else { @@ -212,8 +219,9 @@ static inline cl_error_t matcher_run(const struct cli_matcher *root, if (offset + length >= map->len) { /* check that scanned map does not exceed pcre maxfilesize limit */ maxfilesize = (uint64_t)cl_engine_get_num(ctx->engine, CL_ENGINE_PCRE_MAX_FILESIZE, &rc); - if (rc != CL_SUCCESS) + if (rc != CL_SUCCESS) { return rc; + } if (maxfilesize && (map->len > maxfilesize)) { cli_dbgmsg("matcher_run: pcre max filesize (map) exceeded (limit: %llu, needed: %llu)\n", (long long unsigned)maxfilesize, (long long unsigned)map->len); @@ -223,8 +231,9 @@ static inline cl_error_t matcher_run(const struct cli_matcher *root, cli_dbgmsg("matcher_run: performing regex matching on full map: %u+%u(%u) >= %zu\n", offset, length, offset + length, map->len); buffer = fmap_need_off_once(map, 0, map->len); - if (!buffer) + if (!buffer) { return CL_EMEM; + } /* scan the full buffer */ ret = cli_pcre_scanbuf(buffer, map->len, virname, acres, root, mdata, poffdata, ctx); @@ -232,8 +241,9 @@ static inline cl_error_t matcher_run(const struct cli_matcher *root, } else if (pcremode == PCRE_SCAN_BUFF) { /* check that scanned buffer does not exceed pcre maxfilesize limit */ maxfilesize = (uint64_t)cl_engine_get_num(ctx->engine, CL_ENGINE_PCRE_MAX_FILESIZE, &rc); - if (rc != CL_SUCCESS) + if (rc != CL_SUCCESS) { return rc; + } if (maxfilesize && (length > maxfilesize)) { cli_dbgmsg("matcher_run: pcre max filesize (buf) exceeded (limit: %llu, needed: %u)\n", (long long unsigned)maxfilesize, length); return CL_EMAXSIZE; @@ -249,8 +259,9 @@ static inline cl_error_t matcher_run(const struct cli_matcher *root, if (ctx && ret == CL_VIRUS) { ret = cli_append_virus(ctx, *virname); - if (ret != CL_SUCCESS) + if (ret != CL_SUCCESS) { return ret; + } } if (saved_ret && ret == CL_CLEAN) { @@ -287,7 +298,9 @@ cl_error_t cli_scan_buff(const unsigned char *buffer, uint32_t length, uint32_t break; // Break out of inner loop } } - if (target_ac_root) break; + if (target_ac_root) { + break; + } } } @@ -382,10 +395,11 @@ cl_error_t cli_caloff(const char *offstr, const struct cli_target_info *info, cl *offset_max = *offset_min = CLI_OFF_NONE; if (!strncmp(offcpy, "EP+", 3) || !strncmp(offcpy, "EP-", 3)) { - if (offcpy[2] == '+') + if (offcpy[2] == '+') { offdata[0] = CLI_OFF_EP_PLUS; - else + } else { offdata[0] = CLI_OFF_EP_MINUS; + } if (!cli_isnumber(&offcpy[3])) { cli_errmsg("cli_caloff: Invalid offset value\n"); @@ -461,8 +475,9 @@ cl_error_t cli_caloff(const char *offstr, const struct cli_target_info *info, cl } else { /* calculate relative offsets */ *offset_min = CLI_OFF_NONE; - if (offset_max) + if (offset_max) { *offset_max = CLI_OFF_NONE; + } if (info->status == -1) { // If the executable headers weren't parsed successfully then we // can't process any ndb/ldb EOF-n/EP+n/EP-n/Sx+n/SEx/SL+n subsigs @@ -487,10 +502,11 @@ cl_error_t cli_caloff(const char *offstr, const struct cli_target_info *info, cl break; case CLI_OFF_SX_PLUS: - if (offdata[3] >= info->exeinfo.nsections) + if (offdata[3] >= info->exeinfo.nsections) { *offset_min = CLI_OFF_NONE; - else + } else { *offset_min = info->exeinfo.sections[offdata[3]].raw + offdata[1]; + } break; case CLI_OFF_SE: @@ -498,8 +514,9 @@ cl_error_t cli_caloff(const char *offstr, const struct cli_target_info *info, cl *offset_min = CLI_OFF_NONE; } else { *offset_min = info->exeinfo.sections[offdata[3]].raw; - if (offset_max) + if (offset_max) { *offset_max = *offset_min + info->exeinfo.sections[offdata[3]].rsz + offdata[2]; + } // TODO offdata[2] == MaxShift. Won't this make offset_max // extend beyond the end of the section? This doesn't seem like // what we want... @@ -507,16 +524,18 @@ cl_error_t cli_caloff(const char *offstr, const struct cli_target_info *info, cl break; case CLI_OFF_VERSION: - if (offset_max) + if (offset_max) { *offset_min = *offset_max = CLI_OFF_ANY; + } break; default: cli_errmsg("cli_caloff: Not a relative offset (type: %u)\n", offdata[0]); return CL_EARG; } - if (offset_max && *offset_max == CLI_OFF_NONE && *offset_min != CLI_OFF_NONE) + if (offset_max && *offset_max == CLI_OFF_NONE && *offset_min != CLI_OFF_NONE) { *offset_max = *offset_min + offdata[2]; + } } return CL_SUCCESS; @@ -552,10 +571,11 @@ void cli_targetinfo(struct cli_target_info *info, cli_target_t target, cli_ctx * return; } - if (CL_SUCCESS != einfo(ctx, &info->exeinfo)) + if (CL_SUCCESS != einfo(ctx, &info->exeinfo)) { info->status = -1; - else + } else { info->status = 1; + } } void cli_targetinfo_destroy(struct cli_target_info *info) @@ -612,8 +632,9 @@ cl_error_t cli_check_fp(cli_ctx *ctx, const char *vname) const char *name = ctx->recursion_stack[stack_index].fmap->name; const char *type = cli_ftname(ctx->recursion_stack[stack_index].type); - for (i = 0; i < 16; i++) + for (i = 0; i < 16; i++) { sprintf(md5 + i * 2, "%02x", digest[i]); + } md5[32] = 0; cli_dbgmsg("FP SIGNATURE: %s:%u:%s # Name: %s, Type: %s\n", @@ -691,16 +712,18 @@ cl_error_t cli_check_fp(cli_ctx *ctx, const char *vname) } #endif - if (ctx->engine->cb_hash) + if (ctx->engine->cb_hash) { ctx->engine->cb_hash(fmap_fd(ctx->fmap), size, (const unsigned char *)md5, vname ? vname : "noname", ctx->cb_ctx); + } if (ctx->engine->cb_stats_add_sample) { stats_section_t sections; memset(§ions, 0x00, sizeof(stats_section_t)); if (!(ctx->engine->engine_options & ENGINE_OPTIONS_DISABLE_PE_STATS) && - !(ctx->engine->dconf->stats & (DCONF_STATS_DISABLED | DCONF_STATS_PE_SECTION_DISABLED))) + !(ctx->engine->dconf->stats & (DCONF_STATS_DISABLED | DCONF_STATS_PE_SECTION_DISABLED))) { cli_genhash_pe(ctx, CL_GENHASH_PE_CLASS_SECTION, 1, §ions); + } // TODO We probably only want to call cb_stats_add_sample when // sections.section != NULL... leaving as is for now @@ -726,10 +749,13 @@ static cl_error_t matchicon(cli_ctx *ctx, struct cli_exe_info *exeinfo, const ch !ctx->engine->iconcheck || !ctx->engine->iconcheck->group_counts[0] || !ctx->engine->iconcheck->group_counts[1] || - !exeinfo->res_addr) return CL_CLEAN; + !exeinfo->res_addr) { + return CL_CLEAN; + } - if (!(ctx->dconf->pe & PE_CONF_MATCHICON)) + if (!(ctx->dconf->pe & PE_CONF_MATCHICON)) { return CL_CLEAN; + } cli_icongroupset_init(&iconset); cli_icongroupset_add(grp1 ? grp1 : "*", &iconset, 0, ctx); @@ -752,8 +778,9 @@ int32_t cli_bcapi_matchicon(struct cli_bc_ctx *ctx, const uint8_t *grp1, int32_t return -1; } if ((size_t)grp1len > sizeof(group1) - 1 || - (size_t)grp2len > sizeof(group2) - 1) + (size_t)grp2len > sizeof(group2) - 1) { return -1; + } memcpy(group1, grp1, grp1len); memcpy(group2, grp2, grp2len); @@ -762,12 +789,14 @@ int32_t cli_bcapi_matchicon(struct cli_bc_ctx *ctx, const uint8_t *grp1, int32_t memset(&info, 0, sizeof(info)); if (ctx->bc->kind == BC_PE_UNPACKER || ctx->bc->kind == BC_PE_ALL) { if (le16_to_host(ctx->hooks.pedata->file_hdr.Characteristics) & 0x2000 || - !ctx->hooks.pedata->dirs[2].Size) + !ctx->hooks.pedata->dirs[2].Size) { info.res_addr = 0; - else + } else { info.res_addr = ctx->hooks.pedata->dirs[2].VirtualAddress; - } else + } + } else { info.res_addr = ctx->resaddr; /* from target_info */ + } info.sections = (struct cli_exe_section *)ctx->sections; info.nsections = ctx->hooks.pedata->nsections; info.hdr_size = ctx->hooks.pedata->hdr_size; @@ -818,14 +847,17 @@ static int intermediates_eval(cli_ctx *ctx, struct cli_ac_lsig *ac_lsig) // -1 is the deepest layer (the current layer), so we start at -2, which is the first ancestor int32_t j = -2; - if (ctx->recursion_level < icnt) + if (ctx->recursion_level < icnt) { return 0; + } for (i = icnt; i > 0; i--) { - if (ac_lsig->tdb.intermediates[i] == CL_TYPE_ANY) + if (ac_lsig->tdb.intermediates[i] == CL_TYPE_ANY) { continue; - if (ac_lsig->tdb.intermediates[i] != cli_recursion_stack_get_type(ctx, j--)) + } + if (ac_lsig->tdb.intermediates[i] != cli_recursion_stack_get_type(ctx, j--)) { return 0; + } } return 1; } @@ -841,8 +873,9 @@ static cl_error_t lsig_eval(cli_ctx *ctx, struct cli_matcher *root, struct cli_a char *exp_end = exp + strlen(exp); status = cli_ac_chkmacro(root, acdata, lsid); - if (status != CL_SUCCESS) + if (status != CL_SUCCESS) { return status; + } if (cli_ac_chklsig(exp, exp_end, acdata->lsigcnt[lsid], &evalcnt, &evalids, 0) != 1) { // Logical expression did not match. @@ -880,12 +913,15 @@ static cl_error_t lsig_eval(cli_ctx *ctx, struct cli_matcher *root, struct cli_a } if (ac_lsig->tdb.ep || ac_lsig->tdb.nos) { - if (!target_info || target_info->status != 1) + if (!target_info || target_info->status != 1) { goto done; - if (ac_lsig->tdb.ep && (ac_lsig->tdb.ep[0] > target_info->exeinfo.ep || ac_lsig->tdb.ep[1] < target_info->exeinfo.ep)) + } + if (ac_lsig->tdb.ep && (ac_lsig->tdb.ep[0] > target_info->exeinfo.ep || ac_lsig->tdb.ep[1] < target_info->exeinfo.ep)) { goto done; - if (ac_lsig->tdb.nos && (ac_lsig->tdb.nos[0] > target_info->exeinfo.nsections || ac_lsig->tdb.nos[1] < target_info->exeinfo.nsections)) + } + if (ac_lsig->tdb.nos && (ac_lsig->tdb.nos[0] > target_info->exeinfo.nsections || ac_lsig->tdb.nos[1] < target_info->exeinfo.nsections)) { goto done; + } } if (ac_lsig->tdb.handlertype) { @@ -982,8 +1018,9 @@ static cl_error_t yara_eval(cli_ctx *ctx, struct cli_matcher *root, struct cli_a context.fmap = ctx->fmap; context.file_size = ctx->fmap->len; if (target_info != NULL) { - if (target_info->status == 1) + if (target_info->status == 1) { context.entry_point = target_info->exeinfo.ep; + } } rc = yr_execute_code(ac_lsig, acdata, &context, 0, 0); @@ -1108,7 +1145,9 @@ cl_error_t cli_scan_fmap(cli_ctx *ctx, cli_file_t ftype, bool filetype_only, str break; // Break out of inner loop } } - if (target_ac_root) break; + if (target_ac_root) { + break; + } } } @@ -1286,10 +1325,12 @@ cl_error_t cli_scan_fmap(cli_ctx *ctx, cli_file_t ftype, bool filetype_only, str } bytes = MIN(ctx->fmap->len - offset, SCANBUFF); - if (!(buff = fmap_need_off_once(ctx->fmap, offset, bytes))) + if (!(buff = fmap_need_off_once(ctx->fmap, offset, bytes))) { break; - if (ctx->scanned) + } + if (ctx->scanned) { *ctx->scanned += bytes / CL_COUNT_PRECISION; + } if (target_ac_root) { const char *virname = NULL; @@ -1313,8 +1354,9 @@ cl_error_t cli_scan_fmap(cli_ctx *ctx, cli_file_t ftype, bool filetype_only, str if (ret == CL_VIRUS || ret == CL_EMEM) { goto done; } else if ((acmode & AC_SCAN_FT) && ((cli_file_t)ret >= CL_TYPENO)) { - if (ret > type) + if (ret > type) { type = ret; + } } /* if (bytes <= (maxpatlen * (offset!=0))), it means the last window finished the file hashing * @@ -1323,17 +1365,21 @@ cl_error_t cli_scan_fmap(cli_ctx *ctx, cli_file_t ftype, bool filetype_only, str const void *data = buff + maxpatlen * (offset != 0); uint32_t data_len = bytes - maxpatlen * (offset != 0); - if (compute_hash[CLI_HASH_MD5]) + if (compute_hash[CLI_HASH_MD5]) { cl_update_hash(md5ctx, (void *)data, data_len); - if (compute_hash[CLI_HASH_SHA1]) + } + if (compute_hash[CLI_HASH_SHA1]) { cl_update_hash(sha1ctx, (void *)data, data_len); - if (compute_hash[CLI_HASH_SHA256]) + } + if (compute_hash[CLI_HASH_SHA256]) { cl_update_hash(sha256ctx, (void *)data, data_len); + } } } - if (bytes < SCANBUFF) + if (bytes < SCANBUFF) { break; + } offset += bytes - maxpatlen; } @@ -1493,22 +1539,26 @@ cl_error_t cli_matchmeta(cli_ctx *ctx, const char *fname, size_t fsizec, size_t } do { - if (cdb->ctype != CL_TYPE_ANY && cdb->ctype != cli_recursion_stack_get_type(ctx, -1)) + if (cdb->ctype != CL_TYPE_ANY && cdb->ctype != cli_recursion_stack_get_type(ctx, -1)) { continue; + } - if (cdb->encrypted != 2 && cdb->encrypted != encrypted) + if (cdb->encrypted != 2 && cdb->encrypted != encrypted) { continue; + } - if (cdb->res1 && (cdb->ctype == CL_TYPE_ZIP || cdb->ctype == CL_TYPE_RAR) && cdb->res1 != res1) + if (cdb->res1 && (cdb->ctype == CL_TYPE_ZIP || cdb->ctype == CL_TYPE_RAR) && cdb->res1 != res1) { continue; + } CDBRANGE(cdb->csize, cli_recursion_stack_get_size(ctx, -1)); CDBRANGE(cdb->fsizec, fsizec); CDBRANGE(cdb->fsizer, fsizer); CDBRANGE(cdb->filepos, filepos); - if (cdb->name.re_magic && (!fname || cli_regexec(&cdb->name, fname, 0, NULL, 0) == REG_NOMATCH)) + if (cdb->name.re_magic && (!fname || cli_regexec(&cdb->name, fname, 0, NULL, 0) == REG_NOMATCH)) { continue; + } ret = cli_append_virus(ctx, cdb->virname); if (ret != CL_SUCCESS) { diff --git a/libclamav/mbox.c b/libclamav/mbox.c index 43103fd337..6fbc0a5137 100644 --- a/libclamav/mbox.c +++ b/libclamav/mbox.c @@ -510,7 +510,7 @@ cli_parse_mbox(const char *dir, cli_ctx *ctx) /* * It's a single message, parse the headers then the body */ - if (strncmp(buffer, "P I ", 4) == 0) + if (strncmp(buffer, "P I ", 4) == 0) { /* * CommuniGate Pro format: ignore headers until * blank line @@ -519,6 +519,7 @@ cli_parse_mbox(const char *dir, cli_ctx *ctx) (strchr("\r\n", buffer[0]) == NULL)) { ; } + } /* getline_from_mbox could be using unlocked_stdio(3), * so lock file here */ /* @@ -835,8 +836,9 @@ parseEmailFile(fmap_t *map, size_t *at, const table_t *rfc821, const char *first cli_dbgmsg("parseEmailFile\n"); ret = messageCreate(); - if (ret == NULL) + if (ret == NULL) { return NULL; + } CLI_CALLOC_OR_GOTO_DONE(head, 1, sizeof(ReadStruct)); curr = head; @@ -847,10 +849,11 @@ parseEmailFile(fmap_t *map, size_t *at, const table_t *rfc821, const char *first (void)cli_chomp(buffer); - if (buffer[0] == '\0') + if (buffer[0] == '\0') { line = NULL; - else + } else { line = buffer; + } if (doContinueMultipleEmptyOptions(line, &lastWasOnlySemi)) { continue; @@ -933,9 +936,10 @@ parseEmailFile(fmap_t *map, size_t *at, const table_t *rfc821, const char *first * A blank line signifies the end of * the header and the start of the text */ - if (!anyHeadersFound) + if (!anyHeadersFound) { /* Ignore the junk at the top */ continue; + } cli_dbgmsg("End of header information\n"); inHeader = false; @@ -951,16 +955,18 @@ parseEmailFile(fmap_t *map, size_t *at, const table_t *rfc821, const char *first /* * Continuation of line we're ignoring? */ - if (isblank(line[0])) + if (isblank(line[0])) { continue; + } /* * Is this a header we're interested in? */ if ((strchr(line, ':') == NULL) || (cli_strtokbuf(line, 0, ":", cmd) == NULL)) { - if (strncmp(line, "From ", 5) == 0) + if (strncmp(line, "From ", 5) == 0) { anyHeadersFound = true; + } continue; } @@ -974,8 +980,9 @@ parseEmailFile(fmap_t *map, size_t *at, const table_t *rfc821, const char *first anyHeadersFound = true; break; default: - if (!anyHeadersFound) + if (!anyHeadersFound) { anyHeadersFound = usefulHeader(commandNumber, cmd); + } continue; } curr = appendReadStruct(curr, line); @@ -1006,8 +1013,9 @@ parseEmailFile(fmap_t *map, size_t *at, const table_t *rfc821, const char *first * * Add all the arguments on the line */ - if (isblank(*lookahead)) + if (isblank(*lookahead)) { continue; + } } /* @@ -1051,9 +1059,11 @@ parseEmailFile(fmap_t *map, size_t *at, const table_t *rfc821, const char *first * TODO: binhex, yenc */ bodyIsEmpty = false; - if (uudecodeFile(ret, line, dir, map, at) < 0) - if (messageAddStr(ret, line) < 0) + if (uudecodeFile(ret, line, dir, map, at) < 0) { + if (messageAddStr(ret, line) < 0) { break; + } + } } else { if (line == NULL) { /* @@ -1075,15 +1085,17 @@ parseEmailFile(fmap_t *map, size_t *at, const table_t *rfc821, const char *first * line of the body is in fact * the last lines of the header */ - if (newline_in_header(line)) + if (newline_in_header(line)) { continue; + } bodyIsEmpty = false; } lastBodyLineWasBlank = false; } - if (messageAddStr(ret, line) < 0) + if (messageAddStr(ret, line) < 0) { break; + } } } while (getline_from_mbox(buffer, sizeof(buffer) - 1, map, at) != NULL); @@ -1145,18 +1157,20 @@ parseEmailHeaders(message *m, const table_t *rfc821, bool *heuristicFound) *heuristicFound = false; - if (m == NULL) + if (m == NULL) { return NULL; + } ret = messageCreate(); for (t = messageGetBody(m); t; t = t->t_next) { const char *line; - if (t->t_line) + if (t->t_line) { line = lineGetData(t->t_line); - else + } else { line = NULL; + } if (doContinueMultipleEmptyOptions(line, &lastWasOnlySemi)) { continue; @@ -1191,23 +1205,26 @@ parseEmailHeaders(message *m, const table_t *rfc821, bool *heuristicFound) /* * Continuation of line we're ignoring? */ - if (isblank(line[0])) + if (isblank(line[0])) { continue; + } /* * Is this a header we're interested in? */ if ((strchr(line, ':') == NULL) || (cli_strtokbuf(line, 0, ":", cmd) == NULL)) { - if (strncmp(line, "From ", 5) == 0) + if (strncmp(line, "From ", 5) == 0) { anyHeadersFound = true; + } continue; } ptr = rfc822comments(cmd, NULL); commandNumber = tableFind(rfc821, ptr ? ptr : cmd); - if (ptr) + if (ptr) { free(ptr); + } switch (commandNumber) { case CONTENT_TRANSFER_ENCODING: @@ -1216,8 +1233,9 @@ parseEmailHeaders(message *m, const table_t *rfc821, bool *heuristicFound) anyHeadersFound = true; break; default: - if (!anyHeadersFound) + if (!anyHeadersFound) { anyHeadersFound = usefulHeader(commandNumber, cmd); + } continue; } fullline = cli_safer_strdup(line); @@ -1225,8 +1243,9 @@ parseEmailHeaders(message *m, const table_t *rfc821, bool *heuristicFound) } else if (line) { fulllinelength += strlen(line) + 1; ptr = cli_max_realloc(fullline, fulllinelength); - if (ptr == NULL) + if (ptr == NULL) { continue; + } fullline = ptr; cli_strlcat(fullline, line, fulllinelength); } else { @@ -1244,15 +1263,17 @@ parseEmailHeaders(message *m, const table_t *rfc821, bool *heuristicFound) } } - if (next_is_folded_header(t)) + if (next_is_folded_header(t)) { /* Add arguments to this line */ continue; + } lineUnlink(t->t_line); t->t_line = NULL; - if (count_quotes(fullline) & 1) + if (count_quotes(fullline) & 1) { continue; + } ptr = rfc822comments(fullline, NULL); if (ptr) { @@ -1276,17 +1297,19 @@ parseEmailHeaders(message *m, const table_t *rfc821, bool *heuristicFound) } } else { if (bodyIsEmpty) { - if (line == NULL) + if (line == NULL) { /* throw away leading blank lines */ continue; + } /* * Broken message: new line in the * middle of the headers, so the first * line of the body is in fact * the last lines of the header */ - if (newline_in_header(line)) + if (newline_in_header(line)) { continue; + } bodyIsEmpty = false; } /*if(t->t_line && isuuencodebegin(t->t_line)) @@ -1298,12 +1321,14 @@ parseEmailHeaders(message *m, const table_t *rfc821, bool *heuristicFound) } if (fullline) { - if (*fullline) switch (commandNumber) { + if (*fullline) { + switch (commandNumber) { case CONTENT_TRANSFER_ENCODING: case CONTENT_DISPOSITION: case CONTENT_TYPE: cli_dbgmsg("parseEmailHeaders: Fullline unparsed '%s'\n", fullline); } + } free(fullline); } @@ -1347,12 +1372,15 @@ parseEmailHeader(message *m, const char *line, const table_t *rfc821, cli_ctx *c * However some MUA's are lapse about this and virus writers exploit * this hole, so we need to check all known possibilities */ - for (separator = ":= "; *separator; separator++) - if (strchr(line, *separator) != NULL) + for (separator = ":= "; *separator; separator++) { + if (strchr(line, *separator) != NULL) { break; + } + } - if (*separator == '\0') + if (*separator == '\0') { return -1; + } copy = rfc2047(line); if (copy == NULL) { @@ -1457,8 +1485,9 @@ static cl_error_t parseMHTMLComment(const char *comment, cli_ctx *ctx, void *wrk if (!reader) { cli_dbgmsg("parseMHTMLComment: cannot initialize xmlReader\n"); - if (ctx->wrkproperty != NULL) + if (ctx->wrkproperty != NULL) { ret = cli_json_parse_error(ctx->wrkproperty, "MHTML_ERROR_XML_READER_MEM"); + } return ret; // libxml2 failed! } @@ -1470,8 +1499,9 @@ static cl_error_t parseMHTMLComment(const char *comment, cli_ctx *ctx, void *wrk xmlTextReaderClose(reader); xmlFreeTextReader(reader); - if (ret != CL_SUCCESS) + if (ret != CL_SUCCESS) { return ret; + } } return ret; } @@ -1497,28 +1527,34 @@ parseRootMHTML(mbox_ctx *mctx, message *m, text *t) cli_dbgmsg("in parseRootMHTML\n"); - if (ctx == NULL) + if (ctx == NULL) { return OK; + } - if (m == NULL && t == NULL) + if (m == NULL && t == NULL) { return OK; + } - if (m != NULL) + if (m != NULL) { input = messageToBlob(m, 0); - else /* t != NULL */ + } else { /* t != NULL */ input = textToBlob(t, NULL, 0); + } - if (input == NULL) + if (input == NULL) { return OK; + } htmlDoc = htmlReadMemory((char *)input->data, input->len, "mhtml.html", NULL, CLAMAV_MIN_XMLREADER_FLAGS | HTML_PARSE_NOWARNING); if (htmlDoc == NULL) { cli_dbgmsg("parseRootMHTML: cannot initialize read html document\n"); - if (ctx->wrkproperty != NULL) + if (ctx->wrkproperty != NULL) { ret = cli_json_parse_error(ctx->wrkproperty, "MHTML_ERROR_HTML_READ"); - if (ret != CL_SUCCESS) + } + if (ret != CL_SUCCESS) { rc = FAIL; + } blobDestroy(input); return rc; @@ -1537,10 +1573,12 @@ parseRootMHTML(mbox_ctx *mctx, message *m, text *t) if (reader == NULL) { cli_dbgmsg("parseRootMHTML: cannot initialize xmlTextReader\n"); - if (ctx->wrkproperty != NULL) + if (ctx->wrkproperty != NULL) { ret = cli_json_parse_error(ctx->wrkproperty, "MHTML_ERROR_XML_READER_IO"); - if (ret != CL_SUCCESS) + } + if (ret != CL_SUCCESS) { rc = FAIL; + } blobDestroy(input); return rc; @@ -1613,7 +1651,7 @@ parseEmailBody(message *messageIn, text *textIn, mbox_ctx *mctx, unsigned int re mctx->files); /* FIXMELIMITS: this should be better integrated */ - if (engine->max_recursion_level) + if (engine->max_recursion_level) { /* * This is approximate */ @@ -1623,6 +1661,7 @@ parseEmailBody(message *messageIn, text *textIn, mbox_ctx *mctx, unsigned int re cli_dbgmsg("parseEmailBody: hit maximum recursion level (%u)\n", recursion_level); return MAXREC; } + } if (engine->maxfiles && (mctx->files >= engine->maxfiles)) { /* * FIXME: This is only approx - it may have already @@ -1687,8 +1726,9 @@ parseEmailBody(message *messageIn, text *textIn, mbox_ctx *mctx, unsigned int re cli_dbgmsg("Changing message/rfc822-headers to text/rfc822-headers\n"); mimeType = NOMIME; messageSetMimeSubtype(mainMessage, ""); - } else + } else { cli_dbgmsg("mimeType = %d\n", (int)mimeType); + } switch (mimeType) { case NOMIME: @@ -1716,16 +1756,18 @@ parseEmailBody(message *messageIn, text *textIn, mbox_ctx *mctx, unsigned int re * There might be html sent without subtype * html too, so scan them for phishing */ - if (rc == VIRUS) + if (rc == VIRUS) { infected = true; + } } break; case MULTIPART: cli_dbgmsg("Content-type 'multipart' handler\n"); boundary = messageFindArgument(mainMessage, "boundary"); - if (mctx->wrkobj != NULL) + if (mctx->wrkobj != NULL) { cli_jsonstr(mctx->wrkobj, "Boundary", boundary); + } if (boundary == NULL) { cli_dbgmsg("Multipart/%s MIME message contains no boundary header\n", @@ -1760,10 +1802,11 @@ parseEmailBody(message *messageIn, text *textIn, mbox_ctx *mctx, unsigned int re break; } - do + do { if (t_line->t_line) { - if (boundaryStart(lineGetData(t_line->t_line), boundary)) + if (boundaryStart(lineGetData(t_line->t_line), boundary)) { break; + } /* * Found a binhex file before * the first multipart @@ -1789,11 +1832,12 @@ parseEmailBody(message *messageIn, text *textIn, mbox_ctx *mctx, unsigned int re */ cli_dbgmsg("Found MIME attachment before the first MIME section \"%s\"\n", lineGetData(t_line->t_next->t_line)); - if (messageGetEncoding(mainMessage) == NOENCODING) + if (messageGetEncoding(mainMessage) == NOENCODING) { break; + } } } - while ((t_line = t_line->t_next) != NULL); + } while ((t_line = t_line->t_next) != NULL); if (t_line == NULL) { cli_dbgmsg("Multipart MIME message contains no boundary lines (%s)\n", @@ -1839,8 +1883,9 @@ parseEmailBody(message *messageIn, text *textIn, mbox_ctx *mctx, unsigned int re mbox_status old_rc; m = cli_max_realloc(messages, ((multiparts + 1) * sizeof(message *))); - if (m == NULL) + if (m == NULL) { break; + } messages = m; aMessage = messages[multiparts] = messageCreate(); @@ -1859,11 +1904,13 @@ parseEmailBody(message *messageIn, text *textIn, mbox_ctx *mctx, unsigned int re * Ignore blank lines. There shouldn't be ANY * but some viruses insert them */ - while ((t_line = t_line->t_next) != NULL) + while ((t_line = t_line->t_next) != NULL) { if (t_line->t_line && /*(cli_chomp(t_line->t_text) > 0))*/ - (strlen(lineGetData(t_line->t_line)) > 0)) + (strlen(lineGetData(t_line->t_line)) > 0)) { break; + } + } if (t_line == NULL) { cli_dbgmsg("Empty part\n"); @@ -1917,8 +1964,9 @@ parseEmailBody(message *messageIn, text *textIn, mbox_ctx *mctx, unsigned int re break; } - while (isspace((int)*line)) + while (isspace((int)*line)) { line++; + } if (*line == '\0') { inhead = inMimeHead = 0; @@ -2002,8 +2050,9 @@ parseEmailBody(message *messageIn, text *textIn, mbox_ctx *mctx, unsigned int re * Choose application to * force a save */ - if (messageGetMimeType(aMessage) == NOMIME) + if (messageGetMimeType(aMessage) == NOMIME) { messageSetMimeType(aMessage, "application"); + } continue; } @@ -2020,8 +2069,9 @@ parseEmailBody(message *messageIn, text *textIn, mbox_ctx *mctx, unsigned int re } fullline = rfc822comments(line, NULL); - if (fullline == NULL) + if (fullline == NULL) { fullline = cli_safer_strdup(line); + } /*quotes = count_quotes(fullline);*/ @@ -2056,8 +2106,9 @@ parseEmailBody(message *messageIn, text *textIn, mbox_ctx *mctx, unsigned int re datasz = strlen(fullline) + strlen(data) + 1; ptr = cli_max_realloc(fullline, datasz); - if (ptr == NULL) + if (ptr == NULL) { break; + } fullline = ptr; cli_strlcat(fullline, data, datasz); @@ -2088,8 +2139,9 @@ parseEmailBody(message *messageIn, text *textIn, mbox_ctx *mctx, unsigned int re inhead = 1; break; } else { - if (messageAddLine(aMessage, t_line->t_line) < 0) + if (messageAddLine(aMessage, t_line->t_line) < 0) { break; + } lines++; } } while ((t_line = t_line->t_next) != NULL); @@ -2116,15 +2168,17 @@ parseEmailBody(message *messageIn, text *textIn, mbox_ctx *mctx, unsigned int re messages, multiparts, &rc, mctx, messageIn, &aText, recursion_level); - if ((rc == OK_ATTACHMENTS_NOT_SAVED) && (old_rc == OK)) + if ((rc == OK_ATTACHMENTS_NOT_SAVED) && (old_rc == OK)) { rc = OK; + } if (messages[multiparts]) { messageDestroy(messages[multiparts]); messages[multiparts] = NULL; } --multiparts; - if (rc == VIRUS) + if (rc == VIRUS) { infected = true; + } break; case RELATED: @@ -2152,8 +2206,9 @@ parseEmailBody(message *messageIn, text *textIn, mbox_ctx *mctx, unsigned int re if (haveTooManyMIMEPartsPerMessage(multiparts, mctx->ctx, &rc)) { if (messages) { for (i = 0; i < multiparts; i++) { - if (messages[i]) + if (messages[i]) { messageDestroy(messages[i]); + } } free(messages); messages = NULL; @@ -2195,14 +2250,16 @@ parseEmailBody(message *messageIn, text *textIn, mbox_ctx *mctx, unsigned int re if (infected || ((multiparts == 0) && (aText == NULL))) { if (messages) { for (i = 0; i < multiparts; i++) { - if (messages[i]) + if (messages[i]) { messageDestroy(messages[i]); + } } free(messages); messages = NULL; } - if (aText && (textIn == NULL)) + if (aText && (textIn == NULL)) { textDestroy(aText); + } mctx->wrkobj = saveobj; @@ -2262,8 +2319,9 @@ parseEmailBody(message *messageIn, text *textIn, mbox_ctx *mctx, unsigned int re cli_dbgmsg("No HTML code found to be scanned\n"); } else { /* Send root HTML file for preclassification */ - if (mctx->ctx->wrkproperty) + if (mctx->ctx->wrkproperty) { (void)parseRootMHTML(mctx, messages[htmltextPart], aText); + } rc = parseEmailBody(messages[htmltextPart], aText, mctx, recursion_level + 1); if ((rc == OK) && messages[htmltextPart]) { @@ -2329,8 +2387,9 @@ parseEmailBody(message *messageIn, text *textIn, mbox_ctx *mctx, unsigned int re * matter to add it */ if (aText) { - if (mainMessage && (mainMessage != messageIn)) + if (mainMessage && (mainMessage != messageIn)) { messageDestroy(mainMessage); + } mainMessage = NULL; } @@ -2343,10 +2402,12 @@ parseEmailBody(message *messageIn, text *textIn, mbox_ctx *mctx, unsigned int re infected = true; break; } - if (rc == MAXREC) + if (rc == MAXREC) { break; - if (rc == OK_ATTACHMENTS_NOT_SAVED) + } + if (rc == OK_ATTACHMENTS_NOT_SAVED) { rc = OK; + } } /* rc = parseEmailBody(NULL, NULL, mctx, recursion_level + 1); */ @@ -2363,8 +2424,9 @@ parseEmailBody(message *messageIn, text *textIn, mbox_ctx *mctx, unsigned int re */ if (messages) { htmltextPart = getTextPart(messages, multiparts); - if (htmltextPart == -1) + if (htmltextPart == -1) { htmltextPart = 0; + } rc = parseEmailBody(messages[htmltextPart], aText, mctx, recursion_level + 1); } break; @@ -2374,8 +2436,9 @@ parseEmailBody(message *messageIn, text *textIn, mbox_ctx *mctx, unsigned int re break; } - if (mainMessage && (mainMessage != messageIn)) + if (mainMessage && (mainMessage != messageIn)) { messageDestroy(mainMessage); + } if (aText && (textIn == NULL)) { if ((!infected) && (fb = fileblobCreate()) != NULL) { @@ -2393,8 +2456,9 @@ parseEmailBody(message *messageIn, text *textIn, mbox_ctx *mctx, unsigned int re if (messages) { for (i = 0; i < multiparts; i++) { - if (messages[i]) + if (messages[i]) { messageDestroy(messages[i]); + } } free(messages); messages = NULL; @@ -2429,10 +2493,12 @@ parseEmailBody(message *messageIn, text *textIn, mbox_ctx *mctx, unsigned int re if (mainMessage && (mainMessage != messageIn)) { messageDestroy(mainMessage); mainMessage = NULL; - } else + } else { messageReset(mainMessage); - if (messageGetBody(m)) + } + if (messageGetBody(m)) { rc = parseEmailBody(m, NULL, mctx, recursion_level + 1); + } messageDestroy(m); } else if (heuristicFound) { @@ -2446,24 +2512,28 @@ parseEmailBody(message *messageIn, text *textIn, mbox_ctx *mctx, unsigned int re } else if (strcasecmp(mimeSubtype, "partial") == 0) { if (mctx->ctx->options->mail & CL_SCAN_MAIL_PARTIAL_MESSAGE) { /* RFC1341 message split over many emails */ - if (rfc1341(mctx, mainMessage) >= 0) + if (rfc1341(mctx, mainMessage) >= 0) { rc = OK; + } } else { cli_warnmsg("Partial message received from MUA/MTA - message cannot be scanned\n"); } - } else if (strcasecmp(mimeSubtype, "external-body") == 0) + } else if (strcasecmp(mimeSubtype, "external-body") == 0) { /* TODO */ cli_warnmsg("Attempt to send Content-type message/external-body trapped\n"); - else + } else { cli_warnmsg("Unsupported message format `%s' - if you believe this file contains a virus, submit it to www.clamav.net\n", mimeSubtype); + } - if (mainMessage && (mainMessage != messageIn)) + if (mainMessage && (mainMessage != messageIn)) { messageDestroy(mainMessage); + } if (messages) { for (i = 0; i < multiparts; i++) { - if (messages[i]) + if (messages[i]) { messageDestroy(messages[i]); + } } free(messages); messages = NULL; @@ -2493,14 +2563,16 @@ parseEmailBody(message *messageIn, text *textIn, mbox_ctx *mctx, unsigned int re if (fb) { cli_dbgmsg("Saving main message as attachment\n"); - if (fileblobScanAndDestroy(fb) == CL_VIRUS) + if (fileblobScanAndDestroy(fb) == CL_VIRUS) { rc = VIRUS; + } mctx->files++; if (mainMessage != messageIn) { messageDestroy(mainMessage); mainMessage = NULL; - } else + } else { messageReset(mainMessage); + } } } /*else cli_warnmsg("Discarded application not sent as attachment\n");*/ @@ -2516,8 +2588,9 @@ parseEmailBody(message *messageIn, text *textIn, mbox_ctx *mctx, unsigned int re /* "can't happen" */ cli_warnmsg("messages != NULL\n"); for (i = 0; i < multiparts; i++) { - if (messages[i]) + if (messages[i]) { messageDestroy(messages[i]); + } } free(messages); messages = NULL; @@ -2540,10 +2613,11 @@ parseEmailBody(message *messageIn, text *textIn, mbox_ctx *mctx, unsigned int re continue; } - if (lookahead_definitely_is_bounce) + if (lookahead_definitely_is_bounce) { lookahead_definitely_is_bounce = false; - else if (!isBounceStart(mctx, lineGetData(l))) + } else if (!isBounceStart(mctx, lineGetData(l))) { continue; + } lookahead = t->t_next; if (lookahead) { @@ -2552,8 +2626,9 @@ parseEmailBody(message *messageIn, text *textIn, mbox_ctx *mctx, unsigned int re /* don't save worthless header lines */ continue; } - } else /* don't save a single liner */ + } else { /* don't save a single liner */ break; + } /* * We've found what looks like the start of a bounce @@ -2565,15 +2640,16 @@ parseEmailBody(message *messageIn, text *textIn, mbox_ctx *mctx, unsigned int re for (; lookahead; lookahead = lookahead->t_next) { l = lookahead->t_line; - if (l == NULL) + if (l == NULL) { break; + } s = lineGetData(l); if (strncasecmp(s, "Content-Type:", 13) == 0) { /* * Don't bother with text/plain or * text/html */ - if (CLI_STRCASESTR(s, "text/plain") != NULL) + if (CLI_STRCASESTR(s, "text/plain") != NULL) { /* * Don't bother to save the * unuseful part, read past @@ -2582,9 +2658,11 @@ parseEmailBody(message *messageIn, text *textIn, mbox_ctx *mctx, unsigned int re * bounce message */ continue; + } if ((!doPhishingScan) && - (CLI_STRCASESTR(s, "text/html") != NULL)) + (CLI_STRCASESTR(s, "text/html") != NULL)) { continue; + } break; } } @@ -2613,8 +2691,9 @@ parseEmailBody(message *messageIn, text *textIn, mbox_ctx *mctx, unsigned int re if ((strncasecmp(s, "Content-Type:", 13) == 0) && (strstr(s, "multipart/") == NULL) && (strstr(s, "message/rfc822") == NULL) && - (strstr(s, "text/plain") == NULL)) + (strstr(s, "text/plain") == NULL)) { break; + } } } if (lookahead == NULL) { @@ -2622,8 +2701,9 @@ parseEmailBody(message *messageIn, text *textIn, mbox_ctx *mctx, unsigned int re /* nothing here, move along please */ break; } - if ((fb = fileblobCreate()) == NULL) + if ((fb = fileblobCreate()) == NULL) { break; + } cli_dbgmsg("Save non mime part bounce message\n"); fileblobSetFilename(fb, mctx->dir, "bounce"); fileblobAddData(fb, (const unsigned char *)"Received: by clamd (bounce)\n", 28); @@ -2645,8 +2725,9 @@ parseEmailBody(message *messageIn, text *textIn, mbox_ctx *mctx, unsigned int re } fileblobAddData(fb, (const unsigned char *)"\n", 1); lookahead = t->t_next; - if (lookahead == NULL) + if (lookahead == NULL) { break; + } t = lookahead; l = t->t_line; if ((!inheader) && l) { @@ -2659,12 +2740,14 @@ parseEmailBody(message *messageIn, text *textIn, mbox_ctx *mctx, unsigned int re } } while (!fileblobInfected(fb)); - if (fileblobScanAndDestroy(fb) == CL_VIRUS) + if (fileblobScanAndDestroy(fb) == CL_VIRUS) { rc = VIRUS; + } mctx->files++; - if (topofbounce) + if (topofbounce) { t = topofbounce; + } } textDestroy(aText); aText = NULL; @@ -2682,12 +2765,12 @@ parseEmailBody(message *messageIn, text *textIn, mbox_ctx *mctx, unsigned int re */ if (mainMessage->body_first != NULL && (encodingLine(mainMessage) != NULL) && - ((t_line = bounceBegin(mainMessage)) != NULL)) + ((t_line = bounceBegin(mainMessage)) != NULL)) { rc = (exportBounceMessage(mctx, t_line) == CL_VIRUS) ? VIRUS : OK; - else { + } else { bool saveIt; - if (messageGetMimeType(mainMessage) == MESSAGE) + if (messageGetMimeType(mainMessage) == MESSAGE) { /* * Quick peek, if the encapsulated * message has no @@ -2695,7 +2778,7 @@ parseEmailBody(message *messageIn, text *textIn, mbox_ctx *mctx, unsigned int re * bother saving to scan, it's safe */ saveIt = (bool)(encodingLine(mainMessage) != NULL); - else if (mainMessage->body_last != NULL && (t_line = encodingLine(mainMessage)) != NULL) { + } else if (mainMessage->body_last != NULL && (t_line = encodingLine(mainMessage)) != NULL) { /* * Some bounces include the message * body without the headers. @@ -2712,41 +2795,47 @@ parseEmailBody(message *messageIn, text *textIn, mbox_ctx *mctx, unsigned int re 28); fileblobSetCTX(fb, mctx->ctx); - if (fileblobScanAndDestroy(textToFileblob(t_line, fb, 1)) == CL_VIRUS) + if (fileblobScanAndDestroy(textToFileblob(t_line, fb, 1)) == CL_VIRUS) { rc = VIRUS; + } mctx->files++; } saveIt = false; - } else + } else { /* * Save the entire text portion, * since it may be an HTML file with * a JavaScript virus or a phish */ saveIt = true; + } if (saveIt) { cli_dbgmsg("Saving text part to scan, rc = %d\n", (int)rc); - if (saveTextPart(mctx, mainMessage, 1) == CL_VIRUS) + if (saveTextPart(mctx, mainMessage, 1) == CL_VIRUS) { rc = VIRUS; + } if (mainMessage != messageIn) { messageDestroy(mainMessage); mainMessage = NULL; - } else + } else { messageReset(mainMessage); + } } } } /*else rc = OK_ATTACHMENTS_NOT_SAVED; */ /* nothing saved */ - if (mainMessage && (mainMessage != messageIn)) + if (mainMessage && (mainMessage != messageIn)) { messageDestroy(mainMessage); + } - if ((rc != FAIL) && infected) + if ((rc != FAIL) && infected) { rc = VIRUS; + } mctx->wrkobj = saveobj; @@ -2769,54 +2858,65 @@ boundaryStart(const char *line, const char *boundary) char buf[RFC2821LENGTH + 1]; char *newline; - if (line == NULL || *line == '\0') + if (line == NULL || *line == '\0') { return 0; /* empty line */ - if (boundary == NULL) + } + if (boundary == NULL) { return 0; + } newline = strdup(line); - if (!(newline)) + if (!(newline)) { newline = (char *)line; + } if (newline != line && strlen(line)) { char *p; /* Trim trailing spaces */ p = newline + strlen(line) - 1; - while (p >= newline && *p == ' ') + while (p >= newline && *p == ' ') { *(p--) = '\0'; + } } - if (newline != line) + if (newline != line) { cli_chomp(newline); + } /* cli_dbgmsg("boundaryStart: line = '%s' boundary = '%s'\n", line, boundary); */ if ((*newline != '-') && (*newline != '(')) { - if (newline != line) + if (newline != line) { free(newline); + } return 0; } if (strchr(newline, '-') == NULL) { - if (newline != line) + if (newline != line) { free(newline); + } return 0; } if (strlen(newline) <= sizeof(buf)) { out = NULL; ptr = rfc822comments(newline, buf); - } else + } else { ptr = out = rfc822comments(newline, NULL); + } - if (ptr == NULL) + if (ptr == NULL) { ptr = newline; + } if ((*ptr++ != '-') || (*ptr == '\0')) { - if (out) + if (out) { free(out); - if (newline != line) + } + if (newline != line) { free(newline); + } return 0; } @@ -2850,34 +2950,38 @@ boundaryStart(const char *line, const char *boundary) * false positive problem mentioned above */ rc = 0; - do + do { if (strcmp(++k, boundary) == 0) { rc = 1; break; } - while (*k == '-'); + } while (*k == '-'); if (rc == 0) { k = &line[1]; - do + do { if (strcmp(++k, boundary) == 0) { rc = 1; break; } - while (*k == '-'); + } while (*k == '-'); } - } else if (*ptr++ != '-') + } else if (*ptr++ != '-') { rc = 0; - else + } else { rc = (strcasecmp(ptr, boundary) == 0); + } - if (out) + if (out) { free(out); + } - if (rc == 1) + if (rc == 1) { cli_dbgmsg("boundaryStart: found %s in %s\n", boundary, line); + } - if (newline != line) + if (newline != line) { free(newline); + } return rc; } @@ -2893,8 +2997,9 @@ boundaryEnd(const char *line, const char *boundary) size_t len; char *newline, *p, *p2; - if (line == NULL || *line == '\0') + if (line == NULL || *line == '\0') { return 0; + } p = newline = strdup(line); if (!(newline)) { @@ -2905,29 +3010,33 @@ boundaryEnd(const char *line, const char *boundary) if (newline != line && strlen(line)) { /* Trim trailing spaces */ p2 = newline + strlen(line) - 1; - while (p2 >= newline && *p2 == ' ') + while (p2 >= newline && *p2 == ' ') { *(p2--) = '\0'; + } } /* cli_dbgmsg("boundaryEnd: line = '%s' boundary = '%s'\n", newline, boundary); */ if (*p++ != '-') { - if (newline != line) + if (newline != line) { free(newline); + } return 0; } if (*p++ != '-') { - if (newline != line) + if (newline != line) { free(newline); + } return 0; } len = strlen(boundary); if (strncasecmp(p, boundary, len) != 0) { - if (newline != line) + if (newline != line) { free(newline); + } return 0; } @@ -2936,30 +3045,34 @@ boundaryEnd(const char *line, const char *boundary) * space after the boundary */ if (strlen(p) < (len + 2)) { - if (newline != line) + if (newline != line) { free(newline); + } return 0; } p = &p[len]; if (*p++ != '-') { - if (newline != line) + if (newline != line) { free(newline); + } return 0; } if (*p == '-') { /* cli_dbgmsg("boundaryEnd: found %s in %s\n", boundary, p); */ - if (newline != line) + if (newline != line) { free(newline); + } return 1; } - if (newline != line) + if (newline != line) { free(newline); + } return 0; } @@ -3027,12 +3140,14 @@ getTextPart(message *const messages[], size_t size) size_t i; int textpart = -1; - for (i = 0; i < size; i++) + for (i = 0; i < size; i++) { if (messages[i] && (messageGetMimeType(messages[i]) == TEXT)) { - if (strcasecmp(messageGetMimeSubtype(messages[i]), "html") == 0) + if (strcasecmp(messageGetMimeSubtype(messages[i]), "html") == 0) { return (int)i; + } textpart = (int)i; } + } return textpart; } @@ -3057,19 +3172,22 @@ strip(char *buf, int len) register char *ptr; register size_t i; - if ((buf == NULL) || (len <= 0)) + if ((buf == NULL) || (len <= 0)) { return 0; + } i = strlen(buf); - if (len > (int)(i + 1)) + if (len > (int)(i + 1)) { return i; + } ptr = &buf[--len]; #if defined(UNIX) || defined(C_LINUX) || defined(C_DARWIN) /* watch - it may be in shared text area */ - do - if (*ptr) + do { + if (*ptr) { *ptr = '\0'; - while ((--len >= 0) && (!isgraph(*--ptr)) && (*ptr != '\n') && (*ptr != '\r')); + } + } while ((--len >= 0) && (!isgraph(*--ptr)) && (*ptr != '\n') && (*ptr != '\r')); #else /* more characters can be displayed on DOS */ do #ifndef REAL_MODE_DOS @@ -3088,8 +3206,9 @@ strip(char *buf, int len) size_t strstrip(char *s) { - if (s == (char *)NULL) + if (s == (char *)NULL) { return (0); + } return (strip(s, strlen(s) + 1)); } @@ -3135,7 +3254,7 @@ parseMimeHeader(message *m, const char *cmd, const table_t *rfc821Table, const c * of content-type: Text/Plain, or * just simply "Content-Type:" */ - if (arg == NULL) + if (arg == NULL) { /* * According to section 4 of RFC1521: * "Note also that a subtype specification is @@ -3146,7 +3265,7 @@ parseMimeHeader(message *m, const char *cmd, const table_t *rfc821Table, const c * email client writers don't get it right */ cli_dbgmsg("Empty content-type received, no subtype specified, assuming text/plain; charset=us-ascii\n"); - else if (strchr(ptr, '/') == NULL) + } else if (strchr(ptr, '/') == NULL) { /* * Empty field, such as * Content-Type: @@ -3154,14 +3273,15 @@ parseMimeHeader(message *m, const char *cmd, const table_t *rfc821Table, const c * RFC1521 */ cli_dbgmsg("Invalid content-type '%s' received, no subtype specified, assuming text/plain; charset=us-ascii\n", ptr); - else { + } else { int i; buf = cli_max_malloc(strlen(ptr) + 1); if (buf == NULL) { cli_errmsg("parseMimeHeader: Unable to allocate memory for buf %llu\n", (long long unsigned)(strlen(ptr) + 1)); - if (copy) + if (copy) { free(copy); + } return -1; } /* @@ -3180,10 +3300,12 @@ parseMimeHeader(message *m, const char *cmd, const table_t *rfc821Table, const c * the quotes, it doesn't handle * them properly */ - while (isspace((const unsigned char)*ptr)) + while (isspace((const unsigned char)*ptr)) { ptr++; - if (ptr[0] == '\"') + } + if (ptr[0] == '\"') { ptr++; + } if (ptr[0] != '/') { char *s; @@ -3202,8 +3324,9 @@ parseMimeHeader(message *m, const char *cmd, const table_t *rfc821Table, const c char *buf2 = cli_safer_strdup(buf); if (buf2 == NULL) { - if (copy) + if (copy) { free(copy); + } free(buf); return -1; } @@ -3219,8 +3342,9 @@ parseMimeHeader(message *m, const char *cmd, const table_t *rfc821Table, const c #else s = strtok(NULL, ";"); #endif - if (s == NULL) + if (s == NULL) { break; + } if (set) { size_t len = strstrip(s) - 1; if (s[len] == '\"') { @@ -3228,20 +3352,24 @@ parseMimeHeader(message *m, const char *cmd, const table_t *rfc821Table, const c len = strstrip(s); } if (len) { - if (strchr(s, ' ')) + if (strchr(s, ' ')) { messageSetMimeSubtype(m, cli_strtokbuf(s, 0, " ", buf2)); - else + } else { messageSetMimeSubtype(m, s); + } } } - while (*s && !isspace((unsigned char)*s)) + while (*s && !isspace((unsigned char)*s)) { s++; - if (*s++ == '\0') + } + if (*s++ == '\0') { break; - if (*s == '\0') + } + if (*s == '\0') { break; + } } free(buf2); } @@ -3273,8 +3401,9 @@ parseMimeHeader(message *m, const char *cmd, const table_t *rfc821Table, const c buf = cli_max_malloc(strlen(ptr) + 1); if (buf == NULL) { cli_errmsg("parseMimeHeader: Unable to allocate memory for buf %llu\n", (long long unsigned)(strlen(ptr) + 1)); - if (copy) + if (copy) { free(copy); + } return -1; } p = cli_strtokbuf(ptr, 0, ";", buf); @@ -3282,7 +3411,7 @@ parseMimeHeader(message *m, const char *cmd, const table_t *rfc821Table, const c messageSetDispositionType(m, p); messageAddArgument(m, cli_strtokbuf(ptr, 1, ";", buf)); } - if (!messageHasFilename(m)) + if (!messageHasFilename(m)) { /* * Handle this type of header, without * a filename (e.g. some Worm.Torvil.D) @@ -3291,11 +3420,14 @@ parseMimeHeader(message *m, const char *cmd, const table_t *rfc821Table, const c * Content-Disposition: attachment */ messageAddArgument(m, "filename=unknown"); + } } - if (copy) + if (copy) { free(copy); - if (buf) + } + if (buf) { free(buf); + } return 0; } @@ -3362,12 +3494,13 @@ rfc822comments(const char *in, char *out) cli_dbgmsg("rfc822comments: contains a comment\n"); - for (iptr = in; *iptr; iptr++) + for (iptr = in; *iptr; iptr++) { if (backslash) { - if (commentlevel == 0) + if (commentlevel == 0) { *optr++ = *iptr; + } backslash = 0; - } else + } else { switch (*iptr) { case '\\': backslash = 1; @@ -3377,24 +3510,30 @@ rfc822comments(const char *in, char *out) inquote = !inquote; break; case '(': - if (inquote) + if (inquote) { *optr++ = '('; - else + } else { commentlevel++; + } break; case ')': - if (inquote) + if (inquote) { *optr++ = ')'; - else if (commentlevel > 0) + } else if (commentlevel > 0) { commentlevel--; + } break; default: - if (commentlevel == 0) + if (commentlevel == 0) { *optr++ = *iptr; + } } + } + } - if (backslash) /* last character was a single backslash */ + if (backslash) { /* last character was a single backslash */ *optr++ = '\\'; + } *optr = '\0'; /*strstrip(out);*/ @@ -3414,8 +3553,9 @@ rfc2047(const char *in) char *out, *pout; size_t len; - if ((strstr(in, "=?") == NULL) || (strstr(in, "?=") == NULL)) + if ((strstr(in, "=?") == NULL) || (strstr(in, "?=") == NULL)) { return cli_safer_strdup(in); + } cli_dbgmsg("rfc2047 '%s'\n", in); out = cli_max_malloc(strlen(in) + 1); @@ -3442,10 +3582,12 @@ rfc2047(const char *in) *pout++ = *in++; } /* Skip over charset, find encoding */ - while ((*in != '?') && *in) + while ((*in != '?') && *in) { in++; - if (*in == '\0') + } + if (*in == '\0') { break; + } encoding = *++in; encoding = (char)tolower(encoding); @@ -3456,10 +3598,12 @@ rfc2047(const char *in) break; } /* Skip to encoded text */ - if (*++in != '?') + if (*++in != '?') { break; - if (*++in == '\0') + } + if (*++in == '\0') { break; + } enctext = cli_safer_strdup(in); if (enctext == NULL) { @@ -3510,13 +3654,15 @@ rfc2047(const char *in) memcpy(pout, blobGetData(b), len); blobDestroy(b); messageDestroy(m); - if (len > 0 && pout[len - 1] == '\n') + if (len > 0 && pout[len - 1] == '\n') { pout += len - 1; - else + } else { pout += len; + } } - if (out == NULL) + if (out == NULL) { return NULL; + } *pout = '\0'; @@ -3570,7 +3716,7 @@ rfc1341(mbox_ctx *mctx, message *m) free(id); return -1; } - if (statb.st_mode & 077) + if (statb.st_mode & 077) { cli_warnmsg("Insecure partial directory %s (mode 0%o)\n", pdir, #ifdef ACCESSPERMS @@ -3579,6 +3725,7 @@ rfc1341(mbox_ctx *mctx, message *m) (int)(statb.st_mode & 0777) #endif ); + } } number = (char *)messageFindArgument(m, "number"); @@ -3665,23 +3812,27 @@ rfc1341(mbox_ctx *mctx, message *m) const char *dentry_idpart; int test_fd; - if (dent->d_ino == 0) + if (dent->d_ino == 0) { continue; + } if (!strcmp(".", dent->d_name) || - !strcmp("..", dent->d_name)) + !strcmp("..", dent->d_name)) { continue; + } snprintf(fullname, sizeof(fullname) - 1, "%s" PATHSEP "%s", pdir, dent->d_name); dentry_idpart = strchr(dent->d_name, '_'); if (!dentry_idpart || strcmp(filename, dentry_idpart) != 0) { - if (!m->ctx->engine->keeptmp) + if (!m->ctx->engine->keeptmp) { continue; + } - if ((test_fd = open(fullname, O_RDONLY | O_BINARY)) < 0) + if ((test_fd = open(fullname, O_RDONLY | O_BINARY)) < 0) { continue; + } if (FSTAT(test_fd, &statb) < 0) { close(test_fd); @@ -3717,18 +3868,21 @@ rfc1341(mbox_ctx *mctx, message *m) return -1; } nblanks = 0; - while (fgets(buffer, sizeof(buffer) - 1, fin) != NULL) + while (fgets(buffer, sizeof(buffer) - 1, fin) != NULL) { /* * Ensure that trailing newlines * aren't copied */ - if (buffer[0] == '\n') + if (buffer[0] == '\n') { nblanks++; - else { - if (nblanks) + } else { + if (nblanks) { do { - if (putc('\n', fout) == EOF) break; + if (putc('\n', fout) == EOF) { + break; + } } while (--nblanks > 0); + } if (nblanks || fputs(buffer, fout) == EOF) { fclose(fin); fclose(fout); @@ -3740,6 +3894,7 @@ rfc1341(mbox_ctx *mctx, message *m) return -1; } } + } fclose(fin); /* don't unlink if leave temps */ @@ -3772,8 +3927,9 @@ rfc1341(mbox_ctx *mctx, message *m) static void hrefs_done(blob *b, tag_arguments_t *hrefs) { - if (b) + if (b) { blobDestroy(b); + } html_tag_arg_free(hrefs); } @@ -3796,8 +3952,9 @@ static void extract_text_urls(const unsigned char *mem, size_t len, tag_argument unsigned char c = mem[off + url_len]; /* smart compilers will compile this if into * a single bt + jb instruction */ - if (c == ' ' || c == '\n' || c == '\t') + if (c == ' ' || c == '\n' || c == '\t') { break; + } } memcpy(url, mem + off, url_len); url[url_len] = '\0'; @@ -3819,8 +3976,9 @@ getHrefs(cli_ctx *ctx, message *m, tag_arguments_t *hrefs) blob *b = messageToBlob(m, 0); size_t len; - if (b == NULL) + if (b == NULL) { return NULL; + } len = blobGetDataSize(b); @@ -3867,17 +4025,19 @@ checkURLs(message *mainMessage, mbox_ctx *mctx, mbox_status *rc, int is_html) UNUSEDPARAM(is_html); - if (*rc == VIRUS) + if (*rc == VIRUS) { return; + } hrefs.scanContents = mctx->ctx->engine->dboptions & CL_DB_PHISHING_URLS && (DCONF_PHISHING & PHISHING_CONF_ENGINE); - if (!hrefs.scanContents) + if (!hrefs.scanContents) { /* * Don't waste time extracting hrefs (parsing html), nobody * will need it */ return; + } hrefs.count = 0; hrefs.tag = hrefs.value = NULL; @@ -3953,12 +4113,15 @@ usefulHeader(int commandNumber, const char *cmd) case CONTENT_TYPE: return true; default: - if (strcasecmp(cmd, "From") == 0) + if (strcasecmp(cmd, "From") == 0) { return true; - if (strcasecmp(cmd, "Received") == 0) + } + if (strcasecmp(cmd, "Received") == 0) { return true; - if (strcasecmp(cmd, "De") == 0) + } + if (strcasecmp(cmd, "De") == 0) { return true; + } } return false; @@ -4038,18 +4201,21 @@ isBounceStart(mbox_ctx *mctx, const char *line) { size_t len; - if (line == NULL) + if (line == NULL) { return false; - if (*line == '\0') + } + if (*line == '\0') { return false; + } /*if((strncmp(line, "From ", 5) == 0) && !isalnum(line[5])) return false; if((strncmp(line, ">From ", 6) == 0) && !isalnum(line[6])) return false;*/ len = strlen(line); - if ((len < 6) || (len >= 72)) + if ((len < 6) || (len >= 72)) { return false; + } if ((memcmp(line, "From ", 5) == 0) || (memcmp(line, ">From ", 6) == 0)) { @@ -4057,17 +4223,20 @@ isBounceStart(mbox_ctx *mctx, const char *line) line += 4; - do - if (*line == ' ') + do { + if (*line == ' ') { numSpaces++; - else if (isdigit((*line) & 0xFF)) + } else if (isdigit((*line) & 0xFF)) { numDigits++; - while (*++line != '\0'); + } + } while (*++line != '\0'); - if (numSpaces < 6) + if (numSpaces < 6) { return false; - if (numDigits < 11) + } + if (numDigits < 11) { return false; + } return true; } return (bool)(cli_compare_ftm_file((const unsigned char *)line, len, mctx->ctx->engine) == CL_TYPE_MAIL); @@ -4083,8 +4252,9 @@ exportBinhexMessage(mbox_ctx *mctx, message *m) bool infected = false; fileblob *fb; - if (messageGetEncoding(m) == NOENCODING) + if (messageGetEncoding(m) == NOENCODING) { messageSetEncoding(m, "x-binhex"); + } fb = messageToFileblob(m, mctx->dir, 0); @@ -4092,11 +4262,13 @@ exportBinhexMessage(mbox_ctx *mctx, message *m) cli_dbgmsg("Binhex file decoded to %s\n", fileblobGetFilename(fb)); - if (fileblobScanAndDestroy(fb) == CL_VIRUS) + if (fileblobScanAndDestroy(fb) == CL_VIRUS) { infected = true; + } mctx->files++; - } else + } else { cli_errmsg("Couldn't decode binhex file to %s\n", mctx->dir); + } return infected; } @@ -4134,28 +4306,33 @@ exportBounceMessage(mbox_ctx *mctx, text *start) const char *txt = lineGetData(t->t_line); char cmd[RFC2821LENGTH + 1]; - if (txt == NULL) + if (txt == NULL) { continue; - if (cli_strtokbuf(txt, 0, ":", cmd) == NULL) + } + if (cli_strtokbuf(txt, 0, ":", cmd) == NULL) { continue; + } switch (tableFind(mctx->rfc821Table, cmd)) { case CONTENT_TRANSFER_ENCODING: if ((strstr(txt, "7bit") == NULL) && - (strstr(txt, "8bit") == NULL)) + (strstr(txt, "8bit") == NULL)) { break; + } continue; case CONTENT_DISPOSITION: break; case CONTENT_TYPE: - if (strstr(txt, "text/plain") != NULL) + if (strstr(txt, "text/plain") != NULL) { t = NULL; + } break; default: - if (strcasecmp(cmd, "From") == 0) + if (strcasecmp(cmd, "From") == 0) { start = t; - else if (strcasecmp(cmd, "Received") == 0) + } else if (strcasecmp(cmd, "Received") == 0) { start = t; + } continue; } break; @@ -4167,11 +4344,13 @@ exportBounceMessage(mbox_ctx *mctx, text *start) if (textToFileblob(start, fb, 1) == NULL) { cli_dbgmsg("Nothing new to save in the bounce message\n"); fileblobDestroy(fb); - } else + } else { rc = fileblobScanAndDestroy(fb); + } mctx->files++; - } else + } else { cli_dbgmsg("Not found a bounce message\n"); + } return rc; } @@ -4236,13 +4415,15 @@ do_multipart(message *mainMessage, message **messages, int i, mbox_status *rc, m } if (aMessage == NULL) { - if (thisobj != NULL) + if (thisobj != NULL) { cli_jsonstr(thisobj, "MimeType", "NULL"); + } return mainMessage; } - if (*rc != OK) + if (*rc != OK) { return mainMessage; + } cli_dbgmsg("Mixed message part %d is of type %d\n", i, messageGetMimeType(aMessage)); @@ -4273,38 +4454,44 @@ do_multipart(message *mainMessage, message **messages, int i, mbox_status *rc, m if (binhexBegin(aMessage)) { cli_dbgmsg("Found binhex message in multipart/mixed mainMessage\n"); - if (exportBinhexMessage(mctx, mainMessage)) + if (exportBinhexMessage(mctx, mainMessage)) { *rc = VIRUS; + } } - if (mainMessage != messageIn) + if (mainMessage != messageIn) { messageDestroy(mainMessage); + } mainMessage = NULL; } else if (aMessage) { if (binhexBegin(aMessage)) { cli_dbgmsg("Found binhex message in multipart/mixed non mime part\n"); - if (exportBinhexMessage(mctx, aMessage)) + if (exportBinhexMessage(mctx, aMessage)) { *rc = VIRUS; + } messageReset(messages[i]); } } addToText = true; - if (messageGetBody(aMessage) == NULL) + if (messageGetBody(aMessage) == NULL) { /* * No plain text version */ cli_dbgmsg("No plain text alternative\n"); + } break; case TEXT: dtype = messageGetDispositionType(aMessage); cli_dbgmsg("Mixed message text part disposition \"%s\"\n", dtype); - if (strcasecmp(dtype, "attachment") == 0) + if (strcasecmp(dtype, "attachment") == 0) { break; + } if ((*dtype == '\0') || (strcasecmp(dtype, "inline") == 0)) { const char *cptr; - if (mainMessage && (mainMessage != messageIn)) + if (mainMessage && (mainMessage != messageIn)) { messageDestroy(mainMessage); + } mainMessage = NULL; cptr = messageGetMimeSubtype(aMessage); cli_dbgmsg("Mime subtype \"%s\"\n", cptr); @@ -4318,12 +4505,14 @@ do_multipart(message *mainMessage, message **messages, int i, mbox_status *rc, m if (!messageHasFilename(aMessage)) { cli_dbgmsg("Adding part to main message\n"); addToText = true; - } else + } else { cli_dbgmsg("Treating inline as attachment\n"); + } } else { const int is_html = (tableFind(mctx->subtypeTable, cptr) == HTML); - if (doPhishingScan) + if (doPhishingScan) { checkURLs(aMessage, mctx, rc, is_html); + } messageAddArgument(aMessage, "filename=mixedtextportion"); } @@ -4367,8 +4556,9 @@ do_multipart(message *mainMessage, message **messages, int i, mbox_status *rc, m * Save this embedded message * to a temporary file */ - if (saveTextPart(mctx, aMessage, 1) == CL_VIRUS) + if (saveTextPart(mctx, aMessage, 1) == CL_VIRUS) { *rc = VIRUS; + } messageDestroy(messages[i]); messages[i] = NULL; #else @@ -4502,9 +4692,11 @@ count_quotes(const char *buf) { int quotes = 0; - while (*buf) - if (*buf++ == '\"') + while (*buf) { + if (*buf++ == '\"') { quotes++; + } + } return quotes; } @@ -4518,11 +4710,13 @@ next_is_folded_header(const text *t) const text *next = t->t_next; const char *data, *ptr; - if (next == NULL) + if (next == NULL) { return false; + } - if (next->t_line == NULL) + if (next->t_line == NULL) { return false; + } data = lineGetData(next->t_line); @@ -4530,16 +4724,18 @@ next_is_folded_header(const text *t) * Section B.2 of RFC822 says TAB or SPACE means a continuation of the * previous entry. */ - if (isblank(data[0])) + if (isblank(data[0])) { return true; + } - if (strchr(data, '=') == NULL) + if (strchr(data, '=') == NULL) { /* * Avoid false positives with * Content-Type: text/html; * Content-Transfer-Encoding: quoted-printable */ return false; + } /* * Some are broken and don't fold headers lines @@ -4560,7 +4756,7 @@ next_is_folded_header(const text *t) ptr = strchr(data, '\0'); - while (--ptr > data) + while (--ptr > data) { switch (*ptr) { case ';': return true; @@ -4572,6 +4768,7 @@ next_is_folded_header(const text *t) default: return false; } + } return false; } @@ -4585,10 +4782,12 @@ newline_in_header(const char *line) { cli_dbgmsg("newline_in_header, check \"%s\"\n", line); - if (strncmp(line, "Message-Id: ", 12) == 0) + if (strncmp(line, "Message-Id: ", 12) == 0) { return true; - if (strncmp(line, "Date: ", 6) == 0) + } + if (strncmp(line, "Date: ", 6) == 0) { return true; + } cli_dbgmsg("newline_in_header, returning \"%s\"\n", line); diff --git a/libclamav/mbr.c b/libclamav/mbr.c index 4457f9ec6c..0512ba9611 100644 --- a/libclamav/mbr.c +++ b/libclamav/mbr.c @@ -81,8 +81,9 @@ cl_error_t cli_mbr_check(const unsigned char *buff, size_t len, size_t maplen) memcpy(&mbr, buff + mbr_base, sizeof(mbr)); mbr_convert_to_host(&mbr); - if ((mbr.entries[0].type == MBR_PROTECTIVE) || (mbr.entries[0].type == MBR_HYBRID)) + if ((mbr.entries[0].type == MBR_PROTECTIVE) || (mbr.entries[0].type == MBR_HYBRID)) { return CL_TYPE_GPT; + } return mbr_check_mbr(&mbr, maplen, sectorsize); } @@ -99,8 +100,9 @@ cl_error_t cli_mbr_check2(cli_ctx *ctx, size_t sectorsize) } /* sector size calculation, actual value is OS dependent */ - if (sectorsize == 0) + if (sectorsize == 0) { sectorsize = MBR_SECTOR_SIZE; + } mbr_base = sectorsize - sizeof(struct mbr_boot_record); @@ -124,8 +126,9 @@ cl_error_t cli_mbr_check2(cli_ctx *ctx, size_t sectorsize) /* convert the little endian to host, include the internal */ mbr_convert_to_host(&mbr); - if ((mbr.entries[0].type == MBR_PROTECTIVE) || (mbr.entries[0].type == MBR_HYBRID)) + if ((mbr.entries[0].type == MBR_PROTECTIVE) || (mbr.entries[0].type == MBR_HYBRID)) { return CL_TYPE_GPT; + } return mbr_check_mbr(&mbr, maplen, sectorsize); } @@ -149,8 +152,9 @@ cl_error_t cli_scanmbr(cli_ctx *ctx, size_t sectorsize) } /* sector size calculation, actual value is OS dependent */ - if (sectorsize == 0) + if (sectorsize == 0) { sectorsize = MBR_SECTOR_SIZE; + } mbr_base = sectorsize - sizeof(struct mbr_boot_record); diff --git a/libclamav/message.c b/libclamav/message.c index 563ac2e242..efb96a585f 100644 --- a/libclamav/message.c +++ b/libclamav/message.c @@ -142,8 +142,9 @@ messageCreate(void) { message *m = (message *)calloc(1, sizeof(message)); - if (m) + if (m) { m->mimeType = NOMIME; + } return m; } @@ -167,20 +168,24 @@ void messageReset(message *m) return; } - if (m->mimeSubtype) + if (m->mimeSubtype) { free(m->mimeSubtype); + } - if (m->mimeDispositionType) + if (m->mimeDispositionType) { free(m->mimeDispositionType); + } if (m->mimeArguments) { - for (i = 0; i < m->numberOfArguments; i++) + for (i = 0; i < m->numberOfArguments; i++) { free(m->mimeArguments[i]); + } free(m->mimeArguments); } - if (m->body_first) + if (m->body_first) { textDestroy(m->body_first); + } if (0 != m->base64chars) { cli_errmsg("Internal email parse error: message base64chars should be 0 when resetting the message\n"); @@ -226,9 +231,11 @@ int messageSetMimeType(message *mess, const char *type) cli_dbgmsg("messageSetMimeType: '%s'\n", type); /* Ignore leading spaces */ - while (!isalpha(*type)) - if (*type++ == '\0') + while (!isalpha(*type)) { + if (*type++ == '\0') { return 0; + } + } #ifdef CL_THREAD_SAFE pthread_mutex_lock(&mime_mutex); @@ -242,7 +249,7 @@ int messageSetMimeType(message *mess, const char *type) return 0; } - for (m = mime_map; m->string; m++) + for (m = mime_map; m->string; m++) { if (!tableInsert(mime_table, m->string, m->type)) { tableDestroy(mime_table); mime_table = NULL; @@ -251,6 +258,7 @@ int messageSetMimeType(message *mess, const char *type) #endif return 0; } + } } #ifdef CL_THREAD_SAFE pthread_mutex_unlock(&mime_mutex); @@ -263,9 +271,9 @@ int messageSetMimeType(message *mess, const char *type) return 1; } if (mess->mimeType == NOMIME) { - if (strncasecmp(type, "x-", 2) == 0) + if (strncasecmp(type, "x-", 2) == 0) { mess->mimeType = MEXTENSION; - else { + } else { /* * Force scanning of strange messages */ @@ -335,8 +343,9 @@ void messageSetMimeSubtype(message *m, const char *subtype) subtype = ""; } - if (m->mimeSubtype) + if (m->mimeSubtype) { free(m->mimeSubtype); + } m->mimeSubtype = cli_safer_strdup(subtype); } @@ -354,8 +363,9 @@ void messageSetDispositionType(message *m, const char *disptype) return; } - if (m->mimeDispositionType) + if (m->mimeDispositionType) { free(m->mimeDispositionType); + } if (disptype == NULL) { m->mimeDispositionType = NULL; return; @@ -367,14 +377,17 @@ void messageSetDispositionType(message *m, const char *disptype) * that something is wrong if we get that - maybe we should force a * scan of this part */ - while (*disptype && isspace((int)*disptype)) + while (*disptype && isspace((int)*disptype)) { disptype++; + } if (*disptype) { m->mimeDispositionType = cli_safer_strdup(disptype); - if (m->mimeDispositionType) + if (m->mimeDispositionType) { strstrip(m->mimeDispositionType); - } else + } + } else { m->mimeDispositionType = NULL; + } } const char * @@ -400,26 +413,32 @@ void messageAddArgument(message *m, const char *arg) return; } - if (arg == NULL) + if (arg == NULL) { return; /* Note: this is not an error condition */ + } - while (isspace(*arg)) + while (isspace(*arg)) { arg++; + } - if (*arg == '\0') + if (*arg == '\0') { /* Empty argument? Probably a broken mail client... */ return; + } cli_dbgmsg("messageAddArgument, arg='%s'\n", arg); - if (!usefulArg(arg)) + if (!usefulArg(arg)) { return; + } - for (offset = 0; offset < m->numberOfArguments; offset++) - if (m->mimeArguments[offset] == NULL) + for (offset = 0; offset < m->numberOfArguments; offset++) { + if (m->mimeArguments[offset] == NULL) { break; - else if (strcasecmp(arg, m->mimeArguments[offset]) == 0) + } else if (strcasecmp(arg, m->mimeArguments[offset]) == 0) { return; /* already in there */ + } + } if (offset == m->numberOfArguments) { char **q; @@ -453,8 +472,9 @@ void messageAddArgument(message *m, const char *arg) cli_dbgmsg("Possible data corruption not fixed\n"); } } else { - if (*p) + if (*p) { cli_dbgmsg("messageAddArgument, '%s' contains no '='\n", p); + } free(m->mimeArguments[offset]); m->mimeArguments[offset] = NULL; return; @@ -467,11 +487,12 @@ void messageAddArgument(message *m, const char *arg) * mime. By pretending defaulting to an application rather than * to nomime we can ensure they're saved and scanned */ - if ((strncasecmp(p, "filename=", 9) == 0) || (strncasecmp(p, "name=", 5) == 0)) + if ((strncasecmp(p, "filename=", 9) == 0) || (strncasecmp(p, "name=", 5) == 0)) { if (messageGetMimeType(m) == NOMIME) { cli_dbgmsg("Force mime encoding to application\n"); messageSetMimeType(m, "application"); } + } } /* @@ -516,8 +537,9 @@ void messageAddArguments(message *m, const char *s) * we don't have ESP and don't know what was meant to be there. * It's unlikely to really be a problem. */ - if (data == NULL) + if (data == NULL) { data = strchr(string, ':'); + } if (data == NULL) { /* @@ -538,13 +560,15 @@ void messageAddArguments(message *m, const char *s) * or tspecials> * But too many MUAs ignore this */ - while (isspace(*string) && (*string != '\0')) + while (isspace(*string) && (*string != '\0')) { string++; + } cptr = string; - if (*string) + if (*string) { string++; + } if (*cptr == '"') { char *ptr, *kcopy; @@ -555,8 +579,9 @@ void messageAddArguments(message *m, const char *s) */ kcopy = cli_safer_strdup(key); - if (kcopy == NULL) + if (kcopy == NULL) { return; + } ptr = strchr(kcopy, '='); if (ptr == NULL) { @@ -575,8 +600,9 @@ void messageAddArguments(message *m, const char *s) if (string == NULL) { cli_dbgmsg("Unbalanced quote character in \"%s\"\n", s); string = ""; - } else + } else { string++; + } if (!usefulArg(kcopy)) { free(kcopy); @@ -604,8 +630,9 @@ void messageAddArguments(message *m, const char *s) * * Use the end of line as data. */ - } else + } else { *ptr = '\0'; + } datasz = strlen(kcopy) + strlen(data) + 2; field = cli_max_realloc(kcopy, strlen(kcopy) + strlen(data) + 2); @@ -628,8 +655,9 @@ void messageAddArguments(message *m, const char *s) * The field is not in quotes, so look for the closing * white space */ - while ((*string != '\0') && !isspace(*string)) + while ((*string != '\0') && !isspace(*string)) { string++; + } len = (size_t)string - (size_t)key + 1; field = cli_max_malloc(len); @@ -682,16 +710,18 @@ messageFindArgument(const message *m, const char *variable) const char *ptr; ptr = messageGetArgument(m, i); - if ((ptr == NULL) || (*ptr == '\0')) + if ((ptr == NULL) || (*ptr == '\0')) { continue; + } #ifdef CL_DEBUG cli_dbgmsg("messageFindArgument: compare %lu bytes of %s with %s\n", (unsigned long)len, variable, ptr); #endif if (strncasecmp(ptr, variable, len) == 0) { ptr = &ptr[len]; - while (isspace(*ptr)) + while (isspace(*ptr)) { ptr++; + } if (*ptr != '=') { cli_dbgmsg("messageFindArgument: no '=' sign found in MIME header '%s' (%s)\n", variable, messageGetArgument(m, i)); return NULL; @@ -702,8 +732,9 @@ messageFindArgument(const message *m, const char *variable) char *ret = cli_safer_strdup(++ptr); char *p; - if (ret == NULL) + if (ret == NULL) { return NULL; + } /* * fix un-quoting of boundary strings from @@ -731,8 +762,9 @@ messageGetFilename(const message *m) { char *filename = (char *)messageFindArgument(m, "filename"); - if (filename) + if (filename) { return filename; + } return (char *)messageFindArgument(m, "name"); } @@ -755,16 +787,18 @@ messageHasArgument(const message *m, const char *variable) const char *ptr; ptr = messageGetArgument(m, i); - if ((ptr == NULL) || (*ptr == '\0')) + if ((ptr == NULL) || (*ptr == '\0')) { continue; + } #ifdef CL_DEBUG cli_dbgmsg("messageHasArgument: compare %lu bytes of %s with %s\n", (unsigned long)len, variable, ptr); #endif if (strncasecmp(ptr, variable, len) == 0) { ptr = &ptr[len]; - while (isspace(*ptr)) + while (isspace(*ptr)) { ptr++; + } if (*ptr != '=') { cli_dbgmsg("messageHasArgument: no '=' sign found in MIME header '%s' (%s)\n", variable, messageGetArgument(m, i)); return 0; @@ -793,8 +827,9 @@ void messageSetEncoding(message *m, const char *enctype) /*m->encodingType = EEXTENSION;*/ - while (isblank(*enctype)) + while (isblank(*enctype)) { enctype++; + } cli_dbgmsg("messageSetEncoding: '%s'\n", enctype); @@ -817,7 +852,7 @@ void messageSetEncoding(message *m, const char *enctype) int sim; const char lowertype = tolower(type[0]); - if ((lowertype != tolower(e->string[0])) && (lowertype != 'x')) + if ((lowertype != tolower(e->string[0])) && (lowertype != 'x')) { /* * simil is expensive, I'm yet to encounter only * one example of a missent encoding when the @@ -828,13 +863,15 @@ void messageSetEncoding(message *m, const char *enctype) * X-quoted-printable. */ continue; + } - if (strcmp(e->string, "uuencode") == 0) + if (strcmp(e->string, "uuencode") == 0) { /* * No need to test here - fast track visa will have * handled uuencoded files */ continue; + } sim = simil(type, e->string); @@ -842,9 +879,11 @@ void messageSetEncoding(message *m, const char *enctype) int j; encoding_type *et; - for (j = 0; j < m->numberOfEncTypes; j++) - if (m->encodingTypes[j] == e->type) + for (j = 0; j < m->numberOfEncTypes; j++) { + if (m->encodingTypes[j] == e->type) { break; + } + } if (j < m->numberOfEncTypes) { cli_dbgmsg("Ignoring duplicate encoding mechanism '%s'\n", @@ -853,8 +892,9 @@ void messageSetEncoding(message *m, const char *enctype) } et = (encoding_type *)cli_max_realloc(m->encodingTypes, (m->numberOfEncTypes + 1) * sizeof(encoding_type)); - if (et == NULL) + if (et == NULL) { break; + } m->encodingTypes = et; m->encodingTypes[m->numberOfEncTypes++] = e->type; @@ -902,8 +942,9 @@ messageGetEncoding(const message *m) return NOENCODING; } - if (m->numberOfEncTypes == 0) + if (m->numberOfEncTypes == 0) { return NOENCODING; + } return m->encodingTypes[0]; } @@ -914,9 +955,9 @@ int messageAddLine(message *m, line_t *line) return -1; } - if (m->body_first == NULL) + if (m->body_first == NULL) { m->body_last = m->body_first = (text *)malloc(sizeof(text)); - else { + } else { m->body_last->t_next = (text *)malloc(sizeof(text)); m->body_last = m->body_last->t_next; } @@ -932,8 +973,9 @@ int messageAddLine(message *m, line_t *line) m->body_last->t_line = lineLink(line); messageIsEncoding(m); - } else + } else { m->body_last->t_line = NULL; + } return 1; } @@ -953,9 +995,9 @@ int messageAddStr(message *m, const char *data) } if (data) { - if (*data == '\0') + if (*data == '\0') { data = NULL; - else { + } else { /* * If it's only white space, just store one space to * save memory. You must store something since it may @@ -964,11 +1006,12 @@ int messageAddStr(message *m, const char *data) int iswhite = 1; const char *p; - for (p = data; *p; p++) + for (p = data; *p; p++) { if (((*p) & 0x80) || !isspace(*p)) { iswhite = 0; break; } + } if (iswhite) { /*cli_dbgmsg("messageAddStr: empty line: '%s'\n", data);*/ data = " "; @@ -976,21 +1019,23 @@ int messageAddStr(message *m, const char *data) } } - if (m->body_first == NULL) + if (m->body_first == NULL) { m->body_last = m->body_first = (text *)malloc(sizeof(text)); - else { + } else { if (m->body_last == NULL) { cli_errmsg("Internal email parser error: message 'body_last' pointer should not be NULL if 'body_first' is set.\n"); } else { - if ((data == NULL) && (m->body_last->t_line == NULL)) + if ((data == NULL) && (m->body_last->t_line == NULL)) { /* * Although this would save time and RAM, some * phish signatures have been built which need the * blank lines */ - if (messageGetMimeType(m) != TEXT) + if (messageGetMimeType(m) != TEXT) { /* don't save two blank lines in succession */ return 1; + } + } m->body_last->t_next = (text *)malloc(sizeof(text)); if (m->body_last->t_next == NULL) { @@ -1002,8 +1047,9 @@ int messageAddStr(message *m, const char *data) } } - if (data && m->body_last->t_line && (strcmp(data, lineGetData(m->body_last->t_line)) == 0)) + if (data && m->body_last->t_line && (strcmp(data, lineGetData(m->body_last->t_line)) == 0)) { repeat = m->body_last->t_line; + } m->body_last = m->body_last->t_next; } @@ -1017,9 +1063,9 @@ int messageAddStr(message *m, const char *data) m->body_last->t_next = NULL; if (data && *data) { - if (repeat) + if (repeat) { m->body_last->t_line = lineLink(repeat); - else { + } else { m->body_last->t_line = lineCreate(data); if (m->body_last->t_line == NULL) { @@ -1034,8 +1080,9 @@ int messageAddStr(message *m, const char *data) /* cli_chomp(m->body_last->t_text); */ messageIsEncoding(m); } - } else + } else { m->body_last->t_line = NULL; + } return 1; } @@ -1087,31 +1134,35 @@ int messageMoveText(message *m, text *t, message *old_message) if ((old_message->bounce == NULL) && (old_message->encoding == NULL) && (old_message->binhex == NULL) && - (old_message->yenc == NULL)) + (old_message->yenc == NULL)) { return 0; + } m->body_last = m->body_first; rc = 0; } else { m->body_last = m->body_first = textMove(NULL, t); - if (m->body_first == NULL) + if (m->body_first == NULL) { return -1; - else + } else { rc = 0; + } } } else { m->body_last = textMove(m->body_last, t); if (m->body_last == NULL) { rc = -1; m->body_last = m->body_first; - } else + } else { rc = 0; + } } while (m->body_last->t_next) { m->body_last = m->body_last->t_next; - if (m->body_last->t_line) + if (m->body_last->t_line) { messageIsEncoding(m); + } } return rc; @@ -1133,26 +1184,27 @@ messageIsEncoding(message *m) if ((m->encoding == NULL) && (strncasecmp(line, encoding, sizeof(encoding) - 1) == 0) && - (strstr(line, "7bit") == NULL)) + (strstr(line, "7bit") == NULL)) { m->encoding = m->body_last; - else if ((m->bounce == NULL) && m->ctx && - (strncasecmp(line, "Received: ", 10) == 0) && - (cli_compare_ftm_file((const unsigned char *)line, strlen(line), m->ctx->engine) == CL_TYPE_MAIL)) + } else if ((m->bounce == NULL) && m->ctx && + (strncasecmp(line, "Received: ", 10) == 0) && + (cli_compare_ftm_file((const unsigned char *)line, strlen(line), m->ctx->engine) == CL_TYPE_MAIL)) { m->bounce = m->body_last; - /* Not needed with fast track visa technology */ - /*else if((m->uuencode == NULL) && isuuencodebegin(line)) - m->uuencode = m->body_last;*/ - else if ((m->binhex == NULL) && - strstr(line, "BinHex") && - (simil(line, binhex) > 90)) + /* Not needed with fast track visa technology */ + /*else if((m->uuencode == NULL) && isuuencodebegin(line)) + m->uuencode = m->body_last;*/ + } else if ((m->binhex == NULL) && + strstr(line, "BinHex") && + (simil(line, binhex) > 90)) { /* * Look for close matches for BinHex, but * simil() is expensive so only do it if it's * likely to be found */ m->binhex = m->body_last; - else if ((m->yenc == NULL) && (strncmp(line, "=ybegin line=", 13) == 0)) + } else if ((m->yenc == NULL) && (strncmp(line, "=ybegin line=", 13) == 0)) { m->yenc = m->body_last; + } } /* @@ -1162,8 +1214,9 @@ messageIsEncoding(message *m) text * messageGetBody(message *m) { - if (NULL == m) + if (NULL == m) { return NULL; + } return m->body_first; } @@ -1183,16 +1236,19 @@ messageExport(message *m, const char *dir, void *(*create)(void), void (*destroy char *filename; int i; - if (NULL == m) + if (NULL == m) { return NULL; + } - if (messageGetBody(m) == NULL) + if (messageGetBody(m) == NULL) { return NULL; + } ret = (*create)(); - if (ret == NULL) + if (ret == NULL) { return NULL; + } cli_dbgmsg("messageExport: numberOfEncTypes == %d\n", m->numberOfEncTypes); @@ -1222,27 +1278,31 @@ messageExport(message *m, const char *dir, void *(*create)(void), void (*destroy if (filename == NULL) { cli_dbgmsg("Unencoded attachment sent with no filename\n"); messageAddArgument(m, "name=attachment"); - } else + } else { /* * Some virus attachments don't say how they've * been encoded. We assume base64. * RFC says encoding should be 7-bit. */ messageSetEncoding(m, "7-bit"); + } } #endif (*setFilename)(ret, dir, (filename && *filename) ? filename : "attachment"); - if (filename) + if (filename) { free((char *)filename); + } - if (m->numberOfEncTypes == 0) + if (m->numberOfEncTypes == 0) { return exportText(messageGetBody(m), ret, destroy_text); + } } - if (setCTX && m->ctx) + if (setCTX && m->ctx) { (*setCTX)(ret, m->ctx); + } for (i = 0; i < m->numberOfEncTypes; i++) { encoding_type enctype = m->encodingTypes[i]; @@ -1305,7 +1365,7 @@ messageExport(message *m, const char *dir, void *(*create)(void), void (*destroy if (filename == NULL) { cli_dbgmsg("Attachment sent with no filename\n"); messageAddArgument(m, "name=attachment"); - } else if (enctype == NOENCODING) + } else if (enctype == NOENCODING) { /* * Some virus attachments don't say how * they've been encoded. We assume @@ -1315,14 +1375,16 @@ messageExport(message *m, const char *dir, void *(*create)(void), void (*destroy * through from uuencode */ messageSetEncoding(m, "base64"); + } (*setFilename)(ret, dir, (filename && *filename) ? filename : "attachment"); t_line = messageGetBody(m); } - if (filename) + if (filename) { free((char *)filename); + } /* * t_line should now point to the first (encoded) line of the @@ -1465,8 +1527,9 @@ int messageSavePartial(message *m, const char *dir, const char *md5id, unsigned (void *(*)(text *, void *, int))textToFileblob, (void (*)(void *, cli_ctx *))fileblobSetCTX, 0); - if (!fb) + if (!fb) { return CL_EFORMAT; + } fileblobDestroy(fb); return CL_SUCCESS; } @@ -1544,25 +1607,28 @@ messageToText(message *m) * Fast copy */ for (t_line = messageGetBody(m); t_line; t_line = t_line->t_next) { - if (first == NULL) + if (first == NULL) { first = last = malloc(sizeof(text)); - else { + } else { last->t_next = malloc(sizeof(text)); last = last->t_next; } if (last == NULL) { - if (first) + if (first) { textDestroy(first); + } return NULL; } - if (t_line->t_line) + if (t_line->t_line) { last->t_line = lineLink(t_line->t_line); - else + } else { last->t_line = NULL; /* empty line */ + } } - if (last) + if (last) { last->t_next = NULL; + } return first; } @@ -1584,9 +1650,9 @@ messageToText(message *m) * Fast copy */ for (t_line = messageGetBody(m); t_line; t_line = t_line->t_next) { - if (first == NULL) + if (first == NULL) { first = last = malloc(sizeof(text)); - else if (last) { + } else if (last) { last->t_next = malloc(sizeof(text)); last = last->t_next; } @@ -1597,17 +1663,19 @@ messageToText(message *m) } return NULL; } - if (t_line->t_line) + if (t_line->t_line) { last->t_line = lineLink(t_line->t_line); - else + } else { last->t_line = NULL; /* empty line */ + } } continue; case UUENCODE: cli_warnmsg("messageToText: Unexpected attempt to handle uuencoded file\n"); if (first) { - if (last) + if (last) { last->t_next = NULL; + } textDestroy(first); } return NULL; @@ -1617,8 +1685,9 @@ messageToText(message *m) if (t_line == NULL) { /*cli_warnmsg("YENCODED attachment is missing begin statement\n");*/ if (first) { - if (last) + if (last) { last->t_next = NULL; + } textDestroy(first); } return NULL; @@ -1626,8 +1695,9 @@ messageToText(message *m) t_line = t_line->t_next; /* fall-through */ default: - if ((i == 0) && binhexBegin(m)) + if ((i == 0) && binhexBegin(m)) { cli_warnmsg("Binhex messages not supported yet.\n"); + } t_line = messageGetBody(m); } @@ -1636,13 +1706,15 @@ messageToText(message *m) unsigned char *uptr; const char *line = lineGetData(t_line->t_line); - if (enctype == BASE64) + if (enctype == BASE64) { /* * ignore blanks - breaks RFC which is * probably the point! */ - if (line == NULL) + if (line == NULL) { continue; + } + } if ((line != NULL) && (strlen(line) > sizeof(data))) { cli_errmsg("Internal email parser error: line size greater than size of receiving data buffer\n"); @@ -1651,23 +1723,25 @@ messageToText(message *m) uptr = decodeLine(m, enctype, line, data, sizeof(data)); - if (uptr == NULL) + if (uptr == NULL) { break; + } if ((size_t)(uptr - data) > sizeof(data)) { cli_errmsg("Internal email parser error: line size greater than size of receiving data buffer\n"); break; } - if (first == NULL) + if (first == NULL) { first = last = malloc(sizeof(text)); - else if (last) { + } else if (last) { last->t_next = malloc(sizeof(text)); last = last->t_next; } - if (last == NULL) + if (last == NULL) { break; + } /* * If the decoded line is the same as the encoded @@ -1678,41 +1752,46 @@ messageToText(message *m) * strcmp - that'd be bad for MIME decoders, but is OK * for AV software */ - if ((data[0] == '\n') || (data[0] == '\0')) + if ((data[0] == '\n') || (data[0] == '\0')) { last->t_line = NULL; - else if (line && (strncmp((const char *)data, line, strlen(line)) == 0)) { + } else if (line && (strncmp((const char *)data, line, strlen(line)) == 0)) { #ifdef CL_DEBUG cli_dbgmsg("messageToText: decoded line is the same(%s)\n", data); #endif last->t_line = lineLink(t_line->t_line); - } else + } else { last->t_line = lineCreate((char *)data); + } - if (line && enctype == BASE64) - if (strchr(line, '=')) + if (line && enctype == BASE64) { + if (strchr(line, '=')) { break; + } + } } if (m->base64chars) { unsigned char data[4]; memset(data, '\0', sizeof(data)); if (decode(m, NULL, data, base64, false) && data[0]) { - if (first == NULL) + if (first == NULL) { first = last = malloc(sizeof(text)); - else if (last) { + } else if (last) { last->t_next = malloc(sizeof(text)); last = last->t_next; } - if (last != NULL) + if (last != NULL) { last->t_line = lineCreate((char *)data); + } } m->base64chars = 0; } } - if (last) + if (last) { last->t_next = NULL; + } return first; } @@ -1830,9 +1909,10 @@ decodeLine(message *m, encoding_type et, const char *line, unsigned char *buf, s /* fall through */ case NOENCODING: case EIGHTBIT: - default: /* unknown encoding type - try our best */ - if (line) /* empty line? */ + default: /* unknown encoding type - try our best */ + if (line) { /* empty line? */ buf = (unsigned char *)cli_strrcpy((char *)buf, line); + } /* Put the new line back in */ return (unsigned char *)cli_strrcpy((char *)buf, "\n"); @@ -1869,10 +1949,11 @@ decodeLine(message *m, encoding_type et, const char *line, unsigned char *buf, s * quoted-printable encoding of * href=\"http://, instead of =3D */ - if (byte != '=') + if (byte != '=') { byte = (byte << 4) | hex(*line); - else + } else { line -= 2; + } *buf++ = byte; } else { @@ -1888,8 +1969,9 @@ decodeLine(message *m, encoding_type et, const char *line, unsigned char *buf, s break; case BASE64: - if (line == NULL) + if (line == NULL) { break; + } /* * RFC2045 sets the maximum length to 76 bytes * but many e-mail clients ignore that @@ -1899,13 +1981,15 @@ decodeLine(message *m, encoding_type et, const char *line, unsigned char *buf, s copy = base64buf; } else { copy = cli_safer_strdup(line); - if (copy == NULL) + if (copy == NULL) { break; + } } p2 = strchr(copy, '='); - if (p2) + if (p2) { *p2 = '\0'; + } sanitiseBase64(copy); @@ -1914,61 +1998,74 @@ decodeLine(message *m, encoding_type et, const char *line, unsigned char *buf, s */ buf = decode(m, copy, buf, base64, (p2 == NULL) && ((strlen(copy) & 3) == 0)); - if (copy != base64buf) + if (copy != base64buf) { free(copy); + } break; case UUENCODE: - if (0 != m->base64chars) + if (0 != m->base64chars) { break; + } - if ((line == NULL) || (*line == '\0')) /* empty line */ + if ((line == NULL) || (*line == '\0')) { /* empty line */ break; - if (strcasecmp(line, "end") == 0) + } + if (strcasecmp(line, "end") == 0) { break; - if (isuuencodebegin(line)) + } + if (isuuencodebegin(line)) { break; + } - if ((line[0] & 0x3F) == ' ') + if ((line[0] & 0x3F) == ' ') { break; + } /* * reallen contains the number of bytes that were * encoded */ reallen = (size_t)uudecode(*line++); - if (reallen <= 0) + if (reallen <= 0) { break; - if (reallen > 62) + } + if (reallen > 62) { break; + } len = strlen(line); - if ((len > buflen) || (reallen > len)) + if ((len > buflen) || (reallen > len)) { /* * In practice this should never occur since * the maximum length of a uuencoded line is * 62 characters */ cli_dbgmsg("uudecode: buffer overflow stopped, attempting to ignore but decoding may fail\n"); - else { + } else { (void)decode(m, line, buf, uudecode, (len & 3) == 0); buf = &buf[reallen]; } m->base64chars = 0; /* this happens with broken uuencoded files */ break; case YENCODE: - if ((line == NULL) || (*line == '\0')) /* empty line */ + if ((line == NULL) || (*line == '\0')) { /* empty line */ break; - if (strncmp(line, "=yend ", 6) == 0) + } + if (strncmp(line, "=yend ", 6) == 0) { break; + } - while (*line) + while (*line) { if (*line == '=') { - if (*++line == '\0') + if (*++line == '\0') { break; + } *buf++ = ((*line++ - 64) & 255); - } else + } else { *buf++ = ((*line++ - 42) & 255); + } + } break; } @@ -1986,14 +2083,17 @@ static void sanitiseBase64(char *s) { cli_dbgmsg("sanitiseBase64 '%s'\n", s); - while (*s) + while (*s) { if (base64Table[(unsigned int)(*s & 0xFF)] == 255) { char *p1; - for (p1 = s; p1[0] != '\0'; p1++) + for (p1 = s; p1[0] != '\0'; p1++) { p1[0] = p1[1]; - } else + } + } else { s++; + } + } } /* @@ -2033,7 +2133,7 @@ decode(message *m, const char *in, unsigned char *out, unsigned char (*decoder)( } } - if (isFast) + if (isFast) { /* Fast decoding if not last line */ while (*in) { b1 = (*decoder)(*in++); @@ -2052,11 +2152,12 @@ decode(message *m, const char *in, unsigned char *out, unsigned char (*decoder)( *out++ = (b2 << 4) | ((b3 >> 2) & 0xF); *out++ = (b3 << 6) | (b4 & 0x3F); } - else if (in == NULL) { /* flush */ + } else if (in == NULL) { /* flush */ int nbytes; - if (m->base64chars == 0) + if (m->base64chars == 0) { return out; + } cli_dbgmsg("base64chars = %d (%c %c %c)\n", m->base64chars, isalnum(cb1) ? cb1 : '@', @@ -2076,8 +2177,9 @@ decode(message *m, const char *in, unsigned char *out, unsigned char (*decoder)( m->base64chars--; b3 = cb3; nbytes = 3; - } else if (b2) + } else if (b2) { nbytes = 2; + } } switch (nbytes) { @@ -2087,13 +2189,15 @@ decode(message *m, const char *in, unsigned char *out, unsigned char (*decoder)( case 4: *out++ = (b1 << 2) | ((b2 >> 4) & 0x3); *out++ = (b2 << 4) | ((b3 >> 2) & 0xF); - if ((nbytes == 4) || (b3 & 0x3)) + if ((nbytes == 4) || (b3 & 0x3)) { *out++ = (b3 << 6) | (b4 & 0x3F); + } break; case 2: *out++ = (b1 << 2) | ((b2 >> 4) & 0x3); - if ((b2 << 4) & 0xFF) + if ((b2 << 4) & 0xFF) { *out++ = b2 << 4; + } break; case 1: *out++ = b1 << 2; @@ -2102,15 +2206,16 @@ decode(message *m, const char *in, unsigned char *out, unsigned char (*decoder)( cli_errmsg("email message decode error: invalid nbytes value: %d\n", nbytes); return out; } - } else + } else { while (*in) { int nbytes; if (m->base64chars) { m->base64chars--; b1 = cb1; - } else + } else { b1 = (*decoder)(*in++); + } if (*in == '\0') { b2 = '\0'; @@ -2119,8 +2224,9 @@ decode(message *m, const char *in, unsigned char *out, unsigned char (*decoder)( if (m->base64chars) { m->base64chars--; b2 = cb2; - } else + } else { b2 = (*decoder)(*in++); + } if (*in == '\0') { b3 = '\0'; @@ -2129,8 +2235,9 @@ decode(message *m, const char *in, unsigned char *out, unsigned char (*decoder)( if (m->base64chars) { m->base64chars--; b3 = cb3; - } else + } else { b3 = (*decoder)(*in++); + } if (*in == '\0') { b4 = '\0'; @@ -2164,18 +2271,22 @@ decode(message *m, const char *in, unsigned char *out, unsigned char (*decoder)( } break; /* nbytes != 4 => EOL */ } + } return out; } static unsigned char hex(char c) { - if (isdigit(c)) + if (isdigit(c)) { return c - '0'; - if ((c >= 'A') && (c <= 'F')) + } + if ((c >= 'A') && (c <= 'F')) { return c - 'A' + 10; - if ((c >= 'a') && (c <= 'f')) + } + if ((c >= 'a') && (c <= 'f')) { return c - 'a' + 10; + } cli_dbgmsg("Illegal hex character '%c'\n", c); /* @@ -2261,50 +2372,62 @@ messageDedup(message *m) line_t *l1; unsigned int r1; - if (saved >= 100 * 1000) + if (saved >= 100 * 1000) { break; /* that's enough */ + } l1 = t1->t_line; - if (l1 == NULL) + if (l1 == NULL) { continue; + } d1 = lineGetData(l1); - if (strlen(d1) < 8) + if (strlen(d1) < 8) { continue; /* wouldn't recover many bytes */ + } r1 = (unsigned int)lineGetRefCount(l1); - if (r1 == 255) + if (r1 == 255) { continue; + } /* * We don't want to foul up any pointers */ - if (t1 == m->encoding) + if (t1 == m->encoding) { continue; - if (t1 == m->bounce) + } + if (t1 == m->bounce) { continue; - if (t1 == m->binhex) + } + if (t1 == m->binhex) { continue; - if (t1 == m->yenc) + } + if (t1 == m->yenc) { continue; + } for (t2 = t1->t_next; t2; t2 = t2->t_next) { const char *d2; line_t *l2 = t2->t_line; - if (l2 == NULL) + if (l2 == NULL) { continue; + } d2 = lineGetData(l2); - if (d1 == d2) + if (d1 == d2) { /* already linked */ continue; + } if (strcmp(d1, d2) == 0) { - if (lineUnlink(l2) == NULL) + if (lineUnlink(l2) == NULL) { saved += strlen(d1) + 1; + } t2->t_line = lineLink(l1); if (t2->t_line == NULL) { cli_errmsg("messageDedup: out of memory\n"); return; } - if (++r1 == 255) + if (++r1 == 255) { break; + } } } } @@ -2345,9 +2468,9 @@ rfc2231(const char *in) *p++ = *in++; continue; case '*': - do + do { in++; - while ((*in != '*') && *in); + } while ((*in != '*') && *in); if (*in) { in++; continue; @@ -2369,21 +2492,22 @@ rfc2231(const char *in) } ptr = strstr(in, "*0="); - if (ptr != NULL) + if (ptr != NULL) { /* * Parameter continuation, with no continuation * Thunderbird 1.5 (and possibly other versions) does this */ field = CONTENTS; - else { + } else { ptr = strstr(in, "*="); field = LANGUAGE; } if (ptr == NULL) { /* quick return */ out = ret = cli_safer_strdup(in); - while (*out) + while (*out) { *out++ &= 0x7F; + } return ret; } @@ -2402,12 +2526,15 @@ rfc2231(const char *in) * in = ptr; */ out = ret; - while (in != ptr) + while (in != ptr) { *out++ = *in++; + } *out++ = '='; - while (*ptr++ != '=') continue; + while (*ptr++ != '=') { + continue; + } /* * We don't do anything with the language and character set, just skip @@ -2416,19 +2543,22 @@ rfc2231(const char *in) while (*ptr) { switch (field) { case LANGUAGE: - if (*ptr == '\'') + if (*ptr == '\'') { field = CHARSET; + } break; case CHARSET: - if (*ptr == '\'') + if (*ptr == '\'') { field = CONTENTS; + } break; case CONTENTS: if (*ptr == '%') { unsigned char byte; - if ((*++ptr == '\0') || (*ptr == '\n')) + if ((*++ptr == '\0') || (*ptr == '\n')) { break; + } byte = hex(*ptr); @@ -2440,10 +2570,11 @@ rfc2231(const char *in) byte <<= 4; byte += hex(*ptr); *out++ = byte; - } else + } else { *out++ = *ptr; + } } - if (*ptr++ == '\0') + if (*ptr++ == '\0') { /* * Incorrect message that has just one character after * a '%'. @@ -2451,6 +2582,7 @@ rfc2231(const char *in) * treat %2 as %02, assuming field == CONTENTS */ break; + } } if (field != CONTENTS) { @@ -2501,11 +2633,13 @@ simil(const char *str1, const char *str2) char *s1, *s2; char ls1[MAX_PATTERN_SIZ], ls2[MAX_PATTERN_SIZ]; - if (strcasecmp(str1, str2) == 0) + if (strcasecmp(str1, str2) == 0) { return 100; + } - if ((s1 = cli_safer_strdup(str1)) == NULL) + if ((s1 = cli_safer_strdup(str1)) == NULL) { return OUT_OF_MEMORY; + } if ((s2 = cli_safer_strdup(str2)) == NULL) { free(s1); return OUT_OF_MEMORY; @@ -2534,21 +2668,23 @@ simil(const char *str1, const char *str2) len1 = strlen(ls1); len2 = strlen(ls2); - if ((len1 > 1 && len2 >= 1) || (len2 > 1 && len1 >= 1)) + if ((len1 > 1 && len2 >= 1) || (len2 > 1 && len1 >= 1)) { if ((push(&top, ls1) == OUT_OF_MEMORY) || (push(&top, ls2) == OUT_OF_MEMORY)) { free(s1); free(s2); return OUT_OF_MEMORY; } + } len1 = strlen(rs1); len2 = strlen(rs2); - if ((len1 > 1 && len2 >= 1) || (len2 > 1 && len1 >= 1)) + if ((len1 > 1 && len2 >= 1) || (len2 > 1 && len1 >= 1)) { if ((push(&top, rs1) == OUT_OF_MEMORY) || (push(&top, rs2) == OUT_OF_MEMORY)) { free(s1); free(s2); return OUT_OF_MEMORY; } + } } } free(s1); @@ -2580,15 +2716,15 @@ compare(char *ls1, char **rs1, char *ls2, char **rs2) cs1 = s1; cs2 = s2; common = 0; - do - if (s1 == end1 || s2 == end2) + do { + if (s1 == end1 || s2 == end2) { break; - else { + } else { s1++; s2++; common++; } - while (tolower(*s1) == tolower(*s2)); + } while (tolower(*s1) == tolower(*s2)); if (common > maxchars) { unsigned int diff = common - maxchars; @@ -2599,14 +2735,17 @@ compare(char *ls1, char **rs1, char *ls2, char **rs2) maxe2 = s2; end1 -= diff; end2 -= diff; - } else + } else { s1 -= common; - } else + } + } else { s2++; + } } start1++; - } else + } else { break; + } } if (some_similarity) { *maxs1 = '\0'; @@ -2622,8 +2761,9 @@ push(LINK1 *top, const char *string) { LINK1 element; - if ((element = (LINK1)malloc(sizeof(ELEMENT1))) == NULL) + if ((element = (LINK1)malloc(sizeof(ELEMENT1))) == NULL) { return OUT_OF_MEMORY; + } if ((element->d1 = cli_safer_strdup(string)) == NULL) { free(element); return OUT_OF_MEMORY; @@ -2654,11 +2794,13 @@ pop(LINK1 *top, char *buffer) */ int isuuencodebegin(const char *line) { - if (line[0] != 'b') /* quick check */ + if (line[0] != 'b') { /* quick check */ return 0; + } - if (strlen(line) < 10) + if (strlen(line) < 10) { return 0; + } return (strncasecmp(line, "begin ", 6) == 0) && isdigit(line[6]) && isdigit(line[7]) && diff --git a/libclamav/mew.c b/libclamav/mew.c index 19269d90c6..579c5c72a6 100644 --- a/libclamav/mew.c +++ b/libclamav/mew.c @@ -103,8 +103,9 @@ static const char *lzma_bswap_4861dc(struct lzmastate *p, const char *old_edx) static uint32_t lzma_486248(struct lzmastate *p, const char **old_ecx, char *src, uint32_t size) { uint32_t loc_esi, loc_edi, loc_eax, loc_ecx, ret; - if (!CLI_ISCONTAINED(src, size, *old_ecx, 4) || !CLI_ISCONTAINED(src, size, p->p0, 1)) + if (!CLI_ISCONTAINED(src, size, *old_ecx, 4) || !CLI_ISCONTAINED(src, size, p->p0, 1)) { return 0xffffffff; + } loc_esi = p->p1; loc_eax = loc_esi >> 0xb; loc_ecx = cli_readint32(*old_ecx); @@ -159,8 +160,9 @@ static uint32_t lzma_48635C(uint8_t znaczek, const char **old_ecx, struct lzmast ret = loc_esi << 9; loc_edi = *old_ecx; *old_ecx = loc_edi + ret + 0x202; - if ((ret = lzma_486248(p, old_ecx, src, size)) == 0xffffffff) + if ((ret = lzma_486248(p, old_ecx, src, size)) == 0xffffffff) { return 0xffffffff; + } loc_ebx = ret | 2; while (loc_esi == ret) { @@ -173,8 +175,9 @@ static uint32_t lzma_48635C(uint8_t znaczek, const char **old_ecx, struct lzmast znaczek <<= 1; ret = ((loc_esi + 1) << 8) + loc_ebx; *old_ecx = loc_edi + ret * 2; - if ((ret = lzma_486248(p, old_ecx, src, size)) == 0xffffffff) + if ((ret = lzma_486248(p, old_ecx, src, size)) == 0xffffffff) { return 0xffffffff; + } loc_ebx += loc_ebx; loc_ebx |= ret; } @@ -182,8 +185,9 @@ static uint32_t lzma_48635C(uint8_t znaczek, const char **old_ecx, struct lzmast while (loc_ebx < loc_esi) { loc_ebx += loc_ebx; *old_ecx = loc_edi + loc_ebx; - if ((ret = lzma_486248(p, old_ecx, src, size)) == 0xffffffff) + if ((ret = lzma_486248(p, old_ecx, src, size)) == 0xffffffff) { return 0xffffffff; + } loc_ebx |= ret; } ret = (ret & 0xffffff00) | (loc_ebx & 0xff); @@ -205,8 +209,9 @@ static uint32_t lzma_4862e0(struct lzmastate *p, const char **old_ecx, uint32_t do { loc_esi = ret + ret; *old_ecx = loc_edi + loc_esi; - if ((ret = lzma_486248(p, old_ecx, src, size)) == 0xffffffff) + if ((ret = lzma_486248(p, old_ecx, src, size)) == 0xffffffff) { return 0xffffffff; + } ret += loc_esi; stack_ecx--; } while (stack_ecx); @@ -228,27 +233,31 @@ static uint32_t lzma_4863da(uint32_t var0, struct lzmastate *p, const char **old uint32_t ret; const char *loc_esi = *old_ecx; - if ((ret = lzma_486248(p, old_ecx, src, size)) == 0xffffffff) + if ((ret = lzma_486248(p, old_ecx, src, size)) == 0xffffffff) { return -1; + } if (ret) { /* loc_4863ff */ *old_ecx = loc_esi + 2; - if ((ret = lzma_486248(p, old_ecx, src, size)) == 0xffffffff) + if ((ret = lzma_486248(p, old_ecx, src, size)) == 0xffffffff) { return -1; + } if (ret) { /* loc_486429 */ *old_edx = 8; *old_ecx = loc_esi + 0x204; - if (lzma_4862e0(p, old_ecx, old_edx, &ret, src, size) == 0xffffffff) + if (lzma_4862e0(p, old_ecx, old_edx, &ret, src, size) == 0xffffffff) { return -1; + } ret += 0x10; } else { /* loc_48640e */ ret = var0 << 4; *old_edx = 3; *old_ecx = loc_esi + 0x104 + ret; - if (lzma_4862e0(p, old_ecx, old_edx, &ret, src, size) == 0xffffffff) + if (lzma_4862e0(p, old_ecx, old_edx, &ret, src, size) == 0xffffffff) { return -1; + } ret += 0x8; } } else { @@ -256,8 +265,9 @@ static uint32_t lzma_4863da(uint32_t var0, struct lzmastate *p, const char **old ret = var0 << 4; *old_edx = 3; *old_ecx = loc_esi + 0x4 + ret; - if (lzma_4862e0(p, old_ecx, old_edx, &ret, src, size) == 0xffffffff) + if (lzma_4862e0(p, old_ecx, old_edx, &ret, src, size) == 0xffffffff) { return -1; + } } *retval = ret; return 0; @@ -282,8 +292,9 @@ static uint32_t lzma_486204(struct lzmastate *p, uint32_t old_edx, uint32_t *ret } /* loc_486222 */ if (loc_esi < 0x1000000) { - if (!CLI_ISCONTAINED(src, size, p->p0, 1)) + if (!CLI_ISCONTAINED(src, size, p->p0, 1)) { return 0xffffffff; + } loc_edx = p->p0; loc_edi <<= 8; loc_esi <<= 8; @@ -319,8 +330,9 @@ static uint32_t lzma_48631a(struct lzmastate *p, const char **old_ecx, uint32_t do { loc_esi = *old_edx + *old_edx; *old_ecx = loc_esi + loc_ebx; - if ((ret = lzma_486248(p, old_ecx, src, size)) == 0xffffffff) + if ((ret = lzma_486248(p, old_ecx, src, size)) == 0xffffffff) { return 0xffffffff; + } /* unneeded *old_ecx = loc_edi; */ *old_edx = loc_esi + ret; /* ret <<= (uint32_t)(*old_ecx)&0xff; */ @@ -358,7 +370,9 @@ int mew_lzma(char *orgsource, const char *buf, uint32_t size_sum, uint32_t vma, } temp = cli_readint32(source) - vma; source += 4; - if (!special) pushed_ebx = source; + if (!special) { + pushed_ebx = source; + } new_ebx = orgsource + temp; do { @@ -367,36 +381,42 @@ int mew_lzma(char *orgsource, const char *buf, uint32_t size_sum, uint32_t vma, /* loc_486450 */ if (!special) { source = pushed_ebx; - if (!CLI_ISCONTAINED(orgsource, size_sum, source, 16)) + if (!CLI_ISCONTAINED(orgsource, size_sum, source, 16)) { return -1; + } if (cli_readint32(source) == 0) { return 0; } } else { - if (!CLI_ISCONTAINED(orgsource, size_sum, source, 12)) + if (!CLI_ISCONTAINED(orgsource, size_sum, source, 12)) { return -1; + } } var28 = cli_readint32(source); source += 4; temp = cli_readint32(source) - vma; var18 = (uint8_t *)(orgsource + temp); - if (special) pushed_esi = orgsource + temp; + if (special) { + pushed_esi = orgsource + temp; + } source += 4; temp = cli_readint32(source); source += 5; /* yes, five */ var2C = source; source += temp; - if (special) + if (special) { pushed_ebx = source; - else + } else { pushed_ebx = source; + } var1 = 0; dest = new_ebx; - if (!CLI_ISCONTAINED(orgsource, size_sum, dest, 0x6E6C)) + if (!CLI_ISCONTAINED(orgsource, size_sum, dest, 0x6E6C)) { return -1; + } for (i = 0; i < 0x1b9b; i++) { cli_writeint32(dest, 0x4000400); dest += 4; @@ -406,8 +426,9 @@ int mew_lzma(char *orgsource, const char *buf, uint32_t size_sum, uint32_t vma, loc_edi = 1; var14 = var10 = var24 = 1; - if (!CLI_ISCONTAINED(orgsource, size_sum, var2C, 5)) + if (!CLI_ISCONTAINED(orgsource, size_sum, var2C, 5)) { return -1; + } lzma_bswap_4861dc(&var40, var2C); new_edx = 0; } while (var28 <= loc_esi); /* source = 0 */ @@ -418,15 +439,17 @@ int mew_lzma(char *orgsource, const char *buf, uint32_t size_sum, uint32_t vma, new_eax = var08 & 3; new_ecx = (((loc_esi << 4) + new_eax) * 2) + new_ebx; var0C = new_eax; - if ((new_eax = lzma_486248(&var40, &new_ecx, orgsource, size_sum)) == 0xffffffff) + if ((new_eax = lzma_486248(&var40, &new_ecx, orgsource, size_sum)) == 0xffffffff) { return -1; + } if (new_eax) { /* loc_486549 */ new_ecx = new_ebx + loc_esi * 2 + 0x180; var20 = 1; /* eax=1 */ - if ((new_eax = lzma_486248(&var40, &new_ecx, orgsource, size_sum)) == 0xffffffff) + if ((new_eax = lzma_486248(&var40, &new_ecx, orgsource, size_sum)) == 0xffffffff) { return -1; + } if (new_eax != 1) { /* loc_486627 */ var24 = var10; @@ -437,18 +460,21 @@ int mew_lzma(char *orgsource, const char *buf, uint32_t size_sum, uint32_t vma, new_ecx = new_ebx + 0x664; var14 = loc_edi; loc_esi = new_eax; - if (lzma_4863da(var0C, &var40, &new_ecx, &new_edx, &new_eax, orgsource, size_sum) == 0xffffffff) + if (lzma_4863da(var0C, &var40, &new_ecx, &new_edx, &new_eax, orgsource, size_sum) == 0xffffffff) { return -1; + } var0C = new_eax; - if (var0C >= 4) + if (var0C >= 4) { new_eax = 3; + } /* loc_486662 */ new_edx = 6; new_eax <<= 7; new_ecx = new_eax + new_ebx + 0x360; - if (lzma_4862e0(&var40, &new_ecx, &new_edx, &new_eax, orgsource, size_sum) == 0xffffffff) + if (lzma_4862e0(&var40, &new_ecx, &new_edx, &new_eax, orgsource, size_sum) == 0xffffffff) { return -1; + } if (new_eax < 4) { /* loc_4866ca */ loc_edi = new_eax; @@ -460,8 +486,9 @@ int mew_lzma(char *orgsource, const char *buf, uint32_t size_sum, uint32_t vma, if (new_eax >= 0xe) { /* loc_4866ab */ new_edx = loc_ecx - 4; - if (lzma_486204(&var40, new_edx, &new_eax, orgsource, size_sum) == 0xffffffff) + if (lzma_486204(&var40, new_edx, &new_eax, orgsource, size_sum) == 0xffffffff) { return -1; + } loc_edi += new_eax << 4; new_edx = 4; @@ -473,26 +500,30 @@ int mew_lzma(char *orgsource, const char *buf, uint32_t size_sum, uint32_t vma, new_ecx = new_ebx + loc_ecx * 2 + 0x55e; } /* loc_4866a2 */ - if (lzma_48631a(&var40, &new_ecx, &new_edx, &new_eax, orgsource, size_sum) == 0xffffffff) + if (lzma_48631a(&var40, &new_ecx, &new_edx, &new_eax, orgsource, size_sum) == 0xffffffff) { return -1; + } loc_edi += new_eax; } loc_edi++; } else { /* loc_486568 */ new_ecx = new_ebx + loc_esi * 2 + 0x198; - if ((new_eax = lzma_486248(&var40, &new_ecx, orgsource, size_sum)) == 0xffffffff) + if ((new_eax = lzma_486248(&var40, &new_ecx, orgsource, size_sum)) == 0xffffffff) { return -1; + } if (new_eax) { /* loc_4865bd */ new_ecx = new_ebx + loc_esi * 2 + 0x1B0; - if ((new_eax = lzma_486248(&var40, &new_ecx, orgsource, size_sum)) == 0xffffffff) + if ((new_eax = lzma_486248(&var40, &new_ecx, orgsource, size_sum)) == 0xffffffff) { return -1; + } if (new_eax) { /* loc_4865d2 */ new_ecx = new_ebx + loc_esi * 2 + 0x1C8; - if ((new_eax = lzma_486248(&var40, &new_ecx, orgsource, size_sum)) == 0xffffffff) + if ((new_eax = lzma_486248(&var40, &new_ecx, orgsource, size_sum)) == 0xffffffff) { return -1; + } if (new_eax) { /* loc_4865ea */ new_eax = var24; @@ -514,8 +545,9 @@ int mew_lzma(char *orgsource, const char *buf, uint32_t size_sum, uint32_t vma, /* loc_48657e */ new_eax = ((loc_esi + 0xf) << 4) + var0C; new_ecx = new_ebx + new_eax * 2; - if ((new_eax = lzma_486248(&var40, &new_ecx, orgsource, size_sum)) == 0xffffffff) + if ((new_eax = lzma_486248(&var40, &new_ecx, orgsource, size_sum)) == 0xffffffff) { return -1; + } if (!new_eax) { uint32_t loc_ecx; /* loc_486593 */ @@ -523,14 +555,16 @@ int mew_lzma(char *orgsource, const char *buf, uint32_t size_sum, uint32_t vma, loc_ecx -= loc_edi; /* loc_esi = ((((loc_esi >= 7)-1)&0xFFFFFFFE) + 0xB); */ loc_esi = loc_esi >= 7 ? 11 : 9; - if (!CLI_ISCONTAINED((uint8_t *)orgsource, size_sum, var18 + loc_ecx, 1)) + if (!CLI_ISCONTAINED((uint8_t *)orgsource, size_sum, var18 + loc_ecx, 1)) { return -1; + } var1 = *(var18 + loc_ecx); loc_ecx = (loc_ecx & 0xffffff00) | var1; /* loc_4865af */ new_edx = var08++; - if (!CLI_ISCONTAINED((uint8_t *)orgsource, size_sum, var18 + new_edx, 1)) + if (!CLI_ISCONTAINED((uint8_t *)orgsource, size_sum, var18 + new_edx, 1)) { return -1; + } *(var18 + new_edx) = loc_ecx & 0xff; /* loc_4866fe */ @@ -540,8 +574,9 @@ int mew_lzma(char *orgsource, const char *buf, uint32_t size_sum, uint32_t vma, } /* loc_4865fe */ new_ecx = new_ebx + 0xa68; - if (lzma_4863da(var0C, &var40, &new_ecx, &new_edx, &new_eax, orgsource, size_sum) == 0xffffffff) + if (lzma_4863da(var0C, &var40, &new_ecx, &new_edx, &new_eax, orgsource, size_sum) == 0xffffffff) { return -1; + } var0C = new_eax; /* new_eax = (((loc_esi >= 7)-1)&0xFFFFFFFD) + 0xB; */ new_eax = loc_esi >= 7 ? 11 : 8; @@ -559,8 +594,9 @@ int mew_lzma(char *orgsource, const char *buf, uint32_t size_sum, uint32_t vma, (!CLI_ISCONTAINED(orgsource, size_sum, (char *)(new_ecx + new_eax), var0C) || !CLI_ISCONTAINED(orgsource, size_sum, (char *)(new_ecx + new_edx), var0C))) || (!CLI_ISCONTAINED(orgsource, size_sum, (char *)(new_ecx + new_eax), var28 - new_edx) || - !CLI_ISCONTAINED(orgsource, size_sum, (char *)(new_ecx + new_edx), var28 - new_edx))) + !CLI_ISCONTAINED(orgsource, size_sum, (char *)(new_ecx + new_edx), var28 - new_edx))) { return -1; + } do { var1 = *(uint8_t *)(new_ecx + new_eax); *(uint8_t *)(new_ecx + new_edx) = var1; @@ -568,8 +604,9 @@ int mew_lzma(char *orgsource, const char *buf, uint32_t size_sum, uint32_t vma, new_edx++; new_eax++; var0C--; - if (var0C <= 0) + if (var0C <= 0) { break; + } } while (new_edx < var28); var08 = new_edx; } @@ -580,10 +617,11 @@ int mew_lzma(char *orgsource, const char *buf, uint32_t size_sum, uint32_t vma, var0C_ecxcopy = new_ecx; if (loc_esi >= 4) { /* loc_4864e8 */ - if (loc_esi >= 10) + if (loc_esi >= 10) { loc_esi -= 6; - else + } else { loc_esi -= 3; + } } else { /* loc_4864e4 */ @@ -599,8 +637,9 @@ int mew_lzma(char *orgsource, const char *buf, uint32_t size_sum, uint32_t vma, new_eax += new_eax; new_ecx += new_eax; var34 = new_eax; - if ((new_eax = lzma_486248(&var40, &new_ecx, orgsource, size_sum)) == 0xffffffff) + if ((new_eax = lzma_486248(&var40, &new_ecx, orgsource, size_sum)) == 0xffffffff) { return -1; + } new_eax |= var34; /* loc_486522 */ /* keeping it here instead of at the top @@ -616,13 +655,15 @@ int mew_lzma(char *orgsource, const char *buf, uint32_t size_sum, uint32_t vma, int t; /* loc_4864FB */ new_eax = var08 - loc_edi; - if (!CLI_ISCONTAINED((uint8_t *)orgsource, size_sum, var18 + new_eax, 1)) + if (!CLI_ISCONTAINED((uint8_t *)orgsource, size_sum, var18 + new_eax, 1)) { return -1; + } t = *(var18 + new_eax); new_eax = (new_eax & 0xffffff00) | t; - if (lzma_48635C(t, &new_ecx, &var40, &new_eax, orgsource, size_sum) == 0xffffffff) + if (lzma_48635C(t, &new_ecx, &var40, &new_eax, orgsource, size_sum) == 0xffffffff) { return -1; + } var20 = 0; var1 = new_eax & 0xff; } @@ -634,8 +675,9 @@ int mew_lzma(char *orgsource, const char *buf, uint32_t size_sum, uint32_t vma, /* loc_4865af */ new_edx = var08++; - if (!CLI_ISCONTAINED((uint8_t *)orgsource, size_sum, var18 + new_edx, 1)) + if (!CLI_ISCONTAINED((uint8_t *)orgsource, size_sum, var18 + new_edx, 1)) { return -1; + } *(var18 + new_edx) = var1; } /* loc_4866fe */ @@ -647,8 +689,9 @@ int mew_lzma(char *orgsource, const char *buf, uint32_t size_sum, uint32_t vma, /* let's fix calls */ cli_dbgmsg("MEWlen: %08x ? %08x\n", new_edx, pushed_edx); - if (pushed_edx < 5 || !CLI_ISCONTAINED(orgsource, size_sum, pushed_esi, pushed_edx)) + if (pushed_edx < 5 || !CLI_ISCONTAINED(orgsource, size_sum, pushed_esi, pushed_edx)) { return 0; /* No point in full failing just because we can't fixxup the calls */ + } for (loc_ecx = 0; loc_ecx < pushed_edx - 5; loc_ecx++) { /* 0xe8, 0xe9 call opcodes */ @@ -674,10 +717,11 @@ uint32_t lzma_upack_esi_00(struct lzmastate *p, char *old_ecx, char *bb, uint32_ uint32_t loc_eax, ret, loc_edi; loc_eax = p->p1 >> 0xb; if (!CLI_ISCONTAINED(bb, bl, old_ecx, 4) || !CLI_ISCONTAINED(bb, bl, p->p0, 4)) { - if (!CLI_ISCONTAINED(bb, bl, old_ecx, 4)) + if (!CLI_ISCONTAINED(bb, bl, old_ecx, 4)) { cli_dbgmsg("contain error! %p %08x ecx: %p [%p]\n", bb, bl, old_ecx, bb + bl); - else + } else { cli_dbgmsg("contain error! %p %08x p0: %p [%p]\n", bb, bl, p->p0, bb + bl); + } return 0xffffffff; } ret = cli_readint32(old_ecx); @@ -714,8 +758,9 @@ uint32_t lzma_upack_esi_50(struct lzmastate *p, uint32_t old_eax, uint32_t old_e do { *old_edx = old_ebp + (loc_eax << 2); - if ((ret = lzma_upack_esi_00(p, *old_edx, bs, bl)) == 0xffffffff) + if ((ret = lzma_upack_esi_00(p, *old_edx, bs, bl)) == 0xffffffff) { return 0xffffffff; + } loc_eax += loc_eax; loc_eax += ret; } while (loc_eax < old_ecx); @@ -741,8 +786,9 @@ uint32_t lzma_upack_esi_54(struct lzmastate *p, uint32_t old_eax, uint32_t *old_ } } ret = loc_eax; - if (lzma_upack_esi_50(p, 1, *old_ecx, old_edx, *old_edx + (loc_eax << 2), &loc_eax, bs, bl) == 0xffffffff) + if (lzma_upack_esi_50(p, 1, *old_ecx, old_edx, *old_edx + (loc_eax << 2), &loc_eax, bs, bl) == 0xffffffff) { return 0xffffffff; + } *retval = ret + loc_eax; return 0; @@ -813,8 +859,9 @@ int unmew11(char *src, uint32_t off, uint32_t ssize, uint32_t dsize, uint32_t ba cli_dbgmsg("MEW unpacking section %d (%p->%p)\n", i, lesi, ledi); if (!CLI_ISCONTAINED(src, size_sum, lesi, loc_ss) || !CLI_ISCONTAINED(src, size_sum, ledi, loc_ds)) { cli_dbgmsg("Possibly programmer error or hand-crafted PE file, report to clamav team\n"); - if (section != NULL) + if (section != NULL) { free(section); + } return -1; } if (unmew(lesi, ledi, loc_ss, loc_ds, &f1, &f2)) { @@ -872,8 +919,9 @@ int unmew11(char *src, uint32_t off, uint32_t ssize, uint32_t dsize, uint32_t ba } i++; - if (!cli_readint32(f1)) + if (!cli_readint32(f1)) { break; + } } /* LZMA stuff */ diff --git a/libclamav/mpool.c b/libclamav/mpool.c index f0d4ad4982..8f2f55b0ba 100644 --- a/libclamav/mpool.c +++ b/libclamav/mpool.c @@ -411,14 +411,19 @@ static size_t align_to_pagesize(struct MP *mp, size_t size) static unsigned int to_bits(size_t size) { unsigned int i; - for (i = 0; i < FRAGSBITS; i++) - if (fragsz[i] >= size) return i; + for (i = 0; i < FRAGSBITS; i++) { + if (fragsz[i] >= size) { + return i; + } + } return FRAGSBITS; } static size_t from_bits(unsigned int bits) { - if (bits >= FRAGSBITS) return 0; + if (bits >= FRAGSBITS) { + return 0; + } return fragsz[bits]; } @@ -471,11 +476,12 @@ struct MP *mpool_create() return NULL; } #ifndef _WIN32 - if ((mpool_p = (struct MP *)mmap(NULL, sz, PROT_READ | PROT_WRITE, MAP_PRIVATE | ANONYMOUS_MAP, -1, 0)) == MAP_FAILED) + if ((mpool_p = (struct MP *)mmap(NULL, sz, PROT_READ | PROT_WRITE, MAP_PRIVATE | ANONYMOUS_MAP, -1, 0)) == MAP_FAILED) { #else if (!(mpool_p = (struct MP *)VirtualAlloc(NULL, sz, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE))) #endif return NULL; + } #ifdef CL_DEBUG memset(mpool_p, ALLOCPOISON, sz); #endif @@ -563,11 +569,13 @@ int mpool_getstats(const struct cl_engine *eng, size_t *used, size_t *total) const mpool_t *mp; /* checking refcount is not necessary, but safer */ - if (!eng || !eng->refcount) + if (!eng || !eng->refcount) { return -1; + } mp = eng->mempool; - if (!mp) + if (!mp) { return -1; + } for (mpm = &mp->u.mpm; mpm; mpm = mpm->next) { sum_used += mpm->usize; sum_total += mpm->size; @@ -657,16 +665,18 @@ void *mpool_malloc(struct MP *mp, size_t size) /* Case 2: We have nuff room available for this frag already */ while (mpm) { - if (mpm->size - mpm->usize >= needed) + if (mpm->size - mpm->usize >= needed) { return allocate_aligned(mpm, size, align, "hole"); + } mpm = mpm->next; } /* Case 3: We allocate more */ - if (needed + sizeof(*mpm) > MIN_FRAGSIZE) + if (needed + sizeof(*mpm) > MIN_FRAGSIZE) { i = align_to_pagesize(mp, needed + sizeof(*mpm)); - else + } else { i = align_to_pagesize(mp, MIN_FRAGSIZE); + } #ifndef _WIN32 if ((mpm = (struct MPMAP *)mmap(NULL, i, PROT_READ | PROT_WRITE, MAP_PRIVATE | ANONYMOUS_MAP, -1, 0)) == MAP_FAILED) { @@ -699,7 +709,9 @@ void mpool_free(struct MP *mp, void *ptr) { struct FRAG *f = NULL; unsigned int sbits = 0; - if (!ptr) return; + if (!ptr) { + return; + } f = (struct FRAG *)((char *)ptr - FRAG_OVERHEAD); #ifdef CL_DEBUG @@ -722,9 +734,12 @@ void *mpool_calloc(struct MP *mp, size_t nmemb, size_t size) size_t needed = nmemb * size; void *ptr; - if (!needed) return NULL; - if ((ptr = mpool_malloc(mp, needed))) + if (!needed) { + return NULL; + } + if ((ptr = mpool_malloc(mp, needed))) { memset(ptr, 0, needed); + } return ptr; } @@ -733,7 +748,9 @@ void *mpool_realloc(struct MP *mp, void *ptr, size_t size) struct FRAG *f = NULL; size_t csize = 0; void *new_ptr = NULL; - if (!ptr) return mpool_malloc(mp, size); + if (!ptr) { + return mpool_malloc(mp, size); + } f = (struct FRAG *)((char *)ptr - FRAG_OVERHEAD); if (!size || !(csize = from_bits(f->u.a.sbits))) { @@ -746,8 +763,9 @@ void *mpool_realloc(struct MP *mp, void *ptr, size_t size) spam("malloc @%p size %lu (self) origsize %lu overhead %lu\n", f, (unsigned long)(size + FRAG_OVERHEAD + f->u.a.padding), (unsigned long)size, (unsigned long)(csize - size + FRAG_OVERHEAD + f->u.a.padding)); return ptr; } - if (!(new_ptr = mpool_malloc(mp, size))) + if (!(new_ptr = mpool_malloc(mp, size))) { return NULL; + } memcpy(new_ptr, ptr, csize <= size ? csize : size); mpool_free(mp, ptr); return new_ptr; @@ -756,8 +774,9 @@ void *mpool_realloc(struct MP *mp, void *ptr, size_t size) void *mpool_realloc2(struct MP *mp, void *ptr, size_t size) { void *new_ptr = mpool_realloc(mp, ptr, size); - if (new_ptr) + if (new_ptr) { return new_ptr; + } mpool_free(mp, ptr); return NULL; } @@ -797,10 +816,11 @@ char *cli_mpool_strdup(mpool_t *mp, const char *s) strsz = strlen(s) + 1; alloc = mpool_malloc(mp, strsz); - if (!alloc) + if (!alloc) { cli_errmsg("cli_mpool_strdup(): Can't allocate memory (%lu bytes).\n", (unsigned long)strsz); - else + } else { memcpy(alloc, s, strsz); + } return alloc; } @@ -816,10 +836,11 @@ char *cli_mpool_strndup(mpool_t *mp, const char *s, size_t n) strsz = CLI_STRNLEN(s, n) + 1; alloc = mpool_malloc(mp, strsz); - if (!alloc) + if (!alloc) { cli_errmsg("cli_mpool_strndup(): Can't allocate memory (%lu bytes).\n", (unsigned long)strsz); - else + } else { memcpy(alloc, s, strsz - 1); + } alloc[strsz - 1] = '\0'; return alloc; } @@ -832,12 +853,15 @@ char *cli_mpool_virname(mpool_t *mp, const char *virname, unsigned int official) char buf[1024]; #endif - if (!virname) + if (!virname) { return NULL; + } - if ((pt = strchr(virname, ' '))) - if ((pt = strstr(pt, " (Clam)"))) + if ((pt = strchr(virname, ' '))) { + if ((pt = strstr(pt, " (Clam)"))) { *pt = '\0'; + } + } if (!virname[0]) { cli_errmsg("cli_mpool_virname: Empty virus name\n"); @@ -851,8 +875,9 @@ char *cli_mpool_virname(mpool_t *mp, const char *virname, unsigned int official) virname = buf; } #endif - if (official) + if (official) { return cli_mpool_strdup(mp, virname); + } newname = (char *)mpool_malloc(mp, strlen(virname) + 11 + 1); if (!newname) { @@ -876,11 +901,13 @@ uint16_t *cli_mpool_hex2ui(mpool_t *mp, const char *hex) } str = mpool_calloc(mp, (len / 2) + 1, sizeof(uint16_t)); - if (!str) + if (!str) { return NULL; + } - if (cli_realhex2ui(hex, str, len)) + if (cli_realhex2ui(hex, str, len)) { return str; + } mpool_free(mp, str); return NULL; diff --git a/libclamav/msdoc.c b/libclamav/msdoc.c index 87499ebacc..889ad4edff 100644 --- a/libclamav/msdoc.c +++ b/libclamav/msdoc.c @@ -79,29 +79,33 @@ static char *ole2_convert_utf(summary_ctx_t *sctx, char *begin, size_t sz, const size_t bcnt, scnt; outbuf = cli_max_calloc(1, sz + 1); - if (!(outbuf)) + if (!(outbuf)) { return NULL; + } memcpy(outbuf, begin, sz); track = outbuf + sz - 1; if ((sctx->codepage == CODEPAGE_UTF8) && (*track & 0x80)) { /* UTF-8 with a most significant bit */ /* locate the start of the last character */ for (bcnt = 1; (track != outbuf); track--, bcnt++) { - if (((uint8_t)*track & 0xC0) != 0x80) + if (((uint8_t)*track & 0xC0) != 0x80) { break; + } } /* count number of set (1) significant bits */ for (scnt = 0; scnt < sizeof(uint8_t) * 8; scnt++) { - if (((uint8_t)*track & (0x80 >> scnt)) == 0) + if (((uint8_t)*track & (0x80 >> scnt)) == 0) { break; + } } if (bcnt != scnt) { cli_dbgmsg("ole2_convert_utf: cleaning out %zu bytes from incomplete utf-8 character length %zu\n", bcnt, scnt); - for (; bcnt > 0; bcnt--, track++) + for (; bcnt > 0; bcnt--, track++) { *track = '\0'; + } } } return outbuf; @@ -109,8 +113,9 @@ static char *ole2_convert_utf(summary_ctx_t *sctx, char *begin, size_t sz, const #if HAVE_ICONV p1 = buf = cli_max_calloc(1, sz); - if (!(buf)) + if (!(buf)) { return NULL; + } memcpy(buf, begin, sz); inlen = sz; @@ -118,9 +123,9 @@ static char *ole2_convert_utf(summary_ctx_t *sctx, char *begin, size_t sz, const /* encoding lookup if not specified */ if (!encoding) { for (i = 0; i < NUMCODEPAGES; ++i) { - if (sctx->codepage == codepage_entries[i].codepage) + if (sctx->codepage == codepage_entries[i].codepage) { encoding = codepage_entries[i].encoding; - else if (sctx->codepage < codepage_entries[i].codepage) { + } else if (sctx->codepage < codepage_entries[i].codepage) { /* assuming sorted array */ break; } @@ -176,9 +181,10 @@ static char *ole2_convert_utf(summary_ctx_t *sctx, char *begin, size_t sz, const // cli_dbgmsg("%u %s\n", inlen, outbuf); offset = sz2 - outlen; - if (attempt < 3) + if (attempt < 3) { cli_dbgmsg("ole2_convert_utf: outbuf is too small, resizing %llu -> %llu\n", (long long unsigned)((attempt * 2) * sz), (long long unsigned)(((attempt + 1) * 2) * sz)); + } } if (errno == E2BIG && nonrev == (size_t)-1) { @@ -245,8 +251,9 @@ ole2_process_property(summary_ctx_t *sctx, unsigned char *databuf, uint32_t offs if (sctx->writecp) { sctx->codepage = (uint16_t)dout; ret = cli_jsonint(sctx->summary, sctx->propname, sctx->codepage); - } else + } else { ret = cli_jsonint(sctx->summary, sctx->propname, dout); + } break; } case PT_INT32: @@ -345,8 +352,9 @@ ole2_process_property(summary_ctx_t *sctx, unsigned char *databuf, uint32_t offs /* endian conversion */ dout = sum16_endian_convert(dout); - if (sctx->writecp) + if (sctx->writecp) { sctx->codepage = dout; + } ret = cli_jsonint(sctx->summary, sctx->propname, dout); break; @@ -796,8 +804,9 @@ static int ole2_summary_propset_json(summary_ctx_t *sctx, off_t offset) if (sctx->propname != NULL) { ret = ole2_process_property(sctx, ps, propoff); - if (ret != CL_SUCCESS) + if (ret != CL_SUCCESS) { return ret; + } } else { /* add unknown propid flag */ } diff --git a/libclamav/msexpand.c b/libclamav/msexpand.c index 8f6738fa98..94e0972f69 100644 --- a/libclamav/msexpand.c +++ b/libclamav/msexpand.c @@ -106,8 +106,9 @@ cl_error_t cli_msexpand(cli_ctx *ctx, int ofd) unsigned int fsize; size_t ret; - if (!(hdr = fmap_need_off_once(map, 0, sizeof(*hdr)))) + if (!(hdr = fmap_need_off_once(map, 0, sizeof(*hdr)))) { return CL_EREAD; + } if (EC32(hdr->magic1) != MAGIC1 || EC32(hdr->magic2) != MAGIC2 || EC16(hdr->magic3) != MAGIC3) { cli_dbgmsg("MSEXPAND: Not supported file format\n"); @@ -117,8 +118,9 @@ cl_error_t cli_msexpand(cli_ctx *ctx, int ofd) fsize = EC32(hdr->fsize); cli_dbgmsg("MSEXPAND: File size from header: %u\n", fsize); - if (cli_checklimits("MSEXPAND", ctx, fsize, 0, 0) != CL_CLEAN) + if (cli_checklimits("MSEXPAND", ctx, fsize, 0, 0) != CL_CLEAN) { return CL_SUCCESS; + } memset(buff, 0, B_SIZE); while (1) { diff --git a/libclamav/msxml.c b/libclamav/msxml.c index 49c5d465d7..491ae287aa 100644 --- a/libclamav/msxml.c +++ b/libclamav/msxml.c @@ -126,8 +126,9 @@ int msxml_read_cb(void *ctx, char *buffer, int buffer_len) /* initial iteration */ if (!cbdata->window) { - if ((winret = msxml_read_cb_new_window(cbdata)) <= 0) + if ((winret = msxml_read_cb_new_window(cbdata)) <= 0) { return winret; + } } cli_msxmlmsg("msxml_read_cb: requested %zu bytes from offset %llu\n", len, (long long unsigned)(cbdata->mappos + cbdata->winpos)); @@ -145,8 +146,9 @@ int msxml_read_cb(void *ctx, char *buffer, int buffer_len) #endif if (!rbytes) { - if ((winret = msxml_read_cb_new_window(cbdata)) < 0) + if ((winret = msxml_read_cb_new_window(cbdata)) < 0) { return winret; + } if (winret == 0) { cli_msxmlmsg("msxml_read_cb: propagating fmap EOF [%llu]\n", (long long unsigned)wbytes); return (int)wbytes; @@ -168,34 +170,39 @@ int msxml_read_cb(void *ctx, char *buffer, int buffer_len) while ((rbytes > 0) && (wbytes < len)) { switch (*state) { case MSXML_STATE_NORMAL: - if ((*read_from) == '&') + if ((*read_from) == '&') { *state = MSXML_STATE_ENTITY_START_1; + } break; case MSXML_STATE_ENTITY_START_1: - if ((*read_from) == '#') + if ((*read_from) == '#') { *state = MSXML_STATE_ENTITY_START_2; - else + } else { *state = MSXML_STATE_NORMAL; + } break; case MSXML_STATE_ENTITY_START_2: - if ((*read_from) == 'x') + if ((*read_from) == 'x') { *state = MSXML_STATE_ENTITY_HEX; - else if (((*read_from) >= '0') && ((*read_from) <= '9')) + } else if (((*read_from) >= '0') && ((*read_from) <= '9')) { *state = MSXML_STATE_ENTITY_DEC; - else + } else { *state = MSXML_STATE_NORMAL; + } break; case MSXML_STATE_ENTITY_HEX: if ((((*read_from) >= '0') && ((*read_from) <= '9')) || (((*read_from) >= 'a') && ((*read_from) <= 'f')) || (((*read_from) >= 'A') && ((*read_from) <= 'F'))) { - } else + } else { *state = MSXML_STATE_ENTITY_CLOSE; + } break; case MSXML_STATE_ENTITY_DEC: if (((*read_from) >= '0') && ((*read_from) <= '9')) { - } else + } else { *state = MSXML_STATE_ENTITY_CLOSE; + } break; default: cli_errmsg("unknown *state: %d\n", *state); @@ -209,8 +216,9 @@ int msxml_read_cb(void *ctx, char *buffer, int buffer_len) wbytes++; } *state = MSXML_STATE_NORMAL; - if (wbytes >= len) + if (wbytes >= len) { break; + } } *(write_to++) = *(read_from++); @@ -231,8 +239,9 @@ cl_error_t cli_scanmsxml(cli_ctx *ctx) cli_dbgmsg("in cli_scanmsxml()\n"); - if (!ctx) + if (!ctx) { return CL_ENULLARG; + } memset(&cbdata, 0, sizeof(cbdata)); cbdata.map = ctx->fmap; diff --git a/libclamav/msxml_parser.c b/libclamav/msxml_parser.c index e8a26dc706..0b52100a62 100644 --- a/libclamav/msxml_parser.c +++ b/libclamav/msxml_parser.c @@ -129,8 +129,9 @@ static int msxml_parse_value(json_object *wrkptr, const char *arrname, const xml json_object *newobj, *arrobj; int val; - if (!wrkptr) + if (!wrkptr) { return CL_ENULLARG; + } arrobj = cli_jsonarray(wrkptr, arrname); if (arrobj == NULL) { @@ -179,8 +180,9 @@ static cl_error_t msxml_parse_element(struct msxml_ctx *mxctx, xmlTextReaderPtr if (track_json(mxctx)) { cl_error_t tmp = cli_json_parse_error(root, "MSXML_RECURSIVE_LIMIT"); - if (tmp != CL_SUCCESS) + if (tmp != CL_SUCCESS) { return tmp; + } } /* skip it */ @@ -191,8 +193,9 @@ static cl_error_t msxml_parse_element(struct msxml_ctx *mxctx, xmlTextReaderPtr /* acquire element type */ node_type = xmlTextReaderNodeType(reader); - if (node_type == -1) + if (node_type == -1) { return CL_EPARSE; + } node_name = xmlTextReaderConstLocalName(reader); node_value = xmlTextReaderConstValue(reader); @@ -209,8 +212,9 @@ static cl_error_t msxml_parse_element(struct msxml_ctx *mxctx, xmlTextReaderPtr if (track_json(mxctx)) { cl_error_t tmp = cli_json_parse_error(root, "MSXML_NAMELESS_ELEMENT"); - if (tmp != CL_SUCCESS) + if (tmp != CL_SUCCESS) { return tmp; + } } return CL_EPARSE; /* no name, nameless */ @@ -233,10 +237,11 @@ static cl_error_t msxml_parse_element(struct msxml_ctx *mxctx, xmlTextReaderPtr } if (track_json(mxctx) && (keyinfo->type & MSXML_JSON_TRACK)) { - if (keyinfo->type & MSXML_JSON_ROOT) + if (keyinfo->type & MSXML_JSON_ROOT) { thisjobj = cli_jsonobj(root, keyinfo->name); - else if (keyinfo->type & MSXML_JSON_WRKPTR) + } else if (keyinfo->type & MSXML_JSON_WRKPTR) { thisjobj = cli_jsonobj(parent, keyinfo->name); + } if (!thisjobj) { return CL_EMEM; @@ -266,8 +271,9 @@ static cl_error_t msxml_parse_element(struct msxml_ctx *mxctx, xmlTextReaderPtr cli_msxmlmsg("msxml_parse_element: generated or retrieved json multi array\n"); thisjobj = cli_jsonobj(multi, NULL); - if (!thisjobj) + if (!thisjobj) { return CL_EMEM; + } cli_msxmlmsg("msxml_parse_element: generated json multi entry object\n"); } @@ -291,8 +297,9 @@ static cl_error_t msxml_parse_element(struct msxml_ctx *mxctx, xmlTextReaderPtr cli_msxmlmsg("\t%s: %s\n", name, value); cli_jsonstr(attributes, (char *)name, (const char *)value); } - } else if (state == -1) + } else if (state == -1) { return CL_EPARSE; + } } } @@ -327,8 +334,9 @@ static cl_error_t msxml_parse_element(struct msxml_ctx *mxctx, xmlTextReaderPtr /* check self-containment */ state = xmlTextReaderMoveToElement(reader); - if (state == -1) + if (state == -1) { return CL_EPARSE; + } state = xmlTextReaderIsEmptyElement(reader); if (state == 1) { @@ -337,20 +345,23 @@ static cl_error_t msxml_parse_element(struct msxml_ctx *mxctx, xmlTextReaderPtr state = xmlTextReaderNext(reader); check_state(state); return CL_SUCCESS; - } else if (state == -1) + } else if (state == -1) { return CL_EPARSE; + } /* advance to first content node */ state = xmlTextReaderRead(reader); check_state(state); while (!endtag) { - if (track_json(mxctx) && (cli_json_timeout_cycle_check(ctx, &(mxctx->ictx->toval)) != CL_SUCCESS)) + if (track_json(mxctx) && (cli_json_timeout_cycle_check(ctx, &(mxctx->ictx->toval)) != CL_SUCCESS)) { return CL_ETIMEOUT; + } node_type = xmlTextReaderNodeType(reader); - if (node_type == -1) + if (node_type == -1) { return CL_EPARSE; + } switch (node_type) { case XML_READER_TYPE_ELEMENT: @@ -368,8 +379,9 @@ static cl_error_t msxml_parse_element(struct msxml_ctx *mxctx, xmlTextReaderPtr if (thisjobj && (keyinfo->type & MSXML_JSON_VALUE)) { ret = msxml_parse_value(thisjobj, "Value", node_value); - if (ret != CL_SUCCESS) + if (ret != CL_SUCCESS) { return ret; + } cli_msxmlmsg("msxml_parse_element: added json value [%s: %s]\n", keyinfo->name, (const char *)node_value); } @@ -390,8 +402,9 @@ static cl_error_t msxml_parse_element(struct msxml_ctx *mxctx, xmlTextReaderPtr if (cli_writen(of, (char *)node_value, vlen) != vlen) { close(of); - if (!(ctx->engine->keeptmp)) + if (!(ctx->engine->keeptmp)) { cli_unlink(tempfile); + } free(tempfile); return CL_EWRITE; } @@ -435,8 +448,9 @@ static cl_error_t msxml_parse_element(struct msxml_ctx *mxctx, xmlTextReaderPtr if (cli_writen(of, decoded, decodedlen) != decodedlen) { free(decoded); close(of); - if (!(ctx->engine->keeptmp)) + if (!(ctx->engine->keeptmp)) { cli_unlink(tempfile); + } free(tempfile); return CL_EWRITE; } @@ -446,8 +460,9 @@ static cl_error_t msxml_parse_element(struct msxml_ctx *mxctx, xmlTextReaderPtr ret = cli_magic_scan_desc(of, tempfile, ctx, NULL, LAYER_ATTRIBUTES_NONE); close(of); - if (!(ctx->engine->keeptmp)) + if (!(ctx->engine->keeptmp)) { cli_unlink(tempfile); + } free(tempfile); if (ret != CL_SUCCESS) { return ret; @@ -556,8 +571,9 @@ cl_error_t cli_msxml_parse_document(cli_ctx *ctx, xmlTextReaderPtr reader, const if (flags & MSXML_FLAG_JSON) { ictx.root = ctx->wrkproperty; /* JSON Sanity Check */ - if (!ictx.root) + if (!ictx.root) { ictx.flags &= ~MSXML_FLAG_JSON; + } ictx.toval = 0; } else { ictx.root = NULL; @@ -565,14 +581,16 @@ cl_error_t cli_msxml_parse_document(cli_ctx *ctx, xmlTextReaderPtr reader, const mxctx->ictx = &ictx; /* Error Handler (setting handler on tree walker causes segfault) */ - if (!(flags & MSXML_FLAG_WALK)) + if (!(flags & MSXML_FLAG_WALK)) { // xmlTextReaderSetErrorHandler(reader, NULL, NULL); /* xml default handler */ xmlTextReaderSetErrorHandler(reader, msxml_error_handler, NULL); + } /* Main Processing Loop */ while ((state = xmlTextReaderRead(reader)) == 1) { - if ((ictx.flags & MSXML_FLAG_JSON) && (cli_json_timeout_cycle_check(ictx.ctx, &(ictx.toval)) != CL_SUCCESS)) + if ((ictx.flags & MSXML_FLAG_JSON) && (cli_json_timeout_cycle_check(ictx.ctx, &(ictx.toval)) != CL_SUCCESS)) { return CL_ETIMEOUT; + } ret = msxml_parse_element(mxctx, reader, 0, ictx.root); if (ret != CL_SUCCESS) { @@ -624,8 +642,9 @@ cl_error_t cli_msxml_parse_document(cli_ctx *ctx, xmlTextReaderPtr reader, const } /* non-critical return suppression */ - if (ret == CL_BREAK) + if (ret == CL_BREAK) { ret = CL_SUCCESS; + } /* important but non-critical suppression */ if (ret == CL_EPARSE) { diff --git a/libclamav/nsis/nulsft.c b/libclamav/nsis/nulsft.c index cd3a4b181a..f3225c93cf 100644 --- a/libclamav/nsis/nulsft.c +++ b/libclamav/nsis/nulsft.c @@ -86,14 +86,16 @@ static int nsis_init(struct nsis_st *n) switch (n->comp) { case COMP_BZIP2: memset(&n->bz, 0, sizeof(nsis_bzstream)); - if (nsis_BZ2_bzDecompressInit(&n->bz, 0, 0) != BZ_OK) + if (nsis_BZ2_bzDecompressInit(&n->bz, 0, 0) != BZ_OK) { return CL_EUNPACK; + } n->freecomp = 1; break; case COMP_LZMA: memset(&n->lz, 0, sizeof(struct CLI_LZMA)); - if (cli_LzmaInit(&n->lz, 0xffffffffffffffffULL) != LZMA_RESULT_OK) + if (cli_LzmaInit(&n->lz, 0xffffffffffffffffULL) != LZMA_RESULT_OK) { return CL_EUNPACK; + } n->freecomp = 1; break; case COMP_ZLIB: @@ -108,8 +110,9 @@ static int nsis_init(struct nsis_st *n) static void nsis_shutdown(struct nsis_st *n) { - if (!n->freecomp) + if (!n->freecomp) { return; + } switch (n->comp) { case COMP_BZIP2: @@ -198,13 +201,15 @@ static int nsis_unpack_next(struct nsis_st *n, cli_ctx *ctx) return CL_BREAK; } - if ((ret = cli_checklimits("NSIS", ctx, 0, 0, 0)) != CL_CLEAN) + if ((ret = cli_checklimits("NSIS", ctx, 0, 0, 0)) != CL_CLEAN) { return ret; + } - if (n->fno) + if (n->fno) { snprintf(n->ofn, 1023, "%s" PATHSEP "content.%.3u", n->dir, n->fno); - else + } else { snprintf(n->ofn, 1023, "%s" PATHSEP "headers", n->dir); + } n->fno++; n->opened = 0; @@ -347,7 +352,9 @@ static int nsis_unpack_next(struct nsis_st *n, cli_ctx *ctx) loops = 0; while ((ret = nsis_decomp(n)) == CL_SUCCESS) { - if (n->nsis.next_out - obuf == 4) break; + if (n->nsis.next_out - obuf == 4) { + break; + } if (++loops > 20) { cli_dbgmsg("NSIS: xs looping, breaking out"__AT__ "\n"); @@ -437,8 +444,12 @@ static int nsis_unpack_next(struct nsis_st *n, cli_ctx *ctx) static uint8_t nsis_detcomp(const char *b) { - if (*b == '1') return COMP_BZIP2; - if ((cli_readint32(b) & ~0x80000000) == 0x5d) return COMP_LZMA; + if (*b == '1') { + return COMP_BZIP2; + } + if ((cli_readint32(b) & ~0x80000000) == 0x5d) { + return COMP_LZMA; + } return COMP_ZLIB; } @@ -449,8 +460,9 @@ static int nsis_headers(struct nsis_st *n, cli_ctx *ctx) int i; uint8_t comps[] = {0, 0, 0, 0}, trunc = 0; - if (!(buf = fmap_need_off_once(n->map, n->off, 0x1c))) + if (!(buf = fmap_need_off_once(n->map, n->off, 0x1c))) { return CL_EREAD; + } n->hsz = (uint32_t)cli_readint32(buf + 0x14); n->asz = (uint32_t)cli_readint32(buf + 0x18); @@ -472,13 +484,19 @@ static int nsis_headers(struct nsis_st *n, cli_ctx *ctx) /* Guess if solid */ for (i = 0, pos = 0; pos < n->asz - 4; i++) { int32_t nextsz; - if (!(buf = fmap_need_ptr_once(n->map, (void *)buf, 4))) return CL_EREAD; + if (!(buf = fmap_need_ptr_once(n->map, (void *)buf, 4))) { + return CL_EREAD; + } nextsz = cli_readint32(buf); - if (!i) n->comp = nsis_detcomp(buf); + if (!i) { + n->comp = nsis_detcomp(buf); + } buf += 4; if (nextsz & 0x80000000) { nextsz &= ~0x80000000; - if (!(buf = fmap_need_ptr_once(n->map, (void *)buf, 4))) return CL_EREAD; + if (!(buf = fmap_need_ptr_once(n->map, (void *)buf, 4))) { + return CL_EREAD; + } comps[nsis_detcomp(buf)]++; nextsz -= 4; pos += 4; @@ -492,7 +510,9 @@ static int nsis_headers(struct nsis_st *n, cli_ctx *ctx) buf += nextsz; } - if (trunc && i >= 2) n->solid = 0; + if (trunc && i >= 2) { + n->solid = 0; + } cli_dbgmsg("NSIS: solid compression%s detected\n", (n->solid) ? "" : " not"); @@ -521,8 +541,9 @@ int cli_scannulsft(cli_ctx *ctx, off_t offset) memset(&nsist, 0, sizeof(struct nsis_st)); nsist.off = offset; - if (!(nsist.dir = cli_gentemp_with_prefix(ctx->sub_tmpdir, "nulsft-tmp"))) + if (!(nsist.dir = cli_gentemp_with_prefix(ctx->sub_tmpdir, "nulsft-tmp"))) { return CL_ETMPDIR; + } if (mkdir(nsist.dir, 0700)) { cli_dbgmsg("NSIS: Can't create temporary directory %s\n", nsist.dir); free(nsist.dir); @@ -530,7 +551,9 @@ int cli_scannulsft(cli_ctx *ctx, off_t offset) } nsist.map = ctx->fmap; - if (ctx->engine->keeptmp) cli_dbgmsg("NSIS: Extracting files to %s\n", nsist.dir); + if (ctx->engine->keeptmp) { + cli_dbgmsg("NSIS: Extracting files to %s\n", nsist.dir); + } do { ret = cli_nsis_unpack(&nsist, ctx); @@ -561,8 +584,9 @@ int cli_scannulsft(cli_ctx *ctx, off_t offset) } } while (ret == CL_SUCCESS); - if (ret == CL_BREAK) + if (ret == CL_BREAK) { ret = CL_CLEAN; + } nsis_shutdown(&nsist); diff --git a/libclamav/ole2_extract.c b/libclamav/ole2_extract.c index 0c0a8bedba..cd628fb37a 100644 --- a/libclamav/ole2_extract.c +++ b/libclamav/ole2_extract.c @@ -252,8 +252,9 @@ ole2_list_pop(ole2_list_t *list) int ole2_list_delete(ole2_list_t *list) { - while (!ole2_list_is_empty(list)) + while (!ole2_list_is_empty(list)) { ole2_list_pop(list); + } return CL_SUCCESS; } @@ -375,8 +376,9 @@ print_ole2_property(property_t *property) buf = get_property_name(property->name, property->name_size); snprintf(spam, sizeof(spam), "OLE2: %s ", buf ? buf : ""); spam[sizeof(spam) - 1] = '\0'; - if (buf) + if (buf) { free(buf); + } switch (property->type) { case 2: strncat(spam, " [file] ", sizeof(spam) - 1 - strlen(spam)); @@ -973,8 +975,9 @@ static int ole2_walk_property_tree(ole2_header_t *hdr, const char *dir, int32_t } ole2_listmsg("printing ole2 property\n"); - if (dir) + if (dir) { print_ole2_property(&prop_block[idx]); + } ole2_listmsg("checking bitset\n"); /* Check we aren't in a loop */ @@ -1091,8 +1094,9 @@ static int ole2_walk_property_tree(ole2_header_t *hdr, const char *dir, int32_t return CL_BREAK; } cli_dbgmsg("OLE2 dir entry: %s\n", dirname); - } else + } else { dirname = NULL; + } if ((int)(prop_block[idx].child) != -1) { ret = ole2_walk_property_tree(hdr, dirname, prop_block[idx].child, handler, rec_level + 1, file_count, ctx, scansize, handler_ctx, pEncryptionStatus); if (ret != CL_SUCCESS) { @@ -1559,11 +1563,13 @@ static cl_error_t handler_enum(ole2_header_t *hdr, property_t *prop, const char } if (!hdr->has_vba) { - if (!name) + if (!name) { name = cli_ole2_get_property_name2(prop->name, prop->name_size); + } if (name) { - if (!strcmp(name, "_vba_project") || !strcmp(name, "powerpoint document") || !strcmp(name, "worddocument") || !strcmp(name, "_1_ole10native")) + if (!strcmp(name, "_vba_project") || !strcmp(name, "powerpoint document") || !strcmp(name, "worddocument") || !strcmp(name, "_1_ole10native")) { hdr->has_vba = 1; + } } } @@ -1581,11 +1587,13 @@ static cl_error_t handler_enum(ole2_header_t *hdr, property_t *prop, const char /* reading safety checks; do-while used for breaks */ do { - if (prop->size == 0) + if (prop->size == 0) { break; + } - if (prop->start_block > hdr->max_block_no) + if (prop->start_block > hdr->max_block_no) { break; + } /* read the header block (~256 bytes) */ offset = 0; @@ -1597,8 +1605,9 @@ static cl_error_t handler_enum(ole2_header_t *hdr, property_t *prop, const char (prop->start_block % (1 << (hdr->log2_big_block_size - hdr->log2_small_block_size))); /* reading safety */ - if (offset + 40 >= 1 << hdr->log2_big_block_size) + if (offset + 40 >= 1 << hdr->log2_big_block_size) { break; + } } else { if (!ole2_read_block(hdr, hwp_check, 1 << hdr->log2_big_block_size, prop->start_block)) { break; @@ -1674,8 +1683,9 @@ likely_mso_stream(int fd) return 0; } - if (check[0] == 0x78 && check[1] == 0x9C) + if (check[0] == 0x78 && check[1] == 0x9C) { return 1; + } return 0; } @@ -1760,8 +1770,9 @@ static cl_error_t scan_mso_stream(int fd, cli_ctx *ctx) ret = CL_EUNPACK; goto mso_end; } - if (bytes_read == 0) + if (bytes_read == 0) { break; + } zstrm.avail_in = bytes_read; off_in += bytes_read; @@ -1769,8 +1780,9 @@ static cl_error_t scan_mso_stream(int fd, cli_ctx *ctx) zret = inflate(&zstrm, Z_SYNC_FLUSH); count = FILEBUFF - zstrm.avail_out; if (count) { - if (cli_checklimits("MSO", ctx, outsize + count, 0, 0) != CL_SUCCESS) + if (cli_checklimits("MSO", ctx, outsize + count, 0, 0) != CL_SUCCESS) { break; + } if (cli_writen(ofd, outbuf, count) != count) { cli_errmsg("scan_mso_stream: Can't write to file %s\n", tmpname); ret = CL_EWRITE; @@ -1808,12 +1820,15 @@ static cl_error_t scan_mso_stream(int fd, cli_ctx *ctx) /* clean-up */ mso_end: zret = inflateEnd(&zstrm); - if (zret != Z_OK) + if (zret != Z_OK) { ret = CL_EUNPACK; + } close(ofd); - if (!ctx->engine->keeptmp) - if (cli_unlink(tmpname)) + if (!ctx->engine->keeptmp) { + if (cli_unlink(tmpname)) { ret = CL_EUNLINK; + } + } free(tmpname); funmap(input); return ret; diff --git a/libclamav/ooxml.c b/libclamav/ooxml.c index 8f7a02319a..977eb81d91 100644 --- a/libclamav/ooxml.c +++ b/libclamav/ooxml.c @@ -121,8 +121,9 @@ static cl_error_t ooxml_parse_document(int fd, cli_ctx *ctx) /* perform engine limit checks in temporary tracking session */ ret = ooxml_updatelimits(fd, ctx); - if (ret != CL_CLEAN) + if (ret != CL_CLEAN) { return ret; + } reader = xmlReaderForFd(fd, "properties.xml", NULL, CLAMAV_MIN_XMLREADER_FLAGS); if (reader == NULL) { @@ -132,8 +133,9 @@ static cl_error_t ooxml_parse_document(int fd, cli_ctx *ctx) ret = cli_msxml_parse_document(ctx, reader, ooxml_keys, num_ooxml_keys, MSXML_FLAG_JSON, NULL); - if (ret != CL_SUCCESS && ret != CL_ETIMEOUT && ret != CL_BREAK) + if (ret != CL_SUCCESS && ret != CL_ETIMEOUT && ret != CL_BREAK) { cli_warnmsg("ooxml_parse_document: encountered issue in parsing properties document\n"); + } xmlTextReaderClose(reader); xmlFreeTextReader(reader); @@ -150,10 +152,11 @@ static cl_error_t ooxml_core_cb(int fd, const char *filepath, cli_ctx *ctx, cons cli_dbgmsg("in ooxml_core_cb\n"); ret = ooxml_parse_document(fd, ctx); - if (ret == CL_EPARSE) + if (ret == CL_EPARSE) { cli_json_parse_error(ctx->wrkproperty, "OOXML_ERROR_CORE_XMLPARSER"); - else if (ret == CL_EFORMAT) + } else if (ret == CL_EFORMAT) { cli_json_parse_error(ctx->wrkproperty, "OOXML_ERROR_CORE_MALFORMED"); + } return ret; } @@ -168,10 +171,11 @@ static cl_error_t ooxml_extn_cb(int fd, const char *filepath, cli_ctx *ctx, cons cli_dbgmsg("in ooxml_extn_cb\n"); ret = ooxml_parse_document(fd, ctx); - if (ret == CL_EPARSE) + if (ret == CL_EPARSE) { cli_json_parse_error(ctx->wrkproperty, "OOXML_ERROR_EXTN_XMLPARSER"); - else if (ret == CL_EFORMAT) + } else if (ret == CL_EFORMAT) { cli_json_parse_error(ctx->wrkproperty, "OOXML_ERROR_EXTN_MALFORMED"); + } return ret; } @@ -197,8 +201,9 @@ static cl_error_t ooxml_content_cb(int fd, const char *filepath, cli_ctx *ctx, c /* perform engine limit checks in temporary tracking session */ ret = ooxml_updatelimits(fd, ctx); - if (ret != CL_CLEAN) + if (ret != CL_CLEAN) { return ret; + } /* apply a reader to the document */ reader = xmlReaderForFd(fd, "[Content_Types].xml", NULL, CLAMAV_MIN_XMLREADER_FLAGS); @@ -221,17 +226,25 @@ static cl_error_t ooxml_content_cb(int fd, const char *filepath, cli_ctx *ctx, c } localname = xmlTextReaderConstLocalName(reader); - if (localname == NULL) continue; + if (localname == NULL) { + continue; + } - if (strcmp((const char *)localname, "Override")) continue; + if (strcmp((const char *)localname, "Override")) { + continue; + } - if (xmlTextReaderHasAttributes(reader) != 1) continue; + if (xmlTextReaderHasAttributes(reader) != 1) { + continue; + } CT = PN = NULL; while (xmlTextReaderMoveToNextAttribute(reader) == 1) { localname = xmlTextReaderConstLocalName(reader); value = xmlTextReaderConstValue(reader); - if (localname == NULL || value == NULL) continue; + if (localname == NULL || value == NULL) { + continue; + } if (!xmlStrcmp(localname, (const xmlChar *)"ContentType")) { CT = value; @@ -242,7 +255,9 @@ static cl_error_t ooxml_content_cb(int fd, const char *filepath, cli_ctx *ctx, c cli_dbgmsg("%s: %s\n", localname, value); } - if (!CT || !PN) continue; + if (!CT || !PN) { + continue; + } if (!xmlStrcmp(CT, (const xmlChar *)"application/vnd.openxmlformats-package.core-properties+xml")) { /* default: /docProps/core.xml*/ @@ -297,17 +312,20 @@ static cl_error_t ooxml_content_cb(int fd, const char *filepath, cli_ctx *ctx, c dsig++; } - if (ret != CL_SUCCESS) + if (ret != CL_SUCCESS) { goto ooxml_content_exit; + } } ooxml_content_exit: if (core) { cli_jsonint(ctx->wrkproperty, "CorePropertiesFileCount", core); - if (core > 1) + if (core > 1) { cli_json_parse_error(ctx->wrkproperty, "OOXML_ERROR_MULTIPLE_CORE_PROPFILES"); - } else if (!mcore) + } + } else if (!mcore) { cli_dbgmsg("cli_process_ooxml: file does not contain core properties file\n"); + } if (mcore) { cli_jsonint(ctx->wrkproperty, "CorePropertiesMissingFileCount", mcore); cli_json_parse_error(ctx->wrkproperty, "OOXML_ERROR_MISSING_CORE_PROPFILES"); @@ -315,10 +333,12 @@ static cl_error_t ooxml_content_cb(int fd, const char *filepath, cli_ctx *ctx, c if (extn) { cli_jsonint(ctx->wrkproperty, "ExtendedPropertiesFileCount", extn); - if (extn > 1) + if (extn > 1) { cli_json_parse_error(ctx->wrkproperty, "OOXML_ERROR_MULTIPLE_EXTN_PROPFILES"); - } else if (!mextn) + } + } else if (!mextn) { cli_dbgmsg("cli_process_ooxml: file does not contain extended properties file\n"); + } if (mextn) { cli_jsonint(ctx->wrkproperty, "ExtendedPropertiesMissingFileCount", mextn); cli_json_parse_error(ctx->wrkproperty, "OOXML_ERROR_MISSING_EXTN_PROPFILES"); @@ -326,10 +346,12 @@ static cl_error_t ooxml_content_cb(int fd, const char *filepath, cli_ctx *ctx, c if (cust) { cli_jsonint(ctx->wrkproperty, "CustomPropertiesFileCount", cust); - if (cust > 1) + if (cust > 1) { cli_json_parse_error(ctx->wrkproperty, "OOXML_ERROR_MULTIPLE_CUSTOM_PROPFILES"); - } else if (!mcust) + } + } else if (!mcust) { cli_dbgmsg("cli_process_ooxml: file does not contain custom properties file\n"); + } if (mcust) { cli_jsonint(ctx->wrkproperty, "CustomPropertiesMissingFileCount", mcust); cli_json_parse_error(ctx->wrkproperty, "OOXML_ERROR_MISSING_CUST_PROPFILES"); @@ -361,8 +383,9 @@ static cl_error_t ooxml_hwp_cb(int fd, const char *filepath, cli_ctx *ctx, const /* perform engine limit checks in temporary tracking session */ ret = ooxml_updatelimits(fd, ctx); - if (ret != CL_CLEAN) + if (ret != CL_CLEAN) { return ret; + } reader = xmlReaderForFd(fd, "ooxml_hwp.xml", NULL, CLAMAV_MIN_XMLREADER_FLAGS); if (reader == NULL) { @@ -372,8 +395,9 @@ static cl_error_t ooxml_hwp_cb(int fd, const char *filepath, cli_ctx *ctx, const ret = cli_msxml_parse_document(ctx, reader, ooxml_hwp_keys, num_ooxml_hwp_keys, MSXML_FLAG_JSON, NULL); - if (ret != CL_SUCCESS && ret != CL_ETIMEOUT && ret != CL_BREAK) + if (ret != CL_SUCCESS && ret != CL_ETIMEOUT && ret != CL_BREAK) { cli_warnmsg("ooxml_hwp_cb: encountered issue in parsing properties document\n"); + } xmlTextReaderClose(reader); xmlFreeTextReader(reader); diff --git a/libclamav/openioc.c b/libclamav/openioc.c index 13acb0e055..79378c2f8f 100644 --- a/libclamav/openioc.c +++ b/libclamav/openioc.c @@ -44,8 +44,9 @@ struct openioc_hash { static const xmlChar *openioc_read(xmlTextReaderPtr reader) { const xmlChar *name; - if (xmlTextReaderRead(reader) != 1) + if (xmlTextReaderRead(reader) != 1) { return NULL; + } name = xmlTextReaderConstLocalName(reader); if (name != NULL) { cli_dbgmsg("openioc_parse: xmlTextReaderRead read %s%s\n", name, @@ -64,12 +65,15 @@ static int openioc_is_context_hash(xmlTextReaderPtr reader) !xmlStrcmp(document, (const xmlChar *)"FileItem") && (!xmlStrcmp(search, (const xmlChar *)"FileItem/Md5sum") || !xmlStrcmp(search, (const xmlChar *)"FileItem/Sha1sum") || - !xmlStrcmp(search, (const xmlChar *)"FileItem/Sha256sum"))) + !xmlStrcmp(search, (const xmlChar *)"FileItem/Sha256sum"))) { rc = 1; - if (document != NULL) + } + if (document != NULL) { xmlFree(document); - if (search != NULL) + } + if (search != NULL) { xmlFree(search); + } return rc; } @@ -124,8 +128,9 @@ static int openioc_parse_indicatoritem(xmlTextReaderPtr reader, struct openioc_h while (1) { name = openioc_read(reader); - if (name == NULL) + if (name == NULL) { break; + } if (xmlStrEqual(name, (const xmlChar *)"Context") && xmlTextReaderNodeType(reader) == XML_READER_TYPE_ELEMENT) { context_hash = openioc_is_context_hash(reader); @@ -150,8 +155,9 @@ static int openioc_parse_indicator(xmlTextReaderPtr reader, struct openioc_hash while (1) { name = openioc_read(reader); - if (name == NULL) + if (name == NULL) { return rc; + } if (xmlStrEqual(name, (const xmlChar *)"Indicator") && xmlTextReaderNodeType(reader) == XML_READER_TYPE_ELEMENT) { rc = openioc_parse_indicator(reader, elems); @@ -184,11 +190,13 @@ int openioc_parse(const char *fname, int fd, struct cl_engine *engine, unsigned char *virusname; int hash_count = 0; - if (fname == NULL) + if (fname == NULL) { return CL_ENULLARG; + } - if (fd < 0) + if (fd < 0) { return CL_EARG; + } cli_dbgmsg("openioc_parse: XML parsing file %s\n", fname); @@ -219,10 +227,11 @@ int openioc_parse(const char *fname, int fd, struct cl_engine *engine, unsigned iocp = strrchr(fname, *PATHSEP); - if (NULL == iocp) + if (NULL == iocp) { iocp = fname; - else + } else { iocp++; + } ioclen = (uint16_t)strlen(fname); @@ -248,8 +257,9 @@ int openioc_parse(const char *fname, int fd, struct cl_engine *engine, unsigned elem = elems; elems = elems->next; hash = (char *)(elem->hash); - while (isspace(*hash)) + while (isspace(*hash)) { hash++; + } hashlen = strlen(hash); if (hashlen == 0) { xmlFree(elem->hash); @@ -285,10 +295,11 @@ int openioc_parse(const char *fname, int fd, struct cl_engine *engine, unsigned *vp = '_'; break; default: - if (isspace(*sp)) + if (isspace(*sp)) { *vp = '_'; - else + } else { *vp = *sp; + } } } *vp++ = '.'; @@ -312,21 +323,23 @@ int openioc_parse(const char *fname, int fd, struct cl_engine *engine, unsigned free(vp); rc = hm_addhash_str(engine->hm_hdb, hash, 0, virusname); - if (rc != CL_SUCCESS) + if (rc != CL_SUCCESS) { cli_dbgmsg("openioc_parse: hm_addhash_str failed with %i hash len %i for %s.\n", rc, hashlen, virusname); - else + } else { hash_count++; + } xmlFree(elem->hash); free(elem); } - if (hash_count == 0) + if (hash_count == 0) { cli_warnmsg("openioc_parse: No hash signatures extracted from %s.\n", fname); - else + } else { cli_dbgmsg("openioc_parse: %i hash signature%s extracted from %s.\n", hash_count, hash_count == 1 ? "" : "s", fname); + } xmlTextReaderClose(reader); xmlFreeTextReader(reader); diff --git a/libclamav/others.c b/libclamav/others.c index 7c026c5f2c..c5e8064840 100644 --- a/libclamav/others.c +++ b/libclamav/others.c @@ -155,7 +155,7 @@ static void *load_module(const char *name, const char *featurename) LT_MODULE_EXT "." LIBCLAMAV_FULLVER, PASTE(LT_MODULE_EXT ".", LIBCLAMAV_MAJORVER), LT_MODULE_EXT, - "." LT_LIBEXT}; + ".", LT_LIBEXT}; void *rhandle = NULL; char *tokenized_library_path = NULL; char *ld_library_path = NULL; @@ -310,10 +310,14 @@ static void rarload(void) #endif #endif - if (is_rar_inited) return; + if (is_rar_inited) { + return; + } is_rar_inited = 1; - if (have_rar) return; + if (have_rar) { + return; + } #ifdef UNRAR_LINKED cli_unrar_open = unrar_open; @@ -323,8 +327,9 @@ static void rarload(void) cli_unrar_close = unrar_close; #else rhandle = load_module("libclamunrar_iface", "unrar"); - if (NULL == rhandle) + if (NULL == rhandle) { return; + } if ((NULL == (cli_unrar_open = (cl_unrar_error_t(*)(const char *, void **, char **, uint32_t *, uint8_t))get_module_function(rhandle, "libclamunrar_iface_LTX_unrar_open"))) || (NULL == (cli_unrar_peek_file_header = (cl_unrar_error_t(*)(void *, unrar_metadata_t *))get_module_function(rhandle, "libclamunrar_iface_LTX_unrar_peek_file_header"))) || @@ -458,8 +463,9 @@ cl_error_t cl_init(unsigned int initoptions) gettimeofday(&tv, (struct timezone *)0); srand(pid + tv.tv_usec * (pid + 1) + clock()); rc = bytecode_init(); - if (rc) + if (rc) { return rc; + } xmlInitParser(); @@ -653,8 +659,9 @@ struct cl_engine *cl_engine_new(void) cl_error_t cl_engine_set_num(struct cl_engine *engine, enum cl_engine_field field, long long num) { - if (!engine) + if (!engine) { return CL_ENULLARG; + } /* TODO: consider adding checks and warn/errs when num overflows the * destination type @@ -683,8 +690,9 @@ cl_error_t cl_engine_set_num(struct cl_engine *engine, enum cl_engine_field fiel if (!num) { cli_warnmsg("MaxRecursion: the value of 0 is not allowed, using default: %u\n", CLI_DEFAULT_MAXRECLEVEL); engine->max_recursion_level = CLI_DEFAULT_MAXRECLEVEL; - } else + } else { engine->max_recursion_level = num; + } break; case CL_ENGINE_MAX_FILES: engine->maxfiles = num; @@ -693,36 +701,41 @@ cl_error_t cl_engine_set_num(struct cl_engine *engine, enum cl_engine_field fiel if (num < 0) { cli_warnmsg("MaxEmbeddedPE: negative values are not allowed, using default: %u\n", CLI_DEFAULT_MAXEMBEDDEDPE); engine->maxembeddedpe = CLI_DEFAULT_MAXEMBEDDEDPE; - } else + } else { engine->maxembeddedpe = num; + } break; case CL_ENGINE_MAX_HTMLNORMALIZE: if (num < 0) { cli_warnmsg("MaxHTMLNormalize: negative values are not allowed, using default: %u\n", CLI_DEFAULT_MAXHTMLNORMALIZE); engine->maxhtmlnormalize = CLI_DEFAULT_MAXHTMLNORMALIZE; - } else + } else { engine->maxhtmlnormalize = num; + } break; case CL_ENGINE_MAX_HTMLNOTAGS: if (num < 0) { cli_warnmsg("MaxHTMLNoTags: negative values are not allowed, using default: %u\n", CLI_DEFAULT_MAXHTMLNOTAGS); engine->maxhtmlnotags = CLI_DEFAULT_MAXHTMLNOTAGS; - } else + } else { engine->maxhtmlnotags = num; + } break; case CL_ENGINE_MAX_SCRIPTNORMALIZE: if (num < 0) { cli_warnmsg("MaxScriptNormalize: negative values are not allowed, using default: %u\n", CLI_DEFAULT_MAXSCRIPTNORMALIZE); engine->maxscriptnormalize = CLI_DEFAULT_MAXSCRIPTNORMALIZE; - } else + } else { engine->maxscriptnormalize = num; + } break; case CL_ENGINE_MAX_ZIPTYPERCG: if (num < 0) { cli_warnmsg("MaxZipTypeRcg: negative values are not allowed, using default: %u\n", CLI_DEFAULT_MAXZIPTYPERCG); engine->maxziptypercg = CLI_DEFAULT_MAXZIPTYPERCG; - } else + } else { engine->maxziptypercg = num; + } break; case CL_ENGINE_MIN_CC_COUNT: engine->min_cc_count = num; @@ -748,10 +761,11 @@ cl_error_t cl_engine_set_num(struct cl_engine *engine, enum cl_engine_field fiel engine->keeptmp = num; break; case CL_ENGINE_FORCETODISK: - if (num) + if (num) { engine->engine_options |= ENGINE_OPTIONS_FORCE_TO_DISK; - else + } else { engine->engine_options &= ~(ENGINE_OPTIONS_FORCE_TO_DISK); + } break; case CL_ENGINE_BYTECODE_SECURITY: if (engine->dboptions & CL_DB_COMPILED) { @@ -773,16 +787,18 @@ cl_error_t cl_engine_set_num(struct cl_engine *engine, enum cl_engine_field fiel return CL_EARG; } engine->bytecode_mode = num; - if (num == CL_BYTECODE_MODE_TEST) + if (num == CL_BYTECODE_MODE_TEST) { cli_infomsg(NULL, "bytecode engine in test mode\n"); + } break; case CL_ENGINE_DISABLE_CACHE: if (num) { engine->engine_options |= ENGINE_OPTIONS_DISABLE_CACHE; } else { engine->engine_options &= ~(ENGINE_OPTIONS_DISABLE_CACHE); - if (!(engine->cache)) + if (!(engine->cache)) { clean_cache_init(engine); + } } break; case CL_ENGINE_CACHE_SIZE: @@ -851,13 +867,15 @@ long long cl_engine_get_num(const struct cl_engine *engine, enum cl_engine_field { if (!engine) { cli_errmsg("cl_engine_get_num: engine == NULL\n"); - if (err) + if (err) { *err = CL_ENULLARG; + } return -1; } - if (err) + if (err) { *err = CL_SUCCESS; + } switch (field) { case CL_ENGINE_DB_OPTIONS: @@ -926,16 +944,18 @@ long long cl_engine_get_num(const struct cl_engine *engine, enum cl_engine_field return engine->pcre_max_filesize; default: cli_errmsg("cl_engine_get: Incorrect field number\n"); - if (err) + if (err) { *err = CL_EARG; + } return -1; } } cl_error_t cl_engine_set_str(struct cl_engine *engine, enum cl_engine_field field, const char *str) { - if (!engine) + if (!engine) { return CL_ENULLARG; + } switch (field) { case CL_ENGINE_PUA_CATEGORIES: @@ -944,8 +964,9 @@ cl_error_t cl_engine_set_str(struct cl_engine *engine, enum cl_engine_field fiel engine->pua_cats = NULL; } engine->pua_cats = CLI_MPOOL_STRDUP(engine->mempool, str); - if (NULL == engine->pua_cats) + if (NULL == engine->pua_cats) { return CL_EMEM; + } break; case CL_ENGINE_TMPDIR: if (NULL != engine->tmpdir) { @@ -953,8 +974,9 @@ cl_error_t cl_engine_set_str(struct cl_engine *engine, enum cl_engine_field fiel engine->tmpdir = NULL; } engine->tmpdir = CLI_MPOOL_STRDUP(engine->mempool, str); - if (NULL == engine->tmpdir) + if (NULL == engine->tmpdir) { return CL_EMEM; + } break; case CL_ENGINE_CVDCERTSDIR: if (NULL != engine->certs_directory) { @@ -962,8 +984,9 @@ cl_error_t cl_engine_set_str(struct cl_engine *engine, enum cl_engine_field fiel engine->certs_directory = NULL; } engine->certs_directory = CLI_MPOOL_STRDUP(engine->mempool, str); - if (NULL == engine->certs_directory) + if (NULL == engine->certs_directory) { return CL_EMEM; + } break; default: cli_errmsg("cl_engine_set_num: Incorrect field number\n"); @@ -977,13 +1000,15 @@ const char *cl_engine_get_str(const struct cl_engine *engine, enum cl_engine_fie { if (!engine) { cli_errmsg("cl_engine_get_str: engine == NULL\n"); - if (err) + if (err) { *err = CL_ENULLARG; + } return NULL; } - if (err) + if (err) { *err = CL_SUCCESS; + } switch (field) { case CL_ENGINE_PUA_CATEGORIES: @@ -994,8 +1019,9 @@ const char *cl_engine_get_str(const struct cl_engine *engine, enum cl_engine_fie return engine->certs_directory; default: cli_errmsg("cl_engine_get: Incorrect field number\n"); - if (err) + if (err) { *err = CL_EARG; + } return NULL; } } @@ -1096,22 +1122,26 @@ cl_error_t cl_engine_settings_apply(struct cl_engine *engine, const struct cl_se engine->engine_options = settings->engine_options; engine->cache_size = settings->cache_size; - if (engine->tmpdir) + if (engine->tmpdir) { MPOOL_FREE(engine->mempool, engine->tmpdir); + } if (settings->tmpdir) { engine->tmpdir = CLI_MPOOL_STRDUP(engine->mempool, settings->tmpdir); - if (!engine->tmpdir) + if (!engine->tmpdir) { return CL_EMEM; + } } else { engine->tmpdir = NULL; } - if (engine->pua_cats) + if (engine->pua_cats) { MPOOL_FREE(engine->mempool, engine->pua_cats); + } if (settings->pua_cats) { engine->pua_cats = CLI_MPOOL_STRDUP(engine->mempool, settings->pua_cats); - if (!engine->pua_cats) + if (!engine->pua_cats) { return CL_EMEM; + } } else { engine->pua_cats = NULL; } @@ -1155,8 +1185,9 @@ cl_error_t cl_engine_settings_apply(struct cl_engine *engine, const struct cl_se cl_error_t cl_engine_settings_free(struct cl_settings *settings) { - if (!settings) + if (!settings) { return CL_ENULLARG; + } free(settings->tmpdir); free(settings->pua_cats); @@ -1250,8 +1281,9 @@ cl_error_t cli_updatelimits(cli_ctx *ctx, size_t needed) ctx->scannedfiles++; ctx->scansize += needed; - if (ctx->scansize > ctx->engine->maxscansize) + if (ctx->scansize > ctx->engine->maxscansize) { ctx->scansize = ctx->engine->maxscansize; + } return CL_SUCCESS; } @@ -1321,16 +1353,19 @@ char *cli_hashstream(FILE *fs, unsigned char *digcpy, int type) } ctx = cl_hash_init(alg); - if (!(ctx)) + if (!(ctx)) { return NULL; + } - while ((bytes = fread(buff, 1, FILEBUFF, fs))) + while ((bytes = fread(buff, 1, FILEBUFF, fs))) { cl_update_hash(ctx, buff, bytes); + } cl_finish_hash(ctx, digest); - if (!(hashstr = (char *)calloc(size * 2 + 1, sizeof(char)))) + if (!(hashstr = (char *)calloc(size * 2 + 1, sizeof(char)))) { return NULL; + } pt = hashstr; for (i = 0; i < size; i++) { @@ -1338,8 +1373,9 @@ char *cli_hashstream(FILE *fs, unsigned char *digcpy, int type) pt += 2; } - if (digcpy) + if (digcpy) { memcpy(digcpy, digest, size); + } return hashstr; } @@ -1779,7 +1815,9 @@ int cli_rmdirs(const char *dirname) chmod(dirname, 0700); if ((dd = opendir(dirname)) != NULL) { while (CLAMSTAT(dirname, &maind) != -1) { - if (!rmdir(dirname)) break; + if (!rmdir(dirname)) { + break; + } if (errno != ENOTEMPTY && errno != EEXIST && errno != EBADF) { cli_errmsg("cli_rmdirs: Can't remove temporary directory %s: %s\n", dirname, cli_strerror(errno, err, sizeof(err))); closedir(dd); diff --git a/libclamav/others_common.c b/libclamav/others_common.c index 1458b7d537..762e0944cb 100644 --- a/libclamav/others_common.c +++ b/libclamav/others_common.c @@ -518,8 +518,9 @@ int cli_filecopy(const char *src, const char *dest) int s, d; size_t bytes; - if ((s = open(src, O_RDONLY | O_BINARY)) == -1) + if ((s = open(src, O_RDONLY | O_BINARY)) == -1) { return -1; + } if ((d = open(dest, O_CREAT | O_WRONLY | O_TRUNC | O_BINARY, S_IRUSR | S_IWUSR)) == -1) { close(s); @@ -564,9 +565,11 @@ const char *cli_gettmpdir(void) char *envs[] = {"TMPDIR", NULL}; #endif - for (i = 0; envs[i] != NULL; i++) - if ((tmpdir = getenv(envs[i]))) + for (i = 0; envs[i] != NULL; i++) { + if ((tmpdir = getenv(envs[i]))) { return tmpdir; + } + } return P_tmpdir; } @@ -621,8 +624,9 @@ static int get_filetype(const char *fname, int flags, int need_stat, * to lstat(), we can just stat() directly.*/ if (*ft != ft_link) { /* need to lstat to determine if it is a symlink */ - if (LSTAT(fname, statbuf) == -1) + if (LSTAT(fname, statbuf) == -1) { return -1; + } if (S_ISLNK(statbuf->st_mode)) { *ft = ft_link; } else { @@ -640,8 +644,9 @@ static int get_filetype(const char *fname, int flags, int need_stat, } if (need_stat) { - if (CLAMSTAT(fname, statbuf) == -1) + if (CLAMSTAT(fname, statbuf) == -1) { return -1; + } stated = 1; } @@ -709,8 +714,9 @@ static cl_error_t handle_filetype(const char *fname, int flags, fname, *ft == ft_skipped_link ? warning_skipped_link : warning_skipped_special, data); - if (status != CL_SUCCESS) + if (status != CL_SUCCESS) { goto done; + } } status = CL_SUCCESS; @@ -744,10 +750,14 @@ cl_error_t cli_ftw(char *path, int flags, int maxdepth, cli_ftw_cb callback, str /* trim slashes so that dir and dir/ behave the same when * they are symlinks, and we are not following symlinks */ #ifndef _WIN32 - while (path[0] == *PATHSEP && path[1] == *PATHSEP) path++; + while (path[0] == *PATHSEP && path[1] == *PATHSEP) { + path++; + } #endif pathend = path + strlen(path); - while (pathend > path && pathend[-1] == *PATHSEP) --pathend; + while (pathend > path && pathend[-1] == *PATHSEP) { + --pathend; + } *pathend = '\0'; } @@ -847,8 +857,9 @@ static cl_error_t cli_ftw_dir(const char *dirname, int flags, int maxdepth, cli_ STATBUF statbuf; STATBUF *statbufp; - if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, "..")) + if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, "..")) { continue; + } #ifdef _DIRENT_HAVE_D_TYPE switch (dent->d_type) { case DT_DIR: @@ -879,14 +890,16 @@ static cl_error_t cli_ftw_dir(const char *dirname, int flags, int maxdepth, cli_ fname = (char *)cli_max_malloc(strlen(dirname) + strlen(dent->d_name) + 2); if (!fname) { ret = callback(NULL, NULL, dirname, error_mem, data); - if (ret != CL_SUCCESS) + if (ret != CL_SUCCESS) { break; + } continue; /* have to skip this one if continuing after error */ } - if (!strcmp(dirname, PATHSEP)) + if (!strcmp(dirname, PATHSEP)) { sprintf(fname, PATHSEP "%s", dent->d_name); - else + } else { sprintf(fname, "%s" PATHSEP "%s", dirname, dent->d_name); + } if (pathchk && pathchk(fname, data) == 1) { free(fname); @@ -910,9 +923,9 @@ static cl_error_t cli_ftw_dir(const char *dirname, int flags, int maxdepth, cli_ if (!statbufp) { ret = callback(stated ? &statbuf : NULL, NULL, fname, error_mem, data); free(fname); - if (ret != CL_SUCCESS) + if (ret != CL_SUCCESS) { break; - else { + } else { errno = 0; continue; } @@ -927,8 +940,9 @@ static cl_error_t cli_ftw_dir(const char *dirname, int flags, int maxdepth, cli_ if (!entries) { ret = callback(stated ? &statbuf : NULL, NULL, fname, error_mem, data); free(fname); - if (statbufp) + if (statbufp) { free(statbufp); + } break; } else { struct dirent_data *entry = &entries[entries_cnt - 1]; @@ -952,10 +966,12 @@ static cl_error_t cli_ftw_dir(const char *dirname, int flags, int maxdepth, cli_ for (i = 0; i < entries_cnt; i++) { struct dirent_data *entry = &entries[i]; ret = handle_entry(entry, flags, maxdepth - 1, callback, data, pathchk); - if (entry->is_dir) + if (entry->is_dir) { free(entry->filename); - if (entry->statbuf) + } + if (entry->statbuf) { free(entry->statbuf); + } if (ret != CL_SUCCESS) { /* Something went horribly wrong, Skip the rest of the files */ cli_errmsg("File tree walk aborted.\n"); @@ -1001,11 +1017,13 @@ static char *cli_md5buff(const unsigned char *buffer, unsigned int len, unsigned cl_hash_data("md5", buffer, len, digest, NULL); - if (dig) + if (dig) { memcpy(dig, digest, 16); + } - if (!(md5str = (char *)cli_max_calloc(32 + 1, sizeof(char)))) + if (!(md5str = (char *)cli_max_calloc(32 + 1, sizeof(char)))) { return NULL; + } pt = md5str; for (i = 0; i < 16; i++) { @@ -1211,8 +1229,9 @@ char *cli_genfname(const char *prefix) memcpy(salt, name_salt, 16); - for (i = 16; i < 48; i++) + for (i = 16; i < 48; i++) { salt[i] = cli_rndnum(255); + } tmp = cli_md5buff(salt, 48, name_salt); @@ -1338,8 +1357,9 @@ cl_error_t cli_gentempfd(const char *dir, char **name, int *fd) cl_error_t cli_gentempfd_with_prefix(const char *dir, const char *prefix, char **name, int *fd) { *name = cli_gentemp_with_prefix(dir, prefix); - if (!*name) + if (!*name) { return CL_EMEM; + } *fd = open(*name, O_RDWR | O_CREAT | O_TRUNC | O_BINARY | O_EXCL, S_IRUSR | S_IWUSR); /* @@ -1351,8 +1371,9 @@ cl_error_t cli_gentempfd_with_prefix(const char *dir, const char *prefix, char * cli_dbgmsg("cli_gentempfd_with_prefix: Can't create temp file using prefix. Using a randomly generated name instead.\n"); free(*name); *name = cli_gentemp(dir); - if (!*name) + if (!*name) { return CL_EMEM; + } *fd = open(*name, O_RDWR | O_CREAT | O_TRUNC | O_BINARY | O_EXCL, S_IRUSR | S_IWUSR); if (*fd == -1) { cli_errmsg("cli_gentempfd_with_prefix: Can't create temporary file %s: %s\n", *name, strerror(errno)); diff --git a/libclamav/packlibs.c b/libclamav/packlibs.c index 1cceb75462..02759b5cd9 100644 --- a/libclamav/packlibs.c +++ b/libclamav/packlibs.c @@ -36,8 +36,9 @@ static int doubledl(const char **scur, uint8_t *mydlptr, const char *buffer, uin mydl *= 2; if (!(olddl & 0x7f)) { - if (*scur < buffer || *scur >= buffer + buffersize - 1) + if (*scur < buffer || *scur >= buffer + buffersize - 1) { return -1; + } olddl = **scur; mydl = olddl * 2 + 1; *scur = *scur + 1; @@ -54,49 +55,58 @@ int cli_unfsg(const char *source, char *dest, int ssize, int dsize, const char * char *cdst = dest; int oob, lostbit = 1; - if (ssize <= 0 || dsize <= 0) return -1; + if (ssize <= 0 || dsize <= 0) { + return -1; + } *cdst++ = *csrc++; while (1) { if ((oob = doubledl(&csrc, &mydl, source, ssize))) { - if (oob == -1) + if (oob == -1) { return -1; + } /* 164 */ backsize = 0; if ((oob = doubledl(&csrc, &mydl, source, ssize))) { - if (oob == -1) + if (oob == -1) { return -1; + } /* 16a */ backbytes = 0; if ((oob = doubledl(&csrc, &mydl, source, ssize))) { - if (oob == -1) + if (oob == -1) { return -1; + } /* 170 */ lostbit = 1; backsize++; backbytes = 0x10; while (backbytes < 0x100) { - if ((oob = doubledl(&csrc, &mydl, source, ssize)) == -1) + if ((oob = doubledl(&csrc, &mydl, source, ssize)) == -1) { return -1; + } backbytes = backbytes * 2 + oob; } backbytes &= 0xff; if (!backbytes) { - if (cdst >= dest + dsize) + if (cdst >= dest + dsize) { return -1; + } *cdst++ = 0x00; continue; } } else { /* 18f */ - if (csrc >= source + ssize) + if (csrc >= source + ssize) { return -1; + } backbytes = *(unsigned char *)csrc; backsize = backsize * 2 + (backbytes & 1); backbytes = (backbytes & 0xff) >> 1; csrc++; - if (!backbytes) + if (!backbytes) { break; + } backsize += 2; oldback = backbytes; lostbit = 0; @@ -105,11 +115,13 @@ int cli_unfsg(const char *source, char *dest, int ssize, int dsize, const char * /* 180 */ backsize = 1; do { - if ((oob = doubledl(&csrc, &mydl, source, ssize)) == -1) + if ((oob = doubledl(&csrc, &mydl, source, ssize)) == -1) { return -1; + } backsize = backsize * 2 + oob; - if ((oob = doubledl(&csrc, &mydl, source, ssize)) == -1) + if ((oob = doubledl(&csrc, &mydl, source, ssize)) == -1) { return -1; + } } while (oob); backsize = backsize - 1 - lostbit; @@ -117,43 +129,52 @@ int cli_unfsg(const char *source, char *dest, int ssize, int dsize, const char * /* 18a */ backsize = 1; do { - if ((oob = doubledl(&csrc, &mydl, source, ssize)) == -1) + if ((oob = doubledl(&csrc, &mydl, source, ssize)) == -1) { return -1; + } backsize = backsize * 2 + oob; - if ((oob = doubledl(&csrc, &mydl, source, ssize)) == -1) + if ((oob = doubledl(&csrc, &mydl, source, ssize)) == -1) { return -1; + } } while (oob); backbytes = oldback; } else { /* 198 */ - if (csrc >= source + ssize) + if (csrc >= source + ssize) { return -1; + } backbytes = *(unsigned char *)csrc; backbytes += (backsize - 1) << 8; backsize = 1; csrc++; do { - if ((oob = doubledl(&csrc, &mydl, source, ssize)) == -1) + if ((oob = doubledl(&csrc, &mydl, source, ssize)) == -1) { return -1; + } backsize = backsize * 2 + oob; - if ((oob = doubledl(&csrc, &mydl, source, ssize)) == -1) + if ((oob = doubledl(&csrc, &mydl, source, ssize)) == -1) { return -1; + } } while (oob); - if (backbytes >= 0x7d00) + if (backbytes >= 0x7d00) { backsize++; - if (backbytes >= 0x500) + } + if (backbytes >= 0x500) { backsize++; - if (backbytes <= 0x7f) + } + if (backbytes <= 0x7f) { backsize += 2; + } oldback = backbytes; } lostbit = 0; } - if (!CLI_ISCONTAINED(dest, dsize, cdst, backsize) || !CLI_ISCONTAINED(dest, dsize, cdst - backbytes, backsize)) + if (!CLI_ISCONTAINED(dest, dsize, cdst, backsize) || !CLI_ISCONTAINED(dest, dsize, cdst - backbytes, backsize)) { return -1; + } while (backsize--) { *cdst = *(cdst - backbytes); cdst++; @@ -161,15 +182,20 @@ int cli_unfsg(const char *source, char *dest, int ssize, int dsize, const char * } else { /* 15d */ - if (cdst < dest || cdst >= dest + dsize || csrc < source || csrc >= source + ssize) + if (cdst < dest || cdst >= dest + dsize || csrc < source || csrc >= source + ssize) { return -1; + } *cdst++ = *csrc++; lostbit = 1; } } - if (endsrc) *endsrc = csrc; - if (enddst) *enddst = cdst; + if (endsrc) { + *endsrc = csrc; + } + if (enddst) { + *enddst = cdst; + } return 0; } @@ -185,39 +211,45 @@ int unmew(const char *source, char *dest, int ssize, int dsize, const char **end while (1) { if ((oob = doubledl(&csrc, &mydl, source, ssize))) { - if (oob == -1) + if (oob == -1) { return -1; + } /* 164 */ myecx_backsize = 0; if ((oob = doubledl(&csrc, &mydl, source, ssize))) { - if (oob == -1) + if (oob == -1) { return -1; + } /* 16a */ myeax_backbytes = 0; if ((oob = doubledl(&csrc, &mydl, source, ssize))) { - if (oob == -1) + if (oob == -1) { return -1; + } /* 170 */ lostbit = 1; myecx_backsize++; myeax_backbytes = 0x10; while (myeax_backbytes < 0x100) { - if ((oob = doubledl(&csrc, &mydl, source, ssize)) == -1) + if ((oob = doubledl(&csrc, &mydl, source, ssize)) == -1) { return -1; + } myeax_backbytes = myeax_backbytes * 2 + oob; } myeax_backbytes &= 0xff; if (!myeax_backbytes) { - if (cdst >= dest + dsize) + if (cdst >= dest + dsize) { return -1; + } *cdst++ = 0x00; /*cli_dbgmsg("X%02x ", *(cdst-1)&0xff);*/ continue; } } else { /* 18f */ - if (csrc >= source + ssize) + if (csrc >= source + ssize) { return -1; + } myeax_backbytes = *(unsigned char *)csrc; myecx_backsize = myecx_backsize * 2 + (myeax_backbytes & 1); myeax_backbytes = (myeax_backbytes & 0xff) >> 1; @@ -234,11 +266,13 @@ int unmew(const char *source, char *dest, int ssize, int dsize, const char **end /* 180 */ myecx_backsize = 1; do { - if ((oob = doubledl(&csrc, &mydl, source, ssize)) == -1) + if ((oob = doubledl(&csrc, &mydl, source, ssize)) == -1) { return -1; + } myecx_backsize = myecx_backsize * 2 + oob; - if ((oob = doubledl(&csrc, &mydl, source, ssize)) == -1) + if ((oob = doubledl(&csrc, &mydl, source, ssize)) == -1) { return -1; + } } while (oob); myecx_backsize = myecx_backsize - 1 - lostbit; @@ -246,36 +280,44 @@ int unmew(const char *source, char *dest, int ssize, int dsize, const char **end /* 18a */ myecx_backsize = 1; do { - if ((oob = doubledl(&csrc, &mydl, source, ssize)) == -1) + if ((oob = doubledl(&csrc, &mydl, source, ssize)) == -1) { return -1; + } myecx_backsize = myecx_backsize * 2 + oob; - if ((oob = doubledl(&csrc, &mydl, source, ssize)) == -1) + if ((oob = doubledl(&csrc, &mydl, source, ssize)) == -1) { return -1; + } } while (oob); myeax_backbytes = oldback; } else { /* 198 */ - if (csrc >= source + ssize) + if (csrc >= source + ssize) { return -1; + } myeax_backbytes = *(unsigned char *)csrc; myeax_backbytes += (myecx_backsize - 1) << 8; myecx_backsize = 1; csrc++; do { - if ((oob = doubledl(&csrc, &mydl, source, ssize)) == -1) + if ((oob = doubledl(&csrc, &mydl, source, ssize)) == -1) { return -1; + } myecx_backsize = myecx_backsize * 2 + oob; - if ((oob = doubledl(&csrc, &mydl, source, ssize)) == -1) + if ((oob = doubledl(&csrc, &mydl, source, ssize)) == -1) { return -1; + } } while (oob); - if (myeax_backbytes >= 0x7d00) + if (myeax_backbytes >= 0x7d00) { myecx_backsize++; - if (myeax_backbytes >= 0x500) + } + if (myeax_backbytes >= 0x500) { myecx_backsize++; - if (myeax_backbytes <= 0x7f) + } + if (myeax_backbytes <= 0x7f) { myecx_backsize += 2; + } oldback = myeax_backbytes; } diff --git a/libclamav/pdf.c b/libclamav/pdf.c index 1edf273e79..679ed534eb 100644 --- a/libclamav/pdf.c +++ b/libclamav/pdf.c @@ -128,11 +128,13 @@ static int xrefCheck(const char *xref, const char *eof) { const char *q; - while (xref < eof && (*xref == ' ' || *xref == '\n' || *xref == '\r')) + while (xref < eof && (*xref == ' ' || *xref == '\n' || *xref == '\r')) { xref++; + } - if (xref + 4 >= eof) + if (xref + 4 >= eof) { return -1; + } if (!memcmp(xref, "xref", strlen("xref"))) { cli_dbgmsg("cli_pdf: found xref\n"); @@ -171,8 +173,9 @@ static int xrefCheck(const char *xref, const char *eof) */ static const char *findNextNonWSBack(const char *q, const char *start) { - while (q > start && (*q == 0 || *q == 9 || *q == 0xa || *q == 0xc || *q == 0xd || *q == 0x20)) + while (q > start && (*q == 0 || *q == 9 || *q == 0xa || *q == 0xc || *q == 0xd || *q == 0x20)) { q--; + } return q; } @@ -187,8 +190,9 @@ static const char *findNextNonWSBack(const char *q, const char *start) */ static const char *findNextNonWS(const char *q, const char *end) { - while (q < end && (*q == 0 || *q == 9 || *q == 0xa || *q == 0xc || *q == 0xd || *q == 0x20)) + while (q < end && (*q == 0 || *q == 9 || *q == 0xa || *q == 0xc || *q == 0xd || *q == 0x20)) { q++; + } return q; } @@ -235,8 +239,9 @@ static cl_error_t find_stream_bounds( /* Begin by finding the "stream" string that prefixes stream data. */ if ((stream_begin = cli_memstr(start, bytesleft, "stream", strlen("stream")))) { idx = stream_begin + strlen("stream"); - if ((size_t)(idx - start) >= bytesleft) + if ((size_t)(idx - start) >= bytesleft) { goto done; + } bytesleft -= idx - start; /* Skip any new line characters. */ @@ -268,8 +273,9 @@ static cl_error_t find_stream_bounds( /* Pass back end of the stream data, as offset from start. */ *stream_size = endstream_begin - *stream; - if (CL_EFORMAT != status) + if (CL_EFORMAT != status) { status = CL_SUCCESS; + } } done: @@ -597,8 +603,9 @@ cl_error_t pdf_findobj(struct pdf_struct *pdf) /* Find the generation id (genid) that appears before the "obj" */ genid_search_index = findNextNonWSBack(obj_begin - 1, start); - while (genid_search_index > start && isdigit(*genid_search_index)) + while (genid_search_index > start && isdigit(*genid_search_index)) { genid_search_index--; + } if (CL_SUCCESS != cli_strntol_wrap(genid_search_index, (size_t)((obj_begin)-genid_search_index), 0, 10, &temp_long)) { cli_dbgmsg("pdf_findobj: Failed to parse object genid (# objects found: %u)\n", pdf->nobjs); @@ -616,8 +623,9 @@ cl_error_t pdf_findobj(struct pdf_struct *pdf) /* Find the object id (objid) that appears before the genid */ objid_search_index = findNextNonWSBack(genid_search_index - 1, start); - while (objid_search_index > start && isdigit(*objid_search_index)) + while (objid_search_index > start && isdigit(*objid_search_index)) { objid_search_index--; + } if (CL_SUCCESS != cli_strntol_wrap(objid_search_index, (size_t)((genid_search_index)-objid_search_index), 0, 10, &temp_long)) { /* @@ -722,8 +730,9 @@ cl_error_t pdf_findobj(struct pdf_struct *pdf) pdf->nobjs--; /* Free up the obj struct. */ - if (NULL != obj) + if (NULL != obj) { free(obj); + } if (status == CL_BREAK) { cli_dbgmsg("pdf_findobj: No more objects (# objects found: %u)\n", pdf->nobjs); @@ -741,8 +750,9 @@ static size_t filter_writen(struct pdf_struct *pdf, struct pdf_obj *obj, int fou { UNUSEDPARAM(obj); - if (cli_checklimits("pdf", pdf->ctx, (uint64_t)*sum, 0, 0)) + if (cli_checklimits("pdf", pdf->ctx, (uint64_t)*sum, 0, 0)) { return len; + } *sum += len; @@ -753,8 +763,9 @@ void pdfobj_flag(struct pdf_struct *pdf, struct pdf_obj *obj, enum pdf_flag flag { const char *s = ""; pdf->flags |= 1 << flag; - if (!cli_debug_flag) + if (!cli_debug_flag) { return; + } switch (flag) { case UNTERMINATED_OBJ_DICT: @@ -833,21 +844,24 @@ struct pdf_obj *find_obj(struct pdf_struct *pdf, struct pdf_obj *obj, uint32_t o /* search starting at previous obj (if exists) */ for (i = 0; i < pdf->nobjs; i++) { - if (pdf->objs[i] == obj) + if (pdf->objs[i] == obj) { break; + } } for (j = i; j < pdf->nobjs; j++) { obj = pdf->objs[j]; - if (obj->id == objid) + if (obj->id == objid) { return obj; + } } /* restart search from beginning if not found */ for (j = 0; j < i; j++) { obj = pdf->objs[j]; - if (obj->id == objid) + if (obj->id == objid) { return obj; + } } return NULL; @@ -916,8 +930,9 @@ static size_t find_length(struct pdf_struct *pdf, struct pdf_obj *obj, const cha * Find the "/Length" dictionary key */ index = cli_memstr(obj_start, bytes_remaining, "/Length", 7); - if (!index) + if (!index) { return 0; + } bytes_remaining -= index - obj_start; @@ -932,8 +947,9 @@ static size_t find_length(struct pdf_struct *pdf, struct pdf_obj *obj, const cha /* Find the start of the next direct or indirect object. * pdf_nextobject() assumes we started searching from within a previous object */ obj_start = pdf_nextobject(index, bytes_remaining); - if (!obj_start) + if (!obj_start) { return 0; + } if (bytes_remaining < (size_t)(obj_start - index)) { return 0; @@ -1049,8 +1065,9 @@ static size_t find_length(struct pdf_struct *pdf, struct pdf_obj *obj, const cha } /* limit length */ - if ((size_t)(obj_start - pdf->map) + length + 5 > pdf->size) + if ((size_t)(obj_start - pdf->map) + length + 5 > pdf->size) { length = pdf->size - (obj_start - pdf->map) - 5; + } return length; } @@ -1064,8 +1081,9 @@ static int run_pdf_hooks(struct pdf_struct *pdf, enum pdf_phase phase, int fd) cli_ctx *ctx = NULL; fmap_t *map; - if (NULL == pdf) + if (NULL == pdf) { return CL_EARG; + } ctx = pdf->ctx; @@ -1090,8 +1108,9 @@ static int run_pdf_hooks(struct pdf_struct *pdf, enum pdf_phase phase, int fd) ret = cli_bytecode_runhook(ctx, ctx->engine, bc_ctx, BC_PDF, map); cli_bytecode_context_destroy(bc_ctx); - if (fd != -1) + if (fd != -1) { funmap(map); + } return ret; } @@ -1147,8 +1166,9 @@ static void aes_256cbc_decrypt(const unsigned char *in, size_t *length, unsigned unsigned i; rijndaelDecrypt(rk, nrounds, in, q); - for (i = 0; i < 16; i++) + for (i = 0; i < 16; i++) { q[i] ^= iv[i]; + } memcpy(iv, in, 16); @@ -1213,18 +1233,21 @@ static void aes_128cbc_encrypt(const unsigned char *in, size_t in_length, unsign } cli_dbgmsg("aes_128cbc_encrypt: Beginning rijndaelEncrypt\n"); - if (iv) + if (iv) { memcpy(real_iv, iv, sizeof(real_iv)); + } *out_length = 0; while (in_length >= 16) { - for (i = 0; i < 16; i++) + for (i = 0; i < 16; i++) { real_iv[i] ^= in[i]; + } rijndaelEncrypt(rk, nrounds, real_iv, real_iv); - for (i = 0; i < 16; i++) + for (i = 0; i < 16; i++) { out[i] = real_iv[i]; + } out += 16; *out_length += 16; @@ -1252,8 +1275,9 @@ char *decrypt_any(struct pdf_struct *pdf, uint32_t id, const char *in, size_t *l } n = pdf->keylen + 5; - if (enc_method == ENC_AESV2) + if (enc_method == ENC_AESV2) { n += 4; + } key = cli_max_malloc(n); if (!key) { @@ -1268,15 +1292,17 @@ char *decrypt_any(struct pdf_struct *pdf, uint32_t id, const char *in, size_t *l *q++ = id >> 24; *q++ = id; *q++ = 0; - if (enc_method == ENC_AESV2) + if (enc_method == ENC_AESV2) { memcpy(q, "sAlT", 4); + } cl_hash_data("md5", key, n, result, NULL); free(key); n = pdf->keylen + 5; - if (n > 16) + if (n > 16) { n = 16; + } q = cli_max_calloc(*length, sizeof(char)); if (!q) { @@ -1342,11 +1368,13 @@ char *decrypt_any(struct pdf_struct *pdf, uint32_t id, const char *in, size_t *l enum enc_method get_enc_method(struct pdf_struct *pdf, struct pdf_obj *obj) { - if (obj->flags & (1 << OBJ_EMBEDDED_FILE)) + if (obj->flags & (1 << OBJ_EMBEDDED_FILE)) { return pdf->enc_method_embeddedfile; + } - if (obj->flags & (1 << OBJ_STREAM)) + if (obj->flags & (1 << OBJ_STREAM)) { return pdf->enc_method_stream; + } return pdf->enc_method_string; } @@ -1366,8 +1394,9 @@ static void process(struct text_norm_state *s, enum cstate *st, const char *buf, *st = CSTATE_TJ; } else { const char *nl = memchr(buf, '\n', length); - if (!nl) + if (!nl) { return; + } if ((size_t)(nl - buf) > length) { length = 0; @@ -1379,8 +1408,9 @@ static void process(struct text_norm_state *s, enum cstate *st, const char *buf, break; case CSTATE_TJ: - if (*buf == '(') + if (*buf == '(') { *st = CSTATE_TJ_PAROPEN; + } break; case CSTATE_TJ_PAROPEN: @@ -1397,8 +1427,9 @@ static void process(struct text_norm_state *s, enum cstate *st, const char *buf, } buf++; - if (length > 0) + if (length > 0) { length--; + } } while (length > 0); } @@ -1425,8 +1456,9 @@ static int pdf_scan_contents(int fd, struct pdf_struct *pdf, struct pdf_obj *obj text_normalize_init(&s, (unsigned char *)outbuff, sizeof(outbuff)); while (1) { n = cli_readn(fd, inbuf, sizeof(inbuf)); - if ((n == 0) || (n == (size_t)-1)) + if ((n == 0) || (n == (size_t)-1)) { break; + } process(&s, &st, inbuf, n, fout); } @@ -1437,9 +1469,11 @@ static int pdf_scan_contents(int fd, struct pdf_struct *pdf, struct pdf_obj *obj rc = cli_magic_scan_desc(fout, fullname, pdf->ctx, NULL, LAYER_ATTRIBUTES_NONE); close(fout); - if (!pdf->ctx->engine->keeptmp || (s.out_pos == 0)) - if (cli_unlink(fullname) && rc != CL_VIRUS) + if (!pdf->ctx->engine->keeptmp || (s.out_pos == 0)) { + if (cli_unlink(fullname) && rc != CL_VIRUS) { rc = CL_EUNLINK; + } + } return rc; } @@ -1491,8 +1525,9 @@ cl_error_t pdf_extract_obj(struct pdf_struct *pdf, struct pdf_obj *obj, uint32_t dump = 1; } - if (!dump) + if (!dump) { return CL_CLEAN; + } cli_dbgmsg("pdf_extract_obj: dumping obj %u %u\n", obj->id >> 8, obj->id & 0xff); @@ -1556,8 +1591,9 @@ cl_error_t pdf_extract_obj(struct pdf_struct *pdf, struct pdf_obj *obj, uint32_t q--; length--; - if (length > 0 && *q == '\r') + if (length > 0 && *q == '\r') { length--; + } } else if (*q == '\r') { length--; } @@ -1724,8 +1760,9 @@ cl_error_t pdf_extract_obj(struct pdf_struct *pdf, struct pdf_obj *obj, uint32_t } } - if (dparams) + if (dparams) { pdf_free_dict(dparams); + } if (rc == CL_VIRUS) { sum = 0; /* prevents post-filter scan */ @@ -1750,8 +1787,9 @@ cl_error_t pdf_extract_obj(struct pdf_struct *pdf, struct pdf_obj *obj, uint32_t const char *q3; q2 = cli_memstr(q, bytesleft, "/JavaScript", 11); - if (!q2) + if (!q2) { break; + } bytesleft -= q2 - q + 11; q = q2 + 11; @@ -1800,16 +1838,19 @@ cl_error_t pdf_extract_obj(struct pdf_struct *pdf, struct pdf_obj *obj, uint32_t if (bytesleft > 0) { q2 = pdf_nextobject(q, bytesleft); - if (!q2) + if (!q2) { q2 = q + bytesleft - 1; + } /* non-conforming PDFs that don't escape ) properly */ q3 = memchr(q, ')', bytesleft); - if (q3 && q3 < q2) + if (q3 && q3 < q2) { q2 = q3; + } - while (q2 > q && q2[-1] == ' ') + while (q2 > q && q2[-1] == ' ') { q2--; + } if (q2 > q) { q--; @@ -1823,15 +1864,17 @@ cl_error_t pdf_extract_obj(struct pdf_struct *pdf, struct pdf_obj *obj, uint32_t } else { off_t bytesleft = obj->size; - if (bytesleft < 0) + if (bytesleft < 0) { rc = CL_EFORMAT; - else { + } else { if (obj->objstm) { - if (filter_writen(pdf, obj, fout, obj->objstm->streambuf + obj->start, bytesleft, (size_t *)&sum) != (size_t)bytesleft) + if (filter_writen(pdf, obj, fout, obj->objstm->streambuf + obj->start, bytesleft, (size_t *)&sum) != (size_t)bytesleft) { rc = CL_EWRITE; + } } else { - if (filter_writen(pdf, obj, fout, pdf->map + obj->start, bytesleft, (size_t *)&sum) != (size_t)bytesleft) + if (filter_writen(pdf, obj, fout, pdf->map + obj->start, bytesleft, (size_t *)&sum) != (size_t)bytesleft) { rc = CL_EWRITE; + } } } } @@ -1876,9 +1919,11 @@ cl_error_t pdf_extract_obj(struct pdf_struct *pdf, struct pdf_obj *obj, uint32_t close(fout); if (CL_EMEM != rc) { - if (flags & PDF_EXTRACT_OBJ_SCAN && !pdf->ctx->engine->keeptmp) - if (cli_unlink(fullname) && rc != CL_VIRUS) + if (flags & PDF_EXTRACT_OBJ_SCAN && !pdf->ctx->engine->keeptmp) { + if (cli_unlink(fullname) && rc != CL_VIRUS) { rc = CL_EUNLINK; + } + } } return rc; @@ -1984,8 +2029,9 @@ static void handle_pdfname(struct pdf_struct *pdf, struct pdf_obj *obj, const ch } /* record filter order */ - if (obj->numfilters < PDF_FILTERLIST_MAX && (*state == STATE_FILTER) && ((1 << act->set_objflag) & KNOWN_FILTERS)) + if (obj->numfilters < PDF_FILTERLIST_MAX && (*state == STATE_FILTER) && ((1 << act->set_objflag) & KNOWN_FILTERS)) { obj->filterlist[obj->numfilters++] = act->set_objflag; + } if ((act->nameflags & NAMEFLAG_HEURISTIC) && escapes) { /* if a commonly used PDF name is escaped that is certainly @@ -1994,8 +2040,9 @@ static void handle_pdfname(struct pdf_struct *pdf, struct pdf_obj *obj, const ch pdfobj_flag(pdf, obj, ESCAPED_COMMON_PDFNAME); } - if ((act->pdf_stats_cb)) + if ((act->pdf_stats_cb)) { act->pdf_stats_cb(pdf, obj, act); + } if (act->from_state == *state || act->from_state == STATE_ANY) { *state = act->to_state; @@ -2027,8 +2074,9 @@ static void pdf_parse_encrypt(struct pdf_struct *pdf, const char *enc, int len) if (len >= 16 && !strncmp(enc, "/EncryptMetadata", 16)) { q = cli_memstr(enc + 16, len - 16, "/Encrypt", 8); - if (!q) + if (!q) { return; + } len -= q - enc; enc = q; @@ -2037,8 +2085,9 @@ static void pdf_parse_encrypt(struct pdf_struct *pdf, const char *enc, int len) q = enc + 8; len -= 8; q2 = pdf_nextobject(q, len); - if (!q2 || !isdigit(*q2)) + if (!q2 || !isdigit(*q2)) { return; + } len -= q2 - q; q = q2; @@ -2053,8 +2102,9 @@ static void pdf_parse_encrypt(struct pdf_struct *pdf, const char *enc, int len) objid = objid << 8; q2 = pdf_nextobject(q, len); - if (!q2 || !isdigit(*q2)) + if (!q2 || !isdigit(*q2)) { return; + } len -= q2 - q; q = q2; @@ -2069,8 +2119,9 @@ static void pdf_parse_encrypt(struct pdf_struct *pdf, const char *enc, int len) objid |= genid & 0xff; q2 = pdf_nextobject(q, len); - if (!q2 || *q2 != 'R') + if (!q2 || *q2 != 'R') { return; + } cli_dbgmsg("pdf_parse_encrypt: Encrypt dictionary in obj %lu %lu\n", objid >> 8, objid & 0xff); @@ -2137,8 +2188,9 @@ void pdf_parseobj(struct pdf_struct *pdf, struct pdf_obj *obj) } start = q; - if (obj->size <= 0) + if (obj->size <= 0) { return; + } if (obj->objstm) { bytesleft = MIN(obj->size, obj->objstm->streambuf_len - obj->start); @@ -2181,15 +2233,18 @@ void pdf_parseobj(struct pdf_struct *pdf, struct pdf_obj *obj) if (!(pdfobj) && pdf->ctx->wrkproperty != NULL) { pdfobj = cli_jsonobj(pdf->ctx->wrkproperty, "PDFStats"); - if (!(pdfobj)) + if (!(pdfobj)) { return; + } } if (pdfobj) { - if (!(jsonobj)) + if (!(jsonobj)) { jsonobj = cli_jsonarray(pdfobj, "ObjectsWithoutDictionaries"); - if (jsonobj) + } + if (jsonobj) { cli_jsonint_array(jsonobj, obj->id >> 8); + } } return; @@ -2228,15 +2283,18 @@ void pdf_parseobj(struct pdf_struct *pdf, struct pdf_obj *obj) if (!(pdfobj) && pdf->ctx->wrkproperty != NULL) { pdfobj = cli_jsonobj(pdf->ctx->wrkproperty, "PDFStats"); - if (!(pdfobj)) + if (!(pdfobj)) { return; + } } if (pdfobj) { - if (!(jsonobj)) + if (!(jsonobj)) { jsonobj = cli_jsonarray(pdfobj, "ObjectsWithBrokenDictionaries"); - if (jsonobj) + } + if (jsonobj) { cli_jsonint_array(jsonobj, obj->id >> 8); + } } return; @@ -2277,15 +2335,18 @@ void pdf_parseobj(struct pdf_struct *pdf, struct pdf_obj *obj) if (!(pdfobj) && pdf->ctx->wrkproperty != NULL) { pdfobj = cli_jsonobj(pdf->ctx->wrkproperty, "PDFStats"); - if (!(pdfobj)) + if (!(pdfobj)) { return; + } } if (pdfobj) { - if (!(jsonobj)) + if (!(jsonobj)) { jsonobj = cli_jsonarray(pdfobj, "ObjectsWithBrokenDictionaries"); - if (jsonobj) + } + if (jsonobj) { cli_jsonint_array(jsonobj, obj->id >> 8); + } } return; @@ -2318,8 +2379,9 @@ void pdf_parseobj(struct pdf_struct *pdf, struct pdf_obj *obj) for (q = dict; dict_length > 0;) { int escapes = 0, breakout = 0; q2 = memchr(q, '/', dict_length); - if (!q2) + if (!q2) { break; + } dict_length -= q2 - q; q = q2; @@ -2329,8 +2391,9 @@ void pdf_parseobj(struct pdf_struct *pdf, struct pdf_obj *obj) dict_length--; if (*q == '#') { - if (cli_hex2str_to(q + 1, pdfname + i, 2) == -1) + if (cli_hex2str_to(q + 1, pdfname + i, 2) == -1) { break; + } q += 2; dict_length -= 2; @@ -2352,8 +2415,9 @@ void pdf_parseobj(struct pdf_struct *pdf, struct pdf_obj *obj) breakout = 1; } - if (breakout) + if (breakout) { break; + } pdfname[i] = *q; } @@ -2369,24 +2433,28 @@ void pdf_parseobj(struct pdf_struct *pdf, struct pdf_obj *obj) trailer_end = pdf_readint(dict, full_dict_length, "/H"); if ((trailer_end > 0) && ((size_t)trailer_end < pdf->size)) { trailer = trailer_end - 1024; - if (trailer < 0) + if (trailer < 0) { trailer = 0; + } q2 = pdf->map + trailer; cli_dbgmsg("pdf_parseobj: looking for trailer in linearized pdf: %ld - %ld\n", trailer, trailer_end); pdf_parse_trailer(pdf, q2, trailer_end - trailer); - if (pdf->fileID) + if (pdf->fileID) { cli_dbgmsg("pdf_parseobj: found fileID\n"); + } } } - if (objstate == STATE_LAUNCHACTION) + if (objstate == STATE_LAUNCHACTION) { pdfobj_flag(pdf, obj, HAS_LAUNCHACTION); + } if (dict_length > 0 && (objstate == STATE_JAVASCRIPT || objstate == STATE_OPENACTION || objstate == STATE_CONTENTS)) { off_t dict_remaining = dict_length; - if (objstate == STATE_OPENACTION) + if (objstate == STATE_OPENACTION) { pdfobj_flag(pdf, obj, HAS_OPENACTION); + } q2 = pdf_nextobject(q, dict_remaining); if (q2 && isdigit(*q2)) { @@ -2482,11 +2550,13 @@ void pdf_parseobj(struct pdf_struct *pdf, struct pdf_obj *obj) pdfobj_flag(pdf, obj, MANY_FILTERS); } - if (obj->flags & ((1 << OBJ_SIGNED) | KNOWN_FILTERS)) + if (obj->flags & ((1 << OBJ_SIGNED) | KNOWN_FILTERS)) { obj->flags &= ~(1 << OBJ_FILTER_UNKNOWN); + } - if (obj->flags & (1 << OBJ_FILTER_UNKNOWN)) + if (obj->flags & (1 << OBJ_FILTER_UNKNOWN)) { pdfobj_flag(pdf, obj, UNKNOWN_FILTER); + } cli_dbgmsg("pdf_parseobj: %u %u obj flags: %02x\n", obj->id >> 8, obj->id & 0xff, obj->flags); } @@ -2510,8 +2580,9 @@ static const char *pdf_getdict(const char *q0, int *len, const char *key) return NULL; } - if (!q0) + if (!q0) { return NULL; + } /* find the key */ q = cli_memstr(q0, *len, key, strlen(key)); @@ -2531,8 +2602,9 @@ static const char *pdf_getdict(const char *q0, int *len, const char *key) } /* if the value is a dictionary object, include the < > brackets.*/ - while (q > q0 && (q[-1] == '<' || q[-1] == '\n')) + while (q > q0 && (q[-1] == '<' || q[-1] == '\n')) { q--; + } *len -= q - q0; return q; @@ -2553,15 +2625,18 @@ static char *pdf_readstring(const char *q0, int len, const char *key, unsigned * { char *s, *s0; const char *start, *q, *end; - if (slen) + if (slen) { *slen = 0; + } - if (qend) + if (qend) { *qend = q0; + } q = pdf_getdict(q0, &len, key); - if (!q || len <= 0) + if (!q || len <= 0) { return NULL; + } if (*q == '(') { int paren = 1; @@ -2589,8 +2664,9 @@ static char *pdf_readstring(const char *q0, int len, const char *key, unsigned * return NULL; } - if (qend) + if (qend) { *qend = q; + } q--; len = q - start; @@ -2636,8 +2712,9 @@ static char *pdf_readstring(const char *q0, int len, const char *key, unsigned * break; case '\r': /* ignore */ - if (q + 1 < end && q[1] == '\n') + if (q + 1 < end && q[1] == '\n') { q++; + } break; case '0': case '1': @@ -2666,8 +2743,9 @@ static char *pdf_readstring(const char *q0, int len, const char *key, unsigned * } *s++ = '\0'; - if (slen) + if (slen) { *slen = s - s0 - 1; + } return s0; } @@ -2681,11 +2759,13 @@ static char *pdf_readstring(const char *q0, int len, const char *key, unsigned * len -= 1; } q = memchr(q + 1, '>', len - 1); - if (!q) + if (!q) { return NULL; + } - if (qend) + if (qend) { *qend = q; + } s = cli_max_malloc((q - start) / 2 + 1); if (s == NULL) { /* oops, couldn't allocate memory */ @@ -2700,8 +2780,9 @@ static char *pdf_readstring(const char *q0, int len, const char *key, unsigned * } s[(q - start) / 2] = '\0'; - if (slen) + if (slen) { *slen = (q - start) / 2; + } return s; } @@ -2717,16 +2798,18 @@ static char *pdf_readval(const char *q, int len, const char *key) int origlen = len; q = pdf_getdict(q, &len, key); - if (!q || len <= 0) + if (!q || len <= 0) { return NULL; + } while (len > 0 && *q && *q == ' ') { q++; len--; } - if (*q != '/') + if (*q != '/') { return NULL; + } q++; len--; @@ -2744,8 +2827,9 @@ static char *pdf_readval(const char *q, int len, const char *key) } s = cli_max_malloc(end - q + 1); - if (!s) + if (!s) { return NULL; + } memcpy(s, q, end - q); s[end - q] = '\0'; @@ -2770,14 +2854,17 @@ static int pdf_readbool(const char *q0, int len, const char *key, int Default) { const char *q = pdf_getdict(q0, &len, key); - if (!q || len < 5) + if (!q || len < 5) { return Default; + } - if (!strncmp(q, "true", 4)) + if (!strncmp(q, "true", 4)) { return 1; + } - if (!strncmp(q, "false", 5)) + if (!strncmp(q, "false", 5)) { return 0; + } cli_dbgmsg("pdf_readbool: invalid value for %s bool\n", key); @@ -2847,13 +2934,15 @@ static void compute_hash_r6(const char *password, size_t pwlen, const unsigned c in_data_len += 48; } - for (j = 1; j < 64; j++) + for (j = 1; j < 64; j++) { memcpy(data + j * in_data_len, data, in_data_len); + } aes_128cbc_encrypt(data, in_data_len * 64, data, &out_data_len, block, 16, block + 16); - for (j = 0, sum = 0; j < 16; j++) + for (j = 0, sum = 0; j < 16; j++) { sum += data[j]; + } block_size = 32 + (sum % 3) * 16; switch (block_size) { @@ -3009,8 +3098,9 @@ static void check_user_password(struct pdf_struct *pdf, int R, const char *O, size_t sz = 68 + pdf->fileIDlen + (R >= 4 && !EM ? 4 : 0); d = calloc(1, sz); - if (!(d)) + if (!(d)) { goto done; + } memcpy(d, key_padding, 32); memcpy(d + 32, O, 32); @@ -3027,20 +3117,24 @@ static void check_user_password(struct pdf_struct *pdf, int R, const char *O, cl_hash_data("md5", d, sz, result, NULL); free(d); - if (length > 128) + if (length > 128) { length = 128; + } if (R >= 3) { /* Yes, this really is on purpose */ - for (i = 0; i < 50; i++) + for (i = 0; i < 50; i++) { cl_hash_data("md5", result, length / 8, result, NULL); + } } - if (R == 2) + if (R == 2) { length = 40; + } pdf->keylen = length / 8; pdf->key = cli_max_malloc(pdf->keylen); - if (!pdf->key) + if (!pdf->key) { goto done; + } memcpy(pdf->key, result, pdf->keylen); dbg_printhex("md5", (const char *)result, 16); @@ -3056,16 +3150,18 @@ static void check_user_password(struct pdf_struct *pdf, int R, const char *O, } arc4_apply(&arc4, (uint8_t *)data, 32); dbg_printhex("computed U (R2)", data, 32); - if (!memcmp(data, U, 32)) + if (!memcmp(data, U, 32)) { password_empty = true; + } } else { // R is 3 or 4 unsigned len = pdf->keylen; unsigned char *d; d = calloc(1, 32 + pdf->fileIDlen); - if (!(d)) + if (!(d)) { goto done; + } /* 7.6.3.3 Algorithm 5 */ memcpy(d, key_padding, 32); @@ -3081,8 +3177,9 @@ static void check_user_password(struct pdf_struct *pdf, int R, const char *O, for (i = 1; i <= 19; i++) { unsigned j; - for (j = 0; j < len; j++) + for (j = 0; j < len; j++) { data[j] = pdf->key[j] ^ i; + } if (false == arc4_init(&arc4, (const uint8_t *)data, len)) { noisy_warnmsg("check_user_password: failed to init arc4\n"); @@ -3093,8 +3190,9 @@ static void check_user_password(struct pdf_struct *pdf, int R, const char *O, dbg_printhex("fileID", pdf->fileID, pdf->fileIDlen); dbg_printhex("computed U (R>=3)", (const char *)result, 16); - if (!memcmp(result, U, 16)) + if (!memcmp(result, U, 16)) { password_empty = true; + } free(d); } @@ -3221,27 +3319,31 @@ enum enc_method parse_enc_method(const char *dict, unsigned len, const char *key char *CFM = NULL; enum enc_method ret = ENC_UNKNOWN; - if (!key) + if (!key) { return def; + } - if (!strcmp(key, "Identity")) + if (!strcmp(key, "Identity")) { return ENC_IDENTITY; + } q = pdf_getdict(dict, (int *)(&len), key); - if (!q) + if (!q) { return def; + } CFM = pdf_readval(q, len, "/CFM"); if (CFM) { cli_dbgmsg("parse_enc_method: %s CFM: %s\n", key, CFM); - if (!strncmp(CFM, "V2", 2)) + if (!strncmp(CFM, "V2", 2)) { ret = ENC_V2; - else if (!strncmp(CFM, "AESV2", 5)) + } else if (!strncmp(CFM, "AESV2", 5)) { ret = ENC_AESV2; - else if (!strncmp(CFM, "AESV3", 5)) + } else if (!strncmp(CFM, "AESV3", 5)) { ret = ENC_AESV3; - else if (!strncmp(CFM, "None", 4)) + } else if (!strncmp(CFM, "None", 4)) { ret = ENC_NONE; + } free(CFM); } @@ -3268,8 +3370,9 @@ void pdf_handle_enc(struct pdf_struct *pdf) const char *q, *q2; - if (pdf->enc_objid == ~0u) + if (pdf->enc_objid == ~0u) { return; + } if (!pdf->fileID) { cli_dbgmsg("pdf_handle_enc: no file ID\n"); noisy_warnmsg("pdf_handle_enc: no file ID\n"); @@ -3321,8 +3424,9 @@ void pdf_handle_enc(struct pdf_struct *pdf) * /Length /Standard * make sure we don't mistake AES's length for Standard's */ length = pdf_readint(q2, len - (q2 - q), "/Length"); - if (length == ~0u) + if (length == ~0u) { length = pdf_readint(q, len, "/Length"); + } if (length < 40) { cli_dbgmsg("pdf_handle_enc: invalid length: %d\n", length); @@ -3407,8 +3511,9 @@ void pdf_handle_enc(struct pdf_struct *pdf) } } - if (length == ~0u) + if (length == ~0u) { length = 40; + } /* * Read the O value @@ -3613,9 +3718,10 @@ static cl_error_t pdf_find_and_extract_objs(struct pdf_struct *pdf) } pdf_handle_enc(pdf); - if (pdf->flags & (1 << ENCRYPTED_PDF)) + if (pdf->flags & (1 << ENCRYPTED_PDF)) { cli_dbgmsg("pdf_find_and_extract_objs: encrypted pdf found, %s!\n", (pdf->flags & (1 << DECRYPTABLE_PDF)) ? "decryptable" : "not decryptable, stream will probably fail to decompress"); + } if (SCAN_HEURISTIC_ENCRYPTED_DOC && (pdf->flags & (1 << ENCRYPTED_PDF)) && @@ -3711,8 +3817,9 @@ cl_error_t cli_pdf(const char *dir, cli_ctx *ctx, off_t offset) goto done; } - if (ctx->wrkproperty) + if (ctx->wrkproperty) { pdfobj = cli_jsonobj(ctx->wrkproperty, "PDFStats"); + } /* offset is 0 when coming from filetype2 */ tmp = cli_memstr(pdfver, versize, "%PDF-", 5); @@ -3738,8 +3845,9 @@ cl_error_t cli_pdf(const char *dir, cli_ctx *ctx, off_t offset) pdf.flags |= 1 << BAD_PDF_VERSION; cli_dbgmsg("cli_pdf: bad pdf version: %.8s\n", pdfver); - if (pdfobj) + if (pdfobj) { cli_jsonbool(pdfobj, "BadVersion", 1); + } } else { if (pdfobj) { begin = (char *)(pdfver + 5); @@ -3759,16 +3867,18 @@ cl_error_t cli_pdf(const char *dir, cli_ctx *ctx, off_t offset) pdf.flags |= 1 << BAD_PDF_HEADERPOS; cli_dbgmsg("cli_pdf: PDF header is not at position 0: %lld\n", (long long)(pdfver - start + offset)); - if (pdfobj) + if (pdfobj) { cli_jsonbool(pdfobj, "BadVersionLocation", 1); + } } offset += pdfver - start; /* find trailer and xref, don't fail if not found */ map_off = (off_t)map->len - 2048; - if (map_off < 0) + if (map_off < 0) { map_off = 0; + } bytesleft = map->len - map_off; @@ -3782,36 +3892,41 @@ cl_error_t cli_pdf(const char *dir, cli_ctx *ctx, off_t offset) eof = eofmap + bytesleft; for (q = &eofmap[bytesleft - 5]; q > eofmap; q--) { - if (memcmp(q, "%%EOF", 5) == 0) + if (memcmp(q, "%%EOF", 5) == 0) { break; + } } if (q <= eofmap) { pdf.flags |= 1 << BAD_PDF_TRAILER; cli_dbgmsg("cli_pdf: %%%%EOF not found\n"); - if (pdfobj) + if (pdfobj) { cli_jsonbool(pdfobj, "NoEOF", 1); + } } else { const char *t; /*size = q - eofmap + map_off;*/ q -= 9; for (; q > eofmap; q--) { - if (memcmp(q, "startxref", 9) == 0) + if (memcmp(q, "startxref", 9) == 0) { break; + } } if (q <= eofmap) { pdf.flags |= 1 << BAD_PDF_TRAILER; cli_dbgmsg("cli_pdf: startxref not found\n"); - if (pdfobj) + if (pdfobj) { cli_jsonbool(pdfobj, "NoXREF", 1); + } } else { for (t = q; t > eofmap; t--) { - if (memcmp(t, "trailer", 7) == 0) + if (memcmp(t, "trailer", 7) == 0) { break; + } } pdf_parse_trailer(&pdf, eofmap, eof - eofmap); @@ -3830,8 +3945,9 @@ cl_error_t cli_pdf(const char *dir, cli_ctx *ctx, off_t offset) } else { xref = (unsigned long)temp_long; bytesleft = map->len - offset - xref; - if (bytesleft > 4096) + if (bytesleft > 4096) { bytesleft = 4096; + } q = fmap_need_off_once(map, offset + xref, bytesleft); if (!q || xrefCheck(q, q + bytesleft) == -1) { @@ -3878,8 +3994,9 @@ cl_error_t cli_pdf(const char *dir, cli_ctx *ctx, off_t offset) cli_dbgmsg("cli_pdf: pdf_find_and_extract_objs found %d new objects.\n", pdf.nobjs - objs_found); } - if (pdf.flags & (1 << ENCRYPTED_PDF)) + if (pdf.flags & (1 << ENCRYPTED_PDF)) { pdf.flags &= ~((1 << BAD_FLATESTART) | (1 << BAD_STREAMSTART) | (1 << BAD_ASCIIDECODE)); + } if (pdf.flags && CL_SUCCESS == rc) { cli_dbgmsg("cli_pdf: flags 0x%02x\n", pdf.flags); @@ -3977,15 +4094,17 @@ pdf_nextlinestart(const char *ptr, size_t len) } while (strchr("\r\n", *ptr) == NULL) { - if (--len == 0L) + if (--len == 0L) { return NULL; + } ptr++; } while (strchr("\r\n", *ptr) != NULL) { - if (--len == 0L) + if (--len == 0L) { return NULL; + } ptr++; } @@ -4015,8 +4134,9 @@ pdf_nextobject(const char *ptr, size_t len) case '\r': case '%': /* comment */ p = pdf_nextlinestart(ptr, len); - if (p == NULL) + if (p == NULL) { return NULL; + } len -= (size_t)(p - ptr); ptr = p; @@ -4058,8 +4178,9 @@ static void ASCIIHexDecode_cb(struct pdf_struct *pdf, struct pdf_obj *obj, struc UNUSEDPARAM(obj); UNUSEDPARAM(act); - if (NULL == pdf) + if (NULL == pdf) { return; + } pdf->stats.nasciihexdecode++; } @@ -4069,8 +4190,9 @@ static void ASCII85Decode_cb(struct pdf_struct *pdf, struct pdf_obj *obj, struct UNUSEDPARAM(obj); UNUSEDPARAM(act); - if (NULL == pdf) + if (NULL == pdf) { return; + } pdf->stats.nascii85decode++; } @@ -4080,8 +4202,9 @@ static void EmbeddedFile_cb(struct pdf_struct *pdf, struct pdf_obj *obj, struct UNUSEDPARAM(obj); UNUSEDPARAM(act); - if (NULL == pdf) + if (NULL == pdf) { return; + } pdf->stats.nembeddedfile++; } @@ -4091,8 +4214,9 @@ static void FlateDecode_cb(struct pdf_struct *pdf, struct pdf_obj *obj, struct p UNUSEDPARAM(obj); UNUSEDPARAM(act); - if (NULL == pdf) + if (NULL == pdf) { return; + } pdf->stats.nflate++; } @@ -4102,8 +4226,9 @@ static void Image_cb(struct pdf_struct *pdf, struct pdf_obj *obj, struct pdfname UNUSEDPARAM(obj); UNUSEDPARAM(act); - if (NULL == pdf) + if (NULL == pdf) { return; + } pdf->stats.nimage++; } @@ -4113,8 +4238,9 @@ static void LZWDecode_cb(struct pdf_struct *pdf, struct pdf_obj *obj, struct pdf UNUSEDPARAM(obj); UNUSEDPARAM(act); - if (NULL == pdf) + if (NULL == pdf) { return; + } pdf->stats.nlzw++; } @@ -4124,8 +4250,9 @@ static void RunLengthDecode_cb(struct pdf_struct *pdf, struct pdf_obj *obj, stru UNUSEDPARAM(obj); UNUSEDPARAM(act); - if (NULL == pdf) + if (NULL == pdf) { return; + } pdf->stats.nrunlengthdecode++; } @@ -4135,8 +4262,9 @@ static void CCITTFaxDecode_cb(struct pdf_struct *pdf, struct pdf_obj *obj, struc UNUSEDPARAM(obj); UNUSEDPARAM(act); - if (NULL == pdf) + if (NULL == pdf) { return; + } pdf->stats.nfaxdecode++; } @@ -4149,24 +4277,29 @@ static void JBIG2Decode_cb(struct pdf_struct *pdf, struct pdf_obj *obj, struct p UNUSEDPARAM(obj); UNUSEDPARAM(act); - if (NULL == pdf) + if (NULL == pdf) { return; + } ctx = pdf->ctx; - if (!(SCAN_COLLECT_METADATA)) + if (!(SCAN_COLLECT_METADATA)) { return; + } - if (!(pdf->ctx->wrkproperty)) + if (!(pdf->ctx->wrkproperty)) { return; + } pdfobj = cli_jsonobj(pdf->ctx->wrkproperty, "PDFStats"); - if (!(pdfobj)) + if (!(pdfobj)) { return; + } jbig2arr = cli_jsonarray(pdfobj, "JBIG2Objects"); - if (!(jbig2arr)) + if (!(jbig2arr)) { return; + } cli_jsonint_array(jbig2arr, obj->id >> 8); @@ -4178,8 +4311,9 @@ static void DCTDecode_cb(struct pdf_struct *pdf, struct pdf_obj *obj, struct pdf UNUSEDPARAM(obj); UNUSEDPARAM(act); - if (NULL == pdf) + if (NULL == pdf) { return; + } pdf->stats.ndctdecode++; } @@ -4189,8 +4323,9 @@ static void JPXDecode_cb(struct pdf_struct *pdf, struct pdf_obj *obj, struct pdf UNUSEDPARAM(obj); UNUSEDPARAM(act); - if (NULL == pdf) + if (NULL == pdf) { return; + } pdf->stats.njpxdecode++; } @@ -4200,8 +4335,9 @@ static void Crypt_cb(struct pdf_struct *pdf, struct pdf_obj *obj, struct pdfname UNUSEDPARAM(obj); UNUSEDPARAM(act); - if (NULL == pdf) + if (NULL == pdf) { return; + } pdf->stats.ncrypt++; } @@ -4211,8 +4347,9 @@ static void Standard_cb(struct pdf_struct *pdf, struct pdf_obj *obj, struct pdfn UNUSEDPARAM(obj); UNUSEDPARAM(act); - if (NULL == pdf) + if (NULL == pdf) { return; + } pdf->stats.nstandard++; } @@ -4222,8 +4359,9 @@ static void Sig_cb(struct pdf_struct *pdf, struct pdf_obj *obj, struct pdfname_a UNUSEDPARAM(obj); UNUSEDPARAM(act); - if (NULL == pdf) + if (NULL == pdf) { return; + } pdf->stats.nsigned++; } @@ -4247,8 +4385,9 @@ static void OpenAction_cb(struct pdf_struct *pdf, struct pdf_obj *obj, struct pd UNUSEDPARAM(obj); UNUSEDPARAM(act); - if (NULL == pdf) + if (NULL == pdf) { return; + } pdf->stats.nopenaction++; } @@ -4258,8 +4397,9 @@ static void Launch_cb(struct pdf_struct *pdf, struct pdf_obj *obj, struct pdfnam UNUSEDPARAM(obj); UNUSEDPARAM(act); - if (NULL == pdf) + if (NULL == pdf) { return; + } pdf->stats.nlaunch++; } @@ -4269,8 +4409,9 @@ static void Page_cb(struct pdf_struct *pdf, struct pdf_obj *obj, struct pdfname_ UNUSEDPARAM(obj); UNUSEDPARAM(act); - if (NULL == pdf) + if (NULL == pdf) { return; + } pdf->stats.npage++; } @@ -4281,21 +4422,24 @@ static void Author_cb(struct pdf_struct *pdf, struct pdf_obj *obj, struct pdfnam UNUSEDPARAM(act); - if (NULL == pdf) + if (NULL == pdf) { return; + } ctx = pdf->ctx; - if (!(SCAN_COLLECT_METADATA)) + if (!(SCAN_COLLECT_METADATA)) { return; + } if (!(pdf->stats.author)) { const char *objstart = (obj->objstm) ? (const char *)(obj->start + obj->objstm->streambuf) : (const char *)(obj->start + pdf->map); pdf->stats.author = calloc(1, sizeof(struct pdf_stats_entry)); - if (!(pdf->stats.author)) + if (!(pdf->stats.author)) { return; + } pdf->parse_recursion_depth++; pdf->stats.author->data = pdf_parse_string(pdf, obj, objstart, obj->size, "/Author", NULL, &(pdf->stats.author->meta)); @@ -4309,21 +4453,24 @@ static void Creator_cb(struct pdf_struct *pdf, struct pdf_obj *obj, struct pdfna UNUSEDPARAM(act); - if (NULL == pdf) + if (NULL == pdf) { return; + } ctx = pdf->ctx; - if (!(SCAN_COLLECT_METADATA)) + if (!(SCAN_COLLECT_METADATA)) { return; + } if (!(pdf->stats.creator)) { const char *objstart = (obj->objstm) ? (const char *)(obj->start + obj->objstm->streambuf) : (const char *)(obj->start + pdf->map); pdf->stats.creator = calloc(1, sizeof(struct pdf_stats_entry)); - if (!(pdf->stats.creator)) + if (!(pdf->stats.creator)) { return; + } pdf->parse_recursion_depth++; pdf->stats.creator->data = pdf_parse_string(pdf, obj, objstart, obj->size, "/Creator", NULL, &(pdf->stats.creator->meta)); @@ -4337,21 +4484,24 @@ static void ModificationDate_cb(struct pdf_struct *pdf, struct pdf_obj *obj, str UNUSEDPARAM(act); - if (NULL == pdf) + if (NULL == pdf) { return; + } ctx = pdf->ctx; - if (!(SCAN_COLLECT_METADATA)) + if (!(SCAN_COLLECT_METADATA)) { return; + } if (!(pdf->stats.modificationdate)) { const char *objstart = (obj->objstm) ? (const char *)(obj->start + obj->objstm->streambuf) : (const char *)(obj->start + pdf->map); pdf->stats.modificationdate = calloc(1, sizeof(struct pdf_stats_entry)); - if (!(pdf->stats.modificationdate)) + if (!(pdf->stats.modificationdate)) { return; + } pdf->parse_recursion_depth++; pdf->stats.modificationdate->data = pdf_parse_string(pdf, obj, objstart, obj->size, "/ModDate", NULL, &(pdf->stats.modificationdate->meta)); @@ -4365,21 +4515,24 @@ static void CreationDate_cb(struct pdf_struct *pdf, struct pdf_obj *obj, struct UNUSEDPARAM(act); - if (NULL == pdf) + if (NULL == pdf) { return; + } ctx = pdf->ctx; - if (!(SCAN_COLLECT_METADATA)) + if (!(SCAN_COLLECT_METADATA)) { return; + } if (!(pdf->stats.creationdate)) { const char *objstart = (obj->objstm) ? (const char *)(obj->start + obj->objstm->streambuf) : (const char *)(obj->start + pdf->map); pdf->stats.creationdate = calloc(1, sizeof(struct pdf_stats_entry)); - if (!(pdf->stats.creationdate)) + if (!(pdf->stats.creationdate)) { return; + } pdf->parse_recursion_depth++; pdf->stats.creationdate->data = pdf_parse_string(pdf, obj, objstart, obj->size, "/CreationDate", NULL, &(pdf->stats.creationdate->meta)); @@ -4393,21 +4546,24 @@ static void Producer_cb(struct pdf_struct *pdf, struct pdf_obj *obj, struct pdfn UNUSEDPARAM(act); - if (NULL == pdf) + if (NULL == pdf) { return; + } ctx = pdf->ctx; - if (!(SCAN_COLLECT_METADATA)) + if (!(SCAN_COLLECT_METADATA)) { return; + } if (!(pdf->stats.producer)) { const char *objstart = (obj->objstm) ? (const char *)(obj->start + obj->objstm->streambuf) : (const char *)(obj->start + pdf->map); pdf->stats.producer = calloc(1, sizeof(struct pdf_stats_entry)); - if (!(pdf->stats.producer)) + if (!(pdf->stats.producer)) { return; + } pdf->parse_recursion_depth++; pdf->stats.producer->data = pdf_parse_string(pdf, obj, objstart, obj->size, "/Producer", NULL, &(pdf->stats.producer->meta)); @@ -4421,21 +4577,24 @@ static void Title_cb(struct pdf_struct *pdf, struct pdf_obj *obj, struct pdfname UNUSEDPARAM(act); - if (NULL == pdf) + if (NULL == pdf) { return; + } ctx = pdf->ctx; - if (!(SCAN_COLLECT_METADATA)) + if (!(SCAN_COLLECT_METADATA)) { return; + } if (!(pdf->stats.title)) { const char *objstart = (obj->objstm) ? (const char *)(obj->start + obj->objstm->streambuf) : (const char *)(obj->start + pdf->map); pdf->stats.title = calloc(1, sizeof(struct pdf_stats_entry)); - if (!(pdf->stats.title)) + if (!(pdf->stats.title)) { return; + } pdf->parse_recursion_depth++; pdf->stats.title->data = pdf_parse_string(pdf, obj, objstart, obj->size, "/Title", NULL, &(pdf->stats.title->meta)); @@ -4449,21 +4608,24 @@ static void Keywords_cb(struct pdf_struct *pdf, struct pdf_obj *obj, struct pdfn UNUSEDPARAM(act); - if (NULL == pdf) + if (NULL == pdf) { return; + } ctx = pdf->ctx; - if (!(SCAN_COLLECT_METADATA)) + if (!(SCAN_COLLECT_METADATA)) { return; + } if (!(pdf->stats.keywords)) { const char *objstart = (obj->objstm) ? (const char *)(obj->start + obj->objstm->streambuf) : (const char *)(obj->start + pdf->map); pdf->stats.keywords = calloc(1, sizeof(struct pdf_stats_entry)); - if (!(pdf->stats.keywords)) + if (!(pdf->stats.keywords)) { return; + } pdf->parse_recursion_depth++; pdf->stats.keywords->data = pdf_parse_string(pdf, obj, objstart, obj->size, "/Keywords", NULL, &(pdf->stats.keywords->meta)); @@ -4477,21 +4639,24 @@ static void Subject_cb(struct pdf_struct *pdf, struct pdf_obj *obj, struct pdfna UNUSEDPARAM(act); - if (NULL == pdf) + if (NULL == pdf) { return; + } ctx = pdf->ctx; - if (!(SCAN_COLLECT_METADATA)) + if (!(SCAN_COLLECT_METADATA)) { return; + } if (!(pdf->stats.subject)) { const char *objstart = (obj->objstm) ? (const char *)(obj->start + obj->objstm->streambuf) : (const char *)(obj->start + pdf->map); pdf->stats.subject = calloc(1, sizeof(struct pdf_stats_entry)); - if (!(pdf->stats.subject)) + if (!(pdf->stats.subject)) { return; + } pdf->parse_recursion_depth++; pdf->stats.subject->data = pdf_parse_string(pdf, obj, objstart, obj->size, "/Subject", NULL, &(pdf->stats.subject->meta)); @@ -4504,8 +4669,9 @@ static void RichMedia_cb(struct pdf_struct *pdf, struct pdf_obj *obj, struct pdf UNUSEDPARAM(obj); UNUSEDPARAM(act); - if (NULL == pdf) + if (NULL == pdf) { return; + } pdf->stats.nrichmedia++; } @@ -4515,8 +4681,9 @@ static void AcroForm_cb(struct pdf_struct *pdf, struct pdf_obj *obj, struct pdfn UNUSEDPARAM(obj); UNUSEDPARAM(act); - if (NULL == pdf) + if (NULL == pdf) { return; + } pdf->stats.nacroform++; } @@ -4526,8 +4693,9 @@ static void XFA_cb(struct pdf_struct *pdf, struct pdf_obj *obj, struct pdfname_a UNUSEDPARAM(obj); UNUSEDPARAM(act); - if (NULL == pdf) + if (NULL == pdf) { return; + } pdf->stats.nxfa++; } @@ -4547,21 +4715,25 @@ static void Pages_cb(struct pdf_struct *pdf, struct pdf_obj *obj, struct pdfname UNUSEDPARAM(act); - if (!(pdf) || !(pdf->ctx->wrkproperty)) + if (!(pdf) || !(pdf->ctx->wrkproperty)) { return; + } ctx = pdf->ctx; - if (!(SCAN_COLLECT_METADATA)) + if (!(SCAN_COLLECT_METADATA)) { return; + } pdfobj = cli_jsonobj(pdf->ctx->wrkproperty, "PDFStats"); - if (!(pdfobj)) + if (!(pdfobj)) { return; + } begin = cli_memstr(objstart, obj->size, "/Kids", 5); - if (!(begin)) + if (!(begin)) { return; + } begin += 5; @@ -4574,10 +4746,13 @@ static void Pages_cb(struct pdf_struct *pdf, struct pdf_obj *obj, struct pdfname return; } - for (node = array->nodes; node != NULL; node = node->next) - if (node->datasz) - if (strchr((char *)(node->data), 'R')) + for (node = array->nodes; node != NULL; node = node->next) { + if (node->datasz) { + if (strchr((char *)(node->data), 'R')) { npages++; + } + } + } begin = cli_memstr(objstart, obj->size, "/Count", 6); if (!(begin)) { @@ -4586,8 +4761,9 @@ static void Pages_cb(struct pdf_struct *pdf, struct pdf_obj *obj, struct pdfname } begin += 6; - while (((size_t)(begin - objstart) < obj->size) && isspace(begin[0])) + while (((size_t)(begin - objstart) < obj->size) && isspace(begin[0])) { begin++; + } if ((size_t)(begin - objstart) >= obj->size) { goto cleanup; @@ -4623,29 +4799,35 @@ static void Colors_cb(struct pdf_struct *pdf, struct pdf_obj *obj, struct pdfnam UNUSEDPARAM(act); - if (!(pdf) || !(pdf->ctx) || !(pdf->ctx->wrkproperty)) + if (!(pdf) || !(pdf->ctx) || !(pdf->ctx->wrkproperty)) { return; + } ctx = pdf->ctx; - if (!(SCAN_COLLECT_METADATA)) + if (!(SCAN_COLLECT_METADATA)) { return; + } p1 = (char *)cli_memstr(objstart, obj->size, "/Colors", 7); - if (!(p1)) + if (!(p1)) { return; + } p1 += 7; /* Ensure that we have at least one whitespace character plus at least one number */ - if (obj->size - (size_t)(p1 - objstart) < 2) + if (obj->size - (size_t)(p1 - objstart) < 2) { return; + } - while (((size_t)(p1 - objstart) < obj->size) && isspace(p1[0])) + while (((size_t)(p1 - objstart) < obj->size) && isspace(p1[0])) { p1++; + } - if ((size_t)(p1 - objstart) == obj->size) + if ((size_t)(p1 - objstart) == obj->size) { return; + } if (CL_SUCCESS != cli_strntol_wrap(p1, (size_t)((p1 - objstart) - obj->size), 0, 10, &temp_long)) { return; @@ -4655,16 +4837,19 @@ static void Colors_cb(struct pdf_struct *pdf, struct pdf_obj *obj, struct pdfnam ncolors = (unsigned long)temp_long; /* We only care if the number of colors > 2**24 */ - if (ncolors < 1 << 24) + if (ncolors < 1 << 24) { return; + } pdfobj = cli_jsonobj(pdf->ctx->wrkproperty, "PDFStats"); - if (!(pdfobj)) + if (!(pdfobj)) { return; + } colorsobj = cli_jsonarray(pdfobj, "BigColors"); - if (!(colorsobj)) + if (!(colorsobj)) { return; + } cli_jsonint_array(colorsobj, obj->id >> 8); } @@ -4677,57 +4862,65 @@ static void pdf_free_stats(struct pdf_struct *pdf) } if ((pdf->stats.author)) { - if (pdf->stats.author->data) + if (pdf->stats.author->data) { free(pdf->stats.author->data); + } free(pdf->stats.author); pdf->stats.author = NULL; } if (pdf->stats.creator) { - if (pdf->stats.creator->data) + if (pdf->stats.creator->data) { free(pdf->stats.creator->data); + } free(pdf->stats.creator); pdf->stats.creator = NULL; } if (pdf->stats.producer) { - if (pdf->stats.producer->data) + if (pdf->stats.producer->data) { free(pdf->stats.producer->data); + } free(pdf->stats.producer); pdf->stats.producer = NULL; } if (pdf->stats.modificationdate) { - if (pdf->stats.modificationdate->data) + if (pdf->stats.modificationdate->data) { free(pdf->stats.modificationdate->data); + } free(pdf->stats.modificationdate); pdf->stats.modificationdate = NULL; } if (pdf->stats.creationdate) { - if (pdf->stats.creationdate->data) + if (pdf->stats.creationdate->data) { free(pdf->stats.creationdate->data); + } free(pdf->stats.creationdate); pdf->stats.creationdate = NULL; } if (pdf->stats.title) { - if (pdf->stats.title->data) + if (pdf->stats.title->data) { free(pdf->stats.title->data); + } free(pdf->stats.title); pdf->stats.title = NULL; } if (pdf->stats.subject) { - if (pdf->stats.subject->data) + if (pdf->stats.subject->data) { free(pdf->stats.subject->data); + } free(pdf->stats.subject); pdf->stats.subject = NULL; } if (pdf->stats.keywords) { - if (pdf->stats.keywords->data) + if (pdf->stats.keywords->data) { free(pdf->stats.keywords->data); + } free(pdf->stats.keywords); pdf->stats.keywords = NULL; } @@ -4739,8 +4932,9 @@ static void pdf_export_json(struct pdf_struct *pdf) json_object *pdfobj; unsigned long i; - if (NULL == pdf) + if (NULL == pdf) { return; + } if (!(pdf->ctx)) { goto cleanup; @@ -4933,70 +5127,100 @@ static void pdf_export_json(struct pdf_struct *pdf) cli_jsonstr(pdfobj, "Keywords", ""); } } - if (pdf->stats.ninvalidobjs) + if (pdf->stats.ninvalidobjs) { cli_jsonint(pdfobj, "InvalidObjectCount", pdf->stats.ninvalidobjs); - if (pdf->stats.njs) + } + if (pdf->stats.njs) { cli_jsonint(pdfobj, "JavaScriptObjectCount", pdf->stats.njs); - if (pdf->stats.nflate) + } + if (pdf->stats.nflate) { cli_jsonint(pdfobj, "DeflateObjectCount", pdf->stats.nflate); - if (pdf->stats.nactivex) + } + if (pdf->stats.nactivex) { cli_jsonint(pdfobj, "ActiveXObjectCount", pdf->stats.nactivex); - if (pdf->stats.nflash) + } + if (pdf->stats.nflash) { cli_jsonint(pdfobj, "FlashObjectCount", pdf->stats.nflash); - if (pdf->stats.ncolors) + } + if (pdf->stats.ncolors) { cli_jsonint(pdfobj, "ColorCount", pdf->stats.ncolors); - if (pdf->stats.nasciihexdecode) + } + if (pdf->stats.nasciihexdecode) { cli_jsonint(pdfobj, "AsciiHexDecodeObjectCount", pdf->stats.nasciihexdecode); - if (pdf->stats.nascii85decode) + } + if (pdf->stats.nascii85decode) { cli_jsonint(pdfobj, "Ascii85DecodeObjectCount", pdf->stats.nascii85decode); - if (pdf->stats.nembeddedfile) + } + if (pdf->stats.nembeddedfile) { cli_jsonint(pdfobj, "EmbeddedFileCount", pdf->stats.nembeddedfile); - if (pdf->stats.nimage) + } + if (pdf->stats.nimage) { cli_jsonint(pdfobj, "ImageCount", pdf->stats.nimage); - if (pdf->stats.nlzw) + } + if (pdf->stats.nlzw) { cli_jsonint(pdfobj, "LZWCount", pdf->stats.nlzw); - if (pdf->stats.nrunlengthdecode) + } + if (pdf->stats.nrunlengthdecode) { cli_jsonint(pdfobj, "RunLengthDecodeCount", pdf->stats.nrunlengthdecode); - if (pdf->stats.nfaxdecode) + } + if (pdf->stats.nfaxdecode) { cli_jsonint(pdfobj, "FaxDecodeCount", pdf->stats.nfaxdecode); - if (pdf->stats.njbig2decode) + } + if (pdf->stats.njbig2decode) { cli_jsonint(pdfobj, "JBIG2DecodeCount", pdf->stats.njbig2decode); - if (pdf->stats.ndctdecode) + } + if (pdf->stats.ndctdecode) { cli_jsonint(pdfobj, "DCTDecodeCount", pdf->stats.ndctdecode); - if (pdf->stats.njpxdecode) + } + if (pdf->stats.njpxdecode) { cli_jsonint(pdfobj, "JPXDecodeCount", pdf->stats.njpxdecode); - if (pdf->stats.ncrypt) + } + if (pdf->stats.ncrypt) { cli_jsonint(pdfobj, "CryptCount", pdf->stats.ncrypt); - if (pdf->stats.nstandard) + } + if (pdf->stats.nstandard) { cli_jsonint(pdfobj, "StandardCount", pdf->stats.nstandard); - if (pdf->stats.nsigned) + } + if (pdf->stats.nsigned) { cli_jsonint(pdfobj, "SignedCount", pdf->stats.nsigned); - if (pdf->stats.nopenaction) + } + if (pdf->stats.nopenaction) { cli_jsonint(pdfobj, "OpenActionCount", pdf->stats.nopenaction); - if (pdf->stats.nlaunch) + } + if (pdf->stats.nlaunch) { cli_jsonint(pdfobj, "LaunchCount", pdf->stats.nlaunch); - if (pdf->stats.npage) + } + if (pdf->stats.npage) { cli_jsonint(pdfobj, "PageCount", pdf->stats.npage); - if (pdf->stats.nrichmedia) + } + if (pdf->stats.nrichmedia) { cli_jsonint(pdfobj, "RichMediaCount", pdf->stats.nrichmedia); - if (pdf->stats.nacroform) + } + if (pdf->stats.nacroform) { cli_jsonint(pdfobj, "AcroFormCount", pdf->stats.nacroform); - if (pdf->stats.nxfa) + } + if (pdf->stats.nxfa) { cli_jsonint(pdfobj, "XFACount", pdf->stats.nxfa); - if (pdf->flags & (1 << BAD_PDF_VERSION)) + } + if (pdf->flags & (1 << BAD_PDF_VERSION)) { cli_jsonbool(pdfobj, "BadVersion", 1); - if (pdf->flags & (1 << BAD_PDF_HEADERPOS)) + } + if (pdf->flags & (1 << BAD_PDF_HEADERPOS)) { cli_jsonbool(pdfobj, "BadHeaderPosition", 1); - if (pdf->flags & (1 << BAD_PDF_TRAILER)) + } + if (pdf->flags & (1 << BAD_PDF_TRAILER)) { cli_jsonbool(pdfobj, "BadTrailer", 1); - if (pdf->flags & (1 << BAD_PDF_TOOMANYOBJS)) + } + if (pdf->flags & (1 << BAD_PDF_TOOMANYOBJS)) { cli_jsonbool(pdfobj, "TooManyObjects", 1); + } if (pdf->flags & (1 << ENCRYPTED_PDF)) { cli_jsonbool(pdfobj, "Encrypted", 1); - if (pdf->flags & (1 << DECRYPTABLE_PDF)) + if (pdf->flags & (1 << DECRYPTABLE_PDF)) { cli_jsonbool(pdfobj, "Decryptable", 1); - else + } else { cli_jsonbool(pdfobj, "Decryptable", 0); + } } for (i = 0; i < pdf->nobjs; i++) { @@ -5004,8 +5228,9 @@ static void pdf_export_json(struct pdf_struct *pdf) json_object *truncobj; truncobj = cli_jsonarray(pdfobj, "TruncatedObjects"); - if (!(truncobj)) + if (!(truncobj)) { continue; + } cli_jsonint_array(truncobj, pdf->objs[i]->id >> 8); } diff --git a/libclamav/pdfdecode.c b/libclamav/pdfdecode.c index ca8be3f482..b374cf660b 100644 --- a/libclamav/pdfdecode.c +++ b/libclamav/pdfdecode.c @@ -142,8 +142,9 @@ size_t pdf_decodestream( } token->flags = 0; - if (xref) + if (xref) { token->flags |= PDFTOKEN_FLAG_XREF; + } token->success = 0; @@ -243,9 +244,9 @@ static size_t pdf_decodestream_internal( * if none, force a DECRYPT filter application */ if ((pdf->flags & (1 << DECRYPTABLE_PDF)) && !(obj->flags & (1 << OBJ_FILTER_CRYPT))) { - if (token->flags & PDFTOKEN_FLAG_XREF) /* TODO: is this on all crypt filters or only the assumed one? */ + if (token->flags & PDFTOKEN_FLAG_XREF) { /* TODO: is this on all crypt filters or only the assumed one? */ cli_dbgmsg("pdf_decodestream_internal: skipping decoding => non-filter CRYPT (reason: xref)\n"); - else { + } else { cli_dbgmsg("pdf_decodestream_internal: decoding => non-filter CRYPT\n"); retval = filter_decrypt(pdf, obj, params, token, 1); if (retval != CL_SUCCESS) { @@ -288,16 +289,24 @@ static size_t pdf_decodestream_internal( break; case OBJ_FILTER_JPX: - if (!filter) filter = "JPXDECODE"; + if (!filter) { + filter = "JPXDECODE"; + } /*fallthrough*/ case OBJ_FILTER_DCT: - if (!filter) filter = "DCTDECODE"; + if (!filter) { + filter = "DCTDECODE"; + } /*fallthrough*/ case OBJ_FILTER_FAX: - if (!filter) filter = "FAXDECODE"; + if (!filter) { + filter = "FAXDECODE"; + } /*fallthrough*/ case OBJ_FILTER_JBIG2: - if (!filter) filter = "JBIG2DECODE"; + if (!filter) { + filter = "JBIG2DECODE"; + } cli_dbgmsg("pdf_decodestream_internal: unimplemented filter type [%u] => %s\n", obj->filterlist[i], filter); filter = NULL; @@ -411,14 +420,16 @@ static cl_error_t filter_ascii85decode(struct pdf_struct *pdf, struct pdf_obj *o return CL_EMEM; } - if (cli_memstr((const char *)ptr, remaining, "~>", 2) == NULL) + if (cli_memstr((const char *)ptr, remaining, "~>", 2) == NULL) { cli_dbgmsg("cli_pdf: no EOF marker found\n"); + } while (remaining > 0) { int byte = (remaining--) ? (int)*ptr++ : EOF; - if ((byte == '~') && (remaining > 0) && (*ptr == '>')) + if ((byte == '~') && (remaining > 0) && (*ptr == '>')) { byte = EOF; + } if (byte >= '!' && byte <= 'u') { sum = (sum * 85) + ((uint32_t)byte - '!'); @@ -456,14 +467,17 @@ static cl_error_t filter_ascii85decode(struct pdf_struct *pdf, struct pdf_obj *o break; } - for (i = quintet; i < 5; i++) + for (i = quintet; i < 5; i++) { sum *= 85; + } - if (quintet > 1) + if (quintet > 1) { sum += (0xFFFFFF >> ((quintet - 2) * 8)); + } - for (i = 0; i < quintet - 1; i++) + for (i = 0; i < quintet - 1; i++) { *dptr++ = (uint8_t)((sum >> (24 - 8 * i)) & 0xFF); + } declen += quintet - 1; } @@ -486,8 +500,9 @@ static cl_error_t filter_ascii85decode(struct pdf_struct *pdf, struct pdf_obj *o token->content = decoded; token->length = declen; } else { - if (!(obj->flags & ((1 << OBJ_IMAGE) | (1 << OBJ_TRUNCATED)))) + if (!(obj->flags & ((1 << OBJ_IMAGE) | (1 << OBJ_TRUNCATED)))) { pdfobj_flag(pdf, obj, BAD_ASCIIDECODE); + } cli_dbgmsg("cli_pdf: error occurred parsing byte %lu of %lu\n", (unsigned long)(token->length - remaining), (unsigned long)(token->length)); @@ -528,8 +543,9 @@ static cl_error_t filter_rldecode(struct pdf_struct *pdf, struct pdf_obj *obj, s } if (declen + srclen + 1 > capacity) { - if ((rc = cli_checklimits("pdf", pdf->ctx, capacity + INFLATE_CHUNK_SIZE, 0, 0)) != CL_SUCCESS) + if ((rc = cli_checklimits("pdf", pdf->ctx, capacity + INFLATE_CHUNK_SIZE, 0, 0)) != CL_SUCCESS) { break; + } if (!(temp = cli_max_realloc(decoded, capacity + INFLATE_CHUNK_SIZE))) { cli_errmsg("cli_pdf: cannot reallocate memory for decoded output\n"); @@ -613,10 +629,11 @@ static uint8_t *decode_nextlinestart(uint8_t *content, uint32_t length) int toggle = 0; for (r = 0; r < length; r++, pt++) { - if (*pt == '\n' || *pt == '\r') + if (*pt == '\n' || *pt == '\r') { toggle = 1; - else if (toggle) + } else if (toggle) { break; + } } return pt; @@ -642,8 +659,9 @@ static cl_error_t filter_flatedecode(struct pdf_struct *pdf, struct pdf_obj *obj * Sample 0015315109, it has \r followed by zlib header. * Flag pdf as suspicious, and attempt to extract by skipping the \r. */ - if (!length) + if (!length) { return CL_SUCCESS; + } } capacity = INFLATE_CHUNK_SIZE; @@ -739,12 +757,13 @@ static cl_error_t filter_flatedecode(struct pdf_struct *pdf, struct pdf_obj *obj case Z_DATA_ERROR: case Z_MEM_ERROR: default: - if (stream.msg) + if (stream.msg) { cli_dbgmsg("cli_pdf: after writing %lu bytes, got error \"%s\" inflating PDF stream in %u %u obj\n", (unsigned long)declen, stream.msg, obj->id >> 8, obj->id & 0xff); - else + } else { cli_dbgmsg("cli_pdf: after writing %lu bytes, got error %d inflating PDF stream in %u %u obj\n", (unsigned long)declen, zstat, obj->id >> 8, obj->id & 0xff); + } if (declen == 0) { pdfobj_flag(pdf, obj, BAD_FLATESTART); @@ -801,15 +820,18 @@ static cl_error_t filter_asciihexdecode(struct pdf_struct *pdf, struct pdf_obj * } for (i = 0, j = 0; i + 1 < length; i++) { - if (content[i] == ' ') + if (content[i] == ' ') { continue; + } - if (content[i] == '>') + if (content[i] == '>') { break; + } if (cli_hex2str_to((const char *)content + i, (char *)decoded + j, 2) == -1) { - if (length - i < 4) + if (length - i < 4) { continue; + } rc = CL_EFORMAT; break; @@ -828,8 +850,9 @@ static cl_error_t filter_asciihexdecode(struct pdf_struct *pdf, struct pdf_obj * token->content = decoded; token->length = j; } else { - if (!(obj->flags & ((1 << OBJ_IMAGE) | (1 << OBJ_TRUNCATED)))) + if (!(obj->flags & ((1 << OBJ_IMAGE) | (1 << OBJ_TRUNCATED)))) { pdfobj_flag(pdf, obj, BAD_ASCIIDECODE); + } cli_dbgmsg("cli_pdf: error occurred parsing byte %lu of %lu\n", (unsigned long)i, (unsigned long)(token->length)); @@ -845,21 +868,23 @@ static cl_error_t filter_decrypt(struct pdf_struct *pdf, struct pdf_obj *obj, st size_t length = (size_t)token->length; enum enc_method enc = ENC_IDENTITY; - if (mode) + if (mode) { enc = get_enc_method(pdf, obj); - else if (params) { + } else if (params) { struct pdf_dict_node *node = params->nodes; while (node) { if (node->type == PDF_DICT_STRING) { if (!strncmp(node->key, "/Type", 6)) { /* optional field - Type */ /* MUST be "CryptFilterDecodeParms" */ - if (node->value) + if (node->value) { cli_dbgmsg("cli_pdf: Type: %s\n", (char *)(node->value)); + } } else if (!strncmp(node->key, "/Name", 6)) { /* optional field - Name */ /* overrides document and default encryption method */ - if (node->value) + if (node->value) { cli_dbgmsg("cli_pdf: Name: %s\n", (char *)(node->value)); + } enc = parse_enc_method(pdf->CF, pdf->CF_n, (char *)(node->value), enc); } } @@ -892,8 +917,9 @@ static cl_error_t filter_lzwdecode(struct pdf_struct *pdf, struct pdf_obj *obj, lzw_stream stream; int echg = 1, lzwstat, rc = CL_SUCCESS; - if (pdf->ctx && !(pdf->ctx->dconf->other & OTHER_CONF_LZW)) + if (pdf->ctx && !(pdf->ctx->dconf->other & OTHER_CONF_LZW)) { return CL_BREAK; + } if (params) { struct pdf_dict_node *node = params->nodes; @@ -907,8 +933,9 @@ static cl_error_t filter_lzwdecode(struct pdf_struct *pdf, struct pdf_obj *obj, if (value) { cli_dbgmsg("cli_pdf: EarlyChange: %s\n", value); set = strtol(value, &end, 10); - if (end != value) + if (end != value) { echg = (int)set; + } } } } @@ -924,8 +951,9 @@ static cl_error_t filter_lzwdecode(struct pdf_struct *pdf, struct pdf_obj *obj, * Sample 0015315109, it has \r followed by zlib header. * Flag pdf as suspicious, and attempt to extract by skipping the \r. */ - if (!length) + if (!length) { return CL_SUCCESS; + } } capacity = INFLATE_CHUNK_SIZE; @@ -940,8 +968,9 @@ static cl_error_t filter_lzwdecode(struct pdf_struct *pdf, struct pdf_obj *obj, stream.avail_in = length; stream.next_out = decoded; stream.avail_out = INFLATE_CHUNK_SIZE; - if (echg) + if (echg) { stream.flags |= LZW_FLAG_EARLYCHG; + } lzwstat = lzwInit(&stream); if (lzwstat != Z_OK) { @@ -1024,12 +1053,13 @@ static cl_error_t filter_lzwdecode(struct pdf_struct *pdf, struct pdf_obj *obj, case LZW_BUF_ERROR: case LZW_DICT_ERROR: default: - if (stream.msg) + if (stream.msg) { cli_dbgmsg("cli_pdf: after writing %lu bytes, got error \"%s\" inflating PDF stream in %u %u obj\n", (unsigned long)declen, stream.msg, obj->id >> 8, obj->id & 0xff); - else + } else { cli_dbgmsg("cli_pdf: after writing %lu bytes, got error %d inflating PDF stream in %u %u obj\n", (unsigned long)declen, lzwstat, obj->id >> 8, obj->id & 0xff); + } if (declen == 0) { pdfobj_flag(pdf, obj, BAD_FLATESTART); diff --git a/libclamav/pdfng.c b/libclamav/pdfng.c index 92267e5469..529d7d25cd 100644 --- a/libclamav/pdfng.c +++ b/libclamav/pdfng.c @@ -87,8 +87,9 @@ char *pdf_convert_utf(char *begin, size_t sz) #endif buf = cli_max_calloc(1, sz + 1); - if (!(buf)) + if (!(buf)) { return NULL; + } memcpy(buf, begin, sz); #if HAVE_ICONV @@ -159,66 +160,81 @@ int is_object_reference(char *begin, char **endchar, uint32_t *id) */ /* Skip whitespace */ - while (p1 < end && isspace(p1[0])) + while (p1 < end && isspace(p1[0])) { p1++; + } - if (p1 == end) + if (p1 == end) { return 0; + } - if (!isdigit(p1[0])) + if (!isdigit(p1[0])) { return 0; + } /* Ensure strtoul() isn't going to go past our buffer */ p2 = p1 + 1; - while (p2 < end && !isspace(p2[0])) + while (p2 < end && !isspace(p2[0])) { p2++; + } - if (p2 == end) + if (p2 == end) { return 0; + } n = strtoul(p1, &p2, 10); - if (n == ULONG_MAX && errno) + if (n == ULONG_MAX && errno) { return 0; + } t = n << 8; /* Skip more whitespace */ p1 = p2; - while (p1 < end && isspace(p1[0])) + while (p1 < end && isspace(p1[0])) { p1++; + } - if (p1 == end) + if (p1 == end) { return 0; + } - if (!isdigit(p1[0])) + if (!isdigit(p1[0])) { return 0; + } /* Ensure strtoul() is going to go past our buffer */ p2 = p1 + 1; - while (p2 < end && !isspace(p2[0])) + while (p2 < end && !isspace(p2[0])) { p2++; + } - if (p2 == end) + if (p2 == end) { return 0; + } n = strtoul(p1, &p2, 10); - if (n == ULONG_MAX && errno) + if (n == ULONG_MAX && errno) { return 0; + } t |= (n & 0xff); /* Skip even more whitespace */ p1 = p2; - while (p1 < end && isspace(p1[0])) + while (p1 < end && isspace(p1[0])) { p1++; + } - if (p1 == end) + if (p1 == end) { return 0; + } if (p1[0] == 'R') { *endchar = p1 + 1; - if (id) + if (id) { *id = t; + } return 1; } @@ -307,13 +323,15 @@ char *pdf_finalize_string(struct pdf_struct *pdf, struct pdf_obj *obj, const cha size_t wrklen = len, outlen, i; unsigned int likelyutf = 0; - if (!in) + if (!in) { return NULL; + } /* get a working copy */ wrkstr = cli_max_calloc(len + 1, sizeof(char)); - if (!wrkstr) + if (!wrkstr) { return NULL; + } memcpy(wrkstr, in, len); // cli_errmsg("pdf_final: start(%d): %s\n", wrklen, wrkstr); @@ -341,8 +359,9 @@ char *pdf_finalize_string(struct pdf_struct *pdf, struct pdf_obj *obj, const cha value = (char)strtoul(octal, &check, 8); /* check if all characters were converted */ - if (check == &octal[3]) + if (check == &octal[3]) { output[outlen++] = value; + } i += 3; /* 4 with for loop [\ddd] */ } else { /* other sequences */ @@ -476,26 +495,32 @@ char *pdf_parse_string(struct pdf_struct *pdf, struct pdf_obj *obj, const char * if (str) { checklen = strlen(str); - if (objsize < strlen(str) + 3) + if (objsize < strlen(str) + 3) { return NULL; + } - for (p1 = (char *)q; (size_t)(p1 - q) < objsize - checklen; p1++) - if (!strncmp(p1, str, checklen)) + for (p1 = (char *)q; (size_t)(p1 - q) < objsize - checklen; p1++) { + if (!strncmp(p1, str, checklen)) { break; + } + } - if ((size_t)(p1 - q) == objsize - checklen) + if ((size_t)(p1 - q) == objsize - checklen) { return NULL; + } p1 += checklen; } else { p1 = (char *)q; } - while ((size_t)(p1 - q) < objsize && isspace(p1[0])) + while ((size_t)(p1 - q) < objsize && isspace(p1[0])) { p1++; + } - if ((size_t)(p1 - q) == objsize) + if ((size_t)(p1 - q) == objsize) { return NULL; + } /* * If str is non-null: @@ -515,23 +540,26 @@ char *pdf_parse_string(struct pdf_struct *pdf, struct pdf_obj *obj, const char * size_t objsize2; newobj = find_obj(pdf, obj, objid); - if (!(newobj)) + if (!(newobj)) { return NULL; + } if (!CLI_ISCONTAINED(pdf->map, pdf->size, newobj->start, newobj->size)) { cli_dbgmsg("pdf_parse_string: object not contained in PDF\n"); return NULL; } - if (newobj == obj) + if (newobj == obj) { return NULL; + } /* * If pdf_handlename hasn't been called for this object, * then parse the object prior to extracting it */ - if (!(newobj->statsflags & OBJ_FLAG_PDFNAME_DONE)) + if (!(newobj->statsflags & OBJ_FLAG_PDFNAME_DONE)) { pdf_parseobj(pdf, newobj); + } /* Extract the object. Force pdf_extract_obj() to dump this object. */ objflags = newobj->flags; @@ -546,8 +574,9 @@ char *pdf_parse_string(struct pdf_struct *pdf, struct pdf_obj *obj, const char * newobj->flags = objflags; - if (!(newobj->path)) + if (!(newobj->path)) { return NULL; + } fd = open(newobj->path, O_RDONLY | O_BINARY); if (fd == -1) { @@ -632,8 +661,9 @@ char *pdf_parse_string(struct pdf_struct *pdf, struct pdf_obj *obj, const char * free(newobj->path); newobj->path = NULL; - if (endchar) + if (endchar) { *endchar = p2; + } return res; } @@ -642,8 +672,9 @@ char *pdf_parse_string(struct pdf_struct *pdf, struct pdf_obj *obj, const char * /* Hex string */ p2 = p1 + 1; - while ((size_t)(p2 - objstart) < objsize && *p2 != '>') + while ((size_t)(p2 - objstart) < objsize && *p2 != '>') { p2++; + } if ((size_t)(p2 - objstart) == objsize) { return NULL; @@ -652,8 +683,9 @@ char *pdf_parse_string(struct pdf_struct *pdf, struct pdf_obj *obj, const char * res = pdf_finalize_string(pdf, obj, p1, (p2 - p1) + 1); if (!res) { res = cli_max_calloc(1, (p2 - p1) + 2); - if (!(res)) + if (!(res)) { return NULL; + } memcpy(res, p1, (p2 - p1) + 1); res[(p2 - p1) + 1] = '\0'; @@ -668,15 +700,17 @@ char *pdf_parse_string(struct pdf_struct *pdf, struct pdf_obj *obj, const char * meta->success = 1; } - if (res && endchar) + if (res && endchar) { *endchar = p2; + } return res; } /* We should be at the start of a string literal (...) here */ - if (*p1 != '(') + if (*p1 != '(') { return NULL; + } /* Make a best effort to find the end of the string and determine if UTF-* */ p2 = ++p1; @@ -701,16 +735,18 @@ char *pdf_parse_string(struct pdf_struct *pdf, struct pdf_obj *obj, const char * p2++; } - if (p2 >= objstart + objsize) + if (p2 >= objstart + objsize) { return NULL; + } len = (size_t)(p2 - p1) + 1; res = pdf_finalize_string(pdf, obj, p1, len); if (!res) { res = cli_max_calloc(1, len + 1); - if (!(res)) + if (!(res)) { return NULL; + } memcpy(res, p1, len); res[len] = '\0'; @@ -725,8 +761,9 @@ char *pdf_parse_string(struct pdf_struct *pdf, struct pdf_obj *obj, const char * meta->success = 1; } - if (res && endchar) + if (res && endchar) { *endchar = p2; + } return res; } @@ -740,8 +777,9 @@ struct pdf_dict *pdf_parse_dict(struct pdf_struct *pdf, struct pdf_obj *obj, siz unsigned int in_string = 0, ninner = 0; /* Sanity checking */ - if (!(pdf) || !(obj) || !(begin)) + if (!(pdf) || !(obj) || !(begin)) { return NULL; + } if (PDF_OBJECT_RECURSION_LIMIT < pdf->parse_recursion_depth) { cli_dbgmsg("pdf_parse_dict: Recursion limit reached\n"); @@ -751,11 +789,13 @@ struct pdf_dict *pdf_parse_dict(struct pdf_struct *pdf, struct pdf_obj *obj, siz objstart = (obj->objstm) ? (const char *)(obj->start + obj->objstm->streambuf) : (const char *)(obj->start + pdf->map); - if (begin < objstart || (size_t)(begin - objstart) >= objsize - 2) + if (begin < objstart || (size_t)(begin - objstart) >= objsize - 2) { return NULL; + } - if (begin[0] != '<' || begin[1] != '<') + if (begin[0] != '<' || begin[1] != '<') { return NULL; + } /* Find the end of the dictionary */ end = begin; @@ -767,8 +807,9 @@ struct pdf_dict *pdf_parse_dict(struct pdf_struct *pdf, struct pdf_obj *obj, siz continue; } - if (*end == ')') + if (*end == ')') { in_string = 0; + } end++; continue; @@ -779,34 +820,41 @@ struct pdf_dict *pdf_parse_dict(struct pdf_struct *pdf, struct pdf_obj *obj, siz in_string = 1; break; case '<': - if ((size_t)(end - objstart) <= objsize - 2 && end[1] == '<') + if ((size_t)(end - objstart) <= objsize - 2 && end[1] == '<') { ninner++; + } increment = 2; break; case '>': - if ((size_t)(end - objstart) <= objsize - 2 && end[1] == '>') + if ((size_t)(end - objstart) <= objsize - 2 && end[1] == '>') { ninner--; + } increment = 2; break; } - if ((size_t)(end - objstart) <= objsize - 2) - if (end[0] == '>' && end[1] == '>' && ninner == 0) + if ((size_t)(end - objstart) <= objsize - 2) { + if (end[0] == '>' && end[1] == '>' && ninner == 0) { break; + } + } end += increment; } /* More sanity checking */ - if ((size_t)(end - objstart) >= objsize - 2) + if ((size_t)(end - objstart) >= objsize - 2) { return NULL; + } - if (end[0] != '>' || end[1] != '>') + if (end[0] != '>' || end[1] != '>') { return NULL; + } res = calloc(1, sizeof(struct pdf_dict)); - if (!(res)) + if (!(res)) { return NULL; + } /* Loop through each element of the dictionary */ begin += 2; @@ -817,11 +865,13 @@ struct pdf_dict *pdf_parse_dict(struct pdf_struct *pdf, struct pdf_obj *obj, siz unsigned int nhex = 0, i; /* Skip any whitespaces */ - while (begin < end && isspace(begin[0])) + while (begin < end && isspace(begin[0])) { begin++; + } - if (begin == end) + if (begin == end) { break; + } /* Get the key */ p1 = begin + 1; @@ -852,18 +902,21 @@ struct pdf_dict *pdf_parse_dict(struct pdf_struct *pdf, struct pdf_obj *obj, siz break; } - if (breakout) + if (breakout) { break; + } p1++; } - if (p1 == end) + if (p1 == end) { break; + } key = cli_max_calloc((p1 - begin) + 2, 1); - if (!(key)) + if (!(key)) { break; + } if (nhex == 0) { /* Key isn't obfuscated with hex. Just copy the string */ @@ -884,8 +937,9 @@ struct pdf_dict *pdf_parse_dict(struct pdf_struct *pdf, struct pdf_obj *obj, siz begin = p1; /* Skip any whitespaces */ - while (begin < end && isspace(begin[0])) + while (begin < end && isspace(begin[0])) { begin++; + } if (begin == end) { free(key); @@ -932,8 +986,9 @@ struct pdf_dict *pdf_parse_dict(struct pdf_struct *pdf, struct pdf_obj *obj, siz break; } - if (shouldbreak) + if (shouldbreak) { break; + } p1++; } @@ -941,16 +996,18 @@ struct pdf_dict *pdf_parse_dict(struct pdf_struct *pdf, struct pdf_obj *obj, siz is_object_reference(begin, &p1, NULL); val = cli_max_calloc((p1 - begin) + 2, 1); - if (!(val)) + if (!(val)) { break; + } strncpy(val, begin, p1 - begin); val[p1 - begin] = '\0'; - if (p1[0] != '/') + if (p1[0] != '/') { begin = p1 + 1; - else + } else { begin = p1; + } break; } @@ -964,30 +1021,37 @@ struct pdf_dict *pdf_parse_dict(struct pdf_struct *pdf, struct pdf_obj *obj, siz res->nodes = res->tail = node = calloc(1, sizeof(struct pdf_dict_node)); if (!(node)) { free(key); - if (dict) + if (dict) { pdf_free_dict(dict); - if (val) + } + if (val) { free(val); - if (arr) + } + if (arr) { pdf_free_array(arr); + } break; } } else { node = calloc(1, sizeof(struct pdf_dict_node)); if (!(node)) { free(key); - if (dict) + if (dict) { pdf_free_dict(dict); - if (val) + } + if (val) { free(val); - if (arr) + } + if (arr) { pdf_free_array(arr); + } break; } node->prev = res->tail; - if (res->tail) + if (res->tail) { res->tail->next = node; + } res->tail = node; } @@ -1007,8 +1071,9 @@ struct pdf_dict *pdf_parse_dict(struct pdf_struct *pdf, struct pdf_obj *obj, siz } } - if (endchar) + if (endchar) { *endchar = end; + } return res; } @@ -1022,8 +1087,9 @@ struct pdf_array *pdf_parse_array(struct pdf_struct *pdf, struct pdf_obj *obj, s int in_string = 0, ninner = 0; /* Sanity checking */ - if (!(pdf) || !(obj) || !(begin)) + if (!(pdf) || !(obj) || !(begin)) { return NULL; + } if (PDF_OBJECT_RECURSION_LIMIT < pdf->parse_recursion_depth) { cli_dbgmsg("pdf_parse_array: Recursion limit reached\n"); @@ -1033,11 +1099,13 @@ struct pdf_array *pdf_parse_array(struct pdf_struct *pdf, struct pdf_obj *obj, s objstart = (obj->objstm) ? (const char *)(obj->start + obj->objstm->streambuf) : (const char *)(obj->start + pdf->map); - if (begin < objstart || (size_t)(begin - objstart) >= objsize) + if (begin < objstart || (size_t)(begin - objstart) >= objsize) { return NULL; + } - if (begin[0] != '[') + if (begin[0] != '[') { return NULL; + } /* Find the end of the array */ end = begin; @@ -1048,8 +1116,9 @@ struct pdf_array *pdf_parse_array(struct pdf_struct *pdf, struct pdf_obj *obj, s continue; } - if (*end == ')') + if (*end == ')') { in_string = 0; + } end++; continue; @@ -1067,22 +1136,26 @@ struct pdf_array *pdf_parse_array(struct pdf_struct *pdf, struct pdf_obj *obj, s break; } - if (*end == ']' && ninner == 0) + if (*end == ']' && ninner == 0) { break; + } end++; } /* More sanity checking */ - if ((size_t)(end - objstart) >= objsize) + if ((size_t)(end - objstart) >= objsize) { return NULL; + } - if (*end != ']') + if (*end != ']') { return NULL; + } res = calloc(1, sizeof(struct pdf_array)); - if (!(res)) + if (!(res)) { return NULL; + } begin++; while (begin < end) { @@ -1090,11 +1163,13 @@ struct pdf_array *pdf_parse_array(struct pdf_struct *pdf, struct pdf_obj *obj, s struct pdf_array *arr = NULL; struct pdf_dict *dict = NULL; - while (begin < end && isspace(begin[0])) + while (begin < end && isspace(begin[0])) { begin++; + } - if (begin == end) + if (begin == end) { break; + } switch (begin[0]) { case '<': @@ -1124,13 +1199,15 @@ struct pdf_array *pdf_parse_array(struct pdf_struct *pdf, struct pdf_obj *obj, s p1 = end; if (!is_object_reference(begin, &p1, NULL)) { p1 = begin + 1; - while (p1 < end && !isspace(p1[0])) + while (p1 < end && !isspace(p1[0])) { p1++; + } } val = cli_max_calloc((p1 - begin) + 2, 1); - if (!(val)) + if (!(val)) { break; + } strncpy(val, begin, p1 - begin); val[p1 - begin] = '\0'; @@ -1140,37 +1217,45 @@ struct pdf_array *pdf_parse_array(struct pdf_struct *pdf, struct pdf_obj *obj, s } /* Parse error, just return what we could */ - if (!(val) && !(arr) && !(dict)) + if (!(val) && !(arr) && !(dict)) { break; + } if (!(node)) { res->nodes = res->tail = node = calloc(1, sizeof(struct pdf_array_node)); if (!(node)) { - if (dict) + if (dict) { pdf_free_dict(dict); - if (val) + } + if (val) { free(val); - if (arr) + } + if (arr) { pdf_free_array(arr); + } break; } } else { node = calloc(1, sizeof(struct pdf_array_node)); if (!(node)) { - if (dict) + if (dict) { pdf_free_dict(dict); - if (val) + } + if (val) { free(val); - if (arr) + } + if (arr) { pdf_free_array(arr); + } break; } node->prev = res->tail; - if (res->tail) + if (res->tail) { res->tail->next = node; + } res->tail = node; } @@ -1189,8 +1274,9 @@ struct pdf_array *pdf_parse_array(struct pdf_struct *pdf, struct pdf_obj *obj, s } } - if (endchar) + if (endchar) { *endchar = end; + } return res; } @@ -1203,12 +1289,13 @@ void pdf_free_dict(struct pdf_dict *dict) while (node != NULL) { free(node->key); - if (node->type == PDF_DICT_STRING) + if (node->type == PDF_DICT_STRING) { free(node->value); - else if (node->type == PDF_DICT_ARRAY) + } else if (node->type == PDF_DICT_ARRAY) { pdf_free_array((struct pdf_array *)(node->value)); - else if (node->type == PDF_DICT_DICT) + } else if (node->type == PDF_DICT_DICT) { pdf_free_dict((struct pdf_dict *)(node->value)); + } next = node->next; free(node); @@ -1222,17 +1309,19 @@ void pdf_free_array(struct pdf_array *array) { struct pdf_array_node *node, *next; - if (!(array)) + if (!(array)) { return; + } node = array->nodes; while (node != NULL) { - if (node->type == PDF_ARR_ARRAY) + if (node->type == PDF_ARR_ARRAY) { pdf_free_array((struct pdf_array *)(node->data)); - else if (node->type == PDF_ARR_DICT) + } else if (node->type == PDF_ARR_DICT) { pdf_free_dict((struct pdf_dict *)(node->data)); - else + } else { free(node->data); + } next = node->next; free(node); @@ -1248,10 +1337,11 @@ void pdf_print_array(struct pdf_array *array, unsigned long depth) unsigned long i; for (i = 0, node = array->nodes; node != NULL; node = node->next, i++) { - if (node->type == PDF_ARR_STRING) + if (node->type == PDF_ARR_STRING) { cli_errmsg("array[%lu][%lu]: %s\n", depth, i, (char *)(node->data)); - else + } else { pdf_print_array((struct pdf_array *)(node->data), depth + 1); + } } } diff --git a/libclamav/pe.c b/libclamav/pe.c index 3082efb2ac..6e1a6a31e4 100644 --- a/libclamav/pe.c +++ b/libclamav/pe.c @@ -291,7 +291,9 @@ static void cli_multifree(void *f, ...) va_list ap; free(f); va_start(ap, f); - while ((ff = va_arg(ap, void *))) free(ff); + while ((ff = va_arg(ap, void *))) { + free(ff); + } va_end(ap); } @@ -306,8 +308,9 @@ static int versioninfo_cb(void *opaque, uint32_t type, uint32_t name, uint32_t l cli_dbgmsg("versioninfo_cb: type: %x, name: %x, lang: %x, rva: %x\n", type, name, lang, rva); vlist->rvas[vlist->count] = rva; - if (++vlist->count == sizeof(vlist->rvas) / sizeof(vlist->rvas[0])) + if (++vlist->count == sizeof(vlist->rvas) / sizeof(vlist->rvas[0])) { return 1; + } return 0; } @@ -378,8 +381,9 @@ void findres(uint32_t by_type, uint32_t by_name, fmap_t *map, struct cli_exe_inf res_rva = peinfo->dirs[2].VirtualAddress; - if (!(resdir = fmap_need_off_once(map, cli_rawaddr(res_rva, peinfo->sections, peinfo->nsections, &err, map->len, peinfo->hdr_size), 16)) || err) + if (!(resdir = fmap_need_off_once(map, cli_rawaddr(res_rva, peinfo->sections, peinfo->nsections, &err, map->len, peinfo->hdr_size), 16)) || err) { return; + } type_cnt = (uint16_t)cli_readint16(resdir + 12); type_entry = resdir + 16; @@ -389,43 +393,49 @@ void findres(uint32_t by_type, uint32_t by_name, fmap_t *map, struct cli_exe_inf } while (type_cnt--) { - if (!fmap_need_ptr_once(map, type_entry, 8)) + if (!fmap_need_ptr_once(map, type_entry, 8)) { return; + } type = cli_readint32(type_entry); type_offs = cli_readint32(type_entry + 4); if (type == by_type && (type_offs >> 31)) { type_offs &= 0x7fffffff; - if (!(resdir = fmap_need_off_once(map, cli_rawaddr(res_rva + type_offs, peinfo->sections, peinfo->nsections, &err, map->len, peinfo->hdr_size), 16)) || err) + if (!(resdir = fmap_need_off_once(map, cli_rawaddr(res_rva + type_offs, peinfo->sections, peinfo->nsections, &err, map->len, peinfo->hdr_size), 16)) || err) { return; + } name_cnt = (uint16_t)cli_readint16(resdir + 12); name_entry = resdir + 16; - if (by_name == 0xffffffff) + if (by_name == 0xffffffff) { name_cnt += (uint16_t)cli_readint16(resdir + 14); - else if (!(by_name >> 31)) { + } else if (!(by_name >> 31)) { name_entry += name_cnt * 8; name_cnt = (uint16_t)cli_readint16(resdir + 14); } while (name_cnt--) { - if (!fmap_need_ptr_once(map, name_entry, 8)) + if (!fmap_need_ptr_once(map, name_entry, 8)) { return; + } name = cli_readint32(name_entry); name_offs = cli_readint32(name_entry + 4); if ((by_name == 0xffffffff || name == by_name) && (name_offs >> 31)) { name_offs &= 0x7fffffff; - if (!(resdir = fmap_need_off_once(map, cli_rawaddr(res_rva + name_offs, peinfo->sections, peinfo->nsections, &err, map->len, peinfo->hdr_size), 16)) || err) + if (!(resdir = fmap_need_off_once(map, cli_rawaddr(res_rva + name_offs, peinfo->sections, peinfo->nsections, &err, map->len, peinfo->hdr_size), 16)) || err) { return; + } lang_cnt = (uint16_t)cli_readint16(resdir + 12) + (uint16_t)cli_readint16(resdir + 14); lang_entry = resdir + 16; while (lang_cnt--) { - if (!fmap_need_ptr_once(map, lang_entry, 8)) + if (!fmap_need_ptr_once(map, lang_entry, 8)) { return; + } lang = cli_readint32(lang_entry); lang_offs = cli_readint32(lang_entry + 4); if (!(lang_offs >> 31)) { - if (cb(opaque, type, name, lang, res_rva + lang_offs)) + if (cb(opaque, type, name, lang, res_rva + lang_offs)) { return; + } } lang_entry += 8; } @@ -447,16 +457,20 @@ static void cli_parseres_special(uint32_t base, uint32_t rva, fmap_t *map, struc uint32_t rawaddr = cli_rawaddr(rva, peinfo->sections, peinfo->nsections, &err, fsize, peinfo->hdr_size); uint32_t entries; - if (level > 2 || !*maxres) return; + if (level > 2 || !*maxres) { + return; + } *maxres -= 1; - if (err || !(resdir = fmap_need_off_once(map, rawaddr, 16))) + if (err || !(resdir = fmap_need_off_once(map, rawaddr, 16))) { return; + } named = (uint16_t)cli_readint16(resdir + 12); unnamed = (uint16_t)cli_readint16(resdir + 14); entries = /*named+*/ unnamed; - if (!entries) + if (!entries) { return; + } rawaddr += named * 8; /* skip named */ /* this is just used in a heuristic detection, so don't give error on failure */ if (!(entry = fmap_need_off(map, rawaddr + 16, entries * 8))) { @@ -504,9 +518,9 @@ static void cli_parseres_special(uint32_t base, uint32_t rva, fmap_t *map, struc continue; } offs = cli_readint32(entry + 4); - if (offs >> 31) + if (offs >> 31) { cli_parseres_special(base, base + (offs & 0x7fffffff), map, peinfo, fsize, level + 1, type, maxres, stats); - else { + } else { offs = cli_readint32(entry + 4); rawaddr = cli_rawaddr(base + offs, peinfo->sections, peinfo->nsections, &err, fsize, peinfo->hdr_size); if (!err && (resdir = fmap_need_off_once(map, rawaddr, 16))) { @@ -520,10 +534,12 @@ static void cli_parseres_special(uint32_t base, uint32_t rva, fmap_t *map, struc stats->errors++; continue; } - if ((id & 0xff) != 0x09) /* english res only */ + if ((id & 0xff) != 0x09) { /* english res only */ continue; - if ((str = fmap_need_off_once(map, rawaddr, isz))) + } + if ((str = fmap_need_off_once(map, rawaddr, isz))) { cli_detect_swizz_str(str, isz, stats, type); + } } } } @@ -539,18 +555,23 @@ static unsigned int cli_hashsect(fmap_t *map, struct cli_exe_section *s, unsigne return 0; } - if (!s->rsz) return 0; + if (!s->rsz) { + return 0; + } if (!(hashme = fmap_need_off_once(map, s->raw, s->rsz))) { cli_dbgmsg("cli_hashsect: unable to read section data\n"); return 0; } - if (foundhash[CLI_HASH_MD5] || foundwild[CLI_HASH_MD5]) + if (foundhash[CLI_HASH_MD5] || foundwild[CLI_HASH_MD5]) { cl_hash_data("md5", hashme, s->rsz, digest[CLI_HASH_MD5], NULL); - if (foundhash[CLI_HASH_SHA1] || foundwild[CLI_HASH_SHA1]) + } + if (foundhash[CLI_HASH_SHA1] || foundwild[CLI_HASH_SHA1]) { cl_sha1(hashme, s->rsz, digest[CLI_HASH_SHA1], NULL); - if (foundhash[CLI_HASH_SHA256] || foundwild[CLI_HASH_SHA256]) + } + if (foundhash[CLI_HASH_SHA256] || foundwild[CLI_HASH_SHA256]) { cl_sha256(hashme, s->rsz, digest[CLI_HASH_SHA256], NULL); + } return 1; } @@ -575,8 +596,9 @@ static cl_error_t scan_pe_mdb(cli_ctx *ctx, struct cli_exe_section *exe_section) hashset[type] = malloc(hashlen[type]); if (!hashset[type]) { cli_errmsg("scan_pe_mdb: malloc failed!\n"); - for (; type > 0;) + for (; type > 0;) { free(hashset[--type]); + } return CL_EMEM; } } else { @@ -639,8 +661,9 @@ static cl_error_t scan_pe_mdb(cli_ctx *ctx, struct cli_exe_section *exe_section) } end: - for (type = CLI_HASH_AVAIL_TYPES; type > 0;) + for (type = CLI_HASH_AVAIL_TYPES; type > 0;) { free(hashset[--type]); + } return ret; } @@ -2208,8 +2231,9 @@ static char *pe_ordinal(const char *dll, uint16_t ord) } } - if (name[0] == '\0') + if (name[0] == '\0') { sprintf(name, "ord%u", ord); + } return cli_safer_strdup(name); } @@ -2219,8 +2243,9 @@ static int validate_impname(const char *name, uint32_t length, int dll) uint32_t i = 0; const char *c = name; - if (!name || length == 0) + if (!name || length == 0) { return 1; + } while (i < length && *c != '\0') { if ((*c >= '0' && *c <= '9') || @@ -2231,8 +2256,9 @@ static int validate_impname(const char *name, uint32_t length, int dll) c++; i++; - } else + } else { return 0; + } } return 1; @@ -2249,10 +2275,12 @@ static inline int hash_impfns(cli_ctx *ctx, void **hashctx, uint32_t *impsz, str cli_hash_type_t type; json_object *imptbl = NULL; - if (image->u.OriginalFirstThunk) + if (image->u.OriginalFirstThunk) { thuoff = cli_rawaddr(image->u.OriginalFirstThunk, peinfo->sections, peinfo->nsections, &err, fsize, peinfo->hdr_size); - if (err || thuoff == 0) + } + if (err || thuoff == 0) { thuoff = cli_rawaddr(image->FirstThunk, peinfo->sections, peinfo->nsections, &err, fsize, peinfo->hdr_size); + } if (err) { cli_dbgmsg("scan_pe: invalid rva for image first thunk\n"); return CL_EFORMAT; @@ -2356,8 +2384,9 @@ static inline int hash_impfns(cli_ctx *ctx, void **hashctx, uint32_t *impsz, str UPDATE_IMPHASH(); free(funcname); - if (ret != CL_SUCCESS) + if (ret != CL_SUCCESS) { return ret; + } } } else { struct pe_image_thunk64 thunk64; @@ -2397,8 +2426,9 @@ static inline int hash_impfns(cli_ctx *ctx, void **hashctx, uint32_t *impsz, str UPDATE_IMPHASH(); free(funcname); - if (ret != CL_SUCCESS) + if (ret != CL_SUCCESS) { return ret; + } } } @@ -2585,8 +2615,9 @@ static cl_error_t scan_pe_imp(cli_ctx *ctx, struct cli_exe_info *peinfo) hashset[type] = malloc(hashlen[type]); if (!hashset[type]) { cli_errmsg("scan_pe: malloc failed!\n"); - for (; type > 0;) + for (; type > 0;) { free(hashset[--type]); + } return CL_EMEM; } } else { @@ -2600,8 +2631,9 @@ static cl_error_t scan_pe_imp(cli_ctx *ctx, struct cli_exe_info *peinfo) hashset[CLI_HASH_MD5] = calloc(hashlen[CLI_HASH_MD5], sizeof(char)); if (!hashset[CLI_HASH_MD5]) { cli_errmsg("scan_pe: calloc failed!\n"); - for (type = CLI_HASH_MD5; type < CLI_HASH_AVAIL_TYPES; type++) + for (type = CLI_HASH_MD5; type < CLI_HASH_AVAIL_TYPES; type++) { free(hashset[type]); + } return CL_EMEM; } } @@ -2623,11 +2655,13 @@ static cl_error_t scan_pe_imp(cli_ctx *ctx, struct cli_exe_info *peinfo) char *dstr = cli_str2hex((char *)hashset[CLI_HASH_MD5], hashlen[CLI_HASH_MD5]); cli_dbgmsg("IMP: %s:%u\n", dstr ? (char *)dstr : "(NULL)", impsz); - if (ctx->wrkproperty) + if (ctx->wrkproperty) { cli_jsonstr(ctx->wrkproperty, "Imphash", dstr ? dstr : "(NULL)"); + } - if (dstr) + if (dstr) { free(dstr); + } } /* Do scans */ @@ -2646,8 +2680,9 @@ static cl_error_t scan_pe_imp(cli_ctx *ctx, struct cli_exe_info *peinfo) } } - for (type = CLI_HASH_MD5; type < CLI_HASH_AVAIL_TYPES; type++) + for (type = CLI_HASH_MD5; type < CLI_HASH_AVAIL_TYPES; type++) { free(hashset[type]); + } return ret; } @@ -2655,13 +2690,15 @@ static struct json_object *get_pe_property(cli_ctx *ctx) { struct json_object *pe; - if (!(ctx) || !(ctx->wrkproperty)) + if (!(ctx) || !(ctx->wrkproperty)) { return NULL; + } if (!json_object_object_get_ex(ctx->wrkproperty, "PE", &pe)) { pe = json_object_new_object(); - if (!(pe)) + if (!(pe)) { return NULL; + } json_object_object_add(ctx->wrkproperty, "PE", pe); } @@ -2676,20 +2713,23 @@ static void pe_add_heuristic_property(cli_ctx *ctx, const char *key) struct json_object *str; pe = get_pe_property(ctx); - if (!(pe)) + if (!(pe)) { return; + } if (!json_object_object_get_ex(pe, "Heuristics", &heuristics)) { heuristics = json_object_new_array(); - if (!(heuristics)) + if (!(heuristics)) { return; + } json_object_object_add(pe, "Heuristics", heuristics); } str = json_object_new_string(key); - if (!(str)) + if (!(str)) { return; + } json_object_array_add(heuristics, str); } @@ -2700,13 +2740,15 @@ static struct json_object *get_section_json(cli_ctx *ctx) struct json_object *section; pe = get_pe_property(ctx); - if (!(pe)) + if (!(pe)) { return NULL; + } if (!json_object_object_get_ex(pe, "Sections", §ion)) { section = json_object_new_array(); - if (!(section)) + if (!(section)) { return NULL; + } json_object_object_add(pe, "Sections", section); } @@ -2720,44 +2762,52 @@ static void add_section_info(cli_ctx *ctx, struct cli_exe_section *s) char address[16]; sections = get_section_json(ctx); - if (!(sections)) + if (!(sections)) { return; + } section = json_object_new_object(); - if (!(section)) + if (!(section)) { return; + } obj = json_object_new_int((int32_t)(s->rsz)); - if (!(obj)) + if (!(obj)) { return; + } json_object_object_add(section, "RawSize", obj); obj = json_object_new_int((int32_t)(s->raw)); - if (!(obj)) + if (!(obj)) { return; + } json_object_object_add(section, "RawOffset", obj); snprintf(address, sizeof(address), "0x%08x", s->rva); obj = json_object_new_string(address); - if (!(obj)) + if (!(obj)) { return; + } json_object_object_add(section, "VirtualAddress", obj); obj = json_object_new_boolean((s->chr & 0x20000000) == 0x20000000); - if ((obj)) + if ((obj)) { json_object_object_add(section, "Executable", obj); + } obj = json_object_new_boolean((s->chr & 0x80000000) == 0x80000000); - if ((obj)) + if ((obj)) { json_object_object_add(section, "Writable", obj); + } obj = json_object_new_boolean(s->urva >> 31 || s->uvsz >> 31 || (s->rsz && s->uraw >> 31) || s->ursz >> 31); - if ((obj)) + if ((obj)) { json_object_object_add(section, "Signed", obj); + } json_object_array_add(sections, section); } @@ -2866,7 +2916,9 @@ int cli_scanpe(cli_ctx *ctx) // in cli_scanpe that needs the section name, and since I verified // that detection still occurs for Polipos without this check, // let's leave it commented out for now. - if (SCAN_HEURISTICS && (DCONF & PE_CONF_POLIPOS) && /*!*peinfo->sections[i].sname &&*/ peinfo->sections[i].vsz > 40000 && peinfo->sections[i].vsz < 70000 && peinfo->sections[i].chr == 0xe0000060) polipos = i; + if (SCAN_HEURISTICS && (DCONF & PE_CONF_POLIPOS) && /*!*peinfo->sections[i].sname &&*/ peinfo->sections[i].vsz > 40000 && peinfo->sections[i].vsz < 70000 && peinfo->sections[i].chr == 0xe0000060) { + polipos = i; + } /* check hash section sigs */ if ((DCONF & PE_CONF_MD5SECT) && ctx->engine->hm_mdb) { @@ -3016,8 +3068,9 @@ int cli_scanpe(cli_ctx *ctx) while (*kzstate != KZSTOP) { uint8_t op; - if (kzlen <= 6) + if (kzlen <= 6) { break; + } op = *kzcode++; kzlen--; @@ -3107,10 +3160,11 @@ int cli_scanpe(cli_ctx *ctx) break; case KZSDDELTA: - if (op == kzdptr + 0x48) + if (op == kzdptr + 0x48) { kzstate++; - else + } else { *kzstate = KZSTOP; + } break; case KZSLOOP: @@ -3174,24 +3228,30 @@ int cli_scanpe(cli_ctx *ctx) const uint8_t *code; unsigned int xsjs = 0; - if (peinfo->sections[0].rsz > CLI_MAX_ALLOCATION) + if (peinfo->sections[0].rsz > CLI_MAX_ALLOCATION) { break; - if (peinfo->sections[0].rsz < 5) + } + if (peinfo->sections[0].rsz < 5) { break; - if (!(code = fmap_need_off_once(map, peinfo->sections[0].raw, peinfo->sections[0].rsz))) + } + if (!(code = fmap_need_off_once(map, peinfo->sections[0].raw, peinfo->sections[0].rsz))) { break; + } for (i = 0; i < peinfo->sections[0].rsz - 5; i++) { - if ((uint8_t)(code[i] - 0xe8) > 1) + if ((uint8_t)(code[i] - 0xe8) > 1) { continue; + } jump = cli_rawaddr(peinfo->sections[0].rva + i + 5 + cli_readint32(&code[i + 1]), peinfo->sections, peinfo->nsections, &err, fsize, peinfo->hdr_size); - if (err || !CLI_ISCONTAINED(peinfo->sections[polipos].raw, peinfo->sections[polipos].rsz, jump, 9)) + if (err || !CLI_ISCONTAINED(peinfo->sections[polipos].raw, peinfo->sections[polipos].rsz, jump, 9)) { continue; + } if (xsjs % 128 == 0) { - if (xsjs == 1280) + if (xsjs == 1280) { break; + } if (!(jumps = (uint32_t *)cli_max_realloc_or_free(jumps, (xsjs + 128) * sizeof(uint32_t)))) { cli_exe_info_destroy(peinfo); @@ -3201,8 +3261,9 @@ int cli_scanpe(cli_ctx *ctx) j = 0; for (; j < xsjs; j++) { - if (jumps[j] < jump) + if (jumps[j] < jump) { continue; + } if (jumps[j] == jump) { xsjs--; break; @@ -3217,13 +3278,15 @@ int cli_scanpe(cli_ctx *ctx) xsjs++; } - if (!xsjs) + if (!xsjs) { break; + } cli_dbgmsg("cli_scanpe: Polipos: Checking %d xsect jump(s)\n", xsjs); for (i = 0; i < xsjs; i++) { - if (!(code = fmap_need_off_once(map, jumps[i], 9))) + if (!(code = fmap_need_off_once(map, jumps[i], 9))) { continue; + } if ((jump = cli_readint32(code)) == 0x60ec8b55 || (code[4] == 0x0ec && ((jump == 0x83ec8b55 && code[6] == 0x60) || (jump == 0x81ec8b55 && !code[7] && !code[8])))) { ret = cli_append_potentially_unwanted(ctx, "Heuristics.W32.Polipos.A"); @@ -3277,8 +3340,9 @@ int cli_scanpe(cli_ctx *ctx) found = 1; cli_dbgmsg("cli_scanpe: UPX/FSG/MEW: empty section found - assuming compression\n"); - if (pe_json != NULL) + if (pe_json != NULL) { cli_jsonbool(pe_json, "HasEmptySection", 1); + } break; } @@ -3300,13 +3364,15 @@ int cli_scanpe(cli_ctx *ctx) cli_dbgmsg("cli_scanpe: MEW: found MEW characteristics %08X + %08X + 5 = %08X\n", cli_readint32(epbuff + 1), peinfo->vep, cli_readint32(epbuff + 1) + peinfo->vep + 5); - if (!(tbuff = fmap_need_off_once(map, fileoffset, 0xb0))) + if (!(tbuff = fmap_need_off_once(map, fileoffset, 0xb0))) { break; + } - if (fileoffset == 0x154) + if (fileoffset == 0x154) { cli_dbgmsg("cli_scanpe: MEW: Win9x compatibility was set!\n"); - else + } else { cli_dbgmsg("cli_scanpe: MEW: Win9x compatibility was NOT set!\n"); + } offdiff = cli_readint32(tbuff + 1) - EC32(peinfo->pe_opt.opt32.ImageBase); if ((offdiff <= peinfo->sections[i + 1].rva) || @@ -3376,8 +3442,9 @@ int cli_scanpe(cli_ctx *ctx) uselzma = 0; } - if (pe_json != NULL) + if (pe_json != NULL) { cli_jsonstr(pe_json, "Packer", "MEW"); + } CLI_UNPTEMP("cli_scanpe: MEW", (src, 0)); CLI_UNPRESULTS("cli_scanpe: MEW", (unmew11(src, offdiff, ssize, dsize, EC32(peinfo->pe_opt.opt32.ImageBase), peinfo->sections[0].rva, uselzma, ndesc)), 1, (src, 0)); @@ -3473,8 +3540,9 @@ int cli_scanpe(cli_ctx *ctx) break; } - if (upack) + if (upack) { memmove(dest + peinfo->sections[2].rva - peinfo->sections[0].rva, dest, ssize); + } if (fmap_readn(map, dest + peinfo->sections[1].rva - off, peinfo->sections[1].uraw, peinfo->sections[1].ursz) != peinfo->sections[1].ursz) { cli_dbgmsg("cli_scanpe: Upack: Can't read raw data of section 1\n"); @@ -3482,8 +3550,9 @@ int cli_scanpe(cli_ctx *ctx) break; } - if (pe_json != NULL) + if (pe_json != NULL) { cli_jsonstr(pe_json, "Packer", "Upack"); + } CLI_UNPTEMP("cli_scanpe: Upack", (dest, 0)); CLI_UNPRESULTS("cli_scanpe: Upack", (unupack(upack, dest, dsize, epbuff, vma, peinfo->ep, EC32(peinfo->pe_opt.opt32.ImageBase), peinfo->sections[0].rva, ndesc)), 1, (dest, 0)); @@ -3567,8 +3636,9 @@ int cli_scanpe(cli_ctx *ctx) return CL_EMEM; } - if (pe_json != NULL) + if (pe_json != NULL) { cli_jsonstr(pe_json, "Packer", "FSG"); + } CLI_UNPTEMP("cli_scanpe: FSG", (dest, 0)); CLI_UNPRESULTSFSG2("cli_scanpe: FSG", (unfsg_200(newesi - peinfo->sections[i + 1].rva + src, dest, ssize + peinfo->sections[i + 1].rva - newesi, dsize, newedi, EC32(peinfo->pe_opt.opt32.ImageBase), newedx, ndesc)), 1, (dest, 0)); @@ -3627,14 +3697,16 @@ int cli_scanpe(cli_ctx *ctx) for (t = 12; t < gp - 4; t += 4) { uint32_t rva = cli_readint32(support + t); - if (!rva) + if (!rva) { break; + } rva -= EC32(peinfo->pe_opt.opt32.ImageBase) + 1; sectcnt++; - if (rva % 0x1000) + if (rva % 0x1000) { cli_dbgmsg("cli_scanpe: FSG: Original section %d is misaligned\n", sectcnt); + } if (rva < peinfo->sections[i].rva || rva - peinfo->sections[i].rva >= peinfo->sections[i].vsz) { cli_dbgmsg("cli_scanpe: FSG: Original section %d is out of bounds\n", sectcnt); @@ -3653,8 +3725,9 @@ int cli_scanpe(cli_ctx *ctx) } sections[0].rva = newedi; - for (t = 1; t <= (uint32_t)sectcnt; t++) + for (t = 1; t <= (uint32_t)sectcnt; t++) { sections[t].rva = cli_readint32(support + 8 + t * 4) - 1 - EC32(peinfo->pe_opt.opt32.ImageBase); + } if (!peinfo->sections[i + 1].rsz || !(src = fmap_need_off_once(map, peinfo->sections[i + 1].raw, ssize))) { cli_dbgmsg("cli_scanpe: Can't read raw data of section %d\n", i); @@ -3672,8 +3745,9 @@ int cli_scanpe(cli_ctx *ctx) oldep = peinfo->vep + 161 + 6 + cli_readint32(epbuff + 163); cli_dbgmsg("cli_scanpe: FSG: found old EP @%x\n", oldep); - if (pe_json != NULL) + if (pe_json != NULL) { cli_jsonstr(pe_json, "Packer", "FSG"); + } CLI_UNPTEMP("cli_scanpe: FSG", (dest, sections, 0)); CLI_UNPRESULTSFSG1("cli_scanpe: FSG", (unfsg_133(src + newesi - peinfo->sections[i + 1].rva, dest, ssize + peinfo->sections[i + 1].rva - newesi, dsize, sections, sectcnt, EC32(peinfo->pe_opt.opt32.ImageBase), oldep, ndesc)), 1, (dest, sections, 0)); @@ -3731,8 +3805,9 @@ int cli_scanpe(cli_ctx *ctx) for (t = 0; t < gp - 2; t += 2) { uint32_t rva = support[t] | (support[t + 1] << 8); - if (rva == 2 || rva == 1) + if (rva == 2 || rva == 1) { break; + } rva = ((rva - 2) << 12) - EC32(peinfo->pe_opt.opt32.ImageBase); sectcnt++; @@ -3743,8 +3818,9 @@ int cli_scanpe(cli_ctx *ctx) } } - if (t >= gp - 10 || cli_readint32(support + t + 6) != 2) + if (t >= gp - 10 || cli_readint32(support + t + 6) != 2) { break; + } if ((sections = (struct cli_exe_section *)cli_max_malloc((sectcnt + 1) * sizeof(struct cli_exe_section))) == NULL) { cli_errmsg("cli_scanpe: FSG: Unable to allocate memory for sections %llu\n", (long long unsigned)((sectcnt + 1) * sizeof(struct cli_exe_section))); @@ -3753,8 +3829,9 @@ int cli_scanpe(cli_ctx *ctx) } sections[0].rva = newedi; - for (t = 0; t <= (uint32_t)sectcnt - 1; t++) + for (t = 0; t <= (uint32_t)sectcnt - 1; t++) { sections[t + 1].rva = (((support[t * 2] | (support[t * 2 + 1] << 8)) - 2) << 12) - EC32(peinfo->pe_opt.opt32.ImageBase); + } if (!peinfo->sections[i + 1].rsz || !(src = fmap_need_off_once(map, peinfo->sections[i + 1].raw, ssize))) { cli_dbgmsg("cli_scanpe: FSG: Can't read raw data of section %d\n", i); @@ -3773,8 +3850,9 @@ int cli_scanpe(cli_ctx *ctx) oldep = peinfo->vep + gp + 6 + cli_readint32(src + gp + 2 + oldep); cli_dbgmsg("cli_scanpe: FSG: found old EP @%x\n", oldep); - if (pe_json != NULL) + if (pe_json != NULL) { cli_jsonstr(pe_json, "Packer", "FSG"); + } CLI_UNPTEMP("cli_scanpe: FSG", (dest, sections, 0)); CLI_UNPRESULTSFSG1("cli_scanpe: FSG", (unfsg_133(src + newesi - peinfo->sections[i + 1].rva, dest, ssize + peinfo->sections[i + 1].rva - newesi, dsize, sections, sectcnt, EC32(peinfo->pe_opt.opt32.ImageBase), oldep, ndesc)), 1, (dest, sections, 0)); @@ -3846,10 +3924,11 @@ int cli_scanpe(cli_ctx *ctx) upx_success = 1; } - if (upx_success) + if (upx_success) { cli_dbgmsg("cli_scanpe: UPX: Successfully decompressed\n"); - else + } else { cli_dbgmsg("cli_scanpe: UPX: Preferred decompressor failed\n"); + } } if (!upx_success && upxfn != upx_inflate2b) { @@ -3886,24 +3965,28 @@ int cli_scanpe(cli_ctx *ctx) if (ssize > 0x15 && epbuff[0] == '\x60' && epbuff[1] == '\xbe') { // TODO Add EC32 skew = cli_readint32(epbuff + 2) - peinfo->sections[i + 1].rva - peinfo->pe_opt.opt32.ImageBase; - if (skew != 0x15) + if (skew != 0x15) { skew = 0; + } } - if (strictdsize <= dsize) + if (strictdsize <= dsize) { upx_success = upx_inflatelzma(src + skew, ssize - skew, dest, &strictdsize, peinfo->sections[i].rva, peinfo->sections[i + 1].rva, peinfo->vep, 0x20003) >= 0; + } } else if (cli_memstr(UPX_LZMA1_FIRST, 8, epbuff + 0x39, 8) && cli_memstr(UPX_LZMA1_SECOND, 8, epbuff + 0x45, 8)) { uint32_t strictdsize = cli_readint32(epbuff + 0x2b), skew = 0; uint32_t properties = cli_readint32(epbuff + 0x41); if (ssize > 0x15 && epbuff[0] == '\x60' && epbuff[1] == '\xbe') { // TODO Add EC32 skew = cli_readint32(epbuff + 2) - peinfo->sections[i + 1].rva - peinfo->pe_opt.opt32.ImageBase; - if (skew != 0x15) + if (skew != 0x15) { skew = 0; + } } - if (strictdsize <= dsize) + if (strictdsize <= dsize) { upx_success = upx_inflatelzma(src + skew, ssize - skew, dest, &strictdsize, peinfo->sections[i].rva, peinfo->sections[i + 1].rva, peinfo->vep, properties) >= 0; + } } if (!upx_success) { @@ -3917,8 +4000,9 @@ int cli_scanpe(cli_ctx *ctx) CLI_UNPTEMP("cli_scanpe: UPX/FSG", (dest, 0)); - if (pe_json != NULL) + if (pe_json != NULL) { cli_jsonstr(pe_json, "Packer", "UPX"); + } if ((unsigned int)write(ndesc, dest, dsize) != dsize) { cli_dbgmsg("cli_scanpe: UPX/FSG: Can't write %d bytes\n", dsize); @@ -3938,8 +4022,9 @@ int cli_scanpe(cli_ctx *ctx) return CL_ESEEK; } - if (ctx->engine->keeptmp) + if (ctx->engine->keeptmp) { cli_dbgmsg("cli_scanpe: UPX/FSG: Decompressed data saved in %s\n", tempfile); + } cli_dbgmsg("***** Scanning decompressed file *****\n"); SHA_OFF; @@ -3969,10 +4054,11 @@ int cli_scanpe(cli_ctx *ctx) found = 2; if (epbuff[0] != '\xb8' || (uint32_t)cli_readint32(epbuff + 1) != peinfo->sections[peinfo->nsections - 1].rva + EC32(peinfo->pe_opt.opt32.ImageBase)) { - if (peinfo->nsections < 2 || epbuff[0] != '\xb8' || (uint32_t)cli_readint32(epbuff + 1) != peinfo->sections[peinfo->nsections - 2].rva + EC32(peinfo->pe_opt.opt32.ImageBase)) + if (peinfo->nsections < 2 || epbuff[0] != '\xb8' || (uint32_t)cli_readint32(epbuff + 1) != peinfo->sections[peinfo->nsections - 2].rva + EC32(peinfo->pe_opt.opt32.ImageBase)) { found = 0; - else + } else { found = 1; + } } if (found && (DCONF & PE_CONF_PETITE)) { @@ -3995,13 +4081,15 @@ int cli_scanpe(cli_ctx *ctx) if (peinfo->sections[i].raw) { unsigned int r_ret; - if (!peinfo->sections[i].rsz) + if (!peinfo->sections[i].rsz) { goto out_no_petite; + } if (!CLI_ISCONTAINED(dest, dsize, dest + peinfo->sections[i].rva - peinfo->min, - peinfo->sections[i].ursz)) + peinfo->sections[i].ursz)) { goto out_no_petite; + } r_ret = fmap_readn(map, dest + peinfo->sections[i].rva - peinfo->min, peinfo->sections[i].raw, @@ -4015,8 +4103,9 @@ int cli_scanpe(cli_ctx *ctx) } } - if (pe_json != NULL) + if (pe_json != NULL) { cli_jsonstr(pe_json, "Packer", "Petite"); + } CLI_UNPTEMP("cli_scanpe: Petite", (dest, 0)); CLI_UNPRESULTS("Petite", (petite_inflate2x_1to9(dest, peinfo->min, peinfo->max - peinfo->min, peinfo->sections, peinfo->nsections - (found == 1 ? 1 : 0), EC32(peinfo->pe_opt.opt32.ImageBase), peinfo->vep, ndesc, found, peinfo->dirs[2].VirtualAddress, peinfo->dirs[2].Size)), 0, (dest, 0)); @@ -4048,8 +4137,9 @@ int cli_scanpe(cli_ctx *ctx) return CL_EREAD; } - if (pe_json != NULL) + if (pe_json != NULL) { cli_jsonstr(pe_json, "Packer", "PEspin"); + } CLI_UNPTEMP("cli_scanpe: PESpin", (spinned, 0)); CLI_UNPRESULTS_("cli_scanpe: PEspin", SPINCASE(), (unspin(spinned, fsize, peinfo->sections, peinfo->nsections - 1, peinfo->vep, ndesc, ctx)), 0, (spinned, 0)); @@ -4070,8 +4160,9 @@ int cli_scanpe(cli_ctx *ctx) !memcmp(epbuff + 0x1e, "\x8B\xD5\x81\xC2", 4)) { offset = 0; - if (0x6c - cli_readint32(epbuff + 0xf) + cli_readint32(epbuff + 0x22) == 0xC6) + if (0x6c - cli_readint32(epbuff + 0xf) + cli_readint32(epbuff + 0x22) == 0xC6) { ecx = cli_readint32(epbuff + 0x14) - cli_readint32(epbuff + 0x1a); + } } /* yC 1.3 variant */ @@ -4080,8 +4171,9 @@ int cli_scanpe(cli_ctx *ctx) ((uint8_t)epbuff[0x23] == 0xB9)) { offset = 0x10; - if (0x6c - cli_readint32(epbuff + 0x1f) + cli_readint32(epbuff + 0x32) == 0xC6) + if (0x6c - cli_readint32(epbuff + 0x1f) + cli_readint32(epbuff + 0x32) == 0xC6) { ecx = cli_readint32(epbuff + 0x24) - cli_readint32(epbuff + 0x2a); + } } /* yC 1.x/modified */ @@ -4091,8 +4183,9 @@ int cli_scanpe(cli_ctx *ctx) !memcmp(epbuff + 0x18, "\x8b\xf7\xac", 3)) { offset = -0x18; - if (0x66 - cli_readint32(epbuff + 0x9) + cli_readint32(epbuff + 0x14) == 0xae) + if (0x66 - cli_readint32(epbuff + 0x9) + cli_readint32(epbuff + 0x14) == 0xae) { ecx = cli_readint32(epbuff + 0xe); + } } if (ecx > 0x800 && ecx < 0x2000 && @@ -4115,8 +4208,9 @@ int cli_scanpe(cli_ctx *ctx) return CL_EREAD; } - if (pe_json != NULL) + if (pe_json != NULL) { cli_jsonstr(pe_json, "Packer", "yC"); + } // record number of alerts before unpacking and scanning num_alerts = evidence_num_alerts(ctx->evidence); @@ -4150,18 +4244,22 @@ int cli_scanpe(cli_ctx *ctx) ssize = 0; for (i = 0;; i++) { - if (peinfo->sections[i].raw < head) + if (peinfo->sections[i].raw < head) { head = peinfo->sections[i].raw; + } - if (i + 1 == peinfo->nsections) + if (i + 1 == peinfo->nsections) { break; + } - if (ssize < peinfo->sections[i].rva + peinfo->sections[i].vsz) + if (ssize < peinfo->sections[i].rva + peinfo->sections[i].vsz) { ssize = peinfo->sections[i].rva + peinfo->sections[i].vsz; + } } - if (!head || !ssize || head > ssize) + if (!head || !ssize || head > ssize) { break; + } CLI_UNPSIZELIMITS("cli_scanpe: WWPack", ssize); @@ -4178,14 +4276,17 @@ int cli_scanpe(cli_ctx *ctx) } for (i = 0; i < (unsigned int)peinfo->nsections - 1; i++) { - if (!peinfo->sections[i].rsz) + if (!peinfo->sections[i].rsz) { continue; + } - if (!CLI_ISCONTAINED(src, ssize, src + peinfo->sections[i].rva, peinfo->sections[i].rsz)) + if (!CLI_ISCONTAINED(src, ssize, src + peinfo->sections[i].rva, peinfo->sections[i].rsz)) { break; + } - if (fmap_readn(map, src + peinfo->sections[i].rva, peinfo->sections[i].raw, peinfo->sections[i].rsz) != peinfo->sections[i].rsz) + if (fmap_readn(map, src + peinfo->sections[i].rva, peinfo->sections[i].raw, peinfo->sections[i].rsz) != peinfo->sections[i].rsz) { break; + } } if (i + 1 != peinfo->nsections) { @@ -4208,8 +4309,9 @@ int cli_scanpe(cli_ctx *ctx) return CL_EREAD; } - if (pe_json != NULL) + if (pe_json != NULL) { cli_jsonstr(pe_json, "Packer", "WWPack"); + } CLI_UNPTEMP("cli_scanpe: WWPack", (src, packer, 0)); CLI_UNPRESULTS("cli_scanpe: WWPack", (wwunpack((uint8_t *)src, ssize, packer, peinfo->sections, peinfo->nsections - 1, peinfo->e_lfanew, ndesc)), 0, (src, packer, 0)); @@ -4225,8 +4327,9 @@ int cli_scanpe(cli_ctx *ctx) char *src; aspack_version_t aspack_ver = ASPACK_VER_NONE; - if (epsize < 0x3bf) + if (epsize < 0x3bf) { break; + } if (0 == memcmp(epbuff + ASPACK_EPBUFF_OFFSET_212, "\x68\x00\x00\x00\x00\xc3", 6)) { aspack_ver = ASPACK_VER_212; @@ -4238,12 +4341,15 @@ int cli_scanpe(cli_ctx *ctx) break; } ssize = 0; - for (i = 0; i < peinfo->nsections; i++) - if (ssize < peinfo->sections[i].rva + peinfo->sections[i].vsz) + for (i = 0; i < peinfo->nsections; i++) { + if (ssize < peinfo->sections[i].rva + peinfo->sections[i].vsz) { ssize = peinfo->sections[i].rva + peinfo->sections[i].vsz; + } + } - if (!ssize) + if (!ssize) { break; + } CLI_UNPSIZELIMITS("cli_scanpe: Aspack", ssize); @@ -4252,14 +4358,17 @@ int cli_scanpe(cli_ctx *ctx) return CL_EMEM; } for (i = 0; i < (unsigned int)peinfo->nsections; i++) { - if (!peinfo->sections[i].rsz) + if (!peinfo->sections[i].rsz) { continue; + } - if (!CLI_ISCONTAINED(src, ssize, src + peinfo->sections[i].rva, peinfo->sections[i].rsz)) + if (!CLI_ISCONTAINED(src, ssize, src + peinfo->sections[i].rva, peinfo->sections[i].rsz)) { break; + } - if (fmap_readn(map, src + peinfo->sections[i].rva, peinfo->sections[i].raw, peinfo->sections[i].rsz) != peinfo->sections[i].rsz) + if (fmap_readn(map, src + peinfo->sections[i].rva, peinfo->sections[i].raw, peinfo->sections[i].rsz) != peinfo->sections[i].rsz) { break; + } } if (i != peinfo->nsections) { @@ -4268,8 +4377,9 @@ int cli_scanpe(cli_ctx *ctx) break; } - if (pe_json != NULL) + if (pe_json != NULL) { cli_jsonstr(pe_json, "Packer", "Aspack"); + } CLI_UNPTEMP("cli_scanpe: Aspack", (src, 0)); CLI_UNPRESULTS("cli_scanpe: Aspack", (unaspack((uint8_t *)src, ssize, peinfo->sections, peinfo->nsections, peinfo->vep - 1, EC32(peinfo->pe_opt.opt32.ImageBase), ndesc, aspack_ver)), 1, (src, 0)); @@ -4287,27 +4397,32 @@ int cli_scanpe(cli_ctx *ctx) src = epbuff; if (*epbuff == '\xe9') { /* bitched headers */ eprva = cli_readint32(epbuff + 1) + peinfo->vep + 5; - if (!(rep = cli_rawaddr(eprva, peinfo->sections, peinfo->nsections, &err, fsize, peinfo->hdr_size)) && err) + if (!(rep = cli_rawaddr(eprva, peinfo->sections, peinfo->nsections, &err, fsize, peinfo->hdr_size)) && err) { break; + } - if (!(nbuff = fmap_need_off_once(map, rep, 24))) + if (!(nbuff = fmap_need_off_once(map, rep, 24))) { break; + } src = nbuff; } - if (memcmp(src, "\x9c\x60\xe8\x00\x00\x00\x00\x5d\xb8\x07\x00\x00\x00", 13)) + if (memcmp(src, "\x9c\x60\xe8\x00\x00\x00\x00\x5d\xb8\x07\x00\x00\x00", 13)) { break; + } nowinldr = 0x54 - cli_readint32(src + 17); cli_dbgmsg("cli_scanpe: NsPack: Found *start_of_stuff @delta-%x\n", nowinldr); - if (!(nbuff = fmap_need_off_once(map, rep - nowinldr, 4))) + if (!(nbuff = fmap_need_off_once(map, rep - nowinldr, 4))) { break; + } start_of_stuff = rep + cli_readint32(nbuff); - if (!(nbuff = fmap_need_off_once(map, start_of_stuff, 20))) + if (!(nbuff = fmap_need_off_once(map, start_of_stuff, 20))) { break; + } src = nbuff; if (!cli_readint32(nbuff)) { @@ -4320,8 +4435,9 @@ int cli_scanpe(cli_ctx *ctx) CLI_UNPSIZELIMITS("cli_scanpe: NsPack", MAX(ssize, dsize)); - if (!ssize || !dsize || dsize != peinfo->sections[0].vsz) + if (!ssize || !dsize || dsize != peinfo->sections[0].vsz) { break; + } if (!(dest = cli_max_malloc(dsize))) { cli_errmsg("cli_scanpe: NsPack: Unable to allocate memory for dest %u\n", dsize); @@ -4350,8 +4466,9 @@ int cli_scanpe(cli_ctx *ctx) eprva = eprva + 5 + cli_readint32(nbuff + 1); cli_dbgmsg("cli_scanpe: NsPack: OEP = %08x\n", eprva); - if (pe_json != NULL) + if (pe_json != NULL) { cli_jsonstr(pe_json, "Packer", "NsPack"); + } CLI_UNPTEMP("cli_scanpe: NsPack", (dest, 0)); CLI_UNPRESULTS("cli_scanpe: NsPack", (unspack(src, dest, ctx, peinfo->sections[0].rva, EC32(peinfo->pe_opt.opt32.ImageBase), eprva, ndesc)), 0, (dest, 0)); @@ -4393,8 +4510,9 @@ int cli_scanpe(cli_ctx *ctx) cli_exe_info_destroy(peinfo); - if (cli_json_timeout_cycle_check(ctx, &toval) != CL_SUCCESS) + if (cli_json_timeout_cycle_check(ctx, &toval) != CL_SUCCESS) { return CL_ETIMEOUT; + } return CL_SUCCESS; } @@ -4545,8 +4663,9 @@ cl_error_t cli_peheader(fmap_t *map, struct cli_exe_info *peinfo, uint32_t opts, if (EC16(file_hdr->Characteristics) & 0x2000) { - if (opts & CLI_PEHEADER_OPT_COLLECT_JSON) + if (opts & CLI_PEHEADER_OPT_COLLECT_JSON) { cli_jsonstr(pe_json, "Type", "DLL"); + } if (opts & CLI_PEHEADER_OPT_DBG_PRINT_INFO) { cli_dbgmsg("File type: DLL\n"); @@ -4555,8 +4674,9 @@ cl_error_t cli_peheader(fmap_t *map, struct cli_exe_info *peinfo, uint32_t opts, is_dll = 1; } else if (EC16(file_hdr->Characteristics) & 0x0002) { - if (opts & CLI_PEHEADER_OPT_COLLECT_JSON) + if (opts & CLI_PEHEADER_OPT_COLLECT_JSON) { cli_jsonstr(pe_json, "Type", "EXE"); + } if (opts & CLI_PEHEADER_OPT_DBG_PRINT_INFO) { cli_dbgmsg("File type: Executable\n"); @@ -4685,11 +4805,13 @@ cl_error_t cli_peheader(fmap_t *map, struct cli_exe_info *peinfo, uint32_t opts, archtype = "Unknown"; } - if (opts & CLI_PEHEADER_OPT_DBG_PRINT_INFO) + if (opts & CLI_PEHEADER_OPT_DBG_PRINT_INFO) { cli_dbgmsg("Machine type: %s\n", archtype); + } - if (opts & CLI_PEHEADER_OPT_COLLECT_JSON) + if (opts & CLI_PEHEADER_OPT_COLLECT_JSON) { cli_jsonstr(pe_json, "ArchType", archtype); + } } peinfo->nsections = EC16(file_hdr->NumberOfSections); @@ -4940,8 +5062,9 @@ cl_error_t cli_peheader(fmap_t *map, struct cli_exe_info *peinfo, uint32_t opts, cli_dbgmsg("------------------------------------\n"); } - if (opts & CLI_PEHEADER_OPT_COLLECT_JSON) + if (opts & CLI_PEHEADER_OPT_COLLECT_JSON) { cli_jsonstr(pe_json, "Subsystem", subsystem); + } if (!native && (!salign || (salign % 0x1000))) { cli_dbgmsg("cli_peheader: Bad section alignment\n"); @@ -5097,11 +5220,13 @@ cl_error_t cli_peheader(fmap_t *map, struct cli_exe_info *peinfo, uint32_t opts, goto done; } - for (j = i; j < (size_t)(peinfo->nsections - 1); j++) + for (j = i; j < (size_t)(peinfo->nsections - 1); j++) { memcpy(&(peinfo->sections[j]), &(peinfo->sections[j + 1]), sizeof(struct cli_exe_section)); + } - for (j = i; j < (size_t)(peinfo->nsections - 1); j++) + for (j = i; j < (size_t)(peinfo->nsections - 1); j++) { memcpy(§ion_hdrs[j], §ion_hdrs[j + 1], sizeof(struct pe_image_section_hdr)); + } peinfo->nsections--; @@ -5142,8 +5267,9 @@ cl_error_t cli_peheader(fmap_t *map, struct cli_exe_info *peinfo, uint32_t opts, // TODO Why do we do this // TODO Should this be done before we dump the json - if (!section->vsz && section->rsz) + if (!section->vsz && section->rsz) { section->vsz = PESALIGN(section->ursz, salign); + } if (opts & CLI_PEHEADER_OPT_DBG_PRINT_INFO) { cli_dbgmsg("Section %zu\n", section_pe_idx); @@ -5166,11 +5292,13 @@ cl_error_t cli_peheader(fmap_t *map, struct cli_exe_info *peinfo, uint32_t opts, */ } - if (section->chr & 0x20000000) + if (section->chr & 0x20000000) { cli_dbgmsg("Section's memory is executable\n"); + } - if (section->chr & 0x80000000) + if (section->chr & 0x80000000) { cli_dbgmsg("Section's memory is writeable\n"); + } cli_dbgmsg("------------------------------------\n"); } @@ -5211,8 +5339,9 @@ cl_error_t cli_peheader(fmap_t *map, struct cli_exe_info *peinfo, uint32_t opts, } } - if (section->rva < peinfo->min) + if (section->rva < peinfo->min) { peinfo->min = section->rva; + } if (section->rva + section->rsz > peinfo->max) { peinfo->max = section->rva + section->rsz; @@ -5250,10 +5379,11 @@ cl_error_t cli_peheader(fmap_t *map, struct cli_exe_info *peinfo, uint32_t opts, cli_dbgmsg("EntryPoint offset: 0x%x (%d)\n", peinfo->ep, peinfo->ep); } - if (is_dll || peinfo->ndatadirs < 3 || !peinfo->dirs[2].Size) + if (is_dll || peinfo->ndatadirs < 3 || !peinfo->dirs[2].Size) { peinfo->res_addr = 0; - else + } else { peinfo->res_addr = peinfo->dirs[2].VirtualAddress; + } while (opts & CLI_PEHEADER_OPT_EXTRACT_VINFO && peinfo->ndatadirs >= 3 && peinfo->dirs[2].Size) { @@ -5269,8 +5399,9 @@ cl_error_t cli_peheader(fmap_t *map, struct cli_exe_info *peinfo, uint32_t opts, memset(&vlist, 0, sizeof(vlist)); findres(0x10, 0xffffffff, map, peinfo, versioninfo_cb, &vlist); - if (!vlist.count) + if (!vlist.count) { break; /* No version_information */ + } if (cli_hashset_init(&peinfo->vinfo, 32, 80)) { cli_errmsg("cli_peheader: Unable to init vinfo hashset\n"); @@ -5281,29 +5412,34 @@ cl_error_t cli_peheader(fmap_t *map, struct cli_exe_info *peinfo, uint32_t opts, for (i = 0; i < vlist.count; i++) { /* enum all version_information res - RESUMABLE */ cli_dbgmsg("cli_peheader: parsing version info @ rva %x (%zu/%u)\n", vlist.rvas[i], i + 1, vlist.count); rva = cli_rawaddr(vlist.rvas[i], peinfo->sections, peinfo->nsections, &err, fsize, peinfo->hdr_size); - if (err) + if (err) { continue; + } - if (!(vptr = fmap_need_off_once(map, rva, 16))) + if (!(vptr = fmap_need_off_once(map, rva, 16))) { continue; + } baseptr = vptr - rva; /* parse resource */ rva = cli_readint32(vptr); /* ptr to version_info */ res_sz = cli_readint32(vptr + 4); /* sizeof(resource) */ rva = cli_rawaddr(rva, peinfo->sections, peinfo->nsections, &err, fsize, peinfo->hdr_size); - if (err) + if (err) { continue; - if (!(vptr = fmap_need_off_once(map, rva, res_sz))) + } + if (!(vptr = fmap_need_off_once(map, rva, res_sz))) { continue; + } while (res_sz > 4) { /* look for version_info - NOT RESUMABLE (expecting exactly one versioninfo) */ uint32_t vinfo_sz, vinfo_val_sz, got_varfileinfo = 0; vinfo_sz = vinfo_val_sz = cli_readint32(vptr); vinfo_sz &= 0xffff; - if (vinfo_sz > res_sz) + if (vinfo_sz > res_sz) { break; /* the content is larger than the container */ + } vinfo_val_sz >>= 16; if (vinfo_sz <= 6 + 0x20 + 2 + 0x34 || @@ -5324,8 +5460,9 @@ cl_error_t cli_peheader(fmap_t *map, struct cli_exe_info *peinfo, uint32_t opts, while (vinfo_sz > 6) { /* look for stringfileinfo - NOT RESUMABLE (expecting at most one stringfileinfo) */ uint32_t sfi_sz = cli_readint32(vptr) & 0xffff; - if (sfi_sz > vinfo_sz) + if (sfi_sz > vinfo_sz) { break; /* the content is larger than the container */ + } if (!got_varfileinfo && sfi_sz > 6 + 0x18 && !memcmp(vptr + 6, "V\0a\0r\0F\0i\0l\0e\0I\0n\0f\0o\0\0\0", 0x18)) { /* skip varfileinfo as it sometimes appear before stringtableinfo */ @@ -5376,8 +5513,9 @@ cl_error_t cli_peheader(fmap_t *map, struct cli_exe_info *peinfo, uint32_t opts, /* ~wcstrlen(key) */ for (s_key_sz = 6; s_key_sz + 1 < s_sz; s_key_sz += 2) { - if (vptr[s_key_sz] || vptr[s_key_sz + 1]) + if (vptr[s_key_sz] || vptr[s_key_sz + 1]) { continue; + } s_key_sz += 2; break; @@ -5497,11 +5635,13 @@ cl_error_t cli_check_auth_header(cli_ctx *ctx, struct cli_exe_info *peinfo) // If Authenticode parsing has been disabled via DCONF or an engine // option, then don't continue on. - if (!(DCONF & PE_CONF_CERTS)) + if (!(DCONF & PE_CONF_CERTS)) { return CL_EVERIFY; + } - if (ctx->engine->engine_options & ENGINE_OPTIONS_DISABLE_PE_CERTS) + if (ctx->engine->engine_options & ENGINE_OPTIONS_DISABLE_PE_CERTS) { return CL_EVERIFY; + } // If peinfo is NULL, initialize one. This makes it so that this function // can be used easily by sigtool @@ -5558,10 +5698,11 @@ cl_error_t cli_check_auth_header(cli_ctx *ctx, struct cli_exe_info *peinfo) at = hlen + 4; /* Checksum to security */ - if (peinfo->is_pe32plus) + if (peinfo->is_pe32plus) { hlen = sizeof(struct pe_image_optional_hdr64) - offsetof(struct pe_image_optional_hdr64, CheckSum) - 4; - else + } else { hlen = sizeof(struct pe_image_optional_hdr32) - offsetof(struct pe_image_optional_hdr32, CheckSum) - 4; + } hlen += sizeof(struct pe_image_data_dir) * 4; add_chunk_to_hash_list(at, hlen); @@ -5756,8 +5897,9 @@ cl_error_t cli_genhash_pe(cli_ctx *ctx, unsigned int class, int type, stats_sect } } - if (class >= CL_GENHASH_PE_CLASS_LAST) + if (class >= CL_GENHASH_PE_CLASS_LAST) { return CL_EARG; + } // TODO see if peinfo can be passed in (or lives in ctx or something) and // if so, use that to avoid having to re-parse the header diff --git a/libclamav/pe_icons.c b/libclamav/pe_icons.c index 7a0dcfd735..b2f48f6db3 100644 --- a/libclamav/pe_icons.c +++ b/libclamav/pe_icons.c @@ -78,8 +78,9 @@ static int groupicon_scan_cb(void *ptr, uint32_t type, uint32_t name, uint32_t l /* scan icon group */ ret = cli_groupiconscan(icon_env, rva); - if (ret != CL_CLEAN) + if (ret != CL_CLEAN) { return 1; + } return 0; } @@ -101,8 +102,9 @@ static int icon_scan_cb(void *ptr, uint32_t type, uint32_t name, uint32_t lang, icon_env->result = parseicon(icon_env, rva); icon_env->hcnt++; - if (icon_env->result != CL_CLEAN) + if (icon_env->result != CL_CLEAN) { return 1; + } return 0; } @@ -135,31 +137,39 @@ int cli_scanicon(icon_groupset *set, cli_ctx *ctx, struct cli_exe_info *peinfo) findres(14, 0xffffffff, map, peinfo, groupicon_scan_cb, &icon_env); /* CL_EMAXSIZE is used to track the icon limit */ - if (icon_env.result == CL_EMAXSIZE) + if (icon_env.result == CL_EMAXSIZE) { cli_dbgmsg("cli_scanicon: max icon count reached\n"); + } cli_dbgmsg("cli_scanicon: scanned a total of %u[%u actual] icons across %u groups\n", icon_env.icnt, icon_env.hcnt, icon_env.gcnt); - if (icon_env.hcnt < icon_env.icnt) + if (icon_env.hcnt < icon_env.icnt) { cli_warnmsg("cli_scanicon: found %u invalid icon entries of %u total\n", icon_env.icnt - icon_env.hcnt, icon_env.icnt); + } err_total = icon_env.err_oof + icon_env.err_bhoof + icon_env.err_bhts + icon_env.err_tstl + icon_env.err_insl; if (err_total > 0) { cli_dbgmsg("cli_scanicon: detected %u total image parsing issues\n", err_total); - if (icon_env.err_oof > 0) + if (icon_env.err_oof > 0) { cli_dbgmsg("cli_scanicon: detected %u cases of 'parseicon: offset to icon is out of file'\n", icon_env.err_oof); - if (icon_env.err_bhoof > 0) + } + if (icon_env.err_bhoof > 0) { cli_dbgmsg("cli_scanicon: detected %u cases of 'parseicon: bmp header is out of file'\n", icon_env.err_bhoof); - if (icon_env.err_bhts > 0) + } + if (icon_env.err_bhts > 0) { cli_dbgmsg("cli_scanicon: detected %u cases of 'parseicon: BMP header too small'\n", icon_env.err_bhts); - if (icon_env.err_tstl > 0) + } + if (icon_env.err_tstl > 0) { cli_dbgmsg("cli_scanicon: detected %u cases of 'parseicon: Image too small or too big'\n", icon_env.err_tstl); - if (icon_env.err_insl > 0) + } + if (icon_env.err_insl > 0) { cli_dbgmsg("cli_scanicon: detected %u cases of 'parseicon: Image not square enough'\n", icon_env.err_insl); + } } /* ignore all error returns (previous behavior) */ - if (icon_env.result == CL_VIRUS) + if (icon_env.result == CL_VIRUS) { return CL_VIRUS; + } return CL_CLEAN; } @@ -207,11 +217,13 @@ int cli_groupiconscan(struct ICON_ENV *icon_env, uint32_t rva) /* icon scan callback --> icon_scan_cb() */ findres(3, cli_readint16(&dir->id), map, peinfo, icon_scan_cb, icon_env); - if (icon_env->result != CL_CLEAN) + if (icon_env->result != CL_CLEAN) { return icon_env->result; + } - if (piconcnt == icon_env->hcnt) + if (piconcnt == icon_env->hcnt) { cli_dbgmsg("cli_scanicon: invalid icon entry %u in group @%x\n", dir->id, rva); + } icon_env->icnt++; icnt--; @@ -225,10 +237,12 @@ int cli_groupiconscan(struct ICON_ENV *icon_env, uint32_t rva) gsz -= 14; } - if (icnt != 0) + if (icnt != 0) { cli_dbgmsg("cli_scanicon: could not find %u icons\n", icnt); - if (gsz != 0) + } + if (gsz != 0) { cli_dbgmsg("cli_scanicon: could not parse %u bytes of icon entries\n", gsz); + } } } } @@ -645,18 +659,21 @@ static void lab(double r, double g, double b, double *L, double *A, double *B) g /= 255.0f; b /= 255.0f; - if (r > 0.04045f) + if (r > 0.04045f) { r = pow(((r + 0.055f) / 1.055f), 2.4f); - else + } else { r /= 12.92f; - if (g > 0.04045f) + } + if (g > 0.04045f) { g = pow(((g + 0.055f) / 1.055f), 2.4f); - else + } else { g /= 12.92f; - if (b > 0.04045f) + } + if (b > 0.04045f) { b = pow(((b + 0.055f) / 1.055f), 2.4f); - else + } else { b /= 12.92f; + } r *= 100.0f; g *= 100.0f; @@ -670,18 +687,21 @@ static void lab(double r, double g, double b, double *L, double *A, double *B) y /= 100.000f; z /= 108.883f; - if (x > 0.008856f) + if (x > 0.008856f) { x = pow(x, 1.0f / 3.0f); - else + } else { x = (7.787f * x) + (16.0f / 116.0f); - if (y > 0.008856f) + } + if (y > 0.008856f) { y = pow(y, (1.0f / 3.0f)); - else + } else { y = (7.787f * y) + (16.0f / 116.0f); - if (z > 0.008856f) + } + if (z > 0.008856f) { z = pow(z, (1.0f / 3.0f)); - else + } else { z = (7.787f * z) + (16.0f / 116.0f); + } *L = (116.0f * y) - 16.0f; *A = 500.0f * (x - y); @@ -761,10 +781,12 @@ static void makebmp(const char *step, const char *tempd, int w, int h, void *dat char *fname; FILE *f; - if (!tempd) + if (!tempd) { return; - if (!(fname = cli_gentemp_with_prefix(tempd, "bmp"))) + } + if (!(fname = cli_gentemp_with_prefix(tempd, "bmp"))) { return; + } if (!(f = fopen(fname, "wb"))) { cli_unlink(fname); cli_dbgmsg("makebmp: failed to create file %s\n", fname); @@ -791,27 +813,30 @@ static void makebmp(const char *step, const char *tempd, int w, int h, void *dat return; } - for (y = h - 1; y < (unsigned int)h; y--) + for (y = h - 1; y < (unsigned int)h; y--) { #if WORDS_BIGENDIAN == 0 - if (!fwrite(&((unsigned int *)data)[y * w], w * 4, 1, f)) + if (!fwrite(&((unsigned int *)data)[y * w], w * 4, 1, f)) { break; + } + } #else - { - int x; - for (x = 0; x < w; x++) { - cli_writeint32(&tmp1, ((unsigned int *)data)[y * w]); - if (!fwrite(&tmp1, 4, 1, f)) + { + int x; + for (x = 0; x < w; x++) { + cli_writeint32(&tmp1, ((unsigned int *)data)[y * w]); + if (!fwrite(&tmp1, 4, 1, f)) + break; + } + if (x != w) break; } - if (x != w) - break; - } #endif fclose(f); - if (y < (unsigned int)h) + if (y < (unsigned int)h) { cli_unlink(fname); - else + } else { cli_dbgmsg("makebmp: Image %s dumped to %s\n", step, fname); + } free(fname); } @@ -826,12 +851,14 @@ static unsigned int matchpoint(unsigned int side, unsigned int *x1, unsigned int int diffx = (int)x1[i] - (int)x2[j]; int diffy = ((int)y1[i] - (int)y2[j]); unsigned int diff = sqrt(diffx * diffx + diffy * diffy); - if (diff > ksize * 3 / 4 || (unsigned int)abs((int)avg1[i] - (int)avg2[j]) > max / 5) + if (diff > ksize * 3 / 4 || (unsigned int)abs((int)avg1[i] - (int)avg2[j]) > max / 5) { continue; + } diff = 100 - diff * 60 / (ksize * 3 / 4); - if (diff > best) + if (diff > best) { best = diff; + } } match += best; } @@ -866,12 +893,14 @@ static unsigned int matchbwpoint(unsigned int side, unsigned int *x1a, unsigned int diffx = (int)x1[i] - (int)x2[j]; int diffy = ((int)y1[i] - (int)y2[j]); unsigned int diff = sqrt(diffx * diffx + diffy * diffy); - if (diff > ksize * 3 / 4 || (unsigned int)abs((int)avg1[i] - (int)avg2[j]) > 255 / 5) + if (diff > ksize * 3 / 4 || (unsigned int)abs((int)avg1[i] - (int)avg2[j]) > 255 / 5) { continue; + } diff = 100 - diff * 60 / (ksize * 3 / 4); - if (diff > best) + if (diff > best) { best = diff; + } } match += best; } @@ -888,10 +917,11 @@ static void hsv(unsigned int c, unsigned int *r, unsigned int *g, unsigned int * max = MAX(*r, MAX(*g, *b)); *v = max; *delta = max - min; - if (!*delta) + if (!*delta) { *s = 0; - else + } else { *s = 255 * (*delta) / max; + } } static int getmetrics(unsigned int side, unsigned int *imagedata, struct icomtr *res, const char *tempd) @@ -992,8 +1022,9 @@ static int getmetrics(unsigned int side, unsigned int *imagedata, struct icomtr if (colsum > res->color_avg[i]) { for (j = 0; j < i; j++) { if (x + ksize > res->color_x[j] && x < res->color_x[j] + ksize && - y + ksize > res->color_y[j] && y < res->color_y[j] + ksize) + y + ksize > res->color_y[j] && y < res->color_y[j] + ksize) { break; + } } if (j == i) { res->color_avg[i] = colsum; @@ -1004,8 +1035,9 @@ static int getmetrics(unsigned int side, unsigned int *imagedata, struct icomtr if (colsum < res->gray_avg[i]) { for (j = 0; j < i; j++) { if (x + ksize > res->gray_x[j] && x < res->gray_x[j] + ksize && - y + ksize > res->gray_y[j] && y < res->gray_y[j] + ksize) + y + ksize > res->gray_y[j] && y < res->gray_y[j] + ksize) { break; + } } if (j == i) { res->gray_avg[i] = colsum; @@ -1016,8 +1048,9 @@ static int getmetrics(unsigned int side, unsigned int *imagedata, struct icomtr if (lightsum > res->bright_avg[i]) { for (j = 0; j < i; j++) { if (x + ksize > res->bright_x[j] && x < res->bright_x[j] + ksize && - y + ksize > res->bright_y[j] && y < res->bright_y[j] + ksize) + y + ksize > res->bright_y[j] && y < res->bright_y[j] + ksize) { break; + } } if (j == i) { res->bright_avg[i] = lightsum; @@ -1028,8 +1061,9 @@ static int getmetrics(unsigned int side, unsigned int *imagedata, struct icomtr if (lightsum < res->dark_avg[i]) { for (j = 0; j < i; j++) { if (x + ksize > res->dark_x[j] && x < res->dark_x[j] + ksize && - y + ksize > res->dark_y[j] && y < res->dark_y[j] + ksize) + y + ksize > res->dark_y[j] && y < res->dark_y[j] + ksize) { break; + } } if (j == i) { res->dark_avg[i] = lightsum; @@ -1087,7 +1121,7 @@ static int getmetrics(unsigned int side, unsigned int *imagedata, struct icomtr #ifdef USE_FLOATS double gx, gy; #else - unsigned int gx, gy; + unsigned int gx, gy; #endif /* X matrix */ @@ -1108,8 +1142,9 @@ static int getmetrics(unsigned int side, unsigned int *imagedata, struct icomtr sob = (int)sqrt(gx * gx + gy * gy); tmp[y * side + x] = sob; - if (sob > i) + if (sob > i) { i = sob; + } } } #ifdef USE_FLOATS @@ -1164,8 +1199,9 @@ static int getmetrics(unsigned int side, unsigned int *imagedata, struct icomtr tot += gaussk[disp + gkernsz / 2]; } sum /= tot; - if (sum > i) + if (sum > i) { i = sum; + } imagedata[y * side + x] = 0xff000000 | sum | (sum << 8) | (sum << 16); } } @@ -1178,8 +1214,9 @@ static int getmetrics(unsigned int side, unsigned int *imagedata, struct icomtr if (x == 0 && y == 0) { /* 1st windows */ for (yk = 0; yk < ksize; yk++) { - for (xk = 0; xk < ksize; xk++) + for (xk = 0; xk < ksize; xk++) { sum += imagedata[(y + yk) * side + x + xk] & 0xff; + } } } else if (x) { /* next column */ sum = tmp[y * side + x - 1]; @@ -1209,8 +1246,9 @@ static int getmetrics(unsigned int side, unsigned int *imagedata, struct icomtr if (sum > edge_avg[i]) { for (j = 0; j < i; j++) { if (x + ksize > edge_x[j] && x < edge_x[j] + ksize && - y + ksize > edge_y[j] && y < edge_y[j] + ksize) + y + ksize > edge_y[j] && y < edge_y[j] + ksize) { break; + } } if (j == i) { edge_avg[i] = sum; @@ -1221,8 +1259,9 @@ static int getmetrics(unsigned int side, unsigned int *imagedata, struct icomtr if (sum < noedge_avg[i]) { for (j = 0; j < i; j++) { if (x + ksize > noedge_x[j] && x < noedge_x[j] + ksize && - y + ksize > noedge_y[j] && y < noedge_y[j] + ksize) + y + ksize > noedge_y[j] && y < noedge_y[j] + ksize) { break; + } } if (j == i) { noedge_avg[i] = sum; @@ -1262,8 +1301,9 @@ static int getmetrics(unsigned int side, unsigned int *imagedata, struct icomtr cli_dbgmsg("%s areas: %u@(%u,%u) %u@(%u,%u) %u@(%u,%u)\n", bwonly ? "noedge(2nd)" : "gray", res->gray_avg[0], res->gray_x[0], res->gray_y[0], res->gray_avg[1], res->gray_x[1], res->gray_y[1], res->gray_avg[2], res->gray_x[2], res->gray_y[2]); cli_dbgmsg("bright areas: %u@(%u,%u) %u@(%u,%u) %u@(%u,%u)\n", res->bright_avg[0], res->bright_x[0], res->bright_y[0], res->bright_avg[1], res->bright_x[1], res->bright_y[1], res->bright_avg[2], res->bright_x[2], res->bright_y[2]); cli_dbgmsg("dark areas: %u@(%u,%u) %u@(%u,%u) %u@(%u,%u)\n", res->dark_avg[0], res->dark_x[0], res->dark_y[0], res->dark_avg[1], res->dark_x[1], res->dark_y[1], res->dark_avg[2], res->dark_x[2], res->dark_y[2]); - if (!bwonly) + if (!bwonly) { cli_dbgmsg("color spread: %u,%u,%u %u%%\n", res->rsum, res->gsum, res->bsum, res->ccount); + } if (cli_debug_flag) { #define ICOSIGSZ (2 + (3 + 2 + 2) * 3 * 2 + (2 + 2 + 2) * 3 * 4 + 2 + 2 + 2 + 2) @@ -1366,8 +1406,9 @@ static int parseicon(struct ICON_ENV *icon_env, uint32_t rva) struct icon_matcher *matcher; unsigned int special_32_is_32 = 0; - if (!ctx || !ctx->engine || !(matcher = ctx->engine->iconcheck)) + if (!ctx || !ctx->engine || !(matcher = ctx->engine->iconcheck)) { return CL_SUCCESS; + } map = ctx->fmap; tempd = (cli_debug_flag && ctx->engine->keeptmp) ? (ctx->sub_tmpdir ? ctx->sub_tmpdir : cli_gettmpdir()) : NULL; icoff = cli_rawaddr(rva, peinfo->sections, peinfo->nsections, &err, map->len, peinfo->hdr_size); @@ -1412,12 +1453,13 @@ static int parseicon(struct ICON_ENV *icon_env, uint32_t rva) /* scaling logic */ if (width == height) { - if (width == 16 || width == 24 || width == 32) + if (width == 16 || width == 24 || width == 32) { scalemode = 0; - else if (!(width % 32) || !(width % 24)) + } else if (!(width % 32) || !(width % 24)) { scalemode = 1; - else + } else { scalemode = 2; + } } cli_dbgmsg("parseicon: Bitmap - %ux%ux%u\n", width, height, depth); @@ -1433,8 +1475,9 @@ static int parseicon(struct ICON_ENV *icon_env, uint32_t rva) case 4: case 8: /* HAVE PALETTE */ - if (!(palette = fmap_need_off(map, icoff, (1 << depth) * sizeof(int)))) + if (!(palette = fmap_need_off(map, icoff, (1 << depth) * sizeof(int)))) { return CL_SUCCESS; + } icoff += (1 << depth) * sizeof(int); /* for(j=0; jicons[enginesize][x].group[0]; j = i % 64; i /= 64; - if (!(set->v[0][i] & ((uint64_t)1 << j))) + if (!(set->v[0][i] & ((uint64_t)1 << j))) { continue; + } i = matcher->icons[enginesize][x].group[1]; j = i % 64; i /= 64; - if (!(set->v[1][i] & ((uint64_t)1 << j))) + if (!(set->v[1][i] & ((uint64_t)1 << j))) { continue; + } if (!metrics.ccount && !matcher->icons[enginesize][x].ccount) { /* BW matching */ @@ -1670,8 +1724,9 @@ static int parseicon(struct ICON_ENV *icon_env, uint32_t rva) if (bwmatch) { confidence = (bright + dark + edge * 2 + noedge) / 6; positivematch = 70; - } else + } else { confidence = (color + (gray + bright + noedge) * 2 / 3 + dark + edge + colors) / 6; + } #ifdef LOGPARSEICONDETAILS cli_dbgmsg("parseicon: edge confidence: %u%%\n", edge); @@ -1700,8 +1755,9 @@ void cli_icongroupset_add(const char *groupname, icon_groupset *set, unsigned in struct icon_matcher *matcher; unsigned int i, j; - if (type > 1 || !ctx || !ctx->engine || !(matcher = ctx->engine->iconcheck) || !matcher->group_counts[type]) + if (type > 1 || !ctx || !ctx->engine || !(matcher = ctx->engine->iconcheck) || !matcher->group_counts[type]) { return; + } j = matcher->group_counts[type]; if (groupname[0] == '*' && !groupname[1]) { @@ -1709,12 +1765,13 @@ void cli_icongroupset_add(const char *groupname, icon_groupset *set, unsigned in return; } for (i = 0; i < j; i++) { - if (!strcmp(groupname, matcher->group_names[type][i])) + if (!strcmp(groupname, matcher->group_names[type][i])) { break; + } } - if (i == j) + if (i == j) { cli_dbgmsg("cli_icongroupset_add: failed to locate icon group%u %s\n", type, groupname); - else { + } else { j = i % 64; i /= 64; set->v[type][i] |= (uint64_t)1 << j; diff --git a/libclamav/petite.c b/libclamav/petite.c index b51c089be1..1f8e6bc0ec 100644 --- a/libclamav/petite.c +++ b/libclamav/petite.c @@ -65,8 +65,9 @@ static int doubledl(char **scur, uint8_t *mydlptr, char *buffer, uint32_t buffer mydl *= 2; if (!(olddl & 0x7f)) { - if (*scur < buffer || *scur >= buffer + buffersize - 1) + if (*scur < buffer || *scur >= buffer + buffersize - 1) { return -1; + } olddl = **scur; mydl = olddl * 2 + 1; *scur = *scur + 1; @@ -95,8 +96,9 @@ int petite_inflate2x_1to9(char *buf, uint32_t minrva, uint32_t bufsz, struct cli * See below... */ - if (version == 2) + if (version == 2) { packed = adjbuf + sections[sectcount - 1].rva + 0x1b8; + } if (version == 1) { packed = adjbuf + sections[sectcount - 1].rva + 0x178; grown = 0x323; /* My name is Harry potter */ @@ -110,8 +112,9 @@ int petite_inflate2x_1to9(char *buf, uint32_t minrva, uint32_t bufsz, struct cli unsigned int backsize; if (!CLI_ISCONTAINED(buf, bufsz, packed, 4)) { - if (usects) + if (usects) { free(usects); + } return 1; } srva = cli_readint32(packed); @@ -120,8 +123,9 @@ int petite_inflate2x_1to9(char *buf, uint32_t minrva, uint32_t bufsz, struct cli /* WERE DONE !!! :D */ int t, upd = 1; - if (j <= 0) /* Some non petite compressed files will get here */ + if (j <= 0) { /* Some non petite compressed files will get here */ return 1; + } /* Select * from sections order by rva asc; */ while (upd) { @@ -129,8 +133,9 @@ int petite_inflate2x_1to9(char *buf, uint32_t minrva, uint32_t bufsz, struct cli for (t = 0; t < j - 1; t++) { uint32_t trva, trsz, tvsz; - if (usects[t].rva <= usects[t + 1].rva) + if (usects[t].rva <= usects[t + 1].rva) { continue; + } trva = usects[t].rva; trsz = usects[t].rsz; tvsz = usects[t].vsz; @@ -146,8 +151,9 @@ int petite_inflate2x_1to9(char *buf, uint32_t minrva, uint32_t bufsz, struct cli /* Computes virtualsize... we try to guess, actually :O */ for (t = 0; t < j - 1; t++) { - if (usects[t].vsz != usects[t + 1].rva - usects[t].rva) + if (usects[t].vsz != usects[t + 1].rva - usects[t].rva) { usects[t].vsz = usects[t + 1].rva - usects[t].rva; + } } /* @@ -192,16 +198,19 @@ int petite_inflate2x_1to9(char *buf, uint32_t minrva, uint32_t bufsz, struct cli } else { api = 0xbff01337; /* KERNEL32!leet */ } - if (sections[sectcount - 1].rva + Imagebase < api) + if (sections[sectcount - 1].rva + Imagebase < api) { enc_ep--; - if (api < virtaddr) + } + if (api < virtaddr) { enc_ep--; + } tmpep = (enc_ep & 0xfffffff8) >> 3 & 0x1fffffff; enc_ep = (enc_ep & 7) << 29 | tmpep; } } - } else + } else { workdone = 1; + } enc_ep = pep + 5 + enc_ep; if (workdone == 1) { cli_dbgmsg("Petite: Old EP: %x\n", enc_ep); @@ -227,8 +236,9 @@ int petite_inflate2x_1to9(char *buf, uint32_t minrva, uint32_t bufsz, struct cli /* Showtime!!! */ cli_dbgmsg("Petite: Sections dump:\n"); - for (t = 0; t < j; t++) + for (t = 0; t < j; t++) { cli_dbgmsg("Petite: .SECT%d RVA:%x VSize:%x ROffset: %x, RSize:%x\n", t, usects[t].rva, usects[t].vsz, usects[t].raw, usects[t].rsz); + } if (!cli_rebuildpe(buf, usects, j, Imagebase, enc_ep, ResRva, ResSize, desc)) { cli_dbgmsg("Petite: Rebuilding failed\n"); free(usects); @@ -249,16 +259,18 @@ int petite_inflate2x_1to9(char *buf, uint32_t minrva, uint32_t bufsz, struct cli */ if (!CLI_ISCONTAINED(buf, bufsz, packed + 4, 8)) { - if (usects) + if (usects) { free(usects); + } return 1; } /* Save the end of current packed section for later use */ bottom = (uint32_t)cli_readint32(packed + 8); if (bottom > UINT32_MAX - 4) { /* bottom is too large, would cause integer overflow */ - if (usects) + if (usects) { free(usects); + } return 1; } bottom += 4; @@ -267,8 +279,9 @@ int petite_inflate2x_1to9(char *buf, uint32_t minrva, uint32_t bufsz, struct cli ddst = adjbuf + cli_readint32(packed + 8) - (size - 1) * 4; if (!CLI_ISCONTAINED(buf, bufsz, ssrc, size * 4) || !CLI_ISCONTAINED(buf, bufsz, ddst, size * 4)) { - if (usects) + if (usects) { free(usects); + } return 1; } @@ -284,8 +297,9 @@ int petite_inflate2x_1to9(char *buf, uint32_t minrva, uint32_t bufsz, struct cli /* Unpack each original section in turn */ if (!CLI_ISCONTAINED(buf, bufsz, packed + 4, 8)) { - if (usects) + if (usects) { free(usects); + } return 1; } @@ -300,8 +314,9 @@ int petite_inflate2x_1to9(char *buf, uint32_t minrva, uint32_t bufsz, struct cli } /* Alloc 1 more struct */ if (!(tmpsct = cli_max_realloc(usects, sizeof(struct cli_exe_section) * (j + 1)))) { - if (usects) + if (usects) { free(usects); + } return 1; } @@ -309,10 +324,11 @@ int petite_inflate2x_1to9(char *buf, uint32_t minrva, uint32_t bufsz, struct cli /* Save section spex for later rebuilding */ usects[j].rva = thisrva; usects[j].rsz = size; - if ((int)(bottom - thisrva) > 0) + if ((int)(bottom - thisrva) > 0) { usects[j].vsz = bottom - thisrva; - else + } else { usects[j].vsz = size; + } usects[j].raw = 0; /* Cheaper than memset */ if (!size) { /* That's a ghost section! reloc any1? :P */ @@ -328,8 +344,9 @@ int petite_inflate2x_1to9(char *buf, uint32_t minrva, uint32_t bufsz, struct cli */ for (q = 0; q < sectcount; q++) { - if (!CLI_ISCONTAINED(sections[q].rva, sections[q].vsz, usects[j].rva, usects[j].vsz)) + if (!CLI_ISCONTAINED(sections[q].rva, sections[q].vsz, usects[j].rva, usects[j].vsz)) { continue; + } if (!check4resources) { usects[j].rva = sections[q].rva; usects[j].rsz = thisrva - sections[q].rva + size; @@ -407,8 +424,9 @@ int petite_inflate2x_1to9(char *buf, uint32_t minrva, uint32_t bufsz, struct cli free(usects); return 1; } - if (!oob) + if (!oob) { break; + } } backbytes -= 3; if (backbytes >= 0) { @@ -456,8 +474,9 @@ int petite_inflate2x_1to9(char *buf, uint32_t minrva, uint32_t bufsz, struct cli free(usects); return 1; } - if (!oob) + if (!oob) { break; + } } backsize += 2; } diff --git a/libclamav/phish_allow_list.c b/libclamav/phish_allow_list.c index 9efe7534c9..6b285ee15f 100644 --- a/libclamav/phish_allow_list.c +++ b/libclamav/phish_allow_list.c @@ -61,8 +61,9 @@ cl_error_t init_allow_list(struct cl_engine* engine) ((struct regex_matcher*)(engine->allow_list_matcher))->mempool = engine->mempool; #endif return init_regex_list(engine->allow_list_matcher, engine->dconf->other & OTHER_CONF_PREFILTERING); - } else + } else { return CL_ENULLARG; + } } int is_allow_list_ok(const struct cl_engine* engine) diff --git a/libclamav/phish_domaincheck_db.c b/libclamav/phish_domaincheck_db.c index 5377ac9fa0..0715a5ed96 100644 --- a/libclamav/phish_domaincheck_db.c +++ b/libclamav/phish_domaincheck_db.c @@ -60,8 +60,9 @@ int init_domain_list(struct cl_engine* engine) ((struct regex_matcher*)engine->domain_list_matcher)->mempool = engine->mempool; #endif return init_regex_list(engine->domain_list_matcher, engine->dconf->other & OTHER_CONF_PREFILTERING); - } else + } else { return CL_ENULLARG; + } } int is_domain_list_ok(const struct cl_engine* engine) diff --git a/libclamav/phishcheck.c b/libclamav/phishcheck.c index 5f014aa02c..be67036bf0 100644 --- a/libclamav/phishcheck.c +++ b/libclamav/phishcheck.c @@ -223,15 +223,17 @@ static void string_free(struct string* str) for (;;) { str->refcount--; if (!str->refcount) { - if (str->ref) /* don't free, this is a portion of another string */ + if (str->ref) { /* don't free, this is a portion of another string */ str = str->ref; /* try to free that one*/ - else { - if (str->data) + } else { + if (str->data) { free(str->data); + } break; } - } else + } else { break; + } } } @@ -330,8 +332,9 @@ static int build_regex(regex_t* preg, const char* regex, int nosub) cli_regerror(rc, preg, errbuf, buflen); cli_errmsg("Phishcheck: Error in compiling regex:%s\nDisabling phishing checks\n", errbuf); free(errbuf); - } else + } else { cli_errmsg("Phishcheck: Error in compiling regex, disabling phishing checks. Additionally an Out-of-memory error was encountered while generating a detailed error message\n"); + } return 1; } return CL_SUCCESS; @@ -356,18 +359,21 @@ static int get_host(const char* URL, int isReal, int* phishy, const char** hstar /* it is not required to use mailto: in the displayed url, they might use to:, or whatever */ end = URL + strlen(URL) + 1; start = URL + strcspn(URL, ": ") + 1; - if (start == end) + if (start == end) { start = URL; + } ismailto = 1; } else { start = URL; /*URL without protocol*/ - if (isReal) + if (isReal) { cli_dbgmsg("Phishcheck: Real URL without protocol: %s\n", URL); - else + } else { ismailto = 2; /*no-protocol, might be mailto, @ is no problem*/ + } } - } else + } else { start += 3; /* :// */ + } if (!ismailto || !isReal) { const char *realhost, *tld; @@ -383,20 +389,24 @@ static int get_host(const char* URL, int isReal, int* phishy, const char** hstar tld = strrchr(realhost, '.'); rc = tld ? !!in_tld_set(tld, strlen(tld)) : 0; - if (rc < 0) + if (rc < 0) { return rc; - if (rc) - *phishy |= PHISHY_USERNAME_IN_URL; /* if the url contains a username that is there just to fool people, - like http://banksite@example.com/ */ - start = realhost + 1; /*skip the username*/ - } while (realhost); /*skip over multiple @ characters, text following last @ character is the real host*/ - } else if (ismailto && isReal) + } + if (rc) { + *phishy |= PHISHY_USERNAME_IN_URL; + } /* if the url contains a username that is there just to fool people, + like http://banksite@example.com/ */ + start = realhost + 1; /*skip the username*/ + } while (realhost); /*skip over multiple @ characters, text following last @ character is the real host*/ + } else if (ismailto && isReal) { *phishy |= REAL_IS_MAILTO; + } if (!end) { end = start + strcspn(start, ":/?"); /*especially important for mailto:somebody@yahoo.com?subject=...*/ - if (!end) + if (!end) { end = start + strlen(start); + } } *hstart = start; *hend = end; @@ -411,11 +421,13 @@ rfind(char* start, char c, size_t len) { char* p; - if (start == NULL) + if (start == NULL) { return NULL; + } - for (p = start + len; (p >= start) && (*p != c); p--) + for (p = start + len; (p >= start) && (*p != c); p--) { ; + } return (p < start) ? NULL : p; } @@ -457,12 +469,15 @@ static int isNumeric(const char* host) int a, b, c, d, n = 0; /* 1.2.3.4 -> 7*/ /* 127.127.127.127 -> 15*/ - if (len < 7 || len > 15) + if (len < 7 || len > 15) { return 0; + } sscanf(host, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n); - if (n == len) - if (a >= 0 && a <= 256 && b >= 0 && b <= 256 && c >= 0 && c <= 256 && d >= 0 && d <= 256) + if (n == len) { + if (a >= 0 && a <= 256 && b >= 0 && b <= 256 && c >= 0 && c <= 256 && d >= 0 && d <= 256) { return 1; + } + } return 0; } @@ -480,8 +495,9 @@ str_hex_to_char(char** begin, const char** end) char* sbegin = *begin; const char* str_end = *end; - if (str_end <= &sbegin[1]) + if (str_end <= &sbegin[1]) { return; + } /* convert leading %xx*/ if (sbegin[0] == '%') { @@ -497,8 +513,9 @@ str_hex_to_char(char** begin, const char** end) const char* src = sbegin + 3; if (isxdigit(sbegin[1]) && isxdigit(sbegin[2])) { *sbegin = hex2int((unsigned char*)sbegin + 1); - if (*sbegin == '%' && !firsthex) + if (*sbegin == '%' && !firsthex) { firsthex = sbegin; + } /* move string */ memmove(sbegin + 1, src, str_end - src + 1); str_end -= 2; @@ -523,22 +540,25 @@ str_strip(char** begin, const char** end, const char* what, size_t what_len) const char* str_end_what; size_t cmp_len = what_len; - if (begin == NULL || str_end <= sbegin) + if (begin == NULL || str_end <= sbegin) { return; + } /*if(str_end < (sbegin + what_len)) return;*/ - if (strlen(sbegin) < what_len) + if (strlen(sbegin) < what_len) { return; + } /* strip leading @what */ while (cmp_len && !strncmp(sbegin, what, cmp_len)) { sbegin += what_len; - if (cmp_len > what_len) + if (cmp_len > what_len) { cmp_len -= what_len; - else + } else { cmp_len = 0; + } } /* strip trailing @what */ @@ -568,8 +588,9 @@ str_strip(char** begin, const char** end, const char* what, size_t what_len) static void str_replace(char* str, const char* end, char c, char r) { for (; str <= end; str++) { - if (*str == c) + if (*str == c) { *str = r; + } } } static void str_make_lowercase(char* str, size_t len) @@ -582,8 +603,9 @@ static void str_make_lowercase(char* str, size_t len) #define fix32(x) ((x) < 32 ? 32 : (x)) static void clear_msb(char* begin) { - for (; *begin; begin++) + for (; *begin; begin++) { *begin = fix32((*begin) & 0x7f); + } } /* @@ -610,16 +632,23 @@ str_fixup_spaces(char** begin, const char** end) { char* sbegin = *begin; const char* send = *end; - if (!sbegin || !send || send < sbegin) + if (!sbegin || !send || send < sbegin) { return; + } /* strip spaces */ str_strip(&sbegin, &send, " ", 1); /* strip leading/trailing garbage */ - while (!isalnum(sbegin[0] & 0xff) && sbegin <= send) sbegin++; - while (!isalnum(send[0] & 0xff) && send >= sbegin) send--; + while (!isalnum(sbegin[0] & 0xff) && sbegin <= send) { + sbegin++; + } + while (!isalnum(send[0] & 0xff) && send >= sbegin) { + send--; + } /* keep terminating slash character*/ - if (send[1] == '/') send++; + if (send[1] == '/') { + send++; + } *begin = sbegin; *end = send; } @@ -636,8 +665,9 @@ cleanupURL(struct string* URL, struct string* pre_URL, int isReal) /*if(begin == NULL) return;*/ /*TODO: handle hex-encoded IPs*/ - while (isspace(*begin)) + while (isspace(*begin)) { begin++; + } len = strlen(begin); if (len == 0) { @@ -653,8 +683,9 @@ cleanupURL(struct string* URL, struct string* pre_URL, int isReal) string_assign_null(pre_URL); return 0; } - while (isspace(*end)) + while (isspace(*end)) { end--; + } /* From mailscanner, my comments enclosed in {} */ if (!strncmp(begin, dotnet, dotnet_len) || !strncmp(begin, adonet, adonet_len) || !strncmp(begin, aspnet, aspnet_len)) { string_assign_null(URL); @@ -670,11 +701,14 @@ cleanupURL(struct string* URL, struct string* pre_URL, int isReal) * strip path & query parameter(s) * - we want to make hostname lowercase*/ host_begin = strchr(begin, ':'); - while (host_begin && (host_begin < end) && (host_begin[1] == '/')) host_begin++; - if (!host_begin) + while (host_begin && (host_begin < end) && (host_begin[1] == '/')) { + host_begin++; + } + if (!host_begin) { host_begin = begin; - else + } else { host_begin++; + } host_len = strcspn(host_begin, ":/?"); if (host_begin + host_len > end + 1) { /* prevent hostname extending beyond end, it can happen @@ -704,8 +738,12 @@ cleanupURL(struct string* URL, struct string* pre_URL, int isReal) str_strip(&begin, &end, " ", 1); } else { /* trim space */ - while ((begin <= end) && (begin[0] == ' ')) begin++; - while ((begin <= end) && (end[0] == ' ')) end--; + while ((begin <= end) && (begin[0] == ' ')) { + begin++; + } + while ((begin <= end) && (end[0] == ' ')) { + end--; + } } if ((rc = string_assign_dup(isReal ? URL : pre_URL, begin, end + 1))) { string_assign_null(URL); @@ -739,8 +777,9 @@ cl_error_t phishingScan(cli_ctx* ctx, tag_arguments_t* hrefs) urls.flags = strncmp((char*)hrefs->tag[i], href_text, href_text_len) ? (CL_PHISH_ALL_CHECKS & ~CHECK_SSL) : CL_PHISH_ALL_CHECKS; urls.link_type = 0; if (!strncmp((char*)hrefs->tag[i], src_text, src_text_len)) { - if (!(urls.flags & CHECK_IMG_URL)) + if (!(urls.flags & CHECK_IMG_URL)) { continue; + } urls.link_type |= LINKTYPE_IMAGE; } urls.always_check_flags = 0; @@ -834,8 +873,9 @@ cl_error_t phishing_init(struct cl_engine* engine) pchk->is_disabled = 1; } else { pchk = engine->phishcheck; - if (!pchk) + if (!pchk) { return CL_ENULLARG; + } if (!pchk->is_disabled) { /* already initialized */ return CL_SUCCESS; @@ -931,8 +971,9 @@ static inline int validate_uri_xalphas_nodot(const char* start, const char* end) { const unsigned char* p; for (p = (const unsigned char*)start; p < (const unsigned char*)end; p++) { - if (!URI_xalpha_nodot[*p]) + if (!URI_xalpha_nodot[*p]) { return 0; + } } return 1; } @@ -941,8 +982,9 @@ static inline int validate_uri_xpalphas_nodot(const char* start, const char* end { const unsigned char* p; for (p = (const unsigned char*)start; p < (const unsigned char*)end; p++) { - if (!URI_xpalpha_nodot[*p]) + if (!URI_xpalpha_nodot[*p]) { return 0; + } } /* must have at least on char */ return p > (const unsigned char*)start; @@ -951,8 +993,9 @@ static inline int validate_uri_xpalphas_nodot(const char* start, const char* end static inline int validate_uri_ialpha(const char* start, const char* end) { const unsigned char* p = (const unsigned char*)start; - if (start >= end || !URI_alpha[*p]) + if (start >= end || !URI_alpha[*p]) { return 0; + } return validate_uri_xalphas_nodot(start + 1, end); } @@ -964,24 +1007,30 @@ static int isURL(char* URL, int accept_anyproto) char *last_tld_end = NULL, *q; const char *start = NULL, *p, *end; int has_proto = 0; - if (!URL) + if (!URL) { return 0; + } - while (*URL == ' ') URL++; + while (*URL == ' ') { + URL++; + } switch (URL[0]) { case 'h': - if (strncmp(URL, https, https_len) == 0) + if (strncmp(URL, https, https_len) == 0) { start = URL + https_len - 1; - else if (strncmp(URL, http, http_len) == 0) + } else if (strncmp(URL, http, http_len) == 0) { start = URL + http_len - 1; + } break; case 'f': - if (strncmp(URL, ftp, ftp_len) == 0) + if (strncmp(URL, ftp, ftp_len) == 0) { start = URL + ftp_len - 1; + } break; case 'm': - if (strncmp(URL, mailto_proto, mailto_proto_len) == 0) + if (strncmp(URL, mailto_proto, mailto_proto_len) == 0) { start = URL + mailto_proto_len - 1; + } break; } if (start && start[1] == '/' && start[2] == '/') { @@ -995,51 +1044,68 @@ static int isURL(char* URL, int accept_anyproto) /* skip :// */ if (start[1] == '/') { start += 2; - if (*start == '/') + if (*start == '/') { start++; - } else + } + } else { start++; + } has_proto = 1; - } else + } else { start = URL; /* scheme invalid */ - } else + } + } else { start = URL; + } p = start; end = strchr(p, '/'); - if (!end) + if (!end) { end = p + strlen(p); + } if (!has_proto && (q = memchr(p, '@', end - p))) { /* don't phishcheck if displayed URL is email, but do phishcheck if * foo.TLD@host is used */ const char* q2 = q - 1; - while (q2 > p && *q2 != '.') q2--; - if (q2 == p || !in_tld_set(q2 + 1, q - q2 - 1)) + while (q2 > p && *q2 != '.') { + q2--; + } + if (q2 == p || !in_tld_set(q2 + 1, q - q2 - 1)) { return 0; + } } do { q = strchr(p, '.'); - if (q > end) + if (q > end) { break; + } if (q) { - if (!validate_uri_xpalphas_nodot(p, q)) + if (!validate_uri_xpalphas_nodot(p, q)) { return 0; - if (accept_anyproto && in_tld_set(p, q - p)) + } + if (accept_anyproto && in_tld_set(p, q - p)) { last_tld_end = q; + } p = q + 1; } } while (q); - if (p == start) /* must have at least one dot in the URL */ + if (p == start) { /* must have at least one dot in the URL */ return 0; - if (end < p) + } + if (end < p) { end = p; - while (*end == ' ' && end > p) --end; + } + while (*end == ' ' && end > p) { + --end; + } - if (in_tld_set(p, end - p)) + if (in_tld_set(p, end - p)) { return 1; - if (!accept_anyproto) + } + if (!accept_anyproto) { return 0; + } if (last_tld_end) { *last_tld_end = '\0'; return 1; @@ -1076,10 +1142,12 @@ static enum phish_status cleanupURLs(struct url_check* urls) if (urls->flags & CLEANUP_URL) { cleanupURL(&urls->realLink, NULL, 1); cleanupURL(&urls->displayLink, &urls->pre_fixup.pre_displayLink, 0); - if (!urls->displayLink.data || !urls->realLink.data) + if (!urls->displayLink.data || !urls->realLink.data) { return CL_PHISH_NODECISION; - if (!strcmp(urls->realLink.data, urls->displayLink.data)) + } + if (!strcmp(urls->realLink.data, urls->displayLink.data)) { return CL_PHISH_CLEAN; + } } return CL_PHISH_NODECISION; } @@ -1131,12 +1199,13 @@ static void url_get_domain(struct url_check* url, struct url_check* domains) static enum phish_status phishy_map(int phishy, enum phish_status fallback) { - if (phishy & PHISHY_USERNAME_IN_URL) + if (phishy & PHISHY_USERNAME_IN_URL) { return CL_PHISH_CLOAKED_UIU; - else if (phishy & PHISHY_NUMERIC_IP) + } else if (phishy & PHISHY_NUMERIC_IP) { return CL_PHISH_NUMERIC_IP; - else + } else { return fallback; + } } static cl_error_t allow_list_check(const struct cl_engine* engine, struct url_check* urls, int hostOnly) @@ -1176,8 +1245,9 @@ static cl_error_t hash_match(const struct regex_matcher* rlist, void* sha256; sha256 = cl_hash_init("sha256"); - if (!(sha256)) + if (!(sha256)) { return CL_EMEM; + } cl_update_hash(sha256, (void*)host, hlen); cl_update_hash(sha256, (void*)path, plen); @@ -1235,24 +1305,32 @@ enum phish_status cli_url_canon(const char* inurl, size_t len, char* urlbuff, si /* canonicalize only real URLs, with a protocol */ host_begin = strchr(url, ':'); - if (!host_begin) + if (!host_begin) { return CL_PHISH_CLEAN; + } ++host_begin; /* ignore username in URL */ - while ((host_begin < urlend) && *host_begin == '/') ++host_begin; + while ((host_begin < urlend) && *host_begin == '/') { + ++host_begin; + } host_len = strcspn(host_begin, ":/?"); p = memchr(host_begin, '@', host_len); - if (p) + if (p) { host_begin = p + 1; + } url = host_begin; /* repeatedly % unescape characters */ str_hex_to_char(&url, &urlend); host_begin = url; len = urlend - url; /* skip to beginning of hostname */ - while ((host_begin < urlend) && *host_begin == '/') ++host_begin; - while (*host_begin == '.' && host_begin < urlend) ++host_begin; + while ((host_begin < urlend) && *host_begin == '/') { + ++host_begin; + } + while (*host_begin == '.' && host_begin < urlend) { + ++host_begin; + } last = strchr(host_begin, '/'); p = host_begin; @@ -1260,18 +1338,21 @@ enum phish_status cli_url_canon(const char* inurl, size_t len, char* urlbuff, si if (p + 2 < urlend && *p == '/' && p[1] == '.') { if (p[2] == '/') { /* remove /./ */ - if (p + 3 < urlend) + if (p + 3 < urlend) { memmove(p + 1, p + 3, urlend - p - 3); + } urlend -= 2; } else if (p[2] == '.' && (p[3] == '/' || p[3] == '\0') && last) { /* remove /component/../ */ - if (p + 4 < urlend) + if (p + 4 < urlend) { memmove(last + 1, p + 4, urlend - p - 4); + } urlend -= 3 + (p - last); } } - if (*p == '/') + if (*p == '/') { last = p; + } p++; } p = &url[urlend - url]; @@ -1302,8 +1383,9 @@ enum phish_status cli_url_canon(const char* inurl, size_t len, char* urlbuff, si memmove(path_begin + 2, path_begin + 1, len - host_len); *path_begin++ = '/'; *path_begin++ = '\0'; - } else + } else { path_begin = url + len; + } if (url + len >= path_begin) { path_len = url + len - path_begin + 1; p = strchr(path_begin, '#'); @@ -1372,10 +1454,12 @@ static cl_error_t url_hash_match( do { --component; } while (*component != '.' && component > host_begin); - if (*component != '.') + if (*component != '.') { component = NULL; - if (component) + } + if (component) { lp[j--] = component + 1; + } } lp[j] = host_begin; @@ -1383,17 +1467,19 @@ static cl_error_t url_hash_match( pp[0] = path_len; if (path_len) { pp[1] = strcspn(path_begin, "?"); - if (pp[1] != pp[0]) + if (pp[1] != pp[0]) { k = 2; - else + } else { k = 1; + } pp[k++] = 0; while (k < COMPONENTS + 2) { p = strchr(path_begin + pp[k - 1] + 1, '/'); if (p && p > path_begin) { pp[k++] = p - path_begin + 1; - } else + } else { break; + } } } else { k = 1; diff --git a/libclamav/qsort.c b/libclamav/qsort.c index bc2362f009..a3e1453f97 100644 --- a/libclamav/qsort.c +++ b/libclamav/qsort.c @@ -114,10 +114,12 @@ void cli_qsort(void *a, size_t n, size_t es, int (*cmp)(const void *, const void SWAPINIT(a, es); swap_cnt = 0; if (n < 7) { - for (pm = (char *)a + es; pm < (char *)a + n * es; pm += es) + for (pm = (char *)a + es; pm < (char *)a + n * es; pm += es) { for (pl = pm; pl > (char *)a && CMP(pl - es, pl) > 0; - pl -= es) + pl -= es) { swap(pl, pl - es); +} +} return; } pm = (char *)a + (n / 2) * es; @@ -153,18 +155,21 @@ void cli_qsort(void *a, size_t n, size_t es, int (*cmp)(const void *, const void } pc -= es; } - if (pb > pc) + if (pb > pc) { break; +} swap(pb, pc); swap_cnt = 1; pb += es; pc -= es; } if (swap_cnt == 0) { /* Switch to insertion sort */ - for (pm = (char *)a + es; pm < (char *)a + n * es; pm += es) + for (pm = (char *)a + es; pm < (char *)a + n * es; pm += es) { for (pl = pm; pl > (char *)a && CMP(pl - es, pl) > 0; - pl -= es) + pl -= es) { swap(pl, pl - es); +} +} return; } @@ -173,8 +178,9 @@ void cli_qsort(void *a, size_t n, size_t es, int (*cmp)(const void *, const void vecswap(a, pb - r, r); r = MIN((size_t)(pd - pc), (size_t)(pn - pd - es)); vecswap(pb, pn - r, r); - if ((size_t)(r = pb - pa) > es) + if ((size_t)(r = pb - pa) > es) { cli_qsort(a, r / es, es, cmp); +} if ((size_t)(r = pd - pc) > es) { /* Iterate rather than recurse to save stack space */ a = pn - r; @@ -193,10 +199,12 @@ void cli_qsort_r(void *a, size_t n, size_t es, int (*cmp)(const void *, const vo SWAPINIT(a, es); swap_cnt = 0; if (n < 7) { - for (pm = (char *)a + es; pm < (char *)a + n * es; pm += es) + for (pm = (char *)a + es; pm < (char *)a + n * es; pm += es) { for (pl = pm; pl > (char *)a && CMP_R(arg, pl - es, pl) > 0; - pl -= es) + pl -= es) { swap(pl, pl - es); +} +} return; } pm = (char *)a + (n / 2) * es; @@ -232,18 +240,21 @@ void cli_qsort_r(void *a, size_t n, size_t es, int (*cmp)(const void *, const vo } pc -= es; } - if (pb > pc) + if (pb > pc) { break; +} swap(pb, pc); swap_cnt = 1; pb += es; pc -= es; } if (swap_cnt == 0) { /* Switch to insertion sort */ - for (pm = (char *)a + es; pm < (char *)a + n * es; pm += es) + for (pm = (char *)a + es; pm < (char *)a + n * es; pm += es) { for (pl = pm; pl > (char *)a && CMP_R(arg, pl - es, pl) > 0; - pl -= es) + pl -= es) { swap(pl, pl - es); +} +} return; } @@ -252,8 +263,9 @@ void cli_qsort_r(void *a, size_t n, size_t es, int (*cmp)(const void *, const vo vecswap(a, pb - r, r); r = MIN((size_t)(pd - pc), (size_t)(pn - pd - es)); vecswap(pb, pn - r, r); - if ((size_t)(r = pb - pa) > es) + if ((size_t)(r = pb - pa) > es) { cli_qsort_r(a, r / es, es, cmp, arg); +} if ((size_t)(r = pd - pc) > es) { /* Iterate rather than recurse to save stack space */ a = pn - r; diff --git a/libclamav/readdb.c b/libclamav/readdb.c index b2dacff17e..8e9fc5a2ff 100644 --- a/libclamav/readdb.c +++ b/libclamav/readdb.c @@ -102,19 +102,22 @@ char *cli_virname(const char *virname, unsigned int official) { char *newname, *pt; - if (!virname) + if (!virname) { return NULL; + } - if ((pt = strstr(virname, " (Clam)"))) + if ((pt = strstr(virname, " (Clam)"))) { *pt = '\0'; + } if (!virname[0]) { cli_errmsg("cli_virname: Empty virus name\n"); return NULL; } - if (official) + if (official) { return cli_safer_strdup(virname); + } newname = (char *)malloc(strlen(virname) + 11 + 1); if (!newname) { @@ -143,8 +146,9 @@ cl_error_t cli_sigopts_handler(struct cli_matcher *root, const char *virname, co } hexcpy = cli_safer_strdup(hexsig); - if (!hexcpy) + if (!hexcpy) { return CL_EMEM; + } sigopts |= ACPATT_OPTION_ONCE; @@ -261,18 +265,21 @@ cl_error_t cli_sigopts_handler(struct cli_matcher *root, const char *virname, co /* change the '[' and ']' to '{' and '}' since there are now two bytes */ hexovr[len++] = '{'; ++i; - while (i < strlen(hexcpy) && hexcpy[i] != ']') + while (i < strlen(hexcpy) && hexcpy[i] != ']') { hexovr[len++] = hexcpy[i++]; + } hexovr[len] = '}'; } else if (hexcpy[i] == '{') { - while (i < hexcpylen && hexcpy[i] != '}') + while (i < hexcpylen && hexcpy[i] != '}') { hexovr[len++] = hexcpy[i++]; + } hexovr[len] = '}'; } else if (hexcpy[i] == '!' || hexcpy[i] == '(') { - if (hexcpy[i] == '!') + if (hexcpy[i] == '!') { hexovr[len++] = hexcpy[i++]; + } /* copies '(' */ hexovr[len] = hexcpy[i]; @@ -405,8 +412,9 @@ static cl_error_t readdb_load_regex_subsignature(struct cli_matcher *root, const trigger = hexcpy; pattern = start + 1; cflags = end + 1; - if (*cflags == '\0') /* get compat-ed */ + if (*cflags == '\0') { /* get compat-ed */ cflags = NULL; + } /* normal trigger, get added */ ret = cli_pcre_addpatt(root, virname, trigger, pattern, cflags, offset, lsigid, options); @@ -502,8 +510,9 @@ cl_error_t readdb_parse_ldb_subsignature(struct cli_matcher *root, const char *v if (current_subsig_index > 0) { /* allow mapping from lsig back to pattern for macros */ - if (!tdb->macro_ptids) + if (!tdb->macro_ptids) { tdb->macro_ptids = MPOOL_CALLOC(root->mempool, num_subsigs, sizeof(*tdb->macro_ptids)); + } if (!tdb->macro_ptids) { status = CL_EMEM; goto done; @@ -581,17 +590,19 @@ cl_error_t readdb_parse_ldb_subsignature(struct cli_matcher *root, const char *v goto done; } - if ((subtokens_count % 2) == 0) + if ((subtokens_count % 2) == 0) { offset = subtokens[0]; + } - if (subtokens_count == 3) + if (subtokens_count == 3) { sigopts = subtokens[2]; - else if (subtokens_count == 4) + } else if (subtokens_count == 4) { sigopts = subtokens[3]; + } if (sigopts) { /* signature modifiers */ size_t j; - for (j = 0; j < strlen(sigopts); j++) + for (j = 0; j < strlen(sigopts); j++) { switch (sigopts[j]) { case 'i': subsig_opts |= ACPATT_OPTION_NOCASE; @@ -610,6 +621,7 @@ cl_error_t readdb_parse_ldb_subsignature(struct cli_matcher *root, const char *v status = CL_EMALFDB; goto done; } + } } sig = (subtokens_count % 2) ? subtokens[0] : subtokens[1]; @@ -730,8 +742,9 @@ cl_error_t cli_add_content_match_pattern(struct cli_matcher *root, const char *v * Replaces it with: "??" * n and then re-parses the modified hexsig with recursion. */ hexcpy = calloc(hexlen + 2 * range, sizeof(char)); - if (!hexcpy) + if (!hexcpy) { return CL_EMEM; + } strncpy(hexcpy, hexsig, wild - hexsig); for (i = 0; i < range; i++) { @@ -795,8 +808,9 @@ cl_error_t cli_add_content_match_pattern(struct cli_matcher *root, const char *v // Make a copy of the whole pattern so that we can NULL-terminate the hexsig // and pass it to cli_ac_addsig() without having to pass the part-length. - if (!(hexcpy = cli_safer_strdup(hexsig))) + if (!(hexcpy = cli_safer_strdup(hexsig))) { return CL_EMEM; + } start = pt = hexcpy; for (i = 1; i <= parts; i++) { @@ -824,8 +838,9 @@ cl_error_t cli_add_content_match_pattern(struct cli_matcher *root, const char *v break; } - if (i == parts) + if (i == parts) { break; + } // This time around, we need to parse the integer values from "{n}" or "{min-max}" // to be used when we call `cli_ac_addsig()` for the next part. @@ -900,11 +915,11 @@ cl_error_t cli_add_content_match_pattern(struct cli_matcher *root, const char *v nest = 0; for (i = 0; i < hexlen; i++) { - if (hexsig[i] == '(') + if (hexsig[i] == '(') { nest++; - else if (hexsig[i] == ')') + } else if (hexsig[i] == ')') { nest--; - else if (hexsig[i] == '*') { + } else if (hexsig[i] == '*') { if (nest) { cli_errmsg("cli_add_content_match_pattern: Alternative match cannot contain unbounded wildcards\n"); return CL_EMALFDB; @@ -942,8 +957,9 @@ cl_error_t cli_add_content_match_pattern(struct cli_matcher *root, const char *v * format seems like it can be handled with the Boyer-Moore (BM) pattern matcher. */ bm_new = (struct cli_bm_patt *)MPOOL_CALLOC(root->mempool, 1, sizeof(struct cli_bm_patt)); - if (!bm_new) + if (!bm_new) { return CL_EMEM; + } bm_new->pattern = (unsigned char *)CLI_MPOOL_HEX2STR(root->mempool, hexsig); if (!bm_new->pattern) { @@ -960,8 +976,9 @@ cl_error_t cli_add_content_match_pattern(struct cli_matcher *root, const char *v return CL_EMEM; } - if (bm_new->length > root->maxpatlen) + if (bm_new->length > root->maxpatlen) { root->maxpatlen = bm_new->length; + } if (CL_SUCCESS != (ret = cli_bm_addpatt(root, bm_new, offset))) { cli_errmsg("cli_add_content_match_pattern: Problem adding signature (4).\n"); @@ -994,8 +1011,9 @@ cl_error_t cli_initroots(struct cl_engine *engine, unsigned int options) root->mempool = engine->mempool; #endif root->type = i; - if (cli_mtargets[i].ac_only || engine->ac_only) + if (cli_mtargets[i].ac_only || engine->ac_only) { root->ac_only = 1; + } if (CL_SUCCESS != (ret = cli_ac_init(root, engine->ac_mindepth, engine->ac_maxdepth, engine->dconf->other & OTHER_CONF_PREFILTERING))) { /* no need to free previously allocated memory here */ @@ -1019,8 +1037,9 @@ cl_error_t cli_initroots(struct cl_engine *engine, unsigned int options) char *cli_dbgets(char *buff, unsigned int size, FILE *fs, struct cli_dbio *dbio) { - if (fs) + if (fs) { return fgets(buff, size, fs); + } if (dbio->usebuf) { int bread; @@ -1028,8 +1047,9 @@ char *cli_dbgets(char *buff, unsigned int size, FILE *fs, struct cli_dbio *dbio) while (1) { if (!dbio->bufpt) { - if (!dbio->size) + if (!dbio->size) { return NULL; + } if (dbio->gzs) { bread = gzread(dbio->gzs, dbio->readpt, dbio->readsize); @@ -1044,14 +1064,16 @@ char *cli_dbgets(char *buff, unsigned int size, FILE *fs, struct cli_dbio *dbio) return NULL; } } - if (!bread) + if (!bread) { return NULL; + } dbio->readpt[bread] = 0; dbio->bufpt = dbio->buf; dbio->size -= bread; dbio->bread += bread; - if (dbio->hashctx) + if (dbio->hashctx) { cl_update_hash(dbio->hashctx, dbio->readpt, bread); + } } if (dbio->chkonly && dbio->bufpt) { dbio->bufpt = NULL; @@ -1092,14 +1114,16 @@ char *cli_dbgets(char *buff, unsigned int size, FILE *fs, struct cli_dbio *dbio) char *pt; unsigned int bs; - if (!dbio->size) + if (!dbio->size) { return NULL; + } bs = dbio->size < size ? dbio->size + 1 : size; - if (dbio->gzs) + if (dbio->gzs) { pt = gzgets(dbio->gzs, buff, bs); - else + } else { pt = fgets(buff, bs, dbio->fs); + } if (!pt) { cli_errmsg("cli_dbgets: Preliminary end of data\n"); @@ -1108,8 +1132,9 @@ char *cli_dbgets(char *buff, unsigned int size, FILE *fs, struct cli_dbio *dbio) bs = strlen(buff); dbio->size -= bs; dbio->bread += bs; - if (dbio->hashctx) + if (dbio->hashctx) { cl_update_hash(dbio->hashctx, buff, bs); + } return pt; } } @@ -1120,24 +1145,28 @@ static char *cli_signorm(const char *signame) size_t pad = 0; size_t nsz; - if (!signame) + if (!signame) { return NULL; + } nsz = strlen(signame); if (nsz > 3 && signame[nsz - 1] == '}') { char *pt = strstr(signame, ".{"); - if (pt) /* strip the ".{ }" clause at the end of signame */ + if (pt) { /* strip the ".{ }" clause at the end of signame */ nsz = pt - signame; - else + } else { return NULL; + } } else if (nsz > 11) { - if (!strncmp(signame + nsz - 11, ".UNOFFICIAL", 11)) + if (!strncmp(signame + nsz - 11, ".UNOFFICIAL", 11)) { nsz -= 11; - else + } else { return NULL; - } else if (nsz > 2) + } + } else if (nsz > 2) { return NULL; + } if (nsz < 3) { pad = 3 - nsz; @@ -1145,14 +1174,16 @@ static char *cli_signorm(const char *signame) } new_signame = calloc((nsz + 1), sizeof(char)); - if (!new_signame) + if (!new_signame) { return NULL; + } memcpy(new_signame, signame, nsz - pad); new_signame[nsz] = '\0'; - while (pad > 0) + while (pad > 0) { new_signame[nsz - pad--] = '\x20'; + } return new_signame; } @@ -1165,27 +1196,32 @@ static int cli_chkign(const struct cli_matcher *ignored, const char *signame, co unsigned char digest[16]; int ret = 0; - if (!ignored || !signame || !entry) + if (!ignored || !signame || !entry) { return 0; + } norm_signame = cli_signorm(signame); - if (norm_signame != NULL) + if (norm_signame != NULL) { signame = norm_signame; + } - if (cli_bm_scanbuff((const unsigned char *)signame, strlen(signame), &md5_expected, NULL, ignored, 0, NULL, NULL, NULL) == CL_VIRUS) + if (cli_bm_scanbuff((const unsigned char *)signame, strlen(signame), &md5_expected, NULL, ignored, 0, NULL, NULL, NULL) == CL_VIRUS) { do { if (md5_expected) { cl_hash_data("md5", entry, strlen(entry), digest, NULL); - if (memcmp(digest, (const unsigned char *)md5_expected, 16)) + if (memcmp(digest, (const unsigned char *)md5_expected, 16)) { break; + } } cli_dbgmsg("Ignoring signature %s\n", signame); ret = 1; } while (0); + } - if (norm_signame) + if (norm_signame) { free(norm_signame); + } return ret; } @@ -1231,13 +1267,15 @@ static int cli_chkpua(const char *signame, const char *pua_cats, unsigned int op cat_pt = strstr(cat, pua_cats); cli_dbgmsg("cli_chkpua: cat=[%s]\n", cat); cli_dbgmsg("cli_chkpua: sig=[%s]\n", sig); - if (options & CL_DB_PUA_INCLUDE) + if (options & CL_DB_PUA_INCLUDE) { ret = cat_pt ? 0 : 1; - else + } else { ret = cat_pt ? 1 : 0; + } - if (ret) + if (ret) { cli_dbgmsg("Skipping PUA signature %s - excluded category %s\n", signame, cat); + } return ret; } @@ -1250,24 +1288,28 @@ static cl_error_t cli_loaddb(FILE *fs, struct cl_engine *engine, unsigned int *s UNUSEDPARAM(dbname); - if (CL_SUCCESS != (ret = cli_initroots(engine, options))) + if (CL_SUCCESS != (ret = cli_initroots(engine, options))) { return ret; + } root = engine->root[0]; - if (engine->ignored) + if (engine->ignored) { if (!(buffer_cpy = malloc(FILEBUFF))) { cli_errmsg("cli_loaddb: Can't allocate memory for buffer_cpy\n"); return CL_EMEM; } + } while (cli_dbgets(buffer, FILEBUFF, fs, dbio)) { line++; - if (buffer[0] == '#') + if (buffer[0] == '#') { continue; + } cli_chomp(buffer); - if (engine->ignored) + if (engine->ignored) { strcpy(buffer_cpy, buffer); + } pt = strchr(buffer, '='); if (!pt) { @@ -1279,15 +1321,18 @@ static cl_error_t cli_loaddb(FILE *fs, struct cl_engine *engine, unsigned int *s start = buffer; *pt++ = 0; - if (engine->ignored && cli_chkign(engine->ignored, start, buffer_cpy)) + if (engine->ignored && cli_chkign(engine->ignored, start, buffer_cpy)) { continue; + } if (engine->cb_sigload && engine->cb_sigload("db", start, ~options & CL_DB_OFFICIAL, engine->cb_sigload_ctx)) { cli_dbgmsg("cli_loaddb: skipping %s due to callback\n", start); continue; } - if (*pt == '=') continue; + if (*pt == '=') { + continue; + } if (CL_SUCCESS != (ret = cli_add_content_match_pattern(root, start, pt, 0, 0, 0, "*", NULL, options))) { cli_dbgmsg("cli_loaddb: cli_add_content_match_pattern failed on line %d\n", line); @@ -1297,8 +1342,9 @@ static cl_error_t cli_loaddb(FILE *fs, struct cl_engine *engine, unsigned int *s sigs++; } - if (engine->ignored) + if (engine->ignored) { free(buffer_cpy); + } if (!line) { cli_errmsg("Empty database file\n"); @@ -1310,8 +1356,9 @@ static cl_error_t cli_loaddb(FILE *fs, struct cl_engine *engine, unsigned int *s return ret; } - if (signo) + if (signo) { *signo += sigs; + } return CL_SUCCESS; } @@ -1327,24 +1374,28 @@ static cl_error_t cli_loadidb(FILE *fs, struct cl_engine *engine, unsigned int * struct icomtr *metric = NULL; struct icon_matcher *matcher = NULL; - if (!(matcher = (struct icon_matcher *)MPOOL_CALLOC(engine->mempool, sizeof(*matcher), 1))) + if (!(matcher = (struct icon_matcher *)MPOOL_CALLOC(engine->mempool, sizeof(*matcher), 1))) { return CL_EMEM; + } - if (engine->ignored) + if (engine->ignored) { if (!(buffer_cpy = malloc(FILEBUFF))) { cli_errmsg("cli_loadidb: Can't allocate memory for buffer_cpy\n"); MPOOL_FREE(engine->mempool, matcher); return CL_EMEM; } + } while (cli_dbgets(buffer, FILEBUFF, fs, dbio)) { line++; - if (buffer[0] == '#') + if (buffer[0] == '#') { continue; + } cli_chomp(buffer); - if (engine->ignored) + if (engine->ignored) { strcpy(buffer_cpy, buffer); + } tokens_count = cli_strtokenize(buffer, ':', ICO_TOKENS + 1, tokens); if (tokens_count != ICO_TOKENS) { @@ -1359,8 +1410,9 @@ static cl_error_t cli_loadidb(FILE *fs, struct cl_engine *engine, unsigned int * break; } - if (engine->ignored && cli_chkign(engine->ignored, tokens[0], buffer_cpy)) + if (engine->ignored && cli_chkign(engine->ignored, tokens[0], buffer_cpy)) { continue; + } if (engine->cb_sigload && engine->cb_sigload("idb", tokens[0], ~options & CL_DB_OFFICIAL, engine->cb_sigload_ctx)) { cli_dbgmsg("cli_loadidb: skipping %s due to callback\n", tokens[0]); @@ -1393,12 +1445,15 @@ static cl_error_t cli_loadidb(FILE *fs, struct cl_engine *engine, unsigned int * matcher->icon_counts[enginesize]++; for (i = 0; i < 3; i++) { - if ((metric->color_avg[i] = (hash[0] << 8) | (hash[1] << 4) | hash[2]) > 4072) + if ((metric->color_avg[i] = (hash[0] << 8) | (hash[1] << 4) | hash[2]) > 4072) { break; - if ((metric->color_x[i] = (hash[3] << 4) | hash[4]) > size - size / 8) + } + if ((metric->color_x[i] = (hash[3] << 4) | hash[4]) > size - size / 8) { break; - if ((metric->color_y[i] = (hash[5] << 4) | hash[6]) > size - size / 8) + } + if ((metric->color_y[i] = (hash[5] << 4) | hash[6]) > size - size / 8) { break; + } hash += 7; } if (i != 3) { @@ -1408,12 +1463,15 @@ static cl_error_t cli_loadidb(FILE *fs, struct cl_engine *engine, unsigned int * } for (i = 0; i < 3; i++) { - if ((metric->gray_avg[i] = (hash[0] << 8) | (hash[1] << 4) | hash[2]) > 4072) + if ((metric->gray_avg[i] = (hash[0] << 8) | (hash[1] << 4) | hash[2]) > 4072) { break; - if ((metric->gray_x[i] = (hash[3] << 4) | hash[4]) > size - size / 8) + } + if ((metric->gray_x[i] = (hash[3] << 4) | hash[4]) > size - size / 8) { break; - if ((metric->gray_y[i] = (hash[5] << 4) | hash[6]) > size - size / 8) + } + if ((metric->gray_y[i] = (hash[5] << 4) | hash[6]) > size - size / 8) { break; + } hash += 7; } if (i != 3) { @@ -1424,10 +1482,12 @@ static cl_error_t cli_loadidb(FILE *fs, struct cl_engine *engine, unsigned int * for (i = 0; i < 3; i++) { metric->bright_avg[i] = (hash[0] << 4) | hash[1]; - if ((metric->bright_x[i] = (hash[2] << 4) | hash[3]) > size - size / 8) + if ((metric->bright_x[i] = (hash[2] << 4) | hash[3]) > size - size / 8) { break; - if ((metric->bright_y[i] = (hash[4] << 4) | hash[5]) > size - size / 8) + } + if ((metric->bright_y[i] = (hash[4] << 4) | hash[5]) > size - size / 8) { break; + } hash += 6; } if (i != 3) { @@ -1438,10 +1498,12 @@ static cl_error_t cli_loadidb(FILE *fs, struct cl_engine *engine, unsigned int * for (i = 0; i < 3; i++) { metric->dark_avg[i] = (hash[0] << 4) | hash[1]; - if ((metric->dark_x[i] = (hash[2] << 4) | hash[3]) > size - size / 8) + if ((metric->dark_x[i] = (hash[2] << 4) | hash[3]) > size - size / 8) { break; - if ((metric->dark_y[i] = (hash[4] << 4) | hash[5]) > size - size / 8) + } + if ((metric->dark_y[i] = (hash[4] << 4) | hash[5]) > size - size / 8) { break; + } hash += 6; } if (i != 3) { @@ -1452,10 +1514,12 @@ static cl_error_t cli_loadidb(FILE *fs, struct cl_engine *engine, unsigned int * for (i = 0; i < 3; i++) { metric->edge_avg[i] = (hash[0] << 4) | hash[1]; - if ((metric->edge_x[i] = (hash[2] << 4) | hash[3]) > size - size / 8) + if ((metric->edge_x[i] = (hash[2] << 4) | hash[3]) > size - size / 8) { break; - if ((metric->edge_y[i] = (hash[4] << 4) | hash[5]) > size - size / 8) + } + if ((metric->edge_y[i] = (hash[4] << 4) | hash[5]) > size - size / 8) { break; + } hash += 6; } if (i != 3) { @@ -1466,10 +1530,12 @@ static cl_error_t cli_loadidb(FILE *fs, struct cl_engine *engine, unsigned int * for (i = 0; i < 3; i++) { metric->noedge_avg[i] = (hash[0] << 4) | hash[1]; - if ((metric->noedge_x[i] = (hash[2] << 4) | hash[3]) > size - size / 8) + if ((metric->noedge_x[i] = (hash[2] << 4) | hash[3]) > size - size / 8) { break; - if ((metric->noedge_y[i] = (hash[4] << 4) | hash[5]) > size - size / 8) + } + if ((metric->noedge_y[i] = (hash[4] << 4) | hash[5]) > size - size / 8) { break; + } hash += 6; } if (i != 3) { @@ -1494,8 +1560,9 @@ static cl_error_t cli_loadidb(FILE *fs, struct cl_engine *engine, unsigned int * } for (i = 0; i < matcher->group_counts[0]; i++) { - if (!strcmp(tokens[1], matcher->group_names[0][i])) + if (!strcmp(tokens[1], matcher->group_names[0][i])) { break; + } } if (i == matcher->group_counts[0]) { if (!(matcher->group_names[0] = MPOOL_REALLOC(engine->mempool, matcher->group_names[0], sizeof(char *) * (i + 1))) || @@ -1508,8 +1575,9 @@ static cl_error_t cli_loadidb(FILE *fs, struct cl_engine *engine, unsigned int * metric->group[0] = i; for (i = 0; i < matcher->group_counts[1]; i++) { - if (!strcmp(tokens[2], matcher->group_names[1][i])) + if (!strcmp(tokens[2], matcher->group_names[1][i])) { break; + } } if (i == matcher->group_counts[1]) { if (!(matcher->group_names[1] = MPOOL_REALLOC(engine->mempool, matcher->group_names[1], sizeof(char *) * (i + 1))) || @@ -1529,8 +1597,9 @@ static cl_error_t cli_loadidb(FILE *fs, struct cl_engine *engine, unsigned int * sigs++; } - if (engine->ignored) + if (engine->ignored) { free(buffer_cpy); + } if (!line) { cli_errmsg("cli_loadidb: Empty database file\n"); @@ -1543,8 +1612,9 @@ static cl_error_t cli_loadidb(FILE *fs, struct cl_engine *engine, unsigned int * return ret; } - if (signo) + if (signo) { *signo += sigs; + } engine->iconcheck = matcher; return CL_SUCCESS; @@ -1554,8 +1624,9 @@ static int cli_loadwdb(FILE *fs, struct cl_engine *engine, unsigned int options, { int ret = 0; - if (!(engine->dconf->phishing & PHISHING_CONF_ENGINE)) + if (!(engine->dconf->phishing & PHISHING_CONF_ENGINE)) { return CL_SUCCESS; + } if (!engine->allow_list_matcher) { if (CL_SUCCESS != (ret = init_allow_list(engine))) { @@ -1574,8 +1645,9 @@ static int cli_loadpdb(FILE *fs, struct cl_engine *engine, unsigned int *signo, { int ret = 0; - if (!(engine->dconf->phishing & PHISHING_CONF_ENGINE)) + if (!(engine->dconf->phishing & PHISHING_CONF_ENGINE)) { return CL_SUCCESS; + } if (!engine->domain_list_matcher) { if (CL_SUCCESS != (ret = init_domain_list(engine))) { @@ -1603,27 +1675,33 @@ static int cli_loadndb(FILE *fs, struct cl_engine *engine, unsigned int *signo, UNUSEDPARAM(dbname); - if (CL_SUCCESS != (ret = cli_initroots(engine, options))) + if (CL_SUCCESS != (ret = cli_initroots(engine, options))) { return ret; + } - if (engine->ignored) + if (engine->ignored) { if (!(buffer_cpy = malloc(FILEBUFF))) { cli_errmsg("cli_loadndb: Can't allocate memory for buffer_cpy\n"); return CL_EMEM; } + } while (cli_dbgets(buffer, FILEBUFF, fs, dbio)) { line++; - if (buffer[0] == '#') + if (buffer[0] == '#') { continue; + } - if (!phish) - if (!strncmp(buffer, "HTML.Phishing", 13) || !strncmp(buffer, "Email.Phishing", 14)) + if (!phish) { + if (!strncmp(buffer, "HTML.Phishing", 13) || !strncmp(buffer, "Email.Phishing", 14)) { continue; + } + } cli_chomp(buffer); - if (engine->ignored) + if (engine->ignored) { strcpy(buffer_cpy, buffer); + } tokens_count = cli_strtokenize(buffer, ':', NDB_TOKENS + 1, tokens); if (tokens_count < 4 || tokens_count > 6) { @@ -1633,12 +1711,15 @@ static int cli_loadndb(FILE *fs, struct cl_engine *engine, unsigned int *signo, virname = tokens[0]; - if (engine->pua_cats && (options & CL_DB_PUA_MODE) && (options & (CL_DB_PUA_INCLUDE | CL_DB_PUA_EXCLUDE))) - if (cli_chkpua(virname, engine->pua_cats, options)) + if (engine->pua_cats && (options & CL_DB_PUA_MODE) && (options & (CL_DB_PUA_INCLUDE | CL_DB_PUA_EXCLUDE))) { + if (cli_chkpua(virname, engine->pua_cats, options)) { continue; + } + } - if (engine->ignored && cli_chkign(engine->ignored, virname, buffer_cpy)) + if (engine->ignored && cli_chkign(engine->ignored, virname, buffer_cpy)) { continue; + } if (!sdb && engine->cb_sigload && engine->cb_sigload("ndb", virname, ~options & CL_DB_OFFICIAL, engine->cb_sigload_ctx)) { cli_dbgmsg("cli_loadndb: skipping %s due to callback\n", virname); @@ -1698,8 +1779,9 @@ static int cli_loadndb(FILE *fs, struct cl_engine *engine, unsigned int *signo, (void)engine->cb_sigload_progress(engine->num_total_signatures, *signo + sigs, engine->cb_sigload_progress_ctx); } } - if (engine->ignored) + if (engine->ignored) { free(buffer_cpy); + } if (!line) { cli_errmsg("Empty database file\n"); @@ -1711,8 +1793,9 @@ static int cli_loadndb(FILE *fs, struct cl_engine *engine, unsigned int *signo, return ret; } - if (signo) + if (signo) { *signo += sigs; + } if (sdb && sigs && !engine->sdb) { engine->sdb = 1; @@ -1939,8 +2022,9 @@ static int lsigattribs(char *attribs, struct cli_lsig_tdb *tdb) } } - if (!apt) + if (!apt) { continue; + } switch (apt->type) { case CLI_TDB_UINT: @@ -2085,8 +2169,9 @@ static cl_error_t load_oneldb(char *buffer, int chkpua, struct cl_engine *engine } if (engine->ignored && cli_chkign(engine->ignored, virname, buffer_cpy ? buffer_cpy : virname)) { - if (skip) + if (skip) { *skip = 1; + } cli_dbgmsg("cli_loadldb: Skipping ignored signature %s\n", virname); status = CL_BREAK; goto done; @@ -2238,8 +2323,9 @@ static int cli_loadldb(FILE *fs, struct cl_engine *engine, unsigned int *signo, unsigned int line = 0, sigs = 0; int ret; - if (CL_SUCCESS != (ret = cli_initroots(engine, options))) + if (CL_SUCCESS != (ret = cli_initroots(engine, options))) { return ret; + } if (engine->ignored) { if (!(buffer_cpy = malloc(sizeof(buffer)))) { @@ -2250,19 +2336,22 @@ static int cli_loadldb(FILE *fs, struct cl_engine *engine, unsigned int *signo, while (cli_dbgets(buffer, sizeof(buffer), fs, dbio)) { line++; - if (buffer[0] == '#') + if (buffer[0] == '#') { continue; + } cli_chomp(buffer); - if (engine->ignored) + if (engine->ignored) { strcpy(buffer_cpy, buffer); + } ret = load_oneldb(buffer, engine->pua_cats && (options & CL_DB_PUA_MODE) && (options & (CL_DB_PUA_INCLUDE | CL_DB_PUA_EXCLUDE)), engine, options, dbname, line, &sigs, 0, buffer_cpy, NULL); - if (ret) + if (ret) { break; + } if (engine->cb_sigload_progress && ((*signo + sigs) % 10000 == 0)) { /* Let the progress callback function know how we're doing */ @@ -2270,8 +2359,9 @@ static int cli_loadldb(FILE *fs, struct cl_engine *engine, unsigned int *signo, } } - if (engine->ignored) + if (engine->ignored) { free(buffer_cpy); + } if (!line) { cli_errmsg("Empty database file\n"); @@ -2283,8 +2373,9 @@ static int cli_loadldb(FILE *fs, struct cl_engine *engine, unsigned int *signo, return ret; } - if (signo) + if (signo) { *signo += sigs; + } return CL_SUCCESS; } @@ -2300,8 +2391,9 @@ static int cli_loadcbc(FILE *fs, struct cl_engine *engine, unsigned int *signo, unsigned i; /* TODO: virusname have a common prefix, and allow by that */ - if ((rc = cli_initroots(engine, options))) + if ((rc = cli_initroots(engine, options))) { return rc; + } if (!(engine->dconf->bytecode & BYTECODE_ENGINE_MASK)) { return CL_SUCCESS; @@ -2351,8 +2443,9 @@ static int cli_loadcbc(FILE *fs, struct cl_engine *engine, unsigned int *signo, return CL_SUCCESS; } bc->id = bcs->count; /* must set after _load, since load zeroes */ - if (engine->bytecode_mode == CL_BYTECODE_MODE_TEST) + if (engine->bytecode_mode == CL_BYTECODE_MODE_TEST) { cli_infomsg(NULL, "bytecode %u -> %s\n", bc->id, dbname); + } if (bc->kind == BC_LOGICAL || bc->lsig) { unsigned oldsigs = sigs; if (!bc->lsig) { @@ -2396,10 +2489,10 @@ static int cli_loadcbc(FILE *fs, struct cl_engine *engine, unsigned int *signo, return CL_EMEM; } engine->hooks[hook][cnt - 1] = bcs->count - 1; - } else + } else { switch (bc->kind) { case BC_STARTUP: - for (i = 0; i < bcs->count - 1; i++) + for (i = 0; i < bcs->count - 1; i++) { if (bcs->all_bcs[i].kind == BC_STARTUP) { struct cli_bc *bc0 = &bcs->all_bcs[i]; cli_errmsg("Can only load 1 BC_STARTUP bytecode, attempted to load 2nd!\n"); @@ -2411,14 +2504,17 @@ static int cli_loadcbc(FILE *fs, struct cl_engine *engine, unsigned int *signo, bc->metadata.sigmaker ? bc->metadata.sigmaker : "N/A"); return CL_EMALFDB; } + } break; default: cli_errmsg("Bytecode: unhandled bytecode kind %u\n", bc->kind); return CL_EMALFDB; } + } } - if (signo) + if (signo) { *signo += sigs; + } return CL_SUCCESS; } @@ -2436,21 +2532,25 @@ static int cli_loadftm(FILE *fs, struct cl_engine *engine, unsigned int options, int ret; int magictype; - if (CL_SUCCESS != (ret = cli_initroots(engine, options))) + if (CL_SUCCESS != (ret = cli_initroots(engine, options))) { return ret; + } while (1) { if (internal) { options |= CL_DB_OFFICIAL; - if (!ftypes_int[line]) + if (!ftypes_int[line]) { break; + } strncpy(buffer, ftypes_int[line], sizeof(buffer)); buffer[sizeof(buffer) - 1] = '\0'; } else { - if (!cli_dbgets(buffer, FILEBUFF, fs, dbio)) + if (!cli_dbgets(buffer, FILEBUFF, fs, dbio)) { break; - if (buffer[0] == '#') + } + if (buffer[0] == '#') { continue; + } cli_chomp(buffer); } line++; @@ -2477,8 +2577,9 @@ static int cli_loadftm(FILE *fs, struct cl_engine *engine, unsigned int options, ret = CL_EMALFDB; break; } - if ((unsigned int)atoi(pt) < cl_retflevel()) + if ((unsigned int)atoi(pt) < cl_retflevel()) { continue; + } } } @@ -2497,8 +2598,9 @@ static int cli_loadftm(FILE *fs, struct cl_engine *engine, unsigned int options, magictype = atoi(tokens[0]); if (magictype == 1) { /* A-C */ - if (CL_SUCCESS != (ret = cli_add_content_match_pattern(engine->root[0], tokens[3], tokens[2], 0, rtype, type, tokens[1], NULL, options))) + if (CL_SUCCESS != (ret = cli_add_content_match_pattern(engine->root[0], tokens[3], tokens[2], 0, rtype, type, tokens[1], NULL, options))) { break; + } } else if ((magictype == 0) || (magictype == 4)) { /* memcmp() */ if (!cli_isnumber(tokens[1])) { @@ -2576,8 +2678,9 @@ static int cli_loadinfo(FILE *fs, struct cl_engine *engine, unsigned int options } ctx = cl_hash_init("sha256"); - if (!(ctx)) + if (!(ctx)) { return CL_EMALFDB; + } while (cli_dbgets(buffer, FILEBUFF, fs, dbio)) { line++; @@ -2691,8 +2794,9 @@ static int cli_loadign(FILE *fs, struct cl_engine *engine, unsigned int options, if (!engine->ignored) { engine->ignored = (struct cli_matcher *)MPOOL_CALLOC(engine->mempool, 1, sizeof(struct cli_matcher)); - if (!engine->ignored) + if (!engine->ignored) { return CL_EMEM; + } #ifdef USE_MPOOL engine->ignored->mempool = engine->mempool; #endif @@ -2704,8 +2808,9 @@ static int cli_loadign(FILE *fs, struct cl_engine *engine, unsigned int options, while (cli_dbgets(buffer, FILEBUFF, fs, dbio)) { line++; - if (buffer[0] == '#') + if (buffer[0] == '#') { continue; + } cli_chomp(buffer); tokens_count = cli_strtokenize(buffer, ':', IGN_MAX_TOKENS + 1, tokens); @@ -2735,8 +2840,9 @@ static int cli_loadign(FILE *fs, struct cl_engine *engine, unsigned int options, signame = buffer; } buffer[3] = '\0'; - while (pad > 0) + while (pad > 0) { buffer[3 - pad--] = '\x20'; + } len = 3; } @@ -2764,8 +2870,9 @@ static int cli_loadign(FILE *fs, struct cl_engine *engine, unsigned int options, new->boundary |= BM_BOUNDARY_EOL; if (CL_SUCCESS != (ret = cli_bm_addpatt(engine->ignored, new, "0"))) { - if (hash) + if (hash) { MPOOL_FREE(engine->mempool, new->virname); + } MPOOL_FREE(engine->mempool, new->pattern); MPOOL_FREE(engine->mempool, new); break; @@ -2801,42 +2908,48 @@ static int cli_loadhash(FILE *fs, struct cl_engine *engine, unsigned int *signo, size_field = 0; md5_field = 1; db = engine->hm_mdb; - } else if (mode == MD5_HDB) + } else if (mode == MD5_HDB) { db = engine->hm_hdb; - else if (mode == MD5_IMP) + } else if (mode == MD5_IMP) { db = engine->hm_imp; - else + } else { db = engine->hm_fp; + } if (!db) { - if (!(db = MPOOL_CALLOC(engine->mempool, 1, sizeof(*db)))) + if (!(db = MPOOL_CALLOC(engine->mempool, 1, sizeof(*db)))) { return CL_EMEM; + } #ifdef USE_MPOOL db->mempool = engine->mempool; #endif - if (mode == MD5_HDB) + if (mode == MD5_HDB) { engine->hm_hdb = db; - else if (mode == MD5_MDB) + } else if (mode == MD5_MDB) { engine->hm_mdb = db; - else if (mode == MD5_IMP) + } else if (mode == MD5_IMP) { engine->hm_imp = db; - else + } else { engine->hm_fp = db; + } } - if (engine->ignored) + if (engine->ignored) { if (!(buffer_cpy = malloc(FILEBUFF))) { cli_errmsg("cli_loadhash: Can't allocate memory for buffer_cpy\n"); return CL_EMEM; } + } while (cli_dbgets(buffer, FILEBUFF, fs, dbio)) { line++; - if (buffer[0] == '#') + if (buffer[0] == '#') { continue; + } cli_chomp(buffer); - if (engine->ignored) + if (engine->ignored) { strcpy(buffer_cpy, buffer); + } tokens_count = cli_strtokenize(buffer, ':', MD5_TOKENS + 1, tokens); if (tokens_count < 3) { @@ -2851,12 +2964,14 @@ static int cli_loadhash(FILE *fs, struct cl_engine *engine, unsigned int *signo, break; } - if (cl_retflevel() < req_fl) + if (cl_retflevel() < req_fl) { continue; + } if (tokens_count == MD5_TOKENS) { int max_fl = atoi(tokens[MD5_TOKENS - 1]); - if (cl_retflevel() > (unsigned int)max_fl) + if (cl_retflevel() > (unsigned int)max_fl) { continue; + } } } @@ -2884,19 +2999,23 @@ static int cli_loadhash(FILE *fs, struct cl_engine *engine, unsigned int *signo, } pt = tokens[2]; /* virname */ - if (engine->pua_cats && (options & CL_DB_PUA_MODE) && (options & (CL_DB_PUA_INCLUDE | CL_DB_PUA_EXCLUDE))) - if (cli_chkpua(pt, engine->pua_cats, options)) + if (engine->pua_cats && (options & CL_DB_PUA_MODE) && (options & (CL_DB_PUA_INCLUDE | CL_DB_PUA_EXCLUDE))) { + if (cli_chkpua(pt, engine->pua_cats, options)) { continue; + } + } - if (engine->ignored && cli_chkign(engine->ignored, pt, buffer_cpy)) + if (engine->ignored && cli_chkign(engine->ignored, pt, buffer_cpy)) { continue; + } if (engine->cb_sigload) { const char *dot = strchr(dbname, '.'); - if (!dot) + if (!dot) { dot = dbname; - else + } else { dot++; + } if (engine->cb_sigload(dot, pt, ~options & CL_DB_OFFICIAL, engine->cb_sigload_ctx)) { cli_dbgmsg("cli_loadhash: skipping %s (%s) due to callback\n", pt, dot); continue; @@ -2922,8 +3041,9 @@ static int cli_loadhash(FILE *fs, struct cl_engine *engine, unsigned int *signo, (void)engine->cb_sigload_progress(engine->num_total_signatures, *signo + sigs, engine->cb_sigload_progress_ctx); } } - if (engine->ignored) + if (engine->ignored) { free(buffer_cpy); + } if (!line) { cli_errmsg("cli_loadhash: Empty database file\n"); @@ -2935,8 +3055,9 @@ static int cli_loadhash(FILE *fs, struct cl_engine *engine, unsigned int *signo, return ret; } - if (signo) + if (signo) { *signo += sigs; + } return CL_SUCCESS; } @@ -2952,20 +3073,23 @@ static int cli_loadmd(FILE *fs, struct cl_engine *engine, unsigned int *signo, i UNUSEDPARAM(dbname); - if (engine->ignored) + if (engine->ignored) { if (!(buffer_cpy = malloc(FILEBUFF))) { cli_errmsg("cli_loadmd: Can't allocate memory for buffer_cpy\n"); return CL_EMEM; } + } while (cli_dbgets(buffer, FILEBUFF, fs, dbio)) { line++; - if (buffer[0] == '#') + if (buffer[0] == '#') { continue; + } cli_chomp(buffer); - if (engine->ignored) + if (engine->ignored) { strcpy(buffer_cpy, buffer); + } tokens_count = cli_strtokenize(buffer, ':', MD_TOKENS + 1, tokens); if (tokens_count != MD_TOKENS) { @@ -3042,23 +3166,26 @@ static int cli_loadmd(FILE *fs, struct cl_engine *engine, unsigned int *signo, i } new->csize[0] = new->csize[1] = CLI_OFF_ANY; - if (!strcmp(tokens[3], "*")) + if (!strcmp(tokens[3], "*")) { new->fsizer[0] = new->fsizer[1] = CLI_OFF_ANY; - else + } else { new->fsizer[0] = new->fsizer[1] = atoi(tokens[3]); + } - if (!strcmp(tokens[4], "*")) + if (!strcmp(tokens[4], "*")) { new->fsizec[0] = new->fsizec[1] = CLI_OFF_ANY; - else + } else { new->fsizec[0] = new->fsizec[1] = atoi(tokens[4]); + } if (strcmp(tokens[5], "*")) { new->res1 = cli_hex2num(tokens[5]); if (new->res1 == -1) { MPOOL_FREE(engine->mempool, new->virname); MPOOL_FREE(engine->mempool, new); - if (new->name.re_magic) + if (new->name.re_magic) { cli_regfree(&new->name); + } ret = CL_EMALFDB; break; } @@ -3074,8 +3201,9 @@ static int cli_loadmd(FILE *fs, struct cl_engine *engine, unsigned int *signo, i engine->cdb = new; sigs++; } - if (engine->ignored) + if (engine->ignored) { free(buffer_cpy); + } if (!line) { cli_errmsg("Empty database file\n"); @@ -3087,8 +3215,9 @@ static int cli_loadmd(FILE *fs, struct cl_engine *engine, unsigned int *signo, i return ret; } - if (signo) + if (signo) { *signo += sigs; + } return CL_SUCCESS; } @@ -3106,20 +3235,23 @@ static int cli_loadcdb(FILE *fs, struct cl_engine *engine, unsigned int *signo, int ret = CL_SUCCESS; struct cli_cdb *new; - if (engine->ignored) + if (engine->ignored) { if (!(buffer_cpy = malloc(FILEBUFF))) { cli_errmsg("cli_loadcdb: Can't allocate memory for buffer_cpy\n"); return CL_EMEM; } + } while (cli_dbgets(buffer, FILEBUFF, fs, dbio)) { line++; - if (buffer[0] == '#') + if (buffer[0] == '#') { continue; + } cli_chomp(buffer); - if (engine->ignored) + if (engine->ignored) { strcpy(buffer_cpy, buffer); + } tokens_count = cli_strtokenize(buffer, ':', CDB_TOKENS + 1, tokens); if (tokens_count > CDB_TOKENS || tokens_count < CDB_TOKENS - 2) { @@ -3141,8 +3273,9 @@ static int cli_loadcdb(FILE *fs, struct cl_engine *engine, unsigned int *signo, ret = CL_EMALFDB; break; } - if ((unsigned int)atoi(tokens[11]) < cl_retflevel()) + if ((unsigned int)atoi(tokens[11]) < cl_retflevel()) { continue; + } } } @@ -3229,8 +3362,9 @@ static int cli_loadcdb(FILE *fs, struct cl_engine *engine, unsigned int *signo, } else { if (strcmp(tokens[6], "0") && strcmp(tokens[6], "1")) { cli_errmsg("cli_loadcdb: Invalid encryption flag value in signature for %s\n", tokens[0]); - if (new->name.re_magic) + if (new->name.re_magic) { cli_regfree(&new->name); + } MPOOL_FREE(engine->mempool, new->virname); MPOOL_FREE(engine->mempool, new); ret = CL_EMEM; @@ -3243,8 +3377,9 @@ static int cli_loadcdb(FILE *fs, struct cl_engine *engine, unsigned int *signo, new->res2 = CLI_MPOOL_STRDUP(engine->mempool, tokens[9]); if (!new->res2) { cli_errmsg("cli_loadcdb: Can't allocate memory for res2 in signature for %s\n", tokens[0]); - if (new->name.re_magic) + if (new->name.re_magic) { cli_regfree(&new->name); + } MPOOL_FREE(engine->mempool, new->virname); MPOOL_FREE(engine->mempool, new); ret = CL_EMEM; @@ -3256,8 +3391,9 @@ static int cli_loadcdb(FILE *fs, struct cl_engine *engine, unsigned int *signo, engine->cdb = new; sigs++; } - if (engine->ignored) + if (engine->ignored) { free(buffer_cpy); + } if (!line) { cli_errmsg("Empty database file\n"); @@ -3269,8 +3405,9 @@ static int cli_loadcdb(FILE *fs, struct cl_engine *engine, unsigned int *signo, return ret; } - if (signo) + if (signo) { *signo += sigs; + } return CL_SUCCESS; } @@ -3335,12 +3472,14 @@ static int cli_loadcrt(FILE *fs, struct cl_engine *engine, struct cli_dbio *dbio while (cli_dbgets(buffer, FILEBUFF, fs, dbio)) { line++; - if (buffer[0] == '#') + if (buffer[0] == '#') { continue; + } cli_chomp(buffer); - if (!strlen(buffer)) + if (!strlen(buffer)) { continue; + } tokens_count = cli_strtokenize(buffer, ';', CRT_TOKENS + 1, (const char **)tokens); if (tokens_count > CRT_TOKENS || tokens_count < CRT_TOKENS - 2) { @@ -3457,13 +3596,15 @@ static int cli_loadcrt(FILE *fs, struct cl_engine *engine, struct cli_dbio *dbio goto done; } - if (strlen(tokens[0])) + if (strlen(tokens[0])) { ca.name = tokens[0]; - else + } else { ca.name = NULL; + } - if (strlen(tokens[9])) + if (strlen(tokens[9])) { ca.not_before = atoi(tokens[9]); + } ca.not_after = (-1ULL) >> 1; ca.hashtype = CLI_HASHTYPE_ANY; @@ -3513,8 +3654,9 @@ static int cli_loadopenioc(FILE *fs, const char *dbname, struct cl_engine *engin { int rc; rc = openioc_parse(dbname, fileno(fs), engine, options); - if (rc != CL_SUCCESS) + if (rc != CL_SUCCESS) { return CL_EMALFDB; + } return rc; } @@ -3536,19 +3678,25 @@ static char *parse_yara_hex_string(YR_STRING *string, int *ret) size_t slen, reslen = 0, i, j; if (!(string) || !(string->string)) { - if (ret) *ret = CL_ENULLARG; + if (ret) { + *ret = CL_ENULLARG; + } return NULL; } if (!STRING_IS_HEX(string)) { - if (ret) *ret = CL_EARG; + if (ret) { + *ret = CL_EARG; + } return NULL; } str = (char *)(string->string); if ((slen = string->length) == 0) { - if (ret) *ret = CL_EARG; + if (ret) { + *ret = CL_EARG; + } return NULL; } @@ -3571,7 +3719,9 @@ static char *parse_yara_hex_string(YR_STRING *string, int *ret) reslen++; res = calloc(reslen, 1); if (!(res)) { - if (ret) *ret = CL_EMEM; + if (ret) { + *ret = CL_EMEM; + } return NULL; } @@ -3638,14 +3788,16 @@ static char *parse_yara_hex_string(YR_STRING *string, int *ret) ((ovr = strrchr(res, '}')) && ((res + j - ovr) == 3))) { cli_errmsg("parse_yara_hex_string: Single byte subpatterns unsupported in ClamAV\n"); free(res); - if (ret != NULL) + if (ret != NULL) { *ret = CL_EMALFDB; + } return NULL; } #endif - if (ret) + if (ret) { *ret = CL_SUCCESS; + } return res; } @@ -3671,13 +3823,15 @@ static cl_error_t ytable_add_attrib(struct cli_ytable *ytable, const char *hexsi { int32_t lookup; - if (!ytable || !value) + if (!ytable || !value) { return CL_ENULLARG; + } - if (!hexsig) + if (!hexsig) { lookup = ytable->tbl_cnt - 1; /* assuming to attach to current string */ - else + } else { lookup = ytable_lookup(hexsig); + } if (lookup < 0) { cli_yaramsg("ytable_add_attrib: hexsig cannot be found\n"); @@ -3705,8 +3859,9 @@ static cl_error_t ytable_add_attrib(struct cli_ytable *ytable, const char *hexsi } } else { /* overwrite the previous offset */ - if (ytable->table[lookup]->offset) + if (ytable->table[lookup]->offset) { free(ytable->table[lookup]->offset); + } ytable->table[lookup]->offset = cli_safer_strdup(value); @@ -3726,8 +3881,9 @@ static int ytable_add_string(struct cli_ytable *ytable, const char *hexsig) struct cli_ytable_entry **newtable; int ret; - if (!ytable || !hexsig) + if (!ytable || !hexsig) { return CL_ENULLARG; + } new = calloc(1, sizeof(struct cli_ytable_entry)); if (!new) { @@ -3769,8 +3925,9 @@ static int ytable_add_string(struct cli_ytable *ytable, const char *hexsig) static void ytable_delete(struct cli_ytable *ytable) { int32_t i; - if (!ytable) + if (!ytable) { return; + } if (ytable->table) { for (i = 0; i < ytable->tbl_cnt; ++i) { @@ -3842,8 +3999,9 @@ static int load_oneyara(YR_RULE *rule, int chkpua, struct cl_engine *engine, uns } /* PUA and IGN checks */ - if (chkpua && cli_chkpua(rule->identifier, engine->pua_cats, options)) + if (chkpua && cli_chkpua(rule->identifier, engine->pua_cats, options)) { return CL_SUCCESS; + } if (engine->ignored && cli_chkign(engine->ignored, rule->identifier, rule->identifier)) { return CL_SUCCESS; @@ -4214,8 +4372,9 @@ static int load_oneyara(YR_RULE *rule, int chkpua, struct cl_engine *engine, uns free(target_str); free(newident); (*sigs)--; - if (ret == CL_BREAK) + if (ret == CL_BREAK) { return CL_SUCCESS; + } return ret; } free(target_str); @@ -4250,8 +4409,9 @@ static int load_oneyara(YR_RULE *rule, int chkpua, struct cl_engine *engine, uns } else { if (NULL != (lsig->u.code_start = rule->code_start)) { lsig->type = (rule->cl_flags & RULE_OFFSETS) ? CLI_YARA_OFFSET : CLI_YARA_NORMAL; - if (RULE_IS_PRIVATE(rule)) + if (RULE_IS_PRIVATE(rule)) { lsig->flag |= CLI_LSIG_FLAG_PRIVATE; + } } else { cli_errmsg("load_oneyara: code start is NULL\n"); FREE_TDB(tdb); @@ -4415,8 +4575,9 @@ static int cli_loadyara(FILE *fs, struct cl_engine *engine, unsigned int *signo, UNUSEDPARAM(dbio); - if ((rc = cli_initroots(engine, options))) + if ((rc = cli_initroots(engine, options))) { return rc; + } memset(&compiler, 0, sizeof(YR_COMPILER)); @@ -4425,16 +4586,21 @@ static int cli_loadyara(FILE *fs, struct cl_engine *engine, unsigned int *signo, STAILQ_INIT(&compiler.current_rule_string_q); rc = yr_arena_create(65536, 0, &compiler.sz_arena); - if (rc == ERROR_SUCCESS) + if (rc == ERROR_SUCCESS) { rc = yr_arena_create(65536, 0, &compiler.rules_arena); - if (rc == ERROR_SUCCESS) + } + if (rc == ERROR_SUCCESS) { rc = yr_arena_create(65536, 0, &compiler.code_arena); - if (rc == ERROR_SUCCESS) + } + if (rc == ERROR_SUCCESS) { rc = yr_arena_create(65536, 0, &compiler.strings_arena); - if (rc == ERROR_SUCCESS) + } + if (rc == ERROR_SUCCESS) { rc = yr_arena_create(65536, 0, &compiler.metas_arena); - if (rc != ERROR_SUCCESS) + } + if (rc != ERROR_SUCCESS) { return CL_EMEM; + } compiler.loop_for_of_mem_offset = -1; ns.name = "default"; compiler.current_namespace = &ns; @@ -4462,8 +4628,9 @@ static int cli_loadyara(FILE *fs, struct cl_engine *engine, unsigned int *signo, _yr_compiler_pop_file_name(&compiler); return CL_EMALFDB; #else - if (compiler.last_result == ERROR_INSUFICIENT_MEMORY) + if (compiler.last_result == ERROR_INSUFICIENT_MEMORY) { return CL_EMEM; + } rule_errors = rc; rc = CL_SUCCESS; #endif @@ -4485,8 +4652,9 @@ static int cli_loadyara(FILE *fs, struct cl_engine *engine, unsigned int *signo, } } - if (0 != rule_errors) + if (0 != rule_errors) { cli_warnmsg("cli_loadyara: failed to parse or load %u yara rules from file %s, successfully loaded %u rules.\n", rule_errors + rules - sigs, filename, sigs); + } yr_arena_append(engine->yara_global->the_arena, compiler.sz_arena); yr_arena_append(engine->yara_global->the_arena, compiler.rules_arena); @@ -4495,8 +4663,9 @@ static int cli_loadyara(FILE *fs, struct cl_engine *engine, unsigned int *signo, yr_arena_destroy(compiler.metas_arena); _yr_compiler_pop_file_name(&compiler); - if (rc) + if (rc) { return rc; + } #ifdef YARA_FINISHED if (!rules) { @@ -4513,8 +4682,9 @@ static int cli_loadyara(FILE *fs, struct cl_engine *engine, unsigned int *signo, /* globals */ yara_total += rules; - if (signo) + if (signo) { *signo += sigs; + } cli_yaramsg("cli_loadyara: loaded %u of %u yara signatures from %s\n", sigs, rules, filename); @@ -4543,10 +4713,12 @@ static int cli_loadpwdb(FILE *fs, struct cl_engine *engine, unsigned int options /* TODO - read default passwords */ return CL_SUCCESS; } else { - if (!cli_dbgets(buffer, FILEBUFF, fs, dbio)) + if (!cli_dbgets(buffer, FILEBUFF, fs, dbio)) { break; - if (buffer[0] == '#') + } + if (buffer[0] == '#') { continue; + } cli_chomp(buffer); } line++; @@ -4596,10 +4768,11 @@ static int cli_loadpwdb(FILE *fs, struct cl_engine *engine, unsigned int options free(attribs); if (ret != CL_SUCCESS) { skip++; - if (ret == CL_BREAK) + if (ret == CL_BREAK) { continue; - else + } else { break; + } } /* check container type */ @@ -4655,10 +4828,11 @@ static int cli_loadpwdb(FILE *fs, struct cl_engine *engine, unsigned int options } if (!new->passwd) { cli_errmsg("cli_loadpwdb: Can't decode or add new password entry\n"); - if (pwstype == 0) + if (pwstype == 0) { ret = CL_EMEM; - else + } else { ret = CL_EMALFDB; + } MPOOL_FREE(engine->mempool, new->name); MPOOL_FREE(engine->mempool, new); break; @@ -4702,7 +4876,9 @@ cl_error_t cli_load(const char *filename, struct cl_engine *engine, unsigned int char buff[FILEBUFF]; if (dbio && dbio->chkonly) { - while (cli_dbgets(buff, FILEBUFF, NULL, dbio)) continue; + while (cli_dbgets(buff, FILEBUFF, NULL, dbio)) { + continue; + } return CL_SUCCESS; } @@ -4719,17 +4895,19 @@ cl_error_t cli_load(const char *filename, struct cl_engine *engine, unsigned int return CL_EOPEN; } - if ((dbname = strrchr(filename, *PATHSEP))) + if ((dbname = strrchr(filename, *PATHSEP))) { dbname++; - else + } else { dbname = filename; + } #ifdef HAVE_YARA if (options & CL_DB_YARA_ONLY) { - if (cli_strbcasestr(dbname, ".yar") || cli_strbcasestr(dbname, ".yara")) + if (cli_strbcasestr(dbname, ".yar") || cli_strbcasestr(dbname, ".yara")) { ret = cli_loadyara(fs, engine, signo, options, dbio, filename); - else + } else { skipped = 1; + } } else #endif if (cli_strbcasestr(dbname, ".db")) { @@ -4750,10 +4928,11 @@ cl_error_t cli_load(const char *filename, struct cl_engine *engine, unsigned int } else if (cli_strbcasestr(dbname, ".hdb") || cli_strbcasestr(dbname, ".hsb")) { ret = cli_loadhash(fs, engine, signo, MD5_HDB, options, dbio, dbname); } else if (cli_strbcasestr(dbname, ".hdu") || cli_strbcasestr(dbname, ".hsu")) { - if (options & CL_DB_PUA) + if (options & CL_DB_PUA) { ret = cli_loadhash(fs, engine, signo, MD5_HDB, options | CL_DB_PUA_MODE, dbio, dbname); - else + } else { skipped = 1; + } } else if (cli_strbcasestr(dbname, ".fp") || cli_strbcasestr(dbname, ".sfp")) { ret = cli_loadhash(fs, engine, signo, MD5_FP, options, dbio, dbname); @@ -4763,33 +4942,37 @@ cl_error_t cli_load(const char *filename, struct cl_engine *engine, unsigned int ret = cli_loadhash(fs, engine, signo, MD5_IMP, options, dbio, dbname); } else if (cli_strbcasestr(dbname, ".mdu") || cli_strbcasestr(dbname, ".msu")) { - if (options & CL_DB_PUA) + if (options & CL_DB_PUA) { ret = cli_loadhash(fs, engine, signo, MD5_MDB, options | CL_DB_PUA_MODE, dbio, dbname); - else + } else { skipped = 1; + } } else if (cli_strbcasestr(dbname, ".ndb")) { ret = cli_loadndb(fs, engine, signo, 0, options, dbio, dbname); } else if (cli_strbcasestr(dbname, ".ndu")) { - if (!(options & CL_DB_PUA)) + if (!(options & CL_DB_PUA)) { skipped = 1; - else + } else { ret = cli_loadndb(fs, engine, signo, 0, options | CL_DB_PUA_MODE, dbio, dbname); + } } else if (cli_strbcasestr(filename, ".ldb")) { ret = cli_loadldb(fs, engine, signo, options, dbio, dbname); } else if (cli_strbcasestr(filename, ".ldu")) { - if (options & CL_DB_PUA) + if (options & CL_DB_PUA) { ret = cli_loadldb(fs, engine, signo, options | CL_DB_PUA_MODE, dbio, dbname); - else + } else { skipped = 1; + } } else if (cli_strbcasestr(filename, ".cbc")) { - if (options & CL_DB_BYTECODE) + if (options & CL_DB_BYTECODE) { ret = cli_loadcbc(fs, engine, signo, options, dbio, dbname); - else + } else { skipped = 1; + } } else if (cli_strbcasestr(dbname, ".sdb")) { ret = cli_loadndb(fs, engine, signo, 1, options, dbio, dbname); @@ -4808,13 +4991,15 @@ cl_error_t cli_load(const char *filename, struct cl_engine *engine, unsigned int } else if (cli_strbcasestr(dbname, ".wdb")) { if (options & CL_DB_PHISHING_URLS) { ret = cli_loadwdb(fs, engine, options, dbio); - } else + } else { skipped = 1; + } } else if (cli_strbcasestr(dbname, ".pdb") || cli_strbcasestr(dbname, ".gdb")) { if (options & CL_DB_PHISHING_URLS) { ret = cli_loadpdb(fs, engine, signo, options, dbio); - } else + } else { skipped = 1; + } } else if (cli_strbcasestr(dbname, ".ftm")) { ret = cli_loadftm(fs, engine, options, 0, dbio); @@ -4832,10 +5017,11 @@ cl_error_t cli_load(const char *filename, struct cl_engine *engine, unsigned int ret = cli_loadopenioc(fs, dbname, engine, options); #ifdef HAVE_YARA } else if (cli_strbcasestr(dbname, ".yar") || cli_strbcasestr(dbname, ".yara")) { - if (!(options & CL_DB_YARA_EXCLUDE)) + if (!(options & CL_DB_YARA_EXCLUDE)) { ret = cli_loadyara(fs, engine, signo, options, dbio, filename); - else + } else { skipped = 1; + } #endif } else if (cli_strbcasestr(dbname, ".pwdb")) { ret = cli_loadpwdb(fs, engine, options, 0, dbio); @@ -4847,14 +5033,16 @@ cl_error_t cli_load(const char *filename, struct cl_engine *engine, unsigned int if (ret) { cli_errmsg("Can't load %s: %s\n", filename, cl_strerror(ret)); } else { - if (skipped) + if (skipped) { cli_dbgmsg("%s skipped\n", filename); - else + } else { cli_dbgmsg("%s loaded\n", filename); + } } - if (fs) + if (fs) { fclose(fs); + } if (CL_SUCCESS == ret) { if (engine->cb_sigload_progress) { @@ -5068,10 +5256,11 @@ static cl_error_t cli_loaddbdir(const char *dirname, struct cl_engine *engine, u ret = CL_EMEM; goto done; } - if (ends_with_sep) + if (ends_with_sep) { sprintf(dbfile, "%s%s", dirname, dent->d_name); - else + } else { sprintf(dbfile, "%s" PATHSEP "%s", dirname, dent->d_name); + } #define DB_LOAD_PRIORITY_IGN 1 #define DB_LOAD_PRIORITY_DAILY_CLD 2 @@ -5230,8 +5419,9 @@ static cl_error_t cli_loaddbdir(const char *dirname, struct cl_engine *engine, u cl_cvdfree(daily_cvd); } - if (ret == CL_EOPEN) + if (ret == CL_EOPEN) { cli_errmsg("cli_loaddbdir: No supported database files found in %s\n", dirname); + } return ret; } @@ -5287,19 +5477,23 @@ cl_error_t cl_load(const char *path, struct cl_engine *engine, unsigned int *sig return CL_ESTAT; } - if ((dboptions & CL_DB_PHISHING_URLS) && !engine->phishcheck && (engine->dconf->phishing & PHISHING_CONF_ENGINE)) - if (CL_SUCCESS != (ret = phishing_init(engine))) + if ((dboptions & CL_DB_PHISHING_URLS) && !engine->phishcheck && (engine->dconf->phishing & PHISHING_CONF_ENGINE)) { + if (CL_SUCCESS != (ret = phishing_init(engine))) { return ret; + } + } if ((dboptions & CL_DB_BYTECODE) && !engine->bcs.inited) { - if (CL_SUCCESS != (ret = cli_bytecode_init(&engine->bcs))) + if (CL_SUCCESS != (ret = cli_bytecode_init(&engine->bcs))) { return ret; + } } else { cli_dbgmsg("Bytecode engine disabled\n"); } - if (!engine->cache && clean_cache_init(engine)) + if (!engine->cache && clean_cache_init(engine)) { return CL_EMEM; + } engine->dboptions |= dboptions; @@ -5494,7 +5688,7 @@ int cl_statchkdir(const struct cl_stat *dbstat) free(fname); found = 0; - for (i = 0; i < dbstat->entries; i++) + for (i = 0; i < dbstat->entries; i++) { #ifdef _WIN32 if (!strcmp(dbstat->statdname[i], dent->d_name)) { #else @@ -5506,6 +5700,7 @@ int cl_statchkdir(const struct cl_stat *dbstat) return 1; } } + } if (!found) { closedir(dd); @@ -5592,8 +5787,9 @@ cl_error_t cl_engine_free(struct cl_engine *engine) pthread_mutex_lock(&cli_ref_mutex); #endif - if (engine->refcount) + if (engine->refcount) { engine->refcount--; + } if (engine->refcount) { #ifdef CL_THREAD_SAFE @@ -5602,8 +5798,9 @@ cl_error_t cl_engine_free(struct cl_engine *engine) return CL_SUCCESS; } - if (engine->cb_stats_submit) + if (engine->cb_stats_submit) { engine->cb_stats_submit(engine, engine->stats_data); + } #ifdef CL_THREAD_SAFE if (engine->stats_data) { @@ -5615,8 +5812,9 @@ cl_error_t cl_engine_free(struct cl_engine *engine) pthread_mutex_unlock(&cli_ref_mutex); #endif - if (engine->stats_data) + if (engine->stats_data) { free(engine->stats_data); + } /* * Pre-calculate number of "major" tasks to complete for the progress callback @@ -5761,8 +5959,9 @@ cl_error_t cl_engine_free(struct cl_engine *engine) while (engine->cdb) { struct cli_cdb *pt = engine->cdb; engine->cdb = pt->next; - if (pt->name.re_magic) + if (pt->name.re_magic) { cli_regfree(&pt->name); + } MPOOL_FREE(engine->mempool, pt->res2); MPOOL_FREE(engine->mempool, pt->virname); MPOOL_FREE(engine->mempool, pt); @@ -5774,8 +5973,9 @@ cl_error_t cl_engine_free(struct cl_engine *engine) engine->dbinfo = pt->next; MPOOL_FREE(engine->mempool, pt->name); MPOOL_FREE(engine->mempool, pt->hash); - if (pt->cvd) + if (pt->cvd) { cvd_free(pt->cvd); + } MPOOL_FREE(engine->mempool, pt); } TASK_COMPLETE(); @@ -5808,9 +6008,11 @@ cl_error_t cl_engine_free(struct cl_engine *engine) } if (engine->pwdbs) { - for (i = 0; i < CLI_PWDB_COUNT; i++) - if (engine->pwdbs[i]) + for (i = 0; i < CLI_PWDB_COUNT; i++) { + if (engine->pwdbs[i]) { cli_pwdb_list_free(engine, engine->pwdbs[i]); + } + } MPOOL_FREE(engine->mempool, engine->pwdbs); } TASK_COMPLETE(); @@ -5832,13 +6034,15 @@ cl_error_t cl_engine_free(struct cl_engine *engine) } } if (iconcheck->group_names[0]) { - for (i = 0; i < iconcheck->group_counts[0]; i++) + for (i = 0; i < iconcheck->group_counts[0]; i++) { MPOOL_FREE(engine->mempool, iconcheck->group_names[0][i]); + } MPOOL_FREE(engine->mempool, iconcheck->group_names[0]); } if (iconcheck->group_names[1]) { - for (i = 0; i < iconcheck->group_counts[1]; i++) + for (i = 0; i < iconcheck->group_counts[1]; i++) { MPOOL_FREE(engine->mempool, iconcheck->group_names[1][i]); + } MPOOL_FREE(engine->mempool, iconcheck->group_names[1]); } MPOOL_FREE(engine->mempool, iconcheck); @@ -5895,7 +6099,9 @@ cl_error_t cl_engine_free(struct cl_engine *engine) } #ifdef USE_MPOOL - if (engine->mempool) mpool_destroy(engine->mempool); + if (engine->mempool) { + mpool_destroy(engine->mempool); + } TASK_COMPLETE(); #endif @@ -5970,54 +6176,66 @@ cl_error_t cl_engine_compile(struct cl_engine *engine) #ifdef HAVE_YARA /* Free YARA hash tables - only needed for parse and load */ if (engine->yara_global != NULL) { - if (engine->yara_global->rules_table) + if (engine->yara_global->rules_table) { yr_hash_table_destroy(engine->yara_global->rules_table, NULL); - if (engine->yara_global->objects_table) + } + if (engine->yara_global->objects_table) { yr_hash_table_destroy(engine->yara_global->objects_table, NULL); + } engine->yara_global->rules_table = engine->yara_global->objects_table = NULL; } TASK_COMPLETE(); #endif - if (!engine->ftypes) - if ((ret = cli_loadftm(NULL, engine, 0, 1, NULL))) + if (!engine->ftypes) { + if ((ret = cli_loadftm(NULL, engine, 0, 1, NULL))) { return ret; + } + } TASK_COMPLETE(); /* handle default passwords */ - if (!engine->pwdbs[0] && !engine->pwdbs[1] && !engine->pwdbs[2]) - if ((ret = cli_loadpwdb(NULL, engine, 0, 1, NULL))) + if (!engine->pwdbs[0] && !engine->pwdbs[1] && !engine->pwdbs[2]) { + if ((ret = cli_loadpwdb(NULL, engine, 0, 1, NULL))) { return ret; + } + } TASK_COMPLETE(); for (i = 0; i < CLI_MTARGETS; i++) { if ((root = engine->root[i])) { - if ((ret = cli_ac_buildtrie(root))) + if ((ret = cli_ac_buildtrie(root))) { return ret; + } TASK_COMPLETE(); - if ((ret = cli_pcre_build(root, engine->pcre_match_limit, engine->pcre_recmatch_limit, engine->dconf))) + if ((ret = cli_pcre_build(root, engine->pcre_match_limit, engine->pcre_recmatch_limit, engine->dconf))) { return ret; + } TASK_COMPLETE(); cli_dbgmsg("Matcher[%u]: %s: AC sigs: %u (reloff: %u, absoff: %u) BM sigs: %u (reloff: %u, absoff: %u) PCREs: %u (reloff: %u, absoff: %u) maxpatlen %u %s\n", i, cli_mtargets[i].name, root->ac_patterns, root->ac_reloff_num, root->ac_absoff_num, root->bm_patterns, root->bm_reloff_num, root->bm_absoff_num, root->pcre_metas, root->pcre_reloff_num, root->pcre_absoff_num, root->maxpatlen, root->ac_only ? "(ac_only mode)" : ""); } } - if (engine->hm_hdb) + if (engine->hm_hdb) { hm_flush(engine->hm_hdb); + } TASK_COMPLETE(); - if (engine->hm_mdb) + if (engine->hm_mdb) { hm_flush(engine->hm_mdb); + } TASK_COMPLETE(); - if (engine->hm_imp) + if (engine->hm_imp) { hm_flush(engine->hm_imp); + } TASK_COMPLETE(); - if (engine->hm_fp) + if (engine->hm_fp) { hm_flush(engine->hm_fp); + } TASK_COMPLETE(); if ((ret = cli_build_regex_list(engine->allow_list_matcher))) { @@ -6039,8 +6257,9 @@ cl_error_t cl_engine_compile(struct cl_engine *engine) if (engine->test_root) { root = engine->test_root; - if (!root->ac_only) + if (!root->ac_only) { cli_bm_free(root); + } cli_ac_free(root); if (root->ac_lsigtable) { for (i = 0; i < root->ac_lsigs; i++) { @@ -6107,8 +6326,9 @@ static int countentries(const char *dbname, unsigned int *sigs) return CL_EOPEN; } while (fgets(buffer, sizeof(buffer), fs)) { - if (buffer[0] == '#') + if (buffer[0] == '#') { continue; + } entry++; } fclose(fs); @@ -6139,8 +6359,9 @@ static int countsigs(const char *dbname, unsigned int options, unsigned int *sig cl_cvdfree(cvd); } } else if (cli_strbcasestr(dbname, ".cbc")) { - if (options & CL_COUNTSIGS_UNOFFICIAL) + if (options & CL_COUNTSIGS_UNOFFICIAL) { (*sigs)++; + } } else if (cli_strbcasestr(dbname, ".wdb") || cli_strbcasestr(dbname, ".fp") || cli_strbcasestr(dbname, ".sfp") || cli_strbcasestr(dbname, ".ign") || cli_strbcasestr(dbname, ".ign2") || cli_strbcasestr(dbname, ".ftm") || cli_strbcasestr(dbname, ".cfg") || cli_strbcasestr(dbname, ".cat")) { /* ignore allow list/FP signatures and metadata files */ @@ -6167,8 +6388,9 @@ cl_error_t cl_countsigs(const char *path, unsigned int countoptions, unsigned in DIR *dd; cl_error_t ret; - if (!sigs) + if (!sigs) { return CL_ENULLARG; + } if (CLAMSTAT(path, &sb) == -1) { cli_errmsg("cl_countsigs: Can't stat %s\n", path); diff --git a/libclamav/rebuildpe.c b/libclamav/rebuildpe.c index d51b7123e8..a7f8767e60 100644 --- a/libclamav/rebuildpe.c +++ b/libclamav/rebuildpe.c @@ -131,24 +131,32 @@ int cli_rebuildpe_align(char *buffer, struct cli_exe_section *sections, int sect struct IMAGE_PE_HEADER *fakepe; int i, gotghost = (sections[0].rva > PESALIGN(rawbase, 0x1000)); - if (gotghost) rawbase = PESALIGN(0x148 + 0x80 + 0x28 * (sects + 1), 0x200); + if (gotghost) { + rawbase = PESALIGN(0x148 + 0x80 + 0x28 * (sects + 1), 0x200); + } - if (sects + gotghost > 96) + if (sects + gotghost > 96) { return 0; + } - if (!align) - for (i = 0; i < sects; i++) + if (!align) { + for (i = 0; i < sects; i++) { datasize += PESALIGN(sections[i].rsz, 0x200); - else - for (i = 0; i < sects; i++) + } + } else { + for (i = 0; i < sects; i++) { datasize += PESALIGN(PESALIGN(sections[i].rsz, align), 0x200); + } + } - if (datasize > CLI_MAX_ALLOCATION) + if (datasize > CLI_MAX_ALLOCATION) { return 0; + } pefile = (char *)cli_max_calloc(rawbase + datasize, 1); - if (!pefile) + if (!pefile) { return 0; + } memcpy(pefile, HEADERS, 0x148); diff --git a/libclamav/regex_list.c b/libclamav/regex_list.c index dc28e1f408..6c03327948 100644 --- a/libclamav/regex_list.c +++ b/libclamav/regex_list.c @@ -86,12 +86,18 @@ static inline char get_char_at_pos_with_skip(const struct pre_fixup_info *info, cli_dbgmsg("calc_pos_with_skip: skip:%llu, %llu - %llu \"%s\",\"%s\"\n", (long long unsigned)pos, (long long unsigned)info->host_start, (long long unsigned)info->host_end, str, buffer); pos += info->host_start; - while (str[realpos] && !isalnum(str[realpos])) realpos++; + while (str[realpos] && !isalnum(str[realpos])) { + realpos++; + } for (; str[realpos] && (pos > 0); pos--) { - while (str[realpos] == ' ') realpos++; + while (str[realpos] == ' ') { + realpos++; + } + realpos++; + } + while (str[realpos] == ' ') { realpos++; } - while (str[realpos] == ' ') realpos++; cli_dbgmsg("calc_pos_with_skip:%s\n", str + realpos); return (pos > 0 && !str[realpos]) ? '\0' : str[realpos > 0 ? realpos - 1 : 0]; } @@ -101,8 +107,9 @@ static int validate_subdomain(const struct regex_list *regex, const struct pre_f char c; size_t match_len; - if (!regex || !regex->pattern) + if (!regex || !regex->pattern) { return 0; + } match_len = strlen(regex->pattern); if (((c = get_char_at_pos_with_skip(pre_fixup, buffer, buffer_len + 1)) == ' ' || c == '\0' || c == '/' || c == '?') && (match_len == buffer_len || /* full match */ @@ -110,7 +117,9 @@ static int validate_subdomain(const struct regex_list *regex, const struct pre_f ((c = get_char_at_pos_with_skip(pre_fixup, buffer, buffer_len - match_len)) == '.' || (c == ' '))) /* subdomain matched*/)) { /* we have an extra / at the end */ - if (match_len > 0) match_len--; + if (match_len > 0) { + match_len--; + } cli_dbgmsg("Got a match: %s with %s\n", buffer, regex->pattern); cli_dbgmsg("Before inserting .: %s\n", orig_real_url); if (real_len >= match_len + 1) { @@ -191,8 +200,12 @@ cl_error_t regex_list_match(struct regex_matcher *matcher, char *real_url, const } /* skip initial '.' inserted by get_host */ - if (real_url[0] == '.') real_url++; - if (display_url[0] == '.') display_url++; + if (real_url[0] == '.') { + real_url++; + } + if (display_url[0] == '.') { + display_url++; + } real_len = strlen(real_url); display_len = strlen(display_url); buffer_len = (hostOnly && !is_allow_list_lookup) ? real_len + 1 : real_len + display_len + 1 + 1; @@ -221,12 +234,14 @@ cl_error_t regex_list_match(struct regex_matcher *matcher, char *real_url, const buffer[buffer_len] = 0; cli_dbgmsg("Looking up in regex_list: %s\n", buffer); - if (CL_SUCCESS != (rc = cli_ac_initdata(&mdata, 0, 0, 0, CLI_DEFAULT_AC_TRACKLEN))) + if (CL_SUCCESS != (rc = cli_ac_initdata(&mdata, 0, 0, 0, CLI_DEFAULT_AC_TRACKLEN))) { return rc; + } bufrev = cli_safer_strdup(buffer); - if (!bufrev) + if (!bufrev) { return CL_EMEM; + } reverse_string(bufrev); @@ -263,7 +278,9 @@ cl_error_t regex_list_match(struct regex_matcher *matcher, char *real_url, const } else { rc = !cli_regexec(regex->preg, buffer, 0, NULL, 0); } - if (rc) *info = regex->pattern; + if (rc) { + *info = regex->pattern; + } regex = regex->nxt; } if (res) { @@ -273,10 +290,11 @@ cl_error_t regex_list_match(struct regex_matcher *matcher, char *real_url, const } } free(buffer); - if (!rc) + if (!rc) { cli_dbgmsg("Lookup result: not in regex list\n"); - else + } else { cli_dbgmsg("Lookup result: in regex list\n"); + } done: return rc; } @@ -342,37 +360,44 @@ static int functionality_level_check(char *line) size_t j; ptmin = strrchr(line, ':'); - if (!ptmin) + if (!ptmin) { return CL_SUCCESS; + } ptmin++; ptmax = strchr(ptmin, '-'); - if (!ptmax) + if (!ptmax) { return CL_SUCCESS; /* there is no functionality level specified, so we're ok */ - else { + } else { size_t min, max; ptmax++; - for (j = 0; j + ptmin + 1 < ptmax; j++) - if (!isdigit(ptmin[j])) + for (j = 0; j + ptmin + 1 < ptmax; j++) { + if (!isdigit(ptmin[j])) { return CL_SUCCESS; /* not numbers, not functionality level */ - for (j = 0; j < strlen(ptmax); j++) - if (!isdigit(ptmax[j])) + } + } + for (j = 0; j < strlen(ptmax); j++) { + if (!isdigit(ptmax[j])) { return CL_SUCCESS; /* see above */ + } + } ptmax[-1] = '\0'; min = atoi(ptmin); - if (strlen(ptmax) == 0) + if (strlen(ptmax) == 0) { max = INT_MAX; - else + } else { max = atoi(ptmax); + } if (min > cl_retflevel()) { cli_dbgmsg("regex list line %s not loaded (required f-level: %u)\n", line, (unsigned int)min); return CL_EMALFDB; } - if (max < cl_retflevel()) + if (max < cl_retflevel()) { return CL_EMALFDB; + } ptmin[-1] = '\0'; return CL_SUCCESS; } @@ -466,8 +491,9 @@ cl_error_t load_regex_matcher(struct cl_engine *engine, struct regex_matcher *ma return CL_ENULLARG; } - if (matcher->list_inited == -1) + if (matcher->list_inited == -1) { return CL_EMALFDB; /* already failed to load */ + } if (!fd && !dbio) { cli_errmsg("Unable to load regex list (null file)\n"); return CL_ENULLARG; @@ -510,14 +536,17 @@ cl_error_t load_regex_matcher(struct cl_engine *engine, struct regex_matcher *ma cli_chomp(buffer); line++; - if (!*buffer) + if (!*buffer) { continue; /* skip empty lines */ + } - if (buffer[0] == '#') + if (buffer[0] == '#') { continue; + } - if (functionality_level_check(buffer)) + if (functionality_level_check(buffer)) { continue; + } if (engine->cb_sigload && engine->cb_sigload("phishing", buffer, ~options & CL_DB_OFFICIAL, engine->cb_sigload_ctx)) { cli_dbgmsg("load_regex_matcher: skipping %s due to callback\n", buffer); @@ -555,12 +584,14 @@ cl_error_t load_regex_matcher(struct cl_engine *engine, struct regex_matcher *ma } } else if ((buffer[0] == 'H' && !is_allow_list_lookup) || (buffer[0] == 'M' && is_allow_list_lookup)) { /*matches displayed host*/ - if ((rc = add_static_pattern(matcher, pattern))) + if ((rc = add_static_pattern(matcher, pattern))) { return rc == CL_EMEM ? CL_EMEM : CL_EMALFDB; + } } else if (buffer[0] == 'S' && (!is_allow_list_lookup || pattern[0] == 'W')) { pattern[pattern_len] = '\0'; - if (pattern[0] == 'W') + if (pattern[0] == 'W') { flags[0] = 'W'; + } if ((pattern[0] == 'W' || pattern[0] == 'F' || pattern[0] == 'P') && pattern[1] == ':') { pattern += 2; if ((rc = add_hash(matcher, pattern, flags[0], pattern[-2] == 'P'))) { @@ -576,8 +607,9 @@ cl_error_t load_regex_matcher(struct cl_engine *engine, struct regex_matcher *ma } } matcher->list_loaded = 1; - if (signo) + if (signo) { *signo += entry; + } return CL_SUCCESS; } @@ -586,16 +618,18 @@ cl_error_t load_regex_matcher(struct cl_engine *engine, struct regex_matcher *ma cl_error_t cli_build_regex_list(struct regex_matcher *matcher) { cl_error_t rc; - if (!matcher) + if (!matcher) { return CL_SUCCESS; + } if (!matcher->list_inited || !matcher->list_loaded) { cli_errmsg("Regex list not loaded!\n"); return -1; /*TODO: better error code */ } cli_dbgmsg("Building regex list\n"); cli_hashtab_free(&matcher->suffix_hash); - if ((rc = cli_ac_buildtrie(&matcher->suffixes))) + if ((rc = cli_ac_buildtrie(&matcher->suffixes))) { return rc; + } matcher->list_built = 1; cli_hashset_destroy(&matcher->sha256_pfx_set); @@ -699,8 +733,9 @@ static cl_error_t add_newsuffix(struct regex_matcher *matcher, struct regex_list new->length[0] = (uint16_t)len; new->ch[0] = new->ch[1] |= CLI_MATCH_IGNORE; - if (new->length[0] > root->maxpatlen) + if (new->length[0] > root->maxpatlen) { root->maxpatlen = new->length[0]; + } new->pattern = MPOOL_MALLOC(matcher->mempool, sizeof(new->pattern[0]) * len); if (!new->pattern) { @@ -743,8 +778,9 @@ static cl_error_t add_newsuffix(struct regex_matcher *matcher, struct regex_list static void list_add_tail(struct regex_list_ht *ht, struct regex_list *regex) { - if (!ht->head) + if (!ht->head) { ht->head = regex; + } if (ht->tail) { ht->tail->nxt = regex; } @@ -904,8 +940,9 @@ cl_error_t regex_list_add_pattern(struct regex_matcher *matcher, char *pattern) pattern[len] = '\0'; preg = new_preg(matcher); - if (!preg) + if (!preg) { return CL_EMEM; + } rc = cli_regex2suffix(pattern, preg, add_pattern_suffix, (void *)matcher); if (rc) { diff --git a/libclamav/regex_pcre.c b/libclamav/regex_pcre.c index dec1d37413..30031aff2b 100644 --- a/libclamav/regex_pcre.c +++ b/libclamav/regex_pcre.c @@ -47,8 +47,9 @@ void cli_pcre_free(void *ptr, void *ext) cl_error_t cli_pcre_addoptions(struct cli_pcre_data *pd, const char **opt, int errout) { - if (!pd || !opt || !(*opt)) + if (!pd || !opt || !(*opt)) { return CL_ENULLARG; + } while (**opt != '\0') { switch (**opt) { @@ -79,8 +80,9 @@ cl_error_t cli_pcre_addoptions(struct cli_pcre_data *pd, const char **opt, int e if (errout) { cli_errmsg("cli_pcre_addoptions: unknown/extra pcre option encountered %c\n", **opt); return CL_EMALFDB; - } else + } else { return CL_EPARSE; /* passed to caller to handle */ + } } (*opt)++; } @@ -114,10 +116,11 @@ cl_error_t cli_pcre_compile(struct cli_pcre_data *pd, long long unsigned match_l } /* compile the pcre2 regex last arg is charset, allow for options override */ - if (opt_override) + if (opt_override) { pd->re = pcre2_compile((PCRE2_SPTR8)pd->expression, PCRE2_ZERO_TERMINATED, options, &errornum, &erroffset, cctx); /* pd->re handled by pcre2 -> call pcre_free() -> calls free() */ - else + } else { pd->re = pcre2_compile((PCRE2_SPTR8)pd->expression, PCRE2_ZERO_TERMINATED, pd->options, &errornum, &erroffset, cctx); /* pd->re handled by pcre2 -> call pcre_free() -> calls free() */ + } if (pd->re == NULL) { PCRE2_UCHAR errmsg[256]; pcre2_get_error_message(errornum, errmsg, sizeof(errmsg)); @@ -155,8 +158,9 @@ int cli_pcre_match(struct cli_pcre_data *pd, const unsigned char *buffer, size_t /* set the startoffset, override if a value is specified */ startoffset = pd->search_offset; - if (override_offset != pd->search_offset) + if (override_offset != pd->search_offset) { startoffset = override_offset; + } /* execute the pcre and return */ rc = pcre2_match(pd->re, buffer, buflen, startoffset, options, results->match_data, pd->mctx); @@ -232,8 +236,9 @@ static void named_substr_print(const struct cli_pcre_data *pd, const unsigned ch length = MATCH_MAXLEN; } - for (j = 0; j < length; ++j) + for (j = 0; j < length; ++j) { snprintf(outstr + (2 * j), sizeof(outstr) - (2 * j), "%02x", (unsigned int)*(start + j)); + } cli_dbgmsg("cli_pcre_report: (%d) %*s: %s%s\n", n, name_entry_size - 3, tabptr + 2, outstr, trunc ? " (trunc)" : ""); @@ -282,8 +287,9 @@ void cli_pcre_report(const struct cli_pcre_data *pd, const unsigned char *buffer length = MATCH_MAXLEN; } - for (j = 0; j < length; ++j) + for (j = 0; j < length; ++j) { snprintf(outstr + (2 * j), sizeof(outstr) - (2 * j), "%02x", (unsigned int)*(start + j)); + } cli_dbgmsg("cli_pcre_report: %d: %s%s\n", i, outstr, trunc ? " (trunc)" : ""); // cli_dbgmsg("cli_pcre_report: %d: %.*s%s\n", i, length, start, trunc ? " (trunc)":""); @@ -306,20 +312,23 @@ cl_error_t cli_pcre_results_reset(struct cli_pcre_results *results, const struct results->err = CL_SUCCESS; results->match[0] = results->match[1] = 0; - if (results->match_data) + if (results->match_data) { pcre2_match_data_free(results->match_data); + } results->match_data = pcre2_match_data_create_from_pattern(pd->re, NULL); - if (!results->match_data) + if (!results->match_data) { return CL_EMEM; + } return CL_SUCCESS; } void cli_pcre_results_free(struct cli_pcre_results *results) { - if (results->match_data) + if (results->match_data) { pcre2_match_data_free(results->match_data); + } } void cli_pcre_free_single(struct cli_pcre_data *pd) diff --git a/libclamav/regex_suffix.c b/libclamav/regex_suffix.c index 1952eb6c87..eab6731c62 100644 --- a/libclamav/regex_suffix.c +++ b/libclamav/regex_suffix.c @@ -71,10 +71,12 @@ static struct node *make_node(enum node_type type, struct node *left, struct nod { struct node *n; if (type == concat) { - if (left == NULL) + if (left == NULL) { return right; - if (right == NULL) + } + if (right == NULL) { return left; + } } n = malloc(sizeof(*n)); if (!n) { @@ -85,10 +87,12 @@ static struct node *make_node(enum node_type type, struct node *left, struct nod n->parent = NULL; n->u.children.left = left; n->u.children.right = right; - if (left) + if (left) { left->parent = n; - if (right) + } + if (right) { right->parent = n; + } return n; } @@ -97,8 +101,9 @@ static struct node *dup_node(struct node *p) struct node *node_left, *node_right; struct node *d; - if (!p) + if (!p) { return NULL; + } d = malloc(sizeof(*d)); if (!d) { cli_errmsg("dup_node: Unable to allocate memory for duplicate node\n"); @@ -124,10 +129,12 @@ static struct node *dup_node(struct node *p) node_right = dup_node(p->u.children.right); d->u.children.left = node_left; d->u.children.right = node_right; - if (node_left) + if (node_left) { node_left->parent = d; - if (node_right) + } + if (node_right) { node_right->parent = d; + } break; } return d; @@ -154,8 +161,9 @@ static struct node *make_charclass(uint8_t *bitmap) static struct node *make_leaf(char c) { struct node *v = malloc(sizeof(*v)); - if (!v) + if (!v) { return NULL; + } v->type = leaf; v->parent = NULL; v->u.leaf_char = c; @@ -164,8 +172,9 @@ static struct node *make_leaf(char c) static void destroy_tree(struct node *n) { - if (!n) + if (!n) { return; + } switch (n->type) { case concat: case alternate: @@ -174,8 +183,9 @@ static void destroy_tree(struct node *n) destroy_tree(n->u.children.right); break; case leaf_class: - if (n->u.leaf_class_bitmap != dot_bitmap) + if (n->u.leaf_class_bitmap != dot_bitmap) { CLI_FREE_AND_SET_NULL(n->u.leaf_class_bitmap); + } break; case root: case leaf: @@ -213,8 +223,9 @@ static uint8_t *parse_char_class(const uint8_t *pat, size_t patSize, size_t *pos if (pat[*pos] == '^') { memset(bitmap, 0xFF, 32); /*match chars not in brackets*/ INC_POS(pos, patSize); - } else + } else { memset(bitmap, 0x00, 32); + } do { /* literal ] can be first character, so test for it at the end of the loop, for example: []] */ if (pat[*pos] == '-' && hasprev) { @@ -227,7 +238,7 @@ static uint8_t *parse_char_class(const uint8_t *pat, size_t patSize, size_t *pos goto done; } INC_POS(pos, patSize); - if (pat[*pos] == '[') + if (pat[*pos] == '[') { if (pat[*pos + 1] == '.') { /* collating sequence not handled */ CLI_FREE_AND_SET_NULL(bitmap); @@ -239,12 +250,15 @@ static uint8_t *parse_char_class(const uint8_t *pat, size_t patSize, size_t *pos INC_POS(pos, patSize); while (pat[*pos] != ']') INC_POS(pos, patSize); return dot_bitmap; - } else + } else { range_end = pat[*pos]; - else + } + } else { range_end = pat[*pos]; - for (c = range_start + 1; c <= range_end; c++) + } + for (c = range_start + 1; c <= range_end; c++) { bitmap[c >> 3] ^= 1 << (c & 0x7); + } hasprev = 0; } else if (pat[*pos] == '[' && pat[*pos] == ':') { /* char class */ @@ -288,8 +302,9 @@ static struct node *parse_regex(const uint8_t *p, const size_t pSize, size_t *la case '*': case '?': v = make_node(optional, v, NULL); - if (!v) + if (!v) { return NULL; + } ++*last; break; case '+': @@ -332,8 +347,9 @@ static struct node *parse_regex(const uint8_t *p, const size_t pSize, size_t *la return NULL; } v = make_node(concat, v, right); - if (!v) + if (!v) { return NULL; + } ++*last; break; case '[': @@ -356,7 +372,9 @@ static struct node *parse_regex(const uint8_t *p, const size_t pSize, size_t *la ++*last; /* fall-through */ default: - if (*last >= pSize) break; + if (*last >= pSize) { + break; + } right = make_leaf(p[*last]); v = make_node(concat, v, right); if (!v) { @@ -380,8 +398,9 @@ static cl_error_t build_suffixtree_ascend(struct node *n, struct text_buffer *bu switch (n->type) { case root: textbuffer_putc(buf, '\0'); - if (cb(cbdata, buf->data, buf->pos - 1, regex) != CL_SUCCESS) + if (cb(cbdata, buf->data, buf->pos - 1, regex) != CL_SUCCESS) { return CL_EMEM; + } return CL_SUCCESS; case leaf: textbuffer_putc(buf, n->u.leaf_char); @@ -389,13 +408,16 @@ static cl_error_t build_suffixtree_ascend(struct node *n, struct text_buffer *bu break; case leaf_class: cnt = 0; - for (i = 0; i < 255; i++) - if (BITMAP_HASSET(n->u.leaf_class_bitmap, i)) + for (i = 0; i < 255; i++) { + if (BITMAP_HASSET(n->u.leaf_class_bitmap, i)) { cnt++; + } + } if (cnt > 16) { textbuffer_putc(buf, '\0'); - if (cb(cbdata, buf->data, buf->pos - 1, regex) != CL_SUCCESS) + if (cb(cbdata, buf->data, buf->pos - 1, regex) != CL_SUCCESS) { return CL_EMEM; + } return CL_SUCCESS; } /* handle small classes by expanding */ @@ -404,16 +426,18 @@ static cl_error_t build_suffixtree_ascend(struct node *n, struct text_buffer *bu size_t pos; pos = buf->pos; textbuffer_putc(buf, (char)i); - if (build_suffixtree_ascend(n->parent, buf, n, cb, cbdata, regex) != CL_SUCCESS) + if (build_suffixtree_ascend(n->parent, buf, n, cb, cbdata, regex) != CL_SUCCESS) { return CL_EMEM; + } buf->pos = pos; } } return 0; case concat: if (prev != n->u.children.left) { - if (build_suffixtree_descend(n->u.children.left, buf, cb, cbdata, regex) != CL_SUCCESS) + if (build_suffixtree_descend(n->u.children.left, buf, cb, cbdata, regex) != CL_SUCCESS) { return CL_EMEM; + } /* we're done here, descend will call * ascend if needed */ return CL_SUCCESS; @@ -426,8 +450,9 @@ static cl_error_t build_suffixtree_ascend(struct node *n, struct text_buffer *bu break; case optional: textbuffer_putc(buf, '\0'); - if (cb(cbdata, buf->data, buf->pos - 1, regex) != CL_SUCCESS) + if (cb(cbdata, buf->data, buf->pos - 1, regex) != CL_SUCCESS) { return CL_EMEM; + } return CL_SUCCESS; } prev = q; @@ -441,30 +466,35 @@ static cl_error_t build_suffixtree_descend(struct node *n, struct text_buffer *b while (n && n->type == concat) { n = n->u.children.right; } - if (!n) + if (!n) { return CL_SUCCESS; + } /* find out end of the regular expression, * if it ends with a static pattern */ switch (n->type) { case alternate: /* save pos as restart point */ pos = buf->pos; - if (build_suffixtree_descend(n->u.children.left, buf, cb, cbdata, regex) != CL_SUCCESS) + if (build_suffixtree_descend(n->u.children.left, buf, cb, cbdata, regex) != CL_SUCCESS) { return CL_EMEM; + } buf->pos = pos; - if (build_suffixtree_descend(n->u.children.right, buf, cb, cbdata, regex) != CL_SUCCESS) + if (build_suffixtree_descend(n->u.children.right, buf, cb, cbdata, regex) != CL_SUCCESS) { return CL_EMEM; + } buf->pos = pos; break; case optional: textbuffer_putc(buf, '\0'); - if (cb(cbdata, buf->data, buf->pos - 1, regex) != CL_SUCCESS) + if (cb(cbdata, buf->data, buf->pos - 1, regex) != CL_SUCCESS) { return CL_EMEM; + } return CL_SUCCESS; case leaf: case leaf_class: - if (build_suffixtree_ascend(n, buf, NULL, cb, cbdata, regex) != CL_SUCCESS) + if (build_suffixtree_ascend(n, buf, NULL, cb, cbdata, regex) != CL_SUCCESS) { return CL_EMEM; + } return CL_SUCCESS; default: break; diff --git a/libclamav/rtf.c b/libclamav/rtf.c index 1f2ce6d408..53759cbcf5 100644 --- a/libclamav/rtf.c +++ b/libclamav/rtf.c @@ -210,9 +210,11 @@ static int pop_state(struct stack* stack, struct rtf_state* state) static int load_actions(table_t* t) { size_t i; - for (i = 0; i < rtf_action_mapping_cnt; i++) - if (tableInsert(t, rtf_action_mapping[i].controlword, rtf_action_mapping[i].action) == -1) + for (i = 0; i < rtf_action_mapping_cnt; i++) { + if (tableInsert(t, rtf_action_mapping[i].controlword, rtf_action_mapping[i].action) == -1) { return -1; + } + } return 0; } @@ -257,8 +259,11 @@ static cl_error_t decode_and_scan(struct rtf_object_data* data, cli_ctx* ctx) } if (data->name) { - if (!ctx->engine->keeptmp) - if (cli_unlink(data->name)) ret = CL_EUNLINK; + if (!ctx->engine->keeptmp) { + if (cli_unlink(data->name)) { + ret = CL_EUNLINK; + } + } free(data->name); data->name = NULL; } @@ -275,25 +280,30 @@ static int rtf_object_process(struct rtf_state* state, const unsigned char* inpu size_t i; int ret; - if (!data || !len) + if (!data || !len) { return 0; + } if (data->has_partial) { - for (i = 0; i < len && !isxdigit(input[i]); i++) + for (i = 0; i < len && !isxdigit(input[i]); i++) { ; + } if (i < len) { outdata[out_cnt++] = data->partial | hextable[input[i++]]; data->has_partial = 0; - } else + } else { return 0; - } else + } + } else { i = 0; + } for (; i < len; i++) { if (isxdigit(input[i])) { const unsigned char byte = hextable[input[i++]] << 4; - while (i < len && !isxdigit(input[i])) + while (i < len && !isxdigit(input[i])) { i++; + } if (i == len) { data->partial = byte; data->has_partial = 1; @@ -308,10 +318,11 @@ static int rtf_object_process(struct rtf_state* state, const unsigned char* inpu switch (data->internal_state) { case WAIT_MAGIC: { cli_dbgmsg("RTF: waiting for magic\n"); - for (i = 0; i < out_cnt && data->bread < rtf_data_magic_len; i++, data->bread++) + for (i = 0; i < out_cnt && data->bread < rtf_data_magic_len; i++, data->bread++) { if (rtf_data_magic[data->bread] != out_data[i]) { cli_dbgmsg("Warning: rtf objdata magic number not matched, expected:%d, got: %d, at pos:%lu\n", rtf_data_magic[i], out_data[i], (unsigned long int)data->bread); } + } out_cnt -= i; if (data->bread == rtf_data_magic_len) { out_data += i; @@ -321,10 +332,12 @@ static int rtf_object_process(struct rtf_state* state, const unsigned char* inpu break; } case WAIT_DESC_LEN: { - if (data->bread == 0) + if (data->bread == 0) { data->desc_len = 0; - for (i = 0; i < out_cnt && data->bread < 4; i++, data->bread++) + } + for (i = 0; i < out_cnt && data->bread < 4; i++, data->bread++) { data->desc_len |= ((size_t)out_data[i]) << (data->bread * 8); + } out_cnt -= i; if (data->bread == 4) { out_data += i; @@ -332,8 +345,9 @@ static int rtf_object_process(struct rtf_state* state, const unsigned char* inpu if (data->desc_len > 64) { cli_dbgmsg("Description length too big (%lu), showing only 64 bytes of it\n", (unsigned long int)data->desc_len); data->desc_name = malloc(65); - } else + } else { data->desc_name = cli_max_malloc(data->desc_len + 1); + } if (!data->desc_name) { cli_errmsg("rtf_object_process: Unable to allocate memory for data->desc_name\n"); return CL_EMEM; @@ -345,8 +359,9 @@ static int rtf_object_process(struct rtf_state* state, const unsigned char* inpu } case WAIT_DESC: { cli_dbgmsg("RTF: in WAIT_DESC\n"); - for (i = 0; i < out_cnt && data->bread < data->desc_len && data->bread < 64; i++, data->bread++) + for (i = 0; i < out_cnt && data->bread < data->desc_len && data->bread < 64; i++, data->bread++) { data->desc_name[data->bread] = out_data[i]; + } out_cnt -= i; out_data += i; if (data->bread < data->desc_len && data->bread < 64) { @@ -389,17 +404,20 @@ static int rtf_object_process(struct rtf_state* state, const unsigned char* inpu case WAIT_DATA_SIZE: { cli_dbgmsg("RTF: in WAIT_DATA_SIZE\n"); - if (data->bread == 0) + if (data->bread == 0) { data->desc_len = 0; - for (i = 0; i < out_cnt && data->bread < 4; i++, data->bread++) + } + for (i = 0; i < out_cnt && data->bread < 4; i++, data->bread++) { data->desc_len |= ((size_t)out_data[i]) << (8 * data->bread); + } out_cnt -= i; if (data->bread == 4) { out_data += i; data->bread = 0; cli_dbgmsg("Dumping rtf embedded object of size:%lu\n", (unsigned long int)data->desc_len); - if ((ret = cli_gentempfd(data->tmpdir, &data->name, &data->fd))) + if ((ret = cli_gentempfd(data->tmpdir, &data->name, &data->fd))) { return ret; + } data->internal_state = DUMP_DATA; cli_dbgmsg("RTF: next state: DUMP_DATA\n"); } @@ -414,10 +432,12 @@ static int rtf_object_process(struct rtf_state* state, const unsigned char* inpu char out[4]; data->bread = 1; /* flag to indicate this needs to be scanned with cli_decode_ole_object*/ cli_writeint32(out, data->desc_len); - if (cli_writen(data->fd, out, 4) != 4) + if (cli_writen(data->fd, out, 4) != 4) { return CL_EWRITE; - } else + } + } else { data->bread = 2; + } } data->desc_len -= out_want; @@ -428,8 +448,9 @@ static int rtf_object_process(struct rtf_state* state, const unsigned char* inpu out_cnt -= out_want; if (!data->desc_len) { int rc; - if ((rc = decode_and_scan(data, data->ctx))) + if ((rc = decode_and_scan(data, data->ctx))) { return rc; + } data->bread = 0; data->internal_state = WAIT_MAGIC; } @@ -448,15 +469,18 @@ static int rtf_object_end(struct rtf_state* state, cli_ctx* ctx) { struct rtf_object_data* data = state->cb_data; int rc = 0; - if (!data) + if (!data) { return 0; + } if (data->fd > 0) { rc = decode_and_scan(data, ctx); } - if (data->name) + if (data->name) { free(data->name); - if (data->desc_name) + } + if (data->desc_name) { free(data->desc_name); + } free(data); state->cb_data = NULL; return rc; @@ -480,12 +504,14 @@ static void rtf_action(struct rtf_state* state, long action) static void cleanup_stack(struct stack* stack, struct rtf_state* state, cli_ctx* ctx) { - if (!stack || !stack->states) + if (!stack || !stack->states) { return; + } while (stack && stack->stack_cnt /* && state->default_elements*/) { pop_state(stack, state); - if (state->cb_data && state->cb_end) + if (state->cb_data && state->cb_end) { state->cb_end(state, ctx); + } } } @@ -532,8 +558,9 @@ int cli_scanrtf(cli_ctx* ctx) return CL_EMEM; } - if (!(tempname = cli_gentemp_with_prefix(ctx->sub_tmpdir, "rtf-tmp"))) + if (!(tempname = cli_gentemp_with_prefix(ctx->sub_tmpdir, "rtf-tmp"))) { return CL_EMEM; + } if (mkdir(tempname, 0700)) { cli_dbgmsg("ScanRTF -> Can't create temporary directory %s\n", tempname); @@ -546,8 +573,9 @@ int cli_scanrtf(cli_ctx* ctx) if ((ret = load_actions(actiontable))) { cli_dbgmsg("RTF: Unable to load rtf action table\n"); free(stack.states); - if (!ctx->engine->keeptmp) + if (!ctx->engine->keeptmp) { cli_rmdirs(tempname); + } free(tempname); tableDestroy(actiontable); return ret; @@ -569,11 +597,12 @@ int cli_scanrtf(cli_ctx* ctx) } break; case '}': - if (state.cb_data && state.cb_end) + if (state.cb_data && state.cb_end) { if ((ret = state.cb_end(&state, ctx))) { SCAN_CLEANUP; return ret; } + } if ((ret = pop_state(&stack, &state))) { cli_dbgmsg("RTF:pop failure!\n"); SCAN_CLEANUP; @@ -589,17 +618,19 @@ int cli_scanrtf(cli_ctx* ctx) size_t i; size_t left = ptr_end - ptr; size_t use = left; - for (i = 1; i < left; i++) + for (i = 1; i < left; i++) { if (main_symbols[ptr[i]]) { use = i; break; } + } if (state.cb_begin) { - if (!state.cb_data) + if (!state.cb_data) { if ((ret = state.cb_begin(&state, ctx, tempname))) { SCAN_CLEANUP; return ret; } + } if ((ret = state.cb_process(&state, ptr, use))) { if (state.cb_end) { state.cb_end(&state, ctx); @@ -616,8 +647,9 @@ int cli_scanrtf(cli_ctx* ctx) if (isalpha(*ptr)) { state.parse_state = PARSE_CONTROL_WORD; state.controlword_cnt = 0; - } else + } else { state.parse_state = PARSE_CONTROL_SYMBOL; + } break; case PARSE_CONTROL_SYMBOL: ptr++; /* Do nothing */ @@ -627,9 +659,9 @@ int cli_scanrtf(cli_ctx* ctx) if (state.controlword_cnt == 32) { cli_dbgmsg("Invalid control word: maximum size exceeded:%s\n", state.controlword); state.parse_state = PARSE_MAIN; - } else if (isalpha(*ptr)) + } else if (isalpha(*ptr)) { state.controlword[state.controlword_cnt++] = *ptr++; - else { + } else { if (isspace(*ptr)) { state.controlword[state.controlword_cnt++] = *ptr++; state.parse_state = PARSE_INTERPRET_CONTROLWORD; @@ -660,8 +692,9 @@ int cli_scanrtf(cli_ctx* ctx) } else if (isalpha(*ptr)) { ptr++; } else { - if (state.controlword_param_sign < 0) + if (state.controlword_param_sign < 0) { state.controlword_param = -state.controlword_param; + } state.parse_state = PARSE_INTERPRET_CONTROLWORD; } break; diff --git a/libclamav/scanners.c b/libclamav/scanners.c index db5b818072..38a8ac9869 100644 --- a/libclamav/scanners.c +++ b/libclamav/scanners.c @@ -350,8 +350,9 @@ static cl_error_t cli_scanrar_file(const char *filepath, int desc, cli_ctx *ctx) } /* Check if we've already exceeded the scan limit */ - if (cli_checklimits("RAR", ctx, 0, 0, 0)) + if (cli_checklimits("RAR", ctx, 0, 0, 0)) { break; + } if (metadata.is_dir) { /* Entry is a directory. Skip. */ @@ -771,8 +772,9 @@ static cl_error_t cli_scanegg(cli_ctx *ctx) } /* Check if we've already exceeded the scan limit */ - if (cli_checklimits("EGG", ctx, 0, 0, 0)) + if (cli_checklimits("EGG", ctx, 0, 0, 0)) { break; + } if (metadata.is_dir) { /* Entry is a directory. Skip. */ @@ -980,8 +982,9 @@ static cl_error_t cli_scanarj(cli_ctx *ctx) memset(&metadata, 0, sizeof(arj_metadata_t)); /* generate the temporary directory */ - if (!(dir = cli_gentemp_with_prefix(ctx->sub_tmpdir, "arj-tmp"))) + if (!(dir = cli_gentemp_with_prefix(ctx->sub_tmpdir, "arj-tmp"))) { return CL_EMEM; + } if (mkdir(dir, 0700)) { cli_dbgmsg("ARJ: Can't create temporary directory %s\n", dir); @@ -991,8 +994,9 @@ static cl_error_t cli_scanarj(cli_ctx *ctx) ret = cli_unarj_open(ctx->fmap, dir, &metadata); if (ret != CL_SUCCESS) { - if (!ctx->engine->keeptmp) + if (!ctx->engine->keeptmp) { cli_rmdirs(dir); + } free(dir); cli_dbgmsg("ARJ: Error: %s\n", cl_strerror(ret)); return ret; @@ -1017,8 +1021,9 @@ static cl_error_t cli_scanarj(cli_ctx *ctx) if ((ret = cli_checklimits("ARJ", ctx, metadata.orig_size, metadata.comp_size, 0)) != CL_CLEAN) { ret = CL_SUCCESS; - if (metadata.filename) + if (metadata.filename) { free(metadata.filename); + } continue; } @@ -1078,11 +1083,13 @@ static cl_error_t cli_scangzip_with_zib_from_the_80s(cli_ctx *ctx, unsigned char gzFile gz; ret = fmap_fd(map); - if (ret < 0) + if (ret < 0) { return CL_EDUP; + } fd = dup(ret); - if (fd < 0) + if (fd < 0) { return CL_EDUP; + } if (!(gz = gzdopen(fd, "rb"))) { close(fd); @@ -1098,8 +1105,9 @@ static cl_error_t cli_scangzip_with_zib_from_the_80s(cli_ctx *ctx, unsigned char while ((bytes = gzread(gz, buff, FILEBUFF)) > 0) { outsize += bytes; - if (cli_checklimits("GZip", ctx, outsize, 0, 0) != CL_CLEAN) + if (cli_checklimits("GZip", ctx, outsize, 0, 0) != CL_CLEAN) { break; + } if (cli_writen(fd, buff, (size_t)bytes) != (size_t)bytes) { close(fd); gzclose(gz); @@ -1226,9 +1234,11 @@ static cl_error_t cli_scangzip(cli_ctx *ctx) return ret; } close(fd); - if (!ctx->engine->keeptmp) - if (cli_unlink(tmpname)) + if (!ctx->engine->keeptmp) { + if (cli_unlink(tmpname)) { ret = CL_EUNLINK; + } + } free(tmpname); return ret; @@ -1301,8 +1311,9 @@ static cl_error_t cli_scanbzip(cli_ctx *ctx) return CL_EWRITE; } - if (cli_checklimits("Bzip", ctx, size, 0, 0) != CL_CLEAN) + if (cli_checklimits("Bzip", ctx, size, 0, 0) != CL_CLEAN) { break; + } strm.next_out = buf; strm.avail_out = sizeof(buf); @@ -1323,9 +1334,11 @@ static cl_error_t cli_scanbzip(cli_ctx *ctx) return ret; } close(fd); - if (!ctx->engine->keeptmp) - if (cli_unlink(tmpname)) + if (!ctx->engine->keeptmp) { + if (cli_unlink(tmpname)) { ret = CL_EUNLINK; + } + } free(tmpname); return ret; @@ -1449,9 +1462,11 @@ static cl_error_t cli_scanszdd(cli_ctx *ctx) if (ret != CL_SUCCESS) { /* CL_VIRUS or some error */ close(ofd); - if (!ctx->engine->keeptmp) - if (cli_unlink(tmpname)) + if (!ctx->engine->keeptmp) { + if (cli_unlink(tmpname)) { ret = CL_EUNLINK; + } + } free(tmpname); return ret; } @@ -1459,9 +1474,11 @@ static cl_error_t cli_scanszdd(cli_ctx *ctx) cli_dbgmsg("MSEXPAND: Decompressed into %s\n", tmpname); ret = cli_magic_scan_desc(ofd, tmpname, ctx, NULL, LAYER_ATTRIBUTES_NONE); close(ofd); - if (!ctx->engine->keeptmp) - if (cli_unlink(tmpname)) + if (!ctx->engine->keeptmp) { + if (cli_unlink(tmpname)) { ret = CL_EUNLINK; + } + } free(tmpname); return ret; @@ -1877,8 +1894,9 @@ static cl_error_t cli_ole2_tempdir_scan_vba(const char *dir, cli_ctx *ctx, struc if (NULL != data) { /* cli_dbgmsg("Project content:\n%s", data); */ - if (ctx->scanned) + if (ctx->scanned) { *ctx->scanned += data_len / CL_COUNT_PRECISION; + } if (ctx->engine->keeptmp) { if (CL_SUCCESS != (status = cli_gentempfd(ctx->sub_tmpdir, &proj_contents_fname, &proj_contents_fd))) { cli_warnmsg("WARNING: VBA project '%s_%u' cannot be dumped to file\n", vba_project->name[i], j); @@ -2673,8 +2691,9 @@ static cl_error_t cli_scanscript(cli_ctx *ctx) uint64_t curr_len; struct cli_target_info info; - if (!ctx || !ctx->engine->root) + if (!ctx || !ctx->engine->root) { return CL_ENULLARG; + } map = ctx->fmap; curr_len = map->len; @@ -2719,8 +2738,9 @@ static cl_error_t cli_scanscript(cli_ctx *ctx) cli_dbgmsg("cli_scanscript: Can't generate temporary file/descriptor\n"); goto done; } - if (ctx->engine->keeptmp) + if (ctx->engine->keeptmp) { cli_dbgmsg("cli_scanscript: saving normalized file to %s\n", tmpname); + } } mdata[0] = &tmdata; @@ -2731,8 +2751,9 @@ static cl_error_t cli_scanscript(cli_ctx *ctx) size_t map_off = 0; while (map_off < map->len) { size_t written; - if (!(written = text_normalize_map(&state, map, map_off))) + if (!(written = text_normalize_map(&state, map, map_off))) { break; + } map_off += written; if (write(ofd, state.out, state.out_pos) == -1) { @@ -2773,8 +2794,9 @@ static cl_error_t cli_scanscript(cli_ctx *ctx) if (target_ac_root) { cli_targetinfo(&info, 7, ctx); ret = cli_ac_caloff(target_ac_root, &tmdata, &info); - if (ret) + if (ret) { goto done; + } } while (1) { @@ -2795,18 +2817,21 @@ static cl_error_t cli_scanscript(cli_ctx *ctx) goto done; } - if (ctx->scanned) + 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) + 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) + if (!len) { break; + } if (!buff || text_normalize_buffer(&state, buff, len) != len) { cli_dbgmsg("cli_scanscript: short read during normalizing\n"); } @@ -3143,8 +3168,9 @@ static cl_error_t cli_scantar(cli_ctx *ctx, unsigned int posix) cli_dbgmsg("in cli_scantar()\n"); /* generate temporary directory */ - if (!(dir = cli_gentemp_with_prefix(ctx->sub_tmpdir, "tar-tmp"))) + if (!(dir = cli_gentemp_with_prefix(ctx->sub_tmpdir, "tar-tmp"))) { return CL_EMEM; + } if (mkdir(dir, 0700)) { cli_errmsg("Tar: Can't create temporary directory %s\n", dir); @@ -3154,8 +3180,9 @@ static cl_error_t cli_scantar(cli_ctx *ctx, unsigned int posix) ret = cli_untar(dir, posix, ctx); - if (!ctx->engine->keeptmp) + if (!ctx->engine->keeptmp) { cli_rmdirs(dir); + } free(dir); return ret; @@ -3168,8 +3195,9 @@ static cl_error_t cli_scanscrenc(cli_ctx *ctx) cli_dbgmsg("in cli_scanscrenc()\n"); - if (!(tempname = cli_gentemp_with_prefix(ctx->sub_tmpdir, "screnc-tmp"))) + if (!(tempname = cli_gentemp_with_prefix(ctx->sub_tmpdir, "screnc-tmp"))) { return CL_EMEM; + } if (mkdir(tempname, 0700)) { cli_dbgmsg("CHM: Can't create temporary directory %s\n", tempname); @@ -3177,11 +3205,13 @@ static cl_error_t cli_scanscrenc(cli_ctx *ctx) return CL_ETMPDIR; } - if (html_screnc_decode(ctx->fmap, tempname)) + if (html_screnc_decode(ctx->fmap, tempname)) { ret = cli_magic_scan_dir(tempname, ctx, LAYER_ATTRIBUTES_NONE); + } - if (!ctx->engine->keeptmp) + if (!ctx->engine->keeptmp) { cli_rmdirs(tempname); + } free(tempname); return ret; @@ -3191,8 +3221,9 @@ static cl_error_t cli_scanriff(cli_ctx *ctx) { cl_error_t ret = CL_CLEAN; - if (cli_check_riff_exploit(ctx) == 2) + if (cli_check_riff_exploit(ctx) == 2) { ret = cli_append_potentially_unwanted(ctx, "Heuristics.Exploit.W32.MS05-002"); + } return ret; } @@ -3228,8 +3259,9 @@ static cl_error_t cli_scancryptff(cli_ctx *ctx) } for (; (src = fmap_need_off_once_len(ctx->fmap, pos, FILEBUFF, &bread)) && bread; pos += bread) { - for (i = 0; i < bread; i++) + for (i = 0; i < bread; i++) { dest[i] = src[i] ^ (unsigned char)0xff; + } if (cli_writen(ndesc, dest, bread) == (size_t)-1) { cli_dbgmsg("CryptFF: Can't write to descriptor %d\n", ndesc); free(dest); @@ -3264,8 +3296,9 @@ static cl_error_t cli_scanpdf(cli_ctx *ctx, off_t offset) cl_error_t ret; char *dir = cli_gentemp_with_prefix(ctx->sub_tmpdir, "pdf-tmp"); - if (!dir) + if (!dir) { return CL_EMEM; + } if (mkdir(dir, 0700)) { cli_dbgmsg("Can't create temporary directory for PDF file %s\n", dir); @@ -3275,8 +3308,9 @@ static cl_error_t cli_scanpdf(cli_ctx *ctx, off_t offset) ret = cli_pdf(dir, ctx, offset); - if (!ctx->engine->keeptmp) + if (!ctx->engine->keeptmp) { cli_rmdirs(dir); + } free(dir); return ret; @@ -3287,8 +3321,9 @@ static cl_error_t cli_scantnef(cli_ctx *ctx) cl_error_t ret; char *dir = cli_gentemp_with_prefix(ctx->sub_tmpdir, "tnef-tmp"); - if (!dir) + if (!dir) { return CL_EMEM; + } if (mkdir(dir, 0700)) { cli_dbgmsg("Can't create temporary directory for tnef file %s\n", dir); @@ -3298,11 +3333,13 @@ static cl_error_t cli_scantnef(cli_ctx *ctx) ret = cli_tnef(dir, ctx); - if (ret == CL_CLEAN) + if (ret == CL_CLEAN) { ret = cli_magic_scan_dir(dir, ctx, LAYER_ATTRIBUTES_NONE); + } - if (!ctx->engine->keeptmp) + if (!ctx->engine->keeptmp) { cli_rmdirs(dir); + } free(dir); return ret; @@ -3313,8 +3350,9 @@ static cl_error_t cli_scanuuencoded(cli_ctx *ctx) cl_error_t ret; char *dir = cli_gentemp_with_prefix(ctx->sub_tmpdir, "uuencoded-tmp"); - if (!dir) + if (!dir) { return CL_EMEM; + } if (mkdir(dir, 0700)) { cli_dbgmsg("Can't create temporary directory for uuencoded file %s\n", dir); @@ -3324,11 +3362,13 @@ static cl_error_t cli_scanuuencoded(cli_ctx *ctx) ret = cli_uuencode(dir, ctx->fmap); - if (ret == CL_CLEAN) + if (ret == CL_CLEAN) { ret = cli_magic_scan_dir(dir, ctx, LAYER_ATTRIBUTES_NONE); + } - if (!ctx->engine->keeptmp) + if (!ctx->engine->keeptmp) { cli_rmdirs(dir); + } free(dir); return ret; @@ -3390,36 +3430,41 @@ static cl_error_t cli_scan_structured(cli_ctx *ctx) int (*ccfunc)(const unsigned char *buffer, size_t length, int cc_only); int (*ssnfunc)(const unsigned char *buffer, size_t length); - if (ctx == NULL) + if (ctx == NULL) { return CL_ENULLARG; + } map = ctx->fmap; - if (ctx->engine->min_cc_count == 1) + if (ctx->engine->min_cc_count == 1) { ccfunc = dlp_has_cc; - else + } else { ccfunc = dlp_get_cc_count; + } switch (SCAN_HEURISTIC_STRUCTURED_SSN_NORMAL | SCAN_HEURISTIC_STRUCTURED_SSN_STRIPPED) { case (CL_SCAN_HEURISTIC_STRUCTURED_SSN_NORMAL | CL_SCAN_HEURISTIC_STRUCTURED_SSN_STRIPPED): - if (ctx->engine->min_ssn_count == 1) + if (ctx->engine->min_ssn_count == 1) { ssnfunc = dlp_has_ssn; - else + } else { ssnfunc = dlp_get_ssn_count; + } break; case CL_SCAN_HEURISTIC_STRUCTURED_SSN_NORMAL: - if (ctx->engine->min_ssn_count == 1) + if (ctx->engine->min_ssn_count == 1) { ssnfunc = dlp_has_normal_ssn; - else + } else { ssnfunc = dlp_get_normal_ssn_count; + } break; case CL_SCAN_HEURISTIC_STRUCTURED_SSN_STRIPPED: - if (ctx->engine->min_ssn_count == 1) + if (ctx->engine->min_ssn_count == 1) { ssnfunc = dlp_has_stripped_ssn; - else + } else { ssnfunc = dlp_get_stripped_ssn_count; + } break; default: @@ -3468,8 +3513,9 @@ static cl_error_t cli_scanembpe(cli_ctx *ctx, off_t offset) unsigned int corrupted_input; tmpname = cli_gentemp_with_prefix(ctx->sub_tmpdir, "embedded-pe"); - if (!tmpname) + if (!tmpname) { return CL_EMEM; + } if ((fd = open(tmpname, O_RDWR | O_CREAT | O_TRUNC | O_BINARY, S_IRUSR | S_IWUSR)) < 0) { cli_errmsg("cli_scanembpe: Can't create file %s\n", tmpname); @@ -3480,8 +3526,9 @@ static cl_error_t cli_scanembpe(cli_ctx *ctx, off_t offset) todo = map->len - offset; while (1) { bytes = MIN(todo, map->pgsz); - if (!bytes) + if (!bytes) { break; + } if (!(buff = fmap_need_off_once(map, offset + size, bytes))) { close(fd); @@ -3497,8 +3544,9 @@ static cl_error_t cli_scanembpe(cli_ctx *ctx, off_t offset) size += bytes; todo -= bytes; - if (cli_checklimits("cli_scanembpe", ctx, size, 0, 0) != CL_CLEAN) + if (cli_checklimits("cli_scanembpe", ctx, size, 0, 0) != CL_CLEAN) { break; + } if (cli_writen(fd, buff, bytes) != bytes) { cli_dbgmsg("cli_scanembpe: Can't write to temporary file\n"); @@ -3602,14 +3650,16 @@ static inline void perf_init(cli_ctx *ctx) uint64_t kt, ut; unsigned i; - if (!SCAN_DEV_COLLECT_PERF_INFO) + if (!SCAN_DEV_COLLECT_PERF_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) + perf_events[i].type, multiple_sum) == -1) { continue; + } } cli_event_time_start(ctx->perf, PERFT_SCAN); get_thread_times(&kt, &ut); @@ -3626,8 +3676,9 @@ static inline void perf_done(cli_ctx *ctx) char *pend; cli_events_t *perf = ctx->perf; - if (!perf) + if (!perf) { return; + } p = timestr; pend = timestr + sizeof(timestr) - 1; @@ -3643,10 +3694,11 @@ static inline void perf_done(cli_ctx *ctx) unsigned count; cli_event_get(perf, perf_events[i].id, &val, &count); - if (p < pend) + 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); @@ -4970,48 +5022,57 @@ cl_error_t cli_magic_scan(cli_ctx *ctx, cli_file_t type) break; case CL_TYPE_HWP3: - if (SCAN_PARSE_HWP3 && (DCONF_DOC & DOC_CONF_HWP)) + if (SCAN_PARSE_HWP3 && (DCONF_DOC & DOC_CONF_HWP)) { ret = cli_scanhwp3(ctx); + } break; case CL_TYPE_HWPOLE2: - if (SCAN_PARSE_OLE2 && (DCONF_ARCH & ARCH_CONF_OLE2)) + if (SCAN_PARSE_OLE2 && (DCONF_ARCH & ARCH_CONF_OLE2)) { ret = cli_scanhwpole2(ctx); + } break; case CL_TYPE_XML_WORD: - if (SCAN_PARSE_XMLDOCS && (DCONF_DOC & DOC_CONF_MSXML)) + if (SCAN_PARSE_XMLDOCS && (DCONF_DOC & DOC_CONF_MSXML)) { ret = cli_scanmsxml(ctx); + } break; case CL_TYPE_XML_XL: - if (SCAN_PARSE_XMLDOCS && (DCONF_DOC & DOC_CONF_MSXML)) + if (SCAN_PARSE_XMLDOCS && (DCONF_DOC & DOC_CONF_MSXML)) { ret = cli_scanmsxml(ctx); + } break; case CL_TYPE_XML_HWP: - if (SCAN_PARSE_XMLDOCS && (DCONF_DOC & DOC_CONF_HWP)) + if (SCAN_PARSE_XMLDOCS && (DCONF_DOC & DOC_CONF_HWP)) { ret = cli_scanhwpml(ctx); + } break; case CL_TYPE_XDP: - if (SCAN_PARSE_PDF && (DCONF_DOC & DOC_CONF_PDF)) + if (SCAN_PARSE_PDF && (DCONF_DOC & DOC_CONF_PDF)) { ret = cli_scanxdp(ctx); + } break; case CL_TYPE_RAR: - if (have_rar && SCAN_PARSE_ARCHIVE && (DCONF_ARCH & ARCH_CONF_RAR)) + if (have_rar && SCAN_PARSE_ARCHIVE && (DCONF_ARCH & ARCH_CONF_RAR)) { ret = cli_scanrar(ctx); + } break; case CL_TYPE_EGG: - if (SCAN_PARSE_ARCHIVE && (DCONF_ARCH & ARCH_CONF_EGG)) + if (SCAN_PARSE_ARCHIVE && (DCONF_ARCH & ARCH_CONF_EGG)) { ret = cli_scanegg(ctx); + } break; case CL_TYPE_ONENOTE: - if (SCAN_PARSE_ONENOTE && (DCONF_ARCH & DOC_CONF_ONENOTE)) + if (SCAN_PARSE_ONENOTE && (DCONF_ARCH & DOC_CONF_ONENOTE)) { ret = scan_onenote(ctx); + } break; case CL_TYPE_ALZ: @@ -5021,8 +5082,9 @@ cl_error_t cli_magic_scan(cli_ctx *ctx, cli_file_t type) break; case CL_TYPE_LHA_LZH: - if (SCAN_PARSE_ARCHIVE && (DCONF_ARCH & ARCH_CONF_LHA_LZH)) + if (SCAN_PARSE_ARCHIVE && (DCONF_ARCH & ARCH_CONF_LHA_LZH)) { ret = scan_lha_lzh(ctx); + } break; case CL_TYPE_OOXML_WORD: @@ -5049,163 +5111,195 @@ cl_error_t cli_magic_scan(cli_ctx *ctx, cli_file_t type) } /* fall-through */ case CL_TYPE_ZIP: - if (SCAN_PARSE_ARCHIVE && (DCONF_ARCH & ARCH_CONF_ZIP)) + if (SCAN_PARSE_ARCHIVE && (DCONF_ARCH & ARCH_CONF_ZIP)) { ret = cli_unzip(ctx); + } break; case CL_TYPE_GZ: - if (SCAN_PARSE_ARCHIVE && (DCONF_ARCH & ARCH_CONF_GZ)) + if (SCAN_PARSE_ARCHIVE && (DCONF_ARCH & ARCH_CONF_GZ)) { ret = cli_scangzip(ctx); + } break; case CL_TYPE_BZ: - if (SCAN_PARSE_ARCHIVE && (DCONF_ARCH & ARCH_CONF_BZ)) + if (SCAN_PARSE_ARCHIVE && (DCONF_ARCH & ARCH_CONF_BZ)) { ret = cli_scanbzip(ctx); + } break; case CL_TYPE_XZ: - if (SCAN_PARSE_ARCHIVE && (DCONF_ARCH & ARCH_CONF_XZ)) + if (SCAN_PARSE_ARCHIVE && (DCONF_ARCH & ARCH_CONF_XZ)) { ret = cli_scanxz(ctx); + } break; case CL_TYPE_GPT: - if (SCAN_PARSE_ARCHIVE && (DCONF_ARCH & ARCH_CONF_GPT)) + if (SCAN_PARSE_ARCHIVE && (DCONF_ARCH & ARCH_CONF_GPT)) { ret = cli_scangpt(ctx, 0); + } break; case CL_TYPE_APM: - if (SCAN_PARSE_ARCHIVE && (DCONF_ARCH & ARCH_CONF_APM)) + if (SCAN_PARSE_ARCHIVE && (DCONF_ARCH & ARCH_CONF_APM)) { ret = cli_scanapm(ctx); + } break; case CL_TYPE_ARJ: - if (SCAN_PARSE_ARCHIVE && (DCONF_ARCH & ARCH_CONF_ARJ)) + if (SCAN_PARSE_ARCHIVE && (DCONF_ARCH & ARCH_CONF_ARJ)) { ret = cli_scanarj(ctx); + } break; case CL_TYPE_NULSFT: - if (SCAN_PARSE_ARCHIVE && (DCONF_ARCH & ARCH_CONF_NSIS)) + if (SCAN_PARSE_ARCHIVE && (DCONF_ARCH & ARCH_CONF_NSIS)) { ret = cli_scannulsft(ctx, 0); + } break; case CL_TYPE_AUTOIT: - if (SCAN_PARSE_ARCHIVE && (DCONF_ARCH & ARCH_CONF_AUTOIT)) + if (SCAN_PARSE_ARCHIVE && (DCONF_ARCH & ARCH_CONF_AUTOIT)) { ret = cli_scanautoit(ctx, 23); + } break; case CL_TYPE_MSSZDD: - if (SCAN_PARSE_ARCHIVE && (DCONF_ARCH & ARCH_CONF_SZDD)) + if (SCAN_PARSE_ARCHIVE && (DCONF_ARCH & ARCH_CONF_SZDD)) { ret = cli_scanszdd(ctx); + } break; case CL_TYPE_MSCAB: - if (SCAN_PARSE_ARCHIVE && (DCONF_ARCH & ARCH_CONF_CAB)) + if (SCAN_PARSE_ARCHIVE && (DCONF_ARCH & ARCH_CONF_CAB)) { ret = cli_scanmscab(ctx, 0); + } break; case CL_TYPE_HTML: - if (SCAN_PARSE_HTML && (DCONF_DOC & DOC_CONF_HTML)) + if (SCAN_PARSE_HTML && (DCONF_DOC & DOC_CONF_HTML)) { ret = cli_scanhtml(ctx); + } break; case CL_TYPE_HTML_UTF16: - if (SCAN_PARSE_HTML && (DCONF_DOC & DOC_CONF_HTML)) + if (SCAN_PARSE_HTML && (DCONF_DOC & DOC_CONF_HTML)) { ret = cli_scanhtml_utf16(ctx); + } break; case CL_TYPE_SCRIPT: - if ((DCONF_DOC & DOC_CONF_SCRIPT) && dettype != CL_TYPE_HTML) + if ((DCONF_DOC & DOC_CONF_SCRIPT) && dettype != CL_TYPE_HTML) { ret = cli_scanscript(ctx); + } break; case CL_TYPE_SWF: - if (SCAN_PARSE_SWF && (DCONF_DOC & DOC_CONF_SWF)) + if (SCAN_PARSE_SWF && (DCONF_DOC & DOC_CONF_SWF)) { ret = cli_scanswf(ctx); + } break; case CL_TYPE_RTF: - if (SCAN_PARSE_ARCHIVE && (DCONF_DOC & DOC_CONF_RTF)) + if (SCAN_PARSE_ARCHIVE && (DCONF_DOC & DOC_CONF_RTF)) { ret = cli_scanrtf(ctx); + } break; case CL_TYPE_MAIL: - if (SCAN_PARSE_MAIL && (DCONF_MAIL & MAIL_CONF_MBOX)) + if (SCAN_PARSE_MAIL && (DCONF_MAIL & MAIL_CONF_MBOX)) { ret = cli_scanmail(ctx); + } break; case CL_TYPE_MHTML: - if (SCAN_PARSE_MAIL && (DCONF_MAIL & MAIL_CONF_MBOX)) + if (SCAN_PARSE_MAIL && (DCONF_MAIL & MAIL_CONF_MBOX)) { ret = cli_scanmail(ctx); + } break; case CL_TYPE_TNEF: - if (SCAN_PARSE_MAIL && (DCONF_MAIL & MAIL_CONF_TNEF)) + if (SCAN_PARSE_MAIL && (DCONF_MAIL & MAIL_CONF_TNEF)) { ret = cli_scantnef(ctx); + } break; case CL_TYPE_UUENCODED: - if (DCONF_OTHER & OTHER_CONF_UUENC) + if (DCONF_OTHER & OTHER_CONF_UUENC) { ret = cli_scanuuencoded(ctx); + } break; case CL_TYPE_MSCHM: - if (SCAN_PARSE_ARCHIVE && (DCONF_ARCH & ARCH_CONF_CHM)) + if (SCAN_PARSE_ARCHIVE && (DCONF_ARCH & ARCH_CONF_CHM)) { ret = cli_scanmschm(ctx); + } break; case CL_TYPE_MSOLE2: - if (SCAN_PARSE_OLE2 && (DCONF_ARCH & ARCH_CONF_OLE2)) + if (SCAN_PARSE_OLE2 && (DCONF_ARCH & ARCH_CONF_OLE2)) { ret = cli_scanole2(ctx); + } break; case CL_TYPE_7Z: - if (SCAN_PARSE_ARCHIVE && (DCONF_ARCH & ARCH_CONF_7Z)) + if (SCAN_PARSE_ARCHIVE && (DCONF_ARCH & ARCH_CONF_7Z)) { ret = cli_7unz(ctx, 0); + } break; case CL_TYPE_POSIX_TAR: - if (SCAN_PARSE_ARCHIVE && (DCONF_ARCH & ARCH_CONF_TAR)) + if (SCAN_PARSE_ARCHIVE && (DCONF_ARCH & ARCH_CONF_TAR)) { ret = cli_scantar(ctx, 1); + } break; case CL_TYPE_OLD_TAR: - if (SCAN_PARSE_ARCHIVE && (DCONF_ARCH & ARCH_CONF_TAR)) + if (SCAN_PARSE_ARCHIVE && (DCONF_ARCH & ARCH_CONF_TAR)) { ret = cli_scantar(ctx, 0); + } break; case CL_TYPE_CPIO_OLD: - if (SCAN_PARSE_ARCHIVE && (DCONF_ARCH & ARCH_CONF_CPIO)) + if (SCAN_PARSE_ARCHIVE && (DCONF_ARCH & ARCH_CONF_CPIO)) { ret = cli_scancpio_old(ctx); + } break; case CL_TYPE_CPIO_ODC: - if (SCAN_PARSE_ARCHIVE && (DCONF_ARCH & ARCH_CONF_CPIO)) + if (SCAN_PARSE_ARCHIVE && (DCONF_ARCH & ARCH_CONF_CPIO)) { ret = cli_scancpio_odc(ctx); + } break; case CL_TYPE_CPIO_NEWC: - if (SCAN_PARSE_ARCHIVE && (DCONF_ARCH & ARCH_CONF_CPIO)) + if (SCAN_PARSE_ARCHIVE && (DCONF_ARCH & ARCH_CONF_CPIO)) { ret = cli_scancpio_newc(ctx, 0); + } break; case CL_TYPE_CPIO_CRC: - if (SCAN_PARSE_ARCHIVE && (DCONF_ARCH & ARCH_CONF_CPIO)) + if (SCAN_PARSE_ARCHIVE && (DCONF_ARCH & ARCH_CONF_CPIO)) { ret = cli_scancpio_newc(ctx, 1); + } break; case CL_TYPE_BINHEX: - if (SCAN_PARSE_ARCHIVE && (DCONF_ARCH & ARCH_CONF_BINHEX)) + if (SCAN_PARSE_ARCHIVE && (DCONF_ARCH & ARCH_CONF_BINHEX)) { ret = cli_binhex(ctx); + } break; case CL_TYPE_SCRENC: - if (DCONF_OTHER & OTHER_CONF_SCRENC) + if (DCONF_OTHER & OTHER_CONF_SCRENC) { ret = cli_scanscrenc(ctx); + } break; case CL_TYPE_RIFF: - if (SCAN_HEURISTICS && (DCONF_OTHER & OTHER_CONF_RIFF)) + if (SCAN_HEURISTICS && (DCONF_OTHER & OTHER_CONF_RIFF)) { ret = cli_scanriff(ctx); + } break; case CL_TYPE_GRAPHICS: { @@ -5313,53 +5407,62 @@ cl_error_t cli_magic_scan(cli_ctx *ctx, cli_file_t type) } case CL_TYPE_CRYPTFF: - if (DCONF_OTHER & OTHER_CONF_CRYPTFF) + if (DCONF_OTHER & OTHER_CONF_CRYPTFF) { ret = cli_scancryptff(ctx); + } break; case CL_TYPE_ELF: - if (SCAN_PARSE_ELF && ctx->dconf->elf) + if (SCAN_PARSE_ELF && ctx->dconf->elf) { ret = cli_scanelf(ctx); + } break; case CL_TYPE_MACHO: - if (ctx->dconf->macho) + if (ctx->dconf->macho) { ret = cli_scanmacho(ctx, NULL); + } break; case CL_TYPE_MACHO_UNIBIN: - if (ctx->dconf->macho) + if (ctx->dconf->macho) { ret = cli_scanmacho_unibin(ctx); + } break; case CL_TYPE_SIS: - if (SCAN_PARSE_ARCHIVE && (DCONF_ARCH & ARCH_CONF_SIS)) + if (SCAN_PARSE_ARCHIVE && (DCONF_ARCH & ARCH_CONF_SIS)) { ret = cli_scansis(ctx); + } break; case CL_TYPE_XAR: - if (SCAN_PARSE_ARCHIVE && (DCONF_ARCH & ARCH_CONF_XAR)) + if (SCAN_PARSE_ARCHIVE && (DCONF_ARCH & ARCH_CONF_XAR)) { ret = cli_scanxar(ctx); + } break; case CL_TYPE_PART_HFSPLUS: - if (SCAN_PARSE_ARCHIVE && (DCONF_ARCH & ARCH_CONF_HFSPLUS)) + if (SCAN_PARSE_ARCHIVE && (DCONF_ARCH & ARCH_CONF_HFSPLUS)) { ret = cli_scanhfsplus(ctx); + } break; case CL_TYPE_BINARY_DATA: case CL_TYPE_TEXT_UTF16BE: - if (SCAN_HEURISTICS && (DCONF_OTHER & OTHER_CONF_MYDOOMLOG)) + if (SCAN_HEURISTICS && (DCONF_OTHER & OTHER_CONF_MYDOOMLOG)) { ret = cli_check_mydoom_log(ctx); + } break; case CL_TYPE_TEXT_ASCII: - if (SCAN_HEURISTIC_STRUCTURED && (DCONF_OTHER & OTHER_CONF_DLP)) + if (SCAN_HEURISTIC_STRUCTURED && (DCONF_OTHER & OTHER_CONF_DLP)) { /* TODO: consider calling this from cli_scanscript() for * a normalised text */ ret = cli_scan_structured(ctx); + } break; default: @@ -5455,8 +5558,9 @@ cl_error_t cli_magic_scan(cli_ctx *ctx, cli_file_t type) break; case CL_TYPE_PDF: /* FIXMELIMITS: pdf should be an archive! */ - if (SCAN_PARSE_PDF && (DCONF_DOC & DOC_CONF_PDF)) + if (SCAN_PARSE_PDF && (DCONF_DOC & DOC_CONF_PDF)) { ret = cli_scanpdf(ctx, 0); + } break; default: @@ -5660,8 +5764,9 @@ static cl_error_t magic_scan_nested_fmap_type(cl_fmap_t *map, size_t offset, siz goto done; } - if (!length) + if (!length) { length = map->len - offset; + } if (length > map->len - offset) { cli_dbgmsg("magic_scan_nested_fmap_type: Data truncated: %zu -> %zu\n", @@ -6264,8 +6369,9 @@ cl_error_t cl_scanfile_callback(const char *filename, const char **virname, unsi cl_error_t ret; const char *fname = cli_to_utf8_maybe_alloc(filename); - if (!fname) + if (!fname) { return CL_EARG; + } if ((fd = safe_open(fname, O_RDONLY | O_BINARY)) == -1) { if (errno == EACCES) { @@ -6275,8 +6381,9 @@ cl_error_t cl_scanfile_callback(const char *filename, const char **virname, unsi } } - if (fname != filename) + if (fname != filename) { free((char *)fname); + } ret = cl_scandesc_callback(fd, filename, virname, scanned, engine, scanoptions, context); close(fd); diff --git a/libclamav/sf_base64decode.c b/libclamav/sf_base64decode.c index 21486f14e4..61657f9495 100644 --- a/libclamav/sf_base64decode.c +++ b/libclamav/sf_base64decode.c @@ -124,8 +124,9 @@ int sf_base64decode(uint8_t *inbuf, size_t inbuf_size, uint8_t *outbuf, size_t o cursor++; } - if (error) + if (error) { return (-1); - else + } else { return (0); + } } diff --git a/libclamav/sis.c b/libclamav/sis.c index 0fe74554f8..a062f53221 100644 --- a/libclamav/sis.c +++ b/libclamav/sis.c @@ -74,15 +74,17 @@ cl_error_t cli_scansis(cli_ctx *ctx) cli_dbgmsg("in scansis()\n"); - if (!(tmpd = cli_gentemp_with_prefix(ctx->sub_tmpdir, "sis-tmp"))) + if (!(tmpd = cli_gentemp_with_prefix(ctx->sub_tmpdir, "sis-tmp"))) { return CL_ETMPDIR; + } if (mkdir(tmpd, 0700)) { cli_dbgmsg("SIS: Can't create temporary directory %s\n", tmpd); free(tmpd); return CL_ETMPDIR; } - if (ctx->engine->keeptmp) + if (ctx->engine->keeptmp) { cli_dbgmsg("SIS: Extracting files to %s\n", tmpd); + } if (fmap_readn(map, &uid, 0, SIZEOF_HEADER_UUIDS) != SIZEOF_HEADER_UUIDS) { cli_dbgmsg("SIS: unable to read UIDs\n"); @@ -101,8 +103,9 @@ cl_error_t cli_scansis(cli_ctx *ctx) i = CL_EFORMAT; } - if (!ctx->engine->keeptmp) + if (!ctx->engine->keeptmp) { cli_rmdirs(tmpd); + } free(tmpd); return i; @@ -188,8 +191,12 @@ static char *getsistring(fmap_t *map, uint32_t ptr, uint32_t len) char *name; uint32_t i; - if (!len) return NULL; - if (len > 400) len = 400; + if (!len) { + return NULL; + } + if (len > 400) { + len = 400; + } name = cli_max_malloc(len + 1); if (!name) { cli_dbgmsg("SIS: OOM\n"); @@ -200,7 +207,9 @@ static char *getsistring(fmap_t *map, uint32_t ptr, uint32_t len) free(name); return NULL; } - for (i = 0; i < len; i += 2) name[i / 2] = name[i]; + for (i = 0; i < len; i += 2) { + name[i / 2] = name[i]; + } name[i / 2] = '\0'; return name; } @@ -307,8 +316,9 @@ static cl_error_t real_scansis(cli_ctx *ctx, const char *tmpd) cli_dbgmsg("SIS: OOM\n"); goto done; } - for (i = 0; i < sis.langs; i++) + for (i = 0; i < sis.langs; i++) { alangs[i] = (size_t)EC16(llangs[i]) < MAXLANG ? sislangs[EC16(llangs[i])] : sislangs[0]; + } if (!sis.pnames) { cli_dbgmsg("SIS: Application without a name?\n"); @@ -466,7 +476,9 @@ static cl_error_t real_scansis(cli_ctx *ctx, const char *tmpd) continue; } - if (cli_checklimits("sis", ctx, lens[j], 0, 0) != CL_CLEAN) continue; + if (cli_checklimits("sis", ctx, lens[j], 0, 0) != CL_CLEAN) { + continue; + } cli_dbgmsg("\tUnpacking lang#%d - ptr:%x compressed size:%x original (decompressed) size:%x\n", j, ptrs[j], lens[j], olens[j]); if (!(comp = fmap_need_off_once(map, ptrs[j], lens[j]))) { @@ -478,11 +490,11 @@ static cl_error_t real_scansis(cli_ctx *ctx, const char *tmpd) /* * The compressed flag was set. Try to decompress it. */ - if (olens[j] <= lens[j] * 3 && cli_checklimits("sis", ctx, lens[j] * 3, 0, 0) == CL_CLEAN) + if (olens[j] <= lens[j] * 3 && cli_checklimits("sis", ctx, lens[j] * 3, 0, 0) == CL_CLEAN) { olen = lens[j] * 3; - else if (cli_checklimits("sis", ctx, olens[j], 0, 0) == CL_CLEAN) + } else if (cli_checklimits("sis", ctx, olens[j], 0, 0) == CL_CLEAN) { olen = olens[j]; - else { + } else { continue; } @@ -662,7 +674,9 @@ static inline int getd(struct SISTREAM *s, uint32_t *v) static inline int getsize(struct SISTREAM *s) { uint32_t *fsize = &s->fsize[s->level]; - if (getd(s, fsize) || !*fsize || (*fsize) >> 31 || (s->level && *fsize > s->fsize[s->level - 1] * 2)) return 1; + if (getd(s, fsize) || !*fsize || (*fsize) >> 31 || (s->level && *fsize > s->fsize[s->level - 1] * 2)) { + return 1; + } /* To handle crafted archives we allow the content to overflow the container but only up to 2 times the container size */ s->fnext[s->level] = s->pos - s->sleft + *fsize; return 0; @@ -671,13 +685,15 @@ static inline int getsize(struct SISTREAM *s) static inline int getfield(struct SISTREAM *s, uint32_t *field) { int ret; - if (!(ret = getd(s, field))) + if (!(ret = getd(s, field))) { ret = getsize(s); + } if (!ret) { - if (*field < T_MAXVALUE) + if (*field < T_MAXVALUE) { cli_dbgmsg("SIS: %d:Got %s(%x) field with size %x\n", s->level, sisfields[*field], *field, s->fsize[s->level]); - else + } else { cli_dbgmsg("SIS: %d:Got invalid(%x) field with size %x\n", s->level, *field, s->fsize[s->level]); + } } return ret; } @@ -686,12 +702,13 @@ static inline int skip(struct SISTREAM *s, uint32_t size) { long seekto; cli_dbgmsg("SIS: skipping %x\n", size); - if (s->sleft >= size) + if (s->sleft >= size) { s->sleft -= size; - else { + } else { seekto = size - s->sleft; - if (seekto < 0) /* in case sizeof(long)==sizeof(uint32_t) */ + if (seekto < 0) { /* in case sizeof(long)==sizeof(uint32_t) */ return 1; + } s->pos += seekto; /* s->sleft = s->smax = fread(s->buff,1,BUFSIZ,s->f); */ s->sleft = s->smax = 0; @@ -726,43 +743,57 @@ static cl_error_t real_scansis9x(cli_ctx *ctx, const char *tmpd) s->sleft = 0; s->level = 0; - if (getfield(s, &field) || field != T_CONTENTS) + if (getfield(s, &field) || field != T_CONTENTS) { return CL_CLEAN; + } s->level++; for (i = 0; i < 3;) { - if (getfield(s, &field)) return CL_CLEAN; + if (getfield(s, &field)) { + return CL_CLEAN; + } for (; i < 3; i++) { if (field == optst[i]) { - if (skipthis(s)) return CL_CLEAN; + if (skipthis(s)) { + return CL_CLEAN; + } i++; break; } } } - if (field != T_COMPRESSED) return CL_CLEAN; + if (field != T_COMPRESSED) { + return CL_CLEAN; + } i = 0; while (1) { /* 1DATA */ - if (getfield(s, &field) || field != T_DATA) break; + if (getfield(s, &field) || field != T_DATA) { + break; + } s->level++; while (1) { /* DATA::ARRAY */ uint32_t atype; - if (getfield(s, &field) || field != T_ARRAY || getd(s, &atype) || atype != T_DATAUNIT || s->fsize[s->level] < 4) break; + if (getfield(s, &field) || field != T_ARRAY || getd(s, &atype) || atype != T_DATAUNIT || s->fsize[s->level] < 4) { + break; + } s->fsize[s->level] -= 4; s->level++; while (s->fsize[s->level - 1] && !getsize(s)) { /* FOREACH DATA::ARRAY::DATAUNITs */ cli_dbgmsg("SIS: %d:Got dataunit element with size %x\n", s->level, s->fsize[s->level]); - if (ALIGN4(s->fsize[s->level]) < s->fsize[s->level - 1]) + if (ALIGN4(s->fsize[s->level]) < s->fsize[s->level - 1]) { s->fsize[s->level - 1] -= ALIGN4(s->fsize[s->level]); - else + } else { s->fsize[s->level - 1] = 0; + } s->level++; while (1) { /* DATA::ARRAY::DATAUNIT[x]::ARRAY */ - if (getfield(s, &field) || field != T_ARRAY || getd(s, &atype) || atype != T_FILEDATA || s->fsize[s->level] < 4) break; + if (getfield(s, &field) || field != T_ARRAY || getd(s, &atype) || atype != T_FILEDATA || s->fsize[s->level] < 4) { + break; + } s->fsize[s->level] -= 4; s->level++; @@ -774,14 +805,17 @@ static cl_error_t real_scansis9x(cli_ctx *ctx, const char *tmpd) int fd; cli_dbgmsg("SIS: %d:Got filedata element with size %x\n", s->level, s->fsize[s->level]); - if (ALIGN4(s->fsize[s->level]) < s->fsize[s->level - 1]) + if (ALIGN4(s->fsize[s->level]) < s->fsize[s->level - 1]) { s->fsize[s->level - 1] -= ALIGN4(s->fsize[s->level]); - else + } else { s->fsize[s->level - 1] = 0; + } s->level++; while (1) { /* DATA::ARRAY::DATAUNIT[x]::ARRAY::FILEDATA[x]::COMPRESSED */ - if (getfield(s, &field) || field != T_COMPRESSED || getd(s, &field) || getd(s, &usize) || getd(s, &usizeh) || usizeh) break; + if (getfield(s, &field) || field != T_COMPRESSED || getd(s, &field) || getd(s, &usize) || getd(s, &usizeh) || usizeh) { + break; + } s->fsize[s->level] -= 12; cli_dbgmsg("SIS: File is%s compressed - size %x -> %x\n", (field) ? "" : " not", s->fsize[s->level], usize); snprintf(tempf, 1024, "%s" PATHSEP "sis9x%02d", tmpd, i++); @@ -789,8 +823,12 @@ static cl_error_t real_scansis9x(cli_ctx *ctx, const char *tmpd) s->pos -= (long)s->sleft; s->sleft = s->smax = 0; - if (cli_checklimits("sis", ctx, ALIGN4(s->fsize[s->level]), 0, 0) != CL_CLEAN) break; - if (!(src = cli_max_malloc(ALIGN4(s->fsize[s->level])))) break; + if (cli_checklimits("sis", ctx, ALIGN4(s->fsize[s->level]), 0, 0) != CL_CLEAN) { + break; + } + if (!(src = cli_max_malloc(ALIGN4(s->fsize[s->level])))) { + break; + } len = ALIGN4(s->fsize[s->level]); if ((uint32_t)fmap_readn(s->map, src, s->pos, len) != len) { @@ -802,11 +840,11 @@ static cl_error_t real_scansis9x(cli_ctx *ctx, const char *tmpd) if (field) { /* compressed */ int zresult; - if (usize <= s->fsize[s->level] * 3 && cli_checklimits("sis", ctx, s->fsize[s->level] * 3, 0, 0) == CL_CLEAN) + if (usize <= s->fsize[s->level] * 3 && cli_checklimits("sis", ctx, s->fsize[s->level] * 3, 0, 0) == CL_CLEAN) { uusize = s->fsize[s->level] * 3; - else if (cli_checklimits("sis", ctx, usize, 0, 0) == CL_CLEAN) + } else if (cli_checklimits("sis", ctx, usize, 0, 0) == CL_CLEAN) { uusize = usize; - else { + } else { free(src); break; } @@ -823,10 +861,11 @@ static cl_error_t real_scansis9x(cli_ctx *ctx, const char *tmpd) free(dst); break; } - if ((uLongf)usize != uusize) + if ((uLongf)usize != uusize) { cli_dbgmsg("SIS: Warning: expected size %lx but got %lx\n", (uLongf)usize, uusize); - else + } else { cli_dbgmsg("SIS: File successfully inflated\n"); + } } else { /* not compressed */ dst = src; uusize = s->fsize[s->level]; diff --git a/libclamav/special.c b/libclamav/special.c index fdf6338695..9e3534532c 100644 --- a/libclamav/special.c +++ b/libclamav/special.c @@ -55,10 +55,12 @@ int cli_check_mydoom_log(cli_ctx *ctx) unsigned int blocks = map->len / (8 * 4); cli_dbgmsg("in cli_check_mydoom_log()\n"); - if (blocks < 2) + if (blocks < 2) { return CL_CLEAN; - if (blocks > 5) + } + if (blocks > 5) { blocks = 5; + } /* * The following pointer might not be properly aligned. There there is @@ -66,14 +68,16 @@ int cli_check_mydoom_log(cli_ctx *ctx) * while reading the uint32_t. */ ptr = fmap_need_off_once(map, 0, 8 * 4 * blocks); - if (!ptr) + if (!ptr) { return CL_CLEAN; + } while (blocks) { /* This wasn't probably intended but that's what the current code does anyway */ const uint32_t marker_ff = 0xffffffff; - if (!memcmp(&ptr[--blocks], &marker_ff, sizeof(uint32_t))) + if (!memcmp(&ptr[--blocks], &marker_ff, sizeof(uint32_t))) { return CL_CLEAN; + } } memcpy(record, ptr, sizeof(record)); @@ -86,8 +90,9 @@ int cli_check_mydoom_log(cli_ctx *ctx) (be32_to_host(record[5]) ^ key) + (be32_to_host(record[6]) ^ key) + (be32_to_host(record[7]) ^ key); - if ((~check) != key) + if ((~check) != key) { return CL_CLEAN; + } key = ~be32_to_host(record[8]); check = (be32_to_host(record[9]) ^ key) + @@ -97,18 +102,20 @@ int cli_check_mydoom_log(cli_ctx *ctx) (be32_to_host(record[13]) ^ key) + (be32_to_host(record[14]) ^ key) + (be32_to_host(record[15]) ^ key); - if ((~check) != key) + if ((~check) != key) { return CL_CLEAN; + } return cli_append_potentially_unwanted(ctx, "Heuristics.Worm.Mydoom.M.log"); } static uint32_t riff_endian_convert_32(uint32_t value, int big_endian) { - if (big_endian) + if (big_endian) { return be32_to_host(value); - else + } else { return le32_to_host(value); + } } static int riff_read_chunk(fmap_t *map, off_t *offset, int big_endian, int rec_level) @@ -124,8 +131,9 @@ static int riff_read_chunk(fmap_t *map, off_t *offset, int big_endian, int rec_l return 0; } - if (!(buf = fmap_need_off_once(map, cur_offset, 4 * 2))) + if (!(buf = fmap_need_off_once(map, cur_offset, 4 * 2))) { return 0; + } cur_offset += 4 * 2; buffer = (char *)buf; @@ -133,8 +141,9 @@ static int riff_read_chunk(fmap_t *map, off_t *offset, int big_endian, int rec_l sizeof(cache_buf)); chunk_size = riff_endian_convert_32(cache_buf, big_endian); - if (!memcmp(buf, "anih", 4) && chunk_size != 36) + if (!memcmp(buf, "anih", 4) && chunk_size != 36) { return 2; + } if (memcmp(buf, "RIFF", 4) == 0) { return 0; @@ -175,8 +184,9 @@ int cli_check_riff_exploit(cli_ctx *ctx) cli_dbgmsg("in cli_check_riff_exploit()\n"); - if (!(buf = fmap_need_off_once(map, 0, 4 * 3))) + if (!(buf = fmap_need_off_once(map, 0, 4 * 3))) { return 0; + } if (memcmp(buf, "RIFF", 4) == 0) { big_endian = FALSE; @@ -205,12 +215,14 @@ static inline int swizz_j48(const uint16_t n[]) { cli_dbgmsg("swizz_j48: %u, %u, %u\n", n[0], n[1], n[2]); /* rules based on J48 tree */ - if (n[0] <= 961 || !n[1]) + if (n[0] <= 961 || !n[1]) { return 0; - if (n[0] <= 1006) + } + if (n[0] <= 1006) { return (n[2] > 0 && n[2] <= 6); - else + } else { return n[1] <= 10 && n[2]; + } } void cli_detect_swizz_str(const unsigned char *str, uint32_t len, struct swizz_stats *stats, int blob) @@ -233,20 +245,23 @@ void cli_detect_swizz_str(const unsigned char *str, uint32_t len, struct swizz_s continue; } if (!isalnum(c)) { - if (!lastalnum) + if (!lastalnum) { continue; + } lastalnum = 0; c = ' '; } else { lastalnum = 1; - if (isdigit(c)) + if (isdigit(c)) { continue; + } } stri[j++] = tolower(c); } stri[j++] = '\0'; - if ((!blob && (bad >= 8)) || j < 4) + if ((!blob && (bad >= 8)) || j < 4) { return; + } memset(ngrams, 0, sizeof(ngrams)); memset(ngram_cnts, 0, sizeof(ngram_cnts)); for (i = 0; i < j - 2; i++) { @@ -256,19 +271,23 @@ void cli_detect_swizz_str(const unsigned char *str, uint32_t len, struct swizz_s ngrams[idx]++; stats->gngrams[idx]++; } - } else if (stri[i] == ' ') + } else if (stri[i] == ' ') { words++; + } } for (i = 0; i < sizeof(ngrams); i++) { uint8_t v = ngrams[i]; - if (v > 3) v = 3; + if (v > 3) { + v = 3; + } if (v) { ngram_cnts[v - 1]++; all++; } } - if (!all) + if (!all) { return; + } cli_dbgmsg("cli_detect_swizz_str: %u, %u, %u\n", ngram_cnts[0], ngram_cnts[1], ngram_cnts[2]); /* normalize */ for (i = 0; i < sizeof(ngram_cnts) / sizeof(ngram_cnts[0]); i++) { @@ -276,7 +295,9 @@ void cli_detect_swizz_str(const unsigned char *str, uint32_t len, struct swizz_s ngram_cnts[i] = (v << 10) / all; } ret = swizz_j48(ngram_cnts) ? CL_VIRUS : CL_CLEAN; - if (words < 3) ret = CL_CLEAN; + if (words < 3) { + ret = CL_CLEAN; + } cli_dbgmsg("cli_detect_swizz_str: %s, %u words\n", ret == CL_VIRUS ? "suspicious" : "ok", words); if (ret == CL_VIRUS) { stats->suspicious += j; @@ -322,7 +343,9 @@ int cli_detect_swizz(struct swizz_stats *stats) memset(gn, 0, sizeof(gn)); for (i = 0; i < 17576; i++) { uint8_t v = stats->gngrams[i]; - if (v > 10) v = 10; + if (v > 10) { + v = 10; + } if (v) { gn[v - 1]++; all++; @@ -334,8 +357,9 @@ int cli_detect_swizz(struct swizz_stats *stats) for (i = 0; i < sizeof(gn) / sizeof(gn[0]); i++) { uint32_t v = gn[i]; gn[i] = (v << 15) / all; - if (cli_debug_flag) + if (cli_debug_flag) { cli_eprintf("%lu, ", (unsigned long)gn[i]); + } } global_swizz = swizz_j48_global(gn) ? CL_VIRUS : CL_CLEAN; if (cli_debug_flag) { @@ -348,11 +372,14 @@ int cli_detect_swizz(struct swizz_stats *stats) cli_dbgmsg("cli_detect_swizz: resources broken, ignoring\n"); return CL_CLEAN; } - if (stats->total <= 337) + if (stats->total <= 337) { return CL_CLEAN; - if (stats->suspicious << 10 > 40 * stats->total) + } + if (stats->suspicious << 10 > 40 * stats->total) { return CL_VIRUS; - if (!stats->suspicious) + } + if (!stats->suspicious) { return CL_CLEAN; + } return global_swizz; } diff --git a/libclamav/spin.c b/libclamav/spin.c index 870c55c12d..0aad6a0001 100644 --- a/libclamav/spin.c +++ b/libclamav/spin.c @@ -107,20 +107,22 @@ static char exec86(uint8_t aelle, uint8_t cielle, char *curremu, int *retval) break; case 0xfe: /* inc/dec al */ - if (curremu[len] == '\xc0') + if (curremu[len] == '\xc0') { aelle++; - else + } else { aelle--; + } len++; break; case 0xc0: /* ror/rol al, ?? */ support = curremu[len]; len++; - if (support == 0xc0) + if (support == 0xc0) { CLI_ROL(aelle, curremu[len]); - else + } else { CLI_ROR(aelle, curremu[len]); + } len++; break; @@ -208,11 +210,13 @@ int unspin(char *src, int ssize, struct cli_exe_section *sections, int sectcnt, return 1; } - if (ep[0x1e0] != '\xb8') + if (ep[0x1e0] != '\xb8') { cli_dbgmsg("spin: prolly not spinned, expect failure\n"); + } - if ((cli_readint32(ep + 0x1e1) & 0x00200000)) + if ((cli_readint32(ep + 0x1e1) & 0x00200000)) { cli_dbgmsg("spin: password protected, expect failure\n"); + } curr = ep + 0x1fe5 + len - 1; while (len--) { @@ -383,8 +387,9 @@ int unspin(char *src, int ssize, struct cli_exe_section *sections, int sectcnt, for (j = 0; j < sectcnt; j++) { if (bitmap & 1) { - if (filesize > ctx->engine->maxfilesize || sections[j].vsz > ctx->engine->maxfilesize - filesize) + if (filesize > ctx->engine->maxfilesize || sections[j].vsz > ctx->engine->maxfilesize - filesize) { return 2; + } filesize += sections[j].vsz; } bitmap >>= 1; @@ -427,8 +432,9 @@ int unspin(char *src, int ssize, struct cli_exe_section *sections, int sectcnt, if (len) { int t; for (t = 0; t < j; t++) { - if (bitman & 1) + if (bitman & 1) { free(sects[t]); + } bitman = bitman >> 1 & 0x7fffffff; } free(sects); @@ -440,8 +446,9 @@ int unspin(char *src, int ssize, struct cli_exe_section *sections, int sectcnt, /* len = cli_readint32(ep+0x2fc8); -- Using vsizes instead */ for (j = 0; j < sectcnt; j++) { - if (sections[j].rva <= key32 && key32 - sections[j].rva < sections[j].vsz && CLI_ISCONTAINED(src + sections[j].raw, sections[j].rsz, src + sections[j].raw, key32 - sections[j].rva)) + if (sections[j].rva <= key32 && key32 - sections[j].rva < sections[j].vsz && CLI_ISCONTAINED(src + sections[j].raw, sections[j].rsz, src + sections[j].raw, key32 - sections[j].rva)) { break; + } } if (j != sectcnt && ((bitman & (1 << j)) == 0)) { /* FIXME: not really sure either the res sect is lamed or just compressed, but this'll save some major headaches */ @@ -487,8 +494,9 @@ int unspin(char *src, int ssize, struct cli_exe_section *sections, int sectcnt, memcpy(to, sects[j], rebhlp[j].rsz); to += rebhlp[j].rsz; - if (bitmap & 1) + if (bitmap & 1) { free(sects[j]); + } bitmap = bitmap >> 1; } @@ -506,8 +514,9 @@ int unspin(char *src, int ssize, struct cli_exe_section *sections, int sectcnt, cli_dbgmsg("spin: free bitmap is %x\n", bitman); for (j = 0; j < sectcnt; j++) { - if (bitmap & 1) + if (bitmap & 1) { free(sects[j]); + } bitman = bitman >> 1 & 0x7fffffff; } free(sects); diff --git a/libclamav/stats.c b/libclamav/stats.c index 8f749a4f3e..c626e391eb 100644 --- a/libclamav/stats.c +++ b/libclamav/stats.c @@ -145,35 +145,41 @@ void clamav_stats_add_sample(const char *virname, const unsigned char *md5, size char **p; int err, submit = 0; - if (!(cbdata)) + if (!(cbdata)) { return; + } intel = (cli_intel_t *)cbdata; - if (!(intel->engine)) + if (!(intel->engine)) { return; + } - if (intel->engine->dconf->stats & DCONF_STATS_DISABLED) + if (intel->engine->dconf->stats & DCONF_STATS_DISABLED) { return; + } /* First check if we need to submit stats based on memory/number limits */ - if ((intel->engine->cb_stats_get_size)) + if ((intel->engine->cb_stats_get_size)) { submit = (intel->engine->cb_stats_get_size(cbdata) >= intel->maxmem); - else + } else { submit = (clamav_stats_get_size(cbdata) >= intel->maxmem); + } if (submit == 0) { - if ((intel->engine->cb_stats_get_num)) + if ((intel->engine->cb_stats_get_num)) { submit = (intel->engine->cb_stats_get_num(cbdata) >= intel->maxsamples); - else + } else { submit = (clamav_stats_get_num(cbdata) >= intel->maxsamples); + } } if (submit) { if ((intel->engine->cb_stats_submit)) { intel->engine->cb_stats_submit(intel->engine, cbdata); } else { - if ((intel->engine->cb_stats_flush)) + if ((intel->engine->cb_stats_flush)) { intel->engine->cb_stats_flush(intel->engine, intel); + } return; } @@ -191,12 +197,14 @@ void clamav_stats_add_sample(const char *virname, const unsigned char *md5, size if (!(sample)) { if (!(intel->samples)) { sample = intel->samples = calloc(1, sizeof(cli_flagged_sample_t)); - if (!(sample)) + if (!(sample)) { goto end; + } } else { sample = calloc(1, sizeof(cli_flagged_sample_t)); - if (!(sample)) + if (!(sample)) { goto end; + } sample->next = intel->samples; intel->samples->prev = sample; @@ -204,14 +212,16 @@ void clamav_stats_add_sample(const char *virname, const unsigned char *md5, size } if ((sample->virus_name)) { - for (i = 0; sample->virus_name[i] != NULL; i++) + for (i = 0; sample->virus_name[i] != NULL; i++) { ; + } p = realloc(sample->virus_name, sizeof(char **) * (i + 1)); if (!(p)) { free(sample->virus_name); free(sample); - if (sample == intel->samples) + if (sample == intel->samples) { intel->samples = NULL; + } goto end; } @@ -222,8 +232,9 @@ void clamav_stats_add_sample(const char *virname, const unsigned char *md5, size sample->virus_name = calloc(1, sizeof(char **)); if (!(sample->virus_name)) { free(sample); - if (sample == intel->samples) + if (sample == intel->samples) { intel->samples = NULL; + } goto end; } @@ -233,8 +244,9 @@ void clamav_stats_add_sample(const char *virname, const unsigned char *md5, size if (!(sample->virus_name[i])) { free(sample->virus_name); free(sample); - if (sample == intel->samples) + if (sample == intel->samples) { intel->samples = NULL; + } goto end; } @@ -243,8 +255,9 @@ void clamav_stats_add_sample(const char *virname, const unsigned char *md5, size if (!(p)) { free(sample->virus_name); free(sample); - if (sample == intel->samples) + if (sample == intel->samples) { intel->samples = NULL; + } goto end; } @@ -290,8 +303,9 @@ void clamav_stats_flush(struct cl_engine *engine, void *cbdata) cli_flagged_sample_t *sample, *next; int err; - if (!(cbdata) || !(engine)) + if (!(cbdata) || !(engine)) { return; + } intel = (cli_intel_t *)cbdata; @@ -318,8 +332,9 @@ void clamav_stats_flush(struct cl_engine *engine, void *cbdata) #ifdef CL_THREAD_SAFE err = pthread_mutex_unlock(&(intel->mutex)); - if (err) + if (err) { cli_warnmsg("clamav_stats_flush: unlocking mutex failed (err: %d): %s\n", err, strerror(err)); + } #endif } @@ -328,8 +343,9 @@ void free_sample(cli_flagged_sample_t *sample) size_t i; if ((sample->virus_name)) { - for (i = 0; sample->virus_name[i] != NULL; i++) + for (i = 0; sample->virus_name[i] != NULL; i++) { free(sample->virus_name[i]); + } free(sample->virus_name); } @@ -350,16 +366,19 @@ void clamav_stats_submit(struct cl_engine *engine, void *cbdata) int err; intel = (cli_intel_t *)cbdata; - if (!(intel) || !(engine)) + if (!(intel) || !(engine)) { return; + } - if (engine->dconf->stats & DCONF_STATS_DISABLED) + if (engine->dconf->stats & DCONF_STATS_DISABLED) { return; + } if (!(engine->cb_stats_get_hostid)) { /* Submitting stats is disabled due to HostID being turned off */ - if ((engine->cb_stats_flush)) + if ((engine->cb_stats_flush)) { engine->cb_stats_flush(engine, cbdata); + } return; } @@ -371,8 +390,9 @@ void clamav_stats_submit(struct cl_engine *engine, void *cbdata) if (err) { cli_warnmsg("clamav_stats_submit: locking mutex failed (err: %d): %s\n", err, strerror(err)); - if ((intel->engine) && (intel->engine->cb_stats_flush)) + if ((intel->engine) && (intel->engine->cb_stats_flush)) { intel->engine->cb_stats_flush(intel->engine, cbdata); + } return; } @@ -421,8 +441,9 @@ void clamav_stats_remove_sample(const char *virname, const unsigned char *md5, s int err; intel = (cli_intel_t *)cbdata; - if (!(intel)) + if (!(intel)) { return; + } #ifdef CL_THREAD_SAFE err = pthread_mutex_lock(&(intel->mutex)); @@ -433,12 +454,15 @@ void clamav_stats_remove_sample(const char *virname, const unsigned char *md5, s #endif while ((sample = find_sample(intel, virname, md5, size, NULL))) { - if (sample->prev) + if (sample->prev) { sample->prev->next = sample->next; - if (sample->next) + } + if (sample->next) { sample->next->prev = sample->prev; - if (sample == intel->samples) + } + if (sample == intel->samples) { intel->samples = sample->next; + } free_sample(sample); intel->nsamples--; @@ -459,8 +483,9 @@ void clamav_stats_decrement_count(const char *virname, const unsigned char *md5, int err; intel = (cli_intel_t *)cbdata; - if (!(intel)) + if (!(intel)) { return; + } #ifdef CL_THREAD_SAFE err = pthread_mutex_lock(&(intel->mutex)); @@ -471,14 +496,16 @@ void clamav_stats_decrement_count(const char *virname, const unsigned char *md5, #endif sample = find_sample(intel, virname, md5, size, NULL); - if (!(sample)) + if (!(sample)) { goto clamav_stats_decrement_end; + } if (sample->hits == 1) { - if ((intel->engine->cb_stats_remove_sample)) + if ((intel->engine->cb_stats_remove_sample)) { intel->engine->cb_stats_remove_sample(virname, md5, size, intel); - else + } else { clamav_stats_remove_sample(virname, md5, size, intel); + } goto clamav_stats_decrement_end; } @@ -501,8 +528,9 @@ size_t clamav_stats_get_num(void *cbdata) intel = (cli_intel_t *)cbdata; - if (!(intel)) + if (!(intel)) { return 0; + } return intel->nsamples; } @@ -515,8 +543,9 @@ size_t clamav_stats_get_size(void *cbdata) int err; intel = (cli_intel_t *)cbdata; - if (!(intel)) + if (!(intel)) { return 0; + } sz = sizeof(cli_intel_t); @@ -531,8 +560,9 @@ size_t clamav_stats_get_size(void *cbdata) for (sample = intel->samples; sample != NULL; sample = sample->next) { sz += sizeof(cli_flagged_sample_t); if ((sample->virus_name)) { - for (i = 0; sample->virus_name[i] != NULL; i++) + for (i = 0; sample->virus_name[i] != NULL; i++) { sz += strlen(sample->virus_name[i]); + } sz += sizeof(char **) * i; } } @@ -604,8 +634,9 @@ char *clamav_stats_get_hostid(void *cbdata) return strdup(STATS_ANON_UUID); #else buf = internal_get_host_id(); - if (!(buf)) + if (!(buf)) { return strdup(STATS_ANON_UUID); + } return buf; #endif } @@ -619,33 +650,43 @@ static cli_flagged_sample_t *find_sample(cli_intel_t *intel, const char *virname for (sample = intel->samples; sample != NULL; sample = sample->next) { int foundSections = 0; - if (sample->size != size) + if (sample->size != size) { continue; + } - if (memcmp(sample->md5, md5, sizeof(sample->md5))) + if (memcmp(sample->md5, md5, sizeof(sample->md5))) { continue; + } - if (!(virname)) + if (!(virname)) { return sample; + } if ((sections) && (sample->sections)) { if (sections->nsections == sample->sections->nsections) { - for (i = 0; i < sections->nsections; i++) - if (sections->sections[i].len == sample->sections->sections[i].len) - if (memcmp(sections->sections[i].md5, sample->sections->sections[i].md5, sizeof(stats_section_t))) + for (i = 0; i < sections->nsections; i++) { + if (sections->sections[i].len == sample->sections->sections[i].len) { + if (memcmp(sections->sections[i].md5, sample->sections->sections[i].md5, sizeof(stats_section_t))) { break; + } + } + } - if (i == sections->nsections) + if (i == sections->nsections) { foundSections = 1; + } } } else { foundSections = 1; } - if (foundSections) - for (i = 0; sample->virus_name[i] != NULL; i++) - if (!strcmp(sample->virus_name[i], virname)) + if (foundSections) { + for (i = 0; sample->virus_name[i] != NULL; i++) { + if (!strcmp(sample->virus_name[i], virname)) { return sample; + } + } + } } return NULL; diff --git a/libclamav/stats_json.c b/libclamav/stats_json.c index e0a8e13f69..b921264d22 100644 --- a/libclamav/stats_json.c +++ b/libclamav/stats_json.c @@ -51,8 +51,9 @@ char *hex_encode(char *buf, char *data, size_t len) int t; p = (buf != NULL) ? buf : calloc(1, (len * 2) + 1); - if (!(p)) + if (!(p)) { return NULL; + } for (i = 0; i < len; i++) { t = data[i] & 0xff; @@ -86,41 +87,48 @@ char *export_stats_to_json(struct cl_engine *engine, cli_intel_t *intel) cli_flagged_sample_t *sample; size_t bufsz, curused, i, j; - if (!(intel->hostid)) - if ((engine->cb_stats_get_hostid)) + if (!(intel->hostid)) { + if ((engine->cb_stats_get_hostid)) { intel->hostid = engine->cb_stats_get_hostid(engine->stats_data); + } + } hostid = (intel->hostid != NULL) ? intel->hostid : STATS_ANON_UUID; buf = calloc(1, JSON_BUFSZ); - if (!(buf)) + if (!(buf)) { return NULL; + } bufsz = JSON_BUFSZ; sprintf(buf, "{\n\t\"hostid\": \"%s\",\n", hostid); - if (intel->host_info) + if (intel->host_info) { sprintf(buf + strlen(buf), "\t\"host_info\": \"%s\",\n", intel->host_info); + } sprintf(buf + strlen(buf), "\t\"samples\": [\n"); curused = strlen(buf); for (sample = intel->samples; sample != NULL; sample = sample->next) { - if (sample->hits == 0) + if (sample->hits == 0) { continue; + } memset(md5, 0x00, sizeof(md5)); hex_encode(md5, sample->md5, sizeof(sample->md5)); buf = ensure_bufsize(buf, &bufsz, curused, strlen(md5) + sizeof(SAMPLE_PREFIX) + 45); - if (!(buf)) + if (!(buf)) { return NULL; + } snprintf(buf + curused, bufsz - curused, "\t\t\t{\n"); curused += strlen(buf + curused); buf = ensure_bufsize(buf, &bufsz, curused, sizeof("\t\t\t\"hash\": \"\",\n") + strlen(md5) + 1); - if (!(buf)) + if (!(buf)) { return NULL; + } snprintf(buf + curused, bufsz - curused, "\t\t\t\"hash\": \"%s\",\n", md5); curused += strlen(buf + curused); @@ -129,8 +137,9 @@ char *export_stats_to_json(struct cl_engine *engine, cli_intel_t *intel) snprintf(md5, sizeof(md5), "%u", sample->hits); buf = ensure_bufsize(buf, &bufsz, curused, strlen(md5) + 20); - if (!(buf)) + if (!(buf)) { return NULL; + } snprintf(buf + curused, bufsz - curused, "\t\t\t\"hits\": %s,\n", md5); curused += strlen(buf + curused); @@ -138,61 +147,70 @@ char *export_stats_to_json(struct cl_engine *engine, cli_intel_t *intel) snprintf(md5, sizeof(md5), "%u", sample->size); buf = ensure_bufsize(buf, &bufsz, curused, strlen(md5) + 20); - if (!(buf)) + if (!(buf)) { return NULL; + } snprintf(buf + curused, bufsz - curused, "\t\t\t\"size\": %s,\n", md5); curused += strlen(buf + curused); buf = ensure_bufsize(buf, &bufsz, curused, 30); - if (!(buf)) + if (!(buf)) { return NULL; + } if ((sample->sections) && (sample->sections->nsections)) { buf = ensure_bufsize(buf, &bufsz, curused, 30); - if (!(buf)) + if (!(buf)) { return NULL; + } snprintf(buf + curused, bufsz - curused, "\t\t\t\"sections\": [\n"); curused += strlen(buf + curused); for (i = 0; i < sample->sections->nsections; i++) { buf = ensure_bufsize(buf, &bufsz, curused, 30); - if (!(buf)) + if (!(buf)) { return NULL; + } snprintf(buf + curused, bufsz - curused, "\t\t\t\t%s{\n", (i > 0) ? "," : ""); curused += strlen(buf + curused); buf = ensure_bufsize(buf, &bufsz, curused, 65); - if (!(buf)) + if (!(buf)) { return NULL; + } memset(md5, 0x00, sizeof(md5)); - for (j = 0; j < 16; j++) + for (j = 0; j < 16; j++) { sprintf(md5 + (j * 2), "%02x", sample->sections->sections[i].md5[j]); + } snprintf(buf + curused, bufsz - curused, "\t\t\t\t\t\"hash\": \"%s\",\n", md5); curused += strlen(buf + curused); buf = ensure_bufsize(buf, &bufsz, curused, 65); - if (!(buf)) + if (!(buf)) { return NULL; + } snprintf(buf + curused, bufsz - curused, "\t\t\t\t\t\"size\": %llu\n", (long long unsigned)sample->sections->sections[i].len); curused += strlen(buf + curused); buf = ensure_bufsize(buf, &bufsz, curused, 30); - if (!(buf)) + if (!(buf)) { return NULL; + } snprintf(buf + curused, bufsz - curused, "\t\t\t\t}\n"); curused += strlen(buf + curused); } buf = ensure_bufsize(buf, &bufsz, curused, 20); - if (!(buf)) + if (!(buf)) { return NULL; + } snprintf(buf + curused, bufsz - curused, "\t\t\t],\n"); curused += strlen(buf + curused); @@ -203,24 +221,27 @@ char *export_stats_to_json(struct cl_engine *engine, cli_intel_t *intel) for (i = 0; sample->virus_name[i] != NULL; i++) { buf = ensure_bufsize(buf, &bufsz, curused, strlen(sample->virus_name[i]) + 5); - if (!(buf)) + if (!(buf)) { return NULL; + } snprintf(buf + curused, bufsz - curused, "%s\"%s\"", (i > 0) ? ", " : "", sample->virus_name[i]); curused += strlen(buf + curused); } buf = ensure_bufsize(buf, &bufsz, curused, 10); - if (!(buf)) + if (!(buf)) { return NULL; + } snprintf(buf + curused, bufsz - curused, " ]\n\t\t}%s\n", (sample->next != NULL) ? "," : ""); curused += strlen(buf + curused); } buf = ensure_bufsize(buf, &bufsz, curused, 15); - if (!(buf)) + if (!(buf)) { return NULL; + } snprintf(buf + curused, bufsz - curused, "\t]\n}\n"); diff --git a/libclamav/str.c b/libclamav/str.c index 4de1b6d1fc..ef1b244cd2 100644 --- a/libclamav/str.c +++ b/libclamav/str.c @@ -135,11 +135,13 @@ uint16_t *cli_hex2ui(const char *hex) } str = cli_max_calloc((len / 2) + 1, sizeof(uint16_t)); - if (!str) + if (!str) { return NULL; + } - if (cli_realhex2ui(hex, str, len)) + if (cli_realhex2ui(hex, str, len)) { return str; + } free(str); return NULL; @@ -159,8 +161,9 @@ char *cli_hex2str(const char *hex) } str = cli_max_calloc((len / 2) + 1, sizeof(char)); - if (!str) + if (!str) { return NULL; + } if (cli_hex2str_to(hex, str, len) == -1) { free(str); @@ -206,8 +209,9 @@ int cli_hex2num(const char *hex) } for (i = 0; i < len; i++) { - if ((hexval = cli_hex2int(hex[i])) < 0) + if ((hexval = cli_hex2int(hex[i])) < 0) { break; + } ret = (ret << 4) | hexval; } @@ -221,8 +225,9 @@ int cli_xtoi(const char *hex) len = strlen(hex); - if (len % 2 == 0) + if (len % 2 == 0) { return cli_hex2num(hex); + } hexbuf = cli_max_calloc(len + 2, sizeof(char)); if (hexbuf == NULL) { @@ -230,8 +235,9 @@ int cli_xtoi(const char *hex) return -1; } - for (i = 0; i < len; i++) + for (i = 0; i < len; i++) { hexbuf[i + 1] = hex[i]; + } val = cli_hex2num(hexbuf); free(hexbuf); return val; @@ -244,8 +250,9 @@ char *cli_str2hex(const char *string, unsigned int len) '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; unsigned int i, j; - if ((hexstr = (char *)cli_max_calloc(2 * len + 1, sizeof(char))) == NULL) + if ((hexstr = (char *)cli_max_calloc(2 * len + 1, sizeof(char))) == NULL) { return NULL; + } for (i = 0, j = 0; i < len; i++, j += 2) { hexstr[j] = HEX[(string[i] >> 4) & 0xf]; @@ -263,8 +270,9 @@ int cli_strbcasestr(const char *haystack, const char *needle) i = strlen(haystack); j = strlen(needle); - if (i < j) + if (i < j) { return 0; + } pt += i - j; @@ -282,18 +290,21 @@ int cli_chomp(char *string) { int l; - if (string == NULL) + if (string == NULL) { return -1; + } l = strlen(string); - if (l == 0) + if (l == 0) { return 0; + } --l; - while ((l >= 0) && ((string[l] == '\n') || (string[l] == '\r'))) + while ((l >= 0) && ((string[l] == '\n') || (string[l] == '\r'))) { string[l--] = '\0'; + } return l + 1; } @@ -386,14 +397,17 @@ const char *cli_memstr(const char *haystack, size_t hs, const char *needle, size { size_t i, s1, s2; - if (!hs || !ns || hs < ns) + if (!hs || !ns || hs < ns) { return NULL; + } - if (needle == haystack) + if (needle == haystack) { return haystack; + } - if (ns == 1) + if (ns == 1) { return memchr(haystack, needle[0], hs); + } if (needle[0] == needle[1]) { s1 = 2; @@ -407,8 +421,9 @@ const char *cli_memstr(const char *haystack, size_t hs, const char *needle, size i += s1; } else { if ((needle[0] == haystack[i]) && - !memcmp(needle + 2, haystack + i + 2, ns - 2)) + !memcmp(needle + 2, haystack + i + 2, ns - 2)) { return &haystack[i]; + } i += s2; } } @@ -424,8 +439,9 @@ char *cli_strrcpy(char *dest, const char *source) /* by NJH */ return NULL; } - while ((*dest++ = *source++)) + while ((*dest++ = *source++)) { ; + } return --dest; } @@ -440,9 +456,11 @@ const char *__cli_strcasestr(const char *haystack, const char *needle) f[0] = tolower(*needle); f[1] = toupper(*needle); f[2] = '\0'; - for (l = strcspn(haystack, f); l != strlen_a; l += strcspn(haystack + l + 1, f) + 1) - if (strncasecmp(haystack + l, needle, strlen_b) == 0) + for (l = strcspn(haystack, f); l != strlen_a; l += strcspn(haystack + l + 1, f) + 1) { + if (strncasecmp(haystack + l, needle, strlen_b) == 0) { return (haystack + l); + } + } return (NULL); } @@ -460,8 +478,9 @@ char *__cli_strndup(const char *s, size_t n) if (!alloc) { return NULL; - } else + } else { memcpy(alloc, s, len); + } alloc[len] = '\0'; return alloc; @@ -470,8 +489,9 @@ char *__cli_strndup(const char *s, size_t n) size_t __cli_strnlen(const char *s, size_t n) { size_t i = 0; - for (; (i < n) && s[i] != '\0'; ++i) + for (; (i < n) && s[i] != '\0'; ++i) { ; + } return i; } @@ -504,11 +524,13 @@ char *__cli_strnstr(const char *s, const char *find, size_t slen) len = strlen(find); do { do { - if (slen-- < 1 || (sc = *s++) == '\0') + if (slen-- < 1 || (sc = *s++) == '\0') { return (NULL); + } } while (sc != c); - if (len > slen) + if (len > slen) { return (NULL); + } } while (strncmp(s, find, len) != 0); s--; } @@ -527,8 +549,9 @@ size_t cli_strtokenize(char *buffer, const char delim, const size_t token_count, *buffer++ = '\0'; } else { i = tokens_found; - while (i < token_count) + while (i < token_count) { tokens[i++] = NULL; + } return tokens_found; } @@ -606,8 +629,9 @@ long cli_strntol(const char *nptr, size_t n, char **endptr, register int base) } } - if (base == 0) + if (base == 0) { base = c == '0' ? 8 : 10; + } /* * Compute the cutoff value between legal numbers and illegal @@ -632,17 +656,19 @@ long cli_strntol(const char *nptr, size_t n, char **endptr, register int base) for (acc = 0, any = 0; s < nptr + n; s++) { c = *s; - if (isdigit(c)) + if (isdigit(c)) { c -= '0'; - else if (isalpha(c)) + } else if (isalpha(c)) { c -= isupper(c) ? 'A' - 10 : 'a' - 10; - else + } else { break; - if (c >= base) + } + if (c >= base) { break; - if (any < 0 || acc > cutoff || (acc == cutoff && c > cutlim)) + } + if (any < 0 || acc > cutoff || (acc == cutoff && c > cutlim)) { any = -1; - else { + } else { any = 1; acc *= base; acc += c; @@ -651,12 +677,14 @@ long cli_strntol(const char *nptr, size_t n, char **endptr, register int base) if (any < 0) { acc = neg ? LONG_MIN : LONG_MAX; errno = ERANGE; - } else if (neg) + } else if (neg) { acc = -acc; + } done: - if (endptr != 0) + if (endptr != 0) { *endptr = (char *)(any ? s : nptr); + } return (acc); } @@ -725,25 +753,28 @@ unsigned long cli_strntoul(const char *nptr, size_t n, char **endptr, base = 16; } } - if (base == 0) + if (base == 0) { base = c == '0' ? 8 : 10; + } cutoff = (unsigned long)ULONG_MAX / (unsigned long)base; cutlim = (unsigned long)ULONG_MAX % (unsigned long)base; for (acc = 0, any = 0; s < nptr + n; s++) { c = *s; - if (isdigit(c)) + if (isdigit(c)) { c -= '0'; - else if (isalpha(c)) + } else if (isalpha(c)) { c -= isupper(c) ? 'A' - 10 : 'a' - 10; - else + } else { break; - if (c >= base) + } + if (c >= base) { break; - if (any < 0 || acc > cutoff || (acc == cutoff && c > cutlim)) + } + if (any < 0 || acc > cutoff || (acc == cutoff && c > cutlim)) { any = -1; - else { + } else { any = 1; acc *= base; acc += c; @@ -752,12 +783,14 @@ unsigned long cli_strntoul(const char *nptr, size_t n, char **endptr, if (any < 0) { acc = ULONG_MAX; errno = ERANGE; - } else if (neg) + } else if (neg) { acc = -acc; + } done: - if (endptr != 0) + if (endptr != 0) { *endptr = (char *)(any ? s : nptr); + } return (acc); } @@ -900,9 +933,11 @@ int cli_isnumber(const char *str) return 0; } - while (*str) - if (!strchr("0123456789", *str++)) + while (*str) { + if (!strchr("0123456789", *str++)) { return 0; + } + } return 1; } @@ -969,8 +1004,9 @@ char *cli_unescape(const char *str) continue; } } - if (!c) + if (!c) { c = 1; /* don't add \0 */ + } R[i++] = c; } R[i++] = '\0'; @@ -1010,10 +1046,11 @@ int cli_textbuffer_append_normalize(struct text_buffer *buf, const char *str, c = 13; break; case 'x': - if (i + 2 < len) + if (i + 2 < len) { c = ((cli_hex2int(str[i + 1]) < 0 ? 0 : cli_hex2int(str[i + 1])) << 4) | cli_hex2int(str[i + 2]); + } i += 2; break; case 'u': @@ -1026,8 +1063,9 @@ int cli_textbuffer_append_normalize(struct text_buffer *buf, const char *str, ((cli_hex2int(str[i + 3]) < 0 ? 0 : cli_hex2int(str[i + 3])) << 4) | cli_hex2int(str[i + 4]); - if (textbuffer_ensure_capacity(buf, 4) == -1) + if (textbuffer_ensure_capacity(buf, 4) == -1) { return -1; + } buf->pos += output_utf8(u, (unsigned char *)&buf->data[buf->pos]); i += 4; continue; @@ -1038,10 +1076,12 @@ int cli_textbuffer_append_normalize(struct text_buffer *buf, const char *str, break; } } - if (!c) + if (!c) { c = 1; /* we don't insert \0 */ - if (textbuffer_putc(buf, c) == -1) + } + if (textbuffer_putc(buf, c) == -1) { return -1; + } } return 0; } @@ -1051,8 +1091,9 @@ int cli_hexnibbles(char *str, int len) int i; for (i = 0; i < len; i++) { int c = cli_hex2int(str[i]); - if (c < 0) + if (c < 0) { return 1; + } str[i] = c; } return 0; @@ -1072,12 +1113,14 @@ cl_error_t cli_basename(const char *filepath, size_t filepath_len, index = filepath + filepath_len - 1; while (index > filepath) { - if (index[0] == PATHSEP[0]) + if (index[0] == PATHSEP[0]) { break; + } index--; } - if ((index != filepath) || (index[0] == PATHSEP[0])) + if ((index != filepath) || (index[0] == PATHSEP[0])) { index++; + } if (0 == CLI_STRNLEN(index, filepath_len - (index - filepath))) { cli_dbgmsg("cli_basename: Provided path does not include a file name.\n"); diff --git a/libclamav/swf.c b/libclamav/swf.c index a9c1b920b9..e89e18f4ed 100644 --- a/libclamav/swf.c +++ b/libclamav/swf.c @@ -234,16 +234,18 @@ static cl_error_t scanzws(cli_ctx *ctx, struct swf_file_hdr *hdr) free(tmpname); return CL_EUNPACK; } - if (0 == n_read) + if (0 == n_read) { break; + } lz.avail_in = n_read; offset += n_read; } lret = cli_LzmaDecode(&lz); count = FILEBUFF - lz.avail_out; if (count) { - if (cli_checklimits("SWF", ctx, outsize + count, 0, 0) != CL_SUCCESS) + if (cli_checklimits("SWF", ctx, outsize + count, 0, 0) != CL_SUCCESS) { break; + } if (cli_writen(fd, outbuff, count) != count) { cli_errmsg("scanzws: Can't write to file %s\n", tmpname); cli_LzmaShutdown(&lz); @@ -367,16 +369,18 @@ static cl_error_t scancws(cli_ctx *ctx, struct swf_file_hdr *hdr) free(tmpname); return CL_EUNPACK; } - if (0 == n_read) + if (0 == n_read) { break; + } stream.avail_in = n_read; offset += n_read; } zret = inflate(&stream, Z_SYNC_FLUSH); count = FILEBUFF - stream.avail_out; if (count) { - if (cli_checklimits("SWF", ctx, outsize + count, 0, 0) != CL_SUCCESS) + if (cli_checklimits("SWF", ctx, outsize + count, 0, 0) != CL_SUCCESS) { break; + } if (cli_writen(fd, outbuff, count) != count) { cli_errmsg("scancws: Can't write to file %s\n", tmpname); inflateEnd(&stream); @@ -441,9 +445,11 @@ static const char *tagname(tag_id id) { unsigned int i; - for (i = 0; tag_names[i].name; i++) - if (tag_names[i].id == id) + for (i = 0; tag_names[i].name; i++) { + if (tag_names[i].id == id) { return tag_names[i].name; + } + } return NULL; } @@ -515,8 +521,9 @@ cl_error_t cli_scanswf(cli_ctx *ctx) while (offset < map->len) { GETWORD(tag_hdr); tag_type = tag_hdr >> 6; - if (tag_type == 0) + if (tag_type == 0) { break; + } tag_len = tag_hdr & 0x3f; if (tag_len == 0x3f) GETDWORD(tag_len); @@ -549,20 +556,27 @@ cl_error_t cli_scanswf(cli_ctx *ctx) case TAG_FILEATTRIBUTES: GETDWORD(val); cli_dbgmsg("SWF: File attributes:\n"); - if (val & SWF_ATTR_USENETWORK) + if (val & SWF_ATTR_USENETWORK) { cli_dbgmsg(" * Use network\n"); - if (val & SWF_ATTR_RELATIVEURLS) + } + if (val & SWF_ATTR_RELATIVEURLS) { cli_dbgmsg(" * Relative URLs\n"); - if (val & SWF_ATTR_SUPPRESSCROSSDOMAINCACHE) + } + if (val & SWF_ATTR_SUPPRESSCROSSDOMAINCACHE) { cli_dbgmsg(" * Suppress cross domain cache\n"); - if (val & SWF_ATTR_ACTIONSCRIPT3) + } + if (val & SWF_ATTR_ACTIONSCRIPT3) { cli_dbgmsg(" * ActionScript 3.0\n"); - if (val & SWF_ATTR_HASMETADATA) + } + if (val & SWF_ATTR_HASMETADATA) { cli_dbgmsg(" * Has metadata\n"); - if (val & SWF_ATTR_USEDIRECTBLIT) + } + if (val & SWF_ATTR_USEDIRECTBLIT) { cli_dbgmsg(" * Use hardware acceleration\n"); - if (val & SWF_ATTR_USEGPU) + } + if (val & SWF_ATTR_USEGPU) { cli_dbgmsg(" * Use GPU\n"); + } break; default: diff --git a/libclamav/table.c b/libclamav/table.c index 2cdc3ab843..b97fb58ec5 100644 --- a/libclamav/table.c +++ b/libclamav/table.c @@ -55,8 +55,9 @@ void tableDestroy(table_t *table) while (tableItem) { tableEntry *tableNext = tableItem->next; - if (tableItem->key) + if (tableItem->key) { free(tableItem->key); + } free(tableItem); tableItem = tableNext; @@ -72,14 +73,15 @@ int tableInsert(table_t *table, const char *key, int value) { const int v = tableFind(table, key); - if (v > 0) /* duplicate key */ + if (v > 0) { /* duplicate key */ return (v == value) ? value : -1; /* allow real dups */ + } assert(value != -1); /* that would confuse us */ - if (table->tableHead == NULL) + if (table->tableHead == NULL) { table->tableLast = table->tableHead = (tableEntry *)malloc(sizeof(tableEntry)); - else { + } else { /* * Re-use deleted items */ @@ -88,13 +90,14 @@ int tableInsert(table_t *table, const char *key, int value) assert(table->tableHead != NULL); - for (tableItem = table->tableHead; tableItem; tableItem = tableItem->next) + for (tableItem = table->tableHead; tableItem; tableItem = tableItem->next) { if (tableItem->key == NULL) { /* This item has been deleted */ tableItem->key = cli_safer_strdup(key); tableItem->value = value; return value; } + } table->flags &= ~TABLE_HAS_DELETED_ENTRIES; } @@ -131,8 +134,9 @@ int tableFind(const table_t *table, const char *key) assert(table != NULL); - if (key == NULL) + if (key == NULL) { return -1; /* not treated as a fatal error */ + } #ifdef CL_DEBUG cost = 0; @@ -163,14 +167,16 @@ int tableUpdate(table_t *table, const char *key, int new_value) assert(table != NULL); - if (key == NULL) + if (key == NULL) { return -1; /* not treated as a fatal error */ + } - for (tableItem = table->tableHead; tableItem; tableItem = tableItem->next) + for (tableItem = table->tableHead; tableItem; tableItem = tableItem->next) { if (tableItem->key && (strcasecmp(tableItem->key, key) == 0)) { tableItem->value = new_value; return new_value; } + } /* not found */ return tableInsert(table, key, new_value); @@ -185,26 +191,31 @@ void tableRemove(table_t *table, const char *key) assert(table != NULL); - if (key == NULL) + if (key == NULL) { return; /* not treated as a fatal error */ + } - for (tableItem = table->tableHead; tableItem; tableItem = tableItem->next) + for (tableItem = table->tableHead; tableItem; tableItem = tableItem->next) { if (tableItem->key && (strcasecmp(tableItem->key, key) == 0)) { free(tableItem->key); tableItem->key = NULL; table->flags |= TABLE_HAS_DELETED_ENTRIES; /* don't break, duplicate keys are allowed */ } + } } void tableIterate(table_t *table, void (*callback)(char *key, int value, void *arg), void *arg) { tableEntry *tableItem; - if (table == NULL) + if (table == NULL) { return; + } - for (tableItem = table->tableHead; tableItem; tableItem = tableItem->next) - if (tableItem->key) /* check node has not been deleted */ + for (tableItem = table->tableHead; tableItem; tableItem = tableItem->next) { + if (tableItem->key) { /* check node has not been deleted */ (*callback)(tableItem->key, tableItem->value, arg); + } + } } diff --git a/libclamav/text.c b/libclamav/text.c index a5d5a92572..b7a6f9dbbd 100644 --- a/libclamav/text.c +++ b/libclamav/text.c @@ -139,32 +139,35 @@ textCopy(const text *t_head) text *first = NULL, *last = NULL; while (t_head) { - if (first == NULL) + if (first == NULL) { last = first = (text *)malloc(sizeof(text)); - else { + } else { last->t_next = (text *)malloc(sizeof(text)); last = last->t_next; } if (last == NULL) { cli_errmsg("textCopy: Unable to allocate memory to clone object\n"); - if (first) + if (first) { textDestroy(first); + } return NULL; } last->t_next = NULL; - if (t_head->t_line) + if (t_head->t_line) { last->t_line = lineLink(t_head->t_line); - else + } else { last->t_line = NULL; + } t_head = t_head->t_next; } - if (first) + if (first) { last->t_next = NULL; + } return first; } @@ -184,8 +187,9 @@ textAdd(text *t_head, const text *t) return textCopy(t); } - if (t == NULL) + if (t == NULL) { return t_head; + } ret = t_head; @@ -203,10 +207,11 @@ textAdd(text *t_head, const text *t) assert(t_head != NULL); - if (t->t_line) + if (t->t_line) { t_head->t_line = lineLink(t->t_line); - else + } else { t_head->t_line = NULL; + } t = t->t_next; } @@ -224,9 +229,9 @@ textAddMessage(text *aText, message *aMessage) { assert(aMessage != NULL); - if (messageGetEncoding(aMessage) == NOENCODING) + if (messageGetEncoding(aMessage) == NOENCODING) { return textAdd(aText, messageGetBody(aMessage)); - else { + } else { text *anotherText = messageToText(aMessage); if (aText) { @@ -265,13 +270,15 @@ textMove(text *t_head, text *t) return t_head; } - if (t == NULL) + if (t == NULL) { return t_head; + } ret = t_head; - while (t_head->t_next) + while (t_head->t_next) { t_head = t_head->t_next; + } /* * Move the first line manually so that the caller is left clean but @@ -289,8 +296,9 @@ textMove(text *t_head, text *t) if (t->t_line) { t_head->t_line = t->t_line; t->t_line = NULL; - } else + } else { t_head->t_line = NULL; + } t_head->t_next = t->t_next; t->t_next = NULL; @@ -308,15 +316,17 @@ textToBlob(text *t, blob *b, int destroy) size_t s; blob *bin; - if (t == NULL) + if (t == NULL) { return NULL; + } s = 0; (void)textIterate(t, getLength, &s, 0); - if (s == 0) + if (s == 0) { return b; + } /* * copy b. If b is NULL and an error occurs we know we need to free @@ -326,8 +336,9 @@ textToBlob(text *t, blob *b, int destroy) if (b == NULL) { b = blobCreate(); - if (b == NULL) + if (b == NULL) { return NULL; + } } if (blobGrow(b, s) != CL_SUCCESS) { @@ -343,8 +354,9 @@ textToBlob(text *t, blob *b, int destroy) * create the blob */ #else - if (bin == NULL) + if (bin == NULL) { blobDestroy(b); + } return NULL; #endif } @@ -371,8 +383,9 @@ textToFileblob(text *t, fileblob *fb, int destroy) cli_dbgmsg("textToFileBlob, destroy = %d\n", destroy); fb = fileblobCreate(); - if (fb == NULL) + if (fb == NULL) { return NULL; + } } else { cli_dbgmsg("textToFileBlob to %s, destroy = %d\n", fileblobGetFilename(fb), destroy); @@ -393,10 +406,11 @@ getLength(const line_t *line, void *arg) { size_t *length = (size_t *)arg; - if (line) + if (line) { *length += strlen(lineGetData(line)) + 1; - else + } else { (*length)++; + } } static void @@ -444,7 +458,7 @@ textIterate(text *t_text, void (*cb)(const line_t *item, void *arg), void *arg, t_text = t_text->t_next; } #else - if (destroy) + if (destroy) { while (t_text) { (*cb)(t_text->t_line, arg); @@ -455,12 +469,13 @@ textIterate(text *t_text, void (*cb)(const line_t *item, void *arg), void *arg, t_text = t_text->t_next; } - else + } else { while (t_text) { (*cb)(t_text->t_line, arg); t_text = t_text->t_next; } + } #endif return arg; } diff --git a/libclamav/textdet.c b/libclamav/textdet.c index 03a8b4f9ad..030311f4a2 100644 --- a/libclamav/textdet.c +++ b/libclamav/textdet.c @@ -85,9 +85,11 @@ static int td_isascii(const unsigned char *buf, unsigned int len) /* Validate that the data all falls within the bounds of * plain ASCII, ISO-8859 text, and non-ISO extended ASCII (Mac, IBM PC) */ - for (i = 0; i < len; i++) - if (text_chars[buf[i]] == F) + for (i = 0; i < len; i++) { + if (text_chars[buf[i]] == F) { return 0; + } + } return 1; } @@ -102,8 +104,9 @@ static int td_isutf8(const unsigned char *buf, unsigned int len) * Even if the whole file is valid UTF-8 sequences, * still reject it if it uses weird control characters. */ - if (text_chars[buf[i]] != T) + if (text_chars[buf[i]] != T) { return 0; + } } else if ((buf[i] & 0x40) == 0) { /* 10xxxxxx never 1st byte */ return 0; @@ -130,11 +133,13 @@ static int td_isutf8(const unsigned char *buf, unsigned int len) } for (j = 0; j < following; j++) { - if (++i >= len) + if (++i >= len) { return gotone; + } - if ((buf[i] & 0x80) == 0 || (buf[i] & 0x40)) + if ((buf[i] & 0x80) == 0 || (buf[i] & 0x40)) { return 0; + } /* c = (c << 6) + (buf[i] & 0x3f); */ } @@ -150,30 +155,35 @@ static int td_isutf16(const unsigned char *buf, unsigned int len) { unsigned int be = 1, nobom = 0, i, c, bad = 0, high = 0; - if (len < 2) + if (len < 2) { return 0; + } - if (buf[0] == 0xff && buf[1] == 0xfe) + if (buf[0] == 0xff && buf[1] == 0xfe) { be = 0; - else if (buf[0] == 0xfe && buf[1] == 0xff) + } else if (buf[0] == 0xfe && buf[1] == 0xff) { be = 1; - else + } else { nobom = 1; + } for (i = 2; i + 1 < len; i += 2) { - if (be) + if (be) { c = buf[i + 1] + 256 * buf[i]; - else + } else { c = buf[i] + 256 * buf[i + 1]; + } - if (c == 0xfffe) + if (c == 0xfffe) { return 0; + } if (c < 128 && text_chars[c] != T) { - if (nobom) + if (nobom) { return 0; - else + } else { bad++; + } } else if (c >= 128) { high++; } @@ -182,8 +192,9 @@ static int td_isutf16(const unsigned char *buf, unsigned int len) // if (nobom && high >= len / 4) // return 0; - if (!nobom && bad >= len / 2) + if (!nobom && bad >= len / 2) { return 0; + } return 1 + be; } diff --git a/libclamav/textnorm.c b/libclamav/textnorm.c index aa6d3c9776..2bc0462640 100644 --- a/libclamav/textnorm.c +++ b/libclamav/textnorm.c @@ -146,14 +146,20 @@ size_t text_normalize_map(struct text_norm_state *state, fmap_t *map, size_t off while (1) { /* Break out if we've reached the end of the map or our buffer. */ - if (!(acc_len = MIN_3(map_pgsz, map_len - offset, buff_len - acc_total))) break; + if (!(acc_len = MIN_3(map_pgsz, map_len - offset, buff_len - acc_total))) { + break; + } /* If map_loc is NULL, then there's nothing left to do but recover. */ - if (!(map_loc = fmap_need_off_once(map, offset, acc_len))) break; + if (!(map_loc = fmap_need_off_once(map, offset, acc_len))) { + break; + } offset += acc_len; /* If we didn't normalize anything, no need to update values, just break out. */ - if (!(acc = text_normalize_buffer(state, map_loc, acc_len))) break; + if (!(acc = text_normalize_buffer(state, map_loc, acc_len))) { + break; + } acc_total += acc; } diff --git a/libclamav/tiff.c b/libclamav/tiff.c index 2aa169b3ce..f1bf0daa30 100644 --- a/libclamav/tiff.c +++ b/libclamav/tiff.c @@ -64,11 +64,11 @@ cl_error_t cli_parsetiff(cli_ctx *ctx) } offset += 4; - if (!memcmp(magic, "\x4d\x4d\x00\x2a", 4)) + if (!memcmp(magic, "\x4d\x4d\x00\x2a", 4)) { big_endian = 1; - else if (!memcmp(magic, "\x49\x49\x2a\x00", 4)) + } else if (!memcmp(magic, "\x49\x49\x2a\x00", 4)) { big_endian = 0; - else { + } else { status = CL_CLEAN; /* Not a TIFF file */ goto done; } diff --git a/libclamav/tnef.c b/libclamav/tnef.c index d95c8f0e5c..331a25764f 100644 --- a/libclamav/tnef.c +++ b/libclamav/tnef.c @@ -116,16 +116,18 @@ int cli_tnef(const char *dir, cli_ctx *ctx) alldone = 1; break; } - if (length == 0) + if (length == 0) { continue; + } if (length < 0) { cli_warnmsg("Corrupt TNEF header detected - length %d\n", (int)length); ret = CL_EFORMAT; break; } - if (alldone) + if (alldone) { break; + } switch (part) { case LVL_MESSAGE: cli_dbgmsg("TNEF - found message\n"); @@ -162,8 +164,9 @@ int cli_tnef(const char *dir, cli_ctx *ctx) char *filename = cli_gentemp(ctx->sub_tmpdir); char buffer[BUFSIZ]; - if (filename) + if (filename) { fout = open(filename, O_WRONLY | O_CREAT | O_EXCL | O_TRUNC | O_BINARY, 0600); + } if (fout >= 0) { size_t count; @@ -294,8 +297,9 @@ tnef_attachment(fmap_t *map, off_t *pos, uint16_t type, uint16_t tag, int32_t le switch (tag) { case attATTACHTITLE: - if (length <= 0) + if (length <= 0) { return -1; + } string = cli_max_malloc(length + 1); if (string == NULL) { cli_errmsg("tnef_attachment: Unable to allocate memory for string\n"); @@ -321,15 +325,17 @@ tnef_attachment(fmap_t *map, off_t *pos, uint16_t type, uint16_t tag, int32_t le case attATTACHDATA: if (*fbref == NULL) { *fbref = fileblobCreate(); - if (*fbref == NULL) + if (*fbref == NULL) { return -1; + } } todo = length; while (todo) { unsigned char buf[BUFSIZ]; size_t got = fmap_readn(map, buf, *pos, MIN(sizeof(buf), todo)); - if (got == 0 || got == (size_t)-1) + if (got == 0 || got == (size_t)-1) { break; + } (*pos) += (off_t)got; fileblobAddData(*fbref, buf, got); @@ -361,12 +367,14 @@ tnef_header(fmap_t *map, off_t *pos, uint8_t *part, uint16_t *type, uint16_t *ta uint32_t i32; int rc; - if (fmap_readn(map, part, *pos, 1) != 1) + if (fmap_readn(map, part, *pos, 1) != 1) { return 0; + } (*pos)++; - if (*part == (uint8_t)0) + if (*part == (uint8_t)0) { return 0; + } rc = fmap_readn(map, &i32, *pos, sizeof(uint32_t)); if (rc != sizeof(uint32_t)) { @@ -387,8 +395,9 @@ tnef_header(fmap_t *map, off_t *pos, uint8_t *part, uint16_t *type, uint16_t *ta *tag = (uint16_t)(i32 & 0xFFFF); *type = (uint16_t)((i32 & 0xFFFF0000) >> 16); - if (fmap_readn(map, &i32, *pos, sizeof(uint32_t)) != sizeof(uint32_t)) + if (fmap_readn(map, &i32, *pos, sizeof(uint32_t)) != sizeof(uint32_t)) { return -1; + } (*pos) += sizeof(uint32_t); *length = (int32_t)host32(i32); diff --git a/libclamav/unarj.c b/libclamav/unarj.c index fef71da548..75a5cbaa62 100644 --- a/libclamav/unarj.c +++ b/libclamav/unarj.c @@ -163,10 +163,12 @@ typedef struct arj_decode_tag { static cl_error_t fill_buf(arj_decode_t *decode_data, int n) { - if (decode_data->status == CL_EFORMAT) + if (decode_data->status == CL_EFORMAT) { return CL_EFORMAT; - if (((uint64_t)decode_data->bit_buf) * (n > 0 ? 2 << (n - 1) : 0) > UINT32_MAX) + } + if (((uint64_t)decode_data->bit_buf) * (n > 0 ? 2 << (n - 1) : 0) > UINT32_MAX) { return CL_EFORMAT; + } decode_data->bit_buf = (((uint64_t)decode_data->bit_buf) << n) & 0xFFFF; while (n > decode_data->bit_count) { decode_data->bit_buf |= decode_data->sub_bit_buf << (n -= decode_data->bit_count); @@ -820,8 +822,9 @@ static int is_arj_archive(arj_metadata_t *metadata) const char *mark; mark = fmap_need_off_once(metadata->map, metadata->offset, 2); - if (!mark) + if (!mark) { return FALSE; + } metadata->offset += 2; if (memcmp(&mark[0], &header_id[0], 2) == 0) { return TRUE; @@ -847,8 +850,9 @@ static int arj_read_main_header(arj_metadata_t *metadata) size_t comment_len = 0; size_t orig_offset = metadata->offset; - if (fmap_readn(metadata->map, &header_size, metadata->offset, 2) != 2) + if (fmap_readn(metadata->map, &header_size, metadata->offset, 2) != 2) { return FALSE; + } metadata->offset += 2; header_size = le16_to_host(header_size); @@ -985,8 +989,9 @@ static cl_error_t arj_read_file_header(arj_metadata_t *metadata) size_t comment_len = 0; size_t orig_offset = metadata->offset; - if (fmap_readn(metadata->map, &header_size, metadata->offset, 2) != 2) + if (fmap_readn(metadata->map, &header_size, metadata->offset, 2) != 2) { return CL_EFORMAT; + } header_size = le16_to_host(header_size); metadata->offset += 2; @@ -1100,8 +1105,9 @@ static cl_error_t arj_read_file_header(arj_metadata_t *metadata) for (;;) { const uint16_t *countp = fmap_need_off_once(metadata->map, metadata->offset, 2); if (!countp) { - if (metadata->filename) + if (metadata->filename) { free(metadata->filename); + } metadata->filename = NULL; ret = CL_EFORMAT; goto done; diff --git a/libclamav/uniq.c b/libclamav/uniq.c index 5af271a56c..41469acb17 100644 --- a/libclamav/uniq.c +++ b/libclamav/uniq.c @@ -38,9 +38,13 @@ struct uniq *uniq_init(uint32_t count) { struct uniq *U; - if (!count) return NULL; + if (!count) { + return NULL; + } U = calloc(1, sizeof(*U)); - if (!U) return NULL; + if (!U) { + return NULL; + } U->md5s = cli_max_malloc(count * sizeof(*U->md5s)); if (!U->md5s) { @@ -85,9 +89,13 @@ cl_error_t uniq_add(struct uniq *U, const char *item, uint32_t item_len, char ** } /* Check for md5 digest match in md5 collection */ - if (U->items && U->md5s[U->idx[*digest]].md5[0] == *digest) - for (m = &U->md5s[U->idx[*digest]]; m; m = m->next) - if (!memcmp(&digest[1], &m->md5[1], 15)) break; + if (U->items && U->md5s[U->idx[*digest]].md5[0] == *digest) { + for (m = &U->md5s[U->idx[*digest]]; m; m = m->next) { + if (!memcmp(&digest[1], &m->md5[1], 15)) { + break; + } + } + } if (!m) { /* No match. Add new md5 to list */ @@ -96,10 +104,11 @@ cl_error_t uniq_add(struct uniq *U, const char *item, uint32_t item_len, char ** m = &U->md5s[U->items]; m->count = 0; - if (U->items && U->md5s[U->idx[*digest]].md5[0] == *digest) + if (U->items && U->md5s[U->idx[*digest]].md5[0] == *digest) { m->next = &U->md5s[U->idx[*digest]]; - else + } else { m->next = NULL; + } U->idx[*digest] = U->items; @@ -121,10 +130,14 @@ cl_error_t uniq_add(struct uniq *U, const char *item, uint32_t item_len, char ** m->count++; /* Pass back the ascii hash, if requested. */ - if (rhash) *rhash = m->name; + if (rhash) { + *rhash = m->name; + } /* Pass back the count, if requested. */ - if (count) *count = m->count; + if (count) { + *count = m->count; + } status = CL_SUCCESS; @@ -177,8 +190,9 @@ cl_error_t uniq_get(struct uniq *U, const char *item, uint32_t item_len, char ** * Pass back the ascii hash value (if requested). * Return the count of matching items (will be 1+). */ - if (rhash) + if (rhash) { *rhash = m->name; + } *count = m->count; break; } diff --git a/libclamav/unsp.c b/libclamav/unsp.c index af3946faf6..2f413f6a90 100644 --- a/libclamav/unsp.c +++ b/libclamav/unsp.c @@ -128,31 +128,36 @@ uint32_t unspack(const char *start_of_stuff, char *dest, cli_ctx *ctx, uint32_t const char *src = start_of_stuff + 0xd; struct cli_exe_section section; - if (c >= 0xe1) return 1; + if (c >= 0xe1) { + return 1; + } if (c >= 0x2d) { firstbyte = i = c / 0x2d; do { c += 0xd3; } while (--i); - } else + } else { firstbyte = 0; + } if (c >= 9) { allocsz = i = c / 9; do { c += 0xf7; } while (--i); - } else + } else { allocsz = 0; + } tre = c; i = allocsz; c = (tre + i) & 0xff; tablesz = ((0x300 << c) + 0x736) * sizeof(uint16_t); - if (cli_checklimits("nspack", ctx, tablesz, 0, 0) != CL_CLEAN) + if (cli_checklimits("nspack", ctx, tablesz, 0, 0) != CL_CLEAN) { return 1; /* Should be ~15KB, if it's so big it's prolly just not nspacked */ + } cli_dbgmsg("unsp: table size = %d\n", tablesz); if (!(table = cli_max_malloc(tablesz))) { @@ -169,7 +174,9 @@ uint32_t unspack(const char *start_of_stuff, char *dest, cli_ctx *ctx, uint32_t tre = very_real_unpack(table, tablesz, tre, allocsz, firstbyte, src, ssize, dst, dsize); free(table); - if (tre) return 1; + if (tre) { + return 1; + } section.raw = 0; section.rsz = dsize; @@ -197,10 +204,14 @@ uint32_t very_real_unpack(uint16_t *table, uint32_t tablesz, uint32_t tre, uint3 firstbyte = (1 << (firstbyte & 0xff)) - 1; - if (tablesz < i * sizeof(uint16_t)) return 2; + if (tablesz < i * sizeof(uint16_t)) { + return 2; + } /* init table */ - while (i) table[--i] = 0x400; + while (i) { + table[--i] = 0x400; + } /* table noinit */ @@ -213,8 +224,12 @@ uint32_t very_real_unpack(uint16_t *table, uint32_t tablesz, uint32_t tre, uint3 read_struct.table = (char *)table; read_struct.tablesz = tablesz; - for (i = 0; i < 5; i++) read_struct.oldval = (read_struct.oldval << 8) | get_byte(&read_struct); - if (read_struct.error) return 1; + for (i = 0; i < 5; i++) { + read_struct.oldval = (read_struct.oldval << 8) | get_byte(&read_struct); + } + if (read_struct.error) { + return 1; + } /* if (!dsize) return 0; - checked in pe.c */ /* very_unpacking_loop */ @@ -224,7 +239,9 @@ uint32_t very_real_unpack(uint16_t *table, uint32_t tablesz, uint32_t tre, uint3 uint32_t tpos; uint32_t temp = damian; - if (read_struct.error) return 1; /* checked once per mainloop, keeps the code readable and it's still safe */ + if (read_struct.error) { + return 1; /* checked once per mainloop, keeps the code readable and it's still safe */ + } if (!getbit_from_table(&table[(damian << 4) + backsize], &read_struct)) { /* no_mainbit */ @@ -246,7 +263,9 @@ uint32_t very_real_unpack(uint16_t *table, uint32_t tablesz, uint32_t tre, uint3 /* 44847E */ if (previous_bit) { - if (!CLI_ISCONTAINED(dst, dsize, &dst[unpacked_so_far - backbytes], 1)) return 1; + if (!CLI_ISCONTAINED(dst, dsize, &dst[unpacked_so_far - backbytes], 1)) { + return 1; + } ssize = (ssize & 0xffffff00) | (uint8_t)dst[unpacked_so_far - backbytes]; /* FIXME! ssize is not static */ bielle = get_100_bits_from_tablesize(&table[tpos + 0x736], &read_struct, ssize); previous_bit = 0; @@ -255,10 +274,14 @@ uint32_t very_real_unpack(uint16_t *table, uint32_t tablesz, uint32_t tre, uint3 } /* unpack_one_byte - duplicated */ - if (!CLI_ISCONTAINED(dst, dsize, &dst[unpacked_so_far], 1)) return 1; + if (!CLI_ISCONTAINED(dst, dsize, &dst[unpacked_so_far], 1)) { + return 1; + } dst[unpacked_so_far] = bielle; unpacked_so_far++; - if (unpacked_so_far >= dsize) return 0; + if (unpacked_so_far >= dsize) { + return 0; + } continue; } else { /* got_mainbit */ @@ -271,15 +294,21 @@ uint32_t very_real_unpack(uint16_t *table, uint32_t tablesz, uint32_t tre, uint3 tpos <<= 4; tpos += backsize; if (!getbit_from_table(&table[tpos], &read_struct)) { - if (!unpacked_so_far) return bielle; /* FIXME: WTF?! */ + if (!unpacked_so_far) { + return bielle; /* FIXME: WTF?! */ + } damian = 2 * ((int32_t)damian >= 7) + 9; /* signed */ - if (!CLI_ISCONTAINED(dst, dsize, &dst[unpacked_so_far - backbytes], 1)) return 1; + if (!CLI_ISCONTAINED(dst, dsize, &dst[unpacked_so_far - backbytes], 1)) { + return 1; + } bielle = (uint8_t)dst[unpacked_so_far - backbytes]; /* unpack_one_byte - real */ dst[unpacked_so_far] = bielle; unpacked_so_far++; - if (unpacked_so_far >= dsize) return 0; + if (unpacked_so_far >= dsize) { + return 0; + } continue; } else { /* gotbit_tre */ @@ -354,8 +383,12 @@ uint32_t very_real_unpack(uint16_t *table, uint32_t tablesz, uint32_t tre, uint3 } /* gotbit_uno ends */ /* checkloop_and_backcopy */ - if (!backbytes) return 0; /* very_real_unpack_end */ - if (backbytes > unpacked_so_far) return bielle; /* FIXME: WTF?! */ + if (!backbytes) { + return 0; /* very_real_unpack_end */ + } + if (backbytes > unpacked_so_far) { + return bielle; /* FIXME: WTF?! */ + } backsize += 2; @@ -371,7 +404,9 @@ uint32_t very_real_unpack(uint16_t *table, uint32_t tablesz, uint32_t tre, uint3 } while (--backsize && unpacked_so_far < dsize); bielle = (uint8_t)dst[unpacked_so_far - 1]; - if (unpacked_so_far >= dsize) return 0; + if (unpacked_so_far >= dsize) { + return 0; + } } /* got_mainbit ends */ @@ -449,8 +484,9 @@ uint32_t get_100_bits_from_tablesize(uint16_t *intable, struct UNSP *read_struct count = (count * 2) | tpos; if (lpos != tpos) { /* second loop */ - while (count < 0x100) + while (count < 0x100) { count = (count * 2) | getbit_from_table(&intable[count], read_struct); + } } } return count & 0xff; @@ -460,8 +496,9 @@ uint32_t get_100_bits_from_table(uint16_t *intable, struct UNSP *read_struct) { uint32_t count = 1; - while (count < 0x100) + while (count < 0x100) { count = (count * 2) | getbit_from_table(&intable[count], read_struct); + } return count & 0xff; } @@ -472,8 +509,9 @@ uint32_t get_n_bits_from_table(uint16_t *intable, uint32_t bits, struct UNSP *re /* if (bits) { always set! */ bitcounter = bits; - while (bitcounter--) + while (bitcounter--) { count = count * 2 + getbit_from_table(&intable[count], read_struct); + } /* } */ return count - (1 << (bits & 0xff)); @@ -482,11 +520,13 @@ uint32_t get_n_bits_from_table(uint16_t *intable, uint32_t bits, struct UNSP *re uint32_t get_n_bits_from_tablesize(uint16_t *intable, struct UNSP *read_struct, uint32_t backsize) { - if (!getbit_from_table(intable, read_struct)) + if (!getbit_from_table(intable, read_struct)) { return get_n_bits_from_table(&intable[(backsize << 3) + 2], 3, read_struct); + } - if (!getbit_from_table(&intable[1], read_struct)) + if (!getbit_from_table(&intable[1], read_struct)) { return 8 + get_n_bits_from_table(&intable[(backsize << 3) + 0x82], 3, read_struct); + } return 0x10 + get_n_bits_from_table(&intable[0x102], 8, read_struct); } @@ -497,8 +537,9 @@ uint32_t get_bb(uint16_t *intable, uint32_t back, struct UNSP *read_struct) uint32_t bb = 0; uint32_t i; - if ((int32_t)back <= 0) /* signed */ + if ((int32_t)back <= 0) { /* signed */ return 0; + } for (i = 0; i < back; i++) { uint32_t bit = getbit_from_table(&intable[pos], read_struct); @@ -512,7 +553,9 @@ uint32_t get_bitmap(struct UNSP *read_struct, uint32_t bits) { uint32_t retv = 0; - if ((int32_t)bits <= 0) return 0; /* signed */ + if ((int32_t)bits <= 0) { + return 0; /* signed */ + } while (bits--) { read_struct->bitmap >>= 1; /* unsigned */ diff --git a/libclamav/untar.c b/libclamav/untar.c index 500788bb2b..e25502c958 100644 --- a/libclamav/untar.c +++ b/libclamav/untar.c @@ -62,8 +62,9 @@ octal(const char *str) { int ret; - if (sscanf(str, "%o", (unsigned int *)&ret) != 1) + if (sscanf(str, "%o", (unsigned int *)&ret) != 1) { return -1; + } return ret; } @@ -149,15 +150,18 @@ cl_error_t cli_untar(const char *dir, unsigned int posix, cli_ctx *ctx) block = fmap_need_off_once_len(ctx->fmap, pos, BLOCKSIZE, &nread); cli_dbgmsg("cli_untar: pos = %lu\n", (unsigned long)pos); - if (!in_block && !nread) + if (!in_block && !nread) { break; + } - if (!nread) + if (!nread) { block = zero; + } if (!block) { - if (fout >= 0) + if (fout >= 0) { close(fout); + } cli_errmsg("cli_untar: block read error\n"); return CL_EREAD; } @@ -185,10 +189,12 @@ cl_error_t cli_untar(const char *dir, unsigned int posix, cli_ctx *ctx) fout = -1; } - if (block[0] == '\0') /* We're done */ + if (block[0] == '\0') { /* We're done */ break; - if ((ret = cli_checklimits("cli_untar", ctx, 0, 0, 0)) != CL_CLEAN) + } + if ((ret = cli_checklimits("cli_untar", ctx, 0, 0, 0)) != CL_CLEAN) { return ret; + } if (nread < TARHEADERSIZE) { return CL_CLEAN; @@ -325,8 +331,9 @@ cl_error_t cli_untar(const char *dir, unsigned int posix, cli_ctx *ctx) char err[128]; nbytes = (size > 512) ? 512 : size; - if (nread && (nread < nbytes)) + if (nread && (nread < nbytes)) { nbytes = nread; + } if (limitnear > 0) { currsize += nbytes; @@ -360,8 +367,9 @@ cl_error_t cli_untar(const char *dir, unsigned int posix, cli_ctx *ctx) size = 0; } } - if (size == 0) + if (size == 0) { in_block = 0; + } } if (fout >= 0) { lseek(fout, 0, SEEK_SET); diff --git a/libclamav/unzip.c b/libclamav/unzip.c index ec9046fbc6..35368ace04 100644 --- a/libclamav/unzip.c +++ b/libclamav/unzip.c @@ -125,15 +125,23 @@ static cl_error_t unz( if (tmpd) { if (ctx->engine->keeptmp && (NULL != original_filename)) { - if (!(tempfile = cli_gentemp_with_prefix(tmpd, original_filename))) return CL_EMEM; + if (!(tempfile = cli_gentemp_with_prefix(tmpd, original_filename))) { + return CL_EMEM; + } } else { - if (!(tempfile = cli_gentemp(tmpd))) return CL_EMEM; + if (!(tempfile = cli_gentemp(tmpd))) { + return CL_EMEM; + } } } else { if (ctx->engine->keeptmp && (NULL != original_filename)) { - if (!(tempfile = cli_gentemp_with_prefix(ctx->sub_tmpdir, original_filename))) return CL_EMEM; + if (!(tempfile = cli_gentemp_with_prefix(ctx->sub_tmpdir, original_filename))) { + return CL_EMEM; + } } else { - if (!(tempfile = cli_gentemp(ctx->sub_tmpdir))) return CL_EMEM; + if (!(tempfile = cli_gentemp(ctx->sub_tmpdir))) { + return CL_EMEM; + } } } if ((out_file = open(tempfile, O_RDWR | O_CREAT | O_TRUNC | O_BINARY, S_IRUSR | S_IWUSR)) == -1) { @@ -150,8 +158,9 @@ static cl_error_t unz( tmpd, zcb, original_filename, decrypted))) { (*num_files_unzipped)++; res = fake - (*num_files_unzipped); - } else + } else { break; + } } if (res == 1) { if (ctx->engine->maxfilesize && csize > ctx->engine->maxfilesize) { @@ -159,10 +168,11 @@ static cl_error_t unz( (long unsigned int)ctx->engine->maxfilesize); csize = ctx->engine->maxfilesize; } - if (cli_writen(out_file, src, csize) != csize) + if (cli_writen(out_file, src, csize) != csize) { ret = CL_EWRITE; - else + } else { res = 0; + } } break; @@ -237,7 +247,9 @@ static cl_error_t unz( break; } unz_end(&strm); - if ((res == Z_STREAM_END) | (res == Z_BUF_ERROR)) res = 0; + if ((res == Z_STREAM_END) | (res == Z_BUF_ERROR)) { + res = 0; + } break; } @@ -274,12 +286,16 @@ static cl_error_t unz( } strm.next_out = obuf; strm.avail_out = sizeof(obuf); - if (res == BZ_OK) continue; /* after returning BZ_STREAM_END once, decompress returns an error */ + if (res == BZ_OK) { + continue; /* after returning BZ_STREAM_END once, decompress returns an error */ + } } break; } BZ2_bzDecompressEnd(&strm); - if (res == BZ_STREAM_END) res = 0; + if (res == BZ_STREAM_END) { + res = 0; + } break; } @@ -353,15 +369,21 @@ static cl_error_t unz( } ret = zcb(out_file, tempfile, ctx, original_filename, decrypted); close(out_file); - if (!ctx->engine->keeptmp) - if (cli_unlink(tempfile)) ret = CL_EUNLINK; + if (!ctx->engine->keeptmp) { + if (cli_unlink(tempfile)) { + ret = CL_EUNLINK; + } + } free(tempfile); return ret; } close(out_file); - if (!ctx->engine->keeptmp) - if (cli_unlink(tempfile)) ret = CL_EUNLINK; + if (!ctx->engine->keeptmp) { + if (cli_unlink(tempfile)) { + ret = CL_EUNLINK; + } + } free(tempfile); cli_dbgmsg("cli_unzip: extraction failed\n"); return ret; @@ -393,8 +415,9 @@ static inline void zinitkey(uint32_t key[3], struct cli_pwdb *password) key[2] = 878082192L; /* update keys with password */ - for (i = 0; i < password->length; i++) + for (i = 0; i < password->length; i++) { zupdatekey(key, password->passwd[i]); + } } /* zip decrypt byte */ @@ -438,8 +461,9 @@ static inline cl_error_t zdecrypt( uint8_t encryption_header[12]; /* encryption header buffer */ struct cli_pwdb *password, *pass_any, *pass_zip; - if (!ctx || !ctx->engine) + if (!ctx || !ctx->engine) { return CL_ENULLARG; + } /* dconf */ if (ctx->dconf && !(ctx->dconf->archive & ARCH_CONF_PASSWD)) { @@ -469,24 +493,28 @@ static inline cl_error_t zdecrypt( if (LOCAL_HEADER_flags & F_USEDD) { cli_dbgmsg("cli_unzip: decrypt - (v%u) >> 0x%02x 0x%x (moddate)\n", LOCAL_HEADER_version, a, LOCAL_HEADER_mtime); - if (a == ((LOCAL_HEADER_mtime >> 8) & 0xff)) + if (a == ((LOCAL_HEADER_mtime >> 8) & 0xff)) { v = 1; + } } else { cli_dbgmsg("cli_unzip: decrypt - (v%u) >> 0x%02x 0x%x (crc32)\n", LOCAL_HEADER_version, a, LOCAL_HEADER_crc32); - if (a == ((LOCAL_HEADER_crc32 >> 24) & 0xff)) + if (a == ((LOCAL_HEADER_crc32 >> 24) & 0xff)) { v = 1; + } } } else { uint16_t a = encryption_header[SIZEOF_ENCRYPTION_HEADER - 1], b = encryption_header[SIZEOF_ENCRYPTION_HEADER - 2]; if (LOCAL_HEADER_flags & F_USEDD) { cli_dbgmsg("cli_unzip: decrypt - (v%u) >> 0x0000%02x%02x 0x%x (moddate)\n", LOCAL_HEADER_version, a, b, LOCAL_HEADER_mtime); - if ((uint32_t)(b | (a << 8)) == (LOCAL_HEADER_mtime & 0xffff)) + if ((uint32_t)(b | (a << 8)) == (LOCAL_HEADER_mtime & 0xffff)) { v = 1; + } } else { cli_dbgmsg("cli_unzip: decrypt - (v%u) >> 0x0000%02x%02x 0x%x (crc32)\n", LOCAL_HEADER_version, encryption_header[SIZEOF_ENCRYPTION_HEADER - 1], encryption_header[SIZEOF_ENCRYPTION_HEADER - 2], LOCAL_HEADER_crc32); - if ((uint32_t)(b | (a << 8)) == ((LOCAL_HEADER_crc32 >> 16) & 0xffff)) + if ((uint32_t)(b | (a << 8)) == ((LOCAL_HEADER_crc32 >> 16) & 0xffff)) { v = 1; + } } } @@ -505,11 +533,15 @@ static inline cl_error_t zdecrypt( snprintf(name, sizeof(name), "%s" PATHSEP "zip.decrypt.%03u", tmpd, *num_files_unzipped); name[sizeof(name) - 1] = '\0'; } else { - if (!(tempfile = cli_gentemp_with_prefix(ctx->sub_tmpdir, "zip-decrypt"))) return CL_EMEM; + if (!(tempfile = cli_gentemp_with_prefix(ctx->sub_tmpdir, "zip-decrypt"))) { + return CL_EMEM; + } } if ((out_file = open(tempfile, O_RDWR | O_CREAT | O_TRUNC | O_BINARY, S_IRUSR | S_IWUSR)) == -1) { cli_warnmsg("cli_unzip: decrypt - failed to create temporary file %s\n", tempfile); - if (!tmpd) free(tempfile); + if (!tmpd) { + free(tempfile); + } return CL_ETMPFILE; } @@ -560,19 +592,25 @@ static inline cl_error_t zdecrypt( funmap(dcypt_map); zd_clean: close(out_file); - if (!ctx->engine->keeptmp) + if (!ctx->engine->keeptmp) { if (cli_unlink(tempfile)) { - if (!tmpd) free(tempfile); + if (!tmpd) { + free(tempfile); + } return CL_EUNLINK; } - if (!tmpd) free(tempfile); + } + if (!tmpd) { + free(tempfile); + } return ret; } - if (pass_zip) + if (pass_zip) { pass_zip = pass_zip->next; - else + } else { pass_any = pass_any->next; + } } cli_dbgmsg("cli_unzip: decrypt failed - will attempt to unzip as if it were not encrypted\n"); @@ -630,10 +668,11 @@ static unsigned int parse_local_file_header( goto done; } if (LOCAL_HEADER_magic != ZIP_MAGIC_LOCAL_FILE_HEADER) { - if (!central_header) + if (!central_header) { cli_dbgmsg("cli_unzip: local header - wrkcomplete\n"); - else + } else { cli_dbgmsg("cli_unzip: local header - bad magic\n"); + } fmap_unneed_off(map, loff, SIZEOF_LOCAL_HEADER); goto done; } @@ -726,12 +765,14 @@ static unsigned int parse_local_file_header( /* Don't actually unzip if we're just collecting the file record information (offset, sizes) */ if (NULL == record) { if (LOCAL_HEADER_flags & F_ENCR) { - if (fmap_need_ptr_once(map, zip, csize)) + if (fmap_need_ptr_once(map, zip, csize)) { *ret = zdecrypt(zip, csize, usize, local_header, num_files_unzipped, ctx, tmpd, zcb, original_filename); + } } else { - if (fmap_need_ptr_once(map, zip, csize)) + if (fmap_need_ptr_once(map, zip, csize)) { *ret = unz(zip, csize, usize, LOCAL_HEADER_method, LOCAL_HEADER_flags, num_files_unzipped, ctx, tmpd, zcb, original_filename, false); + } } } else { if ((NULL == original_filename) || @@ -937,10 +978,11 @@ static int sort_by_file_offset(const void *first, const void *second) /* Avoid return x - y, which can cause undefined behaviour because of signed integer overflow. */ - if (a->local_header_offset < b->local_header_offset) + if (a->local_header_offset < b->local_header_offset) { return -1; - else if (a->local_header_offset > b->local_header_offset) + } else if (a->local_header_offset > b->local_header_offset) { return 1; + } return 0; } @@ -1246,8 +1288,9 @@ cl_error_t index_local_file_headers_within_bounds( * Search for local file headers between the start and end offsets. Append found file headers to zip_catalogue */ for (coff = start_offset; coff < end_offset; coff++) { - if (!(ptr = fmap_need_off_once(map, coff, 4))) + if (!(ptr = fmap_need_off_once(map, coff, 4))) { continue; + } if (cli_readint32(ptr) == ZIP_MAGIC_LOCAL_FILE_HEADER) { // increment coff by the size of the found local file header + file data coff += parse_local_file_header( @@ -1643,11 +1686,14 @@ cl_error_t cli_unzip(cli_ctx *ctx) } for (coff = fsize - 22; coff > 0; coff--) { /* sizeof(EOC)==22 */ - if (!(ptr = fmap_need_off_once(map, coff, 20))) + if (!(ptr = fmap_need_off_once(map, coff, 20))) { continue; + } if (cli_readint32(ptr) == ZIP_MAGIC_CENTRAL_DIRECTORY_RECORD_END) { uint32_t chptr = cli_readint32(&ptr[16]); - if (!CLI_ISCONTAINED_0_TO(fsize, chptr, SIZEOF_CENTRAL_HEADER)) continue; + if (!CLI_ISCONTAINED_0_TO(fsize, chptr, SIZEOF_CENTRAL_HEADER)) { + continue; + } coff = chptr; break; } @@ -1887,8 +1933,9 @@ cl_error_t unzip_search(cli_ctx *ctx, fmap_t *map, struct zip_requests *requests } /* get priority to given map over ctx->fmap */ - if (ctx && !map) + if (ctx && !map) { zmap = ctx->fmap; + } fsize = zmap->len; if (sizeof(off_t) != sizeof(uint32_t) && fsize != zmap->len) { cli_dbgmsg("unzip_search: file too big\n"); @@ -1900,11 +1947,14 @@ cl_error_t unzip_search(cli_ctx *ctx, fmap_t *map, struct zip_requests *requests } for (coff = fsize - 22; coff > 0; coff--) { /* sizeof(EOC)==22 */ - if (!(ptr = fmap_need_off_once(zmap, coff, 20))) + if (!(ptr = fmap_need_off_once(zmap, coff, 20))) { continue; + } if (cli_readint32(ptr) == ZIP_MAGIC_CENTRAL_DIRECTORY_RECORD_END) { uint32_t chptr = cli_readint32(&ptr[16]); - if (!CLI_ISCONTAINED_0_TO(fsize, chptr, SIZEOF_CENTRAL_HEADER)) continue; + if (!CLI_ISCONTAINED_0_TO(fsize, chptr, SIZEOF_CENTRAL_HEADER)) { + continue; + } coff = chptr; break; } diff --git a/libclamav/upack.c b/libclamav/upack.c index 88e8929fc6..b982cecbdc 100644 --- a/libclamav/upack.c +++ b/libclamav/upack.c @@ -71,12 +71,14 @@ int unupack(int upack, char *dest, uint32_t dsize, char *buff, uint32_t vma, uin uint32_t aljump, shroff, lngjmpoff; /* dummy characteristics ;/ */ - if (buff[5] == '\xff' && buff[6] == '\x36') + if (buff[5] == '\xff' && buff[6] == '\x36') { upack_version = UPACK_0297729; + } loc_esi = dest + (cli_readint32(buff + 1) - vma); - if (!CLI_ISCONTAINED(dest, dsize, loc_esi, 12)) + if (!CLI_ISCONTAINED(dest, dsize, loc_esi, 12)) { return -1; + } original_ep = cli_readint32(loc_esi); loc_esi += 4; /*cli_readint32(loc_esi);*/ @@ -88,41 +90,47 @@ int unupack(int upack, char *dest, uint32_t dsize, char *buff, uint32_t vma, uin if (upack_version == UPACK_399) { /* jmp 1 */ loc_edi = dest + (cli_readint32(loc_esi) - vma); - if (!CLI_ISCONTAINED(dest, dsize, dest + ep + 0xa, 2) || dest[ep + 0xa] != '\xeb') + if (!CLI_ISCONTAINED(dest, dsize, dest + ep + 0xa, 2) || dest[ep + 0xa] != '\xeb') { return -1; + } loc_esi = dest + *(dest + ep + 0xb) + ep + 0xc; /* use this as a temp var */ /* jmp 2 + 0xa */ alvalue = loc_esi + 0x1a; - if (!CLI_ISCONTAINED(dest, dsize, alvalue, 2) || *alvalue != '\xeb') + if (!CLI_ISCONTAINED(dest, dsize, alvalue, 2) || *alvalue != '\xeb') { return -1; + } alvalue++; alvalue += (*alvalue & 0xff) + 1 + 0xa; lngjmpoff = 8; } else { - if (!CLI_ISCONTAINED(dest, dsize, dest + ep + 7, 5) || dest[ep + 7] != '\xe9') + if (!CLI_ISCONTAINED(dest, dsize, dest + ep + 7, 5) || dest[ep + 7] != '\xe9') { return -1; + } loc_esi = dest + cli_readint32(dest + ep + 8) + ep + 0xc; alvalue = loc_esi + 0x25; lngjmpoff = 10; } - if (!CLI_ISCONTAINED(dest, dsize, alvalue, 2) || *alvalue != '\xb5') + if (!CLI_ISCONTAINED(dest, dsize, alvalue, 2) || *alvalue != '\xb5') { return -1; + } alvalue++; count = *alvalue & 0xff; - if (!CLI_ISCONTAINED(dest, dsize, alvalue, lngjmpoff + 5) || *(alvalue + lngjmpoff) != '\xe9') + if (!CLI_ISCONTAINED(dest, dsize, alvalue, lngjmpoff + 5) || *(alvalue + lngjmpoff) != '\xe9') { return -1; + } /* use this as a temp to make a long jmp to head of unpacking proc */ shlsize = cli_readint32(alvalue + lngjmpoff + 1); /* upack_399 + upack_0151477 */ - if (upack_version == UPACK_399) + if (upack_version == UPACK_399) { shlsize = shlsize + (loc_esi - dest) + *(loc_esi + 0x1b) + 0x1c + 0x018; /* read checked above */ - else + } else { /* there is no additional jump in upack_0297729 */ shlsize = shlsize + (loc_esi - dest) + 0x035; + } /* do the jump, 43 - point to jecxz */ alvalue = dest + shlsize + 43; @@ -132,11 +140,12 @@ int unupack(int upack, char *dest, uint32_t dsize, char *buff, uint32_t vma, uin if (!CLI_ISCONTAINED(dest, dsize, alvalue - 1, 2) || *(alvalue - 1) != '\xe3') { /* in upack_0297729 and upack_0151477 jecxz is at offset: 46 */ alvalue = dest + shlsize + 46; - if (!CLI_ISCONTAINED(dest, dsize, alvalue - 1, 2) || *(alvalue - 1) != '\xe3') + if (!CLI_ISCONTAINED(dest, dsize, alvalue - 1, 2) || *(alvalue - 1) != '\xe3') { return -1; - else { - if (upack_version != UPACK_0297729) + } else { + if (upack_version != UPACK_0297729) { upack_version = UPACK_0151477; + } aljump = 7; shroff = 26; } @@ -144,16 +153,19 @@ int unupack(int upack, char *dest, uint32_t dsize, char *buff, uint32_t vma, uin /* do jecxz */ alvalue += (*alvalue & 0xff) + 1; /* is there a long jump ? */ - if (!CLI_ISCONTAINED(dest, dsize, alvalue, aljump + 5) || *(alvalue + aljump) != '\xe9') + if (!CLI_ISCONTAINED(dest, dsize, alvalue, aljump + 5) || *(alvalue + aljump) != '\xe9') { return -1; + } /* do jmp, 1+4 - size of jmp instruction, aljump - instruction offset, 27 offset to cmp al,xx*/ ret = cli_readint32(alvalue + aljump + 1); alvalue += ret + aljump + 1 + 4 + 27; - if (upack_version == UPACK_0297729) + if (upack_version == UPACK_0297729) { alvalue += 2; + } /* shr ebp */ - if (!CLI_ISCONTAINED(dest, dsize, dest + shlsize + shroff, 3) || *(dest + shlsize + shroff) != '\xc1' || *(dest + shlsize + shroff + 1) != '\xed') + if (!CLI_ISCONTAINED(dest, dsize, dest + shlsize + shroff, 3) || *(dest + shlsize + shroff) != '\xc1' || *(dest + shlsize + shroff + 1) != '\xed') { return -1; + } shlsize = (*(dest + shlsize + shroff + 2)) & 0xff; count *= 0x100; if (shlsize < 2 || shlsize > 8) { @@ -164,32 +176,39 @@ int unupack(int upack, char *dest, uint32_t dsize, char *buff, uint32_t vma, uin /* check if loc_esi + .. == 0xbe -> mov esi */ /* upack_0297729 has mov esi, .. + mov edi, .., in upack_0151477 and upack_399 EDI has been already set before */ if (upack_version == UPACK_0297729) { - if (!CLI_ISCONTAINED(dest, dsize, loc_esi + 6, 10) || *(loc_esi + 6) != '\xbe' || *(loc_esi + 11) != '\xbf') + if (!CLI_ISCONTAINED(dest, dsize, loc_esi + 6, 10) || *(loc_esi + 6) != '\xbe' || *(loc_esi + 11) != '\xbf') { return -1; - if ((uint32_t)cli_readint32(loc_esi + 7) < base || (uint32_t)cli_readint32(loc_esi + 7) > vma) + } + if ((uint32_t)cli_readint32(loc_esi + 7) < base || (uint32_t)cli_readint32(loc_esi + 7) > vma) { return -1; + } loc_edi = dest + (cli_readint32(loc_esi + 12) - vma); loc_esi = dest + (cli_readint32(loc_esi + 7) - base); } else { - if (!CLI_ISCONTAINED(dest, dsize, loc_esi + 7, 5) || *(loc_esi + 7) != '\xbe') + if (!CLI_ISCONTAINED(dest, dsize, loc_esi + 7, 5) || *(loc_esi + 7) != '\xbe') { return -1; + } loc_esi = dest + (cli_readint32(loc_esi + 8) - vma); } if (upack_version == UPACK_0297729) { /* 0x16*4=0x58, 6longs*4 = 24, 0x64-last loc_esi read location */ - if (!CLI_ISCONTAINED(dest, dsize, loc_edi, (0x58 + 24 + 4 * count)) || !CLI_ISCONTAINED(dest, dsize, loc_esi, (0x58 + 0x64 + 4))) + if (!CLI_ISCONTAINED(dest, dsize, loc_edi, (0x58 + 24 + 4 * count)) || !CLI_ISCONTAINED(dest, dsize, loc_esi, (0x58 + 0x64 + 4))) { return -1; + } /* XXX I don't know if this [0x16] is constant number, not enough samples provided */ - for (j = 0; j < 0x16; j++, loc_esi += 4, loc_edi += 4) + for (j = 0; j < 0x16; j++, loc_esi += 4, loc_edi += 4) { cli_writeint32(loc_edi, cli_readint32(loc_esi)); + } } else { /* 0x27*4=0x9c, 6longs*4 = 24, 0x34-last loc_esi read location */ - if (!CLI_ISCONTAINED(dest, dsize, loc_edi, (0x9c + 24 + 4 * count)) || !CLI_ISCONTAINED(dest, dsize, loc_esi, (0x9c + 0x34 + 4))) + if (!CLI_ISCONTAINED(dest, dsize, loc_edi, (0x9c + 24 + 4 * count)) || !CLI_ISCONTAINED(dest, dsize, loc_esi, (0x9c + 0x34 + 4))) { return -1; - for (j = 0; j < 0x27; j++, loc_esi += 4, loc_edi += 4) + } + for (j = 0; j < 0x27; j++, loc_esi += 4, loc_edi += 4) { cli_writeint32(loc_edi, cli_readint32(loc_esi)); + } } save3 = cli_readint32(loc_esi + 4); paddr = dest + ((uint32_t)cli_readint32(loc_edi - 4)) - vma; @@ -198,15 +217,18 @@ int unupack(int upack, char *dest, uint32_t dsize, char *buff, uint32_t vma, uin loc_edi += 4; cli_writeint32(loc_edi, 0); loc_edi += 4; - for (j = 0; j < 4; j++, loc_edi += 4) + for (j = 0; j < 4; j++, loc_edi += 4) { cli_writeint32(loc_edi, (1)); + } - for (j = 0; (unsigned int)j < count; j++, loc_edi += 4) + for (j = 0; (unsigned int)j < count; j++, loc_edi += 4) { cli_writeint32(loc_edi, 0x400); + } loc_edi = dest + cli_readint32(loc_esi + 0xc) - vma; - if (upack_version == UPACK_0297729) + if (upack_version == UPACK_0297729) { loc_edi = dest + vma - base; /* XXX not enough samples provided to be sure of it! */ + } pushed_esi = loc_edi; if (upack_version == UPACK_0297729) { @@ -221,15 +243,17 @@ int unupack(int upack, char *dest, uint32_t dsize, char *buff, uint32_t vma, uin } /* begin end */ cli_dbgmsg("Upack: data initialized, before upack lzma call!\n"); - if ((ret = (uint32_t)unupack399(dest, dsize, 0, loc_ebx, 0, loc_edi, end_edi, shlsize, paddr)) == 0xffffffff) + if ((ret = (uint32_t)unupack399(dest, dsize, 0, loc_ebx, 0, loc_edi, end_edi, shlsize, paddr)) == 0xffffffff) { return -1; + } /* alternative begin */ } else { int ep_jmp_offs, rep_stosd_count_offs, context_bits_offs; loc_esi = dest + vma + ep; /* yet another dummy characteristics ;/ */ - if (buff[0] == '\xbe' && buff[5] == '\xad' && buff[6] == '\x8b' && buff[7] == '\xf8') + if (buff[0] == '\xbe' && buff[5] == '\xad' && buff[6] == '\x8b' && buff[7] == '\xf8') { upack_version = UPACK_11_12; + } if (upack_version == UPACK_11_12) { ep_jmp_offs = 0x1a4; @@ -243,8 +267,9 @@ int unupack(int upack, char *dest, uint32_t dsize, char *buff, uint32_t vma, uin alvalue = loc_esi + 0x1c1; } - if (!CLI_ISCONTAINED(dest, dsize, loc_esi, ep_jmp_offs + 4)) + if (!CLI_ISCONTAINED(dest, dsize, loc_esi, ep_jmp_offs + 4)) { return -1; + } save1 = cli_readint32(loc_esi + ep_jmp_offs); original_ep = (loc_esi - dest) + ep_jmp_offs + 4; original_ep += (int32_t)save1; @@ -271,8 +296,9 @@ int unupack(int upack, char *dest, uint32_t dsize, char *buff, uint32_t vma, uin return -1; /* XXX XXX XXX XXX */ } loc_esi -= (loc_ecx - 2); - if (!CLI_ISCONTAINED(dest, dsize, loc_esi, 12)) + if (!CLI_ISCONTAINED(dest, dsize, loc_esi, 12)) { return -1; + } cli_dbgmsg("Upack: %p %p %08x %08x\n", loc_esi, dest, cli_readint32(loc_esi), base); loc_ebx_u = loc_esi - (dest + cli_readint32(loc_esi) - base); @@ -292,14 +318,18 @@ int unupack(int upack, char *dest, uint32_t dsize, char *buff, uint32_t vma, uin loc_esi += 4; cli_dbgmsg("Upack: ecx counter: %08x\n", j); - if (((uint64_t)count + j) * 4 > UINT_MAX) + if (((uint64_t)count + j) * 4 > UINT_MAX) { return -1; - if (!CLI_ISCONTAINED(dest, dsize, loc_esi, (j * 4)) || !CLI_ISCONTAINED(dest, dsize, loc_edi, ((j + count) * 4))) + } + if (!CLI_ISCONTAINED(dest, dsize, loc_esi, (j * 4)) || !CLI_ISCONTAINED(dest, dsize, loc_edi, ((j + count) * 4))) { return -1; - for (; j--; loc_edi += 4, loc_esi += 4) + } + for (; j--; loc_edi += 4, loc_esi += 4) { cli_writeint32(loc_edi, cli_readint32(loc_esi)); - if (!CLI_ISCONTAINED(dest, dsize, save2, 8)) + } + if (!CLI_ISCONTAINED(dest, dsize, save2, 8)) { return -1; + } loc_ecx = cli_readint32(save2); save2 += 4; loc_esi = save2; @@ -310,16 +340,19 @@ int unupack(int upack, char *dest, uint32_t dsize, char *buff, uint32_t vma, uin loc_esi += loc_ebx_u; loc_esi += 4; } while (--loc_ecx); - if (!CLI_ISCONTAINED(dest, dsize, loc_esi, 4)) + if (!CLI_ISCONTAINED(dest, dsize, loc_esi, 4)) { return -1; + } save1 = cli_readint32(loc_esi); /* loc_eax = 0x400 */ loc_esi += 4; - for (j = 0; (uint32_t)j < count; j++, loc_edi += 4) /* checked above */ + for (j = 0; (uint32_t)j < count; j++, loc_edi += 4) { /* checked above */ cli_writeint32(loc_edi, (save1)); + } - if (!CLI_ISCONTAINED(dest, dsize, (loc_esi + 0x10), 4)) + if (!CLI_ISCONTAINED(dest, dsize, (loc_esi + 0x10), 4)) { return -1; + } cli_writeint32(loc_esi + 0x10, (uint32_t)cli_readint32(loc_esi + 0x10) + loc_ebx_u); loc_ebx = loc_esi + 0x14; loc_esi = save2; @@ -329,8 +362,9 @@ int unupack(int upack, char *dest, uint32_t dsize, char *buff, uint32_t vma, uin loc_esi += 4; cli_dbgmsg("Upack: before_fixing\n"); /* fix values */ - if (!CLI_ISCONTAINED(dest, dsize, loc_ebx - 4, (12 + 4 * 4)) || !CLI_ISCONTAINED(dest, dsize, loc_esi + 0x24, 4) || !CLI_ISCONTAINED(dest, dsize, loc_esi + 0x40, 4)) + if (!CLI_ISCONTAINED(dest, dsize, loc_ebx - 4, (12 + 4 * 4)) || !CLI_ISCONTAINED(dest, dsize, loc_esi + 0x24, 4) || !CLI_ISCONTAINED(dest, dsize, loc_esi + 0x40, 4)) { return -1; + } for (j = 2; j < 6; j++) { int32_t temp = cli_readint32(loc_ebx + (j << 2)); cli_writeint32(loc_ebx + (j << 2), temp); @@ -355,19 +389,23 @@ int unupack(int upack, char *dest, uint32_t dsize, char *buff, uint32_t vma, uin loc_edi += 4; loc_ebx = loc_edi; - if (((uint64_t)count + 6) * 4 > UINT_MAX) + if (((uint64_t)count + 6) * 4 > UINT_MAX) { return -1; - if (!CLI_ISCONTAINED(dest, dsize, loc_edi, ((6 + count) * 4))) + } + if (!CLI_ISCONTAINED(dest, dsize, loc_edi, ((6 + count) * 4))) { return -1; + } cli_writeint32(loc_edi, 0xffffffff); loc_edi += 4; cli_writeint32(loc_edi, 0); loc_edi += 4; - for (j = 0; j < 4; j++, loc_edi += 4) + for (j = 0; j < 4; j++, loc_edi += 4) { cli_writeint32(loc_edi, (1)); + } - for (j = 0; (uint32_t)j < count; j++, loc_edi += 4) + for (j = 0; (uint32_t)j < count; j++, loc_edi += 4) { cli_writeint32(loc_edi, 0x400); + } loc_edi = dest + cli_readint32(loc_esi) - base; /* read checked above */ pushed_esi = loc_edi; @@ -384,12 +422,14 @@ int unupack(int upack, char *dest, uint32_t dsize, char *buff, uint32_t vma, uin return -1; } cli_dbgmsg("Upack: data initialized, before upack lzma call!\n"); - if ((ret = (uint32_t)unupack399(dest, dsize, loc_ecx, loc_ebx, loc_ecx, loc_edi, end_edi, shlsize, paddr)) == 0xffffffff) + if ((ret = (uint32_t)unupack399(dest, dsize, loc_ecx, loc_ebx, loc_ecx, loc_edi, end_edi, shlsize, paddr)) == 0xffffffff) { return -1; - if (upack_version == UPACK_399) + } + if (upack_version == UPACK_399) { save3 = cli_readint32(loc_esi + 0x40); - else if (upack_version == UPACK_11_12) + } else if (upack_version == UPACK_11_12) { save3 = cli_readint32(dest + vma + ep + 0x174); + } } /* let's fix calls */ @@ -413,13 +453,15 @@ int unupack(int upack, char *dest, uint32_t dsize, char *buff, uint32_t vma, uin cli_dbgmsg("Upack: callfixerr\n"); return -1; } - if ((cli_readint32(adr) & 0xff) != searchval) + if ((cli_readint32(adr) & 0xff) != searchval) { continue; + } cli_writeint32(adr, EC32(CE32((uint32_t)(cli_readint32(adr) & 0xffffff00))) - loc_ecx - 4); loc_ecx += 4; save3--; - } else + } else { loc_ecx++; + } } section.raw = 0; @@ -483,18 +525,21 @@ int unupack399(char *bs, uint32_t bl, uint32_t init_eax, char *init_ebx, uint32_ eax_copy = loc_eax; loc_edx = loc_ebx + 0xbc0; state[5] = loc_ebp; - if (lzma_upack_esi_54(&p, loc_eax, &loc_ecx, &loc_edx, &temp, bs, bl) == 0xffffffff) + if (lzma_upack_esi_54(&p, loc_eax, &loc_ecx, &loc_edx, &temp, bs, bl) == 0xffffffff) { return -1; + } loc_ecx = 3; jakas_kopia = temp; loc_eax = temp - 1; - if (loc_eax >= loc_ecx) + if (loc_eax >= loc_ecx) { loc_eax = loc_ecx; + } loc_ecx = 0x40; loc_eax <<= 6; /* ecx=0x40, mul cl */ loc_ebp8 = loc_ebx + ((loc_eax << 2) + 0x378); - if (lzma_upack_esi_50(&p, 1, loc_ecx, &loc_edx, loc_ebp8, &loc_eax, bs, bl) == 0xffffffff) + if (lzma_upack_esi_50(&p, 1, loc_ecx, &loc_edx, loc_ebp8, &loc_eax, bs, bl) == 0xffffffff) { return -1; + } loc_ebp = loc_eax; if ((loc_eax & 0xff) >= 4) { /* loc_4839af */ @@ -514,8 +559,9 @@ int unupack399(char *bs, uint32_t bl, uint32_t init_eax, char *init_ebx, uint32_ uint32_t temp_edx; /* compare with lzma_upack_esi_00 */ /* do not put in one statement because of difference in signedness */ - if (!CLI_ISCONTAINED(bs, bl, p.p0, 4)) + if (!CLI_ISCONTAINED(bs, bl, p.p0, 4)) { return -1; + } temp_edx = cli_readint32((char *)p.p0); temp_edx = EC32(CE32(temp_edx)); p.p1 >>= 1; @@ -545,8 +591,9 @@ int unupack399(char *bs, uint32_t bl, uint32_t init_eax, char *init_ebx, uint32_ temp_ebp = loc_ecx; loc_ecx = loc_eax; loc_eax = temp_ebp; - if (lzma_upack_esi_50(&p, 1, loc_ecx, &loc_edx, loc_ebp8, &loc_eax, bs, bl) == 0xffffffff) + if (lzma_upack_esi_50(&p, 1, loc_ecx, &loc_edx, loc_ebp8, &loc_eax, bs, bl) == 0xffffffff) { return -1; + } /* cdq, loc_edx = (loc_eax&0x80000000)?0xffffffff:0; */ loc_ecx = temp_ebp; temp_ebp = CLI_SRS((int32_t)loc_eax, 31); /* thx, desp */ @@ -597,8 +644,9 @@ int unupack399(char *bs, uint32_t bl, uint32_t init_eax, char *init_ebx, uint32_ edi_copy = loc_edi; edi_copy -= state[2]; loc_ecx = (loc_ecx & 0xffffff00) | 0x80; - if (!CLI_ISCONTAINED(bs, bl, edi_copy, 1) || !CLI_ISCONTAINED(bs, bl, loc_edi, 1)) + if (!CLI_ISCONTAINED(bs, bl, edi_copy, 1) || !CLI_ISCONTAINED(bs, bl, loc_edi, 1)) { return -1; + } loc_al = (*(uint8_t *)edi_copy) & 0xff; /* loc_483922 */ /* ok jmp to 483a19 */ @@ -610,26 +658,30 @@ int unupack399(char *bs, uint32_t bl, uint32_t init_eax, char *init_ebx, uint32_ /* loc_48396a */ eax_copy = loc_eax; loc_edx = loc_ebx + 0x778; - if (lzma_upack_esi_54(&p, loc_eax, &loc_ecx, &loc_edx, &temp, bs, bl) == 0xffffffff) + if (lzma_upack_esi_54(&p, loc_eax, &loc_ecx, &loc_edx, &temp, bs, bl) == 0xffffffff) { return -1; + } loc_eax = loc_ecx; loc_ecx = temp; } /* loc_483a0b */ - if (!CLI_ISCONTAINED(bs, bl, loc_edi, loc_ecx) || !CLI_ISCONTAINED(bs, bl, loc_edi - loc_ebp, loc_ecx + 1)) + if (!CLI_ISCONTAINED(bs, bl, loc_edi, loc_ecx) || !CLI_ISCONTAINED(bs, bl, loc_edi - loc_ebp, loc_ecx + 1)) { return -1; + } state[2] = loc_ebp; - for (i = 0; i < loc_ecx; i++, loc_edi++) + for (i = 0; i < loc_ecx; i++, loc_edi++) { *loc_edi = *(loc_edi - loc_ebp); + } loc_eax = (loc_eax & 0xffffff00) | *(uint8_t *)(loc_edi - loc_ebp); loc_ecx = 0x80; } else { /* loc_4838d8 */ do { - if ((loc_al = (loc_eax & 0xff)) + 0xfd > 0xff) + if ((loc_al = (loc_eax & 0xff)) + 0xfd > 0xff) { loc_al -= 3; /* 0x100 - 0xfd = 3 */ - else + } else { loc_al = 0; + } loc_eax = (loc_eax & 0xffffff00) | loc_al; } while (loc_al >= 7); /* loc_4838e2 */ @@ -648,8 +700,9 @@ int unupack399(char *bs, uint32_t bl, uint32_t init_eax, char *init_ebx, uint32_ if (loc_ecx) { uint8_t loc_cl = loc_ecx & 0xff; loc_edi -= state[2]; - if (!CLI_ISCONTAINED(bs, bl, loc_edi, 1)) + if (!CLI_ISCONTAINED(bs, bl, loc_edi, 1)) { return -1; + } do { loc_eax = (loc_eax & 0xffff00ff) | ((*loc_edi & loc_cl) ? 0x200 : 0x100); @@ -668,18 +721,21 @@ int unupack399(char *bs, uint32_t bl, uint32_t init_eax, char *init_ebx, uint32_ if (!loc_ah) { loc_eax = (loc_eax & 0xffff0000) | (loc_ah << 8) | loc_al; /* loc_483918, loc_48391a */ - if (lzma_upack_esi_50(&p, loc_eax, 0x100, &loc_edx, loc_ebp8, &loc_eax, bs, bl) == 0xffffffff) + if (lzma_upack_esi_50(&p, loc_eax, 0x100, &loc_edx, loc_ebp8, &loc_eax, bs, bl) == 0xffffffff) { return -1; + } break; } - } else + } else { break; + } } while (1); } else { /* loc_48391a */ loc_ecx = (loc_ecx & 0xffff00ff) | 0x100; - if (lzma_upack_esi_50(&p, loc_eax, loc_ecx, &loc_edx, loc_ebp8, &loc_eax, bs, bl) == 0xffffffff) + if (lzma_upack_esi_50(&p, loc_eax, loc_ecx, &loc_edx, loc_ebp8, &loc_eax, bs, bl) == 0xffffffff) { return -1; + } } /* loc_48391f */ loc_ecx = 0; @@ -687,8 +743,9 @@ int unupack399(char *bs, uint32_t bl, uint32_t init_eax, char *init_ebx, uint32_ } /* loc_483a19 */ /* 2GiM: i think this one is not properly checked, 2aCaB: true */ - if (!CLI_ISCONTAINED(bs, bl, loc_edi, 1)) + if (!CLI_ISCONTAINED(bs, bl, loc_edi, 1)) { return -1; + } *loc_edi++ = (loc_eax & 0xff); } while (loc_edi < end_edi); diff --git a/libclamav/upx.c b/libclamav/upx.c index a01636023e..2f23e4f45e 100644 --- a/libclamav/upx.c +++ b/libclamav/upx.c @@ -101,16 +101,26 @@ static char *checkpe(char *dst, uint32_t dsize, char *pehdr, uint32_t *valign, unsigned int *sectcnt) { char *sections; - if (!CLI_ISCONTAINED(dst, dsize, pehdr, 0xf8)) return NULL; + if (!CLI_ISCONTAINED(dst, dsize, pehdr, 0xf8)) { + return NULL; + } - if (cli_readint32(pehdr) != 0x4550) return NULL; + if (cli_readint32(pehdr) != 0x4550) { + return NULL; + } - if (!(*valign = cli_readint32(pehdr + 0x38))) return NULL; + if (!(*valign = cli_readint32(pehdr + 0x38))) { + return NULL; + } sections = pehdr + 0xf8; - if (!(*sectcnt = (unsigned char)pehdr[6] + (unsigned char)pehdr[7] * 256)) return NULL; + if (!(*sectcnt = (unsigned char)pehdr[6] + (unsigned char)pehdr[7] * 256)) { + return NULL; + } - if (!CLI_ISCONTAINED(dst, dsize, sections, *sectcnt * 0x28)) return NULL; + if (!CLI_ISCONTAINED(dst, dsize, sections, *sectcnt * 0x28)) { + return NULL; + } return sections; } @@ -124,14 +134,16 @@ static int pefromupx(const char *src, uint32_t ssize, char *dst, uint32_t *dsize uint32_t realstuffsz = 0, valign = 0; uint32_t foffset = 0xd0 + 0xf8; - if ((dst == NULL) || (src == NULL)) + if ((dst == NULL) || (src == NULL)) { return 0; + } while ((valign = magic[sectcnt++])) { if (CLI_ISCONTAINED(src, ssize - 5, src + ep - upx1 + valign - 2, 2) && src[ep - upx1 + valign - 2] == '\x8d' && /* lea edi, ... */ - src[ep - upx1 + valign - 1] == '\xbe') /* ... [esi + offset] */ + src[ep - upx1 + valign - 1] == '\xbe') { /* ... [esi + offset] */ break; + } } if (!valign && CLI_ISCONTAINED(src, ssize - 8, src + ep - upx1 + 0x80, 8)) { @@ -161,15 +173,18 @@ static int pefromupx(const char *src, uint32_t ssize, char *dst, uint32_t *dsize pehdr += 8; while (CLI_ISCONTAINED(dst, *dsize, pehdr, 2) && *pehdr) { pehdr++; - while (CLI_ISCONTAINED(dst, *dsize, pehdr, 2) && *pehdr) + while (CLI_ISCONTAINED(dst, *dsize, pehdr, 2) && *pehdr) { pehdr++; + } pehdr++; } pehdr++; } pehdr += 4; - if (!(sections = checkpe(dst, *dsize, pehdr, &valign, §cnt))) pehdr = NULL; + if (!(sections = checkpe(dst, *dsize, pehdr, &valign, §cnt))) { + pehdr = NULL; + } } } @@ -177,11 +192,14 @@ static int pefromupx(const char *src, uint32_t ssize, char *dst, uint32_t *dsize cli_dbgmsg("UPX: no luck - scanning for PE\n"); pehdr = &dst[dend - 0xf8 - 0x28]; while (pehdr > dst) { - if ((sections = checkpe(dst, *dsize, pehdr, &valign, §cnt))) + if ((sections = checkpe(dst, *dsize, pehdr, &valign, §cnt))) { break; + } pehdr--; } - if (!(realstuffsz = pehdr - dst)) pehdr = NULL; + if (!(realstuffsz = pehdr - dst)) { + pehdr = NULL; + } } if (!pehdr) { @@ -204,8 +222,9 @@ static int pefromupx(const char *src, uint32_t ssize, char *dst, uint32_t *dsize return 1; } - if (!sections) + if (!sections) { sectcnt = 0; + } foffset = PESALIGN(foffset + 0x28 * sectcnt, valign); for (upd = 0; upd < sectcnt; upd++) { @@ -284,8 +303,9 @@ static int doubleebx(const char *src, uint32_t *myebx, uint32_t *scur, uint32_t *myebx *= 2; if (!(oldebx & 0x7fffffff)) { - if (!CLI_ISCONTAINED(src, ssize, src + *scur, 4)) + if (!CLI_ISCONTAINED(src, ssize, src + *scur, 4)) { return -1; + } oldebx = cli_readint32(src + *scur); *myebx = oldebx * 2 + 1; *scur += 4; @@ -303,77 +323,96 @@ int upx_inflate2b(const char *src, uint32_t ssize, char *dst, uint32_t *dsize, u while (1) { while ((oob = doubleebx(src, &myebx, &scur, ssize)) == 1) { - if (scur >= ssize || dcur >= *dsize) + if (scur >= ssize || dcur >= *dsize) { return -1; + } dst[dcur++] = src[scur++]; } - if (oob == -1) + if (oob == -1) { return -1; + } backbytes = 1; while (1) { - if ((oob = doubleebx(src, &myebx, &scur, ssize)) == -1) + if ((oob = doubleebx(src, &myebx, &scur, ssize)) == -1) { return -1; - if (((int64_t)backbytes + oob) > INT32_MAX / 2) + } + if (((int64_t)backbytes + oob) > INT32_MAX / 2) { return -1; + } backbytes = backbytes * 2 + oob; - if ((oob = doubleebx(src, &myebx, &scur, ssize)) == -1) + if ((oob = doubleebx(src, &myebx, &scur, ssize)) == -1) { return -1; - if (oob) + } + if (oob) { break; + } } backbytes -= 3; if (backbytes >= 0) { - if (scur >= ssize) + if (scur >= ssize) { return -1; - if (backbytes & 0xff000000) + } + if (backbytes & 0xff000000) { return -1; + } backbytes <<= 8; backbytes += (unsigned char)(src[scur++]); backbytes ^= 0xffffffff; - if (!backbytes) + if (!backbytes) { break; + } unp_offset = backbytes; } - if ((backsize = (uint32_t)doubleebx(src, &myebx, &scur, ssize)) == 0xffffffff) + if ((backsize = (uint32_t)doubleebx(src, &myebx, &scur, ssize)) == 0xffffffff) { return -1; - if ((oob = doubleebx(src, &myebx, &scur, ssize)) == -1) + } + if ((oob = doubleebx(src, &myebx, &scur, ssize)) == -1) { return -1; - if (backsize + oob > UINT32_MAX / 2) + } + if (backsize + oob > UINT32_MAX / 2) { return -1; + } backsize = backsize * 2 + oob; if (!backsize) { backsize++; do { - if ((oob = doubleebx(src, &myebx, &scur, ssize)) == -1) + if ((oob = doubleebx(src, &myebx, &scur, ssize)) == -1) { return -1; - if (backsize + oob > UINT32_MAX / 2) + } + if (backsize + oob > UINT32_MAX / 2) { return -1; + } backsize = backsize * 2 + oob; } while ((oob = doubleebx(src, &myebx, &scur, ssize)) == 0); - if (oob == -1) + if (oob == -1) { return -1; - if (backsize + 2 > UINT32_MAX) + } + if (backsize + 2 > UINT32_MAX) { return -1; + } backsize += 2; } - if ((uint32_t)unp_offset < 0xfffff300) + if ((uint32_t)unp_offset < 0xfffff300) { backsize++; + } backsize++; - if (!CLI_ISCONTAINED(dst, *dsize, dst + dcur + unp_offset, backsize) || !CLI_ISCONTAINED(dst, *dsize, dst + dcur, backsize) || unp_offset >= 0) + if (!CLI_ISCONTAINED(dst, *dsize, dst + dcur + unp_offset, backsize) || !CLI_ISCONTAINED(dst, *dsize, dst + dcur, backsize) || unp_offset >= 0) { return -1; - for (i = 0; i < backsize; i++) + } + for (i = 0; i < backsize; i++) { dst[dcur + i] = dst[dcur + unp_offset + i]; + } dcur += backsize; } @@ -388,31 +427,39 @@ int upx_inflate2d(const char *src, uint32_t ssize, char *dst, uint32_t *dsize, u while (1) { while ((oob = doubleebx(src, &myebx, &scur, ssize)) == 1) { - if (scur >= ssize || dcur >= *dsize) + if (scur >= ssize || dcur >= *dsize) { return -1; + } dst[dcur++] = src[scur++]; } - if (oob == -1) + if (oob == -1) { return -1; + } backbytes = 1; while (1) { - if ((oob = doubleebx(src, &myebx, &scur, ssize)) == -1) + if ((oob = doubleebx(src, &myebx, &scur, ssize)) == -1) { return -1; - if (((int64_t)backbytes + oob) > INT32_MAX / 2) + } + if (((int64_t)backbytes + oob) > INT32_MAX / 2) { return -1; + } backbytes = backbytes * 2 + oob; - if ((oob = doubleebx(src, &myebx, &scur, ssize)) == -1) + if ((oob = doubleebx(src, &myebx, &scur, ssize)) == -1) { return -1; - if (oob) + } + if (oob) { break; + } backbytes--; - if ((oob = doubleebx(src, &myebx, &scur, ssize)) == -1) + if ((oob = doubleebx(src, &myebx, &scur, ssize)) == -1) { return -1; - if (((int64_t)backbytes + oob) > INT32_MAX / 2) + } + if (((int64_t)backbytes + oob) > INT32_MAX / 2) { return -1; + } backbytes = backbytes * 2 + oob; } @@ -421,53 +468,66 @@ int upx_inflate2d(const char *src, uint32_t ssize, char *dst, uint32_t *dsize, u if (backbytes >= 0) { - if (scur >= ssize) + if (scur >= ssize) { return -1; - if (backbytes & 0xff000000) + } + if (backbytes & 0xff000000) { return -1; + } backbytes <<= 8; backbytes += (unsigned char)(src[scur++]); backbytes ^= 0xffffffff; - if (!backbytes) + if (!backbytes) { break; + } backsize = backbytes & 1; CLI_SAR(backbytes, 1); unp_offset = backbytes; } else { - if ((backsize = (uint32_t)doubleebx(src, &myebx, &scur, ssize)) == 0xffffffff) + if ((backsize = (uint32_t)doubleebx(src, &myebx, &scur, ssize)) == 0xffffffff) { return -1; + } } - if ((oob = doubleebx(src, &myebx, &scur, ssize)) == -1) + if ((oob = doubleebx(src, &myebx, &scur, ssize)) == -1) { return -1; - if (backsize + oob > UINT32_MAX / 2) + } + if (backsize + oob > UINT32_MAX / 2) { return -1; + } backsize = backsize * 2 + oob; if (!backsize) { backsize++; do { - if ((oob = doubleebx(src, &myebx, &scur, ssize)) == -1) + if ((oob = doubleebx(src, &myebx, &scur, ssize)) == -1) { return -1; - if (backsize + oob > UINT32_MAX / 2) + } + if (backsize + oob > UINT32_MAX / 2) { return -1; + } backsize = backsize * 2 + oob; } while ((oob = doubleebx(src, &myebx, &scur, ssize)) == 0); - if (oob == -1) + if (oob == -1) { return -1; - if (backsize + 2 > UINT32_MAX) + } + if (backsize + 2 > UINT32_MAX) { return -1; + } backsize += 2; } - if ((uint32_t)unp_offset < 0xfffffb00) + if ((uint32_t)unp_offset < 0xfffffb00) { backsize++; + } backsize++; - if (!CLI_ISCONTAINED(dst, *dsize, dst + dcur + unp_offset, backsize) || !CLI_ISCONTAINED(dst, *dsize, dst + dcur, backsize) || unp_offset >= 0) + if (!CLI_ISCONTAINED(dst, *dsize, dst + dcur + unp_offset, backsize) || !CLI_ISCONTAINED(dst, *dsize, dst + dcur, backsize) || unp_offset >= 0) { return -1; - for (i = 0; i < backsize; i++) + } + for (i = 0; i < backsize; i++) { dst[dcur + i] = dst[dcur + unp_offset + i]; + } dcur += backsize; } @@ -482,30 +542,38 @@ int upx_inflate2e(const char *src, uint32_t ssize, char *dst, uint32_t *dsize, u for (;;) { while ((oob = doubleebx(src, &myebx, &scur, ssize))) { - if (oob == -1) + if (oob == -1) { return -1; - if (scur >= ssize || dcur >= *dsize) + } + if (scur >= ssize || dcur >= *dsize) { return -1; + } dst[dcur++] = src[scur++]; } backbytes = 1; for (;;) { - if ((oob = doubleebx(src, &myebx, &scur, ssize)) == -1) + if ((oob = doubleebx(src, &myebx, &scur, ssize)) == -1) { return -1; - if (((int64_t)backbytes + oob) > INT32_MAX / 2) + } + if (((int64_t)backbytes + oob) > INT32_MAX / 2) { return -1; + } backbytes = backbytes * 2 + oob; - if ((oob = doubleebx(src, &myebx, &scur, ssize)) == -1) + if ((oob = doubleebx(src, &myebx, &scur, ssize)) == -1) { return -1; - if (oob) + } + if (oob) { break; + } backbytes--; - if ((oob = doubleebx(src, &myebx, &scur, ssize)) == -1) + if ((oob = doubleebx(src, &myebx, &scur, ssize)) == -1) { return -1; - if (((int64_t)backbytes + oob) > INT32_MAX / 2) + } + if (((int64_t)backbytes + oob) > INT32_MAX / 2) { return -1; + } backbytes = backbytes * 2 + oob; } @@ -513,64 +581,80 @@ int upx_inflate2e(const char *src, uint32_t ssize, char *dst, uint32_t *dsize, u if (backbytes >= 0) { - if (scur >= ssize) + if (scur >= ssize) { return -1; - if (backbytes & 0xff000000) + } + if (backbytes & 0xff000000) { return -1; + } backbytes <<= 8; backbytes += (unsigned char)(src[scur++]); backbytes ^= 0xffffffff; - if (!backbytes) + if (!backbytes) { break; + } backsize = backbytes & 1; /* Using backsize to carry on the shifted out bit (UPX uses CF) */ CLI_SAR(backbytes, 1); unp_offset = backbytes; } else { - if ((backsize = (uint32_t)doubleebx(src, &myebx, &scur, ssize)) == 0xffffffff) + if ((backsize = (uint32_t)doubleebx(src, &myebx, &scur, ssize)) == 0xffffffff) { return -1; + } } /* Using backsize to carry on the doubleebx result (UPX uses CF) */ if (backsize) { /* i.e. IF ( last sar shifted out 1 bit || last doubleebx()==1 ) */ - if ((backsize = (uint32_t)doubleebx(src, &myebx, &scur, ssize)) == 0xffffffff) + if ((backsize = (uint32_t)doubleebx(src, &myebx, &scur, ssize)) == 0xffffffff) { return -1; + } } else { backsize = 1; - if ((oob = doubleebx(src, &myebx, &scur, ssize)) == -1) + if ((oob = doubleebx(src, &myebx, &scur, ssize)) == -1) { return -1; + } if (oob) { - if ((oob = doubleebx(src, &myebx, &scur, ssize)) == -1) + if ((oob = doubleebx(src, &myebx, &scur, ssize)) == -1) { return -1; - if (backsize + oob > UINT32_MAX / 2) + } + if (backsize + oob > UINT32_MAX / 2) { return -1; + } backsize = 2 + oob; } else { do { - if ((oob = doubleebx(src, &myebx, &scur, ssize)) == -1) + if ((oob = doubleebx(src, &myebx, &scur, ssize)) == -1) { return -1; - if (backsize + oob > UINT32_MAX / 2) + } + if (backsize + oob > UINT32_MAX / 2) { return -1; + } backsize = backsize * 2 + oob; } while ((oob = doubleebx(src, &myebx, &scur, ssize)) == 0); - if (oob == -1) + if (oob == -1) { return -1; - if (backsize + 2 > UINT32_MAX) + } + if (backsize + 2 > UINT32_MAX) { return -1; + } backsize += 2; } } - if ((uint32_t)unp_offset < 0xfffffb00) + if ((uint32_t)unp_offset < 0xfffffb00) { backsize++; + } - if (backsize + 2 > UINT32_MAX) + if (backsize + 2 > UINT32_MAX) { return -1; + } backsize += 2; - if (!CLI_ISCONTAINED(dst, *dsize, dst + dcur + unp_offset, backsize) || !CLI_ISCONTAINED(dst, *dsize, dst + dcur, backsize) || unp_offset >= 0) + if (!CLI_ISCONTAINED(dst, *dsize, dst + dcur + unp_offset, backsize) || !CLI_ISCONTAINED(dst, *dsize, dst + dcur, backsize) || unp_offset >= 0) { return -1; - for (i = 0; i < backsize; i++) + } + for (i = 0; i < backsize; i++) { dst[dcur + i] = dst[dcur + unp_offset + i]; + } dcur += backsize; } @@ -588,14 +672,16 @@ int upx_inflatelzma(const char *src, uint32_t ssize, char *dst, uint32_t *dsize, uint8_t lc = properties & 0xff; uint8_t lp = (properties >> 8) & 0xff; uint8_t pb = (properties >> 16) & 0xff; - if (lc >= 9 || lp >= 5 || pb >= 5) + if (lc >= 9 || lp >= 5 || pb >= 5) { return -1; + } *fake_lzmahdr = lc + 9 * (5 * pb + lp); l.next_in = fake_lzmahdr; l.avail_in = 5; - if (cli_LzmaInit(&l, *dsize) != LZMA_RESULT_OK) + if (cli_LzmaInit(&l, *dsize) != LZMA_RESULT_OK) { return 0; + } l.avail_in = ssize; l.avail_out = *dsize; l.next_in = (unsigned char *)src + 2; diff --git a/libclamav/uuencode.c b/libclamav/uuencode.c index 0a3b6934bd..b7c7e02a84 100644 --- a/libclamav/uuencode.c +++ b/libclamav/uuencode.c @@ -88,8 +88,9 @@ int uudecodeFile(message *m, const char *firstline, const char *dir, fmap_t *map char buffer[RFC2821LENGTH + 1]; char *filename = cli_strtok(firstline, 2, " "); - if (filename == NULL) + if (filename == NULL) { return -1; + } fb = fileblobCreate(); if (fb == NULL) { @@ -107,21 +108,26 @@ int uudecodeFile(message *m, const char *firstline, const char *dir, fmap_t *map size_t len; cli_chomp(buffer); - if (strcasecmp(buffer, "end") == 0) + if (strcasecmp(buffer, "end") == 0) { break; - if (buffer[0] == '\0') + } + if (buffer[0] == '\0') { break; + } uptr = decodeLine(m, UUENCODE, buffer, data, sizeof(data)); - if (uptr == NULL) + if (uptr == NULL) { break; + } len = (size_t)(uptr - data); - if ((len > 62) || (len == 0)) + if ((len > 62) || (len == 0)) { break; + } - if (fileblobAddData(fb, data, len) < 0) + if (fileblobAddData(fb, data, len) < 0) { break; + } } fileblobDestroy(fb); diff --git a/libclamav/vba_extract.c b/libclamav/vba_extract.c index 3bc915c3db..6e8af7c706 100644 --- a/libclamav/vba_extract.c +++ b/libclamav/vba_extract.c @@ -82,20 +82,22 @@ static vba_project_t *create_vba_project(int record_count, const char *dir, stru static uint16_t vba_endian_convert_16(uint16_t value, int big_endian) { - if (big_endian) + if (big_endian) { return (uint16_t)be16_to_host(value); - else + } else { return le16_to_host(value); + } } /* Seems to be a duplicate of riff_endian_convert_32() */ static uint32_t vba_endian_convert_32(uint32_t value, int big_endian) { - if (big_endian) + if (big_endian) { return be32_to_host(value); - else + } else { return le32_to_host(value); + } } static char * @@ -104,8 +106,9 @@ get_unicode_name(const char *name, int size, int big_endian) int i, increment; char *newname, *ret; - if ((name == NULL) || (*name == '\0') || (size <= 0)) + if ((name == NULL) || (*name == '\0') || (size <= 0)) { return NULL; + } newname = (char *)cli_max_malloc(size * 7 + 1); if (newname == NULL) { @@ -130,8 +133,9 @@ get_unicode_name(const char *name, int size, int big_endian) *ret++ = (char)(name[i] + '0'); } else { uint16_t x; - if ((i + 1) >= size) + if ((i + 1) >= size) { break; + } x = (uint16_t)((name[i] < 0 ? 0 : name[i] << 8) | name[i + 1]); *ret++ = '_'; @@ -165,8 +169,9 @@ static void vba56_test_middle(int fd) 0x00, 0x00, 0xe1, 0x2e, 0x45, 0x0d, 0x8f, 0xe0, 0x1a, 0x10, 0x85, 0x2e, 0x02, 0x60, 0x8c, 0x4d, 0x0b, 0xb4, 0x00, 0x00}; - if (cli_readn(fd, &test_middle, MIDDLE_SIZE) != MIDDLE_SIZE) + if (cli_readn(fd, &test_middle, MIDDLE_SIZE) != MIDDLE_SIZE) { return; + } if ((memcmp(test_middle, middle1_str, MIDDLE_SIZE) != 0) && (memcmp(test_middle, middle2_str, MIDDLE_SIZE) != 0)) { @@ -175,8 +180,9 @@ static void vba56_test_middle(int fd) cli_dbgmsg("vba_test_middle: call to lseek() failed\n"); return; } - } else + } else { cli_dbgmsg("middle found\n"); + } } /* return count of valid strings found, 0 on error */ @@ -1393,8 +1399,9 @@ cli_vba_readdir(const char *dir, struct uniq *U, uint32_t which) cli_dbgmsg("in cli_vba_readdir()\n"); - if (dir == NULL) + if (dir == NULL) { return NULL; + } /* * _VBA_PROJECT files are embedded within office documents (OLE2) @@ -1411,8 +1418,9 @@ cli_vba_readdir(const char *dir, struct uniq *U, uint32_t which) fullname[sizeof(fullname) - 1] = '\0'; fd = open(fullname, O_RDONLY | O_BINARY); - if (fd == -1) + if (fd == -1) { return NULL; + } if (cli_readn(fd, &v56h, sizeof(struct vba56_header)) != sizeof(struct vba56_header)) { close(fd); @@ -1453,12 +1461,12 @@ cli_vba_readdir(const char *dir, struct uniq *U, uint32_t which) } /* junk some more stuff */ - do + do { if (cli_readn(fd, &ffff, 2) != 2) { close(fd); return NULL; } - while (ffff != 0xFFFF); + } while (ffff != 0xFFFF); /* check for alignment error */ if (!seekandread(fd, -3, SEEK_CUR, &ffff, sizeof(uint16_t))) { @@ -1491,8 +1499,9 @@ cli_vba_readdir(const char *dir, struct uniq *U, uint32_t which) return NULL; } - if (ffff == 0xFFFF) + if (ffff == 0xFFFF) { ffff = 0; + } if (lseek(fd, ffff + 100, SEEK_CUR) == -1) { cli_dbgmsg("call to lseek() failed\n"); @@ -1529,8 +1538,9 @@ cli_vba_readdir(const char *dir, struct uniq *U, uint32_t which) char *ptr; vba_project->colls[i] = 0; - if (!read_uint16(fd, &length, big_endian)) + if (!read_uint16(fd, &length, big_endian)) { break; + } if (length == 0) { cli_dbgmsg("vba_readdir: zero name length\n"); @@ -1538,8 +1548,9 @@ cli_vba_readdir(const char *dir, struct uniq *U, uint32_t which) } if (length > buflen) { unsigned char *newbuf = (unsigned char *)cli_max_realloc(buf, length); - if (newbuf == NULL) + if (newbuf == NULL) { break; + } buflen = length; buf = newbuf; } @@ -1548,7 +1559,9 @@ cli_vba_readdir(const char *dir, struct uniq *U, uint32_t which) break; } ptr = get_unicode_name((const char *)buf, length, big_endian); - if (ptr == NULL) break; + if (ptr == NULL) { + break; + } if (CL_SUCCESS != uniq_get(U, ptr, strlen(ptr), &hash, &hashcnt)) { cli_dbgmsg("vba_readdir: uniq_get('%s') failed.\n", ptr); free(ptr); @@ -1563,32 +1576,39 @@ cli_vba_readdir(const char *dir, struct uniq *U, uint32_t which) cli_dbgmsg("vba_readdir: project name: %s (%s)\n", ptr, hash); free(ptr); vba_project->name[i] = hash; - if (!read_uint16(fd, &length, big_endian)) + if (!read_uint16(fd, &length, big_endian)) { break; + } lseek(fd, length, SEEK_CUR); - if (!read_uint16(fd, &ffff, big_endian)) + if (!read_uint16(fd, &ffff, big_endian)) { break; + } if (ffff == 0xFFFF) { lseek(fd, 2, SEEK_CUR); - if (!read_uint16(fd, &ffff, big_endian)) + if (!read_uint16(fd, &ffff, big_endian)) { break; + } lseek(fd, ffff + 8, SEEK_CUR); - } else + } else { lseek(fd, ffff + 10, SEEK_CUR); + } - if (!read_uint16(fd, &byte_count, big_endian)) + if (!read_uint16(fd, &byte_count, big_endian)) { break; + } lseek(fd, (8 * byte_count) + 5, SEEK_CUR); - if (!read_uint32(fd, &offset, big_endian)) + if (!read_uint32(fd, &offset, big_endian)) { break; + } cli_dbgmsg("vba_readdir: offset: %u\n", (unsigned int)offset); vba_project->offset[i] = offset; lseek(fd, 2, SEEK_CUR); } - if (buf) + if (buf) { free(buf); + } close(fd); @@ -1613,13 +1633,15 @@ cli_vba_inflate(int fd, off_t offset, size_t *size) blob *b; unsigned char buffer[VBA_COMPRESSION_WINDOW]; - if (fd < 0) + if (fd < 0) { return NULL; + } b = blobCreate(); - if (b == NULL) + if (b == NULL) { return NULL; + } memset(buffer, 0, sizeof(buffer)); lseek(fd, offset + 3, SEEK_SET); /* 1byte ?? , 2byte length ?? */ @@ -1635,8 +1657,9 @@ cli_vba_inflate(int fd, off_t offset, size_t *size) if (!read_uint16(fd, &token, FALSE)) { blobDestroy(b); - if (size) + if (size) { *size = 0; + } return NULL; } shift = 12 - (winpos > 0x10) - (winpos > 0x20) - (winpos > 0x40) - (winpos > 0x80) - (winpos > 0x100) - (winpos > 0x200) - (winpos > 0x400) - (winpos > 0x800); @@ -1652,25 +1675,28 @@ cli_vba_inflate(int fd, off_t offset, size_t *size) memcpy(&buffer[winpos], &buffer[srcpos], len); pos += len; - } else + } else { while (len-- > 0) { srcpos = (pos - distance - 1) % VBA_COMPRESSION_WINDOW; buffer[pos++ % VBA_COMPRESSION_WINDOW] = buffer[srcpos]; } + } } else { if ((pos != 0) && (winpos == 0) && clean) { if (cli_readn(fd, &token, 2) != 2) { blobDestroy(b); - if (size) + if (size) { *size = 0; + } return NULL; } (void)blobAddData(b, buffer, VBA_COMPRESSION_WINDOW); clean = FALSE; break; } - if (cli_readn(fd, &buffer[winpos], 1) == 1) + if (cli_readn(fd, &buffer[winpos], 1) == 1) { pos++; + } } clean = TRUE; } @@ -1678,13 +1704,15 @@ cli_vba_inflate(int fd, off_t offset, size_t *size) if (blobAddData(b, buffer, pos % VBA_COMPRESSION_WINDOW) < 0) { blobDestroy(b); - if (size) + if (size) { *size = 0; + } return NULL; } - if (size) + if (size) { *size = blobGetDataSize(b); + } return (unsigned char *)blobToMem(b); } @@ -1699,10 +1727,12 @@ ole_copy_file_data(int s, int d, uint32_t len) while (len > 0) { size_t todo = MIN(sizeof(data), len); - if (cli_readn(s, data, todo) != todo) + if (cli_readn(s, data, todo) != todo) { break; - if (cli_writen(d, data, todo) != todo) + } + if (cli_writen(d, data, todo) != todo) { break; + } if (todo > len) { break; @@ -1720,15 +1750,18 @@ int cli_scan_ole10(int fd, cli_ctx *ctx) STATBUF statbuf; char *fullname; - if (fd < 0) + if (fd < 0) { return CL_CLEAN; + } lseek(fd, 0, SEEK_SET); - if (!read_uint32(fd, &object_size, FALSE)) + if (!read_uint32(fd, &object_size, FALSE)) { return CL_CLEAN; + } - if (FSTAT(fd, &statbuf) == -1) + if (FSTAT(fd, &statbuf) == -1) { return CL_ESTAT; + } if ((statbuf.st_size - object_size) >= 4) { /* Probably the OLE type id */ @@ -1737,23 +1770,28 @@ int cli_scan_ole10(int fd, cli_ctx *ctx) } /* Attachment name */ - if (!skip_past_nul(fd)) + if (!skip_past_nul(fd)) { return CL_CLEAN; + } /* Attachment full path */ - if (!skip_past_nul(fd)) + if (!skip_past_nul(fd)) { return CL_CLEAN; + } /* ??? */ - if (lseek(fd, 8, SEEK_CUR) == -1) + if (lseek(fd, 8, SEEK_CUR) == -1) { return CL_CLEAN; + } /* Attachment full path */ - if (!skip_past_nul(fd)) + if (!skip_past_nul(fd)) { return CL_CLEAN; + } - if (!read_uint32(fd, &object_size, FALSE)) + if (!read_uint32(fd, &object_size, FALSE)) { return CL_CLEAN; + } } if (!(fullname = cli_gentemp(ctx ? ctx->sub_tmpdir : NULL))) { return CL_EMEM; @@ -1905,8 +1943,9 @@ ppt_stream_iter(int fd, const char *dir) atom_header_t atom_header; while (ppt_read_atom_header(fd, &atom_header)) { - if (atom_header.length == 0) + if (atom_header.length == 0) { return NULL; + } if (atom_header.type == 0x1011) { uint32_t length; @@ -1945,8 +1984,9 @@ cli_ppt_vba_read(int ifd, cli_ctx *ctx) /* Create a directory to store the extracted OLE2 objects */ dir = cli_gentemp_with_prefix(ctx ? ctx->sub_tmpdir : NULL, "ppt-ole2-tmp"); - if (dir == NULL) + if (dir == NULL) { return NULL; + } if (mkdir(dir, 0700)) { cli_errmsg("cli_ppt_vba_read: Can't create temporary directory %s\n", dir); free(dir); @@ -2028,8 +2068,9 @@ word_read_macro_entry(int fd, macro_info_t *macro_info) #ifdef HAVE_PRAGMA_PACK_HPPA #pragma pack #endif - if (count == 0) + if (count == 0) { return TRUE; + } msize = count * sizeof(struct macro); m = cli_max_malloc(msize); @@ -2065,8 +2106,9 @@ word_read_macro_info(int fd, macro_info_t *macro_info) return NULL; } cli_dbgmsg("macro count: %d\n", macro_info->count); - if (macro_info->count == 0) + if (macro_info->count == 0) { return NULL; + } macro_info->entries = (macro_entry_t *)cli_max_malloc(sizeof(macro_entry_t) * macro_info->count); if (macro_info->entries == NULL) { macro_info->count = 0; @@ -2110,11 +2152,12 @@ word_skip_oxo3(int fd) } count = twobytes[1]; } - if (count > 0) + if (count > 0) { if (lseek(fd, (count * 4) + 1, SEEK_CUR) == -1) { cli_dbgmsg("lseek oxo3 failed\n"); return FALSE; } + } cli_dbgmsg("oxo3 records2: %d\n", count); return TRUE; @@ -2131,9 +2174,11 @@ word_skip_menu_info(int fd) } cli_dbgmsg("menu_info count: %d\n", count); - if (count) - if (lseek(fd, count * 12, SEEK_CUR) == -1) + if (count) { + if (lseek(fd, count * 12, SEEK_CUR) == -1) { return FALSE; + } + } return TRUE; } @@ -2153,8 +2198,9 @@ word_skip_macro_extnames(int fd) return FALSE; } is_unicode = 1; - } else + } else { is_unicode = 0; + } cli_dbgmsg("ext names size: 0x%x\n", size); @@ -2168,10 +2214,11 @@ word_skip_macro_extnames(int fd) return FALSE; } - if (is_unicode) + if (is_unicode) { offset = (off_t)length * 2 + 1; - else + } else { offset = (off_t)length; + } /* ignore numref as well */ if (lseek(fd, offset + sizeof(uint16_t), SEEK_CUR) == -1) { @@ -2222,8 +2269,9 @@ cli_wm_readdir(int fd) vba_project_t *vba_project; mso_fib_t fib; - if (!word_read_fib(fd, &fib)) + if (!word_read_fib(fd, &fib)) { return NULL; + } if (fib.macro_len == 0) { cli_dbgmsg("wm_readdir: No macros detected\n"); @@ -2251,26 +2299,31 @@ cli_wm_readdir(int fd) } switch (info_id) { case 0x01: - if (macro_info.count) + if (macro_info.count) { free(macro_info.entries); + } word_read_macro_info(fd, ¯o_info); done = TRUE; break; case 0x03: - if (!word_skip_oxo3(fd)) + if (!word_skip_oxo3(fd)) { done = TRUE; + } break; case 0x05: - if (!word_skip_menu_info(fd)) + if (!word_skip_menu_info(fd)) { done = TRUE; + } break; case 0x10: - if (!word_skip_macro_extnames(fd)) + if (!word_skip_macro_extnames(fd)) { done = TRUE; + } break; case 0x11: - if (!word_skip_macro_intnames(fd)) + if (!word_skip_macro_intnames(fd)) { done = TRUE; + } break; case 0x40: /* end marker */ case 0x12: /* ??? */ @@ -2282,8 +2335,9 @@ cli_wm_readdir(int fd) } } - if (macro_info.count == 0) + if (macro_info.count == 0) { return NULL; + } vba_project = create_vba_project(macro_info.count, "", NULL); @@ -2307,10 +2361,12 @@ cli_wm_readdir(int fd) free(vba_project->colls); free(vba_project->dir); free(vba_project->offset); - if (vba_project->length) + if (vba_project->length) { free(vba_project->length); - if (vba_project->key) + } + if (vba_project->key) { free(vba_project->key); + } free(vba_project); vba_project = NULL; } @@ -2325,11 +2381,13 @@ cli_wm_decrypt_macro(int fd, off_t offset, uint32_t len, unsigned char key) { unsigned char *buff; - if (len == 0) + if (len == 0) { return NULL; + } - if (fd < 0) + if (fd < 0) { return NULL; + } buff = (unsigned char *)cli_max_malloc(len); if (buff == NULL) { @@ -2344,8 +2402,9 @@ cli_wm_decrypt_macro(int fd, off_t offset, uint32_t len, unsigned char key) if (key) { unsigned char *p; - for (p = buff; p < &buff[len]; p++) + for (p = buff; p < &buff[len]; p++) { *p ^= key; + } } return buff; } @@ -2363,12 +2422,14 @@ static int skip_past_nul(int fd) do { size_t nread = cli_readn(fd, smallbuf, sizeof(smallbuf)); - if ((nread == 0) || (nread == (size_t)-1)) + if ((nread == 0) || (nread == (size_t)-1)) { return FALSE; + } end = memchr(smallbuf, '\0', nread); if (end) { - if (lseek(fd, 1 + (end - smallbuf) - (off_t)nread, SEEK_CUR) < 0) + if (lseek(fd, 1 + (end - smallbuf) - (off_t)nread, SEEK_CUR) < 0) { return FALSE; + } return TRUE; } } while (1); @@ -2380,8 +2441,9 @@ static int skip_past_nul(int fd) static int read_uint16(int fd, uint16_t *u, int big_endian) { - if (cli_readn(fd, u, sizeof(uint16_t)) != sizeof(uint16_t)) + if (cli_readn(fd, u, sizeof(uint16_t)) != sizeof(uint16_t)) { return FALSE; + } *u = vba_endian_convert_16(*u, big_endian); @@ -2394,8 +2456,9 @@ read_uint16(int fd, uint16_t *u, int big_endian) static int read_uint32(int fd, uint32_t *u, int big_endian) { - if (cli_readn(fd, u, sizeof(uint32_t)) != sizeof(uint32_t)) + if (cli_readn(fd, u, sizeof(uint32_t)) != sizeof(uint32_t)) { return FALSE; + } *u = vba_endian_convert_32(*u, big_endian); @@ -2457,18 +2520,24 @@ create_vba_project(int record_count, const char *dir, struct uniq *U) void cli_free_vba_project(vba_project_t *vba_project) { if (vba_project) { - if (vba_project->dir) + if (vba_project->dir) { free(vba_project->dir); - if (vba_project->colls) + } + if (vba_project->colls) { free(vba_project->colls); - if (vba_project->name) + } + if (vba_project->name) { free(vba_project->name); - if (vba_project->offset) + } + if (vba_project->offset) { free(vba_project->offset); - if (vba_project->length) + } + if (vba_project->length) { free(vba_project->length); - if (vba_project->key) + } + if (vba_project->key) { free(vba_project->key); + } free(vba_project); } diff --git a/libclamav/wwunpack.c b/libclamav/wwunpack.c index d235dca71c..35c71e62cf 100644 --- a/libclamav/wwunpack.c +++ b/libclamav/wwunpack.c @@ -111,10 +111,11 @@ cl_error_t wwunpack(uint8_t *exe, uint32_t exesz, uint8_t *wwsect, struct cli_ex BIT; if (!bits) { /* BYTE copy */ - if (ccur - compd >= szd || !CLI_ISCONTAINED(exe, exesz, ucur, 1)) + if (ccur - compd >= szd || !CLI_ISCONTAINED(exe, exesz, ucur, 1)) { error = 1; - else + } else { *ucur++ = *ccur++; + } continue; } @@ -129,7 +130,9 @@ cl_error_t wwunpack(uint8_t *exe, uint32_t exesz, uint8_t *wwsect, struct cli_ex } backbytes = (1 << shifted) - subbed; /* 1h, 21h, 61h, 161h */ BITS(shifted); /* 5, 6, 8, 9 */ - if (error || bits == 0x1ff) break; + if (error || bits == 0x1ff) { + break; + } backbytes += bits; if (!CLI_ISCONTAINED(exe, exesz, ucur, 2) || !CLI_ISCONTAINED(exe, exesz, ucur - backbytes, 2)) { error = 1; @@ -214,20 +217,23 @@ cl_error_t wwunpack(uint8_t *exe, uint32_t exesz, uint8_t *wwsect, struct cli_ex backsize = saved + 2; } - if (!CLI_ISCONTAINED(exe, exesz, ucur, backsize) || !CLI_ISCONTAINED(exe, exesz, ucur - backbytes, backsize)) + if (!CLI_ISCONTAINED(exe, exesz, ucur, backsize) || !CLI_ISCONTAINED(exe, exesz, ucur - backbytes, backsize)) { error = 1; - else + } else { while (backsize--) { *ucur = *(ucur - backbytes); ucur++; } + } } free(compd); if (error) { cli_dbgmsg("WWPack: decompression error\n"); break; } - if (error || !*structs++) break; + if (error || !*structs++) { + break; + } } if (CL_SUCCESS == error) { diff --git a/libclamav/www.c b/libclamav/www.c index 024f736d40..ccb810f814 100644 --- a/libclamav/www.c +++ b/libclamav/www.c @@ -76,13 +76,15 @@ int connect_host(const char *host, const char *port, uint32_t timeout, int useAs hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; - if (getaddrinfo(host, port, &hints, &servinfo)) + if (getaddrinfo(host, port, &hints, &servinfo)) { return -1; + } for (p = servinfo; p != NULL; p = p->ai_next) { sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol); - if (sockfd < 0) + if (sockfd < 0) { continue; + } if (useAsync) { flags = fcntl(sockfd, F_GETFL, 0); @@ -135,8 +137,9 @@ int connect_host(const char *host, const char *port, uint32_t timeout, int useAs if (!(p)) { freeaddrinfo(servinfo); - if (sockfd >= 0) + if (sockfd >= 0) { closesocket(sockfd); + } return -1; } @@ -158,8 +161,9 @@ size_t encoded_size(const char *postdata) const char *p; size_t len = 0; - for (p = postdata; *p != '\0'; p++) + for (p = postdata; *p != '\0'; p++) { len += isalnum(*p) ? 1 : 3; + } return len; } @@ -170,12 +174,14 @@ char *encode_data(const char *postdata) size_t bufsz, i, j; bufsz = encoded_size(postdata); - if (bufsz == 0) + if (bufsz == 0) { return NULL; + } buf = cli_max_calloc(1, bufsz + 1); - if (!(buf)) + if (!(buf)) { return NULL; + } for (i = 0, j = 0; postdata[i] != '\0'; i++) { if (isalnum(postdata[i])) { @@ -205,12 +211,15 @@ void submit_post(const char *host, const char *port, const char *method, const c "POST", NULL}; - for (i = 0; acceptable_methods[i] != NULL; i++) - if (!strcmp(method, acceptable_methods[i])) + for (i = 0; acceptable_methods[i] != NULL; i++) { + if (!strcmp(method, acceptable_methods[i])) { break; + } + } - if (acceptable_methods[i] == NULL) + if (acceptable_methods[i] == NULL) { return; + } bufsz = strlen(method); bufsz += sizeof(" HTTP/1.1") + 2; /* Yes. Three blank spaces. +1 for the \n */ @@ -222,8 +231,9 @@ void submit_post(const char *host, const char *port, const char *method, const c if (!strcmp(method, "POST") || !strcmp(method, "PUT")) { encoded = encode_data(postdata); - if (!(encoded)) + if (!(encoded)) { return; + } snprintf(chunkedlen, sizeof(chunkedlen), "%zu", strlen(encoded)); bufsz += sizeof("Content-Type: application/x-www-form-urlencoded\r\n"); bufsz += sizeof("Content-Length: \r\n"); @@ -233,8 +243,9 @@ void submit_post(const char *host, const char *port, const char *method, const c buf = cli_max_calloc(1, bufsz); if (!(buf)) { - if ((encoded)) + if ((encoded)) { free(encoded); + } return; } @@ -281,13 +292,15 @@ void submit_post(const char *host, const char *port, const char *method, const c */ tv.tv_sec = timeout; tv.tv_usec = 0; - if ((n = select(sockfd + 1, &readfds, NULL, NULL, &tv)) <= 0) + if ((n = select(sockfd + 1, &readfds, NULL, NULL, &tv)) <= 0) { break; + } if (FD_ISSET(sockfd, &readfds)) { memset(buf, 0x00, bufsz); - if ((recvsz = recv(sockfd, buf, bufsz - 1, 0) <= 0)) + if ((recvsz = recv(sockfd, buf, bufsz - 1, 0) <= 0)) { break; + } buf[bufsz - 1] = '\0'; diff --git a/libclamav/xar.c b/libclamav/xar.c index 1c5be0c09a..baa123573c 100644 --- a/libclamav/xar.c +++ b/libclamav/xar.c @@ -45,8 +45,9 @@ static int xar_cleanup_temp_file(cli_ctx *ctx, int fd, char *tmpname) { int rc = CL_SUCCESS; - if (fd > -1) + if (fd > -1) { close(fd); + } if (tmpname != NULL) { if (!ctx->engine->keeptmp) { if (cli_unlink(tmpname)) { @@ -122,8 +123,9 @@ static void xar_get_checksum_values(xmlTextReaderPtr reader, unsigned char **cks *hash = XAR_CKSUM_OTHER; } } - if (style != NULL) + if (style != NULL) { xmlFree(style); + } if (xmlTextReaderRead(reader) == 1 && xmlTextReaderNodeType(reader) == XML_READER_TYPE_TEXT) { xmlval = xmlTextReaderConstValue(reader); @@ -141,8 +143,9 @@ static void xar_get_checksum_values(xmlTextReaderPtr reader, unsigned char **cks *cksum = NULL; cli_dbgmsg("cli_scanxar: xmlTextReaderConstValue() returns NULL for checksum value.\n"); } - } else + } else { cli_dbgmsg("cli_scanxar: No text for XML checksum element.\n"); + } } /* @@ -180,18 +183,21 @@ static int xar_get_toc_data_values(xmlTextReaderPtr reader, size_t *length, size /* cli_dbgmsg("cli_scanxar: xmlTextReaderRead read %s\n", name); */ if (xmlStrEqual(name, (const xmlChar *)"offset") && xmlTextReaderNodeType(reader) == XML_READER_TYPE_ELEMENT) { - if (CL_SUCCESS == xar_get_numeric_from_xml_element(reader, offset)) + if (CL_SUCCESS == xar_get_numeric_from_xml_element(reader, offset)) { gotoffset = 1; + } } else if (xmlStrEqual(name, (const xmlChar *)"length") && xmlTextReaderNodeType(reader) == XML_READER_TYPE_ELEMENT) { - if (CL_SUCCESS == xar_get_numeric_from_xml_element(reader, length)) + if (CL_SUCCESS == xar_get_numeric_from_xml_element(reader, length)) { gotlength = 1; + } } else if (xmlStrEqual(name, (const xmlChar *)"size") && xmlTextReaderNodeType(reader) == XML_READER_TYPE_ELEMENT) { - if (CL_SUCCESS == xar_get_numeric_from_xml_element(reader, size)) + if (CL_SUCCESS == xar_get_numeric_from_xml_element(reader, size)) { gotsize = 1; + } } else if (xmlStrEqual(name, (const xmlChar *)"archived-checksum") && xmlTextReaderNodeType(reader) == XML_READER_TYPE_ELEMENT) { @@ -230,8 +236,9 @@ static int xar_get_toc_data_values(xmlTextReaderPtr reader, size_t *length, size cli_dbgmsg("cli_scaxar: unknown style value=%s for encoding element\n", style); *encoding = CL_TYPE_ANY; } - if (style != NULL) + if (style != NULL) { xmlFree(style); + } } else if (indata && xmlStrEqual(name, (const xmlChar *)"data") && xmlTextReaderNodeType(reader) == XML_READER_TYPE_END_ELEMENT) { @@ -262,10 +269,11 @@ static int xar_get_toc_data_values(xmlTextReaderPtr reader, size_t *length, size if (gotoffset && gotlength && gotsize) { rc = CL_SUCCESS; - } else if (0 == gotoffset + gotlength + gotsize) + } else if (0 == gotoffset + gotlength + gotsize) { rc = CL_BREAK; - else + } else { rc = CL_EFORMAT; + } return rc; } @@ -295,8 +303,9 @@ static int xar_scan_subdocuments(xmlTextReaderPtr reader, cli_ctx *ctx) break; } if (xmlStrEqual(name, (const xmlChar *)"toc") && - xmlTextReaderNodeType(reader) == XML_READER_TYPE_ELEMENT) + xmlTextReaderNodeType(reader) == XML_READER_TYPE_ELEMENT) { return CL_SUCCESS; + } if (xmlStrEqual(name, (const xmlChar *)"subdoc") && xmlTextReaderNodeType(reader) == XML_READER_TYPE_ELEMENT) { subdoc = xmlTextReaderReadInnerXml(reader); @@ -325,8 +334,9 @@ static int xar_scan_subdocuments(xmlTextReaderPtr reader, cli_ctx *ctx) } xmlFree(subdoc); - if (rc != CL_SUCCESS) + if (rc != CL_SUCCESS) { return rc; + } xmlTextReaderNext(reader); } } @@ -335,8 +345,9 @@ static int xar_scan_subdocuments(xmlTextReaderPtr reader, cli_ctx *ctx) static void *xar_hash_init(int hash, void **sc, void **mc) { - if (!sc && !mc) + if (!sc && !mc) { return NULL; + } switch (hash) { case XAR_CKSUM_SHA1: *sc = cl_hash_init("sha1"); @@ -361,8 +372,9 @@ static void *xar_hash_init(int hash, void **sc, void **mc) static void xar_hash_update(void *hash_ctx, void *data, unsigned long size, int hash) { - if (!hash_ctx || !data || !size) + if (!hash_ctx || !data || !size) { return; + } switch (hash) { case XAR_CKSUM_NONE: @@ -375,8 +387,9 @@ static void xar_hash_update(void *hash_ctx, void *data, unsigned long size, int static void xar_hash_final(void *hash_ctx, void *result, int hash) { - if (!hash_ctx || !result) + if (!hash_ctx || !result) { return; + } switch (hash) { case XAR_CKSUM_OTHER: @@ -391,8 +404,9 @@ static int xar_hash_check(int hash, const void *result, const void *expected) { int len; - if (!result || !expected) + if (!result || !expected) { return 1; + } switch (hash) { case XAR_CKSUM_SHA1: len = CLI_HASHLEN_SHA1; @@ -531,8 +545,9 @@ int cli_scanxar(cli_ctx *ctx) } rc = xar_cleanup_temp_file(ctx, fd, tmpname); tmpname = NULL; - if (rc != CL_SUCCESS) + if (rc != CL_SUCCESS) { goto exit_toc; + } } reader = xmlReaderForMemory(toc, hdr.toc_length_decompressed, "noname.xml", NULL, CLAMAV_MIN_XMLREADER_FLAGS); @@ -562,8 +577,9 @@ int cli_scanxar(cli_ctx *ctx) if (fd > -1 && tmpname) { rc = xar_cleanup_temp_file(ctx, fd, tmpname); tmpname = NULL; - if (rc != CL_SUCCESS) + if (rc != CL_SUCCESS) { goto exit_reader; + } } at = offset + hdr.toc_length_compressed + hdr.size; @@ -619,8 +635,9 @@ int cli_scanxar(cli_ctx *ctx) bytes = sizeof(buff) - strm.avail_out; - if (e_hash_ctx != NULL) + if (e_hash_ctx != NULL) { xar_hash_update(e_hash_ctx, buff, bytes, e_hash); + } if (cli_writen(fd, buff, bytes) == (size_t)-1) { cli_dbgmsg("cli_scanxar: cli_writen error file %s.\n", tmpname); @@ -637,12 +654,14 @@ int cli_scanxar(cli_ctx *ctx) } } while (strm.avail_out == 0); - if (rc != CL_SUCCESS) + if (rc != CL_SUCCESS) { break; + } avail_in -= strm.avail_in; - if (a_hash_ctx != NULL) + if (a_hash_ctx != NULL) { xar_hash_update(a_hash_ctx, next_in, avail_in, a_hash); + } } inflateEnd(&strm); @@ -658,8 +677,9 @@ int cli_scanxar(cli_ctx *ctx) unsigned char *buff = __lzma_wrap_alloc(NULL, CLI_LZMA_OBUF_SIZE); int lret; - if (length > in_remaining) + if (length > in_remaining) { length = in_remaining; + } memset(&lz, 0, sizeof(lz)); if (buff == NULL) { @@ -682,8 +702,9 @@ int cli_scanxar(cli_ctx *ctx) lz.next_in = blockp; lz.avail_in = CLI_LZMA_HDR_SIZE; - if (a_hash_ctx != NULL) + if (a_hash_ctx != NULL) { xar_hash_update(a_hash_ctx, blockp, CLI_LZMA_HDR_SIZE, a_hash); + } lret = cli_LzmaInit(&lz, 0); if (lret != LZMA_RESULT_OK) { @@ -730,15 +751,18 @@ int cli_scanxar(cli_ctx *ctx) at += in_consumed; avail_out = CLI_LZMA_OBUF_SIZE - lz.avail_out; - if (avail_out == 0) + if (avail_out == 0) { cli_dbgmsg("cli_scanxar: cli_LzmaDecode() produces no output for " "avail_in %llu, avail_out %llu.\n", (long long unsigned)avail_in, (long long unsigned)avail_out); + } - if (a_hash_ctx != NULL) + if (a_hash_ctx != NULL) { xar_hash_update(a_hash_ctx, next_in, in_consumed, a_hash); - if (e_hash_ctx != NULL) + } + if (e_hash_ctx != NULL) { xar_hash_update(e_hash_ctx, buff, avail_out, e_hash); + } /* Write a decompressed block. */ /* cli_dbgmsg("Writing %li bytes to LZMA decompress temp file, " */ @@ -760,8 +784,9 @@ int cli_scanxar(cli_ctx *ctx) break; } - if (lret == LZMA_STREAM_END) + if (lret == LZMA_STREAM_END) { break; + } } cli_LzmaShutdown(&lz); @@ -776,8 +801,9 @@ int cli_scanxar(cli_ctx *ctx) { size_t writelen = MIN(map->len - at, length); - if (ctx->engine->maxfilesize) + if (ctx->engine->maxfilesize) { writelen = MIN((size_t)(ctx->engine->maxfilesize), writelen); + } if (!(blockp = (void *)fmap_need_off_once(map, at, writelen))) { char errbuff[128]; @@ -788,8 +814,9 @@ int cli_scanxar(cli_ctx *ctx) goto exit_tmpfile; } - if (a_hash_ctx != NULL) + if (a_hash_ctx != NULL) { xar_hash_update(a_hash_ctx, blockp, writelen, a_hash); + } if (cli_writen(fd, blockp, writelen) == (size_t)-1) { cli_dbgmsg("cli_scanxar: cli_writen error %zu bytes @ %zu.\n", writelen, at); @@ -858,23 +885,28 @@ int cli_scanxar(cli_ctx *ctx) exit_tmpfile: xar_cleanup_temp_file(ctx, fd, tmpname); - if (a_hash_ctx != NULL) + if (a_hash_ctx != NULL) { xar_hash_final(a_hash_ctx, a_hash_result, a_hash); - if (e_hash_ctx != NULL) + } + if (e_hash_ctx != NULL) { xar_hash_final(e_hash_ctx, e_hash_result, e_hash); + } exit_reader: - if (a_cksum != NULL) + if (a_cksum != NULL) { xmlFree(a_cksum); - if (e_cksum != NULL) + } + if (e_cksum != NULL) { xmlFree(e_cksum); + } xmlTextReaderClose(reader); xmlFreeTextReader(reader); exit_toc: free(toc); - if (rc == CL_BREAK) + if (rc == CL_BREAK) { rc = CL_SUCCESS; + } if (cksum_fails + extract_errors != 0) { cli_dbgmsg("cli_scanxar: %u checksum errors and %u extraction errors.\n", diff --git a/libclamav/xdp.c b/libclamav/xdp.c index 11bbcac14d..f021eae6e0 100644 --- a/libclamav/xdp.c +++ b/libclamav/xdp.c @@ -64,14 +64,16 @@ static char *dump_xdp(cli_ctx *ctx, const char *start, size_t sz) size_t nwritten = 0; ssize_t writeret; - if (cli_gentempfd(ctx->sub_tmpdir, &filename, &fd) != CL_SUCCESS) + if (cli_gentempfd(ctx->sub_tmpdir, &filename, &fd) != CL_SUCCESS) { return NULL; + } while (nwritten < sz) { writeret = write(fd, start + nwritten, sz - nwritten); if (writeret < 0) { - if (errno == EAGAIN) + if (errno == EAGAIN) { continue; + } close(fd); cli_unlink(filename); @@ -102,13 +104,15 @@ cl_error_t cli_scanxdp(cli_ctx *ctx) size_t i; buf = (const char *)fmap_need_off_once(ctx->fmap, 0, ctx->fmap->len); - if (!(buf)) + if (!(buf)) { return CL_EREAD; + } if (ctx->engine->keeptmp) { dumpname = dump_xdp(ctx, buf, ctx->fmap->len); - if (dumpname) + if (dumpname) { free(dumpname); + } } /* @@ -119,13 +123,15 @@ cl_error_t cli_scanxdp(cli_ctx *ctx) * continue on. */ reader = xmlReaderForMemory(buf, (int)(ctx->fmap->len), "noname.xml", NULL, CLAMAV_MIN_XMLREADER_FLAGS); - if (!(reader)) + if (!(reader)) { return CL_SUCCESS; + } while (xmlTextReaderRead(reader) == 1) { name = xmlTextReaderConstLocalName(reader); - if (!(name)) + if (!(name)) { continue; + } if (!strcmp((const char *)name, "chunk") && xmlTextReaderNodeType(reader) == XML_READER_TYPE_ELEMENT) { value = xmlTextReaderReadInnerXml(reader); @@ -136,8 +142,9 @@ cl_error_t cli_scanxdp(cli_ctx *ctx) if (decodedlen > 5) { for (i = 0; i < MIN(MAGIC_BUFFER_SIZE, decodedlen - 5); i++) { - if (decoded[i] != '%') + if (decoded[i] != '%') { continue; + } if (decoded[i + 1] == 'P' || decoded[i + 1] == 'p') { if (decoded[i + 2] == 'D' || decoded[i + 2] == 'd') { diff --git a/libclamav/xz_iface.c b/libclamav/xz_iface.c index ac90c4a941..fa0b29c2e0 100644 --- a/libclamav/xz_iface.c +++ b/libclamav/xz_iface.c @@ -50,17 +50,20 @@ static ISzAlloc g_Alloc = {__xz_wrap_alloc, __xz_wrap_free}; int cli_XzInit(struct CLI_XZ *XZ) { - if (SZ_OK != XzUnpacker_Create(&XZ->state, &g_Alloc)) + if (SZ_OK != XzUnpacker_Create(&XZ->state, &g_Alloc)) { return XZ_RESULT_DATA_ERROR; - if (g_Crc64Table[1] == 0) + } + if (g_Crc64Table[1] == 0) { Crc64GenerateTable(); + } return XZ_RESULT_OK; } void cli_XzShutdown(struct CLI_XZ *XZ) { - if (!XZ) + if (!XZ) { return; + } XzUnpacker_Free(&XZ->state); } @@ -79,10 +82,12 @@ int cli_XzDecode(struct CLI_XZ *XZ) XZ->next_in += inbytes; XZ->avail_out -= outbytes; XZ->next_out += outbytes; - if (XZ->status == CODER_STATUS_FINISHED_WITH_MARK || XzUnpacker_IsStreamWasFinished(&XZ->state)) + if (XZ->status == CODER_STATUS_FINISHED_WITH_MARK || XzUnpacker_IsStreamWasFinished(&XZ->state)) { return XZ_STREAM_END; - if (XZ->status == CODER_STATUS_NOT_FINISHED && XZ->avail_out == 0) + } + if (XZ->status == CODER_STATUS_NOT_FINISHED && XZ->avail_out == 0) { return XZ_RESULT_OK; + } if (((inbytes == 0) && (outbytes == 0)) || res != SZ_OK) { if (res == SZ_ERROR_MEM) { return XZ_DIC_HEURISTIC; diff --git a/libclamav/yc.c b/libclamav/yc.c index 2d4a7187c0..9305e9fcac 100644 --- a/libclamav/yc.c +++ b/libclamav/yc.c @@ -102,8 +102,9 @@ static int yc_poly_emulator(cli_ctx *ctx, char *base, unsigned int filesize, cha if (yc_bounds_check(ctx, base, filesize, decryptor_offset, j)) { return 2; } - if (!max_jmp_loop) + if (!max_jmp_loop) { return 2; + } max_jmp_loop--; j = j + decryptor_offset[j]; break; @@ -203,8 +204,9 @@ static int yc_poly_emulator(cli_ctx *ctx, char *base, unsigned int filesize, cha } } cl--; - if (yc_bounds_check(ctx, base, filesize, code, i)) + if (yc_bounds_check(ctx, base, filesize, code, i)) { return 2; + } code[i] = al; } return 0; @@ -264,7 +266,9 @@ int yc_decrypt(cli_ctx *ctx, char *fbuf, unsigned int filesize, struct cli_exe_s name == 0x6164692E || /* .ida */ name == 0x736C742E || /* .tls */ (name & 0xffff) == 0x4379 /* yC */ - ) continue; + ) { + continue; + } cli_dbgmsg("yC: decrypting sect%d\n", i); max_emu = filesize - sections[i].raw; if (max_emu > filesize) { diff --git a/libclamunrar_iface/CMakeLists.txt b/libclamunrar_iface/CMakeLists.txt index 7ced5a6955..8a6ce98f60 100644 --- a/libclamunrar_iface/CMakeLists.txt +++ b/libclamunrar_iface/CMakeLists.txt @@ -55,6 +55,12 @@ if(ENABLE_UNRAR) set_target_properties( clamunrar_iface PROPERTIES COMPILE_FLAGS "${WARNCXXFLAGS} ${CXX1XCXXFLAGS}" ) + if(CLANG_TIDY) + set_target_properties( clamunrar_iface PROPERTIES + C_CLANG_TIDY "${CLANG_TIDY_PROPERTY}" + C_CLANG_TIDY_EXPORT_FIXES_DIR "${CMAKE_BINARY_DIR}/clang-tidy-fixes" ) + endif() + if (APPLE AND CLAMAV_SIGN_FILE) set_target_properties( clamunrar_iface PROPERTIES XCODE_ATTRIBUTE_CODE_SIGN_IDENTITY ${CODE_SIGN_IDENTITY} diff --git a/libfreshclam/CMakeLists.txt b/libfreshclam/CMakeLists.txt index 3245307a71..ade70730c6 100644 --- a/libfreshclam/CMakeLists.txt +++ b/libfreshclam/CMakeLists.txt @@ -69,6 +69,13 @@ if(ENABLE_SHARED_LIB) COMPILE_FLAGS "${WARNCFLAGS}" VERSION ${LIBFRESHCLAM_VERSION} SOVERSION ${LIBFRESHCLAM_SOVERSION} LINK_DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/libfreshclam.map) + + if(CLANG_TIDY) + set_target_properties(freshclam PROPERTIES + C_CLANG_TIDY "${CLANG_TIDY_PROPERTY}" + C_CLANG_TIDY_EXPORT_FIXES_DIR "${CMAKE_BINARY_DIR}/clang-tidy-fixes") + endif() + if(WIN32) install(TARGETS freshclam DESTINATION . COMPONENT libraries) install(FILES $ DESTINATION . OPTIONAL COMPONENT libraries) diff --git a/libfreshclam/dns.c b/libfreshclam/dns.c index d21bc6bac0..56dd6b6b0e 100644 --- a/libfreshclam/dns.c +++ b/libfreshclam/dns.c @@ -50,8 +50,9 @@ dnsquery(const char *domain, int qtype, unsigned int *ttl) int len, type; unsigned int cttl, size, txtlen = 0; - if (ttl) + if (ttl) { *ttl = 0; + } if (res_init() < 0) { logg(LOGG_WARNING, "res_init failed\n"); return NULL; @@ -81,8 +82,9 @@ dnsquery(const char *domain, int qtype, unsigned int *ttl) #endif } if (qtype != T_TXT && qtype != T_ANY) { - if (ttl) + if (ttl) { *ttl = 2; + } return NULL; } @@ -139,13 +141,15 @@ dnsquery(const char *domain, int qtype, unsigned int *ttl) return NULL; } - if (!(txt = (char *)malloc(txtlen + 1))) + if (!(txt = (char *)malloc(txtlen + 1))) { return NULL; + } memcpy(txt, pt + 1, txtlen); txt[txtlen] = 0; - if (ttl) + if (ttl) { *ttl = cttl; + } return txt; } diff --git a/libfreshclam/libfreshclam.c b/libfreshclam/libfreshclam.c index 0babb11b2a..ff980f132b 100644 --- a/libfreshclam/libfreshclam.c +++ b/libfreshclam/libfreshclam.c @@ -145,7 +145,9 @@ fc_error_t fc_initialize(fc_config *fcConfig) curl_global_init(CURL_GLOBAL_ALL); /* Initialize mprintf options */ - if (fcConfig->msgFlags & FC_CONFIG_MSG_DEBUG) cl_debug(); + if (fcConfig->msgFlags & FC_CONFIG_MSG_DEBUG) { + cl_debug(); + } mprintf_verbose = (fcConfig->msgFlags & FC_CONFIG_MSG_VERBOSE) ? 1 : 0; mprintf_quiet = (fcConfig->msgFlags & FC_CONFIG_MSG_QUIET) ? 1 : 0; mprintf_nowarn = (fcConfig->msgFlags & FC_CONFIG_MSG_NOWARN) ? 1 : 0; @@ -208,10 +210,11 @@ fc_error_t fc_initialize(fc_config *fcConfig) */ const struct servent *webcache = getservbyname("webcache", "TCP"); - if (webcache) + if (webcache) { g_proxyPort = ntohs(webcache->s_port); - else + } else { g_proxyPort = 8080; + } endservent(); } @@ -446,10 +449,12 @@ int version_string_compare(char *v1, size_t v1_len, char *v2, size_t v2_len) j++; } - if (vnum1 > vnum2) + if (vnum1 > vnum2) { return 1; - if (vnum2 > vnum1) + } + if (vnum2 > vnum1) { return -1; + } vnum1 = vnum2 = 0; i++; @@ -506,8 +511,9 @@ fc_error_t fc_test_database(const char *dbFilename, int bBytecodeEnabled) done: if (NULL != engine) { - if (engine->domain_list_matcher && engine->domain_list_matcher->sha256_pfx_set.keys) + if (engine->domain_list_matcher && engine->domain_list_matcher->sha256_pfx_set.keys) { cli_hashset_destroy(&engine->domain_list_matcher->sha256_pfx_set); + } cl_engine_free(engine); } @@ -581,8 +587,9 @@ fc_error_t fc_dns_query_update_info( goto done; } - if (*reply_token == '0') + if (*reply_token == '0') { vwarning = 0; + } free(reply_token); reply_token = NULL; diff --git a/libfreshclam/libfreshclam_internal.c b/libfreshclam/libfreshclam_internal.c index e26b00d74e..a7f9c90f10 100644 --- a/libfreshclam/libfreshclam_internal.c +++ b/libfreshclam/libfreshclam_internal.c @@ -187,10 +187,11 @@ fc_error_t load_freshclam_dat(void) if (-1 == (handle = open("freshclam.dat", O_RDONLY | O_BINARY))) { char currdir[PATH_MAX]; - if (getcwd(currdir, sizeof(currdir))) + if (getcwd(currdir, sizeof(currdir))) { logg(LOGG_DEBUG, "Can't open freshclam.dat in %s\n", currdir); - else + } else { logg(LOGG_DEBUG, "Can't open freshclam.dat in the current directory\n"); + } logg(LOGG_DEBUG, "It probably doesn't exist yet. That's ok.\n"); status = FC_EFILE; @@ -322,10 +323,11 @@ fc_error_t save_freshclam_dat(void) if (-1 == (handle = open("freshclam.dat", O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0644))) { char currdir[PATH_MAX]; - if (getcwd(currdir, sizeof(currdir))) + if (getcwd(currdir, sizeof(currdir))) { logg(LOGG_ERROR, "Can't create freshclam.dat in %s\n", currdir); - else + } else { logg(LOGG_ERROR, "Can't create freshclam.dat in the current directory\n"); + } logg(LOGG_INFO, "Hint: The database directory must be writable for UID %d or GID %d\n", getuid(), getgid()); status = FC_EDBDIRACCESS; @@ -1028,10 +1030,11 @@ static fc_error_t remote_cvdhead( */ size_t len = strlen(errbuf); logg(logerr ? LOGG_ERROR : LOGG_WARNING, "remote_cvdhead: Download failed (%d) ", curl_ret); - if (len) + if (len) { logg(logerr ? LOGG_ERROR : LOGG_WARNING, " Message: %s%s", errbuf, ((errbuf[len - 1] != '\n') ? "\n" : "")); - else + } else { logg(logerr ? LOGG_ERROR : LOGG_WARNING, " Message: %s\n", curl_easy_strerror(curl_ret)); + } status = FC_ECONNECTION; goto done; } @@ -1083,10 +1086,11 @@ static fc_error_t remote_cvdhead( break; } case 404: { - if (g_proxyServer) + if (g_proxyServer) { logg(LOGG_WARNING, "remote_cvdhead: file not found: %s (Proxy: %s:%u)\n", url, g_proxyServer, g_proxyPort); - else + } else { logg(LOGG_WARNING, "remote_cvdhead: file not found: %s\n", url); + } status = FC_EFAILEDGET; goto done; } @@ -1096,12 +1100,13 @@ static fc_error_t remote_cvdhead( goto done; } default: { - if (g_proxyServer) + if (g_proxyServer) { logg(logerr ? LOGG_ERROR : LOGG_WARNING, "remote_cvdhead: Unexpected response (%li) from %s (Proxy: %s:%u)\n", http_code, server, g_proxyServer, g_proxyPort); - else + } else { logg(logerr ? LOGG_ERROR : LOGG_WARNING, "remote_cvdhead: Unexpected response (%li) from %s\n", http_code, server); + } status = FC_EFAILEDGET; goto done; } @@ -1308,10 +1313,11 @@ static fc_error_t downloadFile( if (-1 == (receivedFile.handle = open(destfile, O_WRONLY | O_CREAT | O_EXCL | O_BINARY, 0644))) { char currdir[PATH_MAX]; - if (getcwd(currdir, sizeof(currdir))) + if (getcwd(currdir, sizeof(currdir))) { logg(LOGG_ERROR, "downloadFile: Can't create new file %s in %s\n", destfile, currdir); - else + } else { logg(LOGG_ERROR, "downloadFile: Can't create new file %s in the current directory\n", destfile); + } logg(LOGG_INFO, "Hint: The database directory must be writable for UID %d or GID %d\n", getuid(), getgid()); status = FC_EDBDIRACCESS; @@ -1350,10 +1356,11 @@ static fc_error_t downloadFile( */ size_t len = strlen(errbuf); logg(logerr ? LOGG_ERROR : LOGG_WARNING, "Download failed (%d) ", curl_ret); - if (len) + if (len) { logg(logerr ? LOGG_ERROR : LOGG_WARNING, " Message: %s%s", errbuf, ((errbuf[len - 1] != '\n') ? "\n" : "")); - else + } else { logg(logerr ? LOGG_ERROR : LOGG_WARNING, " Message: %s\n", curl_easy_strerror(curl_ret)); + } status = FC_ECONNECTION; goto done; } @@ -1409,10 +1416,11 @@ static fc_error_t downloadFile( break; } case 404: { - if (g_proxyServer) + if (g_proxyServer) { logg(quiet ? LOGG_DEBUG : LOGG_WARNING, "downloadFile: file not found: %s (Proxy: %s:%u)\n", url, g_proxyServer, g_proxyPort); - else + } else { logg(quiet ? LOGG_DEBUG : LOGG_WARNING, "downloadFile: file not found: %s\n", url); + } status = FC_EFAILEDGET; break; } @@ -1422,12 +1430,13 @@ static fc_error_t downloadFile( break; } default: { - if (g_proxyServer) + if (g_proxyServer) { logg(logerr ? LOGG_ERROR : LOGG_WARNING, "downloadFile: Unexpected response (%li) from %s (Proxy: %s:%u)\n", http_code, url, g_proxyServer, g_proxyPort); - else + } else { logg(logerr ? LOGG_ERROR : LOGG_WARNING, "downloadFile: Unexpected response (%li) from %s\n", http_code, url); + } status = FC_EFAILEDGET; } } @@ -1969,8 +1978,9 @@ static fc_error_t buildcld( while (NULL != (dent = readdir(dir))) { if (dent->d_ino) { - if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, "..") || !strcmp(dent->d_name, "COPYING") || !strcmp(dent->d_name, cfg) || !strcmp(dent->d_name, info)) + if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, "..") || !strcmp(dent->d_name, "COPYING") || !strcmp(dent->d_name, cfg) || !strcmp(dent->d_name, info)) { continue; + } if (tar_addfile(fd, gzs, dent->d_name) == -1) { logg(LOGG_ERROR, "buildcld: Can't add %s to new %s.cld - please check if there is enough disk space available\n", dent->d_name, database); @@ -2466,8 +2476,9 @@ fc_error_t updatedb( for (i = localVersion + 1; i <= remoteVersion; i++) { for (j = 1; j <= g_maxAttempts; j++) { int llogerr = logerr; - if (logerr) + if (logerr) { llogerr = (j == g_maxAttempts); + } #ifdef HAVE_UNISTD_H if (!mprintf_quiet && (mprintf_progress || isatty(fileno(stdout)))) diff --git a/sigtool/CMakeLists.txt b/sigtool/CMakeLists.txt index dd55aaee82..40200755e4 100644 --- a/sigtool/CMakeLists.txt +++ b/sigtool/CMakeLists.txt @@ -27,6 +27,12 @@ target_include_directories( sigtool set_target_properties( sigtool PROPERTIES COMPILE_FLAGS "${WARNCFLAGS}" ) +if(CLANG_TIDY) + set_target_properties( sigtool PROPERTIES + C_CLANG_TIDY "${CLANG_TIDY_PROPERTY}" + C_CLANG_TIDY_EXPORT_FIXES_DIR "${CMAKE_BINARY_DIR}/clang-tidy-fixes" ) +endif() + if (APPLE AND CLAMAV_SIGN_FILE) set_target_properties( sigtool PROPERTIES XCODE_ATTRIBUTE_CODE_SIGN_IDENTITY ${CODE_SIGN_IDENTITY} diff --git a/sigtool/sigtool.c b/sigtool/sigtool.c index 7b24300b95..cd49adc3aa 100644 --- a/sigtool/sigtool.c +++ b/sigtool/sigtool.c @@ -122,16 +122,18 @@ static char *getdbname(const char *str, char *dst, int dstlen) { int len = strlen(str); - if (cli_strbcasestr(str, ".cvd") || cli_strbcasestr(str, ".cld") || cli_strbcasestr(str, ".cud")) + if (cli_strbcasestr(str, ".cvd") || cli_strbcasestr(str, ".cld") || cli_strbcasestr(str, ".cud")) { len -= 4; + } if (dst) { strncpy(dst, str, MIN(dstlen - 1, len)); dst[MIN(dstlen - 1, len)] = 0; } else { dst = (char *)malloc(len + 1); - if (!dst) + if (!dst) { return NULL; + } strncpy(dst, str, len - 4); dst[MIN(dstlen - 1, len - 4)] = 0; } @@ -153,8 +155,9 @@ static int hexdump(void) free(pt); } - if (bytes == -1) + if (bytes == -1) { return -1; + } return 0; } @@ -584,8 +587,9 @@ static int htmlnorm(const struct optstruct *opts) if (NULL != (ctx = convenience_ctx(fd))) { html_normalise_map(ctx, ctx->fmap, ".", NULL, NULL); funmap(ctx->fmap); - } else + } else { mprintf(LOGG_ERROR, "fmap failed\n"); + } close(fd); @@ -646,7 +650,9 @@ static int asciinorm(const struct optstruct *opts) map_off = 0; while (map_off != map->len) { size_t written; - if (!(written = text_normalize_map(&state, map, map_off))) break; + if (!(written = text_normalize_map(&state, map, map_off))) { + break; + } map_off += written; if (write(ofd, norm_buff, state.out_pos) == -1) { @@ -726,20 +732,23 @@ static char *sha256file(const char *file, unsigned int *size) void *ctx; ctx = cl_hash_init("sha256"); - if (!(ctx)) + if (!(ctx)) { return NULL; + } if (!(fh = fopen(file, "rb"))) { mprintf(LOGG_ERROR, "sha256file: Can't open file %s\n", file); cl_hash_destroy(ctx); return NULL; } - if (size) + if (size) { *size = 0; + } while ((bytes = fread(buffer, 1, sizeof(buffer), fh))) { cl_update_hash(ctx, buffer, bytes); - if (size) + if (size) { *size += bytes; + } } cl_finish_hash(ctx, digest); sha = (char *)malloc(65); @@ -747,8 +756,9 @@ static char *sha256file(const char *file, unsigned int *size) fclose(fh); return NULL; } - for (i = 0; i < 32; i++) + for (i = 0; i < 32; i++) { sprintf(sha + i * 2, "%02x", digest[i]); + } fclose(fh); return sha; @@ -824,8 +834,9 @@ static int writeinfo(const char *dbname, const char *builder, const char *header return -1; } - while ((bytes = fread(buffer, 1, sizeof(buffer), fh))) + while ((bytes = fread(buffer, 1, sizeof(buffer), fh))) { cl_update_hash(ctx, buffer, bytes); + } cl_finish_hash(ctx, digest); if (!(pt = cli_getdsig(optget(opts, "server")->strarg, builder, digest, 32, 3))) { mprintf(LOGG_ERROR, "writeinfo: Can't get digital signature from remote server\n"); @@ -1174,8 +1185,9 @@ static int build(const struct optstruct *opts) return -1; } - if (optget(opts, "datadir")->active) + if (optget(opts, "datadir")->active) { localdbdir = optget(opts, "datadir")->strarg; + } if (CLAMSTAT("COPYING", &foo) == -1) { mprintf(LOGG_ERROR, "build: COPYING file not found in current working directory.\n"); @@ -1183,11 +1195,13 @@ static int build(const struct optstruct *opts) } getdbname(optget(opts, "build")->strarg, dbname, sizeof(dbname)); - if (!strcmp(dbname, "bytecode")) + if (!strcmp(dbname, "bytecode")) { bc = 1; + } - if (optget(opts, "hybrid")->enabled) + if (optget(opts, "hybrid")->enabled) { hy = 1; + } if (!(engine = cl_engine_new())) { mprintf(LOGG_ERROR, "build: Can't initialize antivirus engine\n"); @@ -1257,13 +1271,15 @@ static int build(const struct optstruct *opts) if (!bc || hy) { for (i = 0; dblist[i].ext; i++) { snprintf(dbfile, sizeof(dbfile), "%s.%s", dbname, dblist[i].ext); - if (dblist[i].count && !access(dbfile, R_OK)) + if (dblist[i].count && !access(dbfile, R_OK)) { entries += countlines(dbfile); + } } } - if (entries != sigs) + if (entries != sigs) { mprintf(LOGG_WARNING, "build: Signatures in %s db files: %u, loaded by libclamav: %u\n", dbname, entries, sigs); + } maxentries = optget(opts, "max-bad-sigs")->numarg; @@ -1290,10 +1306,12 @@ static int build(const struct optstruct *opts) } else { pt = freshdbdir(); snprintf(olddb, sizeof(olddb), "%s" PATHSEP "%s.cvd", localdbdir ? localdbdir : pt, dbname); - if (access(olddb, R_OK)) + if (access(olddb, R_OK)) { snprintf(olddb, sizeof(olddb), "%s" PATHSEP "%s.cld", localdbdir ? localdbdir : pt, dbname); - if (access(olddb, R_OK)) + } + if (access(olddb, R_OK)) { snprintf(olddb, sizeof(olddb), "%s" PATHSEP "%s.cud", localdbdir ? localdbdir : pt, dbname); + } free(pt); } @@ -1318,8 +1336,9 @@ static int build(const struct optstruct *opts) } mprintf(LOGG_INFO, "Total sigs: %u\n", sigs); - if (sigs > oldsigs) + if (sigs > oldsigs) { mprintf(LOGG_INFO, "New sigs: %u\n", sigs - oldsigs); + } strcpy(header, "ClamAV-VDB:"); @@ -1482,8 +1501,9 @@ static int build(const struct optstruct *opts) sprintf(header + strlen(header), ":" STDu64, (uint64_t)timet); /* fill up with spaces */ - while (strlen(header) < sizeof(header) - 1) + while (strlen(header) < sizeof(header) - 1) { strcat(header, " "); + } /* build the final database */ newcvd = optget(opts, "build")->strarg; @@ -1531,8 +1551,9 @@ static int build(const struct optstruct *opts) mprintf(LOGG_INFO, "Created %s\n", newcvd); - if (optget(opts, "unsigned")->enabled) + if (optget(opts, "unsigned")->enabled) { return 0; + } if (!oldcvd || optget(opts, "no-cdiff")->enabled) { mprintf(LOGG_INFO, "Skipping .cdiff creation\n"); @@ -1607,8 +1628,9 @@ static int unpack(const struct optstruct *opts) const char *localdbdir = NULL; const char *certs_directory = NULL; - if (optget(opts, "datadir")->active) + if (optget(opts, "datadir")->active) { localdbdir = optget(opts, "datadir")->strarg; + } if (optget(opts, "unpack-current")->enabled) { dbdir = freshdbdir(); @@ -1683,13 +1705,14 @@ static int cvdinfo(const struct optstruct *opts) mprintf(LOGG_INFO, "Digital signature: %s\n", cvd->dsig); } cl_cvdfree(cvd); - if (cli_strbcasestr(pt, ".cud")) + if (cli_strbcasestr(pt, ".cud")) { mprintf(LOGG_INFO, "Verification: Unsigned container\n"); - else if ((ret = cl_cvdverify(pt))) { + } else if ((ret = cl_cvdverify(pt))) { mprintf(LOGG_ERROR, "cvdinfo: Verification: %s\n", cl_strerror(ret)); return -1; - } else + } else { mprintf(LOGG_INFO, "Verification OK.\n"); + } return 0; } @@ -1825,14 +1848,16 @@ static int listdb(const struct optstruct *opts, const char *filename, const rege while (fgets(buffer, CLI_DEFAULT_LSIG_BUFSIZE, fh)) { if (regex) { cli_chomp(buffer); - if (!cli_regexec(regex, buffer, 0, NULL, 0)) + if (!cli_regexec(regex, buffer, 0, NULL, 0)) { mprintf(LOGG_INFO, "[%s] %s\n", dbname, buffer); + } continue; } line++; - if (buffer && buffer[0] == '#') + if (buffer && buffer[0] == '#') { continue; + } pt = strchr(buffer, '='); if (!pt) { @@ -1845,8 +1870,9 @@ static int listdb(const struct optstruct *opts, const char *filename, const rege start = buffer; *pt = 0; - if ((pt = strstr(start, " (Clam)"))) + if ((pt = strstr(start, " (Clam)"))) { *pt = 0; + } mprintf(LOGG_INFO, "%s\n", start); } @@ -1855,12 +1881,14 @@ static int listdb(const struct optstruct *opts, const char *filename, const rege while (fgets(buffer, CLI_DEFAULT_LSIG_BUFSIZE, fh)) { cli_chomp(buffer); - if (buffer[0] == '#') + if (buffer[0] == '#') { continue; + } if (regex) { - if (!cli_regexec(regex, buffer, 0, NULL, 0)) + if (!cli_regexec(regex, buffer, 0, NULL, 0)) { mprintf(LOGG_INFO, "[%s] %s\n", dbname, buffer); + } continue; } @@ -1872,14 +1900,16 @@ static int listdb(const struct optstruct *opts, const char *filename, const rege while (fgets(buffer, CLI_DEFAULT_LSIG_BUFSIZE, fh)) { cli_chomp(buffer); if (regex) { - if (!cli_regexec(regex, buffer, 0, NULL, 0)) + if (!cli_regexec(regex, buffer, 0, NULL, 0)) { mprintf(LOGG_INFO, "[%s] %s\n", dbname, buffer); + } continue; } line++; - if (buffer && buffer[0] == '#') + if (buffer && buffer[0] == '#') { continue; + } start = cli_strtok(buffer, 2, ":"); @@ -1890,8 +1920,9 @@ static int listdb(const struct optstruct *opts, const char *filename, const rege return -1; } - if ((pt = strstr(start, " (Clam)"))) + if ((pt = strstr(start, " (Clam)"))) { *pt = 0; + } mprintf(LOGG_INFO, "%s\n", start); free(start); @@ -1902,19 +1933,22 @@ static int listdb(const struct optstruct *opts, const char *filename, const rege while (fgets(buffer, CLI_DEFAULT_LSIG_BUFSIZE, fh)) { cli_chomp(buffer); if (regex) { - if (!cli_regexec(regex, buffer, 0, NULL, 0)) + if (!cli_regexec(regex, buffer, 0, NULL, 0)) { mprintf(LOGG_INFO, "[%s] %s\n", dbname, buffer); + } continue; } line++; - if (buffer && buffer[0] == '#') + if (buffer && buffer[0] == '#') { continue; + } - if (cli_strbcasestr(filename, ".ldb") || cli_strbcasestr(filename, ".ldu")) + if (cli_strbcasestr(filename, ".ldb") || cli_strbcasestr(filename, ".ldu")) { pt = strchr(buffer, ';'); - else + } else { pt = strchr(buffer, ':'); + } if (!pt) { mprintf(LOGG_ERROR, "listdb: Malformed pattern line %u (file %s)\n", line, filename); @@ -1924,8 +1958,9 @@ static int listdb(const struct optstruct *opts, const char *filename, const rege } *pt = 0; - if ((pt = strstr(buffer, " (Clam)"))) + if ((pt = strstr(buffer, " (Clam)"))) { *pt = 0; + } mprintf(LOGG_INFO, "%s\n", buffer); } @@ -1962,13 +1997,15 @@ static int listsigs(const struct optstruct *opts, int mode) regex_t reg; const char *localdbdir = NULL; - if (optget(opts, "datadir")->active) + if (optget(opts, "datadir")->active) { localdbdir = optget(opts, "datadir")->strarg; + } if (mode == 0) { name = optget(opts, "list-sigs")->strarg; - if (access(name, R_OK) && localdbdir) + if (access(name, R_OK) && localdbdir) { name = localdbdir; + } if (CLAMSTAT(name, &sb) == -1) { mprintf(LOGG_INFO, "--list-sigs: Can't get status of %s\n", name); return -1; @@ -2159,10 +2196,12 @@ static int vbadump(const struct optstruct *opts) #ifndef _WIN32 if (getrlimit(RLIMIT_FSIZE, &rlim) == 0) { - if (rlim.rlim_cur < (rlim_t)cl_engine_get_num(engine, CL_ENGINE_MAX_FILESIZE, NULL)) + if (rlim.rlim_cur < (rlim_t)cl_engine_get_num(engine, CL_ENGINE_MAX_FILESIZE, NULL)) { logg(LOGG_WARNING, "System limit for file size is lower than engine->maxfilesize\n"); - if (rlim.rlim_cur < (rlim_t)cl_engine_get_num(engine, CL_ENGINE_MAX_SCANSIZE, NULL)) + } + if (rlim.rlim_cur < (rlim_t)cl_engine_get_num(engine, CL_ENGINE_MAX_SCANSIZE, NULL)) { logg(LOGG_WARNING, "System limit for file size is lower than engine->maxscansize\n"); + } } else { logg(LOGG_WARNING, "Cannot obtain resource limits for file size\n"); } @@ -2213,10 +2252,11 @@ static int comparesha(const char *diff) return -1; } *pt = 0; - if ((pt = strrchr(name, *PATHSEP))) + if ((pt = strrchr(name, *PATHSEP))) { pt++; - else + } else { pt = name; + } snprintf(info, sizeof(info), "%s.info", pt); free(name); @@ -2236,8 +2276,9 @@ static int comparesha(const char *diff) cli_chomp(buff); tokens_count = cli_strtokenize(buff, ':', 3, tokens); if (tokens_count != 3) { - if (!strcmp(tokens[0], "DSIG")) + if (!strcmp(tokens[0], "DSIG")) { continue; + } mprintf(LOGG_ERROR, "verifydiff: Incorrect format of %s\n", info); ret = -1; break; @@ -2340,8 +2381,9 @@ static int maxlinelen(const char *file) while ((bytes = read(fd, buff, 512)) > 0) { for (i = 0; i < bytes; i++, ++n) { if (buff[i] == '\n') { - if (n > nmax) + if (n > nmax) { nmax = n; + } n = 0; } } @@ -2382,8 +2424,9 @@ static int compare(const char *oldpath, const char *newpath, FILE *diff) } l2 = maxlinelen(newpath); - if (l1 == -1 || l2 == -1) + if (l1 == -1 || l2 == -1) { return -1; + } l1 = MAX(l1, l2) + 1; obuff = malloc(l1); @@ -2405,8 +2448,9 @@ static int compare(const char *oldpath, const char *newpath, FILE *diff) return -1; } - if (l1 > CLI_DEFAULT_LSIG_BUFSIZE) + if (l1 > CLI_DEFAULT_LSIG_BUFSIZE) { fprintf(diff, "#LSIZE %u\n", l1 + 32); + } fprintf(diff, "OPEN %s\n", newpath); @@ -2423,8 +2467,9 @@ static int compare(const char *oldpath, const char *newpath, FILE *diff) i = strlen(nbuff); if (i >= 2 && (nbuff[i - 1] == '\r' || (nbuff[i - 1] == '\n' && nbuff[i - 2] == '\r'))) { mprintf(LOGG_ERROR, "compare: New %s file contains lines terminated with CRLF or CR\n", newpath); - if (old) + if (old) { fclose(old); + } fclose(new); free(obuff); free(nbuff); @@ -2448,8 +2493,9 @@ static int compare(const char *oldpath, const char *newpath, FILE *diff) tline++; cli_chomp(tbuff); - if (tline > MAX_DEL_LOOKAHEAD) + if (tline > MAX_DEL_LOOKAHEAD) { break; + } if (!strcmp(tbuff, nbuff)) { found = 1; @@ -2463,11 +2509,13 @@ static int compare(const char *oldpath, const char *newpath, FILE *diff) tbuff[l1 - 1] = '\0'; for (i = 0; i < tline; i++) { tbuff[MIN(16, l1 - 1)] = 0; - if ((pt = strchr(tbuff, ' '))) + if ((pt = strchr(tbuff, ' '))) { *pt = 0; + } fprintf(diff, "DEL %u %s\n", oline + i, tbuff); - if (!fgets(tbuff, l1, old)) + if (!fgets(tbuff, l1, old)) { break; + } } oline += tline; @@ -2477,8 +2525,9 @@ static int compare(const char *oldpath, const char *newpath, FILE *diff) break; } obuff[MIN(16, l1 - 1)] = 0; - if ((pt = strchr(obuff, ' '))) + if ((pt = strchr(obuff, ' '))) { *pt = 0; + } fprintf(diff, "XCHG %u %s %s\n", oline, obuff, nbuff); } } @@ -2496,8 +2545,9 @@ static int compare(const char *oldpath, const char *newpath, FILE *diff) oline++; cli_chomp(obuff); obuff[MIN(16, l1 - 1)] = 0; - if ((pt = strchr(obuff, ' '))) + if ((pt = strchr(obuff, ' '))) { *pt = 0; + } fprintf(diff, "DEL %u %s\n", oline, obuff); } } @@ -2551,8 +2601,9 @@ static int dircopy(const char *src, const char *dest) while ((dent = readdir(dd))) { if (dent->d_ino) { - if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, "..")) + if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, "..")) { continue; + } snprintf(spath, sizeof(spath), "%s" PATHSEP "%s", src, dent->d_name); snprintf(dpath, sizeof(dpath), "%s" PATHSEP "%s", dest, dent->d_name); @@ -2780,12 +2831,15 @@ static char *decodehexstr(const char *hex, unsigned int *dlen) unsigned int i, p = 0, wildcard = 0, len = strlen(hex) / 2; str16 = cli_hex2ui(hex); - if (!str16) + if (!str16) { return NULL; + } - for (i = 0; i < len; i++) - if (str16[i] & CLI_MATCH_WILDCARD) + for (i = 0; i < len; i++) { + if (str16[i] & CLI_MATCH_WILDCARD) { wildcard++; + } + } decoded = calloc(len + 1 + wildcard * 32, sizeof(char)); if (!decoded) { @@ -2821,8 +2875,9 @@ static char *decodehexstr(const char *hex, unsigned int *dlen) } } - if (dlen) + if (dlen) { *dlen = p; + } free(str16); return decoded; } @@ -2837,8 +2892,9 @@ inline static char *get_paren_end(char *hexstr) if (*pt == '(') { level++; } else if (*pt == ')') { - if (!level) + if (!level) { return pt; + } level--; } pt++; @@ -2915,44 +2971,50 @@ static char *decodehexspecial(const char *hex, unsigned int *dlen) if (!strcmp(pt, "B")) { if (!*start) { - if (negative) + if (negative) { len += sprintf(buff + len, "{NOT_BOUNDARY_RIGHT}"); - else + } else { len += sprintf(buff + len, "{BOUNDARY_RIGHT}"); + } continue; } else if (pt - 1 == hexcpy) { - if (negative) + if (negative) { len += sprintf(buff + len, "{NOT_BOUNDARY_LEFT}"); - else + } else { len += sprintf(buff + len, "{BOUNDARY_LEFT}"); + } continue; } } else if (!strcmp(pt, "L")) { if (!*start) { - if (negative) + if (negative) { len += sprintf(buff + len, "{NOT_LINE_MARKER_RIGHT}"); - else + } else { len += sprintf(buff + len, "{LINE_MARKER_RIGHT}"); + } continue; } else if (pt - 1 == hexcpy) { - if (negative) + if (negative) { len += sprintf(buff + len, "{NOT_LINE_MARKER_LEFT}"); - else + } else { len += sprintf(buff + len, "{LINE_MARKER_LEFT}"); + } continue; } } else if (!strcmp(pt, "W")) { if (!*start) { - if (negative) + if (negative) { len += sprintf(buff + len, "{NOT_WORD_MARKER_RIGHT}"); - else + } else { len += sprintf(buff + len, "{WORD_MARKER_RIGHT}"); + } continue; } else if (pt - 1 == hexcpy) { - if (negative) + if (negative) { len += sprintf(buff + len, "{NOT_WORD_MARKER_LEFT}"); - else + } else { len += sprintf(buff + len, "{WORD_MARKER_LEFT}"); + } continue; } } else { @@ -2964,10 +3026,11 @@ static char *decodehexspecial(const char *hex, unsigned int *dlen) } /* TODO: analyze string alternative for typing */ - if (negative) + if (negative) { len += sprintf(buff + len, "{EXCLUDING_STRING_ALTERNATIVE:"); - else + } else { len += sprintf(buff + len, "{STRING_ALTERNATIVE:"); + } level = 0; h = e = pt; @@ -3006,10 +3069,11 @@ static char *decodehexspecial(const char *hex, unsigned int *dlen) } } - if (negative) + if (negative) { len += sprintf(buff + len, "{EXCLUDING_STRING_ALTERNATIVE:"); - else + } else { len += sprintf(buff + len, "{STRING_ALTERNATIVE:"); + } break; case ')': @@ -3059,8 +3123,9 @@ static char *decodehexspecial(const char *hex, unsigned int *dlen) } } free(hexcpy); - if (dlen) + if (dlen) { *dlen = len; + } return buff; } @@ -3145,20 +3210,25 @@ static int decodehex(const char *hexsig) free(trigger); free(regex); - if (cflags) + if (cflags) { free(cflags); + } return 0; } else if (strchr(hexsig, '{') || strchr(hexsig, '[')) { - if (!(hexcpy = strdup(hexsig))) + if (!(hexcpy = strdup(hexsig))) { return -1; + } - for (i = 0; i < hexlen; i++) - if (hexsig[i] == '{' || hexsig[i] == '[' || hexsig[i] == '*') + for (i = 0; i < hexlen; i++) { + if (hexsig[i] == '{' || hexsig[i] == '[' || hexsig[i] == '*') { parts++; + } + } - if (parts) + if (parts) { parts++; + } start = pt = hexcpy; for (i = 1; i <= parts; i++) { @@ -3179,14 +3249,16 @@ static int decodehex(const char *hexsig) } if (mindist && maxdist) { - if (mindist == maxdist) + if (mindist == maxdist) { mprintf(LOGG_INFO, "{WILDCARD_ANY_STRING(LENGTH==%u)}", mindist); - else + } else { mprintf(LOGG_INFO, "{WILDCARD_ANY_STRING(LENGTH>=%u&&<=%u)}", mindist, maxdist); - } else if (mindist) + } + } else if (mindist) { mprintf(LOGG_INFO, "{WILDCARD_ANY_STRING(LENGTH>=%u)}", mindist); - else if (maxdist) + } else if (maxdist) { mprintf(LOGG_INFO, "{WILDCARD_ANY_STRING(LENGTH<=%u)}", maxdist); + } if (!(decoded = decodehexspecial(start, &dlen))) { mprintf(LOGG_ERROR, "Decoding failed\n"); @@ -3199,11 +3271,13 @@ static int decodehex(const char *hexsig) } free(decoded); - if (i == parts) + if (i == parts) { break; + } - if (asterisk) + if (asterisk) { mprintf(LOGG_INFO, "{WILDCARD_ANY_STRING}"); + } mindist = maxdist = 0; @@ -3256,16 +3330,20 @@ static int decodehex(const char *hexsig) } free(hexcpy); - if (error) + if (error) { return -1; + } } else if (strchr(hexsig, '*')) { - for (i = 0; i < hexlen; i++) - if (hexsig[i] == '*') + for (i = 0; i < hexlen; i++) { + if (hexsig[i] == '*') { parts++; + } + } - if (parts) + if (parts) { parts++; + } for (i = 1; i <= parts; i++) { if ((pt = cli_strtok(hexsig, i - 1, "*")) == NULL) { @@ -3282,8 +3360,9 @@ static int decodehex(const char *hexsig) mprintf(LOGG_WARNING, "Failed to print all decoded bytes\n"); } free(decoded); - if (i < parts) + if (i < parts) { mprintf(LOGG_INFO, "{WILDCARD_ANY_STRING}"); + } free(pt); } @@ -3338,8 +3417,9 @@ static int decodecdb(char **tokens) int sz = 0; char *range[2]; - if (!tokens) + if (!tokens) { return -1; + } mprintf(LOGG_INFO, "VIRUS NAME: %s\n", tokens[0]); mprintf(LOGG_INFO, "CONTAINER TYPE: %s\n", (strcmp(tokens[1], "*") ? tokens[1] : "ANY")); @@ -3467,10 +3547,11 @@ static int decodeftm(char **tokens, int tokens_count) decodehex(tokens[2]); mprintf(LOGG_INFO, "FILE TYPE REQUIRED: %s\n", tokens[4]); mprintf(LOGG_INFO, "FILE TYPE DETECTED: %s\n", tokens[5]); - if (tokens_count == 7) + if (tokens_count == 7) { mprintf(LOGG_INFO, "FTM FLEVEL: >=%s\n", tokens[6]); - else if (tokens_count == 8) + } else if (tokens_count == 8) { mprintf(LOGG_INFO, "FTM FLEVEL: %s..%s\n", tokens[6], tokens[7]); + } return 0; } @@ -3495,8 +3576,9 @@ static int decodesig(char *sig, int fd) return -1; } mprintf(LOGG_INFO, "VIRUS NAME: %s\n", tokens[0]); - if (strlen(tokens[0]) && strstr(tokens[0], ".{") && tokens[0][strlen(tokens[0]) - 1] == '}') + if (strlen(tokens[0]) && strstr(tokens[0], ".{") && tokens[0][strlen(tokens[0]) - 1] == '}') { bc = 1; + } mprintf(LOGG_INFO, "TDB: %s\n", tokens[1]); mprintf(LOGG_INFO, "LOGICAL EXPRESSION: %s\n", tokens[2]); subsigs = cli_ac_chklsig(tokens[2], tokens[2] + strlen(tokens[2]), NULL, NULL, NULL, 1); @@ -3514,20 +3596,22 @@ static int decodesig(char *sig, int fd) return -1; } for (i = 0; i < tokens_count - 3; i++) { - if (i >= subsigs) + if (i >= subsigs) { mprintf(LOGG_INFO, " * BYTECODE SUBSIG\n"); - else + } else { mprintf(LOGG_INFO, " * SUBSIG ID %d\n", i); + } subtokens_count = cli_ldbtokenize(tokens[3 + i], ':', 4, (const char **)subtokens, 0); if (!subtokens_count) { mprintf(LOGG_ERROR, "decodesig: Invalid or not supported subsignature format\n"); return -1; } - if ((subtokens_count % 2) == 0) + if ((subtokens_count % 2) == 0) { mprintf(LOGG_INFO, " +-> OFFSET: %s\n", subtokens[0]); - else + } else { mprintf(LOGG_INFO, " +-> OFFSET: ANY\n"); + } if (subtokens_count == 3) { mprintf(LOGG_INFO, " +-> SIGMOD:"); @@ -3559,8 +3643,9 @@ static int decodesig(char *sig, int fd) long ftmsigtype; char *end; ftmsigtype = strtol(tokens[0], &end, 10); - if (end == tokens[0] + 1 && (ftmsigtype == 0 || ftmsigtype == 1 || ftmsigtype == 4)) + if (end == tokens[0] + 1 && (ftmsigtype == 0 || ftmsigtype == 1 || ftmsigtype == 4)) { return decodeftm(tokens, tokens_count); + } } if (tokens_count < 4 || tokens_count > 6) { @@ -3569,10 +3654,11 @@ static int decodesig(char *sig, int fd) return -1; } mprintf(LOGG_INFO, "VIRUS NAME: %s\n", tokens[0]); - if (tokens_count == 5) + if (tokens_count == 5) { mprintf(LOGG_INFO, "FUNCTIONALITY LEVEL: >=%s\n", tokens[4]); - else if (tokens_count == 6) + } else if (tokens_count == 6) { mprintf(LOGG_INFO, "FUNCTIONALITY LEVEL: %s..%s\n", tokens[4], tokens[5]); + } if (!cli_isnumber(tokens[1])) { mprintf(LOGG_ERROR, "decodesig: Invalid target type\n"); @@ -3654,10 +3740,12 @@ static int decodesigs(void) fflush(stdin); while (fgets(buffer, sizeof(buffer), stdin)) { cli_chomp(buffer); - if (!strlen(buffer)) + if (!strlen(buffer)) { break; - if (decodesig(buffer, -1) == -1) + } + if (decodesig(buffer, -1) == -1) { return -1; + } } return 0; } @@ -3688,8 +3776,9 @@ static int testsigs(const struct optstruct *opts) while (fgets(buffer, sizeof(buffer), sigs)) { cli_chomp(buffer); - if (!strlen(buffer)) + if (!strlen(buffer)) { break; + } if (decodesig(buffer, fd) == -1) { ret = -1; break; @@ -3732,13 +3821,15 @@ static int diffdirs(const char *old, const char *new, const char *patch) while ((dent = readdir(dd))) { if (dent->d_ino) { - if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, "..")) + if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, "..")) { continue; + } snprintf(path, sizeof(path), "%s" PATHSEP "%s", old, dent->d_name); if (compare(path, dent->d_name, diff) == -1) { - if (chdir(cwd) == -1) + if (chdir(cwd) == -1) { mprintf(LOGG_WARNING, "diffdirs: Can't chdir to %s\n", cwd); + } fclose(diff); unlink(patch); closedir(dd); @@ -3757,20 +3848,23 @@ static int diffdirs(const char *old, const char *new, const char *patch) while ((dent = readdir(dd))) { if (dent->d_ino) { - if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, "..")) + if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, "..")) { continue; + } snprintf(path, sizeof(path), "%s" PATHSEP "%s", new, dent->d_name); - if (access(path, R_OK)) + if (access(path, R_OK)) { fprintf(diff, "UNLINK %s\n", dent->d_name); + } } } closedir(dd); fclose(diff); mprintf(LOGG_INFO, "Generated diff file %s\n", patch); - if (chdir(cwd) == -1) + if (chdir(cwd) == -1) { mprintf(LOGG_WARNING, "diffdirs: Can't chdir to %s\n", cwd); + } return 0; } @@ -3838,8 +3932,9 @@ static int makediff(const struct optstruct *opts) free(odir); free(ndir); - if (ret == -1) + if (ret == -1) { return -1; + } if (verifydiff(opts, name, optget(opts, "diff")->strarg, NULL) == -1) { snprintf(broken, sizeof(broken), "%s.broken", name); @@ -4122,8 +4217,9 @@ int main(int argc, char **argv) struct optstruct *opts; STATBUF sb; - if (check_flevel()) + if (check_flevel()) { exit(1); + } if ((ret = cl_init(CL_INIT_DEFAULT)) != CL_SUCCESS) { mprintf(LOGG_ERROR, "Can't initialize libclamav: %s\n", cl_strerror(ret)); @@ -4143,14 +4239,17 @@ int main(int argc, char **argv) return 1; } - if (optget(opts, "quiet")->enabled) + if (optget(opts, "quiet")->enabled) { mprintf_quiet = 1; + } - if (optget(opts, "stdout")->enabled) + if (optget(opts, "stdout")->enabled) { mprintf_stdout = 1; + } - if (optget(opts, "debug")->enabled) + if (optget(opts, "debug")->enabled) { cl_debug(); + } if (optget(opts, "version")->enabled) { print_version(NULL); @@ -4164,27 +4263,27 @@ int main(int argc, char **argv) return 0; } - if (optget(opts, "hex-dump")->enabled) + if (optget(opts, "hex-dump")->enabled) { ret = hexdump(); - else if (optget(opts, "md5")->enabled) + } else if (optget(opts, "md5")->enabled) { ret = hashsig(opts, 0, 1); - else if (optget(opts, "sha1")->enabled) + } else if (optget(opts, "sha1")->enabled) { ret = hashsig(opts, 0, 2); - else if (optget(opts, "sha256")->enabled) + } else if (optget(opts, "sha256")->enabled) { ret = hashsig(opts, 0, 3); - else if (optget(opts, "mdb")->enabled) + } else if (optget(opts, "mdb")->enabled) { ret = hashsig(opts, 1, 1); - else if (optget(opts, "imp")->enabled) + } else if (optget(opts, "imp")->enabled) { ret = hashsig(opts, 2, 1); - else if (optget(opts, "fuzzy-img")->enabled) + } else if (optget(opts, "fuzzy-img")->enabled) { ret = fuzzy_img(opts); - else if (optget(opts, "html-normalise")->enabled) + } else if (optget(opts, "html-normalise")->enabled) { ret = htmlnorm(opts); - else if (optget(opts, "ascii-normalise")->enabled) + } else if (optget(opts, "ascii-normalise")->enabled) { ret = asciinorm(opts); - else if (optget(opts, "utf16-decode")->enabled) + } else if (optget(opts, "utf16-decode")->enabled) { ret = utf16decode(opts); - else if (optget(opts, "build")->enabled) { + } else if (optget(opts, "build")->enabled) { ret = build(opts); if (ret == CL_ELAST_ERROR) { // build() returns CL_ELAST_ERROR the hash starts with 00. This will fail to verify with ClamAV 1.1 -> 1.4. @@ -4192,35 +4291,35 @@ int main(int argc, char **argv) mprintf(LOGG_WARNING, "Retrying the build for a chance at a better hash.\n"); ret = build(opts); } - } else if (optget(opts, "sign")->enabled) + } else if (optget(opts, "sign")->enabled) { ret = sign(opts); - else if (optget(opts, "verify")->enabled) + } else if (optget(opts, "verify")->enabled) { ret = verify(opts); - else if (optget(opts, "unpack")->enabled) + } else if (optget(opts, "unpack")->enabled) { ret = unpack(opts); - else if (optget(opts, "unpack-current")->enabled) + } else if (optget(opts, "unpack-current")->enabled) { ret = unpack(opts); - else if (optget(opts, "info")->enabled) + } else if (optget(opts, "info")->enabled) { ret = cvdinfo(opts); - else if (optget(opts, "list-sigs")->active) + } else if (optget(opts, "list-sigs")->active) { ret = listsigs(opts, 0); - else if (optget(opts, "find-sigs")->active) + } else if (optget(opts, "find-sigs")->active) { ret = listsigs(opts, 1); - else if (optget(opts, "decode-sigs")->active) + } else if (optget(opts, "decode-sigs")->active) { ret = decodesigs(); - else if (optget(opts, "test-sigs")->enabled) + } else if (optget(opts, "test-sigs")->enabled) { ret = testsigs(opts); - else if (optget(opts, "vba")->enabled || optget(opts, "vba-hex")->enabled) + } else if (optget(opts, "vba")->enabled || optget(opts, "vba-hex")->enabled) { ret = vbadump(opts); - else if (optget(opts, "diff")->enabled) + } else if (optget(opts, "diff")->enabled) { ret = makediff(opts); - else if (optget(opts, "compare")->enabled) + } else if (optget(opts, "compare")->enabled) { ret = compareone(opts); - else if (optget(opts, "print-certs")->enabled) + } else if (optget(opts, "print-certs")->enabled) { ret = dumpcerts(opts); - else if (optget(opts, "run-cdiff")->enabled) + } else if (optget(opts, "run-cdiff")->enabled) { ret = rundiff(opts); - else if (optget(opts, "verify-cdiff")->enabled) { + } else if (optget(opts, "verify-cdiff")->enabled) { if (!opts->filename) { mprintf(LOGG_ERROR, "--verify-cdiff requires two arguments\n"); ret = -1; @@ -4229,14 +4328,16 @@ int main(int argc, char **argv) mprintf(LOGG_INFO, "--verify-cdiff: Can't get status of %s\n", opts->filename[0]); ret = -1; } else { - if (S_ISDIR(sb.st_mode)) + if (S_ISDIR(sb.st_mode)) { ret = verifydiff(opts, optget(opts, "verify-cdiff")->strarg, NULL, opts->filename[0]); - else + } else { ret = verifydiff(opts, optget(opts, "verify-cdiff")->strarg, opts->filename[0], NULL); + } } } - } else + } else { help(); + } optfree(opts);