]> git.ipfire.org Git - thirdparty/snort3.git/commitdiff
Pull request #3935: Cppcheck
authorRon Dempster (rdempste) <rdempste@cisco.com>
Tue, 31 Oct 2023 14:26:28 +0000 (14:26 +0000)
committerRon Dempster (rdempste) <rdempste@cisco.com>
Tue, 31 Oct 2023 14:26:28 +0000 (14:26 +0000)
Merge in SNORT/snort3 from ~RDEMPSTE/snort3:cppcheck to master

Squashed commit of the following:

commit e7663dd3be7fd74a91808f293de0222ea7a467ee
Author: Ron Dempster (rdempste) <rdempste@cisco.com>
Date:   Thu Oct 19 11:46:13 2023 -0400

    build: remove unused functions reported by cppcheck

commit ce623c51d7bb6a034d09b3700db74f1ccf229bc5
Author: Ron Dempster (rdempste) <rdempste@cisco.com>
Date:   Wed Jul 19 12:55:56 2023 -0400

    actions, detection, file_api, flow, stream: coverity fixes

commit bed4872d9259d16a345e61a15f766505c18b0c30
Author: Ron Dempster (rdempste) <rdempste@cisco.com>
Date:   Fri Jun 30 13:57:44 2023 -0400

    build: Address miscellaneous cppcheck warnings

499 files changed:
src/actions/act_react.cc
src/actions/act_reject.cc
src/codecs/ip/cd_auth.cc
src/codecs/ip/cd_gre.cc
src/codecs/ip/cd_icmp4.cc
src/codecs/ip/cd_icmp6.cc
src/codecs/ip/cd_mobility.cc
src/codecs/ip/cd_pgm.cc
src/codecs/link/cd_fabricpath.cc
src/codecs/link/cd_pppoe.cc
src/codecs/link/cd_vlan.cc
src/codecs/misc/cd_vxlan.cc
src/connectors/file_connector/file_connector_module.cc
src/connectors/file_connector/file_connector_module.h
src/connectors/file_connector/test/file_connector_test.cc
src/connectors/tcp_connector/tcp_connector.cc
src/connectors/tcp_connector/tcp_connector.h
src/connectors/tcp_connector/tcp_connector_module.cc
src/connectors/tcp_connector/tcp_connector_module.h
src/connectors/tcp_connector/test/tcp_connector_test.cc
src/decompress/file_decomp_pdf.cc
src/decompress/file_olefile.cc
src/decompress/file_olefile.h
src/decompress/test/file_olefile_test.cc
src/detection/context_switcher.cc
src/detection/detection_continuation.h
src/detection/detection_engine.cc
src/detection/detection_options.cc
src/detection/fp_config.cc
src/detection/fp_config.h
src/detection/fp_create.cc
src/detection/fp_detect.cc
src/detection/fp_utils.cc
src/detection/pattern_match_data.h
src/detection/regex_offload.cc
src/detection/regex_offload.h
src/detection/service_map.cc
src/detection/signature.cc
src/detection/tag.cc
src/detection/treenodes.h
src/dump_config/config_data.cc
src/file_api/file_flows.cc
src/file_api/file_lib.cc
src/file_api/file_log.cc
src/filters/detection_filter.cc
src/filters/sfrf.cc
src/flow/deferred_trust.h
src/flow/expect_cache.cc
src/flow/flow.cc
src/flow/flow.h
src/flow/flow_stash.cc
src/flow/ha.cc
src/flow/ha.h
src/flow/session.h
src/flow/test/CMakeLists.txt
src/flow/test/flow_cache_test.cc
src/flow/test/flow_control_test.cc
src/flow/test/flow_stash_test.cc
src/flow/test/flow_stubs.h [new file with mode: 0644]
src/flow/test/flow_test.cc
src/flow/test/ha_test.cc
src/framework/connector.h
src/framework/cursor.cc
src/framework/cursor.h
src/framework/data_bus.cc
src/framework/decode_data.h
src/framework/inspector.cc
src/framework/ips_option.cc
src/framework/logger.h
src/framework/lua_api.h
src/framework/mpse.cc
src/framework/mpse.h
src/framework/packet_constraints.cc
src/framework/range.cc
src/framework/test/data_bus_test.cc
src/framework/value.cc
src/hash/lru_cache_local.h
src/hash/lru_cache_shared.h
src/hash/lru_segmented_cache_shared.h
src/hash/test/ghash_test.cc
src/hash/test/lru_cache_shared_test.cc
src/hash/test/lru_seg_cache_shared_test.cc
src/hash/test/xhash_test.cc
src/hash/test/zhash_test.cc
src/helpers/discovery_filter.cc
src/helpers/sigsafe.cc
src/helpers/test/bitop_test.cc
src/host_tracker/host_cache_module.cc
src/host_tracker/host_cache_segmented.h
src/host_tracker/host_tracker.cc
src/host_tracker/host_tracker.h
src/host_tracker/host_tracker_module.h
src/host_tracker/test/cache_allocator_test.cc
src/host_tracker/test/host_cache_module_test.cc
src/host_tracker/test/host_tracker_test.cc
src/ips_options/extract.cc
src/ips_options/ips_ack.cc
src/ips_options/ips_base64.cc
src/ips_options/ips_ber_data.cc
src/ips_options/ips_ber_skip.cc
src/ips_options/ips_bufferlen.cc
src/ips_options/ips_byte_extract.cc
src/ips_options/ips_byte_jump.cc
src/ips_options/ips_byte_math.cc
src/ips_options/ips_byte_test.cc
src/ips_options/ips_content.cc
src/ips_options/ips_cvs.cc
src/ips_options/ips_dsize.cc
src/ips_options/ips_file_data.cc
src/ips_options/ips_file_meta.cc
src/ips_options/ips_file_type.cc
src/ips_options/ips_flags.cc
src/ips_options/ips_flow.cc
src/ips_options/ips_flowbits.cc
src/ips_options/ips_fragbits.cc
src/ips_options/ips_fragoffset.cc
src/ips_options/ips_hash.cc
src/ips_options/ips_icmp_id.cc
src/ips_options/ips_icmp_seq.cc
src/ips_options/ips_icode.cc
src/ips_options/ips_id.cc
src/ips_options/ips_ip_proto.cc
src/ips_options/ips_ipopts.cc
src/ips_options/ips_isdataat.cc
src/ips_options/ips_itype.cc
src/ips_options/ips_js_data.cc
src/ips_options/ips_luajit.cc
src/ips_options/ips_pcre.cc
src/ips_options/ips_pkt_data.cc
src/ips_options/ips_raw_data.cc
src/ips_options/ips_regex.cc
src/ips_options/ips_replace.cc
src/ips_options/ips_rpc.cc
src/ips_options/ips_sd_pattern.cc
src/ips_options/ips_seq.cc
src/ips_options/ips_service.cc
src/ips_options/ips_so.cc
src/ips_options/ips_tos.cc
src/ips_options/ips_ttl.cc
src/ips_options/ips_vba_data.cc
src/ips_options/ips_window.cc
src/js_norm/js_identifier_ctx.cc
src/js_norm/js_pdf_norm.cc
src/js_norm/test/js_identifier_ctx_test.cc
src/js_norm/test/js_test_utils.cc
src/js_norm/test/js_test_utils.h
src/js_norm/test/jsn_test.cc
src/js_norm/test/pdf_tokenizer_test.cc
src/latency/packet_latency.cc
src/latency/rule_latency.cc
src/log/obfuscator.h
src/log/test/obfuscator_test.cc
src/loggers/alert_csv.cc
src/loggers/alert_fast.cc
src/loggers/alert_full.cc
src/loggers/alert_json.cc
src/loggers/alert_luajit.cc
src/loggers/alert_syslog.cc
src/loggers/log_hext.cc
src/loggers/log_pcap.cc
src/loggers/unified2.cc
src/main/analyzer.cc
src/main/analyzer.h
src/main/modules.cc
src/main/policy.cc
src/main/reload_tracker.cc
src/main/reload_tracker.h
src/main/snort.cc
src/main/snort_config.cc
src/main/snort_module.cc
src/main/test/distill_verdict_stubs.h
src/main/thread_config.cc
src/managers/action_manager.cc
src/managers/codec_manager.cc
src/managers/connector_manager.cc
src/managers/event_manager.cc
src/managers/inspector_manager.cc
src/managers/ips_manager.cc
src/managers/module_manager.cc
src/managers/mpse_manager.cc
src/managers/plugin_manager.cc
src/managers/script_manager.cc
src/managers/so_manager.cc
src/managers/test/get_inspector_stubs.h
src/managers/test/get_inspector_test.cc
src/memory/memory_overloads.cc
src/mime/file_mime_process.cc
src/network_inspectors/appid/app_info_table.cc
src/network_inspectors/appid/appid_app_descriptor.cc
src/network_inspectors/appid/appid_config.h
src/network_inspectors/appid/appid_debug.h
src/network_inspectors/appid/appid_detector.cc
src/network_inspectors/appid/appid_eve_process_event_handler.cc
src/network_inspectors/appid/appid_http_session.cc
src/network_inspectors/appid/appid_inspector.cc
src/network_inspectors/appid/appid_module.cc
src/network_inspectors/appid/appid_ssh_event_handler.cc
src/network_inspectors/appid/appid_stats.cc
src/network_inspectors/appid/appid_stats.h
src/network_inspectors/appid/client_plugins/client_app_msn.cc
src/network_inspectors/appid/detector_plugins/detector_imap.cc
src/network_inspectors/appid/detector_plugins/detector_pattern.cc
src/network_inspectors/appid/detector_plugins/detector_pop3.cc
src/network_inspectors/appid/detector_plugins/detector_smtp.cc
src/network_inspectors/appid/detector_plugins/http_url_patterns.cc
src/network_inspectors/appid/detector_plugins/test/detector_plugins_mock.h
src/network_inspectors/appid/detector_plugins/test/detector_sip_test.cc
src/network_inspectors/appid/host_port_app_cache.h
src/network_inspectors/appid/ips_appid_option.cc
src/network_inspectors/appid/lua_detector_api.cc
src/network_inspectors/appid/lua_detector_api.h
src/network_inspectors/appid/lua_detector_flow_api.h
src/network_inspectors/appid/lua_detector_module.cc
src/network_inspectors/appid/service_plugins/service_rexec.cc
src/network_inspectors/appid/service_plugins/service_rshell.cc
src/network_inspectors/appid/service_plugins/service_rtmp.cc
src/network_inspectors/appid/service_plugins/test/service_plugin_mock.h
src/network_inspectors/appid/service_state.h
src/network_inspectors/appid/test/appid_mock_inspector.h
src/network_inspectors/appid/test/appid_session_api_test.cc
src/network_inspectors/appid/test/service_state_test.cc
src/network_inspectors/appid/tp_appid_utils.cc
src/network_inspectors/arp_spoof/arp_module.cc
src/network_inspectors/arp_spoof/arp_module.h
src/network_inspectors/arp_spoof/arp_spoof.cc
src/network_inspectors/binder/binder.cc
src/network_inspectors/normalize/norm.cc
src/network_inspectors/normalize/normalize.cc
src/network_inspectors/packet_tracer/packet_tracer.cc
src/network_inspectors/packet_tracer/packet_tracer.h
src/network_inspectors/perf_monitor/csv_formatter.cc
src/network_inspectors/perf_monitor/flow_ip_tracker.cc
src/network_inspectors/perf_monitor/perf_module.cc
src/network_inspectors/perf_monitor/perf_monitor.cc
src/network_inspectors/port_scan/port_scan.cc
src/network_inspectors/reputation/reputation_inspect.cc
src/network_inspectors/reputation/reputation_parse.cc
src/network_inspectors/rna/rna_app_discovery.cc
src/network_inspectors/rna/rna_event_handler.cc
src/network_inspectors/rna/rna_event_handler.h
src/network_inspectors/rna/rna_fingerprint.h
src/network_inspectors/rna/rna_fingerprint_tcp.cc
src/network_inspectors/rna/rna_fingerprint_tcp.h
src/network_inspectors/rna/rna_fingerprint_ua.cc
src/network_inspectors/rna/rna_fingerprint_udp.cc
src/network_inspectors/rna/rna_flow.cc
src/network_inspectors/rna/rna_flow.h
src/network_inspectors/rna/rna_inspector.cc
src/network_inspectors/rna/rna_logger.cc
src/network_inspectors/rna/rna_logger.h
src/network_inspectors/rna/rna_mac_cache.cc
src/network_inspectors/rna/rna_module.cc
src/network_inspectors/rna/rna_pnd.cc
src/network_inspectors/rna/test/rna_module_mock.h
src/network_inspectors/rna/test/rna_ua_fp_processor_test.cc
src/packet_io/active.h
src/packet_io/sfdaq.cc
src/packet_io/sfdaq_config.cc
src/packet_io/test/sfdaq_module_test.cc
src/parser/parse_conf.cc
src/parser/parse_utils.cc
src/parser/parser.cc
src/parser/vars.cc
src/payload_injector/test/payload_injector_translate_test.cc
src/policy_selectors/address_space_selector/address_space_selector.cc
src/policy_selectors/tenant_selector/tenant_selector.cc
src/ports/port_group.cc
src/ports/port_object2.cc
src/profiler/memory_context.cc
src/profiler/profiler.cc
src/profiler/profiler_nodes.cc
src/profiler/rule_profiler.cc
src/profiler/time_profiler.cc
src/protocols/ip.cc
src/protocols/ip.h
src/protocols/layer.cc
src/protocols/layer.h
src/protocols/packet.cc
src/protocols/packet.h
src/pub_sub/appid_events.h
src/pub_sub/eve_process_event.h
src/pub_sub/sip_events.cc
src/pub_sub/sip_events.h
src/pub_sub/test/pub_sub_eve_process_event_test.cc
src/pub_sub/test/pub_sub_http_request_body_event_test.cc
src/search_engines/acsmx2.cc
src/search_engines/acsmx2.h
src/search_engines/bnfa_search.cc
src/search_engines/bnfa_search.h
src/search_engines/hyperscan.cc
src/search_engines/test/hyper_tool_test.cc
src/search_engines/test/hyperscan_test.cc
src/search_engines/test/mpse_test_stubs.cc
src/search_engines/test/search_tool_test.cc
src/service_inspectors/back_orifice/back_orifice.cc
src/service_inspectors/cip/cip.cc
src/service_inspectors/cip/cip_session.cc
src/service_inspectors/cip/cip_session.h
src/service_inspectors/cip/ips_cip_attribute.cc
src/service_inspectors/cip/ips_cip_class.cc
src/service_inspectors/cip/ips_cip_connpathclass.cc
src/service_inspectors/cip/ips_cip_enipcommand.cc
src/service_inspectors/cip/ips_cip_enipreq.cc
src/service_inspectors/cip/ips_cip_eniprsp.cc
src/service_inspectors/cip/ips_cip_instance.cc
src/service_inspectors/cip/ips_cip_req.cc
src/service_inspectors/cip/ips_cip_rsp.cc
src/service_inspectors/cip/ips_cip_service.cc
src/service_inspectors/cip/ips_cip_status.cc
src/service_inspectors/dce_rpc/dce_http_proxy_splitter.cc
src/service_inspectors/dce_rpc/dce_http_server_splitter.cc
src/service_inspectors/dce_rpc/dce_smb.cc
src/service_inspectors/dce_rpc/dce_smb2.cc
src/service_inspectors/dce_rpc/dce_smb2_utils.h
src/service_inspectors/dce_rpc/dce_tcp.cc
src/service_inspectors/dce_rpc/dce_tcp_module.h
src/service_inspectors/dce_rpc/dce_udp.cc
src/service_inspectors/dce_rpc/dce_udp_module.h
src/service_inspectors/dce_rpc/dce_utils.cc
src/service_inspectors/dce_rpc/dce_utils.h
src/service_inspectors/dce_rpc/ips_dce_iface.cc
src/service_inspectors/dce_rpc/ips_dce_opnum.cc
src/service_inspectors/dce_rpc/ips_dce_stub_data.cc
src/service_inspectors/dnp3/dnp3.cc
src/service_inspectors/dnp3/dnp3.h
src/service_inspectors/dnp3/dnp3_module.h
src/service_inspectors/dnp3/ips_dnp3_data.cc
src/service_inspectors/dnp3/ips_dnp3_func.cc
src/service_inspectors/dnp3/ips_dnp3_ind.cc
src/service_inspectors/dnp3/ips_dnp3_obj.cc
src/service_inspectors/dns/dns.cc
src/service_inspectors/ftp_telnet/ftp.cc
src/service_inspectors/ftp_telnet/ftp_data.cc
src/service_inspectors/ftp_telnet/ftp_module.cc
src/service_inspectors/ftp_telnet/ftp_module.h
src/service_inspectors/ftp_telnet/pp_telnet.cc
src/service_inspectors/ftp_telnet/pp_telnet.h
src/service_inspectors/ftp_telnet/telnet.cc
src/service_inspectors/gtp/gtp_inspect.cc
src/service_inspectors/gtp/gtp_module.h
src/service_inspectors/gtp/ips_gtp_info.cc
src/service_inspectors/gtp/ips_gtp_type.cc
src/service_inspectors/gtp/ips_gtp_version.cc
src/service_inspectors/http2_inspect/http2_data_cutter.h
src/service_inspectors/http2_inspect/http2_flow_data.cc
src/service_inspectors/http2_inspect/http2_frame.cc
src/service_inspectors/http2_inspect/http2_hpack.h
src/service_inspectors/http2_inspect/http2_inspect.cc
src/service_inspectors/http2_inspect/http2_settings_frame.cc
src/service_inspectors/http2_inspect/http2_settings_frame.h
src/service_inspectors/http2_inspect/http2_stream_splitter.cc
src/service_inspectors/http2_inspect/ips_http2.cc
src/service_inspectors/http2_inspect/test/http2_hpack_string_decode_test.cc
src/service_inspectors/http_inspect/http_flow_data.cc
src/service_inspectors/http_inspect/http_inspect.cc
src/service_inspectors/http_inspect/http_inspect.h
src/service_inspectors/http_inspect/http_msg_header.cc
src/service_inspectors/http_inspect/http_msg_section.cc
src/service_inspectors/http_inspect/http_msg_start.cc
src/service_inspectors/http_inspect/http_msg_trailer.cc
src/service_inspectors/http_inspect/http_normalized_header.cc
src/service_inspectors/http_inspect/http_normalized_header.h
src/service_inspectors/http_inspect/http_query_parser.h
src/service_inspectors/http_inspect/http_stream_splitter_finish.cc
src/service_inspectors/http_inspect/http_stream_splitter_reassemble.cc
src/service_inspectors/http_inspect/http_stream_splitter_scan.cc
src/service_inspectors/http_inspect/http_test_input.h
src/service_inspectors/http_inspect/ips_http.h
src/service_inspectors/http_inspect/ips_http_buffer.h
src/service_inspectors/http_inspect/ips_http_num_hdrs.cc
src/service_inspectors/http_inspect/ips_http_param.cc
src/service_inspectors/http_inspect/ips_http_test.cc
src/service_inspectors/http_inspect/ips_http_test.h
src/service_inspectors/http_inspect/ips_http_version.cc
src/service_inspectors/http_inspect/test/http_msg_head_shared_util_test.cc
src/service_inspectors/http_inspect/test/http_transaction_test.cc
src/service_inspectors/http_inspect/test/http_uri_norm_test.cc
src/service_inspectors/iec104/iec104.cc
src/service_inspectors/iec104/ips_iec104_apci_type.cc
src/service_inspectors/iec104/ips_iec104_asdu_func.cc
src/service_inspectors/imap/imap.cc
src/service_inspectors/mms/ips_mms_data.cc
src/service_inspectors/mms/mms.cc
src/service_inspectors/mms/tpkt/osi_session_decode.cc
src/service_inspectors/mms/util_tpkt.cc
src/service_inspectors/modbus/ips_modbus_data.cc
src/service_inspectors/modbus/ips_modbus_func.cc
src/service_inspectors/modbus/ips_modbus_unit.cc
src/service_inspectors/modbus/modbus.cc
src/service_inspectors/modbus/modbus_decode.cc
src/service_inspectors/netflow/netflow.cc
src/service_inspectors/netflow/netflow_module.cc
src/service_inspectors/netflow/netflow_module.h
src/service_inspectors/pop/pop.cc
src/service_inspectors/rpc_decode/rpc_decode.cc
src/service_inspectors/s7commplus/ips_s7comm_content.cc
src/service_inspectors/s7commplus/ips_s7comm_func.cc
src/service_inspectors/s7commplus/ips_s7comm_opcode.cc
src/service_inspectors/s7commplus/s7comm.cc
src/service_inspectors/sip/ips_sip_method.cc
src/service_inspectors/sip/ips_sip_stat_code.cc
src/service_inspectors/sip/sip.cc
src/service_inspectors/sip/sip_dialog.cc
src/service_inspectors/sip/sip_dialog.h
src/service_inspectors/smtp/smtp.cc
src/service_inspectors/smtp/smtp_module.cc
src/service_inspectors/smtp/smtp_module.h
src/service_inspectors/smtp/smtp_xlink2state.cc
src/service_inspectors/ssh/ssh.cc
src/service_inspectors/ssh/ssh.h
src/service_inspectors/ssl/ips_ssl_state.cc
src/service_inspectors/ssl/ips_ssl_version.cc
src/service_inspectors/ssl/ssl_inspector.cc
src/service_inspectors/wizard/curse_book.cc
src/service_inspectors/wizard/hexes.cc
src/service_inspectors/wizard/magic.h
src/service_inspectors/wizard/spells.cc
src/service_inspectors/wizard/ssl_curse.cc
src/service_inspectors/wizard/wiz_module.h
src/service_inspectors/wizard/wizard.cc
src/sfip/sf_cidr.h
src/sfip/sf_ip.cc
src/sfip/sf_ipvar.cc
src/sfip/test/sf_ip_test.cc
src/sfrt/sfrt_flat_dir.cc
src/side_channel/side_channel.cc
src/side_channel/side_channel.h
src/stream/base/stream_base.cc
src/stream/base/stream_ha.cc
src/stream/file/file_module.h
src/stream/file/file_session.cc
src/stream/file/file_session.h
src/stream/icmp/icmp_module.cc
src/stream/icmp/icmp_module.h
src/stream/icmp/icmp_session.h
src/stream/ip/ip_defrag.cc
src/stream/ip/ip_session.cc
src/stream/ip/ip_session.h
src/stream/paf.cc
src/stream/stream_splitter.cc
src/stream/tcp/ips_stream_reassemble.cc
src/stream/tcp/ips_stream_size.cc
src/stream/tcp/tcp_reassembler.cc
src/stream/tcp/tcp_reassembler.h
src/stream/tcp/tcp_reassemblers.h
src/stream/tcp/tcp_segment_descriptor.cc
src/stream/tcp/tcp_segment_descriptor.h
src/stream/tcp/tcp_session.cc
src/stream/tcp/tcp_session.h
src/stream/tcp/tcp_stream_config.h
src/stream/tcp/tcp_stream_session.cc
src/stream/tcp/tcp_stream_session.h
src/stream/tcp/tcp_stream_tracker.h
src/stream/tcp/test/tcp_normalizer_test.cc
src/stream/udp/udp_module.cc
src/stream/udp/udp_module.h
src/stream/udp/udp_session.cc
src/stream/user/user_session.cc
src/stream/user/user_session.h
src/target_based/host_attributes.cc
src/time/test/stopwatch_test.cc
src/trace/trace.cc
src/trace/trace_parser.cc
src/utils/kmap.cc
src/utils/primed_allocator.h
src/utils/stats.cc
src/utils/streambuf.cc
src/utils/test/streambuf_test.cc
src/utils/util.cc
src/utils/util.h
src/utils/util_jsnorm.cc
src/utils/util_numa.h
src/utils/util_utf.cc
src/utils/util_utf.h
tools/snort2lua/conversion_state.h
tools/snort2lua/data/data_types/dt_option.h
tools/snort2lua/data/data_types/dt_rule.cc
tools/snort2lua/data/data_types/dt_rule_option.cc
tools/snort2lua/data/data_types/dt_rule_option.h
tools/snort2lua/data/data_types/dt_table.cc
tools/snort2lua/data/data_types/dt_table.h
tools/snort2lua/data/dt_data.cc
tools/snort2lua/data/dt_rule_api.cc
tools/snort2lua/data/dt_state_api.cc
tools/snort2lua/data/dt_table_api.cc
tools/snort2lua/helpers/converter.cc
tools/snort2lua/helpers/s2l_util.cc
tools/snort2lua/helpers/util_binder.cc
tools/snort2lua/helpers/util_binder.h
tools/snort2lua/keyword_states/kws_rule.cc
tools/snort2lua/keyword_states/kws_ruletype.cc
tools/snort2lua/preprocessor_states/pps_ftp_telnet_protocol.cc
tools/snort2lua/rule_states/rule_base64_decode.cc
tools/snort2lua/rule_states/rule_dnp3_obj.cc
tools/snort2lua/rule_states/rule_file_data.cc
tools/snort2lua/rule_states/rule_react.cc
tools/snort2lua/rule_states/rule_resp.cc
tools/snort2lua/rule_states/rule_tag.cc
tools/snort2lua/rule_states/rule_threshold.cc

index cf89582a8f50f9896f215e6d246f7d2ffe31b747..e52576470f20f62d80d12aa504269e0ce679e45f 100644 (file)
@@ -101,7 +101,7 @@ class ReactData
 {
 public:
 
-    ReactData(const std::string& page)
+    explicit ReactData(const std::string& page)
     {
         if ( page.empty())
         {
@@ -136,7 +136,7 @@ private:
 class ReactActiveAction : public ActiveAction
 {
 public:
-    ReactActiveAction(ReactData* c)
+    explicit ReactActiveAction(ReactData* c)
         : ActiveAction( ActionPriority::AP_PROXY ), config(c)
     { }
 
@@ -149,6 +149,7 @@ private:
 
 void ReactActiveAction::delayed_exec(Packet* p)
 {
+    // cppcheck-suppress unreadVariable
     Profile profile(reactPerfStats);
 
     if ( p->active->is_reset_candidate(p) )
index 79ff3ca1e38d4d1732cde43e73cb906c84fde0b0..dbb1fe0dcd1eb9387d09861dc4e55cc3b7a98c49 100644 (file)
@@ -210,7 +210,7 @@ public:
     uint32_t get_data();
 
 private:
-    uint32_t flags;
+    uint32_t flags = 0;
 };
 
 bool RejectModule::begin(const char*, int, SnortConfig*)
index a97c8691498c913f610f16131b7740d0601c5efc..93afcb8428064b758e4331ab16e3d3d43e32e2ef 100644 (file)
@@ -66,9 +66,13 @@ struct AuthHdr
 {
     IpProtocol next;
     uint8_t len;
+    // cppcheck-suppress unusedStructMember
     uint16_t rsv;   /* reserved */
+    // cppcheck-suppress unusedStructMember
     uint32_t spi;   /* Security Parameters Index */
+    // cppcheck-suppress unusedStructMember
     uint32_t seq;   /* Sequence Number */
+    // cppcheck-suppress unusedStructMember
     uint32_t icv[1]; /* VARIABLE LENGTH!! -- specified by len field*/
 };
 
index d8a3488fb98bb11ef09eb279d9de111ce9c94955..054a2071bb5767823ac7fc9494605474b40bbbd3 100644 (file)
@@ -353,6 +353,6 @@ TEST_CASE ("Validate error check for raw_len greater than GRE_HEADER_LEN", "[cd_
     Buffer buf(&t, size);
     Flow *flow = nullptr;
 
-    CHECK (grecodec.encode(&raw_in,raw_len,enc,buf,flow) == false);
+    CHECK (false == grecodec.encode(&raw_in,raw_len,enc,buf,flow));
 }
 #endif
index b8a698df2ff3d3e3fce54103ee443128f1a743ed..334805ca222b7e83a9fceb0b0c1110ce14334c31 100644 (file)
@@ -565,9 +565,12 @@ namespace
 {
 struct IcmpHdr
 {
+    // cppcheck-suppress unusedStructMember
     uint8_t type;
+    // cppcheck-suppress unusedStructMember
     uint8_t code;
     uint16_t cksum;
+    // cppcheck-suppress unusedStructMember
     uint32_t unused;
 };
 } // namespace
index e6825135507cb30238c3fa86c01017e20a76d8d4..1e90b4c66b3d4ecb64ddce65fac4467d41a2ddc3 100644 (file)
@@ -341,9 +341,12 @@ namespace
 {
 struct IcmpHdr
 {
+    // cppcheck-suppress unusedStructMember
     uint8_t type;
+    // cppcheck-suppress unusedStructMember
     uint8_t code;
     uint16_t cksum;
+    // cppcheck-suppress unusedStructMember
     uint32_t unused;
 };
 } // namespace
index 292d9d5359a0a27e96813fed8fb5d1910547d9bb..2971aa3acd9f2a3632525ab2b44712da9b1500bf 100644 (file)
@@ -46,8 +46,11 @@ struct MobileIPV6Header  // RFC 6275
 {
     IpProtocol payload_proto;
     uint8_t header_len;
+    // cppcheck-suppress unusedStructMember
     uint8_t mh_type;
+    // cppcheck-suppress unusedStructMember
     uint8_t reserved;
+    // cppcheck-suppress unusedStructMember
     uint16_t checksum;
 };
 } // namespace
index 2ffb5740a9eeabac616b161006b953ad515c961d..2265d327999dd03224b9b3bc67e9e77409a365cb 100644 (file)
@@ -66,18 +66,27 @@ struct PGM_NAK_OPT
 {
     uint8_t type;     /* 02 = vuln */
     uint8_t len;
+    // cppcheck-suppress unusedStructMember
     uint8_t res[2];
+    // cppcheck-suppress unusedStructMember
     uint32_t seq[1];    /* could be many many more, but 1 is sufficient */
 };
 
 struct PGM_NAK
 {
+    // cppcheck-suppress unusedStructMember
     uint32_t seqnum;
+    // cppcheck-suppress unusedStructMember
     uint16_t afil1;
+    // cppcheck-suppress unusedStructMember
     uint16_t res1;
+    // cppcheck-suppress unusedStructMember
     uint32_t src;
+    // cppcheck-suppress unusedStructMember
     uint16_t afi2;
+    // cppcheck-suppress unusedStructMember
     uint16_t res2;
+    // cppcheck-suppress unusedStructMember
     uint32_t multi;
     PGM_NAK_OPT opt;
 };
index cb05559e5b25b70a939e3bf39ce714b6e5290fe0..d6bdf06199cbb1dcfa5b614949f3292d969e8331 100644 (file)
@@ -63,6 +63,7 @@ struct FPathHdr
     uint8_t fpath_dst[6];
     uint8_t fpath_src[6];
     uint16_t fpath_type;
+    // cppcheck-suppress unusedStructMember
     uint16_t fptag_extra; /* 10-bit FTag + 6-bit TTL */
 };
 
index 64da98ff27511c75e5bb1b1135a8bb2066bb8848..fa11be8967b82aa39ca07dc0be529991ffd34b98 100644 (file)
@@ -38,8 +38,11 @@ enum class PppoepktType
 /* PPPoEHdr Header; eth::EtherHdr plus the PPPoE Header */
 struct PPPoEHdr
 {
+    // cppcheck-suppress unusedStructMember
     uint8_t ver_type;     /* pppoe version/type */
+    // cppcheck-suppress unusedStructMember
     uint8_t code;         /* pppoe code CODE_* */
+    // cppcheck-suppress unusedStructMember
     uint16_t session;     /* session id */
     uint16_t length;      /* payload length */
     /* payload follows */
index 8036fdd1ff13ca451bb4facaabe60aa2059e8c4f..91aa648eada737559bd6c6e372388e47a0ea87e7 100644 (file)
@@ -83,8 +83,8 @@ bool VlanModule::set(const char*, Value& v, SnortConfig*)
 class VlanCodec : public Codec
 {
 public:
-    VlanCodec(const char* s) : Codec(CD_VLAN_NAME)
-    { tpids = s; }
+    VlanCodec(const char* s) : Codec(CD_VLAN_NAME), tpids(s)
+    { }
 
     void get_protocol_ids(std::vector<ProtocolId>& v) override;
     bool decode(const RawData&, CodecData&, DecodeData&) override;
index e81f5ce2d7c91b788cbf4f74f27f405f4a80bd24..c187a813687d5ad314f4c88126dbec76af1dc5c0 100644 (file)
@@ -46,8 +46,10 @@ public:
 struct VXLANHdr
 {
     uint8_t flags;
+    // cppcheck-suppress unusedStructMember
     uint8_t reserved_1[3];
     uint8_t vni[3]; //VXLAN network id
+    // cppcheck-suppress unusedStructMember
     uint8_t reserved_2;
 };
 constexpr uint16_t VXLAN_MIN_HDR_LEN = 8;
index ef3b65ad951bf0a5f0281e9e3e216e76970f44de..fb2a8cd35b964e92c9a84f8730e569caf1df493d 100644 (file)
@@ -59,16 +59,13 @@ extern THREAD_LOCAL ProfileStats file_connector_perfstats;
 FileConnectorModule::FileConnectorModule() :
     Module(FILE_CONNECTOR_NAME, FILE_CONNECTOR_HELP, file_connector_params, true)
 {
-    config = nullptr;
     config_set = new FileConnectorConfig::FileConnectorConfigSet;
 }
 
 FileConnectorModule::~FileConnectorModule()
 {
-    if ( config )
-        delete config;
-    if ( config_set )
-        delete config_set;
+    delete config;
+    delete config_set;
 }
 
 ProfileStats* FileConnectorModule::get_profile() const
index d58417d560e78f1ea7837387c794f2653160c801..020a563aabf1fe1536d1d9827c071d6e7f143152 100644 (file)
@@ -50,7 +50,7 @@ public:
 
 private:
     FileConnectorConfig::FileConnectorConfigSet* config_set;
-    FileConnectorConfig* config;
+    FileConnectorConfig* config = nullptr;
 };
 
 #endif
index 5c6e48d8680ae32ee31ea86e06d847c5b90ffc1b..930008a8536a8f540f8fc5b513b4855ca7522f1b 100644 (file)
@@ -59,12 +59,10 @@ const char* get_instance_file(std::string& file, const char* name)
 
 FileConnectorModule::FileConnectorModule() :
     Module("FC", "FC Help", nullptr)
-{ }
+{ config_set = nullptr; }
 
 FileConnectorConfig::FileConnectorConfigSet* FileConnectorModule::get_and_clear_config()
-{
-    return new FileConnectorConfig::FileConnectorConfigSet;
-}
+{ return new FileConnectorConfig::FileConnectorConfigSet; }
 
 FileConnectorModule::~FileConnectorModule() = default;
 
index 360cbd213dd2914bb7812e11dc9aa2992e75e884..ff6797d2086f9dc796fe67bc9b13151a7d80688c 100644 (file)
@@ -69,11 +69,11 @@ TcpConnectorCommon::~TcpConnectorCommon()
 
 enum ReadDataOutcome { SUCCESS = 0, TRUNCATED, ERROR, CLOSED, PARTIAL, AGAIN };
 
-static ReadDataOutcome read_data(int sockfd, uint8_t *data, uint16_t length, ssize_t *read_offset)
+static ReadDataOutcome read_data(int sockfd, uint8_t *data, uint16_t length, ssize_tread_offset)
 {
     ssize_t bytes_read, offset;
 
-    offset = *read_offset;
+    offset = read_offset;
     bytes_read = recv(sockfd, data + offset, length - offset, 0);
     if (bytes_read == 0)
     {
@@ -91,7 +91,7 @@ static ReadDataOutcome read_data(int sockfd, uint8_t *data, uint16_t length, ssi
         }
         return ERROR;
     }
-    *read_offset = offset + bytes_read;
+    read_offset = offset + bytes_read;
     if ((offset + bytes_read) < length)
         return PARTIAL;
 
@@ -103,10 +103,10 @@ static ReadDataOutcome read_message_data(int sockfd, uint16_t length, uint8_t *d
     if ( length > 0 )
     {
         ReadDataOutcome rval;
-        ssize_t offset = 0;
         do
         {
-            rval = read_data(sockfd, data, length, &offset);
+            ssize_t offset = 0;
+            rval = read_data(sockfd, data, length, offset);
         } while (rval == PARTIAL || rval == AGAIN);
 
         if (rval != SUCCESS)
index 3782a12cd9cc96f960b68e08d4b44ab4c2866f7c..882b4c801e219edc8dcd50d838ed4f799931afc7 100644 (file)
@@ -37,7 +37,8 @@
 class __attribute__((__packed__)) TcpConnectorMsgHdr
 {
 public:
-    TcpConnectorMsgHdr() = default;
+    TcpConnectorMsgHdr() : version(0), connector_msg_length(0)
+    { }
     TcpConnectorMsgHdr(uint32_t length)
     { version = TCP_FORMAT_VERSION; connector_msg_length = length; }
 
index d7d3adc1001b4d2c2feedd3f29bfa0f9f534e71c..bc009c9fb0c82c8d4805e062c4dfd4372b7eaede 100644 (file)
@@ -59,7 +59,6 @@ extern THREAD_LOCAL ProfileStats tcp_connector_perfstats;
 TcpConnectorModule::TcpConnectorModule() :
     Module(TCP_CONNECTOR_NAME, TCP_CONNECTOR_HELP, tcp_connector_params, true)
 {
-    config = nullptr;
     config_set = new TcpConnectorConfig::TcpConnectorConfigSet;
 }
 
index b308503a4e93a395d22916245e88e99d9a38fe00..2d7f34bf0691fd61842fe2e10f60d5b8fe40851d 100644 (file)
@@ -50,7 +50,7 @@ public:
 
 private:
     TcpConnectorConfig::TcpConnectorConfigSet* config_set;
-    TcpConnectorConfig* config;
+    TcpConnectorConfig* config = nullptr;
 };
 
 #endif
index 202c8ba2ac26e2b8119c2d88feaf0db60ecba968..7006016979a039b25b33461155edaad718f8fa58 100644 (file)
@@ -170,7 +170,7 @@ static void set_normal_status()
 
 TcpConnectorModule::TcpConnectorModule() :
     Module("TCPC", "TCPC Help", nullptr)
-{ }
+{ config_set = nullptr; }
 
 TcpConnectorConfig::TcpConnectorConfigSet* TcpConnectorModule::get_and_clear_config()
 {
index 5b6a29894163c14f575b575c56688afef41c4002..69b093f7fc58ac0e879cf47980eac376a8c58fbe 100644 (file)
@@ -396,7 +396,7 @@ static inline fd_status_t Handle_State_DICT_OBJECT(fd_session_t* SessionPtr, uin
            and handles other diversion such as nested Dict objects.
            If the /Filter token doesn't exist then we don't fill the
            Filter_Spec_Buf[].  If in skip mode, no need to look for token. */
-        char Filter_Tok[] = TOK_DICT_FILT;
+        static const char Filter_Tok[] = TOK_DICT_FILT;
 
         if ( (p->Sub_State == P_DICT_ACTIVE) && c == Filter_Tok[p->Elem_Index++] )
         {
index 594478f360081339f229a4c9193c644df5a9859c..5c7bed68f4be95ced0913200f44de4d7259e1c01 100644 (file)
@@ -86,12 +86,12 @@ void OleFile :: walk_directory_list()
             name_buf = new uint8_t[32];
 
             // The filename is UTF16 encoded and will be of the size 64 bytes.
-            dir_list->utf_state = new snort::UtfDecodeSession();
+            snort::UtfDecodeSession utf_state;
             if (!header->get_byte_order())
-                dir_list->utf_state->set_decode_utf_state_charset(CHARSET_UTF16LE);
+                utf_state.set_decode_utf_state_charset(CHARSET_UTF16LE);
             else
-                dir_list->utf_state->set_decode_utf_state_charset(CHARSET_UTF16BE);
-            dir_list->utf_state->decode_utf(buf, OLE_MAX_FILENAME_LEN_UTF16, name_buf,
+                utf_state.set_decode_utf_state_charset(CHARSET_UTF16BE);
+            utf_state.decode_utf(buf, OLE_MAX_FILENAME_LEN_UTF16, name_buf,
                 OLE_MAX_FILENAME_ASCII, &bytes_copied);
 
             node->set_name(name_buf);
@@ -129,7 +129,6 @@ void OleFile :: walk_directory_list()
             else
                 dir_list->oleentry.insert({ file_name, node });
             count++;
-            delete dir_list->utf_state;
         }
         // Reading the next sector of current_sector by referring the FAT list array.
         // A negative number suggests the end of directory entry array and there are
@@ -561,14 +560,6 @@ int32_t cli_readn(const uint8_t*& fd, uint32_t& data_len, void* buff, int32_t co
 void OleFile :: decompression(const uint8_t* data, uint32_t& data_len, uint8_t*& local_vba_buffer,
     uint32_t& vba_buffer_offset)
 {
-    int16_t header;
-    bool flagCompressed;
-    unsigned char buffer[VBA_COMPRESSION_WINDOW]={ };
-    uint16_t token;
-    unsigned int pos, shift, mask, distance;
-    uint8_t flag;
-    bool clean;
-
     if (!data)
         return;
 
@@ -579,11 +570,11 @@ void OleFile :: decompression(const uint8_t* data, uint32_t& data_len, uint8_t*&
         return;
     }
 
-    header = LETOHS_UNALIGNED(data + 1);
+    int16_t data_header = LETOHS_UNALIGNED(data + 1);
 
-    flagCompressed = header & 0x8000;
+    bool flagCompressed = 0 != (data_header & 0x8000);
 
-    if (((header >> 12) & 0x07) != 0b011)
+    if (((data_header >> 12) & 0x07) != 0b011)
     {
         VBA_DEBUG(vba_data_trace, DEFAULT_TRACE_OPTION_ID, TRACE_INFO_LEVEL, CURRENT_PACKET,
             "Invalid Chunk signature.\n");
@@ -592,35 +583,35 @@ void OleFile :: decompression(const uint8_t* data, uint32_t& data_len, uint8_t*&
     data += 3;
     data_len -= 3;
 
+    unsigned char buffer[VBA_COMPRESSION_WINDOW]={ };
     if (flagCompressed == 0)
     {
         memcpy(&buffer, data, data_len);
         return;
     }
 
-    pos = 0;
-    clean = 1;
+    unsigned pos = 0;
+    bool clean = true;
     uint32_t size = data_len;
+    uint8_t flag;
     while (cli_readn(data, size, &flag, 1))
     {
-        for (mask = 1; mask < 0x100; mask <<= 1)
+        for (unsigned mask = 1; mask < 0x100; mask <<= 1)
         {
             unsigned int winpos = pos % VBA_COMPRESSION_WINDOW;
             if (flag & mask)
             {
-                uint16_t len;
-                uint32_t srcpos;
-
+                uint16_t token;
                 if (!cli_readn(data, size, &token, 2))
                     return;
 
-                shift    = 12 - (winpos > 0x10) - (winpos > 0x20) - (winpos > 0x40) - (winpos >
+                unsigned shift = 12 - (winpos > 0x10) - (winpos > 0x20) - (winpos > 0x40) - (winpos >
                     0x80) - (winpos > 0x100) - (winpos > 0x200) - (winpos > 0x400) - (winpos >
                     0x800);
-                len      = (uint16_t)((token & ((1 << shift) - 1)) + 3);
-                distance = token >> shift;
+                uint16_t len = (uint16_t)((token & ((1 << shift) - 1)) + 3);
+                unsigned distance = token >> shift;
 
-                srcpos = pos - distance - 1;
+                uint32_t srcpos = pos - distance - 1;
                 if ((((srcpos + len) % VBA_COMPRESSION_WINDOW) < winpos)and
                         ((winpos + len) < VBA_COMPRESSION_WINDOW) and
                         (((srcpos % VBA_COMPRESSION_WINDOW) + len) < VBA_COMPRESSION_WINDOW) and
@@ -642,17 +633,18 @@ void OleFile :: decompression(const uint8_t* data, uint32_t& data_len, uint8_t*&
             {
                 if ((pos != 0)and (winpos == 0) and clean)
                 {
+                    uint16_t token;
                     if (cli_readn(data, size, &token, 2) != 2)
                     {
                         return;
                     }
-                    clean = 0;
+                    clean = false;
                     break;
                 }
                 if (cli_readn(data, size,  &buffer[winpos], 1) == 1)
                     pos++;
             }
-            clean = 1;
+            clean = true;
         }
     }
 
index d1584221ac5272ab1c57dab0d2468bbf51bb021d..898c4b4fdfb9e626cfcdf22c5cf7a436206dbc96 100644 (file)
@@ -198,7 +198,7 @@ class DirectoryList
 {
 public:
     std::unordered_map<char*, FileProperty*> oleentry;
-    snort::UtfDecodeSession* utf_state;
+    snort::UtfDecodeSession* utf_state = nullptr;
 
     bool is_file_exists(char* name);
     FileProperty* get_file_node(char* name);
@@ -214,16 +214,12 @@ public:
         return mini_stream_sector;
     }
 
-    DirectoryList()
-    {
-        utf_state = nullptr;
-        mini_stream_sector = -1;
-    }
+    DirectoryList() = default;
 
     ~DirectoryList();
 
 private:
-    int32_t mini_stream_sector;
+    int32_t mini_stream_sector = -1;
 };
 
 class OleFile
index c2a301639df3fbf4ab6343b94956fb1b4677fb62..ddc27be44e716b61de61c1b9ed2267085db0c086 100644 (file)
@@ -47,7 +47,6 @@ LiteralSearch* LiteralSearch::instantiate(LiteralSearch::Handle*, const uint8_t*
 void UtfDecodeSession::set_decode_utf_state_charset(CharsetCode, CharsetSrc) { }
 bool UtfDecodeSession::decode_utf(unsigned char const*, unsigned int, unsigned char*, unsigned int,
     int*) { return true; }
-UtfDecodeSession::UtfDecodeSession() { }
 Packet* DetectionEngine::get_current_packet() { return nullptr; }
 void trace_vprintf(char const*, unsigned char, char const*, snort::Packet const*, char const*, va_list) { }
 uint8_t TraceApi::get_constraints_generation() { return 0; }
index c4eb3478b3a7f905bf3ed7b2361e12600d268b56..0da22a7e0c3a7d00999b22bbfe419cd00cf7ff06 100644 (file)
@@ -50,7 +50,7 @@ ContextSwitcher::~ContextSwitcher()
 {
     abort();
 
-    for ( auto* p : contexts )
+    for ( const auto* p : contexts )
         delete p;
 }
 
index 6ceb197f4b9e43a4afc78c8190384f2c9bd05cb8..891b6c25fdd374aa03971230ecf6b5ab25002339 100644 (file)
@@ -245,16 +245,16 @@ bool Continuation::State::eval(snort::Packet& p)
     for (uint8_t i = 0; i < NUM_IPS_OPTIONS_VARS; ++i)
         snort::SetVarValueByIndex(byte_extract_vars[i], i);
 
-    const detection_option_tree_node_t* node = root.children[0];
+    const detection_option_tree_node_t* root_node = root.children[0];
 
     if (opt_parent)
     {
-        for (int i = 0; i < node->num_children; ++i)
-            result += detection_option_node_evaluate(node->children[i], data, cursor);
+        for (int i = 0; i < root_node->num_children; ++i)
+            result += detection_option_node_evaluate(root_node->children[i], data, cursor);
     }
     else
     {
-        result = detection_option_node_evaluate(node, data, cursor);
+        result = detection_option_node_evaluate(root_node, data, cursor);
     }
 
     clear_trace_cursor_info();
index 4f5c3b9164248a30fe85f68f920c15bd7cc07e30..25f7e3341d4788969b5d26240820d2d2378f9dc5 100644 (file)
@@ -102,6 +102,8 @@ void DetectionEngine::thread_term()
     delete offloader;
 }
 
+// Not sure why cppcheck doesn't think context is initialized
+// cppcheck-suppress uninitMemberVar
 DetectionEngine::DetectionEngine()
 {
     context = Analyzer::get_switcher()->interrupt();
@@ -459,6 +461,7 @@ bool DetectionEngine::offload(Packet* p)
 
     if ( p->flow ? p->flow->context_chain.front() : sw->non_flow_chain.front() )
     {
+        // cppcheck-suppress unreadVariable
         Profile profile(mpsePerfStats);
         p->context->searches.search_sync();
         sw->suspend();
@@ -508,6 +511,7 @@ void DetectionEngine::onload(Flow* flow)
 
 void DetectionEngine::onload()
 {
+    // cppcheck-suppress unreadVariable
     Profile profile(mpsePerfStats);
     Packet* p;
 
@@ -519,7 +523,7 @@ void DetectionEngine::onload()
 
         p->clear_offloaded();
 
-        IpsContextChain& chain = p->flow ? p->flow->context_chain :
+        const IpsContextChain& chain = p->flow ? p->flow->context_chain :
             Analyzer::get_switcher()->non_flow_chain;
 
         resume_ready_suspends(chain);
@@ -577,7 +581,9 @@ void DetectionEngine::wait_for_context()
         do
         {
             onload();
-        } while ( !sw->idle_count() );
+        }
+        // cppcheck-suppress knownConditionTrueFalse
+        while ( !sw->idle_count() );
     }
 }
 
@@ -744,6 +750,7 @@ static int log_events(void* event, void* user)
 */
 int DetectionEngine::log_events(Packet* p)
 {
+    // cppcheck-suppress unreadVariable
     Profile profile(eventqPerfStats);
     SF_EVENTQ* pq = p->context->equeue;
     sfeventq_action(pq, ::log_events, (void*)p);
index eaa8053190e13464414b2f28cf4416e2c0309f6d..9b8ebdabeca49ab65414c33f7deb9820bb894b11 100644 (file)
@@ -405,7 +405,6 @@ int detection_option_node_evaluate(
     bool continue_loop = true;
     int loop_count = 0;
 
-    char tmp_noalert_flag = 0;
     int result = 0;
     uint32_t tmp_byte_extract_vars[NUM_IPS_OPTIONS_VARS];
     IpsOption* buf_selector = eval_data.buf_selector;
@@ -425,14 +424,10 @@ int detection_option_node_evaluate(
             {
                 const auto& sig_info = node->otn->sigInfo;
 
-                for ( const auto& svc : sig_info.services )
-                {
-                    if ( snort_protocol_id == svc.snort_protocol_id )
-                    {
-                        check_ports = 0;
-                        break;  // out of for
-                    }
-                }
+                if ( std::any_of(sig_info.services.cbegin(), sig_info.services.cend(),
+                    [snort_protocol_id] (const SignatureServiceInfo& svc)
+                    { return snort_protocol_id == svc.snort_protocol_id; }) )
+                    check_ports = 0;
 
                 if ( !sig_info.services.empty() and check_ports )
                 {
@@ -541,7 +536,7 @@ int detection_option_node_evaluate(
                 Continuation::postpone<true>(cursor, *node, eval_data);
             return result;
         }
-        else if ( rval == (int)IpsOption::FAILED_BIT )
+        if ( rval == (int)IpsOption::FAILED_BIT )
         {
             debug_log(detection_trace, TRACE_RULE_EVAL, p, "failed bit\n");
             eval_data.flowbit_failed = 1;
@@ -550,11 +545,12 @@ int detection_option_node_evaluate(
             state.last_check.result = result;
             return 0;
         }
-        else if ( rval == (int)IpsOption::NO_ALERT )
+
+        // Cache the current flowbit_noalert flag, and set it
+        // so nodes below this don't alert.
+        char tmp_noalert_flag = eval_data.flowbit_noalert;
+        if ( rval == (int)IpsOption::NO_ALERT )
         {
-            // Cache the current flowbit_noalert flag, and set it
-            // so nodes below this don't alert.
-            tmp_noalert_flag = eval_data.flowbit_noalert;
             eval_data.flowbit_noalert = 1;
             debug_log(detection_trace, TRACE_RULE_EVAL, p, "flowbit no alert\n");
         }
@@ -579,6 +575,8 @@ int detection_option_node_evaluate(
 
         if ( PacketLatency::fastpath() )
         {
+            // Reset the flowbit_noalert flag in eval data
+            eval_data.flowbit_noalert = tmp_noalert_flag;
             profile.stop(result != (int)IpsOption::NO_MATCH);
             state.last_check.result = result;
             return result;
@@ -695,11 +693,8 @@ int detection_option_node_evaluate(
             }
         }
 
-        if ( rval == (int)IpsOption::NO_ALERT )
-        {
-            // Reset the flowbit_noalert flag in eval data
-            eval_data.flowbit_noalert = tmp_noalert_flag;
-        }
+        // Reset the flowbit_noalert flag in eval data
+        eval_data.flowbit_noalert = tmp_noalert_flag;
 
         if ( continue_loop && rval == (int)IpsOption::MATCH && node->relative_children )
         {
index 5eee82735f04017c8036aba6507786d773ea2cc9..f7c182eda0410738b8f92f0e7bce8c91d3fe1a50 100644 (file)
@@ -62,7 +62,7 @@ bool FastPatternConfig::set_search_method(const char* method)
     return true;
 }
 
-const char* FastPatternConfig::get_search_method()
+const char* FastPatternConfig::get_search_method() const
 {
     if ( !search_api )
         return nullptr;
index 5073afb97420994cd81e6a5f588f496b93c46431..3f7cc0dcd9195d1c3fb78107981adf2b23c3aaa3 100644 (file)
@@ -125,7 +125,7 @@ public:
     { return rule_db_dir; }
 
     bool set_search_method(const char*);
-    const char* get_search_method();
+    const char* get_search_method() const;
 
     bool set_offload_search_method(const char*);
     void set_max_pattern_len(unsigned);
index 7cbccf92c6cdaa9dd11e4a1d81a03bf1b9a57b10..94af06a679f94828d4992484bca4b1729fc2af19 100644 (file)
@@ -145,8 +145,8 @@ static bool new_sig(int num_children, detection_option_tree_node_t** nodes, OptT
             continue;
 
         OptTreeNode* cotn = (OptTreeNode*)child->option_data;
-        SigInfo& csi = cotn->sigInfo;
-        SigInfo& osi = otn->sigInfo;
+        const SigInfo& csi = cotn->sigInfo;
+        const SigInfo& osi = otn->sigInfo;
 
         if ( csi.gid == osi.gid and csi.sid == osi.sid and csi.rev == osi.rev )
             return false;
@@ -1360,9 +1360,9 @@ static void fpPrintServiceRuleMaps(SnortConfig* sc)
     fpPrintServiceRuleMapTable(sc->srmmTable->to_cli, "to client");
 }
 
-static void fp_print_service_rules(SnortConfig* sc, GHash* cli, GHash* srv)
+static void fp_print_service_rules(SnortConfig* sc, GHash* to_srv, GHash* to_cli)
 {
-    if ( !cli->get_count() and !srv->get_count() )
+    if ( !to_srv->get_count() and !to_cli->get_count() )
         return;
 
     LogLabel("service rule counts          to-srv  to-cli");
@@ -1372,8 +1372,8 @@ static void fp_print_service_rules(SnortConfig* sc, GHash* cli, GHash* srv)
 
     while ( const char* svc = sc->proto_ref->get_name_sorted(idx++) )
     {
-        SF_LIST* clist = (SF_LIST*)cli->find(svc);
-        SF_LIST* slist = (SF_LIST*)srv->find(svc);
+        SF_LIST* clist = (SF_LIST*)to_srv->find(svc);
+        SF_LIST* slist = (SF_LIST*)to_cli->find(svc);
 
         if ( !clist and !slist )
             continue;
index b7585165429ae743395547744a772dd279208e7a..d0c0df7ee33bab838441a5b2aa083571a252a762 100644 (file)
@@ -717,11 +717,15 @@ static inline int fpFinalSelectEvent(OtnxMatchData* omd, Packet* p)
 class MpseStash
 {
 public:
+    // for some reason cppcheck does not understand that all members are used in MpseStash::process
     struct MatchData
     {
+        // cppcheck-suppress unusedStructMember
         void* user;
         void* tree;
+        // cppcheck-suppress unusedStructMember
         void* list;
+        // cppcheck-suppress unusedStructMember
         int index;
     };
 
@@ -781,6 +785,7 @@ bool MpseStash::push(void* user, void* tree, int index, void* context, void* lis
 
     if ( !checker and qmax == queue.size() and is_packet_thread() )
     {
+        // cppcheck-suppress unreadVariable
         Profile rule_profile(rulePerfStats);
         process((IpsContext*)context, queue);
     }
@@ -1282,6 +1287,7 @@ static void fpEvalPacket(Packet* p, FPTask task)
 
 void fp_partial(Packet* p)
 {
+    // cppcheck-suppress unreadVariable
     Profile mpse_profile(mpsePerfStats);
     IpsContext* c = p->context;
     init_match_info(c);
@@ -1299,10 +1305,12 @@ void fp_complete(Packet* p, bool search)
 
     if ( search )
     {
+        // cppcheck-suppress unreadVariable
         Profile mpse_profile(mpsePerfStats);
         c->searches.search_sync();
     }
     {
+        // cppcheck-suppress unreadVariable
         Profile rule_profile(rulePerfStats);
 
         if (p->flow && p->flow->ips_cont)
@@ -1335,10 +1343,12 @@ static void fp_immediate(Packet* p)
     IpsContext* c = p->context;
     MpseStash* stash = c->stash;
     {
+        // cppcheck-suppress unreadVariable
         Profile mpse_profile(mpsePerfStats);
         c->searches.search_sync();
     }
     {
+        // cppcheck-suppress unreadVariable
         Profile rule_profile(rulePerfStats);
         stash->process(c);
         c->searches.items.clear();
@@ -1349,11 +1359,13 @@ static void fp_immediate(MpseGroup* mpg, Packet* p, const uint8_t* buf, unsigned
 {
     MpseStash* stash = p->context->stash;
     {
+        // cppcheck-suppress unreadVariable
         Profile mpse_profile(mpsePerfStats);
         int start_state = 0;
         mpg->get_normal_mpse()->search(buf, len, rule_tree_queue, p->context, &start_state);
     }
     {
+        // cppcheck-suppress unreadVariable
         Profile rule_profile(rulePerfStats);
         stash->process(p->context);
     }
@@ -1382,6 +1394,7 @@ static inline int fp_do_actions(OtnxMatchData* omd, Packet* p)
 
 void fp_eval_service_group(Packet* p, SnortProtocolId snort_protocol_id)
 {
+    // cppcheck-suppress unreadVariable
     Profile mpse_profile(mpsePerfStats);
     RuleGroup* svc = p->context->conf->sopgTable->get_port_group(true, snort_protocol_id);
 
@@ -1404,6 +1417,7 @@ void fp_eval_service_group(Packet* p, SnortProtocolId snort_protocol_id)
     MpseStash* stash = c->stash;
     c->searches.search_sync();
     {
+        // cppcheck-suppress unreadVariable
         Profile rule_profile(rulePerfStats);
         stash->process(c);
 
index 066f310c83067ffabcaee4bdb23c59fad87d7766..13f5c6861b78a3444aa5ef666805ec64c8bce1f5 100644 (file)
@@ -743,42 +743,42 @@ TEST_CASE("pmd_no_options", "[PatternMatchData]")
 {
     PatternMatchData pmd = { };
     set_pmd(pmd, 0x0, "foo");
-    CHECK(pmd.can_be_fp());
+    CHECK(true == pmd.can_be_fp());
 }
 
 TEST_CASE("pmd_negated", "[PatternMatchData]")
 {
     PatternMatchData pmd = { };
     set_pmd(pmd, 0x1, "foo");
-    CHECK(!pmd.can_be_fp());
+    CHECK(false == pmd.can_be_fp());
 }
 
 TEST_CASE("pmd_no_case", "[PatternMatchData]")
 {
     PatternMatchData pmd = { };
     set_pmd(pmd, 0x2, "foo");
-    CHECK(pmd.can_be_fp());
+    CHECK(true == pmd.can_be_fp());
 }
 
 TEST_CASE("pmd_relative", "[PatternMatchData]")
 {
     PatternMatchData pmd = { };
     set_pmd(pmd, 0x4, "foo");
-    CHECK(pmd.can_be_fp());
+    CHECK(true == pmd.can_be_fp());
 }
 
 TEST_CASE("pmd_negated_no_case", "[PatternMatchData]")
 {
     PatternMatchData pmd = { };
     set_pmd(pmd, 0x3, "foo");
-    CHECK(pmd.can_be_fp());
+    CHECK(true == pmd.can_be_fp());
 }
 
 TEST_CASE("pmd_negated_relative", "[PatternMatchData]")
 {
     PatternMatchData pmd = { };
     set_pmd(pmd, 0x5, "foo");
-    CHECK(!pmd.can_be_fp());
+    CHECK(false == pmd.can_be_fp());
 }
 
 TEST_CASE("pmd_negated_no_case_offset", "[PatternMatchData]")
@@ -786,7 +786,7 @@ TEST_CASE("pmd_negated_no_case_offset", "[PatternMatchData]")
     PatternMatchData pmd = { };
     set_pmd(pmd, 0x1, "foo");
     pmd.offset = 3;
-    CHECK(!pmd.can_be_fp());
+    CHECK(false == pmd.can_be_fp());
 }
 
 TEST_CASE("pmd_negated_no_case_depth", "[PatternMatchData]")
@@ -794,7 +794,7 @@ TEST_CASE("pmd_negated_no_case_depth", "[PatternMatchData]")
     PatternMatchData pmd = { };
     set_pmd(pmd, 0x3, "foo");
     pmd.depth = 1;
-    CHECK(!pmd.can_be_fp());
+    CHECK(false == pmd.can_be_fp());
 }
 
 TEST_CASE("fp_simple", "[FastPatternSelect]")
@@ -803,10 +803,10 @@ TEST_CASE("fp_simple", "[FastPatternSelect]")
     PatternMatchData pmd = { };
     set_pmd(pmd, 0x0, "foo");
     FpSelector left(CAT_SET_RAW, nullptr, &pmd);
-    CHECK(left.is_better_than(test, false, RULE_WO_DIR));
+    CHECK(true == left.is_better_than(test, false, RULE_WO_DIR));
 
     test.size = 1;
-    CHECK(left.is_better_than(test, false, RULE_WO_DIR));
+    CHECK(true == left.is_better_than(test, false, RULE_WO_DIR));
 }
 
 TEST_CASE("fp_negated", "[FastPatternSelect]")
@@ -819,8 +819,8 @@ TEST_CASE("fp_negated", "[FastPatternSelect]")
     set_pmd(p1, 0x1, "foo");
     FpSelector s1(CAT_SET_RAW, nullptr, &p1);
 
-    CHECK(s0.is_better_than(s1, false, RULE_WO_DIR));
-    CHECK(!s1.is_better_than(s0, false, RULE_WO_DIR));
+    CHECK(true == s0.is_better_than(s1, false, RULE_WO_DIR));
+    CHECK(false == s1.is_better_than(s0, false, RULE_WO_DIR));
 }
 
 TEST_CASE("fp_cat1", "[FastPatternSelect]")
@@ -833,7 +833,7 @@ TEST_CASE("fp_cat1", "[FastPatternSelect]")
     set_pmd(p1, 0x0, "short");
     FpSelector s1(CAT_SET_FAST_PATTERN, nullptr, &p1);
 
-    CHECK(s0.is_better_than(s1, true, RULE_WO_DIR));
+    CHECK(true == s0.is_better_than(s1, true, RULE_WO_DIR));
 }
 
 TEST_CASE("fp_cat2", "[FastPatternSelect]")
@@ -846,8 +846,8 @@ TEST_CASE("fp_cat2", "[FastPatternSelect]")
     set_pmd(p1, 0x0, "foo");
     FpSelector s1(CAT_SET_FAST_PATTERN, nullptr, &p1);
 
-    CHECK(!s0.is_better_than(s1, false, RULE_WO_DIR));
-    CHECK(!s1.is_better_than(s0, false, RULE_WO_DIR));
+    CHECK(false == s0.is_better_than(s1, false, RULE_WO_DIR));
+    CHECK(false == s1.is_better_than(s0, false, RULE_WO_DIR));
 }
 
 TEST_CASE("fp_cat3", "[FastPatternSelect]")
@@ -860,7 +860,7 @@ TEST_CASE("fp_cat3", "[FastPatternSelect]")
     set_pmd(p1, 0x0, "foo");
     FpSelector s1(CAT_SET_FAST_PATTERN, nullptr, &p1);
 
-    CHECK(!s0.is_better_than(s1, true, RULE_WO_DIR));
+    CHECK(false == s0.is_better_than(s1, true, RULE_WO_DIR));
 }
 
 TEST_CASE("fp_size", "[FastPatternSelect]")
@@ -873,7 +873,7 @@ TEST_CASE("fp_size", "[FastPatternSelect]")
     set_pmd(p1, 0x0, "short");
     FpSelector s1(CAT_SET_FAST_PATTERN, nullptr, &p1);
 
-    CHECK(s0.is_better_than(s1, false, RULE_WO_DIR));
+    CHECK(true == s0.is_better_than(s1, false, RULE_WO_DIR));
 }
 
 TEST_CASE("fp_pkt_key_port", "[FastPatternSelect]")
@@ -886,7 +886,7 @@ TEST_CASE("fp_pkt_key_port", "[FastPatternSelect]")
     set_pmd(p1, 0x0, "longer");
     FpSelector s1(CAT_SET_FAST_PATTERN, nullptr, &p1);
 
-    CHECK(!s0.is_better_than(s1, false, RULE_WO_DIR));
+    CHECK(false == s0.is_better_than(s1, false, RULE_WO_DIR));
 }
 
 TEST_CASE("fp_pkt_key_port_user", "[FastPatternSelect]")
@@ -899,7 +899,7 @@ TEST_CASE("fp_pkt_key_port_user", "[FastPatternSelect]")
     set_pmd(p1, 0x0, "longer");
     FpSelector s1(CAT_SET_FAST_PATTERN, nullptr, &p1);
 
-    CHECK(s0.is_better_than(s1, false, RULE_WO_DIR));
+    CHECK(true == s0.is_better_than(s1, false, RULE_WO_DIR));
 }
 
 TEST_CASE("fp_pkt_key_port_user_user", "[FastPatternSelect]")
@@ -912,7 +912,7 @@ TEST_CASE("fp_pkt_key_port_user_user", "[FastPatternSelect]")
     set_pmd(p1, 0x10, "short");
     FpSelector s1(CAT_SET_FAST_PATTERN, nullptr, &p1);
 
-    CHECK(!s0.is_better_than(s1, false, RULE_WO_DIR));
+    CHECK(false == s0.is_better_than(s1, false, RULE_WO_DIR));
 }
 
 TEST_CASE("fp_pkt_key_port_user_user2", "[FastPatternSelect]")
@@ -925,7 +925,7 @@ TEST_CASE("fp_pkt_key_port_user_user2", "[FastPatternSelect]")
     set_pmd(p1, 0x10, "short");
     FpSelector s1(CAT_SET_FAST_PATTERN, nullptr, &p1);
 
-    CHECK(!s0.is_better_than(s1, false, RULE_WO_DIR));
+    CHECK(false == s0.is_better_than(s1, false, RULE_WO_DIR));
 }
 
 TEST_CASE("fp_pkt_key_srvc_1", "[FastPatternSelect]")
@@ -938,7 +938,7 @@ TEST_CASE("fp_pkt_key_srvc_1", "[FastPatternSelect]")
     set_pmd(p1, 0x0, "longer");
     FpSelector s1(CAT_SET_FAST_PATTERN, nullptr, &p1);
 
-    CHECK(s1.is_better_than(s0, true, RULE_WO_DIR));
+    CHECK(true == s1.is_better_than(s0, true, RULE_WO_DIR));
 }
 
 TEST_CASE("fp_pkt_key_srvc_2", "[FastPatternSelect]")
@@ -951,7 +951,7 @@ TEST_CASE("fp_pkt_key_srvc_2", "[FastPatternSelect]")
     set_pmd(p1, 0x0, "short");
     FpSelector s1(CAT_SET_FAST_PATTERN, nullptr, &p1);
 
-    CHECK(s0.is_better_than(s1, true, RULE_WO_DIR));
+    CHECK(true == s0.is_better_than(s1, true, RULE_WO_DIR));
 }
 
 TEST_CASE("fp_pkt_key_srvc_rsp", "[FastPatternSelect]")
@@ -964,8 +964,8 @@ TEST_CASE("fp_pkt_key_srvc_rsp", "[FastPatternSelect]")
     set_pmd(p1, 0x0, "longer");
     FpSelector s1(CAT_SET_FAST_PATTERN, nullptr, &p1);
 
-    CHECK(!s0.is_better_than(s1, true, RULE_FROM_SERVER));
-    CHECK(s1.is_better_than(s0, true, RULE_FROM_SERVER));
+    CHECK(false == s0.is_better_than(s1, true, RULE_FROM_SERVER));
+    CHECK(true == s1.is_better_than(s0, true, RULE_FROM_SERVER));
 }
 #endif
 
index 5b08e70631d372ebe5d449d279d5a663ebe9f7fb..a2b026880007b43ee88bf8544f3833cf9e90004e 100644 (file)
@@ -144,12 +144,12 @@ inline bool PatternMatchData::can_be_fp() const
 
 inline bool PatternMatchData::has_alpha() const
 {
-    unsigned offset = fp_offset ? fp_offset : 0;
-    unsigned length = fp_length ? fp_length : pattern_size;
+    unsigned tmp_offset = static_cast<unsigned>(fp_offset);
+    unsigned tmp_length = fp_length ? fp_length : pattern_size;
 
-    for ( unsigned idx = 0; idx < length; ++idx )
+    for ( unsigned idx = 0; idx < tmp_length; ++idx )
     {
-        if ( isalpha(pattern_buf[offset + idx]) )
+        if ( isalpha(pattern_buf[tmp_offset + idx]) )
             return true;
     }
     return false;
index 75b002fe7beb8a96cd4c24b4404d8cc25013c1e9..7db47be84de64ce38b7f21656dcb201b079cc6cc 100644 (file)
@@ -90,7 +90,7 @@ RegexOffload::~RegexOffload()
 {
     assert(busy.empty());
 
-    for ( auto* req : idle )
+    for ( const auto* req : idle )
         delete req;
 }
 
@@ -99,14 +99,9 @@ void RegexOffload::stop()
     assert(busy.empty());
 }
 
-bool RegexOffload::on_hold(Flow* f) const
+bool RegexOffload::on_hold(const Flow* f) const
 {
-    for ( auto* req : busy )
-    {
-        if ( req->packet->flow == f )
-            return true;
-    }
-    return false;
+    return std::any_of(busy.cbegin(), busy.cend(), [f](const RegexRequest* req){ return req->packet->flow == f; });
 }
 
 //--------------------------------------------------------------------------
@@ -117,6 +112,7 @@ MpseRegexOffload::MpseRegexOffload(unsigned max) : RegexOffload(max) { }
 
 void MpseRegexOffload::put(Packet* p)
 {
+    // cppcheck-suppress unreadVariable
     Profile profile(mpsePerfStats);
 
     assert(p);
@@ -137,6 +133,7 @@ void MpseRegexOffload::put(Packet* p)
 
 bool MpseRegexOffload::get(Packet*& p)
 {
+    // cppcheck-suppress unreadVariable
     Profile profile(mpsePerfStats);
     assert(!busy.empty());
 
@@ -211,6 +208,7 @@ void ThreadRegexOffload::stop()
 
 void ThreadRegexOffload::put(Packet* p)
 {
+    // cppcheck-suppress unreadVariable
     Profile profile(mpsePerfStats);
 
     assert(p);
index 8f2533ca331e1704292111ad919250127e19e4db..ced7e3ba5ff50b810ac1bc724d6b7379527d9f07 100644 (file)
@@ -57,7 +57,7 @@ public:
     unsigned count() const
     { return busy.size(); }
 
-    bool on_hold(snort::Flow*) const;
+    bool on_hold(const snort::Flow*) const;
 
 protected:
     RegexOffload(unsigned max);
index 85d70f76231823e86dffe0d1f7c1a57a567d26f1..2a95148cf52ff57195378d45ca7b206ed52e76bf 100644 (file)
@@ -228,7 +228,7 @@ sopg_table_t::sopg_table_t(unsigned n)
 
 RuleGroup* sopg_table_t::get_port_group(bool c2s, SnortProtocolId snort_protocol_id)
 {
-    RuleGroupVector& v = c2s ? to_srv : to_cli;
+    const RuleGroupVector& v = c2s ? to_srv : to_cli;
 
     if ( snort_protocol_id >= v.size() )
         return nullptr;
index 4c5ddb3bade1b1ffa7d0b010b749ab8a3d1ea078..c50a3243d2b0baba0568569fb212a5b2518ea008 100644 (file)
@@ -81,11 +81,11 @@ static const ReferenceSystem* reference_system_lookup(SnortConfig* sc, const std
 void add_reference(
     SnortConfig* sc, OptTreeNode* otn, const std::string& system, const std::string& id)
 {
+    assert(sc and otn and !system.empty() and !id.empty());
+
     if ( !sc->alert_refs() )
         return;
 
-    assert(sc and otn and !system.empty() and !id.empty());
-
     const ReferenceSystem* sys = reference_system_lookup(sc, system);
 
     if ( !sys )
@@ -331,7 +331,7 @@ static void dump_services(JsonStream& json, const SigInfo& si)
     json.close_array();
 }
 
-static void dump_bits(JsonStream& json, const char* key, std::vector<std::string>& bits)
+static void dump_bits(JsonStream& json, const char* key, const std::vector<std::string>& bits)
 {
     if ( bits.empty() )
         return;
index 23b4d8ed20fea5a719300d2073d49edffab9856c..7cae0c89f1d8f0149f24f8148c9df261f2f2237b 100644 (file)
@@ -183,7 +183,7 @@ static THREAD_LOCAL TagSessionCache* ssn_tag_cache = nullptr;
  *
  * @returns number of bytes needed
  */
-static inline unsigned int memory_per_node(XHash* hash)
+static inline unsigned int memory_per_node(const XHash* hash)
 {
     if ( hash == ssn_tag_cache )
         return sizeof(tTagFlowKey) + sizeof(HashNode) + sizeof(TagNode);
index 3c1fd917de50edd54e2fb929967a16692fce7c77..17f2b3969b8501bb4ce05a40dca7fbb822428ddf 100644 (file)
@@ -203,7 +203,7 @@ struct OptTreeNode
     SnortProtocolId snort_protocol_id = 0;    // Added for integrity checks during rule parsing.
     unsigned short proto_node_num = 0;
     uint16_t longestPatternLen = 0;
-    IpsPolicy::Enable enable;
+    IpsPolicy::Enable enable = IpsPolicy::Enable::DISABLED;
     Flag flags = 0;
 
     enum SectionDir { SECT_TO_SRV = 0, SECT_TO_CLIENT, SECT_DIR__MAX };
index 06090f055a4dc45e3c57dafbabc62a873076a663..df88ddf0bf53bcb23779a9818571663618477239 100644 (file)
@@ -64,12 +64,9 @@ TreeConfigNode::TreeConfigNode(BaseConfigNode* parent_node,
 
 BaseConfigNode* TreeConfigNode::get_node(const std::string& name)
 {
-    for ( auto node : children )
-    {
-        if ( node->get_name() == name )
-            return node;
-    }
-    return nullptr;
+    auto it = std::find_if(children.cbegin(), children.cend(),
+        [name](BaseConfigNode* node){ return node->get_name() == name; });
+    return it != children.cend() ? *it : nullptr;
 }
 
 ValueConfigNode::ValueConfigNode(BaseConfigNode* parent_node, const Value& val,
@@ -311,7 +308,7 @@ TEST_CASE("value_config_node", "[ValueConfigNode]")
     SECTION("get_value")
     {
         CHECK(value_node_str->get_value()->get_origin_string() == "test_str");
-        CHECK(value_node_bool->get_value()->get_bool() == true);
+        CHECK(true == value_node_bool->get_value()->get_bool());
         CHECK(value_node_multi->get_value()->get_origin_string() == "test2 test3");
         CHECK(value_node_custom_name->get_value()->get_origin_string() == "test_str_custom");
     }
@@ -337,7 +334,7 @@ TEST_CASE("value_config_node", "[ValueConfigNode]")
     SECTION("get_value_after_update")
     {
         CHECK(value_node_str->get_value()->get_origin_string() == "new_value");
-        CHECK(value_node_bool->get_value()->get_bool() == false);
+        CHECK(false == value_node_bool->get_value()->get_bool());
         CHECK(value_node_multi->get_value()->get_origin_string() == "test1 test2 test3");
         CHECK(value_node_custom_name->get_value()->get_origin_string() == "new_custom_value");
     }
index e76a591a5eef8037ef45e5fe88bcf5302a847cfb..30fc602597016c851ac5314fdff7e78a745cd4f6 100644 (file)
@@ -496,7 +496,8 @@ bool FileFlows::set_file_name(const uint8_t* fname, uint32_t name_size, uint64_t
     uint64_t multi_file_processing_id, const uint8_t* url, uint32_t url_size)
 {
     FileContext* context;
-    if (file_id) {
+    if (file_id)
+    {
         bool is_new_context = false;
         context = get_file_context(file_id, false, is_new_context, multi_file_processing_id);
     }
index f72f6adb231695c926e456647d4e437b1263c773..a3c9bf952be16496eb17b186f7ac46339dc4d393 100644 (file)
@@ -133,6 +133,8 @@ void FileInfo::copy(const FileInfo& other)
     pending_expire_time = other.pending_expire_time;
     // only one copy of file capture
     file_capture = nullptr;
+    policy_id = 0;
+    user_file_data = nullptr;
 }
 
 FileInfo::FileInfo(const FileInfo& other)
@@ -461,6 +463,7 @@ void FileContext::check_policy(Flow* flow, FileDirection dir, FilePolicyBase* po
 bool FileContext::process(Packet* p, const uint8_t* file_data, int data_size,
     FilePosition position, FilePolicyBase* policy)
 {
+    // cppcheck-suppress unreadVariable
     Profile profile(file_perf_stats);
     Flow* flow = p->flow;
 
@@ -624,12 +627,10 @@ bool FileContext::process(Packet* p, const uint8_t* file_data, int data_size,
  * 3) file magics are exhausted in depth
  *
  */
-void FileContext::find_file_type_from_ips(Packet* pkt, const uint8_t* file_data, int
-    data_size,
+void FileContext::find_file_type_from_ips(Packet* pkt, const uint8_t* file_data, int data_size,
     FilePosition position)
 {
     bool depth_exhausted = false;
-    bool set_file_context = false;
 
     if ((int64_t)processed_bytes + data_size >= config->file_type_depth)
     {
@@ -649,17 +650,20 @@ void FileContext::find_file_type_from_ips(Packet* pkt, const uint8_t* file_data,
     p->packet_flags |= PKT_ALLOW_MULTIPLE_DETECT;
     p->proto_bits |= PROTO_BIT__PDU;
 
+    bool set_file_context = false;
     FileFlows* files = FileFlows::get_file_flows(p->flow, false);
-    if (files and (!files->get_current_file_context() or files->get_current_file_context() != this))
+    if (files)
     {
-        files->set_current_file_context(this);
-        set_file_context =true;
+        FileContext* context = files->get_current_file_context();
+        if (!context or context != this)
+        {
+            files->set_current_file_context(this);
+            set_file_context = true;
+        }
     }
     fp_eval_service_group(p, conf->snort_protocol_id);
     if (set_file_context)
-    {
         files->set_current_file_context(nullptr);
-    }
     /* Check whether file transfer is done or type depth is reached */
     if ((position == SNORT_FILE_END) || (position == SNORT_FILE_FULL) || depth_exhausted)
         finalize_file_type();
index 21c731041440ee17423648b4feefb541c32a565b..94e6d31510d53e4b68e042ce898aa4a39b896e54 100644 (file)
@@ -81,8 +81,8 @@ static void dl_tterm()
 class LogHandler : public DataHandler
 {
 public:
-    LogHandler(const FileLogConfig& conf) : DataHandler(s_name)
-    { config = conf; }
+    LogHandler(const FileLogConfig& conf) : DataHandler(s_name), config(conf)
+    { }
 
     void handle(DataEvent&, Flow*) override;
 
@@ -202,7 +202,8 @@ void LogHandler::handle(DataEvent&, Flow* f)
 class FileLog : public Inspector
 {
 public:
-    FileLog(const FileLogConfig& conf) { config = conf; }
+    FileLog(const FileLogConfig& conf) : config(conf)
+    { }
 
     void show(const SnortConfig*) const override;
     void eval(Packet*) override { }
index 39758fc8f58a93580b3e24c18d40fe5c107d82b9..4de8f376fb7928ad7420f13f5b531f86e1c97d70 100644 (file)
@@ -57,6 +57,7 @@ void DetectionFilterConfigFree(DetectionFilterConfig* config)
 
 int detection_filter_test(void* pv, const SfIp* sip, const SfIp* dip, long curtime)
 {
+    // cppcheck-suppress unreadVariable
     RuleProfile profile(detectionFilterPerfStats);
 
     if (pv == nullptr)
index 24005c9b8ef62bfd2b60deec81c118077e328dee..57a389b526136bdea477a7beb51994b4b3875518 100644 (file)
@@ -375,6 +375,7 @@ static int SFRF_TestObject(
     switch (op)
     {
     case SFRF_COUNT_INCREMENT:
+        // cppcheck-suppress knownConditionTrueFalse
         if ( (dynNode->count+1) != 0 )
         {
             dynNode->count++;
index cfc4759d1b95014c7957ecb46630e3248c8a10f1..d8d641384596b821f0d68f1472c33c0547af9bfe 100644 (file)
@@ -63,7 +63,7 @@ public:
     DeferredTrust() = default;
     ~DeferredTrust() = default;
     SO_PUBLIC void set_deferred_trust(unsigned module_id, bool on);
-    bool is_active()
+    bool is_active() const
     { return TRUST_DEFER_ON == deferred_trust || TRUST_DEFER_DEFERRING == deferred_trust; }
     bool try_trust()
     {
@@ -71,7 +71,7 @@ public:
             deferred_trust = TRUST_DEFER_DEFERRING;
         return TRUST_DEFER_DEFERRING != deferred_trust;
     }
-    bool is_deferred()
+    bool is_deferred() const
     { return TRUST_DEFER_DEFERRING == deferred_trust; }
     void clear()
     {
index 3dedd660614c81908129b63f0ced58cf2d9c109e..769314ca227516d02d4b35776f1ad616a1d48a2b 100644 (file)
@@ -159,8 +159,8 @@ ExpectNode* ExpectCache::find_node_by_packet(Packet* p, FlowKey &key)
     PktType type = p->type();
     IpProtocol ip_proto = p->get_ip_proto_next();
 
-    bool reversed_key = key.init(p->context->conf, type, ip_proto, dstIP, p->ptrs.dp,
-        srcIP, p->ptrs.sp, vlanId, mplsId, *p->pkth);
+    bool reversed_key = key.init(p->context->conf, type, ip_proto, srcIP, p->ptrs.sp, dstIP, p->ptrs.dp,
+        vlanId, mplsId, *p->pkth);
 
     /*
         Lookup order:
@@ -182,17 +182,17 @@ ExpectNode* ExpectCache::find_node_by_packet(Packet* p, FlowKey &key)
         uint16_t port2;
 
         if (reversed_key)
-        {
-            port1 = key.port_l;
-            port2 = 0;
-            key.port_l = 0;
-        }
-        else
         {
             port1 = 0;
             port2 = key.port_h;
             key.port_h = 0;
         }
+        else
+        {
+            port1 = key.port_l;
+            port2 = 0;
+            key.port_l = 0;
+        }
         node = static_cast<ExpectNode*> ( hash_table->get_user_data(&key) );
         if (!node)
         {
@@ -335,8 +335,14 @@ int ExpectCache::add_flow(const Packet *ctrlPkt, PktType type, IpProtocol ip_pro
     uint32_t mplsId = (ctrlPkt->proto_bits & PROTO_BIT__MPLS) ? ctrlPkt->ptrs.mplsHdr.label : 0;
     FlowKey key;
 
-    bool reversed_key = key.init(ctrlPkt->context->conf, type, ip_proto, cliIP, cliPort,
-        srvIP, srvPort, vlanId, mplsId, *ctrlPkt->pkth);
+    // This code assumes that the expected session is in the opposite direction of the control session
+    // when groups are significant
+    bool reversed_key = (ctrlPkt->pkth->flags & DAQ_PKT_FLAG_SIGNIFICANT_GROUPS)
+        ? key.init(ctrlPkt->context->conf, type, ip_proto, cliIP, cliPort,
+            srvIP, srvPort, vlanId, mplsId, ctrlPkt->pkth->address_space_id, ctrlPkt->pkth->egress_group,
+            ctrlPkt->pkth->ingress_group)
+        : key.init(ctrlPkt->context->conf, type, ip_proto, cliIP, cliPort,
+            srvIP, srvPort, vlanId, mplsId, *ctrlPkt->pkth);
 
     bool new_node = false;
     ExpectNode* node = static_cast<ExpectNode*> ( hash_table->get_user_data(&key) );
index 35e1d54a1c71b968ba3a5aa5d4dba50f1f168b16..58aa8b90227b8383c24773471e72cfc513491ce0 100644 (file)
@@ -423,7 +423,7 @@ void Flow::set_expire(const Packet* p, uint64_t timeout)
     expire_time = (uint64_t)p->pkth->ts.tv_sec + timeout;
 }
 
-bool Flow::expired(const Packet* p)
+bool Flow::expired(const Packet* p) const
 {
     if ( !expire_time )
         return false;
@@ -505,7 +505,7 @@ Layer Flow::get_mpls_layer_per_dir(bool client)
         return mpls_server;
 }
 
-bool Flow::is_pdu_inorder(uint8_t dir)
+bool Flow::is_pdu_inorder(uint8_t dir) const
 {
     return ( (session != nullptr) && session->is_sequenced(dir)
             && (session->missing_in_reassembled(dir) == SSN_MISSING_NONE)
index 3db187b97546161321d4c0c6012e7d87592b9b5e..7c9c5f4808d79fe2f4335616bfff34c148dcfdc3 100644 (file)
@@ -208,14 +208,14 @@ public:
     void set_client_initiate(Packet*);
     void set_direction(Packet*);
     void set_expire(const Packet*, uint64_t timeout);
-    bool expired(const Packet*);
+    bool expired(const Packet*) const;
     void set_ttl(Packet*, bool client);
     void set_mpls_layer_per_dir(Packet*);
     Layer get_mpls_layer_per_dir(bool);
     void swap_roles();
     void set_service(Packet*, const char* new_service);
-    bool get_attr(const std::string& key, int32_t& val);
-    bool get_attr(const std::string& key, std::string& val);
+    bool get_attr(const std::string& key, int32_t& val) const;
+    bool get_attr(const std::string& key, std::string& val) const;
     void set_attr(const std::string& key, const int32_t& val);
     void set_attr(const std::string& key, const std::string& val);
     // Use this API when the publisher of the attribute allocated memory for it and can give up its
@@ -227,7 +227,7 @@ public:
     }
 
     template<typename T>
-    bool get_attr(const std::string& key, T& val)
+    bool get_attr(const std::string& key, T& val) const
     {
         assert(stash);
         return stash->get(key, val);
@@ -258,7 +258,7 @@ public:
     void set_to_client_detection(bool enable);
     void set_to_server_detection(bool enable);
 
-    int get_ignore_direction()
+    int get_ignore_direction() const
     { return ssn_state.ignore_direction; }
 
     int set_ignore_direction(char ignore_direction)
@@ -267,20 +267,20 @@ public:
         return ssn_state.ignore_direction;
     }
 
-    bool two_way_traffic()
+    bool two_way_traffic() const
     { return (ssn_state.session_flags & SSNFLAG_SEEN_BOTH) == SSNFLAG_SEEN_BOTH; }
 
-    bool is_pdu_inorder(uint8_t dir);
+    bool is_pdu_inorder(uint8_t dir) const;
 
     bool is_direction_aborted(bool from_client) const;
 
     void set_proxied()
     { ssn_state.session_flags |= SSNFLAG_PROXIED; }
 
-    bool is_proxied()
+    bool is_proxied() const
     { return (ssn_state.session_flags & SSNFLAG_PROXIED) != 0; }
 
-    bool is_stream()
+    bool is_stream() const
     { return pkt_type == PktType::TCP or pkt_type == PktType::USER; }
 
     void block()
@@ -386,13 +386,13 @@ public:
     void set_hard_expiration()
     { ssn_state.session_flags |= SSNFLAG_HARD_EXPIRATION; }
 
-    bool is_hard_expiration()
+    bool is_hard_expiration() const
     { return (ssn_state.session_flags & SSNFLAG_HARD_EXPIRATION) != 0; }
 
     void set_deferred_trust(unsigned module_id, bool on)
     { deferred_trust.set_deferred_trust(module_id, on); }
 
-    bool cannot_trust()
+    bool cannot_trust() const
     { return deferred_trust.is_active(); }
 
     bool try_trust()
@@ -408,7 +408,7 @@ public:
 
     void trust();
 
-    bool trust_is_deferred()
+    bool trust_is_deferred() const
     { return deferred_trust.is_deferred(); }
  
     void set_idle_timeout(unsigned timeout)
index 318188d57052a994b54b188c85769b743bae0d37..ef0e87a31f9213c222545bf77f2c64bd124b8701 100644 (file)
@@ -163,9 +163,9 @@ bool FlowStash::store(const SfIp& ip, const SnortConfig* sc)
 
     if ( sc->max_aux_ip > 0 )
     {
-        for ( const auto& aip : aux_ip_fifo )
-            if ( aip == ip )
-                return false;
+        if ( std::any_of(aux_ip_fifo.cbegin(), aux_ip_fifo.cend(),
+            [ip](const snort::SfIp& aip){ return aip == ip; }) )
+            return false;
 
         if ( aux_ip_fifo.size() == (unsigned)sc->max_aux_ip )
             aux_ip_fifo.pop_back();
index 0af23ce0612c646fa56150999ec018de90ad75d9..0992d94820e0f162ff578f1f8666ecc979a46d23 100644 (file)
@@ -121,10 +121,6 @@ static inline bool is_ip6_key(const FlowKey* key)
 
 FlowHAState::FlowHAState()
 {
-    state = INITIAL_STATE;
-    state |= (NEW | NEW_SESSION);
-    pending = NONE_PENDING;
-
     // Set the initial update time to now+min_session_lifetime
     packet_gettimeofday(&next_update);
     timeradd(&next_update, &min_session_lifetime, &next_update);
@@ -200,13 +196,11 @@ void FlowHAState::reset()
     init_next_update();
 }
 
-FlowHAClient::FlowHAClient(uint8_t length, bool session_client)
+FlowHAClient::FlowHAClient(uint8_t length, bool session_client) : max_length(length)
 {
     if (!ha)
         return;
 
-    max_length = length;
-
     if (session_client)
     {
         index = SESSION_HA_CLIENT_INDEX;
index 92d02173e9816d48484463d0e032219feeaa6343..38d36b0ebd202bd04a76248cfb3cc7897d6bfeac 100644 (file)
@@ -83,8 +83,8 @@ private:
     static struct timeval min_sync_interval;
 
     struct timeval next_update;
-    uint16_t pending;
-    uint8_t state;
+    uint16_t pending = NONE_PENDING;
+    uint8_t state = NEW | NEW_SESSION;
 };
 
 // Describe the message being produced or consumed.
@@ -130,8 +130,8 @@ public:
     virtual bool is_update_required(snort::Flow*) { return false; }
     virtual uint8_t get_message_size(Flow&) { return max_length; }
 
-    FlowHAClientHandle handle;  // Actual handle for the instance
-    uint8_t index;
+    FlowHAClientHandle handle = 0;  // Actual handle for the instance
+    uint8_t index = 0;
     uint8_t max_length;
 
 protected:
index 6af10e5221dd6e6811303e92ef1b1486e3d44ce3..38d204d41215162b1a9d6039140f896286e6a96a 100644 (file)
@@ -70,13 +70,13 @@ public:
 
     virtual void set_extra_data(snort::Packet*, uint32_t /*flag*/) { }
 
-    virtual bool is_sequenced(uint8_t /*dir*/) { return true; }
-    virtual bool are_packets_missing(uint8_t /*dir*/) { return false; }
-    virtual bool are_client_segments_queued() { return false; }
+    virtual bool is_sequenced(uint8_t /*dir*/) const { return true; }
+    virtual bool are_packets_missing(uint8_t /*dir*/) const { return false; }
+    virtual bool are_client_segments_queued() const { return false; }
 
     virtual void disable_reassembly(snort::Flow*) { }
-    virtual uint8_t get_reassembly_direction() { return SSN_DIR_NONE; }
-    virtual uint8_t missing_in_reassembled(uint8_t /*dir*/) { return SSN_MISSING_NONE; }
+    virtual uint8_t get_reassembly_direction() const { return SSN_DIR_NONE; }
+    virtual uint8_t missing_in_reassembled(uint8_t /*dir*/) const { return SSN_MISSING_NONE; }
 
     virtual bool set_packet_action_to_hold(snort::Packet*) { return false; }
 
index 79dbbc9e7eb12c125a150754bad3191378f2ae06..b62e453f084662840c2669d8e33bc25f7ada4ff6 100644 (file)
@@ -1,4 +1,6 @@
-add_cpputest( ha_test )
+add_cpputest( ha_test
+    SOURCES flow_stubs.h
+)
 
 add_cpputest( deferred_trust_test
     SOURCES ../deferred_trust.cc
@@ -11,6 +13,7 @@ add_cpputest( flow_stash_test
 
 add_cpputest( flow_control_test
     SOURCES ../flow_control.cc
+            flow_stubs.h
 )
 
 add_cpputest( flow_cache_test
@@ -18,6 +21,7 @@ add_cpputest( flow_cache_test
         ../flow_cache.cc
         ../flow_control.cc
         ../flow_key.cc
+        flow_stubs.h
         ../../hash/hash_key_operations.cc
         ../../hash/hash_lru_cache.cc
         ../../hash/primetable.cc
@@ -31,4 +35,5 @@ add_cpputest( flow_test
     SOURCES
         ../flow.cc
         ../flow_data.cc
+        flow_stubs.h
 )
index 6ab9d5bb97691bee9e4a19c779c9481016328daf..164bfb4c9f183b104ecd626802ddd7c3b55d0c7a 100644 (file)
 #include "flow/flow_cache.h"
 #include "flow/ha.h"
 #include "flow/session.h"
-#include "main/policy.h"
-#include "main/snort_config.h"
-#include "main/thread_config.h"
+#include "main/analyzer.h"
 #include "managers/inspector_manager.h"
 #include "packet_io/active.h"
-#include "packet_tracer/packet_tracer.h"
 #include "protocols/icmp4.h"
-#include "protocols/packet.h"
 #include "protocols/tcp.h"
 #include "protocols/udp.h"
 #include "protocols/vlan.h"
-#include "stream/stream.h"
 #include "utils/util.h"
 #include "trace/trace_api.h"
 
 #include <CppUTest/CommandLineTestRunner.h>
 #include <CppUTest/TestHarness.h>
 
+#include "flow_stubs.h"
+
 using namespace snort;
 
 THREAD_LOCAL bool Active::s_suspend = false;
 THREAD_LOCAL Active::ActiveSuspendReason Active::s_suspend_reason = Active::ASP_NONE;
 
-THREAD_LOCAL PacketTracer* snort::s_pkt_trace = nullptr;
 THREAD_LOCAL const Trace* stream_trace = nullptr;
 
 void Active::drop_packet(snort::Packet const*, bool) { }
-PacketTracer::~PacketTracer() = default;
-void PacketTracer::log(const char*, ...) { }
-void PacketTracer::open_file() { }
-void PacketTracer::dump_to_daq(Packet*) { }
-void PacketTracer::reset(bool) { }
-void PacketTracer::pause() { }
-void PacketTracer::unpause() { }
+Analyzer* Analyzer::get_local_analyzer() { return nullptr; }
+void Analyzer::resume(unsigned long) { }
 void Active::set_drop_reason(char const*) { }
-Packet::Packet(bool) { }
-Packet::~Packet() = default;
-uint32_t Packet::get_flow_geneve_vni() const { return 0; }
-Flow::~Flow() = default;
-DetectionEngine::DetectionEngine() = default;
+DetectionEngine::DetectionEngine() { context = nullptr; }
 ExpectCache::~ExpectCache() = default;
 DetectionEngine::~DetectionEngine() = default;
-void Flow::init(PktType) { }
-void Flow::flush(bool) { }
-void Flow::reset(bool) { }
-void Flow::free_flow_data() { }
-void DataBus::publish(unsigned, unsigned, DataEvent&, Flow*) { }
-void DataBus::publish(unsigned, unsigned, const uint8_t*, unsigned, Flow*) { }
-void DataBus::publish(unsigned, unsigned, Packet*, Flow*) { }
 const SnortConfig* SnortConfig::get_conf() { return nullptr; }
-void Flow::set_client_initiate(Packet*) { }
-void Flow::set_direction(Packet*) { }
-void set_network_policy(unsigned) { }
-void set_inspection_policy(unsigned) { }
-void set_ips_policy(const snort::SnortConfig*, unsigned) { }
-void Flow::set_mpls_layer_per_dir(Packet*) { }
 void DetectionEngine::disable_all(Packet*) { }
-void Stream::drop_traffic(const Packet*, char) { }
-bool Stream::blocked_flow(Packet*) { return true; }
 ExpectCache::ExpectCache(uint32_t) { }
 bool ExpectCache::check(Packet*, Flow*) { return true; }
 bool ExpectCache::is_expected(Packet*) { return true; }
@@ -103,29 +75,24 @@ void ThreadConfig::preemptive_kick() {}
 
 namespace snort
 {
-NetworkPolicy* get_network_policy() { return nullptr; }
-InspectionPolicy* get_inspection_policy() { return nullptr; }
-IpsPolicy* get_ips_policy() { return nullptr; }
-unsigned SnortConfig::get_thread_reload_id() { return 0; }
+Flow::~Flow() = default;
+void Flow::init(PktType) { }
+void Flow::flush(bool) { }
+void Flow::reset(bool) { }
+void Flow::free_flow_data() { }
+void Flow::set_client_initiate(Packet*) { }
+void Flow::set_direction(Packet*) { }
+void Flow::set_mpls_layer_per_dir(Packet*) { }
 
-namespace layer
-{
-const vlan::VlanTagHdr* get_vlan_layer(const Packet* const) { return nullptr; }
-}
 time_t packet_time() { return 0; }
-}
+void packet_gettimeofday(struct timeval* tv) { *tv = {}; }
 
-namespace snort
-{
 namespace ip
 {
 uint32_t IpApi::id() const { return 0; }
 }
 }
 
-void Stream::stop_inspection(Flow*, Packet*, char, int32_t, int) { }
-
-
 int ExpectCache::add_flow(const Packet*, PktType, IpProtocol, const SfIp*, uint16_t,
     const SfIp*, uint16_t, char, FlowData*, SnortProtocolId, bool, bool, bool, bool)
 {
index cf83b6b8ffcb97a4b280834ccfafd8aa48ba9116..d4803eb08a1ce8475db8a421fbb1a10f2ec1dbf9 100644 (file)
 #include <CppUTest/CommandLineTestRunner.h>
 #include <CppUTest/TestHarness.h>
 
+#include "flow_stubs.h"
+
 using namespace snort;
 
 THREAD_LOCAL bool Active::s_suspend = false;
 THREAD_LOCAL Active::ActiveSuspendReason Active::s_suspend_reason = Active::ASP_NONE;
 
-THREAD_LOCAL PacketTracer* snort::s_pkt_trace = nullptr;
-
 void Active::drop_packet(snort::Packet const*, bool) { }
-PacketTracer::~PacketTracer() = default;
-void PacketTracer::log(const char*, ...) { }
-void PacketTracer::open_file() { }
-void PacketTracer::dump_to_daq(Packet*) { }
-void PacketTracer::reset(bool) { }
-void PacketTracer::pause() { }
-void PacketTracer::unpause() { }
 void Active::set_drop_reason(char const*) { }
-Packet::Packet(bool) { }
-Packet::~Packet() = default;
-uint32_t Packet::get_flow_geneve_vni() const { return 0; }
 FlowCache::FlowCache(const FlowCacheConfig& cfg) : config(cfg) { }
 FlowCache::~FlowCache() = default;
 Flow::~Flow() = default;
-DetectionEngine::DetectionEngine() = default;
+DetectionEngine::DetectionEngine() { context = nullptr; }
 DetectionEngine::~DetectionEngine() = default;
 ExpectCache::~ExpectCache() = default;
 unsigned FlowCache::purge() { return 1; }
@@ -85,38 +75,17 @@ size_t FlowCache::uni_flows_size() const { return 0; }
 size_t FlowCache::uni_ip_flows_size() const { return 0; }
 size_t FlowCache::flows_size() const { return 0; }
 void Flow::init(PktType) { }
-void DataBus::publish(unsigned, unsigned, DataEvent&, Flow*) { }
-void DataBus::publish(unsigned, unsigned, const uint8_t*, unsigned, Flow*) { }
-void DataBus::publish(unsigned, unsigned, Packet*, Flow*) { }
 const SnortConfig* SnortConfig::get_conf() { return nullptr; }
 void FlowCache::unlink_uni(Flow*) { }
 void Flow::set_client_initiate(Packet*) { }
 void Flow::set_direction(Packet*) { }
-void set_network_policy(unsigned) { }
-void set_inspection_policy(unsigned) { }
-void set_ips_policy(const snort::SnortConfig*, unsigned) { }
 void Flow::set_mpls_layer_per_dir(Packet*) { }
 void DetectionEngine::disable_all(Packet*) { }
-void Stream::drop_traffic(const Packet*, char) { }
-bool Stream::blocked_flow(Packet*) { return true; }
 ExpectCache::ExpectCache(uint32_t) { }
 bool ExpectCache::check(Packet*, Flow*) { return true; }
 bool ExpectCache::is_expected(Packet*) { return true; }
 Flow* HighAvailabilityManager::import(Packet&, FlowKey&) { return nullptr; }
 
-namespace snort
-{
-NetworkPolicy* get_network_policy() { return nullptr; }
-InspectionPolicy* get_inspection_policy() { return nullptr; }
-IpsPolicy* get_ips_policy() { return nullptr; }
-unsigned SnortConfig::get_thread_reload_id() { return 0; }
-
-namespace layer
-{
-const vlan::VlanTagHdr* get_vlan_layer(const Packet* const) { return nullptr; }
-}
-}
-
 namespace snort
 {
 namespace ip
@@ -167,8 +136,6 @@ bool FlowKey::init(
     return true;
 }
 
-void Stream::stop_inspection(Flow*, Packet*, char, int32_t, int) { }
-
 int ExpectCache::add_flow(const Packet*,
     PktType, IpProtocol,
     const SfIp*, uint16_t,
index a7d5fde73454ac2371daedcf51646a0114139b4c..c410f32abe0a38aa0367ff579d1311f06887afb2 100644 (file)
@@ -79,7 +79,11 @@ static SnortConfig snort_conf;
 
 namespace snort
 {
-SnortConfig::SnortConfig(const SnortConfig* const, const char*) { }
+SnortConfig::SnortConfig(const SnortConfig* const, const char*)
+{
+    daq_config = nullptr;
+    thread_config = nullptr;
+}
 SnortConfig::~SnortConfig() = default;
 const SnortConfig* SnortConfig::get_conf() { return &snort_conf; }
 
diff --git a/src/flow/test/flow_stubs.h b/src/flow/test/flow_stubs.h
new file mode 100644 (file)
index 0000000..9a752fc
--- /dev/null
@@ -0,0 +1,84 @@
+//--------------------------------------------------------------------------
+// Copyright (C) 2020-2023 Cisco and/or its affiliates. All rights reserved.
+//
+// This program is free software; you can redistribute it and/or modify it
+// under the terms of the GNU General Public License Version 2 as published
+// by the Free Software Foundation.  You may not use, modify or distribute
+// this program under any other version of the GNU General Public License.
+//
+// This program is distributed in the hope that it will be useful, but
+// WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+// General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License along
+// with this program; if not, write to the Free Software Foundation, Inc.,
+// 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+//--------------------------------------------------------------------------
+// flow_stubs.h author Ron Dempster <rdempste@cisco.com>
+
+#ifndef FLOW_STUBS_H
+#define FLOW_STUBS_H
+
+#include "framework/data_bus.h"
+#include "log/messages.h"
+#include "main/policy.h"
+#include "main/snort_config.h"
+#include "main/thread_config.h"
+#include "packet_tracer/packet_tracer.h"
+#include "protocols/layer.h"
+#include "protocols/packet.h"
+#include "stream/stream.h"
+
+namespace snort
+{
+void ErrorMessage(const char*,...) { }
+void LogMessage(const char*,...) { }
+
+void DataBus::publish(unsigned, unsigned, DataEvent&, Flow*) { }
+void DataBus::publish(unsigned, unsigned, const uint8_t*, unsigned, Flow*) { }
+void DataBus::publish(unsigned, unsigned, Packet*, Flow*) { }
+
+Packet::Packet(bool)
+{
+    memset((char*) this , 0, sizeof(*this));
+    ip_proto_next = IpProtocol::PROTO_NOT_SET;
+    packet_flags = PKT_FROM_CLIENT;
+}
+Packet::~Packet()  = default;
+uint32_t Packet::get_flow_geneve_vni() const { return 0; }
+
+THREAD_LOCAL PacketTracer* s_pkt_trace = nullptr;
+
+PacketTracer::~PacketTracer() = default;
+void PacketTracer::log(const char*, ...) { }
+void PacketTracer::open_file() { }
+void PacketTracer::dump_to_daq(Packet*) { }
+void PacketTracer::reset(bool) { }
+void PacketTracer::pause() { }
+void PacketTracer::unpause() { }
+
+namespace layer
+{
+const vlan::VlanTagHdr* get_vlan_layer(const Packet* const) { return nullptr; }
+}
+
+void Stream::drop_traffic(const Packet*, char) { }
+bool Stream::blocked_flow(Packet*) { return true; }
+void Stream::stop_inspection(Flow*, Packet*, char, int32_t, int) { }
+
+NetworkPolicy* get_network_policy() { return nullptr; }
+InspectionPolicy* get_inspection_policy() { return nullptr; }
+IpsPolicy* get_ips_policy() { return nullptr; }
+void set_network_policy(NetworkPolicy*) { }
+void set_inspection_policy(InspectionPolicy*) { }
+void set_ips_policy(IpsPolicy*) { }
+unsigned SnortConfig::get_thread_reload_id() { return 0; }
+}
+
+void set_network_policy(unsigned) { }
+void set_inspection_policy(unsigned) { }
+void set_ips_policy(const snort::SnortConfig*, unsigned) { }
+void select_default_policy(const _daq_pkt_hdr&, const snort::SnortConfig*) { }
+
+#endif
index 72502b06589739aaa434ad38e9bfbb2b9dc41c5d..3a7889e310b00e3c53e94cd6d8fc6751560c0f24 100644 (file)
 #include <CppUTest/CommandLineTestRunner.h>
 #include <CppUTest/TestHarness.h>
 
-using namespace snort;
+#include "flow_stubs.h"
 
-Packet::Packet(bool) { }
-Packet::~Packet()  = default;
+using namespace snort;
 
 void Inspector::rem_ref() {}
 
@@ -61,28 +60,13 @@ void FlowStash::reset() {}
 
 void DetectionEngine::onload(Flow*) {}
 
-void set_network_policy(unsigned) { }
-void set_inspection_policy(unsigned) { }
-void set_ips_policy(const snort::SnortConfig*, unsigned) { }
-void select_default_policy(const _daq_pkt_hdr&, const SnortConfig*) { }
-namespace snort
-{
-NetworkPolicy* get_network_policy() { return nullptr; }
-InspectionPolicy* get_inspection_policy() { return nullptr; }
-IpsPolicy* get_ips_policy() { return nullptr; }
-void set_network_policy(NetworkPolicy*) { }
-void set_inspection_policy(InspectionPolicy*) { }
-void set_ips_policy(IpsPolicy*) { }
-unsigned SnortConfig::get_thread_reload_id() { return 0; }
-}
-
 Packet* DetectionEngine::set_next_packet(const Packet*, Flow*) { return nullptr; }
 
 ContextSwitcher* Analyzer::get_switcher() { return nullptr; }
 snort::IpsContext* ContextSwitcher::get_context() const { return nullptr; }
 IpsContext* DetectionEngine::get_context() { return nullptr; }
 
-DetectionEngine::DetectionEngine() = default;
+DetectionEngine::DetectionEngine() { context = nullptr; }
 
 DetectionEngine::~DetectionEngine() = default;
 
@@ -93,19 +77,10 @@ uint8_t ip::IpApi::ttl() const { return 0; }
 
 const Layer* layer::get_mpls_layer(const Packet* const) { return nullptr; }
 
-void DataBus::publish(unsigned, unsigned, Packet*, Flow*) {}
-
 const SnortConfig* SnortConfig::get_conf() { return nullptr; }
 
 TEST_GROUP(nondefault_timeout)
 {
-    void setup() override
-    {
-    }
-
-    void teardown() override
-    {
-    }
 };
 
 TEST(nondefault_timeout, hard_expiration)
index e94af042da7941a7a282eae196f323ac4da227bd..55b16b091edbd5c977a9ecfa13c32bae1e3e2b73 100644 (file)
@@ -31,6 +31,8 @@
 
 using namespace snort;
 
+#include "flow_stubs.h"
+
 #define MSG_SIZE 100
 #define TEST_KEY 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47
 
@@ -180,9 +182,6 @@ Flow* Stream::get_flow(const FlowKey* flowkey)
     return (Flow*)mock().getData("flow").getObjectPointer();
 }
 
-Packet::Packet(bool) { }
-Packet::~Packet() = default;
-
 void Stream::delete_flow(const FlowKey* flowkey)
 {
     mock().actualCall("delete_flow");
@@ -193,8 +192,9 @@ void Stream::delete_flow(const FlowKey* flowkey)
 
 namespace snort
 {
-void ErrorMessage(const char*,...) { }
-void LogMessage(const char*,...) { }
+Flow::~Flow() = default;
+void Flow::set_client_initiate(Packet*) { }
+void Flow::set_direction(Packet*) { }
 
 void packet_gettimeofday(struct timeval* tv)
 {
@@ -206,20 +206,13 @@ bool FlowKey::is_equal(const void*, const void*, size_t) { return false; }
 
 int SFDAQInstance::ioctl(DAQ_IoctlCmd, void*, size_t) { return DAQ_SUCCESS; }
 
-Flow::~Flow() { }
-
 FlowStash::~FlowStash() = default;
 
-void Flow::set_client_initiate(Packet*) { }
-void Flow::set_direction(Packet*) { }
-
 SideChannel* SideChannelManager::get_side_channel(SCPort)
 {
     return (SideChannel*)mock().getData("s_side_channel").getObjectPointer();
 }
 
-SideChannel::SideChannel() = default;
-
 Connector::Direction SideChannel::get_direction()
 { return Connector::CONN_DUPLEX; }
 
@@ -395,8 +388,8 @@ TEST_GROUP(high_availability_test)
 {
     Flow s_flow;
     Active active;
-    StreamHAClient* s_ha_client; // cppcheck-suppress variableScope
-    FlowHAClient* s_other_ha_client; // cppcheck-suppress variableScope
+    StreamHAClient* s_ha_client;
+    FlowHAClient* s_other_ha_client;
     uint8_t s_message[MSG_SIZE];
     SCMessage s_sc_message;
     Packet s_pkt;
@@ -427,7 +420,7 @@ TEST_GROUP(high_availability_test)
         s_sc_message = {};
         s_sc_message.content = s_message;
         mock().setDataObject("message_content", "SCMessage", &s_sc_message);
-        s_pkt.active = &active; // cppcheck-suppress unreadVariable
+        s_pkt.active = &active;
 
         memset(&ha_stats, 0, sizeof(ha_stats));
 
@@ -440,8 +433,8 @@ TEST_GROUP(high_availability_test)
 
         HighAvailabilityManager::configure(&hac);
         HighAvailabilityManager::thread_init();
-        s_ha_client = new StreamHAClient; // cppcheck-suppress unreadVariable
-        s_other_ha_client = new OtherHAClient; // cppcheck-suppress unreadVariable
+        s_ha_client = new StreamHAClient;
+        s_other_ha_client = new OtherHAClient;
     }
 
     void teardown() override
index e0af235f1982aa60ea1d8e996f228ace4ea356c0..28e626139f46da76f9eac3f1dded99cd243f19b9 100644 (file)
@@ -74,7 +74,7 @@ public:
     virtual Direction get_connector_direction() = 0;
 
     const std::string connector_name;
-    const ConnectorConfig* config;
+    const ConnectorConfig* config = nullptr;
 
 protected:
     Connector() = default;
index 4ab3a78643f1593c581e6cb455275e0ff7db3522..25cfc96fa9bae283a21b75cc7245160bb61f48aa 100644 (file)
@@ -53,6 +53,7 @@ Cursor::Cursor(const Cursor& rhs)
     if (rhs.data)
     {
         data = new CursorDataVec;
+        data->reserve(rhs.data->size());
 
         for (CursorData*& cd : *rhs.data)
             data->push_back(cd->clone());
@@ -79,10 +80,10 @@ void Cursor::set_data(CursorData* cd)
 
     if (data)
     {
-        unsigned id = cd->get_id();
+        unsigned i = cd->get_id();
         for (CursorData*& old : *data)
         {
-            if (old->get_id() == id)
+            if (old->get_id() == i)
             {
                 delete old;
                 old = cd;
@@ -102,11 +103,11 @@ void Cursor::reset(Packet* p)
 {
     if (p->flow and p->flow->gadget)
     {
-        const DataBuffer& buf = DetectionEngine::get_alt_buffer(p);
+        const DataBuffer& alt_buf = DetectionEngine::get_alt_buffer(p);
 
-        if (buf.len)
+        if (alt_buf.len)
         {
-            set("alt_data", buf.data, buf.len);
+            set("alt_data", alt_buf.data, alt_buf.len);
             return;
         }
     }
index 42cfaade0cd29f23e27d0777fef49d7b49cb6ad6..ac96a64e511be4a8cad1dd00acd72966ef3b15ea 100644 (file)
@@ -44,7 +44,7 @@ public:
     virtual ~CursorData() = default;
     virtual CursorData* clone() = 0;
 
-    unsigned get_id()
+    unsigned get_id() const
     { return id; }
 
     static unsigned create_cursor_data_id()
index f9d0e7ae02e5d7fa33599deb3efe29d065f262d2..d24cd5c19bc077e7d040038bb2537f2a4bb79e16 100644 (file)
@@ -78,7 +78,7 @@ DataBus::DataBus() = default;
 
 DataBus::~DataBus()
 {
-    for ( auto& p : pub_sub )
+    for ( const auto& p : pub_sub )
     {
         for ( auto* h : p )
         {
index ff0b26cbe11da2b29a8438e74edd482f7f3ad985..93c4da995ef801b80cb21f7a4e1ab7c62edb8f4e 100644 (file)
@@ -118,25 +118,30 @@ struct DecodeData
      * these three pointers are each referenced literally
      * dozens if not hundreds of times.  NOTHING else should be added!!
      */
-    const snort::tcp::TCPHdr* tcph;
-    const snort::udp::UDPHdr* udph;
-    const snort::icmp::ICMPHdr* icmph;
+    const snort::tcp::TCPHdr* tcph = nullptr;
+    const snort::udp::UDPHdr* udph = nullptr;
+    const snort::icmp::ICMPHdr* icmph = nullptr;
 
-    uint16_t sp;            /* source port (TCP/UDP) */
-    uint16_t dp;            /* dest port (TCP/UDP) */
+    uint16_t sp = 0;    /* source port (TCP/UDP) */
+    uint16_t dp = 0;    /* dest port (TCP/UDP) */
 
-    uint16_t decode_flags;
-    PktType type;
+    uint16_t decode_flags = 0;
+    PktType type = PktType::NONE;
 
     snort::ip::IpApi ip_api;
-    snort::mpls::MplsHdr mplsHdr;  // FIXIT-L need to zero this?
+    snort::mpls::MplsHdr mplsHdr = {};
 
     inline void reset()
     {
-        memset(this, 0, offsetof(DecodeData, ip_api));
-        ip_api.reset();
+        tcph = nullptr;
+        udph = nullptr;
+        icmph = nullptr;
         sp = 0;
         dp = 0;
+        decode_flags = 0;
+        type = PktType::NONE;
+        ip_api.reset();
+        mplsHdr = {};
     }
 
     inline void set_pkt_type(PktType pkt_type)
index 754312990747c1a7dbfa0cc3f7c7869efee16a92..92229a42eaadd8ec49ab7abab2ebde603e6afd56 100644 (file)
@@ -58,12 +58,8 @@ Inspector::Inspector()
 
 Inspector::~Inspector()
 {
-    unsigned total = 0;
-
     for (unsigned i = 0; i < ThreadConfig::get_instance_max(); ++i )
-        total += ref_count[i];
-
-    assert(!total);
+        assert(0 == ref_count[i]);
 
     delete[] ref_count;
 }
index c6fed3a244ce9b8bf07fa57e1403d0dabbf0abb7..1df0f462a5b1e1cf5763ebfd472945832c3155fa 100644 (file)
@@ -97,18 +97,18 @@ TEST_CASE("IpsOption test", "[ips_option]")
 
     SECTION("hash test")
     {
-        StubIpsOption main_ips("ips_test",
+        StubIpsOption other_main_ips("ips_test",
             option_type_t::RULE_OPTION_TYPE_OTHER);
 
         SECTION("hash test with short string")
         {
             StubIpsOption main_ips_short("ips_test",
                 option_type_t::RULE_OPTION_TYPE_OTHER);
-            REQUIRE((main_ips.hash() == main_ips_short.hash()) == true);
+            REQUIRE((other_main_ips.hash() == main_ips_short.hash()) == true);
 
             StubIpsOption main_ips_short_diff("not_ips_test",
                 option_type_t::RULE_OPTION_TYPE_OTHER);
-            REQUIRE((main_ips.hash() == main_ips_short_diff.hash()) == false);
+            REQUIRE((other_main_ips.hash() == main_ips_short_diff.hash()) == false);
         }
 
         SECTION("hash test with long string")
@@ -134,7 +134,7 @@ TEST_CASE("IpsOption test", "[ips_option]")
                 option_type_t::RULE_OPTION_TYPE_OTHER);
             REQUIRE(main_ips_long_first.hash() == main_ips_long_second.hash());
 
-            REQUIRE(main_ips_long_first.hash() != main_ips.hash());
+            REQUIRE(main_ips_long_first.hash() != other_main_ips.hash());
         }
     }
 }
index 16073b88d5ae9c3bb60e30a78e76d371f9087145..f577d16907023c597cfb1a500ebcb1d0a0d9ba7d 100644 (file)
@@ -70,7 +70,7 @@ protected:
     Logger() = default;
 
 private:
-    const LogApi* api;
+    const LogApi* api = nullptr;
 };
 
 typedef Logger* (* LogNewFunc)(class Module*);
index fbd5f2b767f41fcbecb803a750b72cdd0c74247e..741f24293c9a55a491f4fca92255c0cb16eb872a 100644 (file)
@@ -39,11 +39,8 @@ public:
     std::string chunk;
 
 protected:
-    LuaApi(const std::string& s, const std::string& c)
-    {
-        name = s;
-        chunk = c;
-    }
+    LuaApi(const std::string& s, const std::string& c) : name(s), chunk(c)
+    { }
 };
 
 #endif
index 665720c207e94288bb00185785205fc114e6b3fb..dfb333a25de4f1be61a8d75e2143c11f76112c5a 100644 (file)
@@ -43,12 +43,8 @@ namespace snort
 // base stuff
 //-------------------------------------------------------------------------
 
-Mpse::Mpse(const char* m)
-{
-    method = m;
-    verbose = 0;
-    api = nullptr;
-}
+Mpse::Mpse(const char* m) : method(m)
+{ }
 
 int Mpse::search(
     const unsigned char* T, int n, MpseMatch match,
index 8f9d5f7293645334fb3b21c56d9f9f7851f5297c..2f2915cfcde2aaa8383021d196415d3bc34cb806 100644 (file)
@@ -120,8 +120,8 @@ protected:
 
 private:
     std::string method;
-    int verbose;
-    const MpseApi* api;
+    int verbose = 0;
+    const MpseApi* api = nullptr;
 };
 
 typedef void (* MpseOptFunc)(SnortConfig*);
index 0d4a48c216704e9c40bbba3c9b9d9272977e709f..99f59fae2a0a8a86262547629ce615c7782b8a84 100644 (file)
@@ -171,7 +171,7 @@ TEST_CASE("Packet constraints matching", "[framework]")
         cs.src_ip = sip;
         cs.dst_ip = dip;
 
-        CHECK( match_constraints(cs, sip, dip, sport, dport) );
+        CHECK( true == match_constraints(cs, sip, dip, sport, dport) );
     }
 
     SECTION("backwards")
@@ -188,7 +188,7 @@ TEST_CASE("Packet constraints matching", "[framework]")
         cs.src_ip = sip;
         cs.dst_ip = dip;
 
-        CHECK( !match_constraints(cs, dip, sip, dport, sport) );
+        CHECK( false == match_constraints(cs, dip, sip, dport, sport) );
     }
 
     SECTION("any ip")
@@ -201,7 +201,7 @@ TEST_CASE("Packet constraints matching", "[framework]")
         cs.src_port = sport;
         cs.dst_port = dport;
 
-        CHECK( match_constraints(cs, sip, dip, sport, dport) );
+        CHECK( true == match_constraints(cs, sip, dip, sport, dport) );
     }
 
     SECTION("any port")
@@ -214,7 +214,7 @@ TEST_CASE("Packet constraints matching", "[framework]")
         cs.src_ip = sip;
         cs.dst_ip = dip;
 
-        CHECK( match_constraints(cs, sip, dip, sport, dport) );
+        CHECK( true == match_constraints(cs, sip, dip, sport, dport) );
     }
 
     SECTION("any src")
@@ -227,7 +227,7 @@ TEST_CASE("Packet constraints matching", "[framework]")
         cs.dst_port = dport;
         cs.dst_ip = dip;
 
-        CHECK( match_constraints(cs, sip, dip, sport, dport) );
+        CHECK( true == match_constraints(cs, sip, dip, sport, dport) );
     }
 }
 
index 06b31d899c6bdc16fcca3e8705ccd696a09a8921..9d49ef65a5091c8508fb09855df3a3383e23bd7b 100644 (file)
@@ -332,151 +332,151 @@ TEST_CASE("dflt op", "[RangeCheck]")
 {
     RangeCheck rc;
 
-    REQUIRE(rc.parse("5"));
+    REQUIRE(true == rc.parse("5"));
     REQUIRE(rc.op == RangeCheck::EQ);
     REQUIRE((rc.max == 5));
 
-    CHECK(rc.eval(5));
+    CHECK(true == rc.eval(5));
 
-    CHECK(!rc.eval(4));
-    CHECK(!rc.eval(6));
+    CHECK(false == rc.eval(4));
+    CHECK(false == rc.eval(6));
 }
 
 TEST_CASE("=", "[RangeCheck]")
 {
     RangeCheck rc;
 
-    REQUIRE(rc.parse("=+0x5"));
+    REQUIRE(true == rc.parse("=+0x5"));
     REQUIRE(rc.op == RangeCheck::EQ);
     REQUIRE((rc.max == 5));
 
-    CHECK(rc.eval(5));
+    CHECK(true == rc.eval(5));
 
-    CHECK(!rc.eval(4));
-    CHECK(!rc.eval(6));
+    CHECK(false == rc.eval(4));
+    CHECK(false == rc.eval(6));
 }
 
 TEST_CASE("!", "[RangeCheck]")
 {
     RangeCheck rc;
 
-    REQUIRE(rc.parse("!-5"));
+    REQUIRE(true == rc.parse("!-5"));
     REQUIRE(rc.op == RangeCheck::NOT);
     REQUIRE((rc.max == -5));
 
-    CHECK(rc.eval(-4));
-    CHECK(rc.eval(-6));
+    CHECK(true == rc.eval(-4));
+    CHECK(true == rc.eval(-6));
 
-    CHECK(!rc.eval(-5));
+    CHECK(false == rc.eval(-5));
 }
 
 TEST_CASE("!=", "[RangeCheck]")
 {
     RangeCheck rc;
 
-    REQUIRE(rc.parse("!=5"));
+    REQUIRE(true == rc.parse("!=5"));
     REQUIRE(rc.op == RangeCheck::NOT);
     REQUIRE((rc.max == 5));
 
-    CHECK(rc.eval(4));
-    CHECK(rc.eval(6));
+    CHECK(true == rc.eval(4));
+    CHECK(true == rc.eval(6));
 
-    CHECK(!rc.eval(5));
+    CHECK(false == rc.eval(5));
 }
 
 TEST_CASE("<", "[RangeCheck]")
 {
     RangeCheck rc;
 
-    REQUIRE(rc.parse("<5"));
+    REQUIRE(true == rc.parse("<5"));
     REQUIRE(rc.op == RangeCheck::LT);
     REQUIRE((rc.max == 5));
 
-    CHECK(rc.eval(4));
-    CHECK(rc.eval(-1));
+    CHECK(true == rc.eval(4));
+    CHECK(true == rc.eval(-1));
 
-    CHECK(!rc.eval(5));
-    CHECK(!rc.eval(6));
+    CHECK(false == rc.eval(5));
+    CHECK(false == rc.eval(6));
 }
 
 TEST_CASE("<=", "[RangeCheck]")
 {
     RangeCheck rc;
 
-    REQUIRE(rc.parse("<=5"));
+    REQUIRE(true == rc.parse("<=5"));
     REQUIRE(rc.op == RangeCheck::LE);
     REQUIRE((rc.max == 5));
 
-    CHECK(rc.eval(5));
-    CHECK(rc.eval(-1));
+    CHECK(true == rc.eval(5));
+    CHECK(true == rc.eval(-1));
 
-    CHECK(!rc.eval(6));
-    CHECK(!rc.eval(1000));
+    CHECK(false == rc.eval(6));
+    CHECK(false == rc.eval(1000));
 }
 
 TEST_CASE(">", "[RangeCheck]")
 {
     RangeCheck rc;
 
-    REQUIRE(rc.parse(">5"));
+    REQUIRE(true == rc.parse(">5"));
     REQUIRE((rc.op == RangeCheck::GT));
     REQUIRE((rc.min == 5));
 
-    CHECK(rc.eval(6));
-    CHECK(rc.eval(10));
+    CHECK(true == rc.eval(6));
+    CHECK(true == rc.eval(10));
 
-    CHECK(!rc.eval(5));
-    CHECK(!rc.eval(-1));
+    CHECK(false == rc.eval(5));
+    CHECK(false == rc.eval(-1));
 }
 
 TEST_CASE(">=", "[RangeCheck]")
 {
     RangeCheck rc;
 
-    REQUIRE(rc.parse(">=5"));
+    REQUIRE(true == rc.parse(">=5"));
     REQUIRE((rc.op == RangeCheck::GE));
     REQUIRE((rc.min == 5));
 
-    CHECK(rc.eval(5));
-    CHECK(rc.eval(10));
+    CHECK(true == rc.eval(5));
+    CHECK(true == rc.eval(10));
 
-    CHECK(!rc.eval(4));
-    CHECK(!rc.eval(-4));
+    CHECK(false == rc.eval(4));
+    CHECK(false == rc.eval(-4));
 }
 
 TEST_CASE("<>", "[RangeCheck]")
 {
     RangeCheck rc;
 
-    REQUIRE(rc.parse("0<>5"));
+    REQUIRE(true == rc.parse("0<>5"));
     REQUIRE((rc.op == RangeCheck::LG));
     REQUIRE(rc.min == 0);
     REQUIRE((rc.max == 5));
 
-    CHECK(rc.eval(1));
-    CHECK(rc.eval(4));
+    CHECK(true == rc.eval(1));
+    CHECK(true == rc.eval(4));
 
-    CHECK(!rc.eval(-1));
-    CHECK(!rc.eval(0));
-    CHECK(!rc.eval(5));
-    CHECK(!rc.eval(6));
+    CHECK(false == rc.eval(-1));
+    CHECK(false == rc.eval(0));
+    CHECK(false == rc.eval(5));
+    CHECK(false == rc.eval(6));
 }
 
 TEST_CASE("<=>", "[RangeCheck]")
 {
     RangeCheck rc;
 
-    REQUIRE(rc.parse("0<=>5"));
+    REQUIRE(true == rc.parse("0<=>5"));
     REQUIRE((rc.op == RangeCheck::LEG));
     REQUIRE((rc.max == 5));
 
-    CHECK(rc.eval(0));
-    CHECK(rc.eval(1));
-    CHECK(rc.eval(4));
-    CHECK(rc.eval(5));
+    CHECK(true == rc.eval(0));
+    CHECK(true == rc.eval(1));
+    CHECK(true == rc.eval(4));
+    CHECK(true == rc.eval(5));
 
-    CHECK(!rc.eval(-1));
-    CHECK(!rc.eval(6));
+    CHECK(false == rc.eval(-1));
+    CHECK(false == rc.eval(6));
 }
 
 TEST_CASE("parsing", "[RangeCheck]")
@@ -487,63 +487,63 @@ TEST_CASE("parsing", "[RangeCheck]")
     {
         SECTION("a")
         {
-            REQUIRE(rc.parse("5"));
+            REQUIRE(true == rc.parse("5"));
             CHECK(rc.op == RangeCheck::EQ);
             CHECK((rc.max == 5));
         }
 
         SECTION("b")
         {
-            REQUIRE(rc.parse(" 5 "));
+            REQUIRE(true == rc.parse(" 5 "));
             CHECK(rc.op == RangeCheck::EQ);
             CHECK((rc.max == 5));
         }
 
         SECTION("c")
         {
-            REQUIRE(rc.parse(" ! 5 "));
+            REQUIRE(true == rc.parse(" ! 5 "));
             CHECK(rc.op == RangeCheck::NOT);
             CHECK((rc.max == 5));
         }
 
         SECTION("d")
         {
-            REQUIRE(rc.parse(" != 5 "));
+            REQUIRE(true == rc.parse(" != 5 "));
             CHECK(rc.op == RangeCheck::NOT);
             CHECK((rc.max == 5));
         }
 
         SECTION("e")
         {
-            REQUIRE(rc.parse(" < 5 "));
+            REQUIRE(true == rc.parse(" < 5 "));
             CHECK((rc.op == RangeCheck::LT));
             CHECK((rc.max == 5));
         }
 
         SECTION("f")
         {
-            REQUIRE(rc.parse(" > 5 "));
+            REQUIRE(true == rc.parse(" > 5 "));
             CHECK((rc.op == RangeCheck::GT));
             CHECK((rc.min == 5));
         }
 
         SECTION("g")
         {
-            REQUIRE(rc.parse(" <= 5 "));
+            REQUIRE(true == rc.parse(" <= 5 "));
             CHECK((rc.op == RangeCheck::LE));
             CHECK((rc.max == 5));
         }
 
         SECTION("h")
         {
-            REQUIRE(rc.parse(" >= 5 "));
+            REQUIRE(true == rc.parse(" >= 5 "));
             CHECK((rc.op == RangeCheck::GE));
             CHECK((rc.min == 5));
         }
 
         SECTION("i")
         {
-            REQUIRE(rc.parse(" 10 <> 50 "));
+            REQUIRE(true == rc.parse(" 10 <> 50 "));
             CHECK((rc.op == RangeCheck::LG));
             CHECK((rc.min == 10));
             CHECK((rc.max == 50));
@@ -551,7 +551,7 @@ TEST_CASE("parsing", "[RangeCheck]")
 
         SECTION("j")
         {
-            REQUIRE(rc.parse(" 0x10 <=> 0x50 "));
+            REQUIRE(true == rc.parse(" 0x10 <=> 0x50 "));
             CHECK((rc.op == RangeCheck::LEG));
             CHECK((rc.min == 0x10));
             CHECK((rc.max == 0x50));
@@ -559,7 +559,7 @@ TEST_CASE("parsing", "[RangeCheck]")
 
         SECTION("k")
         {
-            REQUIRE(rc.parse(" -0123 <=> 0x123 "));
+            REQUIRE(true == rc.parse(" -0123 <=> 0x123 "));
             CHECK((rc.op == RangeCheck::LEG));
             CHECK((rc.min == -83));
             CHECK((rc.max == 291));
@@ -569,41 +569,41 @@ TEST_CASE("parsing", "[RangeCheck]")
     SECTION("invalid ranges")
     {
         // spacey operators
-        CHECK(!rc.parse(" ! = 5 "));
-        CHECK(!rc.parse(" < = 5 "));
-        CHECK(!rc.parse(" > = 5 "));
-        CHECK(!rc.parse(" 1 < > 5 "));
-        CHECK(!rc.parse(" 1 < = > 5 "));
-        CHECK(!rc.parse(" < > 5 "));
-        CHECK(!rc.parse(" < = > 5 "));
+        CHECK(false == rc.parse(" ! = 5 "));
+        CHECK(false == rc.parse(" < = 5 "));
+        CHECK(false == rc.parse(" > = 5 "));
+        CHECK(false == rc.parse(" 1 < > 5 "));
+        CHECK(false == rc.parse(" 1 < = > 5 "));
+        CHECK(false == rc.parse(" < > 5 "));
+        CHECK(false == rc.parse(" < = > 5 "));
 
         // other invalids
-        CHECK(!rc.parse("5x"));
-        CHECK(!rc.parse("5.0"));
-        CHECK(!rc.parse("5-0"));
-        CHECK(!rc.parse("*5"));
-        CHECK(!rc.parse("=$5"));
-        CHECK(!rc.parse("=5x"));
-        CHECK(!rc.parse("<<0"));
-        CHECK(!rc.parse("+9223372036854775808"));
-        CHECK(!rc.parse("-9223372036854775809"));
-        CHECK(!rc.parse("4<>2"));
-        CHECK(!rc.parse("24<=>16"));
+        CHECK(false == rc.parse("5x"));
+        CHECK(false == rc.parse("5.0"));
+        CHECK(false == rc.parse("5-0"));
+        CHECK(false == rc.parse("*5"));
+        CHECK(false == rc.parse("=$5"));
+        CHECK(false == rc.parse("=5x"));
+        CHECK(false == rc.parse("<<0"));
+        CHECK(false == rc.parse("+9223372036854775808"));
+        CHECK(false == rc.parse("-9223372036854775809"));
+        CHECK(false == rc.parse("4<>2"));
+        CHECK(false == rc.parse("24<=>16"));
 
         // backwards
-        CHECK(!rc.parse(" 5 = "));
-        CHECK(!rc.parse(" 5 ! "));
-        CHECK(!rc.parse(" 5 != "));
-        CHECK(!rc.parse(" 5 < "));
-        CHECK(!rc.parse(" 5 <= "));
-        CHECK(!rc.parse(" 5 > "));
-        CHECK(!rc.parse(" 5 >= "));
+        CHECK(false == rc.parse(" 5 = "));
+        CHECK(false == rc.parse(" 5 ! "));
+        CHECK(false == rc.parse(" 5 != "));
+        CHECK(false == rc.parse(" 5 < "));
+        CHECK(false == rc.parse(" 5 <= "));
+        CHECK(false == rc.parse(" 5 > "));
+        CHECK(false == rc.parse(" 5 >= "));
 
         // missing bound
-        CHECK(!rc.parse(" 1 <> "));
-        CHECK(!rc.parse(" <> 5 "));
-        CHECK(!rc.parse(" 1 <=> "));
-        CHECK(!rc.parse(" <=> 5 "));
+        CHECK(false == rc.parse(" 1 <> "));
+        CHECK(false == rc.parse(" <> 5 "));
+        CHECK(false == rc.parse(" 1 <=> "));
+        CHECK(false == rc.parse(" <=> 5 "));
     }
 }
 
@@ -611,25 +611,25 @@ TEST_CASE("validate", "[RangeCheck]")
 {
     RangeCheck rc;
 
-    REQUIRE(rc.validate("2<>4", "0:10"));
+    REQUIRE(true == rc.validate("2<>4", "0:10"));
     CHECK((rc.min == 2));
     CHECK((rc.max == 4));
 
     // #
-    CHECK(rc.validate("2<>4", "0"));
+    CHECK(true == rc.validate("2<>4", "0"));
     // #:
-    CHECK(rc.validate("2<>4", "1:"));
+    CHECK(true == rc.validate("2<>4", "1:"));
     // :#
-    CHECK(rc.validate("2<>4", ":8"));
+    CHECK(true == rc.validate("2<>4", ":8"));
     // in hex
-    CHECK(rc.validate("2<>4", "0x1:0x0A"));
+    CHECK(true == rc.validate("2<>4", "0x1:0x0A"));
 
     // invalid low
-    CHECK(!rc.validate("2<>4", "3:"));
+    CHECK(false == rc.validate("2<>4", "3:"));
     // invalid hi
-    CHECK(!rc.validate("2<>4", "1:3"));
+    CHECK(false == rc.validate("2<>4", "1:3"));
     // invalid low and hi
-    CHECK(!rc.validate("200<>400", "3:10"));
+    CHECK(false == rc.validate("200<>400", "3:10"));
 }
 
 #endif
index 7de08bf098edcac92d6c6ce2111008ec9ae6a976..ab5806ec4b7d912df83f607c0ee4a853a00e1713 100644 (file)
@@ -35,7 +35,7 @@ using namespace snort;
 //--------------------------------------------------------------------------
 // mocks
 //--------------------------------------------------------------------------
-InspectionPolicy::InspectionPolicy(unsigned int) {}
+InspectionPolicy::InspectionPolicy(unsigned int) : framework_policy(nullptr), cloned(false) {}
 InspectionPolicy::~InspectionPolicy() = default;
 NetworkPolicy::NetworkPolicy(unsigned int, unsigned int) {}
 NetworkPolicy::~NetworkPolicy() = default;
index be36de7fd4fbd9936f64ea7424aab3798ccb8e56..d4d21fef979629bec024135f5effdf769e4d16aa 100644 (file)
@@ -265,8 +265,8 @@ std::string Value::get_origin_string() const
     std::string value;
     std::string token;
 
-    stringstream s(origin_str);
-    while ( s >> token )
+    stringstream str_s(origin_str);
+    while ( str_s >> token )
     {
         value += token;
         value += " ";
@@ -332,18 +332,40 @@ void Value::update_mask(uint64_t& mask, uint64_t flag, bool invert)
 // and the string value/zero is returned based on the result etc.
 
 TEST_CASE("set double test", "[Value]")
+{
+    Value test_val((double)12345.689);
+    CHECK(true == test_val.get_bool());
+    CHECK(12345 == test_val.get_size());
+    CHECK(12345 == test_val.get_int16());
+    CHECK(12345 == test_val.get_uint16());
+    CHECK(12345 == test_val.get_int32());
+    CHECK(12345 == test_val.get_uint32());
+    CHECK(12345 == test_val.get_int64());
+    CHECK(12345 == test_val.get_uint64());
+    CHECK(12345.689 == test_val.get_real());
+    CHECK(12345 == test_val.get_ip4());
+}
+
+TEST_CASE("set double test 2", "[Value]")
 {
     Value test_val((double)123456.89);
     CHECK(true == test_val.get_bool());
     CHECK(123456 == test_val.get_size());
-    CHECK(-7616 == test_val.get_int16());
-    CHECK(0xe240 == test_val.get_uint16());
-    CHECK(0x1e240 == test_val.get_int32());
-    CHECK(0x1e240 == test_val.get_uint32());
-    CHECK(0x1e240 == test_val.get_int64());
-    CHECK(0x1e240 == test_val.get_uint64());
+    CHECK(123456 == test_val.get_int32());
+    CHECK(123456 == test_val.get_uint32());
+    CHECK(123456 == test_val.get_int64());
+    CHECK(123456 == test_val.get_uint64());
     CHECK(123456.89 == test_val.get_real());
-    CHECK(0x1e240 == test_val.get_ip4());
+    CHECK(123456 == test_val.get_ip4());
+}
+
+TEST_CASE("set double test 3", "[Value]")
+{
+    Value test_val((double)-123456.89);
+    CHECK(true == test_val.get_bool());
+    CHECK(-123456 == test_val.get_int32());
+    CHECK(-123456 == test_val.get_int64());
+    CHECK(-123456.89 == test_val.get_real());
 }
 
 TEST_CASE("mac addr negative test", "[Value]")
@@ -462,7 +484,7 @@ TEST_CASE("token test", "[Value]")
     CHECK(true == test_val.get_next_csv_token(test_str));
     str_val = (const char *)test_str.c_str();
     REQUIRE(nullptr != str_val);
-    CHECK((strcmp(str_val,"123456")==0));
+    CHECK(0 == strcmp(str_val,"123456"));
 }
 
 TEST_CASE("get as string", "[Value]")
index 4cc87f1e2a15a43428c074e356568abd69274ecd..8d0f382371d70738fa2cfb082ad52115161615bb 100644 (file)
@@ -129,7 +129,7 @@ void LruCacheLocal<Key, Value, Hash>::add_entry(const Key& key, const Value& val
 template<typename Key, typename Value, typename Hash>
 Value& LruCacheLocal<Key, Value, Hash>::find_else_create(const Key& key, bool* is_new)
 {
-    LruMapIter it = map.find(key);
+    auto it = map.find(key);
     if (it == map.end())
     {
         stats.cache_misses++;
@@ -147,7 +147,7 @@ Value& LruCacheLocal<Key, Value, Hash>::find_else_create(const Key& key, bool* i
 template<typename Key, typename Value, typename Hash>
 bool LruCacheLocal<Key, Value, Hash>::add(const Key& key, const Value& value, bool replace)
 {
-    LruMapIter it = map.find(key);
+    auto it = map.find(key);
     if (it == map.end())
     {
         stats.cache_misses++;
@@ -168,7 +168,7 @@ bool LruCacheLocal<Key, Value, Hash>::add(const Key& key, const Value& value, bo
 template<typename Key, typename Value, typename Hash>
 bool LruCacheLocal<Key, Value, Hash>::remove(const Key& key)
 {
-    LruMapIter it = map.find(key);
+    auto it = map.find(key);
     if (it == map.end())
     {
         return false;
index a476e45ffda8dff7f36e449f0bb459caa909b683..4460ee2663ef77637aaace3af3629c5512ffcf21 100644 (file)
@@ -79,22 +79,23 @@ public:
     using KeyType = Key;
 
     // Return data entry associated with key. If doesn't exist, return nullptr.
-    Data find(const Key& key);
+    Data find(const Key&);
 
     // Return data entry associated with key. If doesn't exist, create a new entry.
-    Data operator[](const Key& key);
+    Data operator[](const Key&);
 
     // Same as operator[]; additionally, sets the boolean if a new entry is created.
-    Data find_else_create(const Key& key, bool* new_data);
+    Data find_else_create(const Key&, bool* new_data);
 
     // Returns true if found or replaced, takes a ref to a user managed entry
-    bool find_else_insert(const Key& key, std::shared_ptr<Value>& data, bool replace = false);
+    bool find_else_insert(const Key&, Data&, bool replace = false);
 
     // Returns the found or inserted data, takes a ref to user managed entry.
-    Data find_else_insert(const Key&, Data&, LcsInsertStatus*, bool = false);
+    Data find_else_insert(const Key&, Data&, LcsInsertStatus*,
+        bool replace = false);
 
     // Return all data from the LruCache in order (most recently used to least)
-    std::vector<std::pair<Key, Data> > get_all_data();
+    std::vector<std::pair<Key, Data>> get_all_data();
 
     //  Get current number of elements in the LruCache.
     size_t size()
@@ -109,7 +110,7 @@ public:
         return list.size() * mem_chunk;
     }
 
-    size_t get_max_size()
+    size_t get_max_size() const
     {
         return max_size;
     }
@@ -120,18 +121,18 @@ public:
 
     //  Remove entry associated with Key.
     //  Returns true if entry existed, false otherwise.
-    virtual bool remove(const Key& key);
+    virtual bool remove(const Key&);
 
     //  Remove entry associated with key and return removed data.
     //  Returns true and copy of data if entry existed.  Returns false if
     //  entry did not exist.
-    virtual bool remove(const Key& key, Data& data);
+    virtual bool remove(const Key&, Data&);
 
     const PegInfo* get_pegs() const
     { return lru_cache_shared_peg_names; }
 
-    PegCount* get_counts()
-    { return (PegCount*)&stats; }
+    const PegCount* get_counts() const
+    { return (const PegCount*)&stats; }
 
     void lock()
     { cache_mutex.lock(); }
@@ -218,10 +219,9 @@ bool LruCacheShared<Key, Value, Hash, Eq, Purgatory>::set_max_size(size_t newsiz
 template<typename Key, typename Value, typename Hash, typename Eq, typename Purgatory>
 std::shared_ptr<Value> LruCacheShared<Key, Value, Hash, Eq, Purgatory>::find(const Key& key)
 {
-    LruMapIter map_iter;
     std::lock_guard<std::mutex> cache_lock(cache_mutex);
 
-    map_iter = map.find(key);
+    auto map_iter = map.find(key);
     if (map_iter == map.end())
     {
         stats.find_misses++;
@@ -241,11 +241,9 @@ std::shared_ptr<Value> LruCacheShared<Key, Value, Hash, Eq, Purgatory>::operator
 }
 
 template<typename Key, typename Value, typename Hash, typename Eq, typename Purgatory>
-std::shared_ptr<Value> LruCacheShared<Key, Value, Hash, Eq, Purgatory>::
-find_else_create(const Key& key, bool* new_data)
+std::shared_ptr<Value> LruCacheShared<Key, Value, Hash, Eq, Purgatory>::find_else_create(const Key& key,
+    bool* new_data)
 {
-    LruMapIter map_iter;
-
     // As with remove and operator[], we need a temporary list of references
     // to delay the destruction of the items being removed by prune().
     // This is one instance where we cannot get by with directly locking and
@@ -256,7 +254,7 @@ find_else_create(const Key& key, bool* new_data)
 
     std::lock_guard<std::mutex> cache_lock(cache_mutex);
 
-    map_iter = map.find(key);
+    auto map_iter = map.find(key);
     if (map_iter != map.end())
     {
         stats.find_hits++;
@@ -283,15 +281,14 @@ find_else_create(const Key& key, bool* new_data)
 }
 
 template<typename Key, typename Value, typename Hash, typename Eq, typename Purgatory>
-bool LruCacheShared<Key, Value, Hash, Eq, Purgatory>::
-find_else_insert(const Key& key, std::shared_ptr<Value>& data, bool replace)
+bool LruCacheShared<Key, Value, Hash, Eq, Purgatory>::find_else_insert(const Key& key, Data& data,
+    bool replace)
 {
-    LruMapIter map_iter;
-
     Purgatory tmp_data;
+
     std::lock_guard<std::mutex> cache_lock(cache_mutex);
 
-    map_iter = map.find(key);
+    auto map_iter = map.find(key);
     if (map_iter != map.end())
     {
         stats.find_hits++;
@@ -324,15 +321,14 @@ find_else_insert(const Key& key, std::shared_ptr<Value>& data, bool replace)
 }
 
 template<typename Key, typename Value, typename Hash, typename Eq, typename Purgatory>
-std::shared_ptr<Value> LruCacheShared<Key, Value, Hash, Eq, Purgatory>::
-find_else_insert(const Key& key, std::shared_ptr<Value>& data, LcsInsertStatus* status, bool replace)
+std::shared_ptr<Value> LruCacheShared<Key, Value, Hash, Eq, Purgatory>::find_else_insert(const Key& key, Data& data,
+    LcsInsertStatus* status, bool replace)
 {
-    LruMapIter map_iter;
-
     Purgatory tmp_data;
+
     std::lock_guard<std::mutex> cache_lock(cache_mutex);
 
-    map_iter = map.find(key);
+    auto map_iter = map.find(key);
     if (map_iter != map.end())
     {
         stats.find_hits++;
@@ -368,25 +364,19 @@ find_else_insert(const Key& key, std::shared_ptr<Value>& data, LcsInsertStatus*
 }
 
 template<typename Key, typename Value, typename Hash, typename Eq, typename Purgatory>
-std::vector< std::pair<Key, std::shared_ptr<Value>> >
-LruCacheShared<Key, Value, Hash, Eq, Purgatory>::get_all_data()
+std::vector<std::pair<Key, std::shared_ptr<Value>>> LruCacheShared<Key, Value, Hash, Eq, Purgatory>::get_all_data()
 {
     std::vector<std::pair<Key, Data> > vec;
     std::lock_guard<std::mutex> cache_lock(cache_mutex);
 
-    for (auto& entry : list )
-    {
-        vec.emplace_back(entry);
-    }
-
+    vec.reserve(list.size());
+    std::copy(list.cbegin(), list.cend(), std::back_inserter(vec));
     return vec;
 }
 
 template<typename Key, typename Value, typename Hash, typename Eq, typename Purgatory>
 bool LruCacheShared<Key, Value, Hash, Eq, Purgatory>::remove(const Key& key)
 {
-    LruMapIter map_iter;
-
     // There is a potential race condition here, when the destructor of
     // the object being removed needs to call back into the cache and lock
     // the cache (e.g. via an allocator) to update the size of the cache.
@@ -402,11 +392,9 @@ bool LruCacheShared<Key, Value, Hash, Eq, Purgatory>::remove(const Key& key)
 
     std::lock_guard<std::mutex> cache_lock(cache_mutex);
 
-    map_iter = map.find(key);
+    auto map_iter = map.find(key);
     if (map_iter == map.end())
-    {
         return false;   //  Key is not in LruCache.
-    }
 
     data = map_iter->second->second;
 
@@ -424,18 +412,13 @@ bool LruCacheShared<Key, Value, Hash, Eq, Purgatory>::remove(const Key& key)
 }
 
 template<typename Key, typename Value, typename Hash, typename Eq, typename Purgatory>
-bool LruCacheShared<Key, Value, Hash, Eq, Purgatory>::remove(const Key& key,
-    std::shared_ptr<Value>& data)
+bool LruCacheShared<Key, Value, Hash, Eq, Purgatory>::remove(const Key& key, Data& data)
 {
-    LruMapIter map_iter;
-
     std::lock_guard<std::mutex> cache_lock(cache_mutex);
 
-    map_iter = map.find(key);
+    auto map_iter = map.find(key);
     if (map_iter == map.end())
-    {
         return false;   //  Key is not in LruCache.
-    }
 
     data = map_iter->second->second;
 
index c6d4f96ae0382b69de0f6b0ba11afb2840222b3c..1d744ee274c4768169991cd7f022e7339c296a51 100644 (file)
@@ -20,7 +20,9 @@
 #ifndef LRU_SEGMENTED_CACHE_SHARED_H
 #define LRU_SEGMENTED_CACHE_SHARED_H
 
+#include <algorithm>
 #include <cassert>
+#include <numeric>
 #include <vector>
 
 #include "lru_cache_shared.h"
@@ -28,7 +30,7 @@
 #define DEFAULT_SEGMENT_COUNT 4
 
 template<typename Key, typename Value, typename Hash = std::hash<Key>, typename Eq = std::equal_to<Key>>
-class SegmentedLruCache 
+class SegmentedLruCache
 {
 public:
 
@@ -66,10 +68,10 @@ public:
         std::size_t segment_idx = get_segment_idx(key);
         return segments[segment_idx]->remove(key);
     }
-    
+
     bool remove(const Key& key, Data& data)
     {
-        std::size_t idx = get_segment_idx(key); 
+        std::size_t idx = get_segment_idx(key);
         return segments[idx]->remove(key, data);
     }
 
@@ -90,7 +92,7 @@ public:
         std::size_t segment_idx = get_segment_idx(key);
         return segments[segment_idx]->find_else_insert(key, data, status, replace);
     }
-    
+
     bool set_max_size(size_t max_size)
     {
         bool success = true;
@@ -115,22 +117,20 @@ public:
         return all_data;
     }
 
-    size_t mem_size()
+    size_t mem_size() const
     {
         size_t mem_size = 0;
         for ( const auto& cache : segments )
-        {
             mem_size += cache->mem_size();
-        }
         return mem_size;
     }
 
-    const PegInfo* get_pegs() 
-    { 
-        return lru_cache_shared_peg_names; 
+    const PegInfo* get_pegs()
+    {
+        return lru_cache_shared_peg_names;
     }
 
-    PegCount* get_counts() 
+    const PegCount* get_counts()
     {
         PegCount* pcs = (PegCount*)&counts;
         const PegInfo* pegs = get_pegs();
@@ -144,26 +144,22 @@ public:
             }
             pcs[i] = c;
         }
-        return (PegCount*)&counts;
+        return (const PegCount*)&counts;
     }
 
-    size_t size() 
+    size_t size() const
     {
         size_t total_size = 0;
-        for ( const auto& cache : segments ) 
-        {
+        for ( const auto& cache : segments )
             total_size += cache->size();
-        }
         return total_size;
     }
 
-    size_t get_max_size()
+    size_t get_max_size() const
     {
         size_t max_size = 0;
         for ( const auto& cache : segments )
-        {
             max_size += cache->get_max_size();
-        }
         return max_size;
     }
 
index ea0b150cb0c34f20db6074a3428aafe095d6c225..79e8d7a5ec1fcf7d201eb3607485477c8df93f5f 100644 (file)
@@ -42,7 +42,7 @@ DataBus::DataBus() = default;
 DataBus::~DataBus() = default;
 
 // run_flags is used indirectly from HashFnc class by calling SnortConfig::static_hash()
-SnortConfig::SnortConfig(const SnortConfig* const, const char*)
+SnortConfig::SnortConfig(const SnortConfig* const, const char*) : daq_config(nullptr), thread_config(nullptr)
 { snort_conf->run_flags = 0;}
 
 SnortConfig::~SnortConfig() = default;
index 360858500054326543c1a4adc3d08db4a006cfad..115836a5e5a6250cfa581e6317c39db345e0bb9d 100644 (file)
@@ -191,7 +191,7 @@ TEST(lru_cache_shared, stats_test)
     lru_cache.remove(7);    // Removes - hit
     lru_cache.remove(10);   // Removes - miss
 
-    PegCount* stats = lru_cache.get_counts();
+    const PegCount* stats = lru_cache.get_counts();
 
     CHECK(stats[0] == 10);  //  adds
     CHECK(stats[1] == 7);   //  alloc prunes
index 9779e9e07c299db642cee2e05f9ff22ae635ef6e..e703f22c0768a1b37e9d3c422bd4b0623e2b95d7 100644 (file)
@@ -179,7 +179,7 @@ TEST(segmented_lru_cache, stats_test)
     lru_cache.remove(8);
     lru_cache.remove(11); // not in cache
 
-    PegCount* stats = lru_cache.get_counts();
+    const PegCount* stats = lru_cache.get_counts();
 
     CHECK(stats[0] == 10);  // adds
     CHECK(stats[1] == 2);   // alloc_prunes
@@ -199,10 +199,10 @@ TEST(segmented_lru_cache, find_else_insert_replace)
     SegmentedLruCache<int, std::string> lru_cache(8);
     std::shared_ptr<std::string> data(new std::string("hello"));
     LcsInsertStatus status;
-    
+
     lru_cache.find_else_insert(1, data, &status, false);  // initial insert
     CHECK(status == LcsInsertStatus::LCS_ITEM_INSERTED);  // Check status for initial insert
-    
+
     std::shared_ptr<std::string> newData(new std::string("world"));
     std::shared_ptr<std::string> returnedData = lru_cache.find_else_insert(1, newData, &status, true);  // replace existing item
     CHECK(returnedData != nullptr);
index 112d941287bc2c00b4740fc8391d8a2aa0ceb500..1e3ba74bad6f60cd48af315d19b1266eea9aa0cd 100644 (file)
@@ -42,7 +42,7 @@ DataBus::DataBus() = default;
 DataBus::~DataBus() = default;
 
 // run_flags is used indirectly from HashFnc class by calling SnortConfig::static_hash()
-SnortConfig::SnortConfig(const SnortConfig* const, const char*)
+SnortConfig::SnortConfig(const SnortConfig* const, const char*) : daq_config(nullptr), thread_config(nullptr)
 { snort_conf->run_flags = 0;}
 
 SnortConfig::~SnortConfig() = default;
index ed5ddd47b2e7894d6897f9ce92b04b6d978f93f9..551cfb899e7a821939ae9088266c2686589213f5 100644 (file)
@@ -67,7 +67,7 @@ DataBus::DataBus() = default;
 DataBus::~DataBus() = default;
 
 // run_flags is used indirectly from HashFnc class by calling SnortConfig::static_hash()
-SnortConfig::SnortConfig(const SnortConfig* const, const char*)
+SnortConfig::SnortConfig(const SnortConfig* const, const char*) : daq_config(nullptr), thread_config(nullptr)
 { snort_conf->run_flags = 0;}
 
 SnortConfig::~SnortConfig() = default;
index 2cb7394f2ecb3cf77e2d920d7427f3307a086790..b042180029a7db0babc4f83cc34b98508b214fb7 100644 (file)
@@ -179,7 +179,7 @@ DiscoveryFilter::DiscoveryFilter(const string& conf_path)
         auto any_list = get_list((FilterType)type, DF_ANY_INTF);
         if (!any_list)
             continue;
-        for (auto& intf_entry : intf_ip_list[type])
+        for (const auto& intf_entry : intf_ip_list[type])
         {
             if (intf_entry.second != any_list and
                 sfvar_add(intf_entry.second, any_list) != SFIP_SUCCESS)
@@ -412,27 +412,27 @@ TEST_CASE("Discovery Filter", "[is_monitored]")
     DiscoveryFilter df(conf);
 
     // Without flag
-    CHECK(df.is_app_monitored(&p, nullptr) == true);   // any interface rule for app is added to interface 0
-    CHECK(df.is_host_monitored(&p, nullptr) == false); // no rule for host
-    CHECK(df.is_user_monitored(&p, nullptr) == false); // no any interface rule for user
+    CHECK(true == df.is_app_monitored(&p, nullptr));   // any interface rule for app is added to interface 0
+    CHECK(false == df.is_host_monitored(&p, nullptr)); // no rule for host
+    CHECK(false == df.is_user_monitored(&p, nullptr)); // no any interface rule for user
 
     // With flag
     uint8_t flag = 0;
     CHECK((flag & DF_APP_CHECKED) != DF_APP_CHECKED);
     CHECK((flag & DF_APP_MONITORED) != DF_APP_MONITORED);
-    CHECK(df.is_app_monitored(&p, &flag) == true); // first attempt
+    CHECK(true == df.is_app_monitored(&p, &flag)); // first attempt
     CHECK((flag & DF_APP_CHECKED) == DF_APP_CHECKED);
     CHECK((flag & DF_APP_MONITORED) == DF_APP_MONITORED);
-    CHECK(df.is_app_monitored(&p, &flag) == true); // second attempt
+    CHECK(true == df.is_app_monitored(&p, &flag)); // second attempt
     CHECK((flag & DF_APP_CHECKED) == DF_APP_CHECKED);
     CHECK((flag & DF_APP_MONITORED) == DF_APP_MONITORED);
 
     CHECK((flag & DF_USER_CHECKED) != DF_USER_CHECKED);
     CHECK((flag & DF_USER_MONITORED) != DF_USER_MONITORED);
-    CHECK(df.is_user_monitored(&p, &flag) == false); // first attempt
+    CHECK(false == df.is_user_monitored(&p, &flag)); // first attempt
     CHECK((flag & DF_USER_CHECKED) == DF_USER_CHECKED);
     CHECK((flag & DF_USER_MONITORED) != DF_USER_MONITORED);
-    CHECK(df.is_user_monitored(&p, &flag) == false); // second attempt
+    CHECK(false == df.is_user_monitored(&p, &flag)); // second attempt
     CHECK((flag & DF_USER_CHECKED) == DF_USER_CHECKED);
     CHECK((flag & DF_USER_MONITORED) != DF_USER_MONITORED);
 
@@ -453,9 +453,9 @@ TEST_CASE("Discovery Filter Empty Configuration", "[is_monitored_config]")
     p.ptrs.ip_api.set(ip, ip);
     DiscoveryFilter df(conf);
 
-    CHECK(df.is_app_monitored(&p, nullptr) == false);
-    CHECK(df.is_host_monitored(&p, nullptr) == false);
-    CHECK(df.is_user_monitored(&p, nullptr) == false);
+    CHECK(false == df.is_app_monitored(&p, nullptr));
+    CHECK(false == df.is_host_monitored(&p, nullptr));
+    CHECK(false == df.is_user_monitored(&p, nullptr));
 
     remove("test_empty_analyze.txt");
 }
@@ -490,33 +490,33 @@ TEST_CASE("Discovery Filter Intf", "[is_monitored_intf_vs_ip]")
 
     p.ptrs.ip_api.set(ip1, ip7);  // ip from undefined interface matches interface any list
     p.pkth = &z_undefined;
-    CHECK(df.is_app_monitored(&p, nullptr) == true); // analyze host enables application discovery
-    CHECK(df.is_host_monitored(&p, nullptr) == true);
-    CHECK(df.is_user_monitored(&p, nullptr) == false);
+    CHECK(true == df.is_app_monitored(&p, nullptr)); // analyze host enables application discovery
+    CHECK(true == df.is_host_monitored(&p, nullptr));
+    CHECK(false == df.is_user_monitored(&p, nullptr));
 
     p.pkth = &z2; // the ip is not in interface 2 list, but it is in interface any list
-    CHECK(df.is_host_monitored(&p, nullptr) == true);
+    CHECK(true == df.is_host_monitored(&p, nullptr));
 
     p.ptrs.ip_api.set(ip3, ip7); // the ip matches interface 2 list
-    CHECK(df.is_host_monitored(&p, nullptr) == true);
+    CHECK(true == df.is_host_monitored(&p, nullptr));
 
     p.pkth = &z1; // no interface 1 list and the ip is not in interface any list
-    CHECK(df.is_host_monitored(&p, nullptr) == false);
+    CHECK(false == df.is_host_monitored(&p, nullptr));
 
     p.ptrs.ip_api.set(ip1, ip7); // no interface 1 list, but the ip is in interface any list
-    CHECK(df.is_host_monitored(&p, nullptr) == true);
+    CHECK(true == df.is_host_monitored(&p, nullptr));
 
     p.pkth = saved_hdr;
     p.ptrs.ip_api.set(ip2, ip7);  // the ip matches interface 0 list
-    CHECK(df.is_host_monitored(&p, nullptr) == true);
+    CHECK(true == df.is_host_monitored(&p, nullptr));
 
     // no match since the configuration for these ip addresses were invalid
     p.ptrs.ip_api.set(ip4, ip7);
-    CHECK(df.is_host_monitored(&p, nullptr) == false);
+    CHECK(false == df.is_host_monitored(&p, nullptr));
     p.ptrs.ip_api.set(ip5, ip7);
-    CHECK(df.is_host_monitored(&p, nullptr) == false);
+    CHECK(false == df.is_host_monitored(&p, nullptr));
     p.ptrs.ip_api.set(ip6, ip7);
-    CHECK(df.is_host_monitored(&p, nullptr) == false);
+    CHECK(false == df.is_host_monitored(&p, nullptr));
 
     remove("test_intf_ip.txt");
 }
@@ -572,7 +572,7 @@ TEST_CASE("Discovery Filter Port Exclusion", "[portexclusion]")
     p.ptrs.dp = b_port;
     p.packet_flags = 0x0;
     p.packet_flags |= PKT_FROM_CLIENT;
-    CHECK(is_port_excluded_test(df, &p) == true);
+    CHECK(true == is_port_excluded_test(df, &p));
 
     // A:any <- B:b_port
     p.ptrs.ip_api.set(&ba_hdr);
@@ -580,7 +580,7 @@ TEST_CASE("Discovery Filter Port Exclusion", "[portexclusion]")
     p.ptrs.dp = a_port;
     p.packet_flags = 0x0;
     p.packet_flags |= PKT_FROM_SERVER;
-    CHECK(is_port_excluded_test(df, &p) == true);
+    CHECK(true == is_port_excluded_test(df, &p));
 
 
     // Negative test: B = initiator (client), A = responder (server)
@@ -592,7 +592,7 @@ TEST_CASE("Discovery Filter Port Exclusion", "[portexclusion]")
     p.ptrs.dp = a_port;
     p.packet_flags = 0x0;
     p.packet_flags |= PKT_FROM_CLIENT;
-    CHECK(is_port_excluded_test(df, &p) == false);
+    CHECK(false == is_port_excluded_test(df, &p));
 
     // A -> B:b_port
     p.ptrs.ip_api.set(&ab_hdr);
@@ -600,7 +600,7 @@ TEST_CASE("Discovery Filter Port Exclusion", "[portexclusion]")
     p.ptrs.dp = b_port;
     p.packet_flags = 0x0;
     p.packet_flags |= PKT_FROM_SERVER;
-    CHECK(is_port_excluded_test(df, &p) == false);
+    CHECK(false == is_port_excluded_test(df, &p));
 
     remove(conf.c_str());
 }
index d054f068b8cf0eb02bf3c765d80200140b37cf29..afb992431bda71b6823380aa89f5a2b2a1a4d487 100644 (file)
@@ -391,6 +391,7 @@ TEST_CASE("sigsafe printer", "[SigsafePrinter]")
     SECTION("null string")
     {
         const char* nullstr = nullptr;
+        // cppcheck-suppress nullPointer
         snprintf(expected, sizeof(expected), "%s", nullstr);
         SigSafePrinter(actual, sizeof(actual)).printf("%s", nullstr);
         CHECK_THAT(expected, Equals(actual));
index c9282f67ca20d0d68b551548f397c235aaa4f6b6..f3303716a76d020b9e850e0a2d8b263d2e18c943 100644 (file)
@@ -55,12 +55,12 @@ TEST_CASE( "bitop", "[bitop]" )
         const size_t bit = 7;
 
         bitop.set(bit);
-        CHECK(bitop.is_set(bit));
+        CHECK(true == bitop.is_set(bit));
 
         CHECK(num_set(bitop, max) == 1);
 
         bitop.clear(bit);
-        CHECK(!bitop.is_set(bit));
+        CHECK(false == bitop.is_set(bit));
 
         CHECK( (is_clear(bitop, max) == true) );
     }
@@ -71,23 +71,23 @@ TEST_CASE( "bitop", "[bitop]" )
         const size_t k = max + 2;
 
         bitop.set(j);
-        CHECK(bitop.is_set(j));
+        CHECK(true == bitop.is_set(j));
 
-        CHECK(!bitop.is_set(k));
+        CHECK(false == bitop.is_set(k));
 
         bitop.set(k);
-        CHECK(bitop.is_set(k));
+        CHECK(true == bitop.is_set(k));
 
         CHECK(num_set(bitop, k + 2) == 2);
-        CHECK(bitop.is_set(j));
+        CHECK(true == bitop.is_set(j));
 
         bitop.clear(k);
-        CHECK(!bitop.is_set(k));
+        CHECK(false == bitop.is_set(k));
 
-        CHECK(bitop.is_set(j));
+        CHECK(true == bitop.is_set(j));
         bitop.clear(j);
 
-        CHECK( (is_clear(bitop, k + 2) == true) );
+        CHECK(true == is_clear(bitop, k + 2));
     }
 }
 
index f211fbd39327d128b737817d605a790c2f0b9df1..4b19e505a1f4a8bd1df166f44d3bcabba53715f7 100644 (file)
@@ -365,7 +365,7 @@ static const Parameter host_cache_params[] =
 
     { "memcap", Parameter::PT_INT, "512:maxSZ", "8388608",
       "maximum host cache size in bytes" },
-    
+
     { "segments", Parameter::PT_INT, "1:32", "4",
       "number of host cache segments. It must be power of 2."},
 
@@ -385,7 +385,7 @@ bool HostCacheModule::set(const char*, Value& v, SnortConfig*)
     else if ( v.is("segments"))
     {
         segments = v.get_uint8();
-        
+
         if(segments > 32)
             segments = 32;
 
@@ -408,7 +408,7 @@ bool HostCacheModule::end(const char* fqn, int, SnortConfig* sc)
         if ( Snort::is_reloading() )
             sc->register_reload_handler(new HostCacheReloadTuner(memcap));
         else
-        {   
+        {
             host_cache.setup(segments, memcap);
             ControlConn::log_command("host_cache.delete_host",false);
         }
@@ -485,7 +485,7 @@ string HostCacheModule::get_host_cache_segment_stats(int seg_idx)
 
     if(seg_idx >= host_cache.get_segments())
         return "Invalid segment index\nTry host_cache.get_segment_stats() to get all stats\n";
-    
+
     string str;
     const PegInfo* pegs = host_cache.get_pegs();
 
@@ -503,7 +503,7 @@ string HostCacheModule::get_host_cache_segment_stats(int seg_idx)
             cache->stats.items_in_use = cache->list.size();
             cache->unlock();
         }
-        
+
         PegCount* counts = (PegCount*) host_cache.get_counts();
         for ( int i = 0; pegs[i].type != CountType::END; i++ )
         {
@@ -536,7 +536,7 @@ string HostCacheModule::get_host_cache_segment_stats(int seg_idx)
         cache->stats.items_in_use = cache->list.size();
         cache->unlock();
 
-        PegCount* count = (PegCount*) cache->get_counts();
+        const PegCount* count = cache->get_counts();
         for ( int i = 0; pegs[i].type != CountType::END; i++ )
         {
             if ( count[i] )
@@ -566,7 +566,7 @@ string HostCacheModule::get_host_cache_stats()
         cache->stats.items_in_use = cache->list.size();
         cache->unlock();
     }
-    
+
     PegCount* counts = (PegCount*) host_cache.get_counts();
     const PegInfo* pegs = host_cache.get_pegs();
 
index e417435d5ad500f5a3e2d563305229071b2e4eb4..e80519262e04afe8caf96c5f19b24b1e6d987d63 100644 (file)
@@ -26,6 +26,7 @@
 
 #include <atomic>
 #include <cassert>
+#include <numeric>
 
 #include "host_cache.h"
 #include "log/messages.h"
@@ -38,8 +39,8 @@ template<typename Key, typename Value>
 class HostCacheSegmented
 {
 public:
-    HostCacheSegmented() : 
-        segment_count(DEFAULT_HOST_CACHE_SEGMENTS), 
+    HostCacheSegmented() :
+        segment_count(DEFAULT_HOST_CACHE_SEGMENTS),
         memcap_per_segment(LRU_CACHE_INITIAL_SIZE) { }
     HostCacheSegmented(uint8_t segment_count, size_t memcap_per_segment);
 
@@ -93,7 +94,7 @@ HostCacheSegmented<Key, Value>::HostCacheSegmented(uint8_t segment_count, size_t
     memcap_per_segment(memcap_per_segment)
 {
     assert(segment_count > 0);
-    
+
     for (size_t i = 0; i < this->segment_count; ++i)
     {
         auto cache = new HostCacheIp(this->memcap_per_segment);
@@ -109,7 +110,7 @@ void HostCacheSegmented<Key, Value>::init()
         return;
 
     assert(segment_count > 0);
-    
+
     for (size_t i = 0; i < segment_count; ++i)
     {
         auto cache = new HostCacheIp(memcap_per_segment.load());
@@ -139,16 +140,16 @@ void HostCacheSegmented<Key, Value>::setup(uint8_t segs, size_t memcap )
 }
 
 template<typename Key, typename Value>
-size_t HostCacheSegmented<Key, Value>::get_valid_id(uint8_t idx) 
-{ 
+size_t HostCacheSegmented<Key, Value>::get_valid_id(uint8_t idx)
+{
     if(idx < seg_list.size())
         return seg_list[idx]->get_valid_id();
     return 0;
 }
 
 template<typename Key, typename Value>
-void HostCacheSegmented<Key, Value>::print_config() 
-{ 
+void HostCacheSegmented<Key, Value>::print_config()
+{
     if ( snort::SnortConfig::log_verbose() )
     {
         snort::LogLabel("host_cache");
@@ -180,7 +181,7 @@ bool HostCacheSegmented<Key, Value>::set_max_size(size_t max_size)
 }
 
 /**
- * Resize the cache based on the provided memory capacity, distributing the 
+ * Resize the cache based on the provided memory capacity, distributing the
  * memory equally among all the segments. If any segment fails to resize,
  * the operation is considered unsuccessful.
  */
@@ -199,11 +200,11 @@ bool HostCacheSegmented<Key, Value>::reload_resize(size_t memcap)
 
 // Computes the index of the segment where a given key-value pair belongs.
 template<typename Key, typename Value>
-uint8_t HostCacheSegmented<Key, Value>::get_segment_idx(Key val) 
+uint8_t HostCacheSegmented<Key, Value>::get_segment_idx(Key val)
 {
     const uint8_t* bytes = reinterpret_cast<const uint8_t*>(&val);
     uint8_t result = 0;
-    for (size_t i = 0; i < sizeof(Key); ++i) 
+    for (size_t i = 0; i < sizeof(Key); ++i)
         result ^= bytes[i];
     //Assumes segment_count is a power of 2 always
     //This is a fast way to do a modulo operation
@@ -232,7 +233,7 @@ std::shared_ptr<Value> HostCacheSegmented<Key, Value>::find(const Key& key)
 }
 
 /**
- * Updates the internal counts of the host cache. This method aggregates the 
+ * Updates the internal counts of the host cache. This method aggregates the
  * counts from all segments and updates the overall counts for the cache.
  */
 template<typename Key, typename Value>
@@ -245,9 +246,7 @@ void HostCacheSegmented<Key, Value>::update_counts()
     {
         PegCount c = 0;
         for(auto cache : seg_list)
-        {
             c += cache->get_counts()[i];
-        }
         pcs[i] = c;
     }
 }
@@ -258,7 +257,7 @@ std::shared_ptr<Value> HostCacheSegmented<Key, Value>:: find_else_create(const K
     // Determine the segment index where the key-value pair resides or should reside
     uint8_t idx = get_segment_idx(key);
     bool new_data_local = false;
-    
+
     // Retrieve or create the entry for the key in the determined segment
     auto ht = seg_list[idx]->find_else_create(key, &new_data_local);
     if(new_data_local)
@@ -326,9 +325,7 @@ size_t HostCacheSegmented<Key, Value>::get_max_size()
 {
     size_t max_size = 0;
     for (auto cache : seg_list)
-    {
         max_size += cache->get_max_size();
-    }
     return max_size;
 }
 
@@ -340,7 +337,7 @@ size_t HostCacheSegmented<Key, Value>::get_mem_chunk()
 }
 
 template<typename Key, typename Value>
-bool HostCacheSegmented<Key, Value>::remove(const Key& key) 
+bool HostCacheSegmented<Key, Value>::remove(const Key& key)
 {
     uint8_t idx = get_segment_idx(key);
     return seg_list[idx]->remove(key);
@@ -358,19 +355,19 @@ Warning!!!: update_allocator and update_set_allocator don't copy data to old con
 but erase it for speed. Use with care!!!
 */
 template <template <typename, typename...> class Container, typename T, typename Alloc>
-void update_allocator(Container<T, Alloc>& cont, CacheInterface* new_lru) 
+void update_allocator(Container<T, Alloc>& cont, CacheInterface* new_lru)
 {
     Alloc new_allocator;
     new_allocator.set_cache(new_lru);
     cont = std::move(Container<T, Alloc>(new_allocator));
-} 
+}
 
 template <template <typename, typename, typename...> class Container, typename T, typename Comp, typename Alloc>
-void update_set_allocator(Container<T, Comp, Alloc>& cont, CacheInterface* new_lru) 
+void update_set_allocator(Container<T, Comp, Alloc>& cont, CacheInterface* new_lru)
 {
     Alloc new_allocator;
     new_allocator.set_cache(new_lru);
-    cont = std::move(Container<T, Comp, Alloc> (new_allocator)); 
+    cont = std::move(Container<T, Comp, Alloc> (new_allocator));
 }
 
 
index d890b0fa705b7642152553509fa8824a119f8f4f..77afcad83bd702cd393debe072fa527f2c790876 100644 (file)
@@ -44,11 +44,9 @@ THREAD_LOCAL struct HostTrackerStats host_tracker_stats;
 const uint8_t snort::zero_mac[MAC_SIZE] = {0, 0, 0, 0, 0, 0};
 
 
-
-HostTracker::HostTracker() : hops(-1)
+HostTracker::HostTracker()
 {
     last_seen = nat_count_start = (uint32_t) packet_time();
-    last_event = -1;
     visibility = host_cache.get_valid_id(0);
 }
 
@@ -293,7 +291,7 @@ bool HostTracker::reset_hops_if_primary()
 {
     lock_guard<mutex> lck(host_tracker_lock);
 
-    for ( auto& hm : macs )
+    for ( const auto& hm : macs )
         if ( hm.primary and hm.visibility )
         {
             if ( !hops )
@@ -343,28 +341,29 @@ bool HostTracker::add_service(Port port, IpProtocol proto, AppId appid, bool inf
     host_tracker_stats.service_adds++;
     lock_guard<mutex> lck(host_tracker_lock);
 
-    for ( auto& s : services )
+    auto it = std::find_if(services.begin(), services.end(),
+        [port, proto](const HostApplication& s)
+        { return s.port == port and s.proto == proto; });
+    if (it != services.end())
     {
-        if ( s.port == port and s.proto == proto )
+        HostApplication& s = *it;
+        if ( s.appid != appid and appid != APP_ID_NONE )
         {
-            if ( s.appid != appid and appid != APP_ID_NONE )
-            {
-                s.appid = appid;
-                s.inferred_appid = inferred_appid;
-                if ( added )
-                    *added = true;
-            }
-
-            if ( s.visibility == false )
-            {
-                if ( added )
-                    *added = true;
-                s.visibility = true;
-                num_visible_services++;
-            }
+            s.appid = appid;
+            s.inferred_appid = inferred_appid;
+            if ( added )
+                *added = true;
+        }
 
-            return true;
+        if ( !s.visibility )
+        {
+            if ( added )
+                *added = true;
+            s.visibility = true;
+            num_visible_services++;
         }
+
+        return true;
     }
 
     services.emplace_back(port, proto, appid, inferred_appid);
@@ -394,46 +393,49 @@ bool HostTracker::add_client_payload(HostClient& hc, AppId payload, size_t max_p
     Payload_t* invisible_swap_candidate = nullptr;
     std::lock_guard<std::mutex> lck(host_tracker_lock);
 
-    for ( auto& client : clients )
-        if ( client.id == hc.id and client.service == hc.service )
+    auto it = std::find_if(clients.begin(), clients.end(),
+        [&hc](const HostClient& c)
+        { return c.id == hc.id and c.service == hc.service; });
+    if (it != clients.end())
+    {
+        HostClient& client = *it;
+        for ( auto& pld : client.payloads )
         {
-            for ( auto& pld : client.payloads )
+            if ( pld.first == payload )
             {
-                if ( pld.first == payload )
-                {
-                    if ( pld.second )
-                        return false;
-
-                    pld.second = true;
-                    client.num_visible_payloads++;
-                    hc.payloads = client.payloads;
-                    strncpy(hc.version, client.version, INFO_SIZE);
-                    return true;
-                }
-                if ( !invisible_swap_candidate and !pld.second )
-                    invisible_swap_candidate = &pld;
-            }
+                if ( pld.second )
+                    return false;
 
-            if ( invisible_swap_candidate )
-            {
-                invisible_swap_candidate->second = true;
-                invisible_swap_candidate->first = payload;
+                pld.second = true;
                 client.num_visible_payloads++;
                 hc.payloads = client.payloads;
                 strncpy(hc.version, client.version, INFO_SIZE);
                 return true;
             }
+            if ( !invisible_swap_candidate and !pld.second )
+                invisible_swap_candidate = &pld;
+        }
 
-            if ( client.payloads.size() >= max_payloads )
-                return false;
-
-            client.payloads.emplace_back(payload, true);
+        if ( invisible_swap_candidate )
+        {
+            invisible_swap_candidate->second = true;
+            invisible_swap_candidate->first = payload;
+            client.num_visible_payloads++;
             hc.payloads = client.payloads;
             strncpy(hc.version, client.version, INFO_SIZE);
-            client.num_visible_payloads++;
             return true;
         }
 
+        if ( client.payloads.size() >= max_payloads )
+            return false;
+
+        client.payloads.emplace_back(payload, true);
+        hc.payloads = client.payloads;
+        strncpy(hc.version, client.version, INFO_SIZE);
+        client.num_visible_payloads++;
+        return true;
+    }
+
     return false;
 }
 
@@ -442,28 +444,29 @@ bool HostTracker::add_service(const HostApplication& app, bool* added)
     host_tracker_stats.service_adds++;
     lock_guard<mutex> lck(host_tracker_lock);
 
-    for ( auto& s : services )
+    auto it = std::find_if(services.begin(), services.end(),
+        [&app](const HostApplication& s)
+        { return s.port == app.port and s.proto == app.proto; });
+    if (it != services.end())
     {
-        if ( s.port == app.port and s.proto == app.proto )
+        HostApplication& s = *it;
+        if ( s.appid != app.appid and app.appid != APP_ID_NONE )
         {
-            if ( s.appid != app.appid and app.appid != APP_ID_NONE )
-            {
-                s.appid = app.appid;
-                s.inferred_appid = app.inferred_appid;
-                if ( added )
-                    *added = true;
-            }
-
-            if ( s.visibility == false )
-            {
-                if ( added )
-                    *added = true;
-                s.visibility = true;
-                num_visible_services++;
-            }
+            s.appid = app.appid;
+            s.inferred_appid = app.inferred_appid;
+            if ( added )
+                *added = true;
+        }
 
-            return true;
+        if ( !s.visibility )
+        {
+            if ( added )
+                *added = true;
+            s.visibility = true;
+            num_visible_services++;
         }
+
+        return true;
     }
 
     services.emplace_back(app.port, app.proto, app.appid, app.inferred_appid);
@@ -499,15 +502,17 @@ size_t HostTracker::get_service_count()
 
 HostApplication* HostTracker::find_service_no_lock(Port port, IpProtocol proto, AppId appid)
 {
-    for ( auto& s : services )
+    auto it = std::find_if(services.begin(), services.end(),
+        [port, proto, appid](const HostApplication& s)
+        { return s.port == port and s.proto == proto
+            and (s.visibility or (appid != APP_ID_NONE and s.appid == appid)); });
+    if (it != services.end())
     {
-        if ( s.port == port and s.proto == proto )
-        {
-            if ( s.visibility == false )
-                return nullptr;
-            if ( appid != APP_ID_NONE and s.appid == appid )
-                return &s;
-        }
+        HostApplication& s = *it;
+        if ( s.visibility == false )
+            return nullptr;
+        if ( appid != APP_ID_NONE and s.appid == appid )
+            return &s;
     }
 
     return nullptr;
@@ -610,14 +615,13 @@ void HostTracker::update_service(const HostApplication& ha)
     host_tracker_stats.service_finds++;
     lock_guard<mutex> lck(host_tracker_lock);
 
-    for ( auto& s : services )
+    auto it = std::find_if(services.begin(), services.end(),
+        [&ha](const HostApplication& s){ return s.port == ha.port and s.proto == ha.proto; });
+    if (it != services.end())
     {
-        if ( s.port == ha.port and s.proto == ha.proto )
-        {
-            s.hits = ha.hits;
-            s.last_seen = ha.last_seen;
-            return;
-        }
+        HostApplication& s = *it;
+        s.hits = ha.hits;
+        s.last_seen = ha.last_seen;
     }
 }
 
@@ -657,7 +661,7 @@ bool HostTracker::update_service_info(HostApplication& ha, const char* vendor,
     {
         if ( s.port == ha.port and s.proto == ha.proto )
         {
-            if ( s.visibility == false )
+            if ( !s.visibility )
                 return false;
 
             if ( !version and !vendor )
@@ -669,7 +673,7 @@ bool HostTracker::update_service_info(HostApplication& ha, const char* vendor,
                 if ( (version and !strncmp(version, i.version, INFO_SIZE-1)) and
                     (vendor and !strncmp(vendor, i.vendor, INFO_SIZE-1)) )
                 {
-                    if ( i.visibility == false )
+                    if ( !i.visibility )
                     {
                         i.visibility = true;  // rediscover it
                         update_ha_no_lock(ha, s);
@@ -737,7 +741,7 @@ bool HostTracker::update_service_user(Port port, IpProtocol proto, const char* u
     // Appid notifies user events before service events, so use find or add service function.
     HostApplication* ha = find_and_add_service_no_lock(port, proto, lseen, is_new, 0,
         max_services);
-    if ( !ha or ha->visibility == false )
+    if ( !(ha and ha->visibility) )
         return false;
 
     if ( user and strncmp(user, ha->user, INFO_SIZE-1) )
@@ -876,13 +880,13 @@ bool HostTracker::is_visible() const
 bool HostTracker::set_network_proto_visibility(uint16_t proto, bool v)
 {
     std::lock_guard<std::mutex> lck(host_tracker_lock);
-    for ( auto& pp : network_protos )
+    auto it = std::find_if(network_protos.begin(), network_protos.end(),
+        [proto](const HostTracker::NetProto_t&pp)
+        { return pp.first == proto; });
+    if (it != network_protos.end())
     {
-        if ( pp.first == proto )
-        {
-            pp.second = v;
-            return true;
-        }
+        (*it).second = v;
+        return true;
     }
     return false;
 }
@@ -890,59 +894,61 @@ bool HostTracker::set_network_proto_visibility(uint16_t proto, bool v)
 bool HostTracker::set_xproto_visibility(uint8_t proto, bool v)
 {
     std::lock_guard<std::mutex> lck(host_tracker_lock);
-    for ( auto& pp : xport_protos )
+    auto it = std::find_if(xport_protos.begin(), xport_protos.end(),
+        [proto](const HostTracker::XProto_t& pp)
+        { return pp.first == proto; });
+    if (it != xport_protos.end())
     {
-        if ( pp.first == proto )
-        {
-            pp.second = v;
-            return true;
-        }
+        (*it).second = v;
+        return true;
     }
     return false;
 }
 
 void HostTracker::set_payload_visibility_no_lock(PayloadVector& pv, bool v, size_t& num_vis)
 {
-    for ( auto& p : pv )
-    {
-        if ( p.second != v )
+    std::for_each(pv.begin(), pv.end(),
+        [v, &num_vis](Payload_t& p)
         {
-            p.second = v;
-            if ( v )
-                num_vis++;
-            else
-                num_vis--;
-        }
-    }
+            if ( p.second != v )
+            {
+                p.second = v;
+                if ( v )
+                    num_vis++;
+                else
+                    num_vis--;
+            }
+        });
 }
 
 bool HostTracker::set_service_visibility(Port port, IpProtocol proto, bool v)
 {
     std::lock_guard<std::mutex> lck(host_tracker_lock);
-    for ( auto& s : services )
+    auto it = std::find_if(services.begin(), services.end(),
+        [port, proto](const HostApplication& s)
+        { return s.port == port and s.proto == proto; });
+    if (it != services.end())
     {
-        if ( s.port == port and s.proto == proto )
+        HostApplication& s = *it;
+        if ( s.visibility and !v )
         {
-            if ( s.visibility == true and v == false )
-            {
-                assert(num_visible_services > 0);
-                num_visible_services--;
-            }
-            else if ( s.visibility == false and v == true )
-                num_visible_services++;
-
-            s.visibility = v;
-            if ( s.visibility == false )
-            {
-                for ( auto& info : s.info )
-                    info.visibility = false;
-                s.user[0] = '\0';
-                s.banner_updated = false;
-            }
+            assert(num_visible_services > 0);
+            num_visible_services--;
+        }
+        else if ( !s.visibility and v )
+            num_visible_services++;
 
-            set_payload_visibility_no_lock(s.payloads, v, s.num_visible_payloads);
-            return true;
+        s.visibility = v;
+        if ( !s.visibility )
+        {
+            for ( auto& info : s.info )
+                info.visibility = false;
+            s.user[0] = '\0';
+            s.banner_updated = false;
         }
+
+        set_payload_visibility_no_lock(s.payloads, v, s.num_visible_payloads);
+        return true;
     }
     return false;
 }
@@ -955,12 +961,12 @@ bool HostTracker::set_client_visibility(const HostClient& hc, bool v)
     {
         if ( c == hc )
         {
-            if ( c.visibility == true and v == false )
+            if ( c.visibility and !v )
             {
                 assert(num_visible_clients > 0 );
                 num_visible_clients--;
             }
-            else if ( c.visibility == false and v == true )
+            else if ( !c.visibility and v )
                 num_visible_clients++;
 
             c.visibility = v;
@@ -1030,7 +1036,7 @@ HostClient HostTracker::find_or_add_client(AppId id, const char* version, AppId
             and ((c.version[0] == '\0' and !version) or
             (version and strncmp(c.version, version, INFO_SIZE-1) == 0)) )
         {
-            if ( c.visibility == false )
+            if ( !c.visibility )
             {
                 is_new = true;
                 c.visibility = true;
@@ -1117,7 +1123,7 @@ void HostTracker::update_cache_interface(uint8_t idx)
     std::lock_guard<std::mutex> lock(host_tracker_lock);
     cache_idx = idx;
     cache_interface = host_cache.seg_list[idx];
-    
+
     update_allocator(macs, cache_interface);
     update_allocator(network_protos, cache_interface);
     update_allocator(xport_protos, cache_interface);
@@ -1196,7 +1202,7 @@ void HostTracker::stringify(string& str)
 
         for ( const auto& s : services )
         {
-            if ( s.visibility == false )
+            if ( !s.visibility )
                 continue;
 
             str += "\n    port: " + to_string(s.port)
@@ -1211,7 +1217,7 @@ void HostTracker::stringify(string& str)
             if ( !s.info.empty() )
                 for ( const auto& i : s.info )
                 {
-                    if ( i.visibility == false )
+                    if ( !i.visibility )
                         continue;
 
                     if ( i.vendor[0] != '\0' )
@@ -1241,7 +1247,7 @@ void HostTracker::stringify(string& str)
         str += "\nclients size: " + to_string(num_visible_clients);
         for ( const auto& c : clients )
         {
-            if ( c.visibility == false )
+            if ( !c.visibility )
                 continue;
 
             str += "\n    id: " + to_string(c.id)
index f9d5754764a621b4bdb0f2fd64bdc916ab7ef25e..8f033cc5dda7420956f5aba8eb1f26525354c179 100644 (file)
@@ -113,11 +113,13 @@ struct HostApplication
         visibility = ha.visibility;
         banner_updated = ha.banner_updated;
         num_visible_payloads = ha.num_visible_payloads;
+        memcpy(user, ha.user, sizeof(user));
+        user_login = ha.user_login;
         return *this;
     }
 
     Port port = 0;
-    IpProtocol proto;
+    IpProtocol proto = IpProtocol::PROTO_NOT_SET;
     AppId appid = APP_ID_NONE;
     bool inferred_appid = false;
     uint32_t hits = 0;
@@ -144,9 +146,9 @@ struct HostClient
 {
     HostClient() = default;
     HostClient(AppId clientid, const char *ver, AppId ser);
-    AppId id;
+    AppId id = APP_ID_NONE;
     char version[INFO_SIZE] = { '\0' };
-    AppId service;
+    AppId service = APP_ID_NONE;
     PayloadVector payloads;
     size_t num_visible_payloads = 0;
 
@@ -444,9 +446,9 @@ private:
 
     mutable std::mutex host_tracker_lock; // ensure that updates to a shared object are safe
     mutable std::mutex flows_lock;        // protect the flows set separately
-    uint8_t hops;                 // hops from the snort inspector, e.g., zero for ARP
+    uint8_t hops = ~0;                 // hops from the snort inspector, e.g., zero for ARP
     uint32_t last_seen;           // the last time this host was seen
-    uint32_t last_event;          // the last time an event was generated
+    uint32_t last_event = ~0;          // the last time an event was generated
 
     // list guarantees iterator validity on insertion
     std::list<HostMac_t, HostCacheAllocIp<HostMac_t>> macs;
@@ -465,7 +467,7 @@ private:
     std::unordered_set<RNAFlow*> flows;
 
     bool vlan_tag_present = false;
-    vlan::VlanTagHdr vlan_tag;
+    vlan::VlanTagHdr vlan_tag = {};
     HostType host_type = HOST_TYPE_HOST;
     uint8_t ip_ttl = 0;
     uint32_t nat_count = 0;
index f7b49cc21b1ff6d9d2cf07791438fe5e8b1de106..3306b3c7e9b775b3e8806b947492079c636c162e 100644 (file)
@@ -62,7 +62,7 @@ private:
 
     std::vector<snort::HostApplication> apps;
     snort::HostApplication app;
-    snort::SfIp addr;
+    snort::SfIp addr = {};
 };
 
 #endif
index 7b6961410beae891c008183ef32663592494ac82..7f1ba103a0fdc044474c8990c9d0c7ebe1f65105 100644 (file)
@@ -73,14 +73,14 @@ public:
 
 // Instantiate a cache, as soon as we know the Item type:
 typedef LruCacheSharedMemcap<string, Item, hash<string>> CacheType;
-CacheType cache(100);
+CacheType lru_cache(100);
 
 // Implement the allocator constructor AFTER we have a cache object
 // to point to and the implementation of our base CacheAlloc:
 template <class T>
 Alloc<T>::Alloc()
 {
-    lru = &cache;
+    lru = &lru_cache;
 }
 
 namespace snort
@@ -102,19 +102,19 @@ TEST(cache_allocator, allocate)
     // room for n items in the cache and m data in the Item.
     const size_t max_size = n * item_sz + m * item_data_sz;
 
-    cache.set_max_size(max_size);
+    lru_cache.set_max_size(max_size);
 
     // insert n empty host trackers:
     for (size_t i=0; i<n; i++)
     {
         string key = to_string(i);
-        auto item_ptr = cache[key];
+        auto item_ptr = lru_cache[key];
         CHECK( item_ptr != nullptr );
     }
 
     // grow the oldest item in the cache enough to trigger pruning:
     string key = to_string(0);
-    auto item_ptr = cache[key];
+    auto item_ptr = lru_cache[key];
     CHECK( item_ptr != nullptr );
 
     for (size_t i = 0; i<m; i++)
@@ -122,10 +122,10 @@ TEST(cache_allocator, allocate)
 
     // the oldest (0) is no longer the oldest after the look-up above,
     // so it should still be in the cache:
-    CHECK( cache.find(key) != nullptr );
+    CHECK( lru_cache.find(key) != nullptr );
 
     // however, the second oldest should have become oldest and be pruned:
-    CHECK( cache.find(to_string(1)) == nullptr );
+    CHECK( lru_cache.find(to_string(1)) == nullptr );
 }
 
 int main(int argc, char** argv)
index 06d8591ed91adbbd49c7e14dfe1adc351449a173..965cc1a9814ae07cc62d4ab13237d1ac4c053abf 100644 (file)
@@ -50,7 +50,8 @@ static HostCacheModule module;
 static char logged_message[LOG_MAX+1];
 
 static ControlConn ctrlcon(1, true);
-ControlConn::ControlConn(int, bool) {}
+ControlConn::ControlConn(int, bool) : shell(nullptr), fd(-1), touched(0)
+{ }
 ControlConn::~ControlConn() {}
 void ControlConn::log_command(const std::string& , bool ) { }
 ControlConn* ControlConn::query_from_lua(const lua_State*) { return &ctrlcon; }
index 6edf458ac8c162bf14e3e57021e3ce887f745290..d790ecd1e318bf369f436118fe9e6ffddc100953 100644 (file)
@@ -98,10 +98,10 @@ TEST(host_tracker, add_rediscover_service_payload_test)
     auto services = ht.get_services();
 
     // Verify we added the services, payload visibility == true
-    for (auto& srv : services)
+    for (const auto& srv : services)
     {
         CHECK(true == srv.visibility);
-        for (auto& pld : srv.payloads)
+        for (const auto& pld : srv.payloads)
             CHECK(true == pld.second);
     }
 
@@ -113,11 +113,9 @@ TEST(host_tracker, add_rediscover_service_payload_test)
     for (const auto& srv : services)
     {
         if (srv.port == 80)
-        {
             CHECK(false == srv.visibility);
-            for (const auto& pld : srv.payloads)
-                CHECK(false == pld.second);
-        }
+        for ( const auto& pld : srv.payloads )
+            CHECK(false == pld.second);
     }
 
     // Test rediscovery
@@ -131,11 +129,9 @@ TEST(host_tracker, add_rediscover_service_payload_test)
     for (const auto& srv : services)
     {
         if (srv.port == 80)
-        {
             CHECK(true == srv.visibility);
-            for (const  auto& pld : srv.payloads)
-                CHECK(true == pld.second);
-        }
+        for ( const auto& pld : srv.payloads )
+            CHECK(true == pld.second);
     }
 
     CHECK(2 == services.front().payloads.size());
@@ -162,7 +158,7 @@ TEST(host_tracker, max_payloads_test)
     // Verify we added the services, payload visibility == true
     CHECK(5 == services.front().payloads.size());
 
-    for (auto& pld : services.front().payloads)
+    for (const auto& pld : services.front().payloads)
         CHECK(true == pld.second);
 
     // Delete the service
@@ -278,7 +274,7 @@ TEST(host_tracker, client_payload_max_payloads_test)
     ht.add_client_payload(hc, 666, 5);
     ht.add_client_payload(hc, 777, 5);
     clients = ht.get_clients();
-    for (auto& pld : clients.front().payloads)
+    for (const auto& pld : clients.front().payloads)
     {
         if (pld.first == 666 or pld.first == 777)
         {
index b63666e03862cf5dcd9647d6fdeadeea4047ed2b..a673388b693989d669c226d46fa326fdea90eae6 100644 (file)
@@ -434,8 +434,8 @@ TEST_CASE("set_cursor_bounds", "[byte_extraction_tests]")
     p.data = (const uint8_t*)"Lorem 010 12345 0x75";
     p.dsize = 21;
     Cursor c(&p);
-    const uint8_t* start = nullptr;
-    const uint8_t* ptr = nullptr;
+    const uint8_t* start;
+    const uint8_t* ptr;
     const uint8_t* end = nullptr;
 
     SECTION("4 bytes read, no offset")
@@ -445,7 +445,6 @@ TEST_CASE("set_cursor_bounds", "[byte_extraction_tests]")
         set_cursor_bounds(settings, c, start, ptr, end);
         CHECK(start == p.data);
         CHECK(ptr == p.data);
-        CHECK(end == p.data + 21);
     }
     SECTION("4 byte read, offset = 4")
     {
@@ -454,7 +453,6 @@ TEST_CASE("set_cursor_bounds", "[byte_extraction_tests]")
         set_cursor_bounds(settings, c, start, ptr, end);
         CHECK(start == p.data);
         CHECK(ptr == p.data + 4);
-        CHECK(end == p.data + 21);
     }
     SECTION("4 bytes read, cursor move without relative flag")
     {
@@ -464,7 +462,6 @@ TEST_CASE("set_cursor_bounds", "[byte_extraction_tests]")
         set_cursor_bounds(settings, c, start, ptr, end);
         CHECK(start == p.data);
         CHECK(ptr == p.data);
-        CHECK(end == p.data + 21);
     }
     SECTION("4 bytes read, cursor move with relative flag")
     {
@@ -474,8 +471,9 @@ TEST_CASE("set_cursor_bounds", "[byte_extraction_tests]")
         set_cursor_bounds(settings, c, start, ptr, end);
         CHECK(start == p.data);
         CHECK(ptr == p.data + 3);
-        CHECK(end == p.data + 21);
     }
+
+    CHECK(end == p.data + 21);
 }
 
 TEST_CASE("extract_data valid", "[byte_extraction_tests]")
index 632df73635d311e41784722121523671e292edf7..9f00fa10fe7a16bb3d3559f7df743c5076af47e9 100644 (file)
@@ -41,9 +41,8 @@ static THREAD_LOCAL ProfileStats tcpAckPerfStats;
 class TcpAckOption : public IpsOption
 {
 public:
-    TcpAckOption(const RangeCheck& c) :
-        IpsOption(s_name)
-    { config = c; }
+    TcpAckOption(const RangeCheck& c) : IpsOption(s_name), config(c)
+    { }
 
     uint32_t hash() const override;
     bool operator==(const IpsOption&) const override;
@@ -80,6 +79,7 @@ bool TcpAckOption::operator==(const IpsOption& ips) const
 
 IpsOption::EvalStatus TcpAckOption::eval(Cursor&, Packet* p)
 {
+    // cppcheck-suppress unreadVariable
     RuleProfile profile(tcpAckPerfStats);
 
     if ( p->ptrs.tcph && config.eval(p->ptrs.tcph->th_ack) )
index 97999bb114cefc5a7eae205a4417c933934b8ce1..d8a5acdccc375412d06175a25d8b984b427cea4e 100644 (file)
@@ -59,8 +59,8 @@ struct Base64DecodeData
 class Base64DecodeOption : public IpsOption
 {
 public:
-    Base64DecodeOption(const Base64DecodeData& c) : IpsOption(s_name)
-    { config = c; }
+    Base64DecodeOption(const Base64DecodeData& c) : IpsOption(s_name), config(c)
+    { }
 
 
     uint32_t hash() const override;
@@ -115,6 +115,7 @@ bool Base64DecodeOption::operator==(const IpsOption& ips) const
 
 IpsOption::EvalStatus Base64DecodeOption::eval(Cursor& c, Packet* p)
 {
+    // cppcheck-suppress unreadVariable
     RuleProfile profile(base64PerfStats);
     DataBuffer& base64_decode_buffer = DetectionEngine::get_alt_buffer(p);
     base64_decode_buffer.len = 0;
@@ -284,6 +285,7 @@ public:
 
 IpsOption::EvalStatus Base64DataOption::eval(Cursor& c, Packet* p)
 {
+    // cppcheck-suppress unreadVariable
     RuleProfile profile(base64PerfStats);
     const DataBuffer& base64_decode_buffer = DetectionEngine::get_alt_buffer(p);
 
index 507db287c2f4b14fcf097ddbace22b78f0bf811f..ddbb0b593915a26370204f4282aa83e12d9d1905 100644 (file)
@@ -84,6 +84,7 @@ bool BerDataOption::operator==(const IpsOption& ips) const
 
 IpsOption::EvalStatus BerDataOption::eval(Cursor& c, Packet*)
 {
+    // cppcheck-suppress unreadVariable
     RuleProfile profile(berDataPerfStats);
 
     BerReader ber(c);
index ae4bae042363386e8d1d8afdc30357bdc3c601c1..1466f23c2c415b4cc417106986195a2cb346e23a 100644 (file)
@@ -88,6 +88,7 @@ bool BerSkipOption::operator==(const IpsOption& ips) const
 
 IpsOption::EvalStatus BerSkipOption::eval(Cursor& c, Packet*)
 {
+    // cppcheck-suppress unreadVariable
     RuleProfile profile(berSkipPerfStats);
 
     BerReader ber(c);
index 48303c609940821ab8d271df3ac13794ccad2290..bc0ff398db410362366fba4c6afecf7b62126110 100644 (file)
@@ -40,8 +40,8 @@ static THREAD_LOCAL ProfileStats lenCheckPerfStats;
 class LenOption : public IpsOption
 {
 public:
-    LenOption(const RangeCheck& c, bool r) : IpsOption(s_name)
-    { config = c; relative = r; }
+    LenOption(const RangeCheck& c, bool r) : IpsOption(s_name), config(c), relative(r)
+    { }
 
     uint32_t hash() const override;
     bool operator==(const IpsOption&) const override;
@@ -85,6 +85,7 @@ bool LenOption::operator==(const IpsOption& ips) const
 
 IpsOption::EvalStatus LenOption::eval(Cursor& c, Packet*)
 {
+    // cppcheck-suppress unreadVariable
     RuleProfile profile(lenCheckPerfStats);
     unsigned n = relative ? c.length() : c.size();
 
index 46475dae4e3f6d6ce6491c78285808030b7b5e7f..d2e010af7be4a5b72e41f588f4df2354e7ca8559 100644 (file)
@@ -141,6 +141,7 @@ bool ByteExtractOption::operator==(const IpsOption& ips) const
 
 IpsOption::EvalStatus ByteExtractOption::eval(Cursor& c, Packet* p)
 {
+    // cppcheck-suppress unreadVariable
     RuleProfile profile(byteExtractPerfStats);
 
     uint32_t value = 0;
@@ -626,6 +627,7 @@ TEST_CASE("ByteExtractOption::operator== invalid", "[ips_byte_extract]")
         ByteExtractOption rhs(data_rhs);
         CHECK(lhs != rhs);
     }
+    // cppcheck-suppress memleak
 }
 
 TEST_CASE("ByteExtractOption::hash", "[ips_byte_extract]")
index 24792a9cda85db2dcd98db2e0a05285ce81d3a67..60c3188841a935850939a96cd6b754a60972ddee 100644 (file)
@@ -192,6 +192,7 @@ bool ByteJumpOption::operator==(const IpsOption& ips) const
 
 IpsOption::EvalStatus ByteJumpOption::eval(Cursor& c, Packet* p)
 {
+    // cppcheck-suppress unreadVariable
     RuleProfile profile(byteJumpPerfStats);
 
     ByteJumpData* bjd = (ByteJumpData*)&config;
@@ -631,19 +632,19 @@ TEST_CASE("ByteJumpOption test", "[ips_byte_jump]")
         SECTION("Testing hash with maximum values")
         {
             SetByteJumpMaxValue(byte_jump);
-            ByteJumpOption hash_test_max(byte_jump);
+            ByteJumpOption hash_test_max_opt(byte_jump);
             ByteJumpOption hash_test_equal_max(byte_jump);
 
             SECTION("Hash has same source")
             {
-                CHECK(hash_test_max.hash() == hash_test_equal_max.hash());
+                CHECK(hash_test_max_opt.hash() == hash_test_equal_max.hash());
             }
 
             SECTION("Compare hash from different source")
             {
                 SetByteJumpMaxValue(byte_jump);
-                ByteJumpOption hash_test_max(byte_jump);
-                CHECK(hash_test.hash() != hash_test_max.hash());
+                ByteJumpOption tmp_hash_test_max_opt(byte_jump);
+                CHECK(hash_test.hash() != tmp_hash_test_max_opt.hash());
             }
         }
     }
@@ -870,8 +871,8 @@ TEST_CASE("ByteJumpOption test", "[ips_byte_jump]")
                 byte_jump.align_flag = 0;
                 byte_jump.bitmask_val = 0;
                 ByteJumpOption test_8(byte_jump);
-                REQUIRE((test_8.eval(current_cursor, &test_packet)) == NO_MATCH);
-                REQUIRE(current_cursor.awaiting_data());
+                REQUIRE(NO_MATCH == test_8.eval(current_cursor, &test_packet));
+                REQUIRE(true == current_cursor.awaiting_data());
             }
 
             SECTION("Cursor on the last byte of buffer, bytes_to_extract is bigger than offset")
@@ -953,7 +954,7 @@ TEST_CASE("ByteJumpModule test", "[ips_byte_jump]")
             module_jump.var = buff;
             byte_jump.offset_var = -1;
             module_jump.data = byte_jump;
-            REQUIRE(module_jump.end("tmp", 0, nullptr) == false);
+            REQUIRE(false == module_jump.end("tmp", 0, nullptr));
         }
 
         SECTION("Undefined rule option for offset_var")
@@ -962,14 +963,14 @@ TEST_CASE("ByteJumpModule test", "[ips_byte_jump]")
             module_jump.post_var = buff;
             byte_jump.post_offset_var = -1;
             module_jump.data = byte_jump;
-            REQUIRE(module_jump.end("tmp", 0, nullptr) == false);
+            REQUIRE(false == module_jump.end("tmp", 0, nullptr));
         }
 
         SECTION("From_beginning and from_end options together")
         {
             byte_jump.endianness = 0;
             module_jump.data = byte_jump;
-            REQUIRE(module_jump.end("tmp", 0, nullptr) == false);
+            REQUIRE(false == module_jump.end("tmp", 0, nullptr));
         }
 
         SECTION("Number of bytes in \"bitmask\" value is greater than bytes to extract")
@@ -977,7 +978,7 @@ TEST_CASE("ByteJumpModule test", "[ips_byte_jump]")
             byte_jump.from_beginning_flag = 0;
             byte_jump.bytes_to_extract = 0;
             module_jump.data = byte_jump;
-            REQUIRE(module_jump.end("tmp", 0, nullptr) == false);
+            REQUIRE(false == module_jump.end("tmp", 0, nullptr));
         }
 
         SECTION("byte_jump rule option cannot extract more \
@@ -987,14 +988,14 @@ TEST_CASE("ByteJumpModule test", "[ips_byte_jump]")
             byte_jump.bytes_to_extract = 5;
             byte_jump.string_convert_flag = 0;
             module_jump.data = byte_jump;
-            REQUIRE(module_jump.end("tmp", 0, nullptr) == false);
+            REQUIRE(false == module_jump.end("tmp", 0, nullptr));
         }
 
         SECTION("Case with returned value true")
         {
             byte_jump.from_beginning_flag = 0;
             module_jump.data = byte_jump;
-            REQUIRE(module_jump.end("tmp", 0, nullptr) == true);
+            REQUIRE(true == module_jump.end("tmp", 0, nullptr));
         }
     }
 
@@ -1007,7 +1008,7 @@ TEST_CASE("ByteJumpModule test", "[ips_byte_jump]")
             Parameter param("~count", snort::Parameter::Type::PT_BOOL,
                 nullptr, "default", "help");
             value.set(&param);
-            REQUIRE(module_jump.set(nullptr, value, nullptr) == true);
+            REQUIRE(true == module_jump.set(nullptr, value, nullptr));
         }
 
         SECTION("Case param \"~offset\"")
@@ -1017,7 +1018,7 @@ TEST_CASE("ByteJumpModule test", "[ips_byte_jump]")
                 Parameter param("~offset", snort::Parameter::Type::PT_BOOL,
                     nullptr, "default", "help");
                 value.set(&param);
-                REQUIRE(module_jump.set(nullptr, value, nullptr) == true);
+                REQUIRE(true == module_jump.set(nullptr, value, nullptr));
             }
 
             SECTION("When value has a str")
@@ -1026,7 +1027,7 @@ TEST_CASE("ByteJumpModule test", "[ips_byte_jump]")
                 Parameter param("~offset", snort::Parameter::Type::PT_BOOL,
                     nullptr, "default", "help");
                 value_tmp.set(&param);
-                REQUIRE(module_jump.set(nullptr, value_tmp, nullptr) == true);
+                REQUIRE(true == module_jump.set(nullptr, value_tmp, nullptr));
             }
         }
 
@@ -1035,7 +1036,7 @@ TEST_CASE("ByteJumpModule test", "[ips_byte_jump]")
             Parameter param("relative", snort::Parameter::Type::PT_BOOL,
                 nullptr, "default", "help");
             value.set(&param);
-            REQUIRE(module_jump.set(nullptr, value, nullptr) == true);
+            REQUIRE(true == module_jump.set(nullptr, value, nullptr));
         }
 
         SECTION("Param \"from_beginning\" correct")
@@ -1043,7 +1044,7 @@ TEST_CASE("ByteJumpModule test", "[ips_byte_jump]")
             Parameter param("from_beginning", snort::Parameter::Type::PT_BOOL,
                 nullptr, "default", "help");
             value.set(&param);
-            REQUIRE(module_jump.set(nullptr, value, nullptr) == true);
+            REQUIRE(true == module_jump.set(nullptr, value, nullptr));
         }
 
         SECTION("Case param \"from_end\"")
@@ -1051,7 +1052,7 @@ TEST_CASE("ByteJumpModule test", "[ips_byte_jump]")
             Parameter param("from_end", snort::Parameter::Type::PT_BOOL,
                 nullptr, "default", "help");
             value.set(&param);
-            REQUIRE(module_jump.set(nullptr, value, nullptr) == true);
+            REQUIRE(true == module_jump.set(nullptr, value, nullptr));
         }
 
         SECTION("Case param \"align\"")
@@ -1059,7 +1060,7 @@ TEST_CASE("ByteJumpModule test", "[ips_byte_jump]")
             Parameter param("align", snort::Parameter::Type::PT_BOOL,
                 nullptr, "default", "help");
             value.set(&param);
-            REQUIRE(module_jump.set(nullptr, value, nullptr) == true);
+            REQUIRE(true == module_jump.set(nullptr, value, nullptr));
         }
 
         SECTION("Case param \"multiplier\"")
@@ -1067,7 +1068,7 @@ TEST_CASE("ByteJumpModule test", "[ips_byte_jump]")
             Parameter param("multiplier", snort::Parameter::Type::PT_BOOL,
                 nullptr, "default", "help");
             value.set(&param);
-            REQUIRE(module_jump.set(nullptr, value, nullptr) == true);
+            REQUIRE(true == module_jump.set(nullptr, value, nullptr));
         }
 
         SECTION("Case param \"post_offset\"")
@@ -1077,7 +1078,7 @@ TEST_CASE("ByteJumpModule test", "[ips_byte_jump]")
                 Parameter param("post_offset", snort::Parameter::Type::PT_BOOL,
                     nullptr, "default", "help");
                 value.set(&param);
-                REQUIRE(module_jump.set(nullptr, value, nullptr) == true);
+                REQUIRE(true == module_jump.set(nullptr, value, nullptr));
             }
 
             SECTION("When value has a str")
@@ -1086,7 +1087,7 @@ TEST_CASE("ByteJumpModule test", "[ips_byte_jump]")
                 Parameter param("post_offset", snort::Parameter::Type::PT_BOOL,
                     nullptr, "default", "help");
                 value_tmp.set(&param);
-                REQUIRE(module_jump.set(nullptr, value_tmp, nullptr) == true);
+                REQUIRE(true == module_jump.set(nullptr, value_tmp, nullptr));
             }
         }
 
@@ -1095,7 +1096,7 @@ TEST_CASE("ByteJumpModule test", "[ips_byte_jump]")
             Parameter param("big", snort::Parameter::Type::PT_BOOL,
                 nullptr, "default", "help");
             value.set(&param);
-            REQUIRE(module_jump.set(nullptr, value, nullptr) == true);
+            REQUIRE(true == module_jump.set(nullptr, value, nullptr));
         }
 
         SECTION("Case param \"little\"")
@@ -1103,7 +1104,7 @@ TEST_CASE("ByteJumpModule test", "[ips_byte_jump]")
             Parameter param("little", snort::Parameter::Type::PT_BOOL,
                 nullptr, "default", "help");
             value.set(&param);
-            REQUIRE(module_jump.set(nullptr, value, nullptr) == true);
+            REQUIRE(true == module_jump.set(nullptr, value, nullptr));
         }
 
         SECTION("Case param \"dce\"")
@@ -1111,7 +1112,7 @@ TEST_CASE("ByteJumpModule test", "[ips_byte_jump]")
             Parameter param("dce", snort::Parameter::Type::PT_BOOL,
                 nullptr, "default", "help");
             value.set(&param);
-            REQUIRE(module_jump.set(nullptr, value, nullptr) == true);
+            REQUIRE(true == module_jump.set(nullptr, value, nullptr));
         }
 
         SECTION("Case param \"string\"")
@@ -1119,7 +1120,7 @@ TEST_CASE("ByteJumpModule test", "[ips_byte_jump]")
             Parameter param("string", snort::Parameter::Type::PT_BOOL,
                 nullptr, "default", "help");
             value.set(&param);
-            REQUIRE(module_jump.set(nullptr, value, nullptr) == true);
+            REQUIRE(true == module_jump.set(nullptr, value, nullptr));
         }
 
         SECTION("Case param \"dec\"")
@@ -1127,7 +1128,7 @@ TEST_CASE("ByteJumpModule test", "[ips_byte_jump]")
             Parameter param("dec", snort::Parameter::Type::PT_BOOL,
                 nullptr, "default", "help");
             value.set(&param);
-            REQUIRE(module_jump.set(nullptr, value, nullptr) == true);
+            REQUIRE(true == module_jump.set(nullptr, value, nullptr));
         }
 
         SECTION("Case param \"hex\"")
@@ -1135,7 +1136,7 @@ TEST_CASE("ByteJumpModule test", "[ips_byte_jump]")
             Parameter param("hex", snort::Parameter::Type::PT_BOOL,
                 nullptr, "default", "help");
             value.set(&param);
-            REQUIRE(module_jump.set(nullptr, value, nullptr) == true);
+            REQUIRE(true == module_jump.set(nullptr, value, nullptr));
         }
 
         SECTION("Case param \"oct\"")
@@ -1143,7 +1144,7 @@ TEST_CASE("ByteJumpModule test", "[ips_byte_jump]")
             Parameter param("oct", snort::Parameter::Type::PT_BOOL,
                 nullptr, "default", "help");
             value.set(&param);
-            REQUIRE(module_jump.set(nullptr, value, nullptr) == true);
+            REQUIRE(true == module_jump.set(nullptr, value, nullptr));
         }
 
         SECTION("Case param \"bitmask\"")
@@ -1151,7 +1152,7 @@ TEST_CASE("ByteJumpModule test", "[ips_byte_jump]")
             Parameter param("bitmask", snort::Parameter::Type::PT_BOOL,
                 nullptr, "default", "help");
             value.set(&param);
-            REQUIRE(module_jump.set(nullptr, value, nullptr) == true);
+            REQUIRE(true == module_jump.set(nullptr, value, nullptr));
         }
     }
 }
index ab7420dd9549cd7e4051344788d89290b423060b..be5a45bbbea4532f4cce8000e54e1bfc29b42b78 100644 (file)
@@ -160,6 +160,7 @@ bool ByteMathOption::operator==(const IpsOption& ips) const
 
 IpsOption::EvalStatus ByteMathOption::eval(Cursor& c, Packet* p)
 {
+    // cppcheck-suppress unreadVariable
     RuleProfile profile(byteMathPerfStats);
 
     /* Get values from ips options variables, if present. */
@@ -264,14 +265,14 @@ int ByteMathOption::calc(uint32_t& value, const uint32_t rvalue)
 static void parse_base(uint8_t value, ByteMathData& idx)
 {
     assert(value <= 2);
-    const int base[] = { 16, 10, 8 };
+    static const uint32_t base[] = { 16, 10, 8 };
     idx.base = base[value];
 }
 
 static void parse_endian(uint8_t value, ByteMathData& idx)
 {
     assert(value <= 1);
-    int endian[] = { ENDIAN_BIG, ENDIAN_LITTLE };
+    static const uint8_t endian[] = { ENDIAN_BIG, ENDIAN_LITTLE };
     set_byte_order(idx.endianness, endian[value], "byte_math");
 }
 
@@ -772,6 +773,7 @@ TEST_CASE("ByteMathOption::operator== invalid", "[ips_byte_math]")
         ByteMathOption rhs(data_rhs);
         CHECK(lhs != rhs);
     }
+    // cppcheck-suppress memleak
 }
 
 TEST_CASE("ByteMathOption::hash", "[ips_byte_math]")
index 585d60e6a8fcd305298a467fc03f9d5006f5d040..b727360a0a9c657908fbe32c94d2c8d311b9f965 100644 (file)
@@ -269,6 +269,7 @@ bool ByteTestOption::operator==(const IpsOption& ips) const
 
 IpsOption::EvalStatus ByteTestOption::eval(Cursor& c, Packet* p)
 {
+    // cppcheck-suppress unreadVariable
     RuleProfile profile(byteTestPerfStats);
 
     ByteTestData* btd = (ByteTestData*)&config;
@@ -664,54 +665,54 @@ TEST_CASE("byte_test_check test", "[ips_byte_test]")
 {
     SECTION("Incorrect ByteTestOper, other data correct")
     {
-        REQUIRE(byte_test_check(ByteTestOper(7), 1, 1, 0) == false);
+        REQUIRE(false == byte_test_check(ByteTestOper(7), 1, 1, 0));
     }
 
     SECTION("Incorrect ByteTestOper, true not_flag")
     {
-        REQUIRE(byte_test_check(ByteTestOper(7), 1, 1, 1) == true);
+        REQUIRE(true == byte_test_check(ByteTestOper(7), 1, 1, 1));
     }
 
     SECTION("CHECK_EQ both true && false situation")
     {
-        REQUIRE(byte_test_check(ByteTestOper(0), 1, 1, 0) == true);
-        REQUIRE(byte_test_check(ByteTestOper(0), 1, 2, 0) == false);
+        REQUIRE(true == byte_test_check(ByteTestOper(0), 1, 1, 0));
+        REQUIRE(false == byte_test_check(ByteTestOper(0), 1, 2, 0));
     }
 
     SECTION("CHECK_LT both true && false situation")
     {
-        REQUIRE(byte_test_check(ByteTestOper(1), 1, 2, 0) == true);
-        REQUIRE(byte_test_check(ByteTestOper(1), 4, 1, 0) == false);
+        REQUIRE(true == byte_test_check(ByteTestOper(1), 1, 2, 0));
+        REQUIRE(false == byte_test_check(ByteTestOper(1), 4, 1, 0));
     }
 
     SECTION("CHECK_GT both true && false situation")
     {
-        REQUIRE(byte_test_check(ByteTestOper(2), 2, 1, 0) == true);
-        REQUIRE(byte_test_check(ByteTestOper(2), 1, 4, 0) == false);
+        REQUIRE(true == byte_test_check(ByteTestOper(2), 2, 1, 0));
+        REQUIRE(false == byte_test_check(ByteTestOper(2), 1, 4, 0));
     }
 
     SECTION("CHECK_LTE both true && false situation")
     {
-        REQUIRE(byte_test_check(ByteTestOper(3), 0, 1, 0) == true);
-        REQUIRE(byte_test_check(ByteTestOper(3), 4, 1, 0) == false);
+        REQUIRE(true == byte_test_check(ByteTestOper(3), 0, 1, 0));
+        REQUIRE(false == byte_test_check(ByteTestOper(3), 4, 1, 0));
     }
 
     SECTION("CHECK_GTE both true && false situation")
     {
-        REQUIRE(byte_test_check(ByteTestOper(4), 1, 0, 0) == true);
-        REQUIRE(byte_test_check(ByteTestOper(4), 0, 4, 0) == false);
+        REQUIRE(true == byte_test_check(ByteTestOper(4), 1, 0, 0));
+        REQUIRE(false == byte_test_check(ByteTestOper(4), 0, 4, 0));
     }
 
     SECTION("CHECK_AND for bites both true && false situation")
     {
-        REQUIRE(byte_test_check(ByteTestOper(5), 1, 1, 0) == true);
-        REQUIRE(byte_test_check(ByteTestOper(5), 1, 0, 0) == false);
+        REQUIRE(true == byte_test_check(ByteTestOper(5), 1, 1, 0));
+        REQUIRE(false == byte_test_check(ByteTestOper(5), 1, 0, 0));
     }
 
     SECTION("CHECK_XOR for bites both true && false situation")
     {
-        REQUIRE(byte_test_check(ByteTestOper(6), 1, 0, 0) == true);
-        REQUIRE(byte_test_check(ByteTestOper(6), 1, 1, 0) == false);
+        REQUIRE(true == byte_test_check(ByteTestOper(6), 1, 0, 0));
+        REQUIRE(false == byte_test_check(ByteTestOper(6), 1, 1, 0));
     }
 }
 
@@ -754,8 +755,8 @@ TEST_CASE("ByteTestOption test", "[ips_byte_test]")
             SECTION("Testing hash with maximum values from different source")
             {
                 SetByteTestDataMax(byte_test);
-                ByteTestOption hash_test_max(byte_test);
-                CHECK(hash_test.hash() != hash_test_max.hash());
+                ByteTestOption tmp_hash_test_max(byte_test);
+                CHECK(hash_test.hash() != tmp_hash_test_max.hash());
             }
         }
     }
@@ -1028,7 +1029,7 @@ TEST_CASE("ByteTestModule test", "[ips_byte_test]")
         {
             module_test.cmp_var = buff;
             module_test.data = byte_test;
-            REQUIRE(module_test.end("tmp", 0, nullptr) == false);
+            REQUIRE(false == module_test.end("tmp", 0, nullptr));
         }
 
         SECTION("Undefined rule option for offset_var")
@@ -1036,7 +1037,7 @@ TEST_CASE("ByteTestModule test", "[ips_byte_test]")
             module_test.cmp_var.clear();
             module_test.off_var = buff;
             module_test.data = byte_test;
-            REQUIRE(module_test.end("tmp", 0, nullptr) == false);
+            REQUIRE(false == module_test.end("tmp", 0, nullptr));
         }
 
         SECTION("Number of bytes in \"bitmask\" value is greater than bytes to extract")
@@ -1044,13 +1045,13 @@ TEST_CASE("ByteTestModule test", "[ips_byte_test]")
             byte_test.endianness = 0;
             byte_test.bytes_to_extract = 0;
             module_test.data = byte_test;
-            REQUIRE(module_test.end("tmp", 0, nullptr) == false);
+            REQUIRE(false == module_test.end("tmp", 0, nullptr));
         }
 
         SECTION("Case with returned value true")
         {
             module_test.data = byte_test;
-            REQUIRE(module_test.end("tmp", 0, nullptr) == true);
+            REQUIRE(true == module_test.end("tmp", 0, nullptr));
         }
     }
 
@@ -1063,7 +1064,7 @@ TEST_CASE("ByteTestModule test", "[ips_byte_test]")
             Parameter param("~count", snort::Parameter::Type::PT_BOOL,
                 nullptr, "default", "help");
             value.set(&param);
-            REQUIRE(module_test.set(nullptr, value, nullptr) == true);
+            REQUIRE(true == module_test.set(nullptr, value, nullptr));
         }
 
         SECTION("Param \"~operator\" correct")
@@ -1071,7 +1072,7 @@ TEST_CASE("ByteTestModule test", "[ips_byte_test]")
             Parameter param("~operator", snort::Parameter::Type::PT_BOOL,
                 nullptr, "default", "help");
             value.set(&param);
-            REQUIRE(module_test.set(nullptr, value, nullptr) == true);
+            REQUIRE(true == module_test.set(nullptr, value, nullptr));
         }
 
         SECTION("Case param \"~compare\"")
@@ -1081,7 +1082,7 @@ TEST_CASE("ByteTestModule test", "[ips_byte_test]")
                 Parameter param("~compare", snort::Parameter::Type::PT_BOOL,
                     nullptr, "default", "help");
                 value.set(&param);
-                REQUIRE(module_test.set(nullptr, value, nullptr) == true);
+                REQUIRE(true == module_test.set(nullptr, value, nullptr));
             }
 
             SECTION("When value has a str")
@@ -1090,7 +1091,7 @@ TEST_CASE("ByteTestModule test", "[ips_byte_test]")
                 Parameter param("~compare", snort::Parameter::Type::PT_BOOL,
                     nullptr, "default", "help");
                 value_tmp.set(&param);
-                REQUIRE(module_test.set(nullptr, value_tmp, nullptr) == true);
+                REQUIRE(true == module_test.set(nullptr, value_tmp, nullptr));
             }
 
             SECTION("Value isn't truncated")
@@ -1099,7 +1100,7 @@ TEST_CASE("ByteTestModule test", "[ips_byte_test]")
                 Parameter param("~compare", snort::Parameter::Type::PT_BOOL,
                     nullptr, "default", "help");
                 value_tmp.set(&param);
-                REQUIRE(module_test.set(nullptr, value_tmp, nullptr) == true);
+                REQUIRE(true == module_test.set(nullptr, value_tmp, nullptr));
                 REQUIRE(module_test.data.cmp_value == 4294967295UL);
             }
         }
@@ -1111,7 +1112,7 @@ TEST_CASE("ByteTestModule test", "[ips_byte_test]")
                 Parameter param("~offset", snort::Parameter::Type::PT_BOOL,
                     nullptr, "default", "help");
                 value.set(&param);
-                REQUIRE(module_test.set(nullptr, value, nullptr) == true);
+                REQUIRE(true == module_test.set(nullptr, value, nullptr));
             }
 
             SECTION("When value has a str")
@@ -1120,7 +1121,7 @@ TEST_CASE("ByteTestModule test", "[ips_byte_test]")
                 Parameter param("~offset", snort::Parameter::Type::PT_BOOL,
                     nullptr, "default", "help");
                 value_tmp.set(&param);
-                REQUIRE(module_test.set(nullptr, value_tmp, nullptr) == true);
+                REQUIRE(true == module_test.set(nullptr, value_tmp, nullptr));
             }
         }
 
@@ -1129,7 +1130,7 @@ TEST_CASE("ByteTestModule test", "[ips_byte_test]")
             Parameter param("relative", snort::Parameter::Type::PT_BOOL,
                 nullptr, "default", "help");
             value.set(&param);
-            REQUIRE(module_test.set(nullptr, value, nullptr) == true);
+            REQUIRE(true == module_test.set(nullptr, value, nullptr));
         }
 
         SECTION("Case param \"big\"")
@@ -1137,7 +1138,7 @@ TEST_CASE("ByteTestModule test", "[ips_byte_test]")
             Parameter param("big", snort::Parameter::Type::PT_BOOL,
                 nullptr, "default", "help");
             value.set(&param);
-            REQUIRE(module_test.set(nullptr, value, nullptr) == true);
+            REQUIRE(true == module_test.set(nullptr, value, nullptr));
         }
 
         SECTION("Case param \"little\"")
@@ -1145,7 +1146,7 @@ TEST_CASE("ByteTestModule test", "[ips_byte_test]")
             Parameter param("little", snort::Parameter::Type::PT_BOOL,
                 nullptr, "default", "help");
             value.set(&param);
-            REQUIRE(module_test.set(nullptr, value, nullptr) == true);
+            REQUIRE(true == module_test.set(nullptr, value, nullptr));
         }
 
         SECTION("Case param \"dce\"")
@@ -1153,7 +1154,7 @@ TEST_CASE("ByteTestModule test", "[ips_byte_test]")
             Parameter param("dce", snort::Parameter::Type::PT_BOOL,
                 nullptr, "default", "help");
             value.set(&param);
-            REQUIRE(module_test.set(nullptr, value, nullptr) == true);
+            REQUIRE(true == module_test.set(nullptr, value, nullptr));
         }
 
         SECTION("Case param \"string\"")
@@ -1161,7 +1162,7 @@ TEST_CASE("ByteTestModule test", "[ips_byte_test]")
             Parameter param("string", snort::Parameter::Type::PT_BOOL,
                 nullptr, "default", "help");
             value.set(&param);
-            REQUIRE(module_test.set(nullptr, value, nullptr) == true);
+            REQUIRE(true == module_test.set(nullptr, value, nullptr));
         }
 
         SECTION("Case param \"dec\"")
@@ -1169,7 +1170,7 @@ TEST_CASE("ByteTestModule test", "[ips_byte_test]")
             Parameter param("dec", snort::Parameter::Type::PT_BOOL,
                 nullptr, "default", "help");
             value.set(&param);
-            REQUIRE(module_test.set(nullptr, value, nullptr) == true);
+            REQUIRE(true == module_test.set(nullptr, value, nullptr));
         }
 
         SECTION("Case param \"hex\"")
@@ -1177,7 +1178,7 @@ TEST_CASE("ByteTestModule test", "[ips_byte_test]")
             Parameter param("hex", snort::Parameter::Type::PT_BOOL,
                 nullptr, "default", "help");
             value.set(&param);
-            REQUIRE(module_test.set(nullptr, value, nullptr) == true);
+            REQUIRE(true == module_test.set(nullptr, value, nullptr));
         }
 
         SECTION("Case param \"oct\"")
@@ -1185,7 +1186,7 @@ TEST_CASE("ByteTestModule test", "[ips_byte_test]")
             Parameter param("oct", snort::Parameter::Type::PT_BOOL,
                 nullptr, "default", "help");
             value.set(&param);
-            REQUIRE(module_test.set(nullptr, value, nullptr) == true);
+            REQUIRE(true == module_test.set(nullptr, value, nullptr));
         }
 
         SECTION("Case param \"bitmask\"")
@@ -1193,7 +1194,7 @@ TEST_CASE("ByteTestModule test", "[ips_byte_test]")
             Parameter param("bitmask", snort::Parameter::Type::PT_BOOL,
                 nullptr, "default", "help");
             value.set(&param);
-            REQUIRE(module_test.set(nullptr, value, nullptr) == true);
+            REQUIRE(true == module_test.set(nullptr, value, nullptr));
         }
     }
 }
index 37f1b1e3aaa896a292dc5db26a9ad7750e72b154..c0b27eecaa4a469daaa64ade56ca7c11d782ebb1 100644 (file)
@@ -322,10 +322,10 @@ static bool uniSearchReal(ContentData* cd, Cursor& c)
     else
     {
         // retry - adjust from start of last match
-        pos = c.get_pos() - cd->pmd.pattern_size + cd->match_delta;
+        pos = (int64_t)c.get_pos() - cd->pmd.pattern_size + cd->match_delta;
 
         if ( cd->depth_configured )
-            depth -= c.get_delta();
+            depth -= (int64_t)c.get_delta();
 
         if ( pos < 0 )
             return false;
@@ -361,6 +361,7 @@ static bool uniSearchReal(ContentData* cd, Cursor& c)
 
 static IpsOption::EvalStatus CheckANDPatternMatch(ContentData* idx, Cursor& c)
 {
+    // cppcheck-suppress unreadVariable
     RuleProfile profile(contentPerfStats);
 
     bool found = uniSearchReal(idx, c);
index 1e657d8c16ec6ee4f5d2d5a8037f530f57bcb712..1b7d069f92e442b410f55d27a3e9272092461a54 100644 (file)
@@ -94,9 +94,8 @@ static void CvsGetEOL(const uint8_t*, const uint8_t*,
 class CvsOption : public IpsOption
 {
 public:
-    CvsOption(const CvsRuleOption& c) :
-        IpsOption(s_name)
-    { config = c; }
+    CvsOption(const CvsRuleOption& c) : IpsOption(s_name), config(c)
+    { }
 
     uint32_t hash() const override;
     bool operator==(const IpsOption&) const override;
index 2cec75d790f26ac96f0ce5a04c61d9668711e494..29856d33591ef51e4a2cb059ecda55115b86bb5e 100644 (file)
@@ -37,9 +37,8 @@ static THREAD_LOCAL ProfileStats dsizePerfStats;
 class DsizeOption : public IpsOption
 {
 public:
-    DsizeOption(const RangeCheck& c) :
-        IpsOption(s_name)
-    { config = c; }
+    DsizeOption(const RangeCheck& c) : IpsOption(s_name), config(c)
+    { }
 
 
     uint32_t hash() const override;
@@ -78,6 +77,7 @@ bool DsizeOption::operator==(const IpsOption& ips) const
 // Test the packet's payload size against the rule payload size value
 IpsOption::EvalStatus DsizeOption::eval(Cursor&, Packet* p)
 {
+    // cppcheck-suppress unreadVariable
     RuleProfile profile(dsizePerfStats);
 
     /* fake packet dsizes are always wrong
index bc98f4e2fc87eae91f576782d7a386863ad8bc38..f4b6f9de95fb36d3765b9f4da72691f590b3e99a 100644 (file)
@@ -54,6 +54,7 @@ public:
 
 IpsOption::EvalStatus FileDataOption::eval(Cursor& c, Packet* p)
 {
+    // cppcheck-suppress unreadVariable
     RuleProfile profile(fileDataPerfStats);
 
     uint64_t sid;
index 8451155c80211ac9a60f5e0e9f96978e15ea1343..fff9845a8b7bb404e2108cd8ec477b2e47c9de89 100644 (file)
@@ -44,7 +44,7 @@ using namespace snort;
 
 struct FileMetaData
 {
-    uint32_t file_id;
+    uint32_t file_id = 0;
     std::string file_type;
     std::string category;
     std::string version;
index 444278baf6322adcdaf193ef4734e32df9457e99..4720946297e57de494578b571bcf6822df6897b8 100644 (file)
@@ -57,10 +57,8 @@ public:
 // class methods
 //-------------------------------------------------------------------------
 
-FileTypeOption::FileTypeOption(const FileTypeBitSet& t) : IpsOption(s_name)
-{
-    types = t;
-}
+FileTypeOption::FileTypeOption(const FileTypeBitSet& t) : IpsOption(s_name), types(t)
+{ }
 
 uint32_t FileTypeOption::hash() const
 {
@@ -80,6 +78,7 @@ bool FileTypeOption::operator==(const IpsOption& ips) const
 
 IpsOption::EvalStatus FileTypeOption::eval(Cursor&, Packet* pkt)
 {
+    // cppcheck-suppress unreadVariable
     RuleProfile profile(fileTypePerfStats);
 
     if (!pkt->flow)
index 21b90ceae5fdbe3ef37a7fc6aaef80605eff52b7..14abbcea92a383dacfc615e04ead4e70f9092002 100644 (file)
@@ -62,9 +62,8 @@ struct TcpFlagCheckData
 class TcpFlagOption : public IpsOption
 {
 public:
-    TcpFlagOption(const TcpFlagCheckData& c) :
-        IpsOption(s_name)
-    { config = c; }
+    TcpFlagOption(const TcpFlagCheckData& c) : IpsOption(s_name), config(c)
+    { }
 
     uint32_t hash() const override;
     bool operator==(const IpsOption&) const override;
index b3c4c967b42d42d8c7be394e21840cca8dc4cb48..de865813fbad4cc2e205b54ec761a66aae8841d3 100644 (file)
@@ -56,8 +56,8 @@ struct FlowCheckData
 class FlowCheckOption : public IpsOption
 {
 public:
-    FlowCheckOption(const FlowCheckData& c) : IpsOption(s_name)
-    { config = c; }
+    FlowCheckOption(const FlowCheckData& c) : IpsOption(s_name), config(c)
+    { }
 
     uint32_t hash() const override;
     bool operator==(const IpsOption&) const override;
@@ -114,6 +114,7 @@ bool FlowCheckOption::operator==(const IpsOption& ips) const
 
 IpsOption::EvalStatus FlowCheckOption::eval(Cursor&, Packet* p)
 {
+    // cppcheck-suppress unreadVariable
     RuleProfile profile(flowCheckPerfStats);
 
     FlowCheckData* fcd = &config;
index 25e9735dd1133e6eb50a45678c3782433111e5a9..d11a12298cb044f2c8ab362bbdbb16bd50cafdd7 100644 (file)
@@ -287,21 +287,12 @@ IpsOption::EvalStatus FlowBitsOption::eval(Cursor&, Packet* p)
 
 bool FlowBitsOption::is_set(BitOp* bitop)
 {
-    if ( !config->or_bits )
-    {
-        for ( auto id : config->ids )
-        {
-            if ( !bitop->is_set(id) )
-                return false;
-        }
-        return true;
-    }
-    for ( auto id : config->ids )
-    {
-        if ( bitop->is_set(id) )
-            return true;
-    }
-    return false;
+    return config->or_bits ?
+        std::any_of(config->ids.cbegin(), config->ids.cend(),
+            [&bitop](uint16_t id){ return !bitop->is_set(id); })
+        :
+        std::none_of(config->ids.cbegin(), config->ids.cend(),
+            [&bitop](uint16_t id){ return !bitop->is_set(id); });
 }
 
 void FlowBitsOption::get_dependencies(bool& set, std::vector<std::string>& bits)
index 75d93e7bf3079e0076d5b82c27a2406e48cbc618..464be9d20ac3a07123681cedd80c21cd2ed46d5f 100644 (file)
@@ -315,6 +315,7 @@ bool FragBitsOption::operator==(const IpsOption& ips) const
 
 IpsOption::EvalStatus FragBitsOption::eval(Cursor&, Packet* p)
 {
+    // cppcheck-suppress unreadVariable
     RuleProfile profile(fragBitsPerfStats);
 
     if ( !p->has_ip() )
index bab1a56300804fb3022d5a160e36db40194584ca..8404580fb43a2fa00471a0356409084283faf4de 100644 (file)
@@ -37,9 +37,8 @@ static THREAD_LOCAL ProfileStats fragOffsetPerfStats;
 class FragOffsetOption : public IpsOption
 {
 public:
-    FragOffsetOption(const RangeCheck& c) :
-        IpsOption(s_name)
-    { config = c; }
+    FragOffsetOption(const RangeCheck& c) : IpsOption(s_name), config(c)
+    { }
 
     uint32_t hash() const override;
     bool operator==(const IpsOption&) const override;
@@ -76,6 +75,7 @@ bool FragOffsetOption::operator==(const IpsOption& ips) const
 
 IpsOption::EvalStatus FragOffsetOption::eval(Cursor&, Packet* p)
 {
+    // cppcheck-suppress unreadVariable
     RuleProfile profile(fragOffsetPerfStats);
 
     if (!p->has_ip())
index 578d0093e075fa141db80f829ef5b0eb122628ae..0c21d36bef2e45bce9f8353ffb106e606eae246c 100644 (file)
@@ -194,6 +194,7 @@ int HashOption::match(Cursor& c)
 
 IpsOption::EvalStatus HashOption::eval(Cursor& c, Packet*)
 {
+    // cppcheck-suppress unreadVariable
     RuleProfile profile(hash_ps[idx]);
 
     int found = match(c);
index 9f7d355fd795325036a53944cbd672435fe65aba..96bde7382091a41800798d53c5b459217db90afb 100644 (file)
@@ -61,9 +61,8 @@ static THREAD_LOCAL ProfileStats icmpIdPerfStats;
 class IcmpIdOption : public IpsOption
 {
 public:
-    IcmpIdOption(const RangeCheck& c) :
-        IpsOption(s_name)
-    { config = c; }
+    IcmpIdOption(const RangeCheck& c) : IpsOption(s_name), config(c)
+    { }
 
     uint32_t hash() const override;
     bool operator==(const IpsOption&) const override;
@@ -100,6 +99,7 @@ bool IcmpIdOption::operator==(const IpsOption& ips) const
 
 IpsOption::EvalStatus IcmpIdOption::eval(Cursor&, Packet* p)
 {
+    // cppcheck-suppress unreadVariable
     RuleProfile profile(icmpIdPerfStats);
 
     if (!p->ptrs.icmph)
index d881e0bae556cc9ae4750e5f921ed1dc69ebb8bd..7dd0432f36472a24c414d3ec6cf9a1c5fea02f3b 100644 (file)
@@ -61,9 +61,8 @@ static THREAD_LOCAL ProfileStats icmpSeqPerfStats;
 class IcmpSeqOption : public IpsOption
 {
 public:
-    IcmpSeqOption(const RangeCheck& c) :
-        IpsOption(s_name)
-    { config = c; }
+    IcmpSeqOption(const RangeCheck& c) : IpsOption(s_name), config(c)
+    { }
 
     uint32_t hash() const override;
     bool operator==(const IpsOption&) const override;
@@ -100,6 +99,7 @@ bool IcmpSeqOption::operator==(const IpsOption& ips) const
 
 IpsOption::EvalStatus IcmpSeqOption::eval(Cursor&, Packet* p)
 {
+    // cppcheck-suppress unreadVariable
     RuleProfile profile(icmpSeqPerfStats);
 
     if (!p->ptrs.icmph)
index 38aaf68718ead534dc13dea596896381bf816671..678af64b7f5bd1c881d801b9a1bc12768bd37559 100644 (file)
@@ -38,9 +38,8 @@ static THREAD_LOCAL ProfileStats icmpCodePerfStats;
 class IcodeOption : public IpsOption
 {
 public:
-    IcodeOption(const RangeCheck& c) :
-        IpsOption(s_name)
-    { config = c; }
+    IcodeOption(const RangeCheck& c) : IpsOption(s_name), config(c)
+    { }
 
     uint32_t hash() const override;
     bool operator==(const IpsOption&) const override;
@@ -77,6 +76,7 @@ bool IcodeOption::operator==(const IpsOption& ips) const
 
 IpsOption::EvalStatus IcodeOption::eval(Cursor&, Packet* p)
 {
+    // cppcheck-suppress unreadVariable
     RuleProfile profile(icmpCodePerfStats);
 
     // return 0  if we don't have an icmp header
index 32874b0c33671645324fe5f18d958f4c0d5555bf..edfd0899456f62972e291b9b5a77418b160a05fe 100644 (file)
@@ -37,9 +37,8 @@ static THREAD_LOCAL ProfileStats ipIdPerfStats;
 class IpIdOption : public IpsOption
 {
 public:
-    IpIdOption(const RangeCheck& c) :
-        IpsOption(s_name)
-    { config = c; }
+    IpIdOption(const RangeCheck& c) : IpsOption(s_name), config(c)
+    { }
 
     uint32_t hash() const override;
     bool operator==(const IpsOption&) const override;
@@ -76,6 +75,7 @@ bool IpIdOption::operator==(const IpsOption& ips) const
 
 IpsOption::EvalStatus IpIdOption::eval(Cursor&, Packet* p)
 {
+    // cppcheck-suppress unreadVariable
     RuleProfile profile(ipIdPerfStats);
 
     if (!p->has_ip())
index 3cfec1f6545528b34ca946358a92a4c120b2e506..89f2e456f7071426bbd2ebfa7e50f0c9c4b4ceae 100644 (file)
@@ -51,9 +51,8 @@ struct IpProtoData
 class IpProtoOption : public IpsOption
 {
 public:
-    IpProtoOption(const IpProtoData& c) :
-        IpsOption(s_name)
-    { config = c; }
+    IpProtoOption(const IpProtoData& c) : IpsOption(s_name), config(c)
+    { }
 
     uint32_t hash() const override;
     bool operator==(const IpsOption&) const override;
index 2b0acb6e8018f7d04df2f9abe2dea79281c28b05..7173b3924c90066d68ee8fe4ed280e867694b069 100644 (file)
@@ -44,9 +44,8 @@ struct IpOptionData
 class IpOptOption : public IpsOption
 {
 public:
-    IpOptOption(const IpOptionData& c) :
-        IpsOption(s_name)
-    { config = c; }
+    IpOptOption(const IpOptionData& c) : IpsOption(s_name), config(c)
+    { }
 
     uint32_t hash() const override;
     bool operator==(const IpsOption&) const override;
@@ -96,6 +95,7 @@ bool IpOptOption::operator==(const IpsOption& ips) const
 
 IpsOption::EvalStatus IpOptOption::eval(Cursor&, Packet* p)
 {
+    // cppcheck-suppress unreadVariable
     RuleProfile profile(ipOptionPerfStats);
 
     if ( !p->is_ip4() )
@@ -107,9 +107,7 @@ IpsOption::EvalStatus IpOptOption::eval(Cursor&, Packet* p)
     const uint8_t option_len = ip4h->get_opt_len();
 
     if ((config.any_flag == 1) && (option_len > 0))
-    {
         return MATCH;
-    }
 
     ip::IpOptionIterator iter(ip4h, p);
 
@@ -117,7 +115,6 @@ IpsOption::EvalStatus IpOptOption::eval(Cursor&, Packet* p)
     {
         if (config.ip_option == opt.code)
             return MATCH;
-
     }
 
     return NO_MATCH;
index da2ffdad9c23173701e0989a9b9ab339ea81a3c6..b32503c1129b8416199205fb03a1e65a04fb1449 100644 (file)
@@ -68,9 +68,8 @@ typedef struct _IsDataAtData
 class IsDataAtOption : public IpsOption
 {
 public:
-    IsDataAtOption(const IsDataAtData& c) :
-        IpsOption(s_name)
-    { config = c; }
+    IsDataAtOption(const IsDataAtData& c) : IpsOption(s_name), config(c)
+    { }
 
     uint32_t hash() const override;
     bool operator==(const IpsOption&) const override;
@@ -128,6 +127,7 @@ bool IsDataAtOption::operator==(const IpsOption& ips) const
 
 IpsOption::EvalStatus IsDataAtOption::eval(Cursor& c, Packet*)
 {
+    // cppcheck-suppress unreadVariable
     RuleProfile profile(isDataAtPerfStats);
 
     int offset;
index c682fa8ccdee1c79f17516a67bf77eb088babd94..90458fb56256c2fc177b885c079c5af46781f821 100644 (file)
@@ -38,9 +38,8 @@ static THREAD_LOCAL ProfileStats icmpTypePerfStats;
 class IcmpTypeOption : public IpsOption
 {
 public:
-    IcmpTypeOption(const RangeCheck& c) :
-        IpsOption(s_name)
-    { config = c; }
+    IcmpTypeOption(const RangeCheck& c) : IpsOption(s_name), config(c)
+    { }
 
     uint32_t hash() const override;
     bool operator==(const IpsOption&) const override;
@@ -77,6 +76,7 @@ bool IcmpTypeOption::operator==(const IpsOption& ips) const
 
 IpsOption::EvalStatus IcmpTypeOption::eval(Cursor&, Packet* p)
 {
+    // cppcheck-suppress unreadVariable
     RuleProfile profile(icmpTypePerfStats);
 
     // return 0 if we don't have an icmp header
index 372a8d5ee93c28d21e0cfc50e8e3ecef537b26e0..2b1b16ed3979d4a45ca8a15f519d60024e8b9b48 100644 (file)
@@ -60,6 +60,7 @@ public:
 
     EvalStatus eval(Cursor& c, Packet* p) override
     {
+        // cppcheck-suppress unreadVariable
         RuleProfile profile(js_data_profile_stats);
         InspectionBuffer buf;
 
index 1c51cb89879e557dafb3cdb6c2a5e359bd4342dc..616b7cae9a0c5b8ad16a03c55828b31c5889e9eb 100644 (file)
@@ -130,13 +130,8 @@ private:
 
 LuaJitOption::LuaJitOption(
     const char* name, std::string& chunk, LuaJitModule* mod)
-    : IpsOption((my_name = snort_strdup(name)))
+    : IpsOption((my_name = snort_strdup(name))), config("args = { " + mod->args + "}")
 {
-    // create an args table with any rule options
-    config = "args = { ";
-    config += mod->args;
-    config += "}";
-
     unsigned max = ThreadConfig::get_instance_max();
     states.reserve(max);
 
@@ -175,6 +170,7 @@ bool LuaJitOption::operator==(const IpsOption& ips) const
 
 IpsOption::EvalStatus LuaJitOption::eval(Cursor& c, Packet*)
 {
+    // cppcheck-suppress unreadVariable
     RuleProfile profile(luaIpsPerfStats);
 
     cursor = &c;
index 12ada0b248a8214279034eeadd135345a15fead5..f14d7c4ff225615cf2d4e8c373881a22c219f1dd 100644 (file)
@@ -552,6 +552,7 @@ bool PcreOption::operator==(const IpsOption& ips) const
 
 IpsOption::EvalStatus PcreOption::eval(Cursor& c, Packet* p)
 {
+    // cppcheck-suppress unreadVariable
     RuleProfile profile(pcrePerfStats);
 
     // short circuit this for testing pcre performance impact
index 0fb739cf39a64e589424575872aaf45f39f87f09..1de108797f1c919d699c0c625484a549b721f583 100644 (file)
@@ -49,6 +49,7 @@ public:
 
 IpsOption::EvalStatus PktDataOption::eval(Cursor& c, Packet* p)
 {
+    // cppcheck-suppress unreadVariable
     RuleProfile profile(pktDataPerfStats);
 
     c.reset(p);
index 07ebeb20848d912e208ad672bd0f117f5a859e40..e133a71d6965577c39942d82e63e7812fdc89794 100644 (file)
@@ -46,6 +46,7 @@ public:
 
 IpsOption::EvalStatus RawDataOption::eval(Cursor& c, Packet* p)
 {
+    // cppcheck-suppress unreadVariable
     RuleProfile profile(rawDataPerfStats);
 
     c.set(s_name, p->data, p->dsize);
index b69d6b11d2c16552935031329a0efbf490ab1cad..a2ebcb07aa0bdedfd5a0627861fdab81c4fc2eeb 100644 (file)
@@ -98,11 +98,8 @@ private:
     RegexConfig config;
 };
 
-RegexOption::RegexOption(const RegexConfig& c) :
-    IpsOption(s_name, RULE_OPTION_TYPE_CONTENT)
+RegexOption::RegexOption(const RegexConfig& c) : IpsOption(s_name, RULE_OPTION_TYPE_CONTENT), config(c)
 {
-    config = c;
-
     if ( !scratcher->allocate(config.db) )
         ParseError("can't allocate scratch for regex '%s'", config.re.c_str());
 
@@ -166,6 +163,7 @@ static int hs_match(
 
 IpsOption::EvalStatus RegexOption::eval(Cursor& c, Packet*)
 {
+    // cppcheck-suppress unreadVariable
     RuleProfile profile(regex_perf_stats);
 
     unsigned pos = c.get_delta();
@@ -321,7 +319,7 @@ bool RegexModule::convert_pcre_to_regex_form()
     }
 
     // finally, process the modifiers
-    for ( char& c : modifiers )
+    for ( const char& c : modifiers )
     {
         switch ( c )
         {
index 03f5f83d9e548ba3e209d8c4acb23a2e1938f230..37d3e089213298a6905f4d9775bc418c9bc46a9e 100644 (file)
@@ -153,6 +153,7 @@ bool ReplaceOption::operator==(const IpsOption& ips) const
 
 IpsOption::EvalStatus ReplaceOption::eval(Cursor& c, Packet* p)
 {
+    // cppcheck-suppress unreadVariable
     RuleProfile profile(replacePerfStats);
 
     if ( p->is_cooked() )
@@ -172,6 +173,7 @@ IpsOption::EvalStatus ReplaceOption::eval(Cursor& c, Packet* p)
 
 void ReplaceOption::action(Packet*)
 {
+    // cppcheck-suppress unreadVariable
     RuleProfile profile(replacePerfStats);
 
     if ( pending() )
index 37d8d642a350d1b0ff76c4ebfcb1d9e3961c4abf..401fa6f0247d9d612d450d8c72ba49d47149f007 100644 (file)
@@ -50,8 +50,8 @@ struct RpcCheckData
 class RpcOption : public IpsOption
 {
 public:
-    RpcOption(const RpcCheckData& c) : IpsOption(s_name)
-    { config = c; }
+    RpcOption(const RpcCheckData& c) : IpsOption(s_name), config(c)
+    { }
 
     uint32_t hash() const override;
     bool operator==(const IpsOption&) const override;
@@ -116,6 +116,7 @@ bool RpcOption::operator==(const IpsOption& ips) const
 
 IpsOption::EvalStatus RpcOption::eval(Cursor&, Packet* p)
 {
+    // cppcheck-suppress unreadVariable
     RuleProfile profile(rpcCheckPerfStats);
 
     if ( !is_valid(p) )
index dc671a180b1a88bb814a25911a0058b5c4f2dd9c..7a9f00eee6a913a228ab1c9cc5907e43109acc74 100644 (file)
@@ -340,6 +340,7 @@ unsigned SdPatternOption::SdSearch(const Cursor& c, Packet* p)
 
 IpsOption::EvalStatus SdPatternOption::eval(Cursor& c, Packet* p)
 {
+    // cppcheck-suppress unreadVariable
     RuleProfile profile(sd_pattern_perf_stats);
 
     unsigned matches = SdSearch(c, p);
@@ -350,7 +351,7 @@ IpsOption::EvalStatus SdPatternOption::eval(Cursor& c, Packet* p)
     else if ( matches == 0 )
         ++s_stats.nomatch_notfound;
 
-    else if ( matches > 0 && matches < config.threshold )
+    else
         ++s_stats.nomatch_threshold;
 
     return NO_MATCH;
index 1ef507b40024543de64d9a603967187893fcd661..cbc77efb65fbc7b50875ee335db09cebf3761eff 100644 (file)
@@ -38,9 +38,8 @@ static THREAD_LOCAL ProfileStats tcpSeqPerfStats;
 class TcpSeqOption : public IpsOption
 {
 public:
-    TcpSeqOption(const RangeCheck& c) :
-        IpsOption(s_name)
-    { config = c; }
+    TcpSeqOption(const RangeCheck& c) : IpsOption(s_name), config(c)
+    { }
 
     uint32_t hash() const override;
     bool operator==(const IpsOption&) const override;
@@ -77,6 +76,7 @@ bool TcpSeqOption::operator==(const IpsOption& ips) const
 
 IpsOption::EvalStatus TcpSeqOption::eval(Cursor&, Packet* p)
 {
+    // cppcheck-suppress unreadVariable
     RuleProfile profile(tcpSeqPerfStats);
 
     if (!p->ptrs.tcph)
index 4b86bc6a780d3ff88d770589a7eb8e311d7fc112..18a2d8304dcb5a899cadb4cbcf3911fd5c5102bf 100644 (file)
@@ -76,13 +76,10 @@ bool ServiceModule::set(const char*, Value& v, SnortConfig*)
     assert(v.is("*"));
     std::string svc = v.get_string();
 
-    for ( const auto& p : services )
+    if (std::any_of(services.cbegin(), services.cend(), [&svc](const std::string&p){ return p == svc; }))
     {
-        if ( p == svc )
-        {
-            ParseWarning(WARN_RULES, "repeated service '%s'", svc.c_str());
-            return true;
-        }
+        ParseWarning(WARN_RULES, "repeated service '%s'", svc.c_str());
+        return true;
     }
     services.emplace_back(svc);
     return true;
index 9a3d13ed369ba1f59d42a3d35194deca88336410..d805077c356c5230ba5b933da0406a5601ae0799 100644 (file)
@@ -111,6 +111,7 @@ bool SoOption::operator==(const IpsOption& ips) const
 
 IpsOption::EvalStatus SoOption::eval(Cursor& c, Packet* p)
 {
+    // cppcheck-suppress unreadVariable
     RuleProfile profile(soPerfStats);
     return func(data, c, p);
 }
index fac54cc29b93706b2c14d23601f2ffa1d41feb25..374b6790289762e2852fdff9e450052c61966747 100644 (file)
@@ -37,9 +37,8 @@ static THREAD_LOCAL ProfileStats ipTosPerfStats;
 class IpTosOption : public IpsOption
 {
 public:
-    IpTosOption(const RangeCheck& c) :
-        IpsOption(s_name)
-    { config = c; }
+    IpTosOption(const RangeCheck& c) : IpsOption(s_name), config(c)
+    { }
 
     uint32_t hash() const override;
     bool operator==(const IpsOption&) const override;
@@ -80,6 +79,7 @@ bool IpTosOption::operator==(const IpsOption& ips) const
 
 IpsOption::EvalStatus IpTosOption::eval(Cursor&, Packet* p)
 {
+    // cppcheck-suppress unreadVariable
     RuleProfile profile(ipTosPerfStats);
 
     if(!p->ptrs.ip_api.is_ip())
index d5dbfcc5e53a4efa3311652f2c8bd673873b8b2c..1240e4ce228e48b04591c63d32ae05613eb2e8bf 100644 (file)
@@ -37,9 +37,8 @@ static THREAD_LOCAL ProfileStats ttlCheckPerfStats;
 class TtlOption : public IpsOption
 {
 public:
-    TtlOption(const RangeCheck& c) :
-        IpsOption(s_name)
-    { config = c; }
+    TtlOption(const RangeCheck& c) : IpsOption(s_name), config(c)
+    { }
 
     uint32_t hash() const override;
     bool operator==(const IpsOption&) const override;
@@ -77,6 +76,7 @@ bool TtlOption::operator==(const IpsOption& ips) const
 
 IpsOption::EvalStatus TtlOption::eval(Cursor&, Packet* p)
 {
+    // cppcheck-suppress unreadVariable
     RuleProfile profile(ttlCheckPerfStats);
 
     if(!p->ptrs.ip_api.is_ip())
index 74b4f5040c5486048bc19807c7f9602c530a92a5..b9c6decd9b5d8372250514f7d73ad4393b4b35f8 100644 (file)
@@ -37,6 +37,7 @@ CursorActionType VbaDataOption::get_cursor_type() const
 
 IpsOption::EvalStatus VbaDataOption::eval(Cursor& c, Packet* p)
 {
+    // cppcheck-suppress unreadVariable
     RuleProfile profile(vbaDataPerfStats);
 
     if (!p->flow or !p->flow->gadget)
index b5319b6ed3448ab1c7f327bf7c210433a0b308c5..4eea99dac3bb189863688e9ba2c40bd3de218170 100644 (file)
@@ -38,9 +38,8 @@ static THREAD_LOCAL ProfileStats tcpWinPerfStats;
 class TcpWinOption : public IpsOption
 {
 public:
-    TcpWinOption(const RangeCheck& c) :
-        IpsOption(s_name)
-    { config = c; }
+    TcpWinOption(const RangeCheck& c) : IpsOption(s_name), config(c)
+    { }
 
     uint32_t hash() const override;
     bool operator==(const IpsOption&) const override;
@@ -77,6 +76,7 @@ bool TcpWinOption::operator==(const IpsOption& ips) const
 
 IpsOption::EvalStatus TcpWinOption::eval(Cursor&, Packet* p)
 {
+    // cppcheck-suppress unreadVariable
     RuleProfile profile(tcpWinPerfStats);
 
     if (!p->ptrs.tcph)
index ff86031af20eff4b156818005bd4ae534b13fef2..ff503407d292488165e9fb790aa94bfb25880269 100644 (file)
@@ -231,10 +231,8 @@ bool JSIdentifierCtx::scope_check(const std::list<JSProgramScopeType>& compare)
 const std::list<JSProgramScopeType> JSIdentifierCtx::get_types() const
 {
     std::list<JSProgramScopeType> return_list;
-    for (const auto& scope : scopes)
-    {
-        return_list.push_back(scope.type());
-    }
+    std::transform(scopes.cbegin(), scopes.cend(), std::back_inserter(return_list),
+        [](const ProgramScope& scope){ return scope.type(); });
     return return_list;
 }
 
index 5a4ee998b12c9977182db21ed82a6f54f2b36b05..398d6d4692cb4610972bd7f7abc8d47610bd9e22 100644 (file)
@@ -64,12 +64,15 @@ bool PDFJSNorm::pre_proc()
     }
 
     src_ptr = (const uint8_t*)buf_pdf_out.data();
-    src_end = src_ptr + buf_pdf_out.data_len();
 
     // script object not found
     if (!src_ptr)
+    {
+        src_end = nullptr;
         return false;
+    }
 
+    src_end = src_ptr + buf_pdf_out.data_len();
     return true;
 }
 
index ef0fcf25c54dce8388fd5377d12f70f7a75cfdad..214372e5e091bf8b5cc5d9d6232a6ff1a71a24f0 100644 (file)
@@ -121,10 +121,10 @@ TEST_CASE("JSIdentifierCtx::is_ignored()", "[JSIdentifierCtx]")
         auto v3 = ident_ctx.substitute("w", false);
         auto v4 = ident_ctx.substitute("w", true);
 
-        CHECK(ident_ctx.is_ignored(v1) == true);
-        CHECK(ident_ctx.is_ignored(v2) == false);
-        CHECK(ident_ctx.is_ignored(v3) == false);
-        CHECK(ident_ctx.is_ignored(v4) == true);
+        CHECK(true == ident_ctx.is_ignored(v1));
+        CHECK(false == ident_ctx.is_ignored(v2));
+        CHECK(false == ident_ctx.is_ignored(v3));
+        CHECK(true == ident_ctx.is_ignored(v4));
     }
     SECTION("multiple chars identifier")
     {
@@ -135,10 +135,10 @@ TEST_CASE("JSIdentifierCtx::is_ignored()", "[JSIdentifierCtx]")
         auto v3 = ident_ctx.substitute("watch", false);
         auto v4 = ident_ctx.substitute("watch", true);
 
-        CHECK(ident_ctx.is_ignored(v1) == true);
-        CHECK(ident_ctx.is_ignored(v2) == false);
-        CHECK(ident_ctx.is_ignored(v3) == false);
-        CHECK(ident_ctx.is_ignored(v4) == true);
+        CHECK(true == ident_ctx.is_ignored(v1));
+        CHECK(false == ident_ctx.is_ignored(v2));
+        CHECK(false == ident_ctx.is_ignored(v3));
+        CHECK(true == ident_ctx.is_ignored(v4));
     }
 }
 
@@ -148,18 +148,18 @@ TEST_CASE("JSIdentifierCtx::scopes", "[JSIdentifierCtx]")
 
     SECTION("scope stack")
     {
-        CHECK(ident_ctx.scope_check({GLOBAL}));
+        CHECK(true == ident_ctx.scope_check({GLOBAL}));
 
         ident_ctx.scope_push(JSProgramScopeType::FUNCTION);
         ident_ctx.scope_push(JSProgramScopeType::BLOCK);
         ident_ctx.scope_push(JSProgramScopeType::BLOCK);
-        CHECK(ident_ctx.scope_check({GLOBAL, FUNCTION, BLOCK, BLOCK}));
+        CHECK(true == ident_ctx.scope_check({GLOBAL, FUNCTION, BLOCK, BLOCK}));
 
-        CHECK(ident_ctx.scope_pop(JSProgramScopeType::BLOCK));
-        CHECK(ident_ctx.scope_check({GLOBAL, FUNCTION, BLOCK}));
+        CHECK(true == ident_ctx.scope_pop(JSProgramScopeType::BLOCK));
+        CHECK(true == ident_ctx.scope_check({GLOBAL, FUNCTION, BLOCK}));
 
         ident_ctx.reset();
-        CHECK(ident_ctx.scope_check({GLOBAL}));
+        CHECK(true == ident_ctx.scope_check({GLOBAL}));
     }
     SECTION("aliases")
     {
@@ -168,18 +168,18 @@ TEST_CASE("JSIdentifierCtx::scopes", "[JSIdentifierCtx]")
         CHECK(!strcmp(ident_ctx.alias_lookup("a"), "console.log"));
         CHECK(!strcmp(ident_ctx.alias_lookup("b"), "document"));
 
-        REQUIRE(ident_ctx.scope_push(JSProgramScopeType::FUNCTION));
+        REQUIRE(true == ident_ctx.scope_push(JSProgramScopeType::FUNCTION));
         ident_ctx.add_alias("a", "document");
         CHECK(!strcmp(ident_ctx.alias_lookup("a"), "document"));
         CHECK(!strcmp(ident_ctx.alias_lookup("b"), "document"));
 
-        REQUIRE(ident_ctx.scope_push(JSProgramScopeType::BLOCK));
+        REQUIRE(true == ident_ctx.scope_push(JSProgramScopeType::BLOCK));
         ident_ctx.add_alias("b", "console.log");
         CHECK(!strcmp(ident_ctx.alias_lookup("b"), "console.log"));
         CHECK(!strcmp(ident_ctx.alias_lookup("a"), "document"));
 
-        REQUIRE(ident_ctx.scope_pop(JSProgramScopeType::BLOCK));
-        REQUIRE(ident_ctx.scope_pop(JSProgramScopeType::FUNCTION));
+        REQUIRE(true == ident_ctx.scope_pop(JSProgramScopeType::BLOCK));
+        REQUIRE(true == ident_ctx.scope_pop(JSProgramScopeType::FUNCTION));
         ident_ctx.add_alias("a", "eval");
         CHECK(!strcmp(ident_ctx.alias_lookup("a"), "eval"));
         CHECK(!strcmp(ident_ctx.alias_lookup("b"), "document"));
@@ -188,30 +188,30 @@ TEST_CASE("JSIdentifierCtx::scopes", "[JSIdentifierCtx]")
     }
     SECTION("scope mismatch")
     {
-        CHECK(!ident_ctx.scope_pop(JSProgramScopeType::FUNCTION));
-        CHECK(ident_ctx.scope_check({GLOBAL}));
-        CHECK(!ident_ctx.scope_check({FUNCTION}));
-
-        CHECK(ident_ctx.scope_push(JSProgramScopeType::FUNCTION));
-        CHECK(ident_ctx.scope_check({GLOBAL, FUNCTION}));
-        CHECK(!ident_ctx.scope_pop(JSProgramScopeType::BLOCK));
-        CHECK(ident_ctx.scope_check({GLOBAL, FUNCTION}));
-        CHECK(!ident_ctx.scope_check({GLOBAL}));
+        CHECK(false == ident_ctx.scope_pop(JSProgramScopeType::FUNCTION));
+        CHECK(true == ident_ctx.scope_check({GLOBAL}));
+        CHECK(false == ident_ctx.scope_check({FUNCTION}));
+
+        CHECK(true == ident_ctx.scope_push(JSProgramScopeType::FUNCTION));
+        CHECK(true == ident_ctx.scope_check({GLOBAL, FUNCTION}));
+        CHECK(false == ident_ctx.scope_pop(JSProgramScopeType::BLOCK));
+        CHECK(true == ident_ctx.scope_check({GLOBAL, FUNCTION}));
+        CHECK(false == ident_ctx.scope_check({GLOBAL}));
     }
     SECTION("scope max nesting")
     {
         JSIdentifierCtx ident_ctx_limited(DEPTH, 2, s_ignored_ids, s_ignored_props);
 
-        CHECK(ident_ctx_limited.scope_push(JSProgramScopeType::FUNCTION));
-        CHECK(ident_ctx_limited.scope_check({GLOBAL, FUNCTION}));
+        CHECK(true == ident_ctx_limited.scope_push(JSProgramScopeType::FUNCTION));
+        CHECK(true == ident_ctx_limited.scope_check({GLOBAL, FUNCTION}));
 
-        CHECK(!ident_ctx_limited.scope_push(JSProgramScopeType::FUNCTION));
-        CHECK(ident_ctx_limited.scope_check({GLOBAL, FUNCTION}));
-        CHECK(!ident_ctx_limited.scope_push(JSProgramScopeType::FUNCTION));
-        CHECK(ident_ctx_limited.scope_check({GLOBAL, FUNCTION}));
+        CHECK(false == ident_ctx_limited.scope_push(JSProgramScopeType::FUNCTION));
+        CHECK(true == ident_ctx_limited.scope_check({GLOBAL, FUNCTION}));
+        CHECK(false == ident_ctx_limited.scope_push(JSProgramScopeType::FUNCTION));
+        CHECK(true == ident_ctx_limited.scope_check({GLOBAL, FUNCTION}));
 
-        CHECK(ident_ctx_limited.scope_pop(JSProgramScopeType::FUNCTION));
-        CHECK(ident_ctx_limited.scope_push(JSProgramScopeType::FUNCTION));
-        CHECK(ident_ctx_limited.scope_check({GLOBAL, FUNCTION}));
+        CHECK(true == ident_ctx_limited.scope_pop(JSProgramScopeType::FUNCTION));
+        CHECK(true == ident_ctx_limited.scope_push(JSProgramScopeType::FUNCTION));
+        CHECK(true == ident_ctx_limited.scope_check({GLOBAL, FUNCTION}));
     }
 }
index 183e6cc8d63d992db97f60afaa50188164978ca7..cdfc6a3e1e23d9f91f29045be32f9043551cb109 100644 (file)
@@ -74,16 +74,16 @@ void JSTokenizerTester::run_checks(const JSTestConfig& checks)
         CHECK(last_return == checks.return_code);
 
     if (checks.check_open_tag.is_set())
-        CHECK(normalizer.is_opening_tag_seen() == checks.check_open_tag);
+        CHECK((normalizer.is_opening_tag_seen() == checks.check_open_tag));
 
     if (checks.check_closing_tag.is_set())
-        CHECK(normalizer.is_closing_tag_seen() == checks.check_closing_tag);
+        CHECK((normalizer.is_closing_tag_seen() == checks.check_closing_tag));
 
     if (checks.check_mixed_encoding.is_set())
-        CHECK(normalizer.is_mixed_encoding_seen() == checks.check_mixed_encoding);
+        CHECK((normalizer.is_mixed_encoding_seen() == checks.check_mixed_encoding));
 
     if (checks.check_unescape_nesting.is_set())
-        CHECK(normalizer.is_unescape_nesting_seen() == checks.check_unescape_nesting);
+        CHECK((normalizer.is_unescape_nesting_seen() == checks.check_unescape_nesting));
 
     if (checks.expected_cursor_pos.is_set())
         CHECK((normalizer.get_src_next() - last_source.c_str()) == checks.expected_cursor_pos);
index 5b5c9a1aa1f9e6769895bcfce90846f4b117e1e4..af52123095d5e2cb7fc3982a82657fb0eb487da2 100644 (file)
@@ -72,7 +72,7 @@ public:
 
 private:
     const JSTestConfig& config;
-    JSTokenizer::JSRet last_return;
+    JSTokenizer::JSRet last_return = JSTokenizer::EOS;
     std::string last_source;
 };
 
index 8417e0069d1bcadf1506989bbd81139a62da6ba6..ebaf9e6a0dea3cb51f1b68cd845de0bfd02de4bc 100644 (file)
@@ -172,17 +172,17 @@ TEST_CASE("non-blocking events", "[JSNorm]")
 
     SECTION("EVENT_CLOSING_TAG")
     {
-        JSNorm jsn(&config, true);
+        JSNorm tmp_jsn(&config, true);
 
-        std::string src = "'</script>' ;";
-        std::string exp = "'</script>';";
+        std::string tmp_src = "'</script>' ;";
+        std::string tmp_exp = "'</script>';";
 
-        jsn.normalize(src.c_str(), src.size(), dst, dst_len);
+        tmp_jsn.normalize(tmp_src.c_str(), tmp_src.size(), dst, dst_len);
 
         REQUIRE(dst != nullptr);
         REQUIRE(dst_len != 0);
 
-        CHECK(std::string((const char*)dst, dst_len) == exp);
+        CHECK(std::string((const char*)dst, dst_len) == tmp_exp);
     }
 
     jsn.normalize(src.c_str(), src.size(), dst, dst_len);
@@ -222,51 +222,51 @@ TEST_CASE("blocking events", "[JSNorm]")
     {
         config.identifier_depth = 0;
 
-        JSNorm jsn(&config, false);
+        JSNorm tmp_jsn(&config, false);
 
-        std::string src = "; a";
-        std::string exp = ";";
+        std::string tmp_src = "; a";
+        std::string tmp_exp = ";";
 
-        jsn.normalize(src.c_str(), src.size(), dst, dst_len);
+        tmp_jsn.normalize(tmp_src.c_str(), tmp_src.size(), dst, dst_len);
 
         REQUIRE(dst != nullptr);
         REQUIRE(dst_len != 0);
 
-        CHECK(std::string((const char*)dst, dst_len) == exp);
+        CHECK(std::string((const char*)dst, dst_len) == tmp_exp);
     }
 
     SECTION("EVENT_BRACKET_NEST_OVERFLOW")
     {
         config.max_bracket_depth = 0;
 
-        JSNorm jsn(&config, false);
+        JSNorm tmp_jsn(&config, false);
 
-        std::string src = "; {";
-        std::string exp = ";";
+        std::string tmp_src = "; {";
+        std::string tmp_exp = ";";
 
-        jsn.normalize(src.c_str(), src.size(), dst, dst_len);
+        tmp_jsn.normalize(tmp_src.c_str(), tmp_src.size(), dst, dst_len);
 
         REQUIRE(dst != nullptr);
         REQUIRE(dst_len != 0);
 
-        CHECK(std::string((const char*)dst, dst_len) == exp);
+        CHECK(std::string((const char*)dst, dst_len) == tmp_exp);
     }
 
     SECTION("EVENT_SCOPE_NEST_OVERFLOW")
     {
         config.max_scope_depth = 0;
 
-        JSNorm jsn(&config, false);
+        JSNorm tmp_jsn(&config, false);
 
-        std::string src = "; function f () {";
-        std::string exp = ";function var_0000";
+        std::string tmp_src = "; function f () {";
+        std::string tmp_exp = ";function var_0000";
 
-        jsn.normalize(src.c_str(), src.size(), dst, dst_len);
+        tmp_jsn.normalize(tmp_src.c_str(), tmp_src.size(), dst, dst_len);
 
         REQUIRE(dst != nullptr);
         REQUIRE(dst_len != 0);
 
-        CHECK(std::string((const char*)dst, dst_len) == exp);
+        CHECK(std::string((const char*)dst, dst_len) == tmp_exp);
     }
 
     jsn.normalize(src.c_str(), src.size(), dst, dst_len);
index 173c98c38d0101b61e6fd12da6446664273e9bb1..bb54a18b73a1aa14bcb0b776f10c835624f75fac 100644 (file)
@@ -54,7 +54,7 @@ static void test_pdf_proc(const vector<Chunk>& chunks)
     ostringstream out;
     PDFTokenizer extractor(in, out);
 
-    for (auto& chunk : chunks)
+    for (const auto& chunk : chunks)
     {
         auto src = chunk.first;
         auto exp = chunk.second;
index fb182df47827fbbbb8cd663f00cb468085a2018a..fd1e2e33e537597dff0e2edfa4b2b47717aced1c 100644 (file)
@@ -344,16 +344,16 @@ TEST_CASE ( "packet latency impl", "[latency]" )
         {
             MockClock::inc(config.config.max_time + 1_ticks);
 
-            CHECK( impl.fastpath() );
-            CHECK( impl.pop(nullptr) );
+            CHECK( true == impl.fastpath() );
+            CHECK( true == impl.pop(nullptr) );
 
             CHECK( event_handler.count == 1 );
         }
 
         SECTION( "no timeout" )
         {
-            CHECK_FALSE( impl.fastpath() );
-            CHECK_FALSE( impl.pop(nullptr) );
+            CHECK( false == impl.fastpath() );
+            CHECK( false == impl.pop(nullptr) );
 
             CHECK( event_handler.count == 0 );
         }
@@ -370,16 +370,16 @@ TEST_CASE ( "packet latency impl", "[latency]" )
         {
             MockClock::inc(config.config.max_time + 1_ticks);
 
-            CHECK_FALSE( impl.fastpath() );
-            CHECK( impl.pop(nullptr) );
+            CHECK( false == impl.fastpath() );
+            CHECK( true == impl.pop(nullptr) );
 
             CHECK( event_handler.count == 1 );
         }
 
         SECTION( "no timeout" )
         {
-            CHECK_FALSE( impl.fastpath() );
-            CHECK_FALSE( impl.pop(nullptr) );
+            CHECK( false == impl.fastpath() );
+            CHECK( false == impl.pop(nullptr) );
 
             CHECK( event_handler.count == 0 );
         }
index c47a6601c19b7b3b027edaebefb58962f121e327..174411e4676422f9a1a5f0d1449e57b4be9f5afe 100644 (file)
@@ -254,12 +254,12 @@ inline bool Impl<Clock, RuleTree>::pop()
 #endif
         if ( timed_out )
         {
-            auto suspended = RuleTree::timeout_and_suspend(timer.root, config->suspend_threshold,
+            auto s = RuleTree::timeout_and_suspend(timer.root, config->suspend_threshold,
                 Clock::now(), config->suspend);
 
             Event e
             {
-                suspended ? Event::EVENT_SUSPENDED : Event::EVENT_TIMED_OUT,
+                s ? Event::EVENT_SUSPENDED : Event::EVENT_TIMED_OUT,
                 timer.elapsed(), timer.root, timer.packet
             };
 
@@ -477,7 +477,7 @@ TEST_CASE ( "rule latency impl", "[latency]" )
 
             SECTION( "push rule" )
             {
-                CHECK_FALSE( impl.push(root, &pkt) );
+                CHECK( false == impl.push(root, &pkt) );
                 CHECK( event_handler.count == 0 );
                 CHECK( RuleInterfaceSpy::reenable_called );
             }
@@ -486,7 +486,7 @@ TEST_CASE ( "rule latency impl", "[latency]" )
             {
                 RuleInterfaceSpy::reenable_result = true;
 
-                CHECK( impl.push(root, &pkt) );
+                CHECK( true == impl.push(root, &pkt) );
                 CHECK( event_handler.count == 1 );
                 CHECK( RuleInterfaceSpy::reenable_called );
             }
@@ -498,7 +498,7 @@ TEST_CASE ( "rule latency impl", "[latency]" )
 
             SECTION( "push rule" )
             {
-                CHECK_FALSE( impl.push(root, &pkt) );
+                CHECK( false == impl.push(root, &pkt) );
                 CHECK( event_handler.count == 0 );
                 CHECK_FALSE( RuleInterfaceSpy::reenable_called );
             }
@@ -515,7 +515,7 @@ TEST_CASE ( "rule latency impl", "[latency]" )
         {
             config.config.suspend = false;
 
-            CHECK_FALSE( impl.suspended() );
+            CHECK( false == impl.suspended() );
             CHECK_FALSE( RuleInterfaceSpy::is_suspended_called );
         }
 
@@ -523,7 +523,7 @@ TEST_CASE ( "rule latency impl", "[latency]" )
         {
             config.config.suspend = true;
 
-            CHECK( impl.suspended() );
+            CHECK( true == impl.suspended() );
             CHECK( RuleInterfaceSpy::is_suspended_called );
         }
     }
@@ -542,7 +542,7 @@ TEST_CASE ( "rule latency impl", "[latency]" )
             {
                 RuleInterfaceSpy::is_suspended_result = true;
 
-                CHECK_FALSE( impl.pop() );
+                CHECK( false == impl.pop() );
                 CHECK( event_handler.count == 0 );
                 CHECK_FALSE( RuleInterfaceSpy::timeout_and_suspend_called );
             }
@@ -552,7 +552,7 @@ TEST_CASE ( "rule latency impl", "[latency]" )
                 RuleInterfaceSpy::is_suspended_result = false;
                 RuleInterfaceSpy::timeout_and_suspend_result = true;
 
-                CHECK( impl.pop() );
+                CHECK( true == impl.pop() );
                 CHECK( event_handler.count == 1 );
                 CHECK( RuleInterfaceSpy::timeout_and_suspend_called );
             }
@@ -561,7 +561,7 @@ TEST_CASE ( "rule latency impl", "[latency]" )
             {
                 RuleInterfaceSpy::timeout_and_suspend_result = false;
 
-                CHECK( impl.pop() );
+                CHECK( true == impl.pop() );
                 CHECK( event_handler.count == 1 );
                 CHECK( RuleInterfaceSpy::timeout_and_suspend_called );
             }
@@ -573,7 +573,7 @@ TEST_CASE ( "rule latency impl", "[latency]" )
         {
             RuleInterfaceSpy::is_suspended_result = false;
 
-            CHECK_FALSE( impl.pop() );
+            CHECK( false == impl.pop() );
             CHECK( event_handler.count == 0 );
             CHECK_FALSE( RuleInterfaceSpy::timeout_and_suspend_called );
         }
@@ -608,9 +608,9 @@ TEST_CASE ( "default latency rule interface", "[latency]" )
 
     SECTION( "is_suspended" )
     {
-        CHECK_FALSE( RuleInterface::is_suspended(root) );
+        CHECK( false == RuleInterface::is_suspended(root) );
         root.latency_state[0].suspend(hr_time(0_ticks));
-        CHECK( RuleInterface::is_suspended(root) );
+        CHECK( true == RuleInterface::is_suspended(root) );
     }
 
     SECTION( "reenable" )
@@ -618,7 +618,7 @@ TEST_CASE ( "default latency rule interface", "[latency]" )
         SECTION( "rule already enabled" )
         {
             REQUIRE_FALSE( root.latency_state[get_instance_id()].suspended );
-            CHECK_FALSE( RuleInterface::reenable(root, 0_ticks, hr_time(0_ticks)) );
+            CHECK( false == RuleInterface::reenable(root, 0_ticks, hr_time(0_ticks)) );
         }
 
         SECTION( "rule suspended" )
@@ -627,12 +627,12 @@ TEST_CASE ( "default latency rule interface", "[latency]" )
 
             SECTION( "suspend time not exceeded" )
             {
-                CHECK_FALSE( RuleInterface::reenable(root, 1_ticks, hr_time(0_ticks)) );
+                CHECK( false == RuleInterface::reenable(root, 1_ticks, hr_time(0_ticks)) );
             }
 
             SECTION( "suspend time exceeded" )
             {
-                CHECK( RuleInterface::reenable(root, 1_ticks, hr_time(2_ticks)) );
+                CHECK( true == RuleInterface::reenable(root, 1_ticks, hr_time(2_ticks)) );
             }
         }
     }
@@ -643,14 +643,14 @@ TEST_CASE ( "default latency rule interface", "[latency]" )
         {
             SECTION( "timeouts under threshold" )
             {
-                CHECK_FALSE( RuleInterface::timeout_and_suspend(root, 2, hr_time(0_ticks), true) );
+                CHECK( false == RuleInterface::timeout_and_suspend(root, 2, hr_time(0_ticks), true) );
                 CHECK( child_state[0].latency_timeouts == 1 );
                 CHECK( child_state[0].latency_suspends == 0 );
             }
 
             SECTION( "timeouts exceed threshold" )
             {
-                CHECK( RuleInterface::timeout_and_suspend(root, 1, hr_time(0_ticks), true) );
+                CHECK( true == RuleInterface::timeout_and_suspend(root, 1, hr_time(0_ticks), true) );
                 CHECK( child_state[0].latency_timeouts == 1 );
                 CHECK( child_state[0].latency_suspends == 1 );
             }
@@ -658,7 +658,7 @@ TEST_CASE ( "default latency rule interface", "[latency]" )
 
         SECTION( "suspend disabled" )
         {
-            CHECK_FALSE( RuleInterface::timeout_and_suspend(root, 0, hr_time(0_ticks), false) );
+            CHECK( false == RuleInterface::timeout_and_suspend(root, 0, hr_time(0_ticks), false) );
             CHECK( child_state[0].latency_timeouts == 1 );
             CHECK( child_state[0].latency_suspends == 0 );
         }
index 130086ef6e1ee34315992897042fdf7c50a04c20..a985bbe8d0833fca10fc4ae0f219490aaa82696f 100644 (file)
@@ -41,8 +41,8 @@ struct ObfuscatorBlock
     // Used for iterations
     ObfuscatorBlock() = default;
 
-    uint32_t offset;
-    size_t length;
+    uint32_t offset = 0;
+    size_t length = 0;
 };
 
 class SO_PUBLIC Obfuscator
index 713e391a8c1643bf1cc38d5edefafd52c1858b3f..6808d7f52478921f570681bfa736a1b9b77bcdd7 100644 (file)
@@ -188,7 +188,7 @@ TEST(ObfuscatorTests, SortedElements)
     ob.push(0,0);
 
     uint32_t last = 0;
-    for ( auto &b: ob )
+    for ( const auto &b: ob )
     {
         CHECK_TRUE(last <= b.offset);
         last = b.offset;
@@ -203,7 +203,7 @@ TEST(ObfuscatorTests, Overlaps)
     ob.push(0,100);
 
     uint32_t last = 0;
-    for ( auto &b: ob )
+    for ( const auto &b: ob )
     {
         CHECK_TRUE(last <= b.offset);
         last = b.offset;
index 8d509bf8e67d141fa09a1b4733c1861401bf37a8..7792b9b4a4fe3c2ff64a682fbd278ef9236218bb 100644 (file)
@@ -609,13 +609,12 @@ public:
     string sep;
 };
 
-CsvLogger::CsvLogger(CsvModule* m)
-{
-    file = m->file ? F_NAME : "stdout";
-    limit = m->limit;
-    sep = m->sep;
-    fields = std::move(m->fields);
-}
+CsvLogger::CsvLogger(CsvModule* m) :
+    file(m->file ? F_NAME : "stdout"),
+    limit(m->limit),
+    fields(std::move(m->fields)),
+    sep(m->sep)
+{ }
 
 void CsvLogger::open()
 {
index 4e328a4c0af4214d018c018995537ff787e19460..572d280993ea0c9f09acd7c8857543a20f2142de 100644 (file)
@@ -182,12 +182,8 @@ private:
 std::vector<unsigned> FastLogger::req_ids;
 std::vector<unsigned> FastLogger::rsp_ids;
 
-FastLogger::FastLogger(FastModule* m)
-{
-    file = m->file ? F_NAME : "stdout";
-    limit = m->limit;
-    packet = m->packet;
-}
+FastLogger::FastLogger(FastModule* m) : file(m->file ? F_NAME : "stdout"), limit(m->limit), packet(m->packet)
+{ }
 
 //-----------------------------------------------------------------
 // FIXIT-L generalize buffer sets when other inspectors get smarter
index 9059f7842b2cb3572dc8323095ed2f899af69b2b..4bbecaf61ea3219770c8777ccb638b6f25f8ff52 100644 (file)
@@ -129,11 +129,8 @@ private:
     unsigned long limit;
 };
 
-FullLogger::FullLogger(FullModule* m)
-{
-    file = m->file ? F_NAME : "stdout";
-    limit = m->limit;
-}
+FullLogger::FullLogger(FullModule* m) : file(m->file ? F_NAME : "stdout"), limit(m->limit)
+{ }
 
 void FullLogger::open()
 {
index d062e260d3a4e698d4307848541e7501cd6d059c..696fc1e1c01209252bc4a3830caa777156cc6dcb 100644 (file)
@@ -804,13 +804,8 @@ public:
     string sep;
 };
 
-JsonLogger::JsonLogger(JsonModule* m)
-{
-    file = m->file ? F_NAME : "stdout";
-    limit = m->limit;
-    sep = m->sep;
-    fields = std::move(m->fields);
-}
+JsonLogger::JsonLogger(JsonModule* m) : file(m->file ? F_NAME : "stdout"), limit(m->limit), fields(std::move(m->fields)), sep(m->sep)
+{ }
 
 void JsonLogger::open()
 {
index f40039c6387c602bd5dfba7fff3fd9dd66c4206b..4ccf4008ae7a9d093fa10afa1148bea7c5b30fa5 100644 (file)
@@ -147,12 +147,8 @@ private:
 };
 
 LuaJitLogger::LuaJitLogger(const char* name, std::string& chunk, LuaLogModule* mod)
+    : config("args = { " + mod->args + "}")
 {
-    // create an args table with any rule options
-    config = "args = { ";
-    config += mod->args;
-    config += "}";
-
     unsigned max = ThreadConfig::get_instance_max();
 
     // FIXIT-L might make more sense to have one instance with one lua state in
@@ -168,6 +164,7 @@ LuaJitLogger::LuaJitLogger(const char* name, std::string& chunk, LuaLogModule* m
 
 void LuaJitLogger::alert(Packet* p, const char*, const Event& e)
 {
+    // cppcheck-suppress unreadVariable
     Profile profile(luaLogPerfStats);
 
     packet = p;
index d367d22e0602106e5c464bcbcce45df8f0e01d7f..144bafa85c4b1da38f584904194a7095dfff0039 100644 (file)
@@ -293,7 +293,7 @@ static void AlertSyslog(
     }
     else if (msg != nullptr)
     {
-        syslog(priority, "%s", msg == nullptr ? "ALERT" : msg);
+        syslog(priority, "%s", msg);
     }
 }
 
index f10e82a58ce351a12138bf7287471f6df695de81..14ed92d695725c5afebfb9795710fa67df1bffa8 100644 (file)
@@ -276,12 +276,8 @@ private:
 };
 
 HextLogger::HextLogger(HextModule* m)
+    : file(m->file ? F_NAME : "stdout"), limit(m->limit), width(m->width), raw(m->raw)
 {
-    file = m->file ? F_NAME : "stdout";
-    limit = m->limit;
-    width = m->width;
-    raw = m->raw;
-
     DataBus::subscribe(intrinsic_pub_key, IntrinsicEventIds::DAQ_SOF_MSG, new DaqMessageEventHandler());
     DataBus::subscribe(intrinsic_pub_key, IntrinsicEventIds::DAQ_EOF_MSG, new DaqMessageEventHandler());
 }
index 5d34097dde3e474397a57813fe13b2991b747ea1..097e7504ba8b601aaeeb397b87988d10c6cac0e6 100644 (file)
@@ -50,7 +50,6 @@ using namespace std;
 
 struct LtdConfig
 {
-    string file;
     size_t limit;
 };
 
index 47f3b2a2999d4e94db05d49e3615a53f2957ef47..cf599b59cdd103aebfee91aec09af70ca57ac049 100644 (file)
@@ -330,8 +330,8 @@ static void _WriteExtraData(Unified2Config* config,
 
 static void AlertExtraData(
     Flow* flow, void* data,
-    LogFunction* log_funcs, uint32_t max_count,
-    uint32_t xtradata_mask, const AlertInfo& alert_info)
+    LogFunction* log_funcs, //cppcheck-suppress constParameter
+    uint32_t max_count, uint32_t xtradata_mask, const AlertInfo& alert_info)
 {
     Unified2Config* config = (Unified2Config*)data;
     uint32_t xid;
index e955ec62675350f2a983a85da4797ed81232d2b4..4753c162857f8c7d10383ada7f32d4ee6feb6840 100644 (file)
@@ -378,6 +378,7 @@ void Analyzer::post_process_daq_pkt_msg(Packet* p)
         p->pkth = nullptr;  // No longer avail after finalize_message.
 
         {
+            // cppcheck-suppress unreadVariable
             Profile profile(daqPerfStats);
             p->daq_instance->finalize_message(p->daq_msg, verdict);
         }
@@ -471,6 +472,7 @@ void Analyzer::process_daq_msg(DAQ_Msg_h msg, bool retry)
     }
     oops_handler->set_current_message(nullptr, nullptr);
     {
+        // cppcheck-suppress unreadVariable
         Profile profile(daqPerfStats);
         daq_instance->finalize_message(msg, verdict);
     }
@@ -521,6 +523,7 @@ void Analyzer::post_process_packet(Packet* p)
 
 void Analyzer::finalize_daq_message(DAQ_Msg_h msg, DAQ_Verdict verdict)
 {
+    // cppcheck-suppress unreadVariable
     Profile profile(daqPerfStats);
     daq_instance->finalize_message(msg, verdict);
 }
@@ -685,6 +688,7 @@ void Analyzer::term()
     while ((msg = retry_queue->get()) != nullptr)
     {
         daq_stats.retries_discarded++;
+        // cppcheck-suppress unreadVariable
         Profile profile(daqPerfStats);
         daq_instance->finalize_message(msg, DAQ_VERDICT_BLOCK);
     }
@@ -728,14 +732,14 @@ void Analyzer::term()
     TraceApi::thread_term();
 }
 
-Analyzer::Analyzer(SFDAQInstance* instance, unsigned i, const char* s, uint64_t msg_cnt)
+Analyzer::Analyzer(SFDAQInstance* instance, unsigned i, const char* s, uint64_t msg_cnt) :
+    id(i),
+    exit_after_cnt(msg_cnt),
+    source(s ? s : ""),
+    daq_instance(instance),
+    retry_queue(new RetryQueue(200)),
+    oops_handler(new OopsHandler())
 {
-    id = i;
-    exit_after_cnt = msg_cnt;
-    source = s ? s : "";
-    daq_instance = instance;
-    oops_handler = new OopsHandler();
-    retry_queue = new RetryQueue(200);
     set_state(State::NEW);
 }
 
@@ -876,6 +880,7 @@ DAQ_RecvStatus Analyzer::process_messages()
 
     DAQ_RecvStatus rstat;
     {
+        // cppcheck-suppress unreadVariable
         Profile profile(daqPerfStats);
         rstat = daq_instance->receive_messages(max_recv);
     }
index 1b0f37bdf26a5bbb0568c08774230458db0d1e7e..ac1bf70d0346f559f6d92739fb6b547425075e4c 100644 (file)
@@ -80,6 +80,7 @@ public:
     static ContextSwitcher* get_switcher();
     static void set_main_hook(MainHook_f);
 
+    Analyzer() = delete;
     Analyzer(snort::SFDAQInstance*, unsigned id, const char* source, uint64_t msg_cnt = 0);
     ~Analyzer();
 
@@ -149,8 +150,8 @@ private:
     uint64_t skip_cnt = 0;
     std::string source;
     snort::SFDAQInstance* daq_instance;
-    RetryQueue* retry_queue = nullptr;
-    OopsHandler* oops_handler = nullptr;
+    RetryQueue* retry_queue;
+    OopsHandler* oops_handler;
     ContextSwitcher* switcher = nullptr;
     std::mutex pending_work_queue_mutex;
     std::list<UncompletedAnalyzerCommand*> uncompleted_work_queue;
index 9917e76f7eca125a0921c17129eefe45725c6436..422ea86c42871627a857552a365ad0f715e408e8 100644 (file)
@@ -358,7 +358,7 @@ public:
 private:
     string name;
     string text;
-    unsigned priority;
+    unsigned priority = 0;
 };
 
 bool ClassificationsModule::begin(const char*, int, SnortConfig*)
@@ -1202,8 +1202,8 @@ public:
     { return GLOBAL; }
 
 private:
-    int thread;
-    CpuSet* cpuset;
+    int thread = 0;
+    CpuSet* cpuset = nullptr;
     string type;
     string name;
 };
@@ -1369,7 +1369,7 @@ public:
     { return CONTEXT; }
 
 private:
-    THDX_STRUCT thdx;
+    THDX_STRUCT thdx = {};
 };
 
 bool SuppressModule::set(const char*, Value& v, SnortConfig*)
@@ -1488,7 +1488,7 @@ public:
     { return CONTEXT; }
 
 private:
-    THDX_STRUCT thdx;
+    THDX_STRUCT thdx = {};
 };
 
 bool EventFilterModule::set(const char*, Value& v, SnortConfig*)
@@ -1707,7 +1707,7 @@ class HostsModule : public Module
 {
 public:
     HostsModule() : Module("hosts", hosts_help, hosts_params, true)
-    { host = nullptr; }
+    { }
 
     ~HostsModule() override
     { assert(!host); }
@@ -1727,7 +1727,7 @@ public:
 
 private:
     HostServiceDescriptor service;
-    HostAttributesEntry host;
+    HostAttributesEntry host = nullptr;
 };
 
 bool HostsModule::set(const char*, Value& v, SnortConfig* sc)
index db1b11c423eb447765830b75f1e2293d2a40abc5..30c8a6b5bc9bdba9a89e5de1fc414e9be52b05a9 100644 (file)
@@ -282,12 +282,8 @@ PolicyMap::~PolicyMap()
 
 bool PolicyMap::setup_network_policies()
 {
-    for (auto* np : network_policy)
-    {
-        if (!set_user_network(np))
-            return false;
-    }
-    return true;
+    return std::none_of(network_policy.begin(), network_policy.end(),
+        [this](NetworkPolicy* np){ return !set_user_network(np); });
 }
 
 void PolicyMap::clone(PolicyMap *other_map, const char* exclude_name)
index 5a6944bffb1b1ea29fd0c15a84f8ce99eab0738c..dc9cebe9bbdedf3a7e30785ae5b92f681077e497 100644 (file)
@@ -50,7 +50,7 @@ bool ReloadTracker::start(ControlConn* ctrlcon)
     return true;
 }
 
-void ReloadTracker::end(ControlConn* ctrlcon, bool prompt)
+void ReloadTracker::end(const ControlConn* ctrlcon, bool prompt)
 {
 #ifdef NDEBUG
     UNUSED(ctrlcon);
@@ -65,7 +65,7 @@ void ReloadTracker::end(ControlConn* ctrlcon, bool prompt)
     reload_in_progress = false;
 }
 
-void ReloadTracker::failed(ControlConn* ctrlcon, const char* reason)
+void ReloadTracker::failed(const ControlConn* ctrlcon, const char* reason)
 {
 #ifdef NDEBUG
     UNUSED(ctrlcon);
@@ -78,7 +78,7 @@ void ReloadTracker::failed(ControlConn* ctrlcon, const char* reason)
     reload_in_progress = false;
 }
 
-void ReloadTracker::update(ControlConn* ctrlcon, const char* status)
+void ReloadTracker::update(const ControlConn* ctrlcon, const char* status)
 {
 #ifdef NDEBUG
     UNUSED(ctrlcon);
index 6b025e4217ff83d96cd7cbf8aa111eb0efd6b6a0..cd3d2195c17212bcef55817c27359556e4a9d5ad 100644 (file)
@@ -34,9 +34,9 @@ class SO_PUBLIC ReloadTracker
 public:
     ReloadTracker() = delete;
     static bool start(ControlConn* ctrlcon);
-    static void end(ControlConn* ctrlcon, bool prompt=false);
-    static void failed(ControlConn* ctrlcon, const char* reason);
-    static void update(ControlConn* ctrlcon, const char* status);
+    static void end(const ControlConn* ctrlcon, bool prompt=false);
+    static void failed(const ControlConn* ctrlcon, const char* reason);
+    static void update(const ControlConn* ctrlcon, const char* status);
 
 private:
     static bool reload_in_progress;
index 070f5a3bd76cd09495810462061c092196033fe3..1874debd92907dab61a240315cb5352d70431161 100644 (file)
@@ -361,7 +361,7 @@ void Snort::term()
     detection_filter_term();
 
     term_signals();
-    
+
 }
 
 void Snort::clean_exit(int)
index accee009c852108e3c3b47068aab4857b93057a3..76ff805bcc4fad99cc01ce114bfc74932986a98c 100644 (file)
@@ -279,7 +279,7 @@ SnortConfig::~SnortConfig()
     delete trace_config;
     delete overlay_trace_config;
     delete ha_config;
-        delete global_dbus;
+    delete global_dbus;
 
     delete profiler;
     delete latency;
@@ -336,11 +336,8 @@ void SnortConfig::post_setup()
     for ( unsigned i = 0; i < num_slots; ++i )
         state[i].resize(handler_count);
 
-    for ( auto* s : scratch_handlers )
-    {
-        if ( s and s->setup(this) )
-            scratchers.push_back(s);
-    }
+    std::copy_if(scratch_handlers.begin(), scratch_handlers.end(), std::back_inserter(scratchers),
+        [this](ScratchAllocator* s){ return s and s->setup(this); });
 }
 
 void SnortConfig::update_scratch(ControlConn* ctrlcon)
@@ -385,14 +382,13 @@ void SnortConfig::merge(const SnortConfig* cmd_line_conf)
     daq_config->overlay(cmd_line_conf->daq_config);
 
     // -k (only configures eval, not drop)
-    int cl_chk = cmd_line_conf->policy_map->get_network_policy()->checksum_eval;
+    uint32_t cl_chk = cmd_line_conf->policy_map->get_network_policy()->checksum_eval;
     if (!(cl_chk & CHECKSUM_FLAG__DEF))
     {
         for (unsigned idx = 0; idx < policy_map->network_policy_count(); ++idx)
         {
             NetworkPolicy* nw_policy = policy_map->get_network_policy(idx);
-            if (!(cl_chk & CHECKSUM_FLAG__DEF))
-                nw_policy->checksum_eval = cl_chk;
+            nw_policy->checksum_eval = cl_chk;
         }
     }
 
@@ -964,24 +960,24 @@ bool SnortConfig::get_default_rule_state() const
 
 ConfigOutput* SnortConfig::create_config_output() const
 {
-    ConfigOutput* output = nullptr;
+    ConfigOutput* output_cfg = nullptr;
 
     switch (dump_config_type)
     {
     case DUMP_CONFIG_JSON_ALL:
-        output = new JsonAllConfigOutput();
+        output_cfg = new JsonAllConfigOutput();
         break;
     case DUMP_CONFIG_JSON_TOP:
-        output = new JsonTopConfigOutput();
+        output_cfg = new JsonTopConfigOutput();
         break;
     case DUMP_CONFIG_TEXT:
-        output = new TextConfigOutput();
+        output_cfg = new TextConfigOutput();
         break;
     default:
         break;
     }
 
-    return output;
+    return output_cfg;
 }
 
 bool SnortConfig::tunnel_bypass_enabled(uint16_t proto) const
index b73a68b69ecf84f58e0db15b2dc3bbfbecaec02f..6cf8e86f2e8f17f9977614fe6891c71117026b0b 100644 (file)
@@ -701,7 +701,7 @@ public:
 private:
     inline bool is(const Value& v, const char* opt);
 
-    SFDAQModuleConfig* module_config;
+    SFDAQModuleConfig* module_config = nullptr;
     bool no_warn_flowbits = false;
     bool no_warn_rules = false;
     std::string stub_opts;
index c2706726fc2e3d6eb8f32f9210cf4dab66065187..5a2c72e963737d3eb364dc5c8c8ebfcda2d6a1c0 100644 (file)
@@ -15,7 +15,7 @@
 // with this program; if not, write to the Free Software Foundation, Inc.,
 // 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 //--------------------------------------------------------------------------
-// stubs.h author Ron Dempster <rdempste@cisco.com>
+// distill_verdict_stubs.h author Ron Dempster <rdempste@cisco.com>
 
 #include "detection/context_switcher.h"
 #include "detection/detection_engine.h"
@@ -162,7 +162,7 @@ bool SFDAQ::can_inject() { return false; }
 bool SFDAQ::can_inject_raw() { return false; }
 bool SFDAQ::can_replace() { return false; }
 int SFDAQInstance::set_packet_verdict_reason(DAQ_Msg_h, uint8_t) { return 0; }
-DetectionEngine::DetectionEngine() = default;
+DetectionEngine::DetectionEngine() { context = nullptr; }
 DetectionEngine::~DetectionEngine() = default;
 void DetectionEngine::onload() { }
 void DetectionEngine::thread_init() { }
index fb4cab7c028a31f2fac6b64961357fd307e20e6c..29cea962bb1b87ebedd4a90d5327d11da9accb13 100644 (file)
@@ -153,10 +153,10 @@ void ThreadConfig::term()
 
 ThreadConfig::~ThreadConfig()
 {
-    for (auto& iter : thread_affinity)
+    for (const auto& iter : thread_affinity)
         delete iter.second;
 
-    for (auto& iter : named_thread_affinity)
+    for (const auto& iter : named_thread_affinity)
         delete iter.second;
 }
 
@@ -624,11 +624,11 @@ TEST_CASE("set node for thread", "[ThreadConfig]")
     tc.set_thread_affinity(STHREAD_TYPE_PACKET, 0, cpuset2);
     tc.set_thread_affinity(STHREAD_TYPE_PACKET, 1, cpuset);
 
-    CHECK(tc.implement_thread_mempolicy(STHREAD_TYPE_PACKET, 0));
+    CHECK(true == tc.implement_thread_mempolicy(STHREAD_TYPE_PACKET, 0));
 
     hwloc_mock->node.os_index = 1;
     numa_mock->pref = 1;
-    CHECK(tc.implement_thread_mempolicy(STHREAD_TYPE_PACKET, 1));
+    CHECK(true == tc.implement_thread_mempolicy(STHREAD_TYPE_PACKET, 1));
 }
 
 TEST_CASE("numa_available negative test", "[ThreadConfig]")
@@ -643,7 +643,7 @@ TEST_CASE("numa_available negative test", "[ThreadConfig]")
     numa_mock->numa_avail = -1;
     numa = numa_mock;
     hwloc = hwloc_mock;
-    CHECK(!tc.implement_thread_mempolicy(STHREAD_TYPE_PACKET, 0));
+    CHECK(false == tc.implement_thread_mempolicy(STHREAD_TYPE_PACKET, 0));
 }
 
 TEST_CASE("set node failure negative test", "[ThreadConfig]")
@@ -658,7 +658,7 @@ TEST_CASE("set node failure negative test", "[ThreadConfig]")
     numa_mock->pref = -1;
     numa = numa_mock;
     hwloc = hwloc_mock;
-    CHECK(!tc.implement_thread_mempolicy(STHREAD_TYPE_PACKET, 0));
+    CHECK(false == tc.implement_thread_mempolicy(STHREAD_TYPE_PACKET, 0));
 }
 
 TEST_CASE("depth unknown negative test", "[ThreadConfig]")
@@ -674,7 +674,7 @@ TEST_CASE("depth unknown negative test", "[ThreadConfig]")
     hwloc_mock->type_depth = HWLOC_TYPE_DEPTH_UNKNOWN;
     hwloc = hwloc_mock;
     numa = numa_mock;
-    CHECK(!tc.implement_thread_mempolicy(STHREAD_TYPE_PACKET, 0));
+    CHECK(false == tc.implement_thread_mempolicy(STHREAD_TYPE_PACKET, 0));
 }
 
 TEST_CASE("set memory policy failure negative test", "[ThreadConfig]")
@@ -690,7 +690,7 @@ TEST_CASE("set memory policy failure negative test", "[ThreadConfig]")
     numa_mock->mem_policy = -1;
     numa = numa_mock;
     hwloc = hwloc_mock;
-    CHECK(!tc.implement_thread_mempolicy(STHREAD_TYPE_PACKET, 0));
+    CHECK(false == tc.implement_thread_mempolicy(STHREAD_TYPE_PACKET, 0));
 }
 
 TEST_CASE("get_nbobjs_by_depth failure negative test", "[ThreadConfig]")
@@ -705,7 +705,7 @@ TEST_CASE("get_nbobjs_by_depth failure negative test", "[ThreadConfig]")
     hwloc_mock->nbobjs_by_depth = 0;
     hwloc = hwloc_mock;
     numa = numa_mock;
-    CHECK(!tc.implement_thread_mempolicy(STHREAD_TYPE_PACKET, 0));
+    CHECK(false == tc.implement_thread_mempolicy(STHREAD_TYPE_PACKET, 0));
 }
 
 #endif
index dcab42107af40d340cab77c01163c8eccc9fda49..0da1d55d09c705da6110178bd3a72da213db6818 100644 (file)
@@ -85,11 +85,10 @@ std::string ActionManager::get_action_string(Actions::Type action)
 {
     if ( action < s_act_index )
     {
-        for ( const auto& type : s_act_types )
-        {
-            if ( type.second == action )
-                return type.first;
-        }
+        auto it = std::find_if(s_act_types.cbegin(), s_act_types.cend(),
+            [action](const std::pair<const std::string, Actions::Type>& type){ return type.second == action; });
+        if ( it != s_act_types.cend())
+            return (*it).first;
     }
 
     return "ERROR";
@@ -144,7 +143,7 @@ void ActionManager::dump_plugins()
 {
     Dumper d("IPS Actions");
 
-    for ( auto& p : s_actors )
+    for ( const auto& p : s_actors )
         d.dump(p.api->base.name, p.api->base.version);
 }
 
@@ -160,24 +159,23 @@ void ActionManager::release_plugins()
 
 static ActionClass* get_action_class(const ActionApi* api, IpsActionsConfig* iac)
 {
-    for ( auto& ai : iac->clist )
-    {
-        if ( ai.cls.api == api )
-            return &ai.cls;
-    }
-
-    for ( auto& ac : s_actors )
+    auto it = std::find_if(iac->clist.cbegin(), iac->clist.cend(),
+        [api](const ActionInst &ai){ return ai.cls.api == api; });
+    if ( it != iac->clist.cend() )
+        return &(*it).cls;
+
+    auto it2 = std::find_if(s_actors.begin(), s_actors.end(),
+        [api](const ActionClass& ac){ return ac.api == api; });
+    if ( it2 != s_actors.end() )
     {
-        if ( ac.api == api )
+        ActionClass& ac = *it2;
+        if ( !ac.initialized )
         {
-            if ( !ac.initialized )
-            {
-                if ( ac.api->pinit )
-                    ac.api->pinit();
-                ac.initialized = true;
-            }
-            return &ac;
+            if ( ac.api->pinit )
+                ac.api->pinit();
+            ac.initialized = true;
         }
+        return &ac;
     }
 
     return nullptr;
@@ -253,11 +251,10 @@ void ActionManager::initialize_policies(SnortConfig* sc)
 //-------------------------------------------------------------------------
 static ActionClass& get_thread_local_action_class(const ActionApi* api)
 {
-    for ( ActionClass& p : *s_tl_actors )
-    {
-        if ( p.api == api )
-            return p;
-    }
+    auto it = std::find_if(s_tl_actors->begin(), s_tl_actors->end(),
+        [api](const ActionClass& p){ return p.api == api; });
+    if ( it != s_tl_actors->end() )
+        return *it;
     s_tl_actors->emplace_back(api);
     return s_tl_actors->back();
 }
@@ -266,7 +263,7 @@ void ActionManager::thread_init(const SnortConfig* sc)
 {
     // Initial build out of this thread's configured plugin registry
     s_tl_actors = new ACList;
-    for ( auto& p : sc->ips_actions_config->clist )
+    for ( const auto& p : sc->ips_actions_config->clist )
     {
         ActionClass& tlac = get_thread_local_action_class(p.cls.api);
         if ( tlac.api->tinit )
@@ -278,7 +275,7 @@ void ActionManager::thread_init(const SnortConfig* sc)
 void ActionManager::thread_reinit(const SnortConfig* sc)
 {
     // Update this thread's configured plugin registry with any newly configured inspectors
-    for ( auto& p : sc->ips_actions_config->clist )
+    for ( const auto& p : sc->ips_actions_config->clist )
     {
         ActionClass& tlac = get_thread_local_action_class(p.cls.api);
         if (!tlac.initialized)
index 8d8a56853b8cc904fa4bf83feb7fb10d5014fb66..32546023a75aac00f7f36cc96f46a89ddaf86dc7 100644 (file)
@@ -78,11 +78,10 @@ uint8_t CodecManager::get_codec(const char* const keyword)
 
 CodecManager::CodecApiWrapper& CodecManager::get_api_wrapper(const CodecApi* cd_api)
 {
-    for (CodecApiWrapper& caw : s_codecs)
-    {
-        if (caw.api == cd_api)
-            return caw;
-    }
+    auto it = std::find_if(s_codecs.begin(), s_codecs.end(),
+        [cd_api](const CodecApiWrapper& caw){ return caw.api == cd_api; });
+    if (it != s_codecs.end())
+        return *it;
 
     ParseAbort("Attempting to instantiate Codec '%s', "
         "but codec has not been added", cd_api->base.name);
@@ -243,7 +242,7 @@ void CodecManager::dump_plugins()
 {
     Dumper d("Codecs");
 
-    for ( CodecApiWrapper& wrap : s_codecs )
+    for ( const CodecApiWrapper& wrap : s_codecs )
         d.dump(wrap.api->base.name, wrap.api->base.version);
 }
 
index 6705ad7a7cd83835d24ea83aaa6b096da104e848..1128bd9f46c120ad539edd98ec6a5d039f607ef3 100644 (file)
@@ -72,7 +72,7 @@ void ConnectorManager::dump_plugins()
 {
     Dumper d("Connectors");
 
-    for ( auto& sc : s_connector_commons )
+    for ( const auto& sc : s_connector_commons )
         d.dump(sc.api->base.name, sc.api->base.version);
 }
 
@@ -83,7 +83,7 @@ void ConnectorManager::release_plugins()
         if ( sc.api->dtor )
             sc.api->dtor(sc.connector_common);
 
-        for ( auto& conn : sc.connectors )
+        for ( const auto& conn : sc.connectors )
             delete conn.second;
 
         sc.connectors.clear();
index 0a43a1f28ff6eab0cf3f14fe70127aac86652cf1..f311f99447051b1515b95fe5e3ec0d7b0a318617 100644 (file)
@@ -76,7 +76,7 @@ void EventManager::release_plugins()
 {
     s_loggers.outputs.clear();
 
-    for ( auto* p : s_outputs )
+    for ( const auto* p : s_outputs )
         delete p;
 
     s_outputs.clear();
index 9c27cac0046d3688bb10b33ea3299cb468a12ba6..5587b67be91b1c8671371583b2fd0f2477140277 100644 (file)
@@ -343,7 +343,7 @@ void InspectorList::populate_all_removed(SnortConfig* sc, InspectorList* def_il,
 
 void InspectorList::clear_removed()
 {
-    for ( auto& ri : removed_ilist )
+    for ( const auto& ri : removed_ilist )
         ri.instance->handler->rem_global_ref();
     removed_ilist.clear();
 }
@@ -354,18 +354,15 @@ void InspectorList::reconcile_inspectors(SnortConfig* sc, InspectorList* old_lis
     {
         for (auto* p : ilist)
         {
-            for (auto* old_p : old_list->ilist)
+            auto it = std::find_if(old_list->ilist.cbegin(), old_list->ilist.cend(),
+                [&p](const PHInstance* old_p){ return old_p->name == p->name; });
+            if (it != old_list->ilist.cend())
             {
-                if (old_p->name == p->name)
+                ReloadType reload_type = p->get_reload_type();
+                if (!cloned || RELOAD_TYPE_NEW == reload_type || RELOAD_TYPE_REENABLED == reload_type)
                 {
-                    ReloadType reload_type = p->get_reload_type();
-                    if (!cloned || RELOAD_TYPE_NEW == reload_type
-                        || RELOAD_TYPE_REENABLED == reload_type)
-                    {
-                        p->handler->copy_thread_storage(old_p->handler);
-                        p->handler->install_reload_handler(sc);
-                    }
-                    break;
+                    p->handler->copy_thread_storage((*it)->handler);
+                    p->handler->install_reload_handler(sc);
                 }
             }
         }
@@ -416,7 +413,7 @@ TrafficPolicy::~TrafficPolicy()
         --ts_handlers->ref_count;
         if (!ts_handlers->ref_count)
         {
-            for (auto* h : ts_handlers->olists)
+            for (const auto* h : ts_handlers->olists)
                 delete h;
             delete ts_handlers;
         }
@@ -853,9 +850,10 @@ PHInstance* FrameworkPolicy::get_instance_by_type(const char* key, InspectorType
 std::vector<const InspectApi*> InspectorManager::get_apis()
 {
     std::vector<const InspectApi*> v;
+    v.reserve(s_handlers.size());
 
-    for ( const auto* p : s_handlers )
-        v.emplace_back(&p->api);
+    std::transform(s_handlers.cbegin(), s_handlers.cend(), std::back_inserter(v),
+        [](const PHObject* p){ return &p->api; });
 
     return v;
 }
@@ -878,7 +876,7 @@ void InspectorManager::add_plugin(const InspectApi* api)
 
 static const InspectApi* get_plugin(const char* keyword)
 {
-    for ( auto* p : s_handlers )
+    for ( const auto* p : s_handlers )
         if ( !strcmp(p->api.base.name, keyword) )
             return &p->api;
 
@@ -1415,11 +1413,11 @@ void InspectorManager::free_inspector(Inspector* p)
 
 InspectSsnFunc InspectorManager::get_session(uint16_t proto)
 {
-    for ( auto* p : s_handlers )
-    {
-        if ( p->api.type == IT_STREAM && p->api.proto_bits == proto && p->initialized )
-            return p->api.ssn;
-    }
+    auto it = std::find_if(s_handlers.cbegin(), s_handlers.cend(),
+        [proto](const PHObject* p)
+        { return p->api.type == IT_STREAM && p->api.proto_bits == proto && p->initialized; });
+    if (it != s_handlers.cend())
+        return (*it)->api.ssn;
     return nullptr;
 }
 
@@ -1437,7 +1435,7 @@ void InspectorManager::delete_config(SnortConfig* sc)
     if ( !sc->framework_config )
         return;
 
-    for ( auto* p : sc->framework_config->clist )
+    for ( const auto* p : sc->framework_config->clist )
         delete p;
 
     delete sc->framework_config;
@@ -1446,11 +1444,13 @@ void InspectorManager::delete_config(SnortConfig* sc)
 
 static PHClass* get_class(const char* keyword, FrameworkConfig* fc)
 {
+    // cppcheck-suppress constVariable
     for ( auto* p : fc->clist )
         if ( !strcmp(p->api.base.name, keyword) )
             return p;
 
     for ( auto* p : s_handlers )
+    {
         if ( !strcmp(p->api.base.name, keyword) )
         {
             if ( !p->initialized )
@@ -1463,6 +1463,7 @@ static PHClass* get_class(const char* keyword, FrameworkConfig* fc)
             fc->clist.emplace_back(ppc);
             return ppc;
         }
+    }
     return nullptr;
 }
 
@@ -1470,11 +1471,10 @@ static PHObject& get_thread_local_plugin(const InspectApi& api, PHObjectList* ha
 {
     assert(handlers);
 
-    for ( PHObject& phg : *handlers )
-    {
-        if ( &phg.api == &api )
-            return phg;
-    }
+    auto it = std::find_if(handlers->begin(), handlers->end(),
+        [&api](const PHObject& phg){ return &phg.api == &api; });
+    if (it != handlers->end())
+        return (*it);
     handlers->emplace_back(api);
     return handlers->back();
 }
@@ -1908,6 +1908,7 @@ void InspectorManager::prepare_controls(SnortConfig* sc)
             g_disabled.emplace_back(gp->control.vec[i]);
     }
     gp->control.num = g_c;
+    // cppcheck-suppress constVariable
     for (auto* ph : g_disabled)
         gp->control.vec[g_c++] = ph;
     for ( unsigned idx = 0; idx < sc->policy_map->network_policy_count(); ++idx )
@@ -1923,6 +1924,7 @@ void InspectorManager::prepare_controls(SnortConfig* sc)
                 disabled.emplace_back(tp->control.vec[i]);
         }
         tp->control.num = c;
+        // cppcheck-suppress constVariable
         for (auto* ph : disabled)
             tp->control.vec[c++] = ph;
     }
index 2dd46571b6f4e2a54efc4f11dcc9f2f0df30e977..2a5b47a3cd492076fcef7870edb7d7010ecba3e5 100644 (file)
@@ -66,7 +66,7 @@ void IpsManager::add_plugin(const IpsApi* api)
 
 void IpsManager::release_plugins()
 {
-    for ( auto& p : s_options )
+    for ( const auto& p : s_options )
         delete p.second;
 
     s_options.clear();
@@ -337,7 +337,7 @@ void IpsManager::global_init(const SnortConfig*)
 
 void IpsManager::global_term(const SnortConfig* sc)
 {
-    for ( auto& p : s_options )
+    for ( const auto& p : s_options )
         if ( p.second->init && p.second->api->pterm )
         {
             p.second->api->pterm(sc);
@@ -347,27 +347,27 @@ void IpsManager::global_term(const SnortConfig* sc)
 
 void IpsManager::reset_options()
 {
-    for ( auto& p : s_options )
+    for ( const auto& p : s_options )
         p.second->count = 0;
 }
 
 void IpsManager::setup_options(const SnortConfig* sc)
 {
-    for ( auto& p : s_options )
+    for ( const auto& p : s_options )
         if ( p.second->init && p.second->api->tinit )
             p.second->api->tinit(sc);
 }
 
 void IpsManager::clear_options(const SnortConfig* sc)
 {
-    for ( auto& p : s_options )
+    for ( const auto& p : s_options )
         if ( p.second->init && p.second->api->tterm )
             p.second->api->tterm(sc);
 }
 
 bool IpsManager::verify(SnortConfig* sc)
 {
-    for ( auto& p : s_options )
+    for ( const auto& p : s_options )
         if ( p.second->init && p.second->api->verify )
             p.second->api->verify(sc);
 
index 0ff5722435bf33b419cbaa5f156a24bd9f80ee73..33187bd9ec2725b2716dc10c6d41eee9f3614cea 100644 (file)
@@ -674,14 +674,12 @@ static bool interested(Module* m)
 // ffi methods - only called from Lua so cppcheck suppressions required
 //-------------------------------------------------------------------------
 
-// cppcheck-suppress unusedFunction
 SO_PUBLIC void clear_alias()
 {
     s_aliased_name.clear();
     s_aliased_type.clear();
 }
 
-// cppcheck-suppress unusedFunction
 SO_PUBLIC bool set_alias(const char* from, const char* to)
 {
     if ( !from or !to )
@@ -692,7 +690,7 @@ SO_PUBLIC bool set_alias(const char* from, const char* to)
     if ( !m or !m->is_bindable() )
         return false;
 
-    if ( (m->get_usage() == Module::GLOBAL) and from )
+    if ( m->get_usage() == Module::GLOBAL )
     {
         ParseError("global module type '%s' can't be aliased", to);
         return false;
@@ -710,19 +708,16 @@ SO_PUBLIC bool set_alias(const char* from, const char* to)
     return true;
 }
 
-// cppcheck-suppress unusedFunction
 SO_PUBLIC void snort_whitelist_append(const char* s)
 {
     Shell::allowlist_append(s, false);
 }
 
-// cppcheck-suppress unusedFunction
 SO_PUBLIC void snort_whitelist_add_prefix(const char* s)
 {
     Shell::allowlist_append(s, true);
 }
 
-// cppcheck-suppress unusedFunction
 SO_PUBLIC const char* push_include_path(const char* file)
 {
     static std::string path;
@@ -732,13 +727,11 @@ SO_PUBLIC const char* push_include_path(const char* file)
     return path.c_str();
 }
 
-// cppcheck-suppress unusedFunction
 SO_PUBLIC void pop_include_path()
 {
     pop_parse_location();
 }
 
-// cppcheck-suppress unusedFunction
 SO_PUBLIC bool set_includer(const char* fqn, const char* s)
 {
     if ( !strcmp(fqn, "ips.includer") )
@@ -751,7 +744,6 @@ SO_PUBLIC bool set_includer(const char* fqn, const char* s)
     return true;
 }
 
-// cppcheck-suppress unusedFunction
 SO_PUBLIC int get_module_version(const char* name, const char* type)
 {
     // not all modules are plugins
@@ -941,7 +933,7 @@ void ModuleManager::init()
 
 void ModuleManager::term()
 {
-    for ( auto& mh : s_modules )
+    for ( const auto& mh : s_modules )
         delete mh.second;
 
     s_modules.clear();
@@ -986,8 +978,8 @@ list<Module*> ModuleManager::get_all_modules()
 {
     list<Module*> ret;
 
-    for ( auto& mh : s_modules )
-       ret.emplace_back(mh.second->mod);
+    std::transform(s_modules.cbegin(), s_modules.cend(), std::back_inserter(ret),
+        [](const std::pair<const std::string, ModHook*>& mh){ return mh.second->mod; });
 
     return ret;
 }
@@ -996,8 +988,8 @@ static list<ModHook*> get_all_modhooks()
 {
     list<ModHook*> ret;
 
-    for ( auto& mh : s_modules )
-       ret.emplace_back(mh.second);
+    std::transform(s_modules.cbegin(), s_modules.cend(), std::back_inserter(ret),
+        [](const std::pair<const std::string, ModHook*>& mh){ return mh.second; });
 
     return ret;
 }
@@ -1724,30 +1716,21 @@ static void dump_param_range_json(JsonStream& json, const Parameter* p)
         {
             std::string tr = range;
             const char* d = strchr(range, ':');
-            bool is_signed = ('-' == *range) || (d && '-' == d[1]);
             if ( *range == 'm' )
             {
                 if ( d )
-                {
-                    if (is_signed)
-                        tr = std::to_string(Parameter::get_int(range)) + tr.substr(tr.find(":"));
-                    else
-                        tr = std::to_string(Parameter::get_uint(range)) + tr.substr(tr.find(":"));
-                }
+                    tr = std::to_string(Parameter::get_uint(range)) + tr.substr(tr.find(":"));
                 else
-                {
-                    if (is_signed)
-                        tr = std::to_string(Parameter::get_int(range));
-                    else
-                        tr = std::to_string(Parameter::get_uint(range));
-                }
+                    tr = std::to_string(Parameter::get_uint(range));
             }
             if ( d and *++d == 'm' )
             {
-                if (is_signed)
-                    tr = tr.substr(0, tr.find(":") + 1) + std::to_string(Parameter::get_int(d));
+                bool is_signed = ('-' == *range);
+                tr.resize(tr.find(":") + 1);
+                if ( is_signed )
+                    tr += std::to_string(Parameter::get_int(d));
                 else
-                    tr = tr.substr(0, tr.find(":") + 1) + std::to_string(Parameter::get_uint(d));
+                    tr += std::to_string(Parameter::get_uint(d));
             }
             json.put("range", tr);
             break;
@@ -2055,6 +2038,24 @@ TEST_CASE("param range JSON dumper", "[ModuleManager]")
         dump_param_range_json(json, &p_min_max);
         x = R"-(, "range": "2147483647:4294967295")-";
         CHECK(ss.str() == x);
+        ss.str("");
+
+        const Parameter p_s_int_max("s_int_max", Parameter::PT_INT, "-2:max63", nullptr, "help");
+        dump_param_range_json(json, &p_s_int_max);
+        x = R"-(, "range": "-2:9223372036854775807")-";
+        CHECK(ss.str() == x);
+        ss.str("");
+
+        const Parameter p_s_uint_max("s_uint_max", Parameter::PT_INT, "-5:max64", nullptr, "help");
+        dump_param_range_json(json, &p_s_uint_max);
+        x = R"-(, "range": "-5:-1")-";
+        CHECK(ss.str() == x);
+        ss.str("");
+
+        const Parameter p_max("uint_max", Parameter::PT_INT, ":max64", nullptr, "help");
+        dump_param_range_json(json, &p_max);
+        x = R"-(, "range": ":18446744073709551615")-";
+        CHECK(ss.str() == x);
     }
 }
 
index 1d0092f3b32ead432b1bca79d8bef3b1bf589900..dc0b21abffdf61b90f16ce1317577464bfd7311d 100644 (file)
@@ -165,13 +165,3 @@ bool MpseManager::parallel_compiles(const MpseApi* api)
     return (api->flags & MPSE_MTBLD) != 0;
 }
 
-// was called during drop stats but actually commented out
-// FIXIT-M this one has to accumulate across threads
-#if 0
-void MpseManager::print_qinfo()
-{
-    sfksearch_print_qinfo();
-    acsmx2_print_qinfo();
-}
-#endif
-
index 3c13fdf0c2bc7ea3b57cfc948336d26b35fa9ac2..71972ca9571392618dc28bbd21622a40620b70cd 100644 (file)
@@ -231,14 +231,12 @@ static void load_list(
     SoHandlePtr so_file;
     if ( handle and sc )
     {   // for reload, if the so lib file was previously opened, reuse the shared_ptr
-        for( auto const& i : s_plugins.plug_map )
-        {
-            if ( i.second.api == (*api) and i.second.handle.get()->handle == handle )
-            {
-                so_file = i.second.handle;
-                break;
-            }
-        }
+        auto it = std::find_if(s_plugins.plug_map.cbegin(), s_plugins.plug_map.cend(),
+            [api, handle](const std::pair<const std::string, Plugin>& i)
+            { return i.second.api == *api and i.second.handle.get()->handle == handle; });
+
+        if (it != s_plugins.plug_map.cend())
+            so_file = (*it).second.handle;
     }
     if ( !so_file.get() )
         so_file = std::make_shared<SoHandle>(handle);
@@ -448,7 +446,7 @@ void PluginManager::list_plugins()
 {
     for ( auto it = s_plugins.plug_map.begin(); it != s_plugins.plug_map.end(); ++it )
     {
-        Plugin& p = it->second;
+        const Plugin& p = it->second;
         cout << Markup::item();
         cout << p.key;
         cout << " v" << p.api->version;
@@ -461,7 +459,7 @@ void PluginManager::show_plugins()
 {
     for ( auto it = s_plugins.plug_map.begin(); it != s_plugins.plug_map.end(); ++it )
     {
-        Plugin& p = it->second;
+        const Plugin& p = it->second;
 
         cout << Markup::item();
         cout << Markup::emphasis(p.key);
index aced3b3eec9ec6cdcfdc91126e75f03c0b6668d6..3752ba4a7cda650bf661d1f5444fa056ca6d49d9 100644 (file)
@@ -23,6 +23,8 @@
 
 #include "script_manager.h"
 
+#include <algorithm>
+
 #include <sys/stat.h>
 
 #include "framework/ips_option.h"
@@ -72,10 +74,9 @@ public:
 
 const char* IpsLuaApi::type = "ips_option";
 
-IpsLuaApi::IpsLuaApi(string& s, string& c, unsigned v) : LuaApi(s, c)
+extern const IpsApi* ips_luajit;
+IpsLuaApi::IpsLuaApi(string& s, string& c, unsigned v) : LuaApi(s, c), api(*ips_luajit)
 {
-    extern const IpsApi* ips_luajit;
-    api = *ips_luajit;
     api.base.name = name.c_str();
     api.base.version = v;
 }
@@ -99,10 +100,9 @@ public:
 
 const char* LogLuaApi::type = "logger";
 
-LogLuaApi::LogLuaApi(string& s, string& c, unsigned v) : LuaApi(s, c)
+extern const LogApi* log_luajit;
+LogLuaApi::LogLuaApi(string& s, string& c, unsigned v) : LuaApi(s, c), api(*log_luajit)
 {
-    extern const LogApi* log_luajit;
-    api = *log_luajit;
     api.base.name = name.c_str();
     api.base.version = v;
 }
@@ -275,9 +275,10 @@ void ScriptManager::load_scripts(const std::vector<std::string>& paths)
 const BaseApi** ScriptManager::get_plugins()
 {
     base_api.clear();
+    base_api.reserve(lua_api.size() + 1);
 
-    for ( auto p : lua_api )
-        base_api.emplace_back(p->get_base());
+    transform(lua_api.cbegin(), lua_api.cend(), back_inserter(base_api),
+        [](const LuaApi* p){ return p->get_base(); });
 
     base_api.emplace_back(nullptr);
 
@@ -296,9 +297,9 @@ void ScriptManager::release_scripts()
 
 string* ScriptManager::get_chunk(const char* key)
 {
-    for ( auto p : lua_api )
-        if ( p->name == key )
-            return &p->chunk;
+    auto it = find_if(lua_api.cbegin(), lua_api.cend(), [key](const LuaApi* p){ return p->name == key; });
+    if (it != lua_api.cend())
+        return &(*it)->chunk;
 
     return nullptr;
 }
index 29a66029e844b6dd51a2ba188470300724da24ed..0f143f8b64d5a7c8d8846e3b3e72ae3b5756b087 100644 (file)
@@ -353,8 +353,7 @@ public:
     void eval(Packet*) override { }
     bool configure(SnortConfig* sc) override
     {
-        for( auto i : sc->so_rules->handles )
-            handles.emplace_back(i);
+        copy(sc->so_rules->handles.begin(), sc->so_rules->handles.end(), back_inserter(handles));
         sc->so_rules->proxy = this;
         return true;
     }
index 105c12927ca3e001b8dd485a3877212c8eb45d28..96aa8f449d23e5cca1b6734911eb0a04624cbe10 100644 (file)
@@ -55,7 +55,7 @@ unsigned DataBus::get_id(const PubKey&) { return 0; }
 void DetectionEngine::disable_content(Packet*) { }
 unsigned SnortConfig::get_thread_reload_id() { return 1; }
 void SnortConfig::update_thread_reload_id() { }
-Inspector::Inspector() { }
+Inspector::Inspector() { ref_count = nullptr; }
 Inspector::~Inspector() { }
 bool Inspector::likes(Packet*) { return false; }
 bool Inspector::get_buf(const char*, Packet*, InspectionBuffer&) { return false; }
index f0115223110e81ddd45e4ec050defbfac887620a..5055babb15e4838e88acd2c5cbb10d79d8dc20b9 100644 (file)
@@ -58,6 +58,8 @@ NetworkPolicy::~NetworkPolicy()
 }
 PolicyMap::PolicyMap(PolicyMap*, const char*)
 {
+    empty_ips_policy = nullptr;
+    inspector_tinit_complete = nullptr;
     file_id = InspectorManager::create_single_instance_inspector_policy();
     flow_tracking = InspectorManager::create_single_instance_inspector_policy();
     global_inspector_policy = InspectorManager::create_global_inspector_policy();
@@ -87,7 +89,7 @@ SnortConfig::~SnortConfig()
 const SnortConfig* SnortConfig::get_conf()
 { return (const SnortConfig*)mock().getData("snort_config").getObjectPointer(); }
 
-Module::Module(const char* name, const char*) : name(name)
+Module::Module(const char* name, const char*) : name(name), help(nullptr), params(nullptr), list(false)
 { }
 
 class TestInspector : public Inspector
index 6fa6a87b3bb06c176bbcaecd609f30d37455b1c6..620c9b70e915f2fc125300b1e7ddfd5aed8bf5ea 100644 (file)
@@ -291,7 +291,7 @@ TEST_CASE( "memory metadata", "[memory]" )
         auto meta = memory::Metadata::create<AllocatorSpy>(n);
 
         CHECK( (void*)meta == (void*)pool );
-        CHECK( meta->valid() );
+        CHECK( true == meta->valid() );
         CHECK( meta->payload_size == n );
     }
 
index fe99fe386a4575e295a318b737a91b5ee0ffa896..4e6d3470aaff25287a906a1ebbaeb4bfc87a008d 100644 (file)
@@ -252,7 +252,6 @@ bool MimeSession::process_header_line(const uint8_t*& ptr, const uint8_t* eol, c
     const uint8_t* header_value_ptr = nullptr;
     int max_header_name_len = 0;
 
-    int header_found;
     /* got a line with only end of line marker should signify end of header */
     if (eolm == ptr)
     {
@@ -315,7 +314,7 @@ bool MimeSession::process_header_line(const uint8_t*& ptr, const uint8_t* eol, c
         if (tolower((int)*ptr) == 'c')
         {
             mime_current_search = &mime_hdr_search[0];
-            header_found = mime_hdr_search_mpse->find(
+            int header_found = mime_hdr_search_mpse->find(
                 (const char*)ptr, eolm - ptr, search_str_found, true);
 
             /* Headers must start at beginning of line */
index 9e294b9b1ada6f9e646c99f600a1ce88c49ee922..1dfd60e4acc93290444c90bc52c3e8a9e52766d7 100644 (file)
@@ -192,11 +192,11 @@ AppInfoTableEntry* AppInfoManager::add_dynamic_app_entry(const char* app_name)
 
 void AppInfoManager::cleanup_appid_info_table()
 {
-    for (auto& kv: app_info_table)
+    for (const auto& kv: app_info_table)
         delete(kv.second);
     app_info_table.erase(app_info_table.begin(), app_info_table.end());
 
-    for (auto& kv: custom_app_info_table)
+    for (const auto& kv: custom_app_info_table)
         delete(kv.second);
 
     custom_app_info_table.erase(custom_app_info_table.begin(), custom_app_info_table.end());
index c3487ff54350bc0cf50f1e5b52ffbd9d3cc45196..0251449fbbba2ef1405b0f224071dc7dc56ac837 100644 (file)
@@ -20,8 +20,7 @@ using namespace snort;
 
 void ApplicationDescriptor::set_id(AppId app_id)
 {
-    if ( my_id != app_id )
-        my_id = app_id;
+    my_id = app_id;
 }
 
 void ApplicationDescriptor::set_id(const Packet& p, AppIdSession& asd,
index d1c7217541d8c73d88d16e7396cea954c6ae9a4d..f3ebc1f34e9d929fcd6ed5dd29dc8cd65569712a 100644 (file)
@@ -104,7 +104,7 @@ public:
     bool log_all_sessions = false;
     bool enable_rna_filter = false;
     std::string rna_conf_path = "";
-    SnortProtocolId snort_proto_ids[PROTO_INDEX_MAX];
+    SnortProtocolId snort_proto_ids[PROTO_INDEX_MAX] = {};
     void show() const;
 };
 
index 6211aaef722e24922cd0f23f90b5c3918a502761..7eb9e5ccc77c1e6368a959d691056e2ad99c1bfd 100644 (file)
@@ -98,8 +98,8 @@ public:
 private:
     bool enabled = false;
     bool active = false;
-    AppIdDebugSessionConstraints info = { };
-    char debug_session[APPID_DEBUG_SESSION_ID_SIZE];
+    AppIdDebugSessionConstraints info = {};
+    char debug_session[APPID_DEBUG_SESSION_ID_SIZE] = {};
 };
 
 extern THREAD_LOCAL AppIdDebug* appidDebug;
index e9122d8ac5661fe5d18ef6816bb71f88e87613a3..258d1c7fb91156b47100084ac545a54f4cae55c7 100644 (file)
@@ -38,22 +38,22 @@ using namespace snort;
 int AppIdDetector::initialize(AppIdInspector& inspector)
 {
     if ( !tcp_patterns.empty() )
-        for (auto& pat : tcp_patterns)
+        for (const auto& pat : tcp_patterns)
             handler->register_tcp_pattern(this, pat.pattern, pat.length, pat.index, pat.nocase);
 
     if ( !udp_patterns.empty() )
-        for (auto& pat : udp_patterns)
+        for (const auto& pat : udp_patterns)
             handler->register_udp_pattern(this, pat.pattern, pat.length, pat.index, pat.nocase);
 
     if (!appid_registry.empty())
     {
-        AppIdContext& ctxt = inspector.get_ctxt();
-        for (auto& id : appid_registry)
+        const AppIdContext& ctxt = inspector.get_ctxt();
+        for (const auto& id : appid_registry)
             register_appid(id.appId, id.additionalInfo, ctxt.get_odp_ctxt());
       }
 
     if (!service_ports.empty())
-        for (auto& port: service_ports)
+        for (const auto& port: service_ports)
             handler->add_service_port(this, port);
 
     do_custom_init();
index dedb8e29dff58229b3bc16fac7cfe6fa37c34707..41751f575d0f5c167ba483d284a2e4f0b472d0e9 100644 (file)
@@ -113,8 +113,8 @@ void AppIdEveProcessEventHandler::handle(DataEvent& event, Flow* flow)
 
     if (!server_name.empty())
     {
-        AppId client_id = APP_ID_NONE;
-        AppId payload_id = APP_ID_NONE;
+        AppId tmp_client_id = APP_ID_NONE;
+        AppId tmp_payload_id = APP_ID_NONE;
 
         if (!asd->tsession)
             asd->tsession = new TlsSession();
@@ -123,8 +123,8 @@ void AppIdEveProcessEventHandler::handle(DataEvent& event, Flow* flow)
         asd->set_tls_host();
 
         odp_ctxt.get_ssl_matchers().scan_hostname(reinterpret_cast<const uint8_t*>(server_name.c_str()),
-            server_name.length(), client_id, payload_id);
-        asd->set_payload_id(payload_id);
+            server_name.length(), tmp_client_id, tmp_payload_id);
+        asd->set_payload_id(tmp_payload_id);
     }
 
     std::string debug_str;
index 9a76f1e93e8ac478d377321b8373692845df8d75..ed450dd0d616b267d79ad7c07700f0d3e9640904 100644 (file)
@@ -206,7 +206,7 @@ bool AppIdHttpSession::initial_chp_sweep(ChpMatchDescriptor& cmd, HttpPatternMat
     }
 
     int longest = 0;
-    for (auto& item: cmd.match_tally)
+    for (const auto& item: cmd.match_tally)
     {
         // Only those items with key_pattern_countdown field reduced to zero are a full match
         if (item.key_pattern_countdown)
@@ -691,7 +691,7 @@ int AppIdHttpSession::process_http_packet(AppidSessionDirection direction,
 
             if (asd.get_service_id() <= APP_ID_NONE)
             {
-                if (service_id > APP_ID_NONE and service_id != APP_ID_HTTP and asd.get_service_id() != service_id)
+                if (service_id > APP_ID_NONE and service_id != APP_ID_HTTP)
                 {
                     const char* app_name = asd.get_odp_ctxt().get_app_info_mgr().get_app_name(service_id);
                     appid_log(p, TRACE_DEBUG_LEVEL, "URL is service %s (%d)\n",
index 3d547ba41fbdee8fd74bfd32b8528e2ddbfe3089..6a908fe8cec11a94f6f0e36c630bcbad5dcde6ec 100644 (file)
@@ -70,7 +70,7 @@ unsigned AppIdInspector::pub_id = 0;
 
 static THREAD_LOCAL PacketTracer::TracerMute appid_mute;
 
-static void add_appid_to_packet_trace(Flow& flow, const OdpContext& odp_context)
+static void add_appid_to_packet_trace(const Flow& flow, const OdpContext& odp_context)
 {
     AppIdSession* session = appid_api.get_appid_session(flow);
     // Skip sessions using old odp context after odp reload
@@ -222,6 +222,7 @@ void AppIdInspector::tear_down(SnortConfig*)
 
 void AppIdInspector::eval(Packet* p)
 {
+    // cppcheck-suppress unreadVariable
     Profile profile(appid_perf_stats);
     appid_stats.packets++;
 
index 6b49ff5c2190724fc402f247f2bbd518cac05069..d2571cbf4cdc3cd3b452925dd785199493f31a2a 100644 (file)
@@ -109,7 +109,7 @@ static const Parameter s_params[] =
 class AcAppIdDebug : public AnalyzerCommand
 {
 public:
-    AcAppIdDebug(AppIdDebugSessionConstraints* cs);
+    AcAppIdDebug(const AppIdDebugSessionConstraints* cs);
     bool execute(Analyzer&, void**) override;
     const char* stringify() override { return "APPID_DEBUG"; }
 
@@ -118,7 +118,7 @@ private:
     bool enable = false;
 };
 
-AcAppIdDebug::AcAppIdDebug(AppIdDebugSessionConstraints* cs)
+AcAppIdDebug::AcAppIdDebug(const AppIdDebugSessionConstraints* cs)
 {
     if (cs)
     {
index c70b70c1cf43b77691567f0a22bf6a1b6a9076f6..b7e9695ef676fd2afa5b85009a01f628ac5cc4b5 100644 (file)
@@ -82,7 +82,7 @@ static void handle_failure(AppIdSession& asd, SshEventFlowData& data)
 
 static void client_success(const SshAppIdInfo& fd, AppIdSession& asd, AppidChangeBits& change_bits)
 {
-    SshPatternMatchers& table = asd.get_odp_ctxt().get_ssh_matchers();
+    const SshPatternMatchers& table = asd.get_odp_ctxt().get_ssh_matchers();
     AppId client_id;
 
     if (table.has_pattern(fd.vendor))
index dc27294aefda4448f4e0ec11f22508e682028c19..10ba315a723363184c034f3248347b984d38101e 100644 (file)
@@ -120,21 +120,13 @@ void AppIdStatistics::dump_statistics()
 }
 
 AppIdStatistics::AppIdStatistics(const AppIdConfig& config)
+    : bucket_interval(config.app_stats_period), roll_size(config.app_stats_rollover_size)
 {
-    enabled = true;
-
-    roll_size = config.app_stats_rollover_size;
-    bucket_interval = config.app_stats_period;
-
-    time_t now = get_time();
-    start_stats_period(now);
+    start_stats_period(get_time());
 }
 
 AppIdStatistics::~AppIdStatistics()
 {
-    if ( !enabled )
-        return;
-
     /*flush the last stats period. */
     end_stats_period();
     dump_statistics();
@@ -266,9 +258,6 @@ void AppIdStatistics::update(const AppIdSession& asd)
 
 void AppIdStatistics::flush()
 {
-    if ( !enabled )
-        return;
-
     time_t now = get_time();
     if (now >= bucket_end)
     {
index b8a743f7c34f0028a9dff0493ca7a7de89957b16..9e3d171b3a06146076d2fa2969cf9e7f7bf4a000 100644 (file)
@@ -60,6 +60,7 @@ struct StatsBucket
 class AppIdStatistics
 {
 public:
+    AppIdStatistics() = delete;
     ~AppIdStatistics();
 
     static AppIdStatistics* initialize_manager(const AppIdConfig&);
@@ -88,7 +89,6 @@ private:
     void open_stats_log_file();
     void dump_statistics();
 
-    bool enabled = false;
     SF_LIST* curr_buckets = nullptr;
     SF_LIST* log_buckets = nullptr;
     struct TextLog* log = nullptr;
index caf5f1de1e71694a6339ac5e89a7833e9eb62beb..f8e0115fc551b70c8c9342231006ad66e32e0813 100644 (file)
@@ -97,6 +97,7 @@ int MsnClientDetector::validate(AppIdDiscoveryArgs& args)
         }
 
         /* Get the product */
+        // cppcheck-suppress knownConditionTrueFalse
         if ( end - args.data >= (int)sizeof(MSNMSGR) && memcmp(args.data, MSNMSGR, sizeof(MSNMSGR)-
             1) == 0 )
         {
@@ -105,6 +106,7 @@ int MsnClientDetector::validate(AppIdDiscoveryArgs& args)
 
             args.data++; /* skip the space */
         }
+        // cppcheck-suppress knownConditionTrueFalse
         else if ( end - args.data >= (int)sizeof(MACMSGS) &&
             memcmp(args.data, MACMSGS, sizeof(MACMSGS)-1) == 0 )
         {
index 3abc62ef46807e8c4607e797609355217fcd5c4b..626784a33dc3eb87f35f6f8dec2c16fa6a4532dd 100644 (file)
@@ -524,7 +524,7 @@ void ImapClientDetector::do_custom_init()
     {
         unsigned index = 0;
 
-        for (auto& pat : tcp_patterns)
+        for (const auto& pat : tcp_patterns)
         {
             cmd_matcher->add(pat.pattern, pat.length, index++);
             if (pat.length > longest_pattern)
index e56e7aeb5f28aabab8ff7af270afbdb1841467db..4609a4575703ea84092f98f723f4e6121aa198f0 100644 (file)
@@ -117,7 +117,7 @@ static void read_patterns(PortPatternNode* portPatternList, PatternService** ser
         pattern->next = ps->pattern;
         ps->pattern = pattern;
 
-        AppIdContext& ctxt = inspector.get_ctxt();
+        const AppIdContext& ctxt = inspector.get_ctxt();
 
         ctxt.get_odp_ctxt().get_app_info_mgr().set_app_info_active(ps->id);
     }
index 2c7be5a68ae385eb43acbb5f80ba8a5251ad3561..f307000a38f07f29aad4a9638a4f8ee6bdbe9f19 100644 (file)
@@ -40,7 +40,6 @@ enum POP3ClientState
 
 struct ClientPOP3Data
 {
-    int auth;
     char* username;
     POP3ClientState state;
     int detected;
@@ -221,7 +220,7 @@ void Pop3ClientDetector::do_custom_init()
     {
         unsigned index = 0;
 
-        for (auto& pat : tcp_patterns)
+        for (const auto& pat : tcp_patterns)
         {
             cmd_matcher->add(pat.pattern, pat.length, index++);
             if (pat.length > longest_pattern)
index c3da00d3101fa0d780ab1c45a672b247906bb4e4..6d4ccf528988a174d4f666632ff4c5289a9afb84 100644 (file)
@@ -526,7 +526,7 @@ int SmtpClientDetector::validate(AppIdDiscoveryArgs& args)
             if (*args.data == '.')
             {
                 if (len == 0 ||
-                    (len >= 1 && args.data[1] == '\n') ||
+                    args.data[1] == '\n' ||
                     (len >= 2 && args.data[1] == '\r' && args.data[2] == '\n'))
                 {
                     add_app(args.asd, APP_ID_SMTP, APP_ID_SMTP, nullptr, args.change_bits);
index 864ea2c8eb0050943adef5f0cd95c772951db2e4..c1e030a9f0a7f0d9eda27238e5f935d6a6c216a7 100644 (file)
@@ -332,7 +332,7 @@ static void free_app_url_patterns(std::vector<DetectorAppUrlPattern*>& url_patte
 
 static void free_http_patterns(DetectorHTTPPatterns& patterns)
 {
-    for (auto& pat: patterns)
+    for (const auto& pat: patterns)
         if (pat.pattern)
             snort_free(const_cast<uint8_t*>(pat.pattern));
 }
@@ -363,7 +363,7 @@ HttpPatternMatchers::~HttpPatternMatchers()
     free_http_patterns(content_type_patterns);
     free_chp_app_elements();
 
-    for (auto* pattern : host_url_patterns)
+    for (const auto* pattern : host_url_patterns)
         delete pattern;
     host_url_patterns.clear();
     if ( host_url_matcher )
@@ -546,13 +546,13 @@ int HttpPatternMatchers::process_mlmp_patterns()
         if ( add_mlmp_pattern(host_url_matcher, pattern) < 0 )
             return -1;
 
-    for (auto* pattern: rtmp_url_patterns)
-        if ( add_mlmp_pattern(rtmp_host_url_matcher, *pattern) < 0 )
-            return -1;
+    if (std::any_of(rtmp_url_patterns.begin(), rtmp_url_patterns.end(),
+        [this](DetectorAppUrlPattern* pattern){ return add_mlmp_pattern(rtmp_host_url_matcher, *pattern) < 0; }))
+        return -1;
 
-    for (auto* pattern: app_url_patterns)
-        if ( add_mlmp_pattern(host_url_matcher, *pattern) < 0 )
-            return -1;
+    if (std::any_of(app_url_patterns.begin(), app_url_patterns.end(),
+        [this](DetectorAppUrlPattern* pattern){ return add_mlmp_pattern(host_url_matcher, *pattern) < 0; }))
+        return -1;
 
     return 0;
 }
@@ -582,12 +582,13 @@ static int chp_pattern_match(void* id, void*, int match_end_pos, void* data, voi
 
 static inline void chp_add_candidate_to_tally(CHPMatchTally& match_tally, CHPApp* chpapp)
 {
-    for (auto& item: match_tally)
-        if (chpapp == item.chpapp)
-        {
-            item.key_pattern_countdown--;
-            return;
-        }
+    auto it = std::find_if(match_tally.begin(), match_tally.end(),
+        [&chpapp](const CHPMatchCandidate& item){ return chpapp == item.chpapp; });
+    if (it != match_tally.end())
+    {
+        (*it).key_pattern_countdown--;
+        return;
+    }
 
     match_tally.emplace_back( CHPMatchCandidate{ chpapp, chpapp->key_pattern_length_sum,
         chpapp->key_pattern_count - 1 } );
index 0cd5c8c6fc9a06a0065deb65fae78e16ea4a46af..0e1d3bf6dd0a8903e225fd4dbb7f0de02406d7d9 100644 (file)
@@ -32,7 +32,8 @@ void ParseWarning(WarningGroup, const char*, ...) { }
 // LCOV_EXCL_STOP
 
 // Stubs for appid sessions
-FlowData::FlowData(unsigned, Inspector*) { }
+FlowData::FlowData(unsigned, Inspector*) : next(nullptr), prev(nullptr), handler(nullptr), id(0)
+{ }
 FlowData::~FlowData() = default;
 
 // Stubs for packet
index 6317241b43984a1127cdaeb003b0f84377a4e5ee..b3a27487eee3f09b046a7555c59d2194e27bc2a0 100644 (file)
@@ -32,6 +32,7 @@
 #include "framework/mpse_batch.h"
 #include "network_inspectors/appid/appid_utils/sf_mlmp.cc"
 #include "protocols/protocol_ids.h"
+#include "service_inspectors/sip/sip_parser.h"
 #include "utils/util_cstring.cc"
 
 #include "appid_inspector.h"
@@ -173,7 +174,8 @@ void AppIdDetector::add_app(snort::Packet const&, AppIdSession&, AppidSessionDir
     int, char const*, AppidChangeBits&) { }
 // LCOV_EXCL_STOP
 
-SipEvent::SipEvent(snort::Packet const* p, SIPMsg const*, SIP_DialogData const*) { this->p = p; }
+SipEvent::SipEvent(const snort::Packet* p, const SIPMsg& msg, const SIP_DialogData*) : p(p), msg(msg)
+{ }
 SipEvent::~SipEvent() = default;
 bool SipEvent::is_invite() const { return false; }
 bool SipEvent::is_dialog_established() const { return false; }
@@ -189,8 +191,11 @@ void* AppIdDetector::data_get(AppIdSession&)
 
 TEST_GROUP(detector_sip_tests)
 {
+    SIPMsg sip_msg;
+
     void setup() override
     {
+        sip_msg = {};
         appid_inspector.configure(nullptr);
     }
     void teardown() override
@@ -207,7 +212,7 @@ TEST(detector_sip_tests, sip_event_handler)
     OdpContext* odpctxt = pkt_thread_odp_ctxt = &context.get_odp_ctxt();
 
     odpctxt->initialize(appid_inspector);
-    SipEvent event(&pkt, nullptr, nullptr);
+    SipEvent event(&pkt, sip_msg, nullptr);
     SipEventHandler event_handler(appid_inspector);
     Flow* flow = new Flow;
     event_handler.handle(event, flow);
index ac7830bc390420f5aa829e02a2071a011ce1b23d..1b13228cc3ed8fe55dcc19ae4538a70af571fb8e 100644 (file)
@@ -66,8 +66,6 @@ struct FirstPktkey
     {
         max_network_range.clear();
         network_address.clear();
-        port = 0;
-        proto = IpProtocol::PROTO_NOT_SET;
     }
 
     bool operator<(const FirstPktkey& right) const
@@ -81,12 +79,12 @@ struct FirstPktkey
             return false;
     }
 
-    uint32_t netmask[4];
+    uint32_t netmask[4] = {};
     snort::SfIp max_network_range;
     snort::SfIp network_address;
-    uint16_t port;
-    IpProtocol proto;
-    char padding;
+    uint16_t port = 0;
+    IpProtocol proto = IpProtocol::PROTO_NOT_SET;
+    char padding = 0;
 };
 PADDING_GUARD_END
 
index cec54f6c9cf26233e8f053e700d2cccdf682ca3a..4e0b1a812dc5132de66f55044c024099d0cd59af 100644 (file)
@@ -109,6 +109,7 @@ bool AppIdIpsOption::match_id_against_rule(OdpContext& odp_ctxt, int32_t id)
 // first match wins...
 IpsOption::EvalStatus AppIdIpsOption::eval(Cursor&, Packet* p)
 {
+    // cppcheck-suppress unreadVariable
     RuleProfile profile(ips_appid_perf_stats);
 
     if ( !p->flow )
index a73f489d630a2415bfe5361a922db9e25972c15f..ca55a53e9adc49eeb46f29f26245713bd51b14a8 100644 (file)
@@ -2761,6 +2761,7 @@ static int add_port_pattern_client(lua_State* L)
     }
 
     PortPatternNode* pPattern  = (decltype(pPattern))snort_calloc(sizeof(PortPatternNode));
+    // cppcheck-suppress internalAstError
     pPattern->pattern  = (decltype(pPattern->pattern))snort_calloc(pattern_size);
     pPattern->appId = appid;
     pPattern->protocol = protocol;
index 269e33be1d56f0813d10ceffe01750f26d48b3b0..c1664f7f622ed71e69fcb6ff875048ce769ec588 100644 (file)
@@ -51,7 +51,7 @@ struct DetectorPackageInfo
     std::string validateFunctionName;
     int minimum_matches = 0;
     std::string name = "NoName";
-    IpProtocol proto;
+    IpProtocol proto = IpProtocol::PROTO_NOT_SET;
 };
 
 struct LuaDetectorParameters
@@ -69,7 +69,7 @@ struct LuaDetectorParameters
     const uint8_t* data = nullptr;
     uint16_t size = 0;
     AppidSessionDirection dir = APP_ID_FROM_INITIATOR;
-    AppIdSession* asd;
+    AppIdSession* asd = nullptr;
     AppidChangeBits* change_bits = nullptr;
     const snort::Packet* pkt = nullptr;
 };
index 33581b0b34d8150e00a46592c759897d169b2fdf..986435b1fd315f1e0e7204ad21d77fabde1784b4 100644 (file)
@@ -48,7 +48,7 @@ struct DetectorFlow
 
     lua_State* myLuaState;
     AppIdSession* asd;
-    int userDataRef;
+    int userDataRef = 0;
 };
 
 int register_detector_flow_api(lua_State*);
index e555adab6f13a123ca36d2f0f69b7f8884c37361..d1ea421568c845404658ccd5d405848f2e65742d 100644 (file)
@@ -163,7 +163,6 @@ LuaDetectorManager::LuaDetectorManager(AppIdContext& ctxt, bool is_control) :
 
 LuaDetectorManager::~LuaDetectorManager()
 {
-    auto L = this->L;
     if (lua_gettop(L))
         appid_log(nullptr, TRACE_WARNING_LEVEL, "appid: leak of %d lua stack elements before detector unload\n",
             lua_gettop(L));
index fafefba2b01afc72b71fc5b8e9b0c5051e8f4358..d3608c5902cf0182550403dfe2b059115905d752 100644 (file)
@@ -133,9 +133,10 @@ int RexecServiceDetector::validate(AppIdDiscoveryArgs& args)
         data_add(args.asd, rd, &rexec_free_state);
         rd->state = REXEC_STATE_PORT;
     }
+    // cppcheck-suppress nullPointerRedundantCheck
     appid_log(args.pkt, TRACE_DEBUG_LEVEL, "rexec state %d\n", rd->state);
 
-    switch (rd->state)
+    switch (rd->state) // cppcheck-suppress nullPointerRedundantCheck
     {
     case REXEC_STATE_PORT:
         if (args.dir != APP_ID_FROM_INITIATOR)
index 9462b9e36c9ac81c9ec2b690af9c464bb7f565fa..99830acc933d53e1a169bc500598a74dad107a67 100644 (file)
@@ -129,9 +129,10 @@ int RshellServiceDetector::validate(AppIdDiscoveryArgs& args)
         rd->state = RSHELL_STATE_PORT;
     }
 
+    // cppcheck-suppress nullPointerRedundantCheck
     appid_log(args.pkt, TRACE_DEBUG_LEVEL, "RSHELL state %d\n",rd->state);
 
-    switch (rd->state)
+    switch (rd->state) // cppcheck-suppress nullPointerRedundantCheck
     {
     case RSHELL_STATE_PORT:
         if (args.dir != APP_ID_FROM_INITIATOR)
index 5c21479f130ec5b543ae7b6bd9a1379a25236ee5..58867a9868ec18d87d6b35d325ea6f20a0e66e24 100644 (file)
@@ -585,9 +585,7 @@ int RtmpServiceDetector::validate(AppIdDiscoveryArgs& args)
                 else
                 {
                     /* We've gotten all of the bytes that we wanted. */
-                    ss->server_state = RTMP_STATE_SENT_HANDSHAKE2;
                     args.data += ss->server_bytes_left;
-                    args.size -= ss->server_bytes_left;
                 }
             /* fall through */
 
index dd7e44fc81eb5893287b52fc1b7f870e5b2fe6e4..abfa40c218e9172537260d1ffb3db9c452d40124 100644 (file)
@@ -32,7 +32,8 @@ namespace snort
 void ParseWarning(WarningGroup, const char*, ...) { }
 
 // Stubs for appid sessions
-FlowData::FlowData(unsigned, Inspector*) { }
+FlowData::FlowData(unsigned, Inspector*) : next(nullptr), prev(nullptr), handler(nullptr), id(0)
+{ }
 FlowData::~FlowData() = default;
 
 // Stubs for packet
index 2484c3aa3e1662c974cf404af7a2d958eaa346ae..e86ac67877160a1515cc3cb17ac18742252943cd 100644 (file)
@@ -193,7 +193,7 @@ public:
 
     ~MapList()
     {
-        for ( auto& kv : m )
+        for ( const auto& kv : m )
             delete kv.second;
     }
 
index 706e720d04a415cdbd5b2ae7cd8110b624c9d679..19f255ee3faa818ec9cf5207ae2ecdcb85dddb92 100644 (file)
@@ -27,7 +27,7 @@ class Value;
 
 namespace snort
 {
-Inspector::Inspector()
+Inspector::Inspector() : ref_count(nullptr)
 {
     set_api(nullptr);
 }
index c6e53ac38bef7611e5b98c2f9c5974cd7bf66426..0d817061dd925d3fa156b38a580c768b0a81876f 100644 (file)
@@ -69,7 +69,7 @@ TEST_GROUP(appid_session_api)
     {
         AppidChangeBits change_bits;
 
-        SfIp ip;
+        SfIp ip{};
         mock_session = new AppIdSession(IpProtocol::TCP, &ip, 1492, dummy_appid_inspector, odpctxt);
         mock_session->flow = &flow;
         pkt_thread_odp_ctxt = &mock_session->get_odp_ctxt();
@@ -112,7 +112,7 @@ TEST(appid_session_api, get_client_app_id)
 
 TEST(appid_session_api, get_client_app_id_with_eve_for_http2)
 {
-    SfIp ip;
+    SfIp ip{};
     AppIdSession asd(IpProtocol::TCP, &ip, 1492, dummy_appid_inspector, odpctxt);
     asd.flow = &flow;
     AppidChangeBits change_bits;
@@ -162,7 +162,7 @@ TEST(appid_session_api, get_referred_app_id)
 
 TEST(appid_session_api, get_app_id)
 {
-    SfIp ip;
+    SfIp ip{};
     AppIdSession asd(IpProtocol::TCP, &ip, 1492, dummy_appid_inspector, odpctxt);
     asd.flow = &flow;
     AppidChangeBits change_bits;
@@ -191,7 +191,7 @@ TEST(appid_session_api, get_app_id)
 
 TEST(appid_session_api, get_app_id_with_eve_for_http2)
 {
-    SfIp ip;
+    SfIp ip{};
     AppIdSession asd(IpProtocol::TCP, &ip, 1492, dummy_appid_inspector, odpctxt);
     asd.flow = &flow;
     AppidChangeBits change_bits;
@@ -284,7 +284,7 @@ TEST(appid_session_api, get_app_id_with_eve_for_http2)
 
 TEST(appid_session_api, get_first_stream_appids_for_http2)
 {
-    SfIp ip;
+    SfIp ip{};
     AppIdSession asd(IpProtocol::TCP, &ip, 1492, dummy_appid_inspector, odpctxt);
     asd.flow = &flow;
     AppidChangeBits change_bits;
@@ -432,7 +432,7 @@ TEST(appid_session_api, get_client_info)
 
 TEST(appid_session_api, get_client_info_http2)
 {
-    SfIp ip;
+    SfIp ip{};
     AppIdSession asd(IpProtocol::TCP, &ip, 1492, dummy_appid_inspector, odpctxt);
     asd.flow = &flow;
     AppidChangeBits change_bits;
index 73f07b2ad3695be848c1b55551abf4fed5cc1ad0..b747ef508c2fb1557956acd69efe448d48f50dc1 100644 (file)
 
 namespace snort
 {
-Packet::Packet(bool) { }
+Packet::Packet(bool)
+{
+    memset((char*) this , 0, sizeof(*this));
+    ip_proto_next = IpProtocol::PROTO_NOT_SET;
+    packet_flags = PKT_FROM_CLIENT;
+}
 Packet::~Packet() = default;
 Packet* DetectionEngine::get_current_packet() { return nullptr; }
 
@@ -78,7 +83,8 @@ AppInfoTableEntry* AppInfoManager::get_app_info_entry(AppId)
 
 // Stubs for appid classes
 class AppIdInspector{};
-FlowData::FlowData(unsigned, Inspector*) {}
+FlowData::FlowData(unsigned, Inspector*) : next(nullptr), prev(nullptr), handler(nullptr), id(0)
+{ }
 FlowData::~FlowData() = default;
 
 // Stubs for AppIdDebug
index 1763af704a9fe1b3a81dff8808595f01dbd3de72..7db63e3d259c66977c1ad80d6548c6585ea43f14 100644 (file)
@@ -50,10 +50,7 @@ typedef AppIdHttpSession::pair_t pair_t;
 
 static inline bool contains(const vector<AppId>& vec, const AppId val)
 {
-    for (const auto& elem : vec)
-        if (elem == val)
-            return true;
-    return false;
+    return std::any_of(vec.cbegin(), vec.cend(), [val](AppId elem){ return elem == val; });
 }
 
 static inline bool check_reinspect(const Packet* p, const AppIdSession& asd)
@@ -577,8 +574,8 @@ bool do_tp_discovery(ThirdPartyAppIdContext& tp_appid_ctxt, AppIdSession& asd, I
             TP_SESSION_FLAG_TUNNELING | TP_SESSION_FLAG_FUTUREFLOW);
     }
 
-    const char *tp_app_name = asd.get_odp_ctxt().get_app_info_mgr().get_app_name(tp_app_id);
-    appid_log(p, TRACE_DEBUG_LEVEL, "3rd party returned %s (%d)\n", tp_app_name ? tp_app_name : "unknown", tp_app_id);
+    const char *app_name = asd.get_odp_ctxt().get_app_info_mgr().get_app_name(tp_app_id);
+    appid_log(p, TRACE_DEBUG_LEVEL, "3rd party returned %s (%d)\n", app_name ? app_name : "unknown", tp_app_id);
 
     process_third_party_results(*p, asd, tp_confidence, tp_proto_list, tp_attribute_data, change_bits);
 
@@ -706,8 +703,8 @@ bool do_tp_discovery(ThirdPartyAppIdContext& tp_appid_ctxt, AppIdSession& asd, I
                 if (!(asd.scan_flags & SCAN_SPOOFED_SNI_FLAG))
                     asd.set_tp_payload_app_id(*p, direction, tp_app_id, change_bits);
                 tp_app_id = portAppId;
-                const char *app_name = asd.get_odp_ctxt().get_app_info_mgr().get_app_name(tp_app_id);
-                appid_log(p, TRACE_DEBUG_LEVEL, "SSL is %s (%d)\n", app_name ? app_name : "unknown", tp_app_id);
+                const char *tp_app_name = asd.get_odp_ctxt().get_app_info_mgr().get_app_name(tp_app_id);
+                appid_log(p, TRACE_DEBUG_LEVEL, "SSL is %s (%d)\n", tp_app_name ? tp_app_name : "unknown", tp_app_id);
             }
             snort_app_id = APP_ID_SSL;
         }
index cbeb242c318543655fb2b9b8d07b4cd144ba3006..a0970e4dac97305266b631caf48f255e854efaad 100644 (file)
@@ -74,17 +74,11 @@ static const RuleMap s_rules[] =
 // arp_spoof module
 //-------------------------------------------------------------------------
 
-ArpSpoofModule::ArpSpoofModule() :
-    Module(MOD_NAME, MOD_HELP, s_params)
-{
-    config = nullptr;
-}
+ArpSpoofModule::ArpSpoofModule() : Module(MOD_NAME, MOD_HELP, s_params)
+{ }
 
 ArpSpoofModule::~ArpSpoofModule()
-{
-    if ( config )
-        delete config;
-}
+{ delete config; }
 
 const RuleMap* ArpSpoofModule::get_rules() const
 { return s_rules; }
index 7ed632c109753e5e2536f47991404d2f22bdde7c..4ff4e7da02b8c859bf38cc7cb6ea5370c4266825 100644 (file)
@@ -76,8 +76,8 @@ public:
     { return INSPECT; }
 
 private:
-    ArpSpoofConfig* config;
-    IPMacEntry host;
+    ArpSpoofConfig* config = nullptr;
+    IPMacEntry host = {};
 };
 
 #endif
index 872d3be8a111fe4cc0e53d15f770dceb9fafe7ef..fbd81f4d0b4c65599fd3298ee25a1131b466c697 100644 (file)
@@ -98,12 +98,9 @@ THREAD_LOCAL ProfileStats arpPerfStats;
 
 static const IPMacEntry* LookupIPMacEntryByIP(const IPMacEntryList& ipmel, uint32_t ipv4_addr)
 {
-    for ( auto& p : ipmel )
-    {
-        if (p.ipv4_addr == ipv4_addr)
-            return &p;
-    }
-    return nullptr;
+    auto it = std::find_if(ipmel.cbegin(), ipmel.cend(),
+        [ipv4_addr](const IPMacEntry& p){ return p.ipv4_addr == ipv4_addr; });
+    return (it != ipmel.cend()) ? &(*it) : nullptr;
 }
 
 static std::string to_hex_string(const uint8_t* data, size_t len)
index da0b1264246456a7849aa12fd33a98b912386c25..2633374b2c3ed57d9b9ca5ea0a92ca50d07e73d5 100644 (file)
@@ -592,10 +592,8 @@ public:
 };
 
 Binder::Binder(std::vector<Binding>& bv, std::vector<Binding>& pbv)
-{
-    bindings = std::move(bv);
-    policy_bindings = std::move(pbv);
-}
+    : bindings(std::move(bv)),  policy_bindings(std::move(pbv))
+{ }
 
 Binder::~Binder()
 {
@@ -696,6 +694,7 @@ void Binder::remove_inspector_binding(SnortConfig*, const char* name)
 
 void Binder::handle_packet(const Packet* pkt)
 {
+    // cppcheck-suppress unreadVariable
     Profile profile(bindPerfStats);
 
     Stuff stuff;
@@ -798,14 +797,10 @@ void Binder::handle_flow_service_change(Flow& flow)
     else
     {
         // reset to wizard when service is not specified
-        for (const Binding& b : bindings)
-        {
-            if (b.use.what == BindUse::BW_WIZARD)
-            {
-                ins = b.use.inspector;
-                break;
-            }
-        }
+        auto it = std::find_if(bindings.cbegin(), bindings.cend(),
+            [](const Binding& b){ return b.use.what == BindUse::BW_WIZARD; });
+        if (it != bindings.cend())
+            ins = (*it).use.inspector;
 
         if (flow.gadget)
             flow.clear_gadget();
@@ -838,6 +833,7 @@ void Binder::handle_flow_service_change(Flow& flow)
 
 void Binder::handle_assistant_gadget(const char* service, Flow& flow)
 {
+    // cppcheck-suppress unreadVariable
     Profile profile(bindPerfStats);
 
     Stuff stuff;
index 0e860eb7ab4e644a6b8c161e4fe66f1f7e2a1ab8..f08eff143766cc2b06fe5244785cbc0862cf42d8 100644 (file)
@@ -296,7 +296,7 @@ static int Norm_ICMP6(
 
 struct ExtOpt
 {
-    uint8_t next;
+    uint8_t next;   // cppcheck-suppress unusedStructMember
     uint8_t xlen;
     uint8_t type;
     uint8_t olen;
index 6564464717d7887b9596a378f8dcd28523cbc59a..d80383e03e9cd730e2b88036ad92dad697e24e99 100644 (file)
@@ -216,10 +216,8 @@ private:
     NormalizerConfig config;
 };
 
-Normalizer::Normalizer(const NormalizerConfig& nc)
-{
-    config = nc;
-}
+Normalizer::Normalizer(const NormalizerConfig& nc) : config(nc)
+{ }
 
 // FIXIT-L this works with one normalizer per policy
 // but would be better if binder could select
@@ -286,6 +284,7 @@ void Normalizer::show(const SnortConfig*) const
 
 void Normalizer::eval(Packet* p)
 {
+    // cppcheck-suppress unreadVariable
     Profile profile(norm_perf_stats);
 
     if ( !p->is_rebuilt() && !p->active->packet_was_dropped() )
index 441c14073fde6c03f8290dfeafe0105e9bf71d5b..edaa6b72d2098b1cffb10f233e90da3d8fda4469 100644 (file)
@@ -637,19 +637,19 @@ TEST_CASE("enable", "[PacketTracer]")
 {
     TestPacketTracer::thread_init();
     // packet tracer is disabled by default
-    CHECK(!TestPacketTracer::is_active());
+    CHECK(false == TestPacketTracer::is_active());
     // enabled from user
     TestPacketTracer::set_user_enable(true);
-    CHECK(TestPacketTracer::is_user_enabled());
-    CHECK(!TestPacketTracer::is_daq_enabled());
+    CHECK(true == TestPacketTracer::is_user_enabled());
+    CHECK(false == TestPacketTracer::is_daq_enabled());
     // enabled from DAQ
     TestPacketTracer::set_daq_enable(true);
-    CHECK(TestPacketTracer::is_daq_enabled());
+    CHECK(true == TestPacketTracer::is_daq_enabled());
     // disable DAQ enable
     TestPacketTracer::set_daq_enable(false);
-    CHECK(!TestPacketTracer::is_daq_enabled());
+    CHECK(false == TestPacketTracer::is_daq_enabled());
     // user configuration remain enabled
-    CHECK(TestPacketTracer::is_user_enabled());
+    CHECK(true == TestPacketTracer::is_user_enabled());
 
     TestPacketTracer::thread_term();
 }
index 9215b035fca55781c3012b28369636c68ca29983..c552f7f1e0393bba376d756d2d0cb924d369a5b8 100644 (file)
@@ -85,9 +85,9 @@ protected:
     // non-static variable
     FILE* log_fh = stdout;
     std::vector<bool> mutes;
-    char buffer[max_buff_size];
+    char buffer[max_buff_size] = {0};
     unsigned buff_len = 0;
-    char daq_buffer[max_buff_size];
+    char daq_buffer[max_buff_size] = {0};
     unsigned daq_buff_len = 0;
 
     unsigned pause_count = 0;
@@ -96,7 +96,7 @@ protected:
     bool shell_enabled = false;
     bool active = false;
 
-    char debug_session[PT_DEBUG_SESSION_ID_SIZE];
+    char debug_session[PT_DEBUG_SESSION_ID_SIZE] = {0};
     PacketConstraints constraints;
 
     // static functions
index c9a1ec71530700fdae047b5f6b4ad35999832b88..91473101564c762879b66cd7f6db83c630807de0 100644 (file)
@@ -34,7 +34,7 @@ void CSVFormatter::finalize_fields()
     {
         std::string section = section_names[i];
 
-        for( auto& field : field_names[i] )
+        for( const auto& field : field_names[i] )
         {
             header += ",";
             header += section;
index 03adedf4c53d361943727a6c42bdbf0ac46b915a..622b1984b680669a277fce40ca31630697ba5bd0 100644 (file)
@@ -137,10 +137,10 @@ FlowIPTracker::FlowIPTracker(PerfConfig* perf) : PerfTracker(perf, TRACKER_NAME)
 
 FlowIPTracker::~FlowIPTracker()
 {
-    const XHashStats& stats = ip_map->get_stats();
-    pmstats.flow_tracker_creates = stats.nodes_created;
-    pmstats.flow_tracker_total_deletes = stats.memcap_deletes;
-    pmstats.flow_tracker_prunes = stats.memcap_prunes;
+    const XHashStats& tmp_stats = ip_map->get_stats();
+    pmstats.flow_tracker_creates = tmp_stats.nodes_created;
+    pmstats.flow_tracker_total_deletes = tmp_stats.memcap_deletes;
+    pmstats.flow_tracker_prunes = tmp_stats.memcap_prunes;
 
     delete ip_map;
 }
@@ -168,17 +168,17 @@ void FlowIPTracker::update(Packet* p)
         if ( !value )
             return;
 
-        TrafficStats* stats = &value->traffic_stats[type];
+        TrafficStats* tmp_stats = &value->traffic_stats[type];
 
         if ( !swapped )
         {
-            stats->packets_a_to_b++;
-            stats->bytes_a_to_b += len;
+            tmp_stats->packets_a_to_b++;
+            tmp_stats->bytes_a_to_b += len;
         }
         else
         {
-            stats->packets_b_to_a++;
-            stats->bytes_b_to_a += len;
+            tmp_stats->packets_b_to_a++;
+            tmp_stats->bytes_b_to_a += len;
         }
         value->total_packets++;
         value->total_bytes += len;
index 240328d0f76b9cc5bcb5fa40eb220e2e67dac56a..d4f49489a6f8d2f19f8cd4f6b62239b0695bbee2 100644 (file)
@@ -405,14 +405,13 @@ bool ModuleConfig::resolve()
             }
         }
 
-        for ( auto &i : peg_names )
-        {
-            if ( !i.second )
+        std::for_each(peg_names.cbegin(), peg_names.cend(),
+            [this](const std::pair<const std::string, bool>& i)
             {
-                ParseWarning(WARN_CONF, "Perf monitor is unable to find %s.%s count\n",
-                    name.c_str(), i.first.c_str());
-            }
-        }
+                if (!i.second)
+                    ParseWarning(WARN_CONF, "Perf monitor is unable to find %s.%s count\n",
+                        name.c_str(), i.first.c_str());
+            });
     }
     name.clear();
     peg_names.clear();
index ce2c0079e5511d097bcab0b459e9bf48caeb1fdd..ec66a3ca74e0af6bec5458c01327a1bbb7f08417 100644 (file)
@@ -334,6 +334,7 @@ void PerfMonitor::disable_profiling(PerfConstraints* constraints)
 
 void PerfMonitor::eval(Packet* p)
 {
+    // cppcheck-suppress unreadVariable
     Profile profile(perfmonStats);
 
     if (p)
index 254e8b7f32f79af235856d72a7d9e81a5ba80027..accf541561cd5d39fde428f8418cd8bacd7d3ecd 100644 (file)
@@ -433,6 +433,7 @@ void PortScan::show(const SnortConfig*) const
 
 void PortScan::eval(Packet* p)
 {
+    // cppcheck-suppress unreadVariable
     Profile profile(psPerfStats);
     assert(p->ptrs.ip_api.is_ip());
 
index 28d6e8f6e861e376283015ec2311e1553e327b33..2a84aff3ac3b168c8b45bff71f91ec121e76d18e 100644 (file)
@@ -474,6 +474,7 @@ private:
 
 void IpRepHandler::handle(DataEvent& event, Flow*)
 {
+    // cppcheck-suppress unreadVariable
     Profile profile(reputation_perf_stats);
     Packet* p = const_cast<Packet*>(event.get_packet());
     assert(p);
@@ -503,6 +504,7 @@ private:
 
 void AuxiliaryIpRepHandler::handle(DataEvent& event, Flow*)
 {
+    // cppcheck-suppress unreadVariable
     Profile profile(reputation_perf_stats);
     ReputationData* data = static_cast<ReputationData*>(inspector.get_thread_specific_data());
     assert(data);
index 31a2b4ae2fac9c5a63631b2ea1ce22ddbf5f78b6..ba5688f723e1c75f7bcc6dd093ff5773de62c1f2 100644 (file)
@@ -718,6 +718,7 @@ static int load_file(int total_lines, const char* path)
         return 0;
     }
 
+    // cppcheck-suppress invalidTestForOverflow
     if (total_lines + num_lines < total_lines)
     {
         ErrorMessage("Too many entries in one file.\n");
index 920837e49ecead78a984441d788145238e369d8b..35294bb9657b009b82ac2edfc95f5d042757af5f 100644 (file)
@@ -410,9 +410,9 @@ void RnaAppDiscovery::discover_netbios_name(const snort::Packet* p, DiscoveryFil
 
     if ( rt->set_netbios_name(nb_name) )
     {
-        const auto& src_ip = p->ptrs.ip_api.get_src();
-        const auto& src_ip_ptr = (const struct in6_addr*) src_ip->get_ip6_ptr();
-        const auto& src_mac = layer::get_eth_layer(p)->ether_src;
+        const SfIp* src_ip = p->ptrs.ip_api.get_src();
+        const struct in6_addr* src_ip_ptr = (const struct in6_addr*) src_ip->get_ip6_ptr();
+        const uint8_t* src_mac = layer::get_eth_layer(p)->ether_src;
 
         logger.log(RNA_EVENT_CHANGE, CHANGE_NETBIOS_NAME, src_ip_ptr, src_mac,
             &rt, p, (uint32_t) packet_time(), 0, nullptr, nullptr, nullptr, nullptr, nullptr,
index 3db23dc1157967c65aa31459d33e201f2866e49b..47b9d5838c128a8758bc2a59d497258af6ef8e5a 100644 (file)
@@ -30,6 +30,7 @@ using namespace snort;
 
 void RnaAppidEventHandler::handle(DataEvent& event, Flow*)
 {
+    // cppcheck-suppress unreadVariable
     Profile profile(rna_perf_stats);
     ++rna_stats.appid_change;
     update_rna_pkt_stats(event);
@@ -38,6 +39,7 @@ void RnaAppidEventHandler::handle(DataEvent& event, Flow*)
 
 void RnaIcmpBidirectionalEventHandler::handle(DataEvent& event, Flow*)
 {
+    // cppcheck-suppress unreadVariable
     Profile profile(rna_perf_stats);
     ++rna_stats.icmp_bidirectional;
     update_rna_pkt_stats(event);
@@ -46,6 +48,7 @@ void RnaIcmpBidirectionalEventHandler::handle(DataEvent& event, Flow*)
 
 void RnaIcmpNewFlowEventHandler::handle(DataEvent& event, Flow*)
 {
+    // cppcheck-suppress unreadVariable
     Profile profile(rna_perf_stats);
     ++rna_stats.icmp_new;
     update_rna_pkt_stats(event);
@@ -54,6 +57,7 @@ void RnaIcmpNewFlowEventHandler::handle(DataEvent& event, Flow*)
 
 void RnaIpBidirectionalEventHandler::handle(DataEvent& event, Flow*)
 {
+    // cppcheck-suppress unreadVariable
     Profile profile(rna_perf_stats);
     ++rna_stats.ip_bidirectional;
     update_rna_pkt_stats(event);
@@ -62,6 +66,7 @@ void RnaIpBidirectionalEventHandler::handle(DataEvent& event, Flow*)
 
 void RnaIpNewFlowEventHandler::handle(DataEvent& event, Flow*)
 {
+    // cppcheck-suppress unreadVariable
     Profile profile(rna_perf_stats);
     ++rna_stats.ip_new;
     update_rna_pkt_stats(event);
@@ -70,6 +75,7 @@ void RnaIpNewFlowEventHandler::handle(DataEvent& event, Flow*)
 
 void RnaTcpSynEventHandler::handle(DataEvent& event, Flow*)
 {
+    // cppcheck-suppress unreadVariable
     Profile profile(rna_perf_stats);
     ++rna_stats.tcp_syn;
     update_rna_pkt_stats(event);
@@ -78,6 +84,7 @@ void RnaTcpSynEventHandler::handle(DataEvent& event, Flow*)
 
 void RnaTcpSynAckEventHandler::handle(DataEvent& event, Flow*)
 {
+    // cppcheck-suppress unreadVariable
     Profile profile(rna_perf_stats);
     ++rna_stats.tcp_syn_ack;
     update_rna_pkt_stats(event);
@@ -86,6 +93,7 @@ void RnaTcpSynAckEventHandler::handle(DataEvent& event, Flow*)
 
 void RnaTcpMidstreamEventHandler::handle(DataEvent& event, Flow*)
 {
+    // cppcheck-suppress unreadVariable
     Profile profile(rna_perf_stats);
     ++rna_stats.tcp_midstream;
     update_rna_pkt_stats(event);
@@ -94,6 +102,7 @@ void RnaTcpMidstreamEventHandler::handle(DataEvent& event, Flow*)
 
 void RnaUdpBidirectionalEventHandler::handle(DataEvent& event, Flow*)
 {
+    // cppcheck-suppress unreadVariable
     Profile profile(rna_perf_stats);
     ++rna_stats.udp_bidirectional;
     update_rna_pkt_stats(event);
@@ -102,6 +111,7 @@ void RnaUdpBidirectionalEventHandler::handle(DataEvent& event, Flow*)
 
 void RnaUdpNewFlowEventHandler::handle(DataEvent& event, Flow*)
 {
+    // cppcheck-suppress unreadVariable
     Profile profile(rna_perf_stats);
     ++rna_stats.udp_new;
     update_rna_pkt_stats(event);
@@ -110,6 +120,7 @@ void RnaUdpNewFlowEventHandler::handle(DataEvent& event, Flow*)
 
 void RnaIdleEventHandler::handle(DataEvent& event, Flow*)
 {
+    // cppcheck-suppress unreadVariable
     Profile profile(rna_perf_stats);
     ++rna_stats.change_host_update;
     update_rna_pkt_stats(event);
@@ -118,6 +129,7 @@ void RnaIdleEventHandler::handle(DataEvent& event, Flow*)
 
 void RnaDHCPInfoEventHandler::handle(DataEvent& event, Flow*)
 {
+    // cppcheck-suppress unreadVariable
     Profile profile(rna_perf_stats);
     ++rna_stats.dhcp_info;
     update_rna_pkt_stats(event);
@@ -126,6 +138,7 @@ void RnaDHCPInfoEventHandler::handle(DataEvent& event, Flow*)
 
 void RnaDHCPDataEventHandler::handle(DataEvent& event, Flow*)
 {
+    // cppcheck-suppress unreadVariable
     Profile profile(rna_perf_stats);
     ++rna_stats.dhcp_data;
     update_rna_pkt_stats(event);
@@ -134,6 +147,7 @@ void RnaDHCPDataEventHandler::handle(DataEvent& event, Flow*)
 
 void RnaFpSMBEventHandler::handle(DataEvent& event, Flow*)
 {
+    // cppcheck-suppress unreadVariable
     Profile profile(rna_perf_stats);
     ++rna_stats.smb;
     update_rna_pkt_stats(event);
@@ -142,6 +156,7 @@ void RnaFpSMBEventHandler::handle(DataEvent& event, Flow*)
 
 void RnaCPEOSInfoEventHandler::handle(DataEvent& event, Flow*)
 {
+    // cppcheck-suppress unreadVariable
     Profile profile(rna_perf_stats);
     ++rna_stats.cpe_os;
     update_rna_pkt_stats(event);
@@ -150,6 +165,7 @@ void RnaCPEOSInfoEventHandler::handle(DataEvent& event, Flow*)
 
 void RnaNetFlowEventHandler::handle(DataEvent& event, Flow*)
 {
+    // cppcheck-suppress unreadVariable
     Profile profile(rna_perf_stats);
     ++rna_stats.netflow_record;
     update_rna_pkt_stats(event);
index b6faa45c656538a47a880d4f72b98d59d987f871..713787bd95e5813cbb9af2d9490c187fd4db8961 100644 (file)
@@ -32,7 +32,7 @@ inline static void update_rna_pkt_stats(const snort::Packet* p)
     rna_stats.total_bytes_in_interval += p->pktlen;
 }
 
-inline static void update_rna_pkt_stats(snort::DataEvent& event)
+inline static void update_rna_pkt_stats(const snort::DataEvent& event)
 {
     update_rna_pkt_stats(event.get_packet());
 }
index c975d48db878342c994db228c9e617b3216f43d3..1ea4ae78a8bf20de4332856842d871f3ac3c3e6f 100644 (file)
@@ -148,9 +148,9 @@ public:
     std::string dhcp55;
     std::string dhcp60;
 
-    uint16_t smb_major;
-    uint16_t smb_minor;
-    uint32_t smb_flags;
+    uint16_t smb_major = 0;
+    uint16_t smb_minor = 0;
+    uint32_t smb_flags = 0;
 
     void clear()
     {
index 088e47ef3553c4faa12038d2e06f0f6731d85b8f..97f0f3b621b95e270b764978c3d5a630fcde2e97 100644 (file)
@@ -182,7 +182,7 @@ static inline bool is_ws_good(const FpTcpKey& key, const vector<FpElement>& tfp_
 }
 
 static inline bool is_option_good(const int& optpos, const int& fp_optpos,
-    uint8_t* optorder, uint8_t* fp_optorder)
+    const uint8_t* optorder, const uint8_t* fp_optorder)
 {
     if (optpos != fp_optpos)
         return false;
@@ -196,7 +196,7 @@ static inline bool is_option_good(const int& optpos, const int& fp_optpos,
 }
 
 static inline bool is_ts_good(const FpTcpKey& key, const vector<FpElement>& topts,
-    const int& optpos, uint8_t* optorder, uint8_t* fp_optorder)
+    const int& optpos, const uint8_t* optorder, uint8_t* fp_optorder)
 {
     if (key.syn_timestamp)
         return false;
@@ -354,7 +354,7 @@ const TcpFingerprint* TcpFpProcessor::get_tcp_fp(const FpTcpKey& key, uint8_t tt
 static int get_tcp_option(const Packet* p, tcp::TcpOptCode opt_code, int& pos)
 {
     int maxops = (int) p->ptrs.tcph->options_len();
-    if (maxops < 0 || TCP_OPTLENMAX < maxops)
+    if (TCP_OPTLENMAX < maxops)
     {
         pos = -1;
         return -1;
@@ -636,11 +636,11 @@ TEST_CASE("get_tcp_fp", "[rna_fingerprint_tcp]")
     rawfp.fpid = 1234;
     rawfp.fp_type = 1;
     rawfp.tcp_window = "SYN";
-    CHECK( processor->push(rawfp) == true );
+    CHECK( true == processor->push(rawfp) );
 
     // Testing the insertion failure for duplicate fpid
     rawfp.fp_type = 2;
-    CHECK( processor->push(rawfp) == false );
+    CHECK( false == processor->push(rawfp) );
 
     processor->make_tcp_fp_tables(TcpFpProcessor::TCP_FP_MODE::SERVER);
     processor->make_tcp_fp_tables(TcpFpProcessor::TCP_FP_MODE::CLIENT);
@@ -836,7 +836,7 @@ TEST_CASE("get_tcp_option", "[rna_fingerprint_tcp]")
     int pos;
 
     // Check the default case when the desired option does not match
-    CHECK( get_tcp_option(&p, tcp::TcpOptCode::EOL, pos) == -1 );
+    CHECK( -1 == get_tcp_option(&p, tcp::TcpOptCode::EOL, pos) );
 
     // Check the case when NOP option is matched
     cooked_pkt[54] = 1; // 34 + TCP_MIN_HEADER_LEN = 54
index 1765d6163d3ab315d0ed6cc835862a26d7416b86..aa41722ec3cded09a854e8347636d02ae9678d68 100644 (file)
@@ -132,7 +132,7 @@ struct FpFingerprintState
     int initial_mss = -1;
     int timestamp = -1;
     int numopts = -1;
-    uint8_t tcpopts[4];
+    uint8_t tcpopts[4] = {};
     time_t timeout = -1;
 
     bool set(const snort::Packet*);
index 24519bfbd611ebaa27fc1995cec2db46efa17108..4a03cbcce59a2b0040fa4f73180a6037bb4b6502 100644 (file)
@@ -152,12 +152,10 @@ static int match_ua_part(void* id, void*, int, void* data, void*)
     auto cur_fp = (UaFingerprint*) id;
     auto matched_parts = (vector<UaFingerprint*>*)data;
 
-    for (const auto& fp : *matched_parts)
-        if ( *fp == *cur_fp )
-            return 0; // ignore already recorded matching part
-
-    matched_parts->emplace_back(cur_fp);
-    return 0; // search continues for the next match
+    if (std::none_of(matched_parts->cbegin(), matched_parts->cend(),
+        [cur_fp](const UaFingerprint* fp){ return *fp == *cur_fp; }))
+        matched_parts->emplace_back(cur_fp);
+    return 0;
 }
 
 struct CompareParts
index d2ec4f89bbff57e51593b58e3dc97824ff622183..7508070bd9f3412e1c632328509185ce5b1d1789 100644 (file)
@@ -24,6 +24,7 @@
 
 #include "rna_fingerprint_udp.h"
 
+#include <algorithm>
 #include <sstream>
 
 #ifdef UNIT_TEST
@@ -95,7 +96,7 @@ const DHCPFingerprint* UdpFpProcessor::match_dhcp_fingerprint(const FpDHCPKey& k
     uint32_t fptype = FpFingerprint::FpType::FP_TYPE_DHCP;
     for (const auto& fp: dhcp_fps)
     {
-        if (fptype == fp.fp_type && fp.dhcp55.size() == key.dhcp55_len and
+        if (fptype == fp.fp_type and fp.dhcp55.size() == key.dhcp55_len and
             match_dhcp_options(fp.dhcp55, key.dhcp55))
         {
             if (key.dhcp60 and !fp.dhcp60.empty())
index 21e95bf0642600c43d9653d008d14f62a7b98500..81db5301a86a35458f092d7c0191c69f51caf0ea 100644 (file)
@@ -103,14 +103,14 @@ RnaTracker RNAFlow::get_tracker(const Packet* p, DiscoveryFilter& filter)
     return rt;
 }
 
-void RNAFlow::set_server(RnaTracker& ht)
+void RNAFlow::set_server(const RnaTracker& ht)
 {
     rna_mutex.lock();
     serverht = ht;
     rna_mutex.unlock();
 }
 
-void RNAFlow::set_client(RnaTracker& ht)
+void RNAFlow::set_client(const RnaTracker& ht)
 {
     rna_mutex.lock();
     clientht = ht;
index c6c64bbf555d7cebe7588d178b5f96841152ec28..a3e5a1ba9b4b3f722e96304bf51d5c7cb7e067d0 100644 (file)
@@ -61,8 +61,8 @@ public:
     RnaTracker get_client(const snort::SfIp&);
     RnaTracker get_tracker(const snort::Packet*, DiscoveryFilter&);
 
-    void set_server(RnaTracker& ht);
-    void set_client(RnaTracker& ht);
+    void set_server(const RnaTracker& ht);
+    void set_client(const RnaTracker& ht);
 
 };
 
index 92eb8328bcd6167053b2791623456c0eb315fcab..0b2de477beba3eb40dec498c3cb9a00c67d6c5ba 100644 (file)
@@ -132,6 +132,7 @@ void RnaInspector::install_reload_handler(SnortConfig* sc)
 
 void RnaInspector::eval(Packet* p)
 {
+    // cppcheck-suppress unreadVariable
     Profile profile(rna_perf_stats);
     ++rna_stats.other_packets;
     update_rna_pkt_stats(p);
index 7e8dac0f79a0cab8c0d019a1a67e8428d2514506..ff6b51415bb10fd45f42bc1b44e5e45f9881e417 100644 (file)
@@ -264,12 +264,12 @@ TEST_CASE("RNA logger", "[rna_logger]")
         RnaTracker ht;
         uint8_t mac[6] = {0xA1, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6};
         RnaLogger logger1(false);
-        CHECK(logger1.log(0, 0, nullptr, mac, &ht, nullptr, 0, 0,
-            nullptr, nullptr, nullptr, nullptr, nullptr) == false);
+        CHECK(false == logger1.log(0, 0, nullptr, mac, &ht, nullptr, 0, 0,
+            nullptr, nullptr, nullptr, nullptr, nullptr));
 
         RnaLogger logger2(true);
-        CHECK(logger2.log(0, 0, nullptr, mac, &ht, nullptr, 0, 0,
-            nullptr, nullptr, nullptr, nullptr, nullptr) == true);
+        CHECK(true == logger2.log(0, 0, nullptr, mac, &ht, nullptr, 0, 0,
+            nullptr, nullptr, nullptr, nullptr, nullptr));
     }
 }
 #endif
index f854e2229521b18d99e8169935d048937d76aff4..1a149d9683e7669ae15aa90d2be882021e1bc047 100644 (file)
@@ -48,7 +48,7 @@ struct RnaLoggerEvent : public Event
     uint32_t event_time = 0;
     uint16_t type;
     uint16_t subtype;
-    const struct in6_addr* ip;
+    const struct in6_addr* ip = nullptr;
     const uint8_t* mac;
     const RnaTracker* ht;
     const snort::HostMac* hm;
index 7a088b2d38cd4bf57b6b3f0e1782a8915d2195b0..3dd97d33b545c4d9eb3f24b010a4192beef6ab1a 100644 (file)
@@ -34,9 +34,9 @@ bool HostTrackerMac::add_network_proto(const uint16_t type)
 {
     lock_guard<mutex> lck(host_tracker_mac_lock);
 
-    for ( const auto& proto : network_protos )
-        if ( proto == type )
-            return false;
+    if (std::any_of(network_protos.cbegin(), network_protos.cend(),
+        [type](uint16_t proto){ return proto == type; }))
+        return false;
 
     network_protos.emplace_back(type);
     return true;
@@ -163,7 +163,7 @@ TEST_CASE("RNA Mac Cache", "[rna_mac_cache]")
 
         a_ptr->get_vlan_details(cfi, priority, vid);
 
-        CHECK(a_ptr->has_vlan());
+        CHECK(true == a_ptr->has_vlan());
         CHECK(cfi == (ntohs(vth_pri_cfi_vlan) & 0x1000) >> 12);
         CHECK(priority == (ntohs(vth_pri_cfi_vlan)) >> 13);
         CHECK(vid == (ntohs(vth_pri_cfi_vlan) & 0x0FFF));
index 62f383b2bdc3884a2bc5cc204f84f60eaa816af1..0e57da2b288c0c525462bb7236f72b6e3c22e139 100644 (file)
@@ -504,7 +504,7 @@ bool RnaModule::set(const char* fqn, Value& v, SnortConfig*)
             return true;
         else if (v.is("substring"))
         {
-            const auto& ua_part = v.get_string();
+            const char* ua_part = v.get_string();
             if ( !ua_part )
                 return false;
             fingerprint.user_agent.emplace_back(ua_part);
@@ -628,7 +628,6 @@ bool RnaModule::log_mac_cache(const char* outfile)
         snort::LogMessage("Error opening %s for dumping MAC cache", outfile);
     }
 
-    string str;
     HostCacheMac* host_cache_mac = get_host_cache_mac();
     assert(host_cache_mac);
     const auto&& lru_data = host_cache_mac->get_all_data();
@@ -636,7 +635,7 @@ bool RnaModule::log_mac_cache(const char* outfile)
         << lru_data.size() << " trackers" << endl << endl;
     for ( const auto& elem : lru_data )
     {
-        str = "MAC: ";
+        string str = "MAC: ";
         str += format_dump_mac(elem.first.mac_addr);
         str += "\n Key: " + to_string(hash_mac(elem.first.mac_addr));
         elem.second->stringify(str);
@@ -664,14 +663,14 @@ TEST_CASE("RNA module", "[rna_module]")
         RnaModule mod;
         SnortConfig sc;
 
-        CHECK_FALSE(mod.begin("dummy", 0, nullptr));
-        CHECK(mod.end("rna", 0, nullptr) == false);
-        CHECK(mod.begin("rna", 0, nullptr) == true);
+        CHECK(false == mod.begin("dummy", 0, nullptr));
+        CHECK(false == mod.end("rna", 0, nullptr));
+        CHECK(true == mod.begin("rna", 0, nullptr));
 
         Value v1("rna.conf");
         v1.set(Parameter::find(rna_params, "rna_conf_path"));
-        CHECK(mod.set(nullptr, v1, nullptr) == true);
-        CHECK(mod.end("rna", 0, &sc) == true);
+        CHECK(true == mod.set(nullptr, v1, nullptr));
+        CHECK(true == mod.end("rna", 0, &sc));
 
         RnaModuleConfig* rc = mod.get_config();
         CHECK(rc != nullptr);
@@ -686,11 +685,11 @@ TEST_CASE("RNA module", "[rna_module]")
         SnortConfig sc;
 
         sc.set_run_flags(RUN_FLAG__IP_FRAGS_ONLY);
-        CHECK(sc.ip_frags_only() == true);
+        CHECK(true == sc.ip_frags_only());
 
-        CHECK(mod.begin(RNA_NAME, 0, nullptr) == true);
-        CHECK(mod.end(RNA_NAME, 0, &sc) == true);
-        CHECK(sc.ip_frags_only() == false);
+        CHECK(true == mod.begin(RNA_NAME, 0, nullptr));
+        CHECK(true == mod.end(RNA_NAME, 0, &sc));
+        CHECK(false == sc.ip_frags_only());
 
         delete mod.get_config();
     }
@@ -701,11 +700,11 @@ TEST_CASE("RNA module", "[rna_module]")
         SnortConfig sc;
 
         sc.clear_run_flags(RUN_FLAG__TRACK_ON_SYN);
-        CHECK(sc.track_on_syn() == false);
+        CHECK(false == sc.track_on_syn());
 
-        CHECK(mod.begin(RNA_NAME, 0, nullptr) == true);
-        CHECK(mod.end(RNA_NAME, 0, &sc) == true);
-        CHECK(sc.track_on_syn() == true);
+        CHECK(true == mod.begin(RNA_NAME, 0, nullptr));
+        CHECK(true == mod.end(RNA_NAME, 0, &sc));
+        CHECK(true == sc.track_on_syn());
 
         delete mod.get_config();
     }
index 36428520d6e71ec2646e0e63b46b27b7d80bfd59..058301317fb29e3fb1ec9ca05339fbbf1795e221 100644 (file)
@@ -88,10 +88,8 @@ HostCacheIp::Data RnaPnd::find_or_create_host_tracker(const SfIp& ip, bool& new_
 }
 
 RnaPnd::RnaPnd(const bool en, const std::string& cp, RnaConfig* rc) :
-    logger(RnaLogger(en)), filter(DiscoveryFilter(cp)), conf(rc)
-{
-    update_timeout = (rc ? rc->update_timeout : 0);
-}
+    logger(RnaLogger(en)), filter(DiscoveryFilter(cp)), conf(rc), update_timeout(rc ? rc->update_timeout : 0)
+{ }
 
 RnaPnd::~RnaPnd() = default;
 
index 29600d9ba6ad5d131780095633cb0b38659649b1..11f77064d2e5080d75d23c12982f6d3e1a466dfe 100644 (file)
@@ -28,7 +28,9 @@ THREAD_LOCAL ProfileStats rna_perf_stats;
 
 namespace snort
 {
-Module::Module(const char*, const char*, const Parameter*, bool) {}
+Module::Module(const char* s, const char*, const Parameter*, bool)
+    : name(s), help(nullptr), params(nullptr), list(false)
+{ }
 bool TcpFingerprint::operator==(const TcpFingerprint&) const { return true; }
 
 // inspector
@@ -65,7 +67,8 @@ private:
 } // end of namespace snort
 
 static ControlConn s_ctrlcon(1, true);
-ControlConn::ControlConn(int, bool) {}
+ControlConn::ControlConn(int, bool) : shell(nullptr), fd(-1), touched(0)
+{}
 ControlConn::~ControlConn() {}
 
 #endif
index 3b5e479e124d4de6231d6b8768093750fbc08de7..44514b94d240bd0c2ed3a2c56c3efc3b6128dd47 100644 (file)
@@ -91,13 +91,7 @@ namespace snort
 
 TEST_GROUP(rna_ua_fp_processor_test)
 {
-    UaFpProcessor* ua_proc;
-
-    void setup() override
-    { ua_proc = new UaFpProcessor; }
-
-    void teardown() override
-    { delete ua_proc; }
+    UaFpProcessor ua_proc;
 };
 
 TEST(rna_ua_fp_processor_test, sequential_setup)
@@ -105,14 +99,14 @@ TEST(rna_ua_fp_processor_test, sequential_setup)
     UaFingerprint fp;
 
     fp.user_agent = "Pink ";
-    ua_proc->push_agent(fp);
-    ua_proc->make_mpse();
+    ua_proc.push_agent(fp);
+    ua_proc.make_mpse();
 
     CHECK(s_prep_count == 1);
 
     fp.user_agent = "Floyd";
-    ua_proc->push_agent(fp);
-    ua_proc->make_mpse(true);
+    ua_proc.push_agent(fp);
+    ua_proc.make_mpse(true);
 
     CHECK(s_prep_count == 2);
     CHECK(s_prep_data == "Pink Floyd");
@@ -123,18 +117,18 @@ TEST(rna_ua_fp_processor_test, interleaved_setup)
     UaFingerprint fp;
 
     fp.user_agent = "Pink ";
-    ua_proc->push_agent(fp);
+    ua_proc.push_agent(fp);
 
     CHECK(s_prep_count == 0);
 
     fp.user_agent = "Floyd";
-    ua_proc->push_agent(fp);
-    ua_proc->make_mpse(true);
+    ua_proc.push_agent(fp);
+    ua_proc.make_mpse(true);
 
     CHECK(s_prep_count == 2);
     CHECK(s_prep_data == "Pink Floyd");
 
-    ua_proc->make_mpse();
+    ua_proc.make_mpse();
 
     CHECK(s_prep_count == 2);
     CHECK(s_prep_data == "Pink Floyd");
index 30e4ad34a8b4d285d2808c05ce58c81c465f1108..7d1697bb98f0a5c399b0fff1058d21db8c6f04d4 100644 (file)
@@ -35,6 +35,8 @@ class ActiveAction;
 class SO_PUBLIC Active
 {
 public:
+    Active() = default;
+    ~Active() = default;
 
     struct Counts
     {
@@ -233,17 +235,17 @@ private:
     static THREAD_LOCAL bool s_suspend;
     static THREAD_LOCAL ActiveSuspendReason s_suspend_reason;
 
-    int active_tunnel_bypass;
-    const char* drop_reason;
+    int active_tunnel_bypass = 0;
+    const char* drop_reason = nullptr;
 
     // these can't be pkt flags because we do the handling
     // of these flags following all processing and the drop
     // or response may have been produced by a pseudopacket.
-    ActiveStatus active_status;
-    ActiveWouldReason active_would_reason;
-    ActiveActionType active_action;
-    ActiveActionType delayed_active_action;
-    ActiveAction* delayed_reject;    // set with set_delayed_action()
+    ActiveStatus active_status = AST_MAX;
+    ActiveWouldReason active_would_reason = WHD_EXIT;
+    ActiveActionType active_action = ACT_MAX;
+    ActiveActionType delayed_active_action = ACT_MAX;
+    ActiveAction* delayed_reject = nullptr; // set with set_delayed_action()
 };
 
 struct SO_PUBLIC ActiveSuspendContext
index fd5531099d9efce243c51d44c34ac449ddbc00c0..2c60f8a9593176a46657395197893e09335d7b89 100644 (file)
@@ -286,14 +286,12 @@ bool SFDAQ::init(const SFDAQConfig* cfg, unsigned total_instances)
         }
     }
 
-    for (SFDAQModuleConfig* dmc : cfg->module_configs)
+    if (std::any_of(cfg->module_configs.cbegin(), cfg->module_configs.cend(),
+        [](const SFDAQModuleConfig* dmc){ return !AddDaqModuleConfig(dmc); }))
     {
-        if (!AddDaqModuleConfig(dmc))
-        {
-            daq_config_destroy(daqcfg);
-            daqcfg = nullptr;
-            return false;
-        }
+        daq_config_destroy(daqcfg);
+        daqcfg = nullptr;
+        return false;
     }
 
 /*
index 500bf2562577726d746748043e33eed67f92eee1..17bd5cb25a7357fd864de34377e2fc4da8d86108 100644 (file)
@@ -24,6 +24,8 @@
 
 #include "sfdaq_config.h"
 
+#include <algorithm>
+
 using namespace std;
 
 static pair<string, string> parse_variable(const char* varkvp)
@@ -46,11 +48,8 @@ static pair<string, string> parse_variable(const char* varkvp)
  */
 
 SFDAQModuleConfig::SFDAQModuleConfig(const SFDAQModuleConfig& other)
-{
-    name = other.name;
-    mode = other.mode;
-    variables = other.variables;
-}
+    : name(other.name), mode(other.mode), variables(other.variables)
+{ }
 
 void SFDAQModuleConfig::set_variable(const char* varkvp)
 {
@@ -116,8 +115,9 @@ void SFDAQConfig::overlay(const SFDAQConfig* other)
         for (SFDAQModuleConfig *dmc : module_configs)
             delete dmc;
         module_configs.clear();
-        for (SFDAQModuleConfig *dmc : other->module_configs)
-            module_configs.emplace_back(new SFDAQModuleConfig(*dmc));
+        module_configs.reserve(other->module_configs.size());
+        transform(other->module_configs.cbegin(), other->module_configs.cend(), back_inserter(module_configs),
+            [](const SFDAQModuleConfig* dmc){ return new SFDAQModuleConfig(*dmc); });
     }
 
     if (!other->inputs.empty())
index 326b965f58dad94d2a9630af32265b9023465aaf..5c6d553e2911ce9255b5b3d3cd716c90eb25cafe 100644 (file)
@@ -69,7 +69,7 @@ TEST_CASE("parse sfdaq config", "[SFDAQModule]")
     {
         // Empty module table entry should fail
         CHECK(true == sfdm.begin("daq.modules", 1, &sc));
-        CHECK_FALSE(sfdm.end("daq.modules", 1, &sc));
+        CHECK(false == sfdm.end("daq.modules", 1, &sc));
     }
 
     CHECK(true == sfdm.begin("daq.modules", 2, &sc));
index 1777b203d05eaf31985b54abc4cfc47e6f7c30cd..edcb838a055527caa82cb11790daa85755b45fd4 100644 (file)
@@ -55,8 +55,8 @@ struct Location
     std::string file;
     unsigned line;
 
-    Location(const char* c, const char* p, const char* f, unsigned u)
-    { code = c; path = p; file = f; line = u; }
+    Location(const char* c, const char* p, const char* f, unsigned u) : code(c), path(p), file(f), line(u)
+    { }
 };
 
 static std::stack<Location> files;
@@ -254,9 +254,9 @@ static void add_service_to_otn_helper(SnortConfig* sc, OptTreeNode* otn, const c
 {
     SnortProtocolId svc_id = sc->proto_ref->add(svc_name);
 
-    for ( const auto& si : otn->sigInfo.services )
-        if ( si.snort_protocol_id == svc_id )
-            return;  // already added
+    if (std::any_of(otn->sigInfo.services.cbegin(), otn->sigInfo.services.cend(),
+        [svc_id](const SignatureServiceInfo& si){ return si.snort_protocol_id == svc_id; }))
+        return;  // already added
 
     SignatureServiceInfo si(svc_name, svc_id);
     otn->sigInfo.services.emplace_back(si);
index 1bad3e2365a4ef13ddb419671a8f3043ff4cca75..6ef2e19d40dcac9268f4718b5e264cf7bc802caf 100644 (file)
@@ -170,7 +170,7 @@ TEST_CASE("parse_int", "[ParseUtils]")
     {
         int res = parse_int("10  ", "test");
 
-        CHECK(res == 10);
+        CHECK((res == 10));
     }
 
     SECTION("not a number")
@@ -188,7 +188,7 @@ TEST_CASE("parse_int", "[ParseUtils]")
 
         int res = parse_int(data, "test");
 
-        CHECK(res == 65535);
+        CHECK((res == 65535));
         CHECK(errno == ERANGE);
     }
 
@@ -198,7 +198,7 @@ TEST_CASE("parse_int", "[ParseUtils]")
 
         int res = parse_int(data, "test");
 
-        CHECK(res == -65535);
+        CHECK((res == -65535));
         CHECK(errno == ERANGE);
     }
 
@@ -206,14 +206,14 @@ TEST_CASE("parse_int", "[ParseUtils]")
     {
         int res = parse_int("1", "test", 2, 3);
 
-        CHECK(res == 2);
+        CHECK((res == 2));
     }
 
     SECTION("above the limit")
     {
         int res = parse_int("4", "test", 2, 3);
 
-        CHECK(res == 3);
+        CHECK((res == 3));
     }
 }
 
index 7ac82893dac10f46d67e06a46f9646c5015fa13d..7f555a190caf3649c5313e7549bbd377a975e50b 100644 (file)
@@ -129,10 +129,10 @@ public:
 
 struct PolicyRuleStats
 {
-    const char* file;
-    int loaded;
-    int shared;
-    int enabled;
+    const char* file = nullptr;
+    int loaded = 0;
+    int shared = 0;
+    int enabled = 0;
 };
 
 //-------------------------------------------------------------------------
index 28075f7f204930a13b62397c59390c526901c68f..a8f2a35d07abf4af8ac250bdb2ef8e46d5625500 100644 (file)
@@ -464,7 +464,7 @@ const std::string ExpandVars(const std::string& input_str)
                     var_modifier = var_name[p+1];
                     var_aux = var_name.substr(p+2);
                 }
-                var_name = var_name.substr(0, p);
+                var_name.resize(p);
             }
 
             std::string var_contents = VarSearch(var_name);
@@ -473,7 +473,7 @@ const std::string ExpandVars(const std::string& input_str)
             {
             case '-':
                 if (var_contents.empty())
-                    var_contents = var_aux.c_str();
+                    var_contents = var_aux;
                 break;
 
             case '?':
index c26099011cbc48956de74b6a19dfd0224a99373c..4cb3fdaf63d399d998a6af530c482d768484ce73 100644 (file)
@@ -31,9 +31,9 @@
 
 TEST_GROUP(payload_injector_translate_test)
 {
-    uint8_t* http2_payload;
-    uint32_t payload_len;
-    InjectionReturnStatus status;
+    uint8_t* http2_payload; // cppcheck-suppress unusedVariable
+    uint32_t payload_len;   // cppcheck-suppress unusedVariable
+    InjectionReturnStatus status;   // cppcheck-suppress unusedVariable
 };
 
 TEST(payload_injector_translate_test, basic_hdr_translation)
index 480abba9df523c5ac7ef024c0124ee396b3d5da2..08c39ae534ab3059afa636d36c4f334c1bea0fe9 100644 (file)
@@ -77,9 +77,8 @@ protected:
 };
 
 AddressSpaceSelector::AddressSpaceSelector(const PolicySelectorApi* api_in,
-    std::vector<AddressSpaceSelection>& psv) : PolicySelector(api_in)
+    std::vector<AddressSpaceSelection>& psv) : PolicySelector(api_in), policy_selections(std::move(psv))
 {
-    policy_selections = std::move(psv);
     for (auto i = policy_selections.rbegin(); i != policy_selections.rend(); ++i)
     {
         std::sort((*i).addr_spaces.begin(), (*i).addr_spaces.end());
@@ -117,6 +116,7 @@ void AddressSpaceSelector::show() const
 
 bool AddressSpaceSelector::select_default_policies(uint32_t key, const SnortConfig* sc)
 {
+    // cppcheck-suppress unreadVariable
     Profile profile(address_space_selectPerfStats);
 
     address_space_select_stats.packets++;
index 0b3e9407ebc63b2c183261eef3f050d6954b5939..386b8ac5b62fa3e80c612c2337c45d2aa7afb4b0 100644 (file)
@@ -77,9 +77,8 @@ protected:
 };
 
 TenantSelector::TenantSelector(const PolicySelectorApi* api_in, std::vector<TenantSelection>& psv)
-    : PolicySelector(api_in)
+    : PolicySelector(api_in), policy_selections(std::move(psv))
 {
-    policy_selections = std::move(psv);
     for (auto i = policy_selections.rbegin(); i != policy_selections.rend(); ++i)
     {
         std::sort((*i).tenants.begin(), (*i).tenants.end());
@@ -117,6 +116,7 @@ void TenantSelector::show() const
 
 bool TenantSelector::select_default_policies(uint32_t key, const SnortConfig* sc)
 {
+    // cppcheck-suppress unreadVariable
     Profile profile(tenant_select_perf_stats);
 
     tenant_select_stats.packets++;
index 87a40c2004606d3e704b6e318da4fb7969bac932..d78e17ce90503b598f603441ad6c43fd911707d9 100644 (file)
@@ -36,7 +36,7 @@ void RuleGroup::add_rule()
 RuleGroup::~RuleGroup()
 {
     for ( int sect = snort::PS_NONE; sect <= snort::PS_MAX; sect++)
-        for ( auto* it : pm_list[sect] )
+        for ( const auto* it : pm_list[sect] )
             delete it;
 
     delete_nfp_rules();
index 6ba95b97c39ebfbac19cf7338f653d7b62063f6e..4bfd968e7af1a102231a34b960f9523cc8c3702b 100644 (file)
@@ -113,7 +113,7 @@ static int* RuleHashToSortedArray(GHash* rh)
          node != nullptr && k < (int)rh->get_count();
          node = rh->find_next() )
     {
-        if ( int* prid = (int*)node->data )
+        if ( const int* prid = (int*)node->data )
             ra[k++] = *prid;
     }
 
index b2092dc70859dbde7782adee10add4bd61ef95c7..29aa15bc140ec6e4d36e3e9f923de49e25508410 100644 (file)
@@ -112,7 +112,7 @@ TEST_CASE( "active context", "[profiler][active_context]" )
 
     active.get_fallback() = fallback;
 
-    CHECK( !active.is_set() );
+    CHECK( false == active.is_set() );
     CHECK( active.get() == nullptr );
     CHECK( active.get_default() == fallback );
 
@@ -121,12 +121,12 @@ TEST_CASE( "active context", "[profiler][active_context]" )
     CHECK( active.get_default() == fallback );
 
     CHECK( active.set(&a) == nullptr );
-    CHECK( active.is_set() );
+    CHECK( true == active.is_set() );
     CHECK( active.get() == &a );
     CHECK( active.get_default() == a );
 
     CHECK( active.set(&b) == &a );
-    CHECK( active.is_set() );
+    CHECK( true == active.is_set() );
     CHECK( active.get() == &b );
     CHECK( active.get_default() == b );
 }
index b3b3cc27a931a1925cde280ddabc3268954f9832..e43cc6438d78b4786037a0c004ae366b8e756d26 100644 (file)
@@ -25,6 +25,7 @@
 #include "profiler.h"
 
 #include <cassert>
+#include <numeric>
 
 #include "framework/module.h"
 #include "main/snort_config.h"
@@ -138,12 +139,11 @@ void Profiler::prepare_stats()
     auto children = root.get_children();
 
     hr_duration runtime = root.get_stats().time.elapsed;
-    hr_duration sum = 0_ticks;
 
     s_profiler_nodes.clear_flex();
 
-    for ( auto pn : children )
-        sum += pn->get_stats().time.elapsed;
+    hr_duration sum = std::accumulate(children.cbegin(), children.cend(), 0_ticks,
+        [](const hr_duration& s, const ProfilerNode* pn){ return s + pn->get_stats().time.elapsed; });
 
     otherPerfStats.time.checks = root.get_stats().time.checks;
     otherPerfStats.time.elapsed = (runtime > sum) ?  (runtime - sum) : 0_ticks;
index bf8e33b2ac2febc540da67081551476e7c0be1f4..f1392fa9c401d8269d851a73427709b5431d2343 100644 (file)
@@ -129,7 +129,7 @@ void ProfilerNode::accumulate(snort::ProfilerType type)
 }
 
 void ProfilerNode::reset(ProfilerType type)
-{ 
+{
     if ( is_set() )
     {
         auto* local_stats = (*getter)();
@@ -200,8 +200,10 @@ ProfilerNode& ProfilerNodeMap::get_node(const std::string& key)
 static ProfilerNode find_node(const ProfilerNodeMap& tree, const std::string& name)
 {
     for ( const auto& it : tree )
+    {
         if ( it.first == name )
             return it.second;
+    }
 
     return ProfilerNode("");
 }
@@ -217,7 +219,6 @@ public:
 
     ProfileStats* get_stats() { return stats; }
     void set_stats(ProfileStats* ps) { stats = ps; }
-    bool get_multi() { return multi; }
     void set_multi(bool b) { multi = b; }
 
     ProfileStats* get_profile() const override
index 5d84ee1c0171554c90827ef90e2fd3c0b735bebc..a28e84028025a59d05af7ac6c732998971ee431b 100644 (file)
@@ -646,10 +646,10 @@ TEST_CASE( "rule pause", "[profiler][rule_profiler]" )
 
     {
         RulePause pause(ctx);
-        CHECK_FALSE( ctx.active() );
+        CHECK( false == ctx.active() );
     }
 
-    CHECK( ctx.active() );
+    CHECK( true == ctx.active() );
     RuleContext::set_enabled(false);
 }
 
index b4c2c1dc8f2e1162e54ebdc0296c7a6f3c0c10b1..207faf59957f04ed572813e4fe39ad6fcdfb2dc0 100644 (file)
@@ -495,7 +495,7 @@ TEST_CASE( "time profiler time context disabled", "[profiler][time_profiler]" )
     {
         {
             TimeContext ctx(stats);
-            CHECK( ctx.active() );
+            CHECK( true == ctx.active() );
             CHECK( stats.ref_count == 0 );
         }
 
@@ -506,10 +506,10 @@ TEST_CASE( "time profiler time context disabled", "[profiler][time_profiler]" )
     {
         {
             TimeContext ctx(stats);
-            CHECK( ctx.active() );
+            CHECK( true == ctx.active() );
             CHECK( stats.ref_count == 0 );
             ctx.stop();
-            CHECK( ctx.active() );
+            CHECK( true == ctx.active() );
             CHECK( stats.ref_count == 0 );
         }
 
@@ -556,7 +556,7 @@ TEST_CASE( "time profiler time context", "[profiler][time_profiler]" )
     {
         {
             TimeContext ctx(stats);
-            CHECK( ctx.active() );
+            CHECK( true == ctx.active() );
             CHECK( stats.ref_count == 1 );
         }
 
@@ -567,10 +567,10 @@ TEST_CASE( "time profiler time context", "[profiler][time_profiler]" )
     {
         {
             TimeContext ctx(stats);
-            CHECK( ctx.active() );
+            CHECK( true == ctx.active() );
             CHECK( stats.ref_count == 1 );
             ctx.stop();
-            CHECK_FALSE( ctx.active() );
+            CHECK( false == ctx.active() );
             CHECK( stats.ref_count == 0 );
         }
 
index a391f793d2148b9ad009d4f6020b742ee6929033..94c31fb597dcba3f413718c817eb8b9b05d4ab9d 100644 (file)
@@ -265,57 +265,6 @@ uint16_t IpApi::pay_len() const
     return 0;
 }
 
-static inline bool is_loopback(uint32_t addr)
-{ return (addr >> 24) == 0x7F; }
-
-static bool is_loopback(const snort_in6_addr* const ip)
-{
-    const uint32_t* p = ip->u6_addr32;
-
-    /* Check the first 64 bits in an IPv6 address, and
-       verify they're zero.  If not, it's not a loopback */
-    if (p[0] || p[1])
-        return false;
-
-    /* Check if the 3rd 32-bit int is zero */
-    if ( p[2] == 0 )
-    {
-        /* ::7F00:0/104 is ipv4 compatible ipv6 */
-        /* ::1 is the IPv6 loopback */
-        return ( (ip->u6_addr8[12] == 0x7F) || (ntohl(p[3]) == 0x1) );
-    }
-
-    /* Check the 3rd 32-bit int for a mapped IPv4 address */
-    if ( ntohl(p[2]) == 0xffff )
-    {
-        /* ::ffff:127.0.0.0/104 is IPv4 loopback mapped over IPv6 */
-        return ( ip->u6_addr8[12] == 0x7F );
-    }
-    return false;
-}
-
-bool IpApi::is_src_loopback() const
-{
-    switch ( type )
-    {
-    case IAT_4: return is_loopback(ntohl(((const IP4Hdr*)iph)->get_src()));
-    case IAT_6: return is_loopback(((const IP6Hdr*)iph)->get_src());
-    default: break;
-    }
-    return false;
-}
-
-// true if the current source address ia the loopback address
-bool IpApi::is_dst_loopback() const
-{
-    switch ( type )
-    {
-    case IAT_4: return ((ntohl(((const IP4Hdr*)iph)->get_dst())) >> 24) == 0x7F;
-    case IAT_6: return is_loopback(((const IP6Hdr*)iph)->get_dst());
-    default: break;
-    }
-    return false;
-}
 } // namespace ip
 } // namespace snort
 
index ad1757897cb332c3c3fa73dc4bee45dac492d96a..0221558dd18c5e36a94f00b07131e9ccfbd83f32 100644 (file)
@@ -70,10 +70,6 @@ public:
     uint16_t pay_len() const;
     // return the ip_len field in host byte order
     uint16_t actual_ip_len() const;
-    // true if the current source address ia the loopback address
-    bool is_src_loopback() const;
-    // true if the current source address ia the loopback address
-    bool is_dst_loopback() const;
 
     // overloaded == operators.
     friend bool operator==(const IpApi& lhs, const IpApi& rhs);
@@ -126,10 +122,10 @@ public:
     uint8_t ver() const;
 
 private:
-    SfIp src;
-    SfIp dst;
-    const void* iph;
-    Type type;
+    SfIp src = {};
+    SfIp dst = {};
+    const void* iph = nullptr;
+    Type type = IAT_NONE;
 };
 
 } // namespace ip
index 9804eb64f8cefe3440d6354fd3ba956bd99f3a2a..cdc281ba6d568e81bc77c57bae2a27c2b5b0badf 100644 (file)
@@ -99,12 +99,6 @@ static inline const Layer* find_layer(const Layer* lyr,
 void set_packet_pointer(const Packet* const p)
 { curr_pkt = p; }
 
-const uint8_t* get_inner_layer(const Packet* p, ProtocolId prot_id)
-{ return find_inner_layer(p->layers, p->num_layers, prot_id); }
-
-const uint8_t* get_outer_layer(const Packet* p, ProtocolId prot_id)
-{ return find_outer_layer(p->layers, p->num_layers, prot_id); }
-
 const arp::EtherARP* get_arp_layer(const Packet* const p)
 {
     uint8_t num_layers = p->num_layers;
@@ -141,15 +135,6 @@ const gre::GREHdr* get_gre_layer(const Packet* const p)
         find_inner_layer(lyr, num_layers, ProtocolId::GRE));
 }
 
-const eapol::EtherEapol* get_eapol_layer(const Packet* const p)
-{
-    uint8_t num_layers = p->num_layers;
-    const Layer* lyr = p->layers;
-
-    return reinterpret_cast<const eapol::EtherEapol*>(
-        find_inner_layer(lyr, num_layers, ProtocolId::ETHERTYPE_EAPOL));
-}
-
 const Layer* get_mpls_layer(const Packet* const p)
 {
     uint8_t num_layers = p->num_layers;
index 7ad3d009b1fadd981fca8da370ea087c8a25c40c..28653e26c356faa17aaf181a0c7c5db14a90e972 100644 (file)
@@ -105,12 +105,8 @@ void set_packet_pointer(const Packet* const);
 
 SO_PUBLIC const uint8_t* get_root_layer(const Packet* const);
 
-SO_PUBLIC const uint8_t* get_inner_layer(const Packet*, ProtocolId proto);
-SO_PUBLIC const uint8_t* get_outer_layer(const Packet*, ProtocolId proto);
-
 SO_PUBLIC const arp::EtherARP* get_arp_layer(const Packet*);
 SO_PUBLIC const cisco_meta_data::CiscoMetaDataHdr* get_cisco_meta_data_layer(const Packet* const);
-SO_PUBLIC const eapol::EtherEapol* get_eapol_layer(const Packet*);
 SO_PUBLIC const eth::EtherHdr* get_eth_layer(const Packet*);
 SO_PUBLIC const geneve::GeneveLyr* get_geneve_layer(const Packet*, bool inner);
 SO_PUBLIC const gre::GREHdr* get_gre_layer(const Packet*);
index bf090eebc8262ca4e00f7b1a408fe8817fb0a115..1f9037f5ed04ce82ba9595e5816e9dac0ab4330f 100644 (file)
@@ -52,10 +52,7 @@ Packet::Packet(bool packet_data)
         pkt = new uint8_t[Codec::PKT_MAX];
     }
 
-    obfuscator = nullptr;
-    endianness = nullptr;
     active_inst = new Active();
-    action_inst = nullptr;
     reset();
 }
 
index 38d3e2b5eefd478747cb87039188d8f9edca5a69..66bb3e9446eaae3a5e0b93e1f63638ca67565f66 100644 (file)
@@ -120,8 +120,8 @@ struct SO_PUBLIC Packet
     Packet& operator=(const Packet&) = delete;
 
     Flow* flow;   /* for session tracking */
-    Endianness* endianness;
-    Obfuscator* obfuscator;
+    Endianness* endianness = nullptr;
+    Obfuscator* obfuscator = nullptr;
 
     uint32_t packet_flags;      /* special flags for the packet */
     uint32_t xtradata_mask;
@@ -137,28 +137,28 @@ struct SO_PUBLIC Packet
     PduSection sect;
 
     // nothing after this point is zeroed by reset() ...
-    IpsContext* context;
-    Active* active;
+    IpsContext* context = nullptr;
+    Active* active = nullptr;
     Active* active_inst;
-    ActiveAction** action;
-    ActiveAction* action_inst;
+    ActiveAction** action = nullptr;
+    ActiveAction* action_inst = nullptr;
 
     DAQ_Msg_h daq_msg;              // DAQ message this packet came from
-    SFDAQInstance* daq_instance;    // DAQ instance the message came from
+    SFDAQInstance* daq_instance = nullptr;  // DAQ instance the message came from
 
     // Everything beyond this point is set by PacketManager::decode()
     const DAQ_PktHdr_t* pkth;   // packet meta data
     const uint8_t* pkt;         // raw packet data
-    uint32_t pktlen;            // raw packet data length
+    uint32_t pktlen = 0;        // raw packet data length
 
     // These are both set before PacketManager::decode() returns
-    const uint8_t* data;        /* packet payload pointer */
-    uint16_t dsize;             /* packet payload size */
+    const uint8_t* data = nullptr;  /* packet payload pointer */
+    uint16_t dsize = 0;             /* packet payload size */
 
     DecodeData ptrs; // convenience pointers used throughout Snort++
     Layer* layers;    /* decoded encapsulations */
 
-    PseudoPacketType pseudo_type;    // valid only when PKT_PSEUDO is set
+    PseudoPacketType pseudo_type = PSEUDO_PKT_MAX;  // valid only when PKT_PSEUDO is set
 
     uint64_t user_inspection_policy_id;
     uint64_t user_ips_policy_id;
index 9a4a0b466e9e7cc2fe38050c9477ee32845bde70..4644b60faf54cb7f6f4c672ccb7f41a8104012c0 100644 (file)
@@ -69,7 +69,7 @@ enum AppidChangeBit
 
 typedef std::bitset<APPID_MAX_BIT> AppidChangeBits;
 
-inline void change_bits_to_string(AppidChangeBits& change_bits, std::string& str)
+inline void change_bits_to_string(const AppidChangeBits& change_bits, std::string& str)
 {
     size_t n = change_bits.count();
 
index b1a18ba1270423455b8acd35e5f93d45f80cdf26..d127a822ae628337c17cebe744c22ba116a97635 100644 (file)
@@ -70,7 +70,7 @@ public:
         return alpn;
     }
 
-    void set_alpn(std::vector<std::string>& alpn_vec)
+    void set_alpn(const std::vector<std::string>& alpn_vec)
     {
         if(alpn_vec.size())
             alpn = alpn_vec;
index 394a3ba5f91d17bb732a5709376805709d92332e..28ed62ddfa2219851a79f1733d9e64788c9dd943 100644 (file)
 using namespace snort;
 using namespace std;
 
-SipEvent::SipEvent(const Packet* p, const SIPMsg* msg, const SIP_DialogData* dialog)
-{
-    this->p = p;
-    this->msg = msg;
-    this->dialog = dialog;
-
-    from_len = msg->fromLen;
-    from = msg->from;
-    user_name_len = msg->userNameLen;
-    user_name = msg->userName;
-    user_agent_len = msg->userAgentLen;
-    user_agent = msg->userAgent;
-    server_len = msg->serverLen;
-    server = msg->server;
-}
+SipEvent::SipEvent(const Packet* p, const SIPMsg& msg, const SIP_DialogData* dialog) :
+    p(p),
+    msg(msg),
+    dialog(dialog),
+    from(msg.from),
+    from_len(msg.fromLen),
+    user_name(msg.userName),
+    user_name_len(msg.userNameLen),
+    user_agent(msg.userAgent),
+    user_agent_len(msg.userAgentLen),
+    server(msg.server),
+    server_len(msg.serverLen)
+{ }
 
 SipEvent::~SipEvent()
 {
@@ -51,10 +49,10 @@ SipEvent::~SipEvent()
 }
 
 bool SipEvent::is_invite() const
-{ return msg->methodFlag == SIP_METHOD_INVITE; }
+{ return msg.methodFlag == SIP_METHOD_INVITE; }
 
 bool SipEvent::is_media_updated() const
-{ return msg->mediaUpdated; }
+{ return msg.mediaUpdated; }
 
 bool SipEvent::has_dialog() const
 { return dialog; }
index 9f68721962475b4d3fd0d472fdc12e1d9e6ee3fe..bcff19e585b61e114d221bde17a633c15d591628 100644 (file)
@@ -77,7 +77,7 @@ private:
 class SipEvent : public snort::DataEvent
 {
 public:
-    SipEvent(const snort::Packet*, const SIPMsg*, const SIP_DialogData*);
+    SipEvent(const snort::Packet*, const SIPMsg&, const SIP_DialogData*);
     ~SipEvent() override;
 
     const snort::Packet* get_packet() const override
@@ -118,7 +118,7 @@ public:
 private:
     const snort::Packet* p;
 
-    const SIPMsg* msg;
+    const SIPMsg& msg;
     const SIP_DialogData* dialog;
 
     const char* from = nullptr;
index 18a5c79c3cba3ba154da0b7c5ff96311cfce0edb..70b437ae085c76032bb8557c9ac2cc9a7b456e96 100644 (file)
 
 using namespace snort;
 
-Packet::Packet(bool) { }
+Packet::Packet(bool)
+    : flow(nullptr), packet_flags(0), xtradata_mask(0), proto_bits(0), alt_dsize(0), num_layers(0),
+    disable_inspect(true), sect(PS_NONE), active_inst(nullptr), pkth(nullptr), pkt(nullptr), layers(nullptr),
+    user_inspection_policy_id(0), user_ips_policy_id(0), user_network_policy_id(0), vlan_idx(0),
+    ts_packet_flags(0), allocated(false)
+{ }
 Packet::~Packet() = default;
 
 TEST_GROUP(pub_sub_eve_process_event_test)
index 0f8b757ff9632be3ac81c7ebcbf8ad9a73a1e2de..c80036eb768c503208cdfbeecffd890801460d3b 100644 (file)
@@ -77,8 +77,13 @@ HttpMsgSection::HttpMsgSection(const uint8_t* buffer, const uint16_t buf_size,
     source_id(source_id_),
     version_id(VERS__NOT_PRESENT),
     method_id(METH__NOT_PRESENT),
-    tcp_close(false)
-{}
+    tcp_close(false),
+    request(nullptr),
+    status(nullptr)
+{
+    memset(header, 0, sizeof(header));
+    memset(trailer, 0, sizeof(trailer));
+}
 void HttpMsgSection::update_depth() const{}
 bool HttpMsgSection::run_detection(snort::Packet*) { return true; }
 
index adad86835452ac40bf38eed5b613d235e82a4ae6..3e9283d6d6edf75f66dea030060b0d17ab086254 100644 (file)
@@ -970,10 +970,6 @@ int acsmCompile2(SnortConfig* sc, ACSM_STRUCT2* acsm)
     return 0;
 }
 
-void acsmx2_print_qinfo()
-{
-}
-
 /*
 *   Full format DFA search
 *   Do not change anything here without testing, caching and prefetching
index 5fd06b3a8263d27e29a6c498ce765466a7589027..8cff908e4c7d72140f4b1d6f3b091bc696455014 100644 (file)
@@ -140,7 +140,6 @@ void acsmPrintInfo2(ACSM_STRUCT2* p);
 
 int acsmPrintDetailInfo2(ACSM_STRUCT2*);
 int acsmPrintSummaryInfo2();
-void acsmx2_print_qinfo();
 void acsm_init_summary();
 
 #endif
index cf6d5595ba0065a0223d87821532123877d0dadd..3a0cffa96ab3c3c837f6f037d04521dd2e0aa4cd 100644 (file)
@@ -1200,16 +1200,6 @@ bnfa_struct_t* bnfaNew(const MpseAgent* agent)
     return p;
 }
 
-void bnfaSetCase(bnfa_struct_t* p, int flag)
-{
-    if ( flag == BNFA_PER_PAT_CASE )
-        p->bnfaCaseMode = flag;
-    if ( flag == BNFA_CASE    )
-        p->bnfaCaseMode = flag;
-    if ( flag == BNFA_NOCASE  )
-        p->bnfaCaseMode = flag;
-}
-
 /*
 *   Fee all memory
 */
index 1a6a852a003037ad5c9c34d5645dd0e45b87498a..c7eddf3e86a6e7ed835593690ba0393820ac8c0c 100644 (file)
@@ -160,7 +160,6 @@ void bnfa_init_xlatcase();
 
 bnfa_struct_t* bnfaNew(const MpseAgent*);
 
-void bnfaSetCase(bnfa_struct_t* p, int flag);
 void bnfaFree(bnfa_struct_t* pstruct);
 
 int bnfaAddPattern(
index e6f14a4f41ce4a29680cd5b313e21433d5f986da..00976d628e0ef6324525fc98156afe7031cca0b3 100644 (file)
@@ -328,7 +328,7 @@ void HyperscanMpse::get_hash(std::string& hash)
 
     std::stringstream ss;
 
-    for ( auto& p : pvector )
+    for ( const auto& p : pvector )
         ss << p.pat << p.flags;
 
     std::string str = ss.str();
index 1316b6647d10469a074e831768b1e925f886b52c..d40751fa3aeb3bd2ce91b2b334129e244fee1b14 100644 (file)
@@ -57,12 +57,12 @@ const MpseApi* get_test_api()
 TEST_GROUP(search_tool_full)
 {
     Module* mod = nullptr;
-    SearchTool* stool;
+    SearchTool* stool;  // cppcheck-suppress variableScope
     const MpseApi* mpse_api = (const MpseApi*)se_hyperscan;
 
     void setup() override
     {
-        mod = mpse_api->base.mod_ctor();
+        mod = mpse_api->base.mod_ctor();    // cppcheck-suppress unreadVariable
         stool = new SearchTool;
         CHECK(stool->mpsegrp->normal_mpse);
 
index 21e753cbefdc89c3dc286832ef8a4322b1596786..35c33de1f5652f817a763c06c8022ddd2a28591b 100644 (file)
@@ -105,7 +105,7 @@ TEST_GROUP(mpse_hs_match)
     void setup() override
     {
         CHECK(se_hyperscan);
-        mod = mpse_api->base.mod_ctor();
+        mod = mpse_api->base.mod_ctor();    // cppcheck-suppress unreadVariable
         hs = mpse_api->ctor(snort_conf, nullptr, &s_agent);
         CHECK(hs);
         hits = 0;
@@ -252,7 +252,7 @@ TEST_GROUP(mpse_hs_multi)
     {
         CHECK(se_hyperscan);
 
-        mod = mpse_api->base.mod_ctor();
+        mod = mpse_api->base.mod_ctor();    // cppcheck-suppress unreadVariable
 
         hs1 = mpse_api->ctor(snort_conf, nullptr, &s_agent);
         CHECK(hs1);
@@ -312,7 +312,7 @@ TEST_GROUP(mpse_hs_scratch)
     void setup() override
     {
         CHECK(se_hyperscan);
-        mod = mpse_api->base.mod_ctor();
+        mod = mpse_api->base.mod_ctor();    // cppcheck-suppress unreadVariable
         hs1 = mpse_api->ctor(snort_conf, nullptr, nullptr);
         hs2 = mpse_api->ctor(snort_conf, nullptr, nullptr);
         CHECK(hs1);
index 528087970fae46111356bc8229346438edb64332..a6b00657173062a233524f025b0118a3e182630a 100644 (file)
@@ -53,11 +53,9 @@ const SnortConfig* SnortConfig::get_conf()
 { return snort_conf; }
 
 SnortConfig::SnortConfig(const SnortConfig* const, const char*)
-{
-    state = &s_state;
-    num_slots = 1;
-    fast_pattern_config = new FastPatternConfig();
-}
+    : daq_config(nullptr), fast_pattern_config(new FastPatternConfig()), state(&s_state), num_slots(1),
+    thread_config(nullptr)
+{ }
 
 SnortConfig::~SnortConfig() = default;
 
@@ -104,7 +102,7 @@ void md5(const unsigned char*, size_t, unsigned char*) { }
 FastPatternConfig::FastPatternConfig()
 { search_api = get_test_api(); }
 
-const char* FastPatternConfig::get_search_method()
+const char* FastPatternConfig::get_search_method() const
 { return search_api ? search_api->base.name : nullptr; }
 
 using namespace snort;
index e5986f8148a7a35c28d41e3f5363796b0a2fe6f3..e455167c46e786f9c907e972dfb6ea317e399bba 100644 (file)
@@ -56,7 +56,7 @@ const MpseApi* get_test_api()
 
 TEST_GROUP(search_tool_full)
 {
-    SearchTool* stool;
+    SearchTool* stool;  // cppcheck-suppress variableScope
 
     void setup() override
     {
index 8b6ad79b984ab510c660bbec86a563476b38a613..a94a7922fdd9770d592eae51a9a7523949250b52 100644 (file)
@@ -317,12 +317,6 @@ static void PrecalcPrefix()
  */
 static int BoGetDirection(Packet* p, const char* pkt_data)
 {
-    uint32_t len = 0;
-    uint32_t id = 0;
-    uint32_t l, i;
-    char type;
-    char plaintext;
-
     /* Check for the default port on either side */
     if ( p->ptrs.dp == BO_DEFAULT_PORT )
     {
@@ -335,23 +329,19 @@ static int BoGetDirection(Packet* p, const char* pkt_data)
 
     /* Didn't find default port, so look for ping packet */
 
+    uint32_t len = 0;
+
     /* Get length from BO header - 32 bit int */
-    for ( i = 0; i < 4; i++ )
+    for ( uint32_t i = 0; i < 4; i++ )
     {
-        plaintext = (char)(*pkt_data ^ BoRand());
-        l = (uint32_t)plaintext;
+        char plaintext = (char)(*pkt_data ^ BoRand());
+        uint32_t l = (uint32_t)plaintext;
         len += l << (8*i);
         pkt_data++;
     }
 
     /* Get ID from BO header - 32 bit int */
-    for ( i = 0; i < 4; i++ )
-    {
-        plaintext = (char)(*pkt_data ^ BoRand() );
-        l = ((uint32_t)plaintext) & 0x000000FF;
-        id += l << (8*i);
-        pkt_data++;
-    }
+    pkt_data += 4;
 
     /* Do more len checking */
 
@@ -378,7 +368,7 @@ static int BoGetDirection(Packet* p, const char* pkt_data)
     }
 
     /* Continue parsing BO header */
-    type = (char)(*pkt_data ^ BoRand());
+    char type = (char)(*pkt_data ^ BoRand());
     pkt_data++;
 
     /* check to make sure we don't run off end of packet */
@@ -400,7 +390,7 @@ static int BoGetDirection(Packet* p, const char* pkt_data)
         }
         char buf1[BO_BUF_SIZE];
 
-        for (i=0; i<len; i++ ) /* start at 0 to advance the BoRand() function properly */
+        for (uint32_t i=0; i<len; i++ ) /* start at 0 to advance the BoRand() function properly */
         {
             buf1[i] = (char)(pkt_data[i] ^ BoRand());
 
@@ -438,6 +428,7 @@ public:
 
 void BackOrifice::eval(Packet* p)
 {
+    // cppcheck-suppress unreadVariable
     Profile profile(boPerfStats);
 
     const char* const magic_cookie = "*!*QWTY?";
index fcccbc7154f6fd3c8df920a34744391345b4c3c1..65a5fc94472411701a47f3e9d68146ed2626bef6 100644 (file)
@@ -127,7 +127,7 @@ static CipPacketDirection get_packet_direction(Packet* p)
 
 static void publish_data_to_appId(Packet* packet, CipCurrentData& current_data)
 {
-    CipEventData cip_event_data;
+    CipEventData cip_event_data = {};
     CipEvent cip_event(packet, &cip_event_data);
 
     bool publish_appid = true;
@@ -224,6 +224,7 @@ static void cip_current_data_process(CipSessionData* css, CipCurrentData& curren
 
 static void snort_cip(CipProtoConf* config, Packet* p)
 {
+    // cppcheck-suppress unreadVariable
     Profile profile(cip_perf_stats);
 
     if (p->has_tcp_data() && !p->is_full_pdu())
index 12b55dc43d27d50fec7843886c277d7585b3fa8d..4bdf0652a1f3ad68abfa4938451c5930d2951713 100644 (file)
@@ -89,6 +89,7 @@ static void prune_cip_unconnected_list(CipUnconnectedMessageList* unconnected_li
     {
         if (unconnected_list->list[i].slot_active)
         {
+            // cppcheck-suppress unreadVariable
             TIMERSUB(timestamp, &unconnected_list->list[i].timestamp, &timestamp_diff);
 
             // Round up to the nearest whole second.
@@ -139,7 +140,9 @@ static void prune_cip_connection_list(CipConnectionList* connection_list,
     {
         if (connection_list->list[i].slot_active)
         {
+            // cppcheck-suppress unreadVariable
             TIMERSUB(timestamp, &connection_list->list[i].ot_timestamp, &ot_timestamp_diff);
+            // cppcheck-suppress unreadVariable
             TIMERSUB(timestamp, &connection_list->list[i].to_timestamp, &to_timestamp_diff);
 
             // If either OT or TO connection timeouts have been exceeded, remove the connection
@@ -519,8 +522,3 @@ bool cip_request_remove(CipUnconnectedMessageList* unconnected_list,
     return valid;
 }
 
-void set_unconnected_timeout(uint32_t unconnected_timeout)
-{
-    f_unconnected_timeout_ms = unconnected_timeout;
-}
-
index 431dd0e5d56b624bbfdbeacd3f1d985707afb059..1e4c42251cd5e9017a56aeb1f2854198c88657c3 100644 (file)
@@ -68,8 +68,5 @@ bool cip_request_remove(CipUnconnectedMessageList* unconnected_list,
     const EnipSessionData* enip_data,
     CipRequestType* request_type);
 
-// Set timeout (milliseconds) to use for unconnected messages that don't have a built-in timeout.
-void set_unconnected_timeout(uint32_t unconnected_timeout);
-
 #endif  // CIP_SESSION_H
 
index a82e694bb3bff5f4b4b7008e84412dfe71f20dbd..c6911036c987984c16fe1d668c44221b18a33e3c 100644 (file)
@@ -49,8 +49,8 @@ static THREAD_LOCAL ProfileStats cip_attribute_perf_stats;
 class CipAttributeOption : public IpsOption
 {
 public:
-    CipAttributeOption(const RangeCheck& v) : IpsOption(s_name)
-    { cip_attr = v; }
+    CipAttributeOption(const RangeCheck& v) : IpsOption(s_name), cip_attr(v)
+    { }
 
     uint32_t hash() const override;
     bool operator==(const IpsOption&) const override;
@@ -82,6 +82,7 @@ bool CipAttributeOption::operator==(const IpsOption& ips) const
 
 IpsOption::EvalStatus CipAttributeOption::eval(Cursor&, Packet* p)
 {
+    // cppcheck-suppress unreadVariable
     Profile profile(cip_attribute_perf_stats);
 
     if ( !p->flow || !p->is_full_pdu() )
index d8b38d0fedfc2f090f941a9197063e12cc2c0876..3898cb96586a9a20ba7a3555600c4a5ee6867432 100644 (file)
@@ -49,8 +49,8 @@ static THREAD_LOCAL ProfileStats cip_class_perf_stats;
 class CipClassOption : public IpsOption
 {
 public:
-    CipClassOption(const RangeCheck& v) : IpsOption(s_name)
-    { cip_class = v; }
+    CipClassOption(const RangeCheck& v) : IpsOption(s_name), cip_class(v)
+    { }
 
     uint32_t hash() const override;
     bool operator==(const IpsOption&) const override;
@@ -83,6 +83,7 @@ bool CipClassOption::operator==(const IpsOption& ips) const
 
 IpsOption::EvalStatus CipClassOption::eval(Cursor&, Packet* p)
 {
+    // cppcheck-suppress unreadVariable
     Profile profile(cip_class_perf_stats);
 
     if ( !p->flow || !p->is_full_pdu() )
index 2c0e17b2d9aa7b888ac2c064e08197c8f9f99d54..42efdaaee571d2b0621faa26b1fae49caa3eb4b8 100644 (file)
@@ -49,8 +49,8 @@ static THREAD_LOCAL ProfileStats cip_connpathclass_perf_stats;
 class CipConnpathclassOption : public IpsOption
 {
 public:
-    CipConnpathclassOption(const RangeCheck& v) : IpsOption(s_name)
-    { cip_cpc = v; }
+    CipConnpathclassOption(const RangeCheck& v) : IpsOption(s_name), cip_cpc(v)
+    { }
 
     uint32_t hash() const override;
     bool operator==(const IpsOption&) const override;
@@ -82,6 +82,7 @@ bool CipConnpathclassOption::operator==(const IpsOption& ips) const
 
 IpsOption::EvalStatus CipConnpathclassOption::eval(Cursor&, Packet* p)
 {
+    // cppcheck-suppress unreadVariable
     Profile profile(cip_connpathclass_perf_stats);
 
     if ( !p->flow || !p->is_full_pdu() )
index eb4c5eba177aa60e08f09e8aec9d0e0784547942..9694425f527fb8597778828ebbc369579a2b5a21 100644 (file)
@@ -49,8 +49,8 @@ static THREAD_LOCAL ProfileStats cip_enipcommand_perf_stats;
 class CipEnipCommandOption : public IpsOption
 {
 public:
-    CipEnipCommandOption(const RangeCheck& v) : IpsOption(s_name)
-    { cip_enip_cmd = v; }
+    CipEnipCommandOption(const RangeCheck& v) : IpsOption(s_name), cip_enip_cmd(v)
+    { }
 
     uint32_t hash() const override;
     bool operator==(const IpsOption&) const override;
@@ -82,6 +82,7 @@ bool CipEnipCommandOption::operator==(const IpsOption& ips) const
 
 IpsOption::EvalStatus CipEnipCommandOption::eval(Cursor&, Packet* p)
 {
+    // cppcheck-suppress unreadVariable
     Profile profile(cip_enipcommand_perf_stats);
 
     if ( !p->flow || !p->is_full_pdu() )
index 2d33f98323cc4801797da2933e03ac8451501e0a..60b7b2afccc80fde1bae50a4b40c3aaf1a67db4c 100644 (file)
@@ -73,6 +73,7 @@ bool CipEnipreqOption::operator==(const IpsOption& ips) const
 
 IpsOption::EvalStatus CipEnipreqOption::eval(Cursor&, Packet* p)
 {
+    // cppcheck-suppress unreadVariable
     Profile profile(cip_enipreq_perf_stats);
 
     if ( !p->flow || !p->is_full_pdu() )
index 4aa172c7c1fecfe747d3b7279f84959ab51928b9..642ccfb916af518e2b9857513db1d27db546154f 100644 (file)
@@ -73,6 +73,7 @@ bool CipEnipRspOption::operator==(const IpsOption& ips) const
 
 IpsOption::EvalStatus CipEnipRspOption::eval(Cursor&, Packet* p)
 {
+    // cppcheck-suppress unreadVariable
     Profile profile(cip_eniprsp_perf_stats);
 
     if ( !p->flow || !p->is_full_pdu() )
index 13179a921b720df0c8d24de5bb75e5d552c1dc31..58119252678c3423074cf2a7de1e83bbdd5b1988 100644 (file)
@@ -49,8 +49,8 @@ static THREAD_LOCAL ProfileStats cip_instance_perf_stats;
 class CipInstanceOption : public IpsOption
 {
 public:
-    CipInstanceOption(const RangeCheck& v) : IpsOption(s_name)
-    { cip_inst = v; }
+    CipInstanceOption(const RangeCheck& v) : IpsOption(s_name), cip_inst(v)
+    { }
 
     uint32_t hash() const override;
     bool operator==(const IpsOption&) const override;
@@ -82,6 +82,7 @@ bool CipInstanceOption::operator==(const IpsOption& ips) const
 
 IpsOption::EvalStatus CipInstanceOption::eval(Cursor&, Packet* p)
 {
+    // cppcheck-suppress unreadVariable
     Profile profile(cip_instance_perf_stats);
 
     if ( !p->flow || !p->is_full_pdu() )
index ec7ea8bbe0d8121e09749d85bc1351bacfa8215e..d7207d0b3969842351444dd1d367ae53a4b8ccf4 100644 (file)
@@ -73,6 +73,7 @@ bool CipReqOption::operator==(const IpsOption& ips) const
 
 IpsOption::EvalStatus CipReqOption::eval(Cursor&, Packet* p)
 {
+    // cppcheck-suppress unreadVariable
     Profile profile(cip_req_perf_stats);
 
     if ( !p->flow || !p->is_full_pdu() )
index c6437f71e438bb01b89278990c3b2811be4aa803..18ea67b8ecb81169a78b6be67cf447e81a149898 100644 (file)
@@ -73,6 +73,7 @@ bool CipRspOption::operator==(const IpsOption& ips) const
 
 IpsOption::EvalStatus CipRspOption::eval(Cursor&, Packet* p)
 {
+    // cppcheck-suppress unreadVariable
     Profile profile(cip_rsp_perf_stats);
 
     if ( !p->flow || !p->is_full_pdu() )
index 12c63e6736e2cbbe957741c4196144e119db24ba..9f51681633eabf4a92e8e10d9ff0f38dd651eec2 100644 (file)
@@ -49,8 +49,8 @@ static THREAD_LOCAL ProfileStats cip_service_perf_stats;
 class CipServiceOption : public IpsOption
 {
 public:
-    CipServiceOption(const RangeCheck& v) : IpsOption(s_name)
-    { cip_serv = v; }
+    CipServiceOption(const RangeCheck& v) : IpsOption(s_name), cip_serv(v)
+    { }
 
     uint32_t hash() const override;
     bool operator==(const IpsOption&) const override;
@@ -82,6 +82,7 @@ bool CipServiceOption::operator==(const IpsOption& ips) const
 
 IpsOption::EvalStatus CipServiceOption::eval(Cursor&, Packet* p)
 {
+    // cppcheck-suppress unreadVariable
     Profile profile(cip_service_perf_stats);
 
     if ( !p->flow || !p->is_full_pdu() )
index ca9f06d3c01042854894266a352192d58797e98d..a10efb6db22c9b26bcfdabf44f2f9d4940ac2000 100644 (file)
@@ -49,8 +49,8 @@ static THREAD_LOCAL ProfileStats cip_status_perf_stats;
 class CipStatusOption : public IpsOption
 {
 public:
-    CipStatusOption(const RangeCheck& v) : IpsOption(s_name)
-    { cip_status = v; }
+    CipStatusOption(const RangeCheck& v) : IpsOption(s_name), cip_status(v)
+    { }
 
     uint32_t hash() const override;
     bool operator==(const IpsOption&) const override;
@@ -82,6 +82,7 @@ bool CipStatusOption::operator==(const IpsOption& ips) const
 
 IpsOption::EvalStatus CipStatusOption::eval(Cursor&, Packet* p)
 {
+    // cppcheck-suppress unreadVariable
     Profile profile(cip_status_perf_stats);
 
     if ( !p->flow || !p->is_full_pdu() )
index 86222d7cc2a37402087dd8fb4ec511e9c2e4d2bb..b773af4cb512c32872a568cef4035aee7c6ea817 100644 (file)
@@ -179,10 +179,10 @@ TEST_CASE("DceHttpProxySplitter-scan - first_proxy_request", "[http_proxy_splitt
     DceHttpProxySplitter* splitter = new DceHttpProxySplitter(true);
     uint32_t fp;
 
-    REQUIRE(splitter->cutover_inspector() == false);
+    REQUIRE(false == splitter->cutover_inspector());
     REQUIRE(splitter->scan(nullptr, (const uint8_t*)"RPC", 3, PKT_FROM_CLIENT, &fp) ==
         StreamSplitter::SEARCH);
-    REQUIRE(splitter->cutover_inspector() == false);
+    REQUIRE(false == splitter->cutover_inspector());
     delete splitter;
 }
 
@@ -191,9 +191,9 @@ TEST_CASE("DceHttpProxySplitter-scan - first_proxy_request_no_direction", "[http
     DceHttpProxySplitter* splitter = new DceHttpProxySplitter(true);
     uint32_t fp;
 
-    REQUIRE(splitter->cutover_inspector() == false);
+    REQUIRE(false == splitter->cutover_inspector());
     REQUIRE(splitter->scan(nullptr, (const uint8_t*)"RPC", 3, 0, &fp) == StreamSplitter::ABORT);
-    REQUIRE(splitter->cutover_inspector() == false);
+    REQUIRE(false == splitter->cutover_inspector());
     delete splitter;
 }
 
@@ -204,7 +204,7 @@ TEST_CASE("DceHttpProxySplitter-scan - bad_first_proxy_request", "[http_proxy_sp
 
     REQUIRE(splitter->scan(nullptr, (const uint8_t*)"xxx", 1, PKT_FROM_CLIENT, &fp) ==
         StreamSplitter::ABORT);
-    REQUIRE(splitter->cutover_inspector() == false);
+    REQUIRE(false == splitter->cutover_inspector());
     delete splitter;
 }
 
@@ -215,10 +215,10 @@ TEST_CASE("DceHttpProxySplitter-scan - first_bad_second_proxy_request", "[http_p
 
     REQUIRE(splitter->scan(nullptr, (const uint8_t*)"RPC", 3, PKT_FROM_CLIENT, &fp) ==
         StreamSplitter::SEARCH);
-    REQUIRE(splitter->cutover_inspector() == false);
+    REQUIRE(false == splitter->cutover_inspector());
     REQUIRE(splitter->scan(nullptr, (const uint8_t*)"R", 1, PKT_FROM_CLIENT, &fp) ==
         StreamSplitter::ABORT);
-    REQUIRE(splitter->cutover_inspector() == false);
+    REQUIRE(false == splitter->cutover_inspector());
     delete splitter;
 }
 
@@ -231,7 +231,7 @@ TEST_CASE("DceHttpProxySplitter-scan - first_good_second_proxy_request", "[http_
         StreamSplitter::SEARCH);
     REQUIRE(splitter->scan(nullptr, (const uint8_t*)"_CON", 4, PKT_FROM_CLIENT, &fp) ==
         StreamSplitter::SEARCH);
-    REQUIRE(splitter->cutover_inspector() == false);
+    REQUIRE(false == splitter->cutover_inspector());
     delete splitter;
 }
 
@@ -245,7 +245,7 @@ TEST_CASE("DceHttpProxySplitter-scan - full_proxy_request", "[http_proxy_splitte
     REQUIRE(fp == strlen(HTTP_PROXY_REQUEST));
     REQUIRE(splitter->scan(nullptr, (const uint8_t*)"0", 1, PKT_FROM_CLIENT, &fp) ==
         StreamSplitter::FLUSH);
-    REQUIRE(splitter->cutover_inspector() == true);
+    REQUIRE(true == splitter->cutover_inspector());
     delete splitter;
 }
 
@@ -264,7 +264,7 @@ TEST_CASE("DceHttpProxySplitter-scan - extra_proxy_request", "[http_proxy_splitt
     REQUIRE(fp == strlen(HTTP_PROXY_REQUEST));
     REQUIRE(splitter->scan(nullptr, (const uint8_t*)"0", 1, PKT_FROM_CLIENT, &fp) ==
         StreamSplitter::FLUSH);
-    REQUIRE(splitter->cutover_inspector() == true);
+    REQUIRE(true == splitter->cutover_inspector());
     delete splitter;
     delete[] string;
 }
@@ -274,10 +274,10 @@ TEST_CASE("DceHttpProxySplitter-scan - first_proxy_response", "[http_proxy_split
     DceHttpProxySplitter* splitter = new DceHttpProxySplitter(false);
     uint32_t fp;
 
-    REQUIRE(splitter->cutover_inspector() == false);
+    REQUIRE(false == splitter->cutover_inspector());
     REQUIRE(splitter->scan(nullptr, (const uint8_t*)"xxx", 3, PKT_FROM_SERVER, &fp) ==
         StreamSplitter::ABORT);
-    REQUIRE(splitter->cutover_inspector() == false);
+    REQUIRE(false == splitter->cutover_inspector());
     delete splitter;
 }
 
@@ -286,11 +286,11 @@ TEST_CASE("DceHttpProxySplitter-scan - good_1_proxy_response", "[http_proxy_spli
     DceHttpProxySplitter* splitter = new DceHttpProxySplitter(false);
     uint32_t fp = 0;
 
-    REQUIRE(splitter->cutover_inspector() == false);
+    REQUIRE(false == splitter->cutover_inspector());
     REQUIRE(splitter->scan(nullptr, (const uint8_t*)"HTTP/1.xxx\n\n", 12,
         PKT_FROM_SERVER, &fp) == StreamSplitter::FLUSH);
     REQUIRE((fp == 12));
-    REQUIRE(splitter->cutover_inspector() == true);
+    REQUIRE(true == splitter->cutover_inspector());
     delete splitter;
 }
 
@@ -299,11 +299,11 @@ TEST_CASE("DceHttpProxySplitter-scan - good_2_proxy_response", "[http_proxy_spli
     DceHttpProxySplitter* splitter = new DceHttpProxySplitter(false);
     uint32_t fp = 0;
 
-    REQUIRE(splitter->cutover_inspector() == false);
+    REQUIRE(false == splitter->cutover_inspector());
     REQUIRE(splitter->scan(nullptr, (const uint8_t*)"HTTP/1.xxx\nxx\n\n", 15,
         PKT_FROM_SERVER, &fp) == StreamSplitter::FLUSH);
     REQUIRE((fp == 15));
-    REQUIRE(splitter->cutover_inspector() == true);
+    REQUIRE(true == splitter->cutover_inspector());
     delete splitter;
 }
 TEST_CASE("DceHttpProxySplitter-scan - good_3_proxy_response", "[http_proxy_splitter]")
@@ -311,11 +311,11 @@ TEST_CASE("DceHttpProxySplitter-scan - good_3_proxy_response", "[http_proxy_spli
     DceHttpProxySplitter* splitter = new DceHttpProxySplitter(false);
     uint32_t fp = 0;
 
-    REQUIRE(splitter->cutover_inspector() == false);
+    REQUIRE(false == splitter->cutover_inspector());
     REQUIRE(splitter->scan(nullptr, (const uint8_t*)"HTTP/1.xxx\nxx\n\nyyy", 18,
         PKT_FROM_SERVER, &fp) == StreamSplitter::FLUSH);
     REQUIRE((fp == 18));
-    REQUIRE(splitter->cutover_inspector() == true);
+    REQUIRE(true == splitter->cutover_inspector());
     delete splitter;
 }
 
@@ -324,10 +324,10 @@ TEST_CASE("DceHttpProxySplitter-scan - bad_1_proxy_response", "[http_proxy_split
     DceHttpProxySplitter* splitter = new DceHttpProxySplitter(false);
     uint32_t fp;
 
-    REQUIRE(splitter->cutover_inspector() == false);
+    REQUIRE(false == splitter->cutover_inspector());
     REQUIRE(splitter->scan(nullptr, (const uint8_t*)"HTTP/1.xxx\nx\n", 13, PKT_FROM_SERVER, &fp) ==
         StreamSplitter::SEARCH);
-    REQUIRE(splitter->cutover_inspector() == false);
+    REQUIRE(false == splitter->cutover_inspector());
     delete splitter;
 }
 
@@ -336,10 +336,10 @@ TEST_CASE("DceHttpProxySplitter-scan - bad_2_proxy_response", "[http_proxy_split
     DceHttpProxySplitter* splitter = new DceHttpProxySplitter(false);
     uint32_t fp;
 
-    REQUIRE(splitter->cutover_inspector() == false);
+    REQUIRE(false == splitter->cutover_inspector());
     REQUIRE(splitter->scan(nullptr, (const uint8_t*)"HTTP/1.xxx\nx", 12, PKT_FROM_SERVER, &fp) ==
         StreamSplitter::SEARCH);
-    REQUIRE(splitter->cutover_inspector() == false);
+    REQUIRE(false == splitter->cutover_inspector());
     delete splitter;
 }
 
@@ -348,10 +348,10 @@ TEST_CASE("DceHttpProxySplitter-scan - bad_3_proxy_response", "[http_proxy_split
     DceHttpProxySplitter* splitter = new DceHttpProxySplitter(false);
     uint32_t fp;
 
-    REQUIRE(splitter->cutover_inspector() == false);
+    REQUIRE(false == splitter->cutover_inspector());
     REQUIRE(splitter->scan(nullptr, (const uint8_t*)"HTTP/1.", 7, PKT_FROM_SERVER, &fp) ==
         StreamSplitter::SEARCH);
-    REQUIRE(splitter->cutover_inspector() == false);
+    REQUIRE(false == splitter->cutover_inspector());
     delete splitter;
 }
 
index 28736d7122becc698213a71a76a845a66674ad8b..aca7169f802a6fa08687d3e113c5d7050c7db5d7 100644 (file)
@@ -97,10 +97,10 @@ TEST_CASE("DceHttpServerSplitter-scan - first_server", "[http_server_splitter]")
     DceHttpServerSplitter* splitter = new DceHttpServerSplitter(false);
     uint32_t fp;
 
-    REQUIRE(splitter->cutover_inspector() == false);
+    REQUIRE(false == splitter->cutover_inspector());
     REQUIRE(splitter->scan(nullptr, (const uint8_t*)"n", 1, PKT_FROM_SERVER, &fp) ==
         StreamSplitter::SEARCH);
-    REQUIRE(splitter->cutover_inspector() == false);
+    REQUIRE(false == splitter->cutover_inspector());
     delete splitter;
 }
 
@@ -109,10 +109,10 @@ TEST_CASE("DceHttpServerSplitter-scan - first_server_wrong_direction", "[http_se
     DceHttpServerSplitter* splitter = new DceHttpServerSplitter(false);
     uint32_t fp;
 
-    REQUIRE(splitter->cutover_inspector() == false);
+    REQUIRE(false == splitter->cutover_inspector());
     REQUIRE(splitter->scan(nullptr, (const uint8_t*)"n", 1, PKT_FROM_CLIENT, &fp) ==
         StreamSplitter::ABORT);
-    REQUIRE(splitter->cutover_inspector() == false);
+    REQUIRE(false == splitter->cutover_inspector());
     delete splitter;
 }
 
@@ -123,7 +123,7 @@ TEST_CASE("DceHttpServerSplitter-scan - bad_first_server", "[http_server_splitte
 
     REQUIRE(splitter->scan(nullptr, (const uint8_t*)"x", 1, PKT_FROM_SERVER, &fp) ==
         StreamSplitter::ABORT);
-    REQUIRE(splitter->cutover_inspector() == false);
+    REQUIRE(false == splitter->cutover_inspector());
     delete splitter;
 }
 
@@ -134,10 +134,10 @@ TEST_CASE("DceHttpServerSplitter-scan - first_bad_second_server", "[http_server_
 
     REQUIRE(splitter->scan(nullptr, (const uint8_t*)"n", 1, PKT_FROM_SERVER, &fp) ==
         StreamSplitter::SEARCH);
-    REQUIRE(splitter->cutover_inspector() == false);
+    REQUIRE(false == splitter->cutover_inspector());
     REQUIRE(splitter->scan(nullptr, (const uint8_t*)"n", 1, PKT_FROM_SERVER, &fp) ==
         StreamSplitter::ABORT);
-    REQUIRE(splitter->cutover_inspector() == false);
+    REQUIRE(false == splitter->cutover_inspector());
     delete splitter;
 }
 
@@ -150,7 +150,7 @@ TEST_CASE("DceHttpServerSplitter-scan - first_good_second_server", "[http_server
         StreamSplitter::SEARCH);
     REQUIRE(splitter->scan(nullptr, (const uint8_t*)"c", 1, PKT_FROM_SERVER, &fp) ==
         StreamSplitter::SEARCH);
-    REQUIRE(splitter->cutover_inspector() == false);
+    REQUIRE(false == splitter->cutover_inspector());
     delete splitter;
 }
 
@@ -162,7 +162,7 @@ TEST_CASE("DceHttpServerSplitter-scan - full_server", "[http_server_splitter]")
     REQUIRE(splitter->scan(nullptr, (const uint8_t*)HTTP_SERVER_MARKER,
         strlen(HTTP_SERVER_MARKER), PKT_FROM_SERVER, &fp) == StreamSplitter::FLUSH);
     REQUIRE(fp == strlen(HTTP_SERVER_MARKER));
-    REQUIRE(splitter->cutover_inspector() == true);
+    REQUIRE(true == splitter->cutover_inspector());
     delete splitter;
 }
 
@@ -175,7 +175,7 @@ TEST_CASE("DceHttpServerSplitter-scan - extra_server", "[http_server_splitter]")
     REQUIRE(splitter->scan(nullptr, (const uint8_t*)string,
         strlen(string), PKT_FROM_SERVER, &fp) == StreamSplitter::FLUSH);
     REQUIRE(fp == strlen(HTTP_SERVER_MARKER));
-    REQUIRE(splitter->cutover_inspector() == true);
+    REQUIRE(true == splitter->cutover_inspector());
     delete splitter;
 }
 
index d8cefaae9c42d0b1dd507285951168023c8c0ccc..f1e785989924f851bfdf5d0df4b422ed92db1877 100644 (file)
@@ -354,10 +354,11 @@ void Dce2SmbInspector::show(const SnortConfig*) const
 
 void Dce2SmbInspector::eval(Packet* p)
 {
+    Profile profile(dce2_smb_pstat_main); // cppcheck-suppress unreadVariable
+
     DCE2_SmbSsnData* dce2_smb_sess = nullptr;
     DCE2_Smb2SsnData* dce2_smb2_sess = nullptr;
     DCE2_SmbVersion smb_version = DCE2_SMB_VERSION_NULL;
-    Profile profile(dce2_smb_pstat_main);
 
     if (p == nullptr)
         return;
index e1f3bbdf226150ded2eaaa7226a7810422342089..e5ffe85eb593646fbe722e89e648a5bcc05b969a 100644 (file)
@@ -89,7 +89,7 @@ DCE2_Smb2FileTracker::~DCE2_Smb2FileTracker(void)
     SMB_DEBUG(dce_smb_trace, DEFAULT_TRACE_OPTION_ID, TRACE_DEBUG_LEVEL,
         nullptr, "File tracker with file id: 0x%" PRIx64 " tracker terminating\n", file_id);
     auto all_conn_trackers = str->conn_trackers.get_all_entry();
-    for ( auto& h : all_conn_trackers )
+    for ( const auto& h : all_conn_trackers )
     {
         if (h.second->ftracker_tcp)
         {
@@ -139,7 +139,7 @@ DCE2_Smb2SessionTracker::~DCE2_Smb2SessionTracker(void)
         nullptr, "Session tracker 0x%" PRIx64 " terminating\n", session_id);
     removeSessionFromAllConnection();
     auto all_tree_trackers = tree_trackers.get_all_entry();
-    for ( auto& h : all_tree_trackers )
+    for ( const auto& h : all_tree_trackers )
     {
         removeTtracker(h.first);
     }
index 1cda4503e12f19c3d1d436e0ce89afb4702b3021..d36f7e6cf8a615d21b2787a10cb9ed893319ae40 100644 (file)
@@ -95,7 +95,7 @@ inline std::shared_ptr<DCE2_Smb2SessionTracker> DCE2_SmbSessionCacheFindElseCrea
     return session_ptr;
 }
 
-inline bool DCE2_SmbSessionCacheRemove(Smb2SidHashKey& key)
+inline bool DCE2_SmbSessionCacheRemove(const Smb2SidHashKey& key)
 {
     return smb2_session_cache->remove(key);
 }
index 8dd658ee15caa3075ef4b7a969713b901ec8272a..af8a051426fb7e92178874428775cb9a1a1390d0 100644 (file)
@@ -34,7 +34,7 @@
 
 using namespace snort;
 
-Dce2TcpFlowData::Dce2TcpFlowData() :   FlowData(inspector_id)
+Dce2TcpFlowData::Dce2TcpFlowData() : FlowData(inspector_id)
 {
     dce2_tcp_stats.concurrent_sessions++;
     if (dce2_tcp_stats.max_concurrent_sessions < dce2_tcp_stats.concurrent_sessions)
@@ -130,6 +130,7 @@ void Dce2Tcp::show(const SnortConfig*) const
 void Dce2Tcp::eval(Packet* p)
 {
     DCE2_TcpSsnData* dce2_tcp_sess;
+    // cppcheck-suppress unreadVariable
     Profile profile(dce2_tcp_pstat_main);
 
     assert(p->has_tcp_data());
index dee0440e4a445e75ff2c693abe2579bb588a7828..a09b1586a5192a50153f47b2f32599a8a43234ef 100644 (file)
@@ -57,7 +57,7 @@ public:
     { return true; }
 
 private:
-    dce2TcpProtoConf config;
+    dce2TcpProtoConf config = {};
 };
 
 void print_dce2_tcp_conf(const dce2TcpProtoConf& config);
index a3b60631984fdfafb280f1240e869602b1089fc4..dadf6a9feb291338c85f673507bc08f684f8f7bb 100644 (file)
@@ -50,7 +50,7 @@ static void DCE2_ClCleanTracker(DCE2_ClTracker* clt)
 //-------------------------------------------------------------------------
 // class stuff
 //-------------------------------------------------------------------------
-Dce2UdpFlowData::Dce2UdpFlowData() :   FlowData(inspector_id)
+Dce2UdpFlowData::Dce2UdpFlowData() : FlowData(inspector_id)
 {
     dce2_udp_stats.concurrent_sessions++;
     if (dce2_udp_stats.max_concurrent_sessions < dce2_udp_stats.concurrent_sessions)
@@ -118,8 +118,7 @@ private:
 };
 
 Dce2Udp::Dce2Udp(const dce2UdpProtoConf& pc) : config(pc)
-{
-}
+{ }
 
 void Dce2Udp::show(const SnortConfig*) const
 {
@@ -129,6 +128,7 @@ void Dce2Udp::show(const SnortConfig*) const
 void Dce2Udp::eval(Packet* p)
 {
     DCE2_UdpSsnData* dce2_udp_sess;
+    // cppcheck-suppress unreadVariable
     Profile profile(dce2_udp_pstat_main);
 
     assert(p->flow);
index 3c53050b89015526799abf8a4ac0a625b2c254b6..8d2e67811616468f90ff0fa77e39ce4f409f1e84 100644 (file)
@@ -73,7 +73,7 @@ public:
     const snort::TraceOption* get_trace_options() const override;
 
 private:
-    dce2UdpProtoConf config;
+    dce2UdpProtoConf config = {};
 };
 
 void print_dce2_udp_conf(const dce2UdpProtoConf&);
index ffa787c271fbd96500b19caafcc2205e1604a3e0..2640d25de6b337dc28015cb615c429c3a6a8602c 100644 (file)
@@ -166,22 +166,6 @@ DCE2_Ret DCE2_GetValue(const char* start, char* end, void* int_value, int negate
     return DCE2_RET__SUCCESS;
 }
 
-const char* DCE2_UuidToStr(
-    const Uuid* uuid, DceRpcBoFlag byte_order, char (& uuid_buf)[50])
-{
-    snprintf(uuid_buf, DCE2_UUID_BUF_SIZE,
-        "%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x",
-        DceRpcHtonl(&uuid->time_low, byte_order),
-        DceRpcHtons(&uuid->time_mid, byte_order),
-        DceRpcHtons(&uuid->time_high_and_version, byte_order),
-        uuid->clock_seq_and_reserved, uuid->clock_seq_low,
-        uuid->node[0], uuid->node[1], uuid->node[2],
-        uuid->node[3], uuid->node[4], uuid->node[5]);
-
-    uuid_buf[DCE2_UUID_BUF_SIZE - 1] = '\0';
-    return uuid_buf;
-}
-
 DCE2_Buffer* DCE2_BufferNew(uint32_t initial_size, uint32_t min_add_size)
 {
     DCE2_Buffer* buf = (DCE2_Buffer*)snort_calloc(sizeof(DCE2_Buffer));
index c3ce017ab5dec1799a49ce4f5e030ee21f2fc0a2..c3729bbc928b1ad17ba765f60b0f4480ca6d4525 100644 (file)
@@ -133,10 +133,6 @@ DCE2_Ret DCE2_BufferAddData(DCE2_Buffer*, const uint8_t*,
     uint32_t, uint32_t, DCE2_BufferMinAddFlag);
 void DCE2_BufferDestroy(DCE2_Buffer* buf);
 
-#define DCE2_UUID_BUF_SIZE 50
-const char* DCE2_UuidToStr(
-    const Uuid*, DceRpcBoFlag, char (& buf)[DCE2_UUID_BUF_SIZE]);
-
 // Determines if the character passed in is a character that
 // the inspector considers a to be a space character.
 inline bool DCE2_IsSpaceChar(const char c)
index c12a9c0606995c36baa124077e162a3b3983d2ca..2162630bb66a223f2e7da6c111fe9d3e2a1f8f3f 100644 (file)
@@ -375,6 +375,7 @@ bool Dce2IfaceOption::operator==(const IpsOption& ips) const
 
 IpsOption::EvalStatus Dce2IfaceOption::eval(Cursor& c, Packet* p)
 {
+    // cppcheck-suppress unreadVariable
     RuleProfile profile(dce2_iface_perf_stats);
 
     if (p->dsize == 0)
index 5a7b318c3684dfe06ac20981d93bd61f832ce06c..b12ea7aeffd000b5fdfecbe275cd56ca4b5e5634 100644 (file)
@@ -401,6 +401,7 @@ bool Dce2OpnumOption::operator==(const IpsOption& ips) const
 
 IpsOption::EvalStatus Dce2OpnumOption::eval(Cursor&, Packet* p)
 {
+    // cppcheck-suppress unreadVariable
     RuleProfile profile(dce2_opnum_perf_stats);
 
     if (p->dsize == 0)
index 2c0269de21081a078480edd57b37f7a557708bfa..b3eba8c3f32e16c844742ee78dd4ce10f488bc01 100644 (file)
@@ -75,6 +75,7 @@ bool Dce2StubDataOption::operator==(const IpsOption& ips) const
 
 IpsOption::EvalStatus Dce2StubDataOption::eval(Cursor& c, Packet* p)
 {
+    // cppcheck-suppress unreadVariable
     RuleProfile profile(dce2_stub_data_perf_stats);
 
     if (p->dsize == 0)
index 6e3b51c84594f074c754561ad3fdef310b8b0ae5..19c4fe4193f72ce96aed44585ee809c8940154c0 100644 (file)
@@ -218,6 +218,7 @@ void Dnp3::show(const SnortConfig*) const
 
 void Dnp3::eval(Packet* p)
 {
+    // cppcheck-suppress unreadVariable
     Profile profile(dnp3_perf_stats);
 
     assert (p->has_tcp_data() || p->has_udp_data());
index bced6402e2c790d5fff55e964c7f06f0230f29cb..10a0230297785fa52fe51d1db8a10ff61e94883d 100644 (file)
@@ -145,7 +145,7 @@ enum dnp3_reassembly_state_t
 
 struct dnp3_reassembly_data_t
 {
-    uint8_t buffer[DNP3_BUFFER_SIZE];
+    uint8_t buffer[DNP3_BUFFER_SIZE] = {0};
     uint16_t buflen = 0;
     dnp3_reassembly_state_t state = DNP3_REASSEMBLY_STATE__IDLE;
     uint8_t last_seq = 0;
index 1f9c6795138dda651befe465c7e580a50c0c8060..f0d4c374b1e3ad40d2fe8d7fa53240b10fc94d07 100644 (file)
@@ -58,7 +58,7 @@ public:
     void get_data(dnp3ProtoConf&);
 
 private:
-    dnp3ProtoConf config;
+    dnp3ProtoConf config = {};
 };
 
 #endif
index e7783dbbc213d755883ffb0b89c41b6c72c58949..672b3545c8a4a0700a71755bae6cb6385a03b35e 100644 (file)
@@ -75,6 +75,7 @@ bool Dnp3DataOption::operator==(const IpsOption& ips) const
 
 IpsOption::EvalStatus Dnp3DataOption::eval(Cursor& c, Packet* p)
 {
+    // cppcheck-suppress unreadVariable
     RuleProfile profile(dnp3_data_perf_stats);
 
     if ((p->has_tcp_data() && !p->is_full_pdu()) || !p->flow || !p->dsize)
index 93b960785545ca67f0c911a26cb88a95b6bae940..b181c9a58ee0f7d35c95385ead1a5fa44326fa5b 100644 (file)
@@ -79,6 +79,7 @@ bool Dnp3FuncOption::operator==(const IpsOption& ips) const
 
 IpsOption::EvalStatus Dnp3FuncOption::eval(Cursor&, Packet* p)
 {
+    // cppcheck-suppress unreadVariable
     RuleProfile profile(dnp3_func_perf_stats);
 
     if ((p->has_tcp_data() && !p->is_full_pdu()) || !p->flow || !p->dsize)
@@ -130,7 +131,7 @@ public:
     { return DETECT; }
 
 public:
-    uint16_t func;
+    uint16_t func = 0;
 };
 
 ProfileStats* Dnp3FuncModule::get_profile() const
index 05e54a261eb65e62285312aff4a7e7821d9e99ed..400ba775c4921a9fee4ed7d9e3554c3535da025c 100644 (file)
@@ -80,6 +80,7 @@ bool Dnp3IndOption::operator==(const IpsOption& ips) const
 
 IpsOption::EvalStatus Dnp3IndOption::eval(Cursor&, Packet* p)
 {
+    // cppcheck-suppress unreadVariable
     RuleProfile profile(dnp3_ind_perf_stats);
 
     if ((p->has_tcp_data() && !p->is_full_pdu()) || !p->flow || !p->dsize)
@@ -132,7 +133,7 @@ public:
     { return DETECT; }
 
 public:
-    uint16_t flags;
+    uint16_t flags = 0;
 };
 
 bool Dnp3IndModule::set(const char*, Value& v, SnortConfig*)
index df944c9d56aef79e95dc884b9fbc1f2ce99c14e7..1583392b6ffc8bb8fda559fe6bc116010640c2ef 100644 (file)
@@ -107,6 +107,7 @@ bool Dnp3ObjOption::operator==(const IpsOption& ips) const
 
 IpsOption::EvalStatus Dnp3ObjOption::eval(Cursor&, Packet* p)
 {
+    // cppcheck-suppress unreadVariable
     RuleProfile profile(dnp3_obj_perf_stats);
 
     size_t header_size;
@@ -176,8 +177,8 @@ public:
     { return DETECT; }
 
 public:
-    uint8_t group;
-    uint8_t var;
+    uint8_t group = 0;
+    uint8_t var = 0;
 };
 
 bool Dnp3ObjModule::begin(const char*, int, SnortConfig*)
index 83f6f91b65544c77dc07779808126d2b9f4695a2..b02a746934e47ac783d131bf7466fccf3b697e41 100644 (file)
@@ -562,7 +562,6 @@ static uint16_t ParseDNSAnswer(
             if ( !--bytes_unused )
                 return 0;
         }
-        dnsSessionData->curr_rec_state = DNS_RESP_STATE_RR_RDLENGTH;
         // Fall through
 
     case DNS_RESP_STATE_RR_RDLENGTH:
@@ -1101,6 +1100,7 @@ StreamSplitter* Dns::get_splitter(bool c2s)
 
 static void snort_dns(Packet* p, const DnsConfig* dns_config)
 {
+    // cppcheck-suppress unreadVariable
     Profile profile(dnsPerfStats);
 
     // For TCP, do a few extra checks...
index f06405524b207b186885719bee701e31ff16a564..3fa3c4d41f3ff1f347cba15d3eca144b90bb40bf 100644 (file)
@@ -63,6 +63,7 @@ static inline int InspectClientPacket(Packet* p)
 static int SnortFTP(
     FTP_SESSION* FTPsession, Packet* p, int iInspectMode)
 {
+    // cppcheck-suppress unreadVariable
     Profile profile(ftpPerfStats);
 
     if ( !FTPsession || !FTPsession->server_conf || !FTPsession->client_conf )
index 3d487e6c58ef2e9f8e6963f33109f089858beeee..51c2ba0a166af9fd031980c0c0438e4158a6a9fd 100644 (file)
@@ -306,6 +306,7 @@ ProfileStats* FtpDataModule::get_profile() const
 
 void FtpData::eval(Packet* p)
 {
+    // cppcheck-suppress unreadVariable
     Profile profile(ftpdataPerfStats);
 
     // precondition - what we registered for
index aff573404bf8d6954186ef386cc6884a3a216664..31dec494e854b59fc0084d61fa8817f1f6081023 100644 (file)
@@ -81,9 +81,7 @@ static const Parameter ftp_client_params[] =
 
 FtpClientModule::FtpClientModule() :
     Module(FTP_CLIENT_NAME, ftp_client_help, ftp_client_params)
-{
-    conf = nullptr;
-}
+{ }
 
 FtpClientModule::~FtpClientModule()
 {
@@ -123,12 +121,8 @@ bool FtpClientModule::set(const char*, Value& v, SnortConfig*)
     return true;
 }
 
-BounceTo::BounceTo(const string& a, Port l, Port h)
-{
-    address = a;
-    low = l;
-    high = h;
-}
+BounceTo::BounceTo(const string& a, Port l, Port h) : address(a), low(l), high(h)
+{ }
 
 const BounceTo* FtpClientModule::get_bounce(unsigned idx)
 {
@@ -173,7 +167,7 @@ bool FtpClientModule::end(const char* fqn, int idx, SnortConfig*)
     if ( strcmp(fqn, "ftp_client.bounce_to") )
         return true;
 
-    if ( idx && !strcmp(fqn, "ftp_client.bounce_to") )
+    if ( idx )
     {
         if ( address.empty() || (last_port && (port > last_port)) )
         {
@@ -189,21 +183,12 @@ bool FtpClientModule::end(const char* fqn, int idx, SnortConfig*)
 // server stuff
 //-------------------------------------------------------------------------
 
-FtpCmd::FtpCmd(const std::string& key, uint32_t flg, int num)
-{
-    name = key;
-    flags = flg;
-    number = num;
-}
+FtpCmd::FtpCmd(const std::string& key, uint32_t flg, int num) : name(key), flags(flg), number(num)
+{ }
 
 FtpCmd::FtpCmd(const std::string& key, const std::string& fmt, int num)
+    : name(key), format(fmt), flags(CMD_VALID), number(0)
 {
-    name = key;
-    format = fmt;
-
-    flags = CMD_VALID;
-    number = 0;
-
     if ( num >= 0 )
     {
         number = num;
@@ -353,9 +338,7 @@ static const PegInfo ftp_pegs[] =
 
 FtpServerModule::FtpServerModule() :
     Module(FTP_SERVER_NAME, ftp_server_help, ftp_server_params)
-{
-    conf = nullptr;
-}
+{ }
 
 FtpServerModule::~FtpServerModule()
 {
@@ -601,12 +584,9 @@ bool FtpServerModule::end(const char* fqn, int idx, SnortConfig*)
     if ( !idx && !strcmp(fqn, "ftp_server") )
     {
         cmds.emplace_back(new FtpCmd("PROT", CMD_PROT, 0));
-        for( auto cmd : cmds)
-        {
-            if ( FTPP_SUCCESS !=  ProcessFTPDataChanCmdsList(conf, cmd) )
-                return false;
-        }
-        return true;
+        return std::none_of(cmds.cbegin(), cmds.cend(),
+            [this](const FtpCmd* cmd)
+            { return FTPP_SUCCESS !=  ProcessFTPDataChanCmdsList(conf, cmd); });
     }
 
     if ( !strcmp(fqn, "ftp_server.cmd_validity") )
index 19d29ee61ab57567afe87079c6478d5cbfe5999d..cf83743dd2093b6ef85a8ef199db630afd07fbde 100644 (file)
@@ -74,11 +74,12 @@ public:
     { return true; }
 
 private:
-    FTP_CLIENT_PROTO_CONF* conf;
+    FTP_CLIENT_PROTO_CONF* conf = nullptr;
     std::vector<BounceTo*> bounce_to;
 
     std::string address;
-    Port port, last_port;
+    Port port = 0;
+    Port last_port = 0;
 };
 
 //-------------------------------------------------------------------------
@@ -140,11 +141,11 @@ private:
     void add_commands(snort::Value&, uint32_t flags, int num = 0);
 
 private:
-    FTP_SERVER_PROTO_CONF* conf;
+    FTP_SERVER_PROTO_CONF* conf = nullptr;
     std::vector<FtpCmd*> cmds;
     std::string names;
     std::string format;
-    int number;
+    int number = 0;
 };
 
 #endif
index e938fef282073ed1fd8b070cf69bf358d70e9379..4740a26fa9916171007e106659c2789c25e0e500 100644 (file)
@@ -57,13 +57,6 @@ void reset_telnet_buffer(Packet* p)
     DetectionEngine::get_alt_buffer(p).len = 0;
 }
 
-const uint8_t* get_telnet_buffer(Packet* p, unsigned& len)
-{
-    const DataBuffer& buf = DetectionEngine::get_alt_buffer(p);
-    len = buf.len;
-    return len ? buf.data : nullptr;
-}
-
 int normalize_telnet(
     TELNET_SESSION* tnssn, Packet* p, DataBuffer& buf,
     int iMode, char ignoreEraseCmds, bool on_ftp_channel)
index f5c220daeb323ec040b593838e30590eaa9e4316..3eb3bdf7b3d3339e79b603dfabb3bd95afab6462 100644 (file)
@@ -66,7 +66,6 @@ extern int normalize_telnet(
     TELNET_SESSION*, snort::Packet*, DataBuffer&, int iMode, char ignoreEraseCmd, bool on_ftp_channel);
 
 void reset_telnet_buffer(snort::Packet*);
-const uint8_t* get_telnet_buffer(snort::Packet*, unsigned&);
 
 #endif
 
index fad8806fa23ba2179c5dd62673d3e3b7ba470642..80935daa997a4f2fc73b27c9d44fdbbe6c649c65 100644 (file)
@@ -70,6 +70,7 @@ static int TelnetCheckConfigs(SnortConfig*, void* pData)
 static int SnortTelnet(TELNET_PROTO_CONF* telnet_config, TELNET_SESSION* Telnetsession,
     Packet* p, int iInspectMode)
 {
+    // cppcheck-suppress unreadVariable
     Profile profile(telnetPerfStats);
 
     if ( !Telnetsession )
index b5f3aef9e606dbc0ce2c2c5165ba0e47d166b380..e5f4bbbf3dca0dea21f2b700ffe6357139b3320b 100644 (file)
@@ -98,7 +98,7 @@ GTP_IEData* get_infos()
 class GtpInspect : public Inspector
 {
 public:
-    GtpInspect(std::vector<GtpStuff>&);
+    GtpInspect(const std::vector<GtpStuff>&);
 
     void eval(Packet*) override;
 
@@ -109,11 +109,11 @@ private:
     GTPConfig config;
 };
 
-GtpInspect::GtpInspect(std::vector<GtpStuff>& v)
+GtpInspect::GtpInspect(const std::vector<GtpStuff>& v)
 {
     for ( unsigned i = 0; i < v.size(); ++i )
     {
-        GtpStuff& gs = v[i];
+        const GtpStuff& gs = v[i];
 
         if ( gs.length < 0 )
         {
@@ -129,6 +129,7 @@ GtpInspect::GtpInspect(std::vector<GtpStuff>& v)
 
 void GtpInspect::eval(Packet* p)
 {
+    // cppcheck-suppress unreadVariable
     Profile profile(gtp_inspect_prof);
 
     // preconditions - what we registered for
index ff1a5e788b7b4f8b667c2d03980d6f51eb01dd54..a536b6c6285ededc30eac9cc5f6d5894b2ab2a4e 100644 (file)
@@ -44,9 +44,9 @@ extern THREAD_LOCAL const snort::Trace* gtp_inspect_trace;
 struct GtpStuff
 {
     std::string name;
-    int version;
-    int type;
-    int length;
+    int version = 0;
+    int type = 0;
+    int length = 0;
 };
 
 class GtpInspectModule : public snort::Module
index aa38d50996e9c910a91524e6453e3be2c208c883..30048e7b88c042ed7057527c2bb40c74c5486fc7 100644 (file)
@@ -100,6 +100,7 @@ bool GtpInfoOption::operator==(const IpsOption& ips) const
 
 IpsOption::EvalStatus GtpInfoOption::eval(Cursor& c, Packet* p)
 {
+    // cppcheck-suppress unreadVariable
     RuleProfile profile(gtp_info_prof);
 
     if ( !p or !p->flow )
@@ -160,7 +161,7 @@ public:
     { return DETECT; }
 
 public:
-    uint8_t types[MAX_GTP_VERSION_CODE + 1];
+    uint8_t types[MAX_GTP_VERSION_CODE + 1] = {0};
 };
 
 bool GtpInfoModule::set_types(long t)
index 5ebea1468112e66242d3954309ce5e8d9373cf76..5a27de572dbfd59e98f1325e7ef0fd7f8f158e49 100644 (file)
@@ -46,7 +46,7 @@ static THREAD_LOCAL ProfileStats gtp_type_prof;
 class GtpTypeOption : public IpsOption
 {
 public:
-    GtpTypeOption(ByteBitSet*);
+    GtpTypeOption(const ByteBitSet*);
 
     uint32_t hash() const override;
     bool operator==(const IpsOption&) const override;
@@ -59,7 +59,7 @@ public:
     ByteBitSet types[MAX_GTP_VERSION_CODE + 1];
 };
 
-GtpTypeOption::GtpTypeOption(ByteBitSet* t) : IpsOption(s_name)
+GtpTypeOption::GtpTypeOption(const ByteBitSet* t) : IpsOption(s_name)
 {
     for ( int v = 0; v <= MAX_GTP_VERSION_CODE; ++v )
         types[v] = t[v];
@@ -96,6 +96,7 @@ bool GtpTypeOption::operator==(const IpsOption& ips) const
 
 IpsOption::EvalStatus GtpTypeOption::eval(Cursor&, Packet* p)
 {
+    // cppcheck-suppress unreadVariable
     RuleProfile profile(gtp_type_prof);
 
     if ( !p or !p->flow )
index e731bc909ef3b1c42f68a9f9083f5158341039d0..4292feea73ff27f28ee6deed9ba0e0489644c455 100644 (file)
@@ -78,6 +78,7 @@ bool GtpVersionOption::operator==(const IpsOption& ips) const
 
 IpsOption::EvalStatus GtpVersionOption::eval(Cursor&, Packet* p)
 {
+    // cppcheck-suppress unreadVariable
     RuleProfile profile(gtp_ver_prof);
 
     if ( !p->flow )
@@ -120,7 +121,7 @@ public:
     { return DETECT; }
 
 public:
-    uint8_t version;
+    uint8_t version = 0;
 };
 
 bool GtpVersionModule::set(const char*, Value& v, SnortConfig*)
index e7bc5f3c804bd3903765f2c37aca7098921e4c9b..e4b6f10eedd841168b6c2dfffc26ef73be214888 100644 (file)
@@ -46,13 +46,13 @@ private:
     const HttpCommon::SourceId source_id;
 
     // total per frame - scan
-    uint32_t data_len;
+    uint32_t data_len = 0;
     // accumulating - scan
     uint32_t frame_bytes_seen = 0;
     uint32_t bytes_sent_http = 0;
-    uint32_t data_bytes_read;
+    uint32_t data_bytes_read = 0;
     // total per frame - reassemble
-    uint32_t reassemble_data_len;
+    uint32_t reassemble_data_len = 0;
     // accumulating - reassemble
     uint32_t reassemble_bytes_sent = 0;
     uint32_t reassemble_hdr_bytes_read = 0;
index 5f3a05e3f8f8f4a35ce034f5353ab58fa2b3ca79..8dbae40ef3c3bf3ed36a2e06e9b41106079fb861 100644 (file)
@@ -119,13 +119,9 @@ void Http2FlowData::set_hi_flow_data(HttpFlowData* flow)
 
 Http2Stream* Http2FlowData::find_stream(const uint32_t key)
 {
-    for (Http2Stream& stream : streams)
-    {
-        if (stream.get_stream_id() == key)
-            return &stream;
-    }
-
-    return nullptr;
+    auto it = std::find_if(streams.begin(), streams.end(),
+        [key](const Http2Stream &stream){ return stream.get_stream_id() == key; });
+    return (it != streams.end()) ? &(*it) : nullptr;
 }
 
 Http2Stream* Http2FlowData::get_processing_stream(const SourceId source_id, uint32_t concurrent_streams_limit)
index 2271481379ac79e440f77d53d938472ce4676f80..4b3edb2f70b3f3fca28b90dafcf17abede50a5f1 100644 (file)
@@ -162,15 +162,15 @@ const uint8_t* Http2Frame::get_frame_pdu(uint16_t& length) const
         return nullptr;
 
     uint32_t dlen;
-    const uint8_t* data = get_frame_data(dlen);
-    if (!data or (hlen + dlen > UINT16_MAX))
+    const uint8_t* frame_data = get_frame_data(dlen);
+    if (!frame_data or (hlen + dlen > UINT16_MAX))
         return nullptr;
 
     length = (uint16_t)(hlen + dlen);
     uint8_t* pdu = new uint8_t[length];
     memcpy(pdu, header.start(), hlen);
     if (dlen)
-        memcpy(&pdu[hlen], data, dlen);
+        memcpy(&pdu[hlen], frame_data, dlen);
 
     pdu[0] = (dlen >> 16) & 0xff;
     pdu[1] = (dlen >> 8) & 0xff;
index 336ab26687a1b9e9e97f16dee102e1ee2d0bfea4..33a8f09739f33d22747df82f60ce693a08251e17 100644 (file)
@@ -86,8 +86,8 @@ public:
     void cleanup();
 
 private:
-    Http2StartLine* start_line;
-    bool pseudo_headers_allowed;
+    Http2StartLine* start_line = nullptr;
+    bool pseudo_headers_allowed = false;
     uint8_t* decoded_headers = nullptr; // working buffer to store decoded headers
     Http2FlowData* session_data;
     Http2EventGen* const events;
index 46e1f5fad78b9124230fe8f40f4da21ebab11c63..eb45888bd00f95a3d2a22205c94d980593a8e662 100644 (file)
@@ -105,6 +105,7 @@ bool Http2Inspect::get_fp_buf(InspectionBuffer::Type ibt, Packet* p, InspectionB
 
 void Http2Inspect::eval(Packet* p)
 {
+    // cppcheck-suppress unreadVariable
     Profile profile(Http2Module::get_profile_stats());
 
     const SourceId source_id = p->is_from_client() ? SRC_CLIENT : SRC_SERVER;
index 60669d839efd1bc756d9edf83a4a3f9089292180..662a981932f636fcd68850440b3186d4f21d3b64 100644 (file)
@@ -167,7 +167,7 @@ void Http2SettingsFrame::print_frame(FILE* output)
     if (bad_frame)
         fprintf(output, " Error in settings frame.");
     else if (FLAG_ACK & get_flags())
-        fprintf(output, " ACK, Header Table Size: %d.",
+        fprintf(output, " ACK, Header Table Size: %u.",
                 session_data->connection_settings[1 - source_id].get_param(SFID_HEADER_TABLE_SIZE));
     else
         fprintf(output, " Parameters in current frame - %d.", (data.length()/6)) ;
index 13ddd09a77d07c3e9e55082f311564299ab16132..11b02f634a6792eb0e8e6be56c3909a276f3d01a 100644 (file)
@@ -77,7 +77,7 @@ class Http2ConnectionSettingsQueue
 {
 public:
     ~Http2ConnectionSettingsQueue() { delete queue; }
-    auto size() { return queue ? queue->size() : 0; }
+    auto size() const { return queue ? queue->size() : 0; }
     bool extend(Http2ConnectionSettings& item) { return size() ? extend() : init(item); }
     void pop();
     auto& front() { assert(size()); return queue->front(); }
index b18bf1b2d959dadad27a930dabfdba65e7517dee..86d96395554f9779ce7420b92ab6cf566c74c8db 100644 (file)
@@ -43,6 +43,7 @@ using namespace Http2Enums;
 StreamSplitter::Status Http2StreamSplitter::scan(Packet* pkt, const uint8_t* data, uint32_t length,
     uint32_t, uint32_t* flush_offset)
 {
+    // cppcheck-suppress unreadVariable
     Profile profile(Http2Module::get_profile_stats());
 
     Flow* const flow = pkt->flow;
@@ -127,6 +128,7 @@ StreamSplitter::Status Http2StreamSplitter::scan(Packet* pkt, const uint8_t* dat
 const StreamBuffer Http2StreamSplitter::reassemble(Flow* flow, unsigned total, unsigned offset,
     const uint8_t* data, unsigned len, uint32_t flags, unsigned& copied)
 {
+    // cppcheck-suppress unreadVariable
     Profile profile(Http2Module::get_profile_stats());
 
     copied = len;
index ad99333e06683a12206a5ea39edb98bf1deb9db5..be45ec446a8f72fd543d47714e1b61df173f374a 100644 (file)
@@ -66,6 +66,7 @@ bool Http2IpsOption::operator==(const IpsOption& ips) const
 
 IpsOption::EvalStatus Http2IpsOption::eval(Cursor& c, Packet* p)
 {
+    // cppcheck-suppress unreadVariable
     RuleProfile profile(Http2CursorModule::http2_ps[psi]);
 
     if (!p->flow || !p->flow->gadget)
index 7029e86fc5c6c8310514012bda64a3aadbae13f5..164eacc75a25ccd29d6b274a500d7b4119f82ec6 100644 (file)
@@ -53,7 +53,7 @@ TEST_GROUP(http2_hpack_string_decode_success)
     Http2EventGen events;
     Http2Infractions inf;
     Http2HpackStringDecode* const decode = new Http2HpackStringDecode();
-    Http2HpackIntDecode decode_int7{7};
+    Http2HpackIntDecode decode_int7{7}; // cppcheck-suppress unreadVariable
 
     void teardown() override
     {
index 5e02206c21ed00ea6e3211ab172a81c85443c3e5..f7b3fed8772cceb9a3d8a97729ba804d8ef1e046 100644 (file)
@@ -271,8 +271,9 @@ HttpInfractions* HttpFlowData::get_infractions(SourceId source_id)
     if (infractions[source_id] != nullptr)
         return infractions[source_id];
     assert(transaction[source_id] != nullptr);
-    assert(transaction[source_id]->get_infractions(source_id) != nullptr);
-    return transaction[source_id]->get_infractions(source_id);
+    HttpInfractions* tmp_infractions = transaction[source_id]->get_infractions(source_id);
+    assert(nullptr != tmp_infractions);
+    return tmp_infractions;
 }
 
 void HttpFlowData::finish_hx_body(HttpCommon::SourceId source_id, HttpCommon::HXBodyState state,
index d1e26027da4981b1f6692eeabd4466066d938754..de2fa0fe54f3e36cb5b7ee2359a3592a200ee499 100755 (executable)
@@ -472,6 +472,7 @@ void HttpInspect::eval(Packet* p)
 
 void HttpInspect::eval(Packet* p, SourceId source_id, const uint8_t* data, uint16_t dsize)
 {
+    // cppcheck-suppress unreadVariable
     Profile profile(HttpModule::get_profile_stats());
 
     HttpFlowData* session_data = http_get_flow_data(p->flow);
@@ -635,6 +636,7 @@ void HttpInspect::process(const uint8_t* data, const uint16_t dsize, Flow* const
 
 void HttpInspect::clear(Packet* p)
 {
+    // cppcheck-suppress unreadVariable
     Profile profile(HttpModule::get_profile_stats());
 
     HttpFlowData* const session_data = http_get_flow_data(p->flow);
index 397d3df0595710666a548c6ac7833056fe743874..9fff8921915817bcd95e9b02034fcf1908fa8d8f 100644 (file)
@@ -116,7 +116,7 @@ private:
     const uint32_t xtra_host_id;
     const uint32_t xtra_jsnorm_id;
 
-    unsigned pub_id; // for inspection events
+    unsigned pub_id = 0; // for inspection events
 };
 
 #endif
index c4c65e2b44e5bfd516fe0605fbfbe2104979884e..4edbf4b1915d25d9c64f6882d479312e144557d1 100755 (executable)
@@ -109,8 +109,8 @@ const Field& HttpMsgHeader::get_true_ip_addr()
     if (true_ip_addr.length() != STAT_NOT_COMPUTE)
         return true_ip_addr;
 
-    const Field& true_ip = get_true_ip();
-    if (true_ip.length() <= 0)
+    const Field& tmp_true_ip = get_true_ip();
+    if (tmp_true_ip.length() <= 0)
     {
         true_ip_addr.set(STAT_NOT_PRESENT);
         return true_ip_addr;
index f81607f00713018bb06c957165115248ebe56777..4711443f9121ab297dd7ddfdd6a3aa12eb54a18c 100644 (file)
@@ -371,8 +371,8 @@ const Field& HttpMsgSection::get_param_buffer(Cursor& c, const HttpParam& param)
     {
         KeyValue* fields = query_kv[query_index];
 
-        Field& key = fields->key;
-        Field& value = fields->value;
+        const Field& key = fields->key;
+        const Field& value = fields->value;
 
         ++query_index;
 
@@ -387,8 +387,8 @@ const Field& HttpMsgSection::get_param_buffer(Cursor& c, const HttpParam& param)
     {
         KeyValue* fields = body_kv[body_index];
 
-        Field& key = fields->key;
-        Field& value = fields->value;
+        const Field& key = fields->key;
+        const Field& value = fields->value;
 
         ++body_index;
 
index f5a9b3aeb48ec807e3b6023d3e0b961f352e3ef9..e116d8a6d1506c404a560f44de5070f3ebb2c12c 100644 (file)
@@ -75,7 +75,7 @@ void HttpMsgStart::derive_version_id()
         add_infraction(INF_BAD_VERSION);
         create_event(EVENT_BAD_VERS);
     }
-    else if ((version.start()[5] > '1') && (version.start()[5] <= '9'))
+    else if ((version.start()[5] > '1'))
     {
         version_id = VERS__OTHER;
         add_infraction(INF_VERSION_HIGHER_THAN_1);
index af7c04850e3cfa09db8876ffcac872341dd608ff..93ac6ebf443eb19ed5d3ca08e5c033b275d64786 100644 (file)
@@ -23,6 +23,8 @@
 
 #include "http_msg_trailer.h"
 
+#include <array>
+
 #include "http_api.h"
 #include "http_common.h"
 #include "http_enum.h"
@@ -43,7 +45,7 @@ HttpMsgTrailer::HttpMsgTrailer(const uint8_t* buffer, const uint16_t buf_size,
 void HttpMsgTrailer::gen_events()
 {
     // Trailers not allowed by RFC 7230
-    static const HeaderId bad_trailer[] =
+    static const std::array<HeaderId, 27> bad_trailer =
     {
         HEAD_AGE,
         HEAD_AUTHORIZATION,
@@ -74,14 +76,11 @@ void HttpMsgTrailer::gen_events()
         HEAD_WWW_AUTHENTICATE
     };
 
-    for (HeaderId id: bad_trailer)
+    if (std::any_of(bad_trailer.cbegin(), bad_trailer.cend(),
+        [this](HeaderId id){ return get_header_count(id) > 0; }))
     {
-        if (get_header_count(id) > 0)
-        {
-            add_infraction(INF_ILLEGAL_TRAILER);
-            create_event(EVENT_ILLEGAL_TRAILER);
-            break;
-        }
+        add_infraction(INF_ILLEGAL_TRAILER);
+        create_event(EVENT_ILLEGAL_TRAILER);
     }
 }
 
index ae33f5f185a1aa5dff160ce551ece0f509aa6040..4332c918415e69636e0a90c165e3e8190cf40808 100644 (file)
@@ -254,6 +254,7 @@ void NormalizedHeader::HeaderNormalizer::normalize(const HeaderId head_id, const
 
     uint8_t* const norm_value = new uint8_t[buffer_length];
     uint8_t* const temp_space = new uint8_t[buffer_length];
+    // cppcheck-suppress uninitdata
     uint8_t* const norm_start = (num_normalizers%2 == 0) ? norm_value : temp_space;
     uint8_t* working = norm_start;
     int32_t data_length = 0;
@@ -349,7 +350,7 @@ const Field& NormalizedHeader::get_norm(HttpInfractions* infractions, HttpEventG
     return norm;
 }
 
-const Field& NormalizedHeader::get_comma_separated_raw(HttpMsgHeadShared& msg_head,
+const Field& NormalizedHeader::get_comma_separated_raw(const HttpMsgHeadShared& msg_head,
     HttpInfractions* infractions, HttpEventGen* events, const HttpEnums::HeaderId header_name_id[],
     const Field header_value[], const int32_t num_headers)
 {
index 40ab8f7000eaafc8664f5a7ea227e79974154c58..4dfc7ba1cff138201acdef81397cf484e27f6486 100644 (file)
@@ -37,7 +37,7 @@ public:
     const Field& get_norm(HttpInfractions* infractions, HttpEventGen* events,
         const HttpEnums::HeaderId header_name_id[], const Field header_value[],
         const int32_t num_headers);
-    const Field& get_comma_separated_raw(HttpMsgHeadShared& msg_head, HttpInfractions* infractions,
+    const Field& get_comma_separated_raw(const HttpMsgHeadShared& msg_head, HttpInfractions* infractions,
        HttpEventGen* events, const HttpEnums::HeaderId header_name_id[], const Field header_value[],
         const int32_t num_headers);
 
index a876df444570aa828f92229027c02d099d229d65..2b6be8deaaae604ef81a60c16173678b979ec431 100644 (file)
@@ -94,7 +94,7 @@ private:
     const uint8_t* norm_buffer;
     unsigned norm_buffer_len;
 
-    unsigned index;
+    unsigned index = 0;
 
     static const unsigned MAX_REPEAT_PARAMS = 100;
 
index d4042c6cddaea71591673d7e71337ef10a13fb27..953856dde028676169d4e7464a1b044e18f5be80 100644 (file)
@@ -42,6 +42,7 @@ using namespace snort;
 
 bool HttpStreamSplitter::finish(Flow* flow)
 {
+    // cppcheck-suppress unreadVariable
     Profile profile(HttpModule::get_profile_stats());
 
     HttpFlowData* session_data = HttpInspect::http_get_flow_data(flow);
@@ -216,6 +217,7 @@ bool HttpStreamSplitter::finish(Flow* flow)
 
 void HttpStreamSplitter::prep_partial_flush(Flow* flow, uint32_t num_flush)
 {
+    // cppcheck-suppress unreadVariable
     Profile profile(HttpModule::get_profile_stats());
 
     HttpFlowData* session_data = HttpInspect::http_get_flow_data(flow);
index 6b3cfd144f273c5b53ef19276209269996c8fff9..d73cbe8cc189a837f79b7f88fed26084bb9bcee6 100644 (file)
@@ -286,6 +286,7 @@ void HttpStreamSplitter::decompress_copy(uint8_t* buffer, uint32_t& offset, cons
 const StreamBuffer HttpStreamSplitter::reassemble(Flow* flow, unsigned total,
     unsigned, const uint8_t* data, unsigned len, uint32_t flags, unsigned& copied)
 {
+    // cppcheck-suppress unreadVariable
     Profile profile(HttpModule::get_profile_stats());
 
     copied = len;
index 9b2a7edacd8d7d10ddc04f77de5173c3c68553cc..f15a60c07710f159928b889fba3d712e4da9616b 100644 (file)
@@ -277,7 +277,7 @@ StreamSplitter::Status HttpStreamSplitter::call_cutter(Flow* flow, HttpFlowData*
 StreamSplitter::Status HttpStreamSplitter::scan(Flow* flow, const uint8_t* data, uint32_t length,
     uint32_t* flush_offset)
 {
-    Profile profile(HttpModule::get_profile_stats());
+    Profile profile(HttpModule::get_profile_stats()); // cppcheck-suppress unreadVariable
 
     // This is the session state information we share with HttpInspect and store with stream. A
     // session is defined by a TCP connection. Since scan() is the first to see a new TCP
index 430360f3c1fab653bb1dd6e50e397e8f016487e2..40e0ff41c0a0c802a71cebf5a22cb3a5036e9dbd 100644 (file)
@@ -43,7 +43,7 @@ public:
 private:
     FILE* test_data_file;
     // FIXIT-E Figure out how big this buf needs to be and revise value
-    uint8_t msg_buf[2][2 * HttpEnums::MAX_OCTETS];
+    uint8_t msg_buf[2][2 * HttpEnums::MAX_OCTETS] = {{0}, {0}};
     std::queue<uint32_t> segments[2];
     FILE* include_file[2] = { nullptr, nullptr };
 
index 3162f10f026afcaf33dccc461a82a237c88831e4..06cca8d42fc51ca064fe7b7e9a54a3661e562436 100644 (file)
@@ -53,16 +53,16 @@ public:
     { return DETECT; }
 
 protected:
-    snort::PduSection pdu_section;
+    snort::PduSection pdu_section = snort::PduSection::PS_NONE;
     const HttpEnums::HTTP_RULE_OPT rule_opt_index;
     const char* const key;
-    uint64_t sub_id;
+    uint64_t sub_id = 0;
 
 private:
     friend class HttpIpsOption;
 
     const snort::CursorActionType cat;
-    uint64_t form;
+    uint64_t form = 0;
 };
 
 class HttpIpsOption : public snort::IpsOption
index 0af08a7f560ed1748e4168520732b09765024583..dd6e37e67ef97d95c9b6df601e1525260a5ce9c0 100644 (file)
@@ -57,12 +57,12 @@ private:
 
     // URI related params. These affect the sub_id while parsed.
     // These values are saved to alert on conflicts, only used by ::end
-    bool scheme;
-    bool host;
-    bool port;
-    bool path;
-    bool query;
-    bool fragment;
+    bool scheme = false;
+    bool host = false;
+    bool port = false;
+    bool path = false;
+    bool query = false;
+    bool fragment = false;
 };
 
 class HttpBufferIpsOption : public HttpIpsOption
index 833c67e366787e5499d62339a0f73dcd45725627..358b252a0d13d677608844292b80d8e9f6200f81 100644 (file)
@@ -87,6 +87,7 @@ bool HttpRangeIpsOption::operator==(const IpsOption& ips) const
 
 IpsOption::EvalStatus HttpRangeIpsOption::eval(Cursor&, Packet* p)
 {
+    // cppcheck-suppress unreadVariable
     RuleProfile profile(ps);
 
     const HttpInspect* const hi = eval_helper(p);
index 1404419420d199b97bd8b1a362c88a4500419aab..2df4968d07bc0259bbabfeec9e71225eb256c15c 100644 (file)
@@ -108,6 +108,7 @@ bool HttpParamIpsOption::retry(Cursor& current_cursor, const Cursor&)
 
 IpsOption::EvalStatus HttpParamIpsOption::eval(Cursor& c, Packet* p)
 {
+    // cppcheck-suppress unreadVariable
     RuleProfile profile(HttpParamRuleOptModule::http_param_ps);
 
     const HttpInspect* const hi = eval_helper(p);
index f884d76063f8925d6581ea35a427510f3c2cea45..27238063ec3fb9891e5891bc83f25c1e583ef214 100644 (file)
@@ -148,7 +148,7 @@ IpsOption::EvalStatus HttpTestIpsOption::eval_header_test(const Field& http_buff
     else
         is_numeric = NV_FALSE;
 
-    const bool absent_passed = !absent || (absent && is_absent);
+    const bool absent_passed = !absent || is_absent;
     const bool numeric_passed = (numeric == NumericValue::NV_UNDEFINED) ||
                                 (is_numeric == numeric);
     const bool range_passed = !check.is_set() || (is_numeric == NV_TRUE && check.eval(num));
@@ -158,6 +158,7 @@ IpsOption::EvalStatus HttpTestIpsOption::eval_header_test(const Field& http_buff
 
 IpsOption::EvalStatus HttpTestIpsOption::eval(Cursor&, Packet* p)
 {
+    // cppcheck-suppress unreadVariable
     RuleProfile profile(HttpTestRuleOptModule::http_test_ps[idx]);
 
     const HttpInspect* const hi = eval_helper(p);
index 3b285e027c5339e8f06b1f2f5d92f57a1ae7d61a..590c135a97855dc57126cb8064484f2252b0748e 100644 (file)
@@ -55,8 +55,8 @@ private:
     static THREAD_LOCAL std::array<snort::ProfileStats, TEST_PSI_MAX> http_test_ps;
     const TestPsIdx idx;
     snort::RangeCheck check;
-    enum NumericValue numeric;
-    bool absent;
+    enum NumericValue numeric = NV_UNDEFINED;
+    bool absent = false;
 };
 
 class HttpTestIpsOption : public HttpIpsOption
index b802eb98060326b99e4ddfd72c14cb6755f37297..06b0bf76a8fa6e993b41d1179623952c7aa3bd62 100644 (file)
@@ -115,6 +115,7 @@ bool HttpVersionIpsOption::operator==(const IpsOption& ips) const
 
 IpsOption::EvalStatus HttpVersionIpsOption::eval(Cursor&, Packet* p)
 {
+    // cppcheck-suppress unreadVariable
     RuleProfile profile(HttpVersionRuleOptModule::http_version_ps);
 
     const HttpInspect* const hi = eval_helper(p);
index 87b08c22f2b45e7089e0edddf9ce3df368185ea5..e160dea6bf75dbad24b6da7e7f7d9f8130b365cb 100644 (file)
@@ -42,7 +42,8 @@ bool HttpTestManager::print_hex {};
 TEST_GROUP(get_next_code)
 {
     enum Color { COLOR_OTHER=1, COLOR_GREEN, COLOR_BLUE, COLOR_RED, COLOR_YELLOW, COLOR_PURPLE };
-    int32_t offset = 0;
+    int32_t offset = 0; // cppcheck-suppress unreadVariable
+    // cppcheck-suppress unreadVariable
     const StrCode color_table[6] =
     {
         { COLOR_GREEN,  "green" },
index 5d41ba0206d322b6a10f46c6484de47b84346b49..68e832fe97d34dd860649bb160b33ad0701a9c6c 100644 (file)
@@ -42,7 +42,8 @@ namespace snort
 {
 // Stubs whose sole purpose is to make the test code link
 unsigned FlowData::flow_data_id = 0;
-FlowData::FlowData(unsigned, Inspector*) {}
+FlowData::FlowData(unsigned, Inspector*) : next(nullptr), prev(nullptr), handler(nullptr), id(0)
+{}
 FlowData::~FlowData() = default;
 int DetectionEngine::queue_event(unsigned int, unsigned int) { return 0; }
 fd_status_t File_Decomp_StopFree(fd_session_t*) { return File_Decomp_OK; }
index bd03aa5abd82dd470ccba16c402afb78f3709b46..c5ac831f58f9994d5d5f92ea3da38ba6efdef039 100755 (executable)
@@ -91,11 +91,11 @@ TEST_GROUP(http_double_decode_test)
 
     void setup() override
     {
-        uri_param.percent_u = true;
-        uri_param.iis_unicode = true;
-        uri_param.utf8_bare_byte = true;
-        uri_param.iis_double_decode = true;
-        uri_param.backslash_to_slash = true;
+        uri_param.percent_u = true; // cppcheck-suppress unreadVariable
+        uri_param.iis_unicode = true;   // cppcheck-suppress unreadVariable
+        uri_param.utf8_bare_byte = true;    // cppcheck-suppress unreadVariable
+        uri_param.iis_double_decode = true; // cppcheck-suppress unreadVariable
+        uri_param.backslash_to_slash = true;    // cppcheck-suppress unreadVariable
     }
 };
 
index 482d43847e377bbe2c36c94e1258e759dad2dc3c..4c7f1aff5ff95aaf5543e764406045274dd708f9 100644 (file)
@@ -87,6 +87,7 @@ public:
 
 void Iec104::eval(Packet* p)
 {
+    // cppcheck-suppress unreadVariable
     Profile profile(iec104_prof);
 
     // preconditions - what we registered for
index 6c706442cdc83f77f64f111b2d96c2d5ceb95114..b3f5b5a4f7b3795ee2388b8a89cfdd37de99a5f9 100644 (file)
@@ -122,6 +122,7 @@ bool Iec104ApciTypeOption::operator==(const IpsOption& ips) const
 
 IpsOption::EvalStatus Iec104ApciTypeOption::eval(Cursor&, Packet* p)
 {
+    // cppcheck-suppress unreadVariable
     RuleProfile profile(iec104_apci_type_prof);
 
     if (!p->flow)
index 5217823ba3c820ac4764d76cdd4ecbb1d51331c1..e269ae01ad3a1b3fb298a56116d000af89290b8e 100644 (file)
@@ -189,6 +189,7 @@ bool Iec104AsduFuncOption::operator==(const IpsOption& ips) const
 
 IpsOption::EvalStatus Iec104AsduFuncOption::eval(Cursor&, Packet* p)
 {
+    // cppcheck-suppress unreadVariable
     RuleProfile profile(iec104_asdu_func_prof);
 
     if (!p->flow)
index 05b837f85c2fd79bcb46484d49e9e22a83a95cfc..0e92a683406eaa332c28e52eea1449be46eab6ca 100644 (file)
@@ -793,6 +793,7 @@ void Imap::show(const SnortConfig*) const
 
 void Imap::eval(Packet* p)
 {
+    // cppcheck-suppress unreadVariable
     Profile profile(imapPerfStats);
 
     // precondition - what we registered for
index b6ed36cec5d7736dfd0618e2d16f9cde738e7e2b..4fc893a75965ac9eb4d07585a7807ae428d92f83 100644 (file)
@@ -55,6 +55,7 @@ public:
 
 IpsOption::EvalStatus MmsDataOption::eval(Cursor& c, Packet* p)
 {
+    // cppcheck-suppress unreadVariable
     RuleProfile profile(mms_data_prof);
 
     if (!p->flow)
index 6f1a6ec4a8da5436a14ed332b2080bb7b5fbe0fa..4c8939e3cef9aa477cd28cdb4bd96445c75fa033 100644 (file)
@@ -88,6 +88,7 @@ public:
 
 void Mms::eval(Packet* p)
 {
+    // cppcheck-suppress unreadVariable
     Profile profile(mms_prof);
 
     // preconditions - what we registered for
index 753cfe9e5b1072d0bbde8babca2829202f39a4c8..a11ed0eb082311fa7fa43f6cbd3ffadd0e181722 100644 (file)
@@ -80,7 +80,7 @@ static TpktAppliSearchStateType resolve_spdu_parameter(Cursor* tpkt_cur, const O
         struct OsiSessionSpduSessionRequirement
         {
             OsiSessionSpduParameterHdr param_hdr;
-            uint16_t flags;
+            uint16_t flags; // cppcheck-suppress unusedStructMember
         };
 
         // overlay the appropriate struct
@@ -114,7 +114,7 @@ static TpktAppliSearchStateType resolve_spdu_parameter(Cursor* tpkt_cur, const O
         struct OsiSessionSpduCallingSessionSelector
         {
             OsiSessionSpduParameterHdr param_hdr;
-            uint16_t calling_session_selector;
+            uint16_t calling_session_selector;  // cppcheck-suppress unusedStructMember
         };
 
         // overlay the appropriate struct
@@ -143,7 +143,7 @@ static TpktAppliSearchStateType resolve_spdu_parameter(Cursor* tpkt_cur, const O
         struct OsiSessionSpduCalledSessionSelector
         {
             OsiSessionSpduParameterHdr param_hdr;
-            uint16_t called_session_selector;
+            uint16_t called_session_selector;   // cppcheck-suppress unusedStructMember
         };
 
         // overlay the appropriate struct
index 057325374ab95a6ecf9b91b36b5d4383c2388bf4..2871b6b7b1112b3c5f6c3f488c04f1b111cfc52b 100644 (file)
@@ -83,7 +83,7 @@ TpktEncapLayerSearchStateType is_tpkt(Cursor* c, TpktFlowData* tpktfd, bool is_f
     // if it turns out not to be a partial it will get caught on the
     // next loop
     const uint8_t tpkt_version = *(c->start());
-    if (tpkt_version == 0x03 and remaining_bytes > 0x00 and remaining_bytes < sizeof(TpktHdr))
+    if (tpkt_version == 0x03 and remaining_bytes < sizeof(TpktHdr))
     {
         return TPKT_ENCAP_LAYER_SEARCH_STATE__PARTIAL;
     }
index 29f839738f18be5877ba10170392d073c3af526c..22c4b00b4e46809729362d580cf693ca19c4f041 100644 (file)
@@ -73,7 +73,7 @@ bool ModbusDataOption::operator==(const IpsOption& ips) const
 
 IpsOption::EvalStatus ModbusDataOption::eval(Cursor& c, Packet* p)
 {
-    RuleProfile profile(modbus_data_prof);
+    RuleProfile profile(modbus_data_prof);  // cppcheck-suppress unreadVariable
 
     if ( !p->flow )
         return NO_MATCH;
index f9d038cfa5158d0fb96267ab4fd1dd93dad8a76a..7749c90c114b7ae7c874251e6315bb00b7fa9b85 100644 (file)
@@ -125,7 +125,7 @@ bool ModbusFuncOption::operator==(const IpsOption& ips) const
 
 IpsOption::EvalStatus ModbusFuncOption::eval(Cursor&, Packet* p)
 {
-    RuleProfile profile(modbus_func_prof);
+    RuleProfile profile(modbus_func_prof);  // cppcheck-suppress unreadVariable
 
     if ( !p->flow )
         return NO_MATCH;
@@ -171,7 +171,7 @@ public:
     { return DETECT; }
 
 public:
-    uint8_t func;
+    uint8_t func = 0;
 };
 
 bool ModbusFuncModule::set(const char*, Value& v, SnortConfig*)
index 4246f5bc018b75c32ba5de1a69e1803f56f9e088..ddf127be8559cc5943c4b4e48785f978e764a955 100644 (file)
@@ -77,7 +77,7 @@ bool ModbusUnitOption::operator==(const IpsOption& ips) const
 
 IpsOption::EvalStatus ModbusUnitOption::eval(Cursor&, Packet* p)
 {
-    RuleProfile profile(modbus_unit_prof);
+    RuleProfile profile(modbus_unit_prof);  // cppcheck-suppress unreadVariable
 
     if ( !p->flow )
         return NO_MATCH;
@@ -123,7 +123,7 @@ public:
     { return DETECT; }
 
 public:
-    uint8_t unit;
+    uint8_t unit = 0;
 };
 
 bool ModbusUnitModule::set(const char*, Value& v, SnortConfig*)
index 58568cb8be0be8b3657ed8daf00081ec914fb0ac..097fac3aa9a939fea45ff4a3d685d9356ec530a3 100644 (file)
@@ -82,7 +82,7 @@ public:
 
 void Modbus::eval(Packet* p)
 {
-    Profile profile(modbus_prof);
+    Profile profile(modbus_prof);   // cppcheck-suppress unreadVariable
 
     // preconditions - what we registered for
     assert(p->has_tcp_data());
index abcd00ba37e1e17967f00398e98c0461a95bcc47..3d2acd7c7bf39f91bbb8b5f42d2ebb1e54c37df5 100644 (file)
@@ -89,9 +89,9 @@ using namespace snort;
 struct modbus_header_t
 {
     /* MBAP Header */
-    uint16_t transaction_id;
+    uint16_t transaction_id;    // cppcheck-suppress unusedStructMember
     uint16_t protocol_id;
-    uint16_t length;
+    uint16_t length;    // cppcheck-suppress unusedStructMember
     uint8_t unit_id;
 
     /* PDU Start */
index fcd905dea7751ef28a924304d5519067c6ba2c21..baa389a2f16c5cfdae604f6bf39c4be5d587e276 100644 (file)
@@ -58,11 +58,9 @@ static std::vector<const NetFlowRule*> filter_record(const NetFlowRules* rules,
 
     for( auto const & address : addr )
     {
-        for( auto const& rule : rules->exclude )
-        {
-            if ( rule.filter_match(address, zone) )
-                return match_vec;
-        }
+        if (std::any_of(rules->exclude.cbegin(), rules->exclude.cend(),
+            [address, zone](const NetFlowRule& rule){ return rule.filter_match(address, zone); }))
+            return match_vec;
     }
 
     for( auto const & address : addr )
@@ -890,14 +888,13 @@ void NetFlowInspector::stringify(std::ofstream& file_stream)
 {
     std::sort(dump_cache->begin(), dump_cache->end(), IpCompare());
 
-    std::string str;
     SfIpString ip_str;
     uint32_t i = 0;
 
     for (auto& elem : *dump_cache)
     {
         NetFlowSessionRecord& record = elem.second;
-        str = "NetFlow Record #";
+        std::string str = "NetFlow Record #";
         str += std::to_string(++i);
         str += "\n";
 
index 80b56ce121c45520182dc15a927a35939224d0c3..0abdd3ed32c43b466bce41d9a2b9bb226515973b 100644 (file)
@@ -226,12 +226,12 @@ bool NetFlowModule::set(const char*, Value& v, SnortConfig*)
 
 void NetFlowModule::parse_service_id_file(const std::string& serv_id_file_path)
 {
-    std::string serv_line;
     std::ifstream serv_id_file;
     serv_id_file.open(serv_id_file_path);
 
     if ( serv_id_file.is_open() )
     {
+        std::string serv_line;
         while ( std::getline(serv_id_file, serv_line) )
         {
             std::stringstream ss(serv_line);
index 490f9d96dbda12b02d957050deccdeac93cb4923..e15752ea64f9e7f952336a58dc8fd6c1654176f9 100644 (file)
@@ -77,30 +77,14 @@ struct NetFlowRule
 
     bool filter_match(const snort::SfIp* ip, const int zone) const
     {
-        bool zone_match = false;
-        if ( zones.empty() )
-            zone_match = true;
-        else
-        {
-            for( int z : zones)
-            {
-                if ( z == NETFLOW_ANY_ZONE or z == zone )
-                {
-                    zone_match = true;
-                    break;
-                }
-            }
-        }
-        if ( !zone_match )
+        if ( !zones.empty()
+            and std::none_of(zones.cbegin(), zones.cend(),
+                [zone](int z){ return z == NETFLOW_ANY_ZONE or z == zone; }))
             return false;
 
-        if ( networks.empty() )
-            return true;
-        for( auto const &net : networks )
-            if ( net.contains(ip) == SFIP_CONTAINS )
-                return true;
-
-        return false;
+        return networks.empty()
+            or std::any_of(networks.cbegin(), networks.cend(),
+                [ip](const snort::SfCidr& net){ return SFIP_CONTAINS == net.contains(ip);});
     }
 
     std::vector <snort::SfCidr> networks;
index 724cea98990db393622b62278874a7be3dcf05ba..db8ffe22de71a93ccd3e3e250be4fd550d0aeab9 100644 (file)
@@ -731,7 +731,7 @@ void Pop::show(const SnortConfig*) const
 
 void Pop::eval(Packet* p)
 {
-    Profile profile(popPerfStats);
+    Profile profile(popPerfStats);  // cppcheck-suppress unreadVariable
 
     // precondition - what we registered for
     assert(p->has_tcp_data());
index c9b07219126979bc92230932f82ac0584f2dbca4..ad05757f6664f340a3556c4a49a949525ba0c462 100644 (file)
@@ -778,7 +778,7 @@ RpcDecode::RpcDecode(RpcDecodeModule*)
  */
 void RpcDecode::eval(Packet* p)
 {
-    Profile profile(rpcdecodePerfStats);
+    Profile profile(rpcdecodePerfStats);    // cppcheck-suppress unreadVariable
 
     // preconditions - what we registered for
     assert(p->has_tcp_data());
index 833c875798811a808e8bc7b39b6d4394151a0152..6f8cb260d5686c184215e7db64aa91df4e48b263 100644 (file)
@@ -73,7 +73,7 @@ bool S7commplusContentOption::operator==(const IpsOption& ips) const
 
 IpsOption::EvalStatus S7commplusContentOption::eval(Cursor& c, Packet* p)
 {
-    RuleProfile profile(s7commplus_content_prof);
+    RuleProfile profile(s7commplus_content_prof);   // cppcheck-suppress unreadVariable
 
     if ( !p->flow )
         return NO_MATCH;
index 1ff90c1e6f526f0e559026092d350de42020561e..4850ba60c3a7a264523c2a35e794ac76d15029ac 100644 (file)
@@ -118,7 +118,7 @@ bool S7commplusFuncOption::operator==(const IpsOption& ips) const
 
 IpsOption::EvalStatus S7commplusFuncOption::eval(Cursor&, Packet* p)
 {
-    RuleProfile profile(s7commplus_func_prof);
+    RuleProfile profile(s7commplus_func_prof);  // cppcheck-suppress unreadVariable
 
     if ( !p->flow )
         return NO_MATCH;
@@ -165,7 +165,7 @@ public:
 
 public:
     //uint8_t func;
-    uint16_t func;
+    uint16_t func = 0;
 };
 
 bool S7commplusFuncModule::set(const char*, Value& v, SnortConfig*)
index 8e4845cdc5ab89523e529a4a1c9b4b377630aa0a..3093bc2a307b79b846f7ba4e6d86aca140f451e2 100644 (file)
@@ -111,7 +111,7 @@ bool S7commplusOpcodeOption::operator==(const IpsOption& ips) const
 
 IpsOption::EvalStatus S7commplusOpcodeOption::eval(Cursor&, Packet* p)
 {
-    RuleProfile profile(s7commplus_opcode_prof);
+    RuleProfile profile(s7commplus_opcode_prof);    // cppcheck-suppress unreadVariable
 
     if ( !p->flow )
         return NO_MATCH;
@@ -157,7 +157,7 @@ public:
     { return DETECT; }
 
 public:
-    uint8_t opcode;
+    uint8_t opcode = 0;
 };
 
 bool S7commplusOpcodeModule::set(const char*, Value& v, SnortConfig*)
index b6f4f690a2172eec8d12b42ee68fcca1c3c98b0a..3063a6094e58c1458497ae79b9b7b1f36a06068f 100644 (file)
@@ -81,7 +81,7 @@ public:
 
 void S7commplus::eval(Packet* p)
 {
-    Profile profile(s7commplus_prof);
+    Profile profile(s7commplus_prof);   // cppcheck-suppress unreadVariable
 
     // preconditions - what we registered for
     assert(p->has_tcp_data());
index 41acf19259901038844fefb4a14afbf217988344..0271feac1f2b6412fd177b03e42f6aacb16994d4 100644 (file)
@@ -100,7 +100,7 @@ bool SipMethodOption::operator==(const IpsOption& ips) const
 
 IpsOption::EvalStatus SipMethodOption::eval(Cursor&, Packet* p)
 {
-    RuleProfile profile(sipMethodRuleOptionPerfStats);
+    RuleProfile profile(sipMethodRuleOptionPerfStats);  // cppcheck-suppress unreadVariable
 
     if ( !p->flow )
         return NO_MATCH;
@@ -162,7 +162,7 @@ public:
     MethodMap methods;
 
 private:
-    bool negated;
+    bool negated = false;
 };
 
 bool SipMethodModule::begin(const char*, int, SnortConfig*)
index 32cab35aefbe79bdb5e5597e37366cc85bc63a73..44b6db43ebf09acebc1879d10dce9441ba3d7a4f 100644 (file)
@@ -50,9 +50,8 @@ static THREAD_LOCAL ProfileStats sipStatCodeRuleOptionPerfStats;
 class SipStatCodeOption : public IpsOption
 {
 public:
-    SipStatCodeOption(const SipStatCodeRuleOptData& c) :
-        IpsOption(s_name)
-    { ssod = c; }
+    SipStatCodeOption(const SipStatCodeRuleOptData& c) : IpsOption(s_name), ssod(c)
+    { }
 
     uint32_t hash() const override;
     bool operator==(const IpsOption&) const override;
@@ -90,7 +89,7 @@ bool SipStatCodeOption::operator==(const IpsOption& ips) const
 
 IpsOption::EvalStatus SipStatCodeOption::eval(Cursor&, Packet* p)
 {
-    RuleProfile profile(sipStatCodeRuleOptionPerfStats);
+    RuleProfile profile(sipStatCodeRuleOptionPerfStats);    // cppcheck-suppress unreadVariable
 
     if ((!p->has_tcp_data() && !p->is_udp()) || !p->flow || !p->dsize)
         return NO_MATCH;
@@ -151,7 +150,7 @@ public:
     SipStatCodeRuleOptData ssod;
 
 private:
-    int num_tokens;
+    int num_tokens = 0;
 };
 
 bool SipStatCodeModule::begin(const char*, int, SnortConfig*)
index 2927e44759d3eaff489978b95148a4d0aaca9856..a8d35b295435f066308ec79e74099f8e8dfc0eae 100644 (file)
@@ -132,7 +132,7 @@ static inline int SIP_Process(Packet* p, SIPData* sessp, SIP_PROTO_CONF* config)
     if (true == status)
     {
         /*Update the dialog state*/
-        SIP_updateDialog(&sipMsg, &(sessp->dialogs), p, config);
+        SIP_updateDialog(sipMsg, &(sessp->dialogs), p, config);
     }
     /*Update the session data*/
     pRopts = &(sessp->ropts);
@@ -152,7 +152,7 @@ static inline int SIP_Process(Packet* p, SIPData* sessp, SIP_PROTO_CONF* config)
 
 static void snort_sip(SIP_PROTO_CONF* config, Packet* p)
 {
-    Profile profile(sipPerfStats);
+    Profile profile(sipPerfStats);  // cppcheck-suppress unreadVariable
 
     /* Attempt to get a previously allocated SIP block. */
     SIPData* sessp = get_sip_session_data(p->flow);
index bf2a020ad32f0d6395bc71013a8587a1a8774940..83be9fe57f0a58893da38480c3411edcde1ac13f 100644 (file)
 
 using namespace snort;
 
-static void SIP_updateMedias(SIP_MediaSession*, SIP_MediaList*);
+static void SIP_updateMedias(SIP_MediaSession*, SIP_MediaList&);
 static int SIP_compareMedias(const SIP_MediaDataList, const SIP_MediaDataList);
-static bool SIP_checkMediaChange(const SIPMsg*, const SIP_DialogData*);
-static int SIP_processRequest(SIPMsg*, SIP_DialogData*, SIP_DialogList*, Packet*, SIP_PROTO_CONF*);
-static int SIP_processInvite(SIPMsg*, SIP_DialogData*, SIP_DialogList*);
-static int SIP_processACK(SIPMsg*, SIP_DialogData*, SIP_DialogList*, Packet*, SIP_PROTO_CONF*);
-static int SIP_processResponse(SIPMsg*, SIP_DialogData*, SIP_DialogList*, Packet*,
-    SIP_PROTO_CONF*);
-static int SIP_ignoreChannels(SIP_DialogData*, Packet* p, SIP_PROTO_CONF*);
-static SIP_DialogData* SIP_addDialog(SIPMsg*, SIP_DialogData*, SIP_DialogList*);
+static bool SIP_checkMediaChange(const SIPMsg&, const SIP_DialogData*);
+static int SIP_processInvite(const SIPMsg&, SIP_DialogData*, SIP_DialogList*);
+static int SIP_processACK(SIPMsg&, SIP_DialogData*, SIP_DialogList*, Packet*, SIP_PROTO_CONF*);
+static int SIP_ignoreChannels(const SIP_DialogData&, Packet* p, SIP_PROTO_CONF*);
+static SIP_DialogData* SIP_addDialog(const SIPMsg&, SIP_DialogData*, SIP_DialogList*);
 static int SIP_deleteDialog(SIP_DialogData*, SIP_DialogList*);
 
 /********************************************************************
@@ -57,7 +54,7 @@ static int SIP_deleteDialog(SIP_DialogData*, SIP_DialogList*);
  *  Based on the new received sip request message, update the dialog information.
  *  Note: dialog is created through dialog
  * Arguments:
- *  SIPMsg *        - sip request message
+ *  SIPMsg &        - sip request message
  *  SIP_DialogData* - dialog to be updated,
  *  Packet*  - the packet
  *
@@ -65,23 +62,21 @@ static int SIP_deleteDialog(SIP_DialogData*, SIP_DialogList*);
  *  true: request message has been processed correctly
  *  false: request message has not been processed correctly
  ********************************************************************/
-static int SIP_processRequest(SIPMsg* sipMsg, SIP_DialogData* dialog, SIP_DialogList* dList,
+static int SIP_processRequest(SIPMsg& sipMsg, SIP_DialogData* dialog, SIP_DialogList* dList,
     Packet* p, SIP_PROTO_CONF* config)
 {
     SIPMethodsFlag methodFlag;
     int ret = true;
 
-    assert (nullptr != sipMsg);
-
     /*If dialog not exist, create one */
-    if ((nullptr == dialog)&&(SIP_METHOD_CANCEL != sipMsg->methodFlag))
+    if ((nullptr == dialog) && (SIP_METHOD_CANCEL != sipMsg.methodFlag))
     {
         // Clang analyzer is false positive, dlist->head is updated after free
         // (Use of memory after it is freed)
         dialog = SIP_addDialog(sipMsg, dList->head, dList); // ... FIXIT-W
     }
 
-    methodFlag = sipMsg->methodFlag;
+    methodFlag = sipMsg.methodFlag;
 
     sip_stats.requests[TOTAL_REQUESTS]++;
     if (methodFlag > 0 && methodFlag < NUM_OF_REQUEST_TYPES)
@@ -131,14 +126,14 @@ static int SIP_processRequest(SIPMsg* sipMsg, SIP_DialogData* dialog, SIP_Dialog
  *  Based on the new received sip invite request message, update the dialog information.
  *  Note: dialog is created through dialog
  * Arguments:
- *  SIPMsg *        - sip request message
+ *  SIPMsg &        - sip request message
  *  SIP_DialogData* - dialog to be updated,
  *   SIP_DialogList*- dialog list
  * Returns:
  *  true:
  *  false:
  ********************************************************************/
-static int SIP_processInvite(SIPMsg* sipMsg, SIP_DialogData* dialog, SIP_DialogList* dList)
+static int SIP_processInvite(const SIPMsg& sipMsg, SIP_DialogData* dialog, SIP_DialogList* dList)
 {
     bool ret = true;
 
@@ -147,7 +142,7 @@ static int SIP_processInvite(SIPMsg* sipMsg, SIP_DialogData* dialog, SIP_DialogL
 
     /*Check for the invite replay attack: authenticated invite without challenge*/
     // check whether this invite has authorization information
-    if ((SIP_DLG_AUTHENCATING != dialog->state) && (nullptr != sipMsg->authorization))
+    if ((SIP_DLG_AUTHENCATING != dialog->state) && (nullptr != sipMsg.authorization))
     {
         DetectionEngine::queue_event(GID_SIP, SIP_EVENT_AUTH_INVITE_REPLAY_ATTACK);
         return false;
@@ -167,11 +162,11 @@ static int SIP_processInvite(SIPMsg* sipMsg, SIP_DialogData* dialog, SIP_DialogL
         ret = SIP_checkMediaChange(sipMsg, dialog);
         if (false == ret)
             DetectionEngine::queue_event(GID_SIP, SIP_EVENT_AUTH_INVITE_DIFF_SESSION);
-        SIP_updateMedias(sipMsg->mediaSession, &dialog->mediaSessions);
+        SIP_updateMedias(sipMsg.mediaSession, dialog->mediaSessions);
     }
     else if (SIP_DLG_TERMINATED == dialog->state)
     {
-        SIP_updateMedias(sipMsg->mediaSession, &dialog->mediaSessions);
+        SIP_updateMedias(sipMsg.mediaSession, dialog->mediaSessions);
     }
     dialog->state = SIP_DLG_INVITING;
     return ret;
@@ -182,16 +177,8 @@ static int SIP_processInvite(SIPMsg* sipMsg, SIP_DialogData* dialog, SIP_DialogL
  *
  *  Based on the new received sip ACK request message, update the dialog information.
  *  Note: dialog is created through dialog
- * Arguments:
- *  SIPMsg *        - sip request message
- *  SIP_DialogData* - dialog to be updated,
- *  SIP_DialogList* - dialog list
- *  Packet*  - the packet
- * Returns:
- *  true:
- *  false:
  ********************************************************************/
-static int SIP_processACK(SIPMsg* sipMsg, SIP_DialogData* dialog, SIP_DialogList*, Packet* p,
+static int SIP_processACK(SIPMsg& sipMsg, SIP_DialogData* dialog, SIP_DialogList*, Packet* p,
     SIP_PROTO_CONF* config)
 {
     if (nullptr == dialog)
@@ -199,12 +186,11 @@ static int SIP_processACK(SIPMsg* sipMsg, SIP_DialogData* dialog, SIP_DialogList
 
     if (SIP_DLG_ESTABLISHED == dialog->state)
     {
-        if ((SIP_METHOD_INVITE == dialog->creator)&&(SIP_checkMediaChange(sipMsg, dialog) ==
-            false))
+        if ((SIP_METHOD_INVITE == dialog->creator) && !SIP_checkMediaChange(sipMsg, dialog))
         {
-            SIP_updateMedias(sipMsg->mediaSession, &dialog->mediaSessions);
-            SIP_ignoreChannels(dialog, p, config);
-            sipMsg->mediaUpdated = true;
+            SIP_updateMedias(sipMsg.mediaSession, dialog->mediaSessions);
+            SIP_ignoreChannels(*dialog, p, config);
+            sipMsg.mediaUpdated = true;
         }
     }
     return true;
@@ -216,7 +202,7 @@ static int SIP_processACK(SIPMsg* sipMsg, SIP_DialogData* dialog, SIP_DialogList
  *  Based on the new received sip response message, update the dialog information.
  *
  * Arguments:
- *  SIPMsg *        - sip response message
+ *  SIPMsg &        - sip response message
  *  SIP_DialogData* - dialog to be updated,
  *  Packet*  - the packet
  *
@@ -224,15 +210,13 @@ static int SIP_processACK(SIPMsg* sipMsg, SIP_DialogData* dialog, SIP_DialogList
  *  true:
  *  false:
  ********************************************************************/
-static int SIP_processResponse(SIPMsg* sipMsg, SIP_DialogData* dialog, SIP_DialogList* dList,
+static int SIP_processResponse(SIPMsg& sipMsg, SIP_DialogData* dialog, SIP_DialogList* dList,
     Packet* p, SIP_PROTO_CONF* config)
 {
     int statusType;
     SIP_DialogData* currDialog = dialog;
 
-    assert (nullptr != sipMsg);
-
-    statusType = sipMsg->status_code / 100;
+    statusType = sipMsg.status_code / 100;
     sip_stats.responses[TOTAL_RESPONSES]++;
     if (statusType < NUM_OF_RESPONSE_TYPES)
         sip_stats.responses[statusType]++;
@@ -240,8 +224,8 @@ static int SIP_processResponse(SIPMsg* sipMsg, SIP_DialogData* dialog, SIP_Dialo
     if (nullptr == dialog)
         return false;
 
-    if (sipMsg->status_code > 0)
-        dialog->status_code = sipMsg->status_code;
+    if (sipMsg.status_code > 0)
+        dialog->status_code = sipMsg.status_code;
 
     switch (statusType)
     {
@@ -256,9 +240,9 @@ static int SIP_processResponse(SIPMsg* sipMsg, SIP_DialogData* dialog, SIP_Dialo
         // media session
         if ( !SIP_checkMediaChange(sipMsg, dialog) )
         {
-            SIP_updateMedias(sipMsg->mediaSession, &dialog->mediaSessions);
-            SIP_ignoreChannels(currDialog, p,config);
-            sipMsg->mediaUpdated = true;
+            SIP_updateMedias(sipMsg.mediaSession, dialog->mediaSessions);
+            SIP_ignoreChannels(*currDialog, p,config);
+            sipMsg.mediaUpdated = true;
         }
         break;
     case RESPONSE2XX:
@@ -268,9 +252,9 @@ static int SIP_processResponse(SIPMsg* sipMsg, SIP_DialogData* dialog, SIP_Dialo
             SIP_deleteDialog(currDialog->nextD, dList);
             if (SIP_checkMediaChange(sipMsg, dialog) == false)
             {
-                SIP_updateMedias(sipMsg->mediaSession, &dialog->mediaSessions);
-                SIP_ignoreChannels(currDialog, p, config);
-                sipMsg->mediaUpdated = true;
+                SIP_updateMedias(sipMsg.mediaSession, dialog->mediaSessions);
+                SIP_ignoreChannels(*currDialog, p, config);
+                sipMsg.mediaUpdated = true;
             }
             currDialog->state = SIP_DLG_ESTABLISHED;
         }
@@ -284,9 +268,9 @@ static int SIP_processResponse(SIPMsg* sipMsg, SIP_DialogData* dialog, SIP_Dialo
             if ((SIP_METHOD_INVITE == currDialog->creator)&&
                 (SIP_checkMediaChange(sipMsg, dialog) == false))
             {
-                SIP_updateMedias(sipMsg->mediaSession, &dialog->mediaSessions);
-                SIP_ignoreChannels(currDialog, p, config);
-                sipMsg->mediaUpdated = true;
+                SIP_updateMedias(sipMsg.mediaSession, dialog->mediaSessions);
+                SIP_ignoreChannels(*currDialog, p, config);
+                sipMsg.mediaUpdated = true;
             }
             currDialog->state = SIP_DLG_ESTABLISHED;
         }
@@ -297,7 +281,7 @@ static int SIP_processResponse(SIPMsg* sipMsg, SIP_DialogData* dialog, SIP_Dialo
     case RESPONSE6XX:
 
         // If authentication is required
-        if ((401 == sipMsg->status_code) || (407 == sipMsg->status_code))
+        if ((401 == sipMsg.status_code) || (407 == sipMsg.status_code))
         {
             currDialog->state = SIP_DLG_AUTHENCATING;
         }
@@ -324,25 +308,25 @@ static int SIP_processResponse(SIPMsg* sipMsg, SIP_DialogData* dialog, SIP_Dialo
  *  Based on the new received sip invite request message, check whether SDP has been changed
  *
  * Arguments:
- *  SIPMsg *        - sip request message
+ *  SIPMsg &        - sip request message
  *  SIP_DialogData* - dialog to be updated,
  *
  * Returns:
  *  true: media not changed
  *  false: media changed
  ********************************************************************/
-static bool SIP_checkMediaChange(const SIPMsg* sipMsg, const SIP_DialogData* dialog)
+static bool SIP_checkMediaChange(const SIPMsg& sipMsg, const SIP_DialogData* dialog)
 {
     const SIP_MediaSession* medias;
 
     // Compare the medias (SDP part)
-    if (nullptr == sipMsg->mediaSession)
+    if (nullptr == sipMsg.mediaSession)
         return true;
 
     medias = dialog->mediaSessions;
     while (nullptr != medias)
     {
-        if (sipMsg->mediaSession->sessionID == medias->sessionID)
+        if (sipMsg.mediaSession->sessionID == medias->sessionID)
             break;
         medias = medias->nextS;
     }
@@ -353,7 +337,7 @@ static bool SIP_checkMediaChange(const SIPMsg* sipMsg, const SIP_DialogData* dia
         return false;
     }
     // The media content has been changed
-    if (0 != SIP_compareMedias(medias->medias, sipMsg->mediaSession->medias))
+    if (0 != SIP_compareMedias(medias->medias, sipMsg.mediaSession->medias))
         return false;
 
     return true;
@@ -366,7 +350,7 @@ static bool SIP_checkMediaChange(const SIPMsg* sipMsg, const SIP_DialogData* dia
  * sessions, one from each side of conversation
  *
  * Arguments:
- *  SIP_DialogData * - the current dialog
+ *  SIP_DialogData & - the current dialog
  *
  *
  * Returns:
@@ -374,23 +358,21 @@ static bool SIP_checkMediaChange(const SIPMsg* sipMsg, const SIP_DialogData* dia
  *   false: the channel has not been ignored
  *
  ********************************************************************/
-static int SIP_ignoreChannels(SIP_DialogData* dialog, Packet* p, SIP_PROTO_CONF* config)
+static int SIP_ignoreChannels(const SIP_DialogData& dialog, Packet* p, SIP_PROTO_CONF* config)
 {
-    SIP_MediaData* mdataA,* mdataB;
-
     if (0 == config->ignoreChannel)
         return false;
 
     // check the first media session
-    if (nullptr == dialog->mediaSessions)
+    if (nullptr == dialog.mediaSessions)
         return false;
 
     // check the second media session
-    if (nullptr == dialog->mediaSessions->nextS)
+    if (nullptr == dialog.mediaSessions->nextS)
         return false;
 
-    mdataA = dialog->mediaSessions->medias;
-    mdataB = dialog->mediaSessions->nextS->medias;
+    SIP_MediaData* mdataA = dialog.mediaSessions->medias;
+    SIP_MediaData* mdataB = dialog.mediaSessions->nextS->medias;
     sip_stats.ignoreSessions++;
     while ((nullptr != mdataA)&&(nullptr != mdataB))
     {
@@ -424,7 +406,7 @@ static int SIP_ignoreChannels(SIP_DialogData* dialog, Packet* p, SIP_PROTO_CONF*
  * Compare two media list
  *
  * Arguments:
- *  SIPMsg * - the message used to create a dialog
+ *  SIPMsg & - the message used to create a dialog
  *  SIP_DialogData * - the current dialog location
  *  SIP_DialogList * - the dialogs to be added.
  *
@@ -462,21 +444,20 @@ static int SIP_compareMedias(const SIP_MediaDataList mlistA, const SIP_MediaData
  *
  * Arguments:
  *  SIP_MediaSession*  - media session
- *  SIP_MediaList*     - media session list to be updated,
+ *  SIP_MediaList&     - media session list to be updated,
  *
  * Returns:
  *
  ********************************************************************/
-static void SIP_updateMedias(SIP_MediaSession* mSession, SIP_MediaList* dList)
+static void SIP_updateMedias(SIP_MediaSession* mSession, SIP_MediaList& dList)
 {
-    SIP_MediaSession* currSession, * preSession = nullptr;
-
     if (nullptr == mSession)
         return;
 
     mSession->savedFlag = SIP_SESSION_SAVED;
     // Find out the media session based on session id
-    currSession = *dList;
+    SIP_MediaSession* currSession = dList;
+    SIP_MediaSession* preSession = nullptr;
     while (nullptr != currSession)
     {
         if (currSession->sessionID == mSession->sessionID)
@@ -488,8 +469,8 @@ static void SIP_updateMedias(SIP_MediaSession* mSession, SIP_MediaList* dList)
     // if this is a new session data, add to the list head
     if (nullptr == currSession)
     {
-        mSession->nextS = *dList;
-        *dList = mSession;
+        mSession->nextS = dList;
+        dList = mSession;
     }
     else
     {
@@ -497,7 +478,7 @@ static void SIP_updateMedias(SIP_MediaSession* mSession, SIP_MediaList* dList)
         mSession->nextS = currSession->nextS;
         // if this is the header, update the new header
         if (nullptr == preSession)
-            *dList = mSession;
+            dList = mSession;
         else
             preSession->nextS = mSession;
 
@@ -513,7 +494,7 @@ static void SIP_updateMedias(SIP_MediaSession* mSession, SIP_MediaList* dList)
  * Add a sip dialog before the current dialog
  *
  * Arguments:
- *  SIPMsg * - the message used to create a dialog
+ *  SIPMsg & - the message used to create a dialog
  *  SIP_DialogData * - the current dialog location
  *  SIP_DialogList * - the dialogs to be added.
  *
@@ -521,13 +502,11 @@ static void SIP_updateMedias(SIP_MediaSession* mSession, SIP_MediaList* dList)
  * Returns: None
  *
  ********************************************************************/
-static SIP_DialogData* SIP_addDialog(SIPMsg* sipMsg, SIP_DialogData* currDialog,
+static SIP_DialogData* SIP_addDialog(const SIPMsg& sipMsg, SIP_DialogData* currDialog,
     SIP_DialogList* dList)
 {
-    SIP_DialogData* dialog;
-
     sip_stats.dialogs++;
-    dialog = (SIP_DialogData*)snort_calloc(sizeof(SIP_DialogData));
+    SIP_DialogData* dialog = (SIP_DialogData*)snort_calloc(sizeof(SIP_DialogData));
 
     // Add to the head
     dialog->nextD = currDialog;
@@ -546,11 +525,11 @@ static SIP_DialogData* SIP_addDialog(SIPMsg* sipMsg, SIP_DialogData* currDialog,
         dialog->prevD = nullptr;
         dList->head = dialog;
     }
-    dialog->dlgID = sipMsg->dlgID;
-    dialog->creator = sipMsg->methodFlag;
+    dialog->dlgID = sipMsg.dlgID;
+    dialog->creator = sipMsg.methodFlag;
     dialog->state = SIP_DLG_CREATE;
 
-    SIP_updateMedias(sipMsg->mediaSession, &dialog->mediaSessions);
+    SIP_updateMedias(sipMsg.mediaSession, dialog->mediaSessions);
     dList->num_dialogs++;
     return dialog;
 }
@@ -573,7 +552,7 @@ static int SIP_deleteDialog(SIP_DialogData* currDialog, SIP_DialogList* dList)
         return false;
 
     // If this is the header
-    if (nullptr ==  currDialog->prevD)
+    if (nullptr == currDialog->prevD)
     {
         if (nullptr != currDialog->nextD)
             currDialog->nextD->prevD = nullptr;
@@ -595,7 +574,7 @@ static int SIP_deleteDialog(SIP_DialogData* currDialog, SIP_DialogList* dList)
 }
 
 static void sip_publish_data_bus(
-    const Packet* p, const SIPMsg* sip_msg, const SIP_DialogData* dialog)
+    const Packet* p, const SIPMsg& sip_msg, const SIP_DialogData* dialog)
 {
     SipEvent event(p, sip_msg, dialog);
     DataBus::publish(SIPData::pub_id, SipEventIds::DIALOG, event, p->flow);
@@ -608,29 +587,28 @@ static void sip_publish_data_bus(
  *  If not in the current list, created one and add it to the head.
  *
  * Arguments:
- *  SIPMsg *        - sip message
+ *  SIPMsg &        - sip message
  *  SIP_DialogList* - dialog list to be updated,
  *
  * Returns:
  *  true: dialog has been updated
  *  false: dialog has not been updated
  ********************************************************************/
-int SIP_updateDialog(SIPMsg* sipMsg, SIP_DialogList* dList, Packet* p, SIP_PROTO_CONF* config)
+int SIP_updateDialog(SIPMsg& sipMsg, SIP_DialogList* dList, Packet* p, SIP_PROTO_CONF* config)
 {
-    SIP_DialogData* dialog;
     SIP_DialogData* oldDialog = nullptr;
     int ret;
 
-    if ((nullptr == sipMsg)||(0 == sipMsg->dlgID.callIdHash))
+    if (0 == sipMsg.dlgID.callIdHash)
         return false;
 
-    dialog = dList->head;
+    SIP_DialogData* dialog = dList->head;
 
     /*Find out the dialog in the dialog list*/
 
     while (nullptr != dialog)
     {
-        if (sipMsg->dlgID.callIdHash == dialog->dlgID.callIdHash)
+        if (sipMsg.dlgID.callIdHash == dialog->dlgID.callIdHash)
             break;
 
         oldDialog = dialog;
@@ -646,16 +624,14 @@ int SIP_updateDialog(SIPMsg* sipMsg, SIP_DialogList* dList, Packet* p, SIP_PROTO
 
     /*Update the  dialog information*/
 
-    if (sipMsg->status_code == 0)
+    if (sipMsg.status_code == 0)
         ret = SIP_processRequest(sipMsg, dialog, dList, p, config);
-    else if (sipMsg->status_code > 0)
-        ret = SIP_processResponse(sipMsg, dialog, dList, p, config);
     else
-        ret = false;
+        ret = SIP_processResponse(sipMsg, dialog, dList, p, config);
 
     for (dialog = dList->head; dialog; dialog = dialog->nextD)
     {
-        if (sipMsg->dlgID.callIdHash == dialog->dlgID.callIdHash)
+        if (sipMsg.dlgID.callIdHash == dialog->dlgID.callIdHash)
             break;
     }
     sip_publish_data_bus(p, sipMsg, dialog);
index 1253d082f5dabaae1859ec41668f33bbed6193d5..79072857884a6076e4b8ad06a48216c9ea8e7895 100644 (file)
@@ -57,7 +57,7 @@ struct SIP_DialogList
     uint32_t num_dialogs;
 };
 
-int SIP_updateDialog(SIPMsg* sipMsg, SIP_DialogList* dList, snort::Packet* p, SIP_PROTO_CONF*);
+int SIP_updateDialog(SIPMsg& sipMsg, SIP_DialogList* dList, snort::Packet* p, SIP_PROTO_CONF*);
 void sip_freeDialogs(SIP_DialogList* list);
 
 #endif
index 0f7ee27feeff5c79c04d823f959ab12100a39cb7..303c4dcdc2ed08261fb8f901aa72324209ccceba 100644 (file)
@@ -955,12 +955,14 @@ static const uint8_t* SMTP_HandleCommand(SmtpProtoConf* config, Packet* p, SMTPD
                     while ((last < eolm) && isspace((int)*last))
                         last++;
 
+                    // cppcheck-suppress knownConditionTrueFalse
                     if (((eolm - last) >= 4)
                         && (strncasecmp("LAST", (const char*)last, 4) == 0))
                     {
                         bdat_last = true;
                     }
 
+                    // cppcheck-suppress knownConditionTrueFalse
                     if (bdat_last || (dat_chunk == 0))
                         smtp_ssn->state_flags &= ~(SMTP_FLAG_BDAT);
                     else
@@ -1565,7 +1567,7 @@ void Smtp::show(const SnortConfig*) const
 
 void Smtp::eval(Packet* p)
 {
-    Profile profile(smtpPerfStats);
+    Profile profile(smtpPerfStats); // cppcheck-suppress unreadVariable
 
     // precondition - what we registered for
     assert(p->has_tcp_data());
index 254c47565fb8405b03ac1cba3cfa534cd08c759c..0283ef7e33a194c101dac30610f06b9191e0a126 100644 (file)
 using namespace snort;
 using namespace std;
 
-SmtpCmd::SmtpCmd(const std::string& key, uint32_t flg, int num)
-{
-    name = key;
-    flags = flg;
-    number = num;
-}
+SmtpCmd::SmtpCmd(const std::string& key, uint32_t flg, int num) : name(key), flags(flg), number(num)
+{ }
 
-SmtpCmd::SmtpCmd(const std::string& key, int num)
+SmtpCmd::SmtpCmd(const std::string& key, int num) : name(key), flags(PCMD_ALT), number(0)
 {
-    name = key;
-
-    flags = PCMD_ALT;
-    number = 0;
-
     if ( num >= 0 )
     {
         number = num;
@@ -181,9 +172,7 @@ static const RuleMap smtp_rules[] =
 //-------------------------------------------------------------------------
 
 SmtpModule::SmtpModule() : Module(SMTP_NAME, SMTP_HELP, s_params)
-{
-    config = nullptr;
-}
+{ }
 
 SmtpModule::~SmtpModule()
 {
index e9cf062cb7953f402c720a907095fbf4364c947b..a2b9bc08ef141cb1242d15de9534152238fd3213 100644 (file)
@@ -109,10 +109,10 @@ private:
     void add_commands(snort::Value&, uint32_t flags);
 
 private:
-    SmtpProtoConf* config;
+    SmtpProtoConf* config = nullptr;
     std::vector<SmtpCmd*> cmds;
     std::string names;
-    int number;
+    int number = 0;
 };
 
 #endif
index a6a648a382bf726e23c4d0169d7baf105fd82d83..feecd3137ed3c0bfe8e6607780bb3ea152683621 100644 (file)
@@ -99,13 +99,13 @@ static char get_xlink_keyword(const uint8_t* ptr, const uint8_t* end)
 
     len = end - ptr;
 
-    if (len > 5 && strncasecmp((const char*)ptr, "FIRST", 5) == 0)
+    // cppcheck-suppress knownConditionTrueFalse
+    if (len > 5)
     {
-        return XLINK_FIRST;
-    }
-    else if (len > 5 && strncasecmp((const char*)ptr, "CHUNK", 5) == 0)
-    {
-        return XLINK_CHUNK;
+        if (strncasecmp((const char*)ptr, "FIRST", 5) == 0)
+            return XLINK_FIRST;
+        if (strncasecmp((const char*)ptr, "CHUNK", 5) == 0)
+            return XLINK_CHUNK;
     }
 
     return XLINK_OTHER;
index a5bcfe55c529af8cb959d8bb1f2571058484cfa2..1cf1b8052baa4395545e8544969408baf67599a0 100644 (file)
@@ -60,7 +60,6 @@ unsigned SshFlowData::inspector_id = 0;
 
 SshFlowData::SshFlowData() : FlowData(inspector_id)
 {
-    session = {};
     sshstats.concurrent_sessions++;
     if (sshstats.max_concurrent_sessions < sshstats.concurrent_sessions)
         sshstats.max_concurrent_sessions = sshstats.concurrent_sessions;
index 858dcd60da6aa3d0b0f53bf8e9b9aac1c4fb329f..65bf0f8a8a65e19504654f3f5378836f7b2c02a8 100644 (file)
@@ -108,7 +108,7 @@ public:
 
 public:
     static unsigned inspector_id;
-    SSHData session;
+    SSHData session = {};
 };
 
 #define SSH_BANNER "SSH-"
index eb669b5886e935cca7b2348c20035bd14d89065a..47cb775edf1d92ae540d0072960c6b30b0d926b3 100644 (file)
@@ -51,9 +51,8 @@ struct SslStateRuleOptionData
 class SslStateOption : public IpsOption
 {
 public:
-    SslStateOption(const SslStateRuleOptionData& c) :
-        IpsOption(s_name)
-    { ssod = c; }
+    SslStateOption(const SslStateRuleOptionData& c) : IpsOption(s_name), ssod(c)
+    { }
 
     uint32_t hash() const override;
     bool operator==(const IpsOption&) const override;
@@ -61,7 +60,7 @@ public:
     EvalStatus eval(Cursor&, Packet*) override;
 
 private:
-    SslStateRuleOptionData ssod = {};
+    SslStateRuleOptionData ssod;
 };
 
 //-------------------------------------------------------------------------
@@ -94,7 +93,7 @@ bool SslStateOption::operator==(const IpsOption& ips) const
 
 IpsOption::EvalStatus SslStateOption::eval(Cursor&, Packet* pkt)
 {
-    RuleProfile profile(sslStateRuleOptionPerfStats);
+    RuleProfile profile(sslStateRuleOptionPerfStats);   // cppcheck-suppress unreadVariable
 
     if ( !(pkt->packet_flags & PKT_REBUILT_STREAM) && !pkt->is_full_pdu() )
         return NO_MATCH;
index 39d9ca95d61492d022f61ad09a0ddc41c5a17bb1..9eedaf86ecfbc44eda708d373639cfb37c8e0ee3 100644 (file)
@@ -51,9 +51,8 @@ struct SslVersionRuleOptionData
 class SslVersionOption : public IpsOption
 {
 public:
-    SslVersionOption(const SslVersionRuleOptionData& c) :
-        IpsOption(s_name)
-    { svod = c; }
+    SslVersionOption(const SslVersionRuleOptionData& c) : IpsOption(s_name), svod(c)
+    { }
 
     uint32_t hash() const override;
     bool operator==(const IpsOption&) const override;
@@ -61,7 +60,7 @@ public:
     EvalStatus eval(Cursor&, Packet*) override;
 
 private:
-    SslVersionRuleOptionData svod = {};
+    SslVersionRuleOptionData svod;
 };
 
 //-------------------------------------------------------------------------
@@ -94,7 +93,7 @@ bool SslVersionOption::operator==(const IpsOption& ips) const
 
 IpsOption::EvalStatus SslVersionOption::eval(Cursor&, Packet* pkt)
 {
-    RuleProfile profile(sslVersionRuleOptionPerfStats);
+    RuleProfile profile(sslVersionRuleOptionPerfStats); // cppcheck-suppress unreadVariable
 
     if ( !(pkt->packet_flags & PKT_REBUILT_STREAM) && !pkt->is_full_pdu() )
         return NO_MATCH;
index 032cbf51d510ff41302f4bfe614a01ad7c3a8f6f..5d49d0f49cdb04864b419398fa3ec06412a57f3a 100644 (file)
@@ -284,7 +284,7 @@ static inline void SSLPP_process_other(SSL_PROTO_CONF* config, SSLData* sd, uint
 
 static void snort_ssl(SSL_PROTO_CONF* config, Packet* p)
 {
-    Profile profile(sslPerfStats);
+    Profile profile(sslPerfStats);  // cppcheck-suppress unreadVariable
 
     /* Attempt to get a previously allocated SSL block. */
     SSLData* sd = SslBaseFlowData::get_ssl_session_data(p->flow);
index 7219337028dd4dd9d0d522e77a58ba892bf67fd6..7b7423b99c997db58646e51a0bf7d81cf9a93e5b 100644 (file)
 #include "config.h"
 #endif
 
+#include <algorithm>
+
 #include "curse_book.h"
 
 using namespace std;
 
 // map between service and curse details
-vector<CurseDetails> CurseBook::curse_map = 
+vector<CurseDetails> CurseBook::curse_map =
 {
     // name         service        alg                          is_tcp
     { "dce_udp"   , "dcerpc"     , CurseBook::dce_udp_curse   , false },
@@ -40,20 +42,20 @@ vector<CurseDetails> CurseBook::curse_map =
 
 bool CurseBook::add_curse(const char* key)
 {
-    for ( const CurseDetails& curse : curse_map )
-    {
-        if ( curse.name == key )
+    return std::cend(curse_map) != std::find_if(std::cbegin(curse_map), std::cend(curse_map),
+        [this, key](const CurseDetails& curse)
         {
-            if ( curse.is_tcp )
-                tcp_curses.emplace_back(&curse);
-            else
-                non_tcp_curses.emplace_back(&curse);
-
-            return true;
-        }
-    }
+            if ( curse.name == key )
+            {
+                if ( curse.is_tcp )
+                    tcp_curses.emplace_back(&curse);
+                else
+                    non_tcp_curses.emplace_back(&curse);
 
-    return false;
+                return true;
+            }
+            return false;
+        });
 }
 
 const vector<const CurseDetails*>& CurseBook::get_curses(bool tcp) const
index 2201fd0b9a48329e721352f594a22f8264a70f10..ccd1bffac8e835cdb2790b3846f7878fa08117bb 100644 (file)
@@ -80,7 +80,7 @@ bool HexBook::translate(const char* in, HexVector& out)
 //-------------------------------------------------------------------------
 
 void HexBook::add_spell(
-    const char* key, const char* val, HexVector& hv, unsigned i, MagicPage* p)
+    const char* key, const char* val, const HexVector& hv, unsigned i, MagicPage* p)
 {
     while ( i < hv.size() )
     {
index b9477eb95cc781801eb655007d8e2b97ba6bf6f7..889a0c62d0dabd19ac057be63c993964af2867a5 100644 (file)
@@ -98,7 +98,7 @@ public:
 
 private:
     bool translate(const char*, HexVector&);
-    void add_spell(const char*, const char*, HexVector&, unsigned, MagicPage*);
+    void add_spell(const char*, const char*, const HexVector&, unsigned, MagicPage*);
     const MagicPage* find_spell(const uint8_t*, unsigned, const MagicPage*, unsigned,
         const MagicPage*&) const override;
 };
@@ -117,7 +117,7 @@ public:
 
 private:
     bool translate(const char*, HexVector&);
-    void add_spell(const char*, const char*, HexVector&, unsigned, MagicPage*);
+    void add_spell(const char*, const char*, const HexVector&, unsigned, MagicPage*);
     const MagicPage* find_spell(const uint8_t*, unsigned, const MagicPage*, unsigned,
         const MagicPage*&) const override;
 };
index e701c8942d3575b8ffe6d488096ecf55cc75d95a..7bf71ac1b67b3029643f49b11b0c4d53897cdb6c 100644 (file)
@@ -78,7 +78,7 @@ bool SpellBook::translate(const char* in, HexVector& out)
 }
 
 void SpellBook::add_spell(
-    const char* key, const char* val, HexVector& hv, unsigned i, MagicPage* p)
+    const char* key, const char* val, const HexVector& hv, unsigned i, MagicPage* p)
 {
     while ( i < hv.size() )
     {
index 7c965706f4a28f686bf528ae194bf6c4b787ba21..8f342e1331b763b491871c813fb0ee638ac9c1ef 100644 (file)
@@ -214,19 +214,19 @@ TEST_CASE("sslv2 detect", "[SslV2Curse]")
                 if ( (i + incr_by - 1) < max_detect )
                 {
                     CHECK(tracker.ssl.state == static_cast<SSL_State>(i));
-                    CHECK_FALSE(CurseBook::ssl_v2_curse(&ch[i],sizeof(uint8_t) * incr_by,&tracker));
+                    CHECK(false == CurseBook::ssl_v2_curse(&ch[i],sizeof(uint8_t) * incr_by,&tracker));
                 }
                 else
                 {
-                    CHECK(CurseBook::ssl_v2_curse(&ch[i],sizeof(uint8_t) * incr_by,&tracker));
-                    CHECK(tracker.ssl.state == SSL_STATE__SSL_FOUND);
+                    CHECK(true == CurseBook::ssl_v2_curse(&ch[i],sizeof(uint8_t) * incr_by,&tracker));
+                    CHECK(SSL_STATE__SSL_FOUND == tracker.ssl.state);
                 }
 
                 i += incr_by;
             }
             // subsequent checks must return found
-            CHECK(CurseBook::ssl_v2_curse(&ch[max_detect + 1],sizeof(uint8_t),&tracker));
-            CHECK(tracker.ssl.state == SSL_STATE__SSL_FOUND);
+            CHECK(true == CurseBook::ssl_v2_curse(&ch[max_detect + 1],sizeof(uint8_t),&tracker));
+            CHECK(SSL_STATE__SSL_FOUND == tracker.ssl.state);
         };
 
     // sslv2 with ssl version 2
@@ -273,17 +273,17 @@ TEST_CASE("sslv2 not found", "[SslV2Curse]")
                 if ( i < fail_at_byte )
                 {
                     CHECK(tracker.ssl.state == static_cast<SSL_State>(i));
-                    CHECK_FALSE(CurseBook::ssl_v2_curse(&ch_data[i],sizeof(uint8_t),&tracker));
+                    CHECK(false == CurseBook::ssl_v2_curse(&ch_data[i],sizeof(uint8_t),&tracker));
                 }
                 else
                 {
-                    CHECK_FALSE(CurseBook::ssl_v2_curse(&ch_data[i],sizeof(uint8_t),&tracker));
-                    CHECK(tracker.ssl.state == SSL_STATE__SSL_NOT_FOUND);
+                    CHECK(false == CurseBook::ssl_v2_curse(&ch_data[i],sizeof(uint8_t),&tracker));
+                    CHECK(SSL_STATE__SSL_NOT_FOUND == tracker.ssl.state);
                 }
             }
             // subsequent checks must return ssl not found
-            CHECK_FALSE(CurseBook::ssl_v2_curse(&ch_data[max_detect + 1],sizeof(uint8_t),&tracker));
-            CHECK(tracker.ssl.state == SSL_STATE__SSL_NOT_FOUND);
+            CHECK(false == CurseBook::ssl_v2_curse(&ch_data[max_detect + 1],sizeof(uint8_t),&tracker));
+            CHECK(SSL_STATE__SSL_NOT_FOUND == tracker.ssl.state);
         };
 
     SECTION("byte 0"){ test(0);}
index 8cc4e4428ccdd48d5a6405ec9e77c13653c9a867..5c7eb12299cc255066e632b8560711f2fe10a659 100644 (file)
@@ -76,7 +76,7 @@ private:
     std::string service;
     std::vector<std::string> c2s_patterns;
     std::vector<std::string> s2c_patterns;
-    bool c2s;
+    bool c2s = false;
 
     MagicBook* c2s_hexes = nullptr;
     MagicBook* s2c_hexes = nullptr;
@@ -87,7 +87,7 @@ private:
     CurseBook* curses = nullptr;
     uint16_t max_search_depth = 0;
 
-    MagicBook::ArcaneType proto;
+    MagicBook::ArcaneType proto = MagicBook::ArcaneType::MAX;
 };
 
 #endif
index 7919f622cacf04c68d31d25d759e5ae4a7bad633..1e23938b241dfcd743abb751c8b8334f380eac77 100644 (file)
@@ -189,7 +189,7 @@ StreamSplitter::Status MagicSplitter::scan(
     Packet* pkt, const uint8_t* data, uint32_t len,
     uint32_t, uint32_t*)
 {
-    Profile profile(wizPerfStats);
+    Profile profile(wizPerfStats);  // cppcheck-suppress unreadVariable
     count_scan(pkt->flow);
 
     bytes_scanned += len;
@@ -293,7 +293,7 @@ void Wizard::reset(Wand& w, bool c2s, MagicBook::ArcaneType proto)
 
 void Wizard::eval(Packet* p)
 {
-    Profile profile(wizPerfStats);
+    Profile profile(wizPerfStats);  // cppcheck-suppress unreadVariable
 
     if ( !p->is_udp() )
         return;
index 271a0b4dafb3e5a3c2cce220ee4b69f461f07a6b..7f65154cc6576b0e4ccb9eeffee70fc97b76f8c3 100644 (file)
@@ -67,7 +67,7 @@ struct SO_PUBLIC SfCidr
 
 private:
     SfIp addr;
-    uint16_t bits;
+    uint16_t bits = 0;
 } __attribute__((__packed__));
 
 
index 6103055552432407cfa5d996a90468dc213bcfaa..6a802becc85c29721a0e63c9c412b1e897a3d574 100644 (file)
@@ -135,7 +135,7 @@ static inline int _count_bits(unsigned int val)
  * into a number of bits to mask off */
 static inline int _netmask_str_to_bit_count(char* mask, int family)
 {
-    uint32_t buf[4];
+    uint32_t buf[4] = {};
     int bits, i, nBits, nBytes;
     uint8_t* bytes = (uint8_t*)buf;
 
index 9cdb1225f6d0cff779615711b1dfc3fc5ad3516a..84ea09dc4169ad59f694708659a38e3103a98e75 100644 (file)
@@ -48,7 +48,7 @@ using namespace snort;
 #define LIST_CLOSE ']'
 
 static SfIpRet sfvar_list_compare(sfip_node_t*, sfip_node_t*);
-static inline void sfip_node_free(sfip_node_t*);
+static inline void sfip_node_free(sfip_node_t*&);
 static inline void sfip_node_freelist(sfip_node_t*);
 
 static inline sfip_var_t* _alloc_var()
@@ -158,7 +158,7 @@ static sfip_node_t* sfipnode_alloc(const char* str, SfIpRet* status)
     return ret;
 }
 
-static inline void sfip_node_free(sfip_node_t* node)
+static inline void sfip_node_free(sfip_node_t*& node)
 {
     if ( !node )
         return;
@@ -167,6 +167,7 @@ static inline void sfip_node_free(sfip_node_t* node)
         delete node->ip;
 
     snort_free(node);
+    node = nullptr;
 }
 
 static inline void sfip_node_freelist(sfip_node_t* root)
@@ -290,9 +291,6 @@ sfip_var_t* sfvar_deep_copy(const sfip_var_t* var)
 static sfip_node_t* merge_lists(sfip_node_t* list1, sfip_node_t* list2, uint16_t list1_len,
     uint16_t list2_len, uint32_t& merge_len)
 {
-    sfip_node_t* listHead = nullptr, * merge_list = nullptr, * tmp = nullptr, * node = nullptr;
-    uint32_t num_nodes = 0;
-
     if (!list1 && !list2)
     {
         merge_len = 0;
@@ -324,12 +322,15 @@ static sfip_node_t* merge_lists(sfip_node_t* list1, sfip_node_t* list2, uint16_t
         return list2;
     }
 
+    sfip_node_t* listHead = nullptr;
+    sfip_node_t* merge_list = nullptr;
+    uint32_t num_nodes = 0;
     /*Iterate till one of the list is null. Append each node to merge_list*/
     while (list1 && list2)
     {
         if ( num_nodes )
         {
-            tmp = list1->next;
+            sfip_node_t* tmp = list1->next;
             if ( list_contains_node(listHead, merge_list, num_nodes, list1) )
             {
                 list1 = tmp;
@@ -347,6 +348,7 @@ static sfip_node_t* merge_lists(sfip_node_t* list1, sfip_node_t* list2, uint16_t
         }
 
         SfIpRet ret = list1->ip->compare(*(list2->ip));
+        sfip_node_t* node;
         if (ret == SFIP_LESSER)
         {
             node = list1;
@@ -364,7 +366,7 @@ static sfip_node_t* merge_lists(sfip_node_t* list1, sfip_node_t* list2, uint16_t
             node = list1;
             list1 = list1->next;
             /*Free the duplicate node*/
-            tmp = list2->next;
+            sfip_node_t* tmp = list2->next;
             sfip_node_free(list2);
             list2 = tmp;
 
@@ -391,7 +393,7 @@ static sfip_node_t* merge_lists(sfip_node_t* list1, sfip_node_t* list2, uint16_t
     /*list2 is null. Append list1*/
     while ( list1 )
     {
-        tmp = list1->next;
+        sfip_node_t* tmp = list1->next;
         if ( !list_contains_node(listHead, merge_list, num_nodes, list1) and merge_list )
         {
             merge_list->next = list1;
@@ -404,7 +406,7 @@ static sfip_node_t* merge_lists(sfip_node_t* list1, sfip_node_t* list2, uint16_t
     /*list1 is null. Append list2*/
     while ( list2 )
     {
-        tmp = list2->next;
+        sfip_node_t* tmp = list2->next;
         if ( !list_contains_node(listHead, merge_list, num_nodes, list2) and merge_list )
         {
             merge_list->next = list2;
@@ -1208,9 +1210,10 @@ TEST_CASE("SfIpVarListMerge", "[SfIpVar]")
     SECTION("basic list merge")
     {
         table = sfvt_alloc_table();
-        CHECK(sfvt_add_str(table, "foo [ 192.168.0.1, 192.168.5.0, 192.168.0.2, 255.255.248.0 ] ",
-            &var1) == SFIP_SUCCESS);
-        CHECK(sfvt_add_str(table, "goo [ 255.255.241.0, 192.168.2.1] ", &var2) == SFIP_SUCCESS);
+        SfIpRet ret = sfvt_add_str(table, "foo [ 192.168.0.1, 192.168.5.0, 192.168.0.2, 255.255.248.0 ] ", &var1);
+        CHECK( SFIP_SUCCESS == ret);
+        ret = sfvt_add_str(table, "goo [ 255.255.241.0, 192.168.2.1] ", &var2);
+        CHECK( SFIP_SUCCESS == ret);
         print_var_list(var1->head);
         CHECK(!strcmp("192.168.0.1,192.168.0.2,192.168.5.0,255.255.248.0", sfipvar_test_buff));
         print_var_list(var2->head);
@@ -1353,12 +1356,16 @@ TEST_CASE("SfIpVarListMerge", "[SfIpVar]")
         table = sfvt_alloc_table();
 
         // 'foo' variable
-        CHECK(sfvt_add_str(table, "foo 1.0.0.1", &var1) == SFIP_SUCCESS);
+        SfIpRet ret = sfvt_add_str(table, "foo 1.0.0.1", &var1);
+        CHECK(SFIP_SUCCESS == ret);
 
         // no table used
-        CHECK(sfvt_add_to_var(nullptr, var2, "1.0.0.2") == SFIP_SUCCESS);
-        CHECK(sfvt_add_to_var(nullptr, var2, "$foo") == SFIP_LOOKUP_UNAVAILABLE);
-        CHECK(sfvt_add_to_var(nullptr, var2, "$moo") == SFIP_LOOKUP_UNAVAILABLE);
+        ret = sfvt_add_to_var(nullptr, var2, "1.0.0.2");
+        CHECK(SFIP_SUCCESS == ret);
+        ret = sfvt_add_to_var(nullptr, var2, "$foo");
+        CHECK(SFIP_LOOKUP_UNAVAILABLE == ret);
+        ret = sfvt_add_to_var(nullptr, var2, "$moo");
+        CHECK(SFIP_LOOKUP_UNAVAILABLE == ret);
 
         print_var_list(var2->head);
         CHECK(!strcmp("1.0.0.2", sfipvar_test_buff));
@@ -1374,8 +1381,10 @@ TEST_CASE("SfIpVarListMerge", "[SfIpVar]")
         snort_free(ip);
 
         // using table
-        CHECK(sfvt_add_to_var(table, var2, "$foo") == SFIP_SUCCESS);
-        CHECK(sfvt_add_to_var(table, var2, "$moo") == SFIP_LOOKUP_FAILURE);
+        ret = sfvt_add_to_var(table, var2, "$foo");
+        CHECK(SFIP_SUCCESS == ret);
+        ret = sfvt_add_to_var(table, var2, "$moo");
+        CHECK(SFIP_LOOKUP_FAILURE == ret);
 
         print_var_list(var2->head);
         CHECK(!strcmp("1.0.0.1,1.0.0.2", sfipvar_test_buff));
@@ -1403,8 +1412,8 @@ TEST_CASE("SfIpVarCopyAddCompare", "[SfIpVar]")
     sfip_node_t* node;
 
     table = sfvt_alloc_table();
-    CHECK(sfvt_add_str(table, "foo [ 192.168.0.1, 192.168.5.0, 192.168.0.2, 255.255.248.0 ] ",
-        &var1) == SFIP_SUCCESS);
+    SfIpRet ret = sfvt_add_str(table, "foo [ 192.168.0.1, 192.168.5.0, 192.168.0.2, 255.255.248.0 ] ", &var1);
+    CHECK(SFIP_SUCCESS == ret);
     print_var_list(var1->head);
     CHECK(!strcmp("192.168.0.1,192.168.0.2,192.168.5.0,255.255.248.0", sfipvar_test_buff));
     // deep copy the list
@@ -1415,7 +1424,8 @@ TEST_CASE("SfIpVarCopyAddCompare", "[SfIpVar]")
     // add a negate node to original list
     node = sfipnode_alloc("!192.168.3.2", nullptr);
     CHECK(node != nullptr);
-    CHECK(SFIP_SUCCESS == sfvar_add_node(var1, node, 1));
+    ret = sfvar_add_node(var1, node, 1);
+    CHECK(SFIP_SUCCESS == ret);
     print_var_list(var1->neg_head);
     CHECK(!strcmp("!192.168.3.2", sfipvar_test_buff));
     // now compare should fail
@@ -1424,7 +1434,8 @@ TEST_CASE("SfIpVarCopyAddCompare", "[SfIpVar]")
     // add a node
     node = sfipnode_alloc("192.168.90.9", nullptr);
     CHECK(node != nullptr);
-    CHECK(SFIP_SUCCESS == sfvar_add_node(var1, node, 0));
+    ret = sfvar_add_node(var1, node, 0);
+    CHECK(SFIP_SUCCESS == ret);
     print_var_list(var1->head);
     CHECK(!strcmp("192.168.0.1,192.168.0.2,192.168.5.0,192.168.90.9,255.255.248.0",
         sfipvar_test_buff));
@@ -1442,13 +1453,16 @@ TEST_CASE("SfIpVarAny", "[SfIpVar]")
 
     table = sfvt_alloc_table();
 
-    CHECK(sfvt_add_str(table, "foo [any] ", &var1) == SFIP_SUCCESS);
+    SfIpRet ret = sfvt_add_str(table, "foo [any] ", &var1);
+    CHECK(SFIP_SUCCESS == ret);
     print_var_list(var1->head);
     CHECK(!strcmp("any", sfipvar_test_buff));
 
     // try to add list to any
-    CHECK(sfvt_add_str(table, "goo [ 255.255.241.0, 192.168.2.1] ", &var2) == SFIP_SUCCESS);
-    CHECK(SFIP_SUCCESS == sfvar_add(var1, var2));
+    ret = sfvt_add_str(table, "goo [ 255.255.241.0, 192.168.2.1] ", &var2);
+    CHECK(SFIP_SUCCESS == ret);
+    ret= sfvar_add(var1, var2);
+    CHECK(SFIP_SUCCESS == ret);
     // adding something to any should not change any
     print_var_list(var1->head);
     CHECK(!strcmp("any", sfipvar_test_buff));
@@ -1456,7 +1470,8 @@ TEST_CASE("SfIpVarAny", "[SfIpVar]")
     // create a list and add any to it
     node = sfipnode_alloc("any", nullptr);
     CHECK(node != nullptr);
-    CHECK(SFIP_SUCCESS == sfvar_add_node(var1, node, 0));
+    ret = sfvar_add_node(var1, node, 0);
+    CHECK(SFIP_SUCCESS == ret);
 
     // after adding any, the original list should have any only
     print_var_list(var1->head);
index 6d5b968b513174e4f7b33ee362f6ef2d7e2591cf..68c8655ba97b9ade03a5a84154f7f9b1e47d2b92 100644 (file)
@@ -336,36 +336,32 @@ static int RunFunc(const char* func, const char* arg1, const char* arg2)
 
 //---------------------------------------------------------------
 
-static int FuncCheck(int i)
+static void print_func(int i, const char* status, const char* code, const FuncTest* f)
 {
-    FuncTest* f = ftests + i;
-    int result;
+    if ( f->arg2 )
+        printf("[%d] %s: %s(%s, %s) = %s\n",
+            i, status, f->func, f->arg1, f->arg2, code);
+    else
+        printf("[%d] %s: %s(%s) = %s\n",
+            i, status, f->func, f->arg1, code);
+}
 
-    const char* status = "Passed";
-    const char* code;
+static int FuncCheck(int i)
+{
+    const FuncTest* f = ftests + i;
 
-    result = RunFunc(f->func, f->arg1, f->arg2);
+    int result = RunFunc(f->func, f->arg1, f->arg2);
 
-    code = (0 <= result && (size_t)result < sizeof(codes)/sizeof(codes[0])) ?
+    const char* code = (0 <= result && (size_t)result < sizeof(codes)/sizeof(codes[0])) ?
         codes[result] : "uh oh";
 
     if ( result != f->expected )
-    {
-        status = "Failed";
-    }
-#ifndef SFIP_TEST_DEBUG
-    if ( result != f->expected )
-    {
-#endif
-        if ( f->arg2 )
-            printf("[%d] %s: %s(%s, %s) = %s\n",
-                i, status, f->func, f->arg1, f->arg2, code);
-        else
-            printf("[%d] %s: %s(%s) = %s\n",
-                i, status, f->func, f->arg1, code);
-#ifndef SFIP_TEST_DEBUG
-    }
+        print_func(i, "Failed", code, f);
+#ifdef SFIP_TEST_DEBUG
+    else
+        print_func(i, "Passed", code, f);
 #endif
+
     return result == f->expected;
 }
 
index 52ffc4f193a1a6723ee770568249550db61120ce..8fb10a70412026e5df5043f6103c4af01aedcf0c 100644 (file)
@@ -114,7 +114,7 @@ TABLE_PTR RtTable::sfrt_dir_flat_new(uint32_t mem_cap, int count,...)
     va_list ap;
     int index;
     TABLE_PTR table_ptr;
-    dir_table_flat_t* table;
+    dir_table_flat_t* tmp_table;
     uint8_t* base;
 
     table_ptr = segment_snort_alloc(sizeof(dir_table_flat_t));
@@ -125,35 +125,35 @@ TABLE_PTR RtTable::sfrt_dir_flat_new(uint32_t mem_cap, int count,...)
     }
 
     base = (uint8_t*)segment_basePtr();
-    table = (dir_table_flat_t*)(&base[table_ptr]);
+    tmp_table = (dir_table_flat_t*)(&base[table_ptr]);
 
-    table->allocated = 0;
+    tmp_table->allocated = 0;
 
-    table->dim_size = count;
+    tmp_table->dim_size = count;
 
     va_start(ap, count);
 
     for (index=0; index < count; index++)
     {
         uint32_t val = va_arg(ap, int);
-        table->dimensions[index] = val;
+        tmp_table->dimensions[index] = val;
     }
 
     va_end(ap);
 
-    table->mem_cap = mem_cap;
+    tmp_table->mem_cap = mem_cap;
 
-    table->cur_num = 0;
+    tmp_table->cur_num = 0;
 
-    table->sub_table = _sub_table_flat_new(table, 0, 0, 0);
+    tmp_table->sub_table = _sub_table_flat_new(tmp_table, 0, 0, 0);
 
-    if (!table->sub_table)
+    if (!tmp_table->sub_table)
     {
         segment_free(table_ptr);
         return 0;
     }
 
-    table->allocated += sizeof(dir_table_flat_t) + sizeof(int)*count;
+    tmp_table->allocated += sizeof(dir_table_flat_t) + sizeof(int)*count;
 
     return table_ptr;
 }
@@ -472,25 +472,25 @@ return_codes RtTable::sfrt_dir_flat_insert(const uint32_t* addr, int /* numAddrD
     {
         h_addr[1] = ntohl(addr[1]);
         h_addr[2] = ntohl(addr[2]);
-        h_addr[3] = ntohl(addr[3]);
+        h_addr[3] = ntohl(addr[3]); // cppcheck-suppress unreadVariable
     }
     else if (len > 64)
     {
         h_addr[1] = ntohl(addr[1]);
         h_addr[2] = ntohl(addr[2]);
-        h_addr[3] = 0;
+        h_addr[3] = 0;  // cppcheck-suppress unreadVariable
     }
     else if (len > 32)
     {
         h_addr[1] = ntohl(addr[1]);
         h_addr[2] = 0;
-        h_addr[3] = 0;
+        h_addr[3] = 0;  // cppcheck-suppress unreadVariable
     }
     else
     {
         h_addr[1] = 0;
         h_addr[2] = 0;
-        h_addr[3] = 0;
+        h_addr[3] = 0;  // cppcheck-suppress unreadVariable
     }
 
     /* Find the sub table in which to insert */
@@ -505,7 +505,7 @@ tuple_flat_t RtTable::_dir_sub_flat_lookup(IPLOOKUP* ip, TABLE_PTR table_ptr)
     word index;
     uint8_t* base = (uint8_t*)segment_basePtr();
     DIR_Entry* entry;
-    dir_sub_table_flat_t* table = (dir_sub_table_flat_t*)(&base[table_ptr]);
+    dir_sub_table_flat_t* tmp_table = (dir_sub_table_flat_t*)(&base[table_ptr]);
 
     {
         uint32_t local_index, i;
@@ -527,9 +527,9 @@ tuple_flat_t RtTable::_dir_sub_flat_lookup(IPLOOKUP* ip, TABLE_PTR table_ptr)
             i=3;
         }
         local_index = ip->addr[i] << (ip->bits %32);
-        index = local_index >> (ARCH_WIDTH - table->width);
+        index = local_index >> (ARCH_WIDTH - tmp_table->width);
     }
-    entry = (DIR_Entry*)(&base[table->entries]);
+    entry = (DIR_Entry*)(&base[tmp_table->entries]);
 
     if ( !entry[index].value || entry[index].length )
     {
@@ -539,7 +539,7 @@ tuple_flat_t RtTable::_dir_sub_flat_lookup(IPLOOKUP* ip, TABLE_PTR table_ptr)
         return ret;
     }
 
-    ip->bits += table->width;
+    ip->bits += tmp_table->width;
     return _dir_sub_flat_lookup(ip, entry[index].value);
 }
 
@@ -578,14 +578,14 @@ tuple_flat_t RtTable::sfrt_dir_flat_lookup(const uint32_t* addr, int numAddrDwor
 
 uint32_t RtTable::sfrt_dir_flat_usage(TABLE_PTR table_ptr) const
 {
-    dir_table_flat_t* table;
+    dir_table_flat_t* tmp_table;
     uint8_t* base;
     if (!table_ptr)
     {
         return 0;
     }
     base = (uint8_t*)segment_basePtr();
-    table = (dir_table_flat_t*)(&base[table_ptr]);
-    return ((dir_table_flat_t*)(table))->allocated;
+    tmp_table = (dir_table_flat_t*)(&base[table_ptr]);
+    return ((dir_table_flat_t*)(tmp_table))->allocated;
 }
 
index 7a5b773ddd381ccd9a107f4321a50ccaab122f5a..62502d07ee36339406e55f8206a72b323c027a4c 100644 (file)
@@ -26,6 +26,7 @@
 
 #include <sys/time.h>
 
+#include <algorithm>
 #include <cassert>
 
 #include "framework/counts.h"
@@ -57,26 +58,16 @@ static THREAD_LOCAL SCMaps* tls_maps;
 SideChannel* SideChannelManager::get_side_channel(SCPort port)
 {
     if ( tls_maps )
-        for ( auto& scm : * tls_maps )
-        {
-            if ( ( port <= scm->ports.size() ) && ( scm->ports.test(port) ) )
-            {
-                return scm->sc;
-            }
-        }
-
+    {
+        auto it = std::find_if(tls_maps->begin(), tls_maps->end(),
+            [port](const SideChannelMapping* scm)
+            { return port <= scm->ports.size() && scm->ports.test(port); });
+        if (it != tls_maps->end())
+            return (*it)->sc;
+    }
     return nullptr;
 }
 
-SideChannel::SideChannel()
-{
-    sequence = 0;
-    default_port = 0;
-    connector_receive = nullptr;
-    connector_transmit = nullptr;
-    receive_handler = nullptr;
-}
-
 void SideChannel::set_message_port(SCMessage* msg, SCPort port)
 {
     assert ( msg );
index e989aa69ee227933b8a02dcdb325ae29f22f65c5..bdf4f6728bd31e77c60fcf077d8a301a3531e9f8 100644 (file)
@@ -58,7 +58,7 @@ typedef std::function<void(SCMessage*)> SCProcessMsgFunc;
 class SideChannel
 {
 public:
-    SideChannel();
+    SideChannel() = default;
 
     void register_receive_handler(const SCProcessMsgFunc& handler);
     void unregister_receive_handler();
@@ -71,12 +71,12 @@ public:
     void set_default_port(SCPort port);
     snort::Connector::Direction get_direction();
 
-    snort::Connector* connector_receive;
-    snort::Connector* connector_transmit;
+    snort::Connector* connector_receive = nullptr;
+    snort::Connector* connector_transmit = nullptr;
 
 private:
-    SCSequence sequence;
-    SCPort default_port;
+    SCSequence sequence = 0;
+    SCPort default_port = 0;
     SCProcessMsgFunc receive_handler = nullptr;
 };
 
index 3b3c11a9400498b56a55781ecabb7bbc704cb9bb..ba7c975de9d467f73f69b85981ed95514450a24a 100644 (file)
@@ -179,8 +179,8 @@ public:
     StreamModuleConfig config;
 };
 
-StreamBase::StreamBase(const StreamModuleConfig* c)
-{ config = *c; }
+StreamBase::StreamBase(const StreamModuleConfig* c) : config(*c)
+{ }
 
 bool StreamBase::configure(SnortConfig*)
 {
index 8b63072fa9061411d812ad28f67dc28be67815db..b68f67e2e58c243c4b344f069ec98d615e3611af 100644 (file)
@@ -255,19 +255,13 @@ ProtocolHA::~ProtocolHA()
 {
     assert( proto_map );
 
-    for( auto map : *proto_map )
-    {
-        if ( map.second == this )
-        {
-            proto_map->erase(map.first);
-            break;
-        }
-    }
+    auto it = std::find_if(proto_map->cbegin(), proto_map->cend(),
+        [this](const std::pair<const int, ProtocolHA*>& map){ return map.second == this; });
+    if ( it != proto_map->cend() )
+        proto_map->erase((*it).first);
 
     if ( proto_map->empty() )
-    {
         delete proto_map;
-    }
 }
 
 void ProtocolHA::process_deletion(Flow& flow)
index bc890487372601ff3244e18fa11cedfea35649bb..677f41a44371045aaed07a80b301c6357a3ed106 100644 (file)
@@ -53,7 +53,7 @@ public:
     { return true; }
 
 public:
-    bool upload;
+    bool upload = false;
 };
 
 #endif
index e49e4b9a6e28af7930acb80f88aa16506d85284a..7e0ca1a2524fc799d2613f89d75b477fca92c3a5 100644 (file)
@@ -71,7 +71,7 @@ static FilePosition position(Packet* p)
 
 int FileSession::process(Packet* p)
 {
-    Profile profile(file_ssn_stats);
+    Profile profile(file_ssn_stats);    // cppcheck-suppress unreadVariable
 
     p->flow->ssn_state.snort_protocol_id = SNORT_PROTO_FILE;
     StreamFileConfig* c = get_file_cfg(p->flow->ssn_server);
index 8c5499a7b019e8eb31c4430dcec8c8508b36dc5b..585bce619fd3d57794e34668f3d95f9c3aae1a63 100644 (file)
@@ -32,15 +32,6 @@ public:
     void clear() override;
     int process(snort::Packet*) override;
 
-    bool is_sequenced(uint8_t /*dir*/) override
-    { return true; }
-
-    bool are_packets_missing(uint8_t /*dir*/) override
-    { return false; }
-
-    uint8_t missing_in_reassembled(uint8_t /*dir*/) override
-    { return SSN_MISSING_NONE; }
-
 private:
     void start(snort::Packet*, snort::Flow*);
     void update(snort::Packet*, snort::Flow*);
index 35a3d32e9fb05a1fa1299c5ac1cfca6a46cd619f..64d69246532936da11636d6c81f21b9a7b3dde02 100644 (file)
@@ -43,9 +43,7 @@ static const Parameter s_params[] =
 
 StreamIcmpModule::StreamIcmpModule() :
     Module(MOD_NAME, MOD_HELP, s_params)
-{
-    config = nullptr;
-}
+{ }
 
 ProfileStats* StreamIcmpModule::get_profile() const
 {
index 3ef68515f4b60199040588277ed4a9fadf0f2a1f..22bd86fbd8b3eb99d6a5593b6c93f3b484126c16 100644 (file)
@@ -24,6 +24,8 @@
 #include "flow/session.h"
 #include "framework/module.h"
 
+#include "stream_icmp.h"
+
 extern const PegInfo icmp_pegs[];
 extern THREAD_LOCAL struct IcmpStats icmpStats;
 extern THREAD_LOCAL snort::ProfileStats icmp_perf_stats;
@@ -45,12 +47,12 @@ struct IcmpStats
 #define MOD_NAME "stream_icmp"
 #define MOD_HELP "stream inspector for ICMP flow tracking"
 
-struct StreamIcmpConfig;
-
 class StreamIcmpModule : public snort::Module
 {
 public:
     StreamIcmpModule();
+    ~StreamIcmpModule() override
+    { delete config; }
     bool set(const char*, snort::Value&, snort::SnortConfig*) override;
     bool begin(const char*, int, snort::SnortConfig*) override;
     bool end(const char*, int, snort::SnortConfig*) override;
@@ -68,7 +70,7 @@ public:
     StreamIcmpConfig* get_data();
 
 private:
-    StreamIcmpConfig* config;
+    StreamIcmpConfig* config = nullptr;
 };
 
 #endif
index 3264ec07821dee990812e4a953744fd4d3a561df..eb6e5e3e704038eaa43b752193bcecfb0c6d5123 100644 (file)
@@ -33,8 +33,8 @@ public:
     void clear() override;
 
 public:
-    uint32_t echo_count;
-    struct timeval ssn_time;
+    uint32_t echo_count = 0;
+    struct timeval ssn_time = {};
 };
 
 void icmp_stats();
index 3e24545ef2c5a9c4e271594796f615b189131e6f..f421d93e3a1021461445d8ef2ec567fae966f849 100644 (file)
@@ -257,7 +257,7 @@ static inline bool frag_timed_out(
     const timeval* current_time, const timeval* start_time, FragEngine* engine)
 {
     struct timeval tv_diff;
-    TIMERSUB(current_time, start_time, &tv_diff);
+    TIMERSUB(current_time, start_time, &tv_diff);   // cppcheck-suppress unreadVariable
 
     if (tv_diff.tv_sec >= (int)engine->frag_timeout)
         return true;
@@ -1409,25 +1409,22 @@ left_overlap_last:
         trunc = 0;
         overlap = frag_end - right->offset;
 
-        if (overlap)
+        if (frag_end < ft->calculated_size ||
+            ((ft->frag_flags & FRAG_GOT_LAST) &&
+            frag_end != ft->calculated_size))
         {
-            if (frag_end < ft->calculated_size ||
-                ((ft->frag_flags & FRAG_GOT_LAST) &&
-                frag_end != ft->calculated_size))
+            if (!(p->ptrs.decode_flags & DECODE_MF))
             {
-                if (!(p->ptrs.decode_flags & DECODE_MF))
-                {
-                    /*
-                     * teardrop attack...
-                     */
-                    debug_log(stream_ip_trace, p, "[..] Teardrop attack!\n");
+                /*
+                    * teardrop attack...
+                    */
+                debug_log(stream_ip_trace, p, "[..] Teardrop attack!\n");
 
-                    EventAttackTeardrop(fe);
+                EventAttackTeardrop(fe);
 
-                    ft->frag_flags |= FRAG_BAD;
+                ft->frag_flags |= FRAG_BAD;
 
-                    return FRAG_INSERT_ATTACK;
-                }
+                return FRAG_INSERT_ATTACK;
             }
         }
 
index d9034e40c9020123cf049e081b411fcdc80a2fb3..ee06e2310eb4c3c1eed3ae33471259e8c0cdd7bb 100644 (file)
@@ -174,7 +174,7 @@ bool IpSession::setup(Packet* p)
 
 int IpSession::process(Packet* p)
 {
-    Profile profile(ip_perf_stats);
+    Profile profile(ip_perf_stats); // cppcheck-suppress unreadVariable
 
     if ( Stream::expired_flow(flow, p) )
     {
index 99d3e62337583ea07f33e8a4a8d929cd311ff625..87d751f61398004077b4c4274eddf8a12294375b 100644 (file)
@@ -86,7 +86,7 @@ public:
     bool check_alerted(snort::Packet*, uint32_t gid, uint32_t sid) override;
 
 public:
-    FragTracker tracker;
+    FragTracker tracker = {};
 };
 
 extern THREAD_LOCAL IpStats ip_stats;
index 0583db7a03c91204005df057926e8771b3286ae7..de3fcf722ee3d96b373a5cb66486d64ec86ce345 100644 (file)
@@ -250,7 +250,7 @@ int32_t paf_check (
     const uint8_t* data, uint32_t len, uint32_t total,
     uint32_t seq, uint32_t* flags)
 {
-    Profile profile(pafPerfStats);
+    Profile profile(pafPerfStats);  // cppcheck-suppress unreadVariable
     PafAux px;
 
     if ( !paf_initialized(ps) )
index 8764793e90c47012ce8c51e3da0bfa56ec822f8e..9508ac666add4645504391d8b4968983febb3b4f 100644 (file)
@@ -47,11 +47,11 @@ const StreamBuffer StreamSplitter::reassemble(
     if (n == 0)
         return { nullptr, 0 };
 
-    unsigned max;
-    uint8_t* pdu_buf = DetectionEngine::get_next_buffer(max);
-    max = max > Packet::max_dsize ? Packet::max_dsize : max;
+    unsigned tmp_max;
+    uint8_t* pdu_buf = DetectionEngine::get_next_buffer(tmp_max);
+    tmp_max = tmp_max > Packet::max_dsize ? Packet::max_dsize : tmp_max;
 
-    n = std::min(n, max - offset);
+    n = std::min(n, tmp_max - offset);
     /*
     FIXIT:
         - Extra bytes will be lost and will pass without inspection
index 23f74d34fad21de032056b13bbcc1f079f29b1e5..4c3440316e23fc8250edb5c24418487306a8681f 100644 (file)
@@ -53,9 +53,8 @@ struct StreamReassembleRuleOptionData
 class ReassembleOption : public IpsOption
 {
 public:
-    ReassembleOption(const StreamReassembleRuleOptionData& c) :
-        IpsOption(s_name)
-    { srod = c; }
+    ReassembleOption(const StreamReassembleRuleOptionData& c) : IpsOption(s_name), srod(c)
+    { }
 
     uint32_t hash() const override;
     bool operator==(const IpsOption&) const override;
@@ -104,7 +103,7 @@ bool ReassembleOption::operator==(const IpsOption& ips) const
 
 IpsOption::EvalStatus ReassembleOption::eval(Cursor&, Packet* pkt)
 {
-    RuleProfile profile(streamReassembleRuleOptionPerfStats);
+    RuleProfile profile(streamReassembleRuleOptionPerfStats);   // cppcheck-suppress unreadVariable
 
     if (!pkt->flow || !pkt->ptrs.tcph)
         return NO_MATCH;
@@ -196,7 +195,7 @@ public:
     { return DETECT; }
 
 public:
-    StreamReassembleRuleOptionData srod;
+    StreamReassembleRuleOptionData srod = {};
 };
 
 bool ReassembleModule::begin(const char*, int, SnortConfig*)
@@ -287,7 +286,7 @@ const BaseApi* ips_stream_reassemble = &reassemble_api.base;
 TEST_CASE("IPS Stream Reassemble", "[ips_stream_reassemble][stream_tcp]")
 {
     // initialization code here
-    REQUIRE( ( ips_stream_reassemble->api_version == ((BASE_API_VERSION << 16) | 0) ) );
+    REQUIRE( ( ips_stream_reassemble->api_version == (BASE_API_VERSION << 16) ) );
     REQUIRE( ( strcmp(ips_stream_reassemble->name, s_name) == 0 ) );
     ReassembleModule* reassembler = ( ReassembleModule* )ips_stream_reassemble->mod_ctor();
     REQUIRE( reassembler != nullptr );
index c040e73b50dc82a1fa280d8525fda10dc422241b..3c0b3880976fef792b10e5737bf0e71a24b47904 100644 (file)
@@ -44,9 +44,8 @@ static THREAD_LOCAL ProfileStats streamSizePerfStats;
 class SizeOption : public IpsOption
 {
 public:
-    SizeOption(const RangeCheck& c, int dir) :
-        IpsOption(s_name)
-    { ssod = c; direction = dir; }
+    SizeOption(const RangeCheck& c, int dir) : IpsOption(s_name), ssod(c), direction(dir)
+    { }
 
     uint32_t hash() const override;
     bool operator==(const IpsOption&) const override;
@@ -183,7 +182,7 @@ public:
 
 public:
     RangeCheck ssod;
-    int direction;
+    int direction = 0;
 };
 
 bool SizeModule::begin(const char*, int, SnortConfig*)
index a3b55739fe4a99e3bf1fc61002a20f1628b5db5a..9097cc4d676e24b650024326620ea549130faa6d 100644 (file)
@@ -63,21 +63,20 @@ static void purge_alerts_callback_ips(IpsContext* c)
         session->client.reassembler.purge_alerts();
 }
 
-bool TcpReassembler::is_segment_pending_flush(TcpReassemblerState& trs)
+bool TcpReassembler::is_segment_pending_flush(const TcpReassemblerState& trs) const
 {
     return ( get_pending_segment_count(trs, 1) > 0 );
 }
 
-uint32_t TcpReassembler::get_pending_segment_count(TcpReassemblerState& trs, unsigned max)
+uint32_t TcpReassembler::get_pending_segment_count(const TcpReassemblerState& trs, unsigned max) const
 {
     uint32_t n = trs.sos.seg_count - trs.flush_count;
-    TcpSegmentNode* tsn;
 
     if ( !n || max == 1 )
         return n;
 
     n = 0;
-    tsn = trs.sos.seglist.head;
+    const TcpSegmentNode* tsn = trs.sos.seglist.head;
     while ( tsn )
     {
         if ( tsn->c_len && SEQ_LT(tsn->c_seq, trs.tracker->r_win_base) )
@@ -276,11 +275,8 @@ bool TcpReassembler::add_alert(TcpReassemblerState& trs, uint32_t gid, uint32_t
 
 bool TcpReassembler::check_alerted(TcpReassemblerState& trs, uint32_t gid, uint32_t sid)
 {
-    for ( auto& alert : trs.alerts )
-       if (alert.gid == gid && alert.sid == sid)
-            return true;
-
-    return false;
+    return std::any_of(trs.alerts.cbegin(), trs.alerts.cend(),
+        [gid, sid](const StreamAlertInfo& alert){ return alert.gid == gid && alert.sid == sid; });
 }
 
 int TcpReassembler::update_alert(TcpReassemblerState& trs, uint32_t gid, uint32_t sid,
@@ -289,13 +285,15 @@ int TcpReassembler::update_alert(TcpReassemblerState& trs, uint32_t gid, uint32_
     // FIXIT-M comparison of seq_num is wrong, compare value is always 0, should be seq_num of wire packet
     uint32_t seq_num = 0;
 
-    for ( auto& alert : trs.alerts )
-       if (alert.gid == gid && alert.sid == sid && SEQ_EQ(alert.seq, seq_num))
-       {
-           alert.event_id = event_id;
-           alert.event_second = event_second;
-           return 0;
-       }
+    auto it = std::find_if(trs.alerts.begin(), trs.alerts.end(),
+        [gid, sid, seq_num](const StreamAlertInfo& alert)
+        { return alert.gid == gid && alert.sid == sid && SEQ_EQ(alert.seq, seq_num); });
+    if (it != trs.alerts.end())
+    {
+        (*it).event_id = event_id;
+        (*it).event_second = event_second;
+        return 0;
+    }
 
     return -1;
 }
@@ -957,7 +955,7 @@ static inline void fallback(TcpStreamTracker& trk, bool server_side, uint16_t ma
 
     // FIXIT-L: consolidate these 3
     bool to_server = splitter->to_server();
-    assert(splitter && server_side == to_server && server_side == !trk.client_tracker);
+    assert(server_side == to_server && server_side == !trk.client_tracker);
 #endif
 
     trk.set_splitter(new AtomSplitter(server_side, max));
index 9e4d5ade93787a5738891415ef8bb692bb4ae52e..f7f4a59956cb7f71c4b6e29bcc5e15e706d23d7f 100644 (file)
@@ -44,7 +44,7 @@ public:
         TcpReassemblerState&, snort::Flow* flow, bool clear, const snort::Packet* = nullptr);
     void finish_and_final_flush(
         TcpReassemblerState&, snort::Flow* flow, bool clear, snort::Packet*);
-    virtual bool is_segment_pending_flush(TcpReassemblerState&);
+    virtual bool is_segment_pending_flush(const TcpReassemblerState&) const;
     virtual int flush_on_data_policy(TcpReassemblerState&, snort::Packet*);
     virtual int flush_on_ack_policy(TcpReassemblerState&, snort::Packet*);
     virtual bool add_alert(TcpReassemblerState&, uint32_t gid, uint32_t sid);
@@ -68,7 +68,7 @@ protected:
     int delete_reassembly_segment(TcpReassemblerState&, TcpSegmentNode*) override;
     virtual void insert_segment_in_empty_seglist(TcpReassemblerState&, TcpSegmentDescriptor&);
     virtual void insert_segment_in_seglist(TcpReassemblerState&, TcpSegmentDescriptor&);
-    virtual uint32_t get_pending_segment_count(TcpReassemblerState&, unsigned max);
+    virtual uint32_t get_pending_segment_count(const TcpReassemblerState&, unsigned max) const;
     int trim_delete_reassembly_segment(TcpReassemblerState&, TcpSegmentNode*, uint32_t flush_seq);
     void queue_reassembly_segment(TcpReassemblerState&, TcpSegmentNode* prev, TcpSegmentNode*);
     void init_overlap_editor(TcpReassemblerState&, TcpSegmentDescriptor&);
index 927e05753d7ebc4ad34b66f02ef25706b1966443..0e3824138c318da48e128e151950315eaa4b7494 100644 (file)
@@ -76,7 +76,7 @@ public:
     void flush_queued_segments(snort::Flow* flow, bool clear, const snort::Packet* p = nullptr)
     { reassembler->flush_queued_segments(trs, flow, clear, p); }
 
-    bool is_segment_pending_flush()
+    bool is_segment_pending_flush() const
     { return reassembler->is_segment_pending_flush(trs); }
 
     int flush_on_data_policy(snort::Packet* p)
@@ -147,7 +147,7 @@ public:
 
 private:
     TcpReassembler* reassembler = nullptr;
-    TcpReassemblerState trs;
+    TcpReassemblerState trs = {};
     friend inline void TraceSegments(const TcpReassemblerPolicy&, const snort::Packet* p);
 };
 #endif
index 1e6f0728a6408e30d5d993c6263cb15dec1bd065..2ea79df55bdfe4e43afee2fe96fb5bb57fd4cf5b 100644 (file)
@@ -162,16 +162,6 @@ uint32_t TcpSegmentDescriptor::init_wscale(uint16_t* value)
     return TF_NONE;
 }
 
-bool TcpSegmentDescriptor::has_wscale()
-{
-    uint16_t wscale;
-
-    if ( !(pkt->ptrs.decode_flags & DECODE_TCP_WS) )
-        return false;
-
-    return ( init_wscale(&wscale) & TF_WSCALE ) != TF_NONE;
-}
-
 void TcpSegmentDescriptor::set_retransmit_flag()
 {
     if ( PacketTracer::is_active() )
index 51af169ec75594180bd7304d296d3256bc3c4284..963f828dea0b1d8d8bed3726c2a024d0404dbf7b 100644 (file)
@@ -54,7 +54,6 @@ public:
 
     uint32_t init_mss(uint16_t* value);
     uint32_t init_wscale(uint16_t* value);
-    bool has_wscale();
     void set_retransmit_flag();
 
     snort::Flow* get_flow() const
index e282a5e1d274722d5b207ccdd3af5a285946fa00..3a83a409e0b1503b4e3e2a1f4d6e1d91458067d9 100644 (file)
@@ -1160,7 +1160,7 @@ int TcpSession::process_tcp_packet(TcpSegmentDescriptor& tsd, const Packet* p)
 
 int TcpSession::process(Packet* p)
 {
-    Profile profile(s5TcpPerfStats);
+    Profile profile(s5TcpPerfStats);    // cppcheck-suppress unreadVariable
     assert(flow->ssn_server && flow->pkt_type == PktType::TCP);
 
     if ( ignore_this_packet(p) )
index c8ff12e75ddf4babbeeb81014da3cf8f2164b3f7..6b22fd4443feb69dcf8e940b3ae121baea197443 100644 (file)
@@ -51,6 +51,7 @@ public:
     void flush_server(snort::Packet*) override;
     void flush_talker(snort::Packet*, bool final_flush = false) override;
     void flush_listener(snort::Packet*, bool final_flush = false) override;
+    // cppcheck-suppress virtualCallInConstructor
     void clear_session(bool free_flow_data, bool flush_segments, bool restart, snort::Packet* p = nullptr) override;
     void set_extra_data(snort::Packet*, uint32_t /*flag*/) override;
     void update_perf_base_state(char new_state) override;
index 90364438fca030bd11c92606fd4b98e5d7972dde..5c3b76dadfd06f690d2fb511e6f0374b7d885f42 100644 (file)
@@ -70,9 +70,9 @@ public:
     uint32_t paf_max = 16384;
     int hs_timeout = -1;
 
-    bool no_ack;
+    bool no_ack = false;
     uint32_t embryonic_timeout = STREAM_DEFAULT_SSN_TIMEOUT;
-    uint32_t idle_timeout;
+    uint32_t idle_timeout = 3600;
 };
 
 #endif
index 2dd19d52ee524412cec1b4761ac9dd9463481075..c2d55fd48d9383d38384827473d374842f626f34 100644 (file)
@@ -109,7 +109,7 @@ void TcpStreamSession::disable_reassembly(Flow* f)
     server.finalize_held_packet(f);
 }
 
-uint8_t TcpStreamSession::get_reassembly_direction()
+uint8_t TcpStreamSession::get_reassembly_direction() const
 {
     uint8_t dir = SSN_DIR_NONE;
 
@@ -122,7 +122,7 @@ uint8_t TcpStreamSession::get_reassembly_direction()
     return dir;
 }
 
-bool TcpStreamSession::is_sequenced(uint8_t dir)
+bool TcpStreamSession::is_sequenced(uint8_t dir) const
 {
     if ( dir & SSN_DIR_FROM_CLIENT )
     {
@@ -141,7 +141,7 @@ bool TcpStreamSession::is_sequenced(uint8_t dir)
 
 /* This will falsely return SSN_MISSING_BEFORE on the first reassembled
  * packet if reassembly for this direction was set mid-session */
-uint8_t TcpStreamSession::missing_in_reassembled(uint8_t dir)
+uint8_t TcpStreamSession::missing_in_reassembled(uint8_t dir) const
 {
     if ( dir & SSN_DIR_FROM_CLIENT )
     {
@@ -167,7 +167,7 @@ uint8_t TcpStreamSession::missing_in_reassembled(uint8_t dir)
     return SSN_MISSING_NONE;
 }
 
-bool TcpStreamSession::are_packets_missing(uint8_t dir)
+bool TcpStreamSession::are_packets_missing(uint8_t dir) const
 {
     if ( dir & SSN_DIR_FROM_CLIENT )
     {
@@ -184,7 +184,7 @@ bool TcpStreamSession::are_packets_missing(uint8_t dir)
     return false;
 }
 
-bool TcpStreamSession::are_client_segments_queued()
+bool TcpStreamSession::are_client_segments_queued() const
 {
     return client.reassembler.is_segment_pending_flush();
 }
index 0c938ab7e0eed6fb1c8dcf2adaf3e514cba7632e..50ed57984b9e8aaa3dabce240fe15e58619aac0f 100644 (file)
@@ -43,13 +43,13 @@ public:
     void set_splitter(bool, snort::StreamSplitter*) override;
     snort::StreamSplitter* get_splitter(bool) override;
 
-    bool is_sequenced(uint8_t dir) override;
-    bool are_packets_missing(uint8_t dir) override;
+    bool is_sequenced(uint8_t dir) const override;
+    bool are_packets_missing(uint8_t dir) const override;
 
     void disable_reassembly(snort::Flow*) override;
-    uint8_t get_reassembly_direction() override;
-    uint8_t missing_in_reassembled(uint8_t dir) override;
-    bool are_client_segments_queued() override;
+    uint8_t get_reassembly_direction() const override;
+    uint8_t missing_in_reassembled(uint8_t dir) const override;
+    bool are_client_segments_queued() const override;
 
     bool add_alert(snort::Packet*, uint32_t gid, uint32_t sid) override;
     bool check_alerted(snort::Packet*, uint32_t gid, uint32_t sid) override;
@@ -74,7 +74,7 @@ public:
         bool free_flow_data, bool flush_segments, bool restart, snort::Packet* p = nullptr) = 0;
     virtual TcpStreamTracker::TcpState get_talker_state(TcpSegmentDescriptor&) = 0;
     virtual TcpStreamTracker::TcpState get_listener_state(TcpSegmentDescriptor&) = 0;
-    TcpStreamTracker::TcpState get_peer_state(TcpStreamTracker* me)
+    TcpStreamTracker::TcpState get_peer_state(const TcpStreamTracker* me)
     { return me == &client ? server.get_tcp_state() : client.get_tcp_state(); }
 
     virtual void init_new_tcp_session(TcpSegmentDescriptor&);
index 1267c404856dc1c948a648638c83842db5abc1d2..83f7c00f1847c5a9923ef5ca0187847fd54c04e8 100644 (file)
@@ -341,7 +341,7 @@ public:
 
     uint32_t r_win_base = 0; // remote side window base sequence number (the last ack we got)
     uint32_t small_seg_count = 0;
-    uint32_t max_queue_seq_nxt; // next expected sequence once queue limit is exceeded
+    uint32_t max_queue_seq_nxt = 0; // next expected sequence once queue limit is exceeded
     uint8_t max_queue_exceeded = MQ_NONE;
     uint8_t order = 0;
     FinSeqNumStatus fin_seq_status = TcpStreamTracker::FIN_NOT_SEEN;
index 8905bc0760c273113929ffac5616c15d496e9bd2..b55229e5a75643e1c512715417500a3fc5213792 100644 (file)
@@ -64,10 +64,10 @@ void TcpSession::flush_listener(Packet*){ }
 void TcpSession::set_splitter(bool, StreamSplitter*){ }
 StreamSplitter* TcpSession::get_splitter(bool){ return nullptr; }
 void TcpSession::set_extra_data(Packet*, unsigned int){ }
-bool TcpSession::is_sequenced(unsigned char){ return true; }
-bool TcpSession::are_packets_missing(unsigned char){ return false; }
-uint8_t TcpSession::get_reassembly_direction(){ return 0; }
-uint8_t  TcpSession::missing_in_reassembled(unsigned char){ return 0; }
+bool TcpSession::is_sequenced(unsigned char) const { return true; }
+bool TcpSession::are_packets_missing(unsigned char) const { return false; }
+uint8_t TcpSession::get_reassembly_direction() const { return 0; }
+uint8_t  TcpSession::missing_in_reassembled(unsigned char) const { return 0; }
 
 class TcpSessionMock : public TcpSession
 {
index cb28971b1401d2a557f39e2a327ad85078bc9c2c..26567ca1e3b8f5b35b2f3d85dc5424c724b810c5 100644 (file)
@@ -41,11 +41,8 @@ static const Parameter s_params[] =
     { nullptr, Parameter::PT_MAX, nullptr, nullptr, nullptr }
 };
 
-StreamUdpModule::StreamUdpModule() :
-    Module(MOD_NAME, MOD_HELP, s_params)
-{
-    config = nullptr;
-}
+StreamUdpModule::StreamUdpModule() : Module(MOD_NAME, MOD_HELP, s_params)
+{ }
 
 ProfileStats* StreamUdpModule::get_profile() const
 {
index 33bb43469b60aa1225a50c726406b1ddb366e589..e256991c40f7c0a015d4e42f99f85a35585197b6 100644 (file)
@@ -24,6 +24,8 @@
 #include "flow/session.h"
 #include "framework/module.h"
 
+#include "stream_udp.h"
+
 namespace snort
 {
 struct SnortConfig;
@@ -47,12 +49,12 @@ extern THREAD_LOCAL snort::ProfileStats udp_perf_stats;
 #define MOD_NAME "stream_udp"
 #define MOD_HELP "stream inspector for UDP flow tracking"
 
-struct StreamUdpConfig;
-
 class StreamUdpModule : public snort::Module
 {
 public:
     StreamUdpModule();
+    ~StreamUdpModule() override
+    { delete config; }
     bool set(const char*, snort::Value&, snort::SnortConfig*) override;
     bool begin(const char*, int, snort::SnortConfig*) override;
     bool end(const char*, int, snort::SnortConfig*) override;
@@ -69,7 +71,7 @@ public:
     { return true; }
 
 private:
-    StreamUdpConfig* config;
+    StreamUdpConfig* config = nullptr;
 };
 
 #endif
index e857d25300344a410ec662e58684dec7ea68a90a..e54a55e8368a23d1b5c5982d66641483c1766366 100644 (file)
@@ -170,7 +170,7 @@ void UdpSession::update_direction(
 
 int UdpSession::process(Packet* p)
 {
-    Profile profile(udp_perf_stats);
+    Profile profile(udp_perf_stats);    // cppcheck-suppress unreadVariable
 
     StreamUdpConfig* pc = get_udp_cfg(flow->ssn_server);
     // Check if the session is expired.
index dda48c4d6660e0ea09bd00cc66e0a4ab228d3289..09b8f2d6340ed3ca488f16ca36473940272885df 100644 (file)
@@ -74,8 +74,8 @@ void UserSegment::term(UserSegment* us)
 
 unsigned UserSegment::avail()
 {
-    unsigned size = offset + len;
-    return (BUCKET > size) ? BUCKET - size : 0;
+    unsigned tmp_size = offset + len;
+    return (BUCKET > tmp_size) ? BUCKET - tmp_size : 0;
 }
 
 void UserSegment::copy(const uint8_t* p, unsigned n)
@@ -468,7 +468,7 @@ StreamSplitter* UserSession::get_splitter(bool c2s)
 
 int UserSession::process(Packet* p)
 {
-    Profile profile(user_perf_stats);
+    Profile profile(user_perf_stats);   // cppcheck-suppress unreadVariable
 
     if ( Stream::expired_flow(flow, p) )
     {
@@ -516,6 +516,3 @@ int UserSession::update_alert(
     uint32_t /*event_id*/, uint32_t /*event_second*/)
 { return 0; }
 
-uint8_t UserSession::get_reassembly_direction()
-{ return SSN_DIR_NONE; }
-
index 59e543220a0ebed85484ff6f1cff297d47a214d6..fc65f8b2e9fd0d80d47cabe6bcfff7b9daaf31fb 100644 (file)
@@ -25,6 +25,7 @@
 #include "flow/session.h"
 #include "stream/paf.h"
 
+// cppcheck-suppress noConstructor
 struct UserSegment
 {
     static UserSegment* init(const uint8_t*, unsigned);
@@ -98,8 +99,6 @@ private:
     int update_alert(
         snort::Packet*, uint32_t gid, uint32_t sid, uint32_t event_id, uint32_t event_second) override;
 
-    uint8_t get_reassembly_direction() override;
-
 public:
     UserTracker client;
     UserTracker server;
index 6d2d4dcb7007254a12a44cf7e53e1b970327fc39..7ab338e08169e6fc78ec662b2e2b65b4bfeb02cc 100644 (file)
@@ -46,13 +46,13 @@ static const PegInfo host_attribute_pegs[] =
 };
 
 template<typename Key, typename Value, typename Hash>
-class HostLruSegmentedCache : public SegmentedLruCache<Key, Value, Hash> 
+class HostLruSegmentedCache : public SegmentedLruCache<Key, Value, Hash>
 {
 public:
 
     HostLruSegmentedCache(const size_t initial_size, std::size_t seg_count = DEFAULT_SEGMENT_COUNT)
         : SegmentedLruCache<Key, Value, Hash>(initial_size, seg_count)
-      { } 
+      { }
 };
 
 typedef HostLruSegmentedCache<snort::SfIp, HostAttributesDescriptor, HostAttributesCacheKey> HostAttributesSegmentedCache;
@@ -87,18 +87,18 @@ bool HostAttributesDescriptor::update_service
 {
     std::lock_guard<std::mutex> lck(host_attributes_lock);
 
-    for ( auto& s : services)
+    auto it = std::find_if(services.begin(), services.end(),
+        [port, protocol](const HostServiceDescriptor& s){ return s.ipproto == protocol && s.port == port; });
+    if (it != services.cend())
     {
-        if ( s.ipproto == protocol && (uint16_t)s.port == port )
+        HostServiceDescriptor& s = *it;
+        if ( s.snort_protocol_id != snort_protocol_id )
         {
-            if ( s.snort_protocol_id != snort_protocol_id )
-            {
-                s.snort_protocol_id = snort_protocol_id;
-                s.appid_service = is_appid_service;
-            }
-            updated = true;
-            return true;
+            s.snort_protocol_id = snort_protocol_id;
+            s.appid_service = is_appid_service;
         }
+        updated = true;
+        return true;
     }
 
     // service not found, add it
@@ -130,14 +130,10 @@ void HostAttributesDescriptor::get_host_attributes(uint16_t port,HostAttriInfo*
     host_info->frag_policy = policies.fragPolicy;
     host_info->stream_policy = policies.streamPolicy;
     host_info->snort_protocol_id = UNKNOWN_PROTOCOL_ID;
-    for ( auto& s : services )
-    {
-        if ( s.port == port )
-        {
-            host_info->snort_protocol_id = s.snort_protocol_id;
-            return;
-        }
-    }
+    auto it = std::find_if(services.cbegin(), services.cend(),
+        [port](const HostServiceDescriptor &s){ return s.port == port; });
+    if (it != services.cend())
+        host_info->snort_protocol_id = (*it).snort_protocol_id;
 }
 bool HostAttributesManager::load_hosts_file(snort::SnortConfig* sc, const char* fname)
 {
@@ -262,7 +258,7 @@ PegCount* HostAttributesManager::get_peg_counts()
 {
     if ( active_cache )
     {
-        LruCacheSharedStats* cache_stats = (LruCacheSharedStats*) active_cache->get_counts();
+        const LruCacheSharedStats* cache_stats = (const LruCacheSharedStats*) active_cache->get_counts();
         host_attribute_stats.hosts_pruned = cache_stats->alloc_prunes;
         host_attribute_stats.total_hosts = active_cache->size();
     }
index 08b1088d04f3d13efc779de62e6bc8c8c40669eb..3e97200ecff1c358954c813d975dd9350577613c 100644 (file)
@@ -56,7 +56,7 @@ TEST_CASE( "stopwatch", "[time][stopwatch]" )
     Stopwatch<Clock> sw;
     Clock::reset();
 
-    REQUIRE_FALSE( sw.active() );
+    REQUIRE( false == sw.active() );
     REQUIRE( (sw.get() == 0_ticks) );
 
     SECTION( "start" )
@@ -65,7 +65,7 @@ TEST_CASE( "stopwatch", "[time][stopwatch]" )
 
         SECTION( "sets clock to active" )
         {
-            CHECK( sw.active() );
+            CHECK( true == sw.active() );
         }
 
         SECTION( "running elapsed time should be non-zero" )
@@ -77,7 +77,7 @@ TEST_CASE( "stopwatch", "[time][stopwatch]" )
         SECTION( "start on running clock has no effect" )
         {
             sw.start();
-            CHECK( sw.active() );
+            CHECK( true == sw.active() );
         }
     }
 
@@ -88,7 +88,7 @@ TEST_CASE( "stopwatch", "[time][stopwatch]" )
 
         SECTION( "sets clock to be dead" )
         {
-            CHECK_FALSE( sw.active() );
+            CHECK( false == sw.active() );
         }
 
         SECTION( "ticks should not increase after death" )
@@ -103,7 +103,7 @@ TEST_CASE( "stopwatch", "[time][stopwatch]" )
             auto val = sw.get();
             sw.stop();
             Clock::inc();
-            CHECK_FALSE( sw.active() );
+            CHECK( false == sw.active() );
             CHECK( val == sw.get() );
         }
     }
@@ -115,7 +115,7 @@ TEST_CASE( "stopwatch", "[time][stopwatch]" )
         SECTION( "reset on running clock" )
         {
             sw.reset();
-            CHECK_FALSE( sw.active() );
+            CHECK( false == sw.active() );
             CHECK( (sw.get() == 0_ticks) );
         }
 
@@ -123,7 +123,7 @@ TEST_CASE( "stopwatch", "[time][stopwatch]" )
         {
             sw.stop();
             sw.reset();
-            CHECK_FALSE( sw.active() );
+            CHECK( false == sw.active() );
             CHECK( (sw.get() == 0_ticks) );
         }
     }
@@ -134,7 +134,7 @@ TEST_CASE( "stopwatch", "[time][stopwatch]" )
         SECTION( "cancel on running clock that has no lap time" )
         {
             sw.cancel();
-            CHECK_FALSE( sw.active() );
+            CHECK( false == sw.active() );
             CHECK( (sw.get() == 0_ticks) );
         }
 
@@ -144,7 +144,7 @@ TEST_CASE( "stopwatch", "[time][stopwatch]" )
             auto val = sw.get();
             sw.cancel();
 
-            CHECK_FALSE( sw.active() );
+            CHECK( false == sw.active() );
             CHECK( val == sw.get() );
         }
     }
index 3bcbb958acdfb6e3eb21ded7a873577b6e7dc3f9..998c02d6447195fb86f7309efc777daa77020b7e 100644 (file)
@@ -90,9 +90,9 @@ void Trace::clear()
 
 #include "catch/catch.hpp"
 
-Module::Module(const char* s, const char* h) : name(s), help(h)
+Module::Module(const char* s, const char* h) : name(s), help(h), params(nullptr), list(false)
 {}
-Module::Module(const char*, const char*, const Parameter*, bool)
+Module::Module(const char* s, const char* h, const Parameter* p, bool l) : name(s), help(h), params(p), list(l)
 {}
 PegCount Module::get_global_count(char const*) const { return 0; }
 void Module::show_interval_stats(std::vector<unsigned int, std::allocator<unsigned int> >&, FILE*) {}
@@ -122,7 +122,7 @@ TEST_CASE("default option", "[Trace]")
 
     bool result = trace.set(DEFAULT_TRACE_OPTION_NAME, DEFAULT_TRACE_LOG_LEVEL);
     CHECK(result == true);
-    CHECK(trace.enabled(DEFAULT_TRACE_OPTION_ID));
+    CHECK(true == trace.enabled(DEFAULT_TRACE_OPTION_ID));
 }
 
 TEST_CASE("multiple options", "[Trace]")
@@ -149,25 +149,25 @@ TEST_CASE("multiple options", "[Trace]")
 
     bool result = trace.set("option1", DEFAULT_TRACE_LOG_LEVEL);
     CHECK(result == true);
-    CHECK(trace.enabled(TEST_TRACE_OPTION1));
+    CHECK(true == trace.enabled(TEST_TRACE_OPTION1));
 
     result = trace.set("option2", DEFAULT_TRACE_LOG_LEVEL);
     CHECK(result == true);
-    CHECK(trace.enabled(TEST_TRACE_OPTION1));
-    CHECK(trace.enabled(TEST_TRACE_OPTION2));
+    CHECK(true == trace.enabled(TEST_TRACE_OPTION1));
+    CHECK(true == trace.enabled(TEST_TRACE_OPTION2));
 
     result = trace.set("option3", DEFAULT_TRACE_LOG_LEVEL);
     CHECK(result == true);
-    CHECK(trace.enabled(TEST_TRACE_OPTION1));
-    CHECK(trace.enabled(TEST_TRACE_OPTION2));
-    CHECK(trace.enabled(TEST_TRACE_OPTION3));
+    CHECK(true == trace.enabled(TEST_TRACE_OPTION1));
+    CHECK(true == trace.enabled(TEST_TRACE_OPTION2));
+    CHECK(true == trace.enabled(TEST_TRACE_OPTION3));
 
     result = trace.set("option4", DEFAULT_TRACE_LOG_LEVEL);
     CHECK(result == true);
-    CHECK(trace.enabled(TEST_TRACE_OPTION1));
-    CHECK(trace.enabled(TEST_TRACE_OPTION2));
-    CHECK(trace.enabled(TEST_TRACE_OPTION3));
-    CHECK(trace.enabled(TEST_TRACE_OPTION4));
+    CHECK(true == trace.enabled(TEST_TRACE_OPTION1));
+    CHECK(true == trace.enabled(TEST_TRACE_OPTION2));
+    CHECK(true == trace.enabled(TEST_TRACE_OPTION3));
+    CHECK(true == trace.enabled(TEST_TRACE_OPTION4));
 }
 
 TEST_CASE("invalid option", "[Trace]")
index 066224928a8a2c65b5c2dc94d4348a2efa0ea0e8..b92efeb9efd2b9497e4622b741b8b45f9de45bde 100644 (file)
@@ -197,7 +197,7 @@ void TraceParser::init_configured_trace_options()
 
 enum { OPT_1, OPT_2 };
 
-static const TraceOption trace_options[] =
+static const TraceOption s_trace_options[] =
 {
     { "option1", OPT_1, "test option 1" },
     { "option2", OPT_2, "test option 2" },
@@ -211,7 +211,7 @@ class Module1 : public Module
 public:
     Module1() : Module("mod_1", "testing trace parser module 1") { }
     void set_trace(const Trace* t) const override { m1_trace = t; }
-    const TraceOption* get_trace_options() const override { return trace_options; }
+    const TraceOption* get_trace_options() const override { return s_trace_options; }
 
 };
 
@@ -220,7 +220,7 @@ class Module2 : public Module
 public:
     Module2() : Module("mod_2", "testing trace parser module 2") { }
     void set_trace(const Trace* t) const override { m2_trace = t; }
-    const TraceOption* get_trace_options() const override { return trace_options; }
+    const TraceOption* get_trace_options() const override { return s_trace_options; }
 
 };
 
@@ -241,13 +241,13 @@ TEST_CASE("modules traces", "[TraceParser]")
     SECTION("invalid module")
     {
         MODULE_OPTION(all, 10);
-        CHECK(!tp.set_traces("invalid_module", all));
+        CHECK(false == tp.set_traces("invalid_module", all));
     }
 
     SECTION("invalid option")
     {
         MODULE_OPTION(invalid_option, 10);
-        CHECK(!tp.set_traces("mod_1", invalid_option));
+        CHECK(false == tp.set_traces("mod_1", invalid_option));
     }
 
     SECTION("unset")
@@ -255,66 +255,66 @@ TEST_CASE("modules traces", "[TraceParser]")
         REQUIRE(m1_trace != nullptr);
         REQUIRE(m2_trace != nullptr);
 
-        CHECK(!m1_trace->enabled(OPT_1));
-        CHECK(!m1_trace->enabled(OPT_2));
-        CHECK(!m2_trace->enabled(OPT_1));
-        CHECK(!m2_trace->enabled(OPT_2));
+        CHECK(false == m1_trace->enabled(OPT_1));
+        CHECK(false == m1_trace->enabled(OPT_2));
+        CHECK(false == m2_trace->enabled(OPT_1));
+        CHECK(false == m2_trace->enabled(OPT_2));
     }
 
     SECTION("all modules")
     {
         MODULE_OPTION(all, 3);
-        CHECK(tp.set_traces("all", all));
+        CHECK(true == tp.set_traces("all", all));
 
         REQUIRE(m1_trace != nullptr);
         REQUIRE(m2_trace != nullptr);
 
-        CHECK(m1_trace->enabled(OPT_1, 3));
-        CHECK(m1_trace->enabled(OPT_2, 3));
-        CHECK(m2_trace->enabled(OPT_1, 3));
-        CHECK(m2_trace->enabled(OPT_2, 3));
+        CHECK(true == m1_trace->enabled(OPT_1, 3));
+        CHECK(true == m1_trace->enabled(OPT_2, 3));
+        CHECK(true == m2_trace->enabled(OPT_1, 3));
+        CHECK(true == m2_trace->enabled(OPT_2, 3));
 
-        CHECK(!m1_trace->enabled(OPT_1, 4));
-        CHECK(!m1_trace->enabled(OPT_2, 4));
-        CHECK(!m2_trace->enabled(OPT_1, 4));
-        CHECK(!m2_trace->enabled(OPT_2, 4));
+        CHECK(false == m1_trace->enabled(OPT_1, 4));
+        CHECK(false == m1_trace->enabled(OPT_2, 4));
+        CHECK(false == m2_trace->enabled(OPT_1, 4));
+        CHECK(false == m2_trace->enabled(OPT_2, 4));
     }
 
     SECTION("module all")
     {
         MODULE_OPTION(all, 3);
-        CHECK(tp.set_traces("mod_1", all));
+        CHECK(true == tp.set_traces("mod_1", all));
 
         REQUIRE(m1_trace != nullptr);
         REQUIRE(m2_trace != nullptr);
 
-        CHECK(m1_trace->enabled(OPT_1, 3));
-        CHECK(m1_trace->enabled(OPT_2, 3));
-        CHECK(!m2_trace->enabled(OPT_1, 3));
-        CHECK(!m2_trace->enabled(OPT_2, 3));
+        CHECK(true == m1_trace->enabled(OPT_1, 3));
+        CHECK(true == m1_trace->enabled(OPT_2, 3));
+        CHECK(false == m2_trace->enabled(OPT_1, 3));
+        CHECK(false == m2_trace->enabled(OPT_2, 3));
     }
 
     SECTION("options")
     {
         MODULE_OPTION(option1, 1);
         MODULE_OPTION(option2, 5);
-        CHECK(tp.set_traces("mod_1", option1));
-        CHECK(tp.set_traces("mod_1", option2));
-        CHECK(tp.set_traces("mod_2", option1));
-        CHECK(tp.set_traces("mod_2", option2));
+        CHECK(true == tp.set_traces("mod_1", option1));
+        CHECK(true == tp.set_traces("mod_1", option2));
+        CHECK(true == tp.set_traces("mod_2", option1));
+        CHECK(true == tp.set_traces("mod_2", option2));
 
         REQUIRE(m1_trace != nullptr);
         REQUIRE(m2_trace != nullptr);
 
-        CHECK(m1_trace->enabled(OPT_1, 1));
-        CHECK(m1_trace->enabled(OPT_2, 1));
-        CHECK(m2_trace->enabled(OPT_1, 1));
-        CHECK(m2_trace->enabled(OPT_2, 1));
+        CHECK(true == m1_trace->enabled(OPT_1, 1));
+        CHECK(true == m1_trace->enabled(OPT_2, 1));
+        CHECK(true == m2_trace->enabled(OPT_1, 1));
+        CHECK(true == m2_trace->enabled(OPT_2, 1));
 
-        CHECK(!m1_trace->enabled(OPT_1, 5));
-        CHECK(m1_trace->enabled(OPT_2, 5));
-        CHECK(!m2_trace->enabled(OPT_1, 5));
-        CHECK(m2_trace->enabled(OPT_2, 5));
+        CHECK(false == m1_trace->enabled(OPT_1, 5));
+        CHECK(true == m1_trace->enabled(OPT_2, 5));
+        CHECK(false == m2_trace->enabled(OPT_1, 5));
+        CHECK(true == m2_trace->enabled(OPT_2, 5));
     }
 
     SECTION("override all modules")
@@ -322,27 +322,27 @@ TEST_CASE("modules traces", "[TraceParser]")
         MODULE_OPTION(option1, 1);
         MODULE_OPTION(option2, 2);
         MODULE_OPTION(all, 3);
-        CHECK(tp.set_traces("mod_1", option1));
-        CHECK(tp.set_traces("mod_2", option2));
-        CHECK(tp.set_traces("all", all));
+        CHECK(true == tp.set_traces("mod_1", option1));
+        CHECK(true == tp.set_traces("mod_2", option2));
+        CHECK(true == tp.set_traces("all", all));
 
         REQUIRE(m1_trace != nullptr);
         REQUIRE(m2_trace != nullptr);
 
-        CHECK(m1_trace->enabled(OPT_1, 1));
-        CHECK(m1_trace->enabled(OPT_2, 1));
-        CHECK(m2_trace->enabled(OPT_1, 1));
-        CHECK(m2_trace->enabled(OPT_2, 1));
+        CHECK(true == m1_trace->enabled(OPT_1, 1));
+        CHECK(true == m1_trace->enabled(OPT_2, 1));
+        CHECK(true == m2_trace->enabled(OPT_1, 1));
+        CHECK(true == m2_trace->enabled(OPT_2, 1));
 
-        CHECK(!m1_trace->enabled(OPT_1, 2));
-        CHECK(m1_trace->enabled(OPT_2, 2));
-        CHECK(m2_trace->enabled(OPT_1, 2));
-        CHECK(m2_trace->enabled(OPT_2, 2));
+        CHECK(false == m1_trace->enabled(OPT_1, 2));
+        CHECK(true == m1_trace->enabled(OPT_2, 2));
+        CHECK(true == m2_trace->enabled(OPT_1, 2));
+        CHECK(true == m2_trace->enabled(OPT_2, 2));
 
-        CHECK(!m1_trace->enabled(OPT_1, 3));
-        CHECK(m1_trace->enabled(OPT_2, 3));
-        CHECK(m2_trace->enabled(OPT_1, 3));
-        CHECK(!m2_trace->enabled(OPT_2, 3));
+        CHECK(false == m1_trace->enabled(OPT_1, 3));
+        CHECK(true == m1_trace->enabled(OPT_2, 3));
+        CHECK(true == m2_trace->enabled(OPT_1, 3));
+        CHECK(false == m2_trace->enabled(OPT_2, 3));
     }
 
     auto sc = SnortConfig::get_conf();
@@ -361,7 +361,7 @@ TEST_CASE("packet constraints", "[TraceParser]")
         const PacketConstraints exp = { IpProtocol::TCP, 0, 0,
             SfIp(), SfIp(), PacketConstraints::IP_PROTO };
 
-        CHECK(tp.set_constraints(ip_proto));
+        CHECK(true == tp.set_constraints(ip_proto));
         tp.finalize_constraints();
 
         REQUIRE(tc.constraints != nullptr);
@@ -377,7 +377,7 @@ TEST_CASE("packet constraints", "[TraceParser]")
         const PacketConstraints exp = { IpProtocol::PROTO_NOT_SET, 0, 0,
             SfIp(&exp_ip, AF_INET), SfIp(), PacketConstraints::SRC_IP };
 
-        CHECK(tp.set_constraints(src_ip));
+        CHECK(true == tp.set_constraints(src_ip));
         tp.finalize_constraints();
 
         REQUIRE(tc.constraints != nullptr);
@@ -389,7 +389,7 @@ TEST_CASE("packet constraints", "[TraceParser]")
     SECTION("invalid src_ip")
     {
         ADDR_OPTION(src_ip, "10.1.2.300");
-        CHECK(!tp.set_constraints(src_ip));
+        CHECK(false == tp.set_constraints(src_ip));
     }
 
     SECTION("src_port")
@@ -398,7 +398,7 @@ TEST_CASE("packet constraints", "[TraceParser]")
             SfIp(), SfIp(), PacketConstraints::SRC_PORT };
         PORT_OPTION(src_port, 100);
 
-        CHECK(tp.set_constraints(src_port));
+        CHECK(true == tp.set_constraints(src_port));
         tp.finalize_constraints();
 
         REQUIRE(tc.constraints != nullptr);
@@ -414,7 +414,7 @@ TEST_CASE("packet constraints", "[TraceParser]")
         const PacketConstraints exp = { IpProtocol::PROTO_NOT_SET, 0, 0,
             SfIp(), SfIp(&exp_ip, AF_INET), PacketConstraints::DST_IP };
 
-        CHECK(tp.set_constraints(dst_ip));
+        CHECK(true == tp.set_constraints(dst_ip));
         tp.finalize_constraints();
 
         REQUIRE(tc.constraints != nullptr);
@@ -426,7 +426,7 @@ TEST_CASE("packet constraints", "[TraceParser]")
     SECTION("invalid dst_ip")
     {
         ADDR_OPTION(dst_ip, "10.300.2.1");
-        CHECK(!tp.set_constraints(dst_ip));
+        CHECK(false == tp.set_constraints(dst_ip));
     }
 
     SECTION("dst_port")
@@ -435,7 +435,7 @@ TEST_CASE("packet constraints", "[TraceParser]")
         const PacketConstraints exp = { IpProtocol::PROTO_NOT_SET, 0, 200,
             SfIp(), SfIp(), PacketConstraints::DST_PORT };
 
-        CHECK(tp.set_constraints(dst_port));
+        CHECK(true == tp.set_constraints(dst_port));
         tp.finalize_constraints();
 
         REQUIRE(tc.constraints != nullptr);
@@ -447,7 +447,7 @@ TEST_CASE("packet constraints", "[TraceParser]")
     SECTION("invalid option")
     {
         CONFIG_OPTION(invalid_option, (uint64_t)5, Parameter::PT_INT, "0:8");
-        CHECK(!tp.set_constraints(invalid_option));
+        CHECK(false == tp.set_constraints(invalid_option));
     }
 }
 
index 2810f72eff730c03fcbdeb843238f7973c828820..9f26f529abe99edc75ed775ebfd7f4ffb2514ed3 100644 (file)
@@ -137,7 +137,7 @@ int KMapAdd(KMAP* km, void* key, int n, void* userdata)
 
     int type = 0;
     const unsigned char* P = (unsigned char*)key;
-    std::string xkey;
+    std::string xkey; // cppcheck-suppress variableScope
 
     if ( km->nocase )
     {
@@ -264,7 +264,7 @@ void* KMapFind(KMAP* ks, void* key, int n)
 {
     assert(n > 0);
 
-    std::string xkey;
+    std::string xkey; // cppcheck-suppress variableScope
     const unsigned char* T = (unsigned char*)key;
 
     if ( ks->nocase )
@@ -276,6 +276,7 @@ void* KMapFind(KMAP* ks, void* key, int n)
 
         T = (const unsigned char*)xkey.c_str();
     }
+
     //printf("finding key='%.*s'\n",n,T);
 
     /* Check if any keywords start with this character */
index 7d398a477cf19d3588996137661413d3d8853aec..4e084518f17365a89b213afb907c86eb79358e0d 100644 (file)
@@ -65,9 +65,9 @@ public:
     PrimedAllocator() noexcept
     { state = new State; }
 
-    PrimedAllocator(const PrimedAllocator& other) noexcept
+    // cppcheck-suppress copyCtorPointerCopying
+    PrimedAllocator(const PrimedAllocator& other) noexcept : state(other.state)
     {
-        state = other.state;
         state->ref_count++;
     }
 
index 2673ff23a12c8742dce19ba1e4f2c16dcd31ba6d..bd70a05f7501d89fc549833d7340a0cda0091147 100644 (file)
@@ -353,7 +353,7 @@ void show_stats(
 {
     bool head = false;
 
-    for ( auto& i : peg_idxs)
+    for ( const auto& i : peg_idxs)
         head = show_stat(head, pegs[i], info[i].name, module_name, fh);
 }
 
index 5f5911b68da2bc3798da7495eff783ca080f4171..f708b7cc707d8dae6b26bc63c679fbff661d35e8 100644 (file)
@@ -260,27 +260,27 @@ void ostreambuf_infl::reserve(streamsize n)
 
 const char* ostreambuf_infl::take_data()
 {
-    auto data = pbase();
+    auto d = pbase();
 
     setp(nullptr, nullptr);
 
     gen.s = states[0].s;
     gen.n = states[0].n;
 
-    return data;
+    return d;
 }
 
 const char* ostreambuf_infl::take_data(streamsize& n)
 {
-    auto data = pbase();
+    auto d = pbase();
 
-    n = pptr() - data;
+    n = pptr() - d;
     setp(nullptr, nullptr);
 
     gen.s = states[0].s;
     gen.n = states[0].n;
 
-    return data;
+    return d;
 }
 
 streambuf* ostreambuf_infl::setbuf(char* s, streamsize n)
@@ -369,7 +369,6 @@ streamsize ostreambuf_infl::xsputn(const char* s, streamsize n)
     return n;
 }
 
-// cppcheck-suppress unusedFunction
 streamsize ostreambuf_infl::xsgetn(char* s, streamsize n)
 {
     assert(n >= 0);
index 6dfd93db071860b4a8a091aea247a97945cf3635..b8558f86ee084ecd02ada159d7b02b185f0832b4 100644 (file)
@@ -156,11 +156,11 @@ TEST_CASE("input buffer - basic one source", "[Stream buffers]")
         int off_e = b.pubseekoff(0, ios_base::end, ios_base::in);
 
         CHECK(c == EOF);
-        CHECK(avail_1 == -1);
-        CHECK(avail_2 == -1);
-        CHECK(off_b == -1);
-        CHECK(off_c == -1);
-        CHECK(off_e == -1);
+        CHECK((avail_1 == -1));
+        CHECK((avail_2 == -1));
+        CHECK((off_b == -1));
+        CHECK((off_c == -1));
+        CHECK((off_e == -1));
     }
 
     SECTION("get char")
@@ -176,12 +176,12 @@ TEST_CASE("input buffer - basic one source", "[Stream buffers]")
         int off_b = b.pubseekoff(0, ios_base::beg, ios_base::in);
         int off_e = b.pubseekoff(0, ios_base::end, ios_base::in);
 
-        CHECK(c == 'E');
-        CHECK(avail_1 == len);
-        CHECK(avail_2 == len);
+        CHECK((c == 'E'));
+        CHECK((avail_1 == len));
+        CHECK((avail_2 == len));
         CHECK(off_b == 0);
         CHECK(off_c == 0);
-        CHECK(off_e == len);
+        CHECK((off_e == len));
     }
 
     SECTION("get char and bump")
@@ -197,12 +197,12 @@ TEST_CASE("input buffer - basic one source", "[Stream buffers]")
         int off_b = b.pubseekoff(0, ios_base::beg, ios_base::in);
         int off_e = b.pubseekoff(0, ios_base::end, ios_base::in);
 
-        CHECK(c == 'E');
-        CHECK(avail_1 == len);
-        CHECK(avail_2 == len - 1);
+        CHECK((c == 'E'));
+        CHECK((avail_1 == len));
+        CHECK((avail_2 == (len - 1)));
         CHECK(off_b == 0);
         CHECK(off_c == 1);
-        CHECK(off_e == len);
+        CHECK((off_e == len));
     }
 
     SECTION("advance and get char")
@@ -218,12 +218,12 @@ TEST_CASE("input buffer - basic one source", "[Stream buffers]")
         int off_b = b.pubseekoff(0, ios_base::beg, ios_base::in);
         int off_e = b.pubseekoff(0, ios_base::end, ios_base::in);
 
-        CHECK(c == 'a');
-        CHECK(avail_1 == len);
-        CHECK(avail_2 == len - 1);
+        CHECK((c == 'a'));
+        CHECK((avail_1 == len));
+        CHECK((avail_2 == (len - 1)));
         CHECK(off_b == 0);
         CHECK(off_c == 1);
-        CHECK(off_e == len);
+        CHECK((off_e == len));
     }
 
     SECTION("get chars")
@@ -242,14 +242,14 @@ TEST_CASE("input buffer - basic one source", "[Stream buffers]")
         int off_b = b.pubseekoff(0, ios_base::beg, ios_base::in);
         int off_e = b.pubseekoff(0, ios_base::end, ios_base::in);
 
-        CHECK(nread_1 == 10);
-        CHECK(nread_2 == 10);
-        CHECK(avail_1 == len);
-        CHECK(avail_2 == len - 10);
-        CHECK(avail_3 == len - 20);
+        CHECK((nread_1 == 10));
+        CHECK((nread_2 == 10));
+        CHECK((avail_1 == len));
+        CHECK((avail_2 == (len - 10)));
+        CHECK((avail_3 == (len - 20)));
         CHECK(off_b == 0);
-        CHECK(off_c == 20);
-        CHECK(off_e == len);
+        CHECK((off_c == 20));
+        CHECK((off_e == len));
         CHECK(!memcmp(exp, act, 20));
     }
 
@@ -271,16 +271,16 @@ TEST_CASE("input buffer - basic one source", "[Stream buffers]")
         int off_b = b.pubseekoff(0, ios_base::beg, ios_base::in);
         int off_e = b.pubseekoff(0, ios_base::end, ios_base::in);
 
-        CHECK(nread_1 == 10);
-        CHECK(nread_2 == 10);
-        CHECK(nread_3 == 3);
-        CHECK(avail_1 == len);
-        CHECK(avail_2 == len - 10);
-        CHECK(avail_3 == len - 20);
+        CHECK((nread_1 == 10));
+        CHECK((nread_2 == 10));
+        CHECK((nread_3 == 3));
+        CHECK((avail_1 == len));
+        CHECK((avail_2 == (len - 10)));
+        CHECK((avail_3 == (len - 20)));
         CHECK(avail_4 == 0);
         CHECK(off_b == 0);
-        CHECK(off_c == 23);
-        CHECK(off_e == len);
+        CHECK((off_c == 23));
+        CHECK((off_e == len));
         CHECK(!memcmp(exp, act, len));
     }
 
@@ -298,13 +298,13 @@ TEST_CASE("input buffer - basic one source", "[Stream buffers]")
         int off_b = b.pubseekoff(0, ios_base::beg, ios_base::in);
         int off_e = b.pubseekoff(0, ios_base::end, ios_base::in);
 
-        CHECK(c == 'y');
-        CHECK(avail_1 == len - 5);
-        CHECK(avail_2 == len - 4);
-        CHECK(off_o == 5);
+        CHECK((c == 'y'));
+        CHECK((avail_1 == (len - 5)));
+        CHECK((avail_2 == (len - 4)));
+        CHECK((off_o == 5));
         CHECK(off_b == 0);
-        CHECK(off_c == 4);
-        CHECK(off_e == len);
+        CHECK((off_c == 4));
+        CHECK((off_e == len));
     }
 
     SECTION("put another char back")
@@ -322,14 +322,14 @@ TEST_CASE("input buffer - basic one source", "[Stream buffers]")
         int off_b = b.pubseekoff(0, ios_base::beg, ios_base::in);
         int off_e = b.pubseekoff(0, ios_base::end, ios_base::in);
 
-        CHECK(c1 == -1);
-        CHECK(c2 == 'y');
-        CHECK(avail_1 == len - 5);
-        CHECK(avail_2 == len - 4);
-        CHECK(off_o == 5);
+        CHECK((c1 == -1));
+        CHECK((c2 == 'y'));
+        CHECK((avail_1 == (len - 5)));
+        CHECK((avail_2 == (len - 4)));
+        CHECK((off_o == 5));
         CHECK(off_b == 0);
-        CHECK(off_c == 4);
-        CHECK(off_e == len);
+        CHECK((off_c == 4));
+        CHECK((off_e == len));
     }
 }
 
@@ -355,12 +355,12 @@ TEST_CASE("input buffer - basic two sources", "[Stream buffers]")
         int off_b = b.pubseekoff(0, ios_base::beg, ios_base::in);
         int off_e = b.pubseekoff(0, ios_base::end, ios_base::in);
 
-        CHECK(c == 'E');
+        CHECK((c == 'E'));
         CHECK(avail_1 == dat1_len);
         CHECK(avail_2 == dat1_len);
         CHECK(off_b == 0);
         CHECK(off_c == 0);
-        CHECK(off_e == len);
+        CHECK((off_e == len));
     }
 
     SECTION("get char and bump")
@@ -376,12 +376,12 @@ TEST_CASE("input buffer - basic two sources", "[Stream buffers]")
         int off_b = b.pubseekoff(0, ios_base::beg, ios_base::in);
         int off_e = b.pubseekoff(0, ios_base::end, ios_base::in);
 
-        CHECK(c == 'E');
+        CHECK((c == 'E'));
         CHECK(avail_1 == dat1_len);
         CHECK(avail_2 == dat1_len - 1);
         CHECK(off_b == 0);
         CHECK(off_c == 1);
-        CHECK(off_e == len);
+        CHECK((off_e == len));
     }
 
     SECTION("advance and get char")
@@ -397,12 +397,12 @@ TEST_CASE("input buffer - basic two sources", "[Stream buffers]")
         int off_b = b.pubseekoff(0, ios_base::beg, ios_base::in);
         int off_e = b.pubseekoff(0, ios_base::end, ios_base::in);
 
-        CHECK(c == 'a');
+        CHECK((c == 'a'));
         CHECK(avail_1 == dat1_len);
         CHECK(avail_2 == dat1_len - 1);
         CHECK(off_b == 0);
         CHECK(off_c == 1);
-        CHECK(off_e == len);
+        CHECK((off_e == len));
     }
 
     SECTION("get chars")
@@ -421,14 +421,14 @@ TEST_CASE("input buffer - basic two sources", "[Stream buffers]")
         int off_b = b.pubseekoff(0, ios_base::beg, ios_base::in);
         int off_e = b.pubseekoff(0, ios_base::end, ios_base::in);
 
-        CHECK(nread_1 == 10);
-        CHECK(nread_2 == 10);
+        CHECK((nread_1 == 10));
+        CHECK((nread_2 == 10));
         CHECK(avail_1 == dat1_len);
-        CHECK(avail_2 == len - 10);
-        CHECK(avail_3 == len - 20);
+        CHECK((avail_2 == (len - 10)));
+        CHECK((avail_3 == (len - 20)));
         CHECK(off_b == 0);
-        CHECK(off_c == 20);
-        CHECK(off_e == len);
+        CHECK((off_c == 20));
+        CHECK((off_e == len));
         CHECK(!memcmp(exp, act, 20));
     }
 
@@ -450,16 +450,16 @@ TEST_CASE("input buffer - basic two sources", "[Stream buffers]")
         int off_b = b.pubseekoff(0, ios_base::beg, ios_base::in);
         int off_e = b.pubseekoff(0, ios_base::end, ios_base::in);
 
-        CHECK(nread_1 == 10);
-        CHECK(nread_2 == 10);
-        CHECK(nread_3 == 3);
+        CHECK((nread_1 == 10));
+        CHECK((nread_2 == 10));
+        CHECK((nread_3 == 3));
         CHECK(avail_1 == dat1_len);
-        CHECK(avail_2 == len - 10);
-        CHECK(avail_3 == len - 20);
+        CHECK((avail_2 == (len - 10)));
+        CHECK((avail_3 == (len - 20)));
         CHECK(avail_4 == 0);
         CHECK(off_b == 0);
-        CHECK(off_c == 23);
-        CHECK(off_e == len);
+        CHECK((off_c == 23));
+        CHECK((off_e == len));
         CHECK(!memcmp(exp, act, len));
     }
 
@@ -477,13 +477,13 @@ TEST_CASE("input buffer - basic two sources", "[Stream buffers]")
         int off_b = b.pubseekoff(0, ios_base::beg, ios_base::in);
         int off_e = b.pubseekoff(0, ios_base::end, ios_base::in);
 
-        CHECK(c == 'y');
+        CHECK((c == 'y'));
         CHECK(avail_1 == dat1_len - 5);
         CHECK(avail_2 == dat1_len - 4);
-        CHECK(off_o == 5);
+        CHECK((off_o == 5));
         CHECK(off_b == 0);
-        CHECK(off_c == 4);
-        CHECK(off_e == len);
+        CHECK((off_c == 4));
+        CHECK((off_e == len));
     }
 
     SECTION("put another char back")
@@ -501,14 +501,14 @@ TEST_CASE("input buffer - basic two sources", "[Stream buffers]")
         int off_b = b.pubseekoff(0, ios_base::beg, ios_base::in);
         int off_e = b.pubseekoff(0, ios_base::end, ios_base::in);
 
-        CHECK(c1 == -1);
-        CHECK(c2 == 'y');
+        CHECK((c1 == -1));
+        CHECK((c2 == 'y'));
         CHECK(avail_1 == dat1_len - 5);
         CHECK(avail_2 == dat1_len - 4);
-        CHECK(off_o == 5);
+        CHECK((off_o == 5));
         CHECK(off_b == 0);
-        CHECK(off_c == 4);
-        CHECK(off_e == len);
+        CHECK((off_c == 4));
+        CHECK((off_e == len));
     }
 }
 
@@ -516,7 +516,7 @@ TEST_CASE("input buffer - buffer management", "[Stream buffers]")
 {
     const char* exp = "Early bird gets a corn.";
     const int len = strlen(exp);
-    char dat[] = "Early bird gets a corn.";
+    char dat[] = "Early bird gets a corn."; // cppcheck-suppress variableScope
     char dat1[] = "Early ";
     char dat2[] = "bird ";
     char dat3[] = "gets ";
@@ -536,8 +536,8 @@ TEST_CASE("input buffer - buffer management", "[Stream buffers]")
         int r1 = b1.pubsync();
         int r2 = b2.pubsync();
 
-        CHECK(r1 == -1);
-        CHECK(r2 == -1);
+        CHECK((r1 == -1));
+        CHECK((r2 == -1));
     }
 
     SECTION("chain of buffers")
@@ -582,9 +582,9 @@ TEST_CASE("input buffer - offset one source", "[Stream buffers]")
         int off_b = b.pubseekoff(0, ios_base::beg, ios_base::in);
         int off_e = b.pubseekoff(0, ios_base::end, ios_base::in);
 
-        CHECK(off_b == -1);
-        CHECK(off_c == -1);
-        CHECK(off_e == -1);
+        CHECK((off_b == -1));
+        CHECK((off_c == -1));
+        CHECK((off_e == -1));
     }
 
     SECTION("wrong argument")
@@ -598,10 +598,10 @@ TEST_CASE("input buffer - offset one source", "[Stream buffers]")
         int off_e = b.pubseekoff(0, ios_base::end, ios_base::out);
         int off_a = b.pubseekoff(0, static_cast<std::ios_base::seekdir>(0x5a5a), ios_base::in);
 
-        CHECK(off_b == -1);
-        CHECK(off_c == -1);
-        CHECK(off_e == -1);
-        CHECK(off_a == -1);
+        CHECK((off_b == -1));
+        CHECK((off_c == -1));
+        CHECK((off_e == -1));
+        CHECK((off_a == -1));
     }
 
     SECTION("begin")
@@ -616,7 +616,7 @@ TEST_CASE("input buffer - offset one source", "[Stream buffers]")
         EXP_AVAIL1(b, exp, len, off);
 
         off = b.pubseekoff(0 + len + len, ios_base::beg, ios_base::in);
-        CHECK(off == len);
+        CHECK((off == len));
         EXP_AVAIL1(b, exp, len, off);
 
         off = b.pubseekoff(0, ios_base::beg, ios_base::in);
@@ -632,19 +632,19 @@ TEST_CASE("input buffer - offset one source", "[Stream buffers]")
         EXP_AVAIL1(b, exp, len, off);
 
         off = b.pubseekoff(0 + len1d3, ios_base::beg, ios_base::in);
-        CHECK(off == len1d3);
+        CHECK((off == len1d3));
         EXP_AVAIL1(b, exp, len, off);
 
         off = b.pubseekoff(0 + len2d3, ios_base::beg, ios_base::in);
-        CHECK(off == len2d3);
+        CHECK((off == len2d3));
         EXP_AVAIL1(b, exp, len, off);
 
         off = b.pubseekoff(0 + len - 1, ios_base::beg, ios_base::in);
-        CHECK(off == len - 1);
+        CHECK((off == (len - 1)));
         EXP_AVAIL1(b, exp, len, off);
 
         off = b.pubseekoff(0 + len, ios_base::beg, ios_base::in);
-        CHECK(off == len);
+        CHECK((off == len));
         EXP_AVAIL1(b, exp, len, off);
     }
 
@@ -660,27 +660,27 @@ TEST_CASE("input buffer - offset one source", "[Stream buffers]")
         EXP_AVAIL1(b, exp, len, off);
 
         off = b.pubseekoff(0 + len + len, ios_base::end, ios_base::in);
-        CHECK(off == len);
+        CHECK((off == len));
         EXP_AVAIL1(b, exp, len, off);
 
         off = b.pubseekoff(0, ios_base::end, ios_base::in);
-        CHECK(off == len);
+        CHECK((off == len));
         EXP_AVAIL1(b, exp, len, off);
 
         off = b.pubseekoff(0 - 1, ios_base::end, ios_base::in);
-        CHECK(off == len - 1);
+        CHECK((off == (len - 1)));
         EXP_AVAIL1(b, exp, len, off);
 
         off = b.pubseekoff(0 + 1, ios_base::end, ios_base::in);
-        CHECK(off == len);
+        CHECK((off == len));
         EXP_AVAIL1(b, exp, len, off);
 
         off = b.pubseekoff(0 - len1d3, ios_base::end, ios_base::in);
-        CHECK(off == len2d3);
+        CHECK((off == len2d3));
         EXP_AVAIL1(b, exp, len, off);
 
         off = b.pubseekoff(0 - len2d3, ios_base::end, ios_base::in);
-        CHECK(off == len1d3);
+        CHECK((off == len1d3));
         EXP_AVAIL1(b, exp, len, off);
 
         off = b.pubseekoff(0 - len + 1, ios_base::end, ios_base::in);
@@ -706,37 +706,37 @@ TEST_CASE("input buffer - offset one source", "[Stream buffers]")
 
         b.pubseekoff(len1d3, ios_base::beg, ios_base::in);
         off = b.pubseekoff(0 + len + len, ios_base::cur, ios_base::in);
-        CHECK(off == len);
+        CHECK((off == len));
         EXP_AVAIL1(b, exp, len, off);
 
         b.pubseekoff(len1d3, ios_base::beg, ios_base::in);
         off = b.pubseekoff(0, ios_base::cur, ios_base::in);
-        CHECK(off == len1d3);
+        CHECK((off == len1d3));
         EXP_AVAIL1(b, exp, len, off);
 
         b.pubseekoff(len1d3, ios_base::beg, ios_base::in);
         off = b.pubseekoff(0 - 1, ios_base::cur, ios_base::in);
-        CHECK(off == len1d3 - 1);
+        CHECK((off == (len1d3 - 1)));
         EXP_AVAIL1(b, exp, len, off);
 
         b.pubseekoff(len1d3, ios_base::beg, ios_base::in);
         off = b.pubseekoff(0 + 1, ios_base::cur, ios_base::in);
-        CHECK(off == len1d3 + 1);
+        CHECK((off == (len1d3 + 1)));
         EXP_AVAIL1(b, exp, len, off);
 
         b.pubseekoff(len1d3, ios_base::beg, ios_base::in);
         off = b.pubseekoff(0 + len1d3, ios_base::cur, ios_base::in);
-        CHECK(off == len1d3 + len1d3);
+        CHECK((off == (len1d3 + len1d3)));
         EXP_AVAIL1(b, exp, len, off);
 
         b.pubseekoff(len1d3, ios_base::beg, ios_base::in);
         off = b.pubseekoff(0 + len2d3, ios_base::cur, ios_base::in);
-        CHECK(off == len);
+        CHECK((off == len));
         EXP_AVAIL1(b, exp, len, off);
 
         b.pubseekoff(len1d3, ios_base::beg, ios_base::in);
         off = b.pubseekoff(0 + len, ios_base::cur, ios_base::in);
-        CHECK(off == len);
+        CHECK((off == len));
         EXP_AVAIL1(b, exp, len, off);
     }
 
@@ -754,37 +754,37 @@ TEST_CASE("input buffer - offset one source", "[Stream buffers]")
 
         b.pubseekoff(len2d3, ios_base::beg, ios_base::in);
         off = b.pubseekoff(0 + len + len, ios_base::cur, ios_base::in);
-        CHECK(off == len);
+        CHECK((off == len));
         EXP_AVAIL1(b, exp, len, off);
 
         b.pubseekoff(len2d3, ios_base::beg, ios_base::in);
         off = b.pubseekoff(0, ios_base::cur, ios_base::in);
-        CHECK(off == len2d3);
+        CHECK((off == len2d3));
         EXP_AVAIL1(b, exp, len, off);
 
         b.pubseekoff(len2d3, ios_base::beg, ios_base::in);
         off = b.pubseekoff(0 - 1, ios_base::cur, ios_base::in);
-        CHECK(off == len2d3 - 1);
+        CHECK((off == (len2d3 - 1)));
         EXP_AVAIL1(b, exp, len, off);
 
         b.pubseekoff(len2d3, ios_base::beg, ios_base::in);
         off = b.pubseekoff(0 + 1, ios_base::cur, ios_base::in);
-        CHECK(off == len2d3 + 1);
+        CHECK((off == (len2d3 + 1)));
         EXP_AVAIL1(b, exp, len, off);
 
         b.pubseekoff(len2d3, ios_base::beg, ios_base::in);
         off = b.pubseekoff(0 + len1d3, ios_base::cur, ios_base::in);
-        CHECK(off == len);
+        CHECK((off == len));
         EXP_AVAIL1(b, exp, len, off);
 
         b.pubseekoff(len2d3, ios_base::beg, ios_base::in);
         off = b.pubseekoff(0 + len2d3, ios_base::cur, ios_base::in);
-        CHECK(off == len);
+        CHECK((off == len));
         EXP_AVAIL1(b, exp, len, off);
 
         b.pubseekoff(len2d3, ios_base::beg, ios_base::in);
         off = b.pubseekoff(0 + len, ios_base::cur, ios_base::in);
-        CHECK(off == len);
+        CHECK((off == len));
         EXP_AVAIL1(b, exp, len, off);
     }
 }
@@ -810,9 +810,9 @@ TEST_CASE("input buffer - offset two sources", "[Stream buffers]")
         int off_b = b.pubseekoff(0, ios_base::beg, ios_base::out);
         int off_e = b.pubseekoff(0, ios_base::end, ios_base::out);
 
-        CHECK(off_b == -1);
-        CHECK(off_c == -1);
-        CHECK(off_e == -1);
+        CHECK((off_b == -1));
+        CHECK((off_c == -1));
+        CHECK((off_e == -1));
     }
 
     SECTION("begin")
@@ -827,7 +827,7 @@ TEST_CASE("input buffer - offset two sources", "[Stream buffers]")
         EXP_AVAIL2(b, exp, len, off, dat1_len);
 
         off = b.pubseekoff(0 + len + len, ios_base::beg, ios_base::in);
-        CHECK(off == len);
+        CHECK((off == len));
         EXP_AVAIL2(b, exp, len, off, dat1_len);
 
         off = b.pubseekoff(0, ios_base::beg, ios_base::in);
@@ -843,19 +843,19 @@ TEST_CASE("input buffer - offset two sources", "[Stream buffers]")
         EXP_AVAIL2(b, exp, len, off, dat1_len);
 
         off = b.pubseekoff(0 + len1d3, ios_base::beg, ios_base::in);
-        CHECK(off == len1d3);
+        CHECK((off == len1d3));
         EXP_AVAIL2(b, exp, len, off, dat1_len);
 
         off = b.pubseekoff(0 + len2d3, ios_base::beg, ios_base::in);
-        CHECK(off == len2d3);
+        CHECK((off == len2d3));
         EXP_AVAIL2(b, exp, len, off, dat1_len);
 
         off = b.pubseekoff(0 + len - 1, ios_base::beg, ios_base::in);
-        CHECK(off == len - 1);
+        CHECK((off == (len - 1)));
         EXP_AVAIL2(b, exp, len, off, dat1_len);
 
         off = b.pubseekoff(0 + len, ios_base::beg, ios_base::in);
-        CHECK(off == len);
+        CHECK((off == len));
         EXP_AVAIL2(b, exp, len, off, dat1_len);
     }
 
@@ -871,27 +871,27 @@ TEST_CASE("input buffer - offset two sources", "[Stream buffers]")
         EXP_AVAIL2(b, exp, len, off, dat1_len);
 
         off = b.pubseekoff(0 + len + len, ios_base::end, ios_base::in);
-        CHECK(off == len);
+        CHECK((off == len));
         EXP_AVAIL2(b, exp, len, off, dat1_len);
 
         off = b.pubseekoff(0, ios_base::end, ios_base::in);
-        CHECK(off == len);
+        CHECK((off == len));
         EXP_AVAIL2(b, exp, len, off, dat1_len);
 
         off = b.pubseekoff(0 - 1, ios_base::end, ios_base::in);
-        CHECK(off == len - 1);
+        CHECK((off == (len - 1)));
         EXP_AVAIL2(b, exp, len, off, dat1_len);
 
         off = b.pubseekoff(0 + 1, ios_base::end, ios_base::in);
-        CHECK(off == len);
+        CHECK((off == len));
         EXP_AVAIL2(b, exp, len, off, dat1_len);
 
         off = b.pubseekoff(0 - len1d3, ios_base::end, ios_base::in);
-        CHECK(off == len2d3);
+        CHECK((off == len2d3));
         EXP_AVAIL2(b, exp, len, off, dat1_len);
 
         off = b.pubseekoff(0 - len2d3, ios_base::end, ios_base::in);
-        CHECK(off == len1d3);
+        CHECK((off == len1d3));
         EXP_AVAIL2(b, exp, len, off, dat1_len);
 
         off = b.pubseekoff(0 - len + 1, ios_base::end, ios_base::in);
@@ -917,37 +917,37 @@ TEST_CASE("input buffer - offset two sources", "[Stream buffers]")
 
         b.pubseekoff(len1d3, ios_base::beg, ios_base::in);
         off = b.pubseekoff(0 + len + len, ios_base::cur, ios_base::in);
-        CHECK(off == len);
+        CHECK((off == len));
         EXP_AVAIL2(b, exp, len, off, dat1_len);
 
         b.pubseekoff(len1d3, ios_base::beg, ios_base::in);
         off = b.pubseekoff(0, ios_base::cur, ios_base::in);
-        CHECK(off == len1d3);
+        CHECK((off == len1d3));
         EXP_AVAIL2(b, exp, len, off, dat1_len);
 
         b.pubseekoff(len1d3, ios_base::beg, ios_base::in);
         off = b.pubseekoff(0 - 1, ios_base::cur, ios_base::in);
-        CHECK(off == len1d3 - 1);
+        CHECK((off == (len1d3 - 1)));
         EXP_AVAIL2(b, exp, len, off, dat1_len);
 
         b.pubseekoff(len1d3, ios_base::beg, ios_base::in);
         off = b.pubseekoff(0 + 1, ios_base::cur, ios_base::in);
-        CHECK(off == len1d3 + 1);
+        CHECK((off == (len1d3 + 1)));
         EXP_AVAIL2(b, exp, len, off, dat1_len);
 
         b.pubseekoff(len1d3, ios_base::beg, ios_base::in);
         off = b.pubseekoff(0 + len1d3, ios_base::cur, ios_base::in);
-        CHECK(off == len1d3 + len1d3);
+        CHECK((off == (len1d3 + len1d3)));
         EXP_AVAIL2(b, exp, len, off, dat1_len);
 
         b.pubseekoff(len1d3, ios_base::beg, ios_base::in);
         off = b.pubseekoff(0 + len2d3, ios_base::cur, ios_base::in);
-        CHECK(off == len);
+        CHECK((off == len));
         EXP_AVAIL2(b, exp, len, off, dat1_len);
 
         b.pubseekoff(len1d3, ios_base::beg, ios_base::in);
         off = b.pubseekoff(0 + len, ios_base::cur, ios_base::in);
-        CHECK(off == len);
+        CHECK((off == len));
         EXP_AVAIL2(b, exp, len, off, dat1_len);
     }
 
@@ -965,37 +965,37 @@ TEST_CASE("input buffer - offset two sources", "[Stream buffers]")
 
         b.pubseekoff(len2d3, ios_base::beg, ios_base::in);
         off = b.pubseekoff(0 + len + len, ios_base::cur, ios_base::in);
-        CHECK(off == len);
+        CHECK((off == len));
         EXP_AVAIL2(b, exp, len, off, dat1_len);
 
         b.pubseekoff(len2d3, ios_base::beg, ios_base::in);
         off = b.pubseekoff(0, ios_base::cur, ios_base::in);
-        CHECK(off == len2d3);
+        CHECK((off == len2d3));
         EXP_AVAIL2(b, exp, len, off, dat1_len);
 
         b.pubseekoff(len2d3, ios_base::beg, ios_base::in);
         off = b.pubseekoff(0 - 1, ios_base::cur, ios_base::in);
-        CHECK(off == len2d3 - 1);
+        CHECK((off == (len2d3 - 1)));
         EXP_AVAIL2(b, exp, len, off, dat1_len);
 
         b.pubseekoff(len2d3, ios_base::beg, ios_base::in);
         off = b.pubseekoff(0 + 1, ios_base::cur, ios_base::in);
-        CHECK(off == len2d3 + 1);
+        CHECK((off == (len2d3 + 1)));
         EXP_AVAIL2(b, exp, len, off, dat1_len);
 
         b.pubseekoff(len2d3, ios_base::beg, ios_base::in);
         off = b.pubseekoff(0 + len1d3, ios_base::cur, ios_base::in);
-        CHECK(off == len);
+        CHECK((off == len));
         EXP_AVAIL2(b, exp, len, off, dat1_len);
 
         b.pubseekoff(len2d3, ios_base::beg, ios_base::in);
         off = b.pubseekoff(0 + len2d3, ios_base::cur, ios_base::in);
-        CHECK(off == len);
+        CHECK((off == len));
         EXP_AVAIL2(b, exp, len, off, dat1_len);
 
         b.pubseekoff(len2d3, ios_base::beg, ios_base::in);
         off = b.pubseekoff(0 + len, ios_base::cur, ios_base::in);
-        CHECK(off == len);
+        CHECK((off == len));
         EXP_AVAIL2(b, exp, len, off, dat1_len);
     }
 }
@@ -1016,9 +1016,9 @@ TEST_CASE("input buffer - positioning one source", "[Stream buffers]")
         int pos_b = b.pubseekpos(0,       ios_base::in);
         int pos_e = b.pubseekpos(len,     ios_base::in);
 
-        CHECK(pos_b == -1);
-        CHECK(pos_c == -1);
-        CHECK(pos_e == -1);
+        CHECK((pos_b == -1));
+        CHECK((pos_c == -1));
+        CHECK((pos_e == -1));
     }
 
     SECTION("wrong buffer")
@@ -1031,9 +1031,9 @@ TEST_CASE("input buffer - positioning one source", "[Stream buffers]")
         int pos_b = b.pubseekpos(0,       ios_base::out);
         int pos_e = b.pubseekpos(len,     ios_base::out);
 
-        CHECK(pos_b == -1);
-        CHECK(pos_c == -1);
-        CHECK(pos_e == -1);
+        CHECK((pos_b == -1));
+        CHECK((pos_c == -1));
+        CHECK((pos_e == -1));
     }
 
     SECTION("out of range")
@@ -1048,7 +1048,7 @@ TEST_CASE("input buffer - positioning one source", "[Stream buffers]")
         EXP_AVAIL1(b, exp, len, pos);
 
         pos = b.pubseekpos(len + len, ios_base::in);
-        CHECK(pos == len);
+        CHECK((pos == len));
         EXP_AVAIL1(b, exp, len, pos);
     }
 
@@ -1072,15 +1072,15 @@ TEST_CASE("input buffer - positioning one source", "[Stream buffers]")
         EXP_AVAIL1(b, exp, len, pos);
 
         pos = b.pubseekpos(len, ios_base::in);
-        CHECK(pos == len);
+        CHECK((pos == len));
         EXP_AVAIL1(b, exp, len, pos);
 
         pos = b.pubseekpos(len - 1, ios_base::in);
-        CHECK(pos == len - 1);
+        CHECK((pos == (len - 1)));
         EXP_AVAIL1(b, exp, len, pos);
 
         pos = b.pubseekpos(len + 1, ios_base::in);
-        CHECK(pos == len);
+        CHECK((pos == len));
         EXP_AVAIL1(b, exp, len, pos);
     }
 
@@ -1092,11 +1092,11 @@ TEST_CASE("input buffer - positioning one source", "[Stream buffers]")
         b.pubsetbuf(dat, len);
 
         pos = b.pubseekpos(len1d3, ios_base::in);
-        CHECK(pos == len1d3);
+        CHECK((pos == len1d3));
         EXP_AVAIL1(b, exp, len, pos);
 
         pos = b.pubseekpos(len2d3, ios_base::in);
-        CHECK(pos == len2d3);
+        CHECK((pos == len2d3));
         EXP_AVAIL1(b, exp, len, pos);
     }
 }
@@ -1122,9 +1122,9 @@ TEST_CASE("input buffer - positioning two sources", "[Stream buffers]")
         int pos_b = b.pubseekpos(0,       ios_base::out);
         int pos_e = b.pubseekpos(len,     ios_base::out);
 
-        CHECK(pos_b == -1);
-        CHECK(pos_c == -1);
-        CHECK(pos_e == -1);
+        CHECK((pos_b == -1));
+        CHECK((pos_c == -1));
+        CHECK((pos_e == -1));
     }
 
     SECTION("out of range")
@@ -1139,7 +1139,7 @@ TEST_CASE("input buffer - positioning two sources", "[Stream buffers]")
         EXP_AVAIL2(b, exp, len, pos, dat1_len);
 
         pos = b.pubseekpos(len + len, ios_base::in);
-        CHECK(pos == len);
+        CHECK((pos == len));
         EXP_AVAIL2(b, exp, len, pos, dat1_len);
     }
 
@@ -1163,15 +1163,15 @@ TEST_CASE("input buffer - positioning two sources", "[Stream buffers]")
         EXP_AVAIL2(b, exp, len, pos, dat1_len);
 
         pos = b.pubseekpos(len, ios_base::in);
-        CHECK(pos == len);
+        CHECK((pos == len));
         EXP_AVAIL2(b, exp, len, pos, dat1_len);
 
         pos = b.pubseekpos(len - 1, ios_base::in);
-        CHECK(pos == len - 1);
+        CHECK((pos == (len - 1)));
         EXP_AVAIL2(b, exp, len, pos, dat1_len);
 
         pos = b.pubseekpos(len + 1, ios_base::in);
-        CHECK(pos == len);
+        CHECK((pos == len));
         EXP_AVAIL2(b, exp, len, pos, dat1_len);
     }
 
@@ -1183,11 +1183,11 @@ TEST_CASE("input buffer - positioning two sources", "[Stream buffers]")
         b.pubsetbuf(dat1, dat1_len)->pubsetbuf(dat2, dat2_len);
 
         pos = b.pubseekpos(len1d3, ios_base::in);
-        CHECK(pos == len1d3);
+        CHECK((pos == len1d3));
         EXP_AVAIL2(b, exp, len, pos, dat1_len);
 
         pos = b.pubseekpos(len2d3, ios_base::in);
-        CHECK(pos == len2d3);
+        CHECK((pos == len2d3));
         EXP_AVAIL2(b, exp, len, pos, dat1_len);
 
         pos = b.pubseekpos(dat1_len, ios_base::in);
@@ -1468,10 +1468,10 @@ TEST_CASE("output buffer - basic", "[Stream buffers]")
         int off_b = b.pubseekoff(0, ios_base::beg, ios_base::out);
         int off_e = b.pubseekoff(0, ios_base::end, ios_base::out);
 
-        CHECK(c == 'A');
+        CHECK((c == 'A'));
         CHECK(off_b == 0);
         CHECK(off_c == 1);
-        CHECK(off_e == 2048);
+        CHECK((off_e == 2048));
 
         EXP_RES(b, exp, 1, 2048);
     }
@@ -1487,12 +1487,12 @@ TEST_CASE("output buffer - basic", "[Stream buffers]")
         int off_b = b.pubseekoff(0, ios_base::beg, ios_base::out);
         int off_e = b.pubseekoff(0, ios_base::end, ios_base::out);
 
-        CHECK(c1 == 'A');
-        CHECK(c2 == 'B');
+        CHECK((c1 == 'A'));
+        CHECK((c2 == 'B'));
         CHECK(off_b == 0);
         CHECK(off_1 == 1);
-        CHECK(off_2 == 2);
-        CHECK(off_e == 2048);
+        CHECK((off_2 == 2));
+        CHECK((off_e == 2048));
 
         EXP_RES(b, exp, 2, 2048);
     }
@@ -1509,13 +1509,13 @@ TEST_CASE("output buffer - basic", "[Stream buffers]")
         int off_2 = b.pubseekoff(0, ios_base::cur, ios_base::out);
         int off_z = b.pubseekoff(0, ios_base::end, ios_base::out);
 
-        CHECK(c1 == 'A');
-        CHECK(c2 == 'Z');
+        CHECK((c1 == 'A'));
+        CHECK((c2 == 'Z'));
         CHECK(off_b == 0);
         CHECK(off_1 == 1);
-        CHECK(off_2 == 2049);
-        CHECK(off_e == 2048);
-        CHECK(off_z == 6144);
+        CHECK((off_2 == 2049));
+        CHECK((off_e == 2048));
+        CHECK((off_z == 6144));
     }
 
     SECTION("put sequence of chars")
@@ -1528,10 +1528,10 @@ TEST_CASE("output buffer - basic", "[Stream buffers]")
         int off_b = b.pubseekoff(0, ios_base::beg, ios_base::out);
         int off_e = b.pubseekoff(0, ios_base::end, ios_base::out);
 
-        CHECK(n == len);
+        CHECK((n == len));
         CHECK(off_b == 0);
-        CHECK(off_c == len);
-        CHECK(off_e == 4096);
+        CHECK((off_c == len));
+        CHECK((off_e == 4096));
 
         EXP_RES(b, exp, len, 4096);
     }
@@ -1548,12 +1548,12 @@ TEST_CASE("output buffer - basic", "[Stream buffers]")
         int off_b = b.pubseekoff(0, ios_base::beg, ios_base::out);
         int off_e = b.pubseekoff(0, ios_base::end, ios_base::out);
 
-        CHECK(n == len);
-        CHECK(c1 == 'A');
-        CHECK(c2 == 'Z');
+        CHECK((n == len));
+        CHECK((c1 == 'A'));
+        CHECK((c2 == 'Z'));
         CHECK(off_b == 0);
-        CHECK(off_c == len + 2);
-        CHECK(off_e == 4096 + 2048);
+        CHECK((off_c == (len + 2)));
+        CHECK((off_e == (4096 + 2048)));
     }
 
     SECTION("get char sequence")
@@ -1571,7 +1571,7 @@ TEST_CASE("output buffer - basic", "[Stream buffers]")
         delete[] act_seq;
 
         int new_off = b.pubseekoff(0, ios_base::cur, ios_base::out);
-        CHECK(new_off == exp_len);
+        CHECK((new_off == exp_len));
     }
 
     SECTION("get char sequence from the end")
@@ -1583,7 +1583,7 @@ TEST_CASE("output buffer - basic", "[Stream buffers]")
         b.pubsetbuf(buf, exp_len);
 
         int data_off = b.pubseekoff(exp_len, ios_base::beg, ios_base::out);
-        CHECK(data_off == exp_len);
+        CHECK((data_off == exp_len));
 
         char* act_seq = new char[exp_len];
         memset(act_seq, '\0', exp_len);
@@ -1592,7 +1592,7 @@ TEST_CASE("output buffer - basic", "[Stream buffers]")
         delete[] act_seq;
 
         int new_off = b.pubseekoff(0, ios_base::cur, ios_base::out);
-        CHECK(new_off == exp_len);
+        CHECK((new_off == exp_len));
     }
 
     SECTION("get char sequence more than available")
@@ -1609,7 +1609,7 @@ TEST_CASE("output buffer - basic", "[Stream buffers]")
         delete[] act_seq;
 
         int new_off = b.pubseekoff(0, ios_base::cur, ios_base::out);
-        CHECK(new_off == exp_len);
+        CHECK((new_off == exp_len));
     }
 }
 
@@ -1633,7 +1633,7 @@ TEST_CASE("output buffer - buffer management", "[Stream buffers]")
         b.pubsetbuf(buf, dat1_len);
 
         int r = b.pubsync();
-        CHECK(r == -1);
+        CHECK((r == -1));
     }
 
     SECTION("changing buffer")
@@ -1692,9 +1692,9 @@ TEST_CASE("output buffer - positioning", "[Stream buffers]")
         int pos_b = b.pubseekpos(0,       ios_base::in);
         int pos_e = b.pubseekpos(len,     ios_base::in);
 
-        CHECK(pos_b == -1);
-        CHECK(pos_c == -1);
-        CHECK(pos_e == -1);
+        CHECK((pos_b == -1));
+        CHECK((pos_c == -1));
+        CHECK((pos_e == -1));
     }
 
     SECTION("out of range")
@@ -1713,7 +1713,7 @@ TEST_CASE("output buffer - positioning", "[Stream buffers]")
         b.sputn(exp, len);
 
         pos = b.pubseekpos(len + len, ios_base::out);
-        CHECK(pos == len);
+        CHECK((pos == len));
         EXP_RES(b, exp, len, len);
     }
 
@@ -1730,11 +1730,11 @@ TEST_CASE("output buffer - positioning", "[Stream buffers]")
         pos = b.pubseekpos(0 + 1, ios_base::out);
         CHECK(pos == 1);
         pos = b.pubseekpos(len, ios_base::out);
-        CHECK(pos == len);
+        CHECK((pos == len));
         pos = b.pubseekpos(len - 1, ios_base::out);
-        CHECK(pos == len - 1);
+        CHECK((pos == (len - 1)));
         pos = b.pubseekpos(len + 1, ios_base::out);
-        CHECK(pos == len);
+        CHECK((pos == len));
 
         pos = b.pubseekpos(0, ios_base::out);
         CHECK(pos == 0);
@@ -1750,9 +1750,9 @@ TEST_CASE("output buffer - positioning", "[Stream buffers]")
         b.sputn(exp, len);
 
         pos = b.pubseekpos(len1d3, ios_base::out);
-        CHECK(pos == len1d3);
+        CHECK((pos == len1d3));
         pos = b.pubseekpos(len2d3, ios_base::out);
-        CHECK(pos == len2d3);
+        CHECK((pos == len2d3));
     }
 }
 
@@ -1787,10 +1787,10 @@ TEST_CASE("output buffer - offset", "[Stream buffers]")
         int off_e = b.pubseekoff(0, ios_base::end, ios_base::in);
         int off_a = b.pubseekoff(0, static_cast<std::ios_base::seekdir>(0x5a5a), ios_base::out);
 
-        CHECK(off_b == -1);
-        CHECK(off_c == -1);
-        CHECK(off_e == -1);
-        CHECK(off_a == -1);
+        CHECK((off_b == -1));
+        CHECK((off_c == -1));
+        CHECK((off_e == -1));
+        CHECK((off_a == -1));
     }
 
     SECTION("begin")
@@ -1805,7 +1805,7 @@ TEST_CASE("output buffer - offset", "[Stream buffers]")
         CHECK(off == 0);
 
         off = b.pubseekoff(0 + len + len, ios_base::beg, ios_base::out);
-        CHECK(off == len);
+        CHECK((off == len));
 
         off = b.pubseekoff(0 - 1, ios_base::beg, ios_base::out);
         CHECK(off == 0);
@@ -1814,16 +1814,16 @@ TEST_CASE("output buffer - offset", "[Stream buffers]")
         CHECK(off == 1);
 
         off = b.pubseekoff(0 + len1d3, ios_base::beg, ios_base::out);
-        CHECK(off == len1d3);
+        CHECK((off == len1d3));
 
         off = b.pubseekoff(0 + len2d3, ios_base::beg, ios_base::out);
-        CHECK(off == len2d3);
+        CHECK((off == len2d3));
 
         off = b.pubseekoff(0 + len - 1, ios_base::beg, ios_base::out);
-        CHECK(off == len - 1);
+        CHECK((off == (len - 1)));
 
         off = b.pubseekoff(0 + len, ios_base::beg, ios_base::out);
-        CHECK(off == len);
+        CHECK((off == len));
 
         off = b.pubseekoff(0, ios_base::beg, ios_base::out);
         CHECK(off == 0);
@@ -1846,22 +1846,22 @@ TEST_CASE("output buffer - offset", "[Stream buffers]")
         CHECK(off == 0);
 
         off = b.pubseekoff(0 + len + len, ios_base::end, ios_base::out);
-        CHECK(off == len);
+        CHECK((off == len));
 
         off = b.pubseekoff(0, ios_base::end, ios_base::out);
-        CHECK(off == len);
+        CHECK((off == len));
 
         off = b.pubseekoff(0 - 1, ios_base::end, ios_base::out);
-        CHECK(off == len - 1);
+        CHECK((off == (len - 1)));
 
         off = b.pubseekoff(0 + 1, ios_base::end, ios_base::out);
-        CHECK(off == len);
+        CHECK((off == len));
 
         off = b.pubseekoff(0 - len1d3, ios_base::end, ios_base::out);
-        CHECK(off == len2d3);
+        CHECK((off == len2d3));
 
         off = b.pubseekoff(0 - len2d3, ios_base::end, ios_base::out);
-        CHECK(off == len1d3);
+        CHECK((off == len1d3));
 
         off = b.pubseekoff(0 - len + 1, ios_base::end, ios_base::out);
         CHECK(off == 1);
@@ -1872,10 +1872,10 @@ TEST_CASE("output buffer - offset", "[Stream buffers]")
         b.pubsetbuf(new char[len], len);
         b.sputn(exp, len);
         off = b.pubseekoff(- 1, ios_base::end, ios_base::out);
-        CHECK(off == len - 1);
+        CHECK((off == (len - 1)));
         b.sputn("!", 1);
         off = b.pubseekoff(0, ios_base::end, ios_base::out);
-        CHECK(off == len);
+        CHECK((off == len));
         EXP_RES(b, exp_alt, len, len);
     }
 
@@ -1897,31 +1897,31 @@ TEST_CASE("output buffer - offset", "[Stream buffers]")
 
         b.pubseekoff(len1d3, ios_base::beg, ios_base::out);
         off = b.pubseekoff(0 + len + len, ios_base::cur, ios_base::out);
-        CHECK(off == len);
+        CHECK((off == len));
 
         b.pubseekoff(len1d3, ios_base::beg, ios_base::out);
         off = b.pubseekoff(0, ios_base::cur, ios_base::out);
-        CHECK(off == len1d3);
+        CHECK((off == len1d3));
 
         b.pubseekoff(len1d3, ios_base::beg, ios_base::out);
         off = b.pubseekoff(0 - 1, ios_base::cur, ios_base::out);
-        CHECK(off == len1d3 - 1);
+        CHECK((off == (len1d3 - 1)));
 
         b.pubseekoff(len1d3, ios_base::beg, ios_base::out);
         off = b.pubseekoff(0 + 1, ios_base::cur, ios_base::out);
-        CHECK(off == len1d3 + 1);
+        CHECK((off == (len1d3 + 1)));
 
         b.pubseekoff(len1d3, ios_base::beg, ios_base::out);
         off = b.pubseekoff(0 + len1d3, ios_base::cur, ios_base::out);
-        CHECK(off == len1d3 + len1d3);
+        CHECK((off == (len1d3 + len1d3)));
 
         b.pubseekoff(len1d3, ios_base::beg, ios_base::out);
         off = b.pubseekoff(0 + len2d3, ios_base::cur, ios_base::out);
-        CHECK(off == len);
+        CHECK((off == len));
 
         b.pubseekoff(len1d3, ios_base::beg, ios_base::out);
         off = b.pubseekoff(0 + len, ios_base::cur, ios_base::out);
-        CHECK(off == len);
+        CHECK((off == len));
 
         b.pubsetbuf(new char[len], len);
         b.sputn(exp, len);
@@ -1930,7 +1930,7 @@ TEST_CASE("output buffer - offset", "[Stream buffers]")
         CHECK(off == len - off_alt);
         b.sputn(ovr_alt, off_alt);
         off = b.pubseekoff(0, ios_base::end, ios_base::out);
-        CHECK(off == len);
+        CHECK((off == len));
         EXP_RES(b, exp_alt, len, len);
     }
 }
index af9d9824bd91bc87b922fcb5c60cf9daca455f6f..d6dec9be9bd66c76bca203ba1fe7ee6c5b60b074 100644 (file)
@@ -520,25 +520,6 @@ char* snort_strdup(const char* str)
     return p;
 }
 
-const uint8_t* snort_memrchr(const uint8_t* buf, char c, size_t len)
-{
-#ifdef HAVE_MEMRCHR
-    return (const uint8_t*)memrchr(buf, c, len);
-#else
-    size_t n = len;
-    const uint8_t* tmp = buf;
-    const uint8_t* ptr = nullptr;
-
-    while ( n > 0 && (tmp = (const uint8_t*)memchr(tmp, c, n)) )
-    {
-        ptr = tmp++;
-        n = len - (tmp - buf);
-    }
-
-    return ptr;
-#endif
-}
-
 void ts_print(const struct timeval* tvp, char* timebuf, bool yyyymmdd)
 {
     struct timeval tv;
index a8d3302f881ee5336c2504ef70dd3732b3af5a76..096a39d0d1cc55cfbfecfeaba25d1253f2c11ee3 100644 (file)
@@ -94,7 +94,7 @@ inline void snort_free(void* p)
 inline pid_t gettid()
 {
 #if defined(__linux__) && defined(SYS_gettid)
-    return syscall(SYS_gettid);
+    return syscall(SYS_gettid); // cppcheck-suppress ConfigurationNotChecked
 #else
     return getpid();
 #endif
@@ -108,7 +108,6 @@ SO_PUBLIC extern char** protocol_names;
 SO_PUBLIC const char* get_error(int errnum);
 SO_PUBLIC char* snort_strdup(const char*);
 SO_PUBLIC char* snort_strndup(const char*, size_t);
-SO_PUBLIC const uint8_t* snort_memrchr(const uint8_t*, char, size_t);
 SO_PUBLIC void ts_print(const struct timeval*, char*, bool yyyymmdd = false);
 void uint8_to_printable_str(const uint8_t* buff, unsigned len, std::string& print_str);
 }
index e5a890cb6346cc6b8244f4b33bbf2fc599c30672..14ff461224fd77b64a26527d47c78acb08038839 100644 (file)
@@ -171,7 +171,7 @@ static const int valid_chars[256] =
 
 struct JSNorm
 {
-    uint8_t state;
+    uint8_t state;  // cppcheck-suppress unusedStructMember
     uint8_t event;
     uint8_t match;
     uint8_t other;
@@ -968,7 +968,7 @@ static int Unescape_exec(UnescapeState* s, ActionUnsc a, int c, JSState* js)
             if (s->unicode_map && (s->iNorm <= 0xffff))
             {
                 s->iNorm = s->unicode_map[s->iNorm];
-                if (s->iNorm == -1)
+                if (s->iNorm == -1) // cppcheck-suppress knownConditionTrueFalse
                     s->iNorm = NON_ASCII_CHAR;
             }
             else
@@ -994,7 +994,7 @@ static int Unescape_exec(UnescapeState* s, ActionUnsc a, int c, JSState* js)
             if (s->unicode_map && (s->iNorm <= 0xffff))
             {
                 s->iNorm = s->unicode_map[s->iNorm];
-                if (s->iNorm == -1)
+                if (s->iNorm == -1) // cppcheck-suppress knownConditionTrueFalse
                     s->iNorm = NON_ASCII_CHAR;
             }
             else
index e341ae6bd52ccf21211bf15d6551bb963d99bdad..a9e012d61ad0aa4e5fd64d684602d562cef06f42 100644 (file)
@@ -71,4 +71,4 @@ public:
     }
 };
 #endif // HAVE_NUMA
-#endif // NUMA_UTILS_H
\ No newline at end of file
+#endif // NUMA_UTILS_H
index 70bbdc06293c4300bcf127e05ee45fcc58fe61e2..ac2a5010f11269ba63e1c18f27b606a52ac6aad9 100644 (file)
 
 using namespace snort;
 
-UtfDecodeSession::UtfDecodeSession()
-{
-    init_decode_utf_state();
-}
-
-/* init a new decode_utf_state_t */
-void UtfDecodeSession::init_decode_utf_state()
-{
-    dstate.state = DSTATE_FIRST;
-    dstate.charset = CHARSET_DEFAULT;
-    dstate.charset_src = CHARSET_SET_BY_GUESS;
-}
-
 /* setters & getters */
 void UtfDecodeSession::set_decode_utf_state_charset(CharsetCode charset, CharsetSrc src)
 {
index be30bafcd59e310dee0974a16dde85fd3e1a5310..9c9d6a0ce100bff4d9e38846f1e2db08f5f006f3 100644 (file)
@@ -51,9 +51,9 @@ enum CharsetSrc
 // state between subsequent calls.
 struct decode_utf_state_t
 {
-    int state;
-    CharsetCode charset;
-    CharsetSrc charset_src;
+    int state = 0;
+    CharsetCode charset = CHARSET_DEFAULT;
+    CharsetSrc charset_src = CHARSET_SET_BY_GUESS;
 };
 
 namespace snort
@@ -61,9 +61,8 @@ namespace snort
 class SO_PUBLIC UtfDecodeSession
 {
 public:
-    UtfDecodeSession();
+    UtfDecodeSession() = default;
     virtual ~UtfDecodeSession() = default;
-    void init_decode_utf_state();
     void set_decode_utf_state_charset(CharsetCode charset, CharsetSrc src = CHARSET_SET_BY_APP);
     CharsetCode get_decode_utf_state_charset();
     CharsetSrc get_decode_utf_charset_src();
index 29fe61b6208034a04ab55b5d8dc4a0fe1ed61286..f030dd4f4c13f4e6f8f2ceca7c697cf25a339443 100644 (file)
@@ -356,7 +356,7 @@ protected:
                 // found an option without a colon, so set stream to semi-colon
                 std::streamoff off = 1 + (std::streamoff)(pos) + (std::streamoff)(semi_colon_pos);
                 stream.seekg(off);
-                keyword = keyword.substr(0, semi_colon_pos);
+                keyword.resize(semi_colon_pos);
             }
 
             // now, lets get the next option.
index e6a93dd847268c21989aa9bf0747bb59ff0a4356..3b297f84945e368e355139d73a502e3c278080e4 100644 (file)
@@ -33,10 +33,10 @@ public:
     Option(const std::string& name, std::string val, int depth);
     virtual ~Option() = default;
 
-    inline const std::string& get_name()
+    inline const std::string& get_name() const
     { return name; }
 
-    inline const std::string& get_value()
+    inline const std::string& get_value() const
     { return value; }
 
     void set_print_whitespace(bool w)
index 3485ce50506084429b3f51e17ba0e5163885fdf5..8750d991f46f48ef749b0fca524c62e3c6b89970 100644 (file)
@@ -22,6 +22,8 @@
 #include "helpers/s2l_util.h"
 #include "data/data_types/dt_rule_option.h"
 
+#include <algorithm>
+
 Rule::Rule() :  num_hdr_data(0),
     is_bad_rule(false),
     is_comment(false), old_http_rule(false)
@@ -88,24 +90,17 @@ void Rule::add_option(const std::string& keyword, const std::string& data)
 
 std::string Rule::get_option(const std::string& keyword)
 {
-    for (auto option : options)
-    {
-        if (option->get_name() == keyword)
-            return option->get_value();
-    }
-    return std::string();
+    auto it = std::find_if(options.cbegin(), options.cend(),
+        [&keyword](const RuleOption* option){ return option->get_name() == keyword; });
+    return (it != options.cend()) ? (*it)->get_value() : std::string();
 }
 
 void Rule::update_option(const std::string& keyword, const std::string& val)
 {
-    for (auto option : options)
-    {
-        if (option->get_name() == keyword)
-        {
-            option->update_value(val);
-            break;
-        }
-    }
+    auto it = std::find_if(options.begin(), options.end(),
+        [&keyword](const RuleOption* option){ return option->get_name() == keyword; });
+    if (it != options.end())
+        (*it)->update_value(val);
 }
 
 void Rule::add_suboption(const std::string& keyword)
@@ -167,7 +162,7 @@ std::ostream& operator<<(std::ostream& out, const Rule& rule)
         out << " (";
         first_line = true;
 
-        for (auto* r : rule.options)
+        for (const auto* r : rule.options)
         {
             if (first_line)
                 first_line = false;
index aacbddca9507a20e1526dccbefef731a1ecd203c..a33d44d2fe8bd63e2cf24de1e62e68081a280a55 100644 (file)
@@ -67,7 +67,7 @@ std::ostream& operator<<(std::ostream& out, const RuleOption& opt)
         out << ':' << opt.value;
     }
 
-    for (RuleSubOption* rso : opt.sub_options)
+    for (const RuleSubOption* rso : opt.sub_options)
     {
         if (first_print)
             first_print = false;
index 4b84fb5f7a06d6b9f2b438324cb1261e1bb41952..c8da44905f0c81e70e975b245978b0b35c6d6fcf 100644 (file)
@@ -33,8 +33,8 @@ public:
     RuleOption(const std::string& name, const std::string& val);
     virtual ~RuleOption();
 
-    inline const std::string& get_name() { return name; }
-    inline const std::string& get_value() { return value; }
+    inline const std::string& get_name() const { return name; }
+    inline const std::string& get_value() const { return value; }
     inline void update_value(const std::string& new_value) { value = new_value; }
 
     bool add_suboption(const std::string& name);
index 8d26e8566deb7df6a42404b2ea51b7d14c807867..767f329bdfb6effe52e58dc374fc0eb94f0307ca 100644 (file)
 #include "data/data_types/dt_var.h"
 #include "data/data_types/dt_comment.h"
 
+#include <algorithm>
+
 static inline Table* find_table(std::vector<Table*> vec, const std::string& name)
 {
-    for ( auto* t : vec)
-        if (name == t->get_name())
-            return t;
-
-    return nullptr;
+    auto it = std::find_if(vec.begin(), vec.end(), [&name](const Table* t){ return name == t->get_name(); });
+    return (it != vec.end()) ? *it : nullptr;
 }
 
 Table::Table(int d)
@@ -74,16 +73,12 @@ Table::~Table()
     delete comments;
 }
 
-bool Table::has_differences()
+bool Table::has_differences() const
 {
     if (!comments->empty())
         return true;
 
-    for (Table* t : tables)
-        if (t->has_differences())
-            return true;
-
-    return false;
+    return std::any_of(tables.cbegin(), tables.cend(), [](const Table* t){ return t->has_differences(); });
 }
 
 Table* Table::open_table()
@@ -171,9 +166,10 @@ void Table::append_option(const std::string& opt_name, const std::string& value)
 
 bool Table::add_list(const std::string& list_name, const std::string& next_elem)
 {
-    for (auto l : lists)
-        if (l->get_name() == list_name)
-            return l->add_value(next_elem);
+    auto it = std::find_if(lists.begin(), lists.end(),
+        [&list_name](const Variable* l){ return l->get_name() == list_name; });
+    if (it != lists.end())
+        return (*it)->add_value(next_elem);
 
     Variable* var = new Variable(list_name, depth + 1);
     lists.push_back(var);
@@ -182,47 +178,43 @@ bool Table::add_list(const std::string& list_name, const std::string& next_elem)
 
 bool Table::has_option(const std::string& opt_name)
 {
-    for (Option* o : options)
-        if (opt_name == o->get_name())
-            return true;
-
-    for (Option* a : append_options)
-        if (opt_name == a->get_name())
-            return true;
+    if (std::any_of(options.cbegin(), options.cend(),
+        [&opt_name](const Option* o){ return opt_name == o->get_name(); }))
+        return true;
 
-    return false;
+    return std::any_of(append_options.cbegin(), append_options.cend(),
+        [&opt_name](const Option* a){ return opt_name == a->get_name(); });
 }
 
 bool Table::get_option(const std::string& opt_name, std::string& value)
 {
-    for (Option* o : options)
-        if (opt_name == o->get_name())
-        {
-            value = o->get_value();
-            return true;
-        }
+    auto it = std::find_if(options.cbegin(), options.cend(),
+        [&opt_name](const Option* o){ return opt_name == o->get_name(); });
+    if (it != options.cend())
+    {
+        value = (*it)->get_value();
+        return true;
+    }
 
-    for (Option* a : append_options)
-        if (opt_name == a->get_name())
-        {
-            value = a->get_value();
-            return true;
-        }
+    auto a_it = std::find_if(append_options.cbegin(), append_options.cend(),
+        [&opt_name](const Option* a){ return opt_name == a->get_name(); });
+    if (a_it != append_options.cend())
+    {
+        value = (*it)->get_value();
+        return true;
+    }
 
     return false;
 }
 
 bool Table::has_option(const Option& opt)
 {
-    for (Option* o : options)
-        if ( (*o) == opt)
-            return true;
-
-    for (Option* a : append_options)
-        if ( (*a) == opt)
-            return true;
+    if (std::any_of(options.cbegin(), options.cend(),
+        [&opt](const Option* o){ return opt == *o; }))
+        return true;
 
-    return false;
+    return std::any_of(append_options.cbegin(), append_options.cend(),
+        [&opt](const Option* a){ return opt == *a; });
 }
 
 bool Table::has_option(const std::string& opt_name, int val)
index 76f3dcad53124a581542b7baa36e20f72d26b8e5..bfa041e6b4d7ee55cccc6def7b97672b73e70d2c 100644 (file)
@@ -36,10 +36,10 @@ public:
     Table(const std::string& name, const std::string& key, int depth);
     virtual ~Table();
 
-    inline const std::string& get_name() { return name; }
+    inline const std::string& get_name() const { return name; }
     void set_one_line(bool o) { one_line = o; }
     void set_print_whitespace(bool w) { print_whitespace = w; }
-    bool has_differences();
+    bool has_differences() const;
     Table* open_table();
     Table* open_table(const std::string&);
     bool add_option(const std::string& val);
index dd0ae1687f7a2bc3595e05c434da7469d8dc2b07..25a1a642d2a88b636ad154c4ed2f188822d0b70b 100644 (file)
@@ -371,10 +371,10 @@ void DataApi::print_errors(std::ostream& out) const
 
 void DataApi::print_data(std::ostream& out) const
 {
-    for (Variable* v : vars)
+    for (const Variable* v : vars)
         out << (*v) << "\n\n";
 
-    for (Include* i : includes)
+    for (const Include* i : includes)
         out << (*i) << "\n\n";
 }
 
index 727d0b9fb47072ba92ea49dc5e8569bc951fc565..922c71253a867b2969ebedb80512ae4df1f404c0 100644 (file)
@@ -287,7 +287,7 @@ std::ostream& operator<<(std::ostream& out, const RuleApi& data)
     }
 
     out << "local_rules =\n[[\n";
-    for (Rule* r : data.rules)
+    for (const Rule* r : data.rules)
         out << (*r) << "\n\n";
 
     out << "]]\n\n\n";
@@ -303,7 +303,7 @@ void RuleApi::print_rules(std::ostream& out, bool in_rule_file)
     if (!in_rule_file)
         out << "local_rules =\n[[\n";
 
-    for (Rule* r : rules)
+    for (const Rule* r : rules)
         out << (*r) << "\n";
 
     if (!in_rule_file)
index 1dacc0b3925d76b7dc50ca466cfffd4a5848193f..26e27fa9c167a4af87138347f50cfc1151adb2b1 100644 (file)
@@ -68,7 +68,7 @@ void StateApi::print_states(std::ostream& out) const
 
     out << "local_states =\n[[\n";
 
-    for (const auto r : states)
+    for (const auto* r : states)
         out << (*r) << "\n";
 
     out << "]]\n\n";
index 80199357c4834c67719bc2bca879a54bf1d88832..d009c36f8b88367e29916145bd7ce50939f334f6 100644 (file)
@@ -57,8 +57,8 @@ bool TableApi::should_delegate(const std::string& table_name) const
 void TableApi::reset_state()
 {
     // DO NOT RESET DELEGATE STATE. IT HAS ITS OWN LIFECYCLE.
-    std::stack<Table*> empty;
-    open_tables.swap(empty);
+    std::stack<Table*> empty_table;
+    open_tables.swap(empty_table);
     std::stack<unsigned> empty_two;
     top_level_tables.swap(empty_two);
     curr_data_bad = false;
@@ -422,7 +422,7 @@ void TableApi::print_tables(std::ostream& out) const
     if ( empty() )
         return;
 
-    for (Table* t : tables)
+    for (const Table* t : tables)
         out << (*t) << "\n\n";
 }
 
@@ -454,9 +454,7 @@ void TableApi::run_when_exists(const char* table_name, PendingFunction action)
         action(*this);
     else
     {
-        if ( pending.find(table_name) == pending.end() )
-            pending[table_name] = std::queue<PendingFunction>();
-
+        pending.emplace(table_name, std::queue<PendingFunction>());
         pending[table_name].push(action);
     }
 }
index 16a6e7ac44ad84b43cb079845247a83f1fbb7199..25b78310e6468efd149fcac38bd3d96735a7542a 100644 (file)
@@ -378,7 +378,7 @@ Binder& Converter::make_binder()
 void Converter::add_bindings()
 {
     std::unordered_map<int, std::shared_ptr<Binder>> policy_map;
-    for ( auto& b : binders )
+    for ( const auto& b : binders )
     {
         if ( b->has_ips_policy_id() && b->get_use_file().second == Binder::IT_FILE )
             policy_map[b->get_when_ips_policy_id()] = b;
index 2cf60d760c5320a2199f827671eb9d8362d8fde2..60d48c20d29cb3840bb8798b06edc0f2e0e30dad 100644 (file)
@@ -73,7 +73,7 @@ const std::unique_ptr<const ConvertMap>& find_map(
     const std::string& keyword,
     bool strict_case)
 {
-    for (auto& p : map)
+    for (const auto& p : map)
     {
         if (strict_case)
         {
@@ -96,11 +96,8 @@ Table* find_table(const std::vector<Table*>& vec, const std::string& name)
     if (name.empty())
         return nullptr;
 
-    for ( auto* t : vec)
-        if (name == t->get_name())
-            return t;
-
-    return nullptr;
+    auto it = std::find_if(vec.begin(), vec.end(), [&name](const Table* t){ return name == t->get_name(); });
+    return (it != vec.end()) ? (*it) : nullptr;
 }
 
 std::string& ltrim(std::string& s)
index bfaa70a21056fce5908862c73f44d90b6e0ff0e4..06a9d0d9147b30e30b260765713065fb89de806f 100644 (file)
@@ -203,9 +203,6 @@ void Binder::set_use_file(const std::string& file_name, IncludeType type)
     use_file_type = type;
 }
 
-void Binder::set_use_service(const std::string& service_name)
-{ use_service = service_name; }
-
 void Binder::set_use_action(const std::string& action)
 { use_action = action; }
 
index 0c003f1ab348d16328519984b29d447bc43c7379..8d4d06061bdb2592b811616d9436ec27b2d03536 100644 (file)
@@ -117,7 +117,6 @@ public:
     void set_use_type(const std::string& module_name);
     void set_use_name(const std::string& struct_name);
     void set_use_file(const std::string& file_name, IncludeType = IT_FILE);
-    void set_use_service(const std::string& service_name);
     void set_use_action(const std::string& action);
 
     std::string get_use_type() const
index 8f5fec864dfaec0d3960c6357940888fafd881b7..bdb34928295ccb3e78e4f4fe536c66537465ef05 100644 (file)
@@ -50,7 +50,7 @@ bool RuleHeader::convert(std::istringstream& data_stream)
     const std::istringstream::off_type curr_pos = data_stream.tellg();
     std::string rule_string = data_stream.str();
     std::size_t end_pos = rule_string.rfind(')');
-    rule_string = rule_string.substr(0, end_pos);
+    rule_string.resize(end_pos);
     util::rtrim(rule_string); // guarantee last char is a rule opt/subopt
     data_stream.str(rule_string);
     data_stream.seekg(curr_pos);  // position was reset. so find curr position
index e74f633d8bf0ebab57b244bfdee23edfe4966c65..f0ec125a4a9c5a4687b159cc2ca9f2d43af63b6b 100644 (file)
@@ -121,13 +121,13 @@ bool RuleType::convert(std::istringstream& stream)
                 if (map)
                 {
                     // using smart pointer to guarantee new Map is deleted
-                    const std::vector<std::unique_ptr<const ConvertMap> >& ruletype_map =
+                    const std::vector<std::unique_ptr<const ConvertMap> >& tmp_ruletype_map =
                         ruletype_api;
                     std::unique_ptr<ConvertMap> new_map(new ConvertMap());
                     new_map->keyword = name;
                     new_map->ctor = map->ctor;
                     const_cast<std::vector<std::unique_ptr<const ConvertMap> >&>(
-                        ruletype_map).push_back(std::move(new_map));
+                        tmp_ruletype_map).push_back(std::move(new_map));
                     return true;
                 }
                 else
index eebad524fd040a17545eb5846812f96310e5bae0..85f5c38b7665533b6457b0fd44f5e92c7651d117 100644 (file)
@@ -299,8 +299,8 @@ std::set<std::string> ftp_format_commands =
 
 struct FtpDefaultCmd
 {
-    std::string default_name;
-    std::set<std::string> cmd_set;
+    std::string default_name;   // cppcheck-suppress unusedStructMember
+    std::set<std::string> cmd_set;  // cppcheck-suppress unusedStructMember
 };
 
 // Use these defaults for the entries that the original config didn't provide.
index 7c87ca11bf71ac5f9ea9ff42482b231876416f6f..bcc937e232005eef0f92fb3de714943229ccf883 100644 (file)
@@ -39,7 +39,6 @@ public:
 bool Base64Decode::convert(std::istringstream& data_stream)
 {
     std::string args;
-    std::string tmp;
     std::streamoff pos = data_stream.tellg();
 
     args = util::get_rule_option_args(data_stream);
@@ -60,6 +59,7 @@ bool Base64Decode::convert(std::istringstream& data_stream)
         {
             // since we still can't be sure if we passed the base64_decode buffer,
             // check the next option and ensure it matches
+            std::string tmp;
             std::istringstream arg_stream(args);
             if (util::get_string(arg_stream, tmp, ", ") &&
                 (tmp == "bytes" ||
index dc1a2a370fb3dc199948ad23ba4e6e471828a30a..8b2f1876ffd6625e5907cdd647dfdeaa12171dae 100644 (file)
@@ -39,18 +39,18 @@ public:
 bool DNP3Obj::convert(std::istringstream& data)
 {
     std::string val = util::get_rule_option_args(data);
-    std::string group = "group ";
-    std::string var = " var ";
 
     /* convert from dnp3_obj: xxx,xxx to
      * dnp3_obj: group xxx, var xxxx
      */
-    val.insert(0, group);
+    val.insert(0, "group ");
     size_t start_pos = val.find(',');
     if (start_pos == std::string::npos)
         rule_api.bad_rule(data, "dnp3_obj:expecting 2 args separated by comma");
     else
-        val.insert(start_pos+1, var);
+    {
+        val.insert(start_pos+1, " var ");
+    }
 
     rule_api.add_option("dnp3_obj", val);
     return set_next_rule_state(data);
index 1e879539520369ef5552744697790657b1468983..9152f171be9f97128111606fb30c605cad9f4014 100644 (file)
@@ -40,7 +40,6 @@ public:
 bool FileData::convert(std::istringstream& data_stream)
 {
     std::string args;
-    std::string tmp;
     std::streamoff pos = data_stream.tellg();
 
     rule_api.add_option("file_data");
@@ -62,6 +61,7 @@ bool FileData::convert(std::istringstream& data_stream)
         {
             // since we still can't be sure if we passed the file_data buffer,
             // check the next option and ensure it matches 'mime'
+            std::string tmp;
             std::istringstream(args) >> tmp;
 
             if (tmp == "mime")
index 63f76c0d05201ed94d51e72c77b463ad7686d3bd..739ba758f95a1fe4f0e2908e1b97ea6d58e32e7f 100644 (file)
@@ -40,7 +40,6 @@ public:
 bool React::convert(std::istringstream& data_stream)
 {
     std::string args;
-    std::string tmp;
     std::istringstream::off_type pos = data_stream.tellg();
 
     args = util::get_rule_option_args(data_stream);
@@ -60,6 +59,7 @@ bool React::convert(std::istringstream& data_stream)
         {
             // since we still can't be sure if we passed the resp buffer,
             // check the next option and ensure it matches
+            std::string tmp;
             std::istringstream arg_stream(args);
             if (util::get_string(arg_stream, tmp, ",") &&
                 (tmp == "msg" ||
index 219ec6943dead6a41294d4a53667d635884ddab0..9521d1a8a81f2589421860c17ce707e3cf9467bf 100644 (file)
@@ -49,7 +49,6 @@ void Resp::add_diff_comment(const std::string& old_v, const std::string& new_v)
 bool Resp::convert(std::istringstream& data_stream)
 {
     std::string args;
-    std::string tmp;
     std::streamoff pos = data_stream.tellg();
 
     args = util::get_rule_option_args(data_stream);
@@ -68,6 +67,7 @@ bool Resp::convert(std::istringstream& data_stream)
         {
             // since we still can't be sure if we passed the resp buffer,
             // check the next option and ensure it matches
+            std::string tmp;
             std::istringstream arg_stream(args);
             if (util::get_string(arg_stream, tmp, ",") &&
                 (tmp == "reset_dest" ||
index 37cadbc7a375fb6a24d5fd7748e583e29202acd5..b9e3c0110a81cd120f4040b284eb9fb03fb7fda8 100644 (file)
@@ -40,7 +40,6 @@ bool Tag::convert(std::istringstream& data_stream)
 {
     std::string args;
     std::string value;
-    std::string type;
 
     args = util::get_rule_option_args(data_stream);
     std::istringstream arg_stream(args);
@@ -112,6 +111,7 @@ bool Tag::convert(std::istringstream& data_stream)
             cnt = !cnt;
         }
 
+        std::string type;
         if (is_host)
         {
             if (value == "src")
index 6dfd9cd608e0b5b8c16f22a70811fd235397dcfe..00c7f6c133ae9128b56040ce1546a4d4b5fb7950 100644 (file)
@@ -97,7 +97,7 @@ bool Threshold::convert(std::istringstream& data_stream)
             std::streamoff off = 1 + (std::streamoff)(tmp_pos) +
                 (std::streamoff)(semi_colon_pos);
             data_stream.seekg(off);
-            rule_keyword = rule_keyword.substr(0, semi_colon_pos);
+            rule_keyword.resize(semi_colon_pos);
         }
 
         // now, lets get the next option.