From d1469db05441f4526b0cf77da7ae7226ae2b701d Mon Sep 17 00:00:00 2001 From: Jason Ish Date: Mon, 4 Dec 2023 13:31:12 -0600 Subject: [PATCH] reorg: clang-format src/* --- src/action-globals.h | 16 +- src/alert-debuglog.c | 229 +- src/alert-debuglog.h | 1 - src/alert-fastlog.c | 61 +- src/alert-fastlog.h | 1 - src/alert-syslog.c | 50 +- src/alert-syslog.h | 1 - src/app-layer-detect-proto.c | 921 ++--- src/app-layer-detect-proto.h | 40 +- src/app-layer-dnp3-objects.c | 1560 ++++----- src/app-layer-dnp3-objects.h | 1345 ++++--- src/app-layer-dnp3.c | 400 +-- src/app-layer-dnp3.h | 70 +- src/app-layer-enip-common.c | 367 +- src/app-layer-enip-common.h | 152 +- src/app-layer-enip.c | 223 +- src/app-layer-enip.h | 1 - src/app-layer-events.c | 31 +- src/app-layer-events.h | 4 +- src/app-layer-expectation.c | 20 +- src/app-layer-expectation.h | 4 +- src/app-layer-frames.h | 8 +- src/app-layer-ftp.c | 205 +- src/app-layer-ftp.h | 9 +- src/app-layer-htp-body.c | 11 +- src/app-layer-htp-file.c | 147 +- src/app-layer-htp-mem.c | 11 +- src/app-layer-htp-xff.c | 58 +- src/app-layer-htp-xff.h | 5 +- src/app-layer-htp.c | 1318 +++---- src/app-layer-htp.h | 71 +- src/app-layer-http2.c | 8 +- src/app-layer-krb5.c | 3 +- src/app-layer-modbus.c | 511 ++- src/app-layer-mqtt.c | 3 +- src/app-layer-nfs-tcp.c | 1 - src/app-layer-nfs-udp.c | 7 +- src/app-layer-ntp.c | 3 +- src/app-layer-parser.c | 382 +- src/app-layer-parser.h | 119 +- src/app-layer-rdp.c | 3 +- src/app-layer-register.c | 75 +- src/app-layer-register.h | 15 +- src/app-layer-rfb.c | 71 +- src/app-layer-smb.c | 107 +- src/app-layer-smtp.c | 522 ++- src/app-layer-smtp.h | 4 +- src/app-layer-snmp.c | 1 - src/app-layer-ssh.c | 429 +-- src/app-layer-ssh.h | 1 - src/app-layer-ssl.c | 596 ++-- src/app-layer-ssl.h | 63 +- src/app-layer-tftp.c | 61 +- src/app-layer-tftp.h | 2 +- src/app-layer.c | 208 +- src/app-layer.h | 7 +- src/conf-yaml-loader.c | 138 +- src/conf.c | 93 +- src/conf.h | 14 +- src/counters.c | 101 +- src/counters.h | 8 +- src/datasets-md5.c | 2 +- src/datasets-sha256.c | 2 +- src/datasets-string.c | 5 +- src/datasets.c | 89 +- src/datasets.h | 8 +- src/decode-chdlc.c | 13 +- src/decode-chdlc.h | 2 +- src/decode-erspan.c | 11 +- src/decode-erspan.h | 1 - src/decode-ethernet.c | 24 +- src/decode-ethernet.h | 44 +- src/decode-events.h | 3 +- src/decode-gre.c | 119 +- src/decode-gre.h | 56 +- src/decode-icmpv4.c | 190 +- src/decode-icmpv4.h | 172 +- src/decode-icmpv6.c | 210 +- src/decode-icmpv6.h | 209 +- src/decode-ipv4.c | 198 +- src/decode-ipv4.h | 207 +- src/decode-ipv6.c | 190 +- src/decode-ipv6.h | 229 +- src/decode-mpls.c | 91 +- src/decode-nsh.h | 1 - src/decode-null.c | 5 +- src/decode-ppp.c | 49 +- src/decode-ppp.h | 65 +- src/decode-pppoe.c | 58 +- src/decode-pppoe.h | 39 +- src/decode-raw.c | 31 +- src/decode-raw.h | 1 - src/decode-sctp.c | 13 +- src/decode-sctp.h | 33 +- src/decode-sll.c | 8 +- src/decode-sll.h | 13 +- src/decode-tcp.c | 117 +- src/decode-tcp.h | 246 +- src/decode-template.c | 11 +- src/decode-teredo.c | 18 +- src/decode-teredo.h | 4 +- src/decode-udp.c | 46 +- src/decode-udp.h | 62 +- src/decode-vlan.c | 42 +- src/decode-vlan.h | 13 +- src/decode-vxlan.c | 21 +- src/decode.c | 60 +- src/decode.h | 343 +- src/defrag-config.c | 10 +- src/defrag-hash.c | 113 +- src/defrag-hash.h | 48 +- src/defrag-queue.c | 13 +- src/defrag-queue.h | 40 +- src/defrag-timeout.c | 1 - src/defrag-timeout.h | 1 - src/defrag.c | 1197 +++---- src/defrag.h | 36 +- src/detect-app-layer-event.c | 27 +- src/detect-app-layer-protocol.c | 168 +- src/detect-asn1.c | 615 +++- src/detect-asn1.h | 2 +- src/detect-base64-data.c | 28 +- src/detect-base64-data.h | 3 +- src/detect-base64-decode.c | 105 +- src/detect-base64-decode.h | 4 +- src/detect-bsize.c | 8 +- src/detect-bsize.h | 2 +- src/detect-bypass.c | 13 +- src/detect-byte-extract.c | 1861 ++++------ src/detect-byte-extract.h | 8 +- src/detect-bytejump.c | 199 +- src/detect-bytejump.h | 37 +- src/detect-bytemath.c | 74 +- src/detect-bytetest.c | 238 +- src/detect-bytetest.h | 36 +- src/detect-cipservice.c | 89 +- src/detect-cipservice.h | 32 +- src/detect-classtype.c | 40 +- src/detect-classtype.h | 1 - src/detect-config.c | 39 +- src/detect-config.h | 2 +- src/detect-content.c | 380 +- src/detect-content.h | 61 +- src/detect-csum.c | 229 +- src/detect-csum.h | 1 - src/detect-datarep.c | 37 +- src/detect-datarep.h | 13 +- src/detect-dataset.c | 57 +- src/detect-dataset.h | 7 +- src/detect-dce-iface.c | 16 +- src/detect-dce-iface.h | 1 - src/detect-dce-opnum.c | 15 +- src/detect-dce-opnum.h | 1 - src/detect-dce-stub-data.c | 279 +- src/detect-dce-stub-data.h | 1 - src/detect-depth.c | 25 +- src/detect-depth.h | 3 +- src/detect-detection-filter.h | 3 +- src/detect-distance.c | 20 +- src/detect-distance.h | 3 +- src/detect-dnp3.c | 225 +- src/detect-dnp3.h | 4 +- src/detect-dns-opcode.c | 17 +- src/detect-dns-query.c | 149 +- src/detect-dns-query.h | 2 +- src/detect-dsize.c | 28 +- src/detect-dsize.h | 3 +- src/detect-engine-address-ipv4.c | 104 +- src/detect-engine-address-ipv4.h | 4 +- src/detect-engine-address-ipv6.c | 178 +- src/detect-engine-address-ipv6.h | 4 +- src/detect-engine-address.c | 1245 ++++--- src/detect-engine-address.h | 6 +- src/detect-engine-alert.c | 4 +- src/detect-engine-analyzer.c | 96 +- src/detect-engine-build.c | 225 +- src/detect-engine-build.h | 5 +- src/detect-engine-content-inspection.c | 106 +- src/detect-engine-content-inspection.h | 13 +- src/detect-engine-dcepayload.c | 85 +- src/detect-engine-enip.c | 116 +- src/detect-engine-event.c | 61 +- src/detect-engine-event.h | 4 +- src/detect-engine-file.c | 2 +- src/detect-engine-iponly.c | 678 ++-- src/detect-engine-iponly.h | 1 - src/detect-engine-loader.c | 53 +- src/detect-engine-loader.h | 4 +- src/detect-engine-mpm.c | 224 +- src/detect-engine-mpm.h | 13 +- src/detect-engine-payload.c | 262 +- src/detect-engine-payload.h | 12 +- src/detect-engine-port.c | 446 ++- src/detect-engine-port.h | 5 +- src/detect-engine-prefilter-common.c | 164 +- src/detect-engine-prefilter-common.h | 22 +- src/detect-engine-prefilter.c | 91 +- src/detect-engine-prefilter.h | 18 +- src/detect-engine-profile.c | 5 +- src/detect-engine-profile.h | 8 +- src/detect-engine-proto.c | 51 +- src/detect-engine-proto.h | 22 +- src/detect-engine-register.c | 6 +- src/detect-engine-siggroup.c | 37 +- src/detect-engine-siggroup.h | 6 +- src/detect-engine-sigorder.c | 167 +- src/detect-engine-sigorder.h | 2 +- src/detect-engine-state.c | 177 +- src/detect-engine-state.h | 19 +- src/detect-engine-tag.c | 457 +-- src/detect-engine-tag.h | 6 +- src/detect-engine-threshold.c | 91 +- src/detect-engine-threshold.h | 5 +- src/detect-engine-uint.c | 12 +- src/detect-engine.c | 507 ++- src/detect-engine.h | 40 +- src/detect-fast-pattern.c | 41 +- src/detect-fast-pattern.h | 4 +- src/detect-file-data.c | 26 +- src/detect-file-data.h | 2 +- src/detect-file-hash-common.c | 51 +- src/detect-file-hash-common.h | 4 +- src/detect-filemagic.c | 28 +- src/detect-filemagic.h | 2 +- src/detect-filemd5.c | 6 +- src/detect-filemd5.h | 2 +- src/detect-filename.c | 48 +- src/detect-filename.h | 2 +- src/detect-filesha1.c | 6 +- src/detect-filesha1.h | 2 +- src/detect-filesha256.c | 6 +- src/detect-filesha256.h | 2 +- src/detect-filesize.c | 22 +- src/detect-filesize.h | 4 +- src/detect-filestore.c | 72 +- src/detect-filestore.h | 16 +- src/detect-flow.c | 208 +- src/detect-flow.h | 7 +- src/detect-flowbits.c | 277 +- src/detect-flowbits.h | 3 +- src/detect-flowint.c | 348 +- src/detect-flowint.h | 7 +- src/detect-flowvar.c | 52 +- src/detect-flowvar.h | 9 +- src/detect-fragbits.c | 80 +- src/detect-fragbits.h | 3 +- src/detect-fragoffset.c | 79 +- src/detect-ftpbounce.c | 31 +- src/detect-ftpbounce.h | 3 +- src/detect-ftpdata.c | 39 +- src/detect-geoip.c | 144 +- src/detect-geoip.h | 7 +- src/detect-gid.c | 16 +- src/detect-gid.h | 3 +- src/detect-hostbits.c | 142 +- src/detect-hostbits.h | 2 +- src/detect-http-accept-enc.c | 15 +- src/detect-http-accept-lang.c | 15 +- src/detect-http-accept.c | 15 +- src/detect-http-client-body.c | 28 +- src/detect-http-connection.c | 15 +- src/detect-http-content-len.c | 17 +- src/detect-http-content-type.c | 17 +- src/detect-http-cookie.c | 38 +- src/detect-http-cookie.h | 5 +- src/detect-http-header-common.c | 8 +- src/detect-http-header-common.h | 11 +- src/detect-http-header-names.c | 30 +- src/detect-http-header.c | 57 +- src/detect-http-headers-stub.h | 20 +- src/detect-http-headers.c | 1 - src/detect-http-host.c | 54 +- src/detect-http-location.c | 13 +- src/detect-http-method.c | 25 +- src/detect-http-method.h | 1 - src/detect-http-protocol.c | 16 +- src/detect-http-raw-header.c | 79 +- src/detect-http-referer.c | 15 +- src/detect-http-request-line.c | 22 +- src/detect-http-response-line.c | 28 +- src/detect-http-server-body.c | 7 +- src/detect-http-server.c | 13 +- src/detect-http-start.c | 24 +- src/detect-http-stat-code.c | 25 +- src/detect-http-stat-code.h | 5 +- src/detect-http-stat-msg.c | 25 +- src/detect-http-stat-msg.h | 5 +- src/detect-http-ua.c | 22 +- src/detect-http-uri.c | 71 +- src/detect-http-uri.h | 4 +- src/detect-http2.c | 187 +- src/detect-icmp-id.c | 81 +- src/detect-icmp-seq.c | 71 +- src/detect-icmp-seq.h | 2 +- src/detect-icmpv6-mtu.c | 32 +- src/detect-icmpv6hdr.c | 15 +- src/detect-icmpv6hdr.h | 2 +- src/detect-icode.c | 18 +- src/detect-id.c | 76 +- src/detect-id.h | 6 +- src/detect-ipopts.c | 42 +- src/detect-ipopts.h | 4 +- src/detect-ipproto.c | 130 +- src/detect-ipproto.h | 15 +- src/detect-iprep.c | 32 +- src/detect-iprep.h | 2 +- src/detect-ipv4hdr.c | 15 +- src/detect-ipv4hdr.h | 2 +- src/detect-ipv6hdr.c | 12 +- src/detect-ipv6hdr.h | 2 +- src/detect-isdataat.c | 157 +- src/detect-isdataat.h | 7 +- src/detect-itype.c | 19 +- src/detect-krb5-cname.c | 27 +- src/detect-krb5-errcode.c | 41 +- src/detect-krb5-msgtype.c | 41 +- src/detect-krb5-sname.c | 27 +- src/detect-l3proto.c | 8 +- src/detect-l3proto.h | 2 +- src/detect-lua-extensions.c | 28 +- src/detect-lua.c | 262 +- src/detect-lua.h | 13 +- src/detect-mark.c | 45 +- src/detect-mark.h | 7 +- src/detect-metadata.c | 45 +- src/detect-metadata.h | 3 +- src/detect-modbus.c | 3 +- src/detect-mqtt-connack-sessionpresent.c | 51 +- src/detect-mqtt-connect-clientid.c | 16 +- src/detect-mqtt-connect-flags.c | 58 +- src/detect-mqtt-connect-password.c | 16 +- src/detect-mqtt-connect-username.c | 16 +- src/detect-mqtt-connect-willmessage.c | 16 +- src/detect-mqtt-connect-willtopic.c | 16 +- src/detect-mqtt-flags.c | 39 +- src/detect-mqtt-protocol-version.c | 59 +- src/detect-mqtt-publish-message.c | 16 +- src/detect-mqtt-publish-topic.c | 16 +- src/detect-mqtt-qos.c | 25 +- src/detect-mqtt-reason-code.c | 32 +- src/detect-mqtt-subscribe-topic.c | 26 +- src/detect-mqtt-type.c | 30 +- src/detect-mqtt-unsubscribe-topic.c | 28 +- src/detect-msg.c | 23 +- src/detect-msg.h | 3 +- src/detect-nfs-procedure.c | 50 +- src/detect-nfs-procedure.h | 2 +- src/detect-nfs-version.c | 21 +- src/detect-nfs-version.h | 2 +- src/detect-noalert.c | 7 +- src/detect-noalert.h | 3 +- src/detect-nocase.c | 6 +- src/detect-nocase.h | 3 +- src/detect-offset.c | 14 +- src/detect-offset.h | 3 +- src/detect-parse.c | 428 +-- src/detect-parse.h | 26 +- src/detect-pcre.c | 327 +- src/detect-pcre.h | 20 +- src/detect-pkt-data.c | 8 +- src/detect-pkt-data.h | 2 +- src/detect-pktvar.c | 21 +- src/detect-pktvar.h | 3 +- src/detect-prefilter.c | 12 +- src/detect-prefilter.h | 2 +- src/detect-priority.c | 28 +- src/detect-priority.h | 3 +- src/detect-rawbytes.h | 3 +- src/detect-reference.c | 33 +- src/detect-reference.h | 1 - src/detect-replace.c | 106 +- src/detect-replace.h | 2 +- src/detect-rev.c | 8 +- src/detect-rev.h | 3 +- src/detect-rfb-name.c | 19 +- src/detect-rfb-secresult.c | 65 +- src/detect-rfb-sectype.c | 18 +- src/detect-rpc.c | 50 +- src/detect-rpc.h | 21 +- src/detect-sameip.c | 21 +- src/detect-sid.c | 8 +- src/detect-sid.h | 3 +- src/detect-sip-method.c | 15 +- src/detect-sip-protocol.c | 22 +- src/detect-sip-request-line.c | 16 +- src/detect-sip-response-line.c | 16 +- src/detect-sip-stat-code.c | 14 +- src/detect-sip-stat-msg.c | 17 +- src/detect-sip-uri.c | 21 +- src/detect-smb-share.c | 42 +- src/detect-snmp-community.c | 36 +- src/detect-snmp-community.h | 1 - src/detect-snmp-pdu_type.c | 23 +- src/detect-snmp-pdu_type.h | 1 - src/detect-snmp-version.c | 22 +- src/detect-snmp-version.h | 1 - src/detect-ssh-hassh-server-string.c | 35 +- src/detect-ssh-hassh-server-string.h | 2 +- src/detect-ssh-hassh-server.c | 39 +- src/detect-ssh-hassh-server.h | 5 +- src/detect-ssh-hassh-string.c | 35 +- src/detect-ssh-hassh-string.h | 2 +- src/detect-ssh-hassh.c | 40 +- src/detect-ssh-hassh.h | 2 +- src/detect-ssh-proto-version.c | 99 +- src/detect-ssh-proto-version.h | 3 +- src/detect-ssh-proto.c | 34 +- src/detect-ssh-software-version.c | 114 +- src/detect-ssh-software-version.h | 3 +- src/detect-ssh-software.c | 36 +- src/detect-ssl-state.c | 17 +- src/detect-ssl-state.h | 2 +- src/detect-ssl-version.c | 20 +- src/detect-ssl-version.h | 8 +- src/detect-stream_size.c | 26 +- src/detect-stream_size.h | 5 +- src/detect-tag.c | 62 +- src/detect-tag.h | 47 +- src/detect-target.c | 20 +- src/detect-tcp-ack.c | 59 +- src/detect-tcp-ack.h | 2 +- src/detect-tcp-flags.c | 278 +- src/detect-tcp-flags.h | 7 +- src/detect-tcp-seq.c | 76 +- src/detect-tcp-seq.h | 2 +- src/detect-tcp-window.c | 60 +- src/detect-tcp-window.h | 6 +- src/detect-tcphdr.c | 15 +- src/detect-tcphdr.h | 2 +- src/detect-tcpmss.c | 22 +- src/detect-tcpmss.h | 4 +- src/detect-template-rust-buffer.c | 3 +- src/detect-template.c | 34 +- src/detect-template2.c | 25 +- src/detect-template2.h | 6 +- src/detect-threshold.c | 201 +- src/detect-threshold.h | 30 +- src/detect-tls-cert-fingerprint.c | 49 +- src/detect-tls-cert-issuer.c | 23 +- src/detect-tls-cert-issuer.h | 1 - src/detect-tls-cert-serial.c | 40 +- src/detect-tls-cert-serial.h | 2 +- src/detect-tls-cert-subject.c | 15 +- src/detect-tls-cert-subject.h | 1 - src/detect-tls-cert-validity.c | 83 +- src/detect-tls-cert-validity.h | 14 +- src/detect-tls-certs.c | 35 +- src/detect-tls-ja3-hash.c | 31 +- src/detect-tls-ja3-string.c | 13 +- src/detect-tls-ja3s-hash.c | 31 +- src/detect-tls-ja3s-string.c | 13 +- src/detect-tls-sni.c | 17 +- src/detect-tls-version.c | 29 +- src/detect-tls-version.h | 5 +- src/detect-tls.c | 86 +- src/detect-tls.h | 6 +- src/detect-tos.c | 35 +- src/detect-transform-compress-whitespace.c | 32 +- src/detect-transform-compress-whitespace.h | 2 +- src/detect-transform-dotprefix.c | 18 +- src/detect-transform-dotprefix.h | 2 +- src/detect-transform-md5.c | 24 +- src/detect-transform-md5.h | 2 +- src/detect-transform-pcrexform.c | 24 +- src/detect-transform-pcrexform.h | 2 +- src/detect-transform-sha1.c | 24 +- src/detect-transform-sha1.h | 2 +- src/detect-transform-sha256.c | 24 +- src/detect-transform-sha256.h | 2 +- src/detect-transform-strip-whitespace.c | 42 +- src/detect-transform-strip-whitespace.h | 2 +- src/detect-transform-urldecode.c | 37 +- src/detect-transform-urldecode.h | 2 +- src/detect-ttl.c | 21 +- src/detect-ttl.h | 6 +- src/detect-udphdr.c | 12 +- src/detect-udphdr.h | 2 +- src/detect-uricontent.c | 5 +- src/detect-uricontent.h | 2 +- src/detect-urilen.c | 48 +- src/detect-urilen.h | 5 +- src/detect-within.c | 39 +- src/detect-within.h | 3 +- src/detect-xbits.c | 118 +- src/detect-xbits.h | 2 +- src/detect.c | 472 ++- src/detect.h | 291 +- src/device-storage.c | 2 - src/feature.c | 16 +- src/feature.h | 2 +- src/flow-bit.c | 44 +- src/flow-bit.h | 3 +- src/flow-bypass.c | 34 +- src/flow-bypass.h | 14 +- src/flow-hash.c | 99 +- src/flow-hash.h | 31 +- src/flow-manager.c | 71 +- src/flow-manager.h | 4 +- src/flow-private.h | 47 +- src/flow-queue.c | 8 +- src/flow-queue.h | 45 +- src/flow-spare-pool.c | 14 +- src/flow-storage.c | 1 - src/flow-timeout.c | 26 +- src/flow-util.c | 22 +- src/flow-var.c | 7 +- src/flow-var.h | 11 +- src/flow-worker.c | 60 +- src/flow-worker.h | 2 +- src/flow.c | 317 +- src/flow.h | 325 +- src/host-bit.c | 76 +- src/host-queue.c | 13 +- src/host-queue.h | 40 +- src/host-storage.c | 1 - src/host-timeout.c | 3 +- src/host-timeout.h | 1 - src/host.c | 103 +- src/host.h | 86 +- src/ippair-bit.c | 133 +- src/ippair-queue.c | 12 +- src/ippair-queue.h | 39 +- src/ippair-timeout.c | 2 +- src/ippair.c | 121 +- src/ippair.h | 57 +- src/log-cf-common.c | 58 +- src/log-cf-common.h | 33 +- src/log-httplog.c | 209 +- src/log-httplog.h | 1 - src/log-pcap.c | 265 +- src/log-pcap.h | 1 - src/log-stats.c | 48 +- src/log-tcp-data.c | 47 +- src/log-tlslog.c | 152 +- src/log-tlslog.h | 6 +- src/log-tlsstore.c | 61 +- src/output-file.c | 5 +- src/output-file.h | 6 +- src/output-filedata.c | 7 +- src/output-filedata.h | 7 +- src/output-filestore.c | 61 +- src/output-flow.c | 11 +- src/output-flow.h | 6 +- src/output-json-alert.c | 105 +- src/output-json-alert.h | 1 - src/output-json-anomaly.c | 88 +- src/output-json-anomaly.h | 1 - src/output-json-common.c | 1 - src/output-json-dcerpc.c | 5 +- src/output-json-dhcp.c | 10 +- src/output-json-dnp3-objects.h | 3 +- src/output-json-dnp3.c | 19 +- src/output-json-dns.c | 36 +- src/output-json-drop.c | 23 +- src/output-json-email-common.c | 85 +- src/output-json-email-common.h | 7 +- src/output-json-file.c | 14 +- src/output-json-flow.c | 23 +- src/output-json-ftp.c | 21 +- src/output-json-http.c | 62 +- src/output-json-http.h | 1 - src/output-json-http2.c | 10 +- src/output-json-krb5.c | 7 +- src/output-json-metadata.c | 2 +- src/output-json-mqtt.c | 15 +- src/output-json-netflow.c | 21 +- src/output-json-nfs.c | 7 +- src/output-json-rdp.c | 7 +- src/output-json-rfb.c | 7 +- src/output-json-sip.c | 7 +- src/output-json-smb.c | 4 +- src/output-json-smtp.c | 11 +- src/output-json-snmp.c | 7 +- src/output-json-ssh.c | 6 +- src/output-json-stats.c | 47 +- src/output-json-stats.h | 6 +- src/output-json-tftp.c | 7 +- src/output-json-tls.c | 108 +- src/output-json.c | 173 +- src/output-json.h | 9 +- src/output-lua.c | 46 +- src/output-packet.c | 13 +- src/output-packet.h | 6 +- src/output-stats.c | 9 +- src/output-stats.h | 16 +- src/output-streaming.c | 62 +- src/output-streaming.h | 25 +- src/output-tx.c | 34 +- src/output-tx.h | 14 +- src/output.c | 236 +- src/output.h | 178 +- src/packet-queue.c | 35 +- src/packet-queue.h | 8 +- src/pkt-var.c | 6 +- src/pkt-var.h | 1 - src/reputation.c | 58 +- src/reputation.h | 2 +- src/respond-reject-libnet11.c | 123 +- src/respond-reject.c | 2 +- src/respond-reject.h | 3 +- src/runmode-af-packet.c | 46 +- src/runmode-erf-dag.c | 8 +- src/runmode-erf-file.c | 20 +- src/runmode-ipfw.c | 12 +- src/runmode-napatech.c | 12 +- src/runmode-napatech.h | 2 - src/runmode-netmap.c | 56 +- src/runmode-netmap.h | 6 +- src/runmode-nflog.c | 14 +- src/runmode-nfq.c | 11 +- src/runmode-pcap-file.c | 20 +- src/runmode-pcap.c | 15 +- src/runmode-pfring.c | 34 +- src/runmode-unittests.c | 4 +- src/runmode-unittests.h | 4 +- src/runmode-unix-socket.c | 214 +- src/runmode-unix-socket.h | 22 +- src/runmode-windivert.c | 4 +- src/runmodes.c | 99 +- src/runmodes.h | 3 +- src/rust-context.h | 11 +- src/rust.h | 4 +- src/source-af-packet.c | 247 +- src/source-af-packet.h | 52 +- src/source-af-xdp.c | 8 +- src/source-erf-dag.c | 149 +- src/source-erf-dag.h | 1 - src/source-erf-file.c | 43 +- src/source-ipfw.c | 77 +- src/source-ipfw.h | 13 +- src/source-napatech.c | 187 +- src/source-napatech.h | 3 +- src/source-netmap.c | 88 +- src/source-netmap.h | 29 +- src/source-nflog.c | 43 +- src/source-nflog.h | 6 +- src/source-nfq-prototypes.h | 7 +- src/source-nfq.c | 175 +- src/source-nfq.h | 16 +- src/source-pcap-file-directory-helper.c | 99 +- src/source-pcap-file-directory-helper.h | 6 +- src/source-pcap-file-helper.c | 17 +- src/source-pcap-file-helper.h | 6 +- src/source-pcap-file.c | 49 +- src/source-pcap-file.h | 5 +- src/source-pcap.c | 59 +- src/source-pcap.h | 14 +- src/source-pfring.c | 71 +- src/source-pfring.h | 17 +- src/source-windivert.c | 128 +- src/source-windivert.h | 6 +- src/stream-tcp-inline.c | 11 +- src/stream-tcp-inline.h | 7 +- src/stream-tcp-list.c | 163 +- src/stream-tcp-list.h | 1 - src/stream-tcp-private.h | 156 +- src/stream-tcp-reassemble.c | 541 ++- src/stream-tcp-reassemble.h | 16 +- src/stream-tcp-sack.c | 146 +- src/stream-tcp-sack.h | 2 +- src/stream-tcp-util.c | 30 +- src/stream-tcp-util.h | 10 +- src/stream-tcp.c | 1437 ++++---- src/stream-tcp.h | 58 +- src/stream.c | 5 +- src/stream.h | 6 +- src/suricata-common.h | 178 +- src/suricata.c | 1177 +++---- src/suricata.h | 23 +- src/tests/app-layer-htp-file.c | 29 +- src/tests/detect-engine-content-inspection.c | 367 +- src/tests/detect-http-client-body.c | 1209 ++++--- src/tests/detect-http-cookie.c | 489 ++- src/tests/detect-http-header.c | 1152 +++--- src/tests/detect-http-host.c | 1132 +++--- src/tests/detect-http-method.c | 468 ++- src/tests/detect-http-raw-header.c | 958 +++-- src/tests/detect-http-server-body.c | 2547 +++++++------- src/tests/detect-http-stat-code.c | 606 ++-- src/tests/detect-http-stat-msg.c | 599 ++-- src/tests/detect-http-uri.c | 1192 +++---- src/tests/detect-http-user-agent.c | 133 +- src/tests/detect-http2.c | 43 +- src/tests/detect-icmpv6-mtu.c | 7 +- src/tests/detect-icmpv6hdr.c | 6 +- src/tests/detect-ipv4hdr.c | 6 +- src/tests/detect-ipv6hdr.c | 6 +- src/tests/detect-parse.c | 16 +- src/tests/detect-snmp-community.c | 25 +- src/tests/detect-snmp-pdu_type.c | 2 +- src/tests/detect-snmp-version.c | 4 +- src/tests/detect-ssl-state.c | 22 +- src/tests/detect-tcphdr.c | 6 +- src/tests/detect-template-buffer.c | 22 +- src/tests/detect-template.c | 10 +- src/tests/detect-tls-cert-fingerprint.c | 36 +- src/tests/detect-tls-cert-issuer.c | 31 +- src/tests/detect-tls-cert-serial.c | 33 +- src/tests/detect-tls-cert-subject.c | 31 +- src/tests/detect-tls-cert-validity.c | 135 +- src/tests/detect-tls-certs.c | 29 +- src/tests/detect-tls-version.c | 4 +- src/tests/detect-transform-pcrexform.c | 10 +- src/tests/detect-ttl.c | 26 +- src/tests/detect-udphdr.c | 6 +- src/tests/detect.c | 1172 ++++--- src/tests/fuzz/fuzz_applayerparserparse.c | 32 +- .../fuzz/fuzz_applayerprotodetectgetproto.c | 7 +- src/tests/fuzz/fuzz_confyamlloadstring.c | 7 +- src/tests/fuzz/fuzz_decodepcapfile.c | 19 +- src/tests/fuzz/fuzz_mimedecparseline.c | 16 +- src/tests/fuzz/fuzz_siginit.c | 7 +- src/tests/fuzz/fuzz_sigpcap.c | 27 +- src/tests/fuzz/onefile.c | 2 +- src/tests/reputation.c | 34 +- src/tests/source-pcap.c | 68 +- src/tests/stream-tcp-inline.c | 38 +- src/tests/stream-tcp-list.c | 92 +- src/tests/stream-tcp-reassemble.c | 145 +- src/threads-debug.h | 696 ++-- src/threads-profile.h | 284 +- src/threads.c | 22 +- src/threads.h | 219 +- src/threadvars.h | 42 +- src/tm-modules.c | 88 +- src/tm-modules.h | 17 +- src/tm-queuehandlers.c | 2 +- src/tm-queuehandlers.h | 3 +- src/tm-queues.c | 9 +- src/tm-queues.h | 5 +- src/tm-threads-common.h | 7 +- src/tm-threads.c | 153 +- src/tm-threads.h | 20 +- src/tmqh-flow.c | 24 +- src/tmqh-flow.h | 2 +- src/tmqh-packetpool.c | 32 +- src/tmqh-packetpool.h | 4 +- src/tmqh-simple.c | 3 +- src/tmqh-simple.h | 2 +- src/tree.h | 1420 ++++---- src/unix-manager.c | 234 +- src/unix-manager.h | 9 +- src/util-action.c | 25 +- src/util-affinity.c | 60 +- src/util-affinity.h | 27 +- src/util-atomic.c | 2 +- src/util-atomic.h | 123 +- src/util-base64.c | 31 +- src/util-base64.h | 4 +- src/util-bloomfilter-counting.c | 101 +- src/util-bloomfilter-counting.h | 6 +- src/util-bloomfilter.c | 86 +- src/util-bloomfilter.h | 6 +- src/util-bpf.c | 6 +- src/util-bpf.h | 5 +- src/util-buffer.c | 3 +- src/util-buffer.h | 112 +- src/util-byte.c | 53 +- src/util-byte.h | 33 +- src/util-checksum.c | 34 +- src/util-checksum.h | 5 +- src/util-cidr.h | 1 - src/util-classification-config.c | 89 +- src/util-classification-config.h | 3 +- src/util-clock.h | 8 +- src/util-conf.c | 7 +- src/util-config.h | 18 +- src/util-coredump-config.c | 91 +- src/util-cpu.c | 64 +- src/util-daemon.c | 13 +- src/util-daemon.h | 4 +- src/util-debug-filters.c | 60 +- src/util-debug-filters.h | 17 +- src/util-debug.c | 199 +- src/util-debug.h | 249 +- src/util-decode-mime.c | 374 +- src/util-decode-mime.h | 194 +- src/util-detect.c | 9 +- src/util-detect.h | 2 +- src/util-device.c | 71 +- src/util-device.h | 24 +- src/util-dpdk.h | 2 +- src/util-ebpf.c | 126 +- src/util-ebpf.h | 39 +- src/util-enum.c | 2 +- src/util-enum.h | 2 +- src/util-error.c | 10 +- src/util-file-decompression.c | 40 +- src/util-file-decompression.h | 8 +- src/util-file-swf-decompression.c | 30 +- src/util-file-swf-decompression.h | 12 +- src/util-file.c | 69 +- src/util-file.h | 32 +- src/util-fix_checksum.c | 3 +- src/util-fmemopen.c | 12 +- src/util-hash-lookup3.c | 2063 ++++++----- src/util-hash-lookup3.h | 42 +- src/util-hash-string.c | 3 +- src/util-hash-string.h | 3 +- src/util-hash.c | 74 +- src/util-hash.h | 4 +- src/util-hashlist.c | 80 +- src/util-hashlist.h | 5 +- src/util-host-os-info.c | 515 ++- src/util-ioctl.c | 21 +- src/util-ip.c | 11 +- src/util-ja3.c | 13 +- src/util-ja3.h | 1 - src/util-log-redis.c | 110 +- src/util-log-redis.h | 9 +- src/util-logopenfile.c | 114 +- src/util-logopenfile.h | 10 +- src/util-lua-common.c | 49 +- src/util-lua-common.h | 3 +- src/util-lua-dnp3-objects.c | 93 +- src/util-lua-dnp3-objects.h | 3 +- src/util-lua-dnp3.c | 16 +- src/util-lua-dns.c | 1 - src/util-lua-hassh.c | 5 +- src/util-lua-http.c | 31 +- src/util-lua-ja3.c | 27 +- src/util-lua-smtp.c | 64 +- src/util-lua-ssh.c | 1 - src/util-lua-tls.c | 25 +- src/util-lua.c | 4 +- src/util-luajit.c | 2 +- src/util-macset.c | 60 +- src/util-macset.h | 27 +- src/util-magic.c | 419 ++- src/util-mem.h | 30 +- src/util-memcmp.c | 192 +- src/util-memcmp.h | 50 +- src/util-memrchr.c | 6 +- src/util-misc.c | 10 +- src/util-misc.h | 4 +- src/util-mpm-ac-ks-small.c | 16 +- src/util-mpm-ac-ks.c | 452 ++- src/util-mpm-ac-ks.h | 8 +- src/util-mpm-ac.c | 305 +- src/util-mpm-hs.c | 235 +- src/util-mpm.c | 74 +- src/util-mpm.h | 34 +- src/util-napatech.c | 589 ++-- src/util-napatech.h | 36 +- src/util-optimize.h | 5 +- src/util-pages.c | 5 +- src/util-pages.h | 20 +- src/util-path.c | 5 +- src/util-path.h | 4 +- src/util-pidfile.c | 2 +- src/util-pidfile.h | 1 - src/util-plugin.c | 9 +- src/util-pool-thread.c | 65 +- src/util-pool-thread.h | 12 +- src/util-pool.c | 63 +- src/util-pool.h | 15 +- src/util-prefilter.c | 19 +- src/util-print.c | 105 +- src/util-print.h | 42 +- src/util-privs.c | 30 +- src/util-privs.h | 22 +- src/util-profiling-keywords.c | 89 +- src/util-profiling-locks.c | 40 +- src/util-profiling-locks.h | 1 - src/util-profiling-prefilter.c | 52 +- src/util-profiling-rulegroups.c | 85 +- src/util-profiling-rules.c | 186 +- src/util-profiling.c | 335 +- src/util-profiling.h | 315 +- src/util-proto-name.h | 5 +- src/util-radix-tree.c | 493 ++- src/util-radix-tree.h | 10 +- src/util-random.c | 8 +- src/util-random.h | 1 - src/util-reference-config.c | 72 +- src/util-reference-config.h | 7 +- src/util-rohash.c | 19 +- src/util-rohash.h | 1 - src/util-rule-vars.c | 212 +- src/util-runmodes.c | 141 +- src/util-runmodes.h | 30 +- src/util-running-modes.c | 1 - src/util-signal.c | 4 +- src/util-spm-bm.c | 53 +- src/util-spm-bm.h | 6 +- src/util-spm-bs.c | 17 +- src/util-spm-bs.h | 3 +- src/util-spm-bs2bm.c | 6 +- src/util-spm-bs2bm.h | 1 - src/util-spm-hs.c | 25 +- src/util-spm.c | 3111 ++++++++++------- src/util-spm.h | 64 +- src/util-storage.c | 13 +- src/util-storage.h | 3 +- src/util-streaming-buffer.c | 137 +- src/util-streaming-buffer.h | 38 +- src/util-strlcatu.c | 4 +- src/util-strlcpyu.c | 2 +- src/util-strptime.c | 929 +++-- src/util-syslog.c | 46 +- src/util-syslog.h | 4 +- src/util-thash.c | 75 +- src/util-thash.h | 79 +- src/util-threshold-config.c | 520 +-- src/util-time.c | 61 +- src/util-time.h | 20 +- src/util-unittest-helper.c | 121 +- src/util-unittest-helper.h | 9 +- src/util-unittest.c | 44 +- src/util-unittest.h | 55 +- src/util-validate.h | 92 +- src/util-var-name.c | 2 +- src/util-var-name.h | 1 - src/util-var.c | 23 +- src/util-var.h | 5 +- src/win32-misc.c | 27 +- src/win32-misc.h | 2 +- src/win32-service.c | 97 +- src/win32-syscall.c | 341 +- src/win32-syscall.h | 5 +- src/win32-syslog.h | 59 +- 921 files changed, 38655 insertions(+), 42030 deletions(-) diff --git a/src/action-globals.h b/src/action-globals.h index b63086f668d3..7f0fdc9a719a 100644 --- a/src/action-globals.h +++ b/src/action-globals.h @@ -26,15 +26,15 @@ /* Changing them as flags, so later we can have alerts * and drop simultaneously */ -#define ACTION_ALERT 0x01 -#define ACTION_DROP 0x02 -#define ACTION_REJECT 0x04 -#define ACTION_REJECT_DST 0x08 -#define ACTION_REJECT_BOTH 0x10 -#define ACTION_PASS 0x20 -#define ACTION_CONFIG 0x40 +#define ACTION_ALERT 0x01 +#define ACTION_DROP 0x02 +#define ACTION_REJECT 0x04 +#define ACTION_REJECT_DST 0x08 +#define ACTION_REJECT_BOTH 0x10 +#define ACTION_PASS 0x20 +#define ACTION_CONFIG 0x40 -#define ACTION_REJECT_ANY (ACTION_REJECT|ACTION_REJECT_DST|ACTION_REJECT_BOTH) +#define ACTION_REJECT_ANY (ACTION_REJECT | ACTION_REJECT_DST | ACTION_REJECT_BOTH) #define ACTION_DROP_REJECT (ACTION_REJECT_ANY | ACTION_DROP) diff --git a/src/alert-debuglog.c b/src/alert-debuglog.c index aaba84cc6ea6..a7880bef0d97 100644 --- a/src/alert-debuglog.c +++ b/src/alert-debuglog.c @@ -82,32 +82,28 @@ static void AlertDebugLogFlowVars(AlertDebugLogThread *aft, const Packet *p) FlowBit *fb = (FlowBit *)gv; const char *fbname = VarNameStoreLookupById(fb->idx, VAR_TYPE_FLOW_BIT); if (fbname) { - MemBufferWriteString(aft->buffer, "FLOWBIT: %s\n", - fbname); + MemBufferWriteString(aft->buffer, "FLOWBIT: %s\n", fbname); } } else if (gv->type == DETECT_FLOWVAR || gv->type == DETECT_FLOWINT) { - FlowVar *fv = (FlowVar *) gv; + FlowVar *fv = (FlowVar *)gv; if (fv->datatype == FLOWVAR_TYPE_STR) { - const char *fvname = VarNameStoreLookupById(fv->idx, - VAR_TYPE_FLOW_VAR); - MemBufferWriteString(aft->buffer, "FLOWVAR: \"%s\" => \"", - fvname); + const char *fvname = VarNameStoreLookupById(fv->idx, VAR_TYPE_FLOW_VAR); + MemBufferWriteString(aft->buffer, "FLOWVAR: \"%s\" => \"", fvname); for (i = 0; i < fv->data.fv_str.value_len; i++) { if (isprint(fv->data.fv_str.value[i])) { - MemBufferWriteString(aft->buffer, "%c", - fv->data.fv_str.value[i]); + MemBufferWriteString(aft->buffer, "%c", fv->data.fv_str.value[i]); } else { - MemBufferWriteString(aft->buffer, "\\%02X", - fv->data.fv_str.value[i]); + MemBufferWriteString(aft->buffer, "\\%02X", fv->data.fv_str.value[i]); } } MemBufferWriteString(aft->buffer, "\"\n"); } else if (fv->datatype == FLOWVAR_TYPE_INT) { - const char *fvname = VarNameStoreLookupById(fv->idx, - VAR_TYPE_FLOW_INT); - MemBufferWriteString(aft->buffer, "FLOWINT: \"%s\" =>" - " %"PRIu32"\n", fvname, fv->data.fv_int.value); + const char *fvname = VarNameStoreLookupById(fv->idx, VAR_TYPE_FLOW_INT); + MemBufferWriteString(aft->buffer, + "FLOWINT: \"%s\" =>" + " %" PRIu32 "\n", + fvname, fv->data.fv_int.value); } } gv = gv->next; @@ -129,7 +125,7 @@ static void AlertDebugLogPktVars(AlertDebugLogThread *aft, const Packet *p) const char *varname = VarNameStoreLookupById(pv->id, VAR_TYPE_PKT_VAR); MemBufferWriteString(aft->buffer, "PKTVAR: %s\n", varname); PrintRawDataToBuffer(aft->buffer->buffer, &aft->buffer->offset, aft->buffer->size, - pv->value, pv->value_len); + pv->value, pv->value_len); pv = pv->next; } } @@ -141,11 +137,10 @@ static int AlertDebugPrintStreamSegmentCallback( { AlertDebugLogThread *aft = (AlertDebugLogThread *)data; - MemBufferWriteString(aft->buffer, "STREAM DATA LEN: %"PRIu32"\n", buflen); + MemBufferWriteString(aft->buffer, "STREAM DATA LEN: %" PRIu32 "\n", buflen); MemBufferWriteString(aft->buffer, "STREAM DATA:\n"); - PrintRawDataToBuffer(aft->buffer->buffer, &aft->buffer->offset, aft->buffer->size, - buf, buflen); + PrintRawDataToBuffer(aft->buffer->buffer, &aft->buffer->offset, aft->buffer->size, buf, buflen); return 1; } @@ -164,10 +159,12 @@ static TmEcode AlertDebugLogger(ThreadVars *tv, const Packet *p, void *thread_da CreateTimeString(p->ts, timebuf, sizeof(timebuf)); - MemBufferWriteString(aft->buffer, "+================\n" - "TIME: %s\n", timebuf); + MemBufferWriteString(aft->buffer, + "+================\n" + "TIME: %s\n", + timebuf); if (p->pcap_cnt > 0) { - MemBufferWriteString(aft->buffer, "PCAP PKT NUM: %"PRIu64"\n", p->pcap_cnt); + MemBufferWriteString(aft->buffer, "PCAP PKT NUM: %" PRIu64 "\n", p->pcap_cnt); } pkt_src_str = PktSrcToString(p->pkt_src); MemBufferWriteString(aft->buffer, "PKT SRC: %s\n", pkt_src_str); @@ -182,66 +179,70 @@ static TmEcode AlertDebugLogger(ThreadVars *tv, const Packet *p, void *thread_da PrintInet(AF_INET6, (const void *)GET_IPV6_DST_ADDR(p), dstip, sizeof(dstip)); } - MemBufferWriteString(aft->buffer, "SRC IP: %s\n" - "DST IP: %s\n" - "PROTO: %" PRIu32 "\n", - srcip, dstip, p->proto); + MemBufferWriteString(aft->buffer, + "SRC IP: %s\n" + "DST IP: %s\n" + "PROTO: %" PRIu32 "\n", + srcip, dstip, p->proto); if (PKT_IS_TCP(p) || PKT_IS_UDP(p)) { - MemBufferWriteString(aft->buffer, "SRC PORT: %" PRIu32 "\n" - "DST PORT: %" PRIu32 "\n", - p->sp, p->dp); + MemBufferWriteString(aft->buffer, + "SRC PORT: %" PRIu32 "\n" + "DST PORT: %" PRIu32 "\n", + p->sp, p->dp); if (PKT_IS_TCP(p)) { - MemBufferWriteString(aft->buffer, "TCP SEQ: %"PRIu32"\n" - "TCP ACK: %"PRIu32"\n", - TCP_GET_SEQ(p), TCP_GET_ACK(p)); + MemBufferWriteString(aft->buffer, + "TCP SEQ: %" PRIu32 "\n" + "TCP ACK: %" PRIu32 "\n", + TCP_GET_SEQ(p), TCP_GET_ACK(p)); } } /* flow stuff */ - MemBufferWriteString(aft->buffer, "FLOW: to_server: %s, " - "to_client: %s\n", - p->flowflags & FLOW_PKT_TOSERVER ? "TRUE" : "FALSE", - p->flowflags & FLOW_PKT_TOCLIENT ? "TRUE" : "FALSE"); + MemBufferWriteString(aft->buffer, + "FLOW: to_server: %s, " + "to_client: %s\n", + p->flowflags & FLOW_PKT_TOSERVER ? "TRUE" : "FALSE", + p->flowflags & FLOW_PKT_TOCLIENT ? "TRUE" : "FALSE"); if (p->flow != NULL) { int applayer = 0; applayer = StreamTcpAppLayerIsDisabled(p->flow); CreateTimeString(p->flow->startts, timebuf, sizeof(timebuf)); MemBufferWriteString(aft->buffer, "FLOW Start TS: %s\n", timebuf); - MemBufferWriteString(aft->buffer, "FLOW PKTS TODST: %"PRIu32"\n" - "FLOW PKTS TOSRC: %"PRIu32"\n" - "FLOW Total Bytes: %"PRIu64"\n", - p->flow->todstpktcnt, p->flow->tosrcpktcnt, - p->flow->todstbytecnt + p->flow->tosrcbytecnt); MemBufferWriteString(aft->buffer, - "FLOW IPONLY SET: TOSERVER: %s, TOCLIENT: %s\n" - "FLOW ACTION: DROP: %s\n" - "FLOW NOINSPECTION: PACKET: %s, PAYLOAD: %s, APP_LAYER: %s\n" - "FLOW APP_LAYER: DETECTED: %s, PROTO %"PRIu16"\n", - p->flow->flags & FLOW_TOSERVER_IPONLY_SET ? "TRUE" : "FALSE", - p->flow->flags & FLOW_TOCLIENT_IPONLY_SET ? "TRUE" : "FALSE", - p->flow->flags & FLOW_ACTION_DROP ? "TRUE" : "FALSE", - p->flow->flags & FLOW_NOPACKET_INSPECTION ? "TRUE" : "FALSE", - p->flow->flags & FLOW_NOPAYLOAD_INSPECTION ? "TRUE" : "FALSE", - applayer ? "TRUE" : "FALSE", - (p->flow->alproto != ALPROTO_UNKNOWN) ? "TRUE" : "FALSE", p->flow->alproto); + "FLOW PKTS TODST: %" PRIu32 "\n" + "FLOW PKTS TOSRC: %" PRIu32 "\n" + "FLOW Total Bytes: %" PRIu64 "\n", + p->flow->todstpktcnt, p->flow->tosrcpktcnt, + p->flow->todstbytecnt + p->flow->tosrcbytecnt); + MemBufferWriteString(aft->buffer, + "FLOW IPONLY SET: TOSERVER: %s, TOCLIENT: %s\n" + "FLOW ACTION: DROP: %s\n" + "FLOW NOINSPECTION: PACKET: %s, PAYLOAD: %s, APP_LAYER: %s\n" + "FLOW APP_LAYER: DETECTED: %s, PROTO %" PRIu16 "\n", + p->flow->flags & FLOW_TOSERVER_IPONLY_SET ? "TRUE" : "FALSE", + p->flow->flags & FLOW_TOCLIENT_IPONLY_SET ? "TRUE" : "FALSE", + p->flow->flags & FLOW_ACTION_DROP ? "TRUE" : "FALSE", + p->flow->flags & FLOW_NOPACKET_INSPECTION ? "TRUE" : "FALSE", + p->flow->flags & FLOW_NOPAYLOAD_INSPECTION ? "TRUE" : "FALSE", + applayer ? "TRUE" : "FALSE", + (p->flow->alproto != ALPROTO_UNKNOWN) ? "TRUE" : "FALSE", p->flow->alproto); AlertDebugLogFlowVars(aft, p); } AlertDebugLogPktVars(aft, p); -/* any stuff */ -/* Sig details? */ + /* any stuff */ + /* Sig details? */ MemBufferWriteString(aft->buffer, - "PACKET LEN: %" PRIu32 "\n" - "PACKET:\n", - GET_PKT_LEN(p)); + "PACKET LEN: %" PRIu32 "\n" + "PACKET:\n", + GET_PKT_LEN(p)); PrintRawDataToBuffer(aft->buffer->buffer, &aft->buffer->offset, aft->buffer->size, - GET_PKT_DATA(p), GET_PKT_LEN(p)); + GET_PKT_DATA(p), GET_PKT_LEN(p)); - MemBufferWriteString(aft->buffer, "ALERT CNT: %" PRIu32 "\n", - p->alerts.cnt); + MemBufferWriteString(aft->buffer, "ALERT CNT: %" PRIu32 "\n", p->alerts.cnt); for (i = 0; i < p->alerts.cnt; i++) { const PacketAlert *pa = &p->alerts.alerts[i]; @@ -250,44 +251,37 @@ static TmEcode AlertDebugLogger(ThreadVars *tv, const Packet *p, void *thread_da } MemBufferWriteString(aft->buffer, - "ALERT MSG [%02d]: %s\n" - "ALERT GID [%02d]: %" PRIu32 "\n" - "ALERT SID [%02d]: %" PRIu32 "\n" - "ALERT REV [%02d]: %" PRIu32 "\n" - "ALERT CLASS [%02d]: %s\n" - "ALERT PRIO [%02d]: %" PRIu32 "\n" - "ALERT FOUND IN [%02d]: %s\n", - i, pa->s->msg, - i, pa->s->gid, - i, pa->s->id, - i, pa->s->rev, - i, pa->s->class_msg ? pa->s->class_msg : "", - i, pa->s->prio, - i, - pa->flags & PACKET_ALERT_FLAG_STREAM_MATCH ? "STREAM" : - (pa->flags & PACKET_ALERT_FLAG_STATE_MATCH ? "STATE" : "PACKET")); + "ALERT MSG [%02d]: %s\n" + "ALERT GID [%02d]: %" PRIu32 "\n" + "ALERT SID [%02d]: %" PRIu32 "\n" + "ALERT REV [%02d]: %" PRIu32 "\n" + "ALERT CLASS [%02d]: %s\n" + "ALERT PRIO [%02d]: %" PRIu32 "\n" + "ALERT FOUND IN [%02d]: %s\n", + i, pa->s->msg, i, pa->s->gid, i, pa->s->id, i, pa->s->rev, i, + pa->s->class_msg ? pa->s->class_msg : "", i, pa->s->prio, i, + pa->flags & PACKET_ALERT_FLAG_STREAM_MATCH + ? "STREAM" + : (pa->flags & PACKET_ALERT_FLAG_STATE_MATCH ? "STATE" : "PACKET")); if (pa->flags & PACKET_ALERT_FLAG_TX) { - MemBufferWriteString(aft->buffer, - "ALERT IN TX [%02d]: %"PRIu64"\n", i, pa->tx_id); + MemBufferWriteString(aft->buffer, "ALERT IN TX [%02d]: %" PRIu64 "\n", i, pa->tx_id); } else { - MemBufferWriteString(aft->buffer, - "ALERT IN TX [%02d]: N/A\n", i); + MemBufferWriteString(aft->buffer, "ALERT IN TX [%02d]: N/A\n", i); } if (p->payload_len > 0) { MemBufferWriteString(aft->buffer, - "PAYLOAD LEN: %" PRIu32 "\n" - "PAYLOAD:\n", - p->payload_len); + "PAYLOAD LEN: %" PRIu32 "\n" + "PAYLOAD:\n", + p->payload_len); PrintRawDataToBuffer(aft->buffer->buffer, &aft->buffer->offset, aft->buffer->size, - p->payload, p->payload_len); + p->payload, p->payload_len); } if ((pa->flags & PACKET_ALERT_FLAG_STATE_MATCH) || - (pa->flags & PACKET_ALERT_FLAG_STREAM_MATCH)) { + (pa->flags & PACKET_ALERT_FLAG_STREAM_MATCH)) { /* This is an app layer or stream alert */ int ret; uint8_t flag; - if (!(PKT_IS_TCP(p)) || p->flow == NULL || - p->flow->protoctx == NULL) { + if (!(PKT_IS_TCP(p)) || p->flow == NULL || p->flow->protoctx == NULL) { return TM_ECODE_OK; } /* IDS mode reverse the data */ @@ -297,17 +291,16 @@ static TmEcode AlertDebugLogger(ThreadVars *tv, const Packet *p, void *thread_da } else { flag = STREAM_DUMP_TOSERVER; } - ret = StreamSegmentForEach((const Packet *)p, flag, - AlertDebugPrintStreamSegmentCallback, - (void *)aft); + ret = StreamSegmentForEach( + (const Packet *)p, flag, AlertDebugPrintStreamSegmentCallback, (void *)aft); if (ret < 0) { return TM_ECODE_FAILED; } } } - aft->file_ctx->Write((const char *)MEMBUFFER_BUFFER(aft->buffer), - MEMBUFFER_OFFSET(aft->buffer), aft->file_ctx); + aft->file_ctx->Write((const char *)MEMBUFFER_BUFFER(aft->buffer), MEMBUFFER_OFFSET(aft->buffer), + aft->file_ctx); return TM_ECODE_OK; } @@ -327,16 +320,15 @@ static TmEcode AlertDebugLogDecoderEvent(ThreadVars *tv, const Packet *p, void * CreateTimeString(p->ts, timebuf, sizeof(timebuf)); MemBufferWriteString(aft->buffer, - "+================\n" - "TIME: %s\n", timebuf); + "+================\n" + "TIME: %s\n", + timebuf); if (p->pcap_cnt > 0) { - MemBufferWriteString(aft->buffer, - "PCAP PKT NUM: %"PRIu64"\n", p->pcap_cnt); + MemBufferWriteString(aft->buffer, "PCAP PKT NUM: %" PRIu64 "\n", p->pcap_cnt); } pkt_src_str = PktSrcToString(p->pkt_src); MemBufferWriteString(aft->buffer, "PKT SRC: %s\n", pkt_src_str); - MemBufferWriteString(aft->buffer, - "ALERT CNT: %" PRIu32 "\n", p->alerts.cnt); + MemBufferWriteString(aft->buffer, "ALERT CNT: %" PRIu32 "\n", p->alerts.cnt); for (i = 0; i < p->alerts.cnt; i++) { const PacketAlert *pa = &p->alerts.alerts[i]; @@ -345,29 +337,25 @@ static TmEcode AlertDebugLogDecoderEvent(ThreadVars *tv, const Packet *p, void * } MemBufferWriteString(aft->buffer, - "ALERT MSG [%02d]: %s\n" - "ALERT GID [%02d]: %" PRIu32 "\n" - "ALERT SID [%02d]: %" PRIu32 "\n" - "ALERT REV [%02d]: %" PRIu32 "\n" - "ALERT CLASS [%02d]: %s\n" - "ALERT PRIO [%02d]: %" PRIu32 "\n", - i, pa->s->msg, - i, pa->s->gid, - i, pa->s->id, - i, pa->s->rev, - i, pa->s->class_msg, - i, pa->s->prio); + "ALERT MSG [%02d]: %s\n" + "ALERT GID [%02d]: %" PRIu32 "\n" + "ALERT SID [%02d]: %" PRIu32 "\n" + "ALERT REV [%02d]: %" PRIu32 "\n" + "ALERT CLASS [%02d]: %s\n" + "ALERT PRIO [%02d]: %" PRIu32 "\n", + i, pa->s->msg, i, pa->s->gid, i, pa->s->id, i, pa->s->rev, i, pa->s->class_msg, i, + pa->s->prio); } MemBufferWriteString(aft->buffer, - "PACKET LEN: %" PRIu32 "\n" - "PACKET:\n", - GET_PKT_LEN(p)); + "PACKET LEN: %" PRIu32 "\n" + "PACKET:\n", + GET_PKT_LEN(p)); PrintRawDataToBuffer(aft->buffer->buffer, &aft->buffer->offset, aft->buffer->size, - GET_PKT_DATA(p), GET_PKT_LEN(p)); + GET_PKT_DATA(p), GET_PKT_LEN(p)); - aft->file_ctx->Write((const char *)MEMBUFFER_BUFFER(aft->buffer), - MEMBUFFER_OFFSET(aft->buffer), aft->file_ctx); + aft->file_ctx->Write((const char *)MEMBUFFER_BUFFER(aft->buffer), MEMBUFFER_OFFSET(aft->buffer), + aft->file_ctx); return TM_ECODE_OK; } @@ -378,8 +366,7 @@ static TmEcode AlertDebugLogThreadInit(ThreadVars *t, const void *initdata, void if (unlikely(aft == NULL)) return TM_ECODE_FAILED; - if(initdata == NULL) - { + if (initdata == NULL) { SCLogDebug("Error getting context for AlertDebugLog. \"initdata\" argument NULL"); SCFree(aft); return TM_ECODE_FAILED; @@ -483,7 +470,7 @@ static int AlertDebugLogLogger(ThreadVars *tv, void *thread_data, const Packet * void AlertDebugLogRegister(void) { - OutputRegisterPacketModule(LOGGER_ALERT_DEBUG, MODULE_NAME, "alert-debug", - AlertDebugLogInitCtx, AlertDebugLogLogger, AlertDebugLogCondition, - AlertDebugLogThreadInit, AlertDebugLogThreadDeinit, NULL); + OutputRegisterPacketModule(LOGGER_ALERT_DEBUG, MODULE_NAME, "alert-debug", AlertDebugLogInitCtx, + AlertDebugLogLogger, AlertDebugLogCondition, AlertDebugLogThreadInit, + AlertDebugLogThreadDeinit, NULL); } diff --git a/src/alert-debuglog.h b/src/alert-debuglog.h index f7c411c3ab3e..aab462667508 100644 --- a/src/alert-debuglog.h +++ b/src/alert-debuglog.h @@ -27,4 +27,3 @@ void AlertDebugLogRegister(void); #endif /* __ALERT_DEBUGLOG_H__ */ - diff --git a/src/alert-fastlog.c b/src/alert-fastlog.c index 7b4a22a85954..96ffb7bc3773 100644 --- a/src/alert-fastlog.c +++ b/src/alert-fastlog.c @@ -76,15 +76,15 @@ int AlertFastLogger(ThreadVars *tv, void *data, const Packet *p); void AlertFastLogRegister(void) { - OutputRegisterPacketModule(LOGGER_ALERT_FAST, MODULE_NAME, "fast", - AlertFastLogInitCtx, AlertFastLogger, AlertFastLogCondition, - AlertFastLogThreadInit, AlertFastLogThreadDeinit, NULL); + OutputRegisterPacketModule(LOGGER_ALERT_FAST, MODULE_NAME, "fast", AlertFastLogInitCtx, + AlertFastLogger, AlertFastLogCondition, AlertFastLogThreadInit, + AlertFastLogThreadDeinit, NULL); AlertFastLogRegisterTests(); } typedef struct AlertFastLogThread_ { /** LogFileCtx has the pointer to the file and a mutex to allow multithreading */ - LogFileCtx* file_ctx; + LogFileCtx *file_ctx; } AlertFastLogThread; static bool AlertFastLogCondition(ThreadVars *tv, void *thread_data, const Packet *p) @@ -92,8 +92,7 @@ static bool AlertFastLogCondition(ThreadVars *tv, void *thread_data, const Packe return (p->alerts.cnt > 0); } -static inline void AlertFastLogOutputAlert(AlertFastLogThread *aft, char *buffer, - int alert_size) +static inline void AlertFastLogOutputAlert(AlertFastLogThread *aft, char *buffer, int alert_size) { /* Output the alert string and count alerts. Only need to lock here. */ aft->file_ctx->Write(buffer, alert_size, aft->file_ctx); @@ -158,22 +157,24 @@ int AlertFastLogger(ThreadVars *tv, void *data, const Packet *p) int size = 0; if (likely(decoder_event == 0)) { PrintBufferData(alert_buffer, &size, MAX_FASTLOG_ALERT_SIZE, - "%s %s[**] [%" PRIu32 ":%" PRIu32 ":%" - PRIu32 "] %s [**] [Classification: %s] [Priority: %"PRIu32"]" - " {%s} %s:%" PRIu32 " -> %s:%" PRIu32 "\n", timebuf, action, - pa->s->gid, pa->s->id, pa->s->rev, pa->s->msg, pa->s->class_msg, pa->s->prio, - protoptr, srcip, src_port_or_icmp, dstip, dst_port_or_icmp); + "%s %s[**] [%" PRIu32 ":%" PRIu32 ":%" PRIu32 + "] %s [**] [Classification: %s] [Priority: %" PRIu32 "]" + " {%s} %s:%" PRIu32 " -> %s:%" PRIu32 "\n", + timebuf, action, pa->s->gid, pa->s->id, pa->s->rev, pa->s->msg, + pa->s->class_msg, pa->s->prio, protoptr, srcip, src_port_or_icmp, dstip, + dst_port_or_icmp); } else { - PrintBufferData(alert_buffer, &size, MAX_FASTLOG_ALERT_SIZE, - "%s %s[**] [%" PRIu32 ":%" PRIu32 - ":%" PRIu32 "] %s [**] [Classification: %s] [Priority: " - "%" PRIu32 "] [**] [Raw pkt: ", timebuf, action, pa->s->gid, - pa->s->id, pa->s->rev, pa->s->msg, pa->s->class_msg, pa->s->prio); - PrintBufferRawLineHex(alert_buffer, &size, MAX_FASTLOG_ALERT_SIZE, - GET_PKT_DATA(p), GET_PKT_LEN(p) < 32 ? GET_PKT_LEN(p) : 32); + PrintBufferData(alert_buffer, &size, MAX_FASTLOG_ALERT_SIZE, + "%s %s[**] [%" PRIu32 ":%" PRIu32 ":%" PRIu32 + "] %s [**] [Classification: %s] [Priority: " + "%" PRIu32 "] [**] [Raw pkt: ", + timebuf, action, pa->s->gid, pa->s->id, pa->s->rev, pa->s->msg, + pa->s->class_msg, pa->s->prio); + PrintBufferRawLineHex(alert_buffer, &size, MAX_FASTLOG_ALERT_SIZE, GET_PKT_DATA(p), + GET_PKT_LEN(p) < 32 ? GET_PKT_LEN(p) : 32); if (p->pcap_cnt != 0) { - PrintBufferData(alert_buffer, &size, MAX_FASTLOG_ALERT_SIZE, - "] [pcap file packet: %"PRIu64"]\n", p->pcap_cnt); + PrintBufferData(alert_buffer, &size, MAX_FASTLOG_ALERT_SIZE, + "] [pcap file packet: %" PRIu64 "]\n", p->pcap_cnt); } else { PrintBufferData(alert_buffer, &size, MAX_FASTLOG_ALERT_SIZE, "]\n"); } @@ -191,8 +192,7 @@ TmEcode AlertFastLogThreadInit(ThreadVars *t, const void *initdata, void **data) AlertFastLogThread *aft = SCCalloc(1, sizeof(AlertFastLogThread)); if (unlikely(aft == NULL)) return TM_ECODE_FAILED; - if(initdata == NULL) - { + if (initdata == NULL) { SCLogDebug("Error getting context for AlertFastLog. \"initdata\" argument NULL"); SCFree(aft); return TM_ECODE_FAILED; @@ -264,8 +264,8 @@ static void AlertFastLogDeInitCtx(OutputCtx *output_ctx) static int AlertFastLogTest01(void) { - uint8_t *buf = (uint8_t *) "GET /one/ HTTP/1.1\r\n" - "Host: one.example.org\r\n"; + uint8_t *buf = (uint8_t *)"GET /one/ HTTP/1.1\r\n" + "Host: one.example.org\r\n"; uint16_t buflen = strlen((char *)buf); Packet *p = NULL; @@ -284,8 +284,8 @@ static int AlertFastLogTest01(void) SCClassConfLoadClassificationConfigFile(de_ctx, fd); de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"FastLog test\"; content:\"GET\"; " - "Classtype:unknown; sid:1;)"); + "(msg:\"FastLog test\"; content:\"GET\"; " + "Classtype:unknown; sid:1;)"); SigGroupBuild(de_ctx); DetectEngineThreadCtxInit(&th_v, (void *)de_ctx, (void *)&det_ctx); @@ -305,8 +305,8 @@ static int AlertFastLogTest01(void) static int AlertFastLogTest02(void) { - uint8_t *buf = (uint8_t *) "GET /one/ HTTP/1.1\r\n" - "Host: one.example.org\r\n"; + uint8_t *buf = (uint8_t *)"GET /one/ HTTP/1.1\r\n" + "Host: one.example.org\r\n"; uint16_t buflen = strlen((char *)buf); Packet *p = NULL; ThreadVars th_v; @@ -325,8 +325,8 @@ static int AlertFastLogTest02(void) SCClassConfLoadClassificationConfigFile(de_ctx, fd); de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"FastLog test\"; content:\"GET\"; " - "Classtype:unknown; sid:1;)"); + "(msg:\"FastLog test\"; content:\"GET\"; " + "Classtype:unknown; sid:1;)"); SigGroupBuild(de_ctx); DetectEngineThreadCtxInit(&th_v, (void *)de_ctx, (void *)&det_ctx); @@ -358,5 +358,4 @@ void AlertFastLogRegisterTests(void) UtRegisterTest("AlertFastLogTest02", AlertFastLogTest02); #endif /* UNITTESTS */ - } diff --git a/src/alert-fastlog.h b/src/alert-fastlog.h index cdac2a49d404..e86faa289971 100644 --- a/src/alert-fastlog.h +++ b/src/alert-fastlog.h @@ -28,4 +28,3 @@ void AlertFastLogRegister(void); OutputInitResult AlertFastLogInitCtx(ConfNode *); #endif /* __ALERT_FASTLOG_H__ */ - diff --git a/src/alert-syslog.c b/src/alert-syslog.c index fd1742adb01f..1dce444ef9bc 100644 --- a/src/alert-syslog.c +++ b/src/alert-syslog.c @@ -52,13 +52,13 @@ #ifndef OS_WIN32 -#define MODULE_NAME "AlertSyslog" +#define MODULE_NAME "AlertSyslog" static int alert_syslog_level = DEFAULT_ALERT_SYSLOG_LEVEL; typedef struct AlertSyslogThread_ { /** LogFileCtx has the pointer to the file and a mutex to allow multithreading */ - LogFileCtx* file_ctx; + LogFileCtx *file_ctx; } AlertSyslogThread; /** @@ -119,7 +119,7 @@ static OutputInitResult AlertSyslogInitCtx(ConfNode *conf) /* if null we just pass that to openlog, which will then * figure it out by itself. */ - openlog(ident, LOG_PID|LOG_NDELAY, facility); + openlog(ident, LOG_PID | LOG_NDELAY, facility); OutputCtx *output_ctx = SCCalloc(1, sizeof(OutputCtx)); if (unlikely(output_ctx == NULL)) { @@ -148,9 +148,9 @@ static OutputInitResult AlertSyslogInitCtx(ConfNode *conf) */ static TmEcode AlertSyslogThreadInit(ThreadVars *t, const void *initdata, void **data) { - if(initdata == NULL) { + if (initdata == NULL) { SCLogDebug("Error getting context for AlertSyslog. \"initdata\" " - "argument NULL"); + "argument NULL"); return TM_ECODE_FAILED; } @@ -232,11 +232,12 @@ static TmEcode AlertSyslogIPv4(ThreadVars *tv, const Packet *p, void *data) action = "[wDrop] "; } - syslog(alert_syslog_level, "%s[%" PRIu32 ":%" PRIu32 ":%" - PRIu32 "] %s [Classification: %s] [Priority: %"PRIu32"]" - " {%s} %s:%" PRIu32 " -> %s:%" PRIu32 "", action, pa->s->gid, - pa->s->id, pa->s->rev, pa->s->msg, pa->s->class_msg, pa->s->prio, - protoptr, srcip, p->sp, dstip, p->dp); + syslog(alert_syslog_level, + "%s[%" PRIu32 ":%" PRIu32 ":%" PRIu32 + "] %s [Classification: %s] [Priority: %" PRIu32 "]" + " {%s} %s:%" PRIu32 " -> %s:%" PRIu32 "", + action, pa->s->gid, pa->s->id, pa->s->rev, pa->s->msg, pa->s->class_msg, + pa->s->prio, protoptr, srcip, p->sp, dstip, p->dp); } SCMutexUnlock(&ast->file_ctx->fp_mutex); @@ -289,13 +290,12 @@ static TmEcode AlertSyslogIPv6(ThreadVars *tv, const Packet *p, void *data) action = "[wDrop] "; } - syslog(alert_syslog_level, "%s[%" PRIu32 ":%" PRIu32 ":%" + syslog(alert_syslog_level, + "%s[%" PRIu32 ":%" PRIu32 ":%" "" PRIu32 "] %s [Classification: %s] [Priority: %" "" PRIu32 "] {%s} %s:%" PRIu32 " -> %s:%" PRIu32 "", action, pa->s->gid, pa->s->id, pa->s->rev, pa->s->msg, pa->s->class_msg, - pa->s->prio, protoptr, srcip, p->sp, - dstip, p->dp); - + pa->s->prio, protoptr, srcip, p->sp, dstip, p->dp); } SCMutexUnlock(&ast->file_ctx->fp_mutex); @@ -339,17 +339,19 @@ static TmEcode AlertSyslogDecoderEvent(ThreadVars *tv, const Packet *p, void *da action = "[wDrop] "; } - snprintf(temp_buf_hdr, sizeof(temp_buf_hdr), "%s[%" PRIu32 ":%" PRIu32 - ":%" PRIu32 "] %s [Classification: %s] [Priority: %" PRIu32 - "] [**] [Raw pkt: ", action, pa->s->gid, pa->s->id, pa->s->rev, pa->s->msg, - pa->s->class_msg, pa->s->prio); + snprintf(temp_buf_hdr, sizeof(temp_buf_hdr), + "%s[%" PRIu32 ":%" PRIu32 ":%" PRIu32 + "] %s [Classification: %s] [Priority: %" PRIu32 "] [**] [Raw pkt: ", + action, pa->s->gid, pa->s->id, pa->s->rev, pa->s->msg, pa->s->class_msg, + pa->s->prio); strlcpy(alert, temp_buf_hdr, sizeof(alert)); - PrintRawLineHexBuf(temp_buf_pkt, sizeof(temp_buf_pkt), GET_PKT_DATA(p), GET_PKT_LEN(p) < 32 ? GET_PKT_LEN(p) : 32); + PrintRawLineHexBuf(temp_buf_pkt, sizeof(temp_buf_pkt), GET_PKT_DATA(p), + GET_PKT_LEN(p) < 32 ? GET_PKT_LEN(p) : 32); strlcat(alert, temp_buf_pkt, sizeof(alert)); if (p->pcap_cnt != 0) { - snprintf(temp_buf_tail, sizeof(temp_buf_tail), "] [pcap file packet: %"PRIu64"]", + snprintf(temp_buf_tail, sizeof(temp_buf_tail), "] [pcap file packet: %" PRIu64 "]", p->pcap_cnt); } else { temp_buf_tail[0] = ']'; @@ -385,11 +387,11 @@ static int AlertSyslogLogger(ThreadVars *tv, void *thread_data, const Packet *p) #endif /* !OS_WIN32 */ /** \brief Function to register the AlertSyslog module */ -void AlertSyslogRegister (void) +void AlertSyslogRegister(void) { #ifndef OS_WIN32 - OutputRegisterPacketModule(LOGGER_ALERT_SYSLOG, MODULE_NAME, "syslog", - AlertSyslogInitCtx, AlertSyslogLogger, AlertSyslogCondition, - AlertSyslogThreadInit, AlertSyslogThreadDeinit, NULL); + OutputRegisterPacketModule(LOGGER_ALERT_SYSLOG, MODULE_NAME, "syslog", AlertSyslogInitCtx, + AlertSyslogLogger, AlertSyslogCondition, AlertSyslogThreadInit, AlertSyslogThreadDeinit, + NULL); #endif /* !OS_WIN32 */ } diff --git a/src/alert-syslog.h b/src/alert-syslog.h index 0655a3ae47cb..1c866b613b5c 100644 --- a/src/alert-syslog.h +++ b/src/alert-syslog.h @@ -30,4 +30,3 @@ void AlertSyslogRegister(void); #endif /* __ALERT_SYSLOG_H__ */ - diff --git a/src/app-layer-detect-proto.c b/src/app-layer-detect-proto.c index 487abd57066a..ba068589cbef 100644 --- a/src/app-layer-detect-proto.c +++ b/src/app-layer-detect-proto.c @@ -110,7 +110,7 @@ typedef struct AppLayerProtoDetectProbingParser_ { typedef struct AppLayerProtoDetectPMSignature_ { AppProto alproto; - uint8_t direction; /**< direction for midstream */ + uint8_t direction; /**< direction for midstream */ SigIntId id; /* \todo Change this into a non-pointer */ DetectContentData *cd; @@ -181,8 +181,7 @@ struct AppLayerProtoDetectThreadCtx_ { static AppLayerProtoDetectCtx alpd_ctx; static AppLayerProtoDetectAliases *alpda_ctx = NULL; -static void AppLayerProtoDetectPEGetIpprotos(AppProto alproto, - uint8_t *ipprotos); +static void AppLayerProtoDetectPEGetIpprotos(AppProto alproto, uint8_t *ipprotos); /***** Static Internal Calls: Protocol Retrieval *****/ @@ -197,23 +196,21 @@ static AppProto AppLayerProtoDetectPMMatchSignature(const AppLayerProtoDetectPMS SCEnter(); if (s->cd->offset > searchlen) { - SCLogDebug("s->co->offset (%"PRIu16") > searchlen (%"PRIu16")", - s->cd->offset, searchlen); + SCLogDebug( + "s->co->offset (%" PRIu16 ") > searchlen (%" PRIu16 ")", s->cd->offset, searchlen); SCReturnUInt(ALPROTO_UNKNOWN); } if (s->cd->depth > searchlen) { - SCLogDebug("s->co->depth (%"PRIu16") > searchlen (%"PRIu16")", - s->cd->depth, searchlen); + SCLogDebug("s->co->depth (%" PRIu16 ") > searchlen (%" PRIu16 ")", s->cd->depth, searchlen); SCReturnUInt(ALPROTO_UNKNOWN); } const uint8_t *sbuf = buf + s->cd->offset; uint16_t ssearchlen = s->cd->depth - s->cd->offset; - SCLogDebug("s->co->offset (%"PRIu16") s->cd->depth (%"PRIu16")", - s->cd->offset, s->cd->depth); + SCLogDebug( + "s->co->offset (%" PRIu16 ") s->cd->depth (%" PRIu16 ")", s->cd->offset, s->cd->depth); - uint8_t *found = SpmScan(s->cd->spm_ctx, tctx->spm_thread_ctx, - sbuf, ssearchlen); + uint8_t *found = SpmScan(s->cd->spm_ctx, tctx->spm_thread_ctx, sbuf, ssearchlen); if (found == NULL) { SCReturnUInt(ALPROTO_UNKNOWN); } @@ -229,19 +226,18 @@ static AppProto AppLayerProtoDetectPMMatchSignature(const AppLayerProtoDetectPMS SCLogDebug("direction is wrong, rflow = true"); *rflow = true; } - /* validate using Probing Parser */ + /* validate using Probing Parser */ } else { if (s->pp_min_depth > buflen) { - SCLogDebug("PP can't be run yet as pp_min_depth %u > buflen %u", - s->pp_min_depth, buflen); + SCLogDebug( + "PP can't be run yet as pp_min_depth %u > buflen %u", s->pp_min_depth, buflen); SCReturnInt(ALPROTO_UNKNOWN); } uint8_t rdir = 0; AppProto r = s->PPFunc(f, flags, buf, buflen, &rdir); if (r == s->alproto) { - SCLogDebug("found %s/%u, rdir %02x reverse_flow? %s", - AppProtoToString(r), r, rdir, + SCLogDebug("found %s/%u, rdir %02x reverse_flow? %s", AppProtoToString(r), r, rdir, (rdir && direction != rdir) ? "true" : "false"); *rflow = (rdir && direction != rdir); SCReturnUInt(s->alproto); @@ -275,8 +271,7 @@ static inline int PMGetProtoInspect(AppLayerProtoDetectThreadCtx *tctx, /* do the mpm search */ uint32_t search_cnt = mpm_table[pm_ctx->mpm_ctx.mpm_type].Search( - &pm_ctx->mpm_ctx, mpm_tctx, &tctx->pmq, - buf, searchlen); + &pm_ctx->mpm_ctx, mpm_tctx, &tctx->pmq, buf, searchlen); if (search_cnt == 0) { if (buflen >= pm_ctx->mpm_ctx.maxdepth) return -1; @@ -297,9 +292,7 @@ static inline int PMGetProtoInspect(AppLayerProtoDetectThreadCtx *tctx, s, tctx, f, flags, buf, buflen, searchlen, rflow); /* store each unique proto once */ - if (AppProtoIsValid(proto) && - !(pm_results_bf[proto / 8] & (1 << (proto % 8))) ) - { + if (AppProtoIsValid(proto) && !(pm_results_bf[proto / 8] & (1 << (proto % 8)))) { pm_results[pm_matches++] = proto; pm_results_bf[proto / 8] |= 1 << (proto % 8); } @@ -348,7 +341,7 @@ static AppProto AppLayerProtoDetectPMGetProto(AppLayerProtoDetectThreadCtx *tctx FLOW_SET_PM_DONE(f, flags); SCReturnUInt((uint16_t)m); - /* handle non-found in non-midstream case */ + /* handle non-found in non-midstream case */ } else if (!stream_config.midstream) { /* we can give up if mpm gave no results and its search depth * was reached. */ @@ -360,7 +353,7 @@ static AppProto AppLayerProtoDetectPMGetProto(AppLayerProtoDetectThreadCtx *tctx } SCReturnUInt((uint16_t)m); - /* handle non-found in midstream case */ + /* handle non-found in midstream case */ } else if (m <= 0) { if (flags & STREAM_TOSERVER) { pm_ctx = &alpd_ctx.ctx_ipp[f->protomap].ctx_pm[1]; @@ -382,12 +375,12 @@ static AppProto AppLayerProtoDetectPMGetProto(AppLayerProtoDetectThreadCtx *tctx FLOW_SET_PM_DONE(f, flags); SCReturnUInt((uint16_t)om); - /* both sides failed */ + /* both sides failed */ } else if (om < 0 && m && m < 0) { FLOW_SET_PM_DONE(f, flags); SCReturnUInt(0); - /* one side still uncertain */ + /* one side still uncertain */ } else if (om == 0 || m == 0) { SCReturnUInt(0); } @@ -425,9 +418,8 @@ static AppLayerProtoDetectProbingParserElement *AppLayerProtoDetectGetProbingPar SCReturnPtr(pp_elem, "AppLayerProtoDetectProbingParserElement *"); } -static AppLayerProtoDetectProbingParserPort *AppLayerProtoDetectGetProbingParsers(AppLayerProtoDetectProbingParser *pp, - uint8_t ipproto, - uint16_t port) +static AppLayerProtoDetectProbingParserPort *AppLayerProtoDetectGetProbingParsers( + AppLayerProtoDetectProbingParser *pp, uint8_t ipproto, uint16_t port) { AppLayerProtoDetectProbingParserPort *pp_port = NULL; @@ -449,11 +441,10 @@ static AppLayerProtoDetectProbingParserPort *AppLayerProtoDetectGetProbingParser pp_port = pp_port->next; } - end: +end: SCReturnPtr(pp_port, "AppLayerProtoDetectProbingParserPort *"); } - /** * \brief Call the probing expectation to see if there is some for this flow. * @@ -474,8 +465,7 @@ static inline AppProto PPGetProto(const AppLayerProtoDetectProbingParserElement uint8_t flags, const uint8_t *buf, uint32_t buflen, uint32_t *alproto_masks, uint8_t *rdir) { while (pe != NULL) { - if ((buflen < pe->min_depth) || - (alproto_masks[0] & pe->alproto_mask)) { + if ((buflen < pe->min_depth) || (alproto_masks[0] & pe->alproto_mask)) { pe = pe->next; continue; } @@ -489,8 +479,7 @@ static inline AppProto PPGetProto(const AppLayerProtoDetectProbingParserElement if (AppProtoIsValid(alproto)) { SCReturnUInt(alproto); } - if (alproto == ALPROTO_FAILED || - (pe->max_depth != 0 && buflen > pe->max_depth)) { + if (alproto == ALPROTO_FAILED || (pe->max_depth != 0 && buflen > pe->max_depth)) { alproto_masks[0] |= pe->alproto_mask; } pe = pe->next; @@ -527,30 +516,29 @@ static AppProto AppLayerProtoDetectPPGetProto(Flow *f, const uint8_t *buf, uint3 if (idir != dir) { SWAP_VARS(uint16_t, dp, sp); /* look up parsers in rev dir */ } - SCLogDebug("%u->%u %s", sp, dp, - (dir == STREAM_TOSERVER) ? "toserver" : "toclient"); + SCLogDebug("%u->%u %s", sp, dp, (dir == STREAM_TOSERVER) ? "toserver" : "toclient"); if (dir == STREAM_TOSERVER) { /* first try the destination port */ pp_port_dp = AppLayerProtoDetectGetProbingParsers(alpd_ctx.ctx_pp, ipproto, dp); alproto_masks = &f->probing_parser_toserver_alproto_masks; if (pp_port_dp != NULL) { - SCLogDebug("toserver - Probing parser found for destination port %"PRIu16, dp); + SCLogDebug("toserver - Probing parser found for destination port %" PRIu16, dp); /* found based on destination port, so use dp registration */ pe1 = pp_port_dp->dp; } else { - SCLogDebug("toserver - No probing parser registered for dest port %"PRIu16, dp); + SCLogDebug("toserver - No probing parser registered for dest port %" PRIu16, dp); } pp_port_sp = AppLayerProtoDetectGetProbingParsers(alpd_ctx.ctx_pp, ipproto, sp); if (pp_port_sp != NULL) { - SCLogDebug("toserver - Probing parser found for source port %"PRIu16, sp); + SCLogDebug("toserver - Probing parser found for source port %" PRIu16, sp); /* found based on source port, so use sp registration */ pe2 = pp_port_sp->sp; } else { - SCLogDebug("toserver - No probing parser registered for source port %"PRIu16, sp); + SCLogDebug("toserver - No probing parser registered for source port %" PRIu16, sp); } } else { /* first try the destination port */ @@ -561,21 +549,21 @@ static AppProto AppLayerProtoDetectPPGetProto(Flow *f, const uint8_t *buf, uint3 alproto_masks = &f->probing_parser_toclient_alproto_masks; } if (pp_port_dp != NULL) { - SCLogDebug("toclient - Probing parser found for destination port %"PRIu16, dp); + SCLogDebug("toclient - Probing parser found for destination port %" PRIu16, dp); /* found based on destination port, so use dp registration */ pe1 = pp_port_dp->dp; } else { - SCLogDebug("toclient - No probing parser registered for dest port %"PRIu16, dp); + SCLogDebug("toclient - No probing parser registered for dest port %" PRIu16, dp); } pp_port_sp = AppLayerProtoDetectGetProbingParsers(alpd_ctx.ctx_pp, ipproto, sp); if (pp_port_sp != NULL) { - SCLogDebug("toclient - Probing parser found for source port %"PRIu16, sp); + SCLogDebug("toclient - Probing parser found for source port %" PRIu16, sp); pe2 = pp_port_sp->sp; } else { - SCLogDebug("toclient - No probing parser registered for source port %"PRIu16, sp); + SCLogDebug("toclient - No probing parser registered for source port %" PRIu16, sp); } } @@ -587,7 +575,7 @@ static AppProto AppLayerProtoDetectPPGetProto(Flow *f, const uint8_t *buf, uint3 if (pe1 == NULL && pe2 == NULL && pe0 == NULL) { SCLogDebug("%s - No probing parsers found for either port", - (dir == STREAM_TOSERVER) ? "toserver":"toclient"); + (dir == STREAM_TOSERVER) ? "toserver" : "toclient"); goto noparsers; } else { probe_is_found = true; @@ -608,7 +596,7 @@ static AppProto AppLayerProtoDetectPPGetProto(Flow *f, const uint8_t *buf, uint3 /* get the mask we need for this direction */ if (dir == idir) { if (pp_port_dp && pp_port_sp) - mask = pp_port_dp->alproto_mask|pp_port_sp->alproto_mask; + mask = pp_port_dp->alproto_mask | pp_port_sp->alproto_mask; else if (pp_port_dp) mask = pp_port_dp->alproto_mask; else if (pp_port_sp) @@ -617,12 +605,10 @@ static AppProto AppLayerProtoDetectPPGetProto(Flow *f, const uint8_t *buf, uint3 if (alproto_masks[0] == mask) { FLOW_SET_PP_DONE(f, dir); SCLogDebug("%s, mask is now %08x, needed %08x, so done", - (dir == STREAM_TOSERVER) ? "toserver":"toclient", - alproto_masks[0], mask); + (dir == STREAM_TOSERVER) ? "toserver" : "toclient", alproto_masks[0], mask); } else { SCLogDebug("%s, mask is now %08x, need %08x", - (dir == STREAM_TOSERVER) ? "toserver":"toclient", - alproto_masks[0], mask); + (dir == STREAM_TOSERVER) ? "toserver" : "toclient", alproto_masks[0], mask); } } @@ -640,21 +626,20 @@ static AppProto AppLayerProtoDetectPPGetProto(Flow *f, const uint8_t *buf, uint3 FLOW_SET_PP_DONE(f, idir); } - end: +end: if (AppProtoIsValid(alproto) && rdir != 0 && rdir != idir) { SCLogDebug("PP found %u, is reverse flow", alproto); *reverse_flow = true; } - SCLogDebug("%s, mask is now %08x", - (idir == STREAM_TOSERVER) ? "toserver":"toclient", alproto_masks[0]); + SCLogDebug("%s, mask is now %08x", (idir == STREAM_TOSERVER) ? "toserver" : "toclient", + alproto_masks[0]); SCReturnUInt(alproto); } /***** Static Internal Calls: PP registration *****/ -static void AppLayerProtoDetectPPGetIpprotos(AppProto alproto, - uint8_t *ipprotos) +static void AppLayerProtoDetectPPGetIpprotos(AppProto alproto, uint8_t *ipprotos) { SCEnter(); @@ -702,7 +687,6 @@ static AppLayerProtoDetectProbingParserElement *AppLayerProtoDetectProbingParser SCReturnPtr(p, "AppLayerProtoDetectProbingParserElement"); } - static void AppLayerProtoDetectProbingParserElementFree(AppLayerProtoDetectProbingParserElement *p) { SCEnter(); @@ -776,11 +760,8 @@ static void AppLayerProtoDetectProbingParserFree(AppLayerProtoDetectProbingParse SCReturn; } -static AppLayerProtoDetectProbingParserElement * -AppLayerProtoDetectProbingParserElementCreate(AppProto alproto, - uint16_t port, - uint16_t min_depth, - uint16_t max_depth) +static AppLayerProtoDetectProbingParserElement *AppLayerProtoDetectProbingParserElementCreate( + AppProto alproto, uint16_t port, uint16_t min_depth, uint16_t max_depth) { AppLayerProtoDetectProbingParserElement *pe = AppLayerProtoDetectProbingParserElementAlloc(); @@ -804,17 +785,18 @@ AppLayerProtoDetectProbingParserElementCreate(AppProto alproto, } SCReturnPtr(pe, "AppLayerProtoDetectProbingParserElement"); - error: +error: AppLayerProtoDetectProbingParserElementFree(pe); SCReturnPtr(NULL, "AppLayerProtoDetectProbingParserElement"); } -static AppLayerProtoDetectProbingParserElement * -AppLayerProtoDetectProbingParserElementDuplicate(AppLayerProtoDetectProbingParserElement *pe) +static AppLayerProtoDetectProbingParserElement *AppLayerProtoDetectProbingParserElementDuplicate( + AppLayerProtoDetectProbingParserElement *pe) { SCEnter(); - AppLayerProtoDetectProbingParserElement *new_pe = AppLayerProtoDetectProbingParserElementAlloc(); + AppLayerProtoDetectProbingParserElement *new_pe = + AppLayerProtoDetectProbingParserElementAlloc(); new_pe->alproto = pe->alproto; new_pe->port = pe->port; @@ -838,32 +820,31 @@ static void AppLayerProtoDetectPrintProbingParsers(AppLayerProtoDetectProbingPar printf("\nProtocol Detection Configuration\n"); - for ( ; pp != NULL; pp = pp->next) { + for (; pp != NULL; pp = pp->next) { /* print ip protocol */ if (pp->ipproto == IPPROTO_TCP) printf("IPProto: TCP\n"); else if (pp->ipproto == IPPROTO_UDP) printf("IPProto: UDP\n"); else - printf("IPProto: %"PRIu8"\n", pp->ipproto); + printf("IPProto: %" PRIu8 "\n", pp->ipproto); pp_port = pp->port; - for ( ; pp_port != NULL; pp_port = pp_port->next) { + for (; pp_port != NULL; pp_port = pp_port->next) { if (pp_port->dp != NULL) { - printf(" Port: %"PRIu16 "\n", pp_port->port); + printf(" Port: %" PRIu16 "\n", pp_port->port); - printf(" Destination port: (max-depth: %"PRIu16 ", " - "mask - %"PRIu32")\n", - pp_port->dp_max_depth, - pp_port->alproto_mask); + printf(" Destination port: (max-depth: %" PRIu16 ", " + "mask - %" PRIu32 ")\n", + pp_port->dp_max_depth, pp_port->alproto_mask); pp_pe = pp_port->dp; - for ( ; pp_pe != NULL; pp_pe = pp_pe->next) { + for (; pp_pe != NULL; pp_pe = pp_pe->next) { printf(" alproto: %s\n", AppProtoToString(pp_pe->alproto)); - printf(" port: %"PRIu16 "\n", pp_pe->port); - printf(" mask: %"PRIu32 "\n", pp_pe->alproto_mask); - printf(" min_depth: %"PRIu32 "\n", pp_pe->min_depth); - printf(" max_depth: %"PRIu32 "\n", pp_pe->max_depth); + printf(" port: %" PRIu16 "\n", pp_pe->port); + printf(" mask: %" PRIu32 "\n", pp_pe->alproto_mask); + printf(" min_depth: %" PRIu32 "\n", pp_pe->min_depth); + printf(" max_depth: %" PRIu32 "\n", pp_pe->max_depth); printf("\n"); } @@ -873,18 +854,17 @@ static void AppLayerProtoDetectPrintProbingParsers(AppLayerProtoDetectProbingPar continue; } - printf(" Source port: (max-depth: %"PRIu16 ", " - "mask - %"PRIu32")\n", - pp_port->sp_max_depth, - pp_port->alproto_mask); + printf(" Source port: (max-depth: %" PRIu16 ", " + "mask - %" PRIu32 ")\n", + pp_port->sp_max_depth, pp_port->alproto_mask); pp_pe = pp_port->sp; - for ( ; pp_pe != NULL; pp_pe = pp_pe->next) { + for (; pp_pe != NULL; pp_pe = pp_pe->next) { printf(" alproto: %s\n", AppProtoToString(pp_pe->alproto)); - printf(" port: %"PRIu16 "\n", pp_pe->port); - printf(" mask: %"PRIu32 "\n", pp_pe->alproto_mask); - printf(" min_depth: %"PRIu32 "\n", pp_pe->min_depth); - printf(" max_depth: %"PRIu32 "\n", pp_pe->max_depth); + printf(" port: %" PRIu16 "\n", pp_pe->port); + printf(" mask: %" PRIu32 "\n", pp_pe->alproto_mask); + printf(" min_depth: %" PRIu32 "\n", pp_pe->min_depth); + printf(" max_depth: %" PRIu32 "\n", pp_pe->max_depth); printf("\n"); } @@ -895,8 +875,9 @@ static void AppLayerProtoDetectPrintProbingParsers(AppLayerProtoDetectProbingPar } #endif -static void AppLayerProtoDetectProbingParserElementAppend(AppLayerProtoDetectProbingParserElement **head_pe, - AppLayerProtoDetectProbingParserElement *new_pe) +static void AppLayerProtoDetectProbingParserElementAppend( + AppLayerProtoDetectProbingParserElement **head_pe, + AppLayerProtoDetectProbingParserElement *new_pe) { SCEnter(); @@ -926,16 +907,15 @@ static void AppLayerProtoDetectProbingParserElementAppend(AppLayerProtoDetectPro temp_pe = temp_pe->next; new_pe->next = temp_pe->next; temp_pe->next = new_pe; - } } - end: +end: SCReturn; } -static void AppLayerProtoDetectProbingParserAppend(AppLayerProtoDetectProbingParser **head_pp, - AppLayerProtoDetectProbingParser *new_pp) +static void AppLayerProtoDetectProbingParserAppend( + AppLayerProtoDetectProbingParser **head_pp, AppLayerProtoDetectProbingParser *new_pp) { SCEnter(); @@ -949,12 +929,13 @@ static void AppLayerProtoDetectProbingParserAppend(AppLayerProtoDetectProbingPar temp_pp = temp_pp->next; temp_pp->next = new_pp; - end: +end: SCReturn; } -static void AppLayerProtoDetectProbingParserPortAppend(AppLayerProtoDetectProbingParserPort **head_port, - AppLayerProtoDetectProbingParserPort *new_port) +static void AppLayerProtoDetectProbingParserPortAppend( + AppLayerProtoDetectProbingParserPort **head_port, + AppLayerProtoDetectProbingParserPort *new_port) { SCEnter(); @@ -975,18 +956,13 @@ static void AppLayerProtoDetectProbingParserPortAppend(AppLayerProtoDetectProbin temp_port->next = new_port; } - end: +end: SCReturn; } static void AppLayerProtoDetectInsertNewProbingParser(AppLayerProtoDetectProbingParser **pp, - uint8_t ipproto, - uint16_t port, - AppProto alproto, - uint16_t min_depth, uint16_t max_depth, - uint8_t direction, - ProbingParserFPtr ProbingParser1, - ProbingParserFPtr ProbingParser2) + uint8_t ipproto, uint16_t port, AppProto alproto, uint16_t min_depth, uint16_t max_depth, + uint8_t direction, ProbingParserFPtr ProbingParser1, ProbingParserFPtr ProbingParser2) { SCEnter(); @@ -1012,7 +988,8 @@ static void AppLayerProtoDetectInsertNewProbingParser(AppLayerProtoDetectProbing curr_port = curr_port->next; } if (curr_port == NULL) { - AppLayerProtoDetectProbingParserPort *new_port = AppLayerProtoDetectProbingParserPortAlloc(); + AppLayerProtoDetectProbingParserPort *new_port = + AppLayerProtoDetectProbingParserPortAlloc(); new_port->port = port; AppLayerProtoDetectProbingParserPortAppend(&curr_pp->port, new_port); curr_port = new_port; @@ -1032,40 +1009,38 @@ static void AppLayerProtoDetectInsertNewProbingParser(AppLayerProtoDetectProbing AppLayerProtoDetectProbingParserElement *zero_pe; zero_pe = zero_port->dp; - for ( ; zero_pe != NULL; zero_pe = zero_pe->next) { + for (; zero_pe != NULL; zero_pe = zero_pe->next) { if (curr_port->dp == NULL) curr_port->dp_max_depth = zero_pe->max_depth; if (zero_pe->max_depth == 0) curr_port->dp_max_depth = zero_pe->max_depth; - if (curr_port->dp_max_depth != 0 && - curr_port->dp_max_depth < zero_pe->max_depth) { + if (curr_port->dp_max_depth != 0 && curr_port->dp_max_depth < zero_pe->max_depth) { curr_port->dp_max_depth = zero_pe->max_depth; } AppLayerProtoDetectProbingParserElement *dup_pe = - AppLayerProtoDetectProbingParserElementDuplicate(zero_pe); + AppLayerProtoDetectProbingParserElementDuplicate(zero_pe); AppLayerProtoDetectProbingParserElementAppend(&curr_port->dp, dup_pe); curr_port->alproto_mask |= dup_pe->alproto_mask; } zero_pe = zero_port->sp; - for ( ; zero_pe != NULL; zero_pe = zero_pe->next) { + for (; zero_pe != NULL; zero_pe = zero_pe->next) { if (curr_port->sp == NULL) curr_port->sp_max_depth = zero_pe->max_depth; if (zero_pe->max_depth == 0) curr_port->sp_max_depth = zero_pe->max_depth; - if (curr_port->sp_max_depth != 0 && - curr_port->sp_max_depth < zero_pe->max_depth) { + if (curr_port->sp_max_depth != 0 && curr_port->sp_max_depth < zero_pe->max_depth) { curr_port->sp_max_depth = zero_pe->max_depth; } AppLayerProtoDetectProbingParserElement *dup_pe = - AppLayerProtoDetectProbingParserElementDuplicate(zero_pe); + AppLayerProtoDetectProbingParserElementDuplicate(zero_pe); AppLayerProtoDetectProbingParserElementAppend(&curr_port->sp, dup_pe); curr_port->alproto_mask |= dup_pe->alproto_mask; } } /* if (zero_port != NULL) */ - } /* if (curr_port == NULL) */ + } /* if (curr_port == NULL) */ /* insert the pe_pp */ AppLayerProtoDetectProbingParserElement *curr_pe; @@ -1086,10 +1061,8 @@ static void AppLayerProtoDetectInsertNewProbingParser(AppLayerProtoDetectProbing curr_pe = curr_pe->next; } /* Get a new parser element */ - AppLayerProtoDetectProbingParserElement *new_pe = - AppLayerProtoDetectProbingParserElementCreate(alproto, - curr_port->port, - min_depth, max_depth); + AppLayerProtoDetectProbingParserElement *new_pe = AppLayerProtoDetectProbingParserElementCreate( + alproto, curr_port->port, min_depth, max_depth); if (new_pe == NULL) goto error; curr_pe = new_pe; @@ -1101,8 +1074,7 @@ static void AppLayerProtoDetectInsertNewProbingParser(AppLayerProtoDetectProbing curr_port->dp_max_depth = new_pe->max_depth; if (new_pe->max_depth == 0) curr_port->dp_max_depth = new_pe->max_depth; - if (curr_port->dp_max_depth != 0 && - curr_port->dp_max_depth < new_pe->max_depth) { + if (curr_port->dp_max_depth != 0 && curr_port->dp_max_depth < new_pe->max_depth) { curr_port->dp_max_depth = new_pe->max_depth; } curr_port->alproto_mask |= new_pe->alproto_mask; @@ -1114,8 +1086,7 @@ static void AppLayerProtoDetectInsertNewProbingParser(AppLayerProtoDetectProbing curr_port->sp_max_depth = new_pe->max_depth; if (new_pe->max_depth == 0) curr_port->sp_max_depth = new_pe->max_depth; - if (curr_port->sp_max_depth != 0 && - curr_port->sp_max_depth < new_pe->max_depth) { + if (curr_port->sp_max_depth != 0 && curr_port->sp_max_depth < new_pe->max_depth) { curr_port->sp_max_depth = new_pe->max_depth; } curr_port->alproto_mask |= new_pe->alproto_mask; @@ -1131,38 +1102,35 @@ static void AppLayerProtoDetectInsertNewProbingParser(AppLayerProtoDetectProbing temp_port->dp_max_depth = curr_pe->max_depth; if (curr_pe->max_depth == 0) temp_port->dp_max_depth = curr_pe->max_depth; - if (temp_port->dp_max_depth != 0 && - temp_port->dp_max_depth < curr_pe->max_depth) { + if (temp_port->dp_max_depth != 0 && temp_port->dp_max_depth < curr_pe->max_depth) { temp_port->dp_max_depth = curr_pe->max_depth; } - AppLayerProtoDetectProbingParserElementAppend(&temp_port->dp, - AppLayerProtoDetectProbingParserElementDuplicate(curr_pe)); + AppLayerProtoDetectProbingParserElementAppend( + &temp_port->dp, AppLayerProtoDetectProbingParserElementDuplicate(curr_pe)); temp_port->alproto_mask |= curr_pe->alproto_mask; } else { if (temp_port->sp == NULL) temp_port->sp_max_depth = curr_pe->max_depth; if (curr_pe->max_depth == 0) temp_port->sp_max_depth = curr_pe->max_depth; - if (temp_port->sp_max_depth != 0 && - temp_port->sp_max_depth < curr_pe->max_depth) { + if (temp_port->sp_max_depth != 0 && temp_port->sp_max_depth < curr_pe->max_depth) { temp_port->sp_max_depth = curr_pe->max_depth; } - AppLayerProtoDetectProbingParserElementAppend(&temp_port->sp, - AppLayerProtoDetectProbingParserElementDuplicate(curr_pe)); + AppLayerProtoDetectProbingParserElementAppend( + &temp_port->sp, AppLayerProtoDetectProbingParserElementDuplicate(curr_pe)); temp_port->alproto_mask |= curr_pe->alproto_mask; } temp_port = temp_port->next; } /* while */ - } /* if */ + } /* if */ - error: +error: SCReturn; } /***** Static Internal Calls: PM registration *****/ -static void AppLayerProtoDetectPMGetIpprotos(AppProto alproto, - uint8_t *ipprotos) +static void AppLayerProtoDetectPMGetIpprotos(AppProto alproto, uint8_t *ipprotos) { SCEnter(); @@ -1226,8 +1194,7 @@ static int AppLayerProtoDetectPMSetContentIDs(AppLayerProtoDetectPMCtx *ctx) for (; tcdup != struct_offset; tcdup++) { if (tcdup->content_len != content_len || - SCMemcmp(tcdup->content, content, tcdup->content_len) != 0) - { + SCMemcmp(tcdup->content, content, tcdup->content_len) != 0) { continue; } break; @@ -1251,9 +1218,9 @@ static int AppLayerProtoDetectPMSetContentIDs(AppLayerProtoDetectPMCtx *ctx) ctx->max_pat_id = max_id; goto end; - error: +error: ret = -1; - end: +end: if (ahb != NULL) SCFree(ahb); SCReturnInt(ret); @@ -1273,21 +1240,18 @@ static int AppLayerProtoDetectPMMapSignatures(AppLayerProtoDetectPMCtx *ctx) goto error; /* add an array indexed by rule id to look up the sig */ - for (s = ctx->head; s != NULL; ) { + for (s = ctx->head; s != NULL;) { next_s = s->next; s->id = id++; - SCLogDebug("s->id %u offset %u depth %u", - s->id, s->cd->offset, s->cd->depth); + SCLogDebug("s->id %u offset %u depth %u", s->id, s->cd->offset, s->cd->depth); if (s->cd->flags & DETECT_CONTENT_NOCASE) { - mpm_ret = MpmAddPatternCI(&ctx->mpm_ctx, - s->cd->content, s->cd->content_len, + mpm_ret = MpmAddPatternCI(&ctx->mpm_ctx, s->cd->content, s->cd->content_len, s->cd->offset, s->cd->depth, s->cd->id, s->id, 0); if (mpm_ret < 0) goto error; } else { - mpm_ret = MpmAddPatternCS(&ctx->mpm_ctx, - s->cd->content, s->cd->content_len, + mpm_ret = MpmAddPatternCS(&ctx->mpm_ctx, s->cd->content, s->cd->content_len, s->cd->offset, s->cd->depth, s->cd->id, s->id, 0); if (mpm_ret < 0) goto error; @@ -1300,9 +1264,9 @@ static int AppLayerProtoDetectPMMapSignatures(AppLayerProtoDetectPMCtx *ctx) ctx->head = NULL; goto end; - error: +error: ret = -1; - end: +end: SCReturnInt(ret); } @@ -1317,9 +1281,9 @@ static int AppLayerProtoDetectPMPrepareMpm(AppLayerProtoDetectPMCtx *ctx) goto error; goto end; - error: +error: ret = -1; - end: +end: SCReturnInt(ret); } @@ -1335,9 +1299,8 @@ static void AppLayerProtoDetectPMFreeSignature(AppLayerProtoDetectPMSignature *s } static int AppLayerProtoDetectPMAddSignature(AppLayerProtoDetectPMCtx *ctx, DetectContentData *cd, - AppProto alproto, uint8_t direction, - ProbingParserFPtr PPFunc, - uint16_t pp_min_depth, uint16_t pp_max_depth) + AppProto alproto, uint8_t direction, ProbingParserFPtr PPFunc, uint16_t pp_min_depth, + uint16_t pp_max_depth) { SCEnter(); @@ -1360,12 +1323,8 @@ static int AppLayerProtoDetectPMAddSignature(AppLayerProtoDetectPMCtx *ctx, Dete } static int AppLayerProtoDetectPMRegisterPattern(uint8_t ipproto, AppProto alproto, - const char *pattern, - uint16_t depth, uint16_t offset, - uint8_t direction, - uint8_t is_cs, - ProbingParserFPtr PPFunc, - uint16_t pp_min_depth, uint16_t pp_max_depth) + const char *pattern, uint16_t depth, uint16_t offset, uint8_t direction, uint8_t is_cs, + ProbingParserFPtr PPFunc, uint16_t pp_min_depth, uint16_t pp_max_depth) { SCEnter(); @@ -1373,8 +1332,8 @@ static int AppLayerProtoDetectPMRegisterPattern(uint8_t ipproto, AppProto alprot AppLayerProtoDetectPMCtx *ctx_pm = NULL; int ret = 0; - DetectContentData *cd = DetectContentParseEncloseQuotes( - alpd_ctx.spm_global_thread_ctx, pattern); + DetectContentData *cd = + DetectContentParseEncloseQuotes(alpd_ctx.spm_global_thread_ctx, pattern); if (cd == NULL) goto error; cd->depth = depth; @@ -1382,8 +1341,7 @@ static int AppLayerProtoDetectPMRegisterPattern(uint8_t ipproto, AppProto alprot if (!is_cs) { /* Rebuild as nocase */ SpmDestroyCtx(cd->spm_ctx); - cd->spm_ctx = SpmInitCtx(cd->content, cd->content_len, 1, - alpd_ctx.spm_global_thread_ctx); + cd->spm_ctx = SpmInitCtx(cd->content, cd->content_len, 1, alpd_ctx.spm_global_thread_ctx); if (cd->spm_ctx == NULL) { goto error; } @@ -1403,14 +1361,14 @@ static int AppLayerProtoDetectPMRegisterPattern(uint8_t ipproto, AppProto alprot ctx_pm->min_len = depth; /* Finally turn it into a signature and add to the ctx. */ - AppLayerProtoDetectPMAddSignature(ctx_pm, cd, alproto, direction, - PPFunc, pp_min_depth, pp_max_depth); + AppLayerProtoDetectPMAddSignature( + ctx_pm, cd, alproto, direction, PPFunc, pp_min_depth, pp_max_depth); goto end; - error: +error: DetectContentFree(NULL, cd); ret = -1; - end: +end: SCReturnInt(ret); } @@ -1470,7 +1428,7 @@ AppProto AppLayerProtoDetectGetProto(AppLayerProtoDetectThreadCtx *tctx, Flow *f alproto = AppLayerProtoDetectPEGetProto(f, ipproto, flags); } - end: +end: if (!AppProtoIsValid(alproto)) alproto = pm_alproto; @@ -1492,7 +1450,7 @@ static void AppLayerProtoDetectFreeProbingParsers(AppLayerProtoDetectProbingPars pp = tmp_pp; } - end: +end: SCReturn; } @@ -1551,9 +1509,9 @@ int AppLayerProtoDetectPrepareState(void) #endif goto end; - error: +error: ret = -1; - end: +end: SCReturnInt(ret); } @@ -1563,32 +1521,22 @@ int AppLayerProtoDetectPrepareState(void) * * \param direction STREAM_TOSERVER or STREAM_TOCLIENT for dp or sp */ -void AppLayerProtoDetectPPRegister(uint8_t ipproto, - const char *portstr, - AppProto alproto, - uint16_t min_depth, uint16_t max_depth, - uint8_t direction, - ProbingParserFPtr ProbingParser1, - ProbingParserFPtr ProbingParser2) +void AppLayerProtoDetectPPRegister(uint8_t ipproto, const char *portstr, AppProto alproto, + uint16_t min_depth, uint16_t max_depth, uint8_t direction, ProbingParserFPtr ProbingParser1, + ProbingParserFPtr ProbingParser2) { SCEnter(); DetectPort *head = NULL; - DetectPortParse(NULL,&head, portstr); + DetectPortParse(NULL, &head, portstr); DetectPort *temp_dp = head; while (temp_dp != NULL) { uint16_t port = temp_dp->port; if (port == 0 && temp_dp->port2 != 0) port++; for (;;) { - AppLayerProtoDetectInsertNewProbingParser(&alpd_ctx.ctx_pp, - ipproto, - port, - alproto, - min_depth, max_depth, - direction, - ProbingParser1, - ProbingParser2); + AppLayerProtoDetectInsertNewProbingParser(&alpd_ctx.ctx_pp, ipproto, port, alproto, + min_depth, max_depth, direction, ProbingParser1, ProbingParser2); if (port == temp_dp->port2) { break; } else { @@ -1597,18 +1545,14 @@ void AppLayerProtoDetectPPRegister(uint8_t ipproto, } temp_dp = temp_dp->next; } - DetectPortCleanupList(NULL,head); + DetectPortCleanupList(NULL, head); SCReturn; } -int AppLayerProtoDetectPPParseConfPorts(const char *ipproto_name, - uint8_t ipproto, - const char *alproto_name, - AppProto alproto, - uint16_t min_depth, uint16_t max_depth, - ProbingParserFPtr ProbingParserTs, - ProbingParserFPtr ProbingParserTc) +int AppLayerProtoDetectPPParseConfPorts(const char *ipproto_name, uint8_t ipproto, + const char *alproto_name, AppProto alproto, uint16_t min_depth, uint16_t max_depth, + ProbingParserFPtr ProbingParserTs, ProbingParserFPtr ProbingParserTc) { SCEnter(); @@ -1618,8 +1562,8 @@ int AppLayerProtoDetectPPParseConfPorts(const char *ipproto_name, ConfNode *port_node = NULL; int config = 0; - r = snprintf(param, sizeof(param), "%s%s%s", "app-layer.protocols.", - alproto_name, ".detection-ports"); + r = snprintf(param, sizeof(param), "%s%s%s", "app-layer.protocols.", alproto_name, + ".detection-ports"); if (r < 0) { FatalError("snprintf failure."); } else if (r > (int)sizeof(param)) { @@ -1628,8 +1572,8 @@ int AppLayerProtoDetectPPParseConfPorts(const char *ipproto_name, node = ConfGetNode(param); if (node == NULL) { SCLogDebug("Entry for %s not found.", param); - r = snprintf(param, sizeof(param), "%s%s%s%s%s", "app-layer.protocols.", - alproto_name, ".", ipproto_name, ".detection-ports"); + r = snprintf(param, sizeof(param), "%s%s%s%s%s", "app-layer.protocols.", alproto_name, ".", + ipproto_name, ".detection-ports"); if (r < 0) { FatalError("snprintf failure."); } else if (r > (int)sizeof(param)) { @@ -1646,12 +1590,9 @@ int AppLayerProtoDetectPPParseConfPorts(const char *ipproto_name, port_node = ConfNodeLookupChild(node, "toserver"); if (port_node != NULL && port_node->val != NULL) { - AppLayerProtoDetectPPRegister(ipproto, - port_node->val, - alproto, - min_depth, max_depth, - STREAM_TOSERVER, /* to indicate dp */ - ProbingParserTs, ProbingParserTc); + AppLayerProtoDetectPPRegister(ipproto, port_node->val, alproto, min_depth, max_depth, + STREAM_TOSERVER, /* to indicate dp */ + ProbingParserTs, ProbingParserTc); } /* detect by source port of flow */ @@ -1660,59 +1601,43 @@ int AppLayerProtoDetectPPParseConfPorts(const char *ipproto_name, port_node = ConfNodeLookupChild(node, "toclient"); if (port_node != NULL && port_node->val != NULL) { - AppLayerProtoDetectPPRegister(ipproto, - port_node->val, - alproto, - min_depth, max_depth, - STREAM_TOCLIENT, /* to indicate sp */ - ProbingParserTc, ProbingParserTs); - + AppLayerProtoDetectPPRegister(ipproto, port_node->val, alproto, min_depth, max_depth, + STREAM_TOCLIENT, /* to indicate sp */ + ProbingParserTc, ProbingParserTs); } config = 1; - end: +end: SCReturnInt(config); } /***** PM registration *****/ -int AppLayerProtoDetectPMRegisterPatternCS(uint8_t ipproto, AppProto alproto, - const char *pattern, - uint16_t depth, uint16_t offset, - uint8_t direction) +int AppLayerProtoDetectPMRegisterPatternCS(uint8_t ipproto, AppProto alproto, const char *pattern, + uint16_t depth, uint16_t offset, uint8_t direction) { SCEnter(); - int r = AppLayerProtoDetectPMRegisterPattern(ipproto, alproto, - pattern, depth, offset, - direction, 1 /* case-sensitive */, - NULL, 0, 0); + int r = AppLayerProtoDetectPMRegisterPattern(ipproto, alproto, pattern, depth, offset, + direction, 1 /* case-sensitive */, NULL, 0, 0); SCReturnInt(r); } int AppLayerProtoDetectPMRegisterPatternCSwPP(uint8_t ipproto, AppProto alproto, - const char *pattern, uint16_t depth, uint16_t offset, - uint8_t direction, - ProbingParserFPtr PPFunc, - uint16_t pp_min_depth, uint16_t pp_max_depth) + const char *pattern, uint16_t depth, uint16_t offset, uint8_t direction, + ProbingParserFPtr PPFunc, uint16_t pp_min_depth, uint16_t pp_max_depth) { SCEnter(); - int r = AppLayerProtoDetectPMRegisterPattern(ipproto, alproto, - pattern, depth, offset, - direction, 1 /* case-sensitive */, - PPFunc, pp_min_depth, pp_max_depth); + int r = AppLayerProtoDetectPMRegisterPattern(ipproto, alproto, pattern, depth, offset, + direction, 1 /* case-sensitive */, PPFunc, pp_min_depth, pp_max_depth); SCReturnInt(r); } -int AppLayerProtoDetectPMRegisterPatternCI(uint8_t ipproto, AppProto alproto, - const char *pattern, - uint16_t depth, uint16_t offset, - uint8_t direction) +int AppLayerProtoDetectPMRegisterPatternCI(uint8_t ipproto, AppProto alproto, const char *pattern, + uint16_t depth, uint16_t offset, uint8_t direction) { SCEnter(); - int r = AppLayerProtoDetectPMRegisterPattern(ipproto, alproto, - pattern, depth, offset, - direction, 0 /* !case-sensitive */, - NULL, 0, 0); + int r = AppLayerProtoDetectPMRegisterPattern(ipproto, alproto, pattern, depth, offset, + direction, 0 /* !case-sensitive */, NULL, 0, 0); SCReturnInt(r); } @@ -1880,7 +1805,7 @@ void AppLayerProtoDetectReset(Flow *f) // Does not free the structures for the parser // keeps f->alstate for new state creation f->alparser = NULL; - f->alproto = ALPROTO_UNKNOWN; + f->alproto = ALPROTO_UNKNOWN; f->alproto_ts = ALPROTO_UNKNOWN; f->alproto_tc = ALPROTO_UNKNOWN; } @@ -1905,8 +1830,7 @@ int AppLayerProtoDetectConfProtoDetectionEnabledDefault( default_enabled = true; #endif - r = snprintf(param, sizeof(param), "%s%s%s", "app-layer.protocols.", - alproto, ".enabled"); + r = snprintf(param, sizeof(param), "%s%s%s", "app-layer.protocols.", alproto, ".enabled"); if (r < 0) { FatalError("snprintf failure."); } else if (r > (int)sizeof(param)) { @@ -1916,8 +1840,8 @@ int AppLayerProtoDetectConfProtoDetectionEnabledDefault( node = ConfGetNode(param); if (node == NULL) { SCLogDebug("Entry for %s not found.", param); - r = snprintf(param, sizeof(param), "%s%s%s%s%s", "app-layer.protocols.", - alproto, ".", ipproto, ".enabled"); + r = snprintf(param, sizeof(param), "%s%s%s%s%s", "app-layer.protocols.", alproto, ".", + ipproto, ".enabled"); if (r < 0) { FatalError("snprintf failure."); } else if (r > (int)sizeof(param)) { @@ -1949,9 +1873,9 @@ int AppLayerProtoDetectConfProtoDetectionEnabledDefault( SCLogError("Invalid value found for %s.", param); exit(EXIT_FAILURE); - disabled: +disabled: enabled = 0; - enabled: +enabled: SCReturnInt(enabled); } @@ -1976,8 +1900,7 @@ AppLayerProtoDetectThreadCtx *AppLayerProtoDetectGetCtxThread(void) max_pat_id = alpd_ctx.ctx_ipp[i].ctx_pm[j].max_pat_id; } else if (alpd_ctx.ctx_ipp[i].ctx_pm[j].max_pat_id && - max_pat_id < alpd_ctx.ctx_ipp[i].ctx_pm[j].max_pat_id) - { + max_pat_id < alpd_ctx.ctx_ipp[i].ctx_pm[j].max_pat_id) { max_pat_id = alpd_ctx.ctx_ipp[i].ctx_pm[j].max_pat_id; } } @@ -2005,11 +1928,11 @@ AppLayerProtoDetectThreadCtx *AppLayerProtoDetectGetCtxThread(void) } goto end; - error: +error: if (alpd_tctx != NULL) AppLayerProtoDetectDestroyCtxThread(alpd_tctx); alpd_tctx = NULL; - end: +end: SCReturnPtr(alpd_tctx, "AppLayerProtoDetectThreadCtx"); } @@ -2116,8 +2039,7 @@ void AppLayerProtoDetectSupportedAppProtocols(AppProto *alprotos) uint8_t expectation_proto[ALPROTO_MAX]; -static void AppLayerProtoDetectPEGetIpprotos(AppProto alproto, - uint8_t *ipprotos) +static void AppLayerProtoDetectPEGetIpprotos(AppProto alproto, uint8_t *ipprotos) { if (expectation_proto[alproto] == IPPROTO_TCP) { ipprotos[IPPROTO_TCP / 8] |= 1 << (IPPROTO_TCP % 8); @@ -2218,15 +2140,14 @@ static int AppLayerProtoDetectTest03(void) memset(&f, 0x00, sizeof(f)); f.protomap = FlowGetProtoMapping(IPPROTO_TCP); - const char *buf = "HTTP"; AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_HTTP1, buf, 4, 0, STREAM_TOCLIENT); buf = "220 "; AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_FTP, buf, 4, 0, STREAM_TOCLIENT); AppLayerProtoDetectPrepareState(); - /* AppLayerProtoDetectGetCtxThread() should be called post AppLayerProtoDetectPrepareState(), since - * it sets internal structures which depends on the above function. */ + /* AppLayerProtoDetectGetCtxThread() should be called post AppLayerProtoDetectPrepareState(), + * since it sets internal structures which depends on the above function. */ AppLayerProtoDetectThreadCtx *alpd_tctx = AppLayerProtoDetectGetCtxThread(); FAIL_IF_NULL(alpd_tctx); @@ -2238,10 +2159,8 @@ static int AppLayerProtoDetectTest03(void) FAIL_IF(alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map[1]->alproto != ALPROTO_HTTP1); bool rflow = false; - uint32_t cnt = AppLayerProtoDetectPMGetProto(alpd_tctx, - &f, l7data, sizeof(l7data), - STREAM_TOCLIENT, - pm_results, &rflow); + uint32_t cnt = AppLayerProtoDetectPMGetProto( + alpd_tctx, &f, l7data, sizeof(l7data), STREAM_TOCLIENT, pm_results, &rflow); FAIL_IF(cnt != 1); FAIL_IF(pm_results[0] != ALPROTO_HTTP1); @@ -2267,8 +2186,8 @@ static int AppLayerProtoDetectTest04(void) AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_HTTP1, buf, 13, 0, STREAM_TOCLIENT); AppLayerProtoDetectPrepareState(); - /* AppLayerProtoDetectGetCtxThread() should be called post AppLayerProtoDetectPrepareState(), since - * it sets internal structures which depends on the above function. */ + /* AppLayerProtoDetectGetCtxThread() should be called post AppLayerProtoDetectPrepareState(), + * since it sets internal structures which depends on the above function. */ AppLayerProtoDetectThreadCtx *alpd_tctx = AppLayerProtoDetectGetCtxThread(); FAIL_IF_NULL(alpd_tctx); @@ -2279,9 +2198,8 @@ static int AppLayerProtoDetectTest04(void) FAIL_IF(alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map[0]->alproto != ALPROTO_HTTP1); bool rdir = false; - uint32_t cnt = AppLayerProtoDetectPMGetProto(alpd_tctx, - &f, l7data, sizeof(l7data), STREAM_TOCLIENT, - pm_results, &rdir); + uint32_t cnt = AppLayerProtoDetectPMGetProto( + alpd_tctx, &f, l7data, sizeof(l7data), STREAM_TOCLIENT, pm_results, &rdir); FAIL_IF(cnt != 1); FAIL_IF(pm_results[0] != ALPROTO_HTTP1); @@ -2296,7 +2214,8 @@ static int AppLayerProtoDetectTest05(void) AppLayerProtoDetectUnittestCtxBackup(); AppLayerProtoDetectSetup(); - uint8_t l7data[] = "HTTP/1.1 200 OK\r\nServer: Apache/1.0\r\n\r\nBlahblah"; + uint8_t l7data[] = + "HTTP/1.1 200 OK\r\nServer: Apache/1.0\r\n\r\nBlahblah"; AppProto pm_results[ALPROTO_MAX]; memset(pm_results, 0, sizeof(pm_results)); Flow f; @@ -2309,8 +2228,8 @@ static int AppLayerProtoDetectTest05(void) AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_FTP, buf, 4, 0, STREAM_TOCLIENT); AppLayerProtoDetectPrepareState(); - /* AppLayerProtoDetectGetCtxThread() should be called post AppLayerProtoDetectPrepareState(), since - * it sets internal structures which depends on the above function. */ + /* AppLayerProtoDetectGetCtxThread() should be called post AppLayerProtoDetectPrepareState(), + * since it sets internal structures which depends on the above function. */ AppLayerProtoDetectThreadCtx *alpd_tctx = AppLayerProtoDetectGetCtxThread(); FAIL_IF_NULL(alpd_tctx); @@ -2322,10 +2241,8 @@ static int AppLayerProtoDetectTest05(void) FAIL_IF(alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map[1]->alproto != ALPROTO_HTTP1); bool rdir = false; - uint32_t cnt = AppLayerProtoDetectPMGetProto(alpd_tctx, - &f, l7data, sizeof(l7data), - STREAM_TOCLIENT, - pm_results, &rdir); + uint32_t cnt = AppLayerProtoDetectPMGetProto( + alpd_tctx, &f, l7data, sizeof(l7data), STREAM_TOCLIENT, pm_results, &rdir); FAIL_IF(cnt != 1); FAIL_IF(pm_results[0] != ALPROTO_HTTP1); @@ -2353,8 +2270,8 @@ static int AppLayerProtoDetectTest06(void) AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_FTP, buf, 4, 0, STREAM_TOCLIENT); AppLayerProtoDetectPrepareState(); - /* AppLayerProtoDetectGetCtxThread() should be called post AppLayerProtoDetectPrepareState(), since - * it sets internal structures which depends on the above function. */ + /* AppLayerProtoDetectGetCtxThread() should be called post AppLayerProtoDetectPrepareState(), + * since it sets internal structures which depends on the above function. */ AppLayerProtoDetectThreadCtx *alpd_tctx = AppLayerProtoDetectGetCtxThread(); FAIL_IF_NULL(alpd_tctx); @@ -2366,9 +2283,8 @@ static int AppLayerProtoDetectTest06(void) FAIL_IF(alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map[1]->alproto != ALPROTO_HTTP1); bool rdir = false; - uint32_t cnt = AppLayerProtoDetectPMGetProto(alpd_tctx, - &f, l7data, sizeof(l7data), STREAM_TOCLIENT, - pm_results, &rdir); + uint32_t cnt = AppLayerProtoDetectPMGetProto( + alpd_tctx, &f, l7data, sizeof(l7data), STREAM_TOCLIENT, pm_results, &rdir); FAIL_IF(cnt != 1); FAIL_IF(pm_results[0] != ALPROTO_FTP); @@ -2394,8 +2310,8 @@ static int AppLayerProtoDetectTest07(void) AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_HTTP1, buf, 4, 0, STREAM_TOCLIENT); AppLayerProtoDetectPrepareState(); - /* AppLayerProtoDetectGetCtxThread() should be called post AppLayerProtoDetectPrepareState(), since - * it sets internal structures which depends on the above function. */ + /* AppLayerProtoDetectGetCtxThread() should be called post AppLayerProtoDetectPrepareState(), + * since it sets internal structures which depends on the above function. */ AppLayerProtoDetectThreadCtx *alpd_tctx = AppLayerProtoDetectGetCtxThread(); FAIL_IF(alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].max_pat_id != 0); @@ -2405,9 +2321,8 @@ static int AppLayerProtoDetectTest07(void) FAIL_IF(alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map[0]->alproto != ALPROTO_HTTP1); bool rdir = false; - uint32_t cnt = AppLayerProtoDetectPMGetProto(alpd_tctx, - &f, l7data, sizeof(l7data), STREAM_TOCLIENT, - pm_results, &rdir); + uint32_t cnt = AppLayerProtoDetectPMGetProto( + alpd_tctx, &f, l7data, sizeof(l7data), STREAM_TOCLIENT, pm_results, &rdir); FAIL_IF(cnt != 0); AppLayerProtoDetectDestroyCtxThread(alpd_tctx); @@ -2453,8 +2368,8 @@ static int AppLayerProtoDetectTest08(void) AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_SMB, buf, 8, 4, STREAM_TOCLIENT); AppLayerProtoDetectPrepareState(); - /* AppLayerProtoDetectGetCtxThread() should be called post AppLayerProtoDetectPrepareState(), since - * it sets internal structures which depends on the above function. */ + /* AppLayerProtoDetectGetCtxThread() should be called post AppLayerProtoDetectPrepareState(), + * since it sets internal structures which depends on the above function. */ AppLayerProtoDetectThreadCtx *alpd_tctx = AppLayerProtoDetectGetCtxThread(); FAIL_IF_NULL(alpd_tctx); @@ -2465,9 +2380,8 @@ static int AppLayerProtoDetectTest08(void) FAIL_IF(alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map[0]->alproto != ALPROTO_SMB); bool rdir = false; - uint32_t cnt = AppLayerProtoDetectPMGetProto(alpd_tctx, - &f, l7data, sizeof(l7data), STREAM_TOCLIENT, - pm_results, &rdir); + uint32_t cnt = AppLayerProtoDetectPMGetProto( + alpd_tctx, &f, l7data, sizeof(l7data), STREAM_TOCLIENT, pm_results, &rdir); FAIL_IF(cnt != 1); FAIL_IF(pm_results[0] != ALPROTO_SMB); @@ -2510,8 +2424,8 @@ static int AppLayerProtoDetectTest09(void) AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_SMB, buf, 8, 4, STREAM_TOCLIENT); AppLayerProtoDetectPrepareState(); - /* AppLayerProtoDetectGetCtxThread() should be called post AppLayerProtoDetectPrepareState(), since - * it sets internal structures which depends on the above function. */ + /* AppLayerProtoDetectGetCtxThread() should be called post AppLayerProtoDetectPrepareState(), + * since it sets internal structures which depends on the above function. */ AppLayerProtoDetectThreadCtx *alpd_tctx = AppLayerProtoDetectGetCtxThread(); FAIL_IF_NULL(alpd_tctx); @@ -2522,9 +2436,8 @@ static int AppLayerProtoDetectTest09(void) FAIL_IF(alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map[0]->alproto != ALPROTO_SMB); bool rdir = false; - uint32_t cnt = AppLayerProtoDetectPMGetProto(alpd_tctx, - &f, l7data, sizeof(l7data), STREAM_TOCLIENT, - pm_results, &rdir); + uint32_t cnt = AppLayerProtoDetectPMGetProto( + alpd_tctx, &f, l7data, sizeof(l7data), STREAM_TOCLIENT, pm_results, &rdir); FAIL_IF(cnt != 1); FAIL_IF(pm_results[0] != ALPROTO_SMB); @@ -2562,8 +2475,8 @@ static int AppLayerProtoDetectTest10(void) AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_DCERPC, buf, 4, 0, STREAM_TOCLIENT); AppLayerProtoDetectPrepareState(); - /* AppLayerProtoDetectGetCtxThread() should be called post AppLayerProtoDetectPrepareState(), since - * it sets internal structures which depends on the above function. */ + /* AppLayerProtoDetectGetCtxThread() should be called post AppLayerProtoDetectPrepareState(), + * since it sets internal structures which depends on the above function. */ AppLayerProtoDetectThreadCtx *alpd_tctx = AppLayerProtoDetectGetCtxThread(); FAIL_IF_NULL(alpd_tctx); @@ -2574,9 +2487,8 @@ static int AppLayerProtoDetectTest10(void) FAIL_IF(alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map[0]->alproto != ALPROTO_DCERPC); bool rdir = false; - uint32_t cnt = AppLayerProtoDetectPMGetProto(alpd_tctx, - &f, l7data, sizeof(l7data), STREAM_TOCLIENT, - pm_results, &rdir); + uint32_t cnt = AppLayerProtoDetectPMGetProto( + alpd_tctx, &f, l7data, sizeof(l7data), STREAM_TOCLIENT, pm_results, &rdir); FAIL_IF(cnt != 1); FAIL_IF(pm_results[0] != ALPROTO_DCERPC); @@ -2621,8 +2533,8 @@ static int AppLayerProtoDetectTest11(void) IPPROTO_TCP, ALPROTO_HTTP1, "HTTP", 4, 0, STREAM_TOCLIENT); AppLayerProtoDetectPrepareState(); - /* AppLayerProtoDetectGetCtxThread() should be called post AppLayerProtoDetectPrepareState(), since - * it sets internal structures which depends on the above function. */ + /* AppLayerProtoDetectGetCtxThread() should be called post AppLayerProtoDetectPrepareState(), + * since it sets internal structures which depends on the above function. */ AppLayerProtoDetectThreadCtx *alpd_tctx = AppLayerProtoDetectGetCtxThread(); FAIL_IF_NULL(alpd_tctx); @@ -2641,16 +2553,14 @@ static int AppLayerProtoDetectTest11(void) FAIL_IF(alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map[0]->alproto != ALPROTO_HTTP1); bool rdir = false; - uint32_t cnt = AppLayerProtoDetectPMGetProto(alpd_tctx, - &f, l7data, sizeof(l7data), STREAM_TOSERVER, - pm_results, &rdir); + uint32_t cnt = AppLayerProtoDetectPMGetProto( + alpd_tctx, &f, l7data, sizeof(l7data), STREAM_TOSERVER, pm_results, &rdir); FAIL_IF(cnt != 1); FAIL_IF(pm_results[0] != ALPROTO_HTTP1); memset(pm_results, 0, sizeof(pm_results)); - cnt = AppLayerProtoDetectPMGetProto(alpd_tctx, - &f, l7data_resp, sizeof(l7data_resp), STREAM_TOCLIENT, - pm_results, &rdir); + cnt = AppLayerProtoDetectPMGetProto( + alpd_tctx, &f, l7data_resp, sizeof(l7data_resp), STREAM_TOCLIENT, pm_results, &rdir); FAIL_IF(cnt != 1); FAIL_IF(pm_results[0] != ALPROTO_HTTP1); @@ -2673,8 +2583,7 @@ static int AppLayerProtoDetectTest12(void) AppLayerProtoDetectPMRegisterPatternCS( IPPROTO_TCP, ALPROTO_HTTP1, "HTTP", 4, 0, STREAM_TOSERVER); if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].head == NULL || - alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].map != NULL) - { + alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].map != NULL) { printf("failure 1\n"); goto end; } @@ -2685,8 +2594,7 @@ static int AppLayerProtoDetectTest12(void) goto end; } if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].head != NULL || - alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].map == NULL) - { + alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].map == NULL) { printf("failure 3\n"); goto end; } @@ -2705,7 +2613,7 @@ static int AppLayerProtoDetectTest12(void) r = 1; - end: +end: AppLayerProtoDetectDeSetup(); AppLayerProtoDetectUnittestCtxRestore(); return r; @@ -2746,8 +2654,8 @@ static int AppLayerProtoDetectTest13(void) IPPROTO_UDP, ALPROTO_HTTP1, "HTTP", 4, 0, STREAM_TOCLIENT); AppLayerProtoDetectPrepareState(); - /* AppLayerProtoDetectGetCtxThread() should be called post AppLayerProtoDetectPrepareState(), since - * it sets internal structures which depends on the above function. */ + /* AppLayerProtoDetectGetCtxThread() should be called post AppLayerProtoDetectPrepareState(), + * since it sets internal structures which depends on the above function. */ AppLayerProtoDetectThreadCtx *alpd_tctx = AppLayerProtoDetectGetCtxThread(); FAIL_IF(alpd_ctx.ctx_ipp[FLOW_PROTO_UDP].ctx_pm[0].max_pat_id != 7); @@ -2764,15 +2672,13 @@ static int AppLayerProtoDetectTest13(void) memset(pm_results, 0, sizeof(pm_results)); bool rdir = false; - uint32_t cnt = AppLayerProtoDetectPMGetProto(alpd_tctx, - &f, l7data, sizeof(l7data), STREAM_TOSERVER, - pm_results, &rdir); + uint32_t cnt = AppLayerProtoDetectPMGetProto( + alpd_tctx, &f, l7data, sizeof(l7data), STREAM_TOSERVER, pm_results, &rdir); FAIL_IF(cnt != 0); memset(pm_results, 0, sizeof(pm_results)); - cnt = AppLayerProtoDetectPMGetProto(alpd_tctx, - &f, l7data_resp, sizeof(l7data_resp), STREAM_TOCLIENT, - pm_results, &rdir); + cnt = AppLayerProtoDetectPMGetProto( + alpd_tctx, &f, l7data_resp, sizeof(l7data_resp), STREAM_TOCLIENT, pm_results, &rdir); FAIL_IF(cnt != 0); AppLayerProtoDetectDestroyCtxThread(alpd_tctx); @@ -2817,8 +2723,8 @@ static int AppLayerProtoDetectTest14(void) IPPROTO_UDP, ALPROTO_HTTP1, "HTTP", 4, 0, STREAM_TOCLIENT); AppLayerProtoDetectPrepareState(); - /* AppLayerProtoDetectGetCtxThread() should be called post AppLayerProtoDetectPrepareState(), since - * it sets internal structures which depends on the above function. */ + /* AppLayerProtoDetectGetCtxThread() should be called post AppLayerProtoDetectPrepareState(), + * since it sets internal structures which depends on the above function. */ AppLayerProtoDetectThreadCtx *alpd_tctx = AppLayerProtoDetectGetCtxThread(); FAIL_IF_NULL(alpd_tctx); @@ -2836,16 +2742,14 @@ static int AppLayerProtoDetectTest14(void) memset(pm_results, 0, sizeof(pm_results)); bool rdir = false; - cnt = AppLayerProtoDetectPMGetProto(alpd_tctx, - &f, l7data, sizeof(l7data), STREAM_TOSERVER, - pm_results, &rdir); + cnt = AppLayerProtoDetectPMGetProto( + alpd_tctx, &f, l7data, sizeof(l7data), STREAM_TOSERVER, pm_results, &rdir); FAIL_IF(cnt != 1); FAIL_IF(pm_results[0] != ALPROTO_HTTP1); memset(pm_results, 0, sizeof(pm_results)); - cnt = AppLayerProtoDetectPMGetProto(alpd_tctx, - &f, l7data_resp, sizeof(l7data_resp), STREAM_TOCLIENT, - pm_results, &rdir); + cnt = AppLayerProtoDetectPMGetProto( + alpd_tctx, &f, l7data_resp, sizeof(l7data_resp), STREAM_TOCLIENT, pm_results, &rdir); FAIL_IF(cnt != 1); FAIL_IF(pm_results[0] != ALPROTO_HTTP1); @@ -2876,7 +2780,6 @@ typedef struct AppLayerProtoDetectPPTestDataPort_ { int tc_no_of_element; } AppLayerProtoDetectPPTestDataPort; - typedef struct AppLayerProtoDetectPPTestDataIPProto_ { uint8_t ipproto; @@ -2885,11 +2788,10 @@ typedef struct AppLayerProtoDetectPPTestDataIPProto_ { } AppLayerProtoDetectPPTestDataIPProto; static int AppLayerProtoDetectPPTestData(AppLayerProtoDetectProbingParser *pp, - AppLayerProtoDetectPPTestDataIPProto *ip_proto, - int no_of_ip_proto) + AppLayerProtoDetectPPTestDataIPProto *ip_proto, int no_of_ip_proto) { int result = 0; - int i = -1, j = -1 , k = -1; + int i = -1, j = -1, k = -1; #ifdef DEBUG int dir = 0; #endif @@ -2914,8 +2816,8 @@ static int AppLayerProtoDetectPPTestData(AppLayerProtoDetectProbingParser *pp, #ifdef DEBUG dir = 0; #endif - for (j = 0 ; j < ip_proto[i].port[k].ts_no_of_element; - j++, pp_element = pp_element->next) { + for (j = 0; j < ip_proto[i].port[k].ts_no_of_element; + j++, pp_element = pp_element->next) { if (pp_element->alproto != ip_proto[i].port[k].toserver_element[j].alproto) { goto end; @@ -2923,7 +2825,8 @@ static int AppLayerProtoDetectPPTestData(AppLayerProtoDetectProbingParser *pp, if (pp_element->port != ip_proto[i].port[k].toserver_element[j].port) { goto end; } - if (pp_element->alproto_mask != ip_proto[i].port[k].toserver_element[j].alproto_mask) { + if (pp_element->alproto_mask != + ip_proto[i].port[k].toserver_element[j].alproto_mask) { goto end; } if (pp_element->min_depth != ip_proto[i].port[k].toserver_element[j].min_depth) { @@ -2940,14 +2843,16 @@ static int AppLayerProtoDetectPPTestData(AppLayerProtoDetectProbingParser *pp, #ifdef DEBUG dir = 1; #endif - for (j = 0 ; j < ip_proto[i].port[k].tc_no_of_element; j++, pp_element = pp_element->next) { + for (j = 0; j < ip_proto[i].port[k].tc_no_of_element; + j++, pp_element = pp_element->next) { if (pp_element->alproto != ip_proto[i].port[k].toclient_element[j].alproto) { goto end; } if (pp_element->port != ip_proto[i].port[k].toclient_element[j].port) { goto end; } - if (pp_element->alproto_mask != ip_proto[i].port[k].toclient_element[j].alproto_mask) { + if (pp_element->alproto_mask != + ip_proto[i].port[k].toclient_element[j].alproto_mask) { goto end; } if (pp_element->min_depth != ip_proto[i].port[k].toclient_element[j].min_depth) { @@ -2967,16 +2872,15 @@ static int AppLayerProtoDetectPPTestData(AppLayerProtoDetectProbingParser *pp, goto end; result = 1; - end: +end: #ifdef DEBUG printf("i = %d, k = %d, j = %d(%s)\n", i, k, j, (dir == 0) ? "ts" : "tc"); #endif return result; } -static uint16_t ProbingParserDummyForTesting(Flow *f, uint8_t direction, - const uint8_t *input, - uint32_t input_len, uint8_t *rdir) +static uint16_t ProbingParserDummyForTesting( + Flow *f, uint8_t direction, const uint8_t *input, uint32_t input_len, uint8_t *rdir) { return 0; } @@ -2990,135 +2894,55 @@ static int AppLayerProtoDetectTest15(void) AppLayerProtoDetectPPRegister(IPPROTO_TCP, "80", ALPROTO_HTTP1, 5, 8, STREAM_TOSERVER, ProbingParserDummyForTesting, NULL); - AppLayerProtoDetectPPRegister(IPPROTO_TCP, - "80", - ALPROTO_SMB, - 5, 6, - STREAM_TOSERVER, - ProbingParserDummyForTesting, NULL); - AppLayerProtoDetectPPRegister(IPPROTO_TCP, - "80", - ALPROTO_FTP, - 7, 10, - STREAM_TOSERVER, - ProbingParserDummyForTesting, NULL); - - AppLayerProtoDetectPPRegister(IPPROTO_TCP, - "81", - ALPROTO_DCERPC, - 9, 10, - STREAM_TOSERVER, - ProbingParserDummyForTesting, NULL); - AppLayerProtoDetectPPRegister(IPPROTO_TCP, - "81", - ALPROTO_FTP, - 7, 15, - STREAM_TOSERVER, - ProbingParserDummyForTesting, NULL); - AppLayerProtoDetectPPRegister(IPPROTO_TCP, - "0", - ALPROTO_SMTP, - 12, 0, - STREAM_TOSERVER, - ProbingParserDummyForTesting, NULL); - AppLayerProtoDetectPPRegister(IPPROTO_TCP, - "0", - ALPROTO_TLS, - 12, 18, - STREAM_TOSERVER, - ProbingParserDummyForTesting, NULL); - - AppLayerProtoDetectPPRegister(IPPROTO_TCP, - "85", - ALPROTO_DCERPC, - 9, 10, - STREAM_TOSERVER, - ProbingParserDummyForTesting, NULL); - AppLayerProtoDetectPPRegister(IPPROTO_TCP, - "85", - ALPROTO_FTP, - 7, 15, - STREAM_TOSERVER, - ProbingParserDummyForTesting, NULL); + AppLayerProtoDetectPPRegister(IPPROTO_TCP, "80", ALPROTO_SMB, 5, 6, STREAM_TOSERVER, + ProbingParserDummyForTesting, NULL); + AppLayerProtoDetectPPRegister(IPPROTO_TCP, "80", ALPROTO_FTP, 7, 10, STREAM_TOSERVER, + ProbingParserDummyForTesting, NULL); + + AppLayerProtoDetectPPRegister(IPPROTO_TCP, "81", ALPROTO_DCERPC, 9, 10, STREAM_TOSERVER, + ProbingParserDummyForTesting, NULL); + AppLayerProtoDetectPPRegister(IPPROTO_TCP, "81", ALPROTO_FTP, 7, 15, STREAM_TOSERVER, + ProbingParserDummyForTesting, NULL); + AppLayerProtoDetectPPRegister(IPPROTO_TCP, "0", ALPROTO_SMTP, 12, 0, STREAM_TOSERVER, + ProbingParserDummyForTesting, NULL); + AppLayerProtoDetectPPRegister(IPPROTO_TCP, "0", ALPROTO_TLS, 12, 18, STREAM_TOSERVER, + ProbingParserDummyForTesting, NULL); + + AppLayerProtoDetectPPRegister(IPPROTO_TCP, "85", ALPROTO_DCERPC, 9, 10, STREAM_TOSERVER, + ProbingParserDummyForTesting, NULL); + AppLayerProtoDetectPPRegister(IPPROTO_TCP, "85", ALPROTO_FTP, 7, 15, STREAM_TOSERVER, + ProbingParserDummyForTesting, NULL); result = 1; - AppLayerProtoDetectPPRegister(IPPROTO_UDP, - "85", - ALPROTO_IMAP, - 12, 23, - STREAM_TOSERVER, - ProbingParserDummyForTesting, NULL); + AppLayerProtoDetectPPRegister(IPPROTO_UDP, "85", ALPROTO_IMAP, 12, 23, STREAM_TOSERVER, + ProbingParserDummyForTesting, NULL); /* toclient */ - AppLayerProtoDetectPPRegister(IPPROTO_TCP, - "0", - ALPROTO_JABBER, - 12, 23, - STREAM_TOCLIENT, - ProbingParserDummyForTesting, NULL); - AppLayerProtoDetectPPRegister(IPPROTO_TCP, - "0", - ALPROTO_IRC, - 12, 14, - STREAM_TOCLIENT, - ProbingParserDummyForTesting, NULL); - - AppLayerProtoDetectPPRegister(IPPROTO_TCP, - "85", - ALPROTO_DCERPC, - 9, 10, - STREAM_TOCLIENT, - ProbingParserDummyForTesting, NULL); - AppLayerProtoDetectPPRegister(IPPROTO_TCP, - "81", - ALPROTO_FTP, - 7, 15, - STREAM_TOCLIENT, - ProbingParserDummyForTesting, NULL); - AppLayerProtoDetectPPRegister(IPPROTO_TCP, - "0", - ALPROTO_TLS, - 12, 18, - STREAM_TOCLIENT, - ProbingParserDummyForTesting, NULL); + AppLayerProtoDetectPPRegister(IPPROTO_TCP, "0", ALPROTO_JABBER, 12, 23, STREAM_TOCLIENT, + ProbingParserDummyForTesting, NULL); + AppLayerProtoDetectPPRegister(IPPROTO_TCP, "0", ALPROTO_IRC, 12, 14, STREAM_TOCLIENT, + ProbingParserDummyForTesting, NULL); + + AppLayerProtoDetectPPRegister(IPPROTO_TCP, "85", ALPROTO_DCERPC, 9, 10, STREAM_TOCLIENT, + ProbingParserDummyForTesting, NULL); + AppLayerProtoDetectPPRegister(IPPROTO_TCP, "81", ALPROTO_FTP, 7, 15, STREAM_TOCLIENT, + ProbingParserDummyForTesting, NULL); + AppLayerProtoDetectPPRegister(IPPROTO_TCP, "0", ALPROTO_TLS, 12, 18, STREAM_TOCLIENT, + ProbingParserDummyForTesting, NULL); AppLayerProtoDetectPPRegister(IPPROTO_TCP, "80", ALPROTO_HTTP1, 5, 8, STREAM_TOCLIENT, ProbingParserDummyForTesting, NULL); - AppLayerProtoDetectPPRegister(IPPROTO_TCP, - "81", - ALPROTO_DCERPC, - 9, 10, - STREAM_TOCLIENT, - ProbingParserDummyForTesting, NULL); - AppLayerProtoDetectPPRegister(IPPROTO_TCP, - "90", - ALPROTO_FTP, - 7, 15, - STREAM_TOCLIENT, - ProbingParserDummyForTesting, NULL); - AppLayerProtoDetectPPRegister(IPPROTO_TCP, - "80", - ALPROTO_SMB, - 5, 6, - STREAM_TOCLIENT, - ProbingParserDummyForTesting, NULL); - AppLayerProtoDetectPPRegister(IPPROTO_UDP, - "85", - ALPROTO_IMAP, - 12, 23, - STREAM_TOCLIENT, - ProbingParserDummyForTesting, NULL); - AppLayerProtoDetectPPRegister(IPPROTO_TCP, - "0", - ALPROTO_SMTP, - 12, 17, - STREAM_TOCLIENT, - ProbingParserDummyForTesting, NULL); - AppLayerProtoDetectPPRegister(IPPROTO_TCP, - "80", - ALPROTO_FTP, - 7, 10, - STREAM_TOCLIENT, - ProbingParserDummyForTesting, NULL); + AppLayerProtoDetectPPRegister(IPPROTO_TCP, "81", ALPROTO_DCERPC, 9, 10, STREAM_TOCLIENT, + ProbingParserDummyForTesting, NULL); + AppLayerProtoDetectPPRegister(IPPROTO_TCP, "90", ALPROTO_FTP, 7, 15, STREAM_TOCLIENT, + ProbingParserDummyForTesting, NULL); + AppLayerProtoDetectPPRegister(IPPROTO_TCP, "80", ALPROTO_SMB, 5, 6, STREAM_TOCLIENT, + ProbingParserDummyForTesting, NULL); + AppLayerProtoDetectPPRegister(IPPROTO_UDP, "85", ALPROTO_IMAP, 12, 23, STREAM_TOCLIENT, + ProbingParserDummyForTesting, NULL); + AppLayerProtoDetectPPRegister(IPPROTO_TCP, "0", ALPROTO_SMTP, 12, 17, STREAM_TOCLIENT, + ProbingParserDummyForTesting, NULL); + AppLayerProtoDetectPPRegister(IPPROTO_TCP, "80", ALPROTO_FTP, 7, 10, STREAM_TOCLIENT, + ProbingParserDummyForTesting, NULL); AppLayerProtoDetectPPTestDataElement element_ts_80[] = { { "http", ALPROTO_HTTP1, 80, 1 << ALPROTO_HTTP1, 5, 8 }, @@ -3140,71 +2964,66 @@ static int AppLayerProtoDetectTest15(void) AppLayerProtoDetectPPTestDataElement element_ts_81[] = { { "dcerpc", ALPROTO_DCERPC, 81, 1 << ALPROTO_DCERPC, 9, 10 }, - { "ftp", ALPROTO_FTP, 81, 1 << ALPROTO_FTP, 7, 15 }, - { "smtp", ALPROTO_SMTP, 0, 1 << ALPROTO_SMTP, 12, 0 }, - { "tls", ALPROTO_TLS, 0, 1 << ALPROTO_TLS, 12, 18 }, - { "irc", ALPROTO_IRC, 0, 1 << ALPROTO_IRC, 12, 25 }, - { "jabber", ALPROTO_JABBER, 0, 1 << ALPROTO_JABBER, 12, 23 }, - }; - AppLayerProtoDetectPPTestDataElement element_tc_81[] = { { "ftp", ALPROTO_FTP, 81, 1 << ALPROTO_FTP, 7, 15 }, - { "dcerpc", ALPROTO_DCERPC, 81, 1 << ALPROTO_DCERPC, 9, 10 }, - { "jabber", ALPROTO_JABBER, 0, 1 << ALPROTO_JABBER, 12, 23 }, - { "irc", ALPROTO_IRC, 0, 1 << ALPROTO_IRC, 12, 14 }, - { "tls", ALPROTO_TLS, 0, 1 << ALPROTO_TLS, 12, 18 }, - { "smtp", ALPROTO_SMTP, 0, 1 << ALPROTO_SMTP, 12, 17 } - }; + { "smtp", ALPROTO_SMTP, 0, 1 << ALPROTO_SMTP, 12, 0 }, + { "tls", ALPROTO_TLS, 0, 1 << ALPROTO_TLS, 12, 18 }, + { "irc", ALPROTO_IRC, 0, 1 << ALPROTO_IRC, 12, 25 }, + { "jabber", ALPROTO_JABBER, 0, 1 << ALPROTO_JABBER, 12, 23 }, + }; + AppLayerProtoDetectPPTestDataElement element_tc_81[] = { { "ftp", ALPROTO_FTP, 81, + 1 << ALPROTO_FTP, 7, 15 }, + { "dcerpc", ALPROTO_DCERPC, 81, 1 << ALPROTO_DCERPC, 9, 10 }, + { "jabber", ALPROTO_JABBER, 0, 1 << ALPROTO_JABBER, 12, 23 }, + { "irc", ALPROTO_IRC, 0, 1 << ALPROTO_IRC, 12, 14 }, + { "tls", ALPROTO_TLS, 0, 1 << ALPROTO_TLS, 12, 18 }, + { "smtp", ALPROTO_SMTP, 0, 1 << ALPROTO_SMTP, 12, 17 } }; AppLayerProtoDetectPPTestDataElement element_ts_85[] = { { "dcerpc", ALPROTO_DCERPC, 85, 1 << ALPROTO_DCERPC, 9, 10 }, - { "ftp", ALPROTO_FTP, 85, 1 << ALPROTO_FTP, 7, 15 }, - { "smtp", ALPROTO_SMTP, 0, 1 << ALPROTO_SMTP, 12, 0 }, - { "tls", ALPROTO_TLS, 0, 1 << ALPROTO_TLS, 12, 18 }, - { "irc", ALPROTO_IRC, 0, 1 << ALPROTO_IRC, 12, 25 }, - { "jabber", ALPROTO_JABBER, 0, 1 << ALPROTO_JABBER, 12, 23 }, - }; - AppLayerProtoDetectPPTestDataElement element_tc_85[] = { - { "dcerpc", ALPROTO_DCERPC, 85, 1 << ALPROTO_DCERPC, 9, 10 }, - { "jabber", ALPROTO_JABBER, 0, 1 << ALPROTO_JABBER, 12, 23 }, - { "irc", ALPROTO_IRC, 0, 1 << ALPROTO_IRC, 12, 14 }, - { "tls", ALPROTO_TLS, 0, 1 << ALPROTO_TLS, 12, 18 }, - { "smtp", ALPROTO_SMTP, 0, 1 << ALPROTO_SMTP, 12, 17 } - }; + { "ftp", ALPROTO_FTP, 85, 1 << ALPROTO_FTP, 7, 15 }, + { "smtp", ALPROTO_SMTP, 0, 1 << ALPROTO_SMTP, 12, 0 }, + { "tls", ALPROTO_TLS, 0, 1 << ALPROTO_TLS, 12, 18 }, + { "irc", ALPROTO_IRC, 0, 1 << ALPROTO_IRC, 12, 25 }, + { "jabber", ALPROTO_JABBER, 0, 1 << ALPROTO_JABBER, 12, 23 }, + }; + AppLayerProtoDetectPPTestDataElement element_tc_85[] = { { "dcerpc", ALPROTO_DCERPC, 85, + 1 << ALPROTO_DCERPC, 9, 10 }, + { "jabber", ALPROTO_JABBER, 0, 1 << ALPROTO_JABBER, 12, 23 }, + { "irc", ALPROTO_IRC, 0, 1 << ALPROTO_IRC, 12, 14 }, + { "tls", ALPROTO_TLS, 0, 1 << ALPROTO_TLS, 12, 18 }, + { "smtp", ALPROTO_SMTP, 0, 1 << ALPROTO_SMTP, 12, 17 } }; AppLayerProtoDetectPPTestDataElement element_ts_90[] = { { "smtp", ALPROTO_SMTP, 0, 1 << ALPROTO_SMTP, 12, 0 }, - { "tls", ALPROTO_TLS, 0, 1 << ALPROTO_TLS, 12, 18 }, - { "irc", ALPROTO_IRC, 0, 1 << ALPROTO_IRC, 12, 25 }, - { "jabber", ALPROTO_JABBER, 0, 1 << ALPROTO_JABBER, 12, 23 }, - }; - AppLayerProtoDetectPPTestDataElement element_tc_90[] = { - { "ftp", ALPROTO_FTP, 90, 1 << ALPROTO_FTP, 7, 15 }, - { "jabber", ALPROTO_JABBER, 0, 1 << ALPROTO_JABBER, 12, 23 }, - { "irc", ALPROTO_IRC, 0, 1 << ALPROTO_IRC, 12, 14 }, - { "tls", ALPROTO_TLS, 0, 1 << ALPROTO_TLS, 12, 18 }, - { "smtp", ALPROTO_SMTP, 0, 1 << ALPROTO_SMTP, 12, 17 } - }; + { "tls", ALPROTO_TLS, 0, 1 << ALPROTO_TLS, 12, 18 }, + { "irc", ALPROTO_IRC, 0, 1 << ALPROTO_IRC, 12, 25 }, + { "jabber", ALPROTO_JABBER, 0, 1 << ALPROTO_JABBER, 12, 23 }, + }; + AppLayerProtoDetectPPTestDataElement element_tc_90[] = { { "ftp", ALPROTO_FTP, 90, + 1 << ALPROTO_FTP, 7, 15 }, + { "jabber", ALPROTO_JABBER, 0, 1 << ALPROTO_JABBER, 12, 23 }, + { "irc", ALPROTO_IRC, 0, 1 << ALPROTO_IRC, 12, 14 }, + { "tls", ALPROTO_TLS, 0, 1 << ALPROTO_TLS, 12, 18 }, + { "smtp", ALPROTO_SMTP, 0, 1 << ALPROTO_SMTP, 12, 17 } }; AppLayerProtoDetectPPTestDataElement element_ts_0[] = { { "smtp", ALPROTO_SMTP, 0, 1 << ALPROTO_SMTP, 12, 0 }, - { "tls", ALPROTO_TLS, 0, 1 << ALPROTO_TLS, 12, 18 }, - { "irc", ALPROTO_IRC, 0, 1 << ALPROTO_IRC, 12, 25 }, - { "jabber", ALPROTO_JABBER, 0, 1 << ALPROTO_JABBER, 12, 23 }, - }; - AppLayerProtoDetectPPTestDataElement element_tc_0[] = { + { "tls", ALPROTO_TLS, 0, 1 << ALPROTO_TLS, 12, 18 }, + { "irc", ALPROTO_IRC, 0, 1 << ALPROTO_IRC, 12, 25 }, { "jabber", ALPROTO_JABBER, 0, 1 << ALPROTO_JABBER, 12, 23 }, - { "irc", ALPROTO_IRC, 0, 1 << ALPROTO_IRC, 12, 14 }, - { "tls", ALPROTO_TLS, 0, 1 << ALPROTO_TLS, 12, 18 }, - { "smtp", ALPROTO_SMTP, 0, 1 << ALPROTO_SMTP, 12, 17 } - }; - + }; + AppLayerProtoDetectPPTestDataElement element_tc_0[] = { { "jabber", ALPROTO_JABBER, 0, + 1 << ALPROTO_JABBER, 12, 23 }, + { "irc", ALPROTO_IRC, 0, 1 << ALPROTO_IRC, 12, 14 }, + { "tls", ALPROTO_TLS, 0, 1 << ALPROTO_TLS, 12, 18 }, + { "smtp", ALPROTO_SMTP, 0, 1 << ALPROTO_SMTP, 12, 17 } }; AppLayerProtoDetectPPTestDataElement element_ts_85_udp[] = { { "imap", ALPROTO_IMAP, 85, 1 << ALPROTO_IMAP, 12, 23 }, - }; + }; AppLayerProtoDetectPPTestDataElement element_tc_85_udp[] = { { "imap", ALPROTO_IMAP, 85, 1 << ALPROTO_IMAP, 12, 23 }, - }; + }; AppLayerProtoDetectPPTestDataPort ports_tcp[] = { { @@ -3260,41 +3079,43 @@ static int AppLayerProtoDetectTest15(void) }; AppLayerProtoDetectPPTestDataPort ports_udp[] = { - { 85, - (1 << ALPROTO_IMAP), - (1 << ALPROTO_IMAP), - 23, - element_ts_85_udp, element_tc_85_udp, - sizeof(element_ts_85_udp) / sizeof(AppLayerProtoDetectPPTestDataElement), - sizeof(element_tc_85_udp) / sizeof(AppLayerProtoDetectPPTestDataElement), - }, - }; + { + 85, + (1 << ALPROTO_IMAP), + (1 << ALPROTO_IMAP), + 23, + element_ts_85_udp, + element_tc_85_udp, + sizeof(element_ts_85_udp) / sizeof(AppLayerProtoDetectPPTestDataElement), + sizeof(element_tc_85_udp) / sizeof(AppLayerProtoDetectPPTestDataElement), + }, + }; AppLayerProtoDetectPPTestDataIPProto ip_proto[] = { - { IPPROTO_TCP, - ports_tcp, - sizeof(ports_tcp) / sizeof(AppLayerProtoDetectPPTestDataPort), + { + IPPROTO_TCP, + ports_tcp, + sizeof(ports_tcp) / sizeof(AppLayerProtoDetectPPTestDataPort), }, - { IPPROTO_UDP, - ports_udp, - sizeof(ports_udp) / sizeof(AppLayerProtoDetectPPTestDataPort), + { + IPPROTO_UDP, + ports_udp, + sizeof(ports_udp) / sizeof(AppLayerProtoDetectPPTestDataPort), }, }; - if (AppLayerProtoDetectPPTestData(alpd_ctx.ctx_pp, ip_proto, - sizeof(ip_proto) / sizeof(AppLayerProtoDetectPPTestDataIPProto)) == 0) { + sizeof(ip_proto) / sizeof(AppLayerProtoDetectPPTestDataIPProto)) == 0) { goto end; } result = 1; - end: +end: AppLayerProtoDetectDeSetup(); AppLayerProtoDetectUnittestCtxRestore(); return result; } - /** \test test if the engine detect the proto and match with it */ static int AppLayerProtoDetectTest16(void) { @@ -3302,8 +3123,8 @@ static int AppLayerProtoDetectTest16(void) Flow *f = NULL; HtpState *http_state = NULL; uint8_t http_buf1[] = "POST /one HTTP/1.0\r\n" - "User-Agent: Mozilla/1.0\r\n" - "Cookie: hellocatch\r\n\r\n"; + "User-Agent: Mozilla/1.0\r\n" + "Cookie: hellocatch\r\n\r\n"; uint32_t http_buf1_len = sizeof(http_buf1) - 1; TcpSession ssn; Packet *p = NULL; @@ -3333,7 +3154,7 @@ static int AppLayerProtoDetectTest16(void) p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f->alproto = ALPROTO_HTTP1; @@ -3346,8 +3167,8 @@ static int AppLayerProtoDetectTest16(void) de_ctx->flags |= DE_QUIET; s = de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " - "(msg:\"Test content option\"; " - "sid:1;)"); + "(msg:\"Test content option\"; " + "sid:1;)"); if (s == NULL) { goto end; } @@ -3376,7 +3197,7 @@ static int AppLayerProtoDetectTest16(void) goto end; } result = 1; - end: +end: if (alp_tctx != NULL) AppLayerParserThreadCtxFree(alp_tctx); if (det_ctx != NULL) @@ -3401,8 +3222,8 @@ static int AppLayerProtoDetectTest17(void) Flow *f = NULL; HtpState *http_state = NULL; uint8_t http_buf1[] = "POST /one HTTP/1.0\r\n" - "User-Agent: Mozilla/1.0\r\n" - "Cookie: hellocatch\r\n\r\n"; + "User-Agent: Mozilla/1.0\r\n" + "Cookie: hellocatch\r\n\r\n"; uint32_t http_buf1_len = sizeof(http_buf1) - 1; TcpSession ssn; Packet *p = NULL; @@ -3425,7 +3246,7 @@ static int AppLayerProtoDetectTest17(void) p->flow = f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f->alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -3437,8 +3258,8 @@ static int AppLayerProtoDetectTest17(void) de_ctx->flags |= DE_QUIET; s = de_ctx->sig_list = SigInit(de_ctx, "alert http any !80 -> any any " - "(msg:\"http over non standar port\"; " - "sid:1;)"); + "(msg:\"http over non standar port\"; " + "sid:1;)"); if (s == NULL) { goto end; } @@ -3469,7 +3290,7 @@ static int AppLayerProtoDetectTest17(void) result = 1; - end: +end: if (alp_tctx != NULL) AppLayerParserThreadCtxFree(alp_tctx); if (det_ctx != NULL) @@ -3494,8 +3315,8 @@ static int AppLayerProtoDetectTest18(void) Flow *f = NULL; HtpState *http_state = NULL; uint8_t http_buf1[] = "POST /one HTTP/1.0\r\n" - "User-Agent: Mozilla/1.0\r\n" - "Cookie: hellocatch\r\n\r\n"; + "User-Agent: Mozilla/1.0\r\n" + "Cookie: hellocatch\r\n\r\n"; uint32_t http_buf1_len = sizeof(http_buf1) - 1; TcpSession ssn; Packet *p = NULL; @@ -3518,7 +3339,7 @@ static int AppLayerProtoDetectTest18(void) p->flow = f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f->alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -3530,8 +3351,8 @@ static int AppLayerProtoDetectTest18(void) de_ctx->flags |= DE_QUIET; s = de_ctx->sig_list = SigInit(de_ctx, "alert ftp any any -> any any " - "(msg:\"Test content option\"; " - "sid:1;)"); + "(msg:\"Test content option\"; " + "sid:1;)"); if (s == NULL) { goto end; } @@ -3561,7 +3382,7 @@ static int AppLayerProtoDetectTest18(void) } result = 1; - end: +end: if (alp_tctx != NULL) AppLayerParserThreadCtxFree(alp_tctx); if (det_ctx != NULL) @@ -3607,7 +3428,7 @@ static int AppLayerProtoDetectTest19(void) p->flow = f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f->alproto = ALPROTO_FTP; StreamTcpInitConfig(true); @@ -3619,8 +3440,8 @@ static int AppLayerProtoDetectTest19(void) de_ctx->flags |= DE_QUIET; s = de_ctx->sig_list = SigInit(de_ctx, "alert http any !80 -> any any " - "(msg:\"http over non standar port\"; " - "sid:1;)"); + "(msg:\"http over non standar port\"; " + "sid:1;)"); if (s == NULL) { goto end; } @@ -3628,8 +3449,8 @@ static int AppLayerProtoDetectTest19(void) SigGroupBuild(de_ctx); DetectEngineThreadCtxInit(&tv, (void *)de_ctx, (void *)&det_ctx); - int r = AppLayerParserParse(NULL, alp_tctx, f, ALPROTO_FTP, - STREAM_TOSERVER, http_buf1, http_buf1_len); + int r = AppLayerParserParse( + NULL, alp_tctx, f, ALPROTO_FTP, STREAM_TOSERVER, http_buf1, http_buf1_len); if (r != 0) { printf("toserver chunk 1 returned %" PRId32 ", expected 0: ", r); goto end; @@ -3645,7 +3466,7 @@ static int AppLayerProtoDetectTest19(void) result = 1; - end: +end: if (alp_tctx != NULL) AppLayerParserThreadCtxFree(alp_tctx); if (det_ctx != NULL) diff --git a/src/app-layer-detect-proto.h b/src/app-layer-detect-proto.h index 4ee4bac10ad8..59a87e0306b0 100644 --- a/src/app-layer-detect-proto.h +++ b/src/app-layer-detect-proto.h @@ -62,45 +62,32 @@ int AppLayerProtoDetectPrepareState(void); /***** PP registration *****/ -void AppLayerProtoDetectPPRegister(uint8_t ipproto, - const char *portstr, - AppProto alproto, - uint16_t min_depth, uint16_t max_depth, - uint8_t direction, - ProbingParserFPtr ProbingParser1, - ProbingParserFPtr ProbingParser2); +void AppLayerProtoDetectPPRegister(uint8_t ipproto, const char *portstr, AppProto alproto, + uint16_t min_depth, uint16_t max_depth, uint8_t direction, ProbingParserFPtr ProbingParser1, + ProbingParserFPtr ProbingParser2); /** * \retval bool 0 if no config was found, 1 if config was found */ -int AppLayerProtoDetectPPParseConfPorts(const char *ipproto_name, - uint8_t ipproto, - const char *alproto_name, - AppProto alproto, - uint16_t min_depth, uint16_t max_depth, - ProbingParserFPtr ProbingParserTs, - ProbingParserFPtr ProbingParserTc); +int AppLayerProtoDetectPPParseConfPorts(const char *ipproto_name, uint8_t ipproto, + const char *alproto_name, AppProto alproto, uint16_t min_depth, uint16_t max_depth, + ProbingParserFPtr ProbingParserTs, ProbingParserFPtr ProbingParserTc); /***** PM registration *****/ /** * \brief Registers a case-sensitive pattern for protocol detection. */ -int AppLayerProtoDetectPMRegisterPatternCS(uint8_t ipproto, AppProto alproto, - const char *pattern, uint16_t depth, uint16_t offset, - uint8_t direction); +int AppLayerProtoDetectPMRegisterPatternCS(uint8_t ipproto, AppProto alproto, const char *pattern, + uint16_t depth, uint16_t offset, uint8_t direction); int AppLayerProtoDetectPMRegisterPatternCSwPP(uint8_t ipproto, AppProto alproto, - const char *pattern, uint16_t depth, uint16_t offset, - uint8_t direction, - ProbingParserFPtr PPFunc, - uint16_t pp_min_depth, uint16_t pp_max_depth); + const char *pattern, uint16_t depth, uint16_t offset, uint8_t direction, + ProbingParserFPtr PPFunc, uint16_t pp_min_depth, uint16_t pp_max_depth); /** * \brief Registers a case-insensitive pattern for protocol detection. */ -int AppLayerProtoDetectPMRegisterPatternCI(uint8_t ipproto, AppProto alproto, - const char *pattern, - uint16_t depth, uint16_t offset, - uint8_t direction); +int AppLayerProtoDetectPMRegisterPatternCI(uint8_t ipproto, AppProto alproto, const char *pattern, + uint16_t depth, uint16_t offset, uint8_t direction); /***** Setup/General Registration *****/ @@ -162,8 +149,7 @@ void AppLayerProtoDetectRegisterAlias(const char *proto_name, const char *proto_ * \retval 1 If enabled. * \retval 0 If disabled. */ -int AppLayerProtoDetectConfProtoDetectionEnabled(const char *ipproto, - const char *alproto); +int AppLayerProtoDetectConfProtoDetectionEnabled(const char *ipproto, const char *alproto); /** * \brief Given a protocol name, checks if proto detection is enabled in diff --git a/src/app-layer-dnp3-objects.c b/src/app-layer-dnp3-objects.c index 0bf9cd37bda2..d2a790e19086 100644 --- a/src/app-layer-dnp3-objects.c +++ b/src/app-layer-dnp3-objects.c @@ -136,11 +136,9 @@ static int DNP3ReadUint24(const uint8_t **buf, uint32_t *len, uint32_t *out) } #if __BYTE_ORDER__ == __BIG_ENDIAN - *out = ((uint32_t)(*buf)[0] << 16) | ((uint32_t)(*buf)[1] << 8) | - (uint32_t)(*buf)[2]; + *out = ((uint32_t)(*buf)[0] << 16) | ((uint32_t)(*buf)[1] << 8) | (uint32_t)(*buf)[2]; #elif __BYTE_ORDER == __LITTLE_ENDIAN - *out = ((uint64_t)(*buf)[0]) | ((uint64_t)(*buf)[1] << 8) | - ((uint64_t)(*buf)[2] << 16); + *out = ((uint64_t)(*buf)[0]) | ((uint64_t)(*buf)[1] << 8) | ((uint64_t)(*buf)[2] << 16); #endif *buf += 3; @@ -193,13 +191,11 @@ static int DNP3ReadUint48(const uint8_t **buf, uint32_t *len, uint64_t *out) } #if __BYTE_ORDER__ == __BIG_ENDIAN - *out = ((uint64_t)(*buf)[0] << 40) | ((uint64_t)(*buf)[1] << 32) | - ((uint64_t)(*buf)[2] << 24) | ((uint64_t)(*buf)[3] << 16) | - ((uint64_t)(*buf)[4] << 8) | (uint64_t)(*buf)[5]; + *out = ((uint64_t)(*buf)[0] << 40) | ((uint64_t)(*buf)[1] << 32) | ((uint64_t)(*buf)[2] << 24) | + ((uint64_t)(*buf)[3] << 16) | ((uint64_t)(*buf)[4] << 8) | (uint64_t)(*buf)[5]; #elif __BYTE_ORDER == __LITTLE_ENDIAN - *out = ((uint64_t)(*buf)[0]) | ((uint64_t)(*buf)[1] << 8) | - ((uint64_t)(*buf)[2] << 16) | ((uint64_t)(*buf)[3] << 24) | - ((uint64_t)(*buf)[4] << 32) | ((uint64_t)(*buf)[5] << 40); + *out = ((uint64_t)(*buf)[0]) | ((uint64_t)(*buf)[1] << 8) | ((uint64_t)(*buf)[2] << 16) | + ((uint64_t)(*buf)[3] << 24) | ((uint64_t)(*buf)[4] << 32) | ((uint64_t)(*buf)[5] << 40); #endif *buf += 6; @@ -291,8 +287,7 @@ static int DNP3ReadFloat64(const uint8_t **buf, uint32_t *len, double *out) /** * \brief Get the prefix value and advance the buffer. */ -static int DNP3ReadPrefix( - const uint8_t **buf, uint32_t *len, uint8_t prefix_code, uint32_t *out) +static int DNP3ReadPrefix(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, uint32_t *out) { uint8_t prefix_len = 0; @@ -354,7 +349,7 @@ static int DNP3ReadPrefix( * \retval 1 if successful, 0 on failure. */ static int DNP3AddPoint(DNP3PointList *list, void *object, uint32_t point_index, - uint8_t prefix_code, uint32_t prefix) + uint8_t prefix_code, uint32_t prefix) { DNP3Point *point = SCCalloc(1, sizeof(*point)); if (unlikely(point == NULL)) { @@ -390,9 +385,8 @@ static int DNP3AddPoint(DNP3PointList *list, void *object, uint32_t point_index, * ./scripts/dnp3-gen/dnp3-gen.py */ -static int DNP3DecodeObjectG1V1(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG1V1(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG1V1 *object = NULL; uint32_t bytes = (count / 8) + 1; @@ -428,7 +422,6 @@ static int DNP3DecodeObjectG1V1(const uint8_t **buf, uint32_t *len, count--; point_index++; } - } return 1; @@ -439,15 +432,14 @@ static int DNP3DecodeObjectG1V1(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG1V2(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG1V2(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG1V2 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -493,15 +485,14 @@ static int DNP3DecodeObjectG1V2(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG2V1(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG2V1(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG2V1 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -536,15 +527,14 @@ static int DNP3DecodeObjectG2V1(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG2V2(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG2V2(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG2V2 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -593,15 +583,14 @@ static int DNP3DecodeObjectG2V2(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG2V3(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG2V3(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG2V3 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -650,9 +639,8 @@ static int DNP3DecodeObjectG2V3(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG3V1(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG3V1(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG3V1 *object = NULL; uint32_t bytes = (count / 8) + 1; @@ -688,7 +676,6 @@ static int DNP3DecodeObjectG3V1(const uint8_t **buf, uint32_t *len, count--; point_index++; } - } return 1; @@ -699,15 +686,14 @@ static int DNP3DecodeObjectG3V1(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG3V2(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG3V2(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG3V2 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -752,15 +738,14 @@ static int DNP3DecodeObjectG3V2(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG4V1(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG4V1(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG4V1 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -805,15 +790,14 @@ static int DNP3DecodeObjectG4V1(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG4V2(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG4V2(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG4V2 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -861,15 +845,14 @@ static int DNP3DecodeObjectG4V2(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG4V3(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG4V3(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG4V3 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -917,9 +900,8 @@ static int DNP3DecodeObjectG4V3(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG10V1(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG10V1(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG10V1 *object = NULL; uint32_t bytes = (count / 8) + 1; @@ -955,7 +937,6 @@ static int DNP3DecodeObjectG10V1(const uint8_t **buf, uint32_t *len, count--; point_index++; } - } return 1; @@ -966,15 +947,14 @@ static int DNP3DecodeObjectG10V1(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG10V2(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG10V2(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG10V2 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -1020,15 +1000,14 @@ static int DNP3DecodeObjectG10V2(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG11V1(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG11V1(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG11V1 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -1074,15 +1053,14 @@ static int DNP3DecodeObjectG11V1(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG11V2(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG11V2(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG11V2 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -1131,15 +1109,14 @@ static int DNP3DecodeObjectG11V2(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG12V1(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG12V1(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG12V1 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -1198,15 +1175,14 @@ static int DNP3DecodeObjectG12V1(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG12V2(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG12V2(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG12V2 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -1265,9 +1241,8 @@ static int DNP3DecodeObjectG12V2(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG12V3(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG12V3(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG12V3 *object = NULL; uint32_t bytes = (count / 8) + 1; @@ -1303,7 +1278,6 @@ static int DNP3DecodeObjectG12V3(const uint8_t **buf, uint32_t *len, count--; point_index++; } - } return 1; @@ -1314,15 +1288,14 @@ static int DNP3DecodeObjectG12V3(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG13V1(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG13V1(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG13V1 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -1362,15 +1335,14 @@ static int DNP3DecodeObjectG13V1(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG13V2(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG13V2(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG13V2 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -1413,15 +1385,14 @@ static int DNP3DecodeObjectG13V2(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG20V1(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG20V1(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG20V1 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -1470,15 +1441,14 @@ static int DNP3DecodeObjectG20V1(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG20V2(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG20V2(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG20V2 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -1527,15 +1497,14 @@ static int DNP3DecodeObjectG20V2(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG20V3(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG20V3(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG20V3 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -1584,15 +1553,14 @@ static int DNP3DecodeObjectG20V3(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG20V4(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG20V4(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG20V4 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -1641,15 +1609,14 @@ static int DNP3DecodeObjectG20V4(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG20V5(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG20V5(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG20V5 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -1684,15 +1651,14 @@ static int DNP3DecodeObjectG20V5(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG20V6(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG20V6(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG20V6 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -1727,15 +1693,14 @@ static int DNP3DecodeObjectG20V6(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG20V7(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG20V7(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG20V7 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -1770,15 +1735,14 @@ static int DNP3DecodeObjectG20V7(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG20V8(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG20V8(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG20V8 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -1813,15 +1777,14 @@ static int DNP3DecodeObjectG20V8(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG21V1(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG21V1(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG21V1 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -1870,15 +1833,14 @@ static int DNP3DecodeObjectG21V1(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG21V2(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG21V2(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG21V2 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -1927,15 +1889,14 @@ static int DNP3DecodeObjectG21V2(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG21V3(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG21V3(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG21V3 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -1984,15 +1945,14 @@ static int DNP3DecodeObjectG21V3(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG21V4(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG21V4(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG21V4 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -2041,15 +2001,14 @@ static int DNP3DecodeObjectG21V4(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG21V5(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG21V5(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG21V5 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -2101,15 +2060,14 @@ static int DNP3DecodeObjectG21V5(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG21V6(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG21V6(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG21V6 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -2161,15 +2119,14 @@ static int DNP3DecodeObjectG21V6(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG21V7(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG21V7(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG21V7 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -2221,15 +2178,14 @@ static int DNP3DecodeObjectG21V7(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG21V8(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG21V8(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG21V8 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -2281,15 +2237,14 @@ static int DNP3DecodeObjectG21V8(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG21V9(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG21V9(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG21V9 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -2324,15 +2279,14 @@ static int DNP3DecodeObjectG21V9(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG21V10(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG21V10(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG21V10 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -2367,15 +2321,14 @@ static int DNP3DecodeObjectG21V10(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG21V11(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG21V11(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG21V11 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -2410,15 +2363,14 @@ static int DNP3DecodeObjectG21V11(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG21V12(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG21V12(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG21V12 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -2453,15 +2405,14 @@ static int DNP3DecodeObjectG21V12(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG22V1(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG22V1(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG22V1 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -2510,15 +2461,14 @@ static int DNP3DecodeObjectG22V1(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG22V2(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG22V2(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG22V2 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -2567,15 +2517,14 @@ static int DNP3DecodeObjectG22V2(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG22V3(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG22V3(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG22V3 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -2624,15 +2573,14 @@ static int DNP3DecodeObjectG22V3(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG22V4(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG22V4(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG22V4 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -2681,15 +2629,14 @@ static int DNP3DecodeObjectG22V4(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG22V5(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG22V5(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG22V5 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -2741,15 +2688,14 @@ static int DNP3DecodeObjectG22V5(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG22V6(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG22V6(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG22V6 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -2801,15 +2747,14 @@ static int DNP3DecodeObjectG22V6(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG22V7(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG22V7(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG22V7 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -2861,15 +2806,14 @@ static int DNP3DecodeObjectG22V7(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG22V8(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG22V8(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG22V8 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -2921,15 +2865,14 @@ static int DNP3DecodeObjectG22V8(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG23V1(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG23V1(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG23V1 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -2978,15 +2921,14 @@ static int DNP3DecodeObjectG23V1(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG23V2(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG23V2(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG23V2 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -3035,15 +2977,14 @@ static int DNP3DecodeObjectG23V2(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG23V3(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG23V3(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG23V3 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -3092,15 +3033,14 @@ static int DNP3DecodeObjectG23V3(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG23V4(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG23V4(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG23V4 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -3149,15 +3089,14 @@ static int DNP3DecodeObjectG23V4(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG23V5(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG23V5(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG23V5 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -3209,15 +3148,14 @@ static int DNP3DecodeObjectG23V5(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG23V6(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG23V6(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG23V6 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -3269,15 +3207,14 @@ static int DNP3DecodeObjectG23V6(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG23V7(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG23V7(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG23V7 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -3329,15 +3266,14 @@ static int DNP3DecodeObjectG23V7(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG23V8(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG23V8(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG23V8 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -3389,15 +3325,14 @@ static int DNP3DecodeObjectG23V8(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG30V1(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG30V1(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG30V1 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -3446,15 +3381,14 @@ static int DNP3DecodeObjectG30V1(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG30V2(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG30V2(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG30V2 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -3503,15 +3437,14 @@ static int DNP3DecodeObjectG30V2(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG30V3(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG30V3(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG30V3 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -3546,15 +3479,14 @@ static int DNP3DecodeObjectG30V3(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG30V4(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG30V4(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG30V4 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -3589,15 +3521,14 @@ static int DNP3DecodeObjectG30V4(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG30V5(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG30V5(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG30V5 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -3646,15 +3577,14 @@ static int DNP3DecodeObjectG30V5(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG30V6(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG30V6(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG30V6 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -3703,15 +3633,14 @@ static int DNP3DecodeObjectG30V6(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG31V1(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG31V1(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG31V1 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -3760,15 +3689,14 @@ static int DNP3DecodeObjectG31V1(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG31V2(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG31V2(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG31V2 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -3817,15 +3745,14 @@ static int DNP3DecodeObjectG31V2(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG31V3(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG31V3(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG31V3 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -3877,15 +3804,14 @@ static int DNP3DecodeObjectG31V3(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG31V4(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG31V4(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG31V4 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -3937,15 +3863,14 @@ static int DNP3DecodeObjectG31V4(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG31V5(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG31V5(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG31V5 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -3980,15 +3905,14 @@ static int DNP3DecodeObjectG31V5(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG31V6(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG31V6(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG31V6 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -4023,15 +3947,14 @@ static int DNP3DecodeObjectG31V6(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG31V7(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG31V7(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG31V7 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -4080,15 +4003,14 @@ static int DNP3DecodeObjectG31V7(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG31V8(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG31V8(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG31V8 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -4137,15 +4059,14 @@ static int DNP3DecodeObjectG31V8(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG32V1(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG32V1(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG32V1 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -4194,15 +4115,14 @@ static int DNP3DecodeObjectG32V1(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG32V2(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG32V2(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG32V2 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -4251,15 +4171,14 @@ static int DNP3DecodeObjectG32V2(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG32V3(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG32V3(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG32V3 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -4311,15 +4230,14 @@ static int DNP3DecodeObjectG32V3(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG32V4(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG32V4(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG32V4 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -4371,15 +4289,14 @@ static int DNP3DecodeObjectG32V4(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG32V5(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG32V5(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG32V5 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -4428,15 +4345,14 @@ static int DNP3DecodeObjectG32V5(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG32V6(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG32V6(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG32V6 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -4485,15 +4401,14 @@ static int DNP3DecodeObjectG32V6(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG32V7(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG32V7(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG32V7 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -4545,15 +4460,14 @@ static int DNP3DecodeObjectG32V7(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG32V8(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG32V8(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG32V8 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -4605,15 +4519,14 @@ static int DNP3DecodeObjectG32V8(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG33V1(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG33V1(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG33V1 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -4662,15 +4575,14 @@ static int DNP3DecodeObjectG33V1(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG33V2(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG33V2(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG33V2 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -4719,15 +4631,14 @@ static int DNP3DecodeObjectG33V2(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG33V3(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG33V3(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG33V3 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -4779,15 +4690,14 @@ static int DNP3DecodeObjectG33V3(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG33V4(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG33V4(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG33V4 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -4839,15 +4749,14 @@ static int DNP3DecodeObjectG33V4(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG33V5(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG33V5(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG33V5 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -4896,15 +4805,14 @@ static int DNP3DecodeObjectG33V5(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG33V6(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG33V6(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG33V6 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -4953,15 +4861,14 @@ static int DNP3DecodeObjectG33V6(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG33V7(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG33V7(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG33V7 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -5013,15 +4920,14 @@ static int DNP3DecodeObjectG33V7(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG33V8(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG33V8(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG33V8 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -5073,15 +4979,14 @@ static int DNP3DecodeObjectG33V8(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG34V1(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG34V1(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG34V1 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -5116,15 +5021,14 @@ static int DNP3DecodeObjectG34V1(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG34V2(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG34V2(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG34V2 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -5159,15 +5063,14 @@ static int DNP3DecodeObjectG34V2(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG34V3(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG34V3(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG34V3 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -5202,15 +5105,14 @@ static int DNP3DecodeObjectG34V3(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG40V1(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG40V1(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG40V1 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -5259,15 +5161,14 @@ static int DNP3DecodeObjectG40V1(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG40V2(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG40V2(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG40V2 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -5316,15 +5217,14 @@ static int DNP3DecodeObjectG40V2(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG40V3(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG40V3(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG40V3 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -5373,15 +5273,14 @@ static int DNP3DecodeObjectG40V3(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG40V4(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG40V4(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG40V4 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -5430,15 +5329,14 @@ static int DNP3DecodeObjectG40V4(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG41V1(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG41V1(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG41V1 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -5476,15 +5374,14 @@ static int DNP3DecodeObjectG41V1(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG41V2(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG41V2(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG41V2 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -5522,15 +5419,14 @@ static int DNP3DecodeObjectG41V2(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG41V3(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG41V3(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG41V3 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -5568,15 +5464,14 @@ static int DNP3DecodeObjectG41V3(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG41V4(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG41V4(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG41V4 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -5614,15 +5509,14 @@ static int DNP3DecodeObjectG41V4(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG42V1(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG42V1(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG42V1 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -5671,15 +5565,14 @@ static int DNP3DecodeObjectG42V1(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG42V2(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG42V2(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG42V2 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -5728,15 +5621,14 @@ static int DNP3DecodeObjectG42V2(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG42V3(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG42V3(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG42V3 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -5788,15 +5680,14 @@ static int DNP3DecodeObjectG42V3(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG42V4(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG42V4(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG42V4 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -5848,15 +5739,14 @@ static int DNP3DecodeObjectG42V4(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG42V5(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG42V5(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG42V5 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -5905,15 +5795,14 @@ static int DNP3DecodeObjectG42V5(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG42V6(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG42V6(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG42V6 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -5962,15 +5851,14 @@ static int DNP3DecodeObjectG42V6(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG42V7(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG42V7(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG42V7 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -6022,15 +5910,14 @@ static int DNP3DecodeObjectG42V7(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG42V8(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG42V8(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG42V8 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -6082,15 +5969,14 @@ static int DNP3DecodeObjectG42V8(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG43V1(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG43V1(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG43V1 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -6133,15 +6019,14 @@ static int DNP3DecodeObjectG43V1(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG43V2(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG43V2(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG43V2 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -6184,15 +6069,14 @@ static int DNP3DecodeObjectG43V2(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG43V3(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG43V3(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG43V3 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -6238,15 +6122,14 @@ static int DNP3DecodeObjectG43V3(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG43V4(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG43V4(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG43V4 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -6292,15 +6175,14 @@ static int DNP3DecodeObjectG43V4(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG43V5(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG43V5(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG43V5 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -6343,15 +6225,14 @@ static int DNP3DecodeObjectG43V5(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG43V6(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG43V6(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG43V6 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -6394,15 +6275,14 @@ static int DNP3DecodeObjectG43V6(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG43V7(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG43V7(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG43V7 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -6448,15 +6328,14 @@ static int DNP3DecodeObjectG43V7(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG43V8(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG43V8(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG43V8 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -6502,15 +6381,14 @@ static int DNP3DecodeObjectG43V8(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG50V1(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG50V1(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG50V1 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -6545,15 +6423,14 @@ static int DNP3DecodeObjectG50V1(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG50V2(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG50V2(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG50V2 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -6591,15 +6468,14 @@ static int DNP3DecodeObjectG50V2(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG50V3(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG50V3(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG50V3 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -6634,15 +6510,14 @@ static int DNP3DecodeObjectG50V3(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG50V4(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG50V4(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG50V4 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -6683,15 +6558,14 @@ static int DNP3DecodeObjectG50V4(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG51V1(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG51V1(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG51V1 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -6726,15 +6600,14 @@ static int DNP3DecodeObjectG51V1(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG51V2(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG51V2(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG51V2 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -6769,15 +6642,14 @@ static int DNP3DecodeObjectG51V2(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG52V1(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG52V1(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG52V1 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -6812,15 +6684,14 @@ static int DNP3DecodeObjectG52V1(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG52V2(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG52V2(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG52V2 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -6855,15 +6726,14 @@ static int DNP3DecodeObjectG52V2(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG70V1(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG70V1(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG70V1 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -6957,15 +6827,14 @@ static int DNP3DecodeObjectG70V1(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG70V2(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG70V2(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG70V2 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -7032,15 +6901,14 @@ static int DNP3DecodeObjectG70V2(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG70V3(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG70V3(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG70V3 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -7109,9 +6977,8 @@ static int DNP3DecodeObjectG70V3(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG70V4(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG70V4(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG70V4 *object = NULL; uint32_t prefix = 0; @@ -7122,7 +6989,7 @@ static int DNP3DecodeObjectG70V4(const uint8_t **buf, uint32_t *len, goto error; } - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -7185,9 +7052,8 @@ static int DNP3DecodeObjectG70V4(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG70V5(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG70V5(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG70V5 *object = NULL; uint32_t prefix = 0; @@ -7198,7 +7064,7 @@ static int DNP3DecodeObjectG70V5(const uint8_t **buf, uint32_t *len, goto error; } - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -7252,9 +7118,8 @@ static int DNP3DecodeObjectG70V5(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG70V6(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG70V6(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG70V6 *object = NULL; uint32_t prefix = 0; @@ -7265,7 +7130,7 @@ static int DNP3DecodeObjectG70V6(const uint8_t **buf, uint32_t *len, goto error; } - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -7322,15 +7187,14 @@ static int DNP3DecodeObjectG70V6(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG70V7(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG70V7(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG70V7 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -7393,9 +7257,8 @@ static int DNP3DecodeObjectG70V7(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG70V8(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG70V8(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG70V8 *object = NULL; uint32_t prefix = 0; @@ -7406,7 +7269,7 @@ static int DNP3DecodeObjectG70V8(const uint8_t **buf, uint32_t *len, goto error; } - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -7454,9 +7317,8 @@ static int DNP3DecodeObjectG70V8(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG80V1(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG80V1(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG80V1 *object = NULL; uint32_t bytes = (count / 8) + 1; @@ -7492,7 +7354,6 @@ static int DNP3DecodeObjectG80V1(const uint8_t **buf, uint32_t *len, count--; point_index++; } - } return 1; @@ -7503,15 +7364,14 @@ static int DNP3DecodeObjectG80V1(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG81V1(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG81V1(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG81V1 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -7557,15 +7417,14 @@ static int DNP3DecodeObjectG81V1(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG83V1(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG83V1(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG83V1 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -7626,15 +7485,14 @@ static int DNP3DecodeObjectG83V1(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG86V2(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG86V2(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG86V2 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -7680,15 +7538,14 @@ static int DNP3DecodeObjectG86V2(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG102V1(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG102V1(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG102V1 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -7723,9 +7580,8 @@ static int DNP3DecodeObjectG102V1(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG120V1(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG120V1(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG120V1 *object = NULL; uint32_t prefix = 0; @@ -7736,7 +7592,7 @@ static int DNP3DecodeObjectG120V1(const uint8_t **buf, uint32_t *len, goto error; } - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -7802,9 +7658,8 @@ static int DNP3DecodeObjectG120V1(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG120V2(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG120V2(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG120V2 *object = NULL; uint32_t prefix = 0; @@ -7815,7 +7670,7 @@ static int DNP3DecodeObjectG120V2(const uint8_t **buf, uint32_t *len, goto error; } - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -7875,15 +7730,14 @@ static int DNP3DecodeObjectG120V2(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG120V3(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG120V3(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG120V3 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -7921,15 +7775,14 @@ static int DNP3DecodeObjectG120V3(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG120V4(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG120V4(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG120V4 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -7964,9 +7817,8 @@ static int DNP3DecodeObjectG120V4(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG120V5(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG120V5(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG120V5 *object = NULL; uint32_t prefix = 0; @@ -7977,7 +7829,7 @@ static int DNP3DecodeObjectG120V5(const uint8_t **buf, uint32_t *len, goto error; } - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -8065,9 +7917,8 @@ static int DNP3DecodeObjectG120V5(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG120V6(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG120V6(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG120V6 *object = NULL; uint32_t prefix = 0; @@ -8078,7 +7929,7 @@ static int DNP3DecodeObjectG120V6(const uint8_t **buf, uint32_t *len, goto error; } - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -8138,9 +7989,8 @@ static int DNP3DecodeObjectG120V6(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG120V7(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG120V7(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG120V7 *object = NULL; uint32_t prefix = 0; @@ -8151,7 +8001,7 @@ static int DNP3DecodeObjectG120V7(const uint8_t **buf, uint32_t *len, goto error; } - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -8214,9 +8064,8 @@ static int DNP3DecodeObjectG120V7(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG120V8(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG120V8(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG120V8 *object = NULL; uint32_t prefix = 0; @@ -8227,7 +8076,7 @@ static int DNP3DecodeObjectG120V8(const uint8_t **buf, uint32_t *len, goto error; } - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -8287,16 +8136,15 @@ static int DNP3DecodeObjectG120V8(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG120V9(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG120V9(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG120V9 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; uint32_t offset; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -8350,9 +8198,8 @@ static int DNP3DecodeObjectG120V9(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG120V10(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG120V10(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG120V10 *object = NULL; uint32_t prefix = 0; @@ -8362,7 +8209,7 @@ static int DNP3DecodeObjectG120V10(const uint8_t **buf, uint32_t *len, goto error; } - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -8460,9 +8307,8 @@ static int DNP3DecodeObjectG120V10(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG120V11(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG120V11(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG120V11 *object = NULL; uint32_t prefix = 0; @@ -8472,7 +8318,7 @@ static int DNP3DecodeObjectG120V11(const uint8_t **buf, uint32_t *len, goto error; } - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -8539,9 +8385,8 @@ static int DNP3DecodeObjectG120V11(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG120V12(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG120V12(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG120V12 *object = NULL; uint32_t prefix = 0; @@ -8551,7 +8396,7 @@ static int DNP3DecodeObjectG120V12(const uint8_t **buf, uint32_t *len, goto error; } - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -8608,9 +8453,8 @@ static int DNP3DecodeObjectG120V12(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG120V13(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG120V13(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG120V13 *object = NULL; uint32_t prefix = 0; @@ -8620,7 +8464,7 @@ static int DNP3DecodeObjectG120V13(const uint8_t **buf, uint32_t *len, goto error; } - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -8677,9 +8521,8 @@ static int DNP3DecodeObjectG120V13(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG120V14(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG120V14(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG120V14 *object = NULL; uint32_t prefix = 0; @@ -8690,7 +8533,7 @@ static int DNP3DecodeObjectG120V14(const uint8_t **buf, uint32_t *len, goto error; } - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -8744,9 +8587,8 @@ static int DNP3DecodeObjectG120V14(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG120V15(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG120V15(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG120V15 *object = NULL; uint32_t prefix = 0; @@ -8757,7 +8599,7 @@ static int DNP3DecodeObjectG120V15(const uint8_t **buf, uint32_t *len, goto error; } - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -8811,15 +8653,14 @@ static int DNP3DecodeObjectG120V15(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG121V1(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG121V1(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG121V1 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -8871,15 +8712,14 @@ static int DNP3DecodeObjectG121V1(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG122V1(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG122V1(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG122V1 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -8931,15 +8771,14 @@ static int DNP3DecodeObjectG122V1(const uint8_t **buf, uint32_t *len, return 0; } -static int DNP3DecodeObjectG122V2(const uint8_t **buf, uint32_t *len, - uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *points) +static int DNP3DecodeObjectG122V2(const uint8_t **buf, uint32_t *len, uint8_t prefix_code, + uint32_t start, uint32_t count, DNP3PointList *points) { DNP3ObjectG122V2 *object = NULL; uint32_t prefix = 0; uint32_t point_index = start; - if (*len < count/8) { + if (*len < count / 8) { goto error; } while (count--) { @@ -8994,33 +8833,32 @@ static int DNP3DecodeObjectG122V2(const uint8_t **buf, uint32_t *len, return 0; } - void DNP3FreeObjectPoint(int group, int variation, void *point) { - switch(DNP3_OBJECT_CODE(group, variation)) { + switch (DNP3_OBJECT_CODE(group, variation)) { case DNP3_OBJECT_CODE(83, 1): { - DNP3ObjectG83V1 *object = (DNP3ObjectG83V1 *) point; + DNP3ObjectG83V1 *object = (DNP3ObjectG83V1 *)point; if (object->data_objects != NULL) { SCFree(object->data_objects); } break; } case DNP3_OBJECT_CODE(120, 1): { - DNP3ObjectG120V1 *object = (DNP3ObjectG120V1 *) point; + DNP3ObjectG120V1 *object = (DNP3ObjectG120V1 *)point; if (object->challenge_data != NULL) { SCFree(object->challenge_data); } break; } case DNP3_OBJECT_CODE(120, 2): { - DNP3ObjectG120V2 *object = (DNP3ObjectG120V2 *) point; + DNP3ObjectG120V2 *object = (DNP3ObjectG120V2 *)point; if (object->mac_value != NULL) { SCFree(object->mac_value); } break; } case DNP3_OBJECT_CODE(120, 5): { - DNP3ObjectG120V5 *object = (DNP3ObjectG120V5 *) point; + DNP3ObjectG120V5 *object = (DNP3ObjectG120V5 *)point; if (object->challenge_data != NULL) { SCFree(object->challenge_data); } @@ -9030,28 +8868,28 @@ void DNP3FreeObjectPoint(int group, int variation, void *point) break; } case DNP3_OBJECT_CODE(120, 6): { - DNP3ObjectG120V6 *object = (DNP3ObjectG120V6 *) point; + DNP3ObjectG120V6 *object = (DNP3ObjectG120V6 *)point; if (object->wrapped_key_data != NULL) { SCFree(object->wrapped_key_data); } break; } case DNP3_OBJECT_CODE(120, 8): { - DNP3ObjectG120V8 *object = (DNP3ObjectG120V8 *) point; + DNP3ObjectG120V8 *object = (DNP3ObjectG120V8 *)point; if (object->certificate != NULL) { SCFree(object->certificate); } break; } case DNP3_OBJECT_CODE(120, 9): { - DNP3ObjectG120V9 *object = (DNP3ObjectG120V9 *) point; + DNP3ObjectG120V9 *object = (DNP3ObjectG120V9 *)point; if (object->mac_value != NULL) { SCFree(object->mac_value); } break; } case DNP3_OBJECT_CODE(120, 10): { - DNP3ObjectG120V10 *object = (DNP3ObjectG120V10 *) point; + DNP3ObjectG120V10 *object = (DNP3ObjectG120V10 *)point; if (object->user_public_key != NULL) { SCFree(object->user_public_key); } @@ -9061,35 +8899,35 @@ void DNP3FreeObjectPoint(int group, int variation, void *point) break; } case DNP3_OBJECT_CODE(120, 11): { - DNP3ObjectG120V11 *object = (DNP3ObjectG120V11 *) point; + DNP3ObjectG120V11 *object = (DNP3ObjectG120V11 *)point; if (object->master_challenge_data != NULL) { SCFree(object->master_challenge_data); } break; } case DNP3_OBJECT_CODE(120, 12): { - DNP3ObjectG120V12 *object = (DNP3ObjectG120V12 *) point; + DNP3ObjectG120V12 *object = (DNP3ObjectG120V12 *)point; if (object->challenge_data != NULL) { SCFree(object->challenge_data); } break; } case DNP3_OBJECT_CODE(120, 13): { - DNP3ObjectG120V13 *object = (DNP3ObjectG120V13 *) point; + DNP3ObjectG120V13 *object = (DNP3ObjectG120V13 *)point; if (object->encrypted_update_key_data != NULL) { SCFree(object->encrypted_update_key_data); } break; } case DNP3_OBJECT_CODE(120, 14): { - DNP3ObjectG120V14 *object = (DNP3ObjectG120V14 *) point; + DNP3ObjectG120V14 *object = (DNP3ObjectG120V14 *)point; if (object->digital_signature != NULL) { SCFree(object->digital_signature); } break; } case DNP3_OBJECT_CODE(120, 15): { - DNP3ObjectG120V15 *object = (DNP3ObjectG120V15 *) point; + DNP3ObjectG120V15 *object = (DNP3ObjectG120V15 *)point; if (object->mac != NULL) { SCFree(object->mac); } @@ -9107,616 +8945,464 @@ void DNP3FreeObjectPoint(int group, int variation, void *point) * \retval 0 on success. On failure a positive integer corresponding * to a DNP3 application layer event will be returned. */ -int DNP3DecodeObject(int group, int variation, const uint8_t **buf, - uint32_t *len, uint8_t prefix_code, uint32_t start, - uint32_t count, DNP3PointList *points) +int DNP3DecodeObject(int group, int variation, const uint8_t **buf, uint32_t *len, + uint8_t prefix_code, uint32_t start, uint32_t count, DNP3PointList *points) { int rc = 0; switch (DNP3_OBJECT_CODE(group, variation)) { case DNP3_OBJECT_CODE(1, 1): - rc = DNP3DecodeObjectG1V1(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG1V1(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(1, 2): - rc = DNP3DecodeObjectG1V2(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG1V2(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(2, 1): - rc = DNP3DecodeObjectG2V1(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG2V1(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(2, 2): - rc = DNP3DecodeObjectG2V2(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG2V2(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(2, 3): - rc = DNP3DecodeObjectG2V3(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG2V3(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(3, 1): - rc = DNP3DecodeObjectG3V1(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG3V1(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(3, 2): - rc = DNP3DecodeObjectG3V2(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG3V2(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(4, 1): - rc = DNP3DecodeObjectG4V1(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG4V1(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(4, 2): - rc = DNP3DecodeObjectG4V2(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG4V2(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(4, 3): - rc = DNP3DecodeObjectG4V3(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG4V3(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(10, 1): - rc = DNP3DecodeObjectG10V1(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG10V1(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(10, 2): - rc = DNP3DecodeObjectG10V2(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG10V2(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(11, 1): - rc = DNP3DecodeObjectG11V1(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG11V1(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(11, 2): - rc = DNP3DecodeObjectG11V2(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG11V2(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(12, 1): - rc = DNP3DecodeObjectG12V1(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG12V1(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(12, 2): - rc = DNP3DecodeObjectG12V2(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG12V2(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(12, 3): - rc = DNP3DecodeObjectG12V3(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG12V3(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(13, 1): - rc = DNP3DecodeObjectG13V1(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG13V1(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(13, 2): - rc = DNP3DecodeObjectG13V2(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG13V2(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(20, 1): - rc = DNP3DecodeObjectG20V1(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG20V1(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(20, 2): - rc = DNP3DecodeObjectG20V2(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG20V2(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(20, 3): - rc = DNP3DecodeObjectG20V3(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG20V3(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(20, 4): - rc = DNP3DecodeObjectG20V4(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG20V4(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(20, 5): - rc = DNP3DecodeObjectG20V5(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG20V5(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(20, 6): - rc = DNP3DecodeObjectG20V6(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG20V6(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(20, 7): - rc = DNP3DecodeObjectG20V7(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG20V7(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(20, 8): - rc = DNP3DecodeObjectG20V8(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG20V8(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(21, 1): - rc = DNP3DecodeObjectG21V1(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG21V1(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(21, 2): - rc = DNP3DecodeObjectG21V2(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG21V2(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(21, 3): - rc = DNP3DecodeObjectG21V3(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG21V3(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(21, 4): - rc = DNP3DecodeObjectG21V4(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG21V4(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(21, 5): - rc = DNP3DecodeObjectG21V5(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG21V5(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(21, 6): - rc = DNP3DecodeObjectG21V6(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG21V6(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(21, 7): - rc = DNP3DecodeObjectG21V7(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG21V7(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(21, 8): - rc = DNP3DecodeObjectG21V8(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG21V8(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(21, 9): - rc = DNP3DecodeObjectG21V9(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG21V9(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(21, 10): - rc = DNP3DecodeObjectG21V10(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG21V10(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(21, 11): - rc = DNP3DecodeObjectG21V11(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG21V11(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(21, 12): - rc = DNP3DecodeObjectG21V12(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG21V12(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(22, 1): - rc = DNP3DecodeObjectG22V1(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG22V1(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(22, 2): - rc = DNP3DecodeObjectG22V2(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG22V2(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(22, 3): - rc = DNP3DecodeObjectG22V3(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG22V3(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(22, 4): - rc = DNP3DecodeObjectG22V4(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG22V4(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(22, 5): - rc = DNP3DecodeObjectG22V5(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG22V5(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(22, 6): - rc = DNP3DecodeObjectG22V6(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG22V6(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(22, 7): - rc = DNP3DecodeObjectG22V7(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG22V7(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(22, 8): - rc = DNP3DecodeObjectG22V8(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG22V8(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(23, 1): - rc = DNP3DecodeObjectG23V1(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG23V1(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(23, 2): - rc = DNP3DecodeObjectG23V2(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG23V2(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(23, 3): - rc = DNP3DecodeObjectG23V3(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG23V3(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(23, 4): - rc = DNP3DecodeObjectG23V4(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG23V4(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(23, 5): - rc = DNP3DecodeObjectG23V5(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG23V5(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(23, 6): - rc = DNP3DecodeObjectG23V6(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG23V6(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(23, 7): - rc = DNP3DecodeObjectG23V7(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG23V7(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(23, 8): - rc = DNP3DecodeObjectG23V8(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG23V8(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(30, 1): - rc = DNP3DecodeObjectG30V1(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG30V1(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(30, 2): - rc = DNP3DecodeObjectG30V2(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG30V2(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(30, 3): - rc = DNP3DecodeObjectG30V3(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG30V3(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(30, 4): - rc = DNP3DecodeObjectG30V4(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG30V4(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(30, 5): - rc = DNP3DecodeObjectG30V5(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG30V5(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(30, 6): - rc = DNP3DecodeObjectG30V6(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG30V6(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(31, 1): - rc = DNP3DecodeObjectG31V1(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG31V1(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(31, 2): - rc = DNP3DecodeObjectG31V2(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG31V2(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(31, 3): - rc = DNP3DecodeObjectG31V3(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG31V3(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(31, 4): - rc = DNP3DecodeObjectG31V4(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG31V4(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(31, 5): - rc = DNP3DecodeObjectG31V5(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG31V5(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(31, 6): - rc = DNP3DecodeObjectG31V6(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG31V6(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(31, 7): - rc = DNP3DecodeObjectG31V7(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG31V7(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(31, 8): - rc = DNP3DecodeObjectG31V8(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG31V8(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(32, 1): - rc = DNP3DecodeObjectG32V1(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG32V1(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(32, 2): - rc = DNP3DecodeObjectG32V2(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG32V2(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(32, 3): - rc = DNP3DecodeObjectG32V3(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG32V3(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(32, 4): - rc = DNP3DecodeObjectG32V4(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG32V4(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(32, 5): - rc = DNP3DecodeObjectG32V5(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG32V5(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(32, 6): - rc = DNP3DecodeObjectG32V6(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG32V6(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(32, 7): - rc = DNP3DecodeObjectG32V7(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG32V7(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(32, 8): - rc = DNP3DecodeObjectG32V8(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG32V8(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(33, 1): - rc = DNP3DecodeObjectG33V1(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG33V1(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(33, 2): - rc = DNP3DecodeObjectG33V2(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG33V2(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(33, 3): - rc = DNP3DecodeObjectG33V3(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG33V3(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(33, 4): - rc = DNP3DecodeObjectG33V4(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG33V4(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(33, 5): - rc = DNP3DecodeObjectG33V5(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG33V5(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(33, 6): - rc = DNP3DecodeObjectG33V6(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG33V6(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(33, 7): - rc = DNP3DecodeObjectG33V7(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG33V7(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(33, 8): - rc = DNP3DecodeObjectG33V8(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG33V8(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(34, 1): - rc = DNP3DecodeObjectG34V1(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG34V1(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(34, 2): - rc = DNP3DecodeObjectG34V2(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG34V2(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(34, 3): - rc = DNP3DecodeObjectG34V3(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG34V3(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(40, 1): - rc = DNP3DecodeObjectG40V1(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG40V1(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(40, 2): - rc = DNP3DecodeObjectG40V2(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG40V2(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(40, 3): - rc = DNP3DecodeObjectG40V3(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG40V3(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(40, 4): - rc = DNP3DecodeObjectG40V4(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG40V4(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(41, 1): - rc = DNP3DecodeObjectG41V1(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG41V1(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(41, 2): - rc = DNP3DecodeObjectG41V2(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG41V2(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(41, 3): - rc = DNP3DecodeObjectG41V3(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG41V3(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(41, 4): - rc = DNP3DecodeObjectG41V4(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG41V4(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(42, 1): - rc = DNP3DecodeObjectG42V1(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG42V1(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(42, 2): - rc = DNP3DecodeObjectG42V2(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG42V2(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(42, 3): - rc = DNP3DecodeObjectG42V3(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG42V3(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(42, 4): - rc = DNP3DecodeObjectG42V4(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG42V4(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(42, 5): - rc = DNP3DecodeObjectG42V5(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG42V5(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(42, 6): - rc = DNP3DecodeObjectG42V6(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG42V6(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(42, 7): - rc = DNP3DecodeObjectG42V7(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG42V7(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(42, 8): - rc = DNP3DecodeObjectG42V8(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG42V8(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(43, 1): - rc = DNP3DecodeObjectG43V1(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG43V1(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(43, 2): - rc = DNP3DecodeObjectG43V2(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG43V2(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(43, 3): - rc = DNP3DecodeObjectG43V3(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG43V3(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(43, 4): - rc = DNP3DecodeObjectG43V4(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG43V4(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(43, 5): - rc = DNP3DecodeObjectG43V5(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG43V5(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(43, 6): - rc = DNP3DecodeObjectG43V6(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG43V6(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(43, 7): - rc = DNP3DecodeObjectG43V7(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG43V7(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(43, 8): - rc = DNP3DecodeObjectG43V8(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG43V8(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(50, 1): - rc = DNP3DecodeObjectG50V1(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG50V1(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(50, 2): - rc = DNP3DecodeObjectG50V2(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG50V2(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(50, 3): - rc = DNP3DecodeObjectG50V3(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG50V3(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(50, 4): - rc = DNP3DecodeObjectG50V4(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG50V4(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(51, 1): - rc = DNP3DecodeObjectG51V1(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG51V1(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(51, 2): - rc = DNP3DecodeObjectG51V2(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG51V2(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(52, 1): - rc = DNP3DecodeObjectG52V1(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG52V1(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(52, 2): - rc = DNP3DecodeObjectG52V2(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG52V2(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(70, 1): - rc = DNP3DecodeObjectG70V1(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG70V1(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(70, 2): - rc = DNP3DecodeObjectG70V2(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG70V2(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(70, 3): - rc = DNP3DecodeObjectG70V3(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG70V3(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(70, 4): - rc = DNP3DecodeObjectG70V4(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG70V4(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(70, 5): - rc = DNP3DecodeObjectG70V5(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG70V5(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(70, 6): - rc = DNP3DecodeObjectG70V6(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG70V6(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(70, 7): - rc = DNP3DecodeObjectG70V7(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG70V7(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(70, 8): - rc = DNP3DecodeObjectG70V8(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG70V8(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(80, 1): - rc = DNP3DecodeObjectG80V1(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG80V1(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(81, 1): - rc = DNP3DecodeObjectG81V1(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG81V1(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(83, 1): - rc = DNP3DecodeObjectG83V1(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG83V1(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(86, 2): - rc = DNP3DecodeObjectG86V2(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG86V2(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(102, 1): - rc = DNP3DecodeObjectG102V1(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG102V1(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(120, 1): - rc = DNP3DecodeObjectG120V1(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG120V1(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(120, 2): - rc = DNP3DecodeObjectG120V2(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG120V2(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(120, 3): - rc = DNP3DecodeObjectG120V3(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG120V3(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(120, 4): - rc = DNP3DecodeObjectG120V4(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG120V4(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(120, 5): - rc = DNP3DecodeObjectG120V5(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG120V5(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(120, 6): - rc = DNP3DecodeObjectG120V6(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG120V6(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(120, 7): - rc = DNP3DecodeObjectG120V7(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG120V7(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(120, 8): - rc = DNP3DecodeObjectG120V8(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG120V8(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(120, 9): - rc = DNP3DecodeObjectG120V9(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG120V9(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(120, 10): - rc = DNP3DecodeObjectG120V10(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG120V10(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(120, 11): - rc = DNP3DecodeObjectG120V11(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG120V11(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(120, 12): - rc = DNP3DecodeObjectG120V12(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG120V12(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(120, 13): - rc = DNP3DecodeObjectG120V13(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG120V13(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(120, 14): - rc = DNP3DecodeObjectG120V14(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG120V14(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(120, 15): - rc = DNP3DecodeObjectG120V15(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG120V15(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(121, 1): - rc = DNP3DecodeObjectG121V1(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG121V1(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(122, 1): - rc = DNP3DecodeObjectG122V1(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG122V1(buf, len, prefix_code, start, count, points); break; case DNP3_OBJECT_CODE(122, 2): - rc = DNP3DecodeObjectG122V2(buf, len, prefix_code, start, count, - points); + rc = DNP3DecodeObjectG122V2(buf, len, prefix_code, start, count, points); break; default: return DNP3_DECODER_EVENT_UNKNOWN_OBJECT; diff --git a/src/app-layer-dnp3-objects.h b/src/app-layer-dnp3-objects.h index e292f012758b..72b61cd8472c 100644 --- a/src/app-layer-dnp3-objects.h +++ b/src/app-layer-dnp3-objects.h @@ -39,14 +39,14 @@ typedef struct DNP3ObjectG1V1_ { } DNP3ObjectG1V1; typedef struct DNP3ObjectG1V2_ { - uint8_t online:1; - uint8_t restart:1; - uint8_t comm_lost:1; - uint8_t remote_forced:1; - uint8_t local_forced:1; - uint8_t chatter_filter:1; - uint8_t reserved:1; - uint8_t state:1; + uint8_t online : 1; + uint8_t restart : 1; + uint8_t comm_lost : 1; + uint8_t remote_forced : 1; + uint8_t local_forced : 1; + uint8_t chatter_filter : 1; + uint8_t reserved : 1; + uint8_t state : 1; } DNP3ObjectG1V2; typedef struct DNP3ObjectG2V1_ { @@ -54,26 +54,26 @@ typedef struct DNP3ObjectG2V1_ { } DNP3ObjectG2V1; typedef struct DNP3ObjectG2V2_ { - uint8_t online:1; - uint8_t restart:1; - uint8_t comm_lost:1; - uint8_t remote_forced:1; - uint8_t local_forced:1; - uint8_t chatter_filter:1; - uint8_t reserved:1; - uint8_t state:1; + uint8_t online : 1; + uint8_t restart : 1; + uint8_t comm_lost : 1; + uint8_t remote_forced : 1; + uint8_t local_forced : 1; + uint8_t chatter_filter : 1; + uint8_t reserved : 1; + uint8_t state : 1; uint64_t timestamp; } DNP3ObjectG2V2; typedef struct DNP3ObjectG2V3_ { - uint8_t online:1; - uint8_t restart:1; - uint8_t comm_lost:1; - uint8_t remote_forced:1; - uint8_t local_forced:1; - uint8_t chatter_filter:1; - uint8_t reserved:1; - uint8_t state:1; + uint8_t online : 1; + uint8_t restart : 1; + uint8_t comm_lost : 1; + uint8_t remote_forced : 1; + uint8_t local_forced : 1; + uint8_t chatter_filter : 1; + uint8_t reserved : 1; + uint8_t state : 1; uint16_t timestamp; } DNP3ObjectG2V3; @@ -82,44 +82,44 @@ typedef struct DNP3ObjectG3V1_ { } DNP3ObjectG3V1; typedef struct DNP3ObjectG3V2_ { - uint8_t online:1; - uint8_t restart:1; - uint8_t comm_lost:1; - uint8_t remote_forced:1; - uint8_t local_forced:1; - uint8_t chatter_filter:1; - uint8_t state:2; + uint8_t online : 1; + uint8_t restart : 1; + uint8_t comm_lost : 1; + uint8_t remote_forced : 1; + uint8_t local_forced : 1; + uint8_t chatter_filter : 1; + uint8_t state : 2; } DNP3ObjectG3V2; typedef struct DNP3ObjectG4V1_ { - uint8_t online:1; - uint8_t restart:1; - uint8_t comm_lost:1; - uint8_t remote_forced:1; - uint8_t local_forced:1; - uint8_t chatter_filter:1; - uint8_t state:2; + uint8_t online : 1; + uint8_t restart : 1; + uint8_t comm_lost : 1; + uint8_t remote_forced : 1; + uint8_t local_forced : 1; + uint8_t chatter_filter : 1; + uint8_t state : 2; } DNP3ObjectG4V1; typedef struct DNP3ObjectG4V2_ { - uint8_t online:1; - uint8_t restart:1; - uint8_t comm_lost:1; - uint8_t remote_forced:1; - uint8_t local_forced:1; - uint8_t chatter_filter:1; - uint8_t state:2; + uint8_t online : 1; + uint8_t restart : 1; + uint8_t comm_lost : 1; + uint8_t remote_forced : 1; + uint8_t local_forced : 1; + uint8_t chatter_filter : 1; + uint8_t state : 2; uint64_t timestamp; } DNP3ObjectG4V2; typedef struct DNP3ObjectG4V3_ { - uint8_t online:1; - uint8_t restart:1; - uint8_t comm_lost:1; - uint8_t remote_forced:1; - uint8_t local_forced:1; - uint8_t chatter_filter:1; - uint8_t state:2; + uint8_t online : 1; + uint8_t restart : 1; + uint8_t comm_lost : 1; + uint8_t remote_forced : 1; + uint8_t local_forced : 1; + uint8_t chatter_filter : 1; + uint8_t state : 2; uint16_t relative_time_ms; } DNP3ObjectG4V3; @@ -128,61 +128,61 @@ typedef struct DNP3ObjectG10V1_ { } DNP3ObjectG10V1; typedef struct DNP3ObjectG10V2_ { - uint8_t online:1; - uint8_t restart:1; - uint8_t comm_lost:1; - uint8_t remote_forced:1; - uint8_t local_forced:1; - uint8_t reserved0:1; - uint8_t reserved1:1; - uint8_t state:1; + uint8_t online : 1; + uint8_t restart : 1; + uint8_t comm_lost : 1; + uint8_t remote_forced : 1; + uint8_t local_forced : 1; + uint8_t reserved0 : 1; + uint8_t reserved1 : 1; + uint8_t state : 1; } DNP3ObjectG10V2; typedef struct DNP3ObjectG11V1_ { - uint8_t online:1; - uint8_t restart:1; - uint8_t comm_lost:1; - uint8_t remote_forced:1; - uint8_t local_forced:1; - uint8_t reserved0:1; - uint8_t reserved1:1; - uint8_t state:1; + uint8_t online : 1; + uint8_t restart : 1; + uint8_t comm_lost : 1; + uint8_t remote_forced : 1; + uint8_t local_forced : 1; + uint8_t reserved0 : 1; + uint8_t reserved1 : 1; + uint8_t state : 1; } DNP3ObjectG11V1; typedef struct DNP3ObjectG11V2_ { - uint8_t online:1; - uint8_t restart:1; - uint8_t comm_lost:1; - uint8_t remote_forced:1; - uint8_t local_forced:1; - uint8_t reserved0:1; - uint8_t reserved1:1; - uint8_t state:1; + uint8_t online : 1; + uint8_t restart : 1; + uint8_t comm_lost : 1; + uint8_t remote_forced : 1; + uint8_t local_forced : 1; + uint8_t reserved0 : 1; + uint8_t reserved1 : 1; + uint8_t state : 1; uint64_t timestamp; } DNP3ObjectG11V2; typedef struct DNP3ObjectG12V1_ { - uint8_t op_type:4; - uint8_t qu:1; - uint8_t cr:1; - uint8_t tcc:2; + uint8_t op_type : 4; + uint8_t qu : 1; + uint8_t cr : 1; + uint8_t tcc : 2; uint8_t count; uint32_t ontime; uint32_t offtime; - uint8_t status_code:7; - uint8_t reserved:1; + uint8_t status_code : 7; + uint8_t reserved : 1; } DNP3ObjectG12V1; typedef struct DNP3ObjectG12V2_ { - uint8_t op_type:4; - uint8_t qu:1; - uint8_t cr:1; - uint8_t tcc:2; + uint8_t op_type : 4; + uint8_t qu : 1; + uint8_t cr : 1; + uint8_t tcc : 2; uint8_t count; uint32_t ontime; uint32_t offtime; - uint8_t status_code:7; - uint8_t reserved:1; + uint8_t status_code : 7; + uint8_t reserved : 1; } DNP3ObjectG12V2; typedef struct DNP3ObjectG12V3_ { @@ -190,61 +190,61 @@ typedef struct DNP3ObjectG12V3_ { } DNP3ObjectG12V3; typedef struct DNP3ObjectG13V1_ { - uint8_t status_code:7; - uint8_t commanded_state:1; + uint8_t status_code : 7; + uint8_t commanded_state : 1; } DNP3ObjectG13V1; typedef struct DNP3ObjectG13V2_ { - uint8_t status_code:7; - uint8_t commanded_state:1; + uint8_t status_code : 7; + uint8_t commanded_state : 1; uint64_t timestamp; } DNP3ObjectG13V2; typedef struct DNP3ObjectG20V1_ { - uint8_t online:1; - uint8_t restart:1; - uint8_t comm_lost:1; - uint8_t remote_forced:1; - uint8_t local_forced:1; - uint8_t rollover:1; - uint8_t discontinuity:1; - uint8_t reserved0:1; + uint8_t online : 1; + uint8_t restart : 1; + uint8_t comm_lost : 1; + uint8_t remote_forced : 1; + uint8_t local_forced : 1; + uint8_t rollover : 1; + uint8_t discontinuity : 1; + uint8_t reserved0 : 1; uint32_t count; } DNP3ObjectG20V1; typedef struct DNP3ObjectG20V2_ { - uint8_t online:1; - uint8_t restart:1; - uint8_t comm_lost:1; - uint8_t remote_forced:1; - uint8_t local_forced:1; - uint8_t rollover:1; - uint8_t discontinuity:1; - uint8_t reserved0:1; + uint8_t online : 1; + uint8_t restart : 1; + uint8_t comm_lost : 1; + uint8_t remote_forced : 1; + uint8_t local_forced : 1; + uint8_t rollover : 1; + uint8_t discontinuity : 1; + uint8_t reserved0 : 1; uint16_t count; } DNP3ObjectG20V2; typedef struct DNP3ObjectG20V3_ { - uint8_t online:1; - uint8_t restart:1; - uint8_t comm_lost:1; - uint8_t remote_forced:1; - uint8_t local_forced:1; - uint8_t rollover:1; - uint8_t reserved0:1; - uint8_t reserved1:1; + uint8_t online : 1; + uint8_t restart : 1; + uint8_t comm_lost : 1; + uint8_t remote_forced : 1; + uint8_t local_forced : 1; + uint8_t rollover : 1; + uint8_t reserved0 : 1; + uint8_t reserved1 : 1; uint32_t count; } DNP3ObjectG20V3; typedef struct DNP3ObjectG20V4_ { - uint8_t online:1; - uint8_t restart:1; - uint8_t comm_lost:1; - uint8_t remote_forced:1; - uint8_t local_forced:1; - uint8_t rollover:1; - uint8_t reserved0:1; - uint8_t reserved1:1; + uint8_t online : 1; + uint8_t restart : 1; + uint8_t comm_lost : 1; + uint8_t remote_forced : 1; + uint8_t local_forced : 1; + uint8_t rollover : 1; + uint8_t reserved0 : 1; + uint8_t reserved1 : 1; uint16_t count; } DNP3ObjectG20V4; @@ -265,101 +265,101 @@ typedef struct DNP3ObjectG20V8_ { } DNP3ObjectG20V8; typedef struct DNP3ObjectG21V1_ { - uint8_t online:1; - uint8_t restart:1; - uint8_t comm_lost:1; - uint8_t remote_forced:1; - uint8_t local_forced:1; - uint8_t rollover:1; - uint8_t discontinuity:1; - uint8_t reserved0:1; + uint8_t online : 1; + uint8_t restart : 1; + uint8_t comm_lost : 1; + uint8_t remote_forced : 1; + uint8_t local_forced : 1; + uint8_t rollover : 1; + uint8_t discontinuity : 1; + uint8_t reserved0 : 1; uint32_t count; } DNP3ObjectG21V1; typedef struct DNP3ObjectG21V2_ { - uint8_t online:1; - uint8_t restart:1; - uint8_t comm_lost:1; - uint8_t remote_forced:1; - uint8_t local_forced:1; - uint8_t rollover:1; - uint8_t discontinuity:1; - uint8_t reserved0:1; + uint8_t online : 1; + uint8_t restart : 1; + uint8_t comm_lost : 1; + uint8_t remote_forced : 1; + uint8_t local_forced : 1; + uint8_t rollover : 1; + uint8_t discontinuity : 1; + uint8_t reserved0 : 1; uint16_t count; } DNP3ObjectG21V2; typedef struct DNP3ObjectG21V3_ { - uint8_t online:1; - uint8_t restart:1; - uint8_t comm_lost:1; - uint8_t remote_forced:1; - uint8_t local_forced:1; - uint8_t rollover:1; - uint8_t reserved0:1; - uint8_t reserved1:1; + uint8_t online : 1; + uint8_t restart : 1; + uint8_t comm_lost : 1; + uint8_t remote_forced : 1; + uint8_t local_forced : 1; + uint8_t rollover : 1; + uint8_t reserved0 : 1; + uint8_t reserved1 : 1; uint32_t count; } DNP3ObjectG21V3; typedef struct DNP3ObjectG21V4_ { - uint8_t online:1; - uint8_t restart:1; - uint8_t comm_lost:1; - uint8_t remote_forced:1; - uint8_t local_forced:1; - uint8_t rollover:1; - uint8_t reserved0:1; - uint8_t reserved1:1; + uint8_t online : 1; + uint8_t restart : 1; + uint8_t comm_lost : 1; + uint8_t remote_forced : 1; + uint8_t local_forced : 1; + uint8_t rollover : 1; + uint8_t reserved0 : 1; + uint8_t reserved1 : 1; uint16_t count; } DNP3ObjectG21V4; typedef struct DNP3ObjectG21V5_ { - uint8_t online:1; - uint8_t restart:1; - uint8_t comm_lost:1; - uint8_t remote_forced:1; - uint8_t local_forced:1; - uint8_t rollover:1; - uint8_t discontinuity:1; - uint8_t reserved1:1; + uint8_t online : 1; + uint8_t restart : 1; + uint8_t comm_lost : 1; + uint8_t remote_forced : 1; + uint8_t local_forced : 1; + uint8_t rollover : 1; + uint8_t discontinuity : 1; + uint8_t reserved1 : 1; uint32_t count; uint64_t timestamp; } DNP3ObjectG21V5; typedef struct DNP3ObjectG21V6_ { - uint8_t online:1; - uint8_t restart:1; - uint8_t comm_lost:1; - uint8_t remote_forced:1; - uint8_t local_forced:1; - uint8_t rollover:1; - uint8_t discontinuity:1; - uint8_t reserved1:1; + uint8_t online : 1; + uint8_t restart : 1; + uint8_t comm_lost : 1; + uint8_t remote_forced : 1; + uint8_t local_forced : 1; + uint8_t rollover : 1; + uint8_t discontinuity : 1; + uint8_t reserved1 : 1; uint16_t count; uint64_t timestamp; } DNP3ObjectG21V6; typedef struct DNP3ObjectG21V7_ { - uint8_t online:1; - uint8_t restart:1; - uint8_t comm_lost:1; - uint8_t remote_forced:1; - uint8_t local_forced:1; - uint8_t rollover:1; - uint8_t reserved0:1; - uint8_t reserved1:1; + uint8_t online : 1; + uint8_t restart : 1; + uint8_t comm_lost : 1; + uint8_t remote_forced : 1; + uint8_t local_forced : 1; + uint8_t rollover : 1; + uint8_t reserved0 : 1; + uint8_t reserved1 : 1; uint32_t count; uint64_t timestamp; } DNP3ObjectG21V7; typedef struct DNP3ObjectG21V8_ { - uint8_t online:1; - uint8_t restart:1; - uint8_t comm_lost:1; - uint8_t remote_forced:1; - uint8_t local_forced:1; - uint8_t rollover:1; - uint8_t reserved0:1; - uint8_t reserved1:1; + uint8_t online : 1; + uint8_t restart : 1; + uint8_t comm_lost : 1; + uint8_t remote_forced : 1; + uint8_t local_forced : 1; + uint8_t rollover : 1; + uint8_t reserved0 : 1; + uint8_t reserved1 : 1; uint16_t count; uint64_t timestamp; } DNP3ObjectG21V8; @@ -381,226 +381,226 @@ typedef struct DNP3ObjectG21V12_ { } DNP3ObjectG21V12; typedef struct DNP3ObjectG22V1_ { - uint8_t online:1; - uint8_t restart:1; - uint8_t comm_lost:1; - uint8_t remote_forced:1; - uint8_t local_forced:1; - uint8_t rollover:1; - uint8_t discontinuity:1; - uint8_t reserved0:1; + uint8_t online : 1; + uint8_t restart : 1; + uint8_t comm_lost : 1; + uint8_t remote_forced : 1; + uint8_t local_forced : 1; + uint8_t rollover : 1; + uint8_t discontinuity : 1; + uint8_t reserved0 : 1; uint32_t count; } DNP3ObjectG22V1; typedef struct DNP3ObjectG22V2_ { - uint8_t online:1; - uint8_t restart:1; - uint8_t comm_lost:1; - uint8_t remote_forced:1; - uint8_t local_forced:1; - uint8_t rollover:1; - uint8_t discontinuity:1; - uint8_t reserved0:1; + uint8_t online : 1; + uint8_t restart : 1; + uint8_t comm_lost : 1; + uint8_t remote_forced : 1; + uint8_t local_forced : 1; + uint8_t rollover : 1; + uint8_t discontinuity : 1; + uint8_t reserved0 : 1; uint16_t count; } DNP3ObjectG22V2; typedef struct DNP3ObjectG22V3_ { - uint8_t online:1; - uint8_t restart:1; - uint8_t comm_lost:1; - uint8_t remote_forced:1; - uint8_t local_forced:1; - uint8_t rollover:1; - uint8_t reserved0:1; - uint8_t reserved1:1; + uint8_t online : 1; + uint8_t restart : 1; + uint8_t comm_lost : 1; + uint8_t remote_forced : 1; + uint8_t local_forced : 1; + uint8_t rollover : 1; + uint8_t reserved0 : 1; + uint8_t reserved1 : 1; uint32_t count; } DNP3ObjectG22V3; typedef struct DNP3ObjectG22V4_ { - uint8_t online:1; - uint8_t restart:1; - uint8_t comm_lost:1; - uint8_t remote_forced:1; - uint8_t local_forced:1; - uint8_t rollover:1; - uint8_t reserved0:1; - uint8_t reserved1:1; + uint8_t online : 1; + uint8_t restart : 1; + uint8_t comm_lost : 1; + uint8_t remote_forced : 1; + uint8_t local_forced : 1; + uint8_t rollover : 1; + uint8_t reserved0 : 1; + uint8_t reserved1 : 1; uint16_t count; } DNP3ObjectG22V4; typedef struct DNP3ObjectG22V5_ { - uint8_t online:1; - uint8_t restart:1; - uint8_t comm_lost:1; - uint8_t remote_forced:1; - uint8_t local_forced:1; - uint8_t rollover:1; - uint8_t reserved0:1; - uint8_t reserved1:1; + uint8_t online : 1; + uint8_t restart : 1; + uint8_t comm_lost : 1; + uint8_t remote_forced : 1; + uint8_t local_forced : 1; + uint8_t rollover : 1; + uint8_t reserved0 : 1; + uint8_t reserved1 : 1; uint32_t count; uint64_t timestamp; } DNP3ObjectG22V5; typedef struct DNP3ObjectG22V6_ { - uint8_t online:1; - uint8_t restart:1; - uint8_t comm_lost:1; - uint8_t remote_forced:1; - uint8_t local_forced:1; - uint8_t rollover:1; - uint8_t discontinuity:1; - uint8_t reserved0:1; + uint8_t online : 1; + uint8_t restart : 1; + uint8_t comm_lost : 1; + uint8_t remote_forced : 1; + uint8_t local_forced : 1; + uint8_t rollover : 1; + uint8_t discontinuity : 1; + uint8_t reserved0 : 1; uint16_t count; uint64_t timestamp; } DNP3ObjectG22V6; typedef struct DNP3ObjectG22V7_ { - uint8_t online:1; - uint8_t restart:1; - uint8_t comm_lost:1; - uint8_t remote_forced:1; - uint8_t local_forced:1; - uint8_t rollover:1; - uint8_t reserved0:1; - uint8_t reserved1:1; + uint8_t online : 1; + uint8_t restart : 1; + uint8_t comm_lost : 1; + uint8_t remote_forced : 1; + uint8_t local_forced : 1; + uint8_t rollover : 1; + uint8_t reserved0 : 1; + uint8_t reserved1 : 1; uint32_t count; uint64_t timestamp; } DNP3ObjectG22V7; typedef struct DNP3ObjectG22V8_ { - uint8_t online:1; - uint8_t restart:1; - uint8_t comm_lost:1; - uint8_t remote_forced:1; - uint8_t local_forced:1; - uint8_t rollover:1; - uint8_t reserved0:1; - uint8_t reserved1:1; + uint8_t online : 1; + uint8_t restart : 1; + uint8_t comm_lost : 1; + uint8_t remote_forced : 1; + uint8_t local_forced : 1; + uint8_t rollover : 1; + uint8_t reserved0 : 1; + uint8_t reserved1 : 1; uint16_t count; uint64_t timestamp; } DNP3ObjectG22V8; typedef struct DNP3ObjectG23V1_ { - uint8_t online:1; - uint8_t restart:1; - uint8_t comm_lost:1; - uint8_t remote_forced:1; - uint8_t local_forced:1; - uint8_t rollover:1; - uint8_t discontinuity:1; - uint8_t reserved0:1; + uint8_t online : 1; + uint8_t restart : 1; + uint8_t comm_lost : 1; + uint8_t remote_forced : 1; + uint8_t local_forced : 1; + uint8_t rollover : 1; + uint8_t discontinuity : 1; + uint8_t reserved0 : 1; uint32_t count; } DNP3ObjectG23V1; typedef struct DNP3ObjectG23V2_ { - uint8_t online:1; - uint8_t restart:1; - uint8_t comm_lost:1; - uint8_t remote_forced:1; - uint8_t local_forced:1; - uint8_t rollover:1; - uint8_t reserved0:1; - uint8_t reserved1:1; + uint8_t online : 1; + uint8_t restart : 1; + uint8_t comm_lost : 1; + uint8_t remote_forced : 1; + uint8_t local_forced : 1; + uint8_t rollover : 1; + uint8_t reserved0 : 1; + uint8_t reserved1 : 1; uint16_t count; } DNP3ObjectG23V2; typedef struct DNP3ObjectG23V3_ { - uint8_t online:1; - uint8_t restart:1; - uint8_t comm_lost:1; - uint8_t remote_forced:1; - uint8_t local_forced:1; - uint8_t rollover:1; - uint8_t reserved0:1; - uint8_t reserved1:1; + uint8_t online : 1; + uint8_t restart : 1; + uint8_t comm_lost : 1; + uint8_t remote_forced : 1; + uint8_t local_forced : 1; + uint8_t rollover : 1; + uint8_t reserved0 : 1; + uint8_t reserved1 : 1; uint32_t count; } DNP3ObjectG23V3; typedef struct DNP3ObjectG23V4_ { - uint8_t online:1; - uint8_t restart:1; - uint8_t comm_lost:1; - uint8_t remote_forced:1; - uint8_t local_forced:1; - uint8_t rollover:1; - uint8_t reserved0:1; - uint8_t reserved1:1; + uint8_t online : 1; + uint8_t restart : 1; + uint8_t comm_lost : 1; + uint8_t remote_forced : 1; + uint8_t local_forced : 1; + uint8_t rollover : 1; + uint8_t reserved0 : 1; + uint8_t reserved1 : 1; uint16_t count; } DNP3ObjectG23V4; typedef struct DNP3ObjectG23V5_ { - uint8_t online:1; - uint8_t restart:1; - uint8_t comm_lost:1; - uint8_t remote_forced:1; - uint8_t local_forced:1; - uint8_t rollover:1; - uint8_t discontinuity:1; - uint8_t reserved0:1; + uint8_t online : 1; + uint8_t restart : 1; + uint8_t comm_lost : 1; + uint8_t remote_forced : 1; + uint8_t local_forced : 1; + uint8_t rollover : 1; + uint8_t discontinuity : 1; + uint8_t reserved0 : 1; uint32_t count; uint64_t timestamp; } DNP3ObjectG23V5; typedef struct DNP3ObjectG23V6_ { - uint8_t online:1; - uint8_t restart:1; - uint8_t comm_lost:1; - uint8_t remote_forced:1; - uint8_t local_forced:1; - uint8_t rollover:1; - uint8_t discontinuity:1; - uint8_t reserved0:1; + uint8_t online : 1; + uint8_t restart : 1; + uint8_t comm_lost : 1; + uint8_t remote_forced : 1; + uint8_t local_forced : 1; + uint8_t rollover : 1; + uint8_t discontinuity : 1; + uint8_t reserved0 : 1; uint16_t count; uint64_t timestamp; } DNP3ObjectG23V6; typedef struct DNP3ObjectG23V7_ { - uint8_t online:1; - uint8_t restart:1; - uint8_t comm_lost:1; - uint8_t remote_forced:1; - uint8_t local_forced:1; - uint8_t rollover:1; - uint8_t reserved0:1; - uint8_t reserved1:1; + uint8_t online : 1; + uint8_t restart : 1; + uint8_t comm_lost : 1; + uint8_t remote_forced : 1; + uint8_t local_forced : 1; + uint8_t rollover : 1; + uint8_t reserved0 : 1; + uint8_t reserved1 : 1; uint32_t count; uint64_t timestamp; } DNP3ObjectG23V7; typedef struct DNP3ObjectG23V8_ { - uint8_t online:1; - uint8_t restart:1; - uint8_t comm_lost:1; - uint8_t remote_forced:1; - uint8_t local_forced:1; - uint8_t rollover:1; - uint8_t reserved0:1; - uint8_t reserved1:1; + uint8_t online : 1; + uint8_t restart : 1; + uint8_t comm_lost : 1; + uint8_t remote_forced : 1; + uint8_t local_forced : 1; + uint8_t rollover : 1; + uint8_t reserved0 : 1; + uint8_t reserved1 : 1; uint16_t count; uint64_t timestamp; } DNP3ObjectG23V8; typedef struct DNP3ObjectG30V1_ { - uint8_t online:1; - uint8_t restart:1; - uint8_t comm_lost:1; - uint8_t remote_forced:1; - uint8_t local_forced:1; - uint8_t over_range:1; - uint8_t reference_err:1; - uint8_t reserved0:1; + uint8_t online : 1; + uint8_t restart : 1; + uint8_t comm_lost : 1; + uint8_t remote_forced : 1; + uint8_t local_forced : 1; + uint8_t over_range : 1; + uint8_t reference_err : 1; + uint8_t reserved0 : 1; int32_t value; } DNP3ObjectG30V1; typedef struct DNP3ObjectG30V2_ { - uint8_t online:1; - uint8_t restart:1; - uint8_t comm_lost:1; - uint8_t remote_forced:1; - uint8_t local_forced:1; - uint8_t over_range:1; - uint8_t reference_err:1; - uint8_t reserved0:1; + uint8_t online : 1; + uint8_t restart : 1; + uint8_t comm_lost : 1; + uint8_t remote_forced : 1; + uint8_t local_forced : 1; + uint8_t over_range : 1; + uint8_t reference_err : 1; + uint8_t reserved0 : 1; int16_t value; } DNP3ObjectG30V2; @@ -613,75 +613,75 @@ typedef struct DNP3ObjectG30V4_ { } DNP3ObjectG30V4; typedef struct DNP3ObjectG30V5_ { - uint8_t online:1; - uint8_t restart:1; - uint8_t comm_lost:1; - uint8_t remote_forced:1; - uint8_t local_forced:1; - uint8_t over_range:1; - uint8_t reference_err:1; - uint8_t reserved0:1; + uint8_t online : 1; + uint8_t restart : 1; + uint8_t comm_lost : 1; + uint8_t remote_forced : 1; + uint8_t local_forced : 1; + uint8_t over_range : 1; + uint8_t reference_err : 1; + uint8_t reserved0 : 1; float value; } DNP3ObjectG30V5; typedef struct DNP3ObjectG30V6_ { - uint8_t online:1; - uint8_t restart:1; - uint8_t comm_lost:1; - uint8_t remote_forced:1; - uint8_t local_forced:1; - uint8_t over_range:1; - uint8_t reference_err:1; - uint8_t reserved0:1; + uint8_t online : 1; + uint8_t restart : 1; + uint8_t comm_lost : 1; + uint8_t remote_forced : 1; + uint8_t local_forced : 1; + uint8_t over_range : 1; + uint8_t reference_err : 1; + uint8_t reserved0 : 1; double value; } DNP3ObjectG30V6; typedef struct DNP3ObjectG31V1_ { - uint8_t online:1; - uint8_t restart:1; - uint8_t comm_lost:1; - uint8_t remote_forced:1; - uint8_t local_forced:1; - uint8_t over_range:1; - uint8_t reference_err:1; - uint8_t reserved0:1; + uint8_t online : 1; + uint8_t restart : 1; + uint8_t comm_lost : 1; + uint8_t remote_forced : 1; + uint8_t local_forced : 1; + uint8_t over_range : 1; + uint8_t reference_err : 1; + uint8_t reserved0 : 1; int32_t value; } DNP3ObjectG31V1; typedef struct DNP3ObjectG31V2_ { - uint8_t online:1; - uint8_t restart:1; - uint8_t comm_lost:1; - uint8_t remote_forced:1; - uint8_t local_forced:1; - uint8_t over_range:1; - uint8_t reference_err:1; - uint8_t reserved0:1; + uint8_t online : 1; + uint8_t restart : 1; + uint8_t comm_lost : 1; + uint8_t remote_forced : 1; + uint8_t local_forced : 1; + uint8_t over_range : 1; + uint8_t reference_err : 1; + uint8_t reserved0 : 1; int16_t value; } DNP3ObjectG31V2; typedef struct DNP3ObjectG31V3_ { - uint8_t online:1; - uint8_t restart:1; - uint8_t comm_lost:1; - uint8_t remote_forced:1; - uint8_t local_forced:1; - uint8_t over_range:1; - uint8_t reference_err:1; - uint8_t reserved0:1; + uint8_t online : 1; + uint8_t restart : 1; + uint8_t comm_lost : 1; + uint8_t remote_forced : 1; + uint8_t local_forced : 1; + uint8_t over_range : 1; + uint8_t reference_err : 1; + uint8_t reserved0 : 1; int32_t value; uint64_t timestamp; } DNP3ObjectG31V3; typedef struct DNP3ObjectG31V4_ { - uint8_t online:1; - uint8_t restart:1; - uint8_t comm_lost:1; - uint8_t remote_forced:1; - uint8_t local_forced:1; - uint8_t over_range:1; - uint8_t reference_err:1; - uint8_t reserved0:1; + uint8_t online : 1; + uint8_t restart : 1; + uint8_t comm_lost : 1; + uint8_t remote_forced : 1; + uint8_t local_forced : 1; + uint8_t over_range : 1; + uint8_t reference_err : 1; + uint8_t reserved0 : 1; int16_t value; uint64_t timestamp; } DNP3ObjectG31V4; @@ -695,225 +695,225 @@ typedef struct DNP3ObjectG31V6_ { } DNP3ObjectG31V6; typedef struct DNP3ObjectG31V7_ { - uint8_t online:1; - uint8_t restart:1; - uint8_t comm_lost:1; - uint8_t remote_forced:1; - uint8_t local_forced:1; - uint8_t over_range:1; - uint8_t reference_err:1; - uint8_t reserved0:1; + uint8_t online : 1; + uint8_t restart : 1; + uint8_t comm_lost : 1; + uint8_t remote_forced : 1; + uint8_t local_forced : 1; + uint8_t over_range : 1; + uint8_t reference_err : 1; + uint8_t reserved0 : 1; float value; } DNP3ObjectG31V7; typedef struct DNP3ObjectG31V8_ { - uint8_t online:1; - uint8_t restart:1; - uint8_t comm_lost:1; - uint8_t remote_forced:1; - uint8_t local_forced:1; - uint8_t over_range:1; - uint8_t reference_err:1; - uint8_t reserved0:1; + uint8_t online : 1; + uint8_t restart : 1; + uint8_t comm_lost : 1; + uint8_t remote_forced : 1; + uint8_t local_forced : 1; + uint8_t over_range : 1; + uint8_t reference_err : 1; + uint8_t reserved0 : 1; double value; } DNP3ObjectG31V8; typedef struct DNP3ObjectG32V1_ { - uint8_t online:1; - uint8_t restart:1; - uint8_t comm_lost:1; - uint8_t remote_forced:1; - uint8_t local_forced:1; - uint8_t over_range:1; - uint8_t reference_err:1; - uint8_t reserved0:1; + uint8_t online : 1; + uint8_t restart : 1; + uint8_t comm_lost : 1; + uint8_t remote_forced : 1; + uint8_t local_forced : 1; + uint8_t over_range : 1; + uint8_t reference_err : 1; + uint8_t reserved0 : 1; int32_t value; } DNP3ObjectG32V1; typedef struct DNP3ObjectG32V2_ { - uint8_t online:1; - uint8_t restart:1; - uint8_t comm_lost:1; - uint8_t remote_forced:1; - uint8_t local_forced:1; - uint8_t over_range:1; - uint8_t reference_err:1; - uint8_t reserved0:1; + uint8_t online : 1; + uint8_t restart : 1; + uint8_t comm_lost : 1; + uint8_t remote_forced : 1; + uint8_t local_forced : 1; + uint8_t over_range : 1; + uint8_t reference_err : 1; + uint8_t reserved0 : 1; int16_t value; } DNP3ObjectG32V2; typedef struct DNP3ObjectG32V3_ { - uint8_t online:1; - uint8_t restart:1; - uint8_t comm_lost:1; - uint8_t remote_forced:1; - uint8_t local_forced:1; - uint8_t over_range:1; - uint8_t reference_err:1; - uint8_t reserved0:1; + uint8_t online : 1; + uint8_t restart : 1; + uint8_t comm_lost : 1; + uint8_t remote_forced : 1; + uint8_t local_forced : 1; + uint8_t over_range : 1; + uint8_t reference_err : 1; + uint8_t reserved0 : 1; int32_t value; uint64_t timestamp; } DNP3ObjectG32V3; typedef struct DNP3ObjectG32V4_ { - uint8_t online:1; - uint8_t restart:1; - uint8_t comm_lost:1; - uint8_t remote_forced:1; - uint8_t local_forced:1; - uint8_t over_range:1; - uint8_t reference_err:1; - uint8_t reserved0:1; + uint8_t online : 1; + uint8_t restart : 1; + uint8_t comm_lost : 1; + uint8_t remote_forced : 1; + uint8_t local_forced : 1; + uint8_t over_range : 1; + uint8_t reference_err : 1; + uint8_t reserved0 : 1; int16_t value; uint64_t timestamp; } DNP3ObjectG32V4; typedef struct DNP3ObjectG32V5_ { - uint8_t online:1; - uint8_t restart:1; - uint8_t comm_lost:1; - uint8_t remote_forced:1; - uint8_t local_forced:1; - uint8_t over_range:1; - uint8_t reference_err:1; - uint8_t reserved0:1; + uint8_t online : 1; + uint8_t restart : 1; + uint8_t comm_lost : 1; + uint8_t remote_forced : 1; + uint8_t local_forced : 1; + uint8_t over_range : 1; + uint8_t reference_err : 1; + uint8_t reserved0 : 1; float value; } DNP3ObjectG32V5; typedef struct DNP3ObjectG32V6_ { - uint8_t online:1; - uint8_t restart:1; - uint8_t comm_lost:1; - uint8_t remote_forced:1; - uint8_t local_forced:1; - uint8_t over_range:1; - uint8_t reference_err:1; - uint8_t reserved0:1; + uint8_t online : 1; + uint8_t restart : 1; + uint8_t comm_lost : 1; + uint8_t remote_forced : 1; + uint8_t local_forced : 1; + uint8_t over_range : 1; + uint8_t reference_err : 1; + uint8_t reserved0 : 1; double value; } DNP3ObjectG32V6; typedef struct DNP3ObjectG32V7_ { - uint8_t online:1; - uint8_t restart:1; - uint8_t comm_lost:1; - uint8_t remote_forced:1; - uint8_t local_forced:1; - uint8_t over_range:1; - uint8_t reference_err:1; - uint8_t reserved0:1; + uint8_t online : 1; + uint8_t restart : 1; + uint8_t comm_lost : 1; + uint8_t remote_forced : 1; + uint8_t local_forced : 1; + uint8_t over_range : 1; + uint8_t reference_err : 1; + uint8_t reserved0 : 1; float value; uint64_t timestamp; } DNP3ObjectG32V7; typedef struct DNP3ObjectG32V8_ { - uint8_t online:1; - uint8_t restart:1; - uint8_t comm_lost:1; - uint8_t remote_forced:1; - uint8_t local_forced:1; - uint8_t over_range:1; - uint8_t reference_err:1; - uint8_t reserved0:1; + uint8_t online : 1; + uint8_t restart : 1; + uint8_t comm_lost : 1; + uint8_t remote_forced : 1; + uint8_t local_forced : 1; + uint8_t over_range : 1; + uint8_t reference_err : 1; + uint8_t reserved0 : 1; double value; uint64_t timestamp; } DNP3ObjectG32V8; typedef struct DNP3ObjectG33V1_ { - uint8_t online:1; - uint8_t restart:1; - uint8_t comm_lost:1; - uint8_t remote_forced:1; - uint8_t local_forced:1; - uint8_t over_range:1; - uint8_t reference_err:1; - uint8_t reserved0:1; + uint8_t online : 1; + uint8_t restart : 1; + uint8_t comm_lost : 1; + uint8_t remote_forced : 1; + uint8_t local_forced : 1; + uint8_t over_range : 1; + uint8_t reference_err : 1; + uint8_t reserved0 : 1; int32_t value; } DNP3ObjectG33V1; typedef struct DNP3ObjectG33V2_ { - uint8_t online:1; - uint8_t restart:1; - uint8_t comm_lost:1; - uint8_t remote_forced:1; - uint8_t local_forced:1; - uint8_t over_range:1; - uint8_t reference_err:1; - uint8_t reserved0:1; + uint8_t online : 1; + uint8_t restart : 1; + uint8_t comm_lost : 1; + uint8_t remote_forced : 1; + uint8_t local_forced : 1; + uint8_t over_range : 1; + uint8_t reference_err : 1; + uint8_t reserved0 : 1; int16_t value; } DNP3ObjectG33V2; typedef struct DNP3ObjectG33V3_ { - uint8_t online:1; - uint8_t restart:1; - uint8_t comm_lost:1; - uint8_t remote_forced:1; - uint8_t local_forced:1; - uint8_t over_range:1; - uint8_t reference_err:1; - uint8_t reserved0:1; + uint8_t online : 1; + uint8_t restart : 1; + uint8_t comm_lost : 1; + uint8_t remote_forced : 1; + uint8_t local_forced : 1; + uint8_t over_range : 1; + uint8_t reference_err : 1; + uint8_t reserved0 : 1; int32_t value; uint64_t timestamp; } DNP3ObjectG33V3; typedef struct DNP3ObjectG33V4_ { - uint8_t online:1; - uint8_t restart:1; - uint8_t comm_lost:1; - uint8_t remote_forced:1; - uint8_t local_forced:1; - uint8_t over_range:1; - uint8_t reference_err:1; - uint8_t reserved0:1; + uint8_t online : 1; + uint8_t restart : 1; + uint8_t comm_lost : 1; + uint8_t remote_forced : 1; + uint8_t local_forced : 1; + uint8_t over_range : 1; + uint8_t reference_err : 1; + uint8_t reserved0 : 1; int16_t value; uint64_t timestamp; } DNP3ObjectG33V4; typedef struct DNP3ObjectG33V5_ { - uint8_t online:1; - uint8_t restart:1; - uint8_t comm_lost:1; - uint8_t remote_forced:1; - uint8_t local_forced:1; - uint8_t over_range:1; - uint8_t reference_err:1; - uint8_t reserved0:1; + uint8_t online : 1; + uint8_t restart : 1; + uint8_t comm_lost : 1; + uint8_t remote_forced : 1; + uint8_t local_forced : 1; + uint8_t over_range : 1; + uint8_t reference_err : 1; + uint8_t reserved0 : 1; float value; } DNP3ObjectG33V5; typedef struct DNP3ObjectG33V6_ { - uint8_t online:1; - uint8_t restart:1; - uint8_t comm_lost:1; - uint8_t remote_forced:1; - uint8_t local_forced:1; - uint8_t over_range:1; - uint8_t reference_err:1; - uint8_t reserved0:1; + uint8_t online : 1; + uint8_t restart : 1; + uint8_t comm_lost : 1; + uint8_t remote_forced : 1; + uint8_t local_forced : 1; + uint8_t over_range : 1; + uint8_t reference_err : 1; + uint8_t reserved0 : 1; double value; } DNP3ObjectG33V6; typedef struct DNP3ObjectG33V7_ { - uint8_t online:1; - uint8_t restart:1; - uint8_t comm_lost:1; - uint8_t remote_forced:1; - uint8_t local_forced:1; - uint8_t over_range:1; - uint8_t reference_err:1; - uint8_t reserved0:1; + uint8_t online : 1; + uint8_t restart : 1; + uint8_t comm_lost : 1; + uint8_t remote_forced : 1; + uint8_t local_forced : 1; + uint8_t over_range : 1; + uint8_t reference_err : 1; + uint8_t reserved0 : 1; float value; uint64_t timestamp; } DNP3ObjectG33V7; typedef struct DNP3ObjectG33V8_ { - uint8_t online:1; - uint8_t restart:1; - uint8_t comm_lost:1; - uint8_t remote_forced:1; - uint8_t local_forced:1; - uint8_t over_range:1; - uint8_t reference_err:1; - uint8_t reserved0:1; + uint8_t online : 1; + uint8_t restart : 1; + uint8_t comm_lost : 1; + uint8_t remote_forced : 1; + uint8_t local_forced : 1; + uint8_t over_range : 1; + uint8_t reference_err : 1; + uint8_t reserved0 : 1; double value; uint64_t timestamp; } DNP3ObjectG33V8; @@ -931,50 +931,50 @@ typedef struct DNP3ObjectG34V3_ { } DNP3ObjectG34V3; typedef struct DNP3ObjectG40V1_ { - uint8_t online:1; - uint8_t restart:1; - uint8_t comm_lost:1; - uint8_t remote_forced:1; - uint8_t local_forced:1; - uint8_t over_range:1; - uint8_t reference_err:1; - uint8_t reserved0:1; + uint8_t online : 1; + uint8_t restart : 1; + uint8_t comm_lost : 1; + uint8_t remote_forced : 1; + uint8_t local_forced : 1; + uint8_t over_range : 1; + uint8_t reference_err : 1; + uint8_t reserved0 : 1; int32_t value; } DNP3ObjectG40V1; typedef struct DNP3ObjectG40V2_ { - uint8_t online:1; - uint8_t restart:1; - uint8_t comm_lost:1; - uint8_t remote_forced:1; - uint8_t local_forced:1; - uint8_t over_range:1; - uint8_t reference_err:1; - uint8_t reserved0:1; + uint8_t online : 1; + uint8_t restart : 1; + uint8_t comm_lost : 1; + uint8_t remote_forced : 1; + uint8_t local_forced : 1; + uint8_t over_range : 1; + uint8_t reference_err : 1; + uint8_t reserved0 : 1; int16_t value; } DNP3ObjectG40V2; typedef struct DNP3ObjectG40V3_ { - uint8_t online:1; - uint8_t restart:1; - uint8_t comm_lost:1; - uint8_t remote_forced:1; - uint8_t local_forced:1; - uint8_t over_range:1; - uint8_t reference_err:1; - uint8_t reserved0:1; + uint8_t online : 1; + uint8_t restart : 1; + uint8_t comm_lost : 1; + uint8_t remote_forced : 1; + uint8_t local_forced : 1; + uint8_t over_range : 1; + uint8_t reference_err : 1; + uint8_t reserved0 : 1; float value; } DNP3ObjectG40V3; typedef struct DNP3ObjectG40V4_ { - uint8_t online:1; - uint8_t restart:1; - uint8_t comm_lost:1; - uint8_t remote_forced:1; - uint8_t local_forced:1; - uint8_t over_range:1; - uint8_t reference_err:1; - uint8_t reserved0:1; + uint8_t online : 1; + uint8_t restart : 1; + uint8_t comm_lost : 1; + uint8_t remote_forced : 1; + uint8_t local_forced : 1; + uint8_t over_range : 1; + uint8_t reference_err : 1; + uint8_t reserved0 : 1; double value; } DNP3ObjectG40V4; @@ -999,153 +999,153 @@ typedef struct DNP3ObjectG41V4_ { } DNP3ObjectG41V4; typedef struct DNP3ObjectG42V1_ { - uint8_t online:1; - uint8_t restart:1; - uint8_t comm_lost:1; - uint8_t remote_forced:1; - uint8_t local_forced:1; - uint8_t over_range:1; - uint8_t reference_err:1; - uint8_t reserved0:1; + uint8_t online : 1; + uint8_t restart : 1; + uint8_t comm_lost : 1; + uint8_t remote_forced : 1; + uint8_t local_forced : 1; + uint8_t over_range : 1; + uint8_t reference_err : 1; + uint8_t reserved0 : 1; int32_t value; } DNP3ObjectG42V1; typedef struct DNP3ObjectG42V2_ { - uint8_t online:1; - uint8_t restart:1; - uint8_t comm_lost:1; - uint8_t remote_forced:1; - uint8_t local_forced:1; - uint8_t over_range:1; - uint8_t reference_err:1; - uint8_t reserved0:1; + uint8_t online : 1; + uint8_t restart : 1; + uint8_t comm_lost : 1; + uint8_t remote_forced : 1; + uint8_t local_forced : 1; + uint8_t over_range : 1; + uint8_t reference_err : 1; + uint8_t reserved0 : 1; int16_t value; } DNP3ObjectG42V2; typedef struct DNP3ObjectG42V3_ { - uint8_t online:1; - uint8_t restart:1; - uint8_t comm_lost:1; - uint8_t remote_forced:1; - uint8_t local_forced:1; - uint8_t over_range:1; - uint8_t reference_err:1; - uint8_t reserved0:1; + uint8_t online : 1; + uint8_t restart : 1; + uint8_t comm_lost : 1; + uint8_t remote_forced : 1; + uint8_t local_forced : 1; + uint8_t over_range : 1; + uint8_t reference_err : 1; + uint8_t reserved0 : 1; int32_t value; uint64_t timestamp; } DNP3ObjectG42V3; typedef struct DNP3ObjectG42V4_ { - uint8_t online:1; - uint8_t restart:1; - uint8_t comm_lost:1; - uint8_t remote_forced:1; - uint8_t local_forced:1; - uint8_t over_range:1; - uint8_t reference_err:1; - uint8_t reserved0:1; + uint8_t online : 1; + uint8_t restart : 1; + uint8_t comm_lost : 1; + uint8_t remote_forced : 1; + uint8_t local_forced : 1; + uint8_t over_range : 1; + uint8_t reference_err : 1; + uint8_t reserved0 : 1; int16_t value; uint64_t timestamp; } DNP3ObjectG42V4; typedef struct DNP3ObjectG42V5_ { - uint8_t online:1; - uint8_t restart:1; - uint8_t comm_lost:1; - uint8_t remote_forced:1; - uint8_t local_forced:1; - uint8_t over_range:1; - uint8_t reference_err:1; - uint8_t reserved0:1; + uint8_t online : 1; + uint8_t restart : 1; + uint8_t comm_lost : 1; + uint8_t remote_forced : 1; + uint8_t local_forced : 1; + uint8_t over_range : 1; + uint8_t reference_err : 1; + uint8_t reserved0 : 1; float value; } DNP3ObjectG42V5; typedef struct DNP3ObjectG42V6_ { - uint8_t online:1; - uint8_t restart:1; - uint8_t comm_lost:1; - uint8_t remote_forced:1; - uint8_t local_forced:1; - uint8_t over_range:1; - uint8_t reference_err:1; - uint8_t reserved0:1; + uint8_t online : 1; + uint8_t restart : 1; + uint8_t comm_lost : 1; + uint8_t remote_forced : 1; + uint8_t local_forced : 1; + uint8_t over_range : 1; + uint8_t reference_err : 1; + uint8_t reserved0 : 1; double value; } DNP3ObjectG42V6; typedef struct DNP3ObjectG42V7_ { - uint8_t online:1; - uint8_t restart:1; - uint8_t comm_lost:1; - uint8_t remote_forced:1; - uint8_t local_forced:1; - uint8_t over_range:1; - uint8_t reference_err:1; - uint8_t reserved0:1; + uint8_t online : 1; + uint8_t restart : 1; + uint8_t comm_lost : 1; + uint8_t remote_forced : 1; + uint8_t local_forced : 1; + uint8_t over_range : 1; + uint8_t reference_err : 1; + uint8_t reserved0 : 1; float value; uint64_t timestamp; } DNP3ObjectG42V7; typedef struct DNP3ObjectG42V8_ { - uint8_t online:1; - uint8_t restart:1; - uint8_t comm_lost:1; - uint8_t remote_forced:1; - uint8_t local_forced:1; - uint8_t over_range:1; - uint8_t reference_err:1; - uint8_t reserved0:1; + uint8_t online : 1; + uint8_t restart : 1; + uint8_t comm_lost : 1; + uint8_t remote_forced : 1; + uint8_t local_forced : 1; + uint8_t over_range : 1; + uint8_t reference_err : 1; + uint8_t reserved0 : 1; double value; uint64_t timestamp; } DNP3ObjectG42V8; typedef struct DNP3ObjectG43V1_ { - uint8_t status_code:7; - uint8_t reserved0:1; + uint8_t status_code : 7; + uint8_t reserved0 : 1; int32_t commanded_value; } DNP3ObjectG43V1; typedef struct DNP3ObjectG43V2_ { - uint8_t status_code:7; - uint8_t reserved0:1; + uint8_t status_code : 7; + uint8_t reserved0 : 1; int16_t commanded_value; } DNP3ObjectG43V2; typedef struct DNP3ObjectG43V3_ { - uint8_t status_code:7; - uint8_t reserved0:1; + uint8_t status_code : 7; + uint8_t reserved0 : 1; int32_t commanded_value; uint64_t timestamp; } DNP3ObjectG43V3; typedef struct DNP3ObjectG43V4_ { - uint8_t status_code:7; - uint8_t reserved0:1; + uint8_t status_code : 7; + uint8_t reserved0 : 1; int16_t commanded_value; uint64_t timestamp; } DNP3ObjectG43V4; typedef struct DNP3ObjectG43V5_ { - uint8_t status_code:7; - uint8_t reserved0:1; + uint8_t status_code : 7; + uint8_t reserved0 : 1; float commanded_value; } DNP3ObjectG43V5; typedef struct DNP3ObjectG43V6_ { - uint8_t status_code:7; - uint8_t reserved0:1; + uint8_t status_code : 7; + uint8_t reserved0 : 1; double commanded_value; } DNP3ObjectG43V6; typedef struct DNP3ObjectG43V7_ { - uint8_t status_code:7; - uint8_t reserved0:1; + uint8_t status_code : 7; + uint8_t reserved0 : 1; float commanded_value; uint64_t timestamp; } DNP3ObjectG43V7; typedef struct DNP3ObjectG43V8_ { - uint8_t status_code:7; - uint8_t reserved0:1; + uint8_t status_code : 7; + uint8_t reserved0 : 1; double commanded_value; uint64_t timestamp; } DNP3ObjectG43V8; @@ -1273,8 +1273,8 @@ typedef struct DNP3ObjectG80V1_ { } DNP3ObjectG80V1; typedef struct DNP3ObjectG81V1_ { - uint8_t fill_percentage:7; - uint8_t overflow_state:1; + uint8_t fill_percentage : 7; + uint8_t overflow_state : 1; uint8_t group; uint8_t variation; } DNP3ObjectG81V1; @@ -1287,14 +1287,14 @@ typedef struct DNP3ObjectG83V1_ { } DNP3ObjectG83V1; typedef struct DNP3ObjectG86V2_ { - uint8_t rd:1; - uint8_t wr:1; - uint8_t st:1; - uint8_t ev:1; - uint8_t df:1; - uint8_t padding0:1; - uint8_t padding1:1; - uint8_t padding2:1; + uint8_t rd : 1; + uint8_t wr : 1; + uint8_t st : 1; + uint8_t ev : 1; + uint8_t df : 1; + uint8_t padding0 : 1; + uint8_t padding1 : 1; + uint8_t padding2 : 1; } DNP3ObjectG86V2; typedef struct DNP3ObjectG102V1_ { @@ -1414,40 +1414,40 @@ typedef struct DNP3ObjectG120V15_ { } DNP3ObjectG120V15; typedef struct DNP3ObjectG121V1_ { - uint8_t online:1; - uint8_t restart:1; - uint8_t comm_lost:1; - uint8_t remote_forced:1; - uint8_t local_forced:1; - uint8_t reserved0:1; - uint8_t discontinuity:1; - uint8_t reserved1:1; + uint8_t online : 1; + uint8_t restart : 1; + uint8_t comm_lost : 1; + uint8_t remote_forced : 1; + uint8_t local_forced : 1; + uint8_t reserved0 : 1; + uint8_t discontinuity : 1; + uint8_t reserved1 : 1; uint16_t association_id; uint32_t count_value; } DNP3ObjectG121V1; typedef struct DNP3ObjectG122V1_ { - uint8_t online:1; - uint8_t restart:1; - uint8_t comm_lost:1; - uint8_t remote_forced:1; - uint8_t local_forced:1; - uint8_t reserved0:1; - uint8_t discontinuity:1; - uint8_t reserved1:1; + uint8_t online : 1; + uint8_t restart : 1; + uint8_t comm_lost : 1; + uint8_t remote_forced : 1; + uint8_t local_forced : 1; + uint8_t reserved0 : 1; + uint8_t discontinuity : 1; + uint8_t reserved1 : 1; uint16_t association_id; uint32_t count_value; } DNP3ObjectG122V1; typedef struct DNP3ObjectG122V2_ { - uint8_t online:1; - uint8_t restart:1; - uint8_t comm_lost:1; - uint8_t remote_forced:1; - uint8_t local_forced:1; - uint8_t reserved0:1; - uint8_t discontinuity:1; - uint8_t reserved1:1; + uint8_t online : 1; + uint8_t restart : 1; + uint8_t comm_lost : 1; + uint8_t remote_forced : 1; + uint8_t local_forced : 1; + uint8_t reserved0 : 1; + uint8_t discontinuity : 1; + uint8_t reserved1 : 1; uint16_t association_id; uint32_t count_value; uint64_t timestamp; @@ -1455,9 +1455,8 @@ typedef struct DNP3ObjectG122V2_ { /* END GENERATED CODE */ -int DNP3DecodeObject(int group, int variation, const uint8_t **buf, - uint32_t *len, uint8_t prefix_code, uint32_t start, uint32_t count, - DNP3PointList *); +int DNP3DecodeObject(int group, int variation, const uint8_t **buf, uint32_t *len, + uint8_t prefix_code, uint32_t start, uint32_t count, DNP3PointList *); DNP3PointList *DNP3PointListAlloc(void); void DNP3FreeObjectPointList(int group, int variation, DNP3PointList *); diff --git a/src/app-layer-dnp3.c b/src/app-layer-dnp3.c index 9f6073bf59ff..652fd9e1fdc9 100644 --- a/src/app-layer-dnp3.c +++ b/src/app-layer-dnp3.c @@ -46,34 +46,31 @@ #define DNP3_DEFAULT_PORT "20000" /* Expected values for the start bytes. */ -#define DNP3_START_BYTE0 0x05 -#define DNP3_START_BYTE1 0x64 +#define DNP3_START_BYTE0 0x05 +#define DNP3_START_BYTE1 0x64 /* Minimum length for a DNP3 frame. */ -#define DNP3_MIN_LEN 5 +#define DNP3_MIN_LEN 5 /* Length of each CRC. */ -#define DNP3_CRC_LEN 2 +#define DNP3_CRC_LEN 2 /* DNP3 block size. After the link header a CRC is inserted after * after 16 bytes of data. */ -#define DNP3_BLOCK_SIZE 16 +#define DNP3_BLOCK_SIZE 16 /* Maximum transport layer sequence number. */ #define DNP3_MAX_TRAN_SEQNO 64 /* Maximum application layer sequence number. */ -#define DNP3_MAX_APP_SEQNO 16 +#define DNP3_MAX_APP_SEQNO 16 /* The number of bytes in the header that are counted as part of the * header length field. */ #define DNP3_LINK_HDR_LEN 5 /* Link function codes. */ -enum { - DNP3_LINK_FC_CONFIRMED_USER_DATA = 3, - DNP3_LINK_FC_UNCONFIRMED_USER_DATA -}; +enum { DNP3_LINK_FC_CONFIRMED_USER_DATA = 3, DNP3_LINK_FC_UNCONFIRMED_USER_DATA }; /* Reserved addresses. */ #define DNP3_RESERVED_ADDR_MIN 0xfff0 @@ -82,7 +79,7 @@ enum { /* Source addresses must be < 0xfff0. */ #define DNP3_SRC_ADDR_MAX 0xfff0 -#define DNP3_OBJ_TIME_SIZE 6 /* AKA UINT48. */ +#define DNP3_OBJ_TIME_SIZE 6 /* AKA UINT48. */ #define DNP3_OBJ_G12_V1_SIZE 11 #define DNP3_OBJ_G12_V2_SIZE 11 #define DNP3_OBJ_G12_V3_SIZE 1 @@ -91,61 +88,49 @@ enum { #define DNP3_OBJ_PREFIX(x) ((x >> 4) & 0x7) /* Extract the range code from the object qualifier. */ -#define DNP3_OBJ_RANGE(x) (x & 0xf) +#define DNP3_OBJ_RANGE(x) (x & 0xf) /* Decoder event map. */ SCEnumCharMap dnp3_decoder_event_table[] = { - {"FLOODED", DNP3_DECODER_EVENT_FLOODED}, - {"LEN_TOO_SMALL", DNP3_DECODER_EVENT_LEN_TOO_SMALL}, - {"BAD_LINK_CRC", DNP3_DECODER_EVENT_BAD_LINK_CRC}, - {"BAD_TRANSPORT_CRC", DNP3_DECODER_EVENT_BAD_TRANSPORT_CRC}, - {"MALFORMED", DNP3_DECODER_EVENT_MALFORMED}, - {"UNKNOWN_OBJECT", DNP3_DECODER_EVENT_UNKNOWN_OBJECT}, - {NULL, -1}, + { "FLOODED", DNP3_DECODER_EVENT_FLOODED }, + { "LEN_TOO_SMALL", DNP3_DECODER_EVENT_LEN_TOO_SMALL }, + { "BAD_LINK_CRC", DNP3_DECODER_EVENT_BAD_LINK_CRC }, + { "BAD_TRANSPORT_CRC", DNP3_DECODER_EVENT_BAD_TRANSPORT_CRC }, + { "MALFORMED", DNP3_DECODER_EVENT_MALFORMED }, + { "UNKNOWN_OBJECT", DNP3_DECODER_EVENT_UNKNOWN_OBJECT }, + { NULL, -1 }, }; /* Calculate the next transport sequence number. */ #define NEXT_TH_SEQNO(current) ((current + 1) % DNP3_MAX_TRAN_SEQNO) /* Calculate the next application sequence number. */ -#define NEXT_APP_SEQNO(current) ((current + 1) % DNP3_MAX_APP_SEQNO) +#define NEXT_APP_SEQNO(current) ((current + 1) % DNP3_MAX_APP_SEQNO) /* CRC table generated by pycrc - http://github.com/tpircher/pycrc. * - Polynomial: 0x3d65. */ -static const uint16_t crc_table[256] = { - 0x0000, 0x365e, 0x6cbc, 0x5ae2, 0xd978, 0xef26, 0xb5c4, 0x839a, - 0xff89, 0xc9d7, 0x9335, 0xa56b, 0x26f1, 0x10af, 0x4a4d, 0x7c13, - 0xb26b, 0x8435, 0xded7, 0xe889, 0x6b13, 0x5d4d, 0x07af, 0x31f1, - 0x4de2, 0x7bbc, 0x215e, 0x1700, 0x949a, 0xa2c4, 0xf826, 0xce78, - 0x29af, 0x1ff1, 0x4513, 0x734d, 0xf0d7, 0xc689, 0x9c6b, 0xaa35, - 0xd626, 0xe078, 0xba9a, 0x8cc4, 0x0f5e, 0x3900, 0x63e2, 0x55bc, - 0x9bc4, 0xad9a, 0xf778, 0xc126, 0x42bc, 0x74e2, 0x2e00, 0x185e, - 0x644d, 0x5213, 0x08f1, 0x3eaf, 0xbd35, 0x8b6b, 0xd189, 0xe7d7, - 0x535e, 0x6500, 0x3fe2, 0x09bc, 0x8a26, 0xbc78, 0xe69a, 0xd0c4, - 0xacd7, 0x9a89, 0xc06b, 0xf635, 0x75af, 0x43f1, 0x1913, 0x2f4d, - 0xe135, 0xd76b, 0x8d89, 0xbbd7, 0x384d, 0x0e13, 0x54f1, 0x62af, - 0x1ebc, 0x28e2, 0x7200, 0x445e, 0xc7c4, 0xf19a, 0xab78, 0x9d26, - 0x7af1, 0x4caf, 0x164d, 0x2013, 0xa389, 0x95d7, 0xcf35, 0xf96b, - 0x8578, 0xb326, 0xe9c4, 0xdf9a, 0x5c00, 0x6a5e, 0x30bc, 0x06e2, - 0xc89a, 0xfec4, 0xa426, 0x9278, 0x11e2, 0x27bc, 0x7d5e, 0x4b00, - 0x3713, 0x014d, 0x5baf, 0x6df1, 0xee6b, 0xd835, 0x82d7, 0xb489, - 0xa6bc, 0x90e2, 0xca00, 0xfc5e, 0x7fc4, 0x499a, 0x1378, 0x2526, - 0x5935, 0x6f6b, 0x3589, 0x03d7, 0x804d, 0xb613, 0xecf1, 0xdaaf, - 0x14d7, 0x2289, 0x786b, 0x4e35, 0xcdaf, 0xfbf1, 0xa113, 0x974d, - 0xeb5e, 0xdd00, 0x87e2, 0xb1bc, 0x3226, 0x0478, 0x5e9a, 0x68c4, - 0x8f13, 0xb94d, 0xe3af, 0xd5f1, 0x566b, 0x6035, 0x3ad7, 0x0c89, - 0x709a, 0x46c4, 0x1c26, 0x2a78, 0xa9e2, 0x9fbc, 0xc55e, 0xf300, - 0x3d78, 0x0b26, 0x51c4, 0x679a, 0xe400, 0xd25e, 0x88bc, 0xbee2, - 0xc2f1, 0xf4af, 0xae4d, 0x9813, 0x1b89, 0x2dd7, 0x7735, 0x416b, - 0xf5e2, 0xc3bc, 0x995e, 0xaf00, 0x2c9a, 0x1ac4, 0x4026, 0x7678, - 0x0a6b, 0x3c35, 0x66d7, 0x5089, 0xd313, 0xe54d, 0xbfaf, 0x89f1, - 0x4789, 0x71d7, 0x2b35, 0x1d6b, 0x9ef1, 0xa8af, 0xf24d, 0xc413, - 0xb800, 0x8e5e, 0xd4bc, 0xe2e2, 0x6178, 0x5726, 0x0dc4, 0x3b9a, - 0xdc4d, 0xea13, 0xb0f1, 0x86af, 0x0535, 0x336b, 0x6989, 0x5fd7, - 0x23c4, 0x159a, 0x4f78, 0x7926, 0xfabc, 0xcce2, 0x9600, 0xa05e, - 0x6e26, 0x5878, 0x029a, 0x34c4, 0xb75e, 0x8100, 0xdbe2, 0xedbc, - 0x91af, 0xa7f1, 0xfd13, 0xcb4d, 0x48d7, 0x7e89, 0x246b, 0x1235 -}; +static const uint16_t crc_table[256] = { 0x0000, 0x365e, 0x6cbc, 0x5ae2, 0xd978, 0xef26, 0xb5c4, + 0x839a, 0xff89, 0xc9d7, 0x9335, 0xa56b, 0x26f1, 0x10af, 0x4a4d, 0x7c13, 0xb26b, 0x8435, 0xded7, + 0xe889, 0x6b13, 0x5d4d, 0x07af, 0x31f1, 0x4de2, 0x7bbc, 0x215e, 0x1700, 0x949a, 0xa2c4, 0xf826, + 0xce78, 0x29af, 0x1ff1, 0x4513, 0x734d, 0xf0d7, 0xc689, 0x9c6b, 0xaa35, 0xd626, 0xe078, 0xba9a, + 0x8cc4, 0x0f5e, 0x3900, 0x63e2, 0x55bc, 0x9bc4, 0xad9a, 0xf778, 0xc126, 0x42bc, 0x74e2, 0x2e00, + 0x185e, 0x644d, 0x5213, 0x08f1, 0x3eaf, 0xbd35, 0x8b6b, 0xd189, 0xe7d7, 0x535e, 0x6500, 0x3fe2, + 0x09bc, 0x8a26, 0xbc78, 0xe69a, 0xd0c4, 0xacd7, 0x9a89, 0xc06b, 0xf635, 0x75af, 0x43f1, 0x1913, + 0x2f4d, 0xe135, 0xd76b, 0x8d89, 0xbbd7, 0x384d, 0x0e13, 0x54f1, 0x62af, 0x1ebc, 0x28e2, 0x7200, + 0x445e, 0xc7c4, 0xf19a, 0xab78, 0x9d26, 0x7af1, 0x4caf, 0x164d, 0x2013, 0xa389, 0x95d7, 0xcf35, + 0xf96b, 0x8578, 0xb326, 0xe9c4, 0xdf9a, 0x5c00, 0x6a5e, 0x30bc, 0x06e2, 0xc89a, 0xfec4, 0xa426, + 0x9278, 0x11e2, 0x27bc, 0x7d5e, 0x4b00, 0x3713, 0x014d, 0x5baf, 0x6df1, 0xee6b, 0xd835, 0x82d7, + 0xb489, 0xa6bc, 0x90e2, 0xca00, 0xfc5e, 0x7fc4, 0x499a, 0x1378, 0x2526, 0x5935, 0x6f6b, 0x3589, + 0x03d7, 0x804d, 0xb613, 0xecf1, 0xdaaf, 0x14d7, 0x2289, 0x786b, 0x4e35, 0xcdaf, 0xfbf1, 0xa113, + 0x974d, 0xeb5e, 0xdd00, 0x87e2, 0xb1bc, 0x3226, 0x0478, 0x5e9a, 0x68c4, 0x8f13, 0xb94d, 0xe3af, + 0xd5f1, 0x566b, 0x6035, 0x3ad7, 0x0c89, 0x709a, 0x46c4, 0x1c26, 0x2a78, 0xa9e2, 0x9fbc, 0xc55e, + 0xf300, 0x3d78, 0x0b26, 0x51c4, 0x679a, 0xe400, 0xd25e, 0x88bc, 0xbee2, 0xc2f1, 0xf4af, 0xae4d, + 0x9813, 0x1b89, 0x2dd7, 0x7735, 0x416b, 0xf5e2, 0xc3bc, 0x995e, 0xaf00, 0x2c9a, 0x1ac4, 0x4026, + 0x7678, 0x0a6b, 0x3c35, 0x66d7, 0x5089, 0xd313, 0xe54d, 0xbfaf, 0x89f1, 0x4789, 0x71d7, 0x2b35, + 0x1d6b, 0x9ef1, 0xa8af, 0xf24d, 0xc413, 0xb800, 0x8e5e, 0xd4bc, 0xe2e2, 0x6178, 0x5726, 0x0dc4, + 0x3b9a, 0xdc4d, 0xea13, 0xb0f1, 0x86af, 0x0535, 0x336b, 0x6989, 0x5fd7, 0x23c4, 0x159a, 0x4f78, + 0x7926, 0xfabc, 0xcce2, 0x9600, 0xa05e, 0x6e26, 0x5878, 0x029a, 0x34c4, 0xb75e, 0x8100, 0xdbe2, + 0xedbc, 0x91af, 0xa7f1, 0xfd13, 0xcb4d, 0x48d7, 0x7e89, 0x246b, 0x1235 }; /** * \brief Compute the CRC for a buffer. @@ -192,8 +177,7 @@ static int DNP3CheckCRC(const uint8_t *block, uint32_t len) crc_offset = len - DNP3_CRC_LEN; crc = DNP3ComputeCRC(block, len - DNP3_CRC_LEN); - if (((crc & 0xff) == block[crc_offset]) && - ((crc >> 8) == block[crc_offset + 1])) { + if (((crc & 0xff) == block[crc_offset]) && ((crc >> 8) == block[crc_offset + 1])) { return 1; } @@ -228,8 +212,7 @@ static int DNP3CheckUserDataCRCs(const uint8_t *data, uint32_t len) while (offset < len) { if (len - offset >= DNP3_BLOCK_SIZE + DNP3_CRC_LEN) { block_size = DNP3_BLOCK_SIZE + DNP3_CRC_LEN; - } - else { + } else { block_size = len - offset; } @@ -251,8 +234,7 @@ static int DNP3CheckUserDataCRCs(const uint8_t *data, uint32_t len) */ static int DNP3CheckStartBytes(const DNP3LinkHeader *header) { - return header->start_byte0 == DNP3_START_BYTE0 && - header->start_byte1 == DNP3_START_BYTE1; + return header->start_byte0 == DNP3_START_BYTE0 && header->start_byte1 == DNP3_START_BYTE1; } /* Some DNP3 servers start with a banner. */ @@ -274,9 +256,8 @@ static int DNP3ContainsBanner(const uint8_t *input, uint32_t len) /** * \brief DNP3 probing parser. */ -static uint16_t DNP3ProbingParser(Flow *f, uint8_t direction, - const uint8_t *input, uint32_t len, - uint8_t *rdir) +static uint16_t DNP3ProbingParser( + Flow *f, uint8_t direction, const uint8_t *input, uint32_t len, uint8_t *rdir) { const DNP3LinkHeader *const hdr = (const DNP3LinkHeader *)input; const bool toserver = (direction & STREAM_TOSERVER) != 0; @@ -351,8 +332,7 @@ static int DNP3CalculateTransportLengthWithoutCRCs(uint32_t input_len) return -1; } return (blocks * DNP3_BLOCK_SIZE) + (rem - DNP3_CRC_LEN); - } - else { + } else { return (blocks * DNP3_BLOCK_SIZE); } } @@ -376,8 +356,8 @@ static int DNP3CalculateTransportLengthWithoutCRCs(uint32_t input_len) * * \retval 1 if reassembly was successful, otherwise 0. */ -static int DNP3ReassembleApplicationLayer(const uint8_t *input, - uint32_t input_len, uint8_t **output, uint32_t *output_len) +static int DNP3ReassembleApplicationLayer( + const uint8_t *input, uint32_t input_len, uint8_t **output, uint32_t *output_len) { int len = DNP3CalculateTransportLengthWithoutCRCs(input_len); @@ -396,8 +376,7 @@ static int DNP3ReassembleApplicationLayer(const uint8_t *input, if (unlikely(*output == NULL)) { return 0; } - } - else { + } else { uint8_t *ptr = SCRealloc(*output, (size_t)(*output_len + len)); if (unlikely(ptr == NULL)) { return 0; @@ -409,8 +388,7 @@ static int DNP3ReassembleApplicationLayer(const uint8_t *input, while ((uint32_t)offset < input_len) { if (input_len - offset > DNP3_BLOCK_SIZE + DNP3_CRC_LEN) { block_size = DNP3_BLOCK_SIZE + DNP3_CRC_LEN; - } - else { + } else { block_size = input_len - offset; } @@ -436,8 +414,7 @@ static int DNP3ReassembleApplicationLayer(const uint8_t *input, return 0; } - memcpy(*output + *output_len, input + offset, - block_size - DNP3_CRC_LEN); + memcpy(*output + *output_len, input + offset, block_size - DNP3_CRC_LEN); *output_len += block_size - DNP3_CRC_LEN; offset += block_size; len -= block_size - DNP3_CRC_LEN; @@ -475,8 +452,7 @@ static void DNP3SetEvent(DNP3State *dnp3, uint8_t event) if (dnp3 && dnp3->curr) { AppLayerDecoderEventsSetEventRaw(&dnp3->curr->tx_data.events, event); dnp3->events++; - } - else { + } else { SCLogWarning("Failed to set event, state or tx pointer was NULL."); } } @@ -585,12 +561,11 @@ static int DNP3IsUserData(const DNP3LinkHeader *header) static int DNP3HasUserData(const DNP3LinkHeader *header, uint8_t direction) { if (direction == STREAM_TOSERVER) { + return header->len >= + DNP3_LINK_HDR_LEN + sizeof(DNP3TransportHeader) + sizeof(DNP3ApplicationHeader); + } else { return header->len >= DNP3_LINK_HDR_LEN + sizeof(DNP3TransportHeader) + - sizeof(DNP3ApplicationHeader); - } - else { - return header->len >= DNP3_LINK_HDR_LEN + sizeof(DNP3TransportHeader) + - sizeof(DNP3ApplicationHeader) + sizeof(DNP3InternalInd); + sizeof(DNP3ApplicationHeader) + sizeof(DNP3InternalInd); } } @@ -620,8 +595,7 @@ static int DNP3BufferAdd(DNP3Buffer *buffer, const uint8_t *data, uint32_t len) return 0; } buffer->size = len; - } - else if (buffer->len + len > buffer->size) { + } else if (buffer->len + len > buffer->size) { uint8_t *tmp = SCRealloc(buffer->buffer, buffer->len + len); if (unlikely(tmp == NULL)) { return 0; @@ -647,10 +621,8 @@ static void DNP3BufferTrim(DNP3Buffer *buffer) { if (buffer->offset == buffer->len) { DNP3BufferReset(buffer); - } - else if (buffer->offset > 0) { - memmove(buffer->buffer, buffer->buffer + buffer->offset, - buffer->len - buffer->offset); + } else if (buffer->offset > 0) { + memmove(buffer->buffer, buffer->buffer + buffer->offset, buffer->len - buffer->offset); buffer->len = buffer->len - buffer->offset; buffer->offset = 0; } @@ -662,8 +634,7 @@ static void DNP3BufferTrim(DNP3Buffer *buffer) static void DNP3ObjectFree(DNP3Object *object) { if (object->points != NULL) { - DNP3FreeObjectPointList(object->group, object->variation, - object->points); + DNP3FreeObjectPointList(object->group, object->variation, object->points); } SCFree(object); } @@ -700,8 +671,8 @@ static DNP3Object *DNP3ObjectAlloc(void) * \retval 1 if all objects decoded, 0 if all objects could not be decoded ( * unknown group/variations) */ -static int DNP3DecodeApplicationObjects(DNP3Transaction *tx, const uint8_t *buf, - uint32_t len, DNP3ObjectList *objects) +static int DNP3DecodeApplicationObjects( + DNP3Transaction *tx, const uint8_t *buf, uint32_t len, DNP3ObjectList *objects) { int retval = 0; @@ -822,8 +793,7 @@ static int DNP3DecodeApplicationObjects(DNP3Transaction *tx, const uint8_t *buf, break; } default: - SCLogDebug("Range code 0x%02x is reserved.", - object->range_code); + SCLogDebug("Range code 0x%02x is reserved.", object->range_code); goto done; } @@ -834,9 +804,8 @@ static int DNP3DecodeApplicationObjects(DNP3Transaction *tx, const uint8_t *buf, goto next; } - int event = DNP3DecodeObject(header->group, header->variation, &buf, - &len, object->prefix_code, object->start, object->count, - object->points); + int event = DNP3DecodeObject(header->group, header->variation, &buf, &len, + object->prefix_code, object->start, object->count, object->points); if (event) { DNP3SetEventTx(tx, DNP3_DECODER_EVENT_UNKNOWN_OBJECT); goto done; @@ -861,8 +830,7 @@ static int DNP3DecodeApplicationObjects(DNP3Transaction *tx, const uint8_t *buf, * \param input pointer to the DNP3 frame (starting with link header) * \param input_len length of the input frame */ -static void DNP3HandleUserDataRequest(DNP3State *dnp3, const uint8_t *input, - uint32_t input_len) +static void DNP3HandleUserDataRequest(DNP3State *dnp3, const uint8_t *input, uint32_t input_len) { DNP3LinkHeader *lh; DNP3TransportHeader th; @@ -871,15 +839,15 @@ static void DNP3HandleUserDataRequest(DNP3State *dnp3, const uint8_t *input, lh = (DNP3LinkHeader *)input; - if (!DNP3CheckUserDataCRCs(input + sizeof(DNP3LinkHeader), - input_len - sizeof(DNP3LinkHeader))) { + if (!DNP3CheckUserDataCRCs( + input + sizeof(DNP3LinkHeader), input_len - sizeof(DNP3LinkHeader))) { return; } th = input[sizeof(DNP3LinkHeader)]; if (!DNP3_TH_FIR(th)) { - TAILQ_FOREACH(ttx, &dnp3->tx_list, next) { + TAILQ_FOREACH (ttx, &dnp3->tx_list, next) { if (ttx->lh.src == lh->src && ttx->lh.dst == lh->dst && ttx->is_request && !ttx->done && NEXT_TH_SEQNO(DNP3_TH_SEQ(ttx->th)) == DNP3_TH_SEQ(th)) { tx = ttx; @@ -894,10 +862,9 @@ static void DNP3HandleUserDataRequest(DNP3State *dnp3, const uint8_t *input, /* Update the saved transport header so subsequent segments * will be matched to this sequence number. */ tx->th = th; - } - else { + } else { ah = (DNP3ApplicationHeader *)(input + sizeof(DNP3LinkHeader) + - sizeof(DNP3TransportHeader)); + sizeof(DNP3TransportHeader)); /* Ignore confirms - for now. */ if (ah->function_code == DNP3_APP_FC_CONFIRM) { @@ -936,8 +903,7 @@ static void DNP3HandleUserDataRequest(DNP3State *dnp3, const uint8_t *input, } } -static void DNP3HandleUserDataResponse(DNP3State *dnp3, const uint8_t *input, - uint32_t input_len) +static void DNP3HandleUserDataResponse(DNP3State *dnp3, const uint8_t *input, uint32_t input_len) { DNP3LinkHeader *lh; DNP3TransportHeader th; @@ -956,7 +922,7 @@ static void DNP3HandleUserDataResponse(DNP3State *dnp3, const uint8_t *input, th = input[offset++]; if (!DNP3_TH_FIR(th)) { - TAILQ_FOREACH(ttx, &dnp3->tx_list, next) { + TAILQ_FOREACH (ttx, &dnp3->tx_list, next) { if (ttx->lh.src == lh->src && ttx->lh.dst == lh->dst && !ttx->is_request && !ttx->done && NEXT_TH_SEQNO(DNP3_TH_SEQ(ttx->th)) == DNP3_TH_SEQ(th)) { tx = ttx; @@ -971,8 +937,7 @@ static void DNP3HandleUserDataResponse(DNP3State *dnp3, const uint8_t *input, /* Replace the transport header in the transaction with this * one in case there are more frames. */ tx->th = th; - } - else { + } else { ah = (DNP3ApplicationHeader *)(input + offset); offset += sizeof(DNP3ApplicationHeader); iin = (DNP3InternalInd *)(input + offset); @@ -1014,8 +979,7 @@ static void DNP3HandleUserDataResponse(DNP3State *dnp3, const uint8_t *input, * \retval number of bytes processed or -1 if the data stream does not look * like DNP3. */ -static int DNP3HandleRequestLinkLayer(DNP3State *dnp3, const uint8_t *input, - uint32_t input_len) +static int DNP3HandleRequestLinkLayer(DNP3State *dnp3, const uint8_t *input, uint32_t input_len) { SCEnter(); uint32_t processed = 0; @@ -1060,8 +1024,8 @@ static int DNP3HandleRequestLinkLayer(DNP3State *dnp3, const uint8_t *input, goto next; } - if (!DNP3CheckUserDataCRCs(input + sizeof(DNP3LinkHeader), - frame_len - sizeof(DNP3LinkHeader))) { + if (!DNP3CheckUserDataCRCs( + input + sizeof(DNP3LinkHeader), frame_len - sizeof(DNP3LinkHeader))) { DNP3SetEvent(dnp3, DNP3_DECODER_EVENT_BAD_TRANSPORT_CRC); goto next; } @@ -1109,16 +1073,14 @@ static AppLayerResult DNP3ParseRequest(Flow *f, void *state, AppLayerParserState if (!DNP3BufferAdd(buffer, input, input_len)) { goto error; } - processed = DNP3HandleRequestLinkLayer(dnp3, - buffer->buffer + buffer->offset, - buffer->len - buffer->offset); + processed = DNP3HandleRequestLinkLayer( + dnp3, buffer->buffer + buffer->offset, buffer->len - buffer->offset); if (processed < 0) { goto error; } buffer->offset += processed; DNP3BufferTrim(buffer); - } - else { + } else { processed = DNP3HandleRequestLinkLayer(dnp3, input, input_len); if (processed < 0) { SCLogDebug("Failed to process request link layer."); @@ -1150,8 +1112,7 @@ static AppLayerResult DNP3ParseRequest(Flow *f, void *state, AppLayerParserState * \retval number of bytes processed or -1 if the data stream does not * like look DNP3. */ -static int DNP3HandleResponseLinkLayer(DNP3State *dnp3, const uint8_t *input, - uint32_t input_len) +static int DNP3HandleResponseLinkLayer(DNP3State *dnp3, const uint8_t *input, uint32_t input_len) { SCEnter(); uint32_t processed = 0; @@ -1197,8 +1158,8 @@ static int DNP3HandleResponseLinkLayer(DNP3State *dnp3, const uint8_t *input, goto error; } - if (!DNP3CheckUserDataCRCs(input + sizeof(DNP3LinkHeader), - frame_len - sizeof(DNP3LinkHeader))) { + if (!DNP3CheckUserDataCRCs( + input + sizeof(DNP3LinkHeader), frame_len - sizeof(DNP3LinkHeader))) { DNP3SetEvent(dnp3, DNP3_DECODER_EVENT_BAD_TRANSPORT_CRC); goto next; } @@ -1244,16 +1205,14 @@ static AppLayerResult DNP3ParseResponse(Flow *f, void *state, AppLayerParserStat if (!DNP3BufferAdd(buffer, input, input_len)) { goto error; } - processed = DNP3HandleResponseLinkLayer(dnp3, - buffer->buffer + buffer->offset, - buffer->len - buffer->offset); + processed = DNP3HandleResponseLinkLayer( + dnp3, buffer->buffer + buffer->offset, buffer->len - buffer->offset); if (processed < 0) { goto error; } buffer->offset += processed; DNP3BufferTrim(buffer); - } - else { + } else { /* Check if this is a banner, ignore if it is. */ if (DNP3ContainsBanner(input, input_len)) { @@ -1296,7 +1255,7 @@ static void *DNP3GetTx(void *alstate, uint64_t tx_id) SCReturnPtr(dnp3->curr, "void"); } - TAILQ_FOREACH(tx, &dnp3->tx_list, next) { + TAILQ_FOREACH (tx, &dnp3->tx_list, next) { if (tx_num != tx->tx_num) { continue; } @@ -1362,7 +1321,7 @@ static void DNP3StateTxFree(void *state, uint64_t tx_id) DNP3Transaction *tx = NULL, *ttx; uint64_t tx_num = tx_id + 1; - TAILQ_FOREACH_SAFE(tx, &dnp3->tx_list, next, ttx) { + TAILQ_FOREACH_SAFE (tx, &dnp3->tx_list, next, ttx) { if (tx->tx_num != tx_num) { continue; @@ -1428,8 +1387,7 @@ static int DNP3GetAlstateProgress(void *tx, uint8_t direction) int retval = 0; /* If flooded, "ack" old transactions. */ - if (dnp3->flooded && (dnp3->transaction_max - - dnp3tx->tx_num >= DNP3_DEFAULT_REQ_FLOOD_COUNT)) { + if (dnp3->flooded && (dnp3->transaction_max - dnp3tx->tx_num >= DNP3_DEFAULT_REQ_FLOOD_COUNT)) { SCLogDebug("flooded: returning tx as done."); SCReturnInt(1); } @@ -1443,8 +1401,8 @@ static int DNP3GetAlstateProgress(void *tx, uint8_t direction) /** * \brief App-layer support. */ -static int DNP3StateGetEventInfo(const char *event_name, int *event_id, - AppLayerEventType *event_type) +static int DNP3StateGetEventInfo( + const char *event_name, int *event_id, AppLayerEventType *event_type) { *event_id = SCMapEnumNameToValue(event_name, dnp3_decoder_event_table); if (*event_id == -1) { @@ -1462,8 +1420,8 @@ static int DNP3StateGetEventInfo(const char *event_name, int *event_id, /** * \brief App-layer support. */ -static int DNP3StateGetEventInfoById(int event_id, const char **event_name, - AppLayerEventType *event_type) +static int DNP3StateGetEventInfoById( + int event_id, const char **event_name, AppLayerEventType *event_type) { *event_name = SCMapEnumValueToName(event_id, dnp3_decoder_event_table); if (*event_name == NULL) { @@ -1555,14 +1513,11 @@ void RegisterDNP3Parsers(void) AppLayerProtoDetectRegisterProtocol(ALPROTO_DNP3, proto_name); if (RunmodeIsUnittests()) { - AppLayerProtoDetectPPRegister(IPPROTO_TCP, DNP3_DEFAULT_PORT, - ALPROTO_DNP3, 0, sizeof(DNP3LinkHeader), STREAM_TOSERVER, - DNP3ProbingParser, DNP3ProbingParser); - } - else { - if (!AppLayerProtoDetectPPParseConfPorts("tcp", IPPROTO_TCP, - proto_name, ALPROTO_DNP3, 0, sizeof(DNP3LinkHeader), - DNP3ProbingParser, DNP3ProbingParser)) { + AppLayerProtoDetectPPRegister(IPPROTO_TCP, DNP3_DEFAULT_PORT, ALPROTO_DNP3, 0, + sizeof(DNP3LinkHeader), STREAM_TOSERVER, DNP3ProbingParser, DNP3ProbingParser); + } else { + if (!AppLayerProtoDetectPPParseConfPorts("tcp", IPPROTO_TCP, proto_name, ALPROTO_DNP3, + 0, sizeof(DNP3LinkHeader), DNP3ProbingParser, DNP3ProbingParser)) { return; } } @@ -1572,45 +1527,37 @@ void RegisterDNP3Parsers(void) SCReturn; } - if (AppLayerParserConfParserEnabled("tcp", proto_name)) - { + if (AppLayerParserConfParserEnabled("tcp", proto_name)) { SCLogConfig("Registering DNP3/tcp parsers."); - AppLayerParserRegisterParser(IPPROTO_TCP, ALPROTO_DNP3, STREAM_TOSERVER, - DNP3ParseRequest); - AppLayerParserRegisterParser(IPPROTO_TCP, ALPROTO_DNP3, STREAM_TOCLIENT, - DNP3ParseResponse); + AppLayerParserRegisterParser(IPPROTO_TCP, ALPROTO_DNP3, STREAM_TOSERVER, DNP3ParseRequest); + AppLayerParserRegisterParser(IPPROTO_TCP, ALPROTO_DNP3, STREAM_TOCLIENT, DNP3ParseResponse); - AppLayerParserRegisterStateFuncs(IPPROTO_TCP, ALPROTO_DNP3, - DNP3StateAlloc, DNP3StateFree); + AppLayerParserRegisterStateFuncs(IPPROTO_TCP, ALPROTO_DNP3, DNP3StateAlloc, DNP3StateFree); AppLayerParserRegisterGetTx(IPPROTO_TCP, ALPROTO_DNP3, DNP3GetTx); AppLayerParserRegisterGetTxIterator(IPPROTO_TCP, ALPROTO_DNP3, DNP3GetTxIterator); AppLayerParserRegisterGetTxCnt(IPPROTO_TCP, ALPROTO_DNP3, DNP3GetTxCnt); - AppLayerParserRegisterTxFreeFunc(IPPROTO_TCP, ALPROTO_DNP3, - DNP3StateTxFree); + AppLayerParserRegisterTxFreeFunc(IPPROTO_TCP, ALPROTO_DNP3, DNP3StateTxFree); - AppLayerParserRegisterGetStateProgressFunc(IPPROTO_TCP, ALPROTO_DNP3, - DNP3GetAlstateProgress); + AppLayerParserRegisterGetStateProgressFunc( + IPPROTO_TCP, ALPROTO_DNP3, DNP3GetAlstateProgress); AppLayerParserRegisterStateProgressCompletionStatus(ALPROTO_DNP3, 1, 1); - AppLayerParserRegisterGetEventInfo(IPPROTO_TCP, ALPROTO_DNP3, - DNP3StateGetEventInfo); - AppLayerParserRegisterGetEventInfoById(IPPROTO_TCP, ALPROTO_DNP3, - DNP3StateGetEventInfoById); + AppLayerParserRegisterGetEventInfo(IPPROTO_TCP, ALPROTO_DNP3, DNP3StateGetEventInfo); + AppLayerParserRegisterGetEventInfoById( + IPPROTO_TCP, ALPROTO_DNP3, DNP3StateGetEventInfoById); - AppLayerParserRegisterTxDataFunc(IPPROTO_TCP, ALPROTO_DNP3, - DNP3GetTxData); + AppLayerParserRegisterTxDataFunc(IPPROTO_TCP, ALPROTO_DNP3, DNP3GetTxData); AppLayerParserRegisterStateDataFunc(IPPROTO_TCP, ALPROTO_DNP3, DNP3GetStateData); - } - else { + } else { SCLogConfig("Parser disabled for protocol %s. " - "Protocol detection still on.", proto_name); + "Protocol detection still on.", + proto_name); } #ifdef UNITTESTS - AppLayerParserRegisterProtocolUnittests(IPPROTO_TCP, ALPROTO_DNP3, - DNP3ParserRegisterTests); + AppLayerParserRegisterProtocolUnittests(IPPROTO_TCP, ALPROTO_DNP3, DNP3ParserRegisterTests); #endif SCReturn; @@ -1670,8 +1617,7 @@ static int DNP3ParserTestCheckCRC(void) FAIL_IF(!DNP3CheckCRC(request, sizeof(DNP3LinkHeader))); /* Check first application layer segment. */ - FAIL_IF(!DNP3CheckCRC(request + sizeof(DNP3LinkHeader), - DNP3_BLOCK_SIZE + DNP3_CRC_LEN)); + FAIL_IF(!DNP3CheckCRC(request + sizeof(DNP3LinkHeader), DNP3_BLOCK_SIZE + DNP3_CRC_LEN)); #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION /* Change a byte in link header, should fail now. */ @@ -1681,8 +1627,7 @@ static int DNP3ParserTestCheckCRC(void) /* Change a byte in the first application segment, should fail * now. */ request[sizeof(DNP3LinkHeader) + 3]++; - FAIL_IF(DNP3CheckCRC(request + sizeof(DNP3LinkHeader), - DNP3_BLOCK_SIZE + DNP3_CRC_LEN)); + FAIL_IF(DNP3CheckCRC(request + sizeof(DNP3LinkHeader), DNP3_BLOCK_SIZE + DNP3_CRC_LEN)); #endif PASS; @@ -1767,10 +1712,8 @@ static int DNP3CheckUserDataCRCsTest(void) // clang-format off uint8_t three_bytes_good_crc[] = { 0x00, 0x00, 0x00 }; // clang-format on - *(uint16_t *)(three_bytes_good_crc + 1) = DNP3ComputeCRC( - three_bytes_good_crc, 1); - FAIL_IF(!DNP3CheckUserDataCRCs(three_bytes_good_crc, - sizeof(three_bytes_good_crc))); + *(uint16_t *)(three_bytes_good_crc + 1) = DNP3ComputeCRC(three_bytes_good_crc, 1); + FAIL_IF(!DNP3CheckUserDataCRCs(three_bytes_good_crc, sizeof(three_bytes_good_crc))); PASS; } @@ -1929,8 +1872,7 @@ static int DNP3ReassembleApplicationLayerTest01(void) // clang-format on /* Valid frame. */ - FAIL_IF(!DNP3ReassembleApplicationLayer(payload, - sizeof(payload), &output, &reassembled_len)); + FAIL_IF(!DNP3ReassembleApplicationLayer(payload, sizeof(payload), &output, &reassembled_len)); FAIL_IF(output == NULL); FAIL_IF(reassembled_len != sizeof(expected)); FAIL_IF(memcmp(expected, output, reassembled_len)); @@ -1939,16 +1881,14 @@ static int DNP3ReassembleApplicationLayerTest01(void) /* 1 byte, invalid. */ reassembled_len = 0; output = NULL; - FAIL_IF(DNP3ReassembleApplicationLayer(payload, 1, &output, - &reassembled_len)); + FAIL_IF(DNP3ReassembleApplicationLayer(payload, 1, &output, &reassembled_len)); FAIL_IF(output != NULL); FAIL_IF(reassembled_len != 0); /* 2 bytes, invalid. */ reassembled_len = 0; output = NULL; - FAIL_IF(DNP3ReassembleApplicationLayer(payload, 2, &output, - &reassembled_len)); + FAIL_IF(DNP3ReassembleApplicationLayer(payload, 2, &output, &reassembled_len)); FAIL_IF(output != NULL); FAIL_IF(reassembled_len != 0); @@ -1956,16 +1896,14 @@ static int DNP3ReassembleApplicationLayerTest01(void) * which isn't included in the output. */ reassembled_len = 0; output = NULL; - FAIL_IF(DNP3ReassembleApplicationLayer(payload, 3, &output, - &reassembled_len)); + FAIL_IF(DNP3ReassembleApplicationLayer(payload, 3, &output, &reassembled_len)); FAIL_IF(output != NULL); FAIL_IF(reassembled_len != 0); /* 4 bytes is the minimum to get any reassembled data. */ reassembled_len = 0; output = NULL; - FAIL_IF(!DNP3ReassembleApplicationLayer(payload, 4, &output, - &reassembled_len)); + FAIL_IF(!DNP3ReassembleApplicationLayer(payload, 4, &output, &reassembled_len)); FAIL_IF(output == NULL); FAIL_IF(reassembled_len != 1); @@ -1995,8 +1933,8 @@ static int DNP3ReassembleApplicationLayerTest01(void) }; // clang-format on reassembled_len = 0; - FAIL_IF(DNP3ReassembleApplicationLayer(short_payload1, - sizeof(short_payload1), &output, &reassembled_len)); + FAIL_IF(DNP3ReassembleApplicationLayer( + short_payload1, sizeof(short_payload1), &output, &reassembled_len)); /* Last block too short (by 2 bytes) for data + CRC. */ // clang-format off @@ -2024,8 +1962,8 @@ static int DNP3ReassembleApplicationLayerTest01(void) }; // clang-format on reassembled_len = 0; - FAIL_IF(DNP3ReassembleApplicationLayer(short_payload2, - sizeof(short_payload2), &output, &reassembled_len)); + FAIL_IF(DNP3ReassembleApplicationLayer( + short_payload2, sizeof(short_payload2), &output, &reassembled_len)); PASS; } @@ -2047,7 +1985,8 @@ static int DNP3ProbingParserTest(void) FAIL_IF(DNP3ProbingParser(NULL, STREAM_TOSERVER, pkt, sizeof(pkt), &rdir) != ALPROTO_DNP3); /* Send too little bytes. */ - FAIL_IF(DNP3ProbingParser(NULL, STREAM_TOSERVER, pkt, sizeof(DNP3LinkHeader) - 1, &rdir) != ALPROTO_UNKNOWN); + FAIL_IF(DNP3ProbingParser(NULL, STREAM_TOSERVER, pkt, sizeof(DNP3LinkHeader) - 1, &rdir) != + ALPROTO_UNKNOWN); /* Bad start bytes. */ pkt[0] = 0x06; @@ -2123,8 +2062,8 @@ static int DNP3ParserTestRequestResponse(void) StreamTcpInitConfig(true); SCMutexLock(&flow.m); - FAIL_IF(AppLayerParserParse(NULL, alp_tctx, &flow, ALPROTO_DNP3, - STREAM_TOSERVER, request, sizeof(request))); + FAIL_IF(AppLayerParserParse( + NULL, alp_tctx, &flow, ALPROTO_DNP3, STREAM_TOSERVER, request, sizeof(request))); SCMutexUnlock(&flow.m); state = flow.alstate; @@ -2139,8 +2078,8 @@ static int DNP3ParserTestRequestResponse(void) FAIL_IF(tx->ah.function_code != DNP3_APP_FC_DIR_OPERATE); SCMutexLock(&flow.m); - FAIL_IF(AppLayerParserParse(NULL, alp_tctx, &flow, ALPROTO_DNP3, - STREAM_TOCLIENT, response, sizeof(response))); + FAIL_IF(AppLayerParserParse( + NULL, alp_tctx, &flow, ALPROTO_DNP3, STREAM_TOCLIENT, response, sizeof(response))); SCMutexUnlock(&flow.m); DNP3Transaction *tx0 = DNP3GetTx(state, 1); FAIL_IF(tx0 == NULL); @@ -2196,8 +2135,8 @@ static int DNP3ParserTestUnsolicitedResponseConfirm(void) StreamTcpInitConfig(true); SCMutexLock(&flow.m); - FAIL_IF(AppLayerParserParse(NULL, alp_tctx, &flow, ALPROTO_DNP3, - STREAM_TOCLIENT, response, sizeof(response))); + FAIL_IF(AppLayerParserParse( + NULL, alp_tctx, &flow, ALPROTO_DNP3, STREAM_TOCLIENT, response, sizeof(response))); SCMutexUnlock(&flow.m); state = flow.alstate; @@ -2211,8 +2150,8 @@ static int DNP3ParserTestUnsolicitedResponseConfirm(void) FAIL_IF(tx->ah.function_code != DNP3_APP_FC_UNSOLICITED_RESP); SCMutexLock(&flow.m); - FAIL_IF(AppLayerParserParse(NULL, alp_tctx, &flow, ALPROTO_DNP3, - STREAM_TOSERVER, confirm, sizeof(confirm))); + FAIL_IF(AppLayerParserParse( + NULL, alp_tctx, &flow, ALPROTO_DNP3, STREAM_TOSERVER, confirm, sizeof(confirm))); SCMutexUnlock(&flow.m); /* Confirms are ignored currently. With the move to @@ -2267,8 +2206,8 @@ static int DNP3ParserTestFlooded(void) StreamTcpInitConfig(true); SCMutexLock(&flow.m); - FAIL_IF(AppLayerParserParse(NULL, alp_tctx, &flow, ALPROTO_DNP3, - STREAM_TOSERVER, request, sizeof(request))); + FAIL_IF(AppLayerParserParse( + NULL, alp_tctx, &flow, ALPROTO_DNP3, STREAM_TOSERVER, request, sizeof(request))); SCMutexUnlock(&flow.m); state = flow.alstate; @@ -2286,8 +2225,8 @@ static int DNP3ParserTestFlooded(void) for (int i = 0; i < DNP3_DEFAULT_REQ_FLOOD_COUNT - 1; i++) { SCMutexLock(&flow.m); - FAIL_IF(AppLayerParserParse(NULL, alp_tctx, &flow, ALPROTO_DNP3, - STREAM_TOSERVER, request, sizeof(request))); + FAIL_IF(AppLayerParserParse( + NULL, alp_tctx, &flow, ALPROTO_DNP3, STREAM_TOSERVER, request, sizeof(request))); SCMutexUnlock(&flow.m); } FAIL_IF(state->flooded); @@ -2295,8 +2234,8 @@ static int DNP3ParserTestFlooded(void) /* One more request should trip us into flooded state. */ SCMutexLock(&flow.m); - FAIL_IF(AppLayerParserParse(NULL, alp_tctx, &flow, ALPROTO_DNP3, - STREAM_TOSERVER, request, sizeof(request))); + FAIL_IF(AppLayerParserParse( + NULL, alp_tctx, &flow, ALPROTO_DNP3, STREAM_TOSERVER, request, sizeof(request))); SCMutexUnlock(&flow.m); FAIL_IF(!state->flooded); @@ -2380,8 +2319,8 @@ static int DNP3ParserTestPartialFrame(void) /* Pass in the first partial frame. */ SCMutexLock(&flow.m); - r = AppLayerParserParse(NULL, alp_tctx, &flow, ALPROTO_DNP3, - STREAM_TOSERVER, request_partial1, sizeof(request_partial1)); + r = AppLayerParserParse(NULL, alp_tctx, &flow, ALPROTO_DNP3, STREAM_TOSERVER, request_partial1, + sizeof(request_partial1)); SCMutexUnlock(&flow.m); FAIL_IF(r != 0); @@ -2390,8 +2329,7 @@ static int DNP3ParserTestPartialFrame(void) FAIL_IF(state == NULL); FAIL_IF(state->request_buffer.len != sizeof(request_partial1)); FAIL_IF(state->request_buffer.offset != 0); - FAIL_IF(memcmp(state->request_buffer.buffer, request_partial1, - sizeof(request_partial1))); + FAIL_IF(memcmp(state->request_buffer.buffer, request_partial1, sizeof(request_partial1))); /* There should not be a transaction yet. */ FAIL_IF(state->transaction_max != 0); @@ -2399,8 +2337,8 @@ static int DNP3ParserTestPartialFrame(void) /* Send the second partial. */ SCMutexLock(&flow.m); - r = AppLayerParserParse(NULL, alp_tctx, &flow, ALPROTO_DNP3, - STREAM_TOSERVER, request_partial2, sizeof(request_partial2)); + r = AppLayerParserParse(NULL, alp_tctx, &flow, ALPROTO_DNP3, STREAM_TOSERVER, request_partial2, + sizeof(request_partial2)); SCMutexUnlock(&flow.m); FAIL_IF(r != 0); @@ -2420,8 +2358,8 @@ static int DNP3ParserTestPartialFrame(void) /* Send partial response. */ SCMutexLock(&flow.m); - r = AppLayerParserParse(NULL, alp_tctx, &flow, ALPROTO_DNP3, - STREAM_TOCLIENT, response_partial1, sizeof(response_partial1)); + r = AppLayerParserParse(NULL, alp_tctx, &flow, ALPROTO_DNP3, STREAM_TOCLIENT, response_partial1, + sizeof(response_partial1)); SCMutexUnlock(&flow.m); FAIL_IF(r != 0); FAIL_IF(state->response_buffer.len != sizeof(response_partial1)); @@ -2431,8 +2369,8 @@ static int DNP3ParserTestPartialFrame(void) /* Send rest of response. */ SCMutexLock(&flow.m); - r = AppLayerParserParse(NULL, alp_tctx, &flow, ALPROTO_DNP3, - STREAM_TOCLIENT, response_partial2, sizeof(response_partial2)); + r = AppLayerParserParse(NULL, alp_tctx, &flow, ALPROTO_DNP3, STREAM_TOCLIENT, response_partial2, + sizeof(response_partial2)); SCMutexUnlock(&flow.m); FAIL_IF(r != 0); @@ -2481,8 +2419,7 @@ static int DNP3ParserTestMultiFrame(void) uint8_t combined[sizeof(unsol_response1) + sizeof(unsol_response2)]; memcpy(combined, unsol_response1, sizeof(unsol_response1)); - memcpy(combined + sizeof(unsol_response1), unsol_response2, - sizeof(unsol_response2)); + memcpy(combined + sizeof(unsol_response1), unsol_response2, sizeof(unsol_response2)); /* Setup. */ AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -2497,8 +2434,8 @@ static int DNP3ParserTestMultiFrame(void) StreamTcpInitConfig(true); SCMutexLock(&flow.m); - r = AppLayerParserParse(NULL, alp_tctx, &flow, ALPROTO_DNP3, - STREAM_TOCLIENT, combined, sizeof(combined)); + r = AppLayerParserParse( + NULL, alp_tctx, &flow, ALPROTO_DNP3, STREAM_TOCLIENT, combined, sizeof(combined)); SCMutexUnlock(&flow.m); FAIL_IF(r != 0); @@ -2593,9 +2530,8 @@ static int DNP3ParserDecodeG70V3Test(void) FAIL_IF_NOT(point->size == 85); FAIL_IF_NULL(point->data); DNP3ObjectG70V3 *data = point->data; - FAIL_IF_NOT(strcmp( - data->filename, - "C:/temp/DNPDeviceConfiguration written to Remote Device.xml") == 0); + FAIL_IF_NOT(strcmp(data->filename, + "C:/temp/DNPDeviceConfiguration written to Remote Device.xml") == 0); DNP3StateFree(dnp3state); PASS; } @@ -2646,8 +2582,8 @@ static int DNP3ParserUnknownEventAlertTest(void) } /** -* \brief Test that an alert is raised on incorrect data. -*/ + * \brief Test that an alert is raised on incorrect data. + */ static int DNP3ParserIncorrectUserData(void) { // clang-format off @@ -2667,8 +2603,8 @@ static int DNP3ParserIncorrectUserData(void) flow.alproto = ALPROTO_DNP3; StreamTcpInitConfig(true); - int r = AppLayerParserParse(NULL, alp_tctx, &flow, ALPROTO_DNP3, - STREAM_TOCLIENT, packet_bytes, sizeof(packet_bytes)); + int r = AppLayerParserParse(NULL, alp_tctx, &flow, ALPROTO_DNP3, STREAM_TOCLIENT, packet_bytes, + sizeof(packet_bytes)); FAIL_IF(r == 0); @@ -2684,26 +2620,22 @@ void DNP3ParserRegisterTests(void) { #ifdef UNITTESTS UtRegisterTest("DNP3ParserTestCheckCRC", DNP3ParserTestCheckCRC); - UtRegisterTest("DNP3ParserCheckLinkHeaderCRC", - DNP3ParserCheckLinkHeaderCRC); + UtRegisterTest("DNP3ParserCheckLinkHeaderCRC", DNP3ParserCheckLinkHeaderCRC); UtRegisterTest("DNP3CheckUserDataCRCsTest", DNP3CheckUserDataCRCsTest); UtRegisterTest("DNP3CalculateLinkLengthTest", DNP3CalculateLinkLengthTest); UtRegisterTest("DNP3CalculateTransportLengthWithoutCRCsTest", - DNP3CalculateTransportLengthWithoutCRCsTest); - UtRegisterTest("DNP3ReassembleApplicationLayerTest01", - DNP3ReassembleApplicationLayerTest01); + DNP3CalculateTransportLengthWithoutCRCsTest); + UtRegisterTest("DNP3ReassembleApplicationLayerTest01", DNP3ReassembleApplicationLayerTest01); UtRegisterTest("DNP3ProbingParserTest", DNP3ProbingParserTest); - UtRegisterTest("DNP3ParserTestRequestResponse", - DNP3ParserTestRequestResponse); - UtRegisterTest("DNP3ParserTestUnsolicitedResponseConfirm", - DNP3ParserTestUnsolicitedResponseConfirm); + UtRegisterTest("DNP3ParserTestRequestResponse", DNP3ParserTestRequestResponse); + UtRegisterTest( + "DNP3ParserTestUnsolicitedResponseConfirm", DNP3ParserTestUnsolicitedResponseConfirm); UtRegisterTest("DNP3ParserTestPartialFrame", DNP3ParserTestPartialFrame); UtRegisterTest("DNP3ParserTestMultiFrame", DNP3ParserTestMultiFrame); UtRegisterTest("DNP3ParserTestFlooded", DNP3ParserTestFlooded); UtRegisterTest("DNP3ParserTestParsePDU01", DNP3ParserTestParsePDU01); UtRegisterTest("DNP3ParserDecodeG70V3Test", DNP3ParserDecodeG70V3Test); - UtRegisterTest("DNP3ParserUnknownEventAlertTest", - DNP3ParserUnknownEventAlertTest); + UtRegisterTest("DNP3ParserUnknownEventAlertTest", DNP3ParserUnknownEventAlertTest); UtRegisterTest("DNP3ParserIncorrectUserData", DNP3ParserIncorrectUserData); #endif } diff --git a/src/app-layer-dnp3.h b/src/app-layer-dnp3.h index aae07f9c8095..f3fe7fabbd42 100644 --- a/src/app-layer-dnp3.h +++ b/src/app-layer-dnp3.h @@ -66,9 +66,9 @@ #define DNP3_APP_FC_AUTH_REQ_NR 0x21 /* DNP3 application response function codes. */ -#define DNP3_APP_FC_RESPONSE 0x81 -#define DNP3_APP_FC_UNSOLICITED_RESP 0x82 -#define DNP3_APP_FC_AUTH_RESP 0x83 +#define DNP3_APP_FC_RESPONSE 0x81 +#define DNP3_APP_FC_UNSOLICITED_RESP 0x82 +#define DNP3_APP_FC_AUTH_RESP 0x83 /* Extract fields from the link control octet. */ #define DNP3_LINK_DIR(control) (control & 0x80) @@ -115,13 +115,13 @@ enum { * \brief DNP3 link header. */ typedef struct DNP3LinkHeader_ { - uint8_t start_byte0; /**< First check byte. */ - uint8_t start_byte1; /**< Second check byte. */ - uint8_t len; /**< Length of PDU without CRCs. */ - uint8_t control; /**< Control flags. */ - uint16_t dst; /**< DNP3 destination address. */ - uint16_t src; /**< DNP3 source address. */ - uint16_t crc; /**< Link header CRC. */ + uint8_t start_byte0; /**< First check byte. */ + uint8_t start_byte1; /**< Second check byte. */ + uint8_t len; /**< Length of PDU without CRCs. */ + uint8_t control; /**< Control flags. */ + uint16_t dst; /**< DNP3 destination address. */ + uint16_t src; /**< DNP3 source address. */ + uint16_t crc; /**< Link header CRC. */ } __attribute__((__packed__)) DNP3LinkHeader; /** @@ -133,8 +133,8 @@ typedef uint8_t DNP3TransportHeader; * \brief DNP3 application header. */ typedef struct DNP3ApplicationHeader_ { - uint8_t control; /**< Control flags. */ - uint8_t function_code; /**< Application function code. */ + uint8_t control; /**< Control flags. */ + uint8_t function_code; /**< Application function code. */ } __attribute__((__packed__)) DNP3ApplicationHeader; /** @@ -152,9 +152,9 @@ typedef struct DNP3InternalInd_ { */ typedef struct DNP3Buffer_ { uint8_t *buffer; - size_t size; - int len; - int offset; + size_t size; + int len; + int offset; } DNP3Buffer; /** @@ -173,14 +173,14 @@ typedef struct DNP3ObjHeader_ { * of the object. */ typedef struct DNP3Point_ { - uint32_t prefix; /**< Prefix value for point. */ - uint32_t index; /**< Index of point. If the object is prefixed - * with an index then this will be that - * value. Otherwise this is the place the point - * was in the list of points (starting at 0). */ - uint32_t size; /**< Size of point if the object prefix was a - * size. */ - void *data; /**< Data for this point. */ + uint32_t prefix; /**< Prefix value for point. */ + uint32_t index; /**< Index of point. If the object is prefixed + * with an index then this will be that + * value. Otherwise this is the place the point + * was in the list of points (starting at 0). */ + uint32_t size; /**< Size of point if the object prefix was a + * size. */ + void *data; /**< Data for this point. */ TAILQ_ENTRY(DNP3Point_) next; } DNP3Point; @@ -190,14 +190,14 @@ typedef TAILQ_HEAD(DNP3PointList_, DNP3Point_) DNP3PointList; * \brief Struct to hold the list of decoded objects. */ typedef struct DNP3Object_ { - uint8_t group; - uint8_t variation; - uint8_t qualifier; - uint8_t prefix_code; - uint8_t range_code; - uint32_t start; - uint32_t stop; - uint32_t count; + uint8_t group; + uint8_t variation; + uint8_t qualifier; + uint8_t prefix_code; + uint8_t range_code; + uint32_t start; + uint32_t stop; + uint32_t count; DNP3PointList *points; /**< List of points for this object. */ TAILQ_ENTRY(DNP3Object_) next; @@ -209,7 +209,7 @@ typedef TAILQ_HEAD(DNP3ObjectList_, DNP3Object_) DNP3ObjectList; * \brief DNP3 transaction. */ typedef struct DNP3Transaction_ { - AppLayerTxData tx_data; + AppLayerTxData tx_data; uint64_t tx_num; /**< Internal transaction ID. */ bool is_request; /**< Is this tx a request? */ @@ -238,11 +238,11 @@ TAILQ_HEAD(TxListHead, DNP3Transaction_); typedef struct DNP3State_ { AppLayerStateData state_data; TAILQ_HEAD(, DNP3Transaction_) tx_list; - DNP3Transaction *curr; /**< Current transaction. */ + DNP3Transaction *curr; /**< Current transaction. */ uint64_t transaction_max; uint16_t events; - uint32_t unreplied; /**< Number of unreplied requests. */ - uint8_t flooded; /**< Flag indicating flood. */ + uint32_t unreplied; /**< Number of unreplied requests. */ + uint8_t flooded; /**< Flag indicating flood. */ DNP3Buffer request_buffer; /**< Request buffer for buffering * incomplete request PDUs received diff --git a/src/app-layer-enip-common.c b/src/app-layer-enip-common.c index 0608080e21f1..67977476647f 100644 --- a/src/app-layer-enip-common.c +++ b/src/app-layer-enip-common.c @@ -41,11 +41,11 @@ * @param input * @param offset */ -static int ENIPExtractUint8(uint8_t *res, const uint8_t *input, uint16_t *offset, uint32_t input_len) +static int ENIPExtractUint8( + uint8_t *res, const uint8_t *input, uint16_t *offset, uint32_t input_len) { - if (input_len < sizeof(uint8_t) || *offset > (input_len - sizeof(uint8_t))) - { + if (input_len < sizeof(uint8_t) || *offset > (input_len - sizeof(uint8_t))) { SCLogDebug("ENIPExtractUint8: Parsing beyond payload length"); return 0; } @@ -61,7 +61,8 @@ static int ENIPExtractUint8(uint8_t *res, const uint8_t *input, uint16_t *offset * @param input * @param offset */ -static int ENIPExtractUint16(uint16_t *res, const uint8_t *input, uint16_t *offset, uint32_t input_len) +static int ENIPExtractUint16( + uint16_t *res, const uint8_t *input, uint16_t *offset, uint32_t input_len) { if (input_len < sizeof(uint16_t) || *offset > (input_len - sizeof(uint16_t))) { @@ -84,11 +85,11 @@ static int ENIPExtractUint16(uint16_t *res, const uint8_t *input, uint16_t *offs * @param input * @param offset */ -static int ENIPExtractUint32(uint32_t *res, const uint8_t *input, uint16_t *offset, uint32_t input_len) +static int ENIPExtractUint32( + uint32_t *res, const uint8_t *input, uint16_t *offset, uint32_t input_len) { - if (input_len < sizeof(uint32_t) || *offset > (input_len - sizeof(uint32_t))) - { + if (input_len < sizeof(uint32_t) || *offset > (input_len - sizeof(uint32_t))) { SCLogDebug("ENIPExtractUint32: Parsing beyond payload length"); return 0; } @@ -108,11 +109,11 @@ static int ENIPExtractUint32(uint32_t *res, const uint8_t *input, uint16_t *offs * @param input * @param offset */ -static int ENIPExtractUint64(uint64_t *res, const uint8_t *input, uint16_t *offset, uint32_t input_len) +static int ENIPExtractUint64( + uint64_t *res, const uint8_t *input, uint16_t *offset, uint32_t input_len) { - if (input_len < sizeof(uint64_t) || *offset > (input_len - sizeof(uint64_t))) - { + if (input_len < sizeof(uint64_t) || *offset > (input_len - sizeof(uint64_t))) { SCLogDebug("ENIPExtractUint64: Parsing beyond payload length"); return 0; } @@ -126,7 +127,6 @@ static int ENIPExtractUint64(uint64_t *res, const uint8_t *input, uint16_t *offs return 1; } - /** * \brief Create service entry, add to transaction * @param tx Transaction @@ -135,8 +135,7 @@ static int ENIPExtractUint64(uint64_t *res, const uint8_t *input, uint16_t *offs static CIPServiceEntry *CIPServiceAlloc(ENIPTransaction *tx) { - CIPServiceEntry *svc = (CIPServiceEntry *) SCCalloc(1, - sizeof(CIPServiceEntry)); + CIPServiceEntry *svc = (CIPServiceEntry *)SCCalloc(1, sizeof(CIPServiceEntry)); if (unlikely(svc == NULL)) return NULL; @@ -146,7 +145,6 @@ static CIPServiceEntry *CIPServiceAlloc(ENIPTransaction *tx) TAILQ_INSERT_TAIL(&tx->service_list, svc, next); tx->service_count++; return svc; - } #if 0 @@ -188,42 +186,35 @@ static void CIPServiceFree(void *s) * @return 1 Packet ok * @return 0 Packet has errors */ -int DecodeENIPPDU(const uint8_t *input, uint32_t input_len, - ENIPTransaction *enip_data) +int DecodeENIPPDU(const uint8_t *input, uint32_t input_len, ENIPTransaction *enip_data) { int ret = 1; - uint16_t offset = 0; //byte offset + uint16_t offset = 0; // byte offset - //Decode Encapsulation Header + // Decode Encapsulation Header uint16_t cmd; uint16_t len; uint32_t session; uint32_t status; uint64_t context; uint32_t option; - if (ENIPExtractUint16(&cmd, input, &offset, input_len) != 1) - { + if (ENIPExtractUint16(&cmd, input, &offset, input_len) != 1) { return 0; } - if (ENIPExtractUint16(&len, input, &offset, input_len) != 1) - { + if (ENIPExtractUint16(&len, input, &offset, input_len) != 1) { return 0; } - if (ENIPExtractUint32(&session, input, &offset, input_len) != 1) - { + if (ENIPExtractUint32(&session, input, &offset, input_len) != 1) { return 0; } - if (ENIPExtractUint32(&status, input, &offset, input_len) != 1) - { + if (ENIPExtractUint32(&status, input, &offset, input_len) != 1) { return 0; } - if (ENIPExtractUint64(&context, input, &offset, input_len) != 1) - { + if (ENIPExtractUint64(&context, input, &offset, input_len) != 1) { return 0; } - if (ENIPExtractUint32(&option, input, &offset, input_len) != 1) - { + if (ENIPExtractUint32(&option, input, &offset, input_len) != 1) { return 0; } @@ -234,8 +225,7 @@ int DecodeENIPPDU(const uint8_t *input, uint32_t input_len, enip_data->header.context = context; enip_data->header.option = option; - switch (enip_data->header.command) - { + switch (enip_data->header.command) { case NOP: SCLogDebug("DecodeENIP - NOP"); break; @@ -255,16 +245,12 @@ int DecodeENIPPDU(const uint8_t *input, uint32_t input_len, SCLogDebug("DecodeENIP - UNREGISTER_SESSION"); break; case SEND_RR_DATA: - SCLogDebug( - "DecodeENIP - SEND_RR_DATA - parse Common Packet Format"); - ret = DecodeCommonPacketFormatPDU(input, input_len, enip_data, - offset); + SCLogDebug("DecodeENIP - SEND_RR_DATA - parse Common Packet Format"); + ret = DecodeCommonPacketFormatPDU(input, input_len, enip_data, offset); break; case SEND_UNIT_DATA: - SCLogDebug( - "DecodeENIP - SEND UNIT DATA - parse Common Packet Format"); - ret = DecodeCommonPacketFormatPDU(input, input_len, enip_data, - offset); + SCLogDebug("DecodeENIP - SEND UNIT DATA - parse Common Packet Format"); + ret = DecodeCommonPacketFormatPDU(input, input_len, enip_data, offset); break; case INDICATE_STATUS: SCLogDebug("DecodeENIP - INDICATE_STATUS"); @@ -273,14 +259,12 @@ int DecodeENIPPDU(const uint8_t *input, uint32_t input_len, SCLogDebug("DecodeENIP - CANCEL"); break; default: - SCLogDebug("DecodeENIP - UNSUPPORTED COMMAND 0x%x", - enip_data->header.command); + SCLogDebug("DecodeENIP - UNSUPPORTED COMMAND 0x%x", enip_data->header.command); } return ret; } - /** * \brief Decode Common Packet Format * @param input, input_len data stream @@ -289,12 +273,11 @@ int DecodeENIPPDU(const uint8_t *input, uint32_t input_len, * @return 1 Packet ok * @return 0 Packet has errors */ -int DecodeCommonPacketFormatPDU(const uint8_t *input, uint32_t input_len, - ENIPTransaction *enip_data, uint16_t offset) +int DecodeCommonPacketFormatPDU( + const uint8_t *input, uint32_t input_len, ENIPTransaction *enip_data, uint16_t offset) { - if (enip_data->header.length < sizeof(ENIPEncapDataHdr)) - { + if (enip_data->header.length < sizeof(ENIPEncapDataHdr)) { SCLogDebug("DecodeCommonPacketFormat: Malformed ENIP packet"); return 0; } @@ -302,16 +285,13 @@ int DecodeCommonPacketFormatPDU(const uint8_t *input, uint32_t input_len, uint32_t handle; uint16_t timeout; uint16_t count; - if (ENIPExtractUint32(&handle, input, &offset, input_len) != 1) - { + if (ENIPExtractUint32(&handle, input, &offset, input_len) != 1) { return 0; } - if (ENIPExtractUint16(&timeout, input, &offset, input_len) != 1) - { + if (ENIPExtractUint16(&timeout, input, &offset, input_len) != 1) { return 0; } - if (ENIPExtractUint16(&count, input, &offset, input_len) != 1) - { + if (ENIPExtractUint16(&count, input, &offset, input_len) != 1) { return 0; } enip_data->encap_data_header.interface_handle = handle; @@ -319,34 +299,27 @@ int DecodeCommonPacketFormatPDU(const uint8_t *input, uint32_t input_len, enip_data->encap_data_header.item_count = count; uint16_t address_type; - uint16_t address_length; //length of connection id in bytes + uint16_t address_length; // length of connection id in bytes uint32_t address_connectionid = 0; uint32_t address_sequence = 0; - if (ENIPExtractUint16(&address_type, input, &offset, input_len) != 1) - { + if (ENIPExtractUint16(&address_type, input, &offset, input_len) != 1) { return 0; } - if (ENIPExtractUint16(&address_length, input, &offset, input_len) != 1) - { + if (ENIPExtractUint16(&address_length, input, &offset, input_len) != 1) { return 0; } - //depending on addr type, get connection id, sequence if needed. Can also use addr length too? - if (address_type == CONNECTION_BASED) - { //get 4 byte connection id - if (ENIPExtractUint32(&address_connectionid, input, &offset, input_len) != 1) - { + // depending on addr type, get connection id, sequence if needed. Can also use addr length too? + if (address_type == CONNECTION_BASED) { // get 4 byte connection id + if (ENIPExtractUint32(&address_connectionid, input, &offset, input_len) != 1) { return 0; } - } else if (address_type == SEQUENCE_ADDR_ITEM) - { // get 4 byte connection id and 4 byte sequence - if (ENIPExtractUint32(&address_connectionid, input, &offset, input_len) != 1) - { + } else if (address_type == SEQUENCE_ADDR_ITEM) { // get 4 byte connection id and 4 byte sequence + if (ENIPExtractUint32(&address_connectionid, input, &offset, input_len) != 1) { return 0; } - if (ENIPExtractUint32(&address_sequence, input, &offset, input_len) != 1) - { + if (ENIPExtractUint32(&address_sequence, input, &offset, input_len) != 1) { return 0; } } @@ -357,25 +330,22 @@ int DecodeCommonPacketFormatPDU(const uint8_t *input, uint32_t input_len, enip_data->encap_addr_item.sequence_num = address_sequence; uint16_t data_type; - uint16_t data_length; //length of data in bytes + uint16_t data_length; // length of data in bytes uint16_t data_sequence_count; - if (ENIPExtractUint16(&data_type, input, &offset, input_len) != 1) - { + if (ENIPExtractUint16(&data_type, input, &offset, input_len) != 1) { return 0; } - if (ENIPExtractUint16(&data_length, input, &offset, input_len) != 1) - { + if (ENIPExtractUint16(&data_length, input, &offset, input_len) != 1) { return 0; } enip_data->encap_data_item.type = data_type; enip_data->encap_data_item.length = data_length; - if (enip_data->encap_data_item.type == CONNECTED_DATA_ITEM) - { //connected data items have seq number - if (ENIPExtractUint16(&data_sequence_count, input, &offset, input_len) != 1) - { + if (enip_data->encap_data_item.type == + CONNECTED_DATA_ITEM) { // connected data items have seq number + if (ENIPExtractUint16(&data_sequence_count, input, &offset, input_len) != 1) { return 0; } enip_data->encap_data_item.sequence_count = data_sequence_count; @@ -383,8 +353,7 @@ int DecodeCommonPacketFormatPDU(const uint8_t *input, uint32_t input_len, switch (enip_data->encap_data_item.type) { case CONNECTED_DATA_ITEM: - SCLogDebug( - "DecodeCommonPacketFormat - CONNECTED DATA ITEM - parse CIP"); + SCLogDebug("DecodeCommonPacketFormat - CONNECTED DATA ITEM - parse CIP"); DecodeCIPPDU(input, input_len, enip_data, offset); break; case UNCONNECTED_DATA_ITEM: @@ -409,19 +378,17 @@ int DecodeCommonPacketFormatPDU(const uint8_t *input, uint32_t input_len, * @return 0 Packet has errors */ -int DecodeCIPPDU(const uint8_t *input, uint32_t input_len, - ENIPTransaction *enip_data, uint16_t offset) +int DecodeCIPPDU( + const uint8_t *input, uint32_t input_len, ENIPTransaction *enip_data, uint16_t offset) { int ret = 1; - if (enip_data->encap_data_item.length == 0) - { + if (enip_data->encap_data_item.length == 0) { SCLogDebug("DecodeCIP: No CIP Data"); return 0; } - if (offset > (input_len - sizeof(uint8_t))) - { + if (offset > (input_len - sizeof(uint8_t))) { SCLogDebug("DecodeCIP: Parsing beyond payload length"); return 0; } @@ -429,22 +396,18 @@ int DecodeCIPPDU(const uint8_t *input, uint32_t input_len, uint8_t service = 0; service = *(input + offset); - //SCLogDebug("CIP Service 0x%x", service); + // SCLogDebug("CIP Service 0x%x", service); - //use service code first bit to determine request/response, no need to save or push offset - if (service >> 7) - { + // use service code first bit to determine request/response, no need to save or push offset + if (service >> 7) { ret = DecodeCIPResponsePDU(input, input_len, enip_data, offset); - } else - { + } else { ret = DecodeCIPRequestPDU(input, input_len, enip_data, offset); } return ret; } - - /** * \brief Decode CIP Request * @param input, input_len data stream @@ -453,13 +416,12 @@ int DecodeCIPPDU(const uint8_t *input, uint32_t input_len, * @return 1 Packet ok * @return 0 Packet has errors */ -int DecodeCIPRequestPDU(const uint8_t *input, uint32_t input_len, - ENIPTransaction *enip_data, uint16_t offset) +int DecodeCIPRequestPDU( + const uint8_t *input, uint32_t input_len, ENIPTransaction *enip_data, uint16_t offset) { int ret = 1; - if (enip_data->encap_data_item.length < sizeof(CIPReqHdr)) - { + if (enip_data->encap_data_item.length < sizeof(CIPReqHdr)) { SCLogDebug("DecodeCIPRequest - Malformed CIP Data"); return 0; } @@ -467,32 +429,29 @@ int DecodeCIPRequestPDU(const uint8_t *input, uint32_t input_len, uint8_t service = 0; //<-----CIP SERVICE uint8_t path_size = 0; - if (ENIPExtractUint8(&service, input, &offset, input_len) != 1) - { + if (ENIPExtractUint8(&service, input, &offset, input_len) != 1) { return 0; } - if (ENIPExtractUint8(&path_size, input, &offset, input_len) != 1) - { + if (ENIPExtractUint8(&path_size, input, &offset, input_len) != 1) { return 0; } - if (service > MAX_CIP_SERVICE) - { // service codes of value 0x80 or greater are not permitted because in the CIP protocol the highest order bit is used to flag request(0)/response(1) + if (service > MAX_CIP_SERVICE) { // service codes of value 0x80 or greater are not permitted + // because in the CIP protocol the highest order bit is used to + // flag request(0)/response(1) SCLogDebug("DecodeCIPRequest - INVALID CIP SERVICE 0x%x", service); return 0; } - //reached maximum number of services - if (enip_data->service_count > 32) - { + // reached maximum number of services + if (enip_data->service_count > 32) { SCLogDebug("DecodeCIPRequest: Maximum services reached"); return 0; } - //save CIP data + // save CIP data CIPServiceEntry *node = CIPServiceAlloc(enip_data); - if (node == NULL) - { + if (node == NULL) { SCLogDebug("DecodeCIPRequest: Unable to create CIP service"); return 0; } @@ -505,11 +464,11 @@ int DecodeCIPRequestPDU(const uint8_t *input, uint32_t input_len, DecodeCIPRequestPathPDU(input, input_len, node, offset); - offset += path_size * sizeof(uint16_t); //move offset past pathsize + offset += path_size * sizeof(uint16_t); // move offset past pathsize - //list of CIP services is large and can be vendor specific, store CIP service anyways and let the rule decide the action - switch (service) - { + // list of CIP services is large and can be vendor specific, store CIP service anyways and let + // the rule decide the action + switch (service) { case CIP_RESERVED: SCLogDebug("DecodeCIPRequest - CIP_RESERVED"); break; @@ -572,27 +531,26 @@ int DecodeCIPRequestPDU(const uint8_t *input, uint32_t input_len, * @return 1 Packet matches * @return 0 Packet not match */ -int DecodeCIPRequestPathPDU(const uint8_t *input, uint32_t input_len, - CIPServiceEntry *node, uint16_t offset) +int DecodeCIPRequestPathPDU( + const uint8_t *input, uint32_t input_len, CIPServiceEntry *node, uint16_t offset) { - //SCLogDebug("DecodeCIPRequestPath: service 0x%x size %d length %d", + // SCLogDebug("DecodeCIPRequestPath: service 0x%x size %d length %d", // node->service, node->request.path_size, input_len); - if (node->request.path_size < 1) - { - //SCLogDebug("DecodeCIPRequestPath: empty path or CIP Response"); + if (node->request.path_size < 1) { + // SCLogDebug("DecodeCIPRequestPath: empty path or CIP Response"); return 0; } int bytes_remain = node->request.path_size; - uint8_t reserved; //unused byte reserved by ODVA + uint8_t reserved; // unused byte reserved by ODVA - //8 bit fields + // 8 bit fields uint8_t req_path_instance8; uint8_t req_path_attr8; - //16 bit fields + // 16 bit fields uint16_t req_path_class16; uint16_t req_path_instance16; @@ -600,21 +558,18 @@ int DecodeCIPRequestPathPDU(const uint8_t *input, uint32_t input_len, SegmentEntry *seg = NULL; - while (bytes_remain > 0) - { + while (bytes_remain > 0) { uint8_t segment = 0; - if (ENIPExtractUint8(&segment, input, &offset, input_len) != 1) - { + if (ENIPExtractUint8(&segment, input, &offset, input_len) != 1) { return 0; } - switch (segment) - { //assume order is class then instance. Can have multiple + switch (segment) { // assume order is class then instance. Can have multiple case PATH_CLASS_8BIT: { uint8_t req_path_class8 = 0; if (ENIPExtractUint8(&req_path_class8, input, &offset, input_len) != 1) { return 0; } - class = (uint16_t) req_path_class8; + class = (uint16_t)req_path_class8; SCLogDebug("DecodeCIPRequestPathPDU: 8bit class 0x%x", class); seg = SCMalloc(sizeof(SegmentEntry)); @@ -628,20 +583,18 @@ int DecodeCIPRequestPathPDU(const uint8_t *input, uint32_t input_len, break; } case PATH_INSTANCE_8BIT: - if (ENIPExtractUint8(&req_path_instance8, input, &offset, input_len) != 1) - { + if (ENIPExtractUint8(&req_path_instance8, input, &offset, input_len) != 1) { return 0; } - //skip instance, don't need to store + // skip instance, don't need to store bytes_remain--; break; - case PATH_ATTR_8BIT: //single attribute - if (ENIPExtractUint8(&req_path_attr8, input, &offset, input_len) != 1) - { + case PATH_ATTR_8BIT: // single attribute + if (ENIPExtractUint8(&req_path_attr8, input, &offset, input_len) != 1) { return 0; } - //uint16_t attrib = (uint16_t) req_path_attr8; - //SCLogDebug("DecodeCIPRequestPath: 8bit attr 0x%x", attrib); + // uint16_t attrib = (uint16_t) req_path_attr8; + // SCLogDebug("DecodeCIPRequestPath: 8bit attr 0x%x", attrib); seg = SCMalloc(sizeof(SegmentEntry)); if (unlikely(seg == NULL)) @@ -653,12 +606,11 @@ int DecodeCIPRequestPathPDU(const uint8_t *input, uint32_t input_len, bytes_remain--; break; case PATH_CLASS_16BIT: - if (ENIPExtractUint8(&reserved, input, &offset, input_len) != 1) //skip reserved + if (ENIPExtractUint8(&reserved, input, &offset, input_len) != 1) // skip reserved { return 0; } - if (ENIPExtractUint16(&req_path_class16, input, &offset, input_len) != 1) - { + if (ENIPExtractUint16(&req_path_class16, input, &offset, input_len) != 1) { return 0; } class = req_path_class16; @@ -670,11 +622,9 @@ int DecodeCIPRequestPathPDU(const uint8_t *input, uint32_t input_len, seg->segment = segment; seg->value = class; TAILQ_INSERT_TAIL(&node->segment_list, seg, next); - if (bytes_remain >= 2) - { + if (bytes_remain >= 2) { bytes_remain = bytes_remain - 2; - } else - { + } else { bytes_remain = 0; } break; @@ -683,54 +633,43 @@ int DecodeCIPRequestPathPDU(const uint8_t *input, uint32_t input_len, { return 0; } - if (ENIPExtractUint16(&req_path_instance16, input, &offset, input_len) != 1) - { + if (ENIPExtractUint16(&req_path_instance16, input, &offset, input_len) != 1) { return 0; } - //skip instance, don't need to store - if (bytes_remain >= 2) - { + // skip instance, don't need to store + if (bytes_remain >= 2) { bytes_remain = bytes_remain - 2; - } else - { + } else { bytes_remain = 0; } break; default: - SCLogDebug( - "DecodeCIPRequestPath: UNKNOWN SEGMENT 0x%x service 0x%x", - segment, node->service); + SCLogDebug("DecodeCIPRequestPath: UNKNOWN SEGMENT 0x%x service 0x%x", segment, + node->service); return 0; } } - if ((node->service == CIP_SET_ATTR_LIST) || (node->service - == CIP_GET_ATTR_LIST)) - { + if ((node->service == CIP_SET_ATTR_LIST) || (node->service == CIP_GET_ATTR_LIST)) { uint16_t attr_list_count; uint16_t attribute; - //parse get/set attribute list + // parse get/set attribute list - if (ENIPExtractUint16(&attr_list_count, input, &offset, input_len) != 1) - { + if (ENIPExtractUint16(&attr_list_count, input, &offset, input_len) != 1) { return 0; } - SCLogDebug("DecodeCIPRequestPathPDU: attribute list count %d", - attr_list_count); - for (int i = 0; i < attr_list_count; i++) - { - if (ENIPExtractUint16(&attribute, input, &offset, input_len) != 1) - { + SCLogDebug("DecodeCIPRequestPathPDU: attribute list count %d", attr_list_count); + for (int i = 0; i < attr_list_count; i++) { + if (ENIPExtractUint16(&attribute, input, &offset, input_len) != 1) { return 0; } SCLogDebug("DecodeCIPRequestPathPDU: attribute %d", attribute); - //save attrs + // save attrs AttributeEntry *attr = SCMalloc(sizeof(AttributeEntry)); if (unlikely(attr == NULL)) return 0; attr->attribute = attribute; TAILQ_INSERT_TAIL(&node->attrib_list, attr, next); - } } @@ -745,63 +684,57 @@ int DecodeCIPRequestPathPDU(const uint8_t *input, uint32_t input_len, * @return 1 Packet ok * @return 0 Packet has errors */ -int DecodeCIPResponsePDU(const uint8_t *input, uint32_t input_len, - ENIPTransaction *enip_data, uint16_t offset) +int DecodeCIPResponsePDU( + const uint8_t *input, uint32_t input_len, ENIPTransaction *enip_data, uint16_t offset) { int ret = 1; - if (enip_data->encap_data_item.length < sizeof(CIPRespHdr)) - { + if (enip_data->encap_data_item.length < sizeof(CIPRespHdr)) { SCLogDebug("DecodeCIPResponse - Malformed CIP Data"); return 0; } uint8_t service = 0; //<----CIP SERVICE - uint8_t reserved; //unused byte reserved by ODVA + uint8_t reserved; // unused byte reserved by ODVA uint16_t status; - if (ENIPExtractUint8(&service, input, &offset, input_len) != 1) - { + if (ENIPExtractUint8(&service, input, &offset, input_len) != 1) { return 0; } - if (ENIPExtractUint8(&reserved, input, &offset, input_len) != 1) - { + if (ENIPExtractUint8(&reserved, input, &offset, input_len) != 1) { return 0; } - if (ENIPExtractUint16(&status, input, &offset, input_len) != 1) - { + if (ENIPExtractUint16(&status, input, &offset, input_len) != 1) { return 0; } - //SCLogDebug("DecodeCIPResponse: service 0x%x",service); - service &= 0x7f; //strip off top bit to get service code. Responses have first bit as 1 + // SCLogDebug("DecodeCIPResponse: service 0x%x",service); + service &= 0x7f; // strip off top bit to get service code. Responses have first bit as 1 SCLogDebug("CIP service 0x%x status 0x%x", service, status); - //reached maximum number of services - if (enip_data->service_count > 32) - { + // reached maximum number of services + if (enip_data->service_count > 32) { SCLogDebug("DecodeCIPRequest: Maximum services reached"); return 0; } - //save CIP data + // save CIP data CIPServiceEntry *node = CIPServiceAlloc(enip_data); - if (node == NULL) - { + if (node == NULL) { SCLogDebug("DecodeCIPRequest: Unable to create CIP service"); - return 0; + return 0; } node->direction = 1; node->service = service; node->response.status = status; - SCLogDebug("DecodeCIPResponsePDU: service 0x%x size %d", node->service, - node->request.path_size); + SCLogDebug( + "DecodeCIPResponsePDU: service 0x%x size %d", node->service, node->request.path_size); - //list of CIP services is large and can be vendor specific, store CIP service anyways and let the rule decide the action - switch (service) - { + // list of CIP services is large and can be vendor specific, store CIP service anyways and let + // the rule decide the action + switch (service) { case CIP_RESERVED: SCLogDebug("DecodeCIPResponse - CIP_RESERVED"); break; @@ -855,7 +788,6 @@ int DecodeCIPResponsePDU(const uint8_t *input, uint32_t input_len, return ret; } - /** * \brief Decode CIP Request Multi Service Packet * @param input, input_len data stream @@ -864,16 +796,15 @@ int DecodeCIPResponsePDU(const uint8_t *input, uint32_t input_len, * @return 1 Packet ok * @return 0 Packet has errors */ -int DecodeCIPRequestMSPPDU(const uint8_t *input, uint32_t input_len, - ENIPTransaction *enip_data, uint16_t offset) +int DecodeCIPRequestMSPPDU( + const uint8_t *input, uint32_t input_len, ENIPTransaction *enip_data, uint16_t offset) { int ret = 1; - if (offset >= (input_len - sizeof(uint16_t))) - { + if (offset >= (input_len - sizeof(uint16_t))) { SCLogDebug("DecodeCIPRequestMSPPDU: Parsing beyond payload length"); return 0; } - //use temp_offset just to grab the service offset, don't want to use and push offset + // use temp_offset just to grab the service offset, don't want to use and push offset uint16_t temp_offset = offset; uint16_t num_services; if (ByteExtractUint16(&num_services, BYTE_LITTLE_ENDIAN, sizeof(uint16_t), @@ -882,32 +813,28 @@ int DecodeCIPRequestMSPPDU(const uint8_t *input, uint32_t input_len, } temp_offset += sizeof(uint16_t); - //SCLogDebug("DecodeCIPRequestMSP number of services %d",num_services); + // SCLogDebug("DecodeCIPRequestMSP number of services %d",num_services); - for (int svc = 1; svc < num_services + 1; svc++) - { - if (temp_offset >= (input_len - sizeof(uint16_t))) - { + for (int svc = 1; svc < num_services + 1; svc++) { + if (temp_offset >= (input_len - sizeof(uint16_t))) { SCLogDebug("DecodeCIPRequestMSPPDU: Parsing beyond payload length"); return 0; } - uint16_t svc_offset; //read set of service offsets + uint16_t svc_offset; // read set of service offsets if (ByteExtractUint16(&svc_offset, BYTE_LITTLE_ENDIAN, sizeof(uint16_t), (const uint8_t *)(input + temp_offset)) == -1) { return 0; } temp_offset += sizeof(uint16_t); - //SCLogDebug("parseCIPRequestMSP service %d offset %d",svc, svc_offset); + // SCLogDebug("parseCIPRequestMSP service %d offset %d",svc, svc_offset); - DecodeCIPPDU(input, input_len, enip_data, offset + svc_offset); //parse CIP at found offset + DecodeCIPPDU(input, input_len, enip_data, offset + svc_offset); // parse CIP at found offset } return ret; } - - /** * \brief Decode CIP Response MultiService Packet. * @param input, input_len data stream @@ -916,17 +843,16 @@ int DecodeCIPRequestMSPPDU(const uint8_t *input, uint32_t input_len, * @return 1 Packet ok * @return 0 Packet has errors */ -int DecodeCIPResponseMSPPDU(const uint8_t *input, uint32_t input_len, - ENIPTransaction *enip_data, uint16_t offset) +int DecodeCIPResponseMSPPDU( + const uint8_t *input, uint32_t input_len, ENIPTransaction *enip_data, uint16_t offset) { int ret = 1; - if (offset >= (input_len - sizeof(uint16_t))) - { + if (offset >= (input_len - sizeof(uint16_t))) { SCLogDebug("DecodeCIPResponseMSPPDU: Parsing beyond payload length"); return 0; } - //use temp_offset just to grab the service offset, don't want to use and push offset + // use temp_offset just to grab the service offset, don't want to use and push offset uint16_t temp_offset = offset; uint16_t num_services; if (ByteExtractUint16(&num_services, BYTE_LITTLE_ENDIAN, sizeof(uint16_t), @@ -934,24 +860,23 @@ int DecodeCIPResponseMSPPDU(const uint8_t *input, uint32_t input_len, return 0; } temp_offset += sizeof(uint16_t); - //SCLogDebug("DecodeCIPResponseMSP number of services %d", num_services); + // SCLogDebug("DecodeCIPResponseMSP number of services %d", num_services); for (int svc = 0; svc < num_services; svc++) { - if (temp_offset >= (input_len - sizeof(uint16_t))) - { + if (temp_offset >= (input_len - sizeof(uint16_t))) { SCLogDebug("DecodeCIPResponseMSP: Parsing beyond payload length"); return 0; } - uint16_t svc_offset; //read set of service offsets + uint16_t svc_offset; // read set of service offsets if (ByteExtractUint16(&svc_offset, BYTE_LITTLE_ENDIAN, sizeof(uint16_t), (const uint8_t *)(input + temp_offset)) == -1) { return 0; } temp_offset += sizeof(uint16_t); - //SCLogDebug("parseCIPResponseMSP service %d offset %d", svc, svc_offset); + // SCLogDebug("parseCIPResponseMSP service %d offset %d", svc, svc_offset); - DecodeCIPPDU(input, input_len, enip_data, offset + svc_offset); //parse CIP at found offset + DecodeCIPPDU(input, input_len, enip_data, offset + svc_offset); // parse CIP at found offset } return ret; diff --git a/src/app-layer-enip-common.h b/src/app-layer-enip-common.h index 1578343a69eb..318971e06dae 100644 --- a/src/app-layer-enip-common.h +++ b/src/app-layer-enip-common.h @@ -38,27 +38,27 @@ #define INDICATE_STATUS 0x0072 #define CANCEL 0x0073 -//Common Packet Format Types -#define NULL_ADDR 0x0000 -#define CONNECTION_BASED 0x00a1 -#define CONNECTED_DATA_ITEM 0x00b1 -#define UNCONNECTED_DATA_ITEM 0x00b2 -#define SEQUENCE_ADDR_ITEM 0xB002 - -//status codes -#define SUCCESS 0x0000 -#define INVALID_CMD 0x0001 -#define NO_RESOURCES 0x0002 -#define INCORRECT_DATA 0x0003 -#define INVALID_SESSION 0x0064 -#define INVALID_LENGTH 0x0065 -#define UNSUPPORTED_PROT_REV 0x0069 -//Found in wireshark -#define ENCAP_HEADER_ERROR 0x006A - -#define MAX_CIP_SERVICE 127 -#define MAX_CIP_CLASS 65535 -#define MAX_CIP_ATTRIBUTE 65535 +// Common Packet Format Types +#define NULL_ADDR 0x0000 +#define CONNECTION_BASED 0x00a1 +#define CONNECTED_DATA_ITEM 0x00b1 +#define UNCONNECTED_DATA_ITEM 0x00b2 +#define SEQUENCE_ADDR_ITEM 0xB002 + +// status codes +#define SUCCESS 0x0000 +#define INVALID_CMD 0x0001 +#define NO_RESOURCES 0x0002 +#define INCORRECT_DATA 0x0003 +#define INVALID_SESSION 0x0064 +#define INVALID_LENGTH 0x0065 +#define UNSUPPORTED_PROT_REV 0x0069 +// Found in wireshark +#define ENCAP_HEADER_ERROR 0x006A + +#define MAX_CIP_SERVICE 127 +#define MAX_CIP_CLASS 65535 +#define MAX_CIP_ATTRIBUTE 65535 // CIP service codes #define CIP_RESERVED 0x00 @@ -79,19 +79,18 @@ #define CIP_CHANGE_START 0x4f #define CIP_GET_STATUS 0x50 -//PATH sizing codes -#define PATH_CLASS_8BIT 0x20 -#define PATH_CLASS_16BIT 0x21 -#define PATH_INSTANCE_8BIT 0x24 -#define PATH_INSTANCE_16BIT 0x25 -#define PATH_ATTR_8BIT 0x30 -#define PATH_ATTR_16BIT 0x31 //possible value +// PATH sizing codes +#define PATH_CLASS_8BIT 0x20 +#define PATH_CLASS_16BIT 0x21 +#define PATH_INSTANCE_8BIT 0x24 +#define PATH_INSTANCE_16BIT 0x25 +#define PATH_ATTR_8BIT 0x30 +#define PATH_ATTR_16BIT 0x31 // possible value /** * ENIP encapsulation header */ -typedef struct ENIPEncapHdr_ -{ +typedef struct ENIPEncapHdr_ { uint64_t context; uint32_t session; uint32_t status; @@ -103,8 +102,7 @@ typedef struct ENIPEncapHdr_ /** * ENIP encapsulation data header */ -typedef struct ENIPEncapDataHdr_ -{ +typedef struct ENIPEncapDataHdr_ { uint32_t interface_handle; uint16_t timeout; uint16_t item_count; @@ -123,8 +121,7 @@ typedef struct ENIPEncapAddressItem_ { /** * ENIP encapsulation data item */ -typedef struct ENIPEncapDataItem_ -{ +typedef struct ENIPEncapDataItem_ { uint16_t type; uint16_t length; uint16_t sequence_count; @@ -133,8 +130,7 @@ typedef struct ENIPEncapDataItem_ /** * CIP Request Header */ -typedef struct CIPReqHdr_ -{ +typedef struct CIPReqHdr_ { uint8_t service; uint8_t path_size; } CIPReqHdr; @@ -142,63 +138,55 @@ typedef struct CIPReqHdr_ /** * CIP Response Header */ -typedef struct CIPRespHdr_ -{ +typedef struct CIPRespHdr_ { uint8_t service; uint8_t pad; uint8_t status; uint8_t status_size; } CIPRespHdr; -typedef struct SegmentEntry_ -{ - uint16_t segment; /**< segment type */ - uint16_t value; /**< segment value (class or attribute) */ +typedef struct SegmentEntry_ { + uint16_t segment; /**< segment type */ + uint16_t value; /**< segment value (class or attribute) */ TAILQ_ENTRY(SegmentEntry_) next; } SegmentEntry; -typedef struct AttributeEntry_ -{ +typedef struct AttributeEntry_ { uint16_t attribute; /**< segment class */ TAILQ_ENTRY(AttributeEntry_) next; } AttributeEntry; -typedef struct CIPServiceEntry_ -{ - uint8_t service; /**< cip service */ +typedef struct CIPServiceEntry_ { + uint8_t service; /**< cip service */ uint8_t direction; - union - { - struct - { - uint8_t path_size; /**< cip path size */ - uint16_t path_offset; /**< offset to cip path */ + union { + struct { + uint8_t path_size; /**< cip path size */ + uint16_t path_offset; /**< offset to cip path */ } request; - struct - { + struct { uint16_t status; } response; }; - TAILQ_HEAD(, SegmentEntry_) segment_list; /**< list for CIP segment */ - TAILQ_HEAD(, AttributeEntry_) attrib_list; /**< list for CIP segment */ + TAILQ_HEAD(, SegmentEntry_) segment_list; /**< list for CIP segment */ + TAILQ_HEAD(, AttributeEntry_) attrib_list; /**< list for CIP segment */ TAILQ_ENTRY(CIPServiceEntry_) next; } CIPServiceEntry; -typedef struct ENIPTransaction_ -{ +typedef struct ENIPTransaction_ { struct ENIPState_ *enip; - uint64_t tx_num; /**< internal: id */ - uint16_t tx_id; /**< transaction id */ + uint64_t tx_num; /**< internal: id */ + uint16_t tx_id; /**< transaction id */ uint16_t service_count; - ENIPEncapHdr header; /**< encapsulation header */ - ENIPEncapDataHdr encap_data_header; /**< encapsulation data header */ - ENIPEncapAddressItem encap_addr_item; /**< encapsulated address item */ - ENIPEncapDataItem encap_data_item; /**< encapsulated data item */ + ENIPEncapHdr header; /**< encapsulation header */ + ENIPEncapDataHdr encap_data_header; /**< encapsulation data header */ + ENIPEncapAddressItem encap_addr_item; /**< encapsulated address item */ + ENIPEncapDataItem encap_data_item; /**< encapsulated data item */ TAILQ_HEAD(, CIPServiceEntry_) service_list; /**< list for CIP */ @@ -207,8 +195,7 @@ typedef struct ENIPTransaction_ } ENIPTransaction; /** \brief Per flow ENIP state container */ -typedef struct ENIPState_ -{ +typedef struct ENIPState_ { AppLayerStateData state_data; TAILQ_HEAD(, ENIPTransaction_) tx_list; /**< transaction list */ ENIPTransaction *curr; /**< ptr to current tx */ @@ -225,21 +212,20 @@ typedef struct ENIPState_ uint8_t *buffer; } ENIPState; -int DecodeENIPPDU(const uint8_t *input, uint32_t input_len, - ENIPTransaction *enip_data); -int DecodeCommonPacketFormatPDU(const uint8_t *input, uint32_t input_len, - ENIPTransaction *enip_data, uint16_t offset); -int DecodeCIPPDU(const uint8_t *input, uint32_t input_len, - ENIPTransaction *enip_data, uint16_t offset); -int DecodeCIPRequestPDU(const uint8_t *input, uint32_t input_len, - ENIPTransaction *enip_data, uint16_t offset); -int DecodeCIPResponsePDU(const uint8_t *input, uint32_t input_len, - ENIPTransaction *enip_data, uint16_t offset); -int DecodeCIPRequestPathPDU(const uint8_t *input, uint32_t input_len, - CIPServiceEntry *node, uint16_t offset); -int DecodeCIPRequestMSPPDU(const uint8_t *input, uint32_t input_len, - ENIPTransaction *enip_data, uint16_t offset); -int DecodeCIPResponseMSPPDU(const uint8_t *input, uint32_t input_len, - ENIPTransaction *enip_data, uint16_t offset); +int DecodeENIPPDU(const uint8_t *input, uint32_t input_len, ENIPTransaction *enip_data); +int DecodeCommonPacketFormatPDU( + const uint8_t *input, uint32_t input_len, ENIPTransaction *enip_data, uint16_t offset); +int DecodeCIPPDU( + const uint8_t *input, uint32_t input_len, ENIPTransaction *enip_data, uint16_t offset); +int DecodeCIPRequestPDU( + const uint8_t *input, uint32_t input_len, ENIPTransaction *enip_data, uint16_t offset); +int DecodeCIPResponsePDU( + const uint8_t *input, uint32_t input_len, ENIPTransaction *enip_data, uint16_t offset); +int DecodeCIPRequestPathPDU( + const uint8_t *input, uint32_t input_len, CIPServiceEntry *node, uint16_t offset); +int DecodeCIPRequestMSPPDU( + const uint8_t *input, uint32_t input_len, ENIPTransaction *enip_data, uint16_t offset); +int DecodeCIPResponseMSPPDU( + const uint8_t *input, uint32_t input_len, ENIPTransaction *enip_data, uint16_t offset); #endif /* __APP_LAYER_ENIP_COMMON_H__ */ diff --git a/src/app-layer-enip.c b/src/app-layer-enip.c index 903df3045fe3..266f3a9bf2d7 100644 --- a/src/app-layer-enip.c +++ b/src/app-layer-enip.c @@ -53,9 +53,8 @@ #include "pkt-var.h" #include "util-profiling.h" - -SCEnumCharMap enip_decoder_event_table[ ] = { - { NULL, -1 }, +SCEnumCharMap enip_decoder_event_table[] = { + { NULL, -1 }, }; /** \brief get value for 'complete' status in ENIP @@ -81,14 +80,14 @@ static AppLayerStateData *ENIPGetStateData(void *vstate) static void *ENIPGetTx(void *alstate, uint64_t tx_id) { - ENIPState *enip = (ENIPState *) alstate; - ENIPTransaction *tx = NULL; + ENIPState *enip = (ENIPState *)alstate; + ENIPTransaction *tx = NULL; if (enip->curr && enip->curr->tx_num == tx_id + 1) return enip->curr; - TAILQ_FOREACH(tx, &enip->tx_list, next) { - if (tx->tx_num != (tx_id+1)) + TAILQ_FOREACH (tx, &enip->tx_list, next) { + if (tx->tx_num != (tx_id + 1)) continue; SCLogDebug("returning tx %p", tx); @@ -103,7 +102,8 @@ static uint64_t ENIPGetTxCnt(void *alstate) return ((ENIPState *)alstate)->transaction_max; } -static int ENIPStateGetEventInfo(const char *event_name, int *event_id, AppLayerEventType *event_type) +static int ENIPStateGetEventInfo( + const char *event_name, int *event_id, AppLayerEventType *event_type) { *event_id = SCMapEnumNameToValue(event_name, enip_decoder_event_table); @@ -120,8 +120,8 @@ static int ENIPStateGetEventInfo(const char *event_name, int *event_id, AppLayer return 0; } -static int ENIPStateGetEventInfoById(int event_id, const char **event_name, - AppLayerEventType *event_type) +static int ENIPStateGetEventInfoById( + int event_id, const char **event_name, AppLayerEventType *event_type) { *event_name = SCMapEnumValueToName(event_id, enip_decoder_event_table); if (*event_name == NULL) { @@ -148,7 +148,7 @@ static void *ENIPStateAlloc(void *orig_state, AppProto proto_orig) if (unlikely(s == NULL)) return NULL; - ENIPState *enip_state = (ENIPState *) s; + ENIPState *enip_state = (ENIPState *)s; TAILQ_INIT(&enip_state->tx_list); return s; @@ -162,20 +162,17 @@ static void ENIPTransactionFree(ENIPTransaction *tx, ENIPState *state) SCEnter(); SCLogDebug("ENIPTransactionFree"); CIPServiceEntry *svc = NULL; - while ((svc = TAILQ_FIRST(&tx->service_list))) - { + while ((svc = TAILQ_FIRST(&tx->service_list))) { TAILQ_REMOVE(&tx->service_list, svc, next); SegmentEntry *seg = NULL; - while ((seg = TAILQ_FIRST(&svc->segment_list))) - { + while ((seg = TAILQ_FIRST(&svc->segment_list))) { TAILQ_REMOVE(&svc->segment_list, seg, next); SCFree(seg); } AttributeEntry *attr = NULL; - while ((attr = TAILQ_FIRST(&svc->attrib_list))) - { + while ((attr = TAILQ_FIRST(&svc->attrib_list))) { TAILQ_REMOVE(&svc->attrib_list, attr, next); SCFree(attr); } @@ -205,19 +202,16 @@ static void ENIPStateFree(void *s) { SCEnter(); SCLogDebug("ENIPStateFree"); - if (s) - { - ENIPState *enip_state = (ENIPState *) s; + if (s) { + ENIPState *enip_state = (ENIPState *)s; ENIPTransaction *tx = NULL; - while ((tx = TAILQ_FIRST(&enip_state->tx_list))) - { + while ((tx = TAILQ_FIRST(&enip_state->tx_list))) { TAILQ_REMOVE(&enip_state->tx_list, tx, next); ENIPTransactionFree(tx, enip_state); } - if (enip_state->buffer != NULL) - { + if (enip_state->buffer != NULL) { SCFree(enip_state->buffer); } @@ -232,8 +226,7 @@ static void ENIPStateFree(void *s) static ENIPTransaction *ENIPTransactionAlloc(ENIPState *state) { SCLogDebug("ENIPStateTransactionAlloc"); - ENIPTransaction *tx = (ENIPTransaction *) SCCalloc(1, - sizeof(ENIPTransaction)); + ENIPTransaction *tx = (ENIPTransaction *)SCCalloc(1, sizeof(ENIPTransaction)); if (unlikely(tx == NULL)) return NULL; @@ -242,8 +235,8 @@ static ENIPTransaction *ENIPTransactionAlloc(ENIPState *state) TAILQ_INIT(&tx->service_list); - tx->enip = state; - tx->tx_num = state->transaction_max; + tx->enip = state; + tx->tx_num = state->transaction_max; tx->service_count = 0; TAILQ_INSERT_TAIL(&state->tx_list, tx, next); @@ -260,16 +253,15 @@ static void ENIPStateTransactionFree(void *state, uint64_t tx_id) SCLogDebug("ENIPStateTransactionFree"); ENIPState *enip_state = state; ENIPTransaction *tx = NULL; - TAILQ_FOREACH(tx, &enip_state->tx_list, next) - { + TAILQ_FOREACH (tx, &enip_state->tx_list, next) { - if ((tx_id+1) < tx->tx_num) - break; - else if ((tx_id+1) > tx->tx_num) - continue; + if ((tx_id + 1) < tx->tx_num) + break; + else if ((tx_id + 1) > tx->tx_num) + continue; if (tx == enip_state->curr) - enip_state->curr = NULL; + enip_state->curr = NULL; if (tx->tx_data.events != NULL) { if (tx->tx_data.events->cnt <= enip_state->events) @@ -299,26 +291,23 @@ static AppLayerResult ENIPParse(Flow *f, void *state, AppLayerParserState *pstat StreamSlice stream_slice, void *local_data, uint8_t direction) { SCEnter(); - ENIPState *enip = (ENIPState *) state; + ENIPState *enip = (ENIPState *)state; ENIPTransaction *tx; const uint8_t *input = StreamSliceGetData(&stream_slice); uint32_t input_len = StreamSliceGetDataLen(&stream_slice); - if (input == NULL && AppLayerParserStateIssetFlag(pstate, - APP_LAYER_PARSER_EOF_TS|APP_LAYER_PARSER_EOF_TC)) - { + if (input == NULL && AppLayerParserStateIssetFlag( + pstate, APP_LAYER_PARSER_EOF_TS | APP_LAYER_PARSER_EOF_TC)) { SCReturnStruct(APP_LAYER_OK); } else if (input == NULL && input_len != 0) { // GAP SCReturnStruct(APP_LAYER_OK); - } else if (input == NULL || input_len == 0) - { + } else if (input == NULL || input_len == 0) { SCReturnStruct(APP_LAYER_ERROR); } - while (input_len > 0) - { + while (input_len > 0) { tx = ENIPTransactionAlloc(enip); if (tx == NULL) SCReturnStruct(APP_LAYER_OK); @@ -332,19 +321,17 @@ static AppLayerResult ENIPParse(Flow *f, void *state, AppLayerParserState *pstat DecodeENIPPDU(input, input_len, tx); uint32_t pkt_len = tx->header.length + sizeof(ENIPEncapHdr); SCLogDebug("ENIPParse packet len %d", pkt_len); - if (pkt_len > input_len) - { + if (pkt_len > input_len) { SCLogDebug("Invalid packet length"); break; } input += pkt_len; input_len -= pkt_len; - //SCLogDebug("remaining %d", input_len); + // SCLogDebug("remaining %d", input_len); - if (input_len < sizeof(ENIPEncapHdr)) - { - //SCLogDebug("Not enough data"); //not enough data for ENIP + if (input_len < sizeof(ENIPEncapHdr)) { + // SCLogDebug("Not enough data"); //not enough data for ENIP break; } } @@ -366,12 +353,11 @@ static AppLayerResult ENIPParseResponse(Flow *f, void *state, AppLayerParserStat #define ENIP_LEN_REGISTER_SESSION 4 // protocol u16, options u16 -static uint16_t ENIPProbingParser(Flow *f, uint8_t direction, - const uint8_t *input, uint32_t input_len, uint8_t *rdir) +static uint16_t ENIPProbingParser( + Flow *f, uint8_t direction, const uint8_t *input, uint32_t input_len, uint8_t *rdir) { // SCLogDebug("ENIPProbingParser %d", input_len); - if (input_len < sizeof(ENIPEncapHdr)) - { + if (input_len < sizeof(ENIPEncapHdr)) { SCLogDebug("length too small to be a ENIP header"); return ALPROTO_UNKNOWN; } @@ -400,7 +386,7 @@ static uint16_t ENIPProbingParser(Flow *f, uint8_t direction, return ALPROTO_FAILED; } ret = ByteExtractUint16(&cmd, BYTE_LITTLE_ENDIAN, sizeof(uint16_t), (const uint8_t *)(input)); - if(ret < 0) { + if (ret < 0) { return ALPROTO_FAILED; } ret = ByteExtractUint32( @@ -414,8 +400,8 @@ static uint16_t ENIPProbingParser(Flow *f, uint8_t direction, return ALPROTO_FAILED; } - //ok for all the known commands - switch(cmd) { + // ok for all the known commands + switch (cmd) { case NOP: if (option != 0) { return ALPROTO_FAILED; @@ -446,7 +432,7 @@ static uint16_t ENIPProbingParser(Flow *f, uint8_t direction, } ret = ByteExtractUint16( &nbitems, BYTE_LITTLE_ENDIAN, sizeof(uint16_t), (const uint8_t *)(input)); - if(ret < 0) { + if (ret < 0) { return ALPROTO_FAILED; } if (enip_len < sizeof(ENIPEncapHdr) + 2 * (size_t)nbitems) { @@ -504,46 +490,36 @@ void RegisterENIPUDPParsers(void) if (AppLayerProtoDetectConfProtoDetectionEnabledDefault("udp", proto_name, false)) { AppLayerProtoDetectRegisterProtocol(ALPROTO_ENIP, proto_name); - if (RunmodeIsUnittests()) - { - AppLayerProtoDetectPPRegister(IPPROTO_UDP, "44818", ALPROTO_ENIP, - 0, sizeof(ENIPEncapHdr), STREAM_TOSERVER, ENIPProbingParser, NULL); - - AppLayerProtoDetectPPRegister(IPPROTO_UDP, "44818", ALPROTO_ENIP, - 0, sizeof(ENIPEncapHdr), STREAM_TOCLIENT, ENIPProbingParser, NULL); - - } else - { - if (!AppLayerProtoDetectPPParseConfPorts("udp", IPPROTO_UDP, - proto_name, ALPROTO_ENIP, 0, sizeof(ENIPEncapHdr), - ENIPProbingParser, ENIPProbingParser)) - { - SCLogDebug( - "no ENIP UDP config found enabling ENIP detection on port 44818."); - - AppLayerProtoDetectPPRegister(IPPROTO_UDP, "44818", - ALPROTO_ENIP, 0, sizeof(ENIPEncapHdr), STREAM_TOSERVER, - ENIPProbingParser, NULL); - - AppLayerProtoDetectPPRegister(IPPROTO_UDP, "44818", - ALPROTO_ENIP, 0, sizeof(ENIPEncapHdr), STREAM_TOCLIENT, - ENIPProbingParser, NULL); + if (RunmodeIsUnittests()) { + AppLayerProtoDetectPPRegister(IPPROTO_UDP, "44818", ALPROTO_ENIP, 0, + sizeof(ENIPEncapHdr), STREAM_TOSERVER, ENIPProbingParser, NULL); + + AppLayerProtoDetectPPRegister(IPPROTO_UDP, "44818", ALPROTO_ENIP, 0, + sizeof(ENIPEncapHdr), STREAM_TOCLIENT, ENIPProbingParser, NULL); + + } else { + if (!AppLayerProtoDetectPPParseConfPorts("udp", IPPROTO_UDP, proto_name, ALPROTO_ENIP, + 0, sizeof(ENIPEncapHdr), ENIPProbingParser, ENIPProbingParser)) { + SCLogDebug("no ENIP UDP config found enabling ENIP detection on port 44818."); + + AppLayerProtoDetectPPRegister(IPPROTO_UDP, "44818", ALPROTO_ENIP, 0, + sizeof(ENIPEncapHdr), STREAM_TOSERVER, ENIPProbingParser, NULL); + + AppLayerProtoDetectPPRegister(IPPROTO_UDP, "44818", ALPROTO_ENIP, 0, + sizeof(ENIPEncapHdr), STREAM_TOCLIENT, ENIPProbingParser, NULL); } } } else { - SCLogConfig("Protocol detection and parser disabled for %s protocol.", - proto_name); + SCLogConfig("Protocol detection and parser disabled for %s protocol.", proto_name); return; } - if (AppLayerParserConfParserEnabled("udp", proto_name)) - { + if (AppLayerParserConfParserEnabled("udp", proto_name)) { AppLayerParserRegisterParser(IPPROTO_UDP, ALPROTO_ENIP, STREAM_TOSERVER, ENIPParseRequest); AppLayerParserRegisterParser(IPPROTO_UDP, ALPROTO_ENIP, STREAM_TOCLIENT, ENIPParseResponse); - AppLayerParserRegisterStateFuncs(IPPROTO_UDP, ALPROTO_ENIP, - ENIPStateAlloc, ENIPStateFree); + AppLayerParserRegisterStateFuncs(IPPROTO_UDP, ALPROTO_ENIP, ENIPStateAlloc, ENIPStateFree); AppLayerParserRegisterGetTx(IPPROTO_UDP, ALPROTO_ENIP, ENIPGetTx); AppLayerParserRegisterGetTxIterator(IPPROTO_UDP, ALPROTO_ENIP, ENIPGetTxIterator); @@ -552,18 +528,19 @@ void RegisterENIPUDPParsers(void) AppLayerParserRegisterGetTxCnt(IPPROTO_UDP, ALPROTO_ENIP, ENIPGetTxCnt); AppLayerParserRegisterTxFreeFunc(IPPROTO_UDP, ALPROTO_ENIP, ENIPStateTransactionFree); - AppLayerParserRegisterGetStateProgressFunc(IPPROTO_UDP, ALPROTO_ENIP, ENIPGetAlstateProgress); + AppLayerParserRegisterGetStateProgressFunc( + IPPROTO_UDP, ALPROTO_ENIP, ENIPGetAlstateProgress); AppLayerParserRegisterStateProgressCompletionStatus(ALPROTO_ENIP, 1, 1); AppLayerParserRegisterGetEventInfo(IPPROTO_UDP, ALPROTO_ENIP, ENIPStateGetEventInfo); - AppLayerParserRegisterGetEventInfoById(IPPROTO_UDP, ALPROTO_ENIP, ENIPStateGetEventInfoById); + AppLayerParserRegisterGetEventInfoById( + IPPROTO_UDP, ALPROTO_ENIP, ENIPStateGetEventInfoById); AppLayerParserRegisterParserAcceptableDataDirection( IPPROTO_UDP, ALPROTO_ENIP, STREAM_TOSERVER | STREAM_TOCLIENT); - } else - { - SCLogInfo( - "Parsed disabled for %s protocol. Protocol detection" "still on.", + } else { + SCLogInfo("Parsed disabled for %s protocol. Protocol detection" + "still on.", proto_name); } @@ -585,36 +562,29 @@ void RegisterENIPTCPParsers(void) if (AppLayerProtoDetectConfProtoDetectionEnabledDefault("tcp", proto_name, false)) { AppLayerProtoDetectRegisterProtocol(ALPROTO_ENIP, proto_name); - if (RunmodeIsUnittests()) - { - AppLayerProtoDetectPPRegister(IPPROTO_TCP, "44818", ALPROTO_ENIP, - 0, sizeof(ENIPEncapHdr), STREAM_TOSERVER, ENIPProbingParser, NULL); + if (RunmodeIsUnittests()) { + AppLayerProtoDetectPPRegister(IPPROTO_TCP, "44818", ALPROTO_ENIP, 0, + sizeof(ENIPEncapHdr), STREAM_TOSERVER, ENIPProbingParser, NULL); - AppLayerProtoDetectPPRegister(IPPROTO_TCP, "44818", ALPROTO_ENIP, - 0, sizeof(ENIPEncapHdr), STREAM_TOCLIENT, ENIPProbingParser, NULL); + AppLayerProtoDetectPPRegister(IPPROTO_TCP, "44818", ALPROTO_ENIP, 0, + sizeof(ENIPEncapHdr), STREAM_TOCLIENT, ENIPProbingParser, NULL); - } else - { - if (!AppLayerProtoDetectPPParseConfPorts("tcp", IPPROTO_TCP, - proto_name, ALPROTO_ENIP, 0, sizeof(ENIPEncapHdr), - ENIPProbingParser, ENIPProbingParser)) - { + } else { + if (!AppLayerProtoDetectPPParseConfPorts("tcp", IPPROTO_TCP, proto_name, ALPROTO_ENIP, + 0, sizeof(ENIPEncapHdr), ENIPProbingParser, ENIPProbingParser)) { return; } } } else { - SCLogDebug("Protocol detection and parser disabled for %s protocol.", - proto_name); + SCLogDebug("Protocol detection and parser disabled for %s protocol.", proto_name); return; } - if (AppLayerParserConfParserEnabled("tcp", proto_name)) - { + if (AppLayerParserConfParserEnabled("tcp", proto_name)) { AppLayerParserRegisterParser(IPPROTO_TCP, ALPROTO_ENIP, STREAM_TOSERVER, ENIPParseRequest); AppLayerParserRegisterParser(IPPROTO_TCP, ALPROTO_ENIP, STREAM_TOCLIENT, ENIPParseResponse); - AppLayerParserRegisterStateFuncs(IPPROTO_TCP, ALPROTO_ENIP, - ENIPStateAlloc, ENIPStateFree); + AppLayerParserRegisterStateFuncs(IPPROTO_TCP, ALPROTO_ENIP, ENIPStateAlloc, ENIPStateFree); AppLayerParserRegisterGetTx(IPPROTO_TCP, ALPROTO_ENIP, ENIPGetTx); AppLayerParserRegisterGetTxIterator(IPPROTO_TCP, ALPROTO_ENIP, ENIPGetTxIterator); @@ -623,23 +593,22 @@ void RegisterENIPTCPParsers(void) AppLayerParserRegisterGetTxCnt(IPPROTO_TCP, ALPROTO_ENIP, ENIPGetTxCnt); AppLayerParserRegisterTxFreeFunc(IPPROTO_TCP, ALPROTO_ENIP, ENIPStateTransactionFree); - AppLayerParserRegisterGetStateProgressFunc(IPPROTO_TCP, ALPROTO_ENIP, ENIPGetAlstateProgress); + AppLayerParserRegisterGetStateProgressFunc( + IPPROTO_TCP, ALPROTO_ENIP, ENIPGetAlstateProgress); AppLayerParserRegisterStateProgressCompletionStatus(ALPROTO_ENIP, 1, 1); AppLayerParserRegisterGetEventInfo(IPPROTO_TCP, ALPROTO_ENIP, ENIPStateGetEventInfo); - AppLayerParserRegisterParserAcceptableDataDirection(IPPROTO_TCP, - ALPROTO_ENIP, STREAM_TOSERVER | STREAM_TOCLIENT); + AppLayerParserRegisterParserAcceptableDataDirection( + IPPROTO_TCP, ALPROTO_ENIP, STREAM_TOSERVER | STREAM_TOCLIENT); /* This parser accepts gaps. */ - AppLayerParserRegisterOptionFlags(IPPROTO_TCP, ALPROTO_ENIP, - APP_LAYER_PARSER_OPT_ACCEPT_GAPS); + AppLayerParserRegisterOptionFlags( + IPPROTO_TCP, ALPROTO_ENIP, APP_LAYER_PARSER_OPT_ACCEPT_GAPS); AppLayerParserRegisterOptionFlags(IPPROTO_TCP, ALPROTO_ENIP, 0); - } else - { - SCLogConfig("Parser disabled for %s protocol. Protocol detection still on.", - proto_name); + } else { + SCLogConfig("Parser disabled for %s protocol. Protocol detection still on.", proto_name); } #ifdef UNITTESTS @@ -676,17 +645,17 @@ static int ALDecodeENIPTest(void) memset(&f, 0, sizeof(f)); memset(&ssn, 0, sizeof(ssn)); - f.protoctx = (void *)&ssn; - f.proto = IPPROTO_TCP; - f.alproto = ALPROTO_ENIP; + f.protoctx = (void *)&ssn; + f.proto = IPPROTO_TCP; + f.alproto = ALPROTO_ENIP; StreamTcpInitConfig(true); - int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_ENIP, STREAM_TOSERVER, - listIdentity, sizeof(listIdentity)); + int r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_ENIP, STREAM_TOSERVER, listIdentity, sizeof(listIdentity)); FAIL_IF(r != 0); - ENIPState *enip_state = f.alstate; + ENIPState *enip_state = f.alstate; FAIL_IF_NULL(enip_state); ENIPTransaction *tx = ENIPGetTx(enip_state, 0); @@ -706,6 +675,6 @@ static int ALDecodeENIPTest(void) void ENIPParserRegisterTests(void) { #ifdef UNITTESTS - UtRegisterTest("ALDecodeENIPTest", ALDecodeENIPTest); + UtRegisterTest("ALDecodeENIPTest", ALDecodeENIPTest); #endif /* UNITTESTS */ } diff --git a/src/app-layer-enip.h b/src/app-layer-enip.h index 25cb1d5745da..5feac137b324 100644 --- a/src/app-layer-enip.h +++ b/src/app-layer-enip.h @@ -24,7 +24,6 @@ #ifndef __APP_LAYER_ENIP_H__ #define __APP_LAYER_ENIP_H__ - void RegisterENIPUDPParsers(void); void RegisterENIPTCPParsers(void); void ENIPParserRegisterTests(void); diff --git a/src/app-layer-events.c b/src/app-layer-events.c index be5ee99ac290..7e3f251113c2 100644 --- a/src/app-layer-events.c +++ b/src/app-layer-events.c @@ -31,25 +31,17 @@ /* events raised during protocol detection are stored in the * packets storage, not in the flow. */ -SCEnumCharMap app_layer_event_pkt_table[ ] = { - { "APPLAYER_MISMATCH_PROTOCOL_BOTH_DIRECTIONS", - APPLAYER_MISMATCH_PROTOCOL_BOTH_DIRECTIONS }, - { "APPLAYER_WRONG_DIRECTION_FIRST_DATA", - APPLAYER_WRONG_DIRECTION_FIRST_DATA }, - { "APPLAYER_DETECT_PROTOCOL_ONLY_ONE_DIRECTION", - APPLAYER_DETECT_PROTOCOL_ONLY_ONE_DIRECTION }, - { "APPLAYER_PROTO_DETECTION_SKIPPED", - APPLAYER_PROTO_DETECTION_SKIPPED }, - { "APPLAYER_NO_TLS_AFTER_STARTTLS", - APPLAYER_NO_TLS_AFTER_STARTTLS }, - { "APPLAYER_UNEXPECTED_PROTOCOL", - APPLAYER_UNEXPECTED_PROTOCOL }, - { NULL, - -1 }, +SCEnumCharMap app_layer_event_pkt_table[] = { + { "APPLAYER_MISMATCH_PROTOCOL_BOTH_DIRECTIONS", APPLAYER_MISMATCH_PROTOCOL_BOTH_DIRECTIONS }, + { "APPLAYER_WRONG_DIRECTION_FIRST_DATA", APPLAYER_WRONG_DIRECTION_FIRST_DATA }, + { "APPLAYER_DETECT_PROTOCOL_ONLY_ONE_DIRECTION", APPLAYER_DETECT_PROTOCOL_ONLY_ONE_DIRECTION }, + { "APPLAYER_PROTO_DETECTION_SKIPPED", APPLAYER_PROTO_DETECTION_SKIPPED }, + { "APPLAYER_NO_TLS_AFTER_STARTTLS", APPLAYER_NO_TLS_AFTER_STARTTLS }, + { "APPLAYER_UNEXPECTED_PROTOCOL", APPLAYER_UNEXPECTED_PROTOCOL }, + { NULL, -1 }, }; -int AppLayerGetEventInfoById(int event_id, const char **event_name, - AppLayerEventType *event_type) +int AppLayerGetEventInfoById(int event_id, const char **event_name, AppLayerEventType *event_type) { *event_name = SCMapEnumValueToName(event_id, app_layer_event_pkt_table); if (*event_name == NULL) { @@ -96,7 +88,6 @@ void AppLayerDecoderEventsSetEventRaw(AppLayerDecoderEvents **sevents, uint8_t e return; *sevents = new_devents; - } if ((*sevents)->cnt == UCHAR_MAX) { /* we're full */ @@ -107,8 +98,7 @@ void AppLayerDecoderEventsSetEventRaw(AppLayerDecoderEvents **sevents, uint8_t e if (UCHAR_MAX - (*sevents)->cnt < steps) steps = UCHAR_MAX - (*sevents)->cnt < steps; - void *ptr = SCRealloc((*sevents)->events, - ((*sevents)->cnt + steps) * sizeof(uint8_t)); + void *ptr = SCRealloc((*sevents)->events, ((*sevents)->cnt + steps) * sizeof(uint8_t)); if (ptr == NULL) { /* couldn't grow buffer, but no reason to free old * so we keep the events that may already be here */ @@ -129,7 +119,6 @@ void AppLayerDecoderEventsResetEvents(AppLayerDecoderEvents *events) } } - void AppLayerDecoderEventsFreeEvents(AppLayerDecoderEvents **events) { if (events && *events != NULL) { diff --git a/src/app-layer-events.h b/src/app-layer-events.h index 8b0dc8276d61..de6d9357edde 100644 --- a/src/app-layer-events.h +++ b/src/app-layer-events.h @@ -55,8 +55,7 @@ enum { int AppLayerGetPktEventInfo(const char *event_name, int *event_id); -int AppLayerGetEventInfoById(int event_id, const char **event_name, - AppLayerEventType *event_type); +int AppLayerGetEventInfoById(int event_id, const char **event_name, AppLayerEventType *event_type); void AppLayerDecoderEventsSetEventRaw(AppLayerDecoderEvents **sevents, uint8_t event); static inline int AppLayerDecoderEventsIsEventSet( @@ -79,4 +78,3 @@ void AppLayerDecoderEventsFreeEvents(AppLayerDecoderEvents **events); int DetectEngineGetEventInfo(const char *event_name, int *event_id, AppLayerEventType *event_type); #endif /* __APP_LAYER_EVENTS_H__ */ - diff --git a/src/app-layer-expectation.c b/src/app-layer-expectation.c index 7a456f87a336..005baf3b857c 100644 --- a/src/app-layer-expectation.c +++ b/src/app-layer-expectation.c @@ -67,7 +67,7 @@ static FlowStorageId g_flow_expectation_id = { .id = -1 }; SC_ATOMIC_DECLARE(uint32_t, expectation_count); -#define EXPECTATION_TIMEOUT 30 +#define EXPECTATION_TIMEOUT 30 #define EXPECTATION_MAX_LEVEL 10 typedef struct Expectation_ { @@ -96,7 +96,7 @@ typedef struct ExpectationList_ { static void ExpectationDataFree(void *e) { SCLogDebug("Free expectation data"); - ExpectationData *ed = (ExpectationData *) e; + ExpectationData *ed = (ExpectationData *)e; if (ed->DFree) { ed->DFree(e); } else { @@ -128,7 +128,7 @@ static void ExpectationListFree(void *el) if (exp_list->length > 0) { Expectation *exp = NULL, *pexp = NULL; - CIRCLEQ_FOREACH_SAFE(exp, &exp_list->list, entries, pexp) { + CIRCLEQ_FOREACH_SAFE (exp, &exp_list->list, entries, pexp) { CIRCLEQ_REMOVE(&exp_list->list, exp, entries); exp_list->length--; AppLayerFreeExpectation(exp); @@ -181,10 +181,8 @@ static ExpectationList *AppLayerExpectationLookup(Flow *f, IPPair **ipp) return IPPairGetStorageById(*ipp, g_ippair_expectation_id); } - -static ExpectationList *AppLayerExpectationRemove(IPPair *ipp, - ExpectationList *exp_list, - Expectation *exp) +static ExpectationList *AppLayerExpectationRemove( + IPPair *ipp, ExpectationList *exp_list, Expectation *exp) { CIRCLEQ_REMOVE(&exp_list->list, exp, entries); AppLayerFreeExpectation(exp); @@ -216,8 +214,8 @@ static ExpectationList *AppLayerExpectationRemove(IPPair *ipp, * \return -1 if error * \return 0 if success */ -int AppLayerExpectationCreate(Flow *f, int direction, Port src, Port dst, - AppProto alproto, void *data) +int AppLayerExpectationCreate( + Flow *f, int direction, Port src, Port dst, AppProto alproto, void *data) { ExpectationList *exp_list = NULL; IPPair *ipp; @@ -317,7 +315,7 @@ AppProto AppLayerExpectationHandle(Flow *f, uint8_t flags) if (exp_list == NULL) goto out; - CIRCLEQ_FOREACH_SAFE(exp, &exp_list->list, entries, lexp) { + CIRCLEQ_FOREACH_SAFE (exp, &exp_list->list, entries, lexp) { if ((exp->direction & flags) && ((exp->sp == 0) || (exp->sp == f->sp)) && ((exp->dp == 0) || (exp->dp == f->dp))) { alproto = exp->alproto; @@ -374,7 +372,7 @@ void AppLayerExpectationClean(Flow *f) if (exp_list == NULL) goto out; - CIRCLEQ_FOREACH_SAFE(exp, &exp_list->list, entries, pexp) { + CIRCLEQ_FOREACH_SAFE (exp, &exp_list->list, entries, pexp) { /* Cleaning remove old entries */ if (exp->orig_f == (void *)f) { exp_list = AppLayerExpectationRemove(ipp, exp_list, exp); diff --git a/src/app-layer-expectation.h b/src/app-layer-expectation.h index 0219e33bcf24..fa5339a8d21f 100644 --- a/src/app-layer-expectation.h +++ b/src/app-layer-expectation.h @@ -27,8 +27,8 @@ #include "flow-storage.h" void AppLayerExpectationSetup(void); -int AppLayerExpectationCreate(Flow *f, int direction, Port src, Port dst, - AppProto alproto, void *data); +int AppLayerExpectationCreate( + Flow *f, int direction, Port src, Port dst, AppProto alproto, void *data); AppProto AppLayerExpectationHandle(Flow *f, uint8_t flags); FlowStorageId AppLayerExpectationGetFlowId(void); diff --git a/src/app-layer-frames.h b/src/app-layer-frames.h index 65ba5b6a6919..86f8142015a8 100644 --- a/src/app-layer-frames.h +++ b/src/app-layer-frames.h @@ -47,11 +47,11 @@ typedef struct Frame { uint8_t flags; /**< frame flags: FRAME_FLAG_* */ uint8_t event_cnt; // TODO one event per frame enough? - uint8_t events[4]; /**< per frame store for events */ - uint64_t offset; /**< offset from the start of the stream */ + uint8_t events[4]; /**< per frame store for events */ + uint64_t offset; /**< offset from the start of the stream */ int64_t len; int64_t id; - uint64_t tx_id; /**< tx_id to match this frame. UINT64T_MAX if not used. */ + uint64_t tx_id; /**< tx_id to match this frame. UINT64T_MAX if not used. */ uint64_t inspect_progress; /**< inspection tracker relative to the start of the frame */ } Frame; @@ -59,7 +59,7 @@ typedef struct Frame { typedef struct Frames { uint16_t cnt; - uint16_t dyn_size; /**< size in elements of `dframes` */ + uint16_t dyn_size; /**< size in elements of `dframes` */ uint32_t left_edge_rel; uint64_t base_id; Frame sframes[FRAMES_STATIC_CNT]; /**< static frames */ diff --git a/src/app-layer-ftp.c b/src/app-layer-ftp.c index 8925d6dd6a13..e53c6c825b5e 100644 --- a/src/app-layer-ftp.c +++ b/src/app-layer-ftp.c @@ -118,15 +118,14 @@ static void FTPParseMemcap(void) const char *conf_val; /** set config values for memcap, prealloc and hash_size */ - if ((ConfGet("app-layer.protocols.ftp.memcap", &conf_val)) == 1) - { + if ((ConfGet("app-layer.protocols.ftp.memcap", &conf_val)) == 1) { if (ParseSizeStringU64(conf_val, &ftp_config_memcap) < 0) { SCLogError("Error parsing ftp.memcap " "from conf file - %s. Killing engine", conf_val); exit(EXIT_FAILURE); } - SCLogInfo("FTP memcap: %"PRIu64, ftp_config_memcap); + SCLogInfo("FTP memcap: %" PRIu64, ftp_config_memcap); } else { /* default to unlimited */ ftp_config_memcap = 0; @@ -154,13 +153,13 @@ static void FTPParseMemcap(void) static void FTPIncrMemuse(uint64_t size) { - (void) SC_ATOMIC_ADD(ftp_memuse, size); + (void)SC_ATOMIC_ADD(ftp_memuse, size); return; } static void FTPDecrMemuse(uint64_t size) { - (void) SC_ATOMIC_SUB(ftp_memuse, size); + (void)SC_ATOMIC_SUB(ftp_memuse, size); return; } @@ -186,7 +185,7 @@ static int FTPCheckMemcap(uint64_t size) { if (ftp_config_memcap == 0 || size + SC_ATOMIC_GET(ftp_memuse) <= ftp_config_memcap) return 1; - (void) SC_ATOMIC_ADD(ftp_memcap, 1); + (void)SC_ATOMIC_ADD(ftp_memcap, 1); return 0; } @@ -304,7 +303,7 @@ static FTPTransaction *FTPTransactionCreate(FtpState *state) TAILQ_INIT(&tx->response_list); - SCLogDebug("new transaction %p (state tx cnt %"PRIu64")", tx, state->tx_cnt); + SCLogDebug("new transaction %p (state tx cnt %" PRIu64 ")", tx, state->tx_cnt); return tx; } @@ -438,7 +437,7 @@ struct FtpTransferCmd { static void FtpTransferCmdFree(void *data) { - struct FtpTransferCmd *cmd = (struct FtpTransferCmd *) data; + struct FtpTransferCmd *cmd = (struct FtpTransferCmd *)data; if (cmd == NULL) return; if (cmd->file_name) { @@ -586,33 +585,32 @@ static AppLayerResult FTPParseRequest(Flow *f, void *ftp_state, AppLayerParserSt #if SC_FILENAME_MAX > UINT16_MAX #error SC_FILENAME_MAX is greater than UINT16_MAX #endif - data->file_name = FTPCalloc(file_name_len + 1, sizeof(char)); - if (data->file_name == NULL) { - FtpTransferCmdFree(data); - SCReturnStruct(APP_LAYER_ERROR); - } - data->file_name[file_name_len] = 0; - data->file_len = (uint16_t)file_name_len; - memcpy(data->file_name, line.buf + 5, file_name_len); - data->cmd = state->command; - data->flow_id = FlowGetId(f); - data->direction = direction; - int ret = AppLayerExpectationCreate(f, direction, - 0, state->dyn_port, ALPROTO_FTPDATA, data); - if (ret == -1) { - FtpTransferCmdFree(data); - SCLogDebug("No expectation created."); - SCReturnStruct(APP_LAYER_ERROR); - } else { - SCLogDebug("Expectation created [direction: %s, dynamic port %"PRIu16"].", - state->active ? "to server" : "to client", - state->dyn_port); - } + data->file_name = FTPCalloc(file_name_len + 1, sizeof(char)); + if (data->file_name == NULL) { + FtpTransferCmdFree(data); + SCReturnStruct(APP_LAYER_ERROR); + } + data->file_name[file_name_len] = 0; + data->file_len = (uint16_t)file_name_len; + memcpy(data->file_name, line.buf + 5, file_name_len); + data->cmd = state->command; + data->flow_id = FlowGetId(f); + data->direction = direction; + int ret = AppLayerExpectationCreate( + f, direction, 0, state->dyn_port, ALPROTO_FTPDATA, data); + if (ret == -1) { + FtpTransferCmdFree(data); + SCLogDebug("No expectation created."); + SCReturnStruct(APP_LAYER_ERROR); + } else { + SCLogDebug("Expectation created [direction: %s, dynamic port %" PRIu16 "].", + state->active ? "to server" : "to client", state->dyn_port); + } - /* reset the dyn port to avoid duplicate */ - state->dyn_port = 0; - /* reset active/passive indicator */ - state->active = false; + /* reset the dyn port to avoid duplicate */ + state->dyn_port = 0; + /* reset active/passive indicator */ + state->active = false; } break; default: break; @@ -626,13 +624,14 @@ static AppLayerResult FTPParseRequest(Flow *f, void *ftp_state, AppLayerParserSt SCReturnStruct(APP_LAYER_OK); } -static int FTPParsePassiveResponse(Flow *f, FtpState *state, const uint8_t *input, uint32_t input_len) +static int FTPParsePassiveResponse( + Flow *f, FtpState *state, const uint8_t *input, uint32_t input_len) { uint16_t dyn_port = rs_ftp_pasv_response(input, input_len); if (dyn_port == 0) { return -1; } - SCLogDebug("FTP passive mode (v4): dynamic port %"PRIu16"", dyn_port); + SCLogDebug("FTP passive mode (v4): dynamic port %" PRIu16 "", dyn_port); state->active = false; state->dyn_port = dyn_port; state->curr_tx->dyn_port = dyn_port; @@ -641,13 +640,14 @@ static int FTPParsePassiveResponse(Flow *f, FtpState *state, const uint8_t *inpu return 0; } -static int FTPParsePassiveResponseV6(Flow *f, FtpState *state, const uint8_t *input, uint32_t input_len) +static int FTPParsePassiveResponseV6( + Flow *f, FtpState *state, const uint8_t *input, uint32_t input_len) { uint16_t dyn_port = rs_ftp_epsv_response(input, input_len); if (dyn_port == 0) { return -1; } - SCLogDebug("FTP passive mode (v6): dynamic port %"PRIu16"", dyn_port); + SCLogDebug("FTP passive mode (v6): dynamic port %" PRIu16 "", dyn_port); state->active = false; state->dyn_port = dyn_port; state->curr_tx->dyn_port = dyn_port; @@ -666,8 +666,8 @@ static int FTPParsePassiveResponseV6(Flow *f, FtpState *state, const uint8_t *in */ static inline bool FTPIsPPR(const uint8_t *input, uint32_t input_len) { - return input_len >= 4 && isdigit(input[0]) && input[0] == '1' && - isdigit(input[1]) && isdigit(input[2]) && isspace(input[3]); + return input_len >= 4 && isdigit(input[0]) && input[0] == '1' && isdigit(input[1]) && + isdigit(input[2]) && isspace(input[3]); } /** @@ -795,7 +795,6 @@ static AppLayerResult FTPParseResponse(Flow *f, void *ftp_state, AppLayerParserS SCReturnStruct(APP_LAYER_OK); } - #ifdef DEBUG static SCMutex ftp_state_mem_lock = SCMUTEX_INITIALIZER; static uint64_t ftp_state_memuse = 0; @@ -808,13 +807,13 @@ static void *FTPStateAlloc(void *orig_state, AppProto proto_orig) if (unlikely(s == NULL)) return NULL; - FtpState *ftp_state = (FtpState *) s; + FtpState *ftp_state = (FtpState *)s; TAILQ_INIT(&ftp_state->tx_list); #ifdef DEBUG SCMutexLock(&ftp_state_mem_lock); ftp_state_memcnt++; - ftp_state_memuse+=sizeof(FtpState); + ftp_state_memuse += sizeof(FtpState); SCMutexUnlock(&ftp_state_mem_lock); #endif return s; @@ -822,7 +821,7 @@ static void *FTPStateAlloc(void *orig_state, AppProto proto_orig) static void FTPStateFree(void *s) { - FtpState *fstate = (FtpState *) s; + FtpState *fstate = (FtpState *)s; if (fstate->port_line != NULL) FTPFree(fstate->port_line, fstate->port_line_size); @@ -839,7 +838,7 @@ static void FTPStateFree(void *s) #ifdef DEBUG SCMutexLock(&ftp_state_mem_lock); ftp_state_memcnt--; - ftp_state_memuse-=sizeof(FtpState); + ftp_state_memuse -= sizeof(FtpState); SCMutexUnlock(&ftp_state_mem_lock); #endif } @@ -860,10 +859,10 @@ static FTPTransaction *FTPGetOldestTx(const FtpState *ftp_state, FTPTransaction } FTPTransaction *tx = starttx; FTPTransaction *lasttx = NULL; - while(tx != NULL) { + while (tx != NULL) { /* Return oldest open tx */ if (!tx->done) { - SCLogDebug("Returning tx %p id %"PRIu64, tx, tx->tx_id); + SCLogDebug("Returning tx %p id %" PRIu64, tx, tx->tx_id); return tx; } /* save for the end */ @@ -872,7 +871,7 @@ static FTPTransaction *FTPGetOldestTx(const FtpState *ftp_state, FTPTransaction } /* All tx are closed; return last element */ if (lasttx) - SCLogDebug("Returning OLDEST tx %p id %"PRIu64, lasttx, lasttx->tx_id); + SCLogDebug("Returning OLDEST tx %p id %" PRIu64, lasttx, lasttx->tx_id); return lasttx; } @@ -887,7 +886,7 @@ static void *FTPGetTx(void *state, uint64_t tx_id) if (ftp_state->curr_tx->tx_id == tx_id) return ftp_state->curr_tx; - TAILQ_FOREACH(tx, &ftp_state->tx_list, next) { + TAILQ_FOREACH (tx, &ftp_state->tx_list, next) { if (tx->tx_id == tx_id) return tx; } @@ -911,7 +910,7 @@ static void FTPStateTransactionFree(void *state, uint64_t tx_id) { FtpState *ftp_state = state; FTPTransaction *tx = NULL; - TAILQ_FOREACH(tx, &ftp_state->tx_list, next) { + TAILQ_FOREACH (tx, &ftp_state->tx_list, next) { if (tx_id < tx->tx_id) break; else if (tx_id > tx->tx_id) @@ -932,7 +931,7 @@ static uint64_t FTPGetTxCnt(void *state) if (ftp_state) { cnt = ftp_state->tx_cnt; } - SCLogDebug("returning state %p %"PRIu64, state, cnt); + SCLogDebug("returning state %p %" PRIu64, state, cnt); return cnt; } @@ -951,7 +950,6 @@ static int FTPGetAlstateProgress(void *vtx, uint8_t direction) return FTP_STATE_FINISHED; } - static int FTPRegisterPatternsForProtocolDetection(void) { if (AppLayerProtoDetectPMRegisterPatternCI( @@ -978,7 +976,6 @@ static int FTPRegisterPatternsForProtocolDetection(void) return 0; } - static StreamingBufferConfig sbcfg = STREAMING_BUFFER_CONFIG_INITIALIZER; /** @@ -1055,10 +1052,9 @@ static AppLayerResult FTPDataParse(Flow *f, FtpDataState *ftpdata_state, /* open with fixed track_id 0 as we can have just one * file per ftp-data flow. */ - if (FileOpenFileWithId(ftpdata_state->files, &sbcfg, - 0ULL, (uint8_t *) ftpdata_state->file_name, - ftpdata_state->file_len, - input, input_len, flags) != 0) { + if (FileOpenFileWithId(ftpdata_state->files, &sbcfg, 0ULL, + (uint8_t *)ftpdata_state->file_name, ftpdata_state->file_len, input, input_len, + flags) != 0) { SCLogDebug("Can't open file"); ret = -1; } @@ -1131,13 +1127,13 @@ static void *FTPDataStateAlloc(void *orig_state, AppProto proto_orig) if (unlikely(s == NULL)) return NULL; - FtpDataState *state = (FtpDataState *) s; + FtpDataState *state = (FtpDataState *)s; state->state = FTPDATA_STATE_IN_PROGRESS; #ifdef DEBUG SCMutexLock(&ftpdata_state_mem_lock); ftpdata_state_memcnt++; - ftpdata_state_memuse+=sizeof(FtpDataState); + ftpdata_state_memuse += sizeof(FtpDataState); SCMutexUnlock(&ftpdata_state_mem_lock); #endif return s; @@ -1145,7 +1141,7 @@ static void *FTPDataStateAlloc(void *orig_state, AppProto proto_orig) static void FTPDataStateFree(void *s) { - FtpDataState *fstate = (FtpDataState *) s; + FtpDataState *fstate = (FtpDataState *)s; if (fstate->tx_data.de_state != NULL) { DetectEngineStateFree(fstate->tx_data.de_state); @@ -1160,7 +1156,7 @@ static void FTPDataStateFree(void *s) #ifdef DEBUG SCMutexLock(&ftpdata_state_mem_lock); ftpdata_state_memcnt--; - ftpdata_state_memuse-=sizeof(FtpDataState); + ftpdata_state_memuse -= sizeof(FtpDataState); SCMutexUnlock(&ftpdata_state_mem_lock); #endif } @@ -1223,20 +1219,16 @@ static void FTPSetMpmState(void) MpmInitCtx(ftp_mpm_ctx, FTP_MPM); uint32_t i = 0; - for (i = 0; i < sizeof(FtpCommands)/sizeof(FtpCommand) - 1; i++) { + for (i = 0; i < sizeof(FtpCommands) / sizeof(FtpCommand) - 1; i++) { const FtpCommand *cmd = &FtpCommands[i]; if (cmd->command_length == 0) continue; - MpmAddPatternCI(ftp_mpm_ctx, - (uint8_t *)cmd->command_name, - cmd->command_length, - 0 /* defunct */, 0 /* defunct */, - i /* id */, i /* rule id */ , 0 /* no flags */); + MpmAddPatternCI(ftp_mpm_ctx, (uint8_t *)cmd->command_name, cmd->command_length, + 0 /* defunct */, 0 /* defunct */, i /* id */, i /* rule id */, 0 /* no flags */); } mpm_table[FTP_MPM].Prepare(ftp_mpm_ctx); - } static void FTPFreeMpmState(void) @@ -1294,18 +1286,17 @@ void RegisterFTPParsers(void) /** FTP */ if (AppLayerProtoDetectConfProtoDetectionEnabled("tcp", proto_name)) { AppLayerProtoDetectRegisterProtocol(ALPROTO_FTP, proto_name); - if (FTPRegisterPatternsForProtocolDetection() < 0 ) + if (FTPRegisterPatternsForProtocolDetection() < 0) return; AppLayerProtoDetectRegisterProtocol(ALPROTO_FTPDATA, proto_data_name); } if (AppLayerParserConfParserEnabled("tcp", proto_name)) { - AppLayerParserRegisterParser(IPPROTO_TCP, ALPROTO_FTP, STREAM_TOSERVER, - FTPParseRequest); - AppLayerParserRegisterParser(IPPROTO_TCP, ALPROTO_FTP, STREAM_TOCLIENT, - FTPParseResponse); + AppLayerParserRegisterParser(IPPROTO_TCP, ALPROTO_FTP, STREAM_TOSERVER, FTPParseRequest); + AppLayerParserRegisterParser(IPPROTO_TCP, ALPROTO_FTP, STREAM_TOCLIENT, FTPParseResponse); AppLayerParserRegisterStateFuncs(IPPROTO_TCP, ALPROTO_FTP, FTPStateAlloc, FTPStateFree); - AppLayerParserRegisterParserAcceptableDataDirection(IPPROTO_TCP, ALPROTO_FTP, STREAM_TOSERVER | STREAM_TOCLIENT); + AppLayerParserRegisterParserAcceptableDataDirection( + IPPROTO_TCP, ALPROTO_FTP, STREAM_TOSERVER | STREAM_TOCLIENT); AppLayerParserRegisterTxFreeFunc(IPPROTO_TCP, ALPROTO_FTP, FTPStateTransactionFree); @@ -1314,8 +1305,8 @@ void RegisterFTPParsers(void) AppLayerParserRegisterGetTxIterator(IPPROTO_TCP, ALPROTO_FTP, FTPGetTxIterator); AppLayerParserRegisterStateDataFunc(IPPROTO_TCP, ALPROTO_FTP, FTPGetStateData); - AppLayerParserRegisterLocalStorageFunc(IPPROTO_TCP, ALPROTO_FTP, FTPLocalStorageAlloc, - FTPLocalStorageFree); + AppLayerParserRegisterLocalStorageFunc( + IPPROTO_TCP, ALPROTO_FTP, FTPLocalStorageAlloc, FTPLocalStorageFree); AppLayerParserRegisterGetTxCnt(IPPROTO_TCP, ALPROTO_FTP, FTPGetTxCnt); AppLayerParserRegisterGetStateProgressFunc(IPPROTO_TCP, ALPROTO_FTP, FTPGetAlstateProgress); @@ -1324,12 +1315,14 @@ void RegisterFTPParsers(void) ALPROTO_FTP, FTP_STATE_FINISHED, FTP_STATE_FINISHED); AppLayerRegisterExpectationProto(IPPROTO_TCP, ALPROTO_FTPDATA); - AppLayerParserRegisterParser(IPPROTO_TCP, ALPROTO_FTPDATA, STREAM_TOSERVER, - FTPDataParseRequest); - AppLayerParserRegisterParser(IPPROTO_TCP, ALPROTO_FTPDATA, STREAM_TOCLIENT, - FTPDataParseResponse); - AppLayerParserRegisterStateFuncs(IPPROTO_TCP, ALPROTO_FTPDATA, FTPDataStateAlloc, FTPDataStateFree); - AppLayerParserRegisterParserAcceptableDataDirection(IPPROTO_TCP, ALPROTO_FTPDATA, STREAM_TOSERVER | STREAM_TOCLIENT); + AppLayerParserRegisterParser( + IPPROTO_TCP, ALPROTO_FTPDATA, STREAM_TOSERVER, FTPDataParseRequest); + AppLayerParserRegisterParser( + IPPROTO_TCP, ALPROTO_FTPDATA, STREAM_TOCLIENT, FTPDataParseResponse); + AppLayerParserRegisterStateFuncs( + IPPROTO_TCP, ALPROTO_FTPDATA, FTPDataStateAlloc, FTPDataStateFree); + AppLayerParserRegisterParserAcceptableDataDirection( + IPPROTO_TCP, ALPROTO_FTPDATA, STREAM_TOSERVER | STREAM_TOCLIENT); AppLayerParserRegisterTxFreeFunc(IPPROTO_TCP, ALPROTO_FTPDATA, FTPDataStateTransactionFree); AppLayerParserRegisterGetTxFilesFunc(IPPROTO_TCP, ALPROTO_FTPDATA, FTPDataStateGetTxFiles); @@ -1340,7 +1333,8 @@ void RegisterFTPParsers(void) AppLayerParserRegisterGetTxCnt(IPPROTO_TCP, ALPROTO_FTPDATA, FTPDataGetTxCnt); - AppLayerParserRegisterGetStateProgressFunc(IPPROTO_TCP, ALPROTO_FTPDATA, FTPDataGetAlstateProgress); + AppLayerParserRegisterGetStateProgressFunc( + IPPROTO_TCP, ALPROTO_FTPDATA, FTPDataGetAlstateProgress); AppLayerParserRegisterStateProgressCompletionStatus( ALPROTO_FTPDATA, FTPDATA_STATE_FINISHED, FTPDATA_STATE_FINISHED); @@ -1356,7 +1350,8 @@ void RegisterFTPParsers(void) FTPParseMemcap(); } else { SCLogInfo("Parsed disabled for %s protocol. Protocol detection" - "still on.", proto_name); + "still on.", + proto_name); } FTPSetMpmState(); @@ -1370,13 +1365,12 @@ void FTPAtExitPrintStats(void) { #ifdef DEBUG SCMutexLock(&ftp_state_mem_lock); - SCLogDebug("ftp_state_memcnt %"PRIu64", ftp_state_memuse %"PRIu64"", - ftp_state_memcnt, ftp_state_memuse); + SCLogDebug("ftp_state_memcnt %" PRIu64 ", ftp_state_memuse %" PRIu64 "", ftp_state_memcnt, + ftp_state_memuse); SCMutexUnlock(&ftp_state_mem_lock); #endif } - /* * \brief Returns the ending offset of the next line from a multi-line buffer. * @@ -1456,8 +1450,8 @@ static int FTPParserTest01(void) StreamTcpInitConfig(true); - int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_FTP, - STREAM_TOSERVER | STREAM_EOF, ftpbuf, ftplen); + int r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_FTP, STREAM_TOSERVER | STREAM_EOF, ftpbuf, ftplen); FAIL_IF(r != 0); FtpState *ftp_state = f.alstate; @@ -1489,21 +1483,17 @@ static int FTPParserTest11(void) StreamTcpInitConfig(true); - int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_FTP, - STREAM_TOSERVER | STREAM_START, ftpbuf1, - sizeof(ftpbuf1) - 1); + int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_FTP, STREAM_TOSERVER | STREAM_START, + ftpbuf1, sizeof(ftpbuf1) - 1); FAIL_IF(r != 0); /* Response */ - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_FTP, - STREAM_TOCLIENT, - ftpbuf3, - sizeof(ftpbuf3) - 1); + r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_FTP, STREAM_TOCLIENT, ftpbuf3, sizeof(ftpbuf3) - 1); FAIL_IF(r != 0); - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_FTP, - STREAM_TOSERVER, ftpbuf2, - sizeof(ftpbuf2) - 1); + r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_FTP, STREAM_TOSERVER, ftpbuf2, sizeof(ftpbuf2) - 1); FAIL_IF(r == 0); FtpState *ftp_state = f.alstate; @@ -1536,21 +1526,17 @@ static int FTPParserTest12(void) StreamTcpInitConfig(true); - int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_FTP, - STREAM_TOSERVER | STREAM_START, ftpbuf1, - sizeof(ftpbuf1) - 1); + int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_FTP, STREAM_TOSERVER | STREAM_START, + ftpbuf1, sizeof(ftpbuf1) - 1); FAIL_IF(r != 0); /* Response */ - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_FTP, - STREAM_TOCLIENT, - ftpbuf3, - sizeof(ftpbuf3) - 1); + r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_FTP, STREAM_TOCLIENT, ftpbuf3, sizeof(ftpbuf3) - 1); FAIL_IF(r != 0); - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_FTP, - STREAM_TOSERVER, ftpbuf2, - sizeof(ftpbuf2) - 1); + r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_FTP, STREAM_TOSERVER, ftpbuf2, sizeof(ftpbuf2) - 1); FAIL_IF(r == 0); FtpState *ftp_state = f.alstate; @@ -1572,4 +1558,3 @@ void FTPParserRegisterTests(void) UtRegisterTest("FTPParserTest12", FTPParserTest12); #endif /* UNITTESTS */ } - diff --git a/src/app-layer-ftp.h b/src/app-layer-ftp.h index fb71d6b52de7..b69894b6c067 100644 --- a/src/app-layer-ftp.h +++ b/src/app-layer-ftp.h @@ -115,7 +115,7 @@ typedef struct FTPString_ { TAILQ_ENTRY(FTPString_) next; } FTPString; -typedef struct FTPTransaction_ { +typedef struct FTPTransaction_ { /** id of this tx, starting at 0 */ uint64_t tx_id; @@ -130,8 +130,8 @@ typedef struct FTPTransaction_ { const FtpCommand *command_descriptor; uint16_t dyn_port; /* dynamic port, if applicable */ - bool done; /* transaction complete? */ - bool active; /* active or passive mode */ + bool done; /* transaction complete? */ + bool active; /* active or passive mode */ uint8_t direction; @@ -146,7 +146,7 @@ typedef struct FtpState_ { bool active; FTPTransaction *curr_tx; - TAILQ_HEAD(, FTPTransaction_) tx_list; /**< transaction list */ + TAILQ_HEAD(, FTPTransaction_) tx_list; /**< transaction list */ uint64_t tx_cnt; bool current_line_truncated_ts; @@ -193,4 +193,3 @@ uint16_t JsonGetNextLineFromBuffer(const char *buffer, const uint16_t len); bool EveFTPDataAddMetadata(void *vtx, JsonBuilder *jb); #endif /* __APP_LAYER_FTP_H__ */ - diff --git a/src/app-layer-htp-body.c b/src/app-layer-htp-body.c index 11b5941d7e21..f130cac3e870 100644 --- a/src/app-layer-htp-body.c +++ b/src/app-layer-htp-body.c @@ -45,8 +45,7 @@ extern StreamingBufferConfig htp_sbcfg; * \retval 0 ok * \retval -1 error */ -int HtpBodyAppendChunk(const HTPCfgDir *hcfg, HtpBody *body, - const uint8_t *data, uint32_t len) +int HtpBodyAppendChunk(const HTPCfgDir *hcfg, HtpBody *body, const uint8_t *data, uint32_t len) { SCEnter(); @@ -93,7 +92,7 @@ int HtpBodyAppendChunk(const HTPCfgDir *hcfg, HtpBody *body, */ void HtpBodyPrint(HtpBody *body) { - if (SCLogDebugEnabled()||1) { + if (SCLogDebugEnabled() || 1) { SCEnter(); if (body->first == NULL) @@ -106,8 +105,8 @@ void HtpBodyPrint(HtpBody *body) const uint8_t *data = NULL; uint32_t data_len = 0; StreamingBufferSegmentGetData(body->sb, &cur->sbseg, &data, &data_len); - SCLogDebug("Body %p; data %p, len %"PRIu32, body, data, data_len); - printf("Body %p; data %p, len %"PRIu32"\n", body, data, data_len); + SCLogDebug("Body %p; data %p, len %" PRIu32, body, data, data_len); + printf("Body %p; data %p, len %" PRIu32 "\n", body, data, data_len); PrintRawDataFp(stdout, data, data_len); } SCLogDebug("--- End body chunks at %p ---", body); @@ -184,7 +183,7 @@ void HtpBodyPrune(HtpState *state, HtpBody *body, int direction) left_edge -= window; if (left_edge) { - SCLogDebug("sliding body to offset %"PRIu64, left_edge); + SCLogDebug("sliding body to offset %" PRIu64, left_edge); StreamingBufferSlideToOffset(body->sb, &htp_sbcfg, left_edge); } diff --git a/src/app-layer-htp-file.c b/src/app-layer-htp-file.c index f96b37016061..8d25f6877f02 100644 --- a/src/app-layer-htp-file.c +++ b/src/app-layer-htp-file.c @@ -54,7 +54,7 @@ int HTPFileOpen(HtpState *s, HtpTxUserData *tx, const uint8_t *filename, uint16_ uint16_t flags = 0; FileContainer *files = NULL; - SCLogDebug("data %p data_len %"PRIu32, data, data_len); + SCLogDebug("data %p data_len %" PRIu32, data, data_len); if (direction & STREAM_TOCLIENT) { files = &tx->files_tc; @@ -362,11 +362,13 @@ static int HTPFileParserTest01(void) { uint8_t httpbuf1[] = "POST /upload.cgi HTTP/1.1\r\n" "Host: www.server.lan\r\n" - "Content-Type: multipart/form-data; boundary=---------------------------277531038314945\r\n" + "Content-Type: multipart/form-data; " + "boundary=---------------------------277531038314945\r\n" "Content-Length: 215\r\n" "\r\n" "-----------------------------277531038314945\r\n" - "Content-Disposition: form-data; name=\"uploadfile_0\"; filename=\"somepicture1.jpg\"\r\n" + "Content-Disposition: form-data; name=\"uploadfile_0\"; " + "filename=\"somepicture1.jpg\"\r\n" "Content-Type: image/jpeg\r\n" "\r\n"; @@ -417,7 +419,8 @@ static int HTPFileParserTest02(void) { uint8_t httpbuf1[] = "POST /upload.cgi HTTP/1.1\r\n" "Host: www.server.lan\r\n" - "Content-Type: multipart/form-data; boundary=---------------------------277531038314945\r\n" + "Content-Type: multipart/form-data; " + "boundary=---------------------------277531038314945\r\n" "Content-Length: 337\r\n" "\r\n"; uint32_t httplen1 = sizeof(httpbuf1) - 1; /* minus the \0 */ @@ -429,7 +432,8 @@ static int HTPFileParserTest02(void) uint32_t httplen2 = sizeof(httpbuf2) - 1; /* minus the \0 */ uint8_t httpbuf3[] = "-----------------------------277531038314945\r\n" - "Content-Disposition: form-data; name=\"uploadfile_0\"; filename=\"somepicture1.jpg\"\r\n" + "Content-Disposition: form-data; name=\"uploadfile_0\"; " + "filename=\"somepicture1.jpg\"\r\n" "Content-Type: image/jpeg\r\n" "\r\n"; uint32_t httplen3 = sizeof(httpbuf3) - 1; /* minus the \0 */ @@ -494,7 +498,8 @@ static int HTPFileParserTest03(void) { uint8_t httpbuf1[] = "POST /upload.cgi HTTP/1.1\r\n" "Host: www.server.lan\r\n" - "Content-Type: multipart/form-data; boundary=---------------------------277531038314945\r\n" + "Content-Type: multipart/form-data; " + "boundary=---------------------------277531038314945\r\n" "Content-Length: 337\r\n" "\r\n"; uint32_t httplen1 = sizeof(httpbuf1) - 1; /* minus the \0 */ @@ -506,7 +511,8 @@ static int HTPFileParserTest03(void) uint32_t httplen2 = sizeof(httpbuf2) - 1; /* minus the \0 */ uint8_t httpbuf3[] = "-----------------------------277531038314945\r\n" - "Content-Disposition: form-data; name=\"uploadfile_0\"; filename=\"somepicture1.jpg\"\r\n" + "Content-Disposition: form-data; name=\"uploadfile_0\"; " + "filename=\"somepicture1.jpg\"\r\n" "Content-Type: image/jpeg\r\n" "\r\n"; uint32_t httplen3 = sizeof(httpbuf3) - 1; /* minus the \0 */ @@ -590,7 +596,8 @@ static int HTPFileParserTest04(void) { uint8_t httpbuf1[] = "POST /upload.cgi HTTP/1.1\r\n" "Host: www.server.lan\r\n" - "Content-Type: multipart/form-data; boundary=---------------------------277531038314945\r\n" + "Content-Type: multipart/form-data; " + "boundary=---------------------------277531038314945\r\n" "Content-Length: 373\r\n" "\r\n"; uint32_t httplen1 = sizeof(httpbuf1) - 1; /* minus the \0 */ @@ -602,7 +609,8 @@ static int HTPFileParserTest04(void) uint32_t httplen2 = sizeof(httpbuf2) - 1; /* minus the \0 */ uint8_t httpbuf3[] = "-----------------------------277531038314945\r\n" - "Content-Disposition: form-data; name=\"uploadfile_0\"; filename=\"somepicture1.jpg\"\r\n" + "Content-Disposition: form-data; name=\"uploadfile_0\"; " + "filename=\"somepicture1.jpg\"\r\n" "Content-Type: image/jpeg\r\n" "\r\n"; uint32_t httplen3 = sizeof(httpbuf3) - 1; /* minus the \0 */ @@ -685,21 +693,24 @@ static int HTPFileParserTest05(void) { uint8_t httpbuf1[] = "POST /upload.cgi HTTP/1.1\r\n" "Host: www.server.lan\r\n" - "Content-Type: multipart/form-data; boundary=---------------------------277531038314945\r\n" + "Content-Type: multipart/form-data; " + "boundary=---------------------------277531038314945\r\n" "Content-Length: 544\r\n" "\r\n" "-----------------------------277531038314945\r\n" - "Content-Disposition: form-data; name=\"uploadfile_0\"; filename=\"somepicture1.jpg\"\r\n" + "Content-Disposition: form-data; name=\"uploadfile_0\"; " + "filename=\"somepicture1.jpg\"\r\n" "Content-Type: image/jpeg\r\n" "\r\n" "filecontent\r\n" "-----------------------------277531038314945\r\n"; uint32_t httplen1 = sizeof(httpbuf1) - 1; /* minus the \0 */ - uint8_t httpbuf2[] = "Content-Disposition: form-data; name=\"uploadfile_1\"; filename=\"somepicture2.jpg\"\r\n" + uint8_t httpbuf2[] = "Content-Disposition: form-data; name=\"uploadfile_1\"; " + "filename=\"somepicture2.jpg\"\r\n" "Content-Type: image/jpeg\r\n" "\r\n" "FILECONTENT\r\n" - "-----------------------------277531038314945--"; + "-----------------------------277531038314945--"; uint32_t httplen2 = sizeof(httpbuf2) - 1; /* minus the \0 */ TcpSession ssn; @@ -760,21 +771,24 @@ static int HTPFileParserTest06(void) { uint8_t httpbuf1[] = "POST /upload.cgi HTTP/1.1\r\n" "Host: www.server.lan\r\n" - "Content-Type: multipart/form-data; boundary=---------------------------277531038314945\r\n" + "Content-Type: multipart/form-data; " + "boundary=---------------------------277531038314945\r\n" "Content-Length: 544\r\n" "\r\n" "-----------------------------277531038314945\r\n" - "Content-Disposition: form-data; name=\"uploadfile_0\"; filename=\"somepicture1.jpg\"\r\n" + "Content-Disposition: form-data; name=\"uploadfile_0\"; " + "filename=\"somepicture1.jpg\"\r\n" "Content-Type: image/jpeg\r\n" "\r\n" "filecontent\r\n" "-----------------------------27753103831494"; uint32_t httplen1 = sizeof(httpbuf1) - 1; /* minus the \0 */ - uint8_t httpbuf2[] = "5\r\nContent-Disposition: form-data; name=\"uploadfile_1\"; filename=\"somepicture2.jpg\"\r\n" + uint8_t httpbuf2[] = "5\r\nContent-Disposition: form-data; name=\"uploadfile_1\"; " + "filename=\"somepicture2.jpg\"\r\n" "Content-Type: image/jpeg\r\n" "\r\n" "FILECONTENT\r\n" - "-----------------------------277531038314945--"; + "-----------------------------277531038314945--"; uint32_t httplen2 = sizeof(httpbuf2) - 1; /* minus the \0 */ TcpSession ssn; @@ -893,11 +907,13 @@ static int HTPFileParserTest08(void) { uint8_t httpbuf1[] = "POST /upload.cgi HTTP/1.1\r\n" "Host: www.server.lan\r\n" - "Content-Type: multipart/form-data; boundary=---------------------------277531038314945\r\n" + "Content-Type: multipart/form-data; " + "boundary=---------------------------277531038314945\r\n" "Content-Length: 215\r\n" "\r\n" "-----------------------------277531038314945\r\n" - "Content-Disposition: form-data; name=\"uploadfile_0\"; filename=\"somepicture1.jpg\"\r\n" + "Content-Disposition: form-data; name=\"uploadfile_0\"; " + "filename=\"somepicture1.jpg\"\r\n" "Content-Type: image/jpeg\r\n"; uint32_t httplen1 = sizeof(httpbuf1) - 1; /* minus the \0 */ @@ -951,7 +967,8 @@ static int HTPFileParserTest09(void) { uint8_t httpbuf1[] = "POST /upload.cgi HTTP/1.1\r\n" "Host: www.server.lan\r\n" - "Content-Type: multipart/form-data; boundary=---------------------------277531038314945\r\n" + "Content-Type: multipart/form-data; " + "boundary=---------------------------277531038314945\r\n" "Content-Length: 337\r\n" "\r\n"; uint32_t httplen1 = sizeof(httpbuf1) - 1; /* minus the \0 */ @@ -963,7 +980,8 @@ static int HTPFileParserTest09(void) uint32_t httplen2 = sizeof(httpbuf2) - 1; /* minus the \0 */ uint8_t httpbuf3[] = "-----------------------------277531038314945\r\n" - "Content-Disposition: form-data; name=\"uploadfile_0\"; filename=\"somepicture1.jpg\"\r\n" + "Content-Disposition: form-data; name=\"uploadfile_0\"; " + "filename=\"somepicture1.jpg\"\r\n" "Somereallylongheaderstr:\r\n" "\r\n"; uint32_t httplen3 = sizeof(httpbuf3) - 1; /* minus the \0 */ @@ -1029,7 +1047,8 @@ static int HTPFileParserTest10(void) { uint8_t httpbuf1[] = "POST /upload.cgi HTTP/1.1\r\n" "Host: www.server.lan\r\n" - "Content-Type: multipart/form-data; boundary=---------------------------277531038314945\r\n" + "Content-Type: multipart/form-data; " + "boundary=---------------------------277531038314945\r\n" "Content-Length: 337\r\n" "\r\n"; uint32_t httplen1 = sizeof(httpbuf1) - 1; /* minus the \0 */ @@ -1039,7 +1058,8 @@ static int HTPFileParserTest10(void) uint32_t httplen2 = sizeof(httpbuf2) - 1; /* minus the \0 */ uint8_t httpbuf3[] = "-----------------------------277531038314945\r\n" - "Content-Disposition: form-data; name=\"uploadfile_0\"; filename=\"somepicture1.jpg\"\r\n" + "Content-Disposition: form-data; name=\"uploadfile_0\"; " + "filename=\"somepicture1.jpg\"\r\n" "Somereallylongheaderstr: with a good value\r\n" "\r\n"; uint32_t httplen3 = sizeof(httpbuf3) - 1; /* minus the \0 */ @@ -1100,49 +1120,52 @@ static int HTPFileParserTest10(void) /** \test filedata cut in two pieces */ static int HTPFileParserTest11(void) { - uint8_t httpbuf1[] = "POST /upload.cgi HTTP/1.1\r\n" - "Host: www.server.lan\r\n" - "Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryBRDbP74mBhBxsIdo\r\n" - "Content-Length: 1102\r\n" - "\r\n"; + uint8_t httpbuf1[] = + "POST /upload.cgi HTTP/1.1\r\n" + "Host: www.server.lan\r\n" + "Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryBRDbP74mBhBxsIdo\r\n" + "Content-Length: 1102\r\n" + "\r\n"; uint32_t httplen1 = sizeof(httpbuf1) - 1; /* minus the \0 */ uint8_t httpbuf2[] = "------WebKitFormBoundaryBRDbP74mBhBxsIdo\r\n"; uint32_t httplen2 = sizeof(httpbuf2) - 1; /* minus the \0 */ - uint8_t httpbuf3[] = "Content-Disposition: form-data; name=\"PROGRESS_URL\"\r\n" - "\r\n" - "http://somserver.com/progress.php?UPLOAD_IDENTIFIER=XXXXXXXXX.XXXXXXXXXX.XXXXXXXX.XX.X\r\n" - "------WebKitFormBoundaryBRDbP74mBhBxsIdo\r\n" - "Content-Disposition: form-data; name=\"DESTINATION_DIR\"\r\n" - "\r\n" - "10\r\n" - "------WebKitFormBoundaryBRDbP74mBhBxsIdo\r\n" - "Content-Disposition: form-data; name=\"js_enabled\"\r\n" - "\r\n" - "1" - "------WebKitFormBoundaryBRDbP74mBhBxsIdo\r\n" - "Content-Disposition: form-data; name=\"signature\"\r\n" - "\r\n" - "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\r\n" - "------WebKitFormBoundaryBRDbP74mBhBxsIdo\r\n" - "Content-Disposition: form-data; name=\"upload_files\"\r\n" - "\r\n" - "------WebKitFormBoundaryBRDbP74mBhBxsIdo\r\n" - "Content-Disposition: form-data; name=\"terms\"\r\n" - "\r\n" - "1" - "------WebKitFormBoundaryBRDbP74mBhBxsIdo\r\n" - "Content-Disposition: form-data; name=\"file[]\"\r\n" - "\r\n" - "------WebKitFormBoundaryBRDbP74mBhBxsIdo\r\n" - "Content-Disposition: form-data; name=\"description[]\"\r\n" - "\r\n" - "------WebKitFormBoundaryBRDbP74mBhBxsIdo\r\n" - "Content-Disposition: form-data; name=\"upload_file[]\"; filename=\"filename.doc\"\r\n" - "Content-Type: application/msword\r\n" - "\r\n" - "FILE"; + uint8_t httpbuf3[] = + "Content-Disposition: form-data; name=\"PROGRESS_URL\"\r\n" + "\r\n" + "http://somserver.com/" + "progress.php?UPLOAD_IDENTIFIER=XXXXXXXXX.XXXXXXXXXX.XXXXXXXX.XX.X\r\n" + "------WebKitFormBoundaryBRDbP74mBhBxsIdo\r\n" + "Content-Disposition: form-data; name=\"DESTINATION_DIR\"\r\n" + "\r\n" + "10\r\n" + "------WebKitFormBoundaryBRDbP74mBhBxsIdo\r\n" + "Content-Disposition: form-data; name=\"js_enabled\"\r\n" + "\r\n" + "1" + "------WebKitFormBoundaryBRDbP74mBhBxsIdo\r\n" + "Content-Disposition: form-data; name=\"signature\"\r\n" + "\r\n" + "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\r\n" + "------WebKitFormBoundaryBRDbP74mBhBxsIdo\r\n" + "Content-Disposition: form-data; name=\"upload_files\"\r\n" + "\r\n" + "------WebKitFormBoundaryBRDbP74mBhBxsIdo\r\n" + "Content-Disposition: form-data; name=\"terms\"\r\n" + "\r\n" + "1" + "------WebKitFormBoundaryBRDbP74mBhBxsIdo\r\n" + "Content-Disposition: form-data; name=\"file[]\"\r\n" + "\r\n" + "------WebKitFormBoundaryBRDbP74mBhBxsIdo\r\n" + "Content-Disposition: form-data; name=\"description[]\"\r\n" + "\r\n" + "------WebKitFormBoundaryBRDbP74mBhBxsIdo\r\n" + "Content-Disposition: form-data; name=\"upload_file[]\"; filename=\"filename.doc\"\r\n" + "Content-Type: application/msword\r\n" + "\r\n" + "FILE"; uint32_t httplen3 = sizeof(httpbuf3) - 1; /* minus the \0 */ uint8_t httpbuf4[] = "CONTENT\r\n" @@ -1212,7 +1235,7 @@ static int HTPFileParserTest11(void) PASS; } -void AppLayerHtpFileRegisterTests (void); +void AppLayerHtpFileRegisterTests(void); #include "tests/app-layer-htp-file.c" #endif /* UNITTESTS */ diff --git a/src/app-layer-htp-mem.c b/src/app-layer-htp-mem.c index bd9b79f67623..e8d028353238 100644 --- a/src/app-layer-htp-mem.c +++ b/src/app-layer-htp-mem.c @@ -48,8 +48,7 @@ void HTPParseMemcap(void) /** set config values for memcap, prealloc and hash_size */ uint64_t memcap; - if ((ConfGet("app-layer.protocols.http.memcap", &conf_val)) == 1) - { + if ((ConfGet("app-layer.protocols.http.memcap", &conf_val)) == 1) { if (ParseSizeStringU64(conf_val, &memcap) < 0) { SCLogError("Error parsing http.memcap " "from conf file - %s. Killing engine", @@ -58,7 +57,7 @@ void HTPParseMemcap(void) } else { SC_ATOMIC_SET(htp_config_memcap, memcap); } - SCLogInfo("HTTP memcap: %"PRIu64, SC_ATOMIC_GET(htp_config_memcap)); + SCLogInfo("HTTP memcap: %" PRIu64, SC_ATOMIC_GET(htp_config_memcap)); } else { /* default to unlimited */ SC_ATOMIC_SET(htp_config_memcap, 0); @@ -70,13 +69,13 @@ void HTPParseMemcap(void) static void HTPIncrMemuse(uint64_t size) { - (void) SC_ATOMIC_ADD(htp_memuse, size); + (void)SC_ATOMIC_ADD(htp_memuse, size); return; } static void HTPDecrMemuse(uint64_t size) { - (void) SC_ATOMIC_SUB(htp_memuse, size); + (void)SC_ATOMIC_SUB(htp_memuse, size); return; } @@ -103,7 +102,7 @@ static int HTPCheckMemcap(uint64_t size) uint64_t memcapcopy = SC_ATOMIC_GET(htp_config_memcap); if (memcapcopy == 0 || size + SC_ATOMIC_GET(htp_memuse) <= memcapcopy) return 1; - (void) SC_ATOMIC_ADD(htp_memcap, 1); + (void)SC_ATOMIC_ADD(htp_memcap, 1); return 0; } diff --git a/src/app-layer-htp-xff.c b/src/app-layer-htp-xff.c index c145e5818e23..877597452f63 100644 --- a/src/app-layer-htp-xff.c +++ b/src/app-layer-htp-xff.c @@ -61,14 +61,14 @@ static int ParseXFFString(char *input, char *output, int output_size) if (end == NULL) // malformed, not closed return 0; - if (end != input+(len - 1)) { + if (end != input + (len - 1)) { SCLogDebug("data after closing bracket"); // if we ever want to parse the port, we can do it here } /* done, lets wrap up */ - input++; // skip past [ - *end = '\0'; // overwrite ], ignore anything after + input++; // skip past [ + *end = '\0'; // overwrite ], ignore anything after } else { /* lets see if the xff string ends in a port */ @@ -98,9 +98,7 @@ static int ParseXFFString(char *input, char *output, int output_size) /** Sanity check on extracted IP for IPv4 and IPv6 */ uint32_t ip[4]; - if (inet_pton(AF_INET, input, ip) == 1 || - inet_pton(AF_INET6, input, ip) == 1) - { + if (inet_pton(AF_INET, input, ip) == 1 || inet_pton(AF_INET6, input, ip) == 1) { strlcpy(output, input, output_size); return 1; // OK } @@ -113,8 +111,8 @@ static int ParseXFFString(char *input, char *output, int output_size) * \retval 1 if the IP has been found and returned in dstbuf * \retval 0 if the IP has not being found or error */ -int HttpXFFGetIPFromTx(const Flow *f, uint64_t tx_id, HttpXFFCfg *xff_cfg, - char *dstbuf, int dstbuflen) +int HttpXFFGetIPFromTx( + const Flow *f, uint64_t tx_id, HttpXFFCfg *xff_cfg, char *dstbuf, int dstbuflen) { uint8_t xff_chain[XFF_CHAIN_MAXLEN]; HtpState *htp_state = NULL; @@ -148,7 +146,7 @@ int HttpXFFGetIPFromTx(const Flow *f, uint64_t tx_id, HttpXFFCfg *xff_cfg, bstr_len(h_xff->value) < XFF_CHAIN_MAXLEN) { memcpy(xff_chain, bstr_ptr(h_xff->value), bstr_len(h_xff->value)); - xff_chain[bstr_len(h_xff->value)]=0; + xff_chain[bstr_len(h_xff->value)] = 0; if (xff_cfg->flags & XFF_REVERSE) { /** Get the last IP address from the chain */ @@ -158,8 +156,7 @@ int HttpXFFGetIPFromTx(const Flow *f, uint64_t tx_id, HttpXFFCfg *xff_cfg, } else { p_xff++; } - } - else { + } else { /** Get the first IP address from the chain */ p_xff = memchr(xff_chain, ',', bstr_len(h_xff->value)); if (p_xff != NULL) { @@ -219,8 +216,7 @@ void HttpXFFGetCfg(ConfNode *conf, HttpXFFCfg *result) } else { if (xff_mode == NULL) { SCLogWarning("The XFF mode hasn't been defined, falling back to extra-data mode"); - } - else if (strcasecmp(xff_mode, "extra-data") != 0) { + } else if (strcasecmp(xff_mode, "extra-data") != 0) { SCLogWarning( "The XFF mode %s is invalid, falling back to extra-data mode", xff_mode); } @@ -235,8 +231,7 @@ void HttpXFFGetCfg(ConfNode *conf, HttpXFFCfg *result) if (xff_deployment == NULL) { SCLogWarning("The XFF deployment hasn't been defined, falling back to reverse " "proxy deployment"); - } - else if (strcasecmp(xff_deployment, "reverse") != 0) { + } else if (strcasecmp(xff_deployment, "reverse") != 0) { SCLogWarning("The XFF mode %s is invalid, falling back to reverse proxy deployment", xff_deployment); } @@ -246,20 +241,19 @@ void HttpXFFGetCfg(ConfNode *conf, HttpXFFCfg *result) const char *xff_header = ConfNodeLookupChildValue(xff_node, "header"); if (xff_header != NULL) { - result->header = (char *) xff_header; + result->header = (char *)xff_header; } else { SCLogWarning("The XFF header hasn't been defined, using the default %s", XFF_DEFAULT); result->header = XFF_DEFAULT; } - } - else { + } else { result->flags = XFF_DISABLED; } } - #ifdef UNITTESTS -static int XFFTest01(void) { +static int XFFTest01(void) +{ char input[] = "1.2.3.4:5678"; char output[16]; int r = ParseXFFString(input, output, sizeof(output)); @@ -267,7 +261,8 @@ static int XFFTest01(void) { PASS; } -static int XFFTest02(void) { +static int XFFTest02(void) +{ char input[] = "[12::34]:1234"; // thanks chort! char output[16]; int r = ParseXFFString(input, output, sizeof(output)); @@ -275,7 +270,8 @@ static int XFFTest02(void) { PASS; } -static int XFFTest03(void) { +static int XFFTest03(void) +{ char input[] = "[2a03:2880:1010:3f02:face:b00c:0:2]:80"; // thanks chort! char output[46]; int r = ParseXFFString(input, output, sizeof(output)); @@ -283,7 +279,8 @@ static int XFFTest03(void) { PASS; } -static int XFFTest04(void) { +static int XFFTest04(void) +{ char input[] = "[2a03:2880:1010:3f02:face:b00c:0:2]"; // thanks chort! char output[46]; int r = ParseXFFString(input, output, sizeof(output)); @@ -291,7 +288,8 @@ static int XFFTest04(void) { PASS; } -static int XFFTest05(void) { +static int XFFTest05(void) +{ char input[] = "[::ffff:1.2.3.4]:1234"; // thanks double-p char output[46]; int r = ParseXFFString(input, output, sizeof(output)); @@ -299,7 +297,8 @@ static int XFFTest05(void) { PASS; } -static int XFFTest06(void) { +static int XFFTest06(void) +{ char input[] = "12::34"; char output[46]; int r = ParseXFFString(input, output, sizeof(output)); @@ -307,7 +306,8 @@ static int XFFTest06(void) { PASS; } -static int XFFTest07(void) { +static int XFFTest07(void) +{ char input[] = "1.2.3.4"; char output[46]; int r = ParseXFFString(input, output, sizeof(output)); @@ -315,7 +315,8 @@ static int XFFTest07(void) { PASS; } -static int XFFTest08(void) { +static int XFFTest08(void) +{ char input[] = "[1.2.3.4:1234"; char output[46]; int r = ParseXFFString(input, output, sizeof(output)); @@ -323,7 +324,8 @@ static int XFFTest08(void) { PASS; } -static int XFFTest09(void) { +static int XFFTest09(void) +{ char input[] = "999.999.999.999:1234"; char output[46]; int r = ParseXFFString(input, output, sizeof(output)); diff --git a/src/app-layer-htp-xff.h b/src/app-layer-htp-xff.h index 03671d3fbb71..b4dbd8637576 100644 --- a/src/app-layer-htp-xff.h +++ b/src/app-layer-htp-xff.h @@ -39,13 +39,14 @@ #define XFF_MAXLEN 46 typedef struct HttpXFFCfg_ { - uint8_t flags; /**< XFF operation mode and deployment */ + uint8_t flags; /**< XFF operation mode and deployment */ const char *header; /**< XFF header name */ } HttpXFFCfg; void HttpXFFGetCfg(ConfNode *conf, HttpXFFCfg *result); -int HttpXFFGetIPFromTx(const Flow *f, uint64_t tx_id, HttpXFFCfg *xff_cfg, char *dstbuf, int dstbuflen); +int HttpXFFGetIPFromTx( + const Flow *f, uint64_t tx_id, HttpXFFCfg *xff_cfg, char *dstbuf, int dstbuflen); int HttpXFFGetIP(const Flow *f, HttpXFFCfg *xff_cfg, char *dstbuf, int dstbuflen); diff --git a/src/app-layer-htp.c b/src/app-layer-htp.c index 5d48611812c1..ba26daa636af 100644 --- a/src/app-layer-htp.c +++ b/src/app-layer-htp.c @@ -242,8 +242,9 @@ static inline uint64_t HtpGetActiveResponseTxID(HtpState *s) */ static const char *HTPLookupPersonalityString(int p) { -#define CASE_HTP_PERSONALITY_STRING(p) \ - case HTP_SERVER_ ## p: return #p +#define CASE_HTP_PERSONALITY_STRING(p) \ + case HTP_SERVER_##p: \ + return #p switch (p) { CASE_HTP_PERSONALITY_STRING(MINIMAL); @@ -271,8 +272,9 @@ static const char *HTPLookupPersonalityString(int p) */ static int HTPLookupPersonality(const char *str) { -#define IF_HTP_PERSONALITY_NUM(p) \ - if (strcasecmp(#p, str) == 0) return HTP_SERVER_ ## p +#define IF_HTP_PERSONALITY_NUM(p) \ + if (strcasecmp(#p, str) == 0) \ + return HTP_SERVER_##p IF_HTP_PERSONALITY_NUM(MINIMAL); IF_HTP_PERSONALITY_NUM(GENERIC); @@ -289,9 +291,7 @@ static int HTPLookupPersonality(const char *str) "longer supported by libhtp.", str); return -1; - } else if ((strcasecmp("APACHE", str) == 0) || - (strcasecmp("APACHE_2_2", str) == 0)) - { + } else if ((strcasecmp("APACHE", str) == 0) || (strcasecmp("APACHE_2_2", str) == 0)) { SCLogWarning("Personality %s no " "longer supported by libhtp, failing back to " "Apache2 personality.", @@ -302,8 +302,7 @@ static int HTPLookupPersonality(const char *str) return -1; } -static void HTPSetEvent(HtpState *s, HtpTxUserData *htud, - const uint8_t dir, const uint8_t e) +static void HTPSetEvent(HtpState *s, HtpTxUserData *htud, const uint8_t dir, const uint8_t e) { SCLogDebug("setting event %u", e); @@ -313,14 +312,14 @@ static void HTPSetEvent(HtpState *s, HtpTxUserData *htud, return; } - const uint64_t tx_id = (dir == STREAM_TOSERVER) ? - HtpGetActiveRequestTxID(s) : HtpGetActiveResponseTxID(s); + const uint64_t tx_id = + (dir == STREAM_TOSERVER) ? HtpGetActiveRequestTxID(s) : HtpGetActiveResponseTxID(s); htp_tx_t *tx = HTPStateGetTx(s, tx_id); if (tx == NULL && tx_id > 0) tx = HTPStateGetTx(s, tx_id - 1); if (tx != NULL) { - htud = (HtpTxUserData *) htp_tx_get_user_data(tx); + htud = (HtpTxUserData *)htp_tx_get_user_data(tx); if (htud != NULL) { AppLayerDecoderEventsSetEventRaw(&htud->tx_data.events, e); s->events++; @@ -348,7 +347,7 @@ static void *HTPStateAlloc(void *orig_state, AppProto proto_orig) SCMutexLock(&htp_state_mem_lock); htp_state_memcnt++; htp_state_memuse += sizeof(HtpState); - SCLogDebug("htp memory %"PRIu64" (%"PRIu64")", htp_state_memuse, htp_state_memcnt); + SCLogDebug("htp memory %" PRIu64 " (%" PRIu64 ")", htp_state_memuse, htp_state_memcnt); SCMutexUnlock(&htp_state_mem_lock); #endif @@ -404,7 +403,7 @@ void HTPStateFree(void *state) for (tx_id = 0; tx_id < total_txs; tx_id++) { htp_tx_t *tx = HTPStateGetTx(s, tx_id); if (tx != NULL) { - HtpTxUserData *htud = (HtpTxUserData *) htp_tx_get_user_data(tx); + HtpTxUserData *htud = (HtpTxUserData *)htp_tx_get_user_data(tx); HtpTxUserDataFree(s, htud); htp_tx_set_user_data(tx, NULL); } @@ -419,7 +418,7 @@ void HTPStateFree(void *state) SCMutexLock(&htp_state_mem_lock); htp_state_memcnt--; htp_state_memuse -= sizeof(HtpState); - SCLogDebug("htp memory %"PRIu64" (%"PRIu64")", htp_state_memuse, htp_state_memcnt); + SCLogDebug("htp memory %" PRIu64 " (%" PRIu64 ")", htp_state_memuse, htp_state_memcnt); SCMutexUnlock(&htp_state_mem_lock); #endif @@ -438,12 +437,12 @@ static void HTPStateTransactionFree(void *state, uint64_t id) HtpState *s = (HtpState *)state; - SCLogDebug("state %p, id %"PRIu64, s, id); + SCLogDebug("state %p, id %" PRIu64, s, id); htp_tx_t *tx = HTPStateGetTx(s, id); if (tx != NULL) { /* This will remove obsolete body chunks */ - HtpTxUserData *htud = (HtpTxUserData *) htp_tx_get_user_data(tx); + HtpTxUserData *htud = (HtpTxUserData *)htp_tx_get_user_data(tx); HtpTxUserDataFree(s, htud); htp_tx_set_user_data(tx, NULL); @@ -451,10 +450,8 @@ static void HTPStateTransactionFree(void *state, uint64_t id) * free it here. htp_tx_destroy however, will refuse to do this. * As htp_tx_destroy_incomplete isn't available in the public API, * we hack around it here. */ - if (unlikely(!( - tx->request_progress == HTP_REQUEST_COMPLETE && - tx->response_progress == HTP_RESPONSE_COMPLETE))) - { + if (unlikely(!(tx->request_progress == HTP_REQUEST_COMPLETE && + tx->response_progress == HTP_RESPONSE_COMPLETE))) { tx->request_progress = HTP_REQUEST_COMPLETE; tx->response_progress = HTP_RESPONSE_COMPLETE; } @@ -522,7 +519,7 @@ void AppLayerHtpNeedFileInspection(void) static void AppLayerHtpSetStreamDepthFlag(void *tx, const uint8_t flags) { - HtpTxUserData *tx_ud = (HtpTxUserData *) htp_tx_get_user_data((htp_tx_t *)tx); + HtpTxUserData *tx_ud = (HtpTxUserData *)htp_tx_get_user_data((htp_tx_t *)tx); if (tx_ud) { SCLogDebug("setting HTP_STREAM_DEPTH_SET, flags %02x", flags); if (flags & STREAM_TOCLIENT) { @@ -553,18 +550,16 @@ static bool AppLayerHtpCheckDepth(const HTPCfgDir *cfg, HtpBody *body, uint8_t f } static uint32_t AppLayerHtpComputeChunkLength(uint64_t content_len_so_far, uint32_t body_limit, - uint32_t stream_depth, uint8_t flags, uint32_t data_len) + uint32_t stream_depth, uint8_t flags, uint32_t data_len) { uint32_t chunk_len = 0; if (!(flags & HTP_STREAM_DEPTH_SET) && body_limit > 0 && - (content_len_so_far < (uint64_t)body_limit) && - (content_len_so_far + (uint64_t)data_len) > body_limit) - { + (content_len_so_far < (uint64_t)body_limit) && + (content_len_so_far + (uint64_t)data_len) > body_limit) { chunk_len = body_limit - content_len_so_far; } else if ((flags & HTP_STREAM_DEPTH_SET) && stream_depth > 0 && (content_len_so_far < (uint64_t)stream_depth) && - (content_len_so_far + (uint64_t)data_len) > stream_depth) - { + (content_len_so_far + (uint64_t)data_len) > stream_depth) { chunk_len = stream_depth - content_len_so_far; } SCLogDebug("len %u", chunk_len); @@ -576,23 +571,34 @@ struct { const char *msg; uint8_t de; } htp_errors[] = { - { "GZip decompressor: inflateInit2 failed", HTTP_DECODER_EVENT_GZIP_DECOMPRESSION_FAILED}, - { "Request field invalid: colon missing", HTTP_DECODER_EVENT_REQUEST_FIELD_MISSING_COLON}, - { "Response field invalid: missing colon", HTTP_DECODER_EVENT_RESPONSE_FIELD_MISSING_COLON}, - { "Request chunk encoding: Invalid chunk length", HTTP_DECODER_EVENT_INVALID_REQUEST_CHUNK_LEN}, - { "Response chunk encoding: Invalid chunk length", HTTP_DECODER_EVENT_INVALID_RESPONSE_CHUNK_LEN}, -/* { "Invalid T-E value in request", HTTP_DECODER_EVENT_INVALID_TRANSFER_ENCODING_VALUE_IN_REQUEST}, <- tx flag HTP_REQUEST_INVALID_T_E - { "Invalid T-E value in response", HTTP_DECODER_EVENT_INVALID_TRANSFER_ENCODING_VALUE_IN_RESPONSE}, <- nothing to replace it */ -/* { "Invalid C-L field in request", HTTP_DECODER_EVENT_INVALID_CONTENT_LENGTH_FIELD_IN_REQUEST}, <- tx flag HTP_REQUEST_INVALID_C_L */ - { "Invalid C-L field in response", HTTP_DECODER_EVENT_INVALID_CONTENT_LENGTH_FIELD_IN_RESPONSE}, - { "Already seen 100-Continue", HTTP_DECODER_EVENT_100_CONTINUE_ALREADY_SEEN}, - { "Unable to match response to request", HTTP_DECODER_EVENT_UNABLE_TO_MATCH_RESPONSE_TO_REQUEST}, - { "Invalid server port information in request", HTTP_DECODER_EVENT_INVALID_SERVER_PORT_IN_REQUEST}, -/* { "Invalid authority port", HTTP_DECODER_EVENT_INVALID_AUTHORITY_PORT}, htp no longer returns this error */ - { "Request buffer over", HTTP_DECODER_EVENT_REQUEST_FIELD_TOO_LONG}, - { "Response buffer over", HTTP_DECODER_EVENT_RESPONSE_FIELD_TOO_LONG}, - { "C-T multipart/byteranges in responses not supported", HTTP_DECODER_EVENT_RESPONSE_MULTIPART_BYTERANGES}, - { "Compression bomb:", HTTP_DECODER_EVENT_COMPRESSION_BOMB}, + { "GZip decompressor: inflateInit2 failed", HTTP_DECODER_EVENT_GZIP_DECOMPRESSION_FAILED }, + { "Request field invalid: colon missing", HTTP_DECODER_EVENT_REQUEST_FIELD_MISSING_COLON }, + { "Response field invalid: missing colon", HTTP_DECODER_EVENT_RESPONSE_FIELD_MISSING_COLON }, + { "Request chunk encoding: Invalid chunk length", + HTTP_DECODER_EVENT_INVALID_REQUEST_CHUNK_LEN }, + { "Response chunk encoding: Invalid chunk length", + HTTP_DECODER_EVENT_INVALID_RESPONSE_CHUNK_LEN }, + /* { "Invalid T-E value in request", + HTTP_DECODER_EVENT_INVALID_TRANSFER_ENCODING_VALUE_IN_REQUEST}, <- tx flag + HTP_REQUEST_INVALID_T_E { "Invalid T-E value in response", + HTTP_DECODER_EVENT_INVALID_TRANSFER_ENCODING_VALUE_IN_RESPONSE}, <- nothing to replace it */ + /* { "Invalid C-L field in request", + HTTP_DECODER_EVENT_INVALID_CONTENT_LENGTH_FIELD_IN_REQUEST}, <- tx flag + HTP_REQUEST_INVALID_C_L */ + { "Invalid C-L field in response", + HTTP_DECODER_EVENT_INVALID_CONTENT_LENGTH_FIELD_IN_RESPONSE }, + { "Already seen 100-Continue", HTTP_DECODER_EVENT_100_CONTINUE_ALREADY_SEEN }, + { "Unable to match response to request", + HTTP_DECODER_EVENT_UNABLE_TO_MATCH_RESPONSE_TO_REQUEST }, + { "Invalid server port information in request", + HTTP_DECODER_EVENT_INVALID_SERVER_PORT_IN_REQUEST }, + /* { "Invalid authority port", HTTP_DECODER_EVENT_INVALID_AUTHORITY_PORT}, htp no longer + returns this error */ + { "Request buffer over", HTTP_DECODER_EVENT_REQUEST_FIELD_TOO_LONG }, + { "Response buffer over", HTTP_DECODER_EVENT_RESPONSE_FIELD_TOO_LONG }, + { "C-T multipart/byteranges in responses not supported", + HTTP_DECODER_EVENT_RESPONSE_MULTIPART_BYTERANGES }, + { "Compression bomb:", HTTP_DECODER_EVENT_COMPRESSION_BOMB }, }; struct { @@ -642,7 +648,7 @@ struct { { "Request chunk extension", HTTP_DECODER_EVENT_REQUEST_CHUNK_EXTENSION }, }; -#define HTP_ERROR_MAX (sizeof(htp_errors) / sizeof(htp_errors[0])) +#define HTP_ERROR_MAX (sizeof(htp_errors) / sizeof(htp_errors[0])) #define HTP_WARNING_MAX (sizeof(htp_warnings) / sizeof(htp_warnings[0])) /** @@ -659,9 +665,7 @@ static uint8_t HTPHandleWarningGetId(const char *msg) SCLogDebug("received warning \"%s\"", msg); size_t idx; for (idx = 0; idx < HTP_WARNING_MAX; idx++) { - if (strncmp(htp_warnings[idx].msg, msg, - strlen(htp_warnings[idx].msg)) == 0) - { + if (strncmp(htp_warnings[idx].msg, msg, strlen(htp_warnings[idx].msg)) == 0) { return htp_warnings[idx].de; } } @@ -684,9 +688,7 @@ static uint8_t HTPHandleErrorGetId(const char *msg) size_t idx; for (idx = 0; idx < HTP_ERROR_MAX; idx++) { - if (strncmp(htp_errors[idx].msg, msg, - strlen(htp_errors[idx].msg)) == 0) - { + if (strncmp(htp_errors[idx].msg, msg, strlen(htp_errors[idx].msg)) == 0) { return htp_errors[idx].de; } } @@ -704,20 +706,19 @@ static uint8_t HTPHandleErrorGetId(const char *msg) */ static void HTPHandleError(HtpState *s, const uint8_t dir) { - if (s == NULL || s->conn == NULL || - s->conn->messages == NULL) { + if (s == NULL || s->conn == NULL || s->conn->messages == NULL) { return; } size_t size = htp_list_size(s->conn->messages); size_t msg; - if(size >= HTP_MAX_MESSAGES) { + if (size >= HTP_MAX_MESSAGES) { if (s->htp_messages_offset < HTP_MAX_MESSAGES) { - //only once per HtpState + // only once per HtpState HTPSetEvent(s, NULL, dir, HTTP_DECODER_EVENT_TOO_MANY_WARNINGS); s->htp_messages_offset = HTP_MAX_MESSAGES; - //too noisy in fuzzing - //DEBUG_VALIDATE_BUG_ON("Too many libhtp messages"); + // too noisy in fuzzing + // DEBUG_VALIDATE_BUG_ON("Too many libhtp messages"); } // ignore further messages return; @@ -731,7 +732,7 @@ static void HTPHandleError(HtpState *s, const uint8_t dir) HtpTxUserData *htud = NULL; htp_tx_t *tx = log->tx; // will be NULL in <=0.5.9 if (tx != NULL) - htud = (HtpTxUserData *) htp_tx_get_user_data(tx); + htud = (HtpTxUserData *)htp_tx_get_user_data(tx); SCLogDebug("message %s", log->msg); @@ -755,11 +756,9 @@ static inline void HTPErrorCheckTxRequestFlags(HtpState *s, htp_tx_t *tx) #ifdef DEBUG BUG_ON(s == NULL || tx == NULL); #endif - if (tx->flags & ( HTP_REQUEST_INVALID_T_E|HTP_REQUEST_INVALID_C_L| - HTP_HOST_MISSING|HTP_HOST_AMBIGUOUS|HTP_HOSTU_INVALID| - HTP_HOSTH_INVALID)) - { - HtpTxUserData *htud = (HtpTxUserData *) htp_tx_get_user_data(tx); + if (tx->flags & (HTP_REQUEST_INVALID_T_E | HTP_REQUEST_INVALID_C_L | HTP_HOST_MISSING | + HTP_HOST_AMBIGUOUS | HTP_HOSTU_INVALID | HTP_HOSTH_INVALID)) { + HtpTxUserData *htud = (HtpTxUserData *)htp_tx_get_user_data(tx); if (htud == NULL) return; @@ -770,33 +769,27 @@ static inline void HTPErrorCheckTxRequestFlags(HtpState *s, htp_tx_t *tx) HTPSetEvent(s, htud, STREAM_TOSERVER, HTTP_DECODER_EVENT_INVALID_CONTENT_LENGTH_FIELD_IN_REQUEST); if (tx->flags & HTP_HOST_MISSING) - HTPSetEvent(s, htud, STREAM_TOSERVER, - HTTP_DECODER_EVENT_MISSING_HOST_HEADER); + HTPSetEvent(s, htud, STREAM_TOSERVER, HTTP_DECODER_EVENT_MISSING_HOST_HEADER); if (tx->flags & HTP_HOST_AMBIGUOUS) - HTPSetEvent(s, htud, STREAM_TOSERVER, - HTTP_DECODER_EVENT_HOST_HEADER_AMBIGUOUS); + HTPSetEvent(s, htud, STREAM_TOSERVER, HTTP_DECODER_EVENT_HOST_HEADER_AMBIGUOUS); if (tx->flags & HTP_HOSTU_INVALID) - HTPSetEvent(s, htud, STREAM_TOSERVER, - HTTP_DECODER_EVENT_URI_HOST_INVALID); + HTPSetEvent(s, htud, STREAM_TOSERVER, HTTP_DECODER_EVENT_URI_HOST_INVALID); if (tx->flags & HTP_HOSTH_INVALID) - HTPSetEvent(s, htud, STREAM_TOSERVER, - HTTP_DECODER_EVENT_HEADER_HOST_INVALID); + HTPSetEvent(s, htud, STREAM_TOSERVER, HTTP_DECODER_EVENT_HEADER_HOST_INVALID); } if (tx->request_auth_type == HTP_AUTH_UNRECOGNIZED) { - HtpTxUserData *htud = (HtpTxUserData *) htp_tx_get_user_data(tx); + HtpTxUserData *htud = (HtpTxUserData *)htp_tx_get_user_data(tx); if (htud == NULL) return; - HTPSetEvent(s, htud, STREAM_TOSERVER, - HTTP_DECODER_EVENT_AUTH_UNRECOGNIZED); + HTPSetEvent(s, htud, STREAM_TOSERVER, HTTP_DECODER_EVENT_AUTH_UNRECOGNIZED); } if (tx->is_protocol_0_9 && tx->request_method_number == HTP_M_UNKNOWN && - (tx->request_protocol_number == HTP_PROTOCOL_INVALID || - tx->request_protocol_number == HTP_PROTOCOL_UNKNOWN)) { - HtpTxUserData *htud = (HtpTxUserData *) htp_tx_get_user_data(tx); + (tx->request_protocol_number == HTP_PROTOCOL_INVALID || + tx->request_protocol_number == HTP_PROTOCOL_UNKNOWN)) { + HtpTxUserData *htud = (HtpTxUserData *)htp_tx_get_user_data(tx); if (htud == NULL) return; - HTPSetEvent(s, htud, STREAM_TOSERVER, - HTTP_DECODER_EVENT_REQUEST_LINE_INVALID); + HTPSetEvent(s, htud, STREAM_TOSERVER, HTTP_DECODER_EVENT_REQUEST_LINE_INVALID); } } @@ -812,12 +805,10 @@ static int Setup(Flow *f, HtpState *hstate) if (FLOW_IS_IPV4(f)) { SCLogDebug("Looking up HTP config for ipv4 %08x", *GET_IPV4_DST_ADDR_PTR(f)); (void)SCRadixFindKeyIPV4BestMatch((uint8_t *)GET_IPV4_DST_ADDR_PTR(f), cfgtree, &user_data); - } - else if (FLOW_IS_IPV6(f)) { + } else if (FLOW_IS_IPV6(f)) { SCLogDebug("Looking up HTP config for ipv6"); (void)SCRadixFindKeyIPV6BestMatch((uint8_t *)GET_IPV6_DST_ADDR(f), cfgtree, &user_data); - } - else { + } else { SCLogError("unknown address family, bug!"); goto error; } @@ -853,10 +844,10 @@ static int Setup(Flow *f, HtpState *hstate) struct timeval tv = { SCTIME_SECS(f->startts), SCTIME_USECS(f->startts) }; htp_connp_open(hstate->connp, NULL, f->sp, NULL, f->dp, &tv); - StreamTcpReassemblySetMinInspectDepth(f->protoctx, STREAM_TOSERVER, - htp_cfg_rec->request.inspect_min_size); - StreamTcpReassemblySetMinInspectDepth(f->protoctx, STREAM_TOCLIENT, - htp_cfg_rec->response.inspect_min_size); + StreamTcpReassemblySetMinInspectDepth( + f->protoctx, STREAM_TOSERVER, htp_cfg_rec->request.inspect_min_size); + StreamTcpReassemblySetMinInspectDepth( + f->protoctx, STREAM_TOCLIENT, htp_cfg_rec->response.inspect_min_size); return 0; error: return -1; @@ -910,8 +901,7 @@ static AppLayerResult HTPHandleRequestData(Flow *f, void *htp_state, AppLayerPar /* if the TCP connection is closed, then close the HTTP connection */ if (AppLayerParserStateIssetFlag(pstate, APP_LAYER_PARSER_EOF_TS) && - !(hstate->flags & HTP_FLAG_STATE_CLOSED_TS)) - { + !(hstate->flags & HTP_FLAG_STATE_CLOSED_TS)) { htp_connp_req_close(hstate->connp, &ts); hstate->flags |= HTP_FLAG_STATE_CLOSED_TS; SCLogDebug("stream eof encountered, closing htp handle for ts"); @@ -1008,8 +998,7 @@ static AppLayerResult HTPHandleResponseData(Flow *f, void *htp_state, AppLayerPa /* if we the TCP connection is closed, then close the HTTP connection */ if (AppLayerParserStateIssetFlag(pstate, APP_LAYER_PARSER_EOF_TC) && - !(hstate->flags & HTP_FLAG_STATE_CLOSED_TC)) - { + !(hstate->flags & HTP_FLAG_STATE_CLOSED_TC)) { htp_connp_close(hstate->connp, &ts); hstate->flags |= HTP_FLAG_STATE_CLOSED_TC; } @@ -1026,8 +1015,8 @@ static AppLayerResult HTPHandleResponseData(Flow *f, void *htp_state, AppLayerPa /** * \param name /Lowercase/ version of the variable name */ -static int HTTPParseContentDispositionHeader(uint8_t *name, size_t name_len, - uint8_t *data, size_t len, uint8_t **retptr, size_t *retlen) +static int HTTPParseContentDispositionHeader( + uint8_t *name, size_t name_len, uint8_t *data, size_t len, uint8_t **retptr, size_t *retlen) { #ifdef PRINT printf("DATA START: \n"); @@ -1045,21 +1034,22 @@ static int HTTPParseContentDispositionHeader(uint8_t *name, size_t name_len, if (x >= len) return 0; - uint8_t *line = data+x; - size_t line_len = len-x; + uint8_t *line = data + x; + size_t line_len = len - x; size_t offset = 0; #ifdef PRINT printf("LINE START: \n"); PrintRawDataFp(stdout, line, line_len); printf("LINE END: \n"); #endif - for (x = 0 ; x < line_len; x++) { + for (x = 0; x < line_len; x++) { if (x > 0) { if (line[x - 1] != '\\' && line[x] == '\"') { quote++; } - if (((line[x - 1] != '\\' && line[x] == ';') || ((x + 1) == line_len)) && (quote == 0 || quote % 2 == 0)) { + if (((line[x - 1] != '\\' && line[x] == ';') || ((x + 1) == line_len)) && + (quote == 0 || quote % 2 == 0)) { uint8_t *token = line + offset; size_t token_len = x - offset; @@ -1087,7 +1077,7 @@ static int HTTPParseContentDispositionHeader(uint8_t *name, size_t name_len, value++; value_len--; } - if (value[value_len-1] == '\"') { + if (value[value_len - 1] == '\"') { value_len--; } #ifdef PRINT @@ -1110,8 +1100,8 @@ static int HTTPParseContentDispositionHeader(uint8_t *name, size_t name_len, /** * \param name /Lowercase/ version of the variable name */ -static int HTTPParseContentTypeHeader(uint8_t *name, size_t name_len, - uint8_t *data, size_t len, uint8_t **retptr, size_t *retlen) +static int HTTPParseContentTypeHeader( + uint8_t *name, size_t name_len, uint8_t *data, size_t len, uint8_t **retptr, size_t *retlen) { SCEnter(); #ifdef PRINT @@ -1131,21 +1121,22 @@ static int HTTPParseContentTypeHeader(uint8_t *name, size_t name_len, SCReturnInt(0); } - uint8_t *line = data+x; - size_t line_len = len-x; + uint8_t *line = data + x; + size_t line_len = len - x; size_t offset = 0; #ifdef PRINT printf("LINE START: \n"); PrintRawDataFp(stdout, line, line_len); printf("LINE END: \n"); #endif - for (x = 0 ; x < line_len; x++) { + for (x = 0; x < line_len; x++) { if (x > 0) { if (line[x - 1] != '\\' && line[x] == '\"') { quote++; } - if (((line[x - 1] != '\\' && line[x] == ';') || ((x + 1) == line_len)) && (quote == 0 || quote % 2 == 0)) { + if (((line[x - 1] != '\\' && line[x] == ';') || ((x + 1) == line_len)) && + (quote == 0 || quote % 2 == 0)) { uint8_t *token = line + offset; size_t token_len = x - offset; @@ -1173,7 +1164,7 @@ static int HTTPParseContentTypeHeader(uint8_t *name, size_t name_len, value++; value_len--; } - if (value[value_len-1] == '\"') { + if (value[value_len - 1] == '\"') { value_len--; } #ifdef PRINT @@ -1208,15 +1199,13 @@ static int HTTPParseContentTypeHeader(uint8_t *name, size_t name_len, */ static int HtpRequestBodySetupMultipart(htp_tx_t *tx, HtpTxUserData *htud) { - htp_header_t *h = (htp_header_t *)htp_table_get_c(tx->request_headers, - "Content-Type"); + htp_header_t *h = (htp_header_t *)htp_table_get_c(tx->request_headers, "Content-Type"); if (h != NULL && bstr_len(h->value) > 0) { uint8_t *boundary = NULL; size_t boundary_len = 0; - int r = HTTPParseContentTypeHeader((uint8_t *)"boundary=", 9, - (uint8_t *) bstr_ptr(h->value), bstr_len(h->value), - &boundary, &boundary_len); + int r = HTTPParseContentTypeHeader((uint8_t *)"boundary=", 9, (uint8_t *)bstr_ptr(h->value), + bstr_len(h->value), &boundary, &boundary_len); if (r == 1) { #ifdef PRINT printf("BOUNDARY START: \n"); @@ -1238,20 +1227,18 @@ static int HtpRequestBodySetupMultipart(htp_tx_t *tx, HtpTxUserData *htud) } SCReturnInt(1); } - //SCReturnInt(1); + // SCReturnInt(1); } SCReturnInt(0); } -#define C_D_HDR "content-disposition:" +#define C_D_HDR "content-disposition:" #define C_D_HDR_LEN 20 -#define C_T_HDR "content-type:" +#define C_T_HDR "content-type:" #define C_T_HDR_LEN 13 -static void HtpRequestBodyMultipartParseHeader(HtpState *hstate, - HtpTxUserData *htud, - uint8_t *header, uint32_t header_len, - uint8_t **filename, uint16_t *filename_len, +static void HtpRequestBodyMultipartParseHeader(HtpState *hstate, HtpTxUserData *htud, + uint8_t *header, uint32_t header_len, uint8_t **filename, uint16_t *filename_len, uint8_t **filetype, uint16_t *filetype_len) { uint8_t *fn = NULL; @@ -1277,35 +1264,31 @@ static void HtpRequestBodyMultipartParseHeader(HtpState *hstate, } uint8_t *sc = (uint8_t *)memchr(line, ':', line_len); if (sc == NULL) { - HTPSetEvent(hstate, htud, STREAM_TOSERVER, - HTTP_DECODER_EVENT_MULTIPART_INVALID_HEADER); + HTPSetEvent(hstate, htud, STREAM_TOSERVER, HTTP_DECODER_EVENT_MULTIPART_INVALID_HEADER); /* if the : we found is the final char, it means we have * no value */ } else if (line_len > 0 && sc == &line[line_len - 1]) { - HTPSetEvent(hstate, htud, STREAM_TOSERVER, - HTTP_DECODER_EVENT_MULTIPART_INVALID_HEADER); + HTPSetEvent(hstate, htud, STREAM_TOSERVER, HTTP_DECODER_EVENT_MULTIPART_INVALID_HEADER); } else { #ifdef PRINT printf("LINE START: \n"); PrintRawDataFp(stdout, line, line_len); printf("LINE END: \n"); #endif - if (line_len >= C_D_HDR_LEN && - SCMemcmpLowercase(C_D_HDR, line, C_D_HDR_LEN) == 0) { + if (line_len >= C_D_HDR_LEN && SCMemcmpLowercase(C_D_HDR, line, C_D_HDR_LEN) == 0) { uint8_t *value = line + C_D_HDR_LEN; uint32_t value_len = line_len - C_D_HDR_LEN; /* parse content-disposition */ - (void)HTTPParseContentDispositionHeader((uint8_t *)"filename=", 9, - value, value_len, &fn, &fn_len); + (void)HTTPParseContentDispositionHeader( + (uint8_t *)"filename=", 9, value, value_len, &fn, &fn_len); } else if (line_len >= C_T_HDR_LEN && - SCMemcmpLowercase(C_T_HDR, line, C_T_HDR_LEN) == 0) { + SCMemcmpLowercase(C_T_HDR, line, C_T_HDR_LEN) == 0) { SCLogDebug("content-type line"); uint8_t *value = line + C_T_HDR_LEN; uint32_t value_len = line_len - C_T_HDR_LEN; - (void)HTTPParseContentTypeHeader(NULL, 0, - value, value_len, &ft, &ft_len); + (void)HTTPParseContentTypeHeader(NULL, 0, value, value_len, &ft, &ft_len); } } @@ -1335,11 +1318,10 @@ static void HtpRequestBodyMultipartParseHeader(HtpState *hstate, * \param chunks_buffers pointer to pass back the buffer to the caller * \param chunks_buffer_len pointer to pass back the buffer length to the caller */ -static void HtpRequestBodyReassemble(HtpTxUserData *htud, - const uint8_t **chunks_buffer, uint32_t *chunks_buffer_len) +static void HtpRequestBodyReassemble( + HtpTxUserData *htud, const uint8_t **chunks_buffer, uint32_t *chunks_buffer_len) { - StreamingBufferGetDataAtOffset(htud->request_body.sb, - chunks_buffer, chunks_buffer_len, + StreamingBufferGetDataAtOffset(htud->request_body.sb, chunks_buffer, chunks_buffer_len, htud->request_body.body_parsed); } @@ -1360,8 +1342,8 @@ static void FlagDetectStateNewFile(HtpTxUserData *tx, int dir) /** * \brief Setup boundary buffers */ -static void HtpRequestBodySetupBoundary(HtpTxUserData *htud, - uint8_t *boundary, uint32_t boundary_len) +static void HtpRequestBodySetupBoundary( + HtpTxUserData *htud, uint8_t *boundary, uint32_t boundary_len) { memset(boundary, '-', boundary_len); memcpy(boundary + 2, htud->boundary, htud->boundary_len); @@ -1385,8 +1367,8 @@ static int HtpRequestBodyHandleMultipart(HtpState *hstate, HtpTxUserData *htud, HtpRequestBodySetupBoundary(htud, boundary, htud->boundary_len + 4); /* search for the header start, header end and form end */ - const uint8_t *header_start = Bs2bmSearch(chunks_buffer, chunks_buffer_len, - boundary, expected_boundary_len); + const uint8_t *header_start = + Bs2bmSearch(chunks_buffer, chunks_buffer_len, boundary, expected_boundary_len); /* end of the multipart form */ const uint8_t *form_end = NULL; /* end marker belonging to header_start */ @@ -1398,8 +1380,7 @@ static int HtpRequestBodyHandleMultipart(HtpState *hstate, HtpTxUserData *htud, boundary, expected_boundary_end_len); } - SCLogDebug("header_start %p, header_end %p, form_end %p", header_start, - header_end, form_end); + SCLogDebug("header_start %p, header_end %p, form_end %p", header_start, header_end, form_end); /* we currently only handle multipart for ts. When we support it for tc, * we will need to supply right direction */ @@ -1432,8 +1413,8 @@ static int HtpRequestBodyHandleMultipart(HtpState *hstate, HtpTxUserData *htud, } if (filedata_len > chunks_buffer_len) { - HTPSetEvent(hstate, htud, STREAM_TOSERVER, - HTTP_DECODER_EVENT_MULTIPART_GENERIC_ERROR); + HTPSetEvent( + hstate, htud, STREAM_TOSERVER, HTTP_DECODER_EVENT_MULTIPART_GENERIC_ERROR); goto end; } #ifdef PRINT @@ -1448,7 +1429,7 @@ static int HtpRequestBodyHandleMultipart(HtpState *hstate, HtpTxUserData *htud, } } - htud->tsflags &=~ HTP_FILENAME_SET; + htud->tsflags &= ~HTP_FILENAME_SET; /* fall through */ } else { @@ -1493,12 +1474,9 @@ static int HtpRequestBodyHandleMultipart(HtpState *hstate, HtpTxUserData *htud, } } - while (header_start != NULL && header_end != NULL && - header_end != form_end && + while (header_start != NULL && header_end != NULL && header_end != form_end && header_start < (chunks_buffer + chunks_buffer_len) && - header_end < (chunks_buffer + chunks_buffer_len) && - header_start < header_end) - { + header_end < (chunks_buffer + chunks_buffer_len) && header_start < header_end) { uint8_t *filename = NULL; uint16_t filename_len = 0; uint8_t *filetype = NULL; @@ -1516,8 +1494,8 @@ static int HtpRequestBodyHandleMultipart(HtpState *hstate, HtpTxUserData *htud, header = (uint8_t *)header_start + (expected_boundary_len + 2); // + for 0d 0a } - HtpRequestBodyMultipartParseHeader(hstate, htud, header, header_len, - &filename, &filename_len, &filetype, &filetype_len); + HtpRequestBodyMultipartParseHeader(hstate, htud, header, header_len, &filename, + &filename_len, &filetype, &filetype_len); if (filename != NULL) { const uint8_t *filedata = NULL; @@ -1547,11 +1525,11 @@ static int HtpRequestBodyHandleMultipart(HtpState *hstate, HtpTxUserData *htud, } filedata_len = form_end - (header_end + 4 + 2); - SCLogDebug("filedata_len %"PRIuMAX, (uintmax_t)filedata_len); + SCLogDebug("filedata_len %" PRIuMAX, (uintmax_t)filedata_len); /* or is it? */ - uint8_t *header_next = Bs2bmSearch(filedata, filedata_len, - boundary, expected_boundary_len); + uint8_t *header_next = + Bs2bmSearch(filedata, filedata_len, boundary, expected_boundary_len); if (header_next != NULL) { filedata_len -= (form_end - header_next); } @@ -1561,7 +1539,7 @@ static int HtpRequestBodyHandleMultipart(HtpState *hstate, HtpTxUserData *htud, HTTP_DECODER_EVENT_MULTIPART_GENERIC_ERROR); goto end; } - SCLogDebug("filedata_len %"PRIuMAX, (uintmax_t)filedata_len); + SCLogDebug("filedata_len %" PRIuMAX, (uintmax_t)filedata_len); #ifdef PRINT printf("FILEDATA START: \n"); PrintRawDataFp(stdout, filedata, filedata_len); @@ -1588,7 +1566,8 @@ static int HtpRequestBodyHandleMultipart(HtpState *hstate, HtpTxUserData *htud, filedata = header_end + 4; filedata_len = chunks_buffer_len - (filedata - chunks_buffer); - SCLogDebug("filedata_len %u (chunks_buffer_len %u)", filedata_len, chunks_buffer_len); + SCLogDebug( + "filedata_len %u (chunks_buffer_len %u)", filedata_len, chunks_buffer_len); if (filedata_len > chunks_buffer_len) { HTPSetEvent(hstate, htud, STREAM_TOSERVER, @@ -1603,8 +1582,8 @@ static int HtpRequestBodyHandleMultipart(HtpState *hstate, HtpTxUserData *htud, #endif /* form doesn't end in this chunk, but the part might. Lets * see if have another coming up */ - uint8_t *header_next = Bs2bmSearch(filedata, filedata_len, - boundary, expected_boundary_len); + uint8_t *header_next = + Bs2bmSearch(filedata, filedata_len, boundary, expected_boundary_len); SCLogDebug("header_next %p", header_next); if (header_next == NULL) { SCLogDebug("more file data to come"); @@ -1639,7 +1618,8 @@ static int HtpRequestBodyHandleMultipart(HtpState *hstate, HtpTxUserData *htud, } FlagDetectStateNewFile(htud, STREAM_TOSERVER); htud->request_body.body_parsed += filedata_len; - SCLogDebug("htud->request_body.body_parsed %"PRIu64, htud->request_body.body_parsed); + SCLogDebug("htud->request_body.body_parsed %" PRIu64, + htud->request_body.body_parsed); } else if (header_next - filedata > 2) { filedata_len = header_next - filedata - 2; @@ -1663,19 +1643,17 @@ static int HtpRequestBodyHandleMultipart(HtpState *hstate, HtpTxUserData *htud, } } } -next: - SCLogDebug("header_start %p, header_end %p, form_end %p", - header_start, header_end, form_end); + next: + SCLogDebug( + "header_start %p, header_end %p, form_end %p", header_start, header_end, form_end); /* Search next boundary entry after the start of body */ uint32_t cursizeread = header_end - chunks_buffer; - header_start = Bs2bmSearch(header_end + 4, - chunks_buffer_len - (cursizeread + 4), - boundary, expected_boundary_len); + header_start = Bs2bmSearch(header_end + 4, chunks_buffer_len - (cursizeread + 4), boundary, + expected_boundary_len); if (header_start != NULL) { - header_end = Bs2bmSearch(header_end + 4, - chunks_buffer_len - (cursizeread + 4), - (uint8_t *) "\r\n\r\n", 4); + header_end = Bs2bmSearch(header_end + 4, chunks_buffer_len - (cursizeread + 4), + (uint8_t *)"\r\n\r\n", 4); } } @@ -1687,26 +1665,26 @@ static int HtpRequestBodyHandleMultipart(HtpState *hstate, HtpTxUserData *htud, htud->request_body.body_parsed += move; SCLogDebug("form not ready, file not set, parsing non-file " - "record: moved %u", move); + "record: moved %u", + move); } } end: - SCLogDebug("htud->request_body.body_parsed %"PRIu64, htud->request_body.body_parsed); + SCLogDebug("htud->request_body.body_parsed %" PRIu64, htud->request_body.body_parsed); return 0; } /** \internal * \brief Handle POST or PUT, no multipart body data */ -static int HtpRequestBodyHandlePOSTorPUT(HtpState *hstate, HtpTxUserData *htud, - htp_tx_t *tx, uint8_t *data, uint32_t data_len) +static int HtpRequestBodyHandlePOSTorPUT( + HtpState *hstate, HtpTxUserData *htud, htp_tx_t *tx, uint8_t *data, uint32_t data_len) { int result = 0; /* see if we need to open the file */ - if (!(htud->tsflags & HTP_FILENAME_SET)) - { + if (!(htud->tsflags & HTP_FILENAME_SET)) { uint8_t *filename = NULL; size_t filename_len = 0; @@ -1734,9 +1712,7 @@ static int HtpRequestBodyHandlePOSTorPUT(HtpState *hstate, HtpTxUserData *htud, htud->tsflags &= ~HTP_DONTSTORE; } } - } - else - { + } else { /* otherwise, just store the data */ if (!(htud->tsflags & HTP_DONTSTORE)) { @@ -1755,8 +1731,8 @@ static int HtpRequestBodyHandlePOSTorPUT(HtpState *hstate, HtpTxUserData *htud, return -1; } -static int HtpResponseBodyHandle(HtpState *hstate, HtpTxUserData *htud, - htp_tx_t *tx, uint8_t *data, uint32_t data_len) +static int HtpResponseBodyHandle( + HtpState *hstate, HtpTxUserData *htud, htp_tx_t *tx, uint8_t *data, uint32_t data_len) { SCEnter(); @@ -1773,12 +1749,12 @@ static int HtpResponseBodyHandle(HtpState *hstate, HtpTxUserData *htud, size_t filename_len = 0; /* try Content-Disposition header first */ - htp_header_t *h = (htp_header_t *)htp_table_get_c(tx->response_headers, - "Content-Disposition"); + htp_header_t *h = + (htp_header_t *)htp_table_get_c(tx->response_headers, "Content-Disposition"); if (h != NULL && bstr_len(h->value) > 0) { /* parse content-disposition */ (void)HTTPParseContentDispositionHeader((uint8_t *)"filename=", 9, - (uint8_t *) bstr_ptr(h->value), bstr_len(h->value), &filename, &filename_len); + (uint8_t *)bstr_ptr(h->value), bstr_len(h->value), &filename, &filename_len); } /* fall back to name from the uri */ @@ -1864,9 +1840,10 @@ static int HTPCallbackRequestBodyData(htp_tx_data_t *d) } SCLogDebug("New request body data available at %p -> %p -> %p, bodylen " - "%"PRIu32"", hstate, d, d->data, (uint32_t)d->len); + "%" PRIu32 "", + hstate, d, d->data, (uint32_t)d->len); - HtpTxUserData *tx_ud = (HtpTxUserData *) htp_tx_get_user_data(d->tx); + HtpTxUserData *tx_ud = (HtpTxUserData *)htp_tx_get_user_data(d->tx); if (tx_ud == NULL) { SCReturnInt(HTP_OK); } @@ -1892,17 +1869,15 @@ static int HTPCallbackRequestBodyData(htp_tx_data_t *d) /* see if we can get rid of htp body chunks */ HtpBodyPrune(hstate, &tx_ud->request_body, STREAM_TOSERVER); - SCLogDebug("tx_ud->request_body.content_len_so_far %"PRIu64, tx_ud->request_body.content_len_so_far); + SCLogDebug("tx_ud->request_body.content_len_so_far %" PRIu64, + tx_ud->request_body.content_len_so_far); SCLogDebug("hstate->cfg->request.body_limit %u", hstate->cfg->request.body_limit); /* within limits, add the body chunk to the state. */ if (AppLayerHtpCheckDepth(&hstate->cfg->request, &tx_ud->request_body, tx_ud->tsflags)) { uint32_t stream_depth = FileReassemblyDepth(); uint32_t len = AppLayerHtpComputeChunkLength(tx_ud->request_body.content_len_so_far, - hstate->cfg->request.body_limit, - stream_depth, - tx_ud->tsflags, - (uint32_t)d->len); + hstate->cfg->request.body_limit, stream_depth, tx_ud->tsflags, (uint32_t)d->len); BUG_ON(len > (uint32_t)d->len); HtpBodyAppendChunk(&hstate->cfg->request, &tx_ud->request_body, d->data, len); @@ -1943,9 +1918,9 @@ static int HTPCallbackRequestBodyData(htp_tx_data_t *d) end: if (hstate->conn != NULL) { - SCLogDebug("checking body size %"PRIu64" against inspect limit %u (cur %"PRIu64", last %"PRIu64")", - tx_ud->request_body.content_len_so_far, - hstate->cfg->request.inspect_min_size, + SCLogDebug("checking body size %" PRIu64 " against inspect limit %u (cur %" PRIu64 + ", last %" PRIu64 ")", + tx_ud->request_body.content_len_so_far, hstate->cfg->request.inspect_min_size, (uint64_t)hstate->conn->in_data_counter, hstate->last_request_data_stamp); /* if we reach the inspect_min_size we'll trigger inspection, @@ -1953,10 +1928,10 @@ static int HTPCallbackRequestBodyData(htp_tx_data_t *d) * data to be used to the amount of raw bytes we've seen to * get here. */ if (tx_ud->request_body.body_inspected == 0 && - tx_ud->request_body.content_len_so_far >= hstate->cfg->request.inspect_min_size) { + tx_ud->request_body.content_len_so_far >= hstate->cfg->request.inspect_min_size) { if ((uint64_t)hstate->conn->in_data_counter > hstate->last_request_data_stamp && - (uint64_t)hstate->conn->in_data_counter - hstate->last_request_data_stamp < (uint64_t)UINT_MAX) - { + (uint64_t)hstate->conn->in_data_counter - hstate->last_request_data_stamp < + (uint64_t)UINT_MAX) { const uint32_t data_size = (uint32_t)( (uint64_t)hstate->conn->in_data_counter - hstate->last_request_data_stamp); const uint32_t depth = MIN(data_size, hstate->cfg->request.inspect_min_size); @@ -1965,7 +1940,7 @@ static int HTPCallbackRequestBodyData(htp_tx_data_t *d) StreamTcpReassemblySetMinInspectDepth(hstate->f->protoctx, STREAM_TOSERVER, depth); AppLayerParserTriggerRawStreamReassembly(hstate->f, STREAM_TOSERVER); } - /* after the start of the body, disable the depth logic */ + /* after the start of the body, disable the depth logic */ } else if (tx_ud->request_body.body_inspected > 0) { StreamTcpReassemblySetMinInspectDepth(hstate->f->protoctx, STREAM_TOSERVER, 0); } @@ -1994,9 +1969,10 @@ static int HTPCallbackResponseBodyData(htp_tx_data_t *d) } SCLogDebug("New response body data available at %p -> %p -> %p, bodylen " - "%"PRIu32"", hstate, d, d->data, (uint32_t)d->len); + "%" PRIu32 "", + hstate, d, d->data, (uint32_t)d->len); - HtpTxUserData *tx_ud = (HtpTxUserData *) htp_tx_get_user_data(d->tx); + HtpTxUserData *tx_ud = (HtpTxUserData *)htp_tx_get_user_data(d->tx); if (tx_ud == NULL) { SCReturnInt(HTP_OK); } @@ -2008,17 +1984,15 @@ static int HTPCallbackResponseBodyData(htp_tx_data_t *d) /* see if we can get rid of htp body chunks */ HtpBodyPrune(hstate, &tx_ud->response_body, STREAM_TOCLIENT); - SCLogDebug("tx_ud->response_body.content_len_so_far %"PRIu64, tx_ud->response_body.content_len_so_far); + SCLogDebug("tx_ud->response_body.content_len_so_far %" PRIu64, + tx_ud->response_body.content_len_so_far); SCLogDebug("hstate->cfg->response.body_limit %u", hstate->cfg->response.body_limit); /* within limits, add the body chunk to the state. */ if (AppLayerHtpCheckDepth(&hstate->cfg->response, &tx_ud->response_body, tx_ud->tcflags)) { uint32_t stream_depth = FileReassemblyDepth(); uint32_t len = AppLayerHtpComputeChunkLength(tx_ud->response_body.content_len_so_far, - hstate->cfg->response.body_limit, - stream_depth, - tx_ud->tcflags, - (uint32_t)d->len); + hstate->cfg->response.body_limit, stream_depth, tx_ud->tcflags, (uint32_t)d->len); BUG_ON(len > (uint32_t)d->len); HtpBodyAppendChunk(&hstate->cfg->response, &tx_ud->response_body, d->data, len); @@ -2033,19 +2007,19 @@ static int HTPCallbackResponseBodyData(htp_tx_data_t *d) } if (hstate->conn != NULL) { - SCLogDebug("checking body size %"PRIu64" against inspect limit %u (cur %"PRIu64", last %"PRIu64")", - tx_ud->response_body.content_len_so_far, - hstate->cfg->response.inspect_min_size, + SCLogDebug("checking body size %" PRIu64 " against inspect limit %u (cur %" PRIu64 + ", last %" PRIu64 ")", + tx_ud->response_body.content_len_so_far, hstate->cfg->response.inspect_min_size, (uint64_t)hstate->conn->in_data_counter, hstate->last_response_data_stamp); /* if we reach the inspect_min_size we'll trigger inspection, * so make sure that raw stream is also inspected. Set the * data to be used to the amount of raw bytes we've seen to * get here. */ if (tx_ud->response_body.body_inspected == 0 && - tx_ud->response_body.content_len_so_far >= hstate->cfg->response.inspect_min_size) { + tx_ud->response_body.content_len_so_far >= hstate->cfg->response.inspect_min_size) { if ((uint64_t)hstate->conn->out_data_counter > hstate->last_response_data_stamp && - (uint64_t)hstate->conn->out_data_counter - hstate->last_response_data_stamp < (uint64_t)UINT_MAX) - { + (uint64_t)hstate->conn->out_data_counter - hstate->last_response_data_stamp < + (uint64_t)UINT_MAX) { const uint32_t data_size = (uint32_t)((uint64_t)hstate->conn->out_data_counter - hstate->last_response_data_stamp); const uint32_t depth = MIN(data_size, hstate->cfg->response.inspect_min_size); @@ -2054,7 +2028,7 @@ static int HTPCallbackResponseBodyData(htp_tx_data_t *d) StreamTcpReassemblySetMinInspectDepth(hstate->f->protoctx, STREAM_TOCLIENT, depth); AppLayerParserTriggerRawStreamReassembly(hstate->f, STREAM_TOCLIENT); } - /* after the start of the body, disable the depth logic */ + /* after the start of the body, disable the depth logic */ } else if (tx_ud->response_body.body_inspected > 0) { StreamTcpReassemblySetMinInspectDepth(hstate->f->protoctx, STREAM_TOCLIENT, 0); } @@ -2070,8 +2044,8 @@ void HTPAtExitPrintStats(void) #ifdef DEBUG SCEnter(); SCMutexLock(&htp_state_mem_lock); - SCLogDebug("http_state_memcnt %"PRIu64", http_state_memuse %"PRIu64"", - htp_state_memcnt, htp_state_memuse); + SCLogDebug("http_state_memcnt %" PRIu64 ", http_state_memuse %" PRIu64 "", htp_state_memcnt, + htp_state_memuse); SCMutexUnlock(&htp_state_mem_lock); SCReturn; #endif @@ -2083,8 +2057,7 @@ void HTPFreeConfig(void) SCEnter(); if (!AppLayerProtoDetectConfProtoDetectionEnabled("tcp", "http") || - !AppLayerParserConfParserEnabled("tcp", "http")) - { + !AppLayerParserConfParserEnabled("tcp", "http")) { SCReturn; } @@ -2146,10 +2119,10 @@ static int HTPCallbackRequestStart(htp_tx_t *tx) /* app-layer-frame-documentation tag end: frame registration http request */ if (hstate->cfg) - StreamTcpReassemblySetMinInspectDepth(hstate->f->protoctx, STREAM_TOSERVER, - hstate->cfg->request.inspect_min_size); + StreamTcpReassemblySetMinInspectDepth( + hstate->f->protoctx, STREAM_TOSERVER, hstate->cfg->request.inspect_min_size); - HtpTxUserData *tx_ud = (HtpTxUserData *) htp_tx_get_user_data(tx); + HtpTxUserData *tx_ud = (HtpTxUserData *)htp_tx_get_user_data(tx); if (tx_ud == NULL) { tx_ud = HTPCalloc(1, sizeof(HtpTxUserData)); if (unlikely(tx_ud == NULL)) { @@ -2185,10 +2158,10 @@ static int HTPCallbackResponseStart(htp_tx_t *tx) } if (hstate->cfg) - StreamTcpReassemblySetMinInspectDepth(hstate->f->protoctx, STREAM_TOCLIENT, - hstate->cfg->response.inspect_min_size); + StreamTcpReassemblySetMinInspectDepth( + hstate->f->protoctx, STREAM_TOCLIENT, hstate->cfg->response.inspect_min_size); - HtpTxUserData *tx_ud = (HtpTxUserData *) htp_tx_get_user_data(tx); + HtpTxUserData *tx_ud = (HtpTxUserData *)htp_tx_get_user_data(tx); if (tx_ud == NULL) { tx_ud = HTPCalloc(1, sizeof(HtpTxUserData)); if (unlikely(tx_ud == NULL)) { @@ -2239,8 +2212,8 @@ static int HTPCallbackRequestComplete(htp_tx_t *tx) hstate->request_frame_id = 0; } - SCLogDebug("transaction_cnt %"PRIu64", list_size %"PRIu64, - hstate->transaction_cnt, HTPStateGetTxCnt(hstate)); + SCLogDebug("transaction_cnt %" PRIu64 ", list_size %" PRIu64, hstate->transaction_cnt, + HTPStateGetTxCnt(hstate)); SCLogDebug("HTTP request completed"); @@ -2301,7 +2274,7 @@ static int HTPCallbackResponseComplete(htp_tx_t *tx) hstate->response_frame_id = 0; } - HtpTxUserData *htud = (HtpTxUserData *) htp_tx_get_user_data(tx); + HtpTxUserData *htud = (HtpTxUserData *)htp_tx_get_user_data(tx); if (htud != NULL) { if (htud->tcflags & HTP_FILENAME_SET) { SCLogDebug("closing file that was being stored"); @@ -2318,8 +2291,7 @@ static int HTPCallbackResponseComplete(htp_tx_t *tx) if (tx->request_method_number == HTP_M_CONNECT) { /* any 2XX status response implies that the connection will become a tunnel immediately after this packet (RFC 7230, 3.3.3). */ - if ((tx->response_status_number >= 200) && - (tx->response_status_number < 300) && + if ((tx->response_status_number >= 200) && (tx->response_status_number < 300) && (hstate->transaction_cnt == 1)) { uint16_t dp = 0; if (tx->request_port_number != -1) { @@ -2375,14 +2347,13 @@ static int HTPCallbackDoubleDecodeUriPart(htp_tx_t *tx, bstr *part) htp_status_t res = htp_urldecode_inplace(tx->cfg, HTP_DECODER_URLENCODED, part, &flags); // shorter string means that uri was encoded if (res == HTP_OK && prevlen > bstr_len(part)) { - HtpTxUserData *htud = (HtpTxUserData *) htp_tx_get_user_data(tx); + HtpTxUserData *htud = (HtpTxUserData *)htp_tx_get_user_data(tx); if (htud == NULL) return HTP_OK; HtpState *s = htp_connp_get_user_data(tx->connp); if (s == NULL) return HTP_OK; - HTPSetEvent(s, htud, STREAM_TOSERVER, - HTTP_DECODER_EVENT_DOUBLE_ENCODED_URI); + HTPSetEvent(s, htud, STREAM_TOSERVER, HTTP_DECODER_EVENT_DOUBLE_ENCODED_URI); } return HTP_OK; @@ -2414,16 +2385,15 @@ static int HTPCallbackRequestHeaderData(htp_tx_data_t *tx_data) if (tx_ud == NULL) { return HTP_OK; } - ptmp = HTPRealloc(tx_ud->request_headers_raw, - tx_ud->request_headers_raw_len, - tx_ud->request_headers_raw_len + tx_data->len); + ptmp = HTPRealloc(tx_ud->request_headers_raw, tx_ud->request_headers_raw_len, + tx_ud->request_headers_raw_len + tx_data->len); if (ptmp == NULL) { return HTP_OK; } tx_ud->request_headers_raw = ptmp; - memcpy(tx_ud->request_headers_raw + tx_ud->request_headers_raw_len, - tx_data->data, tx_data->len); + memcpy(tx_ud->request_headers_raw + tx_ud->request_headers_raw_len, tx_data->data, + tx_data->len); tx_ud->request_headers_raw_len += tx_data->len; if (tx_data->tx && tx_data->tx->flags) { @@ -2443,16 +2413,15 @@ static int HTPCallbackResponseHeaderData(htp_tx_data_t *tx_data) if (tx_ud == NULL) { return HTP_OK; } - ptmp = HTPRealloc(tx_ud->response_headers_raw, - tx_ud->response_headers_raw_len, - tx_ud->response_headers_raw_len + tx_data->len); + ptmp = HTPRealloc(tx_ud->response_headers_raw, tx_ud->response_headers_raw_len, + tx_ud->response_headers_raw_len + tx_data->len); if (ptmp == NULL) { return HTP_OK; } tx_ud->response_headers_raw = ptmp; - memcpy(tx_ud->response_headers_raw + tx_ud->response_headers_raw_len, - tx_data->data, tx_data->len); + memcpy(tx_ud->response_headers_raw + tx_ud->response_headers_raw_len, tx_data->data, + tx_data->len); tx_ud->response_headers_raw_len += tx_data->len; return HTP_OK; @@ -2506,12 +2475,10 @@ static void HTPConfigSetDefaultsPhase1(HTPCfgRec *cfg_prec) htp_config_set_lzma_layers(cfg_prec->cfg, HTP_CONFIG_DEFAULT_LZMA_LAYERS); #endif #ifdef HAVE_HTP_CONFIG_SET_LZMA_MEMLIMIT - htp_config_set_lzma_memlimit(cfg_prec->cfg, - HTP_CONFIG_DEFAULT_LZMA_MEMLIMIT); + htp_config_set_lzma_memlimit(cfg_prec->cfg, HTP_CONFIG_DEFAULT_LZMA_MEMLIMIT); #endif #ifdef HAVE_HTP_CONFIG_SET_COMPRESSION_BOMB_LIMIT - htp_config_set_compression_bomb_limit(cfg_prec->cfg, - HTP_CONFIG_DEFAULT_COMPRESSION_BOMB_LIMIT); + htp_config_set_compression_bomb_limit(cfg_prec->cfg, HTP_CONFIG_DEFAULT_COMPRESSION_BOMB_LIMIT); #endif #ifdef HAVE_HTP_CONFIG_SET_COMPRESSION_TIME_LIMIT htp_config_set_compression_time_limit(cfg_prec->cfg, HTP_CONFIG_DEFAULT_COMPRESSION_TIME_LIMIT); @@ -2522,8 +2489,7 @@ static void HTPConfigSetDefaultsPhase1(HTPCfgRec *cfg_prec) * config, we have to set the soft limit as well. If libhtp starts using * the soft limit in the future, we at least make sure we control what * it's value is. */ - htp_config_set_field_limits(cfg_prec->cfg, - (size_t)HTP_CONFIG_DEFAULT_FIELD_LIMIT_SOFT, + htp_config_set_field_limits(cfg_prec->cfg, (size_t)HTP_CONFIG_DEFAULT_FIELD_LIMIT_SOFT, (size_t)HTP_CONFIG_DEFAULT_FIELD_LIMIT_HARD); return; } @@ -2537,7 +2503,7 @@ static int RandomGetWrap(void) do { r = RandomGet(); - } while(r >= ULONG_MAX - (ULONG_MAX % RAND_MAX)); + } while (r >= ULONG_MAX - (ULONG_MAX % RAND_MAX)); return r % RAND_MAX; } @@ -2584,8 +2550,7 @@ static void HTPConfigSetDefaultsPhase2(const char *name, HTPCfgRec *cfg_prec) return; } -static void HTPConfigParseParameters(HTPCfgRec *cfg_prec, ConfNode *s, - SCRadixTree *tree) +static void HTPConfigParseParameters(HTPCfgRec *cfg_prec, ConfNode *s, SCRadixTree *tree) { if (cfg_prec == NULL || s == NULL || tree == NULL) return; @@ -2593,34 +2558,33 @@ static void HTPConfigParseParameters(HTPCfgRec *cfg_prec, ConfNode *s, ConfNode *p = NULL; /* Default Parameters */ - TAILQ_FOREACH(p, &s->head, next) { + TAILQ_FOREACH (p, &s->head, next) { if (strcasecmp("address", p->name) == 0) { ConfNode *pval; /* Addresses */ - TAILQ_FOREACH(pval, &p->head, next) { - SCLogDebug("LIBHTP server %s: %s=%s", s->name, p->name, - pval->val); + TAILQ_FOREACH (pval, &p->head, next) { + SCLogDebug("LIBHTP server %s: %s=%s", s->name, p->name, pval->val); /* IPV6 or IPV4? */ if (strchr(pval->val, ':') != NULL) { - SCLogDebug("LIBHTP adding ipv6 server %s at %s: %p", - s->name, pval->val, cfg_prec->cfg); + SCLogDebug("LIBHTP adding ipv6 server %s at %s: %p", s->name, pval->val, + cfg_prec->cfg); if (!SCRadixAddKeyIPV6String(pval->val, tree, cfg_prec)) { SCLogWarning("LIBHTP failed to " "add ipv6 server %s, ignoring", pval->val); } } else { - SCLogDebug("LIBHTP adding ipv4 server %s at %s: %p", - s->name, pval->val, cfg_prec->cfg); + SCLogDebug("LIBHTP adding ipv4 server %s at %s: %p", s->name, pval->val, + cfg_prec->cfg); if (!SCRadixAddKeyIPV4String(pval->val, tree, cfg_prec)) { SCLogWarning("LIBHTP failed " "to add ipv4 server %s, ignoring", pval->val); } } /* else - if (strchr(pval->val, ':') != NULL) */ - } /* TAILQ_FOREACH(pval, &p->head, next) */ + } /* TAILQ_FOREACH(pval, &p->head, next) */ } else if (strcasecmp("personality", p->name) == 0) { /* Personalities */ @@ -2629,15 +2593,14 @@ static void HTPConfigParseParameters(HTPCfgRec *cfg_prec, ConfNode *s, SCLogDebug("LIBHTP default: %s = %s", p->name, p->val); if (personality >= 0) { - SCLogDebug("LIBHTP default: %s=%s (%d)", p->name, p->val, - personality); - if (htp_config_set_server_personality(cfg_prec->cfg, personality) == HTP_ERROR){ + SCLogDebug("LIBHTP default: %s=%s (%d)", p->name, p->val, personality); + if (htp_config_set_server_personality(cfg_prec->cfg, personality) == HTP_ERROR) { SCLogWarning("LIBHTP Failed adding " "personality \"%s\", ignoring", p->val); } else { SCLogDebug("LIBHTP personality set to %s", - HTPLookupPersonalityString(personality)); + HTPLookupPersonalityString(personality)); } /* The IDS personality by default converts the path (and due to @@ -2686,14 +2649,12 @@ static void HTPConfigParseParameters(HTPCfgRec *cfg_prec, ConfNode *s, } else if (strcasecmp("double-decode-query", p->name) == 0) { if (ConfValIsTrue(p->val)) { - htp_config_register_request_line(cfg_prec->cfg, - HTPCallbackDoubleDecodeQuery); + htp_config_register_request_line(cfg_prec->cfg, HTPCallbackDoubleDecodeQuery); } } else if (strcasecmp("double-decode-path", p->name) == 0) { if (ConfValIsTrue(p->val)) { - htp_config_register_request_line(cfg_prec->cfg, - HTPCallbackDoubleDecodePath); + htp_config_register_request_line(cfg_prec->cfg, HTPCallbackDoubleDecodePath); } } else if (strcasecmp("response-body-minimal-inspect-size", p->name) == 0) { @@ -2728,42 +2689,34 @@ static void HTPConfigParseParameters(HTPCfgRec *cfg_prec, ConfNode *s, value); #endif } else if (strcasecmp("path-convert-backslash-separators", p->name) == 0) { - htp_config_set_backslash_convert_slashes(cfg_prec->cfg, - HTP_DECODER_URL_PATH, - ConfValIsTrue(p->val)); + htp_config_set_backslash_convert_slashes( + cfg_prec->cfg, HTP_DECODER_URL_PATH, ConfValIsTrue(p->val)); } else if (strcasecmp("path-bestfit-replacement-char", p->name) == 0) { if (strlen(p->val) == 1) { - htp_config_set_bestfit_replacement_byte(cfg_prec->cfg, - HTP_DECODER_URL_PATH, - p->val[0]); + htp_config_set_bestfit_replacement_byte( + cfg_prec->cfg, HTP_DECODER_URL_PATH, p->val[0]); } else { SCLogError("Invalid entry " "for libhtp param path-bestfit-replacement-char"); } } else if (strcasecmp("path-convert-lowercase", p->name) == 0) { - htp_config_set_convert_lowercase(cfg_prec->cfg, - HTP_DECODER_URL_PATH, - ConfValIsTrue(p->val)); + htp_config_set_convert_lowercase( + cfg_prec->cfg, HTP_DECODER_URL_PATH, ConfValIsTrue(p->val)); } else if (strcasecmp("path-nul-encoded-terminates", p->name) == 0) { - htp_config_set_nul_encoded_terminates(cfg_prec->cfg, - HTP_DECODER_URL_PATH, - ConfValIsTrue(p->val)); + htp_config_set_nul_encoded_terminates( + cfg_prec->cfg, HTP_DECODER_URL_PATH, ConfValIsTrue(p->val)); } else if (strcasecmp("path-nul-raw-terminates", p->name) == 0) { - htp_config_set_nul_raw_terminates(cfg_prec->cfg, - HTP_DECODER_URL_PATH, - ConfValIsTrue(p->val)); + htp_config_set_nul_raw_terminates( + cfg_prec->cfg, HTP_DECODER_URL_PATH, ConfValIsTrue(p->val)); } else if (strcasecmp("path-separators-compress", p->name) == 0) { - htp_config_set_path_separators_compress(cfg_prec->cfg, - HTP_DECODER_URL_PATH, - ConfValIsTrue(p->val)); + htp_config_set_path_separators_compress( + cfg_prec->cfg, HTP_DECODER_URL_PATH, ConfValIsTrue(p->val)); } else if (strcasecmp("path-separators-decode", p->name) == 0) { - htp_config_set_path_separators_decode(cfg_prec->cfg, - HTP_DECODER_URL_PATH, - ConfValIsTrue(p->val)); + htp_config_set_path_separators_decode( + cfg_prec->cfg, HTP_DECODER_URL_PATH, ConfValIsTrue(p->val)); } else if (strcasecmp("path-u-encoding-decode", p->name) == 0) { - htp_config_set_u_encoding_decode(cfg_prec->cfg, - HTP_DECODER_URL_PATH, - ConfValIsTrue(p->val)); + htp_config_set_u_encoding_decode( + cfg_prec->cfg, HTP_DECODER_URL_PATH, ConfValIsTrue(p->val)); } else if (strcasecmp("path-url-encoding-invalid-handling", p->name) == 0) { enum htp_url_encoding_handling_t handling; if (strcasecmp(p->val, "preserve_percent") == 0) { @@ -2777,21 +2730,17 @@ static void HTPConfigParseParameters(HTPCfgRec *cfg_prec, ConfNode *s, "for libhtp param path-url-encoding-invalid-handling"); return; } - htp_config_set_url_encoding_invalid_handling(cfg_prec->cfg, - HTP_DECODER_URL_PATH, - handling); + htp_config_set_url_encoding_invalid_handling( + cfg_prec->cfg, HTP_DECODER_URL_PATH, handling); } else if (strcasecmp("path-utf8-convert-bestfit", p->name) == 0) { - htp_config_set_utf8_convert_bestfit(cfg_prec->cfg, - HTP_DECODER_URL_PATH, - ConfValIsTrue(p->val)); + htp_config_set_utf8_convert_bestfit( + cfg_prec->cfg, HTP_DECODER_URL_PATH, ConfValIsTrue(p->val)); } else if (strcasecmp("uri-include-all", p->name) == 0) { cfg_prec->uri_include_all = (1 == ConfValIsTrue(p->val)); - SCLogDebug("uri-include-all %s", - cfg_prec->uri_include_all ? "enabled" : "disabled"); + SCLogDebug("uri-include-all %s", cfg_prec->uri_include_all ? "enabled" : "disabled"); } else if (strcasecmp("query-plusspace-decode", p->name) == 0) { - htp_config_set_plusspace_decode(cfg_prec->cfg, - HTP_DECODER_URLENCODED, - ConfValIsTrue(p->val)); + htp_config_set_plusspace_decode( + cfg_prec->cfg, HTP_DECODER_URLENCODED, ConfValIsTrue(p->val)); } else if (strcasecmp("meta-field-limit", p->name) == 0) { uint32_t limit = 0; if (ParseSizeStringU32(p->val, &limit) < 0) { @@ -2805,9 +2754,8 @@ static void HTPConfigParseParameters(HTPCfgRec *cfg_prec, ConfNode *s, "from conf file cannot be 0. Killing engine"); } /* set default soft-limit with our new hard limit */ - htp_config_set_field_limits(cfg_prec->cfg, - (size_t)HTP_CONFIG_DEFAULT_FIELD_LIMIT_SOFT, - (size_t)limit); + htp_config_set_field_limits( + cfg_prec->cfg, (size_t)HTP_CONFIG_DEFAULT_FIELD_LIMIT_SOFT, (size_t)limit); #ifdef HAVE_HTP_CONFIG_SET_LZMA_MEMLIMIT } else if (strcasecmp("lzma-memlimit", p->name) == 0) { uint32_t limit = 0; @@ -2821,7 +2769,7 @@ static void HTPConfigParseParameters(HTPCfgRec *cfg_prec, ConfNode *s, "from conf file cannot be 0."); } /* set default soft-limit with our new hard limit */ - SCLogConfig("Setting HTTP LZMA memory limit to %"PRIu32" bytes", limit); + SCLogConfig("Setting HTTP LZMA memory limit to %" PRIu32 " bytes", limit); htp_config_set_lzma_memlimit(cfg_prec->cfg, (size_t)limit); #endif #ifdef HAVE_HTP_CONFIG_SET_LZMA_LAYERS @@ -2852,7 +2800,7 @@ static void HTPConfigParseParameters(HTPCfgRec *cfg_prec, ConfNode *s, "from conf file cannot be 0."); } /* set default soft-limit with our new hard limit */ - SCLogConfig("Setting HTTP compression bomb limit to %"PRIu32" bytes", limit); + SCLogConfig("Setting HTTP compression bomb limit to %" PRIu32 " bytes", limit); htp_config_set_compression_bomb_limit(cfg_prec->cfg, (size_t)limit); #endif #ifdef HAVE_HTP_CONFIG_SET_COMPRESSION_TIME_LIMIT @@ -2873,8 +2821,7 @@ static void HTPConfigParseParameters(HTPCfgRec *cfg_prec, ConfNode *s, } } else if (strcasecmp("randomize-inspection-range", p->name) == 0) { uint32_t range; - if (StringParseU32RangeCheck(&range, 10, 0, - (const char *)p->val, 0, 100) < 0) { + if (StringParseU32RangeCheck(&range, 10, 0, (const char *)p->val, 0, 100) < 0) { SCLogError("Invalid value for randomize" "-inspection-range setting from conf file - \"%s\"." " It should be a valid integer less than or equal to 100." @@ -2901,7 +2848,7 @@ static void HTPConfigParseParameters(HTPCfgRec *cfg_prec, ConfNode *s, } else if (strcasecmp("swf-decompression", p->name) == 0) { ConfNode *pval; - TAILQ_FOREACH(pval, &p->head, next) { + TAILQ_FOREACH (pval, &p->head, next) { if (strcasecmp("enabled", pval->name) == 0) { if (ConfValIsTrue(pval->val)) { cfg_prec->swf_decompression_enabled = 1; @@ -2978,10 +2925,10 @@ void HTPConfigure(void) SCLogDebug("LIBHTP default config: %p", cfglist.cfg); HTPConfigSetDefaultsPhase1(&cfglist); if (ConfGetNode("app-layer.protocols.http.libhtp") == NULL) { - HTPConfigParseParameters(&cfglist, ConfGetNode("libhtp.default-config"), - cfgtree); + HTPConfigParseParameters(&cfglist, ConfGetNode("libhtp.default-config"), cfgtree); } else { - HTPConfigParseParameters(&cfglist, ConfGetNode("app-layer.protocols.http.libhtp.default-config"), cfgtree); + HTPConfigParseParameters( + &cfglist, ConfGetNode("app-layer.protocols.http.libhtp.default-config"), cfgtree); } HTPConfigSetDefaultsPhase2("default", &cfglist); @@ -3000,7 +2947,7 @@ void HTPConfigure(void) ConfNode *si; /* Server Nodes */ - TAILQ_FOREACH(si, &server_config->head, next) { + TAILQ_FOREACH (si, &server_config->head, next) { /* Need the named node, not the index */ ConfNode *s = TAILQ_FIRST(&si->head); if (NULL == s) { @@ -3035,7 +2982,7 @@ void AppLayerHtpPrintStats(void) { #ifdef DEBUG SCMutexLock(&htp_state_mem_lock); - SCLogPerf("htp memory %"PRIu64" (%"PRIu64")", htp_state_memuse, htp_state_memcnt); + SCLogPerf("htp memory %" PRIu64 " (%" PRIu64 ")", htp_state_memuse, htp_state_memcnt); SCMutexUnlock(&htp_state_mem_lock); #endif } @@ -3077,7 +3024,7 @@ static uint64_t HTPStateGetTxCnt(void *alstate) const int64_t size = (int64_t)htp_list_size(http_state->conn->transactions); if (size < 0) return 0ULL; - SCLogDebug("size %"PRIu64, size); + SCLogDebug("size %" PRIu64, size); return (uint64_t)size; } else { return 0ULL; @@ -3107,8 +3054,8 @@ void *HtpGetTxForH2(void *alstate) return NULL; } -static int HTPStateGetEventInfo(const char *event_name, - int *event_id, AppLayerEventType *event_type) +static int HTPStateGetEventInfo( + const char *event_name, int *event_id, AppLayerEventType *event_type) { *event_id = SCMapEnumNameToValue(event_name, http_decoder_event_table); if (*event_id == -1) { @@ -3124,8 +3071,8 @@ static int HTPStateGetEventInfo(const char *event_name, return 0; } -static int HTPStateGetEventInfoById(int event_id, const char **event_name, - AppLayerEventType *event_type) +static int HTPStateGetEventInfoById( + int event_id, const char **event_name, AppLayerEventType *event_type) { *event_name = SCMapEnumValueToName(event_id, http_decoder_event_table); if (*event_name == NULL) { @@ -3159,11 +3106,10 @@ static AppLayerStateData *HTPGetStateData(void *vstate) static int HTPRegisterPatternsForProtocolDetection(void) { - const char *methods[] = { "GET", "PUT", "POST", "HEAD", "TRACE", "OPTIONS", - "CONNECT", "DELETE", "PATCH", "PROPFIND", "PROPPATCH", "MKCOL", - "COPY", "MOVE", "LOCK", "UNLOCK", "CHECKOUT", "UNCHECKOUT", "CHECKIN", - "UPDATE", "LABEL", "REPORT", "MKWORKSPACE", "MKACTIVITY", "MERGE", - "INVALID", "VERSION-CONTROL", "BASELINE-CONTROL", NULL}; + const char *methods[] = { "GET", "PUT", "POST", "HEAD", "TRACE", "OPTIONS", "CONNECT", "DELETE", + "PATCH", "PROPFIND", "PROPPATCH", "MKCOL", "COPY", "MOVE", "LOCK", "UNLOCK", "CHECKOUT", + "UNCHECKOUT", "CHECKIN", "UPDATE", "LABEL", "REPORT", "MKWORKSPACE", "MKACTIVITY", "MERGE", + "INVALID", "VERSION-CONTROL", "BASELINE-CONTROL", NULL }; const char *spacings[] = { "|20|", "|09|", NULL }; const char *versions[] = { "HTTP/0.9", "HTTP/1.0", "HTTP/1.1", NULL }; @@ -3178,12 +3124,13 @@ static int HTPRegisterPatternsForProtocolDetection(void) for (spacings_pos = 0; spacings[spacings_pos]; spacings_pos++) { /* Combine the method name and the spacing */ - snprintf(method_buffer, sizeof(method_buffer), "%s%s", methods[methods_pos], spacings[spacings_pos]); + snprintf(method_buffer, sizeof(method_buffer), "%s%s", methods[methods_pos], + spacings[spacings_pos]); /* Register the new method+spacing pattern * 3 is subtracted from the length since the spacing is hex typed as |xx| * but the pattern matching should only be one char - */ + */ register_result = AppLayerProtoDetectPMRegisterPatternCI(IPPROTO_TCP, ALPROTO_HTTP1, method_buffer, (uint16_t)strlen(method_buffer) - 3, 0, STREAM_TOSERVER); if (register_result < 0) { @@ -3221,8 +3168,7 @@ void RegisterHTPParsers(void) if (HTPRegisterPatternsForProtocolDetection() < 0) return; } else { - SCLogInfo("Protocol detection and parser disabled for %s protocol", - proto_name); + SCLogInfo("Protocol detection and parser disabled for %s protocol", proto_name); return; } @@ -3264,7 +3210,8 @@ void RegisterHTPParsers(void) HTPConfigure(); } else { SCLogInfo("Parsed disabled for %s protocol. Protocol detection" - "still on.", proto_name); + "still on.", + proto_name); } #ifdef UNITTESTS AppLayerParserRegisterProtocolUnittests(IPPROTO_TCP, ALPROTO_HTTP1, HTPParserRegisterTests); @@ -3319,9 +3266,9 @@ static int HTPParserTest01(void) uint8_t flags = 0; if (u == 0) - flags = STREAM_TOSERVER|STREAM_START; + flags = STREAM_TOSERVER | STREAM_START; else if (u == (httplen1 - 1)) - flags = STREAM_TOSERVER|STREAM_EOF; + flags = STREAM_TOSERVER | STREAM_EOF; else flags = STREAM_TOSERVER; @@ -3335,7 +3282,7 @@ static int HTPParserTest01(void) htp_tx_t *tx = HTPStateGetTx(htp_state, 0); FAIL_IF_NULL(tx); - htp_header_t *h = htp_table_get_index(tx->request_headers, 0, NULL); + htp_header_t *h = htp_table_get_index(tx->request_headers, 0, NULL); FAIL_IF_NULL(h); FAIL_IF(strcmp(bstr_util_strdup_to_c(h->value), "Victor/1.0")); @@ -3369,7 +3316,7 @@ static int HTPParserTest01b(void) StreamTcpInitConfig(true); - uint8_t flags =STREAM_TOSERVER|STREAM_START|STREAM_EOF; + uint8_t flags = STREAM_TOSERVER | STREAM_START | STREAM_EOF; int r = AppLayerParserParse(NULL, alp_tctx, f, ALPROTO_HTTP1, flags, httpbuf1, httplen1); FAIL_IF(r != 0); @@ -3379,7 +3326,7 @@ static int HTPParserTest01b(void) htp_tx_t *tx = HTPStateGetTx(htp_state, 0); FAIL_IF_NULL(tx); - htp_header_t *h = htp_table_get_index(tx->request_headers, 0, NULL); + htp_header_t *h = htp_table_get_index(tx->request_headers, 0, NULL); FAIL_IF_NULL(h); FAIL_IF(strcmp(bstr_util_strdup_to_c(h->value), "Victor/1.0")); @@ -3418,9 +3365,9 @@ static int HTPParserTest01c(void) uint8_t flags = 0; if (u == 0) - flags = STREAM_TOSERVER|STREAM_START; + flags = STREAM_TOSERVER | STREAM_START; else if (u == (httplen1 - 1)) - flags = STREAM_TOSERVER|STREAM_EOF; + flags = STREAM_TOSERVER | STREAM_EOF; else flags = STREAM_TOSERVER; @@ -3434,7 +3381,7 @@ static int HTPParserTest01c(void) htp_tx_t *tx = HTPStateGetTx(htp_state, 0); FAIL_IF_NULL(tx); - htp_header_t *h = htp_table_get_index(tx->request_headers, 0, NULL); + htp_header_t *h = htp_table_get_index(tx->request_headers, 0, NULL); FAIL_IF_NULL(h); FAIL_IF(strcmp(bstr_util_strdup_to_c(h->value), "Victor/1.0")); @@ -3457,7 +3404,7 @@ static int HTPParserTest01a(void) " Data is c0oL!"; uint32_t httplen1 = sizeof(httpbuf1) - 1; /* minus the \0 */ TcpSession ssn; - HtpState *htp_state = NULL; + HtpState *htp_state = NULL; int r = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -3477,16 +3424,17 @@ static int HTPParserTest01a(void) uint8_t flags = 0; if (u == 0) - flags = STREAM_TOSERVER|STREAM_START; + flags = STREAM_TOSERVER | STREAM_START; else if (u == (httplen1 - 1)) - flags = STREAM_TOSERVER|STREAM_EOF; + flags = STREAM_TOSERVER | STREAM_EOF; else flags = STREAM_TOSERVER; r = AppLayerParserParse(NULL, alp_tctx, f, ALPROTO_HTTP1, flags, &httpbuf1[u], 1); if (r != 0) { printf("toserver chunk %" PRIu32 " returned %" PRId32 ", expected" - " 0: ", u, r); + " 0: ", + u, r); goto end; } } @@ -3498,15 +3446,14 @@ static int HTPParserTest01a(void) } htp_tx_t *tx = HTPStateGetTx(htp_state, 0); - htp_header_t *h = htp_table_get_index(tx->request_headers, 0, NULL); - if (strcmp(bstr_util_strdup_to_c(h->value), "Victor/1.0") - || tx->request_method_number != HTP_M_POST || - tx->request_protocol_number != HTP_PROTOCOL_1_0) - { + htp_header_t *h = htp_table_get_index(tx->request_headers, 0, NULL); + if (strcmp(bstr_util_strdup_to_c(h->value), "Victor/1.0") || + tx->request_method_number != HTP_M_POST || + tx->request_protocol_number != HTP_PROTOCOL_1_0) { printf("expected header value: Victor/1.0 and got %s: and expected" - " method: POST and got %s, expected protocol number HTTP/1.0" - " and got: %s \n", bstr_util_strdup_to_c(h->value), - bstr_util_strdup_to_c(tx->request_method), + " method: POST and got %s, expected protocol number HTTP/1.0" + " and got: %s \n", + bstr_util_strdup_to_c(h->value), bstr_util_strdup_to_c(tx->request_method), bstr_util_strdup_to_c(tx->request_protocol)); goto end; } @@ -3556,7 +3503,7 @@ static int HTPParserTest02(void) htp_tx_t *tx = HTPStateGetTx(http_state, 0); FAIL_IF_NULL(tx); - htp_header_t *h = htp_table_get_index(tx->request_headers, 0, NULL); + htp_header_t *h = htp_table_get_index(tx->request_headers, 0, NULL); FAIL_IF_NOT_NULL(h); FAIL_IF_NULL(tx->request_method); @@ -3584,7 +3531,7 @@ static int HTPParserTest03(void) uint8_t httpbuf1[] = "HELLO / HTTP/1.0\r\n"; uint32_t httplen1 = sizeof(httpbuf1) - 1; /* minus the \0 */ TcpSession ssn; - HtpState *htp_state = NULL; + HtpState *htp_state = NULL; int r = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -3603,14 +3550,18 @@ static int HTPParserTest03(void) for (u = 0; u < httplen1; u++) { uint8_t flags = 0; - if (u == 0) flags = STREAM_TOSERVER|STREAM_START; - else if (u == (httplen1 - 1)) flags = STREAM_TOSERVER|STREAM_EOF; - else flags = STREAM_TOSERVER; + if (u == 0) + flags = STREAM_TOSERVER | STREAM_START; + else if (u == (httplen1 - 1)) + flags = STREAM_TOSERVER | STREAM_EOF; + else + flags = STREAM_TOSERVER; r = AppLayerParserParse(NULL, alp_tctx, f, ALPROTO_HTTP1, flags, &httpbuf1[u], 1); if (r != 0) { printf("toserver chunk %" PRIu32 " returned %" PRId32 ", expected" - " 0: ", u, r); + " 0: ", + u, r); goto end; } } @@ -3622,12 +3573,12 @@ static int HTPParserTest03(void) htp_tx_t *tx = HTPStateGetTx(htp_state, 0); - htp_header_t *h = htp_table_get_index(tx->request_headers, 0, NULL); - if (tx->request_method_number != HTP_M_UNKNOWN || - h != NULL || tx->request_protocol_number != HTP_PROTOCOL_1_0) - { + htp_header_t *h = htp_table_get_index(tx->request_headers, 0, NULL); + if (tx->request_method_number != HTP_M_UNKNOWN || h != NULL || + tx->request_protocol_number != HTP_PROTOCOL_1_0) { printf("expected method M_UNKNOWN and got %s: , expected protocol " - "HTTP/1.0 and got %s \n", bstr_util_strdup_to_c(tx->request_method), + "HTTP/1.0 and got %s \n", + bstr_util_strdup_to_c(tx->request_method), bstr_util_strdup_to_c(tx->request_protocol)); goto end; } @@ -3677,12 +3628,12 @@ static int HTPParserTest04(void) } htp_tx_t *tx = HTPStateGetTx(htp_state, 0); - htp_header_t *h = htp_table_get_index(tx->request_headers, 0, NULL); - if (tx->request_method_number != HTP_M_UNKNOWN || - h != NULL || tx->request_protocol_number != HTP_PROTOCOL_0_9) - { + htp_header_t *h = htp_table_get_index(tx->request_headers, 0, NULL); + if (tx->request_method_number != HTP_M_UNKNOWN || h != NULL || + tx->request_protocol_number != HTP_PROTOCOL_0_9) { printf("expected method M_UNKNOWN and got %s: , expected protocol " - "NULL and got %s \n", bstr_util_strdup_to_c(tx->request_method), + "NULL and got %s \n", + bstr_util_strdup_to_c(tx->request_method), bstr_util_strdup_to_c(tx->request_protocol)); goto end; } @@ -3757,7 +3708,7 @@ static int HTPParserTest05(void) FAIL_IF_NOT(tx->request_method_number == HTP_M_POST); FAIL_IF_NOT(tx->request_protocol_number == HTP_PROTOCOL_1_0); - htp_header_t *h = htp_table_get_index(tx->request_headers, 0, NULL); + htp_header_t *h = htp_table_get_index(tx->request_headers, 0, NULL); FAIL_IF_NULL(h); FAIL_IF_NOT(tx->response_status_number == 200); @@ -3848,7 +3799,7 @@ static int HTPParserTest06(void) FAIL_IF(tx->response_status_number != 200); FAIL_IF(tx->request_protocol_number != HTP_PROTOCOL_1_1); - htp_header_t *h = htp_table_get_index(tx->request_headers, 0, NULL); + htp_header_t *h = htp_table_get_index(tx->request_headers, 0, NULL); FAIL_IF_NULL(h); AppLayerParserThreadCtxFree(alp_tctx); @@ -3866,7 +3817,7 @@ static int HTPParserTest07(void) uint8_t httpbuf1[] = "GET /awstats.pl?/migratemigrate%20=%20| HTTP/1.0\r\n\r\n"; uint32_t httplen1 = sizeof(httpbuf1) - 1; /* minus the \0 */ TcpSession ssn; - HtpState *htp_state = NULL; + HtpState *htp_state = NULL; int r = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -3886,16 +3837,17 @@ static int HTPParserTest07(void) uint8_t flags = 0; if (u == 0) - flags = STREAM_TOSERVER|STREAM_START; + flags = STREAM_TOSERVER | STREAM_START; else if (u == (httplen1 - 1)) - flags = STREAM_TOSERVER|STREAM_EOF; + flags = STREAM_TOSERVER | STREAM_EOF; else flags = STREAM_TOSERVER; r = AppLayerParserParse(NULL, alp_tctx, f, ALPROTO_HTTP1, flags, &httpbuf1[u], 1); if (r != 0) { printf("toserver chunk %" PRIu32 " returned %" PRId32 ", expected" - " 0: ", u, r); + " 0: ", + u, r); goto end; } } @@ -3912,20 +3864,19 @@ static int HTPParserTest07(void) htp_tx_t *tx = HTPStateGetTx(htp_state, 0); if (tx == NULL) goto end; - HtpTxUserData *tx_ud = (HtpTxUserData *) htp_tx_get_user_data(tx); + HtpTxUserData *tx_ud = (HtpTxUserData *)htp_tx_get_user_data(tx); if (tx_ud != NULL && tx_ud->request_uri_normalized != NULL) { if (reflen != bstr_len(tx_ud->request_uri_normalized)) { - printf("normalized uri len should be %"PRIuMAX", is %"PRIuMAX, - (uintmax_t)reflen, - (uintmax_t)bstr_len(tx_ud->request_uri_normalized)); + printf("normalized uri len should be %" PRIuMAX ", is %" PRIuMAX, (uintmax_t)reflen, + (uintmax_t)bstr_len(tx_ud->request_uri_normalized)); goto end; } if (memcmp(bstr_ptr(tx_ud->request_uri_normalized), ref, - bstr_len(tx_ud->request_uri_normalized)) != 0) - { + bstr_len(tx_ud->request_uri_normalized)) != 0) { printf("normalized uri \""); - PrintRawUriFp(stdout, bstr_ptr(tx_ud->request_uri_normalized), bstr_len(tx_ud->request_uri_normalized)); + PrintRawUriFp(stdout, bstr_ptr(tx_ud->request_uri_normalized), + bstr_len(tx_ud->request_uri_normalized)); printf("\" != \""); PrintRawUriFp(stdout, ref, reflen); printf("\": "); @@ -3950,7 +3901,8 @@ static int HTPParserTest08(void) { int result = 0; Flow *f = NULL; - uint8_t httpbuf1[] = "GET /secondhouse/image/js/\%ce\%de\%ce\%fd_RentCity.js?v=2011.05.02 HTTP/1.0\r\n\r\n"; + uint8_t httpbuf1[] = + "GET /secondhouse/image/js/\%ce\%de\%ce\%fd_RentCity.js?v=2011.05.02 HTTP/1.0\r\n\r\n"; uint32_t httplen1 = sizeof(httpbuf1) - 1; /* minus the \0 */ TcpSession ssn; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -3971,7 +3923,7 @@ libhtp:\n\ ConfYamlLoadString(input, strlen(input)); HTPConfigure(); - HtpState *htp_state = NULL; + HtpState *htp_state = NULL; int r = 0; memset(&ssn, 0, sizeof(ssn)); @@ -3985,12 +3937,13 @@ libhtp:\n\ StreamTcpInitConfig(true); uint8_t flags = 0; - flags = STREAM_TOSERVER|STREAM_START|STREAM_EOF; + flags = STREAM_TOSERVER | STREAM_START | STREAM_EOF; r = AppLayerParserParse(NULL, alp_tctx, f, ALPROTO_HTTP1, flags, httpbuf1, httplen1); if (r != 0) { printf("toserver chunk returned %" PRId32 ", expected" - " 0: ", r); + " 0: ", + r); result = 0; goto end; } @@ -4005,11 +3958,11 @@ libhtp:\n\ htp_tx_t *tx = HTPStateGetTx(htp_state, 0); if (tx == NULL) goto end; - HtpTxUserData *tx_ud = (HtpTxUserData *) htp_tx_get_user_data(tx); + HtpTxUserData *tx_ud = (HtpTxUserData *)htp_tx_get_user_data(tx); if (tx_ud != NULL && tx_ud->request_uri_normalized != NULL) { - //printf("uri %s\n", bstr_util_strdup_to_c(tx->request_uri_normalized)); + // printf("uri %s\n", bstr_util_strdup_to_c(tx->request_uri_normalized)); PrintRawDataFp(stdout, bstr_ptr(tx_ud->request_uri_normalized), - bstr_len(tx_ud->request_uri_normalized)); + bstr_len(tx_ud->request_uri_normalized)); } result = 1; @@ -4031,7 +3984,8 @@ static int HTPParserTest09(void) { int result = 0; Flow *f = NULL; - uint8_t httpbuf1[] = "GET /secondhouse/image/js/\%ce\%de\%ce\%fd_RentCity.js?v=2011.05.02 HTTP/1.0\r\n\r\n"; + uint8_t httpbuf1[] = + "GET /secondhouse/image/js/\%ce\%de\%ce\%fd_RentCity.js?v=2011.05.02 HTTP/1.0\r\n\r\n"; uint32_t httplen1 = sizeof(httpbuf1) - 1; /* minus the \0 */ TcpSession ssn; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -4052,7 +4006,7 @@ libhtp:\n\ ConfYamlLoadString(input, strlen(input)); HTPConfigure(); - HtpState *htp_state = NULL; + HtpState *htp_state = NULL; int r = 0; memset(&ssn, 0, sizeof(ssn)); @@ -4067,12 +4021,13 @@ libhtp:\n\ StreamTcpInitConfig(true); uint8_t flags = 0; - flags = STREAM_TOSERVER|STREAM_START|STREAM_EOF; + flags = STREAM_TOSERVER | STREAM_START | STREAM_EOF; r = AppLayerParserParse(NULL, alp_tctx, f, ALPROTO_HTTP1, flags, httpbuf1, httplen1); if (r != 0) { printf("toserver chunk returned %" PRId32 ", expected" - " 0: ", r); + " 0: ", + r); goto end; } @@ -4085,11 +4040,11 @@ libhtp:\n\ htp_tx_t *tx = HTPStateGetTx(htp_state, 0); if (tx == NULL) goto end; - HtpTxUserData *tx_ud = (HtpTxUserData *) htp_tx_get_user_data(tx); + HtpTxUserData *tx_ud = (HtpTxUserData *)htp_tx_get_user_data(tx); if (tx_ud != NULL && tx_ud->request_uri_normalized != NULL) { - //printf("uri %s\n", bstr_util_strdup_to_c(tx->request_uri_normalized)); + // printf("uri %s\n", bstr_util_strdup_to_c(tx->request_uri_normalized)); PrintRawDataFp(stdout, bstr_ptr(tx_ud->request_uri_normalized), - bstr_len(tx_ud->request_uri_normalized)); + bstr_len(tx_ud->request_uri_normalized)); } result = 1; @@ -4114,7 +4069,7 @@ static int HTPParserTest10(void) uint8_t httpbuf1[] = "GET / HTTP/1.0\r\nHost:www.google.com\r\n\r\n"; uint32_t httplen1 = sizeof(httpbuf1) - 1; /* minus the \0 */ TcpSession ssn; - HtpState *htp_state = NULL; + HtpState *htp_state = NULL; int r = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -4134,16 +4089,17 @@ static int HTPParserTest10(void) uint8_t flags = 0; if (u == 0) - flags = STREAM_TOSERVER|STREAM_START; + flags = STREAM_TOSERVER | STREAM_START; else if (u == (httplen1 - 1)) - flags = STREAM_TOSERVER|STREAM_EOF; + flags = STREAM_TOSERVER | STREAM_EOF; else flags = STREAM_TOSERVER; r = AppLayerParserParse(NULL, alp_tctx, f, ALPROTO_HTTP1, flags, &httpbuf1[u], 1); if (r != 0) { printf("toserver chunk %" PRIu32 " returned %" PRId32 ", expected" - " 0: ", u, r); + " 0: ", + u, r); goto end; } } @@ -4155,7 +4111,7 @@ static int HTPParserTest10(void) } htp_tx_t *tx = HTPStateGetTx(htp_state, 0); - htp_header_t *h = htp_table_get_index(tx->request_headers, 0, NULL); + htp_header_t *h = htp_table_get_index(tx->request_headers, 0, NULL); if (h == NULL) { goto end; } @@ -4202,7 +4158,7 @@ static int HTPParserTest11(void) uint8_t httpbuf1[] = "GET /%2500 HTTP/1.0\r\n\r\n"; uint32_t httplen1 = sizeof(httpbuf1) - 1; /* minus the \0 */ TcpSession ssn; - HtpState *htp_state = NULL; + HtpState *htp_state = NULL; int r = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -4222,16 +4178,17 @@ static int HTPParserTest11(void) uint8_t flags = 0; if (u == 0) - flags = STREAM_TOSERVER|STREAM_START; + flags = STREAM_TOSERVER | STREAM_START; else if (u == (httplen1 - 1)) - flags = STREAM_TOSERVER|STREAM_EOF; + flags = STREAM_TOSERVER | STREAM_EOF; else flags = STREAM_TOSERVER; r = AppLayerParserParse(NULL, alp_tctx, f, ALPROTO_HTTP1, flags, &httpbuf1[u], 1); if (r != 0) { printf("toserver chunk %" PRIu32 " returned %" PRId32 ", expected" - " 0: ", u, r); + " 0: ", + u, r); goto end; } } @@ -4248,18 +4205,18 @@ static int HTPParserTest11(void) HtpTxUserData *tx_ud = (HtpTxUserData *)htp_tx_get_user_data(tx); if (tx != NULL && tx_ud != NULL && tx_ud->request_uri_normalized != NULL) { if (4 != bstr_len(tx_ud->request_uri_normalized)) { - printf("normalized uri len should be 2, is %"PRIuMAX, - (uintmax_t)bstr_len(tx_ud->request_uri_normalized)); + printf("normalized uri len should be 2, is %" PRIuMAX, + (uintmax_t)bstr_len(tx_ud->request_uri_normalized)); goto end; } if (bstr_ptr(tx_ud->request_uri_normalized)[0] != '/' || - bstr_ptr(tx_ud->request_uri_normalized)[1] != '%' || - bstr_ptr(tx_ud->request_uri_normalized)[2] != '0' || - bstr_ptr(tx_ud->request_uri_normalized)[3] != '0') - { + bstr_ptr(tx_ud->request_uri_normalized)[1] != '%' || + bstr_ptr(tx_ud->request_uri_normalized)[2] != '0' || + bstr_ptr(tx_ud->request_uri_normalized)[3] != '0') { printf("normalized uri \""); - PrintRawUriFp(stdout, bstr_ptr(tx_ud->request_uri_normalized), bstr_len(tx_ud->request_uri_normalized)); + PrintRawUriFp(stdout, bstr_ptr(tx_ud->request_uri_normalized), + bstr_len(tx_ud->request_uri_normalized)); printf("\": "); goto end; } @@ -4283,7 +4240,7 @@ static int HTPParserTest12(void) uint8_t httpbuf1[] = "GET /?a=%2500 HTTP/1.0\r\n\r\n"; uint32_t httplen1 = sizeof(httpbuf1) - 1; /* minus the \0 */ TcpSession ssn; - HtpState *htp_state = NULL; + HtpState *htp_state = NULL; int r = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -4303,16 +4260,17 @@ static int HTPParserTest12(void) uint8_t flags = 0; if (u == 0) - flags = STREAM_TOSERVER|STREAM_START; + flags = STREAM_TOSERVER | STREAM_START; else if (u == (httplen1 - 1)) - flags = STREAM_TOSERVER|STREAM_EOF; + flags = STREAM_TOSERVER | STREAM_EOF; else flags = STREAM_TOSERVER; r = AppLayerParserParse(NULL, alp_tctx, f, ALPROTO_HTTP1, flags, &httpbuf1[u], 1); if (r != 0) { printf("toserver chunk %" PRIu32 " returned %" PRId32 ", expected" - " 0: ", u, r); + " 0: ", + u, r); goto end; } } @@ -4326,31 +4284,31 @@ static int HTPParserTest12(void) htp_tx_t *tx = HTPStateGetTx(htp_state, 0); if (tx == NULL) goto end; - HtpTxUserData *tx_ud = (HtpTxUserData *) htp_tx_get_user_data(tx); + HtpTxUserData *tx_ud = (HtpTxUserData *)htp_tx_get_user_data(tx); if (tx_ud != NULL && tx_ud->request_uri_normalized != NULL) { if (7 != bstr_len(tx_ud->request_uri_normalized)) { - printf("normalized uri len should be 5, is %"PRIuMAX, - (uintmax_t)bstr_len(tx_ud->request_uri_normalized)); + printf("normalized uri len should be 5, is %" PRIuMAX, + (uintmax_t)bstr_len(tx_ud->request_uri_normalized)); goto end; } if (bstr_ptr(tx_ud->request_uri_normalized)[0] != '/' || - bstr_ptr(tx_ud->request_uri_normalized)[1] != '?' || - bstr_ptr(tx_ud->request_uri_normalized)[2] != 'a' || - bstr_ptr(tx_ud->request_uri_normalized)[3] != '=' || - bstr_ptr(tx_ud->request_uri_normalized)[4] != '%' || - bstr_ptr(tx_ud->request_uri_normalized)[5] != '0' || - bstr_ptr(tx_ud->request_uri_normalized)[6] != '0') - { + bstr_ptr(tx_ud->request_uri_normalized)[1] != '?' || + bstr_ptr(tx_ud->request_uri_normalized)[2] != 'a' || + bstr_ptr(tx_ud->request_uri_normalized)[3] != '=' || + bstr_ptr(tx_ud->request_uri_normalized)[4] != '%' || + bstr_ptr(tx_ud->request_uri_normalized)[5] != '0' || + bstr_ptr(tx_ud->request_uri_normalized)[6] != '0') { printf("normalized uri \""); - PrintRawUriFp(stdout, bstr_ptr(tx_ud->request_uri_normalized), bstr_len(tx_ud->request_uri_normalized)); + PrintRawUriFp(stdout, bstr_ptr(tx_ud->request_uri_normalized), + bstr_len(tx_ud->request_uri_normalized)); printf("\": "); goto end; } } result = 1; - end: +end: if (alp_tctx != NULL) AppLayerParserThreadCtxFree(alp_tctx); StreamTcpFreeConfig(true); @@ -4367,7 +4325,7 @@ static int HTPParserTest13(void) uint8_t httpbuf1[] = "GET / HTTP/1.0\r\nHost:www.google.com\rName: Value\r\n\r\n"; uint32_t httplen1 = sizeof(httpbuf1) - 1; /* minus the \0 */ TcpSession ssn; - HtpState *htp_state = NULL; + HtpState *htp_state = NULL; int r = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -4387,16 +4345,17 @@ static int HTPParserTest13(void) uint8_t flags = 0; if (u == 0) - flags = STREAM_TOSERVER|STREAM_START; + flags = STREAM_TOSERVER | STREAM_START; else if (u == (httplen1 - 1)) - flags = STREAM_TOSERVER|STREAM_EOF; + flags = STREAM_TOSERVER | STREAM_EOF; else flags = STREAM_TOSERVER; r = AppLayerParserParse(NULL, alp_tctx, f, ALPROTO_HTTP1, flags, &httpbuf1[u], 1); if (r != 0) { printf("toserver chunk %" PRIu32 " returned %" PRId32 ", expected" - " 0: ", u, r); + " 0: ", + u, r); goto end; } } @@ -4408,7 +4367,7 @@ static int HTPParserTest13(void) } htp_tx_t *tx = HTPStateGetTx(htp_state, 0); - htp_header_t *h = htp_table_get_index(tx->request_headers, 0, NULL); + htp_header_t *h = htp_table_get_index(tx->request_headers, 0, NULL); if (h == NULL) { goto end; } @@ -4519,12 +4478,12 @@ libhtp:\n\ if (node == NULL) { goto end; } - TAILQ_FOREACH(n, &node->head, next) { + TAILQ_FOREACH (n, &node->head, next) { if (n == NULL) { goto end; } - switch(i) { + switch (i) { case 0: if (strcmp(n->name, "0") != 0) { goto end; @@ -4590,12 +4549,12 @@ libhtp:\n\ } i = 0; - TAILQ_FOREACH(n, &node->head, next) { + TAILQ_FOREACH (n, &node->head, next) { if (n == NULL) { goto end; } - switch(i) { + switch (i) { case 0: if (strcmp(n->name, "0") != 0) { goto end; @@ -4687,8 +4646,7 @@ libhtp:\n\ printf("Could not get config for: %s\n", addr); goto end; } - } - else { + } else { printf("Failed to parse address: %s\n", addr); goto end; } @@ -4706,8 +4664,7 @@ libhtp:\n\ printf("Could not get config for: %s\n", addr); goto end; } - } - else { + } else { printf("Failed to parse address: %s\n", addr); goto end; } @@ -4734,7 +4691,7 @@ static int HTPParserConfigTest03(void) TcpSession ssn; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); - HtpState *htp_state = NULL; + HtpState *htp_state = NULL; int r = 0; char input[] = "\ %YAML 1.1\n\ @@ -4796,14 +4753,18 @@ libhtp:\n\ for (u = 0; u < httplen1; u++) { uint8_t flags = 0; - if (u == 0) flags = STREAM_TOSERVER|STREAM_START; - else if (u == (httplen1 - 1)) flags = STREAM_TOSERVER|STREAM_EOF; - else flags = STREAM_TOSERVER; + if (u == 0) + flags = STREAM_TOSERVER | STREAM_START; + else if (u == (httplen1 - 1)) + flags = STREAM_TOSERVER | STREAM_EOF; + else + flags = STREAM_TOSERVER; r = AppLayerParserParse(NULL, alp_tctx, f, ALPROTO_HTTP1, flags, &httpbuf1[u], 1); if (r != 0) { printf("toserver chunk %" PRIu32 " returned %" PRId32 ", expected" - " 0: ", u, r); + " 0: ", + u, r); result = 0; goto end; } @@ -4825,16 +4786,14 @@ libhtp:\n\ if (tx == NULL) goto end; if (tx->cfg != htp) { - printf("wrong HTP config (%p instead of %p - default=%p): ", - tx->cfg, htp, cfglist.cfg); + printf("wrong HTP config (%p instead of %p - default=%p): ", tx->cfg, htp, cfglist.cfg); goto end; } tx = HTPStateGetTx(htp_state, 1); if (tx == NULL) goto end; if (tx->cfg != htp) { - printf("wrong HTP config (%p instead of %p - default=%p): ", - tx->cfg, htp, cfglist.cfg); + printf("wrong HTP config (%p instead of %p - default=%p): ", tx->cfg, htp, cfglist.cfg); goto end; } @@ -4933,10 +4892,9 @@ libhtp:\n\ */ static int HTPParserDecodingTest01(void) { - uint8_t httpbuf1[] = - "GET /abc%2fdef HTTP/1.1\r\nHost: www.domain.ltd\r\n\r\n" - "GET /abc/def?ghi%2fjkl HTTP/1.1\r\nHost: www.domain.ltd\r\n\r\n" - "GET /abc/def?ghi%252fjkl HTTP/1.1\r\nHost: www.domain.ltd\r\n\r\n"; + uint8_t httpbuf1[] = "GET /abc%2fdef HTTP/1.1\r\nHost: www.domain.ltd\r\n\r\n" + "GET /abc/def?ghi%2fjkl HTTP/1.1\r\nHost: www.domain.ltd\r\n\r\n" + "GET /abc/def?ghi%252fjkl HTTP/1.1\r\nHost: www.domain.ltd\r\n\r\n"; uint32_t httplen1 = sizeof(httpbuf1) - 1; /* minus the \0 */ TcpSession ssn; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -4969,9 +4927,12 @@ libhtp:\n\ for (uint32_t u = 0; u < httplen1; u++) { uint8_t flags = 0; - if (u == 0) flags = STREAM_TOSERVER|STREAM_START; - else if (u == (httplen1 - 1)) flags = STREAM_TOSERVER|STREAM_EOF; - else flags = STREAM_TOSERVER; + if (u == 0) + flags = STREAM_TOSERVER | STREAM_START; + else if (u == (httplen1 - 1)) + flags = STREAM_TOSERVER | STREAM_EOF; + else + flags = STREAM_TOSERVER; int r = AppLayerParserParse(NULL, alp_tctx, f, ALPROTO_HTTP1, flags, &httpbuf1[u], 1); FAIL_IF(r != 0); @@ -5010,7 +4971,7 @@ libhtp:\n\ reflen = sizeof(ref3) - 1; tx = HTPStateGetTx(htp_state, 2); FAIL_IF_NULL(tx); - tx_ud = (HtpTxUserData *) htp_tx_get_user_data(tx); + tx_ud = (HtpTxUserData *)htp_tx_get_user_data(tx); FAIL_IF_NULL(tx_ud); FAIL_IF_NULL(tx_ud->request_uri_normalized); FAIL_IF(reflen != bstr_len(tx_ud->request_uri_normalized)); @@ -5130,15 +5091,14 @@ static int HTPParserDecodingTest02(void) { int result = 0; Flow *f = NULL; - uint8_t httpbuf1[] = - "GET /abc%2fdef HTTP/1.1\r\nHost: www.domain.ltd\r\n\r\n" - "GET /abc/def?ghi%2fjkl HTTP/1.1\r\nHost: www.domain.ltd\r\n\r\n" - "GET /abc/def?ghi%252fjkl HTTP/1.1\r\nHost: www.domain.ltd\r\n\r\n"; + uint8_t httpbuf1[] = "GET /abc%2fdef HTTP/1.1\r\nHost: www.domain.ltd\r\n\r\n" + "GET /abc/def?ghi%2fjkl HTTP/1.1\r\nHost: www.domain.ltd\r\n\r\n" + "GET /abc/def?ghi%252fjkl HTTP/1.1\r\nHost: www.domain.ltd\r\n\r\n"; uint32_t httplen1 = sizeof(httpbuf1) - 1; /* minus the \0 */ TcpSession ssn; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); - HtpState *htp_state = NULL; + HtpState *htp_state = NULL; int r = 0; char input[] = "\ %YAML 1.1\n\ @@ -5172,14 +5132,18 @@ libhtp:\n\ for (u = 0; u < httplen1; u++) { uint8_t flags = 0; - if (u == 0) flags = STREAM_TOSERVER|STREAM_START; - else if (u == (httplen1 - 1)) flags = STREAM_TOSERVER|STREAM_EOF; - else flags = STREAM_TOSERVER; + if (u == 0) + flags = STREAM_TOSERVER | STREAM_START; + else if (u == (httplen1 - 1)) + flags = STREAM_TOSERVER | STREAM_EOF; + else + flags = STREAM_TOSERVER; r = AppLayerParserParse(NULL, alp_tctx, f, ALPROTO_HTTP1, flags, &httpbuf1[u], 1); if (r != 0) { printf("toserver chunk %" PRIu32 " returned %" PRId32 ", expected" - " 0: ", u, r); + " 0: ", + u, r); goto end; } } @@ -5199,17 +5163,16 @@ libhtp:\n\ HtpTxUserData *tx_ud = (HtpTxUserData *)htp_tx_get_user_data(tx); if (tx_ud != NULL && tx_ud->request_uri_normalized != NULL) { if (reflen != bstr_len(tx_ud->request_uri_normalized)) { - printf("normalized uri len should be %"PRIuMAX", is %"PRIuMAX, - (uintmax_t)reflen, - (uintmax_t)bstr_len(tx_ud->request_uri_normalized)); + printf("normalized uri len should be %" PRIuMAX ", is %" PRIuMAX, (uintmax_t)reflen, + (uintmax_t)bstr_len(tx_ud->request_uri_normalized)); goto end; } if (memcmp(bstr_ptr(tx_ud->request_uri_normalized), ref1, - bstr_len(tx_ud->request_uri_normalized)) != 0) - { + bstr_len(tx_ud->request_uri_normalized)) != 0) { printf("normalized uri \""); - PrintRawUriFp(stdout, bstr_ptr(tx_ud->request_uri_normalized), bstr_len(tx_ud->request_uri_normalized)); + PrintRawUriFp(stdout, bstr_ptr(tx_ud->request_uri_normalized), + bstr_len(tx_ud->request_uri_normalized)); printf("\" != \""); PrintRawUriFp(stdout, ref1, reflen); printf("\": "); @@ -5226,17 +5189,16 @@ libhtp:\n\ tx_ud = (HtpTxUserData *)htp_tx_get_user_data(tx); if (tx_ud != NULL && tx_ud->request_uri_normalized != NULL) { if (reflen != bstr_len(tx_ud->request_uri_normalized)) { - printf("normalized uri len should be %"PRIuMAX", is %"PRIuMAX, - (uintmax_t)reflen, - (uintmax_t)bstr_len(tx_ud->request_uri_normalized)); + printf("normalized uri len should be %" PRIuMAX ", is %" PRIuMAX, (uintmax_t)reflen, + (uintmax_t)bstr_len(tx_ud->request_uri_normalized)); goto end; } if (memcmp(bstr_ptr(tx_ud->request_uri_normalized), ref2, - bstr_len(tx_ud->request_uri_normalized)) != 0) - { + bstr_len(tx_ud->request_uri_normalized)) != 0) { printf("normalized uri \""); - PrintRawUriFp(stdout, bstr_ptr(tx_ud->request_uri_normalized), bstr_len(tx_ud->request_uri_normalized)); + PrintRawUriFp(stdout, bstr_ptr(tx_ud->request_uri_normalized), + bstr_len(tx_ud->request_uri_normalized)); printf("\" != \""); PrintRawUriFp(stdout, ref2, reflen); printf("\": "); @@ -5249,20 +5211,19 @@ libhtp:\n\ tx = HTPStateGetTx(htp_state, 2); if (tx == NULL) goto end; - tx_ud = (HtpTxUserData *) htp_tx_get_user_data(tx); + tx_ud = (HtpTxUserData *)htp_tx_get_user_data(tx); if (tx_ud != NULL && tx_ud->request_uri_normalized != NULL) { if (reflen != bstr_len(tx_ud->request_uri_normalized)) { - printf("normalized uri len should be %"PRIuMAX", is %"PRIuMAX" (3): ", - (uintmax_t)reflen, - (uintmax_t)bstr_len(tx_ud->request_uri_normalized)); + printf("normalized uri len should be %" PRIuMAX ", is %" PRIuMAX " (3): ", + (uintmax_t)reflen, (uintmax_t)bstr_len(tx_ud->request_uri_normalized)); goto end; } if (memcmp(bstr_ptr(tx_ud->request_uri_normalized), ref3, - bstr_len(tx_ud->request_uri_normalized)) != 0) - { + bstr_len(tx_ud->request_uri_normalized)) != 0) { printf("normalized uri \""); - PrintRawUriFp(stdout, bstr_ptr(tx_ud->request_uri_normalized), bstr_len(tx_ud->request_uri_normalized)); + PrintRawUriFp(stdout, bstr_ptr(tx_ud->request_uri_normalized), + bstr_len(tx_ud->request_uri_normalized)); printf("\" != \""); PrintRawUriFp(stdout, ref3, reflen); printf("\": "); @@ -5294,14 +5255,13 @@ static int HTPParserDecodingTest03(void) { int result = 0; Flow *f = NULL; - uint8_t httpbuf1[] = - "GET /abc%252fdef HTTP/1.1\r\nHost: www.domain.ltd\r\n\r\n" - "GET /abc/def?ghi%252fjkl HTTP/1.1\r\nHost: www.domain.ltd\r\n\r\n"; + uint8_t httpbuf1[] = "GET /abc%252fdef HTTP/1.1\r\nHost: www.domain.ltd\r\n\r\n" + "GET /abc/def?ghi%252fjkl HTTP/1.1\r\nHost: www.domain.ltd\r\n\r\n"; uint32_t httplen1 = sizeof(httpbuf1) - 1; /* minus the \0 */ TcpSession ssn; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); - HtpState *htp_state = NULL; + HtpState *htp_state = NULL; int r = 0; char input[] = "\ %YAML 1.1\n\ @@ -5335,14 +5295,18 @@ libhtp:\n\ for (u = 0; u < httplen1; u++) { uint8_t flags = 0; - if (u == 0) flags = STREAM_TOSERVER|STREAM_START; - else if (u == (httplen1 - 1)) flags = STREAM_TOSERVER|STREAM_EOF; - else flags = STREAM_TOSERVER; + if (u == 0) + flags = STREAM_TOSERVER | STREAM_START; + else if (u == (httplen1 - 1)) + flags = STREAM_TOSERVER | STREAM_EOF; + else + flags = STREAM_TOSERVER; r = AppLayerParserParse(NULL, alp_tctx, f, ALPROTO_HTTP1, flags, &httpbuf1[u], 1); if (r != 0) { printf("toserver chunk %" PRIu32 " returned %" PRId32 ", expected" - " 0: ", u, r); + " 0: ", + u, r); goto end; } } @@ -5359,20 +5323,19 @@ libhtp:\n\ htp_tx_t *tx = HTPStateGetTx(htp_state, 0); if (tx == NULL) goto end; - HtpTxUserData *tx_ud = (HtpTxUserData *) htp_tx_get_user_data(tx); + HtpTxUserData *tx_ud = (HtpTxUserData *)htp_tx_get_user_data(tx); if (tx_ud != NULL && tx_ud->request_uri_normalized != NULL) { if (reflen != bstr_len(tx_ud->request_uri_normalized)) { - printf("normalized uri len should be %"PRIuMAX", is %"PRIuMAX, - (uintmax_t)reflen, - (uintmax_t)bstr_len(tx_ud->request_uri_normalized)); + printf("normalized uri len should be %" PRIuMAX ", is %" PRIuMAX, (uintmax_t)reflen, + (uintmax_t)bstr_len(tx_ud->request_uri_normalized)); goto end; } if (memcmp(bstr_ptr(tx_ud->request_uri_normalized), ref1, - bstr_len(tx_ud->request_uri_normalized)) != 0) - { + bstr_len(tx_ud->request_uri_normalized)) != 0) { printf("normalized uri \""); - PrintRawUriFp(stdout, bstr_ptr(tx_ud->request_uri_normalized), bstr_len(tx_ud->request_uri_normalized)); + PrintRawUriFp(stdout, bstr_ptr(tx_ud->request_uri_normalized), + bstr_len(tx_ud->request_uri_normalized)); printf("\" != \""); PrintRawUriFp(stdout, ref1, reflen); printf("\": "); @@ -5389,17 +5352,16 @@ libhtp:\n\ tx_ud = (HtpTxUserData *)htp_tx_get_user_data(tx); if (tx_ud != NULL && tx_ud->request_uri_normalized != NULL) { if (reflen != bstr_len(tx_ud->request_uri_normalized)) { - printf("normalized uri len should be %"PRIuMAX", is %"PRIuMAX, - (uintmax_t)reflen, - (uintmax_t)bstr_len(tx_ud->request_uri_normalized)); + printf("normalized uri len should be %" PRIuMAX ", is %" PRIuMAX, (uintmax_t)reflen, + (uintmax_t)bstr_len(tx_ud->request_uri_normalized)); goto end; } if (memcmp(bstr_ptr(tx_ud->request_uri_normalized), ref2, - bstr_len(tx_ud->request_uri_normalized)) != 0) - { + bstr_len(tx_ud->request_uri_normalized)) != 0) { printf("normalized uri \""); - PrintRawUriFp(stdout, bstr_ptr(tx_ud->request_uri_normalized), bstr_len(tx_ud->request_uri_normalized)); + PrintRawUriFp(stdout, bstr_ptr(tx_ud->request_uri_normalized), + bstr_len(tx_ud->request_uri_normalized)); printf("\" != \""); PrintRawUriFp(stdout, ref2, reflen); printf("\": "); @@ -5429,12 +5391,12 @@ static int HTPParserDecodingTest04(void) int result = 0; Flow *f = NULL; uint8_t httpbuf1[] = - "GET /abc/def?a=http://www.abc.com/ HTTP/1.1\r\nHost: www.domain.ltd\r\n\r\n"; + "GET /abc/def?a=http://www.abc.com/ HTTP/1.1\r\nHost: www.domain.ltd\r\n\r\n"; uint32_t httplen1 = sizeof(httpbuf1) - 1; /* minus the \0 */ TcpSession ssn; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); - HtpState *htp_state = NULL; + HtpState *htp_state = NULL; int r = 0; char input[] = "\ %YAML 1.1\n\ @@ -5468,14 +5430,18 @@ libhtp:\n\ for (u = 0; u < httplen1; u++) { uint8_t flags = 0; - if (u == 0) flags = STREAM_TOSERVER|STREAM_START; - else if (u == (httplen1 - 1)) flags = STREAM_TOSERVER|STREAM_EOF; - else flags = STREAM_TOSERVER; + if (u == 0) + flags = STREAM_TOSERVER | STREAM_START; + else if (u == (httplen1 - 1)) + flags = STREAM_TOSERVER | STREAM_EOF; + else + flags = STREAM_TOSERVER; r = AppLayerParserParse(NULL, alp_tctx, f, ALPROTO_HTTP1, flags, &httpbuf1[u], 1); if (r != 0) { printf("toserver chunk %" PRIu32 " returned %" PRId32 ", expected" - " 0: ", u, r); + " 0: ", + u, r); goto end; } } @@ -5492,20 +5458,19 @@ libhtp:\n\ htp_tx_t *tx = HTPStateGetTx(htp_state, 0); if (tx == NULL) goto end; - HtpTxUserData *tx_ud = (HtpTxUserData *) htp_tx_get_user_data(tx); + HtpTxUserData *tx_ud = (HtpTxUserData *)htp_tx_get_user_data(tx); if (tx_ud != NULL && tx_ud->request_uri_normalized != NULL) { if (reflen != bstr_len(tx_ud->request_uri_normalized)) { - printf("normalized uri len should be %"PRIuMAX", is %"PRIuMAX, - (uintmax_t)reflen, - (uintmax_t)bstr_len(tx_ud->request_uri_normalized)); + printf("normalized uri len should be %" PRIuMAX ", is %" PRIuMAX, (uintmax_t)reflen, + (uintmax_t)bstr_len(tx_ud->request_uri_normalized)); goto end; } if (memcmp(bstr_ptr(tx_ud->request_uri_normalized), ref1, - bstr_len(tx_ud->request_uri_normalized)) != 0) - { + bstr_len(tx_ud->request_uri_normalized)) != 0) { printf("normalized uri \""); - PrintRawUriFp(stdout, bstr_ptr(tx_ud->request_uri_normalized), bstr_len(tx_ud->request_uri_normalized)); + PrintRawUriFp(stdout, bstr_ptr(tx_ud->request_uri_normalized), + bstr_len(tx_ud->request_uri_normalized)); printf("\" != \""); PrintRawUriFp(stdout, ref1, reflen); printf("\": "); @@ -5534,13 +5499,13 @@ static int HTPParserDecodingTest05(void) { int result = 0; Flow *f = NULL; - uint8_t httpbuf1[] = - "GET /index?id=\\\" HTTP/1.1\r\nHost: www.domain.ltd\r\n\r\n"; + uint8_t httpbuf1[] = "GET /index?id=\\\" " + "HTTP/1.1\r\nHost: www.domain.ltd\r\n\r\n"; uint32_t httplen1 = sizeof(httpbuf1) - 1; /* minus the \0 */ TcpSession ssn; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); - HtpState *htp_state = NULL; + HtpState *htp_state = NULL; int r = 0; char input[] = "\ %YAML 1.1\n\ @@ -5574,14 +5539,18 @@ libhtp:\n\ for (u = 0; u < httplen1; u++) { uint8_t flags = 0; - if (u == 0) flags = STREAM_TOSERVER|STREAM_START; - else if (u == (httplen1 - 1)) flags = STREAM_TOSERVER|STREAM_EOF; - else flags = STREAM_TOSERVER; + if (u == 0) + flags = STREAM_TOSERVER | STREAM_START; + else if (u == (httplen1 - 1)) + flags = STREAM_TOSERVER | STREAM_EOF; + else + flags = STREAM_TOSERVER; r = AppLayerParserParse(NULL, alp_tctx, f, ALPROTO_HTTP1, flags, &httpbuf1[u], 1); if (r != 0) { printf("toserver chunk %" PRIu32 " returned %" PRId32 ", expected" - " 0: ", u, r); + " 0: ", + u, r); goto end; } } @@ -5598,20 +5567,19 @@ libhtp:\n\ htp_tx_t *tx = HTPStateGetTx(htp_state, 0); if (tx == NULL) goto end; - HtpTxUserData *tx_ud = (HtpTxUserData *) htp_tx_get_user_data(tx); + HtpTxUserData *tx_ud = (HtpTxUserData *)htp_tx_get_user_data(tx); if (tx_ud != NULL && tx_ud->request_uri_normalized != NULL) { if (reflen != bstr_len(tx_ud->request_uri_normalized)) { - printf("normalized uri len should be %"PRIuMAX", is %"PRIuMAX, - (uintmax_t)reflen, - (uintmax_t)bstr_len(tx_ud->request_uri_normalized)); + printf("normalized uri len should be %" PRIuMAX ", is %" PRIuMAX, (uintmax_t)reflen, + (uintmax_t)bstr_len(tx_ud->request_uri_normalized)); goto end; } if (memcmp(bstr_ptr(tx_ud->request_uri_normalized), ref1, - bstr_len(tx_ud->request_uri_normalized)) != 0) - { + bstr_len(tx_ud->request_uri_normalized)) != 0) { printf("normalized uri \""); - PrintRawUriFp(stdout, bstr_ptr(tx_ud->request_uri_normalized), bstr_len(tx_ud->request_uri_normalized)); + PrintRawUriFp(stdout, bstr_ptr(tx_ud->request_uri_normalized), + bstr_len(tx_ud->request_uri_normalized)); printf("\" != \""); PrintRawUriFp(stdout, ref1, reflen); printf("\": "); @@ -5641,12 +5609,12 @@ static int HTPParserDecodingTest06(void) int result = 0; Flow *f = NULL; uint8_t httpbuf1[] = - "GET /put.php?ip=1.2.3.4&port=+6000 HTTP/1.1\r\nHost: www.domain.ltd\r\n\r\n"; + "GET /put.php?ip=1.2.3.4&port=+6000 HTTP/1.1\r\nHost: www.domain.ltd\r\n\r\n"; uint32_t httplen1 = sizeof(httpbuf1) - 1; /* minus the \0 */ TcpSession ssn; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); - HtpState *htp_state = NULL; + HtpState *htp_state = NULL; int r = 0; char input[] = "\ %YAML 1.1\n\ @@ -5680,14 +5648,18 @@ libhtp:\n\ for (u = 0; u < httplen1; u++) { uint8_t flags = 0; - if (u == 0) flags = STREAM_TOSERVER|STREAM_START; - else if (u == (httplen1 - 1)) flags = STREAM_TOSERVER|STREAM_EOF; - else flags = STREAM_TOSERVER; + if (u == 0) + flags = STREAM_TOSERVER | STREAM_START; + else if (u == (httplen1 - 1)) + flags = STREAM_TOSERVER | STREAM_EOF; + else + flags = STREAM_TOSERVER; r = AppLayerParserParse(NULL, alp_tctx, f, ALPROTO_HTTP1, flags, &httpbuf1[u], 1); if (r != 0) { printf("toserver chunk %" PRIu32 " returned %" PRId32 ", expected" - " 0: ", u, r); + " 0: ", + u, r); goto end; } } @@ -5704,20 +5676,19 @@ libhtp:\n\ htp_tx_t *tx = HTPStateGetTx(htp_state, 0); if (tx == NULL) goto end; - HtpTxUserData *tx_ud = (HtpTxUserData *) htp_tx_get_user_data(tx); + HtpTxUserData *tx_ud = (HtpTxUserData *)htp_tx_get_user_data(tx); if (tx_ud != NULL && tx_ud->request_uri_normalized != NULL) { if (reflen != bstr_len(tx_ud->request_uri_normalized)) { - printf("normalized uri len should be %"PRIuMAX", is %"PRIuMAX, - (uintmax_t)reflen, - (uintmax_t)bstr_len(tx_ud->request_uri_normalized)); + printf("normalized uri len should be %" PRIuMAX ", is %" PRIuMAX, (uintmax_t)reflen, + (uintmax_t)bstr_len(tx_ud->request_uri_normalized)); goto end; } if (memcmp(bstr_ptr(tx_ud->request_uri_normalized), ref1, - bstr_len(tx_ud->request_uri_normalized)) != 0) - { + bstr_len(tx_ud->request_uri_normalized)) != 0) { printf("normalized uri \""); - PrintRawUriFp(stdout, bstr_ptr(tx_ud->request_uri_normalized), bstr_len(tx_ud->request_uri_normalized)); + PrintRawUriFp(stdout, bstr_ptr(tx_ud->request_uri_normalized), + bstr_len(tx_ud->request_uri_normalized)); printf("\" != \""); PrintRawUriFp(stdout, ref1, reflen); printf("\": "); @@ -5747,12 +5718,12 @@ static int HTPParserDecodingTest07(void) int result = 0; Flow *f = NULL; uint8_t httpbuf1[] = - "GET /put.php?ip=1.2.3.4&port=+6000 HTTP/1.1\r\nHost: www.domain.ltd\r\n\r\n"; + "GET /put.php?ip=1.2.3.4&port=+6000 HTTP/1.1\r\nHost: www.domain.ltd\r\n\r\n"; uint32_t httplen1 = sizeof(httpbuf1) - 1; /* minus the \0 */ TcpSession ssn; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); - HtpState *htp_state = NULL; + HtpState *htp_state = NULL; int r = 0; char input[] = "\ %YAML 1.1\n\ @@ -5787,14 +5758,18 @@ libhtp:\n\ for (u = 0; u < httplen1; u++) { uint8_t flags = 0; - if (u == 0) flags = STREAM_TOSERVER|STREAM_START; - else if (u == (httplen1 - 1)) flags = STREAM_TOSERVER|STREAM_EOF; - else flags = STREAM_TOSERVER; + if (u == 0) + flags = STREAM_TOSERVER | STREAM_START; + else if (u == (httplen1 - 1)) + flags = STREAM_TOSERVER | STREAM_EOF; + else + flags = STREAM_TOSERVER; r = AppLayerParserParse(NULL, alp_tctx, f, ALPROTO_HTTP1, flags, &httpbuf1[u], 1); if (r != 0) { printf("toserver chunk %" PRIu32 " returned %" PRId32 ", expected" - " 0: ", u, r); + " 0: ", + u, r); goto end; } } @@ -5811,20 +5786,19 @@ libhtp:\n\ htp_tx_t *tx = HTPStateGetTx(htp_state, 0); if (tx == NULL) goto end; - HtpTxUserData *tx_ud = (HtpTxUserData *) htp_tx_get_user_data(tx); + HtpTxUserData *tx_ud = (HtpTxUserData *)htp_tx_get_user_data(tx); if (tx_ud != NULL && tx_ud->request_uri_normalized != NULL) { if (reflen != bstr_len(tx_ud->request_uri_normalized)) { - printf("normalized uri len should be %"PRIuMAX", is %"PRIuMAX, - (uintmax_t)reflen, - (uintmax_t)bstr_len(tx_ud->request_uri_normalized)); + printf("normalized uri len should be %" PRIuMAX ", is %" PRIuMAX, (uintmax_t)reflen, + (uintmax_t)bstr_len(tx_ud->request_uri_normalized)); goto end; } if (memcmp(bstr_ptr(tx_ud->request_uri_normalized), ref1, - bstr_len(tx_ud->request_uri_normalized)) != 0) - { + bstr_len(tx_ud->request_uri_normalized)) != 0) { printf("normalized uri \""); - PrintRawUriFp(stdout, bstr_ptr(tx_ud->request_uri_normalized), bstr_len(tx_ud->request_uri_normalized)); + PrintRawUriFp(stdout, bstr_ptr(tx_ud->request_uri_normalized), + bstr_len(tx_ud->request_uri_normalized)); printf("\" != \""); PrintRawUriFp(stdout, ref1, reflen); printf("\": "); @@ -5854,12 +5828,12 @@ static int HTPParserDecodingTest08(void) int result = 0; Flow *f = NULL; uint8_t httpbuf1[] = - "GET http://suricata-ids.org/blah/ HTTP/1.1\r\nHost: suricata-ids.org\r\n\r\n"; + "GET http://suricata-ids.org/blah/ HTTP/1.1\r\nHost: suricata-ids.org\r\n\r\n"; uint32_t httplen1 = sizeof(httpbuf1) - 1; /* minus the \0 */ TcpSession ssn; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); - HtpState *htp_state = NULL; + HtpState *htp_state = NULL; int r = 0; char input[] = "\ %YAML 1.1\n\ @@ -5891,14 +5865,18 @@ libhtp:\n\ for (u = 0; u < httplen1; u++) { uint8_t flags = 0; - if (u == 0) flags = STREAM_TOSERVER|STREAM_START; - else if (u == (httplen1 - 1)) flags = STREAM_TOSERVER|STREAM_EOF; - else flags = STREAM_TOSERVER; + if (u == 0) + flags = STREAM_TOSERVER | STREAM_START; + else if (u == (httplen1 - 1)) + flags = STREAM_TOSERVER | STREAM_EOF; + else + flags = STREAM_TOSERVER; r = AppLayerParserParse(NULL, alp_tctx, f, ALPROTO_HTTP1, flags, &httpbuf1[u], 1); if (r != 0) { printf("toserver chunk %" PRIu32 " returned %" PRId32 ", expected" - " 0: ", u, r); + " 0: ", + u, r); goto end; } } @@ -5915,20 +5893,19 @@ libhtp:\n\ htp_tx_t *tx = HTPStateGetTx(htp_state, 0); if (tx == NULL) goto end; - HtpTxUserData *tx_ud = (HtpTxUserData *) htp_tx_get_user_data(tx); + HtpTxUserData *tx_ud = (HtpTxUserData *)htp_tx_get_user_data(tx); if (tx_ud != NULL && tx_ud->request_uri_normalized != NULL) { if (reflen != bstr_len(tx_ud->request_uri_normalized)) { - printf("normalized uri len should be %"PRIuMAX", is %"PRIuMAX, - (uintmax_t)reflen, - (uintmax_t)bstr_len(tx_ud->request_uri_normalized)); + printf("normalized uri len should be %" PRIuMAX ", is %" PRIuMAX, (uintmax_t)reflen, + (uintmax_t)bstr_len(tx_ud->request_uri_normalized)); goto end; } if (memcmp(bstr_ptr(tx_ud->request_uri_normalized), ref1, - bstr_len(tx_ud->request_uri_normalized)) != 0) - { + bstr_len(tx_ud->request_uri_normalized)) != 0) { printf("normalized uri \""); - PrintRawUriFp(stdout, bstr_ptr(tx_ud->request_uri_normalized), bstr_len(tx_ud->request_uri_normalized)); + PrintRawUriFp(stdout, bstr_ptr(tx_ud->request_uri_normalized), + bstr_len(tx_ud->request_uri_normalized)); printf("\" != \""); PrintRawUriFp(stdout, ref1, reflen); printf("\": "); @@ -5958,12 +5935,12 @@ static int HTPParserDecodingTest09(void) int result = 0; Flow *f = NULL; uint8_t httpbuf1[] = - "GET http://suricata-ids.org/blah/ HTTP/1.1\r\nHost: suricata-ids.org\r\n\r\n"; + "GET http://suricata-ids.org/blah/ HTTP/1.1\r\nHost: suricata-ids.org\r\n\r\n"; uint32_t httplen1 = sizeof(httpbuf1) - 1; /* minus the \0 */ TcpSession ssn; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); - HtpState *htp_state = NULL; + HtpState *htp_state = NULL; int r = 0; char input[] = "\ %YAML 1.1\n\ @@ -5996,14 +5973,18 @@ libhtp:\n\ for (u = 0; u < httplen1; u++) { uint8_t flags = 0; - if (u == 0) flags = STREAM_TOSERVER|STREAM_START; - else if (u == (httplen1 - 1)) flags = STREAM_TOSERVER|STREAM_EOF; - else flags = STREAM_TOSERVER; + if (u == 0) + flags = STREAM_TOSERVER | STREAM_START; + else if (u == (httplen1 - 1)) + flags = STREAM_TOSERVER | STREAM_EOF; + else + flags = STREAM_TOSERVER; r = AppLayerParserParse(NULL, alp_tctx, f, ALPROTO_HTTP1, flags, &httpbuf1[u], 1); if (r != 0) { printf("toserver chunk %" PRIu32 " returned %" PRId32 ", expected" - " 0: ", u, r); + " 0: ", + u, r); goto end; } } @@ -6020,20 +6001,19 @@ libhtp:\n\ htp_tx_t *tx = HTPStateGetTx(htp_state, 0); if (tx == NULL) goto end; - HtpTxUserData *tx_ud = (HtpTxUserData *) htp_tx_get_user_data(tx); + HtpTxUserData *tx_ud = (HtpTxUserData *)htp_tx_get_user_data(tx); if (tx_ud != NULL && tx_ud->request_uri_normalized != NULL) { if (reflen != bstr_len(tx_ud->request_uri_normalized)) { - printf("normalized uri len should be %"PRIuMAX", is %"PRIuMAX, - (uintmax_t)reflen, - (uintmax_t)bstr_len(tx_ud->request_uri_normalized)); + printf("normalized uri len should be %" PRIuMAX ", is %" PRIuMAX, (uintmax_t)reflen, + (uintmax_t)bstr_len(tx_ud->request_uri_normalized)); goto end; } if (memcmp(bstr_ptr(tx_ud->request_uri_normalized), ref1, - bstr_len(tx_ud->request_uri_normalized)) != 0) - { + bstr_len(tx_ud->request_uri_normalized)) != 0) { printf("normalized uri \""); - PrintRawUriFp(stdout, bstr_ptr(tx_ud->request_uri_normalized), bstr_len(tx_ud->request_uri_normalized)); + PrintRawUriFp(stdout, bstr_ptr(tx_ud->request_uri_normalized), + bstr_len(tx_ud->request_uri_normalized)); printf("\" != \""); PrintRawUriFp(stdout, ref1, reflen); printf("\": "); @@ -6073,12 +6053,22 @@ static int HTPBodyReassemblyTest01(void) hstate.f = &flow; flow.alparser = parser; - uint8_t chunk1[] = "--e5a320f21416a02493a0a6f561b1c494\r\nContent-Disposition: form-data; name=\"uploadfile\"; filename=\"D2GUef.jpg\"\r"; - uint8_t chunk2[] = "POST /uri HTTP/1.1\r\nHost: hostname.com\r\nKeep-Alive: 115\r\nAccept-Charset: utf-8\r\nUser-Agent: Mozilla/5.0 (X11; Linux i686; rv:9.0.1) Gecko/20100101 Firefox/9.0.1\r\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\nConnection: keep-alive\r\nContent-length: 68102\r\nReferer: http://otherhost.com\r\nAccept-Encoding: gzip\r\nContent-Type: multipart/form-data; boundary=e5a320f21416a02493a0a6f561b1c494\r\nCookie: blah\r\nAccept-Language: us\r\n\r\n--e5a320f21416a02493a0a6f561b1c494\r\nContent-Disposition: form-data; name=\"uploadfile\"; filename=\"D2GUef.jpg\"\r"; - - int r = HtpBodyAppendChunk(NULL, &htud.request_body, chunk1, sizeof(chunk1)-1); + uint8_t chunk1[] = "--e5a320f21416a02493a0a6f561b1c494\r\nContent-Disposition: form-data; " + "name=\"uploadfile\"; filename=\"D2GUef.jpg\"\r"; + uint8_t chunk2[] = + "POST /uri HTTP/1.1\r\nHost: hostname.com\r\nKeep-Alive: 115\r\nAccept-Charset: " + "utf-8\r\nUser-Agent: Mozilla/5.0 (X11; Linux i686; rv:9.0.1) Gecko/20100101 " + "Firefox/9.0.1\r\nAccept: " + "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\nConnection: " + "keep-alive\r\nContent-length: 68102\r\nReferer: " + "http://otherhost.com\r\nAccept-Encoding: gzip\r\nContent-Type: multipart/form-data; " + "boundary=e5a320f21416a02493a0a6f561b1c494\r\nCookie: blah\r\nAccept-Language: " + "us\r\n\r\n--e5a320f21416a02493a0a6f561b1c494\r\nContent-Disposition: form-data; " + "name=\"uploadfile\"; filename=\"D2GUef.jpg\"\r"; + + int r = HtpBodyAppendChunk(NULL, &htud.request_body, chunk1, sizeof(chunk1) - 1); BUG_ON(r != 0); - r = HtpBodyAppendChunk(NULL, &htud.request_body, chunk2, sizeof(chunk2)-1); + r = HtpBodyAppendChunk(NULL, &htud.request_body, chunk2, sizeof(chunk2) - 1); BUG_ON(r != 0); const uint8_t *chunks_buffer = NULL; @@ -6097,7 +6087,8 @@ static int HTPBodyReassemblyTest01(void) HtpRequestBodyHandleMultipart(&hstate, &htud, &tx, chunks_buffer, chunks_buffer_len); if (htud.request_body.content_len_so_far != 669) { - printf("htud.request_body.content_len_so_far %"PRIu64": ", htud.request_body.content_len_so_far); + printf("htud.request_body.content_len_so_far %" PRIu64 ": ", + htud.request_body.content_len_so_far); goto end; } @@ -6113,7 +6104,16 @@ static int HTPSegvTest01(void) { int result = 0; Flow *f = NULL; - uint8_t httpbuf1[] = "POST /uri HTTP/1.1\r\nHost: hostname.com\r\nKeep-Alive: 115\r\nAccept-Charset: utf-8\r\nUser-Agent: Mozilla/5.0 (X11; Linux i686; rv:9.0.1) Gecko/20100101 Firefox/9.0.1\r\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\nConnection: keep-alive\r\nContent-length: 68102\r\nReferer: http://otherhost.com\r\nAccept-Encoding: gzip\r\nContent-Type: multipart/form-data; boundary=e5a320f21416a02493a0a6f561b1c494\r\nCookie: blah\r\nAccept-Language: us\r\n\r\n--e5a320f21416a02493a0a6f561b1c494\r\nContent-Disposition: form-data; name=\"uploadfile\"; filename=\"D2GUef.jpg\"\r"; + uint8_t httpbuf1[] = + "POST /uri HTTP/1.1\r\nHost: hostname.com\r\nKeep-Alive: 115\r\nAccept-Charset: " + "utf-8\r\nUser-Agent: Mozilla/5.0 (X11; Linux i686; rv:9.0.1) Gecko/20100101 " + "Firefox/9.0.1\r\nAccept: " + "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\nConnection: " + "keep-alive\r\nContent-length: 68102\r\nReferer: " + "http://otherhost.com\r\nAccept-Encoding: gzip\r\nContent-Type: multipart/form-data; " + "boundary=e5a320f21416a02493a0a6f561b1c494\r\nCookie: blah\r\nAccept-Language: " + "us\r\n\r\n--e5a320f21416a02493a0a6f561b1c494\r\nContent-Disposition: form-data; " + "name=\"uploadfile\"; filename=\"D2GUef.jpg\"\r"; uint32_t httplen1 = sizeof(httpbuf1) - 1; /* minus the \0 */ char input[] = "\ %YAML 1.1\n\ @@ -6187,7 +6187,8 @@ libhtp:\n\ return result; } -/** \test Test really long request, this should result in HTTP_DECODER_EVENT_REQUEST_FIELD_TOO_LONG */ +/** \test Test really long request, this should result in HTTP_DECODER_EVENT_REQUEST_FIELD_TOO_LONG + */ static int HTPParserTest14(void) { size_t len = 18887; @@ -6220,16 +6221,19 @@ libhtp:\n\ memset(httpbuf, 0x00, len); /* create the request with a longer than 18k cookie */ - strlcpy(httpbuf, "GET /blah/ HTTP/1.1\r\n" - "Host: myhost.lan\r\n" - "Connection: keep-alive\r\n" - "Accept: */*\r\n" - "User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.76 Safari/537.36\r\n" - "Referer: http://blah.lan/\r\n" - "Accept-Encoding: gzip,deflate,sdch\r\nAccept-Language: en-US,en;q=0.8\r\n" - "Cookie: ", len); + strlcpy(httpbuf, + "GET /blah/ HTTP/1.1\r\n" + "Host: myhost.lan\r\n" + "Connection: keep-alive\r\n" + "Accept: */*\r\n" + "User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like " + "Gecko) Chrome/29.0.1547.76 Safari/537.36\r\n" + "Referer: http://blah.lan/\r\n" + "Accept-Encoding: gzip,deflate,sdch\r\nAccept-Language: en-US,en;q=0.8\r\n" + "Cookie: ", + len); size_t o = strlen(httpbuf); - for ( ; o < len - 4; o++) { + for (; o < len - 4; o++) { httpbuf[o] = 'A'; } httpbuf[len - 4] = '\r'; @@ -6249,9 +6253,12 @@ libhtp:\n\ for (u = 0; u < len; u++) { uint8_t flags = 0; - if (u == 0) flags = STREAM_TOSERVER|STREAM_START; - else if (u == (len - 1)) flags = STREAM_TOSERVER|STREAM_EOF; - else flags = STREAM_TOSERVER; + if (u == 0) + flags = STREAM_TOSERVER | STREAM_START; + else if (u == (len - 1)) + flags = STREAM_TOSERVER | STREAM_EOF; + else + flags = STREAM_TOSERVER; (void)AppLayerParserParse( NULL, alp_tctx, f, ALPROTO_HTTP1, flags, (uint8_t *)&httpbuf[u], 1); @@ -6291,7 +6298,7 @@ static int HTPParserTest15(void) char *httpbuf = NULL; size_t len = 18887; TcpSession ssn; - HtpState *htp_state = NULL; + HtpState *htp_state = NULL; int r = 0; char input[] = "\ %YAML 1.1\n\ @@ -6322,16 +6329,19 @@ libhtp:\n\ memset(httpbuf, 0x00, len); /* create the request with a longer than 18k cookie */ - strlcpy(httpbuf, "GET /blah/ HTTP/1.1\r\n" - "Host: myhost.lan\r\n" - "Connection: keep-alive\r\n" - "Accept: */*\r\n" - "User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.76 Safari/537.36\r\n" - "Referer: http://blah.lan/\r\n" - "Accept-Encoding: gzip,deflate,sdch\r\nAccept-Language: en-US,en;q=0.8\r\n" - "Cookie: ", len); + strlcpy(httpbuf, + "GET /blah/ HTTP/1.1\r\n" + "Host: myhost.lan\r\n" + "Connection: keep-alive\r\n" + "Accept: */*\r\n" + "User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like " + "Gecko) Chrome/29.0.1547.76 Safari/537.36\r\n" + "Referer: http://blah.lan/\r\n" + "Accept-Encoding: gzip,deflate,sdch\r\nAccept-Language: en-US,en;q=0.8\r\n" + "Cookie: ", + len); size_t o = strlen(httpbuf); - for ( ; o < len - 4; o++) { + for (; o < len - 4; o++) { httpbuf[o] = 'A'; } httpbuf[len - 4] = '\r'; @@ -6352,14 +6362,18 @@ libhtp:\n\ for (u = 0; u < len; u++) { uint8_t flags = 0; - if (u == 0) flags = STREAM_TOSERVER|STREAM_START; - else if (u == (len - 1)) flags = STREAM_TOSERVER|STREAM_EOF; - else flags = STREAM_TOSERVER; + if (u == 0) + flags = STREAM_TOSERVER | STREAM_START; + else if (u == (len - 1)) + flags = STREAM_TOSERVER | STREAM_EOF; + else + flags = STREAM_TOSERVER; r = AppLayerParserParse(NULL, alp_tctx, f, ALPROTO_HTTP1, flags, (uint8_t *)&httpbuf[u], 1); if (r != 0) { printf("toserver chunk %" PRIu32 " returned %" PRId32 ", expected" - " 0: ", u, r); + " 0: ", + u, r); goto end; } } @@ -6370,10 +6384,11 @@ libhtp:\n\ } htp_tx_t *tx = HTPStateGetTx(htp_state, 0); - if (tx == NULL || tx->request_method_number != HTP_M_GET || tx->request_protocol_number != HTP_PROTOCOL_1_1) - { + if (tx == NULL || tx->request_method_number != HTP_M_GET || + tx->request_protocol_number != HTP_PROTOCOL_1_1) { printf("expected method M_GET and got %s: , expected protocol " - "HTTP/1.1 and got %s \n", bstr_util_strdup_to_c(tx->request_method), + "HTTP/1.1 and got %s \n", + bstr_util_strdup_to_c(tx->request_method), bstr_util_strdup_to_c(tx->request_protocol)); goto end; } @@ -6407,20 +6422,21 @@ static int HTPParserTest16(void) int result = 0; Flow *f = NULL; TcpSession ssn; - HtpState *htp_state = NULL; + HtpState *htp_state = NULL; int r = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); memset(&ssn, 0, sizeof(ssn)); uint8_t httpbuf[] = "GET\f/blah/\fHTTP/1.1\r\n" - "Host: myhost.lan\r\n" - "Connection: keep-alive\r\n" - "Accept: */*\r\n" - "User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.76 Safari/537.36\r\n" - "Referer: http://blah.lan/\r\n" - "Accept-Encoding: gzip,deflate,sdch\r\nAccept-Language: en-US,en;q=0.8\r\n" - "Cookie: blah\r\n\r\n"; + "Host: myhost.lan\r\n" + "Connection: keep-alive\r\n" + "Accept: */*\r\n" + "User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 " + "(KHTML, like Gecko) Chrome/29.0.1547.76 Safari/537.36\r\n" + "Referer: http://blah.lan/\r\n" + "Accept-Encoding: gzip,deflate,sdch\r\nAccept-Language: en-US,en;q=0.8\r\n" + "Cookie: blah\r\n\r\n"; size_t len = sizeof(httpbuf) - 1; f = UTHBuildFlow(AF_INET, "1.2.3.4", "1.2.3.5", 1024, 80); @@ -6432,7 +6448,7 @@ static int HTPParserTest16(void) StreamTcpInitConfig(true); - uint8_t flags = STREAM_TOSERVER|STREAM_START|STREAM_EOF; + uint8_t flags = STREAM_TOSERVER | STREAM_START | STREAM_EOF; r = AppLayerParserParse(NULL, alp_tctx, f, ALPROTO_HTTP1, flags, (uint8_t *)httpbuf, len); if (r != 0) { @@ -6447,16 +6463,17 @@ static int HTPParserTest16(void) } htp_tx_t *tx = HTPStateGetTx(htp_state, 0); - if (tx == NULL || tx->request_method_number != HTP_M_GET || tx->request_protocol_number != HTP_PROTOCOL_1_1) - { + if (tx == NULL || tx->request_method_number != HTP_M_GET || + tx->request_protocol_number != HTP_PROTOCOL_1_1) { printf("expected method M_GET and got %s: , expected protocol " - "HTTP/1.1 and got %s \n", tx ? bstr_util_strdup_to_c(tx->request_method) : "tx null", + "HTTP/1.1 and got %s \n", + tx ? bstr_util_strdup_to_c(tx->request_method) : "tx null", tx ? bstr_util_strdup_to_c(tx->request_protocol) : "tx null"); goto end; } #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION -//these events are disabled during fuzzing as they are too noisy and consume much resource + // these events are disabled during fuzzing as they are too noisy and consume much resource void *txtmp = AppLayerParserGetTx(IPPROTO_TCP, ALPROTO_HTTP1, f->alstate, 0); AppLayerDecoderEvents *decoder_events = AppLayerParserGetEventsByTx(IPPROTO_TCP, ALPROTO_HTTP1, txtmp); @@ -6529,7 +6546,7 @@ static int HTPParserTest20(void) FAIL_IF_NULL(http_state); htp_tx_t *tx = HTPStateGetTx(http_state, 0); FAIL_IF_NULL(tx); - htp_header_t *h = htp_table_get_index(tx->request_headers, 0, NULL); + htp_header_t *h = htp_table_get_index(tx->request_headers, 0, NULL); FAIL_IF_NULL(h); FAIL_IF(tx->request_method_number != HTP_M_GET); @@ -6588,7 +6605,7 @@ static int HTPParserTest21(void) FAIL_IF_NULL(http_state); htp_tx_t *tx = HTPStateGetTx(http_state, 0); FAIL_IF_NULL(tx); - htp_header_t *h = htp_table_get_index(tx->request_headers, 0, NULL); + htp_header_t *h = htp_table_get_index(tx->request_headers, 0, NULL); FAIL_IF_NULL(h); FAIL_IF(tx->request_method_number != HTP_M_GET); @@ -6613,7 +6630,7 @@ static int HTPParserTest22(void) "LD-agent\r\nHost: 209.205.196.16\r\n\r\n"; uint32_t httplen1 = sizeof(httpbuf1) - 1; /* minus the \0 */ uint8_t httpbuf2[] = "\r\n0000=0000000/ASDF3_31.zip, 456723\r\n" - "AAAAAA_0000=0000000/AAAAAAAA.zip,46725\r\n"; + "AAAAAA_0000=0000000/AAAAAAAA.zip,46725\r\n"; uint32_t httplen2 = sizeof(httpbuf2) - 1; /* minus the \0 */ TcpSession ssn; HtpState *http_state = NULL; @@ -6642,7 +6659,7 @@ static int HTPParserTest22(void) FAIL_IF_NULL(http_state); htp_tx_t *tx = HTPStateGetTx(http_state, 0); FAIL_IF_NULL(tx); - htp_header_t *h = htp_table_get_index(tx->request_headers, 0, NULL); + htp_header_t *h = htp_table_get_index(tx->request_headers, 0, NULL); FAIL_IF_NULL(h); FAIL_IF(tx->request_method_number != HTP_M_GET); @@ -6667,7 +6684,7 @@ static int HTPParserTest23(void) "LD-agent\r\nHost: 209.205.196.16\r\n\r\n"; uint32_t httplen1 = sizeof(httpbuf1) - 1; /* minus the \0 */ uint8_t httpbuf2[] = "HTTP0000=0000000/ASDF3_31.zip, 456723\r\n" - "AAAAAA_0000=0000000/AAAAAAAA.zip,46725\r\n"; + "AAAAAA_0000=0000000/AAAAAAAA.zip,46725\r\n"; uint32_t httplen2 = sizeof(httpbuf2) - 1; /* minus the \0 */ TcpSession ssn; HtpState *http_state = NULL; @@ -6696,7 +6713,7 @@ static int HTPParserTest23(void) FAIL_IF_NULL(http_state); htp_tx_t *tx = HTPStateGetTx(http_state, 0); FAIL_IF_NULL(tx); - htp_header_t *h = htp_table_get_index(tx->request_headers, 0, NULL); + htp_header_t *h = htp_table_get_index(tx->request_headers, 0, NULL); FAIL_IF_NULL(h); FAIL_IF(tx->request_method_number != HTP_M_GET); @@ -6721,7 +6738,7 @@ static int HTPParserTest24(void) "LD-agent\r\nHost: 209.205.196.16\r\n\r\n"; uint32_t httplen1 = sizeof(httpbuf1) - 1; /* minus the \0 */ uint8_t httpbuf2[] = "HTTP/1.0 0000=0000000/ASDF3_31.zip, 456723\r\n" - "AAAAAA_0000=0000000/AAAAAAAA.zip,46725\r\n"; + "AAAAAA_0000=0000000/AAAAAAAA.zip,46725\r\n"; uint32_t httplen2 = sizeof(httpbuf2) - 1; /* minus the \0 */ TcpSession ssn; HtpState *http_state = NULL; @@ -6750,7 +6767,7 @@ static int HTPParserTest24(void) FAIL_IF_NULL(http_state); htp_tx_t *tx = HTPStateGetTx(http_state, 0); FAIL_IF_NULL(tx); - htp_header_t *h = htp_table_get_index(tx->request_headers, 0, NULL); + htp_header_t *h = htp_table_get_index(tx->request_headers, 0, NULL); FAIL_IF_NULL(h); FAIL_IF(tx->request_method_number != HTP_M_GET); @@ -6900,13 +6917,15 @@ libhtp:\n\ Flow f; uint8_t httpbuf1[] = "GET /alice.txt HTTP/1.1\r\n\r\n"; uint32_t httplen1 = sizeof(httpbuf1) - 1; /* minus the \0 */ - uint8_t httpbuf2[] = "HTTP/1.1 200 OK\r\n" - "Content-Type: text/plain\r\n" - "Content-Length: 228\r\n\r\n" - "Alice was beginning to get very tired of sitting by her sister on the bank." - "Alice was beginning to get very tired of sitting by her sister on the bank."; + uint8_t httpbuf2[] = + "HTTP/1.1 200 OK\r\n" + "Content-Type: text/plain\r\n" + "Content-Length: 228\r\n\r\n" + "Alice was beginning to get very tired of sitting by her sister on the bank." + "Alice was beginning to get very tired of sitting by her sister on the bank."; uint32_t httplen2 = sizeof(httpbuf2) - 1; /* minus the \0 */ - uint8_t httpbuf3[] = "Alice was beginning to get very tired of sitting by her sister on the bank.\r\n\r\n"; + uint8_t httpbuf3[] = + "Alice was beginning to get very tired of sitting by her sister on the bank.\r\n\r\n"; uint32_t httplen3 = sizeof(httpbuf3) - 1; /* minus the \0 */ TcpSession ssn; HtpState *http_state = NULL; @@ -6928,11 +6947,11 @@ libhtp:\n\ p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOCLIENT; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -6942,8 +6961,8 @@ libhtp:\n\ de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(filestore; sid:1; rev:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(filestore; sid:1; rev:1;)"); FAIL_IF_NULL(de_ctx->sig_list); SigGroupBuild(de_ctx); @@ -7027,11 +7046,8 @@ static int HTPParserTest27(void) FAIL_IF(AppLayerHtpCheckDepth(&cfg, &tx_ud->request_body, tx_ud->tsflags)); - len = AppLayerHtpComputeChunkLength(tx_ud->request_body.content_len_so_far, - 0, - FileReassemblyDepth(), - tx_ud->tsflags, - len); + len = AppLayerHtpComputeChunkLength( + tx_ud->request_body.content_len_so_far, 0, FileReassemblyDepth(), tx_ud->tsflags, len); FAIL_IF(len != 1000); SCFree(tx_ud); diff --git a/src/app-layer-htp.h b/src/app-layer-htp.h index dee5c17e833e..965bc4acc329 100644 --- a/src/app-layer-htp.h +++ b/src/app-layer-htp.h @@ -39,31 +39,32 @@ #include /* default request body limit */ -#define HTP_CONFIG_DEFAULT_REQUEST_BODY_LIMIT 4096U -#define HTP_CONFIG_DEFAULT_RESPONSE_BODY_LIMIT 4096U -#define HTP_CONFIG_DEFAULT_REQUEST_INSPECT_MIN_SIZE 32768U -#define HTP_CONFIG_DEFAULT_REQUEST_INSPECT_WINDOW 4096U -#define HTP_CONFIG_DEFAULT_RESPONSE_INSPECT_MIN_SIZE 32768U -#define HTP_CONFIG_DEFAULT_RESPONSE_INSPECT_WINDOW 4096U -#define HTP_CONFIG_DEFAULT_FIELD_LIMIT_SOFT 9000U -#define HTP_CONFIG_DEFAULT_FIELD_LIMIT_HARD 18000U +#define HTP_CONFIG_DEFAULT_REQUEST_BODY_LIMIT 4096U +#define HTP_CONFIG_DEFAULT_RESPONSE_BODY_LIMIT 4096U +#define HTP_CONFIG_DEFAULT_REQUEST_INSPECT_MIN_SIZE 32768U +#define HTP_CONFIG_DEFAULT_REQUEST_INSPECT_WINDOW 4096U +#define HTP_CONFIG_DEFAULT_RESPONSE_INSPECT_MIN_SIZE 32768U +#define HTP_CONFIG_DEFAULT_RESPONSE_INSPECT_WINDOW 4096U +#define HTP_CONFIG_DEFAULT_FIELD_LIMIT_SOFT 9000U +#define HTP_CONFIG_DEFAULT_FIELD_LIMIT_HARD 18000U #define HTP_CONFIG_DEFAULT_LZMA_LAYERS 0U /* default libhtp lzma limit, taken from libhtp. */ -#define HTP_CONFIG_DEFAULT_LZMA_MEMLIMIT 1048576U -#define HTP_CONFIG_DEFAULT_COMPRESSION_BOMB_LIMIT 1048576U +#define HTP_CONFIG_DEFAULT_LZMA_MEMLIMIT 1048576U +#define HTP_CONFIG_DEFAULT_COMPRESSION_BOMB_LIMIT 1048576U // 100000 usec is 0.1 sec #define HTP_CONFIG_DEFAULT_COMPRESSION_TIME_LIMIT 100000 -#define HTP_CONFIG_DEFAULT_RANDOMIZE 1 -#define HTP_CONFIG_DEFAULT_RANDOMIZE_RANGE 10 +#define HTP_CONFIG_DEFAULT_RANDOMIZE 1 +#define HTP_CONFIG_DEFAULT_RANDOMIZE_RANGE 10 /** a boundary should be smaller in size */ -#define HTP_BOUNDARY_MAX 200U +#define HTP_BOUNDARY_MAX 200U // 0x0001 not used -#define HTP_FLAG_STATE_CLOSED_TS 0x0002 /**< Flag to indicate that HTTP - connection is closed */ +#define HTP_FLAG_STATE_CLOSED_TS \ + 0x0002 /**< Flag to indicate that HTTP \ + connection is closed */ #define HTP_FLAG_STATE_CLOSED_TC \ 0x0004 /**< Flag to indicate that HTTP \ connection is closed */ @@ -154,18 +155,18 @@ typedef struct HTPCfgDir_ { /** Need a linked list in order to keep track of these */ typedef struct HTPCfgRec_ { - htp_cfg_t *cfg; - struct HTPCfgRec_ *next; + htp_cfg_t *cfg; + struct HTPCfgRec_ *next; /** max size of the client body we inspect */ - int randomize; - int randomize_range; - int http_body_inline; + int randomize; + int randomize_range; + int http_body_inline; - int swf_decompression_enabled; - HtpSwfCompressType swf_compression_type; - uint32_t swf_decompress_depth; - uint32_t swf_compress_depth; + int swf_decompression_enabled; + HtpSwfCompressType swf_compression_type; + uint32_t swf_decompress_depth; + uint32_t swf_compress_depth; HTPCfgDir request; HTPCfgDir response; @@ -196,13 +197,13 @@ typedef struct HtpBody_ { uint64_t body_inspected; } HtpBody; -#define HTP_BOUNDARY_SET BIT_U8(1) /**< We have a boundary string */ -#define HTP_FILENAME_SET BIT_U8(3) /**< filename is registered in the flow */ -#define HTP_DONTSTORE BIT_U8(4) /**< not storing this file */ -#define HTP_STREAM_DEPTH_SET BIT_U8(5) /**< stream-depth is set */ +#define HTP_BOUNDARY_SET BIT_U8(1) /**< We have a boundary string */ +#define HTP_FILENAME_SET BIT_U8(3) /**< filename is registered in the flow */ +#define HTP_DONTSTORE BIT_U8(4) /**< not storing this file */ +#define HTP_STREAM_DEPTH_SET BIT_U8(5) /**< stream-depth is set */ /** Now the Body Chunks will be stored per transaction, at - * the tx user data */ + * the tx user data */ typedef struct HtpTxUserData_ { /* Body of the request (if any) */ uint8_t request_body_init; @@ -245,7 +246,7 @@ typedef struct HtpState_ { htp_connp_t *connp; /* Connection structure for each connection */ htp_conn_t *conn; - Flow *f; /**< Needed to retrieve the original flow when using HTPLib callbacks */ + Flow *f; /**< Needed to retrieve the original flow when using HTPLib callbacks */ uint64_t transaction_cnt; const struct HTPCfgRec_ *cfg; uint16_t flags; @@ -261,14 +262,14 @@ typedef struct HtpState_ { } HtpState; /** part of the engine needs the request body (e.g. http_client_body keyword) */ -#define HTP_REQUIRE_REQUEST_BODY (1 << 0) +#define HTP_REQUIRE_REQUEST_BODY (1 << 0) /** part of the engine needs the request body multipart header (e.g. filename * and / or fileext keywords) */ -#define HTP_REQUIRE_REQUEST_MULTIPART (1 << 1) +#define HTP_REQUIRE_REQUEST_MULTIPART (1 << 1) /** part of the engine needs the request file (e.g. log-file module) */ -#define HTP_REQUIRE_REQUEST_FILE (1 << 2) +#define HTP_REQUIRE_REQUEST_FILE (1 << 2) /** part of the engine needs the request body (e.g. file_data keyword) */ -#define HTP_REQUIRE_RESPONSE_BODY (1 << 3) +#define HTP_REQUIRE_RESPONSE_BODY (1 << 3) SC_ATOMIC_EXTERN(uint32_t, htp_config_flags); @@ -290,7 +291,7 @@ void HtpConfigRestoreBackup(void); void *HtpGetTxForH2(void *); -#endif /* __APP_LAYER_HTP_H__ */ +#endif /* __APP_LAYER_HTP_H__ */ /** * @} diff --git a/src/app-layer-http2.c b/src/app-layer-http2.c index dd0b3ec53f93..28b461871041 100644 --- a/src/app-layer-http2.c +++ b/src/app-layer-http2.c @@ -41,10 +41,8 @@ static int HTTP2RegisterPatternsForProtocolDetection(void) /* Using the 24 bytes pattern makes AppLayerTest09 fail/leak * The complete pattern is "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n" */ - if (AppLayerProtoDetectPMRegisterPatternCI(IPPROTO_TCP, ALPROTO_HTTP2, - "PRI * HTTP/2.0\r\n", - 16, 0, STREAM_TOSERVER) < 0) - { + if (AppLayerProtoDetectPMRegisterPatternCI( + IPPROTO_TCP, ALPROTO_HTTP2, "PRI * HTTP/2.0\r\n", 16, 0, STREAM_TOSERVER) < 0) { return -1; } return 0; @@ -67,7 +65,7 @@ void RegisterHTTP2Parsers(void) } #ifdef UNITTESTS - //TODOask HTTP2ParserRegisterTests(); + // TODOask HTTP2ParserRegisterTests(); #endif } diff --git a/src/app-layer-krb5.c b/src/app-layer-krb5.c index 7b2b63f11999..72b2bc394ae5 100644 --- a/src/app-layer-krb5.c +++ b/src/app-layer-krb5.c @@ -40,8 +40,7 @@ void RegisterKRB5Parsers(void) rs_register_krb5_parser(); #ifdef UNITTESTS - AppLayerParserRegisterProtocolUnittests(IPPROTO_TCP, ALPROTO_KRB5, - KRB5ParserRegisterTests); + AppLayerParserRegisterProtocolUnittests(IPPROTO_TCP, ALPROTO_KRB5, KRB5ParserRegisterTests); #endif } diff --git a/src/app-layer-modbus.c b/src/app-layer-modbus.c index 4625885ed288..416c63d15116 100644 --- a/src/app-layer-modbus.c +++ b/src/app-layer-modbus.c @@ -305,7 +305,8 @@ static uint8_t invalidLengthPDUWriteMultipleRegistersReq[] = { // clang-format on /** \test Send Modbus Read Coils request/response. */ -static int ModbusParserTest01(void) { +static int ModbusParserTest01(void) +{ AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); Flow f; TcpSession ssn; @@ -316,15 +317,14 @@ static int ModbusParserTest01(void) { memset(&ssn, 0, sizeof(ssn)); FLOW_INITIALIZE(&f); - f.protoctx = (void *)&ssn; - f.proto = IPPROTO_TCP; - f.alproto = ALPROTO_MODBUS; + f.protoctx = (void *)&ssn; + f.proto = IPPROTO_TCP; + f.alproto = ALPROTO_MODBUS; StreamTcpInitConfig(true); - int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_MODBUS, - STREAM_TOSERVER, readCoilsReq, - sizeof(readCoilsReq)); + int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_MODBUS, STREAM_TOSERVER, readCoilsReq, + sizeof(readCoilsReq)); FAIL_IF_NOT(r == 0); ModbusState *modbus_state = f.alstate; @@ -336,9 +336,8 @@ static int ModbusParserTest01(void) { FAIL_IF_NOT(rs_modbus_message_get_read_request_address(&request) == 0x7890); FAIL_IF_NOT(rs_modbus_message_get_read_request_quantity(&request) == 19); - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_MODBUS, - STREAM_TOCLIENT, readCoilsRsp, - sizeof(readCoilsRsp)); + r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_MODBUS, STREAM_TOCLIENT, readCoilsRsp, + sizeof(readCoilsRsp)); FAIL_IF_NOT(r == 0); FAIL_IF_NOT(rs_modbus_state_get_tx_count(modbus_state) == 1); @@ -350,7 +349,8 @@ static int ModbusParserTest01(void) { } /** \test Send Modbus Write Multiple registers request/response. */ -static int ModbusParserTest02(void) { +static int ModbusParserTest02(void) +{ AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); Flow f; TcpSession ssn; @@ -361,15 +361,14 @@ static int ModbusParserTest02(void) { memset(&ssn, 0, sizeof(ssn)); FLOW_INITIALIZE(&f); - f.protoctx = (void *)&ssn; - f.proto = IPPROTO_TCP; - f.alproto = ALPROTO_MODBUS; + f.protoctx = (void *)&ssn; + f.proto = IPPROTO_TCP; + f.alproto = ALPROTO_MODBUS; StreamTcpInitConfig(true); - int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_MODBUS, - STREAM_TOSERVER, writeMultipleRegistersReq, - sizeof(writeMultipleRegistersReq)); + int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_MODBUS, STREAM_TOSERVER, + writeMultipleRegistersReq, sizeof(writeMultipleRegistersReq)); FAIL_IF_NOT(r == 0); ModbusState *modbus_state = f.alstate; @@ -389,9 +388,8 @@ static int ModbusParserTest02(void) { FAIL_IF_NOT(data[2] == 0x01); FAIL_IF_NOT(data[3] == 0x02); - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_MODBUS, - STREAM_TOCLIENT, writeMultipleRegistersRsp, - sizeof(writeMultipleRegistersRsp)); + r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_MODBUS, STREAM_TOCLIENT, + writeMultipleRegistersRsp, sizeof(writeMultipleRegistersRsp)); FAIL_IF_NOT(r == 0); FAIL_IF_NOT(rs_modbus_state_get_tx_count(modbus_state) == 1); @@ -403,7 +401,8 @@ static int ModbusParserTest02(void) { } /** \test Send Modbus Read/Write Multiple registers request/response with mismatch value. */ -static int ModbusParserTest03(void) { +static int ModbusParserTest03(void) +{ AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); DetectEngineThreadCtx *det_ctx = NULL; Flow f; @@ -421,15 +420,15 @@ static int ModbusParserTest03(void) { p = UTHBuildPacket(NULL, 0, IPPROTO_TCP); FLOW_INITIALIZE(&f); - f.alproto = ALPROTO_MODBUS; - f.protoctx = (void *)&ssn; - f.proto = IPPROTO_TCP; - f.alproto = ALPROTO_MODBUS; - f.flags |= FLOW_IPV4; + f.alproto = ALPROTO_MODBUS; + f.protoctx = (void *)&ssn; + f.proto = IPPROTO_TCP; + f.alproto = ALPROTO_MODBUS; + f.flags |= FLOW_IPV4; - p->flow = &f; - p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; - p->flowflags |= FLOW_PKT_TOSERVER | FLOW_PKT_ESTABLISHED; + p->flow = &f; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; + p->flowflags |= FLOW_PKT_TOSERVER | FLOW_PKT_ESTABLISHED; StreamTcpInitConfig(true); @@ -447,10 +446,8 @@ static int ModbusParserTest03(void) { SigGroupBuild(de_ctx); DetectEngineThreadCtxInit(&tv, (void *)de_ctx, (void *)&det_ctx); - int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_MODBUS, - STREAM_TOSERVER, - readWriteMultipleRegistersReq, - sizeof(readWriteMultipleRegistersReq)); + int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_MODBUS, STREAM_TOSERVER, + readWriteMultipleRegistersReq, sizeof(readWriteMultipleRegistersReq)); FAIL_IF_NOT(r == 0); ModbusState *modbus_state = f.alstate; @@ -475,9 +472,8 @@ static int ModbusParserTest03(void) { FAIL_IF_NOT(data[4] == 0x9A); FAIL_IF_NOT(data[5] == 0xBC); - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_MODBUS, - STREAM_TOCLIENT, readWriteMultipleRegistersRsp, - sizeof(readWriteMultipleRegistersRsp)); + r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_MODBUS, STREAM_TOCLIENT, + readWriteMultipleRegistersRsp, sizeof(readWriteMultipleRegistersRsp)); FAIL_IF_NOT(r == 0); FAIL_IF_NOT(rs_modbus_state_get_tx_count(modbus_state) == 1); @@ -501,7 +497,8 @@ static int ModbusParserTest03(void) { } /** \test Send Modbus Force Listen Only Mode request. */ -static int ModbusParserTest04(void) { +static int ModbusParserTest04(void) +{ AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); Flow f; TcpSession ssn; @@ -512,15 +509,14 @@ static int ModbusParserTest04(void) { memset(&ssn, 0, sizeof(ssn)); FLOW_INITIALIZE(&f); - f.protoctx = (void *)&ssn; - f.proto = IPPROTO_TCP; - f.alproto = ALPROTO_MODBUS; + f.protoctx = (void *)&ssn; + f.proto = IPPROTO_TCP; + f.alproto = ALPROTO_MODBUS; StreamTcpInitConfig(true); - int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_MODBUS, - STREAM_TOSERVER, forceListenOnlyMode, - sizeof(forceListenOnlyMode)); + int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_MODBUS, STREAM_TOSERVER, + forceListenOnlyMode, sizeof(forceListenOnlyMode)); FAIL_IF_NOT(r == 0); ModbusState *modbus_state = f.alstate; @@ -539,7 +535,8 @@ static int ModbusParserTest04(void) { } /** \test Send Modbus invalid Protocol version in request. */ -static int ModbusParserTest05(void) { +static int ModbusParserTest05(void) +{ AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); DetectEngineThreadCtx *det_ctx = NULL; Flow f; @@ -557,15 +554,15 @@ static int ModbusParserTest05(void) { p = UTHBuildPacket(NULL, 0, IPPROTO_TCP); FLOW_INITIALIZE(&f); - f.alproto = ALPROTO_MODBUS; - f.protoctx = (void *)&ssn; - f.proto = IPPROTO_TCP; - f.alproto = ALPROTO_MODBUS; - f.flags |= FLOW_IPV4; + f.alproto = ALPROTO_MODBUS; + f.protoctx = (void *)&ssn; + f.proto = IPPROTO_TCP; + f.alproto = ALPROTO_MODBUS; + f.flags |= FLOW_IPV4; - p->flow = &f; - p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; - p->flowflags |= FLOW_PKT_TOSERVER | FLOW_PKT_ESTABLISHED; + p->flow = &f; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; + p->flowflags |= FLOW_PKT_TOSERVER | FLOW_PKT_ESTABLISHED; StreamTcpInitConfig(true); @@ -583,9 +580,8 @@ static int ModbusParserTest05(void) { SigGroupBuild(de_ctx); DetectEngineThreadCtxInit(&tv, (void *)de_ctx, (void *)&det_ctx); - int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_MODBUS, - STREAM_TOSERVER, invalidProtocolIdReq, - sizeof(invalidProtocolIdReq)); + int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_MODBUS, STREAM_TOSERVER, + invalidProtocolIdReq, sizeof(invalidProtocolIdReq)); FAIL_IF_NOT(r == 0); ModbusState *modbus_state = f.alstate; @@ -610,7 +606,8 @@ static int ModbusParserTest05(void) { } /** \test Send Modbus unsolicited response. */ -static int ModbusParserTest06(void) { +static int ModbusParserTest06(void) +{ AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); DetectEngineThreadCtx *det_ctx = NULL; Flow f; @@ -628,15 +625,15 @@ static int ModbusParserTest06(void) { p = UTHBuildPacket(NULL, 0, IPPROTO_TCP); FLOW_INITIALIZE(&f); - f.alproto = ALPROTO_MODBUS; - f.protoctx = (void *)&ssn; - f.proto = IPPROTO_TCP; - f.alproto = ALPROTO_MODBUS; - f.flags |= FLOW_IPV4; + f.alproto = ALPROTO_MODBUS; + f.protoctx = (void *)&ssn; + f.proto = IPPROTO_TCP; + f.alproto = ALPROTO_MODBUS; + f.flags |= FLOW_IPV4; - p->flow = &f; - p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; - p->flowflags |= FLOW_PKT_TOSERVER | FLOW_PKT_ESTABLISHED; + p->flow = &f; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; + p->flowflags |= FLOW_PKT_TOSERVER | FLOW_PKT_ESTABLISHED; StreamTcpInitConfig(true); @@ -654,9 +651,8 @@ static int ModbusParserTest06(void) { SigGroupBuild(de_ctx); DetectEngineThreadCtxInit(&tv, (void *)de_ctx, (void *)&det_ctx); - int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_MODBUS, - STREAM_TOCLIENT, readCoilsRsp, - sizeof(readCoilsRsp)); + int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_MODBUS, STREAM_TOCLIENT, readCoilsRsp, + sizeof(readCoilsRsp)); FAIL_IF_NOT(r == 0); ModbusState *modbus_state = f.alstate; @@ -681,7 +677,8 @@ static int ModbusParserTest06(void) { } /** \test Send Modbus invalid Length request. */ -static int ModbusParserTest07(void) { +static int ModbusParserTest07(void) +{ AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); DetectEngineThreadCtx *det_ctx = NULL; Flow f; @@ -699,15 +696,15 @@ static int ModbusParserTest07(void) { p = UTHBuildPacket(NULL, 0, IPPROTO_TCP); FLOW_INITIALIZE(&f); - f.alproto = ALPROTO_MODBUS; - f.protoctx = (void *)&ssn; - f.proto = IPPROTO_TCP; - f.alproto = ALPROTO_MODBUS; - f.flags |= FLOW_IPV4; + f.alproto = ALPROTO_MODBUS; + f.protoctx = (void *)&ssn; + f.proto = IPPROTO_TCP; + f.alproto = ALPROTO_MODBUS; + f.flags |= FLOW_IPV4; - p->flow = &f; - p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; - p->flowflags |= FLOW_PKT_TOSERVER | FLOW_PKT_ESTABLISHED; + p->flow = &f; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; + p->flowflags |= FLOW_PKT_TOSERVER | FLOW_PKT_ESTABLISHED; StreamTcpInitConfig(true); @@ -725,10 +722,8 @@ static int ModbusParserTest07(void) { SigGroupBuild(de_ctx); DetectEngineThreadCtxInit(&tv, (void *)de_ctx, (void *)&det_ctx); - int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_MODBUS, - STREAM_TOSERVER, - invalidLengthWriteMultipleRegistersReq, - sizeof(invalidLengthWriteMultipleRegistersReq)); + int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_MODBUS, STREAM_TOSERVER, + invalidLengthWriteMultipleRegistersReq, sizeof(invalidLengthWriteMultipleRegistersReq)); FAIL_IF_NOT(r == 1); ModbusState *modbus_state = f.alstate; @@ -753,7 +748,8 @@ static int ModbusParserTest07(void) { } /** \test Send Modbus Read Coils request and error response with Exception code invalid. */ -static int ModbusParserTest08(void) { +static int ModbusParserTest08(void) +{ AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); DetectEngineThreadCtx *det_ctx = NULL; Flow f; @@ -771,15 +767,15 @@ static int ModbusParserTest08(void) { p = UTHBuildPacket(NULL, 0, IPPROTO_TCP); FLOW_INITIALIZE(&f); - f.alproto = ALPROTO_MODBUS; - f.protoctx = (void *)&ssn; - f.proto = IPPROTO_TCP; - f.alproto = ALPROTO_MODBUS; - f.flags |= FLOW_IPV4; + f.alproto = ALPROTO_MODBUS; + f.protoctx = (void *)&ssn; + f.proto = IPPROTO_TCP; + f.alproto = ALPROTO_MODBUS; + f.flags |= FLOW_IPV4; - p->flow = &f; - p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; - p->flowflags |= FLOW_PKT_TOSERVER | FLOW_PKT_ESTABLISHED; + p->flow = &f; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; + p->flowflags |= FLOW_PKT_TOSERVER | FLOW_PKT_ESTABLISHED; StreamTcpInitConfig(true); @@ -797,9 +793,8 @@ static int ModbusParserTest08(void) { SigGroupBuild(de_ctx); DetectEngineThreadCtxInit(&tv, (void *)de_ctx, (void *)&det_ctx); - int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_MODBUS, - STREAM_TOSERVER, readCoilsReq, - sizeof(readCoilsReq)); + int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_MODBUS, STREAM_TOSERVER, readCoilsReq, + sizeof(readCoilsReq)); FAIL_IF_NOT(r == 0); ModbusState *modbus_state = f.alstate; @@ -812,9 +807,8 @@ static int ModbusParserTest08(void) { FAIL_IF_NOT(rs_modbus_message_get_read_request_address(&request) == 0x7890); FAIL_IF_NOT(rs_modbus_message_get_read_request_quantity(&request) == 19); - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_MODBUS, - STREAM_TOCLIENT, readCoilsErrorRsp, - sizeof(readCoilsErrorRsp)); + r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_MODBUS, STREAM_TOCLIENT, readCoilsErrorRsp, + sizeof(readCoilsErrorRsp)); FAIL_IF_NOT(r == 0); FAIL_IF_NOT(rs_modbus_state_get_tx_count(modbus_state) == 1); @@ -838,13 +832,14 @@ static int ModbusParserTest08(void) { } /** \test Modbus fragmentation - 1 ADU over 2 TCP packets. */ -static int ModbusParserTest09(void) { +static int ModbusParserTest09(void) +{ AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); Flow f; TcpSession ssn; - uint32_t input_len = sizeof(readCoilsReq), part2_len = 3; - uint8_t *input = readCoilsReq; + uint32_t input_len = sizeof(readCoilsReq), part2_len = 3; + uint8_t *input = readCoilsReq; FAIL_IF_NULL(alp_tctx); @@ -852,18 +847,17 @@ static int ModbusParserTest09(void) { memset(&ssn, 0, sizeof(ssn)); FLOW_INITIALIZE(&f); - f.protoctx = (void *)&ssn; - f.proto = IPPROTO_TCP; - f.alproto = ALPROTO_MODBUS; + f.protoctx = (void *)&ssn; + f.proto = IPPROTO_TCP; + f.alproto = ALPROTO_MODBUS; StreamTcpInitConfig(true); - int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_MODBUS, - STREAM_TOSERVER, input, input_len - part2_len); + int r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_MODBUS, STREAM_TOSERVER, input, input_len - part2_len); FAIL_IF_NOT(r == 1); - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_MODBUS, - STREAM_TOSERVER, input, input_len); + r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_MODBUS, STREAM_TOSERVER, input, input_len); FAIL_IF_NOT(r == 0); ModbusState *modbus_state = f.alstate; @@ -880,12 +874,11 @@ static int ModbusParserTest09(void) { part2_len = 10; input = readCoilsRsp; - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_MODBUS, - STREAM_TOCLIENT, input, input_len - part2_len); + r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_MODBUS, STREAM_TOCLIENT, input, input_len - part2_len); FAIL_IF_NOT(r == 1); - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_MODBUS, - STREAM_TOCLIENT, input, input_len); + r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_MODBUS, STREAM_TOCLIENT, input, input_len); FAIL_IF_NOT(r == 0); FAIL_IF_NOT(rs_modbus_state_get_tx_count(modbus_state) == 1); @@ -897,9 +890,10 @@ static int ModbusParserTest09(void) { } /** \test Modbus fragmentation - 2 ADU in 1 TCP packet. */ -static int ModbusParserTest10(void) { - uint32_t input_len = sizeof(readCoilsReq) + sizeof(writeMultipleRegistersReq); - uint8_t *input, *ptr; +static int ModbusParserTest10(void) +{ + uint32_t input_len = sizeof(readCoilsReq) + sizeof(writeMultipleRegistersReq); + uint8_t *input, *ptr; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); Flow f; @@ -907,24 +901,25 @@ static int ModbusParserTest10(void) { FAIL_IF_NULL(alp_tctx); - input = (uint8_t *) SCMalloc (input_len * sizeof(uint8_t)); + input = (uint8_t *)SCMalloc(input_len * sizeof(uint8_t)); FAIL_IF_NULL(input); memcpy(input, readCoilsReq, sizeof(readCoilsReq)); - memcpy(input + sizeof(readCoilsReq), writeMultipleRegistersReq, sizeof(writeMultipleRegistersReq)); + memcpy(input + sizeof(readCoilsReq), writeMultipleRegistersReq, + sizeof(writeMultipleRegistersReq)); memset(&f, 0, sizeof(f)); memset(&ssn, 0, sizeof(ssn)); FLOW_INITIALIZE(&f); - f.protoctx = (void *)&ssn; - f.proto = IPPROTO_TCP; - f.alproto = ALPROTO_MODBUS; + f.protoctx = (void *)&ssn; + f.proto = IPPROTO_TCP; + f.alproto = ALPROTO_MODBUS; StreamTcpInitConfig(true); - int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_MODBUS, - STREAM_TOSERVER, input, input_len); + int r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_MODBUS, STREAM_TOSERVER, input, input_len); FAIL_IF_NOT(r == 0); ModbusState *modbus_state = f.alstate; @@ -949,12 +944,13 @@ static int ModbusParserTest10(void) { input_len = sizeof(readCoilsRsp) + sizeof(writeMultipleRegistersRsp); - ptr = (uint8_t *) SCRealloc (input, input_len * sizeof(uint8_t)); + ptr = (uint8_t *)SCRealloc(input, input_len * sizeof(uint8_t)); FAIL_IF_NULL(ptr); input = ptr; memcpy(input, readCoilsRsp, sizeof(readCoilsRsp)); - memcpy(input + sizeof(readCoilsRsp), writeMultipleRegistersRsp, sizeof(writeMultipleRegistersRsp)); + memcpy(input + sizeof(readCoilsRsp), writeMultipleRegistersRsp, + sizeof(writeMultipleRegistersRsp)); r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_MODBUS, STREAM_TOCLIENT, input, input_len); FAIL_IF_NOT(r == 0); @@ -967,7 +963,8 @@ static int ModbusParserTest10(void) { } /** \test Send Modbus exceed Length request. */ -static int ModbusParserTest11(void) { +static int ModbusParserTest11(void) +{ AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); DetectEngineThreadCtx *det_ctx = NULL; Flow f; @@ -993,15 +990,15 @@ static int ModbusParserTest11(void) { p = UTHBuildPacket(NULL, 0, IPPROTO_TCP); FLOW_INITIALIZE(&f); - f.alproto = ALPROTO_MODBUS; - f.protoctx = (void *)&ssn; - f.proto = IPPROTO_TCP; - f.alproto = ALPROTO_MODBUS; - f.flags |= FLOW_IPV4; + f.alproto = ALPROTO_MODBUS; + f.protoctx = (void *)&ssn; + f.proto = IPPROTO_TCP; + f.alproto = ALPROTO_MODBUS; + f.flags |= FLOW_IPV4; - p->flow = &f; - p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; - p->flowflags |= FLOW_PKT_TOSERVER | FLOW_PKT_ESTABLISHED; + p->flow = &f; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; + p->flowflags |= FLOW_PKT_TOSERVER | FLOW_PKT_ESTABLISHED; StreamTcpInitConfig(true); @@ -1045,7 +1042,8 @@ static int ModbusParserTest11(void) { } /** \test Send Modbus invalid PDU Length. */ -static int ModbusParserTest12(void) { +static int ModbusParserTest12(void) +{ AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); DetectEngineThreadCtx *det_ctx = NULL; Flow f; @@ -1063,15 +1061,15 @@ static int ModbusParserTest12(void) { p = UTHBuildPacket(NULL, 0, IPPROTO_TCP); FLOW_INITIALIZE(&f); - f.alproto = ALPROTO_MODBUS; - f.protoctx = (void *)&ssn; - f.proto = IPPROTO_TCP; - f.alproto = ALPROTO_MODBUS; - f.flags |= FLOW_IPV4; + f.alproto = ALPROTO_MODBUS; + f.protoctx = (void *)&ssn; + f.proto = IPPROTO_TCP; + f.alproto = ALPROTO_MODBUS; + f.flags |= FLOW_IPV4; - p->flow = &f; - p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; - p->flowflags |= FLOW_PKT_TOSERVER | FLOW_PKT_ESTABLISHED; + p->flow = &f; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; + p->flowflags |= FLOW_PKT_TOSERVER | FLOW_PKT_ESTABLISHED; StreamTcpInitConfig(true); @@ -1089,10 +1087,9 @@ static int ModbusParserTest12(void) { SigGroupBuild(de_ctx); DetectEngineThreadCtxInit(&tv, (void *)de_ctx, (void *)&det_ctx); - int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_MODBUS, - STREAM_TOSERVER, - invalidLengthPDUWriteMultipleRegistersReq, - sizeof(invalidLengthPDUWriteMultipleRegistersReq)); + int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_MODBUS, STREAM_TOSERVER, + invalidLengthPDUWriteMultipleRegistersReq, + sizeof(invalidLengthPDUWriteMultipleRegistersReq)); FAIL_IF_NOT(r == 0); ModbusState *modbus_state = f.alstate; @@ -1117,7 +1114,8 @@ static int ModbusParserTest12(void) { } /** \test Send Modbus Mask Write register request/response. */ -static int ModbusParserTest13(void) { +static int ModbusParserTest13(void) +{ AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); Flow f; TcpSession ssn; @@ -1128,15 +1126,14 @@ static int ModbusParserTest13(void) { memset(&ssn, 0, sizeof(ssn)); FLOW_INITIALIZE(&f); - f.protoctx = (void *)&ssn; - f.proto = IPPROTO_TCP; - f.alproto = ALPROTO_MODBUS; + f.protoctx = (void *)&ssn; + f.proto = IPPROTO_TCP; + f.alproto = ALPROTO_MODBUS; StreamTcpInitConfig(true); - int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_MODBUS, - STREAM_TOSERVER, maskWriteRegisterReq, - sizeof(maskWriteRegisterReq)); + int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_MODBUS, STREAM_TOSERVER, + maskWriteRegisterReq, sizeof(maskWriteRegisterReq)); FAIL_IF_NOT(r == 0); ModbusState *modbus_state = f.alstate; @@ -1149,9 +1146,8 @@ static int ModbusParserTest13(void) { FAIL_IF_NOT(rs_modbus_message_get_and_mask(&request) == 0x00F2); FAIL_IF_NOT(rs_modbus_message_get_or_mask(&request) == 0x0025); - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_MODBUS, - STREAM_TOCLIENT, maskWriteRegisterRsp, - sizeof(maskWriteRegisterRsp)); + r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_MODBUS, STREAM_TOCLIENT, + maskWriteRegisterRsp, sizeof(maskWriteRegisterRsp)); FAIL_IF_NOT(r == 0); FAIL_IF_NOT(rs_modbus_state_get_tx_count(modbus_state) == 1); @@ -1163,7 +1159,8 @@ static int ModbusParserTest13(void) { } /** \test Send Modbus Write single register request/response. */ -static int ModbusParserTest14(void) { +static int ModbusParserTest14(void) +{ AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); Flow f; TcpSession ssn; @@ -1174,15 +1171,14 @@ static int ModbusParserTest14(void) { memset(&ssn, 0, sizeof(ssn)); FLOW_INITIALIZE(&f); - f.protoctx = (void *)&ssn; - f.proto = IPPROTO_TCP; - f.alproto = ALPROTO_MODBUS; + f.protoctx = (void *)&ssn; + f.proto = IPPROTO_TCP; + f.alproto = ALPROTO_MODBUS; StreamTcpInitConfig(true); - int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_MODBUS, - STREAM_TOSERVER, writeSingleRegisterReq, - sizeof(writeSingleRegisterReq)); + int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_MODBUS, STREAM_TOSERVER, + writeSingleRegisterReq, sizeof(writeSingleRegisterReq)); FAIL_IF_NOT(r == 0); ModbusState *modbus_state = f.alstate; @@ -1195,9 +1191,8 @@ static int ModbusParserTest14(void) { FAIL_IF_NOT(rs_modbus_message_get_write_address(&request) == 0x0001); FAIL_IF_NOT(rs_modbus_message_get_write_data(&request) == 0x0003); - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_MODBUS, - STREAM_TOCLIENT, writeSingleRegisterRsp, - sizeof(writeSingleRegisterRsp)); + r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_MODBUS, STREAM_TOCLIENT, + writeSingleRegisterRsp, sizeof(writeSingleRegisterRsp)); FAIL_IF_NOT(r == 0); FAIL_IF_NOT(rs_modbus_state_get_tx_count(modbus_state) == 1); @@ -1209,7 +1204,8 @@ static int ModbusParserTest14(void) { } /** \test Send invalid Modbus Mask Write register request. */ -static int ModbusParserTest15(void) { +static int ModbusParserTest15(void) +{ AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); DetectEngineThreadCtx *det_ctx = NULL; Flow f; @@ -1227,15 +1223,15 @@ static int ModbusParserTest15(void) { p = UTHBuildPacket(NULL, 0, IPPROTO_TCP); FLOW_INITIALIZE(&f); - f.alproto = ALPROTO_MODBUS; - f.protoctx = (void *)&ssn; - f.proto = IPPROTO_TCP; - f.alproto = ALPROTO_MODBUS; - f.flags |= FLOW_IPV4; + f.alproto = ALPROTO_MODBUS; + f.protoctx = (void *)&ssn; + f.proto = IPPROTO_TCP; + f.alproto = ALPROTO_MODBUS; + f.flags |= FLOW_IPV4; - p->flow = &f; - p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; - p->flowflags |= FLOW_PKT_TOSERVER | FLOW_PKT_ESTABLISHED; + p->flow = &f; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; + p->flowflags |= FLOW_PKT_TOSERVER | FLOW_PKT_ESTABLISHED; StreamTcpInitConfig(true); @@ -1253,9 +1249,8 @@ static int ModbusParserTest15(void) { SigGroupBuild(de_ctx); DetectEngineThreadCtxInit(&tv, (void *)de_ctx, (void *)&det_ctx); - int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_MODBUS, - STREAM_TOSERVER, invalidMaskWriteRegisterReq, - sizeof(invalidMaskWriteRegisterReq)); + int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_MODBUS, STREAM_TOSERVER, + invalidMaskWriteRegisterReq, sizeof(invalidMaskWriteRegisterReq)); FAIL_IF_NOT(r == 0); ModbusState *modbus_state = f.alstate; @@ -1271,9 +1266,8 @@ static int ModbusParserTest15(void) { FAIL_IF_NOT(PacketAlertCheck(p, 1)); - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_MODBUS, - STREAM_TOCLIENT, maskWriteRegisterRsp, - sizeof(maskWriteRegisterRsp)); + r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_MODBUS, STREAM_TOCLIENT, + maskWriteRegisterRsp, sizeof(maskWriteRegisterRsp)); FAIL_IF_NOT(r == 0); FAIL_IF_NOT(rs_modbus_state_get_tx_count(modbus_state) == 1); @@ -1296,7 +1290,8 @@ static int ModbusParserTest15(void) { } /** \test Send invalid Modbus Mask Write register request. */ -static int ModbusParserTest16(void) { +static int ModbusParserTest16(void) +{ AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); DetectEngineThreadCtx *det_ctx = NULL; Flow f; @@ -1314,15 +1309,15 @@ static int ModbusParserTest16(void) { p = UTHBuildPacket(NULL, 0, IPPROTO_TCP); FLOW_INITIALIZE(&f); - f.alproto = ALPROTO_MODBUS; - f.protoctx = (void *)&ssn; - f.proto = IPPROTO_TCP; - f.alproto = ALPROTO_MODBUS; - f.flags |= FLOW_IPV4; + f.alproto = ALPROTO_MODBUS; + f.protoctx = (void *)&ssn; + f.proto = IPPROTO_TCP; + f.alproto = ALPROTO_MODBUS; + f.flags |= FLOW_IPV4; - p->flow = &f; - p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; - p->flowflags |= FLOW_PKT_TOSERVER | FLOW_PKT_ESTABLISHED; + p->flow = &f; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; + p->flowflags |= FLOW_PKT_TOSERVER | FLOW_PKT_ESTABLISHED; StreamTcpInitConfig(true); @@ -1340,10 +1335,8 @@ static int ModbusParserTest16(void) { SigGroupBuild(de_ctx); DetectEngineThreadCtxInit(&tv, (void *)de_ctx, (void *)&det_ctx); - int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_MODBUS, - STREAM_TOSERVER, - invalidWriteSingleRegisterReq, - sizeof(invalidWriteSingleRegisterReq)); + int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_MODBUS, STREAM_TOSERVER, + invalidWriteSingleRegisterReq, sizeof(invalidWriteSingleRegisterReq)); FAIL_IF_NOT(r == 0); ModbusState *modbus_state = f.alstate; @@ -1364,9 +1357,8 @@ static int ModbusParserTest16(void) { FAIL_IF_NOT(PacketAlertCheck(p, 1)); - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_MODBUS, - STREAM_TOCLIENT, writeSingleRegisterRsp, - sizeof(writeSingleRegisterRsp)); + r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_MODBUS, STREAM_TOCLIENT, + writeSingleRegisterRsp, sizeof(writeSingleRegisterRsp)); FAIL_IF_NOT(r == 0); FAIL_IF_NOT(rs_modbus_state_get_tx_count(modbus_state) == 1); @@ -1386,10 +1378,12 @@ static int ModbusParserTest16(void) { StreamTcpFreeConfig(true); FLOW_DESTROY(&f); UTHFreePackets(&p, 1); - PASS;} + PASS; +} /** \test Checks if stream_depth is correct */ -static int ModbusParserTest17(void) { +static int ModbusParserTest17(void) +{ AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); Flow f; TcpSession ssn; @@ -1400,22 +1394,22 @@ static int ModbusParserTest17(void) { memset(&ssn, 0, sizeof(ssn)); FLOW_INITIALIZE(&f); - f.protoctx = (void *)&ssn; - f.proto = IPPROTO_TCP; - f.alproto = ALPROTO_MODBUS; + f.protoctx = (void *)&ssn; + f.proto = IPPROTO_TCP; + f.alproto = ALPROTO_MODBUS; StreamTcpInitConfig(true); - int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_MODBUS, STREAM_TOSERVER, - readCoilsReq, sizeof(readCoilsReq)); + int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_MODBUS, STREAM_TOSERVER, readCoilsReq, + sizeof(readCoilsReq)); FAIL_IF(r != 0); FAIL_IF(f.alstate == NULL); FAIL_IF(((TcpSession *)(f.protoctx))->reassembly_depth != MODBUS_CONFIG_DEFAULT_STREAM_DEPTH); - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_MODBUS, STREAM_TOCLIENT, - readCoilsRsp, sizeof(readCoilsRsp)); + r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_MODBUS, STREAM_TOCLIENT, readCoilsRsp, + sizeof(readCoilsRsp)); FAIL_IF(r != 0); FAIL_IF(((TcpSession *)(f.protoctx))->reassembly_depth != MODBUS_CONFIG_DEFAULT_STREAM_DEPTH); @@ -1427,13 +1421,14 @@ static int ModbusParserTest17(void) { } /*/ \test Checks if stream depth is correct over 2 TCP packets */ -static int ModbusParserTest18(void) { +static int ModbusParserTest18(void) +{ AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); Flow f; TcpSession ssn; - uint32_t input_len = sizeof(readCoilsReq), part2_len = 3; - uint8_t *input = readCoilsReq; + uint32_t input_len = sizeof(readCoilsReq), part2_len = 3; + uint8_t *input = readCoilsReq; FAIL_IF_NULL(alp_tctx); @@ -1441,20 +1436,19 @@ static int ModbusParserTest18(void) { memset(&ssn, 0, sizeof(ssn)); FLOW_INITIALIZE(&f); - f.protoctx = (void *)&ssn; - f.proto = IPPROTO_TCP; - f.alproto = ALPROTO_MODBUS; + f.protoctx = (void *)&ssn; + f.proto = IPPROTO_TCP; + f.alproto = ALPROTO_MODBUS; StreamTcpInitConfig(true); - int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_MODBUS, STREAM_TOSERVER, - input, input_len - part2_len); + int r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_MODBUS, STREAM_TOSERVER, input, input_len - part2_len); FAIL_IF(r != 1); FAIL_IF(((TcpSession *)(f.protoctx))->reassembly_depth != MODBUS_CONFIG_DEFAULT_STREAM_DEPTH); - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_MODBUS, STREAM_TOSERVER, - input, input_len); + r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_MODBUS, STREAM_TOSERVER, input, input_len); FAIL_IF(r != 0); FAIL_IF(((TcpSession *)(f.protoctx))->reassembly_depth != MODBUS_CONFIG_DEFAULT_STREAM_DEPTH); @@ -1465,14 +1459,13 @@ static int ModbusParserTest18(void) { part2_len = 10; input = readCoilsRsp; - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_MODBUS, STREAM_TOCLIENT, - input, input_len - part2_len); + r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_MODBUS, STREAM_TOCLIENT, input, input_len - part2_len); FAIL_IF(r != 1); FAIL_IF(((TcpSession *)(f.protoctx))->reassembly_depth != MODBUS_CONFIG_DEFAULT_STREAM_DEPTH); - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_MODBUS, STREAM_TOCLIENT, - input, input_len); + r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_MODBUS, STREAM_TOCLIENT, input, input_len); FAIL_IF(r != 0); FAIL_IF(((TcpSession *)(f.protoctx))->reassembly_depth != MODBUS_CONFIG_DEFAULT_STREAM_DEPTH); @@ -1484,7 +1477,8 @@ static int ModbusParserTest18(void) { } /** \test Send Modbus invalid function. */ -static int ModbusParserTest19(void) { +static int ModbusParserTest19(void) +{ AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); DetectEngineThreadCtx *det_ctx = NULL; Flow f; @@ -1502,15 +1496,15 @@ static int ModbusParserTest19(void) { p = UTHBuildPacket(NULL, 0, IPPROTO_TCP); FLOW_INITIALIZE(&f); - f.alproto = ALPROTO_MODBUS; - f.protoctx = (void *)&ssn; - f.proto = IPPROTO_TCP; - f.alproto = ALPROTO_MODBUS; - f.flags |= FLOW_IPV4; + f.alproto = ALPROTO_MODBUS; + f.protoctx = (void *)&ssn; + f.proto = IPPROTO_TCP; + f.alproto = ALPROTO_MODBUS; + f.flags |= FLOW_IPV4; - p->flow = &f; - p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; - p->flowflags |= FLOW_PKT_TOSERVER | FLOW_PKT_ESTABLISHED; + p->flow = &f; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; + p->flowflags |= FLOW_PKT_TOSERVER | FLOW_PKT_ESTABLISHED; StreamTcpInitConfig(true); @@ -1528,10 +1522,8 @@ static int ModbusParserTest19(void) { SigGroupBuild(de_ctx); DetectEngineThreadCtxInit(&tv, (void *)de_ctx, (void *)&det_ctx); - int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_MODBUS, - STREAM_TOSERVER, - invalidFunctionCode, - sizeof(invalidFunctionCode)); + int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_MODBUS, STREAM_TOSERVER, + invalidFunctionCode, sizeof(invalidFunctionCode)); FAIL_IF_NOT(r == 0); ModbusState *modbus_state = f.alstate; @@ -1556,45 +1548,34 @@ static int ModbusParserTest19(void) { } #endif /* UNITTESTS */ -void ModbusParserRegisterTests(void) { +void ModbusParserRegisterTests(void) +{ #ifdef UNITTESTS - UtRegisterTest("ModbusParserTest01 - Modbus Read Coils request", - ModbusParserTest01); - UtRegisterTest("ModbusParserTest02 - Modbus Write Multiple registers request", - ModbusParserTest02); + UtRegisterTest("ModbusParserTest01 - Modbus Read Coils request", ModbusParserTest01); + UtRegisterTest( + "ModbusParserTest02 - Modbus Write Multiple registers request", ModbusParserTest02); UtRegisterTest("ModbusParserTest03 - Modbus Read/Write Multiple registers request", - ModbusParserTest03); - UtRegisterTest("ModbusParserTest04 - Modbus Force Listen Only Mode request", - ModbusParserTest04); - UtRegisterTest("ModbusParserTest05 - Modbus invalid Protocol version", - ModbusParserTest05); - UtRegisterTest("ModbusParserTest06 - Modbus unsolicited response", - ModbusParserTest06); - UtRegisterTest("ModbusParserTest07 - Modbus invalid Length request", - ModbusParserTest07); - UtRegisterTest("ModbusParserTest08 - Modbus Exception code invalid", - ModbusParserTest08); + ModbusParserTest03); + UtRegisterTest( + "ModbusParserTest04 - Modbus Force Listen Only Mode request", ModbusParserTest04); + UtRegisterTest("ModbusParserTest05 - Modbus invalid Protocol version", ModbusParserTest05); + UtRegisterTest("ModbusParserTest06 - Modbus unsolicited response", ModbusParserTest06); + UtRegisterTest("ModbusParserTest07 - Modbus invalid Length request", ModbusParserTest07); + UtRegisterTest("ModbusParserTest08 - Modbus Exception code invalid", ModbusParserTest08); UtRegisterTest("ModbusParserTest09 - Modbus fragmentation - 1 ADU in 2 TCP packets", - ModbusParserTest09); + ModbusParserTest09); UtRegisterTest("ModbusParserTest10 - Modbus fragmentation - 2 ADU in 1 TCP packet", - ModbusParserTest10); - UtRegisterTest("ModbusParserTest11 - Modbus exceeded Length request", - ModbusParserTest11); - UtRegisterTest("ModbusParserTest12 - Modbus invalid PDU Length", - ModbusParserTest12); - UtRegisterTest("ModbusParserTest13 - Modbus Mask Write register request", - ModbusParserTest13); - UtRegisterTest("ModbusParserTest14 - Modbus Write single register request", - ModbusParserTest14); - UtRegisterTest("ModbusParserTest15 - Modbus invalid Mask Write register request", - ModbusParserTest15); + ModbusParserTest10); + UtRegisterTest("ModbusParserTest11 - Modbus exceeded Length request", ModbusParserTest11); + UtRegisterTest("ModbusParserTest12 - Modbus invalid PDU Length", ModbusParserTest12); + UtRegisterTest("ModbusParserTest13 - Modbus Mask Write register request", ModbusParserTest13); + UtRegisterTest("ModbusParserTest14 - Modbus Write single register request", ModbusParserTest14); + UtRegisterTest( + "ModbusParserTest15 - Modbus invalid Mask Write register request", ModbusParserTest15); UtRegisterTest("ModbusParserTest16 - Modbus invalid Write single register request", - ModbusParserTest16); - UtRegisterTest("ModbusParserTest17 - Modbus stream depth", - ModbusParserTest17); - UtRegisterTest("ModbusParserTest18 - Modbus stream depth in 2 TCP packets", - ModbusParserTest18); - UtRegisterTest("ModbusParserTest19 - Modbus invalid Function code", - ModbusParserTest19); + ModbusParserTest16); + UtRegisterTest("ModbusParserTest17 - Modbus stream depth", ModbusParserTest17); + UtRegisterTest("ModbusParserTest18 - Modbus stream depth in 2 TCP packets", ModbusParserTest18); + UtRegisterTest("ModbusParserTest19 - Modbus invalid Function code", ModbusParserTest19); #endif /* UNITTESTS */ } diff --git a/src/app-layer-mqtt.c b/src/app-layer-mqtt.c index 96b4cc27afcc..da1386c6ea7a 100644 --- a/src/app-layer-mqtt.c +++ b/src/app-layer-mqtt.c @@ -52,8 +52,7 @@ void RegisterMQTTParsers(void) rs_mqtt_register_parser(max_msg_len); } #ifdef UNITTESTS - AppLayerParserRegisterProtocolUnittests(IPPROTO_TCP, ALPROTO_MQTT, - MQTTParserRegisterTests); + AppLayerParserRegisterProtocolUnittests(IPPROTO_TCP, ALPROTO_MQTT, MQTTParserRegisterTests); #endif } diff --git a/src/app-layer-nfs-tcp.c b/src/app-layer-nfs-tcp.c index e02dd13788f6..d281e362d8a2 100644 --- a/src/app-layer-nfs-tcp.c +++ b/src/app-layer-nfs-tcp.c @@ -39,7 +39,6 @@ #include "rust.h" - static StreamingBufferConfig sbcfg = STREAMING_BUFFER_CONFIG_INITIALIZER; static SuricataFileContext sfc = { &sbcfg }; diff --git a/src/app-layer-nfs-udp.c b/src/app-layer-nfs-udp.c index af90c11a758f..ece6812179a0 100644 --- a/src/app-layer-nfs-udp.c +++ b/src/app-layer-nfs-udp.c @@ -52,11 +52,9 @@ enum { }; SCEnumCharMap nfs_udp_decoder_event_table[] = { - {"EMPTY_MESSAGE", NFS_DECODER_EVENT_EMPTY_MESSAGE}, - { NULL, 0 } + { "EMPTY_MESSAGE", NFS_DECODER_EVENT_EMPTY_MESSAGE }, { NULL, 0 } }; - static StreamingBufferConfig sbcfg = STREAMING_BUFFER_CONFIG_INITIALIZER; static SuricataFileContext sfc = { &sbcfg }; @@ -66,8 +64,7 @@ void RegisterNFSUDPParsers(void) rs_nfs_udp_register_parser(); #ifdef UNITTESTS - AppLayerParserRegisterProtocolUnittests(IPPROTO_UDP, ALPROTO_NFS, - NFSUDPParserRegisterTests); + AppLayerParserRegisterProtocolUnittests(IPPROTO_UDP, ALPROTO_NFS, NFSUDPParserRegisterTests); #endif } diff --git a/src/app-layer-ntp.c b/src/app-layer-ntp.c index fa7f95d71124..b948e01dfa78 100644 --- a/src/app-layer-ntp.c +++ b/src/app-layer-ntp.c @@ -40,8 +40,7 @@ void RegisterNTPParsers(void) rs_register_ntp_parser(); #ifdef UNITTESTS - AppLayerParserRegisterProtocolUnittests(IPPROTO_UDP, ALPROTO_NTP, - NTPParserRegisterTests); + AppLayerParserRegisterProtocolUnittests(IPPROTO_UDP, ALPROTO_NTP, NTPParserRegisterTests); #endif } diff --git a/src/app-layer-parser.c b/src/app-layer-parser.c index f23329ec92f1..fb9592ce2c52 100644 --- a/src/app-layer-parser.c +++ b/src/app-layer-parser.c @@ -67,12 +67,10 @@ struct AppLayerParserThreadCtx_ { void *alproto_local_storage[FLOW_PROTO_MAX][ALPROTO_MAX]; }; - /** * \brief App layer protocol parser context. */ -typedef struct AppLayerParserProtoCtx_ -{ +typedef struct AppLayerParserProtoCtx_ { /* 0 - to_server, 1 - to_client. */ AppLayerParserFPtr Parser[2]; @@ -83,7 +81,7 @@ typedef struct AppLayerParserProtoCtx_ * STREAM_TOSERVER, STREAM_TOCLIENT */ uint8_t first_data_dir; - uint32_t logger_bits; /**< registered loggers for this proto */ + uint32_t logger_bits; /**< registered loggers for this proto */ void *(*StateAlloc)(void *, AppProto); void (*StateFree)(void *); @@ -103,10 +101,9 @@ typedef struct AppLayerParserProtoCtx_ AppLayerGetTxIteratorFunc StateGetTxIterator; int complete_ts; int complete_tc; - int (*StateGetEventInfoById)(int event_id, const char **event_name, - AppLayerEventType *event_type); - int (*StateGetEventInfo)(const char *event_name, - int *event_id, AppLayerEventType *event_type); + int (*StateGetEventInfoById)( + int event_id, const char **event_name, AppLayerEventType *event_type); + int (*StateGetEventInfo)(const char *event_name, int *event_id, AppLayerEventType *event_type); AppLayerStateData *(*GetStateData)(void *state); AppLayerTxData *(*GetTxData)(void *tx); @@ -213,7 +210,8 @@ static inline void AppLayerParserStreamTruncated(AppLayerParserState *pstate, co const AppProto alproto, void *alstate, const uint8_t direction); #ifdef UNITTESTS -void UTHAppLayerParserStateGetIds(void *ptr, uint64_t *i1, uint64_t *i2, uint64_t *log, uint64_t *min) +void UTHAppLayerParserStateGetIds( + void *ptr, uint64_t *i1, uint64_t *i2, uint64_t *log, uint64_t *min) { struct AppLayerParserState_ *s = ptr; *i1 = s->inspect_id[0]; @@ -242,7 +240,7 @@ AppLayerParserState *AppLayerParserStateAlloc(void) if (pstate == NULL) goto end; - end: +end: SCReturnPtr(pstate, "AppLayerParserState"); } @@ -272,8 +270,7 @@ void AppLayerParserPostStreamSetup(void) for (AppProto alproto = 0; alproto < ALPROTO_MAX; alproto++) { if (!(alp_ctx.ctxs[flow_proto][alproto].internal_flags & APP_LAYER_PARSER_INT_STREAM_DEPTH_SET)) { - alp_ctx.ctxs[flow_proto][alproto].stream_depth = - stream_config.reassembly_depth; + alp_ctx.ctxs[flow_proto][alproto].stream_depth = stream_config.reassembly_depth; } } } @@ -302,11 +299,11 @@ AppLayerParserThreadCtx *AppLayerParserThreadCtxAlloc(void) uint8_t ipproto = FlowGetReverseProtoMapping(flow_proto); tctx->alproto_local_storage[flow_proto][alproto] = - AppLayerParserGetProtocolParserLocalStorage(ipproto, alproto); + AppLayerParserGetProtocolParserLocalStorage(ipproto, alproto); } } - end: +end: SCReturnPtr(tctx, "void *"); } @@ -318,8 +315,8 @@ void AppLayerParserThreadCtxFree(AppLayerParserThreadCtx *tctx) for (AppProto alproto = 0; alproto < ALPROTO_MAX; alproto++) { uint8_t ipproto = FlowGetReverseProtoMapping(flow_proto); - AppLayerParserDestroyProtocolParserLocalStorage(ipproto, alproto, - tctx->alproto_local_storage[flow_proto][alproto]); + AppLayerParserDestroyProtocolParserLocalStorage( + ipproto, alproto, tctx->alproto_local_storage[flow_proto][alproto]); } } @@ -330,8 +327,7 @@ void AppLayerParserThreadCtxFree(AppLayerParserThreadCtx *tctx) /** \brief check if a parser is enabled in the config * Returns enabled always if: were running unittests */ -int AppLayerParserConfParserEnabled(const char *ipproto, - const char *alproto_name) +int AppLayerParserConfParserEnabled(const char *ipproto, const char *alproto_name) { SCEnter(); @@ -343,8 +339,7 @@ int AppLayerParserConfParserEnabled(const char *ipproto, if (RunmodeIsUnittests()) goto enabled; - r = snprintf(param, sizeof(param), "%s%s%s", "app-layer.protocols.", - alproto_name, ".enabled"); + r = snprintf(param, sizeof(param), "%s%s%s", "app-layer.protocols.", alproto_name, ".enabled"); if (r < 0) { FatalError("snprintf failure."); } else if (r > (int)sizeof(param)) { @@ -354,8 +349,8 @@ int AppLayerParserConfParserEnabled(const char *ipproto, node = ConfGetNode(param); if (node == NULL) { SCLogDebug("Entry for %s not found.", param); - r = snprintf(param, sizeof(param), "%s%s%s%s%s", "app-layer.protocols.", - alproto_name, ".", ipproto, ".enabled"); + r = snprintf(param, sizeof(param), "%s%s%s%s%s", "app-layer.protocols.", alproto_name, ".", + ipproto, ".enabled"); if (r < 0) { FatalError("snprintf failure."); } else if (r > (int)sizeof(param)) { @@ -380,39 +375,37 @@ int AppLayerParserConfParserEnabled(const char *ipproto, exit(EXIT_FAILURE); } - disabled: +disabled: enabled = 0; - enabled: +enabled: SCReturnInt(enabled); } /***** Parser related registration *****/ -int AppLayerParserRegisterParser(uint8_t ipproto, AppProto alproto, - uint8_t direction, - AppLayerParserFPtr Parser) +int AppLayerParserRegisterParser( + uint8_t ipproto, AppProto alproto, uint8_t direction, AppLayerParserFPtr Parser) { SCEnter(); - alp_ctx.ctxs[FlowGetProtoMapping(ipproto)][alproto]. - Parser[(direction & STREAM_TOSERVER) ? 0 : 1] = Parser; + alp_ctx.ctxs[FlowGetProtoMapping(ipproto)][alproto] + .Parser[(direction & STREAM_TOSERVER) ? 0 : 1] = Parser; SCReturnInt(0); } -void AppLayerParserRegisterParserAcceptableDataDirection(uint8_t ipproto, AppProto alproto, - uint8_t direction) +void AppLayerParserRegisterParserAcceptableDataDirection( + uint8_t ipproto, AppProto alproto, uint8_t direction) { SCEnter(); alp_ctx.ctxs[FlowGetProtoMapping(ipproto)][alproto].first_data_dir |= - (direction & (STREAM_TOSERVER | STREAM_TOCLIENT)); + (direction & (STREAM_TOSERVER | STREAM_TOCLIENT)); SCReturn; } -void AppLayerParserRegisterOptionFlags(uint8_t ipproto, AppProto alproto, - uint32_t flags) +void AppLayerParserRegisterOptionFlags(uint8_t ipproto, AppProto alproto, uint32_t flags) { SCEnter(); @@ -432,24 +425,19 @@ void AppLayerParserRegisterStateFuncs(uint8_t ipproto, AppProto alproto, { SCEnter(); - alp_ctx.ctxs[FlowGetProtoMapping(ipproto)][alproto].StateAlloc = - StateAlloc; - alp_ctx.ctxs[FlowGetProtoMapping(ipproto)][alproto].StateFree = - StateFree; + alp_ctx.ctxs[FlowGetProtoMapping(ipproto)][alproto].StateAlloc = StateAlloc; + alp_ctx.ctxs[FlowGetProtoMapping(ipproto)][alproto].StateFree = StateFree; SCReturn; } void AppLayerParserRegisterLocalStorageFunc(uint8_t ipproto, AppProto alproto, - void *(*LocalStorageAlloc)(void), - void (*LocalStorageFree)(void *)) + void *(*LocalStorageAlloc)(void), void (*LocalStorageFree)(void *)) { SCEnter(); - alp_ctx.ctxs[FlowGetProtoMapping(ipproto)][alproto].LocalStorageAlloc = - LocalStorageAlloc; - alp_ctx.ctxs[FlowGetProtoMapping(ipproto)][alproto].LocalStorageFree = - LocalStorageFree; + alp_ctx.ctxs[FlowGetProtoMapping(ipproto)][alproto].LocalStorageAlloc = LocalStorageAlloc; + alp_ctx.ctxs[FlowGetProtoMapping(ipproto)][alproto].LocalStorageFree = LocalStorageFree; SCReturn; } @@ -482,8 +470,8 @@ void AppLayerParserRegisterLogger(uint8_t ipproto, AppProto alproto) SCReturn; } -void AppLayerParserRegisterTruncateFunc(uint8_t ipproto, AppProto alproto, - void (*Truncate)(void *, uint8_t)) +void AppLayerParserRegisterTruncateFunc( + uint8_t ipproto, AppProto alproto, void (*Truncate)(void *, uint8_t)) { SCEnter(); @@ -493,51 +481,47 @@ void AppLayerParserRegisterTruncateFunc(uint8_t ipproto, AppProto alproto, } void AppLayerParserRegisterGetStateProgressFunc(uint8_t ipproto, AppProto alproto, - int (*StateGetProgress)(void *alstate, uint8_t direction)) + int (*StateGetProgress)(void *alstate, uint8_t direction)) { SCEnter(); - alp_ctx.ctxs[FlowGetProtoMapping(ipproto)][alproto]. - StateGetProgress = StateGetProgress; + alp_ctx.ctxs[FlowGetProtoMapping(ipproto)][alproto].StateGetProgress = StateGetProgress; SCReturn; } -void AppLayerParserRegisterTxFreeFunc(uint8_t ipproto, AppProto alproto, - void (*StateTransactionFree)(void *, uint64_t)) +void AppLayerParserRegisterTxFreeFunc( + uint8_t ipproto, AppProto alproto, void (*StateTransactionFree)(void *, uint64_t)) { SCEnter(); - alp_ctx.ctxs[FlowGetProtoMapping(ipproto)][alproto]. - StateTransactionFree = StateTransactionFree; + alp_ctx.ctxs[FlowGetProtoMapping(ipproto)][alproto].StateTransactionFree = StateTransactionFree; SCReturn; } -void AppLayerParserRegisterGetTxCnt(uint8_t ipproto, AppProto alproto, - uint64_t (*StateGetTxCnt)(void *alstate)) +void AppLayerParserRegisterGetTxCnt( + uint8_t ipproto, AppProto alproto, uint64_t (*StateGetTxCnt)(void *alstate)) { SCEnter(); - alp_ctx.ctxs[FlowGetProtoMapping(ipproto)][alproto]. - StateGetTxCnt = StateGetTxCnt; + alp_ctx.ctxs[FlowGetProtoMapping(ipproto)][alproto].StateGetTxCnt = StateGetTxCnt; SCReturn; } -void AppLayerParserRegisterGetTx(uint8_t ipproto, AppProto alproto, - void *(StateGetTx)(void *alstate, uint64_t tx_id)) +void AppLayerParserRegisterGetTx( + uint8_t ipproto, AppProto alproto, void *(StateGetTx)(void *alstate, uint64_t tx_id)) { SCEnter(); - alp_ctx.ctxs[FlowGetProtoMapping(ipproto)][alproto]. - StateGetTx = StateGetTx; + alp_ctx.ctxs[FlowGetProtoMapping(ipproto)][alproto].StateGetTx = StateGetTx; SCReturn; } -void AppLayerParserRegisterGetTxIterator(uint8_t ipproto, AppProto alproto, - AppLayerGetTxIteratorFunc Func) +void AppLayerParserRegisterGetTxIterator( + uint8_t ipproto, AppProto alproto, AppLayerGetTxIteratorFunc Func) { SCEnter(); alp_ctx.ctxs[FlowGetProtoMapping(ipproto)][alproto].StateGetTxIterator = Func; @@ -560,13 +544,13 @@ void AppLayerParserRegisterStateProgressCompletionStatus( } void AppLayerParserRegisterGetEventInfoById(uint8_t ipproto, AppProto alproto, - int (*StateGetEventInfoById)(int event_id, const char **event_name, - AppLayerEventType *event_type)) + int (*StateGetEventInfoById)( + int event_id, const char **event_name, AppLayerEventType *event_type)) { SCEnter(); - alp_ctx.ctxs[FlowGetProtoMapping(ipproto)][alproto]. - StateGetEventInfoById = StateGetEventInfoById; + alp_ctx.ctxs[FlowGetProtoMapping(ipproto)][alproto].StateGetEventInfoById = + StateGetEventInfoById; SCReturn; } @@ -582,19 +566,18 @@ void AppLayerParserRegisterGetFrameFuncs(uint8_t ipproto, AppProto alproto, } void AppLayerParserRegisterGetEventInfo(uint8_t ipproto, AppProto alproto, - int (*StateGetEventInfo)(const char *event_name, int *event_id, - AppLayerEventType *event_type)) + int (*StateGetEventInfo)( + const char *event_name, int *event_id, AppLayerEventType *event_type)) { SCEnter(); - alp_ctx.ctxs[FlowGetProtoMapping(ipproto)][alproto]. - StateGetEventInfo = StateGetEventInfo; + alp_ctx.ctxs[FlowGetProtoMapping(ipproto)][alproto].StateGetEventInfo = StateGetEventInfo; SCReturn; } -void AppLayerParserRegisterTxDataFunc(uint8_t ipproto, AppProto alproto, - AppLayerTxData *(*GetTxData)(void *tx)) +void AppLayerParserRegisterTxDataFunc( + uint8_t ipproto, AppProto alproto, AppLayerTxData *(*GetTxData)(void *tx)) { SCEnter(); @@ -623,8 +606,8 @@ void AppLayerParserRegisterApplyTxConfigFunc(uint8_t ipproto, AppProto alproto, SCReturn; } -void AppLayerParserRegisterSetStreamDepthFlag(uint8_t ipproto, AppProto alproto, - void (*SetStreamDepthFlag)(void *tx, uint8_t flags)) +void AppLayerParserRegisterSetStreamDepthFlag( + uint8_t ipproto, AppProto alproto, void (*SetStreamDepthFlag)(void *tx, uint8_t flags)) { SCEnter(); @@ -638,28 +621,22 @@ void AppLayerParserRegisterSetStreamDepthFlag(uint8_t ipproto, AppProto alproto, void *AppLayerParserGetProtocolParserLocalStorage(uint8_t ipproto, AppProto alproto) { SCEnter(); - void * r = NULL; + void *r = NULL; - if (alp_ctx.ctxs[FlowGetProtoMapping(ipproto)][alproto]. - LocalStorageAlloc != NULL) - { - r = alp_ctx.ctxs[FlowGetProtoMapping(ipproto)][alproto]. - LocalStorageAlloc(); + if (alp_ctx.ctxs[FlowGetProtoMapping(ipproto)][alproto].LocalStorageAlloc != NULL) { + r = alp_ctx.ctxs[FlowGetProtoMapping(ipproto)][alproto].LocalStorageAlloc(); } SCReturnPtr(r, "void *"); } -void AppLayerParserDestroyProtocolParserLocalStorage(uint8_t ipproto, AppProto alproto, - void *local_data) +void AppLayerParserDestroyProtocolParserLocalStorage( + uint8_t ipproto, AppProto alproto, void *local_data) { SCEnter(); - if (alp_ctx.ctxs[FlowGetProtoMapping(ipproto)][alproto]. - LocalStorageFree != NULL) - { - alp_ctx.ctxs[FlowGetProtoMapping(ipproto)][alproto]. - LocalStorageFree(local_data); + if (alp_ctx.ctxs[FlowGetProtoMapping(ipproto)][alproto].LocalStorageFree != NULL) { + alp_ctx.ctxs[FlowGetProtoMapping(ipproto)][alproto].LocalStorageFree(local_data); } SCReturn; @@ -673,14 +650,13 @@ void AppLayerParserDestroyProtocolParserLocalStorage(uint8_t ipproto, AppProto a * * \retval txptr or NULL if no more txs in list */ -static AppLayerGetTxIterTuple AppLayerDefaultGetTxIterator( - const uint8_t ipproto, const AppProto alproto, - void *alstate, uint64_t min_tx_id, uint64_t max_tx_id, +static AppLayerGetTxIterTuple AppLayerDefaultGetTxIterator(const uint8_t ipproto, + const AppProto alproto, void *alstate, uint64_t min_tx_id, uint64_t max_tx_id, AppLayerGetTxIterState *state) { uint64_t ustate = *(uint64_t *)state; uint64_t tx_id = MAX(min_tx_id, ustate); - for ( ; tx_id < max_tx_id; tx_id++) { + for (; tx_id < max_tx_id; tx_id++) { void *tx_ptr = AppLayerParserGetTx(ipproto, alproto, alstate, tx_id); if (tx_ptr != NULL) { ustate = tx_id + 1; @@ -690,7 +666,7 @@ static AppLayerGetTxIterTuple AppLayerDefaultGetTxIterator( .tx_id = tx_id, .has_next = (tx_id + 1 < max_tx_id), }; - SCLogDebug("tuple: %p/%"PRIu64"/%s", tuple.tx_ptr, tuple.tx_id, + SCLogDebug("tuple: %p/%" PRIu64 "/%s", tuple.tx_ptr, tuple.tx_id, tuple.has_next ? "true" : "false"); return tuple; } @@ -700,11 +676,10 @@ static AppLayerGetTxIterTuple AppLayerDefaultGetTxIterator( return no_tuple; } -AppLayerGetTxIteratorFunc AppLayerGetTxIterator(const uint8_t ipproto, - const AppProto alproto) +AppLayerGetTxIteratorFunc AppLayerGetTxIterator(const uint8_t ipproto, const AppProto alproto) { AppLayerGetTxIteratorFunc Func = - alp_ctx.ctxs[FlowGetProtoMapping(ipproto)][alproto].StateGetTxIterator; + alp_ctx.ctxs[FlowGetProtoMapping(ipproto)][alproto].StateGetTxIterator; return Func ? Func : AppLayerDefaultGetTxIterator; } @@ -737,12 +712,12 @@ uint64_t AppLayerParserGetTransactionInspectId(AppLayerParserState *pstate, uint inline uint64_t AppLayerParserGetTxDetectFlags(AppLayerTxData *txd, const uint8_t dir) { - uint64_t detect_flags = - (dir & STREAM_TOSERVER) ? txd->detect_flags_ts : txd->detect_flags_tc; + uint64_t detect_flags = (dir & STREAM_TOSERVER) ? txd->detect_flags_ts : txd->detect_flags_tc; return detect_flags; } -static inline void SetTxDetectFlags(AppLayerTxData *txd, const uint8_t dir, const uint64_t detect_flags) +static inline void SetTxDetectFlags( + AppLayerTxData *txd, const uint8_t dir, const uint64_t detect_flags) { if (dir & STREAM_TOSERVER) { txd->detect_flags_ts = detect_flags; @@ -757,15 +732,15 @@ static inline uint32_t GetTxLogged(AppLayerTxData *txd) } void AppLayerParserSetTransactionInspectId(const Flow *f, AppLayerParserState *pstate, - void *alstate, const uint8_t flags, - bool tag_txs_as_inspected) + void *alstate, const uint8_t flags, bool tag_txs_as_inspected) { SCEnter(); const int direction = (flags & STREAM_TOSERVER) ? 0 : 1; const uint64_t total_txs = AppLayerParserGetTxCnt(f, alstate); uint64_t idx = AppLayerParserGetTransactionInspectId(pstate, flags); - const int state_done_progress = AppLayerParserGetStateProgressCompletionStatus(f->alproto, flags); + const int state_done_progress = + AppLayerParserGetStateProgressCompletionStatus(f->alproto, flags); const uint8_t ipproto = f->proto; const AppProto alproto = f->alproto; @@ -773,8 +748,8 @@ void AppLayerParserSetTransactionInspectId(const Flow *f, AppLayerParserState *p AppLayerGetTxIterState state; memset(&state, 0, sizeof(state)); - SCLogDebug("called: %s, tag_txs_as_inspected %s",direction==0?"toserver":"toclient", - tag_txs_as_inspected?"true":"false"); + SCLogDebug("called: %s, tag_txs_as_inspected %s", direction == 0 ? "toserver" : "toclient", + tag_txs_as_inspected ? "true" : "false"); /* mark all txs as inspected if the applayer progress is * at the 'end state'. */ @@ -796,7 +771,7 @@ void AppLayerParserSetTransactionInspectId(const Flow *f, AppLayerParserState *p if ((detect_flags & APP_LAYER_TX_INSPECTED_FLAG) == 0) { detect_flags |= APP_LAYER_TX_INSPECTED_FLAG; SetTxDetectFlags(txd, flags, detect_flags); - SCLogDebug("%p/%"PRIu64" in-order tx is done for direction %s. Flag %016"PRIx64, + SCLogDebug("%p/%" PRIu64 " in-order tx is done for direction %s. Flag %016" PRIx64, tx, idx, flags & STREAM_TOSERVER ? "toserver" : "toclient", detect_flags); } } @@ -805,14 +780,15 @@ void AppLayerParserSetTransactionInspectId(const Flow *f, AppLayerParserState *p break; } pstate->inspect_id[direction] = idx; - SCLogDebug("inspect_id now %"PRIu64, pstate->inspect_id[direction]); + SCLogDebug("inspect_id now %" PRIu64, pstate->inspect_id[direction]); /* if necessary we flag all txs that are complete as 'inspected' * also move inspect_id forward. */ if (tag_txs_as_inspected) { /* continue at idx */ while (1) { - AppLayerGetTxIterTuple ires = IterFunc(ipproto, alproto, alstate, idx, total_txs, &state); + AppLayerGetTxIterTuple ires = + IterFunc(ipproto, alproto, alstate, idx, total_txs, &state); if (ires.tx_ptr == NULL) break; @@ -836,16 +812,18 @@ void AppLayerParserSetTransactionInspectId(const Flow *f, AppLayerParserState *p if ((detect_flags & APP_LAYER_TX_INSPECTED_FLAG) == 0) { detect_flags |= APP_LAYER_TX_INSPECTED_FLAG; SetTxDetectFlags(txd, flags, detect_flags); - SCLogDebug("%p/%"PRIu64" out of order tx is done for direction %s. Flag %016"PRIx64, - tx, idx, flags & STREAM_TOSERVER ? "toserver" : "toclient", detect_flags); - - SCLogDebug("%p/%"PRIu64" out of order tx. Update inspect_id? %"PRIu64, - tx, idx, pstate->inspect_id[direction]); - if (pstate->inspect_id[direction]+1 == idx) + SCLogDebug("%p/%" PRIu64 + " out of order tx is done for direction %s. Flag %016" PRIx64, + tx, idx, flags & STREAM_TOSERVER ? "toserver" : "toclient", + detect_flags); + + SCLogDebug("%p/%" PRIu64 " out of order tx. Update inspect_id? %" PRIu64, tx, + idx, pstate->inspect_id[direction]); + if (pstate->inspect_id[direction] + 1 == idx) pstate->inspect_id[direction] = idx; } } else { - if (pstate->inspect_id[direction]+1 == idx) + if (pstate->inspect_id[direction] + 1 == idx) pstate->inspect_id[direction] = idx; } if (!ires.has_next) @@ -861,8 +839,7 @@ AppLayerDecoderEvents *AppLayerParserGetDecoderEvents(AppLayerParserState *pstat { SCEnter(); - SCReturnPtr(pstate->decoder_events, - "AppLayerDecoderEvents *"); + SCReturnPtr(pstate->decoder_events, "AppLayerDecoderEvents *"); } void AppLayerParserSetDecoderEvents(AppLayerParserState *pstate, AppLayerDecoderEvents *devents) @@ -870,8 +847,7 @@ void AppLayerParserSetDecoderEvents(AppLayerParserState *pstate, AppLayerDecoder pstate->decoder_events = devents; } -AppLayerDecoderEvents *AppLayerParserGetEventsByTx(uint8_t ipproto, AppProto alproto, - void *tx) +AppLayerDecoderEvents *AppLayerParserGetEventsByTx(uint8_t ipproto, AppProto alproto, void *tx) { SCEnter(); @@ -929,8 +905,8 @@ void AppLayerParserTransactionsCleanup(Flow *f, const uint8_t pkt_dir) const bool has_tx_detect_flags = !g_detect_disabled; const uint8_t ipproto = f->proto; const AppProto alproto = f->alproto; - void * const alstate = f->alstate; - AppLayerParserState * const alparser = f->alparser; + void *const alstate = f->alstate; + AppLayerParserState *const alparser = f->alparser; if (alstate == NULL || alparser == NULL) SCReturn; @@ -938,8 +914,10 @@ void AppLayerParserTransactionsCleanup(Flow *f, const uint8_t pkt_dir) const uint64_t min = alparser->min_id; const uint64_t total_txs = AppLayerParserGetTxCnt(f, alstate); const LoggerId logger_expectation = AppLayerParserProtocolGetLoggerBits(ipproto, alproto); - const int tx_end_state_ts = AppLayerParserGetStateProgressCompletionStatus(alproto, STREAM_TOSERVER); - const int tx_end_state_tc = AppLayerParserGetStateProgressCompletionStatus(alproto, STREAM_TOCLIENT); + const int tx_end_state_ts = + AppLayerParserGetStateProgressCompletionStatus(alproto, STREAM_TOSERVER); + const int tx_end_state_tc = + AppLayerParserGetStateProgressCompletionStatus(alproto, STREAM_TOCLIENT); const uint8_t ts_disrupt_flags = FlowGetDisruptionFlags(f, STREAM_TOSERVER); const uint8_t tc_disrupt_flags = FlowGetDisruptionFlags(f, STREAM_TOCLIENT); @@ -950,7 +928,7 @@ void AppLayerParserTransactionsCleanup(Flow *f, const uint8_t pkt_dir) memset(&state, 0, sizeof(state)); uint64_t i = min; uint64_t new_min = min; - SCLogDebug("start min %"PRIu64, min); + SCLogDebug("start min %" PRIu64, min); bool skipped = false; // const bool support_files = AppLayerParserSupportsFiles(f->proto, f->alproto); @@ -963,7 +941,7 @@ void AppLayerParserTransactionsCleanup(Flow *f, const uint8_t pkt_dir) void *tx = ires.tx_ptr; i = ires.tx_id; // actual tx id for the tx the IterFunc returned - SCLogDebug("%p/%"PRIu64" checking", tx, i); + SCLogDebug("%p/%" PRIu64 " checking", tx, i); AppLayerTxData *txd = AppLayerParserGetTxData(ipproto, alproto, tx); if (txd != NULL && AppLayerParserHasFilesInDir(txd, pkt_dir)) { if (pkt_dir_trunc == -1) @@ -978,14 +956,14 @@ void AppLayerParserTransactionsCleanup(Flow *f, const uint8_t pkt_dir) const int tx_progress_tc = AppLayerParserGetStateProgress(ipproto, alproto, tx, tc_disrupt_flags); if (tx_progress_tc < tx_end_state_tc) { - SCLogDebug("%p/%"PRIu64" skipping: tc parser not done", tx, i); + SCLogDebug("%p/%" PRIu64 " skipping: tc parser not done", tx, i); skipped = true; goto next; } const int tx_progress_ts = AppLayerParserGetStateProgress(ipproto, alproto, tx, ts_disrupt_flags); if (tx_progress_ts < tx_end_state_ts) { - SCLogDebug("%p/%"PRIu64" skipping: ts parser not done", tx, i); + SCLogDebug("%p/%" PRIu64 " skipping: ts parser not done", tx, i); skipped = true; goto next; } @@ -1020,7 +998,8 @@ void AppLayerParserTransactionsCleanup(Flow *f, const uint8_t pkt_dir) if (txd && logger_expectation != 0) { LoggerId tx_logged = GetTxLogged(txd); if (tx_logged != logger_expectation) { - SCLogDebug("%p/%"PRIu64" skipping: logging not done: want:%"PRIx32", have:%"PRIx32, + SCLogDebug("%p/%" PRIu64 " skipping: logging not done: want:%" PRIx32 + ", have:%" PRIx32, tx, i, logger_expectation, tx_logged); skipped = true; goto next; @@ -1047,24 +1026,26 @@ void AppLayerParserTransactionsCleanup(Flow *f, const uint8_t pkt_dir) /* if we are here, the tx can be freed. */ p->StateTransactionFree(alstate, i); - SCLogDebug("%p/%"PRIu64" freed", tx, i); + SCLogDebug("%p/%" PRIu64 " freed", tx, i); /* if we didn't skip any tx so far, up the minimum */ - SCLogDebug("skipped? %s i %"PRIu64", new_min %"PRIu64, skipped ? "true" : "false", i, new_min); + SCLogDebug("skipped? %s i %" PRIu64 ", new_min %" PRIu64, skipped ? "true" : "false", i, + new_min); if (!skipped) new_min = i + 1; - SCLogDebug("final i %"PRIu64", new_min %"PRIu64, i, new_min); + SCLogDebug("final i %" PRIu64 ", new_min %" PRIu64, i, new_min); -next: + next: if (!ires.has_next) { /* this was the last tx. See if we skipped any. If not * we removed all and can update the minimum to the max * id. */ - SCLogDebug("no next: cur tx i %"PRIu64", total %"PRIu64, i, total_txs); + SCLogDebug("no next: cur tx i %" PRIu64 ", total %" PRIu64, i, total_txs); if (!skipped) { new_min = total_txs; - SCLogDebug("no next: cur tx i %"PRIu64", total %"PRIu64": " - "new_min updated to %"PRIu64, i, total_txs, new_min); + SCLogDebug("no next: cur tx i %" PRIu64 ", total %" PRIu64 ": " + "new_min updated to %" PRIu64, + i, total_txs, new_min); } break; } @@ -1072,14 +1053,14 @@ void AppLayerParserTransactionsCleanup(Flow *f, const uint8_t pkt_dir) } /* see if we need to bring all trackers up to date. */ - SCLogDebug("update f->alparser->min_id? %"PRIu64" vs %"PRIu64, new_min, alparser->min_id); + SCLogDebug("update f->alparser->min_id? %" PRIu64 " vs %" PRIu64, new_min, alparser->min_id); if (new_min > alparser->min_id) { const uint64_t next_id = new_min; alparser->min_id = next_id; alparser->inspect_id[0] = MAX(alparser->inspect_id[0], next_id); alparser->inspect_id[1] = MAX(alparser->inspect_id[1], next_id); alparser->log_id = MAX(alparser->log_id, next_id); - SCLogDebug("updated f->alparser->min_id %"PRIu64, alparser->min_id); + SCLogDebug("updated f->alparser->min_id %" PRIu64, alparser->min_id); } SCReturn; } @@ -1101,8 +1082,7 @@ static inline int StateGetProgressCompletionStatus(const AppProto alproto, const * * If the stream is disrupted, we return the 'completion' value. */ -int AppLayerParserGetStateProgress(uint8_t ipproto, AppProto alproto, - void *alstate, uint8_t flags) +int AppLayerParserGetStateProgress(uint8_t ipproto, AppProto alproto, void *alstate, uint8_t flags) { SCEnter(); int r; @@ -1130,8 +1110,7 @@ void *AppLayerParserGetTx(uint8_t ipproto, AppProto alproto, void *alstate, uint SCReturnPtr(r, "void *"); } -int AppLayerParserGetStateProgressCompletionStatus(AppProto alproto, - uint8_t direction) +int AppLayerParserGetStateProgressCompletionStatus(AppProto alproto, uint8_t direction) { SCEnter(); int r = StateGetProgressCompletionStatus(alproto, direction); @@ -1139,23 +1118,27 @@ int AppLayerParserGetStateProgressCompletionStatus(AppProto alproto, } int AppLayerParserGetEventInfo(uint8_t ipproto, AppProto alproto, const char *event_name, - int *event_id, AppLayerEventType *event_type) + int *event_id, AppLayerEventType *event_type) { SCEnter(); const int ipproto_map = FlowGetProtoMapping(ipproto); - int r = (alp_ctx.ctxs[ipproto_map][alproto].StateGetEventInfo == NULL) ? - -1 : alp_ctx.ctxs[ipproto_map][alproto].StateGetEventInfo(event_name, event_id, event_type); + int r = (alp_ctx.ctxs[ipproto_map][alproto].StateGetEventInfo == NULL) + ? -1 + : alp_ctx.ctxs[ipproto_map][alproto].StateGetEventInfo( + event_name, event_id, event_type); SCReturnInt(r); } int AppLayerParserGetEventInfoById(uint8_t ipproto, AppProto alproto, int event_id, - const char **event_name, AppLayerEventType *event_type) + const char **event_name, AppLayerEventType *event_type) { SCEnter(); const int ipproto_map = FlowGetProtoMapping(ipproto); *event_name = (const char *)NULL; - int r = (alp_ctx.ctxs[ipproto_map][alproto].StateGetEventInfoById == NULL) ? - -1 : alp_ctx.ctxs[ipproto_map][alproto].StateGetEventInfoById(event_id, event_name, event_type); + int r = (alp_ctx.ctxs[ipproto_map][alproto].StateGetEventInfoById == NULL) + ? -1 + : alp_ctx.ctxs[ipproto_map][alproto].StateGetEventInfoById( + event_id, event_name, event_type); SCReturnInt(r); } @@ -1166,8 +1149,8 @@ uint8_t AppLayerParserGetFirstDataDir(uint8_t ipproto, AppProto alproto) SCReturnCT(r, "uint8_t"); } -uint64_t AppLayerParserGetTransactionActive(const Flow *f, - AppLayerParserState *pstate, uint8_t direction) +uint64_t AppLayerParserGetTransactionActive( + const Flow *f, AppLayerParserState *pstate, uint8_t direction) { SCEnter(); @@ -1211,8 +1194,8 @@ AppLayerStateData *AppLayerParserGetStateData(uint8_t ipproto, AppProto alproto, SCReturnPtr(NULL, "AppLayerStateData"); } -void AppLayerParserApplyTxConfig(uint8_t ipproto, AppProto alproto, - void *state, void *tx, enum ConfigAction mode, AppLayerTxConfig config) +void AppLayerParserApplyTxConfig(uint8_t ipproto, AppProto alproto, void *state, void *tx, + enum ConfigAction mode, AppLayerTxConfig config) { SCEnter(); const int ipproto_map = FlowGetProtoMapping(ipproto); @@ -1226,10 +1209,10 @@ void AppLayerParserApplyTxConfig(uint8_t ipproto, AppProto alproto, static inline void SetEOFFlags(AppLayerParserState *pstate, const uint8_t flags) { - if ((flags & (STREAM_EOF|STREAM_TOSERVER)) == (STREAM_EOF|STREAM_TOSERVER)) { + if ((flags & (STREAM_EOF | STREAM_TOSERVER)) == (STREAM_EOF | STREAM_TOSERVER)) { SCLogDebug("setting APP_LAYER_PARSER_EOF_TS"); AppLayerParserStateSetFlag(pstate, APP_LAYER_PARSER_EOF_TS); - } else if ((flags & (STREAM_EOF|STREAM_TOCLIENT)) == (STREAM_EOF|STREAM_TOCLIENT)) { + } else if ((flags & (STREAM_EOF | STREAM_TOCLIENT)) == (STREAM_EOF | STREAM_TOCLIENT)) { SCLogDebug("setting APP_LAYER_PARSER_EOF_TC"); AppLayerParserStateSetFlag(pstate, APP_LAYER_PARSER_EOF_TC); } @@ -1301,8 +1284,8 @@ static void Setup(Flow *f, const uint8_t direction, const uint8_t *input, uint32 /** \retval int -1 in case of unrecoverable error. App-layer tracking stops for this flow. * \retval int 0 ok: we did not update app_progress * \retval int 1 ok: we updated app_progress */ -int AppLayerParserParse(ThreadVars *tv, AppLayerParserThreadCtx *alp_tctx, Flow *f, AppProto alproto, - uint8_t flags, const uint8_t *input, uint32_t input_len) +int AppLayerParserParse(ThreadVars *tv, AppLayerParserThreadCtx *alp_tctx, Flow *f, + AppProto alproto, uint8_t flags, const uint8_t *input, uint32_t input_len) { SCEnter(); #ifdef DEBUG_VALIDATION @@ -1353,8 +1336,8 @@ int AppLayerParserParse(ThreadVars *tv, AppLayerParserThreadCtx *alp_tctx, Flow AppLayerIncAllocErrorCounter(tv, f); goto error; } - SCLogDebug("alloced new app layer state %p (name %s)", - alstate, AppLayerGetProtoName(f->alproto)); + SCLogDebug("alloced new app layer state %p (name %s)", alstate, + AppLayerGetProtoName(f->alproto)); /* set flow flags to state */ if (f->file_flags != 0) { @@ -1368,8 +1351,8 @@ int AppLayerParserParse(ThreadVars *tv, AppLayerParserThreadCtx *alp_tctx, Flow } } } else { - SCLogDebug("using existing app layer state %p (name %s))", - alstate, AppLayerGetProtoName(f->alproto)); + SCLogDebug("using existing app layer state %p (name %s))", alstate, + AppLayerGetProtoName(f->alproto)); } p_tx_cnt = AppLayerParserGetTxCnt(f, f->alstate); @@ -1467,7 +1450,8 @@ int AppLayerParserParse(ThreadVars *tv, AppLayerParserThreadCtx *alp_tctx, Flow } /* In cases like HeartBleed for TLS we need to inspect AppLayer but not Payload */ - if (!(f->flags & FLOW_NOPAYLOAD_INSPECTION) && pstate->flags & APP_LAYER_PARSER_NO_INSPECTION_PAYLOAD) { + if (!(f->flags & FLOW_NOPAYLOAD_INSPECTION) && + pstate->flags & APP_LAYER_PARSER_NO_INSPECTION_PAYLOAD) { FlowSetNoPayloadInspectionFlag(f); /* Set the no reassembly flag for both the stream in this TcpSession */ if (f->proto == IPPROTO_TCP) { @@ -1490,7 +1474,7 @@ int AppLayerParserParse(ThreadVars *tv, AppLayerParserThreadCtx *alp_tctx, Flow if (flags & STREAM_DEPTH) AppLayerParserStreamTruncated(pstate, f->proto, alproto, f->alstate, flags); - end: +end: /* update app progress */ if (consumed != input_len && f->proto == IPPROTO_TCP && f->protoctx != NULL) { TcpSession *ssn = f->protoctx; @@ -1499,7 +1483,7 @@ int AppLayerParserParse(ThreadVars *tv, AppLayerParserThreadCtx *alp_tctx, Flow } SCReturnInt(0); - error: +error: /* Set the no app layer inspection flag for both * the stream in this Flow */ if (f->proto == IPPROTO_TCP) { @@ -1517,9 +1501,9 @@ void AppLayerParserSetEOF(AppLayerParserState *pstate) goto end; SCLogDebug("setting APP_LAYER_PARSER_EOF_TC and APP_LAYER_PARSER_EOF_TS"); - AppLayerParserStateSetFlag(pstate, (APP_LAYER_PARSER_EOF_TS|APP_LAYER_PARSER_EOF_TC)); + AppLayerParserStateSetFlag(pstate, (APP_LAYER_PARSER_EOF_TS | APP_LAYER_PARSER_EOF_TC)); - end: +end: SCReturn; } @@ -1586,7 +1570,7 @@ void AppLayerParserSetStreamDepth(uint8_t ipproto, AppProto alproto, uint32_t st alp_ctx.ctxs[FlowGetProtoMapping(ipproto)][alproto].stream_depth = stream_depth; alp_ctx.ctxs[FlowGetProtoMapping(ipproto)][alproto].internal_flags |= - APP_LAYER_PARSER_INT_STREAM_DEPTH_SET; + APP_LAYER_PARSER_INT_STREAM_DEPTH_SET; SCReturn; } @@ -1596,7 +1580,8 @@ uint32_t AppLayerParserGetStreamDepth(const Flow *f) SCReturnInt(alp_ctx.ctxs[f->protomap][f->alproto].stream_depth); } -void AppLayerParserSetStreamDepthFlag(uint8_t ipproto, AppProto alproto, void *state, uint64_t tx_id, uint8_t flags) +void AppLayerParserSetStreamDepthFlag( + uint8_t ipproto, AppProto alproto, void *state, uint64_t tx_id, uint8_t flags) { SCEnter(); void *tx = NULL; @@ -1658,25 +1643,27 @@ static void ValidateParserProtoDump(AppProto alproto, uint8_t ipproto) const AppLayerParserProtoCtx *ctx = &alp_ctx.ctxs[map][alproto]; printf("ERROR: incomplete app-layer registration\n"); printf("AppLayer protocol %s ipproto %u\n", AppProtoToString(alproto), ipproto); - printf("- option flags %"PRIx32"\n", ctx->option_flags); - printf("- first_data_dir %"PRIx8"\n", ctx->first_data_dir); + printf("- option flags %" PRIx32 "\n", ctx->option_flags); + printf("- first_data_dir %" PRIx8 "\n", ctx->first_data_dir); printf("Mandatory:\n"); printf("- Parser[0] %p Parser[1] %p\n", ctx->Parser[0], ctx->Parser[1]); printf("- StateAlloc %p StateFree %p\n", ctx->StateAlloc, ctx->StateFree); - printf("- StateGetTx %p StateGetTxCnt %p StateTransactionFree %p\n", - ctx->StateGetTx, ctx->StateGetTxCnt, ctx->StateTransactionFree); + printf("- StateGetTx %p StateGetTxCnt %p StateTransactionFree %p\n", ctx->StateGetTx, + ctx->StateGetTxCnt, ctx->StateTransactionFree); printf("- GetTxData %p\n", ctx->GetTxData); printf("- GetStateData %p\n", ctx->GetStateData); printf("- StateGetProgress %p\n", ctx->StateGetProgress); printf("Optional:\n"); - printf("- LocalStorageAlloc %p LocalStorageFree %p\n", ctx->LocalStorageAlloc, ctx->LocalStorageFree); + printf("- LocalStorageAlloc %p LocalStorageFree %p\n", ctx->LocalStorageAlloc, + ctx->LocalStorageFree); printf("- StateGetEventInfo %p StateGetEventInfoById %p\n", ctx->StateGetEventInfo, ctx->StateGetEventInfoById); } -#define BOTH_SET(a, b) ((a) != NULL && (b) != NULL) +#define BOTH_SET(a, b) ((a) != NULL && (b) != NULL) #define BOTH_SET_OR_BOTH_UNSET(a, b) (((a) == NULL && (b) == NULL) || ((a) != NULL && (b) != NULL)) -#define THREE_SET_OR_THREE_UNSET(a, b, c) (((a) == NULL && (b) == NULL && (c) == NULL) || ((a) != NULL && (b) != NULL && (c) != NULL)) +#define THREE_SET_OR_THREE_UNSET(a, b, c) \ + (((a) == NULL && (b) == NULL && (c) == NULL) || ((a) != NULL && (b) != NULL && (c) != NULL)) #define THREE_SET(a, b, c) ((a) != NULL && (b) != NULL && (c) != NULL) static void ValidateParserProto(AppProto alproto, uint8_t ipproto) @@ -1728,7 +1715,7 @@ static void ValidateParser(AppProto alproto) static void ValidateParsers(void) { AppProto p = 0; - for ( ; p < ALPROTO_MAX; p++) { + for (; p < ALPROTO_MAX; p++) { ValidateParser(p); } } @@ -1775,22 +1762,19 @@ void AppLayerParserRegisterProtocolParsers(void) /** IMAP */ AppLayerProtoDetectRegisterProtocol(ALPROTO_IMAP, "imap"); if (AppLayerProtoDetectConfProtoDetectionEnabled("tcp", "imap")) { - if (AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_IMAP, - "1|20|capability", 12, 0, STREAM_TOSERVER) < 0) - { + if (AppLayerProtoDetectPMRegisterPatternCS( + IPPROTO_TCP, ALPROTO_IMAP, "1|20|capability", 12, 0, STREAM_TOSERVER) < 0) { SCLogInfo("imap proto registration failure"); exit(EXIT_FAILURE); } } else { - SCLogInfo("Protocol detection and parser disabled for %s protocol.", - "imap"); + SCLogInfo("Protocol detection and parser disabled for %s protocol.", "imap"); } ValidateParsers(); return; } - /* coccinelle: AppLayerParserStateSetFlag():2,2:APP_LAYER_PARSER_ */ void AppLayerParserStateSetFlag(AppLayerParserState *pstate, uint16_t flag) { @@ -1834,12 +1818,11 @@ void AppLayerParserStatePrintDetails(AppLayerParserState *pstate) AppLayerParserState *p = pstate; SCLogDebug("AppLayerParser parser state information for parser state p(%p). " - "p->inspect_id[0](%"PRIu64"), " - "p->inspect_id[1](%"PRIu64"), " - "p->log_id(%"PRIu64"), " + "p->inspect_id[0](%" PRIu64 "), " + "p->inspect_id[1](%" PRIu64 "), " + "p->log_id(%" PRIu64 "), " "p->decoder_events(%p).", - pstate, p->inspect_id[0], p->inspect_id[1], p->log_id, - p->decoder_events); + pstate, p->inspect_id[0], p->inspect_id[1], p->log_id, p->decoder_events); SCReturn; } @@ -1876,7 +1859,7 @@ static void *TestProtocolStateAlloc(void *orig_state, AppProto proto_orig) if (unlikely(s == NULL)) goto end; memset(s, 0, sizeof(TestState)); - end: +end: SCReturnPtr(s, "TestState"); } @@ -1904,12 +1887,11 @@ static void *TestGetTx(void *state, uint64_t tx_id) return test_state; } -void AppLayerParserRegisterProtocolUnittests(uint8_t ipproto, AppProto alproto, - void (*RegisterUnittests)(void)) +void AppLayerParserRegisterProtocolUnittests( + uint8_t ipproto, AppProto alproto, void (*RegisterUnittests)(void)) { SCEnter(); - alp_ctx.ctxs[FlowGetProtoMapping(ipproto)][alproto]. - RegisterUnittests = RegisterUnittests; + alp_ctx.ctxs[FlowGetProtoMapping(ipproto)][alproto].RegisterUnittests = RegisterUnittests; SCReturn; } @@ -1949,8 +1931,8 @@ static int AppLayerParserTest01(void) /* Register the Test protocol state and parser functions */ AppLayerParserRegisterParser(IPPROTO_TCP, ALPROTO_TEST, STREAM_TOSERVER, TestProtocolParser); - AppLayerParserRegisterStateFuncs(IPPROTO_TCP, ALPROTO_TEST, - TestProtocolStateAlloc, TestProtocolStateFree); + AppLayerParserRegisterStateFuncs( + IPPROTO_TCP, ALPROTO_TEST, TestProtocolStateAlloc, TestProtocolStateFree); AppLayerParserRegisterTxFreeFunc(IPPROTO_TCP, ALPROTO_TEST, TestStateTransactionFree); AppLayerParserRegisterGetTx(IPPROTO_TCP, ALPROTO_TEST, TestGetTx); AppLayerParserRegisterGetTxCnt(IPPROTO_TCP, ALPROTO_TEST, TestGetTxCnt); @@ -1963,9 +1945,8 @@ static int AppLayerParserTest01(void) StreamTcpInitConfig(true); - int r = AppLayerParserParse(NULL, alp_tctx, f, ALPROTO_TEST, - STREAM_TOSERVER | STREAM_EOF, testbuf, - testlen); + int r = AppLayerParserParse( + NULL, alp_tctx, f, ALPROTO_TEST, STREAM_TOSERVER | STREAM_EOF, testbuf, testlen); FAIL_IF(r != -1); FAIL_IF(!(ssn.flags & STREAMTCP_FLAG_APP_LAYER_DISABLED)); @@ -1992,10 +1973,9 @@ static int AppLayerParserTest02(void) AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); /* Register the Test protocol state and parser functions */ - AppLayerParserRegisterParser(IPPROTO_UDP, ALPROTO_TEST, STREAM_TOSERVER, - TestProtocolParser); - AppLayerParserRegisterStateFuncs(IPPROTO_UDP, ALPROTO_TEST, - TestProtocolStateAlloc, TestProtocolStateFree); + AppLayerParserRegisterParser(IPPROTO_UDP, ALPROTO_TEST, STREAM_TOSERVER, TestProtocolParser); + AppLayerParserRegisterStateFuncs( + IPPROTO_UDP, ALPROTO_TEST, TestProtocolStateAlloc, TestProtocolStateFree); AppLayerParserRegisterTxFreeFunc(IPPROTO_UDP, ALPROTO_TEST, TestStateTransactionFree); AppLayerParserRegisterGetTx(IPPROTO_UDP, ALPROTO_TEST, TestGetTx); AppLayerParserRegisterGetTxCnt(IPPROTO_UDP, ALPROTO_TEST, TestGetTxCnt); @@ -2008,9 +1988,8 @@ static int AppLayerParserTest02(void) StreamTcpInitConfig(true); - int r = AppLayerParserParse(NULL, alp_tctx, f, ALPROTO_TEST, - STREAM_TOSERVER | STREAM_EOF, testbuf, - testlen); + int r = AppLayerParserParse( + NULL, alp_tctx, f, ALPROTO_TEST, STREAM_TOSERVER | STREAM_EOF, testbuf, testlen); FAIL_IF(r != -1); AppLayerParserRestoreParserTable(); @@ -2019,7 +1998,6 @@ static int AppLayerParserTest02(void) PASS; } - void AppLayerParserRegisterUnittests(void) { SCEnter(); diff --git a/src/app-layer-parser.h b/src/app-layer-parser.h index e9f8cf55e925..185f3cac9d2b 100644 --- a/src/app-layer-parser.h +++ b/src/app-layer-parser.h @@ -46,7 +46,7 @@ /* Flags for AppLayerParserProtoCtx. */ #define APP_LAYER_PARSER_OPT_ACCEPT_GAPS BIT_U32(0) -#define APP_LAYER_PARSER_INT_STREAM_DEPTH_SET BIT_U32(0) +#define APP_LAYER_PARSER_INT_STREAM_DEPTH_SET BIT_U32(0) /* applies to DetectFlags uint64_t field */ @@ -78,18 +78,26 @@ /** should inspection be skipped in that direction */ #define APP_LAYER_TX_SKIP_INSPECT_FLAG BIT_U64(62) /** is tx fully inspected? */ -#define APP_LAYER_TX_INSPECTED_FLAG BIT_U64(63) +#define APP_LAYER_TX_INSPECTED_FLAG BIT_U64(63) /** other 63 bits are for tracking which prefilter engine is already * completely inspected */ #define APP_LAYER_TX_PREFILTER_MASK ~(APP_LAYER_TX_INSPECTED_FLAG | APP_LAYER_TX_RESERVED_FLAGS) /** parser has successfully processed in the input, and has consumed * all of it. */ -#define APP_LAYER_OK (AppLayerResult) { 0, 0, 0 } +#define APP_LAYER_OK \ + (AppLayerResult) \ + { \ + 0, 0, 0 \ + } /** parser has hit an unrecoverable error. Returning this to the API * leads to no further calls to the parser. */ -#define APP_LAYER_ERROR (AppLayerResult) { -1, 0, 0 } +#define APP_LAYER_ERROR \ + (AppLayerResult) \ + { \ + -1, 0, 0 \ + } /** parser needs more data. Through 'c' it will indicate how many * of the input bytes it has consumed. Through 'n' it will indicate @@ -97,7 +105,11 @@ * \note consumed (c) should never be more than the input len * needed (n) + consumed (c) should be more than the input len */ -#define APP_LAYER_INCOMPLETE(c,n) (AppLayerResult) { 1, (c), (n) } +#define APP_LAYER_INCOMPLETE(c, n) \ + (AppLayerResult) \ + { \ + 1, (c), (n) \ + } int AppLayerParserProtoIsRegistered(uint8_t ipproto, AppProto alproto); @@ -134,8 +146,7 @@ void AppLayerParserThreadCtxFree(AppLayerParserThreadCtx *tctx); * \retval 1 If enabled. * \retval 0 If disabled. */ -int AppLayerParserConfParserEnabled(const char *ipproto, - const char *alproto_name); +int AppLayerParserConfParserEnabled(const char *ipproto, const char *alproto_name); /** \brief Prototype for parsing functions */ typedef AppLayerResult (*AppLayerParserFPtr)(Flow *f, void *protocol_state, @@ -149,9 +160,8 @@ typedef struct AppLayerGetTxIterState { } AppLayerGetTxIterState; /** \brief tx iterator prototype */ -typedef AppLayerGetTxIterTuple (*AppLayerGetTxIteratorFunc) - (const uint8_t ipproto, const AppProto alproto, - void *alstate, uint64_t min_tx_id, uint64_t max_tx_id, +typedef AppLayerGetTxIterTuple (*AppLayerGetTxIteratorFunc)(const uint8_t ipproto, + const AppProto alproto, void *alstate, uint64_t min_tx_id, uint64_t max_tx_id, AppLayerGetTxIterState *state); /***** Parser related registration *****/ @@ -165,14 +175,11 @@ typedef const char *(*AppLayerParserGetFrameNameByIdFn)(const uint8_t id); * \retval 0 On success. * \retval -1 On failure. */ -int AppLayerParserRegisterParser(uint8_t ipproto, AppProto alproto, - uint8_t direction, - AppLayerParserFPtr Parser); -void AppLayerParserRegisterParserAcceptableDataDirection(uint8_t ipproto, - AppProto alproto, - uint8_t direction); -void AppLayerParserRegisterOptionFlags(uint8_t ipproto, AppProto alproto, - uint32_t flags); +int AppLayerParserRegisterParser( + uint8_t ipproto, AppProto alproto, uint8_t direction, AppLayerParserFPtr Parser); +void AppLayerParserRegisterParserAcceptableDataDirection( + uint8_t ipproto, AppProto alproto, uint8_t direction); +void AppLayerParserRegisterOptionFlags(uint8_t ipproto, AppProto alproto, uint32_t flags); void AppLayerParserRegisterStateFuncs(uint8_t ipproto, AppProto alproto, void *(*StateAlloc)(void *, AppProto), void (*StateFree)(void *)); void AppLayerParserRegisterLocalStorageFunc(uint8_t ipproto, AppProto proto, @@ -183,34 +190,34 @@ void AppLayerParserRegisterGetTxFilesFunc(uint8_t ipproto, AppProto alproto, AppLayerGetFileState (*GetTxFiles)(void *, void *, uint8_t)); void AppLayerParserRegisterLogger(uint8_t ipproto, AppProto alproto); void AppLayerParserRegisterLoggerBits(uint8_t ipproto, AppProto alproto, LoggerId bits); -void AppLayerParserRegisterTruncateFunc(uint8_t ipproto, AppProto alproto, - void (*Truncate)(void *, uint8_t)); +void AppLayerParserRegisterTruncateFunc( + uint8_t ipproto, AppProto alproto, void (*Truncate)(void *, uint8_t)); void AppLayerParserRegisterGetStateProgressFunc(uint8_t ipproto, AppProto alproto, - int (*StateGetStateProgress)(void *alstate, uint8_t direction)); -void AppLayerParserRegisterTxFreeFunc(uint8_t ipproto, AppProto alproto, - void (*StateTransactionFree)(void *, uint64_t)); -void AppLayerParserRegisterGetTxCnt(uint8_t ipproto, AppProto alproto, - uint64_t (*StateGetTxCnt)(void *alstate)); -void AppLayerParserRegisterGetTx(uint8_t ipproto, AppProto alproto, - void *(StateGetTx)(void *alstate, uint64_t tx_id)); -void AppLayerParserRegisterGetTxIterator(uint8_t ipproto, AppProto alproto, - AppLayerGetTxIteratorFunc Func); + int (*StateGetStateProgress)(void *alstate, uint8_t direction)); +void AppLayerParserRegisterTxFreeFunc( + uint8_t ipproto, AppProto alproto, void (*StateTransactionFree)(void *, uint64_t)); +void AppLayerParserRegisterGetTxCnt( + uint8_t ipproto, AppProto alproto, uint64_t (*StateGetTxCnt)(void *alstate)); +void AppLayerParserRegisterGetTx( + uint8_t ipproto, AppProto alproto, void *(StateGetTx)(void *alstate, uint64_t tx_id)); +void AppLayerParserRegisterGetTxIterator( + uint8_t ipproto, AppProto alproto, AppLayerGetTxIteratorFunc Func); void AppLayerParserRegisterStateProgressCompletionStatus( AppProto alproto, const int ts, const int tc); void AppLayerParserRegisterGetEventInfo(uint8_t ipproto, AppProto alproto, - int (*StateGetEventInfo)(const char *event_name, int *event_id, - AppLayerEventType *event_type)); + int (*StateGetEventInfo)( + const char *event_name, int *event_id, AppLayerEventType *event_type)); void AppLayerParserRegisterGetEventInfoById(uint8_t ipproto, AppProto alproto, - int (*StateGetEventInfoById)(int event_id, const char **event_name, - AppLayerEventType *event_type)); + int (*StateGetEventInfoById)( + int event_id, const char **event_name, AppLayerEventType *event_type)); void AppLayerParserRegisterGetFrameFuncs(uint8_t ipproto, AppProto alproto, AppLayerParserGetFrameIdByNameFn GetFrameIdByName, AppLayerParserGetFrameNameByIdFn GetFrameNameById); -void AppLayerParserRegisterSetStreamDepthFlag(uint8_t ipproto, AppProto alproto, - void (*SetStreamDepthFlag)(void *tx, uint8_t flags)); +void AppLayerParserRegisterSetStreamDepthFlag( + uint8_t ipproto, AppProto alproto, void (*SetStreamDepthFlag)(void *tx, uint8_t flags)); -void AppLayerParserRegisterTxDataFunc(uint8_t ipproto, AppProto alproto, - AppLayerTxData *(*GetTxData)(void *tx)); +void AppLayerParserRegisterTxDataFunc( + uint8_t ipproto, AppProto alproto, AppLayerTxData *(*GetTxData)(void *tx)); void AppLayerParserRegisterApplyTxConfigFunc(uint8_t ipproto, AppProto alproto, bool (*ApplyTxConfig)(void *state, void *tx, int mode, AppLayerTxConfig)); void AppLayerParserRegisterStateDataFunc( @@ -219,37 +226,36 @@ void AppLayerParserRegisterStateDataFunc( /***** Get and transaction functions *****/ uint32_t AppLayerParserGetOptionFlags(uint8_t protomap, AppProto alproto); -AppLayerGetTxIteratorFunc AppLayerGetTxIterator(const uint8_t ipproto, - const AppProto alproto); +AppLayerGetTxIteratorFunc AppLayerGetTxIterator(const uint8_t ipproto, const AppProto alproto); void *AppLayerParserGetProtocolParserLocalStorage(uint8_t ipproto, AppProto alproto); -void AppLayerParserDestroyProtocolParserLocalStorage(uint8_t ipproto, AppProto alproto, - void *local_data); - +void AppLayerParserDestroyProtocolParserLocalStorage( + uint8_t ipproto, AppProto alproto, void *local_data); uint64_t AppLayerParserGetTransactionLogId(AppLayerParserState *pstate); void AppLayerParserSetTransactionLogId(AppLayerParserState *pstate, uint64_t tx_id); uint64_t AppLayerParserGetTransactionInspectId(AppLayerParserState *pstate, uint8_t direction); void AppLayerParserSetTransactionInspectId(const Flow *f, AppLayerParserState *pstate, - void *alstate, const uint8_t flags, bool tag_txs_as_inspected); + void *alstate, const uint8_t flags, bool tag_txs_as_inspected); AppLayerDecoderEvents *AppLayerParserGetDecoderEvents(AppLayerParserState *pstate); void AppLayerParserSetDecoderEvents(AppLayerParserState *pstate, AppLayerDecoderEvents *devents); AppLayerDecoderEvents *AppLayerParserGetEventsByTx(uint8_t ipproto, AppProto alproto, void *tx); AppLayerGetFileState AppLayerParserGetTxFiles( const Flow *f, void *state, void *tx, const uint8_t direction); -int AppLayerParserGetStateProgress(uint8_t ipproto, AppProto alproto, - void *alstate, uint8_t direction); +int AppLayerParserGetStateProgress( + uint8_t ipproto, AppProto alproto, void *alstate, uint8_t direction); uint64_t AppLayerParserGetTxCnt(const Flow *, void *alstate); void *AppLayerParserGetTx(uint8_t ipproto, AppProto alproto, void *alstate, uint64_t tx_id); int AppLayerParserGetStateProgressCompletionStatus(AppProto alproto, uint8_t direction); int AppLayerParserGetEventInfo(uint8_t ipproto, AppProto alproto, const char *event_name, - int *event_id, AppLayerEventType *event_type); + int *event_id, AppLayerEventType *event_type); int AppLayerParserGetEventInfoById(uint8_t ipproto, AppProto alproto, int event_id, - const char **event_name, AppLayerEventType *event_type); + const char **event_name, AppLayerEventType *event_type); -uint64_t AppLayerParserGetTransactionActive(const Flow *f, AppLayerParserState *pstate, uint8_t direction); +uint64_t AppLayerParserGetTransactionActive( + const Flow *f, AppLayerParserState *pstate, uint8_t direction); uint8_t AppLayerParserGetFirstDataDir(uint8_t ipproto, AppProto alproto); @@ -258,8 +264,8 @@ bool AppLayerParserSupportsFiles(uint8_t ipproto, AppProto alproto); AppLayerTxData *AppLayerParserGetTxData(uint8_t ipproto, AppProto alproto, void *tx); uint64_t AppLayerParserGetTxDetectFlags(AppLayerTxData *txd, const uint8_t dir); AppLayerStateData *AppLayerParserGetStateData(uint8_t ipproto, AppProto alproto, void *state); -void AppLayerParserApplyTxConfig(uint8_t ipproto, AppProto alproto, - void *state, void *tx, enum ConfigAction mode, AppLayerTxConfig); +void AppLayerParserApplyTxConfig(uint8_t ipproto, AppProto alproto, void *state, void *tx, + enum ConfigAction mode, AppLayerTxConfig); static inline bool AppLayerParserIsFileTx(const AppLayerTxData *txd) { @@ -286,7 +292,7 @@ static inline bool AppLayerParserHasFilesInDir(const AppLayerTxData *txd, const /***** General *****/ int AppLayerParserParse(ThreadVars *tv, AppLayerParserThreadCtx *tctx, Flow *f, AppProto alproto, - uint8_t flags, const uint8_t *input, uint32_t input_len); + uint8_t flags, const uint8_t *input, uint32_t input_len); void AppLayerParserSetEOF(AppLayerParserState *pstate); bool AppLayerParserHasDecoderEvents(AppLayerParserState *pstate); int AppLayerParserProtocolHasLogger(uint8_t ipproto, AppProto alproto); @@ -294,7 +300,8 @@ LoggerId AppLayerParserProtocolGetLoggerBits(uint8_t ipproto, AppProto alproto); void AppLayerParserTriggerRawStreamReassembly(Flow *f, int direction); void AppLayerParserSetStreamDepth(uint8_t ipproto, AppProto alproto, uint32_t stream_depth); uint32_t AppLayerParserGetStreamDepth(const Flow *f); -void AppLayerParserSetStreamDepthFlag(uint8_t ipproto, AppProto alproto, void *state, uint64_t tx_id, uint8_t flags); +void AppLayerParserSetStreamDepthFlag( + uint8_t ipproto, AppProto alproto, void *state, uint64_t tx_id, uint8_t flags); int AppLayerParserIsEnabled(AppProto alproto); int AppLayerParserGetFrameIdByName(uint8_t ipproto, AppProto alproto, const char *name); const char *AppLayerParserGetFrameNameById(uint8_t ipproto, AppProto alproto, const uint8_t id); @@ -319,16 +326,16 @@ void AppLayerParserTransactionsCleanup(Flow *f, const uint8_t pkt_dir); void AppLayerParserStatePrintDetails(AppLayerParserState *pstate); #endif - /***** Unittests *****/ #ifdef UNITTESTS -void AppLayerParserRegisterProtocolUnittests(uint8_t ipproto, AppProto alproto, - void (*RegisterUnittests)(void)); +void AppLayerParserRegisterProtocolUnittests( + uint8_t ipproto, AppProto alproto, void (*RegisterUnittests)(void)); void AppLayerParserRegisterUnittests(void); void AppLayerParserBackupParserTable(void); void AppLayerParserRestoreParserTable(void); -void UTHAppLayerParserStateGetIds(void *ptr, uint64_t *i1, uint64_t *i2, uint64_t *log, uint64_t *min); +void UTHAppLayerParserStateGetIds( + void *ptr, uint64_t *i1, uint64_t *i2, uint64_t *log, uint64_t *min); #endif void AppLayerFramesFreeContainer(Flow *f); diff --git a/src/app-layer-rdp.c b/src/app-layer-rdp.c index 2611de4237b0..33090f5ff146 100644 --- a/src/app-layer-rdp.c +++ b/src/app-layer-rdp.c @@ -32,7 +32,8 @@ #include "app-layer-rdp.h" #include "rust.h" -void RegisterRdpParsers(void) { +void RegisterRdpParsers(void) +{ SCLogDebug("Registering rdp parser"); rs_rdp_register_parser(); } diff --git a/src/app-layer-register.c b/src/app-layer-register.c index c4441d9f7c5b..4f055b5c2efd 100644 --- a/src/app-layer-register.c +++ b/src/app-layer-register.c @@ -33,7 +33,7 @@ #include "app-layer-register.h" -static const char * IpProtoToString(int ip_proto); +static const char *IpProtoToString(int ip_proto); AppProto AppLayerRegisterProtocolDetection(const struct AppLayerParser *p, int enable_default) { @@ -65,30 +65,24 @@ AppProto AppLayerRegisterProtocolDetection(const struct AppLayerParser *p, int e if (RunmodeIsUnittests()) { SCLogDebug("Unittest mode, registering default configuration."); - AppLayerProtoDetectPPRegister(p->ip_proto, p->default_port, - alproto, p->min_depth, p->max_depth, STREAM_TOSERVER, - p->ProbeTS, p->ProbeTC); + AppLayerProtoDetectPPRegister(p->ip_proto, p->default_port, alproto, p->min_depth, + p->max_depth, STREAM_TOSERVER, p->ProbeTS, p->ProbeTC); - } - else { + } else { - if (!AppLayerProtoDetectPPParseConfPorts(ip_proto_str, p->ip_proto, - p->name, alproto, p->min_depth, p->max_depth, - p->ProbeTS, p->ProbeTC)) { + if (!AppLayerProtoDetectPPParseConfPorts(ip_proto_str, p->ip_proto, p->name, alproto, + p->min_depth, p->max_depth, p->ProbeTS, p->ProbeTC)) { if (enable_default != 0) { SCLogDebug("No %s app-layer configuration, enabling %s" - " detection %s detection on port %s.", + " detection %s detection on port %s.", p->name, p->name, ip_proto_str, p->default_port); - AppLayerProtoDetectPPRegister(p->ip_proto, - p->default_port, alproto, - p->min_depth, p->max_depth, STREAM_TOSERVER, - p->ProbeTS, p->ProbeTC); + AppLayerProtoDetectPPRegister(p->ip_proto, p->default_port, alproto, p->min_depth, + p->max_depth, STREAM_TOSERVER, p->ProbeTS, p->ProbeTC); } else { - SCLogDebug("No %s app-layer configuration for detection port (%s).", - p->name, ip_proto_str); + SCLogDebug("No %s app-layer configuration for detection port (%s).", p->name, + ip_proto_str); } } - } return alproto; @@ -114,58 +108,47 @@ int AppLayerRegisterParser(const struct AppLayerParser *p, AppProto alproto) /* Register functions for state allocation and freeing. A * state is allocated for every new flow. */ - AppLayerParserRegisterStateFuncs(p->ip_proto, alproto, - p->StateAlloc, p->StateFree); + AppLayerParserRegisterStateFuncs(p->ip_proto, alproto, p->StateAlloc, p->StateFree); /* Register request parser for parsing frame from server to server. */ - AppLayerParserRegisterParser(p->ip_proto, alproto, - STREAM_TOSERVER, p->ParseTS); + AppLayerParserRegisterParser(p->ip_proto, alproto, STREAM_TOSERVER, p->ParseTS); /* Register response parser for parsing frames from server to client. */ - AppLayerParserRegisterParser(p->ip_proto, alproto, - STREAM_TOCLIENT, p->ParseTC); + AppLayerParserRegisterParser(p->ip_proto, alproto, STREAM_TOCLIENT, p->ParseTC); /* Register a function to be called by the application layer * when a transaction is to be freed. */ - AppLayerParserRegisterTxFreeFunc(p->ip_proto, alproto, - p->StateTransactionFree); + AppLayerParserRegisterTxFreeFunc(p->ip_proto, alproto, p->StateTransactionFree); /* Register a function to return the current transaction count. */ - AppLayerParserRegisterGetTxCnt(p->ip_proto, alproto, - p->StateGetTxCnt); + AppLayerParserRegisterGetTxCnt(p->ip_proto, alproto, p->StateGetTxCnt); /* Transaction handling. */ AppLayerParserRegisterStateProgressCompletionStatus(alproto, p->complete_ts, p->complete_tc); - AppLayerParserRegisterGetStateProgressFunc(p->ip_proto, alproto, - p->StateGetProgress); - AppLayerParserRegisterGetTx(p->ip_proto, alproto, - p->StateGetTx); + AppLayerParserRegisterGetStateProgressFunc(p->ip_proto, alproto, p->StateGetProgress); + AppLayerParserRegisterGetTx(p->ip_proto, alproto, p->StateGetTx); if (p->StateGetEventInfo) { - AppLayerParserRegisterGetEventInfo(p->ip_proto, alproto, - p->StateGetEventInfo); + AppLayerParserRegisterGetEventInfo(p->ip_proto, alproto, p->StateGetEventInfo); } if (p->StateGetEventInfoById) { - AppLayerParserRegisterGetEventInfoById(p->ip_proto, alproto, - p->StateGetEventInfoById); + AppLayerParserRegisterGetEventInfoById(p->ip_proto, alproto, p->StateGetEventInfoById); } if (p->LocalStorageAlloc && p->LocalStorageFree) { - AppLayerParserRegisterLocalStorageFunc(p->ip_proto, alproto, - p->LocalStorageAlloc, p->LocalStorageFree); + AppLayerParserRegisterLocalStorageFunc( + p->ip_proto, alproto, p->LocalStorageAlloc, p->LocalStorageFree); } if (p->GetTxFiles) { AppLayerParserRegisterGetTxFilesFunc(p->ip_proto, alproto, p->GetTxFiles); } if (p->GetTxIterator) { - AppLayerParserRegisterGetTxIterator(p->ip_proto, alproto, - p->GetTxIterator); + AppLayerParserRegisterGetTxIterator(p->ip_proto, alproto, p->GetTxIterator); } if (p->GetTxData) { - AppLayerParserRegisterTxDataFunc(p->ip_proto, alproto, - p->GetTxData); + AppLayerParserRegisterTxDataFunc(p->ip_proto, alproto, p->GetTxData); } if (p->GetStateData) { @@ -173,14 +156,11 @@ int AppLayerRegisterParser(const struct AppLayerParser *p, AppProto alproto) } if (p->ApplyTxConfig) { - AppLayerParserRegisterApplyTxConfigFunc(p->ip_proto, alproto, - p->ApplyTxConfig); + AppLayerParserRegisterApplyTxConfigFunc(p->ip_proto, alproto, p->ApplyTxConfig); } if (p->flags) { - AppLayerParserRegisterOptionFlags(p->ip_proto, alproto, - p->flags); - + AppLayerParserRegisterOptionFlags(p->ip_proto, alproto, p->flags); } if (p->Truncate) { @@ -202,7 +182,7 @@ int AppLayerRegisterParserAlias(const char *proto_name, const char *proto_alias) return 0; } -static const char * IpProtoToString(int ip_proto) +static const char *IpProtoToString(int ip_proto) { switch (ip_proto) { case IPPROTO_TCP: @@ -212,5 +192,4 @@ static const char * IpProtoToString(int ip_proto) default: return NULL; }; - } diff --git a/src/app-layer-register.h b/src/app-layer-register.h index 4fcbe6cf8b6c..3473119d4791 100644 --- a/src/app-layer-register.h +++ b/src/app-layer-register.h @@ -51,19 +51,17 @@ typedef struct AppLayerParser { const int complete_tc; int (*StateGetProgress)(void *alstate, uint8_t direction); - int (*StateGetEventInfo)(const char *event_name, - int *event_id, AppLayerEventType *event_type); - int (*StateGetEventInfoById)(int event_id, const char **event_name, - AppLayerEventType *event_type); + int (*StateGetEventInfo)(const char *event_name, int *event_id, AppLayerEventType *event_type); + int (*StateGetEventInfoById)( + int event_id, const char **event_name, AppLayerEventType *event_type); void *(*LocalStorageAlloc)(void); void (*LocalStorageFree)(void *); AppLayerGetFileState (*GetTxFiles)(void *, void *, uint8_t); - AppLayerGetTxIterTuple (*GetTxIterator)(const uint8_t ipproto, - const AppProto alproto, void *alstate, uint64_t min_tx_id, - uint64_t max_tx_id, AppLayerGetTxIterState *istate); + AppLayerGetTxIterTuple (*GetTxIterator)(const uint8_t ipproto, const AppProto alproto, + void *alstate, uint64_t min_tx_id, uint64_t max_tx_id, AppLayerGetTxIterState *istate); AppLayerStateData *(*GetStateData)(void *state); AppLayerTxData *(*GetTxData)(void *tx); @@ -82,7 +80,8 @@ typedef struct AppLayerParser { * \brief App layer protocol detection function. * * \param parser The parser declaration structure. - * \param enable_default A boolean to indicate if default port configuration should be used if none given + * \param enable_default A boolean to indicate if default port configuration should be used if none + * given * * \retval The AppProto constant if successful. On error, this function never returns. */ diff --git a/src/app-layer-rfb.c b/src/app-layer-rfb.c index 829e918adc8c..a29a82761ec0 100644 --- a/src/app-layer-rfb.c +++ b/src/app-layer-rfb.c @@ -36,14 +36,12 @@ static int RFBRegisterPatternsForProtocolDetection(void) { - if (AppLayerProtoDetectPMRegisterPatternCI(IPPROTO_TCP, ALPROTO_RFB, - "RFB ", 4, 0, STREAM_TOCLIENT) < 0) - { + if (AppLayerProtoDetectPMRegisterPatternCI( + IPPROTO_TCP, ALPROTO_RFB, "RFB ", 4, 0, STREAM_TOCLIENT) < 0) { return -1; } - if (AppLayerProtoDetectPMRegisterPatternCI(IPPROTO_TCP, ALPROTO_RFB, - "RFB ", 4, 0, STREAM_TOSERVER) < 0) - { + if (AppLayerProtoDetectPMRegisterPatternCI( + IPPROTO_TCP, ALPROTO_RFB, "RFB ", 4, 0, STREAM_TOSERVER) < 0) { return -1; } return 0; @@ -54,15 +52,13 @@ void RFBParserRegisterTests(void); void RegisterRFBParsers(void) { rs_rfb_register_parser(); - if (RFBRegisterPatternsForProtocolDetection() < 0 ) - return; + if (RFBRegisterPatternsForProtocolDetection() < 0) + return; #ifdef UNITTESTS - AppLayerParserRegisterProtocolUnittests(IPPROTO_TCP, ALPROTO_RFB, - RFBParserRegisterTests); + AppLayerParserRegisterProtocolUnittests(IPPROTO_TCP, ALPROTO_RFB, RFBParserRegisterTests); #endif } - #ifdef UNITTESTS #include "stream-tcp.h" @@ -84,52 +80,41 @@ static int RFBParserTest(void) f->proto = IPPROTO_TCP; f->alproto = ALPROTO_RFB; - static const unsigned char rfb_version_str[12] = { - 0x52, 0x46, 0x42, 0x20, 0x30, 0x30, 0x33, 0x2e, 0x30, 0x30, 0x37, 0x0a - }; + static const unsigned char rfb_version_str[12] = { 0x52, 0x46, 0x42, 0x20, 0x30, 0x30, 0x33, + 0x2e, 0x30, 0x30, 0x37, 0x0a }; // the RFB server sending the first handshake message int r = AppLayerParserParse(NULL, alp_tctx, f, ALPROTO_RFB, STREAM_TOCLIENT | STREAM_START, (uint8_t *)rfb_version_str, sizeof(rfb_version_str)); FAIL_IF_NOT(r == 0); - r = AppLayerParserParse( - NULL, alp_tctx, f, ALPROTO_RFB, STREAM_TOSERVER, (uint8_t *)rfb_version_str, sizeof(rfb_version_str)); + r = AppLayerParserParse(NULL, alp_tctx, f, ALPROTO_RFB, STREAM_TOSERVER, + (uint8_t *)rfb_version_str, sizeof(rfb_version_str)); FAIL_IF_NOT(r == 0); - static const unsigned char security_types[3] = { - 0x02, 0x01, 0x02 - }; - r = AppLayerParserParse( - NULL, alp_tctx, f, ALPROTO_RFB, STREAM_TOCLIENT, (uint8_t *)security_types, sizeof(security_types)); + static const unsigned char security_types[3] = { 0x02, 0x01, 0x02 }; + r = AppLayerParserParse(NULL, alp_tctx, f, ALPROTO_RFB, STREAM_TOCLIENT, + (uint8_t *)security_types, sizeof(security_types)); FAIL_IF_NOT(r == 0); - static const unsigned char type_selection[1] = { - 0x01 - }; - r = AppLayerParserParse( - NULL, alp_tctx, f, ALPROTO_RFB, STREAM_TOSERVER, (uint8_t *)type_selection, sizeof(type_selection)); + static const unsigned char type_selection[1] = { 0x01 }; + r = AppLayerParserParse(NULL, alp_tctx, f, ALPROTO_RFB, STREAM_TOSERVER, + (uint8_t *)type_selection, sizeof(type_selection)); FAIL_IF_NOT(r == 0); - static const unsigned char client_init[1] = { - 0x01 - }; - r = AppLayerParserParse( - NULL, alp_tctx, f, ALPROTO_RFB, STREAM_TOSERVER, (uint8_t *)client_init, sizeof(client_init)); + static const unsigned char client_init[1] = { 0x01 }; + r = AppLayerParserParse(NULL, alp_tctx, f, ALPROTO_RFB, STREAM_TOSERVER, (uint8_t *)client_init, + sizeof(client_init)); FAIL_IF_NOT(r == 0); - static const unsigned char server_init[] = { - 0x05, 0x00, 0x03, 0x20, 0x20, 0x18, 0x00, 0x01, - 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x10, 0x08, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1e, - 0x61, 0x6e, 0x65, 0x61, 0x67, 0x6c, 0x65, 0x73, - 0x40, 0x6c, 0x6f, 0x63, 0x61, 0x6c, 0x68, 0x6f, - 0x73, 0x74, 0x2e, 0x6c, 0x6f, 0x63, 0x61, 0x6c, - 0x64, 0x6f, 0x6d, 0x61, 0x69, 0x6e - }; - - r = AppLayerParserParse( - NULL, alp_tctx, f, ALPROTO_RFB, STREAM_TOCLIENT, (uint8_t *)server_init, sizeof(server_init)); + static const unsigned char server_init[] = { 0x05, 0x00, 0x03, 0x20, 0x20, 0x18, 0x00, 0x01, + 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0x10, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x1e, 0x61, 0x6e, 0x65, 0x61, 0x67, 0x6c, 0x65, 0x73, 0x40, 0x6c, 0x6f, 0x63, 0x61, 0x6c, + 0x68, 0x6f, 0x73, 0x74, 0x2e, 0x6c, 0x6f, 0x63, 0x61, 0x6c, 0x64, 0x6f, 0x6d, 0x61, 0x69, + 0x6e }; + + r = AppLayerParserParse(NULL, alp_tctx, f, ALPROTO_RFB, STREAM_TOCLIENT, (uint8_t *)server_init, + sizeof(server_init)); FAIL_IF_NOT(r == 0); AppLayerParserTransactionsCleanup(f, STREAM_TOCLIENT); diff --git a/src/app-layer-smb.c b/src/app-layer-smb.c index 0c6102e83e5f..17bce22d4433 100644 --- a/src/app-layer-smb.c +++ b/src/app-layer-smb.c @@ -34,7 +34,6 @@ #include "app-layer-smb.h" #include "util-misc.h" - static StreamingBufferConfig sbcfg = STREAMING_BUFFER_CONFIG_INITIALIZER; static SuricataFileContext sfc = { &sbcfg }; @@ -75,45 +74,45 @@ static int SMBParserTxCleanupTest(void) f->proto = IPPROTO_TCP; f->alproto = ALPROTO_SMB; - char req_str[] ="\x00\x00\x00\x79\xfe\x53\x4d\x42\x40\x00\x01\x00\x00\x00\x00\x00" \ - "\x05\x00\xe0\x1e\x10\x00\x00\x00\x00\x00\x00\x00\x0b\x00\x00\x00" \ - "\x00\x00\x00\x00\x00\x00\x00\x00\x10\x72\xd2\x9f\x36\xc2\x08\x14" \ - "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" \ - "\x00\x00\x00\x00\x39\x00\x00\x00\x02\x00\x00\x00\x00\x00\x00\x00" \ - "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x00\x00\x00" \ - "\x00\x00\x00\x00\x07\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00" \ + char req_str[] = "\x00\x00\x00\x79\xfe\x53\x4d\x42\x40\x00\x01\x00\x00\x00\x00\x00" + "\x05\x00\xe0\x1e\x10\x00\x00\x00\x00\x00\x00\x00\x0b\x00\x00\x00" + "\x00\x00\x00\x00\x00\x00\x00\x00\x10\x72\xd2\x9f\x36\xc2\x08\x14" + "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" + "\x00\x00\x00\x00\x39\x00\x00\x00\x02\x00\x00\x00\x00\x00\x00\x00" + "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x00\x00\x00" + "\x00\x00\x00\x00\x07\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00" "\x78\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"; req_str[28] = 0x01; - int r = AppLayerParserParse(NULL, alp_tctx, f, ALPROTO_SMB, - STREAM_TOSERVER | STREAM_START, (uint8_t *)req_str, sizeof(req_str)); + int r = AppLayerParserParse(NULL, alp_tctx, f, ALPROTO_SMB, STREAM_TOSERVER | STREAM_START, + (uint8_t *)req_str, sizeof(req_str)); FAIL_IF_NOT(r == 0); req_str[28]++; - r = AppLayerParserParse(NULL, alp_tctx, f, ALPROTO_SMB, - STREAM_TOSERVER, (uint8_t *)req_str, sizeof(req_str)); + r = AppLayerParserParse( + NULL, alp_tctx, f, ALPROTO_SMB, STREAM_TOSERVER, (uint8_t *)req_str, sizeof(req_str)); FAIL_IF_NOT(r == 0); req_str[28]++; - r = AppLayerParserParse(NULL, alp_tctx, f, ALPROTO_SMB, - STREAM_TOSERVER, (uint8_t *)req_str, sizeof(req_str)); + r = AppLayerParserParse( + NULL, alp_tctx, f, ALPROTO_SMB, STREAM_TOSERVER, (uint8_t *)req_str, sizeof(req_str)); FAIL_IF_NOT(r == 0); req_str[28]++; - r = AppLayerParserParse(NULL, alp_tctx, f, ALPROTO_SMB, - STREAM_TOSERVER, (uint8_t *)req_str, sizeof(req_str)); + r = AppLayerParserParse( + NULL, alp_tctx, f, ALPROTO_SMB, STREAM_TOSERVER, (uint8_t *)req_str, sizeof(req_str)); FAIL_IF_NOT(r == 0); req_str[28]++; - r = AppLayerParserParse(NULL, alp_tctx, f, ALPROTO_SMB, - STREAM_TOSERVER, (uint8_t *)req_str, sizeof(req_str)); + r = AppLayerParserParse( + NULL, alp_tctx, f, ALPROTO_SMB, STREAM_TOSERVER, (uint8_t *)req_str, sizeof(req_str)); FAIL_IF_NOT(r == 0); req_str[28]++; - r = AppLayerParserParse(NULL, alp_tctx, f, ALPROTO_SMB, - STREAM_TOSERVER, (uint8_t *)req_str, sizeof(req_str)); + r = AppLayerParserParse( + NULL, alp_tctx, f, ALPROTO_SMB, STREAM_TOSERVER, (uint8_t *)req_str, sizeof(req_str)); FAIL_IF_NOT(r == 0); req_str[28]++; - r = AppLayerParserParse(NULL, alp_tctx, f, ALPROTO_SMB, - STREAM_TOSERVER, (uint8_t *)req_str, sizeof(req_str)); + r = AppLayerParserParse( + NULL, alp_tctx, f, ALPROTO_SMB, STREAM_TOSERVER, (uint8_t *)req_str, sizeof(req_str)); FAIL_IF_NOT(r == 0); req_str[28]++; - r = AppLayerParserParse(NULL, alp_tctx, f, ALPROTO_SMB, - STREAM_TOSERVER, (uint8_t *)req_str, sizeof(req_str)); + r = AppLayerParserParse( + NULL, alp_tctx, f, ALPROTO_SMB, STREAM_TOSERVER, (uint8_t *)req_str, sizeof(req_str)); FAIL_IF_NOT(r == 0); req_str[28]++; @@ -124,44 +123,44 @@ static int SMBParserTxCleanupTest(void) FAIL_IF_NOT(ret[2] == 0); // log_id FAIL_IF_NOT(ret[3] == 0); // min_id - char resp_str[] = "\x00\x00\x00\x98\xfe\x53\x4d\x42\x40\x00\x01\x00\x00\x00\x00\x00" \ - "\x05\x00\x21\x00\x11\x00\x00\x00\x00\x00\x00\x00\x0b\x00\x00\x00" \ - "\x00\x00\x00\x00\x00\x00\x00\x00\x10\x72\xd2\x9f\x36\xc2\x08\x14" \ - "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" \ - "\x00\x00\x00\x00\x59\x00\x00\x00\x01\x00\x00\x00\x48\x38\x40\xb3" \ - "\x0f\xa8\xd3\x01\x84\x9a\x2b\x46\xf7\xa8\xd3\x01\x48\x38\x40\xb3" \ - "\x0f\xa8\xd3\x01\x48\x38\x40\xb3\x0f\xa8\xd3\x01\x00\x00\x00\x00" \ - "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x10\x00\x00\x00" \ - "\x00\x00\x00\x00\x9e\x8f\xb8\x91\x00\x00\x00\x00\x01\x5b\x11\xbb" \ - "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"; + char resp_str[] = "\x00\x00\x00\x98\xfe\x53\x4d\x42\x40\x00\x01\x00\x00\x00\x00\x00" + "\x05\x00\x21\x00\x11\x00\x00\x00\x00\x00\x00\x00\x0b\x00\x00\x00" + "\x00\x00\x00\x00\x00\x00\x00\x00\x10\x72\xd2\x9f\x36\xc2\x08\x14" + "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" + "\x00\x00\x00\x00\x59\x00\x00\x00\x01\x00\x00\x00\x48\x38\x40\xb3" + "\x0f\xa8\xd3\x01\x84\x9a\x2b\x46\xf7\xa8\xd3\x01\x48\x38\x40\xb3" + "\x0f\xa8\xd3\x01\x48\x38\x40\xb3\x0f\xa8\xd3\x01\x00\x00\x00\x00" + "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x10\x00\x00\x00" + "\x00\x00\x00\x00\x9e\x8f\xb8\x91\x00\x00\x00\x00\x01\x5b\x11\xbb" + "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"; resp_str[28] = 0x01; - r = AppLayerParserParse(NULL, alp_tctx, f, ALPROTO_SMB, - STREAM_TOCLIENT | STREAM_START, (uint8_t *)resp_str, sizeof(resp_str)); + r = AppLayerParserParse(NULL, alp_tctx, f, ALPROTO_SMB, STREAM_TOCLIENT | STREAM_START, + (uint8_t *)resp_str, sizeof(resp_str)); FAIL_IF_NOT(r == 0); resp_str[28] = 0x04; - r = AppLayerParserParse(NULL, alp_tctx, f, ALPROTO_SMB, - STREAM_TOCLIENT, (uint8_t *)resp_str, sizeof(resp_str)); + r = AppLayerParserParse( + NULL, alp_tctx, f, ALPROTO_SMB, STREAM_TOCLIENT, (uint8_t *)resp_str, sizeof(resp_str)); FAIL_IF_NOT(r == 0); resp_str[28] = 0x05; - r = AppLayerParserParse(NULL, alp_tctx, f, ALPROTO_SMB, - STREAM_TOCLIENT, (uint8_t *)resp_str, sizeof(resp_str)); + r = AppLayerParserParse( + NULL, alp_tctx, f, ALPROTO_SMB, STREAM_TOCLIENT, (uint8_t *)resp_str, sizeof(resp_str)); FAIL_IF_NOT(r == 0); resp_str[28] = 0x06; - r = AppLayerParserParse(NULL, alp_tctx, f, ALPROTO_SMB, - STREAM_TOCLIENT, (uint8_t *)resp_str, sizeof(resp_str)); + r = AppLayerParserParse( + NULL, alp_tctx, f, ALPROTO_SMB, STREAM_TOCLIENT, (uint8_t *)resp_str, sizeof(resp_str)); FAIL_IF_NOT(r == 0); resp_str[28] = 0x08; - r = AppLayerParserParse(NULL, alp_tctx, f, ALPROTO_SMB, - STREAM_TOCLIENT, (uint8_t *)resp_str, sizeof(resp_str)); + r = AppLayerParserParse( + NULL, alp_tctx, f, ALPROTO_SMB, STREAM_TOCLIENT, (uint8_t *)resp_str, sizeof(resp_str)); FAIL_IF_NOT(r == 0); resp_str[28] = 0x02; - r = AppLayerParserParse(NULL, alp_tctx, f, ALPROTO_SMB, - STREAM_TOCLIENT, (uint8_t *)resp_str, sizeof(resp_str)); + r = AppLayerParserParse( + NULL, alp_tctx, f, ALPROTO_SMB, STREAM_TOCLIENT, (uint8_t *)resp_str, sizeof(resp_str)); FAIL_IF_NOT(r == 0); resp_str[28] = 0x07; - r = AppLayerParserParse(NULL, alp_tctx, f, ALPROTO_SMB, - STREAM_TOCLIENT, (uint8_t *)resp_str, sizeof(resp_str)); + r = AppLayerParserParse( + NULL, alp_tctx, f, ALPROTO_SMB, STREAM_TOCLIENT, (uint8_t *)resp_str, sizeof(resp_str)); FAIL_IF_NOT(r == 0); AppLayerParserTransactionsCleanup(f, STREAM_TOCLIENT); @@ -172,8 +171,8 @@ static int SMBParserTxCleanupTest(void) FAIL_IF_NOT(ret[3] == 2); // min_id resp_str[28] = 0x03; - r = AppLayerParserParse(NULL, alp_tctx, f, ALPROTO_SMB, - STREAM_TOCLIENT, (uint8_t *)resp_str, sizeof(resp_str)); + r = AppLayerParserParse( + NULL, alp_tctx, f, ALPROTO_SMB, STREAM_TOCLIENT, (uint8_t *)resp_str, sizeof(resp_str)); FAIL_IF_NOT(r == 0); AppLayerParserTransactionsCleanup(f, STREAM_TOCLIENT); @@ -184,8 +183,8 @@ static int SMBParserTxCleanupTest(void) FAIL_IF_NOT(ret[3] == 8); // min_id req_str[28] = 0x09; - r = AppLayerParserParse(NULL, alp_tctx, f, ALPROTO_SMB, - STREAM_TOSERVER | STREAM_EOF, (uint8_t *)req_str, sizeof(req_str)); + r = AppLayerParserParse(NULL, alp_tctx, f, ALPROTO_SMB, STREAM_TOSERVER | STREAM_EOF, + (uint8_t *)req_str, sizeof(req_str)); FAIL_IF_NOT(r == 0); AppLayerParserTransactionsCleanup(f, STREAM_TOSERVER); @@ -196,8 +195,8 @@ static int SMBParserTxCleanupTest(void) FAIL_IF_NOT(ret[3] == 8); // min_id resp_str[28] = 0x09; - r = AppLayerParserParse(NULL, alp_tctx, f, ALPROTO_SMB, - STREAM_TOCLIENT | STREAM_EOF, (uint8_t *)resp_str, sizeof(resp_str)); + r = AppLayerParserParse(NULL, alp_tctx, f, ALPROTO_SMB, STREAM_TOCLIENT | STREAM_EOF, + (uint8_t *)resp_str, sizeof(resp_str)); FAIL_IF_NOT(r == 0); AppLayerParserTransactionsCleanup(f, STREAM_TOCLIENT); diff --git a/src/app-layer-smtp.c b/src/app-layer-smtp.c index 10786fb05780..f2bf9245edfd 100644 --- a/src/app-layer-smtp.c +++ b/src/app-layer-smtp.c @@ -74,28 +74,28 @@ /* we are in process of parsing a fresh command. Just a placeholder. If we * are not in STATE_COMMAND_DATA_MODE, we have to be in this mode */ -#define SMTP_PARSER_STATE_COMMAND_MODE 0x00 +#define SMTP_PARSER_STATE_COMMAND_MODE 0x00 /* we are in mode of parsing a command's data. Used when we are parsing tls * or accepting the rfc 2822 mail after DATA command */ -#define SMTP_PARSER_STATE_COMMAND_DATA_MODE 0x01 +#define SMTP_PARSER_STATE_COMMAND_DATA_MODE 0x01 /* Used when we are still in the process of parsing a server command. Used * with multi-line replies and the stream is fragmented before all the lines * for a response is seen */ #define SMTP_PARSER_STATE_PARSING_SERVER_RESPONSE 0x02 /* Used to indicate that the parser has seen the first reply */ -#define SMTP_PARSER_STATE_FIRST_REPLY_SEEN 0x04 +#define SMTP_PARSER_STATE_FIRST_REPLY_SEEN 0x04 /* Used to indicate that the parser is parsing a multiline reply */ #define SMTP_PARSER_STATE_PARSING_MULTILINE_REPLY 0x08 /* Used to indicate that the server supports pipelining */ -#define SMTP_PARSER_STATE_PIPELINING_SERVER 0x10 +#define SMTP_PARSER_STATE_PIPELINING_SERVER 0x10 /* Various SMTP commands * We currently have var-ified just STARTTLS and DATA, since we need to them * for state transitions. The rest are just indicate as OTHER_CMD. Other * commands would be introduced as and when needed */ -#define SMTP_COMMAND_STARTTLS 1 -#define SMTP_COMMAND_DATA 2 -#define SMTP_COMMAND_BDAT 3 +#define SMTP_COMMAND_STARTTLS 1 +#define SMTP_COMMAND_DATA 2 +#define SMTP_COMMAND_BDAT 3 /* not an actual command per se, but the mode where we accept the mail after * DATA has it's own reply code for completion, from the server. We give this * stage a pseudo command of it's own, so that we can add this to the command @@ -207,7 +207,7 @@ enum SMTPCode { SMTP_REPLY_555, }; -SCEnumCharMap smtp_reply_map[ ] = { +SCEnumCharMap smtp_reply_map[] = { { "211", SMTP_REPLY_211 }, { "214", SMTP_REPLY_214 }, { "220", SMTP_REPLY_220 }, @@ -237,7 +237,7 @@ SCEnumCharMap smtp_reply_map[ ] = { { "553", SMTP_REPLY_553 }, { "554", SMTP_REPLY_554 }, { "555", SMTP_REPLY_555 }, - { NULL, -1 }, + { NULL, -1 }, }; /* Create SMTP config structure */ @@ -267,7 +267,8 @@ static SMTPString *SMTPStringAlloc(void); * * \return none */ -static void SMTPConfigure(void) { +static void SMTPConfigure(void) +{ SCEnter(); intmax_t imval; @@ -297,7 +298,7 @@ static void SMTPConfigure(void) { ret = ConfGetChildValueInt(config, "header-value-depth", &imval); if (ret) { - smtp_config.mime_config.header_value_depth = (uint32_t) imval; + smtp_config.mime_config.header_value_depth = (uint32_t)imval; } ret = ConfGetChildValueBool(config, "extract-urls", &val); @@ -381,7 +382,7 @@ static void SMTPConfigure(void) { ConfNode *p = NULL; if (t != NULL) { - TAILQ_FOREACH(p, &t->head, next) { + TAILQ_FOREACH (p, &t->head, next) { if (strcasecmp("content-limit", p->name) == 0) { if (ParseSizeStringU32(p->val, &content_limit) < 0) { SCLogWarning("parsing content-limit %s failed", p->val); @@ -478,19 +479,18 @@ static void SMTPNewFile(SMTPTransaction *tx, File *file) /* set inspect sizes used in file pruning logic. * TODO consider moving this to the file.data code that * would actually have use for this. */ - FileSetInspectSizes(file, smtp_config.content_inspect_window, - smtp_config.content_inspect_min_size); + FileSetInspectSizes( + file, smtp_config.content_inspect_window, smtp_config.content_inspect_min_size); } -int SMTPProcessDataChunk(const uint8_t *chunk, uint32_t len, - MimeDecParseState *state) +int SMTPProcessDataChunk(const uint8_t *chunk, uint32_t len, MimeDecParseState *state) { SCEnter(); int ret = MIME_DEC_OK; - Flow *flow = (Flow *) state->data; - SMTPState *smtp_state = (SMTPState *) flow->alstate; + Flow *flow = (Flow *)state->data; + SMTPState *smtp_state = (SMTPState *)flow->alstate; SMTPTransaction *tx = smtp_state->curr_tx; - MimeDecEntity *entity = (MimeDecEntity *) state->stack->top->data; + MimeDecEntity *entity = (MimeDecEntity *)state->stack->top->data; FileContainer *files = NULL; DEBUG_VALIDATE_BUG_ON(tx == NULL); @@ -519,9 +519,10 @@ int SMTPProcessDataChunk(const uint8_t *chunk, uint32_t len, flags |= FILE_STORE; } - uint32_t depth = smtp_config.content_inspect_min_size + - (smtp_state->toserver_data_count - smtp_state->toserver_last_data_stamp); - SCLogDebug("StreamTcpReassemblySetMinInspectDepth STREAM_TOSERVER %"PRIu32, depth); + uint32_t depth = + smtp_config.content_inspect_min_size + + (smtp_state->toserver_data_count - smtp_state->toserver_last_data_stamp); + SCLogDebug("StreamTcpReassemblySetMinInspectDepth STREAM_TOSERVER %" PRIu32, depth); StreamTcpReassemblySetMinInspectDepth(flow->protoctx, STREAM_TOSERVER, depth); uint16_t flen = (uint16_t)entity->filename_len; @@ -554,10 +555,8 @@ int SMTPProcessDataChunk(const uint8_t *chunk, uint32_t len, depth = smtp_state->toserver_data_count - smtp_state->toserver_last_data_stamp; AppLayerParserTriggerRawStreamReassembly(flow, STREAM_TOSERVER); - SCLogDebug("StreamTcpReassemblySetMinInspectDepth STREAM_TOSERVER %u", - depth); - StreamTcpReassemblySetMinInspectDepth(flow->protoctx, STREAM_TOSERVER, - depth); + SCLogDebug("StreamTcpReassemblySetMinInspectDepth STREAM_TOSERVER %u", depth); + StreamTcpReassemblySetMinInspectDepth(flow->protoctx, STREAM_TOSERVER, depth); } } else if (state->body_end) { /* Close file */ @@ -574,10 +573,8 @@ int SMTPProcessDataChunk(const uint8_t *chunk, uint32_t len, } uint32_t depth = smtp_state->toserver_data_count - smtp_state->toserver_last_data_stamp; AppLayerParserTriggerRawStreamReassembly(flow, STREAM_TOSERVER); - SCLogDebug("StreamTcpReassemblySetMinInspectDepth STREAM_TOSERVER %u", - depth); - StreamTcpReassemblySetMinInspectDepth(flow->protoctx, - STREAM_TOSERVER, depth); + SCLogDebug("StreamTcpReassemblySetMinInspectDepth STREAM_TOSERVER %u", depth); + StreamTcpReassemblySetMinInspectDepth(flow->protoctx, STREAM_TOSERVER, depth); } else { /* Append data chunk to file */ SCLogDebug("Appending file...%u bytes", len); @@ -593,28 +590,25 @@ int SMTPProcessDataChunk(const uint8_t *chunk, uint32_t len, if (files->tail && files->tail->content_inspected == 0 && files->tail->size >= smtp_config.content_inspect_min_size) { - uint32_t depth = smtp_config.content_inspect_min_size + - (smtp_state->toserver_data_count - smtp_state->toserver_last_data_stamp); + uint32_t depth = + smtp_config.content_inspect_min_size + + (smtp_state->toserver_data_count - smtp_state->toserver_last_data_stamp); AppLayerParserTriggerRawStreamReassembly(flow, STREAM_TOSERVER); - SCLogDebug("StreamTcpReassemblySetMinInspectDepth STREAM_TOSERVER %u", - depth); - StreamTcpReassemblySetMinInspectDepth(flow->protoctx, - STREAM_TOSERVER, depth); + SCLogDebug("StreamTcpReassemblySetMinInspectDepth STREAM_TOSERVER %u", depth); + StreamTcpReassemblySetMinInspectDepth(flow->protoctx, STREAM_TOSERVER, depth); - /* after the start of the body inspection, disable the depth logic */ + /* after the start of the body inspection, disable the depth logic */ } else if (files->tail && files->tail->content_inspected > 0) { - StreamTcpReassemblySetMinInspectDepth(flow->protoctx, - STREAM_TOSERVER, 0); + StreamTcpReassemblySetMinInspectDepth(flow->protoctx, STREAM_TOSERVER, 0); - /* expand the limit as long as we get file data, as the file data is bigger on the - * wire due to base64 */ + /* expand the limit as long as we get file data, as the file data is bigger on the + * wire due to base64 */ } else { - uint32_t depth = smtp_config.content_inspect_min_size + - (smtp_state->toserver_data_count - smtp_state->toserver_last_data_stamp); - SCLogDebug("StreamTcpReassemblySetMinInspectDepth STREAM_TOSERVER %"PRIu32, - depth); - StreamTcpReassemblySetMinInspectDepth(flow->protoctx, - STREAM_TOSERVER, depth); + uint32_t depth = + smtp_config.content_inspect_min_size + + (smtp_state->toserver_data_count - smtp_state->toserver_last_data_stamp); + SCLogDebug("StreamTcpReassemblySetMinInspectDepth STREAM_TOSERVER %" PRIu32, depth); + StreamTcpReassemblySetMinInspectDepth(flow->protoctx, STREAM_TOSERVER, depth); } } @@ -710,8 +704,7 @@ static int SMTPInsertCommandIntoCommandBuffer(uint8_t command, SMTPState *state, increment = USHRT_MAX - state->cmds_buffer_len; } - ptmp = SCRealloc(state->cmds, - sizeof(uint8_t) * (state->cmds_buffer_len + increment)); + ptmp = SCRealloc(state->cmds, sizeof(uint8_t) * (state->cmds_buffer_len + increment)); if (ptmp == NULL) { SCFree(state->cmds); state->cmds = NULL; @@ -722,9 +715,8 @@ static int SMTPInsertCommandIntoCommandBuffer(uint8_t command, SMTPState *state, state->cmds_buffer_len += increment; } - if (state->cmds_cnt >= 1 && - ((state->cmds[state->cmds_cnt - 1] == SMTP_COMMAND_STARTTLS) || - (state->cmds[state->cmds_cnt - 1] == SMTP_COMMAND_DATA))) { + if (state->cmds_cnt >= 1 && ((state->cmds[state->cmds_cnt - 1] == SMTP_COMMAND_STARTTLS) || + (state->cmds[state->cmds_cnt - 1] == SMTP_COMMAND_DATA))) { /* decoder event */ SMTPSetEvent(state, SMTP_DECODER_EVENT_INVALID_PIPELINED_SEQUENCE); /* we have to have EHLO, DATA, VRFY, EXPN, TURN, QUIT, NOOP, @@ -872,16 +864,14 @@ static int SMTPProcessCommandDATA(SMTPState *state, SMTPTransaction *tx, Flow *f return 0; } -static int SMTPProcessCommandSTARTTLS(SMTPState *state, Flow *f, - AppLayerParserState *pstate) +static int SMTPProcessCommandSTARTTLS(SMTPState *state, Flow *f, AppLayerParserState *pstate) { return 0; } static inline bool IsReplyToCommand(const SMTPState *state, const uint8_t cmd) { - return (state->cmds_idx < state->cmds_buffer_len && - state->cmds[state->cmds_idx] == cmd); + return (state->cmds_idx < state->cmds_buffer_len && state->cmds[state->cmds_idx] == cmd); } static int SMTPProcessReply(SMTPState *state, Flow *f, AppLayerParserState *pstate, @@ -930,8 +920,7 @@ static int SMTPProcessReply(SMTPState *state, Flow *f, AppLayerParserState *psta SCReturnInt(-1); } enum SMTPCode reply_code = smtp_reply_map[td->pmq->rule_id_array[0]].enum_value; - SCLogDebug("REPLY: reply_code %u / %s", reply_code, - smtp_reply_map[reply_code].enum_name); + SCLogDebug("REPLY: reply_code %u / %s", reply_code, smtp_reply_map[reply_code].enum_name); if (state->cmds_idx == state->cmds_cnt) { if (!(state->parser_state & SMTP_PARSER_STATE_FIRST_REPLY_SEEN)) { @@ -1179,8 +1168,8 @@ static int SMTPProcessRequest(SMTPState *state, Flow *f, AppLayerParserState *ps /* keep track of the start of the tx */ state->toserver_last_data_stamp = state->toserver_data_count; - StreamTcpReassemblySetMinInspectDepth(f->protoctx, STREAM_TOSERVER, - smtp_config.content_inspect_min_size); + StreamTcpReassemblySetMinInspectDepth( + f->protoctx, STREAM_TOSERVER, smtp_config.content_inspect_min_size); } state->toserver_data_count += (line->len + line->delim_len); @@ -1237,8 +1226,7 @@ static int SMTPProcessRequest(SMTPState *state, Flow *f, AppLayerParserState *ps if (tx->msg_head == NULL) { tx->msg_head = tx->mime_state->msg; tx->msg_tail = tx->mime_state->msg; - } - else { + } else { tx->msg_tail->next = tx->mime_state->msg; tx->msg_tail = tx->mime_state->msg; } @@ -1283,8 +1271,7 @@ static int SMTPProcessRequest(SMTPState *state, Flow *f, AppLayerParserState *ps /* Every command is inserted into a command buffer, to be matched * against reply(ies) sent by the server */ - if (SMTPInsertCommandIntoCommandBuffer(state->current_command, - state, f) == -1) { + if (SMTPInsertCommandIntoCommandBuffer(state->current_command, state, f) == -1) { SCReturnInt(-1); } @@ -1525,8 +1512,7 @@ void *SMTPStateAlloc(void *orig_state, AppProto proto_orig) if (unlikely(smtp_state == NULL)) return NULL; - smtp_state->cmds = SCMalloc(sizeof(uint8_t) * - SMTP_COMMAND_BUFFER_STEPS); + smtp_state->cmds = SCMalloc(sizeof(uint8_t) * SMTP_COMMAND_BUFFER_STEPS); if (smtp_state->cmds == NULL) { SCFree(smtp_state); return NULL; @@ -1547,7 +1533,6 @@ static SMTPString *SMTPStringAlloc(void) return smtp_string; } - static void SMTPStringFree(SMTPString *str) { if (str->str) { @@ -1661,16 +1646,14 @@ static void SMTPSetMpmState(void) MpmInitCtx(smtp_mpm_ctx, SMTP_MPM); uint32_t i = 0; - for (i = 0; i < sizeof(smtp_reply_map)/sizeof(SCEnumCharMap) - 1; i++) { + for (i = 0; i < sizeof(smtp_reply_map) / sizeof(SCEnumCharMap) - 1; i++) { SCEnumCharMap *map = &smtp_reply_map[i]; /* The third argument is 3, because reply code is always 3 bytes. */ - MpmAddPatternCI(smtp_mpm_ctx, (uint8_t *)map->enum_name, 3, - 0 /* defunct */, 0 /* defunct */, - i /* pattern id */, i /* rule id */ , 0 /* no flags */); + MpmAddPatternCI(smtp_mpm_ctx, (uint8_t *)map->enum_name, 3, 0 /* defunct */, + 0 /* defunct */, i /* pattern id */, i /* rule id */, 0 /* no flags */); } mpm_table[SMTP_MPM].Prepare(smtp_mpm_ctx); - } static void SMTPFreeMpmState(void) @@ -1682,8 +1665,8 @@ static void SMTPFreeMpmState(void) } } -static int SMTPStateGetEventInfo(const char *event_name, - int *event_id, AppLayerEventType *event_type) +static int SMTPStateGetEventInfo( + const char *event_name, int *event_id, AppLayerEventType *event_type) { *event_id = SCMapEnumNameToValue(event_name, smtp_decoder_event_table); if (*event_id == -1) { @@ -1699,8 +1682,8 @@ static int SMTPStateGetEventInfo(const char *event_name, return 0; } -static int SMTPStateGetEventInfoById(int event_id, const char **event_name, - AppLayerEventType *event_type) +static int SMTPStateGetEventInfoById( + int event_id, const char **event_name, AppLayerEventType *event_type) { *event_name = SCMapEnumValueToName(event_id, smtp_decoder_event_table); if (*event_name == NULL) { @@ -1718,30 +1701,27 @@ static int SMTPStateGetEventInfoById(int event_id, const char **event_name, static int SMTPRegisterPatternsForProtocolDetection(void) { - if (AppLayerProtoDetectPMRegisterPatternCI(IPPROTO_TCP, ALPROTO_SMTP, - "EHLO", 4, 0, STREAM_TOSERVER) < 0) - { + if (AppLayerProtoDetectPMRegisterPatternCI( + IPPROTO_TCP, ALPROTO_SMTP, "EHLO", 4, 0, STREAM_TOSERVER) < 0) { return -1; } - if (AppLayerProtoDetectPMRegisterPatternCI(IPPROTO_TCP, ALPROTO_SMTP, - "HELO", 4, 0, STREAM_TOSERVER) < 0) - { + if (AppLayerProtoDetectPMRegisterPatternCI( + IPPROTO_TCP, ALPROTO_SMTP, "HELO", 4, 0, STREAM_TOSERVER) < 0) { return -1; } - if (AppLayerProtoDetectPMRegisterPatternCI(IPPROTO_TCP, ALPROTO_SMTP, - "QUIT", 4, 0, STREAM_TOSERVER) < 0) - { + if (AppLayerProtoDetectPMRegisterPatternCI( + IPPROTO_TCP, ALPROTO_SMTP, "QUIT", 4, 0, STREAM_TOSERVER) < 0) { return -1; } return 0; } -static void SMTPStateTransactionFree (void *state, uint64_t tx_id) +static void SMTPStateTransactionFree(void *state, uint64_t tx_id) { SMTPState *smtp_state = state; SMTPTransaction *tx = NULL; - TAILQ_FOREACH(tx, &smtp_state->tx_list, next) { + TAILQ_FOREACH (tx, &smtp_state->tx_list, next) { if (tx_id < tx->tx_id) break; else if (tx_id > tx->tx_id) @@ -1753,8 +1733,6 @@ static void SMTPStateTransactionFree (void *state, uint64_t tx_id) SMTPTransactionFree(tx, state); break; } - - } /** \retval cnt highest tx id */ @@ -1765,7 +1743,7 @@ static uint64_t SMTPStateGetTxCnt(void *state) if (smtp_state) { cnt = smtp_state->tx_cnt; } - SCLogDebug("returning %"PRIu64, cnt); + SCLogDebug("returning %" PRIu64, cnt); return cnt; } @@ -1780,13 +1758,12 @@ static void *SMTPStateGetTx(void *state, uint64_t id) if (smtp_state->curr_tx->tx_id == id) return smtp_state->curr_tx; - TAILQ_FOREACH(tx, &smtp_state->tx_list, next) { + TAILQ_FOREACH (tx, &smtp_state->tx_list, next) { if (tx->tx_id == id) return tx; } } return NULL; - } static int SMTPStateGetAlstateProgress(void *vtx, uint8_t direction) @@ -1865,31 +1842,32 @@ void RegisterSMTPParsers(void) if (AppLayerProtoDetectConfProtoDetectionEnabled("tcp", proto_name)) { AppLayerProtoDetectRegisterProtocol(ALPROTO_SMTP, proto_name); - if (SMTPRegisterPatternsForProtocolDetection() < 0 ) + if (SMTPRegisterPatternsForProtocolDetection() < 0) return; } else { - SCLogInfo("Protocol detection and parser disabled for %s protocol.", - proto_name); + SCLogInfo("Protocol detection and parser disabled for %s protocol.", proto_name); return; } if (AppLayerParserConfParserEnabled("tcp", proto_name)) { AppLayerParserRegisterStateFuncs(IPPROTO_TCP, ALPROTO_SMTP, SMTPStateAlloc, SMTPStateFree); - AppLayerParserRegisterParser(IPPROTO_TCP, ALPROTO_SMTP, STREAM_TOSERVER, - SMTPParseClientRecord); - AppLayerParserRegisterParser(IPPROTO_TCP, ALPROTO_SMTP, STREAM_TOCLIENT, - SMTPParseServerRecord); + AppLayerParserRegisterParser( + IPPROTO_TCP, ALPROTO_SMTP, STREAM_TOSERVER, SMTPParseClientRecord); + AppLayerParserRegisterParser( + IPPROTO_TCP, ALPROTO_SMTP, STREAM_TOCLIENT, SMTPParseServerRecord); AppLayerParserRegisterGetEventInfo(IPPROTO_TCP, ALPROTO_SMTP, SMTPStateGetEventInfo); - AppLayerParserRegisterGetEventInfoById(IPPROTO_TCP, ALPROTO_SMTP, SMTPStateGetEventInfoById); + AppLayerParserRegisterGetEventInfoById( + IPPROTO_TCP, ALPROTO_SMTP, SMTPStateGetEventInfoById); - AppLayerParserRegisterLocalStorageFunc(IPPROTO_TCP, ALPROTO_SMTP, SMTPLocalStorageAlloc, - SMTPLocalStorageFree); + AppLayerParserRegisterLocalStorageFunc( + IPPROTO_TCP, ALPROTO_SMTP, SMTPLocalStorageAlloc, SMTPLocalStorageFree); AppLayerParserRegisterTxFreeFunc(IPPROTO_TCP, ALPROTO_SMTP, SMTPStateTransactionFree); AppLayerParserRegisterGetTxFilesFunc(IPPROTO_TCP, ALPROTO_SMTP, SMTPGetTxFiles); - AppLayerParserRegisterGetStateProgressFunc(IPPROTO_TCP, ALPROTO_SMTP, SMTPStateGetAlstateProgress); + AppLayerParserRegisterGetStateProgressFunc( + IPPROTO_TCP, ALPROTO_SMTP, SMTPStateGetAlstateProgress); AppLayerParserRegisterGetTxCnt(IPPROTO_TCP, ALPROTO_SMTP, SMTPStateGetTxCnt); AppLayerParserRegisterGetTx(IPPROTO_TCP, ALPROTO_SMTP, SMTPStateGetTx); AppLayerParserRegisterGetTxIterator(IPPROTO_TCP, ALPROTO_SMTP, SMTPGetTxIterator); @@ -1898,7 +1876,8 @@ void RegisterSMTPParsers(void) AppLayerParserRegisterStateProgressCompletionStatus(ALPROTO_SMTP, 1, 1); } else { SCLogInfo("Parsed disabled for %s protocol. Protocol detection" - "still on.", proto_name); + "still on.", + proto_name); } SMTPSetMpmState(); @@ -2027,8 +2006,8 @@ static int SMTPParserTest01(void) StreamTcpInitConfig(true); SMTPTestInitConfig(); - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, - STREAM_TOCLIENT, welcome_reply, welcome_reply_len); + r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_SMTP, STREAM_TOCLIENT, welcome_reply, welcome_reply_len); if (r != 0) { printf("smtp check returned %" PRId32 ", expected 0: ", r); goto end; @@ -2044,8 +2023,8 @@ static int SMTPParserTest01(void) goto end; } - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, - STREAM_TOSERVER, request1, request1_len); + r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_SMTP, STREAM_TOSERVER, request1, request1_len); if (r != 0) { printf("smtp check returned %" PRId32 ", expected 0: ", r); goto end; @@ -2057,8 +2036,7 @@ static int SMTPParserTest01(void) goto end; } - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, - STREAM_TOCLIENT, reply1, reply1_len); + r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, STREAM_TOCLIENT, reply1, reply1_len); if (r != 0) { printf("smtp check returned %" PRId32 ", expected 0: ", r); goto end; @@ -2069,8 +2047,8 @@ static int SMTPParserTest01(void) goto end; } - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, - STREAM_TOSERVER, request2, request2_len); + r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_SMTP, STREAM_TOSERVER, request2, request2_len); if (r != 0) { printf("smtp check returned %" PRId32 ", expected 0: ", r); goto end; @@ -2082,8 +2060,7 @@ static int SMTPParserTest01(void) goto end; } - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, - STREAM_TOCLIENT, reply2, reply2_len); + r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, STREAM_TOCLIENT, reply2, reply2_len); if (r != 0) { printf("smtp check returned %" PRId32 ", expected 0: ", r); goto end; @@ -2415,8 +2392,8 @@ static int SMTPParserTest02(void) StreamTcpInitConfig(true); SMTPTestInitConfig(); - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, - STREAM_TOCLIENT, welcome_reply, welcome_reply_len); + r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_SMTP, STREAM_TOCLIENT, welcome_reply, welcome_reply_len); if (r != 0) { printf("smtp check returned %" PRId32 ", expected 0: ", r); goto end; @@ -2432,8 +2409,8 @@ static int SMTPParserTest02(void) goto end; } - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, - STREAM_TOSERVER, request1, request1_len); + r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_SMTP, STREAM_TOSERVER, request1, request1_len); if (r != 0) { printf("smtp check returned %" PRId32 ", expected 0: ", r); goto end; @@ -2445,8 +2422,7 @@ static int SMTPParserTest02(void) goto end; } - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, - STREAM_TOCLIENT, reply1, reply1_len); + r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, STREAM_TOCLIENT, reply1, reply1_len); if (r != 0) { printf("smtp check returned %" PRId32 ", expected 0: ", r); goto end; @@ -2457,8 +2433,8 @@ static int SMTPParserTest02(void) goto end; } - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, - STREAM_TOSERVER, request2, request2_len); + r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_SMTP, STREAM_TOSERVER, request2, request2_len); if (r != 0) { printf("smtp check returned %" PRId32 ", expected 0: ", r); goto end; @@ -2470,8 +2446,7 @@ static int SMTPParserTest02(void) goto end; } - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, - STREAM_TOCLIENT, reply2, reply2_len); + r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, STREAM_TOCLIENT, reply2, reply2_len); if (r != 0) { printf("smtp check returned %" PRId32 ", expected 0: ", r); goto end; @@ -2482,8 +2457,8 @@ static int SMTPParserTest02(void) goto end; } - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, - STREAM_TOSERVER, request3, request3_len); + r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_SMTP, STREAM_TOSERVER, request3, request3_len); if (r != 0) { printf("smtp check returned %" PRId32 ", expected 0: ", r); goto end; @@ -2495,8 +2470,7 @@ static int SMTPParserTest02(void) goto end; } - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, - STREAM_TOCLIENT, reply3, reply3_len); + r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, STREAM_TOCLIENT, reply3, reply3_len); if (r != 0) { printf("smtp check returned %" PRId32 ", expected 0: ", r); goto end; @@ -2507,8 +2481,8 @@ static int SMTPParserTest02(void) goto end; } - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, - STREAM_TOSERVER, request4, request4_len); + r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_SMTP, STREAM_TOSERVER, request4, request4_len); if (r != 0) { printf("smtp check returned %" PRId32 ", expected 0: ", r); goto end; @@ -2520,8 +2494,7 @@ static int SMTPParserTest02(void) goto end; } - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, - STREAM_TOCLIENT, reply4, reply4_len); + r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, STREAM_TOCLIENT, reply4, reply4_len); if (r != 0) { printf("smtp check returned %" PRId32 ", expected 0: ", r); goto end; @@ -2533,8 +2506,8 @@ static int SMTPParserTest02(void) goto end; } - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, - STREAM_TOSERVER, request5_1, request5_1_len); + r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_SMTP, STREAM_TOSERVER, request5_1, request5_1_len); if (r != 0) { printf("smtp check returned %" PRId32 ", expected 0: ", r); goto end; @@ -2547,8 +2520,8 @@ static int SMTPParserTest02(void) goto end; } - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, - STREAM_TOSERVER, request5_2, request5_2_len); + r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_SMTP, STREAM_TOSERVER, request5_2, request5_2_len); if (r != 0) { printf("smtp check returned %" PRId32 ", expected 0: ", r); goto end; @@ -2561,8 +2534,8 @@ static int SMTPParserTest02(void) goto end; } - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, - STREAM_TOSERVER, request5_3, request5_3_len); + r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_SMTP, STREAM_TOSERVER, request5_3, request5_3_len); if (r != 0) { printf("smtp check returned %" PRId32 ", expected 0: ", r); goto end; @@ -2575,8 +2548,8 @@ static int SMTPParserTest02(void) goto end; } - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, - STREAM_TOSERVER, request5_4, request5_4_len); + r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_SMTP, STREAM_TOSERVER, request5_4, request5_4_len); if (r != 0) { printf("smtp check returned %" PRId32 ", expected 0: ", r); goto end; @@ -2589,8 +2562,8 @@ static int SMTPParserTest02(void) goto end; } - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, - STREAM_TOSERVER, request5_5, request5_5_len); + r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_SMTP, STREAM_TOSERVER, request5_5, request5_5_len); if (r != 0) { printf("smtp check returned %" PRId32 ", expected 0: ", r); goto end; @@ -2602,8 +2575,7 @@ static int SMTPParserTest02(void) goto end; } - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, - STREAM_TOCLIENT, reply5, reply5_len); + r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, STREAM_TOCLIENT, reply5, reply5_len); if (r != 0) { printf("smtp check returned %" PRId32 ", expected 0: ", r); goto end; @@ -2614,8 +2586,8 @@ static int SMTPParserTest02(void) goto end; } - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, - STREAM_TOSERVER, request6, request6_len); + r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_SMTP, STREAM_TOSERVER, request6, request6_len); if (r != 0) { printf("smtp check returned %" PRId32 ", expected 0: ", r); goto end; @@ -2627,8 +2599,7 @@ static int SMTPParserTest02(void) goto end; } - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, - STREAM_TOCLIENT, reply6, reply6_len); + r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, STREAM_TOCLIENT, reply6, reply6_len); if (r != 0) { printf("smtp check returned %" PRId32 ", expected 0: ", r); goto end; @@ -2639,8 +2610,8 @@ static int SMTPParserTest02(void) goto end; } - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, - STREAM_TOSERVER, request7, request7_len); + r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_SMTP, STREAM_TOSERVER, request7, request7_len); if (r != 0) { printf("smtp check returned %" PRId32 ", expected 0: ", r); goto end; @@ -2652,8 +2623,7 @@ static int SMTPParserTest02(void) goto end; } - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, - STREAM_TOCLIENT, reply7, reply7_len); + r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, STREAM_TOCLIENT, reply7, reply7_len); if (r != 0) { printf("smtp check returned %" PRId32 ", expected 0: ", r); goto end; @@ -2664,8 +2634,8 @@ static int SMTPParserTest02(void) goto end; } - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, - STREAM_TOSERVER, request8, request8_len); + r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_SMTP, STREAM_TOSERVER, request8, request8_len); if (r != 0) { printf("smtp check returned %" PRId32 ", expected 0: ", r); goto end; @@ -2677,8 +2647,7 @@ static int SMTPParserTest02(void) goto end; } - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, - STREAM_TOCLIENT, reply8, reply8_len); + r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, STREAM_TOCLIENT, reply8, reply8_len); if (r != 0) { printf("smtp check returned %" PRId32 ", expected 0: ", r); goto end; @@ -2690,8 +2659,8 @@ static int SMTPParserTest02(void) goto end; } - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, - STREAM_TOSERVER, request9_1, request9_1_len); + r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_SMTP, STREAM_TOSERVER, request9_1, request9_1_len); if (r != 0) { printf("smtp check returned %" PRId32 ", expected 0: ", r); goto end; @@ -2704,8 +2673,8 @@ static int SMTPParserTest02(void) goto end; } - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, - STREAM_TOSERVER, request9_2, request9_2_len); + r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_SMTP, STREAM_TOSERVER, request9_2, request9_2_len); if (r != 0) { printf("smtp check returned %" PRId32 ", expected 0: ", r); goto end; @@ -2718,8 +2687,8 @@ static int SMTPParserTest02(void) goto end; } - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, - STREAM_TOSERVER, request9_3, request9_3_len); + r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_SMTP, STREAM_TOSERVER, request9_3, request9_3_len); if (r != 0) { printf("smtp check returned %" PRId32 ", expected 0: ", r); goto end; @@ -2732,8 +2701,8 @@ static int SMTPParserTest02(void) goto end; } - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, - STREAM_TOSERVER, request9_4, request9_4_len); + r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_SMTP, STREAM_TOSERVER, request9_4, request9_4_len); if (r != 0) { printf("smtp check returned %" PRId32 ", expected 0: ", r); goto end; @@ -2746,8 +2715,8 @@ static int SMTPParserTest02(void) goto end; } - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, - STREAM_TOSERVER, request9_5, request9_5_len); + r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_SMTP, STREAM_TOSERVER, request9_5, request9_5_len); if (r != 0) { printf("smtp check returned %" PRId32 ", expected 0: ", r); goto end; @@ -2759,8 +2728,7 @@ static int SMTPParserTest02(void) goto end; } - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, - STREAM_TOCLIENT, reply9, reply9_len); + r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, STREAM_TOCLIENT, reply9, reply9_len); if (r != 0) { printf("smtp check returned %" PRId32 ", expected 0: ", r); goto end; @@ -2771,8 +2739,8 @@ static int SMTPParserTest02(void) goto end; } - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, - STREAM_TOSERVER, request10, request10_len); + r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_SMTP, STREAM_TOSERVER, request10, request10_len); if (r != 0) { printf("smtp check returned %" PRId32 ", expected 0: ", r); goto end; @@ -2784,8 +2752,8 @@ static int SMTPParserTest02(void) goto end; } - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, - STREAM_TOCLIENT, reply10, reply10_len); + r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_SMTP, STREAM_TOCLIENT, reply10, reply10_len); if (r != 0) { printf("smtp check returned %" PRId32 ", expected 0: ", r); goto end; @@ -2919,8 +2887,8 @@ static int SMTPParserTest03(void) StreamTcpInitConfig(true); SMTPTestInitConfig(); - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, - STREAM_TOCLIENT, welcome_reply, welcome_reply_len); + r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_SMTP, STREAM_TOCLIENT, welcome_reply, welcome_reply_len); if (r != 0) { printf("smtp check returned %" PRId32 ", expected 0: ", r); goto end; @@ -2936,8 +2904,8 @@ static int SMTPParserTest03(void) goto end; } - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, - STREAM_TOSERVER, request1, request1_len); + r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_SMTP, STREAM_TOSERVER, request1, request1_len); if (r != 0) { printf("smtp check returned %" PRId32 ", expected 0: ", r); goto end; @@ -2949,8 +2917,7 @@ static int SMTPParserTest03(void) goto end; } - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, - STREAM_TOCLIENT, reply1, reply1_len); + r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, STREAM_TOCLIENT, reply1, reply1_len); if (r != 0) { printf("smtp check returned %" PRId32 ", expected 0: ", r); goto end; @@ -2962,8 +2929,8 @@ static int SMTPParserTest03(void) goto end; } - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, - STREAM_TOSERVER, request2, request2_len); + r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_SMTP, STREAM_TOSERVER, request2, request2_len); if (r != 0) { printf("smtp check returned %" PRId32 ", expected 0: ", r); goto end; @@ -2979,8 +2946,7 @@ static int SMTPParserTest03(void) goto end; } - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, - STREAM_TOCLIENT, reply2, reply2_len); + r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, STREAM_TOCLIENT, reply2, reply2_len); if (r != 0) { printf("smtp check returned %" PRId32 ", expected 0: ", r); goto end; @@ -3051,8 +3017,8 @@ static int SMTPParserTest04(void) StreamTcpInitConfig(true); SMTPTestInitConfig(); - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, - STREAM_TOCLIENT, welcome_reply, welcome_reply_len); + r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_SMTP, STREAM_TOCLIENT, welcome_reply, welcome_reply_len); if (r != 0) { printf("smtp check returned %" PRId32 ", expected 0: ", r); goto end; @@ -3068,8 +3034,8 @@ static int SMTPParserTest04(void) goto end; } - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, - STREAM_TOSERVER, request1, request1_len); + r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_SMTP, STREAM_TOSERVER, request1, request1_len); if (r != 0) { printf("smtp check returned %" PRId32 ", expected 0: ", r); goto end; @@ -3204,8 +3170,8 @@ static int SMTPParserTest05(void) StreamTcpInitConfig(true); SMTPTestInitConfig(); - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, - STREAM_TOCLIENT, welcome_reply, welcome_reply_len); + r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_SMTP, STREAM_TOCLIENT, welcome_reply, welcome_reply_len); if (r != 0) { printf("smtp check returned %" PRId32 ", expected 0: ", r); goto end; @@ -3221,8 +3187,8 @@ static int SMTPParserTest05(void) goto end; } - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, - STREAM_TOSERVER, request1, request1_len); + r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_SMTP, STREAM_TOSERVER, request1, request1_len); if (r != 0) { printf("smtp check returned %" PRId32 ", expected 0: ", r); goto end; @@ -3234,8 +3200,7 @@ static int SMTPParserTest05(void) goto end; } - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, - STREAM_TOCLIENT, reply1, reply1_len); + r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, STREAM_TOCLIENT, reply1, reply1_len); if (r != 0) { printf("smtp check returned %" PRId32 ", expected 0: ", r); goto end; @@ -3247,8 +3212,8 @@ static int SMTPParserTest05(void) goto end; } - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, - STREAM_TOSERVER, request2, request2_len); + r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_SMTP, STREAM_TOSERVER, request2, request2_len); if (r != 0) { printf("smtp check returned %" PRId32 ", expected 0: ", r); goto end; @@ -3261,8 +3226,7 @@ static int SMTPParserTest05(void) goto end; } - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, - STREAM_TOCLIENT, reply2, reply2_len); + r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, STREAM_TOCLIENT, reply2, reply2_len); if (r != 0) { printf("smtp check returned %" PRId32 ", expected 0: ", r); goto end; @@ -3274,15 +3238,14 @@ static int SMTPParserTest05(void) goto end; } - if ((f.flags & FLOW_NOPAYLOAD_INSPECTION) || - (ssn.flags & STREAMTCP_FLAG_APP_LAYER_DISABLED) || - (((TcpSession *)f.protoctx)->server.flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY) || - (((TcpSession *)f.protoctx)->client.flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY)) { + if ((f.flags & FLOW_NOPAYLOAD_INSPECTION) || (ssn.flags & STREAMTCP_FLAG_APP_LAYER_DISABLED) || + (((TcpSession *)f.protoctx)->server.flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY) || + (((TcpSession *)f.protoctx)->client.flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY)) { goto end; } - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, - STREAM_TOSERVER, request3, request3_len); + r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_SMTP, STREAM_TOSERVER, request3, request3_len); if (r != 0) { printf("smtp check returned %" PRId32 ", expected 0: ", r); goto end; @@ -3295,8 +3258,7 @@ static int SMTPParserTest05(void) goto end; } - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, - STREAM_TOCLIENT, reply3, reply3_len); + r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, STREAM_TOCLIENT, reply3, reply3_len); if (r != 0) { printf("smtp check returned %" PRId32 ", expected 0: ", r); goto end; @@ -3490,8 +3452,8 @@ static int SMTPParserTest06(void) StreamTcpInitConfig(true); SMTPTestInitConfig(); - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, - STREAM_TOCLIENT, welcome_reply, welcome_reply_len); + r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_SMTP, STREAM_TOCLIENT, welcome_reply, welcome_reply_len); if (r != 0) { printf("smtp check returned %" PRId32 ", expected 0: ", r); goto end; @@ -3507,8 +3469,8 @@ static int SMTPParserTest06(void) goto end; } - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, - STREAM_TOSERVER, request1, request1_len); + r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_SMTP, STREAM_TOSERVER, request1, request1_len); if (r != 0) { printf("smtp check returned %" PRId32 ", expected 0: ", r); goto end; @@ -3520,8 +3482,7 @@ static int SMTPParserTest06(void) goto end; } - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, - STREAM_TOCLIENT, reply1, reply1_len); + r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, STREAM_TOCLIENT, reply1, reply1_len); if (r != 0) { printf("smtp check returned %" PRId32 ", expected 0: ", r); goto end; @@ -3532,8 +3493,8 @@ static int SMTPParserTest06(void) goto end; } - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, - STREAM_TOSERVER, request2, request2_len); + r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_SMTP, STREAM_TOSERVER, request2, request2_len); if (r != 0) { printf("smtp check returned %" PRId32 ", expected 0: ", r); goto end; @@ -3545,8 +3506,7 @@ static int SMTPParserTest06(void) goto end; } - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, - STREAM_TOCLIENT, reply2, reply2_len); + r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, STREAM_TOCLIENT, reply2, reply2_len); if (r != 0) { printf("smtp check returned %" PRId32 ", expected 0: ", r); goto end; @@ -3557,8 +3517,8 @@ static int SMTPParserTest06(void) goto end; } - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, - STREAM_TOSERVER, request3, request3_len); + r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_SMTP, STREAM_TOSERVER, request3, request3_len); if (r != 0) { printf("smtp check returned %" PRId32 ", expected 0: ", r); goto end; @@ -3570,8 +3530,7 @@ static int SMTPParserTest06(void) goto end; } - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, - STREAM_TOCLIENT, reply3, reply3_len); + r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, STREAM_TOCLIENT, reply3, reply3_len); if (r != 0) { printf("smtp check returned %" PRId32 ", expected 0: ", r); goto end; @@ -3582,8 +3541,8 @@ static int SMTPParserTest06(void) goto end; } - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, - STREAM_TOSERVER, request4, request4_len); + r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_SMTP, STREAM_TOSERVER, request4, request4_len); if (r != 0) { printf("smtp check returned %" PRId32 ", expected 0: ", r); goto end; @@ -3597,8 +3556,8 @@ static int SMTPParserTest06(void) goto end; } - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, - STREAM_TOSERVER, request5, request5_len); + r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_SMTP, STREAM_TOSERVER, request5, request5_len); if (r != 0) { printf("smtp check returned %" PRId32 ", expected 0: ", r); goto end; @@ -3611,8 +3570,8 @@ static int SMTPParserTest06(void) goto end; } - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, - STREAM_TOSERVER, request6, request6_len); + r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_SMTP, STREAM_TOSERVER, request6, request6_len); if (r != 0) { printf("smtp check returned %" PRId32 ", expected 0: ", r); goto end; @@ -3679,7 +3638,7 @@ static int SMTPParserTest12(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_SMTP; StreamTcpInitConfig(true); @@ -3691,19 +3650,18 @@ static int SMTPParserTest12(void) de_ctx->flags |= DE_QUIET; - s = DetectEngineAppendSig(de_ctx,"alert tcp any any -> any any " - "(msg:\"SMTP event handling\"; " - "app-layer-event: smtp.invalid_reply; " - "sid:1;)"); + s = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any " + "(msg:\"SMTP event handling\"; " + "app-layer-event: smtp.invalid_reply; " + "sid:1;)"); if (s == NULL) goto end; SigGroupBuild(de_ctx); DetectEngineThreadCtxInit(&th_v, (void *)de_ctx, (void *)&det_ctx); - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, - STREAM_TOSERVER | STREAM_START, request1, - request1_len); + r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, STREAM_TOSERVER | STREAM_START, + request1, request1_len); if (r != 0) { printf("AppLayerParse for smtp failed. Returned %" PRId32, r); goto end; @@ -3723,9 +3681,8 @@ static int SMTPParserTest12(void) goto end; } - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, - STREAM_TOCLIENT | STREAM_TOCLIENT, reply1, - reply1_len); + r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, STREAM_TOCLIENT | STREAM_TOCLIENT, + reply1, reply1_len); if (r == 0) { printf("AppLayerParse for smtp failed. Returned %" PRId32, r); goto end; @@ -3822,7 +3779,7 @@ static int SMTPParserTest13(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_SMTP; StreamTcpInitConfig(true); @@ -3835,19 +3792,18 @@ static int SMTPParserTest13(void) de_ctx->flags |= DE_QUIET; s = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any " - "(msg:\"SMTP event handling\"; " - "app-layer-event: " - "smtp.invalid_pipelined_sequence; " - "sid:1;)"); + "(msg:\"SMTP event handling\"; " + "app-layer-event: " + "smtp.invalid_pipelined_sequence; " + "sid:1;)"); if (s == NULL) goto end; SigGroupBuild(de_ctx); DetectEngineThreadCtxInit(&th_v, (void *)de_ctx, (void *)&det_ctx); - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, - STREAM_TOSERVER | STREAM_START, request1, - request1_len); + r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, STREAM_TOSERVER | STREAM_START, + request1, request1_len); if (r != 0) { printf("AppLayerParse for smtp failed. Returned %" PRId32, r); goto end; @@ -3867,8 +3823,7 @@ static int SMTPParserTest13(void) goto end; } - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, - STREAM_TOCLIENT, reply1, reply1_len); + r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, STREAM_TOCLIENT, reply1, reply1_len); if (r != 0) { printf("AppLayerParse for smtp failed. Returned %" PRId32, r); goto end; @@ -3882,8 +3837,8 @@ static int SMTPParserTest13(void) goto end; } - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, - STREAM_TOSERVER, request2, request2_len); + r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_SMTP, STREAM_TOSERVER, request2, request2_len); if (r != 0) { printf("AppLayerParse for smtp failed. Returned %" PRId32, r); goto end; @@ -4127,8 +4082,8 @@ static int SMTPParserTest14(void) SMTPTestInitConfig(); /* Welcome reply */ - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, - STREAM_TOCLIENT, welcome_reply, welcome_reply_len); + r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_SMTP, STREAM_TOCLIENT, welcome_reply, welcome_reply_len); if (r != 0) { printf("smtp check returned %" PRId32 ", expected 0: ", r); goto end; @@ -4144,8 +4099,8 @@ static int SMTPParserTest14(void) goto end; } - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, - STREAM_TOSERVER, request1, request1_len); + r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_SMTP, STREAM_TOSERVER, request1, request1_len); if (r != 0) { printf("smtp check returned %" PRId32 ", expected 0: ", r); goto end; @@ -4158,15 +4113,15 @@ static int SMTPParserTest14(void) } /* EHLO Reply */ - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, - STREAM_TOCLIENT, reply1, reply1_len); + r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, STREAM_TOCLIENT, reply1, reply1_len); if (r != 0) { printf("smtp check returned %" PRId32 ", expected 0: ", r); goto end; } if ((smtp_state->helo_len != 7) || strncmp("boo.com", (char *)smtp_state->helo, 7)) { - printf("incorrect parsing of HELO field '%s' (%d)\n", smtp_state->helo, smtp_state->helo_len); + printf("incorrect parsing of HELO field '%s' (%d)\n", smtp_state->helo, + smtp_state->helo_len); goto end; } @@ -4177,8 +4132,8 @@ static int SMTPParserTest14(void) } /* MAIL FROM Request */ - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, - STREAM_TOSERVER, request2, request2_len); + r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_SMTP, STREAM_TOSERVER, request2, request2_len); if (r != 0) { printf("smtp check returned %" PRId32 ", expected 0: ", r); goto end; @@ -4191,18 +4146,16 @@ static int SMTPParserTest14(void) } /* MAIL FROM Reply */ - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, - STREAM_TOCLIENT, reply2, reply2_len); + r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, STREAM_TOCLIENT, reply2, reply2_len); if (r != 0) { printf("smtp check returned %" PRId32 ", expected 0: ", r); goto end; } if ((smtp_state->curr_tx->mail_from_len != 14) || - strncmp("asdff@asdf.com", (char *)smtp_state->curr_tx->mail_from, 14)) { - printf("incorrect parsing of MAIL FROM field '%s' (%d)\n", - smtp_state->curr_tx->mail_from, - smtp_state->curr_tx->mail_from_len); + strncmp("asdff@asdf.com", (char *)smtp_state->curr_tx->mail_from, 14)) { + printf("incorrect parsing of MAIL FROM field '%s' (%d)\n", smtp_state->curr_tx->mail_from, + smtp_state->curr_tx->mail_from_len); goto end; } @@ -4213,8 +4166,8 @@ static int SMTPParserTest14(void) } /* RCPT TO Request */ - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, - STREAM_TOSERVER, request3, request3_len); + r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_SMTP, STREAM_TOSERVER, request3, request3_len); if (r != 0) { printf("smtp check returned %" PRId32 ", expected 0: ", r); goto end; @@ -4227,8 +4180,7 @@ static int SMTPParserTest14(void) } /* RCPT TO Reply */ - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, - STREAM_TOCLIENT, reply3, reply3_len); + r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, STREAM_TOCLIENT, reply3, reply3_len); if (r != 0) { printf("smtp check returned %" PRId32 ", expected 0: ", r); goto end; @@ -4246,8 +4198,8 @@ static int SMTPParserTest14(void) MimeDecSetConfig(&smtp_config.mime_config); /* DATA request */ - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, - STREAM_TOSERVER, request4, request4_len); + r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_SMTP, STREAM_TOSERVER, request4, request4_len); if (r != 0) { printf("smtp check returned %" PRId32 ", expected 0: ", r); goto end; @@ -4261,8 +4213,7 @@ static int SMTPParserTest14(void) } /* Data reply */ - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, - STREAM_TOCLIENT, reply4, reply4_len); + r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, STREAM_TOCLIENT, reply4, reply4_len); if (r != 0) { printf("smtp check returned %" PRId32 ", expected 0: ", r); goto end; @@ -4275,8 +4226,8 @@ static int SMTPParserTest14(void) } /* DATA message */ - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, - STREAM_TOSERVER, request4_msg, request4_msg_len); + r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_SMTP, STREAM_TOSERVER, request4_msg, request4_msg_len); if (r != 0) { printf("smtp check returned %" PRId32 ", expected 0: ", r); goto end; @@ -4292,8 +4243,8 @@ static int SMTPParserTest14(void) } /* DATA . request */ - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, - STREAM_TOSERVER, request4_end, request4_end_len); + r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_SMTP, STREAM_TOSERVER, request4_end, request4_end_len); if (r != 0) { printf("smtp check returned %" PRId32 ", expected 0: ", r); goto end; @@ -4308,7 +4259,7 @@ static int SMTPParserTest14(void) goto end; } - SMTPState *state = (SMTPState *) f.alstate; + SMTPState *state = (SMTPState *)f.alstate; FAIL_IF_NULL(state); FAIL_IF_NULL(state->curr_tx); @@ -4316,12 +4267,12 @@ static int SMTPParserTest14(void) if (files != NULL && files->head != NULL) { File *file = files->head; - if(strncmp((const char *)file->name, "test.exe", 8) != 0){ + if (strncmp((const char *)file->name, "test.exe", 8) != 0) { printf("smtp-mime file name is incorrect"); goto end; } - if (FileTrackedSize(file) != filesize){ - printf("smtp-mime file size %"PRIu64" is incorrect", FileDataSize(file)); + if (FileTrackedSize(file) != filesize) { + printf("smtp-mime file size %" PRIu64 " is incorrect", FileDataSize(file)); goto end; } // clang-format off @@ -4345,17 +4296,15 @@ static int SMTPParserTest14(void) 0x5C, 0x7A, 0x00, 0x00, 0x38,}; // clang-format on - if (StreamingBufferCompareRawData(file->sb, - org_binary, sizeof(org_binary)) != 1) - { + if (StreamingBufferCompareRawData(file->sb, org_binary, sizeof(org_binary)) != 1) { printf("smtp-mime file data incorrect\n"); goto end; } } /* DATA . reply */ - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, - STREAM_TOCLIENT, reply4_end, reply4_end_len); + r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_SMTP, STREAM_TOCLIENT, reply4_end, reply4_end_len); if (r != 0) { printf("smtp check returned %" PRId32 ", expected 0: ", r); goto end; @@ -4367,8 +4316,8 @@ static int SMTPParserTest14(void) } /* QUIT Request */ - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, - STREAM_TOSERVER, request5, request5_len); + r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_SMTP, STREAM_TOSERVER, request5, request5_len); if (r != 0) { printf("smtp check returned %" PRId32 ", expected 0: ", r); goto end; @@ -4381,8 +4330,7 @@ static int SMTPParserTest14(void) } /* QUIT Reply */ - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, - STREAM_TOCLIENT, reply5, reply5_len); + r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SMTP, STREAM_TOCLIENT, reply5, reply5_len); if (r != 0) { printf("smtp check returned %" PRId32 ", expected 0: ", r); goto end; diff --git a/src/app-layer-smtp.h b/src/app-layer-smtp.h index 9fc1d506bbbb..f6d86ed84f0a 100644 --- a/src/app-layer-smtp.h +++ b/src/app-layer-smtp.h @@ -87,7 +87,7 @@ typedef struct SMTPTransaction_ { uint8_t *mail_from; uint16_t mail_from_len; - TAILQ_HEAD(, SMTPString_) rcpt_to_list; /**< rcpt to string list */ + TAILQ_HEAD(, SMTPString_) rcpt_to_list; /**< rcpt to string list */ FileContainer files_ts; @@ -110,7 +110,7 @@ typedef struct SMTPConfig { typedef struct SMTPState_ { AppLayerStateData state_data; SMTPTransaction *curr_tx; - TAILQ_HEAD(, SMTPTransaction_) tx_list; /**< transaction list */ + TAILQ_HEAD(, SMTPTransaction_) tx_list; /**< transaction list */ uint64_t tx_cnt; uint64_t toserver_data_count; uint64_t toserver_last_data_stamp; diff --git a/src/app-layer-snmp.c b/src/app-layer-snmp.c index 589aa451ed48..558cce6a9707 100644 --- a/src/app-layer-snmp.c +++ b/src/app-layer-snmp.c @@ -40,4 +40,3 @@ void RegisterSNMPParsers(void) { rs_register_snmp_parser(); } - diff --git a/src/app-layer-ssh.c b/src/app-layer-ssh.c index 3f4a964d9b32..d6b64adc5faf 100644 --- a/src/app-layer-ssh.c +++ b/src/app-layer-ssh.c @@ -58,14 +58,12 @@ static int SSHRegisterPatternsForProtocolDetection(void) { - if (AppLayerProtoDetectPMRegisterPatternCI(IPPROTO_TCP, ALPROTO_SSH, - "SSH-", 4, 0, STREAM_TOSERVER) < 0) - { + if (AppLayerProtoDetectPMRegisterPatternCI( + IPPROTO_TCP, ALPROTO_SSH, "SSH-", 4, 0, STREAM_TOSERVER) < 0) { return -1; } - if (AppLayerProtoDetectPMRegisterPatternCI(IPPROTO_TCP, ALPROTO_SSH, - "SSH-", 4, 0, STREAM_TOCLIENT) < 0) - { + if (AppLayerProtoDetectPMRegisterPatternCI( + IPPROTO_TCP, ALPROTO_SSH, "SSH-", 4, 0, STREAM_TOCLIENT) < 0) { return -1; } return 0; @@ -108,7 +106,6 @@ void RegisterSSHParsers(void) SCLogDebug("Registering Rust SSH parser."); rs_ssh_register_parser(); - #ifdef UNITTESTS AppLayerParserRegisterProtocolUnittests(IPPROTO_TCP, ALPROTO_SSH, SSHParserRegisterTests); #endif @@ -120,7 +117,9 @@ void RegisterSSHParsers(void) #include "stream-tcp-util.h" #include "util-unittest-helper.h" -static int SSHParserTestUtilCheck(const char *protoexp, const char *softexp, void *tx, uint8_t flags) { +static int SSHParserTestUtilCheck( + const char *protoexp, const char *softexp, void *tx, uint8_t flags) +{ const uint8_t *protocol = NULL; uint32_t p_len = 0; const uint8_t *software = NULL; @@ -179,8 +178,8 @@ static int SSHParserTest01(void) StreamTcpInitConfig(true); - int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SSH, - STREAM_TOSERVER | STREAM_EOF, sshbuf, sshlen); + int r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_SSH, STREAM_TOSERVER | STREAM_EOF, sshbuf, sshlen); if (r != 0) { printf("toclient chunk 1 returned %" PRId32 ", expected 0: ", r); goto end; @@ -192,8 +191,8 @@ static int SSHParserTest01(void) goto end; } - void * tx = rs_ssh_state_get_tx(ssh_state, 0); - if ( rs_ssh_tx_get_alstate_progress(tx, STREAM_TOSERVER) != SshStateBannerDone ) { + void *tx = rs_ssh_state_get_tx(ssh_state, 0); + if (rs_ssh_tx_get_alstate_progress(tx, STREAM_TOSERVER) != SshStateBannerDone) { printf("Client version string not parsed: "); goto end; } @@ -230,8 +229,8 @@ static int SSHParserTest02(void) StreamTcpInitConfig(true); - int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SSH, - STREAM_TOSERVER | STREAM_EOF, sshbuf, sshlen); + int r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_SSH, STREAM_TOSERVER | STREAM_EOF, sshbuf, sshlen); if (r != 0) { printf("toclient chunk 1 returned %" PRId32 ", expected 0: ", r); goto end; @@ -242,9 +241,9 @@ static int SSHParserTest02(void) printf("no ssh state: "); goto end; } - void * tx = rs_ssh_state_get_tx(ssh_state, 0); + void *tx = rs_ssh_state_get_tx(ssh_state, 0); - if ( rs_ssh_tx_get_alstate_progress(tx, STREAM_TOSERVER) != SshStateBannerDone ) { + if (rs_ssh_tx_get_alstate_progress(tx, STREAM_TOSERVER) != SshStateBannerDone) { printf("Client version string not parsed: "); goto end; } @@ -280,8 +279,8 @@ static int SSHParserTest03(void) StreamTcpInitConfig(true); - int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SSH, - STREAM_TOSERVER | STREAM_EOF, sshbuf, sshlen); + int r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_SSH, STREAM_TOSERVER | STREAM_EOF, sshbuf, sshlen); if (r == 0) { printf("toclient chunk 1 returned %" PRId32 ", expected != 0: ", r); goto end; @@ -292,9 +291,9 @@ static int SSHParserTest03(void) printf("no ssh state: "); goto end; } - void * tx = rs_ssh_state_get_tx(ssh_state, 0); + void *tx = rs_ssh_state_get_tx(ssh_state, 0); - if ( rs_ssh_tx_get_alstate_progress(tx, STREAM_TOSERVER) == SshStateBannerDone ) { + if (rs_ssh_tx_get_alstate_progress(tx, STREAM_TOSERVER) == SshStateBannerDone) { printf("Client version string parsed? It's not a valid string: "); goto end; } @@ -332,8 +331,8 @@ static int SSHParserTest04(void) StreamTcpInitConfig(true); - int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SSH, - STREAM_TOCLIENT | STREAM_EOF, sshbuf, sshlen); + int r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_SSH, STREAM_TOCLIENT | STREAM_EOF, sshbuf, sshlen); if (r != 0) { printf("toserver chunk 1 returned %" PRId32 ", expected 0: ", r); goto end; @@ -344,9 +343,9 @@ static int SSHParserTest04(void) printf("no ssh state: "); goto end; } - void * tx = rs_ssh_state_get_tx(ssh_state, 0); + void *tx = rs_ssh_state_get_tx(ssh_state, 0); - if ( rs_ssh_tx_get_alstate_progress(tx, STREAM_TOCLIENT) != SshStateBannerDone ) { + if (rs_ssh_tx_get_alstate_progress(tx, STREAM_TOCLIENT) != SshStateBannerDone) { printf("Client version string not parsed: "); goto end; } @@ -382,8 +381,8 @@ static int SSHParserTest05(void) StreamTcpInitConfig(true); - int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SSH, - STREAM_TOCLIENT | STREAM_EOF, sshbuf, sshlen); + int r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_SSH, STREAM_TOCLIENT | STREAM_EOF, sshbuf, sshlen); if (r != 0) { printf("toserver chunk 1 returned %" PRId32 ", expected 0: ", r); goto end; @@ -394,9 +393,9 @@ static int SSHParserTest05(void) printf("no ssh state: "); goto end; } - void * tx = rs_ssh_state_get_tx(ssh_state, 0); + void *tx = rs_ssh_state_get_tx(ssh_state, 0); - if ( rs_ssh_tx_get_alstate_progress(tx, STREAM_TOCLIENT) != SshStateBannerDone ) { + if (rs_ssh_tx_get_alstate_progress(tx, STREAM_TOCLIENT) != SshStateBannerDone) { printf("Client version string not parsed: "); goto end; } @@ -431,8 +430,8 @@ static int SSHParserTest06(void) StreamTcpInitConfig(true); - int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SSH, - STREAM_TOCLIENT | STREAM_EOF, sshbuf, sshlen); + int r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_SSH, STREAM_TOCLIENT | STREAM_EOF, sshbuf, sshlen); if (r == 0) { printf("toserver chunk 1 returned %" PRId32 ", expected != 0: ", r); goto end; @@ -444,9 +443,9 @@ static int SSHParserTest06(void) printf("no ssh state: "); goto end; } - void * tx = rs_ssh_state_get_tx(ssh_state, 0); + void *tx = rs_ssh_state_get_tx(ssh_state, 0); - if ( rs_ssh_tx_get_alstate_progress(tx, STREAM_TOCLIENT) == SshStateBannerDone ) { + if (rs_ssh_tx_get_alstate_progress(tx, STREAM_TOCLIENT) == SshStateBannerDone) { printf("Client version string parsed? It's not a valid string: "); goto end; } @@ -457,7 +456,6 @@ static int SSHParserTest06(void) if (rs_ssh_tx_get_software(tx, &dummy, &dummy_len, STREAM_TOCLIENT) != 0) goto end; - result = 1; end: if (alp_tctx != NULL) @@ -477,7 +475,7 @@ static int SSHParserTest07(void) Flow *f = NULL; Packet *p = NULL; - char sshbufs[2][MAX_SSH_TEST_SIZE] = {"SSH-2.", "0-MySSHClient-0.5.1\r\n"}; + char sshbufs[2][MAX_SSH_TEST_SIZE] = { "SSH-2.", "0-MySSHClient-0.5.1\r\n" }; memset(&tv, 0x00, sizeof(tv)); @@ -499,16 +497,18 @@ static int SSHParserTest07(void) p->flow = f; uint32_t seq = 2; - for (int i=0; i<2; i++) { - FAIL_IF(StreamTcpUTAddSegmentWithPayload(&tv, ra_ctx, &ssn.client, seq, (uint8_t *) sshbufs[i], strlen(sshbufs[i])) == -1); + for (int i = 0; i < 2; i++) { + FAIL_IF(StreamTcpUTAddSegmentWithPayload(&tv, ra_ctx, &ssn.client, seq, + (uint8_t *)sshbufs[i], strlen(sshbufs[i])) == -1); seq += strlen(sshbufs[i]); - FAIL_IF(StreamTcpReassembleAppLayer(&tv, ra_ctx, &ssn, &ssn.client, p, UPDATE_DIR_PACKET) < 0); + FAIL_IF(StreamTcpReassembleAppLayer(&tv, ra_ctx, &ssn, &ssn.client, p, UPDATE_DIR_PACKET) < + 0); } void *ssh_state = f->alstate; FAIL_IF_NULL(ssh_state); - void * tx = rs_ssh_state_get_tx(ssh_state, 0); - FAIL_IF( rs_ssh_tx_get_alstate_progress(tx, STREAM_TOSERVER) != SshStateBannerDone ); + void *tx = rs_ssh_state_get_tx(ssh_state, 0); + FAIL_IF(rs_ssh_tx_get_alstate_progress(tx, STREAM_TOSERVER) != SshStateBannerDone); FAIL_IF(SSHParserTestUtilCheck("2.0", "MySSHClient-0.5.1", tx, STREAM_TOSERVER)); @@ -528,7 +528,7 @@ static int SSHParserTest08(void) Flow *f = NULL; Packet *p = NULL; - char sshbufs[3][MAX_SSH_TEST_SIZE] = {"SSH-", "2.", "0-MySSHClient-0.5.1\r\n"}; + char sshbufs[3][MAX_SSH_TEST_SIZE] = { "SSH-", "2.", "0-MySSHClient-0.5.1\r\n" }; memset(&tv, 0x00, sizeof(tv)); @@ -550,16 +550,18 @@ static int SSHParserTest08(void) p->flow = f; uint32_t seq = 2; - for (int i=0; i<3; i++) { - FAIL_IF(StreamTcpUTAddSegmentWithPayload(&tv, ra_ctx, &ssn.client, seq, (uint8_t *) sshbufs[i], strlen(sshbufs[i])) == -1); + for (int i = 0; i < 3; i++) { + FAIL_IF(StreamTcpUTAddSegmentWithPayload(&tv, ra_ctx, &ssn.client, seq, + (uint8_t *)sshbufs[i], strlen(sshbufs[i])) == -1); seq += strlen(sshbufs[i]); - FAIL_IF(StreamTcpReassembleAppLayer(&tv, ra_ctx, &ssn, &ssn.client, p, UPDATE_DIR_PACKET) < 0); + FAIL_IF(StreamTcpReassembleAppLayer(&tv, ra_ctx, &ssn, &ssn.client, p, UPDATE_DIR_PACKET) < + 0); } void *ssh_state = f->alstate; FAIL_IF_NULL(ssh_state); - void * tx = rs_ssh_state_get_tx(ssh_state, 0); - FAIL_IF( rs_ssh_tx_get_alstate_progress(tx, STREAM_TOSERVER) != SshStateBannerDone ); + void *tx = rs_ssh_state_get_tx(ssh_state, 0); + FAIL_IF(rs_ssh_tx_get_alstate_progress(tx, STREAM_TOSERVER) != SshStateBannerDone); FAIL_IF(SSHParserTestUtilCheck("2.0", "MySSHClient-0.5.1", tx, STREAM_TOSERVER)); @@ -578,7 +580,7 @@ static int SSHParserTest09(void) Flow *f = NULL; Packet *p = NULL; - char sshbufs[2][MAX_SSH_TEST_SIZE] = {"SSH-2.", "0-MySSHClient-0.5.1\r\n"}; + char sshbufs[2][MAX_SSH_TEST_SIZE] = { "SSH-2.", "0-MySSHClient-0.5.1\r\n" }; memset(&tv, 0x00, sizeof(tv)); @@ -600,16 +602,18 @@ static int SSHParserTest09(void) p->flow = f; uint32_t seq = 2; - for (int i=0; i<2; i++) { - FAIL_IF(StreamTcpUTAddSegmentWithPayload(&tv, ra_ctx, &ssn.server, seq, (uint8_t *) sshbufs[i], strlen(sshbufs[i])) == -1); + for (int i = 0; i < 2; i++) { + FAIL_IF(StreamTcpUTAddSegmentWithPayload(&tv, ra_ctx, &ssn.server, seq, + (uint8_t *)sshbufs[i], strlen(sshbufs[i])) == -1); seq += strlen(sshbufs[i]); - FAIL_IF(StreamTcpReassembleAppLayer(&tv, ra_ctx, &ssn, &ssn.server, p, UPDATE_DIR_PACKET) < 0); + FAIL_IF(StreamTcpReassembleAppLayer(&tv, ra_ctx, &ssn, &ssn.server, p, UPDATE_DIR_PACKET) < + 0); } void *ssh_state = f->alstate; FAIL_IF_NULL(ssh_state); - void * tx = rs_ssh_state_get_tx(ssh_state, 0); - FAIL_IF( rs_ssh_tx_get_alstate_progress(tx, STREAM_TOCLIENT) != SshStateBannerDone ); + void *tx = rs_ssh_state_get_tx(ssh_state, 0); + FAIL_IF(rs_ssh_tx_get_alstate_progress(tx, STREAM_TOCLIENT) != SshStateBannerDone); FAIL_IF(SSHParserTestUtilCheck("2.0", "MySSHClient-0.5.1", tx, STREAM_TOCLIENT)); @@ -629,7 +633,7 @@ static int SSHParserTest10(void) Flow *f = NULL; Packet *p = NULL; - char sshbufs[3][MAX_SSH_TEST_SIZE] = {"SSH-", "2.", "0-MySSHClient-0.5.1\r\n"}; + char sshbufs[3][MAX_SSH_TEST_SIZE] = { "SSH-", "2.", "0-MySSHClient-0.5.1\r\n" }; memset(&tv, 0x00, sizeof(tv)); @@ -651,16 +655,18 @@ static int SSHParserTest10(void) p->flow = f; uint32_t seq = 2; - for (int i=0; i<3; i++) { - FAIL_IF(StreamTcpUTAddSegmentWithPayload(&tv, ra_ctx, &ssn.server, seq, (uint8_t *) sshbufs[i], strlen(sshbufs[i])) == -1); + for (int i = 0; i < 3; i++) { + FAIL_IF(StreamTcpUTAddSegmentWithPayload(&tv, ra_ctx, &ssn.server, seq, + (uint8_t *)sshbufs[i], strlen(sshbufs[i])) == -1); seq += strlen(sshbufs[i]); - FAIL_IF(StreamTcpReassembleAppLayer(&tv, ra_ctx, &ssn, &ssn.server, p, UPDATE_DIR_PACKET) < 0); + FAIL_IF(StreamTcpReassembleAppLayer(&tv, ra_ctx, &ssn, &ssn.server, p, UPDATE_DIR_PACKET) < + 0); } void *ssh_state = f->alstate; FAIL_IF_NULL(ssh_state); - void * tx = rs_ssh_state_get_tx(ssh_state, 0); - FAIL_IF( rs_ssh_tx_get_alstate_progress(tx, STREAM_TOCLIENT) != SshStateBannerDone ); + void *tx = rs_ssh_state_get_tx(ssh_state, 0); + FAIL_IF(rs_ssh_tx_get_alstate_progress(tx, STREAM_TOCLIENT) != SshStateBannerDone); FAIL_IF(SSHParserTestUtilCheck("2.0", "MySSHClient-0.5.1", tx, STREAM_TOCLIENT)); @@ -693,14 +699,12 @@ static int SSHParserTest11(void) StreamTcpInitConfig(true); - int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SSH, - STREAM_TOSERVER, sshbuf1, sshlen1); + int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SSH, STREAM_TOSERVER, sshbuf1, sshlen1); if (r != 0) { printf("toserver chunk 1 returned %" PRId32 ", expected 0: ", r); goto end; } - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SSH, STREAM_TOSERVER, - sshbuf2, sshlen2); + r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SSH, STREAM_TOSERVER, sshbuf2, sshlen2); if (r != 0) { printf("toserver chunk 2 returned %" PRId32 ", expected 0: ", r); goto end; @@ -711,8 +715,8 @@ static int SSHParserTest11(void) printf("no ssh state: "); goto end; } - void * tx = rs_ssh_state_get_tx(ssh_state, 0); - if ( rs_ssh_tx_get_flags(tx, STREAM_TOSERVER) != SshStateFinished ) { + void *tx = rs_ssh_state_get_tx(ssh_state, 0); + if (rs_ssh_tx_get_flags(tx, STREAM_TOSERVER) != SshStateFinished) { printf("Didn't detect the msg code of new keys (ciphered data starts): "); goto end; } @@ -754,20 +758,17 @@ static int SSHParserTest12(void) StreamTcpInitConfig(true); - int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SSH, - STREAM_TOSERVER, sshbuf1, sshlen1); + int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SSH, STREAM_TOSERVER, sshbuf1, sshlen1); if (r != 0) { printf("toserver chunk 1 returned %" PRId32 ", expected 0: ", r); goto end; } - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SSH, STREAM_TOSERVER, - sshbuf2, sshlen2); + r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SSH, STREAM_TOSERVER, sshbuf2, sshlen2); if (r != 0) { printf("toserver chunk 2 returned %" PRId32 ", expected 0: ", r); goto end; } - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SSH, STREAM_TOSERVER, - sshbuf3, sshlen3); + r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SSH, STREAM_TOSERVER, sshbuf3, sshlen3); if (r != 0) { printf("toserver chunk 3 returned %" PRId32 ", expected 0: ", r); goto end; @@ -778,8 +779,8 @@ static int SSHParserTest12(void) printf("no ssh state: "); goto end; } - void * tx = rs_ssh_state_get_tx(ssh_state, 0); - if ( rs_ssh_tx_get_flags(tx, STREAM_TOSERVER) != SshStateFinished ) { + void *tx = rs_ssh_state_get_tx(ssh_state, 0); + if (rs_ssh_tx_get_flags(tx, STREAM_TOSERVER) != SshStateFinished) { printf("Didn't detect the msg code of new keys (ciphered data starts): "); goto end; } @@ -812,8 +813,8 @@ static int SSHParserTest13(void) uint8_t sshbuf3[] = { 0x00, 0x00, 0x00, 0x02, 0x01, 21}; // clang-format on - uint8_t* sshbufs[3] = {sshbuf1, sshbuf2, sshbuf3}; - uint32_t sshlens[3] = {sizeof(sshbuf1) - 1, sizeof(sshbuf2), sizeof(sshbuf3)}; + uint8_t *sshbufs[3] = { sshbuf1, sshbuf2, sshbuf3 }; + uint32_t sshlens[3] = { sizeof(sshbuf1) - 1, sizeof(sshbuf2), sizeof(sshbuf3) }; memset(&tv, 0x00, sizeof(tv)); @@ -835,16 +836,18 @@ static int SSHParserTest13(void) p->flow = f; uint32_t seq = 2; - for (int i=0; i<3; i++) { - FAIL_IF(StreamTcpUTAddSegmentWithPayload(&tv, ra_ctx, &ssn.client, seq, sshbufs[i], sshlens[i]) == -1); + for (int i = 0; i < 3; i++) { + FAIL_IF(StreamTcpUTAddSegmentWithPayload( + &tv, ra_ctx, &ssn.client, seq, sshbufs[i], sshlens[i]) == -1); seq += sshlens[i]; - FAIL_IF(StreamTcpReassembleAppLayer(&tv, ra_ctx, &ssn, &ssn.client, p, UPDATE_DIR_PACKET) < 0); + FAIL_IF(StreamTcpReassembleAppLayer(&tv, ra_ctx, &ssn, &ssn.client, p, UPDATE_DIR_PACKET) < + 0); } void *ssh_state = f->alstate; FAIL_IF_NULL(ssh_state); - void * tx = rs_ssh_state_get_tx(ssh_state, 0); - FAIL_IF( rs_ssh_tx_get_flags(tx, STREAM_TOSERVER) != SshStateFinished ); + void *tx = rs_ssh_state_get_tx(ssh_state, 0); + FAIL_IF(rs_ssh_tx_get_flags(tx, STREAM_TOSERVER) != SshStateFinished); FAIL_IF(SSHParserTestUtilCheck("2.0", "MySSHClient-0.5.1", tx, STREAM_TOSERVER)); @@ -879,8 +882,9 @@ static int SSHParserTest14(void) uint8_t sshbuf5[] = { 0x00, 0x00, 0x02, 0x01, 21}; // clang-format on - uint8_t* sshbufs[5] = {sshbuf1, sshbuf2, sshbuf3, sshbuf4, sshbuf5}; - uint32_t sshlens[5] = {sizeof(sshbuf1) - 1, sizeof(sshbuf2), sizeof(sshbuf3), sizeof(sshbuf4), sizeof(sshbuf5)}; + uint8_t *sshbufs[5] = { sshbuf1, sshbuf2, sshbuf3, sshbuf4, sshbuf5 }; + uint32_t sshlens[5] = { sizeof(sshbuf1) - 1, sizeof(sshbuf2), sizeof(sshbuf3), sizeof(sshbuf4), + sizeof(sshbuf5) }; memset(&tv, 0x00, sizeof(tv)); @@ -902,16 +906,18 @@ static int SSHParserTest14(void) p->flow = f; uint32_t seq = 2; - for (int i=0; i<5; i++) { - FAIL_IF(StreamTcpUTAddSegmentWithPayload(&tv, ra_ctx, &ssn.client, seq, sshbufs[i], sshlens[i]) == -1); + for (int i = 0; i < 5; i++) { + FAIL_IF(StreamTcpUTAddSegmentWithPayload( + &tv, ra_ctx, &ssn.client, seq, sshbufs[i], sshlens[i]) == -1); seq += sshlens[i]; - FAIL_IF(StreamTcpReassembleAppLayer(&tv, ra_ctx, &ssn, &ssn.client, p, UPDATE_DIR_PACKET) < 0); + FAIL_IF(StreamTcpReassembleAppLayer(&tv, ra_ctx, &ssn, &ssn.client, p, UPDATE_DIR_PACKET) < + 0); } void *ssh_state = f->alstate; FAIL_IF_NULL(ssh_state); - void * tx = rs_ssh_state_get_tx(ssh_state, 0); - FAIL_IF( rs_ssh_tx_get_flags(tx, STREAM_TOSERVER) != SshStateFinished ); + void *tx = rs_ssh_state_get_tx(ssh_state, 0); + FAIL_IF(rs_ssh_tx_get_flags(tx, STREAM_TOSERVER) != SshStateFinished); FAIL_IF(SSHParserTestUtilCheck("2.0", "MySSHClient-0.5.1", tx, STREAM_TOSERVER)); @@ -945,8 +951,9 @@ static int SSHParserTest15(void) uint8_t sshbuf5[] = { 0x00, 0x00, 0x02, 0x01, 20, 0x00, 0x00, 0x00, 0x02, 0x01, 21}; // clang-format on - uint8_t* sshbufs[5] = {sshbuf1, sshbuf2, sshbuf3, sshbuf4, sshbuf5}; - uint32_t sshlens[5] = {sizeof(sshbuf1) - 1, sizeof(sshbuf2), sizeof(sshbuf3), sizeof(sshbuf4), sizeof(sshbuf5)}; + uint8_t *sshbufs[5] = { sshbuf1, sshbuf2, sshbuf3, sshbuf4, sshbuf5 }; + uint32_t sshlens[5] = { sizeof(sshbuf1) - 1, sizeof(sshbuf2), sizeof(sshbuf3), sizeof(sshbuf4), + sizeof(sshbuf5) }; memset(&tv, 0x00, sizeof(tv)); @@ -968,16 +975,18 @@ static int SSHParserTest15(void) p->flow = f; uint32_t seq = 2; - for (int i=0; i<5; i++) { - FAIL_IF(StreamTcpUTAddSegmentWithPayload(&tv, ra_ctx, &ssn.client, seq, sshbufs[i], sshlens[i]) == -1); + for (int i = 0; i < 5; i++) { + FAIL_IF(StreamTcpUTAddSegmentWithPayload( + &tv, ra_ctx, &ssn.client, seq, sshbufs[i], sshlens[i]) == -1); seq += sshlens[i]; - FAIL_IF(StreamTcpReassembleAppLayer(&tv, ra_ctx, &ssn, &ssn.client, p, UPDATE_DIR_PACKET) < 0); + FAIL_IF(StreamTcpReassembleAppLayer(&tv, ra_ctx, &ssn, &ssn.client, p, UPDATE_DIR_PACKET) < + 0); } void *ssh_state = f->alstate; FAIL_IF_NULL(ssh_state); - void * tx = rs_ssh_state_get_tx(ssh_state, 0); - FAIL_IF( rs_ssh_tx_get_flags(tx, STREAM_TOSERVER) != SshStateFinished ); + void *tx = rs_ssh_state_get_tx(ssh_state, 0); + FAIL_IF(rs_ssh_tx_get_flags(tx, STREAM_TOSERVER) != SshStateFinished); FAIL_IF(SSHParserTestUtilCheck("2.0", "MySSHClient-0.5.1", tx, STREAM_TOSERVER)); @@ -1003,8 +1012,8 @@ static int SSHParserTest16(void) uint8_t sshbuf3[] = { 0x00, 0x00, 0x00, 0x03,0x01, 21, 0x00}; // clang-format on - uint8_t* sshbufs[3] = {sshbuf1, sshbuf2, sshbuf3}; - uint32_t sshlens[3] = {sizeof(sshbuf1) - 1, sizeof(sshbuf2) - 1, sizeof(sshbuf3)}; + uint8_t *sshbufs[3] = { sshbuf1, sshbuf2, sshbuf3 }; + uint32_t sshlens[3] = { sizeof(sshbuf1) - 1, sizeof(sshbuf2) - 1, sizeof(sshbuf3) }; memset(&tv, 0x00, sizeof(tv)); @@ -1026,16 +1035,18 @@ static int SSHParserTest16(void) p->flow = f; uint32_t seq = 2; - for (int i=0; i<3; i++) { - FAIL_IF(StreamTcpUTAddSegmentWithPayload(&tv, ra_ctx, &ssn.server, seq, sshbufs[i], sshlens[i]) == -1); + for (int i = 0; i < 3; i++) { + FAIL_IF(StreamTcpUTAddSegmentWithPayload( + &tv, ra_ctx, &ssn.server, seq, sshbufs[i], sshlens[i]) == -1); seq += sshlens[i]; - FAIL_IF(StreamTcpReassembleAppLayer(&tv, ra_ctx, &ssn, &ssn.server, p, UPDATE_DIR_PACKET) < 0); + FAIL_IF(StreamTcpReassembleAppLayer(&tv, ra_ctx, &ssn, &ssn.server, p, UPDATE_DIR_PACKET) < + 0); } void *ssh_state = f->alstate; FAIL_IF_NULL(ssh_state); - void * tx = rs_ssh_state_get_tx(ssh_state, 0); - FAIL_IF( rs_ssh_tx_get_flags(tx, STREAM_TOCLIENT) != SshStateFinished ); + void *tx = rs_ssh_state_get_tx(ssh_state, 0); + FAIL_IF(rs_ssh_tx_get_flags(tx, STREAM_TOCLIENT) != SshStateFinished); FAIL_IF(SSHParserTestUtilCheck("2.0", "MySSHClient-0.5.1", tx, STREAM_TOCLIENT)); @@ -1064,8 +1075,9 @@ static int SSHParserTest17(void) uint8_t sshbuf4[] = { 0x00, 0x00, 0x00, 0x03, 0x01, 21, 0x00}; // clang-format on - uint8_t* sshbufs[4] = {sshbuf1, sshbuf2, sshbuf3, sshbuf4}; - uint32_t sshlens[4] = {sizeof(sshbuf1) - 1, sizeof(sshbuf2) - 1, sizeof(sshbuf3), sizeof(sshbuf4)}; + uint8_t *sshbufs[4] = { sshbuf1, sshbuf2, sshbuf3, sshbuf4 }; + uint32_t sshlens[4] = { sizeof(sshbuf1) - 1, sizeof(sshbuf2) - 1, sizeof(sshbuf3), + sizeof(sshbuf4) }; memset(&tv, 0x00, sizeof(tv)); @@ -1087,16 +1099,18 @@ static int SSHParserTest17(void) p->flow = f; uint32_t seq = 2; - for (int i=0; i<4; i++) { - FAIL_IF(StreamTcpUTAddSegmentWithPayload(&tv, ra_ctx, &ssn.server, seq, sshbufs[i], sshlens[i]) == -1); + for (int i = 0; i < 4; i++) { + FAIL_IF(StreamTcpUTAddSegmentWithPayload( + &tv, ra_ctx, &ssn.server, seq, sshbufs[i], sshlens[i]) == -1); seq += sshlens[i]; - FAIL_IF(StreamTcpReassembleAppLayer(&tv, ra_ctx, &ssn, &ssn.server, p, UPDATE_DIR_PACKET) < 0); + FAIL_IF(StreamTcpReassembleAppLayer(&tv, ra_ctx, &ssn, &ssn.server, p, UPDATE_DIR_PACKET) < + 0); } void *ssh_state = f->alstate; FAIL_IF_NULL(ssh_state); - void * tx = rs_ssh_state_get_tx(ssh_state, 0); - FAIL_IF( rs_ssh_tx_get_flags(tx, STREAM_TOCLIENT) != SshStateFinished ); + void *tx = rs_ssh_state_get_tx(ssh_state, 0); + FAIL_IF(rs_ssh_tx_get_flags(tx, STREAM_TOCLIENT) != SshStateFinished); FAIL_IF(SSHParserTestUtilCheck("2.0", "MySSHClient-0.5.1", tx, STREAM_TOCLIENT)); @@ -1126,7 +1140,6 @@ static int SSHParserTest18(void) uint8_t sshbuf3[] = { 0x00, 0x00, 0x00, 0x03, 0x01, 21, 0x00 }; // clang-format on - memset(&tv, 0x00, sizeof(tv)); StreamTcpUTInit(&ra_ctx); @@ -1135,9 +1148,10 @@ static int SSHParserTest18(void) StreamTcpUTSetupStream(&ssn.server, 1); StreamTcpUTSetupStream(&ssn.client, 1); - uint8_t* sshbufs[5] = {server1, sshbuf1, sshbuf2, server2, sshbuf3}; - uint32_t sshlens[5] = {sizeof(server1) - 1, sizeof(sshbuf1) - 1, sizeof(sshbuf2) -1, sizeof(server2) - 1, sizeof(sshbuf3)}; - bool sshdirs[5] = {true, false, false, true, false}; + uint8_t *sshbufs[5] = { server1, sshbuf1, sshbuf2, server2, sshbuf3 }; + uint32_t sshlens[5] = { sizeof(server1) - 1, sizeof(sshbuf1) - 1, sizeof(sshbuf2) - 1, + sizeof(server2) - 1, sizeof(sshbuf3) }; + bool sshdirs[5] = { true, false, false, true, false }; f = UTHBuildFlow(AF_INET, "1.1.1.1", "2.2.2.2", 1234, 2222); FAIL_IF_NULL(f); @@ -1152,22 +1166,26 @@ static int SSHParserTest18(void) uint32_t seqcli = 2; uint32_t seqsrv = 2; - for (int i=0; i<5; i++) { + for (int i = 0; i < 5; i++) { if (sshdirs[i]) { - FAIL_IF(StreamTcpUTAddSegmentWithPayload(&tv, ra_ctx, &ssn.server, seqsrv, sshbufs[i], sshlens[i]) == -1); + FAIL_IF(StreamTcpUTAddSegmentWithPayload( + &tv, ra_ctx, &ssn.server, seqsrv, sshbufs[i], sshlens[i]) == -1); seqsrv += sshlens[i]; - FAIL_IF(StreamTcpReassembleAppLayer(&tv, ra_ctx, &ssn, &ssn.server, p, UPDATE_DIR_PACKET) < 0); + FAIL_IF(StreamTcpReassembleAppLayer( + &tv, ra_ctx, &ssn, &ssn.server, p, UPDATE_DIR_PACKET) < 0); } else { - FAIL_IF(StreamTcpUTAddSegmentWithPayload(&tv, ra_ctx, &ssn.client, seqcli, sshbufs[i], sshlens[i]) == -1); + FAIL_IF(StreamTcpUTAddSegmentWithPayload( + &tv, ra_ctx, &ssn.client, seqcli, sshbufs[i], sshlens[i]) == -1); seqcli += sshlens[i]; - FAIL_IF(StreamTcpReassembleAppLayer(&tv, ra_ctx, &ssn, &ssn.client, p, UPDATE_DIR_PACKET) < 0); + FAIL_IF(StreamTcpReassembleAppLayer( + &tv, ra_ctx, &ssn, &ssn.client, p, UPDATE_DIR_PACKET) < 0); } } void *ssh_state = f->alstate; FAIL_IF_NULL(ssh_state); - void * tx = rs_ssh_state_get_tx(ssh_state, 0); - FAIL_IF( rs_ssh_tx_get_flags(tx, STREAM_TOCLIENT) != SshStateFinished ); + void *tx = rs_ssh_state_get_tx(ssh_state, 0); + FAIL_IF(rs_ssh_tx_get_flags(tx, STREAM_TOCLIENT) != SshStateFinished); FAIL_IF(!(AppLayerParserStateIssetFlag(f->alparser, APP_LAYER_PARSER_NO_INSPECTION))); @@ -1190,21 +1208,22 @@ static int SSHParserTest19(void) uint8_t sshbuf1[] = "SSH-"; uint8_t sshbuf2[] = "2.0-"; uint8_t sshbuf3[] = "abcdefghijklmnopqrstuvwxyz" - "abcdefghijklmnopqrstuvwxyz"//60 + "abcdefghijklmnopqrstuvwxyz" // 60 "abcdefghijklmnopqrstuvwxyz" - "abcdefghijklmnopqrstuvwxyz"//112 + "abcdefghijklmnopqrstuvwxyz" // 112 "abcdefghijklmnopqrstuvwxyz" - "abcdefghijklmnopqrstuvwxyz"//164 + "abcdefghijklmnopqrstuvwxyz" // 164 "abcdefghijklmnopqrstuvwxyz" - "abcdefghijklmnopqrstuvwxyz"//216 - "abcdefghijklmnopqrstuvwxyz"//242 - "abcdefghijkl\r";//255 + "abcdefghijklmnopqrstuvwxyz" // 216 + "abcdefghijklmnopqrstuvwxyz" // 242 + "abcdefghijkl\r"; // 255 // clang-format off uint8_t sshbuf4[] = { 0x00, 0x00, 0x00, 0x03, 0x01, 21, 0x00}; // clang-format on - uint8_t* sshbufs[4] = {sshbuf1, sshbuf2, sshbuf3, sshbuf4}; - uint32_t sshlens[4] = {sizeof(sshbuf1) - 1, sizeof(sshbuf2) - 1, sizeof(sshbuf3) - 1, sizeof(sshbuf4)}; + uint8_t *sshbufs[4] = { sshbuf1, sshbuf2, sshbuf3, sshbuf4 }; + uint32_t sshlens[4] = { sizeof(sshbuf1) - 1, sizeof(sshbuf2) - 1, sizeof(sshbuf3) - 1, + sizeof(sshbuf4) }; memset(&tv, 0x00, sizeof(tv)); @@ -1226,16 +1245,18 @@ static int SSHParserTest19(void) p->flow = f; uint32_t seq = 2; - for (int i=0; i<4; i++) { - FAIL_IF(StreamTcpUTAddSegmentWithPayload(&tv, ra_ctx, &ssn.server, seq, sshbufs[i], sshlens[i]) == -1); + for (int i = 0; i < 4; i++) { + FAIL_IF(StreamTcpUTAddSegmentWithPayload( + &tv, ra_ctx, &ssn.server, seq, sshbufs[i], sshlens[i]) == -1); seq += sshlens[i]; - FAIL_IF(StreamTcpReassembleAppLayer(&tv, ra_ctx, &ssn, &ssn.server, p, UPDATE_DIR_PACKET) < 0); + FAIL_IF(StreamTcpReassembleAppLayer(&tv, ra_ctx, &ssn, &ssn.server, p, UPDATE_DIR_PACKET) < + 0); } void *ssh_state = f->alstate; FAIL_IF_NULL(ssh_state); - void * tx = rs_ssh_state_get_tx(ssh_state, 0); - FAIL_IF( rs_ssh_tx_get_flags(tx, STREAM_TOCLIENT) != SshStateFinished ); + void *tx = rs_ssh_state_get_tx(ssh_state, 0); + FAIL_IF(rs_ssh_tx_get_flags(tx, STREAM_TOCLIENT) != SshStateFinished); sshbuf3[sizeof(sshbuf3) - 2] = 0; FAIL_IF(SSHParserTestUtilCheck("2.0", (char *)sshbuf3, tx, STREAM_TOCLIENT)); @@ -1260,22 +1281,23 @@ static int SSHParserTest20(void) uint8_t sshbuf1[] = "SSH-"; uint8_t sshbuf2[] = "2.0-"; uint8_t sshbuf3[] = "abcdefghijklmnopqrstuvwxyz" - "abcdefghijklmnopqrstuvwxyz"//60 + "abcdefghijklmnopqrstuvwxyz" // 60 "abcdefghijklmnopqrstuvwxyz" - "abcdefghijklmnopqrstuvwxyz"//112 + "abcdefghijklmnopqrstuvwxyz" // 112 "abcdefghijklmnopqrstuvwxyz" - "abcdefghijklmnopqrstuvwxyz"//164 + "abcdefghijklmnopqrstuvwxyz" // 164 "abcdefghijklmnopqrstuvwxyz" - "abcdefghijklmnopqrstuvwxyz"//216 - "abcdefghijklmnopqrstuvwxyz"//242 - "abcdefghijklm\r";//256 + "abcdefghijklmnopqrstuvwxyz" // 216 + "abcdefghijklmnopqrstuvwxyz" // 242 + "abcdefghijklm\r"; // 256 // clang-format off uint8_t sshbuf4[] = {'a','b','c','d','e','f', '\r', 0x00, 0x00, 0x00, 0x06, 0x01, 21, 0x00, 0x00, 0x00}; // clang-format on - uint8_t* sshbufs[4] = {sshbuf1, sshbuf2, sshbuf3, sshbuf4}; - uint32_t sshlens[4] = {sizeof(sshbuf1) - 1, sizeof(sshbuf2) - 1, sizeof(sshbuf3) - 1, sizeof(sshbuf4) - 1}; + uint8_t *sshbufs[4] = { sshbuf1, sshbuf2, sshbuf3, sshbuf4 }; + uint32_t sshlens[4] = { sizeof(sshbuf1) - 1, sizeof(sshbuf2) - 1, sizeof(sshbuf3) - 1, + sizeof(sshbuf4) - 1 }; memset(&tv, 0x00, sizeof(tv)); @@ -1297,16 +1319,18 @@ static int SSHParserTest20(void) p->flow = f; uint32_t seq = 2; - for (int i=0; i<4; i++) { - FAIL_IF(StreamTcpUTAddSegmentWithPayload(&tv, ra_ctx, &ssn.server, seq, sshbufs[i], sshlens[i]) == -1); + for (int i = 0; i < 4; i++) { + FAIL_IF(StreamTcpUTAddSegmentWithPayload( + &tv, ra_ctx, &ssn.server, seq, sshbufs[i], sshlens[i]) == -1); seq += sshlens[i]; - FAIL_IF(StreamTcpReassembleAppLayer(&tv, ra_ctx, &ssn, &ssn.server, p, UPDATE_DIR_PACKET) < 0); + FAIL_IF(StreamTcpReassembleAppLayer(&tv, ra_ctx, &ssn, &ssn.server, p, UPDATE_DIR_PACKET) < + 0); } void *ssh_state = f->alstate; FAIL_IF_NULL(ssh_state); - void * tx = rs_ssh_state_get_tx(ssh_state, 0); - FAIL_IF( rs_ssh_tx_get_flags(tx, STREAM_TOCLIENT) != SshStateFinished ); + void *tx = rs_ssh_state_get_tx(ssh_state, 0); + FAIL_IF(rs_ssh_tx_get_flags(tx, STREAM_TOCLIENT) != SshStateFinished); FAIL_IF(SSHParserTestUtilCheck("2.0", NULL, tx, STREAM_TOCLIENT)); @@ -1330,21 +1354,22 @@ static int SSHParserTest21(void) uint8_t sshbuf1[] = "SSH-"; uint8_t sshbuf2[] = "2.0-"; uint8_t sshbuf3[] = "abcdefghijklmnopqrstuvwxyz" - "abcdefghijklmnopqrstuvwxyz"//60 + "abcdefghijklmnopqrstuvwxyz" // 60 "abcdefghijklmnopqrstuvwxyz" - "abcdefghijklmnopqrstuvwxyz"//112 + "abcdefghijklmnopqrstuvwxyz" // 112 "abcdefghijklmnopqrstuvwxyz" - "abcdefghijklmnopqrstuvwxyz"//164 + "abcdefghijklmnopqrstuvwxyz" // 164 "abcdefghijklmnopqrstuvwxyz" - "abcdefghijklmnopqrstuvwxyz"//216 - "abcdefghijklmnopqrstuvwxy";//241 + "abcdefghijklmnopqrstuvwxyz" // 216 + "abcdefghijklmnopqrstuvwxy"; // 241 // clang-format off uint8_t sshbuf4[] = {'l','i','b','s','s','h', '\r', 0x00, 0x00, 0x00, 0x06, 0x01, 21, 0x00, 0x00, 0x00}; // clang-format on - uint8_t* sshbufs[4] = {sshbuf1, sshbuf2, sshbuf3, sshbuf4}; - uint32_t sshlens[4] = {sizeof(sshbuf1) - 1, sizeof(sshbuf2) - 1, sizeof(sshbuf3) - 1, sizeof(sshbuf4)}; + uint8_t *sshbufs[4] = { sshbuf1, sshbuf2, sshbuf3, sshbuf4 }; + uint32_t sshlens[4] = { sizeof(sshbuf1) - 1, sizeof(sshbuf2) - 1, sizeof(sshbuf3) - 1, + sizeof(sshbuf4) }; memset(&tv, 0x00, sizeof(tv)); @@ -1366,16 +1391,18 @@ static int SSHParserTest21(void) p->flow = f; uint32_t seq = 2; - for (int i=0; i<4; i++) { - FAIL_IF(StreamTcpUTAddSegmentWithPayload(&tv, ra_ctx, &ssn.server, seq, sshbufs[i], sshlens[i]) == -1); + for (int i = 0; i < 4; i++) { + FAIL_IF(StreamTcpUTAddSegmentWithPayload( + &tv, ra_ctx, &ssn.server, seq, sshbufs[i], sshlens[i]) == -1); seq += sshlens[i]; - FAIL_IF(StreamTcpReassembleAppLayer(&tv, ra_ctx, &ssn, &ssn.server, p, UPDATE_DIR_PACKET) < 0); + FAIL_IF(StreamTcpReassembleAppLayer(&tv, ra_ctx, &ssn, &ssn.server, p, UPDATE_DIR_PACKET) < + 0); } void *ssh_state = f->alstate; FAIL_IF_NULL(ssh_state); - void * tx = rs_ssh_state_get_tx(ssh_state, 0); - FAIL_IF( rs_ssh_tx_get_flags(tx, STREAM_TOCLIENT) != SshStateFinished ); + void *tx = rs_ssh_state_get_tx(ssh_state, 0); + FAIL_IF(rs_ssh_tx_get_flags(tx, STREAM_TOCLIENT) != SshStateFinished); FAIL_IF(SSHParserTestUtilCheck("2.0", NULL, tx, STREAM_TOCLIENT)); @@ -1440,48 +1467,49 @@ static int SSHParserTest22(void) }; // clang-format on + uint8_t *sshbufs[3] = { sshbuf1, sshbuf2, sshbuf3 }; + uint32_t sshlens[3] = { sizeof(sshbuf1) - 1, sizeof(sshbuf2) - 1, sizeof(sshbuf3) - 1 }; - uint8_t* sshbufs[3] = {sshbuf1, sshbuf2, sshbuf3}; - uint32_t sshlens[3] = {sizeof(sshbuf1) - 1, sizeof(sshbuf2) - 1, sizeof(sshbuf3) - 1}; - - memset(&tv, 0x00, sizeof(tv)); + memset(&tv, 0x00, sizeof(tv)); - StreamTcpUTInit(&ra_ctx); - StreamTcpUTInitInline(); - StreamTcpUTSetupSession(&ssn); - StreamTcpUTSetupStream(&ssn.server, 1); - StreamTcpUTSetupStream(&ssn.client, 1); + StreamTcpUTInit(&ra_ctx); + StreamTcpUTInitInline(); + StreamTcpUTSetupSession(&ssn); + StreamTcpUTSetupStream(&ssn.server, 1); + StreamTcpUTSetupStream(&ssn.client, 1); - f = UTHBuildFlow(AF_INET, "1.1.1.1", "2.2.2.2", 1234, 2222); - FAIL_IF_NULL(f); - f->protoctx = &ssn; - f->proto = IPPROTO_TCP; - f->alproto = ALPROTO_SSH; + f = UTHBuildFlow(AF_INET, "1.1.1.1", "2.2.2.2", 1234, 2222); + FAIL_IF_NULL(f); + f->protoctx = &ssn; + f->proto = IPPROTO_TCP; + f->alproto = ALPROTO_SSH; - p = PacketGetFromAlloc(); - FAIL_IF(unlikely(p == NULL)); - p->proto = IPPROTO_TCP; - p->flow = f; + p = PacketGetFromAlloc(); + FAIL_IF(unlikely(p == NULL)); + p->proto = IPPROTO_TCP; + p->flow = f; - uint32_t seq = 2; - for (int i=0; i<3; i++) { - FAIL_IF(StreamTcpUTAddSegmentWithPayload(&tv, ra_ctx, &ssn.server, seq, sshbufs[i], sshlens[i]) == -1); - seq += sshlens[i]; - FAIL_IF(StreamTcpReassembleAppLayer(&tv, ra_ctx, &ssn, &ssn.server, p, UPDATE_DIR_PACKET) < 0); - } + uint32_t seq = 2; + for (int i = 0; i < 3; i++) { + FAIL_IF(StreamTcpUTAddSegmentWithPayload( + &tv, ra_ctx, &ssn.server, seq, sshbufs[i], sshlens[i]) == -1); + seq += sshlens[i]; + FAIL_IF(StreamTcpReassembleAppLayer(&tv, ra_ctx, &ssn, &ssn.server, p, UPDATE_DIR_PACKET) < + 0); + } - void *ssh_state = f->alstate; - FAIL_IF_NULL(ssh_state); - void * tx = rs_ssh_state_get_tx(ssh_state, 0); - FAIL_IF( rs_ssh_tx_get_flags(tx, STREAM_TOCLIENT) != SshStateFinished ); + void *ssh_state = f->alstate; + FAIL_IF_NULL(ssh_state); + void *tx = rs_ssh_state_get_tx(ssh_state, 0); + FAIL_IF(rs_ssh_tx_get_flags(tx, STREAM_TOCLIENT) != SshStateFinished); - FAIL_IF(SSHParserTestUtilCheck("2.0", "libssh", tx, STREAM_TOCLIENT)); + FAIL_IF(SSHParserTestUtilCheck("2.0", "libssh", tx, STREAM_TOCLIENT)); - UTHFreePacket(p); - StreamTcpUTClearSession(&ssn); - StreamTcpUTDeinit(ra_ctx); - UTHFreeFlow(f); - PASS; + UTHFreePacket(p); + StreamTcpUTClearSession(&ssn); + StreamTcpUTDeinit(ra_ctx); + UTHFreeFlow(f); + PASS; } /** \test Send a version string in one chunk (client version str). */ @@ -1502,8 +1530,8 @@ static int SSHParserTest23(void) StreamTcpInitConfig(true); - int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SSH, - STREAM_TOSERVER | STREAM_EOF, sshbuf, sshlen); + int r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_SSH, STREAM_TOSERVER | STREAM_EOF, sshbuf, sshlen); if (r == 0) { printf("toclient chunk 1 returned 0 expected non null: "); goto end; @@ -1536,8 +1564,8 @@ static int SSHParserTest24(void) StreamTcpInitConfig(true); - int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SSH, - STREAM_TOSERVER | STREAM_EOF, sshbuf, sshlen); + int r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_SSH, STREAM_TOSERVER | STREAM_EOF, sshbuf, sshlen); if (r != 0) { printf("toclient chunk 1 returned %" PRId32 ", expected 0: ", r); goto end; @@ -1548,8 +1576,8 @@ static int SSHParserTest24(void) printf("no ssh state: "); goto end; } - void * tx = rs_ssh_state_get_tx(ssh_state, 0); - if ( rs_ssh_tx_get_flags(tx, STREAM_TOSERVER) != SshStateBannerDone ) { + void *tx = rs_ssh_state_get_tx(ssh_state, 0); + if (rs_ssh_tx_get_flags(tx, STREAM_TOSERVER) != SshStateBannerDone) { printf("Didn't detect the msg code of new keys (ciphered data starts): "); goto end; } @@ -1583,17 +1611,17 @@ static int SSHParserTest25(void) StreamTcpInitConfig(true); - int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SSH, - STREAM_TOSERVER | STREAM_EOF, sshbuf, sshlen); + int r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_SSH, STREAM_TOSERVER | STREAM_EOF, sshbuf, sshlen); FAIL_IF(r != -1); void *ssh_state = f.alstate; FAIL_IF_NULL(ssh_state); - void * tx = rs_ssh_state_get_tx(ssh_state, 0); - FAIL_IF( rs_ssh_tx_get_flags(tx, STREAM_TOSERVER) == SshStateBannerDone ); + void *tx = rs_ssh_state_get_tx(ssh_state, 0); + FAIL_IF(rs_ssh_tx_get_flags(tx, STREAM_TOSERVER) == SshStateBannerDone); const uint8_t *dummy = NULL; uint32_t dummy_len = 0; - FAIL_IF (rs_ssh_tx_get_software(tx, &dummy, &dummy_len, STREAM_TOCLIENT) != 0); + FAIL_IF(rs_ssh_tx_get_software(tx, &dummy, &dummy_len, STREAM_TOCLIENT) != 0); AppLayerParserThreadCtxFree(alp_tctx); StreamTcpFreeConfig(true); @@ -1633,4 +1661,3 @@ void SSHParserRegisterTests(void) UtRegisterTest("SSHParserTest25", SSHParserTest25); #endif /* UNITTESTS */ } - diff --git a/src/app-layer-ssh.h b/src/app-layer-ssh.h index 996cc260c735..66aee3b5f90e 100644 --- a/src/app-layer-ssh.h +++ b/src/app-layer-ssh.h @@ -31,4 +31,3 @@ void SSHParserRegisterTests(void); bool SSHTxLogCondition(ThreadVars *, const Packet *, void *state, void *tx, uint64_t tx_id); #endif /* __APP_LAYER_SSH_H__ */ - diff --git a/src/app-layer-ssl.c b/src/app-layer-ssl.c index cb094f3801ab..76d621deca52 100644 --- a/src/app-layer-ssl.c +++ b/src/app-layer-ssl.c @@ -127,7 +127,7 @@ SCEnumCharMap tls_decoder_event_table[] = { enum { /* X.509 error codes, returned by decoder * THESE CONSTANTS MUST MATCH rust/src/x509/mod.rs ! */ - ERR_INVALID_CERTIFICATE=1, + ERR_INVALID_CERTIFICATE = 1, ERR_INVALID_LENGTH, ERR_INVALID_VERSION, ERR_INVALID_SERIAL, @@ -163,53 +163,53 @@ typedef struct SslConfig_ { SslConfig ssl_config; /* SSLv3 record types */ -#define SSLV3_CHANGE_CIPHER_SPEC 20 -#define SSLV3_ALERT_PROTOCOL 21 -#define SSLV3_HANDSHAKE_PROTOCOL 22 -#define SSLV3_APPLICATION_PROTOCOL 23 -#define SSLV3_HEARTBEAT_PROTOCOL 24 +#define SSLV3_CHANGE_CIPHER_SPEC 20 +#define SSLV3_ALERT_PROTOCOL 21 +#define SSLV3_HANDSHAKE_PROTOCOL 22 +#define SSLV3_APPLICATION_PROTOCOL 23 +#define SSLV3_HEARTBEAT_PROTOCOL 24 /* SSLv3 handshake protocol types */ -#define SSLV3_HS_HELLO_REQUEST 0 -#define SSLV3_HS_CLIENT_HELLO 1 -#define SSLV3_HS_SERVER_HELLO 2 -#define SSLV3_HS_NEW_SESSION_TICKET 4 -#define SSLV3_HS_CERTIFICATE 11 -#define SSLV3_HS_SERVER_KEY_EXCHANGE 12 -#define SSLV3_HS_CERTIFICATE_REQUEST 13 -#define SSLV3_HS_SERVER_HELLO_DONE 14 -#define SSLV3_HS_CERTIFICATE_VERIFY 15 -#define SSLV3_HS_CLIENT_KEY_EXCHANGE 16 -#define SSLV3_HS_FINISHED 20 -#define SSLV3_HS_CERTIFICATE_URL 21 -#define SSLV3_HS_CERTIFICATE_STATUS 22 +#define SSLV3_HS_HELLO_REQUEST 0 +#define SSLV3_HS_CLIENT_HELLO 1 +#define SSLV3_HS_SERVER_HELLO 2 +#define SSLV3_HS_NEW_SESSION_TICKET 4 +#define SSLV3_HS_CERTIFICATE 11 +#define SSLV3_HS_SERVER_KEY_EXCHANGE 12 +#define SSLV3_HS_CERTIFICATE_REQUEST 13 +#define SSLV3_HS_SERVER_HELLO_DONE 14 +#define SSLV3_HS_CERTIFICATE_VERIFY 15 +#define SSLV3_HS_CLIENT_KEY_EXCHANGE 16 +#define SSLV3_HS_FINISHED 20 +#define SSLV3_HS_CERTIFICATE_URL 21 +#define SSLV3_HS_CERTIFICATE_STATUS 22 /* SSLv2 protocol message types */ -#define SSLV2_MT_ERROR 0 -#define SSLV2_MT_CLIENT_HELLO 1 -#define SSLV2_MT_CLIENT_MASTER_KEY 2 -#define SSLV2_MT_CLIENT_FINISHED 3 -#define SSLV2_MT_SERVER_HELLO 4 -#define SSLV2_MT_SERVER_VERIFY 5 -#define SSLV2_MT_SERVER_FINISHED 6 -#define SSLV2_MT_REQUEST_CERTIFICATE 7 -#define SSLV2_MT_CLIENT_CERTIFICATE 8 - -#define SSLV3_RECORD_HDR_LEN 5 -#define SSLV3_MESSAGE_HDR_LEN 4 +#define SSLV2_MT_ERROR 0 +#define SSLV2_MT_CLIENT_HELLO 1 +#define SSLV2_MT_CLIENT_MASTER_KEY 2 +#define SSLV2_MT_CLIENT_FINISHED 3 +#define SSLV2_MT_SERVER_HELLO 4 +#define SSLV2_MT_SERVER_VERIFY 5 +#define SSLV2_MT_SERVER_FINISHED 6 +#define SSLV2_MT_REQUEST_CERTIFICATE 7 +#define SSLV2_MT_CLIENT_CERTIFICATE 8 + +#define SSLV3_RECORD_HDR_LEN 5 +#define SSLV3_MESSAGE_HDR_LEN 4 /** max length according to RFC 5246 6.2.2 is 2^14 + 1024 */ #define SSLV3_RECORD_MAX_LEN ((1 << 14) + 1024) -#define SSLV3_CLIENT_HELLO_VERSION_LEN 2 +#define SSLV3_CLIENT_HELLO_VERSION_LEN 2 #define SSLV3_CLIENT_HELLO_RANDOM_LEN 32 /* TLS heartbeat protocol types */ -#define TLS_HB_REQUEST 1 -#define TLS_HB_RESPONSE 2 +#define TLS_HB_REQUEST 1 +#define TLS_HB_RESPONSE 2 -#define SSL_RECORD_MINIMUM_LENGTH 6 +#define SSL_RECORD_MINIMUM_LENGTH 6 -#define SHA1_STRING_LENGTH 60 +#define SHA1_STRING_LENGTH 60 #define HAS_SPACE(n) ((uint64_t)(input - initial_input) + (uint64_t)(n) <= (uint64_t)(input_len)) @@ -233,20 +233,19 @@ struct SSLDecoderResult { (c), (n) \ } -static inline int SafeMemcpy(void *dst, size_t dst_offset, size_t dst_size, - const void *src, size_t src_offset, size_t src_size, size_t src_tocopy) WARN_UNUSED; +static inline int SafeMemcpy(void *dst, size_t dst_offset, size_t dst_size, const void *src, + size_t src_offset, size_t src_size, size_t src_tocopy) WARN_UNUSED; -static inline int SafeMemcpy(void *dst, size_t dst_offset, size_t dst_size, - const void *src, size_t src_offset, size_t src_size, size_t src_tocopy) +static inline int SafeMemcpy(void *dst, size_t dst_offset, size_t dst_size, const void *src, + size_t src_offset, size_t src_size, size_t src_tocopy) { DEBUG_VALIDATE_BUG_ON(dst_offset >= dst_size); DEBUG_VALIDATE_BUG_ON(src_offset >= src_size); DEBUG_VALIDATE_BUG_ON(src_tocopy > (src_size - src_offset)); DEBUG_VALIDATE_BUG_ON(src_tocopy > (dst_size - dst_offset)); - if (dst_offset < dst_size && src_offset < src_size && - src_tocopy <= (src_size - src_offset) && - src_tocopy <= (dst_size - dst_offset)) { + if (dst_offset < dst_size && src_offset < src_size && src_tocopy <= (src_size - src_offset) && + src_tocopy <= (dst_size - dst_offset)) { memcpy(dst + dst_offset, src + src_offset, src_tocopy); return 0; } @@ -254,11 +253,11 @@ static inline int SafeMemcpy(void *dst, size_t dst_offset, size_t dst_size, } #ifdef DEBUG_VALIDATION -#define ValidateRecordState(connp) \ - do { \ - DEBUG_VALIDATE_BUG_ON(((connp)->record_length + SSLV3_RECORD_HDR_LEN) < \ - (connp)->bytes_processed); \ - } while(0); +#define ValidateRecordState(connp) \ + do { \ + DEBUG_VALIDATE_BUG_ON( \ + ((connp)->record_length + SSLV3_RECORD_HDR_LEN) < (connp)->bytes_processed); \ + } while (0); #else #define ValidateRecordState(...) #endif @@ -269,12 +268,12 @@ static inline int SafeMemcpy(void *dst, size_t dst_offset, size_t dst_size, (connp)->message_length = 0; \ } while (0) -#define SSLParserReset(state) \ - do { \ - SCLogDebug("resetting state"); \ - (state)->curr_connp->bytes_processed = 0; \ - SSLParserHSReset((state)->curr_connp); \ - } while(0) +#define SSLParserReset(state) \ + do { \ + SCLogDebug("resetting state"); \ + (state)->curr_connp->bytes_processed = 0; \ + SSLParserHSReset((state)->curr_connp); \ + } while (0) #define SSLSetEvent(ssl_state, event) \ do { \ @@ -315,10 +314,8 @@ static int SSLGetAlstateProgress(void *tx, uint8_t direction) return TLS_HANDSHAKE_DONE; } - if (direction == STREAM_TOSERVER && - (ssl_state->server_connp.cert0_subject != NULL || - ssl_state->server_connp.cert0_issuerdn != NULL)) - { + if (direction == STREAM_TOSERVER && (ssl_state->server_connp.cert0_subject != NULL || + ssl_state->server_connp.cert0_issuerdn != NULL)) { return TLS_STATE_CERT_READY; } @@ -428,7 +425,7 @@ void SSLVersionToString(uint16_t version, char *buffer) static void TlsDecodeHSCertificateErrSetEvent(SSLState *ssl_state, uint32_t err) { - switch(err) { + switch (err) { case ERR_EXTRACT_VALIDITY: SSLSetEvent(ssl_state, TLS_DECODER_EVENT_CERTIFICATE_INVALID_VALIDITY); break; @@ -651,8 +648,7 @@ static int TlsDecodeHSCertificates(SSLState *ssl_state, SSLStateConnp *connp, */ static inline int TLSDecodeValueIsGREASE(const uint16_t value) { - switch (value) - { + switch (value) { case 0x0a0a: case 0x1a1a: case 0x2a2a: @@ -675,16 +671,14 @@ static inline int TLSDecodeValueIsGREASE(const uint16_t value) } } -static inline int TLSDecodeHSHelloVersion(SSLState *ssl_state, - const uint8_t * const initial_input, - const uint32_t input_len) +static inline int TLSDecodeHSHelloVersion( + SSLState *ssl_state, const uint8_t *const initial_input, const uint32_t input_len) { uint8_t *input = (uint8_t *)initial_input; if (!(HAS_SPACE(SSLV3_CLIENT_HELLO_VERSION_LEN))) { SCLogDebug("TLS handshake invalid length"); - SSLSetEvent(ssl_state, - TLS_DECODER_EVENT_HANDSHAKE_INVALID_LENGTH); + SSLSetEvent(ssl_state, TLS_DECODER_EVENT_HANDSHAKE_INVALID_LENGTH); return -1; } @@ -695,14 +689,13 @@ static inline int TLSDecodeHSHelloVersion(SSLState *ssl_state, versions, instead of using the supported versions extension. */ if ((ssl_state->current_flags & SSL_AL_FLAG_STATE_SERVER_HELLO) && ((ssl_state->curr_connp->version == TLS_VERSION_13) || - (((ssl_state->curr_connp->version >> 8) & 0xff) == 0x7f))) { + (((ssl_state->curr_connp->version >> 8) & 0xff) == 0x7f))) { ssl_state->flags |= SSL_AL_FLAG_LOG_WITHOUT_CERT; } /* Catch some early TLSv1.3 draft implementations that does not conform to the draft version. */ - if ((ssl_state->curr_connp->version >= 0x7f01) && - (ssl_state->curr_connp->version < 0x7f10)) { + if ((ssl_state->curr_connp->version >= 0x7f01) && (ssl_state->curr_connp->version < 0x7f10)) { ssl_state->curr_connp->version = TLS_VERSION_13_PRE_DRAFT16; } @@ -728,16 +721,14 @@ static inline int TLSDecodeHSHelloVersion(SSLState *ssl_state, return (input - initial_input); } -static inline int TLSDecodeHSHelloRandom(SSLState *ssl_state, - const uint8_t * const initial_input, - const uint32_t input_len) +static inline int TLSDecodeHSHelloRandom( + SSLState *ssl_state, const uint8_t *const initial_input, const uint32_t input_len) { uint8_t *input = (uint8_t *)initial_input; if (!(HAS_SPACE(SSLV3_CLIENT_HELLO_RANDOM_LEN))) { SCLogDebug("TLS handshake invalid length"); - SSLSetEvent(ssl_state, - TLS_DECODER_EVENT_HANDSHAKE_INVALID_LENGTH); + SSLSetEvent(ssl_state, TLS_DECODER_EVENT_HANDSHAKE_INVALID_LENGTH); return -1; } @@ -755,9 +746,8 @@ static inline int TLSDecodeHSHelloRandom(SSLState *ssl_state, return (input - initial_input); } -static inline int TLSDecodeHSHelloSessionID(SSLState *ssl_state, - const uint8_t * const initial_input, - const uint32_t input_len) +static inline int TLSDecodeHSHelloSessionID( + SSLState *ssl_state, const uint8_t *const initial_input, const uint32_t input_len) { uint8_t *input = (uint8_t *)initial_input; @@ -777,8 +767,8 @@ static inline int TLSDecodeHSHelloSessionID(SSLState *ssl_state, return -1; } - if (SafeMemcpy(ssl_state->curr_connp->session_id, 0, session_id_length, - input, 0, input_len, session_id_length) != 0) { + if (SafeMemcpy(ssl_state->curr_connp->session_id, 0, session_id_length, input, 0, input_len, + session_id_length) != 0) { return -1; } ssl_state->curr_connp->session_id_length = session_id_length; @@ -787,9 +777,9 @@ static inline int TLSDecodeHSHelloSessionID(SSLState *ssl_state, ssl_state->client_connp.session_id != NULL && ssl_state->server_connp.session_id != NULL) { if ((ssl_state->client_connp.session_id_length == - ssl_state->server_connp.session_id_length) && - (memcmp(ssl_state->server_connp.session_id, - ssl_state->client_connp.session_id, session_id_length) == 0)) { + ssl_state->server_connp.session_id_length) && + (memcmp(ssl_state->server_connp.session_id, ssl_state->client_connp.session_id, + session_id_length) == 0)) { ssl_state->flags |= SSL_AL_FLAG_SESSION_RESUMED; } } @@ -801,14 +791,12 @@ static inline int TLSDecodeHSHelloSessionID(SSLState *ssl_state, invalid_length: SCLogDebug("TLS handshake invalid length"); - SSLSetEvent(ssl_state, - TLS_DECODER_EVENT_HANDSHAKE_INVALID_LENGTH); + SSLSetEvent(ssl_state, TLS_DECODER_EVENT_HANDSHAKE_INVALID_LENGTH); return -1; } -static inline int TLSDecodeHSHelloCipherSuites(SSLState *ssl_state, - const uint8_t * const initial_input, - const uint32_t input_len) +static inline int TLSDecodeHSHelloCipherSuites( + SSLState *ssl_state, const uint8_t *const initial_input, const uint32_t input_len) { const uint8_t *input = initial_input; @@ -841,8 +829,7 @@ static inline int TLSDecodeHSHelloCipherSuites(SSLState *ssl_state, uint16_t processed_len = 0; /* coverity[tainted_data] */ - while (processed_len < cipher_suites_length) - { + while (processed_len < cipher_suites_length) { if (!(HAS_SPACE(2))) { Ja3BufferFree(&ja3_cipher_suites); goto invalid_length; @@ -861,8 +848,7 @@ static inline int TLSDecodeHSHelloCipherSuites(SSLState *ssl_state, processed_len += 2; } - int rc = Ja3BufferAppendBuffer(&ssl_state->curr_connp->ja3_str, - &ja3_cipher_suites); + int rc = Ja3BufferAppendBuffer(&ssl_state->curr_connp->ja3_str, &ja3_cipher_suites); if (rc == -1) { return -1; } @@ -876,14 +862,12 @@ static inline int TLSDecodeHSHelloCipherSuites(SSLState *ssl_state, invalid_length: SCLogDebug("TLS handshake invalid length"); - SSLSetEvent(ssl_state, - TLS_DECODER_EVENT_HANDSHAKE_INVALID_LENGTH); + SSLSetEvent(ssl_state, TLS_DECODER_EVENT_HANDSHAKE_INVALID_LENGTH); return -1; } -static inline int TLSDecodeHSHelloCompressionMethods(SSLState *ssl_state, - const uint8_t * const initial_input, - const uint32_t input_len) +static inline int TLSDecodeHSHelloCompressionMethods( + SSLState *ssl_state, const uint8_t *const initial_input, const uint32_t input_len) { const uint8_t *input = initial_input; @@ -907,14 +891,12 @@ static inline int TLSDecodeHSHelloCompressionMethods(SSLState *ssl_state, invalid_length: SCLogDebug("TLS handshake invalid_length"); - SSLSetEvent(ssl_state, - TLS_DECODER_EVENT_HANDSHAKE_INVALID_LENGTH); + SSLSetEvent(ssl_state, TLS_DECODER_EVENT_HANDSHAKE_INVALID_LENGTH); return -1; } -static inline int TLSDecodeHSHelloExtensionSni(SSLState *ssl_state, - const uint8_t * const initial_input, - const uint32_t input_len) +static inline int TLSDecodeHSHelloExtensionSni( + SSLState *ssl_state, const uint8_t *const initial_input, const uint32_t input_len) { uint8_t *input = (uint8_t *)initial_input; @@ -938,8 +920,7 @@ static inline int TLSDecodeHSHelloExtensionSni(SSLState *ssl_state, (RFC6066 section 3). */ if (sni_type != SSL_SNI_TYPE_HOST_NAME) { SCLogDebug("Unknown SNI type"); - SSLSetEvent(ssl_state, - TLS_DECODER_EVENT_INVALID_SNI_TYPE); + SSLSetEvent(ssl_state, TLS_DECODER_EVENT_INVALID_SNI_TYPE); return -1; } @@ -953,8 +934,7 @@ static inline int TLSDecodeHSHelloExtensionSni(SSLState *ssl_state, and should therefore be limited by the maximum domain name length. */ if (!(HAS_SPACE(sni_len)) || sni_len > 255 || sni_len == 0) { - SSLSetEvent(ssl_state, - TLS_DECODER_EVENT_INVALID_SNI_LENGTH); + SSLSetEvent(ssl_state, TLS_DECODER_EVENT_INVALID_SNI_LENGTH); return -1; } @@ -962,8 +942,7 @@ static inline int TLSDecodeHSHelloExtensionSni(SSLState *ssl_state, type (RFC5246 section 7.4.1.4). */ if (ssl_state->curr_connp->sni) { SCLogDebug("Multiple SNI extensions"); - SSLSetEvent(ssl_state, - TLS_DECODER_EVENT_MULTIPLE_SNI_EXTENSIONS); + SSLSetEvent(ssl_state, TLS_DECODER_EVENT_MULTIPLE_SNI_EXTENSIONS); input += sni_len; return (input - initial_input); } @@ -974,13 +953,13 @@ static inline int TLSDecodeHSHelloExtensionSni(SSLState *ssl_state, return -1; const size_t consumed = input - initial_input; - if (SafeMemcpy(ssl_state->curr_connp->sni, 0, sni_strlen, - initial_input, consumed, input_len, sni_len) != 0) { + if (SafeMemcpy(ssl_state->curr_connp->sni, 0, sni_strlen, initial_input, consumed, input_len, + sni_len) != 0) { SCFree(ssl_state->curr_connp->sni); ssl_state->curr_connp->sni = NULL; return -1; } - ssl_state->curr_connp->sni[sni_strlen-1] = 0; + ssl_state->curr_connp->sni[sni_strlen - 1] = 0; input += sni_len; @@ -988,16 +967,13 @@ static inline int TLSDecodeHSHelloExtensionSni(SSLState *ssl_state, invalid_length: SCLogDebug("TLS handshake invalid length"); - SSLSetEvent(ssl_state, - TLS_DECODER_EVENT_HANDSHAKE_INVALID_LENGTH); - + SSLSetEvent(ssl_state, TLS_DECODER_EVENT_HANDSHAKE_INVALID_LENGTH); return -1; } -static inline int TLSDecodeHSHelloExtensionSupportedVersions(SSLState *ssl_state, - const uint8_t * const initial_input, - const uint32_t input_len) +static inline int TLSDecodeHSHelloExtensionSupportedVersions( + SSLState *ssl_state, const uint8_t *const initial_input, const uint32_t input_len) { const uint8_t *input = initial_input; @@ -1034,15 +1010,13 @@ static inline int TLSDecodeHSHelloExtensionSupportedVersions(SSLState *ssl_state ssl_state->flags |= SSL_AL_FLAG_CH_VERSION_EXTENSION; input += supported_ver_len; - } - else if (ssl_state->current_flags & SSL_AL_FLAG_STATE_SERVER_HELLO) { + } else if (ssl_state->current_flags & SSL_AL_FLAG_STATE_SERVER_HELLO) { if (!(HAS_SPACE(2))) goto invalid_length; uint16_t ver = (uint16_t)(*input << 8) | *(input + 1); - if ((ssl_state->flags & SSL_AL_FLAG_CH_VERSION_EXTENSION) && - (ver > TLS_VERSION_12)) { + if ((ssl_state->flags & SSL_AL_FLAG_CH_VERSION_EXTENSION) && (ver > TLS_VERSION_12)) { ssl_state->flags |= SSL_AL_FLAG_LOG_WITHOUT_CERT; } @@ -1054,16 +1028,14 @@ static inline int TLSDecodeHSHelloExtensionSupportedVersions(SSLState *ssl_state invalid_length: SCLogDebug("TLS handshake invalid length"); - SSLSetEvent(ssl_state, - TLS_DECODER_EVENT_HANDSHAKE_INVALID_LENGTH); + SSLSetEvent(ssl_state, TLS_DECODER_EVENT_HANDSHAKE_INVALID_LENGTH); return -1; } static inline int TLSDecodeHSHelloExtensionEllipticCurves(SSLState *ssl_state, - const uint8_t * const initial_input, - const uint32_t input_len, - JA3Buffer *ja3_elliptic_curves) + const uint8_t *const initial_input, const uint32_t input_len, + JA3Buffer *ja3_elliptic_curves) { const uint8_t *input = initial_input; @@ -1084,8 +1056,7 @@ static inline int TLSDecodeHSHelloExtensionEllipticCurves(SSLState *ssl_state, SC_ATOMIC_GET(ssl_config.enable_ja3)) { uint16_t ec_processed_len = 0; /* coverity[tainted_data] */ - while (ec_processed_len < elliptic_curves_len) - { + while (ec_processed_len < elliptic_curves_len) { if (!(HAS_SPACE(2))) goto invalid_length; @@ -1093,8 +1064,7 @@ static inline int TLSDecodeHSHelloExtensionEllipticCurves(SSLState *ssl_state, input += 2; if (TLSDecodeValueIsGREASE(elliptic_curve) != 1) { - int rc = Ja3BufferAddValue(&ja3_elliptic_curves, - elliptic_curve); + int rc = Ja3BufferAddValue(&ja3_elliptic_curves, elliptic_curve); if (rc != 0) return -1; } @@ -1111,16 +1081,14 @@ static inline int TLSDecodeHSHelloExtensionEllipticCurves(SSLState *ssl_state, invalid_length: SCLogDebug("TLS handshake invalid length"); - SSLSetEvent(ssl_state, - TLS_DECODER_EVENT_HANDSHAKE_INVALID_LENGTH); + SSLSetEvent(ssl_state, TLS_DECODER_EVENT_HANDSHAKE_INVALID_LENGTH); return -1; } static inline int TLSDecodeHSHelloExtensionEllipticCurvePF(SSLState *ssl_state, - const uint8_t * const initial_input, - const uint32_t input_len, - JA3Buffer *ja3_elliptic_curves_pf) + const uint8_t *const initial_input, const uint32_t input_len, + JA3Buffer *ja3_elliptic_curves_pf) { const uint8_t *input = initial_input; @@ -1141,14 +1109,12 @@ static inline int TLSDecodeHSHelloExtensionEllipticCurvePF(SSLState *ssl_state, SC_ATOMIC_GET(ssl_config.enable_ja3)) { uint8_t ec_pf_processed_len = 0; /* coverity[tainted_data] */ - while (ec_pf_processed_len < ec_pf_len) - { + while (ec_pf_processed_len < ec_pf_len) { uint8_t elliptic_curve_pf = *input; input += 1; if (TLSDecodeValueIsGREASE(elliptic_curve_pf) != 1) { - int rc = Ja3BufferAddValue(&ja3_elliptic_curves_pf, - elliptic_curve_pf); + int rc = Ja3BufferAddValue(&ja3_elliptic_curves_pf, elliptic_curve_pf); if (rc != 0) return -1; } @@ -1165,15 +1131,13 @@ static inline int TLSDecodeHSHelloExtensionEllipticCurvePF(SSLState *ssl_state, invalid_length: SCLogDebug("TLS handshake invalid length"); - SSLSetEvent(ssl_state, - TLS_DECODER_EVENT_HANDSHAKE_INVALID_LENGTH); + SSLSetEvent(ssl_state, TLS_DECODER_EVENT_HANDSHAKE_INVALID_LENGTH); return -1; } -static inline int TLSDecodeHSHelloExtensions(SSLState *ssl_state, - const uint8_t * const initial_input, - const uint32_t input_len) +static inline int TLSDecodeHSHelloExtensions( + SSLState *ssl_state, const uint8_t *const initial_input, const uint32_t input_len) { const uint8_t *input = initial_input; @@ -1213,8 +1177,7 @@ static inline int TLSDecodeHSHelloExtensions(SSLState *ssl_state, uint16_t processed_len = 0; /* coverity[tainted_data] */ - while (processed_len < extensions_len) - { + while (processed_len < extensions_len) { if (!(HAS_SPACE(2))) goto invalid_length; @@ -1231,11 +1194,9 @@ static inline int TLSDecodeHSHelloExtensions(SSLState *ssl_state, goto invalid_length; switch (ext_type) { - case SSL_EXTENSION_SNI: - { + case SSL_EXTENSION_SNI: { /* coverity[tainted_data] */ - ret = TLSDecodeHSHelloExtensionSni(ssl_state, input, - ext_len); + ret = TLSDecodeHSHelloExtensionSni(ssl_state, input, ext_len); if (ret < 0) goto end; @@ -1244,12 +1205,10 @@ static inline int TLSDecodeHSHelloExtensions(SSLState *ssl_state, break; } - case SSL_EXTENSION_ELLIPTIC_CURVES: - { + case SSL_EXTENSION_ELLIPTIC_CURVES: { /* coverity[tainted_data] */ - ret = TLSDecodeHSHelloExtensionEllipticCurves(ssl_state, input, - ext_len, - ja3_elliptic_curves); + ret = TLSDecodeHSHelloExtensionEllipticCurves( + ssl_state, input, ext_len, ja3_elliptic_curves); if (ret < 0) goto end; @@ -1258,12 +1217,10 @@ static inline int TLSDecodeHSHelloExtensions(SSLState *ssl_state, break; } - case SSL_EXTENSION_EC_POINT_FORMATS: - { + case SSL_EXTENSION_EC_POINT_FORMATS: { /* coverity[tainted_data] */ - ret = TLSDecodeHSHelloExtensionEllipticCurvePF(ssl_state, input, - ext_len, - ja3_elliptic_curves_pf); + ret = TLSDecodeHSHelloExtensionEllipticCurvePF( + ssl_state, input, ext_len, ja3_elliptic_curves_pf); if (ret < 0) goto end; @@ -1272,8 +1229,7 @@ static inline int TLSDecodeHSHelloExtensions(SSLState *ssl_state, break; } - case SSL_EXTENSION_EARLY_DATA: - { + case SSL_EXTENSION_EARLY_DATA: { if (ssl_state->current_flags & SSL_AL_FLAG_STATE_CLIENT_HELLO) { /* Used by 0-RTT to indicate that encrypted data will be sent right after the ClientHello record. */ @@ -1285,10 +1241,8 @@ static inline int TLSDecodeHSHelloExtensions(SSLState *ssl_state, break; } - case SSL_EXTENSION_SUPPORTED_VERSIONS: - { - ret = TLSDecodeHSHelloExtensionSupportedVersions(ssl_state, input, - ext_len); + case SSL_EXTENSION_SUPPORTED_VERSIONS: { + ret = TLSDecodeHSHelloExtensionSupportedVersions(ssl_state, input, ext_len); if (ret < 0) goto end; @@ -1297,8 +1251,7 @@ static inline int TLSDecodeHSHelloExtensions(SSLState *ssl_state, break; } - case SSL_EXTENSION_SESSION_TICKET: - { + case SSL_EXTENSION_SESSION_TICKET: { if (ssl_state->current_flags & SSL_AL_FLAG_STATE_CLIENT_HELLO) { /* This has to be verified later on by checking if a certificate record has been sent by the server. */ @@ -1310,8 +1263,7 @@ static inline int TLSDecodeHSHelloExtensions(SSLState *ssl_state, break; } - default: - { + default: { input += ext_len; break; } @@ -1330,19 +1282,16 @@ static inline int TLSDecodeHSHelloExtensions(SSLState *ssl_state, end: if (ja3) { - rc = Ja3BufferAppendBuffer(&ssl_state->curr_connp->ja3_str, - &ja3_extensions); + rc = Ja3BufferAppendBuffer(&ssl_state->curr_connp->ja3_str, &ja3_extensions); if (rc == -1) goto error; if (ssl_state->current_flags & SSL_AL_FLAG_STATE_CLIENT_HELLO) { - rc = Ja3BufferAppendBuffer(&ssl_state->curr_connp->ja3_str, - &ja3_elliptic_curves); + rc = Ja3BufferAppendBuffer(&ssl_state->curr_connp->ja3_str, &ja3_elliptic_curves); if (rc == -1) goto error; - rc = Ja3BufferAppendBuffer(&ssl_state->curr_connp->ja3_str, - &ja3_elliptic_curves_pf); + rc = Ja3BufferAppendBuffer(&ssl_state->curr_connp->ja3_str, &ja3_elliptic_curves_pf); if (rc == -1) goto error; } @@ -1352,8 +1301,7 @@ static inline int TLSDecodeHSHelloExtensions(SSLState *ssl_state, invalid_length: SCLogDebug("TLS handshake invalid length"); - SSLSetEvent(ssl_state, - TLS_DECODER_EVENT_HANDSHAKE_INVALID_LENGTH); + SSLSetEvent(ssl_state, TLS_DECODER_EVENT_HANDSHAKE_INVALID_LENGTH); error: if (ja3_extensions != NULL) @@ -1366,9 +1314,8 @@ static inline int TLSDecodeHSHelloExtensions(SSLState *ssl_state, return -1; } -static int TLSDecodeHandshakeHello(SSLState *ssl_state, - const uint8_t * const input, - const uint32_t input_len) +static int TLSDecodeHandshakeHello( + SSLState *ssl_state, const uint8_t *const input, const uint32_t input_len) { int ret; uint32_t parsed = 0; @@ -1389,37 +1336,33 @@ static int TLSDecodeHandshakeHello(SSLState *ssl_state, TLSv1.3 draft1, but was readded in draft22. */ if ((ssl_state->current_flags & SSL_AL_FLAG_STATE_CLIENT_HELLO) || ((ssl_state->current_flags & SSL_AL_FLAG_STATE_SERVER_HELLO) && - ((ssl_state->flags & SSL_AL_FLAG_LOG_WITHOUT_CERT) == 0))) { - ret = TLSDecodeHSHelloSessionID(ssl_state, input + parsed, - input_len - parsed); + ((ssl_state->flags & SSL_AL_FLAG_LOG_WITHOUT_CERT) == 0))) { + ret = TLSDecodeHSHelloSessionID(ssl_state, input + parsed, input_len - parsed); if (ret < 0) goto end; parsed += ret; } - ret = TLSDecodeHSHelloCipherSuites(ssl_state, input + parsed, - input_len - parsed); + ret = TLSDecodeHSHelloCipherSuites(ssl_state, input + parsed, input_len - parsed); if (ret < 0) goto end; parsed += ret; - /* The compression methods field in the server hello record was - removed in TLSv1.3 draft1, but was readded in draft22. */ - if ((ssl_state->current_flags & SSL_AL_FLAG_STATE_CLIENT_HELLO) || - ((ssl_state->current_flags & SSL_AL_FLAG_STATE_SERVER_HELLO) && - ((ssl_state->flags & SSL_AL_FLAG_LOG_WITHOUT_CERT) == 0))) { - ret = TLSDecodeHSHelloCompressionMethods(ssl_state, input + parsed, - input_len - parsed); + /* The compression methods field in the server hello record was + removed in TLSv1.3 draft1, but was readded in draft22. */ + if ((ssl_state->current_flags & SSL_AL_FLAG_STATE_CLIENT_HELLO) || + ((ssl_state->current_flags & SSL_AL_FLAG_STATE_SERVER_HELLO) && + ((ssl_state->flags & SSL_AL_FLAG_LOG_WITHOUT_CERT) == 0))) { + ret = TLSDecodeHSHelloCompressionMethods(ssl_state, input + parsed, input_len - parsed); if (ret < 0) goto end; parsed += ret; } - ret = TLSDecodeHSHelloExtensions(ssl_state, input + parsed, - input_len - parsed); + ret = TLSDecodeHSHelloExtensions(ssl_state, input + parsed, input_len - parsed); if (ret < 0) goto end; @@ -1432,11 +1375,9 @@ static int TLSDecodeHandshakeHello(SSLState *ssl_state, } #ifdef DEBUG_VALIDATION -static inline bool -RecordAlreadyProcessed(const SSLStateConnp *curr_connp) +static inline bool RecordAlreadyProcessed(const SSLStateConnp *curr_connp) { - return ((curr_connp->record_length + SSLV3_RECORD_HDR_LEN) < - curr_connp->bytes_processed); + return ((curr_connp->record_length + SSLV3_RECORD_HDR_LEN) < curr_connp->bytes_processed); } #endif @@ -1485,8 +1426,8 @@ static int SupportedHandshakeType(const uint8_t type) * \retval parsed number of consumed bytes * \retval < 0 error */ -static int SSLv3ParseHandshakeType(SSLState *ssl_state, const uint8_t *input, - uint32_t input_len, uint8_t direction) +static int SSLv3ParseHandshakeType( + SSLState *ssl_state, const uint8_t *input, uint32_t input_len, uint8_t direction) { const uint8_t *initial_input = input; int rc; @@ -1556,18 +1497,19 @@ static int SSLv3ParseHandshakeType(SSLState *ssl_state, const uint8_t *input, ssl_state->flags |= ssl_state->current_flags; SCLogDebug("message: length %u", ssl_state->curr_connp->message_length); - SCLogDebug("input_len %u ssl_state->curr_connp->bytes_processed %u", input_len, ssl_state->curr_connp->bytes_processed); + SCLogDebug("input_len %u ssl_state->curr_connp->bytes_processed %u", input_len, + ssl_state->curr_connp->bytes_processed); return input_len; } -static int SSLv3ParseHandshakeProtocol(SSLState *ssl_state, const uint8_t *input, - uint32_t input_len, uint8_t direction) +static int SSLv3ParseHandshakeProtocol( + SSLState *ssl_state, const uint8_t *input, uint32_t input_len, uint8_t direction) { const uint8_t *initial_input = input; if (input_len == 0 || ssl_state->curr_connp->bytes_processed == - (ssl_state->curr_connp->record_length + SSLV3_RECORD_HDR_LEN)) { + (ssl_state->curr_connp->record_length + SSLV3_RECORD_HDR_LEN)) { SCReturnInt(0); } @@ -1744,8 +1686,8 @@ static int SSLv3ParseHandshakeProtocol(SSLState *ssl_state, const uint8_t *input * * \retval The number of bytes parsed on success, 0 if nothing parsed, -1 on failure. */ -static int SSLv3ParseHeartbeatProtocol(SSLState *ssl_state, const uint8_t *input, - uint32_t input_len, uint8_t direction) +static int SSLv3ParseHeartbeatProtocol( + SSLState *ssl_state, const uint8_t *input, uint32_t input_len, uint8_t direction) { uint8_t hb_type; uint16_t payload_len; @@ -1781,7 +1723,7 @@ static int SSLv3ParseHeartbeatProtocol(SSLState *ssl_state, const uint8_t *input if (ssl_state->flags & SSL_AL_FLAG_CHANGE_CIPHER_SPEC) { ssl_state->hb_record_len = ssl_state->curr_connp->record_length; SCLogDebug("Encrypted HeartBeat Request In-flight. Storing len %u", - ssl_state->hb_record_len); + ssl_state->hb_record_len); return (ssl_state->curr_connp->record_length - 3); } @@ -1789,7 +1731,7 @@ static int SSLv3ParseHeartbeatProtocol(SSLState *ssl_state, const uint8_t *input /* check that the requested payload length is really present in the record (CVE-2014-0160) */ - if ((uint32_t)(payload_len+3) > ssl_state->curr_connp->record_length) { + if ((uint32_t)(payload_len + 3) > ssl_state->curr_connp->record_length) { SCLogDebug("We have a short record in HeartBeat Request"); SSLSetEvent(ssl_state, TLS_DECODER_EVENT_OVERFLOW_HEARTBEAT); return -1; @@ -1809,16 +1751,16 @@ static int SSLv3ParseHeartbeatProtocol(SSLState *ssl_state, const uint8_t *input return 0; } - /* OpenSSL still seems to discard multiple in-flight - heartbeats although some tools send multiple at once */ + /* OpenSSL still seems to discard multiple in-flight + heartbeats although some tools send multiple at once */ } else if (direction == 1 && (ssl_state->flags & SSL_AL_FLAG_HB_INFLIGHT) && - (ssl_state->flags & SSL_AL_FLAG_HB_SERVER_INIT)) { + (ssl_state->flags & SSL_AL_FLAG_HB_SERVER_INIT)) { SCLogDebug("Multiple in-flight server initiated HeartBeats"); SSLSetEvent(ssl_state, TLS_DECODER_EVENT_INVALID_HEARTBEAT); return -1; } else if (direction == 0 && (ssl_state->flags & SSL_AL_FLAG_HB_INFLIGHT) && - (ssl_state->flags & SSL_AL_FLAG_HB_CLIENT_INIT)) { + (ssl_state->flags & SSL_AL_FLAG_HB_CLIENT_INIT)) { SCLogDebug("Multiple in-flight client initiated HeartBeats"); SSLSetEvent(ssl_state, TLS_DECODER_EVENT_INVALID_HEARTBEAT); return -1; @@ -1835,12 +1777,11 @@ static int SSLv3ParseHeartbeatProtocol(SSLState *ssl_state, const uint8_t *input if (ssl_state->flags & SSL_AL_FLAG_CHANGE_CIPHER_SPEC) { /* check to see if the encrypted response is longer than the encrypted request */ - if (ssl_state->hb_record_len > 0 && ssl_state->hb_record_len < - ssl_state->curr_connp->record_length) { + if (ssl_state->hb_record_len > 0 && + ssl_state->hb_record_len < ssl_state->curr_connp->record_length) { SCLogDebug("My heart is bleeding.. OpenSSL HeartBleed response (%u)", ssl_state->hb_record_len); - SSLSetEvent(ssl_state, - TLS_DECODER_EVENT_DATALEAK_HEARTBEAT_MISMATCH); + SSLSetEvent(ssl_state, TLS_DECODER_EVENT_DATALEAK_HEARTBEAT_MISMATCH); ssl_state->hb_record_len = 0; return -1; } @@ -1856,8 +1797,8 @@ static int SSLv3ParseHeartbeatProtocol(SSLState *ssl_state, const uint8_t *input return (ssl_state->curr_connp->record_length - 3); } -static int SSLv3ParseRecord(uint8_t direction, SSLState *ssl_state, - const uint8_t *input, uint32_t input_len) +static int SSLv3ParseRecord( + uint8_t direction, SSLState *ssl_state, const uint8_t *input, uint32_t input_len) { const uint8_t *initial_input = input; @@ -1938,8 +1879,8 @@ static int SSLv3ParseRecord(uint8_t direction, SSLState *ssl_state, return (input - initial_input); } -static int SSLv2ParseRecord(uint8_t direction, SSLState *ssl_state, - const uint8_t *input, uint32_t input_len) +static int SSLv2ParseRecord( + uint8_t direction, SSLState *ssl_state, const uint8_t *input, uint32_t input_len) { const uint8_t *initial_input = input; @@ -2144,8 +2085,7 @@ static struct SSLDecoderResult SSLv2Decode(uint8_t direction, SSLState *ssl_stat case SSLV2_MT_SERVER_VERIFY: case SSLV2_MT_SERVER_FINISHED: if (direction == 0 && - !(ssl_state->curr_connp->content_type & - SSLV2_MT_CLIENT_CERTIFICATE)) { + !(ssl_state->curr_connp->content_type & SSLV2_MT_CLIENT_CERTIFICATE)) { SCLogDebug("Incorrect SSL Record type sent in the toserver " "direction!"); } @@ -2171,11 +2111,9 @@ static struct SSLDecoderResult SSLv2Decode(uint8_t direction, SSLState *ssl_stat } if ((ssl_state->flags & SSL_AL_FLAG_SSL_CLIENT_SSN_ENCRYPTED) && - (ssl_state->flags & SSL_AL_FLAG_SSL_SERVER_SSN_ENCRYPTED)) - { + (ssl_state->flags & SSL_AL_FLAG_SSL_SERVER_SSN_ENCRYPTED)) { if (ssl_config.encrypt_mode != SSL_CNF_ENC_HANDLE_FULL) { - AppLayerParserStateSetFlag(pstate, - APP_LAYER_PARSER_NO_INSPECTION); + AppLayerParserStateSetFlag(pstate, APP_LAYER_PARSER_NO_INSPECTION); } if (ssl_config.encrypt_mode == SSL_CNF_ENC_HANDLE_BYPASS) { @@ -2198,13 +2136,12 @@ static struct SSLDecoderResult SSLv2Decode(uint8_t direction, SSLState *ssl_stat ssl_state->flags |= ssl_state->current_flags; if (input_len + ssl_state->curr_connp->bytes_processed >= - (ssl_state->curr_connp->record_length + - ssl_state->curr_connp->record_lengths_length)) { + (ssl_state->curr_connp->record_length + ssl_state->curr_connp->record_lengths_length)) { /* looks like we have another record after this */ uint32_t diff = ssl_state->curr_connp->record_length + - ssl_state->curr_connp->record_lengths_length + - - ssl_state->curr_connp->bytes_processed; + ssl_state->curr_connp->record_lengths_length + + -ssl_state->curr_connp->bytes_processed; input += diff; SSLParserReset(ssl_state); @@ -2320,11 +2257,12 @@ static struct SSLDecoderResult SSLv3Decode(uint8_t direction, SSLState *ssl_stat } else { ValidateRecordState(ssl_state->curr_connp); - record_len = (ssl_state->curr_connp->record_length + SSLV3_RECORD_HDR_LEN)- ssl_state->curr_connp->bytes_processed; + record_len = (ssl_state->curr_connp->record_length + SSLV3_RECORD_HDR_LEN) - + ssl_state->curr_connp->bytes_processed; record_len = MIN(input_len, record_len); } - SCLogDebug("record length %u processed %u got %u", - ssl_state->curr_connp->record_length, ssl_state->curr_connp->bytes_processed, record_len); + SCLogDebug("record length %u processed %u got %u", ssl_state->curr_connp->record_length, + ssl_state->curr_connp->bytes_processed, record_len); /* if we don't have the full record, we return incomplete */ if (ssl_state->curr_connp->record_length > input_len - parsed) { @@ -2380,20 +2318,16 @@ static struct SSLDecoderResult SSLv3Decode(uint8_t direction, SSLState *ssl_stat if (ssl_config.encrypt_mode != SSL_CNF_ENC_HANDLE_FULL) { SCLogDebug("setting APP_LAYER_PARSER_NO_INSPECTION_PAYLOAD"); - AppLayerParserStateSetFlag(pstate, - APP_LAYER_PARSER_NO_INSPECTION_PAYLOAD); + AppLayerParserStateSetFlag(pstate, APP_LAYER_PARSER_NO_INSPECTION_PAYLOAD); } /* Encrypted data, reassembly not asked, bypass asked, let's sacrifice * heartbeat lke inspection to be able to be able to bypass the flow */ if (ssl_config.encrypt_mode == SSL_CNF_ENC_HANDLE_BYPASS) { SCLogDebug("setting APP_LAYER_PARSER_NO_REASSEMBLY"); - AppLayerParserStateSetFlag(pstate, - APP_LAYER_PARSER_NO_REASSEMBLY); - AppLayerParserStateSetFlag(pstate, - APP_LAYER_PARSER_NO_INSPECTION); - AppLayerParserStateSetFlag(pstate, - APP_LAYER_PARSER_BYPASS_READY); + AppLayerParserStateSetFlag(pstate, APP_LAYER_PARSER_NO_REASSEMBLY); + AppLayerParserStateSetFlag(pstate, APP_LAYER_PARSER_NO_INSPECTION); + AppLayerParserStateSetFlag(pstate, APP_LAYER_PARSER_BYPASS_READY); } break; @@ -2419,8 +2353,8 @@ static struct SSLDecoderResult SSLv3Decode(uint8_t direction, SSLState *ssl_stat return SSL_DECODER_ERROR(-1); } - int retval = SSLv3ParseHandshakeProtocol(ssl_state, input + parsed, - record_len, direction); + int retval = + SSLv3ParseHandshakeProtocol(ssl_state, input + parsed, record_len, direction); SCLogDebug("retval %d", retval); if (retval < 0 || retval > (int)record_len) { DEBUG_VALIDATE_BUG_ON(retval > (int)record_len); @@ -2434,8 +2368,8 @@ static struct SSLDecoderResult SSLv3Decode(uint8_t direction, SSLState *ssl_stat case SSLV3_HEARTBEAT_PROTOCOL: { AppLayerFrameNewByPointer(ssl_state->f, &stream_slice, input + parsed, ssl_state->curr_connp->record_length, direction, TLS_FRAME_HB_DATA); - int retval = SSLv3ParseHeartbeatProtocol(ssl_state, input + parsed, - record_len, direction); + int retval = + SSLv3ParseHeartbeatProtocol(ssl_state, input + parsed, record_len, direction); if (retval < 0) { SCLogDebug("SSLv3ParseHeartbeatProtocol returned %d", retval); return SSL_DECODER_ERROR(-1); @@ -2519,14 +2453,13 @@ static AppLayerResult SSLDecode(Flow *f, uint8_t direction, void *alstate, } /* if we have more than one record */ - uint32_t max_records = MAX((input_len / SSL_RECORD_MINIMUM_LENGTH),1); + uint32_t max_records = MAX((input_len / SSL_RECORD_MINIMUM_LENGTH), 1); while (input_len > 0) { if (counter > max_records) { SCLogDebug("Looks like we have looped quite a bit. Reset state " "and get out of here"); SSLParserReset(ssl_state); - SSLSetEvent(ssl_state, - TLS_DECODER_EVENT_TOO_MANY_RECORDS_IN_PACKET); + SSLSetEvent(ssl_state, TLS_DECODER_EVENT_TOO_MANY_RECORDS_IN_PACKET); return APP_LAYER_ERROR; } @@ -2559,8 +2492,7 @@ static AppLayerResult SSLDecode(Flow *f, uint8_t direction, void *alstate, SCLogDebug("Error parsing SSLv2. Resetting parser " "state. Let's get outta here"); SSLParserReset(ssl_state); - SSLSetEvent(ssl_state, - TLS_DECODER_EVENT_INVALID_SSL_RECORD); + SSLSetEvent(ssl_state, TLS_DECODER_EVENT_INVALID_SSL_RECORD); return APP_LAYER_ERROR; } else if (r.needed) { input += r.retval; @@ -2573,11 +2505,12 @@ static AppLayerResult SSLDecode(Flow *f, uint8_t direction, void *alstate, SCLogDebug("SSLv2 decoder consumed %d bytes: %u left", r.retval, input_len); } else { if (ssl_state->curr_connp->bytes_processed == 0) { - SCLogDebug("New TLS record: record_length %u", - ssl_state->curr_connp->record_length); + SCLogDebug( + "New TLS record: record_length %u", ssl_state->curr_connp->record_length); } else { SCLogDebug("Continuing parsing TLS record: record_length %u, bytes_processed %u", - ssl_state->curr_connp->record_length, ssl_state->curr_connp->bytes_processed); + ssl_state->curr_connp->record_length, + ssl_state->curr_connp->bytes_processed); } struct SSLDecoderResult r = SSLv3Decode(direction, ssl_state, pstate, input, input_len, stream_slice); @@ -2597,8 +2530,8 @@ static AppLayerResult SSLDecode(Flow *f, uint8_t direction, void *alstate, input += r.retval; SCLogDebug("TLS decoder consumed %d bytes: %u left", r.retval, input_len); - if (ssl_state->curr_connp->bytes_processed == SSLV3_RECORD_HDR_LEN - && ssl_state->curr_connp->record_length == 0) { + if (ssl_state->curr_connp->bytes_processed == SSLV3_RECORD_HDR_LEN && + ssl_state->curr_connp->record_length == 0) { SCLogDebug("TLS empty record"); /* empty record */ SSLParserReset(ssl_state); @@ -2620,7 +2553,7 @@ static AppLayerResult SSLDecode(Flow *f, uint8_t direction, void *alstate, /* flag session as finished if APP_LAYER_PARSER_EOF is set */ if (AppLayerParserStateIssetFlag(pstate, APP_LAYER_PARSER_EOF_TS) && - AppLayerParserStateIssetFlag(pstate, APP_LAYER_PARSER_EOF_TC)) { + AppLayerParserStateIssetFlag(pstate, APP_LAYER_PARSER_EOF_TC)) { SCLogDebug("SSL_AL_FLAG_STATE_FINISHED"); ssl_state->flags |= SSL_AL_FLAG_STATE_FINISHED; } @@ -2740,8 +2673,8 @@ static void SSLStateTransactionFree(void *state, uint64_t tx_id) /* do nothing */ } -static AppProto SSLProbingParser(Flow *f, uint8_t direction, - const uint8_t *input, uint32_t ilen, uint8_t *rdir) +static AppProto SSLProbingParser( + Flow *f, uint8_t direction, const uint8_t *input, uint32_t ilen, uint8_t *rdir) { /* probably a rst/fin sending an eof */ if (ilen < 3) @@ -2771,8 +2704,8 @@ static const char *SSLStateGetFrameNameById(const uint8_t frame_id) return name; } -static int SSLStateGetEventInfo(const char *event_name, - int *event_id, AppLayerEventType *event_type) +static int SSLStateGetEventInfo( + const char *event_name, int *event_id, AppLayerEventType *event_type) { *event_id = SCMapEnumNameToValue(event_name, tls_decoder_event_table); if (*event_id == -1) { @@ -2788,8 +2721,8 @@ static int SSLStateGetEventInfo(const char *event_name, return 0; } -static int SSLStateGetEventInfoById(int event_id, const char **event_name, - AppLayerEventType *event_type) +static int SSLStateGetEventInfoById( + int event_id, const char **event_name, AppLayerEventType *event_type) { *event_name = SCMapEnumValueToName(event_id, tls_decoder_event_table); if (*event_name == NULL) { @@ -2813,119 +2746,99 @@ static int SSLRegisterPatternsForProtocolDetection(void) } /** SSLv3 */ - if (AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_TLS, - "|01 03 00|", 3, 0, STREAM_TOSERVER) < 0) - { + if (AppLayerProtoDetectPMRegisterPatternCS( + IPPROTO_TCP, ALPROTO_TLS, "|01 03 00|", 3, 0, STREAM_TOSERVER) < 0) { return -1; } - if (AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_TLS, - "|16 03 00|", 3, 0, STREAM_TOSERVER) < 0) - { + if (AppLayerProtoDetectPMRegisterPatternCS( + IPPROTO_TCP, ALPROTO_TLS, "|16 03 00|", 3, 0, STREAM_TOSERVER) < 0) { return -1; } /** TLSv1 */ - if (AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_TLS, - "|01 03 01|", 3, 0, STREAM_TOSERVER) < 0) - { + if (AppLayerProtoDetectPMRegisterPatternCS( + IPPROTO_TCP, ALPROTO_TLS, "|01 03 01|", 3, 0, STREAM_TOSERVER) < 0) { return -1; } - if (AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_TLS, - "|16 03 01|", 3, 0, STREAM_TOSERVER) < 0) - { + if (AppLayerProtoDetectPMRegisterPatternCS( + IPPROTO_TCP, ALPROTO_TLS, "|16 03 01|", 3, 0, STREAM_TOSERVER) < 0) { return -1; } /** TLSv1.1 */ - if (AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_TLS, - "|01 03 02|", 3, 0, STREAM_TOSERVER) < 0) - { + if (AppLayerProtoDetectPMRegisterPatternCS( + IPPROTO_TCP, ALPROTO_TLS, "|01 03 02|", 3, 0, STREAM_TOSERVER) < 0) { return -1; } - if (AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_TLS, - "|16 03 02|", 3, 0, STREAM_TOSERVER) < 0) - { + if (AppLayerProtoDetectPMRegisterPatternCS( + IPPROTO_TCP, ALPROTO_TLS, "|16 03 02|", 3, 0, STREAM_TOSERVER) < 0) { return -1; } /** TLSv1.2 */ - if (AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_TLS, - "|01 03 03|", 3, 0, STREAM_TOSERVER) < 0) - { + if (AppLayerProtoDetectPMRegisterPatternCS( + IPPROTO_TCP, ALPROTO_TLS, "|01 03 03|", 3, 0, STREAM_TOSERVER) < 0) { return -1; } - if (AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_TLS, - "|16 03 03|", 3, 0, STREAM_TOSERVER) < 0) - { + if (AppLayerProtoDetectPMRegisterPatternCS( + IPPROTO_TCP, ALPROTO_TLS, "|16 03 03|", 3, 0, STREAM_TOSERVER) < 0) { return -1; } /***** toclient direction *****/ - if (AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_TLS, - "|15 03 00|", 3, 0, STREAM_TOCLIENT) < 0) - { + if (AppLayerProtoDetectPMRegisterPatternCS( + IPPROTO_TCP, ALPROTO_TLS, "|15 03 00|", 3, 0, STREAM_TOCLIENT) < 0) { return -1; } - if (AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_TLS, - "|16 03 00|", 3, 0, STREAM_TOCLIENT) < 0) - { + if (AppLayerProtoDetectPMRegisterPatternCS( + IPPROTO_TCP, ALPROTO_TLS, "|16 03 00|", 3, 0, STREAM_TOCLIENT) < 0) { return -1; } - if (AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_TLS, - "|17 03 00|", 3, 0, STREAM_TOCLIENT) < 0) - { + if (AppLayerProtoDetectPMRegisterPatternCS( + IPPROTO_TCP, ALPROTO_TLS, "|17 03 00|", 3, 0, STREAM_TOCLIENT) < 0) { return -1; } /** TLSv1 */ - if (AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_TLS, - "|15 03 01|", 3, 0, STREAM_TOCLIENT) < 0) - { + if (AppLayerProtoDetectPMRegisterPatternCS( + IPPROTO_TCP, ALPROTO_TLS, "|15 03 01|", 3, 0, STREAM_TOCLIENT) < 0) { return -1; } - if (AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_TLS, - "|16 03 01|", 3, 0, STREAM_TOCLIENT) < 0) - { + if (AppLayerProtoDetectPMRegisterPatternCS( + IPPROTO_TCP, ALPROTO_TLS, "|16 03 01|", 3, 0, STREAM_TOCLIENT) < 0) { return -1; } - if (AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_TLS, - "|17 03 01|", 3, 0, STREAM_TOCLIENT) < 0) - { + if (AppLayerProtoDetectPMRegisterPatternCS( + IPPROTO_TCP, ALPROTO_TLS, "|17 03 01|", 3, 0, STREAM_TOCLIENT) < 0) { return -1; } /** TLSv1.1 */ - if (AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_TLS, - "|15 03 02|", 3, 0, STREAM_TOCLIENT) < 0) - { + if (AppLayerProtoDetectPMRegisterPatternCS( + IPPROTO_TCP, ALPROTO_TLS, "|15 03 02|", 3, 0, STREAM_TOCLIENT) < 0) { return -1; } - if (AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_TLS, - "|16 03 02|", 3, 0, STREAM_TOCLIENT) < 0) - { + if (AppLayerProtoDetectPMRegisterPatternCS( + IPPROTO_TCP, ALPROTO_TLS, "|16 03 02|", 3, 0, STREAM_TOCLIENT) < 0) { return -1; } - if (AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_TLS, - "|17 03 02|", 3, 0, STREAM_TOCLIENT) < 0) - { + if (AppLayerProtoDetectPMRegisterPatternCS( + IPPROTO_TCP, ALPROTO_TLS, "|17 03 02|", 3, 0, STREAM_TOCLIENT) < 0) { return -1; } /** TLSv1.2 */ - if (AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_TLS, - "|15 03 03|", 3, 0, STREAM_TOCLIENT) < 0) - { + if (AppLayerProtoDetectPMRegisterPatternCS( + IPPROTO_TCP, ALPROTO_TLS, "|15 03 03|", 3, 0, STREAM_TOCLIENT) < 0) { return -1; } - if (AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_TLS, - "|16 03 03|", 3, 0, STREAM_TOCLIENT) < 0) - { + if (AppLayerProtoDetectPMRegisterPatternCS( + IPPROTO_TCP, ALPROTO_TLS, "|16 03 03|", 3, 0, STREAM_TOCLIENT) < 0) { return -1; } - if (AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_TLS, - "|17 03 03|", 3, 0, STREAM_TOCLIENT) < 0) - { + if (AppLayerProtoDetectPMRegisterPatternCS( + IPPROTO_TCP, ALPROTO_TLS, "|17 03 03|", 3, 0, STREAM_TOCLIENT) < 0) { return -1; } @@ -2966,39 +2879,28 @@ void RegisterSSLParsers(void) return; if (RunmodeIsUnittests()) { - AppLayerProtoDetectPPRegister(IPPROTO_TCP, - "443", - ALPROTO_TLS, - 0, 3, - STREAM_TOSERVER, - SSLProbingParser, NULL); + AppLayerProtoDetectPPRegister( + IPPROTO_TCP, "443", ALPROTO_TLS, 0, 3, STREAM_TOSERVER, SSLProbingParser, NULL); } else { - if (AppLayerProtoDetectPPParseConfPorts("tcp", IPPROTO_TCP, - proto_name, ALPROTO_TLS, - 0, 3, - SSLProbingParser, NULL) == 0) { + if (AppLayerProtoDetectPPParseConfPorts("tcp", IPPROTO_TCP, proto_name, ALPROTO_TLS, 0, + 3, SSLProbingParser, NULL) == 0) { SCLogConfig("no TLS config found, " "enabling TLS detection on port 443."); - AppLayerProtoDetectPPRegister(IPPROTO_TCP, - "443", - ALPROTO_TLS, - 0, 3, - STREAM_TOSERVER, - SSLProbingParser, NULL); + AppLayerProtoDetectPPRegister(IPPROTO_TCP, "443", ALPROTO_TLS, 0, 3, + STREAM_TOSERVER, SSLProbingParser, NULL); } } } else { - SCLogConfig("Protocol detection and parser disabled for %s protocol", - proto_name); + SCLogConfig("Protocol detection and parser disabled for %s protocol", proto_name); return; } if (AppLayerParserConfParserEnabled("tcp", proto_name)) { - AppLayerParserRegisterParser(IPPROTO_TCP, ALPROTO_TLS, STREAM_TOSERVER, - SSLParseClientRecord); + AppLayerParserRegisterParser( + IPPROTO_TCP, ALPROTO_TLS, STREAM_TOSERVER, SSLParseClientRecord); - AppLayerParserRegisterParser(IPPROTO_TCP, ALPROTO_TLS, STREAM_TOCLIENT, - SSLParseServerRecord); + AppLayerParserRegisterParser( + IPPROTO_TCP, ALPROTO_TLS, STREAM_TOCLIENT, SSLParseServerRecord); AppLayerParserRegisterGetFrameFuncs( IPPROTO_TCP, ALPROTO_TLS, SSLStateGetFrameIdByName, SSLStateGetFrameNameById); @@ -3007,7 +2909,8 @@ void RegisterSSLParsers(void) AppLayerParserRegisterStateFuncs(IPPROTO_TCP, ALPROTO_TLS, SSLStateAlloc, SSLStateFree); - AppLayerParserRegisterParserAcceptableDataDirection(IPPROTO_TCP, ALPROTO_TLS, STREAM_TOSERVER); + AppLayerParserRegisterParserAcceptableDataDirection( + IPPROTO_TCP, ALPROTO_TLS, STREAM_TOSERVER); AppLayerParserRegisterTxFreeFunc(IPPROTO_TCP, ALPROTO_TLS, SSLStateTransactionFree); @@ -3075,7 +2978,8 @@ void RegisterSSLParsers(void) } } else { SCLogConfig("Parsed disabled for %s protocol. Protocol detection" - "still on.", proto_name); + "still on.", + proto_name); } return; diff --git a/src/app-layer-ssl.h b/src/app-layer-ssl.h index f2e42622308e..761db5a49b10 100644 --- a/src/app-layer-ssl.h +++ b/src/app-layer-ssl.h @@ -81,50 +81,50 @@ enum { }; /* Flag to indicate that server will now on send encrypted msgs */ -#define SSL_AL_FLAG_SERVER_CHANGE_CIPHER_SPEC BIT_U32(0) +#define SSL_AL_FLAG_SERVER_CHANGE_CIPHER_SPEC BIT_U32(0) /* Flag to indicate that client will now on send encrypted msgs */ -#define SSL_AL_FLAG_CLIENT_CHANGE_CIPHER_SPEC BIT_U32(1) -#define SSL_AL_FLAG_CHANGE_CIPHER_SPEC BIT_U32(2) +#define SSL_AL_FLAG_CLIENT_CHANGE_CIPHER_SPEC BIT_U32(1) +#define SSL_AL_FLAG_CHANGE_CIPHER_SPEC BIT_U32(2) /* SSL related flags */ -#define SSL_AL_FLAG_SSL_CLIENT_HS BIT_U32(3) -#define SSL_AL_FLAG_SSL_SERVER_HS BIT_U32(4) -#define SSL_AL_FLAG_SSL_CLIENT_MASTER_KEY BIT_U32(5) -#define SSL_AL_FLAG_SSL_CLIENT_SSN_ENCRYPTED BIT_U32(6) -#define SSL_AL_FLAG_SSL_SERVER_SSN_ENCRYPTED BIT_U32(7) -#define SSL_AL_FLAG_SSL_NO_SESSION_ID BIT_U32(8) +#define SSL_AL_FLAG_SSL_CLIENT_HS BIT_U32(3) +#define SSL_AL_FLAG_SSL_SERVER_HS BIT_U32(4) +#define SSL_AL_FLAG_SSL_CLIENT_MASTER_KEY BIT_U32(5) +#define SSL_AL_FLAG_SSL_CLIENT_SSN_ENCRYPTED BIT_U32(6) +#define SSL_AL_FLAG_SSL_SERVER_SSN_ENCRYPTED BIT_U32(7) +#define SSL_AL_FLAG_SSL_NO_SESSION_ID BIT_U32(8) /* flags specific to detect-ssl-state keyword */ -#define SSL_AL_FLAG_STATE_CLIENT_HELLO BIT_U32(9) -#define SSL_AL_FLAG_STATE_SERVER_HELLO BIT_U32(10) -#define SSL_AL_FLAG_STATE_CLIENT_KEYX BIT_U32(11) -#define SSL_AL_FLAG_STATE_SERVER_KEYX BIT_U32(12) -#define SSL_AL_FLAG_STATE_UNKNOWN BIT_U32(13) +#define SSL_AL_FLAG_STATE_CLIENT_HELLO BIT_U32(9) +#define SSL_AL_FLAG_STATE_SERVER_HELLO BIT_U32(10) +#define SSL_AL_FLAG_STATE_CLIENT_KEYX BIT_U32(11) +#define SSL_AL_FLAG_STATE_SERVER_KEYX BIT_U32(12) +#define SSL_AL_FLAG_STATE_UNKNOWN BIT_U32(13) /* flag to indicate that session is finished */ -#define SSL_AL_FLAG_STATE_FINISHED BIT_U32(14) +#define SSL_AL_FLAG_STATE_FINISHED BIT_U32(14) /* flags specific to HeartBeat state */ -#define SSL_AL_FLAG_HB_INFLIGHT BIT_U32(15) -#define SSL_AL_FLAG_HB_CLIENT_INIT BIT_U32(16) -#define SSL_AL_FLAG_HB_SERVER_INIT BIT_U32(17) +#define SSL_AL_FLAG_HB_INFLIGHT BIT_U32(15) +#define SSL_AL_FLAG_HB_CLIENT_INIT BIT_U32(16) +#define SSL_AL_FLAG_HB_SERVER_INIT BIT_U32(17) /* flag to indicate that handshake is done */ -#define SSL_AL_FLAG_HANDSHAKE_DONE BIT_U32(18) +#define SSL_AL_FLAG_HANDSHAKE_DONE BIT_U32(18) /* Session resumed without a full handshake */ -#define SSL_AL_FLAG_SESSION_RESUMED BIT_U32(20) +#define SSL_AL_FLAG_SESSION_RESUMED BIT_U32(20) /* Encountered a supported_versions extension in client hello */ -#define SSL_AL_FLAG_CH_VERSION_EXTENSION BIT_U32(21) +#define SSL_AL_FLAG_CH_VERSION_EXTENSION BIT_U32(21) /* Log the session even without ever seeing a certificate. This is used to log TLSv1.3 sessions. */ -#define SSL_AL_FLAG_LOG_WITHOUT_CERT BIT_U32(22) +#define SSL_AL_FLAG_LOG_WITHOUT_CERT BIT_U32(22) /* Encountered a early data extension in client hello. This extension is used by 0-RTT. */ -#define SSL_AL_FLAG_EARLY_DATA BIT_U32(23) +#define SSL_AL_FLAG_EARLY_DATA BIT_U32(23) /* flag to indicate that server random was filled */ #define TLS_TS_RANDOM_SET BIT_U32(24) @@ -135,18 +135,18 @@ enum { #define SSL_AL_FLAG_NEED_CLIENT_CERT BIT_U32(26) /* config flags */ -#define SSL_TLS_LOG_PEM (1 << 0) +#define SSL_TLS_LOG_PEM (1 << 0) /* extensions */ -#define SSL_EXTENSION_SNI 0x0000 -#define SSL_EXTENSION_ELLIPTIC_CURVES 0x000a -#define SSL_EXTENSION_EC_POINT_FORMATS 0x000b -#define SSL_EXTENSION_SESSION_TICKET 0x0023 -#define SSL_EXTENSION_EARLY_DATA 0x002a -#define SSL_EXTENSION_SUPPORTED_VERSIONS 0x002b +#define SSL_EXTENSION_SNI 0x0000 +#define SSL_EXTENSION_ELLIPTIC_CURVES 0x000a +#define SSL_EXTENSION_EC_POINT_FORMATS 0x000b +#define SSL_EXTENSION_SESSION_TICKET 0x0023 +#define SSL_EXTENSION_EARLY_DATA 0x002a +#define SSL_EXTENSION_SUPPORTED_VERSIONS 0x002b /* SNI types */ -#define SSL_SNI_TYPE_HOST_NAME 0 +#define SSL_SNI_TYPE_HOST_NAME 0 /* Max string length of the TLS version string */ #define SSL_VERSION_MAX_STRLEN 20 @@ -224,7 +224,6 @@ typedef struct SSLCertsChain_ { TAILQ_ENTRY(SSLCertsChain_) next; } SSLCertsChain; - typedef struct SSLStateConnp_ { /* record length */ uint32_t record_length; diff --git a/src/app-layer-tftp.c b/src/app-layer-tftp.c index 73dc52a59eac..95fcb319d75f 100644 --- a/src/app-layer-tftp.c +++ b/src/app-layer-tftp.c @@ -24,7 +24,6 @@ * Parser for NTP application layer running on UDP port 69. */ - #include "suricata-common.h" #include "suricata.h" #include "stream.h" @@ -67,8 +66,8 @@ static void TFTPStateTxFree(void *state, uint64_t tx_id) rs_tftp_state_tx_free(state, tx_id); } -static int TFTPStateGetEventInfo(const char *event_name, int *event_id, - AppLayerEventType *event_type) +static int TFTPStateGetEventInfo( + const char *event_name, int *event_id, AppLayerEventType *event_type) { return -1; } @@ -79,8 +78,8 @@ static int TFTPStateGetEventInfo(const char *event_name, int *event_id, * \retval ALPROTO_TFTP if it looks like tftp, otherwise * ALPROTO_UNKNOWN. */ -static AppProto TFTPProbingParser(Flow *f, uint8_t direction, - const uint8_t *input, uint32_t input_len, uint8_t *rdir) +static AppProto TFTPProbingParser( + Flow *f, uint8_t direction, const uint8_t *input, uint32_t input_len, uint8_t *rdir) { /* Very simple test - if there is input, this is tftp. * Also check if it's starting by a zero */ @@ -103,7 +102,7 @@ static AppLayerResult TFTPParseRequest(Flow *f, void *state, AppLayerParserState /* Likely connection closed, we can just return here. */ if ((input == NULL || input_len == 0) && - AppLayerParserStateIssetFlag(pstate, APP_LAYER_PARSER_EOF_TS)) { + AppLayerParserStateIssetFlag(pstate, APP_LAYER_PARSER_EOF_TS)) { SCReturnStruct(APP_LAYER_OK); } @@ -171,23 +170,16 @@ void RegisterTFTPParsers(void) if (RunmodeIsUnittests()) { SCLogDebug("Unittest mode, registering default configuration."); - AppLayerProtoDetectPPRegister(IPPROTO_UDP, TFTP_DEFAULT_PORT, - ALPROTO_TFTP, 0, TFTP_MIN_FRAME_LEN, - STREAM_TOSERVER, TFTPProbingParser, - TFTPProbingParser); + AppLayerProtoDetectPPRegister(IPPROTO_UDP, TFTP_DEFAULT_PORT, ALPROTO_TFTP, 0, + TFTP_MIN_FRAME_LEN, STREAM_TOSERVER, TFTPProbingParser, TFTPProbingParser); } else { - if (!AppLayerProtoDetectPPParseConfPorts("udp", IPPROTO_UDP, - proto_name, ALPROTO_TFTP, - 0, TFTP_MIN_FRAME_LEN, - TFTPProbingParser, TFTPProbingParser)) { + if (!AppLayerProtoDetectPPParseConfPorts("udp", IPPROTO_UDP, proto_name, ALPROTO_TFTP, + 0, TFTP_MIN_FRAME_LEN, TFTPProbingParser, TFTPProbingParser)) { SCLogDebug("No tftp app-layer configuration, enabling tftp" " detection UDP detection on port %s.", TFTP_DEFAULT_PORT); - AppLayerProtoDetectPPRegister(IPPROTO_UDP, - TFTP_DEFAULT_PORT, ALPROTO_TFTP, - 0, TFTP_MIN_FRAME_LEN, - STREAM_TOSERVER,TFTPProbingParser, - TFTPProbingParser); + AppLayerProtoDetectPPRegister(IPPROTO_UDP, TFTP_DEFAULT_PORT, ALPROTO_TFTP, 0, + TFTP_MIN_FRAME_LEN, STREAM_TOSERVER, TFTPProbingParser, TFTPProbingParser); } } } else { @@ -201,42 +193,31 @@ void RegisterTFTPParsers(void) /* Register functions for state allocation and freeing. A * state is allocated for every new TFTP flow. */ - AppLayerParserRegisterStateFuncs(IPPROTO_UDP, ALPROTO_TFTP, - TFTPStateAlloc, TFTPStateFree); + AppLayerParserRegisterStateFuncs(IPPROTO_UDP, ALPROTO_TFTP, TFTPStateAlloc, TFTPStateFree); /* Register request parser for parsing frame from server to client. */ - AppLayerParserRegisterParser(IPPROTO_UDP, ALPROTO_TFTP, - STREAM_TOSERVER, TFTPParseRequest); + AppLayerParserRegisterParser(IPPROTO_UDP, ALPROTO_TFTP, STREAM_TOSERVER, TFTPParseRequest); /* Register response parser for parsing frames from server to client. */ - AppLayerParserRegisterParser(IPPROTO_UDP, ALPROTO_TFTP, - STREAM_TOCLIENT, TFTPParseResponse); + AppLayerParserRegisterParser(IPPROTO_UDP, ALPROTO_TFTP, STREAM_TOCLIENT, TFTPParseResponse); /* Register a function to be called by the application layer * when a transaction is to be freed. */ - AppLayerParserRegisterTxFreeFunc(IPPROTO_UDP, ALPROTO_TFTP, - TFTPStateTxFree); + AppLayerParserRegisterTxFreeFunc(IPPROTO_UDP, ALPROTO_TFTP, TFTPStateTxFree); /* Register a function to return the current transaction count. */ - AppLayerParserRegisterGetTxCnt(IPPROTO_UDP, ALPROTO_TFTP, - TFTPGetTxCnt); + AppLayerParserRegisterGetTxCnt(IPPROTO_UDP, ALPROTO_TFTP, TFTPGetTxCnt); /* Transaction handling. */ AppLayerParserRegisterStateProgressCompletionStatus(ALPROTO_TFTP, 1, 1); - AppLayerParserRegisterGetStateProgressFunc(IPPROTO_UDP, - ALPROTO_TFTP, - TFTPGetStateProgress); - AppLayerParserRegisterGetTx(IPPROTO_UDP, ALPROTO_TFTP, - TFTPGetTx); + AppLayerParserRegisterGetStateProgressFunc(IPPROTO_UDP, ALPROTO_TFTP, TFTPGetStateProgress); + AppLayerParserRegisterGetTx(IPPROTO_UDP, ALPROTO_TFTP, TFTPGetTx); - AppLayerParserRegisterGetEventInfo(IPPROTO_UDP, ALPROTO_TFTP, - TFTPStateGetEventInfo); + AppLayerParserRegisterGetEventInfo(IPPROTO_UDP, ALPROTO_TFTP, TFTPStateGetEventInfo); - AppLayerParserRegisterTxDataFunc(IPPROTO_UDP, ALPROTO_TFTP, - rs_tftp_get_tx_data); + AppLayerParserRegisterTxDataFunc(IPPROTO_UDP, ALPROTO_TFTP, rs_tftp_get_tx_data); AppLayerParserRegisterStateDataFunc(IPPROTO_UDP, ALPROTO_TFTP, rs_tftp_get_state_data); - } - else { + } else { SCLogDebug("TFTP protocol parsing disabled."); } } diff --git a/src/app-layer-tftp.h b/src/app-layer-tftp.h index 65dd8f4c9bbd..15bad2b2e03c 100644 --- a/src/app-layer-tftp.h +++ b/src/app-layer-tftp.h @@ -28,6 +28,6 @@ void RegisterTFTPParsers(void); /** Opaque Rust types. */ typedef struct TFTPState_ TFTPState; -typedef struct TFTPTransaction_ TFTPTransaction; +typedef struct TFTPTransaction_ TFTPTransaction; #endif /* __APP_LAYER_TFTP_H__ */ diff --git a/src/app-layer.c b/src/app-layer.c index 57e02ae4c876..ad8e85a77382 100644 --- a/src/app-layer.c +++ b/src/app-layer.c @@ -101,7 +101,8 @@ void AppLayerDeSetupCounters(void); /***** L7 layer dispatchers *****/ -static inline int ProtoDetectDone(const Flow *f, const TcpSession *ssn, uint8_t direction) { +static inline int ProtoDetectDone(const Flow *f, const TcpSession *ssn, uint8_t direction) +{ const TcpStream *stream = (direction & STREAM_TOSERVER) ? &ssn->client : &ssn->server; return ((stream->flags & STREAMTCP_STREAM_FLAG_APPPROTO_DETECTION_COMPLETED) || (FLOW_IS_PM_DONE(f, direction) && FLOW_IS_PP_DONE(f, direction))); @@ -194,8 +195,8 @@ static inline void FlagPacketFlow(Packet *p, Flow *f, uint8_t flags) static void DisableAppLayer(ThreadVars *tv, Flow *f, Packet *p) { - SCLogDebug("disable app layer for flow %p alproto %u ts %u tc %u", - f, f->alproto, f->alproto_ts, f->alproto_tc); + SCLogDebug("disable app layer for flow %p alproto %u ts %u tc %u", f, f->alproto, f->alproto_ts, + f->alproto_tc); FlowCleanupAppLayer(f); StreamTcpDisableAppLayer(f); TcpSession *ssn = f->protoctx; @@ -215,8 +216,8 @@ static void DisableAppLayer(ThreadVars *tv, Flow *f, Packet *p) } FlagPacketFlow(p, f, STREAM_TOSERVER); } - SCLogDebug("disabled app layer for flow %p alproto %u ts %u tc %u", - f, f->alproto, f->alproto_ts, f->alproto_tc); + SCLogDebug("disabled app layer for flow %p alproto %u ts %u tc %u", f, f->alproto, + f->alproto_ts, f->alproto_tc); } /* See if we're going to have to give up: @@ -238,8 +239,7 @@ static void DisableAppLayer(ThreadVars *tv, Flow *f, Packet *p) * * Giving up means we disable applayer an set an applayer event */ -static void TCPProtoDetectCheckBailConditions(ThreadVars *tv, - Flow *f, TcpSession *ssn, Packet *p) +static void TCPProtoDetectCheckBailConditions(ThreadVars *tv, Flow *f, TcpSession *ssn, Packet *p) { if (ssn->state < TCP_ESTABLISHED) { SCLogDebug("skip as long as TCP is not ESTABLISHED (TCP fast open)"); @@ -257,9 +257,7 @@ static void TCPProtoDetectCheckBailConditions(ThreadVars *tv, const uint32_t size_ts_limit = MAX(100000, MIN(ssn->server.window, stream_config.reassembly_depth)); - if (ProtoDetectDone(f, ssn, STREAM_TOSERVER) && - ProtoDetectDone(f, ssn, STREAM_TOCLIENT)) - { + if (ProtoDetectDone(f, ssn, STREAM_TOSERVER) && ProtoDetectDone(f, ssn, STREAM_TOCLIENT)) { goto failure; /* we bail out whatever the pp and pm states if @@ -270,34 +268,30 @@ static void TCPProtoDetectCheckBailConditions(ThreadVars *tv, } else if (FLOW_IS_PM_DONE(f, STREAM_TOSERVER) && FLOW_IS_PP_DONE(f, STREAM_TOSERVER) && size_ts > size_ts_limit && size_tc == 0) { - AppLayerDecoderEventsSetEventRaw(&p->app_layer_events, - APPLAYER_PROTO_DETECTION_SKIPPED); + AppLayerDecoderEventsSetEventRaw(&p->app_layer_events, APPLAYER_PROTO_DETECTION_SKIPPED); goto failure; } else if (FLOW_IS_PM_DONE(f, STREAM_TOCLIENT) && FLOW_IS_PP_DONE(f, STREAM_TOCLIENT) && size_tc > size_tc_limit && size_ts == 0) { - AppLayerDecoderEventsSetEventRaw(&p->app_layer_events, - APPLAYER_PROTO_DETECTION_SKIPPED); + AppLayerDecoderEventsSetEventRaw(&p->app_layer_events, APPLAYER_PROTO_DETECTION_SKIPPED); goto failure; - /* little data in ts direction, pp done, pm not done (max - * depth not reached), ts direction done, lots of data in - * tc direction. */ + /* little data in ts direction, pp done, pm not done (max + * depth not reached), ts direction done, lots of data in + * tc direction. */ } else if (size_tc > size_tc_limit && FLOW_IS_PP_DONE(f, STREAM_TOSERVER) && !(FLOW_IS_PM_DONE(f, STREAM_TOSERVER)) && FLOW_IS_PM_DONE(f, STREAM_TOCLIENT) && FLOW_IS_PP_DONE(f, STREAM_TOCLIENT)) { - AppLayerDecoderEventsSetEventRaw(&p->app_layer_events, - APPLAYER_PROTO_DETECTION_SKIPPED); + AppLayerDecoderEventsSetEventRaw(&p->app_layer_events, APPLAYER_PROTO_DETECTION_SKIPPED); goto failure; - /* little data in tc direction, pp done, pm not done (max - * depth not reached), tc direction done, lots of data in - * ts direction. */ + /* little data in tc direction, pp done, pm not done (max + * depth not reached), tc direction done, lots of data in + * ts direction. */ } else if (size_ts > size_ts_limit && FLOW_IS_PP_DONE(f, STREAM_TOCLIENT) && !(FLOW_IS_PM_DONE(f, STREAM_TOCLIENT)) && FLOW_IS_PM_DONE(f, STREAM_TOSERVER) && FLOW_IS_PP_DONE(f, STREAM_TOSERVER)) { - AppLayerDecoderEventsSetEventRaw(&p->app_layer_events, - APPLAYER_PROTO_DETECTION_SKIPPED); + AppLayerDecoderEventsSetEventRaw(&p->app_layer_events, APPLAYER_PROTO_DETECTION_SKIPPED); goto failure; } return; @@ -324,11 +318,8 @@ static int TCPProtoDetectTriggerOpposingSide(ThreadVars *tv, TcpReassemblyThread return -1; } - enum StreamUpdateDir dir = StreamTcpInlineMode() ? - UPDATE_DIR_OPPOSING : - UPDATE_DIR_PACKET; - int ret = StreamTcpReassembleAppLayer(tv, ra_ctx, ssn, - opposing_stream, p, dir); + enum StreamUpdateDir dir = StreamTcpInlineMode() ? UPDATE_DIR_OPPOSING : UPDATE_DIR_PACKET; + int ret = StreamTcpReassembleAppLayer(tv, ra_ctx, ssn, opposing_stream, p, dir); return ret; } @@ -368,16 +359,15 @@ static int TCPProtoDetect(ThreadVars *tv, TcpReassemblyThreadCtx *ra_ctx, bool reverse_flow = false; DEBUG_VALIDATE_BUG_ON(data == NULL && data_len > 0); PACKET_PROFILING_APP_PD_START(app_tctx); - *alproto = AppLayerProtoDetectGetProto(app_tctx->alpd_tctx, - f, data, data_len, - IPPROTO_TCP, flags, &reverse_flow); + *alproto = AppLayerProtoDetectGetProto( + app_tctx->alpd_tctx, f, data, data_len, IPPROTO_TCP, flags, &reverse_flow); PACKET_PROFILING_APP_PD_END(app_tctx); SCLogDebug("alproto %u rev %s", *alproto, reverse_flow ? "true" : "false"); if (*alproto != ALPROTO_UNKNOWN) { if (*alproto_otherdir != ALPROTO_UNKNOWN && *alproto_otherdir != *alproto) { - AppLayerDecoderEventsSetEventRaw(&p->app_layer_events, - APPLAYER_MISMATCH_PROTOCOL_BOTH_DIRECTIONS); + AppLayerDecoderEventsSetEventRaw( + &p->app_layer_events, APPLAYER_MISMATCH_PROTOCOL_BOTH_DIRECTIONS); if (ssn->data_first_seen_dir == APP_LAYER_DATA_ALREADY_SENT_TO_APP_LAYER) { /* if we already invoked the parser, we go with that proto */ @@ -395,8 +385,7 @@ static int TCPProtoDetect(ThreadVars *tv, TcpReassemblyThreadCtx *ra_ctx, } StreamTcpSetStreamFlagAppProtoDetectionCompleted(*stream); - TcpSessionSetReassemblyDepth(ssn, - AppLayerParserGetStreamDepth(f)); + TcpSessionSetReassemblyDepth(ssn, AppLayerParserGetStreamDepth(f)); FlagPacketFlow(p, f, flags); /* if protocol detection indicated that we need to reverse @@ -435,14 +424,11 @@ static int TCPProtoDetect(ThreadVars *tv, TcpReassemblyThreadCtx *ra_ctx, * called by the very same StreamReassembly() function that we * will now call shortly for the opposing direction. */ if ((ssn->data_first_seen_dir & (STREAM_TOSERVER | STREAM_TOCLIENT)) && - !(flags & ssn->data_first_seen_dir)) - { - SCLogDebug("protocol %s needs first data in other direction", - AppProtoToString(*alproto)); - - if (TCPProtoDetectTriggerOpposingSide(tv, ra_ctx, - p, ssn, *stream) != 0) - { + !(flags & ssn->data_first_seen_dir)) { + SCLogDebug( + "protocol %s needs first data in other direction", AppProtoToString(*alproto)); + + if (TCPProtoDetectTriggerOpposingSide(tv, ra_ctx, p, ssn, *stream) != 0) { goto detect_error; } if (FlowChangeProto(f)) { @@ -451,8 +437,8 @@ static int TCPProtoDetect(ThreadVars *tv, TcpReassemblyThreadCtx *ra_ctx, * As the second data was recognized as P1, the protocol did not change ! */ FlowUnsetChangeProtoFlag(f); - AppLayerDecoderEventsSetEventRaw(&p->app_layer_events, - APPLAYER_UNEXPECTED_PROTOCOL); + AppLayerDecoderEventsSetEventRaw( + &p->app_layer_events, APPLAYER_UNEXPECTED_PROTOCOL); } } @@ -477,8 +463,8 @@ static int TCPProtoDetect(ThreadVars *tv, TcpReassemblyThreadCtx *ra_ctx, first_data_dir = AppLayerParserGetFirstDataDir(f->proto, f->alproto); if (first_data_dir && !(first_data_dir & ssn->data_first_seen_dir)) { - AppLayerDecoderEventsSetEventRaw(&p->app_layer_events, - APPLAYER_WRONG_DIRECTION_FIRST_DATA); + AppLayerDecoderEventsSetEventRaw( + &p->app_layer_events, APPLAYER_WRONG_DIRECTION_FIRST_DATA); goto detect_error; } /* This can happen if the current direction is not the @@ -503,8 +489,7 @@ static int TCPProtoDetect(ThreadVars *tv, TcpReassemblyThreadCtx *ra_ctx, /* finally, invoke the parser */ PACKET_PROFILING_APP_START(app_tctx, f->alproto); - int r = AppLayerParserParse(tv, app_tctx->alp_tctx, f, f->alproto, - flags, data, data_len); + int r = AppLayerParserParse(tv, app_tctx->alp_tctx, f, f->alproto, flags, data, data_len); PACKET_PROFILING_APP_END(app_tctx, f->alproto); p->app_update_direction = (uint8_t)dir; if (r != 1) { @@ -529,8 +514,7 @@ static int TCPProtoDetect(ThreadVars *tv, TcpReassemblyThreadCtx *ra_ctx, * detection and parsing is possible. So we give up. */ if ((ssn->flags & STREAMTCP_FLAG_MIDSTREAM) && - !(ssn->flags & STREAMTCP_FLAG_MIDSTREAM_SYNACK)) - { + !(ssn->flags & STREAMTCP_FLAG_MIDSTREAM_SYNACK)) { if (FLOW_IS_PM_DONE(f, STREAM_TOSERVER) && FLOW_IS_PP_DONE(f, STREAM_TOSERVER)) { SCLogDebug("midstream end pd %p", ssn); /* midstream and toserver detection failed: give up */ @@ -559,8 +543,7 @@ static int TCPProtoDetect(ThreadVars *tv, TcpReassemblyThreadCtx *ra_ctx, * acceptable direction we error out. */ if ((ssn->data_first_seen_dir != APP_LAYER_DATA_ALREADY_SENT_TO_APP_LAYER) && - (first_data_dir) && !(first_data_dir & flags)) - { + (first_data_dir) && !(first_data_dir & flags)) { goto detect_error; } @@ -576,22 +559,21 @@ static int TCPProtoDetect(ThreadVars *tv, TcpReassemblyThreadCtx *ra_ctx, if (*alproto_otherdir != ALPROTO_FAILED) { PACKET_PROFILING_APP_START(app_tctx, f->alproto); - int r = AppLayerParserParse(tv, app_tctx->alp_tctx, f, - f->alproto, flags, - data, data_len); + int r = AppLayerParserParse( + tv, app_tctx->alp_tctx, f, f->alproto, flags, data, data_len); PACKET_PROFILING_APP_END(app_tctx, f->alproto); p->app_update_direction = (uint8_t)dir; if (r != 1) { StreamTcpUpdateAppLayerProgress(ssn, direction, data_len); } - AppLayerDecoderEventsSetEventRaw(&p->app_layer_events, - APPLAYER_DETECT_PROTOCOL_ONLY_ONE_DIRECTION); - TcpSessionSetReassemblyDepth(ssn, - AppLayerParserGetStreamDepth(f)); + AppLayerDecoderEventsSetEventRaw( + &p->app_layer_events, APPLAYER_DETECT_PROTOCOL_ONLY_ONE_DIRECTION); + TcpSessionSetReassemblyDepth(ssn, AppLayerParserGetStreamDepth(f)); *alproto = *alproto_otherdir; - SCLogDebug("packet %"PRIu64": pd done(us %u them %u), parser called (r==%d), APPLAYER_DETECT_PROTOCOL_ONLY_ONE_DIRECTION set", + SCLogDebug("packet %" PRIu64 ": pd done(us %u them %u), parser called (r==%d), " + "APPLAYER_DETECT_PROTOCOL_ONLY_ONE_DIRECTION set", p->pcap_cnt, *alproto, *alproto_otherdir, r); if (r < 0) { goto parser_error; @@ -685,8 +667,7 @@ int AppLayerHandleTCPData(ThreadVars *tv, TcpReassemblyThreadCtx *ra_ctx, Packet goto failure; } PACKET_PROFILING_APP_START(app_tctx, f->alproto); - r = AppLayerParserParse(tv, app_tctx->alp_tctx, f, f->alproto, - flags, data, data_len); + r = AppLayerParserParse(tv, app_tctx->alp_tctx, f, f->alproto, flags, data, data_len); PACKET_PROFILING_APP_END(app_tctx, f->alproto); p->app_update_direction = (uint8_t)dir; /* ignore parser result for gap */ @@ -740,28 +721,27 @@ int AppLayerHandleTCPData(ThreadVars *tv, TcpReassemblyThreadCtx *ra_ctx, Packet SCLogDebug("proto detect failure"); goto failure; } - SCLogDebug("protocol change, old %s, new %s", - AppProtoToString(f->alproto_orig), AppProtoToString(f->alproto)); + SCLogDebug("protocol change, old %s, new %s", AppProtoToString(f->alproto_orig), + AppProtoToString(f->alproto)); if (f->alproto_expect != ALPROTO_UNKNOWN && f->alproto != ALPROTO_UNKNOWN && f->alproto != f->alproto_expect) { - AppLayerDecoderEventsSetEventRaw(&p->app_layer_events, - APPLAYER_UNEXPECTED_PROTOCOL); + AppLayerDecoderEventsSetEventRaw(&p->app_layer_events, APPLAYER_UNEXPECTED_PROTOCOL); if (f->alproto_expect == ALPROTO_TLS && f->alproto != ALPROTO_TLS) { - AppLayerDecoderEventsSetEventRaw(&p->app_layer_events, - APPLAYER_NO_TLS_AFTER_STARTTLS); - + AppLayerDecoderEventsSetEventRaw( + &p->app_layer_events, APPLAYER_NO_TLS_AFTER_STARTTLS); } } } else { SCLogDebug("stream data (len %" PRIu32 " alproto " - "%"PRIu16" (flow %p)", data_len, f->alproto, f); + "%" PRIu16 " (flow %p)", + data_len, f->alproto, f); #ifdef PRINT if (data_len > 0) { printf("=> Stream Data (app layer) -- start %s%s\n", - flags & STREAM_TOCLIENT ? "toclient" : "", - flags & STREAM_TOSERVER ? "toserver" : ""); + flags & STREAM_TOCLIENT ? "toclient" : "", + flags & STREAM_TOSERVER ? "toserver" : ""); PrintRawDataFp(stdout, data, data_len); printf("=> Stream Data -- end\n"); } @@ -770,8 +750,7 @@ int AppLayerHandleTCPData(ThreadVars *tv, TcpReassemblyThreadCtx *ra_ctx, Packet * a start msg should have gotten us one */ if (f->alproto != ALPROTO_UNKNOWN) { PACKET_PROFILING_APP_START(app_tctx, f->alproto); - r = AppLayerParserParse(tv, app_tctx->alp_tctx, f, f->alproto, - flags, data, data_len); + r = AppLayerParserParse(tv, app_tctx->alp_tctx, f, f->alproto, flags, data, data_len); PACKET_PROFILING_APP_END(app_tctx, f->alproto); p->app_update_direction = (uint8_t)dir; if (r != 1) { @@ -786,9 +765,9 @@ int AppLayerHandleTCPData(ThreadVars *tv, TcpReassemblyThreadCtx *ra_ctx, Packet } goto end; - failure: +failure: r = -1; - end: +end: SCReturnInt(r); } @@ -830,8 +809,7 @@ int AppLayerHandleUdp(ThreadVars *tv, AppLayerThreadCtx *tctx, Packet *p, Flow * /* if the protocol is still unknown, run detection */ if (*alproto == ALPROTO_UNKNOWN) { - SCLogDebug("Detecting AL proto on udp mesg (len %" PRIu32 ")", - p->payload_len); + SCLogDebug("Detecting AL proto on udp mesg (len %" PRIu32 ")", p->payload_len); bool reverse_flow = false; PACKET_PROFILING_APP_PD_START(tctx); @@ -895,8 +873,8 @@ int AppLayerHandleUdp(ThreadVars *tv, AppLayerThreadCtx *tctx, Packet *p, Flow * } PACKET_PROFILING_APP_START(tctx, f->alproto); - r = AppLayerParserParse(tv, tctx->alp_tctx, f, f->alproto, - flags, p->payload, p->payload_len); + r = AppLayerParserParse( + tv, tctx->alp_tctx, f, f->alproto, flags, p->payload, p->payload_len); PACKET_PROFILING_APP_END(tctx, f->alproto); p->app_update_direction = (uint8_t)UPDATE_DIR_PACKET; } @@ -907,12 +885,13 @@ int AppLayerHandleUdp(ThreadVars *tv, AppLayerThreadCtx *tctx, Packet *p, Flow * FlagPacketFlow(p, f, STREAM_TOCLIENT); } else { SCLogDebug("data (len %" PRIu32 " ), alproto " - "%"PRIu16" (flow %p)", p->payload_len, f->alproto, f); + "%" PRIu16 " (flow %p)", + p->payload_len, f->alproto, f); /* run the parser */ PACKET_PROFILING_APP_START(tctx, f->alproto); - r = AppLayerParserParse(tv, tctx->alp_tctx, f, f->alproto, - flags, p->payload, p->payload_len); + r = AppLayerParserParse( + tv, tctx->alp_tctx, f, f->alproto, flags, p->payload, p->payload_len); PACKET_PROFILING_APP_END(tctx, f->alproto); PACKET_PROFILING_APP_STORE(tctx, p); p->app_update_direction = (uint8_t)UPDATE_DIR_PACKET; @@ -937,7 +916,7 @@ AppProto AppLayerGetProtoByName(char *alproto_name) const char *AppLayerGetProtoName(AppProto alproto) { SCEnter(); - const char * r = AppLayerProtoDetectGetProtoName(alproto); + const char *r = AppLayerProtoDetectGetProtoName(alproto); SCReturnCT(r, "char *"); } @@ -1002,10 +981,10 @@ AppLayerThreadCtx *AppLayerGetCtxThread(ThreadVars *tv) goto error; goto done; - error: +error: AppLayerDestroyCtxThread(app_tctx); app_tctx = NULL; - done: +done: SCReturnPtr(app_tctx, "void *"); } @@ -1074,11 +1053,11 @@ void AppLayerSetupCounters(void) if (AppLayerParserProtoIsRegistered(ipproto, alproto) && AppLayerParserProtoIsRegistered(other_ipproto, alproto)) { snprintf(applayer_counter_names[ipproto_map][alproto].name, - sizeof(applayer_counter_names[ipproto_map][alproto].name), - "%s%s%s", str, alproto_str, ipproto_suffix); + sizeof(applayer_counter_names[ipproto_map][alproto].name), "%s%s%s", + str, alproto_str, ipproto_suffix); snprintf(applayer_counter_names[ipproto_map][alproto].tx_name, - sizeof(applayer_counter_names[ipproto_map][alproto].tx_name), - "%s%s%s", tx_str, alproto_str, ipproto_suffix); + sizeof(applayer_counter_names[ipproto_map][alproto].tx_name), "%s%s%s", + tx_str, alproto_str, ipproto_suffix); if (ipproto == IPPROTO_TCP) { snprintf(applayer_counter_names[ipproto_map][alproto].gap_error, @@ -1096,11 +1075,11 @@ void AppLayerSetupCounters(void) "%s%s%s.internal", estr, alproto_str, ipproto_suffix); } else { snprintf(applayer_counter_names[ipproto_map][alproto].name, - sizeof(applayer_counter_names[ipproto_map][alproto].name), - "%s%s", str, alproto_str); + sizeof(applayer_counter_names[ipproto_map][alproto].name), "%s%s", str, + alproto_str); snprintf(applayer_counter_names[ipproto_map][alproto].tx_name, - sizeof(applayer_counter_names[ipproto_map][alproto].tx_name), - "%s%s", tx_str, alproto_str); + sizeof(applayer_counter_names[ipproto_map][alproto].tx_name), "%s%s", + tx_str, alproto_str); if (ipproto == IPPROTO_TCP) { snprintf(applayer_counter_names[ipproto_map][alproto].gap_error, @@ -1119,8 +1098,8 @@ void AppLayerSetupCounters(void) } } else if (alproto == ALPROTO_FAILED) { snprintf(applayer_counter_names[ipproto_map][alproto].name, - sizeof(applayer_counter_names[ipproto_map][alproto].name), - "%s%s%s", str, "failed", ipproto_suffix); + sizeof(applayer_counter_names[ipproto_map][alproto].name), "%s%s%s", str, + "failed", ipproto_suffix); if (ipproto == IPPROTO_TCP) { snprintf(applayer_counter_names[ipproto_map][alproto].gap_error, sizeof(applayer_counter_names[ipproto_map][alproto].gap_error), @@ -1146,10 +1125,10 @@ void AppLayerRegisterThreadCounters(ThreadVars *tv) for (AppProto alproto = 0; alproto < ALPROTO_MAX; alproto++) { if (alprotos[alproto] == 1) { applayer_counters[ipproto_map][alproto].counter_id = - StatsRegisterCounter(applayer_counter_names[ipproto_map][alproto].name, tv); + StatsRegisterCounter(applayer_counter_names[ipproto_map][alproto].name, tv); - applayer_counters[ipproto_map][alproto].counter_tx_id = - StatsRegisterCounter(applayer_counter_names[ipproto_map][alproto].tx_name, tv); + applayer_counters[ipproto_map][alproto].counter_tx_id = StatsRegisterCounter( + applayer_counter_names[ipproto_map][alproto].tx_name, tv); if (ipproto == IPPROTO_TCP) { applayer_counters[ipproto_map][alproto].gap_error_id = StatsRegisterCounter( @@ -1163,7 +1142,7 @@ void AppLayerRegisterThreadCounters(ThreadVars *tv) applayer_counter_names[ipproto_map][alproto].internal_error, tv); } else if (alproto == ALPROTO_FAILED) { applayer_counters[ipproto_map][alproto].counter_id = - StatsRegisterCounter(applayer_counter_names[ipproto_map][alproto].name, tv); + StatsRegisterCounter(applayer_counter_names[ipproto_map][alproto].name, tv); if (ipproto == IPPROTO_TCP) { applayer_counters[ipproto_map][alproto].gap_error_id = StatsRegisterCounter( @@ -1748,7 +1727,7 @@ static int AppLayerTest04(void) FAIL_IF(FLOW_IS_PP_DONE(&f, STREAM_TOSERVER)); FAIL_IF(FLOW_IS_PM_DONE(&f, STREAM_TOCLIENT)); FAIL_IF(FLOW_IS_PP_DONE(&f, STREAM_TOCLIENT)); - FAIL_IF(ssn->data_first_seen_dir != STREAM_TOSERVER); // TOSERVER data now seen + FAIL_IF(ssn->data_first_seen_dir != STREAM_TOSERVER); // TOSERVER data now seen /* partial response */ // clang-format off @@ -1772,7 +1751,8 @@ static int AppLayerTest04(void) FAIL_IF(FLOW_IS_PP_DONE(&f, STREAM_TOSERVER)); FAIL_IF(FLOW_IS_PM_DONE(&f, STREAM_TOCLIENT)); FAIL_IF(FLOW_IS_PP_DONE(&f, STREAM_TOCLIENT)); - FAIL_IF(ssn->data_first_seen_dir != APP_LAYER_DATA_ALREADY_SENT_TO_APP_LAYER); // first data sent to applayer + FAIL_IF(ssn->data_first_seen_dir != + APP_LAYER_DATA_ALREADY_SENT_TO_APP_LAYER); // first data sent to applayer /* partial response ack */ p->tcph->th_ack = htonl(5); @@ -1791,8 +1771,9 @@ static int AppLayerTest04(void) FAIL_IF(!FLOW_IS_PM_DONE(&f, STREAM_TOSERVER)); FAIL_IF(FLOW_IS_PP_DONE(&f, STREAM_TOSERVER)); FAIL_IF(FLOW_IS_PM_DONE(&f, STREAM_TOCLIENT)); - FAIL_IF(!FLOW_IS_PP_DONE(&f, STREAM_TOCLIENT)); // to client pp got nothing - FAIL_IF(ssn->data_first_seen_dir != APP_LAYER_DATA_ALREADY_SENT_TO_APP_LAYER); // first data sent to applayer + FAIL_IF(!FLOW_IS_PP_DONE(&f, STREAM_TOCLIENT)); // to client pp got nothing + FAIL_IF(ssn->data_first_seen_dir != + APP_LAYER_DATA_ALREADY_SENT_TO_APP_LAYER); // first data sent to applayer /* remaining response */ // clang-format off @@ -1856,8 +1837,9 @@ static int AppLayerTest04(void) FAIL_IF(!FLOW_IS_PM_DONE(&f, STREAM_TOSERVER)); FAIL_IF(FLOW_IS_PP_DONE(&f, STREAM_TOSERVER)); FAIL_IF(FLOW_IS_PM_DONE(&f, STREAM_TOCLIENT)); - FAIL_IF(!FLOW_IS_PP_DONE(&f, STREAM_TOCLIENT)); // to client pp got nothing - FAIL_IF(ssn->data_first_seen_dir != APP_LAYER_DATA_ALREADY_SENT_TO_APP_LAYER); // first data sent to applayer + FAIL_IF(!FLOW_IS_PP_DONE(&f, STREAM_TOCLIENT)); // to client pp got nothing + FAIL_IF(ssn->data_first_seen_dir != + APP_LAYER_DATA_ALREADY_SENT_TO_APP_LAYER); // first data sent to applayer /* response ack */ p->tcph->th_ack = htonl(328); @@ -1867,17 +1849,19 @@ static int AppLayerTest04(void) p->payload_len = 0; p->payload = NULL; FAIL_IF(StreamTcpPacket(&tv, p, stt, &pq) == -1); - FAIL_IF(!StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(&ssn->server)); // toclient complete (failed) + FAIL_IF(!StreamTcpIsSetStreamFlagAppProtoDetectionCompleted( + &ssn->server)); // toclient complete (failed) FAIL_IF(!StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(&ssn->client)); // toserver complete FAIL_IF(f.alproto != ALPROTO_HTTP1); // http based on ts FAIL_IF(f.alproto_ts != ALPROTO_HTTP1); // ts complete - FAIL_IF(f.alproto_tc != ALPROTO_FAILED); // tc failed + FAIL_IF(f.alproto_tc != ALPROTO_FAILED); // tc failed FAIL_IF(ssn->flags & STREAMTCP_FLAG_APP_LAYER_DISABLED); FAIL_IF(!FLOW_IS_PM_DONE(&f, STREAM_TOSERVER)); FAIL_IF(FLOW_IS_PP_DONE(&f, STREAM_TOSERVER)); FAIL_IF(!FLOW_IS_PM_DONE(&f, STREAM_TOCLIENT)); - FAIL_IF(!FLOW_IS_PP_DONE(&f, STREAM_TOCLIENT)); // to client pp got nothing - FAIL_IF(ssn->data_first_seen_dir != APP_LAYER_DATA_ALREADY_SENT_TO_APP_LAYER); // first data sent to applayer + FAIL_IF(!FLOW_IS_PP_DONE(&f, STREAM_TOCLIENT)); // to client pp got nothing + FAIL_IF(ssn->data_first_seen_dir != + APP_LAYER_DATA_ALREADY_SENT_TO_APP_LAYER); // first data sent to applayer TEST_END; PASS; diff --git a/src/app-layer.h b/src/app-layer.h index cbe2fbc9af84..9179c13d58e2 100644 --- a/src/app-layer.h +++ b/src/app-layer.h @@ -34,11 +34,9 @@ #include "stream-tcp-private.h" #include "stream-tcp-reassemble.h" - #include "rust.h" -#define APP_LAYER_DATA_ALREADY_SENT_TO_APP_LAYER \ - (~STREAM_TOSERVER & ~STREAM_TOCLIENT) +#define APP_LAYER_DATA_ALREADY_SENT_TO_APP_LAYER (~STREAM_TOSERVER & ~STREAM_TOCLIENT) /***** L7 layer dispatchers *****/ @@ -52,8 +50,7 @@ int AppLayerHandleTCPData(ThreadVars *tv, TcpReassemblyThreadCtx *ra_ctx, Packet /** * \brief Handles an udp chunk. */ -int AppLayerHandleUdp(ThreadVars *tv, AppLayerThreadCtx *app_tctx, - Packet *p, Flow *f); +int AppLayerHandleUdp(ThreadVars *tv, AppLayerThreadCtx *app_tctx, Packet *p, Flow *f); /***** Utility *****/ diff --git a/src/conf-yaml-loader.c b/src/conf-yaml-loader.c index 1bd107e0c1c9..952ff70f33fd 100644 --- a/src/conf-yaml-loader.c +++ b/src/conf-yaml-loader.c @@ -64,8 +64,7 @@ enum conf_state { * * \retval none */ -static void -Mangle(char *string) +static void Mangle(char *string) { char *c; @@ -80,8 +79,7 @@ Mangle(char *string) * * \param filename The configuration filename. */ -static void -ConfYamlSetConfDirname(const char *filename) +static void ConfYamlSetConfDirname(const char *filename) { char *ep; @@ -94,8 +92,7 @@ ConfYamlSetConfDirname(const char *filename) if (conf_dirname == NULL) { FatalError("ERROR: Failed to allocate memory while loading configuration."); } - } - else { + } else { conf_dirname = SCStrdup(filename); if (conf_dirname == NULL) { FatalError("ERROR: Failed to allocate memory while loading configuration."); @@ -127,10 +124,8 @@ int ConfYamlHandleInclude(ConfNode *parent, const char *filename) if (PathIsAbsolute(filename)) { strlcpy(include_filename, filename, sizeof(include_filename)); - } - else { - snprintf(include_filename, sizeof(include_filename), "%s/%s", - conf_dirname, filename); + } else { + snprintf(include_filename, sizeof(include_filename), "%s/%s", conf_dirname, filename); } file = fopen(include_filename, "r"); @@ -196,8 +191,7 @@ static int ConfYamlParse(yaml_parser_t *parser, ConfNode *parent, int inseq, int /* Verify YAML version - its more likely to be a valid * Suricata configuration file if the version is * correct. */ - yaml_version_directive_t *ver = - event.data.document_start.version_directive; + yaml_version_directive_t *ver = event.data.document_start.version_directive; if (ver == NULL) { SCLogError("ERROR: Invalid configuration file."); SCLogError("The configuration file must begin with the following two lines: %%YAML " @@ -210,12 +204,12 @@ static int ConfYamlParse(yaml_parser_t *parser, ConfNode *parent, int inseq, int SCLogError("ERROR: Invalid YAML version. Must be 1.1"); goto fail; } - } - else if (event.type == YAML_SCALAR_EVENT) { + } else if (event.type == YAML_SCALAR_EVENT) { char *value = (char *)event.data.scalar.value; char *tag = (char *)event.data.scalar.tag; SCLogDebug("event.type=YAML_SCALAR_EVENT; state=%d; value=%s; " - "tag=%s; inseq=%d", state, value, tag, inseq); + "tag=%s; inseq=%d", + state, value, tag, inseq); /* Skip over empty scalar values while in KEY state. This * tends to only happen on an empty file, where a scalar @@ -264,8 +258,7 @@ static int ConfYamlParse(yaml_parser_t *parser, ConfNode *parent, int inseq, int * re-added in the expected order for iteration. */ TAILQ_REMOVE(&parent->head, seq_node, next); - } - else { + } else { seq_node = ConfNodeNew(); if (unlikely(seq_node == NULL)) { goto fail; @@ -286,16 +279,14 @@ static int ConfYamlParse(yaml_parser_t *parser, ConfNode *parent, int inseq, int } } TAILQ_INSERT_TAIL(&parent->head, seq_node, next); - } - else { + } else { if (state == CONF_INCLUDE) { SCLogInfo("Including configuration file %s.", value); if (ConfYamlHandleInclude(parent, value) != 0) { goto fail; } state = CONF_KEY; - } - else if (state == CONF_KEY) { + } else if (state == CONF_KEY) { if (strcmp(value, "include") == 0) { state = CONF_INCLUDE; @@ -356,11 +347,11 @@ static int ConfYamlParse(yaml_parser_t *parser, ConfNode *parent, int inseq, int } } state = CONF_VAL; - } - else { + } else { if (value != NULL && (tag != NULL) && (strcmp(tag, "!include") == 0)) { SCLogInfo("Including configuration file %s at " - "parent node %s.", value, node->name); + "parent node %s.", + value, node->name); if (ConfYamlHandleInclude(node, value) != 0) goto fail; } else if (!node->final && value != NULL) { @@ -371,8 +362,7 @@ static int ConfYamlParse(yaml_parser_t *parser, ConfNode *parent, int inseq, int state = CONF_KEY; } } - } - else if (event.type == YAML_SEQUENCE_START_EVENT) { + } else if (event.type == YAML_SEQUENCE_START_EVENT) { SCLogDebug("event.type=YAML_SEQUENCE_START_EVENT; state=%d", state); /* If we're processing a list of includes, use the current parent. */ if (ConfYamlParse(parser, state == CONF_INCLUDE ? parent : node, 1, rlevel, @@ -380,12 +370,10 @@ static int ConfYamlParse(yaml_parser_t *parser, ConfNode *parent, int inseq, int goto fail; node->is_seq = 1; state = CONF_KEY; - } - else if (event.type == YAML_SEQUENCE_END_EVENT) { + } else if (event.type == YAML_SEQUENCE_END_EVENT) { SCLogDebug("event.type=YAML_SEQUENCE_END_EVENT; state=%d", state); done = 1; - } - else if (event.type == YAML_MAPPING_START_EVENT) { + } else if (event.type == YAML_MAPPING_START_EVENT) { SCLogDebug("event.type=YAML_MAPPING_START_EVENT; state=%d", state); if (state == CONF_INCLUDE) { SCLogError("Include fields cannot be a mapping: line %zu", parser->mark.line); @@ -394,16 +382,14 @@ static int ConfYamlParse(yaml_parser_t *parser, ConfNode *parent, int inseq, int if (inseq) { char sequence_node_name[DEFAULT_NAME_LEN]; snprintf(sequence_node_name, DEFAULT_NAME_LEN, "%d", seq_idx++); - ConfNode *seq_node = ConfNodeLookupChild(node, - sequence_node_name); + ConfNode *seq_node = ConfNodeLookupChild(node, sequence_node_name); if (seq_node != NULL) { /* The sequence node has already been set, probably * from the command line. Remove it so it gets * re-added in the expected order for iteration. */ TAILQ_REMOVE(&node->head, seq_node, next); - } - else { + } else { seq_node = ConfNodeNew(); if (unlikely(seq_node == NULL)) { goto fail; @@ -418,18 +404,15 @@ static int ConfYamlParse(yaml_parser_t *parser, ConfNode *parent, int inseq, int TAILQ_INSERT_TAIL(&node->head, seq_node, next); if (ConfYamlParse(parser, seq_node, 0, rlevel, 0) != 0) goto fail; - } - else { + } else { if (ConfYamlParse(parser, node, inseq, rlevel, 0) != 0) goto fail; } state = CONF_KEY; - } - else if (event.type == YAML_MAPPING_END_EVENT) { + } else if (event.type == YAML_MAPPING_END_EVENT) { SCLogDebug("event.type=YAML_MAPPING_END_EVENT; state=%d", state); done = 1; - } - else if (event.type == YAML_STREAM_END_EVENT) { + } else if (event.type == YAML_STREAM_END_EVENT) { SCLogDebug("event.type=YAML_STREAM_END_EVENT; state=%d", state); done = 1; } @@ -460,8 +443,7 @@ static int ConfYamlParse(yaml_parser_t *parser, ConfNode *parent, int inseq, int * * \retval 0 on success, -1 on failure. */ -int -ConfYamlLoadFile(const char *filename) +int ConfYamlLoadFile(const char *filename) { FILE *infile; yaml_parser_t parser; @@ -507,8 +489,7 @@ ConfYamlLoadFile(const char *filename) /** * \brief Load configuration from a YAML string. */ -int -ConfYamlLoadString(const char *string, size_t len) +int ConfYamlLoadString(const char *string, size_t len) { ConfNode *root = ConfGetRootNode(); yaml_parser_t parser; @@ -538,8 +519,7 @@ ConfYamlLoadString(const char *string, size_t len) * * \retval 0 on success, -1 on failure. */ -int -ConfYamlLoadFileWithPrefix(const char *filename, const char *prefix) +int ConfYamlLoadFileWithPrefix(const char *filename, const char *prefix) { FILE *infile; yaml_parser_t parser; @@ -594,8 +574,7 @@ ConfYamlLoadFileWithPrefix(const char *filename, const char *prefix) #ifdef UNITTESTS -static int -ConfYamlSequenceTest(void) +static int ConfYamlSequenceTest(void) { char input[] = "\ %YAML 1.1\n\ @@ -619,13 +598,12 @@ default-log-dir: /tmp\n\ FAIL_IF(TAILQ_EMPTY(&node->head)); int i = 0; ConfNode *filename; - TAILQ_FOREACH(filename, &node->head, next) { + TAILQ_FOREACH (filename, &node->head, next) { if (i == 0) { FAIL_IF(strcmp(filename->val, "netbios.rules") != 0); FAIL_IF(ConfNodeIsSequence(filename)); FAIL_IF(filename->is_seq != 0); - } - else if (i == 1) { + } else if (i == 1) { FAIL_IF(strcmp(filename->val, "x11.rules") != 0); FAIL_IF(ConfNodeIsSequence(filename)); } @@ -638,8 +616,7 @@ default-log-dir: /tmp\n\ PASS; } -static int -ConfYamlLoggingOutputTest(void) +static int ConfYamlLoggingOutputTest(void) { char input[] = "\ %YAML 1.1\n\ @@ -704,8 +681,7 @@ logging:\n\ /** * Try to load something that is not a valid YAML file. */ -static int -ConfYamlNonYamlFileTest(void) +static int ConfYamlNonYamlFileTest(void) { ConfCreateContextBackup(); ConfInit(); @@ -718,8 +694,7 @@ ConfYamlNonYamlFileTest(void) PASS; } -static int -ConfYamlBadYamlVersionTest(void) +static int ConfYamlBadYamlVersionTest(void) { char input[] = "\ %YAML 9.9\n\ @@ -744,8 +719,7 @@ logging:\n\ PASS; } -static int -ConfYamlSecondLevelSequenceTest(void) +static int ConfYamlSecondLevelSequenceTest(void) { char input[] = "\ %YAML 1.1\n\ @@ -804,27 +778,24 @@ libhtp:\n\ /** * Test file inclusion support. */ -static int -ConfYamlFileIncludeTest(void) +static int ConfYamlFileIncludeTest(void) { FILE *config_file; const char config_filename[] = "ConfYamlFileIncludeTest-config.yaml"; - const char config_file_contents[] = - "%YAML 1.1\n" - "---\n" - "# Include something at the root level.\n" - "include: ConfYamlFileIncludeTest-include.yaml\n" - "# Test including under a mapping.\n" - "mapping: !include ConfYamlFileIncludeTest-include.yaml\n"; + const char config_file_contents[] = "%YAML 1.1\n" + "---\n" + "# Include something at the root level.\n" + "include: ConfYamlFileIncludeTest-include.yaml\n" + "# Test including under a mapping.\n" + "mapping: !include ConfYamlFileIncludeTest-include.yaml\n"; const char include_filename[] = "ConfYamlFileIncludeTest-include.yaml"; - const char include_file_contents[] = - "%YAML 1.1\n" - "---\n" - "host-mode: auto\n" - "unix-command:\n" - " enabled: no\n"; + const char include_file_contents[] = "%YAML 1.1\n" + "---\n" + "host-mode: auto\n" + "unix-command:\n" + " enabled: no\n"; ConfCreateContextBackup(); ConfInit(); @@ -879,8 +850,7 @@ ConfYamlFileIncludeTest(void) * Test that a configuration section is overridden but subsequent * occurrences. */ -static int -ConfYamlOverrideTest(void) +static int ConfYamlOverrideTest(void) { char config[] = "%YAML 1.1\n" "---\n" @@ -940,16 +910,14 @@ ConfYamlOverrideTest(void) * Test that a configuration parameter loaded from YAML doesn't * override a 'final' value that may be set on the command line. */ -static int -ConfYamlOverrideFinalTest(void) +static int ConfYamlOverrideFinalTest(void) { ConfCreateContextBackup(); ConfInit(); - char config[] = - "%YAML 1.1\n" - "---\n" - "default-log-dir: /var/log\n"; + char config[] = "%YAML 1.1\n" + "---\n" + "default-log-dir: /var/log\n"; /* Set the log directory as if it was set on the command line. */ FAIL_IF_NOT(ConfSetFinal("default-log-dir", "/tmp")); @@ -1041,16 +1009,14 @@ static int ConfYamlNull(void) #endif /* UNITTESTS */ -void -ConfYamlRegisterTests(void) +void ConfYamlRegisterTests(void) { #ifdef UNITTESTS UtRegisterTest("ConfYamlSequenceTest", ConfYamlSequenceTest); UtRegisterTest("ConfYamlLoggingOutputTest", ConfYamlLoggingOutputTest); UtRegisterTest("ConfYamlNonYamlFileTest", ConfYamlNonYamlFileTest); UtRegisterTest("ConfYamlBadYamlVersionTest", ConfYamlBadYamlVersionTest); - UtRegisterTest("ConfYamlSecondLevelSequenceTest", - ConfYamlSecondLevelSequenceTest); + UtRegisterTest("ConfYamlSecondLevelSequenceTest", ConfYamlSecondLevelSequenceTest); UtRegisterTest("ConfYamlFileIncludeTest", ConfYamlFileIncludeTest); UtRegisterTest("ConfYamlOverrideTest", ConfYamlOverrideTest); UtRegisterTest("ConfYamlOverrideFinalTest", ConfYamlOverrideFinalTest); diff --git a/src/conf.c b/src/conf.c index f2bf978e8c25..42ce1b1ed6ba 100644 --- a/src/conf.c +++ b/src/conf.c @@ -271,8 +271,7 @@ int ConfSetFromString(const char *input, int final) if (!ConfSetFinal(name, val)) { goto done; } - } - else { + } else { if (!ConfSet(name, val)) { goto done; } @@ -338,8 +337,7 @@ int ConfGet(const char *name, const char **vptr) if (node == NULL) { SCLogDebug("failed to lookup configuration parameter '%s'", name); return 0; - } - else { + } else { *vptr = node->val; return 1; } @@ -352,8 +350,7 @@ int ConfGetChildValue(const ConfNode *base, const char *name, const char **vptr) if (node == NULL) { SCLogDebug("failed to lookup configuration parameter '%s'", name); return 0; - } - else { + } else { if (node->val == NULL) return 0; *vptr = node->val; @@ -361,8 +358,7 @@ int ConfGetChildValue(const ConfNode *base, const char *name, const char **vptr) } } -ConfNode *ConfGetChildWithDefault(const ConfNode *base, const ConfNode *dflt, - const char *name) +ConfNode *ConfGetChildWithDefault(const ConfNode *base, const ConfNode *dflt, const char *name) { ConfNode *node = ConfNodeLookupChild(base, name); if (node != NULL) @@ -375,8 +371,8 @@ ConfNode *ConfGetChildWithDefault(const ConfNode *base, const ConfNode *dflt, return NULL; } -int ConfGetChildValueWithDefault(const ConfNode *base, const ConfNode *dflt, - const char *name, const char **vptr) +int ConfGetChildValueWithDefault( + const ConfNode *base, const ConfNode *dflt, const char *name, const char **vptr) { int ret = ConfGetChildValue(base, name, vptr); /* Get 'default' value */ @@ -456,11 +452,10 @@ int ConfGetChildValueInt(const ConfNode *base, const char *name, intmax_t *val) *val = tmpint; return 1; - } -int ConfGetChildValueIntWithDefault(const ConfNode *base, const ConfNode *dflt, - const char *name, intmax_t *val) +int ConfGetChildValueIntWithDefault( + const ConfNode *base, const ConfNode *dflt, const char *name, intmax_t *val) { int ret = ConfGetChildValueInt(base, name, val); /* Get 'default' value */ @@ -511,8 +506,8 @@ int ConfGetChildValueBool(const ConfNode *base, const char *name, int *val) return 1; } -int ConfGetChildValueBoolWithDefault(const ConfNode *base, const ConfNode *dflt, - const char *name, int *val) +int ConfGetChildValueBoolWithDefault( + const ConfNode *base, const ConfNode *dflt, const char *name, int *val) { int ret = ConfGetChildValueBool(base, name, val); /* Get 'default' value */ @@ -522,7 +517,6 @@ int ConfGetChildValueBoolWithDefault(const ConfNode *base, const ConfNode *dflt, return ret; } - /** * \brief Check if a value is true. * @@ -536,7 +530,7 @@ int ConfGetChildValueBoolWithDefault(const ConfNode *base, const ConfNode *dflt, */ int ConfValIsTrue(const char *val) { - const char *trues[] = {"1", "yes", "true", "on"}; + const char *trues[] = { "1", "yes", "true", "on" }; size_t u; for (u = 0; u < sizeof(trues) / sizeof(trues[0]); u++) { @@ -561,7 +555,7 @@ int ConfValIsTrue(const char *val) */ int ConfValIsFalse(const char *val) { - const char *falses[] = {"0", "no", "false", "off"}; + const char *falses[] = { "0", "no", "false", "off" }; size_t u; for (u = 0; u < sizeof(falses) / sizeof(falses[0]); u++) { @@ -702,7 +696,7 @@ void ConfDeInit(void) static char *ConfPrintNameArray(char **name_arr, int level) { - static char name[128*128]; + static char name[128 * 128]; int i; name[0] = '\0'; @@ -726,18 +720,15 @@ void ConfNodeDump(const ConfNode *node, const char *prefix) static int level = -1; level++; - TAILQ_FOREACH(child, &node->head, next) { + TAILQ_FOREACH (child, &node->head, next) { name[level] = SCStrdup(child->name); if (unlikely(name[level] == NULL)) { continue; } if (prefix == NULL) { - printf("%s = %s\n", ConfPrintNameArray(name, level), - child->val); - } - else { - printf("%s.%s = %s\n", prefix, - ConfPrintNameArray(name, level), child->val); + printf("%s = %s\n", ConfPrintNameArray(name, level), child->val); + } else { + printf("%s.%s = %s\n", prefix, ConfPrintNameArray(name, level), child->val); } ConfNodeDump(child, prefix); SCFree(name[level]); @@ -791,7 +782,7 @@ ConfNode *ConfNodeLookupChild(const ConfNode *node, const char *name) return NULL; } - TAILQ_FOREACH(child, &node->head, next) { + TAILQ_FOREACH (child, &node->head, next) { if (child->name != NULL && strcmp(child->name, name) == 0) return child; } @@ -828,15 +819,14 @@ const char *ConfNodeLookupChildValue(const ConfNode *node, const char *name) * \return the ConfNode matching or NULL */ -ConfNode *ConfNodeLookupKeyValue(const ConfNode *base, const char *key, - const char *value) +ConfNode *ConfNodeLookupKeyValue(const ConfNode *base, const char *key, const char *value) { ConfNode *child; - TAILQ_FOREACH(child, &base->head, next) { + TAILQ_FOREACH (child, &base->head, next) { if (!strncmp(child->val, key, strlen(child->val))) { ConfNode *subchild; - TAILQ_FOREACH(subchild, &child->head, next) { + TAILQ_FOREACH (subchild, &child->head, next) { if ((!strcmp(subchild->name, key)) && (!strcmp(subchild->val, value))) { return child; } @@ -879,8 +869,7 @@ char *ConfLoadCompleteIncludePath(const char *file) if (PathIsRelative(file)) { if (ConfGet("include-path", &defaultpath) == 1) { SCLogDebug("Default path: %s", defaultpath); - size_t path_len = sizeof(char) * (strlen(defaultpath) + - strlen(file) + 2); + size_t path_len = sizeof(char) * (strlen(defaultpath) + strlen(file) + 2); path = SCMalloc(path_len); if (unlikely(path == NULL)) return NULL; @@ -888,7 +877,7 @@ char *ConfLoadCompleteIncludePath(const char *file) if (path[strlen(path) - 1] != '/') strlcat(path, "/", path_len); strlcat(path, file, path_len); - } else { + } else { path = SCStrdup(file); if (unlikely(path == NULL)) return NULL; @@ -1115,16 +1104,22 @@ static int ConfTestGetBool(void) char name[] = "some-bool"; const char *trues[] = { "1", - "on", "ON", - "yes", "YeS", - "true", "TRUE", + "on", + "ON", + "yes", + "YeS", + "true", + "TRUE", }; const char *falses[] = { "0", "something", - "off", "OFF", - "false", "FalSE", - "no", "NO", + "off", + "OFF", + "false", + "FalSE", + "no", + "NO", }; int val; size_t u; @@ -1152,7 +1147,7 @@ static int ConfNodeLookupChildTest(void) ConfNode *parent = ConfNodeNew(); ConfNode *child; - for (u = 0; u < sizeof(test_vals)/sizeof(test_vals[0]); u++) { + for (u = 0; u < sizeof(test_vals) / sizeof(test_vals[0]); u++) { child = ConfNodeNew(); child->name = SCStrdup(test_vals[u]); child->val = SCStrdup(test_vals[u]); @@ -1195,7 +1190,7 @@ static int ConfNodeLookupChildValueTest(void) ConfNode *child; const char *value; - for (u = 0; u < sizeof(test_vals)/sizeof(test_vals[0]); u++) { + for (u = 0; u < sizeof(test_vals) / sizeof(test_vals[0]); u++) { child = ConfNodeNew(); child->name = SCStrdup(test_vals[u]); child->val = SCStrdup(test_vals[u]); @@ -1224,7 +1219,7 @@ static int ConfNodeLookupChildValueTest(void) static int ConfGetChildValueWithDefaultTest(void) { - const char *val = ""; + const char *val = ""; ConfCreateContextBackup(); ConfInit(); ConfSet("af-packet.0.interface", "eth0"); @@ -1499,15 +1494,11 @@ void ConfRegisterTests(void) UtRegisterTest("ConfTestGetInt", ConfTestGetInt); UtRegisterTest("ConfTestGetBool", ConfTestGetBool); UtRegisterTest("ConfNodeLookupChildTest", ConfNodeLookupChildTest); - UtRegisterTest("ConfNodeLookupChildValueTest", - ConfNodeLookupChildValueTest); + UtRegisterTest("ConfNodeLookupChildValueTest", ConfNodeLookupChildValueTest); UtRegisterTest("ConfNodeRemoveTest", ConfNodeRemoveTest); - UtRegisterTest("ConfGetChildValueWithDefaultTest", - ConfGetChildValueWithDefaultTest); - UtRegisterTest("ConfGetChildValueIntWithDefaultTest", - ConfGetChildValueIntWithDefaultTest); - UtRegisterTest("ConfGetChildValueBoolWithDefaultTest", - ConfGetChildValueBoolWithDefaultTest); + UtRegisterTest("ConfGetChildValueWithDefaultTest", ConfGetChildValueWithDefaultTest); + UtRegisterTest("ConfGetChildValueIntWithDefaultTest", ConfGetChildValueIntWithDefaultTest); + UtRegisterTest("ConfGetChildValueBoolWithDefaultTest", ConfGetChildValueBoolWithDefaultTest); UtRegisterTest("ConfGetNodeOrCreateTest", ConfGetNodeOrCreateTest); UtRegisterTest("ConfNodePruneTest", ConfNodePruneTest); UtRegisterTest("ConfNodeIsSequenceTest", ConfNodeIsSequenceTest); diff --git a/src/conf.h b/src/conf.h index 0b278a0f608e..16d2cfb31cff 100644 --- a/src/conf.h +++ b/src/conf.h @@ -43,15 +43,14 @@ typedef struct ConfNode_ { TAILQ_ENTRY(ConfNode_) next; } ConfNode; - /** * The default log directory. */ #ifdef OS_WIN32 -#define DEFAULT_LOG_DIR "C:\\WINDOWS\\Temp" +#define DEFAULT_LOG_DIR "C:\\WINDOWS\\Temp" #define DEFAULT_DATA_DIR "C:\\WINDOWS\\Temp" #else -#define DEFAULT_LOG_DIR "/var/log/suricata" +#define DEFAULT_LOG_DIR "/var/log/suricata" #define DEFAULT_DATA_DIR DATA_DIR #endif /* OS_WIN32 */ @@ -89,9 +88,12 @@ ConfNode *ConfNodeLookupKeyValue(const ConfNode *base, const char *key, const ch int ConfGetChildValue(const ConfNode *base, const char *name, const char **vptr); int ConfGetChildValueInt(const ConfNode *base, const char *name, intmax_t *val); int ConfGetChildValueBool(const ConfNode *base, const char *name, int *val); -int ConfGetChildValueWithDefault(const ConfNode *base, const ConfNode *dflt, const char *name, const char **vptr); -int ConfGetChildValueIntWithDefault(const ConfNode *base, const ConfNode *dflt, const char *name, intmax_t *val); -int ConfGetChildValueBoolWithDefault(const ConfNode *base, const ConfNode *dflt, const char *name, int *val); +int ConfGetChildValueWithDefault( + const ConfNode *base, const ConfNode *dflt, const char *name, const char **vptr); +int ConfGetChildValueIntWithDefault( + const ConfNode *base, const ConfNode *dflt, const char *name, intmax_t *val); +int ConfGetChildValueBoolWithDefault( + const ConfNode *base, const ConfNode *dflt, const char *name, int *val); char *ConfLoadCompleteIncludePath(const char *); int ConfNodeIsSequence(const ConfNode *node); ConfNode *ConfSetIfaceNode(const char *ifaces_node_name, const char *iface); diff --git a/src/counters.c b/src/counters.c index 790f416ba050..44d6f71f6466 100644 --- a/src/counters.c +++ b/src/counters.c @@ -109,7 +109,7 @@ void StatsReleaseCounters(StatsCounter *head); /** stats table is filled each interval and passed to the * loggers. Initialized at first use. */ -static StatsTable stats_table = { NULL, NULL, 0, 0, 0, {0 , 0}}; +static StatsTable stats_table = { NULL, NULL, 0, 0, 0, { 0, 0 } }; static SCMutex stats_table_mutex = SCMUTEX_INITIALIZER; static int stats_loggers_active = 1; @@ -146,12 +146,12 @@ static void StatsPublicThreadContextCleanup(StatsPublicThreadContext *t) void StatsAddUI64(ThreadVars *tv, uint16_t id, uint64_t x) { StatsPrivateThreadContext *pca = &tv->perf_private_ctx; -#if defined (UNITTESTS) || defined (FUZZ) +#if defined(UNITTESTS) || defined(FUZZ) if (pca->initialized == 0) return; #endif #ifdef DEBUG - BUG_ON ((id < 1) || (id > pca->size)); + BUG_ON((id < 1) || (id > pca->size)); #endif pca->head[id].value += x; pca->head[id].updates++; @@ -167,12 +167,12 @@ void StatsAddUI64(ThreadVars *tv, uint16_t id, uint64_t x) void StatsIncr(ThreadVars *tv, uint16_t id) { StatsPrivateThreadContext *pca = &tv->perf_private_ctx; -#if defined (UNITTESTS) || defined (FUZZ) +#if defined(UNITTESTS) || defined(FUZZ) if (pca->initialized == 0) return; #endif #ifdef DEBUG - BUG_ON ((id < 1) || (id > pca->size)); + BUG_ON((id < 1) || (id > pca->size)); #endif pca->head[id].value++; pca->head[id].updates++; @@ -210,12 +210,12 @@ void StatsDecr(ThreadVars *tv, uint16_t id) void StatsSetUI64(ThreadVars *tv, uint16_t id, uint64_t x) { StatsPrivateThreadContext *pca = &tv->perf_private_ctx; -#if defined (UNITTESTS) || defined (FUZZ) +#if defined(UNITTESTS) || defined(FUZZ) if (pca->initialized == 0) return; #endif #ifdef DEBUG - BUG_ON ((id < 1) || (id > pca->size)); + BUG_ON((id < 1) || (id > pca->size)); #endif if ((pca->head[id].pc->type == STATS_TYPE_MAXIMUM) && ((int64_t)x > pca->head[id].value)) { @@ -229,7 +229,8 @@ void StatsSetUI64(ThreadVars *tv, uint16_t id, uint64_t x) return; } -static ConfNode *GetConfig(void) { +static ConfNode *GetConfig(void) +{ ConfNode *stats = ConfGetNode("stats"); if (stats != NULL) return stats; @@ -237,7 +238,7 @@ static ConfNode *GetConfig(void) { ConfNode *root = ConfGetNode("outputs"); ConfNode *node = NULL; if (root != NULL) { - TAILQ_FOREACH(node, &root->head, next) { + TAILQ_FOREACH (node, &root->head, next) { if (strcmp(node->val, "stats") == 0) { return node->head.tqh_first; } @@ -585,8 +586,7 @@ static void StatsReleaseCounter(StatsCounter *pc) * \retval 0 on failure */ static uint16_t StatsRegisterQualifiedCounter(const char *name, const char *tm_name, - StatsPublicThreadContext *pctx, - int type_q, uint64_t (*Func)(void)) + StatsPublicThreadContext *pctx, int type_q, uint64_t (*Func)(void)) { StatsCounter **head = &pctx->head; StatsCounter *temp = NULL; @@ -611,7 +611,7 @@ static uint16_t StatsRegisterQualifiedCounter(const char *name, const char *tm_n /* We already have a counter registered by this name */ if (temp != NULL) - return(temp->id); + return (temp->id); /* if we reach this point we don't have a counter registered by this name */ if ((pc = SCCalloc(1, sizeof(StatsCounter))) == NULL) @@ -704,8 +704,7 @@ static int StatsOutput(ThreadVars *tv) int64_t value; uint64_t updates; } merge_table[max_id]; - memset(&merge_table, 0x00, - max_id * sizeof(struct CountersMergeTable)); + memset(&merge_table, 0x00, max_id * sizeof(struct CountersMergeTable)); int thread = stats_ctx->sts_cnt - 1; StatsRecord *table = stats_table.stats; @@ -723,14 +722,12 @@ static int StatsOutput(ThreadVars *tv) * thread store, so that we can post process them outside * of the thread store lock */ struct CountersMergeTable thread_table[max_id]; - memset(&thread_table, 0x00, - max_id * sizeof(struct CountersMergeTable)); + memset(&thread_table, 0x00, max_id * sizeof(struct CountersMergeTable)); SCMutexLock(&sts->ctx->m); pc = sts->ctx->head; while (pc != NULL) { - SCLogDebug("Counter %s (%u:%u) value %"PRIu64, - pc->name, pc->id, pc->gid, pc->value); + SCLogDebug("Counter %s (%u:%u) value %" PRIu64, pc->name, pc->id, pc->gid, pc->value); thread_table[pc->gid].type = pc->type; switch (pc->type) { @@ -843,8 +840,7 @@ static int StatsOutput(ThreadVars *tv) #ifdef BUILD_UNIX_SOCKET /** \brief callback for getting stats into unix socket */ -TmEcode StatsOutputCounterSocket(json_t *cmd, - json_t *answer, void *data) +TmEcode StatsOutputCounterSocket(json_t *cmd, json_t *answer, void *data) { json_t *message = NULL; TmEcode r = TM_ECODE_OK; @@ -858,7 +854,7 @@ TmEcode StatsOutputCounterSocket(json_t *cmd, r = TM_ECODE_FAILED; message = json_string("stats not yet synchronized"); } else { - message = StatsToJSON(&stats_table, JSON_STATS_TOTALS|JSON_STATS_THREADS); + message = StatsToJSON(&stats_table, JSON_STATS_TOTALS | JSON_STATS_THREADS); } SCMutexUnlock(&stats_table_mutex); } @@ -885,7 +881,7 @@ static void StatsLogSummary(void) } } SCMutexUnlock(&stats_table_mutex); - SCLogInfo("Alerts: %"PRIu64, alerts); + SCLogInfo("Alerts: %" PRIu64, alerts); } /** @@ -912,7 +908,6 @@ void StatsSetupPostConfigPostOutput(void) StatsInitCtxPostOutput(); } - /** * \brief Spawns the wakeup, and the management thread used by the stats api * @@ -931,8 +926,7 @@ void StatsSpawnThreads(void) ThreadVars *tv_mgmt = NULL; /* spawn the stats wakeup thread */ - tv_wakeup = TmThreadCreateMgmtThread(thread_name_counter_wakeup, - StatsWakeupThread, 1); + tv_wakeup = TmThreadCreateMgmtThread(thread_name_counter_wakeup, StatsWakeupThread, 1); if (tv_wakeup == NULL) { FatalError("TmThreadCreateMgmtThread " "failed"); @@ -944,8 +938,7 @@ void StatsSpawnThreads(void) } /* spawn the stats mgmt thread */ - tv_mgmt = TmThreadCreateMgmtThread(thread_name_counter_stats, - StatsMgmtThread, 1); + tv_mgmt = TmThreadCreateMgmtThread(thread_name_counter_stats, StatsMgmtThread, 1); if (tv_mgmt == NULL) { FatalError("TmThreadCreateMgmtThread failed"); } @@ -972,8 +965,7 @@ uint16_t StatsRegisterCounter(const char *name, struct ThreadVars_ *tv) { uint16_t id = StatsRegisterQualifiedCounter(name, (tv->thread_group_name != NULL) ? tv->thread_group_name : tv->printable_name, - &tv->perf_public_ctx, - STATS_TYPE_NORMAL, NULL); + &tv->perf_public_ctx, STATS_TYPE_NORMAL, NULL); return id; } @@ -992,8 +984,7 @@ uint16_t StatsRegisterAvgCounter(const char *name, struct ThreadVars_ *tv) { uint16_t id = StatsRegisterQualifiedCounter(name, (tv->thread_group_name != NULL) ? tv->thread_group_name : tv->printable_name, - &tv->perf_public_ctx, - STATS_TYPE_AVERAGE, NULL); + &tv->perf_public_ctx, STATS_TYPE_AVERAGE, NULL); return id; } @@ -1012,8 +1003,7 @@ uint16_t StatsRegisterMaxCounter(const char *name, struct ThreadVars_ *tv) { uint16_t id = StatsRegisterQualifiedCounter(name, (tv->thread_group_name != NULL) ? tv->thread_group_name : tv->printable_name, - &tv->perf_public_ctx, - STATS_TYPE_MAXIMUM, NULL); + &tv->perf_public_ctx, STATS_TYPE_MAXIMUM, NULL); return id; } @@ -1028,16 +1018,14 @@ uint16_t StatsRegisterMaxCounter(const char *name, struct ThreadVars_ *tv) */ uint16_t StatsRegisterGlobalCounter(const char *name, uint64_t (*Func)(void)) { -#if defined (UNITTESTS) || defined (FUZZ) +#if defined(UNITTESTS) || defined(FUZZ) if (stats_ctx == NULL) return 0; #else BUG_ON(stats_ctx == NULL); #endif - uint16_t id = StatsRegisterQualifiedCounter(name, NULL, - &(stats_ctx->global_counter_ctx), - STATS_TYPE_FUNC, - Func); + uint16_t id = StatsRegisterQualifiedCounter( + name, NULL, &(stats_ctx->global_counter_ctx), STATS_TYPE_FUNC, Func); return id; } @@ -1059,8 +1047,8 @@ static uint32_t CountersIdHashFunc(HashTable *ht, void *data, uint16_t datalen) return hash; } -static char CountersIdHashCompareFunc(void *data1, uint16_t datalen1, - void *data2, uint16_t datalen2) +static char CountersIdHashCompareFunc( + void *data1, uint16_t datalen1, void *data2, uint16_t datalen2) { CountersIdType *t1 = (CountersIdType *)data1; CountersIdType *t2 = (CountersIdType *)data2; @@ -1088,7 +1076,6 @@ static void CountersIdHashFreeFunc(void *data) SCFree(data); } - /** \internal * \brief Adds a TM to the clubbed TM table. Multiple instances of the same TM * are stacked together in a PCTMI container. @@ -1112,9 +1099,8 @@ static int StatsThreadRegister(const char *thread_name, StatsPublicThreadContext SCMutexLock(&stats_ctx->sts_lock); if (stats_ctx->counters_id_hash == NULL) { - stats_ctx->counters_id_hash = HashTableInit(256, CountersIdHashFunc, - CountersIdHashCompareFunc, - CountersIdHashFreeFunc); + stats_ctx->counters_id_hash = HashTableInit( + 256, CountersIdHashFunc, CountersIdHashCompareFunc, CountersIdHashFreeFunc); BUG_ON(stats_ctx->counters_id_hash == NULL); } StatsCounter *pc = pctx->head; @@ -1132,7 +1118,6 @@ static int StatsThreadRegister(const char *thread_name, StatsPublicThreadContext pc = pc->next; } - StatsThreadStore *temp = NULL; if ((temp = SCCalloc(1, sizeof(StatsThreadStore))) == NULL) { SCMutexUnlock(&stats_ctx->sts_lock); @@ -1160,9 +1145,8 @@ static int StatsThreadRegister(const char *thread_name, StatsPublicThreadContext * * \retval a counter-array in this(s_id-e_id) range for this TM instance */ -static int StatsGetCounterArrayRange(uint16_t s_id, uint16_t e_id, - StatsPublicThreadContext *pctx, - StatsPrivateThreadContext *pca) +static int StatsGetCounterArrayRange(uint16_t s_id, uint16_t e_id, StatsPublicThreadContext *pctx, + StatsPrivateThreadContext *pca) { StatsCounter *pc = NULL; uint32_t i = 0; @@ -1212,7 +1196,8 @@ static int StatsGetCounterArrayRange(uint16_t s_id, uint16_t e_id, * \retval pca Pointer to a counter-array for all counter of this tm instance * on success; NULL on failure */ -static int StatsGetAllCountersArray(StatsPublicThreadContext *pctx, StatsPrivateThreadContext *private) +static int StatsGetAllCountersArray( + StatsPublicThreadContext *pctx, StatsPrivateThreadContext *private) { if (pctx == NULL || private == NULL) return -1; @@ -1220,13 +1205,11 @@ static int StatsGetAllCountersArray(StatsPublicThreadContext *pctx, StatsPrivate return StatsGetCounterArrayRange(1, pctx->curr_id, pctx, private); } - int StatsSetupPrivate(ThreadVars *tv) { StatsGetAllCountersArray(&(tv)->perf_public_ctx, &(tv)->perf_private_ctx); - StatsThreadRegister(tv->printable_name ? tv->printable_name : tv->name, - &(tv)->perf_public_ctx); + StatsThreadRegister(tv->printable_name ? tv->printable_name : tv->name, &(tv)->perf_public_ctx); return 0; } @@ -1271,7 +1254,7 @@ uint64_t StatsGetLocalCounterValue(ThreadVars *tv, uint16_t id) { StatsPrivateThreadContext *pca = &tv->perf_private_ctx; #ifdef DEBUG - BUG_ON ((id < 1) || (id > pca->size)); + BUG_ON((id < 1) || (id > pca->size)); #endif return pca->head[id].value; } @@ -1342,11 +1325,10 @@ void StatsThreadCleanup(ThreadVars *tv) * \retval id Counter id for the newly registered counter, or the already * present counter */ -static uint16_t RegisterCounter(const char *name, const char *tm_name, - StatsPublicThreadContext *pctx) +static uint16_t RegisterCounter( + const char *name, const char *tm_name, StatsPublicThreadContext *pctx) { - uint16_t id = StatsRegisterQualifiedCounter(name, tm_name, pctx, - STATS_TYPE_NORMAL, NULL); + uint16_t id = StatsRegisterQualifiedCounter(name, tm_name, pctx, STATS_TYPE_NORMAL, NULL); return id; } @@ -1436,7 +1418,7 @@ static int StatsTestCntArraySize07(void) memset(&tv, 0, sizeof(ThreadVars)); - //pca = (StatsPrivateThreadContext *)&tv.perf_private_ctx; + // pca = (StatsPrivateThreadContext *)&tv.perf_private_ctx; RegisterCounter("t1", "c1", &tv.perf_public_ctx); RegisterCounter("t2", "c2", &tv.perf_public_ctx); @@ -1592,8 +1574,7 @@ void StatsRegisterTests(void) UtRegisterTest("StatsTestCntArraySize07", StatsTestCntArraySize07); UtRegisterTest("StatsTestUpdateCounter08", StatsTestUpdateCounter08); UtRegisterTest("StatsTestUpdateCounter09", StatsTestUpdateCounter09); - UtRegisterTest("StatsTestUpdateGlobalCounter10", - StatsTestUpdateGlobalCounter10); + UtRegisterTest("StatsTestUpdateGlobalCounter10", StatsTestUpdateGlobalCounter10); UtRegisterTest("StatsTestCounterValues11", StatsTestCounterValues11); #endif } diff --git a/src/counters.h b/src/counters.h index b3ffddbd569f..d73a8f711f01 100644 --- a/src/counters.h +++ b/src/counters.h @@ -43,8 +43,8 @@ typedef struct StatsCounter_ { uint16_t gid; /* counter value(s): copies from the 'private' counter */ - int64_t value; /**< sum of updates/increments, or 'set' value */ - uint64_t updates; /**< number of updates (for avg) */ + int64_t value; /**< sum of updates/increments, or 'set' value */ + uint64_t updates; /**< number of updates (for avg) */ /* when using type STATS_TYPE_Q_FUNC this function is called once * to get the counter value, regardless of how many threads there are. */ @@ -139,9 +139,7 @@ void StatsSyncCounters(struct ThreadVars_ *tv); void StatsSyncCountersIfSignalled(struct ThreadVars_ *tv); #ifdef BUILD_UNIX_SOCKET -TmEcode StatsOutputCounterSocket(json_t *cmd, - json_t *answer, void *data); +TmEcode StatsOutputCounterSocket(json_t *cmd, json_t *answer, void *data); #endif #endif /* __COUNTERS_H__ */ - diff --git a/src/datasets-md5.c b/src/datasets-md5.c index 3b1d8f3fc02c..ae5d2e05274c 100644 --- a/src/datasets-md5.c +++ b/src/datasets-md5.c @@ -27,7 +27,7 @@ #include "datasets-md5.h" #include "util-thash.h" #include "util-print.h" -#include "util-base64.h" // decode base64 +#include "util-base64.h" // decode base64 int Md5StrSet(void *dst, void *src) { diff --git a/src/datasets-sha256.c b/src/datasets-sha256.c index 346397d6d6fa..ad14cbe21a4d 100644 --- a/src/datasets-sha256.c +++ b/src/datasets-sha256.c @@ -27,7 +27,7 @@ #include "datasets-sha256.h" #include "util-thash.h" #include "util-print.h" -#include "util-base64.h" // decode base64 +#include "util-base64.h" // decode base64 int Sha256StrSet(void *dst, void *src) { diff --git a/src/datasets-string.c b/src/datasets-string.c index 4a572898ceb3..99cf6c3860e7 100644 --- a/src/datasets-string.c +++ b/src/datasets-string.c @@ -27,7 +27,7 @@ #include "datasets-string.h" #include "util-thash.h" #include "util-print.h" -#include "util-base64.h" // decode base64 +#include "util-base64.h" // decode base64 #include "rust.h" #if 0 @@ -49,8 +49,7 @@ int StringAsBase64(const void *s, char *out, size_t out_size) unsigned long len = Base64EncodeBufferSize(str->len); uint8_t encoded_data[len]; - if (Base64Encode((unsigned char *)str->ptr, str->len, - encoded_data, &len) != SC_BASE64_OK) + if (Base64Encode((unsigned char *)str->ptr, str->len, encoded_data, &len) != SC_BASE64_OK) return 0; strlcpy(out, (const char *)encoded_data, out_size); diff --git a/src/datasets.c b/src/datasets.c index d89ed8df59da..2e2727b42393 100644 --- a/src/datasets.c +++ b/src/datasets.c @@ -34,7 +34,7 @@ #include "util-conf.h" #include "util-thash.h" #include "util-print.h" -#include "util-base64.h" // decode base64 +#include "util-base64.h" // decode base64 #include "util-byte.h" #include "util-misc.h" #include "util-path.h" @@ -44,12 +44,12 @@ SCMutex sets_lock = SCMUTEX_INITIALIZER; static Dataset *sets = NULL; static uint32_t set_ids = 0; -static int DatasetAddwRep(Dataset *set, const uint8_t *data, const uint32_t data_len, - DataRepType *rep); +static int DatasetAddwRep( + Dataset *set, const uint8_t *data, const uint32_t data_len, DataRepType *rep); static inline void DatasetUnlockData(THashData *d) { - (void) THashDecrUsecnt(d); + (void)THashDecrUsecnt(d); THashDataUnlock(d); } static bool DatasetIsStatic(const char *save, const char *load); @@ -103,10 +103,10 @@ static int HexToRaw(const uint8_t *in, size_t ins, uint8_t *out, size_t outs) uint8_t hash[outs]; memset(hash, 0, outs); size_t i, x; - for (x = 0, i = 0; i < ins; i+=2, x++) { + for (x = 0, i = 0; i < ins; i += 2, x++) { char buf[3] = { 0, 0, 0 }; buf[0] = in[i]; - buf[1] = in[i+1]; + buf[1] = in[i + 1]; long value = strtol(buf, NULL, 16); if (value >= 0 && value <= 255) @@ -129,7 +129,7 @@ static int ParseRepLine(const char *in, size_t ins, DataRepType *rep_out) raw[ins] = '\0'; char *line = raw; - char *ptrs[1] = {NULL}; + char *ptrs[1] = { NULL }; int idx = 0; size_t i = 0; @@ -159,7 +159,7 @@ static int ParseRepLine(const char *in, size_t ins, DataRepType *rep_out) SCLogError("'%s' is not a valid reputation value (0-65535)", ptrs[0]); return -1; } - SCLogDebug("v %"PRIu16" raw %s", v, ptrs[0]); + SCLogDebug("v %" PRIu16 " raw %s", v, ptrs[0]); rep_out->value = v; return 0; @@ -383,7 +383,7 @@ static int DatasetLoadMd5(Dataset *set) } cnt++; - /* list with rep data */ + /* list with rep data */ } else if (strlen(line) > 33 && line[32] == ',') { line[strlen(line) - 1] = '\0'; SCLogDebug("MD5 with REP line: '%s'", line); @@ -394,7 +394,7 @@ static int DatasetLoadMd5(Dataset *set) continue; } - DataRepType rep = { .value = 0}; + DataRepType rep = { .value = 0 }; if (ParseRepLine(line + 33, strlen(line) - 33, &rep) < 0) { FatalErrorOnInit("bad rep for dataset %s/%s", set->name, set->load); continue; @@ -407,8 +407,7 @@ static int DatasetLoadMd5(Dataset *set) } cnt++; - } - else { + } else { FatalErrorOnInit("MD5 bad line len %u: '%s'", (uint32_t)strlen(line), line); continue; } @@ -582,8 +581,8 @@ enum DatasetGetPathType { TYPE_LOAD, }; -static void DatasetGetPath(const char *in_path, - char *out_path, size_t out_size, enum DatasetGetPathType type) +static void DatasetGetPath( + const char *in_path, char *out_path, size_t out_size, enum DatasetGetPathType type) { char path[PATH_MAX]; struct stat st; @@ -649,8 +648,7 @@ Dataset *DatasetGet(const char *name, enum DatasetTypes type, const char *save, return NULL; } - if ((save == NULL || strlen(save) == 0) && - (load == NULL || strlen(load) == 0)) { + if ((save == NULL || strlen(save) == 0) && (load == NULL || strlen(load) == 0)) { // OK, rule keyword doesn't have to set state/load, // even when yaml set has set it. } else { @@ -746,8 +744,8 @@ Dataset *DatasetGet(const char *name, enum DatasetTypes type, const char *save, break; } - SCLogDebug("set %p/%s type %u save %s load %s", - set, set->name, set->type, set->save, set->load); + SCLogDebug( + "set %p/%s type %u save %s load %s", set, set->name, set->type, set->save, set->load); set->next = sets; sets = set; @@ -770,8 +768,7 @@ static bool DatasetIsStatic(const char *save, const char *load) /* A set is static if it does not have any dynamic properties like * save and/or state defined but has load defined. * */ - if ((load != NULL && strlen(load) > 0) && - (save == NULL || strlen(save) == 0)) { + if ((load != NULL && strlen(load) > 0) && (save == NULL || strlen(save) == 0)) { return true; } return false; @@ -856,7 +853,7 @@ int DatasetsInit(void) if (datasets != NULL) { int list_pos = 0; ConfNode *iter = NULL; - TAILQ_FOREACH(iter, &datasets->head, next) { + TAILQ_FOREACH (iter, &datasets->head, next) { if (iter->name == NULL) { list_pos++; continue; @@ -874,21 +871,18 @@ int DatasetsInit(void) continue; } - ConfNode *set_type = - ConfNodeLookupChild(iter, "type"); + ConfNode *set_type = ConfNodeLookupChild(iter, "type"); if (set_type == NULL) { list_pos++; continue; } - ConfNode *set_save = - ConfNodeLookupChild(iter, "state"); + ConfNode *set_save = ConfNodeLookupChild(iter, "state"); if (set_save) { DatasetGetPath(set_save->val, save, sizeof(save), TYPE_STATE); strlcpy(load, save, sizeof(load)); } else { - ConfNode *set_load = - ConfNodeLookupChild(iter, "load"); + ConfNode *set_load = ConfNodeLookupChild(iter, "load"); if (set_load) { DatasetGetPath(set_load->val, load, sizeof(load), TYPE_LOAD); } @@ -1000,7 +994,7 @@ void DatasetsDestroy(void) static int SaveCallback(void *ctx, const uint8_t *data, const uint32_t data_len) { FILE *fp = ctx; - //PrintRawDataFp(fp, data, data_len); + // PrintRawDataFp(fp, data, data_len); if (fp) { return fwrite(data, data_len, 1, fp); } @@ -1113,10 +1107,10 @@ static int DatasetLookupString(Dataset *set, const uint8_t *data, const uint32_t return 0; } -static DataRepResultType DatasetLookupStringwRep(Dataset *set, - const uint8_t *data, const uint32_t data_len, const DataRepType *rep) +static DataRepResultType DatasetLookupStringwRep( + Dataset *set, const uint8_t *data, const uint32_t data_len, const DataRepType *rep) { - DataRepResultType rrep = { .found = false, .rep = { .value = 0 }}; + DataRepResultType rrep = { .found = false, .rep = { .value = 0 } }; if (set == NULL) return rrep; @@ -1235,10 +1229,10 @@ static int DatasetLookupMd5(Dataset *set, const uint8_t *data, const uint32_t da return 0; } -static DataRepResultType DatasetLookupMd5wRep(Dataset *set, - const uint8_t *data, const uint32_t data_len, const DataRepType *rep) +static DataRepResultType DatasetLookupMd5wRep( + Dataset *set, const uint8_t *data, const uint32_t data_len, const DataRepType *rep) { - DataRepResultType rrep = { .found = false, .rep = { .value = 0 }}; + DataRepResultType rrep = { .found = false, .rep = { .value = 0 } }; if (set == NULL) return rrep; @@ -1246,7 +1240,7 @@ static DataRepResultType DatasetLookupMd5wRep(Dataset *set, if (data_len != 16) return rrep; - Md5Type lookup = { .rep.value = 0}; + Md5Type lookup = { .rep.value = 0 }; memcpy(lookup.md5, data, data_len); THashData *rdata = THashLookupFromHash(set->hash, &lookup); if (rdata) { @@ -1277,10 +1271,10 @@ static int DatasetLookupSha256(Dataset *set, const uint8_t *data, const uint32_t return 0; } -static DataRepResultType DatasetLookupSha256wRep(Dataset *set, - const uint8_t *data, const uint32_t data_len, const DataRepType *rep) +static DataRepResultType DatasetLookupSha256wRep( + Dataset *set, const uint8_t *data, const uint32_t data_len, const DataRepType *rep) { - DataRepResultType rrep = { .found = false, .rep = { .value = 0 }}; + DataRepResultType rrep = { .found = false, .rep = { .value = 0 } }; if (set == NULL) return rrep; @@ -1330,10 +1324,10 @@ int DatasetLookup(Dataset *set, const uint8_t *data, const uint32_t data_len) return -1; } -DataRepResultType DatasetLookupwRep(Dataset *set, const uint8_t *data, const uint32_t data_len, - const DataRepType *rep) +DataRepResultType DatasetLookupwRep( + Dataset *set, const uint8_t *data, const uint32_t data_len, const DataRepType *rep) { - DataRepResultType rrep = { .found = false, .rep = { .value = 0 }}; + DataRepResultType rrep = { .found = false, .rep = { .value = 0 } }; if (set == NULL) return rrep; @@ -1362,8 +1356,7 @@ static int DatasetAddString(Dataset *set, const uint8_t *data, const uint32_t da if (set == NULL) return -1; - StringType lookup = { .ptr = (uint8_t *)data, .len = data_len, - .rep.value = 0 }; + StringType lookup = { .ptr = (uint8_t *)data, .len = data_len, .rep.value = 0 }; struct THashDataGetResult res = THashGetFromHash(set->hash, &lookup); if (res.data) { DatasetUnlockData(res.data); @@ -1383,8 +1376,7 @@ static int DatasetAddStringwRep( if (set == NULL) return -1; - StringType lookup = { .ptr = (uint8_t *)data, .len = data_len, - .rep = *rep }; + StringType lookup = { .ptr = (uint8_t *)data, .len = data_len, .rep = *rep }; struct THashDataGetResult res = THashGetFromHash(set->hash, &lookup); if (res.data) { DatasetUnlockData(res.data); @@ -1565,8 +1557,8 @@ int DatasetAdd(Dataset *set, const uint8_t *data, const uint32_t data_len) return -1; } -static int DatasetAddwRep(Dataset *set, const uint8_t *data, const uint32_t data_len, - DataRepType *rep) +static int DatasetAddwRep( + Dataset *set, const uint8_t *data, const uint32_t data_len, DataRepType *rep) { if (set == NULL) return -1; @@ -1674,8 +1666,7 @@ static int DatasetRemoveString(Dataset *set, const uint8_t *data, const uint32_t if (set == NULL) return -1; - StringType lookup = { .ptr = (uint8_t *)data, .len = data_len, - .rep.value = 0 }; + StringType lookup = { .ptr = (uint8_t *)data, .len = data_len, .rep.value = 0 }; return THashRemoveFromHash(set->hash, &lookup); } diff --git a/src/datasets.h b/src/datasets.h index af4fc173f194..5ef46364a92c 100644 --- a/src/datasets.h +++ b/src/datasets.h @@ -41,8 +41,8 @@ typedef struct Dataset { char name[DATASET_NAME_MAX_LEN + 1]; enum DatasetTypes type; uint32_t id; - bool from_yaml; /* Mark whether the set was retrieved from YAML */ - bool hidden; /* Mark the old sets hidden in case of reload */ + bool from_yaml; /* Mark whether the set was retrieved from YAML */ + bool hidden; /* Mark the old sets hidden in case of reload */ THashTableContext *hash; char load[PATH_MAX]; @@ -57,8 +57,8 @@ Dataset *DatasetGet(const char *name, enum DatasetTypes type, const char *save, uint64_t memcap, uint32_t hashsize); int DatasetAdd(Dataset *set, const uint8_t *data, const uint32_t data_len); int DatasetLookup(Dataset *set, const uint8_t *data, const uint32_t data_len); -DataRepResultType DatasetLookupwRep(Dataset *set, const uint8_t *data, const uint32_t data_len, - const DataRepType *rep); +DataRepResultType DatasetLookupwRep( + Dataset *set, const uint8_t *data, const uint32_t data_len, const DataRepType *rep); int DatasetAddSerialized(Dataset *set, const char *string); int DatasetRemoveSerialized(Dataset *set, const char *string); diff --git a/src/decode-chdlc.c b/src/decode-chdlc.c index 565c55e451a7..5be16f1c2a02 100644 --- a/src/decode-chdlc.c +++ b/src/decode-chdlc.c @@ -21,7 +21,6 @@ * @{ */ - /** * \file * @@ -39,8 +38,7 @@ #include "util-unittest.h" #include "util-debug.h" -int DecodeCHDLC(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, - const uint8_t *pkt, uint32_t len) +int DecodeCHDLC(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, const uint8_t *pkt, uint32_t len) { DEBUG_VALIDATE_BUG_ON(pkt == NULL); @@ -62,14 +60,14 @@ int DecodeCHDLC(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, SCLogDebug("p %p pkt %p ether type %04x", p, pkt, SCNtohs(hdr->protocol)); - DecodeNetworkLayer(tv, dtv, SCNtohs(hdr->protocol), p, - pkt + CHDLC_HEADER_LEN, len - CHDLC_HEADER_LEN); + DecodeNetworkLayer( + tv, dtv, SCNtohs(hdr->protocol), p, pkt + CHDLC_HEADER_LEN, len - CHDLC_HEADER_LEN); return TM_ECODE_OK; } #ifdef UNITTESTS -static int DecodeCHDLCTest01 (void) +static int DecodeCHDLCTest01(void) { // clang-format off uint8_t raw[] = { 0x0f,0x00,0x08,0x00, // HDLC @@ -86,7 +84,7 @@ static int DecodeCHDLCTest01 (void) DecodeThreadVars dtv; memset(&dtv, 0, sizeof(DecodeThreadVars)); - memset(&tv, 0, sizeof(ThreadVars)); + memset(&tv, 0, sizeof(ThreadVars)); DecodeCHDLC(&tv, &dtv, p, raw, sizeof(raw)); @@ -99,7 +97,6 @@ static int DecodeCHDLCTest01 (void) } #endif /* UNITTESTS */ - /** * \brief Registers Ethernet unit tests * \todo More Ethernet tests diff --git a/src/decode-chdlc.h b/src/decode-chdlc.h index 47e0d7c1a3ef..9af4aa01e4c4 100644 --- a/src/decode-chdlc.h +++ b/src/decode-chdlc.h @@ -24,7 +24,7 @@ #ifndef __DECODE_CHDLC_H__ #define __DECODE_CHDLC_H__ -#define CHDLC_HEADER_LEN 4 +#define CHDLC_HEADER_LEN 4 typedef struct CHDLCHdr_ { uint8_t address; diff --git a/src/decode-erspan.c b/src/decode-erspan.c index ccdf64aeaef9..d4c80ceaa6ec 100644 --- a/src/decode-erspan.c +++ b/src/decode-erspan.c @@ -21,7 +21,6 @@ * @{ */ - /** * \file * @@ -61,8 +60,8 @@ void DecodeERSPANConfig(void) /** * \brief ERSPAN Type I */ -int DecodeERSPANTypeI(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, - const uint8_t *pkt, uint32_t len) +int DecodeERSPANTypeI( + ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, const uint8_t *pkt, uint32_t len) { StatsIncr(tv, dtv->counter_erspan); @@ -79,7 +78,7 @@ int DecodeERSPAN(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, const uint8_t StatsIncr(tv, dtv->counter_erspan); if (len < sizeof(ErspanHdr)) { - ENGINE_SET_EVENT(p,ERSPAN_HEADER_TOO_SMALL); + ENGINE_SET_EVENT(p, ERSPAN_HEADER_TOO_SMALL); return TM_ECODE_FAILED; } if (!PacketIncreaseCheckLayers(p)) { @@ -94,13 +93,13 @@ int DecodeERSPAN(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, const uint8_t /* only v1 is tested at this time */ if (version != 1) { - ENGINE_SET_EVENT(p,ERSPAN_UNSUPPORTED_VERSION); + ENGINE_SET_EVENT(p, ERSPAN_UNSUPPORTED_VERSION); return TM_ECODE_FAILED; } if (vlan_id > 0) { if (p->vlan_idx > VLAN_MAX_LAYER_IDX) { - ENGINE_SET_EVENT(p,ERSPAN_TOO_MANY_VLAN_LAYERS); + ENGINE_SET_EVENT(p, ERSPAN_TOO_MANY_VLAN_LAYERS); return TM_ECODE_FAILED; } p->vlan_id[p->vlan_idx] = vlan_id; diff --git a/src/decode-erspan.h b/src/decode-erspan.h index d92965db027f..a095ae0f025c 100644 --- a/src/decode-erspan.h +++ b/src/decode-erspan.h @@ -25,7 +25,6 @@ #ifndef __DECODE_ERSPAN_H__ #define __DECODE_ERSPAN_H__ - typedef struct ErspanHdr_ { uint16_t ver_vlan; uint16_t flags_spanid; diff --git a/src/decode-ethernet.c b/src/decode-ethernet.c index 1344c1a88818..7e881bda7d58 100644 --- a/src/decode-ethernet.c +++ b/src/decode-ethernet.c @@ -21,7 +21,6 @@ * @{ */ - /** * \file * @@ -39,8 +38,8 @@ #include "util-unittest.h" #include "util-debug.h" -int DecodeEthernet(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, - const uint8_t *pkt, uint32_t len) +int DecodeEthernet( + ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, const uint8_t *pkt, uint32_t len) { DEBUG_VALIDATE_BUG_ON(pkt == NULL); @@ -58,8 +57,8 @@ int DecodeEthernet(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, SCLogDebug("p %p pkt %p ether type %04x", p, pkt, SCNtohs(p->ethh->eth_type)); - DecodeNetworkLayer(tv, dtv, SCNtohs(p->ethh->eth_type), p, - pkt + ETHERNET_HEADER_LEN, len - ETHERNET_HEADER_LEN); + DecodeNetworkLayer(tv, dtv, SCNtohs(p->ethh->eth_type), p, pkt + ETHERNET_HEADER_LEN, + len - ETHERNET_HEADER_LEN); return TM_ECODE_OK; } @@ -69,7 +68,7 @@ int DecodeEthernet(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, * \brief Valid Ethernet packet * \retval 0 Expected test value */ -static int DecodeEthernetTest01 (void) +static int DecodeEthernetTest01(void) { /* ICMP packet wrapped in PPPOE */ // clang-format off @@ -99,7 +98,7 @@ static int DecodeEthernetTest01 (void) DecodeThreadVars dtv; memset(&dtv, 0, sizeof(DecodeThreadVars)); - memset(&tv, 0, sizeof(ThreadVars)); + memset(&tv, 0, sizeof(ThreadVars)); DecodeEthernet(&tv, &dtv, p, raw_eth, sizeof(raw_eth)); @@ -125,7 +124,7 @@ static int DecodeEthernetTestDceTooSmall(void) DecodeThreadVars dtv; memset(&dtv, 0, sizeof(DecodeThreadVars)); - memset(&tv, 0, sizeof(ThreadVars)); + memset(&tv, 0, sizeof(ThreadVars)); DecodeEthernet(&tv, &dtv, p, raw_eth, sizeof(raw_eth)); @@ -162,7 +161,7 @@ static int DecodeEthernetTestDceNextTooSmall(void) DecodeThreadVars dtv; memset(&dtv, 0, sizeof(DecodeThreadVars)); - memset(&tv, 0, sizeof(ThreadVars)); + memset(&tv, 0, sizeof(ThreadVars)); DecodeEthernet(&tv, &dtv, p, raw_eth, sizeof(raw_eth)); @@ -174,7 +173,6 @@ static int DecodeEthernetTestDceNextTooSmall(void) #endif /* UNITTESTS */ - /** * \brief Registers Ethernet unit tests * \todo More Ethernet tests @@ -183,10 +181,8 @@ void DecodeEthernetRegisterTests(void) { #ifdef UNITTESTS UtRegisterTest("DecodeEthernetTest01", DecodeEthernetTest01); - UtRegisterTest("DecodeEthernetTestDceNextTooSmall", - DecodeEthernetTestDceNextTooSmall); - UtRegisterTest("DecodeEthernetTestDceTooSmall", - DecodeEthernetTestDceTooSmall); + UtRegisterTest("DecodeEthernetTestDceNextTooSmall", DecodeEthernetTestDceNextTooSmall); + UtRegisterTest("DecodeEthernetTestDceTooSmall", DecodeEthernetTestDceTooSmall); #endif /* UNITTESTS */ } /** diff --git a/src/decode-ethernet.h b/src/decode-ethernet.h index aa077056d672..30794c69a0ef 100644 --- a/src/decode-ethernet.h +++ b/src/decode-ethernet.h @@ -24,31 +24,32 @@ #ifndef __DECODE_ETHERNET_H__ #define __DECODE_ETHERNET_H__ -#define ETHERNET_HEADER_LEN 14 +#define ETHERNET_HEADER_LEN 14 /* Cisco Fabric Path / DCE header length. */ -#define ETHERNET_DCE_HEADER_LEN (ETHERNET_HEADER_LEN + 2) +#define ETHERNET_DCE_HEADER_LEN (ETHERNET_HEADER_LEN + 2) /* Ethernet types -- taken from Snort and Libdnet */ -#define ETHERNET_TYPE_PUP 0x0200 /* PUP protocol */ -#define ETHERNET_TYPE_IP 0x0800 -#define ETHERNET_TYPE_ARP 0x0806 -#define ETHERNET_TYPE_BRIDGE 0x6558 /* transparent ethernet bridge (GRE) */ -#define ETHERNET_TYPE_REVARP 0x8035 -#define ETHERNET_TYPE_EAPOL 0x888e -#define ETHERNET_TYPE_IPV6 0x86dd -#define ETHERNET_TYPE_IPX 0x8137 -#define ETHERNET_TYPE_PPPOE_DISC 0x8863 /* discovery stage */ -#define ETHERNET_TYPE_PPPOE_SESS 0x8864 /* session stage */ -#define ETHERNET_TYPE_8021AD 0x88a8 -#define ETHERNET_TYPE_8021AH 0x88e7 -#define ETHERNET_TYPE_8021Q 0x8100 -#define ETHERNET_TYPE_LOOP 0x9000 -#define ETHERNET_TYPE_8021QINQ 0x9100 -#define ETHERNET_TYPE_ERSPAN 0x88BE -#define ETHERNET_TYPE_DCE 0x8903 /* Data center ethernet, - * Cisco Fabric Path */ -#define ETHERNET_TYPE_NSH 0x894F +#define ETHERNET_TYPE_PUP 0x0200 /* PUP protocol */ +#define ETHERNET_TYPE_IP 0x0800 +#define ETHERNET_TYPE_ARP 0x0806 +#define ETHERNET_TYPE_BRIDGE 0x6558 /* transparent ethernet bridge (GRE) */ +#define ETHERNET_TYPE_REVARP 0x8035 +#define ETHERNET_TYPE_EAPOL 0x888e +#define ETHERNET_TYPE_IPV6 0x86dd +#define ETHERNET_TYPE_IPX 0x8137 +#define ETHERNET_TYPE_PPPOE_DISC 0x8863 /* discovery stage */ +#define ETHERNET_TYPE_PPPOE_SESS 0x8864 /* session stage */ +#define ETHERNET_TYPE_8021AD 0x88a8 +#define ETHERNET_TYPE_8021AH 0x88e7 +#define ETHERNET_TYPE_8021Q 0x8100 +#define ETHERNET_TYPE_LOOP 0x9000 +#define ETHERNET_TYPE_8021QINQ 0x9100 +#define ETHERNET_TYPE_ERSPAN 0x88BE +#define ETHERNET_TYPE_DCE \ + 0x8903 /* Data center ethernet, \ + * Cisco Fabric Path */ +#define ETHERNET_TYPE_NSH 0x894F #define ETHERNET_TYPE_VNTAG 0x8926 /* 802.1Qbh */ typedef struct EthernetHdr_ { @@ -60,4 +61,3 @@ typedef struct EthernetHdr_ { void DecodeEthernetRegisterTests(void); #endif /* __DECODE_ETHERNET_H__ */ - diff --git a/src/decode-events.h b/src/decode-events.h index 5547866fa59b..2340b718a4ab 100644 --- a/src/decode-events.h +++ b/src/decode-events.h @@ -301,8 +301,7 @@ enum { DECODE_EVENT_MAX, }; -#define EVENT_IS_DECODER_PACKET_ERROR(e) \ - ((e) < (DECODE_EVENT_PACKET_MAX)) +#define EVENT_IS_DECODER_PACKET_ERROR(e) ((e) < (DECODE_EVENT_PACKET_MAX)) /* supported decoder events */ diff --git a/src/decode-gre.c b/src/decode-gre.c index 783e60989f2e..9d06a31c3604 100644 --- a/src/decode-gre.c +++ b/src/decode-gre.c @@ -21,7 +21,6 @@ * @{ */ - /** * \file * @@ -54,7 +53,7 @@ int DecodeGRE(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, const uint8_t *p StatsIncr(tv, dtv->counter_gre); - if(len < GRE_HDR_LEN) { + if (len < GRE_HDR_LEN) { ENGINE_SET_INVALID_EVENT(p, GRE_PKT_TOO_SMALL); return TM_ECODE_FAILED; } @@ -64,11 +63,10 @@ int DecodeGRE(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, const uint8_t *p p->greh = (GREHdr *)pkt; - SCLogDebug("p %p pkt %p GRE protocol %04x Len: %d GRE version %x", - p, pkt, GRE_GET_PROTO(p->greh), len,GRE_GET_VERSION(p->greh)); + SCLogDebug("p %p pkt %p GRE protocol %04x Len: %d GRE version %x", p, pkt, + GRE_GET_PROTO(p->greh), len, GRE_GET_VERSION(p->greh)); - switch (GRE_GET_VERSION(p->greh)) - { + switch (GRE_GET_VERSION(p->greh)) { case GRE_VERSION_0: /* GRE version 0 doesn't support the fields below RFC 1701 */ @@ -85,7 +83,7 @@ int DecodeGRE(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, const uint8_t *p return TM_ECODE_OK; } - if (GREV1_FLAG_ISSET_FLAGS(p->greh)) { + if (GREV1_FLAG_ISSET_FLAGS(p->greh)) { ENGINE_SET_INVALID_EVENT(p, GRE_VERSION0_FLAGS); return TM_ECODE_OK; } @@ -101,18 +99,15 @@ int DecodeGRE(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, const uint8_t *p if (GRE_FLAG_ISSET_CHKSUM(p->greh) || GRE_FLAG_ISSET_ROUTE(p->greh)) header_len += GRE_CHKSUM_LEN + GRE_OFFSET_LEN; - if (header_len > len) { + if (header_len > len) { ENGINE_SET_INVALID_EVENT(p, GRE_VERSION0_HDR_TOO_BIG); return TM_ECODE_OK; } - if (GRE_FLAG_ISSET_ROUTE(p->greh)) - { - while (1) - { + if (GRE_FLAG_ISSET_ROUTE(p->greh)) { + while (1) { if ((header_len + GRE_SRE_HDR_LEN) > len) { - ENGINE_SET_INVALID_EVENT(p, - GRE_VERSION0_MALFORMED_SRE_HDR); + ENGINE_SET_INVALID_EVENT(p, GRE_VERSION0_MALFORMED_SRE_HDR); return TM_ECODE_OK; } @@ -125,8 +120,7 @@ int DecodeGRE(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, const uint8_t *p header_len += gsre->sre_length; if (header_len > len) { - ENGINE_SET_INVALID_EVENT(p, - GRE_VERSION0_MALFORMED_SRE_HDR); + ENGINE_SET_INVALID_EVENT(p, GRE_VERSION0_MALFORMED_SRE_HDR); return TM_ECODE_OK; } } @@ -144,38 +138,38 @@ int DecodeGRE(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, const uint8_t *p * further into it. */ - if (GRE_FLAG_ISSET_CHKSUM(p->greh)) { - ENGINE_SET_INVALID_EVENT(p,GRE_VERSION1_CHKSUM); + if (GRE_FLAG_ISSET_CHKSUM(p->greh)) { + ENGINE_SET_INVALID_EVENT(p, GRE_VERSION1_CHKSUM); return TM_ECODE_OK; } if (GRE_FLAG_ISSET_ROUTE(p->greh)) { - ENGINE_SET_INVALID_EVENT(p,GRE_VERSION1_ROUTE); + ENGINE_SET_INVALID_EVENT(p, GRE_VERSION1_ROUTE); return TM_ECODE_OK; } - if (GRE_FLAG_ISSET_SSR(p->greh)) { - ENGINE_SET_INVALID_EVENT(p,GRE_VERSION1_SSR); + if (GRE_FLAG_ISSET_SSR(p->greh)) { + ENGINE_SET_INVALID_EVENT(p, GRE_VERSION1_SSR); return TM_ECODE_OK; } if (GRE_FLAG_ISSET_RECUR(p->greh)) { - ENGINE_SET_INVALID_EVENT(p,GRE_VERSION1_RECUR); + ENGINE_SET_INVALID_EVENT(p, GRE_VERSION1_RECUR); return TM_ECODE_OK; } - if (GREV1_FLAG_ISSET_FLAGS(p->greh)) { - ENGINE_SET_INVALID_EVENT(p,GRE_VERSION1_FLAGS); + if (GREV1_FLAG_ISSET_FLAGS(p->greh)) { + ENGINE_SET_INVALID_EVENT(p, GRE_VERSION1_FLAGS); return TM_ECODE_OK; } - if (GRE_GET_PROTO(p->greh) != GRE_PROTO_PPP) { - ENGINE_SET_INVALID_EVENT(p,GRE_VERSION1_WRONG_PROTOCOL); + if (GRE_GET_PROTO(p->greh) != GRE_PROTO_PPP) { + ENGINE_SET_INVALID_EVENT(p, GRE_VERSION1_WRONG_PROTOCOL); return TM_ECODE_OK; } if (!(GRE_FLAG_ISSET_KY(p->greh))) { - ENGINE_SET_INVALID_EVENT(p,GRE_VERSION1_NO_KEY); + ENGINE_SET_INVALID_EVENT(p, GRE_VERSION1_NO_KEY); return TM_ECODE_OK; } @@ -191,7 +185,7 @@ int DecodeGRE(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, const uint8_t *p if (GREV1_FLAG_ISSET_ACK(p->greh)) header_len += GREV1_ACK_LEN; - if (header_len > len) { + if (header_len > len) { ENGINE_SET_INVALID_EVENT(p, GRE_VERSION1_HDR_TOO_BIG); return TM_ECODE_OK; } @@ -202,80 +196,71 @@ int DecodeGRE(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, const uint8_t *p return TM_ECODE_OK; } - switch (GRE_GET_PROTO(p->greh)) - { - case ETHERNET_TYPE_IP: - { - Packet *tp = PacketTunnelPktSetup(tv, dtv, p, pkt + header_len, - len - header_len, DECODE_TUNNEL_IPV4); + switch (GRE_GET_PROTO(p->greh)) { + case ETHERNET_TYPE_IP: { + Packet *tp = PacketTunnelPktSetup( + tv, dtv, p, pkt + header_len, len - header_len, DECODE_TUNNEL_IPV4); if (tp != NULL) { PKT_SET_SRC(tp, PKT_SRC_DECODER_GRE); - PacketEnqueueNoLock(&tv->decode_pq,tp); + PacketEnqueueNoLock(&tv->decode_pq, tp); } break; } - case GRE_PROTO_PPP: - { + case GRE_PROTO_PPP: { if (gre_pptp_h && !gre_pptp_h->payload_length) return TM_ECODE_OK; - Packet *tp = PacketTunnelPktSetup(tv, dtv, p, pkt + header_len, - len - header_len, DECODE_TUNNEL_PPP); + Packet *tp = PacketTunnelPktSetup( + tv, dtv, p, pkt + header_len, len - header_len, DECODE_TUNNEL_PPP); if (tp != NULL) { PKT_SET_SRC(tp, PKT_SRC_DECODER_GRE); - PacketEnqueueNoLock(&tv->decode_pq,tp); + PacketEnqueueNoLock(&tv->decode_pq, tp); } break; } - case ETHERNET_TYPE_IPV6: - { - Packet *tp = PacketTunnelPktSetup(tv, dtv, p, pkt + header_len, - len - header_len, DECODE_TUNNEL_IPV6); + case ETHERNET_TYPE_IPV6: { + Packet *tp = PacketTunnelPktSetup( + tv, dtv, p, pkt + header_len, len - header_len, DECODE_TUNNEL_IPV6); if (tp != NULL) { PKT_SET_SRC(tp, PKT_SRC_DECODER_GRE); - PacketEnqueueNoLock(&tv->decode_pq,tp); + PacketEnqueueNoLock(&tv->decode_pq, tp); } break; } - case ETHERNET_TYPE_VLAN: - { - Packet *tp = PacketTunnelPktSetup(tv, dtv, p, pkt + header_len, - len - header_len, DECODE_TUNNEL_VLAN); + case ETHERNET_TYPE_VLAN: { + Packet *tp = PacketTunnelPktSetup( + tv, dtv, p, pkt + header_len, len - header_len, DECODE_TUNNEL_VLAN); if (tp != NULL) { PKT_SET_SRC(tp, PKT_SRC_DECODER_GRE); - PacketEnqueueNoLock(&tv->decode_pq,tp); + PacketEnqueueNoLock(&tv->decode_pq, tp); } break; } - case ETHERNET_TYPE_ERSPAN: - { + case ETHERNET_TYPE_ERSPAN: { // Determine if it's Type I or Type II based on the flags in the GRE header. // Type I: 0|0|0|0|0|00000|000000000|00000 // Type II: 0|0|0|1|0|00000|000000000|00000 // Seq - Packet *tp = PacketTunnelPktSetup(tv, dtv, p, pkt + header_len, - len - header_len, - GRE_FLAG_ISSET_SQ(p->greh) == 0 ? - DECODE_TUNNEL_ERSPANI : - DECODE_TUNNEL_ERSPANII); + Packet *tp = PacketTunnelPktSetup(tv, dtv, p, pkt + header_len, len - header_len, + GRE_FLAG_ISSET_SQ(p->greh) == 0 ? DECODE_TUNNEL_ERSPANI + : DECODE_TUNNEL_ERSPANII); if (tp != NULL) { PKT_SET_SRC(tp, PKT_SRC_DECODER_GRE); - PacketEnqueueNoLock(&tv->decode_pq,tp); + PacketEnqueueNoLock(&tv->decode_pq, tp); } break; } - case ETHERNET_TYPE_BRIDGE: - { - Packet *tp = PacketTunnelPktSetup(tv, dtv, p, pkt + header_len, - len - header_len, DECODE_TUNNEL_ETHERNET); + case ETHERNET_TYPE_BRIDGE: { + Packet *tp = PacketTunnelPktSetup( + tv, dtv, p, pkt + header_len, len - header_len, DECODE_TUNNEL_ETHERNET); if (tp != NULL) { PKT_SET_SRC(tp, PKT_SRC_DECODER_GRE); - PacketEnqueueNoLock(&tv->decode_pq,tp); + PacketEnqueueNoLock(&tv->decode_pq, tp); } break; } @@ -286,13 +271,12 @@ int DecodeGRE(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, const uint8_t *p return TM_ECODE_OK; } - #ifdef UNITTESTS /** * \test DecodeGRETest01 is a test for small gre packet */ -static int DecodeGREtest01 (void) +static int DecodeGREtest01(void) { // clang-format off uint8_t raw_gre[] = { 0x00 ,0x6e ,0x62 }; @@ -316,7 +300,7 @@ static int DecodeGREtest01 (void) * \test DecodeGRETest02 is a test for wrong gre version */ -static int DecodeGREtest02 (void) +static int DecodeGREtest02(void) { // clang-format off uint8_t raw_gre[] = { @@ -350,12 +334,11 @@ static int DecodeGREtest02 (void) PASS; } - /** * \test DecodeGRETest03 is a test for valid gre packet */ -static int DecodeGREtest03 (void) +static int DecodeGREtest03(void) { // clang-format off uint8_t raw_gre[] = { diff --git a/src/decode-gre.h b/src/decode-gre.h index adf576fbd980..c9b383902732 100644 --- a/src/decode-gre.h +++ b/src/decode-gre.h @@ -30,11 +30,9 @@ #define IPPROTO_GRE 47 #endif - -typedef struct GREHdr_ -{ - uint8_t flags; /**< GRE packet flags */ - uint8_t version; /**< GRE version */ +typedef struct GREHdr_ { + uint8_t flags; /**< GRE packet flags */ + uint8_t version; /**< GRE version */ uint16_t ether_type; /**< ether type of the encapsulated traffic */ } __attribute__((__packed__)) GREHdr; @@ -49,40 +47,38 @@ typedef struct GREPPtPHdr_ { /* Generic Routing Encapsulation Source Route Entries (SREs). * The header is followed by a variable amount of Routing Information. */ -typedef struct GRESreHdr_ -{ +typedef struct GRESreHdr_ { uint16_t af; /**< Address family */ uint8_t sre_offset; uint8_t sre_length; } __attribute__((__packed__)) GRESreHdr; -#define GRE_VERSION_0 0x0000 -#define GRE_VERSION_1 0x0001 +#define GRE_VERSION_0 0x0000 +#define GRE_VERSION_1 0x0001 -#define GRE_HDR_LEN 4 -#define GRE_CHKSUM_LEN 2 -#define GRE_OFFSET_LEN 2 -#define GRE_KEY_LEN 4 -#define GRE_SEQ_LEN 4 -#define GRE_SRE_HDR_LEN 4 -#define GRE_PROTO_PPP 0x880b +#define GRE_HDR_LEN 4 +#define GRE_CHKSUM_LEN 2 +#define GRE_OFFSET_LEN 2 +#define GRE_KEY_LEN 4 +#define GRE_SEQ_LEN 4 +#define GRE_SRE_HDR_LEN 4 +#define GRE_PROTO_PPP 0x880b -#define GRE_FLAG_ISSET_CHKSUM(r) (r->flags & 0x80) -#define GRE_FLAG_ISSET_ROUTE(r) (r->flags & 0x40) -#define GRE_FLAG_ISSET_KY(r) (r->flags & 0x20) -#define GRE_FLAG_ISSET_SQ(r) (r->flags & 0x10) -#define GRE_FLAG_ISSET_SSR(r) (r->flags & 0x08) -#define GRE_FLAG_ISSET_RECUR(r) (r->flags & 0x07) -#define GRE_GET_VERSION(r) (r->version & 0x07) -#define GRE_GET_FLAGS(r) (r->version & 0xF8) -#define GRE_GET_PROTO(r) SCNtohs(r->ether_type) +#define GRE_FLAG_ISSET_CHKSUM(r) (r->flags & 0x80) +#define GRE_FLAG_ISSET_ROUTE(r) (r->flags & 0x40) +#define GRE_FLAG_ISSET_KY(r) (r->flags & 0x20) +#define GRE_FLAG_ISSET_SQ(r) (r->flags & 0x10) +#define GRE_FLAG_ISSET_SSR(r) (r->flags & 0x08) +#define GRE_FLAG_ISSET_RECUR(r) (r->flags & 0x07) +#define GRE_GET_VERSION(r) (r->version & 0x07) +#define GRE_GET_FLAGS(r) (r->version & 0xF8) +#define GRE_GET_PROTO(r) SCNtohs(r->ether_type) -#define GREV1_HDR_LEN 8 -#define GREV1_ACK_LEN 4 -#define GREV1_FLAG_ISSET_FLAGS(r) (r->version & 0x78) -#define GREV1_FLAG_ISSET_ACK(r) (r->version & 0x80) +#define GREV1_HDR_LEN 8 +#define GREV1_ACK_LEN 4 +#define GREV1_FLAG_ISSET_FLAGS(r) (r->version & 0x78) +#define GREV1_FLAG_ISSET_ACK(r) (r->version & 0x80) void DecodeGRERegisterTests(void); #endif /* __DECODE_GRE_H__ */ - diff --git a/src/decode-icmpv4.c b/src/decode-icmpv4.c index 8f179571c235..21e0e869129e 100644 --- a/src/decode-icmpv4.c +++ b/src/decode-icmpv4.c @@ -21,7 +21,6 @@ * @{ */ - /** * \file * @@ -48,7 +47,7 @@ /** * Note, this is the IP header, plus a bit of the original packet, not the whole thing! */ -static int DecodePartialIPV4(Packet* p, uint8_t* partial_packet, uint16_t len) +static int DecodePartialIPV4(Packet *p, uint8_t *partial_packet, uint16_t len) { /** Check the sizes, the header must fit at least */ if (len < IPV4_HEADER_LEN) { @@ -57,7 +56,7 @@ static int DecodePartialIPV4(Packet* p, uint8_t* partial_packet, uint16_t len) return -1; } - IPV4Hdr *icmp4_ip4h = (IPV4Hdr*)partial_packet; + IPV4Hdr *icmp4_ip4h = (IPV4Hdr *)partial_packet; /** Check the embedded version */ if (IPV4_GET_RAW_VER(icmp4_ip4h) != 4) { @@ -79,26 +78,26 @@ static int DecodePartialIPV4(Packet* p, uint8_t* partial_packet, uint16_t len) switch (IPV4_GET_RAW_IPPROTO(icmp4_ip4h)) { case IPPROTO_TCP: - if (len >= IPV4_HEADER_LEN + TCP_HEADER_LEN ) { - p->icmpv4vars.emb_tcph = (TCPHdr*)(partial_packet + IPV4_HEADER_LEN); + if (len >= IPV4_HEADER_LEN + TCP_HEADER_LEN) { + p->icmpv4vars.emb_tcph = (TCPHdr *)(partial_packet + IPV4_HEADER_LEN); p->icmpv4vars.emb_sport = SCNtohs(p->icmpv4vars.emb_tcph->th_sport); p->icmpv4vars.emb_dport = SCNtohs(p->icmpv4vars.emb_tcph->th_dport); p->icmpv4vars.emb_ip4_proto = IPPROTO_TCP; SCLogDebug("DecodePartialIPV4: ICMPV4->IPV4->TCP header sport: " - "%"PRIu16" dport %"PRIu16"", p->icmpv4vars.emb_sport, - p->icmpv4vars.emb_dport); + "%" PRIu16 " dport %" PRIu16 "", + p->icmpv4vars.emb_sport, p->icmpv4vars.emb_dport); } else if (len >= IPV4_HEADER_LEN + 4) { /* only access th_sport and th_dport */ - TCPHdr *emb_tcph = (TCPHdr*)(partial_packet + IPV4_HEADER_LEN); + TCPHdr *emb_tcph = (TCPHdr *)(partial_packet + IPV4_HEADER_LEN); p->icmpv4vars.emb_tcph = NULL; p->icmpv4vars.emb_sport = SCNtohs(emb_tcph->th_sport); p->icmpv4vars.emb_dport = SCNtohs(emb_tcph->th_dport); p->icmpv4vars.emb_ip4_proto = IPPROTO_TCP; SCLogDebug("DecodePartialIPV4: ICMPV4->IPV4->TCP partial header sport: " - "%"PRIu16" dport %"PRIu16"", p->icmpv4vars.emb_sport, - p->icmpv4vars.emb_dport); + "%" PRIu16 " dport %" PRIu16 "", + p->icmpv4vars.emb_sport, p->icmpv4vars.emb_dport); } else { SCLogDebug("DecodePartialIPV4: Warning, ICMPV4->IPV4->TCP " "header Didn't fit in the packet!"); @@ -108,15 +107,15 @@ static int DecodePartialIPV4(Packet* p, uint8_t* partial_packet, uint16_t len) break; case IPPROTO_UDP: - if (len >= IPV4_HEADER_LEN + UDP_HEADER_LEN ) { - p->icmpv4vars.emb_udph = (UDPHdr*)(partial_packet + IPV4_HEADER_LEN); + if (len >= IPV4_HEADER_LEN + UDP_HEADER_LEN) { + p->icmpv4vars.emb_udph = (UDPHdr *)(partial_packet + IPV4_HEADER_LEN); p->icmpv4vars.emb_sport = SCNtohs(p->icmpv4vars.emb_udph->uh_sport); p->icmpv4vars.emb_dport = SCNtohs(p->icmpv4vars.emb_udph->uh_dport); p->icmpv4vars.emb_ip4_proto = IPPROTO_UDP; SCLogDebug("DecodePartialIPV4: ICMPV4->IPV4->UDP header sport: " - "%"PRIu16" dport %"PRIu16"", p->icmpv4vars.emb_sport, - p->icmpv4vars.emb_dport); + "%" PRIu16 " dport %" PRIu16 "", + p->icmpv4vars.emb_sport, p->icmpv4vars.emb_dport); } else { SCLogDebug("DecodePartialIPV4: Warning, ICMPV4->IPV4->UDP " "header Didn't fit in the packet!"); @@ -126,8 +125,8 @@ static int DecodePartialIPV4(Packet* p, uint8_t* partial_packet, uint16_t len) break; case IPPROTO_ICMP: - if (len >= IPV4_HEADER_LEN + ICMPV4_HEADER_LEN ) { - p->icmpv4vars.emb_icmpv4h = (ICMPV4Hdr*)(partial_packet + IPV4_HEADER_LEN); + if (len >= IPV4_HEADER_LEN + ICMPV4_HEADER_LEN) { + p->icmpv4vars.emb_icmpv4h = (ICMPV4Hdr *)(partial_packet + IPV4_HEADER_LEN); p->icmpv4vars.emb_sport = 0; p->icmpv4vars.emb_dport = 0; p->icmpv4vars.emb_ip4_proto = IPPROTO_ICMP; @@ -138,12 +137,12 @@ static int DecodePartialIPV4(Packet* p, uint8_t* partial_packet, uint16_t len) break; } - /* debug print */ + /* debug print */ #ifdef DEBUG char s[16], d[16]; PrintInet(AF_INET, &(p->icmpv4vars.emb_ip4_src), s, sizeof(s)); PrintInet(AF_INET, &(p->icmpv4vars.emb_ip4_dst), d, sizeof(d)); - SCLogDebug("ICMPv4 embedding IPV4 %s->%s - PROTO: %" PRIu32 " ID: %" PRIu32 "", s,d, + SCLogDebug("ICMPv4 embedding IPV4 %s->%s - PROTO: %" PRIu32 " ID: %" PRIu32 "", s, d, IPV4_GET_RAW_IPPROTO(icmp4_ip4h), IPV4_GET_RAW_IPID(icmp4_ip4h)); #endif @@ -175,22 +174,21 @@ int DecodeICMPV4(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, const uint8_t p->icmp_d.type = (uint8_t)ctype; } - ICMPV4ExtHdr* icmp4eh = (ICMPV4ExtHdr*) p->icmpv4h; + ICMPV4ExtHdr *icmp4eh = (ICMPV4ExtHdr *)p->icmpv4h; p->icmpv4vars.hlen = ICMPV4_HEADER_LEN; - switch (p->icmpv4h->type) - { + switch (p->icmpv4h->type) { case ICMP_ECHOREPLY: - p->icmpv4vars.id=icmp4eh->id; - p->icmpv4vars.seq=icmp4eh->seq; - if (p->icmpv4h->code!=0) { - ENGINE_SET_EVENT(p,ICMPV4_UNKNOWN_CODE); + p->icmpv4vars.id = icmp4eh->id; + p->icmpv4vars.seq = icmp4eh->seq; + if (p->icmpv4h->code != 0) { + ENGINE_SET_EVENT(p, ICMPV4_UNKNOWN_CODE); } break; case ICMP_DEST_UNREACH: if (p->icmpv4h->code > NR_ICMP_UNREACH) { - ENGINE_SET_EVENT(p,ICMPV4_UNKNOWN_CODE); + ENGINE_SET_EVENT(p, ICMPV4_UNKNOWN_CODE); } else { /* parse IP header plus 64 bytes */ if (len > ICMPV4_HEADER_PKT_OFFSET) { @@ -204,8 +202,8 @@ int DecodeICMPV4(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, const uint8_t break; case ICMP_SOURCE_QUENCH: - if (p->icmpv4h->code!=0) { - ENGINE_SET_EVENT(p,ICMPV4_UNKNOWN_CODE); + if (p->icmpv4h->code != 0) { + ENGINE_SET_EVENT(p, ICMPV4_UNKNOWN_CODE); } else { // parse IP header plus 64 bytes if (len >= ICMPV4_HEADER_PKT_OFFSET) { @@ -219,8 +217,8 @@ int DecodeICMPV4(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, const uint8_t break; case ICMP_REDIRECT: - if (p->icmpv4h->code>ICMP_REDIR_HOSTTOS) { - ENGINE_SET_EVENT(p,ICMPV4_UNKNOWN_CODE); + if (p->icmpv4h->code > ICMP_REDIR_HOSTTOS) { + ENGINE_SET_EVENT(p, ICMPV4_UNKNOWN_CODE); } else { // parse IP header plus 64 bytes if (len > ICMPV4_HEADER_PKT_OFFSET) { @@ -234,16 +232,16 @@ int DecodeICMPV4(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, const uint8_t break; case ICMP_ECHO: - p->icmpv4vars.id=icmp4eh->id; - p->icmpv4vars.seq=icmp4eh->seq; - if (p->icmpv4h->code!=0) { - ENGINE_SET_EVENT(p,ICMPV4_UNKNOWN_CODE); + p->icmpv4vars.id = icmp4eh->id; + p->icmpv4vars.seq = icmp4eh->seq; + if (p->icmpv4h->code != 0) { + ENGINE_SET_EVENT(p, ICMPV4_UNKNOWN_CODE); } break; case ICMP_TIME_EXCEEDED: - if (p->icmpv4h->code>ICMP_EXC_FRAGTIME) { - ENGINE_SET_EVENT(p,ICMPV4_UNKNOWN_CODE); + if (p->icmpv4h->code > ICMP_EXC_FRAGTIME) { + ENGINE_SET_EVENT(p, ICMPV4_UNKNOWN_CODE); } else { // parse IP header plus 64 bytes if (len > ICMPV4_HEADER_PKT_OFFSET) { @@ -257,8 +255,8 @@ int DecodeICMPV4(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, const uint8_t break; case ICMP_PARAMETERPROB: - if (p->icmpv4h->code!=0) { - ENGINE_SET_EVENT(p,ICMPV4_UNKNOWN_CODE); + if (p->icmpv4h->code != 0) { + ENGINE_SET_EVENT(p, ICMPV4_UNKNOWN_CODE); } else { // parse IP header plus 64 bytes if (len > ICMPV4_HEADER_PKT_OFFSET) { @@ -272,10 +270,10 @@ int DecodeICMPV4(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, const uint8_t break; case ICMP_TIMESTAMP: - p->icmpv4vars.id=icmp4eh->id; - p->icmpv4vars.seq=icmp4eh->seq; - if (p->icmpv4h->code!=0) { - ENGINE_SET_EVENT(p,ICMPV4_UNKNOWN_CODE); + p->icmpv4vars.id = icmp4eh->id; + p->icmpv4vars.seq = icmp4eh->seq; + if (p->icmpv4h->code != 0) { + ENGINE_SET_EVENT(p, ICMPV4_UNKNOWN_CODE); } if (len < (sizeof(ICMPV4Timestamp) + ICMPV4_HEADER_LEN)) { @@ -286,10 +284,10 @@ int DecodeICMPV4(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, const uint8_t break; case ICMP_TIMESTAMPREPLY: - p->icmpv4vars.id=icmp4eh->id; - p->icmpv4vars.seq=icmp4eh->seq; - if (p->icmpv4h->code!=0) { - ENGINE_SET_EVENT(p,ICMPV4_UNKNOWN_CODE); + p->icmpv4vars.id = icmp4eh->id; + p->icmpv4vars.seq = icmp4eh->seq; + if (p->icmpv4h->code != 0) { + ENGINE_SET_EVENT(p, ICMPV4_UNKNOWN_CODE); } if (len < (sizeof(ICMPV4Timestamp) + ICMPV4_HEADER_LEN)) { @@ -300,18 +298,18 @@ int DecodeICMPV4(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, const uint8_t break; case ICMP_INFO_REQUEST: - p->icmpv4vars.id=icmp4eh->id; - p->icmpv4vars.seq=icmp4eh->seq; - if (p->icmpv4h->code!=0) { - ENGINE_SET_EVENT(p,ICMPV4_UNKNOWN_CODE); + p->icmpv4vars.id = icmp4eh->id; + p->icmpv4vars.seq = icmp4eh->seq; + if (p->icmpv4h->code != 0) { + ENGINE_SET_EVENT(p, ICMPV4_UNKNOWN_CODE); } break; case ICMP_INFO_REPLY: - p->icmpv4vars.id=icmp4eh->id; - p->icmpv4vars.seq=icmp4eh->seq; - if (p->icmpv4h->code!=0) { - ENGINE_SET_EVENT(p,ICMPV4_UNKNOWN_CODE); + p->icmpv4vars.id = icmp4eh->id; + p->icmpv4vars.seq = icmp4eh->seq; + if (p->icmpv4h->code != 0) { + ENGINE_SET_EVENT(p, ICMPV4_UNKNOWN_CODE); } break; @@ -328,24 +326,23 @@ int DecodeICMPV4(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, const uint8_t } break; case ICMP_ADDRESS: - p->icmpv4vars.id=icmp4eh->id; - p->icmpv4vars.seq=icmp4eh->seq; - if (p->icmpv4h->code!=0) { - ENGINE_SET_EVENT(p,ICMPV4_UNKNOWN_CODE); + p->icmpv4vars.id = icmp4eh->id; + p->icmpv4vars.seq = icmp4eh->seq; + if (p->icmpv4h->code != 0) { + ENGINE_SET_EVENT(p, ICMPV4_UNKNOWN_CODE); } break; case ICMP_ADDRESSREPLY: - p->icmpv4vars.id=icmp4eh->id; - p->icmpv4vars.seq=icmp4eh->seq; - if (p->icmpv4h->code!=0) { - ENGINE_SET_EVENT(p,ICMPV4_UNKNOWN_CODE); + p->icmpv4vars.id = icmp4eh->id; + p->icmpv4vars.seq = icmp4eh->seq; + if (p->icmpv4h->code != 0) { + ENGINE_SET_EVENT(p, ICMPV4_UNKNOWN_CODE); } break; default: - ENGINE_SET_EVENT(p,ICMPV4_UNKNOWN_TYPE); - + ENGINE_SET_EVENT(p, ICMPV4_UNKNOWN_TYPE); } p->payload = (uint8_t *)pkt + p->icmpv4vars.hlen; @@ -359,13 +356,17 @@ int DecodeICMPV4(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, const uint8_t /** \retval type counterpart type or -1 */ int ICMPv4GetCounterpart(uint8_t type) { -#define CASE_CODE(t,r) case (t): return r; case (r): return t; +#define CASE_CODE(t, r) \ + case (t): \ + return r; \ + case (r): \ + return t; switch (type) { - CASE_CODE(ICMP_ECHO, ICMP_ECHOREPLY); - CASE_CODE(ICMP_TIMESTAMP, ICMP_TIMESTAMPREPLY); - CASE_CODE(ICMP_INFO_REQUEST, ICMP_INFO_REPLY); - CASE_CODE(ICMP_ROUTERSOLICIT, ICMP_ROUTERADVERT); - CASE_CODE(ICMP_ADDRESS, ICMP_ADDRESSREPLY); + CASE_CODE(ICMP_ECHO, ICMP_ECHOREPLY); + CASE_CODE(ICMP_TIMESTAMP, ICMP_TIMESTAMPREPLY); + CASE_CODE(ICMP_INFO_REQUEST, ICMP_INFO_REPLY); + CASE_CODE(ICMP_ROUTERSOLICIT, ICMP_ROUTERADVERT); + CASE_CODE(ICMP_ADDRESS, ICMP_ADDRESSREPLY); default: return -1; } @@ -416,8 +417,8 @@ static int DecodeICMPV4test01(void) DecodeICMPV4(&tv, &dtv, p, raw_icmpv4, sizeof(raw_icmpv4)); - if (NULL!=p->icmpv4h) { - if (p->icmpv4h->type==8 && p->icmpv4h->code==0) { + if (NULL != p->icmpv4h) { + if (p->icmpv4h->type == 8 && p->icmpv4h->code == 0) { ret = 1; } } @@ -468,8 +469,8 @@ static int DecodeICMPV4test02(void) DecodeICMPV4(&tv, &dtv, p, raw_icmpv4, sizeof(raw_icmpv4)); - if (NULL!=p->icmpv4h) { - if (p->icmpv4h->type==0 && p->icmpv4h->code==0) { + if (NULL != p->icmpv4h) { + if (p->icmpv4h->type == 0 && p->icmpv4h->code == 0) { ret = 1; } } @@ -519,22 +520,20 @@ static int DecodeICMPV4test03(void) DecodeICMPV4(&tv, &dtv, p, raw_icmpv4, sizeof(raw_icmpv4)); if (NULL == p->icmpv4h) { - printf("NULL == p->icmpv4h: "); + printf("NULL == p->icmpv4h: "); goto end; } /* check it's type 11 code 0 */ if (p->icmpv4h->type != 11 || p->icmpv4h->code != 0) { - printf("p->icmpv4h->type %u, p->icmpv4h->code %u: ", - p->icmpv4h->type, p->icmpv4h->code); + printf("p->icmpv4h->type %u, p->icmpv4h->code %u: ", p->icmpv4h->type, p->icmpv4h->code); goto end; } /* check it's source port 35602 to port 33450 */ - if (p->icmpv4vars.emb_sport != 35602 || - p->icmpv4vars.emb_dport != 33450) { - printf("p->icmpv4vars.emb_sport %u, p->icmpv4vars.emb_dport %u: ", - p->icmpv4vars.emb_sport, p->icmpv4vars.emb_dport); + if (p->icmpv4vars.emb_sport != 35602 || p->icmpv4vars.emb_dport != 33450) { + printf("p->icmpv4vars.emb_sport %u, p->icmpv4vars.emb_dport %u: ", p->icmpv4vars.emb_sport, + p->icmpv4vars.emb_dport); goto end; } @@ -547,9 +546,8 @@ static int DecodeICMPV4test03(void) /* ICMPv4 embedding IPV4 192.168.1.13->209.85.227.147 pass */ if (strcmp(s, "192.168.1.13") == 0 && strcmp(d, "209.85.227.147") == 0) { ret = 1; - } - else { - printf("s %s, d %s: ", s, d); + } else { + printf("s %s, d %s: ", s, d); } end: @@ -609,8 +607,7 @@ static int DecodeICMPV4test04(void) } /* check it's src port 45322 to dst port 50 */ - if (p->icmpv4vars.emb_sport != 45322 || - p->icmpv4vars.emb_dport != 50) { + if (p->icmpv4vars.emb_sport != 45322 || p->icmpv4vars.emb_dport != 50) { goto end; } @@ -680,8 +677,7 @@ static int DecodeICMPV4test05(void) } /* check it's src port 1048 to dst port 80 */ - if (p->icmpv4vars.emb_sport != 1048 || - p->icmpv4vars.emb_dport != 80) { + if (p->icmpv4vars.emb_sport != 1048 || p->icmpv4vars.emb_dport != 80) { goto end; } @@ -718,7 +714,7 @@ static int ICMPV4CalculateValidChecksumtest05(void) 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37}; // clang-format on - csum = *( ((uint16_t *)raw_icmpv4) + 1); + csum = *(((uint16_t *)raw_icmpv4) + 1); return (csum == ICMPV4CalculateChecksum((uint16_t *)raw_icmpv4, sizeof(raw_icmpv4))); } @@ -738,7 +734,7 @@ static int ICMPV4CalculateInvalidChecksumtest06(void) 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x38}; // clang-format on - csum = *( ((uint16_t *)raw_icmpv4) + 1); + csum = *(((uint16_t *)raw_icmpv4) + 1); return (csum != ICMPV4CalculateChecksum((uint16_t *)raw_icmpv4, sizeof(raw_icmpv4))); } @@ -759,7 +755,7 @@ static int ICMPV4InvalidType07(void) Packet *p = PacketGetFromAlloc(); if (unlikely(p == NULL)) - return 0; + return 0; ThreadVars tv; DecodeThreadVars dtv; int ret = 0; @@ -782,7 +778,7 @@ static int ICMPV4InvalidType07(void) DecodeICMPV4(&tv, &dtv, p, raw_icmpv4, sizeof(raw_icmpv4)); - if(ENGINE_ISSET_EVENT(p,ICMPV4_UNKNOWN_TYPE)) { + if (ENGINE_ISSET_EVENT(p, ICMPV4_UNKNOWN_TYPE)) { ret = 1; } @@ -827,8 +823,8 @@ static int DecodeICMPV4test08(void) DecodeICMPV4(&tv, &dtv, p, raw_icmpv4, sizeof(raw_icmpv4)); - if (NULL!=p->icmpv4h) { - if (p->icmpv4h->type==8 && p->icmpv4h->code==0) { + if (NULL != p->icmpv4h) { + if (p->icmpv4h->type == 8 && p->icmpv4h->code == 0) { ret = 1; } } @@ -850,10 +846,8 @@ void DecodeICMPV4RegisterTests(void) UtRegisterTest("DecodeICMPV4test03", DecodeICMPV4test03); UtRegisterTest("DecodeICMPV4test04", DecodeICMPV4test04); UtRegisterTest("DecodeICMPV4test05", DecodeICMPV4test05); - UtRegisterTest("ICMPV4CalculateValidChecksumtest05", - ICMPV4CalculateValidChecksumtest05); - UtRegisterTest("ICMPV4CalculateInvalidChecksumtest06", - ICMPV4CalculateInvalidChecksumtest06); + UtRegisterTest("ICMPV4CalculateValidChecksumtest05", ICMPV4CalculateValidChecksumtest05); + UtRegisterTest("ICMPV4CalculateInvalidChecksumtest06", ICMPV4CalculateInvalidChecksumtest06); UtRegisterTest("DecodeICMPV4InvalidType", ICMPV4InvalidType07); UtRegisterTest("DecodeICMPV4test08", DecodeICMPV4test08); #endif /* UNITTESTS */ diff --git a/src/decode-icmpv4.h b/src/decode-icmpv4.h index f3a94ad2e594..90977a9b2452 100644 --- a/src/decode-icmpv4.h +++ b/src/decode-icmpv4.h @@ -27,162 +27,158 @@ #include "decode-tcp.h" #include "decode-udp.h" -#define ICMPV4_HEADER_LEN 8 +#define ICMPV4_HEADER_LEN 8 #ifndef ICMP_ECHOREPLY -#define ICMP_ECHOREPLY 0 /* Echo Reply */ +#define ICMP_ECHOREPLY 0 /* Echo Reply */ #endif #ifndef ICMP_DEST_UNREACH -#define ICMP_DEST_UNREACH 3 /* Destination Unreachable */ +#define ICMP_DEST_UNREACH 3 /* Destination Unreachable */ #endif #ifndef ICMP_SOURCE_QUENCH -#define ICMP_SOURCE_QUENCH 4 /* Source Quench */ +#define ICMP_SOURCE_QUENCH 4 /* Source Quench */ #endif #ifndef ICMP_REDIRECT -#define ICMP_REDIRECT 5 /* Redirect (change route) */ +#define ICMP_REDIRECT 5 /* Redirect (change route) */ #endif #ifndef ICMP_ECHO -#define ICMP_ECHO 8 /* Echo Request */ +#define ICMP_ECHO 8 /* Echo Request */ #endif #ifndef ICMP_ROUTERADVERT -#define ICMP_ROUTERADVERT 9 +#define ICMP_ROUTERADVERT 9 #endif #ifndef ICMP_ROUTERSOLICIT -#define ICMP_ROUTERSOLICIT 10 +#define ICMP_ROUTERSOLICIT 10 #endif #ifndef ICMP_TIME_EXCEEDED -#define ICMP_TIME_EXCEEDED 11 /* Time Exceeded */ +#define ICMP_TIME_EXCEEDED 11 /* Time Exceeded */ #endif #ifndef ICMP_PARAMETERPROB -#define ICMP_PARAMETERPROB 12 /* Parameter Problem */ +#define ICMP_PARAMETERPROB 12 /* Parameter Problem */ #endif #ifndef ICMP_TIMESTAMP -#define ICMP_TIMESTAMP 13 /* Timestamp Request */ +#define ICMP_TIMESTAMP 13 /* Timestamp Request */ #endif #ifndef ICMP_TIMESTAMPREPLY -#define ICMP_TIMESTAMPREPLY 14 /* Timestamp Reply */ +#define ICMP_TIMESTAMPREPLY 14 /* Timestamp Reply */ #endif #ifndef ICMP_INFO_REQUEST -#define ICMP_INFO_REQUEST 15 /* Information Request */ +#define ICMP_INFO_REQUEST 15 /* Information Request */ #endif #ifndef ICMP_INFO_REPLY -#define ICMP_INFO_REPLY 16 /* Information Reply */ +#define ICMP_INFO_REPLY 16 /* Information Reply */ #endif #ifndef ICMP_ADDRESS -#define ICMP_ADDRESS 17 /* Address Mask Request */ +#define ICMP_ADDRESS 17 /* Address Mask Request */ #endif #ifndef ICMP_ADDRESSREPLY -#define ICMP_ADDRESSREPLY 18 /* Address Mask Reply */ +#define ICMP_ADDRESSREPLY 18 /* Address Mask Reply */ #endif #ifndef NR_ICMP_TYPES -#define NR_ICMP_TYPES 18 +#define NR_ICMP_TYPES 18 #endif - /* Codes for UNREACH. */ #ifndef ICMP_NET_UNREACH -#define ICMP_NET_UNREACH 0 /* Network Unreachable */ +#define ICMP_NET_UNREACH 0 /* Network Unreachable */ #endif #ifndef ICMP_HOST_UNREACH -#define ICMP_HOST_UNREACH 1 /* Host Unreachable */ +#define ICMP_HOST_UNREACH 1 /* Host Unreachable */ #endif #ifndef ICMP_PROT_UNREACH -#define ICMP_PROT_UNREACH 2 /* Protocol Unreachable */ +#define ICMP_PROT_UNREACH 2 /* Protocol Unreachable */ #endif #ifndef ICMP_PORT_UNREACH -#define ICMP_PORT_UNREACH 3 /* Port Unreachable */ +#define ICMP_PORT_UNREACH 3 /* Port Unreachable */ #endif #ifndef ICMP_FRAG_NEEDED -#define ICMP_FRAG_NEEDED 4 /* Fragmentation Needed/DF set */ +#define ICMP_FRAG_NEEDED 4 /* Fragmentation Needed/DF set */ #endif #ifndef ICMP_SR_FAILED -#define ICMP_SR_FAILED 5 /* Source Route failed */ +#define ICMP_SR_FAILED 5 /* Source Route failed */ #endif #ifndef ICMP_NET_UNKNOWN -#define ICMP_NET_UNKNOWN 6 +#define ICMP_NET_UNKNOWN 6 #endif #ifndef ICMP_HOST_UNKNOWN -#define ICMP_HOST_UNKNOWN 7 +#define ICMP_HOST_UNKNOWN 7 #endif #ifndef ICMP_HOST_ISOLATED -#define ICMP_HOST_ISOLATED 8 +#define ICMP_HOST_ISOLATED 8 #endif #ifndef ICMP_NET_ANO -#define ICMP_NET_ANO 9 +#define ICMP_NET_ANO 9 #endif #ifndef ICMP_HOST_ANO -#define ICMP_HOST_ANO 10 +#define ICMP_HOST_ANO 10 #endif #ifndef ICMP_NET_UNR_TOS -#define ICMP_NET_UNR_TOS 11 +#define ICMP_NET_UNR_TOS 11 #endif #ifndef ICMP_HOST_UNR_TOS -#define ICMP_HOST_UNR_TOS 12 +#define ICMP_HOST_UNR_TOS 12 #endif #ifndef ICMP_PKT_FILTERED -#define ICMP_PKT_FILTERED 13 /* Packet filtered */ +#define ICMP_PKT_FILTERED 13 /* Packet filtered */ #endif #ifndef ICMP_PREC_VIOLATION -#define ICMP_PREC_VIOLATION 14 /* Precedence violation */ +#define ICMP_PREC_VIOLATION 14 /* Precedence violation */ #endif #ifndef ICMP_PREC_CUTOFF -#define ICMP_PREC_CUTOFF 15 /* Precedence cut off */ +#define ICMP_PREC_CUTOFF 15 /* Precedence cut off */ #endif #ifndef NR_ICMP_UNREACH -#define NR_ICMP_UNREACH 15 /* instead of hardcoding immediate value */ +#define NR_ICMP_UNREACH 15 /* instead of hardcoding immediate value */ #endif /* Codes for REDIRECT. */ #ifndef ICMP_REDIR_NET -#define ICMP_REDIR_NET 0 /* Redirect Net */ +#define ICMP_REDIR_NET 0 /* Redirect Net */ #endif #ifndef ICMP_REDIR_HOST -#define ICMP_REDIR_HOST 1 /* Redirect Host */ +#define ICMP_REDIR_HOST 1 /* Redirect Host */ #endif #ifndef ICMP_REDIR_NETTOS -#define ICMP_REDIR_NETTOS 2 /* Redirect Net for TOS */ +#define ICMP_REDIR_NETTOS 2 /* Redirect Net for TOS */ #endif #ifndef ICMP_REDIR_HOSTTOS -#define ICMP_REDIR_HOSTTOS 3 /* Redirect Host for TOS */ +#define ICMP_REDIR_HOSTTOS 3 /* Redirect Host for TOS */ #endif /* Codes for TIME_EXCEEDED. */ #ifndef ICMP_EXC_TTL -#define ICMP_EXC_TTL 0 /* TTL count exceeded */ +#define ICMP_EXC_TTL 0 /* TTL count exceeded */ #endif #ifndef ICMP_EXC_FRAGTIME -#define ICMP_EXC_FRAGTIME 1 /* Fragment Reass time exceeded */ +#define ICMP_EXC_FRAGTIME 1 /* Fragment Reass time exceeded */ #endif /** marco for icmpv4 type access */ -#define ICMPV4_GET_TYPE(p) (p)->icmpv4h->type +#define ICMPV4_GET_TYPE(p) (p)->icmpv4h->type /** marco for icmpv4 code access */ -#define ICMPV4_GET_CODE(p) (p)->icmpv4h->code +#define ICMPV4_GET_CODE(p) (p)->icmpv4h->code /* ICMPv4 header structure */ -typedef struct ICMPV4Hdr_ -{ - uint8_t type; - uint8_t code; +typedef struct ICMPV4Hdr_ { + uint8_t type; + uint8_t code; uint16_t checksum; } __attribute__((__packed__)) ICMPV4Hdr; /* ICMPv4 header structure */ -typedef struct ICMPV4ExtHdr_ -{ - uint8_t type; - uint8_t code; +typedef struct ICMPV4ExtHdr_ { + uint8_t type; + uint8_t code; uint16_t checksum; uint16_t id; uint16_t seq; } ICMPV4ExtHdr; /* ICMPv4 vars */ -typedef struct ICMPV4Vars_ -{ - uint16_t id; - uint16_t seq; +typedef struct ICMPV4Vars_ { + uint16_t id; + uint16_t seq; /** Actual header length **/ uint16_t hlen; @@ -221,56 +217,54 @@ typedef struct ICMPV4Timestamp_ { uint32_t tx_ts; } __attribute__((__packed__)) ICMPV4Timestamp; -#define CLEAR_ICMPV4_PACKET(p) do { \ - (p)->level4_comp_csum = -1; \ - PACKET_CLEAR_L4VARS((p)); \ - (p)->icmpv4h = NULL; \ -} while(0) +#define CLEAR_ICMPV4_PACKET(p) \ + do { \ + (p)->level4_comp_csum = -1; \ + PACKET_CLEAR_L4VARS((p)); \ + (p)->icmpv4h = NULL; \ + } while (0) #define ICMPV4_HEADER_PKT_OFFSET 8 /** macro for icmpv4 "type" access */ -#define ICMPV4_GET_TYPE(p) (p)->icmpv4h->type +#define ICMPV4_GET_TYPE(p) (p)->icmpv4h->type /** macro for icmpv4 "code" access */ -#define ICMPV4_GET_CODE(p) (p)->icmpv4h->code +#define ICMPV4_GET_CODE(p) (p)->icmpv4h->code /** macro for icmpv4 "csum" access */ -#define ICMPV4_GET_RAW_CSUM(p) SCNtohs((p)->icmpv4h->checksum) -#define ICMPV4_GET_CSUM(p) (p)->icmpv4h->checksum +#define ICMPV4_GET_RAW_CSUM(p) SCNtohs((p)->icmpv4h->checksum) +#define ICMPV4_GET_CSUM(p) (p)->icmpv4h->checksum /* If message is informational */ /** macro for icmpv4 "id" access */ -#define ICMPV4_GET_ID(p) ((p)->icmpv4vars.id) +#define ICMPV4_GET_ID(p) ((p)->icmpv4vars.id) /** macro for icmpv4 "seq" access */ -#define ICMPV4_GET_SEQ(p) ((p)->icmpv4vars.seq) +#define ICMPV4_GET_SEQ(p) ((p)->icmpv4vars.seq) /* If message is Error */ /** macro for icmpv4 embedded "protocol" access */ -#define ICMPV4_GET_EMB_PROTO(p) (p)->icmpv4vars.emb_ip4_proto +#define ICMPV4_GET_EMB_PROTO(p) (p)->icmpv4vars.emb_ip4_proto /** macro for icmpv4 embedded "ipv4h" header access */ -#define ICMPV4_GET_EMB_IPV4(p) (p)->icmpv4vars.emb_ipv4h +#define ICMPV4_GET_EMB_IPV4(p) (p)->icmpv4vars.emb_ipv4h /** macro for icmpv4 embedded "tcph" header access */ -#define ICMPV4_GET_EMB_TCP(p) (p)->icmpv4vars.emb_tcph +#define ICMPV4_GET_EMB_TCP(p) (p)->icmpv4vars.emb_tcph /** macro for icmpv4 embedded "udph" header access */ -#define ICMPV4_GET_EMB_UDP(p) (p)->icmpv4vars.emb_udph +#define ICMPV4_GET_EMB_UDP(p) (p)->icmpv4vars.emb_udph /** macro for icmpv4 embedded "icmpv4h" header access */ -#define ICMPV4_GET_EMB_ICMPV4H(p) (p)->icmpv4vars.emb_icmpv4h +#define ICMPV4_GET_EMB_ICMPV4H(p) (p)->icmpv4vars.emb_icmpv4h /** macro for icmpv4 header length */ #define ICMPV4_GET_HLEN_ICMPV4H(p) (p)->icmpv4vars.hlen /** macro for checking if a ICMP DEST UNREACH packet is valid for use - * in other parts of the engine, such as the flow engine. + * in other parts of the engine, such as the flow engine. * * \warning use only _after_ the decoder has processed the packet */ -#define ICMPV4_DEST_UNREACH_IS_VALID(p) ( \ - (!((p)->flags & PKT_IS_INVALID)) && \ - ((p)->icmpv4h != NULL) && \ - (ICMPV4_GET_TYPE((p)) == ICMP_DEST_UNREACH) && \ - (ICMPV4_GET_EMB_IPV4((p)) != NULL) && \ - ((ICMPV4_GET_EMB_TCP((p)) != NULL) || \ - (ICMPV4_GET_EMB_UDP((p)) != NULL))) +#define ICMPV4_DEST_UNREACH_IS_VALID(p) \ + ((!((p)->flags & PKT_IS_INVALID)) && ((p)->icmpv4h != NULL) && \ + (ICMPV4_GET_TYPE((p)) == ICMP_DEST_UNREACH) && (ICMPV4_GET_EMB_IPV4((p)) != NULL) && \ + ((ICMPV4_GET_EMB_TCP((p)) != NULL) || (ICMPV4_GET_EMB_UDP((p)) != NULL))) /** * marco for checking if a ICMP packet is an error message or an @@ -281,11 +275,10 @@ typedef struct ICMPV4Timestamp_ { * stage so we can to a bit check instead of the more expensive * check below. */ -#define ICMPV4_IS_ERROR_MSG(p) (ICMPV4_GET_TYPE((p)) == ICMP_DEST_UNREACH || \ - ICMPV4_GET_TYPE((p)) == ICMP_SOURCE_QUENCH || \ - ICMPV4_GET_TYPE((p)) == ICMP_REDIRECT || \ - ICMPV4_GET_TYPE((p)) == ICMP_TIME_EXCEEDED || \ - ICMPV4_GET_TYPE((p)) == ICMP_PARAMETERPROB) +#define ICMPV4_IS_ERROR_MSG(p) \ + (ICMPV4_GET_TYPE((p)) == ICMP_DEST_UNREACH || ICMPV4_GET_TYPE((p)) == ICMP_SOURCE_QUENCH || \ + ICMPV4_GET_TYPE((p)) == ICMP_REDIRECT || ICMPV4_GET_TYPE((p)) == ICMP_TIME_EXCEEDED || \ + ICMPV4_GET_TYPE((p)) == ICMP_PARAMETERPROB) void DecodeICMPV4RegisterTests(void); @@ -308,20 +301,19 @@ static inline uint16_t ICMPV4CalculateChecksum(const uint16_t *pkt, uint16_t tle pkt += 2; while (tlen >= 32) { - csum += pkt[0] + pkt[1] + pkt[2] + pkt[3] + pkt[4] + pkt[5] + pkt[6] + - pkt[7] + pkt[8] + pkt[9] + pkt[10] + pkt[11] + pkt[12] + pkt[13] + - pkt[14] + pkt[15]; + csum += pkt[0] + pkt[1] + pkt[2] + pkt[3] + pkt[4] + pkt[5] + pkt[6] + pkt[7] + pkt[8] + + pkt[9] + pkt[10] + pkt[11] + pkt[12] + pkt[13] + pkt[14] + pkt[15]; tlen -= 32; pkt += 16; } - while(tlen >= 8) { + while (tlen >= 8) { csum += pkt[0] + pkt[1] + pkt[2] + pkt[3]; tlen -= 8; pkt += 4; } - while(tlen >= 4) { + while (tlen >= 4) { csum += pkt[0] + pkt[1]; tlen -= 4; pkt += 2; @@ -341,7 +333,7 @@ static inline uint16_t ICMPV4CalculateChecksum(const uint16_t *pkt, uint16_t tle csum = (csum >> 16) + (csum & 0x0000FFFF); csum += (csum >> 16); - return (uint16_t) ~csum; + return (uint16_t)~csum; } int ICMPv4GetCounterpart(uint8_t type); diff --git a/src/decode-icmpv6.c b/src/decode-icmpv6.c index c343539adec8..ecd1a5631264 100644 --- a/src/decode-icmpv6.c +++ b/src/decode-icmpv6.c @@ -21,7 +21,6 @@ * @{ */ - /** * \file * @@ -46,7 +45,7 @@ * * \retval void No return value */ -static void DecodePartialIPV6(Packet *p, uint8_t *partial_packet, uint16_t len ) +static void DecodePartialIPV6(Packet *p, uint8_t *partial_packet, uint16_t len) { /** Check the sizes, the header must fit at least */ if (len < IPV6_HEADER_LEN) { @@ -55,13 +54,12 @@ static void DecodePartialIPV6(Packet *p, uint8_t *partial_packet, uint16_t len ) return; } - IPV6Hdr *icmp6_ip6h = (IPV6Hdr*)partial_packet; + IPV6Hdr *icmp6_ip6h = (IPV6Hdr *)partial_packet; /** Check the embedded version */ - if(((icmp6_ip6h->s_ip6_vfc & 0xf0) >> 4) != 6) - { + if (((icmp6_ip6h->s_ip6_vfc & 0xf0) >> 4) != 6) { SCLogDebug("ICMPv6 contains Unknown IPV6 version " - "ICMPV6_IPV6_UNKNOWN_VER"); + "ICMPV6_IPV6_UNKNOWN_VER"); ENGINE_SET_INVALID_EVENT(p, ICMPV6_IPV6_UNKNOWN_VER); return; } @@ -85,14 +83,14 @@ static void DecodePartialIPV6(Packet *p, uint8_t *partial_packet, uint16_t len ) switch (icmp6_ip6h->s_ip6_nxt) { case IPPROTO_TCP: - if (len >= IPV6_HEADER_LEN + TCP_HEADER_LEN ) { - p->icmpv6vars.emb_tcph = (TCPHdr*)(partial_packet + IPV6_HEADER_LEN); + if (len >= IPV6_HEADER_LEN + TCP_HEADER_LEN) { + p->icmpv6vars.emb_tcph = (TCPHdr *)(partial_packet + IPV6_HEADER_LEN); p->icmpv6vars.emb_sport = p->icmpv6vars.emb_tcph->th_sport; p->icmpv6vars.emb_dport = p->icmpv6vars.emb_tcph->th_dport; SCLogDebug("ICMPV6->IPV6->TCP header sport: " - "%"PRIu16" dport %"PRIu16"", p->icmpv6vars.emb_sport, - p->icmpv6vars.emb_dport); + "%" PRIu16 " dport %" PRIu16 "", + p->icmpv6vars.emb_sport, p->icmpv6vars.emb_dport); } else { SCLogDebug("Warning, ICMPV6->IPV6->TCP " "header Didn't fit in the packet!"); @@ -102,14 +100,14 @@ static void DecodePartialIPV6(Packet *p, uint8_t *partial_packet, uint16_t len ) break; case IPPROTO_UDP: - if (len >= IPV6_HEADER_LEN + UDP_HEADER_LEN ) { - p->icmpv6vars.emb_udph = (UDPHdr*)(partial_packet + IPV6_HEADER_LEN); + if (len >= IPV6_HEADER_LEN + UDP_HEADER_LEN) { + p->icmpv6vars.emb_udph = (UDPHdr *)(partial_packet + IPV6_HEADER_LEN); p->icmpv6vars.emb_sport = p->icmpv6vars.emb_udph->uh_sport; p->icmpv6vars.emb_dport = p->icmpv6vars.emb_udph->uh_dport; SCLogDebug("ICMPV6->IPV6->UDP header sport: " - "%"PRIu16" dport %"PRIu16"", p->icmpv6vars.emb_sport, - p->icmpv6vars.emb_dport); + "%" PRIu16 " dport %" PRIu16 "", + p->icmpv6vars.emb_sport, p->icmpv6vars.emb_dport); } else { SCLogDebug("Warning, ICMPV6->IPV6->UDP " "header Didn't fit in the packet!"); @@ -119,7 +117,7 @@ static void DecodePartialIPV6(Packet *p, uint8_t *partial_packet, uint16_t len ) break; case IPPROTO_ICMPV6: - p->icmpv6vars.emb_icmpv6h = (ICMPV6Hdr*)(partial_packet + IPV6_HEADER_LEN); + p->icmpv6vars.emb_icmpv6h = (ICMPV6Hdr *)(partial_packet + IPV6_HEADER_LEN); p->icmpv6vars.emb_sport = 0; p->icmpv6vars.emb_dport = 0; @@ -128,15 +126,16 @@ static void DecodePartialIPV6(Packet *p, uint8_t *partial_packet, uint16_t len ) break; } - /* debug print */ + /* debug print */ #ifdef DEBUG char s[46], d[46]; PrintInet(AF_INET6, (const void *)p->icmpv6vars.emb_ip6_src, s, sizeof(s)); PrintInet(AF_INET6, (const void *)p->icmpv6vars.emb_ip6_dst, d, sizeof(d)); SCLogDebug("ICMPv6 embedding IPV6 %s->%s - CLASS: %" PRIu32 " FLOW: " "%" PRIu32 " NH: %" PRIu32 " PLEN: %" PRIu32 " HLIM: %" PRIu32, - s, d, IPV6_GET_RAW_CLASS(icmp6_ip6h), IPV6_GET_RAW_FLOW(icmp6_ip6h), - IPV6_GET_RAW_NH(icmp6_ip6h), IPV6_GET_RAW_PLEN(icmp6_ip6h), IPV6_GET_RAW_HLIM(icmp6_ip6h)); + s, d, IPV6_GET_RAW_CLASS(icmp6_ip6h), IPV6_GET_RAW_FLOW(icmp6_ip6h), + IPV6_GET_RAW_NH(icmp6_ip6h), IPV6_GET_RAW_PLEN(icmp6_ip6h), + IPV6_GET_RAW_HLIM(icmp6_ip6h)); #endif return; @@ -145,19 +144,23 @@ static void DecodePartialIPV6(Packet *p, uint8_t *partial_packet, uint16_t len ) /** \retval type counterpart type or -1 */ int ICMPv6GetCounterpart(uint8_t type) { -#define CASE_CODE(t,r) case (t): return r; case (r): return t; +#define CASE_CODE(t, r) \ + case (t): \ + return r; \ + case (r): \ + return t; switch (type) { - CASE_CODE(ICMP6_ECHO_REQUEST, ICMP6_ECHO_REPLY); - CASE_CODE(ND_NEIGHBOR_SOLICIT, ND_NEIGHBOR_ADVERT); - CASE_CODE(ND_ROUTER_SOLICIT, ND_ROUTER_ADVERT); - CASE_CODE(MLD_LISTENER_QUERY, MLD_LISTENER_REPORT); - CASE_CODE(ICMP6_NI_QUERY, ICMP6_NI_REPLY); - CASE_CODE(HOME_AGENT_AD_REQUEST,HOME_AGENT_AD_REPLY); - - CASE_CODE(MOBILE_PREFIX_SOLICIT,MOBILE_PREFIX_ADVERT); - CASE_CODE(CERT_PATH_SOLICIT, CERT_PATH_ADVERT); - CASE_CODE(MC_ROUTER_ADVERT, MC_ROUTER_SOLICIT); - CASE_CODE(DUPL_ADDR_REQUEST, DUPL_ADDR_CONFIRM); + CASE_CODE(ICMP6_ECHO_REQUEST, ICMP6_ECHO_REPLY); + CASE_CODE(ND_NEIGHBOR_SOLICIT, ND_NEIGHBOR_ADVERT); + CASE_CODE(ND_ROUTER_SOLICIT, ND_ROUTER_ADVERT); + CASE_CODE(MLD_LISTENER_QUERY, MLD_LISTENER_REPORT); + CASE_CODE(ICMP6_NI_QUERY, ICMP6_NI_REPLY); + CASE_CODE(HOME_AGENT_AD_REQUEST, HOME_AGENT_AD_REPLY); + + CASE_CODE(MOBILE_PREFIX_SOLICIT, MOBILE_PREFIX_ADVERT); + CASE_CODE(CERT_PATH_SOLICIT, CERT_PATH_ADVERT); + CASE_CODE(MC_ROUTER_ADVERT, MC_ROUTER_SOLICIT); + CASE_CODE(DUPL_ADDR_REQUEST, DUPL_ADDR_CONFIRM); default: return -1; } @@ -175,8 +178,7 @@ int ICMPv6GetCounterpart(uint8_t type) * * \retval void No return value */ -int DecodeICMPV6(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, - const uint8_t *pkt, uint32_t len) +int DecodeICMPV6(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, const uint8_t *pkt, uint32_t len) { int full_hdr = 0; StatsIncr(tv, dtv->counter_icmpv6); @@ -200,8 +202,7 @@ int DecodeICMPV6(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, p->icmp_d.type = (uint8_t)ctype; } - SCLogDebug("ICMPV6 TYPE %" PRIu32 " CODE %" PRIu32 "", p->icmpv6h->type, - p->icmpv6h->code); + SCLogDebug("ICMPV6 TYPE %" PRIu32 " CODE %" PRIu32 "", p->icmpv6h->type, p->icmpv6h->code); switch (ICMPV6_GET_TYPE(p)) { case ICMP6_DST_UNREACH: @@ -259,7 +260,7 @@ int DecodeICMPV6(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, if (unlikely(len > ICMPV6_HEADER_LEN + USHRT_MAX)) { return TM_ECODE_FAILED; } - p->icmpv6vars.error_ptr= ICMPV6_GET_ERROR_PTR(p); + p->icmpv6vars.error_ptr = ICMPV6_GET_ERROR_PTR(p); DecodePartialIPV6(p, (uint8_t *)(pkt + ICMPV6_HEADER_LEN), (uint16_t)(len - ICMPV6_HEADER_LEN)); full_hdr = 1; @@ -267,8 +268,8 @@ int DecodeICMPV6(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, break; case ICMP6_ECHO_REQUEST: - SCLogDebug("ICMP6_ECHO_REQUEST id: %u seq: %u", - p->icmpv6h->icmpv6b.icmpv6i.id, p->icmpv6h->icmpv6b.icmpv6i.seq); + SCLogDebug("ICMP6_ECHO_REQUEST id: %u seq: %u", p->icmpv6h->icmpv6b.icmpv6i.id, + p->icmpv6h->icmpv6b.icmpv6i.seq); if (ICMPV6_GET_CODE(p) != 0) { ENGINE_SET_EVENT(p, ICMPV6_UNKNOWN_CODE); @@ -280,8 +281,8 @@ int DecodeICMPV6(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, break; case ICMP6_ECHO_REPLY: - SCLogDebug("ICMP6_ECHO_REPLY id: %u seq: %u", - p->icmpv6h->icmpv6b.icmpv6i.id, p->icmpv6h->icmpv6b.icmpv6i.seq); + SCLogDebug("ICMP6_ECHO_REPLY id: %u seq: %u", p->icmpv6h->icmpv6b.icmpv6i.id, + p->icmpv6h->icmpv6b.icmpv6i.seq); if (ICMPV6_GET_CODE(p) != 0) { ENGINE_SET_EVENT(p, ICMPV6_UNKNOWN_CODE); @@ -476,21 +477,22 @@ int DecodeICMPV6(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, /* Various range taken from: * http://www.iana.org/assignments/icmpv6-parameters/icmpv6-parameters.xhtml#icmpv6-parameters-2 */ - if ((ICMPV6_GET_TYPE(p) > 4) && (ICMPV6_GET_TYPE(p) < 100)) { + if ((ICMPV6_GET_TYPE(p) > 4) && (ICMPV6_GET_TYPE(p) < 100)) { ENGINE_SET_EVENT(p, ICMPV6_UNASSIGNED_TYPE); - } else if ((ICMPV6_GET_TYPE(p) >= 100) && (ICMPV6_GET_TYPE(p) < 102)) { + } else if ((ICMPV6_GET_TYPE(p) >= 100) && (ICMPV6_GET_TYPE(p) < 102)) { ENGINE_SET_EVENT(p, ICMPV6_EXPERIMENTATION_TYPE); - } else if ((ICMPV6_GET_TYPE(p) >= 102) && (ICMPV6_GET_TYPE(p) < 127)) { + } else if ((ICMPV6_GET_TYPE(p) >= 102) && (ICMPV6_GET_TYPE(p) < 127)) { ENGINE_SET_EVENT(p, ICMPV6_UNASSIGNED_TYPE); - } else if ((ICMPV6_GET_TYPE(p) >= 160) && (ICMPV6_GET_TYPE(p) < 200)) { + } else if ((ICMPV6_GET_TYPE(p) >= 160) && (ICMPV6_GET_TYPE(p) < 200)) { ENGINE_SET_EVENT(p, ICMPV6_UNASSIGNED_TYPE); - } else if ((ICMPV6_GET_TYPE(p) >= 200) && (ICMPV6_GET_TYPE(p) < 202)) { + } else if ((ICMPV6_GET_TYPE(p) >= 200) && (ICMPV6_GET_TYPE(p) < 202)) { ENGINE_SET_EVENT(p, ICMPV6_EXPERIMENTATION_TYPE); } else if (ICMPV6_GET_TYPE(p) >= 202) { ENGINE_SET_EVENT(p, ICMPV6_UNASSIGNED_TYPE); } else { SCLogDebug("ICMPV6 Message type %" PRIu8 " not " - "implemented yet", ICMPV6_GET_TYPE(p)); + "implemented yet", + ICMPV6_GET_TYPE(p)); ENGINE_SET_EVENT(p, ICMPV6_UNKNOWN_TYPE); } } @@ -547,10 +549,10 @@ static int ICMPV6CalculateValidChecksumtest01(void) 0x08, 0x00}; // clang-format on - csum = *( ((uint16_t *)(raw_ipv6 + 56))); + csum = *(((uint16_t *)(raw_ipv6 + 56))); - FAIL_IF(csum != ICMPV6CalculateChecksum((uint16_t *)(raw_ipv6 + 14 + 8), - (uint16_t *)(raw_ipv6 + 54), 68)); + FAIL_IF(csum != ICMPV6CalculateChecksum( + (uint16_t *)(raw_ipv6 + 14 + 8), (uint16_t *)(raw_ipv6 + 54), 68)); PASS; } @@ -578,10 +580,10 @@ static int ICMPV6CalculateInvalidChecksumtest02(void) 0x08, 0x01}; // clang-format on - csum = *( ((uint16_t *)(raw_ipv6 + 56))); + csum = *(((uint16_t *)(raw_ipv6 + 56))); - FAIL_IF(csum == ICMPV6CalculateChecksum((uint16_t *)(raw_ipv6 + 14 + 8), - (uint16_t *)(raw_ipv6 + 54), 68)); + FAIL_IF(csum == ICMPV6CalculateChecksum( + (uint16_t *)(raw_ipv6 + 14 + 8), (uint16_t *)(raw_ipv6 + 54), 68)); PASS; } @@ -614,8 +616,8 @@ static int ICMPV6ParamProbTest01(void) DecodeThreadVars dtv; uint32_t *ipv6src; uint32_t *ipv6dst; - ipv6src = (uint32_t*) &raw_ipv6[8]; - ipv6dst = (uint32_t*) &raw_ipv6[24]; + ipv6src = (uint32_t *)&raw_ipv6[8]; + ipv6dst = (uint32_t *)&raw_ipv6[24]; memset(&tv, 0, sizeof(ThreadVars)); memset(&dtv, 0, sizeof(DecodeThreadVars)); @@ -628,13 +630,13 @@ static int ICMPV6ParamProbTest01(void) /* ICMPv6 not processed at all? */ FAIL_IF(ICMPV6_GET_TYPE(p) != 4 || ICMPV6_GET_CODE(p) != 0 || - ICMPV6_GET_EMB_PROTO(p) != IPPROTO_ICMPV6); + ICMPV6_GET_EMB_PROTO(p) != IPPROTO_ICMPV6); /* Let's check if we retrieved the embedded ipv6 addresses correctly */ - uint32_t i=0; + uint32_t i = 0; for (i = 0; i < 4; i++) { FAIL_IF(p->icmpv6vars.emb_ip6_src[i] != ipv6src[i] || - p->icmpv6vars.emb_ip6_dst[i] != ipv6dst[i]); + p->icmpv6vars.emb_ip6_dst[i] != ipv6dst[i]); } PacketRecycle(p); @@ -671,8 +673,8 @@ static int ICMPV6PktTooBigTest01(void) DecodeThreadVars dtv; uint32_t *ipv6src; uint32_t *ipv6dst; - ipv6src = (uint32_t*) &raw_ipv6[8]; - ipv6dst = (uint32_t*) &raw_ipv6[24]; + ipv6src = (uint32_t *)&raw_ipv6[8]; + ipv6dst = (uint32_t *)&raw_ipv6[24]; memset(&tv, 0, sizeof(ThreadVars)); memset(&dtv, 0, sizeof(DecodeThreadVars)); @@ -686,13 +688,13 @@ static int ICMPV6PktTooBigTest01(void) /* Note: it has an embedded ipv6 packet but no protocol after ipv6 * (IPPROTO_NONE) */ /* Check if ICMPv6 header was processed at all. */ - FAIL_IF(ICMPV6_GET_TYPE(p) != 2 || ICMPV6_GET_CODE(p) != 0 ); + FAIL_IF(ICMPV6_GET_TYPE(p) != 2 || ICMPV6_GET_CODE(p) != 0); /* Let's check if we retrieved the embedded ipv6 addresses correctly */ - uint32_t i=0; + uint32_t i = 0; for (i = 0; i < 4; i++) { FAIL_IF(p->icmpv6vars.emb_ip6_src[i] != ipv6src[i] || - p->icmpv6vars.emb_ip6_dst[i] != ipv6dst[i]); + p->icmpv6vars.emb_ip6_dst[i] != ipv6dst[i]); } SCLogDebug("ICMPV6 IPV6 src and dst properly set"); @@ -731,8 +733,8 @@ static int ICMPV6TimeExceedTest01(void) DecodeThreadVars dtv; uint32_t *ipv6src; uint32_t *ipv6dst; - ipv6src = (uint32_t*) &raw_ipv6[8]; - ipv6dst = (uint32_t*) &raw_ipv6[24]; + ipv6src = (uint32_t *)&raw_ipv6[8]; + ipv6dst = (uint32_t *)&raw_ipv6[24]; memset(&tv, 0, sizeof(ThreadVars)); memset(&dtv, 0, sizeof(DecodeThreadVars)); @@ -744,15 +746,14 @@ static int ICMPV6TimeExceedTest01(void) FAIL_IF_NULL(p->icmpv6h); /* Note: it has an embedded ipv6 packet but no protocol after ipv6 (IPPROTO_NONE) */ - FAIL_IF(ICMPV6_GET_TYPE(p) != 3 || ICMPV6_GET_CODE(p) != 0 || - ICMPV6_GET_EMB_IPV6(p) == NULL || - ICMPV6_GET_EMB_PROTO(p) != IPPROTO_NONE); + FAIL_IF(ICMPV6_GET_TYPE(p) != 3 || ICMPV6_GET_CODE(p) != 0 || ICMPV6_GET_EMB_IPV6(p) == NULL || + ICMPV6_GET_EMB_PROTO(p) != IPPROTO_NONE); /* Let's check if we retrieved the embedded ipv6 addresses correctly */ - uint32_t i=0; + uint32_t i = 0; for (i = 0; i < 4; i++) { FAIL_IF(p->icmpv6vars.emb_ip6_src[i] != ipv6src[i] || - p->icmpv6vars.emb_ip6_dst[i] != ipv6dst[i]); + p->icmpv6vars.emb_ip6_dst[i] != ipv6dst[i]); } SCLogDebug("ICMPV6 IPV6 src and dst properly set"); @@ -791,8 +792,8 @@ static int ICMPV6DestUnreachTest01(void) DecodeThreadVars dtv; uint32_t *ipv6src; uint32_t *ipv6dst; - ipv6src = (uint32_t*) &raw_ipv6[8]; - ipv6dst = (uint32_t*) &raw_ipv6[24]; + ipv6src = (uint32_t *)&raw_ipv6[8]; + ipv6dst = (uint32_t *)&raw_ipv6[24]; memset(&tv, 0, sizeof(ThreadVars)); memset(&dtv, 0, sizeof(DecodeThreadVars)); @@ -804,15 +805,14 @@ static int ICMPV6DestUnreachTest01(void) FAIL_IF_NULL(p->icmpv6h); /* Note: it has an embedded ipv6 packet but no protocol after ipv6 (IPPROTO_NONE) */ - FAIL_IF(ICMPV6_GET_TYPE(p) != 1 || ICMPV6_GET_CODE(p) != 0 || - ICMPV6_GET_EMB_IPV6(p) == NULL || - ICMPV6_GET_EMB_PROTO(p) != IPPROTO_NONE); + FAIL_IF(ICMPV6_GET_TYPE(p) != 1 || ICMPV6_GET_CODE(p) != 0 || ICMPV6_GET_EMB_IPV6(p) == NULL || + ICMPV6_GET_EMB_PROTO(p) != IPPROTO_NONE); /* Let's check if we retrieved the embedded ipv6 addresses correctly */ - uint32_t i=0; + uint32_t i = 0; for (i = 0; i < 4; i++) { FAIL_IF(p->icmpv6vars.emb_ip6_src[i] != ipv6src[i] || - p->icmpv6vars.emb_ip6_dst[i] != ipv6dst[i]); + p->icmpv6vars.emb_ip6_dst[i] != ipv6dst[i]); } PacketRecycle(p); @@ -853,8 +853,8 @@ static int ICMPV6EchoReqTest01(void) SCLogDebug("ID: %u seq: %u", ICMPV6_GET_ID(p), ICMPV6_GET_SEQ(p)); - if (ICMPV6_GET_TYPE(p) != 128 || ICMPV6_GET_CODE(p) != 0 || - SCNtohs(ICMPV6_GET_ID(p)) != 9712 || SCNtohs(ICMPV6_GET_SEQ(p)) != 29987) { + if (ICMPV6_GET_TYPE(p) != 128 || ICMPV6_GET_CODE(p) != 0 || SCNtohs(ICMPV6_GET_ID(p)) != 9712 || + SCNtohs(ICMPV6_GET_SEQ(p)) != 29987) { printf("ICMPv6 Echo reply decode failed TYPE %u CODE %u ID %04x(%u) SEQ %04x(%u): ", ICMPV6_GET_TYPE(p), ICMPV6_GET_CODE(p), ICMPV6_GET_ID(p), SCNtohs(ICMPV6_GET_ID(p)), ICMPV6_GET_SEQ(p), SCNtohs(ICMPV6_GET_SEQ(p))); @@ -898,11 +898,11 @@ static int ICMPV6EchoRepTest01(void) FAIL_IF_NULL(p->icmpv6h); - SCLogDebug("type: %u code %u ID: %u seq: %u", ICMPV6_GET_TYPE(p), - ICMPV6_GET_CODE(p),ICMPV6_GET_ID(p), ICMPV6_GET_SEQ(p)); + SCLogDebug("type: %u code %u ID: %u seq: %u", ICMPV6_GET_TYPE(p), ICMPV6_GET_CODE(p), + ICMPV6_GET_ID(p), ICMPV6_GET_SEQ(p)); - if (ICMPV6_GET_TYPE(p) != 129 || ICMPV6_GET_CODE(p) != 0 || - SCNtohs(ICMPV6_GET_ID(p)) != 9712 || SCNtohs(ICMPV6_GET_SEQ(p)) != 29987) { + if (ICMPV6_GET_TYPE(p) != 129 || ICMPV6_GET_CODE(p) != 0 || SCNtohs(ICMPV6_GET_ID(p)) != 9712 || + SCNtohs(ICMPV6_GET_SEQ(p)) != 29987) { printf("ICMPv6 Echo reply decode failed TYPE %u CODE %u ID %04x(%u) SEQ %04x(%u): ", ICMPV6_GET_TYPE(p), ICMPV6_GET_CODE(p), ICMPV6_GET_ID(p), SCNtohs(ICMPV6_GET_ID(p)), ICMPV6_GET_SEQ(p), SCNtohs(ICMPV6_GET_SEQ(p))); @@ -916,8 +916,8 @@ static int ICMPV6EchoRepTest01(void) } /** \test icmpv6 message type: parameter problem, invalid packet - * \brief set the event ICMPV6_IPV6_UNKNOWN_VER properly when the embedded packet has an unknown version - * \retval retval 0 = Error ; 1 = ok + * \brief set the event ICMPV6_IPV6_UNKNOWN_VER properly when the embedded packet has an unknown + * version \retval retval 0 = Error ; 1 = ok */ static int ICMPV6ParamProbTest02(void) { @@ -1587,10 +1587,10 @@ static int ICMPV6CalculateValidChecksumWithFCS(void) FAIL_IF_NULL(p->icmpv6h); uint16_t icmpv6_len = IPV6_GET_RAW_PLEN(p->ip6h) - - ((uint8_t *)p->icmpv6h - (uint8_t *)p->ip6h - IPV6_HEADER_LEN); + ((uint8_t *)p->icmpv6h - (uint8_t *)p->ip6h - IPV6_HEADER_LEN); FAIL_IF(icmpv6_len != 28); - FAIL_IF(ICMPV6CalculateChecksum(p->ip6h->s_ip6_addrs, - (uint16_t *)p->icmpv6h, icmpv6_len) != csum); + FAIL_IF(ICMPV6CalculateChecksum(p->ip6h->s_ip6_addrs, (uint16_t *)p->icmpv6h, icmpv6_len) != + csum); PacketRecycle(p); FlowShutdown(); @@ -1606,8 +1606,7 @@ static int ICMPV6CalculateValidChecksumWithFCS(void) void DecodeICMPV6RegisterTests(void) { #ifdef UNITTESTS - UtRegisterTest("ICMPV6CalculateValidChecksumtest01", - ICMPV6CalculateValidChecksumtest01); + UtRegisterTest("ICMPV6CalculateValidChecksumtest01", ICMPV6CalculateValidChecksumtest01); UtRegisterTest("ICMPV6CalculateInvalidChecksumtest02", ICMPV6CalculateInvalidChecksumtest02); UtRegisterTest("ICMPV6ParamProbTest01 (Valid)", ICMPV6ParamProbTest01); @@ -1618,8 +1617,7 @@ void DecodeICMPV6RegisterTests(void) UtRegisterTest("ICMPV6EchoRepTest01 (Valid)", ICMPV6EchoRepTest01); UtRegisterTest("ICMPV6ParamProbTest02 (Invalid)", ICMPV6ParamProbTest02); - UtRegisterTest("ICMPV6DestUnreachTest02 (Invalid)", - ICMPV6DestUnreachTest02); + UtRegisterTest("ICMPV6DestUnreachTest02 (Invalid)", ICMPV6DestUnreachTest02); UtRegisterTest("ICMPV6PktTooBigTest02 (Invalid)", ICMPV6PktTooBigTest02); UtRegisterTest("ICMPV6TimeExceedTest02 (Invalid)", ICMPV6TimeExceedTest02); UtRegisterTest("ICMPV6EchoReqTest02 (Invalid)", ICMPV6EchoReqTest02); @@ -1627,29 +1625,19 @@ void DecodeICMPV6RegisterTests(void) UtRegisterTest("ICMPV6PayloadTest01", ICMPV6PayloadTest01); - UtRegisterTest("ICMPV6RouterSolicitTestKnownCode", - ICMPV6RouterSolicitTestKnownCode); - UtRegisterTest("ICMPV6RouterSolicitTestUnknownCode", - ICMPV6RouterSolicitTestUnknownCode); - UtRegisterTest("ICMPV6RouterAdvertTestKnownCode", - ICMPV6RouterAdvertTestKnownCode); - UtRegisterTest("ICMPV6RouterAdvertTestUnknownCode", - ICMPV6RouterAdvertTestUnknownCode); - - UtRegisterTest("ICMPV6NeighbourSolicitTestKnownCode", - ICMPV6NeighbourSolicitTestKnownCode); - UtRegisterTest("ICMPV6NeighbourSolicitTestUnknownCode", - ICMPV6NeighbourSolicitTestUnknownCode); - UtRegisterTest("ICMPV6NeighbourAdvertTestKnownCode", - ICMPV6NeighbourAdvertTestKnownCode); - UtRegisterTest("ICMPV6NeighbourAdvertTestUnknownCode", - ICMPV6NeighbourAdvertTestUnknownCode); + UtRegisterTest("ICMPV6RouterSolicitTestKnownCode", ICMPV6RouterSolicitTestKnownCode); + UtRegisterTest("ICMPV6RouterSolicitTestUnknownCode", ICMPV6RouterSolicitTestUnknownCode); + UtRegisterTest("ICMPV6RouterAdvertTestKnownCode", ICMPV6RouterAdvertTestKnownCode); + UtRegisterTest("ICMPV6RouterAdvertTestUnknownCode", ICMPV6RouterAdvertTestUnknownCode); + + UtRegisterTest("ICMPV6NeighbourSolicitTestKnownCode", ICMPV6NeighbourSolicitTestKnownCode); + UtRegisterTest("ICMPV6NeighbourSolicitTestUnknownCode", ICMPV6NeighbourSolicitTestUnknownCode); + UtRegisterTest("ICMPV6NeighbourAdvertTestKnownCode", ICMPV6NeighbourAdvertTestKnownCode); + UtRegisterTest("ICMPV6NeighbourAdvertTestUnknownCode", ICMPV6NeighbourAdvertTestUnknownCode); UtRegisterTest("ICMPV6RedirectTestKnownCode", ICMPV6RedirectTestKnownCode); - UtRegisterTest("ICMPV6RedirectTestUnknownCode", - ICMPV6RedirectTestUnknownCode); - UtRegisterTest("ICMPV6CalculateValidChecksumWithFCS", - ICMPV6CalculateValidChecksumWithFCS); + UtRegisterTest("ICMPV6RedirectTestUnknownCode", ICMPV6RedirectTestUnknownCode); + UtRegisterTest("ICMPV6CalculateValidChecksumWithFCS", ICMPV6CalculateValidChecksumWithFCS); #endif /* UNITTESTS */ } /** diff --git a/src/decode-icmpv6.h b/src/decode-icmpv6.h index aa66c1f64a3e..c0326a5191bf 100644 --- a/src/decode-icmpv6.h +++ b/src/decode-icmpv6.h @@ -28,142 +28,137 @@ #include "decode-udp.h" #include "decode-ipv6.h" -#define ICMPV6_HEADER_LEN 8 +#define ICMPV6_HEADER_LEN 8 #define ICMPV6_HEADER_PKT_OFFSET 8 /** ICMPV6 Message Types: */ /** Error Messages: (type <128) */ -#define ICMP6_DST_UNREACH 1 -#define ICMP6_PACKET_TOO_BIG 2 -#define ICMP6_TIME_EXCEEDED 3 -#define ICMP6_PARAM_PROB 4 +#define ICMP6_DST_UNREACH 1 +#define ICMP6_PACKET_TOO_BIG 2 +#define ICMP6_TIME_EXCEEDED 3 +#define ICMP6_PARAM_PROB 4 /** Informational Messages (type>=128) */ -#define ICMP6_ECHO_REQUEST 128 -#define ICMP6_ECHO_REPLY 129 - -#define MLD_LISTENER_QUERY 130 -#define MLD_LISTENER_REPORT 131 -#define MLD_LISTENER_REDUCTION 132 - -#define ND_ROUTER_SOLICIT 133 -#define ND_ROUTER_ADVERT 134 -#define ND_NEIGHBOR_SOLICIT 135 -#define ND_NEIGHBOR_ADVERT 136 -#define ND_REDIRECT 137 - -#define ICMP6_RR 138 -#define ICMP6_NI_QUERY 139 -#define ICMP6_NI_REPLY 140 -#define ND_INVERSE_SOLICIT 141 -#define ND_INVERSE_ADVERT 142 -#define MLD_V2_LIST_REPORT 143 -#define HOME_AGENT_AD_REQUEST 144 -#define HOME_AGENT_AD_REPLY 145 -#define MOBILE_PREFIX_SOLICIT 146 -#define MOBILE_PREFIX_ADVERT 147 -#define CERT_PATH_SOLICIT 148 -#define CERT_PATH_ADVERT 149 -#define ICMP6_MOBILE_EXPERIMENTAL 150 -#define MC_ROUTER_ADVERT 151 -#define MC_ROUTER_SOLICIT 152 -#define MC_ROUTER_TERMINATE 153 -#define FMIPV6_MSG 154 -#define RPL_CONTROL_MSG 155 -#define LOCATOR_UDATE_MSG 156 -#define DUPL_ADDR_REQUEST 157 -#define DUPL_ADDR_CONFIRM 158 -#define MPL_CONTROL_MSG 159 +#define ICMP6_ECHO_REQUEST 128 +#define ICMP6_ECHO_REPLY 129 + +#define MLD_LISTENER_QUERY 130 +#define MLD_LISTENER_REPORT 131 +#define MLD_LISTENER_REDUCTION 132 + +#define ND_ROUTER_SOLICIT 133 +#define ND_ROUTER_ADVERT 134 +#define ND_NEIGHBOR_SOLICIT 135 +#define ND_NEIGHBOR_ADVERT 136 +#define ND_REDIRECT 137 + +#define ICMP6_RR 138 +#define ICMP6_NI_QUERY 139 +#define ICMP6_NI_REPLY 140 +#define ND_INVERSE_SOLICIT 141 +#define ND_INVERSE_ADVERT 142 +#define MLD_V2_LIST_REPORT 143 +#define HOME_AGENT_AD_REQUEST 144 +#define HOME_AGENT_AD_REPLY 145 +#define MOBILE_PREFIX_SOLICIT 146 +#define MOBILE_PREFIX_ADVERT 147 +#define CERT_PATH_SOLICIT 148 +#define CERT_PATH_ADVERT 149 +#define ICMP6_MOBILE_EXPERIMENTAL 150 +#define MC_ROUTER_ADVERT 151 +#define MC_ROUTER_SOLICIT 152 +#define MC_ROUTER_TERMINATE 153 +#define FMIPV6_MSG 154 +#define RPL_CONTROL_MSG 155 +#define LOCATOR_UDATE_MSG 156 +#define DUPL_ADDR_REQUEST 157 +#define DUPL_ADDR_CONFIRM 158 +#define MPL_CONTROL_MSG 159 /** Destination Unreachable Message (type=1) Code: */ -#define ICMP6_DST_UNREACH_NOROUTE 0 /* no route to destination */ -#define ICMP6_DST_UNREACH_ADMIN 1 /* communication with destination */ - /* administratively prohibited */ -#define ICMP6_DST_UNREACH_BEYONDSCOPE 2 /* beyond scope of source address */ -#define ICMP6_DST_UNREACH_ADDR 3 /* address unreachable */ -#define ICMP6_DST_UNREACH_NOPORT 4 /* bad port */ -#define ICMP6_DST_UNREACH_FAILEDPOLICY 5 /* Source address failed ingress/egress policy */ -#define ICMP6_DST_UNREACH_REJECTROUTE 6 /* Reject route to destination */ - +#define ICMP6_DST_UNREACH_NOROUTE 0 /* no route to destination */ +#define ICMP6_DST_UNREACH_ADMIN 1 /* communication with destination */ + /* administratively prohibited */ +#define ICMP6_DST_UNREACH_BEYONDSCOPE 2 /* beyond scope of source address */ +#define ICMP6_DST_UNREACH_ADDR 3 /* address unreachable */ +#define ICMP6_DST_UNREACH_NOPORT 4 /* bad port */ +#define ICMP6_DST_UNREACH_FAILEDPOLICY 5 /* Source address failed ingress/egress policy */ +#define ICMP6_DST_UNREACH_REJECTROUTE 6 /* Reject route to destination */ /** Time Exceeded Message (type=3) Code: */ -#define ICMP6_TIME_EXCEED_TRANSIT 0 /* Hop Limit == 0 in transit */ -#define ICMP6_TIME_EXCEED_REASSEMBLY 1 /* Reassembly time out */ +#define ICMP6_TIME_EXCEED_TRANSIT 0 /* Hop Limit == 0 in transit */ +#define ICMP6_TIME_EXCEED_REASSEMBLY 1 /* Reassembly time out */ /** Parameter Problem Message (type=4) Code: */ -#define ICMP6_PARAMPROB_HEADER 0 /* erroneous header field */ -#define ICMP6_PARAMPROB_NEXTHEADER 1 /* unrecognized Next Header */ -#define ICMP6_PARAMPROB_OPTION 2 /* unrecognized IPv6 option */ - +#define ICMP6_PARAMPROB_HEADER 0 /* erroneous header field */ +#define ICMP6_PARAMPROB_NEXTHEADER 1 /* unrecognized Next Header */ +#define ICMP6_PARAMPROB_OPTION 2 /* unrecognized IPv6 option */ /** macro for icmpv6 "type" access */ -#define ICMPV6_GET_TYPE(p) (p)->icmpv6h->type +#define ICMPV6_GET_TYPE(p) (p)->icmpv6h->type /** macro for icmpv6 "code" access */ -#define ICMPV6_GET_CODE(p) (p)->icmpv6h->code +#define ICMPV6_GET_CODE(p) (p)->icmpv6h->code /** macro for icmpv6 "csum" access */ -#define ICMPV6_GET_RAW_CSUM(p) SCNtohs((p)->icmpv6h->csum) -#define ICMPV6_GET_CSUM(p) (p)->icmpv6h->csum +#define ICMPV6_GET_RAW_CSUM(p) SCNtohs((p)->icmpv6h->csum) +#define ICMPV6_GET_CSUM(p) (p)->icmpv6h->csum /** If message is informational */ /** macro for icmpv6 "id" access */ -#define ICMPV6_GET_ID(p) (p)->icmpv6vars.id +#define ICMPV6_GET_ID(p) (p)->icmpv6vars.id /** macro for icmpv6 "seq" access */ -#define ICMPV6_GET_SEQ(p) (p)->icmpv6vars.seq +#define ICMPV6_GET_SEQ(p) (p)->icmpv6vars.seq /** If message is Error */ /** macro for icmpv6 "unused" access */ -#define ICMPV6_GET_UNUSED(p) (p)->icmpv6h->icmpv6b.icmpv6e.unused +#define ICMPV6_GET_UNUSED(p) (p)->icmpv6h->icmpv6b.icmpv6e.unused /** macro for icmpv6 "error_ptr" access */ -#define ICMPV6_GET_ERROR_PTR(p) (p)->icmpv6h->icmpv6b.icmpv6e.error_ptr +#define ICMPV6_GET_ERROR_PTR(p) (p)->icmpv6h->icmpv6b.icmpv6e.error_ptr /** macro for icmpv6 "mtu" accessibility */ // ICMPv6 has MTU only for type too big -#define ICMPV6_HAS_MTU(p) ((p)->icmpv6h->type == ICMP6_PACKET_TOO_BIG) +#define ICMPV6_HAS_MTU(p) ((p)->icmpv6h->type == ICMP6_PACKET_TOO_BIG) /** macro for icmpv6 "mtu" access */ -#define ICMPV6_GET_MTU(p) SCNtohl((p)->icmpv6h->icmpv6b.icmpv6e.mtu) +#define ICMPV6_GET_MTU(p) SCNtohl((p)->icmpv6h->icmpv6b.icmpv6e.mtu) /** macro for icmpv6 embedded "protocol" access */ -#define ICMPV6_GET_EMB_PROTO(p) (p)->icmpv6vars.emb_ip6_proto_next +#define ICMPV6_GET_EMB_PROTO(p) (p)->icmpv6vars.emb_ip6_proto_next /** macro for icmpv6 embedded "ipv6h" header access */ -#define ICMPV6_GET_EMB_IPV6(p) (p)->icmpv6vars.emb_ipv6h +#define ICMPV6_GET_EMB_IPV6(p) (p)->icmpv6vars.emb_ipv6h /** macro for icmpv6 embedded "tcph" header access */ -#define ICMPV6_GET_EMB_TCP(p) (p)->icmpv6vars.emb_tcph +#define ICMPV6_GET_EMB_TCP(p) (p)->icmpv6vars.emb_tcph /** macro for icmpv6 embedded "udph" header access */ -#define ICMPV6_GET_EMB_UDP(p) (p)->icmpv6vars.emb_udph +#define ICMPV6_GET_EMB_UDP(p) (p)->icmpv6vars.emb_udph /** macro for icmpv6 embedded "icmpv6h" header access */ -#define ICMPV6_GET_EMB_icmpv6h(p) (p)->icmpv6vars.emb_icmpv6h +#define ICMPV6_GET_EMB_icmpv6h(p) (p)->icmpv6vars.emb_icmpv6h -typedef struct ICMPV6Info_ -{ - uint16_t id; - uint16_t seq; +typedef struct ICMPV6Info_ { + uint16_t id; + uint16_t seq; } ICMPV6Info; /** ICMPv6 header structure */ -typedef struct ICMPV6Hdr_ -{ - uint8_t type; - uint8_t code; +typedef struct ICMPV6Hdr_ { + uint8_t type; + uint8_t code; uint16_t csum; union { ICMPV6Info icmpv6i; /** Informational message */ - union - { - uint32_t unused; /** for types 1 and 3, should be zero */ - uint32_t error_ptr; /** for type 4, pointer to the octet that originate the error */ - uint32_t mtu; /** for type 2, the Maximum Transmission Unit of the next-hop link */ - } icmpv6e; /** Error Message */ + union { + uint32_t unused; /** for types 1 and 3, should be zero */ + uint32_t error_ptr; /** for type 4, pointer to the octet that originate the error */ + uint32_t mtu; /** for type 2, the Maximum Transmission Unit of the next-hop link */ + } icmpv6e; /** Error Message */ } icmpv6b; } ICMPV6Hdr; /** Data available from the decoded packet */ typedef struct ICMPV6Vars_ { /* checksum of the icmpv6 packet */ - uint16_t id; - uint16_t seq; - uint32_t mtu; - uint32_t error_ptr; + uint16_t id; + uint16_t seq; + uint32_t mtu; + uint32_t error_ptr; /** Pointers to the embedded packet headers */ IPV6Hdr *emb_ipv6h; @@ -182,12 +177,12 @@ typedef struct ICMPV6Vars_ { } ICMPV6Vars; - -#define CLEAR_ICMPV6_PACKET(p) do { \ - (p)->level4_comp_csum = -1; \ - PACKET_CLEAR_L4VARS((p)); \ - (p)->icmpv6h = NULL; \ -} while(0) +#define CLEAR_ICMPV6_PACKET(p) \ + do { \ + (p)->level4_comp_csum = -1; \ + PACKET_CLEAR_L4VARS((p)); \ + (p)->icmpv6h = NULL; \ + } while (0) void DecodeICMPV6RegisterTests(void); @@ -211,9 +206,9 @@ static inline uint16_t ICMPV6CalculateChecksum( uint16_t pad = 0; uint32_t csum = shdr[0]; - csum += shdr[1] + shdr[2] + shdr[3] + shdr[4] + shdr[5] + shdr[6] + - shdr[7] + shdr[8] + shdr[9] + shdr[10] + shdr[11] + shdr[12] + - shdr[13] + shdr[14] + shdr[15] + htons(58 + tlen); + csum += shdr[1] + shdr[2] + shdr[3] + shdr[4] + shdr[5] + shdr[6] + shdr[7] + shdr[8] + + shdr[9] + shdr[10] + shdr[11] + shdr[12] + shdr[13] + shdr[14] + shdr[15] + + htons(58 + tlen); csum += pkt[0]; @@ -221,30 +216,28 @@ static inline uint16_t ICMPV6CalculateChecksum( pkt += 2; while (tlen >= 64) { - csum += pkt[0] + pkt[1] + pkt[2] + pkt[3] + pkt[4] + pkt[5] + pkt[6] + - pkt[7] + pkt[8] + pkt[9] + pkt[10] + pkt[11] + pkt[12] + pkt[13] + - pkt[14] + pkt[15] + pkt[16] + pkt[17] + pkt[18] + pkt[19] + - pkt[20] + pkt[21] + pkt[22] + pkt[23] + pkt[24] + pkt[25] + - pkt[26] + pkt[27] + pkt[28] + pkt[29] + pkt[30] + pkt[31]; + csum += pkt[0] + pkt[1] + pkt[2] + pkt[3] + pkt[4] + pkt[5] + pkt[6] + pkt[7] + pkt[8] + + pkt[9] + pkt[10] + pkt[11] + pkt[12] + pkt[13] + pkt[14] + pkt[15] + pkt[16] + + pkt[17] + pkt[18] + pkt[19] + pkt[20] + pkt[21] + pkt[22] + pkt[23] + pkt[24] + + pkt[25] + pkt[26] + pkt[27] + pkt[28] + pkt[29] + pkt[30] + pkt[31]; tlen -= 64; pkt += 32; } while (tlen >= 32) { - csum += pkt[0] + pkt[1] + pkt[2] + pkt[3] + pkt[4] + pkt[5] + pkt[6] + - pkt[7] + pkt[8] + pkt[9] + pkt[10] + pkt[11] + pkt[12] + pkt[13] + - pkt[14] + pkt[15]; + csum += pkt[0] + pkt[1] + pkt[2] + pkt[3] + pkt[4] + pkt[5] + pkt[6] + pkt[7] + pkt[8] + + pkt[9] + pkt[10] + pkt[11] + pkt[12] + pkt[13] + pkt[14] + pkt[15]; tlen -= 32; pkt += 16; } - while(tlen >= 8) { + while (tlen >= 8) { csum += pkt[0] + pkt[1] + pkt[2] + pkt[3]; tlen -= 8; pkt += 4; } - while(tlen >= 4) { + while (tlen >= 4) { csum += pkt[0] + pkt[1]; tlen -= 4; pkt += 2; @@ -264,7 +257,7 @@ static inline uint16_t ICMPV6CalculateChecksum( csum = (csum >> 16) + (csum & 0x0000FFFF); csum += (csum >> 16); - return (uint16_t) ~csum; + return (uint16_t)~csum; } #endif /* __DECODE_ICMPV6_H__ */ diff --git a/src/decode-ipv4.c b/src/decode-ipv4.c index 56e016c1e660..83732a1d9eed 100644 --- a/src/decode-ipv4.c +++ b/src/decode-ipv4.c @@ -21,7 +21,6 @@ * @{ */ - /** * \file * @@ -178,7 +177,7 @@ static int IPV4OptValidateTimestamp(Packet *p, const IPV4Opt *o) */ static int IPV4OptValidateCIPSO(Packet *p, const IPV4Opt *o) { -// uint32_t doi; + // uint32_t doi; const uint8_t *tag; uint16_t len; @@ -193,11 +192,10 @@ static int IPV4OptValidateCIPSO(Packet *p, const IPV4Opt *o) ENGINE_SET_INVALID_EVENT(p, IPV4_OPT_MALFORMED); return -1; } -// doi = *o->data; + // doi = *o->data; tag = o->data + 4; len = o->len - 1 - 1 - 4; /* Length of tags after header */ - #if 0 /* Domain of Interest (DOI) of 0 is reserved and thus invalid */ /** \todo Apparently a DOI of zero is fine in practice - verify. */ @@ -218,7 +216,7 @@ static int IPV4OptValidateCIPSO(Packet *p, const IPV4Opt *o) /* Tag header must fit within option length */ if (unlikely(len < 2)) { - //printf("CIPSO tag header too large %" PRIu16 " < 2\n", len); + // printf("CIPSO tag header too large %" PRIu16 " < 2\n", len); ENGINE_SET_INVALID_EVENT(p, IPV4_OPT_MALFORMED); return -1; } @@ -229,12 +227,12 @@ static int IPV4OptValidateCIPSO(Packet *p, const IPV4Opt *o) /* Tag length must fit within the option length */ if (unlikely(tlen > len)) { - //printf("CIPSO tag len too large %" PRIu8 " > %" PRIu16 "\n", tlen, len); + // printf("CIPSO tag len too large %" PRIu8 " > %" PRIu16 "\n", tlen, len); ENGINE_SET_INVALID_EVENT(p, IPV4_OPT_MALFORMED); return -1; } - switch(ttype) { + switch (ttype) { case 1: case 2: case 5: @@ -242,7 +240,8 @@ static int IPV4OptValidateCIPSO(Packet *p, const IPV4Opt *o) case 7: /* Tag is at least 4 and at most the remainder of option len */ if (unlikely((tlen < 4) || (tlen > len))) { - //printf("CIPSO tag %" PRIu8 " bad tlen=%" PRIu8 " len=%" PRIu8 "\n", ttype, tlen, len); + // printf("CIPSO tag %" PRIu8 " bad tlen=%" PRIu8 " len=%" PRIu8 "\n", ttype, + // tlen, len); ENGINE_SET_INVALID_EVENT(p, IPV4_OPT_MALFORMED); return -1; } @@ -251,7 +250,7 @@ static int IPV4OptValidateCIPSO(Packet *p, const IPV4Opt *o) * type 7, which has no such field. */ if (unlikely((ttype != 7) && (*tag != 0))) { - //printf("CIPSO tag %" PRIu8 " ao=%" PRIu8 "\n", ttype, tlen); + // printf("CIPSO tag %" PRIu8 " ao=%" PRIu8 "\n", ttype, tlen); ENGINE_SET_INVALID_EVENT(p, IPV4_OPT_MALFORMED); return -1; } @@ -264,12 +263,13 @@ static int IPV4OptValidateCIPSO(Packet *p, const IPV4Opt *o) case 0: /* Tag type 0 is reserved and thus invalid */ /** \todo Wireshark marks this a padding, but spec says reserved. */ - ENGINE_SET_INVALID_EVENT(p,IPV4_OPT_MALFORMED); + ENGINE_SET_INVALID_EVENT(p, IPV4_OPT_MALFORMED); return -1; default: - //printf("CIPSO tag %" PRIu8 " unknown tag\n", ttype); + // printf("CIPSO tag %" PRIu8 " unknown tag\n", ttype); ENGINE_SET_INVALID_EVENT(p, IPV4_OPT_MALFORMED); - /** \todo May not want to return error here on unknown tag type (at least not for 3|4) */ + /** \todo May not want to return error here on unknown tag type (at least not for + * 3|4) */ return -1; } } @@ -312,45 +312,43 @@ static int DecodeIPV4Options(Packet *p, const uint8_t *pkt, uint16_t len, IPV4Op /* Options length must be padded to 8byte boundary */ if (plen % 8) { - ENGINE_SET_EVENT(p,IPV4_OPT_PAD_REQUIRED); + ENGINE_SET_EVENT(p, IPV4_OPT_PAD_REQUIRED); /* Warn - we can keep going */ } - while (plen) - { + while (plen) { p->ip4vars.opt_cnt++; /* single byte options */ if (*pkt == IPV4_OPT_EOL) { - /** \todo What if more data exist after EOL (possible covert channel or data leakage)? */ - SCLogDebug("IPV4OPT %" PRIu8 " len 1 @ %d/%d", - *pkt, (len - plen), (len - 1)); + /** \todo What if more data exist after EOL (possible covert channel or data leakage)? + */ + SCLogDebug("IPV4OPT %" PRIu8 " len 1 @ %d/%d", *pkt, (len - plen), (len - 1)); p->ip4vars.opts_set |= IPV4_OPT_FLAG_EOL; break; } else if (*pkt == IPV4_OPT_NOP) { - SCLogDebug("IPV4OPT %" PRIu8 " len 1 @ %d/%d", - *pkt, (len - plen), (len - 1)); + SCLogDebug("IPV4OPT %" PRIu8 " len 1 @ %d/%d", *pkt, (len - plen), (len - 1)); pkt++; plen--; p->ip4vars.opts_set |= IPV4_OPT_FLAG_NOP; - /* multibyte options */ + /* multibyte options */ } else { if (unlikely(plen < 2)) { /** \todo What if padding is non-zero (possible covert channel or data leakage)? */ /** \todo Spec seems to indicate EOL required if there is padding */ - ENGINE_SET_EVENT(p,IPV4_OPT_EOL_REQUIRED); + ENGINE_SET_EVENT(p, IPV4_OPT_EOL_REQUIRED); break; } /* Option length is too big for packet */ - if (unlikely(*(pkt+1) > plen)) { + if (unlikely(*(pkt + 1) > plen)) { ENGINE_SET_INVALID_EVENT(p, IPV4_OPT_INVALID_LEN); return -1; } - IPV4Opt opt = {*pkt, *(pkt+1), plen > 2 ? (pkt + 2) : NULL }; + IPV4Opt opt = { *pkt, *(pkt + 1), plen > 2 ? (pkt + 2) : NULL }; /* we already know that the total options len is valid, * so here the len of the specific option must be bad. @@ -366,7 +364,7 @@ static int DecodeIPV4Options(Packet *p, const uint8_t *pkt, uint16_t len, IPV4Op switch (opt.type) { case IPV4_OPT_TS: if (opts->o_ts.type != 0) { - ENGINE_SET_EVENT(p,IPV4_OPT_DUPLICATE); + ENGINE_SET_EVENT(p, IPV4_OPT_DUPLICATE); /* Warn - we can keep going */ } else if (IPV4OptValidateTimestamp(p, &opt) == 0) { opts->o_ts = opt; @@ -375,7 +373,7 @@ static int DecodeIPV4Options(Packet *p, const uint8_t *pkt, uint16_t len, IPV4Op break; case IPV4_OPT_RR: if (opts->o_rr.type != 0) { - ENGINE_SET_EVENT(p,IPV4_OPT_DUPLICATE); + ENGINE_SET_EVENT(p, IPV4_OPT_DUPLICATE); /* Warn - we can keep going */ } else if (IPV4OptValidateRoute(p, &opt) == 0) { opts->o_rr = opt; @@ -384,7 +382,7 @@ static int DecodeIPV4Options(Packet *p, const uint8_t *pkt, uint16_t len, IPV4Op break; case IPV4_OPT_QS: if (opts->o_qs.type != 0) { - ENGINE_SET_EVENT(p,IPV4_OPT_DUPLICATE); + ENGINE_SET_EVENT(p, IPV4_OPT_DUPLICATE); /* Warn - we can keep going */ } else if (IPV4OptValidateGeneric(p, &opt) == 0) { opts->o_qs = opt; @@ -393,7 +391,7 @@ static int DecodeIPV4Options(Packet *p, const uint8_t *pkt, uint16_t len, IPV4Op break; case IPV4_OPT_SEC: if (opts->o_sec.type != 0) { - ENGINE_SET_EVENT(p,IPV4_OPT_DUPLICATE); + ENGINE_SET_EVENT(p, IPV4_OPT_DUPLICATE); /* Warn - we can keep going */ } else if (IPV4OptValidateGeneric(p, &opt) == 0) { opts->o_sec = opt; @@ -402,7 +400,7 @@ static int DecodeIPV4Options(Packet *p, const uint8_t *pkt, uint16_t len, IPV4Op break; case IPV4_OPT_LSRR: if (opts->o_lsrr.type != 0) { - ENGINE_SET_EVENT(p,IPV4_OPT_DUPLICATE); + ENGINE_SET_EVENT(p, IPV4_OPT_DUPLICATE); /* Warn - we can keep going */ } else if (IPV4OptValidateRoute(p, &opt) == 0) { opts->o_lsrr = opt; @@ -420,7 +418,7 @@ static int DecodeIPV4Options(Packet *p, const uint8_t *pkt, uint16_t len, IPV4Op break; case IPV4_OPT_CIPSO: if (opts->o_cipso.type != 0) { - ENGINE_SET_EVENT(p,IPV4_OPT_DUPLICATE); + ENGINE_SET_EVENT(p, IPV4_OPT_DUPLICATE); /* Warn - we can keep going */ } else if (IPV4OptValidateCIPSO(p, &opt) == 0) { opts->o_cipso = opt; @@ -429,7 +427,7 @@ static int DecodeIPV4Options(Packet *p, const uint8_t *pkt, uint16_t len, IPV4Op break; case IPV4_OPT_SID: if (opts->o_sid.type != 0) { - ENGINE_SET_EVENT(p,IPV4_OPT_DUPLICATE); + ENGINE_SET_EVENT(p, IPV4_OPT_DUPLICATE); /* Warn - we can keep going */ } else if (IPV4OptValidateGeneric(p, &opt) == 0) { opts->o_sid = opt; @@ -438,7 +436,7 @@ static int DecodeIPV4Options(Packet *p, const uint8_t *pkt, uint16_t len, IPV4Op break; case IPV4_OPT_SSRR: if (opts->o_ssrr.type != 0) { - ENGINE_SET_EVENT(p,IPV4_OPT_DUPLICATE); + ENGINE_SET_EVENT(p, IPV4_OPT_DUPLICATE); /* Warn - we can keep going */ } else if (IPV4OptValidateRoute(p, &opt) == 0) { opts->o_ssrr = opt; @@ -447,7 +445,7 @@ static int DecodeIPV4Options(Packet *p, const uint8_t *pkt, uint16_t len, IPV4Op break; case IPV4_OPT_RTRALT: if (opts->o_rtralt.type != 0) { - ENGINE_SET_EVENT(p,IPV4_OPT_DUPLICATE); + ENGINE_SET_EVENT(p, IPV4_OPT_DUPLICATE); /* Warn - we can keep going */ } else if (IPV4OptValidateGeneric(p, &opt) == 0) { opts->o_rtralt = opt; @@ -455,9 +453,8 @@ static int DecodeIPV4Options(Packet *p, const uint8_t *pkt, uint16_t len, IPV4Op } break; default: - SCLogDebug("IPV4OPT (%" PRIu8 ") len %" PRIu8, - opt.type, opt.len); - ENGINE_SET_EVENT(p,IPV4_OPT_INVALID); + SCLogDebug("IPV4OPT (%" PRIu8 ") len %" PRIu8, opt.type, opt.len); + ENGINE_SET_EVENT(p, IPV4_OPT_INVALID); /* Warn - we can keep going */ break; } @@ -478,7 +475,7 @@ static int DecodeIPV4Packet(Packet *p, const uint8_t *pkt, uint16_t len) } if (unlikely(IP_GET_RAW_VER(pkt) != 4)) { - SCLogDebug("wrong ip version %d",IP_GET_RAW_VER(pkt)); + SCLogDebug("wrong ip version %d", IP_GET_RAW_VER(pkt)); ENGINE_SET_INVALID_EVENT(p, IPV4_WRONG_IP_VER); return -1; } @@ -501,8 +498,8 @@ static int DecodeIPV4Packet(Packet *p, const uint8_t *pkt, uint16_t len) } /* set the address struct */ - SET_IPV4_SRC_ADDR(p,&p->src); - SET_IPV4_DST_ADDR(p,&p->dst); + SET_IPV4_SRC_ADDR(p, &p->src); + SET_IPV4_DST_ADDR(p, &p->dst); /* save the options len */ uint8_t ip_opt_len = IPV4_GET_HLEN(p) - IPV4_HEADER_LEN; @@ -517,18 +514,17 @@ static int DecodeIPV4Packet(Packet *p, const uint8_t *pkt, uint16_t len) return 0; } -int DecodeIPV4(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, - const uint8_t *pkt, uint16_t len) +int DecodeIPV4(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, const uint8_t *pkt, uint16_t len) { StatsIncr(tv, dtv->counter_ipv4); - SCLogDebug("pkt %p len %"PRIu16"", pkt, len); + SCLogDebug("pkt %p len %" PRIu16 "", pkt, len); if (!PacketIncreaseCheckLayers(p)) { return TM_ECODE_FAILED; } /* do the actual decoding */ - if (unlikely(DecodeIPV4Packet (p, pkt, len) < 0)) { + if (unlikely(DecodeIPV4Packet(p, pkt, len) < 0)) { SCLogDebug("decoding IPv4 packet failed"); CLEAR_IPV4_PACKET((p)); return TM_ECODE_FAILED; @@ -553,57 +549,50 @@ int DecodeIPV4(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, char s[16], d[16]; PrintInet(AF_INET, (const void *)GET_IPV4_SRC_ADDR_PTR(p), s, sizeof(s)); PrintInet(AF_INET, (const void *)GET_IPV4_DST_ADDR_PTR(p), d, sizeof(d)); - SCLogDebug("IPV4 %s->%s PROTO: %" PRIu32 " OFFSET: %" PRIu32 " RF: %" PRIu32 " DF: %" PRIu32 " MF: %" PRIu32 " ID: %" PRIu32 "", s,d, - IPV4_GET_IPPROTO(p), IPV4_GET_IPOFFSET(p), IPV4_GET_RF(p), - IPV4_GET_DF(p), IPV4_GET_MF(p), IPV4_GET_IPID(p)); + SCLogDebug("IPV4 %s->%s PROTO: %" PRIu32 " OFFSET: %" PRIu32 " RF: %" PRIu32 " DF: %" PRIu32 + " MF: %" PRIu32 " ID: %" PRIu32 "", + s, d, IPV4_GET_IPPROTO(p), IPV4_GET_IPOFFSET(p), IPV4_GET_RF(p), IPV4_GET_DF(p), + IPV4_GET_MF(p), IPV4_GET_IPID(p)); } #endif /* DEBUG */ /* check what next decoder to invoke */ switch (IPV4_GET_IPPROTO(p)) { case IPPROTO_TCP: - DecodeTCP(tv, dtv, p, pkt + IPV4_GET_HLEN(p), - IPV4_GET_IPLEN(p) - IPV4_GET_HLEN(p)); + DecodeTCP(tv, dtv, p, pkt + IPV4_GET_HLEN(p), IPV4_GET_IPLEN(p) - IPV4_GET_HLEN(p)); break; case IPPROTO_UDP: - DecodeUDP(tv, dtv, p, pkt + IPV4_GET_HLEN(p), - IPV4_GET_IPLEN(p) - IPV4_GET_HLEN(p)); + DecodeUDP(tv, dtv, p, pkt + IPV4_GET_HLEN(p), IPV4_GET_IPLEN(p) - IPV4_GET_HLEN(p)); break; case IPPROTO_ICMP: - DecodeICMPV4(tv, dtv, p, pkt + IPV4_GET_HLEN(p), - IPV4_GET_IPLEN(p) - IPV4_GET_HLEN(p)); + DecodeICMPV4(tv, dtv, p, pkt + IPV4_GET_HLEN(p), IPV4_GET_IPLEN(p) - IPV4_GET_HLEN(p)); break; case IPPROTO_GRE: - DecodeGRE(tv, dtv, p, pkt + IPV4_GET_HLEN(p), - IPV4_GET_IPLEN(p) - IPV4_GET_HLEN(p)); + DecodeGRE(tv, dtv, p, pkt + IPV4_GET_HLEN(p), IPV4_GET_IPLEN(p) - IPV4_GET_HLEN(p)); break; case IPPROTO_SCTP: - DecodeSCTP(tv, dtv, p, pkt + IPV4_GET_HLEN(p), - IPV4_GET_IPLEN(p) - IPV4_GET_HLEN(p)); + DecodeSCTP(tv, dtv, p, pkt + IPV4_GET_HLEN(p), IPV4_GET_IPLEN(p) - IPV4_GET_HLEN(p)); break; case IPPROTO_ESP: DecodeESP(tv, dtv, p, pkt + IPV4_GET_HLEN(p), IPV4_GET_IPLEN(p) - IPV4_GET_HLEN(p)); break; - case IPPROTO_IPV6: - { - /* spawn off tunnel packet */ - Packet *tp = PacketTunnelPktSetup(tv, dtv, p, pkt + IPV4_GET_HLEN(p), - IPV4_GET_IPLEN(p) - IPV4_GET_HLEN(p), - DECODE_TUNNEL_IPV6); - if (tp != NULL) { - PKT_SET_SRC(tp, PKT_SRC_DECODER_IPV4); - PacketEnqueueNoLock(&tv->decode_pq,tp); - } - FlowSetupPacket(p); - break; + case IPPROTO_IPV6: { + /* spawn off tunnel packet */ + Packet *tp = PacketTunnelPktSetup(tv, dtv, p, pkt + IPV4_GET_HLEN(p), + IPV4_GET_IPLEN(p) - IPV4_GET_HLEN(p), DECODE_TUNNEL_IPV6); + if (tp != NULL) { + PKT_SET_SRC(tp, PKT_SRC_DECODER_IPV4); + PacketEnqueueNoLock(&tv->decode_pq, tp); } + FlowSetupPacket(p); + break; + } case IPPROTO_IP: /* check PPP VJ uncompressed packets and decode tcp dummy */ - if(p->ppph != NULL && SCNtohs(p->ppph->protocol) == PPP_VJ_UCOMP) { - DecodeTCP(tv, dtv, p, pkt + IPV4_GET_HLEN(p), - IPV4_GET_IPLEN(p) - IPV4_GET_HLEN(p)); + if (p->ppph != NULL && SCNtohs(p->ppph->protocol) == PPP_VJ_UCOMP) { + DecodeTCP(tv, dtv, p, pkt + IPV4_GET_HLEN(p), IPV4_GET_IPLEN(p) - IPV4_GET_HLEN(p)); } break; case IPPROTO_ICMPV6: @@ -1287,7 +1276,7 @@ static int IPV4CalculateValidChecksumtest01(void) 0xc0, 0xa8, 0x01, 0x03}; // clang-format on - csum = *( ((uint16_t *)raw_ipv4) + 5); + csum = *(((uint16_t *)raw_ipv4) + 5); FAIL_IF(IPV4Checksum((uint16_t *)raw_ipv4, sizeof(raw_ipv4), csum) != 0); PASS; @@ -1304,7 +1293,7 @@ static int IPV4CalculateInvalidChecksumtest02(void) 0xc0, 0xa8, 0x01, 0x07}; // clang-format on - csum = *( ((uint16_t *)raw_ipv4) + 5); + csum = *(((uint16_t *)raw_ipv4) + 5); FAIL_IF(IPV4Checksum((uint16_t *)raw_ipv4, sizeof(raw_ipv4), csum) == 0); PASS; @@ -1371,7 +1360,7 @@ static int DecodeIPV4DefragTest01(void) PacketCopyData(p, pkt1, sizeof(pkt1)); DecodeIPV4(&tv, &dtv, p, GET_PKT_DATA(p) + ETHERNET_HEADER_LEN, - GET_PKT_LEN(p) - ETHERNET_HEADER_LEN); + GET_PKT_LEN(p) - ETHERNET_HEADER_LEN); if (p->tcph != NULL) { printf("tcp header should be NULL for ip fragment, but it isn't\n"); result = 0; @@ -1381,7 +1370,7 @@ static int DecodeIPV4DefragTest01(void) PacketCopyData(p, pkt2, sizeof(pkt2)); DecodeIPV4(&tv, &dtv, p, GET_PKT_DATA(p) + ETHERNET_HEADER_LEN, - GET_PKT_LEN(p) - ETHERNET_HEADER_LEN); + GET_PKT_LEN(p) - ETHERNET_HEADER_LEN); if (p->tcph != NULL) { printf("tcp header should be NULL for ip fragment, but it isn't\n"); result = 0; @@ -1391,7 +1380,7 @@ static int DecodeIPV4DefragTest01(void) PacketCopyData(p, pkt3, sizeof(pkt3)); DecodeIPV4(&tv, &dtv, p, GET_PKT_DATA(p) + ETHERNET_HEADER_LEN, - GET_PKT_LEN(p) - ETHERNET_HEADER_LEN); + GET_PKT_LEN(p) - ETHERNET_HEADER_LEN); if (p->tcph != NULL) { printf("tcp header should be NULL for ip fragment, but it isn't\n"); result = 0; @@ -1406,7 +1395,7 @@ static int DecodeIPV4DefragTest01(void) if (tp->recursion_level != p->recursion_level) { printf("defragged pseudo packet's and parent packet's recursion " "level don't match\n %d != %d", - tp->recursion_level, p->recursion_level); + tp->recursion_level, p->recursion_level); result = 0; goto end; } @@ -1418,14 +1407,14 @@ static int DecodeIPV4DefragTest01(void) } if (GET_PKT_LEN(tp) != sizeof(tunnel_pkt)) { printf("defragged pseudo packet's and parent packet's pkt lens " - "don't match\n %u != %"PRIuMAX, - GET_PKT_LEN(tp), (uintmax_t)sizeof(tunnel_pkt)); + "don't match\n %u != %" PRIuMAX, + GET_PKT_LEN(tp), (uintmax_t)sizeof(tunnel_pkt)); result = 0; goto end; } if (memcmp(GET_PKT_DATA(tp), tunnel_pkt, sizeof(tunnel_pkt)) != 0) { - result = 0; - goto end; + result = 0; + goto end; } PacketRecycle(tp); @@ -1514,7 +1503,7 @@ static int DecodeIPV4DefragTest02(void) PacketCopyData(p, pkt1, sizeof(pkt1)); DecodeIPV4(&tv, &dtv, p, GET_PKT_DATA(p) + ETHERNET_HEADER_LEN, - GET_PKT_LEN(p) - ETHERNET_HEADER_LEN); + GET_PKT_LEN(p) - ETHERNET_HEADER_LEN); if (p->tcph != NULL) { printf("tcp header should be NULL for ip fragment, but it isn't\n"); goto end; @@ -1523,7 +1512,7 @@ static int DecodeIPV4DefragTest02(void) PacketCopyData(p, pkt2, sizeof(pkt2)); DecodeIPV4(&tv, &dtv, p, GET_PKT_DATA(p) + ETHERNET_HEADER_LEN, - GET_PKT_LEN(p) - ETHERNET_HEADER_LEN); + GET_PKT_LEN(p) - ETHERNET_HEADER_LEN); if (p->tcph != NULL) { printf("tcp header should be NULL for ip fragment, but it isn't\n"); goto end; @@ -1533,7 +1522,7 @@ static int DecodeIPV4DefragTest02(void) p->recursion_level = 3; PacketCopyData(p, pkt3, sizeof(pkt3)); DecodeIPV4(&tv, &dtv, p, GET_PKT_DATA(p) + ETHERNET_HEADER_LEN, - GET_PKT_LEN(p) - ETHERNET_HEADER_LEN); + GET_PKT_LEN(p) - ETHERNET_HEADER_LEN); if (p->tcph != NULL) { printf("tcp header should be NULL for ip fragment, but it isn't\n"); goto end; @@ -1546,7 +1535,7 @@ static int DecodeIPV4DefragTest02(void) if (tp->recursion_level != p->recursion_level) { printf("defragged pseudo packet's and parent packet's recursion " "level don't match %d != %d: ", - tp->recursion_level, p->recursion_level); + tp->recursion_level, p->recursion_level); goto end; } if (tp->ip4h == NULL || tp->tcph == NULL) { @@ -1556,8 +1545,8 @@ static int DecodeIPV4DefragTest02(void) } if (GET_PKT_LEN(tp) != sizeof(tunnel_pkt)) { printf("defragged pseudo packet's and parent packet's pkt lens " - "don't match %u != %"PRIuMAX": ", - GET_PKT_LEN(tp), (uintmax_t)sizeof(tunnel_pkt)); + "don't match %u != %" PRIuMAX ": ", + GET_PKT_LEN(tp), (uintmax_t)sizeof(tunnel_pkt)); goto end; } @@ -1649,7 +1638,7 @@ static int DecodeIPV4DefragTest03(void) PacketCopyData(p, pkt, sizeof(pkt)); DecodeIPV4(&tv, &dtv, p, GET_PKT_DATA(p) + ETHERNET_HEADER_LEN, - GET_PKT_LEN(p) - ETHERNET_HEADER_LEN); + GET_PKT_LEN(p) - ETHERNET_HEADER_LEN); if (p->tcph == NULL) { printf("tcp header shouldn't be NULL, but it is\n"); result = 0; @@ -1664,7 +1653,7 @@ static int DecodeIPV4DefragTest03(void) PacketCopyData(p, pkt1, sizeof(pkt1)); DecodeIPV4(&tv, &dtv, p, GET_PKT_DATA(p) + ETHERNET_HEADER_LEN, - GET_PKT_LEN(p) - ETHERNET_HEADER_LEN); + GET_PKT_LEN(p) - ETHERNET_HEADER_LEN); if (p->tcph != NULL) { printf("tcp header should be NULL for ip fragment, but it isn't\n"); result = 0; @@ -1674,7 +1663,7 @@ static int DecodeIPV4DefragTest03(void) PacketCopyData(p, pkt2, sizeof(pkt2)); DecodeIPV4(&tv, &dtv, p, GET_PKT_DATA(p) + ETHERNET_HEADER_LEN, - GET_PKT_LEN(p) - ETHERNET_HEADER_LEN); + GET_PKT_LEN(p) - ETHERNET_HEADER_LEN); if (p->tcph != NULL) { printf("tcp header should be NULL for ip fragment, but it isn't\n"); result = 0; @@ -1684,7 +1673,7 @@ static int DecodeIPV4DefragTest03(void) PacketCopyData(p, pkt3, sizeof(pkt3)); DecodeIPV4(&tv, &dtv, p, GET_PKT_DATA(p) + ETHERNET_HEADER_LEN, - GET_PKT_LEN(p) - ETHERNET_HEADER_LEN); + GET_PKT_LEN(p) - ETHERNET_HEADER_LEN); if (p->tcph != NULL) { printf("tcp header should be NULL for ip fragment, but it isn't\n"); result = 0; @@ -1708,7 +1697,7 @@ static int DecodeIPV4DefragTest03(void) if (tp->recursion_level != p->recursion_level) { printf("defragged pseudo packet's and parent packet's recursion " "level don't match\n %d != %d", - tp->recursion_level, p->recursion_level); + tp->recursion_level, p->recursion_level); result = 0; goto end; } @@ -1720,15 +1709,15 @@ static int DecodeIPV4DefragTest03(void) } if (GET_PKT_LEN(tp) != sizeof(tunnel_pkt)) { printf("defragged pseudo packet's and parent packet's pkt lens " - "don't match\n %u != %"PRIuMAX, - GET_PKT_LEN(tp), (uintmax_t)sizeof(tunnel_pkt)); + "don't match\n %u != %" PRIuMAX, + GET_PKT_LEN(tp), (uintmax_t)sizeof(tunnel_pkt)); result = 0; goto end; } if (memcmp(GET_PKT_DATA(tp), tunnel_pkt, sizeof(tunnel_pkt)) != 0) { - result = 0; - goto end; + result = 0; + goto end; } PacketRecycle(tp); @@ -1764,7 +1753,7 @@ static int DecodeEthernetTestIPv4Opt(void) DecodeThreadVars dtv; memset(&dtv, 0, sizeof(DecodeThreadVars)); - memset(&tv, 0, sizeof(ThreadVars)); + memset(&tv, 0, sizeof(ThreadVars)); DecodeEthernet(&tv, &dtv, p, raw_eth, sizeof(raw_eth)); @@ -1799,22 +1788,17 @@ void DecodeIPV4RegisterTests(void) UtRegisterTest("DecodeIPV4OptionsLSRRTest02", DecodeIPV4OptionsLSRRTest02); UtRegisterTest("DecodeIPV4OptionsLSRRTest03", DecodeIPV4OptionsLSRRTest03); UtRegisterTest("DecodeIPV4OptionsLSRRTest04", DecodeIPV4OptionsLSRRTest04); - UtRegisterTest("DecodeIPV4OptionsCIPSOTest01", - DecodeIPV4OptionsCIPSOTest01); + UtRegisterTest("DecodeIPV4OptionsCIPSOTest01", DecodeIPV4OptionsCIPSOTest01); UtRegisterTest("DecodeIPV4OptionsSIDTest01", DecodeIPV4OptionsSIDTest01); UtRegisterTest("DecodeIPV4OptionsSIDTest02", DecodeIPV4OptionsSIDTest02); UtRegisterTest("DecodeIPV4OptionsSSRRTest01", DecodeIPV4OptionsSSRRTest01); UtRegisterTest("DecodeIPV4OptionsSSRRTest02", DecodeIPV4OptionsSSRRTest02); UtRegisterTest("DecodeIPV4OptionsSSRRTest03", DecodeIPV4OptionsSSRRTest03); UtRegisterTest("DecodeIPV4OptionsSSRRTest04", DecodeIPV4OptionsSSRRTest04); - UtRegisterTest("DecodeIPV4OptionsRTRALTTest01", - DecodeIPV4OptionsRTRALTTest01); - UtRegisterTest("DecodeIPV4OptionsRTRALTTest02", - DecodeIPV4OptionsRTRALTTest02); - UtRegisterTest("IPV4CalculateValidChecksumtest01", - IPV4CalculateValidChecksumtest01); - UtRegisterTest("IPV4CalculateInvalidChecksumtest02", - IPV4CalculateInvalidChecksumtest02); + UtRegisterTest("DecodeIPV4OptionsRTRALTTest01", DecodeIPV4OptionsRTRALTTest01); + UtRegisterTest("DecodeIPV4OptionsRTRALTTest02", DecodeIPV4OptionsRTRALTTest02); + UtRegisterTest("IPV4CalculateValidChecksumtest01", IPV4CalculateValidChecksumtest01); + UtRegisterTest("IPV4CalculateInvalidChecksumtest02", IPV4CalculateInvalidChecksumtest02); UtRegisterTest("DecodeIPV4DefragTest01", DecodeIPV4DefragTest01); UtRegisterTest("DecodeIPV4DefragTest02", DecodeIPV4DefragTest02); UtRegisterTest("DecodeIPV4DefragTest03", DecodeIPV4DefragTest03); diff --git a/src/decode-ipv4.h b/src/decode-ipv4.h index d247fa9f0033..59fefa3e6fe9 100644 --- a/src/decode-ipv4.h +++ b/src/decode-ipv4.h @@ -25,92 +25,92 @@ #ifndef __DECODE_IPV4_H__ #define __DECODE_IPV4_H__ -#define IPV4_HEADER_LEN 20 /**< Header length */ -#define IPV4_OPTMAX 40 /**< Max options length */ -#define IPV4_MAXPACKET_LEN 65535 /**< Maximum packet size */ +#define IPV4_HEADER_LEN 20 /**< Header length */ +#define IPV4_OPTMAX 40 /**< Max options length */ +#define IPV4_MAXPACKET_LEN 65535 /**< Maximum packet size */ /** IP Option Types */ -#define IPV4_OPT_EOL 0x00 /**< Option: End of List */ -#define IPV4_OPT_NOP 0x01 /**< Option: No op */ -#define IPV4_OPT_RR 0x07 /**< Option: Record Route */ -#define IPV4_OPT_QS 0x19 /**< Option: Quick Start */ -#define IPV4_OPT_TS 0x44 /**< Option: Timestamp */ -#define IPV4_OPT_SEC 0x82 /**< Option: Security */ -#define IPV4_OPT_LSRR 0x83 /**< Option: Loose Source Route */ -#define IPV4_OPT_ESEC 0x85 /**< Option: Extended Security */ -#define IPV4_OPT_CIPSO 0x86 /**< Option: Commercial IP Security */ -#define IPV4_OPT_SID 0x88 /**< Option: Stream Identifier */ -#define IPV4_OPT_SSRR 0x89 /**< Option: Strict Source Route */ -#define IPV4_OPT_RTRALT 0x94 /**< Option: Router Alert */ +#define IPV4_OPT_EOL 0x00 /**< Option: End of List */ +#define IPV4_OPT_NOP 0x01 /**< Option: No op */ +#define IPV4_OPT_RR 0x07 /**< Option: Record Route */ +#define IPV4_OPT_QS 0x19 /**< Option: Quick Start */ +#define IPV4_OPT_TS 0x44 /**< Option: Timestamp */ +#define IPV4_OPT_SEC 0x82 /**< Option: Security */ +#define IPV4_OPT_LSRR 0x83 /**< Option: Loose Source Route */ +#define IPV4_OPT_ESEC 0x85 /**< Option: Extended Security */ +#define IPV4_OPT_CIPSO 0x86 /**< Option: Commercial IP Security */ +#define IPV4_OPT_SID 0x88 /**< Option: Stream Identifier */ +#define IPV4_OPT_SSRR 0x89 /**< Option: Strict Source Route */ +#define IPV4_OPT_RTRALT 0x94 /**< Option: Router Alert */ /** IP Option Lengths (fixed) */ -#define IPV4_OPT_SID_LEN 4 /**< SID Option Fixed Length */ -#define IPV4_OPT_RTRALT_LEN 4 /**< RTRALT Option Fixed Length */ +#define IPV4_OPT_SID_LEN 4 /**< SID Option Fixed Length */ +#define IPV4_OPT_RTRALT_LEN 4 /**< RTRALT Option Fixed Length */ /** IP Option Lengths (variable) */ -#define IPV4_OPT_SEC_MIN 3 /**< SEC, ESEC Option Min Length */ -#define IPV4_OPT_ROUTE_MIN 3 /**< RR, SRR, LTRR Option Min Length */ -#define IPV4_OPT_QS_MIN 8 /**< QS Option Min Length */ -#define IPV4_OPT_TS_MIN 5 /**< TS Option Min Length */ -#define IPV4_OPT_CIPSO_MIN 10 /**< CIPSO Option Min Length */ +#define IPV4_OPT_SEC_MIN 3 /**< SEC, ESEC Option Min Length */ +#define IPV4_OPT_ROUTE_MIN 3 /**< RR, SRR, LTRR Option Min Length */ +#define IPV4_OPT_QS_MIN 8 /**< QS Option Min Length */ +#define IPV4_OPT_TS_MIN 5 /**< TS Option Min Length */ +#define IPV4_OPT_CIPSO_MIN 10 /**< CIPSO Option Min Length */ /** IP Option fields */ -#define IPV4_OPTS ip4vars.ip_opts -#define IPV4_OPTS_CNT ip4vars.ip_opt_cnt +#define IPV4_OPTS ip4vars.ip_opts +#define IPV4_OPTS_CNT ip4vars.ip_opt_cnt typedef struct IPV4Opt_ { /** \todo We may want to break type up into its 3 fields * as the reassembler may want to know which options * must be copied to each fragment. */ - uint8_t type; /**< option type */ - uint8_t len; /**< option length (type+len+data) */ - const uint8_t *data; /**< option data */ + uint8_t type; /**< option type */ + uint8_t len; /**< option length (type+len+data) */ + const uint8_t *data; /**< option data */ } IPV4Opt; -typedef struct IPV4Hdr_ -{ - uint8_t ip_verhl; /**< version & header length */ - uint8_t ip_tos; /**< type of service */ - uint16_t ip_len; /**< length */ - uint16_t ip_id; /**< id */ - uint16_t ip_off; /**< frag offset */ - uint8_t ip_ttl; /**< time to live */ - uint8_t ip_proto; /**< protocol (tcp, udp, etc) */ - uint16_t ip_csum; /**< checksum */ +typedef struct IPV4Hdr_ { + uint8_t ip_verhl; /**< version & header length */ + uint8_t ip_tos; /**< type of service */ + uint16_t ip_len; /**< length */ + uint16_t ip_id; /**< id */ + uint16_t ip_off; /**< frag offset */ + uint8_t ip_ttl; /**< time to live */ + uint8_t ip_proto; /**< protocol (tcp, udp, etc) */ + uint16_t ip_csum; /**< checksum */ union { struct { - struct in_addr ip_src;/**< source address */ - struct in_addr ip_dst;/**< destination address */ + struct in_addr ip_src; /**< source address */ + struct in_addr ip_dst; /**< destination address */ } ip4_un1; uint16_t ip_addrs[4]; } ip4_hdrun1; } IPV4Hdr; - -#define s_ip_src ip4_hdrun1.ip4_un1.ip_src -#define s_ip_dst ip4_hdrun1.ip4_un1.ip_dst -#define s_ip_addrs ip4_hdrun1.ip_addrs - -#define IPV4_GET_RAW_VER(ip4h) (((ip4h)->ip_verhl & 0xf0) >> 4) -#define IPV4_GET_RAW_HLEN(ip4h) ((ip4h)->ip_verhl & 0x0f) -#define IPV4_GET_RAW_IPTOS(ip4h) ((ip4h)->ip_tos) -#define IPV4_GET_RAW_IPLEN(ip4h) ((ip4h)->ip_len) -#define IPV4_GET_RAW_IPID(ip4h) ((ip4h)->ip_id) -#define IPV4_GET_RAW_IPOFFSET(ip4h) ((ip4h)->ip_off) -#define IPV4_GET_RAW_IPTTL(ip4h) ((ip4h)->ip_ttl) -#define IPV4_GET_RAW_IPPROTO(ip4h) ((ip4h)->ip_proto) -#define IPV4_GET_RAW_IPSRC(ip4h) ((ip4h)->s_ip_src) -#define IPV4_GET_RAW_IPDST(ip4h) ((ip4h)->s_ip_dst) +#define s_ip_src ip4_hdrun1.ip4_un1.ip_src +#define s_ip_dst ip4_hdrun1.ip4_un1.ip_dst +#define s_ip_addrs ip4_hdrun1.ip_addrs + +#define IPV4_GET_RAW_VER(ip4h) (((ip4h)->ip_verhl & 0xf0) >> 4) +#define IPV4_GET_RAW_HLEN(ip4h) ((ip4h)->ip_verhl & 0x0f) +#define IPV4_GET_RAW_IPTOS(ip4h) ((ip4h)->ip_tos) +#define IPV4_GET_RAW_IPLEN(ip4h) ((ip4h)->ip_len) +#define IPV4_GET_RAW_IPID(ip4h) ((ip4h)->ip_id) +#define IPV4_GET_RAW_IPOFFSET(ip4h) ((ip4h)->ip_off) +#define IPV4_GET_RAW_IPTTL(ip4h) ((ip4h)->ip_ttl) +#define IPV4_GET_RAW_IPPROTO(ip4h) ((ip4h)->ip_proto) +#define IPV4_GET_RAW_IPSRC(ip4h) ((ip4h)->s_ip_src) +#define IPV4_GET_RAW_IPDST(ip4h) ((ip4h)->s_ip_dst) /** return the raw (directly from the header) src ip as uint32_t */ -#define IPV4_GET_RAW_IPSRC_U32(ip4h) (uint32_t)((ip4h)->s_ip_src.s_addr) +#define IPV4_GET_RAW_IPSRC_U32(ip4h) (uint32_t)((ip4h)->s_ip_src.s_addr) /** return the raw (directly from the header) dst ip as uint32_t */ -#define IPV4_GET_RAW_IPDST_U32(ip4h) (uint32_t)((ip4h)->s_ip_dst.s_addr) +#define IPV4_GET_RAW_IPDST_U32(ip4h) (uint32_t)((ip4h)->s_ip_dst.s_addr) /* we need to change them as well as get them */ -#define IPV4_SET_RAW_VER(ip4h, value) ((ip4h)->ip_verhl = (((ip4h)->ip_verhl & 0x0f) | (value << 4))) -#define IPV4_SET_RAW_HLEN(ip4h, value) ((ip4h)->ip_verhl = (((ip4h)->ip_verhl & 0xf0) | (value & 0x0f))) +#define IPV4_SET_RAW_VER(ip4h, value) \ + ((ip4h)->ip_verhl = (((ip4h)->ip_verhl & 0x0f) | (value << 4))) +#define IPV4_SET_RAW_HLEN(ip4h, value) \ + ((ip4h)->ip_verhl = (((ip4h)->ip_verhl & 0xf0) | (value & 0x0f))) #define IPV4_SET_RAW_IPTOS(ip4h, value) ((ip4h)->ip_tos = value) #define IPV4_SET_RAW_IPLEN(ip4h, value) ((ip4h)->ip_len = value) #define IPV4_SET_RAW_IPPROTO(ip4h, value) ((ip4h)->ip_proto = value) @@ -119,40 +119,30 @@ typedef struct IPV4Hdr_ * 1. p->ip4h is set * 2. p->ip4h is valid (len is correct) */ -#define IPV4_GET_VER(p) \ - IPV4_GET_RAW_VER((p)->ip4h) -#define IPV4_GET_HLEN(p) ((uint8_t)(IPV4_GET_RAW_HLEN((p)->ip4h) << 2)) -#define IPV4_GET_IPTOS(p) \ - IPV4_GET_RAW_IPTOS((p)->ip4h) -#define IPV4_GET_IPLEN(p) \ - (SCNtohs(IPV4_GET_RAW_IPLEN((p)->ip4h))) -#define IPV4_GET_IPID(p) \ - (SCNtohs(IPV4_GET_RAW_IPID((p)->ip4h))) +#define IPV4_GET_VER(p) IPV4_GET_RAW_VER((p)->ip4h) +#define IPV4_GET_HLEN(p) ((uint8_t)(IPV4_GET_RAW_HLEN((p)->ip4h) << 2)) +#define IPV4_GET_IPTOS(p) IPV4_GET_RAW_IPTOS((p)->ip4h) +#define IPV4_GET_IPLEN(p) (SCNtohs(IPV4_GET_RAW_IPLEN((p)->ip4h))) +#define IPV4_GET_IPID(p) (SCNtohs(IPV4_GET_RAW_IPID((p)->ip4h))) /* _IPV4_GET_IPOFFSET: get the content of the offset header field in host order */ -#define _IPV4_GET_IPOFFSET(p) \ - (SCNtohs(IPV4_GET_RAW_IPOFFSET((p)->ip4h))) +#define _IPV4_GET_IPOFFSET(p) (SCNtohs(IPV4_GET_RAW_IPOFFSET((p)->ip4h))) /* IPV4_GET_IPOFFSET: get the final offset */ -#define IPV4_GET_IPOFFSET(p) \ - (_IPV4_GET_IPOFFSET(p) & 0x1fff) +#define IPV4_GET_IPOFFSET(p) (_IPV4_GET_IPOFFSET(p) & 0x1fff) /* IPV4_GET_RF: get the RF flag. Use _IPV4_GET_IPOFFSET to save a SCNtohs call. */ -#define IPV4_GET_RF(p) \ - (uint8_t)((_IPV4_GET_IPOFFSET((p)) & 0x8000) >> 15) +#define IPV4_GET_RF(p) (uint8_t)((_IPV4_GET_IPOFFSET((p)) & 0x8000) >> 15) /* IPV4_GET_DF: get the DF flag. Use _IPV4_GET_IPOFFSET to save a SCNtohs call. */ -#define IPV4_GET_DF(p) \ - (uint8_t)((_IPV4_GET_IPOFFSET((p)) & 0x4000) >> 14) +#define IPV4_GET_DF(p) (uint8_t)((_IPV4_GET_IPOFFSET((p)) & 0x4000) >> 14) /* IPV4_GET_MF: get the MF flag. Use _IPV4_GET_IPOFFSET to save a SCNtohs call. */ -#define IPV4_GET_MF(p) \ - (uint8_t)((_IPV4_GET_IPOFFSET((p)) & 0x2000) >> 13) -#define IPV4_GET_IPTTL(p) \ - IPV4_GET_RAW_IPTTL(p->ip4h) -#define IPV4_GET_IPPROTO(p) \ - IPV4_GET_RAW_IPPROTO((p)->ip4h) - -#define CLEAR_IPV4_PACKET(p) do { \ - (p)->ip4h = NULL; \ - (p)->level3_comp_csum = -1; \ - memset(&p->ip4vars, 0x00, sizeof(p->ip4vars)); \ -} while (0) +#define IPV4_GET_MF(p) (uint8_t)((_IPV4_GET_IPOFFSET((p)) & 0x2000) >> 13) +#define IPV4_GET_IPTTL(p) IPV4_GET_RAW_IPTTL(p->ip4h) +#define IPV4_GET_IPPROTO(p) IPV4_GET_RAW_IPPROTO((p)->ip4h) + +#define CLEAR_IPV4_PACKET(p) \ + do { \ + (p)->ip4h = NULL; \ + (p)->level3_comp_csum = -1; \ + memset(&p->ip4vars, 0x00, sizeof(p->ip4vars)); \ + } while (0) enum IPV4OptionFlags { IPV4_OPT_FLAG_EOL = 0, @@ -170,15 +160,13 @@ enum IPV4OptionFlags { }; /* helper structure with parsed ipv4 info */ -typedef struct IPV4Vars_ -{ - int32_t comp_csum; /* checksum computed over the ipv4 packet */ +typedef struct IPV4Vars_ { + int32_t comp_csum; /* checksum computed over the ipv4 packet */ uint16_t opt_cnt; uint16_t opts_set; } IPV4Vars; - void DecodeIPV4RegisterTests(void); /** ----- Inline functions ----- */ @@ -197,8 +185,7 @@ static inline uint16_t IPV4Checksum(const uint16_t *pkt, uint16_t hlen, uint16_t { uint32_t csum = init; - csum += pkt[0] + pkt[1] + pkt[2] + pkt[3] + pkt[4] + pkt[6] + pkt[7] + - pkt[8] + pkt[9]; + csum += pkt[0] + pkt[1] + pkt[2] + pkt[3] + pkt[4] + pkt[6] + pkt[7] + pkt[8] + pkt[9]; hlen -= 20; pkt += 10; @@ -212,35 +199,33 @@ static inline uint16_t IPV4Checksum(const uint16_t *pkt, uint16_t hlen, uint16_t } else if (hlen == 12) { csum += pkt[0] + pkt[1] + pkt[2] + pkt[3] + pkt[4] + pkt[5]; } else if (hlen == 16) { - csum += pkt[0] + pkt[1] + pkt[2] + pkt[3] + pkt[4] + pkt[5] + pkt[6] + - pkt[7]; + csum += pkt[0] + pkt[1] + pkt[2] + pkt[3] + pkt[4] + pkt[5] + pkt[6] + pkt[7]; } else if (hlen == 20) { - csum += pkt[0] + pkt[1] + pkt[2] + pkt[3] + pkt[4] + pkt[5] + pkt[6] + - pkt[7] + pkt[8] + pkt[9]; + csum += pkt[0] + pkt[1] + pkt[2] + pkt[3] + pkt[4] + pkt[5] + pkt[6] + pkt[7] + pkt[8] + + pkt[9]; } else if (hlen == 24) { - csum += pkt[0] + pkt[1] + pkt[2] + pkt[3] + pkt[4] + pkt[5] + pkt[6] + - pkt[7] + pkt[8] + pkt[9] + pkt[10] + pkt[11]; + csum += pkt[0] + pkt[1] + pkt[2] + pkt[3] + pkt[4] + pkt[5] + pkt[6] + pkt[7] + pkt[8] + + pkt[9] + pkt[10] + pkt[11]; } else if (hlen == 28) { - csum += pkt[0] + pkt[1] + pkt[2] + pkt[3] + pkt[4] + pkt[5] + pkt[6] + - pkt[7] + pkt[8] + pkt[9] + pkt[10] + pkt[11] + pkt[12] + pkt[13]; + csum += pkt[0] + pkt[1] + pkt[2] + pkt[3] + pkt[4] + pkt[5] + pkt[6] + pkt[7] + pkt[8] + + pkt[9] + pkt[10] + pkt[11] + pkt[12] + pkt[13]; } else if (hlen == 32) { - csum += pkt[0] + pkt[1] + pkt[2] + pkt[3] + pkt[4] + pkt[5] + pkt[6] + - pkt[7] + pkt[8] + pkt[9] + pkt[10] + pkt[11] + pkt[12] + pkt[13] + - pkt[14] + pkt[15]; + csum += pkt[0] + pkt[1] + pkt[2] + pkt[3] + pkt[4] + pkt[5] + pkt[6] + pkt[7] + pkt[8] + + pkt[9] + pkt[10] + pkt[11] + pkt[12] + pkt[13] + pkt[14] + pkt[15]; } else if (hlen == 36) { - csum += pkt[0] + pkt[1] + pkt[2] + pkt[3] + pkt[4] + pkt[5] + pkt[6] + - pkt[7] + pkt[8] + pkt[9] + pkt[10] + pkt[11] + pkt[12] + pkt[13] + - pkt[14] + pkt[15] + pkt[16] + pkt[17]; + csum += pkt[0] + pkt[1] + pkt[2] + pkt[3] + pkt[4] + pkt[5] + pkt[6] + pkt[7] + pkt[8] + + pkt[9] + pkt[10] + pkt[11] + pkt[12] + pkt[13] + pkt[14] + pkt[15] + pkt[16] + + pkt[17]; } else if (hlen == 40) { - csum += pkt[0] + pkt[1] + pkt[2] + pkt[3] + pkt[4] + pkt[5] + pkt[6] + - pkt[7] + pkt[8] + pkt[9] + pkt[10] + pkt[11] + pkt[12] + pkt[13] + - pkt[14] + pkt[15] + pkt[16] + pkt[17] + pkt[18] + pkt[19]; + csum += pkt[0] + pkt[1] + pkt[2] + pkt[3] + pkt[4] + pkt[5] + pkt[6] + pkt[7] + pkt[8] + + pkt[9] + pkt[10] + pkt[11] + pkt[12] + pkt[13] + pkt[14] + pkt[15] + pkt[16] + + pkt[17] + pkt[18] + pkt[19]; } csum = (csum >> 16) + (csum & 0x0000FFFF); csum += (csum >> 16); - return (uint16_t) ~csum; + return (uint16_t)~csum; } #endif /* __DECODE_IPV4_H__ */ diff --git a/src/decode-ipv6.c b/src/decode-ipv6.c index 99995ef02070..1b2ceb6db2b8 100644 --- a/src/decode-ipv6.c +++ b/src/decode-ipv6.c @@ -21,7 +21,6 @@ * @{ */ - /** * \file * @@ -41,7 +40,8 @@ * \brief Function to decode IPv4 in IPv6 packets * */ -static void DecodeIPv4inIPv6(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, const uint8_t *pkt, uint16_t plen) +static void DecodeIPv4inIPv6( + ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, const uint8_t *pkt, uint16_t plen) { if (unlikely(plen < IPV4_HEADER_LEN)) { @@ -52,7 +52,7 @@ static void DecodeIPv4inIPv6(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, c Packet *tp = PacketTunnelPktSetup(tv, dtv, p, pkt, plen, DECODE_TUNNEL_IPV4); if (tp != NULL) { PKT_SET_SRC(tp, PKT_SRC_DECODER_IPV6); - PacketEnqueueNoLock(&tv->decode_pq,tp); + PacketEnqueueNoLock(&tv->decode_pq, tp); StatsIncr(tv, dtv->counter_ipv4inipv6); return; } @@ -66,8 +66,8 @@ static void DecodeIPv4inIPv6(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, c * \brief Function to decode IPv6 in IPv6 packets * */ -static int DecodeIP6inIP6(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, - const uint8_t *pkt, uint16_t plen) +static int DecodeIP6inIP6( + ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, const uint8_t *pkt, uint16_t plen) { if (unlikely(plen < IPV6_HEADER_LEN)) { @@ -78,7 +78,7 @@ static int DecodeIP6inIP6(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, Packet *tp = PacketTunnelPktSetup(tv, dtv, p, pkt, plen, DECODE_TUNNEL_IPV6); if (tp != NULL) { PKT_SET_SRC(tp, PKT_SRC_DECODER_IPV6); - PacketEnqueueNoLock(&tv->decode_pq,tp); + PacketEnqueueNoLock(&tv->decode_pq, tp); StatsIncr(tv, dtv->counter_ipv6inipv6); } } else { @@ -90,26 +90,24 @@ static int DecodeIP6inIP6(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, #ifndef UNITTESTS // ugly, but we need this in defrag tests static inline #endif -void DecodeIPV6FragHeader(Packet *p, const uint8_t *pkt, - uint16_t hdrextlen, uint16_t plen, - uint16_t prev_hdrextlen) + void + DecodeIPV6FragHeader(Packet *p, const uint8_t *pkt, uint16_t hdrextlen, uint16_t plen, + uint16_t prev_hdrextlen) { uint16_t frag_offset = (*(pkt + 2) << 8 | *(pkt + 3)) & 0xFFF8; - int frag_morefrags = (*(pkt + 2) << 8 | *(pkt + 3)) & 0x0001; + int frag_morefrags = (*(pkt + 2) << 8 | *(pkt + 3)) & 0x0001; p->ip6eh.fh_offset = frag_offset; p->ip6eh.fh_more_frags_set = frag_morefrags ? true : false; p->ip6eh.fh_nh = *pkt; uint32_t fh_id; - memcpy(&fh_id, pkt+4, 4); + memcpy(&fh_id, pkt + 4, 4); p->ip6eh.fh_id = SCNtohl(fh_id); - SCLogDebug("IPV6 FH: offset %u, mf %s, nh %u, id %u/%x", - p->ip6eh.fh_offset, - p->ip6eh.fh_more_frags_set ? "true" : "false", - p->ip6eh.fh_nh, - p->ip6eh.fh_id, p->ip6eh.fh_id); + SCLogDebug("IPV6 FH: offset %u, mf %s, nh %u, id %u/%x", p->ip6eh.fh_offset, + p->ip6eh.fh_more_frags_set ? "true" : "false", p->ip6eh.fh_nh, p->ip6eh.fh_id, + p->ip6eh.fh_id); // store header offset, data offset uint16_t frag_hdr_offset = (uint16_t)(pkt - GET_PKT_DATA(p)); @@ -126,13 +124,11 @@ void DecodeIPV6FragHeader(Packet *p, const uint8_t *pkt, } SCLogDebug("IPV6 FH: frag_hdr_offset %u, data_offset %u, data_len %u", - p->ip6eh.fh_header_offset, p->ip6eh.fh_data_offset, - p->ip6eh.fh_data_len); + p->ip6eh.fh_header_offset, p->ip6eh.fh_data_offset, p->ip6eh.fh_data_len); } -static void -DecodeIPV6ExtHdrs(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, - const uint8_t *pkt, uint16_t len) +static void DecodeIPV6ExtHdrs( + ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, const uint8_t *pkt, uint16_t len) { SCEnter(); @@ -146,8 +142,7 @@ DecodeIPV6ExtHdrs(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, int rh = 0; int ah = 0; - while(1) - { + while (1) { IPV6_SET_EXTHDRS_LEN(p, (len - plen)); if (nh == IPPROTO_NONE) { @@ -163,33 +158,32 @@ DecodeIPV6ExtHdrs(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, SCReturn; } - switch(nh) - { + switch (nh) { case IPPROTO_TCP: - IPV6_SET_L4PROTO(p,nh); + IPV6_SET_L4PROTO(p, nh); DecodeTCP(tv, dtv, p, pkt, plen); SCReturn; case IPPROTO_UDP: - IPV6_SET_L4PROTO(p,nh); + IPV6_SET_L4PROTO(p, nh); DecodeUDP(tv, dtv, p, pkt, plen); SCReturn; case IPPROTO_ICMPV6: - IPV6_SET_L4PROTO(p,nh); + IPV6_SET_L4PROTO(p, nh); DecodeICMPV6(tv, dtv, p, pkt, plen); SCReturn; case IPPROTO_SCTP: - IPV6_SET_L4PROTO(p,nh); + IPV6_SET_L4PROTO(p, nh); DecodeSCTP(tv, dtv, p, pkt, plen); SCReturn; case IPPROTO_ROUTING: - IPV6_SET_L4PROTO(p,nh); - hdrextlen = 8 + (*(pkt+1) * 8); /* 8 bytes + length in 8 octet units */ + IPV6_SET_L4PROTO(p, nh); + hdrextlen = 8 + (*(pkt + 1) * 8); /* 8 bytes + length in 8 octet units */ - SCLogDebug("hdrextlen %"PRIu16, hdrextlen); + SCLogDebug("hdrextlen %" PRIu16, hdrextlen); if (hdrextlen > plen) { ENGINE_SET_INVALID_EVENT(p, IPV6_TRUNC_EXTHDR); @@ -221,14 +215,13 @@ DecodeIPV6ExtHdrs(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, break; case IPPROTO_HOPOPTS: - case IPPROTO_DSTOPTS: - { + case IPPROTO_DSTOPTS: { IPV6OptHAO hao_s, *hao = &hao_s; IPV6OptRA ra_s, *ra = &ra_s; IPV6OptJumbo jumbo_s, *jumbo = &jumbo_s; uint16_t optslen = 0; - IPV6_SET_L4PROTO(p,nh); + IPV6_SET_L4PROTO(p, nh); hdrextlen = (uint16_t)((*(pkt + 1) + 1) << 3); if (hdrextlen > plen) { ENGINE_SET_INVALID_EVENT(p, IPV6_TRUNC_EXTHDR); @@ -253,9 +246,7 @@ DecodeIPV6ExtHdrs(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, hh = 1; optslen = (uint16_t)((*(pkt + 1) + 1) << 3) - 2; - } - else if (nh == IPPROTO_DSTOPTS) - { + } else if (nh == IPPROTO_DSTOPTS) { if (dstopts == 0) { optslen = (uint16_t)((*(pkt + 1) + 1) << 3) - 2; dstopts = 1; @@ -284,14 +275,12 @@ DecodeIPV6ExtHdrs(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, plen -= hdrextlen; break; } -/** \todo move into own function to loaded on demand */ + /** \todo move into own function to loaded on demand */ uint16_t padn_cnt = 0; uint16_t other_cnt = 0; uint16_t offset = 0; - while(offset < optslen) - { - if (*ptr == IPV6OPT_PAD1) - { + while (offset < optslen) { + if (*ptr == IPV6OPT_PAD1) { padn_cnt++; offset++; ptr++; @@ -314,17 +303,16 @@ DecodeIPV6ExtHdrs(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, if (*ptr == IPV6OPT_PADN) /* PadN */ { - //printf("PadN option\n"); + // printf("PadN option\n"); padn_cnt++; /* a zero padN len would be weird */ if (ip6_optlen == 0) ENGINE_SET_EVENT(p, IPV6_EXTHDR_ZERO_LEN_PADN); - } - else if (*ptr == IPV6OPT_RA) /* RA */ + } else if (*ptr == IPV6OPT_RA) /* RA */ { ra->ip6ra_type = *(ptr); - ra->ip6ra_len = ip6_optlen; + ra->ip6ra_len = ip6_optlen; if (ip6_optlen < sizeof(ra->ip6ra_value)) { ENGINE_SET_INVALID_EVENT(p, IPV6_EXTHDR_INVALID_OPTLEN); @@ -333,42 +321,42 @@ DecodeIPV6ExtHdrs(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, memcpy(&ra->ip6ra_value, (ptr + 2), sizeof(ra->ip6ra_value)); ra->ip6ra_value = SCNtohs(ra->ip6ra_value); - //printf("RA option: type %" PRIu32 " len %" PRIu32 " value %" PRIu32 "\n", + // printf("RA option: type %" PRIu32 " len %" PRIu32 " value %" PRIu32 "\n", // ra->ip6ra_type, ra->ip6ra_len, ra->ip6ra_value); other_cnt++; - } - else if (*ptr == IPV6OPT_JUMBO) /* Jumbo */ + } else if (*ptr == IPV6OPT_JUMBO) /* Jumbo */ { jumbo->ip6j_type = *(ptr); - jumbo->ip6j_len = ip6_optlen; + jumbo->ip6j_len = ip6_optlen; if (ip6_optlen < sizeof(jumbo->ip6j_payload_len)) { ENGINE_SET_INVALID_EVENT(p, IPV6_EXTHDR_INVALID_OPTLEN); break; } - memcpy(&jumbo->ip6j_payload_len, (ptr+2), sizeof(jumbo->ip6j_payload_len)); + memcpy(&jumbo->ip6j_payload_len, (ptr + 2), + sizeof(jumbo->ip6j_payload_len)); jumbo->ip6j_payload_len = SCNtohl(jumbo->ip6j_payload_len); - //printf("Jumbo option: type %" PRIu32 " len %" PRIu32 " payload len %" PRIu32 "\n", + // printf("Jumbo option: type %" PRIu32 " len %" PRIu32 " payload len %" + // PRIu32 "\n", // jumbo->ip6j_type, jumbo->ip6j_len, jumbo->ip6j_payload_len); - } - else if (*ptr == IPV6OPT_HAO) /* HAO */ + } else if (*ptr == IPV6OPT_HAO) /* HAO */ { hao->ip6hao_type = *(ptr); - hao->ip6hao_len = ip6_optlen; + hao->ip6hao_len = ip6_optlen; if (ip6_optlen < sizeof(hao->ip6hao_hoa)) { ENGINE_SET_INVALID_EVENT(p, IPV6_EXTHDR_INVALID_OPTLEN); break; } - memcpy(&hao->ip6hao_hoa, (ptr+2), sizeof(hao->ip6hao_hoa)); - //printf("HAO option: type %" PRIu32 " len %" PRIu32 " ", + memcpy(&hao->ip6hao_hoa, (ptr + 2), sizeof(hao->ip6hao_hoa)); + // printf("HAO option: type %" PRIu32 " len %" PRIu32 " ", // hao->ip6hao_type, hao->ip6hao_len); - //char addr_buf[46]; - //PrintInet(AF_INET6, (char *)&(hao->ip6hao_hoa), + // char addr_buf[46]; + // PrintInet(AF_INET6, (char *)&(hao->ip6hao_hoa), // addr_buf,sizeof(addr_buf)); - //printf("home addr %s\n", addr_buf); + // printf("home addr %s\n", addr_buf); other_cnt++; } else { if (nh == IPPROTO_HOPOPTS) @@ -396,9 +384,8 @@ DecodeIPV6ExtHdrs(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, break; } - case IPPROTO_FRAGMENT: - { - IPV6_SET_L4PROTO(p,nh); + case IPPROTO_FRAGMENT: { + IPV6_SET_L4PROTO(p, nh); /* store the offset of this extension into the packet * past the ipv6 header. We use it in defrag for creating * a defragmented packet without the frag header */ @@ -458,23 +445,21 @@ DecodeIPV6ExtHdrs(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, p->flags |= PKT_IS_FRAGMENT; SCReturn; } - case IPPROTO_ESP: - { - IPV6_SET_L4PROTO(p,nh); + case IPPROTO_ESP: { + IPV6_SET_L4PROTO(p, nh); DecodeESP(tv, dtv, p, pkt, plen); SCReturn; } - case IPPROTO_AH: - { - IPV6_SET_L4PROTO(p,nh); + case IPPROTO_AH: { + IPV6_SET_L4PROTO(p, nh); /* we need the header as a minimum */ hdrextlen = sizeof(IPV6AuthHdr); /* the payload len field is the number of extra 4 byte fields, * IPV6AuthHdr already contains the first */ - if (*(pkt+1) > 0) - hdrextlen += ((*(pkt+1) - 1) * 4); + if (*(pkt + 1) > 0) + hdrextlen += ((*(pkt + 1) - 1) * 4); - SCLogDebug("hdrextlen %"PRIu16, hdrextlen); + SCLogDebug("hdrextlen %" PRIu16, hdrextlen); if (hdrextlen > plen) { ENGINE_SET_INVALID_EVENT(p, IPV6_TRUNC_EXTHDR); @@ -502,21 +487,21 @@ DecodeIPV6ExtHdrs(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, break; } case IPPROTO_IPIP: - IPV6_SET_L4PROTO(p,nh); + IPV6_SET_L4PROTO(p, nh); DecodeIPv4inIPv6(tv, dtv, p, pkt, plen); SCReturn; /* none, last header */ case IPPROTO_NONE: - IPV6_SET_L4PROTO(p,nh); + IPV6_SET_L4PROTO(p, nh); SCReturn; case IPPROTO_ICMP: - ENGINE_SET_EVENT(p,IPV6_WITH_ICMPV4); + ENGINE_SET_EVENT(p, IPV6_WITH_ICMPV4); SCReturn; /* no parsing yet, just skip it */ case IPPROTO_MH: case IPPROTO_HIP: case IPPROTO_SHIM6: - hdrextlen = 8 + (*(pkt+1) * 8); /* 8 bytes + length in 8 octet units */ + hdrextlen = 8 + (*(pkt + 1) * 8); /* 8 bytes + length in 8 octet units */ if (hdrextlen > plen) { ENGINE_SET_INVALID_EVENT(p, IPV6_TRUNC_EXTHDR); SCReturn; @@ -527,7 +512,7 @@ DecodeIPV6ExtHdrs(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, break; default: ENGINE_SET_EVENT(p, IPV6_UNKNOWN_NEXT_HEADER); - IPV6_SET_L4PROTO(p,nh); + IPV6_SET_L4PROTO(p, nh); SCReturn; } } @@ -535,28 +520,28 @@ DecodeIPV6ExtHdrs(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, SCReturn; } -static int DecodeIPV6Packet (ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, const uint8_t *pkt, uint16_t len) +static int DecodeIPV6Packet( + ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, const uint8_t *pkt, uint16_t len) { if (unlikely(len < IPV6_HEADER_LEN)) { return -1; } if (unlikely(IP_GET_RAW_VER(pkt) != 6)) { - SCLogDebug("wrong ip version %d",IP_GET_RAW_VER(pkt)); + SCLogDebug("wrong ip version %d", IP_GET_RAW_VER(pkt)); ENGINE_SET_INVALID_EVENT(p, IPV6_WRONG_IP_VER); return -1; } p->ip6h = (IPV6Hdr *)pkt; - if (unlikely(len < (IPV6_HEADER_LEN + IPV6_GET_PLEN(p)))) - { + if (unlikely(len < (IPV6_HEADER_LEN + IPV6_GET_PLEN(p)))) { ENGINE_SET_INVALID_EVENT(p, IPV6_TRUNC_PKT); return -1; } - SET_IPV6_SRC_ADDR(p,&p->src); - SET_IPV6_DST_ADDR(p,&p->dst); + SET_IPV6_SRC_ADDR(p, &p->src); + SET_IPV6_DST_ADDR(p, &p->dst); return 0; } @@ -569,7 +554,7 @@ int DecodeIPV6(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, const uint8_t * return TM_ECODE_FAILED; } /* do the actual decoding */ - int ret = DecodeIPV6Packet (tv, dtv, p, pkt, len); + int ret = DecodeIPV6Packet(tv, dtv, p, pkt, len); if (unlikely(ret < 0)) { CLEAR_IPV6_PACKET(p); return TM_ECODE_FAILED; @@ -582,28 +567,29 @@ int DecodeIPV6(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, const uint8_t * char s[46], d[46]; PrintInet(AF_INET6, (const void *)GET_IPV6_SRC_ADDR(p), s, sizeof(s)); PrintInet(AF_INET6, (const void *)GET_IPV6_DST_ADDR(p), d, sizeof(d)); - SCLogDebug("IPV6 %s->%s - CLASS: %" PRIu32 " FLOW: %" PRIu32 " NH: %" PRIu32 " PLEN: %" PRIu32 " HLIM: %" PRIu32 "", s,d, - IPV6_GET_CLASS(p), IPV6_GET_FLOW(p), IPV6_GET_NH(p), IPV6_GET_PLEN(p), + SCLogDebug("IPV6 %s->%s - CLASS: %" PRIu32 " FLOW: %" PRIu32 " NH: %" PRIu32 + " PLEN: %" PRIu32 " HLIM: %" PRIu32 "", + s, d, IPV6_GET_CLASS(p), IPV6_GET_FLOW(p), IPV6_GET_NH(p), IPV6_GET_PLEN(p), IPV6_GET_HLIM(p)); } #endif /* DEBUG */ /* now process the Ext headers and/or the L4 Layer */ - switch(IPV6_GET_NH(p)) { + switch (IPV6_GET_NH(p)) { case IPPROTO_TCP: - IPV6_SET_L4PROTO (p, IPPROTO_TCP); + IPV6_SET_L4PROTO(p, IPPROTO_TCP); DecodeTCP(tv, dtv, p, pkt + IPV6_HEADER_LEN, IPV6_GET_PLEN(p)); return TM_ECODE_OK; case IPPROTO_UDP: - IPV6_SET_L4PROTO (p, IPPROTO_UDP); + IPV6_SET_L4PROTO(p, IPPROTO_UDP); DecodeUDP(tv, dtv, p, pkt + IPV6_HEADER_LEN, IPV6_GET_PLEN(p)); return TM_ECODE_OK; case IPPROTO_ICMPV6: - IPV6_SET_L4PROTO (p, IPPROTO_ICMPV6); + IPV6_SET_L4PROTO(p, IPPROTO_ICMPV6); DecodeICMPV6(tv, dtv, p, pkt + IPV6_HEADER_LEN, IPV6_GET_PLEN(p)); return TM_ECODE_OK; case IPPROTO_SCTP: - IPV6_SET_L4PROTO (p, IPPROTO_SCTP); + IPV6_SET_L4PROTO(p, IPPROTO_SCTP); DecodeSCTP(tv, dtv, p, pkt + IPV6_HEADER_LEN, IPV6_GET_PLEN(p)); return TM_ECODE_OK; case IPPROTO_IPIP: @@ -630,20 +616,20 @@ int DecodeIPV6(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, const uint8_t * DecodeIPV6ExtHdrs(tv, dtv, p, pkt + IPV6_HEADER_LEN, IPV6_GET_PLEN(p)); break; case IPPROTO_ICMP: - ENGINE_SET_EVENT(p,IPV6_WITH_ICMPV4); + ENGINE_SET_EVENT(p, IPV6_WITH_ICMPV4); break; default: ENGINE_SET_EVENT(p, IPV6_UNKNOWN_NEXT_HEADER); - IPV6_SET_L4PROTO (p, IPV6_GET_NH(p)); + IPV6_SET_L4PROTO(p, IPV6_GET_NH(p)); break; } - p->proto = IPV6_GET_L4PROTO (p); + p->proto = IPV6_GET_L4PROTO(p); /* Pass to defragger if a fragment. */ if (IPV6_EXTHDR_ISSET_FH(p)) { Packet *rp = Defrag(tv, dtv, p); if (rp != NULL) { - PacketEnqueueNoLock(&tv->decode_pq,rp); + PacketEnqueueNoLock(&tv->decode_pq, rp); } } @@ -657,7 +643,7 @@ int DecodeIPV6(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, const uint8_t * /** * \test fragment decoding */ -static int DecodeIPV6FragTest01 (void) +static int DecodeIPV6FragTest01(void) { // clang-format off @@ -827,7 +813,7 @@ static int DecodeIPV6FragTest01 (void) /** * \test routing header decode */ -static int DecodeIPV6RouteTest01 (void) +static int DecodeIPV6RouteTest01(void) { // clang-format off uint8_t raw_pkt1[] = { @@ -857,8 +843,8 @@ static int DecodeIPV6RouteTest01 (void) DecodeIPV6(&tv, &dtv, p1, GET_PKT_DATA(p1), GET_PKT_LEN(p1)); - FAIL_IF (!(IPV6_EXTHDR_ISSET_RH(p1))); - FAIL_IF (p1->ip6eh.rh_type != 0); + FAIL_IF(!(IPV6_EXTHDR_ISSET_RH(p1))); + FAIL_IF(p1->ip6eh.rh_type != 0); PacketRecycle(p1); SCFree(p1); FlowShutdown(); @@ -868,7 +854,7 @@ static int DecodeIPV6RouteTest01 (void) /** * \test HOP header decode */ -static int DecodeIPV6HopTest01 (void) +static int DecodeIPV6HopTest01(void) { // clang-format off uint8_t raw_pkt1[] = { 0x60, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x01, 0xfe, 0x80, 0x00, 0x00, @@ -892,7 +878,7 @@ static int DecodeIPV6HopTest01 (void) DecodeIPV6(&tv, &dtv, p1, GET_PKT_DATA(p1), GET_PKT_LEN(p1)); - FAIL_IF (!(ENGINE_ISSET_EVENT(p1, IPV6_HOPOPTS_UNKNOWN_OPT))); + FAIL_IF(!(ENGINE_ISSET_EVENT(p1, IPV6_HOPOPTS_UNKNOWN_OPT))); PacketRecycle(p1); SCFree(p1); diff --git a/src/decode-ipv6.h b/src/decode-ipv6.h index 651939ae567f..81d8ed46aeb8 100644 --- a/src/decode-ipv6.h +++ b/src/decode-ipv6.h @@ -24,20 +24,19 @@ #ifndef __DECODE_IPV6_H__ #define __DECODE_IPV6_H__ -#define IPV6_HEADER_LEN 40 -#define IPV6_MAXPACKET 65535 /* maximum packet size */ -#define IPV6_MAX_OPT 40 +#define IPV6_HEADER_LEN 40 +#define IPV6_MAXPACKET 65535 /* maximum packet size */ +#define IPV6_MAX_OPT 40 -typedef struct IPV6Hdr_ -{ +typedef struct IPV6Hdr_ { union { struct ip6_un1_ { uint32_t ip6_un1_flow; /* 20 bits of flow-ID */ uint16_t ip6_un1_plen; /* payload length */ - uint8_t ip6_un1_nxt; /* next header */ - uint8_t ip6_un1_hlim; /* hop limit */ + uint8_t ip6_un1_nxt; /* next header */ + uint8_t ip6_un1_hlim; /* hop limit */ } ip6_un1; - uint8_t ip6_un2_vfc; /* 4 bits version, top 4 bits class */ + uint8_t ip6_un2_vfc; /* 4 bits version, top 4 bits class */ } ip6_hdrun; union { @@ -49,170 +48,150 @@ typedef struct IPV6Hdr_ } ip6_hdrun2; } IPV6Hdr; -#define s_ip6_src ip6_hdrun2.ip6_un2.ip6_src -#define s_ip6_dst ip6_hdrun2.ip6_un2.ip6_dst -#define s_ip6_addrs ip6_hdrun2.ip6_addrs +#define s_ip6_src ip6_hdrun2.ip6_un2.ip6_src +#define s_ip6_dst ip6_hdrun2.ip6_un2.ip6_dst +#define s_ip6_addrs ip6_hdrun2.ip6_addrs -#define s_ip6_vfc ip6_hdrun.ip6_un2_vfc -#define s_ip6_flow ip6_hdrun.ip6_un1.ip6_un1_flow -#define s_ip6_plen ip6_hdrun.ip6_un1.ip6_un1_plen -#define s_ip6_nxt ip6_hdrun.ip6_un1.ip6_un1_nxt -#define s_ip6_hlim ip6_hdrun.ip6_un1.ip6_un1_hlim +#define s_ip6_vfc ip6_hdrun.ip6_un2_vfc +#define s_ip6_flow ip6_hdrun.ip6_un1.ip6_un1_flow +#define s_ip6_plen ip6_hdrun.ip6_un1.ip6_un1_plen +#define s_ip6_nxt ip6_hdrun.ip6_un1.ip6_un1_nxt +#define s_ip6_hlim ip6_hdrun.ip6_un1.ip6_un1_hlim -#define IPV6_GET_RAW_VER(ip6h) (((ip6h)->s_ip6_vfc & 0xf0) >> 4) -#define IPV6_GET_RAW_CLASS(ip6h) ((SCNtohl((ip6h)->s_ip6_flow) & 0x0FF00000) >> 20) -#define IPV6_GET_RAW_FLOW(ip6h) (SCNtohl((ip6h)->s_ip6_flow) & 0x000FFFFF) -#define IPV6_GET_RAW_NH(ip6h) ((ip6h)->s_ip6_nxt) -#define IPV6_GET_RAW_PLEN(ip6h) (SCNtohs((ip6h)->s_ip6_plen)) -#define IPV6_GET_RAW_HLIM(ip6h) ((ip6h)->s_ip6_hlim) +#define IPV6_GET_RAW_VER(ip6h) (((ip6h)->s_ip6_vfc & 0xf0) >> 4) +#define IPV6_GET_RAW_CLASS(ip6h) ((SCNtohl((ip6h)->s_ip6_flow) & 0x0FF00000) >> 20) +#define IPV6_GET_RAW_FLOW(ip6h) (SCNtohl((ip6h)->s_ip6_flow) & 0x000FFFFF) +#define IPV6_GET_RAW_NH(ip6h) ((ip6h)->s_ip6_nxt) +#define IPV6_GET_RAW_PLEN(ip6h) (SCNtohs((ip6h)->s_ip6_plen)) +#define IPV6_GET_RAW_HLIM(ip6h) ((ip6h)->s_ip6_hlim) -#define IPV6_SET_RAW_VER(ip6h, value) ((ip6h)->s_ip6_vfc = (((ip6h)->s_ip6_vfc & 0x0f) | (value << 4))) -#define IPV6_SET_RAW_NH(ip6h, value) ((ip6h)->s_ip6_nxt = (value)) - -#define IPV6_SET_L4PROTO(p,proto) (p)->ip6vars.l4proto = (proto) -#define IPV6_SET_EXTHDRS_LEN(p,len) (p)->ip6vars.exthdrs_len = (len) +#define IPV6_SET_RAW_VER(ip6h, value) \ + ((ip6h)->s_ip6_vfc = (((ip6h)->s_ip6_vfc & 0x0f) | (value << 4))) +#define IPV6_SET_RAW_NH(ip6h, value) ((ip6h)->s_ip6_nxt = (value)) +#define IPV6_SET_L4PROTO(p, proto) (p)->ip6vars.l4proto = (proto) +#define IPV6_SET_EXTHDRS_LEN(p, len) (p)->ip6vars.exthdrs_len = (len) /* ONLY call these functions after making sure that: * 1. p->ip6h is set * 2. p->ip6h is valid (len is correct) */ -#define IPV6_GET_VER(p) \ - IPV6_GET_RAW_VER((p)->ip6h) -#define IPV6_GET_CLASS(p) \ - IPV6_GET_RAW_CLASS((p)->ip6h) -#define IPV6_GET_FLOW(p) \ - IPV6_GET_RAW_FLOW((p)->ip6h) -#define IPV6_GET_NH(p) \ - (IPV6_GET_RAW_NH((p)->ip6h)) -#define IPV6_GET_PLEN(p) \ - IPV6_GET_RAW_PLEN((p)->ip6h) -#define IPV6_GET_HLIM(p) \ - (IPV6_GET_RAW_HLIM((p)->ip6h)) - -#define IPV6_GET_L4PROTO(p) \ - ((p)->ip6vars.l4proto) -#define IPV6_GET_EXTHDRS_LEN(p) \ - ((p)->ip6vars.exthdrs_len) +#define IPV6_GET_VER(p) IPV6_GET_RAW_VER((p)->ip6h) +#define IPV6_GET_CLASS(p) IPV6_GET_RAW_CLASS((p)->ip6h) +#define IPV6_GET_FLOW(p) IPV6_GET_RAW_FLOW((p)->ip6h) +#define IPV6_GET_NH(p) (IPV6_GET_RAW_NH((p)->ip6h)) +#define IPV6_GET_PLEN(p) IPV6_GET_RAW_PLEN((p)->ip6h) +#define IPV6_GET_HLIM(p) (IPV6_GET_RAW_HLIM((p)->ip6h)) + +#define IPV6_GET_L4PROTO(p) ((p)->ip6vars.l4proto) +#define IPV6_GET_EXTHDRS_LEN(p) ((p)->ip6vars.exthdrs_len) /** \brief get the highest proto/next header field we know */ //#define IPV6_GET_UPPER_PROTO(p) (p)->ip6eh.ip6_exthdrs_cnt ? // (p)->ip6eh.ip6_exthdrs[(p)->ip6eh.ip6_exthdrs_cnt - 1].next : IPV6_GET_NH((p)) /* helper structure with parsed ipv6 info */ -typedef struct IPV6Vars_ -{ - uint8_t l4proto; /**< the proto after the extension headers - * store while decoding so we don't have - * to loop through the exthdrs all the time */ - uint16_t exthdrs_len; /**< length of the exthdrs */ +typedef struct IPV6Vars_ { + uint8_t l4proto; /**< the proto after the extension headers + * store while decoding so we don't have + * to loop through the exthdrs all the time */ + uint16_t exthdrs_len; /**< length of the exthdrs */ } IPV6Vars; -#define CLEAR_IPV6_PACKET(p) do { \ - (p)->ip6h = NULL; \ - (p)->ip6vars.l4proto = 0; \ - (p)->ip6vars.exthdrs_len = 0; \ - memset(&(p)->ip6eh, 0x00, sizeof((p)->ip6eh)); \ -} while (0) +#define CLEAR_IPV6_PACKET(p) \ + do { \ + (p)->ip6h = NULL; \ + (p)->ip6vars.l4proto = 0; \ + (p)->ip6vars.exthdrs_len = 0; \ + memset(&(p)->ip6eh, 0x00, sizeof((p)->ip6eh)); \ + } while (0) /* Fragment header */ -typedef struct IPV6FragHdr_ -{ - uint8_t ip6fh_nxt; /* next header */ - uint8_t ip6fh_reserved; /* reserved field */ - uint16_t ip6fh_offlg; /* offset, reserved, and flag */ - uint32_t ip6fh_ident; /* identification */ +typedef struct IPV6FragHdr_ { + uint8_t ip6fh_nxt; /* next header */ + uint8_t ip6fh_reserved; /* reserved field */ + uint16_t ip6fh_offlg; /* offset, reserved, and flag */ + uint32_t ip6fh_ident; /* identification */ } __attribute__((__packed__)) IPV6FragHdr; -#define IPV6_EXTHDR_GET_FH_NH(p) (p)->ip6eh.fh_nh -#define IPV6_EXTHDR_GET_FH_OFFSET(p) (p)->ip6eh.fh_offset -#define IPV6_EXTHDR_GET_FH_FLAG(p) (p)->ip6eh.fh_more_frags_set -#define IPV6_EXTHDR_GET_FH_ID(p) (p)->ip6eh.fh_id +#define IPV6_EXTHDR_GET_FH_NH(p) (p)->ip6eh.fh_nh +#define IPV6_EXTHDR_GET_FH_OFFSET(p) (p)->ip6eh.fh_offset +#define IPV6_EXTHDR_GET_FH_FLAG(p) (p)->ip6eh.fh_more_frags_set +#define IPV6_EXTHDR_GET_FH_ID(p) (p)->ip6eh.fh_id /* rfc 1826 */ -typedef struct IPV6AuthHdr_ -{ - uint8_t ip6ah_nxt; /* next header */ - uint8_t ip6ah_len; /* header length in units of 8 bytes, not - including first 8 bytes. */ - uint16_t ip6ah_reserved; /* reserved for future use */ - uint32_t ip6ah_spi; /* SECURITY PARAMETERS INDEX (SPI) */ - uint32_t ip6ah_seq; /* sequence number */ +typedef struct IPV6AuthHdr_ { + uint8_t ip6ah_nxt; /* next header */ + uint8_t ip6ah_len; /* header length in units of 8 bytes, not + including first 8 bytes. */ + uint16_t ip6ah_reserved; /* reserved for future use */ + uint32_t ip6ah_spi; /* SECURITY PARAMETERS INDEX (SPI) */ + uint32_t ip6ah_seq; /* sequence number */ } __attribute__((__packed__)) IPV6AuthHdr; -typedef struct IPV6EspHdr_ -{ - uint32_t ip6esph_spi; /* SECURITY PARAMETERS INDEX (SPI) */ - uint32_t ip6esph_seq; /* sequence number */ +typedef struct IPV6EspHdr_ { + uint32_t ip6esph_spi; /* SECURITY PARAMETERS INDEX (SPI) */ + uint32_t ip6esph_seq; /* sequence number */ } __attribute__((__packed__)) IPV6EspHdr; -typedef struct IPV6RouteHdr_ -{ - uint8_t ip6rh_nxt; /* next header */ - uint8_t ip6rh_len; /* header length in units of 8 bytes, not - including first 8 bytes. */ - uint8_t ip6rh_type; /* routing type */ - uint8_t ip6rh_segsleft; /* segments left */ +typedef struct IPV6RouteHdr_ { + uint8_t ip6rh_nxt; /* next header */ + uint8_t ip6rh_len; /* header length in units of 8 bytes, not + including first 8 bytes. */ + uint8_t ip6rh_type; /* routing type */ + uint8_t ip6rh_segsleft; /* segments left */ } __attribute__((__packed__)) IPV6RouteHdr; - /* Hop-by-Hop header and Destination Options header use options that are * defined here. */ -#define IPV6OPT_PAD1 0x00 -#define IPV6OPT_PADN 0x01 -#define IPV6OPT_RA 0x05 -#define IPV6OPT_JUMBO 0xC2 -#define IPV6OPT_HAO 0xC9 +#define IPV6OPT_PAD1 0x00 +#define IPV6OPT_PADN 0x01 +#define IPV6OPT_RA 0x05 +#define IPV6OPT_JUMBO 0xC2 +#define IPV6OPT_HAO 0xC9 /* Home Address Option */ -typedef struct IPV6OptHAO_ -{ - uint8_t ip6hao_type; /* Option type */ - uint8_t ip6hao_len; /* Option Data len (excludes type and len) */ - struct in6_addr ip6hao_hoa; /* Home address. */ +typedef struct IPV6OptHAO_ { + uint8_t ip6hao_type; /* Option type */ + uint8_t ip6hao_len; /* Option Data len (excludes type and len) */ + struct in6_addr ip6hao_hoa; /* Home address. */ } IPV6OptHAO; /* Router Alert Option */ -typedef struct IPV6OptRA_ -{ - uint8_t ip6ra_type; /* Option type */ - uint8_t ip6ra_len; /* Option Data len (excludes type and len) */ - uint16_t ip6ra_value; /* Router Alert value */ +typedef struct IPV6OptRA_ { + uint8_t ip6ra_type; /* Option type */ + uint8_t ip6ra_len; /* Option Data len (excludes type and len) */ + uint16_t ip6ra_value; /* Router Alert value */ } IPV6OptRA; /* Jumbo Option */ -typedef struct IPV6OptJumbo_ -{ - uint8_t ip6j_type; /* Option type */ - uint8_t ip6j_len; /* Option Data len (excludes type and len) */ - uint32_t ip6j_payload_len; /* Jumbo Payload Length */ +typedef struct IPV6OptJumbo_ { + uint8_t ip6j_type; /* Option type */ + uint8_t ip6j_len; /* Option Data len (excludes type and len) */ + uint32_t ip6j_payload_len; /* Jumbo Payload Length */ } IPV6OptJumbo; -typedef struct IPV6HopOptsHdr_ -{ - uint8_t ip6hh_nxt; /* next header */ - uint8_t ip6hh_len; /* header length in units of 8 bytes, not - including first 8 bytes. */ +typedef struct IPV6HopOptsHdr_ { + uint8_t ip6hh_nxt; /* next header */ + uint8_t ip6hh_len; /* header length in units of 8 bytes, not + including first 8 bytes. */ } __attribute__((__packed__)) IPV6HopOptsHdr; -typedef struct IPV6DstOptsHdr_ -{ - uint8_t ip6dh_nxt; /* next header */ - uint8_t ip6dh_len; /* header length in units of 8 bytes, not - including first 8 bytes. */ +typedef struct IPV6DstOptsHdr_ { + uint8_t ip6dh_nxt; /* next header */ + uint8_t ip6dh_len; /* header length in units of 8 bytes, not + including first 8 bytes. */ } __attribute__((__packed__)) IPV6DstOptsHdr; -typedef struct IPV6GenOptHdr_ -{ +typedef struct IPV6GenOptHdr_ { uint8_t type; uint8_t next; uint8_t len; uint8_t *data; -} IPV6GenOptHdr; +} IPV6GenOptHdr; -typedef struct IPV6ExtHdrs_ -{ +typedef struct IPV6ExtHdrs_ { bool rh_set; uint8_t rh_type; @@ -235,10 +214,10 @@ typedef struct IPV6ExtHdrs_ } IPV6ExtHdrs; -#define IPV6_EXTHDR_SET_FH(p) (p)->ip6eh.fh_set = true -#define IPV6_EXTHDR_ISSET_FH(p) (p)->ip6eh.fh_set -#define IPV6_EXTHDR_SET_RH(p) (p)->ip6eh.rh_set = true -#define IPV6_EXTHDR_ISSET_RH(p) (p)->ip6eh.rh_set +#define IPV6_EXTHDR_SET_FH(p) (p)->ip6eh.fh_set = true +#define IPV6_EXTHDR_ISSET_FH(p) (p)->ip6eh.fh_set +#define IPV6_EXTHDR_SET_RH(p) (p)->ip6eh.rh_set = true +#define IPV6_EXTHDR_ISSET_RH(p) (p)->ip6eh.rh_set void DecodeIPV6RegisterTests(void); diff --git a/src/decode-mpls.c b/src/decode-mpls.c index 349b75288dd1..6bc1f96d3019 100644 --- a/src/decode-mpls.c +++ b/src/decode-mpls.c @@ -38,16 +38,15 @@ #define MPLS_LABEL_IPV6 2 #define MPLS_LABEL_NULL 3 -#define MPLS_LABEL(shim) SCNtohl(shim) >> 12 -#define MPLS_BOTTOM(shim) ((SCNtohl(shim) >> 8) & 0x1) +#define MPLS_LABEL(shim) SCNtohl(shim) >> 12 +#define MPLS_BOTTOM(shim) ((SCNtohl(shim) >> 8) & 0x1) /* Inner protocol guessing values. */ -#define MPLS_PROTO_ETHERNET_PW 0 -#define MPLS_PROTO_IPV4 4 -#define MPLS_PROTO_IPV6 6 +#define MPLS_PROTO_ETHERNET_PW 0 +#define MPLS_PROTO_IPV4 4 +#define MPLS_PROTO_IPV6 6 -int DecodeMPLS(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, - const uint8_t *pkt, uint32_t len) +int DecodeMPLS(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, const uint8_t *pkt, uint32_t len) { DEBUG_VALIDATE_BUG_ON(pkt == NULL); @@ -76,22 +75,18 @@ int DecodeMPLS(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, return TM_ECODE_FAILED; } return DecodeIPV4(tv, dtv, p, pkt, (uint16_t)len); - } - else if (label == MPLS_LABEL_ROUTER_ALERT) { + } else if (label == MPLS_LABEL_ROUTER_ALERT) { /* Not valid at the bottom of the stack. */ event = MPLS_BAD_LABEL_ROUTER_ALERT; - } - else if (label == MPLS_LABEL_IPV6) { + } else if (label == MPLS_LABEL_IPV6) { if (len > USHRT_MAX) { return TM_ECODE_FAILED; } return DecodeIPV6(tv, dtv, p, pkt, (uint16_t)len); - } - else if (label == MPLS_LABEL_NULL) { + } else if (label == MPLS_LABEL_NULL) { /* Shouldn't appear on the wire. */ event = MPLS_BAD_LABEL_IMPLICIT_NULL; - } - else if (label < MPLS_MAX_RESERVED_LABEL) { + } else if (label < MPLS_MAX_RESERVED_LABEL) { event = MPLS_BAD_LABEL_RESERVED; } @@ -108,24 +103,24 @@ int DecodeMPLS(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, /* Best guess at inner packet. */ switch (pkt[0] >> 4) { - case MPLS_PROTO_IPV4: - if (len > USHRT_MAX) { - return TM_ECODE_FAILED; - } - DecodeIPV4(tv, dtv, p, pkt, (uint16_t)len); - break; - case MPLS_PROTO_IPV6: - if (len > USHRT_MAX) { - return TM_ECODE_FAILED; - } - DecodeIPV6(tv, dtv, p, pkt, (uint16_t)len); - break; - case MPLS_PROTO_ETHERNET_PW: - DecodeEthernet(tv, dtv, p, pkt + MPLS_PW_LEN, len - MPLS_PW_LEN); - break; - default: - ENGINE_SET_INVALID_EVENT(p, MPLS_UNKNOWN_PAYLOAD_TYPE); - return TM_ECODE_OK; + case MPLS_PROTO_IPV4: + if (len > USHRT_MAX) { + return TM_ECODE_FAILED; + } + DecodeIPV4(tv, dtv, p, pkt, (uint16_t)len); + break; + case MPLS_PROTO_IPV6: + if (len > USHRT_MAX) { + return TM_ECODE_FAILED; + } + DecodeIPV6(tv, dtv, p, pkt, (uint16_t)len); + break; + case MPLS_PROTO_ETHERNET_PW: + DecodeEthernet(tv, dtv, p, pkt + MPLS_PW_LEN, len - MPLS_PW_LEN); + break; + default: + ENGINE_SET_INVALID_EVENT(p, MPLS_UNKNOWN_PAYLOAD_TYPE); + return TM_ECODE_OK; } end: @@ -151,7 +146,7 @@ static int DecodeMPLSTestHeaderTooSmall(void) ThreadVars tv; DecodeThreadVars dtv; memset(&dtv, 0, sizeof(DecodeThreadVars)); - memset(&tv, 0, sizeof(ThreadVars)); + memset(&tv, 0, sizeof(ThreadVars)); DecodeMPLS(&tv, &dtv, p, pkt, sizeof(pkt)); FAIL_IF(!ENGINE_ISSET_EVENT(p, MPLS_HEADER_TOO_SMALL)); @@ -165,7 +160,7 @@ static int DecodeMPLSTestPacketTooSmall(void) ThreadVars tv; DecodeThreadVars dtv; memset(&dtv, 0, sizeof(DecodeThreadVars)); - memset(&tv, 0, sizeof(ThreadVars)); + memset(&tv, 0, sizeof(ThreadVars)); Packet *p = PacketGetFromAlloc(); FAIL_IF_NULL(p); @@ -243,7 +238,7 @@ static int DecodeMPLSTestBadLabelRouterAlert(void) DecodeThreadVars dtv; memset(&dtv, 0, sizeof(DecodeThreadVars)); - memset(&tv, 0, sizeof(ThreadVars)); + memset(&tv, 0, sizeof(ThreadVars)); DecodeMPLS(&tv, &dtv, p, pkt, sizeof(pkt)); FAIL_IF(!ENGINE_ISSET_EVENT(p, MPLS_BAD_LABEL_ROUTER_ALERT)); @@ -277,7 +272,7 @@ static int DecodeMPLSTestBadLabelImplicitNull(void) ThreadVars tv; DecodeThreadVars dtv; memset(&dtv, 0, sizeof(DecodeThreadVars)); - memset(&tv, 0, sizeof(ThreadVars)); + memset(&tv, 0, sizeof(ThreadVars)); DecodeMPLS(&tv, &dtv, p, pkt, sizeof(pkt)); FAIL_IF(!ENGINE_ISSET_EVENT(p, MPLS_BAD_LABEL_IMPLICIT_NULL)); @@ -311,7 +306,7 @@ static int DecodeMPLSTestBadLabelReserved(void) ThreadVars tv; DecodeThreadVars dtv; memset(&dtv, 0, sizeof(DecodeThreadVars)); - memset(&tv, 0, sizeof(ThreadVars)); + memset(&tv, 0, sizeof(ThreadVars)); DecodeMPLS(&tv, &dtv, p, pkt, sizeof(pkt)); FAIL_IF(!ENGINE_ISSET_EVENT(p, MPLS_BAD_LABEL_RESERVED)); @@ -348,7 +343,7 @@ static int DecodeMPLSTestUnknownPayloadType(void) ThreadVars tv; DecodeThreadVars dtv; memset(&dtv, 0, sizeof(DecodeThreadVars)); - memset(&tv, 0, sizeof(ThreadVars)); + memset(&tv, 0, sizeof(ThreadVars)); DecodeMPLS(&tv, &dtv, p, pkt, sizeof(pkt)); FAIL_IF(!ENGINE_ISSET_EVENT(p, MPLS_UNKNOWN_PAYLOAD_TYPE)); @@ -362,17 +357,11 @@ static int DecodeMPLSTestUnknownPayloadType(void) void DecodeMPLSRegisterTests(void) { #ifdef UNITTESTS - UtRegisterTest("DecodeMPLSTestHeaderTooSmall", - DecodeMPLSTestHeaderTooSmall); - UtRegisterTest("DecodeMPLSTestPacketTooSmall", - DecodeMPLSTestPacketTooSmall); - UtRegisterTest("DecodeMPLSTestBadLabelRouterAlert", - DecodeMPLSTestBadLabelRouterAlert); - UtRegisterTest("DecodeMPLSTestBadLabelImplicitNull", - DecodeMPLSTestBadLabelImplicitNull); - UtRegisterTest("DecodeMPLSTestBadLabelReserved", - DecodeMPLSTestBadLabelReserved); - UtRegisterTest("DecodeMPLSTestUnknownPayloadType", - DecodeMPLSTestUnknownPayloadType); + UtRegisterTest("DecodeMPLSTestHeaderTooSmall", DecodeMPLSTestHeaderTooSmall); + UtRegisterTest("DecodeMPLSTestPacketTooSmall", DecodeMPLSTestPacketTooSmall); + UtRegisterTest("DecodeMPLSTestBadLabelRouterAlert", DecodeMPLSTestBadLabelRouterAlert); + UtRegisterTest("DecodeMPLSTestBadLabelImplicitNull", DecodeMPLSTestBadLabelImplicitNull); + UtRegisterTest("DecodeMPLSTestBadLabelReserved", DecodeMPLSTestBadLabelReserved); + UtRegisterTest("DecodeMPLSTestUnknownPayloadType", DecodeMPLSTestUnknownPayloadType); #endif /* UNITTESTS */ } diff --git a/src/decode-nsh.h b/src/decode-nsh.h index a45cce3029e0..534c8f83e3e8 100644 --- a/src/decode-nsh.h +++ b/src/decode-nsh.h @@ -25,7 +25,6 @@ #ifndef __DECODE_NSH_H__ #define __DECODE_NSH_H__ - #define NSH_NEXT_PROTO_UNASSIGNED 0x0 #define NSH_NEXT_PROTO_IPV4 0x1 #define NSH_NEXT_PROTO_IPV6 0x2 diff --git a/src/decode-null.c b/src/decode-null.c index 5bf934045766..15c3cd4786f9 100644 --- a/src/decode-null.c +++ b/src/decode-null.c @@ -48,8 +48,7 @@ #define AF_INET6_SOLARIS 26 #define AF_INET6_WINSOCK 23 -int DecodeNull(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, - const uint8_t *pkt, uint32_t len) +int DecodeNull(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, const uint8_t *pkt, uint32_t len) { DEBUG_VALIDATE_BUG_ON(pkt == NULL); @@ -68,7 +67,7 @@ int DecodeNull(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, #else uint32_t type = *((uint32_t *)pkt); #endif - switch(type) { + switch (type) { case AF_INET: SCLogDebug("IPV4 Packet"); if (GET_PKT_LEN(p) - HDR_SIZE > USHRT_MAX) { diff --git a/src/decode-ppp.c b/src/decode-ppp.c index 676e64c0558c..a2026b605bd7 100644 --- a/src/decode-ppp.c +++ b/src/decode-ppp.c @@ -21,7 +21,6 @@ * @{ */ - /** * \file * @@ -41,8 +40,7 @@ #include "util-unittest.h" #include "util-debug.h" -int DecodePPP(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, - const uint8_t *pkt, uint32_t len) +int DecodePPP(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, const uint8_t *pkt, uint32_t len) { DEBUG_VALIDATE_BUG_ON(pkt == NULL); @@ -58,14 +56,13 @@ int DecodePPP(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, p->ppph = (PPPHdr *)pkt; - SCLogDebug("p %p pkt %p PPP protocol %04x Len: %" PRIu32 "", - p, pkt, SCNtohs(p->ppph->protocol), len); + SCLogDebug("p %p pkt %p PPP protocol %04x Len: %" PRIu32 "", p, pkt, SCNtohs(p->ppph->protocol), + len); - switch (SCNtohs(p->ppph->protocol)) - { + switch (SCNtohs(p->ppph->protocol)) { case PPP_VJ_UCOMP: if (unlikely(len < (PPP_HEADER_LEN + IPV4_HEADER_LEN))) { - ENGINE_SET_INVALID_EVENT(p,PPPVJU_PKT_TOO_SMALL); + ENGINE_SET_INVALID_EVENT(p, PPPVJU_PKT_TOO_SMALL); p->ppph = NULL; return TM_ECODE_FAILED; } @@ -83,7 +80,7 @@ int DecodePPP(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, case PPP_IP: if (unlikely(len < (PPP_HEADER_LEN + IPV4_HEADER_LEN))) { - ENGINE_SET_INVALID_EVENT(p,PPPIPV4_PKT_TOO_SMALL); + ENGINE_SET_INVALID_EVENT(p, PPPIPV4_PKT_TOO_SMALL); p->ppph = NULL; return TM_ECODE_FAILED; } @@ -96,7 +93,7 @@ int DecodePPP(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, /* PPP IPv6 was not tested */ case PPP_IPV6: if (unlikely(len < (PPP_HEADER_LEN + IPV6_HEADER_LEN))) { - ENGINE_SET_INVALID_EVENT(p,PPPIPV6_PKT_TOO_SMALL); + ENGINE_SET_INVALID_EVENT(p, PPPIPV6_PKT_TOO_SMALL); p->ppph = NULL; return TM_ECODE_FAILED; } @@ -134,15 +131,14 @@ int DecodePPP(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, case PPP_PAP: case PPP_LQM: case PPP_CHAP: - ENGINE_SET_EVENT(p,PPP_UNSUP_PROTO); + ENGINE_SET_EVENT(p, PPP_UNSUP_PROTO); return TM_ECODE_OK; default: - SCLogDebug("unknown PPP protocol: %" PRIx32 "",SCNtohs(p->ppph->protocol)); + SCLogDebug("unknown PPP protocol: %" PRIx32 "", SCNtohs(p->ppph->protocol)); ENGINE_SET_INVALID_EVENT(p, PPP_WRONG_TYPE); return TM_ECODE_OK; } - } /* TESTS BELOW */ @@ -152,7 +148,7 @@ int DecodePPP(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, * Decode malformed ip layer PPP packet * Expected test value: 1 */ -static int DecodePPPtest01 (void) +static int DecodePPPtest01(void) { // clang-format off uint8_t raw_ppp[] = { 0xff, 0x03, 0x00, 0x21, 0x45, 0xc0, 0x00 }; @@ -170,7 +166,7 @@ static int DecodePPPtest01 (void) /* Function my returns here with expected value */ - if(ENGINE_ISSET_EVENT(p,PPPIPV4_PKT_TOO_SMALL)) { + if (ENGINE_ISSET_EVENT(p, PPPIPV4_PKT_TOO_SMALL)) { SCFree(p); return 1; } @@ -183,7 +179,7 @@ static int DecodePPPtest01 (void) * Decode malformed ppp layer packet * Expected test value: 1 */ -static int DecodePPPtest02 (void) +static int DecodePPPtest02(void) { // clang-format off uint8_t raw_ppp[] = { 0xff, 0x03, 0x00, 0xff, 0x45, 0xc0, 0x00, 0x2c, 0x4d, @@ -205,7 +201,7 @@ static int DecodePPPtest02 (void) /* Function must returns here */ - if(ENGINE_ISSET_EVENT(p,PPP_WRONG_TYPE)) { + if (ENGINE_ISSET_EVENT(p, PPP_WRONG_TYPE)) { SCFree(p); return 1; } @@ -220,7 +216,7 @@ static int DecodePPPtest02 (void) * \retval 0 Test failed * \retval 1 Test succeeded */ -static int DecodePPPtest03 (void) +static int DecodePPPtest03(void) { // clang-format off uint8_t raw_ppp[] = { 0xff, 0x03, 0x00, 0x21, 0x45, 0xc0, 0x00, 0x2c, 0x4d, @@ -244,27 +240,27 @@ static int DecodePPPtest03 (void) FlowShutdown(); - if(p->ppph == NULL) { + if (p->ppph == NULL) { SCFree(p); return 0; } - if(ENGINE_ISSET_EVENT(p,PPP_PKT_TOO_SMALL)) { + if (ENGINE_ISSET_EVENT(p, PPP_PKT_TOO_SMALL)) { SCFree(p); return 0; } - if(ENGINE_ISSET_EVENT(p,PPPIPV4_PKT_TOO_SMALL)) { + if (ENGINE_ISSET_EVENT(p, PPPIPV4_PKT_TOO_SMALL)) { SCFree(p); return 0; } - if(ENGINE_ISSET_EVENT(p,PPP_WRONG_TYPE)) { + if (ENGINE_ISSET_EVENT(p, PPP_WRONG_TYPE)) { SCFree(p); return 0; } - if (!(ENGINE_ISSET_EVENT(p,IPV4_TRUNC_PKT))) { + if (!(ENGINE_ISSET_EVENT(p, IPV4_TRUNC_PKT))) { SCFree(p); return 0; } @@ -274,13 +270,12 @@ static int DecodePPPtest03 (void) return 1; } - /* DecodePPPtest04 * Check if ppp header is null * Expected test value: 1 */ -static int DecodePPPtest04 (void) +static int DecodePPPtest04(void) { // clang-format off uint8_t raw_ppp[] = { 0xff, 0x03, 0x00, 0x21, 0x45, 0xc0, 0x00, 0x2c, 0x4d, @@ -304,12 +299,12 @@ static int DecodePPPtest04 (void) FlowShutdown(); - if(p->ppph == NULL) { + if (p->ppph == NULL) { SCFree(p); return 0; } - if (!(ENGINE_ISSET_EVENT(p,IPV4_TRUNC_PKT))) { + if (!(ENGINE_ISSET_EVENT(p, IPV4_TRUNC_PKT))) { SCFree(p); return 0; } diff --git a/src/decode-ppp.h b/src/decode-ppp.h index f8914cf2e77d..c40aef23bd6a 100644 --- a/src/decode-ppp.h +++ b/src/decode-ppp.h @@ -25,40 +25,40 @@ #define __DECODE_PPP_H__ /** Point to Point Protocol RFC1331 - Supported tyes */ -#define PPP_IP 0x0021 /* Internet Protocol */ -#define PPP_IPV6 0x0057 /* Internet Protocol version 6 */ -#define PPP_VJ_UCOMP 0x002f /* VJ uncompressed TCP/IP */ +#define PPP_IP 0x0021 /* Internet Protocol */ +#define PPP_IPV6 0x0057 /* Internet Protocol version 6 */ +#define PPP_VJ_UCOMP 0x002f /* VJ uncompressed TCP/IP */ /** Unsupported PPP types (libpcap source reference) */ -#define PPP_IPX 0x002b /* Novell IPX Protocol */ -#define PPP_VJ_COMP 0x002d /* VJ compressed TCP/IP */ -#define PPP_IPX 0x002b /* Novell IPX Protocol */ -#define PPP_OSI 0x0023 /* OSI Network Layer */ -#define PPP_NS 0x0025 /* Xerox NS IDP */ -#define PPP_DECNET 0x0027 /* DECnet Phase IV */ -#define PPP_APPLE 0x0029 /* Appletalk */ -#define PPP_BRPDU 0x0031 /* Bridging PDU */ -#define PPP_STII 0x0033 /* Stream Protocol (ST-II) */ -#define PPP_VINES 0x0035 /* Banyan Vines */ -#define PPP_HELLO 0x0201 /* 802.1d Hello Packets */ -#define PPP_LUXCOM 0x0231 /* Luxcom */ -#define PPP_SNS 0x0233 /* Sigma Network Systems */ -#define PPP_MPLS_UCAST 0x0281 /* rfc 3032 */ -#define PPP_MPLS_MCAST 0x0283 /* rfc 3022 */ -#define PPP_IPCP 0x8021 /* IP Control Protocol */ -#define PPP_OSICP 0x8023 /* OSI Network Layer Control Protocol */ -#define PPP_NSCP 0x8025 /* Xerox NS IDP Control Protocol */ -#define PPP_DECNETCP 0x8027 /* DECnet Control Protocol */ -#define PPP_APPLECP 0x8029 /* Appletalk Control Protocol */ -#define PPP_IPXCP 0x802b /* Novell IPX Control Protocol */ -#define PPP_STIICP 0x8033 /* Stream Protocol Control Protocol */ -#define PPP_VINESCP 0x8035 /* Banyan Vines Control Protocol */ -#define PPP_IPV6CP 0x8057 /* IPv6 Control Protocol */ -#define PPP_MPLSCP 0x8281 /* rfc 3022 */ -#define PPP_LCP 0xc021 /* Link Control Protocol */ -#define PPP_PAP 0xc023 /* Password Authentication Protocol */ -#define PPP_LQM 0xc025 /* Link Quality Monitoring */ -#define PPP_CHAP 0xc223 /* Challenge Handshake Authentication Protocol */ +#define PPP_IPX 0x002b /* Novell IPX Protocol */ +#define PPP_VJ_COMP 0x002d /* VJ compressed TCP/IP */ +#define PPP_IPX 0x002b /* Novell IPX Protocol */ +#define PPP_OSI 0x0023 /* OSI Network Layer */ +#define PPP_NS 0x0025 /* Xerox NS IDP */ +#define PPP_DECNET 0x0027 /* DECnet Phase IV */ +#define PPP_APPLE 0x0029 /* Appletalk */ +#define PPP_BRPDU 0x0031 /* Bridging PDU */ +#define PPP_STII 0x0033 /* Stream Protocol (ST-II) */ +#define PPP_VINES 0x0035 /* Banyan Vines */ +#define PPP_HELLO 0x0201 /* 802.1d Hello Packets */ +#define PPP_LUXCOM 0x0231 /* Luxcom */ +#define PPP_SNS 0x0233 /* Sigma Network Systems */ +#define PPP_MPLS_UCAST 0x0281 /* rfc 3032 */ +#define PPP_MPLS_MCAST 0x0283 /* rfc 3022 */ +#define PPP_IPCP 0x8021 /* IP Control Protocol */ +#define PPP_OSICP 0x8023 /* OSI Network Layer Control Protocol */ +#define PPP_NSCP 0x8025 /* Xerox NS IDP Control Protocol */ +#define PPP_DECNETCP 0x8027 /* DECnet Control Protocol */ +#define PPP_APPLECP 0x8029 /* Appletalk Control Protocol */ +#define PPP_IPXCP 0x802b /* Novell IPX Control Protocol */ +#define PPP_STIICP 0x8033 /* Stream Protocol Control Protocol */ +#define PPP_VINESCP 0x8035 /* Banyan Vines Control Protocol */ +#define PPP_IPV6CP 0x8057 /* IPv6 Control Protocol */ +#define PPP_MPLSCP 0x8281 /* rfc 3022 */ +#define PPP_LCP 0xc021 /* Link Control Protocol */ +#define PPP_PAP 0xc023 /* Password Authentication Protocol */ +#define PPP_LQM 0xc025 /* Link Quality Monitoring */ +#define PPP_CHAP 0xc223 /* Challenge Handshake Authentication Protocol */ /** PPP Packet header */ typedef struct PPPHdr_ { @@ -73,4 +73,3 @@ typedef struct PPPHdr_ { void DecodePPPRegisterTests(void); #endif /* __DECODE_PPP_H__ */ - diff --git a/src/decode-pppoe.c b/src/decode-pppoe.c index 5214fe649e15..f74d86a5830e 100644 --- a/src/decode-pppoe.c +++ b/src/decode-pppoe.c @@ -21,7 +21,6 @@ * @{ */ - /** * \file * @@ -47,8 +46,8 @@ /** * \brief Main decoding function for PPPOE Discovery packets */ -int DecodePPPOEDiscovery(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, - const uint8_t *pkt, uint32_t len) +int DecodePPPOEDiscovery( + ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, const uint8_t *pkt, uint32_t len) { DEBUG_VALIDATE_BUG_ON(pkt == NULL); @@ -62,20 +61,19 @@ int DecodePPPOEDiscovery(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, p->pppoedh = (PPPOEDiscoveryHdr *)pkt; /* parse the PPPOE code */ - switch (p->pppoedh->pppoe_code) - { - case PPPOE_CODE_PADI: + switch (p->pppoedh->pppoe_code) { + case PPPOE_CODE_PADI: break; - case PPPOE_CODE_PADO: + case PPPOE_CODE_PADO: break; - case PPPOE_CODE_PADR: + case PPPOE_CODE_PADR: break; case PPPOE_CODE_PADS: break; case PPPOE_CODE_PADT: break; default: - SCLogDebug("unknown PPPOE code: 0x%0"PRIX8"", p->pppoedh->pppoe_code); + SCLogDebug("unknown PPPOE code: 0x%0" PRIX8 "", p->pppoedh->pppoe_code); ENGINE_SET_INVALID_EVENT(p, PPPOE_WRONG_CODE); return TM_ECODE_OK; } @@ -83,13 +81,12 @@ int DecodePPPOEDiscovery(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, /* parse any tags we have in the packet */ uint32_t tag_length = 0; - PPPOEDiscoveryTag* pppoedt = (PPPOEDiscoveryTag*) (p->pppoedh + PPPOE_DISCOVERY_HEADER_MIN_LEN); + PPPOEDiscoveryTag *pppoedt = (PPPOEDiscoveryTag *)(p->pppoedh + PPPOE_DISCOVERY_HEADER_MIN_LEN); uint32_t pppoe_length = SCNtohs(p->pppoedh->pppoe_length); - uint32_t packet_length = len - PPPOE_DISCOVERY_HEADER_MIN_LEN ; + uint32_t packet_length = len - PPPOE_DISCOVERY_HEADER_MIN_LEN; - SCLogDebug("pppoe_length %"PRIu32", packet_length %"PRIu32"", - pppoe_length, packet_length); + SCLogDebug("pppoe_length %" PRIu32 ", packet_length %" PRIu32 "", pppoe_length, packet_length); if (pppoe_length > packet_length) { SCLogDebug("malformed PPPOE tags"); @@ -97,14 +94,14 @@ int DecodePPPOEDiscovery(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, return TM_ECODE_OK; } - while (pppoedt < (PPPOEDiscoveryTag*) (pkt + (len - sizeof(PPPOEDiscoveryTag))) && pppoe_length >=4 && packet_length >=4) - { + while (pppoedt < (PPPOEDiscoveryTag *)(pkt + (len - sizeof(PPPOEDiscoveryTag))) && + pppoe_length >= 4 && packet_length >= 4) { #ifdef DEBUG uint16_t tag_type = SCNtohs(pppoedt->pppoe_tag_type); #endif tag_length = SCNtohs(pppoedt->pppoe_tag_length); - SCLogDebug ("PPPoE Tag type %x, length %"PRIu32, tag_type, tag_length); + SCLogDebug("PPPoE Tag type %x, length %" PRIu32, tag_type, tag_length); if (pppoe_length >= (4 + tag_length)) { pppoe_length -= (4 + tag_length); @@ -127,8 +124,8 @@ int DecodePPPOEDiscovery(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, /** * \brief Main decoding function for PPPOE Session packets */ -int DecodePPPOESession(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, - const uint8_t *pkt, uint32_t len) +int DecodePPPOESession( + ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, const uint8_t *pkt, uint32_t len) { DEBUG_VALIDATE_BUG_ON(pkt == NULL); @@ -141,10 +138,14 @@ int DecodePPPOESession(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, p->pppoesh = (PPPOESessionHdr *)pkt; - SCLogDebug("PPPOE VERSION %" PRIu32 " TYPE %" PRIu32 " CODE %" PRIu32 " SESSIONID %" PRIu32 " LENGTH %" PRIu32 "", - PPPOE_SESSION_GET_VERSION(p->pppoesh), PPPOE_SESSION_GET_TYPE(p->pppoesh), p->pppoesh->pppoe_code, SCNtohs(p->pppoesh->session_id), SCNtohs(p->pppoesh->pppoe_length)); + SCLogDebug("PPPOE VERSION %" PRIu32 " TYPE %" PRIu32 " CODE %" PRIu32 " SESSIONID %" PRIu32 + " LENGTH %" PRIu32 "", + PPPOE_SESSION_GET_VERSION(p->pppoesh), PPPOE_SESSION_GET_TYPE(p->pppoesh), + p->pppoesh->pppoe_code, SCNtohs(p->pppoesh->session_id), + SCNtohs(p->pppoesh->pppoe_length)); - /* can't use DecodePPP() here because we only get a single 2-byte word to indicate protocol instead of the full PPP header */ + /* can't use DecodePPP() here because we only get a single 2-byte word to indicate protocol + * instead of the full PPP header */ if (SCNtohs(p->pppoesh->pppoe_length) > 0) { /* decode contained PPP packet */ @@ -198,7 +199,7 @@ int DecodePPPOESession(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, case PPP_PAP: case PPP_LQM: case PPP_CHAP: - ENGINE_SET_EVENT(p,PPP_UNSUP_PROTO); + ENGINE_SET_EVENT(p, PPP_UNSUP_PROTO); break; case PPP_VJ_UCOMP: @@ -254,7 +255,7 @@ int DecodePPPOESession(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, * \brief Decode malformed PPPOE packet (too short) * \retval 1 Expected test value */ -static int DecodePPPOEtest01 (void) +static int DecodePPPOEtest01(void) { // clang-format off @@ -280,7 +281,7 @@ static int DecodePPPOEtest01 (void) * \brief Valid PPPOE packet - check the invalid ICMP type encapsulated is flagged * \retval 0 Expected test value */ -static int DecodePPPOEtest02 (void) +static int DecodePPPOEtest02(void) { // clang-format off @@ -318,12 +319,11 @@ static int DecodePPPOEtest02 (void) PASS; } - /** DecodePPPOEtest03 * \brief Valid example PADO packet PPPOE packet taken from RFC2516 * \retval 0 Expected test value */ -static int DecodePPPOEtest03 (void) +static int DecodePPPOEtest03(void) { /* example PADO packet taken from RFC2516 */ @@ -356,7 +356,7 @@ static int DecodePPPOEtest03 (void) * \brief Valid example PPPOE packet taken from RFC2516 - but with wrong PPPOE code * \retval 1 Expected test value */ -static int DecodePPPOEtest04 (void) +static int DecodePPPOEtest04(void) { /* example PADI packet taken from RFC2516, but with wrong code */ @@ -387,7 +387,7 @@ static int DecodePPPOEtest04 (void) * \brief Valid example PADO PPPOE packet taken from RFC2516, but too short for given length * \retval 0 Expected test value */ -static int DecodePPPOEtest05 (void) +static int DecodePPPOEtest05(void) { /* example PADI packet taken from RFC2516 */ @@ -422,7 +422,7 @@ static int DecodePPPOEtest05 (void) * should extract the first 4 bits for version and the second 4 bits for type * \retval 1 Expected test value */ -static int DecodePPPOEtest06 (void) +static int DecodePPPOEtest06(void) { PPPOESessionHdr pppoesh; diff --git a/src/decode-pppoe.h b/src/decode-pppoe.h index 836d4a30c350..a755c6cf07eb 100644 --- a/src/decode-pppoe.h +++ b/src/decode-pppoe.h @@ -24,17 +24,15 @@ #ifndef __DECODE_PPPOE_H__ #define __DECODE_PPPOE_H__ - // Session header length minus the protocol field #define PPPOE_SESSION_HEADER_MIN_LEN 7 -#define PPPOE_DISCOVERY_HEADER_MIN_LEN 6 -#define PPPOE_SESSION_GET_VERSION(hdr) ((hdr)->pppoe_version_type & 0xF0) >> 4 -#define PPPOE_SESSION_GET_TYPE(hdr) ((hdr)->pppoe_version_type & 0x0F) +#define PPPOE_DISCOVERY_HEADER_MIN_LEN 6 +#define PPPOE_SESSION_GET_VERSION(hdr) ((hdr)->pppoe_version_type & 0xF0) >> 4 +#define PPPOE_SESSION_GET_TYPE(hdr) ((hdr)->pppoe_version_type & 0x0F) #define PPPOE_DISCOVERY_GET_VERSION(hdr) ((hdr)->pppoe_version_type & 0xF0) >> 4 -#define PPPOE_DISCOVERY_GET_TYPE(hdr) ((hdr)->pppoe_version_type & 0x0F) +#define PPPOE_DISCOVERY_GET_TYPE(hdr) ((hdr)->pppoe_version_type & 0x0F) -typedef struct PPPOESessionHdr_ -{ +typedef struct PPPOESessionHdr_ { uint8_t pppoe_version_type; uint8_t pppoe_code; uint16_t session_id; @@ -42,14 +40,12 @@ typedef struct PPPOESessionHdr_ uint16_t protocol; } PPPOESessionHdr; -typedef struct PPPOEDiscoveryTag_ -{ +typedef struct PPPOEDiscoveryTag_ { uint16_t pppoe_tag_type; uint16_t pppoe_tag_length; } __attribute__((__packed__)) PPPOEDiscoveryTag; -typedef struct PPPOEDiscoveryHdr_ -{ +typedef struct PPPOEDiscoveryHdr_ { uint8_t pppoe_version_type; uint8_t pppoe_code; uint16_t discovery_id; @@ -64,18 +60,17 @@ typedef struct PPPOEDiscoveryHdr_ #define PPPOE_CODE_PADT 0xa7 /* see RFC 2516 Appendix A */ -#define PPPOE_TAG_END_OF_LIST 0x0000 /* End-Of-List */ -#define PPPOE_TAG_SERVICE_NAME 0x0101 /* Service-Name */ -#define PPPOE_TAG_AC_NAME 0x0102 /* AC-Name */ -#define PPPOE_TAG_HOST_UNIQ 0x0103 /* Host-Uniq */ -#define PPPOE_TAG_AC_COOKIE 0x0104 /* AC-Cookie */ -#define PPPOE_TAG_VENDOR_SPECIFIC 0x0105 /* Vendor-Specific */ -#define PPPOE_TAG_RELAY_SESSION_ID 0x0110 /* Relay-Session-Id */ -#define PPPOE_TAG_SERVICE_NAME_ERROR 0x0201 /* Service-Name-Error */ -#define PPPOE_TAG_AC_SYS_ERROR 0x0202 /* AC-System Error */ -#define PPPOE_TAG_GEN_ERROR 0x0203 /* Generic-Error */ +#define PPPOE_TAG_END_OF_LIST 0x0000 /* End-Of-List */ +#define PPPOE_TAG_SERVICE_NAME 0x0101 /* Service-Name */ +#define PPPOE_TAG_AC_NAME 0x0102 /* AC-Name */ +#define PPPOE_TAG_HOST_UNIQ 0x0103 /* Host-Uniq */ +#define PPPOE_TAG_AC_COOKIE 0x0104 /* AC-Cookie */ +#define PPPOE_TAG_VENDOR_SPECIFIC 0x0105 /* Vendor-Specific */ +#define PPPOE_TAG_RELAY_SESSION_ID 0x0110 /* Relay-Session-Id */ +#define PPPOE_TAG_SERVICE_NAME_ERROR 0x0201 /* Service-Name-Error */ +#define PPPOE_TAG_AC_SYS_ERROR 0x0202 /* AC-System Error */ +#define PPPOE_TAG_GEN_ERROR 0x0203 /* Generic-Error */ void DecodePPPOERegisterTests(void); #endif /* __DECODE_PPPOE_H__ */ - diff --git a/src/decode-raw.c b/src/decode-raw.c index 7e8349f7fe37..8b1130b7e7b4 100644 --- a/src/decode-raw.c +++ b/src/decode-raw.c @@ -21,7 +21,6 @@ * @{ */ - /** * \file * @@ -39,8 +38,7 @@ #include "util-unittest.h" #include "util-debug.h" -int DecodeRaw(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, - const uint8_t *pkt, uint32_t len) +int DecodeRaw(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, const uint8_t *pkt, uint32_t len) { DEBUG_VALIDATE_BUG_ON(pkt == NULL); @@ -52,8 +50,6 @@ int DecodeRaw(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, return TM_ECODE_FAILED; } - - if (IP_GET_RAW_VER(pkt) == 4) { if (unlikely(GET_PKT_LEN(p) > USHRT_MAX)) { return TM_ECODE_FAILED; @@ -68,7 +64,7 @@ int DecodeRaw(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, DecodeIPV6(tv, dtv, p, GET_PKT_DATA(p), (uint16_t)(GET_PKT_LEN(p))); } else { SCLogDebug("Unknown ip version %d", IP_GET_RAW_VER(pkt)); - ENGINE_SET_EVENT(p,IPRAW_INVALID_IPV); + ENGINE_SET_EVENT(p, IPRAW_INVALID_IPV); } return TM_ECODE_OK; } @@ -81,7 +77,7 @@ int DecodeRaw(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, * \brief Valid Raw packet * \retval 0 Expected test value */ -static int DecodeRawTest01 (void) +static int DecodeRawTest01(void) { /* IPV6/TCP/no eth header */ @@ -105,11 +101,11 @@ static int DecodeRawTest01 (void) DecodeThreadVars dtv; memset(&dtv, 0, sizeof(DecodeThreadVars)); - memset(&tv, 0, sizeof(ThreadVars)); + memset(&tv, 0, sizeof(ThreadVars)); if (PacketCopyData(p, raw_ip, sizeof(raw_ip)) == -1) { - SCFree(p); - return 0; + SCFree(p); + return 0; } FlowInitConfig(FLOW_QUIET); @@ -126,13 +122,12 @@ static int DecodeRawTest01 (void) FlowShutdown(); SCFree(p); return 1; - } /** DecodeRawtest02 * \brief Valid Raw packet * \retval 0 Expected test value */ -static int DecodeRawTest02 (void) +static int DecodeRawTest02(void) { /* IPV4/TCP/no eth header */ @@ -153,11 +148,11 @@ static int DecodeRawTest02 (void) DecodeThreadVars dtv; memset(&dtv, 0, sizeof(DecodeThreadVars)); - memset(&tv, 0, sizeof(ThreadVars)); + memset(&tv, 0, sizeof(ThreadVars)); if (PacketCopyData(p, raw_ip, sizeof(raw_ip)) == -1) { - SCFree(p); - return 0; + SCFree(p); + return 0; } FlowInitConfig(FLOW_QUIET); @@ -180,7 +175,7 @@ static int DecodeRawTest02 (void) * \brief Valid Raw packet * \retval 0 Expected test value */ -static int DecodeRawTest03 (void) +static int DecodeRawTest03(void) { /* IPV13 */ @@ -203,7 +198,7 @@ static int DecodeRawTest03 (void) DecodeThreadVars dtv; memset(&dtv, 0, sizeof(DecodeThreadVars)); - memset(&tv, 0, sizeof(ThreadVars)); + memset(&tv, 0, sizeof(ThreadVars)); if (PacketCopyData(p, raw_ip, sizeof(raw_ip)) == -1) { SCFree(p); @@ -213,7 +208,7 @@ static int DecodeRawTest03 (void) FlowInitConfig(FLOW_QUIET); DecodeRaw(&tv, &dtv, p, raw_ip, GET_PKT_LEN(p)); - if (!ENGINE_ISSET_EVENT(p,IPRAW_INVALID_IPV)) { + if (!ENGINE_ISSET_EVENT(p, IPRAW_INVALID_IPV)) { printf("expected IPRAW_INVALID_IPV to be set but it wasn't: "); FlowShutdown(); SCFree(p); diff --git a/src/decode-raw.h b/src/decode-raw.h index ff637870ad14..a546b6c076ef 100644 --- a/src/decode-raw.h +++ b/src/decode-raw.h @@ -25,4 +25,3 @@ #define __DECODE_RAW_H__ void DecodeRawRegisterTests(void); #endif /* __DECODE_RAW_H__ */ - diff --git a/src/decode-sctp.c b/src/decode-sctp.c index 9a6c4e8ead2a..e81a12685389 100644 --- a/src/decode-sctp.c +++ b/src/decode-sctp.c @@ -21,7 +21,6 @@ * @{ */ - /** * \file * @@ -52,8 +51,8 @@ static int DecodeSCTPPacket(ThreadVars *tv, Packet *p, const uint8_t *pkt, uint1 p->sctph = (SCTPHdr *)pkt; - SET_SCTP_SRC_PORT(p,&p->sp); - SET_SCTP_DST_PORT(p,&p->dp); + SET_SCTP_SRC_PORT(p, &p->sp); + SET_SCTP_DST_PORT(p, &p->dp); p->payload = (uint8_t *)pkt + sizeof(SCTPHdr); p->payload_len = len - sizeof(SCTPHdr); @@ -63,19 +62,17 @@ static int DecodeSCTPPacket(ThreadVars *tv, Packet *p, const uint8_t *pkt, uint1 return 0; } -int DecodeSCTP(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, - const uint8_t *pkt, uint16_t len) +int DecodeSCTP(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, const uint8_t *pkt, uint16_t len) { StatsIncr(tv, dtv->counter_sctp); - if (unlikely(DecodeSCTPPacket(tv, p,pkt,len) < 0)) { + if (unlikely(DecodeSCTPPacket(tv, p, pkt, len) < 0)) { CLEAR_SCTP_PACKET(p); return TM_ECODE_FAILED; } #ifdef DEBUG - SCLogDebug("SCTP sp: %" PRIu32 " -> dp: %" PRIu32, - SCTP_GET_SRC_PORT(p), SCTP_GET_DST_PORT(p)); + SCLogDebug("SCTP sp: %" PRIu32 " -> dp: %" PRIu32, SCTP_GET_SRC_PORT(p), SCTP_GET_DST_PORT(p)); #endif FlowSetupPacket(p); diff --git a/src/decode-sctp.h b/src/decode-sctp.h index 53aa007dbbc0..03edd22ffb38 100644 --- a/src/decode-sctp.h +++ b/src/decode-sctp.h @@ -25,26 +25,27 @@ #define __DECODE_SCTP_H__ /** size of the packet header without any chunk headers */ -#define SCTP_HEADER_LEN 12 +#define SCTP_HEADER_LEN 12 /* XXX RAW* needs to be really 'raw', so no SCNtohs there */ -#define SCTP_GET_RAW_SRC_PORT(sctph) SCNtohs((sctph)->sh_sport) -#define SCTP_GET_RAW_DST_PORT(sctph) SCNtohs((sctph)->sh_dport) - -#define SCTP_GET_SRC_PORT(p) SCTP_GET_RAW_SRC_PORT(p->sctph) -#define SCTP_GET_DST_PORT(p) SCTP_GET_RAW_DST_PORT(p->sctph) - -typedef struct SCTPHdr_ -{ - uint16_t sh_sport; /* source port */ - uint16_t sh_dport; /* destination port */ - uint32_t sh_vtag; /* verification tag, defined per flow */ - uint32_t sh_sum; /* checksum, computed via crc32 */ +#define SCTP_GET_RAW_SRC_PORT(sctph) SCNtohs((sctph)->sh_sport) +#define SCTP_GET_RAW_DST_PORT(sctph) SCNtohs((sctph)->sh_dport) + +#define SCTP_GET_SRC_PORT(p) SCTP_GET_RAW_SRC_PORT(p->sctph) +#define SCTP_GET_DST_PORT(p) SCTP_GET_RAW_DST_PORT(p->sctph) + +typedef struct SCTPHdr_ { + uint16_t sh_sport; /* source port */ + uint16_t sh_dport; /* destination port */ + uint32_t sh_vtag; /* verification tag, defined per flow */ + uint32_t sh_sum; /* checksum, computed via crc32 */ } __attribute__((__packed__)) SCTPHdr; -#define CLEAR_SCTP_PACKET(p) { \ - (p)->sctph = NULL; \ -} while (0) +#define CLEAR_SCTP_PACKET(p) \ + { \ + (p)->sctph = NULL; \ + } \ + while (0) void DecodeSCTPRegisterTests(void); diff --git a/src/decode-sll.c b/src/decode-sll.c index f26950fffead..f09becaf1260 100644 --- a/src/decode-sll.c +++ b/src/decode-sll.c @@ -21,7 +21,6 @@ * @{ */ - /** * \file * @@ -38,8 +37,7 @@ #include "util-validate.h" #include "util-debug.h" -int DecodeSll(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, - const uint8_t *pkt, uint32_t len) +int DecodeSll(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, const uint8_t *pkt, uint32_t len) { DEBUG_VALIDATE_BUG_ON(pkt == NULL); @@ -57,8 +55,8 @@ int DecodeSll(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, SCLogDebug("p %p pkt %p sll_protocol %04x", p, pkt, SCNtohs(sllh->sll_protocol)); - DecodeNetworkLayer(tv, dtv, SCNtohs(sllh->sll_protocol), p, - pkt + SLL_HEADER_LEN, len - SLL_HEADER_LEN); + DecodeNetworkLayer( + tv, dtv, SCNtohs(sllh->sll_protocol), p, pkt + SLL_HEADER_LEN, len - SLL_HEADER_LEN); return TM_ECODE_OK; } diff --git a/src/decode-sll.h b/src/decode-sll.h index babdd7ac2109..cb43021cafc8 100644 --- a/src/decode-sll.h +++ b/src/decode-sll.h @@ -24,15 +24,14 @@ #ifndef __DECODE_SLL_H__ #define __DECODE_SLL_H__ -#define SLL_HEADER_LEN 16 +#define SLL_HEADER_LEN 16 typedef struct SllHdr_ { - uint16_t sll_pkttype; /* packet type */ - uint16_t sll_hatype; /* link-layer address type */ - uint16_t sll_halen; /* link-layer address length */ - uint8_t sll_addr[8]; /* link-layer address */ - uint16_t sll_protocol; /* protocol */ + uint16_t sll_pkttype; /* packet type */ + uint16_t sll_hatype; /* link-layer address type */ + uint16_t sll_halen; /* link-layer address length */ + uint8_t sll_addr[8]; /* link-layer address */ + uint16_t sll_protocol; /* protocol */ } __attribute__((__packed__)) SllHdr; #endif /* __DECODE_SLL_H__ */ - diff --git a/src/decode-tcp.c b/src/decode-tcp.c index 5c095b7e337c..8dafb5b76864 100644 --- a/src/decode-tcp.c +++ b/src/decode-tcp.c @@ -21,7 +21,6 @@ * @{ */ - /** * \file * @@ -39,9 +38,9 @@ #include "util-optimize.h" #include "flow.h" -#define SET_OPTS(dst, src) \ - (dst).type = (src).type; \ - (dst).len = (src).len; \ +#define SET_OPTS(dst, src) \ + (dst).type = (src).type; \ + (dst).len = (src).len; \ (dst).data = (src).data static void DecodeTCPOptions(Packet *p, const uint8_t *pkt, uint16_t pktlen) @@ -50,8 +49,7 @@ static void DecodeTCPOptions(Packet *p, const uint8_t *pkt, uint16_t pktlen) TCPOpt tcp_opts[TCP_OPTMAX]; uint16_t plen = pktlen; - while (plen) - { + while (plen) { const uint8_t type = *pkt; /* single byte options */ @@ -61,13 +59,13 @@ static void DecodeTCPOptions(Packet *p, const uint8_t *pkt, uint16_t pktlen) pkt++; plen--; - /* multibyte options */ + /* multibyte options */ } else { if (plen < 2) { break; } - const uint8_t olen = *(pkt+1); + const uint8_t olen = *(pkt + 1); /* we already know that the total options len is valid, * so here the len of the specific option must be bad. @@ -78,8 +76,8 @@ static void DecodeTCPOptions(Packet *p, const uint8_t *pkt, uint16_t pktlen) } tcp_opts[tcp_opt_cnt].type = type; - tcp_opts[tcp_opt_cnt].len = olen; - tcp_opts[tcp_opt_cnt].data = (olen > 2) ? (pkt+2) : NULL; + tcp_opts[tcp_opt_cnt].len = olen; + tcp_opts[tcp_opt_cnt].data = (olen > 2) ? (pkt + 2) : NULL; /* we are parsing the most commonly used opts to prevent * us from having to walk the opts list for these all the @@ -87,10 +85,10 @@ static void DecodeTCPOptions(Packet *p, const uint8_t *pkt, uint16_t pktlen) switch (type) { case TCP_OPT_WS: if (olen != TCP_OPT_WS_LEN) { - ENGINE_SET_EVENT(p,TCP_OPT_INVALID_LEN); + ENGINE_SET_EVENT(p, TCP_OPT_INVALID_LEN); } else { if (p->tcpvars.ws.type != 0) { - ENGINE_SET_EVENT(p,TCP_OPT_DUPLICATE); + ENGINE_SET_EVENT(p, TCP_OPT_DUPLICATE); } else { SET_OPTS(p->tcpvars.ws, tcp_opts[tcp_opt_cnt]); } @@ -98,10 +96,10 @@ static void DecodeTCPOptions(Packet *p, const uint8_t *pkt, uint16_t pktlen) break; case TCP_OPT_MSS: if (olen != TCP_OPT_MSS_LEN) { - ENGINE_SET_EVENT(p,TCP_OPT_INVALID_LEN); + ENGINE_SET_EVENT(p, TCP_OPT_INVALID_LEN); } else { if (p->tcpvars.mss.type != 0) { - ENGINE_SET_EVENT(p,TCP_OPT_DUPLICATE); + ENGINE_SET_EVENT(p, TCP_OPT_DUPLICATE); } else { SET_OPTS(p->tcpvars.mss, tcp_opts[tcp_opt_cnt]); } @@ -109,10 +107,10 @@ static void DecodeTCPOptions(Packet *p, const uint8_t *pkt, uint16_t pktlen) break; case TCP_OPT_SACKOK: if (olen != TCP_OPT_SACKOK_LEN) { - ENGINE_SET_EVENT(p,TCP_OPT_INVALID_LEN); + ENGINE_SET_EVENT(p, TCP_OPT_INVALID_LEN); } else { if (p->tcpvars.sackok.type != 0) { - ENGINE_SET_EVENT(p,TCP_OPT_DUPLICATE); + ENGINE_SET_EVENT(p, TCP_OPT_DUPLICATE); } else { SET_OPTS(p->tcpvars.sackok, tcp_opts[tcp_opt_cnt]); } @@ -120,10 +118,10 @@ static void DecodeTCPOptions(Packet *p, const uint8_t *pkt, uint16_t pktlen) break; case TCP_OPT_TS: if (olen != TCP_OPT_TS_LEN) { - ENGINE_SET_EVENT(p,TCP_OPT_INVALID_LEN); + ENGINE_SET_EVENT(p, TCP_OPT_INVALID_LEN); } else { if (p->tcpvars.ts_set) { - ENGINE_SET_EVENT(p,TCP_OPT_DUPLICATE); + ENGINE_SET_EVENT(p, TCP_OPT_DUPLICATE); } else { uint32_t values[2]; memcpy(&values, tcp_opts[tcp_opt_cnt].data, sizeof(values)); @@ -136,14 +134,12 @@ static void DecodeTCPOptions(Packet *p, const uint8_t *pkt, uint16_t pktlen) case TCP_OPT_SACK: SCLogDebug("SACK option, len %u", olen); if ((olen != 2) && - (olen < TCP_OPT_SACK_MIN_LEN || - olen > TCP_OPT_SACK_MAX_LEN || - !((olen - 2) % 8 == 0))) - { - ENGINE_SET_EVENT(p,TCP_OPT_INVALID_LEN); + (olen < TCP_OPT_SACK_MIN_LEN || olen > TCP_OPT_SACK_MAX_LEN || + !((olen - 2) % 8 == 0))) { + ENGINE_SET_EVENT(p, TCP_OPT_INVALID_LEN); } else { if (p->tcpvars.sack.type != 0) { - ENGINE_SET_EVENT(p,TCP_OPT_DUPLICATE); + ENGINE_SET_EVENT(p, TCP_OPT_DUPLICATE); } else { SET_OPTS(p->tcpvars.sack, tcp_opts[tcp_opt_cnt]); } @@ -153,10 +149,10 @@ static void DecodeTCPOptions(Packet *p, const uint8_t *pkt, uint16_t pktlen) SCLogDebug("TFO option, len %u", olen); if ((olen != 2) && (olen < TCP_OPT_TFO_MIN_LEN || olen > TCP_OPT_TFO_MAX_LEN || !(((olen - 2) & 0x1) == 0))) { - ENGINE_SET_EVENT(p,TCP_OPT_INVALID_LEN); + ENGINE_SET_EVENT(p, TCP_OPT_INVALID_LEN); } else { if (p->tcpvars.tfo.type != 0) { - ENGINE_SET_EVENT(p,TCP_OPT_DUPLICATE); + ENGINE_SET_EVENT(p, TCP_OPT_DUPLICATE); } else { SET_OPTS(p->tcpvars.tfo, tcp_opts[tcp_opt_cnt]); } @@ -170,21 +166,21 @@ static void DecodeTCPOptions(Packet *p, const uint8_t *pkt, uint16_t pktlen) uint16_t magic = SCNtohs(*(uint16_t *)tcp_opts[tcp_opt_cnt].data); if (magic == 0xf989) { if (p->tcpvars.tfo.type != 0) { - ENGINE_SET_EVENT(p,TCP_OPT_DUPLICATE); + ENGINE_SET_EVENT(p, TCP_OPT_DUPLICATE); } else { SET_OPTS(p->tcpvars.tfo, tcp_opts[tcp_opt_cnt]); p->tcpvars.tfo.type = TCP_OPT_TFO; // treat as regular TFO } } } else { - ENGINE_SET_EVENT(p,TCP_OPT_INVALID_LEN); + ENGINE_SET_EVENT(p, TCP_OPT_INVALID_LEN); } break; /* RFC 2385 MD5 option */ case TCP_OPT_MD5: SCLogDebug("MD5 option, len %u", olen); if (olen != 18) { - ENGINE_SET_INVALID_EVENT(p,TCP_OPT_INVALID_LEN); + ENGINE_SET_INVALID_EVENT(p, TCP_OPT_INVALID_LEN); } else { /* we can't validate the option as the key is out of band */ p->tcpvars.md5_option_present = true; @@ -194,7 +190,7 @@ static void DecodeTCPOptions(Packet *p, const uint8_t *pkt, uint16_t pktlen) case TCP_OPT_AO: SCLogDebug("AU option, len %u", olen); if (olen < 4) { - ENGINE_SET_INVALID_EVENT(p,TCP_OPT_INVALID_LEN); + ENGINE_SET_INVALID_EVENT(p, TCP_OPT_INVALID_LEN); } else { /* we can't validate the option as the key is out of band */ p->tcpvars.ao_option_present = true; @@ -234,8 +230,8 @@ static int DecodeTCPPacket(ThreadVars *tv, Packet *p, const uint8_t *pkt, uint16 DecodeTCPOptions(p, pkt + TCP_HEADER_LEN, tcp_opt_len); } - SET_TCP_SRC_PORT(p,&p->sp); - SET_TCP_DST_PORT(p,&p->dp); + SET_TCP_SRC_PORT(p, &p->sp); + SET_TCP_DST_PORT(p, &p->dp); p->proto = IPPROTO_TCP; @@ -245,12 +241,11 @@ static int DecodeTCPPacket(ThreadVars *tv, Packet *p, const uint8_t *pkt, uint16 return 0; } -int DecodeTCP(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, - const uint8_t *pkt, uint16_t len) +int DecodeTCP(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, const uint8_t *pkt, uint16_t len) { StatsIncr(tv, dtv->counter_tcp); - if (unlikely(DecodeTCPPacket(tv, p, pkt,len) < 0)) { + if (unlikely(DecodeTCPPacket(tv, p, pkt, len) < 0)) { SCLogDebug("invalid TCP packet"); CLEAR_TCP_PACKET(p); return TM_ECODE_FAILED; @@ -266,11 +261,12 @@ int DecodeTCP(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, StatsIncr(tv, dtv->counter_tcp_rst); } #ifdef DEBUG - SCLogDebug("TCP sp: %" PRIu32 " -> dp: %" PRIu32 " - HLEN: %" PRIu32 " LEN: %" PRIu32 " %s%s%s%s%s%s", - GET_TCP_SRC_PORT(p), GET_TCP_DST_PORT(p), TCP_GET_HLEN(p), len, - TCP_HAS_SACKOK(p) ? "SACKOK " : "", TCP_HAS_SACK(p) ? "SACK " : "", - TCP_HAS_WSCALE(p) ? "WS " : "", TCP_HAS_TS(p) ? "TS " : "", - TCP_HAS_MSS(p) ? "MSS " : "", TCP_HAS_TFO(p) ? "TFO " : ""); + SCLogDebug("TCP sp: %" PRIu32 " -> dp: %" PRIu32 " - HLEN: %" PRIu32 " LEN: %" PRIu32 + " %s%s%s%s%s%s", + GET_TCP_SRC_PORT(p), GET_TCP_DST_PORT(p), TCP_GET_HLEN(p), len, + TCP_HAS_SACKOK(p) ? "SACKOK " : "", TCP_HAS_SACK(p) ? "SACK " : "", + TCP_HAS_WSCALE(p) ? "WS " : "", TCP_HAS_TS(p) ? "TS " : "", + TCP_HAS_MSS(p) ? "MSS " : "", TCP_HAS_TFO(p) ? "TFO " : ""); #endif FlowSetupPacket(p); @@ -300,10 +296,9 @@ static int TCPCalculateValidChecksumtest01(void) 0x01, 0x71, 0x74, 0xde, 0x01, 0x03, 0x03, 02}; // clang-format on - csum = *( ((uint16_t *)raw_tcp) + 8); + csum = *(((uint16_t *)raw_tcp) + 8); - FAIL_IF(TCPChecksum((uint16_t *)raw_ipshdr, - (uint16_t *)raw_tcp, sizeof(raw_tcp), csum) != 0); + FAIL_IF(TCPChecksum((uint16_t *)raw_ipshdr, (uint16_t *)raw_tcp, sizeof(raw_tcp), csum) != 0); PASS; } @@ -325,10 +320,9 @@ static int TCPCalculateInvalidChecksumtest02(void) 0x01, 0x71, 0x74, 0xde, 0x01, 0x03, 0x03, 03}; // clang-format on - csum = *( ((uint16_t *)raw_tcp) + 8); + csum = *(((uint16_t *)raw_tcp) + 8); - FAIL_IF(TCPChecksum((uint16_t *) raw_ipshdr, - (uint16_t *)raw_tcp, sizeof(raw_tcp), csum) == 0); + FAIL_IF(TCPChecksum((uint16_t *)raw_ipshdr, (uint16_t *)raw_tcp, sizeof(raw_tcp), csum) == 0); PASS; } @@ -351,10 +345,10 @@ static int TCPV6CalculateValidChecksumtest03(void) 0xca, 0x5a, 0x00, 0x01, 0x69, 0x27}; // clang-format on - csum = *( ((uint16_t *)(raw_ipv6 + 70))); + csum = *(((uint16_t *)(raw_ipv6 + 70))); - FAIL_IF(TCPV6Checksum((uint16_t *)(raw_ipv6 + 14 + 8), - (uint16_t *)(raw_ipv6 + 54), 32, csum) != 0); + FAIL_IF(TCPV6Checksum((uint16_t *)(raw_ipv6 + 14 + 8), (uint16_t *)(raw_ipv6 + 54), 32, csum) != + 0); PASS; } @@ -377,10 +371,10 @@ static int TCPV6CalculateInvalidChecksumtest04(void) 0xca, 0x5a, 0x00, 0x01, 0x69, 0x28}; // clang-format on - csum = *( ((uint16_t *)(raw_ipv6 + 70))); + csum = *(((uint16_t *)(raw_ipv6 + 70))); - FAIL_IF(TCPV6Checksum((uint16_t *)(raw_ipv6 + 14 + 8), - (uint16_t *)(raw_ipv6 + 54), 32, csum) == 0); + FAIL_IF(TCPV6Checksum((uint16_t *)(raw_ipv6 + 14 + 8), (uint16_t *)(raw_ipv6 + 54), 32, csum) == + 0); PASS; } @@ -410,7 +404,6 @@ static int TCPGetWscaleTest01(void) p->dst.family = AF_INET; p->ip4h = &ip4h; - FlowInitConfig(FLOW_QUIET); DecodeTCP(&tv, &dtv, p, raw_tcp, sizeof(raw_tcp)); @@ -421,7 +414,7 @@ static int TCPGetWscaleTest01(void) uint8_t wscale = TCP_GET_WSCALE(p); if (wscale != 2) { - printf("wscale %"PRIu8", expected 2: ", wscale); + printf("wscale %" PRIu8 ", expected 2: ", wscale); goto end; } @@ -469,7 +462,7 @@ static int TCPGetWscaleTest02(void) uint8_t wscale = TCP_GET_WSCALE(p); if (wscale != 0) { - printf("wscale %"PRIu8", expected 0: ", wscale); + printf("wscale %" PRIu8 ", expected 0: ", wscale); goto end; } @@ -516,7 +509,7 @@ static int TCPGetWscaleTest03(void) uint8_t wscale = TCP_GET_WSCALE(p); if (wscale != 0) { - printf("wscale %"PRIu8", expected 0: ", wscale); + printf("wscale %" PRIu8 ", expected 0: ", wscale); goto end; } @@ -601,14 +594,10 @@ static int TCPGetSackTest01(void) void DecodeTCPRegisterTests(void) { #ifdef UNITTESTS - UtRegisterTest("TCPCalculateValidChecksumtest01", - TCPCalculateValidChecksumtest01); - UtRegisterTest("TCPCalculateInvalidChecksumtest02", - TCPCalculateInvalidChecksumtest02); - UtRegisterTest("TCPV6CalculateValidChecksumtest03", - TCPV6CalculateValidChecksumtest03); - UtRegisterTest("TCPV6CalculateInvalidChecksumtest04", - TCPV6CalculateInvalidChecksumtest04); + UtRegisterTest("TCPCalculateValidChecksumtest01", TCPCalculateValidChecksumtest01); + UtRegisterTest("TCPCalculateInvalidChecksumtest02", TCPCalculateInvalidChecksumtest02); + UtRegisterTest("TCPV6CalculateValidChecksumtest03", TCPV6CalculateValidChecksumtest03); + UtRegisterTest("TCPV6CalculateInvalidChecksumtest04", TCPV6CalculateInvalidChecksumtest04); UtRegisterTest("TCPGetWscaleTest01", TCPGetWscaleTest01); UtRegisterTest("TCPGetWscaleTest02", TCPGetWscaleTest02); UtRegisterTest("TCPGetWscaleTest03", TCPGetWscaleTest03); diff --git a/src/decode-tcp.h b/src/decode-tcp.h index 4b26df5c26f4..971ce73419f5 100644 --- a/src/decode-tcp.h +++ b/src/decode-tcp.h @@ -25,108 +25,113 @@ #ifndef __DECODE_TCP_H__ #define __DECODE_TCP_H__ -#define TCP_HEADER_LEN 20 -#define TCP_OPTLENMAX 40 -#define TCP_OPTMAX 20 /* every opt is at least 2 bytes - * (type + len), except EOL and NOP */ +#define TCP_HEADER_LEN 20 +#define TCP_OPTLENMAX 40 +#define TCP_OPTMAX \ + 20 /* every opt is at least 2 bytes \ + * (type + len), except EOL and NOP */ /* TCP flags */ -#define TH_FIN 0x01 -#define TH_SYN 0x02 -#define TH_RST 0x04 -#define TH_PUSH 0x08 -#define TH_ACK 0x10 -#define TH_URG 0x20 +#define TH_FIN 0x01 +#define TH_SYN 0x02 +#define TH_RST 0x04 +#define TH_PUSH 0x08 +#define TH_ACK 0x10 +#define TH_URG 0x20 /** Establish a new connection reducing window */ -#define TH_ECN 0x40 +#define TH_ECN 0x40 /** Echo Congestion flag */ -#define TH_CWR 0x80 +#define TH_CWR 0x80 /* tcp option codes */ -#define TCP_OPT_EOL 0x00 -#define TCP_OPT_NOP 0x01 -#define TCP_OPT_MSS 0x02 -#define TCP_OPT_WS 0x03 -#define TCP_OPT_SACKOK 0x04 -#define TCP_OPT_SACK 0x05 -#define TCP_OPT_TS 0x08 -#define TCP_OPT_TFO 0x22 /* TCP Fast Open */ -#define TCP_OPT_EXP1 0xfd /* Experimental, could be TFO */ -#define TCP_OPT_EXP2 0xfe /* Experimental, could be TFO */ -#define TCP_OPT_MD5 0x13 /* 19: RFC 2385 TCP MD5 option */ -#define TCP_OPT_AO 0x1d /* 29: RFC 5925 TCP AO option */ - -#define TCP_OPT_SACKOK_LEN 2 -#define TCP_OPT_WS_LEN 3 -#define TCP_OPT_TS_LEN 10 -#define TCP_OPT_MSS_LEN 4 -#define TCP_OPT_SACK_MIN_LEN 10 /* hdr 2, 1 pair 8 = 10 */ -#define TCP_OPT_SACK_MAX_LEN 34 /* hdr 2, 4 pair 32= 34 */ -#define TCP_OPT_TFO_MIN_LEN 4 /* kind, len, 2 bytes cookie: 4 */ -#define TCP_OPT_TFO_MAX_LEN 18 /* kind, len, 18 */ +#define TCP_OPT_EOL 0x00 +#define TCP_OPT_NOP 0x01 +#define TCP_OPT_MSS 0x02 +#define TCP_OPT_WS 0x03 +#define TCP_OPT_SACKOK 0x04 +#define TCP_OPT_SACK 0x05 +#define TCP_OPT_TS 0x08 +#define TCP_OPT_TFO 0x22 /* TCP Fast Open */ +#define TCP_OPT_EXP1 0xfd /* Experimental, could be TFO */ +#define TCP_OPT_EXP2 0xfe /* Experimental, could be TFO */ +#define TCP_OPT_MD5 0x13 /* 19: RFC 2385 TCP MD5 option */ +#define TCP_OPT_AO 0x1d /* 29: RFC 5925 TCP AO option */ + +#define TCP_OPT_SACKOK_LEN 2 +#define TCP_OPT_WS_LEN 3 +#define TCP_OPT_TS_LEN 10 +#define TCP_OPT_MSS_LEN 4 +#define TCP_OPT_SACK_MIN_LEN 10 /* hdr 2, 1 pair 8 = 10 */ +#define TCP_OPT_SACK_MAX_LEN 34 /* hdr 2, 4 pair 32= 34 */ +#define TCP_OPT_TFO_MIN_LEN 4 /* kind, len, 2 bytes cookie: 4 */ +#define TCP_OPT_TFO_MAX_LEN 18 /* kind, len, 18 */ /** Max valid wscale value. */ -#define TCP_WSCALE_MAX 14 +#define TCP_WSCALE_MAX 14 -#define TCP_GET_RAW_OFFSET(tcph) (((tcph)->th_offx2 & 0xf0) >> 4) -#define TCP_GET_RAW_X2(tcph) (unsigned char)((tcph)->th_offx2 & 0x0f) -#define TCP_GET_RAW_SRC_PORT(tcph) SCNtohs((tcph)->th_sport) -#define TCP_GET_RAW_DST_PORT(tcph) SCNtohs((tcph)->th_dport) +#define TCP_GET_RAW_OFFSET(tcph) (((tcph)->th_offx2 & 0xf0) >> 4) +#define TCP_GET_RAW_X2(tcph) (unsigned char)((tcph)->th_offx2 & 0x0f) +#define TCP_GET_RAW_SRC_PORT(tcph) SCNtohs((tcph)->th_sport) +#define TCP_GET_RAW_DST_PORT(tcph) SCNtohs((tcph)->th_dport) -#define TCP_SET_RAW_TCP_OFFSET(tcph, value) ((tcph)->th_offx2 = (unsigned char)(((tcph)->th_offx2 & 0x0f) | (value << 4))) -#define TCP_SET_RAW_TCP_X2(tcph, value) ((tcph)->th_offx2 = (unsigned char)(((tcph)->th_offx2 & 0xf0) | (value & 0x0f))) +#define TCP_SET_RAW_TCP_OFFSET(tcph, value) \ + ((tcph)->th_offx2 = (unsigned char)(((tcph)->th_offx2 & 0x0f) | (value << 4))) +#define TCP_SET_RAW_TCP_X2(tcph, value) \ + ((tcph)->th_offx2 = (unsigned char)(((tcph)->th_offx2 & 0xf0) | (value & 0x0f))) -#define TCP_GET_RAW_SEQ(tcph) SCNtohl((tcph)->th_seq) -#define TCP_GET_RAW_ACK(tcph) SCNtohl((tcph)->th_ack) +#define TCP_GET_RAW_SEQ(tcph) SCNtohl((tcph)->th_seq) +#define TCP_GET_RAW_ACK(tcph) SCNtohl((tcph)->th_ack) -#define TCP_GET_RAW_WINDOW(tcph) SCNtohs((tcph)->th_win) -#define TCP_GET_RAW_URG_POINTER(tcph) SCNtohs((tcph)->th_urp) -#define TCP_GET_RAW_SUM(tcph) SCNtohs((tcph)->th_sum) +#define TCP_GET_RAW_WINDOW(tcph) SCNtohs((tcph)->th_win) +#define TCP_GET_RAW_URG_POINTER(tcph) SCNtohs((tcph)->th_urp) +#define TCP_GET_RAW_SUM(tcph) SCNtohs((tcph)->th_sum) /** macro for getting the first timestamp from the packet in host order */ -#define TCP_GET_TSVAL(p) ((p)->tcpvars.ts_val) +#define TCP_GET_TSVAL(p) ((p)->tcpvars.ts_val) /** macro for getting the second timestamp from the packet in host order. */ -#define TCP_GET_TSECR(p) ((p)->tcpvars.ts_ecr) +#define TCP_GET_TSECR(p) ((p)->tcpvars.ts_ecr) -#define TCP_HAS_WSCALE(p) ((p)->tcpvars.ws.type == TCP_OPT_WS) -#define TCP_HAS_SACK(p) ((p)->tcpvars.sack.type == TCP_OPT_SACK) -#define TCP_HAS_SACKOK(p) ((p)->tcpvars.sackok.type == TCP_OPT_SACKOK) -#define TCP_HAS_TS(p) ((p)->tcpvars.ts_set) -#define TCP_HAS_MSS(p) ((p)->tcpvars.mss.type == TCP_OPT_MSS) -#define TCP_HAS_TFO(p) ((p)->tcpvars.tfo.type == TCP_OPT_TFO) +#define TCP_HAS_WSCALE(p) ((p)->tcpvars.ws.type == TCP_OPT_WS) +#define TCP_HAS_SACK(p) ((p)->tcpvars.sack.type == TCP_OPT_SACK) +#define TCP_HAS_SACKOK(p) ((p)->tcpvars.sackok.type == TCP_OPT_SACKOK) +#define TCP_HAS_TS(p) ((p)->tcpvars.ts_set) +#define TCP_HAS_MSS(p) ((p)->tcpvars.mss.type == TCP_OPT_MSS) +#define TCP_HAS_TFO(p) ((p)->tcpvars.tfo.type == TCP_OPT_TFO) /** macro for getting the wscale from the packet. */ -#define TCP_GET_WSCALE(p) (TCP_HAS_WSCALE((p)) ? \ - (((*(uint8_t *)(p)->tcpvars.ws.data) <= TCP_WSCALE_MAX) ? \ - (*(uint8_t *)((p)->tcpvars.ws.data)) : 0) : 0) - -#define TCP_GET_SACKOK(p) (TCP_HAS_SACKOK((p)) ? 1 : 0) -#define TCP_GET_SACK_PTR(p) TCP_HAS_SACK((p)) ? (p)->tcpvars.sack.data : NULL -#define TCP_GET_SACK_CNT(p) (TCP_HAS_SACK((p)) ? (((p)->tcpvars.sack.len - 2) / 8) : 0) -#define TCP_GET_MSS(p) SCNtohs(*(uint16_t *)((p)->tcpvars.mss.data)) - -#define TCP_GET_OFFSET(p) TCP_GET_RAW_OFFSET((p)->tcph) -#define TCP_GET_X2(p) TCP_GET_RAW_X2((p)->tcph) -#define TCP_GET_HLEN(p) ((uint8_t)(TCP_GET_OFFSET((p)) << 2)) -#define TCP_GET_SRC_PORT(p) TCP_GET_RAW_SRC_PORT((p)->tcph) -#define TCP_GET_DST_PORT(p) TCP_GET_RAW_DST_PORT((p)->tcph) -#define TCP_GET_SEQ(p) TCP_GET_RAW_SEQ((p)->tcph) -#define TCP_GET_ACK(p) TCP_GET_RAW_ACK((p)->tcph) -#define TCP_GET_WINDOW(p) TCP_GET_RAW_WINDOW((p)->tcph) -#define TCP_GET_URG_POINTER(p) TCP_GET_RAW_URG_POINTER((p)->tcph) -#define TCP_GET_SUM(p) TCP_GET_RAW_SUM((p)->tcph) -#define TCP_GET_FLAGS(p) (p)->tcph->th_flags - -#define TCP_ISSET_FLAG_FIN(p) ((p)->tcph->th_flags & TH_FIN) -#define TCP_ISSET_FLAG_SYN(p) ((p)->tcph->th_flags & TH_SYN) -#define TCP_ISSET_FLAG_RST(p) ((p)->tcph->th_flags & TH_RST) -#define TCP_ISSET_FLAG_PUSH(p) ((p)->tcph->th_flags & TH_PUSH) -#define TCP_ISSET_FLAG_ACK(p) ((p)->tcph->th_flags & TH_ACK) -#define TCP_ISSET_FLAG_URG(p) ((p)->tcph->th_flags & TH_URG) -#define TCP_ISSET_FLAG_RES2(p) ((p)->tcph->th_flags & TH_RES2) -#define TCP_ISSET_FLAG_RES1(p) ((p)->tcph->th_flags & TH_RES1) +#define TCP_GET_WSCALE(p) \ + (TCP_HAS_WSCALE((p)) ? (((*(uint8_t *)(p)->tcpvars.ws.data) <= TCP_WSCALE_MAX) \ + ? (*(uint8_t *)((p)->tcpvars.ws.data)) \ + : 0) \ + : 0) + +#define TCP_GET_SACKOK(p) (TCP_HAS_SACKOK((p)) ? 1 : 0) +#define TCP_GET_SACK_PTR(p) TCP_HAS_SACK((p)) ? (p)->tcpvars.sack.data : NULL +#define TCP_GET_SACK_CNT(p) (TCP_HAS_SACK((p)) ? (((p)->tcpvars.sack.len - 2) / 8) : 0) +#define TCP_GET_MSS(p) SCNtohs(*(uint16_t *)((p)->tcpvars.mss.data)) + +#define TCP_GET_OFFSET(p) TCP_GET_RAW_OFFSET((p)->tcph) +#define TCP_GET_X2(p) TCP_GET_RAW_X2((p)->tcph) +#define TCP_GET_HLEN(p) ((uint8_t)(TCP_GET_OFFSET((p)) << 2)) +#define TCP_GET_SRC_PORT(p) TCP_GET_RAW_SRC_PORT((p)->tcph) +#define TCP_GET_DST_PORT(p) TCP_GET_RAW_DST_PORT((p)->tcph) +#define TCP_GET_SEQ(p) TCP_GET_RAW_SEQ((p)->tcph) +#define TCP_GET_ACK(p) TCP_GET_RAW_ACK((p)->tcph) +#define TCP_GET_WINDOW(p) TCP_GET_RAW_WINDOW((p)->tcph) +#define TCP_GET_URG_POINTER(p) TCP_GET_RAW_URG_POINTER((p)->tcph) +#define TCP_GET_SUM(p) TCP_GET_RAW_SUM((p)->tcph) +#define TCP_GET_FLAGS(p) (p)->tcph->th_flags + +#define TCP_ISSET_FLAG_FIN(p) ((p)->tcph->th_flags & TH_FIN) +#define TCP_ISSET_FLAG_SYN(p) ((p)->tcph->th_flags & TH_SYN) +#define TCP_ISSET_FLAG_RST(p) ((p)->tcph->th_flags & TH_RST) +#define TCP_ISSET_FLAG_PUSH(p) ((p)->tcph->th_flags & TH_PUSH) +#define TCP_ISSET_FLAG_ACK(p) ((p)->tcph->th_flags & TH_ACK) +#define TCP_ISSET_FLAG_URG(p) ((p)->tcph->th_flags & TH_URG) +#define TCP_ISSET_FLAG_RES2(p) ((p)->tcph->th_flags & TH_RES2) +#define TCP_ISSET_FLAG_RES1(p) ((p)->tcph->th_flags & TH_RES1) typedef struct TCPOpt_ { uint8_t type; @@ -135,44 +140,43 @@ typedef struct TCPOpt_ { } TCPOpt; typedef struct TCPOptSackRecord_ { - uint32_t le; /**< left edge, network order */ - uint32_t re; /**< right edge, network order */ + uint32_t le; /**< left edge, network order */ + uint32_t re; /**< right edge, network order */ } TCPOptSackRecord; -typedef struct TCPHdr_ -{ - uint16_t th_sport; /**< source port */ - uint16_t th_dport; /**< destination port */ - uint32_t th_seq; /**< sequence number */ - uint32_t th_ack; /**< acknowledgement number */ - uint8_t th_offx2; /**< offset and reserved */ - uint8_t th_flags; /**< pkt flags */ - uint16_t th_win; /**< pkt window */ - uint16_t th_sum; /**< checksum */ - uint16_t th_urp; /**< urgent pointer */ +typedef struct TCPHdr_ { + uint16_t th_sport; /**< source port */ + uint16_t th_dport; /**< destination port */ + uint32_t th_seq; /**< sequence number */ + uint32_t th_ack; /**< acknowledgement number */ + uint8_t th_offx2; /**< offset and reserved */ + uint8_t th_flags; /**< pkt flags */ + uint16_t th_win; /**< pkt window */ + uint16_t th_sum; /**< checksum */ + uint16_t th_urp; /**< urgent pointer */ } __attribute__((__packed__)) TCPHdr; -typedef struct TCPVars_ -{ +typedef struct TCPVars_ { /* commonly used and needed opts */ bool md5_option_present; bool ao_option_present; bool ts_set; - uint32_t ts_val; /* host-order */ - uint32_t ts_ecr; /* host-order */ + uint32_t ts_val; /* host-order */ + uint32_t ts_ecr; /* host-order */ uint16_t stream_pkt_flags; TCPOpt sack; TCPOpt sackok; TCPOpt ws; TCPOpt mss; - TCPOpt tfo; /* tcp fast open */ + TCPOpt tfo; /* tcp fast open */ } TCPVars; -#define CLEAR_TCP_PACKET(p) { \ - (p)->level4_comp_csum = -1; \ - PACKET_CLEAR_L4VARS((p)); \ - (p)->tcph = NULL; \ -} +#define CLEAR_TCP_PACKET(p) \ + { \ + (p)->level4_comp_csum = -1; \ + PACKET_CLEAR_L4VARS((p)); \ + (p)->tcph = NULL; \ + } void DecodeTCPRegisterTests(void); @@ -198,29 +202,25 @@ static inline uint16_t TCPChecksum( csum += shdr[0] + shdr[1] + shdr[2] + shdr[3] + htons(6) + htons(tlen); - csum += pkt[0] + pkt[1] + pkt[2] + pkt[3] + pkt[4] + pkt[5] + pkt[6] + - pkt[7] + pkt[9]; + csum += pkt[0] + pkt[1] + pkt[2] + pkt[3] + pkt[4] + pkt[5] + pkt[6] + pkt[7] + pkt[9]; tlen -= 20; pkt += 10; while (tlen >= 32) { - csum += pkt[0] + pkt[1] + pkt[2] + pkt[3] + pkt[4] + pkt[5] + pkt[6] + - pkt[7] + - pkt[8] + - pkt[9] + pkt[10] + pkt[11] + pkt[12] + pkt[13] + - pkt[14] + pkt[15]; + csum += pkt[0] + pkt[1] + pkt[2] + pkt[3] + pkt[4] + pkt[5] + pkt[6] + pkt[7] + pkt[8] + + pkt[9] + pkt[10] + pkt[11] + pkt[12] + pkt[13] + pkt[14] + pkt[15]; tlen -= 32; pkt += 16; } - while(tlen >= 8) { + while (tlen >= 8) { csum += pkt[0] + pkt[1] + pkt[2] + pkt[3]; tlen -= 8; pkt += 4; } - while(tlen >= 4) { + while (tlen >= 4) { csum += pkt[0] + pkt[1]; tlen -= 4; pkt += 2; @@ -261,31 +261,29 @@ static inline uint16_t TCPV6Checksum( uint16_t pad = 0; uint32_t csum = init; - csum += shdr[0] + shdr[1] + shdr[2] + shdr[3] + shdr[4] + shdr[5] + - shdr[6] + shdr[7] + shdr[8] + shdr[9] + shdr[10] + shdr[11] + - shdr[12] + shdr[13] + shdr[14] + shdr[15] + htons(6) + htons(tlen); + csum += shdr[0] + shdr[1] + shdr[2] + shdr[3] + shdr[4] + shdr[5] + shdr[6] + shdr[7] + + shdr[8] + shdr[9] + shdr[10] + shdr[11] + shdr[12] + shdr[13] + shdr[14] + shdr[15] + + htons(6) + htons(tlen); - csum += pkt[0] + pkt[1] + pkt[2] + pkt[3] + pkt[4] + pkt[5] + pkt[6] + - pkt[7] + pkt[9]; + csum += pkt[0] + pkt[1] + pkt[2] + pkt[3] + pkt[4] + pkt[5] + pkt[6] + pkt[7] + pkt[9]; tlen -= 20; pkt += 10; while (tlen >= 32) { - csum += pkt[0] + pkt[1] + pkt[2] + pkt[3] + pkt[4] + pkt[5] + pkt[6] + - pkt[7] + pkt[8] + pkt[9] + pkt[10] + pkt[11] + pkt[12] + pkt[13] + - pkt[14] + pkt[15]; + csum += pkt[0] + pkt[1] + pkt[2] + pkt[3] + pkt[4] + pkt[5] + pkt[6] + pkt[7] + pkt[8] + + pkt[9] + pkt[10] + pkt[11] + pkt[12] + pkt[13] + pkt[14] + pkt[15]; tlen -= 32; pkt += 16; } - while(tlen >= 8) { + while (tlen >= 8) { csum += pkt[0] + pkt[1] + pkt[2] + pkt[3]; tlen -= 8; pkt += 4; } - while(tlen >= 4) { + while (tlen >= 4) { csum += pkt[0] + pkt[1]; tlen -= 4; pkt += 2; diff --git a/src/decode-template.c b/src/decode-template.c index fdaee0a77fd5..335a6bb1bea1 100644 --- a/src/decode-template.c +++ b/src/decode-template.c @@ -21,7 +21,6 @@ * @{ */ - /** * \file * @@ -48,14 +47,14 @@ * \retval TM_ECODE_OK or TM_ECODE_FAILED on serious error */ -int DecodeTEMPLATE(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, - const uint8_t *pkt, uint32_t len) +int DecodeTEMPLATE( + ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, const uint8_t *pkt, uint32_t len) { DEBUG_VALIDATE_BUG_ON(pkt == NULL); /* TODO add counter for your type of packet to DecodeThreadVars, * and register it in DecodeRegisterPerfCounters */ - //StatsIncr(tv, dtv->counter_template); + // StatsIncr(tv, dtv->counter_template); /* Validation: make sure that the input data is big enough to hold * the header */ @@ -63,7 +62,7 @@ int DecodeTEMPLATE(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, /* in case of errors, we set events. Events are defined in * decode-events.h, and are then exposed to the detection * engine through detect-engine-events.h */ - //ENGINE_SET_EVENT(p,TEMPLATE_HEADER_TOO_SMALL); + // ENGINE_SET_EVENT(p,TEMPLATE_HEADER_TOO_SMALL); return TM_ECODE_FAILED; } /* Each packet keeps a count of decoded layers @@ -100,7 +99,7 @@ int DecodeTEMPLATE(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, /* invoke the next decoder on the remainder of the data */ return DecodeUDP(tv, dtv, p, (uint8_t *)pkt + hdr_len, (uint16_t)(len - hdr_len)); } else { - //ENGINE_SET_EVENT(p,TEMPLATE_UNSUPPORTED_PROTOCOL); + // ENGINE_SET_EVENT(p,TEMPLATE_UNSUPPORTED_PROTOCOL); return TM_ECODE_FAILED; } diff --git a/src/decode-teredo.c b/src/decode-teredo.c index bbeda3efa398..538965b2c23e 100644 --- a/src/decode-teredo.c +++ b/src/decode-teredo.c @@ -21,7 +21,6 @@ * @{ */ - /** * \file * @@ -44,9 +43,9 @@ #include "detect.h" #include "detect-engine-port.h" -#define TEREDO_ORIG_INDICATION_LENGTH 8 -#define TEREDO_MAX_PORTS 4 -#define TEREDO_UNSET_PORT -1 +#define TEREDO_ORIG_INDICATION_LENGTH 8 +#define TEREDO_MAX_PORTS 4 +#define TEREDO_UNSET_PORT -1 static bool g_teredo_enabled = true; static bool g_teredo_ports_any = true; @@ -124,8 +123,7 @@ void DecodeTeredoConfig(void) * * \retval TM_ECODE_FAILED if packet is not a Teredo packet, TM_ECODE_OK if it is */ -int DecodeTeredo(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, - const uint8_t *pkt, uint16_t len) +int DecodeTeredo(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, const uint8_t *pkt, uint16_t len) { DEBUG_VALIDATE_BUG_ON(pkt == NULL); @@ -180,16 +178,14 @@ int DecodeTeredo(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, if (IPV6_GET_RAW_NH(thdr) == 0 && IPV6_GET_RAW_PLEN(thdr) < 8) return TM_ECODE_FAILED; - if (len == IPV6_HEADER_LEN + - IPV6_GET_RAW_PLEN(thdr) + (start - pkt)) { + if (len == IPV6_HEADER_LEN + IPV6_GET_RAW_PLEN(thdr) + (start - pkt)) { int blen = len - (start - pkt); /* spawn off tunnel packet */ - Packet *tp = PacketTunnelPktSetup(tv, dtv, p, start, blen, - DECODE_TUNNEL_IPV6_TEREDO); + Packet *tp = PacketTunnelPktSetup(tv, dtv, p, start, blen, DECODE_TUNNEL_IPV6_TEREDO); if (tp != NULL) { PKT_SET_SRC(tp, PKT_SRC_DECODER_TEREDO); /* add the tp to the packet queue. */ - PacketEnqueueNoLock(&tv->decode_pq,tp); + PacketEnqueueNoLock(&tv->decode_pq, tp); StatsIncr(tv, dtv->counter_teredo); return TM_ECODE_OK; } diff --git a/src/decode-teredo.h b/src/decode-teredo.h index bbd9dc816383..fb7024330698 100644 --- a/src/decode-teredo.h +++ b/src/decode-teredo.h @@ -18,8 +18,8 @@ #ifndef __DECODE_TEREDO_H__ #define __DECODE_TEREDO_H__ -int DecodeTeredo(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, - const uint8_t *pkt, uint16_t len); +int DecodeTeredo( + ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, const uint8_t *pkt, uint16_t len); void DecodeTeredoConfig(void); bool DecodeTeredoEnabledForPort(const uint16_t sp, const uint16_t dp); diff --git a/src/decode-udp.c b/src/decode-udp.c index 1de82e249c2d..b443a156e5e7 100644 --- a/src/decode-udp.c +++ b/src/decode-udp.c @@ -21,7 +21,6 @@ * @{ */ - /** * \file * @@ -61,8 +60,8 @@ static int DecodeUDPPacket(ThreadVars *t, Packet *p, const uint8_t *pkt, uint16_ return -1; } - SET_UDP_SRC_PORT(p,&p->sp); - SET_UDP_DST_PORT(p,&p->dp); + SET_UDP_SRC_PORT(p, &p->sp); + SET_UDP_DST_PORT(p, &p->dp); p->payload = (uint8_t *)pkt + UDP_HEADER_LEN; p->payload_len = UDP_GET_LEN(p) - UDP_HEADER_LEN; @@ -72,18 +71,17 @@ static int DecodeUDPPacket(ThreadVars *t, Packet *p, const uint8_t *pkt, uint16_ return 0; } -int DecodeUDP(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, - const uint8_t *pkt, uint16_t len) +int DecodeUDP(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, const uint8_t *pkt, uint16_t len) { StatsIncr(tv, dtv->counter_udp); - if (unlikely(DecodeUDPPacket(tv, p, pkt,len) < 0)) { + if (unlikely(DecodeUDPPacket(tv, p, pkt, len) < 0)) { CLEAR_UDP_PACKET(p); return TM_ECODE_FAILED; } SCLogDebug("UDP sp: %" PRIu32 " -> dp: %" PRIu32 " - HLEN: %" PRIu32 " LEN: %" PRIu32 "", - UDP_GET_SRC_PORT(p), UDP_GET_DST_PORT(p), UDP_HEADER_LEN, p->payload_len); + UDP_GET_SRC_PORT(p), UDP_GET_DST_PORT(p), UDP_HEADER_LEN, p->payload_len); if (DecodeTeredoEnabledForPort(p->sp, p->dp) && likely(DecodeTeredo(tv, dtv, p, p->payload, p->payload_len) == TM_ECODE_OK)) { @@ -141,10 +139,9 @@ static int UDPV4CalculateValidChecksumtest01(void) 0x67, 0x6c, 0x65, 0xc0, 0x26}; // clang-format on - csum = *( ((uint16_t *)raw_udp) + 3); + csum = *(((uint16_t *)raw_udp) + 3); - FAIL_IF(UDPV4Checksum((uint16_t *) raw_ipshdr, - (uint16_t *)raw_udp, sizeof(raw_udp), csum) != 0); + FAIL_IF(UDPV4Checksum((uint16_t *)raw_ipshdr, (uint16_t *)raw_udp, sizeof(raw_udp), csum) != 0); PASS; } @@ -172,10 +169,9 @@ static int UDPV4CalculateInvalidChecksumtest02(void) 0x67, 0x6c, 0x65, 0xc0, 0x27}; // clang-format on - csum = *( ((uint16_t *)raw_udp) + 3); + csum = *(((uint16_t *)raw_udp) + 3); - FAIL_IF(UDPV4Checksum((uint16_t *) raw_ipshdr, - (uint16_t *)raw_udp, sizeof(raw_udp), csum) == 0); + FAIL_IF(UDPV4Checksum((uint16_t *)raw_ipshdr, (uint16_t *)raw_udp, sizeof(raw_udp), csum) == 0); PASS; } @@ -197,10 +193,10 @@ static int UDPV6CalculateValidChecksumtest03(void) 0x09, 0x00}; // clang-format on - csum = *( ((uint16_t *)(raw_ipv6 + 60))); + csum = *(((uint16_t *)(raw_ipv6 + 60))); - FAIL_IF(UDPV6Checksum((uint16_t *)(raw_ipv6 + 14 + 8), - (uint16_t *)(raw_ipv6 + 54), 20, csum) != 0); + FAIL_IF(UDPV6Checksum((uint16_t *)(raw_ipv6 + 14 + 8), (uint16_t *)(raw_ipv6 + 54), 20, csum) != + 0); PASS; } @@ -222,10 +218,10 @@ static int UDPV6CalculateInvalidChecksumtest04(void) 0x09, 0x01}; // clang-format on - csum = *( ((uint16_t *)(raw_ipv6 + 60))); + csum = *(((uint16_t *)(raw_ipv6 + 60))); - FAIL_IF(UDPV6Checksum((uint16_t *)(raw_ipv6 + 14 + 8), - (uint16_t *)(raw_ipv6 + 54), 20, csum) == 0); + FAIL_IF(UDPV6Checksum((uint16_t *)(raw_ipv6 + 14 + 8), (uint16_t *)(raw_ipv6 + 54), 20, csum) == + 0); PASS; } #endif /* UNITTESTS */ @@ -233,14 +229,10 @@ static int UDPV6CalculateInvalidChecksumtest04(void) void DecodeUDPV4RegisterTests(void) { #ifdef UNITTESTS - UtRegisterTest("UDPV4CalculateValidChecksumtest01", - UDPV4CalculateValidChecksumtest01); - UtRegisterTest("UDPV4CalculateInvalidChecksumtest02", - UDPV4CalculateInvalidChecksumtest02); - UtRegisterTest("UDPV6CalculateValidChecksumtest03", - UDPV6CalculateValidChecksumtest03); - UtRegisterTest("UDPV6CalculateInvalidChecksumtest04", - UDPV6CalculateInvalidChecksumtest04); + UtRegisterTest("UDPV4CalculateValidChecksumtest01", UDPV4CalculateValidChecksumtest01); + UtRegisterTest("UDPV4CalculateInvalidChecksumtest02", UDPV4CalculateInvalidChecksumtest02); + UtRegisterTest("UDPV6CalculateValidChecksumtest03", UDPV6CalculateValidChecksumtest03); + UtRegisterTest("UDPV6CalculateInvalidChecksumtest04", UDPV6CalculateInvalidChecksumtest04); #endif /* UNITTESTS */ } /** diff --git a/src/decode-udp.h b/src/decode-udp.h index 6f695bd1779e..6f70e303f7a0 100644 --- a/src/decode-udp.h +++ b/src/decode-udp.h @@ -24,32 +24,32 @@ #ifndef __DECODE_UDP_H__ #define __DECODE_UDP_H__ -#define UDP_HEADER_LEN 8 +#define UDP_HEADER_LEN 8 /* XXX RAW* needs to be really 'raw', so no SCNtohs there */ -#define UDP_GET_RAW_LEN(udph) SCNtohs((udph)->uh_len) -#define UDP_GET_RAW_SRC_PORT(udph) SCNtohs((udph)->uh_sport) -#define UDP_GET_RAW_DST_PORT(udph) SCNtohs((udph)->uh_dport) -#define UDP_GET_RAW_SUM(udph) SCNtohs((udph)->uh_sum) +#define UDP_GET_RAW_LEN(udph) SCNtohs((udph)->uh_len) +#define UDP_GET_RAW_SRC_PORT(udph) SCNtohs((udph)->uh_sport) +#define UDP_GET_RAW_DST_PORT(udph) SCNtohs((udph)->uh_dport) +#define UDP_GET_RAW_SUM(udph) SCNtohs((udph)->uh_sum) -#define UDP_GET_LEN(p) UDP_GET_RAW_LEN(p->udph) -#define UDP_GET_SRC_PORT(p) UDP_GET_RAW_SRC_PORT(p->udph) -#define UDP_GET_DST_PORT(p) UDP_GET_RAW_DST_PORT(p->udph) -#define UDP_GET_SUM(p) UDP_GET_RAW_SUM(p->udph) +#define UDP_GET_LEN(p) UDP_GET_RAW_LEN(p->udph) +#define UDP_GET_SRC_PORT(p) UDP_GET_RAW_SRC_PORT(p->udph) +#define UDP_GET_DST_PORT(p) UDP_GET_RAW_DST_PORT(p->udph) +#define UDP_GET_SUM(p) UDP_GET_RAW_SUM(p->udph) /* UDP header structure */ -typedef struct UDPHdr_ -{ - uint16_t uh_sport; /* source port */ - uint16_t uh_dport; /* destination port */ - uint16_t uh_len; /* length */ - uint16_t uh_sum; /* checksum */ +typedef struct UDPHdr_ { + uint16_t uh_sport; /* source port */ + uint16_t uh_dport; /* destination port */ + uint16_t uh_len; /* length */ + uint16_t uh_sum; /* checksum */ } __attribute__((__packed__)) UDPHdr; -#define CLEAR_UDP_PACKET(p) do { \ - (p)->level4_comp_csum = -1; \ - (p)->udph = NULL; \ -} while (0) +#define CLEAR_UDP_PACKET(p) \ + do { \ + (p)->level4_comp_csum = -1; \ + (p)->udph = NULL; \ + } while (0) void DecodeUDPV4RegisterTests(void); @@ -82,20 +82,19 @@ static inline uint16_t UDPV4Checksum( pkt += 4; while (tlen >= 32) { - csum += pkt[0] + pkt[1] + pkt[2] + pkt[3] + pkt[4] + pkt[5] + pkt[6] + - pkt[7] + pkt[8] + pkt[9] + pkt[10] + pkt[11] + pkt[12] + pkt[13] + - pkt[14] + pkt[15]; + csum += pkt[0] + pkt[1] + pkt[2] + pkt[3] + pkt[4] + pkt[5] + pkt[6] + pkt[7] + pkt[8] + + pkt[9] + pkt[10] + pkt[11] + pkt[12] + pkt[13] + pkt[14] + pkt[15]; tlen -= 32; pkt += 16; } - while(tlen >= 8) { + while (tlen >= 8) { csum += pkt[0] + pkt[1] + pkt[2] + pkt[3]; tlen -= 8; pkt += 4; } - while(tlen >= 4) { + while (tlen >= 4) { csum += pkt[0] + pkt[1]; tlen -= 4; pkt += 2; @@ -141,9 +140,9 @@ static inline uint16_t UDPV6Checksum( uint16_t pad = 0; uint32_t csum = init; - csum += shdr[0] + shdr[1] + shdr[2] + shdr[3] + shdr[4] + shdr[5] + shdr[6] + - shdr[7] + shdr[8] + shdr[9] + shdr[10] + shdr[11] + shdr[12] + - shdr[13] + shdr[14] + shdr[15] + htons(17) + htons(tlen); + csum += shdr[0] + shdr[1] + shdr[2] + shdr[3] + shdr[4] + shdr[5] + shdr[6] + shdr[7] + + shdr[8] + shdr[9] + shdr[10] + shdr[11] + shdr[12] + shdr[13] + shdr[14] + shdr[15] + + htons(17) + htons(tlen); csum += pkt[0] + pkt[1] + pkt[2]; @@ -151,20 +150,19 @@ static inline uint16_t UDPV6Checksum( pkt += 4; while (tlen >= 32) { - csum += pkt[0] + pkt[1] + pkt[2] + pkt[3] + pkt[4] + pkt[5] + pkt[6] + - pkt[7] + pkt[8] + pkt[9] + pkt[10] + pkt[11] + pkt[12] + pkt[13] + - pkt[14] + pkt[15]; + csum += pkt[0] + pkt[1] + pkt[2] + pkt[3] + pkt[4] + pkt[5] + pkt[6] + pkt[7] + pkt[8] + + pkt[9] + pkt[10] + pkt[11] + pkt[12] + pkt[13] + pkt[14] + pkt[15]; tlen -= 32; pkt += 16; } - while(tlen >= 8) { + while (tlen >= 8) { csum += pkt[0] + pkt[1] + pkt[2] + pkt[3]; tlen -= 8; pkt += 4; } - while(tlen >= 4) { + while (tlen >= 4) { csum += pkt[0] + pkt[1]; tlen -= 4; pkt += 2; diff --git a/src/decode-vlan.c b/src/decode-vlan.c index 7de9aa32fb6b..ea94debff970 100644 --- a/src/decode-vlan.c +++ b/src/decode-vlan.c @@ -21,7 +21,6 @@ * @{ */ - /** * \file * @@ -51,8 +50,7 @@ * \param pq pointer to the packet queue * */ -int DecodeVLAN(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, - const uint8_t *pkt, uint32_t len) +int DecodeVLAN(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, const uint8_t *pkt, uint32_t len) { DEBUG_VALIDATE_BUG_ON(pkt == NULL); @@ -65,7 +63,7 @@ int DecodeVLAN(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, else if (p->vlan_idx == 2) StatsIncr(tv, dtv->counter_vlan_qinqinq); - if(len < VLAN_HEADER_LEN) { + if (len < VLAN_HEADER_LEN) { ENGINE_SET_INVALID_EVENT(p, VLAN_HEADER_TOO_SMALL); return TM_ECODE_FAILED; } @@ -73,7 +71,7 @@ int DecodeVLAN(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, return TM_ECODE_FAILED; } if (p->vlan_idx > VLAN_MAX_LAYER_IDX) { - ENGINE_SET_EVENT(p,VLAN_HEADER_TOO_MANY_LAYERS); + ENGINE_SET_EVENT(p, VLAN_HEADER_TOO_MANY_LAYERS); return TM_ECODE_FAILED; } @@ -87,8 +85,8 @@ int DecodeVLAN(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, p->vlan_id[p->vlan_idx++] = (uint16_t)GET_VLAN_ID(vlan_hdr); - if (DecodeNetworkLayer(tv, dtv, proto, p, - pkt + VLAN_HEADER_LEN, len - VLAN_HEADER_LEN) == false) { + if (DecodeNetworkLayer(tv, dtv, proto, p, pkt + VLAN_HEADER_LEN, len - VLAN_HEADER_LEN) == + false) { ENGINE_SET_INVALID_EVENT(p, VLAN_UNKNOWN_TYPE); return TM_ECODE_FAILED; } @@ -99,13 +97,13 @@ typedef struct IEEE8021ahHdr_ { uint32_t flags; uint8_t c_destination[6]; uint8_t c_source[6]; - uint16_t type; /**< next protocol */ -} __attribute__((__packed__)) IEEE8021ahHdr; + uint16_t type; /**< next protocol */ +} __attribute__((__packed__)) IEEE8021ahHdr; #define IEEE8021AH_HEADER_LEN sizeof(IEEE8021ahHdr) -int DecodeIEEE8021ah(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, - const uint8_t *pkt, uint32_t len) +int DecodeIEEE8021ah( + ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, const uint8_t *pkt, uint32_t len) { DEBUG_VALIDATE_BUG_ON(pkt == NULL); @@ -119,8 +117,8 @@ int DecodeIEEE8021ah(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, IEEE8021ahHdr *hdr = (IEEE8021ahHdr *)pkt; const uint16_t next_proto = SCNtohs(hdr->type); - DecodeNetworkLayer(tv, dtv, next_proto, p, - pkt + IEEE8021AH_HEADER_LEN, len - IEEE8021AH_HEADER_LEN); + DecodeNetworkLayer( + tv, dtv, next_proto, p, pkt + IEEE8021AH_HEADER_LEN, len - IEEE8021AH_HEADER_LEN); return TM_ECODE_OK; } @@ -139,7 +137,7 @@ int DecodeIEEE8021ah(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, * \retval 1 on success * \retval 0 on failure */ -static int DecodeVLANtest01 (void) +static int DecodeVLANtest01(void) { // clang-format off uint8_t raw_vlan[] = { 0x00, 0x20, 0x08 }; @@ -155,7 +153,7 @@ static int DecodeVLANtest01 (void) DecodeVLAN(&tv, &dtv, p, raw_vlan, sizeof(raw_vlan)); - if(ENGINE_ISSET_EVENT(p,VLAN_HEADER_TOO_SMALL)) { + if (ENGINE_ISSET_EVENT(p, VLAN_HEADER_TOO_SMALL)) { SCFree(p); return 1; } @@ -170,7 +168,7 @@ static int DecodeVLANtest01 (void) * \retval 1 on success * \retval 0 on failure */ -static int DecodeVLANtest02 (void) +static int DecodeVLANtest02(void) { // clang-format off uint8_t raw_vlan[] = { @@ -193,8 +191,7 @@ static int DecodeVLANtest02 (void) DecodeVLAN(&tv, &dtv, p, raw_vlan, sizeof(raw_vlan)); - - if(ENGINE_ISSET_EVENT(p,VLAN_UNKNOWN_TYPE)) { + if (ENGINE_ISSET_EVENT(p, VLAN_UNKNOWN_TYPE)) { SCFree(p); return 1; } @@ -209,7 +206,7 @@ static int DecodeVLANtest02 (void) * \retval 1 on success * \retval 0 on failure */ -static int DecodeVLANtest03 (void) +static int DecodeVLANtest03(void) { // clang-format off uint8_t raw_vlan[] = { @@ -234,16 +231,15 @@ static int DecodeVLANtest03 (void) DecodeVLAN(&tv, &dtv, p, raw_vlan, sizeof(raw_vlan)); - - if(p->vlan_id[0] == 0) { + if (p->vlan_id[0] == 0) { goto error; } - if(ENGINE_ISSET_EVENT(p,VLAN_HEADER_TOO_SMALL)) { + if (ENGINE_ISSET_EVENT(p, VLAN_HEADER_TOO_SMALL)) { goto error; } - if(ENGINE_ISSET_EVENT(p,VLAN_UNKNOWN_TYPE)) { + if (ENGINE_ISSET_EVENT(p, VLAN_UNKNOWN_TYPE)) { goto error; } diff --git a/src/decode-vlan.h b/src/decode-vlan.h index 809038dbe6fc..9c45fe99e856 100644 --- a/src/decode-vlan.h +++ b/src/decode-vlan.h @@ -28,18 +28,18 @@ uint16_t DecodeVLANGetId(const struct Packet_ *, uint8_t layer); /** Vlan type */ -#define ETHERNET_TYPE_VLAN 0x8100 +#define ETHERNET_TYPE_VLAN 0x8100 /** Vlan macros to access Vlan priority, Vlan CFI and VID */ -#define GET_VLAN_PRIORITY(vlanh) ((SCNtohs((vlanh)->vlan_cfi) & 0xe000) >> 13) -#define GET_VLAN_CFI(vlanh) ((SCNtohs((vlanh)->vlan_cfi) & 0x0100) >> 12) -#define GET_VLAN_ID(vlanh) ((uint16_t)(SCNtohs((vlanh)->vlan_cfi) & 0x0FFF)) -#define GET_VLAN_PROTO(vlanh) ((SCNtohs((vlanh)->protocol))) +#define GET_VLAN_PRIORITY(vlanh) ((SCNtohs((vlanh)->vlan_cfi) & 0xe000) >> 13) +#define GET_VLAN_CFI(vlanh) ((SCNtohs((vlanh)->vlan_cfi) & 0x0100) >> 12) +#define GET_VLAN_ID(vlanh) ((uint16_t)(SCNtohs((vlanh)->vlan_cfi) & 0x0FFF)) +#define GET_VLAN_PROTO(vlanh) ((SCNtohs((vlanh)->protocol))) /** Vlan header struct */ typedef struct VLANHdr_ { uint16_t vlan_cfi; - uint16_t protocol; /**< protocol field */ + uint16_t protocol; /**< protocol field */ } __attribute__((__packed__)) VLANHdr; /** VLAN header length */ @@ -52,4 +52,3 @@ void DecodeVLANRegisterTests(void); #define VLAN_MAX_LAYER_IDX (VLAN_MAX_LAYERS - 1) #endif /* __DECODE_VLAN_H__ */ - diff --git a/src/decode-vxlan.c b/src/decode-vxlan.c index 786abf32f3e8..1d2ac6e7b067 100644 --- a/src/decode-vxlan.c +++ b/src/decode-vxlan.c @@ -42,10 +42,10 @@ #define VXLAN_HEADER_LEN sizeof(VXLANHeader) -#define VXLAN_MAX_PORTS 4 -#define VXLAN_UNSET_PORT -1 -#define VXLAN_DEFAULT_PORT 4789 -#define VXLAN_DEFAULT_PORT_S "4789" +#define VXLAN_MAX_PORTS 4 +#define VXLAN_UNSET_PORT -1 +#define VXLAN_DEFAULT_PORT 4789 +#define VXLAN_DEFAULT_PORT_S "4789" static bool g_vxlan_enabled = true; static int g_vxlan_ports_idx = 0; @@ -119,8 +119,7 @@ void DecodeVXLANConfig(void) /** \param pkt payload data directly above UDP header * \param len length in bytes of pkt */ -int DecodeVXLAN(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, - const uint8_t *pkt, uint32_t len) +int DecodeVXLAN(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, const uint8_t *pkt, uint32_t len) { DEBUG_VALIDATE_BUG_ON(pkt == NULL); @@ -195,7 +194,7 @@ int DecodeVXLAN(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, * \test DecodeVXLANTest01 test a good vxlan header. * Contains a DNS request packet. */ -static int DecodeVXLANtest01 (void) +static int DecodeVXLANtest01(void) { // clang-format off uint8_t raw_vxlan[] = { @@ -236,7 +235,7 @@ static int DecodeVXLANtest01 (void) /** * \test DecodeVXLANtest02 tests default port disabled by the config. */ -static int DecodeVXLANtest02 (void) +static int DecodeVXLANtest02(void) { // clang-format off uint8_t raw_vxlan[] = { @@ -274,9 +273,7 @@ static int DecodeVXLANtest02 (void) void DecodeVXLANRegisterTests(void) { #ifdef UNITTESTS - UtRegisterTest("DecodeVXLANtest01", - DecodeVXLANtest01); - UtRegisterTest("DecodeVXLANtest02", - DecodeVXLANtest02); + UtRegisterTest("DecodeVXLANtest01", DecodeVXLANtest01); + UtRegisterTest("DecodeVXLANtest02", DecodeVXLANtest02); #endif /* UNITTESTS */ } diff --git a/src/decode.c b/src/decode.c index d302c7654675..4af65a24a14a 100644 --- a/src/decode.c +++ b/src/decode.c @@ -38,7 +38,6 @@ * @{ */ - /** * \file * @@ -151,8 +150,7 @@ void PacketDecodeFinalize(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p) } } -void PacketUpdateEngineEventCounters(ThreadVars *tv, - DecodeThreadVars *dtv, Packet *p) +void PacketUpdateEngineEventCounters(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p) { for (uint8_t i = 0; i < p->events.cnt; i++) { const uint8_t e = p->events.events[i]; @@ -223,7 +221,7 @@ Packet *PacketGetFromQueueOrAlloc(void) inline int PacketCallocExtPkt(Packet *p, int datalen) { - if (! p->ext_pkt) { + if (!p->ext_pkt) { p->ext_pkt = SCCalloc(1, datalen); if (unlikely(p->ext_pkt == NULL)) { SET_PKT_LEN(p, 0); @@ -256,7 +254,7 @@ inline int PacketCopyDataOffset(Packet *p, uint32_t offset, const uint8_t *data, } /* Do we have already an packet with allocated data */ - if (! p->ext_pkt) { + if (!p->ext_pkt) { uint32_t newsize = offset + datalen; // check overflow if (newsize < offset) @@ -306,7 +304,7 @@ inline int PacketCopyData(Packet *p, const uint8_t *pktdata, uint32_t pktlen) * \retval p the pseudo packet or NULL if out of memory */ Packet *PacketTunnelPktSetup(ThreadVars *tv, DecodeThreadVars *dtv, Packet *parent, - const uint8_t *pkt, uint32_t len, enum DecodeTunnelProto proto) + const uint8_t *pkt, uint32_t len, enum DecodeTunnelProto proto) { int ret; @@ -343,12 +341,10 @@ Packet *PacketTunnelPktSetup(ThreadVars *tv, DecodeThreadVars *dtv, Packet *pare /* tell new packet it's part of a tunnel */ SET_TUNNEL_PKT(p); - ret = DecodeTunnel(tv, dtv, p, GET_PKT_DATA(p), - GET_PKT_LEN(p), proto); + ret = DecodeTunnel(tv, dtv, p, GET_PKT_DATA(p), GET_PKT_LEN(p), proto); if (unlikely(ret != TM_ECODE_OK) || - (proto == DECODE_TUNNEL_IPV6_TEREDO && (p->flags & PKT_IS_INVALID))) - { + (proto == DECODE_TUNNEL_IPV6_TEREDO && (p->flags & PKT_IS_INVALID))) { /* Not a (valid) tunnel packet */ SCLogDebug("tunnel packet is invalid"); @@ -358,7 +354,6 @@ Packet *PacketTunnelPktSetup(ThreadVars *tv, DecodeThreadVars *dtv, Packet *pare SCReturnPtr(NULL, "Packet"); } - /* tell parent packet it's part of a tunnel */ SET_TUNNEL_PKT(parent); @@ -450,8 +445,7 @@ void PacketBypassCallback(Packet *p) * if we have failed to do it once */ if (p->flow) { int state = p->flow->flow_state; - if ((state == FLOW_STATE_LOCAL_BYPASSED) || - (state == FLOW_STATE_CAPTURE_BYPASSED)) { + if ((state == FLOW_STATE_LOCAL_BYPASSED) || (state == FLOW_STATE_CAPTURE_BYPASSED)) { return; } @@ -586,17 +580,15 @@ void DecodeRegisterPerfCounters(DecodeThreadVars *dtv, ThreadVars *tv) dtv->counter_flow_spare_sync_avg = StatsRegisterAvgCounter("flow.wrk.spare_sync_avg", tv); dtv->counter_flow_spare_sync = StatsRegisterCounter("flow.wrk.spare_sync", tv); - dtv->counter_flow_spare_sync_incomplete = StatsRegisterCounter("flow.wrk.spare_sync_incomplete", tv); + dtv->counter_flow_spare_sync_incomplete = + StatsRegisterCounter("flow.wrk.spare_sync_incomplete", tv); dtv->counter_flow_spare_sync_empty = StatsRegisterCounter("flow.wrk.spare_sync_empty", tv); - dtv->counter_defrag_ipv4_fragments = - StatsRegisterCounter("defrag.ipv4.fragments", tv); + dtv->counter_defrag_ipv4_fragments = StatsRegisterCounter("defrag.ipv4.fragments", tv); dtv->counter_defrag_ipv4_reassembled = StatsRegisterCounter("defrag.ipv4.reassembled", tv); - dtv->counter_defrag_ipv6_fragments = - StatsRegisterCounter("defrag.ipv6.fragments", tv); + dtv->counter_defrag_ipv6_fragments = StatsRegisterCounter("defrag.ipv6.fragments", tv); dtv->counter_defrag_ipv6_reassembled = StatsRegisterCounter("defrag.ipv6.reassembled", tv); - dtv->counter_defrag_max_hit = - StatsRegisterCounter("defrag.max_frag_hits", tv); + dtv->counter_defrag_max_hit = StatsRegisterCounter("defrag.max_frag_hits", tv); for (int i = 0; i < DECODE_EVENT_MAX; i++) { BUG_ON(i != (int)DEvents[i].code); @@ -606,14 +598,11 @@ void DecodeRegisterPerfCounters(DecodeThreadVars *dtv, ThreadVars *tv) else if (i > DECODE_EVENT_PACKET_MAX && !stats_stream_events) continue; - if (i < DECODE_EVENT_PACKET_MAX && - strncmp(DEvents[i].event_name, "decoder.", 8) == 0) - { + if (i < DECODE_EVENT_PACKET_MAX && strncmp(DEvents[i].event_name, "decoder.", 8) == 0) { SCMutexLock(&g_counter_table_mutex); if (g_counter_table == NULL) { - g_counter_table = HashTableInit(256, StringHashFunc, - StringHashCompareFunc, - StringHashFreeFunc); + g_counter_table = HashTableInit( + 256, StringHashFunc, StringHashCompareFunc, StringHashFreeFunc); if (g_counter_table == NULL) { FatalError("decoder counter hash " "table init failed"); @@ -623,8 +612,7 @@ void DecodeRegisterPerfCounters(DecodeThreadVars *dtv, ThreadVars *tv) char name[256]; char *dot = strchr(DEvents[i].event_name, '.'); BUG_ON(!dot); - snprintf(name, sizeof(name), "%s.%s", - stats_decoder_events_prefix, dot+1); + snprintf(name, sizeof(name), "%s.%s", stats_decoder_events_prefix, dot + 1); const char *found = HashTableLookup(g_counter_table, name, 0); if (!found) { @@ -638,24 +626,21 @@ void DecodeRegisterPerfCounters(DecodeThreadVars *dtv, ThreadVars *tv) "table name add failed"); found = add; } - dtv->counter_engine_events[i] = StatsRegisterCounter( - found, tv); + dtv->counter_engine_events[i] = StatsRegisterCounter(found, tv); SCMutexUnlock(&g_counter_table_mutex); } else { - dtv->counter_engine_events[i] = StatsRegisterCounter( - DEvents[i].event_name, tv); + dtv->counter_engine_events[i] = StatsRegisterCounter(DEvents[i].event_name, tv); } } return; } -void DecodeUpdatePacketCounters(ThreadVars *tv, - const DecodeThreadVars *dtv, const Packet *p) +void DecodeUpdatePacketCounters(ThreadVars *tv, const DecodeThreadVars *dtv, const Packet *p) { StatsIncr(tv, dtv->counter_pkts); - //StatsIncr(tv, dtv->counter_pkts_per_sec); + // StatsIncr(tv, dtv->counter_pkts_per_sec); StatsAddUI64(tv, dtv->counter_bytes, GET_PKT_LEN(p)); StatsAddUI64(tv, dtv->counter_avg_pkt_size, GET_PKT_LEN(p)); StatsSetUI64(tv, dtv->counter_max_pkt_size, GET_PKT_LEN(p)); @@ -674,8 +659,7 @@ void AddressDebugPrint(Address *a) return; switch (a->family) { - case AF_INET: - { + case AF_INET: { char s[16]; PrintInet(AF_INET, (const void *)&a->addr_data32[0], s, sizeof(s)); SCLogDebug("%s", s); @@ -730,7 +714,7 @@ inline int PacketSetData(Packet *p, const uint8_t *pktdata, uint32_t pktlen) return -1; } // ext_pkt cannot be const (because we sometimes copy) - p->ext_pkt = (uint8_t *) pktdata; + p->ext_pkt = (uint8_t *)pktdata; p->flags |= PKT_ZERO_COPY; return 0; diff --git a/src/decode.h b/src/decode.h index 6392f3361e58..2dea675c9b17 100644 --- a/src/decode.h +++ b/src/decode.h @@ -98,7 +98,6 @@ enum PktSrcEnum { #include "decode-vlan.h" #include "decode-mpls.h" - /* forward declarations */ struct DetectionEngineThreadCtx_; typedef struct AppLayerThreadCtx_ AppLayerThreadCtx; @@ -115,24 +114,25 @@ void AppLayerDecoderEventsFreeEvents(AppLayerDecoderEvents **events); typedef struct Address_ { char family; union { - uint32_t address_un_data32[4]; /* type-specific field */ - uint16_t address_un_data16[8]; /* type-specific field */ - uint8_t address_un_data8[16]; /* type-specific field */ + uint32_t address_un_data32[4]; /* type-specific field */ + uint16_t address_un_data16[8]; /* type-specific field */ + uint8_t address_un_data8[16]; /* type-specific field */ struct in6_addr address_un_in6; } address; } Address; -#define addr_data32 address.address_un_data32 -#define addr_data16 address.address_un_data16 -#define addr_data8 address.address_un_data8 -#define addr_in6addr address.address_un_in6 - -#define COPY_ADDRESS(a, b) do { \ - (b)->family = (a)->family; \ - (b)->addr_data32[0] = (a)->addr_data32[0]; \ - (b)->addr_data32[1] = (a)->addr_data32[1]; \ - (b)->addr_data32[2] = (a)->addr_data32[2]; \ - (b)->addr_data32[3] = (a)->addr_data32[3]; \ +#define addr_data32 address.address_un_data32 +#define addr_data16 address.address_un_data16 +#define addr_data8 address.address_un_data8 +#define addr_in6addr address.address_un_in6 + +#define COPY_ADDRESS(a, b) \ + do { \ + (b)->family = (a)->family; \ + (b)->addr_data32[0] = (a)->addr_data32[0]; \ + (b)->addr_data32[1] = (a)->addr_data32[1]; \ + (b)->addr_data32[2] = (a)->addr_data32[2]; \ + (b)->addr_data32[3] = (a)->addr_data32[3]; \ } while (0) /* Set the IPv4 addresses into the Addrs of the Packet. @@ -140,70 +140,79 @@ typedef struct Address_ { * * We set the rest of the struct to 0 so we can * prevent using memset. */ -#define SET_IPV4_SRC_ADDR(p, a) do { \ - (a)->family = AF_INET; \ - (a)->addr_data32[0] = (uint32_t)(p)->ip4h->s_ip_src.s_addr; \ - (a)->addr_data32[1] = 0; \ - (a)->addr_data32[2] = 0; \ - (a)->addr_data32[3] = 0; \ +#define SET_IPV4_SRC_ADDR(p, a) \ + do { \ + (a)->family = AF_INET; \ + (a)->addr_data32[0] = (uint32_t)(p)->ip4h->s_ip_src.s_addr; \ + (a)->addr_data32[1] = 0; \ + (a)->addr_data32[2] = 0; \ + (a)->addr_data32[3] = 0; \ } while (0) -#define SET_IPV4_DST_ADDR(p, a) do { \ - (a)->family = AF_INET; \ - (a)->addr_data32[0] = (uint32_t)(p)->ip4h->s_ip_dst.s_addr; \ - (a)->addr_data32[1] = 0; \ - (a)->addr_data32[2] = 0; \ - (a)->addr_data32[3] = 0; \ +#define SET_IPV4_DST_ADDR(p, a) \ + do { \ + (a)->family = AF_INET; \ + (a)->addr_data32[0] = (uint32_t)(p)->ip4h->s_ip_dst.s_addr; \ + (a)->addr_data32[1] = 0; \ + (a)->addr_data32[2] = 0; \ + (a)->addr_data32[3] = 0; \ } while (0) /* Set the IPv6 addresses into the Addrs of the Packet. * Make sure p->ip6h is initialized and validated. */ -#define SET_IPV6_SRC_ADDR(p, a) do { \ - (a)->family = AF_INET6; \ - (a)->addr_data32[0] = (p)->ip6h->s_ip6_src[0]; \ - (a)->addr_data32[1] = (p)->ip6h->s_ip6_src[1]; \ - (a)->addr_data32[2] = (p)->ip6h->s_ip6_src[2]; \ - (a)->addr_data32[3] = (p)->ip6h->s_ip6_src[3]; \ +#define SET_IPV6_SRC_ADDR(p, a) \ + do { \ + (a)->family = AF_INET6; \ + (a)->addr_data32[0] = (p)->ip6h->s_ip6_src[0]; \ + (a)->addr_data32[1] = (p)->ip6h->s_ip6_src[1]; \ + (a)->addr_data32[2] = (p)->ip6h->s_ip6_src[2]; \ + (a)->addr_data32[3] = (p)->ip6h->s_ip6_src[3]; \ } while (0) -#define SET_IPV6_DST_ADDR(p, a) do { \ - (a)->family = AF_INET6; \ - (a)->addr_data32[0] = (p)->ip6h->s_ip6_dst[0]; \ - (a)->addr_data32[1] = (p)->ip6h->s_ip6_dst[1]; \ - (a)->addr_data32[2] = (p)->ip6h->s_ip6_dst[2]; \ - (a)->addr_data32[3] = (p)->ip6h->s_ip6_dst[3]; \ +#define SET_IPV6_DST_ADDR(p, a) \ + do { \ + (a)->family = AF_INET6; \ + (a)->addr_data32[0] = (p)->ip6h->s_ip6_dst[0]; \ + (a)->addr_data32[1] = (p)->ip6h->s_ip6_dst[1]; \ + (a)->addr_data32[2] = (p)->ip6h->s_ip6_dst[2]; \ + (a)->addr_data32[3] = (p)->ip6h->s_ip6_dst[3]; \ } while (0) /* Set the TCP ports into the Ports of the Packet. * Make sure p->tcph is initialized and validated. */ -#define SET_TCP_SRC_PORT(pkt, prt) do { \ - SET_PORT(TCP_GET_SRC_PORT((pkt)), *(prt)); \ +#define SET_TCP_SRC_PORT(pkt, prt) \ + do { \ + SET_PORT(TCP_GET_SRC_PORT((pkt)), *(prt)); \ } while (0) -#define SET_TCP_DST_PORT(pkt, prt) do { \ - SET_PORT(TCP_GET_DST_PORT((pkt)), *(prt)); \ +#define SET_TCP_DST_PORT(pkt, prt) \ + do { \ + SET_PORT(TCP_GET_DST_PORT((pkt)), *(prt)); \ } while (0) /* Set the UDP ports into the Ports of the Packet. * Make sure p->udph is initialized and validated. */ -#define SET_UDP_SRC_PORT(pkt, prt) do { \ - SET_PORT(UDP_GET_SRC_PORT((pkt)), *(prt)); \ +#define SET_UDP_SRC_PORT(pkt, prt) \ + do { \ + SET_PORT(UDP_GET_SRC_PORT((pkt)), *(prt)); \ } while (0) -#define SET_UDP_DST_PORT(pkt, prt) do { \ - SET_PORT(UDP_GET_DST_PORT((pkt)), *(prt)); \ +#define SET_UDP_DST_PORT(pkt, prt) \ + do { \ + SET_PORT(UDP_GET_DST_PORT((pkt)), *(prt)); \ } while (0) /* Set the SCTP ports into the Ports of the Packet. * Make sure p->sctph is initialized and validated. */ -#define SET_SCTP_SRC_PORT(pkt, prt) do { \ - SET_PORT(SCTP_GET_SRC_PORT((pkt)), *(prt)); \ +#define SET_SCTP_SRC_PORT(pkt, prt) \ + do { \ + SET_PORT(SCTP_GET_SRC_PORT((pkt)), *(prt)); \ } while (0) -#define SET_SCTP_DST_PORT(pkt, prt) do { \ - SET_PORT(SCTP_GET_DST_PORT((pkt)), *(prt)); \ +#define SET_SCTP_DST_PORT(pkt, prt) \ + do { \ + SET_PORT(SCTP_GET_DST_PORT((pkt)), *(prt)); \ } while (0) - #define GET_IPV4_SRC_ADDR_U32(p) ((p)->src.addr_data32[0]) #define GET_IPV4_DST_ADDR_U32(p) ((p)->dst.addr_data32[0]) #define GET_IPV4_SRC_ADDR_PTR(p) ((p)->src.addr_data32) @@ -211,57 +220,58 @@ typedef struct Address_ { #define GET_IPV6_SRC_IN6ADDR(p) ((p)->src.addr_in6addr) #define GET_IPV6_DST_IN6ADDR(p) ((p)->dst.addr_in6addr) -#define GET_IPV6_SRC_ADDR(p) ((p)->src.addr_data32) -#define GET_IPV6_DST_ADDR(p) ((p)->dst.addr_data32) -#define GET_TCP_SRC_PORT(p) ((p)->sp) -#define GET_TCP_DST_PORT(p) ((p)->dp) +#define GET_IPV6_SRC_ADDR(p) ((p)->src.addr_data32) +#define GET_IPV6_DST_ADDR(p) ((p)->dst.addr_data32) +#define GET_TCP_SRC_PORT(p) ((p)->sp) +#define GET_TCP_DST_PORT(p) ((p)->dp) #define GET_PKT_LEN(p) (p)->pktlen #define GET_PKT_DATA(p) (((p)->ext_pkt == NULL) ? GET_PKT_DIRECT_DATA(p) : (p)->ext_pkt) #define GET_PKT_DIRECT_DATA(p) (p)->pkt_data #define GET_PKT_DIRECT_MAX_SIZE(p) (default_packet_size) -#define SET_PKT_LEN(p, len) do { \ - (p)->pktlen = (len); \ +#define SET_PKT_LEN(p, len) \ + do { \ + (p)->pktlen = (len); \ } while (0) /* Port is just a uint16_t */ typedef uint16_t Port; -#define SET_PORT(v, p) ((p) = (v)) -#define COPY_PORT(a,b) ((b) = (a)) +#define SET_PORT(v, p) ((p) = (v)) +#define COPY_PORT(a, b) ((b) = (a)) -#define CMP_ADDR(a1, a2) \ - (((a1)->addr_data32[3] == (a2)->addr_data32[3] && \ - (a1)->addr_data32[2] == (a2)->addr_data32[2] && \ - (a1)->addr_data32[1] == (a2)->addr_data32[1] && \ - (a1)->addr_data32[0] == (a2)->addr_data32[0])) -#define CMP_PORT(p1, p2) \ - ((p1) == (p2)) +#define CMP_ADDR(a1, a2) \ + (((a1)->addr_data32[3] == (a2)->addr_data32[3] && \ + (a1)->addr_data32[2] == (a2)->addr_data32[2] && \ + (a1)->addr_data32[1] == (a2)->addr_data32[1] && \ + (a1)->addr_data32[0] == (a2)->addr_data32[0])) +#define CMP_PORT(p1, p2) ((p1) == (p2)) /*Given a packet pkt offset to the start of the ip header in a packet *We determine the ip version. */ #define IP_GET_RAW_VER(pkt) ((((pkt)[0] & 0xf0) >> 4)) -#define PKT_IS_IPV4(p) (((p)->ip4h != NULL)) -#define PKT_IS_IPV6(p) (((p)->ip6h != NULL)) -#define PKT_IS_TCP(p) (((p)->tcph != NULL)) -#define PKT_IS_UDP(p) (((p)->udph != NULL)) -#define PKT_IS_ICMPV4(p) (((p)->icmpv4h != NULL)) -#define PKT_IS_ICMPV6(p) (((p)->icmpv6h != NULL)) -#define PKT_IS_TOSERVER(p) (((p)->flowflags & FLOW_PKT_TOSERVER)) -#define PKT_IS_TOCLIENT(p) (((p)->flowflags & FLOW_PKT_TOCLIENT)) +#define PKT_IS_IPV4(p) (((p)->ip4h != NULL)) +#define PKT_IS_IPV6(p) (((p)->ip6h != NULL)) +#define PKT_IS_TCP(p) (((p)->tcph != NULL)) +#define PKT_IS_UDP(p) (((p)->udph != NULL)) +#define PKT_IS_ICMPV4(p) (((p)->icmpv4h != NULL)) +#define PKT_IS_ICMPV6(p) (((p)->icmpv6h != NULL)) +#define PKT_IS_TOSERVER(p) (((p)->flowflags & FLOW_PKT_TOSERVER)) +#define PKT_IS_TOCLIENT(p) (((p)->flowflags & FLOW_PKT_TOCLIENT)) #define IPH_IS_VALID(p) (PKT_IS_IPV4((p)) || PKT_IS_IPV6((p))) /* Retrieve proto regardless of IP version */ -#define IP_GET_IPPROTO(p) \ - (p->proto ? p->proto : \ - (PKT_IS_IPV4((p))? IPV4_GET_IPPROTO((p)) : (PKT_IS_IPV6((p))? IPV6_GET_L4PROTO((p)) : 0))) +#define IP_GET_IPPROTO(p) \ + (p->proto ? p->proto \ + : (PKT_IS_IPV4((p)) ? IPV4_GET_IPPROTO((p)) \ + : (PKT_IS_IPV6((p)) ? IPV6_GET_L4PROTO((p)) : 0))) /* structure to store the sids/gids/etc the detection engine * found in this packet */ typedef struct PacketAlert_ { - SigIntId num; /* Internal num, used for sorting */ + SigIntId num; /* Internal num, used for sorting */ uint8_t action; /* Internal num, used for thresholding */ uint8_t flags; const struct Signature_ *s; @@ -272,13 +282,13 @@ typedef struct PacketAlert_ { /* flag to indicate the rule action (drop/pass) needs to be applied to the flow */ #define PACKET_ALERT_FLAG_APPLY_ACTION_TO_FLOW 0x1 /** alert was generated based on state */ -#define PACKET_ALERT_FLAG_STATE_MATCH 0x02 +#define PACKET_ALERT_FLAG_STATE_MATCH 0x02 /** alert was generated based on stream */ -#define PACKET_ALERT_FLAG_STREAM_MATCH 0x04 +#define PACKET_ALERT_FLAG_STREAM_MATCH 0x04 /** alert is in a tx, tx_id set */ -#define PACKET_ALERT_FLAG_TX 0x08 +#define PACKET_ALERT_FLAG_TX 0x08 /** action was changed by rate_filter */ -#define PACKET_ALERT_RATE_FILTER_MODIFIED 0x10 +#define PACKET_ALERT_RATE_FILTER_MODIFIED 0x10 /** alert is in a frame, frame_id set */ #define PACKET_ALERT_FLAG_FRAME 0x20 @@ -305,8 +315,8 @@ void PacketAlertFree(PacketAlert *pa); /** data structure to store decoder, defrag and stream events */ typedef struct PacketEngineEvents_ { - uint8_t cnt; /**< number of events */ - uint8_t events[PACKET_ENGINE_EVENT_MAX]; /**< array of events */ + uint8_t cnt; /**< number of events */ + uint8_t events[PACKET_ENGINE_EVENT_MAX]; /**< array of events */ } PacketEngineEvents; typedef struct PktVar_ { @@ -369,7 +379,7 @@ typedef struct PktProfilingPrefilterEngine_ { typedef struct PktProfilingPrefilterData_ { PktProfilingPrefilterEngine *engines; - uint32_t size; /**< array size */ + uint32_t size; /**< array size */ } PktProfilingPrefilterData; /** \brief Per pkt stats storage */ @@ -426,8 +436,7 @@ struct PacketQueue_; * * sum of above 44/48 bytes */ -typedef struct Packet_ -{ +typedef struct Packet_ { /* Addresses, Ports and protocol * these are on top so we can use * the Packet as a hash key */ @@ -550,9 +559,9 @@ typedef struct Packet_ ICMPV4Vars icmpv4vars; ICMPV6Vars icmpv6vars; } l4vars; -#define tcpvars l4vars.tcpvars -#define icmpv4vars l4vars.icmpv4vars -#define icmpv6vars l4vars.icmpv6vars +#define tcpvars l4vars.tcpvars +#define icmpv4vars l4vars.icmpv4vars +#define icmpv6vars l4vars.icmpv6vars TCPHdr *tcph; @@ -597,7 +606,6 @@ typedef struct Packet_ /** packet number in the pcap file, matches wireshark */ uint64_t pcap_cnt; - /* engine events */ PacketEngineEvents events; @@ -660,7 +668,7 @@ typedef struct Packet_ /** highest mtu of the interfaces we monitor */ #define DEFAULT_MTU 1500 -#define MINIMUM_MTU 68 /**< ipv4 minimum: rfc791 */ +#define MINIMUM_MTU 68 /**< ipv4 minimum: rfc791 */ #define DEFAULT_PACKET_SIZE (DEFAULT_MTU + ETHERNET_HEADER_LEN) /* storage: maximum ip packet size + link header */ @@ -669,8 +677,7 @@ extern uint32_t default_packet_size; #define SIZE_OF_PACKET (default_packet_size + sizeof(Packet)) /** \brief Structure to hold thread specific data for all decode modules */ -typedef struct DecodeThreadVars_ -{ +typedef struct DecodeThreadVars_ { /** Specific context for udp protocol detection (here atm) */ AppLayerThreadCtx *app_tctx; @@ -759,30 +766,34 @@ typedef struct DecodeThreadVars_ void CaptureStatsUpdate(ThreadVars *tv, const Packet *p); void CaptureStatsSetup(ThreadVars *tv); -#define PACKET_CLEAR_L4VARS(p) do { \ - memset(&(p)->l4vars, 0x00, sizeof((p)->l4vars)); \ +#define PACKET_CLEAR_L4VARS(p) \ + do { \ + memset(&(p)->l4vars, 0x00, sizeof((p)->l4vars)); \ } while (0) /** * \brief reset these to -1(indicates that the packet is fresh from the queue) */ -#define PACKET_RESET_CHECKSUMS(p) do { \ - (p)->level3_comp_csum = -1; \ - (p)->level4_comp_csum = -1; \ +#define PACKET_RESET_CHECKSUMS(p) \ + do { \ + (p)->level3_comp_csum = -1; \ + (p)->level4_comp_csum = -1; \ } while (0) /* if p uses extended data, free them */ -#define PACKET_FREE_EXTDATA(p) do { \ - if ((p)->ext_pkt) { \ - if (!((p)->flags & PKT_ZERO_COPY)) { \ - SCFree((p)->ext_pkt); \ - } \ - (p)->ext_pkt = NULL; \ - } \ - } while(0) - -#define TUNNEL_INCR_PKT_RTV_NOLOCK(p) do { \ - ((p)->root ? (p)->root->tunnel_rtv_cnt++ : (p)->tunnel_rtv_cnt++); \ +#define PACKET_FREE_EXTDATA(p) \ + do { \ + if ((p)->ext_pkt) { \ + if (!((p)->flags & PKT_ZERO_COPY)) { \ + SCFree((p)->ext_pkt); \ + } \ + (p)->ext_pkt = NULL; \ + } \ + } while (0) + +#define TUNNEL_INCR_PKT_RTV_NOLOCK(p) \ + do { \ + ((p)->root ? (p)->root->tunnel_rtv_cnt++ : (p)->tunnel_rtv_cnt++); \ } while (0) static inline void TUNNEL_INCR_PKT_TPR(Packet *p) @@ -796,10 +807,10 @@ static inline void TUNNEL_INCR_PKT_TPR(Packet *p) #define TUNNEL_PKT_RTV(p) ((p)->root ? (p)->root->tunnel_rtv_cnt : (p)->tunnel_rtv_cnt) #define TUNNEL_PKT_TPR(p) ((p)->root ? (p)->root->tunnel_tpr_cnt : (p)->tunnel_tpr_cnt) -#define IS_TUNNEL_PKT(p) (((p)->flags & PKT_TUNNEL)) -#define SET_TUNNEL_PKT(p) ((p)->flags |= PKT_TUNNEL) -#define UNSET_TUNNEL_PKT(p) ((p)->flags &= ~PKT_TUNNEL) -#define IS_TUNNEL_ROOT_PKT(p) (IS_TUNNEL_PKT(p) && (p)->root == NULL) +#define IS_TUNNEL_PKT(p) (((p)->flags & PKT_TUNNEL)) +#define SET_TUNNEL_PKT(p) ((p)->flags |= PKT_TUNNEL) +#define UNSET_TUNNEL_PKT(p) ((p)->flags &= ~PKT_TUNNEL) +#define IS_TUNNEL_ROOT_PKT(p) (IS_TUNNEL_PKT(p) && (p)->root == NULL) #define IS_TUNNEL_PKT_VERDICTED(p) (((p)->flags & PKT_TUNNEL_VERDICTED)) #define SET_TUNNEL_PKT_VERDICTED(p) ((p)->flags |= PKT_TUNNEL_VERDICTED) @@ -818,15 +829,14 @@ enum DecodeTunnelProto { }; Packet *PacketTunnelPktSetup(ThreadVars *tv, DecodeThreadVars *dtv, Packet *parent, - const uint8_t *pkt, uint32_t len, enum DecodeTunnelProto proto); + const uint8_t *pkt, uint32_t len, enum DecodeTunnelProto proto); Packet *PacketDefragPktSetup(Packet *parent, const uint8_t *pkt, uint32_t len, uint8_t proto); void PacketDefragPktSetupParent(Packet *parent); void DecodeRegisterPerfCounters(DecodeThreadVars *, ThreadVars *); Packet *PacketGetFromQueueOrAlloc(void); Packet *PacketGetFromAlloc(void); void PacketDecodeFinalize(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p); -void PacketUpdateEngineEventCounters(ThreadVars *tv, - DecodeThreadVars *dtv, Packet *p); +void PacketUpdateEngineEventCounters(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p); void PacketFree(Packet *p); void PacketFreeOrRelease(Packet *p); int PacketCallocExtPkt(Packet *p, int datalen); @@ -839,8 +849,7 @@ void PacketSwap(Packet *p); DecodeThreadVars *DecodeThreadVarsAlloc(ThreadVars *); void DecodeThreadVarsFree(ThreadVars *, DecodeThreadVars *); -void DecodeUpdatePacketCounters(ThreadVars *tv, - const DecodeThreadVars *dtv, const Packet *p); +void DecodeUpdatePacketCounters(ThreadVars *tv, const DecodeThreadVars *dtv, const Packet *p); const char *PacketDropReasonToString(enum PacketDropReason r); /* decoder functions */ @@ -873,45 +882,45 @@ int DecodeTEMPLATE(ThreadVars *, DecodeThreadVars *, Packet *, const uint8_t *, int DecodeNSH(ThreadVars *, DecodeThreadVars *, Packet *, const uint8_t *, uint32_t); #ifdef UNITTESTS -void DecodeIPV6FragHeader(Packet *p, const uint8_t *pkt, - uint16_t hdrextlen, uint16_t plen, - uint16_t prev_hdrextlen); +void DecodeIPV6FragHeader( + Packet *p, const uint8_t *pkt, uint16_t hdrextlen, uint16_t plen, uint16_t prev_hdrextlen); #endif void AddressDebugPrint(Address *); -typedef int (*DecoderFunc)(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, - const uint8_t *pkt, uint32_t len); +typedef int (*DecoderFunc)( + ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, const uint8_t *pkt, uint32_t len); void DecodeGlobalConfig(void); void PacketAlertGetMaxConfig(void); void DecodeUnregisterCounters(void); -#define ENGINE_SET_EVENT(p, e) do { \ - SCLogDebug("p %p event %d", (p), e); \ - if ((p)->events.cnt < PACKET_ENGINE_EVENT_MAX) { \ - (p)->events.events[(p)->events.cnt] = e; \ - (p)->events.cnt++; \ - } \ -} while(0) - -#define ENGINE_SET_INVALID_EVENT(p, e) do { \ - p->flags |= PKT_IS_INVALID; \ - ENGINE_SET_EVENT(p, e); \ -} while(0) - - - -#define ENGINE_ISSET_EVENT(p, e) ({ \ - int r = 0; \ - uint8_t u; \ - for (u = 0; u < (p)->events.cnt; u++) { \ - if ((p)->events.events[u] == (e)) { \ - r = 1; \ - break; \ - } \ - } \ - r; \ -}) +#define ENGINE_SET_EVENT(p, e) \ + do { \ + SCLogDebug("p %p event %d", (p), e); \ + if ((p)->events.cnt < PACKET_ENGINE_EVENT_MAX) { \ + (p)->events.events[(p)->events.cnt] = e; \ + (p)->events.cnt++; \ + } \ + } while (0) + +#define ENGINE_SET_INVALID_EVENT(p, e) \ + do { \ + p->flags |= PKT_IS_INVALID; \ + ENGINE_SET_EVENT(p, e); \ + } while (0) + +#define ENGINE_ISSET_EVENT(p, e) \ + ({ \ + int r = 0; \ + uint8_t u; \ + for (u = 0; u < (p)->events.cnt; u++) { \ + if ((p)->events.events[u] == (e)) { \ + r = 1; \ + break; \ + } \ + } \ + r; \ + }) #ifndef IPPROTO_IPIP #define IPPROTO_IPIP 4 @@ -958,9 +967,9 @@ void DecodeUnregisterCounters(void); /* taken from pcap's bpf.h */ #ifndef DLT_RAW #ifdef __OpenBSD__ -#define DLT_RAW 14 /* raw IP */ +#define DLT_RAW 14 /* raw IP */ #else -#define DLT_RAW 12 /* raw IP */ +#define DLT_RAW 12 /* raw IP */ #endif #endif @@ -970,11 +979,11 @@ void DecodeUnregisterCounters(void); /** libpcap shows us the way to linktype codes * \todo we need more & maybe put them in a separate file? */ -#define LINKTYPE_NULL DLT_NULL -#define LINKTYPE_ETHERNET DLT_EN10MB -#define LINKTYPE_LINUX_SLL 113 -#define LINKTYPE_PPP 9 -#define LINKTYPE_RAW DLT_RAW +#define LINKTYPE_NULL DLT_NULL +#define LINKTYPE_ETHERNET DLT_EN10MB +#define LINKTYPE_LINUX_SLL 113 +#define LINKTYPE_PPP 9 +#define LINKTYPE_RAW DLT_RAW /* http://www.tcpdump.org/linktypes.html defines DLT_RAW as 101, yet others don't. * Libpcap on at least OpenBSD returns 101 as datalink type for RAW pcaps though. */ #define LINKTYPE_RAW2 101 @@ -1055,8 +1064,7 @@ void DecodeUnregisterCounters(void); #define PKT_FIRST_TAG BIT_U32(30) /** \brief return 1 if the packet is a pseudo packet */ -#define PKT_IS_PSEUDOPKT(p) \ - ((p)->flags & (PKT_PSEUDO_STREAM_END|PKT_PSEUDO_DETECTLOG_FLUSH)) +#define PKT_IS_PSEUDOPKT(p) ((p)->flags & (PKT_PSEUDO_STREAM_END | PKT_PSEUDO_DETECTLOG_FLUSH)) #define PKT_SET_SRC(p, src_val) ((p)->pkt_src = src_val) @@ -1113,7 +1121,8 @@ static inline bool VerdictTunnelPacket(Packet *p) if (IS_TUNNEL_ROOT_PKT(p) && !IS_TUNNEL_PKT_VERDICTED(p) && !outstanding) { // verdict SCLogDebug("root %p: verdict", p); - } else if (!IS_TUNNEL_ROOT_PKT(p) && outstanding == 1 && p->root && IS_TUNNEL_PKT_VERDICTED(p->root)) { + } else if (!IS_TUNNEL_ROOT_PKT(p) && outstanding == 1 && p->root && + IS_TUNNEL_PKT_VERDICTED(p->root)) { // verdict SCLogDebug("tunnel %p: verdict", p); } else { @@ -1123,8 +1132,8 @@ static inline bool VerdictTunnelPacket(Packet *p) return verdict; } -static inline void DecodeLinkLayer(ThreadVars *tv, DecodeThreadVars *dtv, - const int datalink, Packet *p, const uint8_t *data, const uint32_t len) +static inline void DecodeLinkLayer(ThreadVars *tv, DecodeThreadVars *dtv, const int datalink, + Packet *p, const uint8_t *data, const uint32_t len) { /* call the decoder */ switch (datalink) { @@ -1144,7 +1153,7 @@ static inline void DecodeLinkLayer(ThreadVars *tv, DecodeThreadVars *dtv, case LINKTYPE_NULL: DecodeNull(tv, dtv, p, data, len); break; - case LINKTYPE_CISCO_HDLC: + case LINKTYPE_CISCO_HDLC: DecodeCHDLC(tv, dtv, p, data, len); break; default: @@ -1157,8 +1166,8 @@ static inline void DecodeLinkLayer(ThreadVars *tv, DecodeThreadVars *dtv, /** \brief decode network layer * \retval bool true if successful, false if unknown */ -static inline bool DecodeNetworkLayer(ThreadVars *tv, DecodeThreadVars *dtv, - const uint16_t proto, Packet *p, const uint8_t *data, const uint32_t len) +static inline bool DecodeNetworkLayer(ThreadVars *tv, DecodeThreadVars *dtv, const uint16_t proto, + Packet *p, const uint8_t *data, const uint32_t len) { switch (proto) { case ETHERNET_TYPE_IP: { @@ -1181,7 +1190,7 @@ static inline bool DecodeNetworkLayer(ThreadVars *tv, DecodeThreadVars *dtv, case ETHERNET_TYPE_8021AD: case ETHERNET_TYPE_8021QINQ: if (p->vlan_idx > VLAN_MAX_LAYER_IDX) { - ENGINE_SET_EVENT(p,VLAN_HEADER_TOO_MANY_LAYERS); + ENGINE_SET_EVENT(p, VLAN_HEADER_TOO_MANY_LAYERS); } else { DecodeVLAN(tv, dtv, p, data, len); } diff --git a/src/defrag-config.c b/src/defrag-config.c index 7e2ae0cde96a..170e0e63491c 100644 --- a/src/defrag-config.c +++ b/src/defrag-config.c @@ -43,7 +43,7 @@ static void DefragPolicyAddHostInfo(char *host_ip_range, uint64_t timeout) { uint64_t *user_data = NULL; - if ( (user_data = SCMalloc(sizeof(uint64_t))) == NULL) { + if ((user_data = SCMalloc(sizeof(uint64_t))) == NULL) { FatalError("Error allocating memory. Exiting"); } @@ -108,7 +108,7 @@ static void DefragParseParameters(ConfNode *n) ConfNode *si; uint64_t timeout = 0; - TAILQ_FOREACH(si, &n->head, next) { + TAILQ_FOREACH (si, &n->head, next) { if (strcasecmp("timeout", si->name) == 0) { SCLogDebug("timeout value %s", si->val); if (ParseSizeStringU64(si->val, &timeout) < 0) { @@ -118,7 +118,7 @@ static void DefragParseParameters(ConfNode *n) } if (strcasecmp("address", si->name) == 0) { ConfNode *pval; - TAILQ_FOREACH(pval, &si->head, next) { + TAILQ_FOREACH (pval, &si->head, next) { DefragPolicyAddHostInfo(pval->val, timeout); } } @@ -149,10 +149,10 @@ void DefragPolicyLoadFromConfig(void) SCLogDebug("configuring host config %p", server_config); ConfNode *sc; - TAILQ_FOREACH(sc, &server_config->head, next) { + TAILQ_FOREACH (sc, &server_config->head, next) { ConfNode *p = NULL; - TAILQ_FOREACH(p, &sc->head, next) { + TAILQ_FOREACH (p, &sc->head, next) { SCLogDebug("parsing configuration for %s", p->name); DefragParseParameters(p); } diff --git a/src/defrag-hash.c b/src/defrag-hash.c index eb754d6eface..5faab2051cde 100644 --- a/src/defrag-hash.c +++ b/src/defrag-hash.c @@ -28,9 +28,9 @@ /** defrag tracker hash table */ DefragTrackerHashRow *defragtracker_hash; DefragConfig defrag_config; -SC_ATOMIC_DECLARE(uint64_t,defrag_memuse); -SC_ATOMIC_DECLARE(unsigned int,defragtracker_counter); -SC_ATOMIC_DECLARE(unsigned int,defragtracker_prune_idx); +SC_ATOMIC_DECLARE(uint64_t, defrag_memuse); +SC_ATOMIC_DECLARE(unsigned int, defragtracker_counter); +SC_ATOMIC_DECLARE(unsigned int, defragtracker_prune_idx); static DefragTracker *DefragTrackerGetUsedDefragTracker(void); @@ -82,7 +82,7 @@ uint32_t DefragTrackerSpareQueueGetSize(void) void DefragTrackerMoveToSpare(DefragTracker *h) { DefragTrackerEnqueue(&defragtracker_spare_q, h); - (void) SC_ATOMIC_SUB(defragtracker_counter, 1); + (void)SC_ATOMIC_SUB(defragtracker_counter, 1); } static DefragTracker *DefragTrackerAlloc(void) @@ -91,7 +91,7 @@ static DefragTracker *DefragTrackerAlloc(void) return NULL; } - (void) SC_ATOMIC_ADD(defrag_memuse, sizeof(DefragTracker)); + (void)SC_ATOMIC_ADD(defrag_memuse, sizeof(DefragTracker)); DefragTracker *dt = SCCalloc(1, sizeof(DefragTracker)); if (unlikely(dt == NULL)) @@ -112,14 +112,12 @@ static void DefragTrackerFree(DefragTracker *dt) SCMutexDestroy(&dt->lock); SCFree(dt); - (void) SC_ATOMIC_SUB(defrag_memuse, sizeof(DefragTracker)); + (void)SC_ATOMIC_SUB(defrag_memuse, sizeof(DefragTracker)); } } -#define DefragTrackerIncrUsecnt(dt) \ - SC_ATOMIC_ADD((dt)->use_cnt, 1) -#define DefragTrackerDecrUsecnt(dt) \ - SC_ATOMIC_SUB((dt)->use_cnt, 1) +#define DefragTrackerIncrUsecnt(dt) SC_ATOMIC_ADD((dt)->use_cnt, 1) +#define DefragTrackerDecrUsecnt(dt) SC_ATOMIC_SUB((dt)->use_cnt, 1) static void DefragTrackerInit(DefragTracker *dt, Packet *p) { @@ -141,12 +139,12 @@ static void DefragTrackerInit(DefragTracker *dt, Packet *p) dt->remove = 0; dt->seen_last = 0; - (void) DefragTrackerIncrUsecnt(dt); + (void)DefragTrackerIncrUsecnt(dt); } void DefragTrackerRelease(DefragTracker *t) { - (void) DefragTrackerDecrUsecnt(t); + (void)DefragTrackerDecrUsecnt(t); SCMutexUnlock(&t->lock); } @@ -156,7 +154,7 @@ void DefragTrackerClearMemory(DefragTracker *dt) } #define DEFRAG_DEFAULT_HASHSIZE 4096 -#define DEFRAG_DEFAULT_MEMCAP 16777216 +#define DEFRAG_DEFAULT_MEMCAP 16777216 #define DEFRAG_DEFAULT_PREALLOC 1000 /** \brief initialize the configuration @@ -165,8 +163,8 @@ void DefragInitConfig(bool quiet) { SCLogDebug("initializing defrag engine..."); - memset(&defrag_config, 0, sizeof(defrag_config)); - //SC_ATOMIC_INIT(flow_flags); + memset(&defrag_config, 0, sizeof(defrag_config)); + // SC_ATOMIC_INIT(flow_flags); SC_ATOMIC_INIT(defragtracker_counter); SC_ATOMIC_INIT(defrag_memuse); SC_ATOMIC_INIT(defragtracker_prune_idx); @@ -174,9 +172,9 @@ void DefragInitConfig(bool quiet) DefragTrackerQueueInit(&defragtracker_spare_q); /* set defaults */ - defrag_config.hash_rand = (uint32_t)RandomGet(); - defrag_config.hash_size = DEFRAG_DEFAULT_HASHSIZE; - defrag_config.prealloc = DEFRAG_DEFAULT_PREALLOC; + defrag_config.hash_rand = (uint32_t)RandomGet(); + defrag_config.hash_size = DEFRAG_DEFAULT_HASHSIZE; + defrag_config.prealloc = DEFRAG_DEFAULT_PREALLOC; SC_ATOMIC_SET(defrag_config.memcap, DEFRAG_DEFAULT_MEMCAP); defrag_config.memcap_policy = ExceptionPolicyParse("defrag.memcap-policy", false); @@ -186,8 +184,7 @@ void DefragInitConfig(bool quiet) uint64_t defrag_memcap; /** set config values for memcap, prealloc and hash_size */ - if ((ConfGet("defrag.memcap", &conf_val)) == 1) - { + if ((ConfGet("defrag.memcap", &conf_val)) == 1) { if (ParseSizeStringU64(conf_val, &defrag_memcap) < 0) { SCLogError("Error parsing defrag.memcap " "from conf file - %s. Killing engine", @@ -197,29 +194,24 @@ void DefragInitConfig(bool quiet) SC_ATOMIC_SET(defrag_config.memcap, defrag_memcap); } } - if ((ConfGet("defrag.hash-size", &conf_val)) == 1) - { - if (StringParseUint32(&configval, 10, strlen(conf_val), - conf_val) > 0) { + if ((ConfGet("defrag.hash-size", &conf_val)) == 1) { + if (StringParseUint32(&configval, 10, strlen(conf_val), conf_val) > 0) { defrag_config.hash_size = configval; } else { - WarnInvalidConfEntry("defrag.hash-size", "%"PRIu32, defrag_config.hash_size); + WarnInvalidConfEntry("defrag.hash-size", "%" PRIu32, defrag_config.hash_size); } } - - if ((ConfGet("defrag.trackers", &conf_val)) == 1) - { - if (StringParseUint32(&configval, 10, strlen(conf_val), - conf_val) > 0) { + if ((ConfGet("defrag.trackers", &conf_val)) == 1) { + if (StringParseUint32(&configval, 10, strlen(conf_val), conf_val) > 0) { defrag_config.prealloc = configval; } else { - WarnInvalidConfEntry("defrag.trackers", "%"PRIu32, defrag_config.prealloc); + WarnInvalidConfEntry("defrag.trackers", "%" PRIu32, defrag_config.prealloc); } } - SCLogDebug("DefragTracker config from suricata.yaml: memcap: %"PRIu64", hash-size: " - "%"PRIu32", prealloc: %"PRIu32, SC_ATOMIC_GET(defrag_config.memcap), - defrag_config.hash_size, defrag_config.prealloc); + SCLogDebug("DefragTracker config from suricata.yaml: memcap: %" PRIu64 ", hash-size: " + "%" PRIu32 ", prealloc: %" PRIu32, + SC_ATOMIC_GET(defrag_config.memcap), defrag_config.hash_size, defrag_config.prealloc); /* alloc hash memory */ uint64_t hash_size = defrag_config.hash_size * sizeof(DefragTrackerHashRow); @@ -243,17 +235,16 @@ void DefragInitConfig(bool quiet) for (i = 0; i < defrag_config.hash_size; i++) { DRLOCK_INIT(&defragtracker_hash[i]); } - (void) SC_ATOMIC_ADD(defrag_memuse, (defrag_config.hash_size * sizeof(DefragTrackerHashRow))); + (void)SC_ATOMIC_ADD(defrag_memuse, (defrag_config.hash_size * sizeof(DefragTrackerHashRow))); if (!quiet) { - SCLogConfig("allocated %"PRIu64" bytes of memory for the defrag hash... " - "%" PRIu32 " buckets of size %" PRIuMAX "", - SC_ATOMIC_GET(defrag_memuse), defrag_config.hash_size, - (uintmax_t)sizeof(DefragTrackerHashRow)); + SCLogConfig("allocated %" PRIu64 " bytes of memory for the defrag hash... " + "%" PRIu32 " buckets of size %" PRIuMAX "", + SC_ATOMIC_GET(defrag_memuse), defrag_config.hash_size, + (uintmax_t)sizeof(DefragTrackerHashRow)); } - if ((ConfGet("defrag.prealloc", &conf_val)) == 1) - { + if ((ConfGet("defrag.prealloc", &conf_val)) == 1) { if (ConfValIsTrue(conf_val)) { /* pre allocate defrag trackers */ for (i = 0; i < defrag_config.prealloc; i++) { @@ -272,7 +263,7 @@ void DefragInitConfig(bool quiet) SCLogError("preallocating defrag failed: %s", strerror(errno)); exit(EXIT_FAILURE); } - DefragTrackerEnqueue(&defragtracker_spare_q,h); + DefragTrackerEnqueue(&defragtracker_spare_q, h); } if (!quiet) { SCLogConfig("preallocated %" PRIu32 " defrag trackers of size %" PRIuMAX "", @@ -282,7 +273,7 @@ void DefragInitConfig(bool quiet) } if (!quiet) { - SCLogConfig("defrag memory usage: %"PRIu64" bytes, maximum: %"PRIu64, + SCLogConfig("defrag memory usage: %" PRIu64 " bytes, maximum: %" PRIu64, SC_ATOMIC_GET(defrag_memuse), SC_ATOMIC_GET(defrag_config.memcap)); } @@ -291,7 +282,7 @@ void DefragInitConfig(bool quiet) /** \brief print some defrag stats * \warning Not thread safe */ -static void DefragTrackerPrintStats (void) +static void DefragTrackerPrintStats(void) { } @@ -305,7 +296,7 @@ void DefragHashShutdown(void) DefragTrackerPrintStats(); /* free spare queue */ - while((dt = DefragTrackerDequeue(&defragtracker_spare_q))) { + while ((dt = DefragTrackerDequeue(&defragtracker_spare_q))) { BUG_ON(SC_ATOMIC_GET(dt->use_cnt) > 0); DefragTrackerFree(dt); } @@ -326,7 +317,7 @@ void DefragHashShutdown(void) SCFree(defragtracker_hash); defragtracker_hash = NULL; } - (void) SC_ATOMIC_SUB(defrag_memuse, defrag_config.hash_size * sizeof(DefragTrackerHashRow)); + (void)SC_ATOMIC_SUB(defrag_memuse, defrag_config.hash_size * sizeof(DefragTrackerHashRow)); DefragTrackerQueueDestroy(&defragtracker_spare_q); return; } @@ -485,12 +476,12 @@ static DefragTracker *DefragTrackerGetNew(Packet *p) /* If we reached the max memcap, we get a used tracker */ if (!(DEFRAG_CHECK_MEMCAP(sizeof(DefragTracker)))) { /* declare state of emergency */ - //if (!(SC_ATOMIC_GET(defragtracker_flags) & DEFRAG_EMERGENCY)) { + // if (!(SC_ATOMIC_GET(defragtracker_flags) & DEFRAG_EMERGENCY)) { // SC_ATOMIC_OR(defragtracker_flags, DEFRAG_EMERGENCY); - /* under high load, waking up the flow mgr each time leads - * to high cpu usage. Flows are not timed out much faster if - * we check a 1000 times a second. */ + /* under high load, waking up the flow mgr each time leads + * to high cpu usage. Flows are not timed out much faster if + * we check a 1000 times a second. */ // FlowWakeupFlowManagerThread(); //} @@ -517,7 +508,7 @@ static DefragTracker *DefragTrackerGetNew(Packet *p) /* tracker is initialized (recycled) but *unlocked* */ } - (void) SC_ATOMIC_ADD(defragtracker_counter, 1); + (void)SC_ATOMIC_ADD(defragtracker_counter, 1); SCMutexLock(&dt->lock); return dt; } @@ -530,7 +521,7 @@ static DefragTracker *DefragTrackerGetNew(Packet *p) * * returns a *LOCKED* tracker or NULL */ -DefragTracker *DefragGetTrackerFromHash (Packet *p) +DefragTracker *DefragGetTrackerFromHash(Packet *p) { DefragTracker *dt = NULL; @@ -553,7 +544,7 @@ DefragTracker *DefragGetTrackerFromHash (Packet *p) hb->tail = dt; /* got one, now lock, initialize and return */ - DefragTrackerInit(dt,p); + DefragTrackerInit(dt, p); DRLOCK_UNLOCK(hb); return dt; @@ -583,7 +574,7 @@ DefragTracker *DefragGetTrackerFromHash (Packet *p) dt->hprev = pdt; /* initialize and return */ - DefragTrackerInit(dt,p); + DefragTrackerInit(dt, p); DRLOCK_UNLOCK(hb); return dt; @@ -609,7 +600,7 @@ DefragTracker *DefragGetTrackerFromHash (Packet *p) /* found our tracker, lock & return */ SCMutexLock(&dt->lock); - (void) DefragTrackerIncrUsecnt(dt); + (void)DefragTrackerIncrUsecnt(dt); DRLOCK_UNLOCK(hb); return dt; } @@ -618,7 +609,7 @@ DefragTracker *DefragGetTrackerFromHash (Packet *p) /* lock & return */ SCMutexLock(&dt->lock); - (void) DefragTrackerIncrUsecnt(dt); + (void)DefragTrackerIncrUsecnt(dt); DRLOCK_UNLOCK(hb); return dt; } @@ -629,7 +620,7 @@ DefragTracker *DefragGetTrackerFromHash (Packet *p) * * \retval h *LOCKED* tracker or NULL */ -DefragTracker *DefragLookupTrackerFromHash (Packet *p) +DefragTracker *DefragLookupTrackerFromHash(Packet *p) { DefragTracker *dt = NULL; @@ -678,7 +669,7 @@ DefragTracker *DefragLookupTrackerFromHash (Packet *p) /* found our tracker, lock & return */ SCMutexLock(&dt->lock); - (void) DefragTrackerIncrUsecnt(dt); + (void)DefragTrackerIncrUsecnt(dt); DRLOCK_UNLOCK(hb); return dt; } @@ -687,7 +678,7 @@ DefragTracker *DefragLookupTrackerFromHash (Packet *p) /* lock & return */ SCMutexLock(&dt->lock); - (void) DefragTrackerIncrUsecnt(dt); + (void)DefragTrackerIncrUsecnt(dt); DRLOCK_UNLOCK(hb); return dt; } @@ -754,11 +745,9 @@ static DefragTracker *DefragTrackerGetUsedDefragTracker(void) SCMutexUnlock(&dt->lock); - (void) SC_ATOMIC_ADD(defragtracker_prune_idx, (defrag_config.hash_size - cnt)); + (void)SC_ATOMIC_ADD(defragtracker_prune_idx, (defrag_config.hash_size - cnt)); return dt; } return NULL; } - - diff --git a/src/defrag-hash.h b/src/defrag-hash.h index b115b13a91d7..295ef856a5e6 100644 --- a/src/defrag-hash.h +++ b/src/defrag-hash.h @@ -33,27 +33,27 @@ #define DRLOCK_MUTEX #ifdef DRLOCK_SPIN - #ifdef DRLOCK_MUTEX - #error Cannot enable both DRLOCK_SPIN and DRLOCK_MUTEX - #endif +#ifdef DRLOCK_MUTEX +#error Cannot enable both DRLOCK_SPIN and DRLOCK_MUTEX +#endif #endif #ifdef DRLOCK_SPIN - #define DRLOCK_TYPE SCSpinlock - #define DRLOCK_INIT(fb) SCSpinInit(&(fb)->lock, 0) - #define DRLOCK_DESTROY(fb) SCSpinDestroy(&(fb)->lock) - #define DRLOCK_LOCK(fb) SCSpinLock(&(fb)->lock) - #define DRLOCK_TRYLOCK(fb) SCSpinTrylock(&(fb)->lock) - #define DRLOCK_UNLOCK(fb) SCSpinUnlock(&(fb)->lock) +#define DRLOCK_TYPE SCSpinlock +#define DRLOCK_INIT(fb) SCSpinInit(&(fb)->lock, 0) +#define DRLOCK_DESTROY(fb) SCSpinDestroy(&(fb)->lock) +#define DRLOCK_LOCK(fb) SCSpinLock(&(fb)->lock) +#define DRLOCK_TRYLOCK(fb) SCSpinTrylock(&(fb)->lock) +#define DRLOCK_UNLOCK(fb) SCSpinUnlock(&(fb)->lock) #elif defined DRLOCK_MUTEX - #define DRLOCK_TYPE SCMutex - #define DRLOCK_INIT(fb) SCMutexInit(&(fb)->lock, NULL) - #define DRLOCK_DESTROY(fb) SCMutexDestroy(&(fb)->lock) - #define DRLOCK_LOCK(fb) SCMutexLock(&(fb)->lock) - #define DRLOCK_TRYLOCK(fb) SCMutexTrylock(&(fb)->lock) - #define DRLOCK_UNLOCK(fb) SCMutexUnlock(&(fb)->lock) +#define DRLOCK_TYPE SCMutex +#define DRLOCK_INIT(fb) SCMutexInit(&(fb)->lock, NULL) +#define DRLOCK_DESTROY(fb) SCMutexDestroy(&(fb)->lock) +#define DRLOCK_LOCK(fb) SCMutexLock(&(fb)->lock) +#define DRLOCK_TRYLOCK(fb) SCMutexTrylock(&(fb)->lock) +#define DRLOCK_UNLOCK(fb) SCMutexUnlock(&(fb)->lock) #else - #error Enable DRLOCK_SPIN or DRLOCK_MUTEX +#error Enable DRLOCK_SPIN or DRLOCK_MUTEX #endif typedef struct DefragTrackerHashRow_ { @@ -80,19 +80,20 @@ typedef struct DefragConfig_ { * \retval 1 it fits * \retval 0 no fit */ -#define DEFRAG_CHECK_MEMCAP(size) \ - ((((uint64_t)SC_ATOMIC_GET(defrag_memuse) + (uint64_t)(size)) <= SC_ATOMIC_GET(defrag_config.memcap))) +#define DEFRAG_CHECK_MEMCAP(size) \ + ((((uint64_t)SC_ATOMIC_GET(defrag_memuse) + (uint64_t)(size)) <= \ + SC_ATOMIC_GET(defrag_config.memcap))) extern DefragConfig defrag_config; -SC_ATOMIC_EXTERN(uint64_t,defrag_memuse); -SC_ATOMIC_EXTERN(unsigned int,defragtracker_counter); -SC_ATOMIC_EXTERN(unsigned int,defragtracker_prune_idx); +SC_ATOMIC_EXTERN(uint64_t, defrag_memuse); +SC_ATOMIC_EXTERN(unsigned int, defragtracker_counter); +SC_ATOMIC_EXTERN(unsigned int, defragtracker_prune_idx); void DefragInitConfig(bool quiet); void DefragHashShutdown(void); -DefragTracker *DefragLookupTrackerFromHash (Packet *); -DefragTracker *DefragGetTrackerFromHash (Packet *); +DefragTracker *DefragLookupTrackerFromHash(Packet *); +DefragTracker *DefragGetTrackerFromHash(Packet *); void DefragTrackerRelease(DefragTracker *); void DefragTrackerClearMemory(DefragTracker *); void DefragTrackerMoveToSpare(DefragTracker *); @@ -103,4 +104,3 @@ uint64_t DefragTrackerGetMemcap(void); uint64_t DefragTrackerGetMemuse(void); #endif /* __DEFRAG_HASH_H__ */ - diff --git a/src/defrag-queue.c b/src/defrag-queue.c index dccff8871f95..bf520e116314 100644 --- a/src/defrag-queue.c +++ b/src/defrag-queue.c @@ -29,7 +29,7 @@ #include "util-debug.h" #include "util-print.h" -DefragTrackerQueue *DefragTrackerQueueInit (DefragTrackerQueue *q) +DefragTrackerQueue *DefragTrackerQueueInit(DefragTrackerQueue *q) { if (q != NULL) { memset(q, 0, sizeof(DefragTrackerQueue)); @@ -54,7 +54,7 @@ DefragTrackerQueue *DefragTrackerQueueNew(void) * * \param q the tracker queue to destroy */ -void DefragTrackerQueueDestroy (DefragTrackerQueue *q) +void DefragTrackerQueueDestroy(DefragTrackerQueue *q) { DQLOCK_DESTROY(q); } @@ -65,7 +65,7 @@ void DefragTrackerQueueDestroy (DefragTrackerQueue *q) * \param q queue * \param dt tracker */ -void DefragTrackerEnqueue (DefragTrackerQueue *q, DefragTracker *dt) +void DefragTrackerEnqueue(DefragTrackerQueue *q, DefragTracker *dt) { #ifdef DEBUG BUG_ON(q == NULL || dt == NULL); @@ -78,7 +78,7 @@ void DefragTrackerEnqueue (DefragTrackerQueue *q, DefragTracker *dt) dt->lnext = q->top; q->top->lprev = dt; q->top = dt; - /* only tracker */ + /* only tracker */ } else { q->top = dt; q->bot = dt; @@ -98,7 +98,7 @@ void DefragTrackerEnqueue (DefragTrackerQueue *q, DefragTracker *dt) * * \retval dt tracker or NULL if empty list. */ -DefragTracker *DefragTrackerDequeue (DefragTrackerQueue *q) +DefragTracker *DefragTrackerDequeue(DefragTrackerQueue *q) { DQLOCK_LOCK(q); @@ -112,7 +112,7 @@ DefragTracker *DefragTrackerDequeue (DefragTrackerQueue *q) if (q->bot->lprev != NULL) { q->bot = q->bot->lprev; q->bot->lnext = NULL; - /* just the one we remove, so now empty */ + /* just the one we remove, so now empty */ } else { q->top = NULL; q->bot = NULL; @@ -139,4 +139,3 @@ uint32_t DefragTrackerQueueLen(DefragTrackerQueue *q) DQLOCK_UNLOCK(q); return len; } - diff --git a/src/defrag-queue.h b/src/defrag-queue.h index 63a58d078645..dbdda95da742 100644 --- a/src/defrag-queue.h +++ b/src/defrag-queue.h @@ -32,14 +32,13 @@ #define DQLOCK_MUTEX #ifdef DQLOCK_SPIN - #ifdef DQLOCK_MUTEX - #error Cannot enable both DQLOCK_SPIN and DQLOCK_MUTEX - #endif +#ifdef DQLOCK_MUTEX +#error Cannot enable both DQLOCK_SPIN and DQLOCK_MUTEX +#endif #endif /* Define a queue for storing defrag trackers */ -typedef struct DefragTrackerQueue_ -{ +typedef struct DefragTrackerQueue_ { DefragTracker *top; DefragTracker *bot; uint32_t len; @@ -51,34 +50,33 @@ typedef struct DefragTrackerQueue_ #elif defined DQLOCK_SPIN SCSpinlock s; #else - #error Enable DQLOCK_SPIN or DQLOCK_MUTEX +#error Enable DQLOCK_SPIN or DQLOCK_MUTEX #endif } DefragTrackerQueue; #ifdef DQLOCK_SPIN - #define DQLOCK_INIT(q) SCSpinInit(&(q)->s, 0) - #define DQLOCK_DESTROY(q) SCSpinDestroy(&(q)->s) - #define DQLOCK_LOCK(q) SCSpinLock(&(q)->s) - #define DQLOCK_TRYLOCK(q) SCSpinTrylock(&(q)->s) - #define DQLOCK_UNLOCK(q) SCSpinUnlock(&(q)->s) +#define DQLOCK_INIT(q) SCSpinInit(&(q)->s, 0) +#define DQLOCK_DESTROY(q) SCSpinDestroy(&(q)->s) +#define DQLOCK_LOCK(q) SCSpinLock(&(q)->s) +#define DQLOCK_TRYLOCK(q) SCSpinTrylock(&(q)->s) +#define DQLOCK_UNLOCK(q) SCSpinUnlock(&(q)->s) #elif defined DQLOCK_MUTEX - #define DQLOCK_INIT(q) SCMutexInit(&(q)->m, NULL) - #define DQLOCK_DESTROY(q) SCMutexDestroy(&(q)->m) - #define DQLOCK_LOCK(q) SCMutexLock(&(q)->m) - #define DQLOCK_TRYLOCK(q) SCMutexTrylock(&(q)->m) - #define DQLOCK_UNLOCK(q) SCMutexUnlock(&(q)->m) +#define DQLOCK_INIT(q) SCMutexInit(&(q)->m, NULL) +#define DQLOCK_DESTROY(q) SCMutexDestroy(&(q)->m) +#define DQLOCK_LOCK(q) SCMutexLock(&(q)->m) +#define DQLOCK_TRYLOCK(q) SCMutexTrylock(&(q)->m) +#define DQLOCK_UNLOCK(q) SCMutexUnlock(&(q)->m) #else - #error Enable DQLOCK_SPIN or DQLOCK_MUTEX +#error Enable DQLOCK_SPIN or DQLOCK_MUTEX #endif /* prototypes */ DefragTrackerQueue *DefragTrackerQueueNew(void); DefragTrackerQueue *DefragTrackerQueueInit(DefragTrackerQueue *); -void DefragTrackerQueueDestroy (DefragTrackerQueue *); +void DefragTrackerQueueDestroy(DefragTrackerQueue *); -void DefragTrackerEnqueue (DefragTrackerQueue *, DefragTracker *); -DefragTracker *DefragTrackerDequeue (DefragTrackerQueue *); +void DefragTrackerEnqueue(DefragTrackerQueue *, DefragTracker *); +DefragTracker *DefragTrackerDequeue(DefragTrackerQueue *); uint32_t DefragTrackerQueueLen(DefragTrackerQueue *); #endif /* __DEFRAG_QUEUE_H__ */ - diff --git a/src/defrag-timeout.c b/src/defrag-timeout.c index 2d7c96f028cc..4699eea92927 100644 --- a/src/defrag-timeout.c +++ b/src/defrag-timeout.c @@ -143,4 +143,3 @@ uint32_t DefragTimeoutHash(SCTime_t ts) return cnt; } - diff --git a/src/defrag-timeout.h b/src/defrag-timeout.h index baece4516e87..a6b36a33bd72 100644 --- a/src/defrag-timeout.h +++ b/src/defrag-timeout.h @@ -27,4 +27,3 @@ uint32_t DefragTimeoutHash(SCTime_t ts); #endif - diff --git a/src/defrag.c b/src/defrag.c index 71cf4204c17a..313fe299a803 100644 --- a/src/defrag.c +++ b/src/defrag.c @@ -126,8 +126,7 @@ DumpFrags(DefragTracker *tracker) /** * \brief Reset a frag for reuse in a pool. */ -static void -DefragFragReset(Frag *frag) +static void DefragFragReset(Frag *frag) { if (frag->pkt != NULL) SCFree(frag->pkt); @@ -137,8 +136,7 @@ DefragFragReset(Frag *frag) /** * \brief Allocate a new frag for use in a pool. */ -static int -DefragFragInit(void *data, void *initdata) +static int DefragFragInit(void *data, void *initdata) { Frag *frag = data; @@ -149,15 +147,14 @@ DefragFragInit(void *data, void *initdata) /** * \brief Free all frags associated with a tracker. */ -void -DefragTrackerFreeFrags(DefragTracker *tracker) +void DefragTrackerFreeFrags(DefragTracker *tracker) { Frag *frag, *tmp; /* Lock the frag pool as we'll be return items to it. */ SCMutexLock(&defrag_context->frag_pool_lock); - RB_FOREACH_SAFE(frag, IP_FRAGMENTS, &tracker->fragment_tree, tmp) { + RB_FOREACH_SAFE (frag, IP_FRAGMENTS, &tracker->fragment_tree, tmp) { RB_REMOVE(IP_FRAGMENTS, &tracker->fragment_tree, frag); DefragFragReset(frag); PoolReturn(defrag_context->frag_pool, frag); @@ -172,8 +169,7 @@ DefragTrackerFreeFrags(DefragTracker *tracker) * \retval On success a return an initialized DefragContext, otherwise * NULL will be returned. */ -static DefragContext * -DefragContextNew(void) +static DefragContext *DefragContextNew(void) { DefragContext *dc; @@ -193,9 +189,8 @@ DefragContextNew(void) frag_pool_size = DEFAULT_DEFRAG_POOL_SIZE; } intmax_t frag_pool_prealloc = frag_pool_size / 2; - dc->frag_pool = PoolInit(frag_pool_size, frag_pool_prealloc, - sizeof(Frag), - NULL, DefragFragInit, dc, NULL, NULL); + dc->frag_pool = PoolInit( + frag_pool_size, frag_pool_prealloc, sizeof(Frag), NULL, DefragFragInit, dc, NULL, NULL); if (dc->frag_pool == NULL) { FatalError("Defrag: Failed to initialize fragment pool."); } @@ -207,29 +202,26 @@ DefragContextNew(void) intmax_t timeout; if (!ConfGetInt("defrag.timeout", &timeout)) { dc->timeout = TIMEOUT_DEFAULT; - } - else { + } else { if (timeout < TIMEOUT_MIN) { FatalError("defrag: Timeout less than minimum allowed value."); - } - else if (timeout > TIMEOUT_MAX) { + } else if (timeout > TIMEOUT_MAX) { FatalError("defrag: Timeout greater than maximum allowed value."); } dc->timeout = timeout; } SCLogDebug("Defrag Initialized:"); - SCLogDebug("\tTimeout: %"PRIuMAX, (uintmax_t)dc->timeout); - SCLogDebug("\tMaximum defrag trackers: %"PRIuMAX, tracker_pool_size); - SCLogDebug("\tPreallocated defrag trackers: %"PRIuMAX, tracker_pool_size); - SCLogDebug("\tMaximum fragments: %"PRIuMAX, (uintmax_t)frag_pool_size); - SCLogDebug("\tPreallocated fragments: %"PRIuMAX, (uintmax_t)frag_pool_prealloc); + SCLogDebug("\tTimeout: %" PRIuMAX, (uintmax_t)dc->timeout); + SCLogDebug("\tMaximum defrag trackers: %" PRIuMAX, tracker_pool_size); + SCLogDebug("\tPreallocated defrag trackers: %" PRIuMAX, tracker_pool_size); + SCLogDebug("\tMaximum fragments: %" PRIuMAX, (uintmax_t)frag_pool_size); + SCLogDebug("\tPreallocated fragments: %" PRIuMAX, (uintmax_t)frag_pool_prealloc); return dc; } -static void -DefragContextDestroy(DefragContext *dc) +static void DefragContextDestroy(DefragContext *dc) { if (dc == NULL) return; @@ -243,8 +235,7 @@ DefragContextDestroy(DefragContext *dc) * * \param tracker The defragmentation tracker to reassemble from. */ -static Packet * -Defrag4Reassemble(ThreadVars *tv, DefragTracker *tracker, Packet *p) +static Packet *Defrag4Reassemble(ThreadVars *tv, DefragTracker *tracker, Packet *p) { Packet *rp = NULL; @@ -269,13 +260,12 @@ Defrag4Reassemble(ThreadVars *tv, DefragTracker *tracker, Packet *p) * fragments are inserted if frag_offset order. */ Frag *frag = NULL; size_t len = 0; - RB_FOREACH_FROM(frag, IP_FRAGMENTS, first) { + RB_FOREACH_FROM (frag, IP_FRAGMENTS, first) { if (frag->offset > len) { /* This fragment starts after the end of the previous * fragment. We have a hole. */ goto done; - } - else { + } else { len += frag->data_len; } } @@ -295,9 +285,10 @@ Defrag4Reassemble(ThreadVars *tv, DefragTracker *tracker, Packet *p) uint16_t hlen = 0; int ip_hdr_offset = 0; - RB_FOREACH(frag, IP_FRAGMENTS, &tracker->fragment_tree) { - SCLogDebug("frag %p, data_len %u, offset %u, pcap_cnt %"PRIu64, - frag, frag->data_len, frag->offset, frag->pcap_cnt); + RB_FOREACH(frag, IP_FRAGMENTS, &tracker->fragment_tree) + { + SCLogDebug("frag %p, data_len %u, offset %u, pcap_cnt %" PRIu64, frag, frag->data_len, + frag->offset, frag->pcap_cnt); if (frag->skip) continue; @@ -316,18 +307,16 @@ Defrag4Reassemble(ThreadVars *tv, DefragTracker *tracker, Packet *p) * this. */ fragmentable_offset = frag->ip_hdr_offset + frag->hlen; fragmentable_len = frag->data_len; - } - else { + } else { int pkt_end = fragmentable_offset + frag->offset + frag->data_len; if (pkt_end > (int)MAX_PAYLOAD_SIZE) { SCLogDebug("Failed re-assemble " "fragmented packet, exceeds size of packet buffer."); goto error_remove_tracker; } - if (PacketCopyDataOffset(rp, - fragmentable_offset + frag->offset + frag->ltrim, - frag->pkt + frag->data_offset + frag->ltrim, - frag->data_len - frag->ltrim) == -1) { + if (PacketCopyDataOffset(rp, fragmentable_offset + frag->offset + frag->ltrim, + frag->pkt + frag->data_offset + frag->ltrim, + frag->data_len - frag->ltrim) == -1) { goto error_remove_tracker; } if (frag->offset > UINT16_MAX - frag->data_len) { @@ -352,8 +341,7 @@ Defrag4Reassemble(ThreadVars *tv, DefragTracker *tracker, Packet *p) DEBUG_VALIDATE_BUG_ON(hlen > UINT16_MAX - fragmentable_len); rp->ip4h->ip_len = htons(fragmentable_len + hlen); rp->ip4h->ip_off = 0; - rp->ip4h->ip_csum = FixChecksum(rp->ip4h->ip_csum, - old, rp->ip4h->ip_len + rp->ip4h->ip_off); + rp->ip4h->ip_csum = FixChecksum(rp->ip4h->ip_csum, old, rp->ip4h->ip_len + rp->ip4h->ip_off); SET_PKT_LEN(rp, ip_hdr_offset + hlen + fragmentable_len); tracker->remove = 1; @@ -374,8 +362,7 @@ Defrag4Reassemble(ThreadVars *tv, DefragTracker *tracker, Packet *p) * * \param tracker The defragmentation tracker to reassemble from. */ -static Packet * -Defrag6Reassemble(ThreadVars *tv, DefragTracker *tracker, Packet *p) +static Packet *Defrag6Reassemble(ThreadVars *tv, DefragTracker *tracker, Packet *p) { Packet *rp = NULL; @@ -399,7 +386,7 @@ Defrag6Reassemble(ThreadVars *tv, DefragTracker *tracker, Packet *p) * fragments are inserted if frag_offset order. */ size_t len = 0; Frag *frag = NULL; - RB_FOREACH_FROM(frag, IP_FRAGMENTS, first) { + RB_FOREACH_FROM (frag, IP_FRAGMENTS, first) { if (frag->skip) { continue; } @@ -409,14 +396,12 @@ Defrag6Reassemble(ThreadVars *tv, DefragTracker *tracker, Packet *p) goto done; } len = frag->data_len; - } - else { + } else { if (frag->offset > len) { /* This fragment starts after the end of the previous * fragment. We have a hole. */ goto done; - } - else { + } else { len += frag->data_len; } } @@ -424,8 +409,7 @@ Defrag6Reassemble(ThreadVars *tv, DefragTracker *tracker, Packet *p) /* Allocate a Packet for the reassembled packet. On failure we * SCFree all the resources held by this tracker. */ - rp = PacketDefragPktSetup(p, (uint8_t *)p->ip6h, - IPV6_GET_PLEN(p) + sizeof(IPV6Hdr), 0); + rp = PacketDefragPktSetup(p, (uint8_t *)p->ip6h, IPV6_GET_PLEN(p) + sizeof(IPV6Hdr), 0); if (rp == NULL) { goto error_remove_tracker; } @@ -436,14 +420,14 @@ Defrag6Reassemble(ThreadVars *tv, DefragTracker *tracker, Packet *p) uint16_t fragmentable_len = 0; int ip_hdr_offset = 0; uint8_t next_hdr = 0; - RB_FOREACH(frag, IP_FRAGMENTS, &tracker->fragment_tree) { + RB_FOREACH(frag, IP_FRAGMENTS, &tracker->fragment_tree) + { if (frag->skip) continue; if (frag->data_len - frag->ltrim <= 0) continue; if (frag->offset == 0) { - IPV6FragHdr *frag_hdr = (IPV6FragHdr *)(frag->pkt + - frag->frag_hdr_offset); + IPV6FragHdr *frag_hdr = (IPV6FragHdr *)(frag->pkt + frag->frag_hdr_offset); next_hdr = frag_hdr->ip6fh_nxt; /* This is the first packet, we use this packets link and @@ -452,8 +436,8 @@ Defrag6Reassemble(ThreadVars *tv, DefragTracker *tracker, Packet *p) if (PacketCopyData(rp, frag->pkt, frag->frag_hdr_offset) == -1) goto error_remove_tracker; if (PacketCopyDataOffset(rp, frag->frag_hdr_offset, - frag->pkt + frag->frag_hdr_offset + sizeof(IPV6FragHdr), - frag->data_len) == -1) + frag->pkt + frag->frag_hdr_offset + sizeof(IPV6FragHdr), + frag->data_len) == -1) goto error_remove_tracker; ip_hdr_offset = frag->ip_hdr_offset; @@ -471,11 +455,10 @@ Defrag6Reassemble(ThreadVars *tv, DefragTracker *tracker, Packet *p) unfragmentable_len = (uint16_t)(fragmentable_offset - ip_hdr_offset - IPV6_HEADER_LEN); if (unfragmentable_len >= fragmentable_offset) goto error_remove_tracker; - } - else { + } else { if (PacketCopyDataOffset(rp, fragmentable_offset + frag->offset + frag->ltrim, - frag->pkt + frag->data_offset + frag->ltrim, - frag->data_len - frag->ltrim) == -1) + frag->pkt + frag->data_offset + frag->ltrim, + frag->data_len - frag->ltrim) == -1) goto error_remove_tracker; if (frag->offset + frag->data_len > fragmentable_len) fragmentable_len = frag->offset + frag->data_len; @@ -495,8 +478,7 @@ Defrag6Reassemble(ThreadVars *tv, DefragTracker *tracker, Packet *p) * directly after the frag header. */ if (unfragmentable_len == 0) rp->ip6h->s_ip6_nxt = next_hdr; - SET_PKT_LEN(rp, ip_hdr_offset + sizeof(IPV6Hdr) + - unfragmentable_len + fragmentable_len); + SET_PKT_LEN(rp, ip_hdr_offset + sizeof(IPV6Hdr) + unfragmentable_len + fragmentable_len); tracker->remove = 1; DefragTrackerFreeFrags(tracker); @@ -518,7 +500,8 @@ Defrag6Reassemble(ThreadVars *tv, DefragTracker *tracker, Packet *p) * same offset to be treated as greater than, so we don't have an * equal return value here. */ -int DefragRbFragCompare(struct Frag_ *a, struct Frag_ *b) { +int DefragRbFragCompare(struct Frag_ *a, struct Frag_ *b) +{ if (a->offset < b->offset) { return -1; } @@ -530,8 +513,8 @@ int DefragRbFragCompare(struct Frag_ *a, struct Frag_ *b) { * * \todo Allocate packet buffers from a pool. */ -static Packet * -DefragInsertFrag(ThreadVars *tv, DecodeThreadVars *dtv, DefragTracker *tracker, Packet *p) +static Packet *DefragInsertFrag( + ThreadVars *tv, DecodeThreadVars *dtv, DefragTracker *tracker, Packet *p) { Packet *r = NULL; uint16_t ltrim = 0; @@ -586,8 +569,7 @@ DefragInsertFrag(ThreadVars *tv, DecodeThreadVars *dtv, DefragTracker *tracker, ENGINE_SET_EVENT(p, IPV4_FRAG_PKT_TOO_LARGE); return NULL; } - } - else if (tracker->af == AF_INET6) { + } else if (tracker->af == AF_INET6) { more_frags = IPV6_EXTHDR_GET_FH_FLAG(p); frag_offset = IPV6_EXTHDR_GET_FH_OFFSET(p); data_offset = p->ip6eh.fh_data_offset; @@ -597,9 +579,9 @@ DefragInsertFrag(ThreadVars *tv, DecodeThreadVars *dtv, DefragTracker *tracker, frag_hdr_offset = p->ip6eh.fh_header_offset; SCLogDebug("mf %s frag_offset %u data_offset %u, data_len %u, " - "frag_end %u, ip_hdr_offset %u, frag_hdr_offset %u", - more_frags ? "true" : "false", frag_offset, data_offset, - data_len, frag_end, ip_hdr_offset, frag_hdr_offset); + "frag_end %u, ip_hdr_offset %u, frag_hdr_offset %u", + more_frags ? "true" : "false", frag_offset, data_offset, data_len, frag_end, + ip_hdr_offset, frag_hdr_offset); /* handle unfragmentable exthdrs */ if (ip_hdr_offset + IPV6_HEADER_LEN < frag_hdr_offset) { @@ -621,8 +603,7 @@ DefragInsertFrag(ThreadVars *tv, DecodeThreadVars *dtv, DefragTracker *tracker, ENGINE_SET_EVENT(p, IPV6_FRAG_PKT_TOO_LARGE); return NULL; } - } - else { + } else { DEBUG_VALIDATE_BUG_ON(1); return NULL; } @@ -658,132 +639,132 @@ DefragInsertFrag(ThreadVars *tv, DecodeThreadVars *dtv, DefragTracker *tracker, } switch (tracker->policy) { - case DEFRAG_POLICY_BSD: - if (frag_offset < prev->offset + prev->data_len) { - if (frag_offset >= prev->offset) { - ltrim = prev->offset + prev->data_len - frag_offset; + case DEFRAG_POLICY_BSD: + if (frag_offset < prev->offset + prev->data_len) { + if (frag_offset >= prev->offset) { + ltrim = prev->offset + prev->data_len - frag_offset; + } + if ((next != NULL) && (frag_end > next->offset)) { + next->ltrim = frag_end - next->offset; + } + if ((frag_offset < prev->offset) && + (frag_end >= prev->offset + prev->data_len)) { + prev->skip = 1; + } + goto insert; } - if ((next != NULL) && (frag_end > next->offset)) { - next->ltrim = frag_end - next->offset; + break; + case DEFRAG_POLICY_LINUX: + /* Check if new fragment overlaps the end of previous + * fragment, if it does, trim the new fragment. + * + * Old: AAAAAAAA AAAAAAAA AAAAAAAA + * New: BBBBBBBB BBBBBBBB BBBBBBBB + * Res: AAAAAAAA AAAAAAAA AAAAAAAA BBBBBBBB + */ + if (prev->offset + prev->ltrim < frag_offset + ltrim && + prev->offset + prev->data_len > frag_offset + ltrim) { + ltrim += prev->offset + prev->data_len - frag_offset; } - if ((frag_offset < prev->offset) && - (frag_end >= prev->offset + prev->data_len)) { - prev->skip = 1; - } - goto insert; - } - break; - case DEFRAG_POLICY_LINUX: - /* Check if new fragment overlaps the end of previous - * fragment, if it does, trim the new fragment. - * - * Old: AAAAAAAA AAAAAAAA AAAAAAAA - * New: BBBBBBBB BBBBBBBB BBBBBBBB - * Res: AAAAAAAA AAAAAAAA AAAAAAAA BBBBBBBB - */ - if (prev->offset + prev->ltrim < frag_offset + ltrim && - prev->offset + prev->data_len > frag_offset + ltrim) { - ltrim += prev->offset + prev->data_len - frag_offset; - } - /* Check if new fragment overlaps the beginning of - * previous fragment, if it does, tim the previous - * fragment. - * - * Old: AAAAAAAA AAAAAAAA - * New: BBBBBBBB BBBBBBBB BBBBBBBB - * Res: BBBBBBBB BBBBBBBB BBBBBBBB - */ - if (frag_offset + ltrim < prev->offset + prev->ltrim && - frag_end > prev->offset + prev->ltrim) { - prev->ltrim += frag_end - (prev->offset + prev->ltrim); - goto insert; - } + /* Check if new fragment overlaps the beginning of + * previous fragment, if it does, tim the previous + * fragment. + * + * Old: AAAAAAAA AAAAAAAA + * New: BBBBBBBB BBBBBBBB BBBBBBBB + * Res: BBBBBBBB BBBBBBBB BBBBBBBB + */ + if (frag_offset + ltrim < prev->offset + prev->ltrim && + frag_end > prev->offset + prev->ltrim) { + prev->ltrim += frag_end - (prev->offset + prev->ltrim); + goto insert; + } - /* If the new fragment completely overlaps the - * previous fragment, mark the previous to be - * skipped. Re-assembly would succeed without doing - * this, but this will prevent the bytes from being - * copied just to be overwritten. */ - if (frag_offset + ltrim <= prev->offset + prev->ltrim && - frag_end >= prev->offset + prev->data_len) { - prev->skip = 1; - goto insert; - } + /* If the new fragment completely overlaps the + * previous fragment, mark the previous to be + * skipped. Re-assembly would succeed without doing + * this, but this will prevent the bytes from being + * copied just to be overwritten. */ + if (frag_offset + ltrim <= prev->offset + prev->ltrim && + frag_end >= prev->offset + prev->data_len) { + prev->skip = 1; + goto insert; + } - break; - case DEFRAG_POLICY_WINDOWS: - /* If new fragment fits inside a previous fragment, drop it. */ - if (frag_offset + ltrim >= prev->offset + ltrim && - frag_end <= prev->offset + prev->data_len) { - goto done; - } + break; + case DEFRAG_POLICY_WINDOWS: + /* If new fragment fits inside a previous fragment, drop it. */ + if (frag_offset + ltrim >= prev->offset + ltrim && + frag_end <= prev->offset + prev->data_len) { + goto done; + } - /* If new fragment starts before and ends after - * previous fragment, drop the previous fragment. */ - if (frag_offset + ltrim < prev->offset + ltrim && - frag_end > prev->offset + prev->data_len) { - prev->skip = 1; - goto insert; - } + /* If new fragment starts before and ends after + * previous fragment, drop the previous fragment. */ + if (frag_offset + ltrim < prev->offset + ltrim && + frag_end > prev->offset + prev->data_len) { + prev->skip = 1; + goto insert; + } - /* Check if new fragment overlaps the end of previous - * fragment, if it does, trim the new fragment. - * - * Old: AAAAAAAA AAAAAAAA AAAAAAAA - * New: BBBBBBBB BBBBBBBB BBBBBBBB - * Res: AAAAAAAA AAAAAAAA AAAAAAAA BBBBBBBB - */ - if (frag_offset + ltrim > prev->offset + prev->ltrim && - frag_offset + ltrim < prev->offset + prev->data_len) { - ltrim += prev->offset + prev->data_len - frag_offset; - goto insert; - } + /* Check if new fragment overlaps the end of previous + * fragment, if it does, trim the new fragment. + * + * Old: AAAAAAAA AAAAAAAA AAAAAAAA + * New: BBBBBBBB BBBBBBBB BBBBBBBB + * Res: AAAAAAAA AAAAAAAA AAAAAAAA BBBBBBBB + */ + if (frag_offset + ltrim > prev->offset + prev->ltrim && + frag_offset + ltrim < prev->offset + prev->data_len) { + ltrim += prev->offset + prev->data_len - frag_offset; + goto insert; + } - /* If new fragment starts at same offset as an - * existing fragment, but ends after it, trim the new - * fragment. */ - if (frag_offset + ltrim == prev->offset + ltrim && - frag_end > prev->offset + prev->data_len) { - ltrim += prev->offset + prev->data_len - frag_offset; - goto insert; - } - break; - case DEFRAG_POLICY_SOLARIS: - if (frag_offset < prev->offset + prev->data_len) { - if (frag_offset >= prev->offset) { - ltrim = prev->offset + prev->data_len - frag_offset; + /* If new fragment starts at same offset as an + * existing fragment, but ends after it, trim the new + * fragment. */ + if (frag_offset + ltrim == prev->offset + ltrim && + frag_end > prev->offset + prev->data_len) { + ltrim += prev->offset + prev->data_len - frag_offset; + goto insert; } - if ((frag_offset < prev->offset) && - (frag_end >= prev->offset + prev->data_len)) { - prev->skip = 1; + break; + case DEFRAG_POLICY_SOLARIS: + if (frag_offset < prev->offset + prev->data_len) { + if (frag_offset >= prev->offset) { + ltrim = prev->offset + prev->data_len - frag_offset; + } + if ((frag_offset < prev->offset) && + (frag_end >= prev->offset + prev->data_len)) { + prev->skip = 1; + } + goto insert; } - goto insert; - } - break; - case DEFRAG_POLICY_FIRST: - if ((frag_offset >= prev->offset) && - (frag_end <= prev->offset + prev->data_len)) { - goto done; - } - if (frag_offset < prev->offset) { - goto insert; - } - if (frag_offset < prev->offset + prev->data_len) { - ltrim = prev->offset + prev->data_len - frag_offset; - goto insert; - } - break; - case DEFRAG_POLICY_LAST: - if (frag_offset <= prev->offset) { - if (frag_end > prev->offset) { - prev->ltrim = frag_end - prev->offset; + break; + case DEFRAG_POLICY_FIRST: + if ((frag_offset >= prev->offset) && + (frag_end <= prev->offset + prev->data_len)) { + goto done; } - goto insert; - } - break; - default: - break; + if (frag_offset < prev->offset) { + goto insert; + } + if (frag_offset < prev->offset + prev->data_len) { + ltrim = prev->offset + prev->data_len - frag_offset; + goto insert; + } + break; + case DEFRAG_POLICY_LAST: + if (frag_offset <= prev->offset) { + if (frag_end > prev->offset) { + prev->ltrim = frag_end - prev->offset; + } + goto insert; + } + break; + default: + break; } next: @@ -873,8 +854,7 @@ DefragInsertFrag(ThreadVars *tv, DecodeThreadVars *dtv, DefragTracker *tracker, r = Defrag4Reassemble(tv, tracker, p); if (r != NULL && tv != NULL && dtv != NULL) { StatsIncr(tv, dtv->counter_defrag_ipv4_reassembled); - if (DecodeIPV4(tv, dtv, r, (void *)r->ip4h, - IPV4_GET_IPLEN(r)) != TM_ECODE_OK) { + if (DecodeIPV4(tv, dtv, r, (void *)r->ip4h, IPV4_GET_IPLEN(r)) != TM_ECODE_OK) { UNSET_TUNNEL_PKT(r); r->root = NULL; @@ -884,14 +864,12 @@ DefragInsertFrag(ThreadVars *tv, DecodeThreadVars *dtv, DefragTracker *tracker, PacketDefragPktSetupParent(p); } } - } - else if (tracker->af == AF_INET6) { + } else if (tracker->af == AF_INET6) { r = Defrag6Reassemble(tv, tracker, p); if (r != NULL && tv != NULL && dtv != NULL) { StatsIncr(tv, dtv->counter_defrag_ipv6_reassembled); if (DecodeIPV6(tv, dtv, r, (uint8_t *)r->ip6h, - IPV6_GET_PLEN(r) + IPV6_HEADER_LEN) - != TM_ECODE_OK) { + IPV6_GET_PLEN(r) + IPV6_HEADER_LEN) != TM_ECODE_OK) { UNSET_TUNNEL_PKT(r); r->root = NULL; @@ -904,13 +882,11 @@ DefragInsertFrag(ThreadVars *tv, DecodeThreadVars *dtv, DefragTracker *tracker, } } - done: if (overlap) { if (af == AF_INET) { ENGINE_SET_EVENT(p, IPV4_FRAG_OVERLAP); - } - else { + } else { ENGINE_SET_EVENT(p, IPV6_FRAG_OVERLAP); } } @@ -925,15 +901,13 @@ DefragInsertFrag(ThreadVars *tv, DecodeThreadVars *dtv, DefragTracker *tracker, * * \retval The defrag policy to use. */ -uint8_t -DefragGetOsPolicy(Packet *p) +uint8_t DefragGetOsPolicy(Packet *p) { int policy = -1; if (PKT_IS_IPV4(p)) { policy = SCHInfoGetIPv4HostOSFlavour((uint8_t *)GET_IPV4_DST_ADDR_PTR(p)); - } - else if (PKT_IS_IPV6(p)) { + } else if (PKT_IS_IPV6(p)) { policy = SCHInfoGetIPv6HostOSFlavour((uint8_t *)GET_IPV6_DST_ADDR(p)); } @@ -944,52 +918,51 @@ DefragGetOsPolicy(Packet *p) /* Map the OS policies returned from the configured host info to * defrag specific policies. */ switch (policy) { - /* BSD. */ - case OS_POLICY_BSD: - case OS_POLICY_HPUX10: - case OS_POLICY_IRIX: - return DEFRAG_POLICY_BSD; - - /* BSD-Right. */ - case OS_POLICY_BSD_RIGHT: - return DEFRAG_POLICY_BSD_RIGHT; - - /* Linux. */ - case OS_POLICY_OLD_LINUX: - case OS_POLICY_LINUX: - return DEFRAG_POLICY_LINUX; - - /* First. */ - case OS_POLICY_OLD_SOLARIS: - case OS_POLICY_HPUX11: - case OS_POLICY_MACOS: - case OS_POLICY_FIRST: - return DEFRAG_POLICY_FIRST; - - /* Solaris. */ - case OS_POLICY_SOLARIS: - return DEFRAG_POLICY_SOLARIS; - - /* Windows. */ - case OS_POLICY_WINDOWS: - case OS_POLICY_VISTA: - case OS_POLICY_WINDOWS2K3: - return DEFRAG_POLICY_WINDOWS; - - /* Last. */ - case OS_POLICY_LAST: - return DEFRAG_POLICY_LAST; - - default: - return default_policy; + /* BSD. */ + case OS_POLICY_BSD: + case OS_POLICY_HPUX10: + case OS_POLICY_IRIX: + return DEFRAG_POLICY_BSD; + + /* BSD-Right. */ + case OS_POLICY_BSD_RIGHT: + return DEFRAG_POLICY_BSD_RIGHT; + + /* Linux. */ + case OS_POLICY_OLD_LINUX: + case OS_POLICY_LINUX: + return DEFRAG_POLICY_LINUX; + + /* First. */ + case OS_POLICY_OLD_SOLARIS: + case OS_POLICY_HPUX11: + case OS_POLICY_MACOS: + case OS_POLICY_FIRST: + return DEFRAG_POLICY_FIRST; + + /* Solaris. */ + case OS_POLICY_SOLARIS: + return DEFRAG_POLICY_SOLARIS; + + /* Windows. */ + case OS_POLICY_WINDOWS: + case OS_POLICY_VISTA: + case OS_POLICY_WINDOWS2K3: + return DEFRAG_POLICY_WINDOWS; + + /* Last. */ + case OS_POLICY_LAST: + return DEFRAG_POLICY_LAST; + + default: + return default_policy; } } /** \internal * * \retval NULL or a *LOCKED* tracker */ -static DefragTracker * -DefragGetTracker(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p) +static DefragTracker *DefragGetTracker(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p) { return DefragGetTrackerFromHash(p); } @@ -1004,8 +977,7 @@ DefragGetTracker(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p) * recent fragment allowed the packet to be re-assembled, otherwise * NULL is returned. */ -Packet * -Defrag(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p) +Packet *Defrag(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p) { uint16_t frag_offset; uint8_t more_frags; @@ -1016,13 +988,11 @@ Defrag(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p) af = AF_INET; more_frags = IPV4_GET_MF(p); frag_offset = IPV4_GET_IPOFFSET(p); - } - else if (PKT_IS_IPV6(p)) { + } else if (PKT_IS_IPV6(p)) { af = AF_INET6; frag_offset = IPV6_EXTHDR_GET_FH_OFFSET(p); more_frags = IPV6_EXTHDR_GET_FH_FLAG(p); - } - else { + } else { return NULL; } @@ -1033,8 +1003,7 @@ Defrag(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p) if (tv != NULL && dtv != NULL) { if (af == AF_INET) { StatsIncr(tv, dtv->counter_defrag_ipv4_fragments); - } - else if (af == AF_INET6) { + } else if (af == AF_INET6) { StatsIncr(tv, dtv->counter_defrag_ipv6_fragments); } } @@ -1054,8 +1023,7 @@ Defrag(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p) return rp; } -void -DefragInit(void) +void DefragInit(void) { intmax_t tracker_pool_size; if (!ConfGetInt("defrag.trackers", &tracker_pool_size)) { @@ -1093,8 +1061,8 @@ void DefragDestroy(void) * Allocate a test packet. Nothing to fancy, just a simple IP packet * with some payload of no particular protocol. */ -static Packet *BuildTestPacket(uint8_t proto, uint16_t id, uint16_t off, int mf, - const char content, int content_len) +static Packet *BuildTestPacket( + uint8_t proto, uint16_t id, uint16_t off, int mf, const char content, int content_len) { Packet *p = NULL; int hlen = 20; @@ -1111,7 +1079,7 @@ static Packet *BuildTestPacket(uint8_t proto, uint16_t id, uint16_t off, int mf, struct timeval tval; gettimeofday(&tval, NULL); p->ts = SCTIME_FROM_TIMEVAL(&tval); - //p->ip4h = (IPV4Hdr *)GET_PKT_DATA(p); + // p->ip4h = (IPV4Hdr *)GET_PKT_DATA(p); ip4h.ip_verhl = 4 << 4; ip4h.ip_verhl |= hlen >> 2; ip4h.ip_len = htons(hlen + content_len); @@ -1167,8 +1135,8 @@ static Packet *BuildTestPacket(uint8_t proto, uint16_t id, uint16_t off, int mf, return NULL; } -static Packet *IPV6BuildTestPacket(uint8_t proto, uint32_t id, uint16_t off, - int mf, const char content, int content_len) +static Packet *IPV6BuildTestPacket( + uint8_t proto, uint32_t id, uint16_t off, int mf, const char content, int content_len) { Packet *p = NULL; uint8_t *pcontent; @@ -1444,8 +1412,7 @@ static int IPV6DefragReverseSimpleTest(void) PASS; } -static int DefragDoSturgesNovakTest(int policy, u_char *expected, - size_t expected_len) +static int DefragDoSturgesNovakTest(int policy, u_char *expected, size_t expected_len) { int i; @@ -1556,8 +1523,7 @@ static int DefragDoSturgesNovakTest(int policy, u_char *expected, PASS; } -static int IPV6DefragDoSturgesNovakTest(int policy, u_char *expected, - size_t expected_len) +static int IPV6DefragDoSturgesNovakTest(int policy, u_char *expected, size_t expected_len) { int i; @@ -1667,424 +1633,386 @@ static int IPV6DefragDoSturgesNovakTest(int policy, u_char *expected, PASS; } -static int -DefragSturgesNovakBsdTest(void) +static int DefragSturgesNovakBsdTest(void) { /* Expected data. */ - u_char expected[] = { - "AAAAAAAA" - "AAAAAAAA" - "AAAAAAAA" - "JJJJJJJJ" - "JJJJJJJJ" - "BBBBBBBB" - "CCCCCCCC" - "CCCCCCCC" - "CCCCCCCC" - "LLLLLLLL" - "LLLLLLLL" - "LLLLLLLL" - "MMMMMMMM" - "MMMMMMMM" - "MMMMMMMM" - "FFFFFFFF" - "FFFFFFFF" - "FFFFFFFF" - "GGGGGGGG" - "GGGGGGGG" - "HHHHHHHH" - "HHHHHHHH" - "IIIIIIII" - "QQQQQQQQ" - }; - - FAIL_IF_NOT(DefragDoSturgesNovakTest(DEFRAG_POLICY_BSD, expected, - sizeof(expected))); + u_char expected[] = { "AAAAAAAA" + "AAAAAAAA" + "AAAAAAAA" + "JJJJJJJJ" + "JJJJJJJJ" + "BBBBBBBB" + "CCCCCCCC" + "CCCCCCCC" + "CCCCCCCC" + "LLLLLLLL" + "LLLLLLLL" + "LLLLLLLL" + "MMMMMMMM" + "MMMMMMMM" + "MMMMMMMM" + "FFFFFFFF" + "FFFFFFFF" + "FFFFFFFF" + "GGGGGGGG" + "GGGGGGGG" + "HHHHHHHH" + "HHHHHHHH" + "IIIIIIII" + "QQQQQQQQ" }; + + FAIL_IF_NOT(DefragDoSturgesNovakTest(DEFRAG_POLICY_BSD, expected, sizeof(expected))); PASS; } static int IPV6DefragSturgesNovakBsdTest(void) { /* Expected data. */ - u_char expected[] = { - "AAAAAAAA" - "AAAAAAAA" - "AAAAAAAA" - "JJJJJJJJ" - "JJJJJJJJ" - "BBBBBBBB" - "CCCCCCCC" - "CCCCCCCC" - "CCCCCCCC" - "LLLLLLLL" - "LLLLLLLL" - "LLLLLLLL" - "MMMMMMMM" - "MMMMMMMM" - "MMMMMMMM" - "FFFFFFFF" - "FFFFFFFF" - "FFFFFFFF" - "GGGGGGGG" - "GGGGGGGG" - "HHHHHHHH" - "HHHHHHHH" - "IIIIIIII" - "QQQQQQQQ" - }; - - FAIL_IF_NOT(IPV6DefragDoSturgesNovakTest(DEFRAG_POLICY_BSD, expected, - sizeof(expected))); + u_char expected[] = { "AAAAAAAA" + "AAAAAAAA" + "AAAAAAAA" + "JJJJJJJJ" + "JJJJJJJJ" + "BBBBBBBB" + "CCCCCCCC" + "CCCCCCCC" + "CCCCCCCC" + "LLLLLLLL" + "LLLLLLLL" + "LLLLLLLL" + "MMMMMMMM" + "MMMMMMMM" + "MMMMMMMM" + "FFFFFFFF" + "FFFFFFFF" + "FFFFFFFF" + "GGGGGGGG" + "GGGGGGGG" + "HHHHHHHH" + "HHHHHHHH" + "IIIIIIII" + "QQQQQQQQ" }; + + FAIL_IF_NOT(IPV6DefragDoSturgesNovakTest(DEFRAG_POLICY_BSD, expected, sizeof(expected))); PASS; } static int DefragSturgesNovakLinuxIpv4Test(void) { /* Expected data. */ - u_char expected[] = { - "AAAAAAAA" - "AAAAAAAA" - "AAAAAAAA" - "JJJJJJJJ" - "JJJJJJJJ" - "BBBBBBBB" - "KKKKKKKK" - "KKKKKKKK" - "KKKKKKKK" - "LLLLLLLL" - "LLLLLLLL" - "LLLLLLLL" - "MMMMMMMM" - "MMMMMMMM" - "MMMMMMMM" - "FFFFFFFF" - "FFFFFFFF" - "FFFFFFFF" - "GGGGGGGG" - "GGGGGGGG" - "PPPPPPPP" - "HHHHHHHH" - "QQQQQQQQ" - "QQQQQQQQ" - }; - - FAIL_IF_NOT(DefragDoSturgesNovakTest(DEFRAG_POLICY_LINUX, expected, - sizeof(expected))); + u_char expected[] = { "AAAAAAAA" + "AAAAAAAA" + "AAAAAAAA" + "JJJJJJJJ" + "JJJJJJJJ" + "BBBBBBBB" + "KKKKKKKK" + "KKKKKKKK" + "KKKKKKKK" + "LLLLLLLL" + "LLLLLLLL" + "LLLLLLLL" + "MMMMMMMM" + "MMMMMMMM" + "MMMMMMMM" + "FFFFFFFF" + "FFFFFFFF" + "FFFFFFFF" + "GGGGGGGG" + "GGGGGGGG" + "PPPPPPPP" + "HHHHHHHH" + "QQQQQQQQ" + "QQQQQQQQ" }; + + FAIL_IF_NOT(DefragDoSturgesNovakTest(DEFRAG_POLICY_LINUX, expected, sizeof(expected))); PASS; } static int IPV6DefragSturgesNovakLinuxTest(void) { /* Expected data. */ - u_char expected[] = { - "AAAAAAAA" - "AAAAAAAA" - "AAAAAAAA" - "JJJJJJJJ" - "JJJJJJJJ" - "BBBBBBBB" - "KKKKKKKK" - "KKKKKKKK" - "KKKKKKKK" - "LLLLLLLL" - "LLLLLLLL" - "LLLLLLLL" - "MMMMMMMM" - "MMMMMMMM" - "MMMMMMMM" - "FFFFFFFF" - "FFFFFFFF" - "FFFFFFFF" - "GGGGGGGG" - "GGGGGGGG" - "PPPPPPPP" - "HHHHHHHH" - "QQQQQQQQ" - "QQQQQQQQ" - }; - - FAIL_IF_NOT(IPV6DefragDoSturgesNovakTest(DEFRAG_POLICY_LINUX, expected, - sizeof(expected))); + u_char expected[] = { "AAAAAAAA" + "AAAAAAAA" + "AAAAAAAA" + "JJJJJJJJ" + "JJJJJJJJ" + "BBBBBBBB" + "KKKKKKKK" + "KKKKKKKK" + "KKKKKKKK" + "LLLLLLLL" + "LLLLLLLL" + "LLLLLLLL" + "MMMMMMMM" + "MMMMMMMM" + "MMMMMMMM" + "FFFFFFFF" + "FFFFFFFF" + "FFFFFFFF" + "GGGGGGGG" + "GGGGGGGG" + "PPPPPPPP" + "HHHHHHHH" + "QQQQQQQQ" + "QQQQQQQQ" }; + + FAIL_IF_NOT(IPV6DefragDoSturgesNovakTest(DEFRAG_POLICY_LINUX, expected, sizeof(expected))); PASS; } static int DefragSturgesNovakWindowsIpv4Test(void) { /* Expected data. */ - u_char expected[] = { - "AAAAAAAA" - "AAAAAAAA" - "AAAAAAAA" - "JJJJJJJJ" - "BBBBBBBB" - "BBBBBBBB" - "CCCCCCCC" - "CCCCCCCC" - "CCCCCCCC" - "LLLLLLLL" - "LLLLLLLL" - "LLLLLLLL" - "MMMMMMMM" - "EEEEEEEE" - "EEEEEEEE" - "FFFFFFFF" - "FFFFFFFF" - "FFFFFFFF" - "GGGGGGGG" - "GGGGGGGG" - "HHHHHHHH" - "HHHHHHHH" - "IIIIIIII" - "QQQQQQQQ" - }; - - FAIL_IF_NOT(DefragDoSturgesNovakTest(DEFRAG_POLICY_WINDOWS, expected, - sizeof(expected))); + u_char expected[] = { "AAAAAAAA" + "AAAAAAAA" + "AAAAAAAA" + "JJJJJJJJ" + "BBBBBBBB" + "BBBBBBBB" + "CCCCCCCC" + "CCCCCCCC" + "CCCCCCCC" + "LLLLLLLL" + "LLLLLLLL" + "LLLLLLLL" + "MMMMMMMM" + "EEEEEEEE" + "EEEEEEEE" + "FFFFFFFF" + "FFFFFFFF" + "FFFFFFFF" + "GGGGGGGG" + "GGGGGGGG" + "HHHHHHHH" + "HHHHHHHH" + "IIIIIIII" + "QQQQQQQQ" }; + + FAIL_IF_NOT(DefragDoSturgesNovakTest(DEFRAG_POLICY_WINDOWS, expected, sizeof(expected))); PASS; } static int IPV6DefragSturgesNovakWindowsTest(void) { /* Expected data. */ - u_char expected[] = { - "AAAAAAAA" - "AAAAAAAA" - "AAAAAAAA" - "JJJJJJJJ" - "BBBBBBBB" - "BBBBBBBB" - "CCCCCCCC" - "CCCCCCCC" - "CCCCCCCC" - "LLLLLLLL" - "LLLLLLLL" - "LLLLLLLL" - "MMMMMMMM" - "EEEEEEEE" - "EEEEEEEE" - "FFFFFFFF" - "FFFFFFFF" - "FFFFFFFF" - "GGGGGGGG" - "GGGGGGGG" - "HHHHHHHH" - "HHHHHHHH" - "IIIIIIII" - "QQQQQQQQ" - }; - - FAIL_IF_NOT(IPV6DefragDoSturgesNovakTest(DEFRAG_POLICY_WINDOWS, expected, - sizeof(expected))); + u_char expected[] = { "AAAAAAAA" + "AAAAAAAA" + "AAAAAAAA" + "JJJJJJJJ" + "BBBBBBBB" + "BBBBBBBB" + "CCCCCCCC" + "CCCCCCCC" + "CCCCCCCC" + "LLLLLLLL" + "LLLLLLLL" + "LLLLLLLL" + "MMMMMMMM" + "EEEEEEEE" + "EEEEEEEE" + "FFFFFFFF" + "FFFFFFFF" + "FFFFFFFF" + "GGGGGGGG" + "GGGGGGGG" + "HHHHHHHH" + "HHHHHHHH" + "IIIIIIII" + "QQQQQQQQ" }; + + FAIL_IF_NOT(IPV6DefragDoSturgesNovakTest(DEFRAG_POLICY_WINDOWS, expected, sizeof(expected))); PASS; } static int DefragSturgesNovakSolarisTest(void) { /* Expected data. */ - u_char expected[] = { - "AAAAAAAA" - "AAAAAAAA" - "AAAAAAAA" - "JJJJJJJJ" - "BBBBBBBB" - "BBBBBBBB" - "CCCCCCCC" - "CCCCCCCC" - "CCCCCCCC" - "LLLLLLLL" - "LLLLLLLL" - "LLLLLLLL" - "MMMMMMMM" - "MMMMMMMM" - "MMMMMMMM" - "FFFFFFFF" - "FFFFFFFF" - "FFFFFFFF" - "GGGGGGGG" - "GGGGGGGG" - "HHHHHHHH" - "HHHHHHHH" - "IIIIIIII" - "QQQQQQQQ" - }; - - FAIL_IF_NOT(DefragDoSturgesNovakTest(DEFRAG_POLICY_SOLARIS, expected, - sizeof(expected))); + u_char expected[] = { "AAAAAAAA" + "AAAAAAAA" + "AAAAAAAA" + "JJJJJJJJ" + "BBBBBBBB" + "BBBBBBBB" + "CCCCCCCC" + "CCCCCCCC" + "CCCCCCCC" + "LLLLLLLL" + "LLLLLLLL" + "LLLLLLLL" + "MMMMMMMM" + "MMMMMMMM" + "MMMMMMMM" + "FFFFFFFF" + "FFFFFFFF" + "FFFFFFFF" + "GGGGGGGG" + "GGGGGGGG" + "HHHHHHHH" + "HHHHHHHH" + "IIIIIIII" + "QQQQQQQQ" }; + + FAIL_IF_NOT(DefragDoSturgesNovakTest(DEFRAG_POLICY_SOLARIS, expected, sizeof(expected))); PASS; } static int IPV6DefragSturgesNovakSolarisTest(void) { /* Expected data. */ - u_char expected[] = { - "AAAAAAAA" - "AAAAAAAA" - "AAAAAAAA" - "JJJJJJJJ" - "BBBBBBBB" - "BBBBBBBB" - "CCCCCCCC" - "CCCCCCCC" - "CCCCCCCC" - "LLLLLLLL" - "LLLLLLLL" - "LLLLLLLL" - "MMMMMMMM" - "MMMMMMMM" - "MMMMMMMM" - "FFFFFFFF" - "FFFFFFFF" - "FFFFFFFF" - "GGGGGGGG" - "GGGGGGGG" - "HHHHHHHH" - "HHHHHHHH" - "IIIIIIII" - "QQQQQQQQ" - }; - - FAIL_IF_NOT(IPV6DefragDoSturgesNovakTest(DEFRAG_POLICY_SOLARIS, expected, - sizeof(expected))); + u_char expected[] = { "AAAAAAAA" + "AAAAAAAA" + "AAAAAAAA" + "JJJJJJJJ" + "BBBBBBBB" + "BBBBBBBB" + "CCCCCCCC" + "CCCCCCCC" + "CCCCCCCC" + "LLLLLLLL" + "LLLLLLLL" + "LLLLLLLL" + "MMMMMMMM" + "MMMMMMMM" + "MMMMMMMM" + "FFFFFFFF" + "FFFFFFFF" + "FFFFFFFF" + "GGGGGGGG" + "GGGGGGGG" + "HHHHHHHH" + "HHHHHHHH" + "IIIIIIII" + "QQQQQQQQ" }; + + FAIL_IF_NOT(IPV6DefragDoSturgesNovakTest(DEFRAG_POLICY_SOLARIS, expected, sizeof(expected))); PASS; } static int DefragSturgesNovakFirstTest(void) { /* Expected data. */ - u_char expected[] = { - "AAAAAAAA" - "AAAAAAAA" - "AAAAAAAA" - "JJJJJJJJ" - "BBBBBBBB" - "BBBBBBBB" - "CCCCCCCC" - "CCCCCCCC" - "CCCCCCCC" - "LLLLLLLL" - "DDDDDDDD" - "LLLLLLLL" - "MMMMMMMM" - "EEEEEEEE" - "EEEEEEEE" - "FFFFFFFF" - "FFFFFFFF" - "FFFFFFFF" - "GGGGGGGG" - "GGGGGGGG" - "HHHHHHHH" - "HHHHHHHH" - "IIIIIIII" - "QQQQQQQQ" - }; - - FAIL_IF_NOT(DefragDoSturgesNovakTest(DEFRAG_POLICY_FIRST, expected, - sizeof(expected))); + u_char expected[] = { "AAAAAAAA" + "AAAAAAAA" + "AAAAAAAA" + "JJJJJJJJ" + "BBBBBBBB" + "BBBBBBBB" + "CCCCCCCC" + "CCCCCCCC" + "CCCCCCCC" + "LLLLLLLL" + "DDDDDDDD" + "LLLLLLLL" + "MMMMMMMM" + "EEEEEEEE" + "EEEEEEEE" + "FFFFFFFF" + "FFFFFFFF" + "FFFFFFFF" + "GGGGGGGG" + "GGGGGGGG" + "HHHHHHHH" + "HHHHHHHH" + "IIIIIIII" + "QQQQQQQQ" }; + + FAIL_IF_NOT(DefragDoSturgesNovakTest(DEFRAG_POLICY_FIRST, expected, sizeof(expected))); PASS; } static int IPV6DefragSturgesNovakFirstTest(void) { /* Expected data. */ - u_char expected[] = { - "AAAAAAAA" - "AAAAAAAA" - "AAAAAAAA" - "JJJJJJJJ" - "BBBBBBBB" - "BBBBBBBB" - "CCCCCCCC" - "CCCCCCCC" - "CCCCCCCC" - "LLLLLLLL" - "DDDDDDDD" - "LLLLLLLL" - "MMMMMMMM" - "EEEEEEEE" - "EEEEEEEE" - "FFFFFFFF" - "FFFFFFFF" - "FFFFFFFF" - "GGGGGGGG" - "GGGGGGGG" - "HHHHHHHH" - "HHHHHHHH" - "IIIIIIII" - "QQQQQQQQ" - }; - - return IPV6DefragDoSturgesNovakTest(DEFRAG_POLICY_FIRST, expected, - sizeof(expected)); + u_char expected[] = { "AAAAAAAA" + "AAAAAAAA" + "AAAAAAAA" + "JJJJJJJJ" + "BBBBBBBB" + "BBBBBBBB" + "CCCCCCCC" + "CCCCCCCC" + "CCCCCCCC" + "LLLLLLLL" + "DDDDDDDD" + "LLLLLLLL" + "MMMMMMMM" + "EEEEEEEE" + "EEEEEEEE" + "FFFFFFFF" + "FFFFFFFF" + "FFFFFFFF" + "GGGGGGGG" + "GGGGGGGG" + "HHHHHHHH" + "HHHHHHHH" + "IIIIIIII" + "QQQQQQQQ" }; + + return IPV6DefragDoSturgesNovakTest(DEFRAG_POLICY_FIRST, expected, sizeof(expected)); } -static int -DefragSturgesNovakLastTest(void) +static int DefragSturgesNovakLastTest(void) { /* Expected data. */ - u_char expected[] = { - "AAAAAAAA" - "JJJJJJJJ" - "JJJJJJJJ" - "JJJJJJJJ" - "JJJJJJJJ" - "BBBBBBBB" - "KKKKKKKK" - "KKKKKKKK" - "KKKKKKKK" - "LLLLLLLL" - "LLLLLLLL" - "LLLLLLLL" - "MMMMMMMM" - "MMMMMMMM" - "MMMMMMMM" - "FFFFFFFF" - "NNNNNNNN" - "FFFFFFFF" - "GGGGGGGG" - "OOOOOOOO" - "PPPPPPPP" - "HHHHHHHH" - "QQQQQQQQ" - "QQQQQQQQ" - }; - - FAIL_IF_NOT(DefragDoSturgesNovakTest(DEFRAG_POLICY_LAST, expected, - sizeof(expected))); + u_char expected[] = { "AAAAAAAA" + "JJJJJJJJ" + "JJJJJJJJ" + "JJJJJJJJ" + "JJJJJJJJ" + "BBBBBBBB" + "KKKKKKKK" + "KKKKKKKK" + "KKKKKKKK" + "LLLLLLLL" + "LLLLLLLL" + "LLLLLLLL" + "MMMMMMMM" + "MMMMMMMM" + "MMMMMMMM" + "FFFFFFFF" + "NNNNNNNN" + "FFFFFFFF" + "GGGGGGGG" + "OOOOOOOO" + "PPPPPPPP" + "HHHHHHHH" + "QQQQQQQQ" + "QQQQQQQQ" }; + + FAIL_IF_NOT(DefragDoSturgesNovakTest(DEFRAG_POLICY_LAST, expected, sizeof(expected))); PASS; } static int IPV6DefragSturgesNovakLastTest(void) { /* Expected data. */ - u_char expected[] = { - "AAAAAAAA" - "JJJJJJJJ" - "JJJJJJJJ" - "JJJJJJJJ" - "JJJJJJJJ" - "BBBBBBBB" - "KKKKKKKK" - "KKKKKKKK" - "KKKKKKKK" - "LLLLLLLL" - "LLLLLLLL" - "LLLLLLLL" - "MMMMMMMM" - "MMMMMMMM" - "MMMMMMMM" - "FFFFFFFF" - "NNNNNNNN" - "FFFFFFFF" - "GGGGGGGG" - "OOOOOOOO" - "PPPPPPPP" - "HHHHHHHH" - "QQQQQQQQ" - "QQQQQQQQ" - }; - - FAIL_IF_NOT(IPV6DefragDoSturgesNovakTest(DEFRAG_POLICY_LAST, expected, - sizeof(expected))); + u_char expected[] = { "AAAAAAAA" + "JJJJJJJJ" + "JJJJJJJJ" + "JJJJJJJJ" + "JJJJJJJJ" + "BBBBBBBB" + "KKKKKKKK" + "KKKKKKKK" + "KKKKKKKK" + "LLLLLLLL" + "LLLLLLLL" + "LLLLLLLL" + "MMMMMMMM" + "MMMMMMMM" + "MMMMMMMM" + "FFFFFFFF" + "NNNNNNNN" + "FFFFFFFF" + "GGGGGGGG" + "OOOOOOOO" + "PPPPPPPP" + "HHHHHHHH" + "QQQQQQQQ" + "QQQQQQQQ" }; + + FAIL_IF_NOT(IPV6DefragDoSturgesNovakTest(DEFRAG_POLICY_LAST, expected, sizeof(expected))); PASS; } @@ -2099,7 +2027,7 @@ static int DefragTimeoutTest(void) /* Load in 16 packets. */ for (i = 0; i < 16; i++) { - Packet *p = BuildTestPacket(IPPROTO_ICMP,i, 0, 1, 'A' + i, 16); + Packet *p = BuildTestPacket(IPPROTO_ICMP, i, 0, 1, 'A' + i, 16); FAIL_IF_NULL(p); Packet *tp = Defrag(NULL, NULL, p); @@ -2462,18 +2390,18 @@ static int DefragTestBadProto(void) static int DefragTestJeremyLinux(void) { char expected[] = "AAAAAAAA" - "AAAAAAAA" - "AAAAAAAA" - "CCCCCCCC" - "CCCCCCCC" - "CCCCCCCC" - "CCCCCCCC" - "CCCCCCCC" - "CCCCCCCC" - "BBBBBBBB" - "BBBBBBBB" - "DDDDDDDD" - "DDDDDD"; + "AAAAAAAA" + "AAAAAAAA" + "CCCCCCCC" + "CCCCCCCC" + "CCCCCCCC" + "CCCCCCCC" + "CCCCCCCC" + "CCCCCCCC" + "BBBBBBBB" + "BBBBBBBB" + "DDDDDDDD" + "DDDDDD"; DefragInit(); default_policy = DEFRAG_POLICY_LINUX; @@ -2518,12 +2446,9 @@ void DefragRegisterTests(void) UtRegisterTest("DefragInOrderSimpleTest", DefragInOrderSimpleTest); UtRegisterTest("DefragReverseSimpleTest", DefragReverseSimpleTest); UtRegisterTest("DefragSturgesNovakBsdTest", DefragSturgesNovakBsdTest); - UtRegisterTest("DefragSturgesNovakLinuxIpv4Test", - DefragSturgesNovakLinuxIpv4Test); - UtRegisterTest("DefragSturgesNovakWindowsIpv4Test", - DefragSturgesNovakWindowsIpv4Test); - UtRegisterTest("DefragSturgesNovakSolarisTest", - DefragSturgesNovakSolarisTest); + UtRegisterTest("DefragSturgesNovakLinuxIpv4Test", DefragSturgesNovakLinuxIpv4Test); + UtRegisterTest("DefragSturgesNovakWindowsIpv4Test", DefragSturgesNovakWindowsIpv4Test); + UtRegisterTest("DefragSturgesNovakSolarisTest", DefragSturgesNovakSolarisTest); UtRegisterTest("DefragSturgesNovakFirstTest", DefragSturgesNovakFirstTest); UtRegisterTest("DefragSturgesNovakLastTest", DefragSturgesNovakLastTest); @@ -2532,18 +2457,12 @@ void DefragRegisterTests(void) UtRegisterTest("IPV6DefragInOrderSimpleTest", IPV6DefragInOrderSimpleTest); UtRegisterTest("IPV6DefragReverseSimpleTest", IPV6DefragReverseSimpleTest); - UtRegisterTest("IPV6DefragSturgesNovakBsdTest", - IPV6DefragSturgesNovakBsdTest); - UtRegisterTest("IPV6DefragSturgesNovakLinuxTest", - IPV6DefragSturgesNovakLinuxTest); - UtRegisterTest("IPV6DefragSturgesNovakWindowsTest", - IPV6DefragSturgesNovakWindowsTest); - UtRegisterTest("IPV6DefragSturgesNovakSolarisTest", - IPV6DefragSturgesNovakSolarisTest); - UtRegisterTest("IPV6DefragSturgesNovakFirstTest", - IPV6DefragSturgesNovakFirstTest); - UtRegisterTest("IPV6DefragSturgesNovakLastTest", - IPV6DefragSturgesNovakLastTest); + UtRegisterTest("IPV6DefragSturgesNovakBsdTest", IPV6DefragSturgesNovakBsdTest); + UtRegisterTest("IPV6DefragSturgesNovakLinuxTest", IPV6DefragSturgesNovakLinuxTest); + UtRegisterTest("IPV6DefragSturgesNovakWindowsTest", IPV6DefragSturgesNovakWindowsTest); + UtRegisterTest("IPV6DefragSturgesNovakSolarisTest", IPV6DefragSturgesNovakSolarisTest); + UtRegisterTest("IPV6DefragSturgesNovakFirstTest", IPV6DefragSturgesNovakFirstTest); + UtRegisterTest("IPV6DefragSturgesNovakLastTest", IPV6DefragSturgesNovakLastTest); UtRegisterTest("DefragVlanTest", DefragVlanTest); UtRegisterTest("DefragVlanQinQTest", DefragVlanQinQTest); diff --git a/src/defrag.h b/src/defrag.h index 11e6a619b2f1..355347ba8dcf 100644 --- a/src/defrag.h +++ b/src/defrag.h @@ -44,31 +44,31 @@ typedef struct DefragContext_ { * Storage for an individual fragment. */ typedef struct Frag_ { - uint16_t offset; /**< The offset of this fragment, already - * multiplied by 8. */ + uint16_t offset; /**< The offset of this fragment, already + * multiplied by 8. */ uint32_t len; /**< The length of this fragment. */ - uint8_t hlen; /**< The length of this fragments IP header. */ + uint8_t hlen; /**< The length of this fragments IP header. */ - uint8_t more_frags:4; /**< More frags? */ - uint8_t skip:4; /**< Skip this fragment during re-assembly. */ + uint8_t more_frags : 4; /**< More frags? */ + uint8_t skip : 4; /**< Skip this fragment during re-assembly. */ - uint16_t ip_hdr_offset; /**< Offset in the packet where the IP - * header starts. */ - uint16_t frag_hdr_offset; /**< Offset in the packet where the frag - * header starts. */ + uint16_t ip_hdr_offset; /**< Offset in the packet where the IP + * header starts. */ + uint16_t frag_hdr_offset; /**< Offset in the packet where the frag + * header starts. */ - uint16_t data_offset; /**< Offset to the packet data. */ - uint16_t data_len; /**< Length of data. */ + uint16_t data_offset; /**< Offset to the packet data. */ + uint16_t data_len; /**< Length of data. */ - uint16_t ltrim; /**< Number of leading bytes to trim when - * re-assembling the packet. */ + uint16_t ltrim; /**< Number of leading bytes to trim when + * re-assembling the packet. */ - uint8_t *pkt; /**< The actual packet. */ + uint8_t *pkt; /**< The actual packet. */ #ifdef DEBUG - uint64_t pcap_cnt; /**< pcap_cnt of original packet */ + uint64_t pcap_cnt; /**< pcap_cnt of original packet */ #endif RB_ENTRY(Frag_) rb; @@ -85,7 +85,7 @@ RB_PROTOTYPE(IP_FRAGMENTS, Frag_, rb, DefragRbFragCompare); */ typedef struct DefragTracker_ { SCMutex lock; /**< Mutex for locking list operations on - * this tracker. */ + * this tracker. */ uint16_t vlan_id[VLAN_MAX_LAYERS]; /**< VLAN ID tracker applies to. */ @@ -106,8 +106,8 @@ typedef struct DefragTracker_ { Address src_addr; /**< Source address for this tracker. */ Address dst_addr; /**< Destination address for this tracker. */ - SCTime_t timeout; /**< When this tracker will timeout. */ - uint32_t host_timeout; /**< Host timeout, statically assigned from the yaml */ + SCTime_t timeout; /**< When this tracker will timeout. */ + uint32_t host_timeout; /**< Host timeout, statically assigned from the yaml */ /** use cnt, reference counter */ SC_ATOMIC_DECLARE(unsigned int, use_cnt); diff --git a/src/detect-app-layer-event.c b/src/detect-app-layer-event.c index 9c323359b577..cddecc6d9c03 100644 --- a/src/detect-app-layer-event.c +++ b/src/detect-app-layer-event.c @@ -56,8 +56,8 @@ typedef struct DetectAppLayerEventData_ { uint8_t event_id; } DetectAppLayerEventData; -static int DetectAppLayerEventPktMatch(DetectEngineThreadCtx *det_ctx, - Packet *p, const Signature *s, const SigMatchCtx *ctx); +static int DetectAppLayerEventPktMatch( + DetectEngineThreadCtx *det_ctx, Packet *p, const Signature *s, const SigMatchCtx *ctx); static int DetectAppLayerEventSetup(DetectEngineCtx *, Signature *, const char *); static void DetectAppLayerEventFree(DetectEngineCtx *, void *); static uint8_t DetectEngineAptEventInspect(DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx, @@ -71,10 +71,10 @@ static int g_applayer_events_list_id = 0; void DetectAppLayerEventRegister(void) { sigmatch_table[DETECT_AL_APP_LAYER_EVENT].name = "app-layer-event"; - sigmatch_table[DETECT_AL_APP_LAYER_EVENT].desc = "match on events generated by the App Layer Parsers and the protocol detection engine"; + sigmatch_table[DETECT_AL_APP_LAYER_EVENT].desc = + "match on events generated by the App Layer Parsers and the protocol detection engine"; sigmatch_table[DETECT_AL_APP_LAYER_EVENT].url = "/rules/app-layer.html#app-layer-event"; - sigmatch_table[DETECT_AL_APP_LAYER_EVENT].Match = - DetectAppLayerEventPktMatch; + sigmatch_table[DETECT_AL_APP_LAYER_EVENT].Match = DetectAppLayerEventPktMatch; sigmatch_table[DETECT_AL_APP_LAYER_EVENT].Setup = DetectAppLayerEventSetup; sigmatch_table[DETECT_AL_APP_LAYER_EVENT].Free = DetectAppLayerEventFree; @@ -117,13 +117,12 @@ static uint8_t DetectEngineAptEventInspect(DetectEngineCtx *de_ctx, DetectEngine r = 1; - end: +end: if (r == 1) { return DETECT_ENGINE_INSPECT_SIG_MATCH; } else { if (AppLayerParserGetStateProgress(f->proto, alproto, tx, flags) == - AppLayerParserGetStateProgressCompletionStatus(alproto, flags)) - { + AppLayerParserGetStateProgressCompletionStatus(alproto, flags)) { return DETECT_ENGINE_INSPECT_SIG_CANT_MATCH; } else { return DETECT_ENGINE_INSPECT_SIG_NO_MATCH; @@ -131,18 +130,16 @@ static uint8_t DetectEngineAptEventInspect(DetectEngineCtx *de_ctx, DetectEngine } } - -static int DetectAppLayerEventPktMatch(DetectEngineThreadCtx *det_ctx, - Packet *p, const Signature *s, const SigMatchCtx *ctx) +static int DetectAppLayerEventPktMatch( + DetectEngineThreadCtx *det_ctx, Packet *p, const Signature *s, const SigMatchCtx *ctx) { const DetectAppLayerEventData *aled = (const DetectAppLayerEventData *)ctx; - return AppLayerDecoderEventsIsEventSet(p->app_layer_events, - aled->event_id); + return AppLayerDecoderEventsIsEventSet(p->app_layer_events, aled->event_id); } -static DetectAppLayerEventData *DetectAppLayerEventParsePkt(const char *arg, - AppLayerEventType *event_type) +static DetectAppLayerEventData *DetectAppLayerEventParsePkt( + const char *arg, AppLayerEventType *event_type) { int event_id = 0; int r = AppLayerGetPktEventInfo(arg, &event_id); diff --git a/src/detect-app-layer-protocol.c b/src/detect-app-layer-protocol.c index 182f6d0faeb3..c7468e315868 100644 --- a/src/detect-app-layer-protocol.c +++ b/src/detect-app-layer-protocol.c @@ -44,8 +44,7 @@ typedef struct DetectAppLayerProtocolData_ { } DetectAppLayerProtocolData; static int DetectAppLayerProtocolPacketMatch( - DetectEngineThreadCtx *det_ctx, - Packet *p, const Signature *s, const SigMatchCtx *ctx) + DetectEngineThreadCtx *det_ctx, Packet *p, const Signature *s, const SigMatchCtx *ctx) { SCEnter(); @@ -55,37 +54,33 @@ static int DetectAppLayerProtocolPacketMatch( /* if the sig is PD-only we only match when PD packet flags are set */ if (s->type == SIG_TYPE_PDONLY && (p->flags & (PKT_PROTO_DETECT_TS_DONE | PKT_PROTO_DETECT_TC_DONE)) == 0) { - SCLogDebug("packet %"PRIu64": flags not set", p->pcap_cnt); + SCLogDebug("packet %" PRIu64 ": flags not set", p->pcap_cnt); SCReturnInt(0); } const Flow *f = p->flow; if (f == NULL) { - SCLogDebug("packet %"PRIu64": no flow", p->pcap_cnt); + SCLogDebug("packet %" PRIu64 ": no flow", p->pcap_cnt); SCReturnInt(0); } /* unknown means protocol detection isn't ready yet */ - if ((f->alproto_ts != ALPROTO_UNKNOWN) && (p->flowflags & FLOW_PKT_TOSERVER)) - { - SCLogDebug("toserver packet %"PRIu64": looking for %u/neg %u, got %u", - p->pcap_cnt, data->alproto, data->negated, f->alproto_ts); + if ((f->alproto_ts != ALPROTO_UNKNOWN) && (p->flowflags & FLOW_PKT_TOSERVER)) { + SCLogDebug("toserver packet %" PRIu64 ": looking for %u/neg %u, got %u", p->pcap_cnt, + data->alproto, data->negated, f->alproto_ts); r = AppProtoEquals(data->alproto, f->alproto_ts); - } else if ((f->alproto_tc != ALPROTO_UNKNOWN) && (p->flowflags & FLOW_PKT_TOCLIENT)) - { - SCLogDebug("toclient packet %"PRIu64": looking for %u/neg %u, got %u", - p->pcap_cnt, data->alproto, data->negated, f->alproto_tc); + } else if ((f->alproto_tc != ALPROTO_UNKNOWN) && (p->flowflags & FLOW_PKT_TOCLIENT)) { + SCLogDebug("toclient packet %" PRIu64 ": looking for %u/neg %u, got %u", p->pcap_cnt, + data->alproto, data->negated, f->alproto_tc); r = AppProtoEquals(data->alproto, f->alproto_tc); - } - else { - SCLogDebug("packet %"PRIu64": default case: direction %02x, approtos %u/%u/%u", - p->pcap_cnt, - p->flowflags & (FLOW_PKT_TOCLIENT|FLOW_PKT_TOSERVER), - f->alproto, f->alproto_ts, f->alproto_tc); + } else { + SCLogDebug("packet %" PRIu64 ": default case: direction %02x, approtos %u/%u/%u", + p->pcap_cnt, p->flowflags & (FLOW_PKT_TOCLIENT | FLOW_PKT_TOSERVER), f->alproto, + f->alproto_ts, f->alproto_tc); } r = r ^ data->negated; if (r) { @@ -120,8 +115,8 @@ static DetectAppLayerProtocolData *DetectAppLayerProtocolParse(const char *arg, return data; } -static bool HasConflicts(const DetectAppLayerProtocolData *us, - const DetectAppLayerProtocolData *them) +static bool HasConflicts( + const DetectAppLayerProtocolData *us, const DetectAppLayerProtocolData *them) { /* mixing negated and non negated is illegal */ if (them->negated ^ us->negated) @@ -137,8 +132,7 @@ static bool HasConflicts(const DetectAppLayerProtocolData *us, return false; } -static int DetectAppLayerProtocolSetup(DetectEngineCtx *de_ctx, - Signature *s, const char *arg) +static int DetectAppLayerProtocolSetup(DetectEngineCtx *de_ctx, Signature *s, const char *arg) { DetectAppLayerProtocolData *data = NULL; @@ -155,7 +149,7 @@ static int DetectAppLayerProtocolSetup(DetectEngineCtx *de_ctx, goto error; SigMatch *tsm = s->init_data->smlists[DETECT_SM_LIST_MATCH]; - for ( ; tsm != NULL; tsm = tsm->next) { + for (; tsm != NULL; tsm = tsm->next) { if (tsm->type == DETECT_AL_APP_LAYER_PROTOCOL) { const DetectAppLayerProtocolData *them = (const DetectAppLayerProtocolData *)tsm->ctx; @@ -189,34 +183,32 @@ static void DetectAppLayerProtocolFree(DetectEngineCtx *de_ctx, void *ptr) /** \internal * \brief prefilter function for protocol detect matching */ -static void -PrefilterPacketAppProtoMatch(DetectEngineThreadCtx *det_ctx, Packet *p, const void *pectx) +static void PrefilterPacketAppProtoMatch( + DetectEngineThreadCtx *det_ctx, Packet *p, const void *pectx) { const PrefilterPacketHeaderCtx *ctx = pectx; if (!PrefilterPacketHeaderExtraMatch(ctx, p)) { - SCLogDebug("packet %"PRIu64": extra match failed", p->pcap_cnt); + SCLogDebug("packet %" PRIu64 ": extra match failed", p->pcap_cnt); SCReturn; } if (p->flow == NULL) { - SCLogDebug("packet %"PRIu64": no flow, no alproto", p->pcap_cnt); + SCLogDebug("packet %" PRIu64 ": no flow, no alproto", p->pcap_cnt); SCReturn; } - if ((p->flags & (PKT_PROTO_DETECT_TS_DONE|PKT_PROTO_DETECT_TC_DONE)) == 0) { - SCLogDebug("packet %"PRIu64": flags not set", p->pcap_cnt); + if ((p->flags & (PKT_PROTO_DETECT_TS_DONE | PKT_PROTO_DETECT_TC_DONE)) == 0) { + SCLogDebug("packet %" PRIu64 ": flags not set", p->pcap_cnt); SCReturn; } - if ((p->flags & PKT_PROTO_DETECT_TS_DONE) && (p->flowflags & FLOW_PKT_TOSERVER)) - { + if ((p->flags & PKT_PROTO_DETECT_TS_DONE) && (p->flowflags & FLOW_PKT_TOSERVER)) { int r = (ctx->v1.u16[0] == p->flow->alproto_ts) ^ ctx->v1.u8[2]; if (r) { PrefilterAddSids(&det_ctx->pmq, ctx->sigs_array, ctx->sigs_cnt); } - } else if ((p->flags & PKT_PROTO_DETECT_TC_DONE) && (p->flowflags & FLOW_PKT_TOCLIENT)) - { + } else if ((p->flags & PKT_PROTO_DETECT_TC_DONE) && (p->flowflags & FLOW_PKT_TOCLIENT)) { int r = (ctx->v1.u16[0] == p->flow->alproto_tc) ^ ctx->v1.u8[2]; if (r) { PrefilterAddSids(&det_ctx->pmq, ctx->sigs_array, ctx->sigs_cnt); @@ -224,20 +216,17 @@ PrefilterPacketAppProtoMatch(DetectEngineThreadCtx *det_ctx, Packet *p, const vo } } -static void -PrefilterPacketAppProtoSet(PrefilterPacketHeaderValue *v, void *smctx) +static void PrefilterPacketAppProtoSet(PrefilterPacketHeaderValue *v, void *smctx) { const DetectAppLayerProtocolData *a = smctx; v->u16[0] = a->alproto; v->u8[2] = (uint8_t)a->negated; } -static bool -PrefilterPacketAppProtoCompare(PrefilterPacketHeaderValue v, void *smctx) +static bool PrefilterPacketAppProtoCompare(PrefilterPacketHeaderValue v, void *smctx) { const DetectAppLayerProtocolData *a = smctx; - if (v.u16[0] == a->alproto && - v.u8[2] == (uint8_t)a->negated) + if (v.u16[0] == a->alproto && v.u8[2] == (uint8_t)a->negated) return true; return false; } @@ -245,9 +234,8 @@ PrefilterPacketAppProtoCompare(PrefilterPacketHeaderValue v, void *smctx) static int PrefilterSetupAppProto(DetectEngineCtx *de_ctx, SigGroupHead *sgh) { return PrefilterSetupPacketHeader(de_ctx, sgh, DETECT_AL_APP_LAYER_PROTOCOL, - PrefilterPacketAppProtoSet, - PrefilterPacketAppProtoCompare, - PrefilterPacketAppProtoMatch); + PrefilterPacketAppProtoSet, PrefilterPacketAppProtoCompare, + PrefilterPacketAppProtoMatch); } static bool PrefilterAppProtoIsPrefilterable(const Signature *s) @@ -264,23 +252,19 @@ void DetectAppLayerProtocolRegister(void) sigmatch_table[DETECT_AL_APP_LAYER_PROTOCOL].name = "app-layer-protocol"; sigmatch_table[DETECT_AL_APP_LAYER_PROTOCOL].desc = "match on the detected app-layer protocol"; sigmatch_table[DETECT_AL_APP_LAYER_PROTOCOL].url = "/rules/app-layer.html#app-layer-protocol"; - sigmatch_table[DETECT_AL_APP_LAYER_PROTOCOL].Match = - DetectAppLayerProtocolPacketMatch; - sigmatch_table[DETECT_AL_APP_LAYER_PROTOCOL].Setup = - DetectAppLayerProtocolSetup; - sigmatch_table[DETECT_AL_APP_LAYER_PROTOCOL].Free = - DetectAppLayerProtocolFree; + sigmatch_table[DETECT_AL_APP_LAYER_PROTOCOL].Match = DetectAppLayerProtocolPacketMatch; + sigmatch_table[DETECT_AL_APP_LAYER_PROTOCOL].Setup = DetectAppLayerProtocolSetup; + sigmatch_table[DETECT_AL_APP_LAYER_PROTOCOL].Free = DetectAppLayerProtocolFree; #ifdef UNITTESTS sigmatch_table[DETECT_AL_APP_LAYER_PROTOCOL].RegisterTests = - DetectAppLayerProtocolRegisterTests; + DetectAppLayerProtocolRegisterTests; #endif sigmatch_table[DETECT_AL_APP_LAYER_PROTOCOL].flags = - (SIGMATCH_QUOTES_OPTIONAL|SIGMATCH_HANDLE_NEGATION); + (SIGMATCH_QUOTES_OPTIONAL | SIGMATCH_HANDLE_NEGATION); - sigmatch_table[DETECT_AL_APP_LAYER_PROTOCOL].SetupPrefilter = - PrefilterSetupAppProto; + sigmatch_table[DETECT_AL_APP_LAYER_PROTOCOL].SetupPrefilter = PrefilterSetupAppProto; sigmatch_table[DETECT_AL_APP_LAYER_PROTOCOL].SupportsPrefilter = - PrefilterAppProtoIsPrefilterable; + PrefilterAppProtoIsPrefilterable; return; } @@ -317,7 +301,7 @@ static int DetectAppLayerProtocolTest03(void) de_ctx->flags |= DE_QUIET; s = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any " - "(app-layer-protocol:http; sid:1;)"); + "(app-layer-protocol:http; sid:1;)"); FAIL_IF_NULL(s); FAIL_IF(s->alproto != ALPROTO_UNKNOWN); @@ -341,7 +325,7 @@ static int DetectAppLayerProtocolTest04(void) de_ctx->flags |= DE_QUIET; s = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any " - "(app-layer-protocol:!http; sid:1;)"); + "(app-layer-protocol:!http; sid:1;)"); FAIL_IF_NULL(s); FAIL_IF(s->alproto != ALPROTO_UNKNOWN); FAIL_IF(s->flags & SIG_FLAG_APPLAYER); @@ -366,7 +350,8 @@ static int DetectAppLayerProtocolTest05(void) FAIL_IF_NULL(de_ctx); de_ctx->flags |= DE_QUIET; - s = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any " + s = DetectEngineAppendSig(de_ctx, + "alert tcp any any -> any any " "(app-layer-protocol:!http; app-layer-protocol:!smtp; sid:1;)"); FAIL_IF_NULL(s); FAIL_IF(s->alproto != ALPROTO_UNKNOWN); @@ -397,7 +382,7 @@ static int DetectAppLayerProtocolTest06(void) de_ctx->flags |= DE_QUIET; s = DetectEngineAppendSig(de_ctx, "alert http any any -> any any " - "(app-layer-protocol:smtp; sid:1;)"); + "(app-layer-protocol:smtp; sid:1;)"); FAIL_IF_NOT_NULL(s); DetectEngineCtxFree(de_ctx); PASS; @@ -411,7 +396,7 @@ static int DetectAppLayerProtocolTest07(void) de_ctx->flags |= DE_QUIET; s = DetectEngineAppendSig(de_ctx, "alert http any any -> any any " - "(app-layer-protocol:!smtp; sid:1;)"); + "(app-layer-protocol:!smtp; sid:1;)"); FAIL_IF_NOT_NULL(s); DetectEngineCtxFree(de_ctx); PASS; @@ -424,7 +409,8 @@ static int DetectAppLayerProtocolTest08(void) FAIL_IF_NULL(de_ctx); de_ctx->flags |= DE_QUIET; - s = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any " + s = DetectEngineAppendSig(de_ctx, + "alert tcp any any -> any any " "(app-layer-protocol:!smtp; app-layer-protocol:http; sid:1;)"); FAIL_IF_NOT_NULL(s); DetectEngineCtxFree(de_ctx); @@ -438,7 +424,8 @@ static int DetectAppLayerProtocolTest09(void) FAIL_IF_NULL(de_ctx); de_ctx->flags |= DE_QUIET; - s = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any " + s = DetectEngineAppendSig(de_ctx, + "alert tcp any any -> any any " "(app-layer-protocol:http; app-layer-protocol:!smtp; sid:1;)"); FAIL_IF_NOT_NULL(s); DetectEngineCtxFree(de_ctx); @@ -452,7 +439,8 @@ static int DetectAppLayerProtocolTest10(void) FAIL_IF_NULL(de_ctx); de_ctx->flags |= DE_QUIET; - s = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any " + s = DetectEngineAppendSig(de_ctx, + "alert tcp any any -> any any " "(app-layer-protocol:smtp; app-layer-protocol:!http; sid:1;)"); FAIL_IF_NOT_NULL(s); DetectEngineCtxFree(de_ctx); @@ -488,7 +476,7 @@ static int DetectAppLayerProtocolTest13(void) de_ctx->flags |= DE_QUIET; s = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any " - "(app-layer-protocol:failed; sid:1;)"); + "(app-layer-protocol:failed; sid:1;)"); FAIL_IF_NULL(s); FAIL_IF(s->alproto != ALPROTO_UNKNOWN); @@ -510,8 +498,9 @@ static int DetectAppLayerProtocolTest14(void) FAIL_IF_NULL(de_ctx); de_ctx->flags |= DE_QUIET; - Signature *s1 = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any " - "(app-layer-protocol:http; flowbits:set,blah; sid:1;)"); + Signature *s1 = + DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any " + "(app-layer-protocol:http; flowbits:set,blah; sid:1;)"); FAIL_IF_NULL(s1); FAIL_IF(s1->alproto != ALPROTO_UNKNOWN); FAIL_IF_NULL(s1->init_data->smlists[DETECT_SM_LIST_MATCH]); @@ -520,8 +509,9 @@ static int DetectAppLayerProtocolTest14(void) FAIL_IF(data->alproto != ALPROTO_HTTP); FAIL_IF(data->negated); - Signature *s2 = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any " - "(app-layer-protocol:http; flow:to_client; sid:2;)"); + Signature *s2 = + DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any " + "(app-layer-protocol:http; flow:to_client; sid:2;)"); FAIL_IF_NULL(s2); FAIL_IF(s2->alproto != ALPROTO_UNKNOWN); FAIL_IF_NULL(s2->init_data->smlists[DETECT_SM_LIST_MATCH]); @@ -531,7 +521,8 @@ static int DetectAppLayerProtocolTest14(void) FAIL_IF(data->negated); /* flow:established and other options not supported for PD-only */ - Signature *s3 = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any " + Signature *s3 = DetectEngineAppendSig(de_ctx, + "alert tcp any any -> any any " "(app-layer-protocol:http; flow:to_client,established; sid:3;)"); FAIL_IF_NULL(s3); FAIL_IF(s3->alproto != ALPROTO_UNKNOWN); @@ -550,36 +541,21 @@ static int DetectAppLayerProtocolTest14(void) PASS; } - static void DetectAppLayerProtocolRegisterTests(void) { - UtRegisterTest("DetectAppLayerProtocolTest01", - DetectAppLayerProtocolTest01); - UtRegisterTest("DetectAppLayerProtocolTest02", - DetectAppLayerProtocolTest02); - UtRegisterTest("DetectAppLayerProtocolTest03", - DetectAppLayerProtocolTest03); - UtRegisterTest("DetectAppLayerProtocolTest04", - DetectAppLayerProtocolTest04); - UtRegisterTest("DetectAppLayerProtocolTest05", - DetectAppLayerProtocolTest05); - UtRegisterTest("DetectAppLayerProtocolTest06", - DetectAppLayerProtocolTest06); - UtRegisterTest("DetectAppLayerProtocolTest07", - DetectAppLayerProtocolTest07); - UtRegisterTest("DetectAppLayerProtocolTest08", - DetectAppLayerProtocolTest08); - UtRegisterTest("DetectAppLayerProtocolTest09", - DetectAppLayerProtocolTest09); - UtRegisterTest("DetectAppLayerProtocolTest10", - DetectAppLayerProtocolTest10); - UtRegisterTest("DetectAppLayerProtocolTest11", - DetectAppLayerProtocolTest11); - UtRegisterTest("DetectAppLayerProtocolTest12", - DetectAppLayerProtocolTest12); - UtRegisterTest("DetectAppLayerProtocolTest13", - DetectAppLayerProtocolTest13); - UtRegisterTest("DetectAppLayerProtocolTest14", - DetectAppLayerProtocolTest14); + UtRegisterTest("DetectAppLayerProtocolTest01", DetectAppLayerProtocolTest01); + UtRegisterTest("DetectAppLayerProtocolTest02", DetectAppLayerProtocolTest02); + UtRegisterTest("DetectAppLayerProtocolTest03", DetectAppLayerProtocolTest03); + UtRegisterTest("DetectAppLayerProtocolTest04", DetectAppLayerProtocolTest04); + UtRegisterTest("DetectAppLayerProtocolTest05", DetectAppLayerProtocolTest05); + UtRegisterTest("DetectAppLayerProtocolTest06", DetectAppLayerProtocolTest06); + UtRegisterTest("DetectAppLayerProtocolTest07", DetectAppLayerProtocolTest07); + UtRegisterTest("DetectAppLayerProtocolTest08", DetectAppLayerProtocolTest08); + UtRegisterTest("DetectAppLayerProtocolTest09", DetectAppLayerProtocolTest09); + UtRegisterTest("DetectAppLayerProtocolTest10", DetectAppLayerProtocolTest10); + UtRegisterTest("DetectAppLayerProtocolTest11", DetectAppLayerProtocolTest11); + UtRegisterTest("DetectAppLayerProtocolTest12", DetectAppLayerProtocolTest12); + UtRegisterTest("DetectAppLayerProtocolTest13", DetectAppLayerProtocolTest13); + UtRegisterTest("DetectAppLayerProtocolTest14", DetectAppLayerProtocolTest14); } #endif /* UNITTESTS */ diff --git a/src/detect-asn1.c b/src/detect-asn1.c index 5b3a3a2229b2..b82dd9bb6203 100644 --- a/src/detect-asn1.c +++ b/src/detect-asn1.c @@ -36,9 +36,9 @@ #include "util-byte.h" #include "util-debug.h" -static int DetectAsn1Match(DetectEngineThreadCtx *, Packet *, - const Signature *, const SigMatchCtx *); -static int DetectAsn1Setup (DetectEngineCtx *, Signature *, const char *); +static int DetectAsn1Match( + DetectEngineThreadCtx *, Packet *, const Signature *, const SigMatchCtx *); +static int DetectAsn1Setup(DetectEngineCtx *, Signature *, const char *); #ifdef UNITTESTS static void DetectAsn1RegisterTests(void); #endif @@ -52,7 +52,7 @@ void DetectAsn1Register(void) sigmatch_table[DETECT_ASN1].name = "asn1"; sigmatch_table[DETECT_ASN1].Match = DetectAsn1Match; sigmatch_table[DETECT_ASN1].Setup = DetectAsn1Setup; - sigmatch_table[DETECT_ASN1].Free = DetectAsn1Free; + sigmatch_table[DETECT_ASN1].Free = DetectAsn1Free; #ifdef UNITTESTS sigmatch_table[DETECT_ASN1].RegisterTests = DetectAsn1RegisterTests; #endif @@ -70,8 +70,8 @@ void DetectAsn1Register(void) * \retval 1 match * \retval 0 no match */ -static int DetectAsn1Match(DetectEngineThreadCtx *det_ctx, Packet *p, - const Signature *s, const SigMatchCtx *ctx) +static int DetectAsn1Match( + DetectEngineThreadCtx *det_ctx, Packet *p, const Signature *s, const SigMatchCtx *ctx) { uint8_t ret = 0; @@ -155,42 +155,140 @@ static void DetectAsn1Free(DetectEngineCtx *de_ctx, void *ptr) */ static int DetectAsn1TestReal01(void) { - uint8_t *buf = (uint8_t *) "\x60\x81\x85\x61\x10\x1A\x04""John""\x1A\x01" - "P""\x1A\x05""Smith""\xA0\x0A\x1A\x08""Director" - "\x42\x01\x33\xA1\x0A\x43\x08""19710917" - "\xA2\x12\x61\x10\x1A\x04""Mary""\x1A\x01""T""\x1A\x05" - "Smith""\xA3\x42\x31\x1F\x61\x11\x1A\x05""Ralph""\x1A\x01" - "T""\x1A\x05""Smith""\xA0\x0A\x43\x08""19571111" - "\x31\x1F\x61\x11\x1A\x05""Susan""\x1A\x01""B""\x1A\x05" - "Jones""\xA0\x0A\x43\x08""19590717" - "\x60\x81\x85\x61\x10\x1A\x04""John""\x1A\x01""P" - "\x1A\x05""Smith""\xA0\x0A\x1A\x08""Director" - "\x42\x01\x33\xA1\x0A\x43\x08""19710917" - "\xA2\x12\x61\x10\x1A\x04""Mary""\x1A\x01""T""\x1A\x05" - "Smith""\xA3\x42\x31\x1F\x61\x11\x1A\x05""Ralph""\x1A\x01" - "T""\x1A\x05""Smith""\xA0\x0A\x43\x08""19571111""\x31\x1F" - "\x61\x11\x1A\x05""Pablo""\x1A\x01""B""\x1A\x05""Jones" - "\xA0\x0A\x43\x08""19590717"; + uint8_t *buf = (uint8_t *)"\x60\x81\x85\x61\x10\x1A\x04" + "John" + "\x1A\x01" + "P" + "\x1A\x05" + "Smith" + "\xA0\x0A\x1A\x08" + "Director" + "\x42\x01\x33\xA1\x0A\x43\x08" + "19710917" + "\xA2\x12\x61\x10\x1A\x04" + "Mary" + "\x1A\x01" + "T" + "\x1A\x05" + "Smith" + "\xA3\x42\x31\x1F\x61\x11\x1A\x05" + "Ralph" + "\x1A\x01" + "T" + "\x1A\x05" + "Smith" + "\xA0\x0A\x43\x08" + "19571111" + "\x31\x1F\x61\x11\x1A\x05" + "Susan" + "\x1A\x01" + "B" + "\x1A\x05" + "Jones" + "\xA0\x0A\x43\x08" + "19590717" + "\x60\x81\x85\x61\x10\x1A\x04" + "John" + "\x1A\x01" + "P" + "\x1A\x05" + "Smith" + "\xA0\x0A\x1A\x08" + "Director" + "\x42\x01\x33\xA1\x0A\x43\x08" + "19710917" + "\xA2\x12\x61\x10\x1A\x04" + "Mary" + "\x1A\x01" + "T" + "\x1A\x05" + "Smith" + "\xA3\x42\x31\x1F\x61\x11\x1A\x05" + "Ralph" + "\x1A\x01" + "T" + "\x1A\x05" + "Smith" + "\xA0\x0A\x43\x08" + "19571111" + "\x31\x1F" + "\x61\x11\x1A\x05" + "Pablo" + "\x1A\x01" + "B" + "\x1A\x05" + "Jones" + "\xA0\x0A\x43\x08" + "19590717"; uint16_t buflen = strlen((char *)buf) - 1; /* Check the start with AA (this is to test the relative_offset keyword) */ - uint8_t *buf2 = (uint8_t *) "AA\x60\x81\x85\x61\x10\x1A\x04""John""\x1A\x01" - "P""\x1A\x05""Smith""\xA0\x0A\x1A\x08""Director" - "\x42\x01\x33\xA1\x0A\x43\x08""19710917" - "\xA2\x12\x61\x10\x1A\x04""Mary""\x1A\x01""T""\x1A\x05" - "Smith""\xA3\x42\x31\x1F\x61\x11\x1A\x05""Ralph""\x1A\x01" - "T""\x1A\x05""Smith""\xA0\x0A\x43\x08""19571111" - "\x31\x1F\x61\x11\x1A\x05""Susan""\x1A\x01""B""\x1A\x05" - "Jones""\xA0\x0A\x43\x08""19590717" - "\x60\x81\x85\x61\x10\x1A\x04""John""\x1A\x01""P" - "\x1A\x05""Smith""\xA0\x0A\x1A\x08""Director" - "\x42\x01\x33\xA1\x0A\x43\x08""19710917" - "\xA2\x12\x61\x10\x1A\x04""Mary""\x1A\x01""T""\x1A\x05" - "Smith""\xA3\x42\x31\x1F\x61\x11\x1A\x05""Ralph""\x1A\x01" - "T""\x1A\x05""Smith""\xA0\x0A\x43\x08""19571111""\x31\x1F" - "\x61\x11\x1A\x05""Susan""\x1A\x01""B""\x1A\x05""Jones" - "\xA0\x0A\x43\x08""19590717"; + uint8_t *buf2 = (uint8_t *)"AA\x60\x81\x85\x61\x10\x1A\x04" + "John" + "\x1A\x01" + "P" + "\x1A\x05" + "Smith" + "\xA0\x0A\x1A\x08" + "Director" + "\x42\x01\x33\xA1\x0A\x43\x08" + "19710917" + "\xA2\x12\x61\x10\x1A\x04" + "Mary" + "\x1A\x01" + "T" + "\x1A\x05" + "Smith" + "\xA3\x42\x31\x1F\x61\x11\x1A\x05" + "Ralph" + "\x1A\x01" + "T" + "\x1A\x05" + "Smith" + "\xA0\x0A\x43\x08" + "19571111" + "\x31\x1F\x61\x11\x1A\x05" + "Susan" + "\x1A\x01" + "B" + "\x1A\x05" + "Jones" + "\xA0\x0A\x43\x08" + "19590717" + "\x60\x81\x85\x61\x10\x1A\x04" + "John" + "\x1A\x01" + "P" + "\x1A\x05" + "Smith" + "\xA0\x0A\x1A\x08" + "Director" + "\x42\x01\x33\xA1\x0A\x43\x08" + "19710917" + "\xA2\x12\x61\x10\x1A\x04" + "Mary" + "\x1A\x01" + "T" + "\x1A\x05" + "Smith" + "\xA3\x42\x31\x1F\x61\x11\x1A\x05" + "Ralph" + "\x1A\x01" + "T" + "\x1A\x05" + "Smith" + "\xA0\x0A\x43\x08" + "19571111" + "\x31\x1F" + "\x61\x11\x1A\x05" + "Susan" + "\x1A\x01" + "B" + "\x1A\x05" + "Jones" + "\xA0\x0A\x43\x08" + "19590717"; uint16_t buflen2 = strlen((char *)buf2) - 1; @@ -202,21 +300,21 @@ static int DetectAsn1TestReal01(void) FAIL_IF_NULL(p[1]); const char *sigs[3]; - sigs[0]= "alert ip any any -> any any (msg:\"Testing id 1\"; " - "content:\"Pablo\"; asn1:absolute_offset 0, " - "oversize_length 130; sid:1;)"; - sigs[1]= "alert ip any any -> any any (msg:\"Testing id 2\"; " - "content:\"AA\"; asn1:relative_offset 0, " - "oversize_length 130; sid:2;)"; - sigs[2]= "alert ip any any -> any any (msg:\"Testing id 3\"; " - "content:\"lalala\"; asn1: oversize_length 2000; sid:3;)"; - - uint32_t sid[3] = {1, 2, 3}; - uint32_t results[2][3] = { - /* packet 0 match sid 1 */ - {1, 0, 0}, - /* packet 1 match sid 2 */ - {0, 1, 0}}; + sigs[0] = "alert ip any any -> any any (msg:\"Testing id 1\"; " + "content:\"Pablo\"; asn1:absolute_offset 0, " + "oversize_length 130; sid:1;)"; + sigs[1] = "alert ip any any -> any any (msg:\"Testing id 2\"; " + "content:\"AA\"; asn1:relative_offset 0, " + "oversize_length 130; sid:2;)"; + sigs[2] = "alert ip any any -> any any (msg:\"Testing id 3\"; " + "content:\"lalala\"; asn1: oversize_length 2000; sid:3;)"; + + uint32_t sid[3] = { 1, 2, 3 }; + uint32_t results[2][3] = { /* packet 0 match sid 1 */ + { 1, 0, 0 }, + /* packet 1 match sid 2 */ + { 0, 1, 0 } + }; /* None of the packets should match sid 3 */ FAIL_IF_NOT(UTHGenericTest(p, 2, sigs, sid, (uint32_t *)results, 3) == 1); @@ -230,42 +328,140 @@ static int DetectAsn1TestReal01(void) static int DetectAsn1TestReal02(void) { int result = 0; - uint8_t *buf = (uint8_t *) "\x60\x81\x85\x61\x10\x1A\x04""John""\x1A\x01" - "P""\x1A\x05""Smith""\xA0\x0A\x1A\x08""Director" - "\x42\x01\x33\xA1\x0A\x43\x08""19710917" - "\xA2\x12\x61\x10\x1A\x04""Mary""\x1A\x01""T""\x1A\x05" - "Smith""\xA3\x42\x31\x1F\x61\x11\x1A\x05""Ralph""\x1A\x01" - "T""\x1A\x05""Smith""\xA0\x0A\x43\x08""19571111" - "\x31\x1F\x61\x11\x1A\x05""Susan""\x1A\x01""B""\x1A\x05" - "Jones""\xA0\x0A\x43\x08""19590717" - "\x60\x81\x85\x61\x10\x1A\x04""John""\x1A\x01""P" - "\x1A\x05""Smith""\xA0\x0A\x1A\x08""Director" - "\x42\x01\x33\xA1\x0A\x43\x08""19710917" - "\xA2\x12\x61\x10\x1A\x04""Mary""\x1A\x01""T""\x1A\x05" - "Smith""\xA3\x42\x31\x1F\x61\x11\x1A\x05""Ralph""\x1A\x01" - "T""\x1A\x05""Smith""\xA0\x0A\x43\x08""19571111""\x31\x1F" - "\x61\x11\x1A\x05""Pablo""\x1A\x01""B""\x1A\x05""Jones" - "\xA0\x0A\x43\x08""19590717"; + uint8_t *buf = (uint8_t *)"\x60\x81\x85\x61\x10\x1A\x04" + "John" + "\x1A\x01" + "P" + "\x1A\x05" + "Smith" + "\xA0\x0A\x1A\x08" + "Director" + "\x42\x01\x33\xA1\x0A\x43\x08" + "19710917" + "\xA2\x12\x61\x10\x1A\x04" + "Mary" + "\x1A\x01" + "T" + "\x1A\x05" + "Smith" + "\xA3\x42\x31\x1F\x61\x11\x1A\x05" + "Ralph" + "\x1A\x01" + "T" + "\x1A\x05" + "Smith" + "\xA0\x0A\x43\x08" + "19571111" + "\x31\x1F\x61\x11\x1A\x05" + "Susan" + "\x1A\x01" + "B" + "\x1A\x05" + "Jones" + "\xA0\x0A\x43\x08" + "19590717" + "\x60\x81\x85\x61\x10\x1A\x04" + "John" + "\x1A\x01" + "P" + "\x1A\x05" + "Smith" + "\xA0\x0A\x1A\x08" + "Director" + "\x42\x01\x33\xA1\x0A\x43\x08" + "19710917" + "\xA2\x12\x61\x10\x1A\x04" + "Mary" + "\x1A\x01" + "T" + "\x1A\x05" + "Smith" + "\xA3\x42\x31\x1F\x61\x11\x1A\x05" + "Ralph" + "\x1A\x01" + "T" + "\x1A\x05" + "Smith" + "\xA0\x0A\x43\x08" + "19571111" + "\x31\x1F" + "\x61\x11\x1A\x05" + "Pablo" + "\x1A\x01" + "B" + "\x1A\x05" + "Jones" + "\xA0\x0A\x43\x08" + "19590717"; uint16_t buflen = strlen((char *)buf) - 1; /* Check the start with AA (this is to test the relative_offset keyword) */ - uint8_t *buf2 = (uint8_t *) "AA\x60\x81\x85\x61\x10\x1A\x04""John""\x1A\x01" - "P""\x1A\x05""Smith""\xA0\x0A\x1A\x08""Director" - "\x42\x01\x33\xA1\x0A\x43\x08""19710917" - "\xA2\x12\x61\x10\x1A\x04""Mary""\x1A\x01""T""\x1A\x05" - "Smith""\xA3\x42\x31\x1F\x61\x11\x1A\x05""Ralph""\x1A\x01" - "T""\x1A\x05""Smith""\xA0\x0A\x43\x08""19571111" - "\x31\x1F\x61\x11\x1A\x05""Susan""\x1A\x01""B""\x1A\x05" - "Jones""\xA0\x0A\x43\x08""19590717" - "\x60\x81\x85\x61\x10\x1A\x04""John""\x1A\x01""P" - "\x1A\x05""Smith""\xA0\x0A\x1A\x08""Director" - "\x42\x01\x33\xA1\x0A\x43\x08""19710917" - "\xA2\x12\x61\x10\x1A\x04""Mary""\x1A\x01""T""\x1A\x05" - "Smith""\xA3\x42\x31\x1F\x61\x11\x1A\x05""Ralph""\x1A\x01" - "T""\x1A\x05""Smith""\xA0\x0A\x43\x08""19571111""\x31\x1F" - "\x61\x11\x1A\x05""Susan""\x1A\x01""B""\x1A\x05""Jones" - "\xA0\x0A\x43\x08""19590717"; + uint8_t *buf2 = (uint8_t *)"AA\x60\x81\x85\x61\x10\x1A\x04" + "John" + "\x1A\x01" + "P" + "\x1A\x05" + "Smith" + "\xA0\x0A\x1A\x08" + "Director" + "\x42\x01\x33\xA1\x0A\x43\x08" + "19710917" + "\xA2\x12\x61\x10\x1A\x04" + "Mary" + "\x1A\x01" + "T" + "\x1A\x05" + "Smith" + "\xA3\x42\x31\x1F\x61\x11\x1A\x05" + "Ralph" + "\x1A\x01" + "T" + "\x1A\x05" + "Smith" + "\xA0\x0A\x43\x08" + "19571111" + "\x31\x1F\x61\x11\x1A\x05" + "Susan" + "\x1A\x01" + "B" + "\x1A\x05" + "Jones" + "\xA0\x0A\x43\x08" + "19590717" + "\x60\x81\x85\x61\x10\x1A\x04" + "John" + "\x1A\x01" + "P" + "\x1A\x05" + "Smith" + "\xA0\x0A\x1A\x08" + "Director" + "\x42\x01\x33\xA1\x0A\x43\x08" + "19710917" + "\xA2\x12\x61\x10\x1A\x04" + "Mary" + "\x1A\x01" + "T" + "\x1A\x05" + "Smith" + "\xA3\x42\x31\x1F\x61\x11\x1A\x05" + "Ralph" + "\x1A\x01" + "T" + "\x1A\x05" + "Smith" + "\xA0\x0A\x43\x08" + "19571111" + "\x31\x1F" + "\x61\x11\x1A\x05" + "Susan" + "\x1A\x01" + "B" + "\x1A\x05" + "Jones" + "\xA0\x0A\x43\x08" + "19590717"; uint16_t buflen2 = strlen((char *)buf2) - 1; @@ -278,23 +474,21 @@ static int DetectAsn1TestReal02(void) goto end; const char *sigs[3]; - sigs[0]= "alert ip any any -> any any (msg:\"Testing id 1\"; " - "content:\"Pablo\"; asn1:absolute_offset 0, " - "oversize_length 140; sid:1;)"; - sigs[1]= "alert ip any any -> any any (msg:\"Testing id 2\"; " - "content:\"AA\"; asn1:relative_offset 0, " - "oversize_length 140; sid:2;)"; - sigs[2]= "alert ip any any -> any any (msg:\"Testing id 3\"; " - "content:\"lalala\"; asn1: oversize_length 2000; sid:3;)"; - - uint32_t sid[3] = {1, 2, 3}; - - uint32_t results[2][3] = { - {0, 0, 0}, - {0, 0, 0}}; + sigs[0] = "alert ip any any -> any any (msg:\"Testing id 1\"; " + "content:\"Pablo\"; asn1:absolute_offset 0, " + "oversize_length 140; sid:1;)"; + sigs[1] = "alert ip any any -> any any (msg:\"Testing id 2\"; " + "content:\"AA\"; asn1:relative_offset 0, " + "oversize_length 140; sid:2;)"; + sigs[2] = "alert ip any any -> any any (msg:\"Testing id 3\"; " + "content:\"lalala\"; asn1: oversize_length 2000; sid:3;)"; + + uint32_t sid[3] = { 1, 2, 3 }; + + uint32_t results[2][3] = { { 0, 0, 0 }, { 0, 0, 0 } }; /* None of the packets should match */ - result = UTHGenericTest(p, 2, sigs, sid, (uint32_t *) results, 3); + result = UTHGenericTest(p, 2, sigs, sid, (uint32_t *)results, 3); UTHFreePackets(p, 2); end: @@ -318,13 +512,13 @@ static int DetectAsn1TestReal03(void) /* Fill the content of the number */ uint16_t i = 4; - for (; i < 257;i++) + for (; i < 257; i++) buf[i] = '\x05'; uint16_t buflen = 261; /* Check the start with AA (this is to test the relative_offset keyword) */ - uint8_t *buf2 = (uint8_t *) "AA\x03\x01\xFF"; + uint8_t *buf2 = (uint8_t *)"AA\x03\x01\xFF"; uint16_t buflen2 = 5; @@ -337,23 +531,22 @@ static int DetectAsn1TestReal03(void) goto end; const char *sigs[3]; - /* This should match the first packet */ - sigs[0]= "alert ip any any -> any any (msg:\"Testing id 1\"; " - "asn1:absolute_offset 0, double_overflow; sid:1;)"; - /* This should match the second packet */ - sigs[1]= "alert ip any any -> any any (msg:\"Testing id 2\"; " - "asn1:relative_offset 2, bitstring_overflow," - "oversize_length 140; sid:2;)"; - /* This should match no packet */ - sigs[2]= "alert ip any any -> any any (msg:\"Testing id 3\"; " - "asn1: oversize_length 2000; sid:3;)"; + /* This should match the first packet */ + sigs[0] = "alert ip any any -> any any (msg:\"Testing id 1\"; " + "asn1:absolute_offset 0, double_overflow; sid:1;)"; + /* This should match the second packet */ + sigs[1] = "alert ip any any -> any any (msg:\"Testing id 2\"; " + "asn1:relative_offset 2, bitstring_overflow," + "oversize_length 140; sid:2;)"; + /* This should match no packet */ + sigs[2] = "alert ip any any -> any any (msg:\"Testing id 3\"; " + "asn1: oversize_length 2000; sid:3;)"; - uint32_t sid[3] = {1, 2, 3}; + uint32_t sid[3] = { 1, 2, 3 }; - uint32_t results[2][3] = {{1, 0, 0}, - {0, 1, 0}}; + uint32_t results[2][3] = { { 1, 0, 0 }, { 0, 1, 0 } }; - result = UTHGenericTest(p, 2, sigs, sid, (uint32_t *) results, 3); + result = UTHGenericTest(p, 2, sigs, sid, (uint32_t *)results, 3); UTHFreePackets(p, 2); end: @@ -368,42 +561,140 @@ static int DetectAsn1TestReal03(void) static int DetectAsn1TestReal04(void) { int result = 0; - uint8_t *buf = (uint8_t *) "\x60\x81\x85\x61\x10\x1A\x04""John""\x1A\x01" - "P""\x1A\x05""Smith""\xA0\x0A\x1A\x08""Director" - "\x42\x01\x33\xA1\x0A\x43\x08""19710917" - "\xA2\x12\x61\x10\x1A\x04""Mary""\x1A\x01""T""\x1A\x05" - "Smith""\xA3\x42\x31\x1F\x61\x11\x1A\x05""Ralph""\x1A\x01" - "T""\x1A\x05""Smith""\xA0\x0A\x43\x08""19571111" - "\x31\x1F\x61\x11\x1A\x05""Susan""\x1A\x01""B""\x1A\x05" - "Jones""\xA0\x0A\x43\x08""19590717" - "\x60\x81\x85\x61\x10\x1A\x04""John""\x1A\x01""P" - "\x1A\x05""Smith""\xA0\x0A\x1A\x08""Director" - "\x42\x01\x33\xA1\x0A\x43\x08""19710917" - "\xA2\x12\x61\x10\x1A\x04""Mary""\x1A\x01""T""\x1A\x05" - "Smith""\xA3\x42\x31\x1F\x61\x11\x1A\x05""Ralph""\x1A\x01" - "T""\x1A\x05""Smith""\xA0\x0A\x43\x08""19571111""\x31\x1F" - "\x61\x11\x1A\x05""Pablo""\x1A\x01""B""\x1A\x05""Jones" - "\xA0\x0A\x43\x08""19590717"; + uint8_t *buf = (uint8_t *)"\x60\x81\x85\x61\x10\x1A\x04" + "John" + "\x1A\x01" + "P" + "\x1A\x05" + "Smith" + "\xA0\x0A\x1A\x08" + "Director" + "\x42\x01\x33\xA1\x0A\x43\x08" + "19710917" + "\xA2\x12\x61\x10\x1A\x04" + "Mary" + "\x1A\x01" + "T" + "\x1A\x05" + "Smith" + "\xA3\x42\x31\x1F\x61\x11\x1A\x05" + "Ralph" + "\x1A\x01" + "T" + "\x1A\x05" + "Smith" + "\xA0\x0A\x43\x08" + "19571111" + "\x31\x1F\x61\x11\x1A\x05" + "Susan" + "\x1A\x01" + "B" + "\x1A\x05" + "Jones" + "\xA0\x0A\x43\x08" + "19590717" + "\x60\x81\x85\x61\x10\x1A\x04" + "John" + "\x1A\x01" + "P" + "\x1A\x05" + "Smith" + "\xA0\x0A\x1A\x08" + "Director" + "\x42\x01\x33\xA1\x0A\x43\x08" + "19710917" + "\xA2\x12\x61\x10\x1A\x04" + "Mary" + "\x1A\x01" + "T" + "\x1A\x05" + "Smith" + "\xA3\x42\x31\x1F\x61\x11\x1A\x05" + "Ralph" + "\x1A\x01" + "T" + "\x1A\x05" + "Smith" + "\xA0\x0A\x43\x08" + "19571111" + "\x31\x1F" + "\x61\x11\x1A\x05" + "Pablo" + "\x1A\x01" + "B" + "\x1A\x05" + "Jones" + "\xA0\x0A\x43\x08" + "19590717"; uint16_t buflen = strlen((char *)buf) - 1; /* Check the start with AA (this is to test the relative_offset keyword) */ - uint8_t *buf2 = (uint8_t *) "AA\x60\x81\x85\x61\x10\x1A\x04""John""\x1A\x01" - "P""\x1A\x05""Smith""\xA0\x0A\x1A\x08""Director" - "\x42\x01\x33\xA1\x0A\x43\x08""19710917" - "\xA2\x12\x61\x10\x1A\x04""Mary""\x1A\x01""T""\x1A\x05" - "Smith""\xA3\x42\x31\x1F\x61\x11\x1A\x05""Ralph""\x1A\x01" - "T""\x1A\x05""Smith""\xA0\x0A\x43\x08""19571111" - "\x31\x1F\x61\x11\x1A\x05""Susan""\x1A\x01""B""\x1A\x05" - "Jones""\xA0\x0A\x43\x08""19590717" - "\x60\x81\x85\x61\x10\x1A\x04""John""\x1A\x01""P" - "\x1A\x05""Smith""\xA0\x0A\x1A\x08""Director" - "\x42\x01\x33\xA1\x0A\x43\x08""19710917" - "\xA2\x12\x61\x10\x1A\x04""Mary""\x1A\x01""T""\x1A\x05" - "Smith""\xA3\x42\x31\x1F\x61\x11\x1A\x05""Ralph""\x1A\x01" - "T""\x1A\x05""Smith""\xA0\x0A\x43\x08""19571111""\x31\x1F" - "\x61\x11\x1A\x05""Susan""\x1A\x01""B""\x1A\x05""Jones" - "\xA0\x0A\x43\x08""19590717"; + uint8_t *buf2 = (uint8_t *)"AA\x60\x81\x85\x61\x10\x1A\x04" + "John" + "\x1A\x01" + "P" + "\x1A\x05" + "Smith" + "\xA0\x0A\x1A\x08" + "Director" + "\x42\x01\x33\xA1\x0A\x43\x08" + "19710917" + "\xA2\x12\x61\x10\x1A\x04" + "Mary" + "\x1A\x01" + "T" + "\x1A\x05" + "Smith" + "\xA3\x42\x31\x1F\x61\x11\x1A\x05" + "Ralph" + "\x1A\x01" + "T" + "\x1A\x05" + "Smith" + "\xA0\x0A\x43\x08" + "19571111" + "\x31\x1F\x61\x11\x1A\x05" + "Susan" + "\x1A\x01" + "B" + "\x1A\x05" + "Jones" + "\xA0\x0A\x43\x08" + "19590717" + "\x60\x81\x85\x61\x10\x1A\x04" + "John" + "\x1A\x01" + "P" + "\x1A\x05" + "Smith" + "\xA0\x0A\x1A\x08" + "Director" + "\x42\x01\x33\xA1\x0A\x43\x08" + "19710917" + "\xA2\x12\x61\x10\x1A\x04" + "Mary" + "\x1A\x01" + "T" + "\x1A\x05" + "Smith" + "\xA3\x42\x31\x1F\x61\x11\x1A\x05" + "Ralph" + "\x1A\x01" + "T" + "\x1A\x05" + "Smith" + "\xA0\x0A\x43\x08" + "19571111" + "\x31\x1F" + "\x61\x11\x1A\x05" + "Susan" + "\x1A\x01" + "B" + "\x1A\x05" + "Jones" + "\xA0\x0A\x43\x08" + "19590717"; uint16_t buflen2 = strlen((char *)buf2) - 1; @@ -416,23 +707,21 @@ static int DetectAsn1TestReal04(void) goto end; const char *sigs[3]; - sigs[0]= "alert ip any any -> any any (msg:\"Testing id 1\"; " - "content:\"Pablo\"; asn1:absolute_offset 0, " - "oversize_length 140; sid:1;)"; - sigs[1]= "alert ip any any -> any any (msg:\"Testing id 2\"; " - "content:\"John\"; asn1:relative_offset -11, " - "oversize_length 140; sid:2;)"; - sigs[2]= "alert ip any any -> any any (msg:\"Testing id 3\"; " - "content:\"lalala\"; asn1: oversize_length 2000; sid:3;)"; - - uint32_t sid[3] = {1, 2, 3}; - - uint32_t results[2][3] = { - {0, 0, 0}, - {0, 0, 0}}; + sigs[0] = "alert ip any any -> any any (msg:\"Testing id 1\"; " + "content:\"Pablo\"; asn1:absolute_offset 0, " + "oversize_length 140; sid:1;)"; + sigs[1] = "alert ip any any -> any any (msg:\"Testing id 2\"; " + "content:\"John\"; asn1:relative_offset -11, " + "oversize_length 140; sid:2;)"; + sigs[2] = "alert ip any any -> any any (msg:\"Testing id 3\"; " + "content:\"lalala\"; asn1: oversize_length 2000; sid:3;)"; + + uint32_t sid[3] = { 1, 2, 3 }; + + uint32_t results[2][3] = { { 0, 0, 0 }, { 0, 0, 0 } }; /* None of the packets should match */ - result = UTHGenericTest(p, 2, sigs, sid, (uint32_t *) results, 3); + result = UTHGenericTest(p, 2, sigs, sid, (uint32_t *)results, 3); UTHFreePackets(p, 2); end: diff --git a/src/detect-asn1.h b/src/detect-asn1.h index a7b67340aa27..1b68bf8c2023 100644 --- a/src/detect-asn1.h +++ b/src/detect-asn1.h @@ -24,6 +24,6 @@ #define __DETECT_ASN1_H__ /* prototypes */ -void DetectAsn1Register (void); +void DetectAsn1Register(void); #endif /* __DETECT_ASN1_H__ */ diff --git a/src/detect-base64-data.c b/src/detect-base64-data.c index 09d89113d675..7dcf4f116594 100644 --- a/src/detect-base64-data.c +++ b/src/detect-base64-data.c @@ -33,20 +33,16 @@ static void DetectBase64DataRegisterTests(void); void DetectBase64DataRegister(void) { sigmatch_table[DETECT_BASE64_DATA].name = "base64_data"; - sigmatch_table[DETECT_BASE64_DATA].desc = - "Content match base64 decoded data."; - sigmatch_table[DETECT_BASE64_DATA].url = - "/rules/base64-keywords.html#base64-data"; + sigmatch_table[DETECT_BASE64_DATA].desc = "Content match base64 decoded data."; + sigmatch_table[DETECT_BASE64_DATA].url = "/rules/base64-keywords.html#base64-data"; sigmatch_table[DETECT_BASE64_DATA].Setup = DetectBase64DataSetup; #ifdef UNITTESTS - sigmatch_table[DETECT_BASE64_DATA].RegisterTests = - DetectBase64DataRegisterTests; + sigmatch_table[DETECT_BASE64_DATA].RegisterTests = DetectBase64DataRegisterTests; #endif sigmatch_table[DETECT_BASE64_DATA].flags |= SIGMATCH_NOOPT; } -static int DetectBase64DataSetup(DetectEngineCtx *de_ctx, Signature *s, - const char *str) +static int DetectBase64DataSetup(DetectEngineCtx *de_ctx, Signature *s, const char *str) { SigMatch *pm = NULL; @@ -61,8 +57,8 @@ static int DetectBase64DataSetup(DetectEngineCtx *de_ctx, Signature *s, return 0; } -int DetectBase64DataDoMatch(DetectEngineCtx *de_ctx, - DetectEngineThreadCtx *det_ctx, const Signature *s, Flow *f) +int DetectBase64DataDoMatch( + DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx, const Signature *s, Flow *f) { if (det_ctx->base64_decoded_len) { return DetectEngineContentInspectionInternal(de_ctx, det_ctx, s, @@ -90,9 +86,9 @@ static int DetectBase64DataSetupTest01(void) } de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx, - "alert smtp any any -> any any (msg:\"DetectBase64DataSetupTest\"; " - "base64_decode; base64_data; content:\"content\"; sid:1; rev:1;)"); + de_ctx->sig_list = + SigInit(de_ctx, "alert smtp any any -> any any (msg:\"DetectBase64DataSetupTest\"; " + "base64_decode; base64_data; content:\"content\"; sid:1; rev:1;)"); if (de_ctx->sig_list == NULL) { printf("SigInit failed: "); goto end; @@ -110,7 +106,7 @@ static int DetectBase64DataSetupTest01(void) if (de_ctx->sig_list->init_data->smlists[DETECT_SM_LIST_BASE64_DATA] == NULL) { printf("DETECT_SM_LIST_BASE64_DATA should not be NULL: "); - goto end; + goto end; } retval = 1; @@ -139,7 +135,9 @@ static int DetectBase64DataSetupTest04(void) de_ctx->flags |= DE_QUIET; de_ctx->sig_list = SigInit(de_ctx, - "alert tcp any any -> any any (msg:\"some b64thing\"; flow:established,from_server; file_data; content:\"sometext\"; fast_pattern; base64_decode:relative; base64_data; content:\"foobar\"; nocase; tag:session,120,seconds; sid:1111111; rev:1;)"); + "alert tcp any any -> any any (msg:\"some b64thing\"; flow:established,from_server; " + "file_data; content:\"sometext\"; fast_pattern; base64_decode:relative; base64_data; " + "content:\"foobar\"; nocase; tag:session,120,seconds; sid:1111111; rev:1;)"); if (de_ctx->sig_list == NULL) { printf("SigInit failed: "); goto end; diff --git a/src/detect-base64-data.h b/src/detect-base64-data.h index 38bb93fc0691..4e5196e5f56f 100644 --- a/src/detect-base64-data.h +++ b/src/detect-base64-data.h @@ -19,7 +19,6 @@ #define __DETECT_BASE64_DATA_H__ void DetectBase64DataRegister(void); -int DetectBase64DataDoMatch(DetectEngineCtx *, DetectEngineThreadCtx *, - const Signature *, Flow *); +int DetectBase64DataDoMatch(DetectEngineCtx *, DetectEngineThreadCtx *, const Signature *, Flow *); #endif /* __DETECT_BASE64_DATA_H__ */ diff --git a/src/detect-base64-decode.c b/src/detect-base64-decode.c index 7e3850c5d682..74b314b67e25 100644 --- a/src/detect-base64-decode.c +++ b/src/detect-base64-decode.c @@ -34,8 +34,8 @@ typedef struct DetectBase64Decode_ { } DetectBase64Decode; static const char decode_pattern[] = "\\s*(bytes\\s+(\\d+),?)?" - "\\s*(offset\\s+(\\d+),?)?" - "\\s*(\\w+)?"; + "\\s*(offset\\s+(\\d+),?)?" + "\\s*(\\w+)?"; static DetectParseRegex decode_pcre; @@ -48,15 +48,12 @@ static void DetectBase64DecodeRegisterTests(void); void DetectBase64DecodeRegister(void) { sigmatch_table[DETECT_BASE64_DECODE].name = "base64_decode"; - sigmatch_table[DETECT_BASE64_DECODE].desc = - "Decodes base64 encoded data."; - sigmatch_table[DETECT_BASE64_DECODE].url = - "/rules/base64-keywords.html#base64-decode"; + sigmatch_table[DETECT_BASE64_DECODE].desc = "Decodes base64 encoded data."; + sigmatch_table[DETECT_BASE64_DECODE].url = "/rules/base64-keywords.html#base64-decode"; sigmatch_table[DETECT_BASE64_DECODE].Setup = DetectBase64DecodeSetup; sigmatch_table[DETECT_BASE64_DECODE].Free = DetectBase64DecodeFree; #ifdef UNITTESTS - sigmatch_table[DETECT_BASE64_DECODE].RegisterTests = - DetectBase64DecodeRegisterTests; + sigmatch_table[DETECT_BASE64_DECODE].RegisterTests = DetectBase64DecodeRegisterTests; #endif sigmatch_table[DETECT_BASE64_DECODE].flags |= SIGMATCH_OPTIONAL_OPT; @@ -64,7 +61,7 @@ void DetectBase64DecodeRegister(void) } int DetectBase64DecodeDoMatch(DetectEngineThreadCtx *det_ctx, const Signature *s, - const SigMatchData *smd, const uint8_t *payload, uint32_t payload_len) + const SigMatchData *smd, const uint8_t *payload, uint32_t payload_len) { DetectBase64Decode *data = (DetectBase64Decode *)smd->ctx; int decode_len; @@ -98,8 +95,7 @@ int DetectBase64DecodeDoMatch(DetectEngineThreadCtx *det_ctx, const Signature *s (void)DecodeBase64(det_ctx->base64_decoded, det_ctx->base64_decoded_len_max, payload, decode_len, &consumed, &num_decoded, BASE64_MODE_RFC4648); det_ctx->base64_decoded_len = num_decoded; - SCLogDebug("Decoded %d bytes from base64 data.", - det_ctx->base64_decoded_len); + SCLogDebug("Decoded %d bytes from base64 data.", det_ctx->base64_decoded_len); #if 0 if (det_ctx->base64_decoded_len) { printf("Decoded data:\n"); @@ -111,8 +107,8 @@ int DetectBase64DecodeDoMatch(DetectEngineThreadCtx *det_ctx, const Signature *s return det_ctx->base64_decoded_len > 0; } -static int DetectBase64DecodeParse(const char *str, uint32_t *bytes, - uint32_t *offset, uint8_t *relative) +static int DetectBase64DecodeParse( + const char *str, uint32_t *bytes, uint32_t *offset, uint8_t *relative) { const char *bytes_str = NULL; const char *offset_str = NULL; @@ -137,7 +133,7 @@ static int DetectBase64DecodeParse(const char *str, uint32_t *bytes, goto error; } } - } + } if (pcre_rc >= 5) { if (pcre2_substring_get_bynumber(match, 4, (PCRE2_UCHAR8 **)&offset_str, &pcre2_len) == 0) { @@ -153,8 +149,7 @@ static int DetectBase64DecodeParse(const char *str, uint32_t *bytes, 0) { if (strcmp(relative_str, "relative") == 0) { *relative = 1; - } - else { + } else { SCLogError("Invalid argument: \"%s\"", relative_str); goto error; } @@ -183,8 +178,7 @@ static int DetectBase64DecodeParse(const char *str, uint32_t *bytes, return retval; } -static int DetectBase64DecodeSetup(DetectEngineCtx *de_ctx, Signature *s, - const char *str) +static int DetectBase64DecodeSetup(DetectEngineCtx *de_ctx, Signature *s, const char *str) { uint32_t bytes = 0; uint32_t offset = 0; @@ -208,16 +202,12 @@ static int DetectBase64DecodeSetup(DetectEngineCtx *de_ctx, Signature *s, if (s->init_data->list != DETECT_SM_LIST_NOTSET) { sm_list = s->init_data->list; - } - else { - pm = DetectGetLastSMFromLists(s, - DETECT_CONTENT, DETECT_PCRE, - DETECT_BYTETEST, DETECT_BYTEJUMP, DETECT_BYTE_EXTRACT, - DETECT_ISDATAAT, -1); + } else { + pm = DetectGetLastSMFromLists(s, DETECT_CONTENT, DETECT_PCRE, DETECT_BYTETEST, + DETECT_BYTEJUMP, DETECT_BYTE_EXTRACT, DETECT_ISDATAAT, -1); if (pm == NULL) { sm_list = DETECT_SM_LIST_PMATCH; - } - else { + } else { sm_list = SigMatchListSMBelongsTo(s, pm); if (sm_list < 0) { goto error; @@ -254,7 +244,6 @@ static void DetectBase64DecodeFree(DetectEngineCtx *de_ctx, void *ptr) SCFree(data); } - #ifdef UNITTESTS #include "detect-engine.h" #include "util-unittest.h" @@ -293,24 +282,21 @@ static int DetectBase64TestDecodeParse(void) goto end; } - if (!DetectBase64DecodeParse("bytes 1, offset 2", &bytes, &offset, - &relative)) { + if (!DetectBase64DecodeParse("bytes 1, offset 2", &bytes, &offset, &relative)) { goto end; } if (bytes != 1 || offset != 2 || relative != 0) { goto end; } - if (!DetectBase64DecodeParse("bytes 1, offset 2, relative", &bytes, &offset, - &relative)) { + if (!DetectBase64DecodeParse("bytes 1, offset 2, relative", &bytes, &offset, &relative)) { goto end; } if (bytes != 1 || offset != 2 || relative != 1) { goto end; } - if (!DetectBase64DecodeParse("offset 2, relative", &bytes, &offset, - &relative)) { + if (!DetectBase64DecodeParse("offset 2, relative", &bytes, &offset, &relative)) { goto end; } if (bytes != 0 || offset != 2 || relative != 1) { @@ -318,20 +304,17 @@ static int DetectBase64TestDecodeParse(void) } /* Misspelled relative. */ - if (DetectBase64DecodeParse("bytes 1, offset 2, relatve", &bytes, &offset, - &relative)) { + if (DetectBase64DecodeParse("bytes 1, offset 2, relatve", &bytes, &offset, &relative)) { goto end; } /* Misspelled bytes. */ - if (DetectBase64DecodeParse("byts 1, offset 2, relatve", &bytes, &offset, - &relative)) { + if (DetectBase64DecodeParse("byts 1, offset 2, relatve", &bytes, &offset, &relative)) { goto end; } /* Misspelled offset. */ - if (DetectBase64DecodeParse("bytes 1, offst 2, relatve", &bytes, &offset, - &relative)) { + if (DetectBase64DecodeParse("bytes 1, offst 2, relatve", &bytes, &offset, &relative)) { goto end; } @@ -384,10 +367,9 @@ static int DetectBase64DecodeTestDecode(void) goto end; } - de_ctx->sig_list = SigInit(de_ctx, - "alert tcp any any -> any any (msg:\"base64 test\"; " - "base64_decode; " - "sid:1; rev:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any (msg:\"base64 test\"; " + "base64_decode; " + "sid:1; rev:1;)"); if (de_ctx->sig_list == NULL) { goto end; } @@ -443,10 +425,9 @@ static int DetectBase64DecodeTestDecodeWithOffset(void) goto end; } - de_ctx->sig_list = SigInit(de_ctx, - "alert tcp any any -> any any (msg:\"base64 test\"; " - "base64_decode: offset 8; " - "sid:1; rev:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any (msg:\"base64 test\"; " + "base64_decode: offset 8; " + "sid:1; rev:1;)"); if (de_ctx->sig_list == NULL) { goto end; } @@ -504,10 +485,9 @@ static int DetectBase64DecodeTestDecodeLargeOffset(void) } /* Offset is out of range. */ - de_ctx->sig_list = SigInit(de_ctx, - "alert tcp any any -> any any (msg:\"base64 test\"; " - "base64_decode: bytes 16, offset 32; " - "sid:1; rev:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any (msg:\"base64 test\"; " + "base64_decode: bytes 16, offset 32; " + "sid:1; rev:1;)"); if (de_ctx->sig_list == NULL) { goto end; } @@ -563,11 +543,10 @@ static int DetectBase64DecodeTestDecodeRelative(void) goto end; } - de_ctx->sig_list = SigInit(de_ctx, - "alert tcp any any -> any any (msg:\"base64 test\"; " - "content:\"aaaaaaaa\"; " - "base64_decode: relative; " - "sid:1; rev:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any (msg:\"base64 test\"; " + "content:\"aaaaaaaa\"; " + "base64_decode: relative; " + "sid:1; rev:1;)"); if (de_ctx->sig_list == NULL) { goto end; } @@ -609,13 +588,11 @@ static void DetectBase64DecodeRegisterTests(void) UtRegisterTest("DetectBase64TestDecodeParse", DetectBase64TestDecodeParse); UtRegisterTest("DetectBase64DecodeTestSetup", DetectBase64DecodeTestSetup); - UtRegisterTest("DetectBase64DecodeTestDecode", - DetectBase64DecodeTestDecode); - UtRegisterTest("DetectBase64DecodeTestDecodeWithOffset", - DetectBase64DecodeTestDecodeWithOffset); - UtRegisterTest("DetectBase64DecodeTestDecodeLargeOffset", - DetectBase64DecodeTestDecodeLargeOffset); - UtRegisterTest("DetectBase64DecodeTestDecodeRelative", - DetectBase64DecodeTestDecodeRelative); + UtRegisterTest("DetectBase64DecodeTestDecode", DetectBase64DecodeTestDecode); + UtRegisterTest( + "DetectBase64DecodeTestDecodeWithOffset", DetectBase64DecodeTestDecodeWithOffset); + UtRegisterTest( + "DetectBase64DecodeTestDecodeLargeOffset", DetectBase64DecodeTestDecodeLargeOffset); + UtRegisterTest("DetectBase64DecodeTestDecodeRelative", DetectBase64DecodeTestDecodeRelative); } #endif /* UNITTESTS */ diff --git a/src/detect-base64-decode.h b/src/detect-base64-decode.h index 58f4e526884c..9cd12f89e8fe 100644 --- a/src/detect-base64-decode.h +++ b/src/detect-base64-decode.h @@ -19,7 +19,7 @@ #define __DETECT_BASE64_DECODE_H__ void DetectBase64DecodeRegister(void); -int DetectBase64DecodeDoMatch(DetectEngineThreadCtx *, const Signature *, - const SigMatchData *, const uint8_t *, uint32_t); +int DetectBase64DecodeDoMatch(DetectEngineThreadCtx *, const Signature *, const SigMatchData *, + const uint8_t *, uint32_t); #endif /* __DETECT_BASE64_DECODE_H__ */ diff --git a/src/detect-bsize.c b/src/detect-bsize.c index f69e20851839..4d678e0f490f 100644 --- a/src/detect-bsize.c +++ b/src/detect-bsize.c @@ -38,11 +38,11 @@ #include "util-misc.h" /*prototypes*/ -static int DetectBsizeSetup (DetectEngineCtx *, Signature *, const char *); -static void DetectBsizeFree (DetectEngineCtx *, void *); +static int DetectBsizeSetup(DetectEngineCtx *, Signature *, const char *); +static void DetectBsizeFree(DetectEngineCtx *, void *); static int SigParseGetMaxBsize(DetectU64Data *bsz); #ifdef UNITTESTS -static void DetectBsizeRegisterTests (void); +static void DetectBsizeRegisterTests(void); #endif bool DetectBsizeValidateContentCallback(Signature *s, const SignatureInitDataBuffer *b) @@ -196,7 +196,7 @@ static int SigParseGetMaxBsize(DetectU64Data *bsz) * \retval 0 on Success * \retval -1 on Failure */ -static int DetectBsizeSetup (DetectEngineCtx *de_ctx, Signature *s, const char *sizestr) +static int DetectBsizeSetup(DetectEngineCtx *de_ctx, Signature *s, const char *sizestr) { SCEnter(); diff --git a/src/detect-bsize.h b/src/detect-bsize.h index ac0b72e5893d..f6758fe64ce7 100644 --- a/src/detect-bsize.h +++ b/src/detect-bsize.h @@ -22,7 +22,7 @@ */ #ifndef __DETECT_BSIZE_H__ -#define __DETECT_BSIZE_H__ +#define __DETECT_BSIZE_H__ void DetectBsizeRegister(void); int DetectBsizeMatch(const SigMatchCtx *ctx, const uint64_t buffer_size, bool eof); diff --git a/src/detect-bypass.c b/src/detect-bypass.c index 51c5d2835160..3463304b798f 100644 --- a/src/detect-bypass.c +++ b/src/detect-bypass.c @@ -49,8 +49,8 @@ #include "util-unittest-helper.h" #include "util-device.h" -static int DetectBypassMatch(DetectEngineThreadCtx *, Packet *, - const Signature *, const SigMatchCtx *); +static int DetectBypassMatch( + DetectEngineThreadCtx *, Packet *, const Signature *, const SigMatchCtx *); static int DetectBypassSetup(DetectEngineCtx *, Signature *, const char *); /** @@ -59,11 +59,12 @@ static int DetectBypassSetup(DetectEngineCtx *, Signature *, const char *); void DetectBypassRegister(void) { sigmatch_table[DETECT_BYPASS].name = "bypass"; - sigmatch_table[DETECT_BYPASS].desc = "call the bypass callback when the match of a sig is complete"; + sigmatch_table[DETECT_BYPASS].desc = + "call the bypass callback when the match of a sig is complete"; sigmatch_table[DETECT_BYPASS].url = "/rules/bypass-keyword.html"; sigmatch_table[DETECT_BYPASS].Match = DetectBypassMatch; sigmatch_table[DETECT_BYPASS].Setup = DetectBypassSetup; - sigmatch_table[DETECT_BYPASS].Free = NULL; + sigmatch_table[DETECT_BYPASS].Free = NULL; sigmatch_table[DETECT_BYPASS].flags = SIGMATCH_NOOPT; } @@ -83,8 +84,8 @@ static int DetectBypassSetup(DetectEngineCtx *de_ctx, Signature *s, const char * return 0; } -static int DetectBypassMatch(DetectEngineThreadCtx *det_ctx, Packet *p, - const Signature *s, const SigMatchCtx *ctx) +static int DetectBypassMatch( + DetectEngineThreadCtx *det_ctx, Packet *p, const Signature *s, const SigMatchCtx *ctx) { PacketBypassCallback(p); diff --git a/src/detect-byte-extract.c b/src/detect-byte-extract.c index cf9b24348e5e..12fb8881dd0b 100644 --- a/src/detect-byte-extract.c +++ b/src/detect-byte-extract.c @@ -58,7 +58,7 @@ #define DETECT_BYTE_EXTRACT_BASE_NONE 0 #define DETECT_BYTE_EXTRACT_BASE_HEX 16 #define DETECT_BYTE_EXTRACT_BASE_DEC 10 -#define DETECT_BYTE_EXTRACT_BASE_OCT 8 +#define DETECT_BYTE_EXTRACT_BASE_OCT 8 /* the default value for multiplier. Either ways we always store a * multiplier, 1 or otherwise, so that we can always multiply the extracted @@ -76,15 +76,16 @@ /* the max no of bytes that can be extracted in non-string mode */ #define NO_STRING_MAX_BYTES_TO_EXTRACT 8 -#define PARSE_REGEX "^" \ - "\\s*([0-9]+)\\s*" \ - ",\\s*(-?[0-9]+)\\s*" \ - ",\\s*([^\\s,]+)\\s*" \ - "(?:(?:,\\s*([^\\s,]+)\\s*)|(?:,\\s*([^\\s,]+)\\s+([^\\s,]+)\\s*))?" \ - "(?:(?:,\\s*([^\\s,]+)\\s*)|(?:,\\s*([^\\s,]+)\\s+([^\\s,]+)\\s*))?" \ - "(?:(?:,\\s*([^\\s,]+)\\s*)|(?:,\\s*([^\\s,]+)\\s+([^\\s,]+)\\s*))?" \ - "(?:(?:,\\s*([^\\s,]+)\\s*)|(?:,\\s*([^\\s,]+)\\s+([^\\s,]+)\\s*))?" \ - "(?:(?:,\\s*([^\\s,]+)\\s*)|(?:,\\s*([^\\s,]+)\\s+([^\\s,]+)\\s*))?" \ +#define PARSE_REGEX \ + "^" \ + "\\s*([0-9]+)\\s*" \ + ",\\s*(-?[0-9]+)\\s*" \ + ",\\s*([^\\s,]+)\\s*" \ + "(?:(?:,\\s*([^\\s,]+)\\s*)|(?:,\\s*([^\\s,]+)\\s+([^\\s,]+)\\s*))?" \ + "(?:(?:,\\s*([^\\s,]+)\\s*)|(?:,\\s*([^\\s,]+)\\s+([^\\s,]+)\\s*))?" \ + "(?:(?:,\\s*([^\\s,]+)\\s*)|(?:,\\s*([^\\s,]+)\\s+([^\\s,]+)\\s*))?" \ + "(?:(?:,\\s*([^\\s,]+)\\s*)|(?:,\\s*([^\\s,]+)\\s+([^\\s,]+)\\s*))?" \ + "(?:(?:,\\s*([^\\s,]+)\\s*)|(?:,\\s*([^\\s,]+)\\s+([^\\s,]+)\\s*))?" \ "$" static DetectParseRegex parse_regex; @@ -101,7 +102,8 @@ static void DetectByteExtractFree(DetectEngineCtx *, void *); void DetectByteExtractRegister(void) { sigmatch_table[DETECT_BYTE_EXTRACT].name = "byte_extract"; - sigmatch_table[DETECT_BYTE_EXTRACT].desc = "extract at a particular and store it in "; + sigmatch_table[DETECT_BYTE_EXTRACT].desc = + "extract at a particular and store it in "; sigmatch_table[DETECT_BYTE_EXTRACT].url = "/rules/payload-keywords.html#byte-extract"; sigmatch_table[DETECT_BYTE_EXTRACT].Match = NULL; sigmatch_table[DETECT_BYTE_EXTRACT].Setup = DetectByteExtractSetup; @@ -130,8 +132,9 @@ int DetectByteExtractDoMatch(DetectEngineThreadCtx *det_ctx, const SigMatchData * the packet from that point. */ if (data->flags & DETECT_BYTE_EXTRACT_FLAG_RELATIVE) { - SCLogDebug("relative, working with det_ctx->buffer_offset %"PRIu32", " - "data->offset %"PRIu32"", det_ctx->buffer_offset, data->offset); + SCLogDebug("relative, working with det_ctx->buffer_offset %" PRIu32 ", " + "data->offset %" PRIu32 "", + det_ctx->buffer_offset, data->offset); ptr = payload + det_ctx->buffer_offset; len = payload_len - det_ctx->buffer_offset; @@ -143,9 +146,9 @@ int DetectByteExtractDoMatch(DetectEngineThreadCtx *det_ctx, const SigMatchData if (len <= 0) { return 0; } - //PrintRawDataFp(stdout,ptr,len); + // PrintRawDataFp(stdout,ptr,len); } else { - SCLogDebug("absolute, data->offset %"PRIu32"", data->offset); + SCLogDebug("absolute, data->offset %" PRIu32 "", data->offset); ptr = payload + data->offset; len = payload_len - data->offset; @@ -153,33 +156,30 @@ int DetectByteExtractDoMatch(DetectEngineThreadCtx *det_ctx, const SigMatchData /* Validate that the to-be-extracted is within the packet */ if (ptr < payload || data->nbytes > len) { - SCLogDebug("Data not within payload pkt=%p, ptr=%p, len=%"PRIu32", nbytes=%d", - payload, ptr, len, data->nbytes); + SCLogDebug("Data not within payload pkt=%p, ptr=%p, len=%" PRIu32 ", nbytes=%d", payload, + ptr, len, data->nbytes); return 0; } /* Extract the byte data */ if (data->flags & DETECT_BYTE_EXTRACT_FLAG_STRING) { - extbytes = ByteExtractStringUint64(&val, data->base, - data->nbytes, (const char *)ptr); + extbytes = ByteExtractStringUint64(&val, data->base, data->nbytes, (const char *)ptr); if (extbytes <= 0) { /* strtoull() return 0 if there is no numeric value in data string */ if (val == 0) { SCLogDebug("No Numeric value"); return 0; } else { - SCLogDebug("error extracting %d bytes of string data: %d", - data->nbytes, extbytes); + SCLogDebug("error extracting %d bytes of string data: %d", data->nbytes, extbytes); return -1; } } } else { - int endianness = (endian == DETECT_BYTE_EXTRACT_ENDIAN_BIG) ? - BYTE_BIG_ENDIAN : BYTE_LITTLE_ENDIAN; + int endianness = + (endian == DETECT_BYTE_EXTRACT_ENDIAN_BIG) ? BYTE_BIG_ENDIAN : BYTE_LITTLE_ENDIAN; extbytes = ByteExtractUint64(&val, endianness, data->nbytes, ptr); if (extbytes != data->nbytes) { - SCLogDebug("error extracting %d bytes of numeric data: %d", - data->nbytes, extbytes); + SCLogDebug("error extracting %d bytes of numeric data: %d", data->nbytes, extbytes); return 0; } } @@ -197,7 +197,7 @@ int DetectByteExtractDoMatch(DetectEngineThreadCtx *det_ctx, const SigMatchData det_ctx->buffer_offset = ptr - payload; *value = val; - SCLogDebug("extracted value is %"PRIu64, val); + SCLogDebug("extracted value is %" PRIu64, val); return 1; } @@ -211,7 +211,8 @@ int DetectByteExtractDoMatch(DetectEngineThreadCtx *det_ctx, const SigMatchData * \param bed On success an instance containing the parsed data. * On failure, NULL. */ -static inline DetectByteExtractData *DetectByteExtractParse(DetectEngineCtx *de_ctx, const char *arg) +static inline DetectByteExtractData *DetectByteExtractParse( + DetectEngineCtx *de_ctx, const char *arg) { DetectByteExtractData *bed = NULL; int res = 0; @@ -241,8 +242,7 @@ static inline DetectByteExtractData *DetectByteExtractParse(DetectEngineCtx *de_ "for arg 1 for byte_extract"); goto error; } - if (StringParseUint8(&bed->nbytes, 10, 0, - (const char *)nbytes_str) < 0) { + if (StringParseUint8(&bed->nbytes, 10, 0, (const char *)nbytes_str) < 0) { SCLogError("Invalid value for number of bytes" " to be extracted: \"%s\".", nbytes_str); @@ -420,8 +420,7 @@ static inline DetectByteExtractData *DetectByteExtractParse(DetectEngineCtx *de_ i); goto error; } - if (StringParseUint8(&bed->align_value, 10, 0, - (const char *)align_str) < 0) { + if (StringParseUint8(&bed->align_value, 10, 0, (const char *)align_str) < 0) { SCLogError("Invalid align_value: " "\"%s\".", align_str); @@ -506,7 +505,7 @@ static inline DetectByteExtractData *DetectByteExtractParse(DetectEngineCtx *de_ pcre2_match_data_free(match); return bed; - error: +error: if (bed != NULL) DetectByteExtractFree(de_ctx, bed); if (match) { @@ -547,9 +546,8 @@ static int DetectByteExtractSetup(DetectEngineCtx *de_ctx, Signature *s, const c } } else if (data->endian == DETECT_BYTE_EXTRACT_ENDIAN_DCE) { if (data->flags & DETECT_BYTE_EXTRACT_FLAG_RELATIVE) { - prev_pm = DetectGetLastSMFromLists(s, DETECT_CONTENT, DETECT_PCRE, - DETECT_BYTETEST, DETECT_BYTEJUMP, DETECT_BYTE_EXTRACT, - DETECT_BYTEMATH, DETECT_ISDATAAT, -1); + prev_pm = DetectGetLastSMFromLists(s, DETECT_CONTENT, DETECT_PCRE, DETECT_BYTETEST, + DETECT_BYTEJUMP, DETECT_BYTE_EXTRACT, DETECT_BYTEMATH, DETECT_ISDATAAT, -1); if (prev_pm == NULL) { sm_list = DETECT_SM_LIST_PMATCH; } else { @@ -566,10 +564,8 @@ static int DetectByteExtractSetup(DetectEngineCtx *de_ctx, Signature *s, const c s->flags |= SIG_FLAG_APPLAYER; } else if (data->flags & DETECT_BYTE_EXTRACT_FLAG_RELATIVE) { - prev_pm = DetectGetLastSMFromLists(s, - DETECT_CONTENT, DETECT_PCRE, - DETECT_BYTETEST, DETECT_BYTEJUMP, DETECT_BYTE_EXTRACT, - DETECT_BYTEMATH, DETECT_ISDATAAT, -1); + prev_pm = DetectGetLastSMFromLists(s, DETECT_CONTENT, DETECT_PCRE, DETECT_BYTETEST, + DETECT_BYTEJUMP, DETECT_BYTE_EXTRACT, DETECT_BYTEMATH, DETECT_ISDATAAT, -1); if (prev_pm == NULL) { sm_list = DETECT_SM_LIST_PMATCH; } else { @@ -589,17 +585,16 @@ static int DetectByteExtractSetup(DetectEngineCtx *de_ctx, Signature *s, const c goto error; if ((data->flags & DETECT_BYTE_EXTRACT_FLAG_STRING) || - (data->base == DETECT_BYTE_EXTRACT_BASE_DEC) || - (data->base == DETECT_BYTE_EXTRACT_BASE_HEX) || - (data->base == DETECT_BYTE_EXTRACT_BASE_OCT) ) { + (data->base == DETECT_BYTE_EXTRACT_BASE_DEC) || + (data->base == DETECT_BYTE_EXTRACT_BASE_HEX) || + (data->base == DETECT_BYTE_EXTRACT_BASE_OCT)) { SCLogError("Invalid option. " "A byte_jump keyword with dce holds other invalid modifiers."); goto error; } } - SigMatch *prev_bed_sm = DetectGetLastSMByListId(s, sm_list, - DETECT_BYTE_EXTRACT, -1); + SigMatch *prev_bed_sm = DetectGetLastSMByListId(s, sm_list, DETECT_BYTE_EXTRACT, -1); if (prev_bed_sm == NULL) data->local_id = 0; else @@ -626,10 +621,10 @@ static int DetectByteExtractSetup(DetectEngineCtx *de_ctx, Signature *s, const c pd->flags |= DETECT_PCRE_RELATIVE_NEXT; } - okay: +okay: ret = 0; return ret; - error: +error: DetectByteExtractFree(de_ctx, data); return ret; } @@ -705,19 +700,15 @@ static int DetectByteExtractTest01(void) if (bed == NULL) goto end; - if (bed->nbytes != 4 || - bed->offset != 2 || - strcmp(bed->name, "one") != 0 || - bed->flags != 0 || - bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_DEFAULT || - bed->base != DETECT_BYTE_EXTRACT_BASE_NONE || - bed->align_value != 0 || - bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { + if (bed->nbytes != 4 || bed->offset != 2 || strcmp(bed->name, "one") != 0 || bed->flags != 0 || + bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_DEFAULT || + bed->base != DETECT_BYTE_EXTRACT_BASE_NONE || bed->align_value != 0 || + bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { goto end; } result = 1; - end: +end: if (bed != NULL) DetectByteExtractFree(NULL, bed); return result; @@ -731,19 +722,16 @@ static int DetectByteExtractTest02(void) if (bed == NULL) goto end; - if (bed->nbytes != 4 || - bed->offset != 2 || - strcmp(bed->name, "one") != 0 || - bed->flags != DETECT_BYTE_EXTRACT_FLAG_RELATIVE || - bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_DEFAULT || - bed->base != DETECT_BYTE_EXTRACT_BASE_NONE || - bed->align_value != 0 || - bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { + if (bed->nbytes != 4 || bed->offset != 2 || strcmp(bed->name, "one") != 0 || + bed->flags != DETECT_BYTE_EXTRACT_FLAG_RELATIVE || + bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_DEFAULT || + bed->base != DETECT_BYTE_EXTRACT_BASE_NONE || bed->align_value != 0 || + bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { goto end; } result = 1; - end: +end: if (bed != NULL) DetectByteExtractFree(NULL, bed); return result; @@ -757,19 +745,16 @@ static int DetectByteExtractTest03(void) if (bed == NULL) goto end; - if (bed->nbytes != 4 || - bed->offset != 2 || - strcmp(bed->name, "one") != 0 || - bed->flags != DETECT_BYTE_EXTRACT_FLAG_MULTIPLIER || - bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_DEFAULT || - bed->base != DETECT_BYTE_EXTRACT_BASE_NONE || - bed->align_value != 0 || - bed->multiplier_value != 10) { + if (bed->nbytes != 4 || bed->offset != 2 || strcmp(bed->name, "one") != 0 || + bed->flags != DETECT_BYTE_EXTRACT_FLAG_MULTIPLIER || + bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_DEFAULT || + bed->base != DETECT_BYTE_EXTRACT_BASE_NONE || bed->align_value != 0 || + bed->multiplier_value != 10) { goto end; } result = 1; - end: +end: if (bed != NULL) DetectByteExtractFree(NULL, bed); return result; @@ -783,20 +768,17 @@ static int DetectByteExtractTest04(void) if (bed == NULL) goto end; - if (bed->nbytes != 4 || - bed->offset != 2 || - strcmp(bed->name, "one") != 0 || - bed->flags != (DETECT_BYTE_EXTRACT_FLAG_RELATIVE | - DETECT_BYTE_EXTRACT_FLAG_MULTIPLIER) || - bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_DEFAULT || - bed->base != DETECT_BYTE_EXTRACT_BASE_NONE || - bed->align_value != 0 || - bed->multiplier_value != 10) { + if (bed->nbytes != 4 || bed->offset != 2 || strcmp(bed->name, "one") != 0 || + bed->flags != + (DETECT_BYTE_EXTRACT_FLAG_RELATIVE | DETECT_BYTE_EXTRACT_FLAG_MULTIPLIER) || + bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_DEFAULT || + bed->base != DETECT_BYTE_EXTRACT_BASE_NONE || bed->align_value != 0 || + bed->multiplier_value != 10) { goto end; } result = 1; - end: +end: if (bed != NULL) DetectByteExtractFree(NULL, bed); return result; @@ -810,19 +792,16 @@ static int DetectByteExtractTest05(void) if (bed == NULL) goto end; - if (bed->nbytes != 4 || - bed->offset != 2 || - strcmp(bed->name, "one") != 0 || - bed->flags != DETECT_BYTE_EXTRACT_FLAG_ENDIAN || - bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_BIG || - bed->base != DETECT_BYTE_EXTRACT_BASE_NONE || - bed->align_value != 0 || - bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { + if (bed->nbytes != 4 || bed->offset != 2 || strcmp(bed->name, "one") != 0 || + bed->flags != DETECT_BYTE_EXTRACT_FLAG_ENDIAN || + bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_BIG || + bed->base != DETECT_BYTE_EXTRACT_BASE_NONE || bed->align_value != 0 || + bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { goto end; } result = 1; - end: +end: if (bed != NULL) DetectByteExtractFree(NULL, bed); return result; @@ -836,19 +815,16 @@ static int DetectByteExtractTest06(void) if (bed == NULL) goto end; - if (bed->nbytes != 4 || - bed->offset != 2 || - strcmp(bed->name, "one") != 0 || - bed->flags != DETECT_BYTE_EXTRACT_FLAG_ENDIAN || - bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_LITTLE || - bed->base != DETECT_BYTE_EXTRACT_BASE_NONE || - bed->align_value != 0 || - bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { + if (bed->nbytes != 4 || bed->offset != 2 || strcmp(bed->name, "one") != 0 || + bed->flags != DETECT_BYTE_EXTRACT_FLAG_ENDIAN || + bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_LITTLE || + bed->base != DETECT_BYTE_EXTRACT_BASE_NONE || bed->align_value != 0 || + bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { goto end; } result = 1; - end: +end: if (bed != NULL) DetectByteExtractFree(NULL, bed); return result; @@ -862,19 +838,16 @@ static int DetectByteExtractTest07(void) if (bed == NULL) goto end; - if (bed->nbytes != 4 || - bed->offset != 2 || - strcmp(bed->name, "one") != 0 || - bed->flags != DETECT_BYTE_EXTRACT_FLAG_ENDIAN || - bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_DCE || - bed->base != DETECT_BYTE_EXTRACT_BASE_NONE || - bed->align_value != 0 || - bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { + if (bed->nbytes != 4 || bed->offset != 2 || strcmp(bed->name, "one") != 0 || + bed->flags != DETECT_BYTE_EXTRACT_FLAG_ENDIAN || + bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_DCE || + bed->base != DETECT_BYTE_EXTRACT_BASE_NONE || bed->align_value != 0 || + bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { goto end; } result = 1; - end: +end: if (bed != NULL) DetectByteExtractFree(NULL, bed); return result; @@ -888,19 +861,16 @@ static int DetectByteExtractTest08(void) if (bed == NULL) goto end; - if (bed->nbytes != 4 || - bed->offset != 2 || - strcmp(bed->name, "one") != 0 || - bed->flags != DETECT_BYTE_EXTRACT_FLAG_STRING || - bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE || - bed->base != DETECT_BYTE_EXTRACT_BASE_HEX || - bed->align_value != 0 || - bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { + if (bed->nbytes != 4 || bed->offset != 2 || strcmp(bed->name, "one") != 0 || + bed->flags != DETECT_BYTE_EXTRACT_FLAG_STRING || + bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE || + bed->base != DETECT_BYTE_EXTRACT_BASE_HEX || bed->align_value != 0 || + bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { goto end; } result = 1; - end: +end: if (bed != NULL) DetectByteExtractFree(NULL, bed); return result; @@ -914,19 +884,16 @@ static int DetectByteExtractTest09(void) if (bed == NULL) goto end; - if (bed->nbytes != 4 || - bed->offset != 2 || - strcmp(bed->name, "one") != 0 || - bed->flags != DETECT_BYTE_EXTRACT_FLAG_STRING || - bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE || - bed->base != DETECT_BYTE_EXTRACT_BASE_OCT || - bed->align_value != 0 || - bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { + if (bed->nbytes != 4 || bed->offset != 2 || strcmp(bed->name, "one") != 0 || + bed->flags != DETECT_BYTE_EXTRACT_FLAG_STRING || + bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE || + bed->base != DETECT_BYTE_EXTRACT_BASE_OCT || bed->align_value != 0 || + bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { goto end; } result = 1; - end: +end: if (bed != NULL) DetectByteExtractFree(NULL, bed); return result; @@ -940,19 +907,16 @@ static int DetectByteExtractTest10(void) if (bed == NULL) goto end; - if (bed->nbytes != 4 || - bed->offset != 2 || - strcmp(bed->name, "one") != 0 || - bed->flags != DETECT_BYTE_EXTRACT_FLAG_STRING || - bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE || - bed->base != DETECT_BYTE_EXTRACT_BASE_DEC || - bed->align_value != 0 || - bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { + if (bed->nbytes != 4 || bed->offset != 2 || strcmp(bed->name, "one") != 0 || + bed->flags != DETECT_BYTE_EXTRACT_FLAG_STRING || + bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE || + bed->base != DETECT_BYTE_EXTRACT_BASE_DEC || bed->align_value != 0 || + bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { goto end; } result = 1; - end: +end: if (bed != NULL) DetectByteExtractFree(NULL, bed); return result; @@ -966,19 +930,16 @@ static int DetectByteExtractTest11(void) if (bed == NULL) goto end; - if (bed->nbytes != 4 || - bed->offset != 2 || - strcmp(bed->name, "one") != 0 || - bed->flags != DETECT_BYTE_EXTRACT_FLAG_ALIGN || - bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_DEFAULT || - bed->base != DETECT_BYTE_EXTRACT_BASE_NONE || - bed->align_value != 4 || - bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { + if (bed->nbytes != 4 || bed->offset != 2 || strcmp(bed->name, "one") != 0 || + bed->flags != DETECT_BYTE_EXTRACT_FLAG_ALIGN || + bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_DEFAULT || + bed->base != DETECT_BYTE_EXTRACT_BASE_NONE || bed->align_value != 4 || + bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { goto end; } result = 1; - end: +end: if (bed != NULL) DetectByteExtractFree(NULL, bed); return result; @@ -992,20 +953,16 @@ static int DetectByteExtractTest12(void) if (bed == NULL) goto end; - if (bed->nbytes != 4 || - bed->offset != 2 || - strcmp(bed->name, "one") != 0 || - bed->flags != (DETECT_BYTE_EXTRACT_FLAG_ALIGN | - DETECT_BYTE_EXTRACT_FLAG_RELATIVE) || - bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_DEFAULT || - bed->base != DETECT_BYTE_EXTRACT_BASE_NONE || - bed->align_value != 4 || - bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { + if (bed->nbytes != 4 || bed->offset != 2 || strcmp(bed->name, "one") != 0 || + bed->flags != (DETECT_BYTE_EXTRACT_FLAG_ALIGN | DETECT_BYTE_EXTRACT_FLAG_RELATIVE) || + bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_DEFAULT || + bed->base != DETECT_BYTE_EXTRACT_BASE_NONE || bed->align_value != 4 || + bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { goto end; } result = 1; - end: +end: if (bed != NULL) DetectByteExtractFree(NULL, bed); return result; @@ -1019,21 +976,17 @@ static int DetectByteExtractTest13(void) if (bed == NULL) goto end; - if (bed->nbytes != 4 || - bed->offset != 2 || - strcmp(bed->name, "one") != 0 || - bed->flags != (DETECT_BYTE_EXTRACT_FLAG_ALIGN | - DETECT_BYTE_EXTRACT_FLAG_ENDIAN | - DETECT_BYTE_EXTRACT_FLAG_RELATIVE) || - bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_BIG || - bed->base != DETECT_BYTE_EXTRACT_BASE_NONE || - bed->align_value != 4 || - bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { + if (bed->nbytes != 4 || bed->offset != 2 || strcmp(bed->name, "one") != 0 || + bed->flags != (DETECT_BYTE_EXTRACT_FLAG_ALIGN | DETECT_BYTE_EXTRACT_FLAG_ENDIAN | + DETECT_BYTE_EXTRACT_FLAG_RELATIVE) || + bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_BIG || + bed->base != DETECT_BYTE_EXTRACT_BASE_NONE || bed->align_value != 4 || + bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { goto end; } result = 1; - end: +end: if (bed != NULL) DetectByteExtractFree(NULL, bed); return result; @@ -1047,21 +1000,17 @@ static int DetectByteExtractTest14(void) if (bed == NULL) goto end; - if (bed->nbytes != 4 || - bed->offset != 2 || - strcmp(bed->name, "one") != 0 || - bed->flags != (DETECT_BYTE_EXTRACT_FLAG_ALIGN | - DETECT_BYTE_EXTRACT_FLAG_ENDIAN | - DETECT_BYTE_EXTRACT_FLAG_RELATIVE) || - bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_DCE || - bed->base != DETECT_BYTE_EXTRACT_BASE_NONE || - bed->align_value != 4 || - bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { + if (bed->nbytes != 4 || bed->offset != 2 || strcmp(bed->name, "one") != 0 || + bed->flags != (DETECT_BYTE_EXTRACT_FLAG_ALIGN | DETECT_BYTE_EXTRACT_FLAG_ENDIAN | + DETECT_BYTE_EXTRACT_FLAG_RELATIVE) || + bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_DCE || + bed->base != DETECT_BYTE_EXTRACT_BASE_NONE || bed->align_value != 4 || + bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { goto end; } result = 1; - end: +end: if (bed != NULL) DetectByteExtractFree(NULL, bed); return result; @@ -1071,25 +1020,22 @@ static int DetectByteExtractTest15(void) { int result = 0; - DetectByteExtractData *bed = DetectByteExtractParse(NULL, "4, 2, one, align 4, relative, little"); + DetectByteExtractData *bed = + DetectByteExtractParse(NULL, "4, 2, one, align 4, relative, little"); if (bed == NULL) goto end; - if (bed->nbytes != 4 || - bed->offset != 2 || - strcmp(bed->name, "one") != 0 || - bed->flags != (DETECT_BYTE_EXTRACT_FLAG_ALIGN | - DETECT_BYTE_EXTRACT_FLAG_ENDIAN | - DETECT_BYTE_EXTRACT_FLAG_RELATIVE) || - bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_LITTLE || - bed->base != DETECT_BYTE_EXTRACT_BASE_NONE || - bed->align_value != 4 || - bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { + if (bed->nbytes != 4 || bed->offset != 2 || strcmp(bed->name, "one") != 0 || + bed->flags != (DETECT_BYTE_EXTRACT_FLAG_ALIGN | DETECT_BYTE_EXTRACT_FLAG_ENDIAN | + DETECT_BYTE_EXTRACT_FLAG_RELATIVE) || + bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_LITTLE || + bed->base != DETECT_BYTE_EXTRACT_BASE_NONE || bed->align_value != 4 || + bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { goto end; } result = 1; - end: +end: if (bed != NULL) DetectByteExtractFree(NULL, bed); return result; @@ -1099,26 +1045,23 @@ static int DetectByteExtractTest16(void) { int result = 0; - DetectByteExtractData *bed = DetectByteExtractParse(NULL, "4, 2, one, align 4, relative, little, multiplier 2"); + DetectByteExtractData *bed = + DetectByteExtractParse(NULL, "4, 2, one, align 4, relative, little, multiplier 2"); if (bed == NULL) goto end; - if (bed->nbytes != 4 || - bed->offset != 2 || - strcmp(bed->name, "one") != 0 || - bed->flags != (DETECT_BYTE_EXTRACT_FLAG_ALIGN | - DETECT_BYTE_EXTRACT_FLAG_RELATIVE | - DETECT_BYTE_EXTRACT_FLAG_ENDIAN | - DETECT_BYTE_EXTRACT_FLAG_MULTIPLIER) || - bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_LITTLE || - bed->base != DETECT_BYTE_EXTRACT_BASE_NONE || - bed->align_value != 4 || - bed->multiplier_value != 2) { + if (bed->nbytes != 4 || bed->offset != 2 || strcmp(bed->name, "one") != 0 || + bed->flags != (DETECT_BYTE_EXTRACT_FLAG_ALIGN | DETECT_BYTE_EXTRACT_FLAG_RELATIVE | + DETECT_BYTE_EXTRACT_FLAG_ENDIAN | + DETECT_BYTE_EXTRACT_FLAG_MULTIPLIER) || + bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_LITTLE || + bed->base != DETECT_BYTE_EXTRACT_BASE_NONE || bed->align_value != 4 || + bed->multiplier_value != 2) { goto end; } result = 1; - end: +end: if (bed != NULL) DetectByteExtractFree(NULL, bed); return result; @@ -1129,13 +1072,13 @@ static int DetectByteExtractTest17(void) int result = 0; DetectByteExtractData *bed = DetectByteExtractParse(NULL, "4, 2, one, align 4, " - "relative, little, " - "multiplier 2, string hex"); + "relative, little, " + "multiplier 2, string hex"); if (bed != NULL) goto end; result = 1; - end: +end: if (bed != NULL) DetectByteExtractFree(NULL, bed); return result; @@ -1146,14 +1089,14 @@ static int DetectByteExtractTest18(void) int result = 0; DetectByteExtractData *bed = DetectByteExtractParse(NULL, "4, 2, one, align 4, " - "relative, little, " - "multiplier 2, " - "relative"); + "relative, little, " + "multiplier 2, " + "relative"); if (bed != NULL) goto end; result = 1; - end: +end: if (bed != NULL) DetectByteExtractFree(NULL, bed); return result; @@ -1164,14 +1107,14 @@ static int DetectByteExtractTest19(void) int result = 0; DetectByteExtractData *bed = DetectByteExtractParse(NULL, "4, 2, one, align 4, " - "relative, little, " - "multiplier 2, " - "little"); + "relative, little, " + "multiplier 2, " + "little"); if (bed != NULL) goto end; result = 1; - end: +end: if (bed != NULL) DetectByteExtractFree(NULL, bed); return result; @@ -1182,14 +1125,14 @@ static int DetectByteExtractTest20(void) int result = 0; DetectByteExtractData *bed = DetectByteExtractParse(NULL, "4, 2, one, align 4, " - "relative, " - "multiplier 2, " - "align 2"); + "relative, " + "multiplier 2, " + "align 2"); if (bed != NULL) goto end; result = 1; - end: +end: if (bed != NULL) DetectByteExtractFree(NULL, bed); return result; @@ -1200,14 +1143,14 @@ static int DetectByteExtractTest21(void) int result = 0; DetectByteExtractData *bed = DetectByteExtractParse(NULL, "4, 2, one, align 4, " - "multiplier 2, " - "relative, " - "multiplier 2"); + "multiplier 2, " + "relative, " + "multiplier 2"); if (bed != NULL) goto end; result = 1; - end: +end: if (bed != NULL) DetectByteExtractFree(NULL, bed); return result; @@ -1218,14 +1161,14 @@ static int DetectByteExtractTest22(void) int result = 0; DetectByteExtractData *bed = DetectByteExtractParse(NULL, "4, 2, one, align 4, " - "string hex, " - "relative, " - "string hex"); + "string hex, " + "relative, " + "string hex"); if (bed != NULL) goto end; result = 1; - end: +end: if (bed != NULL) DetectByteExtractFree(NULL, bed); return result; @@ -1236,14 +1179,14 @@ static int DetectByteExtractTest23(void) int result = 0; DetectByteExtractData *bed = DetectByteExtractParse(NULL, "4, 2, one, align 4, " - "string hex, " - "relative, " - "string oct"); + "string hex, " + "relative, " + "string oct"); if (bed != NULL) goto end; result = 1; - end: +end: if (bed != NULL) DetectByteExtractFree(NULL, bed); return result; @@ -1254,13 +1197,13 @@ static int DetectByteExtractTest24(void) int result = 0; DetectByteExtractData *bed = DetectByteExtractParse(NULL, "24, 2, one, align 4, " - "string hex, " - "relative"); + "string hex, " + "relative"); if (bed != NULL) goto end; result = 1; - end: +end: if (bed != NULL) DetectByteExtractFree(NULL, bed); return result; @@ -1271,13 +1214,13 @@ static int DetectByteExtractTest25(void) int result = 0; DetectByteExtractData *bed = DetectByteExtractParse(NULL, "9, 2, one, align 4, " - "little, " - "relative"); + "little, " + "relative"); if (bed != NULL) goto end; result = 1; - end: +end: if (bed != NULL) DetectByteExtractFree(NULL, bed); return result; @@ -1288,14 +1231,14 @@ static int DetectByteExtractTest26(void) int result = 0; DetectByteExtractData *bed = DetectByteExtractParse(NULL, "4, 2, one, align 4, " - "little, " - "relative, " - "multiplier 65536"); + "little, " + "relative, " + "multiplier 65536"); if (bed != NULL) goto end; result = 1; - end: +end: if (bed != NULL) DetectByteExtractFree(NULL, bed); return result; @@ -1306,14 +1249,14 @@ static int DetectByteExtractTest27(void) int result = 0; DetectByteExtractData *bed = DetectByteExtractParse(NULL, "4, 2, one, align 4, " - "little, " - "relative, " - "multiplier 0"); + "little, " + "relative, " + "multiplier 0"); if (bed != NULL) goto end; result = 1; - end: +end: if (bed != NULL) DetectByteExtractFree(NULL, bed); return result; @@ -1328,7 +1271,7 @@ static int DetectByteExtractTest28(void) goto end; result = 1; - end: +end: if (bed != NULL) DetectByteExtractFree(NULL, bed); return result; @@ -1343,7 +1286,7 @@ static int DetectByteExtractTest29(void) goto end; result = 1; - end: +end: if (bed != NULL) DetectByteExtractFree(NULL, bed); return result; @@ -1358,7 +1301,7 @@ static int DetectByteExtractTest30(void) goto end; result = 1; - end: +end: if (bed != NULL) DetectByteExtractFree(NULL, bed); return result; @@ -1373,7 +1316,7 @@ static int DetectByteExtractTest31(void) goto end; result = 1; - end: +end: if (bed != NULL) DetectByteExtractFree(NULL, bed); return result; @@ -1388,7 +1331,7 @@ static int DetectByteExtractTest32(void) goto end; result = 1; - end: +end: if (bed != NULL) DetectByteExtractFree(NULL, bed); return result; @@ -1403,7 +1346,7 @@ static int DetectByteExtractTest33(void) goto end; result = 1; - end: +end: if (bed != NULL) DetectByteExtractFree(NULL, bed); return result; @@ -1424,10 +1367,10 @@ static int DetectByteExtractTest34(void) de_ctx->flags |= DE_QUIET; s = de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"Testing bytejump_body\"; " - "content:\"one\"; " - "byte_extract:4,2,two,relative,string,hex; " - "sid:1;)"); + "(msg:\"Testing bytejump_body\"; " + "content:\"one\"; " + "byte_extract:4,2,two,relative,string,hex; " + "sid:1;)"); if (de_ctx->sig_list == NULL) { result = 0; goto end; @@ -1445,13 +1388,10 @@ static int DetectByteExtractTest34(void) } cd = (DetectContentData *)sm->ctx; if (cd->flags & DETECT_CONTENT_RAWBYTES || - strncmp((char *)cd->content, "one", cd->content_len) != 0 || - cd->flags & DETECT_CONTENT_NOCASE || - cd->flags & DETECT_CONTENT_WITHIN || - cd->flags & DETECT_CONTENT_DISTANCE || - cd->flags & DETECT_CONTENT_FAST_PATTERN || - !(cd->flags & DETECT_CONTENT_RELATIVE_NEXT) || - cd->flags & DETECT_CONTENT_NEGATED ) { + strncmp((char *)cd->content, "one", cd->content_len) != 0 || + cd->flags & DETECT_CONTENT_NOCASE || cd->flags & DETECT_CONTENT_WITHIN || + cd->flags & DETECT_CONTENT_DISTANCE || cd->flags & DETECT_CONTENT_FAST_PATTERN || + !(cd->flags & DETECT_CONTENT_RELATIVE_NEXT) || cd->flags & DETECT_CONTENT_NEGATED) { printf("one failed\n"); result = 0; goto end; @@ -1463,21 +1403,17 @@ static int DetectByteExtractTest34(void) goto end; } bed = (DetectByteExtractData *)sm->ctx; - if (bed->nbytes != 4 || - bed->offset != 2 || - strncmp(bed->name, "two", cd->content_len) != 0 || - bed->flags != (DETECT_BYTE_EXTRACT_FLAG_RELATIVE | - DETECT_BYTE_EXTRACT_FLAG_STRING) || - bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE || - bed->base != DETECT_BYTE_EXTRACT_BASE_HEX || - bed->align_value != 0 || - bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { + if (bed->nbytes != 4 || bed->offset != 2 || strncmp(bed->name, "two", cd->content_len) != 0 || + bed->flags != (DETECT_BYTE_EXTRACT_FLAG_RELATIVE | DETECT_BYTE_EXTRACT_FLAG_STRING) || + bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE || + bed->base != DETECT_BYTE_EXTRACT_BASE_HEX || bed->align_value != 0 || + bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { goto end; } result = 1; - end: +end: SigGroupCleanup(de_ctx); SigCleanSignatures(de_ctx); DetectEngineCtxFree(de_ctx); @@ -1501,10 +1437,10 @@ static int DetectByteExtractTest35(void) de_ctx->flags |= DE_QUIET; s = de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"Testing bytejump_body\"; " - "content:\"one\"; pcre:/asf/; " - "byte_extract:4,0,two,relative,string,hex; " - "sid:1;)"); + "(msg:\"Testing bytejump_body\"; " + "content:\"one\"; pcre:/asf/; " + "byte_extract:4,0,two,relative,string,hex; " + "sid:1;)"); if (de_ctx->sig_list == NULL) { result = 0; goto end; @@ -1522,13 +1458,10 @@ static int DetectByteExtractTest35(void) } cd = (DetectContentData *)sm->ctx; if (cd->flags & DETECT_CONTENT_RAWBYTES || - strncmp((char *)cd->content, "one", cd->content_len) != 0 || - cd->flags & DETECT_CONTENT_NOCASE || - cd->flags & DETECT_CONTENT_WITHIN || - cd->flags & DETECT_CONTENT_DISTANCE || - cd->flags & DETECT_CONTENT_FAST_PATTERN || - cd->flags & DETECT_CONTENT_RELATIVE_NEXT || - cd->flags & DETECT_CONTENT_NEGATED ) { + strncmp((char *)cd->content, "one", cd->content_len) != 0 || + cd->flags & DETECT_CONTENT_NOCASE || cd->flags & DETECT_CONTENT_WITHIN || + cd->flags & DETECT_CONTENT_DISTANCE || cd->flags & DETECT_CONTENT_FAST_PATTERN || + cd->flags & DETECT_CONTENT_RELATIVE_NEXT || cd->flags & DETECT_CONTENT_NEGATED) { printf("one failed\n"); result = 0; goto end; @@ -1551,21 +1484,17 @@ static int DetectByteExtractTest35(void) goto end; } bed = (DetectByteExtractData *)sm->ctx; - if (bed->nbytes != 4 || - bed->offset != 0 || - strcmp(bed->name, "two") != 0 || - bed->flags != (DETECT_BYTE_EXTRACT_FLAG_RELATIVE | - DETECT_BYTE_EXTRACT_FLAG_STRING) || - bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE || - bed->base != DETECT_BYTE_EXTRACT_BASE_HEX || - bed->align_value != 0 || - bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { + if (bed->nbytes != 4 || bed->offset != 0 || strcmp(bed->name, "two") != 0 || + bed->flags != (DETECT_BYTE_EXTRACT_FLAG_RELATIVE | DETECT_BYTE_EXTRACT_FLAG_STRING) || + bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE || + bed->base != DETECT_BYTE_EXTRACT_BASE_HEX || bed->align_value != 0 || + bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { goto end; } result = 1; - end: +end: SigGroupCleanup(de_ctx); SigCleanSignatures(de_ctx); DetectEngineCtxFree(de_ctx); @@ -1589,10 +1518,10 @@ static int DetectByteExtractTest36(void) de_ctx->flags |= DE_QUIET; s = de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"Testing bytejump_body\"; " - "content:\"one\"; byte_jump:1,13; " - "byte_extract:4,0,two,relative,string,hex; " - "sid:1;)"); + "(msg:\"Testing bytejump_body\"; " + "content:\"one\"; byte_jump:1,13; " + "byte_extract:4,0,two,relative,string,hex; " + "sid:1;)"); if (de_ctx->sig_list == NULL) { result = 0; goto end; @@ -1610,13 +1539,10 @@ static int DetectByteExtractTest36(void) } cd = (DetectContentData *)sm->ctx; if (cd->flags & DETECT_CONTENT_RAWBYTES || - strncmp((char *)cd->content, "one", cd->content_len) != 0 || - cd->flags & DETECT_CONTENT_NOCASE || - cd->flags & DETECT_CONTENT_WITHIN || - cd->flags & DETECT_CONTENT_DISTANCE || - cd->flags & DETECT_CONTENT_FAST_PATTERN || - cd->flags & DETECT_CONTENT_RELATIVE_NEXT || - cd->flags & DETECT_CONTENT_NEGATED ) { + strncmp((char *)cd->content, "one", cd->content_len) != 0 || + cd->flags & DETECT_CONTENT_NOCASE || cd->flags & DETECT_CONTENT_WITHIN || + cd->flags & DETECT_CONTENT_DISTANCE || cd->flags & DETECT_CONTENT_FAST_PATTERN || + cd->flags & DETECT_CONTENT_RELATIVE_NEXT || cd->flags & DETECT_CONTENT_NEGATED) { printf("one failed\n"); result = 0; goto end; @@ -1639,21 +1565,17 @@ static int DetectByteExtractTest36(void) goto end; } bed = (DetectByteExtractData *)sm->ctx; - if (bed->nbytes != 4 || - bed->offset != 0 || - strcmp(bed->name, "two") != 0 || - bed->flags != (DETECT_BYTE_EXTRACT_FLAG_RELATIVE | - DETECT_BYTE_EXTRACT_FLAG_STRING) || - bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE || - bed->base != DETECT_BYTE_EXTRACT_BASE_HEX || - bed->align_value != 0 || - bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { + if (bed->nbytes != 4 || bed->offset != 0 || strcmp(bed->name, "two") != 0 || + bed->flags != (DETECT_BYTE_EXTRACT_FLAG_RELATIVE | DETECT_BYTE_EXTRACT_FLAG_STRING) || + bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE || + bed->base != DETECT_BYTE_EXTRACT_BASE_HEX || bed->align_value != 0 || + bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { goto end; } result = 1; - end: +end: SigGroupCleanup(de_ctx); SigCleanSignatures(de_ctx); DetectEngineCtxFree(de_ctx); @@ -1677,10 +1599,10 @@ static int DetectByteExtractTest37(void) de_ctx->flags |= DE_QUIET; s = de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"Testing bytejump_body\"; " - "content:\"one\"; uricontent:\"two\"; " - "byte_extract:4,0,two,relative,string,hex; " - "sid:1;)"); + "(msg:\"Testing bytejump_body\"; " + "content:\"one\"; uricontent:\"two\"; " + "byte_extract:4,0,two,relative,string,hex; " + "sid:1;)"); if (de_ctx->sig_list == NULL) { result = 0; goto end; @@ -1698,13 +1620,10 @@ static int DetectByteExtractTest37(void) } cd = (DetectContentData *)sm->ctx; if (cd->flags & DETECT_CONTENT_RAWBYTES || - strncmp((char *)cd->content, "one", cd->content_len) != 0 || - cd->flags & DETECT_CONTENT_NOCASE || - cd->flags & DETECT_CONTENT_WITHIN || - cd->flags & DETECT_CONTENT_DISTANCE || - cd->flags & DETECT_CONTENT_FAST_PATTERN || - cd->flags & DETECT_CONTENT_RELATIVE_NEXT || - cd->flags & DETECT_CONTENT_NEGATED ) { + strncmp((char *)cd->content, "one", cd->content_len) != 0 || + cd->flags & DETECT_CONTENT_NOCASE || cd->flags & DETECT_CONTENT_WITHIN || + cd->flags & DETECT_CONTENT_DISTANCE || cd->flags & DETECT_CONTENT_FAST_PATTERN || + cd->flags & DETECT_CONTENT_RELATIVE_NEXT || cd->flags & DETECT_CONTENT_NEGATED) { printf("one failed\n"); result = 0; goto end; @@ -1722,13 +1641,10 @@ static int DetectByteExtractTest37(void) } ud = (DetectContentData *)sm->ctx; if (ud->flags & DETECT_CONTENT_RAWBYTES || - strncmp((char *)ud->content, "two", cd->content_len) != 0 || - ud->flags & DETECT_CONTENT_NOCASE || - ud->flags & DETECT_CONTENT_WITHIN || - ud->flags & DETECT_CONTENT_DISTANCE || - ud->flags & DETECT_CONTENT_FAST_PATTERN || - !(ud->flags & DETECT_CONTENT_RELATIVE_NEXT) || - ud->flags & DETECT_CONTENT_NEGATED ) { + strncmp((char *)ud->content, "two", cd->content_len) != 0 || + ud->flags & DETECT_CONTENT_NOCASE || ud->flags & DETECT_CONTENT_WITHIN || + ud->flags & DETECT_CONTENT_DISTANCE || ud->flags & DETECT_CONTENT_FAST_PATTERN || + !(ud->flags & DETECT_CONTENT_RELATIVE_NEXT) || ud->flags & DETECT_CONTENT_NEGATED) { printf("two failed\n"); result = 0; goto end; @@ -1740,21 +1656,17 @@ static int DetectByteExtractTest37(void) goto end; } bed = (DetectByteExtractData *)sm->ctx; - if (bed->nbytes != 4 || - bed->offset != 0 || - strcmp(bed->name, "two") != 0 || - bed->flags != (DETECT_BYTE_EXTRACT_FLAG_RELATIVE | - DETECT_BYTE_EXTRACT_FLAG_STRING) || - bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE || - bed->base != DETECT_BYTE_EXTRACT_BASE_HEX || - bed->align_value != 0 || - bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { + if (bed->nbytes != 4 || bed->offset != 0 || strcmp(bed->name, "two") != 0 || + bed->flags != (DETECT_BYTE_EXTRACT_FLAG_RELATIVE | DETECT_BYTE_EXTRACT_FLAG_STRING) || + bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE || + bed->base != DETECT_BYTE_EXTRACT_BASE_HEX || bed->align_value != 0 || + bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { goto end; } result = 1; - end: +end: SigGroupCleanup(de_ctx); SigCleanSignatures(de_ctx); DetectEngineCtxFree(de_ctx); @@ -1778,10 +1690,10 @@ static int DetectByteExtractTest38(void) de_ctx->flags |= DE_QUIET; s = de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"Testing bytejump_body\"; " - "content:\"one\"; uricontent:\"two\"; " - "byte_extract:4,0,two,string,hex; " - "sid:1;)"); + "(msg:\"Testing bytejump_body\"; " + "content:\"one\"; uricontent:\"two\"; " + "byte_extract:4,0,two,string,hex; " + "sid:1;)"); if (de_ctx->sig_list == NULL) { result = 0; goto end; @@ -1799,13 +1711,10 @@ static int DetectByteExtractTest38(void) } cd = (DetectContentData *)sm->ctx; if (cd->flags & DETECT_CONTENT_RAWBYTES || - strncmp((char *)cd->content, "one", cd->content_len) != 0 || - cd->flags & DETECT_CONTENT_NOCASE || - cd->flags & DETECT_CONTENT_WITHIN || - cd->flags & DETECT_CONTENT_DISTANCE || - cd->flags & DETECT_CONTENT_FAST_PATTERN || - cd->flags & DETECT_CONTENT_RELATIVE_NEXT || - cd->flags & DETECT_CONTENT_NEGATED ) { + strncmp((char *)cd->content, "one", cd->content_len) != 0 || + cd->flags & DETECT_CONTENT_NOCASE || cd->flags & DETECT_CONTENT_WITHIN || + cd->flags & DETECT_CONTENT_DISTANCE || cd->flags & DETECT_CONTENT_FAST_PATTERN || + cd->flags & DETECT_CONTENT_RELATIVE_NEXT || cd->flags & DETECT_CONTENT_NEGATED) { printf("one failed\n"); result = 0; goto end; @@ -1817,14 +1726,11 @@ static int DetectByteExtractTest38(void) goto end; } bed = (DetectByteExtractData *)sm->ctx; - if (bed->nbytes != 4 || - bed->offset != 0 || - strcmp(bed->name, "two") != 0 || - bed->flags !=DETECT_BYTE_EXTRACT_FLAG_STRING || - bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE || - bed->base != DETECT_BYTE_EXTRACT_BASE_HEX || - bed->align_value != 0 || - bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { + if (bed->nbytes != 4 || bed->offset != 0 || strcmp(bed->name, "two") != 0 || + bed->flags != DETECT_BYTE_EXTRACT_FLAG_STRING || + bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE || + bed->base != DETECT_BYTE_EXTRACT_BASE_HEX || bed->align_value != 0 || + bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { goto end; } @@ -1835,13 +1741,10 @@ static int DetectByteExtractTest38(void) } ud = (DetectContentData *)sm->ctx; if (ud->flags & DETECT_CONTENT_RAWBYTES || - strncmp((char *)ud->content, "two", cd->content_len) != 0 || - ud->flags & DETECT_CONTENT_NOCASE || - ud->flags & DETECT_CONTENT_WITHIN || - ud->flags & DETECT_CONTENT_DISTANCE || - ud->flags & DETECT_CONTENT_FAST_PATTERN || - ud->flags & DETECT_CONTENT_RELATIVE_NEXT || - ud->flags & DETECT_CONTENT_NEGATED ) { + strncmp((char *)ud->content, "two", cd->content_len) != 0 || + ud->flags & DETECT_CONTENT_NOCASE || ud->flags & DETECT_CONTENT_WITHIN || + ud->flags & DETECT_CONTENT_DISTANCE || ud->flags & DETECT_CONTENT_FAST_PATTERN || + ud->flags & DETECT_CONTENT_RELATIVE_NEXT || ud->flags & DETECT_CONTENT_NEGATED) { printf("two failed\n"); result = 0; goto end; @@ -1854,7 +1757,7 @@ static int DetectByteExtractTest38(void) result = 1; - end: +end: SigGroupCleanup(de_ctx); SigCleanSignatures(de_ctx); DetectEngineCtxFree(de_ctx); @@ -1878,10 +1781,10 @@ static int DetectByteExtractTest39(void) de_ctx->flags |= DE_QUIET; s = de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"Testing bytejump_body\"; " - "content:\"one\"; content:\"two\"; http_uri; " - "byte_extract:4,0,two,relative,string,hex; " - "sid:1;)"); + "(msg:\"Testing bytejump_body\"; " + "content:\"one\"; content:\"two\"; http_uri; " + "byte_extract:4,0,two,relative,string,hex; " + "sid:1;)"); if (de_ctx->sig_list == NULL) { result = 0; goto end; @@ -1899,13 +1802,10 @@ static int DetectByteExtractTest39(void) } cd = (DetectContentData *)sm->ctx; if (cd->flags & DETECT_CONTENT_RAWBYTES || - strncmp((char *)cd->content, "one", cd->content_len) != 0 || - cd->flags & DETECT_CONTENT_NOCASE || - cd->flags & DETECT_CONTENT_WITHIN || - cd->flags & DETECT_CONTENT_DISTANCE || - cd->flags & DETECT_CONTENT_FAST_PATTERN || - cd->flags & DETECT_CONTENT_RELATIVE_NEXT || - cd->flags & DETECT_CONTENT_NEGATED ) { + strncmp((char *)cd->content, "one", cd->content_len) != 0 || + cd->flags & DETECT_CONTENT_NOCASE || cd->flags & DETECT_CONTENT_WITHIN || + cd->flags & DETECT_CONTENT_DISTANCE || cd->flags & DETECT_CONTENT_FAST_PATTERN || + cd->flags & DETECT_CONTENT_RELATIVE_NEXT || cd->flags & DETECT_CONTENT_NEGATED) { printf("one failed\n"); result = 0; goto end; @@ -1923,13 +1823,10 @@ static int DetectByteExtractTest39(void) } ud = (DetectContentData *)sm->ctx; if (ud->flags & DETECT_CONTENT_RAWBYTES || - strncmp((char *)ud->content, "two", cd->content_len) != 0 || - ud->flags & DETECT_CONTENT_NOCASE || - ud->flags & DETECT_CONTENT_WITHIN || - ud->flags & DETECT_CONTENT_DISTANCE || - ud->flags & DETECT_CONTENT_FAST_PATTERN || - !(ud->flags & DETECT_CONTENT_RELATIVE_NEXT) || - ud->flags & DETECT_CONTENT_NEGATED ) { + strncmp((char *)ud->content, "two", cd->content_len) != 0 || + ud->flags & DETECT_CONTENT_NOCASE || ud->flags & DETECT_CONTENT_WITHIN || + ud->flags & DETECT_CONTENT_DISTANCE || ud->flags & DETECT_CONTENT_FAST_PATTERN || + !(ud->flags & DETECT_CONTENT_RELATIVE_NEXT) || ud->flags & DETECT_CONTENT_NEGATED) { printf("two failed\n"); result = 0; goto end; @@ -1941,21 +1838,17 @@ static int DetectByteExtractTest39(void) goto end; } bed = (DetectByteExtractData *)sm->ctx; - if (bed->nbytes != 4 || - bed->offset != 0 || - strcmp(bed->name, "two") != 0 || - bed->flags != (DETECT_BYTE_EXTRACT_FLAG_RELATIVE | - DETECT_BYTE_EXTRACT_FLAG_STRING) || - bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE || - bed->base != DETECT_BYTE_EXTRACT_BASE_HEX || - bed->align_value != 0 || - bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { + if (bed->nbytes != 4 || bed->offset != 0 || strcmp(bed->name, "two") != 0 || + bed->flags != (DETECT_BYTE_EXTRACT_FLAG_RELATIVE | DETECT_BYTE_EXTRACT_FLAG_STRING) || + bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE || + bed->base != DETECT_BYTE_EXTRACT_BASE_HEX || bed->align_value != 0 || + bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { goto end; } result = 1; - end: +end: SigGroupCleanup(de_ctx); SigCleanSignatures(de_ctx); DetectEngineCtxFree(de_ctx); @@ -1979,10 +1872,10 @@ static int DetectByteExtractTest40(void) de_ctx->flags |= DE_QUIET; s = de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"Testing bytejump_body\"; " - "content:\"one\"; content:\"two\"; http_uri; " - "byte_extract:4,0,two,string,hex; " - "sid:1;)"); + "(msg:\"Testing bytejump_body\"; " + "content:\"one\"; content:\"two\"; http_uri; " + "byte_extract:4,0,two,string,hex; " + "sid:1;)"); if (de_ctx->sig_list == NULL) { result = 0; goto end; @@ -2000,13 +1893,10 @@ static int DetectByteExtractTest40(void) } cd = (DetectContentData *)sm->ctx; if (cd->flags & DETECT_CONTENT_RAWBYTES || - strncmp((char *)cd->content, "one", cd->content_len) != 0 || - cd->flags & DETECT_CONTENT_NOCASE || - cd->flags & DETECT_CONTENT_WITHIN || - cd->flags & DETECT_CONTENT_DISTANCE || - cd->flags & DETECT_CONTENT_FAST_PATTERN || - cd->flags & DETECT_CONTENT_RELATIVE_NEXT || - cd->flags & DETECT_CONTENT_NEGATED ) { + strncmp((char *)cd->content, "one", cd->content_len) != 0 || + cd->flags & DETECT_CONTENT_NOCASE || cd->flags & DETECT_CONTENT_WITHIN || + cd->flags & DETECT_CONTENT_DISTANCE || cd->flags & DETECT_CONTENT_FAST_PATTERN || + cd->flags & DETECT_CONTENT_RELATIVE_NEXT || cd->flags & DETECT_CONTENT_NEGATED) { printf("one failed\n"); result = 0; goto end; @@ -2018,14 +1908,11 @@ static int DetectByteExtractTest40(void) goto end; } bed = (DetectByteExtractData *)sm->ctx; - if (bed->nbytes != 4 || - bed->offset != 0 || - strcmp(bed->name, "two") != 0 || - bed->flags !=DETECT_BYTE_EXTRACT_FLAG_STRING || - bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE || - bed->base != DETECT_BYTE_EXTRACT_BASE_HEX || - bed->align_value != 0 || - bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { + if (bed->nbytes != 4 || bed->offset != 0 || strcmp(bed->name, "two") != 0 || + bed->flags != DETECT_BYTE_EXTRACT_FLAG_STRING || + bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE || + bed->base != DETECT_BYTE_EXTRACT_BASE_HEX || bed->align_value != 0 || + bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { goto end; } @@ -2036,13 +1923,10 @@ static int DetectByteExtractTest40(void) } ud = (DetectContentData *)sm->ctx; if (ud->flags & DETECT_CONTENT_RAWBYTES || - strncmp((char *)ud->content, "two", cd->content_len) != 0 || - ud->flags & DETECT_CONTENT_NOCASE || - ud->flags & DETECT_CONTENT_WITHIN || - ud->flags & DETECT_CONTENT_DISTANCE || - ud->flags & DETECT_CONTENT_FAST_PATTERN || - ud->flags & DETECT_CONTENT_RELATIVE_NEXT || - ud->flags & DETECT_CONTENT_NEGATED ) { + strncmp((char *)ud->content, "two", cd->content_len) != 0 || + ud->flags & DETECT_CONTENT_NOCASE || ud->flags & DETECT_CONTENT_WITHIN || + ud->flags & DETECT_CONTENT_DISTANCE || ud->flags & DETECT_CONTENT_FAST_PATTERN || + ud->flags & DETECT_CONTENT_RELATIVE_NEXT || ud->flags & DETECT_CONTENT_NEGATED) { printf("two failed\n"); result = 0; goto end; @@ -2055,7 +1939,7 @@ static int DetectByteExtractTest40(void) result = 1; - end: +end: SigGroupCleanup(de_ctx); SigCleanSignatures(de_ctx); DetectEngineCtxFree(de_ctx); @@ -2078,11 +1962,11 @@ static int DetectByteExtractTest41(void) de_ctx->flags |= DE_QUIET; s = de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"Testing bytejump_body\"; " - "content:\"one\"; " - "byte_extract:4,0,two,string,hex; " - "byte_extract:4,0,three,string,hex; " - "sid:1;)"); + "(msg:\"Testing bytejump_body\"; " + "content:\"one\"; " + "byte_extract:4,0,two,string,hex; " + "byte_extract:4,0,three,string,hex; " + "sid:1;)"); if (de_ctx->sig_list == NULL) { result = 0; goto end; @@ -2100,13 +1984,10 @@ static int DetectByteExtractTest41(void) } cd = (DetectContentData *)sm->ctx; if (cd->flags & DETECT_CONTENT_RAWBYTES || - strncmp((char *)cd->content, "one", cd->content_len) != 0 || - cd->flags & DETECT_CONTENT_NOCASE || - cd->flags & DETECT_CONTENT_WITHIN || - cd->flags & DETECT_CONTENT_DISTANCE || - cd->flags & DETECT_CONTENT_FAST_PATTERN || - cd->flags & DETECT_CONTENT_RELATIVE_NEXT || - cd->flags & DETECT_CONTENT_NEGATED ) { + strncmp((char *)cd->content, "one", cd->content_len) != 0 || + cd->flags & DETECT_CONTENT_NOCASE || cd->flags & DETECT_CONTENT_WITHIN || + cd->flags & DETECT_CONTENT_DISTANCE || cd->flags & DETECT_CONTENT_FAST_PATTERN || + cd->flags & DETECT_CONTENT_RELATIVE_NEXT || cd->flags & DETECT_CONTENT_NEGATED) { printf("one failed\n"); result = 0; goto end; @@ -2118,14 +1999,11 @@ static int DetectByteExtractTest41(void) goto end; } bed = (DetectByteExtractData *)sm->ctx; - if (bed->nbytes != 4 || - bed->offset != 0 || - strcmp(bed->name, "two") != 0 || - bed->flags != DETECT_BYTE_EXTRACT_FLAG_STRING || - bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE || - bed->base != DETECT_BYTE_EXTRACT_BASE_HEX || - bed->align_value != 0 || - bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { + if (bed->nbytes != 4 || bed->offset != 0 || strcmp(bed->name, "two") != 0 || + bed->flags != DETECT_BYTE_EXTRACT_FLAG_STRING || + bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE || + bed->base != DETECT_BYTE_EXTRACT_BASE_HEX || bed->align_value != 0 || + bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { goto end; } if (bed->local_id != 0) { @@ -2139,14 +2017,11 @@ static int DetectByteExtractTest41(void) goto end; } bed = (DetectByteExtractData *)sm->ctx; - if (bed->nbytes != 4 || - bed->offset != 0 || - strcmp(bed->name, "three") != 0 || - bed->flags != DETECT_BYTE_EXTRACT_FLAG_STRING || - bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE || - bed->base != DETECT_BYTE_EXTRACT_BASE_HEX || - bed->align_value != 0 || - bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { + if (bed->nbytes != 4 || bed->offset != 0 || strcmp(bed->name, "three") != 0 || + bed->flags != DETECT_BYTE_EXTRACT_FLAG_STRING || + bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE || + bed->base != DETECT_BYTE_EXTRACT_BASE_HEX || bed->align_value != 0 || + bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { goto end; } if (bed->local_id != 1) { @@ -2156,7 +2031,7 @@ static int DetectByteExtractTest41(void) result = 1; - end: +end: SigGroupCleanup(de_ctx); SigCleanSignatures(de_ctx); DetectEngineCtxFree(de_ctx); @@ -2180,13 +2055,13 @@ static int DetectByteExtractTest42(void) de_ctx->flags |= DE_QUIET; s = de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"Testing bytejump_body\"; " - "content:\"one\"; " - "byte_extract:4,0,two,string,hex; " - "uricontent: \"three\"; " - "byte_extract:4,0,four,string,hex,relative; " - "byte_extract:4,0,five,string,hex; " - "sid:1;)"); + "(msg:\"Testing bytejump_body\"; " + "content:\"one\"; " + "byte_extract:4,0,two,string,hex; " + "uricontent: \"three\"; " + "byte_extract:4,0,four,string,hex,relative; " + "byte_extract:4,0,five,string,hex; " + "sid:1;)"); if (de_ctx->sig_list == NULL) { result = 0; goto end; @@ -2204,13 +2079,10 @@ static int DetectByteExtractTest42(void) } cd = (DetectContentData *)sm->ctx; if (cd->flags & DETECT_CONTENT_RAWBYTES || - strncmp((char *)cd->content, "one", cd->content_len) != 0 || - cd->flags & DETECT_CONTENT_NOCASE || - cd->flags & DETECT_CONTENT_WITHIN || - cd->flags & DETECT_CONTENT_DISTANCE || - cd->flags & DETECT_CONTENT_FAST_PATTERN || - cd->flags & DETECT_CONTENT_RELATIVE_NEXT || - cd->flags & DETECT_CONTENT_NEGATED ) { + strncmp((char *)cd->content, "one", cd->content_len) != 0 || + cd->flags & DETECT_CONTENT_NOCASE || cd->flags & DETECT_CONTENT_WITHIN || + cd->flags & DETECT_CONTENT_DISTANCE || cd->flags & DETECT_CONTENT_FAST_PATTERN || + cd->flags & DETECT_CONTENT_RELATIVE_NEXT || cd->flags & DETECT_CONTENT_NEGATED) { printf("one failed\n"); result = 0; goto end; @@ -2222,14 +2094,11 @@ static int DetectByteExtractTest42(void) goto end; } bed = (DetectByteExtractData *)sm->ctx; - if (bed->nbytes != 4 || - bed->offset != 0 || - strcmp(bed->name, "two") != 0 || - bed->flags != DETECT_BYTE_EXTRACT_FLAG_STRING || - bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE || - bed->base != DETECT_BYTE_EXTRACT_BASE_HEX || - bed->align_value != 0 || - bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { + if (bed->nbytes != 4 || bed->offset != 0 || strcmp(bed->name, "two") != 0 || + bed->flags != DETECT_BYTE_EXTRACT_FLAG_STRING || + bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE || + bed->base != DETECT_BYTE_EXTRACT_BASE_HEX || bed->align_value != 0 || + bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { goto end; } if (bed->local_id != 0) { @@ -2243,14 +2112,11 @@ static int DetectByteExtractTest42(void) goto end; } bed = (DetectByteExtractData *)sm->ctx; - if (bed->nbytes != 4 || - bed->offset != 0 || - strcmp(bed->name, "five") != 0 || - bed->flags != DETECT_BYTE_EXTRACT_FLAG_STRING || - bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE || - bed->base != DETECT_BYTE_EXTRACT_BASE_HEX || - bed->align_value != 0 || - bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { + if (bed->nbytes != 4 || bed->offset != 0 || strcmp(bed->name, "five") != 0 || + bed->flags != DETECT_BYTE_EXTRACT_FLAG_STRING || + bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE || + bed->base != DETECT_BYTE_EXTRACT_BASE_HEX || bed->align_value != 0 || + bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { goto end; } if (bed->local_id != 1) { @@ -2268,13 +2134,10 @@ static int DetectByteExtractTest42(void) } ud = (DetectContentData *)sm->ctx; if (ud->flags & DETECT_CONTENT_RAWBYTES || - strncmp((char *)ud->content, "three", cd->content_len) != 0 || - ud->flags & DETECT_CONTENT_NOCASE || - ud->flags & DETECT_CONTENT_WITHIN || - ud->flags & DETECT_CONTENT_DISTANCE || - ud->flags & DETECT_CONTENT_FAST_PATTERN || - !(ud->flags & DETECT_CONTENT_RELATIVE_NEXT) || - ud->flags & DETECT_CONTENT_NEGATED ) { + strncmp((char *)ud->content, "three", cd->content_len) != 0 || + ud->flags & DETECT_CONTENT_NOCASE || ud->flags & DETECT_CONTENT_WITHIN || + ud->flags & DETECT_CONTENT_DISTANCE || ud->flags & DETECT_CONTENT_FAST_PATTERN || + !(ud->flags & DETECT_CONTENT_RELATIVE_NEXT) || ud->flags & DETECT_CONTENT_NEGATED) { printf("two failed\n"); result = 0; goto end; @@ -2286,15 +2149,11 @@ static int DetectByteExtractTest42(void) goto end; } bed = (DetectByteExtractData *)sm->ctx; - if (bed->nbytes != 4 || - bed->offset != 0 || - strcmp(bed->name, "four") != 0 || - bed->flags != (DETECT_BYTE_EXTRACT_FLAG_RELATIVE | - DETECT_BYTE_EXTRACT_FLAG_STRING) || - bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE || - bed->base != DETECT_BYTE_EXTRACT_BASE_HEX || - bed->align_value != 0 || - bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { + if (bed->nbytes != 4 || bed->offset != 0 || strcmp(bed->name, "four") != 0 || + bed->flags != (DETECT_BYTE_EXTRACT_FLAG_RELATIVE | DETECT_BYTE_EXTRACT_FLAG_STRING) || + bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE || + bed->base != DETECT_BYTE_EXTRACT_BASE_HEX || bed->align_value != 0 || + bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { goto end; } if (bed->local_id != 0) { @@ -2307,7 +2166,7 @@ static int DetectByteExtractTest42(void) result = 1; - end: +end: SigGroupCleanup(de_ctx); SigCleanSignatures(de_ctx); DetectEngineCtxFree(de_ctx); @@ -2330,11 +2189,11 @@ static int DetectByteExtractTest43(void) de_ctx->flags |= DE_QUIET; s = de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"Testing bytejump_body\"; " - "content:\"one\"; " - "byte_extract:4,0,two,string,hex; " - "content: \"three\"; offset:two; " - "sid:1;)"); + "(msg:\"Testing bytejump_body\"; " + "content:\"one\"; " + "byte_extract:4,0,two,string,hex; " + "content: \"three\"; offset:two; " + "sid:1;)"); if (de_ctx->sig_list == NULL) { result = 0; goto end; @@ -2352,13 +2211,10 @@ static int DetectByteExtractTest43(void) } cd = (DetectContentData *)sm->ctx; if (cd->flags & DETECT_CONTENT_RAWBYTES || - strncmp((char *)cd->content, "one", cd->content_len) != 0 || - cd->flags & DETECT_CONTENT_NOCASE || - cd->flags & DETECT_CONTENT_WITHIN || - cd->flags & DETECT_CONTENT_DISTANCE || - cd->flags & DETECT_CONTENT_FAST_PATTERN || - cd->flags & DETECT_CONTENT_RELATIVE_NEXT || - cd->flags & DETECT_CONTENT_NEGATED ) { + strncmp((char *)cd->content, "one", cd->content_len) != 0 || + cd->flags & DETECT_CONTENT_NOCASE || cd->flags & DETECT_CONTENT_WITHIN || + cd->flags & DETECT_CONTENT_DISTANCE || cd->flags & DETECT_CONTENT_FAST_PATTERN || + cd->flags & DETECT_CONTENT_RELATIVE_NEXT || cd->flags & DETECT_CONTENT_NEGATED) { printf("one failed\n"); result = 0; goto end; @@ -2370,14 +2226,11 @@ static int DetectByteExtractTest43(void) goto end; } bed = (DetectByteExtractData *)sm->ctx; - if (bed->nbytes != 4 || - bed->offset != 0 || - strcmp(bed->name, "two") != 0 || - bed->flags != DETECT_BYTE_EXTRACT_FLAG_STRING || - bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE || - bed->base != DETECT_BYTE_EXTRACT_BASE_HEX || - bed->align_value != 0 || - bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { + if (bed->nbytes != 4 || bed->offset != 0 || strcmp(bed->name, "two") != 0 || + bed->flags != DETECT_BYTE_EXTRACT_FLAG_STRING || + bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE || + bed->base != DETECT_BYTE_EXTRACT_BASE_HEX || bed->align_value != 0 || + bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { goto end; } if (bed->local_id != 0) { @@ -2392,9 +2245,8 @@ static int DetectByteExtractTest43(void) } cd = (DetectContentData *)sm->ctx; if (strncmp((char *)cd->content, "three", cd->content_len) != 0 || - cd->flags != (DETECT_CONTENT_OFFSET_VAR | - DETECT_CONTENT_OFFSET) || - cd->offset != bed->local_id) { + cd->flags != (DETECT_CONTENT_OFFSET_VAR | DETECT_CONTENT_OFFSET) || + cd->offset != bed->local_id) { printf("three failed\n"); result = 0; goto end; @@ -2405,7 +2257,7 @@ static int DetectByteExtractTest43(void) result = 1; - end: +end: SigGroupCleanup(de_ctx); SigCleanSignatures(de_ctx); DetectEngineCtxFree(de_ctx); @@ -2429,13 +2281,13 @@ static int DetectByteExtractTest44(void) de_ctx->flags |= DE_QUIET; s = de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"Testing bytejump_body\"; " - "content:\"one\"; " - "byte_extract:4,0,two,string,hex; " - "byte_extract:4,0,three,string,hex; " - "content: \"four\"; offset:two; " - "content: \"five\"; offset:three; " - "sid:1;)"); + "(msg:\"Testing bytejump_body\"; " + "content:\"one\"; " + "byte_extract:4,0,two,string,hex; " + "byte_extract:4,0,three,string,hex; " + "content: \"four\"; offset:two; " + "content: \"five\"; offset:three; " + "sid:1;)"); if (de_ctx->sig_list == NULL) { result = 0; goto end; @@ -2453,13 +2305,10 @@ static int DetectByteExtractTest44(void) } cd = (DetectContentData *)sm->ctx; if (cd->flags & DETECT_CONTENT_RAWBYTES || - strncmp((char *)cd->content, "one", cd->content_len) != 0 || - cd->flags & DETECT_CONTENT_NOCASE || - cd->flags & DETECT_CONTENT_WITHIN || - cd->flags & DETECT_CONTENT_DISTANCE || - cd->flags & DETECT_CONTENT_FAST_PATTERN || - cd->flags & DETECT_CONTENT_RELATIVE_NEXT || - cd->flags & DETECT_CONTENT_NEGATED ) { + strncmp((char *)cd->content, "one", cd->content_len) != 0 || + cd->flags & DETECT_CONTENT_NOCASE || cd->flags & DETECT_CONTENT_WITHIN || + cd->flags & DETECT_CONTENT_DISTANCE || cd->flags & DETECT_CONTENT_FAST_PATTERN || + cd->flags & DETECT_CONTENT_RELATIVE_NEXT || cd->flags & DETECT_CONTENT_NEGATED) { printf("one failed\n"); result = 0; goto end; @@ -2471,14 +2320,11 @@ static int DetectByteExtractTest44(void) goto end; } bed1 = (DetectByteExtractData *)sm->ctx; - if (bed1->nbytes != 4 || - bed1->offset != 0 || - strcmp(bed1->name, "two") != 0 || - bed1->flags != DETECT_BYTE_EXTRACT_FLAG_STRING || - bed1->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE || - bed1->base != DETECT_BYTE_EXTRACT_BASE_HEX || - bed1->align_value != 0 || - bed1->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { + if (bed1->nbytes != 4 || bed1->offset != 0 || strcmp(bed1->name, "two") != 0 || + bed1->flags != DETECT_BYTE_EXTRACT_FLAG_STRING || + bed1->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE || + bed1->base != DETECT_BYTE_EXTRACT_BASE_HEX || bed1->align_value != 0 || + bed1->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { goto end; } if (bed1->local_id != 0) { @@ -2500,9 +2346,8 @@ static int DetectByteExtractTest44(void) } cd = (DetectContentData *)sm->ctx; if (strncmp((char *)cd->content, "four", cd->content_len) != 0 || - cd->flags != (DETECT_CONTENT_OFFSET_VAR | - DETECT_CONTENT_OFFSET) || - cd->offset != bed1->local_id) { + cd->flags != (DETECT_CONTENT_OFFSET_VAR | DETECT_CONTENT_OFFSET) || + cd->offset != bed1->local_id) { printf("four failed\n"); result = 0; goto end; @@ -2515,9 +2360,8 @@ static int DetectByteExtractTest44(void) } cd = (DetectContentData *)sm->ctx; if (strncmp((char *)cd->content, "five", cd->content_len) != 0 || - cd->flags != (DETECT_CONTENT_OFFSET_VAR | - DETECT_CONTENT_OFFSET) || - cd->offset != bed2->local_id) { + cd->flags != (DETECT_CONTENT_OFFSET_VAR | DETECT_CONTENT_OFFSET) || + cd->offset != bed2->local_id) { printf("five failed\n"); result = 0; goto end; @@ -2528,7 +2372,7 @@ static int DetectByteExtractTest44(void) result = 1; - end: +end: SigGroupCleanup(de_ctx); SigCleanSignatures(de_ctx); DetectEngineCtxFree(de_ctx); @@ -2551,11 +2395,11 @@ static int DetectByteExtractTest45(void) de_ctx->flags |= DE_QUIET; s = de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"Testing bytejump_body\"; " - "content:\"one\"; " - "byte_extract:4,0,two,string,hex; " - "content: \"three\"; depth:two; " - "sid:1;)"); + "(msg:\"Testing bytejump_body\"; " + "content:\"one\"; " + "byte_extract:4,0,two,string,hex; " + "content: \"three\"; depth:two; " + "sid:1;)"); if (de_ctx->sig_list == NULL) { result = 0; goto end; @@ -2573,13 +2417,10 @@ static int DetectByteExtractTest45(void) } cd = (DetectContentData *)sm->ctx; if (cd->flags & DETECT_CONTENT_RAWBYTES || - strncmp((char *)cd->content, "one", cd->content_len) != 0 || - cd->flags & DETECT_CONTENT_NOCASE || - cd->flags & DETECT_CONTENT_WITHIN || - cd->flags & DETECT_CONTENT_DISTANCE || - cd->flags & DETECT_CONTENT_FAST_PATTERN || - cd->flags & DETECT_CONTENT_RELATIVE_NEXT || - cd->flags & DETECT_CONTENT_NEGATED ) { + strncmp((char *)cd->content, "one", cd->content_len) != 0 || + cd->flags & DETECT_CONTENT_NOCASE || cd->flags & DETECT_CONTENT_WITHIN || + cd->flags & DETECT_CONTENT_DISTANCE || cd->flags & DETECT_CONTENT_FAST_PATTERN || + cd->flags & DETECT_CONTENT_RELATIVE_NEXT || cd->flags & DETECT_CONTENT_NEGATED) { printf("one failed\n"); result = 0; goto end; @@ -2591,14 +2432,11 @@ static int DetectByteExtractTest45(void) goto end; } bed = (DetectByteExtractData *)sm->ctx; - if (bed->nbytes != 4 || - bed->offset != 0 || - strcmp(bed->name, "two") != 0 || - bed->flags != DETECT_BYTE_EXTRACT_FLAG_STRING || - bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE || - bed->base != DETECT_BYTE_EXTRACT_BASE_HEX || - bed->align_value != 0 || - bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { + if (bed->nbytes != 4 || bed->offset != 0 || strcmp(bed->name, "two") != 0 || + bed->flags != DETECT_BYTE_EXTRACT_FLAG_STRING || + bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE || + bed->base != DETECT_BYTE_EXTRACT_BASE_HEX || bed->align_value != 0 || + bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { goto end; } if (bed->local_id != 0) { @@ -2613,10 +2451,8 @@ static int DetectByteExtractTest45(void) } cd = (DetectContentData *)sm->ctx; if (strncmp((char *)cd->content, "three", cd->content_len) != 0 || - cd->flags != (DETECT_CONTENT_DEPTH_VAR | - DETECT_CONTENT_DEPTH) || - cd->depth != bed->local_id || - cd->offset != 0) { + cd->flags != (DETECT_CONTENT_DEPTH_VAR | DETECT_CONTENT_DEPTH) || + cd->depth != bed->local_id || cd->offset != 0) { printf("three failed\n"); result = 0; goto end; @@ -2627,7 +2463,7 @@ static int DetectByteExtractTest45(void) result = 1; - end: +end: SigGroupCleanup(de_ctx); SigCleanSignatures(de_ctx); DetectEngineCtxFree(de_ctx); @@ -2651,13 +2487,13 @@ static int DetectByteExtractTest46(void) de_ctx->flags |= DE_QUIET; s = de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"Testing bytejump_body\"; " - "content:\"one\"; " - "byte_extract:4,0,two,string,hex; " - "byte_extract:4,0,three,string,hex; " - "content: \"four\"; depth:two; " - "content: \"five\"; depth:three; " - "sid:1;)"); + "(msg:\"Testing bytejump_body\"; " + "content:\"one\"; " + "byte_extract:4,0,two,string,hex; " + "byte_extract:4,0,three,string,hex; " + "content: \"four\"; depth:two; " + "content: \"five\"; depth:three; " + "sid:1;)"); if (de_ctx->sig_list == NULL) { result = 0; goto end; @@ -2675,13 +2511,10 @@ static int DetectByteExtractTest46(void) } cd = (DetectContentData *)sm->ctx; if (cd->flags & DETECT_CONTENT_RAWBYTES || - strncmp((char *)cd->content, "one", cd->content_len) != 0 || - cd->flags & DETECT_CONTENT_NOCASE || - cd->flags & DETECT_CONTENT_WITHIN || - cd->flags & DETECT_CONTENT_DISTANCE || - cd->flags & DETECT_CONTENT_FAST_PATTERN || - cd->flags & DETECT_CONTENT_RELATIVE_NEXT || - cd->flags & DETECT_CONTENT_NEGATED ) { + strncmp((char *)cd->content, "one", cd->content_len) != 0 || + cd->flags & DETECT_CONTENT_NOCASE || cd->flags & DETECT_CONTENT_WITHIN || + cd->flags & DETECT_CONTENT_DISTANCE || cd->flags & DETECT_CONTENT_FAST_PATTERN || + cd->flags & DETECT_CONTENT_RELATIVE_NEXT || cd->flags & DETECT_CONTENT_NEGATED) { printf("one failed\n"); result = 0; goto end; @@ -2693,14 +2526,11 @@ static int DetectByteExtractTest46(void) goto end; } bed1 = (DetectByteExtractData *)sm->ctx; - if (bed1->nbytes != 4 || - bed1->offset != 0 || - strcmp(bed1->name, "two") != 0 || - bed1->flags != DETECT_BYTE_EXTRACT_FLAG_STRING || - bed1->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE || - bed1->base != DETECT_BYTE_EXTRACT_BASE_HEX || - bed1->align_value != 0 || - bed1->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { + if (bed1->nbytes != 4 || bed1->offset != 0 || strcmp(bed1->name, "two") != 0 || + bed1->flags != DETECT_BYTE_EXTRACT_FLAG_STRING || + bed1->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE || + bed1->base != DETECT_BYTE_EXTRACT_BASE_HEX || bed1->align_value != 0 || + bed1->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { goto end; } if (bed1->local_id != 0) { @@ -2722,9 +2552,8 @@ static int DetectByteExtractTest46(void) } cd = (DetectContentData *)sm->ctx; if (strncmp((char *)cd->content, "four", cd->content_len) != 0 || - cd->flags != (DETECT_CONTENT_DEPTH_VAR | - DETECT_CONTENT_DEPTH) || - cd->depth != bed1->local_id) { + cd->flags != (DETECT_CONTENT_DEPTH_VAR | DETECT_CONTENT_DEPTH) || + cd->depth != bed1->local_id) { printf("four failed\n"); result = 0; goto end; @@ -2737,9 +2566,8 @@ static int DetectByteExtractTest46(void) } cd = (DetectContentData *)sm->ctx; if (strncmp((char *)cd->content, "five", cd->content_len) != 0 || - cd->flags != (DETECT_CONTENT_DEPTH_VAR | - DETECT_CONTENT_DEPTH) || - cd->depth != bed2->local_id) { + cd->flags != (DETECT_CONTENT_DEPTH_VAR | DETECT_CONTENT_DEPTH) || + cd->depth != bed2->local_id) { printf("five failed\n"); result = 0; goto end; @@ -2750,7 +2578,7 @@ static int DetectByteExtractTest46(void) result = 1; - end: +end: SigGroupCleanup(de_ctx); SigCleanSignatures(de_ctx); DetectEngineCtxFree(de_ctx); @@ -2773,11 +2601,11 @@ static int DetectByteExtractTest47(void) de_ctx->flags |= DE_QUIET; s = de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"Testing bytejump_body\"; " - "content:\"one\"; " - "byte_extract:4,0,two,string,hex; " - "content: \"three\"; distance:two; " - "sid:1;)"); + "(msg:\"Testing bytejump_body\"; " + "content:\"one\"; " + "byte_extract:4,0,two,string,hex; " + "content: \"three\"; distance:two; " + "sid:1;)"); if (de_ctx->sig_list == NULL) { result = 0; goto end; @@ -2795,13 +2623,10 @@ static int DetectByteExtractTest47(void) } cd = (DetectContentData *)sm->ctx; if (cd->flags & DETECT_CONTENT_RAWBYTES || - strncmp((char *)cd->content, "one", cd->content_len) != 0 || - cd->flags & DETECT_CONTENT_NOCASE || - cd->flags & DETECT_CONTENT_WITHIN || - cd->flags & DETECT_CONTENT_DISTANCE || - cd->flags & DETECT_CONTENT_FAST_PATTERN || - !(cd->flags & DETECT_CONTENT_RELATIVE_NEXT) || - cd->flags & DETECT_CONTENT_NEGATED ) { + strncmp((char *)cd->content, "one", cd->content_len) != 0 || + cd->flags & DETECT_CONTENT_NOCASE || cd->flags & DETECT_CONTENT_WITHIN || + cd->flags & DETECT_CONTENT_DISTANCE || cd->flags & DETECT_CONTENT_FAST_PATTERN || + !(cd->flags & DETECT_CONTENT_RELATIVE_NEXT) || cd->flags & DETECT_CONTENT_NEGATED) { printf("one failed\n"); result = 0; goto end; @@ -2813,14 +2638,11 @@ static int DetectByteExtractTest47(void) goto end; } bed = (DetectByteExtractData *)sm->ctx; - if (bed->nbytes != 4 || - bed->offset != 0 || - strcmp(bed->name, "two") != 0 || - bed->flags != DETECT_BYTE_EXTRACT_FLAG_STRING || - bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE || - bed->base != DETECT_BYTE_EXTRACT_BASE_HEX || - bed->align_value != 0 || - bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { + if (bed->nbytes != 4 || bed->offset != 0 || strcmp(bed->name, "two") != 0 || + bed->flags != DETECT_BYTE_EXTRACT_FLAG_STRING || + bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE || + bed->base != DETECT_BYTE_EXTRACT_BASE_HEX || bed->align_value != 0 || + bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { goto end; } if (bed->local_id != 0) { @@ -2835,11 +2657,8 @@ static int DetectByteExtractTest47(void) } cd = (DetectContentData *)sm->ctx; if (strncmp((char *)cd->content, "three", cd->content_len) != 0 || - cd->flags != (DETECT_CONTENT_DISTANCE_VAR | - DETECT_CONTENT_DISTANCE) || - cd->distance != bed->local_id || - cd->offset != 0 || - cd->depth != 0) { + cd->flags != (DETECT_CONTENT_DISTANCE_VAR | DETECT_CONTENT_DISTANCE) || + cd->distance != bed->local_id || cd->offset != 0 || cd->depth != 0) { printf("three failed\n"); result = 0; goto end; @@ -2850,7 +2669,7 @@ static int DetectByteExtractTest47(void) result = 1; - end: +end: SigGroupCleanup(de_ctx); SigCleanSignatures(de_ctx); DetectEngineCtxFree(de_ctx); @@ -2874,13 +2693,13 @@ static int DetectByteExtractTest48(void) de_ctx->flags |= DE_QUIET; s = de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"Testing bytejump_body\"; " - "content:\"one\"; " - "byte_extract:4,0,two,string,hex; " - "byte_extract:4,0,three,string,hex; " - "content: \"four\"; distance:two; " - "content: \"five\"; distance:three; " - "sid:1;)"); + "(msg:\"Testing bytejump_body\"; " + "content:\"one\"; " + "byte_extract:4,0,two,string,hex; " + "byte_extract:4,0,three,string,hex; " + "content: \"four\"; distance:two; " + "content: \"five\"; distance:three; " + "sid:1;)"); if (de_ctx->sig_list == NULL) { result = 0; goto end; @@ -2898,13 +2717,10 @@ static int DetectByteExtractTest48(void) } cd = (DetectContentData *)sm->ctx; if (cd->flags & DETECT_CONTENT_RAWBYTES || - strncmp((char *)cd->content, "one", cd->content_len) != 0 || - cd->flags & DETECT_CONTENT_NOCASE || - cd->flags & DETECT_CONTENT_WITHIN || - cd->flags & DETECT_CONTENT_DISTANCE || - cd->flags & DETECT_CONTENT_FAST_PATTERN || - !(cd->flags & DETECT_CONTENT_RELATIVE_NEXT) || - cd->flags & DETECT_CONTENT_NEGATED ) { + strncmp((char *)cd->content, "one", cd->content_len) != 0 || + cd->flags & DETECT_CONTENT_NOCASE || cd->flags & DETECT_CONTENT_WITHIN || + cd->flags & DETECT_CONTENT_DISTANCE || cd->flags & DETECT_CONTENT_FAST_PATTERN || + !(cd->flags & DETECT_CONTENT_RELATIVE_NEXT) || cd->flags & DETECT_CONTENT_NEGATED) { printf("one failed\n"); result = 0; goto end; @@ -2916,14 +2732,11 @@ static int DetectByteExtractTest48(void) goto end; } bed1 = (DetectByteExtractData *)sm->ctx; - if (bed1->nbytes != 4 || - bed1->offset != 0 || - strcmp(bed1->name, "two") != 0 || - bed1->flags != DETECT_BYTE_EXTRACT_FLAG_STRING || - bed1->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE || - bed1->base != DETECT_BYTE_EXTRACT_BASE_HEX || - bed1->align_value != 0 || - bed1->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { + if (bed1->nbytes != 4 || bed1->offset != 0 || strcmp(bed1->name, "two") != 0 || + bed1->flags != DETECT_BYTE_EXTRACT_FLAG_STRING || + bed1->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE || + bed1->base != DETECT_BYTE_EXTRACT_BASE_HEX || bed1->align_value != 0 || + bed1->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { goto end; } if (bed1->local_id != 0) { @@ -2945,12 +2758,9 @@ static int DetectByteExtractTest48(void) } cd = (DetectContentData *)sm->ctx; if (strncmp((char *)cd->content, "four", cd->content_len) != 0 || - cd->flags != (DETECT_CONTENT_DISTANCE_VAR | - DETECT_CONTENT_DISTANCE | - DETECT_CONTENT_DISTANCE_NEXT) || - cd->distance != bed1->local_id || - cd->depth != 0 || - cd->offset != 0) { + cd->flags != (DETECT_CONTENT_DISTANCE_VAR | DETECT_CONTENT_DISTANCE | + DETECT_CONTENT_DISTANCE_NEXT) || + cd->distance != bed1->local_id || cd->depth != 0 || cd->offset != 0) { printf("four failed\n"); result = 0; goto end; @@ -2963,11 +2773,8 @@ static int DetectByteExtractTest48(void) } cd = (DetectContentData *)sm->ctx; if (strncmp((char *)cd->content, "five", cd->content_len) != 0 || - cd->flags != (DETECT_CONTENT_DISTANCE_VAR | - DETECT_CONTENT_DISTANCE) || - cd->distance != bed2->local_id || - cd->depth != 0 || - cd->offset != 0) { + cd->flags != (DETECT_CONTENT_DISTANCE_VAR | DETECT_CONTENT_DISTANCE) || + cd->distance != bed2->local_id || cd->depth != 0 || cd->offset != 0) { printf("five failed\n"); result = 0; goto end; @@ -2978,7 +2785,7 @@ static int DetectByteExtractTest48(void) result = 1; - end: +end: SigGroupCleanup(de_ctx); SigCleanSignatures(de_ctx); DetectEngineCtxFree(de_ctx); @@ -3001,11 +2808,11 @@ static int DetectByteExtractTest49(void) de_ctx->flags |= DE_QUIET; s = de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"Testing bytejump_body\"; " - "content:\"one\"; " - "byte_extract:4,0,two,string,hex; " - "content: \"three\"; within:two; " - "sid:1;)"); + "(msg:\"Testing bytejump_body\"; " + "content:\"one\"; " + "byte_extract:4,0,two,string,hex; " + "content: \"three\"; within:two; " + "sid:1;)"); if (de_ctx->sig_list == NULL) { result = 0; goto end; @@ -3023,13 +2830,10 @@ static int DetectByteExtractTest49(void) } cd = (DetectContentData *)sm->ctx; if (cd->flags & DETECT_CONTENT_RAWBYTES || - strncmp((char *)cd->content, "one", cd->content_len) != 0 || - cd->flags & DETECT_CONTENT_NOCASE || - cd->flags & DETECT_CONTENT_WITHIN || - cd->flags & DETECT_CONTENT_DISTANCE || - cd->flags & DETECT_CONTENT_FAST_PATTERN || - !(cd->flags & DETECT_CONTENT_RELATIVE_NEXT) || - cd->flags & DETECT_CONTENT_NEGATED ) { + strncmp((char *)cd->content, "one", cd->content_len) != 0 || + cd->flags & DETECT_CONTENT_NOCASE || cd->flags & DETECT_CONTENT_WITHIN || + cd->flags & DETECT_CONTENT_DISTANCE || cd->flags & DETECT_CONTENT_FAST_PATTERN || + !(cd->flags & DETECT_CONTENT_RELATIVE_NEXT) || cd->flags & DETECT_CONTENT_NEGATED) { printf("one failed\n"); result = 0; goto end; @@ -3041,14 +2845,11 @@ static int DetectByteExtractTest49(void) goto end; } bed = (DetectByteExtractData *)sm->ctx; - if (bed->nbytes != 4 || - bed->offset != 0 || - strcmp(bed->name, "two") != 0 || - bed->flags != DETECT_BYTE_EXTRACT_FLAG_STRING || - bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE || - bed->base != DETECT_BYTE_EXTRACT_BASE_HEX || - bed->align_value != 0 || - bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { + if (bed->nbytes != 4 || bed->offset != 0 || strcmp(bed->name, "two") != 0 || + bed->flags != DETECT_BYTE_EXTRACT_FLAG_STRING || + bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE || + bed->base != DETECT_BYTE_EXTRACT_BASE_HEX || bed->align_value != 0 || + bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { goto end; } if (bed->local_id != 0) { @@ -3063,12 +2864,8 @@ static int DetectByteExtractTest49(void) } cd = (DetectContentData *)sm->ctx; if (strncmp((char *)cd->content, "three", cd->content_len) != 0 || - cd->flags != (DETECT_CONTENT_WITHIN_VAR | - DETECT_CONTENT_WITHIN) || - cd->within != bed->local_id || - cd->offset != 0 || - cd->depth != 0 || - cd->distance != 0) { + cd->flags != (DETECT_CONTENT_WITHIN_VAR | DETECT_CONTENT_WITHIN) || + cd->within != bed->local_id || cd->offset != 0 || cd->depth != 0 || cd->distance != 0) { printf("three failed\n"); result = 0; goto end; @@ -3079,7 +2876,7 @@ static int DetectByteExtractTest49(void) result = 1; - end: +end: SigGroupCleanup(de_ctx); SigCleanSignatures(de_ctx); DetectEngineCtxFree(de_ctx); @@ -3103,13 +2900,13 @@ static int DetectByteExtractTest50(void) de_ctx->flags |= DE_QUIET; s = de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"Testing bytejump_body\"; " - "content:\"one\"; " - "byte_extract:4,0,two,string,hex; " - "byte_extract:4,0,three,string,hex; " - "content: \"four\"; within:two; " - "content: \"five\"; within:three; " - "sid:1;)"); + "(msg:\"Testing bytejump_body\"; " + "content:\"one\"; " + "byte_extract:4,0,two,string,hex; " + "byte_extract:4,0,three,string,hex; " + "content: \"four\"; within:two; " + "content: \"five\"; within:three; " + "sid:1;)"); if (de_ctx->sig_list == NULL) { result = 0; goto end; @@ -3127,13 +2924,10 @@ static int DetectByteExtractTest50(void) } cd = (DetectContentData *)sm->ctx; if (cd->flags & DETECT_CONTENT_RAWBYTES || - strncmp((char *)cd->content, "one", cd->content_len) != 0 || - cd->flags & DETECT_CONTENT_NOCASE || - cd->flags & DETECT_CONTENT_WITHIN || - cd->flags & DETECT_CONTENT_DISTANCE || - cd->flags & DETECT_CONTENT_FAST_PATTERN || - !(cd->flags & DETECT_CONTENT_RELATIVE_NEXT) || - cd->flags & DETECT_CONTENT_NEGATED ) { + strncmp((char *)cd->content, "one", cd->content_len) != 0 || + cd->flags & DETECT_CONTENT_NOCASE || cd->flags & DETECT_CONTENT_WITHIN || + cd->flags & DETECT_CONTENT_DISTANCE || cd->flags & DETECT_CONTENT_FAST_PATTERN || + !(cd->flags & DETECT_CONTENT_RELATIVE_NEXT) || cd->flags & DETECT_CONTENT_NEGATED) { printf("one failed\n"); result = 0; goto end; @@ -3145,14 +2939,11 @@ static int DetectByteExtractTest50(void) goto end; } bed1 = (DetectByteExtractData *)sm->ctx; - if (bed1->nbytes != 4 || - bed1->offset != 0 || - strcmp(bed1->name, "two") != 0 || - bed1->flags != DETECT_BYTE_EXTRACT_FLAG_STRING || - bed1->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE || - bed1->base != DETECT_BYTE_EXTRACT_BASE_HEX || - bed1->align_value != 0 || - bed1->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { + if (bed1->nbytes != 4 || bed1->offset != 0 || strcmp(bed1->name, "two") != 0 || + bed1->flags != DETECT_BYTE_EXTRACT_FLAG_STRING || + bed1->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE || + bed1->base != DETECT_BYTE_EXTRACT_BASE_HEX || bed1->align_value != 0 || + bed1->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { goto end; } if (bed1->local_id != 0) { @@ -3174,13 +2965,10 @@ static int DetectByteExtractTest50(void) } cd = (DetectContentData *)sm->ctx; if (strncmp((char *)cd->content, "four", cd->content_len) != 0 || - cd->flags != (DETECT_CONTENT_WITHIN_VAR | - DETECT_CONTENT_WITHIN| - DETECT_CONTENT_WITHIN_NEXT) || - cd->within != bed1->local_id || - cd->depth != 0 || - cd->offset != 0 || - cd->distance != 0) { + cd->flags != (DETECT_CONTENT_WITHIN_VAR | DETECT_CONTENT_WITHIN | + DETECT_CONTENT_WITHIN_NEXT) || + cd->within != bed1->local_id || cd->depth != 0 || cd->offset != 0 || + cd->distance != 0) { printf("four failed\n"); result = 0; goto end; @@ -3193,12 +2981,9 @@ static int DetectByteExtractTest50(void) } cd = (DetectContentData *)sm->ctx; if (strncmp((char *)cd->content, "five", cd->content_len) != 0 || - cd->flags != (DETECT_CONTENT_WITHIN_VAR | - DETECT_CONTENT_WITHIN) || - cd->within != bed2->local_id || - cd->depth != 0 || - cd->offset != 0 || - cd->distance != 0) { + cd->flags != (DETECT_CONTENT_WITHIN_VAR | DETECT_CONTENT_WITHIN) || + cd->within != bed2->local_id || cd->depth != 0 || cd->offset != 0 || + cd->distance != 0) { printf("five failed\n"); result = 0; goto end; @@ -3209,7 +2994,7 @@ static int DetectByteExtractTest50(void) result = 1; - end: +end: SigGroupCleanup(de_ctx); SigCleanSignatures(de_ctx); DetectEngineCtxFree(de_ctx); @@ -3233,11 +3018,11 @@ static int DetectByteExtractTest51(void) de_ctx->flags |= DE_QUIET; s = de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"Testing bytejump_body\"; " - "content:\"one\"; " - "byte_extract:4,0,two,string,hex; " - "byte_test: 2,=,10, two; " - "sid:1;)"); + "(msg:\"Testing bytejump_body\"; " + "content:\"one\"; " + "byte_extract:4,0,two,string,hex; " + "byte_test: 2,=,10, two; " + "sid:1;)"); if (de_ctx->sig_list == NULL) { result = 0; goto end; @@ -3255,13 +3040,10 @@ static int DetectByteExtractTest51(void) } cd = (DetectContentData *)sm->ctx; if (cd->flags & DETECT_CONTENT_RAWBYTES || - strncmp((char *)cd->content, "one", cd->content_len) != 0 || - cd->flags & DETECT_CONTENT_NOCASE || - cd->flags & DETECT_CONTENT_WITHIN || - cd->flags & DETECT_CONTENT_DISTANCE || - cd->flags & DETECT_CONTENT_FAST_PATTERN || - cd->flags & DETECT_CONTENT_RELATIVE_NEXT || - cd->flags & DETECT_CONTENT_NEGATED ) { + strncmp((char *)cd->content, "one", cd->content_len) != 0 || + cd->flags & DETECT_CONTENT_NOCASE || cd->flags & DETECT_CONTENT_WITHIN || + cd->flags & DETECT_CONTENT_DISTANCE || cd->flags & DETECT_CONTENT_FAST_PATTERN || + cd->flags & DETECT_CONTENT_RELATIVE_NEXT || cd->flags & DETECT_CONTENT_NEGATED) { printf("one failed\n"); result = 0; goto end; @@ -3273,14 +3055,11 @@ static int DetectByteExtractTest51(void) goto end; } bed = (DetectByteExtractData *)sm->ctx; - if (bed->nbytes != 4 || - bed->offset != 0 || - strcmp(bed->name, "two") != 0 || - bed->flags != DETECT_BYTE_EXTRACT_FLAG_STRING || - bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE || - bed->base != DETECT_BYTE_EXTRACT_BASE_HEX || - bed->align_value != 0 || - bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { + if (bed->nbytes != 4 || bed->offset != 0 || strcmp(bed->name, "two") != 0 || + bed->flags != DETECT_BYTE_EXTRACT_FLAG_STRING || + bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE || + bed->base != DETECT_BYTE_EXTRACT_BASE_HEX || bed->align_value != 0 || + bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { goto end; } if (bed->local_id != 0) { @@ -3294,9 +3073,7 @@ static int DetectByteExtractTest51(void) goto end; } btd = (DetectBytetestData *)sm->ctx; - if (btd->flags != DETECT_BYTETEST_OFFSET_VAR || - btd->value != 10 || - btd->offset != 0) { + if (btd->flags != DETECT_BYTETEST_OFFSET_VAR || btd->value != 10 || btd->offset != 0) { printf("three failed\n"); result = 0; goto end; @@ -3307,7 +3084,7 @@ static int DetectByteExtractTest51(void) result = 1; - end: +end: SigGroupCleanup(de_ctx); SigCleanSignatures(de_ctx); DetectEngineCtxFree(de_ctx); @@ -3331,13 +3108,13 @@ static int DetectByteExtractTest52(void) de_ctx->flags |= DE_QUIET; s = de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"Testing bytejump_body\"; " - "content:\"one\"; " - "byte_extract:4,0,two,string,hex; " - "byte_extract:4,0,three,string,hex; " - "byte_test: 2,=,two,three; " - "byte_test: 3,=,10,three; " - "sid:1;)"); + "(msg:\"Testing bytejump_body\"; " + "content:\"one\"; " + "byte_extract:4,0,two,string,hex; " + "byte_extract:4,0,three,string,hex; " + "byte_test: 2,=,two,three; " + "byte_test: 3,=,10,three; " + "sid:1;)"); if (de_ctx->sig_list == NULL) { result = 0; goto end; @@ -3355,13 +3132,10 @@ static int DetectByteExtractTest52(void) } cd = (DetectContentData *)sm->ctx; if (cd->flags & DETECT_CONTENT_RAWBYTES || - strncmp((char *)cd->content, "one", cd->content_len) != 0 || - cd->flags & DETECT_CONTENT_NOCASE || - cd->flags & DETECT_CONTENT_WITHIN || - cd->flags & DETECT_CONTENT_DISTANCE || - cd->flags & DETECT_CONTENT_FAST_PATTERN || - cd->flags & DETECT_CONTENT_RELATIVE_NEXT || - cd->flags & DETECT_CONTENT_NEGATED ) { + strncmp((char *)cd->content, "one", cd->content_len) != 0 || + cd->flags & DETECT_CONTENT_NOCASE || cd->flags & DETECT_CONTENT_WITHIN || + cd->flags & DETECT_CONTENT_DISTANCE || cd->flags & DETECT_CONTENT_FAST_PATTERN || + cd->flags & DETECT_CONTENT_RELATIVE_NEXT || cd->flags & DETECT_CONTENT_NEGATED) { printf("one failed\n"); result = 0; goto end; @@ -3373,14 +3147,11 @@ static int DetectByteExtractTest52(void) goto end; } bed1 = (DetectByteExtractData *)sm->ctx; - if (bed1->nbytes != 4 || - bed1->offset != 0 || - strcmp(bed1->name, "two") != 0 || - bed1->flags != DETECT_BYTE_EXTRACT_FLAG_STRING || - bed1->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE || - bed1->base != DETECT_BYTE_EXTRACT_BASE_HEX || - bed1->align_value != 0 || - bed1->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { + if (bed1->nbytes != 4 || bed1->offset != 0 || strcmp(bed1->name, "two") != 0 || + bed1->flags != DETECT_BYTE_EXTRACT_FLAG_STRING || + bed1->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE || + bed1->base != DETECT_BYTE_EXTRACT_BASE_HEX || bed1->align_value != 0 || + bed1->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { goto end; } if (bed1->local_id != 0) { @@ -3400,10 +3171,8 @@ static int DetectByteExtractTest52(void) goto end; } btd = (DetectBytetestData *)sm->ctx; - if (btd->flags != (DETECT_BYTETEST_OFFSET_VAR | - DETECT_BYTETEST_VALUE_VAR) || - btd->value != 0 || - btd->offset != 1) { + if (btd->flags != (DETECT_BYTETEST_OFFSET_VAR | DETECT_BYTETEST_VALUE_VAR) || btd->value != 0 || + btd->offset != 1) { printf("three failed\n"); result = 0; goto end; @@ -3415,9 +3184,7 @@ static int DetectByteExtractTest52(void) goto end; } btd = (DetectBytetestData *)sm->ctx; - if (btd->flags != DETECT_BYTETEST_OFFSET_VAR || - btd->value != 10 || - btd->offset != 1) { + if (btd->flags != DETECT_BYTETEST_OFFSET_VAR || btd->value != 10 || btd->offset != 1) { printf("four failed\n"); result = 0; goto end; @@ -3428,7 +3195,7 @@ static int DetectByteExtractTest52(void) result = 1; - end: +end: SigGroupCleanup(de_ctx); SigCleanSignatures(de_ctx); DetectEngineCtxFree(de_ctx); @@ -3452,11 +3219,11 @@ static int DetectByteExtractTest53(void) de_ctx->flags |= DE_QUIET; s = de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"Testing bytejump_body\"; " - "content:\"one\"; " - "byte_extract:4,0,two,string,hex; " - "byte_jump: 2,two; " - "sid:1;)"); + "(msg:\"Testing bytejump_body\"; " + "content:\"one\"; " + "byte_extract:4,0,two,string,hex; " + "byte_jump: 2,two; " + "sid:1;)"); if (de_ctx->sig_list == NULL) { result = 0; goto end; @@ -3474,13 +3241,10 @@ static int DetectByteExtractTest53(void) } cd = (DetectContentData *)sm->ctx; if (cd->flags & DETECT_CONTENT_RAWBYTES || - strncmp((char *)cd->content, "one", cd->content_len) != 0 || - cd->flags & DETECT_CONTENT_NOCASE || - cd->flags & DETECT_CONTENT_WITHIN || - cd->flags & DETECT_CONTENT_DISTANCE || - cd->flags & DETECT_CONTENT_FAST_PATTERN || - cd->flags & DETECT_CONTENT_RELATIVE_NEXT || - cd->flags & DETECT_CONTENT_NEGATED ) { + strncmp((char *)cd->content, "one", cd->content_len) != 0 || + cd->flags & DETECT_CONTENT_NOCASE || cd->flags & DETECT_CONTENT_WITHIN || + cd->flags & DETECT_CONTENT_DISTANCE || cd->flags & DETECT_CONTENT_FAST_PATTERN || + cd->flags & DETECT_CONTENT_RELATIVE_NEXT || cd->flags & DETECT_CONTENT_NEGATED) { printf("one failed\n"); result = 0; goto end; @@ -3492,14 +3256,11 @@ static int DetectByteExtractTest53(void) goto end; } bed = (DetectByteExtractData *)sm->ctx; - if (bed->nbytes != 4 || - bed->offset != 0 || - strcmp(bed->name, "two") != 0 || - bed->flags != DETECT_BYTE_EXTRACT_FLAG_STRING || - bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE || - bed->base != DETECT_BYTE_EXTRACT_BASE_HEX || - bed->align_value != 0 || - bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { + if (bed->nbytes != 4 || bed->offset != 0 || strcmp(bed->name, "two") != 0 || + bed->flags != DETECT_BYTE_EXTRACT_FLAG_STRING || + bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE || + bed->base != DETECT_BYTE_EXTRACT_BASE_HEX || bed->align_value != 0 || + bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { goto end; } if (bed->local_id != 0) { @@ -3513,8 +3274,7 @@ static int DetectByteExtractTest53(void) goto end; } bjd = (DetectBytejumpData *)sm->ctx; - if (bjd->flags != DETECT_CONTENT_OFFSET_VAR || - bjd->offset != 0) { + if (bjd->flags != DETECT_CONTENT_OFFSET_VAR || bjd->offset != 0) { printf("three failed\n"); result = 0; goto end; @@ -3525,7 +3285,7 @@ static int DetectByteExtractTest53(void) result = 1; - end: +end: SigGroupCleanup(de_ctx); SigCleanSignatures(de_ctx); DetectEngineCtxFree(de_ctx); @@ -3549,13 +3309,13 @@ static int DetectByteExtractTest54(void) de_ctx->flags |= DE_QUIET; s = de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"Testing bytejump_body\"; " - "content:\"one\"; " - "byte_extract:4,0,two,string,hex; " - "byte_extract:4,0,three,string,hex; " - "byte_jump: 2,two; " - "byte_jump: 3,three; " - "sid:1;)"); + "(msg:\"Testing bytejump_body\"; " + "content:\"one\"; " + "byte_extract:4,0,two,string,hex; " + "byte_extract:4,0,three,string,hex; " + "byte_jump: 2,two; " + "byte_jump: 3,three; " + "sid:1;)"); if (de_ctx->sig_list == NULL) { result = 0; goto end; @@ -3573,13 +3333,10 @@ static int DetectByteExtractTest54(void) } cd = (DetectContentData *)sm->ctx; if (cd->flags & DETECT_CONTENT_RAWBYTES || - strncmp((char *)cd->content, "one", cd->content_len) != 0 || - cd->flags & DETECT_CONTENT_NOCASE || - cd->flags & DETECT_CONTENT_WITHIN || - cd->flags & DETECT_CONTENT_DISTANCE || - cd->flags & DETECT_CONTENT_FAST_PATTERN || - cd->flags & DETECT_CONTENT_RELATIVE_NEXT || - cd->flags & DETECT_CONTENT_NEGATED ) { + strncmp((char *)cd->content, "one", cd->content_len) != 0 || + cd->flags & DETECT_CONTENT_NOCASE || cd->flags & DETECT_CONTENT_WITHIN || + cd->flags & DETECT_CONTENT_DISTANCE || cd->flags & DETECT_CONTENT_FAST_PATTERN || + cd->flags & DETECT_CONTENT_RELATIVE_NEXT || cd->flags & DETECT_CONTENT_NEGATED) { printf("one failed\n"); result = 0; goto end; @@ -3591,14 +3348,11 @@ static int DetectByteExtractTest54(void) goto end; } bed1 = (DetectByteExtractData *)sm->ctx; - if (bed1->nbytes != 4 || - bed1->offset != 0 || - strcmp(bed1->name, "two") != 0 || - bed1->flags != DETECT_BYTE_EXTRACT_FLAG_STRING || - bed1->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE || - bed1->base != DETECT_BYTE_EXTRACT_BASE_HEX || - bed1->align_value != 0 || - bed1->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { + if (bed1->nbytes != 4 || bed1->offset != 0 || strcmp(bed1->name, "two") != 0 || + bed1->flags != DETECT_BYTE_EXTRACT_FLAG_STRING || + bed1->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE || + bed1->base != DETECT_BYTE_EXTRACT_BASE_HEX || bed1->align_value != 0 || + bed1->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { goto end; } if (bed1->local_id != 0) { @@ -3618,8 +3372,7 @@ static int DetectByteExtractTest54(void) goto end; } bjd = (DetectBytejumpData *)sm->ctx; - if (bjd->flags != DETECT_CONTENT_OFFSET_VAR || - bjd->offset != 0) { + if (bjd->flags != DETECT_CONTENT_OFFSET_VAR || bjd->offset != 0) { printf("three failed\n"); result = 0; goto end; @@ -3631,8 +3384,7 @@ static int DetectByteExtractTest54(void) goto end; } bjd = (DetectBytejumpData *)sm->ctx; - if (bjd->flags != DETECT_CONTENT_OFFSET_VAR || - bjd->offset != 1) { + if (bjd->flags != DETECT_CONTENT_OFFSET_VAR || bjd->offset != 1) { printf("four failed\n"); result = 0; goto end; @@ -3643,7 +3395,7 @@ static int DetectByteExtractTest54(void) result = 1; - end: +end: SigGroupCleanup(de_ctx); SigCleanSignatures(de_ctx); DetectEngineCtxFree(de_ctx); @@ -3667,14 +3419,14 @@ static int DetectByteExtractTest55(void) de_ctx->flags |= DE_QUIET; s = de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"Testing byte_extract\"; " - "content:\"one\"; " - "byte_extract:4,0,two,string,hex; " - "byte_extract:4,0,three,string,hex; " - "byte_extract:4,0,four,string,hex; " - "byte_extract:4,0,five,string,hex; " - "content: \"four\"; within:two; distance:three; " - "sid:1;)"); + "(msg:\"Testing byte_extract\"; " + "content:\"one\"; " + "byte_extract:4,0,two,string,hex; " + "byte_extract:4,0,three,string,hex; " + "byte_extract:4,0,four,string,hex; " + "byte_extract:4,0,five,string,hex; " + "content: \"four\"; within:two; distance:three; " + "sid:1;)"); if (de_ctx->sig_list == NULL) { goto end; } @@ -3689,13 +3441,10 @@ static int DetectByteExtractTest55(void) } cd = (DetectContentData *)sm->ctx; if (cd->flags & DETECT_CONTENT_RAWBYTES || - strncmp((char *)cd->content, "one", cd->content_len) != 0 || - cd->flags & DETECT_CONTENT_NOCASE || - cd->flags & DETECT_CONTENT_WITHIN || - cd->flags & DETECT_CONTENT_DISTANCE || - cd->flags & DETECT_CONTENT_FAST_PATTERN || - !(cd->flags & DETECT_CONTENT_RELATIVE_NEXT) || - cd->flags & DETECT_CONTENT_NEGATED ) { + strncmp((char *)cd->content, "one", cd->content_len) != 0 || + cd->flags & DETECT_CONTENT_NOCASE || cd->flags & DETECT_CONTENT_WITHIN || + cd->flags & DETECT_CONTENT_DISTANCE || cd->flags & DETECT_CONTENT_FAST_PATTERN || + !(cd->flags & DETECT_CONTENT_RELATIVE_NEXT) || cd->flags & DETECT_CONTENT_NEGATED) { printf("one failed: "); goto end; } @@ -3705,14 +3454,11 @@ static int DetectByteExtractTest55(void) goto end; } bed1 = (DetectByteExtractData *)sm->ctx; - if (bed1->nbytes != 4 || - bed1->offset != 0 || - strcmp(bed1->name, "two") != 0 || - bed1->flags != DETECT_BYTE_EXTRACT_FLAG_STRING || - bed1->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE || - bed1->base != DETECT_BYTE_EXTRACT_BASE_HEX || - bed1->align_value != 0 || - bed1->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { + if (bed1->nbytes != 4 || bed1->offset != 0 || strcmp(bed1->name, "two") != 0 || + bed1->flags != DETECT_BYTE_EXTRACT_FLAG_STRING || + bed1->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE || + bed1->base != DETECT_BYTE_EXTRACT_BASE_HEX || bed1->align_value != 0 || + bed1->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { goto end; } if (bed1->local_id != 0) { @@ -3741,12 +3487,9 @@ static int DetectByteExtractTest55(void) } cd = (DetectContentData *)sm->ctx; if (strncmp((char *)cd->content, "four", cd->content_len) != 0 || - cd->flags != (DETECT_CONTENT_DISTANCE_VAR | - DETECT_CONTENT_WITHIN_VAR | - DETECT_CONTENT_DISTANCE | - DETECT_CONTENT_WITHIN) || - cd->within != bed1->local_id || - cd->distance != bed2->local_id) { + cd->flags != (DETECT_CONTENT_DISTANCE_VAR | DETECT_CONTENT_WITHIN_VAR | + DETECT_CONTENT_DISTANCE | DETECT_CONTENT_WITHIN) || + cd->within != bed1->local_id || cd->distance != bed2->local_id) { printf("four failed: "); goto end; } @@ -3757,7 +3500,7 @@ static int DetectByteExtractTest55(void) result = 1; - end: +end: SigGroupCleanup(de_ctx); SigCleanSignatures(de_ctx); DetectEngineCtxFree(de_ctx); @@ -3781,15 +3524,15 @@ static int DetectByteExtractTest56(void) de_ctx->flags |= DE_QUIET; s = de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"Testing bytejump_body\"; " - "uricontent:\"urione\"; " - "content:\"one\"; " - "byte_extract:4,0,two,string,hex; " - "byte_extract:4,0,three,string,hex; " - "byte_extract:4,0,four,string,hex; " - "byte_extract:4,0,five,string,hex; " - "content: \"four\"; within:two; distance:three; " - "sid:1;)"); + "(msg:\"Testing bytejump_body\"; " + "uricontent:\"urione\"; " + "content:\"one\"; " + "byte_extract:4,0,two,string,hex; " + "byte_extract:4,0,three,string,hex; " + "byte_extract:4,0,four,string,hex; " + "byte_extract:4,0,five,string,hex; " + "content: \"four\"; within:two; distance:three; " + "sid:1;)"); if (de_ctx->sig_list == NULL) { result = 0; goto end; @@ -3807,13 +3550,10 @@ static int DetectByteExtractTest56(void) } cd = (DetectContentData *)sm->ctx; if (cd->flags & DETECT_CONTENT_RAWBYTES || - strncmp((char *)cd->content, "urione", cd->content_len) != 0 || - cd->flags & DETECT_CONTENT_NOCASE || - cd->flags & DETECT_CONTENT_WITHIN || - cd->flags & DETECT_CONTENT_DISTANCE || - cd->flags & DETECT_CONTENT_FAST_PATTERN || - cd->flags & DETECT_CONTENT_RELATIVE_NEXT || - cd->flags & DETECT_CONTENT_NEGATED ) { + strncmp((char *)cd->content, "urione", cd->content_len) != 0 || + cd->flags & DETECT_CONTENT_NOCASE || cd->flags & DETECT_CONTENT_WITHIN || + cd->flags & DETECT_CONTENT_DISTANCE || cd->flags & DETECT_CONTENT_FAST_PATTERN || + cd->flags & DETECT_CONTENT_RELATIVE_NEXT || cd->flags & DETECT_CONTENT_NEGATED) { printf("one failed\n"); result = 0; goto end; @@ -3829,13 +3569,10 @@ static int DetectByteExtractTest56(void) } cd = (DetectContentData *)sm->ctx; if (cd->flags & DETECT_CONTENT_RAWBYTES || - strncmp((char *)cd->content, "one", cd->content_len) != 0 || - cd->flags & DETECT_CONTENT_NOCASE || - cd->flags & DETECT_CONTENT_WITHIN || - cd->flags & DETECT_CONTENT_DISTANCE || - cd->flags & DETECT_CONTENT_FAST_PATTERN || - !(cd->flags & DETECT_CONTENT_RELATIVE_NEXT) || - cd->flags & DETECT_CONTENT_NEGATED ) { + strncmp((char *)cd->content, "one", cd->content_len) != 0 || + cd->flags & DETECT_CONTENT_NOCASE || cd->flags & DETECT_CONTENT_WITHIN || + cd->flags & DETECT_CONTENT_DISTANCE || cd->flags & DETECT_CONTENT_FAST_PATTERN || + !(cd->flags & DETECT_CONTENT_RELATIVE_NEXT) || cd->flags & DETECT_CONTENT_NEGATED) { printf("one failed\n"); result = 0; goto end; @@ -3847,14 +3584,11 @@ static int DetectByteExtractTest56(void) goto end; } bed1 = (DetectByteExtractData *)sm->ctx; - if (bed1->nbytes != 4 || - bed1->offset != 0 || - strcmp(bed1->name, "two") != 0 || - bed1->flags != DETECT_BYTE_EXTRACT_FLAG_STRING || - bed1->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE || - bed1->base != DETECT_BYTE_EXTRACT_BASE_HEX || - bed1->align_value != 0 || - bed1->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { + if (bed1->nbytes != 4 || bed1->offset != 0 || strcmp(bed1->name, "two") != 0 || + bed1->flags != DETECT_BYTE_EXTRACT_FLAG_STRING || + bed1->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE || + bed1->base != DETECT_BYTE_EXTRACT_BASE_HEX || bed1->align_value != 0 || + bed1->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { goto end; } if (bed1->local_id != 0) { @@ -3888,12 +3622,9 @@ static int DetectByteExtractTest56(void) } cd = (DetectContentData *)sm->ctx; if (strncmp((char *)cd->content, "four", cd->content_len) != 0 || - cd->flags != (DETECT_CONTENT_DISTANCE_VAR | - DETECT_CONTENT_WITHIN_VAR | - DETECT_CONTENT_DISTANCE | - DETECT_CONTENT_WITHIN) || - cd->within != bed1->local_id || - cd->distance != bed2->local_id ) { + cd->flags != (DETECT_CONTENT_DISTANCE_VAR | DETECT_CONTENT_WITHIN_VAR | + DETECT_CONTENT_DISTANCE | DETECT_CONTENT_WITHIN) || + cd->within != bed1->local_id || cd->distance != bed2->local_id) { printf("four failed\n"); result = 0; goto end; @@ -3905,7 +3636,7 @@ static int DetectByteExtractTest56(void) result = 1; - end: +end: SigGroupCleanup(de_ctx); SigCleanSignatures(de_ctx); DetectEngineCtxFree(de_ctx); @@ -3931,15 +3662,15 @@ static int DetectByteExtractTest57(void) de_ctx->flags |= DE_QUIET; s = de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"Testing bytejump_body\"; " - "content:\"one\"; " - "uricontent: \"urione\"; " - "byte_extract:4,0,two,string,hex,relative; " - "byte_extract:4,0,three,string,hex,relative; " - "byte_extract:4,0,four,string,hex,relative; " - "byte_extract:4,0,five,string,hex,relative; " - "uricontent: \"four\"; within:two; distance:three; " - "sid:1;)"); + "(msg:\"Testing bytejump_body\"; " + "content:\"one\"; " + "uricontent: \"urione\"; " + "byte_extract:4,0,two,string,hex,relative; " + "byte_extract:4,0,three,string,hex,relative; " + "byte_extract:4,0,four,string,hex,relative; " + "byte_extract:4,0,five,string,hex,relative; " + "uricontent: \"four\"; within:two; distance:three; " + "sid:1;)"); if (de_ctx->sig_list == NULL) { result = 0; goto end; @@ -3957,13 +3688,10 @@ static int DetectByteExtractTest57(void) } cd = (DetectContentData *)sm->ctx; if (cd->flags & DETECT_CONTENT_RAWBYTES || - strncmp((char *)cd->content, "one", cd->content_len) != 0 || - cd->flags & DETECT_CONTENT_NOCASE || - cd->flags & DETECT_CONTENT_WITHIN || - cd->flags & DETECT_CONTENT_DISTANCE || - cd->flags & DETECT_CONTENT_FAST_PATTERN || - cd->flags & DETECT_CONTENT_RELATIVE_NEXT || - cd->flags & DETECT_CONTENT_NEGATED ) { + strncmp((char *)cd->content, "one", cd->content_len) != 0 || + cd->flags & DETECT_CONTENT_NOCASE || cd->flags & DETECT_CONTENT_WITHIN || + cd->flags & DETECT_CONTENT_DISTANCE || cd->flags & DETECT_CONTENT_FAST_PATTERN || + cd->flags & DETECT_CONTENT_RELATIVE_NEXT || cd->flags & DETECT_CONTENT_NEGATED) { printf("one failed\n"); result = 0; goto end; @@ -3979,13 +3707,10 @@ static int DetectByteExtractTest57(void) } cd = (DetectContentData *)sm->ctx; if (cd->flags & DETECT_CONTENT_RAWBYTES || - strncmp((char *)cd->content, "urione", cd->content_len) != 0 || - cd->flags & DETECT_CONTENT_NOCASE || - cd->flags & DETECT_CONTENT_WITHIN || - cd->flags & DETECT_CONTENT_DISTANCE || - cd->flags & DETECT_CONTENT_FAST_PATTERN || - !(cd->flags & DETECT_CONTENT_RELATIVE_NEXT) || - cd->flags & DETECT_CONTENT_NEGATED ) { + strncmp((char *)cd->content, "urione", cd->content_len) != 0 || + cd->flags & DETECT_CONTENT_NOCASE || cd->flags & DETECT_CONTENT_WITHIN || + cd->flags & DETECT_CONTENT_DISTANCE || cd->flags & DETECT_CONTENT_FAST_PATTERN || + !(cd->flags & DETECT_CONTENT_RELATIVE_NEXT) || cd->flags & DETECT_CONTENT_NEGATED) { printf("one failed\n"); result = 0; goto end; @@ -3997,15 +3722,11 @@ static int DetectByteExtractTest57(void) goto end; } bed1 = (DetectByteExtractData *)sm->ctx; - if (bed1->nbytes != 4 || - bed1->offset != 0 || - strcmp(bed1->name, "two") != 0 || - bed1->flags != (DETECT_BYTE_EXTRACT_FLAG_STRING | - DETECT_BYTE_EXTRACT_FLAG_RELATIVE) || - bed1->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE || - bed1->base != DETECT_BYTE_EXTRACT_BASE_HEX || - bed1->align_value != 0 || - bed1->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { + if (bed1->nbytes != 4 || bed1->offset != 0 || strcmp(bed1->name, "two") != 0 || + bed1->flags != (DETECT_BYTE_EXTRACT_FLAG_STRING | DETECT_BYTE_EXTRACT_FLAG_RELATIVE) || + bed1->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE || + bed1->base != DETECT_BYTE_EXTRACT_BASE_HEX || bed1->align_value != 0 || + bed1->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { goto end; } if (bed1->local_id != 0) { @@ -4053,12 +3774,9 @@ static int DetectByteExtractTest57(void) } cd = (DetectContentData *)sm->ctx; if (strncmp((char *)cd->content, "four", cd->content_len) != 0 || - cd->flags != (DETECT_CONTENT_DISTANCE_VAR | - DETECT_CONTENT_WITHIN_VAR | - DETECT_CONTENT_DISTANCE | - DETECT_CONTENT_WITHIN) || - cd->within != bed1->local_id || - cd->distance != bed2->local_id) { + cd->flags != (DETECT_CONTENT_DISTANCE_VAR | DETECT_CONTENT_WITHIN_VAR | + DETECT_CONTENT_DISTANCE | DETECT_CONTENT_WITHIN) || + cd->within != bed1->local_id || cd->distance != bed2->local_id) { printf("four failed\n"); result = 0; goto end; @@ -4070,7 +3788,7 @@ static int DetectByteExtractTest57(void) result = 1; - end: +end: SigGroupCleanup(de_ctx); SigCleanSignatures(de_ctx); DetectEngineCtxFree(de_ctx); @@ -4095,14 +3813,14 @@ static int DetectByteExtractTest58(void) de_ctx->flags |= DE_QUIET; s = de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"Testing bytejump_body\"; " - "content:\"one\"; " - "byte_extract:4,0,two,string,hex; " - "byte_extract:4,0,three,string,hex; " - "byte_jump: 2,two; " - "byte_jump: 3,three; " - "isdataat: three; " - "sid:1;)"); + "(msg:\"Testing bytejump_body\"; " + "content:\"one\"; " + "byte_extract:4,0,two,string,hex; " + "byte_extract:4,0,three,string,hex; " + "byte_jump: 2,two; " + "byte_jump: 3,three; " + "isdataat: three; " + "sid:1;)"); if (de_ctx->sig_list == NULL) { result = 0; goto end; @@ -4120,13 +3838,10 @@ static int DetectByteExtractTest58(void) } cd = (DetectContentData *)sm->ctx; if (cd->flags & DETECT_CONTENT_RAWBYTES || - strncmp((char *)cd->content, "one", cd->content_len) != 0 || - cd->flags & DETECT_CONTENT_NOCASE || - cd->flags & DETECT_CONTENT_WITHIN || - cd->flags & DETECT_CONTENT_DISTANCE || - cd->flags & DETECT_CONTENT_FAST_PATTERN || - cd->flags & DETECT_CONTENT_RELATIVE_NEXT || - cd->flags & DETECT_CONTENT_NEGATED ) { + strncmp((char *)cd->content, "one", cd->content_len) != 0 || + cd->flags & DETECT_CONTENT_NOCASE || cd->flags & DETECT_CONTENT_WITHIN || + cd->flags & DETECT_CONTENT_DISTANCE || cd->flags & DETECT_CONTENT_FAST_PATTERN || + cd->flags & DETECT_CONTENT_RELATIVE_NEXT || cd->flags & DETECT_CONTENT_NEGATED) { printf("one failed\n"); result = 0; goto end; @@ -4138,14 +3853,11 @@ static int DetectByteExtractTest58(void) goto end; } bed1 = (DetectByteExtractData *)sm->ctx; - if (bed1->nbytes != 4 || - bed1->offset != 0 || - strcmp(bed1->name, "two") != 0 || - bed1->flags != DETECT_BYTE_EXTRACT_FLAG_STRING || - bed1->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE || - bed1->base != DETECT_BYTE_EXTRACT_BASE_HEX || - bed1->align_value != 0 || - bed1->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { + if (bed1->nbytes != 4 || bed1->offset != 0 || strcmp(bed1->name, "two") != 0 || + bed1->flags != DETECT_BYTE_EXTRACT_FLAG_STRING || + bed1->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE || + bed1->base != DETECT_BYTE_EXTRACT_BASE_HEX || bed1->align_value != 0 || + bed1->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { goto end; } if (bed1->local_id != 0) { @@ -4165,8 +3877,7 @@ static int DetectByteExtractTest58(void) goto end; } bjd = (DetectBytejumpData *)sm->ctx; - if (bjd->flags != DETECT_CONTENT_OFFSET_VAR || - bjd->offset != 0) { + if (bjd->flags != DETECT_CONTENT_OFFSET_VAR || bjd->offset != 0) { printf("three failed\n"); result = 0; goto end; @@ -4178,8 +3889,7 @@ static int DetectByteExtractTest58(void) goto end; } bjd = (DetectBytejumpData *)sm->ctx; - if (bjd->flags != DETECT_CONTENT_OFFSET_VAR || - bjd->offset != 1) { + if (bjd->flags != DETECT_CONTENT_OFFSET_VAR || bjd->offset != 1) { printf("four failed\n"); result = 0; goto end; @@ -4191,8 +3901,7 @@ static int DetectByteExtractTest58(void) goto end; } isdd = (DetectIsdataatData *)sm->ctx; - if (isdd->flags != ISDATAAT_OFFSET_VAR || - isdd->dataat != 1) { + if (isdd->flags != ISDATAAT_OFFSET_VAR || isdd->dataat != 1) { printf("isdataat failed\n"); result = 0; goto end; @@ -4203,7 +3912,7 @@ static int DetectByteExtractTest58(void) result = 1; - end: +end: SigGroupCleanup(de_ctx); SigCleanSignatures(de_ctx); DetectEngineCtxFree(de_ctx); @@ -4228,14 +3937,14 @@ static int DetectByteExtractTest59(void) de_ctx->flags |= DE_QUIET; s = de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"Testing bytejump_body\"; " - "content:\"one\"; " - "byte_extract:4,0,two,string,hex; " - "byte_extract:4,0,three,string,hex; " - "byte_jump: 2,two; " - "byte_jump: 3,three; " - "isdataat: three,relative; " - "sid:1;)"); + "(msg:\"Testing bytejump_body\"; " + "content:\"one\"; " + "byte_extract:4,0,two,string,hex; " + "byte_extract:4,0,three,string,hex; " + "byte_jump: 2,two; " + "byte_jump: 3,three; " + "isdataat: three,relative; " + "sid:1;)"); if (de_ctx->sig_list == NULL) { result = 0; goto end; @@ -4253,13 +3962,10 @@ static int DetectByteExtractTest59(void) } cd = (DetectContentData *)sm->ctx; if (cd->flags & DETECT_CONTENT_RAWBYTES || - strncmp((char *)cd->content, "one", cd->content_len) != 0 || - cd->flags & DETECT_CONTENT_NOCASE || - cd->flags & DETECT_CONTENT_WITHIN || - cd->flags & DETECT_CONTENT_DISTANCE || - cd->flags & DETECT_CONTENT_FAST_PATTERN || - cd->flags & DETECT_CONTENT_RELATIVE_NEXT || - cd->flags & DETECT_CONTENT_NEGATED ) { + strncmp((char *)cd->content, "one", cd->content_len) != 0 || + cd->flags & DETECT_CONTENT_NOCASE || cd->flags & DETECT_CONTENT_WITHIN || + cd->flags & DETECT_CONTENT_DISTANCE || cd->flags & DETECT_CONTENT_FAST_PATTERN || + cd->flags & DETECT_CONTENT_RELATIVE_NEXT || cd->flags & DETECT_CONTENT_NEGATED) { printf("one failed\n"); result = 0; goto end; @@ -4271,14 +3977,11 @@ static int DetectByteExtractTest59(void) goto end; } bed1 = (DetectByteExtractData *)sm->ctx; - if (bed1->nbytes != 4 || - bed1->offset != 0 || - strcmp(bed1->name, "two") != 0 || - bed1->flags != DETECT_BYTE_EXTRACT_FLAG_STRING || - bed1->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE || - bed1->base != DETECT_BYTE_EXTRACT_BASE_HEX || - bed1->align_value != 0 || - bed1->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { + if (bed1->nbytes != 4 || bed1->offset != 0 || strcmp(bed1->name, "two") != 0 || + bed1->flags != DETECT_BYTE_EXTRACT_FLAG_STRING || + bed1->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE || + bed1->base != DETECT_BYTE_EXTRACT_BASE_HEX || bed1->align_value != 0 || + bed1->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { goto end; } if (bed1->local_id != 0) { @@ -4298,8 +4001,7 @@ static int DetectByteExtractTest59(void) goto end; } bjd = (DetectBytejumpData *)sm->ctx; - if (bjd->flags != DETECT_CONTENT_OFFSET_VAR || - bjd->offset != 0) { + if (bjd->flags != DETECT_CONTENT_OFFSET_VAR || bjd->offset != 0) { printf("three failed\n"); result = 0; goto end; @@ -4311,8 +4013,7 @@ static int DetectByteExtractTest59(void) goto end; } bjd = (DetectBytejumpData *)sm->ctx; - if (bjd->flags != DETECT_CONTENT_OFFSET_VAR || - bjd->offset != 1) { + if (bjd->flags != DETECT_CONTENT_OFFSET_VAR || bjd->offset != 1) { printf("four failed\n"); result = 0; goto end; @@ -4324,9 +4025,7 @@ static int DetectByteExtractTest59(void) goto end; } isdd = (DetectIsdataatData *)sm->ctx; - if (isdd->flags != (ISDATAAT_OFFSET_VAR | - ISDATAAT_RELATIVE) || - isdd->dataat != 1) { + if (isdd->flags != (ISDATAAT_OFFSET_VAR | ISDATAAT_RELATIVE) || isdd->dataat != 1) { printf("isdataat failed\n"); result = 0; goto end; @@ -4337,7 +4036,7 @@ static int DetectByteExtractTest59(void) result = 1; - end: +end: SigGroupCleanup(de_ctx); SigCleanSignatures(de_ctx); DetectEngineCtxFree(de_ctx); @@ -4361,13 +4060,13 @@ static int DetectByteExtractTest60(void) de_ctx->flags |= DE_QUIET; s = de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"Testing bytejump_body\"; " - "content:\"one\"; " - "byte_extract:4,0,two,string,hex,relative; " - "uricontent: \"three\"; " - "byte_extract:4,0,four,string,hex,relative; " - "isdataat: two; " - "sid:1;)"); + "(msg:\"Testing bytejump_body\"; " + "content:\"one\"; " + "byte_extract:4,0,two,string,hex,relative; " + "uricontent: \"three\"; " + "byte_extract:4,0,four,string,hex,relative; " + "isdataat: two; " + "sid:1;)"); if (de_ctx->sig_list == NULL) { result = 0; goto end; @@ -4385,13 +4084,10 @@ static int DetectByteExtractTest60(void) } cd = (DetectContentData *)sm->ctx; if (cd->flags & DETECT_CONTENT_RAWBYTES || - strncmp((char *)cd->content, "one", cd->content_len) != 0 || - cd->flags & DETECT_CONTENT_NOCASE || - cd->flags & DETECT_CONTENT_WITHIN || - cd->flags & DETECT_CONTENT_DISTANCE || - cd->flags & DETECT_CONTENT_FAST_PATTERN || - !(cd->flags & DETECT_CONTENT_RELATIVE_NEXT) || - cd->flags & DETECT_CONTENT_NEGATED ) { + strncmp((char *)cd->content, "one", cd->content_len) != 0 || + cd->flags & DETECT_CONTENT_NOCASE || cd->flags & DETECT_CONTENT_WITHIN || + cd->flags & DETECT_CONTENT_DISTANCE || cd->flags & DETECT_CONTENT_FAST_PATTERN || + !(cd->flags & DETECT_CONTENT_RELATIVE_NEXT) || cd->flags & DETECT_CONTENT_NEGATED) { printf("one failed\n"); result = 0; goto end; @@ -4403,15 +4099,11 @@ static int DetectByteExtractTest60(void) goto end; } bed1 = (DetectByteExtractData *)sm->ctx; - if (bed1->nbytes != 4 || - bed1->offset != 0 || - strcmp(bed1->name, "two") != 0 || - bed1->flags != (DETECT_BYTE_EXTRACT_FLAG_STRING | - DETECT_BYTE_EXTRACT_FLAG_RELATIVE) || - bed1->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE || - bed1->base != DETECT_BYTE_EXTRACT_BASE_HEX || - bed1->align_value != 0 || - bed1->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { + if (bed1->nbytes != 4 || bed1->offset != 0 || strcmp(bed1->name, "two") != 0 || + bed1->flags != (DETECT_BYTE_EXTRACT_FLAG_STRING | DETECT_BYTE_EXTRACT_FLAG_RELATIVE) || + bed1->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE || + bed1->base != DETECT_BYTE_EXTRACT_BASE_HEX || bed1->align_value != 0 || + bed1->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { goto end; } if (bed1->local_id != 0) { @@ -4425,8 +4117,7 @@ static int DetectByteExtractTest60(void) goto end; } isdd = (DetectIsdataatData *)sm->ctx; - if (isdd->flags != (ISDATAAT_OFFSET_VAR) || - isdd->dataat != bed1->local_id) { + if (isdd->flags != (ISDATAAT_OFFSET_VAR) || isdd->dataat != bed1->local_id) { printf("isdataat failed\n"); result = 0; goto end; @@ -4446,7 +4137,7 @@ static int DetectByteExtractTest60(void) } cd = (DetectContentData *)sm->ctx; if (cd->flags != DETECT_CONTENT_RELATIVE_NEXT || - strncmp((char *)cd->content, "three", cd->content_len) != 0) { + strncmp((char *)cd->content, "three", cd->content_len) != 0) { printf("one failed\n"); result = 0; goto end; @@ -4458,15 +4149,11 @@ static int DetectByteExtractTest60(void) goto end; } bed1 = (DetectByteExtractData *)sm->ctx; - if (bed1->nbytes != 4 || - bed1->offset != 0 || - strcmp(bed1->name, "four") != 0 || - bed1->flags != (DETECT_BYTE_EXTRACT_FLAG_STRING | - DETECT_BYTE_EXTRACT_FLAG_RELATIVE) || - bed1->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE || - bed1->base != DETECT_BYTE_EXTRACT_BASE_HEX || - bed1->align_value != 0 || - bed1->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { + if (bed1->nbytes != 4 || bed1->offset != 0 || strcmp(bed1->name, "four") != 0 || + bed1->flags != (DETECT_BYTE_EXTRACT_FLAG_STRING | DETECT_BYTE_EXTRACT_FLAG_RELATIVE) || + bed1->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE || + bed1->base != DETECT_BYTE_EXTRACT_BASE_HEX || bed1->align_value != 0 || + bed1->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { goto end; } if (bed1->local_id != 0) { @@ -4479,7 +4166,7 @@ static int DetectByteExtractTest60(void) result = 1; - end: +end: SigGroupCleanup(de_ctx); SigCleanSignatures(de_ctx); DetectEngineCtxFree(de_ctx); @@ -4503,13 +4190,13 @@ static int DetectByteExtractTest61(void) de_ctx->flags |= DE_QUIET; s = de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"Testing bytejump_body\"; " - "content:\"one\"; " - "byte_extract:4,0,two,string,hex,relative; " - "uricontent: \"three\"; " - "byte_extract:4,0,four,string,hex,relative; " - "isdataat: four, relative; " - "sid:1;)"); + "(msg:\"Testing bytejump_body\"; " + "content:\"one\"; " + "byte_extract:4,0,two,string,hex,relative; " + "uricontent: \"three\"; " + "byte_extract:4,0,four,string,hex,relative; " + "isdataat: four, relative; " + "sid:1;)"); if (de_ctx->sig_list == NULL) { result = 0; goto end; @@ -4527,13 +4214,10 @@ static int DetectByteExtractTest61(void) } cd = (DetectContentData *)sm->ctx; if (cd->flags & DETECT_CONTENT_RAWBYTES || - strncmp((char *)cd->content, "one", cd->content_len) != 0 || - cd->flags & DETECT_CONTENT_NOCASE || - cd->flags & DETECT_CONTENT_WITHIN || - cd->flags & DETECT_CONTENT_DISTANCE || - cd->flags & DETECT_CONTENT_FAST_PATTERN || - !(cd->flags & DETECT_CONTENT_RELATIVE_NEXT) || - cd->flags & DETECT_CONTENT_NEGATED ) { + strncmp((char *)cd->content, "one", cd->content_len) != 0 || + cd->flags & DETECT_CONTENT_NOCASE || cd->flags & DETECT_CONTENT_WITHIN || + cd->flags & DETECT_CONTENT_DISTANCE || cd->flags & DETECT_CONTENT_FAST_PATTERN || + !(cd->flags & DETECT_CONTENT_RELATIVE_NEXT) || cd->flags & DETECT_CONTENT_NEGATED) { printf("one failed\n"); result = 0; goto end; @@ -4545,15 +4229,11 @@ static int DetectByteExtractTest61(void) goto end; } bed1 = (DetectByteExtractData *)sm->ctx; - if (bed1->nbytes != 4 || - bed1->offset != 0 || - strcmp(bed1->name, "two") != 0 || - bed1->flags != (DETECT_BYTE_EXTRACT_FLAG_STRING | - DETECT_BYTE_EXTRACT_FLAG_RELATIVE) || - bed1->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE || - bed1->base != DETECT_BYTE_EXTRACT_BASE_HEX || - bed1->align_value != 0 || - bed1->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { + if (bed1->nbytes != 4 || bed1->offset != 0 || strcmp(bed1->name, "two") != 0 || + bed1->flags != (DETECT_BYTE_EXTRACT_FLAG_STRING | DETECT_BYTE_EXTRACT_FLAG_RELATIVE) || + bed1->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE || + bed1->base != DETECT_BYTE_EXTRACT_BASE_HEX || bed1->align_value != 0 || + bed1->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { goto end; } if (bed1->local_id != 0) { @@ -4575,7 +4255,7 @@ static int DetectByteExtractTest61(void) } cd = (DetectContentData *)sm->ctx; if (cd->flags != DETECT_CONTENT_RELATIVE_NEXT || - strncmp((char *)cd->content, "three", cd->content_len) != 0) { + strncmp((char *)cd->content, "three", cd->content_len) != 0) { printf("one failed\n"); result = 0; goto end; @@ -4587,15 +4267,11 @@ static int DetectByteExtractTest61(void) goto end; } bed1 = (DetectByteExtractData *)sm->ctx; - if (bed1->nbytes != 4 || - bed1->offset != 0 || - strcmp(bed1->name, "four") != 0 || - bed1->flags != (DETECT_BYTE_EXTRACT_FLAG_STRING | - DETECT_BYTE_EXTRACT_FLAG_RELATIVE) || - bed1->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE || - bed1->base != DETECT_BYTE_EXTRACT_BASE_HEX || - bed1->align_value != 0 || - bed1->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { + if (bed1->nbytes != 4 || bed1->offset != 0 || strcmp(bed1->name, "four") != 0 || + bed1->flags != (DETECT_BYTE_EXTRACT_FLAG_STRING | DETECT_BYTE_EXTRACT_FLAG_RELATIVE) || + bed1->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE || + bed1->base != DETECT_BYTE_EXTRACT_BASE_HEX || bed1->align_value != 0 || + bed1->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { goto end; } if (bed1->local_id != 0) { @@ -4609,9 +4285,8 @@ static int DetectByteExtractTest61(void) goto end; } isdd = (DetectIsdataatData *)sm->ctx; - if (isdd->flags != (ISDATAAT_OFFSET_VAR | - ISDATAAT_RELATIVE) || - isdd->dataat != bed1->local_id) { + if (isdd->flags != (ISDATAAT_OFFSET_VAR | ISDATAAT_RELATIVE) || + isdd->dataat != bed1->local_id) { printf("isdataat failed\n"); result = 0; goto end; @@ -4622,7 +4297,7 @@ static int DetectByteExtractTest61(void) result = 1; - end: +end: SigGroupCleanup(de_ctx); SigCleanSignatures(de_ctx); DetectEngineCtxFree(de_ctx); @@ -4644,8 +4319,8 @@ static int DetectByteExtractTest62(void) de_ctx->flags |= DE_QUIET; s = de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " - "(file_data; byte_extract:4,2,two,relative,string,hex; " - "sid:1;)"); + "(file_data; byte_extract:4,2,two,relative,string,hex; " + "sid:1;)"); if (de_ctx->sig_list == NULL) { goto end; } @@ -4658,20 +4333,17 @@ static int DetectByteExtractTest62(void) goto end; } bed = (DetectByteExtractData *)sm->ctx; - if (bed->nbytes != 4 || - bed->offset != 2 || - strncmp(bed->name, "two", 3) != 0 || - bed->flags != (DETECT_BYTE_EXTRACT_FLAG_STRING | DETECT_BYTE_EXTRACT_FLAG_RELATIVE) || - bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE || - bed->base != DETECT_BYTE_EXTRACT_BASE_HEX || - bed->align_value != 0 || - bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { + if (bed->nbytes != 4 || bed->offset != 2 || strncmp(bed->name, "two", 3) != 0 || + bed->flags != (DETECT_BYTE_EXTRACT_FLAG_STRING | DETECT_BYTE_EXTRACT_FLAG_RELATIVE) || + bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE || + bed->base != DETECT_BYTE_EXTRACT_BASE_HEX || bed->align_value != 0 || + bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { goto end; } result = 1; - end: +end: SigGroupCleanup(de_ctx); SigCleanSignatures(de_ctx); DetectEngineCtxFree(de_ctx); @@ -4687,19 +4359,15 @@ static int DetectByteExtractTest63(void) if (bed == NULL) goto end; - if (bed->nbytes != 4 || - bed->offset != -2 || - strcmp(bed->name, "one") != 0 || - bed->flags != 0 || - bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_DEFAULT || - bed->base != DETECT_BYTE_EXTRACT_BASE_NONE || - bed->align_value != 0 || - bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { + if (bed->nbytes != 4 || bed->offset != -2 || strcmp(bed->name, "one") != 0 || bed->flags != 0 || + bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_DEFAULT || + bed->base != DETECT_BYTE_EXTRACT_BASE_NONE || bed->align_value != 0 || + bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) { goto end; } result = 1; - end: +end: if (bed != NULL) DetectByteExtractFree(NULL, bed); return result; @@ -4739,7 +4407,7 @@ static int DetectByteExtractTestParseNoBase(void) } result = 1; - end: +end: if (bed != NULL) DetectByteExtractFree(NULL, bed); return result; @@ -4822,7 +4490,6 @@ static void DetectByteExtractRegisterTests(void) UtRegisterTest("DetectByteExtractTest62", DetectByteExtractTest62); UtRegisterTest("DetectByteExtractTest63", DetectByteExtractTest63); - UtRegisterTest("DetectByteExtractTestParseNoBase", - DetectByteExtractTestParseNoBase); + UtRegisterTest("DetectByteExtractTestParseNoBase", DetectByteExtractTestParseNoBase); } #endif /* UNITTESTS */ diff --git a/src/detect-byte-extract.h b/src/detect-byte-extract.h index 71b433d3405f..a3036cf6c485 100644 --- a/src/detect-byte-extract.h +++ b/src/detect-byte-extract.h @@ -32,10 +32,10 @@ #define DETECT_BYTE_EXTRACT_FLAG_ENDIAN 0x10 /* endian value to be used. Would be stored in DetectByteParseData->endian */ -#define DETECT_BYTE_EXTRACT_ENDIAN_NONE 0 -#define DETECT_BYTE_EXTRACT_ENDIAN_BIG 1 -#define DETECT_BYTE_EXTRACT_ENDIAN_LITTLE 2 -#define DETECT_BYTE_EXTRACT_ENDIAN_DCE 3 +#define DETECT_BYTE_EXTRACT_ENDIAN_NONE 0 +#define DETECT_BYTE_EXTRACT_ENDIAN_BIG 1 +#define DETECT_BYTE_EXTRACT_ENDIAN_LITTLE 2 +#define DETECT_BYTE_EXTRACT_ENDIAN_DCE 3 /** * \brief Holds data related to byte_extract keyword. diff --git a/src/detect-bytejump.c b/src/detect-bytejump.c index cf4b9debd0bb..f06bd85d3356 100644 --- a/src/detect-bytejump.c +++ b/src/detect-bytejump.c @@ -46,37 +46,40 @@ /** * \brief Regex for parsing our options */ -#define PARSE_REGEX "^\\s*" \ - "([^\\s,]+\\s*,\\s*[^\\s,]+)" \ - "(?:\\s*,\\s*((?:multiplier|post_offset)\\s+[^\\s,]+|[^\\s,]+))?" \ - "(?:\\s*,\\s*((?:multiplier|post_offset)\\s+[^\\s,]+|[^\\s,]+))?" \ - "(?:\\s*,\\s*((?:multiplier|post_offset)\\s+[^\\s,]+|[^\\s,]+))?" \ - "(?:\\s*,\\s*((?:multiplier|post_offset)\\s+[^\\s,]+|[^\\s,]+))?" \ - "(?:\\s*,\\s*((?:multiplier|post_offset)\\s+[^\\s,]+|[^\\s,]+))?" \ - "(?:\\s*,\\s*((?:multiplier|post_offset)\\s+[^\\s,]+|[^\\s,]+))?" \ - "(?:\\s*,\\s*((?:multiplier|post_offset)\\s+[^\\s,]+|[^\\s,]+))?" \ - "(?:\\s*,\\s*((?:multiplier|post_offset)\\s+[^\\s,]+|[^\\s,]+))?" \ - "(?:\\s*,\\s*((?:multiplier|post_offset)\\s+[^\\s,]+|[^\\s,]+))?" \ - "\\s*$" +#define PARSE_REGEX \ + "^\\s*" \ + "([^\\s,]+\\s*,\\s*[^\\s,]+)" \ + "(?:\\s*,\\s*((?:multiplier|post_offset)\\s+[^\\s,]+|[^\\s,]+))?" \ + "(?:\\s*,\\s*((?:multiplier|post_offset)\\s+[^\\s,]+|[^\\s,]+))?" \ + "(?:\\s*,\\s*((?:multiplier|post_offset)\\s+[^\\s,]+|[^\\s,]+))?" \ + "(?:\\s*,\\s*((?:multiplier|post_offset)\\s+[^\\s,]+|[^\\s,]+))?" \ + "(?:\\s*,\\s*((?:multiplier|post_offset)\\s+[^\\s,]+|[^\\s,]+))?" \ + "(?:\\s*,\\s*((?:multiplier|post_offset)\\s+[^\\s,]+|[^\\s,]+))?" \ + "(?:\\s*,\\s*((?:multiplier|post_offset)\\s+[^\\s,]+|[^\\s,]+))?" \ + "(?:\\s*,\\s*((?:multiplier|post_offset)\\s+[^\\s,]+|[^\\s,]+))?" \ + "(?:\\s*,\\s*((?:multiplier|post_offset)\\s+[^\\s,]+|[^\\s,]+))?" \ + "\\s*$" static DetectParseRegex parse_regex; static DetectBytejumpData *DetectBytejumpParse( DetectEngineCtx *de_ctx, const char *optstr, char **nbytes, char **offset); static int DetectBytejumpSetup(DetectEngineCtx *de_ctx, Signature *s, const char *optstr); -static void DetectBytejumpFree(DetectEngineCtx*, void *ptr); +static void DetectBytejumpFree(DetectEngineCtx *, void *ptr); #ifdef UNITTESTS static void DetectBytejumpRegisterTests(void); #endif -void DetectBytejumpRegister (void) +void DetectBytejumpRegister(void) { sigmatch_table[DETECT_BYTEJUMP].name = "byte_jump"; - sigmatch_table[DETECT_BYTEJUMP].desc = "allow the ability to select a from an and move the detection pointer to that position"; + sigmatch_table[DETECT_BYTEJUMP].desc = + "allow the ability to select a from an and move the detection " + "pointer to that position"; sigmatch_table[DETECT_BYTEJUMP].url = "/rules/payload-keywords.html#byte-jump"; sigmatch_table[DETECT_BYTEJUMP].Match = NULL; sigmatch_table[DETECT_BYTEJUMP].Setup = DetectBytejumpSetup; - sigmatch_table[DETECT_BYTEJUMP].Free = DetectBytejumpFree; + sigmatch_table[DETECT_BYTEJUMP].Free = DetectBytejumpFree; #ifdef UNITTESTS sigmatch_table[DETECT_BYTEJUMP].RegisterTests = DetectBytejumpRegisterTests; #endif @@ -191,12 +194,11 @@ bool DetectBytejumpDoMatch(DetectEngineThreadCtx *det_ctx, const Signature *s, /* Extract the byte data */ if (flags & DETECT_BYTEJUMP_STRING) { extbytes = ByteExtractStringUint64(&val, data->base, nbytes, (const char *)ptr); - if(extbytes <= 0) { + if (extbytes <= 0) { SCLogDebug("error extracting %d bytes of string data: %d", nbytes, extbytes); SCReturnBool(false); } - } - else { + } else { int endianness = (flags & DETECT_BYTEJUMP_LITTLE) ? BYTE_LITTLE_ENDIAN : BYTE_BIG_ENDIAN; extbytes = ByteExtractUint64(&val, endianness, (uint16_t)nbytes, ptr); if (extbytes != nbytes) { @@ -300,13 +302,15 @@ static DetectBytejumpData *DetectBytejumpParse( * and *yes* this *is* ugly. */ end_ptr = str; - while (!(isspace((unsigned char)*end_ptr) || (*end_ptr == ','))) end_ptr++; + while (!(isspace((unsigned char)*end_ptr) || (*end_ptr == ','))) + end_ptr++; *(end_ptr++) = '\0'; strlcpy(args[0], str, sizeof(args[0])); numargs++; str_ptr = end_ptr; - while (isspace((unsigned char)*str_ptr) || (*str_ptr == ',')) str_ptr++; + while (isspace((unsigned char)*str_ptr) || (*str_ptr == ',')) + str_ptr++; end_ptr = str_ptr; while (!(isspace((unsigned char)*end_ptr) || (*end_ptr == ',')) && (*end_ptr != '\0')) end_ptr++; @@ -491,10 +495,8 @@ static int DetectBytejumpSetup(DetectEngineCtx *de_ctx, Signature *s, const char } } else if (data->flags & DETECT_BYTEJUMP_DCE) { if (data->flags & DETECT_BYTEJUMP_RELATIVE) { - prev_pm = DetectGetLastSMFromLists(s, - DETECT_CONTENT, DETECT_PCRE, - DETECT_BYTETEST, DETECT_BYTEJUMP, DETECT_BYTE_EXTRACT, - DETECT_ISDATAAT, DETECT_BYTEMATH, -1); + prev_pm = DetectGetLastSMFromLists(s, DETECT_CONTENT, DETECT_PCRE, DETECT_BYTETEST, + DETECT_BYTEJUMP, DETECT_BYTE_EXTRACT, DETECT_ISDATAAT, DETECT_BYTEMATH, -1); if (prev_pm == NULL) { sm_list = DETECT_SM_LIST_PMATCH; } else { @@ -510,10 +512,8 @@ static int DetectBytejumpSetup(DetectEngineCtx *de_ctx, Signature *s, const char goto error; } else if (data->flags & DETECT_BYTEJUMP_RELATIVE) { - prev_pm = DetectGetLastSMFromLists(s, - DETECT_CONTENT, DETECT_PCRE, - DETECT_BYTETEST, DETECT_BYTEJUMP, DETECT_BYTE_EXTRACT, - DETECT_ISDATAAT, DETECT_BYTEMATH, -1); + prev_pm = DetectGetLastSMFromLists(s, DETECT_CONTENT, DETECT_PCRE, DETECT_BYTETEST, + DETECT_BYTEJUMP, DETECT_BYTE_EXTRACT, DETECT_ISDATAAT, DETECT_BYTEMATH, -1); if (prev_pm == NULL) { sm_list = DETECT_SM_LIST_PMATCH; } else { @@ -527,14 +527,11 @@ static int DetectBytejumpSetup(DetectEngineCtx *de_ctx, Signature *s, const char } if (data->flags & DETECT_BYTEJUMP_DCE) { - if ((data->flags & DETECT_BYTEJUMP_STRING) || - (data->flags & DETECT_BYTEJUMP_LITTLE) || - (data->flags & DETECT_BYTEJUMP_BIG) || - (data->flags & DETECT_BYTEJUMP_BEGIN) || - (data->flags & DETECT_BYTEJUMP_END) || - (data->base == DETECT_BYTEJUMP_BASE_DEC) || - (data->base == DETECT_BYTEJUMP_BASE_HEX) || - (data->base == DETECT_BYTEJUMP_BASE_OCT) ) { + if ((data->flags & DETECT_BYTEJUMP_STRING) || (data->flags & DETECT_BYTEJUMP_LITTLE) || + (data->flags & DETECT_BYTEJUMP_BIG) || (data->flags & DETECT_BYTEJUMP_BEGIN) || + (data->flags & DETECT_BYTEJUMP_END) || (data->base == DETECT_BYTEJUMP_BASE_DEC) || + (data->base == DETECT_BYTEJUMP_BASE_HEX) || + (data->base == DETECT_BYTEJUMP_BASE_OCT)) { SCLogError("Invalid option. " "A byte_jump keyword with dce holds other invalid modifiers."); goto error; @@ -586,14 +583,14 @@ static int DetectBytejumpSetup(DetectEngineCtx *de_ctx, Signature *s, const char pd->flags |= DETECT_PCRE_RELATIVE_NEXT; } - okay: +okay: ret = 0; return ret; - error: - if (nbytes != NULL) { - SCFree(nbytes); - } +error: + if (nbytes != NULL) { + SCFree(nbytes); + } if (offset != NULL) { SCFree(offset); } @@ -615,7 +612,6 @@ static void DetectBytejumpFree(DetectEngineCtx *de_ctx, void *ptr) SCFree(data); } - /* UNITTESTS */ #ifdef UNITTESTS #include "util-unittest-helper.h" @@ -887,59 +883,59 @@ static int DetectBytejumpTestParse11(void) de_ctx->flags |= DE_QUIET; s = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"Testing bytejump_body\"; " - "dce_iface:3919286a-b10c-11d0-9ba8-00c04fd92ef5; " - "dce_stub_data; " - "content:\"one\"; byte_jump:4,0,align,multiplier 2, " - "post_offset -16,string,dce; sid:1;)"); + "(msg:\"Testing bytejump_body\"; " + "dce_iface:3919286a-b10c-11d0-9ba8-00c04fd92ef5; " + "dce_stub_data; " + "content:\"one\"; byte_jump:4,0,align,multiplier 2, " + "post_offset -16,string,dce; sid:1;)"); FAIL_IF_NOT_NULL(s); s = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"Testing bytejump_body\"; " - "dce_iface:3919286a-b10c-11d0-9ba8-00c04fd92ef5; " - "dce_sub_data; " - "content:\"one\"; byte_jump:4,0,align,multiplier 2, " - "post_offset -16,big,dce; sid:1;)"); + "(msg:\"Testing bytejump_body\"; " + "dce_iface:3919286a-b10c-11d0-9ba8-00c04fd92ef5; " + "dce_sub_data; " + "content:\"one\"; byte_jump:4,0,align,multiplier 2, " + "post_offset -16,big,dce; sid:1;)"); FAIL_IF_NOT_NULL(s); s = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"Testing bytejump_body\"; " - "dce_iface:3919286a-b10c-11d0-9ba8-00c04fd92ef5; " - "dce_stub_data; " - "content:\"one\"; byte_jump:4,0,align,multiplier 2, " - "post_offset -16,little,dce; sid:1;)"); + "(msg:\"Testing bytejump_body\"; " + "dce_iface:3919286a-b10c-11d0-9ba8-00c04fd92ef5; " + "dce_stub_data; " + "content:\"one\"; byte_jump:4,0,align,multiplier 2, " + "post_offset -16,little,dce; sid:1;)"); FAIL_IF_NOT_NULL(s); s = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"Testing bytejump_body\"; " - "dce_iface:3919286a-b10c-11d0-9ba8-00c04fd92ef5; " - "dce_stub_data; " - "content:\"one\"; byte_jump:4,0,align,multiplier 2, " - "post_offset -16,string,hex,dce; sid:1;)"); + "(msg:\"Testing bytejump_body\"; " + "dce_iface:3919286a-b10c-11d0-9ba8-00c04fd92ef5; " + "dce_stub_data; " + "content:\"one\"; byte_jump:4,0,align,multiplier 2, " + "post_offset -16,string,hex,dce; sid:1;)"); FAIL_IF_NOT_NULL(s); s = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"Testing bytejump_body\"; " - "dce_iface:3919286a-b10c-11d0-9ba8-00c04fd92ef5; " - "dce_stub_data; " - "content:\"one\"; byte_jump:4,0,align,multiplier 2, " - "post_offset -16,string,dec,dce; sid:1;)"); + "(msg:\"Testing bytejump_body\"; " + "dce_iface:3919286a-b10c-11d0-9ba8-00c04fd92ef5; " + "dce_stub_data; " + "content:\"one\"; byte_jump:4,0,align,multiplier 2, " + "post_offset -16,string,dec,dce; sid:1;)"); FAIL_IF_NOT_NULL(s); s = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"Testing bytejump_body\"; " - "dce_iface:3919286a-b10c-11d0-9ba8-00c04fd92ef5; " - "dce_stub_data; " - "content:\"one\"; byte_jump:4,0,align,multiplier 2, " - "post_offset -16,string,oct,dce; sid:1;)"); + "(msg:\"Testing bytejump_body\"; " + "dce_iface:3919286a-b10c-11d0-9ba8-00c04fd92ef5; " + "dce_stub_data; " + "content:\"one\"; byte_jump:4,0,align,multiplier 2, " + "post_offset -16,string,oct,dce; sid:1;)"); FAIL_IF_NOT_NULL(s); s = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"Testing bytejump_body\"; " - "dce_iface:3919286a-b10c-11d0-9ba8-00c04fd92ef5; " - "dce_stub_data; " - "content:\"one\"; byte_jump:4,0,align,multiplier 2, " - "post_offset -16,from_beginning,dce; sid:1;)"); + "(msg:\"Testing bytejump_body\"; " + "dce_iface:3919286a-b10c-11d0-9ba8-00c04fd92ef5; " + "dce_stub_data; " + "content:\"one\"; byte_jump:4,0,align,multiplier 2, " + "post_offset -16,from_beginning,dce; sid:1;)"); FAIL_IF_NOT_NULL(s); SigGroupCleanup(de_ctx); @@ -1007,14 +1003,14 @@ static int DetectBytejumpTestParse14(void) * byte_jump and byte_jump relative works if the previous keyword is pcre * (bug 142) */ -static int DetectByteJumpTestPacket01 (void) +static int DetectByteJumpTestPacket01(void) { uint8_t *buf = (uint8_t *)"GET /AllWorkAndNoPlayMakesWillADullBoy HTTP/1.0" - "User-Agent: Wget/1.11.4" - "Accept: */*" - "Host: www.google.com" - "Connection: Keep-Alive" - "Date: Mon, 04 Jan 2010 17:29:39 GMT"; + "User-Agent: Wget/1.11.4" + "Accept: */*" + "Host: www.google.com" + "Connection: Keep-Alive" + "Date: Mon, 04 Jan 2010 17:29:39 GMT"; uint16_t buflen = strlen((char *)buf); Packet *p; p = UTHBuildPacket((uint8_t *)buf, buflen, IPPROTO_TCP); @@ -1022,8 +1018,8 @@ static int DetectByteJumpTestPacket01 (void) FAIL_IF_NULL(p); char sig[] = "alert tcp any any -> any any (msg:\"pcre + byte_test + " - "relative\"; pcre:\"/AllWorkAndNoPlayMakesWillADullBoy/\"; byte_jump:1,6," - "relative,string,dec; content:\"0\"; sid:134; rev:1;)"; + "relative\"; pcre:\"/AllWorkAndNoPlayMakesWillADullBoy/\"; byte_jump:1,6," + "relative,string,dec; content:\"0\"; sid:134; rev:1;)"; FAIL_IF_NOT(UTHPacketMatchSig(p, sig)); @@ -1036,7 +1032,7 @@ static int DetectByteJumpTestPacket01 (void) * byte_jump and byte_jump relative works if the previous keyword is byte_jump * (bug 165) */ -static int DetectByteJumpTestPacket02 (void) +static int DetectByteJumpTestPacket02(void) { // clang-format off uint8_t buf[] = { 0x00, 0x00, 0x00, 0x77, 0xff, 0x53, @@ -1081,7 +1077,7 @@ static int DetectByteJumpTestPacket03(void) FAIL_IF_NULL(p); char sig[] = "alert tcp any any -> any any (msg:\"byte_jump\"; " - "byte_jump:1,214748364; sid:1; rev:1;)"; + "byte_jump:1,214748364; sid:1; rev:1;)"; FAIL_IF(UTHPacketMatchSig(p, sig)); @@ -1095,7 +1091,7 @@ static int DetectByteJumpTestPacket03(void) /** * \test check matches of with from_beginning (bug 626/627) */ -static int DetectByteJumpTestPacket04 (void) +static int DetectByteJumpTestPacket04(void) { uint8_t *buf = (uint8_t *)"XYZ04abcdABCD"; uint16_t buflen = strlen((char *)buf); @@ -1104,7 +1100,9 @@ static int DetectByteJumpTestPacket04 (void) FAIL_IF_NULL(p); - char sig[] = "alert tcp any any -> any any (content:\"XYZ\"; byte_jump:2,0,relative,string,dec; content:\"ABCD\"; distance:0; within:4; sid:1; rev:1;)"; + char sig[] = + "alert tcp any any -> any any (content:\"XYZ\"; byte_jump:2,0,relative,string,dec; " + "content:\"ABCD\"; distance:0; within:4; sid:1; rev:1;)"; FAIL_IF_NOT(UTHPacketMatchSig(p, sig)); @@ -1115,7 +1113,7 @@ static int DetectByteJumpTestPacket04 (void) /** * \test check matches of with from_beginning (bug 626/627) */ -static int DetectByteJumpTestPacket05 (void) +static int DetectByteJumpTestPacket05(void) { uint8_t *buf = (uint8_t *)"XYZ04abcdABCD"; uint16_t buflen = strlen((char *)buf); @@ -1124,7 +1122,8 @@ static int DetectByteJumpTestPacket05 (void) FAIL_IF_NULL(p); - char sig[] = "alert tcp any any -> any any (content:\"XYZ\"; byte_jump:2,0,relative,string,dec; content:\"cdABCD\"; within:6; sid:1; rev:1;)"; + char sig[] = "alert tcp any any -> any any (content:\"XYZ\"; " + "byte_jump:2,0,relative,string,dec; content:\"cdABCD\"; within:6; sid:1; rev:1;)"; FAIL_IF_NOT(UTHPacketMatchSig(p, sig) ? 0 : 1); @@ -1135,7 +1134,7 @@ static int DetectByteJumpTestPacket05 (void) /** * \test check matches of with from_beginning (bug 626/627) */ -static int DetectByteJumpTestPacket06 (void) +static int DetectByteJumpTestPacket06(void) { uint8_t *buf = (uint8_t *)"XX04abcdABCD"; uint16_t buflen = strlen((char *)buf); @@ -1144,7 +1143,9 @@ static int DetectByteJumpTestPacket06 (void) FAIL_IF_NULL(p); - char sig[] = "alert tcp any any -> any any (content:\"XX\"; byte_jump:2,0,relative,string,dec,from_beginning; content:\"ABCD\"; distance:4; within:4; sid:1; rev:1;)"; + char sig[] = "alert tcp any any -> any any (content:\"XX\"; " + "byte_jump:2,0,relative,string,dec,from_beginning; content:\"ABCD\"; distance:4; " + "within:4; sid:1; rev:1;)"; FAIL_IF_NOT(UTHPacketMatchSig(p, sig)); @@ -1155,7 +1156,7 @@ static int DetectByteJumpTestPacket06 (void) /** * \test check matches of with from_beginning (bug 626/627) */ -static int DetectByteJumpTestPacket07 (void) +static int DetectByteJumpTestPacket07(void) { uint8_t *buf = (uint8_t *)"XX04abcdABCD"; uint16_t buflen = strlen((char *)buf); @@ -1164,7 +1165,9 @@ static int DetectByteJumpTestPacket07 (void) FAIL_IF_NULL(p); - char sig[] = "alert tcp any any -> any any (content:\"XX\"; byte_jump:2,0,relative,string,dec,from_beginning; content:\"abcdABCD\"; distance:0; within:8; sid:1; rev:1;)"; + char sig[] = "alert tcp any any -> any any (content:\"XX\"; " + "byte_jump:2,0,relative,string,dec,from_beginning; content:\"abcdABCD\"; " + "distance:0; within:8; sid:1; rev:1;)"; FAIL_IF_NOT(UTHPacketMatchSig(p, sig) ? 1 : 0); @@ -1175,7 +1178,7 @@ static int DetectByteJumpTestPacket07 (void) /** * \test check matches of with from_end */ -static int DetectByteJumpTestPacket08 (void) +static int DetectByteJumpTestPacket08(void) { uint8_t *buf = (uint8_t *)"XX04abcdABCD"; uint16_t buflen = strlen((char *)buf); @@ -1184,7 +1187,7 @@ static int DetectByteJumpTestPacket08 (void) FAIL_IF_NULL(p); char sig[] = "alert tcp any any -> any any (content:\"XX\"; byte_jump:2,0," - "relative,string,dec,from_end, post_offset -8; content:\"ABCD\"; sid:1; rev:1;)"; + "relative,string,dec,from_end, post_offset -8; content:\"ABCD\"; sid:1; rev:1;)"; FAIL_IF_NOT(UTHPacketMatchSig(p, sig)); diff --git a/src/detect-bytejump.h b/src/detect-bytejump.h index f8ee530b3864..6b6d425437cf 100644 --- a/src/detect-bytejump.h +++ b/src/detect-bytejump.h @@ -25,30 +25,30 @@ #define __DETECT_BYTEJUMP_H__ /** Bytejump Base */ -#define DETECT_BYTEJUMP_BASE_UNSET 0 /**< Unset type value string (automatic)*/ -#define DETECT_BYTEJUMP_BASE_OCT 8 /**< "oct" type value string */ +#define DETECT_BYTEJUMP_BASE_UNSET 0 /**< Unset type value string (automatic)*/ +#define DETECT_BYTEJUMP_BASE_OCT 8 /**< "oct" type value string */ #define DETECT_BYTEJUMP_BASE_DEC 10 /**< "dec" type value string */ #define DETECT_BYTEJUMP_BASE_HEX 16 /**< "hex" type value string */ /** Bytejump Flags */ -#define DETECT_BYTEJUMP_BEGIN BIT_U16(0) /**< "from_beginning" jump */ -#define DETECT_BYTEJUMP_LITTLE BIT_U16(1) /**< "little" endian value */ -#define DETECT_BYTEJUMP_BIG BIT_U16(2) /**< "big" endian value */ -#define DETECT_BYTEJUMP_STRING BIT_U16(3) /**< "string" value */ -#define DETECT_BYTEJUMP_RELATIVE BIT_U16(4) /**< "relative" offset */ -#define DETECT_BYTEJUMP_ALIGN BIT_U16(5) /**< "align" offset */ -#define DETECT_BYTEJUMP_DCE BIT_U16(6) /**< "dce" enabled */ -#define DETECT_BYTEJUMP_OFFSET_BE BIT_U16(7) /**< "byte extract" enabled */ -#define DETECT_BYTEJUMP_END BIT_U16(8) /**< "from_end" jump */ +#define DETECT_BYTEJUMP_BEGIN BIT_U16(0) /**< "from_beginning" jump */ +#define DETECT_BYTEJUMP_LITTLE BIT_U16(1) /**< "little" endian value */ +#define DETECT_BYTEJUMP_BIG BIT_U16(2) /**< "big" endian value */ +#define DETECT_BYTEJUMP_STRING BIT_U16(3) /**< "string" value */ +#define DETECT_BYTEJUMP_RELATIVE BIT_U16(4) /**< "relative" offset */ +#define DETECT_BYTEJUMP_ALIGN BIT_U16(5) /**< "align" offset */ +#define DETECT_BYTEJUMP_DCE BIT_U16(6) /**< "dce" enabled */ +#define DETECT_BYTEJUMP_OFFSET_BE BIT_U16(7) /**< "byte extract" enabled */ +#define DETECT_BYTEJUMP_END BIT_U16(8) /**< "from_end" jump */ #define DETECT_BYTEJUMP_NBYTES_VAR BIT_U16(9) /**< nbytes string*/ typedef struct DetectBytejumpData_ { - uint8_t nbytes; /**< Number of bytes to compare */ - uint8_t base; /**< String value base (oct|dec|hex) */ - uint16_t flags; /**< Flags (big|little|relative|string) */ - int32_t offset; /**< Offset in payload to extract value */ - int32_t post_offset; /**< Offset to adjust post-jump */ - uint16_t multiplier; /**< Multiplier for nbytes (multiplier n)*/ + uint8_t nbytes; /**< Number of bytes to compare */ + uint8_t base; /**< String value base (oct|dec|hex) */ + uint16_t flags; /**< Flags (big|little|relative|string) */ + int32_t offset; /**< Offset in payload to extract value */ + int32_t post_offset; /**< Offset to adjust post-jump */ + uint16_t multiplier; /**< Multiplier for nbytes (multiplier n)*/ } DetectBytejumpData; /* prototypes */ @@ -58,7 +58,7 @@ typedef struct DetectBytejumpData_ { * * \todo add support for no_stream and stream_only */ -void DetectBytejumpRegister (void); +void DetectBytejumpRegister(void); /** * This function is used to match byte_jump @@ -75,4 +75,3 @@ bool DetectBytejumpDoMatch(DetectEngineThreadCtx *, const Signature *, const Sig const uint8_t *, uint32_t, uint16_t, int32_t, int32_t); #endif /* __DETECT_BYTEJUMP_H__ */ - diff --git a/src/detect-bytemath.c b/src/detect-bytemath.c index 26095ac8d8cc..6bcbf5e898ea 100644 --- a/src/detect-bytemath.c +++ b/src/detect-bytemath.c @@ -251,7 +251,7 @@ static DetectByteMathData *DetectByteMathParse( if (bmd->flags & DETECT_BYTEMATH_FLAG_BITMASK) { if (bmd->bitmask_val) { uint32_t bmask = bmd->bitmask_val; - while (!(bmask & 0x1)){ + while (!(bmask & 0x1)) { bmask = bmask >> 1; bmd->bitmask_shift_count++; } @@ -260,7 +260,7 @@ static DetectByteMathData *DetectByteMathParse( return bmd; - error: +error: if (bmd != NULL) DetectByteMathFree(de_ctx, bmd); return NULL; @@ -306,11 +306,8 @@ static int DetectByteMathSetup(DetectEngineCtx *de_ctx, Signature *s, const char } } else if (data->endian == EndianDCE) { if (data->flags & DETECT_BYTEMATH_FLAG_RELATIVE) { - prev_pm = DetectGetLastSMFromLists(s, DETECT_CONTENT, DETECT_PCRE, - DETECT_BYTETEST, DETECT_BYTEJUMP, - DETECT_BYTE_EXTRACT, - DETECT_BYTEMATH, - DETECT_ISDATAAT, -1); + prev_pm = DetectGetLastSMFromLists(s, DETECT_CONTENT, DETECT_PCRE, DETECT_BYTETEST, + DETECT_BYTEJUMP, DETECT_BYTE_EXTRACT, DETECT_BYTEMATH, DETECT_ISDATAAT, -1); if (prev_pm == NULL) { sm_list = DETECT_SM_LIST_PMATCH; } else { @@ -327,10 +324,8 @@ static int DetectByteMathSetup(DetectEngineCtx *de_ctx, Signature *s, const char s->flags |= SIG_FLAG_APPLAYER; } else if (data->flags & DETECT_BYTEMATH_FLAG_RELATIVE) { - prev_pm = DetectGetLastSMFromLists(s, DETECT_CONTENT, DETECT_PCRE, - DETECT_BYTETEST, DETECT_BYTEJUMP, - DETECT_BYTE_EXTRACT, DETECT_BYTEMATH, - DETECT_ISDATAAT, -1); + prev_pm = DetectGetLastSMFromLists(s, DETECT_CONTENT, DETECT_PCRE, DETECT_BYTETEST, + DETECT_BYTEJUMP, DETECT_BYTE_EXTRACT, DETECT_BYTEMATH, DETECT_ISDATAAT, -1); if (prev_pm == NULL) { sm_list = DETECT_SM_LIST_PMATCH; } else { @@ -381,8 +376,7 @@ static int DetectByteMathSetup(DetectEngineCtx *de_ctx, Signature *s, const char rvalue = NULL; } - SigMatch *prev_bmd_sm = DetectGetLastSMByListId(s, sm_list, - DETECT_BYTEMATH, -1); + SigMatch *prev_bmd_sm = DetectGetLastSMByListId(s, sm_list, DETECT_BYTEMATH, -1); if (prev_bmd_sm == NULL) { data->local_id = 0; } else { @@ -410,10 +404,10 @@ static int DetectByteMathSetup(DetectEngineCtx *de_ctx, Signature *s, const char pd->flags |= DETECT_PCRE_RELATIVE_NEXT; } - okay: +okay: return 0; - error: +error: if (rvalue) SCFree(rvalue); if (nbytes) @@ -710,8 +704,7 @@ static int DetectByteMathParseTest12(void) static int DetectByteMathParseTest13(void) { - uint8_t flags = DETECT_BYTEMATH_FLAG_STRING | - DETECT_BYTEMATH_FLAG_RELATIVE | + uint8_t flags = DETECT_BYTEMATH_FLAG_STRING | DETECT_BYTEMATH_FLAG_RELATIVE | DETECT_BYTEMATH_FLAG_BITMASK; DetectByteMathData *bmd = DetectByteMathParse(NULL, @@ -738,7 +731,6 @@ static int DetectByteMathParseTest13(void) PASS; } - static int DetectByteMathParseTest14(void) { /* incomplete */ @@ -813,9 +805,7 @@ static int DetectByteMathPacket01(void) memset(&tv, 0, sizeof(ThreadVars)); memset(&f, 0, sizeof(Flow)); - p = UTHBuildPacketReal(buf, sizeof(buf), IPPROTO_UDP, - "192.168.1.5", "192.168.1.1", - 41424, 53); + p = UTHBuildPacketReal(buf, sizeof(buf), IPPROTO_UDP, "192.168.1.5", "192.168.1.1", 41424, 53); FAIL_IF_NULL(p); FLOW_INITIALIZE(&f); @@ -841,41 +831,43 @@ static int DetectByteMathPacket01(void) * byte_test: Compare 2 bytes at offset 13 bytes from last * match and compare with 0x6d */ - s = DetectEngineAppendSig(de_ctx, "alert udp any any -> any any " - "(byte_extract: 1, 0, extracted_val, relative;" - "byte_math: bytes 1, offset 1, oper +, rvalue extracted_val, result var;" - "byte_test: 2, =, var, 13;" - "msg:\"Byte extract and byte math with byte test verification\";" - "sid:1;)"); + s = DetectEngineAppendSig(de_ctx, + "alert udp any any -> any any " + "(byte_extract: 1, 0, extracted_val, relative;" + "byte_math: bytes 1, offset 1, oper +, rvalue extracted_val, result var;" + "byte_test: 2, =, var, 13;" + "msg:\"Byte extract and byte math with byte test verification\";" + "sid:1;)"); FAIL_IF_NULL(s); /* this rule should not alert */ - s = DetectEngineAppendSig(de_ctx, "alert udp any any -> any any " - "(byte_extract: 1, 0, extracted_val, relative;" - "byte_math: bytes 1, offset 1, oper +, rvalue extracted_val, result var;" - "byte_test: 2, !=, var, 13;" - "msg:\"Byte extract and byte math with byte test verification\";" - "sid:2;)"); + s = DetectEngineAppendSig(de_ctx, + "alert udp any any -> any any " + "(byte_extract: 1, 0, extracted_val, relative;" + "byte_math: bytes 1, offset 1, oper +, rvalue extracted_val, result var;" + "byte_test: 2, !=, var, 13;" + "msg:\"Byte extract and byte math with byte test verification\";" + "sid:2;)"); FAIL_IF_NULL(s); /* * this rule should alert: * compares offset 15 with var ... 1 (offset 15) < 0x6d (var) */ - s = DetectEngineAppendSig(de_ctx, "alert udp any any -> any any " - "(byte_extract: 1, 0, extracted_val, relative;" - "byte_math: bytes 1, offset 1, oper +, rvalue extracted_val, result var;" - "byte_test: 2, <, var, 15;" - "msg:\"Byte extract and byte math with byte test verification\";" - "sid:3;)"); + s = DetectEngineAppendSig(de_ctx, + "alert udp any any -> any any " + "(byte_extract: 1, 0, extracted_val, relative;" + "byte_math: bytes 1, offset 1, oper +, rvalue extracted_val, result var;" + "byte_test: 2, <, var, 15;" + "msg:\"Byte extract and byte math with byte test verification\";" + "sid:3;)"); FAIL_IF_NULL(s); SigGroupBuild(de_ctx); DetectEngineThreadCtxInit(&tv, (void *)de_ctx, (void *)&det_ctx); FAIL_IF_NULL(det_ctx); - int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DNS, - STREAM_TOSERVER, buf, sizeof(buf)); + int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DNS, STREAM_TOSERVER, buf, sizeof(buf)); FAIL_IF_NOT(r == 0); dns_state = f.alstate; diff --git a/src/detect-bytetest.c b/src/detect-bytetest.c index 481eb51136db..457f73ccd526 100644 --- a/src/detect-bytetest.c +++ b/src/detect-bytetest.c @@ -44,7 +44,6 @@ #include "util-debug.h" #include "detect-pcre.h" - /** * \brief Regex for parsing our options */ @@ -54,36 +53,39 @@ * 4th and 5th (test value, offset) are combined */ #define VALID_KW "relative|big|little|string|oct|dec|hex|dce|bitmask" -#define PARSE_REGEX "^\\s*" \ - "([^\\s,]+)\\s*,\\s*" \ - "(\\!?\\s*[^\\s,]*)" \ - "\\s*,\\s*([^\\s,]+\\s*,\\s*[^\\s,]+)" \ - "(?:\\s*,\\s*((?:"VALID_KW")\\s+[^\\s,]+|["VALID_KW"]+))?" \ - "(?:\\s*,\\s*((?:"VALID_KW")\\s+[^\\s,]+|["VALID_KW"]+))?" \ - "(?:\\s*,\\s*((?:"VALID_KW")\\s+[^\\s,]+|["VALID_KW"]+))?" \ - "(?:\\s*,\\s*((?:"VALID_KW")\\s+[^\\s,]+|["VALID_KW"]+))?" \ - "(?:\\s*,\\s*((?:"VALID_KW")\\s+[^\\s,]+|["VALID_KW"]+))?" \ - "(?:\\s*,\\s*((?:"VALID_KW")\\s+[^\\s,]+|["VALID_KW"]+))?" \ - "\\s*$" +#define PARSE_REGEX \ + "^\\s*" \ + "([^\\s,]+)\\s*,\\s*" \ + "(\\!?\\s*[^\\s,]*)" \ + "\\s*,\\s*([^\\s,]+\\s*,\\s*[^\\s,]+)" \ + "(?:\\s*,\\s*((?:" VALID_KW ")\\s+[^\\s,]+|[" VALID_KW "]+))?" \ + "(?:\\s*,\\s*((?:" VALID_KW ")\\s+[^\\s,]+|[" VALID_KW "]+))?" \ + "(?:\\s*,\\s*((?:" VALID_KW ")\\s+[^\\s,]+|[" VALID_KW "]+))?" \ + "(?:\\s*,\\s*((?:" VALID_KW ")\\s+[^\\s,]+|[" VALID_KW "]+))?" \ + "(?:\\s*,\\s*((?:" VALID_KW ")\\s+[^\\s,]+|[" VALID_KW "]+))?" \ + "(?:\\s*,\\s*((?:" VALID_KW ")\\s+[^\\s,]+|[" VALID_KW "]+))?" \ + "\\s*$" static DetectParseRegex parse_regex; -static int DetectBytetestMatch(DetectEngineThreadCtx *det_ctx, - Packet *p, const Signature *s, const SigMatchCtx *ctx); +static int DetectBytetestMatch( + DetectEngineThreadCtx *det_ctx, Packet *p, const Signature *s, const SigMatchCtx *ctx); static int DetectBytetestSetup(DetectEngineCtx *de_ctx, Signature *s, const char *optstr); static void DetectBytetestFree(DetectEngineCtx *, void *ptr); #ifdef UNITTESTS static void DetectBytetestRegisterTests(void); #endif -void DetectBytetestRegister (void) +void DetectBytetestRegister(void) { sigmatch_table[DETECT_BYTETEST].name = "byte_test"; - sigmatch_table[DETECT_BYTETEST].desc = "extract and perform an operation selected with against the value in at a particular "; + sigmatch_table[DETECT_BYTETEST].desc = + "extract and perform an operation selected with against the " + "value in at a particular "; sigmatch_table[DETECT_BYTETEST].url = "/rules/payload-keywords.html#byte-test"; sigmatch_table[DETECT_BYTETEST].Match = DetectBytetestMatch; sigmatch_table[DETECT_BYTETEST].Setup = DetectBytetestSetup; - sigmatch_table[DETECT_BYTETEST].Free = DetectBytetestFree; + sigmatch_table[DETECT_BYTETEST].Free = DetectBytetestFree; #ifdef UNITTESTS sigmatch_table[DETECT_BYTETEST].RegisterTests = DetectBytetestRegisterTests; #endif @@ -183,8 +185,9 @@ int DetectBytetestDoMatch(DetectEngineThreadCtx *det_ctx, const Signature *s, * the packet from that point. */ if (flags & DETECT_BYTETEST_RELATIVE) { - SCLogDebug("relative, working with det_ctx->buffer_offset %"PRIu32", " - "data->offset %"PRIi32"", det_ctx->buffer_offset, data->offset); + SCLogDebug("relative, working with det_ctx->buffer_offset %" PRIu32 ", " + "data->offset %" PRIi32 "", + det_ctx->buffer_offset, data->offset); ptr = payload + det_ctx->buffer_offset; len = payload_len - det_ctx->buffer_offset; @@ -196,9 +199,8 @@ int DetectBytetestDoMatch(DetectEngineThreadCtx *det_ctx, const Signature *s, if (ptr == NULL || len <= 0) { SCReturnInt(0); } - } - else { - SCLogDebug("absolute, data->offset %"PRIi32"", data->offset); + } else { + SCLogDebug("absolute, data->offset %" PRIi32 "", data->offset); ptr = payload + offset; len = payload_len - offset; @@ -231,12 +233,10 @@ int DetectBytetestDoMatch(DetectEngineThreadCtx *det_ctx, const Signature *s, } } - SCLogDebug("comparing base %d string 0x%" PRIx64 " %s%u 0x%" PRIx64, - data->base, val, (neg ? "!" : ""), data->op, data->value); - } - else { - int endianness = (flags & DETECT_BYTETEST_LITTLE) ? - BYTE_LITTLE_ENDIAN : BYTE_BIG_ENDIAN; + SCLogDebug("comparing base %d string 0x%" PRIx64 " %s%u 0x%" PRIx64, data->base, val, + (neg ? "!" : ""), data->op, data->value); + } else { + int endianness = (flags & DETECT_BYTETEST_LITTLE) ? BYTE_LITTLE_ENDIAN : BYTE_BIG_ENDIAN; extbytes = ByteExtractUint64(&val, endianness, (uint16_t)nbytes, ptr); if (extbytes != nbytes) { SCLogDebug("error extracting %d bytes " @@ -245,8 +245,8 @@ int DetectBytetestDoMatch(DetectEngineThreadCtx *det_ctx, const Signature *s, SCReturnInt(-1); } - SCLogDebug("comparing numeric 0x%" PRIx64 " %s%u 0x%" PRIx64, - val, (neg ? "!" : ""), data->op, data->value); + SCLogDebug("comparing numeric 0x%" PRIx64 " %s%u 0x%" PRIx64, val, (neg ? "!" : ""), + data->op, data->value); } /* apply bitmask, if any and then right-shift 1 bit for each trailing 0 in @@ -304,17 +304,16 @@ int DetectBytetestDoMatch(DetectEngineThreadCtx *det_ctx, const Signature *s, /* A successful match depends on negation */ if ((!neg && match) || (neg && !match)) { - SCLogDebug("MATCH [bt] extracted value is %"PRIu64, val); + SCLogDebug("MATCH [bt] extracted value is %" PRIu64, val); SCReturnInt(1); } SCLogDebug("NO MATCH"); SCReturnInt(0); - } -static int DetectBytetestMatch(DetectEngineThreadCtx *det_ctx, - Packet *p, const Signature *s, const SigMatchCtx *ctx) +static int DetectBytetestMatch( + DetectEngineThreadCtx *det_ctx, Packet *p, const Signature *s, const SigMatchCtx *ctx) { return DetectBytetestDoMatch(det_ctx, s, ctx, p->payload, p->payload_len, ((DetectBytetestData *)ctx)->flags, 0, 0, 0); @@ -324,11 +323,8 @@ static DetectBytetestData *DetectBytetestParse( const char *optstr, char **value, char **offset, char **nbytes_str) { DetectBytetestData *data = NULL; - char *args[9] = { - NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, - NULL - }; - char *test_value = NULL; + char *args[9] = { NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL }; + char *test_value = NULL; char *data_offset = NULL; int res = 0; size_t pcre2_len; @@ -355,8 +351,8 @@ static DetectBytetestData *DetectBytetestParse( } /* args[2] is comma separated test value, offset */ if (i == 2) { - test_value = (char *) str_ptr; - data_offset = SCStrdup((char *) str_ptr); + test_value = (char *)str_ptr; + data_offset = SCStrdup((char *)str_ptr); if (data_offset == NULL) { goto error; } @@ -410,14 +406,14 @@ static DetectBytetestData *DetectBytetestParse( if (args[1][op_offset] == '!') { data->neg_op = true; op_ptr = &args[1][1]; - while (isspace((char)*op_ptr) || (*op_ptr == ',')) op_ptr++; + while (isspace((char)*op_ptr) || (*op_ptr == ',')) + op_ptr++; op_offset = op_ptr - &args[1][0]; } else { data->neg_op = false; } op_ptr = args[1] + op_offset; - if ((strcmp("=", op_ptr) == 0) || (data->neg_op - && strcmp("", op_ptr) == 0)) { + if ((strcmp("=", op_ptr) == 0) || (data->neg_op && strcmp("", op_ptr) == 0)) { data->op |= DETECT_BYTETEST_OP_EQ; } else if (strcmp("<", op_ptr) == 0) { data->op |= DETECT_BYTETEST_OP_LT; @@ -444,7 +440,8 @@ static DetectBytetestData *DetectBytetestParse( * and data_offset (SCStrdup), respectively; e.g., test_value,offset */ char *end_ptr = test_value; - while (!(isspace((unsigned char)*end_ptr) || (*end_ptr == ','))) end_ptr++; + while (!(isspace((unsigned char)*end_ptr) || (*end_ptr == ','))) + end_ptr++; *end_ptr = '\0'; if (test_value[0] != '-' && isalpha((unsigned char)test_value[0])) { @@ -468,14 +465,16 @@ static DetectBytetestData *DetectBytetestParse( /* Offset -- note that this *also* contains test_value, offset so parse accordingly */ if (data_offset) { char *end_ptr = data_offset; - while (!(isspace((unsigned char)*end_ptr) || (*end_ptr == ','))) end_ptr++; + while (!(isspace((unsigned char)*end_ptr) || (*end_ptr == ','))) + end_ptr++; str_ptr = ++end_ptr; - while (isspace((unsigned char)*str_ptr) || (*str_ptr == ',')) str_ptr++; + while (isspace((unsigned char)*str_ptr) || (*str_ptr == ',')) + str_ptr++; end_ptr = (char *)str_ptr; while (!(isspace((unsigned char)*end_ptr) || (*end_ptr == ',')) && (*end_ptr != '\0')) end_ptr++; memmove(data_offset, str_ptr, end_ptr - str_ptr); - data_offset[end_ptr-str_ptr] = '\0'; + data_offset[end_ptr - str_ptr] = '\0'; if (data_offset[0] != '-' && isalpha((unsigned char)data_offset[0])) { if (data_offset == NULL) { SCLogError("byte_test supplied with " @@ -538,7 +537,8 @@ static DetectBytetestData *DetectBytetestParse( } if (bitmask_index != -1 && data->flags & DETECT_BYTETEST_BITMASK) { - if (ByteExtractStringUint32(&data->bitmask, 0, 0, args[bitmask_index]+strlen("bitmask")) <= 0) { + if (ByteExtractStringUint32( + &data->bitmask, 0, 0, args[bitmask_index] + strlen("bitmask")) <= 0) { SCLogError("Malformed bitmask value: %s", args[bitmask_index] + strlen("bitmask")); goto error; } @@ -548,32 +548,35 @@ static DetectBytetestData *DetectBytetestParse( data->bitmask_shift_count = 0; if (data->bitmask) { uint32_t bmask = data->bitmask; - while (!(bmask & 0x1)){ + while (!(bmask & 0x1)) { bmask = bmask >> 1; data->bitmask_shift_count++; } } } - for (i = 0; i < (ret - 1); i++){ + for (i = 0; i < (ret - 1); i++) { if (args[i] != NULL) pcre2_substring_free((PCRE2_UCHAR8 *)args[i]); } - if (data_offset) SCFree(data_offset); + if (data_offset) + SCFree(data_offset); if (test_value) pcre2_substring_free((PCRE2_UCHAR8 *)test_value); pcre2_match_data_free(match); return data; error: - for (i = 0; i < (ret - 1); i++){ + for (i = 0; i < (ret - 1); i++) { if (args[i] != NULL) pcre2_substring_free((PCRE2_UCHAR8 *)args[i]); } - if (data_offset) SCFree(data_offset); + if (data_offset) + SCFree(data_offset); if (test_value) pcre2_substring_free((PCRE2_UCHAR8 *)test_value); - if (data) SCFree(data); + if (data) + SCFree(data); if (match) { pcre2_match_data_free(match); } @@ -605,10 +608,8 @@ static int DetectBytetestSetup(DetectEngineCtx *de_ctx, Signature *s, const char } else if (data->flags & DETECT_BYTETEST_DCE) { if (data->flags & DETECT_BYTETEST_RELATIVE) { - prev_pm = DetectGetLastSMFromLists(s, - DETECT_CONTENT, DETECT_PCRE, - DETECT_BYTETEST, DETECT_BYTEJUMP, DETECT_BYTE_EXTRACT, - DETECT_ISDATAAT, DETECT_BYTEMATH, -1); + prev_pm = DetectGetLastSMFromLists(s, DETECT_CONTENT, DETECT_PCRE, DETECT_BYTETEST, + DETECT_BYTEJUMP, DETECT_BYTE_EXTRACT, DETECT_ISDATAAT, DETECT_BYTEMATH, -1); if (prev_pm == NULL) { sm_list = DETECT_SM_LIST_PMATCH; } else { @@ -624,10 +625,8 @@ static int DetectBytetestSetup(DetectEngineCtx *de_ctx, Signature *s, const char goto error; } else if (data->flags & DETECT_BYTETEST_RELATIVE) { - prev_pm = DetectGetLastSMFromLists(s, - DETECT_CONTENT, DETECT_PCRE, - DETECT_BYTETEST, DETECT_BYTEJUMP, DETECT_BYTE_EXTRACT, - DETECT_ISDATAAT, DETECT_BYTEMATH, -1); + prev_pm = DetectGetLastSMFromLists(s, DETECT_CONTENT, DETECT_PCRE, DETECT_BYTETEST, + DETECT_BYTEJUMP, DETECT_BYTE_EXTRACT, DETECT_ISDATAAT, DETECT_BYTEMATH, -1); if (prev_pm == NULL) { sm_list = DETECT_SM_LIST_PMATCH; } else { @@ -641,12 +640,10 @@ static int DetectBytetestSetup(DetectEngineCtx *de_ctx, Signature *s, const char } if (data->flags & DETECT_BYTETEST_DCE) { - if ((data->flags & DETECT_BYTETEST_STRING) || - (data->flags & DETECT_BYTETEST_LITTLE) || - (data->flags & DETECT_BYTETEST_BIG) || - (data->base == DETECT_BYTETEST_BASE_DEC) || - (data->base == DETECT_BYTETEST_BASE_HEX) || - (data->base == DETECT_BYTETEST_BASE_OCT) ) { + if ((data->flags & DETECT_BYTETEST_STRING) || (data->flags & DETECT_BYTETEST_LITTLE) || + (data->flags & DETECT_BYTETEST_BIG) || (data->base == DETECT_BYTETEST_BASE_DEC) || + (data->base == DETECT_BYTETEST_BASE_HEX) || + (data->base == DETECT_BYTETEST_BASE_OCT)) { SCLogError("Invalid option. " "A byte_test keyword with dce holds other invalid modifiers."); goto error; @@ -712,10 +709,10 @@ static int DetectBytetestSetup(DetectEngineCtx *de_ctx, Signature *s, const char pd->flags |= DETECT_PCRE_RELATIVE_NEXT; } - okay: +okay: ret = 0; return ret; - error: +error: if (offset) SCFree(offset); if (value) @@ -740,7 +737,6 @@ static void DetectBytetestFree(DetectEngineCtx *de_ctx, void *ptr) SCFree(data); } - /* UNITTESTS */ #ifdef UNITTESTS #include "util-unittest-helper.h" @@ -1090,11 +1086,11 @@ static int DetectBytetestTestParse20(void) de_ctx->flags |= DE_QUIET; de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"Testing bytetest_body\"; " - "dce_iface:3919286a-b10c-11d0-9ba8-00c04fd92ef5; " - "dce_stub_data; " - "content:\"one\"; distance:0; " - "byte_test:1,=,1,6,relative,dce; sid:1;)"); + "(msg:\"Testing bytetest_body\"; " + "dce_iface:3919286a-b10c-11d0-9ba8-00c04fd92ef5; " + "dce_stub_data; " + "content:\"one\"; distance:0; " + "byte_test:1,=,1,6,relative,dce; sid:1;)"); FAIL_IF_NULL(de_ctx->sig_list); s = de_ctx->sig_list; @@ -1113,11 +1109,11 @@ static int DetectBytetestTestParse20(void) FAIL_IF(bd->neg_op); s->next = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"Testing bytetest_body\"; " - "dce_iface:3919286a-b10c-11d0-9ba8-00c04fd92ef5; " - "dce_stub_data; " - "content:\"one\"; distance:0; " - "byte_test:1,=,1,6,relative,dce; sid:1;)"); + "(msg:\"Testing bytetest_body\"; " + "dce_iface:3919286a-b10c-11d0-9ba8-00c04fd92ef5; " + "dce_stub_data; " + "content:\"one\"; distance:0; " + "byte_test:1,=,1,6,relative,dce; sid:1;)"); FAIL_IF_NULL(s->next); s = s->next; @@ -1135,11 +1131,11 @@ static int DetectBytetestTestParse20(void) FAIL_IF(bd->neg_op); s->next = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"Testing bytetest_body\"; " - "dce_iface:3919286a-b10c-11d0-9ba8-00c04fd92ef5; " - "dce_stub_data; " - "content:\"one\"; distance:0; " - "byte_test:1,=,1,6,relative; sid:1;)"); + "(msg:\"Testing bytetest_body\"; " + "dce_iface:3919286a-b10c-11d0-9ba8-00c04fd92ef5; " + "dce_stub_data; " + "content:\"one\"; distance:0; " + "byte_test:1,=,1,6,relative; sid:1;)"); FAIL_IF_NULL(s->next); s = s->next; @@ -1175,69 +1171,69 @@ static int DetectBytetestTestParse21(void) de_ctx->flags |= DE_QUIET; s = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"Testing bytetest_body\"; " - "dce_iface:3919286a-b10c-11d0-9ba8-00c04fd92ef5; " - "content:\"one\"; byte_test:1,=,1,6,string,dce; sid:1;)"); + "(msg:\"Testing bytetest_body\"; " + "dce_iface:3919286a-b10c-11d0-9ba8-00c04fd92ef5; " + "content:\"one\"; byte_test:1,=,1,6,string,dce; sid:1;)"); FAIL_IF_NOT_NULL(s); s = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"Testing bytetest_body\"; " - "dce_iface:3919286a-b10c-11d0-9ba8-00c04fd92ef5; " - "content:\"one\"; byte_test:1,=,1,6,big,dce; sid:1;)"); + "(msg:\"Testing bytetest_body\"; " + "dce_iface:3919286a-b10c-11d0-9ba8-00c04fd92ef5; " + "content:\"one\"; byte_test:1,=,1,6,big,dce; sid:1;)"); FAIL_IF_NOT_NULL(s); s = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"Testing bytetest_body\"; " - "dce_iface:3919286a-b10c-11d0-9ba8-00c04fd92ef5; " - "content:\"one\"; byte_test:1,=,1,6,little,dce; sid:1;)"); + "(msg:\"Testing bytetest_body\"; " + "dce_iface:3919286a-b10c-11d0-9ba8-00c04fd92ef5; " + "content:\"one\"; byte_test:1,=,1,6,little,dce; sid:1;)"); FAIL_IF_NOT_NULL(s); s = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"Testing bytetest_body\"; " - "dce_iface:3919286a-b10c-11d0-9ba8-00c04fd92ef5; " - "content:\"one\"; byte_test:1,=,1,6,hex,dce; sid:1;)"); + "(msg:\"Testing bytetest_body\"; " + "dce_iface:3919286a-b10c-11d0-9ba8-00c04fd92ef5; " + "content:\"one\"; byte_test:1,=,1,6,hex,dce; sid:1;)"); FAIL_IF_NOT_NULL(s); s = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"Testing bytetest_body\"; " - "dce_iface:3919286a-b10c-11d0-9ba8-00c04fd92ef5; " - "content:\"one\"; byte_test:1,=,1,6,dec,dce; sid:1;)"); + "(msg:\"Testing bytetest_body\"; " + "dce_iface:3919286a-b10c-11d0-9ba8-00c04fd92ef5; " + "content:\"one\"; byte_test:1,=,1,6,dec,dce; sid:1;)"); FAIL_IF_NOT_NULL(s); s = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"Testing bytetest_body\"; " - "dce_iface:3919286a-b10c-11d0-9ba8-00c04fd92ef5; " - "content:\"one\"; byte_test:1,=,1,6,oct,dce; sid:1;)"); + "(msg:\"Testing bytetest_body\"; " + "dce_iface:3919286a-b10c-11d0-9ba8-00c04fd92ef5; " + "content:\"one\"; byte_test:1,=,1,6,oct,dce; sid:1;)"); FAIL_IF_NOT_NULL(s); s = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"Testing bytetest_body\"; " - "dce_iface:3919286a-b10c-11d0-9ba8-00c04fd92ef5; " - "content:\"one\"; byte_test:1,=,1,6,string,hex,dce; sid:1;)"); + "(msg:\"Testing bytetest_body\"; " + "dce_iface:3919286a-b10c-11d0-9ba8-00c04fd92ef5; " + "content:\"one\"; byte_test:1,=,1,6,string,hex,dce; sid:1;)"); FAIL_IF_NOT_NULL(s); s = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"Testing bytetest_body\"; " - "dce_iface:3919286a-b10c-11d0-9ba8-00c04fd92ef5; " - "content:\"one\"; byte_test:1,=,1,6,big,string,hex,dce; sid:1;)"); + "(msg:\"Testing bytetest_body\"; " + "dce_iface:3919286a-b10c-11d0-9ba8-00c04fd92ef5; " + "content:\"one\"; byte_test:1,=,1,6,big,string,hex,dce; sid:1;)"); FAIL_IF_NOT_NULL(s); s = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"Testing bytetest_body\"; " - "dce_iface:3919286a-b10c-11d0-9ba8-00c04fd92ef5; " - "content:\"one\"; byte_test:1,=,1,6,big,string,oct,dce; sid:1;)"); + "(msg:\"Testing bytetest_body\"; " + "dce_iface:3919286a-b10c-11d0-9ba8-00c04fd92ef5; " + "content:\"one\"; byte_test:1,=,1,6,big,string,oct,dce; sid:1;)"); FAIL_IF_NOT_NULL(s); s = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"Testing bytetest_body\"; " - "dce_iface:3919286a-b10c-11d0-9ba8-00c04fd92ef5; " - "content:\"one\"; byte_test:1,=,1,6,little,string,hex,dce; sid:1;)"); + "(msg:\"Testing bytetest_body\"; " + "dce_iface:3919286a-b10c-11d0-9ba8-00c04fd92ef5; " + "content:\"one\"; byte_test:1,=,1,6,little,string,hex,dce; sid:1;)"); FAIL_IF_NOT_NULL(s); s = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"Testing bytetest_body\"; " - "dce_iface:3919286a-b10c-11d0-9ba8-00c04fd92ef5; " - "content:\"one\"; byte_test:1,=,1,6,big,string,dec,dce; sid:1;)"); + "(msg:\"Testing bytetest_body\"; " + "dce_iface:3919286a-b10c-11d0-9ba8-00c04fd92ef5; " + "content:\"one\"; byte_test:1,=,1,6,big,string,dec,dce; sid:1;)"); FAIL_IF_NOT_NULL(s); SigGroupCleanup(de_ctx); @@ -1261,7 +1257,7 @@ static int DetectBytetestTestParse22(void) de_ctx->flags |= DE_QUIET; de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " - "(file_data; byte_test:1,=,1,6,relative; sid:1;)"); + "(file_data; byte_test:1,=,1,6,relative; sid:1;)"); FAIL_IF_NULL(de_ctx->sig_list); s = de_ctx->sig_list; diff --git a/src/detect-bytetest.h b/src/detect-bytetest.h index 4b4684972b91..f202eff01639 100644 --- a/src/detect-bytetest.h +++ b/src/detect-bytetest.h @@ -25,17 +25,17 @@ #define __DETECT_BYTETEST_H__ /** Bytetest Operators */ -#define DETECT_BYTETEST_OP_LT 1 /**< "less than" operator */ -#define DETECT_BYTETEST_OP_GT 2 /**< "greater than" operator */ -#define DETECT_BYTETEST_OP_EQ 3 /**< "equals" operator */ -#define DETECT_BYTETEST_OP_AND 4 /**< "bitwise and" operator */ -#define DETECT_BYTETEST_OP_OR 5 /**< "bitwise or" operator */ -#define DETECT_BYTETEST_OP_GE 6 /**< greater than equal operator */ -#define DETECT_BYTETEST_OP_LE 7 /**< less than equal operator */ +#define DETECT_BYTETEST_OP_LT 1 /**< "less than" operator */ +#define DETECT_BYTETEST_OP_GT 2 /**< "greater than" operator */ +#define DETECT_BYTETEST_OP_EQ 3 /**< "equals" operator */ +#define DETECT_BYTETEST_OP_AND 4 /**< "bitwise and" operator */ +#define DETECT_BYTETEST_OP_OR 5 /**< "bitwise or" operator */ +#define DETECT_BYTETEST_OP_GE 6 /**< greater than equal operator */ +#define DETECT_BYTETEST_OP_LE 7 /**< less than equal operator */ /** Bytetest Base */ -#define DETECT_BYTETEST_BASE_UNSET 0 /**< Unset type value string (automatic)*/ -#define DETECT_BYTETEST_BASE_OCT 8 /**< "oct" type value string */ +#define DETECT_BYTETEST_BASE_UNSET 0 /**< Unset type value string (automatic)*/ +#define DETECT_BYTETEST_BASE_OCT 8 /**< "oct" type value string */ #define DETECT_BYTETEST_BASE_DEC 10 /**< "dec" type value string */ #define DETECT_BYTETEST_BASE_HEX 16 /**< "hex" type value string */ @@ -51,15 +51,15 @@ #define DETECT_BYTETEST_NBYTES_VAR BIT_U16(8) /**< byte extract value enabled */ typedef struct DetectBytetestData_ { - uint8_t nbytes; /**< Number of bytes to compare */ - uint8_t op; /**< Operator used to compare */ - uint8_t base; /**< String value base (oct|dec|hex) */ - uint8_t bitmask_shift_count; /**< bitmask trailing 0 count */ - uint16_t flags; /**< Flags (big|little|relative|string|bitmask) */ + uint8_t nbytes; /**< Number of bytes to compare */ + uint8_t op; /**< Operator used to compare */ + uint8_t base; /**< String value base (oct|dec|hex) */ + uint8_t bitmask_shift_count; /**< bitmask trailing 0 count */ + uint16_t flags; /**< Flags (big|little|relative|string|bitmask) */ bool neg_op; - int32_t offset; /**< Offset in payload */ - uint32_t bitmask; /**< bitmask value */ - uint64_t value; /**< Value to compare against */ + int32_t offset; /**< Offset in payload */ + uint32_t bitmask; /**< bitmask value */ + uint64_t value; /**< Value to compare against */ } DetectBytetestData; /* prototypes */ @@ -69,7 +69,7 @@ typedef struct DetectBytetestData_ { * * \todo add support for no_stream and stream_only */ -void DetectBytetestRegister (void); +void DetectBytetestRegister(void); int DetectBytetestDoMatch(DetectEngineThreadCtx *, const Signature *, const SigMatchCtx *ctx, const uint8_t *, uint32_t, uint16_t, int32_t, int32_t, uint64_t); diff --git a/src/detect-cipservice.c b/src/detect-cipservice.c index 494e1e17520f..f5d816d0d8ab 100644 --- a/src/detect-cipservice.c +++ b/src/detect-cipservice.c @@ -53,15 +53,14 @@ static int g_cip_buffer_id = 0; void DetectCipServiceRegister(void) { SCEnter(); - sigmatch_table[DETECT_CIPSERVICE].name = "cip_service"; //rule keyword + sigmatch_table[DETECT_CIPSERVICE].name = "cip_service"; // rule keyword sigmatch_table[DETECT_CIPSERVICE].desc = "match on CIP Service"; sigmatch_table[DETECT_CIPSERVICE].url = "/rules/enip-keyword.html#enip-cip-keywords"; sigmatch_table[DETECT_CIPSERVICE].Match = NULL; sigmatch_table[DETECT_CIPSERVICE].Setup = DetectCipServiceSetup; sigmatch_table[DETECT_CIPSERVICE].Free = DetectCipServiceFree; #ifdef UNITTESTS - sigmatch_table[DETECT_CIPSERVICE].RegisterTests - = DetectCipServiceRegisterTests; + sigmatch_table[DETECT_CIPSERVICE].RegisterTests = DetectCipServiceRegisterTests; #endif DetectAppLayerInspectEngineRegister2( "cip", ALPROTO_ENIP, SIG_FLAG_TOSERVER, 0, DetectEngineInspectCIP, NULL); @@ -87,7 +86,7 @@ static DetectCipServiceData *DetectCipServiceParse(const char *rulestrc) const char delims[] = ","; DetectCipServiceData *cipserviced = NULL; - //SCLogDebug("DetectCipServiceParse - rule string %s", rulestr); + // SCLogDebug("DetectCipServiceParse - rule string %s", rulestr); /* strtok_r modifies the string so work with a copy */ char *rulestr = SCStrdup(rulestrc); @@ -103,55 +102,50 @@ static DetectCipServiceData *DetectCipServiceParse(const char *rulestrc) cipserviced->matchattribute = 1; cipserviced->cipattribute = 0; - char* token; + char *token; char *save; uint8_t var; uint8_t input[3] = { 0, 0, 0 }; uint8_t i = 0; token = strtok_r(rulestr, delims, &save); - while (token != NULL) - { - if (i > 2) //for now only need 3 parameters + while (token != NULL) { + if (i > 2) // for now only need 3 parameters { SCLogError("too many parameters"); goto error; } - if (i < 2) //if on service or class + if (i < 2) // if on service or class { - if (!isdigit((int) *token)) - { + if (!isdigit((int)*token)) { SCLogError("parameter error %s", token); goto error; } - } else //if on attribute + } else // if on attribute { - if (token[0] == '!') - { + if (token[0] == '!') { cipserviced->matchattribute = 0; token++; } - if (!isdigit((int) *token)) - { + if (!isdigit((int)*token)) { SCLogError("attribute error %s", token); goto error; } - } unsigned long num = atol(token); - if ((num > MAX_CIP_SERVICE) && (i == 0))//if service greater than 7 bit + if ((num > MAX_CIP_SERVICE) && (i == 0)) // if service greater than 7 bit { SCLogError("invalid CIP service %lu", num); goto error; - } else if ((num > MAX_CIP_CLASS) && (i == 1))//if service greater than 16 bit + } else if ((num > MAX_CIP_CLASS) && (i == 1)) // if service greater than 16 bit { SCLogError("invalid CIP class %lu", num); goto error; - } else if ((num > MAX_CIP_ATTRIBUTE) && (i == 2))//if service greater than 16 bit + } else if ((num > MAX_CIP_ATTRIBUTE) && (i == 2)) // if service greater than 16 bit { SCLogError("invalid CIP attribute %lu", num); goto error; @@ -176,10 +170,8 @@ static DetectCipServiceData *DetectCipServiceParse(const char *rulestrc) SCLogDebug("DetectCipServiceParse - tokens %d", cipserviced->tokens); SCLogDebug("DetectCipServiceParse - service %d", cipserviced->cipservice); SCLogDebug("DetectCipServiceParse - class %d", cipserviced->cipclass); - SCLogDebug("DetectCipServiceParse - match attribute %d", - cipserviced->matchattribute); - SCLogDebug("DetectCipServiceParse - attribute %d", - cipserviced->cipattribute); + SCLogDebug("DetectCipServiceParse - match attribute %d", cipserviced->matchattribute); + SCLogDebug("DetectCipServiceParse - attribute %d", cipserviced->cipattribute); SCFree(rulestr); SCReturnPtr(cipserviced, "DetectENIPFunction"); @@ -193,7 +185,8 @@ static DetectCipServiceData *DetectCipServiceParse(const char *rulestrc) } /** - * \brief this function is used to a cipserviced the parsed cip_service data into the current signature + * \brief this function is used to a cipserviced the parsed cip_service data into the current + * signature * * \param de_ctx pointer to the Detection Engine Context * \param s pointer to the Current Signature @@ -202,8 +195,7 @@ static DetectCipServiceData *DetectCipServiceParse(const char *rulestrc) * \retval 0 on Success * \retval -1 on Failure */ -static int DetectCipServiceSetup(DetectEngineCtx *de_ctx, Signature *s, - const char *rulestr) +static int DetectCipServiceSetup(DetectEngineCtx *de_ctx, Signature *s, const char *rulestr) { SCEnter(); @@ -235,7 +227,7 @@ static int DetectCipServiceSetup(DetectEngineCtx *de_ctx, Signature *s, */ static void DetectCipServiceFree(DetectEngineCtx *de_ctx, void *ptr) { - DetectCipServiceData *cipserviced = (DetectCipServiceData *) ptr; + DetectCipServiceData *cipserviced = (DetectCipServiceData *)ptr; SCFree(cipserviced); } @@ -244,7 +236,7 @@ static void DetectCipServiceFree(DetectEngineCtx *de_ctx, void *ptr) /** * \test Test CIP Command parameter parsing */ -static int DetectCipServiceParseTest01 (void) +static int DetectCipServiceParseTest01(void) { DetectCipServiceData *cipserviced = NULL; cipserviced = DetectCipServiceParse("7"); @@ -257,11 +249,12 @@ static int DetectCipServiceParseTest01 (void) /** * \test Test CIP Service signature */ -static int DetectCipServiceSignatureTest01 (void) +static int DetectCipServiceSignatureTest01(void) { DetectEngineCtx *de_ctx = DetectEngineCtxInit(); FAIL_IF_NULL(de_ctx); - Signature *sig = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any (cip_service:1; sid:1; rev:1;)"); + Signature *sig = DetectEngineAppendSig( + de_ctx, "alert tcp any any -> any any (cip_service:1; sid:1; rev:1;)"); FAIL_IF_NULL(sig); DetectEngineCtxFree(de_ctx); PASS; @@ -272,10 +265,8 @@ static int DetectCipServiceSignatureTest01 (void) */ static void DetectCipServiceRegisterTests(void) { - UtRegisterTest("DetectCipServiceParseTest01", - DetectCipServiceParseTest01); - UtRegisterTest("DetectCipServiceSignatureTest01", - DetectCipServiceSignatureTest01); + UtRegisterTest("DetectCipServiceParseTest01", DetectCipServiceParseTest01); + UtRegisterTest("DetectCipServiceSignatureTest01", DetectCipServiceSignatureTest01); } #endif /* UNITTESTS */ @@ -298,16 +289,14 @@ static int g_enip_buffer_id = 0; */ void DetectEnipCommandRegister(void) { - sigmatch_table[DETECT_ENIPCOMMAND].name = "enip_command"; //rule keyword - sigmatch_table[DETECT_ENIPCOMMAND].desc - = "rules for detecting EtherNet/IP command"; + sigmatch_table[DETECT_ENIPCOMMAND].name = "enip_command"; // rule keyword + sigmatch_table[DETECT_ENIPCOMMAND].desc = "rules for detecting EtherNet/IP command"; sigmatch_table[DETECT_ENIPCOMMAND].url = "/rules/enip-keyword.html#enip-cip-keywords"; sigmatch_table[DETECT_ENIPCOMMAND].Match = NULL; sigmatch_table[DETECT_ENIPCOMMAND].Setup = DetectEnipCommandSetup; sigmatch_table[DETECT_ENIPCOMMAND].Free = DetectEnipCommandFree; #ifdef UNITTESTS - sigmatch_table[DETECT_ENIPCOMMAND].RegisterTests - = DetectEnipCommandRegisterTests; + sigmatch_table[DETECT_ENIPCOMMAND].RegisterTests = DetectEnipCommandRegisterTests; #endif DetectAppLayerInspectEngineRegister2( "enip", ALPROTO_ENIP, SIG_FLAG_TOSERVER, 0, DetectEngineInspectENIP, NULL); @@ -334,7 +323,7 @@ static DetectEnipCommandData *DetectEnipCommandParse(const char *rulestr) if (unlikely(enipcmdd == NULL)) goto error; - if (!(isdigit((int) *rulestr))) { + if (!(isdigit((int)*rulestr))) { SCLogError("invalid ENIP command %s", rulestr); goto error; } @@ -367,8 +356,7 @@ static DetectEnipCommandData *DetectEnipCommandParse(const char *rulestr) * \retval 0 on Success * \retval -1 on Failure */ -static int DetectEnipCommandSetup(DetectEngineCtx *de_ctx, Signature *s, - const char *rulestr) +static int DetectEnipCommandSetup(DetectEngineCtx *de_ctx, Signature *s, const char *rulestr) { DetectEnipCommandData *enipcmdd = NULL; @@ -398,7 +386,7 @@ static int DetectEnipCommandSetup(DetectEngineCtx *de_ctx, Signature *s, */ static void DetectEnipCommandFree(DetectEngineCtx *de_ctx, void *ptr) { - DetectEnipCommandData *enipcmdd = (DetectEnipCommandData *) ptr; + DetectEnipCommandData *enipcmdd = (DetectEnipCommandData *)ptr; SCFree(enipcmdd); } @@ -408,7 +396,7 @@ static void DetectEnipCommandFree(DetectEngineCtx *de_ctx, void *ptr) * \test ENIP parameter test */ -static int DetectEnipCommandParseTest01 (void) +static int DetectEnipCommandParseTest01(void) { DetectEnipCommandData *enipcmdd = NULL; @@ -423,12 +411,13 @@ static int DetectEnipCommandParseTest01 (void) /** * \test ENIP Command signature test */ -static int DetectEnipCommandSignatureTest01 (void) +static int DetectEnipCommandSignatureTest01(void) { DetectEngineCtx *de_ctx = DetectEngineCtxInit(); FAIL_IF_NULL(de_ctx); - Signature *sig = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any (enip_command:1; sid:1; rev:1;)"); + Signature *sig = DetectEngineAppendSig( + de_ctx, "alert tcp any any -> any any (enip_command:1; sid:1; rev:1;)"); FAIL_IF_NULL(sig); DetectEngineCtxFree(de_ctx); @@ -440,9 +429,7 @@ static int DetectEnipCommandSignatureTest01 (void) */ static void DetectEnipCommandRegisterTests(void) { - UtRegisterTest("DetectEnipCommandParseTest01", - DetectEnipCommandParseTest01); - UtRegisterTest("DetectEnipCommandSignatureTest01", - DetectEnipCommandSignatureTest01); + UtRegisterTest("DetectEnipCommandParseTest01", DetectEnipCommandParseTest01); + UtRegisterTest("DetectEnipCommandSignatureTest01", DetectEnipCommandSignatureTest01); } #endif /* UNITTESTS */ diff --git a/src/detect-cipservice.h b/src/detect-cipservice.h index 6a9c500cc9fa..964a203ef8ce 100644 --- a/src/detect-cipservice.h +++ b/src/detect-cipservice.h @@ -22,14 +22,13 @@ */ #ifndef _DETECT_CIPSERVICE_H -#define _DETECT_CIPSERVICE_H +#define _DETECT_CIPSERVICE_H /** * CIP Service rule data structure */ -typedef struct DetectCipServiceData_ -{ - uint8_t cipservice; /* cip service type */ +typedef struct DetectCipServiceData_ { + uint8_t cipservice; /* cip service type */ uint16_t cipclass; uint16_t cipattribute; uint8_t matchattribute; /* whether to match on attribute*/ @@ -39,8 +38,7 @@ typedef struct DetectCipServiceData_ /** * ENIP Command rule data structure */ -typedef struct DetectEnipCommandData_ -{ +typedef struct DetectEnipCommandData_ { uint16_t enipcommand; /* enip command */ } DetectEnipCommandData; @@ -50,22 +48,18 @@ void DetectEnipCommandRegister(void); /** * link list node for storing CIP service data */ -typedef struct CIPServiceData_ -{ - uint8_t service; //cip service - union - { - struct - { - uint8_t path_size; //cip path size - uint16_t path_offset; //offset to cip path +typedef struct CIPServiceData_ { + uint8_t service; // cip service + union { + struct { + uint8_t path_size; // cip path size + uint16_t path_offset; // offset to cip path } request; - struct - { + struct { uint8_t status; } response; }; - struct CIPServiceData* next; + struct CIPServiceData *next; } CIPServiceData; -#endif /* _DETECT_CIPSERVICE_H */ +#endif /* _DETECT_CIPSERVICE_H */ diff --git a/src/detect-classtype.c b/src/detect-classtype.c index bec179e72bc8..997ff319ec44 100644 --- a/src/detect-classtype.c +++ b/src/detect-classtype.c @@ -51,7 +51,8 @@ static void DetectClasstypeRegisterTests(void); void DetectClasstypeRegister(void) { sigmatch_table[DETECT_CLASSTYPE].name = "classtype"; - sigmatch_table[DETECT_CLASSTYPE].desc = "information about the classification of rules and alerts"; + sigmatch_table[DETECT_CLASSTYPE].desc = + "information about the classification of rules and alerts"; sigmatch_table[DETECT_CLASSTYPE].url = "/rules/meta.html#classtype"; sigmatch_table[DETECT_CLASSTYPE].Setup = DetectClasstypeSetup; #ifdef UNITTESTS @@ -163,8 +164,7 @@ static int DetectClasstypeSetup(DetectEngineCtx *de_ctx, Signature *s, const cha } char str[256]; - snprintf(str, sizeof(str), - "config classification: %s,Unknown Classtype,%d\n", + snprintf(str, sizeof(str), "config classification: %s,Unknown Classtype,%d\n", parsed_ct_name, DETECT_DEFAULT_PRIO); if (SCClassConfAddClasstype(de_ctx, str, 0) < 0) @@ -215,8 +215,8 @@ static int DetectClasstypeTest01(void) FAIL_IF_NULL(fd); SCClassConfLoadClassificationConfigFile(de_ctx, fd); Signature *s = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any " - "(msg:\"Classtype test\"; " - "Classtype:not_available; sid:1;)"); + "(msg:\"Classtype test\"; " + "Classtype:not_available; sid:1;)"); FAIL_IF_NULL(s); FAIL_IF_NOT(s->prio == 3); @@ -239,29 +239,29 @@ static int DetectClasstypeTest02(void) SCClassConfLoadClassificationConfigFile(de_ctx, fd); Signature *sig = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any " - "(Classtype:bad-unknown; sid:1;)"); + "(Classtype:bad-unknown; sid:1;)"); FAIL_IF_NULL(sig); sig = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any " - "(Classtype:not-there; sid:2;)"); + "(Classtype:not-there; sid:2;)"); FAIL_IF_NULL(sig); sig = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any " - "(Classtype:Bad-UnkNown; sid:3;)"); + "(Classtype:Bad-UnkNown; sid:3;)"); FAIL_IF_NULL(sig); sig = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any " - "(Classtype:nothing-wrong; sid:4;)"); + "(Classtype:nothing-wrong; sid:4;)"); FAIL_IF_NULL(sig); sig = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any " - "(Classtype:attempted_dos; Classtype:bad-unknown; sid:5;)"); + "(Classtype:attempted_dos; Classtype:bad-unknown; sid:5;)"); FAIL_IF_NULL(sig); FAIL_IF_NOT(sig->prio == 2); /* duplicate test */ sig = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any " - "(Classtype:nothing-wrong; Classtype:Bad-UnkNown; sid:6;)"); + "(Classtype:nothing-wrong; Classtype:Bad-UnkNown; sid:6;)"); FAIL_IF_NULL(sig); FAIL_IF_NOT(sig->prio == 2); @@ -282,24 +282,26 @@ static int DetectClasstypeTest03(void) FAIL_IF_NULL(fd); SCClassConfLoadClassificationConfigFile(de_ctx, fd); - Signature *sig = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any " - "(msg:\"Classtype test\"; Classtype:bad-unknown; priority:1; sid:1;)"); + Signature *sig = DetectEngineAppendSig(de_ctx, + "alert tcp any any -> any any " + "(msg:\"Classtype test\"; Classtype:bad-unknown; priority:1; sid:1;)"); FAIL_IF_NULL(sig); FAIL_IF_NOT(sig->prio == 1); sig = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any " - "(msg:\"Classtype test\"; Classtype:unKnoWn; " - "priority:3; sid:2;)"); + "(msg:\"Classtype test\"; Classtype:unKnoWn; " + "priority:3; sid:2;)"); FAIL_IF_NULL(sig); FAIL_IF_NOT(sig->prio == 3); sig = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any (msg:\"Classtype test\"; " - "Classtype:nothing-wrong; priority:1; sid:3;)"); + "Classtype:nothing-wrong; priority:1; sid:3;)"); FAIL_IF_NOT(sig->prio == 1); - sig = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any " - "(msg:\"Classtype test\"; Classtype:bad-unknown; Classtype:undefined; " - "priority:5; sid:4;)"); + sig = DetectEngineAppendSig(de_ctx, + "alert tcp any any -> any any " + "(msg:\"Classtype test\"; Classtype:bad-unknown; Classtype:undefined; " + "priority:5; sid:4;)"); FAIL_IF_NULL(sig); FAIL_IF_NOT(sig->prio == 5); diff --git a/src/detect-classtype.h b/src/detect-classtype.h index 6e0dd509cf48..5a45e2296418 100644 --- a/src/detect-classtype.h +++ b/src/detect-classtype.h @@ -28,4 +28,3 @@ void DetectClasstypeRegister(void); #endif /* __DETECT_CLASSTYPE_H__ */ - diff --git a/src/detect-config.c b/src/detect-config.c index 7ad8c88dca68..7ca23fa5ae0c 100644 --- a/src/detect-config.c +++ b/src/detect-config.c @@ -58,13 +58,15 @@ /** * \brief Regex for parsing our flow options */ -#define PARSE_REGEX "^\\s*([A-z_]+)\\s*\\s*([A-z_]+)\\s*(?:,\\s*([A-z_]+)\\s+([A-z_]+))?\\s*(?:,\\s*([A-z_]+)\\s+([A-z_]+))?$" +#define PARSE_REGEX \ + "^\\s*([A-z_]+)\\s*\\s*([A-z_]+)\\s*(?:,\\s*([A-z_]+)\\s+([A-z_]+))?\\s*(?:,\\s*([A-z_]+)\\s+" \ + "([A-z_]+))?$" static DetectParseRegex parse_regex; -static int DetectConfigPostMatch (DetectEngineThreadCtx *det_ctx, Packet *p, - const Signature *s, const SigMatchCtx *ctx); -static int DetectConfigSetup (DetectEngineCtx *, Signature *, const char *); +static int DetectConfigPostMatch( + DetectEngineThreadCtx *det_ctx, Packet *p, const Signature *s, const SigMatchCtx *ctx); +static int DetectConfigSetup(DetectEngineCtx *, Signature *, const char *); static void DetectConfigFree(DetectEngineCtx *, void *); #ifdef UNITTESTS static void DetectConfigRegisterTests(void); @@ -78,15 +80,14 @@ void DetectConfigRegister(void) sigmatch_table[DETECT_CONFIG].name = "config"; sigmatch_table[DETECT_CONFIG].Match = DetectConfigPostMatch; sigmatch_table[DETECT_CONFIG].Setup = DetectConfigSetup; - sigmatch_table[DETECT_CONFIG].Free = DetectConfigFree; + sigmatch_table[DETECT_CONFIG].Free = DetectConfigFree; #ifdef UNITTESTS sigmatch_table[DETECT_CONFIG].RegisterTests = DetectConfigRegisterTests; #endif DetectSetupParseRegexes(PARSE_REGEX, &parse_regex); } -static void ConfigApplyTx(Flow *f, - const uint64_t tx_id, const DetectConfigData *config) +static void ConfigApplyTx(Flow *f, const uint64_t tx_id, const DetectConfigData *config) { if (f->alstate == NULL) { return; @@ -120,8 +121,7 @@ static void ConfigApplyTx(Flow *f, /** * \brief apply the post match filestore with options */ -static int ConfigApply(DetectEngineThreadCtx *det_ctx, - Packet *p, const DetectConfigData *config) +static int ConfigApply(DetectEngineThreadCtx *det_ctx, Packet *p, const DetectConfigData *config) { bool this_tx = false; bool this_flow = false; @@ -136,7 +136,7 @@ static int ConfigApply(DetectEngineThreadCtx *det_ctx, } if (this_tx) { - SCLogDebug("tx logic here: tx_id %"PRIu64, det_ctx->tx_id); + SCLogDebug("tx logic here: tx_id %" PRIu64, det_ctx->tx_id); ConfigApplyTx(p->flow, det_ctx->tx_id, config); } else if (this_flow) { SCLogDebug("flow logic here"); @@ -145,8 +145,8 @@ static int ConfigApply(DetectEngineThreadCtx *det_ctx, SCReturnInt(0); } -static int DetectConfigPostMatch(DetectEngineThreadCtx *det_ctx, - Packet *p, const Signature *s, const SigMatchCtx *ctx) +static int DetectConfigPostMatch( + DetectEngineThreadCtx *det_ctx, Packet *p, const Signature *s, const SigMatchCtx *ctx) { SCEnter(); const DetectConfigData *config = (const DetectConfigData *)ctx; @@ -165,7 +165,7 @@ static int DetectConfigPostMatch(DetectEngineThreadCtx *det_ctx, * \retval 0 on Success * \retval -1 on Failure */ -static int DetectConfigSetup (DetectEngineCtx *de_ctx, Signature *s, const char *str) +static int DetectConfigSetup(DetectEngineCtx *de_ctx, Signature *s, const char *str) { SCEnter(); @@ -245,7 +245,7 @@ static int DetectConfigSetup (DetectEngineCtx *de_ctx, Signature *s, const char goto error; } - if (!(strcmp(typeval, "tx") == 0 ||strcmp(typeval, "flow") == 0)) { + if (!(strcmp(typeval, "tx") == 0 || strcmp(typeval, "flow") == 0)) { SCLogError("only 'tx' and 'flow' supported at this time"); goto error; } @@ -271,7 +271,7 @@ static int DetectConfigSetup (DetectEngineCtx *de_ctx, Signature *s, const char goto error; } - if (!(strcmp(scopeval, "tx") == 0 ||strcmp(scopeval, "flow") == 0)) { + if (!(strcmp(scopeval, "tx") == 0 || strcmp(scopeval, "flow") == 0)) { SCLogError("only 'tx' and 'flow' supported at this time"); goto error; } @@ -325,11 +325,10 @@ static int DetectConfigTest01(void) DetectEngineCtx *de_ctx = DetectEngineCtxInit(); FAIL_IF(de_ctx == NULL); de_ctx->flags |= DE_QUIET; - Signature *s = DetectEngineAppendSig(de_ctx, - "config dns any any -> any any (" - "dns.query; content:\"common.domain.com\"; " - "config:logging disable, type tx, scope tx; " - "sid:1;)"); + Signature *s = DetectEngineAppendSig(de_ctx, "config dns any any -> any any (" + "dns.query; content:\"common.domain.com\"; " + "config:logging disable, type tx, scope tx; " + "sid:1;)"); FAIL_IF_NULL(s); DetectEngineCtxFree(de_ctx); PASS; diff --git a/src/detect-config.h b/src/detect-config.h index d6948a3f4e29..ed38e8ebfc25 100644 --- a/src/detect-config.h +++ b/src/detect-config.h @@ -33,6 +33,6 @@ typedef struct DetectConfigData_ { } DetectConfigData; /* prototypes */ -void DetectConfigRegister (void); +void DetectConfigRegister(void); #endif /* __DETECT_CONFIG_H__ */ diff --git a/src/detect-content.c b/src/detect-content.c index 54cd2a6c3948..29282dca34d2 100644 --- a/src/detect-content.c +++ b/src/detect-content.c @@ -55,18 +55,18 @@ static void DetectContentRegisterTests(void); #endif -void DetectContentRegister (void) +void DetectContentRegister(void) { sigmatch_table[DETECT_CONTENT].name = "content"; sigmatch_table[DETECT_CONTENT].desc = "match on payload content"; sigmatch_table[DETECT_CONTENT].url = "/rules/payload-keywords.html#content"; sigmatch_table[DETECT_CONTENT].Match = NULL; sigmatch_table[DETECT_CONTENT].Setup = DetectContentSetup; - sigmatch_table[DETECT_CONTENT].Free = DetectContentFree; + sigmatch_table[DETECT_CONTENT].Free = DetectContentFree; #ifdef UNITTESTS sigmatch_table[DETECT_CONTENT].RegisterTests = DetectContentRegisterTests; #endif - sigmatch_table[DETECT_CONTENT].flags = (SIGMATCH_QUOTES_MANDATORY|SIGMATCH_HANDLE_NEGATION); + sigmatch_table[DETECT_CONTENT].flags = (SIGMATCH_QUOTES_MANDATORY | SIGMATCH_HANDLE_NEGATION); } /** @@ -80,8 +80,8 @@ void DetectContentRegister (void) * \retval -1 error * \retval 0 ok */ -int DetectContentDataParse(const char *keyword, const char *contentstr, - uint8_t **pstr, uint16_t *plen) +int DetectContentDataParse( + const char *keyword, const char *contentstr, uint8_t **pstr, uint16_t *plen) { char *str = NULL; size_t slen = 0; @@ -96,7 +96,7 @@ int DetectContentDataParse(const char *keyword, const char *contentstr, SCLogDebug("\"%s\", len %" PRIuMAX, str, (uintmax_t)slen); - //SCLogDebug("DetectContentParse: \"%s\", len %" PRIu32 "", str, len); + // SCLogDebug("DetectContentParse: \"%s\", len %" PRIu32 "", str, len); char converted = 0; { @@ -121,25 +121,21 @@ int DetectContentDataParse(const char *keyword, const char *contentstr, } else { bin = 1; } - } else if(!escape && str[i] == '\\') { + } else if (!escape && str[i] == '\\') { escape = 1; } else { if (bin) { - if (isdigit((unsigned char)str[i]) || - str[i] == 'A' || str[i] == 'a' || - str[i] == 'B' || str[i] == 'b' || - str[i] == 'C' || str[i] == 'c' || - str[i] == 'D' || str[i] == 'd' || - str[i] == 'E' || str[i] == 'e' || - str[i] == 'F' || str[i] == 'f') - { + if (isdigit((unsigned char)str[i]) || str[i] == 'A' || str[i] == 'a' || + str[i] == 'B' || str[i] == 'b' || str[i] == 'C' || str[i] == 'c' || + str[i] == 'D' || str[i] == 'd' || str[i] == 'E' || str[i] == 'e' || + str[i] == 'F' || str[i] == 'f') { // SCLogDebug("part of binary: %c", str[i]); binstr[binpos] = (char)str[i]; binpos++; if (binpos == 2) { - uint8_t c = strtol((char *)binstr, (char **) NULL, 16) & 0xFF; + uint8_t c = strtol((char *)binstr, (char **)NULL, 16) & 0xFF; binpos = 0; str[x] = c; x++; @@ -147,19 +143,14 @@ int DetectContentDataParse(const char *keyword, const char *contentstr, } } else if (str[i] == ' ') { // SCLogDebug("space as part of binary string"); - } - else if (str[i] != ',') { + } else if (str[i] != ',') { SCLogError("Invalid hex code in " "content - %s, hex %c. Invalidating signature.", contentstr, str[i]); goto error; } } else if (escape) { - if (str[i] == ':' || - str[i] == ';' || - str[i] == '\\' || - str[i] == '\"') - { + if (str[i] == ':' || str[i] == ';' || str[i] == '\\' || str[i] == '\"') { str[x] = str[i]; x++; } else { @@ -208,8 +199,8 @@ int DetectContentDataParse(const char *keyword, const char *contentstr, * \brief DetectContentParse * \initonly */ -DetectContentData *DetectContentParse(SpmGlobalThreadCtx *spm_global_thread_ctx, - const char *contentstr) +DetectContentData *DetectContentParse( + SpmGlobalThreadCtx *spm_global_thread_ctx, const char *contentstr) { DetectContentData *cd = NULL; uint8_t *content = NULL; @@ -232,8 +223,7 @@ DetectContentData *DetectContentParse(SpmGlobalThreadCtx *spm_global_thread_ctx, cd->content_len = len; /* Prepare SPM search context. */ - cd->spm_ctx = SpmInitCtx(cd->content, cd->content_len, 0, - spm_global_thread_ctx); + cd->spm_ctx = SpmInitCtx(cd->content, cd->content_len, 0, spm_global_thread_ctx); if (cd->spm_ctx == NULL) { SCFree(content); SCFree(cd); @@ -247,11 +237,10 @@ DetectContentData *DetectContentParse(SpmGlobalThreadCtx *spm_global_thread_ctx, SCFree(content); return cd; - } -DetectContentData *DetectContentParseEncloseQuotes(SpmGlobalThreadCtx *spm_global_thread_ctx, - const char *contentstr) +DetectContentData *DetectContentParseEncloseQuotes( + SpmGlobalThreadCtx *spm_global_thread_ctx, const char *contentstr) { return DetectContentParse(spm_global_thread_ctx, contentstr); } @@ -283,15 +272,16 @@ void DetectContentPrint(DetectContentData *cd) SCLogDebug("%c", cd->content[i]); } - SCLogDebug("Content_id: %"PRIu32, cd->id); - SCLogDebug("Content_len: %"PRIu16, cd->content_len); - SCLogDebug("Depth: %"PRIu16, cd->depth); - SCLogDebug("Offset: %"PRIu16, cd->offset); - SCLogDebug("Within: %"PRIi32, cd->within); - SCLogDebug("Distance: %"PRIi32, cd->distance); + SCLogDebug("Content_id: %" PRIu32, cd->id); + SCLogDebug("Content_len: %" PRIu16, cd->content_len); + SCLogDebug("Depth: %" PRIu16, cd->depth); + SCLogDebug("Offset: %" PRIu16, cd->offset); + SCLogDebug("Within: %" PRIi32, cd->within); + SCLogDebug("Distance: %" PRIi32, cd->distance); SCLogDebug("flags: %u ", cd->flags); SCLogDebug("negated: %s ", cd->flags & DETECT_CONTENT_NEGATED ? "true" : "false"); - SCLogDebug("relative match next: %s ", cd->flags & DETECT_CONTENT_RELATIVE_NEXT ? "true" : "false"); + SCLogDebug("relative match next: %s ", + cd->flags & DETECT_CONTENT_RELATIVE_NEXT ? "true" : "false"); if (cd->replace && cd->replace_len) { char *tmprstr = SCMalloc(sizeof(char) * cd->replace_len + 1); @@ -342,8 +332,7 @@ int DetectContentSetup(DetectEngineCtx *de_ctx, Signature *s, const char *conten int sm_list = s->init_data->list; if (sm_list == DETECT_SM_LIST_NOTSET) { sm_list = DETECT_SM_LIST_PMATCH; - } else if (sm_list > DETECT_SM_LIST_MAX && - 0 == (cd->flags & DETECT_CONTENT_NEGATED)) { + } else if (sm_list > DETECT_SM_LIST_MAX && 0 == (cd->flags & DETECT_CONTENT_NEGATED)) { /* Check transform compatibility */ const char *tstr; if (!DetectEngineBufferTypeValidateTransform( @@ -817,8 +806,7 @@ static bool TestLastContent(const Signature *s, uint16_t o, uint16_t d) DetectEngineCtxFree(de_ctx); \ } -#define TEST_DONE \ - PASS +#define TEST_DONE PASS /** \test test propagation of depth/offset/distance/within */ static int DetectContentDepthTest01(void) @@ -837,37 +825,62 @@ static int DetectContentDepthTest01(void) TEST_RUN("content:\"abc\"; depth:6; content:\"xyz\"; distance:0; within:3; ", 3, 9); // multiple relative matches after anchored content - TEST_RUN("content:\"abc\"; depth:3; content:\"klm\"; distance:0; within:3; content:\"xyz\"; distance:0; within:3; ", 6, 9); + TEST_RUN("content:\"abc\"; depth:3; content:\"klm\"; distance:0; within:3; content:\"xyz\"; " + "distance:0; within:3; ", + 6, 9); // test 'reset' due to unanchored content - TEST_RUN("content:\"abc\"; depth:3; content:\"klm\"; content:\"xyz\"; distance:0; within:3; ", 3, 0); + TEST_RUN("content:\"abc\"; depth:3; content:\"klm\"; content:\"xyz\"; distance:0; within:3; ", + 3, 0); // test 'reset' due to unanchored pcre - TEST_RUN("content:\"abc\"; depth:3; pcre:/\"klm\"/; content:\"xyz\"; distance:0; within:3; ", 0, 0); + TEST_RUN("content:\"abc\"; depth:3; pcre:/\"klm\"/; content:\"xyz\"; distance:0; within:3; ", 0, + 0); // test relative pcre. We can use previous offset+pattern len - TEST_RUN("content:\"abc\"; depth:3; pcre:/\"klm\"/R; content:\"xyz\"; distance:0; within:3; ", 3, 0); - TEST_RUN("content:\"abc\"; offset:3; depth:3; pcre:/\"klm\"/R; content:\"xyz\"; distance:0; within:3; ", 6, 0); + TEST_RUN("content:\"abc\"; depth:3; pcre:/\"klm\"/R; content:\"xyz\"; distance:0; within:3; ", + 3, 0); + TEST_RUN("content:\"abc\"; offset:3; depth:3; pcre:/\"klm\"/R; content:\"xyz\"; distance:0; " + "within:3; ", + 6, 0); - TEST_RUN("content:\"abc\"; depth:3; content:\"klm\"; within:3; content:\"xyz\"; within:3; ", 0, 9); + TEST_RUN("content:\"abc\"; depth:3; content:\"klm\"; within:3; content:\"xyz\"; within:3; ", 0, + 9); - TEST_RUN("content:\"abc\"; depth:3; content:\"klm\"; distance:0; content:\"xyz\"; distance:0; ", 6, 0); + TEST_RUN("content:\"abc\"; depth:3; content:\"klm\"; distance:0; content:\"xyz\"; distance:0; ", + 6, 0); // tests to see if anchored 'ends_with' is applied to other content as depth TEST_RUN("content:\"abc\"; depth:6; isdataat:!1,relative; content:\"klm\";", 0, 6); - TEST_RUN("content:\"abc\"; depth:3; content:\"klm\"; within:3; content:\"xyz\"; within:3; isdataat:!1,relative; content:\"def\"; ", 0, 9); + TEST_RUN("content:\"abc\"; depth:3; content:\"klm\"; within:3; content:\"xyz\"; within:3; " + "isdataat:!1,relative; content:\"def\"; ", + 0, 9); TEST_RUN("content:\"|03|\"; depth:1; content:\"|e0|\"; distance:4; within:1;", 5, 6); - TEST_RUN("content:\"|03|\"; depth:1; content:\"|e0|\"; distance:4; within:1; content:\"Cookie|3a|\"; distance:5; within:7;", 11, 18); + TEST_RUN("content:\"|03|\"; depth:1; content:\"|e0|\"; distance:4; within:1; " + "content:\"Cookie|3a|\"; distance:5; within:7;", + 11, 18); - TEST_RUN("content:\"this\"; content:\"is\"; within:6; content:\"big\"; within:8; content:\"string\"; within:8;", 0, 0); + TEST_RUN("content:\"this\"; content:\"is\"; within:6; content:\"big\"; within:8; " + "content:\"string\"; within:8;", + 0, 0); - TEST_RUN("dsize:<80; content:!\"|00 22 02 00|\"; depth: 4; content:\"|00 00 04|\"; distance:8; within:3; content:\"|00 00 00 00 00|\"; distance:6; within:5;", 17, 80); - TEST_RUN("content:!\"|00 22 02 00|\"; depth: 4; content:\"|00 00 04|\"; distance:8; within:3; content:\"|00 00 00 00 00|\"; distance:6; within:5;", 17, 0); + TEST_RUN("dsize:<80; content:!\"|00 22 02 00|\"; depth: 4; content:\"|00 00 04|\"; distance:8; " + "within:3; content:\"|00 00 00 00 00|\"; distance:6; within:5;", + 17, 80); + TEST_RUN("content:!\"|00 22 02 00|\"; depth: 4; content:\"|00 00 04|\"; distance:8; within:3; " + "content:\"|00 00 00 00 00|\"; distance:6; within:5;", + 17, 0); TEST_RUN("content:\"|0d 0a 0d 0a|\"; content:\"code=\"; distance:0;", 4, 0); - TEST_RUN("content:\"|0d 0a 0d 0a|\"; content:\"code=\"; distance:0; content:\"xploit.class\"; distance:2; within:18;", 11, 0); + TEST_RUN("content:\"|0d 0a 0d 0a|\"; content:\"code=\"; distance:0; content:\"xploit.class\"; " + "distance:2; within:18;", + 11, 0); TEST_RUN("content:\"|16 03|\"; depth:2; content:\"|55 04 0a|\"; distance:0;", 2, 0); - TEST_RUN("content:\"|16 03|\"; depth:2; content:\"|55 04 0a|\"; distance:0; content:\"|0d|LogMeIn, Inc.\"; distance:1; within:14;", 6, 0); - TEST_RUN("content:\"|16 03|\"; depth:2; content:\"|55 04 0a|\"; distance:0; content:\"|0d|LogMeIn, Inc.\"; distance:1; within:14; content:\".app\";", 0, 0); + TEST_RUN("content:\"|16 03|\"; depth:2; content:\"|55 04 0a|\"; distance:0; " + "content:\"|0d|LogMeIn, Inc.\"; distance:1; within:14;", + 6, 0); + TEST_RUN("content:\"|16 03|\"; depth:2; content:\"|55 04 0a|\"; distance:0; " + "content:\"|0d|LogMeIn, Inc.\"; distance:1; within:14; content:\".app\";", + 0, 0); TEST_RUN("content:\"=\"; offset:4; depth:9;", 4, 13); // low end: offset 4 + patlen 1 = 5. So 5 + distance 55 = 60. @@ -909,11 +922,11 @@ static void DetectContentPrintAll(SigMatch *sm) SigMatch *first_sm = sm; - /* Print all of them */ + /* Print all of them */ for (; first_sm != NULL; first_sm = first_sm->next) { if (first_sm->type == DETECT_CONTENT) { SCLogDebug("Printing SigMatch DETECT_CONTENT %d", ++i); - DetectContentPrint((DetectContentData*)first_sm->ctx); + DetectContentPrint((DetectContentData *)first_sm->ctx); } } } @@ -926,7 +939,7 @@ static int g_dce_stub_data_buffer_id = 0; /** * \test DetectContentParseTest01 this is a test to make sure we can deal with escaped colons */ -static int DetectContentParseTest01 (void) +static int DetectContentParseTest01(void) { int result = 1; DetectContentData *cd = NULL; @@ -941,7 +954,7 @@ static int DetectContentParseTest01 (void) if (cd != NULL) { if (memcmp(cd->content, teststringparsed, strlen(teststringparsed)) != 0) { SCLogDebug("expected %s got ", teststringparsed); - PrintRawUriFp(stdout,cd->content,cd->content_len); + PrintRawUriFp(stdout, cd->content, cd->content_len); SCLogDebug(": "); result = 0; DetectContentFree(NULL, cd); @@ -957,7 +970,7 @@ static int DetectContentParseTest01 (void) /** * \test DetectContentParseTest02 this is a test to make sure we can deal with escaped semi-colons */ -static int DetectContentParseTest02 (void) +static int DetectContentParseTest02(void) { int result = 1; DetectContentData *cd = NULL; @@ -972,7 +985,7 @@ static int DetectContentParseTest02 (void) if (cd != NULL) { if (memcmp(cd->content, teststringparsed, strlen(teststringparsed)) != 0) { SCLogDebug("expected %s got ", teststringparsed); - PrintRawUriFp(stdout,cd->content,cd->content_len); + PrintRawUriFp(stdout, cd->content, cd->content_len); SCLogDebug(": "); result = 0; DetectContentFree(NULL, cd); @@ -988,7 +1001,7 @@ static int DetectContentParseTest02 (void) /** * \test DetectContentParseTest03 this is a test to make sure we can deal with escaped double-quotes */ -static int DetectContentParseTest03 (void) +static int DetectContentParseTest03(void) { int result = 1; DetectContentData *cd = NULL; @@ -1003,7 +1016,7 @@ static int DetectContentParseTest03 (void) if (cd != NULL) { if (memcmp(cd->content, teststringparsed, strlen(teststringparsed)) != 0) { SCLogDebug("expected %s got ", teststringparsed); - PrintRawUriFp(stdout,cd->content,cd->content_len); + PrintRawUriFp(stdout, cd->content, cd->content_len); SCLogDebug(": "); result = 0; DetectContentFree(NULL, cd); @@ -1019,7 +1032,7 @@ static int DetectContentParseTest03 (void) /** * \test DetectContentParseTest04 this is a test to make sure we can deal with escaped backslashes */ -static int DetectContentParseTest04 (void) +static int DetectContentParseTest04(void) { int result = 1; DetectContentData *cd = NULL; @@ -1035,7 +1048,7 @@ static int DetectContentParseTest04 (void) uint16_t len = (cd->content_len > strlen(teststringparsed)); if (memcmp(cd->content, teststringparsed, len) != 0) { SCLogDebug("expected %s got ", teststringparsed); - PrintRawUriFp(stdout,cd->content,cd->content_len); + PrintRawUriFp(stdout, cd->content, cd->content_len); SCLogDebug(": "); result = 0; DetectContentFree(NULL, cd); @@ -1051,7 +1064,7 @@ static int DetectContentParseTest04 (void) /** * \test DetectContentParseTest05 test illegal escape */ -static int DetectContentParseTest05 (void) +static int DetectContentParseTest05(void) { int result = 1; DetectContentData *cd = NULL; @@ -1064,7 +1077,7 @@ static int DetectContentParseTest05 (void) cd = DetectContentParse(spm_global_thread_ctx, teststring); if (cd != NULL) { SCLogDebug("expected NULL got "); - PrintRawUriFp(stdout,cd->content,cd->content_len); + PrintRawUriFp(stdout, cd->content, cd->content_len); SCLogDebug(": "); result = 0; DetectContentFree(NULL, cd); @@ -1076,7 +1089,7 @@ static int DetectContentParseTest05 (void) /** * \test DetectContentParseTest06 test a binary content */ -static int DetectContentParseTest06 (void) +static int DetectContentParseTest06(void) { int result = 1; DetectContentData *cd = NULL; @@ -1092,7 +1105,7 @@ static int DetectContentParseTest06 (void) uint16_t len = (cd->content_len > strlen(teststringparsed)); if (memcmp(cd->content, teststringparsed, len) != 0) { SCLogDebug("expected %s got ", teststringparsed); - PrintRawUriFp(stdout,cd->content,cd->content_len); + PrintRawUriFp(stdout, cd->content, cd->content_len); SCLogDebug(": "); result = 0; DetectContentFree(NULL, cd); @@ -1108,7 +1121,7 @@ static int DetectContentParseTest06 (void) /** * \test DetectContentParseTest07 test an empty content */ -static int DetectContentParseTest07 (void) +static int DetectContentParseTest07(void) { int result = 1; DetectContentData *cd = NULL; @@ -1131,7 +1144,7 @@ static int DetectContentParseTest07 (void) /** * \test DetectContentParseTest08 test an empty content */ -static int DetectContentParseTest08 (void) +static int DetectContentParseTest08(void) { int result = 1; DetectContentData *cd = NULL; @@ -1160,8 +1173,8 @@ static int DetectContentParseTest08 (void) * \retval return 1 if match * \retval return 0 if not */ -static int DetectContentLongPatternMatchTest(uint8_t *raw_eth_pkt, uint16_t pktsize, const char *sig, - uint32_t sid) +static int DetectContentLongPatternMatchTest( + uint8_t *raw_eth_pkt, uint16_t pktsize, const char *sig, uint32_t sid) { Packet *p = PacketGetFromAlloc(); FAIL_IF_NULL(p); @@ -2655,13 +2668,13 @@ static int SigTest77TestBug139(void) 0x52, 0x24, 0x82, 0x00, 0x00, 0x00, 0x00, 0x00, 0x24, 0x34 }; // clang-format on uint16_t buflen = sizeof(buf); - Packet *p = UTHBuildPacket( buf, buflen, IPPROTO_UDP); + Packet *p = UTHBuildPacket(buf, buflen, IPPROTO_UDP); int result = 0; p->dp = 53; char sig[] = "alert udp any any -> any 53 (msg:\"dns testing\";" - " content:\"|00 00|\"; depth:5; offset:13; sid:9436601;" - " rev:1;)"; + " content:\"|00 00|\"; depth:5; offset:13; sid:9436601;" + " rev:1;)"; if (UTHPacketMatchSigMpm(p, sig, MPM_AC) == 0) { result = 0; goto end; @@ -2677,110 +2690,69 @@ static int SigTest77TestBug139(void) static int DetectLongContentTestCommon(const char *sig, uint32_t sid) { /* Packet with 512 A's in it for testing long content. */ - static uint8_t pkt[739] = { - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x45, 0x00, - 0x02, 0xd5, 0x4a, 0x18, 0x40, 0x00, 0x40, 0x06, - 0xd7, 0xd6, 0x0a, 0x10, 0x01, 0x0b, 0x0a, 0x10, - 0x01, 0x0a, 0xdb, 0x36, 0x00, 0x50, 0xca, 0xc5, - 0xcc, 0xd1, 0x95, 0x77, 0x0f, 0x7d, 0x80, 0x18, - 0x00, 0xe5, 0x77, 0x9d, 0x00, 0x00, 0x01, 0x01, - 0x08, 0x0a, 0x1d, 0xe0, 0x86, 0xc6, 0xfc, 0x73, - 0x49, 0xf3, 0x50, 0x4f, 0x53, 0x54, 0x20, 0x2f, - 0x20, 0x48, 0x54, 0x54, 0x50, 0x2f, 0x31, 0x2e, - 0x31, 0x0d, 0x0a, 0x55, 0x73, 0x65, 0x72, 0x2d, - 0x41, 0x67, 0x65, 0x6e, 0x74, 0x3a, 0x20, 0x63, - 0x75, 0x72, 0x6c, 0x2f, 0x37, 0x2e, 0x33, 0x37, - 0x2e, 0x30, 0x0d, 0x0a, 0x48, 0x6f, 0x73, 0x74, - 0x3a, 0x20, 0x31, 0x30, 0x2e, 0x31, 0x36, 0x2e, - 0x31, 0x2e, 0x31, 0x30, 0x0d, 0x0a, 0x41, 0x63, - 0x63, 0x65, 0x70, 0x74, 0x3a, 0x20, 0x2a, 0x2f, - 0x2a, 0x0d, 0x0a, 0x43, 0x6f, 0x6e, 0x74, 0x65, - 0x6e, 0x74, 0x2d, 0x4c, 0x65, 0x6e, 0x67, 0x74, - 0x68, 0x3a, 0x20, 0x35, 0x32, 0x38, 0x0d, 0x0a, - 0x43, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2d, - 0x54, 0x79, 0x70, 0x65, 0x3a, 0x20, 0x61, 0x70, - 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, - 0x6e, 0x2f, 0x78, 0x2d, 0x77, 0x77, 0x77, 0x2d, - 0x66, 0x6f, 0x72, 0x6d, 0x2d, 0x75, 0x72, 0x6c, - 0x65, 0x6e, 0x63, 0x6f, 0x64, 0x65, 0x64, 0x0d, - 0x0a, 0x0d, 0x0a, 0x58, 0x58, 0x58, 0x58, 0x58, - 0x58, 0x58, 0x58, 0x41, 0x41, 0x41, 0x41, 0x41, - 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, - 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, - 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, - 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, - 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, - 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, - 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, - 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, - 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, - 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, - 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, - 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, - 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, - 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, - 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, - 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, - 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, - 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, - 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, - 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, - 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, - 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, - 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, - 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, - 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, - 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, - 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, - 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, - 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, - 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, - 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, - 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, - 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, - 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, - 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, - 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, - 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, - 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, - 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, - 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, - 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, - 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, - 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, - 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, - 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, - 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, - 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, - 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, - 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, - 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, - 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, - 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, - 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, - 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, - 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, - 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, - 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, - 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, - 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, - 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, - 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, - 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, - 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, - 0x41, 0x41, 0x41, 0x58, 0x58, 0x58, 0x58, 0x58, - 0x58, 0x58, 0x58 - }; - - return DetectContentLongPatternMatchTest(pkt, (uint16_t)sizeof(pkt), sig, - sid); + static uint8_t pkt[739] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x08, 0x00, 0x45, 0x00, 0x02, 0xd5, 0x4a, 0x18, 0x40, 0x00, 0x40, 0x06, 0xd7, 0xd6, + 0x0a, 0x10, 0x01, 0x0b, 0x0a, 0x10, 0x01, 0x0a, 0xdb, 0x36, 0x00, 0x50, 0xca, 0xc5, 0xcc, + 0xd1, 0x95, 0x77, 0x0f, 0x7d, 0x80, 0x18, 0x00, 0xe5, 0x77, 0x9d, 0x00, 0x00, 0x01, 0x01, + 0x08, 0x0a, 0x1d, 0xe0, 0x86, 0xc6, 0xfc, 0x73, 0x49, 0xf3, 0x50, 0x4f, 0x53, 0x54, 0x20, + 0x2f, 0x20, 0x48, 0x54, 0x54, 0x50, 0x2f, 0x31, 0x2e, 0x31, 0x0d, 0x0a, 0x55, 0x73, 0x65, + 0x72, 0x2d, 0x41, 0x67, 0x65, 0x6e, 0x74, 0x3a, 0x20, 0x63, 0x75, 0x72, 0x6c, 0x2f, 0x37, + 0x2e, 0x33, 0x37, 0x2e, 0x30, 0x0d, 0x0a, 0x48, 0x6f, 0x73, 0x74, 0x3a, 0x20, 0x31, 0x30, + 0x2e, 0x31, 0x36, 0x2e, 0x31, 0x2e, 0x31, 0x30, 0x0d, 0x0a, 0x41, 0x63, 0x63, 0x65, 0x70, + 0x74, 0x3a, 0x20, 0x2a, 0x2f, 0x2a, 0x0d, 0x0a, 0x43, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, + 0x2d, 0x4c, 0x65, 0x6e, 0x67, 0x74, 0x68, 0x3a, 0x20, 0x35, 0x32, 0x38, 0x0d, 0x0a, 0x43, + 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2d, 0x54, 0x79, 0x70, 0x65, 0x3a, 0x20, 0x61, 0x70, + 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2f, 0x78, 0x2d, 0x77, 0x77, 0x77, + 0x2d, 0x66, 0x6f, 0x72, 0x6d, 0x2d, 0x75, 0x72, 0x6c, 0x65, 0x6e, 0x63, 0x6f, 0x64, 0x65, + 0x64, 0x0d, 0x0a, 0x0d, 0x0a, 0x58, 0x58, 0x58, 0x58, 0x58, 0x58, 0x58, 0x58, 0x41, 0x41, + 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, + 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, + 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, + 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, + 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, + 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, + 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, + 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, + 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, + 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, + 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, + 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, + 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, + 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, + 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, + 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, + 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, + 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, + 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, + 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, + 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, + 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, + 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, + 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, + 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, + 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, + 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, + 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, + 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, + 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, + 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, + 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, + 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, + 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, + 0x58, 0x58, 0x58, 0x58, 0x58, 0x58, 0x58, 0x58 }; + + return DetectContentLongPatternMatchTest(pkt, (uint16_t)sizeof(pkt), sig, sid); } static int DetectLongContentTest1(void) { /* Signature with 256 A's. */ - const char *sig = "alert tcp any any -> any any (msg:\"Test Rule\"; content:\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"; sid:1;)"; + const char *sig = "alert tcp any any -> any any (msg:\"Test Rule\"; " + "content:" + "\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"; sid:1;)"; return DetectLongContentTestCommon(sig, 1); } @@ -2788,7 +2760,15 @@ static int DetectLongContentTest1(void) static int DetectLongContentTest2(void) { /* Signature with 512 A's. */ - const char *sig = "alert tcp any any -> any any (msg:\"Test Rule\"; content:\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"; sid:1;)"; + const char *sig = "alert tcp any any -> any any (msg:\"Test Rule\"; " + "content:" + "\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"; sid:1;)"; return DetectLongContentTestCommon(sig, 1); } @@ -2796,7 +2776,15 @@ static int DetectLongContentTest2(void) static int DetectLongContentTest3(void) { /* Signature with 513 A's. */ - const char *sig = "alert tcp any any -> any any (msg:\"Test Rule\"; content:\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"; sid:1;)"; + const char *sig = "alert tcp any any -> any any (msg:\"Test Rule\"; " + "content:" + "\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"; sid:1;)"; return !DetectLongContentTestCommon(sig, 1); } @@ -2865,33 +2853,21 @@ static void DetectContentRegisterTests(void) UtRegisterTest("DetectContentParseTest45", DetectContentParseTest45); /* The reals */ - UtRegisterTest("DetectContentLongPatternMatchTest01", - DetectContentLongPatternMatchTest01); - UtRegisterTest("DetectContentLongPatternMatchTest02", - DetectContentLongPatternMatchTest02); - UtRegisterTest("DetectContentLongPatternMatchTest03", - DetectContentLongPatternMatchTest03); - UtRegisterTest("DetectContentLongPatternMatchTest04", - DetectContentLongPatternMatchTest04); - UtRegisterTest("DetectContentLongPatternMatchTest05", - DetectContentLongPatternMatchTest05); - UtRegisterTest("DetectContentLongPatternMatchTest06", - DetectContentLongPatternMatchTest06); - UtRegisterTest("DetectContentLongPatternMatchTest07", - DetectContentLongPatternMatchTest07); - UtRegisterTest("DetectContentLongPatternMatchTest08", - DetectContentLongPatternMatchTest08); - UtRegisterTest("DetectContentLongPatternMatchTest09", - DetectContentLongPatternMatchTest09); - UtRegisterTest("DetectContentLongPatternMatchTest10", - DetectContentLongPatternMatchTest10); - UtRegisterTest("DetectContentLongPatternMatchTest11", - DetectContentLongPatternMatchTest11); + UtRegisterTest("DetectContentLongPatternMatchTest01", DetectContentLongPatternMatchTest01); + UtRegisterTest("DetectContentLongPatternMatchTest02", DetectContentLongPatternMatchTest02); + UtRegisterTest("DetectContentLongPatternMatchTest03", DetectContentLongPatternMatchTest03); + UtRegisterTest("DetectContentLongPatternMatchTest04", DetectContentLongPatternMatchTest04); + UtRegisterTest("DetectContentLongPatternMatchTest05", DetectContentLongPatternMatchTest05); + UtRegisterTest("DetectContentLongPatternMatchTest06", DetectContentLongPatternMatchTest06); + UtRegisterTest("DetectContentLongPatternMatchTest07", DetectContentLongPatternMatchTest07); + UtRegisterTest("DetectContentLongPatternMatchTest08", DetectContentLongPatternMatchTest08); + UtRegisterTest("DetectContentLongPatternMatchTest09", DetectContentLongPatternMatchTest09); + UtRegisterTest("DetectContentLongPatternMatchTest10", DetectContentLongPatternMatchTest10); + UtRegisterTest("DetectContentLongPatternMatchTest11", DetectContentLongPatternMatchTest11); /* Negated content tests */ UtRegisterTest("SigTest41TestNegatedContent", SigTest41TestNegatedContent); - UtRegisterTest("SigTest41aTestNegatedContent", - SigTest41aTestNegatedContent); + UtRegisterTest("SigTest41aTestNegatedContent", SigTest41aTestNegatedContent); UtRegisterTest("SigTest42TestNegatedContent", SigTest42TestNegatedContent); UtRegisterTest("SigTest43TestNegatedContent", SigTest43TestNegatedContent); UtRegisterTest("SigTest44TestNegatedContent", SigTest44TestNegatedContent); diff --git a/src/detect-content.h b/src/detect-content.h index bc47562a96f8..74482fb21eb3 100644 --- a/src/detect-content.h +++ b/src/detect-content.h @@ -35,52 +35,49 @@ #define DETECT_CONTENT_FAST_PATTERN_ONLY BIT_U32(6) #define DETECT_CONTENT_FAST_PATTERN_CHOP BIT_U32(7) /** content applies to a "raw"/undecoded field if applicable */ -#define DETECT_CONTENT_RAWBYTES BIT_U32(8) +#define DETECT_CONTENT_RAWBYTES BIT_U32(8) /** content is negated */ -#define DETECT_CONTENT_NEGATED BIT_U32(9) +#define DETECT_CONTENT_NEGATED BIT_U32(9) -#define DETECT_CONTENT_ENDS_WITH BIT_U32(10) +#define DETECT_CONTENT_ENDS_WITH BIT_U32(10) /* BE - byte extract */ -#define DETECT_CONTENT_OFFSET_VAR BIT_U32(11) -#define DETECT_CONTENT_DEPTH_VAR BIT_U32(12) -#define DETECT_CONTENT_DISTANCE_VAR BIT_U32(13) -#define DETECT_CONTENT_WITHIN_VAR BIT_U32(14) +#define DETECT_CONTENT_OFFSET_VAR BIT_U32(11) +#define DETECT_CONTENT_DEPTH_VAR BIT_U32(12) +#define DETECT_CONTENT_DISTANCE_VAR BIT_U32(13) +#define DETECT_CONTENT_WITHIN_VAR BIT_U32(14) /* replace data */ -#define DETECT_CONTENT_REPLACE BIT_U32(15) +#define DETECT_CONTENT_REPLACE BIT_U32(15) /* this flag is set during the staging phase. It indicates that a content * has been added to the mpm phase and requires no further inspection inside * the inspection phase */ #define DETECT_CONTENT_NO_DOUBLE_INSPECTION_REQUIRED BIT_U32(16) -#define DETECT_CONTENT_WITHIN_NEXT BIT_U32(17) -#define DETECT_CONTENT_DISTANCE_NEXT BIT_U32(18) -#define DETECT_CONTENT_STARTS_WITH BIT_U32(19) +#define DETECT_CONTENT_WITHIN_NEXT BIT_U32(17) +#define DETECT_CONTENT_DISTANCE_NEXT BIT_U32(18) +#define DETECT_CONTENT_STARTS_WITH BIT_U32(19) /** MPM pattern selected by the engine or forced by fast_pattern keyword */ -#define DETECT_CONTENT_MPM BIT_U32(20) -#define DETECT_CONTENT_WITHIN2DEPTH BIT_U32(21) -#define DETECT_CONTENT_DISTANCE2OFFSET BIT_U32(22) +#define DETECT_CONTENT_MPM BIT_U32(20) +#define DETECT_CONTENT_WITHIN2DEPTH BIT_U32(21) +#define DETECT_CONTENT_DISTANCE2OFFSET BIT_U32(22) /** a relative match to this content is next, used in matching phase */ -#define DETECT_CONTENT_RELATIVE_NEXT (DETECT_CONTENT_WITHIN_NEXT|DETECT_CONTENT_DISTANCE_NEXT) +#define DETECT_CONTENT_RELATIVE_NEXT (DETECT_CONTENT_WITHIN_NEXT | DETECT_CONTENT_DISTANCE_NEXT) -#define DETECT_CONTENT_IS_SINGLE(c) (!( ((c)->flags & DETECT_CONTENT_DISTANCE) || \ - ((c)->flags & DETECT_CONTENT_WITHIN) || \ - ((c)->flags & DETECT_CONTENT_RELATIVE_NEXT) || \ - ((c)->flags & DETECT_CONTENT_DEPTH) || \ - ((c)->flags & DETECT_CONTENT_OFFSET) )) +#define DETECT_CONTENT_IS_SINGLE(c) \ + (!(((c)->flags & DETECT_CONTENT_DISTANCE) || ((c)->flags & DETECT_CONTENT_WITHIN) || \ + ((c)->flags & DETECT_CONTENT_RELATIVE_NEXT) || ((c)->flags & DETECT_CONTENT_DEPTH) || \ + ((c)->flags & DETECT_CONTENT_OFFSET))) /* if a pattern has no depth/offset limits, no relative specifiers and isn't * chopped for the mpm, we can take the mpm and consider this pattern a match * w/o further inspection. Warning: this may still mean other patterns depend * on this pattern that force match validation anyway. */ -#define DETECT_CONTENT_MPM_IS_CONCLUSIVE(c) \ - !( ((c)->flags & DETECT_CONTENT_DISTANCE) || \ - ((c)->flags & DETECT_CONTENT_WITHIN) || \ - ((c)->flags & DETECT_CONTENT_DEPTH) || \ - ((c)->flags & DETECT_CONTENT_OFFSET) || \ - ((c)->flags & DETECT_CONTENT_FAST_PATTERN_CHOP)) +#define DETECT_CONTENT_MPM_IS_CONCLUSIVE(c) \ + !(((c)->flags & DETECT_CONTENT_DISTANCE) || ((c)->flags & DETECT_CONTENT_WITHIN) || \ + ((c)->flags & DETECT_CONTENT_DEPTH) || ((c)->flags & DETECT_CONTENT_OFFSET) || \ + ((c)->flags & DETECT_CONTENT_FAST_PATTERN_CHOP)) /* * Values for distance, and within must be less than or equal @@ -115,12 +112,12 @@ typedef struct DetectContentData_ { /* prototypes */ void DetectContentRegister(void); -DetectContentData *DetectContentParse(SpmGlobalThreadCtx *spm_global_thread_ctx, - const char *contentstr); -int DetectContentDataParse(const char *keyword, const char *contentstr, - uint8_t **pstr, uint16_t *plen); -DetectContentData *DetectContentParseEncloseQuotes(SpmGlobalThreadCtx *spm_global_thread_ctx, - const char *contentstr); +DetectContentData *DetectContentParse( + SpmGlobalThreadCtx *spm_global_thread_ctx, const char *contentstr); +int DetectContentDataParse( + const char *keyword, const char *contentstr, uint8_t **pstr, uint16_t *plen); +DetectContentData *DetectContentParseEncloseQuotes( + SpmGlobalThreadCtx *spm_global_thread_ctx, const char *contentstr); int DetectContentSetup(DetectEngineCtx *de_ctx, Signature *s, const char *contentstr); void DetectContentPrint(DetectContentData *); diff --git a/src/detect-csum.c b/src/detect-csum.c index 5d59f06751a6..133e69d79272 100644 --- a/src/detect-csum.c +++ b/src/detect-csum.c @@ -49,44 +49,44 @@ typedef struct DetectCsumData_ { } DetectCsumData; /* prototypes for the "ipv4-csum" rule keyword */ -static int DetectIPV4CsumMatch(DetectEngineThreadCtx *, - Packet *, const Signature *, const SigMatchCtx *); +static int DetectIPV4CsumMatch( + DetectEngineThreadCtx *, Packet *, const Signature *, const SigMatchCtx *); static int DetectIPV4CsumSetup(DetectEngineCtx *, Signature *, const char *); static void DetectIPV4CsumFree(DetectEngineCtx *, void *); /* prototypes for the "tcpv4-csum" rule keyword */ -static int DetectTCPV4CsumMatch(DetectEngineThreadCtx *, - Packet *, const Signature *, const SigMatchCtx *); +static int DetectTCPV4CsumMatch( + DetectEngineThreadCtx *, Packet *, const Signature *, const SigMatchCtx *); static int DetectTCPV4CsumSetup(DetectEngineCtx *, Signature *, const char *); static void DetectTCPV4CsumFree(DetectEngineCtx *, void *); /* prototypes for the "tcpv6-csum" rule keyword */ -static int DetectTCPV6CsumMatch(DetectEngineThreadCtx *, - Packet *, const Signature *, const SigMatchCtx *); +static int DetectTCPV6CsumMatch( + DetectEngineThreadCtx *, Packet *, const Signature *, const SigMatchCtx *); static int DetectTCPV6CsumSetup(DetectEngineCtx *, Signature *, const char *); static void DetectTCPV6CsumFree(DetectEngineCtx *, void *); /* prototypes for the "udpv4-csum" rule keyword */ -static int DetectUDPV4CsumMatch(DetectEngineThreadCtx *, - Packet *, const Signature *, const SigMatchCtx *); +static int DetectUDPV4CsumMatch( + DetectEngineThreadCtx *, Packet *, const Signature *, const SigMatchCtx *); static int DetectUDPV4CsumSetup(DetectEngineCtx *, Signature *, const char *); static void DetectUDPV4CsumFree(DetectEngineCtx *, void *); /* prototypes for the "udpv6-csum" rule keyword */ -static int DetectUDPV6CsumMatch(DetectEngineThreadCtx *, - Packet *, const Signature *, const SigMatchCtx *); +static int DetectUDPV6CsumMatch( + DetectEngineThreadCtx *, Packet *, const Signature *, const SigMatchCtx *); static int DetectUDPV6CsumSetup(DetectEngineCtx *, Signature *, const char *); static void DetectUDPV6CsumFree(DetectEngineCtx *de_ctx, void *); /* prototypes for the "icmpv4-csum" rule keyword */ -static int DetectICMPV4CsumMatch(DetectEngineThreadCtx *, - Packet *, const Signature *, const SigMatchCtx *); +static int DetectICMPV4CsumMatch( + DetectEngineThreadCtx *, Packet *, const Signature *, const SigMatchCtx *); static int DetectICMPV4CsumSetup(DetectEngineCtx *, Signature *, const char *); static void DetectICMPV4CsumFree(DetectEngineCtx *, void *); /* prototypes for the "icmpv6-csum" rule keyword */ -static int DetectICMPV6CsumMatch(DetectEngineThreadCtx *, - Packet *, const Signature *, const SigMatchCtx *); +static int DetectICMPV6CsumMatch( + DetectEngineThreadCtx *, Packet *, const Signature *, const SigMatchCtx *); static int DetectICMPV6CsumSetup(DetectEngineCtx *, Signature *, const char *); static void DetectICMPV6CsumFree(DetectEngineCtx *, void *); @@ -136,12 +136,12 @@ static void DetectCsumRegisterTests(void); * * void * (ptr) - Pointer to the DetectCsumData for a keyword */ -void DetectCsumRegister (void) +void DetectCsumRegister(void) { sigmatch_table[DETECT_IPV4_CSUM].name = "ipv4-csum"; sigmatch_table[DETECT_IPV4_CSUM].Match = DetectIPV4CsumMatch; sigmatch_table[DETECT_IPV4_CSUM].Setup = DetectIPV4CsumSetup; - sigmatch_table[DETECT_IPV4_CSUM].Free = DetectIPV4CsumFree; + sigmatch_table[DETECT_IPV4_CSUM].Free = DetectIPV4CsumFree; #ifdef UNITTESTS sigmatch_table[DETECT_IPV4_CSUM].RegisterTests = DetectCsumRegisterTests; #endif @@ -149,32 +149,32 @@ void DetectCsumRegister (void) sigmatch_table[DETECT_TCPV4_CSUM].name = "tcpv4-csum"; sigmatch_table[DETECT_TCPV4_CSUM].Match = DetectTCPV4CsumMatch; sigmatch_table[DETECT_TCPV4_CSUM].Setup = DetectTCPV4CsumSetup; - sigmatch_table[DETECT_TCPV4_CSUM].Free = DetectTCPV4CsumFree; + sigmatch_table[DETECT_TCPV4_CSUM].Free = DetectTCPV4CsumFree; sigmatch_table[DETECT_TCPV6_CSUM].name = "tcpv6-csum"; sigmatch_table[DETECT_TCPV6_CSUM].Match = DetectTCPV6CsumMatch; sigmatch_table[DETECT_TCPV6_CSUM].Setup = DetectTCPV6CsumSetup; - sigmatch_table[DETECT_TCPV6_CSUM].Free = DetectTCPV6CsumFree; + sigmatch_table[DETECT_TCPV6_CSUM].Free = DetectTCPV6CsumFree; sigmatch_table[DETECT_UDPV4_CSUM].name = "udpv4-csum"; sigmatch_table[DETECT_UDPV4_CSUM].Match = DetectUDPV4CsumMatch; sigmatch_table[DETECT_UDPV4_CSUM].Setup = DetectUDPV4CsumSetup; - sigmatch_table[DETECT_UDPV4_CSUM].Free = DetectUDPV4CsumFree; + sigmatch_table[DETECT_UDPV4_CSUM].Free = DetectUDPV4CsumFree; sigmatch_table[DETECT_UDPV6_CSUM].name = "udpv6-csum"; sigmatch_table[DETECT_UDPV6_CSUM].Match = DetectUDPV6CsumMatch; sigmatch_table[DETECT_UDPV6_CSUM].Setup = DetectUDPV6CsumSetup; - sigmatch_table[DETECT_UDPV6_CSUM].Free = DetectUDPV6CsumFree; + sigmatch_table[DETECT_UDPV6_CSUM].Free = DetectUDPV6CsumFree; sigmatch_table[DETECT_ICMPV4_CSUM].name = "icmpv4-csum"; sigmatch_table[DETECT_ICMPV4_CSUM].Match = DetectICMPV4CsumMatch; sigmatch_table[DETECT_ICMPV4_CSUM].Setup = DetectICMPV4CsumSetup; - sigmatch_table[DETECT_ICMPV4_CSUM].Free = DetectICMPV4CsumFree; + sigmatch_table[DETECT_ICMPV4_CSUM].Free = DetectICMPV4CsumFree; sigmatch_table[DETECT_ICMPV6_CSUM].name = "icmpv6-csum"; sigmatch_table[DETECT_ICMPV6_CSUM].Match = DetectICMPV6CsumMatch; sigmatch_table[DETECT_ICMPV6_CSUM].Setup = DetectICMPV6CsumSetup; - sigmatch_table[DETECT_ICMPV6_CSUM].Free = DetectICMPV6CsumFree; + sigmatch_table[DETECT_ICMPV6_CSUM].Free = DetectICMPV6CsumFree; } /** @@ -206,8 +206,7 @@ static int DetectCsumParseArg(const char *key, DetectCsumData *cd) } } - if (strcasecmp(str, DETECT_CSUM_VALID) == 0 || - strcasecmp(str, DETECT_CSUM_INVALID) == 0) { + if (strcasecmp(str, DETECT_CSUM_VALID) == 0 || strcasecmp(str, DETECT_CSUM_INVALID) == 0) { cd->valid = (strcasecmp(key, DETECT_CSUM_VALID) == 0); SCFree(str); return 1; @@ -234,8 +233,8 @@ static int DetectCsumParseArg(const char *key, DetectCsumData *cd) * * \retval 1 if the Packet contents match the keyword option; 0 otherwise */ -static int DetectIPV4CsumMatch(DetectEngineThreadCtx *det_ctx, - Packet *p, const Signature *s, const SigMatchCtx *ctx) +static int DetectIPV4CsumMatch( + DetectEngineThreadCtx *det_ctx, Packet *p, const Signature *s, const SigMatchCtx *ctx) { const DetectCsumData *cd = (const DetectCsumData *)ctx; @@ -247,9 +246,7 @@ static int DetectIPV4CsumMatch(DetectEngineThreadCtx *det_ctx, } if (p->level3_comp_csum == -1) - p->level3_comp_csum = IPV4Checksum((uint16_t *)p->ip4h, - IPV4_GET_HLEN(p), - p->ip4h->ip_csum); + p->level3_comp_csum = IPV4Checksum((uint16_t *)p->ip4h, IPV4_GET_HLEN(p), p->ip4h->ip_csum); if (p->level3_comp_csum == 0 && cd->valid == 1) return 1; @@ -275,7 +272,7 @@ static int DetectIPV4CsumSetup(DetectEngineCtx *de_ctx, Signature *s, const char { DetectCsumData *cd = NULL; - //printf("DetectCsumSetup: \'%s\'\n", csum_str); + // printf("DetectCsumSetup: \'%s\'\n", csum_str); if ((cd = SCCalloc(1, sizeof(DetectCsumData))) == NULL) goto error; @@ -322,8 +319,8 @@ static void DetectIPV4CsumFree(DetectEngineCtx *de_ctx, void *ptr) * * \retval 1 if the Packet contents match the keyword option; 0 otherwise */ -static int DetectTCPV4CsumMatch(DetectEngineThreadCtx *det_ctx, - Packet *p, const Signature *s, const SigMatchCtx *ctx) +static int DetectTCPV4CsumMatch( + DetectEngineThreadCtx *det_ctx, Packet *p, const Signature *s, const SigMatchCtx *ctx) { const DetectCsumData *cd = (const DetectCsumData *)ctx; @@ -335,11 +332,8 @@ static int DetectTCPV4CsumMatch(DetectEngineThreadCtx *det_ctx, } if (p->level4_comp_csum == -1) - p->level4_comp_csum = TCPChecksum(p->ip4h->s_ip_addrs, - (uint16_t *)p->tcph, - (p->payload_len + - TCP_GET_HLEN(p)), - p->tcph->th_sum); + p->level4_comp_csum = TCPChecksum(p->ip4h->s_ip_addrs, (uint16_t *)p->tcph, + (p->payload_len + TCP_GET_HLEN(p)), p->tcph->th_sum); if (p->level4_comp_csum == 0 && cd->valid == 1) return 1; @@ -365,7 +359,7 @@ static int DetectTCPV4CsumSetup(DetectEngineCtx *de_ctx, Signature *s, const cha { DetectCsumData *cd = NULL; - //printf("DetectCsumSetup: \'%s\'\n", csum_str); + // printf("DetectCsumSetup: \'%s\'\n", csum_str); if ((cd = SCCalloc(1, sizeof(DetectCsumData))) == NULL) goto error; @@ -412,8 +406,8 @@ static void DetectTCPV4CsumFree(DetectEngineCtx *de_ctx, void *ptr) * * \retval 1 if the Packet contents match the keyword option; 0 otherwise */ -static int DetectTCPV6CsumMatch(DetectEngineThreadCtx *det_ctx, - Packet *p, const Signature *s, const SigMatchCtx *ctx) +static int DetectTCPV6CsumMatch( + DetectEngineThreadCtx *det_ctx, Packet *p, const Signature *s, const SigMatchCtx *ctx) { const DetectCsumData *cd = (const DetectCsumData *)ctx; @@ -425,11 +419,8 @@ static int DetectTCPV6CsumMatch(DetectEngineThreadCtx *det_ctx, } if (p->level4_comp_csum == -1) - p->level4_comp_csum = TCPV6Checksum(p->ip6h->s_ip6_addrs, - (uint16_t *)p->tcph, - (p->payload_len + - TCP_GET_HLEN(p)), - p->tcph->th_sum); + p->level4_comp_csum = TCPV6Checksum(p->ip6h->s_ip6_addrs, (uint16_t *)p->tcph, + (p->payload_len + TCP_GET_HLEN(p)), p->tcph->th_sum); if (p->level4_comp_csum == 0 && cd->valid == 1) return 1; @@ -455,7 +446,7 @@ static int DetectTCPV6CsumSetup(DetectEngineCtx *de_ctx, Signature *s, const cha { DetectCsumData *cd = NULL; - //printf("DetectCsumSetup: \'%s\'\n", csum_str); + // printf("DetectCsumSetup: \'%s\'\n", csum_str); if ((cd = SCCalloc(1, sizeof(DetectCsumData))) == NULL) goto error; @@ -502,12 +493,13 @@ static void DetectTCPV6CsumFree(DetectEngineCtx *de_ctx, void *ptr) * * \retval 1 if the Packet contents match the keyword option; 0 otherwise */ -static int DetectUDPV4CsumMatch(DetectEngineThreadCtx *det_ctx, - Packet *p, const Signature *s, const SigMatchCtx *ctx) +static int DetectUDPV4CsumMatch( + DetectEngineThreadCtx *det_ctx, Packet *p, const Signature *s, const SigMatchCtx *ctx) { const DetectCsumData *cd = (const DetectCsumData *)ctx; - if (p->ip4h == NULL || p->udph == NULL || p->proto != IPPROTO_UDP || PKT_IS_PSEUDOPKT(p) || p->udph->uh_sum == 0) + if (p->ip4h == NULL || p->udph == NULL || p->proto != IPPROTO_UDP || PKT_IS_PSEUDOPKT(p) || + p->udph->uh_sum == 0) return 0; if (p->flags & PKT_IGNORE_CHECKSUM) { @@ -515,11 +507,8 @@ static int DetectUDPV4CsumMatch(DetectEngineThreadCtx *det_ctx, } if (p->level4_comp_csum == -1) - p->level4_comp_csum = UDPV4Checksum(p->ip4h->s_ip_addrs, - (uint16_t *)p->udph, - (p->payload_len + - UDP_HEADER_LEN), - p->udph->uh_sum); + p->level4_comp_csum = UDPV4Checksum(p->ip4h->s_ip_addrs, (uint16_t *)p->udph, + (p->payload_len + UDP_HEADER_LEN), p->udph->uh_sum); if (p->level4_comp_csum == 0 && cd->valid == 1) return 1; @@ -545,7 +534,7 @@ static int DetectUDPV4CsumSetup(DetectEngineCtx *de_ctx, Signature *s, const cha { DetectCsumData *cd = NULL; - //printf("DetectCsumSetup: \'%s\'\n", csum_str); + // printf("DetectCsumSetup: \'%s\'\n", csum_str); if ((cd = SCCalloc(1, sizeof(DetectCsumData))) == NULL) goto error; @@ -592,8 +581,8 @@ static void DetectUDPV4CsumFree(DetectEngineCtx *de_ctx, void *ptr) * * \retval 1 if the Packet contents match the keyword option; 0 otherwise */ -static int DetectUDPV6CsumMatch(DetectEngineThreadCtx *det_ctx, - Packet *p, const Signature *s, const SigMatchCtx *ctx) +static int DetectUDPV6CsumMatch( + DetectEngineThreadCtx *det_ctx, Packet *p, const Signature *s, const SigMatchCtx *ctx) { const DetectCsumData *cd = (const DetectCsumData *)ctx; @@ -605,11 +594,8 @@ static int DetectUDPV6CsumMatch(DetectEngineThreadCtx *det_ctx, } if (p->level4_comp_csum == -1) - p->level4_comp_csum = UDPV6Checksum(p->ip6h->s_ip6_addrs, - (uint16_t *)p->udph, - (p->payload_len + - UDP_HEADER_LEN), - p->udph->uh_sum); + p->level4_comp_csum = UDPV6Checksum(p->ip6h->s_ip6_addrs, (uint16_t *)p->udph, + (p->payload_len + UDP_HEADER_LEN), p->udph->uh_sum); if (p->level4_comp_csum == 0 && cd->valid == 1) return 1; @@ -635,7 +621,7 @@ static int DetectUDPV6CsumSetup(DetectEngineCtx *de_ctx, Signature *s, const cha { DetectCsumData *cd = NULL; - //printf("DetectCsumSetup: \'%s\'\n", csum_str); + // printf("DetectCsumSetup: \'%s\'\n", csum_str); if ((cd = SCCalloc(1, sizeof(DetectCsumData))) == NULL) goto error; @@ -682,8 +668,8 @@ static void DetectUDPV6CsumFree(DetectEngineCtx *de_ctx, void *ptr) * * \retval 1 if the Packet contents match the keyword option; 0 otherwise */ -static int DetectICMPV4CsumMatch(DetectEngineThreadCtx *det_ctx, - Packet *p, const Signature *s, const SigMatchCtx *ctx) +static int DetectICMPV4CsumMatch( + DetectEngineThreadCtx *det_ctx, Packet *p, const Signature *s, const SigMatchCtx *ctx) { const DetectCsumData *cd = (const DetectCsumData *)ctx; @@ -696,8 +682,7 @@ static int DetectICMPV4CsumMatch(DetectEngineThreadCtx *det_ctx, if (p->level4_comp_csum == -1) p->level4_comp_csum = ICMPV4CalculateChecksum((uint16_t *)p->icmpv4h, - SCNtohs(IPV4_GET_RAW_IPLEN(p->ip4h)) - - IPV4_GET_RAW_HLEN(p->ip4h) * 4); + SCNtohs(IPV4_GET_RAW_IPLEN(p->ip4h)) - IPV4_GET_RAW_HLEN(p->ip4h) * 4); if (p->level4_comp_csum == p->icmpv4h->checksum && cd->valid == 1) return 1; @@ -723,7 +708,7 @@ static int DetectICMPV4CsumSetup(DetectEngineCtx *de_ctx, Signature *s, const ch { DetectCsumData *cd = NULL; - //printf("DetectCsumSetup: \'%s\'\n", csum_str); + // printf("DetectCsumSetup: \'%s\'\n", csum_str); if ((cd = SCCalloc(1, sizeof(DetectCsumData))) == NULL) goto error; @@ -770,13 +755,14 @@ static void DetectICMPV4CsumFree(DetectEngineCtx *de_ctx, void *ptr) * * \retval 1 if the Packet contents match the keyword option; 0 otherwise */ -static int DetectICMPV6CsumMatch(DetectEngineThreadCtx *det_ctx, - Packet *p, const Signature *s, const SigMatchCtx *ctx) +static int DetectICMPV6CsumMatch( + DetectEngineThreadCtx *det_ctx, Packet *p, const Signature *s, const SigMatchCtx *ctx) { const DetectCsumData *cd = (const DetectCsumData *)ctx; - if (p->ip6h == NULL || p->icmpv6h == NULL || p->proto != IPPROTO_ICMPV6 || PKT_IS_PSEUDOPKT(p) || - (GET_PKT_LEN(p) - ((uint8_t *)p->icmpv6h - GET_PKT_DATA(p))) <= 0) { + if (p->ip6h == NULL || p->icmpv6h == NULL || p->proto != IPPROTO_ICMPV6 || + PKT_IS_PSEUDOPKT(p) || + (GET_PKT_LEN(p) - ((uint8_t *)p->icmpv6h - GET_PKT_DATA(p))) <= 0) { return 0; } @@ -787,9 +773,8 @@ static int DetectICMPV6CsumMatch(DetectEngineThreadCtx *det_ctx, if (p->level4_comp_csum == -1) { uint16_t len = IPV6_GET_RAW_PLEN(p->ip6h) - (uint16_t)((uint8_t *)p->icmpv6h - (uint8_t *)p->ip6h - IPV6_HEADER_LEN); - p->level4_comp_csum = ICMPV6CalculateChecksum(p->ip6h->s_ip6_addrs, - (uint16_t *)p->icmpv6h, - len); + p->level4_comp_csum = + ICMPV6CalculateChecksum(p->ip6h->s_ip6_addrs, (uint16_t *)p->icmpv6h, len); } if (p->level4_comp_csum == p->icmpv6h->csum && cd->valid == 1) @@ -855,24 +840,29 @@ static void DetectICMPV6CsumFree(DetectEngineCtx *de_ctx, void *ptr) #include "packet.h" #define mystr(s) #s -#define TEST1(kwstr) {\ - DetectEngineCtx *de_ctx = DetectEngineCtxInit();\ - FAIL_IF_NULL(de_ctx);\ - de_ctx->flags = DE_QUIET;\ - \ - Signature *s = DetectEngineAppendSig(de_ctx, "alert ip any any -> any any ("mystr(kwstr)"-csum:valid; sid:1;)");\ - FAIL_IF_NULL(s);\ - s = DetectEngineAppendSig(de_ctx, "alert ip any any -> any any ("mystr(kwstr)"-csum:invalid; sid:2;)");\ - FAIL_IF_NULL(s);\ - s = DetectEngineAppendSig(de_ctx, "alert ip any any -> any any ("mystr(kwstr)"-csum:vaLid; sid:3;)");\ - FAIL_IF_NULL(s);\ - s = DetectEngineAppendSig(de_ctx, "alert ip any any -> any any ("mystr(kwstr)"-csum:VALID; sid:4;)");\ - FAIL_IF_NULL(s);\ - s = DetectEngineAppendSig(de_ctx, "alert ip any any -> any any ("mystr(kwstr)"-csum:iNvaLid; sid:5;)");\ - FAIL_IF_NULL(s);\ - DetectEngineCtxFree(de_ctx);\ -} - +#define TEST1(kwstr) \ + { \ + DetectEngineCtx *de_ctx = DetectEngineCtxInit(); \ + FAIL_IF_NULL(de_ctx); \ + de_ctx->flags = DE_QUIET; \ + \ + Signature *s = DetectEngineAppendSig( \ + de_ctx, "alert ip any any -> any any (" mystr(kwstr) "-csum:valid; sid:1;)"); \ + FAIL_IF_NULL(s); \ + s = DetectEngineAppendSig( \ + de_ctx, "alert ip any any -> any any (" mystr(kwstr) "-csum:invalid; sid:2;)"); \ + FAIL_IF_NULL(s); \ + s = DetectEngineAppendSig( \ + de_ctx, "alert ip any any -> any any (" mystr(kwstr) "-csum:vaLid; sid:3;)"); \ + FAIL_IF_NULL(s); \ + s = DetectEngineAppendSig( \ + de_ctx, "alert ip any any -> any any (" mystr(kwstr) "-csum:VALID; sid:4;)"); \ + FAIL_IF_NULL(s); \ + s = DetectEngineAppendSig( \ + de_ctx, "alert ip any any -> any any (" mystr(kwstr) "-csum:iNvaLid; sid:5;)"); \ + FAIL_IF_NULL(s); \ + DetectEngineCtxFree(de_ctx); \ + } static int DetectCsumValidArgsTestParse01(void) { @@ -922,23 +912,26 @@ static int DetectCsumInvalidArgsTestParse02(void) } #undef TEST2 -#define TEST3(kwstr, kwtype) { \ - DetectEngineCtx *de_ctx = DetectEngineCtxInit();\ - FAIL_IF_NULL(de_ctx);\ - Signature *s = DetectEngineAppendSig(de_ctx, "alert ip any any -> any any ("mystr(kwstr)"-csum:valid; sid:1;)");\ - FAIL_IF_NULL(s);\ - SigMatch *sm = DetectGetLastSMFromLists(s, (kwtype), -1);\ - FAIL_IF_NULL(sm);\ - FAIL_IF_NULL(sm->ctx);\ - FAIL_IF_NOT(((DetectCsumData *)sm->ctx)->valid == 1);\ - s = DetectEngineAppendSig(de_ctx, "alert ip any any -> any any ("mystr(kwstr)"-csum:INVALID; sid:2;)");\ - FAIL_IF_NULL(s);\ - sm = DetectGetLastSMFromLists(s, (kwtype), -1);\ - FAIL_IF_NULL(sm);\ - FAIL_IF_NULL(sm->ctx);\ - FAIL_IF_NOT(((DetectCsumData *)sm->ctx)->valid == 0);\ - DetectEngineCtxFree(de_ctx);\ -} +#define TEST3(kwstr, kwtype) \ + { \ + DetectEngineCtx *de_ctx = DetectEngineCtxInit(); \ + FAIL_IF_NULL(de_ctx); \ + Signature *s = DetectEngineAppendSig( \ + de_ctx, "alert ip any any -> any any (" mystr(kwstr) "-csum:valid; sid:1;)"); \ + FAIL_IF_NULL(s); \ + SigMatch *sm = DetectGetLastSMFromLists(s, (kwtype), -1); \ + FAIL_IF_NULL(sm); \ + FAIL_IF_NULL(sm->ctx); \ + FAIL_IF_NOT(((DetectCsumData *)sm->ctx)->valid == 1); \ + s = DetectEngineAppendSig( \ + de_ctx, "alert ip any any -> any any (" mystr(kwstr) "-csum:INVALID; sid:2;)"); \ + FAIL_IF_NULL(s); \ + sm = DetectGetLastSMFromLists(s, (kwtype), -1); \ + FAIL_IF_NULL(sm); \ + FAIL_IF_NULL(sm->ctx); \ + FAIL_IF_NOT(((DetectCsumData *)sm->ctx)->valid == 0); \ + DetectEngineCtxFree(de_ctx); \ + } static int DetectCsumValidArgsTestParse03(void) { @@ -1000,7 +993,7 @@ static int DetectCsumICMPV6Test01(void) de_ctx->flags |= DE_QUIET; s = de_ctx->sig_list = SigInit(de_ctx, "alert ip any any -> any any " - "(icmpv6-csum:valid; sid:1;)"); + "(icmpv6-csum:valid; sid:1;)"); FAIL_IF_NULL(s); SigGroupBuild(de_ctx); @@ -1024,14 +1017,10 @@ static int DetectCsumICMPV6Test01(void) static void DetectCsumRegisterTests(void) { - UtRegisterTest("DetectCsumValidArgsTestParse01", - DetectCsumValidArgsTestParse01); - UtRegisterTest("DetectCsumInvalidArgsTestParse02", - DetectCsumInvalidArgsTestParse02); - UtRegisterTest("DetectCsumValidArgsTestParse03", - DetectCsumValidArgsTestParse03); - - UtRegisterTest("DetectCsumICMPV6Test01", - DetectCsumICMPV6Test01); + UtRegisterTest("DetectCsumValidArgsTestParse01", DetectCsumValidArgsTestParse01); + UtRegisterTest("DetectCsumInvalidArgsTestParse02", DetectCsumInvalidArgsTestParse02); + UtRegisterTest("DetectCsumValidArgsTestParse03", DetectCsumValidArgsTestParse03); + + UtRegisterTest("DetectCsumICMPV6Test01", DetectCsumICMPV6Test01); } #endif /* UNITTESTS */ diff --git a/src/detect-csum.h b/src/detect-csum.h index 64914912fe8f..f97c84c7113c 100644 --- a/src/detect-csum.h +++ b/src/detect-csum.h @@ -27,4 +27,3 @@ void DetectCsumRegister(void); #endif /* __DETECT_CSUM_H__ */ - diff --git a/src/detect-datarep.c b/src/detect-datarep.c index 5b959b4023a3..83ee67ae3e1a 100644 --- a/src/detect-datarep.c +++ b/src/detect-datarep.c @@ -41,21 +41,21 @@ #include "util-misc.h" #include "util-path.h" -#define PARSE_REGEX "([a-z]+)(?:,\\s*([\\-_A-z0-9\\s\\.]+)){1,4}" +#define PARSE_REGEX "([a-z]+)(?:,\\s*([\\-_A-z0-9\\s\\.]+)){1,4}" static DetectParseRegex parse_regex; -int DetectDatarepMatch (ThreadVars *, DetectEngineThreadCtx *, Packet *, - const Signature *, const SigMatchCtx *); -static int DetectDatarepSetup (DetectEngineCtx *, Signature *, const char *); -void DetectDatarepFree (DetectEngineCtx *, void *); +int DetectDatarepMatch( + ThreadVars *, DetectEngineThreadCtx *, Packet *, const Signature *, const SigMatchCtx *); +static int DetectDatarepSetup(DetectEngineCtx *, Signature *, const char *); +void DetectDatarepFree(DetectEngineCtx *, void *); -void DetectDatarepRegister (void) +void DetectDatarepRegister(void) { sigmatch_table[DETECT_DATAREP].name = "datarep"; sigmatch_table[DETECT_DATAREP].desc = "operate on datasets (experimental)"; sigmatch_table[DETECT_DATAREP].url = "/rules/dataset-keywords.html#datarep"; sigmatch_table[DETECT_DATAREP].Setup = DetectDatarepSetup; - sigmatch_table[DETECT_DATAREP].Free = DetectDatarepFree; + sigmatch_table[DETECT_DATAREP].Free = DetectDatarepFree; DetectSetupParseRegexes(PARSE_REGEX, &parse_regex); } @@ -65,9 +65,8 @@ void DetectDatarepRegister (void) 0 no match -1 can't match */ -int DetectDatarepBufferMatch(DetectEngineThreadCtx *det_ctx, - const DetectDatarepData *sd, - const uint8_t *data, const uint32_t data_len) +int DetectDatarepBufferMatch(DetectEngineThreadCtx *det_ctx, const DetectDatarepData *sd, + const uint8_t *data, const uint32_t data_len) { if (data == NULL || data_len == 0) return 0; @@ -101,7 +100,7 @@ static int DetectDatarepParse(const char *str, char *cmd, int cmd_len, char *nam bool name_set = false; bool value_set = false; - char copy[strlen(str)+1]; + char copy[strlen(str) + 1]; strlcpy(copy, str, sizeof(copy)); char *xsaveptr = NULL; char *key = strtok_r(copy, ",", &xsaveptr); @@ -241,8 +240,7 @@ static void GetDirName(const char *in, char *out, size_t outs) return; } -static int SetupLoadPath(const DetectEngineCtx *de_ctx, - char *load, size_t load_size) +static int SetupLoadPath(const DetectEngineCtx *de_ctx, char *load, size_t load_size) { SCLogDebug("load %s", load); @@ -290,7 +288,7 @@ static int SetupLoadPath(const DetectEngineCtx *de_ctx, return 0; } -static int DetectDatarepSetup (DetectEngineCtx *de_ctx, Signature *s, const char *rawstr) +static int DetectDatarepSetup(DetectEngineCtx *de_ctx, Signature *s, const char *rawstr) { char cmd_str[16] = "", name[64] = ""; enum DatasetTypes type = DATASET_TYPE_NOTSET; @@ -321,11 +319,11 @@ static int DetectDatarepSetup (DetectEngineCtx *de_ctx, Signature *s, const char } enum DetectDatarepOp op; - if (strcmp(cmd_str,">") == 0) { + if (strcmp(cmd_str, ">") == 0) { op = DATAREP_OP_GT; - } else if (strcmp(cmd_str,"<") == 0) { + } else if (strcmp(cmd_str, "<") == 0) { op = DATAREP_OP_LT; - } else if (strcmp(cmd_str,"==") == 0) { + } else if (strcmp(cmd_str, "==") == 0) { op = DATAREP_OP_EQ; } else { SCLogError("datarep operation \"%s\" is not supported.", cmd_str); @@ -346,8 +344,7 @@ static int DetectDatarepSetup (DetectEngineCtx *de_ctx, Signature *s, const char cd->op = op; cd->rep.value = value; - SCLogDebug("cmd %s, name %s", - cmd_str, strlen(name) ? name : "(none)"); + SCLogDebug("cmd %s, name %s", cmd_str, strlen(name) ? name : "(none)"); /* Okay so far so good, lets get this into a SigMatch * and put it in the Signature. */ @@ -363,7 +360,7 @@ static int DetectDatarepSetup (DetectEngineCtx *de_ctx, Signature *s, const char return -1; } -void DetectDatarepFree (DetectEngineCtx *de_ctx, void *ptr) +void DetectDatarepFree(DetectEngineCtx *de_ctx, void *ptr) { DetectDatarepData *fd = (DetectDatarepData *)ptr; diff --git a/src/detect-datarep.h b/src/detect-datarep.h index b6191588240c..f6836138daa1 100644 --- a/src/detect-datarep.h +++ b/src/detect-datarep.h @@ -28,9 +28,9 @@ #include "datasets-reputation.h" enum DetectDatarepOp { - DATAREP_OP_GT, /* rep is greater than requested */ - DATAREP_OP_LT, /* rep is smaller than requested */ - DATAREP_OP_EQ, /* rep is smaller than requested */ + DATAREP_OP_GT, /* rep is greater than requested */ + DATAREP_OP_LT, /* rep is smaller than requested */ + DATAREP_OP_EQ, /* rep is smaller than requested */ }; typedef struct DetectDatarepData_ { @@ -40,11 +40,10 @@ typedef struct DetectDatarepData_ { DataRepType rep; } DetectDatarepData; -int DetectDatarepBufferMatch(DetectEngineThreadCtx *det_ctx, - const DetectDatarepData *sd, - const uint8_t *data, const uint32_t data_len); +int DetectDatarepBufferMatch(DetectEngineThreadCtx *det_ctx, const DetectDatarepData *sd, + const uint8_t *data, const uint32_t data_len); /* prototypes */ -void DetectDatarepRegister (void); +void DetectDatarepRegister(void); #endif /* __DETECT_DATAREP_H__ */ diff --git a/src/detect-dataset.c b/src/detect-dataset.c index f6d0d844e2e5..cf8ac5868c1a 100644 --- a/src/detect-dataset.c +++ b/src/detect-dataset.c @@ -41,18 +41,18 @@ #include "util-path.h" #include "util-conf.h" -int DetectDatasetMatch (ThreadVars *, DetectEngineThreadCtx *, Packet *, - const Signature *, const SigMatchCtx *); -static int DetectDatasetSetup (DetectEngineCtx *, Signature *, const char *); -void DetectDatasetFree (DetectEngineCtx *, void *); +int DetectDatasetMatch( + ThreadVars *, DetectEngineThreadCtx *, Packet *, const Signature *, const SigMatchCtx *); +static int DetectDatasetSetup(DetectEngineCtx *, Signature *, const char *); +void DetectDatasetFree(DetectEngineCtx *, void *); -void DetectDatasetRegister (void) +void DetectDatasetRegister(void) { sigmatch_table[DETECT_DATASET].name = "dataset"; sigmatch_table[DETECT_DATASET].desc = "match sticky buffer against datasets (experimental)"; sigmatch_table[DETECT_DATASET].url = "/rules/dataset-keywords.html#dataset"; sigmatch_table[DETECT_DATASET].Setup = DetectDatasetSetup; - sigmatch_table[DETECT_DATASET].Free = DetectDatasetFree; + sigmatch_table[DETECT_DATASET].Free = DetectDatasetFree; } /* @@ -60,16 +60,15 @@ void DetectDatasetRegister (void) 0 no match -1 can't match */ -int DetectDatasetBufferMatch(DetectEngineThreadCtx *det_ctx, - const DetectDatasetData *sd, - const uint8_t *data, const uint32_t data_len) +int DetectDatasetBufferMatch(DetectEngineThreadCtx *det_ctx, const DetectDatasetData *sd, + const uint8_t *data, const uint32_t data_len) { if (data == NULL || data_len == 0) return 0; switch (sd->cmd) { case DETECT_DATASET_CMD_ISSET: { - //PrintRawDataFp(stdout, data, data_len); + // PrintRawDataFp(stdout, data, data_len); int r = DatasetLookup(sd->set, data, data_len); SCLogDebug("r %d", r); if (r == 1) @@ -77,7 +76,7 @@ int DetectDatasetBufferMatch(DetectEngineThreadCtx *det_ctx, break; } case DETECT_DATASET_CMD_ISNOTSET: { - //PrintRawDataFp(stdout, data, data_len); + // PrintRawDataFp(stdout, data, data_len); int r = DatasetLookup(sd->set, data, data_len); SCLogDebug("r %d", r); if (r < 1) @@ -85,7 +84,7 @@ int DetectDatasetBufferMatch(DetectEngineThreadCtx *det_ctx, break; } case DETECT_DATASET_CMD_SET: { - //PrintRawDataFp(stdout, data, data_len); + // PrintRawDataFp(stdout, data, data_len); int r = DatasetAdd(sd->set, data, data_len); if (r == 1) return 1; @@ -107,7 +106,7 @@ static int DetectDatasetParse(const char *str, char *cmd, int cmd_len, char *nam bool save_set = false; bool state_set = false; - char copy[strlen(str)+1]; + char copy[strlen(str) + 1]; strlcpy(copy, str, sizeof(copy)); char *xsaveptr = NULL; char *key = strtok_r(copy, ",", &xsaveptr); @@ -255,8 +254,7 @@ static void GetDirName(const char *in, char *out, size_t outs) return; } -static int SetupLoadPath(const DetectEngineCtx *de_ctx, - char *load, size_t load_size) +static int SetupLoadPath(const DetectEngineCtx *de_ctx, char *load, size_t load_size) { SCLogDebug("load %s", load); @@ -298,8 +296,7 @@ static int SetupLoadPath(const DetectEngineCtx *de_ctx, return 0; } -static int SetupSavePath(const DetectEngineCtx *de_ctx, - char *save, size_t save_size) +static int SetupSavePath(const DetectEngineCtx *de_ctx, char *save, size_t save_size) { SCLogDebug("save %s", save); @@ -341,7 +338,7 @@ static int SetupSavePath(const DetectEngineCtx *de_ctx, return 0; } -int DetectDatasetSetup (DetectEngineCtx *de_ctx, Signature *s, const char *rawstr) +int DetectDatasetSetup(DetectEngineCtx *de_ctx, Signature *s, const char *rawstr) { DetectDatasetData *cd = NULL; uint8_t cmd = 0; @@ -368,13 +365,13 @@ int DetectDatasetSetup (DetectEngineCtx *de_ctx, Signature *s, const char *rawst return -1; } - if (strcmp(cmd_str,"isset") == 0) { + if (strcmp(cmd_str, "isset") == 0) { cmd = DETECT_DATASET_CMD_ISSET; - } else if (strcmp(cmd_str,"isnotset") == 0) { + } else if (strcmp(cmd_str, "isnotset") == 0) { cmd = DETECT_DATASET_CMD_ISNOTSET; - } else if (strcmp(cmd_str,"set") == 0) { + } else if (strcmp(cmd_str, "set") == 0) { cmd = DETECT_DATASET_CMD_SET; - } else if (strcmp(cmd_str,"unset") == 0) { + } else if (strcmp(cmd_str, "unset") == 0) { cmd = DETECT_DATASET_CMD_UNSET; } else { SCLogError("dataset action \"%s\" is not supported.", cmd_str); @@ -386,15 +383,14 @@ int DetectDatasetSetup (DetectEngineCtx *de_ctx, Signature *s, const char *rawst if (strlen(save) == 0 && strlen(load) != 0) { if (SetupLoadPath(de_ctx, load, sizeof(load)) != 0) return -1; - /* if just 'save' is set, we use either full path or the - * data-dir */ + /* if just 'save' is set, we use either full path or the + * data-dir */ } else if (strlen(save) != 0 && strlen(load) == 0) { if (SetupSavePath(de_ctx, save, sizeof(save)) != 0) return -1; - /* use 'save' logic for 'state', but put the resulting - * path into 'load' as well. */ - } else if (strlen(save) != 0 && strlen(load) != 0 && - strcmp(save, load) == 0) { + /* use 'save' logic for 'state', but put the resulting + * path into 'load' as well. */ + } else if (strlen(save) != 0 && strlen(load) != 0 && strcmp(save, load) == 0) { if (SetupSavePath(de_ctx, save, sizeof(save)) != 0) return -1; strlcpy(load, save, sizeof(load)); @@ -418,8 +414,7 @@ int DetectDatasetSetup (DetectEngineCtx *de_ctx, Signature *s, const char *rawst cd->set = set; cd->cmd = cmd; - SCLogDebug("cmd %s, name %s", - cmd_str, strlen(name) ? name : "(none)"); + SCLogDebug("cmd %s, name %s", cmd_str, strlen(name) ? name : "(none)"); /* Okay so far so good, lets get this into a SigMatch * and put it in the Signature. */ @@ -435,7 +430,7 @@ int DetectDatasetSetup (DetectEngineCtx *de_ctx, Signature *s, const char *rawst return -1; } -void DetectDatasetFree (DetectEngineCtx *de_ctx, void *ptr) +void DetectDatasetFree(DetectEngineCtx *de_ctx, void *ptr) { DetectDatasetData *fd = (DetectDatasetData *)ptr; if (fd == NULL) diff --git a/src/detect-dataset.h b/src/detect-dataset.h index ca83267d1592..a73243158e4b 100644 --- a/src/detect-dataset.h +++ b/src/detect-dataset.h @@ -36,11 +36,10 @@ typedef struct DetectDatasetData_ { uint8_t cmd; } DetectDatasetData; -int DetectDatasetBufferMatch(DetectEngineThreadCtx *det_ctx, - const DetectDatasetData *sd, - const uint8_t *data, const uint32_t data_len); +int DetectDatasetBufferMatch(DetectEngineThreadCtx *det_ctx, const DetectDatasetData *sd, + const uint8_t *data, const uint32_t data_len); /* prototypes */ -void DetectDatasetRegister (void); +void DetectDatasetRegister(void); #endif /* __DETECT_DATASET_H__ */ diff --git a/src/detect-dce-iface.c b/src/detect-dce-iface.c index 17895e070e9c..c9a6054cbd8b 100644 --- a/src/detect-dce-iface.c +++ b/src/detect-dce-iface.c @@ -49,13 +49,14 @@ #include "rust.h" -#define PARSE_REGEX "^\\s*([0-9a-zA-Z]{8}-[0-9a-zA-Z]{4}-[0-9a-zA-Z]{4}-[0-9a-zA-Z]{4}-[0-9a-zA-Z]{12})(?:\\s*,\\s*(<|>|=|!)([0-9]{1,5}))?(?:\\s*,\\s*(any_frag))?\\s*$" +#define PARSE_REGEX \ + "^\\s*([0-9a-zA-Z]{8}-[0-9a-zA-Z]{4}-[0-9a-zA-Z]{4}-[0-9a-zA-Z]{4}-[0-9a-zA-Z]{12})(?:\\s*," \ + "\\s*(<|>|=|!)([0-9]{1,5}))?(?:\\s*,\\s*(any_frag))?\\s*$" static DetectParseRegex parse_regex; -static int DetectDceIfaceMatchRust(DetectEngineThreadCtx *det_ctx, - Flow *f, uint8_t flags, void *state, void *txv, - const Signature *s, const SigMatchCtx *m); +static int DetectDceIfaceMatchRust(DetectEngineThreadCtx *det_ctx, Flow *f, uint8_t flags, + void *state, void *txv, const Signature *s, const SigMatchCtx *m); static int DetectDceIfaceSetup(DetectEngineCtx *, Signature *, const char *); static void DetectDceIfaceFree(DetectEngineCtx *, void *); #ifdef UNITTESTS @@ -72,7 +73,7 @@ void DetectDceIfaceRegister(void) sigmatch_table[DETECT_DCE_IFACE].alias = "dce_iface"; sigmatch_table[DETECT_DCE_IFACE].AppLayerTxMatch = DetectDceIfaceMatchRust; sigmatch_table[DETECT_DCE_IFACE].Setup = DetectDceIfaceSetup; - sigmatch_table[DETECT_DCE_IFACE].Free = DetectDceIfaceFree; + sigmatch_table[DETECT_DCE_IFACE].Free = DetectDceIfaceFree; #ifdef UNITTESTS sigmatch_table[DETECT_DCE_IFACE].RegisterTests = DetectDceIfaceRegisterTests; #endif @@ -105,9 +106,8 @@ void DetectDceIfaceRegister(void) * \retval 1 On Match. * \retval 0 On no match. */ -static int DetectDceIfaceMatchRust(DetectEngineThreadCtx *det_ctx, - Flow *f, uint8_t flags, void *state, void *txv, - const Signature *s, const SigMatchCtx *m) +static int DetectDceIfaceMatchRust(DetectEngineThreadCtx *det_ctx, Flow *f, uint8_t flags, + void *state, void *txv, const Signature *s, const SigMatchCtx *m) { SCEnter(); diff --git a/src/detect-dce-iface.h b/src/detect-dce-iface.h index edaded404442..0990602d8e34 100644 --- a/src/detect-dce-iface.h +++ b/src/detect-dce-iface.h @@ -18,7 +18,6 @@ #ifndef __DETECT_DCE_IFACE_H__ #define __DETECT_DCE_IFACE_H__ - void DetectDceIfaceRegister(void); #endif /* __DETECT_DCE_IFACE_H__ */ diff --git a/src/detect-dce-opnum.c b/src/detect-dce-opnum.c index e0e1ceeed04e..1c613086d979 100644 --- a/src/detect-dce-opnum.c +++ b/src/detect-dce-opnum.c @@ -50,13 +50,13 @@ #include "rust.h" -#define PARSE_REGEX "^\\s*([0-9]{1,5}(\\s*-\\s*[0-9]{1,5}\\s*)?)(,\\s*[0-9]{1,5}(\\s*-\\s*[0-9]{1,5})?\\s*)*$" +#define PARSE_REGEX \ + "^\\s*([0-9]{1,5}(\\s*-\\s*[0-9]{1,5}\\s*)?)(,\\s*[0-9]{1,5}(\\s*-\\s*[0-9]{1,5})?\\s*)*$" static DetectParseRegex parse_regex; -static int DetectDceOpnumMatchRust(DetectEngineThreadCtx *det_ctx, - Flow *f, uint8_t flags, void *state, void *txv, - const Signature *s, const SigMatchCtx *m); +static int DetectDceOpnumMatchRust(DetectEngineThreadCtx *det_ctx, Flow *f, uint8_t flags, + void *state, void *txv, const Signature *s, const SigMatchCtx *m); static int DetectDceOpnumSetup(DetectEngineCtx *, Signature *, const char *); static void DetectDceOpnumFree(DetectEngineCtx *, void *); #ifdef UNITTESTS @@ -73,7 +73,7 @@ void DetectDceOpnumRegister(void) sigmatch_table[DETECT_DCE_OPNUM].alias = "dce_opnum"; sigmatch_table[DETECT_DCE_OPNUM].AppLayerTxMatch = DetectDceOpnumMatchRust; sigmatch_table[DETECT_DCE_OPNUM].Setup = DetectDceOpnumSetup; - sigmatch_table[DETECT_DCE_OPNUM].Free = DetectDceOpnumFree; + sigmatch_table[DETECT_DCE_OPNUM].Free = DetectDceOpnumFree; #ifdef UNITTESTS sigmatch_table[DETECT_DCE_OPNUM].RegisterTests = DetectDceOpnumRegisterTests; #endif @@ -96,9 +96,8 @@ void DetectDceOpnumRegister(void) * \retval 1 On Match. * \retval 0 On no match. */ -static int DetectDceOpnumMatchRust(DetectEngineThreadCtx *det_ctx, - Flow *f, uint8_t flags, void *state, void *txv, - const Signature *s, const SigMatchCtx *m) +static int DetectDceOpnumMatchRust(DetectEngineThreadCtx *det_ctx, Flow *f, uint8_t flags, + void *state, void *txv, const Signature *s, const SigMatchCtx *m) { SCEnter(); diff --git a/src/detect-dce-opnum.h b/src/detect-dce-opnum.h index 1072a60bba62..61120c1f5c3e 100644 --- a/src/detect-dce-opnum.h +++ b/src/detect-dce-opnum.h @@ -24,7 +24,6 @@ #ifndef __DETECT_DCE_OPNUM_H__ #define __DETECT_DCE_OPNUM_H__ - void DetectDceOpnumRegister(void); #endif /* __DETECT_DCE_OPNUM_H__ */ diff --git a/src/detect-dce-stub-data.c b/src/detect-dce-stub-data.c index ea6e5d9263fa..cb14b22b3099 100644 --- a/src/detect-dce-stub-data.c +++ b/src/detect-dce-stub-data.c @@ -57,7 +57,7 @@ #include "rust.h" -#define BUFFER_NAME "dce_stub_data" +#define BUFFER_NAME "dce_stub_data" #define KEYWORD_NAME "dce_stub_data" static int DetectDceStubDataSetup(DetectEngineCtx *, Signature *, const char *); @@ -67,15 +67,14 @@ static void DetectDceStubDataRegisterTests(void); static int g_dce_stub_data_buffer_id = 0; static InspectionBuffer *GetSMBData(DetectEngineThreadCtx *det_ctx, - const DetectEngineTransforms *transforms, - Flow *_f, const uint8_t flow_flags, - void *txv, const int list_id) + const DetectEngineTransforms *transforms, Flow *_f, const uint8_t flow_flags, void *txv, + const int list_id) { InspectionBuffer *buffer = InspectionBufferGet(det_ctx, list_id); if (!buffer->initialized) { uint32_t data_len = 0; const uint8_t *data = NULL; - uint8_t dir = flow_flags & (STREAM_TOSERVER|STREAM_TOCLIENT); + uint8_t dir = flow_flags & (STREAM_TOSERVER | STREAM_TOCLIENT); if (rs_smb_tx_get_stub_data(txv, dir, &data, &data_len) != 1) return NULL; SCLogDebug("have data!"); @@ -87,9 +86,8 @@ static InspectionBuffer *GetSMBData(DetectEngineThreadCtx *det_ctx, } static InspectionBuffer *GetDCEData(DetectEngineThreadCtx *det_ctx, - const DetectEngineTransforms *transforms, - Flow *_f, const uint8_t flow_flags, - void *txv, const int list_id) + const DetectEngineTransforms *transforms, Flow *_f, const uint8_t flow_flags, void *txv, + const int list_id) { InspectionBuffer *buffer = InspectionBufferGet(det_ctx, list_id); if (!buffer->initialized) { @@ -123,37 +121,25 @@ void DetectDceStubDataRegister(void) #ifdef UNITTESTS sigmatch_table[DETECT_DCE_STUB_DATA].RegisterTests = DetectDceStubDataRegisterTests; #endif - sigmatch_table[DETECT_DCE_STUB_DATA].flags |= SIGMATCH_NOOPT|SIGMATCH_INFO_STICKY_BUFFER; - - DetectAppLayerInspectEngineRegister2(BUFFER_NAME, - ALPROTO_SMB, SIG_FLAG_TOSERVER, 0, - DetectEngineInspectBufferGeneric, - GetSMBData); - DetectAppLayerMpmRegister2(BUFFER_NAME, SIG_FLAG_TOSERVER, 2, - PrefilterGenericMpmRegister, GetSMBData, - ALPROTO_SMB, 0); - DetectAppLayerInspectEngineRegister2(BUFFER_NAME, - ALPROTO_SMB, SIG_FLAG_TOCLIENT, 0, - DetectEngineInspectBufferGeneric, - GetSMBData); - DetectAppLayerMpmRegister2(BUFFER_NAME, SIG_FLAG_TOCLIENT, 2, - PrefilterGenericMpmRegister, GetSMBData, - ALPROTO_SMB, 0); - - DetectAppLayerInspectEngineRegister2(BUFFER_NAME, - ALPROTO_DCERPC, SIG_FLAG_TOSERVER, 0, - DetectEngineInspectBufferGeneric, - GetDCEData); - DetectAppLayerMpmRegister2(BUFFER_NAME, SIG_FLAG_TOSERVER, 2, - PrefilterGenericMpmRegister, GetDCEData, - ALPROTO_DCERPC, 0); - DetectAppLayerInspectEngineRegister2(BUFFER_NAME, - ALPROTO_DCERPC, SIG_FLAG_TOCLIENT, 0, - DetectEngineInspectBufferGeneric, - GetDCEData); - DetectAppLayerMpmRegister2(BUFFER_NAME, SIG_FLAG_TOCLIENT, 2, - PrefilterGenericMpmRegister, GetDCEData, - ALPROTO_DCERPC, 0); + sigmatch_table[DETECT_DCE_STUB_DATA].flags |= SIGMATCH_NOOPT | SIGMATCH_INFO_STICKY_BUFFER; + + DetectAppLayerInspectEngineRegister2(BUFFER_NAME, ALPROTO_SMB, SIG_FLAG_TOSERVER, 0, + DetectEngineInspectBufferGeneric, GetSMBData); + DetectAppLayerMpmRegister2(BUFFER_NAME, SIG_FLAG_TOSERVER, 2, PrefilterGenericMpmRegister, + GetSMBData, ALPROTO_SMB, 0); + DetectAppLayerInspectEngineRegister2(BUFFER_NAME, ALPROTO_SMB, SIG_FLAG_TOCLIENT, 0, + DetectEngineInspectBufferGeneric, GetSMBData); + DetectAppLayerMpmRegister2(BUFFER_NAME, SIG_FLAG_TOCLIENT, 2, PrefilterGenericMpmRegister, + GetSMBData, ALPROTO_SMB, 0); + + DetectAppLayerInspectEngineRegister2(BUFFER_NAME, ALPROTO_DCERPC, SIG_FLAG_TOSERVER, 0, + DetectEngineInspectBufferGeneric, GetDCEData); + DetectAppLayerMpmRegister2(BUFFER_NAME, SIG_FLAG_TOSERVER, 2, PrefilterGenericMpmRegister, + GetDCEData, ALPROTO_DCERPC, 0); + DetectAppLayerInspectEngineRegister2(BUFFER_NAME, ALPROTO_DCERPC, SIG_FLAG_TOCLIENT, 0, + DetectEngineInspectBufferGeneric, GetDCEData); + DetectAppLayerMpmRegister2(BUFFER_NAME, SIG_FLAG_TOCLIENT, 2, PrefilterGenericMpmRegister, + GetDCEData, ALPROTO_DCERPC, 0); g_dce_stub_data_buffer_id = DetectBufferTypeGetByName(BUFFER_NAME); } @@ -665,7 +651,7 @@ static int DetectDceStubDataTestParse02(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_DCERPC; StreamTcpInitConfig(true); @@ -676,20 +662,18 @@ static int DetectDceStubDataTestParse02(void) de_ctx->flags |= DE_QUIET; - s = de_ctx->sig_list = SigInit(de_ctx, - "alert tcp any any -> any any " - "(msg:\"DCERPC\"; " - "dce_stub_data; content:\"|42 42 42 42|\";" - "sid:1;)"); + s = de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " + "(msg:\"DCERPC\"; " + "dce_stub_data; content:\"|42 42 42 42|\";" + "sid:1;)"); if (s == NULL) goto end; SigGroupBuild(de_ctx); DetectEngineThreadCtxInit(&th_v, (void *)de_ctx, (void *)&det_ctx); - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, - STREAM_TOSERVER | STREAM_START, dcerpc_bind, - dcerpc_bind_len); + r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, STREAM_TOSERVER | STREAM_START, + dcerpc_bind, dcerpc_bind_len); if (r != 0) { SCLogDebug("AppLayerParse for dcerpc failed. Returned %" PRId32, r); goto end; @@ -701,7 +685,7 @@ static int DetectDceStubDataTestParse02(void) goto end; } - p->flowflags &=~ FLOW_PKT_TOCLIENT; + p->flowflags &= ~FLOW_PKT_TOCLIENT; p->flowflags |= FLOW_PKT_TOSERVER; /* do detect */ SigMatchSignatures(&th_v, de_ctx, det_ctx, p); @@ -711,15 +695,14 @@ static int DetectDceStubDataTestParse02(void) goto end; /* do detect */ - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, - STREAM_TOCLIENT, dcerpc_bindack, - dcerpc_bindack_len); + r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, STREAM_TOCLIENT, dcerpc_bindack, + dcerpc_bindack_len); if (r != 0) { SCLogDebug("AppLayerParse for dcerpc failed. Returned %" PRId32, r); goto end; } - p->flowflags &=~ FLOW_PKT_TOSERVER; + p->flowflags &= ~FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_TOCLIENT; /* do detect */ SigMatchSignatures(&th_v, de_ctx, det_ctx, p); @@ -728,15 +711,14 @@ static int DetectDceStubDataTestParse02(void) if (PacketAlertCheck(p, 1)) goto end; - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, - STREAM_TOSERVER | STREAM_EOF, dcerpc_request, - dcerpc_request_len); + r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, STREAM_TOSERVER | STREAM_EOF, + dcerpc_request, dcerpc_request_len); if (r != 0) { SCLogDebug("AppLayerParse for dcerpc failed. Returned %" PRId32, r); goto end; } - p->flowflags &=~ FLOW_PKT_TOCLIENT; + p->flowflags &= ~FLOW_PKT_TOCLIENT; p->flowflags |= FLOW_PKT_TOSERVER; /* do detect */ SigMatchSignatures(&th_v, de_ctx, det_ctx, p); @@ -747,7 +729,7 @@ static int DetectDceStubDataTestParse02(void) result = 1; - end: +end: if (alp_tctx != NULL) AppLayerParserThreadCtxFree(alp_tctx); SigGroupCleanup(de_ctx); @@ -1215,7 +1197,7 @@ static int DetectDceStubDataTestParse03(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_DCERPC; StreamTcpInitConfig(true); @@ -1225,25 +1207,23 @@ static int DetectDceStubDataTestParse03(void) de_ctx->flags |= DE_QUIET; - s = de_ctx->sig_list = SigInit(de_ctx, - "alert tcp any any -> any any " - "(msg:\"DCERPC\"; " - "dce_stub_data; content:\"|42 42 42 42|\";" - "sid:1;)"); + s = de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " + "(msg:\"DCERPC\"; " + "dce_stub_data; content:\"|42 42 42 42|\";" + "sid:1;)"); FAIL_IF(s == NULL); SigGroupBuild(de_ctx); DetectEngineThreadCtxInit(&th_v, (void *)de_ctx, (void *)&det_ctx); - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, - STREAM_TOSERVER | STREAM_START, dcerpc_request, - dcerpc_request_len); + r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, STREAM_TOSERVER | STREAM_START, + dcerpc_request, dcerpc_request_len); FAIL_IF(r != 0); dcerpc_state = f.alstate; - FAIL_IF (dcerpc_state == NULL); + FAIL_IF(dcerpc_state == NULL); - p->flowflags &=~ FLOW_PKT_TOCLIENT; + p->flowflags &= ~FLOW_PKT_TOCLIENT; p->flowflags |= FLOW_PKT_TOSERVER; /* do detect */ SigMatchSignatures(&th_v, de_ctx, det_ctx, p); @@ -1413,7 +1393,7 @@ static int DetectDceStubDataTestParse04(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_DCERPC; StreamTcpInitConfig(true); @@ -1424,15 +1404,18 @@ static int DetectDceStubDataTestParse04(void) de_ctx->flags |= DE_QUIET; - s = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any " + s = DetectEngineAppendSig(de_ctx, + "alert tcp any any -> any any " "(msg:\"DCERPC\"; dce_stub_data; content:\"|00 02|\"; sid:1;)"); if (s == NULL) goto end; - s = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any " + s = DetectEngineAppendSig(de_ctx, + "alert tcp any any -> any any " "(msg:\"DCERPC\"; dce_stub_data; content:\"|00 75|\"; sid:2;)"); if (s == NULL) goto end; - s = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any " + s = DetectEngineAppendSig(de_ctx, + "alert tcp any any -> any any " "(msg:\"DCERPC\"; dce_stub_data; content:\"|00 18|\"; sid:3;)"); if (s == NULL) goto end; @@ -1440,14 +1423,13 @@ static int DetectDceStubDataTestParse04(void) SigGroupBuild(de_ctx); DetectEngineThreadCtxInit(&th_v, (void *)de_ctx, (void *)&det_ctx); - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, - STREAM_TOSERVER | STREAM_START, dcerpc_bind, - dcerpc_bind_len); + r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, STREAM_TOSERVER | STREAM_START, + dcerpc_bind, dcerpc_bind_len); if (r != 0) { SCLogDebug("AppLayerParse for dcerpc failed. Returned %" PRId32, r); goto end; } - p->flowflags &=~ FLOW_PKT_TOCLIENT; + p->flowflags &= ~FLOW_PKT_TOCLIENT; p->flowflags |= FLOW_PKT_TOSERVER; SigMatchSignatures(&th_v, de_ctx, det_ctx, p); @@ -1457,27 +1439,25 @@ static int DetectDceStubDataTestParse04(void) goto end; } - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, - STREAM_TOCLIENT, dcerpc_bindack, - dcerpc_bindack_len); + r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, STREAM_TOCLIENT, dcerpc_bindack, + dcerpc_bindack_len); if (r != 0) { SCLogDebug("AppLayerParse for dcerpc failed. Returned %" PRId32, r); goto end; } - p->flowflags &=~ FLOW_PKT_TOSERVER; + p->flowflags &= ~FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_TOCLIENT; SigMatchSignatures(&th_v, de_ctx, det_ctx, p); /* request1 */ - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, - STREAM_TOSERVER, dcerpc_request1, - dcerpc_request1_len); + r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, STREAM_TOSERVER, dcerpc_request1, + dcerpc_request1_len); if (r != 0) { SCLogDebug("AppLayerParse for dcerpc failed. Returned %" PRId32, r); goto end; } - p->flowflags &=~ FLOW_PKT_TOCLIENT; + p->flowflags &= ~FLOW_PKT_TOCLIENT; p->flowflags |= FLOW_PKT_TOSERVER; /* do detect */ SigMatchSignatures(&th_v, de_ctx, det_ctx, p); @@ -1486,15 +1466,14 @@ static int DetectDceStubDataTestParse04(void) goto end; /* response1 */ - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, - STREAM_TOCLIENT, dcerpc_response1, - dcerpc_response1_len); + r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, STREAM_TOCLIENT, dcerpc_response1, + dcerpc_response1_len); if (r != 0) { SCLogDebug("AppLayerParse for dcerpc failed. Returned %" PRId32, r); goto end; } - p->flowflags &=~ FLOW_PKT_TOSERVER; + p->flowflags &= ~FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_TOCLIENT; /* do detect */ SigMatchSignatures(&th_v, de_ctx, det_ctx, p); @@ -1503,15 +1482,14 @@ static int DetectDceStubDataTestParse04(void) goto end; /* request2 */ - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, - STREAM_TOSERVER, dcerpc_request2, - dcerpc_request2_len); + r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, STREAM_TOSERVER, dcerpc_request2, + dcerpc_request2_len); if (r != 0) { SCLogDebug("AppLayerParse for dcerpc failed. Returned %" PRId32, r); goto end; } - p->flowflags &=~ FLOW_PKT_TOCLIENT; + p->flowflags &= ~FLOW_PKT_TOCLIENT; p->flowflags |= FLOW_PKT_TOSERVER; /* do detect */ SigMatchSignatures(&th_v, de_ctx, det_ctx, p); @@ -1520,15 +1498,14 @@ static int DetectDceStubDataTestParse04(void) goto end; /* response2 */ - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, - STREAM_TOCLIENT, dcerpc_response2, - dcerpc_response2_len); + r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, STREAM_TOCLIENT, dcerpc_response2, + dcerpc_response2_len); if (r != 0) { SCLogDebug("AppLayerParse for dcerpc failed. Returned %" PRId32, r); goto end; } - p->flowflags &=~ FLOW_PKT_TOSERVER; + p->flowflags &= ~FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_TOCLIENT; /* do detect */ SigMatchSignatures(&th_v, de_ctx, det_ctx, p); @@ -1536,15 +1513,14 @@ static int DetectDceStubDataTestParse04(void) if (PacketAlertCheck(p, 1) || PacketAlertCheck(p, 2) || PacketAlertCheck(p, 3)) goto end; /* request3 */ - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, - STREAM_TOSERVER, dcerpc_request3, - dcerpc_request3_len); + r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, STREAM_TOSERVER, dcerpc_request3, + dcerpc_request3_len); if (r != 0) { SCLogDebug("AppLayerParse for dcerpc failed. Returned %" PRId32, r); goto end; } - p->flowflags &=~ FLOW_PKT_TOCLIENT; + p->flowflags &= ~FLOW_PKT_TOCLIENT; p->flowflags |= FLOW_PKT_TOSERVER; /* do detect */ SigMatchSignatures(&th_v, de_ctx, det_ctx, p); @@ -1553,15 +1529,14 @@ static int DetectDceStubDataTestParse04(void) goto end; /* response3 */ - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, - STREAM_TOCLIENT | STREAM_EOF, dcerpc_response3, - dcerpc_response3_len); + r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, STREAM_TOCLIENT | STREAM_EOF, + dcerpc_response3, dcerpc_response3_len); if (r != 0) { SCLogDebug("AppLayerParse for dcerpc failed. Returned %" PRId32, r); goto end; } - p->flowflags &=~ FLOW_PKT_TOSERVER; + p->flowflags &= ~FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_TOCLIENT; /* do detect */ SigMatchSignatures(&th_v, de_ctx, det_ctx, p); @@ -1571,7 +1546,7 @@ static int DetectDceStubDataTestParse04(void) result = 1; - end: +end: if (alp_tctx != NULL) AppLayerParserThreadCtxFree(alp_tctx); SigGroupCleanup(de_ctx); @@ -1709,7 +1684,7 @@ static int DetectDceStubDataTestParse05(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_DCERPC; StreamTcpInitConfig(true); @@ -1720,25 +1695,22 @@ static int DetectDceStubDataTestParse05(void) de_ctx->flags |= DE_QUIET; - s = de_ctx->sig_list = SigInit(de_ctx, - "alert tcp any any -> any any " - "(msg:\"DCERPC\"; " - "dce_stub_data; content:\"|00 02|\"; " - "sid:1;)"); + s = de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " + "(msg:\"DCERPC\"; " + "dce_stub_data; content:\"|00 02|\"; " + "sid:1;)"); if (s == NULL) goto end; - s = de_ctx->sig_list->next = SigInit(de_ctx, - "alert tcp any any -> any any " - "(msg:\"DCERPC\"; " - "dce_stub_data; content:\"|00 75|\"; " - "sid:2;)"); + s = de_ctx->sig_list->next = SigInit(de_ctx, "alert tcp any any -> any any " + "(msg:\"DCERPC\"; " + "dce_stub_data; content:\"|00 75|\"; " + "sid:2;)"); if (s == NULL) goto end; - s = de_ctx->sig_list->next->next = SigInit(de_ctx, - "alert tcp any any -> any any " - "(msg:\"DCERPC\"; " - "dce_stub_data; content:\"|00 18|\"; " - "sid:3;)"); + s = de_ctx->sig_list->next->next = SigInit(de_ctx, "alert tcp any any -> any any " + "(msg:\"DCERPC\"; " + "dce_stub_data; content:\"|00 18|\"; " + "sid:3;)"); if (s == NULL) goto end; @@ -1746,9 +1718,8 @@ static int DetectDceStubDataTestParse05(void) DetectEngineThreadCtxInit(&th_v, (void *)de_ctx, (void *)&det_ctx); /* request1 */ - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, - STREAM_TOSERVER | STREAM_START, dcerpc_request1, - dcerpc_request1_len); + r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, STREAM_TOSERVER | STREAM_START, + dcerpc_request1, dcerpc_request1_len); if (r != 0) { SCLogDebug("AppLayerParse for dcerpc failed. Returned %" PRId32, r); goto end; @@ -1760,7 +1731,7 @@ static int DetectDceStubDataTestParse05(void) goto end; } - p->flowflags &=~ FLOW_PKT_TOCLIENT; + p->flowflags &= ~FLOW_PKT_TOCLIENT; p->flowflags |= FLOW_PKT_TOSERVER; /* do detect */ SigMatchSignatures(&th_v, de_ctx, det_ctx, p); @@ -1769,15 +1740,14 @@ static int DetectDceStubDataTestParse05(void) goto end; /* response1 */ - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, - STREAM_TOCLIENT, dcerpc_response1, - dcerpc_response1_len); + r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, STREAM_TOCLIENT, dcerpc_response1, + dcerpc_response1_len); if (r != 0) { SCLogDebug("AppLayerParse for dcerpc failed. Returned %" PRId32, r); goto end; } - p->flowflags &=~ FLOW_PKT_TOSERVER; + p->flowflags &= ~FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_TOCLIENT; /* do detect */ SigMatchSignatures(&th_v, de_ctx, det_ctx, p); @@ -1786,15 +1756,14 @@ static int DetectDceStubDataTestParse05(void) goto end; /* request2 */ - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, - STREAM_TOSERVER, dcerpc_request2, - dcerpc_request2_len); + r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, STREAM_TOSERVER, dcerpc_request2, + dcerpc_request2_len); if (r != 0) { SCLogDebug("AppLayerParse for dcerpc failed. Returned %" PRId32, r); goto end; } - p->flowflags &=~ FLOW_PKT_TOCLIENT; + p->flowflags &= ~FLOW_PKT_TOCLIENT; p->flowflags |= FLOW_PKT_TOSERVER; /* do detect */ SigMatchSignatures(&th_v, de_ctx, det_ctx, p); @@ -1803,15 +1772,14 @@ static int DetectDceStubDataTestParse05(void) goto end; /* response2 */ - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, - STREAM_TOCLIENT, dcerpc_response2, - dcerpc_response2_len); + r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, STREAM_TOCLIENT, dcerpc_response2, + dcerpc_response2_len); if (r != 0) { SCLogDebug("AppLayerParse for dcerpc failed. Returned %" PRId32, r); goto end; } - p->flowflags &=~ FLOW_PKT_TOSERVER; + p->flowflags &= ~FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_TOCLIENT; /* do detect */ SigMatchSignatures(&th_v, de_ctx, det_ctx, p); @@ -1820,15 +1788,14 @@ static int DetectDceStubDataTestParse05(void) goto end; /* request3 */ - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, - STREAM_TOSERVER, dcerpc_request3, - dcerpc_request3_len); + r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, STREAM_TOSERVER, dcerpc_request3, + dcerpc_request3_len); if (r != 0) { SCLogDebug("AppLayerParse for dcerpc failed. Returned %" PRId32, r); goto end; } - p->flowflags &=~ FLOW_PKT_TOCLIENT; + p->flowflags &= ~FLOW_PKT_TOCLIENT; p->flowflags |= FLOW_PKT_TOSERVER; /* do detect */ SigMatchSignatures(&th_v, de_ctx, det_ctx, p); @@ -1837,15 +1804,14 @@ static int DetectDceStubDataTestParse05(void) goto end; /* response3 */ - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, - STREAM_TOCLIENT | STREAM_EOF, dcerpc_response3, - dcerpc_response3_len); + r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, STREAM_TOCLIENT | STREAM_EOF, + dcerpc_response3, dcerpc_response3_len); if (r != 0) { SCLogDebug("AppLayerParse for dcerpc failed. Returned %" PRId32, r); goto end; } - p->flowflags &=~ FLOW_PKT_TOSERVER; + p->flowflags &= ~FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_TOCLIENT; /* do detect */ SigMatchSignatures(&th_v, de_ctx, det_ctx, p); @@ -1855,7 +1821,7 @@ static int DetectDceStubDataTestParse05(void) result = 1; - end: +end: if (alp_tctx != NULL) AppLayerParserThreadCtxFree(alp_tctx); @@ -1878,8 +1844,8 @@ static int DetectDceStubDataTestParse06(void) DetectEngineCtx *de_ctx = DetectEngineCtxInit(); FAIL_IF_NULL(de_ctx); de_ctx->flags = DE_QUIET; - Signature *s = DetectEngineAppendSig(de_ctx, - "alert dns any any -> any any dce_stub_data;content:\"0\";"); + Signature *s = DetectEngineAppendSig( + de_ctx, "alert dns any any -> any any dce_stub_data;content:\"0\";"); FAIL_IF_NOT_NULL(s); DetectEngineCtxFree(de_ctx); PASS; @@ -1887,15 +1853,10 @@ static int DetectDceStubDataTestParse06(void) static void DetectDceStubDataRegisterTests(void) { - UtRegisterTest("DetectDceStubDataTestParse02", - DetectDceStubDataTestParse02); - UtRegisterTest("DetectDceStubDataTestParse03", - DetectDceStubDataTestParse03); - UtRegisterTest("DetectDceStubDataTestParse04", - DetectDceStubDataTestParse04); - UtRegisterTest("DetectDceStubDataTestParse05", - DetectDceStubDataTestParse05); - UtRegisterTest("DetectDceStubDataTestParse06", - DetectDceStubDataTestParse06); + UtRegisterTest("DetectDceStubDataTestParse02", DetectDceStubDataTestParse02); + UtRegisterTest("DetectDceStubDataTestParse03", DetectDceStubDataTestParse03); + UtRegisterTest("DetectDceStubDataTestParse04", DetectDceStubDataTestParse04); + UtRegisterTest("DetectDceStubDataTestParse05", DetectDceStubDataTestParse05); + UtRegisterTest("DetectDceStubDataTestParse06", DetectDceStubDataTestParse06); } #endif diff --git a/src/detect-dce-stub-data.h b/src/detect-dce-stub-data.h index 035fa258a558..80c82145c0e8 100644 --- a/src/detect-dce-stub-data.h +++ b/src/detect-dce-stub-data.h @@ -24,7 +24,6 @@ #ifndef __DETECT_DCE_STUB_DATA_H__ #define __DETECT_DCE_STUB_DATA_H__ - void DetectDceStubDataRegister(void); #endif /* __DETECT_DCE_STUB_DATA_H__ */ diff --git a/src/detect-depth.c b/src/detect-depth.c index 1c4f94a396f0..718f68798f07 100644 --- a/src/detect-depth.c +++ b/src/detect-depth.c @@ -42,26 +42,28 @@ #include "util-byte.h" #include "util-debug.h" -static int DetectDepthSetup (DetectEngineCtx *, Signature *, const char *); -static int DetectStartsWithSetup (DetectEngineCtx *, Signature *, const char *); +static int DetectDepthSetup(DetectEngineCtx *, Signature *, const char *); +static int DetectStartsWithSetup(DetectEngineCtx *, Signature *, const char *); -void DetectDepthRegister (void) +void DetectDepthRegister(void) { sigmatch_table[DETECT_DEPTH].name = "depth"; - sigmatch_table[DETECT_DEPTH].desc = "designate how many bytes from the beginning of the payload will be checked"; + sigmatch_table[DETECT_DEPTH].desc = + "designate how many bytes from the beginning of the payload will be checked"; sigmatch_table[DETECT_DEPTH].url = "/rules/payload-keywords.html#depth"; sigmatch_table[DETECT_DEPTH].Match = NULL; sigmatch_table[DETECT_DEPTH].Setup = DetectDepthSetup; - sigmatch_table[DETECT_DEPTH].Free = NULL; + sigmatch_table[DETECT_DEPTH].Free = NULL; sigmatch_table[DETECT_STARTS_WITH].name = "startswith"; - sigmatch_table[DETECT_STARTS_WITH].desc = "pattern must be at the start of a buffer (same as 'depth:')"; + sigmatch_table[DETECT_STARTS_WITH].desc = + "pattern must be at the start of a buffer (same as 'depth:')"; sigmatch_table[DETECT_STARTS_WITH].url = "/rules/payload-keywords.html#startswith"; sigmatch_table[DETECT_STARTS_WITH].Setup = DetectStartsWithSetup; sigmatch_table[DETECT_STARTS_WITH].flags |= SIGMATCH_NOOPT; } -static int DetectDepthSetup (DetectEngineCtx *de_ctx, Signature *s, const char *depthstr) +static int DetectDepthSetup(DetectEngineCtx *de_ctx, Signature *s, const char *depthstr) { const char *str = depthstr; SigMatch *pm = NULL; @@ -115,8 +117,7 @@ static int DetectDepthSetup (DetectEngineCtx *de_ctx, Signature *s, const char * cd->depth = index; cd->flags |= DETECT_CONTENT_DEPTH_VAR; } else { - if (StringParseUint16(&cd->depth, 0, 0, str) < 0) - { + if (StringParseUint16(&cd->depth, 0, 0, str) < 0) { SCLogError("invalid value for depth: %s.", str); goto end; } @@ -133,11 +134,11 @@ static int DetectDepthSetup (DetectEngineCtx *de_ctx, Signature *s, const char * cd->flags |= DETECT_CONTENT_DEPTH; ret = 0; - end: +end: return ret; } -static int DetectStartsWithSetup (DetectEngineCtx *de_ctx, Signature *s, const char *unused) +static int DetectStartsWithSetup(DetectEngineCtx *de_ctx, Signature *s, const char *unused) { SigMatch *pm = NULL; int ret = -1; @@ -186,6 +187,6 @@ static int DetectStartsWithSetup (DetectEngineCtx *de_ctx, Signature *s, const c cd->flags |= DETECT_CONTENT_STARTS_WITH; ret = 0; - end: +end: return ret; } diff --git a/src/detect-depth.h b/src/detect-depth.h index b864f62175d8..c7e54858ce61 100644 --- a/src/detect-depth.h +++ b/src/detect-depth.h @@ -25,7 +25,6 @@ #define __DETECT_DEPTH_H__ /* prototypes */ -void DetectDepthRegister (void); +void DetectDepthRegister(void); #endif /* __DETECT_DEPTH_H__ */ - diff --git a/src/detect-detection-filter.h b/src/detect-detection-filter.h index f136d3aca5f9..787ed48f1a83 100644 --- a/src/detect-detection-filter.h +++ b/src/detect-detection-filter.h @@ -28,7 +28,6 @@ * Registration function for detection_filter: keyword */ -void DetectDetectionFilterRegister (void); +void DetectDetectionFilterRegister(void); #endif /*__DETECT_DETECTION_FILTER_H__ */ - diff --git a/src/detect-distance.c b/src/detect-distance.c index f55d29fd22b7..8dab864425c4 100644 --- a/src/detect-distance.c +++ b/src/detect-distance.c @@ -56,18 +56,18 @@ static void DetectDistanceRegisterTests(void); void DetectDistanceRegister(void) { sigmatch_table[DETECT_DISTANCE].name = "distance"; - sigmatch_table[DETECT_DISTANCE].desc = "indicates a relation between this content keyword and the content preceding it"; + sigmatch_table[DETECT_DISTANCE].desc = + "indicates a relation between this content keyword and the content preceding it"; sigmatch_table[DETECT_DISTANCE].url = "/rules/payload-keywords.html#distance"; sigmatch_table[DETECT_DISTANCE].Match = NULL; sigmatch_table[DETECT_DISTANCE].Setup = DetectDistanceSetup; - sigmatch_table[DETECT_DISTANCE].Free = NULL; + sigmatch_table[DETECT_DISTANCE].Free = NULL; #ifdef UNITTESTS sigmatch_table[DETECT_DISTANCE].RegisterTests = DetectDistanceRegisterTests; #endif } -static int DetectDistanceSetup (DetectEngineCtx *de_ctx, Signature *s, - const char *distancestr) +static int DetectDistanceSetup(DetectEngineCtx *de_ctx, Signature *s, const char *distancestr) { const char *str = distancestr; @@ -125,8 +125,7 @@ static int DetectDistanceSetup (DetectEngineCtx *de_ctx, Signature *s, } cd->flags |= DETECT_CONTENT_DISTANCE; - SigMatch *prev_pm = DetectGetLastSMByListPtr(s, pm->prev, - DETECT_CONTENT, DETECT_PCRE, -1); + SigMatch *prev_pm = DetectGetLastSMByListPtr(s, pm->prev, DETECT_CONTENT, DETECT_PCRE, -1); if (prev_pm == NULL) { return 0; } @@ -190,7 +189,7 @@ static int DetectDistanceTest01(void) * distance works, if the previous keyword is byte_jump and content * (bug 163) */ -static int DetectDistanceTestPacket01 (void) +static int DetectDistanceTestPacket01(void) { // clang-format off uint8_t buf[] = { 0x01, 0x00, 0x00, 0x00, 0x00, 0x00 }; @@ -200,8 +199,8 @@ static int DetectDistanceTestPacket01 (void) FAIL_IF_NULL(p); char sig[] = "alert tcp any any -> any any (msg:\"suricata test\"; " - "byte_jump:1,2; content:\"|00|\"; " - "within:1; distance:2; sid:98711212; rev:1;)"; + "byte_jump:1,2; content:\"|00|\"; " + "within:1; distance:2; sid:98711212; rev:1;)"; p->flowflags = FLOW_PKT_ESTABLISHED | FLOW_PKT_TOCLIENT; FAIL_IF_NOT(UTHPacketMatchSig(p, sig)); @@ -213,8 +212,7 @@ static int DetectDistanceTestPacket01 (void) static void DetectDistanceRegisterTests(void) { - UtRegisterTest("DetectDistanceTest01 -- distance / within mix", - DetectDistanceTest01); + UtRegisterTest("DetectDistanceTest01 -- distance / within mix", DetectDistanceTest01); UtRegisterTest("DetectDistanceTestPacket01", DetectDistanceTestPacket01); } #endif /* UNITTESTS */ diff --git a/src/detect-distance.h b/src/detect-distance.h index 80aebe4f71e2..b135cf403b1d 100644 --- a/src/detect-distance.h +++ b/src/detect-distance.h @@ -25,7 +25,6 @@ #define __DETECT_DISTANCE_H__ /* prototypes */ -void DetectDistanceRegister (void); +void DetectDistanceRegister(void); #endif /* __DETECT_DISTANCE_H__ */ - diff --git a/src/detect-dnp3.c b/src/detect-dnp3.c index 6d92596c1d73..5af143b8e1e2 100644 --- a/src/detect-dnp3.c +++ b/src/detect-dnp3.c @@ -40,7 +40,7 @@ typedef struct DetectDNP3_ { union { struct { /* Function code for function code detection. */ - uint8_t function_code; + uint8_t function_code; }; struct { /* Internal indicator flags for IIN detection. */ @@ -48,8 +48,8 @@ typedef struct DetectDNP3_ { }; struct { /* Object info for object detection. */ - uint8_t obj_group; - uint8_t obj_variation; + uint8_t obj_group; + uint8_t obj_variation; }; }; } DetectDNP3; @@ -58,69 +58,42 @@ typedef struct DetectDNP3_ { * Indicator names to value mappings (Snort compatible). */ DNP3Mapping DNP3IndicatorsMap[] = { - {"device_restart", 0x8000}, - {"device_trouble", 0x4000}, - {"local_control", 0x2000}, - {"need_time", 0x1000}, - {"class_3_events", 0x0800}, - {"class_2_events", 0x0400}, - {"class_1_events", 0x0200}, - {"all_stations", 0x0100}, - - {"reserved_1", 0x0080}, - {"reserved_2", 0x0040}, - {"config_corrupt", 0x0020}, - {"already_executing", 0x0010}, - {"event_buffer_overflow", 0x0008}, - {"parameter_error", 0x0004}, - {"object_unknown", 0x0002}, - {"no_func_code_support", 0x0001}, - - {NULL, 0}, + { "device_restart", 0x8000 }, + { "device_trouble", 0x4000 }, + { "local_control", 0x2000 }, + { "need_time", 0x1000 }, + { "class_3_events", 0x0800 }, + { "class_2_events", 0x0400 }, + { "class_1_events", 0x0200 }, + { "all_stations", 0x0100 }, + + { "reserved_1", 0x0080 }, + { "reserved_2", 0x0040 }, + { "config_corrupt", 0x0020 }, + { "already_executing", 0x0010 }, + { "event_buffer_overflow", 0x0008 }, + { "parameter_error", 0x0004 }, + { "object_unknown", 0x0002 }, + { "no_func_code_support", 0x0001 }, + + { NULL, 0 }, }; /** * Application function code name to code mappings (Snort compatible). */ -DNP3Mapping DNP3FunctionNameMap[] = { - {"confirm", 0}, - {"read", 1}, - {"write", 2}, - {"select", 3}, - {"operate", 4}, - {"direct_operate", 5}, - {"direct_operate_nr", 6}, - {"immed_freeze", 7}, - {"immed_freeze_nr", 8}, - {"freeze_clear", 9}, - {"freeze_clear_nr", 10}, - {"freeze_at_time", 11}, - {"freeze_at_time_nr", 12}, - {"cold_restart", 13}, - {"warm_restart", 14}, - {"initialize_data", 15}, - {"initialize_appl", 16}, - {"start_appl", 17}, - {"stop_appl", 18}, - {"save_config", 19}, - {"enable_unsolicited", 20}, - {"disable_unsolicited", 21}, - {"assign_class", 22}, - {"delay_measure", 23}, - {"record_current_time", 24}, - {"open_file", 25}, - {"close_file", 26}, - {"delete_file", 27}, - {"get_file_info", 28}, - {"authenticate_file", 29}, - {"abort_file", 30}, - {"activate_config", 31}, - {"authenticate_req", 32}, - {"authenticate_err", 33}, - {"response", 129}, - {"unsolicited_response", 130}, - {"authenticate_resp", 131} -}; +DNP3Mapping DNP3FunctionNameMap[] = { { "confirm", 0 }, { "read", 1 }, { "write", 2 }, + { "select", 3 }, { "operate", 4 }, { "direct_operate", 5 }, { "direct_operate_nr", 6 }, + { "immed_freeze", 7 }, { "immed_freeze_nr", 8 }, { "freeze_clear", 9 }, + { "freeze_clear_nr", 10 }, { "freeze_at_time", 11 }, { "freeze_at_time_nr", 12 }, + { "cold_restart", 13 }, { "warm_restart", 14 }, { "initialize_data", 15 }, + { "initialize_appl", 16 }, { "start_appl", 17 }, { "stop_appl", 18 }, { "save_config", 19 }, + { "enable_unsolicited", 20 }, { "disable_unsolicited", 21 }, { "assign_class", 22 }, + { "delay_measure", 23 }, { "record_current_time", 24 }, { "open_file", 25 }, + { "close_file", 26 }, { "delete_file", 27 }, { "get_file_info", 28 }, + { "authenticate_file", 29 }, { "abort_file", 30 }, { "activate_config", 31 }, + { "authenticate_req", 32 }, { "authenticate_err", 33 }, { "response", 129 }, + { "unsolicited_response", 130 }, { "authenticate_resp", 131 } }; #ifdef UNITTESTS static void DetectDNP3FuncRegisterTests(void); @@ -146,9 +119,8 @@ static char *TrimString(char *str) } static InspectionBuffer *GetDNP3Data(DetectEngineThreadCtx *det_ctx, - const DetectEngineTransforms *transforms, - Flow *_f, const uint8_t flow_flags, - void *txv, const int list_id) + const DetectEngineTransforms *transforms, Flow *_f, const uint8_t flow_flags, void *txv, + const int list_id) { SCLogDebug("list_id %d", list_id); InspectionBuffer *buffer = InspectionBufferGet(det_ctx, list_id); @@ -190,8 +162,7 @@ static int DetectDNP3FuncParseFunctionCode(const char *str, uint8_t *fc) } /* Lookup by name. */ - for (size_t i = 0; - i < sizeof(DNP3FunctionNameMap) / sizeof(DNP3Mapping); i++) { + for (size_t i = 0; i < sizeof(DNP3FunctionNameMap) / sizeof(DNP3Mapping); i++) { if (strcasecmp(str, DNP3FunctionNameMap[i].name) == 0) { *fc = (uint8_t)(DNP3FunctionNameMap[i].value); return 1; @@ -388,9 +359,8 @@ static void DetectDNP3Free(DetectEngineCtx *de_ctx, void *ptr) SCReturn; } -static int DetectDNP3FuncMatch(DetectEngineThreadCtx *det_ctx, - Flow *f, uint8_t flags, void *state, void *txv, const Signature *s, - const SigMatchCtx *ctx) +static int DetectDNP3FuncMatch(DetectEngineThreadCtx *det_ctx, Flow *f, uint8_t flags, void *state, + void *txv, const Signature *s, const SigMatchCtx *ctx) { DNP3Transaction *tx = (DNP3Transaction *)txv; DetectDNP3 *detect = (DetectDNP3 *)ctx; @@ -405,9 +375,8 @@ static int DetectDNP3FuncMatch(DetectEngineThreadCtx *det_ctx, return match; } -static int DetectDNP3ObjMatch(DetectEngineThreadCtx *det_ctx, - Flow *f, uint8_t flags, void *state, void *txv, const Signature *s, - const SigMatchCtx *ctx) +static int DetectDNP3ObjMatch(DetectEngineThreadCtx *det_ctx, Flow *f, uint8_t flags, void *state, + void *txv, const Signature *s, const SigMatchCtx *ctx) { DNP3Transaction *tx = (DNP3Transaction *)txv; DetectDNP3 *detect = (DetectDNP3 *)ctx; @@ -421,9 +390,8 @@ static int DetectDNP3ObjMatch(DetectEngineThreadCtx *det_ctx, if (objects != NULL) { DNP3Object *object; - TAILQ_FOREACH(object, objects, next) { - if (object->group == detect->obj_group && - object->variation == detect->obj_variation) { + TAILQ_FOREACH (object, objects, next) { + if (object->group == detect->obj_group && object->variation == detect->obj_variation) { return 1; } } @@ -432,9 +400,8 @@ static int DetectDNP3ObjMatch(DetectEngineThreadCtx *det_ctx, return 0; } -static int DetectDNP3IndMatch(DetectEngineThreadCtx *det_ctx, - Flow *f, uint8_t flags, void *state, void *txv, const Signature *s, - const SigMatchCtx *ctx) +static int DetectDNP3IndMatch(DetectEngineThreadCtx *det_ctx, Flow *f, uint8_t flags, void *state, + void *txv, const Signature *s, const SigMatchCtx *ctx) { DNP3Transaction *tx = (DNP3Transaction *)txv; DetectDNP3 *detect = (DetectDNP3 *)ctx; @@ -453,17 +420,17 @@ static void DetectDNP3FuncRegister(void) { SCEnter(); - sigmatch_table[DETECT_AL_DNP3FUNC].name = "dnp3_func"; - sigmatch_table[DETECT_AL_DNP3FUNC].alias = "dnp3.func"; - sigmatch_table[DETECT_AL_DNP3FUNC].desc = "match on the application function code found in DNP3 request and responses"; - sigmatch_table[DETECT_AL_DNP3FUNC].url = "/rules/dnp3-keywords.html#dnp3-func"; - sigmatch_table[DETECT_AL_DNP3FUNC].Match = NULL; + sigmatch_table[DETECT_AL_DNP3FUNC].name = "dnp3_func"; + sigmatch_table[DETECT_AL_DNP3FUNC].alias = "dnp3.func"; + sigmatch_table[DETECT_AL_DNP3FUNC].desc = + "match on the application function code found in DNP3 request and responses"; + sigmatch_table[DETECT_AL_DNP3FUNC].url = "/rules/dnp3-keywords.html#dnp3-func"; + sigmatch_table[DETECT_AL_DNP3FUNC].Match = NULL; sigmatch_table[DETECT_AL_DNP3FUNC].AppLayerTxMatch = DetectDNP3FuncMatch; - sigmatch_table[DETECT_AL_DNP3FUNC].Setup = DetectDNP3FuncSetup; - sigmatch_table[DETECT_AL_DNP3FUNC].Free = DetectDNP3Free; + sigmatch_table[DETECT_AL_DNP3FUNC].Setup = DetectDNP3FuncSetup; + sigmatch_table[DETECT_AL_DNP3FUNC].Free = DetectDNP3Free; #ifdef UNITTESTS - sigmatch_table[DETECT_AL_DNP3FUNC].RegisterTests = - DetectDNP3FuncRegisterTests; + sigmatch_table[DETECT_AL_DNP3FUNC].RegisterTests = DetectDNP3FuncRegisterTests; #endif SCReturn; } @@ -472,17 +439,17 @@ static void DetectDNP3IndRegister(void) { SCEnter(); - sigmatch_table[DETECT_AL_DNP3IND].name = "dnp3_ind"; - sigmatch_table[DETECT_AL_DNP3IND].alias = "dnp3.ind"; - sigmatch_table[DETECT_AL_DNP3IND].desc = "match on the DNP3 internal indicator flags in the response application header"; - sigmatch_table[DETECT_AL_DNP3IND].url = "/rules/dnp3-keywords.html#dnp3-ind"; - sigmatch_table[DETECT_AL_DNP3IND].Match = NULL; + sigmatch_table[DETECT_AL_DNP3IND].name = "dnp3_ind"; + sigmatch_table[DETECT_AL_DNP3IND].alias = "dnp3.ind"; + sigmatch_table[DETECT_AL_DNP3IND].desc = + "match on the DNP3 internal indicator flags in the response application header"; + sigmatch_table[DETECT_AL_DNP3IND].url = "/rules/dnp3-keywords.html#dnp3-ind"; + sigmatch_table[DETECT_AL_DNP3IND].Match = NULL; sigmatch_table[DETECT_AL_DNP3IND].AppLayerTxMatch = DetectDNP3IndMatch; - sigmatch_table[DETECT_AL_DNP3IND].Setup = DetectDNP3IndSetup; - sigmatch_table[DETECT_AL_DNP3IND].Free = DetectDNP3Free; + sigmatch_table[DETECT_AL_DNP3IND].Setup = DetectDNP3IndSetup; + sigmatch_table[DETECT_AL_DNP3IND].Free = DetectDNP3Free; #ifdef UNITTESTS - sigmatch_table[DETECT_AL_DNP3IND].RegisterTests = - DetectDNP3IndRegisterTests; + sigmatch_table[DETECT_AL_DNP3IND].RegisterTests = DetectDNP3IndRegisterTests; #endif SCReturn; } @@ -491,17 +458,16 @@ static void DetectDNP3ObjRegister(void) { SCEnter(); - sigmatch_table[DETECT_AL_DNP3OBJ].name = "dnp3_obj"; - sigmatch_table[DETECT_AL_DNP3OBJ].alias = "dnp3.obj"; - sigmatch_table[DETECT_AL_DNP3OBJ].desc = "match on the DNP3 application data objects"; - sigmatch_table[DETECT_AL_DNP3OBJ].url = "/rules/dnp3-keywords.html#dnp3-obj"; - sigmatch_table[DETECT_AL_DNP3OBJ].Match = NULL; + sigmatch_table[DETECT_AL_DNP3OBJ].name = "dnp3_obj"; + sigmatch_table[DETECT_AL_DNP3OBJ].alias = "dnp3.obj"; + sigmatch_table[DETECT_AL_DNP3OBJ].desc = "match on the DNP3 application data objects"; + sigmatch_table[DETECT_AL_DNP3OBJ].url = "/rules/dnp3-keywords.html#dnp3-obj"; + sigmatch_table[DETECT_AL_DNP3OBJ].Match = NULL; sigmatch_table[DETECT_AL_DNP3OBJ].AppLayerTxMatch = DetectDNP3ObjMatch; - sigmatch_table[DETECT_AL_DNP3OBJ].Setup = DetectDNP3ObjSetup; - sigmatch_table[DETECT_AL_DNP3OBJ].Free = DetectDNP3Free; + sigmatch_table[DETECT_AL_DNP3OBJ].Setup = DetectDNP3ObjSetup; + sigmatch_table[DETECT_AL_DNP3OBJ].Free = DetectDNP3Free; #ifdef UNITTESTS - sigmatch_table[DETECT_AL_DNP3OBJ].RegisterTests = - DetectDNP3ObjRegisterTests; + sigmatch_table[DETECT_AL_DNP3OBJ].RegisterTests = DetectDNP3ObjRegisterTests; #endif SCReturn; } @@ -522,28 +488,23 @@ static void DetectDNP3DataRegister(void) { SCEnter(); - sigmatch_table[DETECT_AL_DNP3DATA].name = "dnp3.data"; - sigmatch_table[DETECT_AL_DNP3DATA].alias = "dnp3_data"; - sigmatch_table[DETECT_AL_DNP3DATA].desc = "make the following content options to match on the re-assembled application buffer"; - sigmatch_table[DETECT_AL_DNP3DATA].url = "/rules/dnp3-keywords.html#dnp3-data"; - sigmatch_table[DETECT_AL_DNP3DATA].Setup = DetectDNP3DataSetup; - sigmatch_table[DETECT_AL_DNP3DATA].flags |= SIGMATCH_NOOPT|SIGMATCH_INFO_STICKY_BUFFER; - - DetectAppLayerInspectEngineRegister2("dnp3_data", - ALPROTO_DNP3, SIG_FLAG_TOSERVER, 0, - DetectEngineInspectBufferGeneric, - GetDNP3Data); - DetectAppLayerMpmRegister2("dnp3_data", SIG_FLAG_TOSERVER, 2, - PrefilterGenericMpmRegister, GetDNP3Data, - ALPROTO_DNP3, 0); - - DetectAppLayerInspectEngineRegister2("dnp3_data", - ALPROTO_DNP3, SIG_FLAG_TOCLIENT, 0, - DetectEngineInspectBufferGeneric, - GetDNP3Data); - DetectAppLayerMpmRegister2("dnp3_data", SIG_FLAG_TOCLIENT, 2, - PrefilterGenericMpmRegister, GetDNP3Data, - ALPROTO_DNP3, 0); + sigmatch_table[DETECT_AL_DNP3DATA].name = "dnp3.data"; + sigmatch_table[DETECT_AL_DNP3DATA].alias = "dnp3_data"; + sigmatch_table[DETECT_AL_DNP3DATA].desc = + "make the following content options to match on the re-assembled application buffer"; + sigmatch_table[DETECT_AL_DNP3DATA].url = "/rules/dnp3-keywords.html#dnp3-data"; + sigmatch_table[DETECT_AL_DNP3DATA].Setup = DetectDNP3DataSetup; + sigmatch_table[DETECT_AL_DNP3DATA].flags |= SIGMATCH_NOOPT | SIGMATCH_INFO_STICKY_BUFFER; + + DetectAppLayerInspectEngineRegister2("dnp3_data", ALPROTO_DNP3, SIG_FLAG_TOSERVER, 0, + DetectEngineInspectBufferGeneric, GetDNP3Data); + DetectAppLayerMpmRegister2("dnp3_data", SIG_FLAG_TOSERVER, 2, PrefilterGenericMpmRegister, + GetDNP3Data, ALPROTO_DNP3, 0); + + DetectAppLayerInspectEngineRegister2("dnp3_data", ALPROTO_DNP3, SIG_FLAG_TOCLIENT, 0, + DetectEngineInspectBufferGeneric, GetDNP3Data); + DetectAppLayerMpmRegister2("dnp3_data", SIG_FLAG_TOCLIENT, 2, PrefilterGenericMpmRegister, + GetDNP3Data, ALPROTO_DNP3, 0); g_dnp3_data_buffer_id = DetectBufferTypeGetByName("dnp3_data"); SCReturn; @@ -564,7 +525,6 @@ void DetectDNP3Register(void) "dnp3", ALPROTO_DNP3, SIG_FLAG_TOCLIENT, 0, DetectEngineInspectGenericList, NULL); g_dnp3_match_buffer_id = DetectBufferTypeRegister("dnp3"); - } #ifdef UNITTESTS @@ -711,17 +671,14 @@ static int DetectDNP3ObjParseTest(void) static void DetectDNP3FuncRegisterTests(void) { - UtRegisterTest("DetectDNP3FuncParseFunctionCodeTest", - DetectDNP3FuncParseFunctionCodeTest); + UtRegisterTest("DetectDNP3FuncParseFunctionCodeTest", DetectDNP3FuncParseFunctionCodeTest); UtRegisterTest("DetectDNP3FuncTest01", DetectDNP3FuncTest01); } static void DetectDNP3IndRegisterTests(void) { - UtRegisterTest("DetectDNP3IndTestParseAsInteger", - DetectDNP3IndTestParseAsInteger); - UtRegisterTest("DetectDNP3IndTestParseByName", - DetectDNP3IndTestParseByName); + UtRegisterTest("DetectDNP3IndTestParseAsInteger", DetectDNP3IndTestParseAsInteger); + UtRegisterTest("DetectDNP3IndTestParseByName", DetectDNP3IndTestParseByName); } static void DetectDNP3ObjRegisterTests(void) diff --git a/src/detect-dnp3.h b/src/detect-dnp3.h index 7479d7841aa2..518a483d7373 100644 --- a/src/detect-dnp3.h +++ b/src/detect-dnp3.h @@ -22,8 +22,8 @@ * Struct for mapping symbolic names to values. */ typedef struct DNP3Mapping_ { - const char *name; - uint16_t value; + const char *name; + uint16_t value; } DNP3Mapping; /* Map of internal indicators to value for external use. */ diff --git a/src/detect-dns-opcode.c b/src/detect-dns-opcode.c index 853b01f0097d..6adb91586042 100644 --- a/src/detect-dns-opcode.c +++ b/src/detect-dns-opcode.c @@ -26,8 +26,7 @@ static int dns_opcode_list_id = 0; static void DetectDnsOpcodeFree(DetectEngineCtx *, void *ptr); -static int DetectDnsOpcodeSetup(DetectEngineCtx *de_ctx, Signature *s, - const char *str) +static int DetectDnsOpcodeSetup(DetectEngineCtx *de_ctx, Signature *s, const char *str) { SCEnter(); @@ -62,22 +61,20 @@ static void DetectDnsOpcodeFree(DetectEngineCtx *de_ctx, void *ptr) SCReturn; } -static int DetectDnsOpcodeMatch(DetectEngineThreadCtx *det_ctx, - Flow *f, uint8_t flags, void *state, void *txv, const Signature *s, - const SigMatchCtx *ctx) +static int DetectDnsOpcodeMatch(DetectEngineThreadCtx *det_ctx, Flow *f, uint8_t flags, void *state, + void *txv, const Signature *s, const SigMatchCtx *ctx) { return rs_dns_opcode_match(txv, (void *)ctx, flags); } void DetectDnsOpcodeRegister(void) { - sigmatch_table[DETECT_AL_DNS_OPCODE].name = "dns.opcode"; - sigmatch_table[DETECT_AL_DNS_OPCODE].desc = "Match the DNS header opcode flag."; + sigmatch_table[DETECT_AL_DNS_OPCODE].name = "dns.opcode"; + sigmatch_table[DETECT_AL_DNS_OPCODE].desc = "Match the DNS header opcode flag."; sigmatch_table[DETECT_AL_DNS_OPCODE].Setup = DetectDnsOpcodeSetup; - sigmatch_table[DETECT_AL_DNS_OPCODE].Free = DetectDnsOpcodeFree; + sigmatch_table[DETECT_AL_DNS_OPCODE].Free = DetectDnsOpcodeFree; sigmatch_table[DETECT_AL_DNS_OPCODE].Match = NULL; - sigmatch_table[DETECT_AL_DNS_OPCODE].AppLayerTxMatch = - DetectDnsOpcodeMatch; + sigmatch_table[DETECT_AL_DNS_OPCODE].AppLayerTxMatch = DetectDnsOpcodeMatch; DetectAppLayerInspectEngineRegister2( "dns.opcode", ALPROTO_DNS, SIG_FLAG_TOSERVER, 0, DetectEngineInspectGenericList, NULL); diff --git a/src/detect-dns-query.c b/src/detect-dns-query.c index 6578762f6a6a..fa614fcd52c0 100644 --- a/src/detect-dns-query.c +++ b/src/detect-dns-query.c @@ -21,7 +21,6 @@ * @{ */ - /** * \file * @@ -61,7 +60,7 @@ #include "util-unittest-helper.h" #include "rust.h" -static int DetectDnsQuerySetup (DetectEngineCtx *, Signature *, const char *); +static int DetectDnsQuerySetup(DetectEngineCtx *, Signature *, const char *); #ifdef UNITTESTS static void DetectDnsQueryRegisterTests(void); #endif @@ -107,8 +106,11 @@ static uint8_t DetectEngineInspectDnsQuery(DetectEngineCtx *de_ctx, DetectEngine transforms = engine->v2.transforms; } - while(1) { - struct DnsQueryGetDataArgs cbdata = { local_id, txv, }; + while (1) { + struct DnsQueryGetDataArgs cbdata = { + local_id, + txv, + }; InspectionBuffer *buffer = DnsQueryGetData(det_ctx, transforms, f, &cbdata, engine->sm_list); if (buffer == NULL || buffer->inspect == NULL) @@ -149,7 +151,7 @@ static void PrefilterTxDnsQuery(DetectEngineThreadCtx *det_ctx, const void *pect const int list_id = ctx->list_id; uint32_t local_id = 0; - while(1) { + while (1) { // loop until we get a NULL struct DnsQueryGetDataArgs cbdata = { local_id, txv }; @@ -182,15 +184,14 @@ static int PrefilterMpmDnsQueryRegister(DetectEngineCtx *de_ctx, SigGroupHead *s pectx->mpm_ctx = mpm_ctx; pectx->transforms = &mpm_reg->transforms; - return PrefilterAppendTxEngine(de_ctx, sgh, PrefilterTxDnsQuery, - mpm_reg->app_v2.alproto, mpm_reg->app_v2.tx_min_progress, - pectx, PrefilterMpmDnsQueryFree, mpm_reg->pname); + return PrefilterAppendTxEngine(de_ctx, sgh, PrefilterTxDnsQuery, mpm_reg->app_v2.alproto, + mpm_reg->app_v2.tx_min_progress, pectx, PrefilterMpmDnsQueryFree, mpm_reg->pname); } /** * \brief Registration function for keyword: dns_query */ -void DetectDnsQueryRegister (void) +void DetectDnsQueryRegister(void) { sigmatch_table[DETECT_AL_DNS_QUERY].name = "dns.query"; sigmatch_table[DETECT_AL_DNS_QUERY].alias = "dns_query"; @@ -203,16 +204,13 @@ void DetectDnsQueryRegister (void) sigmatch_table[DETECT_AL_DNS_QUERY].flags |= SIGMATCH_NOOPT; sigmatch_table[DETECT_AL_DNS_QUERY].flags |= SIGMATCH_INFO_STICKY_BUFFER; - DetectAppLayerMpmRegister2("dns_query", SIG_FLAG_TOSERVER, 2, - PrefilterMpmDnsQueryRegister, NULL, - ALPROTO_DNS, 1); + DetectAppLayerMpmRegister2( + "dns_query", SIG_FLAG_TOSERVER, 2, PrefilterMpmDnsQueryRegister, NULL, ALPROTO_DNS, 1); - DetectAppLayerInspectEngineRegister2("dns_query", - ALPROTO_DNS, SIG_FLAG_TOSERVER, 1, - DetectEngineInspectDnsQuery, NULL); + DetectAppLayerInspectEngineRegister2( + "dns_query", ALPROTO_DNS, SIG_FLAG_TOSERVER, 1, DetectEngineInspectDnsQuery, NULL); - DetectBufferTypeSetDescriptionByName("dns_query", - "dns request query"); + DetectBufferTypeSetDescriptionByName("dns_query", "dns request query"); DetectBufferTypeSupportsMultiInstance("dns_query"); g_dns_query_buffer_id = DetectBufferTypeGetByName("dns_query"); @@ -224,14 +222,11 @@ void DetectDnsQueryRegister (void) DetectAppLayerInspectEngineRegister2("dns_response", ALPROTO_DNS, SIG_FLAG_TOCLIENT, 1, DetectEngineInspectGenericList, NULL); - DetectBufferTypeSetDescriptionByName("dns_request", - "dns requests"); - DetectBufferTypeSetDescriptionByName("dns_response", - "dns responses"); + DetectBufferTypeSetDescriptionByName("dns_request", "dns requests"); + DetectBufferTypeSetDescriptionByName("dns_response", "dns responses"); #endif } - /** * \brief setup the dns_query sticky buffer keyword used in the rule * @@ -278,9 +273,7 @@ static int DetectDnsQueryTest01(void) memset(&tv, 0, sizeof(ThreadVars)); memset(&f, 0, sizeof(Flow)); - p = UTHBuildPacketReal(buf, sizeof(buf), IPPROTO_UDP, - "192.168.1.5", "192.168.1.1", - 41424, 53); + p = UTHBuildPacketReal(buf, sizeof(buf), IPPROTO_UDP, "192.168.1.5", "192.168.1.1", 41424, 53); FLOW_INITIALIZE(&f); f.flags |= FLOW_IPV4; @@ -298,15 +291,14 @@ static int DetectDnsQueryTest01(void) de_ctx->flags |= DE_QUIET; s = DetectEngineAppendSig(de_ctx, "alert dns any any -> any any " - "(msg:\"Test dns_query option\"; " - "dns_query; content:\"google\"; nocase; sid:1;)"); + "(msg:\"Test dns_query option\"; " + "dns_query; content:\"google\"; nocase; sid:1;)"); FAIL_IF_NULL(s); SigGroupBuild(de_ctx); DetectEngineThreadCtxInit(&tv, (void *)de_ctx, (void *)&det_ctx); - int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DNS, - STREAM_TOSERVER, buf, sizeof(buf)); + int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DNS, STREAM_TOSERVER, buf, sizeof(buf)); if (r != 0) { printf("toserver chunk 1 returned %" PRId32 ", expected 0: ", r); FAIL; @@ -386,15 +378,12 @@ static int DetectDnsQueryTest02(void) memset(&tv, 0, sizeof(ThreadVars)); memset(&f, 0, sizeof(Flow)); - p1 = UTHBuildPacketReal(buf1, sizeof(buf1), IPPROTO_UDP, - "192.168.1.5", "192.168.1.1", - 41424, 53); - p2 = UTHBuildPacketReal(buf1, sizeof(buf1), IPPROTO_UDP, - "192.168.1.5", "192.168.1.1", - 41424, 53); - p3 = UTHBuildPacketReal(buf1, sizeof(buf1), IPPROTO_UDP, - "192.168.1.5", "192.168.1.1", - 41424, 53); + p1 = UTHBuildPacketReal( + buf1, sizeof(buf1), IPPROTO_UDP, "192.168.1.5", "192.168.1.1", 41424, 53); + p2 = UTHBuildPacketReal( + buf1, sizeof(buf1), IPPROTO_UDP, "192.168.1.5", "192.168.1.1", 41424, 53); + p3 = UTHBuildPacketReal( + buf1, sizeof(buf1), IPPROTO_UDP, "192.168.1.5", "192.168.1.1", 41424, 53); FLOW_INITIALIZE(&f); f.flags |= FLOW_IPV4; @@ -423,19 +412,19 @@ static int DetectDnsQueryTest02(void) de_ctx->flags |= DE_QUIET; s = DetectEngineAppendSig(de_ctx, "alert dns any any -> any any " - "(msg:\"Test dns_query option\"; " - "dns_query; content:\"google.com\"; nocase; sid:1;)"); + "(msg:\"Test dns_query option\"; " + "dns_query; content:\"google.com\"; nocase; sid:1;)"); FAIL_IF_NULL(s); s = DetectEngineAppendSig(de_ctx, "alert dns any any -> any any " - "(msg:\"Test dns_query option\"; " - "dns_query; content:\"google.net\"; nocase; sid:2;)"); + "(msg:\"Test dns_query option\"; " + "dns_query; content:\"google.net\"; nocase; sid:2;)"); FAIL_IF_NULL(s); SigGroupBuild(de_ctx); DetectEngineThreadCtxInit(&tv, (void *)de_ctx, (void *)&det_ctx); - int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DNS, - STREAM_TOSERVER, buf1, sizeof(buf1)); + int r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_DNS, STREAM_TOSERVER, buf1, sizeof(buf1)); if (r != 0) { printf("toserver chunk 1 returned %" PRId32 ", expected 0: ", r); FAIL; @@ -456,8 +445,7 @@ static int DetectDnsQueryTest02(void) FAIL; } - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DNS, STREAM_TOCLIENT, - buf2, sizeof(buf2)); + r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DNS, STREAM_TOCLIENT, buf2, sizeof(buf2)); if (r != 0) { printf("toserver client 1 returned %" PRId32 ", expected 0: ", r); FAIL; @@ -475,8 +463,7 @@ static int DetectDnsQueryTest02(void) FAIL; } - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DNS, STREAM_TOSERVER, - buf3, sizeof(buf3)); + r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DNS, STREAM_TOSERVER, buf3, sizeof(buf3)); if (r != 0) { printf("toserver chunk 3 returned %" PRId32 ", expected 0: ", r); FAIL; @@ -535,9 +522,7 @@ static int DetectDnsQueryTest03(void) memset(&f, 0, sizeof(Flow)); memset(&ssn, 0, sizeof(TcpSession)); - p = UTHBuildPacketReal(buf, sizeof(buf), IPPROTO_TCP, - "192.168.1.5", "192.168.1.1", - 41424, 53); + p = UTHBuildPacketReal(buf, sizeof(buf), IPPROTO_TCP, "192.168.1.5", "192.168.1.1", 41424, 53); FLOW_INITIALIZE(&f); f.protoctx = (void *)&ssn; @@ -546,8 +531,8 @@ static int DetectDnsQueryTest03(void) f.protomap = FlowGetProtoMapping(f.proto); p->flow = &f; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; - p->flowflags |= FLOW_PKT_TOSERVER|FLOW_PKT_ESTABLISHED; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; + p->flowflags |= FLOW_PKT_TOSERVER | FLOW_PKT_ESTABLISHED; f.alproto = ALPROTO_DNS; StreamTcpInitConfig(true); @@ -558,15 +543,14 @@ static int DetectDnsQueryTest03(void) de_ctx->flags |= DE_QUIET; s = DetectEngineAppendSig(de_ctx, "alert dns any any -> any any " - "(msg:\"Test dns_query option\"; " - "dns_query; content:\"google\"; nocase; sid:1;)"); + "(msg:\"Test dns_query option\"; " + "dns_query; content:\"google\"; nocase; sid:1;)"); FAIL_IF_NULL(s); SigGroupBuild(de_ctx); DetectEngineThreadCtxInit(&tv, (void *)de_ctx, (void *)&det_ctx); - int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DNS, - STREAM_TOSERVER, buf, sizeof(buf)); + int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DNS, STREAM_TOSERVER, buf, sizeof(buf)); if (r != 0) { printf("toserver chunk 1 returned %" PRId32 ", expected 0: ", r); FAIL; @@ -598,7 +582,6 @@ static int DetectDnsQueryTest03(void) PASS; } - /** \test simple google.com query matching, pcre */ static int DetectDnsQueryTest04(void) { @@ -621,9 +604,7 @@ static int DetectDnsQueryTest04(void) memset(&tv, 0, sizeof(ThreadVars)); memset(&f, 0, sizeof(Flow)); - p = UTHBuildPacketReal(buf, sizeof(buf), IPPROTO_UDP, - "192.168.1.5", "192.168.1.1", - 41424, 53); + p = UTHBuildPacketReal(buf, sizeof(buf), IPPROTO_UDP, "192.168.1.5", "192.168.1.1", 41424, 53); FLOW_INITIALIZE(&f); f.flags |= FLOW_IPV4; @@ -641,9 +622,9 @@ static int DetectDnsQueryTest04(void) de_ctx->flags |= DE_QUIET; s = DetectEngineAppendSig(de_ctx, "alert dns any any -> any any " - "(msg:\"Test dns_query option\"; " - "dns_query; content:\"google\"; nocase; " - "pcre:\"/google\\.com$/i\"; sid:1;)"); + "(msg:\"Test dns_query option\"; " + "dns_query; content:\"google\"; nocase; " + "pcre:\"/google\\.com$/i\"; sid:1;)"); FAIL_IF_NULL(s); s = DetectEngineAppendSig(de_ctx, "alert dns any any -> any any " "(msg:\"Test dns_query option\"; " @@ -654,8 +635,7 @@ static int DetectDnsQueryTest04(void) SigGroupBuild(de_ctx); DetectEngineThreadCtxInit(&tv, (void *)de_ctx, (void *)&det_ctx); - int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DNS, - STREAM_TOSERVER, buf, sizeof(buf)); + int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DNS, STREAM_TOSERVER, buf, sizeof(buf)); if (r != 0) { printf("toserver chunk 1 returned %" PRId32 ", expected 0: ", r); FAIL; @@ -740,15 +720,12 @@ static int DetectDnsQueryTest05(void) memset(&tv, 0, sizeof(ThreadVars)); memset(&f, 0, sizeof(Flow)); - p1 = UTHBuildPacketReal(buf1, sizeof(buf1), IPPROTO_UDP, - "192.168.1.5", "192.168.1.1", - 41424, 53); - p2 = UTHBuildPacketReal(buf2, sizeof(buf2), IPPROTO_UDP, - "192.168.1.5", "192.168.1.1", - 41424, 53); - p3 = UTHBuildPacketReal(buf3, sizeof(buf3), IPPROTO_UDP, - "192.168.1.5", "192.168.1.1", - 41424, 53); + p1 = UTHBuildPacketReal( + buf1, sizeof(buf1), IPPROTO_UDP, "192.168.1.5", "192.168.1.1", 41424, 53); + p2 = UTHBuildPacketReal( + buf2, sizeof(buf2), IPPROTO_UDP, "192.168.1.5", "192.168.1.1", 41424, 53); + p3 = UTHBuildPacketReal( + buf3, sizeof(buf3), IPPROTO_UDP, "192.168.1.5", "192.168.1.1", 41424, 53); FLOW_INITIALIZE(&f); f.flags |= FLOW_IPV4; @@ -777,23 +754,23 @@ static int DetectDnsQueryTest05(void) de_ctx->flags |= DE_QUIET; s = DetectEngineAppendSig(de_ctx, "alert dns any any -> any any " - "(msg:\"Test dns_query option\"; " - "dns_query; content:\"google.com\"; nocase; sid:1;)"); + "(msg:\"Test dns_query option\"; " + "dns_query; content:\"google.com\"; nocase; sid:1;)"); FAIL_IF_NULL(s); s = DetectEngineAppendSig(de_ctx, "alert dns any any -> any any " - "(msg:\"Test dns_query option\"; " - "dns_query; content:\"google.net\"; nocase; sid:2;)"); + "(msg:\"Test dns_query option\"; " + "dns_query; content:\"google.net\"; nocase; sid:2;)"); FAIL_IF_NULL(s); s = DetectEngineAppendSig(de_ctx, "alert dns any any -> any any " - "(msg:\"Test Z flag event\"; " - "app-layer-event:dns.z_flag_set; sid:3;)"); + "(msg:\"Test Z flag event\"; " + "app-layer-event:dns.z_flag_set; sid:3;)"); FAIL_IF_NULL(s); SigGroupBuild(de_ctx); DetectEngineThreadCtxInit(&tv, (void *)de_ctx, (void *)&det_ctx); - int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DNS, - STREAM_TOSERVER, buf1, sizeof(buf1)); + int r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_DNS, STREAM_TOSERVER, buf1, sizeof(buf1)); if (r != 0) { printf("toserver chunk 1 returned %" PRId32 ", expected 0: ", r); FAIL; @@ -814,8 +791,7 @@ static int DetectDnsQueryTest05(void) FAIL; } - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DNS, STREAM_TOCLIENT, - buf2, sizeof(buf2)); + r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DNS, STREAM_TOCLIENT, buf2, sizeof(buf2)); if (r != 0) { printf("toserver client 1 returned %" PRId32 ", expected 0\n", r); FAIL; @@ -837,8 +813,7 @@ static int DetectDnsQueryTest05(void) FAIL; } - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DNS, STREAM_TOSERVER, - buf3, sizeof(buf3)); + r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DNS, STREAM_TOSERVER, buf3, sizeof(buf3)); if (r != 0) { printf("toserver chunk 3 returned %" PRId32 ", expected 0: ", r); FAIL; diff --git a/src/detect-dns-query.h b/src/detect-dns-query.h index c894b878dbfb..a041ff1f27e9 100644 --- a/src/detect-dns-query.h +++ b/src/detect-dns-query.h @@ -24,6 +24,6 @@ #ifndef __DETECT_DNS_QUERY_H__ #define __DETECT_DNS_QUERY_H__ -void DetectDnsQueryRegister (void); +void DetectDnsQueryRegister(void); #endif /* __DETECT_DNS_QUERY_H__ */ diff --git a/src/detect-dsize.c b/src/detect-dsize.c index 9ef427a1b6ab..17ad24bc621c 100644 --- a/src/detect-dsize.c +++ b/src/detect-dsize.c @@ -44,9 +44,9 @@ #include "host.h" #include "util-profiling.h" -static int DetectDsizeMatch (DetectEngineThreadCtx *, Packet *, - const Signature *, const SigMatchCtx *); -static int DetectDsizeSetup (DetectEngineCtx *, Signature *s, const char *str); +static int DetectDsizeMatch( + DetectEngineThreadCtx *, Packet *, const Signature *, const SigMatchCtx *); +static int DetectDsizeSetup(DetectEngineCtx *, Signature *s, const char *str); #ifdef UNITTESTS static void DsizeRegisterTests(void); #endif @@ -58,14 +58,14 @@ static bool PrefilterDsizeIsPrefilterable(const Signature *s); /** * \brief Registration function for dsize: keyword */ -void DetectDsizeRegister (void) +void DetectDsizeRegister(void) { sigmatch_table[DETECT_DSIZE].name = "dsize"; sigmatch_table[DETECT_DSIZE].desc = "match on the size of the packet payload"; sigmatch_table[DETECT_DSIZE].url = "/rules/payload-keywords.html#dsize"; sigmatch_table[DETECT_DSIZE].Match = DetectDsizeMatch; sigmatch_table[DETECT_DSIZE].Setup = DetectDsizeSetup; - sigmatch_table[DETECT_DSIZE].Free = DetectDsizeFree; + sigmatch_table[DETECT_DSIZE].Free = DetectDsizeFree; #ifdef UNITTESTS sigmatch_table[DETECT_DSIZE].RegisterTests = DsizeRegisterTests; #endif @@ -86,8 +86,8 @@ void DetectDsizeRegister (void) * \retval 0 no match * \retval 1 match */ -static int DetectDsizeMatch (DetectEngineThreadCtx *det_ctx, Packet *p, - const Signature *s, const SigMatchCtx *ctx) +static int DetectDsizeMatch( + DetectEngineThreadCtx *det_ctx, Packet *p, const Signature *s, const SigMatchCtx *ctx) { SCEnter(); int ret = 0; @@ -98,7 +98,7 @@ static int DetectDsizeMatch (DetectEngineThreadCtx *det_ctx, Packet *p, const DetectU16Data *dd = (const DetectU16Data *)ctx; - SCLogDebug("p->payload_len %"PRIu16"", p->payload_len); + SCLogDebug("p->payload_len %" PRIu16 "", p->payload_len); ret = DetectU16Match(p->payload_len, dd); @@ -116,7 +116,7 @@ static int DetectDsizeMatch (DetectEngineThreadCtx *det_ctx, Packet *p, * \retval 0 on Success * \retval -1 on Failure */ -static int DetectDsizeSetup (DetectEngineCtx *de_ctx, Signature *s, const char *rawstr) +static int DetectDsizeSetup(DetectEngineCtx *de_ctx, Signature *s, const char *rawstr) { DetectU16Data *dd = NULL; @@ -172,8 +172,7 @@ void DetectDsizeFree(DetectEngineCtx *de_ctx, void *de_ptr) /* prefilter code */ -static void -PrefilterPacketDsizeMatch(DetectEngineThreadCtx *det_ctx, Packet *p, const void *pectx) +static void PrefilterPacketDsizeMatch(DetectEngineThreadCtx *det_ctx, Packet *p, const void *pectx) { if (PKT_IS_PSEUDOPKT(p)) { SCReturn; @@ -204,7 +203,7 @@ static int PrefilterSetupDsize(DetectEngineCtx *de_ctx, SigGroupHead *sgh) static bool PrefilterDsizeIsPrefilterable(const Signature *s) { const SigMatch *sm; - for (sm = s->init_data->smlists[DETECT_SM_LIST_MATCH] ; sm != NULL; sm = sm->next) { + for (sm = s->init_data->smlists[DETECT_SM_LIST_MATCH]; sm != NULL; sm = sm->next) { switch (sm->type) { case DETECT_DSIZE: return true; @@ -344,7 +343,7 @@ void SigParseApplyDsizeToContent(Signature *s) } SigMatch *sm = s->init_data->smlists[DETECT_SM_LIST_PMATCH]; - for ( ; sm != NULL; sm = sm->next) { + for (; sm != NULL; sm = sm->next) { if (sm->type != DETECT_CONTENT) { continue; } @@ -358,7 +357,8 @@ void SigParseApplyDsizeToContent(Signature *s) cd->flags |= DETECT_CONTENT_DEPTH; cd->depth = (uint16_t)dsize; SCLogDebug("updated %u, content %u to have depth %u " - "because of dsize.", s->id, cd->id, cd->depth); + "because of dsize.", + s->id, cd->id, cd->depth); } } } diff --git a/src/detect-dsize.h b/src/detect-dsize.h index c262a31186fe..b7bd0d7b0b46 100644 --- a/src/detect-dsize.h +++ b/src/detect-dsize.h @@ -27,7 +27,7 @@ #include "detect-engine-uint.h" /* prototypes */ -void DetectDsizeRegister (void); +void DetectDsizeRegister(void); int SigParseMaxRequiredDsize(const Signature *s); int SigParseGetMaxDsize(const Signature *s); @@ -51,4 +51,3 @@ static inline bool SigDsizePrefilter(const Packet *p, const Signature *s, uint32 } #endif /* __DETECT_DSIZE_H__ */ - diff --git a/src/detect-engine-address-ipv4.c b/src/detect-engine-address-ipv4.c index 80d29012988f..df0046afdb20 100644 --- a/src/detect-engine-address-ipv4.c +++ b/src/detect-engine-address-ipv4.c @@ -110,8 +110,8 @@ int DetectAddressCmpIPv4(DetectAddress *a, DetectAddress *b) * \retval 0 On success. * \retval -1 On failure. */ -int DetectAddressCutIPv4(DetectEngineCtx *de_ctx, DetectAddress *a, - DetectAddress *b, DetectAddress **c) +int DetectAddressCutIPv4( + DetectEngineCtx *de_ctx, DetectAddress *a, DetectAddress *b, DetectAddress **c) { uint32_t a_ip1 = SCNtohl(a->ip.addr_data32[0]); uint32_t a_ip2 = SCNtohl(a->ip2.addr_data32[0]); @@ -143,10 +143,10 @@ int DetectAddressCutIPv4(DetectEngineCtx *de_ctx, DetectAddress *a, if (r == ADDRESS_LE) { SCLogDebug("DetectAddressCutIPv4: r == ADDRESS_LE"); - a->ip.addr_data32[0] = htonl(a_ip1); + a->ip.addr_data32[0] = htonl(a_ip1); a->ip2.addr_data32[0] = htonl(b_ip1 - 1); - b->ip.addr_data32[0] = htonl(b_ip1); + b->ip.addr_data32[0] = htonl(b_ip1); b->ip2.addr_data32[0] = htonl(a_ip2); tmp_c = DetectAddressInit(); @@ -158,11 +158,11 @@ int DetectAddressCutIPv4(DetectEngineCtx *de_ctx, DetectAddress *a, tmp_c->ip2.addr_data32[0] = htonl(b_ip2); *c = tmp_c; - /* we have 3 parts: [bbb[baba]aaa] - * part a: b_ip1 <-> a_ip1 - 1 - * part b: a_ip1 <-> b_ip2 - * part c: b_ip2 + 1 <-> a_ip2 - */ + /* we have 3 parts: [bbb[baba]aaa] + * part a: b_ip1 <-> a_ip1 - 1 + * part b: a_ip1 <-> b_ip2 + * part c: b_ip2 + 1 <-> a_ip2 + */ } else if (r == ADDRESS_GE) { SCLogDebug("DetectAddressCutIPv4: r == ADDRESS_GE"); @@ -177,7 +177,7 @@ int DetectAddressCutIPv4(DetectEngineCtx *de_ctx, DetectAddress *a, goto error; tmp_c->ip.family = AF_INET; - tmp_c->ip.addr_data32[0] = htonl(b_ip2 + 1); + tmp_c->ip.addr_data32[0] = htonl(b_ip2 + 1); tmp_c->ip2.addr_data32[0] = htonl(a_ip2); *c = tmp_c; @@ -212,19 +212,19 @@ int DetectAddressCutIPv4(DetectEngineCtx *de_ctx, DetectAddress *a, } else if (a_ip2 == b_ip2) { SCLogDebug("DetectAddressCutIPv4: 2"); - a->ip.addr_data32[0] = htonl(b_ip1); + a->ip.addr_data32[0] = htonl(b_ip1); a->ip2.addr_data32[0] = htonl(a_ip1 - 1); - b->ip.addr_data32[0] = htonl(a_ip1); + b->ip.addr_data32[0] = htonl(a_ip1); b->ip2.addr_data32[0] = htonl(a_ip2); } else { SCLogDebug("3"); - a->ip.addr_data32[0] = htonl(b_ip1); + a->ip.addr_data32[0] = htonl(b_ip1); a->ip2.addr_data32[0] = htonl(a_ip1 - 1); - b->ip.addr_data32[0] = htonl(a_ip1); + b->ip.addr_data32[0] = htonl(a_ip1); b->ip2.addr_data32[0] = htonl(a_ip2); tmp_c = DetectAddressInit(); @@ -266,10 +266,10 @@ int DetectAddressCutIPv4(DetectEngineCtx *de_ctx, DetectAddress *a, } else if (a_ip2 == b_ip2) { SCLogDebug("DetectAddressCutIPv4: 2"); - a->ip.addr_data32[0] = htonl(a_ip1); + a->ip.addr_data32[0] = htonl(a_ip1); a->ip2.addr_data32[0] = htonl(b_ip1 - 1); - b->ip.addr_data32[0] = htonl(b_ip1); + b->ip.addr_data32[0] = htonl(b_ip1); b->ip2.addr_data32[0] = htonl(b_ip2); } else { SCLogDebug("DetectAddressCutIPv4: 3"); @@ -330,7 +330,7 @@ int DetectAddressIsCompleteIPSpaceIPv4(DetectAddress *ag) next_ip = htonl(SCNtohl(ag->ip2.addr_data32[0]) + 1); ag = ag->next; - for ( ; ag != NULL; ag = ag->next) { + for (; ag != NULL; ag = ag->next) { if (ag->ip.addr_data32[0] != next_ip) return 0; @@ -375,7 +375,7 @@ int DetectAddressCutNotIPv4(DetectAddress *a, DetectAddress **b) *b = NULL; if (a_ip1 != 0x00000000 && a_ip2 != 0xFFFFFFFF) { - a->ip.addr_data32[0] = htonl(0x00000000); + a->ip.addr_data32[0] = htonl(0x00000000); a->ip2.addr_data32[0] = htonl(a_ip1 - 1); tmp_b = DetectAddressInit(); @@ -383,7 +383,7 @@ int DetectAddressCutNotIPv4(DetectAddress *a, DetectAddress **b) goto error; tmp_b->ip.family = AF_INET; - tmp_b->ip.addr_data32[0] = htonl(a_ip2 + 1); + tmp_b->ip.addr_data32[0] = htonl(a_ip2 + 1); tmp_b->ip2.addr_data32[0] = htonl(0xFFFFFFFF); *b = tmp_b; } else if (a_ip1 == 0x00000000 && a_ip2 != 0xFFFFFFFF) { @@ -394,7 +394,7 @@ int DetectAddressCutNotIPv4(DetectAddress *a, DetectAddress **b) a->ip2.addr_data32[0] = htonl(a_ip1 - 1); } else { goto error; - } + } return 0; @@ -847,7 +847,7 @@ static int DetectAddressIPv4TestAddressCmp01(void) DetectAddressFree(b); return result; - error: +error: DetectAddressFree(a); DetectAddressFree(b); return 0; @@ -859,7 +859,7 @@ static int DetectAddressIPv4IsCompleteIPSpace02(void) struct in_addr in; int result = 1; - if ( (a = DetectAddressInit()) == NULL) + if ((a = DetectAddressInit()) == NULL) goto error; if (inet_pton(AF_INET, "0.0.0.0", &in) < 0) @@ -880,7 +880,7 @@ static int DetectAddressIPv4IsCompleteIPSpace02(void) DetectAddressFree(a); - if ( (a = DetectAddressInit()) == NULL) + if ((a = DetectAddressInit()) == NULL) goto error; if (inet_pton(AF_INET, "0.0.0.0", &in) < 0) @@ -895,7 +895,7 @@ static int DetectAddressIPv4IsCompleteIPSpace02(void) return result; - error: +error: if (a != NULL) DetectAddressFree(a); return 0; @@ -908,7 +908,7 @@ static int DetectAddressIPv4IsCompleteIPSpace03(void) struct in_addr in; int result = 1; - if ( (a = DetectAddressInit()) == NULL) + if ((a = DetectAddressInit()) == NULL) goto error; temp = a; @@ -920,7 +920,7 @@ static int DetectAddressIPv4IsCompleteIPSpace03(void) a->ip2.addr_data32[0] = in.s_addr; result &= (DetectAddressIsCompleteIPSpaceIPv4(a) == 0); - if ( (temp->next = DetectAddressInit()) == NULL) + if ((temp->next = DetectAddressInit()) == NULL) goto error; temp = temp->next; @@ -932,7 +932,7 @@ static int DetectAddressIPv4IsCompleteIPSpace03(void) temp->ip2.addr_data32[0] = in.s_addr; result &= (DetectAddressIsCompleteIPSpaceIPv4(a) == 0); - if ( (temp->next = DetectAddressInit()) == NULL) + if ((temp->next = DetectAddressInit()) == NULL) goto error; temp = temp->next; @@ -944,7 +944,7 @@ static int DetectAddressIPv4IsCompleteIPSpace03(void) temp->ip2.addr_data32[0] = in.s_addr; result &= (DetectAddressIsCompleteIPSpaceIPv4(a) == 0); - if ( (temp->next = DetectAddressInit()) == NULL) + if ((temp->next = DetectAddressInit()) == NULL) goto error; temp = temp->next; @@ -956,7 +956,7 @@ static int DetectAddressIPv4IsCompleteIPSpace03(void) temp->ip2.addr_data32[0] = in.s_addr; result &= (DetectAddressIsCompleteIPSpaceIPv4(a) == 0); - if ( (temp->next = DetectAddressInit()) == NULL) + if ((temp->next = DetectAddressInit()) == NULL) goto error; temp = temp->next; @@ -972,7 +972,7 @@ static int DetectAddressIPv4IsCompleteIPSpace03(void) return result; - error: +error: if (a != NULL) DetectAddressFree(a); return 0; @@ -985,7 +985,7 @@ static int DetectAddressIPv4IsCompleteIPSpace04(void) struct in_addr in; int result = 1; - if ( (a = DetectAddressInit()) == NULL) + if ((a = DetectAddressInit()) == NULL) goto error; temp = a; @@ -997,7 +997,7 @@ static int DetectAddressIPv4IsCompleteIPSpace04(void) a->ip2.addr_data32[0] = in.s_addr; result &= (DetectAddressIsCompleteIPSpaceIPv4(a) == 0); - if ( (temp->next = DetectAddressInit()) == NULL) + if ((temp->next = DetectAddressInit()) == NULL) goto error; temp = temp->next; @@ -1009,7 +1009,7 @@ static int DetectAddressIPv4IsCompleteIPSpace04(void) temp->ip2.addr_data32[0] = in.s_addr; result &= (DetectAddressIsCompleteIPSpaceIPv4(a) == 0); - if ( (temp->next = DetectAddressInit()) == NULL) + if ((temp->next = DetectAddressInit()) == NULL) goto error; temp = temp->next; @@ -1021,7 +1021,7 @@ static int DetectAddressIPv4IsCompleteIPSpace04(void) temp->ip2.addr_data32[0] = in.s_addr; result &= (DetectAddressIsCompleteIPSpaceIPv4(a) == 0); - if ( (temp->next = DetectAddressInit()) == NULL) + if ((temp->next = DetectAddressInit()) == NULL) goto error; temp = temp->next; @@ -1033,7 +1033,7 @@ static int DetectAddressIPv4IsCompleteIPSpace04(void) temp->ip2.addr_data32[0] = in.s_addr; result &= (DetectAddressIsCompleteIPSpaceIPv4(a) == 0); - if ( (temp->next = DetectAddressInit()) == NULL) + if ((temp->next = DetectAddressInit()) == NULL) goto error; temp = temp->next; @@ -1049,7 +1049,7 @@ static int DetectAddressIPv4IsCompleteIPSpace04(void) return result; - error: +error: if (a != NULL) DetectAddressFree(a); return 0; @@ -1062,7 +1062,7 @@ static int DetectAddressIPv4CutNot05(void) struct in_addr in; int result = 1; - if ( (a = DetectAddressInit()) == NULL) + if ((a = DetectAddressInit()) == NULL) return 0; if (inet_pton(AF_INET, "0.0.0.0", &in) < 0) @@ -1078,7 +1078,7 @@ static int DetectAddressIPv4CutNot05(void) DetectAddressFree(b); return result; - error: +error: DetectAddressFree(a); if (b != NULL) DetectAddressFree(b); @@ -1092,7 +1092,7 @@ static int DetectAddressIPv4CutNot06(void) struct in_addr in; int result = 1; - if ( (a = DetectAddressInit()) == NULL) + if ((a = DetectAddressInit()) == NULL) return 0; if (inet_pton(AF_INET, "0.0.0.0", &in) < 0) @@ -1115,7 +1115,7 @@ static int DetectAddressIPv4CutNot06(void) DetectAddressFree(b); return result; - error: +error: DetectAddressFree(a); if (b != NULL) DetectAddressFree(b); @@ -1129,7 +1129,7 @@ static int DetectAddressIPv4CutNot07(void) struct in_addr in; int result = 1; - if ( (a = DetectAddressInit()) == NULL) + if ((a = DetectAddressInit()) == NULL) return 0; if (inet_pton(AF_INET, "1.2.3.4", &in) < 0) @@ -1152,7 +1152,7 @@ static int DetectAddressIPv4CutNot07(void) DetectAddressFree(b); return result; - error: +error: DetectAddressFree(a); if (b != NULL) DetectAddressFree(b); @@ -1166,7 +1166,7 @@ static int DetectAddressIPv4CutNot08(void) struct in_addr in; int result = 1; - if ( (a = DetectAddressInit()) == NULL) + if ((a = DetectAddressInit()) == NULL) return 0; if (inet_pton(AF_INET, "1.2.3.4", &in) < 0) @@ -1202,7 +1202,7 @@ static int DetectAddressIPv4CutNot08(void) DetectAddressFree(b); return result; - error: +error: DetectAddressFree(a); if (b != NULL) DetectAddressFree(b); @@ -1216,7 +1216,7 @@ static int DetectAddressIPv4CutNot09(void) struct in_addr in; int result = 1; - if ( (a = DetectAddressInit()) == NULL) + if ((a = DetectAddressInit()) == NULL) return 0; if (inet_pton(AF_INET, "1.2.3.4", &in) < 0) @@ -1252,7 +1252,7 @@ static int DetectAddressIPv4CutNot09(void) DetectAddressFree(b); return result; - error: +error: DetectAddressFree(a); if (b != NULL) DetectAddressFree(b); @@ -1264,14 +1264,10 @@ static int DetectAddressIPv4CutNot09(void) void DetectAddressIPv4Tests(void) { #ifdef UNITTESTS - UtRegisterTest("DetectAddressIPv4TestAddressCmp01", - DetectAddressIPv4TestAddressCmp01); - UtRegisterTest("DetectAddressIPv4IsCompleteIPSpace02", - DetectAddressIPv4IsCompleteIPSpace02); - UtRegisterTest("DetectAddressIPv4IsCompleteIPSpace03", - DetectAddressIPv4IsCompleteIPSpace03); - UtRegisterTest("DetectAddressIPv4IsCompleteIPSpace04", - DetectAddressIPv4IsCompleteIPSpace04); + UtRegisterTest("DetectAddressIPv4TestAddressCmp01", DetectAddressIPv4TestAddressCmp01); + UtRegisterTest("DetectAddressIPv4IsCompleteIPSpace02", DetectAddressIPv4IsCompleteIPSpace02); + UtRegisterTest("DetectAddressIPv4IsCompleteIPSpace03", DetectAddressIPv4IsCompleteIPSpace03); + UtRegisterTest("DetectAddressIPv4IsCompleteIPSpace04", DetectAddressIPv4IsCompleteIPSpace04); UtRegisterTest("DetectAddressIPv4CutNot05", DetectAddressIPv4CutNot05); UtRegisterTest("DetectAddressIPv4CutNot06", DetectAddressIPv4CutNot06); UtRegisterTest("DetectAddressIPv4CutNot07", DetectAddressIPv4CutNot07); diff --git a/src/detect-engine-address-ipv4.h b/src/detect-engine-address-ipv4.h index 5f2780a3c066..87df4f82ce2a 100644 --- a/src/detect-engine-address-ipv4.h +++ b/src/detect-engine-address-ipv4.h @@ -27,11 +27,9 @@ int DetectAddressCutNotIPv4(DetectAddress *, DetectAddress **); int DetectAddressCmpIPv4(DetectAddress *a, DetectAddress *b); -int DetectAddressCutIPv4(DetectEngineCtx *, DetectAddress *, - DetectAddress *, DetectAddress **); +int DetectAddressCutIPv4(DetectEngineCtx *, DetectAddress *, DetectAddress *, DetectAddress **); int DetectAddressIsCompleteIPSpaceIPv4(DetectAddress *); void DetectAddressIPv4Tests(void); #endif /* __DETECT_ENGINE_ADDRESS_IPV4_H__ */ - diff --git a/src/detect-engine-address-ipv6.c b/src/detect-engine-address-ipv6.c index 3179628c6d55..111e44db5faf 100644 --- a/src/detect-engine-address-ipv6.c +++ b/src/detect-engine-address-ipv6.c @@ -231,25 +231,19 @@ int AddressIPv6GeU32(uint32_t *a, uint32_t *b) */ int DetectAddressCmpIPv6(DetectAddress *a, DetectAddress *b) { - if (AddressIPv6Eq(&a->ip, &b->ip) == 1 && - AddressIPv6Eq(&a->ip2, &b->ip2) == 1) { + if (AddressIPv6Eq(&a->ip, &b->ip) == 1 && AddressIPv6Eq(&a->ip2, &b->ip2) == 1) { return ADDRESS_EQ; - } else if (AddressIPv6Ge(&a->ip, &b->ip) == 1 && - AddressIPv6Le(&a->ip, &b->ip2) == 1 && + } else if (AddressIPv6Ge(&a->ip, &b->ip) == 1 && AddressIPv6Le(&a->ip, &b->ip2) == 1 && AddressIPv6Le(&a->ip2, &b->ip2) == 1) { return ADDRESS_ES; - } else if (AddressIPv6Le(&a->ip, &b->ip) == 1 && - AddressIPv6Ge(&a->ip2, &b->ip2) == 1) { + } else if (AddressIPv6Le(&a->ip, &b->ip) == 1 && AddressIPv6Ge(&a->ip2, &b->ip2) == 1) { return ADDRESS_EB; - } else if (AddressIPv6Lt(&a->ip, &b->ip) == 1 && - AddressIPv6Lt(&a->ip2, &b->ip2) == 1 && + } else if (AddressIPv6Lt(&a->ip, &b->ip) == 1 && AddressIPv6Lt(&a->ip2, &b->ip2) == 1 && AddressIPv6Ge(&a->ip2, &b->ip) == 1) { return ADDRESS_LE; - } else if (AddressIPv6Lt(&a->ip, &b->ip) == 1 && - AddressIPv6Lt(&a->ip2, &b->ip2) == 1) { + } else if (AddressIPv6Lt(&a->ip, &b->ip) == 1 && AddressIPv6Lt(&a->ip2, &b->ip2) == 1) { return ADDRESS_LT; - } else if (AddressIPv6Gt(&a->ip, &b->ip) == 1 && - AddressIPv6Le(&a->ip, &b->ip2) == 1 && + } else if (AddressIPv6Gt(&a->ip, &b->ip) == 1 && AddressIPv6Le(&a->ip, &b->ip2) == 1 && AddressIPv6Gt(&a->ip2, &b->ip2) == 1) { return ADDRESS_GE; } else if (AddressIPv6Gt(&a->ip, &b->ip2) == 1) { @@ -356,17 +350,17 @@ static void AddressCutIPv6Copy(uint32_t *a, uint32_t *b) return; } -int DetectAddressCutIPv6(DetectEngineCtx *de_ctx, DetectAddress *a, - DetectAddress *b, DetectAddress **c) +int DetectAddressCutIPv6( + DetectEngineCtx *de_ctx, DetectAddress *a, DetectAddress *b, DetectAddress **c) { uint32_t a_ip1[4] = { SCNtohl(a->ip.addr_data32[0]), SCNtohl(a->ip.addr_data32[1]), - SCNtohl(a->ip.addr_data32[2]), SCNtohl(a->ip.addr_data32[3]) }; + SCNtohl(a->ip.addr_data32[2]), SCNtohl(a->ip.addr_data32[3]) }; uint32_t a_ip2[4] = { SCNtohl(a->ip2.addr_data32[0]), SCNtohl(a->ip2.addr_data32[1]), - SCNtohl(a->ip2.addr_data32[2]), SCNtohl(a->ip2.addr_data32[3]) }; + SCNtohl(a->ip2.addr_data32[2]), SCNtohl(a->ip2.addr_data32[3]) }; uint32_t b_ip1[4] = { SCNtohl(b->ip.addr_data32[0]), SCNtohl(b->ip.addr_data32[1]), - SCNtohl(b->ip.addr_data32[2]), SCNtohl(b->ip.addr_data32[3]) }; + SCNtohl(b->ip.addr_data32[2]), SCNtohl(b->ip.addr_data32[3]) }; uint32_t b_ip2[4] = { SCNtohl(b->ip2.addr_data32[0]), SCNtohl(b->ip2.addr_data32[1]), - SCNtohl(b->ip2.addr_data32[2]), SCNtohl(b->ip2.addr_data32[3]) }; + SCNtohl(b->ip2.addr_data32[2]), SCNtohl(b->ip2.addr_data32[3]) }; /* default to NULL */ *c = NULL; @@ -392,18 +386,18 @@ int DetectAddressCutIPv6(DetectEngineCtx *de_ctx, DetectAddress *a, tmp_c = DetectAddressInit(); if (tmp_c == NULL) goto error; - tmp_c->ip.family = AF_INET6; + tmp_c->ip.family = AF_INET6; AddressCutIPv6CopyAddOne(a_ip2, tmp_c->ip.addr_data32); AddressCutIPv6Copy(b_ip2, tmp_c->ip2.addr_data32); *c = tmp_c; - /* we have 3 parts: [bbb[baba]aaa] - * part a: b_ip1 <-> a_ip1 - 1 - * part b: a_ip1 <-> b_ip2 - * part c: b_ip2 + 1 <-> a_ip2 - */ + /* we have 3 parts: [bbb[baba]aaa] + * part a: b_ip1 <-> a_ip1 - 1 + * part b: a_ip1 <-> b_ip2 + * part c: b_ip2 + 1 <-> a_ip2 + */ } else if (r == ADDRESS_GE) { AddressCutIPv6Copy(b_ip1, a->ip.addr_data32); AddressCutIPv6CopySubOne(a_ip1, a->ip2.addr_data32); @@ -415,26 +409,26 @@ int DetectAddressCutIPv6(DetectEngineCtx *de_ctx, DetectAddress *a, tmp_c = DetectAddressInit(); if (tmp_c == NULL) goto error; - tmp_c->ip.family = AF_INET6; + tmp_c->ip.family = AF_INET6; AddressCutIPv6CopyAddOne(b_ip2, tmp_c->ip.addr_data32); AddressCutIPv6Copy(a_ip2, tmp_c->ip2.addr_data32); *c = tmp_c; - /* we have 2 or three parts: - * - * 2 part: [[abab]bbb] or [bbb[baba]] - * part a: a_ip1 <-> a_ip2 - * part b: a_ip2 + 1 <-> b_ip2 - * - * part a: b_ip1 <-> a_ip1 - 1 - * part b: a_ip1 <-> a_ip2 - * - * 3 part [bbb[aaa]bbb] - * part a: b_ip1 <-> a_ip1 - 1 - * part b: a_ip1 <-> a_ip2 - * part c: a_ip2 + 1 <-> b_ip2 - */ + /* we have 2 or three parts: + * + * 2 part: [[abab]bbb] or [bbb[baba]] + * part a: a_ip1 <-> a_ip2 + * part b: a_ip2 + 1 <-> b_ip2 + * + * part a: b_ip1 <-> a_ip1 - 1 + * part b: a_ip1 <-> a_ip2 + * + * 3 part [bbb[aaa]bbb] + * part a: b_ip1 <-> a_ip1 - 1 + * part b: a_ip1 <-> a_ip2 + * part c: a_ip2 + 1 <-> b_ip2 + */ } else if (r == ADDRESS_ES) { if (AddressIPv6EqU32(a_ip1, b_ip1) == 1) { AddressCutIPv6Copy(a_ip1, a->ip.addr_data32); @@ -466,22 +460,21 @@ int DetectAddressCutIPv6(DetectEngineCtx *de_ctx, DetectAddress *a, AddressCutIPv6CopyAddOne(a_ip2, tmp_c->ip.addr_data32); AddressCutIPv6Copy(b_ip2, tmp_c->ip2.addr_data32); *c = tmp_c; - } - /* we have 2 or three parts: - * - * 2 part: [[baba]aaa] or [aaa[abab]] - * part a: b_ip1 <-> b_ip2 - * part b: b_ip2 + 1 <-> a_ip2 - * - * part a: a_ip1 <-> b_ip1 - 1 - * part b: b_ip1 <-> b_ip2 - * - * 3 part [aaa[bbb]aaa] - * part a: a_ip1 <-> b_ip2 - 1 - * part b: b_ip1 <-> b_ip2 - * part c: b_ip2 + 1 <-> a_ip2 - */ + /* we have 2 or three parts: + * + * 2 part: [[baba]aaa] or [aaa[abab]] + * part a: b_ip1 <-> b_ip2 + * part b: b_ip2 + 1 <-> a_ip2 + * + * part a: a_ip1 <-> b_ip1 - 1 + * part b: b_ip1 <-> b_ip2 + * + * 3 part [aaa[bbb]aaa] + * part a: a_ip1 <-> b_ip2 - 1 + * part b: b_ip1 <-> b_ip2 + * part c: b_ip2 + 1 <-> a_ip2 + */ } else if (r == ADDRESS_EB) { if (AddressIPv6EqU32(a_ip1, b_ip1) == 1) { AddressCutIPv6Copy(b_ip1, a->ip.addr_data32); @@ -507,7 +500,7 @@ int DetectAddressCutIPv6(DetectEngineCtx *de_ctx, DetectAddress *a, if (tmp_c == NULL) goto error; - tmp_c->ip.family = AF_INET6; + tmp_c->ip.family = AF_INET6; AddressCutIPv6CopyAddOne(b_ip2, tmp_c->ip.addr_data32); AddressCutIPv6Copy(a_ip2, tmp_c->ip2.addr_data32); *c = tmp_c; @@ -710,19 +703,19 @@ int DetectAddressCutIPv6(DetectAddressData *a, DetectAddressData *b, int DetectAddressCutNotIPv6(DetectAddress *a, DetectAddress **b) { uint32_t a_ip1[4] = { SCNtohl(a->ip.addr_data32[0]), SCNtohl(a->ip.addr_data32[1]), - SCNtohl(a->ip.addr_data32[2]), SCNtohl(a->ip.addr_data32[3]) }; + SCNtohl(a->ip.addr_data32[2]), SCNtohl(a->ip.addr_data32[3]) }; uint32_t a_ip2[4] = { SCNtohl(a->ip2.addr_data32[0]), SCNtohl(a->ip2.addr_data32[1]), - SCNtohl(a->ip2.addr_data32[2]), SCNtohl(a->ip2.addr_data32[3]) }; + SCNtohl(a->ip2.addr_data32[2]), SCNtohl(a->ip2.addr_data32[3]) }; uint32_t ip_nul[4] = { 0x00000000, 0x00000000, 0x00000000, 0x00000000 }; uint32_t ip_max[4] = { 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF }; /* default to NULL */ *b = NULL; - if (!(a_ip1[0] == 0x00000000 && a_ip1[1] == 0x00000000 && - a_ip1[2] == 0x00000000 && a_ip1[3] == 0x00000000) && - !(a_ip2[0] == 0xFFFFFFFF && a_ip2[1] == 0xFFFFFFFF && - a_ip2[2] == 0xFFFFFFFF && a_ip2[3] == 0xFFFFFFFF)) { + if (!(a_ip1[0] == 0x00000000 && a_ip1[1] == 0x00000000 && a_ip1[2] == 0x00000000 && + a_ip1[3] == 0x00000000) && + !(a_ip2[0] == 0xFFFFFFFF && a_ip2[1] == 0xFFFFFFFF && a_ip2[2] == 0xFFFFFFFF && + a_ip2[3] == 0xFFFFFFFF)) { AddressCutIPv6Copy(ip_nul, a->ip.addr_data32); AddressCutIPv6CopySubOne(a_ip1, a->ip2.addr_data32); @@ -730,20 +723,20 @@ int DetectAddressCutNotIPv6(DetectAddress *a, DetectAddress **b) if (tmp_b == NULL) goto error; - tmp_b->ip.family = AF_INET6; + tmp_b->ip.family = AF_INET6; AddressCutIPv6CopyAddOne(a_ip2, tmp_b->ip.addr_data32); AddressCutIPv6Copy(ip_max, tmp_b->ip2.addr_data32); *b = tmp_b; - } else if ((a_ip1[0] == 0x00000000 && a_ip1[1] == 0x00000000 && - a_ip1[2] == 0x00000000 && a_ip1[3] == 0x00000000) && - !(a_ip2[0] == 0xFFFFFFFF && a_ip2[1] == 0xFFFFFFFF && - a_ip2[2] == 0xFFFFFFFF && a_ip2[3] == 0xFFFFFFFF)) { + } else if ((a_ip1[0] == 0x00000000 && a_ip1[1] == 0x00000000 && a_ip1[2] == 0x00000000 && + a_ip1[3] == 0x00000000) && + !(a_ip2[0] == 0xFFFFFFFF && a_ip2[1] == 0xFFFFFFFF && a_ip2[2] == 0xFFFFFFFF && + a_ip2[3] == 0xFFFFFFFF)) { AddressCutIPv6CopyAddOne(a_ip2, a->ip.addr_data32); AddressCutIPv6Copy(ip_max, a->ip2.addr_data32); - } else if (!(a_ip1[0] == 0x00000000 && a_ip1[1] == 0x00000000 && - a_ip1[2] == 0x00000000 && a_ip1[3] == 0x00000000) && - (a_ip2[0] == 0xFFFFFFFF && a_ip2[1] == 0xFFFFFFFF && - a_ip2[2] == 0xFFFFFFFF && a_ip2[3] == 0xFFFFFFFF)) { + } else if (!(a_ip1[0] == 0x00000000 && a_ip1[1] == 0x00000000 && a_ip1[2] == 0x00000000 && + a_ip1[3] == 0x00000000) && + (a_ip2[0] == 0xFFFFFFFF && a_ip2[1] == 0xFFFFFFFF && a_ip2[2] == 0xFFFFFFFF && + a_ip2[3] == 0xFFFFFFFF)) { AddressCutIPv6Copy(ip_nul, a->ip.addr_data32); AddressCutIPv6CopySubOne(a_ip1, a->ip2.addr_data32); } else { @@ -756,7 +749,6 @@ int DetectAddressCutNotIPv6(DetectAddress *a, DetectAddress **b) return -1; } - /***************************************Unittests******************************/ #ifdef UNITTESTS @@ -1086,8 +1078,7 @@ static int AddressTestIPv6SubOne01(void) if (inet_pton(AF_INET6, "2000::0", &in6) != 1) return 0; memcpy(a, in6.s6_addr, sizeof(in6.s6_addr)); - if (b[0] == a[0] && b[1] == a[1] && - b[2] == a[2] && b[3] == a[3]) { + if (b[0] == a[0] && b[1] == a[1] && b[2] == a[2] && b[3] == a[3]) { result = 1; } @@ -1115,8 +1106,7 @@ static int AddressTestIPv6SubOne02(void) if (inet_pton(AF_INET6, "1FFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF", &in6) != 1) return 0; memcpy(a, in6.s6_addr, sizeof(in6.s6_addr)); - if (b[0] == a[0] && b[1] == a[1] && - b[2] == a[2] && b[3] == a[3]) { + if (b[0] == a[0] && b[1] == a[1] && b[2] == a[2] && b[3] == a[3]) { result = 1; } @@ -1144,8 +1134,7 @@ static int AddressTestIPv6AddOne01(void) if (inet_pton(AF_INET6, "2000::1", &in6) != 1) return 0; memcpy(a, in6.s6_addr, sizeof(in6.s6_addr)); - if (b[0] == a[0] && b[1] == a[1] && - b[2] == a[2] && b[3] == a[3]) { + if (b[0] == a[0] && b[1] == a[1] && b[2] == a[2] && b[3] == a[3]) { result = 1; } @@ -1172,9 +1161,8 @@ static int AddressTestIPv6AddOne02(void) if (inet_pton(AF_INET6, "2000::0", &in6) != 1) return 0; - memcpy(a, in6.s6_addr, sizeof(in6.s6_addr)); - if (b[0] == a[0] && b[1] == a[1] && - b[2] == a[2] && b[3] == a[3]) { + memcpy(a, in6.s6_addr, sizeof(in6.s6_addr)); + if (b[0] == a[0] && b[1] == a[1] && b[2] == a[2] && b[3] == a[3]) { result = 1; } @@ -1619,7 +1607,7 @@ static int AddressTestIPv6AddressCmp01(void) DetectAddressFree(b); return result; - error: +error: if (a != NULL) DetectAddressFree(a); if (b != NULL) @@ -1634,7 +1622,7 @@ static int AddressTestIPv6CutNot01(void) struct in6_addr in6; int result = 1; - if ( (a = DetectAddressInit()) == NULL) + if ((a = DetectAddressInit()) == NULL) goto error; if (inet_pton(AF_INET6, "::", &in6) != 1) @@ -1651,7 +1639,7 @@ static int AddressTestIPv6CutNot01(void) DetectAddressFree(b); return result; - error: +error: if (a != NULL) DetectAddressFree(a); if (b != NULL) @@ -1667,9 +1655,9 @@ static int AddressTestIPv6CutNot02(void) struct in6_addr in6; int result = 1; - if ( (a = DetectAddressInit()) == NULL) + if ((a = DetectAddressInit()) == NULL) goto error; - if ( (temp = DetectAddressInit()) == NULL) + if ((temp = DetectAddressInit()) == NULL) goto error; if (inet_pton(AF_INET6, "::", &in6) != 1) @@ -1699,7 +1687,7 @@ static int AddressTestIPv6CutNot02(void) DetectAddressFree(temp); return result; - error: +error: if (a != NULL) DetectAddressFree(a); if (b != NULL) @@ -1717,9 +1705,9 @@ static int AddressTestIPv6CutNot03(void) struct in6_addr in6; int result = 1; - if ( (a = DetectAddressInit()) == NULL) + if ((a = DetectAddressInit()) == NULL) goto error; - if ( (temp = DetectAddressInit()) == NULL) + if ((temp = DetectAddressInit()) == NULL) goto error; if (inet_pton(AF_INET6, "2000::1", &in6) != 1) @@ -1749,7 +1737,7 @@ static int AddressTestIPv6CutNot03(void) DetectAddressFree(temp); return result; - error: +error: if (a != NULL) DetectAddressFree(a); if (b != NULL) @@ -1767,9 +1755,9 @@ static int AddressTestIPv6CutNot04(void) struct in6_addr in6; int result = 1; - if ( (a = DetectAddressInit()) == NULL) + if ((a = DetectAddressInit()) == NULL) goto error; - if ( (temp = DetectAddressInit()) == NULL) + if ((temp = DetectAddressInit()) == NULL) goto error; if (inet_pton(AF_INET6, "2000::1", &in6) != 1) @@ -1807,7 +1795,7 @@ static int AddressTestIPv6CutNot04(void) DetectAddressFree(temp); return result; - error: +error: if (a != NULL) DetectAddressFree(a); if (b != NULL) @@ -1825,9 +1813,9 @@ static int AddressTestIPv6CutNot05(void) struct in6_addr in6; int result = 1; - if ( (a = DetectAddressInit()) == NULL) + if ((a = DetectAddressInit()) == NULL) goto error; - if ( (temp = DetectAddressInit()) == NULL) + if ((temp = DetectAddressInit()) == NULL) goto error; if (inet_pton(AF_INET6, "2000::1", &in6) != 1) @@ -1865,7 +1853,7 @@ static int AddressTestIPv6CutNot05(void) DetectAddressFree(temp); return result; - error: +error: if (a != NULL) DetectAddressFree(a); if (b != NULL) diff --git a/src/detect-engine-address-ipv6.h b/src/detect-engine-address-ipv6.h index b8c573d0ce44..0edcba64ed17 100644 --- a/src/detect-engine-address-ipv6.h +++ b/src/detect-engine-address-ipv6.h @@ -39,10 +39,8 @@ int AddressIPv6GeU32(uint32_t *a, uint32_t *b); int DetectAddressCutNotIPv6(DetectAddress *, DetectAddress **); int DetectAddressCmpIPv6(DetectAddress *a, DetectAddress *b); -int DetectAddressCutIPv6(DetectEngineCtx *, DetectAddress *, DetectAddress *, - DetectAddress **); +int DetectAddressCutIPv6(DetectEngineCtx *, DetectAddress *, DetectAddress *, DetectAddress **); void DetectAddressIPv6Tests(void); #endif /* __DETECT_ENGINE_ADDRESS_IPV6_H__ */ - diff --git a/src/detect-engine-address.c b/src/detect-engine-address.c index 7819969e6ef3..d4e1ce28986b 100644 --- a/src/detect-engine-address.c +++ b/src/detect-engine-address.c @@ -52,8 +52,7 @@ static void DetectAddressPrint(DetectAddress *); #define DetectAddressPrint(...) #endif static int DetectAddressCutNot(DetectAddress *, DetectAddress **); -static int DetectAddressCut(DetectEngineCtx *, DetectAddress *, DetectAddress *, - DetectAddress **); +static int DetectAddressCut(DetectEngineCtx *, DetectAddress *, DetectAddress *, DetectAddress **); static int DetectAddressParse2(const DetectEngineCtx *de_ctx, DetectAddressHead *gh, DetectAddressHead *ghn, const char *s, int negate, ResolvedVariablesList *var_list, int recur); @@ -162,7 +161,7 @@ void DetectAddressPrintList(DetectAddress *head) */ static void DetectAddressCleanupList(DetectAddress *head) { - for (DetectAddress *cur = head; cur != NULL; ) { + for (DetectAddress *cur = head; cur != NULL;) { DetectAddress *next = cur->next; cur->next = NULL; DetectAddressFree(cur); @@ -232,8 +231,7 @@ static DetectAddress *GetHeadPtr(DetectAddressHead *gh, DetectAddress *new) * \retval -1 On error. * \retval 0 Not inserted, memory of new is freed. */ -static int DetectAddressInsert(DetectEngineCtx *de_ctx, DetectAddressHead *gh, - DetectAddress *new) +static int DetectAddressInsert(DetectEngineCtx *de_ctx, DetectAddressHead *gh, DetectAddress *new) { DetectAddress *head = NULL; DetectAddress *cur = NULL; @@ -290,8 +288,8 @@ static int DetectAddressInsert(DetectEngineCtx *de_ctx, DetectAddressHead *gh, } return 1; - /* alright, those were the simple cases, lets handle the more - * complex ones now */ + /* alright, those were the simple cases, lets handle the more + * complex ones now */ } else if (r == ADDRESS_ES) { c = NULL; r = DetectAddressCut(de_ctx, cur, new, &c); @@ -327,7 +325,7 @@ static int DetectAddressInsert(DetectEngineCtx *de_ctx, DetectAddressHead *gh, return 1; } else if (r == ADDRESS_GE) { c = NULL; - r = DetectAddressCut(de_ctx, cur,new,&c); + r = DetectAddressCut(de_ctx, cur, new, &c); if (r == -1) goto error; @@ -339,7 +337,7 @@ static int DetectAddressInsert(DetectEngineCtx *de_ctx, DetectAddressHead *gh, } } - /* head is NULL, so get a group and set head to it */ + /* head is NULL, so get a group and set head to it */ } else { head = new; if (SetHeadPtr(gh, head) < 0) { @@ -430,18 +428,18 @@ static int DetectAddressParseString(DetectAddress *dd, const char *str) dd->ip.family = AF_INET; - if ((mask = strchr(ip, '/')) != NULL) { + if ((mask = strchr(ip, '/')) != NULL) { /* 1.2.3.4/xxx format (either dotted or cidr notation */ ip[mask - ip] = '\0'; mask++; uint32_t ip4addr = 0; uint32_t netmask = 0; - if ((strchr (mask, '.')) == NULL) { + if ((strchr(mask, '.')) == NULL) { /* 1.2.3.4/24 format */ for (size_t u = 0; u < strlen(mask); u++) { - if(!isdigit((unsigned char)mask[u])) + if (!isdigit((unsigned char)mask[u])) goto error; } @@ -475,8 +473,8 @@ static int DetectAddressParseString(DetectAddress *dd, const char *str) ip4addr = in.s_addr; dd->ip.addr_data32[0] = dd->ip2.addr_data32[0] = ip4addr & netmask; - dd->ip2.addr_data32[0] |=~ netmask; - } else if ((ip2 = strchr(ip, '-')) != NULL) { + dd->ip2.addr_data32[0] |= ~netmask; + } else if ((ip2 = strchr(ip, '-')) != NULL) { /* 1.2.3.4-1.2.3.6 range format */ ip[ip2 - ip] = '\0'; ip2++; @@ -510,7 +508,7 @@ static int DetectAddressParseString(DetectAddress *dd, const char *str) dd->ip.family = AF_INET6; - if ((mask = strchr(ip, '/')) != NULL) { + if ((mask = strchr(ip, '/')) != NULL) { ip[mask - ip] = '\0'; mask++; @@ -531,11 +529,11 @@ static int DetectAddressParseString(DetectAddress *dd, const char *str) dd->ip2.addr_data32[2] = dd->ip.addr_data32[2] = ip6addr[2] & netmask[2]; dd->ip2.addr_data32[3] = dd->ip.addr_data32[3] = ip6addr[3] & netmask[3]; - dd->ip2.addr_data32[0] |=~ netmask[0]; - dd->ip2.addr_data32[1] |=~ netmask[1]; - dd->ip2.addr_data32[2] |=~ netmask[2]; - dd->ip2.addr_data32[3] |=~ netmask[3]; - } else if ((ip2 = strchr(ip, '-')) != NULL) { + dd->ip2.addr_data32[0] |= ~netmask[0]; + dd->ip2.addr_data32[1] |= ~netmask[1]; + dd->ip2.addr_data32[2] |= ~netmask[2]; + dd->ip2.addr_data32[3] |= ~netmask[3]; + } else if ((ip2 = strchr(ip, '-')) != NULL) { /* 2001::1-2001::4 range format */ ip[ip2 - ip] = '\0'; ip2++; @@ -561,7 +559,6 @@ static int DetectAddressParseString(DetectAddress *dd, const char *str) memcpy(&dd->ip.address, &in6.s6_addr, sizeof(dd->ip.address)); memcpy(&dd->ip2.address, &in6.s6_addr, sizeof(dd->ip2.address)); } - } BUG_ON(dd->ip.family == 0); @@ -682,7 +679,7 @@ static int DetectAddressSetup(DetectAddressHead *gh, const char *s) DetectAddressFree(ad); return -1; } - SCLogDebug("r %d",r); + SCLogDebug("r %d", r); return 0; } @@ -760,7 +757,8 @@ static int DetectAddressParseInternal(const DetectEngineCtx *de_ctx, DetectAddre /* normal block */ SCLogDebug("normal block"); - if (DetectAddressParse2(de_ctx, gh, ghn, address, (negate + n_set) % 2, var_list, recur) < 0) + if (DetectAddressParse2(de_ctx, gh, ghn, address, (negate + n_set) % 2, + var_list, recur) < 0) goto error; } else { /* negated block @@ -773,7 +771,8 @@ static int DetectAddressParseInternal(const DetectEngineCtx *de_ctx, DetectAddre DetectAddressHead tmp_gh = { NULL, NULL }; DetectAddressHead tmp_ghn = { NULL, NULL }; - if (DetectAddressParse2(de_ctx, &tmp_gh, &tmp_ghn, address, 0, var_list, recur) < 0) { + if (DetectAddressParse2( + de_ctx, &tmp_gh, &tmp_ghn, address, 0, var_list, recur) < 0) { DetectAddressHeadCleanup(&tmp_gh); DetectAddressHeadCleanup(&tmp_ghn); goto error; @@ -845,8 +844,8 @@ static int DetectAddressParseInternal(const DetectEngineCtx *de_ctx, DetectAddre } else if (d_set == 1) { address[x - 1] = '\0'; - rule_var_address = SCRuleVarsGetConfVar(de_ctx, address, - SC_RULE_VARS_ADDRESS_GROUPS); + rule_var_address = + SCRuleVarsGetConfVar(de_ctx, address, SC_RULE_VARS_ADDRESS_GROUPS); if (rule_var_address == NULL) goto error; @@ -864,8 +863,8 @@ static int DetectAddressParseInternal(const DetectEngineCtx *de_ctx, DetectAddre temp_rule_var_address = SCMalloc(strlen(rule_var_address) + 3); if (unlikely(temp_rule_var_address == NULL)) goto error; - snprintf(temp_rule_var_address, strlen(rule_var_address) + 3, - "[%s]", rule_var_address); + snprintf(temp_rule_var_address, strlen(rule_var_address) + 3, "[%s]", + rule_var_address); } else { temp_rule_var_address = SCStrdup(rule_var_address); if (unlikely(temp_rule_var_address == NULL)) @@ -913,8 +912,8 @@ static int DetectAddressParseInternal(const DetectEngineCtx *de_ctx, DetectAddre } if (d_set == 1) { - rule_var_address = SCRuleVarsGetConfVar(de_ctx, address, - SC_RULE_VARS_ADDRESS_GROUPS); + rule_var_address = + SCRuleVarsGetConfVar(de_ctx, address, SC_RULE_VARS_ADDRESS_GROUPS); if (rule_var_address == NULL) goto error; @@ -932,8 +931,8 @@ static int DetectAddressParseInternal(const DetectEngineCtx *de_ctx, DetectAddre temp_rule_var_address = SCMalloc(strlen(rule_var_address) + 3); if (unlikely(temp_rule_var_address == NULL)) goto error; - snprintf(temp_rule_var_address, strlen(rule_var_address) + 3, - "[%s]", rule_var_address); + snprintf(temp_rule_var_address, strlen(rule_var_address) + 3, "[%s]", + rule_var_address); } else { temp_rule_var_address = SCStrdup(rule_var_address); if (unlikely(temp_rule_var_address == NULL)) @@ -1056,8 +1055,7 @@ int DetectAddressMergeNot(DetectAddressHead *gh, DetectAddressHead *ghn) DetectAddress *ag, *ag2; int r = 0; - SCLogDebug("gh->ipv4_head %p, ghn->ipv4_head %p", gh->ipv4_head, - ghn->ipv4_head); + SCLogDebug("gh->ipv4_head %p, ghn->ipv4_head %p", gh->ipv4_head, ghn->ipv4_head); /* check if the negated list covers the entire ip space. If so * the user screwed up the rules/vars. */ @@ -1133,7 +1131,7 @@ int DetectAddressMergeNot(DetectAddressHead *gh, DetectAddressHead *ghn) DetectAddressPrint(ag); int applied = 0; - for (ag2 = gh->ipv4_head; ag2 != NULL; ) { + for (ag2 = gh->ipv4_head; ag2 != NULL;) { SCLogDebug("ag2 %p", ag2); DetectAddressPrint(ag2); @@ -1163,7 +1161,7 @@ int DetectAddressMergeNot(DetectAddressHead *gh, DetectAddressHead *ghn) /* ... and the same for ipv6 */ for (ag = ghn->ipv6_head; ag != NULL; ag = ag->next) { int applied = 0; - for (ag2 = gh->ipv6_head; ag2 != NULL; ) { + for (ag2 = gh->ipv6_head; ag2 != NULL;) { r = DetectAddressCmp(ag, ag2); if (r == ADDRESS_EQ || r == ADDRESS_EB) { /* XXX more ??? */ if (ag2->prev != NULL) @@ -1247,7 +1245,7 @@ int DetectAddressTestConfVars(void) DetectAddressHead *ghn = NULL; ConfNode *seq_node; - TAILQ_FOREACH(seq_node, &address_vars_node->head, next) { + TAILQ_FOREACH (seq_node, &address_vars_node->head, next) { SCLogDebug("Testing %s - %s", seq_node->name, seq_node->val); gh = DetectAddressHeadInit(); @@ -1294,7 +1292,7 @@ int DetectAddressTestConfVars(void) } return 0; - error: +error: if (gh != NULL) DetectAddressHeadFree(gh); if (ghn != NULL) @@ -1321,8 +1319,7 @@ static uint32_t DetectAddressMapHashFunc(HashListTable *ht, void *data, uint16_t return hash; } -static char DetectAddressMapCompareFunc(void *data1, uint16_t len1, void *data2, - uint16_t len2) +static char DetectAddressMapCompareFunc(void *data1, uint16_t len1, void *data2, uint16_t len2) { DetectAddressMap *map1 = (DetectAddressMap *)data1; DetectAddressMap *map2 = (DetectAddressMap *)data2; @@ -1343,9 +1340,8 @@ static void DetectAddressMapFreeFunc(void *data) int DetectAddressMapInit(DetectEngineCtx *de_ctx) { - de_ctx->address_table = HashListTableInit(4096, DetectAddressMapHashFunc, - DetectAddressMapCompareFunc, - DetectAddressMapFreeFunc); + de_ctx->address_table = HashListTableInit( + 4096, DetectAddressMapHashFunc, DetectAddressMapCompareFunc, DetectAddressMapFreeFunc); if (de_ctx->address_table == NULL) return -1; @@ -1363,7 +1359,7 @@ void DetectAddressMapFree(DetectEngineCtx *de_ctx) } static int DetectAddressMapAdd(DetectEngineCtx *de_ctx, const char *string, - DetectAddressHead *address, bool contains_negation) + DetectAddressHead *address, bool contains_negation) { DetectAddressMap *map = SCCalloc(1, sizeof(*map)); if (map == NULL) @@ -1381,13 +1377,11 @@ static int DetectAddressMapAdd(DetectEngineCtx *de_ctx, const char *string, return 0; } -static const DetectAddressMap *DetectAddressMapLookup(DetectEngineCtx *de_ctx, - const char *string) +static const DetectAddressMap *DetectAddressMapLookup(DetectEngineCtx *de_ctx, const char *string) { DetectAddressMap map = { (char *)string, NULL, false }; - const DetectAddressMap *res = HashListTableLookup(de_ctx->address_table, - &map, 0); + const DetectAddressMap *res = HashListTableLookup(de_ctx->address_table, &map, 0); return res; } @@ -1405,8 +1399,7 @@ static const DetectAddressMap *DetectAddressMapLookup(DetectEngineCtx *de_ctx, * \retval 0 On success. Did not contain negation. * \retval -1 On failure. */ -int DetectAddressParse(const DetectEngineCtx *de_ctx, - DetectAddressHead *gh, const char *str) +int DetectAddressParse(const DetectEngineCtx *de_ctx, DetectAddressHead *gh, const char *str) { SCLogDebug("gh %p, str %s", gh, str); @@ -1428,8 +1421,7 @@ int DetectAddressParse(const DetectEngineCtx *de_ctx, return -1; } - SCLogDebug("gh->ipv4_head %p, ghn->ipv4_head %p", gh->ipv4_head, - ghn->ipv4_head); + SCLogDebug("gh->ipv4_head %p, ghn->ipv4_head %p", gh->ipv4_head, ghn->ipv4_head); bool contains_negation = (ghn->ipv4_head != NULL || ghn->ipv6_head != NULL); @@ -1445,8 +1437,8 @@ int DetectAddressParse(const DetectEngineCtx *de_ctx, return contains_negation ? 1 : 0; } -const DetectAddressHead *DetectParseAddress(DetectEngineCtx *de_ctx, - const char *string, bool *contains_negation) +const DetectAddressHead *DetectParseAddress( + DetectEngineCtx *de_ctx, const char *string, bool *contains_negation) { const DetectAddressMap *res = DetectAddressMapLookup(de_ctx, string); if (res != NULL) { @@ -1471,8 +1463,7 @@ const DetectAddressHead *DetectParseAddress(DetectEngineCtx *de_ctx, *contains_negation = false; } - DetectAddressMapAdd((DetectEngineCtx *)de_ctx, string, head, - *contains_negation); + DetectAddressMapAdd((DetectEngineCtx *)de_ctx, string, head, *contains_negation); return head; } @@ -1514,8 +1505,7 @@ void DetectAddressHeadCleanup(DetectAddressHead *gh) * \retval 0 On success. * \retval -1 On failure. */ -int DetectAddressCut(DetectEngineCtx *de_ctx, DetectAddress *a, - DetectAddress *b, DetectAddress **c) +int DetectAddressCut(DetectEngineCtx *de_ctx, DetectAddress *a, DetectAddress *b, DetectAddress **c) { if (a->ip.family == AF_INET) return DetectAddressCutIPv4(de_ctx, a, b, c); @@ -1599,8 +1589,8 @@ int DetectAddressCmp(DetectAddress *a, DetectAddress *b) * * \todo array should be ordered, so we can break out of the loop */ -int DetectAddressMatchIPv4(const DetectMatchAddressIPv4 *addrs, - uint16_t addrs_cnt, const Address *a) +int DetectAddressMatchIPv4( + const DetectMatchAddressIPv4 *addrs, uint16_t addrs_cnt, const Address *a) { SCEnter(); @@ -1632,8 +1622,8 @@ int DetectAddressMatchIPv4(const DetectMatchAddressIPv4 *addrs, * * \todo array should be ordered, so we can break out of the loop */ -int DetectAddressMatchIPv6(const DetectMatchAddressIPv6 *addrs, - uint16_t addrs_cnt, const Address *a) +int DetectAddressMatchIPv6( + const DetectMatchAddressIPv6 *addrs, uint16_t addrs_cnt, const Address *a) { SCEnter(); @@ -1724,8 +1714,8 @@ static int DetectAddressMatch(DetectAddress *dd, Address *a) SCReturnInt(0); } - //DetectAddressPrint(dd); - //AddressDebugPrint(a); + // DetectAddressPrint(dd); + // AddressDebugPrint(a); switch (a->family) { case AF_INET: @@ -1733,8 +1723,7 @@ static int DetectAddressMatch(DetectAddress *dd, Address *a) /* XXX figure out a way to not need to do this SCNtohl if we switch to * Address inside DetectAddressData we can do uint8_t checks */ if (SCNtohl(a->addr_data32[0]) >= SCNtohl(dd->ip.addr_data32[0]) && - SCNtohl(a->addr_data32[0]) <= SCNtohl(dd->ip2.addr_data32[0])) - { + SCNtohl(a->addr_data32[0]) <= SCNtohl(dd->ip2.addr_data32[0])) { SCReturnInt(1); } else { SCReturnInt(0); @@ -1742,9 +1731,7 @@ static int DetectAddressMatch(DetectAddress *dd, Address *a) break; case AF_INET6: - if (AddressIPv6Ge(a, &dd->ip) == 1 && - AddressIPv6Le(a, &dd->ip2) == 1) - { + if (AddressIPv6Ge(a, &dd->ip) == 1 && AddressIPv6Le(a, &dd->ip2) == 1) { SCReturnInt(1); } else { SCReturnInt(0); @@ -1783,7 +1770,7 @@ static void DetectAddressPrint(DetectAddress *gr) PrintInet(AF_INET, &in, mask, sizeof(mask)); SCLogDebug("%s/%s", ip, mask); -// printf("%s/%s", ip, mask); + // printf("%s/%s", ip, mask); } else if (gr->ip.family == AF_INET6) { struct in6_addr in6; char ip[66], mask[66]; @@ -1794,7 +1781,7 @@ static void DetectAddressPrint(DetectAddress *gr) PrintInet(AF_INET6, &in6, mask, sizeof(mask)); SCLogDebug("%s/%s", ip, mask); -// printf("%s/%s", ip, mask); + // printf("%s/%s", ip, mask); } return; @@ -1829,8 +1816,8 @@ DetectAddress *DetectAddressLookupInHead(const DetectAddressHead *gh, Address *a g = gh->ipv6_head; } - for ( ; g != NULL; g = g->next) { - if (DetectAddressMatch(g,a) == 1) { + for (; g != NULL; g = g->next) { + if (DetectAddressMatch(g, a) == 1) { SCReturnPtr(g, "DetectAddress"); } } @@ -1849,7 +1836,7 @@ static bool UTHValidateDetectAddress(DetectAddress *ad, const char *one, const c if (ad == NULL) return false; - switch(ad->ip.family) { + switch (ad->ip.family) { case AF_INET: PrintInet(AF_INET, (const void *)&ad->ip.addr_data32[0], str1, sizeof(str1)); SCLogDebug("%s", str1); @@ -1897,7 +1884,8 @@ typedef struct UTHValidateDetectAddressHeadRange_ { const char *two; } UTHValidateDetectAddressHeadRange; -static int UTHValidateDetectAddressHead(DetectAddressHead *gh, int nranges, UTHValidateDetectAddressHeadRange *expectations) +static int UTHValidateDetectAddressHead( + DetectAddressHead *gh, int nranges, UTHValidateDetectAddressHeadRange *expectations) { int expect = nranges; int have = 0; @@ -1944,11 +1932,11 @@ static int AddressTestParse02(void) if (dd) { if (dd->ip2.addr_data32[0] != SCNtohl(16909060) || - dd->ip.addr_data32[0] != SCNtohl(16909060)) { + dd->ip.addr_data32[0] != SCNtohl(16909060)) { result = 0; } - printf("ip %"PRIu32", ip2 %"PRIu32"\n", dd->ip.addr_data32[0], dd->ip2.addr_data32[0]); + printf("ip %" PRIu32 ", ip2 %" PRIu32 "\n", dd->ip.addr_data32[0], dd->ip2.addr_data32[0]); DetectAddressFree(dd); return result; } @@ -2022,7 +2010,7 @@ static int AddressTestParse06(void) if (dd) { if (dd->ip2.addr_data32[0] != SCNtohl(16909311) || - dd->ip.addr_data32[0] != SCNtohl(16909056)) { + dd->ip.addr_data32[0] != SCNtohl(16909056)) { result = 0; } @@ -2052,10 +2040,11 @@ static int AddressTestParse08(void) if (dd) { if (dd->ip.addr_data32[0] != SCNtohl(536870912) || dd->ip.addr_data32[1] != 0x00000000 || - dd->ip.addr_data32[2] != 0x00000000 || dd->ip.addr_data32[3] != 0x00000000 || + dd->ip.addr_data32[2] != 0x00000000 || dd->ip.addr_data32[3] != 0x00000000 || - dd->ip2.addr_data32[0] != SCNtohl(1073741823) || dd->ip2.addr_data32[1] != 0xFFFFFFFF || - dd->ip2.addr_data32[2] != 0xFFFFFFFF || dd->ip2.addr_data32[3] != 0xFFFFFFFF) { + dd->ip2.addr_data32[0] != SCNtohl(1073741823) || + dd->ip2.addr_data32[1] != 0xFFFFFFFF || dd->ip2.addr_data32[2] != 0xFFFFFFFF || + dd->ip2.addr_data32[3] != 0xFFFFFFFF) { DetectAddressPrint(dd); result = 0; } @@ -2084,12 +2073,13 @@ static int AddressTestParse10(void) int result = 1; DetectAddress *dd = DetectAddressParseSingle("2001::/128"); - if (dd) { + if (dd) { if (dd->ip.addr_data32[0] != SCNtohl(536936448) || dd->ip.addr_data32[1] != 0x00000000 || - dd->ip.addr_data32[2] != 0x00000000 || dd->ip.addr_data32[3] != 0x00000000 || + dd->ip.addr_data32[2] != 0x00000000 || dd->ip.addr_data32[3] != 0x00000000 || - dd->ip2.addr_data32[0] != SCNtohl(536936448) || dd->ip2.addr_data32[1] != 0x00000000 || - dd->ip2.addr_data32[2] != 0x00000000 || dd->ip2.addr_data32[3] != 0x00000000) { + dd->ip2.addr_data32[0] != SCNtohl(536936448) || + dd->ip2.addr_data32[1] != 0x00000000 || dd->ip2.addr_data32[2] != 0x00000000 || + dd->ip2.addr_data32[3] != 0x00000000) { DetectAddressPrint(dd); result = 0; } @@ -2120,10 +2110,11 @@ static int AddressTestParse12(void) if (dd) { if (dd->ip.addr_data32[0] != SCNtohl(536936448) || dd->ip.addr_data32[1] != 0x00000000 || - dd->ip.addr_data32[2] != 0x00000000 || dd->ip.addr_data32[3] != 0x00000000 || + dd->ip.addr_data32[2] != 0x00000000 || dd->ip.addr_data32[3] != 0x00000000 || - dd->ip2.addr_data32[0] != SCNtohl(536936448) || dd->ip2.addr_data32[1] != SCNtohl(65535) || - dd->ip2.addr_data32[2] != 0xFFFFFFFF || dd->ip2.addr_data32[3] != 0xFFFFFFFF) { + dd->ip2.addr_data32[0] != SCNtohl(536936448) || + dd->ip2.addr_data32[1] != SCNtohl(65535) || dd->ip2.addr_data32[2] != 0xFFFFFFFF || + dd->ip2.addr_data32[3] != 0xFFFFFFFF) { DetectAddressPrint(dd); result = 0; } @@ -2153,10 +2144,11 @@ static int AddressTestParse14(void) if (dd) { if (dd->ip.addr_data32[0] != SCNtohl(536936448) || dd->ip.addr_data32[1] != 0x00000000 || - dd->ip.addr_data32[2] != 0x00000000 || dd->ip.addr_data32[3] != 0x00000000 || + dd->ip.addr_data32[2] != 0x00000000 || dd->ip.addr_data32[3] != 0x00000000 || - dd->ip2.addr_data32[0] != SCNtohl(537001983) || dd->ip2.addr_data32[1] != 0xFFFFFFFF || - dd->ip2.addr_data32[2] != 0xFFFFFFFF || dd->ip2.addr_data32[3] != 0xFFFFFFFF) { + dd->ip2.addr_data32[0] != SCNtohl(537001983) || + dd->ip2.addr_data32[1] != 0xFFFFFFFF || dd->ip2.addr_data32[2] != 0xFFFFFFFF || + dd->ip2.addr_data32[3] != 0xFFFFFFFF) { result = 0; } @@ -2186,10 +2178,10 @@ static int AddressTestParse16(void) if (dd) { if (dd->ip.addr_data32[0] != 0x00000000 || dd->ip.addr_data32[1] != 0x00000000 || - dd->ip.addr_data32[2] != 0x00000000 || dd->ip.addr_data32[3] != 0x00000000 || + dd->ip.addr_data32[2] != 0x00000000 || dd->ip.addr_data32[3] != 0x00000000 || - dd->ip2.addr_data32[0] != 0xFFFFFFFF || dd->ip2.addr_data32[1] != 0xFFFFFFFF || - dd->ip2.addr_data32[2] != 0xFFFFFFFF || dd->ip2.addr_data32[3] != 0xFFFFFFFF) { + dd->ip2.addr_data32[0] != 0xFFFFFFFF || dd->ip2.addr_data32[1] != 0xFFFFFFFF || + dd->ip2.addr_data32[2] != 0xFFFFFFFF || dd->ip2.addr_data32[3] != 0xFFFFFFFF) { result = 0; } @@ -2219,7 +2211,7 @@ static int AddressTestParse18(void) if (dd) { if (dd->ip2.addr_data32[0] != SCNtohl(16909062) || - dd->ip.addr_data32[0] != SCNtohl(16909060)) { + dd->ip.addr_data32[0] != SCNtohl(16909060)) { result = 0; } @@ -2261,10 +2253,11 @@ static int AddressTestParse21(void) if (dd) { if (dd->ip.addr_data32[0] != SCNtohl(536936448) || dd->ip.addr_data32[1] != 0x00000000 || - dd->ip.addr_data32[2] != 0x00000000 || dd->ip.addr_data32[3] != SCNtohl(1) || + dd->ip.addr_data32[2] != 0x00000000 || dd->ip.addr_data32[3] != SCNtohl(1) || - dd->ip2.addr_data32[0] != SCNtohl(536936448) || dd->ip2.addr_data32[1] != 0x00000000 || - dd->ip2.addr_data32[2] != 0x00000000 || dd->ip2.addr_data32[3] != SCNtohl(4)) { + dd->ip2.addr_data32[0] != SCNtohl(536936448) || + dd->ip2.addr_data32[1] != 0x00000000 || dd->ip2.addr_data32[2] != 0x00000000 || + dd->ip2.addr_data32[3] != SCNtohl(4)) { result = 0; } @@ -2326,8 +2319,7 @@ static int AddressTestParse26(void) int r = DetectAddressParse(NULL, gh, "[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[" "1.2.3.4" - "]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]" - ); + "]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]"); FAIL_IF_NOT(r == 0); DetectAddressHeadFree(gh); gh = DetectAddressHeadInit(); @@ -2336,8 +2328,7 @@ static int AddressTestParse26(void) r = DetectAddressParse(NULL, gh, "[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[" "1.2.3.4" - "]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]" - ); + "]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]"); FAIL_IF(r == 0); DetectAddressHeadFree(gh); PASS; @@ -2361,8 +2352,7 @@ static int AddressTestParse28(void) DetectAddress *dd = DetectAddressParseSingle("!1.2.3.4"); if (dd) { - if (dd->flags & ADDRESS_FLAG_NOT && - dd->ip.addr_data32[0] == SCNtohl(16909060)) { + if (dd->flags & ADDRESS_FLAG_NOT && dd->ip.addr_data32[0] == SCNtohl(16909060)) { result = 1; } @@ -2391,9 +2381,8 @@ static int AddressTestParse30(void) DetectAddress *dd = DetectAddressParseSingle("!1.2.3.4/24"); if (dd) { - if (dd->flags & ADDRESS_FLAG_NOT && - dd->ip.addr_data32[0] == SCNtohl(16909056) && - dd->ip2.addr_data32[0] == SCNtohl(16909311)) { + if (dd->flags & ADDRESS_FLAG_NOT && dd->ip.addr_data32[0] == SCNtohl(16909056) && + dd->ip2.addr_data32[0] == SCNtohl(16909311)) { result = 1; } @@ -2437,9 +2426,9 @@ static int AddressTestParse33(void) DetectAddress *dd = DetectAddressParseSingle("!2001::1"); if (dd) { - if (dd->flags & ADDRESS_FLAG_NOT && - dd->ip.addr_data32[0] == SCNtohl(536936448) && dd->ip.addr_data32[1] == 0x00000000 && - dd->ip.addr_data32[2] == 0x00000000 && dd->ip.addr_data32[3] == SCNtohl(1)) { + if (dd->flags & ADDRESS_FLAG_NOT && dd->ip.addr_data32[0] == SCNtohl(536936448) && + dd->ip.addr_data32[1] == 0x00000000 && dd->ip.addr_data32[2] == 0x00000000 && + dd->ip.addr_data32[3] == SCNtohl(1)) { result = 1; } @@ -2468,12 +2457,13 @@ static int AddressTestParse35(void) DetectAddress *dd = DetectAddressParseSingle("!2001::/16"); if (dd) { - if (dd->flags & ADDRESS_FLAG_NOT && - dd->ip.addr_data32[0] == SCNtohl(536936448) && dd->ip.addr_data32[1] == 0x00000000 && - dd->ip.addr_data32[2] == 0x00000000 && dd->ip.addr_data32[3] == 0x00000000 && + if (dd->flags & ADDRESS_FLAG_NOT && dd->ip.addr_data32[0] == SCNtohl(536936448) && + dd->ip.addr_data32[1] == 0x00000000 && dd->ip.addr_data32[2] == 0x00000000 && + dd->ip.addr_data32[3] == 0x00000000 && - dd->ip2.addr_data32[0] == SCNtohl(537001983) && dd->ip2.addr_data32[1] == 0xFFFFFFFF && - dd->ip2.addr_data32[2] == 0xFFFFFFFF && dd->ip2.addr_data32[3] == 0xFFFFFFFF) { + dd->ip2.addr_data32[0] == SCNtohl(537001983) && + dd->ip2.addr_data32[1] == 0xFFFFFFFF && dd->ip2.addr_data32[2] == 0xFFFFFFFF && + dd->ip2.addr_data32[3] == 0xFFFFFFFF) { result = 1; } @@ -2491,10 +2481,10 @@ static int AddressTestParse36(void) if (dd) { if (dd->ip.addr_data32[0] != SCNtohl(0xFFFF0000) || dd->ip.addr_data32[1] != 0x00000000 || - dd->ip.addr_data32[2] != 0x00000000 || dd->ip.addr_data32[3] != 0x00000000 || + dd->ip.addr_data32[2] != 0x00000000 || dd->ip.addr_data32[3] != 0x00000000 || - dd->ip2.addr_data32[0] != 0xFFFFFFFF || dd->ip2.addr_data32[1] != 0xFFFFFFFF || - dd->ip2.addr_data32[2] != 0xFFFFFFFF || dd->ip2.addr_data32[3] != 0xFFFFFFFF) { + dd->ip2.addr_data32[0] != 0xFFFFFFFF || dd->ip2.addr_data32[1] != 0xFFFFFFFF || + dd->ip2.addr_data32[2] != 0xFFFFFFFF || dd->ip2.addr_data32[3] != 0xFFFFFFFF) { DetectAddressPrint(dd); result = 0; @@ -2515,10 +2505,10 @@ static int AddressTestParse37(void) if (dd) { if (dd->ip.addr_data32[0] != 0x00000000 || dd->ip.addr_data32[1] != 0x00000000 || - dd->ip.addr_data32[2] != 0x00000000 || dd->ip.addr_data32[3] != 0x00000000 || + dd->ip.addr_data32[2] != 0x00000000 || dd->ip.addr_data32[3] != 0x00000000 || - dd->ip2.addr_data32[0] != 0xFFFFFFFF || dd->ip2.addr_data32[1] != 0xFFFFFFFF || - dd->ip2.addr_data32[2] != 0xFFFFFFFF || dd->ip2.addr_data32[3] != 0xFFFFFFFF) { + dd->ip2.addr_data32[0] != 0xFFFFFFFF || dd->ip2.addr_data32[1] != 0xFFFFFFFF || + dd->ip2.addr_data32[2] != 0xFFFFFFFF || dd->ip2.addr_data32[3] != 0xFFFFFFFF) { DetectAddressPrint(dd); result = 0; } @@ -2812,9 +2802,11 @@ static int AddressTestCmp01(void) int result = 1; da = DetectAddressParseSingle("192.168.0.0/255.255.255.0"); - if (da == NULL) goto error; + if (da == NULL) + goto error; db = DetectAddressParseSingle("192.168.0.0/255.255.255.0"); - if (db == NULL) goto error; + if (db == NULL) + goto error; if (DetectAddressCmp(da, db) != ADDRESS_EQ) result = 0; @@ -2824,8 +2816,10 @@ static int AddressTestCmp01(void) return result; error: - if (da) DetectAddressFree(da); - if (db) DetectAddressFree(db); + if (da) + DetectAddressFree(da); + if (db) + DetectAddressFree(db); return 0; } @@ -2835,9 +2829,11 @@ static int AddressTestCmp02(void) int result = 1; da = DetectAddressParseSingle("192.168.0.0/255.255.0.0"); - if (da == NULL) goto error; + if (da == NULL) + goto error; db = DetectAddressParseSingle("192.168.0.0/255.255.255.0"); - if (db == NULL) goto error; + if (db == NULL) + goto error; if (DetectAddressCmp(da, db) != ADDRESS_EB) result = 0; @@ -2847,8 +2843,10 @@ static int AddressTestCmp02(void) return result; error: - if (da) DetectAddressFree(da); - if (db) DetectAddressFree(db); + if (da) + DetectAddressFree(da); + if (db) + DetectAddressFree(db); return 0; } @@ -2858,9 +2856,11 @@ static int AddressTestCmp03(void) int result = 1; da = DetectAddressParseSingle("192.168.0.0/255.255.255.0"); - if (da == NULL) goto error; + if (da == NULL) + goto error; db = DetectAddressParseSingle("192.168.0.0/255.255.0.0"); - if (db == NULL) goto error; + if (db == NULL) + goto error; if (DetectAddressCmp(da, db) != ADDRESS_ES) result = 0; @@ -2870,8 +2870,10 @@ static int AddressTestCmp03(void) return result; error: - if (da) DetectAddressFree(da); - if (db) DetectAddressFree(db); + if (da) + DetectAddressFree(da); + if (db) + DetectAddressFree(db); return 0; } @@ -2881,9 +2883,11 @@ static int AddressTestCmp04(void) int result = 1; da = DetectAddressParseSingle("192.168.0.0/255.255.255.0"); - if (da == NULL) goto error; + if (da == NULL) + goto error; db = DetectAddressParseSingle("192.168.1.0/255.255.255.0"); - if (db == NULL) goto error; + if (db == NULL) + goto error; if (DetectAddressCmp(da, db) != ADDRESS_LT) result = 0; @@ -2893,8 +2897,10 @@ static int AddressTestCmp04(void) return result; error: - if (da) DetectAddressFree(da); - if (db) DetectAddressFree(db); + if (da) + DetectAddressFree(da); + if (db) + DetectAddressFree(db); return 0; } @@ -2904,9 +2910,11 @@ static int AddressTestCmp05(void) int result = 1; da = DetectAddressParseSingle("192.168.1.0/255.255.255.0"); - if (da == NULL) goto error; + if (da == NULL) + goto error; db = DetectAddressParseSingle("192.168.0.0/255.255.255.0"); - if (db == NULL) goto error; + if (db == NULL) + goto error; if (DetectAddressCmp(da, db) != ADDRESS_GT) result = 0; @@ -2916,8 +2924,10 @@ static int AddressTestCmp05(void) return result; error: - if (da) DetectAddressFree(da); - if (db) DetectAddressFree(db); + if (da) + DetectAddressFree(da); + if (db) + DetectAddressFree(db); return 0; } @@ -2927,9 +2937,11 @@ static int AddressTestCmp06(void) int result = 1; da = DetectAddressParseSingle("192.168.1.0/255.255.0.0"); - if (da == NULL) goto error; + if (da == NULL) + goto error; db = DetectAddressParseSingle("192.168.0.0/255.255.0.0"); - if (db == NULL) goto error; + if (db == NULL) + goto error; if (DetectAddressCmp(da, db) != ADDRESS_EQ) result = 0; @@ -2939,8 +2951,10 @@ static int AddressTestCmp06(void) return result; error: - if (da) DetectAddressFree(da); - if (db) DetectAddressFree(db); + if (da) + DetectAddressFree(da); + if (db) + DetectAddressFree(db); return 0; } @@ -2950,9 +2964,11 @@ static int AddressTestCmpIPv407(void) int result = 1; da = DetectAddressParseSingle("192.168.1.0/255.255.255.0"); - if (da == NULL) goto error; + if (da == NULL) + goto error; db = DetectAddressParseSingle("192.168.1.128-192.168.2.128"); - if (db == NULL) goto error; + if (db == NULL) + goto error; if (DetectAddressCmp(da, db) != ADDRESS_LE) result = 0; @@ -2962,8 +2978,10 @@ static int AddressTestCmpIPv407(void) return result; error: - if (da) DetectAddressFree(da); - if (db) DetectAddressFree(db); + if (da) + DetectAddressFree(da); + if (db) + DetectAddressFree(db); return 0; } @@ -2973,9 +2991,11 @@ static int AddressTestCmpIPv408(void) int result = 1; da = DetectAddressParseSingle("192.168.1.128-192.168.2.128"); - if (da == NULL) goto error; + if (da == NULL) + goto error; db = DetectAddressParseSingle("192.168.1.0/255.255.255.0"); - if (db == NULL) goto error; + if (db == NULL) + goto error; if (DetectAddressCmp(da, db) != ADDRESS_GE) result = 0; @@ -2985,8 +3005,10 @@ static int AddressTestCmpIPv408(void) return result; error: - if (da) DetectAddressFree(da); - if (db) DetectAddressFree(db); + if (da) + DetectAddressFree(da); + if (db) + DetectAddressFree(db); return 0; } @@ -2996,9 +3018,11 @@ static int AddressTestCmp07(void) int result = 1; da = DetectAddressParseSingle("2001::/3"); - if (da == NULL) goto error; + if (da == NULL) + goto error; db = DetectAddressParseSingle("2001::1/3"); - if (db == NULL) goto error; + if (db == NULL) + goto error; if (DetectAddressCmp(da, db) != ADDRESS_EQ) result = 0; @@ -3008,8 +3032,10 @@ static int AddressTestCmp07(void) return result; error: - if (da) DetectAddressFree(da); - if (db) DetectAddressFree(db); + if (da) + DetectAddressFree(da); + if (db) + DetectAddressFree(db); return 0; } @@ -3019,9 +3045,11 @@ static int AddressTestCmp08(void) int result = 1; da = DetectAddressParseSingle("2001::/3"); - if (da == NULL) goto error; + if (da == NULL) + goto error; db = DetectAddressParseSingle("2001::/8"); - if (db == NULL) goto error; + if (db == NULL) + goto error; if (DetectAddressCmp(da, db) != ADDRESS_EB) result = 0; @@ -3031,8 +3059,10 @@ static int AddressTestCmp08(void) return result; error: - if (da) DetectAddressFree(da); - if (db) DetectAddressFree(db); + if (da) + DetectAddressFree(da); + if (db) + DetectAddressFree(db); return 0; } @@ -3042,9 +3072,11 @@ static int AddressTestCmp09(void) int result = 1; da = DetectAddressParseSingle("2001::/8"); - if (da == NULL) goto error; + if (da == NULL) + goto error; db = DetectAddressParseSingle("2001::/3"); - if (db == NULL) goto error; + if (db == NULL) + goto error; if (DetectAddressCmp(da, db) != ADDRESS_ES) result = 0; @@ -3054,8 +3086,10 @@ static int AddressTestCmp09(void) return result; error: - if (da) DetectAddressFree(da); - if (db) DetectAddressFree(db); + if (da) + DetectAddressFree(da); + if (db) + DetectAddressFree(db); return 0; } @@ -3065,9 +3099,11 @@ static int AddressTestCmp10(void) int result = 1; da = DetectAddressParseSingle("2001:1:2:3:0:0:0:0/64"); - if (da == NULL) goto error; + if (da == NULL) + goto error; db = DetectAddressParseSingle("2001:1:2:4:0:0:0:0/64"); - if (db == NULL) goto error; + if (db == NULL) + goto error; if (DetectAddressCmp(da, db) != ADDRESS_LT) result = 0; @@ -3077,8 +3113,10 @@ static int AddressTestCmp10(void) return result; error: - if (da) DetectAddressFree(da); - if (db) DetectAddressFree(db); + if (da) + DetectAddressFree(da); + if (db) + DetectAddressFree(db); return 0; } @@ -3088,9 +3126,11 @@ static int AddressTestCmp11(void) int result = 1; da = DetectAddressParseSingle("2001:1:2:4:0:0:0:0/64"); - if (da == NULL) goto error; + if (da == NULL) + goto error; db = DetectAddressParseSingle("2001:1:2:3:0:0:0:0/64"); - if (db == NULL) goto error; + if (db == NULL) + goto error; if (DetectAddressCmp(da, db) != ADDRESS_GT) result = 0; @@ -3100,8 +3140,10 @@ static int AddressTestCmp11(void) return result; error: - if (da) DetectAddressFree(da); - if (db) DetectAddressFree(db); + if (da) + DetectAddressFree(da); + if (db) + DetectAddressFree(db); return 0; } @@ -3111,9 +3153,11 @@ static int AddressTestCmp12(void) int result = 1; da = DetectAddressParseSingle("2001:1:2:3:1:0:0:0/64"); - if (da == NULL) goto error; + if (da == NULL) + goto error; db = DetectAddressParseSingle("2001:1:2:3:2:0:0:0/64"); - if (db == NULL) goto error; + if (db == NULL) + goto error; if (DetectAddressCmp(da, db) != ADDRESS_EQ) result = 0; @@ -3123,8 +3167,10 @@ static int AddressTestCmp12(void) return result; error: - if (da) DetectAddressFree(da); - if (db) DetectAddressFree(db); + if (da) + DetectAddressFree(da); + if (db) + DetectAddressFree(db); return 0; } @@ -3169,8 +3215,8 @@ static int AddressTestAddressGroupSetup03(void) DetectAddress *prev_head = gh->ipv4_head; r = DetectAddressParse(NULL, gh, "1.2.3.3"); - if (r == 0 && gh->ipv4_head != prev_head && - gh->ipv4_head != NULL && gh->ipv4_head->next == prev_head) { + if (r == 0 && gh->ipv4_head != prev_head && gh->ipv4_head != NULL && + gh->ipv4_head->next == prev_head) { result = 1; } } @@ -3191,13 +3237,13 @@ static int AddressTestAddressGroupSetup04(void) DetectAddress *prev_head = gh->ipv4_head; r = DetectAddressParse(NULL, gh, "1.2.3.3"); - if (r == 0 && gh->ipv4_head != prev_head && - gh->ipv4_head != NULL && gh->ipv4_head->next == prev_head) { + if (r == 0 && gh->ipv4_head != prev_head && gh->ipv4_head != NULL && + gh->ipv4_head->next == prev_head) { DetectAddress *ph = gh->ipv4_head; r = DetectAddressParse(NULL, gh, "1.2.3.2"); - if (r == 0 && gh->ipv4_head != ph && - gh->ipv4_head != NULL && gh->ipv4_head->next == ph) { + if (r == 0 && gh->ipv4_head != ph && gh->ipv4_head != NULL && + gh->ipv4_head->next == ph) { result = 1; } } @@ -3219,13 +3265,13 @@ static int AddressTestAddressGroupSetup05(void) DetectAddress *prev_head = gh->ipv4_head; r = DetectAddressParse(NULL, gh, "1.2.3.3"); - if (r == 0 && gh->ipv4_head == prev_head && - gh->ipv4_head != NULL && gh->ipv4_head->next != prev_head) { + if (r == 0 && gh->ipv4_head == prev_head && gh->ipv4_head != NULL && + gh->ipv4_head->next != prev_head) { DetectAddress *ph = gh->ipv4_head; r = DetectAddressParse(NULL, gh, "1.2.3.4"); - if (r == 0 && gh->ipv4_head == ph && - gh->ipv4_head != NULL && gh->ipv4_head->next != ph) { + if (r == 0 && gh->ipv4_head == ph && gh->ipv4_head != NULL && + gh->ipv4_head->next != ph) { result = 1; } } @@ -3247,8 +3293,8 @@ static int AddressTestAddressGroupSetup06(void) DetectAddress *prev_head = gh->ipv4_head; r = DetectAddressParse(NULL, gh, "1.2.3.2"); - if (r == 0 && gh->ipv4_head == prev_head && - gh->ipv4_head != NULL && gh->ipv4_head->next == NULL) { + if (r == 0 && gh->ipv4_head == prev_head && gh->ipv4_head != NULL && + gh->ipv4_head->next == NULL) { result = 1; } } @@ -3267,9 +3313,8 @@ static int AddressTestAddressGroupSetup07(void) int r = DetectAddressParse(NULL, gh, "10.0.0.0/8"); if (r == 0 && gh->ipv4_head != NULL) { r = DetectAddressParse(NULL, gh, "10.10.10.10"); - if (r == 0 && gh->ipv4_head != NULL && - gh->ipv4_head->next != NULL && - gh->ipv4_head->next->next != NULL) { + if (r == 0 && gh->ipv4_head != NULL && gh->ipv4_head->next != NULL && + gh->ipv4_head->next->next != NULL) { result = 1; } } @@ -3288,9 +3333,8 @@ static int AddressTestAddressGroupSetup08(void) int r = DetectAddressParse(NULL, gh, "10.10.10.10"); if (r == 0 && gh->ipv4_head != NULL) { r = DetectAddressParse(NULL, gh, "10.0.0.0/8"); - if (r == 0 && gh->ipv4_head != NULL && - gh->ipv4_head->next != NULL && - gh->ipv4_head->next->next != NULL) { + if (r == 0 && gh->ipv4_head != NULL && gh->ipv4_head->next != NULL && + gh->ipv4_head->next->next != NULL) { result = 1; } } @@ -3309,9 +3353,8 @@ static int AddressTestAddressGroupSetup09(void) int r = DetectAddressParse(NULL, gh, "10.10.10.0/24"); if (r == 0 && gh->ipv4_head != NULL) { r = DetectAddressParse(NULL, gh, "10.10.10.10-10.10.11.1"); - if (r == 0 && gh->ipv4_head != NULL && - gh->ipv4_head->next != NULL && - gh->ipv4_head->next->next != NULL) { + if (r == 0 && gh->ipv4_head != NULL && gh->ipv4_head->next != NULL && + gh->ipv4_head->next->next != NULL) { result = 1; } } @@ -3330,9 +3373,8 @@ static int AddressTestAddressGroupSetup10(void) int r = DetectAddressParse(NULL, gh, "10.10.10.10-10.10.11.1"); if (r == 0 && gh->ipv4_head != NULL) { r = DetectAddressParse(NULL, gh, "10.10.10.0/24"); - if (r == 0 && gh->ipv4_head != NULL && - gh->ipv4_head->next != NULL && - gh->ipv4_head->next->next != NULL) { + if (r == 0 && gh->ipv4_head != NULL && gh->ipv4_head->next != NULL && + gh->ipv4_head->next->next != NULL) { result = 1; } } @@ -3354,9 +3396,8 @@ static int AddressTestAddressGroupSetup11(void) if (r == 0) { r = DetectAddressParse(NULL, gh, "0.0.0.0/0"); if (r == 0) { - DetectAddress *one = gh->ipv4_head, *two = one->next, - *three = two->next, *four = three->next, - *five = four->next; + DetectAddress *one = gh->ipv4_head, *two = one->next, *three = two->next, + *four = three->next, *five = four->next; /* result should be: * 0.0.0.0/10.10.9.255 @@ -3365,11 +3406,16 @@ static int AddressTestAddressGroupSetup11(void) * 10.10.11.0/10.10.11.1 * 10.10.11.2/255.255.255.255 */ - if (one->ip.addr_data32[0] == 0x00000000 && one->ip2.addr_data32[0] == SCNtohl(168430079) && - two->ip.addr_data32[0] == SCNtohl(168430080) && two->ip2.addr_data32[0] == SCNtohl(168430089) && - three->ip.addr_data32[0] == SCNtohl(168430090) && three->ip2.addr_data32[0] == SCNtohl(168430335) && - four->ip.addr_data32[0] == SCNtohl(168430336) && four->ip2.addr_data32[0] == SCNtohl(168430337) && - five->ip.addr_data32[0] == SCNtohl(168430338) && five->ip2.addr_data32[0] == 0xFFFFFFFF) { + if (one->ip.addr_data32[0] == 0x00000000 && + one->ip2.addr_data32[0] == SCNtohl(168430079) && + two->ip.addr_data32[0] == SCNtohl(168430080) && + two->ip2.addr_data32[0] == SCNtohl(168430089) && + three->ip.addr_data32[0] == SCNtohl(168430090) && + three->ip2.addr_data32[0] == SCNtohl(168430335) && + four->ip.addr_data32[0] == SCNtohl(168430336) && + four->ip2.addr_data32[0] == SCNtohl(168430337) && + five->ip.addr_data32[0] == SCNtohl(168430338) && + five->ip2.addr_data32[0] == 0xFFFFFFFF) { result = 1; } } @@ -3381,7 +3427,7 @@ static int AddressTestAddressGroupSetup11(void) return result; } -static int AddressTestAddressGroupSetup12 (void) +static int AddressTestAddressGroupSetup12(void) { int result = 0; DetectAddressHead *gh = DetectAddressHeadInit(); @@ -3393,9 +3439,8 @@ static int AddressTestAddressGroupSetup12 (void) if (r == 0) { r = DetectAddressParse(NULL, gh, "10.10.10.0/24"); if (r == 0) { - DetectAddress *one = gh->ipv4_head, *two = one->next, - *three = two->next, *four = three->next, - *five = four->next; + DetectAddress *one = gh->ipv4_head, *two = one->next, *three = two->next, + *four = three->next, *five = four->next; /* result should be: * 0.0.0.0/10.10.9.255 @@ -3404,11 +3449,16 @@ static int AddressTestAddressGroupSetup12 (void) * 10.10.11.0/10.10.11.1 * 10.10.11.2/255.255.255.255 */ - if (one->ip.addr_data32[0] == 0x00000000 && one->ip2.addr_data32[0] == SCNtohl(168430079) && - two->ip.addr_data32[0] == SCNtohl(168430080) && two->ip2.addr_data32[0] == SCNtohl(168430089) && - three->ip.addr_data32[0] == SCNtohl(168430090) && three->ip2.addr_data32[0] == SCNtohl(168430335) && - four->ip.addr_data32[0] == SCNtohl(168430336) && four->ip2.addr_data32[0] == SCNtohl(168430337) && - five->ip.addr_data32[0] == SCNtohl(168430338) && five->ip2.addr_data32[0] == 0xFFFFFFFF) { + if (one->ip.addr_data32[0] == 0x00000000 && + one->ip2.addr_data32[0] == SCNtohl(168430079) && + two->ip.addr_data32[0] == SCNtohl(168430080) && + two->ip2.addr_data32[0] == SCNtohl(168430089) && + three->ip.addr_data32[0] == SCNtohl(168430090) && + three->ip2.addr_data32[0] == SCNtohl(168430335) && + four->ip.addr_data32[0] == SCNtohl(168430336) && + four->ip2.addr_data32[0] == SCNtohl(168430337) && + five->ip.addr_data32[0] == SCNtohl(168430338) && + five->ip2.addr_data32[0] == 0xFFFFFFFF) { result = 1; } } @@ -3432,9 +3482,8 @@ static int AddressTestAddressGroupSetup13(void) if (r == 0) { r = DetectAddressParse(NULL, gh, "10.10.10.0/24"); if (r == 0) { - DetectAddress *one = gh->ipv4_head, *two = one->next, - *three = two->next, *four = three->next, - *five = four->next; + DetectAddress *one = gh->ipv4_head, *two = one->next, *three = two->next, + *four = three->next, *five = four->next; /* result should be: * 0.0.0.0/10.10.9.255 @@ -3443,11 +3492,16 @@ static int AddressTestAddressGroupSetup13(void) * 10.10.11.0/10.10.11.1 * 10.10.11.2/255.255.255.255 */ - if (one->ip.addr_data32[0] == 0x00000000 && one->ip2.addr_data32[0] == SCNtohl(168430079) && - two->ip.addr_data32[0] == SCNtohl(168430080) && two->ip2.addr_data32[0] == SCNtohl(168430089) && - three->ip.addr_data32[0] == SCNtohl(168430090) && three->ip2.addr_data32[0] == SCNtohl(168430335) && - four->ip.addr_data32[0] == SCNtohl(168430336) && four->ip2.addr_data32[0] == SCNtohl(168430337) && - five->ip.addr_data32[0] == SCNtohl(168430338) && five->ip2.addr_data32[0] == 0xFFFFFFFF) { + if (one->ip.addr_data32[0] == 0x00000000 && + one->ip2.addr_data32[0] == SCNtohl(168430079) && + two->ip.addr_data32[0] == SCNtohl(168430080) && + two->ip2.addr_data32[0] == SCNtohl(168430089) && + three->ip.addr_data32[0] == SCNtohl(168430090) && + three->ip2.addr_data32[0] == SCNtohl(168430335) && + four->ip.addr_data32[0] == SCNtohl(168430336) && + four->ip2.addr_data32[0] == SCNtohl(168430337) && + five->ip.addr_data32[0] == SCNtohl(168430338) && + five->ip2.addr_data32[0] == 0xFFFFFFFF) { result = 1; } } @@ -3570,8 +3624,8 @@ static int AddressTestAddressGroupSetup16(void) DetectAddress *prev_head = gh->ipv6_head; r = DetectAddressParse(NULL, gh, "2001::3"); - if (r == 0 && gh->ipv6_head != prev_head && - gh->ipv6_head != NULL && gh->ipv6_head->next == prev_head) { + if (r == 0 && gh->ipv6_head != prev_head && gh->ipv6_head != NULL && + gh->ipv6_head->next == prev_head) { result = 1; } } @@ -3592,13 +3646,13 @@ static int AddressTestAddressGroupSetup17(void) DetectAddress *prev_head = gh->ipv6_head; r = DetectAddressParse(NULL, gh, "2001::3"); - if (r == 0 && gh->ipv6_head != prev_head && - gh->ipv6_head != NULL && gh->ipv6_head->next == prev_head) { + if (r == 0 && gh->ipv6_head != prev_head && gh->ipv6_head != NULL && + gh->ipv6_head->next == prev_head) { DetectAddress *ph = gh->ipv6_head; r = DetectAddressParse(NULL, gh, "2001::2"); - if (r == 0 && gh->ipv6_head != ph && - gh->ipv6_head != NULL && gh->ipv6_head->next == ph) { + if (r == 0 && gh->ipv6_head != ph && gh->ipv6_head != NULL && + gh->ipv6_head->next == ph) { result = 1; } } @@ -3620,13 +3674,13 @@ static int AddressTestAddressGroupSetup18(void) DetectAddress *prev_head = gh->ipv6_head; r = DetectAddressParse(NULL, gh, "2001::3"); - if (r == 0 && gh->ipv6_head == prev_head && - gh->ipv6_head != NULL && gh->ipv6_head->next != prev_head) { + if (r == 0 && gh->ipv6_head == prev_head && gh->ipv6_head != NULL && + gh->ipv6_head->next != prev_head) { DetectAddress *ph = gh->ipv6_head; r = DetectAddressParse(NULL, gh, "2001::4"); - if (r == 0 && gh->ipv6_head == ph && - gh->ipv6_head != NULL && gh->ipv6_head->next != ph) { + if (r == 0 && gh->ipv6_head == ph && gh->ipv6_head != NULL && + gh->ipv6_head->next != ph) { result = 1; } } @@ -3648,8 +3702,8 @@ static int AddressTestAddressGroupSetup19(void) DetectAddress *prev_head = gh->ipv6_head; r = DetectAddressParse(NULL, gh, "2001::2"); - if (r == 0 && gh->ipv6_head == prev_head && - gh->ipv6_head != NULL && gh->ipv6_head->next == NULL) { + if (r == 0 && gh->ipv6_head == prev_head && gh->ipv6_head != NULL && + gh->ipv6_head->next == NULL) { result = 1; } } @@ -3668,9 +3722,8 @@ static int AddressTestAddressGroupSetup20(void) int r = DetectAddressParse(NULL, gh, "2000::/3"); if (r == 0 && gh->ipv6_head != NULL) { r = DetectAddressParse(NULL, gh, "2001::4"); - if (r == 0 && gh->ipv6_head != NULL && - gh->ipv6_head->next != NULL && - gh->ipv6_head->next->next != NULL) { + if (r == 0 && gh->ipv6_head != NULL && gh->ipv6_head->next != NULL && + gh->ipv6_head->next->next != NULL) { result = 1; } } @@ -3689,9 +3742,8 @@ static int AddressTestAddressGroupSetup21(void) int r = DetectAddressParse(NULL, gh, "2001::4"); if (r == 0 && gh->ipv6_head != NULL) { r = DetectAddressParse(NULL, gh, "2000::/3"); - if (r == 0 && gh->ipv6_head != NULL && - gh->ipv6_head->next != NULL && - gh->ipv6_head->next->next != NULL) { + if (r == 0 && gh->ipv6_head != NULL && gh->ipv6_head->next != NULL && + gh->ipv6_head->next->next != NULL) { result = 1; } } @@ -3710,9 +3762,8 @@ static int AddressTestAddressGroupSetup22(void) int r = DetectAddressParse(NULL, gh, "2000::/3"); if (r == 0 && gh->ipv6_head != NULL) { r = DetectAddressParse(NULL, gh, "2001::4-2001::6"); - if (r == 0 && gh->ipv6_head != NULL && - gh->ipv6_head->next != NULL && - gh->ipv6_head->next->next != NULL) { + if (r == 0 && gh->ipv6_head != NULL && gh->ipv6_head->next != NULL && + gh->ipv6_head->next->next != NULL) { result = 1; } } @@ -3731,9 +3782,8 @@ static int AddressTestAddressGroupSetup23(void) int r = DetectAddressParse(NULL, gh, "2001::4-2001::6"); if (r == 0 && gh->ipv6_head != NULL) { r = DetectAddressParse(NULL, gh, "2000::/3"); - if (r == 0 && gh->ipv6_head != NULL && - gh->ipv6_head->next != NULL && - gh->ipv6_head->next->next != NULL) { + if (r == 0 && gh->ipv6_head != NULL && gh->ipv6_head->next != NULL && + gh->ipv6_head->next->next != NULL) { result = 1; } } @@ -3755,53 +3805,52 @@ static int AddressTestAddressGroupSetup24(void) if (r == 0) { r = DetectAddressParse(NULL, gh, "::/0"); if (r == 0) { - DetectAddress *one = gh->ipv6_head, *two = one->next, - *three = two->next, *four = three->next, - *five = four->next; + DetectAddress *one = gh->ipv6_head, *two = one->next, *three = two->next, + *four = three->next, *five = four->next; if (one->ip.addr_data32[0] == 0x00000000 && - one->ip.addr_data32[1] == 0x00000000 && - one->ip.addr_data32[2] == 0x00000000 && - one->ip.addr_data32[3] == 0x00000000 && - one->ip2.addr_data32[0] == SCNtohl(536870911) && - one->ip2.addr_data32[1] == 0xFFFFFFFF && - one->ip2.addr_data32[2] == 0xFFFFFFFF && - one->ip2.addr_data32[3] == 0xFFFFFFFF && - - two->ip.addr_data32[0] == SCNtohl(536870912) && - two->ip.addr_data32[1] == 0x00000000 && - two->ip.addr_data32[2] == 0x00000000 && - two->ip.addr_data32[3] == 0x00000000 && - two->ip2.addr_data32[0] == SCNtohl(536936448) && - two->ip2.addr_data32[1] == 0x00000000 && - two->ip2.addr_data32[2] == 0x00000000 && - two->ip2.addr_data32[3] == SCNtohl(3) && - - three->ip.addr_data32[0] == SCNtohl(536936448) && - three->ip.addr_data32[1] == 0x00000000 && - three->ip.addr_data32[2] == 0x00000000 && - three->ip.addr_data32[3] == SCNtohl(4) && - three->ip2.addr_data32[0] == SCNtohl(536936448) && - three->ip2.addr_data32[1] == 0x00000000 && - three->ip2.addr_data32[2] == 0x00000000 && - three->ip2.addr_data32[3] == SCNtohl(6) && - - four->ip.addr_data32[0] == SCNtohl(536936448) && - four->ip.addr_data32[1] == 0x00000000 && - four->ip.addr_data32[2] == 0x00000000 && - four->ip.addr_data32[3] == SCNtohl(7) && - four->ip2.addr_data32[0] == SCNtohl(1073741823) && - four->ip2.addr_data32[1] == 0xFFFFFFFF && - four->ip2.addr_data32[2] == 0xFFFFFFFF && - four->ip2.addr_data32[3] == 0xFFFFFFFF && - - five->ip.addr_data32[0] == SCNtohl(1073741824) && - five->ip.addr_data32[1] == 0x00000000 && - five->ip.addr_data32[2] == 0x00000000 && - five->ip.addr_data32[3] == 0x00000000 && - five->ip2.addr_data32[0] == 0xFFFFFFFF && - five->ip2.addr_data32[1] == 0xFFFFFFFF && - five->ip2.addr_data32[2] == 0xFFFFFFFF && - five->ip2.addr_data32[3] == 0xFFFFFFFF) { + one->ip.addr_data32[1] == 0x00000000 && + one->ip.addr_data32[2] == 0x00000000 && + one->ip.addr_data32[3] == 0x00000000 && + one->ip2.addr_data32[0] == SCNtohl(536870911) && + one->ip2.addr_data32[1] == 0xFFFFFFFF && + one->ip2.addr_data32[2] == 0xFFFFFFFF && + one->ip2.addr_data32[3] == 0xFFFFFFFF && + + two->ip.addr_data32[0] == SCNtohl(536870912) && + two->ip.addr_data32[1] == 0x00000000 && + two->ip.addr_data32[2] == 0x00000000 && + two->ip.addr_data32[3] == 0x00000000 && + two->ip2.addr_data32[0] == SCNtohl(536936448) && + two->ip2.addr_data32[1] == 0x00000000 && + two->ip2.addr_data32[2] == 0x00000000 && + two->ip2.addr_data32[3] == SCNtohl(3) && + + three->ip.addr_data32[0] == SCNtohl(536936448) && + three->ip.addr_data32[1] == 0x00000000 && + three->ip.addr_data32[2] == 0x00000000 && + three->ip.addr_data32[3] == SCNtohl(4) && + three->ip2.addr_data32[0] == SCNtohl(536936448) && + three->ip2.addr_data32[1] == 0x00000000 && + three->ip2.addr_data32[2] == 0x00000000 && + three->ip2.addr_data32[3] == SCNtohl(6) && + + four->ip.addr_data32[0] == SCNtohl(536936448) && + four->ip.addr_data32[1] == 0x00000000 && + four->ip.addr_data32[2] == 0x00000000 && + four->ip.addr_data32[3] == SCNtohl(7) && + four->ip2.addr_data32[0] == SCNtohl(1073741823) && + four->ip2.addr_data32[1] == 0xFFFFFFFF && + four->ip2.addr_data32[2] == 0xFFFFFFFF && + four->ip2.addr_data32[3] == 0xFFFFFFFF && + + five->ip.addr_data32[0] == SCNtohl(1073741824) && + five->ip.addr_data32[1] == 0x00000000 && + five->ip.addr_data32[2] == 0x00000000 && + five->ip.addr_data32[3] == 0x00000000 && + five->ip2.addr_data32[0] == 0xFFFFFFFF && + five->ip2.addr_data32[1] == 0xFFFFFFFF && + five->ip2.addr_data32[2] == 0xFFFFFFFF && + five->ip2.addr_data32[3] == 0xFFFFFFFF) { result = 1; } } @@ -3825,53 +3874,52 @@ static int AddressTestAddressGroupSetup25(void) if (r == 0) { r = DetectAddressParse(NULL, gh, "2001::/3"); if (r == 0) { - DetectAddress *one = gh->ipv6_head, *two = one->next, - *three = two->next, *four = three->next, - *five = four->next; + DetectAddress *one = gh->ipv6_head, *two = one->next, *three = two->next, + *four = three->next, *five = four->next; if (one->ip.addr_data32[0] == 0x00000000 && - one->ip.addr_data32[1] == 0x00000000 && - one->ip.addr_data32[2] == 0x00000000 && - one->ip.addr_data32[3] == 0x00000000 && - one->ip2.addr_data32[0] == SCNtohl(536870911) && - one->ip2.addr_data32[1] == 0xFFFFFFFF && - one->ip2.addr_data32[2] == 0xFFFFFFFF && - one->ip2.addr_data32[3] == 0xFFFFFFFF && - - two->ip.addr_data32[0] == SCNtohl(536870912) && - two->ip.addr_data32[1] == 0x00000000 && - two->ip.addr_data32[2] == 0x00000000 && - two->ip.addr_data32[3] == 0x00000000 && - two->ip2.addr_data32[0] == SCNtohl(536936448) && - two->ip2.addr_data32[1] == 0x00000000 && - two->ip2.addr_data32[2] == 0x00000000 && - two->ip2.addr_data32[3] == SCNtohl(3) && - - three->ip.addr_data32[0] == SCNtohl(536936448) && - three->ip.addr_data32[1] == 0x00000000 && - three->ip.addr_data32[2] == 0x00000000 && - three->ip.addr_data32[3] == SCNtohl(4) && - three->ip2.addr_data32[0] == SCNtohl(536936448) && - three->ip2.addr_data32[1] == 0x00000000 && - three->ip2.addr_data32[2] == 0x00000000 && - three->ip2.addr_data32[3] == SCNtohl(6) && - - four->ip.addr_data32[0] == SCNtohl(536936448) && - four->ip.addr_data32[1] == 0x00000000 && - four->ip.addr_data32[2] == 0x00000000 && - four->ip.addr_data32[3] == SCNtohl(7) && - four->ip2.addr_data32[0] == SCNtohl(1073741823) && - four->ip2.addr_data32[1] == 0xFFFFFFFF && - four->ip2.addr_data32[2] == 0xFFFFFFFF && - four->ip2.addr_data32[3] == 0xFFFFFFFF && - - five->ip.addr_data32[0] == SCNtohl(1073741824) && - five->ip.addr_data32[1] == 0x00000000 && - five->ip.addr_data32[2] == 0x00000000 && - five->ip.addr_data32[3] == 0x00000000 && - five->ip2.addr_data32[0] == 0xFFFFFFFF && - five->ip2.addr_data32[1] == 0xFFFFFFFF && - five->ip2.addr_data32[2] == 0xFFFFFFFF && - five->ip2.addr_data32[3] == 0xFFFFFFFF) { + one->ip.addr_data32[1] == 0x00000000 && + one->ip.addr_data32[2] == 0x00000000 && + one->ip.addr_data32[3] == 0x00000000 && + one->ip2.addr_data32[0] == SCNtohl(536870911) && + one->ip2.addr_data32[1] == 0xFFFFFFFF && + one->ip2.addr_data32[2] == 0xFFFFFFFF && + one->ip2.addr_data32[3] == 0xFFFFFFFF && + + two->ip.addr_data32[0] == SCNtohl(536870912) && + two->ip.addr_data32[1] == 0x00000000 && + two->ip.addr_data32[2] == 0x00000000 && + two->ip.addr_data32[3] == 0x00000000 && + two->ip2.addr_data32[0] == SCNtohl(536936448) && + two->ip2.addr_data32[1] == 0x00000000 && + two->ip2.addr_data32[2] == 0x00000000 && + two->ip2.addr_data32[3] == SCNtohl(3) && + + three->ip.addr_data32[0] == SCNtohl(536936448) && + three->ip.addr_data32[1] == 0x00000000 && + three->ip.addr_data32[2] == 0x00000000 && + three->ip.addr_data32[3] == SCNtohl(4) && + three->ip2.addr_data32[0] == SCNtohl(536936448) && + three->ip2.addr_data32[1] == 0x00000000 && + three->ip2.addr_data32[2] == 0x00000000 && + three->ip2.addr_data32[3] == SCNtohl(6) && + + four->ip.addr_data32[0] == SCNtohl(536936448) && + four->ip.addr_data32[1] == 0x00000000 && + four->ip.addr_data32[2] == 0x00000000 && + four->ip.addr_data32[3] == SCNtohl(7) && + four->ip2.addr_data32[0] == SCNtohl(1073741823) && + four->ip2.addr_data32[1] == 0xFFFFFFFF && + four->ip2.addr_data32[2] == 0xFFFFFFFF && + four->ip2.addr_data32[3] == 0xFFFFFFFF && + + five->ip.addr_data32[0] == SCNtohl(1073741824) && + five->ip.addr_data32[1] == 0x00000000 && + five->ip.addr_data32[2] == 0x00000000 && + five->ip.addr_data32[3] == 0x00000000 && + five->ip2.addr_data32[0] == 0xFFFFFFFF && + five->ip2.addr_data32[1] == 0xFFFFFFFF && + five->ip2.addr_data32[2] == 0xFFFFFFFF && + five->ip2.addr_data32[3] == 0xFFFFFFFF) { result = 1; } } @@ -3895,53 +3943,52 @@ static int AddressTestAddressGroupSetup26(void) if (r == 0) { r = DetectAddressParse(NULL, gh, "2001::/3"); if (r == 0) { - DetectAddress *one = gh->ipv6_head, *two = one->next, - *three = two->next, *four = three->next, - *five = four->next; + DetectAddress *one = gh->ipv6_head, *two = one->next, *three = two->next, + *four = three->next, *five = four->next; if (one->ip.addr_data32[0] == 0x00000000 && - one->ip.addr_data32[1] == 0x00000000 && - one->ip.addr_data32[2] == 0x00000000 && - one->ip.addr_data32[3] == 0x00000000 && - one->ip2.addr_data32[0] == SCNtohl(536870911) && - one->ip2.addr_data32[1] == 0xFFFFFFFF && - one->ip2.addr_data32[2] == 0xFFFFFFFF && - one->ip2.addr_data32[3] == 0xFFFFFFFF && - - two->ip.addr_data32[0] == SCNtohl(536870912) && - two->ip.addr_data32[1] == 0x00000000 && - two->ip.addr_data32[2] == 0x00000000 && - two->ip.addr_data32[3] == 0x00000000 && - two->ip2.addr_data32[0] == SCNtohl(536936448) && - two->ip2.addr_data32[1] == 0x00000000 && - two->ip2.addr_data32[2] == 0x00000000 && - two->ip2.addr_data32[3] == SCNtohl(3) && - - three->ip.addr_data32[0] == SCNtohl(536936448) && - three->ip.addr_data32[1] == 0x00000000 && - three->ip.addr_data32[2] == 0x00000000 && - three->ip.addr_data32[3] == SCNtohl(4) && - three->ip2.addr_data32[0] == SCNtohl(536936448) && - three->ip2.addr_data32[1] == 0x00000000 && - three->ip2.addr_data32[2] == 0x00000000 && - three->ip2.addr_data32[3] == SCNtohl(6) && - - four->ip.addr_data32[0] == SCNtohl(536936448) && - four->ip.addr_data32[1] == 0x00000000 && - four->ip.addr_data32[2] == 0x00000000 && - four->ip.addr_data32[3] == SCNtohl(7) && - four->ip2.addr_data32[0] == SCNtohl(1073741823) && - four->ip2.addr_data32[1] == 0xFFFFFFFF && - four->ip2.addr_data32[2] == 0xFFFFFFFF && - four->ip2.addr_data32[3] == 0xFFFFFFFF && - - five->ip.addr_data32[0] == SCNtohl(1073741824) && - five->ip.addr_data32[1] == 0x00000000 && - five->ip.addr_data32[2] == 0x00000000 && - five->ip.addr_data32[3] == 0x00000000 && - five->ip2.addr_data32[0] == 0xFFFFFFFF && - five->ip2.addr_data32[1] == 0xFFFFFFFF && - five->ip2.addr_data32[2] == 0xFFFFFFFF && - five->ip2.addr_data32[3] == 0xFFFFFFFF) { + one->ip.addr_data32[1] == 0x00000000 && + one->ip.addr_data32[2] == 0x00000000 && + one->ip.addr_data32[3] == 0x00000000 && + one->ip2.addr_data32[0] == SCNtohl(536870911) && + one->ip2.addr_data32[1] == 0xFFFFFFFF && + one->ip2.addr_data32[2] == 0xFFFFFFFF && + one->ip2.addr_data32[3] == 0xFFFFFFFF && + + two->ip.addr_data32[0] == SCNtohl(536870912) && + two->ip.addr_data32[1] == 0x00000000 && + two->ip.addr_data32[2] == 0x00000000 && + two->ip.addr_data32[3] == 0x00000000 && + two->ip2.addr_data32[0] == SCNtohl(536936448) && + two->ip2.addr_data32[1] == 0x00000000 && + two->ip2.addr_data32[2] == 0x00000000 && + two->ip2.addr_data32[3] == SCNtohl(3) && + + three->ip.addr_data32[0] == SCNtohl(536936448) && + three->ip.addr_data32[1] == 0x00000000 && + three->ip.addr_data32[2] == 0x00000000 && + three->ip.addr_data32[3] == SCNtohl(4) && + three->ip2.addr_data32[0] == SCNtohl(536936448) && + three->ip2.addr_data32[1] == 0x00000000 && + three->ip2.addr_data32[2] == 0x00000000 && + three->ip2.addr_data32[3] == SCNtohl(6) && + + four->ip.addr_data32[0] == SCNtohl(536936448) && + four->ip.addr_data32[1] == 0x00000000 && + four->ip.addr_data32[2] == 0x00000000 && + four->ip.addr_data32[3] == SCNtohl(7) && + four->ip2.addr_data32[0] == SCNtohl(1073741823) && + four->ip2.addr_data32[1] == 0xFFFFFFFF && + four->ip2.addr_data32[2] == 0xFFFFFFFF && + four->ip2.addr_data32[3] == 0xFFFFFFFF && + + five->ip.addr_data32[0] == SCNtohl(1073741824) && + five->ip.addr_data32[1] == 0x00000000 && + five->ip.addr_data32[2] == 0x00000000 && + five->ip.addr_data32[3] == 0x00000000 && + five->ip2.addr_data32[0] == 0xFFFFFFFF && + five->ip2.addr_data32[1] == 0xFFFFFFFF && + five->ip2.addr_data32[2] == 0xFFFFFFFF && + five->ip2.addr_data32[3] == 0xFFFFFFFF) { result = 1; } } @@ -4004,7 +4051,8 @@ static int AddressTestAddressGroupSetup30(void) DetectAddressHead *gh = DetectAddressHeadInit(); if (gh != NULL) { - int r = DetectAddressParse(NULL, gh, "[[1.2.3.4,2.3.4.5],4.3.2.1,[10.10.10.10,11.11.11.11]]"); + int r = DetectAddressParse( + NULL, gh, "[[1.2.3.4,2.3.4.5],4.3.2.1,[10.10.10.10,11.11.11.11]]"); if (r == 0) result = 1; @@ -4019,7 +4067,8 @@ static int AddressTestAddressGroupSetup31(void) DetectAddressHead *gh = DetectAddressHeadInit(); if (gh != NULL) { - int r = DetectAddressParse(NULL, gh, "[[1.2.3.4,[2.3.4.5,3.4.5.6]],4.3.2.1,[10.10.10.10,[11.11.11.11,12.12.12.12]]]"); + int r = DetectAddressParse(NULL, gh, + "[[1.2.3.4,[2.3.4.5,3.4.5.6]],4.3.2.1,[10.10.10.10,[11.11.11.11,12.12.12.12]]]"); if (r == 0) result = 1; @@ -4034,7 +4083,9 @@ static int AddressTestAddressGroupSetup32(void) DetectAddressHead *gh = DetectAddressHeadInit(); if (gh != NULL) { - int r = DetectAddressParse(NULL, gh, "[[1.2.3.4,[2.3.4.5,[3.4.5.6,4.5.6.7]]],4.3.2.1,[10.10.10.10,[11.11.11.11,[12.12.12.12,13.13.13.13]]]]"); + int r = DetectAddressParse(NULL, gh, + "[[1.2.3.4,[2.3.4.5,[3.4.5.6,4.5.6.7]]],4.3.2.1,[10.10.10.10,[11.11.11.11,[12.12." + "12.12,13.13.13.13]]]]"); if (r == 0) result = 1; @@ -4088,7 +4139,7 @@ static int AddressTestAddressGroupSetup35(void) return result; } -static int AddressTestAddressGroupSetup36 (void) +static int AddressTestAddressGroupSetup36(void) { int result = 0; @@ -4120,10 +4171,8 @@ static int AddressTestAddressGroupSetup37(void) static int AddressTestAddressGroupSetup38(void) { - UTHValidateDetectAddressHeadRange expectations[3] = { - { "0.0.0.0", "192.167.255.255" }, - { "192.168.14.0", "192.168.14.255" }, - { "192.169.0.0", "255.255.255.255" } }; + UTHValidateDetectAddressHeadRange expectations[3] = { { "0.0.0.0", "192.167.255.255" }, + { "192.168.14.0", "192.168.14.255" }, { "192.169.0.0", "255.255.255.255" } }; int result = 0; DetectAddressHead *gh = DetectAddressHeadInit(); @@ -4141,10 +4190,8 @@ static int AddressTestAddressGroupSetup38(void) static int AddressTestAddressGroupSetup39(void) { - UTHValidateDetectAddressHeadRange expectations[3] = { - { "0.0.0.0", "192.167.255.255" }, - { "192.168.14.0", "192.168.14.255" }, - { "192.169.0.0", "255.255.255.255" } }; + UTHValidateDetectAddressHeadRange expectations[3] = { { "0.0.0.0", "192.167.255.255" }, + { "192.168.14.0", "192.168.14.255" }, { "192.169.0.0", "255.255.255.255" } }; int result = 0; DetectAddressHead *gh = DetectAddressHeadInit(); @@ -4162,10 +4209,8 @@ static int AddressTestAddressGroupSetup39(void) static int AddressTestAddressGroupSetup40(void) { - UTHValidateDetectAddressHeadRange expectations[3] = { - { "0.0.0.0", "192.167.255.255" }, - { "192.168.14.0", "192.168.14.255" }, - { "192.169.0.0", "255.255.255.255" } }; + UTHValidateDetectAddressHeadRange expectations[3] = { { "0.0.0.0", "192.167.255.255" }, + { "192.168.14.0", "192.168.14.255" }, { "192.169.0.0", "255.255.255.255" } }; int result = 0; DetectAddressHead *gh = DetectAddressHeadInit(); if (gh != NULL) { @@ -4182,10 +4227,8 @@ static int AddressTestAddressGroupSetup40(void) static int AddressTestAddressGroupSetup41(void) { - UTHValidateDetectAddressHeadRange expectations[3] = { - { "0.0.0.0", "192.167.255.255" }, - { "192.168.14.0", "192.168.14.255" }, - { "192.169.0.0", "255.255.255.255" } }; + UTHValidateDetectAddressHeadRange expectations[3] = { { "0.0.0.0", "192.167.255.255" }, + { "192.168.14.0", "192.168.14.255" }, { "192.169.0.0", "255.255.255.255" } }; int result = 0; DetectAddressHead *gh = DetectAddressHeadInit(); if (gh != NULL) { @@ -4203,7 +4246,8 @@ static int AddressTestAddressGroupSetup41(void) static int AddressTestAddressGroupSetup42(void) { UTHValidateDetectAddressHeadRange expectations[1] = { - { "2000:0000:0000:0000:0000:0000:0000:0000", "3fff:ffff:ffff:ffff:ffff:ffff:ffff:ffff" } }; + { "2000:0000:0000:0000:0000:0000:0000:0000", "3fff:ffff:ffff:ffff:ffff:ffff:ffff:ffff" } + }; int result = 0; DetectAddressHead *gh = DetectAddressHeadInit(); if (gh != NULL) { @@ -4222,7 +4266,8 @@ static int AddressTestAddressGroupSetup43(void) { UTHValidateDetectAddressHeadRange expectations[2] = { { "2000:0000:0000:0000:0000:0000:0000:0000", "2fff:ffff:ffff:ffff:ffff:ffff:ffff:ffff" }, - { "3800:0000:0000:0000:0000:0000:0000:0000", "3fff:ffff:ffff:ffff:ffff:ffff:ffff:ffff" } }; + { "3800:0000:0000:0000:0000:0000:0000:0000", "3fff:ffff:ffff:ffff:ffff:ffff:ffff:ffff" } + }; int result = 0; DetectAddressHead *gh = DetectAddressHeadInit(); if (gh != NULL) { @@ -4240,7 +4285,8 @@ static int AddressTestAddressGroupSetup43(void) static int AddressTestAddressGroupSetup44(void) { UTHValidateDetectAddressHeadRange expectations[2] = { - { "3ffe:ffff:7654:feda:1245:ba98:0000:0000", "3ffe:ffff:7654:feda:1245:ba98:ffff:ffff" }}; + { "3ffe:ffff:7654:feda:1245:ba98:0000:0000", "3ffe:ffff:7654:feda:1245:ba98:ffff:ffff" } + }; int result = 0; DetectAddressHead *gh = DetectAddressHeadInit(); if (gh != NULL) { @@ -4272,15 +4318,14 @@ static int AddressTestAddressGroupSetup45(void) static int AddressTestAddressGroupSetup46(void) { - UTHValidateDetectAddressHeadRange expectations[4] = { - { "0.0.0.0", "192.167.255.255" }, - { "192.168.1.0", "192.168.1.255" }, - { "192.168.3.0", "192.168.3.255" }, + UTHValidateDetectAddressHeadRange expectations[4] = { { "0.0.0.0", "192.167.255.255" }, + { "192.168.1.0", "192.168.1.255" }, { "192.168.3.0", "192.168.3.255" }, { "192.169.0.0", "255.255.255.255" } }; int result = 0; DetectAddressHead *gh = DetectAddressHeadInit(); if (gh != NULL) { - int r = DetectAddressParse(NULL, gh, "[![192.168.0.0/16,![192.168.1.0/24,192.168.3.0/24]]]"); + int r = DetectAddressParse( + NULL, gh, "[![192.168.0.0/16,![192.168.1.0/24,192.168.3.0/24]]]"); if (r == 1) { if (UTHValidateDetectAddressHead(gh, 4, expectations)) result = 1; @@ -4294,16 +4339,14 @@ static int AddressTestAddressGroupSetup46(void) /** \test net with some negations, then all negated */ static int AddressTestAddressGroupSetup47(void) { - UTHValidateDetectAddressHeadRange expectations[5] = { - { "0.0.0.0", "192.167.255.255" }, - { "192.168.1.0", "192.168.1.255" }, - { "192.168.3.0", "192.168.3.255" }, - { "192.168.5.0", "192.168.5.255" }, - { "192.169.0.0", "255.255.255.255" } }; + UTHValidateDetectAddressHeadRange expectations[5] = { { "0.0.0.0", "192.167.255.255" }, + { "192.168.1.0", "192.168.1.255" }, { "192.168.3.0", "192.168.3.255" }, + { "192.168.5.0", "192.168.5.255" }, { "192.169.0.0", "255.255.255.255" } }; int result = 0; DetectAddressHead *gh = DetectAddressHeadInit(); if (gh != NULL) { - int r = DetectAddressParse(NULL, gh, "[![192.168.0.0/16,![192.168.1.0/24,192.168.3.0/24],!192.168.5.0/24]]"); + int r = DetectAddressParse( + NULL, gh, "[![192.168.0.0/16,![192.168.1.0/24,192.168.3.0/24],!192.168.5.0/24]]"); if (r == 1) { if (UTHValidateDetectAddressHead(gh, 5, expectations)) result = 1; @@ -4317,15 +4360,14 @@ static int AddressTestAddressGroupSetup47(void) /** \test same as AddressTestAddressGroupSetup47, but not negated */ static int AddressTestAddressGroupSetup48(void) { - UTHValidateDetectAddressHeadRange expectations[4] = { - { "192.168.0.0", "192.168.0.255" }, - { "192.168.2.0", "192.168.2.255" }, - { "192.168.4.0", "192.168.4.255" }, + UTHValidateDetectAddressHeadRange expectations[4] = { { "192.168.0.0", "192.168.0.255" }, + { "192.168.2.0", "192.168.2.255" }, { "192.168.4.0", "192.168.4.255" }, { "192.168.6.0", "192.168.255.255" } }; int result = 0; DetectAddressHead *gh = DetectAddressHeadInit(); if (gh != NULL) { - int r = DetectAddressParse(NULL, gh, "[192.168.0.0/16,![192.168.1.0/24,192.168.3.0/24],!192.168.5.0/24]"); + int r = DetectAddressParse( + NULL, gh, "[192.168.0.0/16,![192.168.1.0/24,192.168.3.0/24],!192.168.5.0/24]"); if (r == 1) { if (UTHValidateDetectAddressHead(gh, 4, expectations)) result = 1; @@ -4426,7 +4468,6 @@ static int AddressTestCutIPv404(void) if (c->ip.addr_data32[0] != SCNtohl(16909062) || c->ip2.addr_data32[0] != SCNtohl(16909062)) goto error; - DetectAddressFree(a); DetectAddressFree(b); DetectAddressFree(c); @@ -4605,7 +4646,8 @@ static int AddressTestCutIPv410(void) if (b->ip.addr_data32[0] != SCNtohl(16909059) || b->ip2.addr_data32[0] != SCNtohl(16909065)) goto error; - printf("ip %u ip2 %u ", (uint32_t)htonl(a->ip.addr_data32[0]), (uint32_t)htonl(a->ip2.addr_data32[0])); + printf("ip %u ip2 %u ", (uint32_t)htonl(a->ip.addr_data32[0]), + (uint32_t)htonl(a->ip2.addr_data32[0])); DetectAddressFree(a); DetectAddressFree(b); @@ -4660,24 +4702,23 @@ static int AddressTestParseInvalidMask03(void) static int AddressConfVarsTest01(void) { - static const char *dummy_conf_string = - "%YAML 1.1\n" - "---\n" - "\n" - "vars:\n" - "\n" - " address-groups:\n" - "\n" - " HOME_NET: \"any\"\n" - "\n" - " EXTERNAL_NET: \"!any\"\n" - "\n" - " port-groups:\n" - "\n" - " HTTP_PORTS: \"any\"\n" - "\n" - " SHELLCODE_PORTS: \"!any\"\n" - "\n"; + static const char *dummy_conf_string = "%YAML 1.1\n" + "---\n" + "\n" + "vars:\n" + "\n" + " address-groups:\n" + "\n" + " HOME_NET: \"any\"\n" + "\n" + " EXTERNAL_NET: \"!any\"\n" + "\n" + " port-groups:\n" + "\n" + " HTTP_PORTS: \"any\"\n" + "\n" + " SHELLCODE_PORTS: \"!any\"\n" + "\n"; int result = 0; @@ -4696,24 +4737,23 @@ static int AddressConfVarsTest01(void) static int AddressConfVarsTest02(void) { - static const char *dummy_conf_string = - "%YAML 1.1\n" - "---\n" - "\n" - "vars:\n" - "\n" - " address-groups:\n" - "\n" - " HOME_NET: \"any\"\n" - "\n" - " EXTERNAL_NET: \"any\"\n" - "\n" - " port-groups:\n" - "\n" - " HTTP_PORTS: \"any\"\n" - "\n" - " SHELLCODE_PORTS: \"!any\"\n" - "\n"; + static const char *dummy_conf_string = "%YAML 1.1\n" + "---\n" + "\n" + "vars:\n" + "\n" + " address-groups:\n" + "\n" + " HOME_NET: \"any\"\n" + "\n" + " EXTERNAL_NET: \"any\"\n" + "\n" + " port-groups:\n" + "\n" + " HTTP_PORTS: \"any\"\n" + "\n" + " SHELLCODE_PORTS: \"!any\"\n" + "\n"; int result = 0; @@ -4732,24 +4772,23 @@ static int AddressConfVarsTest02(void) static int AddressConfVarsTest03(void) { - static const char *dummy_conf_string = - "%YAML 1.1\n" - "---\n" - "\n" - "vars:\n" - "\n" - " address-groups:\n" - "\n" - " HOME_NET: \"any\"\n" - "\n" - " EXTERNAL_NET: \"!$HOME_NET\"\n" - "\n" - " port-groups:\n" - "\n" - " HTTP_PORTS: \"any\"\n" - "\n" - " SHELLCODE_PORTS: \"!$HTTP_PORTS\"\n" - "\n"; + static const char *dummy_conf_string = "%YAML 1.1\n" + "---\n" + "\n" + "vars:\n" + "\n" + " address-groups:\n" + "\n" + " HOME_NET: \"any\"\n" + "\n" + " EXTERNAL_NET: \"!$HOME_NET\"\n" + "\n" + " port-groups:\n" + "\n" + " HTTP_PORTS: \"any\"\n" + "\n" + " SHELLCODE_PORTS: \"!$HTTP_PORTS\"\n" + "\n"; int result = 0; @@ -4768,24 +4807,23 @@ static int AddressConfVarsTest03(void) static int AddressConfVarsTest04(void) { - static const char *dummy_conf_string = - "%YAML 1.1\n" - "---\n" - "\n" - "vars:\n" - "\n" - " address-groups:\n" - "\n" - " HOME_NET: \"any\"\n" - "\n" - " EXTERNAL_NET: \"$HOME_NET\"\n" - "\n" - " port-groups:\n" - "\n" - " HTTP_PORTS: \"any\"\n" - "\n" - " SHELLCODE_PORTS: \"$HTTP_PORTS\"\n" - "\n"; + static const char *dummy_conf_string = "%YAML 1.1\n" + "---\n" + "\n" + "vars:\n" + "\n" + " address-groups:\n" + "\n" + " HOME_NET: \"any\"\n" + "\n" + " EXTERNAL_NET: \"$HOME_NET\"\n" + "\n" + " port-groups:\n" + "\n" + " HTTP_PORTS: \"any\"\n" + "\n" + " SHELLCODE_PORTS: \"$HTTP_PORTS\"\n" + "\n"; int result = 0; @@ -4804,24 +4842,23 @@ static int AddressConfVarsTest04(void) static int AddressConfVarsTest05(void) { - static const char *dummy_conf_string = - "%YAML 1.1\n" - "---\n" - "\n" - "vars:\n" - "\n" - " address-groups:\n" - "\n" - " HOME_NET: \"any\"\n" - "\n" - " EXTERNAL_NET: [192.168.0.1]\n" - "\n" - " port-groups:\n" - "\n" - " HTTP_PORTS: \"any\"\n" - "\n" - " SHELLCODE_PORTS: [80]\n" - "\n"; + static const char *dummy_conf_string = "%YAML 1.1\n" + "---\n" + "\n" + "vars:\n" + "\n" + " address-groups:\n" + "\n" + " HOME_NET: \"any\"\n" + "\n" + " EXTERNAL_NET: [192.168.0.1]\n" + "\n" + " port-groups:\n" + "\n" + " HTTP_PORTS: \"any\"\n" + "\n" + " SHELLCODE_PORTS: [80]\n" + "\n"; int result = 0; @@ -4834,7 +4871,7 @@ static int AddressConfVarsTest05(void) result = 1; - end: +end: ConfDeInit(); ConfRestoreContextBackup(); @@ -5079,110 +5116,59 @@ void DetectAddressTests(void) UtRegisterTest("AddressTestCmp11", AddressTestCmp11); UtRegisterTest("AddressTestCmp12", AddressTestCmp12); - UtRegisterTest("AddressTestAddressGroupSetup01", - AddressTestAddressGroupSetup01); - UtRegisterTest("AddressTestAddressGroupSetup02", - AddressTestAddressGroupSetup02); - UtRegisterTest("AddressTestAddressGroupSetup03", - AddressTestAddressGroupSetup03); - UtRegisterTest("AddressTestAddressGroupSetup04", - AddressTestAddressGroupSetup04); - UtRegisterTest("AddressTestAddressGroupSetup05", - AddressTestAddressGroupSetup05); - UtRegisterTest("AddressTestAddressGroupSetup06", - AddressTestAddressGroupSetup06); - UtRegisterTest("AddressTestAddressGroupSetup07", - AddressTestAddressGroupSetup07); - UtRegisterTest("AddressTestAddressGroupSetup08", - AddressTestAddressGroupSetup08); - UtRegisterTest("AddressTestAddressGroupSetup09", - AddressTestAddressGroupSetup09); - UtRegisterTest("AddressTestAddressGroupSetup10", - AddressTestAddressGroupSetup10); - UtRegisterTest("AddressTestAddressGroupSetup11", - AddressTestAddressGroupSetup11); - UtRegisterTest("AddressTestAddressGroupSetup12", - AddressTestAddressGroupSetup12); - UtRegisterTest("AddressTestAddressGroupSetup13", - AddressTestAddressGroupSetup13); - UtRegisterTest("AddressTestAddressGroupSetupIPv414", - AddressTestAddressGroupSetupIPv414); - UtRegisterTest("AddressTestAddressGroupSetupIPv415", - AddressTestAddressGroupSetupIPv415); - UtRegisterTest("AddressTestAddressGroupSetupIPv416", - AddressTestAddressGroupSetupIPv416); - - UtRegisterTest("AddressTestAddressGroupSetup14", - AddressTestAddressGroupSetup14); - UtRegisterTest("AddressTestAddressGroupSetup15", - AddressTestAddressGroupSetup15); - UtRegisterTest("AddressTestAddressGroupSetup16", - AddressTestAddressGroupSetup16); - UtRegisterTest("AddressTestAddressGroupSetup17", - AddressTestAddressGroupSetup17); - UtRegisterTest("AddressTestAddressGroupSetup18", - AddressTestAddressGroupSetup18); - UtRegisterTest("AddressTestAddressGroupSetup19", - AddressTestAddressGroupSetup19); - UtRegisterTest("AddressTestAddressGroupSetup20", - AddressTestAddressGroupSetup20); - UtRegisterTest("AddressTestAddressGroupSetup21", - AddressTestAddressGroupSetup21); - UtRegisterTest("AddressTestAddressGroupSetup22", - AddressTestAddressGroupSetup22); - UtRegisterTest("AddressTestAddressGroupSetup23", - AddressTestAddressGroupSetup23); - UtRegisterTest("AddressTestAddressGroupSetup24", - AddressTestAddressGroupSetup24); - UtRegisterTest("AddressTestAddressGroupSetup25", - AddressTestAddressGroupSetup25); - UtRegisterTest("AddressTestAddressGroupSetup26", - AddressTestAddressGroupSetup26); - - UtRegisterTest("AddressTestAddressGroupSetup27", - AddressTestAddressGroupSetup27); - UtRegisterTest("AddressTestAddressGroupSetup28", - AddressTestAddressGroupSetup28); - UtRegisterTest("AddressTestAddressGroupSetup29", - AddressTestAddressGroupSetup29); - UtRegisterTest("AddressTestAddressGroupSetup30", - AddressTestAddressGroupSetup30); - UtRegisterTest("AddressTestAddressGroupSetup31", - AddressTestAddressGroupSetup31); - UtRegisterTest("AddressTestAddressGroupSetup32", - AddressTestAddressGroupSetup32); - UtRegisterTest("AddressTestAddressGroupSetup33", - AddressTestAddressGroupSetup33); - UtRegisterTest("AddressTestAddressGroupSetup34", - AddressTestAddressGroupSetup34); - UtRegisterTest("AddressTestAddressGroupSetup35", - AddressTestAddressGroupSetup35); - UtRegisterTest("AddressTestAddressGroupSetup36", - AddressTestAddressGroupSetup36); - UtRegisterTest("AddressTestAddressGroupSetup37", - AddressTestAddressGroupSetup37); - UtRegisterTest("AddressTestAddressGroupSetup38", - AddressTestAddressGroupSetup38); - UtRegisterTest("AddressTestAddressGroupSetup39", - AddressTestAddressGroupSetup39); - UtRegisterTest("AddressTestAddressGroupSetup40", - AddressTestAddressGroupSetup40); - UtRegisterTest("AddressTestAddressGroupSetup41", - AddressTestAddressGroupSetup41); - UtRegisterTest("AddressTestAddressGroupSetup42", - AddressTestAddressGroupSetup42); - UtRegisterTest("AddressTestAddressGroupSetup43", - AddressTestAddressGroupSetup43); - UtRegisterTest("AddressTestAddressGroupSetup44", - AddressTestAddressGroupSetup44); - UtRegisterTest("AddressTestAddressGroupSetup45", - AddressTestAddressGroupSetup45); - UtRegisterTest("AddressTestAddressGroupSetup46", - AddressTestAddressGroupSetup46); - UtRegisterTest("AddressTestAddressGroupSetup47", - AddressTestAddressGroupSetup47); - UtRegisterTest("AddressTestAddressGroupSetup48", - AddressTestAddressGroupSetup48); + UtRegisterTest("AddressTestAddressGroupSetup01", AddressTestAddressGroupSetup01); + UtRegisterTest("AddressTestAddressGroupSetup02", AddressTestAddressGroupSetup02); + UtRegisterTest("AddressTestAddressGroupSetup03", AddressTestAddressGroupSetup03); + UtRegisterTest("AddressTestAddressGroupSetup04", AddressTestAddressGroupSetup04); + UtRegisterTest("AddressTestAddressGroupSetup05", AddressTestAddressGroupSetup05); + UtRegisterTest("AddressTestAddressGroupSetup06", AddressTestAddressGroupSetup06); + UtRegisterTest("AddressTestAddressGroupSetup07", AddressTestAddressGroupSetup07); + UtRegisterTest("AddressTestAddressGroupSetup08", AddressTestAddressGroupSetup08); + UtRegisterTest("AddressTestAddressGroupSetup09", AddressTestAddressGroupSetup09); + UtRegisterTest("AddressTestAddressGroupSetup10", AddressTestAddressGroupSetup10); + UtRegisterTest("AddressTestAddressGroupSetup11", AddressTestAddressGroupSetup11); + UtRegisterTest("AddressTestAddressGroupSetup12", AddressTestAddressGroupSetup12); + UtRegisterTest("AddressTestAddressGroupSetup13", AddressTestAddressGroupSetup13); + UtRegisterTest("AddressTestAddressGroupSetupIPv414", AddressTestAddressGroupSetupIPv414); + UtRegisterTest("AddressTestAddressGroupSetupIPv415", AddressTestAddressGroupSetupIPv415); + UtRegisterTest("AddressTestAddressGroupSetupIPv416", AddressTestAddressGroupSetupIPv416); + + UtRegisterTest("AddressTestAddressGroupSetup14", AddressTestAddressGroupSetup14); + UtRegisterTest("AddressTestAddressGroupSetup15", AddressTestAddressGroupSetup15); + UtRegisterTest("AddressTestAddressGroupSetup16", AddressTestAddressGroupSetup16); + UtRegisterTest("AddressTestAddressGroupSetup17", AddressTestAddressGroupSetup17); + UtRegisterTest("AddressTestAddressGroupSetup18", AddressTestAddressGroupSetup18); + UtRegisterTest("AddressTestAddressGroupSetup19", AddressTestAddressGroupSetup19); + UtRegisterTest("AddressTestAddressGroupSetup20", AddressTestAddressGroupSetup20); + UtRegisterTest("AddressTestAddressGroupSetup21", AddressTestAddressGroupSetup21); + UtRegisterTest("AddressTestAddressGroupSetup22", AddressTestAddressGroupSetup22); + UtRegisterTest("AddressTestAddressGroupSetup23", AddressTestAddressGroupSetup23); + UtRegisterTest("AddressTestAddressGroupSetup24", AddressTestAddressGroupSetup24); + UtRegisterTest("AddressTestAddressGroupSetup25", AddressTestAddressGroupSetup25); + UtRegisterTest("AddressTestAddressGroupSetup26", AddressTestAddressGroupSetup26); + + UtRegisterTest("AddressTestAddressGroupSetup27", AddressTestAddressGroupSetup27); + UtRegisterTest("AddressTestAddressGroupSetup28", AddressTestAddressGroupSetup28); + UtRegisterTest("AddressTestAddressGroupSetup29", AddressTestAddressGroupSetup29); + UtRegisterTest("AddressTestAddressGroupSetup30", AddressTestAddressGroupSetup30); + UtRegisterTest("AddressTestAddressGroupSetup31", AddressTestAddressGroupSetup31); + UtRegisterTest("AddressTestAddressGroupSetup32", AddressTestAddressGroupSetup32); + UtRegisterTest("AddressTestAddressGroupSetup33", AddressTestAddressGroupSetup33); + UtRegisterTest("AddressTestAddressGroupSetup34", AddressTestAddressGroupSetup34); + UtRegisterTest("AddressTestAddressGroupSetup35", AddressTestAddressGroupSetup35); + UtRegisterTest("AddressTestAddressGroupSetup36", AddressTestAddressGroupSetup36); + UtRegisterTest("AddressTestAddressGroupSetup37", AddressTestAddressGroupSetup37); + UtRegisterTest("AddressTestAddressGroupSetup38", AddressTestAddressGroupSetup38); + UtRegisterTest("AddressTestAddressGroupSetup39", AddressTestAddressGroupSetup39); + UtRegisterTest("AddressTestAddressGroupSetup40", AddressTestAddressGroupSetup40); + UtRegisterTest("AddressTestAddressGroupSetup41", AddressTestAddressGroupSetup41); + UtRegisterTest("AddressTestAddressGroupSetup42", AddressTestAddressGroupSetup42); + UtRegisterTest("AddressTestAddressGroupSetup43", AddressTestAddressGroupSetup43); + UtRegisterTest("AddressTestAddressGroupSetup44", AddressTestAddressGroupSetup44); + UtRegisterTest("AddressTestAddressGroupSetup45", AddressTestAddressGroupSetup45); + UtRegisterTest("AddressTestAddressGroupSetup46", AddressTestAddressGroupSetup46); + UtRegisterTest("AddressTestAddressGroupSetup47", AddressTestAddressGroupSetup47); + UtRegisterTest("AddressTestAddressGroupSetup48", AddressTestAddressGroupSetup48); UtRegisterTest("AddressTestCutIPv401", AddressTestCutIPv401); UtRegisterTest("AddressTestCutIPv402", AddressTestCutIPv402); @@ -5195,12 +5181,9 @@ void DetectAddressTests(void) UtRegisterTest("AddressTestCutIPv409", AddressTestCutIPv409); UtRegisterTest("AddressTestCutIPv410", AddressTestCutIPv410); - UtRegisterTest("AddressTestParseInvalidMask01", - AddressTestParseInvalidMask01); - UtRegisterTest("AddressTestParseInvalidMask02", - AddressTestParseInvalidMask02); - UtRegisterTest("AddressTestParseInvalidMask03", - AddressTestParseInvalidMask03); + UtRegisterTest("AddressTestParseInvalidMask01", AddressTestParseInvalidMask01); + UtRegisterTest("AddressTestParseInvalidMask02", AddressTestParseInvalidMask02); + UtRegisterTest("AddressTestParseInvalidMask03", AddressTestParseInvalidMask03); UtRegisterTest("AddressConfVarsTest01 ", AddressConfVarsTest01); UtRegisterTest("AddressConfVarsTest02 ", AddressConfVarsTest02); diff --git a/src/detect-engine-address.h b/src/detect-engine-address.h index 3c8221e630b4..930059217a16 100644 --- a/src/detect-engine-address.h +++ b/src/detect-engine-address.h @@ -24,8 +24,6 @@ #ifndef __DETECT_ADDRESS_H__ #define __DETECT_ADDRESS_H__ - - DetectAddress *DetectAddressInit(void); void DetectAddressFree(DetectAddress *); DetectAddress *DetectAddressCopy(DetectAddress *); @@ -47,8 +45,8 @@ void DetectAddressTests(void); int DetectAddressMapInit(DetectEngineCtx *de_ctx); void DetectAddressMapFree(DetectEngineCtx *de_ctx); -const DetectAddressHead *DetectParseAddress(DetectEngineCtx *de_ctx, - const char *string, bool *contains_negation); +const DetectAddressHead *DetectParseAddress( + DetectEngineCtx *de_ctx, const char *string, bool *contains_negation); #ifdef DEBUG void DetectAddressPrintList(DetectAddress *); diff --git a/src/detect-engine-alert.c b/src/detect-engine-alert.c index f9cbed1564c5..367566c0525a 100644 --- a/src/detect-engine-alert.c +++ b/src/detect-engine-alert.c @@ -70,7 +70,7 @@ void PacketAlertTagInit(void) * \retval 0 alert is suppressed */ static int PacketAlertHandle(DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx, - const Signature *s, Packet *p, PacketAlert *pa) + const Signature *s, Packet *p, PacketAlert *pa) { SCEnter(); int ret = 1; @@ -118,7 +118,7 @@ static int PacketAlertHandle(DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det KEYWORD_PROFILING_START; ret = PacketAlertThreshold(de_ctx, det_ctx, td, p, s, pa); if (ret == 0 || ret == 2) { - KEYWORD_PROFILING_END(det_ctx, DETECT_THRESHOLD ,0); + KEYWORD_PROFILING_END(det_ctx, DETECT_THRESHOLD, 0); /* It doesn't match threshold, remove it */ SCReturnInt(ret); } diff --git a/src/detect-engine-analyzer.c b/src/detect-engine-analyzer.c index a37afabb0f00..d1ebbbda30c1 100644 --- a/src/detect-engine-analyzer.c +++ b/src/detect-engine-analyzer.c @@ -50,12 +50,12 @@ static int rule_warnings_only = 0; /* Details for each buffer being tracked */ typedef struct DetectEngineAnalyzerItems { - int16_t item_id; - bool item_seen; - bool export_item_seen; - bool check_encoding_match; - const char *item_name; - const char *display_name; + int16_t item_id; + bool item_seen; + bool export_item_seen; + bool check_encoding_match; + const char *item_name; + const char *display_name; } DetectEngineAnalyzerItems; typedef struct FpPatternStats_ { @@ -67,8 +67,8 @@ typedef struct FpPatternStats_ { /* Track which items require the item_seen value to be exposed */ struct ExposedItemSeen { - const char *bufname; - bool *item_seen_ptr; + const char *bufname; + bool *item_seen_ptr; }; typedef struct EngineAnalysisCtx_ { @@ -213,7 +213,8 @@ void EngineAnalysisFP(const DetectEngineCtx *de_ctx, const Signature *s, char *l if (fp_cd->flags & DETECT_CONTENT_OFFSET) { fprintf(fp, " Offset"); flags_set = 1; - } if (fp_cd->flags & DETECT_CONTENT_DEPTH) { + } + if (fp_cd->flags & DETECT_CONTENT_DEPTH) { fprintf(fp, " Depth"); flags_set = 1; } @@ -293,8 +294,7 @@ static int SetupFPAnalyzer(DetectEngineCtx *de_ctx) { int fp_engine_analysis_set = 0; - if ((ConfGetBool("engine-analysis.rules-fast-pattern", - &fp_engine_analysis_set)) == 0) { + if ((ConfGetBool("engine-analysis.rules-fast-pattern", &fp_engine_analysis_set)) == 0) { return false; } @@ -318,8 +318,7 @@ static int SetupFPAnalyzer(DetectEngineCtx *de_ctx) de_ctx->ea->fp_engine_analysis_fp = fp; - SCLogInfo("Engine-Analysis for fast_pattern printed to file - %s", - log_path); + SCLogInfo("Engine-Analysis for fast_pattern printed to file - %s", log_path); SCFree(log_path); struct timeval tval; @@ -393,8 +392,7 @@ static int SetupRuleAnalyzer(DetectEngineCtx *de_ctx) return 0; } - SCLogInfo("Engine-Analysis for rules printed to file - %s", - log_path); + SCLogInfo("Engine-Analysis for rules printed to file - %s", log_path); struct timeval tval; gettimeofday(&tval, NULL); @@ -419,10 +417,9 @@ static int SetupRuleAnalyzer(DetectEngineCtx *de_ctx) "http content.\n"); } } - } - else { + } else { SCLogInfo("Conf parameter \"engine-analysis.rules\" not found. " - "Defaulting to not printing the rules analysis report."); + "Defaulting to not printing the rules analysis report."); } if (!enabled) { SCLogInfo("Engine-Analysis for rules disabled in conf file."); @@ -594,8 +591,7 @@ static void EngineAnalysisRulesPrintFP(const DetectEngineCtx *de_ctx, const Sign fprintf(ea_ctx->rule_engine_analysis_fp, "%s", payload ? (stream ? "payload and reassembled stream" : "payload") : "reassembled stream"); - } - else { + } else { const char *desc = DetectEngineBufferTypeGetDescriptionById(de_ctx, list_type); const char *name = DetectEngineBufferTypeGetNameById(de_ctx, list_type); if (desc && name) { @@ -603,7 +599,6 @@ static void EngineAnalysisRulesPrintFP(const DetectEngineCtx *de_ctx, const Sign } else if (desc || name) { fprintf(ea_ctx->rule_engine_analysis_fp, "%s", desc ? desc : name); } - } fprintf(ea_ctx->rule_engine_analysis_fp, "\" "); @@ -663,7 +658,9 @@ static void ATTR_FMT_PRINTF(2, 3) AnalyzerWarning(RuleAnalyzer *ctx, char *fmt, jb_append_string(ctx->js_warnings, str); } -#define CHECK(pat) if (strlen((pat)) <= len && memcmp((pat), buf, MIN(len, strlen((pat)))) == 0) return true; +#define CHECK(pat) \ + if (strlen((pat)) <= len && memcmp((pat), buf, MIN(len, strlen((pat)))) == 0) \ + return true; static bool LooksLikeHTTPMethod(const uint8_t *buf, uint16_t len) { @@ -1019,7 +1016,7 @@ void EngineAnalysisRules2(const DetectEngineCtx *de_ctx, const Signature *s) jb_open_array(ctx.js, "pkt_engines"); const DetectEnginePktInspectionEngine *pkt = s->pkt_inspect; - for ( ; pkt != NULL; pkt = pkt->next) { + for (; pkt != NULL; pkt = pkt->next) { const char *name = DetectEngineBufferTypeGetNameById(de_ctx, pkt->sm_list); if (name == NULL) { switch (pkt->sm_list) { @@ -1083,7 +1080,7 @@ void EngineAnalysisRules2(const DetectEngineCtx *de_ctx, const Signature *s) jb_open_array(ctx.js, "engines"); const DetectEngineAppInspectionEngine *app = s->app_inspect; - for ( ; app != NULL; app = app->next) { + for (; app != NULL; app = app->next) { const char *name = DetectEngineBufferTypeGetNameById(de_ctx, app->sm_list); if (name == NULL) { switch (app->sm_list) { @@ -1131,9 +1128,11 @@ void EngineAnalysisRules2(const DetectEngineCtx *de_ctx, const Signature *s) jb_close(ctx.js); if (has_stream && has_client_body_mpm) - AnalyzerNote(&ctx, (char *)"mpm in http_client_body combined with stream match leads to stream buffering"); + AnalyzerNote(&ctx, (char *)"mpm in http_client_body combined with stream match leads " + "to stream buffering"); if (has_stream && has_file_data_mpm) - AnalyzerNote(&ctx, (char *)"mpm in file_data combined with stream match leads to stream buffering"); + AnalyzerNote(&ctx, (char *)"mpm in file_data combined with stream match leads to " + "stream buffering"); } jb_open_object(ctx.js, "lists"); @@ -1364,8 +1363,7 @@ static void EngineAnalysisItemsInit(EngineAnalysisCtx *ea_ctx) * * \param s Pointer to the signature. */ -void EngineAnalysisRules(const DetectEngineCtx *de_ctx, - const Signature *s, const char *line) +void EngineAnalysisRules(const DetectEngineCtx *de_ctx, const Signature *s, const char *line) { uint32_t rule_bidirectional = 0; uint32_t rule_pcre = 0; @@ -1466,13 +1464,11 @@ void EngineAnalysisRules(const DetectEngineCtx *de_ctx, warn_encoding_norm_http_buf += 1; } } - } - else if (sm->type == DETECT_FLOW) { + } else if (sm->type == DETECT_FLOW) { rule_flow += 1; if ((s->flags & SIG_FLAG_TOSERVER) && !(s->flags & SIG_FLAG_TOCLIENT)) { rule_flow_toserver = 1; - } - else if ((s->flags & SIG_FLAG_TOCLIENT) && !(s->flags & SIG_FLAG_TOSERVER)) { + } else if ((s->flags & SIG_FLAG_TOCLIENT) && !(s->flags & SIG_FLAG_TOSERVER)) { rule_flow_toclient = 1; } DetectFlowData *fd = (DetectFlowData *)sm->ctx; @@ -1480,18 +1476,15 @@ void EngineAnalysisRules(const DetectEngineCtx *de_ctx, if (fd->flags & DETECT_FLOW_FLAG_NOSTREAM) rule_flow_nostream = 1; } - } - else if (sm->type == DETECT_FLOWBITS) { + } else if (sm->type == DETECT_FLOWBITS) { if (list_id == DETECT_SM_LIST_MATCH) { rule_flowbits += 1; } - } - else if (sm->type == DETECT_FLOWINT) { + } else if (sm->type == DETECT_FLOWINT) { if (list_id == DETECT_SM_LIST_MATCH) { rule_flowint += 1; } - } - else if (sm->type == DETECT_FLAGS) { + } else if (sm->type == DETECT_FLAGS) { DetectFlagsData *fd = (DetectFlagsData *)sm->ctx; if (fd != NULL) { rule_flags = 1; @@ -1528,7 +1521,7 @@ void EngineAnalysisRules(const DetectEngineCtx *de_ctx, warn_content_http = 1; } if (rule_content == 1) { - //todo: warning if content is weak, separate warning for pcre + weak content + // todo: warning if content is weak, separate warning for pcre + weak content } if (rule_flow == 0 && rule_flags == 0 && !(s->proto.flags & DETECT_PROTO_ANY) && DetectProtoContainsProto(&s->proto, IPPROTO_TCP) && @@ -1537,10 +1530,12 @@ void EngineAnalysisRules(const DetectEngineCtx *de_ctx, rule_warning += 1; warn_tcp_no_flow = 1; } - if (rule_flow && !rule_bidirectional && (rule_flow_toserver || rule_flow_toclient) - && !((s->flags & SIG_FLAG_SP_ANY) && (s->flags & SIG_FLAG_DP_ANY))) { - if (((s->flags & SIG_FLAG_TOSERVER) && !(s->flags & SIG_FLAG_SP_ANY) && (s->flags & SIG_FLAG_DP_ANY)) - || ((s->flags & SIG_FLAG_TOCLIENT) && !(s->flags & SIG_FLAG_DP_ANY) && (s->flags & SIG_FLAG_SP_ANY))) { + if (rule_flow && !rule_bidirectional && (rule_flow_toserver || rule_flow_toclient) && + !((s->flags & SIG_FLAG_SP_ANY) && (s->flags & SIG_FLAG_DP_ANY))) { + if (((s->flags & SIG_FLAG_TOSERVER) && !(s->flags & SIG_FLAG_SP_ANY) && + (s->flags & SIG_FLAG_DP_ANY)) || + ((s->flags & SIG_FLAG_TOCLIENT) && !(s->flags & SIG_FLAG_DP_ANY) && + (s->flags & SIG_FLAG_SP_ANY))) { rule_warning += 1; warn_client_ports = 1; } @@ -1568,7 +1563,8 @@ void EngineAnalysisRules(const DetectEngineCtx *de_ctx, rule_warning += 1; warn_offset_depth_pkt_stream = 1; } - if (rule_content_offset_depth > 0 && !stream_buf && packet_buf && s->alproto != ALPROTO_UNKNOWN) { + if (rule_content_offset_depth > 0 && !stream_buf && packet_buf && + s->alproto != ALPROTO_UNKNOWN) { rule_warning += 1; warn_offset_depth_alproto = 1; } @@ -1578,14 +1574,16 @@ void EngineAnalysisRules(const DetectEngineCtx *de_ctx, warn_non_alproto_fp_for_alproto_sig = 1; } - if ((s->flags & (SIG_FLAG_TOSERVER|SIG_FLAG_TOCLIENT)) == 0) { + if ((s->flags & (SIG_FLAG_TOSERVER | SIG_FLAG_TOCLIENT)) == 0) { warn_no_direction += 1; rule_warning += 1; } /* No warning about direction for ICMP protos */ - if (!(DetectProtoContainsProto(&s->proto, IPPROTO_ICMPV6) && DetectProtoContainsProto(&s->proto, IPPROTO_ICMP))) { - if ((s->flags & (SIG_FLAG_TOSERVER|SIG_FLAG_TOCLIENT)) == (SIG_FLAG_TOSERVER|SIG_FLAG_TOCLIENT)) { + if (!(DetectProtoContainsProto(&s->proto, IPPROTO_ICMPV6) && + DetectProtoContainsProto(&s->proto, IPPROTO_ICMP))) { + if ((s->flags & (SIG_FLAG_TOSERVER | SIG_FLAG_TOCLIENT)) == + (SIG_FLAG_TOSERVER | SIG_FLAG_TOCLIENT)) { warn_both_direction += 1; rule_warning += 1; } @@ -1639,7 +1637,7 @@ void EngineAnalysisRules(const DetectEngineCtx *de_ctx, (rule_flow || rule_flowbits || rule_flowint || rule_content || rule_pcre)) { fprintf(fp, " Rule matches on reassembled stream.\n"); } - for(size_t i = 0; i < ARRAY_SIZE(analyzer_items); i++) { + for (size_t i = 0; i < ARRAY_SIZE(analyzer_items); i++) { DetectEngineAnalyzerItems *ai = &de_ctx->ea->analyzer_items[i]; if (ai->item_seen) { fprintf(fp, " Rule matches on %s buffer.\n", ai->display_name); @@ -1690,7 +1688,7 @@ void EngineAnalysisRules(const DetectEngineCtx *de_ctx, " -Consider adding http content modifiers.\n"); } if (rule_content == 1) { - //todo: warning if content is weak, separate warning for pcre + weak content + // todo: warning if content is weak, separate warning for pcre + weak content } if (warn_encoding_norm_http_buf) { fprintf(fp, " Warning: Rule may contain percent encoded content for a normalized " diff --git a/src/detect-engine-build.c b/src/detect-engine-build.c index 8c01104c48de..2c5e32282ed5 100644 --- a/src/detect-engine-build.c +++ b/src/detect-engine-build.c @@ -210,9 +210,9 @@ int SignatureIsIPOnly(DetectEngineCtx *de_ctx, const Signature *s) return 0; /* if flow dir is set we can't process it in ip-only */ - if (!(((s->flags & (SIG_FLAG_TOSERVER|SIG_FLAG_TOCLIENT)) == 0) || - (s->flags & (SIG_FLAG_TOSERVER|SIG_FLAG_TOCLIENT)) == - (SIG_FLAG_TOSERVER|SIG_FLAG_TOCLIENT))) + if (!(((s->flags & (SIG_FLAG_TOSERVER | SIG_FLAG_TOCLIENT)) == 0) || + (s->flags & (SIG_FLAG_TOSERVER | SIG_FLAG_TOCLIENT)) == + (SIG_FLAG_TOSERVER | SIG_FLAG_TOCLIENT))) return 0; /* for now assume that all registered buffer types are incompatible */ @@ -235,13 +235,13 @@ int SignatureIsIPOnly(DetectEngineCtx *de_ctx, const Signature *s) } } sm = s->init_data->smlists[DETECT_SM_LIST_POSTMATCH]; - for ( ; sm != NULL; sm = sm->next) { - if ( !(sigmatch_table[sm->type].flags & SIGMATCH_IPONLY_COMPAT)) + for (; sm != NULL; sm = sm->next) { + if (!(sigmatch_table[sm->type].flags & SIGMATCH_IPONLY_COMPAT)) return 0; /* we have enabled flowbits to be compatible with ip only sigs, as long * as the sig only has a "set" flowbits */ if (sm->type == DETECT_FLOWBITS && - (((DetectFlowbitsData *)sm->ctx)->cmd != DETECT_FLOWBITS_CMD_SET) ) { + (((DetectFlowbitsData *)sm->ctx)->cmd != DETECT_FLOWBITS_CMD_SET)) { return 0; } } @@ -252,8 +252,8 @@ int SignatureIsIPOnly(DetectEngineCtx *de_ctx, const Signature *s) } if (!(de_ctx->flags & DE_QUIET)) { SCLogDebug("IP-ONLY (%" PRIu32 "): source %s, dest %s", s->id, - s->flags & SIG_FLAG_SRC_ANY ? "ANY" : "SET", - s->flags & SIG_FLAG_DST_ANY ? "ANY" : "SET"); + s->flags & SIG_FLAG_SRC_ANY ? "ANY" : "SET", + s->flags & SIG_FLAG_DST_ANY ? "ANY" : "SET"); } return 1; } @@ -289,24 +289,27 @@ static int SignatureIsPDOnly(const DetectEngineCtx *de_ctx, const Signature *s) return 0; int pd = 0; - for ( ; sm != NULL; sm = sm->next) { + for (; sm != NULL; sm = sm->next) { if (sm->type == DETECT_AL_APP_LAYER_PROTOCOL) { pd = 1; } else { /* flowbits are supported for dp only sigs, as long * as the sig only has a "set" flowbits */ if (sm->type == DETECT_FLOWBITS) { - if ((((DetectFlowbitsData *)sm->ctx)->cmd != DETECT_FLOWBITS_CMD_SET) ) { + if ((((DetectFlowbitsData *)sm->ctx)->cmd != DETECT_FLOWBITS_CMD_SET)) { SCLogDebug("%u: not PD-only: flowbit settings other than 'set'", s->id); return 0; } } else if (sm->type == DETECT_FLOW) { - if (((DetectFlowData *)sm->ctx)->flags & ~(DETECT_FLOW_FLAG_TOSERVER|DETECT_FLOW_FLAG_TOCLIENT)) { - SCLogDebug("%u: not PD-only: flow settings other than toserver/toclient", s->id); + if (((DetectFlowData *)sm->ctx)->flags & + ~(DETECT_FLOW_FLAG_TOSERVER | DETECT_FLOW_FLAG_TOCLIENT)) { + SCLogDebug( + "%u: not PD-only: flow settings other than toserver/toclient", s->id); return 0; } - } else if ( !(sigmatch_table[sm->type].flags & SIGMATCH_IPONLY_COMPAT)) { - SCLogDebug("%u: not PD-only: %s not PD/IP-only compat", s->id, sigmatch_table[sm->type].name); + } else if (!(sigmatch_table[sm->type].flags & SIGMATCH_IPONLY_COMPAT)) { + SCLogDebug("%u: not PD-only: %s not PD/IP-only compat", s->id, + sigmatch_table[sm->type].name); return 0; } } @@ -349,8 +352,7 @@ static int SignatureIsDEOnly(DetectEngineCtx *de_ctx, const Signature *s) SCReturnInt(0); } - if (s->init_data->smlists[DETECT_SM_LIST_PMATCH] != NULL) - { + if (s->init_data->smlists[DETECT_SM_LIST_PMATCH] != NULL) { SCReturnInt(0); } @@ -361,14 +363,14 @@ static int SignatureIsDEOnly(DetectEngineCtx *de_ctx, const Signature *s) /* check for conflicting keywords */ SigMatch *sm = s->init_data->smlists[DETECT_SM_LIST_MATCH]; - for ( ;sm != NULL; sm = sm->next) { - if ( !(sigmatch_table[sm->type].flags & SIGMATCH_DEONLY_COMPAT)) + for (; sm != NULL; sm = sm->next) { + if (!(sigmatch_table[sm->type].flags & SIGMATCH_DEONLY_COMPAT)) SCReturnInt(0); } /* need at least one decode event keyword to be considered decode event. */ sm = s->init_data->smlists[DETECT_SM_LIST_MATCH]; - for ( ;sm != NULL; sm = sm->next) { + for (; sm != NULL; sm = sm->next) { if (sm->type == DETECT_DECODE_EVENT) goto deonly; if (sm->type == DETECT_ENGINE_EVENT) @@ -382,21 +384,19 @@ static int SignatureIsDEOnly(DetectEngineCtx *de_ctx, const Signature *s) deonly: if (!(de_ctx->flags & DE_QUIET)) { SCLogDebug("DE-ONLY (%" PRIu32 "): source %s, dest %s", s->id, - s->flags & SIG_FLAG_SRC_ANY ? "ANY" : "SET", - s->flags & SIG_FLAG_DST_ANY ? "ANY" : "SET"); + s->flags & SIG_FLAG_SRC_ANY ? "ANY" : "SET", + s->flags & SIG_FLAG_DST_ANY ? "ANY" : "SET"); } SCReturnInt(1); } -#define MASK_TCP_INITDEINIT_FLAGS (TH_SYN|TH_RST|TH_FIN) -#define MASK_TCP_UNUSUAL_FLAGS (TH_URG|TH_ECN|TH_CWR) +#define MASK_TCP_INITDEINIT_FLAGS (TH_SYN | TH_RST | TH_FIN) +#define MASK_TCP_UNUSUAL_FLAGS (TH_URG | TH_ECN | TH_CWR) /* Create mask for this packet + it's flow if it has one */ -void -PacketCreateMask(Packet *p, SignatureMask *mask, AppProto alproto, - bool app_decoder_events) +void PacketCreateMask(Packet *p, SignatureMask *mask, AppProto alproto, bool app_decoder_events) { if (!(p->flags & PKT_NOPAYLOAD_INSPECTION) && p->payload_len > 0) { SCLogDebug("packet has payload"); @@ -471,10 +471,9 @@ static int SignatureCreateMask(Signature *s) } SigMatch *sm; - for (sm = s->init_data->smlists[DETECT_SM_LIST_MATCH] ; sm != NULL; sm = sm->next) { - switch(sm->type) { - case DETECT_FLOWBITS: - { + for (sm = s->init_data->smlists[DETECT_SM_LIST_MATCH]; sm != NULL; sm = sm->next) { + switch (sm->type) { + case DETECT_FLOWBITS: { /* figure out what flowbit action */ DetectFlowbitsData *fb = (DetectFlowbitsData *)sm->ctx; if (fb->cmd == DETECT_FLOWBITS_CMD_ISSET) { @@ -482,23 +481,22 @@ static int SignatureCreateMask(Signature *s) s->flags |= SIG_FLAG_REQUIRE_FLOWVAR; SCLogDebug("SIG_FLAG_REQUIRE_FLOWVAR set as sig has " - "flowbit isset option."); + "flowbit isset option."); } /* flow is required for any flowbit manipulation */ s->mask |= SIG_MASK_REQUIRE_FLOW; SCLogDebug("sig requires flow to be able to manipulate " - "flowbit(s)"); + "flowbit(s)"); break; } case DETECT_FLOWINT: /* flow is required for any flowint manipulation */ s->mask |= SIG_MASK_REQUIRE_FLOW; SCLogDebug("sig requires flow to be able to manipulate " - "flowint(s)"); + "flowint(s)"); break; - case DETECT_FLAGS: - { + case DETECT_FLAGS: { DetectFlagsData *fl = (DetectFlagsData *)sm->ctx; if (fl->flags & TH_SYN) { @@ -527,8 +525,7 @@ static int SignatureCreateMask(Signature *s) } break; } - case DETECT_DSIZE: - { + case DETECT_DSIZE: { DetectU16Data *ds = (DetectU16Data *)sm->ctx; /* LT will include 0, so no payload. * if GT is used in the same rule the @@ -650,7 +647,7 @@ static json_t *RulesGroupPrintSghStats(const DetectEngineCtx *de_ctx, const SigG } mpm_stats[max_buffer_type_id]; memset(mpm_stats, 0x00, sizeof(mpm_stats)); - uint32_t alstats[ALPROTO_MAX] = {0}; + uint32_t alstats[ALPROTO_MAX] = { 0 }; uint32_t mpm_sizes[max_buffer_type_id][256]; memset(mpm_sizes, 0, sizeof(mpm_sizes)); uint32_t alproto_mpm_bufs[ALPROTO_MAX][max_buffer_type_id]; @@ -730,16 +727,22 @@ static json_t *RulesGroupPrintSghStats(const DetectEngineCtx *de_ctx, const SigG DetectPort *dp = s->dp; if (s->flags & SIG_FLAG_TOSERVER) { if (dp->port == 0 && dp->port2 == 65535) { - SCLogDebug("SGH %p toserver 1byte fast_pattern to ANY. Rule %u", sgh, s->id); + SCLogDebug("SGH %p toserver 1byte fast_pattern to ANY. Rule %u", sgh, + s->id); } else { - SCLogDebug("SGH %p toserver 1byte fast_pattern to port(s) %u-%u. Rule %u", sgh, dp->port, dp->port2, s->id); + SCLogDebug( + "SGH %p toserver 1byte fast_pattern to port(s) %u-%u. Rule %u", + sgh, dp->port, dp->port2, s->id); } } if (s->flags & SIG_FLAG_TOCLIENT) { if (sp->port == 0 && sp->port2 == 65535) { - SCLogDebug("SGH %p toclient 1byte fast_pattern to ANY. Rule %u", sgh, s->id); + SCLogDebug("SGH %p toclient 1byte fast_pattern to ANY. Rule %u", sgh, + s->id); } else { - SCLogDebug("SGH %p toclient 1byte fast_pattern to port(s) %u-%u. Rule %u", sgh, sp->port, sp->port2, s->id); + SCLogDebug( + "SGH %p toclient 1byte fast_pattern to port(s) %u-%u. Rule %u", + sgh, sp->port, sp->port2, s->id); } } } @@ -764,14 +767,17 @@ static json_t *RulesGroupPrintSghStats(const DetectEngineCtx *de_ctx, const SigG mpm_cnt++; if (w < 10) { - SCLogDebug("SGH %p Weak MPM Pattern on %s. Rule %u", sgh, DetectListToString(mpm_list), s->id); + SCLogDebug("SGH %p Weak MPM Pattern on %s. Rule %u", sgh, + DetectListToString(mpm_list), s->id); } if (w < 10 && any == 5) { - SCLogDebug("SGH %p Weak MPM Pattern on %s, rule is 5xAny. Rule %u", sgh, DetectListToString(mpm_list), s->id); + SCLogDebug("SGH %p Weak MPM Pattern on %s, rule is 5xAny. Rule %u", sgh, + DetectListToString(mpm_list), s->id); } if (cd->flags & DETECT_CONTENT_NEGATED) { - SCLogDebug("SGH %p MPM Pattern on %s, is negated. Rule %u", sgh, DetectListToString(mpm_list), s->id); + SCLogDebug("SGH %p MPM Pattern on %s, is negated. Rule %u", sgh, + DetectListToString(mpm_list), s->id); negmpm_cnt++; } if (cd->flags & DETECT_CONTENT_ENDS_WITH) { @@ -857,7 +863,8 @@ static json_t *RulesGroupPrintSghStats(const DetectEngineCtx *de_ctx, const SigG json_t *buf = json_object(); json_object_set_new(buf, "total", json_integer(mpm_stats[i].cnt)); - json_object_set_new(buf, "avg_strength", json_integer(mpm_stats[i].total / mpm_stats[i].cnt)); + json_object_set_new( + buf, "avg_strength", json_integer(mpm_stats[i].total / mpm_stats[i].cnt)); json_object_set_new(buf, "min_strength", json_integer(mpm_stats[i].min)); json_object_set_new(buf, "max_strength", json_integer(mpm_stats[i].max)); @@ -882,8 +889,8 @@ static json_t *RulesGroupPrintSghStats(const DetectEngineCtx *de_ctx, const SigG return js; } -static void RulesDumpGrouping(const DetectEngineCtx *de_ctx, - const int add_rules, const int add_mpm_stats) +static void RulesDumpGrouping( + const DetectEngineCtx *de_ctx, const int add_rules, const int add_mpm_stats) { json_t *js = json_object(); if (unlikely(js == NULL)) @@ -897,8 +904,7 @@ static void RulesDumpGrouping(const DetectEngineCtx *de_ctx, json_t *tcp = json_object(); json_t *ts_array = json_array(); - DetectPort *list = (p == IPPROTO_TCP) ? de_ctx->flow_gh[1].tcp : - de_ctx->flow_gh[1].udp; + DetectPort *list = (p == IPPROTO_TCP) ? de_ctx->flow_gh[1].tcp : de_ctx->flow_gh[1].udp; while (list != NULL) { json_t *port = json_object(); json_object_set_new(port, "port", json_integer(list->port)); @@ -914,8 +920,7 @@ static void RulesDumpGrouping(const DetectEngineCtx *de_ctx, json_object_set_new(tcp, "toserver", ts_array); json_t *tc_array = json_array(); - list = (p == IPPROTO_TCP) ? de_ctx->flow_gh[0].tcp : - de_ctx->flow_gh[0].udp; + list = (p == IPPROTO_TCP) ? de_ctx->flow_gh[0].tcp : de_ctx->flow_gh[0].udp; while (list != NULL) { json_t *port = json_object(); json_object_set_new(port, "port", json_integer(list->port)); @@ -963,8 +968,7 @@ static void RulesDumpGrouping(const DetectEngineCtx *de_ctx, return; } - char *js_s = json_dumps(js, - JSON_PRESERVE_ORDER|JSON_ESCAPE_SLASH); + char *js_s = json_dumps(js, JSON_PRESERVE_ORDER | JSON_ESCAPE_SLASH); if (unlikely(js_s == NULL)) { fclose(fp); return; @@ -984,10 +988,10 @@ static int RulesGroupByProto(DetectEngineCtx *de_ctx) Signature *s = de_ctx->sig_list; uint32_t max_idx = 0; - SigGroupHead *sgh_ts[256] = {NULL}; - SigGroupHead *sgh_tc[256] = {NULL}; + SigGroupHead *sgh_ts[256] = { NULL }; + SigGroupHead *sgh_tc[256] = { NULL }; - for ( ; s != NULL; s = s->next) { + for (; s != NULL; s = s->next) { if (s->type == SIG_TYPE_IPONLY) continue; @@ -996,7 +1000,7 @@ static int RulesGroupByProto(DetectEngineCtx *de_ctx) if (p == IPPROTO_TCP || p == IPPROTO_UDP) { continue; } - if (!(s->proto.proto[p / 8] & (1<<(p % 8)) || (s->proto.flags & DETECT_PROTO_ANY))) { + if (!(s->proto.proto[p / 8] & (1 << (p % 8)) || (s->proto.flags & DETECT_PROTO_ANY))) { continue; } @@ -1046,8 +1050,7 @@ static int RulesGroupByProto(DetectEngineCtx *de_ctx) ref++; } } - SCLogPerf("OTHER %s: %u proto groups, %u unique SGH's, %u copies", - "toserver", cnt, own, ref); + SCLogPerf("OTHER %s: %u proto groups, %u unique SGH's, %u copies", "toserver", cnt, own, ref); cnt = 0; own = 0; @@ -1079,8 +1082,7 @@ static int RulesGroupByProto(DetectEngineCtx *de_ctx) ref++; } } - SCLogPerf("OTHER %s: %u proto groups, %u unique SGH's, %u copies", - "toclient", cnt, own, ref); + SCLogPerf("OTHER %s: %u proto groups, %u unique SGH's, %u copies", "toclient", cnt, own, ref); for (p = 0; p < 256; p++) { if (p == IPPROTO_TCP || p == IPPROTO_UDP) @@ -1093,8 +1095,7 @@ static int RulesGroupByProto(DetectEngineCtx *de_ctx) return 0; } -static int PortIsWhitelisted(const DetectEngineCtx *de_ctx, - const DetectPort *a, int ipproto) +static int PortIsWhitelisted(const DetectEngineCtx *de_ctx, const DetectPort *a, int ipproto) { DetectPort *w = de_ctx->tcp_whitelist; if (ipproto == IPPROTO_UDP) @@ -1152,7 +1153,8 @@ static int RuleSetWhitelist(Signature *s) return wl; } -int CreateGroupedPortList(DetectEngineCtx *de_ctx, DetectPort *port_list, DetectPort **newhead, uint32_t unique_groups, int (*CompareFunc)(DetectPort *, DetectPort *), uint32_t max_idx); +int CreateGroupedPortList(DetectEngineCtx *de_ctx, DetectPort *port_list, DetectPort **newhead, + uint32_t unique_groups, int (*CompareFunc)(DetectPort *, DetectPort *), uint32_t max_idx); int CreateGroupedPortListCmpCnt(DetectPort *a, DetectPort *b); static DetectPort *RulesGroupByPorts(DetectEngineCtx *de_ctx, uint8_t ipproto, uint32_t direction) @@ -1169,7 +1171,8 @@ static DetectPort *RulesGroupByPorts(DetectEngineCtx *de_ctx, uint8_t ipproto, u /* IP Only rules are handled separately */ if (s->type == SIG_TYPE_IPONLY) goto next; - if (!(s->proto.proto[ipproto / 8] & (1<<(ipproto % 8)) || (s->proto.flags & DETECT_PROTO_ANY))) + if (!(s->proto.proto[ipproto / 8] & (1 << (ipproto % 8)) || + (s->proto.flags & DETECT_PROTO_ANY))) goto next; if (direction == SIG_FLAG_TOSERVER) { if (!(s->flags & SIG_FLAG_TOSERVER)) @@ -1189,12 +1192,11 @@ static DetectPort *RulesGroupByPorts(DetectEngineCtx *de_ctx, uint8_t ipproto, u /* see if we want to exclude directionless sigs that really care only for * to_server syn scans/floods */ - if ((direction == SIG_FLAG_TOCLIENT) && - DetectFlagsSignatureNeedsSynPackets(s) && - DetectFlagsSignatureNeedsSynOnlyPackets(s) && - ((s->flags & (SIG_FLAG_TOSERVER|SIG_FLAG_TOCLIENT)) == (SIG_FLAG_TOSERVER|SIG_FLAG_TOCLIENT)) && - (!(s->dp->port == 0 && s->dp->port2 == 65535))) - { + if ((direction == SIG_FLAG_TOCLIENT) && DetectFlagsSignatureNeedsSynPackets(s) && + DetectFlagsSignatureNeedsSynOnlyPackets(s) && + ((s->flags & (SIG_FLAG_TOSERVER | SIG_FLAG_TOCLIENT)) == + (SIG_FLAG_TOSERVER | SIG_FLAG_TOCLIENT)) && + (!(s->dp->port == 0 && s->dp->port2 == 65535))) { SCLogWarning("rule %u: SYN-only to port(s) %u:%u " "w/o direction specified, disabling for toclient direction", s->id, s->dp->port, s->dp->port2); @@ -1204,7 +1206,7 @@ static DetectPort *RulesGroupByPorts(DetectEngineCtx *de_ctx, uint8_t ipproto, u int wl = s->init_data->whitelist; while (p) { int pwl = PortIsWhitelisted(de_ctx, p, ipproto) ? 111 : 0; - pwl = MAX(wl,pwl); + pwl = MAX(wl, pwl); DetectPort *lookup = DetectPortHashLookup(de_ctx, p); if (lookup) { @@ -1227,14 +1229,12 @@ static DetectPort *RulesGroupByPorts(DetectEngineCtx *de_ctx, uint8_t ipproto, u /* step 2: create a list of DetectPort objects */ HashListTableBucket *htb = NULL; - for (htb = HashListTableGetListHead(de_ctx->dport_hash_table); - htb != NULL; - htb = HashListTableGetListNext(htb)) - { + for (htb = HashListTableGetListHead(de_ctx->dport_hash_table); htb != NULL; + htb = HashListTableGetListNext(htb)) { DetectPort *p = HashListTableGetListData(htb); DetectPort *tmp = DetectPortCopySingle(de_ctx, p); BUG_ON(tmp == NULL); - int r = DetectPortInsert(de_ctx, &list , tmp); + int r = DetectPortInsert(de_ctx, &list, tmp); BUG_ON(r == -1); } DetectPortHashFree(de_ctx); @@ -1244,8 +1244,8 @@ static DetectPort *RulesGroupByPorts(DetectEngineCtx *de_ctx, uint8_t ipproto, u /* step 3: group the list and shrink it if necessary */ DetectPort *newlist = NULL; - uint16_t groupmax = (direction == SIG_FLAG_TOCLIENT) ? de_ctx->max_uniq_toclient_groups : - de_ctx->max_uniq_toserver_groups; + uint16_t groupmax = (direction == SIG_FLAG_TOCLIENT) ? de_ctx->max_uniq_toclient_groups + : de_ctx->max_uniq_toserver_groups; CreateGroupedPortList(de_ctx, list, &newlist, groupmax, CreateGroupedPortListCmpCnt, max_idx); list = newlist; @@ -1257,8 +1257,8 @@ static DetectPort *RulesGroupByPorts(DetectEngineCtx *de_ctx, uint8_t ipproto, u uint32_t own = 0; uint32_t ref = 0; DetectPort *iter; - for (iter = list ; iter != NULL; iter = iter->next) { - BUG_ON (iter->sh == NULL); + for (iter = list; iter != NULL; iter = iter->next) { + BUG_ON(iter->sh == NULL); cnt++; SigGroupHead *lookup_sgh = SigGroupHeadHashLookup(de_ctx, iter->sh); @@ -1290,10 +1290,8 @@ static DetectPort *RulesGroupByPorts(DetectEngineCtx *de_ctx, uint8_t ipproto, u iter->sh->init->whitelist); } #endif - SCLogPerf("%s %s: %u port groups, %u unique SGH's, %u copies", - ipproto == 6 ? "TCP" : "UDP", - direction == SIG_FLAG_TOSERVER ? "toserver" : "toclient", - cnt, own, ref); + SCLogPerf("%s %s: %u port groups, %u unique SGH's, %u copies", ipproto == 6 ? "TCP" : "UDP", + direction == SIG_FLAG_TOSERVER ? "toserver" : "toclient", cnt, own, ref); return list; } @@ -1387,28 +1385,29 @@ int SigAddressPrepareStage1(DetectEngineCtx *de_ctx) if (de_ctx->sig_array == NULL) goto error; - SCLogDebug("signature lookup array: %" PRIu32 " sigs, %" PRIu32 " bytes", - de_ctx->sig_array_len, de_ctx->sig_array_size); + SCLogDebug("signature lookup array: %" PRIu32 " sigs, %" PRIu32 " bytes", de_ctx->sig_array_len, + de_ctx->sig_array_size); /* now for every rule add the source group */ for (Signature *s = de_ctx->sig_list; s != NULL; s = s->next) { de_ctx->sig_array[s->num] = s; - SCLogDebug("Signature %" PRIu32 ", internal id %" PRIu32 ", ptrs %p %p ", s->id, s->num, s, de_ctx->sig_array[s->num]); + SCLogDebug("Signature %" PRIu32 ", internal id %" PRIu32 ", ptrs %p %p ", s->id, s->num, s, + de_ctx->sig_array[s->num]); if (s->type == SIG_TYPE_PDONLY) { - SCLogDebug("Signature %"PRIu32" is considered \"PD only\"", s->id); + SCLogDebug("Signature %" PRIu32 " is considered \"PD only\"", s->id); } else if (s->type == SIG_TYPE_IPONLY) { - SCLogDebug("Signature %"PRIu32" is considered \"IP only\"", s->id); + SCLogDebug("Signature %" PRIu32 " is considered \"IP only\"", s->id); cnt_iponly++; } else if (SignatureIsInspectingPayload(de_ctx, s) == 1) { - SCLogDebug("Signature %"PRIu32" is considered \"Payload inspecting\"", s->id); + SCLogDebug("Signature %" PRIu32 " is considered \"Payload inspecting\"", s->id); cnt_payload++; } else if (s->type == SIG_TYPE_DEONLY) { - SCLogDebug("Signature %"PRIu32" is considered \"Decoder Event only\"", s->id); + SCLogDebug("Signature %" PRIu32 " is considered \"Decoder Event only\"", s->id); cnt_deonly++; } else if (s->flags & SIG_FLAG_APPLAYER) { - SCLogDebug("Signature %"PRIu32" is considered \"Applayer inspecting\"", s->id); + SCLogDebug("Signature %" PRIu32 " is considered \"Applayer inspecting\"", s->id); cnt_applayer++; } @@ -1431,7 +1430,7 @@ int SigAddressPrepareStage1(DetectEngineCtx *de_ctx) if (copresent && colen == 1) { SCLogDebug("signature %8u content maxlen 1", s->id); for (int proto = 0; proto < 256; proto++) { - if (s->proto.proto[(proto/8)] & (1<<(proto%8))) + if (s->proto.proto[(proto / 8)] & (1 << (proto % 8))) SCLogDebug("=> proto %" PRId32 "", proto); } } @@ -1450,8 +1449,7 @@ int SigAddressPrepareStage1(DetectEngineCtx *de_ctx) /* if keyword engines are enabled in the config, handle them here */ if (de_ctx->prefilter_setting == DETECT_PREFILTER_AUTO && - !(s->flags & SIG_FLAG_PREFILTER)) - { + !(s->flags & SIG_FLAG_PREFILTER)) { int prefilter_list = DETECT_TBLSIZE; // TODO buffers? @@ -1474,7 +1472,8 @@ int SigAddressPrepareStage1(DetectEngineCtx *de_ctx) if (sm->type == prefilter_list) { s->init_data->prefilter_sm = sm; s->flags |= SIG_FLAG_PREFILTER; - SCLogConfig("sid %u: prefilter is on \"%s\"", s->id, sigmatch_table[sm->type].name); + SCLogConfig("sid %u: prefilter is on \"%s\"", s->id, + sigmatch_table[sm->type].name); break; } } @@ -1508,7 +1507,7 @@ int SigAddressPrepareStage1(DetectEngineCtx *de_ctx) de_ctx->sig_cnt, cnt_iponly, cnt_payload, cnt_applayer, cnt_deonly); SCLogConfig("building signature grouping structure, stage 1: " - "preprocessing rules... complete"); + "preprocessing rules... complete"); } if (DetectFlowbitsAnalyze(de_ctx) != 0) @@ -1567,7 +1566,8 @@ int CreateGroupedPortListCmpCnt(DetectPort *a, DetectPort *b) * The joingr is meant to be a catch all. * */ -int CreateGroupedPortList(DetectEngineCtx *de_ctx, DetectPort *port_list, DetectPort **newhead, uint32_t unique_groups, int (*CompareFunc)(DetectPort *, DetectPort *), uint32_t max_idx) +int CreateGroupedPortList(DetectEngineCtx *de_ctx, DetectPort *port_list, DetectPort **newhead, + uint32_t unique_groups, int (*CompareFunc)(DetectPort *, DetectPort *), uint32_t max_idx) { DetectPort *tmplist = NULL, *joingr = NULL; char insert = 0; @@ -1596,7 +1596,7 @@ int CreateGroupedPortList(DetectEngineCtx *de_ctx, DetectPort *port_list, Detect tmplist = list; } else { /* look for the place to insert */ - for ( ; tmpgr != NULL && !insert; tmpgr = tmpgr->next) { + for (; tmpgr != NULL && !insert; tmpgr = tmpgr->next) { if (CompareFunc(list, tmpgr) == 1) { if (tmpgr == tmplist) { list->next = tmplist; @@ -1628,7 +1628,7 @@ int CreateGroupedPortList(DetectEngineCtx *de_ctx, DetectPort *port_list, Detect * count. The rest is added to the 'join' group. */ DetectPort *tmplist2 = NULL, *tmplist2_tail = NULL; DetectPort *gr, *next_gr; - for (gr = tmplist; gr != NULL; ) { + for (gr = tmplist; gr != NULL;) { next_gr = gr->next; SCLogDebug("temp list gr %p %u:%u", gr, gr->port, gr->port2); @@ -1645,12 +1645,12 @@ int CreateGroupedPortList(DetectEngineCtx *de_ctx, DetectPort *port_list, Detect SCLogDebug("joingr => %u-%u", joingr->port, joingr->port2); joingr->next = NULL; } - SigGroupHeadCopySigs(de_ctx,gr->sh,&joingr->sh); + SigGroupHeadCopySigs(de_ctx, gr->sh, &joingr->sh); /* when a group's sigs are added to the joingr, we can free it */ gr->next = NULL; DetectPortFree(de_ctx, gr); - /* append */ + /* append */ } else { gr->next = NULL; @@ -1675,10 +1675,10 @@ int CreateGroupedPortList(DetectEngineCtx *de_ctx, DetectPort *port_list, Detect if (tmplist2 == NULL) { tmplist2 = joingr; - //tmplist2_tail = joingr; + // tmplist2_tail = joingr; } else { tmplist2_tail->next = joingr; - //tmplist2_tail = joingr; + // tmplist2_tail = joingr; } } else { SCLogDebug("no joingr"); @@ -1699,7 +1699,7 @@ int CreateGroupedPortList(DetectEngineCtx *de_ctx, DetectPort *port_list, Detect */ static void DetectEngineAddDecoderEventSig(DetectEngineCtx *de_ctx, Signature *s) { - SCLogDebug("adding signature %"PRIu32" to the decoder event sgh", s->id); + SCLogDebug("adding signature %" PRIu32 " to the decoder event sgh", s->id); SigGroupHeadAppendSig(de_ctx, &de_ctx->decoder_event_sgh, s); } @@ -1715,7 +1715,7 @@ static void DetectEngineAddDecoderEventSig(DetectEngineCtx *de_ctx, Signature *s int SigAddressPrepareStage2(DetectEngineCtx *de_ctx) { SCLogDebug("building signature grouping structure, stage 2: " - "building source address lists..."); + "building source address lists..."); IPOnlyInit(de_ctx, &de_ctx->io_ctx); @@ -1729,7 +1729,7 @@ int SigAddressPrepareStage2(DetectEngineCtx *de_ctx) /* now for every rule add the source group to our temp lists */ for (Signature *s = de_ctx->sig_list; s != NULL; s = s->next) { - SCLogDebug("s->id %"PRIu32, s->id); + SCLogDebug("s->id %" PRIu32, s->id); if (s->type == SIG_TYPE_IPONLY) { IPOnlyAddSignature(de_ctx, &de_ctx->io_ctx, s); } else if (s->type == SIG_TYPE_DEONLY) { @@ -1837,7 +1837,7 @@ int SigAddressPrepareStage4(DetectEngineCtx *de_ctx) { SCEnter(); - //SCLogInfo("sgh's %"PRIu32, de_ctx->sgh_array_cnt); + // SCLogInfo("sgh's %"PRIu32, de_ctx->sgh_array_cnt); uint32_t cnt = 0; for (uint32_t idx = 0; idx < de_ctx->sgh_array_cnt; idx++) { @@ -1918,7 +1918,8 @@ static int SigMatchPrepare(DetectEngineCtx *de_ctx) /* built-ins */ for (int type = 0; type < DETECT_SM_LIST_MAX; type++) { /* skip PMATCH if it is used in a stream 'app engine' instead */ - if (type == DETECT_SM_LIST_PMATCH && (s->init_data->init_flags & SIG_FLAG_INIT_STATE_MATCH)) + if (type == DETECT_SM_LIST_PMATCH && + (s->init_data->init_flags & SIG_FLAG_INIT_STATE_MATCH)) continue; SigMatch *sm = s->init_data->smlists[type]; s->sm_arrays[type] = SigMatchList2DataArray(sm); @@ -2042,7 +2043,7 @@ int SigGroupBuild(DetectEngineCtx *de_ctx) return 0; } -int SigGroupCleanup (DetectEngineCtx *de_ctx) +int SigGroupCleanup(DetectEngineCtx *de_ctx) { SigAddressCleanupStage1(de_ctx); diff --git a/src/detect-engine-build.h b/src/detect-engine-build.h index 2c9c48792856..80ac67062ef4 100644 --- a/src/detect-engine-build.h +++ b/src/detect-engine-build.h @@ -18,8 +18,7 @@ #ifndef __DETECT_ENGINE_BUILD_H__ #define __DETECT_ENGINE_BUILD_H__ -void PacketCreateMask(Packet *p, SignatureMask *mask, AppProto alproto, - bool app_decoder_events); +void PacketCreateMask(Packet *p, SignatureMask *mask, AppProto alproto, bool app_decoder_events); int SignatureIsFilestoring(const Signature *); int SignatureIsFilemagicInspecting(const Signature *); @@ -38,6 +37,6 @@ int SigAddressCleanupStage1(DetectEngineCtx *de_ctx); void SigCleanSignatures(DetectEngineCtx *); int SigGroupBuild(DetectEngineCtx *); -int SigGroupCleanup (DetectEngineCtx *de_ctx); +int SigGroupCleanup(DetectEngineCtx *de_ctx); #endif /* __DETECT_ENGINE_BUILD_H__ */ diff --git a/src/detect-engine-content-inspection.c b/src/detect-engine-content-inspection.c index 1ec78fb550bb..53ba68612490 100644 --- a/src/detect-engine-content-inspection.c +++ b/src/detect-engine-content-inspection.c @@ -116,12 +116,12 @@ int DetectEngineContentInspectionInternal(DetectEngineCtx *de_ctx, DetectEngineT if (smd->type == DETECT_CONTENT) { const DetectContentData *cd = (const DetectContentData *)smd->ctx; - SCLogDebug("inspecting content %"PRIu32" buffer_len %"PRIu32, cd->id, buffer_len); + SCLogDebug("inspecting content %" PRIu32 " buffer_len %" PRIu32, cd->id, buffer_len); /* we might have already have this content matched by the mpm. * (if there is any other reason why we'd want to avoid checking * it here, please fill it in) */ - //if (cd->flags & DETECT_CONTENT_NO_DOUBLE_INSPECTION_REQUIRED) { + // if (cd->flags & DETECT_CONTENT_NO_DOUBLE_INSPECTION_REQUIRED) { // goto match; //} @@ -139,8 +139,7 @@ int DetectEngineContentInspectionInternal(DetectEngineCtx *de_ctx, DetectEngineT uint32_t prev_buffer_offset = det_ctx->buffer_offset; do { - if ((cd->flags & DETECT_CONTENT_DISTANCE) || - (cd->flags & DETECT_CONTENT_WITHIN)) { + if ((cd->flags & DETECT_CONTENT_DISTANCE) || (cd->flags & DETECT_CONTENT_WITHIN)) { SCLogDebug("det_ctx->buffer_offset %" PRIu32, det_ctx->buffer_offset); offset = prev_buffer_offset; @@ -154,22 +153,27 @@ int DetectEngineContentInspectionInternal(DetectEngineCtx *de_ctx, DetectEngineT else offset += distance; - SCLogDebug("cd->distance %"PRIi32", offset %"PRIu32", depth %"PRIu32, - distance, offset, depth); + SCLogDebug("cd->distance %" PRIi32 ", offset %" PRIu32 ", depth %" PRIu32, + distance, offset, depth); } if (cd->flags & DETECT_CONTENT_WITHIN) { if (cd->flags & DETECT_CONTENT_WITHIN_VAR) { - if ((int32_t)depth > (int32_t)(prev_buffer_offset + det_ctx->byte_values[cd->within] + distance)) { - depth = prev_buffer_offset + det_ctx->byte_values[cd->within] + distance; + if ((int32_t)depth > + (int32_t)(prev_buffer_offset + det_ctx->byte_values[cd->within] + + distance)) { + depth = prev_buffer_offset + det_ctx->byte_values[cd->within] + + distance; } } else { - if ((int32_t)depth > (int32_t)(prev_buffer_offset + cd->within + distance)) { + if ((int32_t)depth > + (int32_t)(prev_buffer_offset + cd->within + distance)) { depth = prev_buffer_offset + cd->within + distance; } - SCLogDebug("cd->within %"PRIi32", det_ctx->buffer_offset %"PRIu32", depth %"PRIu32, - cd->within, prev_buffer_offset, depth); + SCLogDebug("cd->within %" PRIi32 ", det_ctx->buffer_offset %" PRIu32 + ", depth %" PRIu32, + cd->within, prev_buffer_offset, depth); } if (stream_start_offset != 0 && prev_buffer_offset == 0) { @@ -193,7 +197,7 @@ int DetectEngineContentInspectionInternal(DetectEngineCtx *de_ctx, DetectEngineT depth = prev_buffer_offset + cd->depth; } - SCLogDebug("cd->depth %"PRIu32", depth %"PRIu32, cd->depth, depth); + SCLogDebug("cd->depth %" PRIu32 ", depth %" PRIu32, cd->depth, depth); } } @@ -203,7 +207,7 @@ int DetectEngineContentInspectionInternal(DetectEngineCtx *de_ctx, DetectEngineT } else { if (cd->offset > offset) { offset = cd->offset; - SCLogDebug("setting offset %"PRIu32, offset); + SCLogDebug("setting offset %" PRIu32, offset); } } } else { /* implied no relative matches */ @@ -237,17 +241,18 @@ int DetectEngineContentInspectionInternal(DetectEngineCtx *de_ctx, DetectEngineT /* If the value came from a variable, make sure to adjust the depth so it's relative * to the offset value. */ - if (cd->flags & (DETECT_CONTENT_DISTANCE_VAR|DETECT_CONTENT_OFFSET_VAR|DETECT_CONTENT_DEPTH_VAR)) { - depth += offset; + if (cd->flags & (DETECT_CONTENT_DISTANCE_VAR | DETECT_CONTENT_OFFSET_VAR | + DETECT_CONTENT_DEPTH_VAR)) { + depth += offset; } /* update offset with prev_offset if we're searching for * matches after the first occurrence. */ - SCLogDebug("offset %"PRIu32", prev_offset %"PRIu32, offset, prev_offset); + SCLogDebug("offset %" PRIu32 ", prev_offset %" PRIu32, offset, prev_offset); if (prev_offset != 0) offset = prev_offset; - SCLogDebug("offset %"PRIu32", depth %"PRIu32, offset, depth); + SCLogDebug("offset %" PRIu32 ", depth %" PRIu32, offset, depth); if (depth > buffer_len) depth = buffer_len; @@ -270,19 +275,20 @@ int DetectEngineContentInspectionInternal(DetectEngineCtx *de_ctx, DetectEngineT BUG_ON(sbuffer_len > buffer_len); #endif if (cd->flags & DETECT_CONTENT_ENDS_WITH && depth < buffer_len) { - SCLogDebug("depth < buffer_len while DETECT_CONTENT_ENDS_WITH is set. Can't possibly match."); + SCLogDebug("depth < buffer_len while DETECT_CONTENT_ENDS_WITH is set. Can't " + "possibly match."); found = NULL; } else if (cd->content_len > sbuffer_len) { found = NULL; } else { /* do the actual search */ - found = SpmScan(cd->spm_ctx, det_ctx->spm_thread_ctx, sbuffer, - sbuffer_len); + found = SpmScan(cd->spm_ctx, det_ctx->spm_thread_ctx, sbuffer, sbuffer_len); } /* next we evaluate the result in combination with the * negation flag. */ - SCLogDebug("found %p cd negated %s", found, cd->flags & DETECT_CONTENT_NEGATED ? "true" : "false"); + SCLogDebug("found %p cd negated %s", found, + cd->flags & DETECT_CONTENT_NEGATED ? "true" : "false"); if (found == NULL) { if (!(cd->flags & DETECT_CONTENT_NEGATED)) { @@ -373,7 +379,7 @@ int DetectEngineContentInspectionInternal(DetectEngineCtx *de_ctx, DetectEngineT } } - } while(1); + } while (1); } else if (smd->type == DETECT_ISDATAAT) { SCLogDebug("inspecting isdataat"); @@ -384,19 +390,21 @@ int DetectEngineContentInspectionInternal(DetectEngineCtx *de_ctx, DetectEngineT uint64_t be_value = det_ctx->byte_values[dataat]; if (be_value >= 100000000) { if ((id->flags & ISDATAAT_NEGATED) == 0) { - SCLogDebug("extracted value %"PRIu64" very big: no match", be_value); + SCLogDebug("extracted value %" PRIu64 " very big: no match", be_value); goto no_match; } - SCLogDebug("extracted value way %"PRIu64" very big: match", be_value); + SCLogDebug("extracted value way %" PRIu64 " very big: match", be_value); goto match; } dataat = (uint32_t)be_value; - SCLogDebug("isdataat: using value %u from byte_extract local_id %u", dataat, id->dataat); + SCLogDebug( + "isdataat: using value %u from byte_extract local_id %u", dataat, id->dataat); } if (id->flags & ISDATAAT_RELATIVE) { if (det_ctx->buffer_offset + dataat > buffer_len) { - SCLogDebug("det_ctx->buffer_offset + dataat %"PRIu32" > %"PRIu32, det_ctx->buffer_offset + dataat, buffer_len); + SCLogDebug("det_ctx->buffer_offset + dataat %" PRIu32 " > %" PRIu32, + det_ctx->buffer_offset + dataat, buffer_len); if (id->flags & ISDATAAT_NEGATED) goto match; goto no_match; @@ -413,7 +421,9 @@ int DetectEngineContentInspectionInternal(DetectEngineCtx *de_ctx, DetectEngineT goto no_match; goto match; } else { - SCLogDebug("absolute isdataat mismatch, id->isdataat %"PRIu32", buffer_len %"PRIu32"", dataat, buffer_len); + SCLogDebug("absolute isdataat mismatch, id->isdataat %" PRIu32 + ", buffer_len %" PRIu32 "", + dataat, buffer_len); if (id->flags & ISDATAAT_NEGATED) goto match; goto no_match; @@ -478,8 +488,7 @@ int DetectEngineContentInspectionInternal(DetectEngineCtx *de_ctx, DetectEngineT if (btflags & DETECT_BYTETEST_DCE) { /* enable the endianness flag temporarily. once we are done * processing we reset the flags to the original value*/ - btflags |= ((flags & DETECT_CI_FLAGS_DCE_LE) ? - DETECT_BYTETEST_LITTLE: 0); + btflags |= ((flags & DETECT_CI_FLAGS_DCE_LE) ? DETECT_BYTETEST_LITTLE : 0); } if (DetectBytetestDoMatch(det_ctx, s, smd->ctx, buffer, buffer_len, btflags, offset, nbytes, @@ -510,8 +519,7 @@ int DetectEngineContentInspectionInternal(DetectEngineCtx *de_ctx, DetectEngineT if (bjflags & DETECT_BYTEJUMP_DCE) { /* enable the endianness flag temporarily. once we are done * processing we reset the flags to the original value*/ - bjflags |= ((flags & DETECT_CI_FLAGS_DCE_LE) ? - DETECT_BYTEJUMP_LITTLE: 0); + bjflags |= ((flags & DETECT_CI_FLAGS_DCE_LE) ? DETECT_BYTEJUMP_LITTLE : 0); } if (!DetectBytejumpDoMatch( @@ -529,13 +537,13 @@ int DetectEngineContentInspectionInternal(DetectEngineCtx *de_ctx, DetectEngineT /* if we have dce enabled we will have to use the endianness * specified by the dce header */ if ((bed->flags & DETECT_BYTE_EXTRACT_FLAG_ENDIAN) && - endian == DETECT_BYTE_EXTRACT_ENDIAN_DCE && - flags & (DETECT_CI_FLAGS_DCE_LE|DETECT_CI_FLAGS_DCE_BE)) { + endian == DETECT_BYTE_EXTRACT_ENDIAN_DCE && + flags & (DETECT_CI_FLAGS_DCE_LE | DETECT_CI_FLAGS_DCE_BE)) { /* enable the endianness flag temporarily. once we are done * processing we reset the flags to the original value*/ - endian |= ((flags & DETECT_CI_FLAGS_DCE_LE) ? - DETECT_BYTE_EXTRACT_ENDIAN_LITTLE : DETECT_BYTE_EXTRACT_ENDIAN_BIG); + endian |= ((flags & DETECT_CI_FLAGS_DCE_LE) ? DETECT_BYTE_EXTRACT_ENDIAN_LITTLE + : DETECT_BYTE_EXTRACT_ENDIAN_BIG); } if (DetectByteExtractDoMatch(det_ctx, smd, s, buffer, buffer_len, @@ -543,8 +551,8 @@ int DetectEngineContentInspectionInternal(DetectEngineCtx *de_ctx, DetectEngineT goto no_match; } - SCLogDebug("[BE] Fetched value for index %d: %"PRIu64, - bed->local_id, det_ctx->byte_values[bed->local_id]); + SCLogDebug("[BE] Fetched value for index %d: %" PRIu64, bed->local_id, + det_ctx->byte_values[bed->local_id]); goto match; } else if (smd->type == DETECT_BYTEMATH) { @@ -581,8 +589,8 @@ int DetectEngineContentInspectionInternal(DetectEngineCtx *de_ctx, DetectEngineT goto no_match; } - SCLogDebug("[BM] Fetched value for index %d: %"PRIu64, - bmd->local_id, det_ctx->byte_values[bmd->local_id]); + SCLogDebug("[BM] Fetched value for index %d: %" PRIu64, bmd->local_id, + det_ctx->byte_values[bmd->local_id]); goto match; } else if (smd->type == DETECT_BSIZE) { @@ -599,9 +607,9 @@ int DetectEngineContentInspectionInternal(DetectEngineCtx *de_ctx, DetectEngineT } else if (smd->type == DETECT_DATASET) { - //PrintRawDataFp(stdout, buffer, buffer_len); - const DetectDatasetData *sd = (const DetectDatasetData *) smd->ctx; - int r = DetectDatasetBufferMatch(det_ctx, sd, buffer, buffer_len); //TODO buffer offset? + // PrintRawDataFp(stdout, buffer, buffer_len); + const DetectDatasetData *sd = (const DetectDatasetData *)smd->ctx; + int r = DetectDatasetBufferMatch(det_ctx, sd, buffer, buffer_len); // TODO buffer offset? if (r == 1) { goto match; } @@ -609,9 +617,9 @@ int DetectEngineContentInspectionInternal(DetectEngineCtx *de_ctx, DetectEngineT } else if (smd->type == DETECT_DATAREP) { - //PrintRawDataFp(stdout, buffer, buffer_len); - const DetectDatarepData *sd = (const DetectDatarepData *) smd->ctx; - int r = DetectDatarepBufferMatch(det_ctx, sd, buffer, buffer_len); //TODO buffer offset? + // PrintRawDataFp(stdout, buffer, buffer_len); + const DetectDatarepData *sd = (const DetectDatarepData *)smd->ctx; + int r = DetectDatarepBufferMatch(det_ctx, sd, buffer, buffer_len); // TODO buffer offset? if (r == 1) { goto match; } @@ -633,13 +641,11 @@ int DetectEngineContentInspectionInternal(DetectEngineCtx *de_ctx, DetectEngineT } goto no_match_discontinue; #ifdef HAVE_LUA - } - else if (smd->type == DETECT_LUA) { + } else if (smd->type == DETECT_LUA) { SCLogDebug("lua starting"); - if (DetectLuaMatchBuffer(det_ctx, s, smd, buffer, buffer_len, - det_ctx->buffer_offset, f) != 1) - { + if (DetectLuaMatchBuffer(det_ctx, s, smd, buffer, buffer_len, det_ctx->buffer_offset, f) != + 1) { SCLogDebug("lua no_match"); goto no_match; } diff --git a/src/detect-engine-content-inspection.h b/src/detect-engine-content-inspection.h index 188ebef2d881..34677dea7588 100644 --- a/src/detect-engine-content-inspection.h +++ b/src/detect-engine-content-inspection.h @@ -36,15 +36,16 @@ enum { DETECT_ENGINE_CONTENT_INSPECTION_MODE_STATE, }; -#define DETECT_CI_FLAGS_START BIT_U8(0) /**< unused, reserved for future use */ -#define DETECT_CI_FLAGS_END BIT_U8(1) /**< indication that current buffer - * is the end of the data */ -#define DETECT_CI_FLAGS_DCE_LE BIT_U8(2) /**< DCERPC record in little endian */ -#define DETECT_CI_FLAGS_DCE_BE BIT_U8(3) /**< DCERPC record in big endian */ +#define DETECT_CI_FLAGS_START BIT_U8(0) /**< unused, reserved for future use */ +#define DETECT_CI_FLAGS_END \ + BIT_U8(1) /**< indication that current buffer \ + * is the end of the data */ +#define DETECT_CI_FLAGS_DCE_LE BIT_U8(2) /**< DCERPC record in little endian */ +#define DETECT_CI_FLAGS_DCE_BE BIT_U8(3) /**< DCERPC record in big endian */ /** buffer is a single, non-streaming, buffer. Data sent to the content * inspection function contains both start and end of the data. */ -#define DETECT_CI_FLAGS_SINGLE (DETECT_CI_FLAGS_START|DETECT_CI_FLAGS_END) +#define DETECT_CI_FLAGS_SINGLE (DETECT_CI_FLAGS_START | DETECT_CI_FLAGS_END) /* "internal" returns 1 match, 0 no match, -1 can't match */ int DetectEngineContentInspectionInternal(DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx, diff --git a/src/detect-engine-dcepayload.c b/src/detect-engine-dcepayload.c index 1b90083aacf7..c8c345aad0b7 100644 --- a/src/detect-engine-dcepayload.c +++ b/src/detect-engine-dcepayload.c @@ -53,7 +53,6 @@ static int g_dce_stub_data_buffer_id = 0; - /**************************************Unittests*******************************/ #ifdef UNITTESTS @@ -94,11 +93,11 @@ static int DcePayloadTest15(void) int r; const char *sig1 = "alert tcp any any -> any any " - "(dce_stub_data; content:\"|5c 00 5c 00 31|\"; distance:0; " - "byte_test:2,=,14080,0,relative,dce; sid:1;)"; + "(dce_stub_data; content:\"|5c 00 5c 00 31|\"; distance:0; " + "byte_test:2,=,14080,0,relative,dce; sid:1;)"; const char *sig2 = "alert tcp any any -> any any " - "(dce_stub_data; content:\"|5c 00 5c 00 31|\"; distance:0; " - "byte_test:2,=,46,5,relative,dce; sid:2;)"; + "(dce_stub_data; content:\"|5c 00 5c 00 31|\"; distance:0; " + "byte_test:2,=,46,5,relative,dce; sid:2;)"; Signature *s; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -109,7 +108,7 @@ static int DcePayloadTest15(void) p = UTHBuildPacket(NULL, 0, IPPROTO_TCP); p->flow = &f; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; @@ -138,8 +137,8 @@ static int DcePayloadTest15(void) DetectEngineThreadCtxInit(&tv, (void *)de_ctx, (void *)&det_ctx); /* request 1 */ - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, - STREAM_TOSERVER, request1, request1_len); + r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_DCERPC, STREAM_TOSERVER, request1, request1_len); if (r != 0) { printf("toserver chunk 1 returned %" PRId32 ", expected 0: ", r); result = 0; @@ -210,11 +209,11 @@ static int DcePayloadTest16(void) int r; const char *sig1 = "alert tcp any any -> any any " - "(dce_stub_data; content:\"|5c 00 5c 00 31|\"; distance:0; " - "byte_test:2,=,55,0,relative; sid:1;)"; + "(dce_stub_data; content:\"|5c 00 5c 00 31|\"; distance:0; " + "byte_test:2,=,55,0,relative; sid:1;)"; const char *sig2 = "alert tcp any any -> any any " - "(dce_stub_data; content:\"|5c 00 5c 00 31|\"; distance:0; " - "byte_test:2,=,11776,5,relative; sid:2;)"; + "(dce_stub_data; content:\"|5c 00 5c 00 31|\"; distance:0; " + "byte_test:2,=,11776,5,relative; sid:2;)"; Signature *s; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -225,7 +224,7 @@ static int DcePayloadTest16(void) p = UTHBuildPacket(NULL, 0, IPPROTO_TCP); p->flow = &f; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; @@ -254,8 +253,8 @@ static int DcePayloadTest16(void) DetectEngineThreadCtxInit(&tv, (void *)de_ctx, (void *)&det_ctx); /* request 1 */ - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, - STREAM_TOSERVER, request1, request1_len); + r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_DCERPC, STREAM_TOSERVER, request1, request1_len); if (r != 0) { printf("toserver chunk 1 returned %" PRId32 ", expected 0: ", r); result = 0; @@ -326,11 +325,11 @@ static int DcePayloadTest17(void) int r; const char *sig1 = "alert tcp any any -> any any " - "(dce_stub_data; content:\"|5c 00 5c 00 31|\"; distance:0; " - "byte_test:2,=,55,0,relative,big; sid:1;)"; + "(dce_stub_data; content:\"|5c 00 5c 00 31|\"; distance:0; " + "byte_test:2,=,55,0,relative,big; sid:1;)"; const char *sig2 = "alert tcp any any -> any any " - "(dce_stub_data; content:\"|5c 00 5c 00 31|\"; distance:0; " - "byte_test:2,=,46,5,relative,little; sid:2;)"; + "(dce_stub_data; content:\"|5c 00 5c 00 31|\"; distance:0; " + "byte_test:2,=,46,5,relative,little; sid:2;)"; Signature *s; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -341,7 +340,7 @@ static int DcePayloadTest17(void) p = UTHBuildPacket(NULL, 0, IPPROTO_TCP); p->flow = &f; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; @@ -370,8 +369,8 @@ static int DcePayloadTest17(void) DetectEngineThreadCtxInit(&tv, (void *)de_ctx, (void *)&det_ctx); /* request 1 */ - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, - STREAM_TOSERVER, request1, request1_len); + r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_DCERPC, STREAM_TOSERVER, request1, request1_len); if (r != 0) { printf("toserver chunk 1 returned %" PRId32 ", expected 0: ", r); result = 0; @@ -442,11 +441,11 @@ static int DcePayloadTest18(void) int r; const char *sig1 = "alert tcp any any -> any any " - "(dce_stub_data; content:\"|5c 00 5c 00 31|\"; distance:0; " - "byte_jump:2,0,relative,dce; byte_test:2,=,46,0,relative,dce; sid:1;)"; + "(dce_stub_data; content:\"|5c 00 5c 00 31|\"; distance:0; " + "byte_jump:2,0,relative,dce; byte_test:2,=,46,0,relative,dce; sid:1;)"; const char *sig2 = "alert tcp any any -> any any " - "(dce_stub_data; content:\"|5c 00 5c 00 31|\"; distance:0; " - "byte_jump:2,2,relative,dce; byte_test:2,=,14080,0,relative; sid:2;)"; + "(dce_stub_data; content:\"|5c 00 5c 00 31|\"; distance:0; " + "byte_jump:2,2,relative,dce; byte_test:2,=,14080,0,relative; sid:2;)"; Signature *s; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -457,7 +456,7 @@ static int DcePayloadTest18(void) p = UTHBuildPacket(NULL, 0, IPPROTO_TCP); p->flow = &f; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; @@ -486,8 +485,8 @@ static int DcePayloadTest18(void) DetectEngineThreadCtxInit(&tv, (void *)de_ctx, (void *)&det_ctx); /* request 1 */ - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, - STREAM_TOSERVER, request1, request1_len); + r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_DCERPC, STREAM_TOSERVER, request1, request1_len); if (r != 0) { printf("toserver chunk 1 returned %" PRId32 ", expected 0: ", r); result = 0; @@ -558,11 +557,11 @@ static int DcePayloadTest19(void) int r; const char *sig1 = "alert tcp any any -> any any " - "(dce_stub_data; content:\"|5c 00 5c 00 31|\"; distance:0; " - "byte_jump:2,0,relative; byte_test:2,=,46,0,relative,dce; sid:1;)"; + "(dce_stub_data; content:\"|5c 00 5c 00 31|\"; distance:0; " + "byte_jump:2,0,relative; byte_test:2,=,46,0,relative,dce; sid:1;)"; const char *sig2 = "alert tcp any any -> any any " - "(dce_stub_data; content:\"|5c 00 5c 00 31|\"; distance:0; " - "byte_jump:2,2,relative; byte_test:2,=,14080,0,relative; sid:2;)"; + "(dce_stub_data; content:\"|5c 00 5c 00 31|\"; distance:0; " + "byte_jump:2,2,relative; byte_test:2,=,14080,0,relative; sid:2;)"; Signature *s; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -573,7 +572,7 @@ static int DcePayloadTest19(void) p = UTHBuildPacket(NULL, 0, IPPROTO_TCP); p->flow = &f; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; @@ -602,8 +601,8 @@ static int DcePayloadTest19(void) DetectEngineThreadCtxInit(&tv, (void *)de_ctx, (void *)&det_ctx); /* request 1 */ - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, - STREAM_TOSERVER, request1, request1_len); + r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_DCERPC, STREAM_TOSERVER, request1, request1_len); if (r != 0) { printf("toserver chunk 1 returned %" PRId32 ", expected 0: ", r); result = 0; @@ -674,11 +673,11 @@ static int DcePayloadTest20(void) int r; const char *sig1 = "alert tcp any any -> any any " - "(dce_stub_data; content:\"|5c 00 5c 00 31|\"; distance:0; " - "byte_jump:2,0,relative,big; byte_test:2,=,46,0,relative,dce; sid:1;)"; + "(dce_stub_data; content:\"|5c 00 5c 00 31|\"; distance:0; " + "byte_jump:2,0,relative,big; byte_test:2,=,46,0,relative,dce; sid:1;)"; const char *sig2 = "alert tcp any any -> any any " - "(dce_stub_data; content:\"|5c 00 5c 00 31|\"; distance:0; " - "byte_jump:2,2,little,relative; byte_test:2,=,14080,0,relative; sid:2;)"; + "(dce_stub_data; content:\"|5c 00 5c 00 31|\"; distance:0; " + "byte_jump:2,2,little,relative; byte_test:2,=,14080,0,relative; sid:2;)"; Signature *s; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -689,7 +688,7 @@ static int DcePayloadTest20(void) p = UTHBuildPacket(NULL, 0, IPPROTO_TCP); p->flow = &f; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; @@ -718,8 +717,8 @@ static int DcePayloadTest20(void) DetectEngineThreadCtxInit(&tv, (void *)de_ctx, (void *)&det_ctx); /* request 1 */ - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_DCERPC, - STREAM_TOSERVER, request1, request1_len); + r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_DCERPC, STREAM_TOSERVER, request1, request1_len); if (r != 0) { printf("toserver chunk 1 returned %" PRId32 ", expected 0: ", r); result = 0; diff --git a/src/detect-engine-enip.c b/src/detect-engine-enip.c index 0c5fb0a81cbe..5632e7b7fa56 100644 --- a/src/detect-engine-enip.c +++ b/src/detect-engine-enip.c @@ -80,50 +80,39 @@ static int CIPPathMatch(CIPServiceEntry *svc, DetectCipServiceData *cipserviced) int found_class = 0; SegmentEntry *seg = NULL; - TAILQ_FOREACH(seg, &svc->segment_list, next) - { - switch(seg->segment) - { + TAILQ_FOREACH (seg, &svc->segment_list, next) { + switch (seg->segment) { case PATH_CLASS_8BIT: class = seg->value; - if (cipserviced->cipclass == class) - { - if (cipserviced->tokens == 2) - {// if rule only has class + if (cipserviced->cipclass == class) { + if (cipserviced->tokens == 2) { // if rule only has class return 1; - } else - { + } else { found_class = 1; } } break; case PATH_INSTANCE_8BIT: break; - case PATH_ATTR_8BIT: //single attribute + case PATH_ATTR_8BIT: // single attribute attrib = seg->value; - if ((cipserviced->tokens == 3) && - (cipserviced->cipclass == class) && + if ((cipserviced->tokens == 3) && (cipserviced->cipclass == class) && (cipserviced->cipattribute == attrib) && - (cipserviced->matchattribute == 1)) - { // if rule has class & attribute, matched all here + (cipserviced->matchattribute == + 1)) { // if rule has class & attribute, matched all here return 1; } - if ((cipserviced->tokens == 3) && - (cipserviced->cipclass == class) && - (cipserviced->matchattribute == 0)) - { // for negation rule on attribute + if ((cipserviced->tokens == 3) && (cipserviced->cipclass == class) && + (cipserviced->matchattribute == 0)) { // for negation rule on attribute return 1; } break; case PATH_CLASS_16BIT: class = seg->value; - if (cipserviced->cipclass == class) - { - if (cipserviced->tokens == 2) - {// if rule only has class + if (cipserviced->cipclass == class) { + if (cipserviced->tokens == 2) { // if rule only has class return 1; - } else - { + } else { found_class = 1; } } @@ -135,19 +124,14 @@ static int CIPPathMatch(CIPServiceEntry *svc, DetectCipServiceData *cipserviced) } } - if (found_class == 0) - { // if haven't matched class yet, no need to check attribute + if (found_class == 0) { // if haven't matched class yet, no need to check attribute return 0; } - if ((svc->service == CIP_SET_ATTR_LIST) || - (svc->service == CIP_GET_ATTR_LIST)) - { + if ((svc->service == CIP_SET_ATTR_LIST) || (svc->service == CIP_GET_ATTR_LIST)) { AttributeEntry *attr = NULL; - TAILQ_FOREACH (attr, &svc->attrib_list, next) - { - if (cipserviced->cipattribute == attr->attribute) - { + TAILQ_FOREACH (attr, &svc->attrib_list, next) { + if (cipserviced->cipattribute == attr->attribute) { return 1; } } @@ -162,42 +146,35 @@ static int CIPPathMatch(CIPServiceEntry *svc, DetectCipServiceData *cipserviced) * * @param cipserviced - the CIP service rule */ -static int CIPServiceMatch(ENIPTransaction *enip_data, - DetectCipServiceData *cipserviced) +static int CIPServiceMatch(ENIPTransaction *enip_data, DetectCipServiceData *cipserviced) { #ifdef DEBUG int count = 1; #endif CIPServiceEntry *svc = NULL; - //SCLogDebug("CIPServiceMatchAL"); - TAILQ_FOREACH(svc, &enip_data->service_list, next) - { - SCLogDebug("CIPServiceMatchAL service #%d : 0x%x dir %d", - count, svc->service, svc->direction); - - if (cipserviced->cipservice == svc->service) - { // compare service - //SCLogDebug("Rule Match for cip service %d",cipserviced->cipservice ); + // SCLogDebug("CIPServiceMatchAL"); + TAILQ_FOREACH (svc, &enip_data->service_list, next) { + SCLogDebug( + "CIPServiceMatchAL service #%d : 0x%x dir %d", count, svc->service, svc->direction); - if (cipserviced->tokens > 1) - { //if rule params have class and attribute + if (cipserviced->cipservice == svc->service) { // compare service + // SCLogDebug("Rule Match for cip service %d",cipserviced->cipservice ); + if (cipserviced->tokens > 1) { // if rule params have class and attribute - if ((svc->service == CIP_SET_ATTR_LIST) || (svc->service - == CIP_SET_ATTR_SINGLE) || (svc->service - == CIP_GET_ATTR_LIST) || (svc->service - == CIP_GET_ATTR_SINGLE)) - { //decode path - if (CIPPathMatch(svc, cipserviced) == 1) - { - if (svc->direction == 1) return 0; //don't match responses + if ((svc->service == CIP_SET_ATTR_LIST) || (svc->service == CIP_SET_ATTR_SINGLE) || + (svc->service == CIP_GET_ATTR_LIST) || + (svc->service == CIP_GET_ATTR_SINGLE)) { // decode path + if (CIPPathMatch(svc, cipserviced) == 1) { + if (svc->direction == 1) + return 0; // don't match responses return 1; } } - } else - { - if (svc->direction == 1) return 0; //don't match responses + } else { + if (svc->direction == 1) + return 0; // don't match responses // SCLogDebug("CIPServiceMatchAL found"); return 1; @@ -228,20 +205,17 @@ uint8_t DetectEngineInspectCIP(DetectEngineCtx *de_ctx, DetectEngineThreadCtx *d { SCEnter(); - - ENIPTransaction *tx = (ENIPTransaction *) txv; + ENIPTransaction *tx = (ENIPTransaction *)txv; DetectCipServiceData *cipserviced = (DetectCipServiceData *)engine->smd->ctx; - if (cipserviced == NULL) - { + if (cipserviced == NULL) { SCLogDebug("no cipservice state, no match"); SCReturnInt(0); } - //SCLogDebug("DetectEngineInspectCIP %d", cipserviced->cipservice); + // SCLogDebug("DetectEngineInspectCIP %d", cipserviced->cipservice); - if (CIPServiceMatch(tx, cipserviced) == 1) - { - //SCLogDebug("DetectCIPServiceMatchAL found"); + if (CIPServiceMatch(tx, cipserviced) == 1) { + // SCLogDebug("DetectCIPServiceMatchAL found"); SCReturnInt(1); } @@ -267,19 +241,17 @@ uint8_t DetectEngineInspectENIP(DetectEngineCtx *de_ctx, DetectEngineThreadCtx * { SCEnter(); - ENIPTransaction *tx = (ENIPTransaction *) txv; + ENIPTransaction *tx = (ENIPTransaction *)txv; DetectEnipCommandData *enipcmdd = (DetectEnipCommandData *)engine->smd->ctx; - if (enipcmdd == NULL) - { + if (enipcmdd == NULL) { SCLogDebug("no enipcommand state, no match"); SCReturnInt(0); } - //SCLogDebug("DetectEngineInspectENIP %d, %d", enipcmdd->enipcommand, tx->header.command); + // SCLogDebug("DetectEngineInspectENIP %d, %d", enipcmdd->enipcommand, tx->header.command); - if (enipcmdd->enipcommand == tx->header.command) - { + if (enipcmdd->enipcommand == tx->header.command) { // SCLogDebug("DetectENIPCommandMatchAL found!"); SCReturnInt(1); } diff --git a/src/detect-engine-event.c b/src/detect-engine-event.c index 5bbd5711259f..84d7afadd69d 100644 --- a/src/detect-engine-event.c +++ b/src/detect-engine-event.c @@ -36,7 +36,6 @@ #include "stream-tcp.h" - /* Need to get the DEvents[] array */ #include "detect-engine-event.h" @@ -46,12 +45,12 @@ static DetectParseRegex parse_regex; -static int DetectEngineEventMatch (DetectEngineThreadCtx *, - Packet *, const Signature *, const SigMatchCtx *); -static int DetectEngineEventSetup (DetectEngineCtx *, Signature *, const char *); -static int DetectDecodeEventSetup (DetectEngineCtx *, Signature *, const char *); -static int DetectStreamEventSetup (DetectEngineCtx *, Signature *, const char *); -static void DetectEngineEventFree (DetectEngineCtx *, void *); +static int DetectEngineEventMatch( + DetectEngineThreadCtx *, Packet *, const Signature *, const SigMatchCtx *); +static int DetectEngineEventSetup(DetectEngineCtx *, Signature *, const char *); +static int DetectDecodeEventSetup(DetectEngineCtx *, Signature *, const char *); +static int DetectStreamEventSetup(DetectEngineCtx *, Signature *, const char *); +static void DetectEngineEventFree(DetectEngineCtx *, void *); #ifdef UNITTESTS void EngineEventRegisterTests(void); #endif @@ -59,12 +58,12 @@ void EngineEventRegisterTests(void); /** * \brief Registration function for decode-event: keyword */ -void DetectEngineEventRegister (void) +void DetectEngineEventRegister(void) { sigmatch_table[DETECT_ENGINE_EVENT].name = "engine-event"; sigmatch_table[DETECT_ENGINE_EVENT].Match = DetectEngineEventMatch; sigmatch_table[DETECT_ENGINE_EVENT].Setup = DetectEngineEventSetup; - sigmatch_table[DETECT_ENGINE_EVENT].Free = DetectEngineEventFree; + sigmatch_table[DETECT_ENGINE_EVENT].Free = DetectEngineEventFree; #ifdef UNITTESTS sigmatch_table[DETECT_ENGINE_EVENT].RegisterTests = EngineEventRegisterTests; #endif @@ -72,19 +71,20 @@ void DetectEngineEventRegister (void) sigmatch_table[DETECT_DECODE_EVENT].name = "decode-event"; sigmatch_table[DETECT_DECODE_EVENT].Match = DetectEngineEventMatch; sigmatch_table[DETECT_DECODE_EVENT].Setup = DetectDecodeEventSetup; - sigmatch_table[DETECT_DECODE_EVENT].Free = DetectEngineEventFree; + sigmatch_table[DETECT_DECODE_EVENT].Free = DetectEngineEventFree; sigmatch_table[DETECT_DECODE_EVENT].flags |= SIGMATCH_DEONLY_COMPAT; sigmatch_table[DETECT_STREAM_EVENT].name = "stream-event"; sigmatch_table[DETECT_STREAM_EVENT].Match = DetectEngineEventMatch; sigmatch_table[DETECT_STREAM_EVENT].Setup = DetectStreamEventSetup; - sigmatch_table[DETECT_STREAM_EVENT].Free = DetectEngineEventFree; + sigmatch_table[DETECT_STREAM_EVENT].Free = DetectEngineEventFree; DetectSetupParseRegexes(PARSE_REGEX, &parse_regex); } /** - * \brief This function is used to match decoder event flags set on a packet with those passed via decode-event: + * \brief This function is used to match decoder event flags set on a packet with those passed via + * decode-event: * * \param t pointer to thread vars * \param det_ctx pointer to the pattern matcher thread @@ -95,8 +95,8 @@ void DetectEngineEventRegister (void) * \retval 0 no match * \retval 1 match */ -static int DetectEngineEventMatch (DetectEngineThreadCtx *det_ctx, - Packet *p, const Signature *s, const SigMatchCtx *ctx) +static int DetectEngineEventMatch( + DetectEngineThreadCtx *det_ctx, Packet *p, const Signature *s, const SigMatchCtx *ctx) { SCEnter(); @@ -126,7 +126,7 @@ static bool OutdatedEvent(const char *raw) * \retval de pointer to DetectFlowData on success * \retval NULL on failure */ -static DetectEngineEventData *DetectEngineEventParse (const char *rawstr) +static DetectEngineEventData *DetectEngineEventParse(const char *rawstr) { int i; DetectEngineEventData *de = NULL; @@ -150,7 +150,7 @@ static DetectEngineEventData *DetectEngineEventParse (const char *rawstr) } for (i = 0; DEvents[i].event_name != NULL; i++) { - if (strcasecmp(DEvents[i].event_name,copy_str) == 0) { + if (strcasecmp(DEvents[i].event_name, copy_str) == 0) { found = 1; break; } @@ -219,10 +219,9 @@ static int DetectEngineEventSetupDo( return 0; } - -static int DetectEngineEventSetup (DetectEngineCtx *de_ctx, Signature *s, const char *rawstr) +static int DetectEngineEventSetup(DetectEngineCtx *de_ctx, Signature *s, const char *rawstr) { - return DetectEngineEventSetupDo (de_ctx, s, rawstr, DETECT_ENGINE_EVENT); + return DetectEngineEventSetupDo(de_ctx, s, rawstr, DETECT_ENGINE_EVENT); } /** @@ -237,12 +236,11 @@ static void DetectEngineEventFree(DetectEngineCtx *de_ctx, void *ptr) SCFree(de); } - /** * \brief this function Setup the 'decode-event' keyword by setting the correct * signature type -*/ -static int DetectDecodeEventSetup (DetectEngineCtx *de_ctx, Signature *s, const char *rawstr) + */ +static int DetectDecodeEventSetup(DetectEngineCtx *de_ctx, Signature *s, const char *rawstr) { char drawstr[64] = "decoder."; @@ -254,8 +252,8 @@ static int DetectDecodeEventSetup (DetectEngineCtx *de_ctx, Signature *s, const /** * \brief this function Setup the 'stream-event' keyword by resolving the alias -*/ -static int DetectStreamEventSetup (DetectEngineCtx *de_ctx, Signature *s, const char *rawstr) + */ +static int DetectStreamEventSetup(DetectEngineCtx *de_ctx, Signature *s, const char *rawstr) { char srawstr[64] = "stream."; @@ -279,7 +277,7 @@ static int DetectStreamEventSetup (DetectEngineCtx *de_ctx, Signature *s, const /** * \test EngineEventTestParse01 is a test for a valid decode-event value */ -static int EngineEventTestParse01 (void) +static int EngineEventTestParse01(void) { DetectEngineEventData *de = DetectEngineEventParse("decoder.ipv4.pkt_too_small"); @@ -290,11 +288,10 @@ static int EngineEventTestParse01 (void) PASS; } - /** * \test EngineEventTestParse02 is a test for a valid upper + lower case decode-event value */ -static int EngineEventTestParse02 (void) +static int EngineEventTestParse02(void) { DetectEngineEventData *de = DetectEngineEventParse("decoder.PPP.pkt_too_small"); @@ -308,7 +305,7 @@ static int EngineEventTestParse02 (void) /** * \test EngineEventTestParse03 is a test for a valid upper case decode-event value */ -static int EngineEventTestParse03 (void) +static int EngineEventTestParse03(void) { DetectEngineEventData *de = DetectEngineEventParse("decoder.IPV6.PKT_TOO_SMALL"); @@ -322,7 +319,7 @@ static int EngineEventTestParse03 (void) /** * \test EngineEventTestParse04 is a test for an invalid upper case decode-event value */ -static int EngineEventTestParse04 (void) +static int EngineEventTestParse04(void) { DetectEngineEventData *de = DetectEngineEventParse("decoder.IPV6.INVALID_EVENT"); @@ -336,7 +333,7 @@ static int EngineEventTestParse04 (void) /** * \test EngineEventTestParse05 is a test for an invalid char into the decode-event value */ -static int EngineEventTestParse05 (void) +static int EngineEventTestParse05(void) { DetectEngineEventData *de = DetectEngineEventParse("decoder.IPV-6,INVALID_CHAR"); @@ -350,7 +347,7 @@ static int EngineEventTestParse05 (void) /** * \test EngineEventTestParse06 is a test for match function with valid decode-event value */ -static int EngineEventTestParse06 (void) +static int EngineEventTestParse06(void) { Packet *p = PacketGetFromAlloc(); FAIL_IF_NULL(p); @@ -359,7 +356,7 @@ static int EngineEventTestParse06 (void) memset(&tv, 0, sizeof(ThreadVars)); - ENGINE_SET_EVENT(p,PPP_PKT_TOO_SMALL); + ENGINE_SET_EVENT(p, PPP_PKT_TOO_SMALL); DetectEngineEventData *de = DetectEngineEventParse("decoder.ppp.pkt_too_small"); FAIL_IF_NULL(de); diff --git a/src/detect-engine-event.h b/src/detect-engine-event.h index 178af0472ffb..e8c4e7ef36b5 100644 --- a/src/detect-engine-event.h +++ b/src/detect-engine-event.h @@ -24,13 +24,11 @@ #ifndef __DETECT_ENGINE_EVENT_H__ #define __DETECT_ENGINE_EVENT_H__ - typedef struct DetectEngineEventData_ { uint8_t event; } DetectEngineEventData; /* prototypes */ -void DetectEngineEventRegister (void); +void DetectEngineEventRegister(void); #endif /*__DETECT_ENGINE_EVENT_H__ */ - diff --git a/src/detect-engine-file.c b/src/detect-engine-file.c index e7fd9e0c4ad7..e84cc154407c 100644 --- a/src/detect-engine-file.c +++ b/src/detect-engine-file.c @@ -186,7 +186,7 @@ uint8_t DetectFileInspectGeneric(DetectEngineCtx *de_ctx, DetectEngineThreadCtx SCEnter(); DEBUG_VALIDATE_BUG_ON(f->alstate != alstate); - const uint8_t direction = flags & (STREAM_TOSERVER|STREAM_TOCLIENT); + const uint8_t direction = flags & (STREAM_TOSERVER | STREAM_TOCLIENT); AppLayerGetFileState files = AppLayerParserGetTxFiles(f, alstate, tx, direction); FileContainer *ffc = files.fc; SCLogDebug("tx %p tx_id %" PRIu64 " ffc %p ffc->head %p sid %u", tx, tx_id, ffc, diff --git a/src/detect-engine-iponly.c b/src/detect-engine-iponly.c index 63261ee716d5..4eed8f052334 100644 --- a/src/detect-engine-iponly.c +++ b/src/detect-engine-iponly.c @@ -81,21 +81,19 @@ static IPOnlyCIDRItem *IPOnlyCIDRItemNew(void) SCReturnPtr(item, "IPOnlyCIDRItem"); } -static uint8_t IPOnlyCIDRItemCompare(IPOnlyCIDRItem *head, - IPOnlyCIDRItem *item) +static uint8_t IPOnlyCIDRItemCompare(IPOnlyCIDRItem *head, IPOnlyCIDRItem *item) { uint8_t i = 0; for (; i < head->netmask / 32 || i < 1; i++) { if (item->ip[i] < head->ip[i]) - //if (*(uint8_t *)(item->ip + i) < *(uint8_t *)(head->ip + i)) + // if (*(uint8_t *)(item->ip + i) < *(uint8_t *)(head->ip + i)) return 1; } return 0; } -//declaration for using it already -static IPOnlyCIDRItem *IPOnlyCIDRItemInsert(IPOnlyCIDRItem *head, - IPOnlyCIDRItem *item); +// declaration for using it already +static IPOnlyCIDRItem *IPOnlyCIDRItemInsert(IPOnlyCIDRItem *head, IPOnlyCIDRItem *item); static int InsertRange( IPOnlyCIDRItem **pdd, IPOnlyCIDRItem *dd, const uint32_t first_in, const uint32_t last_in) @@ -189,7 +187,7 @@ static int IPOnlyCIDRItemParseSingle(IPOnlyCIDRItem **pdd, const char *str) /* handle the negation case */ if (ip[0] == '!') { - dd->negated = (dd->negated)? 0 : 1; + dd->negated = (dd->negated) ? 0 : 1; ip++; } @@ -207,11 +205,11 @@ static int IPOnlyCIDRItemParseSingle(IPOnlyCIDRItem **pdd, const char *str) uint32_t netmask = 0; size_t u = 0; - if ((strchr (mask, '.')) == NULL) { + if ((strchr(mask, '.')) == NULL) { /* 1.2.3.4/24 format */ for (u = 0; u < strlen(mask); u++) { - if(!isdigit((unsigned char)mask[u])) + if (!isdigit((unsigned char)mask[u])) goto error; } @@ -280,7 +278,7 @@ static int IPOnlyCIDRItemParseSingle(IPOnlyCIDRItem **pdd, const char *str) dd->family = AF_INET6; - if ((mask = strchr(ip, '/')) != NULL) { + if ((mask = strchr(ip, '/')) != NULL) { mask[0] = '\0'; mask++; @@ -289,8 +287,7 @@ static int IPOnlyCIDRItemParseSingle(IPOnlyCIDRItem **pdd, const char *str) goto error; /* Format is cidr val */ - if (StringParseU8RangeCheck(&dd->netmask, 10, 0, - (const char *)mask, 0, 128) < 0) { + if (StringParseU8RangeCheck(&dd->netmask, 10, 0, (const char *)mask, 0, 128) < 0) { goto error; } @@ -310,7 +307,6 @@ static int IPOnlyCIDRItemParseSingle(IPOnlyCIDRItem **pdd, const char *str) memcpy(dd->ip, &in6.s6_addr, sizeof(dd->ip)); dd->netmask = 128; } - } BUG_ON(dd->family == 0); @@ -348,7 +344,6 @@ static int IPOnlyCIDRItemSetup(IPOnlyCIDRItem **gh, char *s) return -1; } - /** * \brief This function insert a IPOnlyCIDRItem * to a list of IPOnlyCIDRItems sorted by netmask @@ -358,8 +353,7 @@ static int IPOnlyCIDRItemSetup(IPOnlyCIDRItem **gh, char *s) * * \retval IPOnlyCIDRItem address of the new head if apply */ -static IPOnlyCIDRItem *IPOnlyCIDRItemInsertReal(IPOnlyCIDRItem *head, - IPOnlyCIDRItem *item) +static IPOnlyCIDRItem *IPOnlyCIDRItemInsertReal(IPOnlyCIDRItem *head, IPOnlyCIDRItem *item) { IPOnlyCIDRItem *it, *prev = NULL; @@ -367,7 +361,8 @@ static IPOnlyCIDRItem *IPOnlyCIDRItemInsertReal(IPOnlyCIDRItem *head, return head; /* Compare with the head */ - if (item->netmask < head->netmask || (item->netmask == head->netmask && IPOnlyCIDRItemCompare(head, item))) { + if (item->netmask < head->netmask || + (item->netmask == head->netmask && IPOnlyCIDRItemCompare(head, item))) { item->next = head; return item; } @@ -378,9 +373,7 @@ static IPOnlyCIDRItem *IPOnlyCIDRItemInsertReal(IPOnlyCIDRItem *head, return head; } - for (prev = it = head; - it != NULL && it->netmask < item->netmask; - it = it->next) + for (prev = it = head; it != NULL && it->netmask < item->netmask; it = it->next) prev = it; if (it == NULL) { @@ -403,14 +396,13 @@ static IPOnlyCIDRItem *IPOnlyCIDRItemInsertReal(IPOnlyCIDRItem *head, * * \retval IPOnlyCIDRItem address of the new head if apply */ -static IPOnlyCIDRItem *IPOnlyCIDRItemInsert(IPOnlyCIDRItem *head, - IPOnlyCIDRItem *item) +static IPOnlyCIDRItem *IPOnlyCIDRItemInsert(IPOnlyCIDRItem *head, IPOnlyCIDRItem *item) { IPOnlyCIDRItem *it, *prev = NULL; /* The first element */ if (head == NULL) { - SCLogDebug("Head is NULL to insert item (%p)",item); + SCLogDebug("Head is NULL to insert item (%p)", item); return item; } @@ -428,11 +420,11 @@ static IPOnlyCIDRItem *IPOnlyCIDRItemInsert(IPOnlyCIDRItem *head, /* Separate from the item list */ prev->next = NULL; - //SCLogDebug("Before:"); - //IPOnlyCIDRListPrint(head); + // SCLogDebug("Before:"); + // IPOnlyCIDRListPrint(head); head = IPOnlyCIDRItemInsertReal(head, prev); - //SCLogDebug("After:"); - //IPOnlyCIDRListPrint(head); + // SCLogDebug("After:"); + // IPOnlyCIDRListPrint(head); prev = it; } @@ -462,7 +454,7 @@ void IPOnlyCIDRListFree(IPOnlyCIDRItem *tmphead) while (it != NULL) { #ifdef DEBUG i++; - SCLogDebug("Item(%p) %"PRIu32" removed", it, i); + SCLogDebug("Item(%p) %" PRIu32 " removed", it, i); #endif SCFree(it); it = next; @@ -500,11 +492,10 @@ static void IPOnlyCIDRListPrint(IPOnlyCIDRItem *tmphead) while (tmphead != NULL) { i++; - SCLogDebug("Item %"PRIu32" has netmask %"PRIu8" negated:" - " %s; IP: %s; signum: %"PRIu32, i, tmphead->netmask, - (tmphead->negated) ? "yes":"no", - inet_ntoa(*(struct in_addr*)&tmphead->ip[0]), - tmphead->signum); + SCLogDebug("Item %" PRIu32 " has netmask %" PRIu8 " negated:" + " %s; IP: %s; signum: %" PRIu32, + i, tmphead->netmask, (tmphead->negated) ? "yes" : "no", + inet_ntoa(*(struct in_addr *)&tmphead->ip[0]), tmphead->signum); tmphead = tmphead->next; } #endif @@ -546,8 +537,7 @@ static void SigNumArrayPrint(void *tmp) * * \retval SigNumArray address of the new instance */ -static SigNumArray *SigNumArrayNew(DetectEngineCtx *de_ctx, - DetectEngineIPOnlyCtx *io_ctx) +static SigNumArray *SigNumArrayNew(DetectEngineCtx *de_ctx, DetectEngineIPOnlyCtx *io_ctx) { SigNumArray *new = SCCalloc(1, sizeof(SigNumArray)); @@ -557,7 +547,7 @@ static SigNumArray *SigNumArrayNew(DetectEngineCtx *de_ctx, new->array = SCCalloc(1, io_ctx->max_idx / 8 + 1); if (new->array == NULL) { - exit(EXIT_FAILURE); + exit(EXIT_FAILURE); } new->size = io_ctx->max_idx / 8 + 1; @@ -656,8 +646,7 @@ static IPOnlyCIDRItem *IPOnlyCIDRListParse2( address[x - 1] = '\0'; x = 0; - if ( (subhead = IPOnlyCIDRListParse2(de_ctx, address, - (negate + n_set) % 2)) == NULL) + if ((subhead = IPOnlyCIDRListParse2(de_ctx, address, (negate + n_set) % 2)) == NULL) goto error; head = IPOnlyCIDRItemInsert(head, subhead); @@ -670,8 +659,8 @@ static IPOnlyCIDRItem *IPOnlyCIDRListParse2( } else if (d_set == 1) { address[x - 1] = '\0'; - rule_var_address = SCRuleVarsGetConfVar(de_ctx, address, - SC_RULE_VARS_ADDRESS_GROUPS); + rule_var_address = + SCRuleVarsGetConfVar(de_ctx, address, SC_RULE_VARS_ADDRESS_GROUPS); if (rule_var_address == NULL) goto error; @@ -681,8 +670,8 @@ static IPOnlyCIDRItem *IPOnlyCIDRListParse2( goto error; } - snprintf(temp_rule_var_address, strlen(rule_var_address) + 3, - "[%s]", rule_var_address); + snprintf(temp_rule_var_address, strlen(rule_var_address) + 3, "[%s]", + rule_var_address); } else { temp_rule_var_address = SCStrdup(rule_var_address); if (unlikely(temp_rule_var_address == NULL)) { @@ -690,8 +679,7 @@ static IPOnlyCIDRItem *IPOnlyCIDRListParse2( } } - subhead = IPOnlyCIDRListParse2(de_ctx, temp_rule_var_address, - (negate + n_set) % 2); + subhead = IPOnlyCIDRListParse2(de_ctx, temp_rule_var_address, (negate + n_set) % 2); head = IPOnlyCIDRItemInsert(head, subhead); d_set = 0; @@ -732,8 +720,8 @@ static IPOnlyCIDRItem *IPOnlyCIDRListParse2( x = 0; if (d_set == 1) { - rule_var_address = SCRuleVarsGetConfVar(de_ctx, address, - SC_RULE_VARS_ADDRESS_GROUPS); + rule_var_address = + SCRuleVarsGetConfVar(de_ctx, address, SC_RULE_VARS_ADDRESS_GROUPS); if (rule_var_address == NULL) goto error; @@ -742,16 +730,15 @@ static IPOnlyCIDRItem *IPOnlyCIDRListParse2( if (unlikely(temp_rule_var_address == NULL)) { goto error; } - snprintf(temp_rule_var_address, strlen(rule_var_address) + 3, - "[%s]", rule_var_address); + snprintf(temp_rule_var_address, strlen(rule_var_address) + 3, "[%s]", + rule_var_address); } else { temp_rule_var_address = SCStrdup(rule_var_address); if (unlikely(temp_rule_var_address == NULL)) { goto error; } } - subhead = IPOnlyCIDRListParse2(de_ctx, temp_rule_var_address, - (negate + n_set) % 2); + subhead = IPOnlyCIDRListParse2(de_ctx, temp_rule_var_address, (negate + n_set) % 2); head = IPOnlyCIDRItemInsert(head, subhead); d_set = 0; @@ -785,7 +772,6 @@ static IPOnlyCIDRItem *IPOnlyCIDRListParse2( return head; } - /** * \brief Parses an address group sent as a character string and updates the * IPOnlyCIDRItem list @@ -828,8 +814,8 @@ static int IPOnlyCIDRListParse(const DetectEngineCtx *de_ctx, IPOnlyCIDRItem **g * \retval 0 On success. * \retval -1 On failure. */ -int IPOnlySigParseAddress(const DetectEngineCtx *de_ctx, - Signature *s, const char *addrstr, char flag) +int IPOnlySigParseAddress( + const DetectEngineCtx *de_ctx, Signature *s, const char *addrstr, char flag) { SCLogDebug("Address Group \"%s\" to be parsed now", addrstr); @@ -937,10 +923,8 @@ void IPOnlyDeinit(DetectEngineCtx *de_ctx, DetectEngineIPOnlyCtx *io_ctx) io_ctx->sig_mapping = NULL; } -static inline -int IPOnlyMatchCompatSMs(ThreadVars *tv, - DetectEngineThreadCtx *det_ctx, - Signature *s, Packet *p) +static inline int IPOnlyMatchCompatSMs( + ThreadVars *tv, DetectEngineThreadCtx *det_ctx, Signature *s, Packet *p) { KEYWORD_PROFILING_SET_LIST(det_ctx, DETECT_SM_LIST_MATCH); SigMatchData *smd = s->sm_arrays[DETECT_SM_LIST_MATCH]; @@ -980,19 +964,19 @@ void IPOnlyMatchPacket(ThreadVars *tv, const DetectEngineCtx *de_ctx, SCEnter(); if (p->src.family == AF_INET) { - (void)SCRadixFindKeyIPV4BestMatch((uint8_t *)&GET_IPV4_SRC_ADDR_U32(p), - io_ctx->tree_ipv4src, &user_data_src); + (void)SCRadixFindKeyIPV4BestMatch( + (uint8_t *)&GET_IPV4_SRC_ADDR_U32(p), io_ctx->tree_ipv4src, &user_data_src); } else if (p->src.family == AF_INET6) { - (void)SCRadixFindKeyIPV6BestMatch((uint8_t *)&GET_IPV6_SRC_ADDR(p), - io_ctx->tree_ipv6src, &user_data_src); + (void)SCRadixFindKeyIPV6BestMatch( + (uint8_t *)&GET_IPV6_SRC_ADDR(p), io_ctx->tree_ipv6src, &user_data_src); } if (p->dst.family == AF_INET) { - (void)SCRadixFindKeyIPV4BestMatch((uint8_t *)&GET_IPV4_DST_ADDR_U32(p), - io_ctx->tree_ipv4dst, &user_data_dst); + (void)SCRadixFindKeyIPV4BestMatch( + (uint8_t *)&GET_IPV4_DST_ADDR_U32(p), io_ctx->tree_ipv4dst, &user_data_dst); } else if (p->dst.family == AF_INET6) { - (void)SCRadixFindKeyIPV6BestMatch((uint8_t *)&GET_IPV6_DST_ADDR(p), - io_ctx->tree_ipv6dst, &user_data_dst); + (void)SCRadixFindKeyIPV6BestMatch( + (uint8_t *)&GET_IPV6_DST_ADDR(p), io_ctx->tree_ipv6dst, &user_data_dst); } src = user_data_src; @@ -1003,7 +987,7 @@ void IPOnlyMatchPacket(ThreadVars *tv, const DetectEngineCtx *de_ctx, uint32_t u; for (u = 0; u < src->size; u++) { - SCLogDebug("And %"PRIu8" & %"PRIu8, src->array[u], dst->array[u]); + SCLogDebug("And %" PRIu8 " & %" PRIu8, src->array[u], dst->array[u]); uint8_t bitarray = dst->array[u] & src->array[u]; @@ -1014,7 +998,7 @@ void IPOnlyMatchPacket(ThreadVars *tv, const DetectEngineCtx *de_ctx, /* We have a match :) Let's see from which signum's */ uint8_t i = 0; - for (; i < 8; i++, bitarray = bitarray >> 1) { + for (; i<8; i++, bitarray = bitarray>> 1) { if (bitarray & 0x01) { Signature *s = de_ctx->sig_array[io_ctx->sig_mapping[u * 8 + i]]; @@ -1033,12 +1017,13 @@ void IPOnlyMatchPacket(ThreadVars *tv, const DetectEngineCtx *de_ctx, } /* check the source & dst port in the sig */ - if (p->proto == IPPROTO_TCP || p->proto == IPPROTO_UDP || p->proto == IPPROTO_SCTP) { + if (p->proto == IPPROTO_TCP || p->proto == IPPROTO_UDP || + p->proto == IPPROTO_SCTP) { if (!(s->flags & SIG_FLAG_DP_ANY)) { if (p->flags & PKT_IS_FRAGMENT) continue; - DetectPort *dport = DetectPortLookupGroup(s->dp,p->dp); + DetectPort *dport = DetectPortLookupGroup(s->dp, p->dp); if (dport == NULL) { SCLogDebug("dport didn't match."); continue; @@ -1048,13 +1033,14 @@ void IPOnlyMatchPacket(ThreadVars *tv, const DetectEngineCtx *de_ctx, if (p->flags & PKT_IS_FRAGMENT) continue; - DetectPort *sport = DetectPortLookupGroup(s->sp,p->sp); + DetectPort *sport = DetectPortLookupGroup(s->sp, p->sp); if (sport == NULL) { SCLogDebug("sport didn't match."); continue; } } - } else if ((s->flags & (SIG_FLAG_DP_ANY|SIG_FLAG_SP_ANY)) != (SIG_FLAG_DP_ANY|SIG_FLAG_SP_ANY)) { + } else if ((s->flags & (SIG_FLAG_DP_ANY | SIG_FLAG_SP_ANY)) != + (SIG_FLAG_DP_ANY | SIG_FLAG_SP_ANY)) { SCLogDebug("port-less protocol and sig needs ports"); continue; } @@ -1063,8 +1049,8 @@ void IPOnlyMatchPacket(ThreadVars *tv, const DetectEngineCtx *de_ctx, continue; } - SCLogDebug("Signum %"PRIu32" match (sid: %"PRIu32", msg: %s)", - u * 8 + i, s->id, s->msg); + SCLogDebug("Signum %" PRIu32 " match (sid: %" PRIu32 ", msg: %s)", u * 8 + i, + s->id, s->msg); if (s->sm_arrays[DETECT_SM_LIST_POSTMATCH] != NULL) { KEYWORD_PROFILING_SET_LIST(det_ctx, DETECT_SM_LIST_POSTMATCH); @@ -1112,34 +1098,31 @@ void IPOnlyPrepare(DetectEngineCtx *de_ctx) SCRadixNode *node = NULL; /* Prepare Src radix trees */ - for (src = (de_ctx->io_ctx).ip_src; src != NULL; ) { + for (src = (de_ctx->io_ctx).ip_src; src != NULL;) { if (src->family == AF_INET) { - /* - SCLogDebug("To IPv4"); - SCLogDebug("Item has netmask %"PRIu16" negated: %s; IP: %s; " - "signum: %"PRIu16, src->netmask, - (src->negated) ? "yes":"no", - inet_ntoa( *(struct in_addr*)&src->ip[0]), - src->signum); - */ + /* + SCLogDebug("To IPv4"); + SCLogDebug("Item has netmask %"PRIu16" negated: %s; IP: %s; " + "signum: %"PRIu16, src->netmask, + (src->negated) ? "yes":"no", + inet_ntoa( *(struct in_addr*)&src->ip[0]), + src->signum); + */ void *user_data = NULL; if (src->netmask == 32) - (void)SCRadixFindKeyIPV4ExactMatch((uint8_t *)&src->ip[0], - (de_ctx->io_ctx).tree_ipv4src, - &user_data); + (void)SCRadixFindKeyIPV4ExactMatch( + (uint8_t *)&src->ip[0], (de_ctx->io_ctx).tree_ipv4src, &user_data); else (void)SCRadixFindKeyIPV4Netblock((uint8_t *)&src->ip[0], - (de_ctx->io_ctx).tree_ipv4src, - src->netmask, &user_data); + (de_ctx->io_ctx).tree_ipv4src, src->netmask, &user_data); if (user_data == NULL) { SCLogDebug("Exact match not found"); /** Not found, look if there's a subnet of this range with * bigger netmask */ - (void)SCRadixFindKeyIPV4BestMatch((uint8_t *)&src->ip[0], - (de_ctx->io_ctx).tree_ipv4src, - &user_data); + (void)SCRadixFindKeyIPV4BestMatch( + (uint8_t *)&src->ip[0], (de_ctx->io_ctx).tree_ipv4src, &user_data); if (user_data == NULL) { SCLogDebug("best match not found"); @@ -1157,12 +1140,11 @@ void IPOnlyPrepare(DetectEngineCtx *de_ctx) sna->array[src->signum / 8] |= tmp; if (src->netmask == 32) - node = SCRadixAddKeyIPV4((uint8_t *)&src->ip[0], - (de_ctx->io_ctx).tree_ipv4src, sna); + node = SCRadixAddKeyIPV4( + (uint8_t *)&src->ip[0], (de_ctx->io_ctx).tree_ipv4src, sna); else node = SCRadixAddKeyIPV4Netblock((uint8_t *)&src->ip[0], - (de_ctx->io_ctx).tree_ipv4src, - sna, src->netmask); + (de_ctx->io_ctx).tree_ipv4src, sna, src->netmask); if (node == NULL) SCLogError("Error inserting in the " @@ -1172,7 +1154,7 @@ void IPOnlyPrepare(DetectEngineCtx *de_ctx) /* Found, copy the sig num table, add this signum and insert */ SigNumArray *sna = NULL; - sna = SigNumArrayCopy((SigNumArray *) user_data); + sna = SigNumArrayCopy((SigNumArray *)user_data); /* Update the sig */ uint8_t tmp = (uint8_t)(1 << (src->signum % 8)); @@ -1185,12 +1167,11 @@ void IPOnlyPrepare(DetectEngineCtx *de_ctx) sna->array[src->signum / 8] |= tmp; if (src->netmask == 32) - node = SCRadixAddKeyIPV4((uint8_t *)&src->ip[0], - (de_ctx->io_ctx).tree_ipv4src, sna); + node = SCRadixAddKeyIPV4( + (uint8_t *)&src->ip[0], (de_ctx->io_ctx).tree_ipv4src, sna); else node = SCRadixAddKeyIPV4Netblock((uint8_t *)&src->ip[0], - (de_ctx->io_ctx).tree_ipv4src, sna, - src->netmask); + (de_ctx->io_ctx).tree_ipv4src, sna, src->netmask); if (node == NULL) { char tmpstr[64]; @@ -1198,7 +1179,7 @@ void IPOnlyPrepare(DetectEngineCtx *de_ctx) SCLogError("Error inserting in the" " src ipv4 radix tree ip %s netmask %" PRIu8, tmpstr, src->netmask); - //SCRadixPrintTree((de_ctx->io_ctx).tree_ipv4src); + // SCRadixPrintTree((de_ctx->io_ctx).tree_ipv4src); exit(-1); } } @@ -1223,19 +1204,16 @@ void IPOnlyPrepare(DetectEngineCtx *de_ctx) void *user_data = NULL; if (src->netmask == 128) - (void)SCRadixFindKeyIPV6ExactMatch((uint8_t *)&src->ip[0], - (de_ctx->io_ctx).tree_ipv6src, - &user_data); + (void)SCRadixFindKeyIPV6ExactMatch( + (uint8_t *)&src->ip[0], (de_ctx->io_ctx).tree_ipv6src, &user_data); else (void)SCRadixFindKeyIPV6Netblock((uint8_t *)&src->ip[0], - (de_ctx->io_ctx).tree_ipv6src, - src->netmask, &user_data); + (de_ctx->io_ctx).tree_ipv6src, src->netmask, &user_data); if (user_data == NULL) { /* Not found, look if there's a subnet of this range with bigger netmask */ - (void)SCRadixFindKeyIPV6BestMatch((uint8_t *)&src->ip[0], - (de_ctx->io_ctx).tree_ipv6src, - &user_data); + (void)SCRadixFindKeyIPV6BestMatch( + (uint8_t *)&src->ip[0], (de_ctx->io_ctx).tree_ipv6src, &user_data); if (user_data == NULL) { /* Not found, insert a new one */ @@ -1252,12 +1230,11 @@ void IPOnlyPrepare(DetectEngineCtx *de_ctx) sna->array[src->signum / 8] |= tmp; if (src->netmask == 128) - node = SCRadixAddKeyIPV6((uint8_t *)&src->ip[0], - (de_ctx->io_ctx).tree_ipv6src, sna); + node = SCRadixAddKeyIPV6( + (uint8_t *)&src->ip[0], (de_ctx->io_ctx).tree_ipv6src, sna); else node = SCRadixAddKeyIPV6Netblock((uint8_t *)&src->ip[0], - (de_ctx->io_ctx).tree_ipv6src, - sna, src->netmask); + (de_ctx->io_ctx).tree_ipv6src, sna, src->netmask); if (node == NULL) SCLogError("Error inserting in the src " "ipv6 radix tree"); @@ -1276,12 +1253,11 @@ void IPOnlyPrepare(DetectEngineCtx *de_ctx) sna->array[src->signum / 8] |= tmp; if (src->netmask == 128) - node = SCRadixAddKeyIPV6((uint8_t *)&src->ip[0], - (de_ctx->io_ctx).tree_ipv6src, sna); + node = SCRadixAddKeyIPV6( + (uint8_t *)&src->ip[0], (de_ctx->io_ctx).tree_ipv6src, sna); else node = SCRadixAddKeyIPV6Netblock((uint8_t *)&src->ip[0], - (de_ctx->io_ctx).tree_ipv6src, - sna, src->netmask); + (de_ctx->io_ctx).tree_ipv6src, sna, src->netmask); if (node == NULL) SCLogError("Error inserting in the src " "ipv6 radix tree"); @@ -1308,24 +1284,22 @@ void IPOnlyPrepare(DetectEngineCtx *de_ctx) SCLogDebug("dsts:"); /* Prepare Dst radix trees */ - for (dst = (de_ctx->io_ctx).ip_dst; dst != NULL; ) { + for (dst = (de_ctx->io_ctx).ip_dst; dst != NULL;) { if (dst->family == AF_INET) { SCLogDebug("To IPv4"); - SCLogDebug("Item has netmask %"PRIu8" negated: %s; IP: %s; signum:" - " %"PRIu32"", dst->netmask, (dst->negated)?"yes":"no", - inet_ntoa(*(struct in_addr*)&dst->ip[0]), dst->signum); + SCLogDebug("Item has netmask %" PRIu8 " negated: %s; IP: %s; signum:" + " %" PRIu32 "", + dst->netmask, (dst->negated) ? "yes" : "no", + inet_ntoa(*(struct in_addr *)&dst->ip[0]), dst->signum); void *user_data = NULL; if (dst->netmask == 32) - (void) SCRadixFindKeyIPV4ExactMatch((uint8_t *) &dst->ip[0], - (de_ctx->io_ctx).tree_ipv4dst, - &user_data); + (void)SCRadixFindKeyIPV4ExactMatch( + (uint8_t *)&dst->ip[0], (de_ctx->io_ctx).tree_ipv4dst, &user_data); else - (void) SCRadixFindKeyIPV4Netblock((uint8_t *) &dst->ip[0], - (de_ctx->io_ctx).tree_ipv4dst, - dst->netmask, - &user_data); + (void)SCRadixFindKeyIPV4Netblock((uint8_t *)&dst->ip[0], + (de_ctx->io_ctx).tree_ipv4dst, dst->netmask, &user_data); if (user_data == NULL) { SCLogDebug("Exact match not found"); @@ -1334,9 +1308,8 @@ void IPOnlyPrepare(DetectEngineCtx *de_ctx) * Not found, look if there's a subnet of this range * with bigger netmask */ - (void) SCRadixFindKeyIPV4BestMatch((uint8_t *)&dst->ip[0], - (de_ctx->io_ctx).tree_ipv4dst, - &user_data); + (void)SCRadixFindKeyIPV4BestMatch( + (uint8_t *)&dst->ip[0], (de_ctx->io_ctx).tree_ipv4dst, &user_data); if (user_data == NULL) { SCLogDebug("Best match not found"); @@ -1353,12 +1326,11 @@ void IPOnlyPrepare(DetectEngineCtx *de_ctx) sna->array[dst->signum / 8] |= tmp; if (dst->netmask == 32) - node = SCRadixAddKeyIPV4((uint8_t *)&dst->ip[0], - (de_ctx->io_ctx).tree_ipv4dst, sna); + node = SCRadixAddKeyIPV4( + (uint8_t *)&dst->ip[0], (de_ctx->io_ctx).tree_ipv4dst, sna); else node = SCRadixAddKeyIPV4Netblock((uint8_t *)&dst->ip[0], - (de_ctx->io_ctx).tree_ipv4dst, - sna, dst->netmask); + (de_ctx->io_ctx).tree_ipv4dst, sna, dst->netmask); if (node == NULL) SCLogError("Error inserting in the dst " @@ -1368,7 +1340,7 @@ void IPOnlyPrepare(DetectEngineCtx *de_ctx) /* Found, copy the sig num table, add this signum and insert */ SigNumArray *sna = NULL; - sna = SigNumArrayCopy((SigNumArray *) user_data); + sna = SigNumArrayCopy((SigNumArray *)user_data); /* Update the sig */ uint8_t tmp = (uint8_t)(1 << (dst->signum % 8)); @@ -1380,12 +1352,11 @@ void IPOnlyPrepare(DetectEngineCtx *de_ctx) sna->array[dst->signum / 8] |= tmp; if (dst->netmask == 32) - node = SCRadixAddKeyIPV4((uint8_t *)&dst->ip[0], - (de_ctx->io_ctx).tree_ipv4dst, sna); + node = SCRadixAddKeyIPV4( + (uint8_t *)&dst->ip[0], (de_ctx->io_ctx).tree_ipv4dst, sna); else node = SCRadixAddKeyIPV4Netblock((uint8_t *)&dst->ip[0], - (de_ctx->io_ctx).tree_ipv4dst, - sna, dst->netmask); + (de_ctx->io_ctx).tree_ipv4dst, sna, dst->netmask); if (node == NULL) SCLogError("Error inserting in the dst " @@ -1411,21 +1382,18 @@ void IPOnlyPrepare(DetectEngineCtx *de_ctx) void *user_data = NULL; if (dst->netmask == 128) - (void) SCRadixFindKeyIPV6ExactMatch((uint8_t *)&dst->ip[0], - (de_ctx->io_ctx).tree_ipv6dst, - &user_data); + (void)SCRadixFindKeyIPV6ExactMatch( + (uint8_t *)&dst->ip[0], (de_ctx->io_ctx).tree_ipv6dst, &user_data); else - (void) SCRadixFindKeyIPV6Netblock((uint8_t *)&dst->ip[0], - (de_ctx->io_ctx).tree_ipv6dst, - dst->netmask, &user_data); + (void)SCRadixFindKeyIPV6Netblock((uint8_t *)&dst->ip[0], + (de_ctx->io_ctx).tree_ipv6dst, dst->netmask, &user_data); if (user_data == NULL) { /** Not found, look if there's a subnet of this range with * bigger netmask */ - (void) SCRadixFindKeyIPV6BestMatch((uint8_t *)&dst->ip[0], - (de_ctx->io_ctx).tree_ipv6dst, - &user_data); + (void)SCRadixFindKeyIPV6BestMatch( + (uint8_t *)&dst->ip[0], (de_ctx->io_ctx).tree_ipv6dst, &user_data); if (user_data == NULL) { /* Not found, insert a new one */ @@ -1441,12 +1409,11 @@ void IPOnlyPrepare(DetectEngineCtx *de_ctx) sna->array[dst->signum / 8] |= tmp; if (dst->netmask == 128) - node = SCRadixAddKeyIPV6((uint8_t *)&dst->ip[0], - (de_ctx->io_ctx).tree_ipv6dst, sna); + node = SCRadixAddKeyIPV6( + (uint8_t *)&dst->ip[0], (de_ctx->io_ctx).tree_ipv6dst, sna); else node = SCRadixAddKeyIPV6Netblock((uint8_t *)&dst->ip[0], - (de_ctx->io_ctx).tree_ipv6dst, - sna, dst->netmask); + (de_ctx->io_ctx).tree_ipv6dst, sna, dst->netmask); if (node == NULL) SCLogError("Error inserting in the dst " @@ -1466,12 +1433,11 @@ void IPOnlyPrepare(DetectEngineCtx *de_ctx) sna->array[dst->signum / 8] |= tmp; if (dst->netmask == 128) - node = SCRadixAddKeyIPV6((uint8_t *)&dst->ip[0], - (de_ctx->io_ctx).tree_ipv6dst, sna); + node = SCRadixAddKeyIPV6( + (uint8_t *)&dst->ip[0], (de_ctx->io_ctx).tree_ipv6dst, sna); else node = SCRadixAddKeyIPV6Netblock((uint8_t *)&dst->ip[0], - (de_ctx->io_ctx).tree_ipv6dst, - sna, dst->netmask); + (de_ctx->io_ctx).tree_ipv6dst, sna, dst->netmask); if (node == NULL) SCLogError("Error inserting in the dst " @@ -1519,8 +1485,7 @@ void IPOnlyPrepare(DetectEngineCtx *de_ctx) * \param de_ctx Pointer to the current ip only detection engine contest * \param s Pointer to the current signature */ -void IPOnlyAddSignature(DetectEngineCtx *de_ctx, DetectEngineIPOnlyCtx *io_ctx, - Signature *s) +void IPOnlyAddSignature(DetectEngineCtx *de_ctx, DetectEngineIPOnlyCtx *io_ctx, Signature *s) { if (!(s->type == SIG_TYPE_IPONLY)) return; @@ -1560,7 +1525,7 @@ static int IPOnlyTestSig01(void) FAIL_IF(de_ctx == NULL); de_ctx->flags |= DE_QUIET; - Signature *s = SigInit(de_ctx,"alert tcp any any -> any any (sid:400001; rev:1;)"); + Signature *s = SigInit(de_ctx, "alert tcp any any -> any any (sid:400001; rev:1;)"); FAIL_IF(s == NULL); FAIL_IF(SignatureIsIPOnly(de_ctx, s) == 0); @@ -1574,13 +1539,13 @@ static int IPOnlyTestSig01(void) * option appending a SigMatch but a port is fixed */ -static int IPOnlyTestSig02 (void) +static int IPOnlyTestSig02(void) { DetectEngineCtx *de_ctx = DetectEngineCtxInit(); FAIL_IF(de_ctx == NULL); de_ctx->flags |= DE_QUIET; - Signature *s = SigInit(de_ctx,"alert tcp any any -> any 80 (sid:400001; rev:1;)"); + Signature *s = SigInit(de_ctx, "alert tcp any any -> any 80 (sid:400001; rev:1;)"); FAIL_IF(s == NULL); FAIL_IF(SignatureIsIPOnly(de_ctx, s) == 0); @@ -1594,11 +1559,11 @@ static int IPOnlyTestSig02 (void) * because it has rule options appending a SigMatch like content, and pcre */ -static int IPOnlyTestSig03 (void) +static int IPOnlyTestSig03(void) { int result = 1; DetectEngineCtx *de_ctx; - Signature *s=NULL; + Signature *s = NULL; de_ctx = DetectEngineCtxInit(); if (de_ctx == NULL) @@ -1606,110 +1571,117 @@ static int IPOnlyTestSig03 (void) de_ctx->flags |= DE_QUIET; /* combination of pcre and content */ - s = SigInit(de_ctx,"alert tcp any any -> any any (msg:\"SigTest40-03 sig is not IPOnly (pcre and content) \"; content:\"php\"; pcre:\"/require(_once)?/i\"; classtype:misc-activity; sid:400001; rev:1;)"); + s = SigInit(de_ctx, "alert tcp any any -> any any (msg:\"SigTest40-03 sig is not IPOnly (pcre " + "and content) \"; content:\"php\"; pcre:\"/require(_once)?/i\"; " + "classtype:misc-activity; sid:400001; rev:1;)"); if (s == NULL) { goto end; } - if(SignatureIsIPOnly(de_ctx, s)) - { + if (SignatureIsIPOnly(de_ctx, s)) { printf("got a IPOnly signature (content): "); - result=0; + result = 0; } SigFree(de_ctx, s); /* content */ - s = SigInit(de_ctx,"alert tcp any any -> any any (msg:\"SigTest40-03 sig is not IPOnly (content) \"; content:\"match something\"; classtype:misc-activity; sid:400001; rev:1;)"); + s = SigInit(de_ctx, + "alert tcp any any -> any any (msg:\"SigTest40-03 sig is not IPOnly (content) \"; " + "content:\"match something\"; classtype:misc-activity; sid:400001; rev:1;)"); if (s == NULL) { goto end; } - if(SignatureIsIPOnly(de_ctx, s)) - { + if (SignatureIsIPOnly(de_ctx, s)) { printf("got a IPOnly signature (content): "); - result=0; + result = 0; } SigFree(de_ctx, s); /* uricontent */ - s = SigInit(de_ctx,"alert tcp any any -> any any (msg:\"SigTest40-03 sig is not IPOnly (uricontent) \"; uricontent:\"match something\"; classtype:misc-activity; sid:400001; rev:1;)"); + s = SigInit(de_ctx, + "alert tcp any any -> any any (msg:\"SigTest40-03 sig is not IPOnly (uricontent) \"; " + "uricontent:\"match something\"; classtype:misc-activity; sid:400001; rev:1;)"); if (s == NULL) { goto end; } - if(SignatureIsIPOnly(de_ctx, s)) - { + if (SignatureIsIPOnly(de_ctx, s)) { printf("got a IPOnly signature (uricontent): "); - result=0; + result = 0; } SigFree(de_ctx, s); /* pcre */ - s = SigInit(de_ctx,"alert tcp any any -> any any (msg:\"SigTest40-03 sig is not IPOnly (pcre) \"; pcre:\"/e?idps rule[sz]/i\"; classtype:misc-activity; sid:400001; rev:1;)"); + s = SigInit( + de_ctx, "alert tcp any any -> any any (msg:\"SigTest40-03 sig is not IPOnly (pcre) \"; " + "pcre:\"/e?idps rule[sz]/i\"; classtype:misc-activity; sid:400001; rev:1;)"); if (s == NULL) { goto end; } - if(SignatureIsIPOnly(de_ctx, s)) - { + if (SignatureIsIPOnly(de_ctx, s)) { printf("got a IPOnly signature (pcre): "); - result=0; + result = 0; } SigFree(de_ctx, s); /* flow */ - s = SigInit(de_ctx,"alert tcp any any -> any any (msg:\"SigTest40-03 sig is not IPOnly (flow) \"; flow:to_server; classtype:misc-activity; sid:400001; rev:1;)"); + s = SigInit(de_ctx, "alert tcp any any -> any any (msg:\"SigTest40-03 sig is not IPOnly (flow) " + "\"; flow:to_server; classtype:misc-activity; sid:400001; rev:1;)"); if (s == NULL) { goto end; } - if(SignatureIsIPOnly(de_ctx, s)) - { + if (SignatureIsIPOnly(de_ctx, s)) { printf("got a IPOnly signature (flow): "); - result=0; + result = 0; } SigFree(de_ctx, s); /* dsize */ - s = SigInit(de_ctx,"alert tcp any any -> any any (msg:\"SigTest40-03 sig is not IPOnly (dsize) \"; dsize:100; classtype:misc-activity; sid:400001; rev:1;)"); + s = SigInit(de_ctx, "alert tcp any any -> any any (msg:\"SigTest40-03 sig is not IPOnly " + "(dsize) \"; dsize:100; classtype:misc-activity; sid:400001; rev:1;)"); if (s == NULL) { goto end; } - if(SignatureIsIPOnly(de_ctx, s)) - { + if (SignatureIsIPOnly(de_ctx, s)) { printf("got a IPOnly signature (dsize): "); - result=0; + result = 0; } SigFree(de_ctx, s); /* flowbits */ - s = SigInit(de_ctx,"alert tcp any any -> any any (msg:\"SigTest40-03 sig is not IPOnly (flowbits) \"; flowbits:unset; classtype:misc-activity; sid:400001; rev:1;)"); + s = SigInit( + de_ctx, "alert tcp any any -> any any (msg:\"SigTest40-03 sig is not IPOnly (flowbits) " + "\"; flowbits:unset; classtype:misc-activity; sid:400001; rev:1;)"); if (s == NULL) { goto end; } - if(SignatureIsIPOnly(de_ctx, s)) - { + if (SignatureIsIPOnly(de_ctx, s)) { printf("got a IPOnly signature (flowbits): "); - result=0; + result = 0; } SigFree(de_ctx, s); /* flowvar */ - s = SigInit(de_ctx,"alert tcp any any -> any any (msg:\"SigTest40-03 sig is not IPOnly (flowvar) \"; pcre:\"/(?.*)/i\"; flowvar:var,\"str\"; classtype:misc-activity; sid:400001; rev:1;)"); + s = SigInit(de_ctx, "alert tcp any any -> any any (msg:\"SigTest40-03 sig is not IPOnly " + "(flowvar) \"; pcre:\"/(?.*)/i\"; flowvar:var,\"str\"; " + "classtype:misc-activity; sid:400001; rev:1;)"); if (s == NULL) { goto end; } - if(SignatureIsIPOnly(de_ctx, s)) - { + if (SignatureIsIPOnly(de_ctx, s)) { printf("got a IPOnly signature (flowvar): "); - result=0; + result = 0; } SigFree(de_ctx, s); /* pktvar */ - s = SigInit(de_ctx,"alert tcp any any -> any any (msg:\"SigTest40-03 sig is not IPOnly (pktvar) \"; pcre:\"/(?.*)/i\"; pktvar:var,\"str\"; classtype:misc-activity; sid:400001; rev:1;)"); + s = SigInit(de_ctx, "alert tcp any any -> any any (msg:\"SigTest40-03 sig is not IPOnly " + "(pktvar) \"; pcre:\"/(?.*)/i\"; pktvar:var,\"str\"; " + "classtype:misc-activity; sid:400001; rev:1;)"); if (s == NULL) { goto end; } - if(SignatureIsIPOnly(de_ctx, s)) - { + if (SignatureIsIPOnly(de_ctx, s)) { printf("got a IPOnly signature (pktvar): "); - result=0; + result = 0; } SigFree(de_ctx, s); @@ -1722,7 +1694,7 @@ static int IPOnlyTestSig03 (void) /** * \test */ -static int IPOnlyTestSig04 (void) +static int IPOnlyTestSig04(void) { int result = 1; @@ -1730,27 +1702,27 @@ static int IPOnlyTestSig04 (void) IPOnlyCIDRItem *new; new = IPOnlyCIDRItemNew(); - new->netmask= 10; + new->netmask = 10; head = IPOnlyCIDRItemInsert(head, new); new = IPOnlyCIDRItemNew(); - new->netmask= 11; + new->netmask = 11; head = IPOnlyCIDRItemInsert(head, new); new = IPOnlyCIDRItemNew(); - new->netmask= 9; + new->netmask = 9; head = IPOnlyCIDRItemInsert(head, new); new = IPOnlyCIDRItemNew(); - new->netmask= 10; + new->netmask = 10; head = IPOnlyCIDRItemInsert(head, new); new = IPOnlyCIDRItemNew(); - new->netmask= 10; + new->netmask = 10; head = IPOnlyCIDRItemInsert(head, new); @@ -1804,19 +1776,24 @@ static int IPOnlyTestSig05(void) p[0] = UTHBuildPacket((uint8_t *)buf, buflen, IPPROTO_TCP); const char *sigs[numsigs]; - sigs[0]= "alert tcp 192.168.1.5 any -> any any (msg:\"Testing src ip (sid 1)\"; sid:1;)"; - sigs[1]= "alert tcp any any -> 192.168.1.1 any (msg:\"Testing dst ip (sid 2)\"; sid:2;)"; - sigs[2]= "alert tcp 192.168.1.5 any -> 192.168.1.1 any (msg:\"Testing src/dst ip (sid 3)\"; sid:3;)"; - sigs[3]= "alert tcp 192.168.1.5 any -> 192.168.1.1 any (msg:\"Testing src/dst ip (sid 4)\"; sid:4;)"; - sigs[4]= "alert tcp 192.168.1.0/24 any -> any any (msg:\"Testing src/dst ip (sid 5)\"; sid:5;)"; - sigs[5]= "alert tcp any any -> 192.168.0.0/16 any (msg:\"Testing src/dst ip (sid 6)\"; sid:6;)"; - sigs[6]= "alert tcp 192.168.1.0/24 any -> 192.168.0.0/16 any (msg:\"Testing src/dst ip (sid 7)\"; content:\"Hi all\";sid:7;)"; + sigs[0] = "alert tcp 192.168.1.5 any -> any any (msg:\"Testing src ip (sid 1)\"; sid:1;)"; + sigs[1] = "alert tcp any any -> 192.168.1.1 any (msg:\"Testing dst ip (sid 2)\"; sid:2;)"; + sigs[2] = "alert tcp 192.168.1.5 any -> 192.168.1.1 any (msg:\"Testing src/dst ip (sid 3)\"; " + "sid:3;)"; + sigs[3] = "alert tcp 192.168.1.5 any -> 192.168.1.1 any (msg:\"Testing src/dst ip (sid 4)\"; " + "sid:4;)"; + sigs[4] = + "alert tcp 192.168.1.0/24 any -> any any (msg:\"Testing src/dst ip (sid 5)\"; sid:5;)"; + sigs[5] = + "alert tcp any any -> 192.168.0.0/16 any (msg:\"Testing src/dst ip (sid 6)\"; sid:6;)"; + sigs[6] = "alert tcp 192.168.1.0/24 any -> 192.168.0.0/16 any (msg:\"Testing src/dst ip (sid " + "7)\"; content:\"Hi all\";sid:7;)"; /* Sid numbers (we could extract them from the sig) */ - uint32_t sid[7] = { 1, 2, 3, 4, 5, 6, 7}; - uint32_t results[7] = { 1, 1, 1, 1, 1, 1, 1}; + uint32_t sid[7] = { 1, 2, 3, 4, 5, 6, 7 }; + uint32_t results[7] = { 1, 1, 1, 1, 1, 1, 1 }; - result = UTHGenericTest(p, numpkts, sigs, sid, (uint32_t *) results, numsigs); + result = UTHGenericTest(p, numpkts, sigs, sid, (uint32_t *)results, numsigs); UTHFreePackets(p, numpkts); @@ -1841,19 +1818,24 @@ static int IPOnlyTestSig06(void) p[0] = UTHBuildPacketSrcDst((uint8_t *)buf, buflen, IPPROTO_TCP, "80.58.0.33", "195.235.113.3"); const char *sigs[numsigs]; - sigs[0]= "alert tcp 192.168.1.5 any -> any any (msg:\"Testing src ip (sid 1)\"; sid:1;)"; - sigs[1]= "alert tcp any any -> 192.168.1.1 any (msg:\"Testing dst ip (sid 2)\"; sid:2;)"; - sigs[2]= "alert tcp 192.168.1.5 any -> 192.168.1.1 any (msg:\"Testing src/dst ip (sid 3)\"; sid:3;)"; - sigs[3]= "alert tcp 192.168.1.5 any -> 192.168.1.1 any (msg:\"Testing src/dst ip (sid 4)\"; sid:4;)"; - sigs[4]= "alert tcp 192.168.1.0/24 any -> any any (msg:\"Testing src/dst ip (sid 5)\"; sid:5;)"; - sigs[5]= "alert tcp any any -> 192.168.0.0/16 any (msg:\"Testing src/dst ip (sid 6)\"; sid:6;)"; - sigs[6]= "alert tcp 192.168.1.0/24 any -> 192.168.0.0/16 any (msg:\"Testing src/dst ip (sid 7)\"; content:\"Hi all\";sid:7;)"; + sigs[0] = "alert tcp 192.168.1.5 any -> any any (msg:\"Testing src ip (sid 1)\"; sid:1;)"; + sigs[1] = "alert tcp any any -> 192.168.1.1 any (msg:\"Testing dst ip (sid 2)\"; sid:2;)"; + sigs[2] = "alert tcp 192.168.1.5 any -> 192.168.1.1 any (msg:\"Testing src/dst ip (sid 3)\"; " + "sid:3;)"; + sigs[3] = "alert tcp 192.168.1.5 any -> 192.168.1.1 any (msg:\"Testing src/dst ip (sid 4)\"; " + "sid:4;)"; + sigs[4] = + "alert tcp 192.168.1.0/24 any -> any any (msg:\"Testing src/dst ip (sid 5)\"; sid:5;)"; + sigs[5] = + "alert tcp any any -> 192.168.0.0/16 any (msg:\"Testing src/dst ip (sid 6)\"; sid:6;)"; + sigs[6] = "alert tcp 192.168.1.0/24 any -> 192.168.0.0/16 any (msg:\"Testing src/dst ip (sid " + "7)\"; content:\"Hi all\";sid:7;)"; /* Sid numbers (we could extract them from the sig) */ - uint32_t sid[7] = { 1, 2, 3, 4, 5, 6, 7}; - uint32_t results[7] = { 0, 0, 0, 0, 0, 0, 0}; + uint32_t sid[7] = { 1, 2, 3, 4, 5, 6, 7 }; + uint32_t results[7] = { 0, 0, 0, 0, 0, 0, 0 }; - result = UTHGenericTest(p, numpkts, sigs, sid, (uint32_t *) results, numsigs); + result = UTHGenericTest(p, numpkts, sigs, sid, (uint32_t *)results, numsigs); UTHFreePackets(p, numpkts); @@ -1917,22 +1899,34 @@ static int IPOnlyTestSig08(void) Packet *p[1]; - p[0] = UTHBuildPacketSrcDst((uint8_t *)buf, buflen, IPPROTO_TCP,"192.168.1.1","192.168.1.5"); + p[0] = UTHBuildPacketSrcDst((uint8_t *)buf, buflen, IPPROTO_TCP, "192.168.1.1", "192.168.1.5"); const char *sigs[numsigs]; - sigs[0]= "alert tcp 192.168.1.5 any -> 192.168.0.0/16 any (msg:\"Testing src/dst ip (sid 1)\"; sid:1;)"; - sigs[1]= "alert tcp [192.168.1.2,192.168.1.5,192.168.1.4] any -> 192.168.1.1 any (msg:\"Testing src/dst ip (sid 2)\"; sid:2;)"; - sigs[2]= "alert tcp [192.168.1.0/24,!192.168.1.1] any -> 192.168.1.1 any (msg:\"Testing src/dst ip (sid 3)\"; sid:3;)"; - sigs[3]= "alert tcp [192.0.0.0/8,!192.168.0.0/16,192.168.1.0/24,!192.168.1.1] any -> [192.168.1.0/24,!192.168.1.5] any (msg:\"Testing src/dst ip (sid 4)\"; sid:4;)"; - sigs[4]= "alert tcp any any -> !192.168.1.5 any (msg:\"Testing src/dst ip (sid 5)\"; sid:5;)"; - sigs[5]= "alert tcp any any -> [192.168.0.0/16,!192.168.1.0/24,192.168.1.1] any (msg:\"Testing src/dst ip (sid 6)\"; sid:6;)"; - sigs[6]= "alert tcp [78.129.202.0/24,192.168.1.5,78.129.205.64,78.129.214.103,78.129.223.19,78.129.233.17,78.137.168.33,78.140.132.11,78.140.133.15,78.140.138.105,78.140.139.105,78.140.141.107,78.140.141.114,78.140.143.103,78.140.143.13,78.140.145.144,78.140.170.164,78.140.23.18,78.143.16.7,78.143.46.124,78.157.129.71] any -> 192.168.1.1 any (msg:\"ET RBN Known Russian Business Network IP TCP - BLOCKING (246)\"; sid:7;)"; /* real sid:"2407490" */ + sigs[0] = "alert tcp 192.168.1.5 any -> 192.168.0.0/16 any (msg:\"Testing src/dst ip (sid " + "1)\"; sid:1;)"; + sigs[1] = "alert tcp [192.168.1.2,192.168.1.5,192.168.1.4] any -> 192.168.1.1 any " + "(msg:\"Testing src/dst ip (sid 2)\"; sid:2;)"; + sigs[2] = "alert tcp [192.168.1.0/24,!192.168.1.1] any -> 192.168.1.1 any (msg:\"Testing " + "src/dst ip (sid 3)\"; sid:3;)"; + sigs[3] = "alert tcp [192.0.0.0/8,!192.168.0.0/16,192.168.1.0/24,!192.168.1.1] any -> " + "[192.168.1.0/24,!192.168.1.5] any (msg:\"Testing src/dst ip (sid 4)\"; sid:4;)"; + sigs[4] = "alert tcp any any -> !192.168.1.5 any (msg:\"Testing src/dst ip (sid 5)\"; sid:5;)"; + sigs[5] = "alert tcp any any -> [192.168.0.0/16,!192.168.1.0/24,192.168.1.1] any " + "(msg:\"Testing src/dst ip (sid 6)\"; sid:6;)"; + sigs[6] = + "alert tcp " + "[78.129.202.0/" + "24,192.168.1.5,78.129.205.64,78.129.214.103,78.129.223.19,78.129.233.17,78.137.168.33," + "78.140.132.11,78.140.133.15,78.140.138.105,78.140.139.105,78.140.141.107,78.140.141." + "114,78.140.143.103,78.140.143.13,78.140.145.144,78.140.170.164,78.140.23.18,78.143.16." + "7,78.143.46.124,78.157.129.71] any -> 192.168.1.1 any (msg:\"ET RBN Known Russian " + "Business Network IP TCP - BLOCKING (246)\"; sid:7;)"; /* real sid:"2407490" */ /* Sid numbers (we could extract them from the sig) */ - uint32_t sid[7] = { 1, 2, 3, 4, 5, 6, 7}; - uint32_t results[7] = { 0, 0, 0, 0, 0, 0, 0}; + uint32_t sid[7] = { 1, 2, 3, 4, 5, 6, 7 }; + uint32_t results[7] = { 0, 0, 0, 0, 0, 0, 0 }; - result = UTHGenericTest(p, numpkts, sigs, sid, (uint32_t *) results, numsigs); + result = UTHGenericTest(p, numpkts, sigs, sid, (uint32_t *)results, numsigs); UTHFreePackets(p, numpkts); @@ -1954,22 +1948,32 @@ static int IPOnlyTestSig09(void) Packet *p[1]; - p[0] = UTHBuildPacketIPV6SrcDst((uint8_t *)buf, buflen, IPPROTO_TCP, "3FFE:FFFF:7654:FEDA:1245:BA98:3210:4565", "3FFE:FFFF:7654:FEDA:1245:BA98:3210:4562"); + p[0] = UTHBuildPacketIPV6SrcDst((uint8_t *)buf, buflen, IPPROTO_TCP, + "3FFE:FFFF:7654:FEDA:1245:BA98:3210:4565", "3FFE:FFFF:7654:FEDA:1245:BA98:3210:4562"); const char *sigs[numsigs]; - sigs[0]= "alert tcp 3FFE:FFFF:7654:FEDA:1245:BA98:3210:4565 any -> any any (msg:\"Testing src ip (sid 1)\"; sid:1;)"; - sigs[1]= "alert tcp any any -> 3FFE:FFFF:7654:FEDA:1245:BA98:3210:4562 any (msg:\"Testing dst ip (sid 2)\"; sid:2;)"; - sigs[2]= "alert tcp 3FFE:FFFF:7654:FEDA:1245:BA98:3210:4565 any -> 3FFE:FFFF:7654:FEDA:1245:BA98:3210:4562 any (msg:\"Testing src/dst ip (sid 3)\"; sid:3;)"; - sigs[3]= "alert tcp 3FFE:FFFF:7654:FEDA:1245:BA98:3210:4565 any -> 3FFE:FFFF:7654:FEDA:1245:BA98:3210:0/96 any (msg:\"Testing src/dst ip (sid 4)\"; sid:4;)"; - sigs[4]= "alert tcp 3FFE:FFFF:7654:FEDA:0:0:0:0/64 any -> any any (msg:\"Testing src/dst ip (sid 5)\"; sid:5;)"; - sigs[5]= "alert tcp any any -> 3FFE:FFFF:7654:FEDA:0:0:0:0/64 any (msg:\"Testing src/dst ip (sid 6)\"; sid:6;)"; - sigs[6]= "alert tcp 3FFE:FFFF:7654:FEDA:0:0:0:0/64 any -> 3FFE:FFFF:7654:FEDA:0:0:0:0/64 any (msg:\"Testing src/dst ip (sid 7)\"; content:\"Hi all\";sid:7;)"; + sigs[0] = "alert tcp 3FFE:FFFF:7654:FEDA:1245:BA98:3210:4565 any -> any any (msg:\"Testing src " + "ip (sid 1)\"; sid:1;)"; + sigs[1] = "alert tcp any any -> 3FFE:FFFF:7654:FEDA:1245:BA98:3210:4562 any (msg:\"Testing dst " + "ip (sid 2)\"; sid:2;)"; + sigs[2] = "alert tcp 3FFE:FFFF:7654:FEDA:1245:BA98:3210:4565 any -> " + "3FFE:FFFF:7654:FEDA:1245:BA98:3210:4562 any (msg:\"Testing src/dst ip (sid 3)\"; " + "sid:3;)"; + sigs[3] = "alert tcp 3FFE:FFFF:7654:FEDA:1245:BA98:3210:4565 any -> " + "3FFE:FFFF:7654:FEDA:1245:BA98:3210:0/96 any (msg:\"Testing src/dst ip (sid 4)\"; " + "sid:4;)"; + sigs[4] = "alert tcp 3FFE:FFFF:7654:FEDA:0:0:0:0/64 any -> any any (msg:\"Testing src/dst ip " + "(sid 5)\"; sid:5;)"; + sigs[5] = "alert tcp any any -> 3FFE:FFFF:7654:FEDA:0:0:0:0/64 any (msg:\"Testing src/dst ip " + "(sid 6)\"; sid:6;)"; + sigs[6] = "alert tcp 3FFE:FFFF:7654:FEDA:0:0:0:0/64 any -> 3FFE:FFFF:7654:FEDA:0:0:0:0/64 any " + "(msg:\"Testing src/dst ip (sid 7)\"; content:\"Hi all\";sid:7;)"; /* Sid numbers (we could extract them from the sig) */ - uint32_t sid[7] = { 1, 2, 3, 4, 5, 6, 7}; - uint32_t results[7] = { 1, 1, 1, 1, 1, 1, 1}; + uint32_t sid[7] = { 1, 2, 3, 4, 5, 6, 7 }; + uint32_t results[7] = { 1, 1, 1, 1, 1, 1, 1 }; - result = UTHGenericTest(p, numpkts, sigs, sid, (uint32_t *) results, numsigs); + result = UTHGenericTest(p, numpkts, sigs, sid, (uint32_t *)results, numsigs); UTHFreePackets(p, numpkts); @@ -1991,22 +1995,32 @@ static int IPOnlyTestSig10(void) Packet *p[1]; - p[0] = UTHBuildPacketIPV6SrcDst((uint8_t *)buf, buflen, IPPROTO_TCP, "3FFE:FFFF:7654:FEDA:1245:BA98:3210:4562", "3FFE:FFFF:7654:FEDA:1245:BA98:3210:4565"); + p[0] = UTHBuildPacketIPV6SrcDst((uint8_t *)buf, buflen, IPPROTO_TCP, + "3FFE:FFFF:7654:FEDA:1245:BA98:3210:4562", "3FFE:FFFF:7654:FEDA:1245:BA98:3210:4565"); const char *sigs[numsigs]; - sigs[0]= "alert tcp 3FFE:FFFF:7654:FEDA:1245:BA98:3210:4565 any -> any any (msg:\"Testing src ip (sid 1)\"; sid:1;)"; - sigs[1]= "alert tcp any any -> 3FFE:FFFF:7654:FEDA:1245:BA98:3210:4562 any (msg:\"Testing dst ip (sid 2)\"; sid:2;)"; - sigs[2]= "alert tcp 3FFE:FFFF:7654:FEDA:1245:BA98:3210:4565 any -> 3FFE:FFFF:7654:FEDA:1245:BA98:3210:4562 any (msg:\"Testing src/dst ip (sid 3)\"; sid:3;)"; - sigs[3]= "alert tcp 3FFE:FFFF:7654:FEDA:1245:BA98:3210:4565 any -> !3FFE:FFFF:7654:FEDA:1245:BA98:3210:4562/96 any (msg:\"Testing src/dst ip (sid 4)\"; sid:4;)"; - sigs[4]= "alert tcp !3FFE:FFFF:7654:FEDA:0:0:0:0/64 any -> any any (msg:\"Testing src/dst ip (sid 5)\"; sid:5;)"; - sigs[5]= "alert tcp any any -> !3FFE:FFFF:7654:FEDA:0:0:0:0/64 any (msg:\"Testing src/dst ip (sid 6)\"; sid:6;)"; - sigs[6]= "alert tcp 3FFE:FFFF:7654:FEDA:0:0:0:0/64 any -> 3FFE:FFFF:7654:FEDB:0:0:0:0/64 any (msg:\"Testing src/dst ip (sid 7)\"; content:\"Hi all\";sid:7;)"; + sigs[0] = "alert tcp 3FFE:FFFF:7654:FEDA:1245:BA98:3210:4565 any -> any any (msg:\"Testing src " + "ip (sid 1)\"; sid:1;)"; + sigs[1] = "alert tcp any any -> 3FFE:FFFF:7654:FEDA:1245:BA98:3210:4562 any (msg:\"Testing dst " + "ip (sid 2)\"; sid:2;)"; + sigs[2] = "alert tcp 3FFE:FFFF:7654:FEDA:1245:BA98:3210:4565 any -> " + "3FFE:FFFF:7654:FEDA:1245:BA98:3210:4562 any (msg:\"Testing src/dst ip (sid 3)\"; " + "sid:3;)"; + sigs[3] = "alert tcp 3FFE:FFFF:7654:FEDA:1245:BA98:3210:4565 any -> " + "!3FFE:FFFF:7654:FEDA:1245:BA98:3210:4562/96 any (msg:\"Testing src/dst ip (sid " + "4)\"; sid:4;)"; + sigs[4] = "alert tcp !3FFE:FFFF:7654:FEDA:0:0:0:0/64 any -> any any (msg:\"Testing src/dst ip " + "(sid 5)\"; sid:5;)"; + sigs[5] = "alert tcp any any -> !3FFE:FFFF:7654:FEDA:0:0:0:0/64 any (msg:\"Testing src/dst ip " + "(sid 6)\"; sid:6;)"; + sigs[6] = "alert tcp 3FFE:FFFF:7654:FEDA:0:0:0:0/64 any -> 3FFE:FFFF:7654:FEDB:0:0:0:0/64 any " + "(msg:\"Testing src/dst ip (sid 7)\"; content:\"Hi all\";sid:7;)"; /* Sid numbers (we could extract them from the sig) */ - uint32_t sid[7] = { 1, 2, 3, 4, 5, 6, 7}; - uint32_t results[7] = { 0, 0, 0, 0, 0, 0, 0}; + uint32_t sid[7] = { 1, 2, 3, 4, 5, 6, 7 }; + uint32_t results[7] = { 0, 0, 0, 0, 0, 0, 0 }; - result = UTHGenericTest(p, numpkts, sigs, sid, (uint32_t *) results, numsigs); + result = UTHGenericTest(p, numpkts, sigs, sid, (uint32_t *)results, numsigs); UTHFreePackets(p, numpkts); @@ -2071,23 +2085,51 @@ static int IPOnlyTestSig12(void) Packet *p[2]; - p[0] = UTHBuildPacketIPV6SrcDst((uint8_t *)buf, buflen, IPPROTO_TCP,"3FBE:FFFF:7654:FEDA:1245:BA98:3210:4562","3FBE:FFFF:7654:FEDA:1245:BA98:3210:4565"); - p[1] = UTHBuildPacketSrcDst((uint8_t *)buf, buflen, IPPROTO_TCP,"195.85.1.1","80.198.1.5"); + p[0] = UTHBuildPacketIPV6SrcDst((uint8_t *)buf, buflen, IPPROTO_TCP, + "3FBE:FFFF:7654:FEDA:1245:BA98:3210:4562", "3FBE:FFFF:7654:FEDA:1245:BA98:3210:4565"); + p[1] = UTHBuildPacketSrcDst((uint8_t *)buf, buflen, IPPROTO_TCP, "195.85.1.1", "80.198.1.5"); const char *sigs[numsigs]; - sigs[0]= "alert tcp 3FFE:FFFF:7654:FEDA:1245:BA98:3210:4565,192.168.1.1 any -> 3FFE:FFFF:7654:FEDA:0:0:0:0/64,192.168.1.5 any (msg:\"Testing src/dst ip (sid 1)\"; sid:1;)"; - sigs[1]= "alert tcp [192.168.1.1,3FFE:FFFF:7654:FEDA:1245:BA98:3210:4565,192.168.1.4,192.168.1.5,!192.168.1.0/24] any -> [3FFE:FFFF:7654:FEDA:1245:BA98:3210:4562,192.168.1.0/24] any (msg:\"Testing src/dst ip (sid 2)\"; sid:2;)"; - sigs[2]= "alert tcp [3FFE:FFFF:7654:FEDA:0:0:0:0/64,!3FFE:FFFF:7654:FEDA:1245:BA98:3210:4562,192.168.1.1] any -> [3FFE:FFFF:7654:FEDA:1245:BA98:3210:4562,192.168.1.5] any (msg:\"Testing src/dst ip (sid 3)\"; sid:3;)"; - sigs[3]= "alert tcp [3FFE:FFFF:0:0:0:0:0:0/32,!3FFE:FFFF:7654:FEDA:0:0:0:0/64,3FFE:FFFF:7654:FEDA:0:0:0:0/64,!3FFE:FFFF:7654:FEDA:1245:BA98:3210:4562,192.168.1.1] any -> [3FFE:FFFF:7654:FEDA:0:0:0:0/64,192.168.1.0/24,!3FFE:FFFF:7654:FEDA:1245:BA98:3210:4565] any (msg:\"Testing src/dst ip (sid 4)\"; sid:4;)"; - sigs[4]= "alert tcp any any -> [!3FBE:FFFF:7654:FEDA:1245:BA98:3210:4565,!80.198.1.5] any (msg:\"Testing src/dst ip (sid 5)\"; sid:5;)"; - sigs[5]= "alert tcp any any -> [3FFE:FFFF:7654:FEDA:0:0:0:0/64,!3FFE:FFFF:7654:FEDA:0:0:0:0/64,3FFE:FFFF:7654:FEDA:1245:BA98:3210:4562,192.168.1.5] any (msg:\"Testing src/dst ip (sid 6)\"; sid:6;)"; - sigs[6]= "alert tcp [78.129.202.0/24,3FFE:FFFF:7654:FEDA:1245:BA98:3210:4565,192.168.1.1,78.129.205.64,78.129.214.103,78.129.223.19,78.129.233.17,78.137.168.33,78.140.132.11,78.140.133.15,78.140.138.105,78.140.139.105,78.140.141.107,78.140.141.114,78.140.143.103,78.140.143.13,78.140.145.144,78.140.170.164,78.140.23.18,78.143.16.7,78.143.46.124,78.157.129.71] any -> [3FFE:FFFF:7654:FEDA:1245:BA98:3210:4562,192.0.0.0/8] any (msg:\"ET RBN Known Russian Business Network IP TCP - BLOCKING (246)\"; sid:7;)"; /* real sid:"2407490" */ + sigs[0] = "alert tcp 3FFE:FFFF:7654:FEDA:1245:BA98:3210:4565,192.168.1.1 any -> " + "3FFE:FFFF:7654:FEDA:0:0:0:0/64,192.168.1.5 any (msg:\"Testing src/dst ip (sid 1)\"; " + "sid:1;)"; + sigs[1] = "alert tcp " + "[192.168.1.1,3FFE:FFFF:7654:FEDA:1245:BA98:3210:4565,192.168.1.4,192.168.1.5,!192." + "168.1.0/24] any -> [3FFE:FFFF:7654:FEDA:1245:BA98:3210:4562,192.168.1.0/24] any " + "(msg:\"Testing src/dst ip (sid 2)\"; sid:2;)"; + sigs[2] = + "alert tcp " + "[3FFE:FFFF:7654:FEDA:0:0:0:0/64,!3FFE:FFFF:7654:FEDA:1245:BA98:3210:4562,192.168.1.1] " + "any -> [3FFE:FFFF:7654:FEDA:1245:BA98:3210:4562,192.168.1.5] any (msg:\"Testing " + "src/dst ip (sid 3)\"; sid:3;)"; + sigs[3] = + "alert tcp " + "[3FFE:FFFF:0:0:0:0:0:0/32,!3FFE:FFFF:7654:FEDA:0:0:0:0/64,3FFE:FFFF:7654:FEDA:0:0:0:0/" + "64,!3FFE:FFFF:7654:FEDA:1245:BA98:3210:4562,192.168.1.1] any -> " + "[3FFE:FFFF:7654:FEDA:0:0:0:0/64,192.168.1.0/" + "24,!3FFE:FFFF:7654:FEDA:1245:BA98:3210:4565] any (msg:\"Testing src/dst ip (sid 4)\"; " + "sid:4;)"; + sigs[4] = "alert tcp any any -> [!3FBE:FFFF:7654:FEDA:1245:BA98:3210:4565,!80.198.1.5] any " + "(msg:\"Testing src/dst ip (sid 5)\"; sid:5;)"; + sigs[5] = "alert tcp any any -> " + "[3FFE:FFFF:7654:FEDA:0:0:0:0/64,!3FFE:FFFF:7654:FEDA:0:0:0:0/" + "64,3FFE:FFFF:7654:FEDA:1245:BA98:3210:4562,192.168.1.5] any (msg:\"Testing src/dst " + "ip (sid 6)\"; sid:6;)"; + sigs[6] = + "alert tcp " + "[78.129.202.0/" + "24,3FFE:FFFF:7654:FEDA:1245:BA98:3210:4565,192.168.1.1,78.129.205.64,78.129.214.103," + "78.129.223.19,78.129.233.17,78.137.168.33,78.140.132.11,78.140.133.15,78.140.138.105," + "78.140.139.105,78.140.141.107,78.140.141.114,78.140.143.103,78.140.143.13,78.140.145." + "144,78.140.170.164,78.140.23.18,78.143.16.7,78.143.46.124,78.157.129.71] any -> " + "[3FFE:FFFF:7654:FEDA:1245:BA98:3210:4562,192.0.0.0/8] any (msg:\"ET RBN Known Russian " + "Business Network IP TCP - BLOCKING (246)\"; sid:7;)"; /* real sid:"2407490" */ /* Sid numbers (we could extract them from the sig) */ - uint32_t sid[7] = { 1, 2, 3, 4, 5, 6, 7}; - uint32_t results[2][7] = {{ 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0}}; + uint32_t sid[7] = { 1, 2, 3, 4, 5, 6, 7 }; + uint32_t results[2][7] = { { 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0 } }; - result = UTHGenericTest(p, numpkts, sigs, sid, (uint32_t *) results, numsigs); + result = UTHGenericTest(p, numpkts, sigs, sid, (uint32_t *)results, numsigs); UTHFreePackets(p, numpkts); @@ -2100,9 +2142,8 @@ static int IPOnlyTestSig13(void) FAIL_IF(de_ctx == NULL); de_ctx->flags |= DE_QUIET; - Signature *s = SigInit(de_ctx, - "alert tcp any any -> any any (msg:\"Test flowbits ip only\"; " - "flowbits:set,myflow1; sid:1; rev:1;)"); + Signature *s = SigInit(de_ctx, "alert tcp any any -> any any (msg:\"Test flowbits ip only\"; " + "flowbits:set,myflow1; sid:1; rev:1;)"); FAIL_IF(s == NULL); FAIL_IF(SignatureIsIPOnly(de_ctx, s) == 0); @@ -2117,9 +2158,8 @@ static int IPOnlyTestSig14(void) FAIL_IF(de_ctx == NULL); de_ctx->flags |= DE_QUIET; - Signature *s = SigInit(de_ctx, - "alert tcp any any -> any any (msg:\"Test flowbits ip only\"; " - "flowbits:set,myflow1; flowbits:isset,myflow2; sid:1; rev:1;)"); + Signature *s = SigInit(de_ctx, "alert tcp any any -> any any (msg:\"Test flowbits ip only\"; " + "flowbits:set,myflow1; flowbits:isset,myflow2; sid:1; rev:1;)"); FAIL_IF(s == NULL); FAIL_IF(SignatureIsIPOnly(de_ctx, s) == 1); @@ -2152,26 +2192,27 @@ static int IPOnlyTestSig15(void) p[0]->flowflags |= FLOW_PKT_TOSERVER; const char *sigs[numsigs]; - sigs[0]= "alert tcp 192.168.1.5 any -> any any (msg:\"Testing src ip (sid 1)\"; " - "flowbits:set,one; sid:1;)"; - sigs[1]= "alert tcp any any -> 192.168.1.1 any (msg:\"Testing dst ip (sid 2)\"; " - "flowbits:set,two; sid:2;)"; - sigs[2]= "alert tcp 192.168.1.5 any -> 192.168.1.1 any (msg:\"Testing src/dst ip (sid 3)\"; " - "flowbits:set,three; sid:3;)"; - sigs[3]= "alert tcp 192.168.1.5 any -> 192.168.1.1 any (msg:\"Testing src/dst ip (sid 4)\"; " - "flowbits:set,four; sid:4;)"; - sigs[4]= "alert tcp 192.168.1.0/24 any -> any any (msg:\"Testing src/dst ip (sid 5)\"; " - "flowbits:set,five; sid:5;)"; - sigs[5]= "alert tcp any any -> 192.168.0.0/16 any (msg:\"Testing src/dst ip (sid 6)\"; " - "flowbits:set,six; sid:6;)"; - sigs[6]= "alert tcp 192.168.1.0/24 any -> 192.168.0.0/16 any (msg:\"Testing src/dst ip (sid 7)\"; " - "flowbits:set,seven; content:\"Hi all\"; sid:7;)"; + sigs[0] = "alert tcp 192.168.1.5 any -> any any (msg:\"Testing src ip (sid 1)\"; " + "flowbits:set,one; sid:1;)"; + sigs[1] = "alert tcp any any -> 192.168.1.1 any (msg:\"Testing dst ip (sid 2)\"; " + "flowbits:set,two; sid:2;)"; + sigs[2] = "alert tcp 192.168.1.5 any -> 192.168.1.1 any (msg:\"Testing src/dst ip (sid 3)\"; " + "flowbits:set,three; sid:3;)"; + sigs[3] = "alert tcp 192.168.1.5 any -> 192.168.1.1 any (msg:\"Testing src/dst ip (sid 4)\"; " + "flowbits:set,four; sid:4;)"; + sigs[4] = "alert tcp 192.168.1.0/24 any -> any any (msg:\"Testing src/dst ip (sid 5)\"; " + "flowbits:set,five; sid:5;)"; + sigs[5] = "alert tcp any any -> 192.168.0.0/16 any (msg:\"Testing src/dst ip (sid 6)\"; " + "flowbits:set,six; sid:6;)"; + sigs[6] = "alert tcp 192.168.1.0/24 any -> 192.168.0.0/16 any (msg:\"Testing src/dst ip (sid " + "7)\"; " + "flowbits:set,seven; content:\"Hi all\"; sid:7;)"; /* Sid numbers (we could extract them from the sig) */ - uint32_t sid[7] = { 1, 2, 3, 4, 5, 6, 7}; - uint32_t results[7] = { 1, 1, 1, 1, 1, 1, 1}; + uint32_t sid[7] = { 1, 2, 3, 4, 5, 6, 7 }; + uint32_t results[7] = { 1, 1, 1, 1, 1, 1, 1 }; - result = UTHGenericTest(p, numpkts, sigs, sid, (uint32_t *) results, numsigs); + result = UTHGenericTest(p, numpkts, sigs, sid, (uint32_t *)results, numsigs); UTHFreePackets(p, numpkts); @@ -2196,14 +2237,14 @@ static int IPOnlyTestSig16(void) p[0] = UTHBuildPacketSrcDst((uint8_t *)buf, buflen, IPPROTO_TCP, "100.100.0.0", "50.0.0.0"); const char *sigs[numsigs]; - sigs[0]= "alert tcp !100.100.0.1 any -> any any (msg:\"Testing src ip (sid 1)\"; sid:1;)"; - sigs[1]= "alert tcp any any -> !50.0.0.1 any (msg:\"Testing dst ip (sid 2)\"; sid:2;)"; + sigs[0] = "alert tcp !100.100.0.1 any -> any any (msg:\"Testing src ip (sid 1)\"; sid:1;)"; + sigs[1] = "alert tcp any any -> !50.0.0.1 any (msg:\"Testing dst ip (sid 2)\"; sid:2;)"; /* Sid numbers (we could extract them from the sig) */ - uint32_t sid[2] = { 1, 2}; - uint32_t results[2] = { 1, 1}; + uint32_t sid[2] = { 1, 2 }; + uint32_t results[2] = { 1, 1 }; - result = UTHGenericTest(p, numpkts, sigs, sid, (uint32_t *) results, numsigs); + result = UTHGenericTest(p, numpkts, sigs, sid, (uint32_t *)results, numsigs); UTHFreePackets(p, numpkts); @@ -2227,13 +2268,13 @@ static int IPOnlyTestSig17(void) p[0] = UTHBuildPacketSrcDst((uint8_t *)buf, buflen, IPPROTO_ICMP, "100.100.0.0", "50.0.0.0"); const char *sigs[numsigs]; - sigs[0]= "alert ip 100.100.0.0 80 -> any any (msg:\"Testing src ip (sid 1)\"; sid:1;)"; - sigs[1]= "alert ip any any -> 50.0.0.0 123 (msg:\"Testing dst ip (sid 2)\"; sid:2;)"; + sigs[0] = "alert ip 100.100.0.0 80 -> any any (msg:\"Testing src ip (sid 1)\"; sid:1;)"; + sigs[1] = "alert ip any any -> 50.0.0.0 123 (msg:\"Testing dst ip (sid 2)\"; sid:2;)"; - uint32_t sid[2] = { 1, 2}; - uint32_t results[2] = { 0, 0}; /* neither should match */ + uint32_t sid[2] = { 1, 2 }; + uint32_t results[2] = { 0, 0 }; /* neither should match */ - result = UTHGenericTest(p, numpkts, sigs, sid, (uint32_t *) results, numsigs); + result = UTHGenericTest(p, numpkts, sigs, sid, (uint32_t *)results, numsigs); UTHFreePackets(p, numpkts); @@ -2261,16 +2302,26 @@ static int IPOnlyTestSig18(void) const char *sigs[numsigs]; // really many IP addresses - sigs[0]= "alert ip 1.2.3.4-219.6.7.8 any -> any any (sid:1;)"; - sigs[1]= "alert ip 51.2.3.4-253.1.2.3 any -> any any (sid:2;)"; - sigs[2]= "alert ip 0.0.0.0-50.0.0.2 any -> any any (sid:3;)"; - sigs[3]= "alert ip 50.0.0.0-255.255.255.255 any -> any any (sid:4;)"; - - uint32_t sid[4] = { 1, 2, 3, 4, }; - uint32_t results[4][4] = { - { 1, 0, 1, 0, }, { 0, 1, 0, 1}, { 0, 0, 1, 0 }, { 0, 0, 0, 1}}; - - result = UTHGenericTest(p, numpkts, sigs, sid, (uint32_t *) results, numsigs); + sigs[0] = "alert ip 1.2.3.4-219.6.7.8 any -> any any (sid:1;)"; + sigs[1] = "alert ip 51.2.3.4-253.1.2.3 any -> any any (sid:2;)"; + sigs[2] = "alert ip 0.0.0.0-50.0.0.2 any -> any any (sid:3;)"; + sigs[3] = "alert ip 50.0.0.0-255.255.255.255 any -> any any (sid:4;)"; + + uint32_t sid[4] = { + 1, + 2, + 3, + 4, + }; + uint32_t results[4][4] = { { + 1, + 0, + 1, + 0, + }, + { 0, 1, 0, 1 }, { 0, 0, 1, 0 }, { 0, 0, 0, 1 } }; + + result = UTHGenericTest(p, numpkts, sigs, sid, (uint32_t *)results, numsigs); UTHFreePackets(p, numpkts); @@ -2446,4 +2497,3 @@ void IPOnlyRegisterTests(void) return; } - diff --git a/src/detect-engine-iponly.h b/src/detect-engine-iponly.h index 7fa9e223e743..dbc372587fbb 100644 --- a/src/detect-engine-iponly.h +++ b/src/detect-engine-iponly.h @@ -37,4 +37,3 @@ void IPOnlyAddSignature(DetectEngineCtx *, DetectEngineIPOnlyCtx *, Signature *) void IPOnlyRegisterTests(void); #endif /* __DETECT_ENGINE_IPONLY_H__ */ - diff --git a/src/detect-engine-loader.c b/src/detect-engine-loader.c index 40919568503a..c823493e4085 100644 --- a/src/detect-engine-loader.c +++ b/src/detect-engine-loader.c @@ -74,8 +74,7 @@ char *DetectLoadCompleteSigPath(const DetectEngineCtx *de_ctx, const char *sig_f * a --set. */ ConfNode *default_rule_path = ConfGetNode("default-rule-path"); if ((!default_rule_path || !default_rule_path->final) && strlen(de_ctx->config_prefix) > 0) { - snprintf(varname, sizeof(varname), "%s.default-rule-path", - de_ctx->config_prefix); + snprintf(varname, sizeof(varname), "%s.default-rule-path", de_ctx->config_prefix); default_rule_path = ConfGetNode(varname); } if (default_rule_path) { @@ -109,8 +108,7 @@ char *DetectLoadCompleteSigPath(const DetectEngineCtx *de_ctx, const char *sig_f * \param badsigs_tot Will store number of invalid signatures in the file * \retval 0 on success, -1 on error */ -static int DetectLoadSigFile(DetectEngineCtx *de_ctx, char *sig_file, - int *goodsigs, int *badsigs) +static int DetectLoadSigFile(DetectEngineCtx *de_ctx, char *sig_file, int *goodsigs, int *badsigs) { Signature *sig = NULL; int good = 0, bad = 0; @@ -129,16 +127,18 @@ static int DetectLoadSigFile(DetectEngineCtx *de_ctx, char *sig_file, return -1; } - while(fgets(line + offset, (int)sizeof(line) - offset, fp) != NULL) { + while (fgets(line + offset, (int)sizeof(line) - offset, fp) != NULL) { lineno++; size_t len = strlen(line); /* ignore comments and empty lines */ - if (line[0] == '\n' || line [0] == '\r' || line[0] == ' ' || line[0] == '#' || line[0] == '\t') + if (line[0] == '\n' || line[0] == '\r' || line[0] == ' ' || line[0] == '#' || + line[0] == '\t') continue; /* Check for multiline rules. */ - while (len > 0 && isspace((unsigned char)line[--len])); + while (len > 0 && isspace((unsigned char)line[--len])) + ; if (line[len] == '\\') { multiline++; offset = len; @@ -173,7 +173,7 @@ static int DetectLoadSigFile(DetectEngineCtx *de_ctx, char *sig_file, EngineAnalysisRules(de_ctx, sig, line); } } - SCLogDebug("signature %"PRIu32" loaded", sig->id); + SCLogDebug("signature %" PRIu32 " loaded", sig->id); good++; } else { if (!de_ctx->sigerror_silent) { @@ -181,7 +181,8 @@ static int DetectLoadSigFile(DetectEngineCtx *de_ctx, char *sig_file, "file %s at line %" PRId32 "", line, sig_file, lineno - multiline); - if (!SigStringAppend(&de_ctx->sig_stat, sig_file, line, de_ctx->sigerror, (lineno - multiline))) { + if (!SigStringAppend(&de_ctx->sig_stat, sig_file, line, de_ctx->sigerror, + (lineno - multiline))) { SCLogError("Error adding sig \"%s\" from " "file %s at line %" PRId32 "", line, sig_file, lineno - multiline); @@ -212,8 +213,8 @@ static int DetectLoadSigFile(DetectEngineCtx *de_ctx, char *sig_file, * \param sig_file Filename (or pattern) holding signatures * \retval -1 on error */ -static int ProcessSigFiles(DetectEngineCtx *de_ctx, char *pattern, - SigFileLoaderStat *st, int *good_sigs, int *bad_sigs) +static int ProcessSigFiles(DetectEngineCtx *de_ctx, char *pattern, SigFileLoaderStat *st, + int *good_sigs, int *bad_sigs) { int r = 0; @@ -241,9 +242,9 @@ static int ProcessSigFiles(DetectEngineCtx *de_ctx, char *pattern, if (strcmp("/dev/null", fname) == 0) continue; #else - char *fname = pattern; - if (strcmp("/dev/null", fname) == 0) - return 0; + char *fname = pattern; + if (strcmp("/dev/null", fname) == 0) + return 0; #endif if (strlen(de_ctx->config_prefix) > 0) { SCLogConfig("tenant id %d: Loading rule file: %s", de_ctx->tenant_id, fname); @@ -288,8 +289,7 @@ int SigLoadSignatures(DetectEngineCtx *de_ctx, char *sig_file, bool sig_file_exc int bad_sigs = 0; if (strlen(de_ctx->config_prefix) > 0) { - snprintf(varname, sizeof(varname), "%s.rule-files", - de_ctx->config_prefix); + snprintf(varname, sizeof(varname), "%s.rule-files", de_ctx->config_prefix); } if (RunmodeGetCurrent() == RUNMODE_ENGINE_ANALYSIS) { @@ -303,9 +303,8 @@ int SigLoadSignatures(DetectEngineCtx *de_ctx, char *sig_file, bool sig_file_exc if (!ConfNodeIsSequence(rule_files)) { SCLogWarning("Invalid rule-files configuration section: " "expected a list of filenames."); - } - else { - TAILQ_FOREACH(file, &rule_files->head, next) { + } else { + TAILQ_FOREACH (file, &rule_files->head, next) { sfile = DetectLoadCompleteSigPath(de_ctx, file->val); good_sigs = bad_sigs = 0; ret = ProcessSigFiles(de_ctx, sfile, sig_stat, &good_sigs, &bad_sigs); @@ -382,7 +381,7 @@ int SigLoadSignatures(DetectEngineCtx *de_ctx, char *sig_file, bool sig_file_exc ret = 0; - end: +end: gettimeofday(&de_ctx->last_reload, NULL); if (RunmodeGetCurrent() == RUNMODE_ENGINE_ANALYSIS) { CleanupEngineAnalysis(de_ctx); @@ -501,7 +500,7 @@ static void TmThreadWakeupDetectLoaderThreads(void) for (int i = 0; i < TVT_MAX; i++) { ThreadVars *tv = tv_root[i]; while (tv != NULL) { - if (strncmp(tv->name,"DL#",3) == 0) { + if (strncmp(tv->name, "DL#", 3) == 0) { BUG_ON(tv->ctrl_cond == NULL); pthread_cond_broadcast(tv->ctrl_cond); } @@ -520,7 +519,7 @@ void TmThreadContinueDetectLoaderThreads(void) for (int i = 0; i < TVT_MAX; i++) { ThreadVars *tv = tv_root[i]; while (tv != NULL) { - if (strncmp(tv->name,"DL#",3) == 0) + if (strncmp(tv->name, "DL#", 3) == 0) TmThreadContinue(tv); tv = tv->next; @@ -556,7 +555,6 @@ static TmEcode DetectLoaderThreadDeinit(ThreadVars *t, void *data) return TM_ECODE_OK; } - static TmEcode DetectLoader(ThreadVars *th_v, void *thread_data) { DetectLoaderThreadData *ftd = (DetectLoaderThreadData *)thread_data; @@ -564,8 +562,7 @@ static TmEcode DetectLoader(ThreadVars *th_v, void *thread_data) TmThreadsSetFlag(th_v, THV_INIT_DONE | THV_RUNNING); SCLogDebug("loader thread started"); - while (1) - { + while (1) { if (TmThreadsCheckFlag(th_v, THV_PAUSE)) { TmThreadsSetFlag(th_v, THV_PAUSED); TmThreadTestThreadUnPaused(th_v); @@ -578,7 +575,7 @@ static TmEcode DetectLoader(ThreadVars *th_v, void *thread_data) SCMutexLock(&loader->m); DetectLoaderTask *task = NULL, *tmptask = NULL; - TAILQ_FOREACH_SAFE(task, &loader->task_list, next, tmptask) { + TAILQ_FOREACH_SAFE (task, &loader->task_list, next, tmptask) { int r = task->Func(task->ctx, ftd->instance); loader->result |= r; TAILQ_REMOVE(&loader->task_list, task, next); @@ -612,7 +609,7 @@ void DetectLoaderThreadSpawn(void) { for (int i = 0; i < num_loaders; i++) { char name[TM_THREAD_NAME_MAX]; - snprintf(name, sizeof(name), "%s#%02d", thread_name_detect_loader, i+1); + snprintf(name, sizeof(name), "%s#%02d", thread_name_detect_loader, i + 1); ThreadVars *tv_loader = TmThreadCreateCmdThreadByName(name, "DetectLoader", 1); if (tv_loader == NULL) { @@ -624,7 +621,7 @@ void DetectLoaderThreadSpawn(void) } } -void TmModuleDetectLoaderRegister (void) +void TmModuleDetectLoaderRegister(void) { tmm_modules[TMM_DETECTLOADER].name = "DetectLoader"; tmm_modules[TMM_DETECTLOADER].ThreadInit = DetectLoaderThreadInit; diff --git a/src/detect-engine-loader.h b/src/detect-engine-loader.h index 7ffb8c8648a0..806a25555a04 100644 --- a/src/detect-engine-loader.h +++ b/src/detect-engine-loader.h @@ -43,7 +43,7 @@ typedef struct DetectLoaderTask_ { typedef struct DetectLoaderControl_ { int id; - int result; /* 0 for ok, error otherwise */ + int result; /* 0 for ok, error otherwise */ SCMutex m; TAILQ_HEAD(, DetectLoaderTask_) task_list; } DetectLoaderControl; @@ -54,6 +54,6 @@ void DetectLoadersInit(void); void TmThreadContinueDetectLoaderThreads(void); void DetectLoaderThreadSpawn(void); -void TmModuleDetectLoaderRegister (void); +void TmModuleDetectLoaderRegister(void); #endif /* __DETECT_ENGINE_LOADER_H__ */ diff --git a/src/detect-engine-mpm.c b/src/detect-engine-mpm.c index 849930a7a9cf..ef5653dc3289 100644 --- a/src/detect-engine-mpm.c +++ b/src/detect-engine-mpm.c @@ -63,14 +63,8 @@ #include "util-validate.h" #include "util-hash-string.h" -const char *builtin_mpms[] = { - "toserver TCP packet", - "toclient TCP packet", - "toserver TCP stream", - "toclient TCP stream", - "toserver UDP packet", - "toclient UDP packet", - "other IP packet", +const char *builtin_mpms[] = { "toserver TCP packet", "toclient TCP packet", "toserver TCP stream", + "toclient TCP stream", "toserver UDP packet", "toclient UDP packet", "other IP packet", NULL }; @@ -90,8 +84,8 @@ void DetectAppLayerMpmRegister2(const char *name, int direction, int priority, PrefilterRegisterFunc PrefilterRegister, InspectionBufferGetDataPtr GetData, AppProto alproto, int tx_min_progress) { - SCLogDebug("registering %s/%d/%d/%p/%p/%u/%d", name, direction, priority, - PrefilterRegister, GetData, alproto, tx_min_progress); + SCLogDebug("registering %s/%d/%d/%p/%p/%u/%d", name, direction, priority, PrefilterRegister, + GetData, alproto, tx_min_progress); BUG_ON(tx_min_progress >= 48); @@ -140,8 +134,7 @@ void DetectAppLayerMpmRegister2(const char *name, int direction, int priority, } /** \brief copy a mpm engine from parent_id, add in transforms */ -void DetectAppLayerMpmRegisterByParentId(DetectEngineCtx *de_ctx, - const int id, const int parent_id, +void DetectAppLayerMpmRegisterByParentId(DetectEngineCtx *de_ctx, const int id, const int parent_id, DetectEngineTransforms *transforms) { SCLogDebug("registering %d/%d", id, parent_id); @@ -175,11 +168,11 @@ void DetectAppLayerMpmRegisterByParentId(DetectEngineCtx *de_ctx, char xforms[1024] = ""; for (int i = 0; i < transforms->cnt; i++) { char ttstr[64]; - (void)snprintf(ttstr,sizeof(ttstr), "%s,", + (void)snprintf(ttstr, sizeof(ttstr), "%s,", sigmatch_table[transforms->transforms[i].transform].name); strlcat(xforms, ttstr, sizeof(xforms)); } - xforms[strlen(xforms)-1] = '\0'; + xforms[strlen(xforms) - 1] = '\0'; size_t space = sizeof(am->pname) - strlen(am->name) - 3; char toprint[space + 1]; @@ -187,20 +180,18 @@ void DetectAppLayerMpmRegisterByParentId(DetectEngineCtx *de_ctx, if (space < strlen(xforms)) { ShortenString(xforms, toprint, space, '~'); } else { - strlcpy(toprint, xforms,sizeof(toprint)); + strlcpy(toprint, xforms, sizeof(toprint)); } - (void)snprintf(am->pname, sizeof(am->pname), "%s#%d (%s)", - am->name, id, toprint); + (void)snprintf(am->pname, sizeof(am->pname), "%s#%d (%s)", am->name, id, toprint); } else { - (void)snprintf(am->pname, sizeof(am->pname), "%s#%d", - am->name, id); + (void)snprintf(am->pname, sizeof(am->pname), "%s#%d", am->name, id); } am->id = de_ctx->app_mpms_list_cnt++; DetectEngineRegisterFastPatternForId(de_ctx, am->sm_list, am->priority); t->next = am; SCLogDebug("copied mpm registration for %s id %u " - "with parent %u and GetData %p", + "with parent %u and GetData %p", t->name, id, parent_id, am->app_v2.GetData); t = am; } @@ -250,8 +241,7 @@ void DetectMpmInitializeAppMpms(DetectEngineCtx *de_ctx) list = list->next; } de_ctx->app_mpms_list_cnt = g_mpm_list_cnt[DETECT_BUFFER_MPM_TYPE_APP]; - SCLogDebug("mpm: de_ctx app_mpms_list %p %u", - de_ctx->app_mpms_list, de_ctx->app_mpms_list_cnt); + SCLogDebug("mpm: de_ctx app_mpms_list %p %u", de_ctx->app_mpms_list, de_ctx->app_mpms_list_cnt); } /** @@ -265,8 +255,7 @@ int DetectMpmPrepareAppMpms(DetectEngineCtx *de_ctx) while (am != NULL) { int dir = (am->direction == SIG_FLAG_TOSERVER) ? 1 : 0; - if (am->sgh_mpm_context != MPM_CTX_FACTORY_UNIQUE_CONTEXT) - { + if (am->sgh_mpm_context != MPM_CTX_FACTORY_UNIQUE_CONTEXT) { MpmCtx *mpm_ctx = MpmFactoryGetMpmCtxForProfile(de_ctx, am->sgh_mpm_context, dir); if (mpm_ctx != NULL) { if (mpm_table[de_ctx->mpm_matcher].Prepare != NULL) { @@ -518,8 +507,7 @@ void DetectPktMpmRegister(const char *name, int priority, const DetectBufferMpmRegistry *mpm_reg, int list_id), InspectionBufferGetPktDataPtr GetData) { - SCLogDebug("registering %s/%d/%p/%p", name, priority, - PrefilterRegister, GetData); + SCLogDebug("registering %s/%d/%p/%p", name, priority, PrefilterRegister, GetData); if (PrefilterRegister == PrefilterGenericMpmPktRegister && GetData == NULL) { // must register GetData with PrefilterGenericMpmRegister @@ -562,8 +550,7 @@ void DetectPktMpmRegister(const char *name, int priority, } /** \brief copy a mpm engine from parent_id, add in transforms */ -void DetectPktMpmRegisterByParentId(DetectEngineCtx *de_ctx, - const int id, const int parent_id, +void DetectPktMpmRegisterByParentId(DetectEngineCtx *de_ctx, const int id, const int parent_id, DetectEngineTransforms *transforms) { SCLogDebug("registering %d/%d", id, parent_id); @@ -592,7 +579,7 @@ void DetectPktMpmRegisterByParentId(DetectEngineCtx *de_ctx, DetectEngineRegisterFastPatternForId(de_ctx, am->sm_list, am->priority); t->next = am; SCLogDebug("copied mpm registration for %s id %u " - "with parent %u and GetData %p", + "with parent %u and GetData %p", t->name, id, parent_id, am->pkt_v1.GetData); t = am; } @@ -644,8 +631,7 @@ void DetectMpmInitializePktMpms(DetectEngineCtx *de_ctx) list = list->next; } de_ctx->pkt_mpms_list_cnt = g_mpm_list_cnt[DETECT_BUFFER_MPM_TYPE_PKT]; - SCLogDebug("mpm: de_ctx pkt_mpms_list %p %u", - de_ctx->pkt_mpms_list, de_ctx->pkt_mpms_list_cnt); + SCLogDebug("mpm: de_ctx pkt_mpms_list %p %u", de_ctx->pkt_mpms_list, de_ctx->pkt_mpms_list_cnt); } /** @@ -659,8 +645,7 @@ int DetectMpmPreparePktMpms(DetectEngineCtx *de_ctx) const DetectBufferMpmRegistry *am = de_ctx->pkt_mpms_list; while (am != NULL) { SCLogDebug("%s", am->name); - if (am->sgh_mpm_context != MPM_CTX_FACTORY_UNIQUE_CONTEXT) - { + if (am->sgh_mpm_context != MPM_CTX_FACTORY_UNIQUE_CONTEXT) { MpmCtx *mpm_ctx = MpmFactoryGetMpmCtxForProfile(de_ctx, am->sgh_mpm_context, 0); if (mpm_ctx != NULL) { if (mpm_table[de_ctx->mpm_matcher].Prepare != NULL) { @@ -717,29 +702,34 @@ int DetectMpmPrepareBuiltinMpms(DetectEngineCtx *de_ctx) MpmCtx *mpm_ctx = NULL; if (de_ctx->sgh_mpm_context_proto_tcp_packet != MPM_CTX_FACTORY_UNIQUE_CONTEXT) { - mpm_ctx = MpmFactoryGetMpmCtxForProfile(de_ctx, de_ctx->sgh_mpm_context_proto_tcp_packet, 0); + mpm_ctx = + MpmFactoryGetMpmCtxForProfile(de_ctx, de_ctx->sgh_mpm_context_proto_tcp_packet, 0); if (mpm_table[de_ctx->mpm_matcher].Prepare != NULL) { r |= mpm_table[de_ctx->mpm_matcher].Prepare(mpm_ctx); } - mpm_ctx = MpmFactoryGetMpmCtxForProfile(de_ctx, de_ctx->sgh_mpm_context_proto_tcp_packet, 1); + mpm_ctx = + MpmFactoryGetMpmCtxForProfile(de_ctx, de_ctx->sgh_mpm_context_proto_tcp_packet, 1); if (mpm_table[de_ctx->mpm_matcher].Prepare != NULL) { r |= mpm_table[de_ctx->mpm_matcher].Prepare(mpm_ctx); } } if (de_ctx->sgh_mpm_context_proto_udp_packet != MPM_CTX_FACTORY_UNIQUE_CONTEXT) { - mpm_ctx = MpmFactoryGetMpmCtxForProfile(de_ctx, de_ctx->sgh_mpm_context_proto_udp_packet, 0); + mpm_ctx = + MpmFactoryGetMpmCtxForProfile(de_ctx, de_ctx->sgh_mpm_context_proto_udp_packet, 0); if (mpm_table[de_ctx->mpm_matcher].Prepare != NULL) { r |= mpm_table[de_ctx->mpm_matcher].Prepare(mpm_ctx); } - mpm_ctx = MpmFactoryGetMpmCtxForProfile(de_ctx, de_ctx->sgh_mpm_context_proto_udp_packet, 1); + mpm_ctx = + MpmFactoryGetMpmCtxForProfile(de_ctx, de_ctx->sgh_mpm_context_proto_udp_packet, 1); if (mpm_table[de_ctx->mpm_matcher].Prepare != NULL) { r |= mpm_table[de_ctx->mpm_matcher].Prepare(mpm_ctx); } } if (de_ctx->sgh_mpm_context_proto_other_packet != MPM_CTX_FACTORY_UNIQUE_CONTEXT) { - mpm_ctx = MpmFactoryGetMpmCtxForProfile(de_ctx, de_ctx->sgh_mpm_context_proto_other_packet, 0); + mpm_ctx = MpmFactoryGetMpmCtxForProfile( + de_ctx, de_ctx->sgh_mpm_context_proto_other_packet, 0); if (mpm_table[de_ctx->mpm_matcher].Prepare != NULL) { r |= mpm_table[de_ctx->mpm_matcher].Prepare(mpm_ctx); } @@ -781,8 +771,7 @@ int SignatureHasPacketContent(const Signature *s) } if ((s->init_data != NULL && s->init_data->smlists[DETECT_SM_LIST_PMATCH] == NULL) || - (s->init_data == NULL && s->sm_arrays[DETECT_SM_LIST_PMATCH] == NULL)) - { + (s->init_data == NULL && s->sm_arrays[DETECT_SM_LIST_PMATCH] == NULL)) { SCLogDebug("no mpm"); SCReturnInt(0); } @@ -817,8 +806,7 @@ int SignatureHasStreamContent(const Signature *s) } if ((s->init_data != NULL && s->init_data->smlists[DETECT_SM_LIST_PMATCH] == NULL) || - (s->init_data == NULL && s->sm_arrays[DETECT_SM_LIST_PMATCH] == NULL)) - { + (s->init_data == NULL && s->sm_arrays[DETECT_SM_LIST_PMATCH] == NULL)) { SCLogDebug("no mpm"); SCReturnInt(0); } @@ -830,7 +818,6 @@ int SignatureHasStreamContent(const Signature *s) SCReturnInt(1); } - /** * \brief Function to return the multi pattern matcher algorithm to be * used by the engine, based on the mpm-algo setting in yaml @@ -880,29 +867,29 @@ uint8_t PatternMatchDefaultMatcher(void) mpm_algo); } - done: +done: return mpm_algo_val; } void PatternMatchDestroy(MpmCtx *mpm_ctx, uint16_t mpm_matcher) { - SCLogDebug("mpm_ctx %p, mpm_matcher %"PRIu16"", mpm_ctx, mpm_matcher); + SCLogDebug("mpm_ctx %p, mpm_matcher %" PRIu16 "", mpm_ctx, mpm_matcher); mpm_table[mpm_matcher].DestroyCtx(mpm_ctx); } void PatternMatchThreadPrint(MpmThreadCtx *mpm_thread_ctx, uint16_t mpm_matcher) { - SCLogDebug("mpm_thread_ctx %p, mpm_matcher %"PRIu16" defunct", mpm_thread_ctx, mpm_matcher); - //mpm_table[mpm_matcher].PrintThreadCtx(mpm_thread_ctx); + SCLogDebug("mpm_thread_ctx %p, mpm_matcher %" PRIu16 " defunct", mpm_thread_ctx, mpm_matcher); + // mpm_table[mpm_matcher].PrintThreadCtx(mpm_thread_ctx); } void PatternMatchThreadDestroy(MpmThreadCtx *mpm_thread_ctx, uint16_t mpm_matcher) { - SCLogDebug("mpm_thread_ctx %p, mpm_matcher %"PRIu16"", mpm_thread_ctx, mpm_matcher); + SCLogDebug("mpm_thread_ctx %p, mpm_matcher %" PRIu16 "", mpm_thread_ctx, mpm_matcher); MpmDestroyThreadCtx(mpm_thread_ctx, mpm_matcher); } void PatternMatchThreadPrepare(MpmThreadCtx *mpm_thread_ctx, uint16_t mpm_matcher) { - SCLogDebug("mpm_thread_ctx %p, type %"PRIu16, mpm_thread_ctx, mpm_matcher); + SCLogDebug("mpm_thread_ctx %p, type %" PRIu16, mpm_thread_ctx, mpm_matcher); MpmInitThreadCtx(mpm_thread_ctx, mpm_matcher); } @@ -922,7 +909,7 @@ void PatternMatchThreadPrepare(MpmThreadCtx *mpm_thread_ctx, uint16_t mpm_matche uint32_t PatternStrength(uint8_t *pat, uint16_t patlen) { uint8_t a[256]; - memset(&a, 0 ,sizeof(a)); + memset(&a, 0, sizeof(a)); uint32_t s = 0; uint16_t u = 0; @@ -944,10 +931,8 @@ uint32_t PatternStrength(uint8_t *pat, uint16_t patlen) return s; } -static void PopulateMpmHelperAddPattern(MpmCtx *mpm_ctx, - const DetectContentData *cd, - const Signature *s, uint8_t flags, - int chop) +static void PopulateMpmHelperAddPattern( + MpmCtx *mpm_ctx, const DetectContentData *cd, const Signature *s, uint8_t flags, int chop) { uint16_t pat_offset = cd->offset; uint16_t pat_depth = cd->depth; @@ -970,34 +955,26 @@ static void PopulateMpmHelperAddPattern(MpmCtx *mpm_ctx, if (cd->flags & DETECT_CONTENT_NOCASE) { if (chop) { - MpmAddPatternCI(mpm_ctx, - cd->content + cd->fp_chop_offset, cd->fp_chop_len, - pat_offset, pat_depth, - cd->id, s->num, flags|MPM_PATTERN_CTX_OWNS_ID); + MpmAddPatternCI(mpm_ctx, cd->content + cd->fp_chop_offset, cd->fp_chop_len, pat_offset, + pat_depth, cd->id, s->num, flags | MPM_PATTERN_CTX_OWNS_ID); } else { - MpmAddPatternCI(mpm_ctx, - cd->content, cd->content_len, - pat_offset, pat_depth, - cd->id, s->num, flags|MPM_PATTERN_CTX_OWNS_ID); + MpmAddPatternCI(mpm_ctx, cd->content, cd->content_len, pat_offset, pat_depth, cd->id, + s->num, flags | MPM_PATTERN_CTX_OWNS_ID); } } else { if (chop) { - MpmAddPatternCS(mpm_ctx, - cd->content + cd->fp_chop_offset, cd->fp_chop_len, - pat_offset, pat_depth, - cd->id, s->num, flags|MPM_PATTERN_CTX_OWNS_ID); + MpmAddPatternCS(mpm_ctx, cd->content + cd->fp_chop_offset, cd->fp_chop_len, pat_offset, + pat_depth, cd->id, s->num, flags | MPM_PATTERN_CTX_OWNS_ID); } else { - MpmAddPatternCS(mpm_ctx, - cd->content, cd->content_len, - pat_offset, pat_depth, - cd->id, s->num, flags|MPM_PATTERN_CTX_OWNS_ID); + MpmAddPatternCS(mpm_ctx, cd->content, cd->content_len, pat_offset, pat_depth, cd->id, + s->num, flags | MPM_PATTERN_CTX_OWNS_ID); } } return; } -#define SGH_PROTO(sgh, p) ((sgh)->init->protos[(p)] == 1) +#define SGH_PROTO(sgh, p) ((sgh)->init->protos[(p)] == 1) #define SGH_DIRECTION_TS(sgh) ((sgh)->init->direction & SIG_FLAG_TOSERVER) #define SGH_DIRECTION_TC(sgh) ((sgh)->init->direction & SIG_FLAG_TOCLIENT) @@ -1008,18 +985,13 @@ static void SetMpm(Signature *s, SigMatch *mpm_sm, const int mpm_sm_list) DetectContentData *cd = (DetectContentData *)mpm_sm->ctx; if (cd->flags & DETECT_CONTENT_FAST_PATTERN_CHOP) { - if (DETECT_CONTENT_IS_SINGLE(cd) && - !(cd->flags & DETECT_CONTENT_NEGATED) && - !(cd->flags & DETECT_CONTENT_REPLACE) && - cd->content_len == cd->fp_chop_len) - { + if (DETECT_CONTENT_IS_SINGLE(cd) && !(cd->flags & DETECT_CONTENT_NEGATED) && + !(cd->flags & DETECT_CONTENT_REPLACE) && cd->content_len == cd->fp_chop_len) { cd->flags |= DETECT_CONTENT_NO_DOUBLE_INSPECTION_REQUIRED; } } else { - if (DETECT_CONTENT_IS_SINGLE(cd) && - !(cd->flags & DETECT_CONTENT_NEGATED) && - !(cd->flags & DETECT_CONTENT_REPLACE)) - { + if (DETECT_CONTENT_IS_SINGLE(cd) && !(cd->flags & DETECT_CONTENT_NEGATED) && + !(cd->flags & DETECT_CONTENT_REPLACE)) { cd->flags |= DETECT_CONTENT_NO_DOUBLE_INSPECTION_REQUIRED; } } @@ -1161,10 +1133,7 @@ void RetrieveFPForSig(const DetectEngineCtx *de_ctx, Signature *s) const SCFPSupportSMList *tmp = de_ctx->fp_support_smlist_list; while (tmp != NULL) { - for (priority = tmp->priority; - tmp != NULL && priority == tmp->priority; - tmp = tmp->next) - { + for (priority = tmp->priority; tmp != NULL && priority == tmp->priority; tmp = tmp->next) { SCLogDebug("tmp->list_id %d tmp->priority %d", tmp->list_id, tmp->priority); if (tmp->list_id >= nlists) continue; @@ -1297,8 +1266,7 @@ static uint32_t MpmStoreHashFunc(HashListTable *ht, void *data, uint16_t datalen * \retval 1 If the 2 MpmStores sent as args match. * \retval 0 If the 2 MpmStores sent as args do not match. */ -static char MpmStoreCompareFunc(void *data1, uint16_t len1, void *data2, - uint16_t len2) +static char MpmStoreCompareFunc(void *data1, uint16_t len1, void *data2, uint16_t len2) { const MpmStore *ms1 = (MpmStore *)data1; const MpmStore *ms2 = (MpmStore *)data2; @@ -1318,9 +1286,7 @@ static char MpmStoreCompareFunc(void *data1, uint16_t len1, void *data2, if (ms1->sm_list != ms2->sm_list) return 0; - if (SCMemcmp(ms1->sid_array, ms2->sid_array, - ms1->sid_array_size) != 0) - { + if (SCMemcmp(ms1->sid_array, ms2->sid_array, ms1->sid_array_size) != 0) { return 0; } @@ -1331,8 +1297,7 @@ static void MpmStoreFreeFunc(void *ptr) { MpmStore *ms = ptr; if (ms != NULL) { - if (ms->mpm_ctx != NULL && !(ms->mpm_ctx->flags & MPMCTX_FLAGS_GLOBAL)) - { + if (ms->mpm_ctx != NULL && !(ms->mpm_ctx->flags & MPMCTX_FLAGS_GLOBAL)) { SCLogDebug("destroying mpm_ctx %p", ms->mpm_ctx); mpm_table[ms->mpm_ctx->mpm_type].DestroyCtx(ms->mpm_ctx); SCFree(ms->mpm_ctx); @@ -1355,10 +1320,8 @@ static void MpmStoreFreeFunc(void *ptr) */ int MpmStoreInit(DetectEngineCtx *de_ctx) { - de_ctx->mpm_hash_table = HashListTableInit(4096, - MpmStoreHashFunc, - MpmStoreCompareFunc, - MpmStoreFreeFunc); + de_ctx->mpm_hash_table = + HashListTableInit(4096, MpmStoreHashFunc, MpmStoreCompareFunc, MpmStoreFreeFunc); if (de_ctx->mpm_hash_table == NULL) goto error; @@ -1393,8 +1356,7 @@ static int MpmStoreAdd(DetectEngineCtx *de_ctx, MpmStore *s) */ static MpmStore *MpmStoreLookup(DetectEngineCtx *de_ctx, MpmStore *s) { - MpmStore *rs = HashListTableLookup(de_ctx->mpm_hash_table, - (void *)s, 0); + MpmStore *rs = HashListTableLookup(de_ctx->mpm_hash_table, (void *)s, 0); return rs; } @@ -1403,8 +1365,7 @@ static const DetectBufferMpmRegistry *GetByMpmStore( { const DetectBufferMpmRegistry *am = de_ctx->app_mpms_list; while (am != NULL) { - if (ms->sm_list == am->sm_list && - ms->direction == am->direction) { + if (ms->sm_list == am->sm_list && ms->direction == am->direction) { return am; } am = am->next; @@ -1423,21 +1384,19 @@ void MpmStoreReportStats(const DetectEngineCtx *de_ctx) { HashListTableBucket *htb = NULL; - uint32_t stats[MPMB_MAX] = {0}; + uint32_t stats[MPMB_MAX] = { 0 }; int app_mpms_cnt = de_ctx->buffer_type_id; - uint32_t appstats[app_mpms_cnt + 1]; // +1 to silence scan-build + uint32_t appstats[app_mpms_cnt + 1]; // +1 to silence scan-build memset(&appstats, 0x00, sizeof(appstats)); int pkt_mpms_cnt = de_ctx->buffer_type_id; - uint32_t pktstats[pkt_mpms_cnt + 1]; // +1 to silence scan-build + uint32_t pktstats[pkt_mpms_cnt + 1]; // +1 to silence scan-build memset(&pktstats, 0x00, sizeof(pktstats)); int frame_mpms_cnt = de_ctx->buffer_type_id; uint32_t framestats[frame_mpms_cnt + 1]; // +1 to silence scan-build memset(&framestats, 0x00, sizeof(framestats)); - for (htb = HashListTableGetListHead(de_ctx->mpm_hash_table); - htb != NULL; - htb = HashListTableGetListNext(htb)) - { + for (htb = HashListTableGetListHead(de_ctx->mpm_hash_table); htb != NULL; + htb = HashListTableGetListNext(htb)) { const MpmStore *ms = (MpmStore *)HashListTableGetListData(htb); if (ms == NULL || ms->mpm_ctx == NULL) { continue; @@ -1449,10 +1408,8 @@ void MpmStoreReportStats(const DetectEngineCtx *de_ctx) if (am != NULL) { switch (am->type) { case DETECT_BUFFER_MPM_TYPE_PKT: - SCLogDebug("%s: %u patterns. Min %u, Max %u. Ctx %p", - am->name, - ms->mpm_ctx->pattern_cnt, - ms->mpm_ctx->minlen, ms->mpm_ctx->maxlen, + SCLogDebug("%s: %u patterns. Min %u, Max %u. Ctx %p", am->name, + ms->mpm_ctx->pattern_cnt, ms->mpm_ctx->minlen, ms->mpm_ctx->maxlen, ms->mpm_ctx); pktstats[am->sm_list]++; break; @@ -1485,7 +1442,8 @@ void MpmStoreReportStats(const DetectEngineCtx *de_ctx) while (am != NULL) { if (appstats[am->sm_list] > 0) { const char *name = am->name; - const char *direction = am->direction == SIG_FLAG_TOSERVER ? "toserver" : "toclient"; + const char *direction = + am->direction == SIG_FLAG_TOSERVER ? "toserver" : "toclient"; SCLogPerf("AppLayer MPM \"%s %s (%s)\": %u", direction, name, AppProtoToString(am->app_v2.alproto), appstats[am->sm_list]); } @@ -1548,7 +1506,7 @@ static void MpmStoreSetup(const DetectEngineCtx *de_ctx, MpmStore *ms) case MPMB_UDP_TC: case MPMB_TCP_STREAM_TC: case MPMB_TCP_PKT_TC: - case MPMB_OTHERIP: /**< use 0 for other */ + case MPMB_OTHERIP: /**< use 0 for other */ dir = 0; break; } @@ -1586,16 +1544,14 @@ static void MpmStoreSetup(const DetectEngineCtx *de_ctx, MpmStore *ms) * match. So in this case there is no point of adding it at all. * The non-mpm list entry for the sig will make sure the sig is * inspected. */ - if ((cd->flags & DETECT_CONTENT_NEGATED) && - !(DETECT_CONTENT_MPM_IS_CONCLUSIVE(cd))) - { + if ((cd->flags & DETECT_CONTENT_NEGATED) && !(DETECT_CONTENT_MPM_IS_CONCLUSIVE(cd))) { skip = 1; SCLogDebug("not adding negated mpm as it's not 'single'"); } if (!skip) { - PopulateMpmHelperAddPattern(ms->mpm_ctx, - cd, s, 0, (cd->flags & DETECT_CONTENT_FAST_PATTERN_CHOP)); + PopulateMpmHelperAddPattern( + ms->mpm_ctx, cd, s, 0, (cd->flags & DETECT_CONTENT_FAST_PATTERN_CHOP)); } } } @@ -1612,12 +1568,11 @@ static void MpmStoreSetup(const DetectEngineCtx *de_ctx, MpmStore *ms) } } - /** \brief Get MpmStore for a built-in buffer type * */ -MpmStore *MpmStorePrepareBuffer(DetectEngineCtx *de_ctx, SigGroupHead *sgh, - enum MpmBuiltinBuffers buf) +MpmStore *MpmStorePrepareBuffer( + DetectEngineCtx *de_ctx, SigGroupHead *sgh, enum MpmBuiltinBuffers buf) { const Signature *s = NULL; uint32_t sig; @@ -1649,7 +1604,7 @@ MpmStore *MpmStorePrepareBuffer(DetectEngineCtx *de_ctx, SigGroupHead *sgh, break; } - switch(buf) { + switch (buf) { case MPMB_TCP_PKT_TS: case MPMB_TCP_STREAM_TS: case MPMB_UDP_TS: @@ -1663,7 +1618,7 @@ MpmStore *MpmStorePrepareBuffer(DetectEngineCtx *de_ctx, SigGroupHead *sgh, break; case MPMB_OTHERIP: - direction = (SIG_FLAG_TOCLIENT|SIG_FLAG_TOSERVER); + direction = (SIG_FLAG_TOCLIENT | SIG_FLAG_TOSERVER); break; case MPMB_MAX: @@ -1689,16 +1644,14 @@ MpmStore *MpmStorePrepareBuffer(DetectEngineCtx *de_ctx, SigGroupHead *sgh, switch (buf) { case MPMB_TCP_PKT_TS: case MPMB_TCP_PKT_TC: - if (SignatureHasPacketContent(s) == 1) - { + if (SignatureHasPacketContent(s) == 1) { sids_array[s->num / 8] |= 1 << (s->num % 8); cnt++; } break; case MPMB_TCP_STREAM_TS: case MPMB_TCP_STREAM_TC: - if (SignatureHasStreamContent(s) == 1) - { + if (SignatureHasStreamContent(s) == 1) { sids_array[s->num / 8] |= 1 << (s->num % 8); cnt++; } @@ -1765,8 +1718,7 @@ static MpmStore *MpmStorePrepareBufferAppLayer(DetectEngineCtx *de_ctx, SigGroup return NULL; SCLogDebug("handling %s direction %s for list %d", am->name, - am->direction == SIG_FLAG_TOSERVER ? "toserver" : "toclient", - am->sm_list); + am->direction == SIG_FLAG_TOSERVER ? "toserver" : "toclient", am->sm_list); MpmStore lookup = { sa->sids_array, sa->sids_array_size, am->direction, MPMB_MAX, am->sm_list, 0, am->app_v2.alproto, NULL }; @@ -1809,8 +1761,7 @@ static MpmStore *MpmStorePrepareBufferAppLayer(DetectEngineCtx *de_ctx, SigGroup static MpmStore *MpmStorePrepareBufferPkt(DetectEngineCtx *de_ctx, SigGroupHead *sgh, const DetectBufferMpmRegistry *am, const struct SidsArray *sa) { - SCLogDebug("handling %s for list %d", am->name, - am->sm_list); + SCLogDebug("handling %s for list %d", am->name, am->sm_list); if (sa->sids_array_size == 0 || sa->sids_array == NULL) return NULL; @@ -1836,7 +1787,7 @@ static MpmStore *MpmStorePrepareBufferPkt(DetectEngineCtx *de_ctx, SigGroupHead copy->sid_array = sids; copy->sid_array_size = sa->sids_array_size; copy->buffer = MPMB_MAX; - copy->direction = SIG_FLAG_TOSERVER|SIG_FLAG_TOCLIENT; + copy->direction = SIG_FLAG_TOSERVER | SIG_FLAG_TOCLIENT; copy->sm_list = am->sm_list; copy->sgh_mpm_context = am->sgh_mpm_context; @@ -2123,15 +2074,14 @@ static void PrepareMpms(DetectEngineCtx *de_ctx, SigGroupHead *sh) sh->init->pkt_mpms[a->id] = mpm_store->mpm_ctx; SCLogDebug("a %p a->name %s a->reg->PrefilterRegisterWithListId %p " - "mpm_store->mpm_ctx %p", a, a->name, - a->PrefilterRegisterWithListId, mpm_store->mpm_ctx); + "mpm_store->mpm_ctx %p", + a, a->name, a->PrefilterRegisterWithListId, mpm_store->mpm_ctx); /* if we have just certain types of negated patterns, * mpm_ctx can be NULL */ if (a->PrefilterRegisterWithListId && mpm_store->mpm_ctx) { - BUG_ON(a->PrefilterRegisterWithListId(de_ctx, - sh, mpm_store->mpm_ctx, - a, a->sm_list) != 0); + BUG_ON(a->PrefilterRegisterWithListId( + de_ctx, sh, mpm_store->mpm_ctx, a, a->sm_list) != 0); SCLogDebug("mpm %s %d set up", a->name, a->sm_list); } } @@ -2237,7 +2187,7 @@ int PatternMatchPrepareGroup(DetectEngineCtx *de_ctx, SigGroupHead *sh) } SetRawReassemblyFlag(de_ctx, sh); - } + } } else if (SGH_PROTO(sh, IPPROTO_UDP)) { if (SGH_DIRECTION_TS(sh)) { mpm_store = MpmStorePrepareBuffer(de_ctx, sh, MPMB_UDP_TS); diff --git a/src/detect-engine-mpm.h b/src/detect-engine-mpm.h index adb40297190f..9b98c5b7504b 100644 --- a/src/detect-engine-mpm.h +++ b/src/detect-engine-mpm.h @@ -24,10 +24,8 @@ #ifndef __DETECT_ENGINE_MPM_H__ #define __DETECT_ENGINE_MPM_H__ - #include "detect.h" - void DetectMpmInitializeFrameMpms(DetectEngineCtx *de_ctx); int DetectMpmPrepareFrameMpms(DetectEngineCtx *de_ctx); void DetectMpmInitializePktMpms(DetectEngineCtx *de_ctx); @@ -62,7 +60,8 @@ void RetrieveFPForSig(const DetectEngineCtx *de_ctx, Signature *s); int MpmStoreInit(DetectEngineCtx *); void MpmStoreFree(DetectEngineCtx *); void MpmStoreReportStats(const DetectEngineCtx *de_ctx); -MpmStore *MpmStorePrepareBuffer(DetectEngineCtx *de_ctx, SigGroupHead *sgh, enum MpmBuiltinBuffers buf); +MpmStore *MpmStorePrepareBuffer( + DetectEngineCtx *de_ctx, SigGroupHead *sgh, enum MpmBuiltinBuffers buf); /** * \brief Figure out the FP and their respective content ids for all the @@ -93,15 +92,12 @@ typedef int (*PrefilterRegisterFunc)(DetectEngineCtx *de_ctx, SigGroupHead *sgh, void DetectAppLayerMpmRegister2(const char *name, int direction, int priority, PrefilterRegisterFunc PrefilterRegister, InspectionBufferGetDataPtr GetData, AppProto alproto, int tx_min_progress); -void DetectAppLayerMpmRegisterByParentId( - DetectEngineCtx *de_ctx, - const int id, const int parent_id, +void DetectAppLayerMpmRegisterByParentId(DetectEngineCtx *de_ctx, const int id, const int parent_id, DetectEngineTransforms *transforms); void DetectPktMpmRegister(const char *name, int priority, PrefilterRegisterFunc PrefilterRegister, InspectionBufferGetPktDataPtr GetData); -void DetectPktMpmRegisterByParentId(DetectEngineCtx *de_ctx, - const int id, const int parent_id, +void DetectPktMpmRegisterByParentId(DetectEngineCtx *de_ctx, const int id, const int parent_id, DetectEngineTransforms *transforms); void DetectFrameMpmRegister(const char *name, int direction, int priority, @@ -136,4 +132,3 @@ struct MpmListIdDataArgs { void EngineAnalysisAddAllRulePatterns(DetectEngineCtx *de_ctx, const Signature *s); #endif /* __DETECT_ENGINE_MPM_H__ */ - diff --git a/src/detect-engine-payload.c b/src/detect-engine-payload.c index 3c485bc1da6d..9cd21e5f116f 100644 --- a/src/detect-engine-payload.c +++ b/src/detect-engine-payload.c @@ -71,8 +71,7 @@ static int StreamMpmFunc( return 0; } -static void PrefilterPktStream(DetectEngineThreadCtx *det_ctx, - Packet *p, const void *pectx) +static void PrefilterPktStream(DetectEngineThreadCtx *det_ctx, Packet *p, const void *pectx) { SCEnter(); @@ -80,15 +79,11 @@ static void PrefilterPktStream(DetectEngineThreadCtx *det_ctx, /* for established packets inspect any stream we may have queued up */ if (p->flags & PKT_DETECT_HAS_STREAMDATA) { - SCLogDebug("PRE det_ctx->raw_stream_progress %"PRIu64, - det_ctx->raw_stream_progress); + SCLogDebug("PRE det_ctx->raw_stream_progress %" PRIu64, det_ctx->raw_stream_progress); struct StreamMpmData stream_mpm_data = { det_ctx, mpm_ctx }; - StreamReassembleRaw(p->flow->protoctx, p, - StreamMpmFunc, &stream_mpm_data, - &det_ctx->raw_stream_progress, - false /* mpm doesn't use min inspect depth */); - SCLogDebug("POST det_ctx->raw_stream_progress %"PRIu64, - det_ctx->raw_stream_progress); + StreamReassembleRaw(p->flow->protoctx, p, StreamMpmFunc, &stream_mpm_data, + &det_ctx->raw_stream_progress, false /* mpm doesn't use min inspect depth */); + SCLogDebug("POST det_ctx->raw_stream_progress %" PRIu64, det_ctx->raw_stream_progress); /* packets that have not been added to the stream will be inspected as if they are stream * chunks */ @@ -98,23 +93,19 @@ static void PrefilterPktStream(DetectEngineThreadCtx *det_ctx, det_ctx->payload_mpm_cnt++; det_ctx->payload_mpm_size += p->payload_len; #endif - (void)mpm_table[mpm_ctx->mpm_type].Search(mpm_ctx, - &det_ctx->mtc, &det_ctx->pmq, - p->payload, p->payload_len); + (void)mpm_table[mpm_ctx->mpm_type].Search( + mpm_ctx, &det_ctx->mtc, &det_ctx->pmq, p->payload, p->payload_len); PREFILTER_PROFILING_ADD_BYTES(det_ctx, p->payload_len); } } } -int PrefilterPktStreamRegister(DetectEngineCtx *de_ctx, - SigGroupHead *sgh, MpmCtx *mpm_ctx) +int PrefilterPktStreamRegister(DetectEngineCtx *de_ctx, SigGroupHead *sgh, MpmCtx *mpm_ctx) { - return PrefilterAppendPayloadEngine(de_ctx, sgh, - PrefilterPktStream, mpm_ctx, NULL, "stream"); + return PrefilterAppendPayloadEngine(de_ctx, sgh, PrefilterPktStream, mpm_ctx, NULL, "stream"); } -static void PrefilterPktPayload(DetectEngineThreadCtx *det_ctx, - Packet *p, const void *pectx) +static void PrefilterPktPayload(DetectEngineThreadCtx *det_ctx, Packet *p, const void *pectx) { SCEnter(); @@ -122,21 +113,17 @@ static void PrefilterPktPayload(DetectEngineThreadCtx *det_ctx, if (p->payload_len < mpm_ctx->minlen) SCReturn; - (void)mpm_table[mpm_ctx->mpm_type].Search(mpm_ctx, - &det_ctx->mtc, &det_ctx->pmq, - p->payload, p->payload_len); + (void)mpm_table[mpm_ctx->mpm_type].Search( + mpm_ctx, &det_ctx->mtc, &det_ctx->pmq, p->payload, p->payload_len); PREFILTER_PROFILING_ADD_BYTES(det_ctx, p->payload_len); } -int PrefilterPktPayloadRegister(DetectEngineCtx *de_ctx, - SigGroupHead *sgh, MpmCtx *mpm_ctx) +int PrefilterPktPayloadRegister(DetectEngineCtx *de_ctx, SigGroupHead *sgh, MpmCtx *mpm_ctx) { - return PrefilterAppendPayloadEngine(de_ctx, sgh, - PrefilterPktPayload, mpm_ctx, NULL, "payload"); + return PrefilterAppendPayloadEngine(de_ctx, sgh, PrefilterPktPayload, mpm_ctx, NULL, "payload"); } - /** * \brief Do the content inspection & validation for a signature * @@ -249,17 +236,15 @@ static int StreamContentInspectFunc( * \retval 0 no match * \retval 1 match */ -int DetectEngineInspectStreamPayload(DetectEngineCtx *de_ctx, - DetectEngineThreadCtx *det_ctx, const Signature *s, - Flow *f, Packet *p) +int DetectEngineInspectStreamPayload(DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx, + const Signature *s, Flow *f, Packet *p) { SCEnter(); - SCLogDebug("FLUSH? %s", (s->flags & SIG_FLAG_FLUSH)?"true":"false"); + SCLogDebug("FLUSH? %s", (s->flags & SIG_FLAG_FLUSH) ? "true" : "false"); uint64_t unused; struct StreamContentInspectData inspect_data = { de_ctx, det_ctx, s, f }; - int r = StreamReassembleRaw(f->protoctx, p, - StreamContentInspectFunc, &inspect_data, - &unused, ((s->flags & SIG_FLAG_FLUSH) != 0)); + int r = StreamReassembleRaw(f->protoctx, p, StreamContentInspectFunc, &inspect_data, &unused, + ((s->flags & SIG_FLAG_FLUSH) != 0)); return r; } @@ -317,13 +302,11 @@ uint8_t DetectEngineInspectStream(DetectEngineCtx *de_ctx, DetectEngineThreadCtx if (ssn == NULL) return DETECT_ENGINE_INSPECT_SIG_CANT_MATCH; - SCLogDebug("pre-inspect det_ctx->raw_stream_progress %"PRIu64" FLUSH? %s", - det_ctx->raw_stream_progress, - (s->flags & SIG_FLAG_FLUSH)?"true":"false"); + SCLogDebug("pre-inspect det_ctx->raw_stream_progress %" PRIu64 " FLUSH? %s", + det_ctx->raw_stream_progress, (s->flags & SIG_FLAG_FLUSH) ? "true" : "false"); uint64_t unused; struct StreamContentInspectEngineData inspect_data = { de_ctx, det_ctx, s, engine->smd, f }; - int match = StreamReassembleRaw(f->protoctx, p, - StreamContentInspectEngineFunc, &inspect_data, + int match = StreamReassembleRaw(f->protoctx, p, StreamContentInspectEngineFunc, &inspect_data, &unused, ((s->flags & SIG_FLAG_FLUSH) != 0)); bool is_last = false; @@ -337,15 +320,14 @@ uint8_t DetectEngineInspectStream(DetectEngineCtx *de_ctx, DetectEngineThreadCtx is_last = true; } - SCLogDebug("%s ran stream for sid %u on packet %"PRIu64" and we %s", - is_last? "LAST:" : "normal:", s->id, p->pcap_cnt, - match ? "matched" : "didn't match"); + SCLogDebug("%s ran stream for sid %u on packet %" PRIu64 " and we %s", + is_last ? "LAST:" : "normal:", s->id, p->pcap_cnt, match ? "matched" : "didn't match"); if (match) { return DETECT_ENGINE_INSPECT_SIG_MATCH; } else { if (is_last) { - //SCLogNotice("last, so DETECT_ENGINE_INSPECT_SIG_CANT_MATCH"); + // SCLogNotice("last, so DETECT_ENGINE_INSPECT_SIG_CANT_MATCH"); return DETECT_ENGINE_INSPECT_SIG_CANT_MATCH; } /* TODO maybe we can set 'CANT_MATCH' for EOF too? */ @@ -358,16 +340,16 @@ uint8_t DetectEngineInspectStream(DetectEngineCtx *de_ctx, DetectEngineThreadCtx /** \test Not the first but the second occurrence of "abc" should be used * for the 2nd match */ -static int PayloadTestSig01 (void) +static int PayloadTestSig01(void) { - uint8_t *buf = (uint8_t *) - "abcabcd"; + uint8_t *buf = (uint8_t *)"abcabcd"; uint16_t buflen = strlen((char *)buf); Packet *p = UTHBuildPacket(buf, buflen, IPPROTO_TCP); FAIL_IF_NULL(p); - char sig[] = "alert tcp any any -> any any (content:\"abc\"; content:\"d\"; distance:0; within:1; sid:1;)"; + char sig[] = "alert tcp any any -> any any (content:\"abc\"; content:\"d\"; distance:0; " + "within:1; sid:1;)"; FAIL_IF(UTHPacketMatchSigMpm(p, sig, mpm_default_matcher) == 0); @@ -377,16 +359,16 @@ static int PayloadTestSig01 (void) } /** \test Nocase matching */ -static int PayloadTestSig02 (void) +static int PayloadTestSig02(void) { - uint8_t *buf = (uint8_t *) - "abcaBcd"; + uint8_t *buf = (uint8_t *)"abcaBcd"; uint16_t buflen = strlen((char *)buf); Packet *p = UTHBuildPacket(buf, buflen, IPPROTO_TCP); FAIL_IF_NULL(p); - char sig[] = "alert tcp any any -> any any (content:\"abc\"; nocase; content:\"d\"; distance:0; within:1; sid:1;)"; + char sig[] = "alert tcp any any -> any any (content:\"abc\"; nocase; content:\"d\"; " + "distance:0; within:1; sid:1;)"; FAIL_IF(UTHPacketMatchSigMpm(p, sig, mpm_default_matcher) == 0); @@ -396,16 +378,16 @@ static int PayloadTestSig02 (void) } /** \test Negative distance matching */ -static int PayloadTestSig03 (void) +static int PayloadTestSig03(void) { - uint8_t *buf = (uint8_t *) - "abcaBcd"; + uint8_t *buf = (uint8_t *)"abcaBcd"; uint16_t buflen = strlen((char *)buf); Packet *p = UTHBuildPacket(buf, buflen, IPPROTO_TCP); FAIL_IF_NULL(p); - char sig[] = "alert tcp any any -> any any (content:\"aBc\"; nocase; content:\"abca\"; distance:-10; within:4; sid:1;)"; + char sig[] = "alert tcp any any -> any any (content:\"aBc\"; nocase; content:\"abca\"; " + "distance:-10; within:4; sid:1;)"; FAIL_IF(UTHPacketMatchSigMpm(p, sig, mpm_default_matcher) == 0); @@ -426,8 +408,8 @@ static int PayloadTestSig04(void) FAIL_IF_NULL(p); char sig[] = "alert tcp any any -> any any (msg:\"dummy\"; " - "content:\"this\"; content:\"is\"; within:6; content:\"big\"; within:8; " - "content:\"string\"; within:8; sid:1;)"; + "content:\"this\"; content:\"is\"; within:6; content:\"big\"; within:8; " + "content:\"string\"; within:8; sid:1;)"; FAIL_IF(UTHPacketMatchSigMpm(p, sig, mpm_default_matcher) == 0); @@ -448,8 +430,8 @@ static int PayloadTestSig05(void) FAIL_IF_NULL(p); char sig[] = "alert tcp any any -> any any (msg:\"dummy\"; " - "content:\"this\"; content:\"is\"; within:9; content:\"big\"; within:12; " - "content:\"string\"; within:8; sid:1;)"; + "content:\"this\"; content:\"is\"; within:9; content:\"big\"; within:12; " + "content:\"string\"; within:8; sid:1;)"; FAIL_IF(UTHPacketMatchSigMpm(p, sig, mpm_default_matcher) == 0); @@ -470,8 +452,9 @@ static int PayloadTestSig06(void) FAIL_IF_NULL(p); char sig[] = "alert tcp any any -> any any (msg:\"dummy\"; " - "content:\"now\"; content:\"this\"; content:\"is\"; within:12; content:\"big\"; within:8; " - "content:\"string\"; within:8; sid:1;)"; + "content:\"now\"; content:\"this\"; content:\"is\"; within:12; content:\"big\"; " + "within:8; " + "content:\"string\"; within:8; sid:1;)"; FAIL_IF(UTHPacketMatchSigMpm(p, sig, mpm_default_matcher) == 0); @@ -492,7 +475,8 @@ static int PayloadTestSig07(void) FAIL_IF_NULL(p); char sig[] = "alert tcp any any -> any any (msg:\"dummy\"; " - "content:\"thus\"; offset:8; content:\"is\"; within:6; content:\"big\"; within:8; sid:1;)"; + "content:\"thus\"; offset:8; content:\"is\"; within:6; content:\"big\"; within:8; " + "sid:1;)"; FAIL_IF(UTHPacketMatchSigMpm(p, sig, mpm_default_matcher) == 0); @@ -513,8 +497,9 @@ static int PayloadTestSig08(void) FAIL_IF_NULL(p); - char sig[] = "alert tcp any any -> any any (msg:\"dummy\"; " - "content:\"fix\"; content:\"this\"; within:6; content:!\"and\"; distance:0; sid:1;)"; + char sig[] = + "alert tcp any any -> any any (msg:\"dummy\"; " + "content:\"fix\"; content:\"this\"; within:6; content:!\"and\"; distance:0; sid:1;)"; FAIL_IF(UTHPacketMatchSigMpm(p, sig, mpm_default_matcher) != 1); @@ -535,7 +520,7 @@ static int PayloadTestSig09(void) FAIL_IF_NULL(p); char sig[] = "alert tcp any any -> any any (msg:\"dummy\"; " - "pcre:/super/; content:\"nova\"; within:7; sid:1;)"; + "pcre:/super/; content:\"nova\"; within:7; sid:1;)"; FAIL_IF(UTHPacketMatchSigMpm(p, sig, mpm_default_matcher) == 0); @@ -556,7 +541,7 @@ static int PayloadTestSig10(void) FAIL_IF_NULL(p); char sig[] = "alert udp any any -> any any (msg:\"crash\"; " - "byte_test:4,>,2,0,relative; sid:11;)"; + "byte_test:4,>,2,0,relative; sid:11;)"; FAIL_IF(UTHPacketMatchSigMpm(p, sig, mpm_default_matcher) == 1); @@ -577,7 +562,7 @@ static int PayloadTestSig11(void) FAIL_IF_NULL(p); char sig[] = "alert udp any any -> any any (msg:\"crash\"; " - "byte_jump:1,0,relative; sid:11;)"; + "byte_jump:1,0,relative; sid:11;)"; FAIL_IF(UTHPacketMatchSigMpm(p, sig, mpm_default_matcher) == 1); @@ -598,7 +583,7 @@ static int PayloadTestSig12(void) FAIL_IF_NULL(p); char sig[] = "alert udp any any -> any any (msg:\"crash\"; " - "isdataat:10,relative; sid:11;)"; + "isdataat:10,relative; sid:11;)"; FAIL_IF(UTHPacketMatchSigMpm(p, sig, mpm_default_matcher) == 1); @@ -613,25 +598,25 @@ static int PayloadTestSig12(void) static int PayloadTestSig13(void) { uint8_t *buf = (uint8_t *)"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; uint16_t buflen = strlen((char *)buf); Packet *p = UTHBuildPacket(buf, buflen, IPPROTO_TCP); @@ -640,8 +625,8 @@ static int PayloadTestSig13(void) FAIL_IF_NULL(p); char sig[] = "alert tcp any any -> any any (msg:\"dummy\"; " - "content:\"aa\"; content:\"aa\"; distance:0; content:\"aa\"; distance:0; " - "byte_test:1,>,200,0,relative; sid:1;)"; + "content:\"aa\"; content:\"aa\"; distance:0; content:\"aa\"; distance:0; " + "byte_test:1,>,200,0,relative; sid:1;)"; DecodeThreadVars dtv; ThreadVars th_v; @@ -681,15 +666,23 @@ static int PayloadTestSig13(void) */ static int PayloadTestSig14(void) { - uint8_t *buf = (uint8_t *)"User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.1b4) Gecko/20090423 Firefox/3.6 GTB5"; + uint8_t *buf = (uint8_t *)"User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; " + "rv:1.9.1b4) Gecko/20090423 Firefox/3.6 GTB5"; uint16_t buflen = strlen((char *)buf); Packet *p = UTHBuildPacket(buf, buflen, IPPROTO_TCP); FAIL_IF_NULL(p); - char sig[] = "alert tcp any any -> any any (content:\"User-Agent|3A| Mozilla/5.0 |28|Macintosh|3B| \"; content:\"Firefox/3.\"; distance:0; content:!\"Firefox/3.6.12\"; distance:-10; content:!\"Mozilla/5.0 |28|Macintosh|3B| U|3B| Intel Mac OS X 10.5|3B| en-US|3B| rv|3A|1.9.1b4|29| Gecko/20090423 Firefox/3.6 GTB5\"; sid:1; rev:1;)"; + char sig[] = + "alert tcp any any -> any any (content:\"User-Agent|3A| Mozilla/5.0 |28|Macintosh|3B| " + "\"; content:\"Firefox/3.\"; distance:0; content:!\"Firefox/3.6.12\"; distance:-10; " + "content:!\"Mozilla/5.0 |28|Macintosh|3B| U|3B| Intel Mac OS X 10.5|3B| en-US|3B| " + "rv|3A|1.9.1b4|29| Gecko/20090423 Firefox/3.6 GTB5\"; sid:1; rev:1;)"; - //char sig[] = "alert tcp any any -> any any (content:\"User-Agent: Mozilla/5.0 (Macintosh; \"; content:\"Firefox/3.\"; distance:0; content:!\"Firefox/3.6.12\"; distance:-10; content:!\"Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.1b4) Gecko/20090423 Firefox/3.6 GTB5\"; sid:1; rev:1;)"; + // char sig[] = "alert tcp any any -> any any (content:\"User-Agent: Mozilla/5.0 (Macintosh; \"; + // content:\"Firefox/3.\"; distance:0; content:!\"Firefox/3.6.12\"; distance:-10; + // content:!\"Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.1b4) Gecko/20090423 + // Firefox/3.6 GTB5\"; sid:1; rev:1;)"; FAIL_IF(UTHPacketMatchSigMpm(p, sig, mpm_default_matcher) == 1); @@ -707,7 +700,7 @@ static int PayloadTestSig15(void) FAIL_IF_NULL(p); char sig[] = "alert tcp any any -> any any (msg:\"dummy\"; " - "content:\"nova\"; isdataat:18,relative; sid:1;)"; + "content:\"nova\"; isdataat:18,relative; sid:1;)"; FAIL_IF(UTHPacketMatchSigMpm(p, sig, mpm_default_matcher) == 0); @@ -725,7 +718,7 @@ static int PayloadTestSig16(void) FAIL_IF_NULL(p); char sig[] = "alert tcp any any -> any any (msg:\"dummy\"; " - "content:\"nova\"; isdataat:!20,relative; sid:1;)"; + "content:\"nova\"; isdataat:!20,relative; sid:1;)"; FAIL_IF(UTHPacketMatchSigMpm(p, sig, mpm_default_matcher) == 0); @@ -745,8 +738,8 @@ static int PayloadTestSig17(void) FAIL_IF_NULL(p); char sig[] = "alert tcp any any -> any any (msg:\"dummy\"; " - "content:\"%\"; depth:4; offset:0; " - "content:\"%\"; within:2; distance:1; sid:1;)"; + "content:\"%\"; depth:4; offset:0; " + "content:\"%\"; within:2; distance:1; sid:1;)"; FAIL_IF(UTHPacketMatchSigMpm(p, sig, mpm_default_matcher) == 0); @@ -770,9 +763,9 @@ static int PayloadTestSig18(void) FAIL_IF_NULL(p); char sig[] = "alert tcp any any -> any any (msg:\"dummy\"; " - "content:\"|01 02 03 04|\"; " - "byte_extract:1,2,one,string,dec,relative; " - "content:\"|0C 0D 0E 0F|\"; distance:one; sid:1;)"; + "content:\"|01 02 03 04|\"; " + "byte_extract:1,2,one,string,dec,relative; " + "content:\"|0C 0D 0E 0F|\"; distance:one; sid:1;)"; FAIL_IF(UTHPacketMatchSigMpm(p, sig, mpm_default_matcher) == 0); @@ -796,9 +789,9 @@ static int PayloadTestSig19(void) FAIL_IF_NULL(p); char sig[] = "alert tcp any any -> any any (msg:\"dummy\"; " - "content:\"|01 02 03 04|\"; " - "byte_extract:1,2,one,string,hex,relative; " - "content:\"|0C 0D 0E 0F|\"; distance:one; sid:1;)"; + "content:\"|01 02 03 04|\"; " + "byte_extract:1,2,one,string,hex,relative; " + "content:\"|0C 0D 0E 0F|\"; distance:one; sid:1;)"; FAIL_IF(UTHPacketMatchSigMpm(p, sig, mpm_default_matcher) == 0); @@ -822,9 +815,9 @@ static int PayloadTestSig20(void) FAIL_IF_NULL(p); char sig[] = "alert tcp any any -> any any (msg:\"dummy\"; " - "content:\"|01 02 03 04|\"; " - "byte_extract:1,2,one,string,dec,relative; " - "content:\"|06 35 07 08|\"; offset:one; sid:1;)"; + "content:\"|01 02 03 04|\"; " + "byte_extract:1,2,one,string,dec,relative; " + "content:\"|06 35 07 08|\"; offset:one; sid:1;)"; FAIL_IF(UTHPacketMatchSigMpm(p, sig, mpm_default_matcher) == 0); @@ -848,9 +841,9 @@ static int PayloadTestSig21(void) FAIL_IF_NULL(p); char sig[] = "alert tcp any any -> any any (msg:\"dummy\"; " - "content:\"|01 02 03 04|\"; " - "byte_extract:1,2,one,string,dec,relative; " - "content:\"|03 04 05 06|\"; depth:one; sid:1;)"; + "content:\"|01 02 03 04|\"; " + "byte_extract:1,2,one,string,dec,relative; " + "content:\"|03 04 05 06|\"; depth:one; sid:1;)"; FAIL_IF(UTHPacketMatchSigMpm(p, sig, mpm_default_matcher) == 0); @@ -874,9 +867,9 @@ static int PayloadTestSig22(void) FAIL_IF_NULL(p); char sig[] = "alert tcp any any -> any any (msg:\"dummy\"; " - "content:\"|01 02 03 04|\"; " - "byte_extract:1,2,one,string,dec,relative; " - "content:\"|09 0A 0B 0C|\"; within:one; sid:1;)"; + "content:\"|01 02 03 04|\"; " + "byte_extract:1,2,one,string,dec,relative; " + "content:\"|09 0A 0B 0C|\"; within:one; sid:1;)"; FAIL_IF(UTHPacketMatchSigMpm(p, sig, mpm_default_matcher) == 0); @@ -900,10 +893,10 @@ static int PayloadTestSig23(void) FAIL_IF_NULL(p); char sig[] = "alert tcp any any -> any any (msg:\"dummy\"; " - "content:\"|01 02 03 04|\"; " - "byte_extract:1,2,one,string,dec,relative; " - "byte_extract:1,3,two,string,dec,relative; " - "byte_test:1,=,one,two,string,dec,relative; sid:1;)"; + "content:\"|01 02 03 04|\"; " + "byte_extract:1,2,one,string,dec,relative; " + "byte_extract:1,3,two,string,dec,relative; " + "byte_test:1,=,one,two,string,dec,relative; sid:1;)"; FAIL_IF(UTHPacketMatchSigMpm(p, sig, mpm_default_matcher) == 0); @@ -927,10 +920,10 @@ static int PayloadTestSig24(void) FAIL_IF_NULL(p); char sig[] = "alert tcp any any -> any any (msg:\"dummy\"; " - "content:\"|01 02 03 04|\"; " - "byte_extract:1,2,one,string,dec,relative; " - "byte_jump:1,one,string,dec,relative; " - "content:\"|0D 0E 0F|\"; distance:0; sid:1;)"; + "content:\"|01 02 03 04|\"; " + "byte_extract:1,2,one,string,dec,relative; " + "byte_jump:1,one,string,dec,relative; " + "content:\"|0D 0E 0F|\"; distance:0; sid:1;)"; FAIL_IF(UTHPacketMatchSigMpm(p, sig, mpm_default_matcher) == 0); @@ -957,9 +950,9 @@ static int PayloadTestSig25(void) FAIL_IF_NULL(p); char sig[] = "alert tcp any any -> any any (msg:\"dummy\"; " - "content:\"|35 07 08 09|\"; " - "byte_extract:1,-4,one,string,dec,relative; " - "content:\"|0C 0D 0E 0F|\"; distance:one; sid:1;)"; + "content:\"|35 07 08 09|\"; " + "byte_extract:1,-4,one,string,dec,relative; " + "content:\"|0C 0D 0E 0F|\"; distance:one; sid:1;)"; FAIL_IF(UTHPacketMatchSigMpm(p, sig, mpm_default_matcher) == 0); @@ -986,9 +979,9 @@ static int PayloadTestSig26(void) FAIL_IF_NULL(p); char sig[] = "alert tcp any any -> any any (msg:\"dummy\"; " - "content:\"|35 07 08 09|\"; " - "byte_extract:1,-3000,one,string,dec,relative; " - "content:\"|0C 0D 0E 0F|\"; distance:one; sid:1;)"; + "content:\"|35 07 08 09|\"; " + "byte_extract:1,-3000,one,string,dec,relative; " + "content:\"|0C 0D 0E 0F|\"; distance:one; sid:1;)"; FAIL_IF(UTHPacketMatchSigMpm(p, sig, mpm_default_matcher) != 0); @@ -1009,7 +1002,7 @@ static int PayloadTestSig27(void) FAIL_IF_NULL(p); char sig[] = "alert tcp any any -> any any (content:\"dummy\"; " - "depth:5; sid:1;)"; + "depth:5; sid:1;)"; p->flags |= PKT_STREAM_ADD; FAIL_IF(UTHPacketMatchSigMpm(p, sig, mpm_default_matcher) != 1); @@ -1031,7 +1024,7 @@ static int PayloadTestSig28(void) FAIL_IF_NULL(p); char sig[] = "alert tcp any any -> any any (content:\"payload\"; " - "offset:4; depth:12; sid:1;)"; + "offset:4; depth:12; sid:1;)"; p->flags |= PKT_STREAM_ADD; FAIL_IF(UTHPacketMatchSigMpm(p, sig, mpm_default_matcher) != 1); @@ -1053,7 +1046,7 @@ static int PayloadTestSig29(void) FAIL_IF_NULL(p); char sig[] = "alert tcp any any -> any any (msg:\"dummy\"; " - "pcre:/^.{4}/; content:\"nova\"; within:4; sid:1;)"; + "pcre:/^.{4}/; content:\"nova\"; within:4; sid:1;)"; FAIL_IF(UTHPacketMatchSigMpm(p, sig, mpm_default_matcher) == 1); @@ -1064,8 +1057,7 @@ static int PayloadTestSig29(void) static int PayloadTestSig30(void) { - uint8_t *buf = (uint8_t *) - "xyonexxxxxxtwojunkonetwo"; + uint8_t *buf = (uint8_t *)"xyonexxxxxxtwojunkonetwo"; uint16_t buflen = strlen((char *)buf); Packet *p = UTHBuildPacket(buf, buflen, IPPROTO_TCP); @@ -1082,8 +1074,7 @@ static int PayloadTestSig30(void) static int PayloadTestSig31(void) { - uint8_t *buf = (uint8_t *) - "xyonexxxxxxtwojunkonetwo"; + uint8_t *buf = (uint8_t *)"xyonexxxxxxtwojunkonetwo"; uint16_t buflen = strlen((char *)buf); Packet *p = UTHBuildPacket(buf, buflen, IPPROTO_TCP); @@ -1110,7 +1101,8 @@ static int PayloadTestSig32(void) FAIL_IF_NULL(p); char sig[] = "alert tcp any any -> any any (msg:\"crash\"; " - "content:\"message\"; byte_jump:2,-14,string,dec,relative; content:\"card\"; within:4; sid:1;)"; + "content:\"message\"; byte_jump:2,-14,string,dec,relative; content:\"card\"; " + "within:4; sid:1;)"; FAIL_IF(UTHPacketMatchSigMpm(p, sig, mpm_default_matcher) == 0); @@ -1131,7 +1123,7 @@ static int PayloadTestSig33(void) FAIL_IF_NULL(p); char sig[] = "alert tcp any any -> any any (msg:\"crash\"; " - "content:\"message\"; byte_test:1,=,2,-14,string,dec,relative; sid:1;)"; + "content:\"message\"; byte_test:1,=,2,-14,string,dec,relative; sid:1;)"; FAIL_IF(UTHPacketMatchSigMpm(p, sig, mpm_default_matcher) == 0); @@ -1152,7 +1144,7 @@ static int PayloadTestSig34(void) FAIL_IF_NULL(p); char sig[] = "alert tcp any any -> any any (msg:\"crash\"; " - "content:\"message\"; byte_extract:1,-14,boom,string,dec,relative; sid:1;)"; + "content:\"message\"; byte_extract:1,-14,boom,string,dec,relative; sid:1;)"; FAIL_IF(UTHPacketMatchSigMpm(p, sig, mpm_default_matcher) == 0); diff --git a/src/detect-engine-payload.h b/src/detect-engine-payload.h index 7ef29db6c666..eb0bf98e9ca9 100644 --- a/src/detect-engine-payload.h +++ b/src/detect-engine-payload.h @@ -24,16 +24,13 @@ #ifndef __DETECT_ENGINE_PAYLOAD_H__ #define __DETECT_ENGINE_PAYLOAD_H__ -int PrefilterPktPayloadRegister(DetectEngineCtx *de_ctx, - SigGroupHead *sgh, MpmCtx *mpm_ctx); -int PrefilterPktStreamRegister(DetectEngineCtx *de_ctx, - SigGroupHead *sgh, MpmCtx *mpm_ctx); +int PrefilterPktPayloadRegister(DetectEngineCtx *de_ctx, SigGroupHead *sgh, MpmCtx *mpm_ctx); +int PrefilterPktStreamRegister(DetectEngineCtx *de_ctx, SigGroupHead *sgh, MpmCtx *mpm_ctx); uint8_t DetectEngineInspectPacketPayload( DetectEngineCtx *, DetectEngineThreadCtx *, const Signature *, Flow *, Packet *); -int DetectEngineInspectStreamPayload(DetectEngineCtx *, - DetectEngineThreadCtx *, const Signature *, Flow *, - Packet *); +int DetectEngineInspectStreamPayload( + DetectEngineCtx *, DetectEngineThreadCtx *, const Signature *, Flow *, Packet *); uint8_t DetectEngineInspectStream(DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx, const struct DetectEngineAppInspectionEngine_ *engine, const Signature *s, Flow *f, uint8_t flags, void *alstate, void *txv, uint64_t tx_id); @@ -41,4 +38,3 @@ uint8_t DetectEngineInspectStream(DetectEngineCtx *de_ctx, DetectEngineThreadCtx void PayloadRegisterTests(void); #endif /* __DETECT_ENGINE_PAYLOAD_H__ */ - diff --git a/src/detect-engine-port.c b/src/detect-engine-port.c index d6e38fb230b3..1461f4588528 100644 --- a/src/detect-engine-port.c +++ b/src/detect-engine-port.c @@ -54,8 +54,7 @@ #include "util-byte.h" static int DetectPortCutNot(DetectPort *, DetectPort **); -static int DetectPortCut(DetectEngineCtx *, DetectPort *, DetectPort *, - DetectPort **); +static int DetectPortCut(DetectEngineCtx *, DetectPort *, DetectPort *, DetectPort **); DetectPort *PortParse(const char *str); static bool DetectPortIsValidRange(char *, uint16_t *); @@ -106,9 +105,9 @@ void DetectPortPrintList(DetectPort *head) SCLogDebug("= list start:"); if (head != NULL) { for (cur = head; cur != NULL; cur = cur->next) { - DetectPortPrint(cur); + DetectPortPrint(cur); #ifdef DEBUG - cnt++; + cnt++; #endif } SCLogDebug(" "); @@ -121,14 +120,14 @@ void DetectPortPrintList(DetectPort *head) * * \param head Pointer to the DetectPort list head */ -void DetectPortCleanupList (const DetectEngineCtx *de_ctx, DetectPort *head) +void DetectPortCleanupList(const DetectEngineCtx *de_ctx, DetectPort *head) { if (head == NULL) return; DetectPort *cur, *next; - for (cur = head; cur != NULL; ) { + for (cur = head; cur != NULL;) { next = cur->next; cur->next = NULL; DetectPortFree(de_ctx, cur); @@ -150,14 +149,13 @@ void DetectPortCleanupList (const DetectEngineCtx *de_ctx, DetectPort *head) * * \todo rewrite to avoid recursive calls * */ -int DetectPortInsert(DetectEngineCtx *de_ctx, DetectPort **head, - DetectPort *new) +int DetectPortInsert(DetectEngineCtx *de_ctx, DetectPort **head, DetectPort *new) { if (new == NULL) return 0; - //BUG_ON(new->next != NULL); - //BUG_ON(new->prev != NULL); + // BUG_ON(new->next != NULL); + // BUG_ON(new->prev != NULL); /* see if it already exists or overlaps with existing ports */ if (*head != NULL) { @@ -165,7 +163,7 @@ int DetectPortInsert(DetectEngineCtx *de_ctx, DetectPort **head, int r = 0; for (cur = *head; cur != NULL; cur = cur->next) { - r = DetectPortCmp(new,cur); + r = DetectPortCmp(new, cur); BUG_ON(r == PORT_ER); /* if so, handle that */ @@ -206,8 +204,8 @@ int DetectPortInsert(DetectEngineCtx *de_ctx, DetectPort **head, } return 1; - /* alright, those were the simple cases, - * lets handle the more complex ones now */ + /* alright, those were the simple cases, + * lets handle the more complex ones now */ } else { DetectPort *c = NULL; @@ -233,11 +231,10 @@ int DetectPortInsert(DetectEngineCtx *de_ctx, DetectPort **head, goto error; } return 1; - } } - /* head is NULL, so get a group and set head to it */ + /* head is NULL, so get a group and set head to it */ } else { SCLogDebug("setting new head %p", new); *head = new; @@ -260,8 +257,7 @@ int DetectPortInsert(DetectEngineCtx *de_ctx, DetectPort **head, * \retval 0 ok * \retval -1 error * */ -static int DetectPortCut(DetectEngineCtx *de_ctx, DetectPort *a, - DetectPort *b, DetectPort **c) +static int DetectPortCut(DetectEngineCtx *de_ctx, DetectPort *a, DetectPort *b, DetectPort **c) { uint16_t a_port1 = a->port; uint16_t a_port2 = a->port2; @@ -271,7 +267,7 @@ static int DetectPortCut(DetectEngineCtx *de_ctx, DetectPort *a, /* default to NULL */ *c = NULL; - int r = DetectPortCmp(a,b); + int r = DetectPortCmp(a, b); BUG_ON(r != PORT_ES && r != PORT_EB && r != PORT_LE && r != PORT_GE); /* get a place to temporary put sigs lists */ @@ -303,15 +299,15 @@ static int DetectPortCut(DetectEngineCtx *de_ctx, DetectPort *a, tmp_c->port = a_port2 + 1; tmp_c->port2 = b_port2; - SigGroupHeadCopySigs(de_ctx,b->sh,&tmp_c->sh); /* copy old b to c */ - SigGroupHeadCopySigs(de_ctx,a->sh,&b->sh); /* copy a to b */ + SigGroupHeadCopySigs(de_ctx, b->sh, &tmp_c->sh); /* copy old b to c */ + SigGroupHeadCopySigs(de_ctx, a->sh, &b->sh); /* copy a to b */ - /** - * We have 3 parts: [bbb[baba]aaa] - * part a: b_port1 <-> a_port1 - 1 - * part b: a_port1 <-> b_port2 - * part c: b_port2 + 1 <-> a_port2 - */ + /** + * We have 3 parts: [bbb[baba]aaa] + * part a: b_port1 <-> a_port1 - 1 + * part b: a_port1 <-> b_port2 + * part c: b_port2 + 1 <-> a_port2 + */ } else if (r == PORT_GE) { SCLogDebug("cut r == PORT_GE"); a->port = b_port1; @@ -334,31 +330,31 @@ static int DetectPortCut(DetectEngineCtx *de_ctx, DetectPort *a, * 'b' gets clean, then 'a' then 'b' sigs * 'c' gets 'a' sigs */ - SigGroupHeadCopySigs(de_ctx,a->sh,&tmp->sh); /* store old a list */ - SigGroupHeadClearSigs(a->sh); /* clean a list */ - SigGroupHeadCopySigs(de_ctx,tmp->sh,&tmp_c->sh); /* copy old b to c */ - SigGroupHeadCopySigs(de_ctx,b->sh,&a->sh); /* copy old b to a */ - SigGroupHeadCopySigs(de_ctx,tmp->sh,&b->sh);/* prepend old a before b */ + SigGroupHeadCopySigs(de_ctx, a->sh, &tmp->sh); /* store old a list */ + SigGroupHeadClearSigs(a->sh); /* clean a list */ + SigGroupHeadCopySigs(de_ctx, tmp->sh, &tmp_c->sh); /* copy old b to c */ + SigGroupHeadCopySigs(de_ctx, b->sh, &a->sh); /* copy old b to a */ + SigGroupHeadCopySigs(de_ctx, tmp->sh, &b->sh); /* prepend old a before b */ SigGroupHeadClearSigs(tmp->sh); /* clean tmp list */ - /** - * We have 2 or three parts: - * - * 2 part: [[abab]bbb] or [bbb[baba]] - * part a: a_port1 <-> a_port2 - * part b: a_port2 + 1 <-> b_port2 - * - * part a: b_port1 <-> a_port1 - 1 - * part b: a_port1 <-> a_port2 - * - * 3 part [bbb[aaa]bbb] - * becomes[aaa[bbb]ccc] - * - * part a: b_port1 <-> a_port1 - 1 - * part b: a_port1 <-> a_port2 - * part c: a_port2 + 1 <-> b_port2 - */ + /** + * We have 2 or three parts: + * + * 2 part: [[abab]bbb] or [bbb[baba]] + * part a: a_port1 <-> a_port2 + * part b: a_port2 + 1 <-> b_port2 + * + * part a: b_port1 <-> a_port1 - 1 + * part b: a_port1 <-> a_port2 + * + * 3 part [bbb[aaa]bbb] + * becomes[aaa[bbb]ccc] + * + * part a: b_port1 <-> a_port1 - 1 + * part b: a_port1 <-> a_port2 + * part c: a_port2 + 1 <-> b_port2 + */ } else if (r == PORT_ES) { SCLogDebug("cut r == PORT_ES"); if (a_port1 == b_port1) { @@ -366,11 +362,11 @@ static int DetectPortCut(DetectEngineCtx *de_ctx, DetectPort *a, a->port = a_port1; a->port2 = a_port2; - b->port = a_port2 + 1; + b->port = a_port2 + 1; b->port2 = b_port2; /** 'b' overlaps 'a' so 'a' needs the 'b' sigs */ - SigGroupHeadCopySigs(de_ctx,b->sh,&a->sh); + SigGroupHeadCopySigs(de_ctx, b->sh, &a->sh); } else if (a_port2 == b_port2) { SCLogDebug("2"); @@ -386,11 +382,11 @@ static int DetectPortCut(DetectEngineCtx *de_ctx, DetectPort *a, * a overlaps b, so copy a to b * clear a * copy tmp to a */ - SigGroupHeadCopySigs(de_ctx,b->sh,&tmp->sh); /* store old a list */ - SigGroupHeadCopySigs(de_ctx,a->sh,&b->sh); - SigGroupHeadClearSigs(a->sh); /* clean a list */ - SigGroupHeadCopySigs(de_ctx,tmp->sh,&a->sh);/* merge old a with b */ - SigGroupHeadClearSigs(tmp->sh); /* clean tmp list */ + SigGroupHeadCopySigs(de_ctx, b->sh, &tmp->sh); /* store old a list */ + SigGroupHeadCopySigs(de_ctx, a->sh, &b->sh); + SigGroupHeadClearSigs(a->sh); /* clean a list */ + SigGroupHeadCopySigs(de_ctx, tmp->sh, &a->sh); /* merge old a with b */ + SigGroupHeadClearSigs(tmp->sh); /* clean tmp list */ } else { SCLogDebug("3"); a->port = b_port1; @@ -413,31 +409,31 @@ static int DetectPortCut(DetectEngineCtx *de_ctx, DetectPort *a, * 'b' gets clean, then 'a' then 'b' sigs * 'c' gets 'b' sigs */ - SigGroupHeadCopySigs(de_ctx,a->sh,&tmp->sh); /* store old a list */ - SigGroupHeadClearSigs(a->sh); /* clean a list */ - SigGroupHeadCopySigs(de_ctx,b->sh,&tmp_c->sh); /* copy old b to c */ - SigGroupHeadCopySigs(de_ctx,b->sh,&a->sh); /* copy old b to a */ - SigGroupHeadCopySigs(de_ctx,tmp->sh,&b->sh);/* merge old a with b */ + SigGroupHeadCopySigs(de_ctx, a->sh, &tmp->sh); /* store old a list */ + SigGroupHeadClearSigs(a->sh); /* clean a list */ + SigGroupHeadCopySigs(de_ctx, b->sh, &tmp_c->sh); /* copy old b to c */ + SigGroupHeadCopySigs(de_ctx, b->sh, &a->sh); /* copy old b to a */ + SigGroupHeadCopySigs(de_ctx, tmp->sh, &b->sh); /* merge old a with b */ SigGroupHeadClearSigs(tmp->sh); /* clean tmp list */ } - /** - * We have 2 or three parts: - * - * 2 part: [[baba]aaa] or [aaa[abab]] - * part a: b_port1 <-> b_port2 - * part b: b_port2 + 1 <-> a_port2 - * - * part a: a_port1 <-> b_port1 - 1 - * part b: b_port1 <-> b_port2 - * - * 3 part [aaa[bbb]aaa] - * becomes[aaa[bbb]ccc] - * - * part a: a_port1 <-> b_port2 - 1 - * part b: b_port1 <-> b_port2 - * part c: b_port2 + 1 <-> a_port2 - */ + /** + * We have 2 or three parts: + * + * 2 part: [[baba]aaa] or [aaa[abab]] + * part a: b_port1 <-> b_port2 + * part b: b_port2 + 1 <-> a_port2 + * + * part a: a_port1 <-> b_port1 - 1 + * part b: b_port1 <-> b_port2 + * + * 3 part [aaa[bbb]aaa] + * becomes[aaa[bbb]ccc] + * + * part a: a_port1 <-> b_port2 - 1 + * part b: b_port1 <-> b_port2 + * part c: b_port2 + 1 <-> a_port2 + */ } else if (r == PORT_EB) { SCLogDebug("cut r == PORT_EB"); if (a_port1 == b_port1) { @@ -449,10 +445,10 @@ static int DetectPortCut(DetectEngineCtx *de_ctx, DetectPort *a, b->port2 = a_port2; /** 'b' overlaps 'a' so 'a' needs the 'b' sigs */ - SigGroupHeadCopySigs(de_ctx,b->sh,&tmp->sh); + SigGroupHeadCopySigs(de_ctx, b->sh, &tmp->sh); SigGroupHeadClearSigs(b->sh); - SigGroupHeadCopySigs(de_ctx,a->sh,&b->sh); - SigGroupHeadCopySigs(de_ctx,tmp->sh,&a->sh); + SigGroupHeadCopySigs(de_ctx, a->sh, &b->sh); + SigGroupHeadCopySigs(de_ctx, tmp->sh, &a->sh); SigGroupHeadClearSigs(tmp->sh); @@ -466,7 +462,7 @@ static int DetectPortCut(DetectEngineCtx *de_ctx, DetectPort *a, b->port2 = b_port2; /** 'a' overlaps 'b' so 'b' needs the 'a' sigs */ - SigGroupHeadCopySigs(de_ctx,a->sh,&b->sh); + SigGroupHeadCopySigs(de_ctx, a->sh, &b->sh); } else { SCLogDebug("3"); @@ -485,8 +481,8 @@ static int DetectPortCut(DetectEngineCtx *de_ctx, DetectPort *a, tmp_c->port = b_port2 + 1; tmp_c->port2 = a_port2; - SigGroupHeadCopySigs(de_ctx,a->sh,&b->sh); - SigGroupHeadCopySigs(de_ctx,a->sh,&tmp_c->sh); + SigGroupHeadCopySigs(de_ctx, a->sh, &b->sh); + SigGroupHeadCopySigs(de_ctx, a->sh, &tmp_c->sh); } } @@ -572,27 +568,27 @@ int DetectPortCmp(DetectPort *a, DetectPort *b) /* PORT_EQ */ if (a_port1 == b_port1 && a_port2 == b_port2) { - //SCLogDebug("PORT_EQ"); + // SCLogDebug("PORT_EQ"); return PORT_EQ; - /* PORT_ES */ + /* PORT_ES */ } else if (a_port1 >= b_port1 && a_port1 <= b_port2 && a_port2 <= b_port2) { - //SCLogDebug("PORT_ES"); + // SCLogDebug("PORT_ES"); return PORT_ES; - /* PORT_EB */ + /* PORT_EB */ } else if (a_port1 <= b_port1 && a_port2 >= b_port2) { - //SCLogDebug("PORT_EB"); + // SCLogDebug("PORT_EB"); return PORT_EB; } else if (a_port1 < b_port1 && a_port2 < b_port2 && a_port2 >= b_port1) { - //SCLogDebug("PORT_LE"); + // SCLogDebug("PORT_LE"); return PORT_LE; } else if (a_port1 < b_port1 && a_port2 < b_port2) { - //SCLogDebug("PORT_LT"); + // SCLogDebug("PORT_LT"); return PORT_LT; } else if (a_port1 > b_port1 && a_port1 <= b_port2 && a_port2 > b_port2) { - //SCLogDebug("PORT_GE"); + // SCLogDebug("PORT_GE"); return PORT_GE; } else if (a_port1 > b_port2) { - //SCLogDebug("PORT_GT"); + // SCLogDebug("PORT_GT"); return PORT_GT; } else { /* should be unreachable */ @@ -611,7 +607,7 @@ int DetectPortCmp(DetectPort *a, DetectPort *b) * \retval Pointer to a DetectPort instance (copy of src) * \retval NULL on error * */ -DetectPort *DetectPortCopySingle(DetectEngineCtx *de_ctx,DetectPort *src) +DetectPort *DetectPortCopySingle(DetectEngineCtx *de_ctx, DetectPort *src) { if (src == NULL) return NULL; @@ -624,7 +620,7 @@ DetectPort *DetectPortCopySingle(DetectEngineCtx *de_ctx,DetectPort *src) dst->port = src->port; dst->port2 = src->port2; - SigGroupHeadCopySigs(de_ctx,src->sh,&dst->sh); + SigGroupHeadCopySigs(de_ctx, src->sh, &dst->sh); return dst; } @@ -639,8 +635,7 @@ DetectPort *DetectPortCopySingle(DetectEngineCtx *de_ctx,DetectPort *src) * */ static int DetectPortMatch(DetectPort *dp, uint16_t port) { - if (port >= dp->port && - port <= dp->port2) { + if (port >= dp->port && port <= dp->port2) { return 1; } @@ -658,10 +653,10 @@ void DetectPortPrint(DetectPort *dp) if (dp->flags & PORT_FLAG_ANY) { SCLogDebug("=> port %p: ANY", dp); -// printf("ANY"); + // printf("ANY"); } else { SCLogDebug("=> port %p %" PRIu32 "-%" PRIu32 "", dp, dp->port, dp->port2); -// printf("%" PRIu32 "-%" PRIu32 "", dp->port, dp->port2); + // printf("%" PRIu32 "-%" PRIu32 "", dp->port, dp->port2); } } @@ -681,8 +676,8 @@ DetectPort *DetectPortLookupGroup(DetectPort *dp, uint16_t port) for (DetectPort *p = dp; p != NULL; p = p->next) { if (DetectPortMatch(p, port) == 1) { - //SCLogDebug("match, port %" PRIu32 ", dp ", port); - //DetectPortPrint(p); SCLogDebug(""); + // SCLogDebug("match, port %" PRIu32 ", dp ", port); + // DetectPortPrint(p); SCLogDebug(""); return p; } } @@ -748,8 +743,8 @@ static int DetectPortParseInsert(DetectPort **head, DetectPort *new) * \retval 0 on success * \retval -1 on error */ -static int DetectPortParseInsertString(const DetectEngineCtx *de_ctx, - DetectPort **head, const char *s) +static int DetectPortParseInsertString( + const DetectEngineCtx *de_ctx, DetectPort **head, const char *s) { DetectPort *ad = NULL, *ad_any = NULL; int r = 0; @@ -781,7 +776,8 @@ static int DetectPortParseInsertString(const DetectEngineCtx *de_ctx, */ if (ad2 != NULL) { if (DetectPortParseInsert(head, ad2) < 0) { - if (ad2 != NULL) SCFree(ad2); + if (ad2 != NULL) + SCFree(ad2); goto error; } } @@ -800,7 +796,7 @@ static int DetectPortParseInsertString(const DetectEngineCtx *de_ctx, goto error; if (DetectPortParseInsert(head, ad_any) < 0) - goto error; + goto error; } return 0; @@ -836,10 +832,8 @@ static int DetectPortParseInsertString(const DetectEngineCtx *de_ctx, * \retval 0 On successfully parsing. * \retval -1 On failure. */ -static int DetectPortParseDo(const DetectEngineCtx *de_ctx, - DetectPort **head, DetectPort **nhead, - const char *s, int negate, - ResolvedVariablesList *var_list, int recur) +static int DetectPortParseDo(const DetectEngineCtx *de_ctx, DetectPort **head, DetectPort **nhead, + const char *s, int negate, ResolvedVariablesList *var_list, int recur) { size_t u = 0; size_t x = 0; @@ -885,8 +879,8 @@ static int DetectPortParseDo(const DetectEngineCtx *de_ctx, SCLogDebug("Parsed port from DetectPortParseDo - %s", address); x = 0; - r = DetectPortParseDo(de_ctx, head, nhead, address, - negate? negate: n_set, var_list, recur); + r = DetectPortParseDo( + de_ctx, head, nhead, address, negate ? negate : n_set, var_list, recur); if (r == -1) goto error; @@ -898,13 +892,11 @@ static int DetectPortParseDo(const DetectEngineCtx *de_ctx, if (o_set == 1) { o_set = 0; } else if (d_set == 1) { - char *temp_rule_var_port = NULL, - *alloc_rule_var_port = NULL; + char *temp_rule_var_port = NULL, *alloc_rule_var_port = NULL; address[x - 1] = '\0'; - rule_var_port = SCRuleVarsGetConfVar(de_ctx, address, - SC_RULE_VARS_PORT_GROUPS); + rule_var_port = SCRuleVarsGetConfVar(de_ctx, address, SC_RULE_VARS_PORT_GROUPS); if (rule_var_port == NULL) goto error; if (strlen(rule_var_port) == 0) { @@ -919,16 +911,15 @@ static int DetectPortParseDo(const DetectEngineCtx *de_ctx, alloc_rule_var_port = SCMalloc(strlen(rule_var_port) + 3); if (unlikely(alloc_rule_var_port == NULL)) goto error; - snprintf(alloc_rule_var_port, strlen(rule_var_port) + 3, - "[%s]", rule_var_port); + snprintf(alloc_rule_var_port, strlen(rule_var_port) + 3, "[%s]", rule_var_port); } else { alloc_rule_var_port = SCStrdup(rule_var_port); if (unlikely(alloc_rule_var_port == NULL)) goto error; } temp_rule_var_port = alloc_rule_var_port; - r = DetectPortParseDo(de_ctx, head, nhead, temp_rule_var_port, - (negate + n_set) % 2, var_list, recur); + r = DetectPortParseDo(de_ctx, head, nhead, temp_rule_var_port, (negate + n_set) % 2, + var_list, recur); if (r == -1) { SCFree(alloc_rule_var_port); goto error; @@ -954,7 +945,7 @@ static int DetectPortParseDo(const DetectEngineCtx *de_ctx, range = 0; } else if (depth == 0 && s[u] == '$') { d_set = 1; - } else if (depth == 0 && u == size-1) { + } else if (depth == 0 && u == size - 1) { range = 0; if (x == 1024) { address[x - 1] = '\0'; @@ -971,11 +962,9 @@ static int DetectPortParseDo(const DetectEngineCtx *de_ctx, x = 0; if (d_set == 1) { - char *temp_rule_var_port = NULL, - *alloc_rule_var_port = NULL; + char *temp_rule_var_port = NULL, *alloc_rule_var_port = NULL; - rule_var_port = SCRuleVarsGetConfVar(de_ctx, address, - SC_RULE_VARS_PORT_GROUPS); + rule_var_port = SCRuleVarsGetConfVar(de_ctx, address, SC_RULE_VARS_PORT_GROUPS); if (rule_var_port == NULL) goto error; if (strlen(rule_var_port) == 0) { @@ -990,16 +979,15 @@ static int DetectPortParseDo(const DetectEngineCtx *de_ctx, alloc_rule_var_port = SCMalloc(strlen(rule_var_port) + 3); if (unlikely(alloc_rule_var_port == NULL)) goto error; - snprintf(alloc_rule_var_port, strlen(rule_var_port) + 3, - "[%s]", rule_var_port); + snprintf(alloc_rule_var_port, strlen(rule_var_port) + 3, "[%s]", rule_var_port); } else { alloc_rule_var_port = SCStrdup(rule_var_port); if (unlikely(alloc_rule_var_port == NULL)) goto error; } temp_rule_var_port = alloc_rule_var_port; - r = DetectPortParseDo(de_ctx, head, nhead, temp_rule_var_port, - (negate + n_set) % 2, var_list, recur); + r = DetectPortParseDo(de_ctx, head, nhead, temp_rule_var_port, (negate + n_set) % 2, + var_list, recur); SCFree(alloc_rule_var_port); if (r == -1) goto error; @@ -1007,9 +995,9 @@ static int DetectPortParseDo(const DetectEngineCtx *de_ctx, d_set = 0; } else { if (!((negate + n_set) % 2)) { - r = DetectPortParseInsertString(de_ctx, head,address); + r = DetectPortParseInsertString(de_ctx, head, address); } else { - r = DetectPortParseInsertString(de_ctx, nhead,address); + r = DetectPortParseInsertString(de_ctx, nhead, address); } if (r == -1) goto error; @@ -1062,7 +1050,7 @@ static int DetectPortIsCompletePortSpace(DetectPort *p) next_port = p->port2 + 1; p = p->next; - for ( ; p != NULL; p = p->next) { + for (; p != NULL; p = p->next) { if (p->port != next_port) return 0; @@ -1084,8 +1072,8 @@ static int DetectPortIsCompletePortSpace(DetectPort *p) * \retval 0 on success * \retval -1 on error */ -static int DetectPortParseMergeNotPorts(const DetectEngineCtx *de_ctx, - DetectPort **head, DetectPort **nhead) +static int DetectPortParseMergeNotPorts( + const DetectEngineCtx *de_ctx, DetectPort **head, DetectPort **nhead) { DetectPort *ad = NULL; DetectPort *ag, *ag2; @@ -1104,7 +1092,7 @@ static int DetectPortParseMergeNotPorts(const DetectEngineCtx *de_ctx, */ if (*head == NULL && *nhead != NULL) { SCLogDebug("inserting 0:65535 into head"); - r = DetectPortParseInsertString(de_ctx, head,"0:65535"); + r = DetectPortParseInsertString(de_ctx, head, "0:65535"); if (r < 0) { goto error; } @@ -1131,7 +1119,7 @@ static int DetectPortParseMergeNotPorts(const DetectEngineCtx *de_ctx, SCLogDebug("ag %p", ag); DetectPortPrint(ag); - for (ag2 = *head; ag2 != NULL; ) { + for (ag2 = *head; ag2 != NULL;) { SCLogDebug("ag2 %p", ag2); DetectPortPrint(ag2); @@ -1145,7 +1133,7 @@ static int DetectPortParseMergeNotPorts(const DetectEngineCtx *de_ctx, *head = ag2->next; /** store the next ptr and remove the group */ DetectPort *next_ag2 = ag2->next; - DetectPortFree(de_ctx,ag2); + DetectPortFree(de_ctx, ag2); ag2 = next_ag2; } else { ag2 = ag2->next; @@ -1182,10 +1170,10 @@ int DetectPortTestConfVars(void) } ConfNode *seq_node; - TAILQ_FOREACH(seq_node, &port_vars_node->head, next) { + TAILQ_FOREACH (seq_node, &port_vars_node->head, next) { SCLogDebug("Testing %s - %s\n", seq_node->name, seq_node->val); - DetectPort *gh = DetectPortInit(); + DetectPort *gh = DetectPortInit(); if (gh == NULL) { goto error; } @@ -1201,7 +1189,7 @@ int DetectPortTestConfVars(void) } int r = DetectPortParseDo(NULL, &gh, &ghn, seq_node->val, - /* start with negate no */0, &var_list, 0); + /* start with negate no */ 0, &var_list, 0); CleanVariableResolveList(&var_list); @@ -1231,11 +1219,10 @@ int DetectPortTestConfVars(void) } return 0; - error: +error: return -1; } - /** * \brief Function for parsing port strings * @@ -1246,8 +1233,7 @@ int DetectPortTestConfVars(void) * \retval 0 on success * \retval -1 on error */ -int DetectPortParse(const DetectEngineCtx *de_ctx, - DetectPort **head, const char *str) +int DetectPortParse(const DetectEngineCtx *de_ctx, DetectPort **head, const char *str) { SCLogDebug("Port string to be parsed - str %s", str); @@ -1331,7 +1317,7 @@ DetectPort *PortParse(const char *str) if (dp->port > dp->port2) goto error; } else { - if (strcasecmp(port,"any") == 0) { + if (strcasecmp(port, "any") == 0) { dp->port = 0; dp->port2 = 65535; } else { @@ -1389,7 +1375,7 @@ static uint32_t DetectPortHashFunc(HashListTable *ht, void *data, uint16_t datal uint32_t hash = ((uint32_t)p->port << 16) | p->port2; hash %= ht->array_size; - SCLogDebug("hash %"PRIu32, hash); + SCLogDebug("hash %" PRIu32, hash); return hash; } @@ -1405,8 +1391,7 @@ static uint32_t DetectPortHashFunc(HashListTable *ht, void *data, uint16_t datal * \retval 1 If the 2 DetectPort sent as args match. * \retval 0 If the 2 DetectPort sent as args do not match. */ -static char DetectPortCompareFunc(void *data1, uint16_t len1, - void *data2, uint16_t len2) +static char DetectPortCompareFunc(void *data1, uint16_t len1, void *data2, uint16_t len2) { DetectPort *dp1 = (DetectPort *)data1; DetectPort *dp2 = (DetectPort *)data2; @@ -1437,9 +1422,8 @@ static void DetectPortHashFreeFunc(void *ptr) */ int DetectPortHashInit(DetectEngineCtx *de_ctx) { - de_ctx->dport_hash_table = HashListTableInit(4096, DetectPortHashFunc, - DetectPortCompareFunc, - DetectPortHashFreeFunc); + de_ctx->dport_hash_table = HashListTableInit( + 4096, DetectPortHashFunc, DetectPortCompareFunc, DetectPortHashFreeFunc); if (de_ctx->dport_hash_table == NULL) return -1; @@ -1516,12 +1500,12 @@ static int PortTestDetectPortAdd(DetectPort **head, DetectPort *dp) { DetectPort *cur, *prev_cur = NULL; - //SCLogDebug("DetectPortAdd: adding "); DetectPortPrint(ag); SCLogDebug(""); + // SCLogDebug("DetectPortAdd: adding "); DetectPortPrint(ag); SCLogDebug(""); if (*head != NULL) { for (cur = *head; cur != NULL; cur = cur->next) { prev_cur = cur; - int r = DetectPortCmp(dp,cur); + int r = DetectPortCmp(dp, cur); if (r == PORT_EB) { /* insert here */ dp->prev = cur->prev; @@ -1546,14 +1530,13 @@ static int PortTestDetectPortAdd(DetectPort **head, DetectPort *dp) return 0; } - /** * \test Check if a DetectPort is properly allocated */ -static int PortTestParse01 (void) +static int PortTestParse01(void) { DetectPort *dd = NULL; - int r = DetectPortParse(NULL,&dd,"80"); + int r = DetectPortParse(NULL, &dd, "80"); FAIL_IF_NOT(r == 0); DetectPortFree(NULL, dd); PASS; @@ -1562,12 +1545,12 @@ static int PortTestParse01 (void) /** * \test Check if two ports are properly allocated in the DetectPort group */ -static int PortTestParse02 (void) +static int PortTestParse02(void) { DetectPort *dd = NULL; - int r = DetectPortParse(NULL,&dd,"80"); + int r = DetectPortParse(NULL, &dd, "80"); FAIL_IF_NOT(r == 0); - r = DetectPortParse(NULL,&dd,"22"); + r = DetectPortParse(NULL, &dd, "22"); FAIL_IF_NOT(r == 0); DetectPortCleanupList(NULL, dd); PASS; @@ -1576,12 +1559,12 @@ static int PortTestParse02 (void) /** * \test Check if two port ranges are properly allocated in the DetectPort group */ -static int PortTestParse03 (void) +static int PortTestParse03(void) { DetectPort *dd = NULL; - int r = DetectPortParse(NULL,&dd,"80:88"); + int r = DetectPortParse(NULL, &dd, "80:88"); FAIL_IF_NOT(r == 0); - r = DetectPortParse(NULL,&dd,"85:100"); + r = DetectPortParse(NULL, &dd, "85:100"); FAIL_IF_NOT(r == 0); DetectPortCleanupList(NULL, dd); PASS; @@ -1590,10 +1573,10 @@ static int PortTestParse03 (void) /** * \test Check if a negated port range is properly allocated in the DetectPort */ -static int PortTestParse04 (void) +static int PortTestParse04(void) { DetectPort *dd = NULL; - int r = DetectPortParse(NULL,&dd,"!80:81"); + int r = DetectPortParse(NULL, &dd, "!80:81"); FAIL_IF_NOT(r == 0); DetectPortCleanupList(NULL, dd); PASS; @@ -1603,10 +1586,10 @@ static int PortTestParse04 (void) * \test Check if a negated port range is properly fragmented in the allowed * real groups, ex !80:81 should allow 0:79 and 82:65535 */ -static int PortTestParse05 (void) +static int PortTestParse05(void) { DetectPort *dd = NULL; - int r = DetectPortParse(NULL,&dd,"!80:81"); + int r = DetectPortParse(NULL, &dd, "!80:81"); FAIL_IF_NOT(r == 0); FAIL_IF_NULL(dd->next); FAIL_IF_NOT(dd->port == 0); @@ -1621,11 +1604,11 @@ static int PortTestParse05 (void) * \test Check if a negated port range is properly fragmented in the allowed * real groups */ -static int PortTestParse07 (void) +static int PortTestParse07(void) { DetectPort *dd = NULL; - int r = DetectPortParse(NULL,&dd,"!21:902"); + int r = DetectPortParse(NULL, &dd, "!21:902"); FAIL_IF_NOT(r == 0); FAIL_IF_NULL(dd->next); @@ -1641,11 +1624,11 @@ static int PortTestParse07 (void) /** * \test Check if we dont allow invalid port range specification */ -static int PortTestParse08 (void) +static int PortTestParse08(void) { DetectPort *dd = NULL; - int r = DetectPortParse(NULL,&dd,"[80:!80]"); + int r = DetectPortParse(NULL, &dd, "[80:!80]"); FAIL_IF(r == 0); DetectPortCleanupList(NULL, dd); @@ -1655,11 +1638,11 @@ static int PortTestParse08 (void) /** * \test Check if we autocomplete correctly an open range */ -static int PortTestParse09 (void) +static int PortTestParse09(void) { DetectPort *dd = NULL; - int r = DetectPortParse(NULL,&dd,"1024:"); + int r = DetectPortParse(NULL, &dd, "1024:"); FAIL_IF_NOT(r == 0); FAIL_IF_NULL(dd); @@ -1673,10 +1656,10 @@ static int PortTestParse09 (void) /** * \test Test we don't allow a port that is too big */ -static int PortTestParse10 (void) +static int PortTestParse10(void) { DetectPort *dd = NULL; - int r = DetectPortParse(NULL,&dd,"77777777777777777777777777777777777777777777"); + int r = DetectPortParse(NULL, &dd, "77777777777777777777777777777777777777777777"); FAIL_IF(r == 0); PASS; } @@ -1684,11 +1667,11 @@ static int PortTestParse10 (void) /** * \test Test second port of range being too big */ -static int PortTestParse11 (void) +static int PortTestParse11(void) { DetectPort *dd = NULL; - int r = DetectPortParse(NULL,&dd,"1024:65536"); + int r = DetectPortParse(NULL, &dd, "1024:65536"); FAIL_IF(r == 0); PASS; } @@ -1696,10 +1679,10 @@ static int PortTestParse11 (void) /** * \test Test second port of range being just right */ -static int PortTestParse12 (void) +static int PortTestParse12(void) { DetectPort *dd = NULL; - int r = DetectPortParse(NULL,&dd,"1024:65535"); + int r = DetectPortParse(NULL, &dd, "1024:65535"); FAIL_IF_NOT(r == 0); DetectPortFree(NULL, dd); PASS; @@ -1708,10 +1691,10 @@ static int PortTestParse12 (void) /** * \test Test first port of range being too big */ -static int PortTestParse13 (void) +static int PortTestParse13(void) { DetectPort *dd = NULL; - int r = DetectPortParse(NULL,&dd,"65536:65535"); + int r = DetectPortParse(NULL, &dd, "65536:65535"); FAIL_IF(r == 0); PASS; } @@ -1719,7 +1702,7 @@ static int PortTestParse13 (void) /** * \test Test merging port groups */ -static int PortTestParse14 (void) +static int PortTestParse14(void) { DetectPort *dd = NULL; @@ -1741,11 +1724,11 @@ static int PortTestParse14 (void) /** * \test Test merging negated port groups */ -static int PortTestParse15 (void) +static int PortTestParse15(void) { DetectPort *dd = NULL; - int r = DetectPortParse(NULL,&dd,"![0:100,1000:3000]"); + int r = DetectPortParse(NULL, &dd, "![0:100,1000:3000]"); FAIL_IF_NOT(r == 0); FAIL_IF_NULL(dd->next); @@ -1758,10 +1741,10 @@ static int PortTestParse15 (void) PASS; } -static int PortTestParse16 (void) +static int PortTestParse16(void) { DetectPort *dd = NULL; - int r = DetectPortParse(NULL,&dd,"\ + int r = DetectPortParse(NULL, &dd, "\ [[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[\ 1:65535\ ]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]\ @@ -1769,7 +1752,7 @@ static int PortTestParse16 (void) FAIL_IF_NOT(r == 0); DetectPortFree(NULL, dd); dd = NULL; - r = DetectPortParse(NULL,&dd,"\ + r = DetectPortParse(NULL, &dd, "\ [[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[\ 1:65535\ ]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]\ @@ -1784,11 +1767,11 @@ static int PortTestParse16 (void) static int PortTestFunctions01(void) { DetectPort *head = NULL; - DetectPort *dp1= NULL; + DetectPort *dp1 = NULL; int result = 0; /* Parse */ - int r = DetectPortParse(NULL,&head,"![0:100,1000:65535]"); + int r = DetectPortParse(NULL, &head, "![0:100,1000:65535]"); if (r != 0 || head->next != NULL) goto end; @@ -1800,7 +1783,7 @@ static int PortTestFunctions01(void) if (!(head->next == NULL)) goto end; - r = DetectPortParse(NULL, &dp1,"2000:3000"); + r = DetectPortParse(NULL, &dp1, "2000:3000"); if (r != 0 || dp1->next != NULL) goto end; if (!(dp1->port == 2000)) @@ -1846,12 +1829,12 @@ static int PortTestFunctions01(void) static int PortTestFunctions02(void) { DetectPort *head = NULL; - DetectPort *dp1= NULL; - DetectPort *dp2= NULL; + DetectPort *dp1 = NULL; + DetectPort *dp2 = NULL; int result = 0; /* Parse */ - int r = DetectPortParse(NULL,&head, "![0:100,1000:65535]"); + int r = DetectPortParse(NULL, &head, "![0:100,1000:65535]"); if (r != 0 || head->next != NULL) goto end; @@ -1895,9 +1878,9 @@ static int PortTestFunctions02(void) */ static int PortTestFunctions03(void) { - DetectPort *dp1= NULL; - DetectPort *dp2= NULL; - DetectPort *dp3= NULL; + DetectPort *dp1 = NULL; + DetectPort *dp2 = NULL; + DetectPort *dp3 = NULL; int result = 0; int r = DetectPortParse(NULL, &dp1, "200:300"); @@ -1961,8 +1944,8 @@ static int PortTestFunctions03(void) */ static int PortTestFunctions04(void) { - DetectPort *dp1= NULL; - DetectPort *dp2= NULL; + DetectPort *dp1 = NULL; + DetectPort *dp2 = NULL; int result = 0; int r = DetectPortParse(NULL, &dp1, "200:300"); @@ -2007,7 +1990,7 @@ static int PortTestFunctions05(void) DetectEngineCtx *de_ctx = DetectEngineCtxInit(); Signature s[2]; - memset(s,0x00,sizeof(s)); + memset(s, 0x00, sizeof(s)); s[0].num = 0; s[1].num = 1; @@ -2039,9 +2022,9 @@ static int PortTestFunctions05(void) SCLogDebug("dp3"); DetectPort *x = dp3; - for ( ; x != NULL; x = x->next) { + for (; x != NULL; x = x->next) { DetectPortPrint(x); - //SigGroupHeadPrintSigs(de_ctx, x->sh); + // SigGroupHeadPrintSigs(de_ctx, x->sh); } DetectPort *one = dp3; @@ -2085,7 +2068,7 @@ static int PortTestFunctions06(void) DetectEngineCtx *de_ctx = DetectEngineCtxInit(); Signature s[2]; - memset(s,0x00,sizeof(s)); + memset(s, 0x00, sizeof(s)); s[0].num = 0; s[1].num = 1; @@ -2117,9 +2100,9 @@ static int PortTestFunctions06(void) SCLogDebug("dp3"); DetectPort *x = dp3; - for ( ; x != NULL; x = x->next) { + for (; x != NULL; x = x->next) { DetectPortPrint(x); - //SigGroupHeadPrintSigs(de_ctx, x->sh); + // SigGroupHeadPrintSigs(de_ctx, x->sh); } DetectPort *one = dp3; @@ -2187,8 +2170,7 @@ static int PortTestFunctions07(void) * \retval return 1 if match * \retval return 0 if not */ -static int PortTestMatchReal(uint8_t *raw_eth_pkt, uint16_t pktsize, const char *sig, - uint32_t sid) +static int PortTestMatchReal(uint8_t *raw_eth_pkt, uint16_t pktsize, const char *sig, uint32_t sid) { int result = 0; FlowInitConfig(FLOW_QUIET); @@ -2266,10 +2248,9 @@ static int PortTestMatchRealWrp(const char *sig, uint32_t sid) 0x6b,0x65,0x65,0x70,0x2d,0x61,0x6c,0x69, 0x76,0x65,0x0d,0x0a,0x0d,0x0a }; // clang-format on - /* end raw_eth_pkt */ + /* end raw_eth_pkt */ - return PortTestMatchReal(raw_eth_pkt, (uint16_t)sizeof(raw_eth_pkt), - sig, sid); + return PortTestMatchReal(raw_eth_pkt, (uint16_t)sizeof(raw_eth_pkt), sig, sid); } /** @@ -2288,7 +2269,7 @@ static int PortTestMatchReal01(void) static int PortTestMatchReal02(void) { const char *sig = "alert tcp any 47370 -> any any (msg:\"Nothing..\";" - " content:\"GET\"; sid:1;)"; + " content:\"GET\"; sid:1;)"; return PortTestMatchRealWrp(sig, 1); } @@ -2298,7 +2279,7 @@ static int PortTestMatchReal02(void) static int PortTestMatchReal03(void) { const char *sig = "alert tcp any 47370 -> any 80 (msg:\"Nothing..\";" - " content:\"GET\"; sid:1;)"; + " content:\"GET\"; sid:1;)"; return PortTestMatchRealWrp(sig, 1); } @@ -2308,8 +2289,8 @@ static int PortTestMatchReal03(void) static int PortTestMatchReal04(void) { const char *sig = "alert tcp any any -> any !80 (msg:\"Nothing..\";" - " content:\"GET\"; sid:1;)"; - return (PortTestMatchRealWrp(sig, 1) == 0)? 1 : 0; + " content:\"GET\"; sid:1;)"; + return (PortTestMatchRealWrp(sig, 1) == 0) ? 1 : 0; } /** @@ -2318,8 +2299,8 @@ static int PortTestMatchReal04(void) static int PortTestMatchReal05(void) { const char *sig = "alert tcp any !47370 -> any any (msg:\"Nothing..\";" - " content:\"GET\"; sid:1;)"; - return (PortTestMatchRealWrp(sig, 1) == 0)? 1 : 0; + " content:\"GET\"; sid:1;)"; + return (PortTestMatchRealWrp(sig, 1) == 0) ? 1 : 0; } /** @@ -2328,8 +2309,8 @@ static int PortTestMatchReal05(void) static int PortTestMatchReal06(void) { const char *sig = "alert tcp any !47370 -> any !80 (msg:\"Nothing..\";" - " content:\"GET\"; sid:1;)"; - return (PortTestMatchRealWrp(sig, 1) == 0)? 1 : 0; + " content:\"GET\"; sid:1;)"; + return (PortTestMatchRealWrp(sig, 1) == 0) ? 1 : 0; } /** @@ -2338,7 +2319,7 @@ static int PortTestMatchReal06(void) static int PortTestMatchReal07(void) { const char *sig = "alert tcp any any -> any 70:100 (msg:\"Nothing..\";" - " content:\"GET\"; sid:1;)"; + " content:\"GET\"; sid:1;)"; return PortTestMatchRealWrp(sig, 1); } @@ -2348,7 +2329,7 @@ static int PortTestMatchReal07(void) static int PortTestMatchReal08(void) { const char *sig = "alert tcp any 47000:50000 -> any any (msg:\"Nothing..\";" - " content:\"GET\"; sid:1;)"; + " content:\"GET\"; sid:1;)"; return PortTestMatchRealWrp(sig, 1); } @@ -2358,7 +2339,7 @@ static int PortTestMatchReal08(void) static int PortTestMatchReal09(void) { const char *sig = "alert tcp any 47000:50000 -> any 70:100 (msg:\"Nothing..\";" - " content:\"GET\"; sid:1;)"; + " content:\"GET\"; sid:1;)"; return PortTestMatchRealWrp(sig, 1); } @@ -2368,8 +2349,8 @@ static int PortTestMatchReal09(void) static int PortTestMatchReal10(void) { const char *sig = "alert tcp any any -> any !70:100 (msg:\"Nothing..\";" - " content:\"GET\"; sid:1;)"; - return (PortTestMatchRealWrp(sig, 1) == 0)? 1 : 0; + " content:\"GET\"; sid:1;)"; + return (PortTestMatchRealWrp(sig, 1) == 0) ? 1 : 0; } /** @@ -2378,8 +2359,8 @@ static int PortTestMatchReal10(void) static int PortTestMatchReal11(void) { const char *sig = "alert tcp any !47000:50000 -> any any (msg:\"Nothing..\";" - " content:\"GET\"; sid:1;)"; - return (PortTestMatchRealWrp(sig, 1) == 0)? 1 : 0; + " content:\"GET\"; sid:1;)"; + return (PortTestMatchRealWrp(sig, 1) == 0) ? 1 : 0; } /** @@ -2388,8 +2369,8 @@ static int PortTestMatchReal11(void) static int PortTestMatchReal12(void) { const char *sig = "alert tcp any !47000:50000 -> any !70:100 (msg:\"Nothing..\";" - " content:\"GET\"; sid:1;)"; - return (PortTestMatchRealWrp(sig, 1) == 0)? 1 : 0; + " content:\"GET\"; sid:1;)"; + return (PortTestMatchRealWrp(sig, 1) == 0) ? 1 : 0; } /** @@ -2398,7 +2379,7 @@ static int PortTestMatchReal12(void) static int PortTestMatchReal13(void) { const char *sig = "alert tcp any 47000:50000 -> any !81: (msg:\"Nothing..\";" - " content:\"GET\"; sid:1;)"; + " content:\"GET\"; sid:1;)"; return PortTestMatchRealWrp(sig, 1); } @@ -2408,7 +2389,7 @@ static int PortTestMatchReal13(void) static int PortTestMatchReal14(void) { const char *sig = "alert tcp any !48000:50000 -> any :100 (msg:\"Nothing..\";" - " content:\"GET\"; sid:1;)"; + " content:\"GET\"; sid:1;)"; return PortTestMatchRealWrp(sig, 1); } @@ -2418,8 +2399,8 @@ static int PortTestMatchReal14(void) static int PortTestMatchReal15(void) { const char *sig = "alert tcp any :50000 -> any 81:100 (msg:\"Nothing..\";" - " content:\"GET\"; sid:1;)"; - return (PortTestMatchRealWrp(sig, 1) == 0)? 1 : 0; + " content:\"GET\"; sid:1;)"; + return (PortTestMatchRealWrp(sig, 1) == 0) ? 1 : 0; } /** @@ -2428,7 +2409,7 @@ static int PortTestMatchReal15(void) static int PortTestMatchReal16(void) { const char *sig = "alert tcp any 100: -> any ![0:79,81:65535] (msg:\"Nothing..\";" - " content:\"GET\"; sid:1;)"; + " content:\"GET\"; sid:1;)"; return PortTestMatchRealWrp(sig, 1); } @@ -2438,8 +2419,8 @@ static int PortTestMatchReal16(void) static int PortTestMatchReal17(void) { const char *sig = "alert tcp any ![0:39999,48000:50000] -> any ![0:80,82:65535] " - "(msg:\"Nothing..\"; content:\"GET\"; sid:1;)"; - return (PortTestMatchRealWrp(sig, 1) == 0)? 1 : 0; + "(msg:\"Nothing..\"; content:\"GET\"; sid:1;)"; + return (PortTestMatchRealWrp(sig, 1) == 0) ? 1 : 0; } /** @@ -2448,7 +2429,7 @@ static int PortTestMatchReal17(void) static int PortTestMatchReal18(void) { const char *sig = "alert tcp any ![0:39999,48000:50000] -> any 80 (msg:\"Nothing" - " at all\"; content:\"GET\"; sid:1;)"; + " at all\"; content:\"GET\"; sid:1;)"; return PortTestMatchRealWrp(sig, 1); } @@ -2458,7 +2439,7 @@ static int PortTestMatchReal18(void) static int PortTestMatchReal19(void) { const char *sig = "alert tcp any any -> any 80 (msg:\"Nothing..\";" - " content:\"GET\"; sid:1;)"; + " content:\"GET\"; sid:1;)"; return PortTestMatchRealWrp(sig, 1); } @@ -2602,4 +2583,3 @@ void DetectPortTests(void) } #endif /* UNITTESTS */ - diff --git a/src/detect-engine-port.h b/src/detect-engine-port.h index d27dff3d307f..82b621d2f18d 100644 --- a/src/detect-engine-port.h +++ b/src/detect-engine-port.h @@ -28,8 +28,8 @@ int DetectPortParse(const DetectEngineCtx *, DetectPort **head, const char *str); DetectPort *DetectPortCopySingle(DetectEngineCtx *, DetectPort *); -int DetectPortInsert(DetectEngineCtx *,DetectPort **, DetectPort *); -void DetectPortCleanupList (const DetectEngineCtx *de_ctx, DetectPort *head); +int DetectPortInsert(DetectEngineCtx *, DetectPort **, DetectPort *); +void DetectPortCleanupList(const DetectEngineCtx *de_ctx, DetectPort *head); DetectPort *DetectPortLookupGroup(DetectPort *dp, uint16_t port); @@ -52,4 +52,3 @@ void DetectPortTests(void); #endif #endif /* __DETECT_PORT_H__ */ - diff --git a/src/detect-engine-prefilter-common.c b/src/detect-engine-prefilter-common.c index 15df839b0c94..269c9af0509e 100644 --- a/src/detect-engine-prefilter-common.c +++ b/src/detect-engine-prefilter-common.c @@ -22,7 +22,7 @@ typedef struct PrefilterPacketHeaderHashCtx_ { PrefilterPacketHeaderValue v1; - uint16_t type; /**< PREFILTER_EXTRA_MATCH_* */ + uint16_t type; /**< PREFILTER_EXTRA_MATCH_* */ uint16_t value; uint32_t cnt; @@ -36,15 +36,12 @@ static uint32_t PrefilterPacketHeaderHashFunc(HashListTable *ht, void *data, uin return hash; } -static char PrefilterPacketHeaderCompareFunc(void *data1, uint16_t len1, - void *data2, uint16_t len2) +static char PrefilterPacketHeaderCompareFunc(void *data1, uint16_t len1, void *data2, uint16_t len2) { PrefilterPacketHeaderHashCtx *ctx1 = data1; PrefilterPacketHeaderHashCtx *ctx2 = data2; - return (ctx1->v1.u64[0] == ctx2->v1.u64[0] && - ctx1->v1.u64[1] == ctx2->v1.u64[1] && - ctx1->type == ctx2->type && - ctx1->value == ctx2->value); + return (ctx1->v1.u64[0] == ctx2->v1.u64[0] && ctx1->v1.u64[1] == ctx2->v1.u64[1] && + ctx1->type == ctx2->type && ctx1->value == ctx2->value); } static void PrefilterPacketHeaderFreeFunc(void *ptr) @@ -76,16 +73,14 @@ static void PrefilterPacketU8HashCtxFree(void *vctx) static void GetExtraMatch(const Signature *s, uint16_t *type, uint16_t *value) { if (s->sp != NULL && s->sp->next == NULL && s->sp->port == s->sp->port2 && - !(s->sp->flags & PORT_FLAG_NOT)) - { + !(s->sp->flags & PORT_FLAG_NOT)) { *type = PREFILTER_EXTRA_MATCH_SRCPORT; *value = s->sp->port; } else if (s->alproto != ALPROTO_UNKNOWN) { *type = PREFILTER_EXTRA_MATCH_ALPROTO; *value = s->alproto; } else if (s->dp != NULL && s->dp->next == NULL && s->dp->port == s->dp->port2 && - !(s->dp->flags & PORT_FLAG_NOT)) - { + !(s->dp->flags & PORT_FLAG_NOT)) { *type = PREFILTER_EXTRA_MATCH_DSTPORT; *value = s->dp->port; } @@ -93,10 +88,8 @@ static void GetExtraMatch(const Signature *s, uint16_t *type, uint16_t *value) /** \internal */ -static int -SetupEngineForPacketHeader(DetectEngineCtx *de_ctx, SigGroupHead *sgh, - int sm_type, PrefilterPacketHeaderHashCtx *hctx, - bool (*Compare)(PrefilterPacketHeaderValue v, void *), +static int SetupEngineForPacketHeader(DetectEngineCtx *de_ctx, SigGroupHead *sgh, int sm_type, + PrefilterPacketHeaderHashCtx *hctx, bool (*Compare)(PrefilterPacketHeaderValue v, void *), void (*Match)(DetectEngineThreadCtx *det_ctx, Packet *p, const void *pectx)) { Signature *s = NULL; @@ -129,9 +122,8 @@ SetupEngineForPacketHeader(DetectEngineCtx *de_ctx, SigGroupHead *sgh, uint16_t value = 0; GetExtraMatch(s, &type, &value); - if (Compare(ctx->v1, s->init_data->prefilter_sm->ctx) && - ctx->type == type && ctx->value == value) - { + if (Compare(ctx->v1, s->init_data->prefilter_sm->ctx) && ctx->type == type && + ctx->value == value) { SCLogDebug("appending sid %u on %u", s->id, sig_offset); ctx->sigs_array[sig_offset] = s->num; sig_offset++; @@ -140,11 +132,10 @@ SetupEngineForPacketHeader(DetectEngineCtx *de_ctx, SigGroupHead *sgh, } } - SCLogDebug("%s: ctx %p extra type %u extra value %u, sig cnt %u", - sigmatch_table[sm_type].name, ctx, ctx->type, ctx->value, - ctx->sigs_cnt); - PrefilterAppendEngine(de_ctx, sgh, Match, ctx, - PrefilterPacketHeaderFree, sigmatch_table[sm_type].name); + SCLogDebug("%s: ctx %p extra type %u extra value %u, sig cnt %u", sigmatch_table[sm_type].name, + ctx, ctx->type, ctx->value, ctx->sigs_cnt); + PrefilterAppendEngine( + de_ctx, sgh, Match, ctx, PrefilterPacketHeaderFree, sigmatch_table[sm_type].name); return 0; } @@ -153,42 +144,38 @@ SetupEngineForPacketHeader(DetectEngineCtx *de_ctx, SigGroupHead *sgh, static void ApplyToU8Hash(PrefilterPacketU8HashCtx *ctx, PrefilterPacketHeaderValue v, Signature *s) { switch (v.u8[0]) { - case PREFILTER_U8HASH_MODE_EQ: - { - SigsArray *sa = ctx->array[v.u8[1]]; + case PREFILTER_U8HASH_MODE_EQ: { + SigsArray *sa = ctx->array[v.u8[1]]; + sa->sigs[sa->offset++] = s->num; + break; + } + case PREFILTER_U8HASH_MODE_LT: { + uint8_t x = v.u8[1] - 1; + do { + SigsArray *sa = ctx->array[x]; sa->sigs[sa->offset++] = s->num; - break; - } - case PREFILTER_U8HASH_MODE_LT: - { - uint8_t x = v.u8[1] - 1; - do { - SigsArray *sa = ctx->array[x]; - sa->sigs[sa->offset++] = s->num; - } while (x--); + } while (x--); - break; - } - case PREFILTER_U8HASH_MODE_GT: - { - int x = v.u8[1] + 1; - do { - SigsArray *sa = ctx->array[x]; - sa->sigs[sa->offset++] = s->num; - } while (++x < 256); + break; + } + case PREFILTER_U8HASH_MODE_GT: { + int x = v.u8[1] + 1; + do { + SigsArray *sa = ctx->array[x]; + sa->sigs[sa->offset++] = s->num; + } while (++x < 256); - break; - } - case PREFILTER_U8HASH_MODE_RA: - { - int x = v.u8[1] + 1; - do { - SigsArray *sa = ctx->array[x]; - sa->sigs[sa->offset++] = s->num; - } while (++x < v.u8[2]); + break; + } + case PREFILTER_U8HASH_MODE_RA: { + int x = v.u8[1] + 1; + do { + SigsArray *sa = ctx->array[x]; + sa->sigs[sa->offset++] = s->num; + } while (++x < v.u8[2]); - break; - } + break; + } } } @@ -197,8 +184,7 @@ static void ApplyToU8Hash(PrefilterPacketU8HashCtx *ctx, PrefilterPacketHeaderVa * \todo improve error handling * \todo deduplicate sigs arrays */ -static int -SetupEngineForPacketHeaderPrefilterPacketU8HashCtx(DetectEngineCtx *de_ctx, +static int SetupEngineForPacketHeaderPrefilterPacketU8HashCtx(DetectEngineCtx *de_ctx, SigGroupHead *sgh, int sm_type, uint32_t *counts, void (*Set)(PrefilterPacketHeaderValue *v, void *), bool (*Compare)(PrefilterPacketHeaderValue v, void *), @@ -247,8 +233,7 @@ SetupEngineForPacketHeaderPrefilterPacketU8HashCtx(DetectEngineCtx *de_ctx, } if (cnt) { - PrefilterAppendEngine(de_ctx, sgh, Match, ctx, - PrefilterPacketU8HashCtxFree, + PrefilterAppendEngine(de_ctx, sgh, Match, ctx, PrefilterPacketU8HashCtxFree, sigmatch_table[sm_type].name); } else { PrefilterPacketU8HashCtxFree(ctx); @@ -259,44 +244,38 @@ SetupEngineForPacketHeaderPrefilterPacketU8HashCtx(DetectEngineCtx *de_ctx, /** \internal * \brief setup a engine for each unique value */ -static void SetupSingle(DetectEngineCtx *de_ctx, HashListTable *hash_table, - SigGroupHead *sgh, int sm_type, - bool (*Compare)(PrefilterPacketHeaderValue v, void *), - void (*Match)(DetectEngineThreadCtx *det_ctx, - Packet *p, const void *pectx)) +static void SetupSingle(DetectEngineCtx *de_ctx, HashListTable *hash_table, SigGroupHead *sgh, + int sm_type, bool (*Compare)(PrefilterPacketHeaderValue v, void *), + void (*Match)(DetectEngineThreadCtx *det_ctx, Packet *p, const void *pectx)) { HashListTableBucket *hb = HashListTableGetListHead(hash_table); - for ( ; hb != NULL; hb = HashListTableGetListNext(hb)) { + for (; hb != NULL; hb = HashListTableGetListNext(hb)) { PrefilterPacketHeaderHashCtx *ctx = HashListTableGetListData(hb); - SetupEngineForPacketHeader(de_ctx, sgh, sm_type, - ctx, Compare, Match); + SetupEngineForPacketHeader(de_ctx, sgh, sm_type, ctx, Compare, Match); } } /** \internal * \brief setup a single engine with a hash map for u8 values */ -static void SetupU8Hash(DetectEngineCtx *de_ctx, HashListTable *hash_table, - SigGroupHead *sgh, int sm_type, - void (*Set)(PrefilterPacketHeaderValue *v, void *), +static void SetupU8Hash(DetectEngineCtx *de_ctx, HashListTable *hash_table, SigGroupHead *sgh, + int sm_type, void (*Set)(PrefilterPacketHeaderValue *v, void *), bool (*Compare)(PrefilterPacketHeaderValue v, void *), - void (*Match)(DetectEngineThreadCtx *det_ctx, - Packet *p, const void *pectx)) + void (*Match)(DetectEngineThreadCtx *det_ctx, Packet *p, const void *pectx)) { uint32_t counts[256]; memset(&counts, 0, sizeof(counts)); HashListTableBucket *hb = HashListTableGetListHead(hash_table); - for ( ; hb != NULL; hb = HashListTableGetListNext(hb)) { + for (; hb != NULL; hb = HashListTableGetListNext(hb)) { PrefilterPacketHeaderHashCtx *ctx = HashListTableGetListData(hb); switch (ctx->v1.u8[0]) { case PREFILTER_U8HASH_MODE_EQ: counts[ctx->v1.u8[1]] += ctx->cnt; break; - case PREFILTER_U8HASH_MODE_LT: - { + case PREFILTER_U8HASH_MODE_LT: { uint8_t v = ctx->v1.u8[1]; while (v > 0) { v--; @@ -305,8 +284,7 @@ static void SetupU8Hash(DetectEngineCtx *de_ctx, HashListTable *hash_table, break; } - case PREFILTER_U8HASH_MODE_GT: - { + case PREFILTER_U8HASH_MODE_GT: { uint8_t v = ctx->v1.u8[1]; while (v < UINT8_MAX) { v++; @@ -315,8 +293,7 @@ static void SetupU8Hash(DetectEngineCtx *de_ctx, HashListTable *hash_table, break; } - case PREFILTER_U8HASH_MODE_RA: - { + case PREFILTER_U8HASH_MODE_RA: { if (ctx->v1.u8[1] < ctx->v1.u8[2]) { // ctx->v1.u8[1] is not UINT8_MAX uint8_t v = ctx->v1.u8[1] + 1; @@ -330,17 +307,14 @@ static void SetupU8Hash(DetectEngineCtx *de_ctx, HashListTable *hash_table, } } - SetupEngineForPacketHeaderPrefilterPacketU8HashCtx(de_ctx, sgh, sm_type, - counts, Set, Compare, Match); + SetupEngineForPacketHeaderPrefilterPacketU8HashCtx( + de_ctx, sgh, sm_type, counts, Set, Compare, Match); } -static int PrefilterSetupPacketHeaderCommon(DetectEngineCtx *de_ctx, - SigGroupHead *sgh, int sm_type, +static int PrefilterSetupPacketHeaderCommon(DetectEngineCtx *de_ctx, SigGroupHead *sgh, int sm_type, void (*Set)(PrefilterPacketHeaderValue *v, void *), bool (*Compare)(PrefilterPacketHeaderValue v, void *), - void (*Match)(DetectEngineThreadCtx *det_ctx, - Packet *p, const void *pectx), - bool u8hash) + void (*Match)(DetectEngineThreadCtx *det_ctx, Packet *p, const void *pectx), bool u8hash) { Signature *s = NULL; uint32_t sig = 0; @@ -350,10 +324,8 @@ static int PrefilterSetupPacketHeaderCommon(DetectEngineCtx *de_ctx, /* first count how many engines we will need */ - HashListTable *hash_table = HashListTableInit(4096, - PrefilterPacketHeaderHashFunc, - PrefilterPacketHeaderCompareFunc, - PrefilterPacketHeaderFreeFunc); + HashListTable *hash_table = HashListTableInit(4096, PrefilterPacketHeaderHashFunc, + PrefilterPacketHeaderCompareFunc, PrefilterPacketHeaderFreeFunc); if (hash_table == NULL) return -1; @@ -404,22 +376,18 @@ static int PrefilterSetupPacketHeaderCommon(DetectEngineCtx *de_ctx, return -1; } -int PrefilterSetupPacketHeaderU8Hash(DetectEngineCtx *de_ctx, - SigGroupHead *sgh, int sm_type, +int PrefilterSetupPacketHeaderU8Hash(DetectEngineCtx *de_ctx, SigGroupHead *sgh, int sm_type, void (*Set)(PrefilterPacketHeaderValue *v, void *), bool (*Compare)(PrefilterPacketHeaderValue v, void *), - void (*Match)(DetectEngineThreadCtx *det_ctx, - Packet *p, const void *pectx)) + void (*Match)(DetectEngineThreadCtx *det_ctx, Packet *p, const void *pectx)) { return PrefilterSetupPacketHeaderCommon(de_ctx, sgh, sm_type, Set, Compare, Match, true); } -int PrefilterSetupPacketHeader(DetectEngineCtx *de_ctx, - SigGroupHead *sgh, int sm_type, +int PrefilterSetupPacketHeader(DetectEngineCtx *de_ctx, SigGroupHead *sgh, int sm_type, void (*Set)(PrefilterPacketHeaderValue *v, void *), bool (*Compare)(PrefilterPacketHeaderValue v, void *), - void (*Match)(DetectEngineThreadCtx *det_ctx, - Packet *p, const void *pectx)) + void (*Match)(DetectEngineThreadCtx *det_ctx, Packet *p, const void *pectx)) { return PrefilterSetupPacketHeaderCommon(de_ctx, sgh, sm_type, Set, Compare, Match, false); } diff --git a/src/detect-engine-prefilter-common.h b/src/detect-engine-prefilter-common.h index f5ea76521527..31302f80ad4d 100644 --- a/src/detect-engine-prefilter-common.h +++ b/src/detect-engine-prefilter-common.h @@ -58,26 +58,20 @@ typedef struct PrefilterPacketU8HashCtx_ { #define PREFILTER_U8HASH_MODE_GT DetectUintModeGt #define PREFILTER_U8HASH_MODE_RA DetectUintModeRange -int PrefilterSetupPacketHeader(DetectEngineCtx *de_ctx, - SigGroupHead *sgh, int sm_type, +int PrefilterSetupPacketHeader(DetectEngineCtx *de_ctx, SigGroupHead *sgh, int sm_type, void (*Set)(PrefilterPacketHeaderValue *v, void *), bool (*Compare)(PrefilterPacketHeaderValue v, void *), - void (*Match)(DetectEngineThreadCtx *det_ctx, - Packet *p, const void *pectx)); + void (*Match)(DetectEngineThreadCtx *det_ctx, Packet *p, const void *pectx)); -int PrefilterSetupPacketHeaderU8Hash(DetectEngineCtx *de_ctx, - SigGroupHead *sgh, int sm_type, +int PrefilterSetupPacketHeaderU8Hash(DetectEngineCtx *de_ctx, SigGroupHead *sgh, int sm_type, void (*Set)(PrefilterPacketHeaderValue *v, void *), bool (*Compare)(PrefilterPacketHeaderValue v, void *), - void (*Match)(DetectEngineThreadCtx *det_ctx, - Packet *p, const void *pectx)); + void (*Match)(DetectEngineThreadCtx *det_ctx, Packet *p, const void *pectx)); -static inline bool -PrefilterPacketHeaderExtraMatch(const PrefilterPacketHeaderCtx *ctx, - const Packet *p) +static inline bool PrefilterPacketHeaderExtraMatch( + const PrefilterPacketHeaderCtx *ctx, const Packet *p) { - switch (ctx->type) - { + switch (ctx->type) { case PREFILTER_EXTRA_MATCH_UNUSED: break; case PREFILTER_EXTRA_MATCH_ALPROTO: @@ -99,7 +93,7 @@ PrefilterPacketHeaderExtraMatch(const PrefilterPacketHeaderCtx *ctx, static inline bool PrefilterIsPrefilterableById(const Signature *s, enum DetectKeywordId kid) { const SigMatch *sm; - for (sm = s->init_data->smlists[DETECT_SM_LIST_MATCH] ; sm != NULL; sm = sm->next) { + for (sm = s->init_data->smlists[DETECT_SM_LIST_MATCH]; sm != NULL; sm = sm->next) { if (sm->type == kid) { return true; } diff --git a/src/detect-engine-prefilter.c b/src/detect-engine-prefilter.c index e40a5175dafb..a64c4db44380 100644 --- a/src/detect-engine-prefilter.c +++ b/src/detect-engine-prefilter.c @@ -58,10 +58,9 @@ #include "util-profiling.h" #include "util-validate.h" -static int PrefilterStoreGetId(DetectEngineCtx *de_ctx, - const char *name, void (*FreeFunc)(void *)); -static const PrefilterStore *PrefilterStoreGetStore(const DetectEngineCtx *de_ctx, - const uint32_t id); +static int PrefilterStoreGetId(DetectEngineCtx *de_ctx, const char *name, void (*FreeFunc)(void *)); +static const PrefilterStore *PrefilterStoreGetStore( + const DetectEngineCtx *de_ctx, const uint32_t id); static inline void QuickSortSigIntId(SigIntId *sids, uint32_t n) { @@ -90,13 +89,8 @@ static inline void QuickSortSigIntId(SigIntId *sids, uint32_t n) /** * \brief run prefilter engines on a transaction */ -void DetectRunPrefilterTx(DetectEngineThreadCtx *det_ctx, - const SigGroupHead *sgh, - Packet *p, - const uint8_t ipproto, - const uint8_t flow_flags, - const AppProto alproto, - void *alstate, +void DetectRunPrefilterTx(DetectEngineThreadCtx *det_ctx, const SigGroupHead *sgh, Packet *p, + const uint8_t ipproto, const uint8_t flow_flags, const AppProto alproto, void *alstate, DetectTransaction *tx) { /* reset rule store */ @@ -140,8 +134,8 @@ void DetectRunPrefilterTx(DetectEngineThreadCtx *det_ctx, } } -void Prefilter(DetectEngineThreadCtx *det_ctx, const SigGroupHead *sgh, - Packet *p, const uint8_t flags) +void Prefilter( + DetectEngineThreadCtx *det_ctx, const SigGroupHead *sgh, Packet *p, const uint8_t flags) { SCEnter(); #if 0 @@ -171,10 +165,8 @@ void Prefilter(DetectEngineThreadCtx *det_ctx, const SigGroupHead *sgh, } /* run payload inspecting engines */ - if (sgh->payload_engines && - (p->payload_len || (p->flags & PKT_DETECT_HAS_STREAMDATA)) && - !(p->flags & PKT_NOPAYLOAD_INSPECTION)) - { + if (sgh->payload_engines && (p->payload_len || (p->flags & PKT_DETECT_HAS_STREAMDATA)) && + !(p->flags & PKT_NOPAYLOAD_INSPECTION)) { PACKET_PROFILING_DETECT_START(p, PROF_DETECT_PF_PAYLOAD); PrefilterEngine *engine = sgh->payload_engines; while (1) { @@ -201,8 +193,7 @@ void Prefilter(DetectEngineThreadCtx *det_ctx, const SigGroupHead *sgh, int PrefilterAppendEngine(DetectEngineCtx *de_ctx, SigGroupHead *sgh, void (*PrefilterFunc)(DetectEngineThreadCtx *det_ctx, Packet *p, const void *pectx), - void *pectx, void (*FreeFunc)(void *pectx), - const char *name) + void *pectx, void (*FreeFunc)(void *pectx), const char *name) { if (sgh == NULL || PrefilterFunc == NULL || pectx == NULL) return -1; @@ -235,8 +226,7 @@ int PrefilterAppendEngine(DetectEngineCtx *de_ctx, SigGroupHead *sgh, int PrefilterAppendPayloadEngine(DetectEngineCtx *de_ctx, SigGroupHead *sgh, void (*PrefilterFunc)(DetectEngineThreadCtx *det_ctx, Packet *p, const void *pectx), - void *pectx, void (*FreeFunc)(void *pectx), - const char *name) + void *pectx, void (*FreeFunc)(void *pectx), const char *name) { if (sgh == NULL || PrefilterFunc == NULL || pectx == NULL) return -1; @@ -421,12 +411,9 @@ void PrefilterSetupRuleGroup(DetectEngineCtx *de_ctx, SigGroupHead *sgh) * all engines, otherwise only those that have been forced by the * prefilter keyword. */ const enum DetectEnginePrefilterSetting setting = de_ctx->prefilter_setting; - for (int i = 0; i < DETECT_TBLSIZE; i++) - { + for (int i = 0; i < DETECT_TBLSIZE; i++) { if (sigmatch_table[i].SetupPrefilter != NULL && - (setting == DETECT_PREFILTER_AUTO || - de_ctx->sm_types_prefilter[i])) - { + (setting == DETECT_PREFILTER_AUTO || de_ctx->sm_types_prefilter[i])) { sigmatch_table[i].SetupPrefilter(de_ctx, sgh); } } @@ -436,7 +423,7 @@ void PrefilterSetupRuleGroup(DetectEngineCtx *de_ctx, SigGroupHead *sgh) PrefilterEngineList *el; if (sgh->init->pkt_engines != NULL) { uint32_t cnt = 0; - for (el = sgh->init->pkt_engines ; el != NULL; el = el->next) { + for (el = sgh->init->pkt_engines; el != NULL; el = el->next) { cnt++; } sgh->pkt_engines = SCMallocAligned(cnt * sizeof(PrefilterEngine), CLS); @@ -446,7 +433,7 @@ void PrefilterSetupRuleGroup(DetectEngineCtx *de_ctx, SigGroupHead *sgh) memset(sgh->pkt_engines, 0x00, (cnt * sizeof(PrefilterEngine))); PrefilterEngine *e = sgh->pkt_engines; - for (el = sgh->init->pkt_engines ; el != NULL; el = el->next) { + for (el = sgh->init->pkt_engines; el != NULL; el = el->next) { e->local_id = el->id; e->cb.Prefilter = el->Prefilter; e->pectx = el->pectx; @@ -460,7 +447,7 @@ void PrefilterSetupRuleGroup(DetectEngineCtx *de_ctx, SigGroupHead *sgh) } if (sgh->init->payload_engines != NULL) { uint32_t cnt = 0; - for (el = sgh->init->payload_engines ; el != NULL; el = el->next) { + for (el = sgh->init->payload_engines; el != NULL; el = el->next) { cnt++; } sgh->payload_engines = SCMallocAligned(cnt * sizeof(PrefilterEngine), CLS); @@ -470,7 +457,7 @@ void PrefilterSetupRuleGroup(DetectEngineCtx *de_ctx, SigGroupHead *sgh) memset(sgh->payload_engines, 0x00, (cnt * sizeof(PrefilterEngine))); PrefilterEngine *e = sgh->payload_engines; - for (el = sgh->init->payload_engines ; el != NULL; el = el->next) { + for (el = sgh->init->payload_engines; el != NULL; el = el->next) { e->local_id = el->id; e->cb.Prefilter = el->Prefilter; e->pectx = el->pectx; @@ -484,7 +471,7 @@ void PrefilterSetupRuleGroup(DetectEngineCtx *de_ctx, SigGroupHead *sgh) } if (sgh->init->tx_engines != NULL) { uint32_t cnt = 0; - for (el = sgh->init->tx_engines ; el != NULL; el = el->next) { + for (el = sgh->init->tx_engines; el != NULL; el = el->next) { cnt++; } sgh->tx_engines = SCMallocAligned(cnt * sizeof(PrefilterEngine), CLS); @@ -495,7 +482,7 @@ void PrefilterSetupRuleGroup(DetectEngineCtx *de_ctx, SigGroupHead *sgh) uint16_t local_id = 0; PrefilterEngine *e = sgh->tx_engines; - for (el = sgh->init->tx_engines ; el != NULL; el = el->next) { + for (el = sgh->init->tx_engines; el != NULL; el = el->next) { e->local_id = local_id++; e->alproto = el->alproto; e->ctx.tx_min_progress = el->tx_min_progress; @@ -602,8 +589,7 @@ static uint32_t PrefilterStoreHashFunc(HashListTable *ht, void *data, uint16_t d return hash; } -static char PrefilterStoreCompareFunc(void *data1, uint16_t len1, - void *data2, uint16_t len2) +static char PrefilterStoreCompareFunc(void *data1, uint16_t len1, void *data2, uint16_t len2) { PrefilterStore *ctx1 = data1; PrefilterStore *ctx2 = data2; @@ -626,15 +612,12 @@ void PrefilterInit(DetectEngineCtx *de_ctx) { BUG_ON(de_ctx->prefilter_hash_table != NULL); - de_ctx->prefilter_hash_table = HashListTableInit(256, - PrefilterStoreHashFunc, - PrefilterStoreCompareFunc, - PrefilterStoreFreeFunc); + de_ctx->prefilter_hash_table = HashListTableInit( + 256, PrefilterStoreHashFunc, PrefilterStoreCompareFunc, PrefilterStoreFreeFunc); BUG_ON(de_ctx->prefilter_hash_table == NULL); } -static int PrefilterStoreGetId(DetectEngineCtx *de_ctx, - const char *name, void (*FreeFunc)(void *)) +static int PrefilterStoreGetId(DetectEngineCtx *de_ctx, const char *name, void (*FreeFunc)(void *)) { PrefilterStore ctx = { name, FreeFunc, 0 }; @@ -668,14 +651,14 @@ static int PrefilterStoreGetId(DetectEngineCtx *de_ctx, } /** \warning slow */ -static const PrefilterStore *PrefilterStoreGetStore(const DetectEngineCtx *de_ctx, - const uint32_t id) +static const PrefilterStore *PrefilterStoreGetStore( + const DetectEngineCtx *de_ctx, const uint32_t id) { const PrefilterStore *store = NULL; if (de_ctx->prefilter_hash_table != NULL) { HashListTableBucket *hb = HashListTableGetListHead(de_ctx->prefilter_hash_table); - for ( ; hb != NULL; hb = HashListTableGetListNext(hb)) { + for (; hb != NULL; hb = HashListTableGetListNext(hb)) { PrefilterStore *ctx = HashListTableGetListData(hb); if (ctx->id == id) { store = ctx; @@ -719,8 +702,7 @@ static void PrefilterMpm(DetectEngineThreadCtx *det_ctx, const void *pectx, Pack const MpmCtx *mpm_ctx = ctx->mpm_ctx; SCLogDebug("running on list %d", ctx->list_id); - InspectionBuffer *buffer = ctx->GetData(det_ctx, ctx->transforms, - f, flags, txv, ctx->list_id); + InspectionBuffer *buffer = ctx->GetData(det_ctx, ctx->transforms, f, flags, txv, ctx->list_id); if (buffer == NULL) return; @@ -728,7 +710,7 @@ static void PrefilterMpm(DetectEngineThreadCtx *det_ctx, const void *pectx, Pack const uint8_t *data = buffer->inspect; SCLogDebug("mpm'ing buffer:"); - //PrintRawDataFp(stdout, data, data_len); + // PrintRawDataFp(stdout, data, data_len); if (data != NULL && data_len >= mpm_ctx->minlen) { (void)mpm_table[mpm_ctx->mpm_type].Search( @@ -754,9 +736,8 @@ int PrefilterGenericMpmRegister(DetectEngineCtx *de_ctx, SigGroupHead *sgh, MpmC pectx->mpm_ctx = mpm_ctx; pectx->transforms = &mpm_reg->transforms; - int r = PrefilterAppendTxEngine(de_ctx, sgh, PrefilterMpm, - mpm_reg->app_v2.alproto, mpm_reg->app_v2.tx_min_progress, - pectx, PrefilterGenericMpmFree, mpm_reg->pname); + int r = PrefilterAppendTxEngine(de_ctx, sgh, PrefilterMpm, mpm_reg->app_v2.alproto, + mpm_reg->app_v2.tx_min_progress, pectx, PrefilterGenericMpmFree, mpm_reg->pname); if (r != 0) { SCFree(pectx); } @@ -780,8 +761,7 @@ typedef struct PrefilterMpmPktCtx { * \param txv tx to inspect * \param pectx inspection context */ -static void PrefilterMpmPkt(DetectEngineThreadCtx *det_ctx, - Packet *p, const void *pectx) +static void PrefilterMpmPkt(DetectEngineThreadCtx *det_ctx, Packet *p, const void *pectx) { SCEnter(); @@ -789,8 +769,7 @@ static void PrefilterMpmPkt(DetectEngineThreadCtx *det_ctx, const MpmCtx *mpm_ctx = ctx->mpm_ctx; SCLogDebug("running on list %d", ctx->list_id); - InspectionBuffer *buffer = ctx->GetData(det_ctx, ctx->transforms, - p, ctx->list_id); + InspectionBuffer *buffer = ctx->GetData(det_ctx, ctx->transforms, p, ctx->list_id); if (buffer == NULL) return; @@ -798,7 +777,7 @@ static void PrefilterMpmPkt(DetectEngineThreadCtx *det_ctx, const uint8_t *data = buffer->inspect; SCLogDebug("mpm'ing buffer:"); - //PrintRawDataFp(stdout, data, data_len); + // PrintRawDataFp(stdout, data, data_len); if (data != NULL && data_len >= mpm_ctx->minlen) { (void)mpm_table[mpm_ctx->mpm_type].Search( @@ -824,8 +803,8 @@ int PrefilterGenericMpmPktRegister(DetectEngineCtx *de_ctx, SigGroupHead *sgh, M pectx->mpm_ctx = mpm_ctx; pectx->transforms = &mpm_reg->transforms; - int r = PrefilterAppendEngine(de_ctx, sgh, PrefilterMpmPkt, - pectx, PrefilterMpmPktFree, mpm_reg->pname); + int r = PrefilterAppendEngine( + de_ctx, sgh, PrefilterMpmPkt, pectx, PrefilterMpmPktFree, mpm_reg->pname); if (r != 0) { SCFree(pectx); } diff --git a/src/detect-engine-prefilter.h b/src/detect-engine-prefilter.h index 1f6143fd1545..2b06423dfaf3 100644 --- a/src/detect-engine-prefilter.h +++ b/src/detect-engine-prefilter.h @@ -47,17 +47,14 @@ typedef struct PrefilterStore_ { uint32_t id; } PrefilterStore; -void Prefilter(DetectEngineThreadCtx *, const SigGroupHead *, Packet *p, - const uint8_t flags); +void Prefilter(DetectEngineThreadCtx *, const SigGroupHead *, Packet *p, const uint8_t flags); int PrefilterAppendEngine(DetectEngineCtx *de_ctx, SigGroupHead *sgh, void (*Prefilter)(DetectEngineThreadCtx *det_ctx, Packet *p, const void *pectx), - void *pectx, void (*FreeFunc)(void *pectx), - const char *name); + void *pectx, void (*FreeFunc)(void *pectx), const char *name); int PrefilterAppendPayloadEngine(DetectEngineCtx *de_ctx, SigGroupHead *sgh, void (*Prefilter)(DetectEngineThreadCtx *det_ctx, Packet *p, const void *pectx), - void *pectx, void (*FreeFunc)(void *pectx), - const char *name); + void *pectx, void (*FreeFunc)(void *pectx), const char *name); int PrefilterAppendTxEngine(DetectEngineCtx *de_ctx, SigGroupHead *sgh, PrefilterTxFn PrefilterTxFunc, const AppProto alproto, const int tx_min_progress, void *pectx, void (*FreeFunc)(void *pectx), const char *name); @@ -65,13 +62,8 @@ int PrefilterAppendFrameEngine(DetectEngineCtx *de_ctx, SigGroupHead *sgh, PrefilterFrameFn PrefilterFrameFunc, AppProto alproto, uint8_t frame_type, void *pectx, void (*FreeFunc)(void *pectx), const char *name); -void DetectRunPrefilterTx(DetectEngineThreadCtx *det_ctx, - const SigGroupHead *sgh, - Packet *p, - const uint8_t ipproto, - const uint8_t flow_flags, - const AppProto alproto, - void *alstate, +void DetectRunPrefilterTx(DetectEngineThreadCtx *det_ctx, const SigGroupHead *sgh, Packet *p, + const uint8_t ipproto, const uint8_t flow_flags, const AppProto alproto, void *alstate, DetectTransaction *tx); void PrefilterFreeEnginesList(PrefilterEngineList *list); diff --git a/src/detect-engine-profile.c b/src/detect-engine-profile.c index 36cf6e106b05..9ba861404368 100644 --- a/src/detect-engine-profile.c +++ b/src/detect-engine-profile.c @@ -76,8 +76,8 @@ void RulesDumpTxMatchArray(const DetectEngineThreadCtx *det_ctx, const SigGroupH jb_free(js); } -void RulesDumpMatchArray(const DetectEngineThreadCtx *det_ctx, - const SigGroupHead *sgh, const Packet *p) +void RulesDumpMatchArray( + const DetectEngineThreadCtx *det_ctx, const SigGroupHead *sgh, const Packet *p) { JsonBuilder *js = CreateEveHeader(p, LOG_DIR_PACKET, "inspectedrules", NULL, NULL); if (js == NULL) @@ -99,7 +99,6 @@ void RulesDumpMatchArray(const DetectEngineThreadCtx *det_ctx, if (s == NULL) continue; jb_append_uint(js, s->id); - } jb_close(js); // close array jb_close(js); // close inspectedrules object diff --git a/src/detect-engine-profile.h b/src/detect-engine-profile.h index 2699a2435769..177e880d4c44 100644 --- a/src/detect-engine-profile.h +++ b/src/detect-engine-profile.h @@ -22,14 +22,14 @@ */ #ifndef _DETECT_ENGINE_PROFILE_H -#define _DETECT_ENGINE_PROFILE_H +#define _DETECT_ENGINE_PROFILE_H #include "detect.h" void RulesDumpTxMatchArray(const DetectEngineThreadCtx *det_ctx, const SigGroupHead *sgh, const Packet *p, const uint64_t tx_id, const uint32_t rule_cnt, const uint32_t pkt_prefilter_cnt); -void RulesDumpMatchArray(const DetectEngineThreadCtx *det_ctx, - const SigGroupHead *sgh, const Packet *p); +void RulesDumpMatchArray( + const DetectEngineThreadCtx *det_ctx, const SigGroupHead *sgh, const Packet *p); -#endif /* _DETECT_ENGINE_PROFILE_H */ +#endif /* _DETECT_ENGINE_PROFILE_H */ diff --git a/src/detect-engine-proto.c b/src/detect-engine-proto.c index 5ead3d8d93be..6a9380f82b4b 100644 --- a/src/detect-engine-proto.c +++ b/src/detect-engine-proto.c @@ -82,18 +82,15 @@ int DetectProtoParse(DetectProto *dp, const char *str) } else if (strcasecmp(str, "sctp") == 0) { dp->proto[IPPROTO_SCTP / 8] |= 1 << (IPPROTO_SCTP % 8); SCLogDebug("SCTP protocol detected"); - } else if (strcasecmp(str,"ipv4") == 0 || - strcasecmp(str,"ip4") == 0 ) { + } else if (strcasecmp(str, "ipv4") == 0 || strcasecmp(str, "ip4") == 0) { dp->flags |= (DETECT_PROTO_IPV4 | DETECT_PROTO_ANY); memset(dp->proto, 0xff, sizeof(dp->proto)); SCLogDebug("IPv4 protocol detected"); - } else if (strcasecmp(str,"ipv6") == 0 || - strcasecmp(str,"ip6") == 0 ) { + } else if (strcasecmp(str, "ipv6") == 0 || strcasecmp(str, "ip6") == 0) { dp->flags |= (DETECT_PROTO_IPV6 | DETECT_PROTO_ANY); memset(dp->proto, 0xff, sizeof(dp->proto)); SCLogDebug("IPv6 protocol detected"); - } else if (strcasecmp(str,"ip") == 0 || - strcasecmp(str,"pkthdr") == 0) { + } else if (strcasecmp(str, "ip") == 0 || strcasecmp(str, "pkthdr") == 0) { /* Proto "ip" is treated as an "any" */ dp->flags |= DETECT_PROTO_ANY; memset(dp->proto, 0xff, sizeof(dp->proto)); @@ -137,7 +134,7 @@ int DetectProtoContainsProto(const DetectProto *dp, int proto) if (dp->flags & DETECT_PROTO_ANY) return 1; - if (dp->proto[proto / 8] & (1<<(proto % 8))) + if (dp->proto[proto / 8] & (1 << (proto % 8))) return 1; return 0; @@ -153,8 +150,8 @@ int DetectProtoContainsProto(const DetectProto *dp, int proto) * \brief this function is used to initialize the detection engine context and * setup the signature with passed values. */ -static int DetectProtoInitTest(DetectEngineCtx **de_ctx, Signature **sig, - DetectProto *dp, const char *str) +static int DetectProtoInitTest( + DetectEngineCtx **de_ctx, Signature **sig, DetectProto *dp, const char *str) { char fullstr[1024]; int result = 0; @@ -162,9 +159,10 @@ static int DetectProtoInitTest(DetectEngineCtx **de_ctx, Signature **sig, *de_ctx = NULL; *sig = NULL; - if (snprintf(fullstr, 1024, "alert %s any any -> any any (msg:\"DetectProto" - " test\"; sid:1;)", str) >= 1024) - { + if (snprintf(fullstr, 1024, + "alert %s any any -> any any (msg:\"DetectProto" + " test\"; sid:1;)", + str) >= 1024) { goto end; } @@ -195,10 +193,10 @@ static int DetectProtoInitTest(DetectEngineCtx **de_ctx, Signature **sig, * \test ProtoTestParse01 is a test to make sure that we parse the * protocol correctly, when given valid proto option. */ -static int ProtoTestParse01 (void) +static int ProtoTestParse01(void) { DetectProto dp; - memset(&dp,0,sizeof(DetectProto)); + memset(&dp, 0, sizeof(DetectProto)); int r = DetectProtoParse(&dp, "6"); @@ -210,10 +208,10 @@ static int ProtoTestParse01 (void) * \test ProtoTestParse02 is a test to make sure that we parse the * protocol correctly, when given "tcp" as proto option. */ -static int ProtoTestParse02 (void) +static int ProtoTestParse02(void) { DetectProto dp; - memset(&dp,0,sizeof(DetectProto)); + memset(&dp, 0, sizeof(DetectProto)); int r = DetectProtoParse(&dp, "tcp"); @@ -226,10 +224,10 @@ static int ProtoTestParse02 (void) * \test ProtoTestParse03 is a test to make sure that we parse the * protocol correctly, when given "ip" as proto option. */ -static int ProtoTestParse03 (void) +static int ProtoTestParse03(void) { DetectProto dp; - memset(&dp,0,sizeof(DetectProto)); + memset(&dp, 0, sizeof(DetectProto)); int r = DetectProtoParse(&dp, "ip"); @@ -243,10 +241,10 @@ static int ProtoTestParse03 (void) * \test ProtoTestParse04 is a test to make sure that we do not parse the * protocol, when given an invalid proto option. */ -static int ProtoTestParse04 (void) +static int ProtoTestParse04(void) { DetectProto dp; - memset(&dp,0,sizeof(DetectProto)); + memset(&dp, 0, sizeof(DetectProto)); /* Check for a bad number */ int r = DetectProtoParse(&dp, "4242"); @@ -260,10 +258,10 @@ static int ProtoTestParse04 (void) * \test ProtoTestParse05 is a test to make sure that we do not parse the * protocol, when given an invalid proto option. */ -static int ProtoTestParse05 (void) +static int ProtoTestParse05(void) { DetectProto dp; - memset(&dp,0,sizeof(DetectProto)); + memset(&dp, 0, sizeof(DetectProto)); /* Check for a bad string */ int r = DetectProtoParse(&dp, "tcp/udp"); @@ -276,10 +274,10 @@ static int ProtoTestParse05 (void) /** * \test make sure that we properly parse tcp-pkt */ -static int ProtoTestParse06 (void) +static int ProtoTestParse06(void) { DetectProto dp; - memset(&dp,0,sizeof(DetectProto)); + memset(&dp, 0, sizeof(DetectProto)); /* Check for a bad string */ int r = DetectProtoParse(&dp, "tcp-pkt"); @@ -293,10 +291,10 @@ static int ProtoTestParse06 (void) /** * \test make sure that we properly parse tcp-stream */ -static int ProtoTestParse07 (void) +static int ProtoTestParse07(void) { DetectProto dp; - memset(&dp,0,sizeof(DetectProto)); + memset(&dp, 0, sizeof(DetectProto)); /* Check for a bad string */ int r = DetectProtoParse(&dp, "tcp-stream"); @@ -408,4 +406,3 @@ void DetectProtoTests(void) UtRegisterTest("DetectProtoTestSig01", DetectProtoTestSig01); #endif /* UNITTESTS */ } - diff --git a/src/detect-engine-proto.h b/src/detect-engine-proto.h index 4e4c031110db..ffa061a63fa6 100644 --- a/src/detect-engine-proto.h +++ b/src/detect-engine-proto.h @@ -24,17 +24,20 @@ #ifndef __DETECT_PROTO_H__ #define __DETECT_PROTO_H__ -#define DETECT_PROTO_ANY (1 << 0) /**< Indicate that given protocol - is considered as IP */ -#define DETECT_PROTO_ONLY_PKT (1 << 1) /**< Indicate that we only care - about packet payloads. */ -#define DETECT_PROTO_ONLY_STREAM (1 << 2) /**< Indicate that we only care - about stream payloads. */ -#define DETECT_PROTO_IPV4 (1 << 3) /**< IPv4 only */ -#define DETECT_PROTO_IPV6 (1 << 4) /**< IPv6 only */ +#define DETECT_PROTO_ANY \ + (1 << 0) /**< Indicate that given protocol \ + is considered as IP */ +#define DETECT_PROTO_ONLY_PKT \ + (1 << 1) /**< Indicate that we only care \ + about packet payloads. */ +#define DETECT_PROTO_ONLY_STREAM \ + (1 << 2) /**< Indicate that we only care \ + about stream payloads. */ +#define DETECT_PROTO_IPV4 (1 << 3) /**< IPv4 only */ +#define DETECT_PROTO_IPV6 (1 << 4) /**< IPv6 only */ typedef struct DetectProto_ { - uint8_t proto[256/8]; /**< bit array for 256 protocol bits */ + uint8_t proto[256 / 8]; /**< bit array for 256 protocol bits */ uint8_t flags; } DetectProto; @@ -45,4 +48,3 @@ int DetectProtoContainsProto(const DetectProto *, int); void DetectProtoTests(void); #endif /* __DETECT_PROTO_H__ */ - diff --git a/src/detect-engine-register.c b/src/detect-engine-register.c index 0f459eccb67b..0f1f030e4321 100644 --- a/src/detect-engine-register.c +++ b/src/detect-engine-register.c @@ -434,8 +434,7 @@ int SigTableList(const char *keyword) } } else { for (i = 0; i < size; i++) { - if ((sigmatch_table[i].name != NULL) && - strcmp(sigmatch_table[i].name, keyword) == 0) { + if ((sigmatch_table[i].name != NULL) && strcmp(sigmatch_table[i].name, keyword) == 0) { printf("= %s =\n", sigmatch_table[i].name); if (sigmatch_table[i].flags & SIGMATCH_NOT_BUILT) { printf("Not built-in\n"); @@ -726,7 +725,8 @@ void SigTableRegisterTests(void) g_ut_covered++; } else { SCLogDebug("detection plugin %s has no unittest " - "registration function.", sigmatch_table[i].name); + "registration function.", + sigmatch_table[i].name); if (coverage_unittests) SCLogWarning("detection plugin %s has no unittest " diff --git a/src/detect-engine-siggroup.c b/src/detect-engine-siggroup.c index 36df347a503c..98b07632cc7e 100644 --- a/src/detect-engine-siggroup.c +++ b/src/detect-engine-siggroup.c @@ -104,13 +104,14 @@ static SigGroupHeadInitData *SigGroupHeadInitDataAlloc(uint32_t size) void SigGroupHeadStore(DetectEngineCtx *de_ctx, SigGroupHead *sgh) { void *ptmp; - //printf("de_ctx->sgh_array_cnt %u, de_ctx->sgh_array_size %u, de_ctx->sgh_array %p\n", de_ctx->sgh_array_cnt, de_ctx->sgh_array_size, de_ctx->sgh_array); + // printf("de_ctx->sgh_array_cnt %u, de_ctx->sgh_array_size %u, de_ctx->sgh_array %p\n", + // de_ctx->sgh_array_cnt, de_ctx->sgh_array_size, de_ctx->sgh_array); if (de_ctx->sgh_array_cnt < de_ctx->sgh_array_size) { de_ctx->sgh_array[de_ctx->sgh_array_cnt] = sgh; } else { int increase = 16; - ptmp = SCRealloc(de_ctx->sgh_array, - sizeof(SigGroupHead *) * (increase + de_ctx->sgh_array_size)); + ptmp = SCRealloc( + de_ctx->sgh_array, sizeof(SigGroupHead *) * (increase + de_ctx->sgh_array_size)); if (ptmp == NULL) { SCFree(de_ctx->sgh_array); de_ctx->sgh_array = NULL; @@ -207,7 +208,7 @@ static uint32_t SigGroupHeadHashFunc(HashListTable *ht, void *data, uint16_t dat hash += sgh->init->sig_array[b]; hash %= ht->array_size; - SCLogDebug("hash %"PRIu32" (sig_size %"PRIu32")", hash, sgh->init->sig_size); + SCLogDebug("hash %" PRIu32 " (sig_size %" PRIu32 ")", hash, sgh->init->sig_size); return hash; } @@ -223,8 +224,7 @@ static uint32_t SigGroupHeadHashFunc(HashListTable *ht, void *data, uint16_t dat * \retval 1 If the 2 SigGroupHeads sent as args match. * \retval 0 If the 2 SigGroupHeads sent as args do not match. */ -static char SigGroupHeadCompareFunc(void *data1, uint16_t len1, void *data2, - uint16_t len2) +static char SigGroupHeadCompareFunc(void *data1, uint16_t len1, void *data2, uint16_t len2) { SigGroupHead *sgh1 = (SigGroupHead *)data1; SigGroupHead *sgh2 = (SigGroupHead *)data2; @@ -252,8 +252,8 @@ static char SigGroupHeadCompareFunc(void *data1, uint16_t len1, void *data2, */ int SigGroupHeadHashInit(DetectEngineCtx *de_ctx) { - de_ctx->sgh_hash_table = HashListTableInit(4096, SigGroupHeadHashFunc, - SigGroupHeadCompareFunc, NULL); + de_ctx->sgh_hash_table = + HashListTableInit(4096, SigGroupHeadHashFunc, SigGroupHeadCompareFunc, NULL); if (de_ctx->sgh_hash_table == NULL) goto error; @@ -298,8 +298,7 @@ SigGroupHead *SigGroupHeadHashLookup(DetectEngineCtx *de_ctx, SigGroupHead *sgh) { SCEnter(); - SigGroupHead *rsgh = HashListTableLookup(de_ctx->sgh_hash_table, - (void *)sgh, 0); + SigGroupHead *rsgh = HashListTableLookup(de_ctx->sgh_hash_table, (void *)sgh, 0); SCReturnPtr(rsgh, "SigGroupHead"); } @@ -332,8 +331,7 @@ void SigGroupHeadHashFree(DetectEngineCtx *de_ctx) * \retval 0 On success. * \retval -1 On failure. */ -int SigGroupHeadAppendSig(const DetectEngineCtx *de_ctx, SigGroupHead **sgh, - const Signature *s) +int SigGroupHeadAppendSig(const DetectEngineCtx *de_ctx, SigGroupHead **sgh, const Signature *s) { if (de_ctx == NULL) return 0; @@ -432,8 +430,7 @@ void SigGroupHeadSetSigCnt(SigGroupHead *sgh, uint32_t max_idx) return; } -void SigGroupHeadSetProtoAndDirection(SigGroupHead *sgh, - uint8_t ipproto, int dir) +void SigGroupHeadSetProtoAndDirection(SigGroupHead *sgh, uint8_t ipproto, int dir) { if (sgh && sgh->init) { SCLogDebug("setting proto %u and dir %d on sgh %p", ipproto, dir, sgh); @@ -463,7 +460,7 @@ void SigGroupHeadPrintSigs(DetectEngineCtx *de_ctx, SigGroupHead *sgh) for (u = 0; u < (sgh->init->sig_size * 8); u++) { if (sgh->init->sig_array[u / 8] & (1 << (u % 8))) { SCLogDebug("%" PRIu32, u); - printf("s->num %"PRIu32" ", u); + printf("s->num %" PRIu32 " ", u); } } @@ -481,8 +478,7 @@ void SigGroupHeadPrintSigs(DetectEngineCtx *de_ctx, SigGroupHead *sgh) * \retval 0 success * \retval -1 error */ -int SigGroupHeadBuildMatchArray(DetectEngineCtx *de_ctx, SigGroupHead *sgh, - uint32_t max_idx) +int SigGroupHeadBuildMatchArray(DetectEngineCtx *de_ctx, SigGroupHead *sgh, uint32_t max_idx) { Signature *s = NULL; uint32_t idx = 0; @@ -498,7 +494,7 @@ int SigGroupHeadBuildMatchArray(DetectEngineCtx *de_ctx, SigGroupHead *sgh, return -1; for (sig = 0; sig < max_idx + 1; sig++) { - if (!(sgh->init->sig_array[(sig / 8)] & (1 << (sig % 8))) ) + if (!(sgh->init->sig_array[(sig / 8)] & (1 << (sig % 8)))) continue; s = de_ctx->sig_array[sig]; @@ -725,8 +721,7 @@ int SigGroupHeadBuildNonPrefilterArray(DetectEngineCtx *de_ctx, SigGroupHead *sg * \retval 1 On successfully finding the sid in the SigGroupHead. * \retval 0 If the sid is not found in the SigGroupHead */ -int SigGroupHeadContainsSigId(DetectEngineCtx *de_ctx, SigGroupHead *sgh, - uint32_t sid) +int SigGroupHeadContainsSigId(DetectEngineCtx *de_ctx, SigGroupHead *sgh, uint32_t sid) { SCEnter(); @@ -744,7 +739,7 @@ int SigGroupHeadContainsSigId(DetectEngineCtx *de_ctx, SigGroupHead *sgh, } /* Check if the SigGroupHead has an entry for the sid */ - if ( !(sgh->init->sig_array[sig / 8] & (1 << (sig % 8))) ) + if (!(sgh->init->sig_array[sig / 8] & (1 << (sig % 8)))) continue; /* If we have reached here, we have an entry for sid in the SigGroupHead. diff --git a/src/detect-engine-siggroup.h b/src/detect-engine-siggroup.h index d4c9e93c6771..995b38c8523d 100644 --- a/src/detect-engine-siggroup.h +++ b/src/detect-engine-siggroup.h @@ -42,12 +42,10 @@ int SigGroupHeadHashRemove(DetectEngineCtx *, SigGroupHead *); void SigGroupHeadInitDataFree(SigGroupHeadInitData *sghid); void SigGroupHeadSetSigCnt(SigGroupHead *sgh, uint32_t max_idx); -void SigGroupHeadSetProtoAndDirection(SigGroupHead *sgh, - uint8_t ipproto, int dir); +void SigGroupHeadSetProtoAndDirection(SigGroupHead *sgh, uint8_t ipproto, int dir); int SigGroupHeadBuildMatchArray(DetectEngineCtx *de_ctx, SigGroupHead *sgh, uint32_t max_idx); -int SigGroupHeadContainsSigId (DetectEngineCtx *de_ctx, SigGroupHead *sgh, - uint32_t sid); +int SigGroupHeadContainsSigId(DetectEngineCtx *de_ctx, SigGroupHead *sgh, uint32_t sid); void SigGroupHeadRegisterTests(void); void SigGroupHeadPrintSigs(DetectEngineCtx *de_ctx, SigGroupHead *sgh); diff --git a/src/detect-engine-sigorder.c b/src/detect-engine-sigorder.c index ea51e191ecee..ab2e1307da44 100644 --- a/src/detect-engine-sigorder.c +++ b/src/detect-engine-sigorder.c @@ -66,7 +66,6 @@ #define DETECT_XBITS_TYPE_SET_READ 3 #define DETECT_XBITS_TYPE_SET 4 - /** * \brief Registers a keyword-based, signature ordering function * @@ -78,7 +77,7 @@ * anything */ static void SCSigRegisterSignatureOrderingFunc(DetectEngineCtx *de_ctx, - int (*SWCompare)(SCSigSignatureWrapper *sw1, SCSigSignatureWrapper *sw2)) + int (*SWCompare)(SCSigSignatureWrapper *sw1, SCSigSignatureWrapper *sw2)) { SCSigOrderFunc *curr = NULL; SCSigOrderFunc *prev = NULL; @@ -138,8 +137,7 @@ static inline int SCSigGetFlowbitsType(Signature *sig) while (sm != NULL) { if (sm->type == DETECT_FLOWBITS) { fb = (DetectFlowbitsData *)sm->ctx; - if (fb->cmd == DETECT_FLOWBITS_CMD_ISNOTSET || - fb->cmd == DETECT_FLOWBITS_CMD_ISSET) { + if (fb->cmd == DETECT_FLOWBITS_CMD_ISNOTSET || fb->cmd == DETECT_FLOWBITS_CMD_ISSET) { read++; } else { #ifdef DEBUG @@ -155,9 +153,8 @@ static inline int SCSigGetFlowbitsType(Signature *sig) while (sm != NULL) { if (sm->type == DETECT_FLOWBITS) { fb = (DetectFlowbitsData *)sm->ctx; - if (fb->cmd == DETECT_FLOWBITS_CMD_SET || - fb->cmd == DETECT_FLOWBITS_CMD_UNSET || - fb->cmd == DETECT_FLOWBITS_CMD_TOGGLE) { + if (fb->cmd == DETECT_FLOWBITS_CMD_SET || fb->cmd == DETECT_FLOWBITS_CMD_UNSET || + fb->cmd == DETECT_FLOWBITS_CMD_TOGGLE) { write++; } else { #ifdef DEBUG @@ -193,14 +190,11 @@ static inline int SCSigGetFlowintType(Signature *sig) while (sm != NULL) { if (sm->type == DETECT_FLOWINT) { fi = (DetectFlowintData *)sm->ctx; - if (fi->modifier == FLOWINT_MODIFIER_LT || - fi->modifier == FLOWINT_MODIFIER_LE || - fi->modifier == FLOWINT_MODIFIER_EQ || - fi->modifier == FLOWINT_MODIFIER_NE || - fi->modifier == FLOWINT_MODIFIER_GE || - fi->modifier == FLOWINT_MODIFIER_GT || - fi->modifier == FLOWINT_MODIFIER_NOTSET || - fi->modifier == FLOWINT_MODIFIER_ISSET) { + if (fi->modifier == FLOWINT_MODIFIER_LT || fi->modifier == FLOWINT_MODIFIER_LE || + fi->modifier == FLOWINT_MODIFIER_EQ || fi->modifier == FLOWINT_MODIFIER_NE || + fi->modifier == FLOWINT_MODIFIER_GE || fi->modifier == FLOWINT_MODIFIER_GT || + fi->modifier == FLOWINT_MODIFIER_NOTSET || + fi->modifier == FLOWINT_MODIFIER_ISSET) { read++; } else { #ifdef DEBUG @@ -216,9 +210,8 @@ static inline int SCSigGetFlowintType(Signature *sig) while (sm != NULL) { if (sm->type == DETECT_FLOWINT) { fi = (DetectFlowintData *)sm->ctx; - if (fi->modifier == FLOWINT_MODIFIER_SET || - fi->modifier == FLOWINT_MODIFIER_ADD || - fi->modifier == FLOWINT_MODIFIER_SUB) { + if (fi->modifier == FLOWINT_MODIFIER_SET || fi->modifier == FLOWINT_MODIFIER_ADD || + fi->modifier == FLOWINT_MODIFIER_SUB) { write++; } else { #ifdef DEBUG @@ -385,8 +378,7 @@ static inline int SCSigGetXbitsType(Signature *sig, enum VarTypes type) if (sm->type == DETECT_XBITS) { fb = (DetectXbitsData *)sm->ctx; if (fb->type == type) { - if (fb->cmd == DETECT_XBITS_CMD_ISNOTSET || - fb->cmd == DETECT_XBITS_CMD_ISSET) { + if (fb->cmd == DETECT_XBITS_CMD_ISNOTSET || fb->cmd == DETECT_XBITS_CMD_ISSET) { read++; } else { #ifdef DEBUG @@ -404,8 +396,7 @@ static inline int SCSigGetXbitsType(Signature *sig, enum VarTypes type) if (sm->type == DETECT_HOSTBITS) { fb = (DetectXbitsData *)sm->ctx; if (fb->type == type) { - if (fb->cmd == DETECT_XBITS_CMD_SET || - fb->cmd == DETECT_XBITS_CMD_UNSET || + if (fb->cmd == DETECT_XBITS_CMD_SET || fb->cmd == DETECT_XBITS_CMD_UNSET || fb->cmd == DETECT_XBITS_CMD_TOGGLE) { write++; } else { @@ -498,9 +489,8 @@ static inline void SCSigProcessUserDataForIPPairbits(SCSigSignatureWrapper *sw) } /* Return 1 if sw1 comes before sw2 in the final list. */ -static int SCSigLessThan(SCSigSignatureWrapper *sw1, - SCSigSignatureWrapper *sw2, - SCSigOrderFunc *cmp_func_list) +static int SCSigLessThan( + SCSigSignatureWrapper *sw1, SCSigSignatureWrapper *sw2, SCSigOrderFunc *cmp_func_list) { SCSigOrderFunc *funcs = cmp_func_list; @@ -519,8 +509,7 @@ static int SCSigLessThan(SCSigSignatureWrapper *sw1, /* Merge sort based on a list of compare functions * debug asserts are here to guide scan-build */ -static SCSigSignatureWrapper *SCSigOrder(SCSigSignatureWrapper *sw, - SCSigOrderFunc *cmp_func_list) +static SCSigSignatureWrapper *SCSigOrder(SCSigSignatureWrapper *sw, SCSigOrderFunc *cmp_func_list) { DEBUG_VALIDATE_BUG_ON(sw == NULL); @@ -595,8 +584,7 @@ static SCSigSignatureWrapper *SCSigOrder(SCSigSignatureWrapper *sw, * signatures have to be ordered. * \param sw The new signature that has to be ordered based on its action */ -static int SCSigOrderByActionCompare(SCSigSignatureWrapper *sw1, - SCSigSignatureWrapper *sw2) +static int SCSigOrderByActionCompare(SCSigSignatureWrapper *sw1, SCSigSignatureWrapper *sw2) { return ActionOrderVal(sw2->sig->action) - ActionOrderVal(sw1->sig->action); } @@ -608,11 +596,9 @@ static int SCSigOrderByActionCompare(SCSigSignatureWrapper *sw1, * signatures have to be ordered. * \param sw The new signature that has to be ordered based on its flowbits */ -static int SCSigOrderByFlowbitsCompare(SCSigSignatureWrapper *sw1, - SCSigSignatureWrapper *sw2) +static int SCSigOrderByFlowbitsCompare(SCSigSignatureWrapper *sw1, SCSigSignatureWrapper *sw2) { - return sw1->user[SC_RADIX_USER_DATA_FLOWBITS] - - sw2->user[SC_RADIX_USER_DATA_FLOWBITS]; + return sw1->user[SC_RADIX_USER_DATA_FLOWBITS] - sw2->user[SC_RADIX_USER_DATA_FLOWBITS]; } /** @@ -622,11 +608,9 @@ static int SCSigOrderByFlowbitsCompare(SCSigSignatureWrapper *sw1, * signatures have to be ordered. * \param sw The new signature that has to be ordered based on its flowvar */ -static int SCSigOrderByFlowvarCompare(SCSigSignatureWrapper *sw1, - SCSigSignatureWrapper *sw2) +static int SCSigOrderByFlowvarCompare(SCSigSignatureWrapper *sw1, SCSigSignatureWrapper *sw2) { - return sw1->user[SC_RADIX_USER_DATA_FLOWVAR] - - sw2->user[SC_RADIX_USER_DATA_FLOWVAR]; + return sw1->user[SC_RADIX_USER_DATA_FLOWVAR] - sw2->user[SC_RADIX_USER_DATA_FLOWVAR]; } /** @@ -636,18 +620,14 @@ static int SCSigOrderByFlowvarCompare(SCSigSignatureWrapper *sw1, * signatures have to be ordered. * \param sw The new signature that has to be ordered based on its pktvar */ -static int SCSigOrderByPktvarCompare(SCSigSignatureWrapper *sw1, - SCSigSignatureWrapper *sw2) +static int SCSigOrderByPktvarCompare(SCSigSignatureWrapper *sw1, SCSigSignatureWrapper *sw2) { - return sw1->user[SC_RADIX_USER_DATA_PKTVAR] - - sw2->user[SC_RADIX_USER_DATA_PKTVAR]; + return sw1->user[SC_RADIX_USER_DATA_PKTVAR] - sw2->user[SC_RADIX_USER_DATA_PKTVAR]; } -static int SCSigOrderByFlowintCompare(SCSigSignatureWrapper *sw1, - SCSigSignatureWrapper *sw2) +static int SCSigOrderByFlowintCompare(SCSigSignatureWrapper *sw1, SCSigSignatureWrapper *sw2) { - return sw1->user[SC_RADIX_USER_DATA_FLOWINT] - - sw2->user[SC_RADIX_USER_DATA_FLOWINT]; + return sw1->user[SC_RADIX_USER_DATA_FLOWINT] - sw2->user[SC_RADIX_USER_DATA_FLOWINT]; } /** @@ -657,11 +637,9 @@ static int SCSigOrderByFlowintCompare(SCSigSignatureWrapper *sw1, * signatures have to be ordered. * \param sw The new signature that has to be ordered based on its hostbits */ -static int SCSigOrderByHostbitsCompare(SCSigSignatureWrapper *sw1, - SCSigSignatureWrapper *sw2) +static int SCSigOrderByHostbitsCompare(SCSigSignatureWrapper *sw1, SCSigSignatureWrapper *sw2) { - return sw1->user[SC_RADIX_USER_DATA_HOSTBITS] - - sw2->user[SC_RADIX_USER_DATA_HOSTBITS]; + return sw1->user[SC_RADIX_USER_DATA_HOSTBITS] - sw2->user[SC_RADIX_USER_DATA_HOSTBITS]; } /** @@ -671,11 +649,9 @@ static int SCSigOrderByHostbitsCompare(SCSigSignatureWrapper *sw1, * signatures have to be ordered. * \param sw The new signature that has to be ordered based on its bits */ -static int SCSigOrderByIPPairbitsCompare(SCSigSignatureWrapper *sw1, - SCSigSignatureWrapper *sw2) +static int SCSigOrderByIPPairbitsCompare(SCSigSignatureWrapper *sw1, SCSigSignatureWrapper *sw2) { - return sw1->user[SC_RADIX_USER_DATA_IPPAIRBITS] - - sw2->user[SC_RADIX_USER_DATA_IPPAIRBITS]; + return sw1->user[SC_RADIX_USER_DATA_IPPAIRBITS] - sw2->user[SC_RADIX_USER_DATA_IPPAIRBITS]; } /** @@ -685,8 +661,7 @@ static int SCSigOrderByIPPairbitsCompare(SCSigSignatureWrapper *sw1, * signatures have to be ordered. * \param sw The new signature that has to be ordered based on its priority */ -static int SCSigOrderByPriorityCompare(SCSigSignatureWrapper *sw1, - SCSigSignatureWrapper *sw2) +static int SCSigOrderByPriorityCompare(SCSigSignatureWrapper *sw1, SCSigSignatureWrapper *sw2) { if (sw1->sig->prio > sw2->sig->prio) { return -1; @@ -762,7 +737,8 @@ void SCSigOrderSignatures(DetectEngineCtx *de_ctx) sigw_list = SCSigOrder(sigw_list, de_ctx->sc_sig_order_funcs); SCLogDebug("Total Signatures to be processed by the" - "sigordering module: %d", i); + "sigordering module: %d", + i); /* Recreate the sig list in order */ de_ctx->sig_list = NULL; @@ -886,60 +862,79 @@ static int SCSigOrderingTest02(void) DetectEngineCtx *de_ctx = DetectEngineCtxInit(); FAIL_IF(de_ctx == NULL); - sig = DetectEngineAppendSig(de_ctx, - "alert tcp any !21:902 -> any any (msg:\"Testing sigordering\"; content:\"220\"; offset:0; depth:4; pcre:\"/220[- ]/\"; rev:4; sid:1;)"); + sig = DetectEngineAppendSig( + de_ctx, "alert tcp any !21:902 -> any any (msg:\"Testing sigordering\"; " + "content:\"220\"; offset:0; depth:4; pcre:\"/220[- ]/\"; rev:4; sid:1;)"); FAIL_IF_NULL(sig); - sig = DetectEngineAppendSig(de_ctx, - "drop tcp any !21:902 -> any any (msg:\"Testing sigordering\"; content:\"220\"; offset:0; depth:4; pcre:\"/220[- ]/\"; rev:4; sid:2;)"); + sig = DetectEngineAppendSig( + de_ctx, "drop tcp any !21:902 -> any any (msg:\"Testing sigordering\"; " + "content:\"220\"; offset:0; depth:4; pcre:\"/220[- ]/\"; rev:4; sid:2;)"); FAIL_IF_NULL(sig); - sig = DetectEngineAppendSig(de_ctx, - "drop tcp any !21:902 -> any any (msg:\"Testing sigordering\"; content:\"220\"; offset:10; depth:4; pcre:\"/220[- ]/\"; rev:4; sid:3;)"); + sig = DetectEngineAppendSig( + de_ctx, "drop tcp any !21:902 -> any any (msg:\"Testing sigordering\"; " + "content:\"220\"; offset:10; depth:4; pcre:\"/220[- ]/\"; rev:4; sid:3;)"); FAIL_IF_NULL(sig); - sig = DetectEngineAppendSig(de_ctx, - "pass tcp any !21:902 -> any any (msg:\"Testing sigordering\"; content:\"220\"; offset:0; depth:4; pcre:\"/220[- ]/\"; flowvar:http_host,\"www.oisf.net\"; rev:4; priority:1; sid:4;)"); + sig = DetectEngineAppendSig( + de_ctx, "pass tcp any !21:902 -> any any (msg:\"Testing sigordering\"; " + "content:\"220\"; offset:0; depth:4; pcre:\"/220[- ]/\"; " + "flowvar:http_host,\"www.oisf.net\"; rev:4; priority:1; sid:4;)"); FAIL_IF_NULL(sig); sig = DetectEngineAppendSig(de_ctx, - "alert tcp any !21:902 -> any any (msg:\"Testing sigordering\"; content:\"220\"; offset:0; depth:4; pcre:\"/220[- ]/\"; rev:4; priority:1; sid:5;)"); + "alert tcp any !21:902 -> any any (msg:\"Testing sigordering\"; content:\"220\"; " + "offset:0; depth:4; pcre:\"/220[- ]/\"; rev:4; priority:1; sid:5;)"); FAIL_IF_NULL(sig); - sig = DetectEngineAppendSig(de_ctx, - "pass tcp any !21:902 -> any any (msg:\"Testing sigordering\"; pcre:\"/^User-Agent: (?P.*)\\r\\n/m\"; content:\"220\"; offset:10; depth:4; rev:4; priority:3; sid:6;)"); + sig = DetectEngineAppendSig( + de_ctx, "pass tcp any !21:902 -> any any (msg:\"Testing sigordering\"; " + "pcre:\"/^User-Agent: (?P.*)\\r\\n/m\"; content:\"220\"; " + "offset:10; depth:4; rev:4; priority:3; sid:6;)"); FAIL_IF_NULL(sig); sig = DetectEngineAppendSig(de_ctx, - "pass tcp any !21:902 -> any any (msg:\"Testing sigordering\"; content:\"220\"; offset:10; depth:4; pcre:\"/220[- ]/\"; rev:4; priority:3; sid:7;)"); + "pass tcp any !21:902 -> any any (msg:\"Testing sigordering\"; content:\"220\"; " + "offset:10; depth:4; pcre:\"/220[- ]/\"; rev:4; priority:3; sid:7;)"); FAIL_IF_NULL(sig); sig = DetectEngineAppendSig(de_ctx, - "pass tcp any !21:902 -> any any (msg:\"Testing sigordering\"; content:\"220\"; offset:10; depth:4; pcre:\"/220[- ]/\"; rev:4; priority:2; sid:8;)"); + "pass tcp any !21:902 -> any any (msg:\"Testing sigordering\"; content:\"220\"; " + "offset:10; depth:4; pcre:\"/220[- ]/\"; rev:4; priority:2; sid:8;)"); FAIL_IF_NULL(sig); sig = DetectEngineAppendSig(de_ctx, - "drop tcp any !21:902 -> any any (msg:\"Testing sigordering\"; content:\"220\"; offset:10; depth:4; pcre:\"/^User-Agent: (?P.*)\\r\\n/m\"; rev:4; priority:3; flowbits:set,TEST.one; flowbits:noalert; sid:9;)"); + "drop tcp any !21:902 -> any any (msg:\"Testing sigordering\"; content:\"220\"; " + "offset:10; depth:4; pcre:\"/^User-Agent: (?P.*)\\r\\n/m\"; rev:4; " + "priority:3; flowbits:set,TEST.one; flowbits:noalert; sid:9;)"); FAIL_IF_NULL(sig); sig = DetectEngineAppendSig(de_ctx, - "pass tcp any !21:902 -> any any (msg:\"Testing sigordering\"; content:\"220\"; offset:11; depth:4; pcre:\"/220[- ]/\"; rev:4; priority:3; sid:10;)"); + "pass tcp any !21:902 -> any any (msg:\"Testing sigordering\"; content:\"220\"; " + "offset:11; depth:4; pcre:\"/220[- ]/\"; rev:4; priority:3; sid:10;)"); FAIL_IF_NULL(sig); - sig = DetectEngineAppendSig(de_ctx, - "alert tcp any !21:902 -> any any (msg:\"Testing sigordering\"; content:\"220\"; offset:11; depth:4; pcre:\"/220[- ]/\"; rev:4; sid:11;)"); + sig = DetectEngineAppendSig( + de_ctx, "alert tcp any !21:902 -> any any (msg:\"Testing sigordering\"; " + "content:\"220\"; offset:11; depth:4; pcre:\"/220[- ]/\"; rev:4; sid:11;)"); FAIL_IF_NULL(sig); - sig = DetectEngineAppendSig(de_ctx, - "alert tcp any !21:902 -> any any (msg:\"Testing sigordering\"; content:\"220\"; offset:11; depth:4; pcre:\"/220[- ]/\"; rev:4; sid:12;)"); + sig = DetectEngineAppendSig( + de_ctx, "alert tcp any !21:902 -> any any (msg:\"Testing sigordering\"; " + "content:\"220\"; offset:11; depth:4; pcre:\"/220[- ]/\"; rev:4; sid:12;)"); FAIL_IF_NULL(sig); sig = DetectEngineAppendSig(de_ctx, - "drop tcp any !21:902 -> any any (msg:\"Testing sigordering\"; content:\"220\"; offset:12; depth:4; pcre:\"/220[- ]/\"; rev:4; pktvar:http_host,\"www.oisf.net\"; priority:2; flowbits:isnotset,TEST.two; sid:13;)"); + "drop tcp any !21:902 -> any any (msg:\"Testing sigordering\"; content:\"220\"; " + "offset:12; depth:4; pcre:\"/220[- ]/\"; rev:4; pktvar:http_host,\"www.oisf.net\"; " + "priority:2; flowbits:isnotset,TEST.two; sid:13;)"); FAIL_IF_NULL(sig); - sig = DetectEngineAppendSig(de_ctx, - "alert tcp any !21:902 -> any any (msg:\"Testing sigordering\"; content:\"220\"; offset:12; depth:4; pcre:\"/220[- ]/\"; rev:4; priority:2; flowbits:set,TEST.two; sid:14;)"); + sig = DetectEngineAppendSig( + de_ctx, "alert tcp any !21:902 -> any any (msg:\"Testing sigordering\"; " + "content:\"220\"; offset:12; depth:4; pcre:\"/220[- ]/\"; rev:4; priority:2; " + "flowbits:set,TEST.two; sid:14;)"); FAIL_IF_NULL(sig); SCSigRegisterSignatureOrderingFunc(de_ctx, SCSigOrderByActionCompare); @@ -1894,7 +1889,8 @@ static int SCSigOrderingTest12(void) de_ctx->flags |= DE_QUIET; const char *sigs[2]; - sigs[0] = "alert tcp any any -> any any (content:\"test\"; dsize:>0; flowbits:isset,one; flowbits:set,two; sid:1;)"; + sigs[0] = "alert tcp any any -> any any (content:\"test\"; dsize:>0; flowbits:isset,one; " + "flowbits:set,two; sid:1;)"; sigs[1] = "alert tcp any any -> any any (content:\"test\"; dsize:>0; flowbits:set,one; sid:2;)"; UTHAppendSigs(de_ctx, sigs, 2); @@ -1915,8 +1911,8 @@ static int SCSigOrderingTest12(void) UTHMatchPackets(de_ctx, &p, 1); - uint32_t sids[2] = {1, 2}; - uint32_t results[2] = {1, 1}; + uint32_t sids[2] = { 1, 2 }; + uint32_t results[2] = { 1, 1 }; FAIL_IF_NOT(UTHCheckPacketMatchResults(p, sids, results, 2)); UTHFreePackets(&p, 1); @@ -1937,11 +1933,14 @@ static int SCSigOrderingTest13(void) DetectEngineCtx *de_ctx = DetectEngineCtxInit(); FAIL_IF(de_ctx == NULL); - sig = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any (flowbits:isset,bit1; flowbits:set,bit2; flowbits:set,bit3; sid:6;)"); + sig = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any (flowbits:isset,bit1; " + "flowbits:set,bit2; flowbits:set,bit3; sid:6;)"); FAIL_IF_NULL(sig); - sig = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any (flowbits:set,bit1; flowbits:set,bit2; sid:7;)"); + sig = DetectEngineAppendSig( + de_ctx, "alert tcp any any -> any any (flowbits:set,bit1; flowbits:set,bit2; sid:7;)"); FAIL_IF_NULL(sig); - sig = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any (flowbits:isset,bit1; flowbits:isset,bit2; flowbits:isset,bit3; sid:5;)"); + sig = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any (flowbits:isset,bit1; " + "flowbits:isset,bit2; flowbits:isset,bit3; sid:5;)"); FAIL_IF_NULL(sig); SCSigRegisterSignatureOrderingFunc(de_ctx, SCSigOrderByFlowbitsCompare); diff --git a/src/detect-engine-sigorder.h b/src/detect-engine-sigorder.h index 7d7e10536171..93c53f3286c8 100644 --- a/src/detect-engine-sigorder.h +++ b/src/detect-engine-sigorder.h @@ -28,7 +28,7 @@ * \brief Different kinds of helper data that can be used by the signature * ordering module. Used by the "user" field in SCSigSignatureWrapper */ -typedef enum{ +typedef enum { SC_RADIX_USER_DATA_FLOWBITS, SC_RADIX_USER_DATA_FLOWVAR, SC_RADIX_USER_DATA_PKTVAR, diff --git a/src/detect-engine-state.c b/src/detect-engine-state.c index 74f87ff938f1..f7eb90a3318f 100644 --- a/src/detect-engine-state.c +++ b/src/detect-engine-state.c @@ -65,7 +65,9 @@ #include "flow-util.h" /** convert enum to string */ -#define CASE_CODE(E) case E: return #E +#define CASE_CODE(E) \ + case E: \ + return #E static inline int StateIsValid(uint16_t alproto, void *alstate) { @@ -101,15 +103,13 @@ static int DeStateSearchState(DetectEngineState *state, uint8_t direction, SigIn for (; tx_store != NULL; tx_store = tx_store->next) { SCLogDebug("tx_store %p", tx_store); - for (store_cnt = 0; - store_cnt < DE_STATE_CHUNK_SIZE && state_cnt < dir_state->cnt; - store_cnt++, state_cnt++) - { + for (store_cnt = 0; store_cnt < DE_STATE_CHUNK_SIZE && state_cnt < dir_state->cnt; + store_cnt++, state_cnt++) { DeStateStoreItem *item = &tx_store->store[store_cnt]; if (item->sid == num) { - SCLogDebug("sid %u already in state: %p %p %p %u %u, direction %s", - num, state, dir_state, tx_store, state_cnt, - store_cnt, direction & STREAM_TOSERVER ? "toserver" : "toclient"); + SCLogDebug("sid %u already in state: %p %p %p %u %u, direction %s", num, state, + dir_state, tx_store, state_cnt, store_cnt, + direction & STREAM_TOSERVER ? "toserver" : "toclient"); return 1; } } @@ -118,8 +118,8 @@ static int DeStateSearchState(DetectEngineState *state, uint8_t direction, SigIn } #endif -static void DeStateSignatureAppend(DetectEngineState *state, - const Signature *s, uint32_t inspect_flags, uint8_t direction) +static void DeStateSignatureAppend( + DetectEngineState *state, const Signature *s, uint32_t inspect_flags, uint8_t direction) { SCEnter(); @@ -188,14 +188,16 @@ void DetectEngineStateFree(DetectEngineState *state) return; } -static void StoreFileNoMatchCnt(DetectEngineState *de_state, uint16_t file_no_match, uint8_t direction) +static void StoreFileNoMatchCnt( + DetectEngineState *de_state, uint16_t file_no_match, uint8_t direction) { de_state->dir_state[(direction & STREAM_TOSERVER) ? 0 : 1].filestore_cnt += file_no_match; return; } -static bool StoreFilestoreSigsCantMatch(const SigGroupHead *sgh, const DetectEngineState *de_state, uint8_t direction) +static bool StoreFilestoreSigsCantMatch( + const SigGroupHead *sgh, const DetectEngineState *de_state, uint8_t direction) { if (de_state->dir_state[(direction & STREAM_TOSERVER) ? 0 : 1].filestore_cnt == sgh->filestore_cnt) @@ -207,7 +209,7 @@ static bool StoreFilestoreSigsCantMatch(const SigGroupHead *sgh, const DetectEng static void StoreStateTxHandleFiles(const SigGroupHead *sgh, Flow *f, DetectEngineState *destate, const uint8_t flow_flags, void *tx, const uint64_t tx_id, const uint16_t file_no_match) { - SCLogDebug("tx %"PRIu64", file_no_match %u", tx_id, file_no_match); + SCLogDebug("tx %" PRIu64 ", file_no_match %u", tx_id, file_no_match); StoreFileNoMatchCnt(destate, file_no_match, flow_flags); if (StoreFilestoreSigsCantMatch(sgh, destate, flow_flags)) { SCLogDebug("filestore sigs can't match"); @@ -218,11 +220,8 @@ static void StoreStateTxHandleFiles(const SigGroupHead *sgh, Flow *f, DetectEngi } } -void DetectRunStoreStateTx( - const SigGroupHead *sgh, - Flow *f, void *tx, uint64_t tx_id, - const Signature *s, - uint32_t inspect_flags, uint8_t flow_flags, +void DetectRunStoreStateTx(const SigGroupHead *sgh, Flow *f, void *tx, uint64_t tx_id, + const Signature *s, uint32_t inspect_flags, uint8_t flow_flags, const uint16_t file_no_match) { AppLayerTxData *tx_data = AppLayerParserGetTxData(f->proto, f->alproto, tx); @@ -235,12 +234,12 @@ void DetectRunStoreStateTx( tx_data->de_state = DetectEngineStateAlloc(); if (tx_data->de_state == NULL) return; - SCLogDebug("destate created for %"PRIu64, tx_id); + SCLogDebug("destate created for %" PRIu64, tx_id); } DeStateSignatureAppend(tx_data->de_state, s, inspect_flags, flow_flags); StoreStateTxHandleFiles(sgh, f, tx_data->de_state, flow_flags, tx, tx_id, file_no_match); - SCLogDebug("Stored for TX %"PRIu64, tx_id); + SCLogDebug("Stored for TX %" PRIu64, tx_id); } static inline void ResetTxState(DetectEngineState *s) @@ -278,7 +277,7 @@ void DetectEngineStateResetTxs(Flow *f) uint64_t total_txs = AppLayerParserGetTxCnt(f, alstate); - for ( ; inspect_tx_id < total_txs; inspect_tx_id++) { + for (; inspect_tx_id < total_txs; inspect_tx_id++) { void *inspect_tx = AppLayerParserGetTx(f->proto, f->alproto, alstate, inspect_tx_id); if (inspect_tx != NULL) { AppLayerTxData *txd = AppLayerParserGetTxData(f->proto, f->alproto, inspect_tx); @@ -297,12 +296,9 @@ void DetectEngineStateResetTxs(Flow *f) static int DeStateTest01(void) { - SCLogDebug("sizeof(DetectEngineState)\t\t%"PRIuMAX, - (uintmax_t)sizeof(DetectEngineState)); - SCLogDebug("sizeof(DeStateStore)\t\t\t%"PRIuMAX, - (uintmax_t)sizeof(DeStateStore)); - SCLogDebug("sizeof(DeStateStoreItem)\t\t%"PRIuMAX"", - (uintmax_t)sizeof(DeStateStoreItem)); + SCLogDebug("sizeof(DetectEngineState)\t\t%" PRIuMAX, (uintmax_t)sizeof(DetectEngineState)); + SCLogDebug("sizeof(DeStateStore)\t\t\t%" PRIuMAX, (uintmax_t)sizeof(DeStateStore)); + SCLogDebug("sizeof(DeStateStoreItem)\t\t%" PRIuMAX "", (uintmax_t)sizeof(DeStateStoreItem)); return 1; } @@ -449,9 +445,11 @@ static int DeStateTest03(void) FAIL_IF(state->dir_state[direction & STREAM_TOSERVER ? 0 : 1].head == NULL); FAIL_IF(state->dir_state[direction & STREAM_TOSERVER ? 0 : 1].head->store[0].sid != 11); - FAIL_IF(state->dir_state[direction & STREAM_TOSERVER ? 0 : 1].head->store[0].flags & BIT_U32(DE_STATE_FLAG_BASE)); + FAIL_IF(state->dir_state[direction & STREAM_TOSERVER ? 0 : 1].head->store[0].flags & + BIT_U32(DE_STATE_FLAG_BASE)); FAIL_IF(state->dir_state[direction & STREAM_TOSERVER ? 0 : 1].head->store[1].sid != 22); - FAIL_IF(!(state->dir_state[direction & STREAM_TOSERVER ? 0 : 1].head->store[1].flags & BIT_U32(DE_STATE_FLAG_BASE))); + FAIL_IF(!(state->dir_state[direction & STREAM_TOSERVER ? 0 : 1].head->store[1].flags & + BIT_U32(DE_STATE_FLAG_BASE))); DetectEngineStateFree(state); PASS; @@ -490,7 +488,7 @@ static int DeStateSigTest01(void) f.alproto = ALPROTO_HTTP1; p->flow = &f; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; @@ -500,7 +498,9 @@ static int DeStateSigTest01(void) FAIL_IF_NULL(de_ctx); de_ctx->flags |= DE_QUIET; - Signature *s = de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any (content:\"POST\"; http_method; content:\"dummy\"; http_cookie; sid:1; rev:1;)"); + Signature *s = de_ctx->sig_list = + SigInit(de_ctx, "alert tcp any any -> any any (content:\"POST\"; http_method; " + "content:\"dummy\"; http_cookie; sid:1; rev:1;)"); FAIL_IF_NULL(s); SigGroupBuild(de_ctx); @@ -574,7 +574,7 @@ static int DeStateSigTest02(void) f.flags |= FLOW_IPV4; p->flow = &f; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; f.alproto = ALPROTO_HTTP1; @@ -586,9 +586,14 @@ static int DeStateSigTest02(void) de_ctx->flags |= DE_QUIET; - Signature *s = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any (flow:to_server; content:\"POST\"; http_method; content:\"/\"; http_uri; content:\"Mozilla\"; http_header; content:\"dummy\"; http_cookie; content:\"body\"; nocase; http_client_body; sid:1; rev:1;)"); + Signature *s = DetectEngineAppendSig( + de_ctx, "alert tcp any any -> any any (flow:to_server; content:\"POST\"; http_method; " + "content:\"/\"; http_uri; content:\"Mozilla\"; http_header; content:\"dummy\"; " + "http_cookie; content:\"body\"; nocase; http_client_body; sid:1; rev:1;)"); FAIL_IF_NULL(s); - s = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any (flow:to_server; content:\"GET\"; http_method; content:\"Firefox\"; http_header; content:\"dummy2\"; http_cookie; sid:2; rev:1;)"); + s = DetectEngineAppendSig(de_ctx, + "alert tcp any any -> any any (flow:to_server; content:\"GET\"; http_method; " + "content:\"Firefox\"; http_header; content:\"dummy2\"; http_cookie; sid:2; rev:1;)"); FAIL_IF_NULL(s); SigGroupBuild(de_ctx); @@ -656,11 +661,13 @@ static int DeStateSigTest03(void) { uint8_t httpbuf1[] = "POST /upload.cgi HTTP/1.1\r\n" "Host: www.server.lan\r\n" - "Content-Type: multipart/form-data; boundary=---------------------------277531038314945\r\n" + "Content-Type: multipart/form-data; " + "boundary=---------------------------277531038314945\r\n" "Content-Length: 215\r\n" "\r\n" "-----------------------------277531038314945\r\n" - "Content-Disposition: form-data; name=\"uploadfile_0\"; filename=\"somepicture1.jpg\"\r\n" + "Content-Disposition: form-data; name=\"uploadfile_0\"; " + "filename=\"somepicture1.jpg\"\r\n" "Content-Type: image/jpeg\r\n" "\r\n" "filecontent\r\n" @@ -682,7 +689,9 @@ static int DeStateSigTest03(void) de_ctx->flags |= DE_QUIET; - Signature *s = DetectEngineAppendSig(de_ctx, "alert http any any -> any any (flow:to_server; content:\"POST\"; http_method; content:\"upload.cgi\"; http_uri; filestore; sid:1; rev:1;)"); + Signature *s = DetectEngineAppendSig( + de_ctx, "alert http any any -> any any (flow:to_server; content:\"POST\"; http_method; " + "content:\"upload.cgi\"; http_uri; filestore; sid:1; rev:1;)"); FAIL_IF_NULL(s); SigGroupBuild(de_ctx); @@ -698,7 +707,7 @@ static int DeStateSigTest03(void) FAIL_IF_NULL(p); p->flow = f; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; @@ -740,11 +749,13 @@ static int DeStateSigTest04(void) { uint8_t httpbuf1[] = "POST /upload.cgi HTTP/1.1\r\n" "Host: www.server.lan\r\n" - "Content-Type: multipart/form-data; boundary=---------------------------277531038314945\r\n" + "Content-Type: multipart/form-data; " + "boundary=---------------------------277531038314945\r\n" "Content-Length: 215\r\n" "\r\n" "-----------------------------277531038314945\r\n" - "Content-Disposition: form-data; name=\"uploadfile_0\"; filename=\"somepicture1.jpg\"\r\n" + "Content-Disposition: form-data; name=\"uploadfile_0\"; " + "filename=\"somepicture1.jpg\"\r\n" "Content-Type: image/jpeg\r\n" "\r\n" "filecontent\r\n" @@ -763,7 +774,9 @@ static int DeStateSigTest04(void) FAIL_IF_NULL(de_ctx); de_ctx->flags |= DE_QUIET; - Signature *s = DetectEngineAppendSig(de_ctx, "alert http any any -> any any (content:\"GET\"; http_method; content:\"upload.cgi\"; http_uri; filestore; sid:1; rev:1;)"); + Signature *s = DetectEngineAppendSig( + de_ctx, "alert http any any -> any any (content:\"GET\"; http_method; " + "content:\"upload.cgi\"; http_uri; filestore; sid:1; rev:1;)"); FAIL_IF_NULL(s); SigGroupBuild(de_ctx); @@ -779,7 +792,7 @@ static int DeStateSigTest04(void) Packet *p = UTHBuildPacket(NULL, 0, IPPROTO_TCP); FAIL_IF_NULL(p); p->flow = f; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; @@ -818,11 +831,13 @@ static int DeStateSigTest05(void) { uint8_t httpbuf1[] = "POST /upload.cgi HTTP/1.1\r\n" "Host: www.server.lan\r\n" - "Content-Type: multipart/form-data; boundary=---------------------------277531038314945\r\n" + "Content-Type: multipart/form-data; " + "boundary=---------------------------277531038314945\r\n" "Content-Length: 215\r\n" "\r\n" "-----------------------------277531038314945\r\n" - "Content-Disposition: form-data; name=\"uploadfile_0\"; filename=\"somepicture1.jpg\"\r\n" + "Content-Disposition: form-data; name=\"uploadfile_0\"; " + "filename=\"somepicture1.jpg\"\r\n" "Content-Type: image/jpeg\r\n" "\r\n" "filecontent\r\n" @@ -842,7 +857,9 @@ static int DeStateSigTest05(void) FAIL_IF_NULL(de_ctx); de_ctx->flags |= DE_QUIET; - Signature *s = DetectEngineAppendSig(de_ctx, "alert http any any -> any any (content:\"GET\"; http_method; content:\"upload.cgi\"; http_uri; filename:\"nomatch\"; sid:1; rev:1;)"); + Signature *s = DetectEngineAppendSig( + de_ctx, "alert http any any -> any any (content:\"GET\"; http_method; " + "content:\"upload.cgi\"; http_uri; filename:\"nomatch\"; sid:1; rev:1;)"); FAIL_IF_NULL(s); SigGroupBuild(de_ctx); @@ -857,7 +874,7 @@ static int DeStateSigTest05(void) Packet *p = UTHBuildPacket(NULL, 0, IPPROTO_TCP); FAIL_IF_NULL(p); p->flow = f; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; @@ -900,11 +917,13 @@ static int DeStateSigTest06(void) { uint8_t httpbuf1[] = "POST /upload.cgi HTTP/1.1\r\n" "Host: www.server.lan\r\n" - "Content-Type: multipart/form-data; boundary=---------------------------277531038314945\r\n" + "Content-Type: multipart/form-data; " + "boundary=---------------------------277531038314945\r\n" "Content-Length: 215\r\n" "\r\n" "-----------------------------277531038314945\r\n" - "Content-Disposition: form-data; name=\"uploadfile_0\"; filename=\"somepicture1.jpg\"\r\n" + "Content-Disposition: form-data; name=\"uploadfile_0\"; " + "filename=\"somepicture1.jpg\"\r\n" "Content-Type: image/jpeg\r\n" "\r\n" "filecontent\r\n" @@ -924,7 +943,9 @@ static int DeStateSigTest06(void) FAIL_IF_NULL(de_ctx); de_ctx->flags |= DE_QUIET; - Signature *s = DetectEngineAppendSig(de_ctx, "alert http any any -> any any (content:\"POST\"; http_method; content:\"upload.cgi\"; http_uri; filename:\"nomatch\"; filestore; sid:1; rev:1;)"); + Signature *s = DetectEngineAppendSig(de_ctx, + "alert http any any -> any any (content:\"POST\"; http_method; content:\"upload.cgi\"; " + "http_uri; filename:\"nomatch\"; filestore; sid:1; rev:1;)"); FAIL_IF_NULL(s); SigGroupBuild(de_ctx); @@ -940,7 +961,7 @@ static int DeStateSigTest06(void) Packet *p = UTHBuildPacket(NULL, 0, IPPROTO_TCP); FAIL_IF_NULL(p); p->flow = f; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; @@ -981,11 +1002,13 @@ static int DeStateSigTest07(void) { uint8_t httpbuf1[] = "POST /upload.cgi HTTP/1.1\r\n" "Host: www.server.lan\r\n" - "Content-Type: multipart/form-data; boundary=---------------------------277531038314945\r\n" + "Content-Type: multipart/form-data; " + "boundary=---------------------------277531038314945\r\n" "Content-Length: 215\r\n" "\r\n" "-----------------------------277531038314945\r\n" - "Content-Disposition: form-data; name=\"uploadfile_0\"; filename=\"somepicture1.jpg\"\r\n" + "Content-Disposition: form-data; name=\"uploadfile_0\"; " + "filename=\"somepicture1.jpg\"\r\n" "Content-Type: image/jpeg\r\n" "\r\n"; @@ -1007,7 +1030,9 @@ static int DeStateSigTest07(void) FAIL_IF_NULL(de_ctx); de_ctx->flags |= DE_QUIET; - Signature *s = DetectEngineAppendSig(de_ctx, "alert http any any -> any any (content:\"GET\"; http_method; content:\"upload.cgi\"; http_uri; filestore; sid:1; rev:1;)"); + Signature *s = DetectEngineAppendSig( + de_ctx, "alert http any any -> any any (content:\"GET\"; http_method; " + "content:\"upload.cgi\"; http_uri; filestore; sid:1; rev:1;)"); FAIL_IF_NULL(s); SigGroupBuild(de_ctx); @@ -1022,7 +1047,7 @@ static int DeStateSigTest07(void) Packet *p = UTHBuildPacket(NULL, 0, IPPROTO_TCP); FAIL_IF_NULL(p); p->flow = f; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; @@ -1069,11 +1094,13 @@ static int DeStateSigTest08(void) { uint8_t httpbuf1[] = "POST /upload.cgi HTTP/1.1\r\n" "Host: www.server.lan\r\n" - "Content-Type: multipart/form-data; boundary=---------------------------277531038314945\r\n" + "Content-Type: multipart/form-data; " + "boundary=---------------------------277531038314945\r\n" "Content-Length: 440\r\n" "\r\n" "-----------------------------277531038314945\r\n" - "Content-Disposition: form-data; name=\"uploadfile_0\"; filename=\"AAAApicture1.jpg\"\r\n" + "Content-Disposition: form-data; name=\"uploadfile_0\"; " + "filename=\"AAAApicture1.jpg\"\r\n" "Content-Type: image/jpeg\r\n" "\r\n"; @@ -1084,7 +1111,8 @@ static int DeStateSigTest08(void) "-----------------------------277531038314945\r\n"; uint32_t httplen3 = sizeof(httpbuf3) - 1; /* minus the \0 */ - uint8_t httpbuf4[] = "Content-Disposition: form-data; name=\"uploadfile_1\"; filename=\"BBBBpicture2.jpg\"\r\n" + uint8_t httpbuf4[] = "Content-Disposition: form-data; name=\"uploadfile_1\"; " + "filename=\"BBBBpicture2.jpg\"\r\n" "Content-Type: image/jpeg\r\n" "\r\n" "filecontent2\r\n" @@ -1105,7 +1133,9 @@ static int DeStateSigTest08(void) FAIL_IF_NULL(de_ctx); de_ctx->flags |= DE_QUIET; - Signature *s = DetectEngineAppendSig(de_ctx, "alert http any any -> any any (content:\"POST\"; http_method; content:\"upload.cgi\"; http_uri; filename:\"BBBBpicture\"; filestore; sid:1; rev:1;)"); + Signature *s = DetectEngineAppendSig(de_ctx, + "alert http any any -> any any (content:\"POST\"; http_method; content:\"upload.cgi\"; " + "http_uri; filename:\"BBBBpicture\"; filestore; sid:1; rev:1;)"); FAIL_IF_NULL(s); SigGroupBuild(de_ctx); @@ -1120,7 +1150,7 @@ static int DeStateSigTest08(void) Packet *p = UTHBuildPacket(NULL, 0, IPPROTO_TCP); FAIL_IF_NULL(p); p->flow = f; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; @@ -1197,11 +1227,13 @@ static int DeStateSigTest09(void) { uint8_t httpbuf1[] = "POST /upload.cgi HTTP/1.1\r\n" "Host: www.server.lan\r\n" - "Content-Type: multipart/form-data; boundary=---------------------------277531038314945\r\n" + "Content-Type: multipart/form-data; " + "boundary=---------------------------277531038314945\r\n" "Content-Length: 440\r\n" "\r\n" "-----------------------------277531038314945\r\n" - "Content-Disposition: form-data; name=\"uploadfile_0\"; filename=\"somepicture1.jpg\"\r\n" + "Content-Disposition: form-data; name=\"uploadfile_0\"; " + "filename=\"somepicture1.jpg\"\r\n" "Content-Type: image/jpeg\r\n" "\r\n"; @@ -1212,7 +1244,8 @@ static int DeStateSigTest09(void) "-----------------------------277531038314945\r\n"; uint32_t httplen3 = sizeof(httpbuf3) - 1; /* minus the \0 */ - uint8_t httpbuf4[] = "Content-Disposition: form-data; name=\"uploadfile_1\"; filename=\"somepicture2.jpg\"\r\n" + uint8_t httpbuf4[] = "Content-Disposition: form-data; name=\"uploadfile_1\"; " + "filename=\"somepicture2.jpg\"\r\n" "Content-Type: image/jpeg\r\n" "\r\n" "filecontent2\r\n" @@ -1233,7 +1266,9 @@ static int DeStateSigTest09(void) FAIL_IF_NULL(de_ctx); de_ctx->flags |= DE_QUIET; - Signature *s = DetectEngineAppendSig(de_ctx, "alert http any any -> any any (content:\"POST\"; http_method; content:\"upload.cgi\"; http_uri; filename:\"somepicture\"; filestore; sid:1; rev:1;)"); + Signature *s = DetectEngineAppendSig(de_ctx, + "alert http any any -> any any (content:\"POST\"; http_method; content:\"upload.cgi\"; " + "http_uri; filename:\"somepicture\"; filestore; sid:1; rev:1;)"); FAIL_IF_NULL(s); SigGroupBuild(de_ctx); @@ -1248,7 +1283,7 @@ static int DeStateSigTest09(void) Packet *p = UTHBuildPacket(NULL, 0, IPPROTO_TCP); FAIL_IF_NULL(p); p->flow = f; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; @@ -1323,11 +1358,13 @@ static int DeStateSigTest10(void) { uint8_t httpbuf1[] = "POST /upload.cgi HTTP/1.1\r\n" "Host: www.server.lan\r\n" - "Content-Type: multipart/form-data; boundary=---------------------------277531038314945\r\n" + "Content-Type: multipart/form-data; " + "boundary=---------------------------277531038314945\r\n" "Content-Length: 440\r\n" "\r\n" "-----------------------------277531038314945\r\n" - "Content-Disposition: form-data; name=\"uploadfile_0\"; filename=\"somepicture1.jpg\"\r\n" + "Content-Disposition: form-data; name=\"uploadfile_0\"; " + "filename=\"somepicture1.jpg\"\r\n" "Content-Type: image/jpeg\r\n" "\r\n"; @@ -1338,7 +1375,8 @@ static int DeStateSigTest10(void) "-----------------------------277531038314945\r\n"; uint32_t httplen3 = sizeof(httpbuf3) - 1; /* minus the \0 */ - uint8_t httpbuf4[] = "Content-Disposition: form-data; name=\"uploadfile_1\"; filename=\"somepicture2.jpg\"\r\n" + uint8_t httpbuf4[] = "Content-Disposition: form-data; name=\"uploadfile_1\"; " + "filename=\"somepicture2.jpg\"\r\n" "Content-Type: image/jpeg\r\n" "\r\n" "filecontent2\r\n" @@ -1359,7 +1397,8 @@ static int DeStateSigTest10(void) FAIL_IF_NULL(de_ctx); de_ctx->flags |= DE_QUIET; - Signature *s = DetectEngineAppendSig(de_ctx, "alert http any any -> any any (filename:\"somepicture\"; filestore; sid:1; rev:1;)"); + Signature *s = DetectEngineAppendSig(de_ctx, + "alert http any any -> any any (filename:\"somepicture\"; filestore; sid:1; rev:1;)"); FAIL_IF_NULL(s); SigGroupBuild(de_ctx); @@ -1374,7 +1413,7 @@ static int DeStateSigTest10(void) Packet *p = UTHBuildPacket(NULL, 0, IPPROTO_TCP); FAIL_IF_NULL(p); p->flow = f; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; diff --git a/src/detect-engine-state.h b/src/detect-engine-state.h index 25cd679a0dae..91379074b61d 100644 --- a/src/detect-engine-state.h +++ b/src/detect-engine-state.h @@ -31,12 +31,11 @@ * \author Anoop Saldanha */ - #ifndef __DETECT_ENGINE_STATE_H__ #define __DETECT_ENGINE_STATE_H__ -#define DETECT_ENGINE_INSPECT_SIG_NO_MATCH 0 -#define DETECT_ENGINE_INSPECT_SIG_MATCH 1 +#define DETECT_ENGINE_INSPECT_SIG_NO_MATCH 0 +#define DETECT_ENGINE_INSPECT_SIG_MATCH 1 #define DETECT_ENGINE_INSPECT_SIG_CANT_MATCH 2 /** indicate that the file inspection portion of a sig didn't match. * This is used to handle state keeping as the detect engine is still @@ -50,25 +49,25 @@ #define DETECT_ENGINE_INSPECT_SIG_MATCH_MORE_FILES 4 /** number of DeStateStoreItem's in one DeStateStore object */ -#define DE_STATE_CHUNK_SIZE 15 +#define DE_STATE_CHUNK_SIZE 15 /* per sig flags */ -#define DE_STATE_FLAG_FULL_INSPECT BIT_U32(0) -#define DE_STATE_FLAG_SIG_CANT_MATCH BIT_U32(1) +#define DE_STATE_FLAG_FULL_INSPECT BIT_U32(0) +#define DE_STATE_FLAG_SIG_CANT_MATCH BIT_U32(1) /* flag set if file inspecting sig did not match, but might need to be * re-evaluated for a new file in a tx */ -#define DE_STATE_ID_FILE_INSPECT 2UL -#define DE_STATE_FLAG_FILE_INSPECT BIT_U32(DE_STATE_ID_FILE_INSPECT) +#define DE_STATE_ID_FILE_INSPECT 2UL +#define DE_STATE_FLAG_FILE_INSPECT BIT_U32(DE_STATE_ID_FILE_INSPECT) /* first bit position after the built-ins */ -#define DE_STATE_FLAG_BASE 3UL +#define DE_STATE_FLAG_BASE 3UL /* state flags * * Used by app-layer-parsers to notify us that new files * are available in the tx. */ -#define DETECT_ENGINE_STATE_FLAG_FILE_NEW BIT_U8(0) +#define DETECT_ENGINE_STATE_FLAG_FILE_NEW BIT_U8(0) typedef struct DeStateStoreItem_ { uint32_t flags; diff --git a/src/detect-engine-tag.c b/src/detect-engine-tag.c index 21610264ef5b..d8b59c21da09 100644 --- a/src/detect-engine-tag.c +++ b/src/detect-engine-tag.c @@ -43,9 +43,9 @@ #include "flow-util.h" #include "stream-tcp-private.h" -SC_ATOMIC_DECLARE(unsigned int, num_tags); /**< Atomic counter, to know if we - have tagged hosts/sessions, - to avoid locking */ +SC_ATOMIC_DECLARE(unsigned int, num_tags); /**< Atomic counter, to know if we + have tagged hosts/sessions, + to avoid locking */ static HostStorageId host_tag_id = { .id = -1 }; /**< Host storage id for tags */ static FlowStorageId flow_tag_id = { .id = -1 }; /**< Flow storage id for tags */ @@ -159,10 +159,10 @@ int TagFlowAdd(Packet *p, DetectTagDataEntry *tde) new_tde->next = FlowGetStorageById(p->flow, flow_tag_id); FlowSetStorageById(p->flow, flow_tag_id, new_tde); SCLogDebug("adding tag with first_ts %u", new_tde->first_ts); - (void) SC_ATOMIC_ADD(num_tags, 1); + (void)SC_ATOMIC_ADD(num_tags, 1); } } else if (tag_cnt == DETECT_TAG_MAX_TAGS) { - SCLogDebug("Max tags for sessions reached (%"PRIu16")", tag_cnt); + SCLogDebug("Max tags for sessions reached (%" PRIu16 ")", tag_cnt); } return updated; @@ -204,7 +204,7 @@ int TagHashAddTag(DetectTagDataEntry *tde, Packet *p) DetectTagDataEntry *new_tde = DetectTagDataCopy(tde); if (new_tde != NULL) { HostSetStorageById(host, host_tag_id, new_tde); - (void) SC_ATOMIC_ADD(num_tags, 1); + (void)SC_ATOMIC_ADD(num_tags, 1); SCLogDebug("host tag added"); } } else { @@ -236,13 +236,13 @@ int TagHashAddTag(DetectTagDataEntry *tde, Packet *p) /* get a new tde as the one we have is on the stack */ DetectTagDataEntry *new_tde = DetectTagDataCopy(tde); if (new_tde != NULL) { - (void) SC_ATOMIC_ADD(num_tags, 1); + (void)SC_ATOMIC_ADD(num_tags, 1); new_tde->next = tag; HostSetStorageById(host, host_tag_id, new_tde); } } else if (ntags == DETECT_TAG_MAX_TAGS) { - SCLogDebug("Max tags for sessions reached (%"PRIu16")", ntags); + SCLogDebug("Max tags for sessions reached (%" PRIu16 ")", ntags); } } @@ -282,22 +282,21 @@ static void TagHandlePacketFlow(Flow *f, Packet *p) switch (iter->metric) { case DETECT_TAG_METRIC_PACKET: if (iter->packets > iter->count) { - SCLogDebug("flow tag expired: packets %u > %u", - iter->packets, iter->count); + SCLogDebug("flow tag expired: packets %u > %u", iter->packets, iter->count); /* tag expired */ if (prev != NULL) { tde = iter; prev->next = iter->next; iter = iter->next; SCFree(tde); - (void) SC_ATOMIC_SUB(num_tags, 1); + (void)SC_ATOMIC_SUB(num_tags, 1); continue; } else { FlowSetStorageById(p->flow, flow_tag_id, iter->next); tde = iter; iter = iter->next; SCFree(tde); - (void) SC_ATOMIC_SUB(num_tags, 1); + (void)SC_ATOMIC_SUB(num_tags, 1); continue; } } else if (flag_added == 0) { @@ -310,21 +309,20 @@ static void TagHandlePacketFlow(Flow *f, Packet *p) case DETECT_TAG_METRIC_BYTES: if (iter->bytes > iter->count) { /* tag expired */ - SCLogDebug("flow tag expired: bytes %u > %u", - iter->bytes, iter->count); + SCLogDebug("flow tag expired: bytes %u > %u", iter->bytes, iter->count); if (prev != NULL) { tde = iter; prev->next = iter->next; iter = iter->next; SCFree(tde); - (void) SC_ATOMIC_SUB(num_tags, 1); + (void)SC_ATOMIC_SUB(num_tags, 1); continue; } else { FlowSetStorageById(p->flow, flow_tag_id, iter->next); tde = iter; iter = iter->next; SCFree(tde); - (void) SC_ATOMIC_SUB(num_tags, 1); + (void)SC_ATOMIC_SUB(num_tags, 1); continue; } } else if (flag_added == 0) { @@ -338,23 +336,22 @@ static void TagHandlePacketFlow(Flow *f, Packet *p) /* last_ts handles this metric, but also a generic time based * expiration to prevent dead sessions/hosts */ if (iter->last_ts - iter->first_ts > iter->count) { - SCLogDebug("flow tag expired: %u - %u = %u > %u", - iter->last_ts, iter->first_ts, - (iter->last_ts - iter->first_ts), iter->count); + SCLogDebug("flow tag expired: %u - %u = %u > %u", iter->last_ts, + iter->first_ts, (iter->last_ts - iter->first_ts), iter->count); /* tag expired */ if (prev != NULL) { tde = iter; prev->next = iter->next; iter = iter->next; SCFree(tde); - (void) SC_ATOMIC_SUB(num_tags, 1); + (void)SC_ATOMIC_SUB(num_tags, 1); continue; } else { FlowSetStorageById(p->flow, flow_tag_id, iter->next); tde = iter; iter = iter->next; SCFree(tde); - (void) SC_ATOMIC_SUB(num_tags, 1); + (void)SC_ATOMIC_SUB(num_tags, 1); continue; } } else if (flag_added == 0) { @@ -365,7 +362,6 @@ static void TagHandlePacketFlow(Flow *f, Packet *p) } break; } - } prev = iter; @@ -410,13 +406,13 @@ static void TagHandlePacketHost(Host *host, Packet *p) prev->next = iter->next; iter = iter->next; SCFree(tde); - (void) SC_ATOMIC_SUB(num_tags, 1); + (void)SC_ATOMIC_SUB(num_tags, 1); continue; } else { tde = iter; iter = iter->next; SCFree(tde); - (void) SC_ATOMIC_SUB(num_tags, 1); + (void)SC_ATOMIC_SUB(num_tags, 1); HostSetStorageById(host, host_tag_id, iter); continue; } @@ -436,13 +432,13 @@ static void TagHandlePacketHost(Host *host, Packet *p) prev->next = iter->next; iter = iter->next; SCFree(tde); - (void) SC_ATOMIC_SUB(num_tags, 1); + (void)SC_ATOMIC_SUB(num_tags, 1); continue; } else { tde = iter; iter = iter->next; SCFree(tde); - (void) SC_ATOMIC_SUB(num_tags, 1); + (void)SC_ATOMIC_SUB(num_tags, 1); HostSetStorageById(host, host_tag_id, iter); continue; } @@ -457,22 +453,21 @@ static void TagHandlePacketHost(Host *host, Packet *p) /* last_ts handles this metric, but also a generic time based * expiration to prevent dead sessions/hosts */ if (iter->last_ts - iter->first_ts > iter->count) { - SCLogDebug("host tag expired: %u - %u = %u > %u", - iter->last_ts, iter->first_ts, - (iter->last_ts - iter->first_ts), iter->count); + SCLogDebug("host tag expired: %u - %u = %u > %u", iter->last_ts, + iter->first_ts, (iter->last_ts - iter->first_ts), iter->count); /* tag expired */ if (prev != NULL) { tde = iter; prev->next = iter->next; iter = iter->next; SCFree(tde); - (void) SC_ATOMIC_SUB(num_tags, 1); + (void)SC_ATOMIC_SUB(num_tags, 1); continue; } else { tde = iter; iter = iter->next; SCFree(tde); - (void) SC_ATOMIC_SUB(num_tags, 1); + (void)SC_ATOMIC_SUB(num_tags, 1); HostSetStorageById(host, host_tag_id, iter); continue; } @@ -484,7 +479,6 @@ static void TagHandlePacketHost(Host *host, Packet *p) } break; } - } prev = iter; @@ -520,8 +514,7 @@ static Host *GetLockedDstHost(Packet *p) * \param p packet * */ -void TagHandlePacket(DetectEngineCtx *de_ctx, - DetectEngineThreadCtx *det_ctx, Packet *p) +void TagHandlePacket(DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx, Packet *p) { SCEnter(); @@ -593,7 +586,7 @@ int TagTimeoutCheck(Host *host, SCTime_t ts) tmp = tde->next; SCFree(tde); - (void) SC_ATOMIC_SUB(num_tags, 1); + (void)SC_ATOMIC_SUB(num_tags, 1); } else { HostSetStorageById(host, host_tag_id, tmp->next); @@ -601,7 +594,7 @@ int TagTimeoutCheck(Host *host, SCTime_t ts) tmp = tde->next; SCFree(tde); - (void) SC_ATOMIC_SUB(num_tags, 1); + (void)SC_ATOMIC_SUB(num_tags, 1); } } return retval; @@ -612,7 +605,7 @@ int TagTimeoutCheck(Host *host, SCTime_t ts) /** * \test host tagging: packets */ -static int DetectTagTestPacket01 (void) +static int DetectTagTestPacket01(void) { uint8_t *buf = (uint8_t *)"Hi all!"; uint8_t *buf2 = (uint8_t *)"lalala!"; @@ -620,47 +613,30 @@ static int DetectTagTestPacket01 (void) uint16_t buf_len2 = strlen((char *)buf2); Packet *p[7]; - p[0] = UTHBuildPacketReal(buf, buf_len, IPPROTO_TCP, - "192.168.1.5", "192.168.1.1", - 41424, 80); - p[1] = UTHBuildPacketReal(buf2, buf_len2, IPPROTO_TCP, - "192.168.1.5", "192.168.1.1", - 41424, 80); - p[2] = UTHBuildPacketReal(buf2, buf_len2, IPPROTO_TCP, - "192.168.1.5", "192.168.1.9", - 41424, 80); - p[3] = UTHBuildPacketReal(buf2, buf_len2, IPPROTO_TCP, - "192.168.1.5", "192.168.1.9", - 41424, 80); - p[4] = UTHBuildPacketReal(buf2, buf_len2, IPPROTO_TCP, - "192.168.1.1", "192.168.1.9", - 41424, 80); - p[5] = UTHBuildPacketReal(buf2, buf_len2, IPPROTO_TCP, - "192.168.1.1", "192.168.1.11", - 41424, 80); - p[6] = UTHBuildPacketReal(buf2, buf_len2, IPPROTO_TCP, - "192.168.1.5", "192.168.1.11", - 41424, 80); + p[0] = UTHBuildPacketReal(buf, buf_len, IPPROTO_TCP, "192.168.1.5", "192.168.1.1", 41424, 80); + p[1] = UTHBuildPacketReal(buf2, buf_len2, IPPROTO_TCP, "192.168.1.5", "192.168.1.1", 41424, 80); + p[2] = UTHBuildPacketReal(buf2, buf_len2, IPPROTO_TCP, "192.168.1.5", "192.168.1.9", 41424, 80); + p[3] = UTHBuildPacketReal(buf2, buf_len2, IPPROTO_TCP, "192.168.1.5", "192.168.1.9", 41424, 80); + p[4] = UTHBuildPacketReal(buf2, buf_len2, IPPROTO_TCP, "192.168.1.1", "192.168.1.9", 41424, 80); + p[5] = UTHBuildPacketReal( + buf2, buf_len2, IPPROTO_TCP, "192.168.1.1", "192.168.1.11", 41424, 80); + p[6] = UTHBuildPacketReal( + buf2, buf_len2, IPPROTO_TCP, "192.168.1.5", "192.168.1.11", 41424, 80); const char *sigs[5]; - sigs[0]= "alert tcp any any -> any any (msg:\"Testing tag 1\"; content:\"Hi all\"; tag:host,3,packets,src; sid:1;)"; - sigs[1]= "alert tcp any any -> any any (msg:\"Testing tag 2\"; content:\"Hi all\"; tag:host,4,packets,dst; sid:2;)"; - sigs[2]= "alert tcp any any -> any any (msg:\"Testing tag 2\"; content:\"no match\"; sid:3;)"; - sigs[3]= "alert tcp any any -> any any (msg:\"Testing tag 2\"; content:\"no match\"; sid:4;)"; - sigs[4]= "alert tcp any any -> any any (msg:\"Testing tag 2\"; content:\"no match\"; sid:5;)"; + sigs[0] = "alert tcp any any -> any any (msg:\"Testing tag 1\"; content:\"Hi all\"; " + "tag:host,3,packets,src; sid:1;)"; + sigs[1] = "alert tcp any any -> any any (msg:\"Testing tag 2\"; content:\"Hi all\"; " + "tag:host,4,packets,dst; sid:2;)"; + sigs[2] = "alert tcp any any -> any any (msg:\"Testing tag 2\"; content:\"no match\"; sid:3;)"; + sigs[3] = "alert tcp any any -> any any (msg:\"Testing tag 2\"; content:\"no match\"; sid:4;)"; + sigs[4] = "alert tcp any any -> any any (msg:\"Testing tag 2\"; content:\"no match\"; sid:5;)"; /* Please, Notice that tagged data goes with sig_id = 1 and tag sig generator = 2 */ - uint32_t sid[5] = {1,2,3,4,5}; - - int32_t results[7][5] = { - {1, 1, 0, 0, 0}, - {0, 0, 0, 0, 0}, - {0, 0, 0, 0, 0}, - {0, 0, 0, 0, 0}, - {0, 0, 0, 0, 0}, - {0, 0, 0, 0, 0}, - {0, 0, 0, 0, 0} - }; + uint32_t sid[5] = { 1, 2, 3, 4, 5 }; + + int32_t results[7][5] = { { 1, 1, 0, 0, 0 }, { 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0 } }; StorageInit(); TagInitCtx(); StorageFinalize(); @@ -702,7 +678,7 @@ static int DetectTagTestPacket01 (void) /** * \test host tagging: seconds */ -static int DetectTagTestPacket02 (void) +static int DetectTagTestPacket02(void) { uint8_t *buf = (uint8_t *)"Hi all!"; uint8_t *buf2 = (uint8_t *)"lalala!"; @@ -725,52 +701,35 @@ static int DetectTagTestPacket02 (void) de_ctx->flags |= DE_QUIET; Packet *p[7]; - p[0] = UTHBuildPacketReal(buf, buf_len, IPPROTO_TCP, - "192.168.1.5", "192.168.1.1", - 41424, 80); - p[1] = UTHBuildPacketReal(buf2, buf_len2, IPPROTO_TCP, - "192.168.1.5", "192.168.1.1", - 41424, 80); - p[2] = UTHBuildPacketReal(buf2, buf_len2, IPPROTO_TCP, - "192.168.1.5", "192.168.1.9", - 41424, 80); - p[3] = UTHBuildPacketReal(buf2, buf_len2, IPPROTO_TCP, - "192.168.1.5", "192.168.1.9", - 41424, 80); - p[4] = UTHBuildPacketReal(buf2, buf_len2, IPPROTO_TCP, - "192.168.1.1", "192.168.1.9", - 41424, 80); - p[5] = UTHBuildPacketReal(buf2, buf_len2, IPPROTO_TCP, - "192.168.1.1", "192.168.1.11", - 41424, 80); - p[6] = UTHBuildPacketReal(buf2, buf_len2, IPPROTO_TCP, - "192.168.1.5", "192.168.1.11", - 41424, 80); + p[0] = UTHBuildPacketReal(buf, buf_len, IPPROTO_TCP, "192.168.1.5", "192.168.1.1", 41424, 80); + p[1] = UTHBuildPacketReal(buf2, buf_len2, IPPROTO_TCP, "192.168.1.5", "192.168.1.1", 41424, 80); + p[2] = UTHBuildPacketReal(buf2, buf_len2, IPPROTO_TCP, "192.168.1.5", "192.168.1.9", 41424, 80); + p[3] = UTHBuildPacketReal(buf2, buf_len2, IPPROTO_TCP, "192.168.1.5", "192.168.1.9", 41424, 80); + p[4] = UTHBuildPacketReal(buf2, buf_len2, IPPROTO_TCP, "192.168.1.1", "192.168.1.9", 41424, 80); + p[5] = UTHBuildPacketReal( + buf2, buf_len2, IPPROTO_TCP, "192.168.1.1", "192.168.1.11", 41424, 80); + p[6] = UTHBuildPacketReal( + buf2, buf_len2, IPPROTO_TCP, "192.168.1.5", "192.168.1.11", 41424, 80); const char *sigs[5]; - sigs[0]= "alert tcp any any -> any any (msg:\"Testing tag 1\"; content:\"Hi all\"; tag:host,3,seconds,src; sid:1;)"; - sigs[1]= "alert tcp any any -> any any (msg:\"Testing tag 2\"; content:\"Hi all\"; tag:host,8,seconds,dst; sid:2;)"; - sigs[2]= "alert tcp any any -> any any (msg:\"Testing tag 2\"; content:\"no match\"; sid:3;)"; - sigs[3]= "alert tcp any any -> any any (msg:\"Testing tag 2\"; content:\"no match\"; sid:4;)"; - sigs[4]= "alert tcp any any -> any any (msg:\"Testing tag 2\"; content:\"no match\"; sid:5;)"; + sigs[0] = "alert tcp any any -> any any (msg:\"Testing tag 1\"; content:\"Hi all\"; " + "tag:host,3,seconds,src; sid:1;)"; + sigs[1] = "alert tcp any any -> any any (msg:\"Testing tag 2\"; content:\"Hi all\"; " + "tag:host,8,seconds,dst; sid:2;)"; + sigs[2] = "alert tcp any any -> any any (msg:\"Testing tag 2\"; content:\"no match\"; sid:3;)"; + sigs[3] = "alert tcp any any -> any any (msg:\"Testing tag 2\"; content:\"no match\"; sid:4;)"; + sigs[4] = "alert tcp any any -> any any (msg:\"Testing tag 2\"; content:\"no match\"; sid:5;)"; /* Please, Notice that tagged data goes with sig_id = 1 and tag sig generator = 2 */ - uint32_t sid[5] = {1,2,3,4,5}; + uint32_t sid[5] = { 1, 2, 3, 4, 5 }; int numsigs = 5; FAIL_IF(UTHAppendSigs(de_ctx, sigs, numsigs) == 0); - //de_ctx->flags |= DE_QUIET; + // de_ctx->flags |= DE_QUIET; - int32_t results[7][5] = { - {1, 1, 0, 0, 0}, - {0, 0, 0, 0, 0}, - {0, 0, 0, 0, 0}, - {0, 0, 0, 0, 0}, - {0, 0, 0, 0, 0}, - {0, 0, 0, 0, 0}, - {0, 0, 0, 0, 0} - }; + int32_t results[7][5] = { { 1, 1, 0, 0, 0 }, { 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0 } }; int num_packets = 7; SigGroupBuild(de_ctx); @@ -804,7 +763,7 @@ static int DetectTagTestPacket02 (void) /** * \test host tagging: bytes */ -static int DetectTagTestPacket03 (void) +static int DetectTagTestPacket03(void) { uint8_t *buf = (uint8_t *)"Hi all!"; uint8_t *buf2 = (uint8_t *)"lalala!"; @@ -828,50 +787,33 @@ static int DetectTagTestPacket03 (void) de_ctx->flags |= DE_QUIET; Packet *p[7]; - p[0] = UTHBuildPacketReal(buf, buf_len, IPPROTO_TCP, - "192.168.1.5", "192.168.1.1", - 41424, 80); - p[1] = UTHBuildPacketReal(buf2, buf_len2, IPPROTO_TCP, - "192.168.1.5", "192.168.1.1", - 41424, 80); - p[2] = UTHBuildPacketReal(buf2, buf_len2, IPPROTO_TCP, - "192.168.1.5", "192.168.1.9", - 41424, 80); - p[3] = UTHBuildPacketReal(buf2, buf_len2, IPPROTO_TCP, - "192.168.1.5", "192.168.1.9", - 41424, 80); - p[4] = UTHBuildPacketReal(buf2, buf_len2, IPPROTO_TCP, - "192.168.1.1", "192.168.1.9", - 41424, 80); - p[5] = UTHBuildPacketReal(buf2, buf_len2, IPPROTO_TCP, - "192.168.1.1", "192.168.1.11", - 41424, 80); - p[6] = UTHBuildPacketReal(buf2, buf_len2, IPPROTO_TCP, - "192.168.1.5", "192.168.1.11", - 41424, 80); + p[0] = UTHBuildPacketReal(buf, buf_len, IPPROTO_TCP, "192.168.1.5", "192.168.1.1", 41424, 80); + p[1] = UTHBuildPacketReal(buf2, buf_len2, IPPROTO_TCP, "192.168.1.5", "192.168.1.1", 41424, 80); + p[2] = UTHBuildPacketReal(buf2, buf_len2, IPPROTO_TCP, "192.168.1.5", "192.168.1.9", 41424, 80); + p[3] = UTHBuildPacketReal(buf2, buf_len2, IPPROTO_TCP, "192.168.1.5", "192.168.1.9", 41424, 80); + p[4] = UTHBuildPacketReal(buf2, buf_len2, IPPROTO_TCP, "192.168.1.1", "192.168.1.9", 41424, 80); + p[5] = UTHBuildPacketReal( + buf2, buf_len2, IPPROTO_TCP, "192.168.1.1", "192.168.1.11", 41424, 80); + p[6] = UTHBuildPacketReal( + buf2, buf_len2, IPPROTO_TCP, "192.168.1.5", "192.168.1.11", 41424, 80); const char *sigs[5]; - sigs[0]= "alert tcp any any -> any any (msg:\"Testing tag 1\"; content:\"Hi all\"; tag:host, 150, bytes, src; sid:1;)"; - sigs[1]= "alert tcp any any -> any any (msg:\"Testing tag 2\"; content:\"Hi all\"; tag:host, 150, bytes, dst; sid:2;)"; - sigs[2]= "alert tcp any any -> any any (msg:\"Testing tag 2\"; content:\"no match\"; sid:3;)"; - sigs[3]= "alert tcp any any -> any any (msg:\"Testing tag 2\"; content:\"no match\"; sid:4;)"; - sigs[4]= "alert tcp any any -> any any (msg:\"Testing tag 2\"; content:\"no match\"; sid:5;)"; + sigs[0] = "alert tcp any any -> any any (msg:\"Testing tag 1\"; content:\"Hi all\"; tag:host, " + "150, bytes, src; sid:1;)"; + sigs[1] = "alert tcp any any -> any any (msg:\"Testing tag 2\"; content:\"Hi all\"; tag:host, " + "150, bytes, dst; sid:2;)"; + sigs[2] = "alert tcp any any -> any any (msg:\"Testing tag 2\"; content:\"no match\"; sid:3;)"; + sigs[3] = "alert tcp any any -> any any (msg:\"Testing tag 2\"; content:\"no match\"; sid:4;)"; + sigs[4] = "alert tcp any any -> any any (msg:\"Testing tag 2\"; content:\"no match\"; sid:5;)"; /* Please, Notice that tagged data goes with sig_id = 1 and tag sig generator = 2 */ - uint32_t sid[5] = {1,2,3,4,5}; + uint32_t sid[5] = { 1, 2, 3, 4, 5 }; int numsigs = 5; FAIL_IF(UTHAppendSigs(de_ctx, sigs, numsigs) == 0); - int32_t results[7][5] = { - {1, 1, 0, 0, 0}, - {0, 0, 0, 0, 0}, - {0, 0, 0, 0, 0}, - {0, 0, 0, 0, 0}, - {0, 0, 0, 0, 0}, - {0, 0, 0, 0, 0}, - {0, 0, 0, 0, 0} - }; + int32_t results[7][5] = { { 1, 1, 0, 0, 0 }, { 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0 } }; int num_packets = 7; SigGroupBuild(de_ctx); @@ -903,7 +845,7 @@ static int DetectTagTestPacket03 (void) /** * \test session tagging: packets */ -static int DetectTagTestPacket04 (void) +static int DetectTagTestPacket04(void) { uint8_t *buf = (uint8_t *)"Hi all!"; uint8_t *buf2 = (uint8_t *)"lalala!"; @@ -941,50 +883,30 @@ static int DetectTagTestPacket04 (void) de_ctx->flags |= DE_QUIET; Packet *p[7]; - p[0] = UTHBuildPacketReal(buf, buf_len, IPPROTO_TCP, - "192.168.1.5", "192.168.1.1", - 41424, 80); - p[1] = UTHBuildPacketReal(buf2, buf_len2, IPPROTO_TCP, - "192.168.1.5", "192.168.1.1", - 41424, 80); - p[2] = UTHBuildPacketReal(buf2, buf_len2, IPPROTO_TCP, - "192.168.1.5", "192.168.1.1", - 41424, 80); - p[3] = UTHBuildPacketReal(buf2, buf_len2, IPPROTO_TCP, - "192.168.1.5", "192.168.1.1", - 41424, 80); - p[4] = UTHBuildPacketReal(buf2, buf_len2, IPPROTO_TCP, - "192.168.1.1", "192.168.1.5", - 80, 41424); - p[5] = UTHBuildPacketReal(buf2, buf_len2, IPPROTO_TCP, - "192.168.1.1", "192.168.1.5", - 80, 41424); - p[6] = UTHBuildPacketReal(buf2, buf_len2, IPPROTO_TCP, - "192.168.1.5", "192.168.1.1", - 80, 41424); + p[0] = UTHBuildPacketReal(buf, buf_len, IPPROTO_TCP, "192.168.1.5", "192.168.1.1", 41424, 80); + p[1] = UTHBuildPacketReal(buf2, buf_len2, IPPROTO_TCP, "192.168.1.5", "192.168.1.1", 41424, 80); + p[2] = UTHBuildPacketReal(buf2, buf_len2, IPPROTO_TCP, "192.168.1.5", "192.168.1.1", 41424, 80); + p[3] = UTHBuildPacketReal(buf2, buf_len2, IPPROTO_TCP, "192.168.1.5", "192.168.1.1", 41424, 80); + p[4] = UTHBuildPacketReal(buf2, buf_len2, IPPROTO_TCP, "192.168.1.1", "192.168.1.5", 80, 41424); + p[5] = UTHBuildPacketReal(buf2, buf_len2, IPPROTO_TCP, "192.168.1.1", "192.168.1.5", 80, 41424); + p[6] = UTHBuildPacketReal(buf2, buf_len2, IPPROTO_TCP, "192.168.1.5", "192.168.1.1", 80, 41424); const char *sigs[5]; - sigs[0]= "alert tcp any any -> any any (msg:\"Testing tag 1\"; content:\"Hi all\"; tag:session,4,packets; sid:1;)"; - sigs[1]= "alert tcp any any -> any any (msg:\"Testing tag 2\"; content:\"blahblah\"; sid:2;)"; - sigs[2]= "alert tcp any any -> any any (msg:\"Testing tag 2\"; content:\"no match\"; sid:3;)"; - sigs[3]= "alert tcp any any -> any any (msg:\"Testing tag 2\"; content:\"no match\"; sid:4;)"; - sigs[4]= "alert tcp any any -> any any (msg:\"Testing tag 2\"; content:\"no match\"; sid:5;)"; + sigs[0] = "alert tcp any any -> any any (msg:\"Testing tag 1\"; content:\"Hi all\"; " + "tag:session,4,packets; sid:1;)"; + sigs[1] = "alert tcp any any -> any any (msg:\"Testing tag 2\"; content:\"blahblah\"; sid:2;)"; + sigs[2] = "alert tcp any any -> any any (msg:\"Testing tag 2\"; content:\"no match\"; sid:3;)"; + sigs[3] = "alert tcp any any -> any any (msg:\"Testing tag 2\"; content:\"no match\"; sid:4;)"; + sigs[4] = "alert tcp any any -> any any (msg:\"Testing tag 2\"; content:\"no match\"; sid:5;)"; /* Please, Notice that tagged data goes with sig_id = 1 and tag sig generator = 2 */ - uint32_t sid[5] = {1,2,3,4,5}; + uint32_t sid[5] = { 1, 2, 3, 4, 5 }; int numsigs = 5; FAIL_IF(UTHAppendSigs(de_ctx, sigs, numsigs) == 0); - int32_t results[7][5] = { - {1, 0, 0, 0, 0}, - {0, 0, 0, 0, 0}, - {0, 0, 0, 0, 0}, - {0, 0, 0, 0, 0}, - {0, 0, 0, 0, 0}, - {0, 0, 0, 0, 0}, - {0, 0, 0, 0, 0} - }; + int32_t results[7][5] = { { 1, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0 } }; int num_packets = 7; SigGroupBuild(de_ctx); @@ -1024,7 +946,7 @@ static int DetectTagTestPacket04 (void) /** * \test session tagging: seconds */ -static int DetectTagTestPacket05 (void) +static int DetectTagTestPacket05(void) { uint8_t *buf = (uint8_t *)"Hi all!"; uint8_t *buf2 = (uint8_t *)"lalala!"; @@ -1062,50 +984,30 @@ static int DetectTagTestPacket05 (void) de_ctx->flags |= DE_QUIET; Packet *p[7]; - p[0] = UTHBuildPacketReal(buf, buf_len, IPPROTO_TCP, - "192.168.1.5", "192.168.1.1", - 41424, 80); - p[1] = UTHBuildPacketReal(buf2, buf_len2, IPPROTO_TCP, - "192.168.1.5", "192.168.1.1", - 41424, 80); - p[2] = UTHBuildPacketReal(buf2, buf_len2, IPPROTO_TCP, - "192.168.1.5", "192.168.1.1", - 41424, 80); - p[3] = UTHBuildPacketReal(buf2, buf_len2, IPPROTO_TCP, - "192.168.1.5", "192.168.1.1", - 41424, 80); - p[4] = UTHBuildPacketReal(buf2, buf_len2, IPPROTO_TCP, - "192.168.1.1", "192.168.1.5", - 80, 41424); - p[5] = UTHBuildPacketReal(buf2, buf_len2, IPPROTO_TCP, - "192.168.1.1", "192.168.1.5", - 80, 41424); - p[6] = UTHBuildPacketReal(buf2, buf_len2, IPPROTO_TCP, - "192.168.1.5", "192.168.1.1", - 80, 41424); + p[0] = UTHBuildPacketReal(buf, buf_len, IPPROTO_TCP, "192.168.1.5", "192.168.1.1", 41424, 80); + p[1] = UTHBuildPacketReal(buf2, buf_len2, IPPROTO_TCP, "192.168.1.5", "192.168.1.1", 41424, 80); + p[2] = UTHBuildPacketReal(buf2, buf_len2, IPPROTO_TCP, "192.168.1.5", "192.168.1.1", 41424, 80); + p[3] = UTHBuildPacketReal(buf2, buf_len2, IPPROTO_TCP, "192.168.1.5", "192.168.1.1", 41424, 80); + p[4] = UTHBuildPacketReal(buf2, buf_len2, IPPROTO_TCP, "192.168.1.1", "192.168.1.5", 80, 41424); + p[5] = UTHBuildPacketReal(buf2, buf_len2, IPPROTO_TCP, "192.168.1.1", "192.168.1.5", 80, 41424); + p[6] = UTHBuildPacketReal(buf2, buf_len2, IPPROTO_TCP, "192.168.1.5", "192.168.1.1", 80, 41424); const char *sigs[5]; - sigs[0]= "alert tcp any any -> any any (msg:\"Testing tag 1\"; content:\"Hi all\"; tag:session,8,seconds; sid:1;)"; - sigs[1]= "alert tcp any any -> any any (msg:\"Testing tag 2\"; content:\"blahblah\"; sid:2;)"; - sigs[2]= "alert tcp any any -> any any (msg:\"Testing tag 2\"; content:\"no match\"; sid:3;)"; - sigs[3]= "alert tcp any any -> any any (msg:\"Testing tag 2\"; content:\"no match\"; sid:4;)"; - sigs[4]= "alert tcp any any -> any any (msg:\"Testing tag 2\"; content:\"no match\"; sid:5;)"; + sigs[0] = "alert tcp any any -> any any (msg:\"Testing tag 1\"; content:\"Hi all\"; " + "tag:session,8,seconds; sid:1;)"; + sigs[1] = "alert tcp any any -> any any (msg:\"Testing tag 2\"; content:\"blahblah\"; sid:2;)"; + sigs[2] = "alert tcp any any -> any any (msg:\"Testing tag 2\"; content:\"no match\"; sid:3;)"; + sigs[3] = "alert tcp any any -> any any (msg:\"Testing tag 2\"; content:\"no match\"; sid:4;)"; + sigs[4] = "alert tcp any any -> any any (msg:\"Testing tag 2\"; content:\"no match\"; sid:5;)"; /* Please, Notice that tagged data goes with sig_id = 1 and tag sig generator = 2 */ - uint32_t sid[5] = {1,2,3,4,5}; + uint32_t sid[5] = { 1, 2, 3, 4, 5 }; int numsigs = 5; FAIL_IF(UTHAppendSigs(de_ctx, sigs, numsigs) == 0); - int32_t results[7][5] = { - {1, 0, 0, 0, 0}, - {0, 0, 0, 0, 0}, - {0, 0, 0, 0, 0}, - {0, 0, 0, 0, 0}, - {0, 0, 0, 0, 0}, - {0, 0, 0, 0, 0}, - {0, 0, 0, 0, 0} - }; + int32_t results[7][5] = { { 1, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0 } }; int num_packets = 7; SigGroupBuild(de_ctx); @@ -1150,7 +1052,7 @@ static int DetectTagTestPacket05 (void) /** * \test session tagging: bytes */ -static int DetectTagTestPacket06 (void) +static int DetectTagTestPacket06(void) { uint8_t *buf = (uint8_t *)"Hi all!"; uint8_t *buf2 = (uint8_t *)"lalala!"; @@ -1188,50 +1090,30 @@ static int DetectTagTestPacket06 (void) de_ctx->flags |= DE_QUIET; Packet *p[7]; - p[0] = UTHBuildPacketReal(buf, buf_len, IPPROTO_TCP, - "192.168.1.5", "192.168.1.1", - 41424, 80); - p[1] = UTHBuildPacketReal(buf2, buf_len2, IPPROTO_TCP, - "192.168.1.5", "192.168.1.1", - 41424, 80); - p[2] = UTHBuildPacketReal(buf2, buf_len2, IPPROTO_TCP, - "192.168.1.5", "192.168.1.1", - 41424, 80); - p[3] = UTHBuildPacketReal(buf2, buf_len2, IPPROTO_TCP, - "192.168.1.5", "192.168.1.1", - 41424, 80); - p[4] = UTHBuildPacketReal(buf2, buf_len2, IPPROTO_TCP, - "192.168.1.1", "192.168.1.5", - 80, 41424); - p[5] = UTHBuildPacketReal(buf2, buf_len2, IPPROTO_TCP, - "192.168.1.1", "192.168.1.5", - 80, 41424); - p[6] = UTHBuildPacketReal(buf2, buf_len2, IPPROTO_TCP, - "192.168.1.5", "192.168.1.1", - 80, 41424); + p[0] = UTHBuildPacketReal(buf, buf_len, IPPROTO_TCP, "192.168.1.5", "192.168.1.1", 41424, 80); + p[1] = UTHBuildPacketReal(buf2, buf_len2, IPPROTO_TCP, "192.168.1.5", "192.168.1.1", 41424, 80); + p[2] = UTHBuildPacketReal(buf2, buf_len2, IPPROTO_TCP, "192.168.1.5", "192.168.1.1", 41424, 80); + p[3] = UTHBuildPacketReal(buf2, buf_len2, IPPROTO_TCP, "192.168.1.5", "192.168.1.1", 41424, 80); + p[4] = UTHBuildPacketReal(buf2, buf_len2, IPPROTO_TCP, "192.168.1.1", "192.168.1.5", 80, 41424); + p[5] = UTHBuildPacketReal(buf2, buf_len2, IPPROTO_TCP, "192.168.1.1", "192.168.1.5", 80, 41424); + p[6] = UTHBuildPacketReal(buf2, buf_len2, IPPROTO_TCP, "192.168.1.5", "192.168.1.1", 80, 41424); const char *sigs[5]; - sigs[0]= "alert tcp any any -> any any (msg:\"Testing tag 1\"; content:\"Hi all\"; tag:session,150,bytes; sid:1;)"; - sigs[1]= "alert tcp any any -> any any (msg:\"Testing tag 2\"; content:\"blahblah\"; sid:2;)"; - sigs[2]= "alert tcp any any -> any any (msg:\"Testing tag 2\"; content:\"no match\"; sid:3;)"; - sigs[3]= "alert tcp any any -> any any (msg:\"Testing tag 2\"; content:\"no match\"; sid:4;)"; - sigs[4]= "alert tcp any any -> any any (msg:\"Testing tag 2\"; content:\"no match\"; sid:5;)"; + sigs[0] = "alert tcp any any -> any any (msg:\"Testing tag 1\"; content:\"Hi all\"; " + "tag:session,150,bytes; sid:1;)"; + sigs[1] = "alert tcp any any -> any any (msg:\"Testing tag 2\"; content:\"blahblah\"; sid:2;)"; + sigs[2] = "alert tcp any any -> any any (msg:\"Testing tag 2\"; content:\"no match\"; sid:3;)"; + sigs[3] = "alert tcp any any -> any any (msg:\"Testing tag 2\"; content:\"no match\"; sid:4;)"; + sigs[4] = "alert tcp any any -> any any (msg:\"Testing tag 2\"; content:\"no match\"; sid:5;)"; /* Please, Notice that tagged data goes with sig_id = 1 and tag sig generator = 2 */ - uint32_t sid[5] = {1,2,3,4,5}; + uint32_t sid[5] = { 1, 2, 3, 4, 5 }; int numsigs = 5; FAIL_IF(UTHAppendSigs(de_ctx, sigs, numsigs) == 0); - int32_t results[7][5] = { - {1, 0, 0, 0, 0}, - {0, 0, 0, 0, 0}, - {0, 0, 0, 0, 0}, - {0, 0, 0, 0, 0}, - {0, 0, 0, 0, 0}, - {0, 0, 0, 0, 0}, - {0, 0, 0, 0, 0} - }; + int32_t results[7][5] = { { 1, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0 }, + { 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0 } }; int num_packets = 7; SigGroupBuild(de_ctx); @@ -1272,7 +1154,7 @@ static int DetectTagTestPacket06 (void) /** * \test session tagging: bytes, where a 2nd match makes us tag more */ -static int DetectTagTestPacket07 (void) +static int DetectTagTestPacket07(void) { uint8_t *buf = (uint8_t *)"Hi all!"; uint8_t *buf2 = (uint8_t *)"lalala!"; @@ -1310,49 +1192,29 @@ static int DetectTagTestPacket07 (void) de_ctx->flags |= DE_QUIET; Packet *p[7]; - p[0] = UTHBuildPacketReal(buf, buf_len, IPPROTO_TCP, - "192.168.1.5", "192.168.1.1", - 41424, 80); - p[1] = UTHBuildPacketReal(buf2, buf_len2, IPPROTO_TCP, - "192.168.1.5", "192.168.1.1", - 41424, 80); - p[2] = UTHBuildPacketReal(buf2, buf_len2, IPPROTO_TCP, - "192.168.1.5", "192.168.1.1", - 41424, 80); - p[3] = UTHBuildPacketReal(buf, buf_len, IPPROTO_TCP, - "192.168.1.5", "192.168.1.1", - 41424, 80); - p[4] = UTHBuildPacketReal(buf2, buf_len2, IPPROTO_TCP, - "192.168.1.1", "192.168.1.5", - 80, 41424); - p[5] = UTHBuildPacketReal(buf2, buf_len2, IPPROTO_TCP, - "192.168.1.1", "192.168.1.5", - 80, 41424); - p[6] = UTHBuildPacketReal(buf2, buf_len2, IPPROTO_TCP, - "192.168.1.5", "192.168.1.1", - 80, 41424); + p[0] = UTHBuildPacketReal(buf, buf_len, IPPROTO_TCP, "192.168.1.5", "192.168.1.1", 41424, 80); + p[1] = UTHBuildPacketReal(buf2, buf_len2, IPPROTO_TCP, "192.168.1.5", "192.168.1.1", 41424, 80); + p[2] = UTHBuildPacketReal(buf2, buf_len2, IPPROTO_TCP, "192.168.1.5", "192.168.1.1", 41424, 80); + p[3] = UTHBuildPacketReal(buf, buf_len, IPPROTO_TCP, "192.168.1.5", "192.168.1.1", 41424, 80); + p[4] = UTHBuildPacketReal(buf2, buf_len2, IPPROTO_TCP, "192.168.1.1", "192.168.1.5", 80, 41424); + p[5] = UTHBuildPacketReal(buf2, buf_len2, IPPROTO_TCP, "192.168.1.1", "192.168.1.5", 80, 41424); + p[6] = UTHBuildPacketReal(buf2, buf_len2, IPPROTO_TCP, "192.168.1.5", "192.168.1.1", 80, 41424); const char *sigs[5]; - sigs[0]= "alert tcp any any -> any any (msg:\"Testing tag 1\"; content:\"Hi all\"; tag:session,150,bytes; sid:1;)"; - sigs[1]= "alert tcp any any -> any any (msg:\"Testing tag 2\"; content:\"blahblah\"; sid:2;)"; - sigs[2]= "alert tcp any any -> any any (msg:\"Testing tag 2\"; content:\"no match\"; sid:3;)"; - sigs[3]= "alert tcp any any -> any any (msg:\"Testing tag 2\"; content:\"no match\"; sid:4;)"; - sigs[4]= "alert tcp any any -> any any (msg:\"Testing tag 2\"; content:\"no match\"; sid:5;)"; + sigs[0] = "alert tcp any any -> any any (msg:\"Testing tag 1\"; content:\"Hi all\"; " + "tag:session,150,bytes; sid:1;)"; + sigs[1] = "alert tcp any any -> any any (msg:\"Testing tag 2\"; content:\"blahblah\"; sid:2;)"; + sigs[2] = "alert tcp any any -> any any (msg:\"Testing tag 2\"; content:\"no match\"; sid:3;)"; + sigs[3] = "alert tcp any any -> any any (msg:\"Testing tag 2\"; content:\"no match\"; sid:4;)"; + sigs[4] = "alert tcp any any -> any any (msg:\"Testing tag 2\"; content:\"no match\"; sid:5;)"; /* Please, Notice that tagged data goes with sig_id = 1 and tag sig generator = 2 */ - uint32_t sid[5] = {1,2,3,4,5}; + uint32_t sid[5] = { 1, 2, 3, 4, 5 }; int numsigs = 5; FAIL_IF(UTHAppendSigs(de_ctx, sigs, numsigs) == 0); - int32_t results[7][5] = { - {1, 0, 0, 0, 0}, - {0, 0, 0, 0, 0}, - {0, 0, 0, 0, 0}, - {1, 0, 0, 0, 0}, - {0, 0, 0, 0, 0}, - {0, 0, 0, 0, 0}, - {0, 0, 0, 0, 0} - }; + int32_t results[7][5] = { { 1, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0 }, + { 1, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0 } }; int num_packets = 7; SigGroupBuild(de_ctx); @@ -1407,4 +1269,3 @@ void DetectEngineTagRegisterTests(void) UtRegisterTest("DetectTagTestPacket07", DetectTagTestPacket07); #endif /* UNITTESTS */ } - diff --git a/src/detect-engine-tag.h b/src/detect-engine-tag.h index 73f3fd871a35..448295a625f3 100644 --- a/src/detect-engine-tag.h +++ b/src/detect-engine-tag.h @@ -38,8 +38,8 @@ /* Used for tagged data (sid and gid of the packets that * follow the one that triggered the rule with tag option) */ -#define TAG_SIG_GEN 2 -#define TAG_SIG_ID 1 +#define TAG_SIG_GEN 2 +#define TAG_SIG_ID 1 int TagHashAddTag(DetectTagDataEntry *, Packet *); int TagFlowAdd(Packet *, DetectTagDataEntry *); @@ -57,5 +57,3 @@ int TagHostHasTag(Host *host); void DetectEngineTagRegisterTests(void); #endif /* __DETECT_ENGINE_TAG_H__ */ - - diff --git a/src/detect-engine-threshold.c b/src/detect-engine-threshold.c index b5ac8670d0bb..3b3d446f6d43 100644 --- a/src/detect-engine-threshold.c +++ b/src/detect-engine-threshold.c @@ -84,7 +84,8 @@ void ThresholdInit(void) if (host_threshold_id.id == -1) { FatalError("Can't initiate host storage for thresholding"); } - ippair_threshold_id = IPPairStorageRegister("threshold", sizeof(void *), NULL, ThresholdListFree); + ippair_threshold_id = + IPPairStorageRegister("threshold", sizeof(void *), NULL, ThresholdListFree); if (ippair_threshold_id.id == -1) { FatalError("Can't initiate IP pair storage for thresholding"); } @@ -178,8 +179,7 @@ static DetectThresholdEntry *ThresholdTimeoutCheck(DetectThresholdEntry *head, S DetectThresholdEntry *tde = tmp; if (prev != NULL) { prev->next = tmp->next; - } - else { + } else { new_head = tmp->next; } tmp = tde->next; @@ -191,7 +191,7 @@ static DetectThresholdEntry *ThresholdTimeoutCheck(DetectThresholdEntry *head, S int ThresholdHostTimeoutCheck(Host *host, SCTime_t ts) { - DetectThresholdEntry* head = HostGetStorageById(host, host_threshold_id); + DetectThresholdEntry *head = HostGetStorageById(host, host_threshold_id); DetectThresholdEntry *new_head = ThresholdTimeoutCheck(head, ts); if (new_head != head) { HostSetStorageById(host, host_threshold_id, new_head); @@ -201,7 +201,7 @@ int ThresholdHostTimeoutCheck(Host *host, SCTime_t ts) int ThresholdIPPairTimeoutCheck(IPPair *pair, SCTime_t ts) { - DetectThresholdEntry* head = IPPairGetStorageById(pair, ippair_threshold_id); + DetectThresholdEntry *head = IPPairGetStorageById(pair, ippair_threshold_id); DetectThresholdEntry *new_head = ThresholdTimeoutCheck(head, ts); if (new_head != head) { IPPairSetStorageById(pair, ippair_threshold_id, new_head); @@ -209,9 +209,8 @@ int ThresholdIPPairTimeoutCheck(IPPair *pair, SCTime_t ts) return new_head == NULL; } -static DetectThresholdEntry * -DetectThresholdEntryAlloc(const DetectThresholdData *td, Packet *p, - uint32_t sid, uint32_t gid) +static DetectThresholdEntry *DetectThresholdEntryAlloc( + const DetectThresholdData *td, Packet *p, uint32_t sid, uint32_t gid) { SCEnter(); @@ -228,8 +227,7 @@ DetectThresholdEntryAlloc(const DetectThresholdData *td, Packet *p, SCReturnPtr(ste, "DetectThresholdEntry"); } -static DetectThresholdEntry *ThresholdHostLookupEntry(Host *h, - uint32_t sid, uint32_t gid) +static DetectThresholdEntry *ThresholdHostLookupEntry(Host *h, uint32_t sid, uint32_t gid) { DetectThresholdEntry *e; @@ -241,8 +239,7 @@ static DetectThresholdEntry *ThresholdHostLookupEntry(Host *h, return e; } -static DetectThresholdEntry *ThresholdIPPairLookupEntry(IPPair *pair, - uint32_t sid, uint32_t gid) +static DetectThresholdEntry *ThresholdIPPairLookupEntry(IPPair *pair, uint32_t sid, uint32_t gid) { DetectThresholdEntry *e; @@ -254,8 +251,8 @@ static DetectThresholdEntry *ThresholdIPPairLookupEntry(IPPair *pair, return e; } -static int ThresholdHandlePacketSuppress(Packet *p, - const DetectThresholdData *td, uint32_t sid, uint32_t gid) +static int ThresholdHandlePacketSuppress( + Packet *p, const DetectThresholdData *td, uint32_t sid, uint32_t gid) { int ret = 0; DetectAddress *m = NULL; @@ -315,22 +312,22 @@ static inline void RateFilterSetAction(Packet *p, PacketAlert *pa, uint8_t new_a } /** -* \brief Check if the entry reached threshold count limit -* -* \param lookup_tsh Current threshold entry -* \param td Threshold settings -* \param packet_time used to compare against previous detection and to set timeouts -* -* \retval int 1 if threshold reached for this entry -* -*/ + * \brief Check if the entry reached threshold count limit + * + * \param lookup_tsh Current threshold entry + * \param td Threshold settings + * \param packet_time used to compare against previous detection and to set timeouts + * + * \retval int 1 if threshold reached for this entry + * + */ static int IsThresholdReached( DetectThresholdEntry *lookup_tsh, const DetectThresholdData *td, SCTime_t packet_time) { int ret = 0; /* Check if we have a timeout enabled, if so, - * we still matching (and enabling the new_action) */ + * we still matching (and enabling the new_action) */ if (lookup_tsh->tv_timeout != 0) { if ((SCTIME_SECS(packet_time) - lookup_tsh->tv_timeout) > td->timeout) { /* Ok, we are done, timeout reached */ @@ -340,15 +337,14 @@ static int IsThresholdReached( ret = 1; } /* else - if ((packet_time - lookup_tsh->tv_timeout) > td->timeout) */ - } - else { + } else { /* Update the matching state with the timeout interval */ SCTime_t entry = SCTIME_ADD_SECS(lookup_tsh->tv1, td->seconds); if (SCTIME_CMP_LTE(packet_time, entry)) { lookup_tsh->current_count++; if (lookup_tsh->current_count > td->count) { /* Then we must enable the new action by setting a - * timeout */ + * timeout */ lookup_tsh->tv_timeout = SCTIME_SECS(packet_time); ret = 1; } @@ -392,17 +388,16 @@ static void AddEntryToIPPairStorage(IPPair *pair, DetectThresholdEntry *e, SCTim * for this rule, then it will be returned in new_tsh. */ static int ThresholdHandlePacket(Packet *p, DetectThresholdEntry *lookup_tsh, - DetectThresholdEntry **new_tsh, const DetectThresholdData *td, - uint32_t sid, uint32_t gid, PacketAlert *pa) + DetectThresholdEntry **new_tsh, const DetectThresholdData *td, uint32_t sid, uint32_t gid, + PacketAlert *pa) { int ret = 0; - switch(td->type) { - case TYPE_LIMIT: - { + switch (td->type) { + case TYPE_LIMIT: { SCLogDebug("limit"); - if (lookup_tsh != NULL) { + if (lookup_tsh != NULL) { SCTime_t entry = SCTIME_ADD_SECS(lookup_tsh->tv1, td->seconds); if (SCTIME_CMP_LTE(p->ts, entry)) { lookup_tsh->current_count++; @@ -425,11 +420,10 @@ static int ThresholdHandlePacket(Packet *p, DetectThresholdEntry *lookup_tsh, } break; } - case TYPE_THRESHOLD: - { + case TYPE_THRESHOLD: { SCLogDebug("threshold"); - if (lookup_tsh != NULL) { + if (lookup_tsh != NULL) { SCTime_t entry = SCTIME_ADD_SECS(lookup_tsh->tv1, td->seconds); if (SCTIME_CMP_LTE(p->ts, entry)) { lookup_tsh->current_count++; @@ -443,7 +437,7 @@ static int ThresholdHandlePacket(Packet *p, DetectThresholdEntry *lookup_tsh, lookup_tsh->current_count = 1; } } else { - if (td->count == 1) { + if (td->count == 1) { ret = 1; } else { *new_tsh = DetectThresholdEntryAlloc(td, p, sid, gid); @@ -451,8 +445,7 @@ static int ThresholdHandlePacket(Packet *p, DetectThresholdEntry *lookup_tsh, } break; } - case TYPE_BOTH: - { + case TYPE_BOTH: { SCLogDebug("both"); if (lookup_tsh != NULL) { @@ -482,15 +475,14 @@ static int ThresholdHandlePacket(Packet *p, DetectThresholdEntry *lookup_tsh, /* for the first match we return 1 to * indicate we should alert */ - if (td->count == 1) { + if (td->count == 1) { ret = 1; } } break; } /* detection_filter */ - case TYPE_DETECTION: - { + case TYPE_DETECTION: { SCLogDebug("detection_filter"); if (lookup_tsh != NULL) { @@ -512,8 +504,7 @@ static int ThresholdHandlePacket(Packet *p, DetectThresholdEntry *lookup_tsh, break; } /* rate_filter */ - case TYPE_RATE: - { + case TYPE_RATE: { SCLogDebug("rate_filter"); ret = 1; if (lookup_tsh && IsThresholdReached(lookup_tsh, td, p->ts)) { @@ -531,7 +522,7 @@ static int ThresholdHandlePacket(Packet *p, DetectThresholdEntry *lookup_tsh, } static int ThresholdHandlePacketIPPair(IPPair *pair, Packet *p, const DetectThresholdData *td, - uint32_t sid, uint32_t gid, PacketAlert *pa) + uint32_t sid, uint32_t gid, PacketAlert *pa) { int ret = 0; @@ -572,7 +563,7 @@ static int ThresholdHandlePacketRule(DetectEngineCtx *de_ctx, Packet *p, { int ret = 0; - DetectThresholdEntry* lookup_tsh = (DetectThresholdEntry *)de_ctx->ths_ctx.th_entry[s->num]; + DetectThresholdEntry *lookup_tsh = (DetectThresholdEntry *)de_ctx->ths_ctx.th_entry[s->num]; SCLogDebug("by_rule lookup_tsh %p num %u", lookup_tsh, s->num); DetectThresholdEntry *new_tsh = NULL; @@ -610,17 +601,17 @@ int PacketAlertThreshold(DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx } if (td->type == TYPE_SUPPRESS) { - ret = ThresholdHandlePacketSuppress(p,td,s->id,s->gid); + ret = ThresholdHandlePacketSuppress(p, td, s->id, s->gid); } else if (td->track == TRACK_SRC) { Host *src = HostGetHostFromHash(&p->src); if (src) { - ret = ThresholdHandlePacketHost(src,p,td,s->id,s->gid,pa); + ret = ThresholdHandlePacketHost(src, p, td, s->id, s->gid, pa); HostRelease(src); } } else if (td->track == TRACK_DST) { Host *dst = HostGetHostFromHash(&p->dst); if (dst) { - ret = ThresholdHandlePacketHost(dst,p,td,s->id,s->gid,pa); + ret = ThresholdHandlePacketHost(dst, p, td, s->id, s->gid, pa); HostRelease(dst); } } else if (td->track == TRACK_BOTH) { @@ -631,7 +622,7 @@ int PacketAlertThreshold(DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx } } else if (td->track == TRACK_RULE) { SCMutexLock(&de_ctx->ths_ctx.threshold_table_lock); - ret = ThresholdHandlePacketRule(de_ctx,p,td,s,pa); + ret = ThresholdHandlePacketRule(de_ctx, p, td, s, pa); SCMutexUnlock(&de_ctx->ths_ctx.threshold_table_lock); } diff --git a/src/detect-engine-threshold.h b/src/detect-engine-threshold.h index 6fd7a9feaa58..5bedb17ad53b 100644 --- a/src/detect-engine-threshold.h +++ b/src/detect-engine-threshold.h @@ -39,9 +39,8 @@ int ThresholdIPPairHasThreshold(IPPair *pair); const DetectThresholdData *SigGetThresholdTypeIter( const Signature *, const SigMatchData **, int list); -int PacketAlertThreshold(DetectEngineCtx *, DetectEngineThreadCtx *, - const DetectThresholdData *, Packet *, - const Signature *, PacketAlert *); +int PacketAlertThreshold(DetectEngineCtx *, DetectEngineThreadCtx *, const DetectThresholdData *, + Packet *, const Signature *, PacketAlert *); void ThresholdHashInit(DetectEngineCtx *); void ThresholdHashAllocate(DetectEngineCtx *); diff --git a/src/detect-engine-uint.c b/src/detect-engine-uint.c index a02552bcd9de..58027c78535a 100644 --- a/src/detect-engine-uint.c +++ b/src/detect-engine-uint.c @@ -47,8 +47,7 @@ DetectUintData_u32 *DetectU32Parse(const char *u32str) return rs_detect_u32_parse(u32str); } -void -PrefilterPacketU32Set(PrefilterPacketHeaderValue *v, void *smctx) +void PrefilterPacketU32Set(PrefilterPacketHeaderValue *v, void *smctx) { const DetectUintData_u32 *a = smctx; v->u8[0] = a->mode; @@ -56,18 +55,15 @@ PrefilterPacketU32Set(PrefilterPacketHeaderValue *v, void *smctx) v->u32[2] = a->arg2; } -bool -PrefilterPacketU32Compare(PrefilterPacketHeaderValue v, void *smctx) +bool PrefilterPacketU32Compare(PrefilterPacketHeaderValue v, void *smctx) { const DetectUintData_u32 *a = smctx; - if (v.u8[0] == a->mode && - v.u32[1] == a->arg1 && - v.u32[2] == a->arg2) + if (v.u8[0] == a->mode && v.u32[1] == a->arg1 && v.u32[2] == a->arg2) return true; return false; } -//same as u32 but with u8 +// same as u32 but with u8 int DetectU8Match(const uint8_t parg, const DetectUintData_u8 *du8) { return rs_detect_u8_match(parg, du8); diff --git a/src/detect-engine.c b/src/detect-engine.c index a4ce2126544d..0f6aa264bf19 100644 --- a/src/detect-engine.c +++ b/src/detect-engine.c @@ -93,8 +93,8 @@ static int DetectEngineCtxLoadConf(DetectEngineCtx *); -static DetectEngineMasterCtx g_master_de_ctx = { SCMUTEX_INITIALIZER, - 0, 99, NULL, NULL, TENANT_SELECTOR_UNKNOWN, NULL, NULL, 0}; +static DetectEngineMasterCtx g_master_de_ctx = { SCMUTEX_INITIALIZER, 0, 99, NULL, NULL, + TENANT_SELECTOR_UNKNOWN, NULL, NULL, 0 }; static uint32_t TenantIdHash(HashTable *h, void *data, uint16_t data_len); static char TenantIdCompare(void *d1, uint16_t d1_len, void *d2, uint16_t d2_len); @@ -125,8 +125,7 @@ const struct SignatureProperties signature_properties[SIG_TYPE_MAX] = { /** \brief register inspect engine at start up time * * \note errors are fatal */ -void DetectPktInspectEngineRegister(const char *name, - InspectionBufferGetPktDataPtr GetPktData, +void DetectPktInspectEngineRegister(const char *name, InspectionBufferGetPktDataPtr GetPktData, InspectionBufferPktInspectFunc Callback) { DetectBufferTypeRegister(name); @@ -135,9 +134,7 @@ void DetectPktInspectEngineRegister(const char *name, FatalError("failed to register inspect engine %s", name); } - if ((sm_list < DETECT_SM_LIST_MATCH) || (sm_list >= SHRT_MAX) || - (Callback == NULL)) - { + if ((sm_list < DETECT_SM_LIST_MATCH) || (sm_list >= SHRT_MAX) || (Callback == NULL)) { SCLogError("Invalid arguments"); BUG_ON(1); } @@ -213,10 +210,8 @@ void DetectFrameInspectEngineRegister(const char *name, int dir, /** \brief register inspect engine at start up time * * \note errors are fatal */ -void DetectAppLayerInspectEngineRegister2(const char *name, - AppProto alproto, uint32_t dir, int progress, - InspectEngineFuncPtr2 Callback2, - InspectionBufferGetDataPtr GetData) +void DetectAppLayerInspectEngineRegister2(const char *name, AppProto alproto, uint32_t dir, + int progress, InspectEngineFuncPtr2 Callback2, InspectionBufferGetDataPtr GetData) { BUG_ON(progress >= 48); @@ -227,12 +222,9 @@ void DetectAppLayerInspectEngineRegister2(const char *name, } SCLogDebug("name %s id %d", name, sm_list); - if ((alproto >= ALPROTO_FAILED) || - (!(dir == SIG_FLAG_TOSERVER || dir == SIG_FLAG_TOCLIENT)) || - (sm_list < DETECT_SM_LIST_MATCH) || (sm_list >= SHRT_MAX) || - (progress < 0 || progress >= SHRT_MAX) || - (Callback2 == NULL)) - { + if ((alproto >= ALPROTO_FAILED) || (!(dir == SIG_FLAG_TOSERVER || dir == SIG_FLAG_TOCLIENT)) || + (sm_list < DETECT_SM_LIST_MATCH) || (sm_list >= SHRT_MAX) || + (progress < 0 || progress >= SHRT_MAX) || (Callback2 == NULL)) { SCLogError("Invalid arguments"); BUG_ON(1); } else if (Callback2 == DetectEngineInspectBufferGeneric && GetData == NULL) { @@ -274,15 +266,14 @@ void DetectAppLayerInspectEngineRegister2(const char *name, } /* copy an inspect engine with transforms to a new list id. */ -static void DetectAppLayerInspectEngineCopy( - DetectEngineCtx *de_ctx, - int sm_list, int new_list, +static void DetectAppLayerInspectEngineCopy(DetectEngineCtx *de_ctx, int sm_list, int new_list, const DetectEngineTransforms *transforms) { const DetectEngineAppInspectionEngine *t = g_app_inspect_engines; while (t) { if (t->sm_list == sm_list) { - DetectEngineAppInspectionEngine *new_engine = SCCalloc(1, sizeof(DetectEngineAppInspectionEngine)); + DetectEngineAppInspectionEngine *new_engine = + SCCalloc(1, sizeof(DetectEngineAppInspectionEngine)); if (unlikely(new_engine == NULL)) { exit(EXIT_FAILURE); } @@ -317,7 +308,8 @@ static void DetectAppLayerInspectEngineCopyListToDetectCtx(DetectEngineCtx *de_c const DetectEngineAppInspectionEngine *t = g_app_inspect_engines; DetectEngineAppInspectionEngine *list = de_ctx->app_inspect_engines; while (t) { - DetectEngineAppInspectionEngine *new_engine = SCCalloc(1, sizeof(DetectEngineAppInspectionEngine)); + DetectEngineAppInspectionEngine *new_engine = + SCCalloc(1, sizeof(DetectEngineAppInspectionEngine)); if (unlikely(new_engine == NULL)) { exit(EXIT_FAILURE); } @@ -340,15 +332,14 @@ static void DetectAppLayerInspectEngineCopyListToDetectCtx(DetectEngineCtx *de_c } /* copy an inspect engine with transforms to a new list id. */ -static void DetectPktInspectEngineCopy( - DetectEngineCtx *de_ctx, - int sm_list, int new_list, +static void DetectPktInspectEngineCopy(DetectEngineCtx *de_ctx, int sm_list, int new_list, const DetectEngineTransforms *transforms) { const DetectEnginePktInspectionEngine *t = g_pkt_inspect_engines; while (t) { if (t->sm_list == sm_list) { - DetectEnginePktInspectionEngine *new_engine = SCCalloc(1, sizeof(DetectEnginePktInspectionEngine)); + DetectEnginePktInspectionEngine *new_engine = + SCCalloc(1, sizeof(DetectEnginePktInspectionEngine)); if (unlikely(new_engine == NULL)) { exit(EXIT_FAILURE); } @@ -380,7 +371,8 @@ static void DetectPktInspectEngineCopyListToDetectCtx(DetectEngineCtx *de_ctx) const DetectEnginePktInspectionEngine *t = g_pkt_inspect_engines; while (t) { SCLogDebug("engine %p", t); - DetectEnginePktInspectionEngine *new_engine = SCCalloc(1, sizeof(DetectEnginePktInspectionEngine)); + DetectEnginePktInspectionEngine *new_engine = + SCCalloc(1, sizeof(DetectEnginePktInspectionEngine)); if (unlikely(new_engine == NULL)) { exit(EXIT_FAILURE); } @@ -528,7 +520,8 @@ static void AppendStreamInspectEngine( { bool prepend = false; - DetectEngineAppInspectionEngine *new_engine = SCCalloc(1, sizeof(DetectEngineAppInspectionEngine)); + DetectEngineAppInspectionEngine *new_engine = + SCCalloc(1, sizeof(DetectEngineAppInspectionEngine)); if (unlikely(new_engine == NULL)) { exit(EXIT_FAILURE); } @@ -801,8 +794,7 @@ int DetectEngineAppInspectionEngine2Signature(DetectEngineCtx *de_ctx, Signature } if ((s->init_data->init_flags & SIG_FLAG_INIT_STATE_MATCH) && - s->init_data->smlists[DETECT_SM_LIST_PMATCH] != NULL) - { + s->init_data->smlists[DETECT_SM_LIST_PMATCH] != NULL) { /* if engine is added multiple times, we pass it the same list */ SigMatchData *stream = SigMatchList2DataArray(s->init_data->smlists[DETECT_SM_LIST_PMATCH]); BUG_ON(stream == NULL); @@ -976,7 +968,8 @@ static char DetectBufferTypeCompareNameFunc(void *data1, uint16_t len1, void *da DetectBufferType *map2 = (DetectBufferType *)data2; char r = (strcmp(map1->name, map2->name) == 0); - r &= (memcmp((uint8_t *)&map1->transforms, (uint8_t *)&map2->transforms, sizeof(map2->transforms)) == 0); + r &= (memcmp((uint8_t *)&map1->transforms, (uint8_t *)&map2->transforms, + sizeof(map2->transforms)) == 0); return r; } @@ -1004,7 +997,8 @@ static void DetectBufferTypeFreeFunc(void *data) sigmatch_table[map->transforms.transforms[i].transform].name); continue; } - sigmatch_table[map->transforms.transforms[i].transform].Free(NULL, map->transforms.transforms[i].options); + sigmatch_table[map->transforms.transforms[i].transform].Free( + NULL, map->transforms.transforms[i].options); } SCFree(map); @@ -1315,8 +1309,8 @@ bool DetectEngineBufferTypeSupportsFramesGetById(const DetectEngineCtx *de_ctx, return map->frame; } -void DetectBufferTypeRegisterSetupCallback(const char *name, - void (*SetupCallback)(const DetectEngineCtx *, Signature *)) +void DetectBufferTypeRegisterSetupCallback( + const char *name, void (*SetupCallback)(const DetectEngineCtx *, Signature *)) { BUG_ON(g_buffer_type_reg_closed); DetectBufferTypeRegister(name); @@ -1333,8 +1327,8 @@ void DetectEngineBufferRunSetupCallback(const DetectEngineCtx *de_ctx, const int } } -void DetectBufferTypeRegisterValidateCallback(const char *name, - bool (*ValidateCallback)(const Signature *, const char **sigerror)) +void DetectBufferTypeRegisterValidateCallback( + const char *name, bool (*ValidateCallback)(const Signature *, const char **sigerror)) { BUG_ON(g_buffer_type_reg_closed); DetectBufferTypeRegister(name); @@ -1458,15 +1452,15 @@ int DetectBufferGetActiveList(DetectEngineCtx *de_ctx, Signature *s) if (s->init_data->list && s->init_data->transforms.cnt) { if (s->init_data->list == DETECT_SM_LIST_NOTSET || - s->init_data->list < DETECT_SM_LIST_DYNAMIC_START) { + s->init_data->list < DETECT_SM_LIST_DYNAMIC_START) { SCLogError("previous transforms not consumed " "(list: %u, transform_cnt %u)", s->init_data->list, s->init_data->transforms.cnt); SCReturnInt(-1); } - SCLogDebug("buffer %d has transform(s) registered: %d", - s->init_data->list, s->init_data->transforms.cnt); + SCLogDebug("buffer %d has transform(s) registered: %d", s->init_data->list, + s->init_data->transforms.cnt); int new_list = DetectEngineBufferTypeGetByIdTransforms(de_ctx, s->init_data->list, s->init_data->transforms.transforms, s->init_data->transforms.cnt); if (new_list == -1) { @@ -1503,8 +1497,7 @@ int DetectBufferGetActiveList(DetectEngineCtx *de_ctx, Signature *s) void InspectionBufferClean(DetectEngineThreadCtx *det_ctx) { /* single buffers */ - for (uint32_t i = 0; i < det_ctx->inspect.to_clear_idx; i++) - { + for (uint32_t i = 0; i < det_ctx->inspect.to_clear_idx; i++) { const uint32_t idx = det_ctx->inspect.to_clear_queue[i]; InspectionBuffer *buffer = &det_ctx->inspect.buffers[idx]; buffer->inspect = NULL; @@ -1513,8 +1506,7 @@ void InspectionBufferClean(DetectEngineThreadCtx *det_ctx) det_ctx->inspect.to_clear_idx = 0; /* multi buffers */ - for (uint32_t i = 0; i < det_ctx->multi_inspect.to_clear_idx; i++) - { + for (uint32_t i = 0; i < det_ctx->multi_inspect.to_clear_idx; i++) { const uint32_t idx = det_ctx->multi_inspect.to_clear_queue[i]; InspectionBufferMultipleForList *mbuffer = &det_ctx->multi_inspect.buffers[idx]; for (uint32_t x = 0; x <= mbuffer->max; x++) { @@ -1727,8 +1719,8 @@ bool DetectEngineBufferTypeValidateTransform(DetectEngineCtx *de_ctx, int sm_lis return true; } -void InspectionBufferApplyTransforms(InspectionBuffer *buffer, - const DetectEngineTransforms *transforms) +void InspectionBufferApplyTransforms( + InspectionBuffer *buffer, const DetectEngineTransforms *transforms) { if (transforms) { for (int i = 0; i < DETECT_TRANSFORMS_MAX; i++) { @@ -1888,11 +1880,9 @@ int DetectEngineBufferTypeGetByIdTransforms( if (map->frame) { DetectFrameMpmRegisterByParentId(de_ctx, map->id, map->parent_id, &map->transforms); } else if (map->packet) { - DetectPktMpmRegisterByParentId(de_ctx, - map->id, map->parent_id, &map->transforms); + DetectPktMpmRegisterByParentId(de_ctx, map->id, map->parent_id, &map->transforms); } else { - DetectAppLayerMpmRegisterByParentId(de_ctx, - map->id, map->parent_id, &map->transforms); + DetectAppLayerMpmRegisterByParentId(de_ctx, map->id, map->parent_id, &map->transforms); } BUG_ON(HashListTableAdd(de_ctx->buffer_type_hash_name, (void *)map, 0) != 0); @@ -1910,11 +1900,9 @@ int DetectEngineBufferTypeGetByIdTransforms( } /* returns false if no match, true if match */ -static int DetectEngineInspectRulePacketMatches( - DetectEngineThreadCtx *det_ctx, - const DetectEnginePktInspectionEngine *engine, - const Signature *s, - Packet *p, uint8_t *_alert_flags) +static int DetectEngineInspectRulePacketMatches(DetectEngineThreadCtx *det_ctx, + const DetectEnginePktInspectionEngine *engine, const Signature *s, Packet *p, + uint8_t *_alert_flags) { SCEnter(); @@ -1940,10 +1928,9 @@ static int DetectEngineInspectRulePacketMatches( return DETECT_ENGINE_INSPECT_SIG_MATCH; } -static int DetectEngineInspectRulePayloadMatches( - DetectEngineThreadCtx *det_ctx, - const DetectEnginePktInspectionEngine *engine, - const Signature *s, Packet *p, uint8_t *alert_flags) +static int DetectEngineInspectRulePayloadMatches(DetectEngineThreadCtx *det_ctx, + const DetectEnginePktInspectionEngine *engine, const Signature *s, Packet *p, + uint8_t *alert_flags) { SCEnter(); @@ -1986,10 +1973,8 @@ static int DetectEngineInspectRulePayloadMatches( return DETECT_ENGINE_INSPECT_SIG_MATCH; } -bool DetectEnginePktInspectionRun(ThreadVars *tv, - DetectEngineThreadCtx *det_ctx, const Signature *s, - Flow *f, Packet *p, - uint8_t *alert_flags) +bool DetectEnginePktInspectionRun(ThreadVars *tv, DetectEngineThreadCtx *det_ctx, + const Signature *s, Flow *f, Packet *p, uint8_t *alert_flags) { SCEnter(); @@ -2037,7 +2022,8 @@ static int DetectEnginePktInspectionAppend(Signature *s, InspectionBufferPktInsp int DetectEnginePktInspectionSetup(Signature *s) { /* only handle PMATCH here if we're not an app inspect rule */ - if (s->sm_arrays[DETECT_SM_LIST_PMATCH] && (s->init_data->init_flags & SIG_FLAG_INIT_STATE_MATCH) == 0) { + if (s->sm_arrays[DETECT_SM_LIST_PMATCH] && + (s->init_data->init_flags & SIG_FLAG_INIT_STATE_MATCH) == 0) { if (DetectEnginePktInspectionAppend( s, DetectEngineInspectRulePayloadMatches, NULL, DETECT_SM_LIST_PMATCH) < 0) return -1; @@ -2061,7 +2047,6 @@ enum DetectEngineSyncState { RELOAD, /**< command main thread to do the reload */ }; - typedef struct DetectEngineSyncer_ { SCMutex m; enum DetectEngineSyncState state; @@ -2138,8 +2123,8 @@ uint8_t DetectEngineInspectGenericList(DetectEngineCtx *de_ctx, DetectEngineThre while (1) { int match = 0; KEYWORD_PROFILING_START; - match = sigmatch_table[smd->type]. - AppLayerTxMatch(det_ctx, f, flags, alstate, txv, s, smd->ctx); + match = sigmatch_table[smd->type].AppLayerTxMatch( + det_ctx, f, flags, alstate, txv, s, smd->ctx); KEYWORD_PROFILING_END(det_ctx, smd->type, (match == 1)); if (match == 0) return DETECT_ENGINE_INSPECT_SIG_NO_MATCH; @@ -2156,7 +2141,6 @@ uint8_t DetectEngineInspectGenericList(DetectEngineCtx *de_ctx, DetectEngineThre return DETECT_ENGINE_INSPECT_SIG_MATCH; } - /** * \brief Do the content inspection & validation for a signature * @@ -2178,10 +2162,11 @@ uint8_t DetectEngineInspectBufferGeneric(DetectEngineCtx *de_ctx, DetectEngineTh const int list_id = engine->sm_list; SCLogDebug("running inspect on %d", list_id); - const bool eof = (AppLayerParserGetStateProgress(f->proto, f->alproto, txv, flags) > engine->progress); + const bool eof = + (AppLayerParserGetStateProgress(f->proto, f->alproto, txv, flags) > engine->progress); - SCLogDebug("list %d mpm? %s transforms %p", - engine->sm_list, engine->mpm ? "true" : "false", engine->v2.transforms); + SCLogDebug("list %d mpm? %s transforms %p", engine->sm_list, engine->mpm ? "true" : "false", + engine->v2.transforms); /* if prefilter didn't already run, we need to consider transformations */ const DetectEngineTransforms *transforms = NULL; @@ -2189,11 +2174,10 @@ uint8_t DetectEngineInspectBufferGeneric(DetectEngineCtx *de_ctx, DetectEngineTh transforms = engine->v2.transforms; } - const InspectionBuffer *buffer = engine->v2.GetData(det_ctx, transforms, - f, flags, txv, list_id); + const InspectionBuffer *buffer = + engine->v2.GetData(det_ctx, transforms, f, flags, txv, list_id); if (unlikely(buffer == NULL)) { - return eof ? DETECT_ENGINE_INSPECT_SIG_CANT_MATCH : - DETECT_ENGINE_INSPECT_SIG_NO_MATCH; + return eof ? DETECT_ENGINE_INSPECT_SIG_CANT_MATCH : DETECT_ENGINE_INSPECT_SIG_NO_MATCH; } const uint32_t data_len = buffer->inspect_len; @@ -2212,8 +2196,7 @@ uint8_t DetectEngineInspectBufferGeneric(DetectEngineCtx *de_ctx, DetectEngineTh if (match) { return DETECT_ENGINE_INSPECT_SIG_MATCH; } else { - return eof ? DETECT_ENGINE_INSPECT_SIG_CANT_MATCH : - DETECT_ENGINE_INSPECT_SIG_NO_MATCH; + return eof ? DETECT_ENGINE_INSPECT_SIG_CANT_MATCH : DETECT_ENGINE_INSPECT_SIG_NO_MATCH; } } @@ -2228,16 +2211,14 @@ uint8_t DetectEngineInspectBufferGeneric(DetectEngineCtx *de_ctx, DetectEngineTh * \retval 0 no match. * \retval 1 match. */ -int DetectEngineInspectPktBufferGeneric( - DetectEngineThreadCtx *det_ctx, - const DetectEnginePktInspectionEngine *engine, - const Signature *s, Packet *p, uint8_t *_alert_flags) +int DetectEngineInspectPktBufferGeneric(DetectEngineThreadCtx *det_ctx, + const DetectEnginePktInspectionEngine *engine, const Signature *s, Packet *p, + uint8_t *_alert_flags) { const int list_id = engine->sm_list; SCLogDebug("running inspect on %d", list_id); - SCLogDebug("list %d transforms %p", - engine->sm_list, engine->v1.transforms); + SCLogDebug("list %d transforms %p", engine->sm_list, engine->v1.transforms); /* if prefilter didn't already run, we need to consider transformations */ const DetectEngineTransforms *transforms = NULL; @@ -2245,13 +2226,12 @@ int DetectEngineInspectPktBufferGeneric( transforms = engine->v1.transforms; } - const InspectionBuffer *buffer = engine->v1.GetData(det_ctx, transforms, p, - list_id); + const InspectionBuffer *buffer = engine->v1.GetData(det_ctx, transforms, p, list_id); if (unlikely(buffer == NULL)) { return DETECT_ENGINE_INSPECT_SIG_NO_MATCH; } - uint8_t ci_flags = DETECT_CI_FLAGS_START|DETECT_CI_FLAGS_END; + uint8_t ci_flags = DETECT_CI_FLAGS_START | DETECT_CI_FLAGS_END; ci_flags |= buffer->flags; /* Inspect all the uricontents fetched on each @@ -2270,9 +2250,8 @@ int DetectEngineInspectPktBufferGeneric( * \brief inject a pseudo packet into each detect thread that doesn't use the * new det_ctx yet */ -static void InjectPackets(ThreadVars **detect_tvs, - DetectEngineThreadCtx **new_det_ctx, - int no_of_detect_tvs) +static void InjectPackets( + ThreadVars **detect_tvs, DetectEngineThreadCtx **new_det_ctx, int no_of_detect_tvs) { /* inject a fake packet if the detect thread isn't using the new ctx yet, * this speeds up the process */ @@ -2357,7 +2336,8 @@ static int DetectEngineReloadThreads(DetectEngineCtx *new_de_ctx) goto error; } SCLogDebug("live rule swap created new det_ctx - %p and de_ctx " - "- %p\n", new_det_ctx[i], new_de_ctx); + "- %p\n", + new_det_ctx[i], new_de_ctx); i++; break; } @@ -2375,8 +2355,8 @@ static int DetectEngineReloadThreads(DetectEngineCtx *new_de_ctx) if (!(tm->flags & TM_FLAG_DETECT_TM)) { continue; } - SCLogDebug("swapping new det_ctx - %p with older one - %p", - new_det_ctx[i], SC_ATOMIC_GET(s->slot_data)); + SCLogDebug("swapping new det_ctx - %p with older one - %p", new_det_ctx[i], + SC_ATOMIC_GET(s->slot_data)); FlowWorkerReplaceDetectCtx(SC_ATOMIC_GET(s->slot_data), new_det_ctx[i++]); break; } @@ -2387,7 +2367,8 @@ static int DetectEngineReloadThreads(DetectEngineCtx *new_de_ctx) * it and may still use the old data */ SCLogDebug("Live rule swap has swapped %d old det_ctx's with new ones, " - "along with the new de_ctx", no_of_detect_tvs); + "along with the new de_ctx", + no_of_detect_tvs); InjectPackets(detect_tvs, new_det_ctx, no_of_detect_tvs); @@ -2433,8 +2414,7 @@ static int DetectEngineReloadThreads(DetectEngineCtx *new_de_ctx) /* free all the ctxs */ for (i = 0; i < no_of_detect_tvs; i++) { - SCLogDebug("Freeing old_det_ctx - %p used by detect", - old_det_ctx[i]); + SCLogDebug("Freeing old_det_ctx - %p used by detect", old_det_ctx[i]); DetectEngineThreadCtxDeinit(NULL, old_det_ctx[i]); } @@ -2442,7 +2422,7 @@ static int DetectEngineReloadThreads(DetectEngineCtx *new_de_ctx) return 1; - error: +error: for (i = 0; i < no_of_detect_tvs; i++) { if (new_det_ctx[i] != NULL) DetectEngineThreadCtxDeinit(NULL, new_det_ctx[i]); @@ -2482,9 +2462,8 @@ static DetectEngineCtx *DetectEngineCtxInitReal( de_ctx->mpm_matcher = PatternMatchDefaultMatcher(); de_ctx->spm_matcher = SinglePatternMatchDefaultMatcher(); - SCLogConfig("pattern matchers: MPM: %s, SPM: %s", - mpm_table[de_ctx->mpm_matcher].name, - spm_table[de_ctx->spm_matcher].name); + SCLogConfig("pattern matchers: MPM: %s, SPM: %s", mpm_table[de_ctx->mpm_matcher].name, + spm_table[de_ctx->spm_matcher].name); de_ctx->spm_global_thread_ctx = SpmInitGlobalThreadCtx(de_ctx->spm_matcher); if (de_ctx->spm_global_thread_ctx == NULL) { @@ -2531,7 +2510,6 @@ static DetectEngineCtx *DetectEngineCtxInitReal( DetectEngineCtxFree(de_ctx); } return NULL; - } DetectEngineCtx *DetectEngineCtxInitStubForMT(void) @@ -2567,7 +2545,7 @@ static void DetectEngineCtxFreeFailedSigs(DetectEngineCtx *de_ctx) SigString *item = NULL; SigString *sitem; - TAILQ_FOREACH_SAFE(item, &de_ctx->sig_stat.failed_sigs, next, sitem) { + TAILQ_FOREACH_SAFE (item, &de_ctx->sig_stat.failed_sigs, next, sitem) { SCFree(item->filename); SCFree(item->sig_str); if (item->sig_error) { @@ -2597,8 +2575,8 @@ void DetectEngineCtxFree(DetectEngineCtx *de_ctx) #endif #ifdef PROFILING if (de_ctx->profile_keyword_ctx != NULL) { - SCProfilingKeywordDestroyCtx(de_ctx);//->profile_keyword_ctx); -// de_ctx->profile_keyword_ctx = NULL; + SCProfilingKeywordDestroyCtx(de_ctx); //->profile_keyword_ctx); + // de_ctx->profile_keyword_ctx = NULL; } if (de_ctx->profile_sgh_ctx != NULL) { SCProfilingSghDestroyCtx(de_ctx); @@ -2659,9 +2637,9 @@ void DetectEngineCtxFree(DetectEngineCtx *de_ctx) } SCFree(de_ctx); - //DetectAddressGroupPrintMemory(); - //DetectSigGroupPrintMemory(); - //DetectPortPrintMemory(); + // DetectAddressGroupPrintMemory(); + // DetectSigGroupPrintMemory(); + // DetectPortPrintMemory(); } /** \brief Function that load DetectEngineCtx config for grouping sigs @@ -2684,7 +2662,7 @@ static int DetectEngineCtxLoadConf(DetectEngineCtx *de_ctx) ConfNode *opt = NULL; if (de_ctx_custom != NULL) { - TAILQ_FOREACH(opt, &de_ctx_custom->head, next) { + TAILQ_FOREACH (opt, &de_ctx_custom->head, next) { if (de_ctx_profile == NULL) { if (opt->val && strcmp(opt->val, "profile") == 0) { de_ctx_profile = opt->head.tqh_first->val; @@ -2700,8 +2678,7 @@ static int DetectEngineCtxLoadConf(DetectEngineCtx *de_ctx) } if (de_ctx_profile != NULL) { - if (strcmp(de_ctx_profile, "low") == 0 || - strcmp(de_ctx_profile, "lowest") == 0) { // legacy + if (strcmp(de_ctx_profile, "low") == 0 || strcmp(de_ctx_profile, "lowest") == 0) { // legacy profile = ENGINE_PROFILE_LOW; } else if (strcmp(de_ctx_profile, "medium") == 0) { profile = ENGINE_PROFILE_MEDIUM; @@ -2765,29 +2742,27 @@ static int DetectEngineCtxLoadConf(DetectEngineCtx *de_ctx) break; case ENGINE_PROFILE_CUSTOM: - (void)ConfGet("detect.custom-values.toclient-groups", - &max_uniq_toclient_groups_str); - (void)ConfGet("detect.custom-values.toserver-groups", - &max_uniq_toserver_groups_str); + (void)ConfGet("detect.custom-values.toclient-groups", &max_uniq_toclient_groups_str); + (void)ConfGet("detect.custom-values.toserver-groups", &max_uniq_toserver_groups_str); if (de_ctx_custom != NULL) { - TAILQ_FOREACH(opt, &de_ctx_custom->head, next) { + TAILQ_FOREACH (opt, &de_ctx_custom->head, next) { if (opt->val && strcmp(opt->val, "custom-values") == 0) { if (max_uniq_toclient_groups_str == NULL) { - max_uniq_toclient_groups_str = (char *)ConfNodeLookupChildValue - (opt->head.tqh_first, "toclient-sp-groups"); + max_uniq_toclient_groups_str = (char *)ConfNodeLookupChildValue( + opt->head.tqh_first, "toclient-sp-groups"); } if (max_uniq_toclient_groups_str == NULL) { - max_uniq_toclient_groups_str = (char *)ConfNodeLookupChildValue - (opt->head.tqh_first, "toclient-groups"); + max_uniq_toclient_groups_str = (char *)ConfNodeLookupChildValue( + opt->head.tqh_first, "toclient-groups"); } if (max_uniq_toserver_groups_str == NULL) { - max_uniq_toserver_groups_str = (char *)ConfNodeLookupChildValue - (opt->head.tqh_first, "toserver-dp-groups"); + max_uniq_toserver_groups_str = (char *)ConfNodeLookupChildValue( + opt->head.tqh_first, "toserver-dp-groups"); } if (max_uniq_toserver_groups_str == NULL) { - max_uniq_toserver_groups_str = (char *)ConfNodeLookupChildValue - (opt->head.tqh_first, "toserver-groups"); + max_uniq_toserver_groups_str = (char *)ConfNodeLookupChildValue( + opt->head.tqh_first, "toserver-groups"); } } } @@ -2833,20 +2808,19 @@ static int DetectEngineCtxLoadConf(DetectEngineCtx *de_ctx) } intmax_t value = 0; - if (ConfGetInt("detect.inspection-recursion-limit", &value) == 1) - { + if (ConfGetInt("detect.inspection-recursion-limit", &value) == 1) { if (value >= 0 && value <= INT_MAX) { de_ctx->inspection_recursion_limit = (int)value; } - /* fall back to old config parsing */ + /* fall back to old config parsing */ } else { ConfNode *insp_recursion_limit_node = NULL; char *insp_recursion_limit = NULL; if (de_ctx_custom != NULL) { opt = NULL; - TAILQ_FOREACH(opt, &de_ctx_custom->head, next) { + TAILQ_FOREACH (opt, &de_ctx_custom->head, next) { if (opt->val && strcmp(opt->val, "inspection-recursion-limit") != 0) continue; @@ -2863,18 +2837,18 @@ static int DetectEngineCtxLoadConf(DetectEngineCtx *de_ctx) } if (insp_recursion_limit != NULL) { - if (StringParseInt32(&de_ctx->inspection_recursion_limit, 10, - 0, (const char *)insp_recursion_limit) < 0) { + if (StringParseInt32(&de_ctx->inspection_recursion_limit, 10, 0, + (const char *)insp_recursion_limit) < 0) { SCLogWarning("Invalid value for " "detect-engine.inspection-recursion-limit: %s " "resetting to %d", insp_recursion_limit, DETECT_ENGINE_DEFAULT_INSPECTION_RECURSION_LIMIT); de_ctx->inspection_recursion_limit = - DETECT_ENGINE_DEFAULT_INSPECTION_RECURSION_LIMIT; + DETECT_ENGINE_DEFAULT_INSPECTION_RECURSION_LIMIT; } } else { de_ctx->inspection_recursion_limit = - DETECT_ENGINE_DEFAULT_INSPECTION_RECURSION_LIMIT; + DETECT_ENGINE_DEFAULT_INSPECTION_RECURSION_LIMIT; } } } @@ -2882,8 +2856,7 @@ static int DetectEngineCtxLoadConf(DetectEngineCtx *de_ctx) if (de_ctx->inspection_recursion_limit == 0) de_ctx->inspection_recursion_limit = -1; - SCLogDebug("de_ctx->inspection_recursion_limit: %d", - de_ctx->inspection_recursion_limit); + SCLogDebug("de_ctx->inspection_recursion_limit: %d", de_ctx->inspection_recursion_limit); /* parse port grouping whitelisting settings */ @@ -2894,7 +2867,6 @@ static int DetectEngineCtxLoadConf(DetectEngineCtx *de_ctx) } else { ports = "53, 80, 139, 443, 445, 1433, 3306, 3389, 6666, 6667, 8080"; SCLogConfig("grouping: tcp-whitelist (default) %s", ports); - } if (DetectPortParse(de_ctx, &de_ctx->tcp_whitelist, ports) != 0) { SCLogWarning("'%s' is not a valid value " @@ -2902,7 +2874,7 @@ static int DetectEngineCtxLoadConf(DetectEngineCtx *de_ctx) ports); } DetectPort *x = de_ctx->tcp_whitelist; - for ( ; x != NULL; x = x->next) { + for (; x != NULL; x = x->next) { if (x->port != x->port2) { SCLogWarning("'%s' is not a valid value " "for detect.grouping.tcp-whitelist: only single ports allowed", @@ -2920,14 +2892,13 @@ static int DetectEngineCtxLoadConf(DetectEngineCtx *de_ctx) } else { ports = "53, 135, 5060"; SCLogConfig("grouping: udp-whitelist (default) %s", ports); - } if (DetectPortParse(de_ctx, &de_ctx->udp_whitelist, ports) != 0) { SCLogWarning("'%s' is not a valid value " "for detect.grouping.udp-whitelist", ports); } - for (x = de_ctx->udp_whitelist; x != NULL; x = x->next) { + for (x = de_ctx->udp_whitelist; x != NULL; x = x->next) { if (x->port != x->port2) { SCLogWarning("'%s' is not a valid value " "for detect.grouping.udp-whitelist: only single ports allowed", @@ -2963,7 +2934,7 @@ static int DetectEngineCtxLoadConf(DetectEngineCtx *de_ctx) * getting & (re)setting the internal sig i */ -//inline uint32_t DetectEngineGetMaxSigId(DetectEngineCtx *de_ctx) +// inline uint32_t DetectEngineGetMaxSigId(DetectEngineCtx *de_ctx) //{ // return de_ctx->signum; //} @@ -3003,8 +2974,7 @@ static int DetectEngineThreadCtxInitGlobalKeywords(DetectEngineThreadCtx *det_ct static void DetectEngineThreadCtxDeinitGlobalKeywords(DetectEngineThreadCtx *det_ctx) { - if (det_ctx->global_keyword_ctxs_array == NULL || - det_ctx->global_keyword_ctxs_size == 0) { + if (det_ctx->global_keyword_ctxs_array == NULL || det_ctx->global_keyword_ctxs_size == 0) { return; } @@ -3023,7 +2993,8 @@ static void DetectEngineThreadCtxDeinitGlobalKeywords(DetectEngineThreadCtx *det } } -static int DetectEngineThreadCtxInitKeywords(DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx) +static int DetectEngineThreadCtxInitKeywords( + DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx) { if (de_ctx->keyword_id > 0) { // coverity[suspicious_sizeof : FALSE] @@ -3051,7 +3022,8 @@ static int DetectEngineThreadCtxInitKeywords(DetectEngineCtx *de_ctx, DetectEngi return TM_ECODE_OK; } -static void DetectEngineThreadCtxDeinitKeywords(DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx) +static void DetectEngineThreadCtxDeinitKeywords( + DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx) { if (de_ctx->keyword_id > 0) { HashListTableBucket *hb = HashListTableGetListHead(de_ctx->keyword_hash); @@ -3128,7 +3100,6 @@ static TmEcode DetectEngineThreadCtxInitForMT(ThreadVars *tv, DetectEngineThread map_cnt++; map = map->next; } - } /* set up hash for tenant lookup */ @@ -3186,7 +3157,7 @@ static TmEcode DetectEngineThreadCtxInitForMT(ThreadVars *tv, DetectEngineThread /** \internal * \brief Helper for DetectThread setup functions */ -static TmEcode ThreadCtxDoInit (DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx) +static TmEcode ThreadCtxDoInit(DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx) { PatternMatchThreadPrepare(&det_ctx->mtc, de_ctx->mpm_matcher); @@ -3200,7 +3171,7 @@ static TmEcode ThreadCtxDoInit (DetectEngineCtx *de_ctx, DetectEngineThreadCtx * /* sized to the max of our sgh settings. A max setting of 0 implies that all * sgh's have: sgh->non_pf_store_cnt == 0 */ if (de_ctx->non_pf_store_cnt_max > 0) { - det_ctx->non_pf_id_array = SCCalloc(de_ctx->non_pf_store_cnt_max, sizeof(SigIntId)); + det_ctx->non_pf_id_array = SCCalloc(de_ctx->non_pf_store_cnt_max, sizeof(SigIntId)); BUG_ON(det_ctx->non_pf_id_array == NULL); } @@ -3219,8 +3190,8 @@ static TmEcode ThreadCtxDoInit (DetectEngineCtx *de_ctx, DetectEngineThreadCtx * AlertQueueInit(det_ctx); /* byte_extract storage */ - det_ctx->byte_values = SCMalloc(sizeof(*det_ctx->byte_values) * - (de_ctx->byte_extract_max_local_id + 1)); + det_ctx->byte_values = + SCMalloc(sizeof(*det_ctx->byte_values) * (de_ctx->byte_extract_max_local_id + 1)); if (det_ctx->byte_values == NULL) { return TM_ECODE_FAILED; } @@ -3247,17 +3218,18 @@ static TmEcode ThreadCtxDoInit (DetectEngineCtx *de_ctx, DetectEngineThreadCtx * det_ctx->inspect.to_clear_idx = 0; det_ctx->multi_inspect.buffers_size = de_ctx->buffer_type_id; - det_ctx->multi_inspect.buffers = SCCalloc(det_ctx->multi_inspect.buffers_size, sizeof(InspectionBufferMultipleForList)); + det_ctx->multi_inspect.buffers = + SCCalloc(det_ctx->multi_inspect.buffers_size, sizeof(InspectionBufferMultipleForList)); if (det_ctx->multi_inspect.buffers == NULL) { return TM_ECODE_FAILED; } - det_ctx->multi_inspect.to_clear_queue = SCCalloc(det_ctx->multi_inspect.buffers_size, sizeof(uint32_t)); + det_ctx->multi_inspect.to_clear_queue = + SCCalloc(det_ctx->multi_inspect.buffers_size, sizeof(uint32_t)); if (det_ctx->multi_inspect.to_clear_queue == NULL) { return TM_ECODE_FAILED; } det_ctx->multi_inspect.to_clear_idx = 0; - DetectEngineThreadCtxInitKeywords(de_ctx, det_ctx); DetectEngineThreadCtxInitGlobalKeywords(det_ctx); #ifdef PROFILE_RULES @@ -3313,8 +3285,7 @@ TmEcode DetectEngineThreadCtxInit(ThreadVars *tv, void *initdata, void **data) } if (det_ctx->de_ctx->type == DETECT_ENGINE_TYPE_NORMAL || - det_ctx->de_ctx->type == DETECT_ENGINE_TYPE_TENANT) - { + det_ctx->de_ctx->type == DETECT_ENGINE_TYPE_TENANT) { if (ThreadCtxDoInit(det_ctx->de_ctx, det_ctx) != TM_ECODE_OK) { DetectEngineThreadCtxDeinit(tv, det_ctx); return TM_ECODE_FAILED; @@ -3371,8 +3342,7 @@ DetectEngineThreadCtx *DetectEngineThreadCtxInitForReload( /* most of the init happens here */ if (det_ctx->de_ctx->type == DETECT_ENGINE_TYPE_NORMAL || - det_ctx->de_ctx->type == DETECT_ENGINE_TYPE_TENANT) - { + det_ctx->de_ctx->type == DETECT_ENGINE_TYPE_TENANT) { if (ThreadCtxDoInit(det_ctx->de_ctx, det_ctx) != TM_ECODE_OK) { DetectEngineDeReference(&det_ctx->de_ctx); SCFree(det_ctx); @@ -3408,14 +3378,18 @@ DetectEngineThreadCtx *DetectEngineThreadCtxInitForReload( static void DetectEngineThreadCtxFree(DetectEngineThreadCtx *det_ctx) { -#if DEBUG - SCLogDebug("PACKET PKT_STREAM_ADD: %"PRIu64, det_ctx->pkt_stream_add_cnt); +#if DEBUG + SCLogDebug("PACKET PKT_STREAM_ADD: %" PRIu64, det_ctx->pkt_stream_add_cnt); - SCLogDebug("PAYLOAD MPM %"PRIu64"/%"PRIu64, det_ctx->payload_mpm_cnt, det_ctx->payload_mpm_size); - SCLogDebug("STREAM MPM %"PRIu64"/%"PRIu64, det_ctx->stream_mpm_cnt, det_ctx->stream_mpm_size); + SCLogDebug("PAYLOAD MPM %" PRIu64 "/%" PRIu64, det_ctx->payload_mpm_cnt, + det_ctx->payload_mpm_size); + SCLogDebug( + "STREAM MPM %" PRIu64 "/%" PRIu64, det_ctx->stream_mpm_cnt, det_ctx->stream_mpm_size); - SCLogDebug("PAYLOAD SIG %"PRIu64"/%"PRIu64, det_ctx->payload_persig_cnt, det_ctx->payload_persig_size); - SCLogDebug("STREAM SIG %"PRIu64"/%"PRIu64, det_ctx->stream_persig_cnt, det_ctx->stream_persig_size); + SCLogDebug("PAYLOAD SIG %" PRIu64 "/%" PRIu64, det_ctx->payload_persig_cnt, + det_ctx->payload_persig_size); + SCLogDebug("STREAM SIG %" PRIu64 "/%" PRIu64, det_ctx->stream_persig_cnt, + det_ctx->stream_persig_size); #endif if (det_ctx->tenant_array != NULL) { @@ -3563,7 +3537,8 @@ static void DetectKeywordCtxFreeFunc(void *ptr) * recommended to store it in the keywords global ctx so that * it's freed when the de_ctx is freed. */ -int DetectRegisterThreadCtxFuncs(DetectEngineCtx *de_ctx, const char *name, void *(*InitFunc)(void *), void *data, void (*FreeFunc)(void *), int mode) +int DetectRegisterThreadCtxFuncs(DetectEngineCtx *de_ctx, const char *name, + void *(*InitFunc)(void *), void *data, void (*FreeFunc)(void *), int mode) { BUG_ON(de_ctx == NULL || InitFunc == NULL || FreeFunc == NULL); @@ -3641,7 +3616,6 @@ void *DetectThreadCtxGetKeywordThreadCtx(DetectEngineThreadCtx *det_ctx, int id) return det_ctx->keyword_ctxs_array[id]; } - /** \brief Register Thread keyword context Funcs (Global) * * IDs stay static over reloads and between tenants @@ -3653,8 +3627,8 @@ void *DetectThreadCtxGetKeywordThreadCtx(DetectEngineThreadCtx *det_ctx, int id) * \retval id for retrieval of ctx at runtime * \retval -1 on error */ -int DetectRegisterThreadCtxGlobalFuncs(const char *name, - void *(*InitFunc)(void *), void *data, void (*FreeFunc)(void *)) +int DetectRegisterThreadCtxGlobalFuncs( + const char *name, void *(*InitFunc)(void *), void *data, void (*FreeFunc)(void *)) { int id; BUG_ON(InitFunc == NULL || FreeFunc == NULL); @@ -3700,7 +3674,7 @@ int DetectRegisterThreadCtxGlobalFuncs(const char *name, void *DetectThreadCtxGetGlobalKeywordThreadCtx(DetectEngineThreadCtx *det_ctx, int id) { if (id < 0 || id > det_ctx->global_keyword_ctxs_size || - det_ctx->global_keyword_ctxs_array == NULL) { + det_ctx->global_keyword_ctxs_array == NULL) { return NULL; } @@ -3750,9 +3724,8 @@ DetectEngineCtx *DetectEngineGetCurrent(void) DetectEngineCtx *de_ctx = master->list; while (de_ctx) { if (de_ctx->type == DETECT_ENGINE_TYPE_NORMAL || - de_ctx->type == DETECT_ENGINE_TYPE_DD_STUB || - de_ctx->type == DETECT_ENGINE_TYPE_MT_STUB) - { + de_ctx->type == DETECT_ENGINE_TYPE_DD_STUB || + de_ctx->type == DETECT_ENGINE_TYPE_MT_STUB) { de_ctx->ref_cnt++; SCLogDebug("de_ctx %p ref_cnt %u", de_ctx, de_ctx->ref_cnt); SCMutexUnlock(&master->lock); @@ -3790,7 +3763,8 @@ int DetectEngineMultiTenantEnabled(void) * \retval 0 ok * \retval -1 failed */ -static int DetectEngineMultiTenantLoadTenant(uint32_t tenant_id, const char *filename, int loader_id) +static int DetectEngineMultiTenantLoadTenant( + uint32_t tenant_id, const char *filename, int loader_id) { DetectEngineCtx *de_ctx = NULL; char prefix[64]; @@ -3849,7 +3823,8 @@ static int DetectEngineMultiTenantLoadTenant(uint32_t tenant_id, const char *fil return -1; } -static int DetectEngineMultiTenantReloadTenant(uint32_t tenant_id, const char *filename, int reload_cnt) +static int DetectEngineMultiTenantReloadTenant( + uint32_t tenant_id, const char *filename, int reload_cnt) { DetectEngineCtx *old_de_ctx = DetectEngineGetByTenantId(tenant_id); if (old_de_ctx == NULL) { @@ -3910,7 +3885,6 @@ static int DetectEngineMultiTenantReloadTenant(uint32_t tenant_id, const char *f return -1; } - typedef struct TenantLoaderCtx_ { uint32_t tenant_id; int reload_cnt; /**< used by reload */ @@ -4068,14 +4042,14 @@ int DetectEngineReloadTenantsBlocking(const int reload_cnt) return 0; } -static int DetectEngineMultiTenantSetupLoadLivedevMappings(const ConfNode *mappings_root_node, - bool failure_fatal) +static int DetectEngineMultiTenantSetupLoadLivedevMappings( + const ConfNode *mappings_root_node, bool failure_fatal) { ConfNode *mapping_node = NULL; int mapping_cnt = 0; if (mappings_root_node != NULL) { - TAILQ_FOREACH(mapping_node, &mappings_root_node->head, next) { + TAILQ_FOREACH (mapping_node, &mappings_root_node->head, next) { ConfNode *tenant_id_node = ConfNodeLookupChild(mapping_node, "tenant-id"); if (tenant_id_node == NULL) goto bad_mapping; @@ -4127,14 +4101,14 @@ static int DetectEngineMultiTenantSetupLoadLivedevMappings(const ConfNode *mappi return 0; } -static int DetectEngineMultiTenantSetupLoadVlanMappings(const ConfNode *mappings_root_node, - bool failure_fatal) +static int DetectEngineMultiTenantSetupLoadVlanMappings( + const ConfNode *mappings_root_node, bool failure_fatal) { ConfNode *mapping_node = NULL; int mapping_cnt = 0; if (mappings_root_node != NULL) { - TAILQ_FOREACH(mapping_node, &mappings_root_node->head, next) { + TAILQ_FOREACH (mapping_node, &mappings_root_node->head, next) { ConfNode *tenant_id_node = ConfNodeLookupChild(mapping_node, "tenant-id"); if (tenant_id_node == NULL) goto bad_mapping; @@ -4249,8 +4223,8 @@ int DetectEngineMultiTenantSetup(const bool unix_socket) ConfNode *mappings_root_node = ConfGetNode("multi-detect.mappings"); if (tenant_selector == TENANT_SELECTOR_VLAN) { - int mapping_cnt = DetectEngineMultiTenantSetupLoadVlanMappings(mappings_root_node, - failure_fatal); + int mapping_cnt = + DetectEngineMultiTenantSetupLoadVlanMappings(mappings_root_node, failure_fatal); if (mapping_cnt == 0) { /* no mappings are valid when we're in unix socket mode, * they can be added on the fly. Otherwise warn/error @@ -4258,7 +4232,7 @@ int DetectEngineMultiTenantSetup(const bool unix_socket) if (unix_socket) { SCLogNotice("no tenant traffic mappings defined, " - "tenants won't be used until mappings are added"); + "tenants won't be used until mappings are added"); } else { if (failure_fatal) { SCLogError("no multi-detect mappings defined"); @@ -4269,8 +4243,8 @@ int DetectEngineMultiTenantSetup(const bool unix_socket) } } } else if (tenant_selector == TENANT_SELECTOR_LIVEDEV) { - int mapping_cnt = DetectEngineMultiTenantSetupLoadLivedevMappings(mappings_root_node, - failure_fatal); + int mapping_cnt = DetectEngineMultiTenantSetupLoadLivedevMappings( + mappings_root_node, failure_fatal); if (mapping_cnt == 0) { if (failure_fatal) { SCLogError("no multi-detect mappings defined"); @@ -4293,7 +4267,7 @@ int DetectEngineMultiTenantSetup(const bool unix_socket) SCLogConfig("tenants config path: %s", path); } - TAILQ_FOREACH(tenant_node, &tenants_root_node->head, next) { + TAILQ_FOREACH (tenant_node, &tenants_root_node->head, next) { ConfNode *id_node = ConfNodeLookupChild(tenant_node, "id"); if (id_node == NULL) { goto bad_tenant; @@ -4400,7 +4374,8 @@ static int DetectEngineTenantRegisterSelector( DetectEngineMasterCtx *master = &g_master_de_ctx; SCMutexLock(&master->lock); - if (!(master->tenant_selector == TENANT_SELECTOR_UNKNOWN || master->tenant_selector == selector)) { + if (!(master->tenant_selector == TENANT_SELECTOR_UNKNOWN || + master->tenant_selector == selector)) { SCLogInfo("conflicting selector already set"); SCMutexUnlock(&master->lock); return -1; @@ -4449,9 +4424,7 @@ static int DetectEngineTenantUnregisterSelector( DetectEngineTenantMapping *prev = NULL; DetectEngineTenantMapping *map = master->tenant_mapping_list; while (map) { - if (map->traffic_id == traffic_id && - map->tenant_id == tenant_id) - { + if (map->traffic_id == traffic_id && map->tenant_id == tenant_id) { if (prev != NULL) prev->next = map->next; else @@ -4516,9 +4489,7 @@ DetectEngineCtx *DetectEngineGetByTenantId(uint32_t tenant_id) DetectEngineCtx *de_ctx = master->list; while (de_ctx) { - if (de_ctx->type == DETECT_ENGINE_TYPE_TENANT && - de_ctx->tenant_id == tenant_id) - { + if (de_ctx->type == DETECT_ENGINE_TYPE_TENANT && de_ctx->tenant_id == tenant_id) { de_ctx->ref_cnt++; break; } @@ -4726,8 +4697,7 @@ int DetectEngineReload(const SCInstance *suri) /* only reload a regular 'normal' and 'delayed detect stub' detect engines */ if (!(old_de_ctx->type == DETECT_ENGINE_TYPE_NORMAL || - old_de_ctx->type == DETECT_ENGINE_TYPE_DD_STUB)) - { + old_de_ctx->type == DETECT_ENGINE_TYPE_DD_STUB)) { DetectEngineDeReference(&old_de_ctx); SCLogNotice("rule reload complete"); return -1; @@ -4741,8 +4711,7 @@ int DetectEngineReload(const SCInstance *suri) DetectEngineDeReference(&old_de_ctx); return -1; } - if (SigLoadSignatures(new_de_ctx, - suri->sig_file, suri->sig_file_exclusive) != 0) { + if (SigLoadSignatures(new_de_ctx, suri->sig_file, suri->sig_file_exclusive) != 0) { DetectEngineCtxFree(new_de_ctx); DetectEngineDeReference(&old_de_ctx); return -1; @@ -4814,13 +4783,11 @@ int DetectEngineMTApply(void) DetectEngineCtx *stub_de_ctx = NULL; DetectEngineCtx *list = master->list; - for ( ; list != NULL; list = list->next) { + for (; list != NULL; list = list->next) { SCLogDebug("list %p tenant %u", list, list->tenant_id); - if (list->type == DETECT_ENGINE_TYPE_NORMAL || - list->type == DETECT_ENGINE_TYPE_MT_STUB || - list->type == DETECT_ENGINE_TYPE_DD_STUB) - { + if (list->type == DETECT_ENGINE_TYPE_NORMAL || list->type == DETECT_ENGINE_TYPE_MT_STUB || + list->type == DETECT_ENGINE_TYPE_DD_STUB) { stub_de_ctx = list; break; } @@ -4934,21 +4901,20 @@ static void DetectEngineDeInitYamlConf(void) static int DetectEngineTest01(void) { - const char *conf = - "%YAML 1.1\n" - "---\n" - "detect-engine:\n" - " - profile: medium\n" - " - custom-values:\n" - " toclient_src_groups: 2\n" - " toclient_dst_groups: 2\n" - " toclient_sp_groups: 2\n" - " toclient_dp_groups: 3\n" - " toserver_src_groups: 2\n" - " toserver_dst_groups: 4\n" - " toserver_sp_groups: 2\n" - " toserver_dp_groups: 25\n" - " - inspection-recursion-limit: 0\n"; + const char *conf = "%YAML 1.1\n" + "---\n" + "detect-engine:\n" + " - profile: medium\n" + " - custom-values:\n" + " toclient_src_groups: 2\n" + " toclient_dst_groups: 2\n" + " toclient_sp_groups: 2\n" + " toclient_dp_groups: 3\n" + " toserver_src_groups: 2\n" + " toserver_dst_groups: 4\n" + " toserver_sp_groups: 2\n" + " toserver_dp_groups: 25\n" + " - inspection-recursion-limit: 0\n"; FAIL_IF(DetectEngineInitYamlConf(conf) == -1); @@ -4966,21 +4932,20 @@ static int DetectEngineTest01(void) static int DetectEngineTest02(void) { - const char *conf = - "%YAML 1.1\n" - "---\n" - "detect-engine:\n" - " - profile: medium\n" - " - custom-values:\n" - " toclient_src_groups: 2\n" - " toclient_dst_groups: 2\n" - " toclient_sp_groups: 2\n" - " toclient_dp_groups: 3\n" - " toserver_src_groups: 2\n" - " toserver_dst_groups: 4\n" - " toserver_sp_groups: 2\n" - " toserver_dp_groups: 25\n" - " - inspection-recursion-limit:\n"; + const char *conf = "%YAML 1.1\n" + "---\n" + "detect-engine:\n" + " - profile: medium\n" + " - custom-values:\n" + " toclient_src_groups: 2\n" + " toclient_dst_groups: 2\n" + " toclient_sp_groups: 2\n" + " toclient_dp_groups: 3\n" + " toserver_src_groups: 2\n" + " toserver_dst_groups: 4\n" + " toserver_sp_groups: 2\n" + " toserver_dp_groups: 25\n" + " - inspection-recursion-limit:\n"; FAIL_IF(DetectEngineInitYamlConf(conf) == -1); @@ -4999,20 +4964,19 @@ static int DetectEngineTest02(void) static int DetectEngineTest03(void) { - const char *conf = - "%YAML 1.1\n" - "---\n" - "detect-engine:\n" - " - profile: medium\n" - " - custom-values:\n" - " toclient_src_groups: 2\n" - " toclient_dst_groups: 2\n" - " toclient_sp_groups: 2\n" - " toclient_dp_groups: 3\n" - " toserver_src_groups: 2\n" - " toserver_dst_groups: 4\n" - " toserver_sp_groups: 2\n" - " toserver_dp_groups: 25\n"; + const char *conf = "%YAML 1.1\n" + "---\n" + "detect-engine:\n" + " - profile: medium\n" + " - custom-values:\n" + " toclient_src_groups: 2\n" + " toclient_dst_groups: 2\n" + " toclient_sp_groups: 2\n" + " toclient_dp_groups: 3\n" + " toserver_src_groups: 2\n" + " toserver_dst_groups: 4\n" + " toserver_sp_groups: 2\n" + " toserver_dp_groups: 25\n"; FAIL_IF(DetectEngineInitYamlConf(conf) == -1); @@ -5031,21 +4995,20 @@ static int DetectEngineTest03(void) static int DetectEngineTest04(void) { - const char *conf = - "%YAML 1.1\n" - "---\n" - "detect-engine:\n" - " - profile: medium\n" - " - custom-values:\n" - " toclient_src_groups: 2\n" - " toclient_dst_groups: 2\n" - " toclient_sp_groups: 2\n" - " toclient_dp_groups: 3\n" - " toserver_src_groups: 2\n" - " toserver_dst_groups: 4\n" - " toserver_sp_groups: 2\n" - " toserver_dp_groups: 25\n" - " - inspection-recursion-limit: 10\n"; + const char *conf = "%YAML 1.1\n" + "---\n" + "detect-engine:\n" + " - profile: medium\n" + " - custom-values:\n" + " toclient_src_groups: 2\n" + " toclient_dst_groups: 2\n" + " toclient_sp_groups: 2\n" + " toclient_dp_groups: 3\n" + " toserver_src_groups: 2\n" + " toserver_dst_groups: 4\n" + " toserver_sp_groups: 2\n" + " toserver_dp_groups: 25\n" + " - inspection-recursion-limit: 10\n"; FAIL_IF(DetectEngineInitYamlConf(conf) == -1); @@ -5063,14 +5026,13 @@ static int DetectEngineTest04(void) static int DetectEngineTest08(void) { - const char *conf = - "%YAML 1.1\n" - "---\n" - "detect-engine:\n" - " - profile: custom\n" - " - custom-values:\n" - " toclient-groups: 23\n" - " toserver-groups: 27\n"; + const char *conf = "%YAML 1.1\n" + "---\n" + "detect-engine:\n" + " - profile: custom\n" + " - custom-values:\n" + " toclient-groups: 23\n" + " toserver-groups: 27\n"; FAIL_IF(DetectEngineInitYamlConf(conf) == -1); @@ -5090,15 +5052,14 @@ static int DetectEngineTest08(void) /** \test bug 892 bad values */ static int DetectEngineTest09(void) { - const char *conf = - "%YAML 1.1\n" - "---\n" - "detect-engine:\n" - " - profile: custom\n" - " - custom-values:\n" - " toclient-groups: BA\n" - " toserver-groups: BA\n" - " - inspection-recursion-limit: 10\n"; + const char *conf = "%YAML 1.1\n" + "---\n" + "detect-engine:\n" + " - profile: custom\n" + " - custom-values:\n" + " toclient-groups: BA\n" + " toserver-groups: BA\n" + " - inspection-recursion-limit: 10\n"; FAIL_IF(DetectEngineInitYamlConf(conf) == -1); diff --git a/src/detect-engine.h b/src/detect-engine.h index 02e784ee973c..9e16f74392e2 100644 --- a/src/detect-engine.h +++ b/src/detect-engine.h @@ -33,8 +33,8 @@ void InspectionBufferSetup(DetectEngineThreadCtx *det_ctx, const int list_id, void InspectionBufferFree(InspectionBuffer *buffer); void InspectionBufferCheckAndExpand(InspectionBuffer *buffer, uint32_t min_size); void InspectionBufferCopy(InspectionBuffer *buffer, uint8_t *buf, uint32_t buf_len); -void InspectionBufferApplyTransforms(InspectionBuffer *buffer, - const DetectEngineTransforms *transforms); +void InspectionBufferApplyTransforms( + InspectionBuffer *buffer, const DetectEngineTransforms *transforms); void InspectionBufferClean(DetectEngineThreadCtx *det_ctx); InspectionBuffer *InspectionBufferGet(DetectEngineThreadCtx *det_ctx, const int list_id); void InspectionBufferSetupMultiEmpty(InspectionBuffer *buffer); @@ -56,10 +56,10 @@ int DetectBufferTypeMaxId(void); void DetectBufferTypeCloseRegistration(void); void DetectBufferTypeSetDescriptionByName(const char *name, const char *desc); const char *DetectBufferTypeGetDescriptionByName(const char *name); -void DetectBufferTypeRegisterSetupCallback(const char *name, - void (*Callback)(const DetectEngineCtx *, Signature *)); -void DetectBufferTypeRegisterValidateCallback(const char *name, - bool (*ValidateCallback)(const Signature *, const char **sigerror)); +void DetectBufferTypeRegisterSetupCallback( + const char *name, void (*Callback)(const DetectEngineCtx *, Signature *)); +void DetectBufferTypeRegisterValidateCallback( + const char *name, bool (*ValidateCallback)(const Signature *, const char **sigerror)); /* detect engine related buffer funcs */ @@ -94,13 +94,13 @@ DetectEngineCtx *DetectEngineCtxInitStubForDD(void); DetectEngineCtx *DetectEngineCtxInitStubForMT(void); void DetectEngineCtxFree(DetectEngineCtx *); -int DetectRegisterThreadCtxGlobalFuncs(const char *name, - void *(*InitFunc)(void *), void *data, void (*FreeFunc)(void *)); +int DetectRegisterThreadCtxGlobalFuncs( + const char *name, void *(*InitFunc)(void *), void *data, void (*FreeFunc)(void *)); void *DetectThreadCtxGetGlobalKeywordThreadCtx(DetectEngineThreadCtx *det_ctx, int id); TmEcode DetectEngineThreadCtxInit(ThreadVars *, void *, void **); TmEcode DetectEngineThreadCtxDeinit(ThreadVars *, void *); -//inline uint32_t DetectEngineGetMaxSigId(DetectEngineCtx *); +// inline uint32_t DetectEngineGetMaxSigId(DetectEngineCtx *); /* faster as a macro than a inline function on my box -- VJ */ #define DetectEngineGetMaxSigId(de_ctx) ((de_ctx)->signum) void DetectEngineResetMaxSigId(DetectEngineCtx *); @@ -146,10 +146,9 @@ uint8_t DetectEngineInspectBufferGeneric(DetectEngineCtx *de_ctx, DetectEngineTh const DetectEngineAppInspectionEngine *engine, const Signature *s, Flow *f, uint8_t flags, void *alstate, void *txv, uint64_t tx_id); -int DetectEngineInspectPktBufferGeneric( - DetectEngineThreadCtx *det_ctx, - const DetectEnginePktInspectionEngine *engine, - const Signature *s, Packet *p, uint8_t *alert_flags); +int DetectEngineInspectPktBufferGeneric(DetectEngineThreadCtx *det_ctx, + const DetectEnginePktInspectionEngine *engine, const Signature *s, Packet *p, + uint8_t *alert_flags); /** * \brief Registers an app inspection engine. @@ -161,13 +160,10 @@ int DetectEngineInspectPktBufferGeneric( * \param progress Minimal progress value for inspect engine to run * \param Callback The engine callback. */ -void DetectAppLayerInspectEngineRegister2(const char *name, - AppProto alproto, uint32_t dir, int progress, - InspectEngineFuncPtr2 Callback2, - InspectionBufferGetDataPtr GetData); +void DetectAppLayerInspectEngineRegister2(const char *name, AppProto alproto, uint32_t dir, + int progress, InspectEngineFuncPtr2 Callback2, InspectionBufferGetDataPtr GetData); -void DetectPktInspectEngineRegister(const char *name, - InspectionBufferGetPktDataPtr GetPktData, +void DetectPktInspectEngineRegister(const char *name, InspectionBufferGetPktDataPtr GetPktData, InspectionBufferPktInspectFunc Callback); void DetectFrameInspectEngineRegister(const char *name, int dir, @@ -178,10 +174,8 @@ void DetectEngineFrameInspectEngineRegister(DetectEngineCtx *de_ctx, const char int DetectEngineAppInspectionEngine2Signature(DetectEngineCtx *de_ctx, Signature *s); void DetectEngineAppInspectionEngineSignatureFree(DetectEngineCtx *, Signature *s); -bool DetectEnginePktInspectionRun(ThreadVars *tv, - DetectEngineThreadCtx *det_ctx, const Signature *s, - Flow *f, Packet *p, - uint8_t *alert_flags); +bool DetectEnginePktInspectionRun(ThreadVars *tv, DetectEngineThreadCtx *det_ctx, + const Signature *s, Flow *f, Packet *p, uint8_t *alert_flags); int DetectEnginePktInspectionSetup(Signature *s); void DetectEngineSetParseMetadata(void); diff --git a/src/detect-fast-pattern.c b/src/detect-fast-pattern.c index 6748186727c9..c616a0181a0e 100644 --- a/src/detect-fast-pattern.c +++ b/src/detect-fast-pattern.c @@ -61,8 +61,7 @@ static SCFPSupportSMList *g_fp_support_smlist_list = NULL; * \retval 1 If supported. * \retval 0 If not. */ -int FastPatternSupportEnabledForSigMatchList(const DetectEngineCtx *de_ctx, - const int list_id) +int FastPatternSupportEnabledForSigMatchList(const DetectEngineCtx *de_ctx, const int list_id) { if (de_ctx->fp_support_smlist_list == NULL) { return 0; @@ -185,11 +184,12 @@ void DetectEngineFreeFastPatternList(DetectEngineCtx *de_ctx) void DetectFastPatternRegister(void) { sigmatch_table[DETECT_FAST_PATTERN].name = "fast_pattern"; - sigmatch_table[DETECT_FAST_PATTERN].desc = "force using preceding content in the multi pattern matcher"; + sigmatch_table[DETECT_FAST_PATTERN].desc = + "force using preceding content in the multi pattern matcher"; sigmatch_table[DETECT_FAST_PATTERN].url = "/rules/prefilter-keywords.html#fast-pattern"; sigmatch_table[DETECT_FAST_PATTERN].Match = NULL; sigmatch_table[DETECT_FAST_PATTERN].Setup = DetectFastPatternSetup; - sigmatch_table[DETECT_FAST_PATTERN].Free = NULL; + sigmatch_table[DETECT_FAST_PATTERN].Free = NULL; #ifdef UNITTESTS sigmatch_table[DETECT_FAST_PATTERN].RegisterTests = DetectFastPatternRegisterTests; #endif @@ -240,10 +240,8 @@ static int DetectFastPatternSetup(DetectEngineCtx *de_ctx, Signature *s, const c cd = (DetectContentData *)pm->ctx; if ((cd->flags & DETECT_CONTENT_NEGATED) && - ((cd->flags & DETECT_CONTENT_DISTANCE) || - (cd->flags & DETECT_CONTENT_WITHIN) || - (cd->flags & DETECT_CONTENT_OFFSET) || - (cd->flags & DETECT_CONTENT_DEPTH))) { + ((cd->flags & DETECT_CONTENT_DISTANCE) || (cd->flags & DETECT_CONTENT_WITHIN) || + (cd->flags & DETECT_CONTENT_OFFSET) || (cd->flags & DETECT_CONTENT_DEPTH))) { /* we can't have any of these if we are having "only" */ SCLogError("fast_pattern; cannot be " @@ -251,13 +249,12 @@ static int DetectFastPatternSetup(DetectEngineCtx *de_ctx, Signature *s, const c goto error; } - if (arg == NULL|| strcmp(arg, "") == 0) { + if (arg == NULL || strcmp(arg, "") == 0) { if (cd->flags & DETECT_CONTENT_FAST_PATTERN) { SCLogError("can't use multiple fast_pattern " "options for the same content"); goto error; - } - else { /*allow only one content to have fast_pattern modifier*/ + } else { /*allow only one content to have fast_pattern modifier*/ for (uint32_t list_id = 0; list_id < DETECT_SM_LIST_MAX; list_id++) { SigMatch *sm = NULL; for (sm = s->init_data->smlists[list_id]; sm != NULL; sm = sm->next) { @@ -280,11 +277,9 @@ static int DetectFastPatternSetup(DetectEngineCtx *de_ctx, Signature *s, const c int ret = DetectParsePcreExec(&parse_regex, &match, arg, 0, 0); /* fast pattern only */ if (ret == 2) { - if ((cd->flags & DETECT_CONTENT_NEGATED) || - (cd->flags & DETECT_CONTENT_DISTANCE) || - (cd->flags & DETECT_CONTENT_WITHIN) || - (cd->flags & DETECT_CONTENT_OFFSET) || - (cd->flags & DETECT_CONTENT_DEPTH)) { + if ((cd->flags & DETECT_CONTENT_NEGATED) || (cd->flags & DETECT_CONTENT_DISTANCE) || + (cd->flags & DETECT_CONTENT_WITHIN) || (cd->flags & DETECT_CONTENT_OFFSET) || + (cd->flags & DETECT_CONTENT_DEPTH)) { /* we can't have any of these if we are having "only" */ SCLogError("fast_pattern: only; cannot be " @@ -304,8 +299,7 @@ static int DetectFastPatternSetup(DetectEngineCtx *de_ctx, Signature *s, const c goto error; } uint16_t offset; - if (StringParseUint16(&offset, 10, 0, - (const char *)arg_substr) < 0) { + if (StringParseUint16(&offset, 10, 0, (const char *)arg_substr) < 0) { SCLogError("Invalid fast pattern offset:" " \"%s\"", arg_substr); @@ -320,8 +314,7 @@ static int DetectFastPatternSetup(DetectEngineCtx *de_ctx, Signature *s, const c goto error; } uint16_t length; - if (StringParseUint16(&length, 10, 0, - (const char *)arg_substr) < 0) { + if (StringParseUint16(&length, 10, 0, (const char *)arg_substr) < 0) { SCLogError("Invalid value for fast " "pattern: \"%s\"", arg_substr); @@ -356,10 +349,10 @@ static int DetectFastPatternSetup(DetectEngineCtx *de_ctx, Signature *s, const c pcre2_match_data_free(match); return 0; - error: - if (match) { - pcre2_match_data_free(match); - } +error: + if (match) { + pcre2_match_data_free(match); + } return -1; } diff --git a/src/detect-fast-pattern.h b/src/detect-fast-pattern.h index af57540c74f1..2e7de2706e1f 100644 --- a/src/detect-fast-pattern.h +++ b/src/detect-fast-pattern.h @@ -25,8 +25,7 @@ #define __DETECT_FAST_PATTERN_H__ void SupportFastPatternForSigMatchList(int list_id, int priority); -int FastPatternSupportEnabledForSigMatchList(const DetectEngineCtx *de_ctx, - const int list_id); +int FastPatternSupportEnabledForSigMatchList(const DetectEngineCtx *de_ctx, const int list_id); void SupportFastPatternForSigMatchTypes(void); void DetectEngineRegisterFastPatternForId(DetectEngineCtx *de_ctx, int list_id, int priority); @@ -37,4 +36,3 @@ void DetectEngineFreeFastPatternList(DetectEngineCtx *de_ctx); void DetectFastPatternRegister(void); #endif /* __DETECT_FAST_PATTERN_H__ */ - diff --git a/src/detect-file-data.c b/src/detect-file-data.c index f31715adda01..5edd5ba3dcf8 100644 --- a/src/detect-file-data.c +++ b/src/detect-file-data.c @@ -53,12 +53,11 @@ #include "util-file-decompression.h" #include "util-profiling.h" -static int DetectFiledataSetup (DetectEngineCtx *, Signature *, const char *); +static int DetectFiledataSetup(DetectEngineCtx *, Signature *, const char *); #ifdef UNITTESTS static void DetectFiledataRegisterTests(void); #endif -static void DetectFiledataSetupCallback(const DetectEngineCtx *de_ctx, - Signature *s); +static void DetectFiledataSetupCallback(const DetectEngineCtx *de_ctx, Signature *s); static int g_file_data_buffer_id = 0; /* file API */ @@ -93,7 +92,8 @@ void DetectFiledataRegister(void) g_file_data_buffer_id = DetectBufferTypeGetByName("file_data"); } -static void SetupDetectEngineConfig(DetectEngineCtx *de_ctx) { +static void SetupDetectEngineConfig(DetectEngineCtx *de_ctx) +{ if (de_ctx->filedata_config_initialized) return; @@ -108,8 +108,10 @@ static void SetupDetectEngineConfig(DetectEngineCtx *de_ctx) { /* SMTP */ de_ctx->filedata_config[ALPROTO_SMTP].content_limit = smtp_config.content_limit; - de_ctx->filedata_config[ALPROTO_SMTP].content_inspect_min_size = smtp_config.content_inspect_min_size; - de_ctx->filedata_config[ALPROTO_SMTP].content_inspect_window = smtp_config.content_inspect_window; + de_ctx->filedata_config[ALPROTO_SMTP].content_inspect_min_size = + smtp_config.content_inspect_min_size; + de_ctx->filedata_config[ALPROTO_SMTP].content_inspect_window = + smtp_config.content_inspect_window; de_ctx->filedata_config_initialized = true; } @@ -125,7 +127,7 @@ static void SetupDetectEngineConfig(DetectEngineCtx *de_ctx) { * \retval 0 on Success * \retval -1 on Failure */ -static int DetectFiledataSetup (DetectEngineCtx *de_ctx, Signature *s, const char *str) +static int DetectFiledataSetup(DetectEngineCtx *de_ctx, Signature *s, const char *str) { SCEnter(); @@ -141,7 +143,7 @@ static int DetectFiledataSetup (DetectEngineCtx *de_ctx, Signature *s, const cha } if (s->alproto == ALPROTO_SMTP && (s->init_data->init_flags & SIG_FLAG_INIT_FLOW) && - !(s->flags & SIG_FLAG_TOSERVER) && (s->flags & SIG_FLAG_TOCLIENT)) { + !(s->flags & SIG_FLAG_TOSERVER) && (s->flags & SIG_FLAG_TOCLIENT)) { SCLogError("The 'file-data' keyword cannot be used with SMTP flow:to_client or " "flow:from_server."); return -1; @@ -155,8 +157,7 @@ static int DetectFiledataSetup (DetectEngineCtx *de_ctx, Signature *s, const cha return 0; } -static void DetectFiledataSetupCallback(const DetectEngineCtx *de_ctx, - Signature *s) +static void DetectFiledataSetupCallback(const DetectEngineCtx *de_ctx, Signature *s) { if (s->alproto == ALPROTO_HTTP1 || s->alproto == ALPROTO_UNKNOWN || s->alproto == ALPROTO_HTTP) { @@ -486,9 +487,8 @@ int PrefilterMpmFiledataRegister(DetectEngineCtx *de_ctx, SigGroupHead *sgh, Mpm pectx->mpm_ctx = mpm_ctx; pectx->transforms = &mpm_reg->transforms; - return PrefilterAppendTxEngine(de_ctx, sgh, PrefilterTxFiledata, - mpm_reg->app_v2.alproto, mpm_reg->app_v2.tx_min_progress, - pectx, PrefilterMpmFiledataFree, mpm_reg->pname); + return PrefilterAppendTxEngine(de_ctx, sgh, PrefilterTxFiledata, mpm_reg->app_v2.alproto, + mpm_reg->app_v2.tx_min_progress, pectx, PrefilterMpmFiledataFree, mpm_reg->pname); } #ifdef UNITTESTS diff --git a/src/detect-file-data.h b/src/detect-file-data.h index 1be9b4001049..ff793da09cba 100644 --- a/src/detect-file-data.h +++ b/src/detect-file-data.h @@ -25,7 +25,7 @@ #define __DETECT_FILEDATA_H__ /* prototypes */ -void DetectFiledataRegister (void); +void DetectFiledataRegister(void); typedef struct PrefilterMpmFiledata { int list_id; diff --git a/src/detect-file-hash-common.c b/src/detect-file-hash-common.c index f81ce4be29ea..0fca062fb5d8 100644 --- a/src/detect-file-hash-common.c +++ b/src/detect-file-hash-common.c @@ -44,8 +44,8 @@ * \retval -1 the hexadecimal string is invalid * \retval 1 the hexadecimal string was read successfully */ -int ReadHashString(uint8_t *hash, const char *string, const char *filename, int line_no, - uint16_t expected_len) +int ReadHashString( + uint8_t *hash, const char *string, const char *filename, int line_no, uint16_t expected_len) { if (strlen(string) != expected_len) { SCLogError("%s:%d hash string not %d characters", filename, line_no, expected_len); @@ -53,10 +53,10 @@ int ReadHashString(uint8_t *hash, const char *string, const char *filename, int } int i, x; - for (x = 0, i = 0; i < expected_len; i+=2, x++) { + for (x = 0, i = 0; i < expected_len; i += 2, x++) { char buf[3] = { 0, 0, 0 }; buf[0] = string[i]; - buf[1] = string[i+1]; + buf[1] = string[i + 1]; long value = strtol(buf, NULL, 16); if (value >= 0 && value <= 255) @@ -82,8 +82,8 @@ int ReadHashString(uint8_t *hash, const char *string, const char *filename, int * \retval -1 failed to load the hash into the hash table * \retval 1 successfully loaded the has into the hash table */ -int LoadHashTable(ROHashTable *hash_table, const char *string, const char *filename, - int line_no, uint32_t type) +int LoadHashTable(ROHashTable *hash_table, const char *string, const char *filename, int line_no, + uint32_t type) { /* allocate the maximum size a hash can have (in this case is SHA256, 32 bytes) */ uint8_t hash[32]; @@ -92,8 +92,7 @@ int LoadHashTable(ROHashTable *hash_table, const char *string, const char *filen if (type == DETECT_FILEMD5) { size = 16; - } - else if (type == DETECT_FILESHA1) { + } else if (type == DETECT_FILESHA1) { size = 20; } @@ -118,8 +117,7 @@ int LoadHashTable(ROHashTable *hash_table, const char *string, const char *filen * \retval 0 didn't find the specified hash * \retval 1 the hash matched a stored value */ -static int HashMatchHashTable(ROHashTable *hash_table, uint8_t *hash, - size_t hash_len) +static int HashMatchHashTable(ROHashTable *hash_table, uint8_t *hash, size_t hash_len) { void *ptr = ROHashLookup(hash_table, hash, (uint16_t)hash_len); if (ptr == NULL) @@ -141,8 +139,8 @@ static int HashMatchHashTable(ROHashTable *hash_table, uint8_t *hash, * \retval 0 no match * \retval 1 match */ -int DetectFileHashMatch (DetectEngineThreadCtx *det_ctx, - Flow *f, uint8_t flags, File *file, const Signature *s, const SigMatchCtx *m) +int DetectFileHashMatch(DetectEngineThreadCtx *det_ctx, Flow *f, uint8_t flags, File *file, + const Signature *s, const SigMatchCtx *m) { SCEnter(); int ret = 0; @@ -156,11 +154,9 @@ int DetectFileHashMatch (DetectEngineThreadCtx *det_ctx, if (s->file_flags & FILE_SIG_NEED_MD5 && file->flags & FILE_MD5) { match = HashMatchHashTable(filehash->hash, file->md5, sizeof(file->md5)); - } - else if (s->file_flags & FILE_SIG_NEED_SHA1 && file->flags & FILE_SHA1) { + } else if (s->file_flags & FILE_SIG_NEED_SHA1 && file->flags & FILE_SHA1) { match = HashMatchHashTable(filehash->hash, file->sha1, sizeof(file->sha1)); - } - else if (s->file_flags & FILE_SIG_NEED_SHA256 && file->flags & FILE_SHA256) { + } else if (s->file_flags & FILE_SIG_NEED_SHA256 && file->flags & FILE_SHA256) { match = HashMatchHashTable(filehash->hash, file->sha256, sizeof(file->sha256)); } @@ -169,8 +165,7 @@ int DetectFileHashMatch (DetectEngineThreadCtx *det_ctx, ret = 1; else ret = 0; - } - else if (match == 0) { + } else if (match == 0) { if (filehash->negated == 0) ret = 0; else @@ -192,8 +187,8 @@ static const char *hexcodes = "ABCDEFabcdef0123456789"; * \retval hash pointer to DetectFileHashData on success * \retval NULL on failure */ -static DetectFileHashData *DetectFileHashParse (const DetectEngineCtx *de_ctx, - const char *str, uint32_t type) +static DetectFileHashData *DetectFileHashParse( + const DetectEngineCtx *de_ctx, const char *str, uint32_t type) { DetectFileHashData *filehash = NULL; FILE *fp = NULL; @@ -212,11 +207,9 @@ static DetectFileHashData *DetectFileHashParse (const DetectEngineCtx *de_ctx, if (type == DETECT_FILEMD5) { filehash->hash = ROHashInit(18, 16); - } - else if (type == DETECT_FILESHA1) { + } else if (type == DETECT_FILESHA1) { filehash->hash = ROHashInit(18, 20); - } - else if (type == DETECT_FILESHA256) { + } else if (type == DETECT_FILESHA256) { filehash->hash = ROHashInit(18, 32); } @@ -261,11 +254,12 @@ static DetectFileHashData *DetectFileHashParse (const DetectEngineCtx *de_ctx, } int line_no = 0; - while(fgets(line, (int)sizeof(line), fp) != NULL) { + while (fgets(line, (int)sizeof(line), fp) != NULL) { size_t valid = 0, len = strlen(line); line_no++; - while (strchr(hexcodes, line[valid]) != NULL && valid++ < len); + while (strchr(hexcodes, line[valid]) != NULL && valid++ < len) + ; /* lines that do not contain sequentially any valid character are ignored */ if (valid == 0) @@ -284,7 +278,8 @@ static DetectFileHashData *DetectFileHashParse (const DetectEngineCtx *de_ctx, if (ROHashInitFinalize(filehash->hash) != 1) { goto error; } - SCLogInfo("Hash hash table size %u bytes%s", ROHashMemorySize(filehash->hash), filehash->negated ? ", negated match" : ""); + SCLogInfo("Hash hash table size %u bytes%s", ROHashMemorySize(filehash->hash), + filehash->negated ? ", negated match" : ""); SCFree(rule_filename); SCFree(filename); @@ -292,7 +287,7 @@ static DetectFileHashData *DetectFileHashParse (const DetectEngineCtx *de_ctx, error: if (filehash != NULL) - DetectFileHashFree((DetectEngineCtx *) de_ctx, filehash); + DetectFileHashFree((DetectEngineCtx *)de_ctx, filehash); if (fp != NULL) fclose(fp); if (filename != NULL) diff --git a/src/detect-file-hash-common.h b/src/detect-file-hash-common.h index b547e03677f2..000ca5bdb8df 100644 --- a/src/detect-file-hash-common.h +++ b/src/detect-file-hash-common.h @@ -37,8 +37,8 @@ typedef struct DetectFileHashData_ { int ReadHashString(uint8_t *, const char *, const char *, int, uint16_t); int LoadHashTable(ROHashTable *, const char *, const char *, int, uint32_t); -int DetectFileHashMatch(DetectEngineThreadCtx *, Flow *, uint8_t, - File *, const Signature *, const SigMatchCtx *); +int DetectFileHashMatch( + DetectEngineThreadCtx *, Flow *, uint8_t, File *, const Signature *, const SigMatchCtx *); int DetectFileHashSetup(DetectEngineCtx *, Signature *, const char *, uint16_t, int); void DetectFileHashFree(DetectEngineCtx *, void *); diff --git a/src/detect-filemagic.c b/src/detect-filemagic.c index 7ade159fb52d..0433163c98b0 100644 --- a/src/detect-filemagic.c +++ b/src/detect-filemagic.c @@ -61,7 +61,7 @@ #ifndef HAVE_MAGIC -static int DetectFilemagicSetupNoSupport (DetectEngineCtx *de_ctx, Signature *s, const char *str) +static int DetectFilemagicSetupNoSupport(DetectEngineCtx *de_ctx, Signature *s, const char *str) { SCLogError("no libmagic support built in, needed for filemagic keyword"); return -1; @@ -73,10 +73,11 @@ static int DetectFilemagicSetupNoSupport (DetectEngineCtx *de_ctx, Signature *s, void DetectFilemagicRegister(void) { sigmatch_table[DETECT_FILEMAGIC].name = "filemagic"; - sigmatch_table[DETECT_FILEMAGIC].desc = "match on the information libmagic returns about a file"; + sigmatch_table[DETECT_FILEMAGIC].desc = + "match on the information libmagic returns about a file"; sigmatch_table[DETECT_FILEMAGIC].url = "/rules/file-keywords.html#filemagic"; sigmatch_table[DETECT_FILEMAGIC].Setup = DetectFilemagicSetupNoSupport; - sigmatch_table[DETECT_FILEMAGIC].flags = SIGMATCH_QUOTES_MANDATORY|SIGMATCH_HANDLE_NEGATION; + sigmatch_table[DETECT_FILEMAGIC].flags = SIGMATCH_QUOTES_MANDATORY | SIGMATCH_HANDLE_NEGATION; } #else /* HAVE_MAGIC */ @@ -103,17 +104,18 @@ static uint8_t DetectEngineInspectFilemagic(DetectEngineCtx *de_ctx, DetectEngin void DetectFilemagicRegister(void) { sigmatch_table[DETECT_FILEMAGIC].name = "filemagic"; - sigmatch_table[DETECT_FILEMAGIC].desc = "match on the information libmagic returns about a file"; + sigmatch_table[DETECT_FILEMAGIC].desc = + "match on the information libmagic returns about a file"; sigmatch_table[DETECT_FILEMAGIC].url = "/rules/file-keywords.html#filemagic"; sigmatch_table[DETECT_FILEMAGIC].Setup = DetectFilemagicSetup; - sigmatch_table[DETECT_FILEMAGIC].flags = SIGMATCH_QUOTES_MANDATORY|SIGMATCH_HANDLE_NEGATION; + sigmatch_table[DETECT_FILEMAGIC].flags = SIGMATCH_QUOTES_MANDATORY | SIGMATCH_HANDLE_NEGATION; sigmatch_table[DETECT_FILEMAGIC].alternative = DETECT_FILE_MAGIC; sigmatch_table[DETECT_FILE_MAGIC].name = "file.magic"; sigmatch_table[DETECT_FILE_MAGIC].desc = "sticky buffer to match on the file magic"; sigmatch_table[DETECT_FILE_MAGIC].url = "/rules/file-keywords.html#filemagic"; sigmatch_table[DETECT_FILE_MAGIC].Setup = DetectFilemagicSetupSticky; - sigmatch_table[DETECT_FILE_MAGIC].flags = SIGMATCH_NOOPT|SIGMATCH_INFO_STICKY_BUFFER; + sigmatch_table[DETECT_FILE_MAGIC].flags = SIGMATCH_NOOPT | SIGMATCH_INFO_STICKY_BUFFER; filehandler_table[DETECT_FILE_MAGIC].name = "file.magic", filehandler_table[DETECT_FILE_MAGIC].priority = 2; @@ -126,11 +128,11 @@ void DetectFilemagicRegister(void) DetectBufferTypeSupportsMultiInstance("file.magic"); g_file_magic_buffer_id = DetectBufferTypeGetByName("file.magic"); - SCLogDebug("registering filemagic rule option"); + SCLogDebug("registering filemagic rule option"); return; } -#define FILEMAGIC_MIN_SIZE 512 +#define FILEMAGIC_MIN_SIZE 512 /** * \brief run the magic check @@ -150,8 +152,7 @@ int FilemagicThreadLookup(magic_t *ctx, File *file) uint32_t data_len = 0; uint64_t offset = 0; - StreamingBufferGetData(file->sb, - &data, &data_len, &offset); + StreamingBufferGetData(file->sb, &data, &data_len, &offset); if (offset == 0) { if (FileDataSize(file) >= FILEMAGIC_MIN_SIZE) { file->magic = MagicThreadLookup(ctx, data, data_len); @@ -204,7 +205,7 @@ static void DetectFilemagicThreadFree(void *ctx) * \retval 0 on Success * \retval -1 on Failure */ -static int DetectFilemagicSetup (DetectEngineCtx *de_ctx, Signature *s, const char *str) +static int DetectFilemagicSetup(DetectEngineCtx *de_ctx, Signature *s, const char *str) { if (s->init_data->transforms.cnt) { SCLogError("previous transforms not consumed before 'filemagic'"); @@ -394,9 +395,8 @@ static int PrefilterMpmFilemagicRegister(DetectEngineCtx *de_ctx, SigGroupHead * pectx->mpm_ctx = mpm_ctx; pectx->transforms = &mpm_reg->transforms; - return PrefilterAppendTxEngine(de_ctx, sgh, PrefilterTxFilemagic, - mpm_reg->app_v2.alproto, mpm_reg->app_v2.tx_min_progress, - pectx, PrefilterMpmFilemagicFree, mpm_reg->pname); + return PrefilterAppendTxEngine(de_ctx, sgh, PrefilterTxFilemagic, mpm_reg->app_v2.alproto, + mpm_reg->app_v2.tx_min_progress, pectx, PrefilterMpmFilemagicFree, mpm_reg->pname); } #endif /* HAVE_MAGIC */ diff --git a/src/detect-filemagic.h b/src/detect-filemagic.h index d005597fca34..50a984df940a 100644 --- a/src/detect-filemagic.h +++ b/src/detect-filemagic.h @@ -28,6 +28,6 @@ /* prototypes */ int FilemagicThreadLookup(magic_t *ctx, File *file); #endif -void DetectFilemagicRegister (void); +void DetectFilemagicRegister(void); #endif /* __DETECT_FILEMAGIC_H__ */ diff --git a/src/detect-filemd5.c b/src/detect-filemd5.c index 9ea08803d8b8..fda0ea7391d9 100644 --- a/src/detect-filemd5.c +++ b/src/detect-filemd5.c @@ -33,7 +33,7 @@ static int g_file_match_list_id = 0; -static int DetectFileMd5Setup (DetectEngineCtx *, Signature *, const char *); +static int DetectFileMd5Setup(DetectEngineCtx *, Signature *, const char *); #ifdef UNITTESTS static void DetectFileMd5RegisterTests(void); #endif @@ -48,7 +48,7 @@ void DetectFileMd5Register(void) sigmatch_table[DETECT_FILEMD5].url = "/rules/file-keywords.html#filemd5"; sigmatch_table[DETECT_FILEMD5].FileMatch = DetectFileHashMatch; sigmatch_table[DETECT_FILEMD5].Setup = DetectFileMd5Setup; - sigmatch_table[DETECT_FILEMD5].Free = DetectFileHashFree; + sigmatch_table[DETECT_FILEMD5].Free = DetectFileHashFree; #ifdef UNITTESTS sigmatch_table[DETECT_FILEMD5].RegisterTests = DetectFileMd5RegisterTests; #endif @@ -69,7 +69,7 @@ void DetectFileMd5Register(void) * \retval 0 on Success * \retval -1 on Failure */ -static int DetectFileMd5Setup (DetectEngineCtx *de_ctx, Signature *s, const char *str) +static int DetectFileMd5Setup(DetectEngineCtx *de_ctx, Signature *s, const char *str) { return DetectFileHashSetup(de_ctx, s, str, DETECT_FILEMD5, g_file_match_list_id); } diff --git a/src/detect-filemd5.h b/src/detect-filemd5.h index 0905fc4ce02b..47ca8c9fb194 100644 --- a/src/detect-filemd5.h +++ b/src/detect-filemd5.h @@ -25,6 +25,6 @@ #define __DETECT_FILEMD5_H__ /* prototypes */ -void DetectFileMd5Register (void); +void DetectFileMd5Register(void); #endif /* __DETECT_FILEMD5_H__ */ diff --git a/src/detect-filename.c b/src/detect-filename.c index 88e580862452..92a892c36a9c 100644 --- a/src/detect-filename.c +++ b/src/detect-filename.c @@ -59,7 +59,7 @@ #include "app-layer-parser.h" static int DetectFileextSetup(DetectEngineCtx *de_ctx, Signature *s, const char *str); -static int DetectFilenameSetup (DetectEngineCtx *, Signature *, const char *); +static int DetectFilenameSetup(DetectEngineCtx *, Signature *, const char *); static int DetectFilenameSetupSticky(DetectEngineCtx *de_ctx, Signature *s, const char *str); #ifdef UNITTESTS static void DetectFilenameRegisterTests(void); @@ -85,7 +85,7 @@ void DetectFilenameRegister(void) #ifdef UNITTESTS sigmatch_table[DETECT_FILENAME].RegisterTests = DetectFilenameRegisterTests; #endif - sigmatch_table[DETECT_FILENAME].flags = SIGMATCH_QUOTES_OPTIONAL|SIGMATCH_HANDLE_NEGATION; + sigmatch_table[DETECT_FILENAME].flags = SIGMATCH_QUOTES_OPTIONAL | SIGMATCH_HANDLE_NEGATION; sigmatch_table[DETECT_FILENAME].alternative = DETECT_FILE_NAME; sigmatch_table[DETECT_FILEEXT].name = "fileext"; @@ -99,7 +99,7 @@ void DetectFilenameRegister(void) sigmatch_table[DETECT_FILE_NAME].desc = "sticky buffer to match on the file name"; sigmatch_table[DETECT_FILE_NAME].url = "/rules/file-keywords.html#filename"; sigmatch_table[DETECT_FILE_NAME].Setup = DetectFilenameSetupSticky; - sigmatch_table[DETECT_FILE_NAME].flags = SIGMATCH_NOOPT|SIGMATCH_INFO_STICKY_BUFFER; + sigmatch_table[DETECT_FILE_NAME].flags = SIGMATCH_NOOPT | SIGMATCH_INFO_STICKY_BUFFER; DetectBufferTypeSetDescriptionByName("file.name", "file name"); @@ -168,7 +168,7 @@ static int DetectFileextSetup(DetectEngineCtx *de_ctx, Signature *s, const char * \retval 0 on Success * \retval -1 on Failure */ -static int DetectFilenameSetup (DetectEngineCtx *de_ctx, Signature *s, const char *str) +static int DetectFilenameSetup(DetectEngineCtx *de_ctx, Signature *s, const char *str) { if (s->init_data->transforms.cnt) { SCLogError("previous transforms not consumed before 'filename'"); @@ -331,9 +331,8 @@ static int PrefilterMpmFilenameRegister(DetectEngineCtx *de_ctx, SigGroupHead *s pectx->mpm_ctx = mpm_ctx; pectx->transforms = &mpm_reg->transforms; - return PrefilterAppendTxEngine(de_ctx, sgh, PrefilterTxFilename, - mpm_reg->app_v2.alproto, mpm_reg->app_v2.tx_min_progress, - pectx, PrefilterMpmFilenameFree, mpm_reg->pname); + return PrefilterAppendTxEngine(de_ctx, sgh, PrefilterTxFilename, mpm_reg->app_v2.alproto, + mpm_reg->app_v2.tx_min_progress, pectx, PrefilterMpmFilenameFree, mpm_reg->pname); } #ifdef UNITTESTS /* UNITTESTS */ @@ -343,16 +342,31 @@ static int PrefilterMpmFilenameRegister(DetectEngineCtx *de_ctx, SigGroupHead *s */ static int DetectFilenameSignatureParseTest01(void) { - FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_client; file.name; content:\"abc\"; sid:1;)", true)); - FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_client; file.name; content:\"abc\"; nocase; sid:1;)", true)); - FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_client; file.name; content:\"abc\"; endswith; sid:1;)", true)); - FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_client; file.name; content:\"abc\"; startswith; sid:1;)", true)); - FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_client; file.name; content:\"abc\"; startswith; endswith; sid:1;)", true)); - FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_client; file.name; bsize:10; sid:1;)", true)); - - FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_client; file.name; content:\"abc\"; rawbytes; sid:1;)", false)); - FAIL_IF_NOT(UTHParseSignature("alert tcp any any -> any any (flow:to_client; file.name; sid:1;)", false)); - //FAIL_IF_NOT(UTHParseSignature("alert tls any any -> any any (flow:to_client; file.name; content:\"abc\"; sid:1;)", false)); + FAIL_IF_NOT(UTHParseSignature( + "alert http any any -> any any (flow:to_client; file.name; content:\"abc\"; sid:1;)", + true)); + FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_client; file.name; " + "content:\"abc\"; nocase; sid:1;)", + true)); + FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_client; file.name; " + "content:\"abc\"; endswith; sid:1;)", + true)); + FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_client; file.name; " + "content:\"abc\"; startswith; sid:1;)", + true)); + FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_client; file.name; " + "content:\"abc\"; startswith; endswith; sid:1;)", + true)); + FAIL_IF_NOT(UTHParseSignature( + "alert http any any -> any any (flow:to_client; file.name; bsize:10; sid:1;)", true)); + + FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_client; file.name; " + "content:\"abc\"; rawbytes; sid:1;)", + false)); + FAIL_IF_NOT(UTHParseSignature( + "alert tcp any any -> any any (flow:to_client; file.name; sid:1;)", false)); + // FAIL_IF_NOT(UTHParseSignature("alert tls any any -> any any (flow:to_client; file.name; + // content:\"abc\"; sid:1;)", false)); PASS; } /** diff --git a/src/detect-filename.h b/src/detect-filename.h index 02684fcea416..9dda2b762543 100644 --- a/src/detect-filename.h +++ b/src/detect-filename.h @@ -25,6 +25,6 @@ #define __DETECT_FILENAME_H__ /* prototypes */ -void DetectFilenameRegister (void); +void DetectFilenameRegister(void); #endif /* __DETECT_FILENAME_H__ */ diff --git a/src/detect-filesha1.c b/src/detect-filesha1.c index 6eef33c60824..33790850675e 100644 --- a/src/detect-filesha1.c +++ b/src/detect-filesha1.c @@ -32,7 +32,7 @@ #include "detect-filesha1.h" -static int DetectFileSha1Setup (DetectEngineCtx *, Signature *, const char *); +static int DetectFileSha1Setup(DetectEngineCtx *, Signature *, const char *); #ifdef UNITTESTS static void DetectFileSha1RegisterTests(void); #endif @@ -48,7 +48,7 @@ void DetectFileSha1Register(void) sigmatch_table[DETECT_FILESHA1].url = "/rules/file-keywords.html#filesha1"; sigmatch_table[DETECT_FILESHA1].FileMatch = DetectFileHashMatch; sigmatch_table[DETECT_FILESHA1].Setup = DetectFileSha1Setup; - sigmatch_table[DETECT_FILESHA1].Free = DetectFileHashFree; + sigmatch_table[DETECT_FILESHA1].Free = DetectFileHashFree; #ifdef UNITTESTS sigmatch_table[DETECT_FILESHA1].RegisterTests = DetectFileSha1RegisterTests; #endif @@ -66,7 +66,7 @@ void DetectFileSha1Register(void) * \param s pointer to the Current Signature * \param str pointer to the user provided "filesha1" option */ -static int DetectFileSha1Setup (DetectEngineCtx *de_ctx, Signature *s, const char *str) +static int DetectFileSha1Setup(DetectEngineCtx *de_ctx, Signature *s, const char *str) { return DetectFileHashSetup(de_ctx, s, str, DETECT_FILESHA1, g_file_match_list_id); } diff --git a/src/detect-filesha1.h b/src/detect-filesha1.h index d7504344c606..bf0140cd65b8 100644 --- a/src/detect-filesha1.h +++ b/src/detect-filesha1.h @@ -26,6 +26,6 @@ #define __DETECT_FILESHA1_H__ /* prototypes */ -void DetectFileSha1Register (void); +void DetectFileSha1Register(void); #endif /* __DETECT_FILESHA1_H__ */ diff --git a/src/detect-filesha256.c b/src/detect-filesha256.c index 3b41f42f9573..4fc5a5c40b59 100644 --- a/src/detect-filesha256.c +++ b/src/detect-filesha256.c @@ -32,7 +32,7 @@ #include "detect-filesha256.h" -static int DetectFileSha256Setup (DetectEngineCtx *, Signature *, const char *); +static int DetectFileSha256Setup(DetectEngineCtx *, Signature *, const char *); #ifdef UNITTESTS static void DetectFileSha256RegisterTests(void); #endif @@ -48,7 +48,7 @@ void DetectFileSha256Register(void) sigmatch_table[DETECT_FILESHA256].url = "/rules/file-keywords.html#filesha256"; sigmatch_table[DETECT_FILESHA256].FileMatch = DetectFileHashMatch; sigmatch_table[DETECT_FILESHA256].Setup = DetectFileSha256Setup; - sigmatch_table[DETECT_FILESHA256].Free = DetectFileHashFree; + sigmatch_table[DETECT_FILESHA256].Free = DetectFileHashFree; #ifdef UNITTESTS sigmatch_table[DETECT_FILESHA256].RegisterTests = DetectFileSha256RegisterTests; #endif @@ -70,7 +70,7 @@ void DetectFileSha256Register(void) * \retval 0 on Success * \retval -1 on Failure */ -static int DetectFileSha256Setup (DetectEngineCtx *de_ctx, Signature *s, const char *str) +static int DetectFileSha256Setup(DetectEngineCtx *de_ctx, Signature *s, const char *str) { return DetectFileHashSetup(de_ctx, s, str, DETECT_FILESHA256, g_file_match_list_id); } diff --git a/src/detect-filesha256.h b/src/detect-filesha256.h index a205b48699a0..71b5cb32fdb7 100644 --- a/src/detect-filesha256.h +++ b/src/detect-filesha256.h @@ -26,6 +26,6 @@ #define __DETECT_FILESHA256_H__ /* prototypes */ -void DetectFileSha256Register (void); +void DetectFileSha256Register(void); #endif /* __DETECT_FILESHA256_H__ */ diff --git a/src/detect-filesize.c b/src/detect-filesize.c index c29957d2870b..8b984867844b 100644 --- a/src/detect-filesize.c +++ b/src/detect-filesize.c @@ -43,14 +43,13 @@ #include "flow-util.h" #include "stream-tcp.h" - /*prototypes*/ -static int DetectFilesizeMatch (DetectEngineThreadCtx *det_ctx, Flow *f, - uint8_t flags, File *file, const Signature *s, const SigMatchCtx *m); -static int DetectFilesizeSetup (DetectEngineCtx *, Signature *, const char *); -static void DetectFilesizeFree (DetectEngineCtx *, void *); +static int DetectFilesizeMatch(DetectEngineThreadCtx *det_ctx, Flow *f, uint8_t flags, File *file, + const Signature *s, const SigMatchCtx *m); +static int DetectFilesizeSetup(DetectEngineCtx *, Signature *, const char *); +static void DetectFilesizeFree(DetectEngineCtx *, void *); #ifdef UNITTESTS -static void DetectFilesizeRegisterTests (void); +static void DetectFilesizeRegisterTests(void); #endif static int g_file_match_list_id = 0; @@ -61,7 +60,8 @@ static int g_file_match_list_id = 0; void DetectFilesizeRegister(void) { sigmatch_table[DETECT_FILESIZE].name = "filesize"; - sigmatch_table[DETECT_FILESIZE].desc = "match on the size of the file as it is being transferred"; + sigmatch_table[DETECT_FILESIZE].desc = + "match on the size of the file as it is being transferred"; sigmatch_table[DETECT_FILESIZE].url = "/rules/file-keywords.html#filesize"; sigmatch_table[DETECT_FILESIZE].FileMatch = DetectFilesizeMatch; sigmatch_table[DETECT_FILESIZE].Setup = DetectFilesizeSetup; @@ -87,8 +87,8 @@ void DetectFilesizeRegister(void) * \retval 0 no match * \retval 1 match */ -static int DetectFilesizeMatch (DetectEngineThreadCtx *det_ctx, Flow *f, - uint8_t flags, File *file, const Signature *s, const SigMatchCtx *m) +static int DetectFilesizeMatch(DetectEngineThreadCtx *det_ctx, Flow *f, uint8_t flags, File *file, + const Signature *s, const SigMatchCtx *m) { SCEnter(); @@ -119,7 +119,7 @@ static int DetectFilesizeMatch (DetectEngineThreadCtx *det_ctx, Flow *f, * \retval 0 on Success * \retval -1 on Failure */ -static int DetectFilesizeSetup (DetectEngineCtx *de_ctx, Signature *s, const char *str) +static int DetectFilesizeSetup(DetectEngineCtx *de_ctx, Signature *s, const char *str) { SCEnter(); DetectU64Data *fsd = NULL; @@ -133,7 +133,7 @@ static int DetectFilesizeSetup (DetectEngineCtx *de_ctx, Signature *s, const cha goto error; } - s->file_flags |= (FILE_SIG_NEED_FILE|FILE_SIG_NEED_SIZE); + s->file_flags |= (FILE_SIG_NEED_FILE | FILE_SIG_NEED_SIZE); SCReturnInt(0); error: diff --git a/src/detect-filesize.h b/src/detect-filesize.h index 803b0a3607d6..5e6a8eb1ebdc 100644 --- a/src/detect-filesize.h +++ b/src/detect-filesize.h @@ -22,8 +22,8 @@ */ #ifndef __DETECT_FILESIZE_H__ -#define __DETECT_FILESIZE_H__ +#define __DETECT_FILESIZE_H__ void DetectFilesizeRegister(void); -#endif /* _DETECT_URILEN_H */ +#endif /* _DETECT_URILEN_H */ diff --git a/src/detect-filestore.c b/src/detect-filestore.c index 07bbd91ff199..c926fce98e81 100644 --- a/src/detect-filestore.c +++ b/src/detect-filestore.c @@ -58,15 +58,15 @@ /** * \brief Regex for parsing our flow options */ -#define PARSE_REGEX "^\\s*([A-z_]+)\\s*(?:,\\s*([A-z_]+))?\\s*(?:,\\s*([A-z_]+))?\\s*$" +#define PARSE_REGEX "^\\s*([A-z_]+)\\s*(?:,\\s*([A-z_]+))?\\s*(?:,\\s*([A-z_]+))?\\s*$" static DetectParseRegex parse_regex; -static int DetectFilestoreMatch (DetectEngineThreadCtx *, - Flow *, uint8_t, File *, const Signature *, const SigMatchCtx *); -static int DetectFilestorePostMatch(DetectEngineThreadCtx *det_ctx, - Packet *p, const Signature *s, const SigMatchCtx *ctx); -static int DetectFilestoreSetup (DetectEngineCtx *, Signature *, const char *); +static int DetectFilestoreMatch( + DetectEngineThreadCtx *, Flow *, uint8_t, File *, const Signature *, const SigMatchCtx *); +static int DetectFilestorePostMatch( + DetectEngineThreadCtx *det_ctx, Packet *p, const Signature *s, const SigMatchCtx *ctx); +static int DetectFilestoreSetup(DetectEngineCtx *, Signature *, const char *); static void DetectFilestoreFree(DetectEngineCtx *, void *); #ifdef UNITTESTS static void DetectFilestoreRegisterTests(void); @@ -83,7 +83,7 @@ void DetectFilestoreRegister(void) sigmatch_table[DETECT_FILESTORE].url = "/rules/file-keywords.html#filestore"; sigmatch_table[DETECT_FILESTORE].FileMatch = DetectFilestoreMatch; sigmatch_table[DETECT_FILESTORE].Setup = DetectFilestoreSetup; - sigmatch_table[DETECT_FILESTORE].Free = DetectFilestoreFree; + sigmatch_table[DETECT_FILESTORE].Free = DetectFilestoreFree; #ifdef UNITTESTS sigmatch_table[DETECT_FILESTORE].RegisterTests = DetectFilestoreRegisterTests; #endif @@ -91,7 +91,7 @@ void DetectFilestoreRegister(void) sigmatch_table[DETECT_FILESTORE_POSTMATCH].name = "__filestore__postmatch__"; sigmatch_table[DETECT_FILESTORE_POSTMATCH].Match = DetectFilestorePostMatch; - sigmatch_table[DETECT_FILESTORE_POSTMATCH].Free = DetectFilestoreFree; + sigmatch_table[DETECT_FILESTORE_POSTMATCH].Free = DetectFilestoreFree; DetectSetupParseRegexes(PARSE_REGEX, &parse_regex); @@ -149,7 +149,7 @@ static int FilestorePostMatchWithOptions(Packet *p, Flow *f, const DetectFilesto break; } - if (this_file) { + if (this_file) { FileStoreFileById(fc, file_id); } else if (this_tx) { /* set in AppLayerTxData. Parsers and logger will propagate it to the @@ -189,8 +189,8 @@ static int FilestorePostMatchWithOptions(Packet *p, Flow *f, const DetectFilesto * When we are sure all parts of the signature matched, we run this function * to finalize the filestore. */ -static int DetectFilestorePostMatch(DetectEngineThreadCtx *det_ctx, - Packet *p, const Signature *s, const SigMatchCtx *ctx) +static int DetectFilestorePostMatch( + DetectEngineThreadCtx *det_ctx, Packet *p, const Signature *s, const SigMatchCtx *ctx) { SCEnter(); @@ -261,8 +261,8 @@ static int DetectFilestorePostMatch(DetectEngineThreadCtx *det_ctx, * \todo when we start supporting more protocols, the logic in this function * needs to be put behind a api. */ -static int DetectFilestoreMatch (DetectEngineThreadCtx *det_ctx, Flow *f, - uint8_t flags, File *file, const Signature *s, const SigMatchCtx *m) +static int DetectFilestoreMatch(DetectEngineThreadCtx *det_ctx, Flow *f, uint8_t flags, File *file, + const Signature *s, const SigMatchCtx *m) { uint32_t file_id = 0; @@ -307,9 +307,9 @@ static int DetectFilestoreMatch (DetectEngineThreadCtx *det_ctx, Flow *f, det_ctx->filestore[det_ctx->filestore_cnt].file_id = file_id; det_ctx->filestore[det_ctx->filestore_cnt].tx_id = det_ctx->tx_id; - SCLogDebug("%u, file %u, tx %"PRIu64, det_ctx->filestore_cnt, - det_ctx->filestore[det_ctx->filestore_cnt].file_id, - det_ctx->filestore[det_ctx->filestore_cnt].tx_id); + SCLogDebug("%u, file %u, tx %" PRIu64, det_ctx->filestore_cnt, + det_ctx->filestore[det_ctx->filestore_cnt].file_id, + det_ctx->filestore[det_ctx->filestore_cnt].tx_id); det_ctx->filestore_cnt++; SCReturnInt(1); @@ -326,7 +326,7 @@ static int DetectFilestoreMatch (DetectEngineThreadCtx *det_ctx, Flow *f, * \retval 0 on Success * \retval -1 on Failure */ -static int DetectFilestoreSetup (DetectEngineCtx *de_ctx, Signature *s, const char *str) +static int DetectFilestoreSetup(DetectEngineCtx *de_ctx, Signature *s, const char *str) { SCEnter(); @@ -336,8 +336,8 @@ static int DetectFilestoreSetup (DetectEngineCtx *de_ctx, Signature *s, const ch /* Check on first-time loads (includes following a reload) */ if (!warn_not_configured || (de_ctx->version != de_version)) { if (de_version != de_ctx->version) { - SCLogDebug("reload-detected; re-checking feature presence; DE version now %"PRIu32, - de_ctx->version); + SCLogDebug("reload-detected; re-checking feature presence; DE version now %" PRIu32, + de_ctx->version); } if (!RequiresFeature(FEATURE_OUTPUT_FILESTORE)) { SCLogWarning("One or more rule(s) depends on the " @@ -349,7 +349,7 @@ static int DetectFilestoreSetup (DetectEngineCtx *de_ctx, Signature *s, const ch } DetectFilestoreData *fd = NULL; - char *args[3] = {NULL,NULL,NULL}; + char *args[3] = { NULL, NULL, NULL }; int res = 0; size_t pcre2len; pcre2_match_data *match = NULL; @@ -408,20 +408,14 @@ static int DetectFilestoreSetup (DetectEngineCtx *de_ctx, Signature *s, const ch if (args[0] != NULL) { SCLogDebug("first arg %s", args[0]); - if (strcasecmp(args[0], "request") == 0 || - strcasecmp(args[0], "to_server") == 0) - { + if (strcasecmp(args[0], "request") == 0 || strcasecmp(args[0], "to_server") == 0) { fd->direction = FILESTORE_DIR_TOSERVER; fd->scope = FILESTORE_SCOPE_TX; - } - else if (strcasecmp(args[0], "response") == 0 || - strcasecmp(args[0], "to_client") == 0) - { + } else if (strcasecmp(args[0], "response") == 0 || + strcasecmp(args[0], "to_client") == 0) { fd->direction = FILESTORE_DIR_TOCLIENT; fd->scope = FILESTORE_SCOPE_TX; - } - else if (strcasecmp(args[0], "both") == 0) - { + } else if (strcasecmp(args[0], "both") == 0) { fd->direction = FILESTORE_DIR_BOTH; fd->scope = FILESTORE_SCOPE_TX; } @@ -432,15 +426,11 @@ static int DetectFilestoreSetup (DetectEngineCtx *de_ctx, Signature *s, const ch if (args[1] != NULL) { SCLogDebug("second arg %s", args[1]); - if (strcasecmp(args[1], "file") == 0) - { + if (strcasecmp(args[1], "file") == 0) { fd->scope = FILESTORE_SCOPE_DEFAULT; - } else if (strcasecmp(args[1], "tx") == 0) - { + } else if (strcasecmp(args[1], "tx") == 0) { fd->scope = FILESTORE_SCOPE_TX; - } else if (strcasecmp(args[1], "ssn") == 0 || - strcasecmp(args[1], "flow") == 0) - { + } else if (strcasecmp(args[1], "ssn") == 0 || strcasecmp(args[1], "flow") == 0) { fd->scope = FILESTORE_SCOPE_SSN; } } else { @@ -502,10 +492,10 @@ static int DetectFilestoreTest01(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(bypass; filestore; " - "content:\"message\"; http_host; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(bypass; filestore; " + "content:\"message\"; http_host; " + "sid:1;)"); FAIL_IF_NOT_NULL(de_ctx->sig_list); DetectEngineCtxFree(de_ctx); diff --git a/src/detect-filestore.h b/src/detect-filestore.h index f394842fbd8b..632b679fb351 100644 --- a/src/detect-filestore.h +++ b/src/detect-filestore.h @@ -24,14 +24,14 @@ #ifndef __DETECT_FILESTORE_H__ #define __DETECT_FILESTORE_H__ -#define FILESTORE_DIR_DEFAULT 0 /* rule dir */ -#define FILESTORE_DIR_TOSERVER 1 -#define FILESTORE_DIR_TOCLIENT 2 -#define FILESTORE_DIR_BOTH 3 +#define FILESTORE_DIR_DEFAULT 0 /* rule dir */ +#define FILESTORE_DIR_TOSERVER 1 +#define FILESTORE_DIR_TOCLIENT 2 +#define FILESTORE_DIR_BOTH 3 -#define FILESTORE_SCOPE_DEFAULT 0 /* per file */ -#define FILESTORE_SCOPE_TX 1 /* per transaction */ -#define FILESTORE_SCOPE_SSN 2 /* per flow/ssn */ +#define FILESTORE_SCOPE_DEFAULT 0 /* per file */ +#define FILESTORE_SCOPE_TX 1 /* per transaction */ +#define FILESTORE_SCOPE_SSN 2 /* per flow/ssn */ typedef struct DetectFilestoreData_ { int16_t direction; @@ -39,6 +39,6 @@ typedef struct DetectFilestoreData_ { } DetectFilestoreData; /* prototypes */ -void DetectFilestoreRegister (void); +void DetectFilestoreRegister(void); #endif /* __DETECT_FILESTORE_H__ */ diff --git a/src/detect-flow.c b/src/detect-flow.c index 696e5013a03e..28b96eddcf86 100644 --- a/src/detect-flow.c +++ b/src/detect-flow.c @@ -44,13 +44,12 @@ /** * \brief Regex for parsing our flow options */ -#define PARSE_REGEX "^\\s*([A-z_]+)\\s*(?:,\\s*([A-z_]+))?\\s*(?:,\\s*([A-z_]+))?\\s*$" +#define PARSE_REGEX "^\\s*([A-z_]+)\\s*(?:,\\s*([A-z_]+))?\\s*(?:,\\s*([A-z_]+))?\\s*$" static DetectParseRegex parse_regex; -int DetectFlowMatch (DetectEngineThreadCtx *, Packet *, - const Signature *, const SigMatchCtx *); -static int DetectFlowSetup (DetectEngineCtx *, Signature *, const char *); +int DetectFlowMatch(DetectEngineThreadCtx *, Packet *, const Signature *, const SigMatchCtx *); +static int DetectFlowSetup(DetectEngineCtx *, Signature *, const char *); #ifdef UNITTESTS static void DetectFlowRegisterTests(void); #endif @@ -62,14 +61,14 @@ static bool PrefilterFlowIsPrefilterable(const Signature *s); /** * \brief Registration function for flow: keyword */ -void DetectFlowRegister (void) +void DetectFlowRegister(void) { sigmatch_table[DETECT_FLOW].name = "flow"; sigmatch_table[DETECT_FLOW].desc = "match on direction and state of the flow"; sigmatch_table[DETECT_FLOW].url = "/rules/flow-keywords.html#flow"; sigmatch_table[DETECT_FLOW].Match = DetectFlowMatch; sigmatch_table[DETECT_FLOW].Setup = DetectFlowSetup; - sigmatch_table[DETECT_FLOW].Free = DetectFlowFree; + sigmatch_table[DETECT_FLOW].Free = DetectFlowFree; #ifdef UNITTESTS sigmatch_table[DETECT_FLOW].RegisterTests = DetectFlowRegisterTests; #endif @@ -90,11 +89,9 @@ static inline int FlowMatch(const uint32_t pflags, const uint8_t pflowflags, con { uint8_t cnt = 0; - if ((dflags & DETECT_FLOW_FLAG_NO_FRAG) && - (!(pflags & PKT_REBUILT_FRAGMENT))) { + if ((dflags & DETECT_FLOW_FLAG_NO_FRAG) && (!(pflags & PKT_REBUILT_FRAGMENT))) { cnt++; - } else if ((dflags & DETECT_FLOW_FLAG_ONLY_FRAG) && - (pflags & PKT_REBUILT_FRAGMENT)) { + } else if ((dflags & DETECT_FLOW_FLAG_ONLY_FRAG) && (pflags & PKT_REBUILT_FRAGMENT)) { cnt++; } @@ -106,7 +103,8 @@ static inline int FlowMatch(const uint32_t pflags, const uint8_t pflowflags, con if ((dflags & DETECT_FLOW_FLAG_ESTABLISHED) && (pflowflags & FLOW_PKT_ESTABLISHED)) { cnt++; - } else if (dflags & DETECT_FLOW_FLAG_NOT_ESTABLISHED && (!(pflowflags & FLOW_PKT_ESTABLISHED))) { + } else if (dflags & DETECT_FLOW_FLAG_NOT_ESTABLISHED && + (!(pflowflags & FLOW_PKT_ESTABLISHED))) { cnt++; } else if (dflags & DETECT_FLOW_FLAG_STATELESS) { cnt++; @@ -126,8 +124,8 @@ static inline int FlowMatch(const uint32_t pflags, const uint8_t pflowflags, con * \retval 0 no match * \retval 1 match */ -int DetectFlowMatch (DetectEngineThreadCtx *det_ctx, Packet *p, - const Signature *s, const SigMatchCtx *ctx) +int DetectFlowMatch( + DetectEngineThreadCtx *det_ctx, Packet *p, const Signature *s, const SigMatchCtx *ctx) { SCEnter(); @@ -146,8 +144,9 @@ int DetectFlowMatch (DetectEngineThreadCtx *det_ctx, Packet *p, const DetectFlowData *fd = (const DetectFlowData *)ctx; const int ret = FlowMatch(p->flags, p->flowflags, fd->flags, fd->match_cnt); - SCLogDebug("returning %" PRId32 " fd->match_cnt %" PRId32 " fd->flags 0x%02X p->flowflags 0x%02X", - ret, fd->match_cnt, fd->flags, p->flowflags); + SCLogDebug("returning %" PRId32 " fd->match_cnt %" PRId32 + " fd->flags 0x%02X p->flowflags 0x%02X", + ret, fd->match_cnt, fd->flags, p->flowflags); SCReturnInt(ret); } @@ -165,7 +164,7 @@ static DetectFlowData *DetectFlowParse( DetectEngineCtx *de_ctx, const char *flowstr, uint16_t *parse_flags) { DetectFlowData *fd = NULL; - char *args[3] = {NULL,NULL,NULL}; + char *args[3] = { NULL, NULL, NULL }; int res = 0; size_t pcre2len; char str1[16] = "", str2[16] = "", str3[16] = ""; @@ -251,7 +250,8 @@ static DetectFlowData *DetectFlowParse( } fd->flags |= DETECT_FLOW_FLAG_STATELESS; fd->match_cnt++; - } else if (strcasecmp(args[i], "to_client") == 0 || strcasecmp(args[i], "from_server") == 0) { + } else if (strcasecmp(args[i], "to_client") == 0 || + strcasecmp(args[i], "from_server") == 0) { if (fd->flags & DETECT_FLOW_FLAG_TOCLIENT) { SCLogError("cannot set DETECT_FLOW_FLAG_TOCLIENT flag is already set"); goto error; @@ -261,7 +261,8 @@ static DetectFlowData *DetectFlowParse( } fd->flags |= DETECT_FLOW_FLAG_TOCLIENT; fd->match_cnt++; - } else if (strcasecmp(args[i], "to_server") == 0 || strcasecmp(args[i], "from_client") == 0){ + } else if (strcasecmp(args[i], "to_server") == 0 || + strcasecmp(args[i], "from_client") == 0) { if (fd->flags & DETECT_FLOW_FLAG_TOSERVER) { SCLogError("cannot set DETECT_FLOW_FLAG_TOSERVER flag is already set"); goto error; @@ -330,12 +331,11 @@ static DetectFlowData *DetectFlowParse( if (fd != NULL) DetectFlowFree(de_ctx, fd); return NULL; - } int DetectFlowSetupImplicit(Signature *s, uint32_t flags) { -#define SIG_FLAG_BOTH (SIG_FLAG_TOSERVER|SIG_FLAG_TOCLIENT) +#define SIG_FLAG_BOTH (SIG_FLAG_TOSERVER | SIG_FLAG_TOCLIENT) BUG_ON(flags == 0); BUG_ON(flags & ~SIG_FLAG_BOTH); BUG_ON((flags & SIG_FLAG_BOTH) == SIG_FLAG_BOTH); @@ -374,7 +374,7 @@ int DetectFlowSetupImplicit(Signature *s, uint32_t flags) * \retval 0 on Success * \retval -1 on Failure */ -int DetectFlowSetup (DetectEngineCtx *de_ctx, Signature *s, const char *flowstr) +int DetectFlowSetup(DetectEngineCtx *de_ctx, Signature *s, const char *flowstr) { uint16_t parse_flags = 0; @@ -428,7 +428,6 @@ int DetectFlowSetup (DetectEngineCtx *de_ctx, Signature *s, const char *flowstr) if (fd != NULL) DetectFlowFree(de_ctx, fd); return -1; - } /** @@ -442,8 +441,7 @@ void DetectFlowFree(DetectEngineCtx *de_ctx, void *ptr) SCFree(fd); } -static void -PrefilterPacketFlowMatch(DetectEngineThreadCtx *det_ctx, Packet *p, const void *pectx) +static void PrefilterPacketFlowMatch(DetectEngineThreadCtx *det_ctx, Packet *p, const void *pectx) { const PrefilterPacketHeaderCtx *ctx = pectx; @@ -455,16 +453,14 @@ PrefilterPacketFlowMatch(DetectEngineThreadCtx *det_ctx, Packet *p, const void * } } -static void -PrefilterPacketFlowSet(PrefilterPacketHeaderValue *v, void *smctx) +static void PrefilterPacketFlowSet(PrefilterPacketHeaderValue *v, void *smctx) { const DetectFlowData *fb = smctx; v->u16[0] = fb->flags; v->u16[1] = fb->match_cnt; } -static bool -PrefilterPacketFlowCompare(PrefilterPacketHeaderValue v, void *smctx) +static bool PrefilterPacketFlowCompare(PrefilterPacketHeaderValue v, void *smctx) { const DetectFlowData *fb = smctx; if (v.u16[0] == fb->flags && v.u16[1] == fb->match_cnt) { @@ -475,16 +471,14 @@ PrefilterPacketFlowCompare(PrefilterPacketHeaderValue v, void *smctx) static int PrefilterSetupFlow(DetectEngineCtx *de_ctx, SigGroupHead *sgh) { - return PrefilterSetupPacketHeader(de_ctx, sgh, DETECT_FLOW, - PrefilterPacketFlowSet, - PrefilterPacketFlowCompare, - PrefilterPacketFlowMatch); + return PrefilterSetupPacketHeader(de_ctx, sgh, DETECT_FLOW, PrefilterPacketFlowSet, + PrefilterPacketFlowCompare, PrefilterPacketFlowMatch); } static bool PrefilterFlowIsPrefilterable(const Signature *s) { const SigMatch *sm; - for (sm = s->init_data->smlists[DETECT_SM_LIST_MATCH] ; sm != NULL; sm = sm->next) { + for (sm = s->init_data->smlists[DETECT_SM_LIST_MATCH]; sm != NULL; sm = sm->next) { switch (sm->type) { case DETECT_FLOW: return true; @@ -500,7 +494,7 @@ static bool PrefilterFlowIsPrefilterable(const Signature *s) * \test DetectFlowTestParse01 is a test to make sure that we return "something" * when given valid flow opt */ -static int DetectFlowTestParse01 (void) +static int DetectFlowTestParse01(void) { uint16_t parsed_flags = 0; DetectFlowData *fd = DetectFlowParse(NULL, "established", &parsed_flags); @@ -513,20 +507,19 @@ static int DetectFlowTestParse01 (void) /** * \test DetectFlowTestParse02 is a test for setting the established flow opt */ -static int DetectFlowTestParse02 (void) +static int DetectFlowTestParse02(void) { uint16_t parsed_flags = 0; DetectFlowData *fd = DetectFlowParse(NULL, "established", &parsed_flags); FAIL_IF_NULL(fd); - FAIL_IF_NOT(fd->flags == DETECT_FLOW_FLAG_ESTABLISHED && - fd->match_cnt == 1); + FAIL_IF_NOT(fd->flags == DETECT_FLOW_FLAG_ESTABLISHED && fd->match_cnt == 1); PASS; } /** * \test DetectFlowTestParse03 is a test for setting the stateless flow opt */ -static int DetectFlowTestParse03 (void) +static int DetectFlowTestParse03(void) { uint16_t parsed_flags = 0; DetectFlowData *fd = DetectFlowParse(NULL, "stateless", &parsed_flags); @@ -539,7 +532,7 @@ static int DetectFlowTestParse03 (void) /** * \test DetectFlowTestParse04 is a test for setting the to_client flow opt */ -static int DetectFlowTestParse04 (void) +static int DetectFlowTestParse04(void) { uint16_t parsed_flags = 0; DetectFlowData *fd = DetectFlowParse(NULL, "to_client", &parsed_flags); @@ -552,7 +545,7 @@ static int DetectFlowTestParse04 (void) /** * \test DetectFlowTestParse05 is a test for setting the to_server flow opt */ -static int DetectFlowTestParse05 (void) +static int DetectFlowTestParse05(void) { uint16_t parsed_flags = 0; DetectFlowData *fd = DetectFlowParse(NULL, "to_server", &parsed_flags); @@ -565,7 +558,7 @@ static int DetectFlowTestParse05 (void) /** * \test DetectFlowTestParse06 is a test for setting the from_server flow opt */ -static int DetectFlowTestParse06 (void) +static int DetectFlowTestParse06(void) { uint16_t parsed_flags = 0; DetectFlowData *fd = DetectFlowParse(NULL, "from_server", &parsed_flags); @@ -578,7 +571,7 @@ static int DetectFlowTestParse06 (void) /** * \test DetectFlowTestParse07 is a test for setting the from_client flow opt */ -static int DetectFlowTestParse07 (void) +static int DetectFlowTestParse07(void) { uint16_t parsed_flags = 0; DetectFlowData *fd = DetectFlowParse(NULL, "from_client", &parsed_flags); @@ -591,57 +584,58 @@ static int DetectFlowTestParse07 (void) /** * \test DetectFlowTestParse08 is a test for setting the established,to_client flow opts */ -static int DetectFlowTestParse08 (void) +static int DetectFlowTestParse08(void) { uint16_t parsed_flags = 0; DetectFlowData *fd = DetectFlowParse(NULL, "established,to_client", &parsed_flags); FAIL_IF_NULL(fd); - FAIL_IF_NOT(fd->flags & DETECT_FLOW_FLAG_ESTABLISHED && fd->flags & DETECT_FLOW_FLAG_TOCLIENT && fd->match_cnt == 2); + FAIL_IF_NOT(fd->flags & DETECT_FLOW_FLAG_ESTABLISHED && fd->flags & DETECT_FLOW_FLAG_TOCLIENT && + fd->match_cnt == 2); DetectFlowFree(NULL, fd); PASS; } /** - * \test DetectFlowTestParse09 is a test for setting the to_client,stateless flow opts (order of state,dir reversed) + * \test DetectFlowTestParse09 is a test for setting the to_client,stateless flow opts (order of + * state,dir reversed) */ -static int DetectFlowTestParse09 (void) +static int DetectFlowTestParse09(void) { uint16_t parsed_flags = 0; DetectFlowData *fd = DetectFlowParse(NULL, "to_client,stateless", &parsed_flags); FAIL_IF_NULL(fd); - FAIL_IF_NOT(fd->flags & DETECT_FLOW_FLAG_STATELESS && - fd->flags & DETECT_FLOW_FLAG_TOCLIENT && - fd->match_cnt == 2); + FAIL_IF_NOT(fd->flags & DETECT_FLOW_FLAG_STATELESS && fd->flags & DETECT_FLOW_FLAG_TOCLIENT && + fd->match_cnt == 2); DetectFlowFree(NULL, fd); PASS; } /** - * \test DetectFlowTestParse10 is a test for setting the from_server,stateless flow opts (order of state,dir reversed) + * \test DetectFlowTestParse10 is a test for setting the from_server,stateless flow opts (order of + * state,dir reversed) */ -static int DetectFlowTestParse10 (void) +static int DetectFlowTestParse10(void) { uint16_t parsed_flags = 0; DetectFlowData *fd = DetectFlowParse(NULL, "from_server,stateless", &parsed_flags); FAIL_IF_NULL(fd); - FAIL_IF_NOT(fd->flags & DETECT_FLOW_FLAG_STATELESS && - fd->flags & DETECT_FLOW_FLAG_TOCLIENT && - fd->match_cnt == 2); + FAIL_IF_NOT(fd->flags & DETECT_FLOW_FLAG_STATELESS && fd->flags & DETECT_FLOW_FLAG_TOCLIENT && + fd->match_cnt == 2); DetectFlowFree(NULL, fd); PASS; } /** - * \test DetectFlowTestParse11 is a test for setting the from_server,stateless flow opts with spaces all around + * \test DetectFlowTestParse11 is a test for setting the from_server,stateless flow opts with spaces + * all around */ -static int DetectFlowTestParse11 (void) +static int DetectFlowTestParse11(void) { uint16_t parsed_flags = 0; DetectFlowData *fd = DetectFlowParse(NULL, " from_server , stateless ", &parsed_flags); FAIL_IF_NULL(fd); - FAIL_IF_NOT(fd->flags & DETECT_FLOW_FLAG_STATELESS && - fd->flags & DETECT_FLOW_FLAG_TOCLIENT && - fd->match_cnt == 2); + FAIL_IF_NOT(fd->flags & DETECT_FLOW_FLAG_STATELESS && fd->flags & DETECT_FLOW_FLAG_TOCLIENT && + fd->match_cnt == 2); DetectFlowFree(NULL, fd); PASS; } @@ -650,7 +644,7 @@ static int DetectFlowTestParse11 (void) * \test DetectFlowTestParseNocase01 is a test to make sure that we return "something" * when given valid flow opt */ -static int DetectFlowTestParseNocase01 (void) +static int DetectFlowTestParseNocase01(void) { uint16_t parsed_flags = 0; DetectFlowData *fd = DetectFlowParse(NULL, "ESTABLISHED", &parsed_flags); @@ -662,13 +656,12 @@ static int DetectFlowTestParseNocase01 (void) /** * \test DetectFlowTestParseNocase02 is a test for setting the established flow opt */ -static int DetectFlowTestParseNocase02 (void) +static int DetectFlowTestParseNocase02(void) { uint16_t parsed_flags = 0; DetectFlowData *fd = DetectFlowParse(NULL, "ESTABLISHED", &parsed_flags); FAIL_IF_NULL(fd); - FAIL_IF_NOT(fd->flags == DETECT_FLOW_FLAG_ESTABLISHED && - fd->match_cnt == 1); + FAIL_IF_NOT(fd->flags == DETECT_FLOW_FLAG_ESTABLISHED && fd->match_cnt == 1); DetectFlowFree(NULL, fd); PASS; } @@ -676,7 +669,7 @@ static int DetectFlowTestParseNocase02 (void) /** * \test DetectFlowTestParseNocase03 is a test for setting the stateless flow opt */ -static int DetectFlowTestParseNocase03 (void) +static int DetectFlowTestParseNocase03(void) { uint16_t parsed_flags = 0; DetectFlowData *fd = DetectFlowParse(NULL, "STATELESS", &parsed_flags); @@ -689,7 +682,7 @@ static int DetectFlowTestParseNocase03 (void) /** * \test DetectFlowTestParseNocase04 is a test for setting the to_client flow opt */ -static int DetectFlowTestParseNocase04 (void) +static int DetectFlowTestParseNocase04(void) { uint16_t parsed_flags = 0; DetectFlowData *fd = DetectFlowParse(NULL, "TO_CLIENT", &parsed_flags); @@ -702,7 +695,7 @@ static int DetectFlowTestParseNocase04 (void) /** * \test DetectFlowTestParseNocase05 is a test for setting the to_server flow opt */ -static int DetectFlowTestParseNocase05 (void) +static int DetectFlowTestParseNocase05(void) { uint16_t parsed_flags = 0; DetectFlowData *fd = DetectFlowParse(NULL, "TO_SERVER", &parsed_flags); @@ -715,7 +708,7 @@ static int DetectFlowTestParseNocase05 (void) /** * \test DetectFlowTestParseNocase06 is a test for setting the from_server flow opt */ -static int DetectFlowTestParseNocase06 (void) +static int DetectFlowTestParseNocase06(void) { uint16_t parsed_flags = 0; DetectFlowData *fd = DetectFlowParse(NULL, "FROM_SERVER", &parsed_flags); @@ -728,7 +721,7 @@ static int DetectFlowTestParseNocase06 (void) /** * \test DetectFlowTestParseNocase07 is a test for setting the from_client flow opt */ -static int DetectFlowTestParseNocase07 (void) +static int DetectFlowTestParseNocase07(void) { uint16_t parsed_flags = 0; DetectFlowData *fd = DetectFlowParse(NULL, "FROM_CLIENT", &parsed_flags); @@ -741,59 +734,58 @@ static int DetectFlowTestParseNocase07 (void) /** * \test DetectFlowTestParseNocase08 is a test for setting the established,to_client flow opts */ -static int DetectFlowTestParseNocase08 (void) +static int DetectFlowTestParseNocase08(void) { uint16_t parsed_flags = 0; DetectFlowData *fd = DetectFlowParse(NULL, "ESTABLISHED,TO_CLIENT", &parsed_flags); FAIL_IF_NULL(fd); - FAIL_IF_NOT(fd->flags & DETECT_FLOW_FLAG_ESTABLISHED && - fd->flags & DETECT_FLOW_FLAG_TOCLIENT && - fd->match_cnt == 2); + FAIL_IF_NOT(fd->flags & DETECT_FLOW_FLAG_ESTABLISHED && fd->flags & DETECT_FLOW_FLAG_TOCLIENT && + fd->match_cnt == 2); DetectFlowFree(NULL, fd); PASS; } /** - * \test DetectFlowTestParseNocase09 is a test for setting the to_client,stateless flow opts (order of state,dir reversed) + * \test DetectFlowTestParseNocase09 is a test for setting the to_client,stateless flow opts (order + * of state,dir reversed) */ -static int DetectFlowTestParseNocase09 (void) +static int DetectFlowTestParseNocase09(void) { uint16_t parsed_flags = 0; DetectFlowData *fd = DetectFlowParse(NULL, "TO_CLIENT,STATELESS", &parsed_flags); FAIL_IF_NULL(fd); - FAIL_IF_NOT(fd->flags & DETECT_FLOW_FLAG_STATELESS && - fd->flags & DETECT_FLOW_FLAG_TOCLIENT && - fd->match_cnt == 2); + FAIL_IF_NOT(fd->flags & DETECT_FLOW_FLAG_STATELESS && fd->flags & DETECT_FLOW_FLAG_TOCLIENT && + fd->match_cnt == 2); DetectFlowFree(NULL, fd); PASS; } /** - * \test DetectFlowTestParseNocase10 is a test for setting the from_server,stateless flow opts (order of state,dir reversed) + * \test DetectFlowTestParseNocase10 is a test for setting the from_server,stateless flow opts + * (order of state,dir reversed) */ -static int DetectFlowTestParseNocase10 (void) +static int DetectFlowTestParseNocase10(void) { uint16_t parsed_flags = 0; DetectFlowData *fd = DetectFlowParse(NULL, "FROM_SERVER,STATELESS", &parsed_flags); FAIL_IF_NULL(fd); - FAIL_IF_NOT(fd->flags & DETECT_FLOW_FLAG_STATELESS && - fd->flags & DETECT_FLOW_FLAG_TOCLIENT && - fd->match_cnt == 2); + FAIL_IF_NOT(fd->flags & DETECT_FLOW_FLAG_STATELESS && fd->flags & DETECT_FLOW_FLAG_TOCLIENT && + fd->match_cnt == 2); DetectFlowFree(NULL, fd); PASS; } /** - * \test DetectFlowTestParseNocase11 is a test for setting the from_server,stateless flow opts with spaces all around + * \test DetectFlowTestParseNocase11 is a test for setting the from_server,stateless flow opts with + * spaces all around */ -static int DetectFlowTestParseNocase11 (void) +static int DetectFlowTestParseNocase11(void) { uint16_t parsed_flags = 0; DetectFlowData *fd = DetectFlowParse(NULL, " FROM_SERVER , STATELESS ", &parsed_flags); FAIL_IF_NULL(fd); - FAIL_IF_NOT(fd->flags & DETECT_FLOW_FLAG_STATELESS && - fd->flags & DETECT_FLOW_FLAG_TOCLIENT && - fd->match_cnt == 2); + FAIL_IF_NOT(fd->flags & DETECT_FLOW_FLAG_STATELESS && fd->flags & DETECT_FLOW_FLAG_TOCLIENT && + fd->match_cnt == 2); DetectFlowFree(NULL, fd); PASS; } @@ -801,7 +793,7 @@ static int DetectFlowTestParseNocase11 (void) /** * \test DetectFlowTestParse12 is a test for setting an invalid separator : */ -static int DetectFlowTestParse12 (void) +static int DetectFlowTestParse12(void) { uint16_t parsed_flags = 0; DetectFlowData *fd = DetectFlowParse(NULL, "from_server:stateless", &parsed_flags); @@ -812,7 +804,7 @@ static int DetectFlowTestParse12 (void) /** * \test DetectFlowTestParse13 is a test for an invalid option */ -static int DetectFlowTestParse13 (void) +static int DetectFlowTestParse13(void) { uint16_t parsed_flags = 0; DetectFlowData *fd = DetectFlowParse(NULL, "invalidoptiontest", &parsed_flags); @@ -823,7 +815,7 @@ static int DetectFlowTestParse13 (void) /** * \test DetectFlowTestParse14 is a test for a empty option */ -static int DetectFlowTestParse14 (void) +static int DetectFlowTestParse14(void) { uint16_t parsed_flags = 0; DetectFlowData *fd = DetectFlowParse(NULL, "", &parsed_flags); @@ -834,7 +826,7 @@ static int DetectFlowTestParse14 (void) /** * \test DetectFlowTestParse15 is a test for an invalid combo of options established,stateless */ -static int DetectFlowTestParse15 (void) +static int DetectFlowTestParse15(void) { uint16_t parsed_flags = 0; DetectFlowData *fd = DetectFlowParse(NULL, "established,stateless", &parsed_flags); @@ -845,7 +837,7 @@ static int DetectFlowTestParse15 (void) /** * \test DetectFlowTestParse16 is a test for an invalid combo of options to_client,to_server */ -static int DetectFlowTestParse16 (void) +static int DetectFlowTestParse16(void) { uint16_t parsed_flags = 0; DetectFlowData *fd = DetectFlowParse(NULL, "to_client,to_server", &parsed_flags); @@ -857,7 +849,7 @@ static int DetectFlowTestParse16 (void) * \test DetectFlowTestParse16 is a test for an invalid combo of options to_client,from_server * flowbit flags are the same */ -static int DetectFlowTestParse17 (void) +static int DetectFlowTestParse17(void) { uint16_t parsed_flags = 0; DetectFlowData *fd = DetectFlowParse(NULL, "to_client,from_server", &parsed_flags); @@ -866,9 +858,10 @@ static int DetectFlowTestParse17 (void) } /** - * \test DetectFlowTestParse18 is a test for setting the from_server,stateless,only_stream flow opts (order of state,dir reversed) + * \test DetectFlowTestParse18 is a test for setting the from_server,stateless,only_stream flow opts + * (order of state,dir reversed) */ -static int DetectFlowTestParse18 (void) +static int DetectFlowTestParse18(void) { uint16_t parsed_flags = 0; DetectFlowData *fd = @@ -882,9 +875,10 @@ static int DetectFlowTestParse18 (void) } /** - * \test DetectFlowTestParseNocase18 is a test for setting the from_server,stateless,only_stream flow opts (order of state,dir reversed) + * \test DetectFlowTestParseNocase18 is a test for setting the from_server,stateless,only_stream + * flow opts (order of state,dir reversed) */ -static int DetectFlowTestParseNocase18 (void) +static int DetectFlowTestParseNocase18(void) { uint16_t parsed_flags = 0; DetectFlowData *fd = @@ -897,11 +891,10 @@ static int DetectFlowTestParseNocase18 (void) PASS; } - /** * \test DetectFlowTestParse19 is a test for one to many options passed to DetectFlowParse */ -static int DetectFlowTestParse19 (void) +static int DetectFlowTestParse19(void) { uint16_t parsed_flags = 0; DetectFlowData *fd = @@ -913,7 +906,7 @@ static int DetectFlowTestParse19 (void) /** * \test DetectFlowTestParse20 is a test for setting from_server, established, no_stream */ -static int DetectFlowTestParse20 (void) +static int DetectFlowTestParse20(void) { uint16_t parsed_flags = 0; DetectFlowData *fd = DetectFlowParse(NULL, "from_server,established,no_stream", &parsed_flags); @@ -928,7 +921,7 @@ static int DetectFlowTestParse20 (void) /** * \test DetectFlowTestParse20 is a test for setting from_server, established, no_stream */ -static int DetectFlowTestParseNocase20 (void) +static int DetectFlowTestParseNocase20(void) { uint16_t parsed_flags = 0; DetectFlowData *fd = DetectFlowParse(NULL, "FROM_SERVER,ESTABLISHED,NO_STREAM", &parsed_flags); @@ -943,7 +936,7 @@ static int DetectFlowTestParseNocase20 (void) /** * \test DetectFlowTestParse21 is a test for an invalid opt between to valid opts */ -static int DetectFlowTestParse21 (void) +static int DetectFlowTestParse21(void) { uint16_t parsed_flags = 0; DetectFlowData *fd = DetectFlowParse(NULL, "from_server,a,no_stream", &parsed_flags); @@ -977,7 +970,7 @@ static int DetectFlowSigTest01(void) FAIL_IF_NULL(p); const char *sig1 = "alert tcp any any -> any any (msg:\"dummy\"; " - "content:\"nova\"; flow:no_stream; sid:1;)"; + "content:\"nova\"; flow:no_stream; sid:1;)"; DetectEngineCtx *de_ctx = DetectEngineCtxInit(); FAIL_IF_NULL(de_ctx); @@ -1125,13 +1118,10 @@ static void DetectFlowRegisterTests(void) UtRegisterTest("DetectFlowTestParseNocase20", DetectFlowTestParseNocase20); UtRegisterTest("DetectFlowTestParse21", DetectFlowTestParse21); UtRegisterTest("DetectFlowTestParse22", DetectFlowTestParse22); - UtRegisterTest("DetectFlowTestParseNotEstablished", - DetectFlowTestParseNotEstablished); + UtRegisterTest("DetectFlowTestParseNotEstablished", DetectFlowTestParseNotEstablished); UtRegisterTest("DetectFlowTestParseNoFrag", DetectFlowTestParseNoFrag); - UtRegisterTest("DetectFlowTestParseOnlyFrag", - DetectFlowTestParseOnlyFrag); - UtRegisterTest("DetectFlowTestParseNoFragOnlyFrag", - DetectFlowTestParseNoFragOnlyFrag); + UtRegisterTest("DetectFlowTestParseOnlyFrag", DetectFlowTestParseOnlyFrag); + UtRegisterTest("DetectFlowTestParseNoFragOnlyFrag", DetectFlowTestParseNoFragOnlyFrag); UtRegisterTest("DetectFlowTestNoFragMatch", DetectFlowTestNoFragMatch); UtRegisterTest("DetectFlowTestOnlyFragMatch", DetectFlowTestOnlyFragMatch); diff --git a/src/detect-flow.h b/src/detect-flow.h index 0fee4bf8c17a..d289795dba08 100644 --- a/src/detect-flow.h +++ b/src/detect-flow.h @@ -35,14 +35,13 @@ #define DETECT_FLOW_FLAG_ONLY_FRAG BIT_U16(8) typedef struct DetectFlowData_ { - uint16_t flags; /* flags to match */ - uint8_t match_cnt; /* number of matches we need */ + uint16_t flags; /* flags to match */ + uint8_t match_cnt; /* number of matches we need */ } DetectFlowData; int DetectFlowSetupImplicit(Signature *s, uint32_t flags); /* prototypes */ -void DetectFlowRegister (void); +void DetectFlowRegister(void); #endif /* __DETECT_FLOW_H__ */ - diff --git a/src/detect-flowbits.c b/src/detect-flowbits.c index b04c271dc548..2c53791a53ed 100644 --- a/src/detect-flowbits.c +++ b/src/detect-flowbits.c @@ -47,28 +47,27 @@ #include "util-debug.h" #include "util-conf.h" -#define PARSE_REGEX "^([a-z]+)(?:,\\s*(.*))?" +#define PARSE_REGEX "^([a-z]+)(?:,\\s*(.*))?" static DetectParseRegex parse_regex; #define MAX_TOKENS 100 -int DetectFlowbitMatch (DetectEngineThreadCtx *, Packet *, - const Signature *, const SigMatchCtx *); -static int DetectFlowbitSetup (DetectEngineCtx *, Signature *, const char *); +int DetectFlowbitMatch(DetectEngineThreadCtx *, Packet *, const Signature *, const SigMatchCtx *); +static int DetectFlowbitSetup(DetectEngineCtx *, Signature *, const char *); static int FlowbitOrAddData(DetectEngineCtx *, DetectFlowbitsData *, char *); -void DetectFlowbitFree (DetectEngineCtx *, void *); +void DetectFlowbitFree(DetectEngineCtx *, void *); #ifdef UNITTESTS void FlowBitsRegisterTests(void); #endif -void DetectFlowbitsRegister (void) +void DetectFlowbitsRegister(void) { sigmatch_table[DETECT_FLOWBITS].name = "flowbits"; sigmatch_table[DETECT_FLOWBITS].desc = "operate on flow flag"; sigmatch_table[DETECT_FLOWBITS].url = "/rules/flow-keywords.html#flowbits"; sigmatch_table[DETECT_FLOWBITS].Match = DetectFlowbitMatch; sigmatch_table[DETECT_FLOWBITS].Setup = DetectFlowbitSetup; - sigmatch_table[DETECT_FLOWBITS].Free = DetectFlowbitFree; + sigmatch_table[DETECT_FLOWBITS].Free = DetectFlowbitFree; #ifdef UNITTESTS sigmatch_table[DETECT_FLOWBITS].RegisterTests = FlowBitsRegisterTests; #endif @@ -87,12 +86,12 @@ static int FlowbitOrAddData(DetectEngineCtx *de_ctx, DetectFlowbitsData *cd, cha while ((token = strtok_r(arrptr, "|", &saveptr))) { // Check for leading/trailing spaces in the token - while(isspace((unsigned char)*token)) + while (isspace((unsigned char)*token)) token++; if (*token == 0) goto next; char *end = token + strlen(token) - 1; - while(end > token && isspace((unsigned char)*end)) + while (end > token && isspace((unsigned char)*end)) *(end--) = '\0'; // Check for spaces in between the flowbit names @@ -120,7 +119,7 @@ static int FlowbitOrAddData(DetectEngineCtx *de_ctx, DetectFlowbitsData *cd, cha cd->or_list = SCCalloc(cd->or_list_size, sizeof(uint32_t)); if (unlikely(cd->or_list == NULL)) return -1; - for (uint8_t j = 0; j < cd->or_list_size ; j++) { + for (uint8_t j = 0; j < cd->or_list_size; j++) { cd->or_list[j] = VarNameStoreRegister(strarr[j], VAR_TYPE_FLOW_BIT); de_ctx->max_fb_id = MAX(cd->or_list[j], de_ctx->max_fb_id); } @@ -128,37 +127,37 @@ static int FlowbitOrAddData(DetectEngineCtx *de_ctx, DetectFlowbitsData *cd, cha return 1; } -static int DetectFlowbitMatchToggle (Packet *p, const DetectFlowbitsData *fd) +static int DetectFlowbitMatchToggle(Packet *p, const DetectFlowbitsData *fd) { if (p->flow == NULL) return 0; - FlowBitToggle(p->flow,fd->idx); + FlowBitToggle(p->flow, fd->idx); return 1; } -static int DetectFlowbitMatchUnset (Packet *p, const DetectFlowbitsData *fd) +static int DetectFlowbitMatchUnset(Packet *p, const DetectFlowbitsData *fd) { if (p->flow == NULL) return 0; - FlowBitUnset(p->flow,fd->idx); + FlowBitUnset(p->flow, fd->idx); return 1; } -static int DetectFlowbitMatchSet (Packet *p, const DetectFlowbitsData *fd) +static int DetectFlowbitMatchSet(Packet *p, const DetectFlowbitsData *fd) { if (p->flow == NULL) return 0; - FlowBitSet(p->flow,fd->idx); + FlowBitSet(p->flow, fd->idx); return 1; } -static int DetectFlowbitMatchIsset (Packet *p, const DetectFlowbitsData *fd) +static int DetectFlowbitMatchIsset(Packet *p, const DetectFlowbitsData *fd) { if (p->flow == NULL) return 0; @@ -170,10 +169,10 @@ static int DetectFlowbitMatchIsset (Packet *p, const DetectFlowbitsData *fd) return 0; } - return FlowBitIsset(p->flow,fd->idx); + return FlowBitIsset(p->flow, fd->idx); } -static int DetectFlowbitMatchIsnotset (Packet *p, const DetectFlowbitsData *fd) +static int DetectFlowbitMatchIsnotset(Packet *p, const DetectFlowbitsData *fd) { if (p->flow == NULL) return 0; @@ -184,7 +183,7 @@ static int DetectFlowbitMatchIsnotset (Packet *p, const DetectFlowbitsData *fd) } return 0; } - return FlowBitIsnotset(p->flow,fd->idx); + return FlowBitIsnotset(p->flow, fd->idx); } /* @@ -193,8 +192,8 @@ static int DetectFlowbitMatchIsnotset (Packet *p, const DetectFlowbitsData *fd) * -1: error */ -int DetectFlowbitMatch (DetectEngineThreadCtx *det_ctx, Packet *p, - const Signature *s, const SigMatchCtx *ctx) +int DetectFlowbitMatch( + DetectEngineThreadCtx *det_ctx, Packet *p, const Signature *s, const SigMatchCtx *ctx) { const DetectFlowbitsData *fd = (const DetectFlowbitsData *)ctx; if (fd == NULL) @@ -202,15 +201,15 @@ int DetectFlowbitMatch (DetectEngineThreadCtx *det_ctx, Packet *p, switch (fd->cmd) { case DETECT_FLOWBITS_CMD_ISSET: - return DetectFlowbitMatchIsset(p,fd); + return DetectFlowbitMatchIsset(p, fd); case DETECT_FLOWBITS_CMD_ISNOTSET: - return DetectFlowbitMatchIsnotset(p,fd); + return DetectFlowbitMatchIsnotset(p, fd); case DETECT_FLOWBITS_CMD_SET: - return DetectFlowbitMatchSet(p,fd); + return DetectFlowbitMatchSet(p, fd); case DETECT_FLOWBITS_CMD_UNSET: - return DetectFlowbitMatchUnset(p,fd); + return DetectFlowbitMatchUnset(p, fd); case DETECT_FLOWBITS_CMD_TOGGLE: - return DetectFlowbitMatchToggle(p,fd); + return DetectFlowbitMatchToggle(p, fd); default: SCLogError("unknown cmd %" PRIu32 "", fd->cmd); return 0; @@ -219,8 +218,7 @@ int DetectFlowbitMatch (DetectEngineThreadCtx *det_ctx, Packet *p, return 0; } -static int DetectFlowbitParse(const char *str, char *cmd, int cmd_len, char *name, - int name_len) +static int DetectFlowbitParse(const char *str, char *cmd, int cmd_len, char *name, int name_len) { int rc; size_t pcre2len; @@ -273,28 +271,27 @@ static int DetectFlowbitParse(const char *str, char *cmd, int cmd_len, char *nam return 0; } -int DetectFlowbitSetup (DetectEngineCtx *de_ctx, Signature *s, const char *rawstr) +int DetectFlowbitSetup(DetectEngineCtx *de_ctx, Signature *s, const char *rawstr) { DetectFlowbitsData *cd = NULL; uint8_t fb_cmd = 0; char fb_cmd_str[16] = "", fb_name[256] = ""; - if (!DetectFlowbitParse(rawstr, fb_cmd_str, sizeof(fb_cmd_str), fb_name, - sizeof(fb_name))) { + if (!DetectFlowbitParse(rawstr, fb_cmd_str, sizeof(fb_cmd_str), fb_name, sizeof(fb_name))) { return -1; } - if (strcmp(fb_cmd_str,"noalert") == 0) { + if (strcmp(fb_cmd_str, "noalert") == 0) { fb_cmd = DETECT_FLOWBITS_CMD_NOALERT; - } else if (strcmp(fb_cmd_str,"isset") == 0) { + } else if (strcmp(fb_cmd_str, "isset") == 0) { fb_cmd = DETECT_FLOWBITS_CMD_ISSET; - } else if (strcmp(fb_cmd_str,"isnotset") == 0) { + } else if (strcmp(fb_cmd_str, "isnotset") == 0) { fb_cmd = DETECT_FLOWBITS_CMD_ISNOTSET; - } else if (strcmp(fb_cmd_str,"set") == 0) { + } else if (strcmp(fb_cmd_str, "set") == 0) { fb_cmd = DETECT_FLOWBITS_CMD_SET; - } else if (strcmp(fb_cmd_str,"unset") == 0) { + } else if (strcmp(fb_cmd_str, "unset") == 0) { fb_cmd = DETECT_FLOWBITS_CMD_UNSET; - } else if (strcmp(fb_cmd_str,"toggle") == 0) { + } else if (strcmp(fb_cmd_str, "toggle") == 0) { fb_cmd = DETECT_FLOWBITS_CMD_TOGGLE; } else { SCLogError("ERROR: flowbits action \"%s\" is not supported.", fb_cmd_str); @@ -333,14 +330,14 @@ int DetectFlowbitSetup (DetectEngineCtx *de_ctx, Signature *s, const char *rawst cd->cmd = fb_cmd; cd->or_list_size = 0; cd->or_list = NULL; - SCLogDebug("idx %" PRIu32 ", cmd %s, name %s", - cd->idx, fb_cmd_str, strlen(fb_name) ? fb_name : "(none)"); + SCLogDebug("idx %" PRIu32 ", cmd %s, name %s", cd->idx, fb_cmd_str, + strlen(fb_name) ? fb_name : "(none)"); } /* Okay so far so good, lets get this into a SigMatch * and put it in the Signature. */ switch (fb_cmd) { - /* case DETECT_FLOWBITS_CMD_NOALERT can't happen here */ + /* case DETECT_FLOWBITS_CMD_NOALERT can't happen here */ case DETECT_FLOWBITS_CMD_ISNOTSET: case DETECT_FLOWBITS_CMD_ISSET: @@ -375,7 +372,7 @@ int DetectFlowbitSetup (DetectEngineCtx *de_ctx, Signature *s, const char *rawst return -1; } -void DetectFlowbitFree (DetectEngineCtx *de_ctx, void *ptr) +void DetectFlowbitFree(DetectEngineCtx *de_ctx, void *ptr) { DetectFlowbitsData *fd = (DetectFlowbitsData *)ptr; if (fd == NULL) @@ -416,8 +413,8 @@ struct FBAnalyze { }; extern bool rule_engine_analysis_set; -static void DetectFlowbitsAnalyzeDump(const DetectEngineCtx *de_ctx, - struct FBAnalyze *array, uint32_t elements); +static void DetectFlowbitsAnalyzeDump( + const DetectEngineCtx *de_ctx, struct FBAnalyze *array, uint32_t elements); int DetectFlowbitsAnalyze(DetectEngineCtx *de_ctx) { @@ -434,8 +431,8 @@ int DetectFlowbitsAnalyze(DetectEngineCtx *de_ctx) return -1; } - SCLogDebug("fb analyzer array size: %"PRIu64, - (uint64_t)(array_size * sizeof(struct FBAnalyze))); + SCLogDebug( + "fb analyzer array size: %" PRIu64, (uint64_t)(array_size * sizeof(struct FBAnalyze))); /* fill flowbit array, updating counters per sig */ for (uint32_t i = 0; i < de_ctx->sig_array_len; i++) { @@ -444,10 +441,10 @@ int DetectFlowbitsAnalyze(DetectEngineCtx *de_ctx) /* see if the signature uses stateful matching */ bool has_state = (s->init_data->buffer_index != 0); - for (const SigMatch *sm = s->init_data->smlists[DETECT_SM_LIST_MATCH] ; sm != NULL; sm = sm->next) { + for (const SigMatch *sm = s->init_data->smlists[DETECT_SM_LIST_MATCH]; sm != NULL; + sm = sm->next) { switch (sm->type) { - case DETECT_FLOWBITS: - { + case DETECT_FLOWBITS: { /* figure out the flowbit action */ const DetectFlowbitsData *fb = (DetectFlowbitsData *)sm->ctx; // Handle flowbit array in case of ORed flowbits @@ -456,32 +453,39 @@ int DetectFlowbitsAnalyze(DetectEngineCtx *de_ctx) if (has_state) array[fb->or_list[k]].state_cnts[fb->cmd]++; if (fb->cmd == DETECT_FLOWBITS_CMD_ISSET) { - if (array[fb->or_list[k]].isset_sids_idx >= array[fb->or_list[k]].isset_sids_size) { + if (array[fb->or_list[k]].isset_sids_idx >= + array[fb->or_list[k]].isset_sids_size) { uint32_t old_size = array[fb->or_list[k]].isset_sids_size; uint32_t new_size = MAX(2 * old_size, MAX_SIDS); - void *ptr = SCRealloc(array[fb->or_list[k]].isset_sids, new_size * sizeof(uint32_t)); + void *ptr = SCRealloc(array[fb->or_list[k]].isset_sids, + new_size * sizeof(uint32_t)); if (ptr == NULL) goto end; array[fb->or_list[k]].isset_sids_size = new_size; array[fb->or_list[k]].isset_sids = ptr; } - array[fb->or_list[k]].isset_sids[array[fb->or_list[k]].isset_sids_idx] = s->num; + array[fb->or_list[k]].isset_sids[array[fb->or_list[k]].isset_sids_idx] = + s->num; array[fb->or_list[k]].isset_sids_idx++; } else if (fb->cmd == DETECT_FLOWBITS_CMD_ISNOTSET) { - if (array[fb->or_list[k]].isnotset_sids_idx >= array[fb->or_list[k]].isnotset_sids_size) { + if (array[fb->or_list[k]].isnotset_sids_idx >= + array[fb->or_list[k]].isnotset_sids_size) { uint32_t old_size = array[fb->or_list[k]].isnotset_sids_size; uint32_t new_size = MAX(2 * old_size, MAX_SIDS); - void *ptr = SCRealloc(array[fb->or_list[k]].isnotset_sids, new_size * sizeof(uint32_t)); + void *ptr = SCRealloc(array[fb->or_list[k]].isnotset_sids, + new_size * sizeof(uint32_t)); if (ptr == NULL) goto end; array[fb->or_list[k]].isnotset_sids_size = new_size; array[fb->or_list[k]].isnotset_sids = ptr; } - array[fb->or_list[k]].isnotset_sids[array[fb->or_list[k]].isnotset_sids_idx] = s->num; + array[fb->or_list[k]] + .isnotset_sids[array[fb->or_list[k]].isnotset_sids_idx] = + s->num; array[fb->or_list[k]].isnotset_sids_idx++; } } @@ -494,7 +498,8 @@ int DetectFlowbitsAnalyze(DetectEngineCtx *de_ctx) uint32_t old_size = array[fb->idx].isset_sids_size; uint32_t new_size = MAX(2 * old_size, MAX_SIDS); - void *ptr = SCRealloc(array[fb->idx].isset_sids, new_size * sizeof(uint32_t)); + void *ptr = SCRealloc( + array[fb->idx].isset_sids, new_size * sizeof(uint32_t)); if (ptr == NULL) goto end; array[fb->idx].isset_sids_size = new_size; @@ -504,11 +509,13 @@ int DetectFlowbitsAnalyze(DetectEngineCtx *de_ctx) array[fb->idx].isset_sids[array[fb->idx].isset_sids_idx] = s->num; array[fb->idx].isset_sids_idx++; } else if (fb->cmd == DETECT_FLOWBITS_CMD_ISNOTSET) { - if (array[fb->idx].isnotset_sids_idx >= array[fb->idx].isnotset_sids_size) { + if (array[fb->idx].isnotset_sids_idx >= + array[fb->idx].isnotset_sids_size) { uint32_t old_size = array[fb->idx].isnotset_sids_size; uint32_t new_size = MAX(2 * old_size, MAX_SIDS); - void *ptr = SCRealloc(array[fb->idx].isnotset_sids, new_size * sizeof(uint32_t)); + void *ptr = SCRealloc( + array[fb->idx].isnotset_sids, new_size * sizeof(uint32_t)); if (ptr == NULL) goto end; array[fb->idx].isnotset_sids_size = new_size; @@ -522,10 +529,10 @@ int DetectFlowbitsAnalyze(DetectEngineCtx *de_ctx) } } } - for (const SigMatch *sm = s->init_data->smlists[DETECT_SM_LIST_POSTMATCH] ; sm != NULL; sm = sm->next) { + for (const SigMatch *sm = s->init_data->smlists[DETECT_SM_LIST_POSTMATCH]; sm != NULL; + sm = sm->next) { switch (sm->type) { - case DETECT_FLOWBITS: - { + case DETECT_FLOWBITS: { /* figure out what flowbit action */ const DetectFlowbitsData *fb = (DetectFlowbitsData *)sm->ctx; array[fb->idx].cnts[fb->cmd]++; @@ -536,7 +543,8 @@ int DetectFlowbitsAnalyze(DetectEngineCtx *de_ctx) uint32_t old_size = array[fb->idx].set_sids_size; uint32_t new_size = MAX(2 * old_size, MAX_SIDS); - void *ptr = SCRealloc(array[fb->idx].set_sids, new_size * sizeof(uint32_t)); + void *ptr = + SCRealloc(array[fb->idx].set_sids, new_size * sizeof(uint32_t)); if (ptr == NULL) goto end; array[fb->idx].set_sids_size = new_size; @@ -545,13 +553,13 @@ int DetectFlowbitsAnalyze(DetectEngineCtx *de_ctx) array[fb->idx].set_sids[array[fb->idx].set_sids_idx] = s->num; array[fb->idx].set_sids_idx++; - } - else if (fb->cmd == DETECT_FLOWBITS_CMD_UNSET) { + } else if (fb->cmd == DETECT_FLOWBITS_CMD_UNSET) { if (array[fb->idx].unset_sids_idx >= array[fb->idx].unset_sids_size) { uint32_t old_size = array[fb->idx].unset_sids_size; uint32_t new_size = MAX(2 * old_size, MAX_SIDS); - void *ptr = SCRealloc(array[fb->idx].unset_sids, new_size * sizeof(uint32_t)); + void *ptr = SCRealloc( + array[fb->idx].unset_sids, new_size * sizeof(uint32_t)); if (ptr == NULL) goto end; array[fb->idx].unset_sids_size = new_size; @@ -560,13 +568,13 @@ int DetectFlowbitsAnalyze(DetectEngineCtx *de_ctx) array[fb->idx].unset_sids[array[fb->idx].unset_sids_idx] = s->num; array[fb->idx].unset_sids_idx++; - } - else if (fb->cmd == DETECT_FLOWBITS_CMD_TOGGLE) { + } else if (fb->cmd == DETECT_FLOWBITS_CMD_TOGGLE) { if (array[fb->idx].toggle_sids_idx >= array[fb->idx].toggle_sids_size) { uint32_t old_size = array[fb->idx].toggle_sids_size; uint32_t new_size = MAX(2 * old_size, MAX_SIDS); - void *ptr = SCRealloc(array[fb->idx].toggle_sids, new_size * sizeof(uint32_t)); + void *ptr = SCRealloc( + array[fb->idx].toggle_sids, new_size * sizeof(uint32_t)); if (ptr == NULL) goto end; array[fb->idx].toggle_sids_size = new_size; @@ -590,8 +598,8 @@ int DetectFlowbitsAnalyze(DetectEngineCtx *de_ctx) bool to_state = false; if (array[i].cnts[DETECT_FLOWBITS_CMD_ISSET] && - array[i].cnts[DETECT_FLOWBITS_CMD_TOGGLE] == 0 && - array[i].cnts[DETECT_FLOWBITS_CMD_SET] == 0) { + array[i].cnts[DETECT_FLOWBITS_CMD_TOGGLE] == 0 && + array[i].cnts[DETECT_FLOWBITS_CMD_SET] == 0) { const Signature *s = de_ctx->sig_array[array[i].isset_sids[0]]; SCLogWarning("flowbit '%s' is checked but not " @@ -599,28 +607,29 @@ int DetectFlowbitsAnalyze(DetectEngineCtx *de_ctx) varname, s->id, array[i].isset_sids_idx - 1); } if (array[i].state_cnts[DETECT_FLOWBITS_CMD_ISSET] && - array[i].state_cnts[DETECT_FLOWBITS_CMD_SET] == 0) - { + array[i].state_cnts[DETECT_FLOWBITS_CMD_SET] == 0) { SCLogDebug("flowbit %s/%u: isset in state, set not in state", varname, i); } /* if signature depends on 'stateful' flowbits, then turn the * sig into a stateful sig itself */ if (array[i].cnts[DETECT_FLOWBITS_CMD_ISSET] > 0 && - array[i].state_cnts[DETECT_FLOWBITS_CMD_ISSET] == 0 && - array[i].state_cnts[DETECT_FLOWBITS_CMD_SET]) - { + array[i].state_cnts[DETECT_FLOWBITS_CMD_ISSET] == 0 && + array[i].state_cnts[DETECT_FLOWBITS_CMD_SET]) { SCLogDebug("flowbit %s/%u: isset not in state, set in state", varname, i); to_state = true; } - SCLogDebug("ALL flowbit %s/%u: sets %u toggles %u unsets %u isnotsets %u issets %u", varname, i, - array[i].cnts[DETECT_FLOWBITS_CMD_SET], array[i].cnts[DETECT_FLOWBITS_CMD_TOGGLE], - array[i].cnts[DETECT_FLOWBITS_CMD_UNSET], array[i].cnts[DETECT_FLOWBITS_CMD_ISNOTSET], + SCLogDebug("ALL flowbit %s/%u: sets %u toggles %u unsets %u isnotsets %u issets %u", + varname, i, array[i].cnts[DETECT_FLOWBITS_CMD_SET], + array[i].cnts[DETECT_FLOWBITS_CMD_TOGGLE], array[i].cnts[DETECT_FLOWBITS_CMD_UNSET], + array[i].cnts[DETECT_FLOWBITS_CMD_ISNOTSET], array[i].cnts[DETECT_FLOWBITS_CMD_ISSET]); - SCLogDebug("STATE flowbit %s/%u: sets %u toggles %u unsets %u isnotsets %u issets %u", varname, i, - array[i].state_cnts[DETECT_FLOWBITS_CMD_SET], array[i].state_cnts[DETECT_FLOWBITS_CMD_TOGGLE], - array[i].state_cnts[DETECT_FLOWBITS_CMD_UNSET], array[i].state_cnts[DETECT_FLOWBITS_CMD_ISNOTSET], + SCLogDebug("STATE flowbit %s/%u: sets %u toggles %u unsets %u isnotsets %u issets %u", + varname, i, array[i].state_cnts[DETECT_FLOWBITS_CMD_SET], + array[i].state_cnts[DETECT_FLOWBITS_CMD_TOGGLE], + array[i].state_cnts[DETECT_FLOWBITS_CMD_UNSET], + array[i].state_cnts[DETECT_FLOWBITS_CMD_ISNOTSET], array[i].state_cnts[DETECT_FLOWBITS_CMD_ISSET]); for (uint32_t x = 0; x < array[i].set_sids_idx; x++) { SCLogDebug("SET flowbit %s/%u: SID %u", varname, i, @@ -633,7 +642,8 @@ int DetectFlowbitsAnalyze(DetectEngineCtx *de_ctx) if (to_state) { s->init_data->init_flags |= SIG_FLAG_INIT_STATE_MATCH; SCLogDebug("made SID %u stateful because it depends on " - "stateful rules that set flowbit %s", s->id, varname); + "stateful rules that set flowbit %s", + s->id, varname); } } } @@ -656,8 +666,8 @@ int DetectFlowbitsAnalyze(DetectEngineCtx *de_ctx) } SCMutex g_flowbits_dump_write_m = SCMUTEX_INITIALIZER; -static void DetectFlowbitsAnalyzeDump(const DetectEngineCtx *de_ctx, - struct FBAnalyze *array, uint32_t elements) +static void DetectFlowbitsAnalyzeDump( + const DetectEngineCtx *de_ctx, struct FBAnalyze *array, uint32_t elements) { JsonBuilder *js = jb_new_object(); if (js == NULL) @@ -754,37 +764,31 @@ static int FlowBitsTestParse01(void) char command[16] = "", name[16] = ""; /* Single argument version. */ - FAIL_IF(!DetectFlowbitParse("noalert", command, sizeof(command), name, - sizeof(name))); + FAIL_IF(!DetectFlowbitParse("noalert", command, sizeof(command), name, sizeof(name))); FAIL_IF(strcmp(command, "noalert") != 0); /* No leading or trailing spaces. */ - FAIL_IF(!DetectFlowbitParse("set,flowbit", command, sizeof(command), name, - sizeof(name))); + FAIL_IF(!DetectFlowbitParse("set,flowbit", command, sizeof(command), name, sizeof(name))); FAIL_IF(strcmp(command, "set") != 0); FAIL_IF(strcmp(name, "flowbit") != 0); /* Leading space. */ - FAIL_IF(!DetectFlowbitParse("set, flowbit", command, sizeof(command), name, - sizeof(name))); + FAIL_IF(!DetectFlowbitParse("set, flowbit", command, sizeof(command), name, sizeof(name))); FAIL_IF(strcmp(command, "set") != 0); FAIL_IF(strcmp(name, "flowbit") != 0); /* Trailing space. */ - FAIL_IF(!DetectFlowbitParse("set,flowbit ", command, sizeof(command), name, - sizeof(name))); + FAIL_IF(!DetectFlowbitParse("set,flowbit ", command, sizeof(command), name, sizeof(name))); FAIL_IF(strcmp(command, "set") != 0); FAIL_IF(strcmp(name, "flowbit") != 0); /* Leading and trailing space. */ - FAIL_IF(!DetectFlowbitParse("set, flowbit ", command, sizeof(command), name, - sizeof(name))); + FAIL_IF(!DetectFlowbitParse("set, flowbit ", command, sizeof(command), name, sizeof(name))); FAIL_IF(strcmp(command, "set") != 0); FAIL_IF(strcmp(name, "flowbit") != 0); /* Spaces are not allowed in the name. */ - FAIL_IF(DetectFlowbitParse("set,namewith space", command, sizeof(command), - name, sizeof(name))); + FAIL_IF(DetectFlowbitParse("set,namewith space", command, sizeof(command), name, sizeof(name))); PASS; } @@ -806,7 +810,9 @@ static int FlowBitsTestSig01(void) de_ctx->flags |= DE_QUIET; - s = de_ctx->sig_list = SigInit(de_ctx,"alert ip any any -> any any (msg:\"Noalert\"; flowbits:noalert,wrongusage; content:\"GET \"; sid:1;)"); + s = de_ctx->sig_list = + SigInit(de_ctx, "alert ip any any -> any any (msg:\"Noalert\"; " + "flowbits:noalert,wrongusage; content:\"GET \"; sid:1;)"); FAIL_IF_NOT_NULL(s); SigGroupBuild(de_ctx); @@ -834,22 +840,30 @@ static int FlowBitsTestSig02(void) de_ctx->flags |= DE_QUIET; - s = de_ctx->sig_list = SigInit(de_ctx,"alert ip any any -> any any (msg:\"isset rule need an option\"; flowbits:isset; content:\"GET \"; sid:1;)"); + s = de_ctx->sig_list = SigInit(de_ctx, "alert ip any any -> any any (msg:\"isset rule need an " + "option\"; flowbits:isset; content:\"GET \"; sid:1;)"); FAIL_IF_NOT_NULL(s); - s = de_ctx->sig_list = SigInit(de_ctx,"alert ip any any -> any any (msg:\"isnotset rule need an option\"; flowbits:isnotset; content:\"GET \"; sid:2;)"); + s = de_ctx->sig_list = + SigInit(de_ctx, "alert ip any any -> any any (msg:\"isnotset rule need an option\"; " + "flowbits:isnotset; content:\"GET \"; sid:2;)"); FAIL_IF_NOT_NULL(s); - s = de_ctx->sig_list = SigInit(de_ctx,"alert ip any any -> any any (msg:\"set rule need an option\"; flowbits:set; content:\"GET \"; sid:3;)"); + s = de_ctx->sig_list = SigInit(de_ctx, "alert ip any any -> any any (msg:\"set rule need an " + "option\"; flowbits:set; content:\"GET \"; sid:3;)"); FAIL_IF_NOT_NULL(s); - s = de_ctx->sig_list = SigInit(de_ctx,"alert ip any any -> any any (msg:\"unset rule need an option\"; flowbits:unset; content:\"GET \"; sid:4;)"); + s = de_ctx->sig_list = SigInit(de_ctx, "alert ip any any -> any any (msg:\"unset rule need an " + "option\"; flowbits:unset; content:\"GET \"; sid:4;)"); FAIL_IF_NOT_NULL(s); - s = de_ctx->sig_list = SigInit(de_ctx,"alert ip any any -> any any (msg:\"toggle rule need an option\"; flowbits:toggle; content:\"GET \"; sid:5;)"); + s = de_ctx->sig_list = SigInit(de_ctx, "alert ip any any -> any any (msg:\"toggle rule need an " + "option\"; flowbits:toggle; content:\"GET \"; sid:5;)"); FAIL_IF_NOT_NULL(s); - s = de_ctx->sig_list = SigInit(de_ctx,"alert ip any any -> any any (msg:\"!set is not an option\"; flowbits:!set,myerr; content:\"GET \"; sid:6;)"); + s = de_ctx->sig_list = + SigInit(de_ctx, "alert ip any any -> any any (msg:\"!set is not an option\"; " + "flowbits:!set,myerr; content:\"GET \"; sid:6;)"); FAIL_IF_NOT_NULL(s); SigGroupBuild(de_ctx); @@ -875,7 +889,8 @@ static int FlowBitsTestSig03(void) de_ctx->flags |= DE_QUIET; - s = de_ctx->sig_list = SigInit(de_ctx,"alert ip any any -> any any (msg:\"Unknown cmd\"; flowbits:wrongcmd; content:\"GET \"; sid:1;)"); + s = de_ctx->sig_list = SigInit(de_ctx, "alert ip any any -> any any (msg:\"Unknown cmd\"; " + "flowbits:wrongcmd; content:\"GET \"; sid:1;)"); FAIL_IF_NOT_NULL(s); SigGroupBuild(de_ctx); @@ -900,7 +915,8 @@ static int FlowBitsTestSig04(void) de_ctx->flags |= DE_QUIET; - s = de_ctx->sig_list = SigInit(de_ctx,"alert ip any any -> any any (msg:\"isset option\"; flowbits:isset,fbt; content:\"GET \"; sid:1;)"); + s = de_ctx->sig_list = SigInit(de_ctx, "alert ip any any -> any any (msg:\"isset option\"; " + "flowbits:isset,fbt; content:\"GET \"; sid:1;)"); FAIL_IF_NULL(s); idx = VarNameStoreRegister("fbt", VAR_TYPE_FLOW_BIT); @@ -928,7 +944,8 @@ static int FlowBitsTestSig05(void) de_ctx->flags |= DE_QUIET; - s = de_ctx->sig_list = SigInit(de_ctx,"alert ip any any -> any any (msg:\"Noalert\"; flowbits:noalert; content:\"GET \"; sid:1;)"); + s = de_ctx->sig_list = SigInit(de_ctx, "alert ip any any -> any any (msg:\"Noalert\"; " + "flowbits:noalert; content:\"GET \"; sid:1;)"); FAIL_IF_NULL(s); FAIL_IF((s->flags & SIG_FLAG_NOALERT) != SIG_FLAG_NOALERT); @@ -946,10 +963,9 @@ static int FlowBitsTestSig05(void) static int FlowBitsTestSig06(void) { - uint8_t *buf = (uint8_t *) - "GET /one/ HTTP/1.1\r\n" - "Host: one.example.org\r\n" - "\r\n"; + uint8_t *buf = (uint8_t *)"GET /one/ HTTP/1.1\r\n" + "Host: one.example.org\r\n" + "\r\n"; uint16_t buflen = strlen((char *)buf); Packet *p = PacketGetFromAlloc(); FAIL_IF_NULL(p); @@ -983,7 +999,8 @@ static int FlowBitsTestSig06(void) de_ctx->flags |= DE_QUIET; - s = de_ctx->sig_list = SigInit(de_ctx,"alert ip any any -> any any (msg:\"Flowbit set\"; flowbits:set,myflow; sid:10;)"); + s = de_ctx->sig_list = SigInit(de_ctx, + "alert ip any any -> any any (msg:\"Flowbit set\"; flowbits:set,myflow; sid:10;)"); FAIL_IF_NULL(s); idx = VarNameStoreRegister("myflow", VAR_TYPE_FLOW_BIT); @@ -994,9 +1011,9 @@ static int FlowBitsTestSig06(void) gv = p->flow->flowvar; FAIL_IF_NULL(gv); - for ( ; gv != NULL; gv = gv->next) { + for (; gv != NULL; gv = gv->next) { if (gv->type == DETECT_FLOWBITS && gv->idx == idx) { - result = 1; + result = 1; } } FAIL_IF_NOT(result); @@ -1019,10 +1036,9 @@ static int FlowBitsTestSig06(void) static int FlowBitsTestSig07(void) { - uint8_t *buf = (uint8_t *) - "GET /one/ HTTP/1.1\r\n" - "Host: one.example.org\r\n" - "\r\n"; + uint8_t *buf = (uint8_t *)"GET /one/ HTTP/1.1\r\n" + "Host: one.example.org\r\n" + "\r\n"; uint16_t buflen = strlen((char *)buf); Packet *p = PacketGetFromAlloc(); FAIL_IF_NULL(p); @@ -1054,10 +1070,12 @@ static int FlowBitsTestSig07(void) de_ctx->flags |= DE_QUIET; - s = de_ctx->sig_list = SigInit(de_ctx,"alert ip any any -> any any (msg:\"Flowbit set\"; flowbits:set,myflow2; sid:10;)"); + s = de_ctx->sig_list = SigInit(de_ctx, + "alert ip any any -> any any (msg:\"Flowbit set\"; flowbits:set,myflow2; sid:10;)"); FAIL_IF_NULL(s); - s = s->next = SigInit(de_ctx,"alert ip any any -> any any (msg:\"Flowbit unset\"; flowbits:unset,myflow2; sid:11;)"); + s = s->next = SigInit(de_ctx, + "alert ip any any -> any any (msg:\"Flowbit unset\"; flowbits:unset,myflow2; sid:11;)"); FAIL_IF_NULL(s); idx = VarNameStoreRegister("myflow", VAR_TYPE_FLOW_BIT); @@ -1069,9 +1087,9 @@ static int FlowBitsTestSig07(void) gv = p->flow->flowvar; FAIL_IF_NULL(gv); - for ( ; gv != NULL; gv = gv->next) { + for (; gv != NULL; gv = gv->next) { if (gv->type == DETECT_FLOWBITS && gv->idx == idx) { - result = 1; + result = 1; } } FAIL_IF(result); @@ -1094,10 +1112,9 @@ static int FlowBitsTestSig07(void) static int FlowBitsTestSig08(void) { - uint8_t *buf = (uint8_t *) - "GET /one/ HTTP/1.1\r\n" - "Host: one.example.org\r\n" - "\r\n"; + uint8_t *buf = (uint8_t *)"GET /one/ HTTP/1.1\r\n" + "Host: one.example.org\r\n" + "\r\n"; uint16_t buflen = strlen((char *)buf); Packet *p = PacketGetFromAlloc(); if (unlikely(p == NULL)) @@ -1130,10 +1147,12 @@ static int FlowBitsTestSig08(void) de_ctx->flags |= DE_QUIET; - s = de_ctx->sig_list = SigInit(de_ctx,"alert ip any any -> any any (msg:\"Flowbit set\"; flowbits:set,myflow2; sid:10;)"); + s = de_ctx->sig_list = SigInit(de_ctx, + "alert ip any any -> any any (msg:\"Flowbit set\"; flowbits:set,myflow2; sid:10;)"); FAIL_IF_NULL(s); - s = s->next = SigInit(de_ctx,"alert ip any any -> any any (msg:\"Flowbit unset\"; flowbits:toggle,myflow2; sid:11;)"); + s = s->next = SigInit(de_ctx, "alert ip any any -> any any (msg:\"Flowbit unset\"; " + "flowbits:toggle,myflow2; sid:11;)"); FAIL_IF_NULL(s); idx = VarNameStoreRegister("myflow", VAR_TYPE_FLOW_BIT); @@ -1145,9 +1164,9 @@ static int FlowBitsTestSig08(void) gv = p->flow->flowvar; FAIL_IF_NULL(gv); - for ( ; gv != NULL; gv = gv->next) { + for (; gv != NULL; gv = gv->next) { if (gv->type == DETECT_FLOWBITS && gv->idx == idx) { - result = 1; + result = 1; } } FAIL_IF(result); diff --git a/src/detect-flowbits.h b/src/detect-flowbits.h index 5ecd6cf87296..1f9b6d693a7c 100644 --- a/src/detect-flowbits.h +++ b/src/detect-flowbits.h @@ -41,7 +41,6 @@ typedef struct DetectFlowbitsData_ { } DetectFlowbitsData; /* prototypes */ -void DetectFlowbitsRegister (void); +void DetectFlowbitsRegister(void); #endif /* __DETECT_FLOWBITS_H__ */ - diff --git a/src/detect-flowint.c b/src/detect-flowint.c index 224eb650dc64..f396a5a1341f 100644 --- a/src/detect-flowint.c +++ b/src/detect-flowint.c @@ -48,13 +48,15 @@ #include "util-profiling.h" /* name modifiers value */ -#define PARSE_REGEX "^\\s*([a-zA-Z][\\w\\d_./]+)\\s*,\\s*([+=-]{1}|==|!=|<|<=|>|>=|isset|notset)\\s*,?\\s*([a-zA-Z][\\w\\d]+|[\\d]{1,10})?\\s*$" +#define PARSE_REGEX \ + "^\\s*([a-zA-Z][\\w\\d_./" \ + "]+)\\s*,\\s*([+=-]{1}|==|!=|<|<=|>|>=|isset|notset)\\s*,?\\s*([a-zA-Z][\\w\\d]+|[\\d]{1,10})" \ + "?\\s*$" /* Varnames must begin with a letter */ static DetectParseRegex parse_regex; -int DetectFlowintMatch(DetectEngineThreadCtx *, Packet *, - const Signature *, const SigMatchCtx *); +int DetectFlowintMatch(DetectEngineThreadCtx *, Packet *, const Signature *, const SigMatchCtx *); static int DetectFlowintSetup(DetectEngineCtx *, Signature *, const char *); void DetectFlowintFree(DetectEngineCtx *, void *); #ifdef UNITTESTS @@ -89,8 +91,8 @@ void DetectFlowintRegister(void) * \retval 1 match, when a var is initialized well, add/subtracted, or a true * condition */ -int DetectFlowintMatch(DetectEngineThreadCtx *det_ctx, - Packet *p, const Signature *s, const SigMatchCtx *ctx) +int DetectFlowintMatch( + DetectEngineThreadCtx *det_ctx, Packet *p, const Signature *s, const SigMatchCtx *ctx) { const DetectFlowintData *sfd = (const DetectFlowintData *)ctx; FlowVar *fv; @@ -113,7 +115,7 @@ int DetectFlowintMatch(DetectEngineThreadCtx *det_ctx, uint32_t tvar_idx = VarNameStoreLookupByName(sfd->target.tvar.name, VAR_TYPE_FLOW_INT); fvt = FlowVarGet(p->flow, tvar_idx); - /* We don't have that variable initialized yet */ + /* We don't have that variable initialized yet */ if (fvt == NULL) targetval = 0; else @@ -122,7 +124,7 @@ int DetectFlowintMatch(DetectEngineThreadCtx *det_ctx, targetval = sfd->target.value; } - SCLogDebug("Our var %s is at idx: %"PRIu32"", sfd->name, sfd->idx); + SCLogDebug("Our var %s is at idx: %" PRIu32 "", sfd->name, sfd->idx); if (sfd->modifier == FLOWINT_MODIFIER_SET) { FlowVarAddIntNoLock(p->flow, sfd->idx, targetval); @@ -134,14 +136,14 @@ int DetectFlowintMatch(DetectEngineThreadCtx *det_ctx, fv = FlowVarGet(p->flow, sfd->idx); if (sfd->modifier == FLOWINT_MODIFIER_ISSET) { - SCLogDebug(" Isset %s? = %u", sfd->name,(fv) ? 1 : 0); + SCLogDebug(" Isset %s? = %u", sfd->name, (fv) ? 1 : 0); if (fv != NULL) ret = 1; goto end; } if (sfd->modifier == FLOWINT_MODIFIER_NOTSET) { - SCLogDebug(" Not set %s? = %u", sfd->name,(fv) ? 0 : 1); + SCLogDebug(" Not set %s? = %u", sfd->name, (fv) ? 0 : 1); if (fv == NULL) ret = 1; goto end; @@ -150,21 +152,19 @@ int DetectFlowintMatch(DetectEngineThreadCtx *det_ctx, if (fv != NULL && fv->datatype == FLOWVAR_TYPE_INT) { if (sfd->modifier == FLOWINT_MODIFIER_ADD) { SCLogDebug("Adding %u to %s", targetval, sfd->name); - FlowVarAddIntNoLock(p->flow, sfd->idx, fv->data.fv_int.value + - targetval); + FlowVarAddIntNoLock(p->flow, sfd->idx, fv->data.fv_int.value + targetval); ret = 1; goto end; } if (sfd->modifier == FLOWINT_MODIFIER_SUB) { SCLogDebug("Subtracting %u to %s", targetval, sfd->name); - FlowVarAddIntNoLock(p->flow, sfd->idx, fv->data.fv_int.value - - targetval); + FlowVarAddIntNoLock(p->flow, sfd->idx, fv->data.fv_int.value - targetval); ret = 1; goto end; } - switch(sfd->modifier) { + switch (sfd->modifier) { case FLOWINT_MODIFIER_EQ: SCLogDebug("( %u EQ %u )", fv->data.fv_int.value, targetval); ret = (fv->data.fv_int.value == targetval); @@ -309,10 +309,11 @@ static DetectFlowintData *DetectFlowintParse(DetectEngineCtx *de_ctx, const char value_long = atoll(varval); if (value_long > UINT32_MAX) { SCLogDebug("DetectFlowintParse: Cannot load this value." - " Values should be between 0 and %"PRIu32, UINT32_MAX); + " Values should be between 0 and %" PRIu32, + UINT32_MAX); goto error; } - sfd->target.value = (uint32_t) value_long; + sfd->target.value = (uint32_t)value_long; } else { sfd->targettype = FLOWINT_TARGET_VAR; sfd->target.tvar.name = SCStrdup(varval); @@ -417,7 +418,7 @@ static int DetectFlowintSetup(DetectEngineCtx *de_ctx, Signature *s, const char */ void DetectFlowintFree(DetectEngineCtx *de_ctx, void *tmp) { - DetectFlowintData *sfd =(DetectFlowintData*) tmp; + DetectFlowintData *sfd = (DetectFlowintData *)tmp; if (sfd != NULL) { VarNameStoreUnregister(sfd->idx, VAR_TYPE_FLOW_INT); if (sfd->name != NULL) @@ -441,17 +442,16 @@ static void DetectFlowintPrintData(DetectFlowintData *sfd) return; } - SCLogDebug("Varname: %s, modifier: %"PRIu8", idx: %"PRIu32" Target: ", - sfd->name, sfd->modifier, sfd->idx); - switch(sfd->targettype) { + SCLogDebug("Varname: %s, modifier: %" PRIu8 ", idx: %" PRIu32 " Target: ", sfd->name, + sfd->modifier, sfd->idx); + switch (sfd->targettype) { case FLOWINT_TARGET_VAR: - SCLogDebug("target_var: %s", - sfd->target.tvar.name); + SCLogDebug("target_var: %s", sfd->target.tvar.name); break; case FLOWINT_TARGET_VAL: - SCLogDebug("Value: %"PRIu32"; ", sfd->target.value); + SCLogDebug("Value: %" PRIu32 "; ", sfd->target.value); break; - default : + default: SCLogDebug("DetectFlowintPrintData: Error, Targettype not known!"); } } @@ -472,11 +472,12 @@ static int DetectFlowintTestParseVal01(void) sfd = DetectFlowintParse(de_ctx, "myvar,=,35"); DetectFlowintPrintData(sfd); - if (sfd != NULL && sfd->target.value == 35 && !strcmp(sfd->name, "myvar") - && sfd->modifier == FLOWINT_MODIFIER_SET) { + if (sfd != NULL && sfd->target.value == 35 && !strcmp(sfd->name, "myvar") && + sfd->modifier == FLOWINT_MODIFIER_SET) { result = 1; } - if (sfd) DetectFlowintFree(NULL, sfd); + if (sfd) + DetectFlowintFree(NULL, sfd); DetectEngineCtxFree(de_ctx); @@ -499,15 +500,14 @@ static int DetectFlowintTestParseVar01(void) sfd = DetectFlowintParse(de_ctx, "myvar,=,targetvar"); DetectFlowintPrintData(sfd); - if (sfd != NULL && !strcmp(sfd->name, "myvar") - && sfd->targettype == FLOWINT_TARGET_VAR - && sfd->target.tvar.name != NULL - && !strcmp(sfd->target.tvar.name, "targetvar") - && sfd->modifier == FLOWINT_MODIFIER_SET) { + if (sfd != NULL && !strcmp(sfd->name, "myvar") && sfd->targettype == FLOWINT_TARGET_VAR && + sfd->target.tvar.name != NULL && !strcmp(sfd->target.tvar.name, "targetvar") && + sfd->modifier == FLOWINT_MODIFIER_SET) { result = 1; } - if (sfd) DetectFlowintFree(NULL, sfd); + if (sfd) + DetectFlowintFree(NULL, sfd); DetectEngineCtxFree(de_ctx); return result; @@ -529,11 +529,12 @@ static int DetectFlowintTestParseVal02(void) sfd = DetectFlowintParse(de_ctx, "myvar,+,35"); DetectFlowintPrintData(sfd); - if (sfd != NULL && sfd->target.value == 35 && !strcmp(sfd->name, "myvar") - && sfd->modifier == FLOWINT_MODIFIER_ADD) { + if (sfd != NULL && sfd->target.value == 35 && !strcmp(sfd->name, "myvar") && + sfd->modifier == FLOWINT_MODIFIER_ADD) { result = 1; } - if (sfd) DetectFlowintFree(NULL, sfd); + if (sfd) + DetectFlowintFree(NULL, sfd); DetectEngineCtxFree(de_ctx); @@ -556,15 +557,14 @@ static int DetectFlowintTestParseVar02(void) sfd = DetectFlowintParse(de_ctx, "myvar,+,targetvar"); DetectFlowintPrintData(sfd); - if (sfd != NULL && !strcmp(sfd->name, "myvar") - && sfd->targettype == FLOWINT_TARGET_VAR - && sfd->target.tvar.name != NULL - && !strcmp(sfd->target.tvar.name, "targetvar") - && sfd->modifier == FLOWINT_MODIFIER_ADD) { + if (sfd != NULL && !strcmp(sfd->name, "myvar") && sfd->targettype == FLOWINT_TARGET_VAR && + sfd->target.tvar.name != NULL && !strcmp(sfd->target.tvar.name, "targetvar") && + sfd->modifier == FLOWINT_MODIFIER_ADD) { result = 1; } - if (sfd) DetectFlowintFree(NULL, sfd); + if (sfd) + DetectFlowintFree(NULL, sfd); DetectEngineCtxFree(de_ctx); return result; @@ -586,11 +586,12 @@ static int DetectFlowintTestParseVal03(void) sfd = DetectFlowintParse(de_ctx, "myvar,-,35"); DetectFlowintPrintData(sfd); - if (sfd != NULL && sfd->target.value == 35 && !strcmp(sfd->name, "myvar") - && sfd->modifier == FLOWINT_MODIFIER_SUB) { + if (sfd != NULL && sfd->target.value == 35 && !strcmp(sfd->name, "myvar") && + sfd->modifier == FLOWINT_MODIFIER_SUB) { result = 1; } - if (sfd) DetectFlowintFree(NULL, sfd); + if (sfd) + DetectFlowintFree(NULL, sfd); DetectEngineCtxFree(de_ctx); @@ -613,21 +614,19 @@ static int DetectFlowintTestParseVar03(void) sfd = DetectFlowintParse(de_ctx, "myvar,-,targetvar"); DetectFlowintPrintData(sfd); - if (sfd != NULL && !strcmp(sfd->name, "myvar") - && sfd->targettype == FLOWINT_TARGET_VAR - && sfd->target.tvar.name != NULL - && !strcmp(sfd->target.tvar.name, "targetvar") - && sfd->modifier == FLOWINT_MODIFIER_SUB) { + if (sfd != NULL && !strcmp(sfd->name, "myvar") && sfd->targettype == FLOWINT_TARGET_VAR && + sfd->target.tvar.name != NULL && !strcmp(sfd->target.tvar.name, "targetvar") && + sfd->modifier == FLOWINT_MODIFIER_SUB) { result = 1; } - if (sfd) DetectFlowintFree(NULL, sfd); + if (sfd) + DetectFlowintFree(NULL, sfd); DetectEngineCtxFree(de_ctx); return result; } - /** * \test DetectFlowintTestParseVal04 is a test to make sure that we set the * DetectFlowint correctly for checking if equal to a valid target value @@ -644,11 +643,12 @@ static int DetectFlowintTestParseVal04(void) sfd = DetectFlowintParse(de_ctx, "myvar,==,35"); DetectFlowintPrintData(sfd); - if (sfd != NULL && sfd->target.value == 35 && !strcmp(sfd->name, "myvar") - && sfd->modifier == FLOWINT_MODIFIER_EQ) { + if (sfd != NULL && sfd->target.value == 35 && !strcmp(sfd->name, "myvar") && + sfd->modifier == FLOWINT_MODIFIER_EQ) { result = 1; } - if (sfd) DetectFlowintFree(NULL, sfd); + if (sfd) + DetectFlowintFree(NULL, sfd); DetectEngineCtxFree(de_ctx); @@ -671,15 +671,14 @@ static int DetectFlowintTestParseVar04(void) sfd = DetectFlowintParse(de_ctx, "myvar,==,targetvar"); DetectFlowintPrintData(sfd); - if (sfd != NULL && !strcmp(sfd->name, "myvar") - && sfd->targettype == FLOWINT_TARGET_VAR - && sfd->target.tvar.name != NULL - && !strcmp(sfd->target.tvar.name, "targetvar") - && sfd->modifier == FLOWINT_MODIFIER_EQ) { + if (sfd != NULL && !strcmp(sfd->name, "myvar") && sfd->targettype == FLOWINT_TARGET_VAR && + sfd->target.tvar.name != NULL && !strcmp(sfd->target.tvar.name, "targetvar") && + sfd->modifier == FLOWINT_MODIFIER_EQ) { result = 1; } - if (sfd) DetectFlowintFree(NULL, sfd); + if (sfd) + DetectFlowintFree(NULL, sfd); DetectEngineCtxFree(de_ctx); return result; @@ -701,11 +700,12 @@ static int DetectFlowintTestParseVal05(void) sfd = DetectFlowintParse(de_ctx, "myvar,!=,35"); DetectFlowintPrintData(sfd); - if (sfd != NULL && sfd->target.value == 35 && !strcmp(sfd->name, "myvar") - && sfd->modifier == FLOWINT_MODIFIER_NE) { + if (sfd != NULL && sfd->target.value == 35 && !strcmp(sfd->name, "myvar") && + sfd->modifier == FLOWINT_MODIFIER_NE) { result = 1; } - if (sfd) DetectFlowintFree(NULL, sfd); + if (sfd) + DetectFlowintFree(NULL, sfd); DetectEngineCtxFree(de_ctx); @@ -728,15 +728,14 @@ static int DetectFlowintTestParseVar05(void) sfd = DetectFlowintParse(de_ctx, "myvar,!=,targetvar"); DetectFlowintPrintData(sfd); - if (sfd != NULL && !strcmp(sfd->name, "myvar") - && sfd->targettype == FLOWINT_TARGET_VAR - && sfd->target.tvar.name != NULL - && !strcmp(sfd->target.tvar.name, "targetvar") - && sfd->modifier == FLOWINT_MODIFIER_NE) { + if (sfd != NULL && !strcmp(sfd->name, "myvar") && sfd->targettype == FLOWINT_TARGET_VAR && + sfd->target.tvar.name != NULL && !strcmp(sfd->target.tvar.name, "targetvar") && + sfd->modifier == FLOWINT_MODIFIER_NE) { result = 1; } - if (sfd) DetectFlowintFree(NULL, sfd); + if (sfd) + DetectFlowintFree(NULL, sfd); DetectEngineCtxFree(de_ctx); return result; @@ -758,11 +757,12 @@ static int DetectFlowintTestParseVal06(void) sfd = DetectFlowintParse(de_ctx, "myvar, >,35"); DetectFlowintPrintData(sfd); - if (sfd != NULL && sfd->target.value == 35 && !strcmp(sfd->name, "myvar") - && sfd->modifier == FLOWINT_MODIFIER_GT) { + if (sfd != NULL && sfd->target.value == 35 && !strcmp(sfd->name, "myvar") && + sfd->modifier == FLOWINT_MODIFIER_GT) { result = 1; } - if (sfd) DetectFlowintFree(NULL, sfd); + if (sfd) + DetectFlowintFree(NULL, sfd); DetectEngineCtxFree(de_ctx); @@ -785,15 +785,14 @@ static int DetectFlowintTestParseVar06(void) sfd = DetectFlowintParse(de_ctx, "myvar, >,targetvar"); DetectFlowintPrintData(sfd); - if (sfd != NULL && !strcmp(sfd->name, "myvar") - && sfd->targettype == FLOWINT_TARGET_VAR - && sfd->target.tvar.name != NULL - && !strcmp(sfd->target.tvar.name, "targetvar") - && sfd->modifier == FLOWINT_MODIFIER_GT) { + if (sfd != NULL && !strcmp(sfd->name, "myvar") && sfd->targettype == FLOWINT_TARGET_VAR && + sfd->target.tvar.name != NULL && !strcmp(sfd->target.tvar.name, "targetvar") && + sfd->modifier == FLOWINT_MODIFIER_GT) { result = 1; } - if (sfd) DetectFlowintFree(NULL, sfd); + if (sfd) + DetectFlowintFree(NULL, sfd); DetectEngineCtxFree(de_ctx); return result; @@ -815,11 +814,12 @@ static int DetectFlowintTestParseVal07(void) sfd = DetectFlowintParse(de_ctx, "myvar, >= ,35"); DetectFlowintPrintData(sfd); - if (sfd != NULL && sfd->target.value == 35 && !strcmp(sfd->name, "myvar") - && sfd->modifier == FLOWINT_MODIFIER_GE) { + if (sfd != NULL && sfd->target.value == 35 && !strcmp(sfd->name, "myvar") && + sfd->modifier == FLOWINT_MODIFIER_GE) { result = 1; } - if (sfd) DetectFlowintFree(NULL, sfd); + if (sfd) + DetectFlowintFree(NULL, sfd); DetectEngineCtxFree(de_ctx); @@ -842,15 +842,14 @@ static int DetectFlowintTestParseVar07(void) sfd = DetectFlowintParse(de_ctx, "myvar, >= ,targetvar"); DetectFlowintPrintData(sfd); - if (sfd != NULL && !strcmp(sfd->name, "myvar") - && sfd->targettype == FLOWINT_TARGET_VAR - && sfd->target.tvar.name != NULL - && !strcmp(sfd->target.tvar.name, "targetvar") - && sfd->modifier == FLOWINT_MODIFIER_GE) { + if (sfd != NULL && !strcmp(sfd->name, "myvar") && sfd->targettype == FLOWINT_TARGET_VAR && + sfd->target.tvar.name != NULL && !strcmp(sfd->target.tvar.name, "targetvar") && + sfd->modifier == FLOWINT_MODIFIER_GE) { result = 1; } - if (sfd) DetectFlowintFree(NULL, sfd); + if (sfd) + DetectFlowintFree(NULL, sfd); DetectEngineCtxFree(de_ctx); return result; @@ -872,11 +871,12 @@ static int DetectFlowintTestParseVal08(void) sfd = DetectFlowintParse(de_ctx, "myvar, <= ,35"); DetectFlowintPrintData(sfd); - if (sfd != NULL && sfd->target.value == 35 && !strcmp(sfd->name, "myvar") - && sfd->modifier == FLOWINT_MODIFIER_LE) { + if (sfd != NULL && sfd->target.value == 35 && !strcmp(sfd->name, "myvar") && + sfd->modifier == FLOWINT_MODIFIER_LE) { result = 1; } - if (sfd) DetectFlowintFree(NULL, sfd); + if (sfd) + DetectFlowintFree(NULL, sfd); DetectEngineCtxFree(de_ctx); @@ -899,15 +899,14 @@ static int DetectFlowintTestParseVar08(void) sfd = DetectFlowintParse(de_ctx, "myvar, <= ,targetvar"); DetectFlowintPrintData(sfd); - if (sfd != NULL && !strcmp(sfd->name, "myvar") - && sfd->targettype == FLOWINT_TARGET_VAR - && sfd->target.tvar.name != NULL - && !strcmp(sfd->target.tvar.name, "targetvar") - && sfd->modifier == FLOWINT_MODIFIER_LE) { + if (sfd != NULL && !strcmp(sfd->name, "myvar") && sfd->targettype == FLOWINT_TARGET_VAR && + sfd->target.tvar.name != NULL && !strcmp(sfd->target.tvar.name, "targetvar") && + sfd->modifier == FLOWINT_MODIFIER_LE) { result = 1; } - if (sfd) DetectFlowintFree(NULL, sfd); + if (sfd) + DetectFlowintFree(NULL, sfd); DetectEngineCtxFree(de_ctx); return result; @@ -929,11 +928,12 @@ static int DetectFlowintTestParseVal09(void) sfd = DetectFlowintParse(de_ctx, "myvar, < ,35"); DetectFlowintPrintData(sfd); - if (sfd != NULL && sfd->target.value == 35 && !strcmp(sfd->name, "myvar") - && sfd->modifier == FLOWINT_MODIFIER_LT) { + if (sfd != NULL && sfd->target.value == 35 && !strcmp(sfd->name, "myvar") && + sfd->modifier == FLOWINT_MODIFIER_LT) { result = 1; } - if (sfd) DetectFlowintFree(NULL, sfd); + if (sfd) + DetectFlowintFree(NULL, sfd); DetectEngineCtxFree(de_ctx); @@ -956,15 +956,14 @@ static int DetectFlowintTestParseVar09(void) sfd = DetectFlowintParse(de_ctx, "myvar, < ,targetvar"); DetectFlowintPrintData(sfd); - if (sfd != NULL && !strcmp(sfd->name, "myvar") - && sfd->targettype == FLOWINT_TARGET_VAR - && sfd->target.tvar.name != NULL - && !strcmp(sfd->target.tvar.name, "targetvar") - && sfd->modifier == FLOWINT_MODIFIER_LT) { + if (sfd != NULL && !strcmp(sfd->name, "myvar") && sfd->targettype == FLOWINT_TARGET_VAR && + sfd->target.tvar.name != NULL && !strcmp(sfd->target.tvar.name, "targetvar") && + sfd->modifier == FLOWINT_MODIFIER_LT) { result = 1; } - if (sfd) DetectFlowintFree(NULL, sfd); + if (sfd) + DetectFlowintFree(NULL, sfd); DetectEngineCtxFree(de_ctx); return result; @@ -986,28 +985,28 @@ static int DetectFlowintTestParseIsset10(void) sfd = DetectFlowintParse(de_ctx, "myvar, isset"); DetectFlowintPrintData(sfd); - if (sfd != NULL && !strcmp(sfd->name, "myvar") - && sfd->targettype == FLOWINT_TARGET_SELF - && sfd->modifier == FLOWINT_MODIFIER_ISSET) { + if (sfd != NULL && !strcmp(sfd->name, "myvar") && sfd->targettype == FLOWINT_TARGET_SELF && + sfd->modifier == FLOWINT_MODIFIER_ISSET) { result &= 1; } else { result = 0; } - if (sfd) DetectFlowintFree(NULL, sfd); + if (sfd) + DetectFlowintFree(NULL, sfd); sfd = DetectFlowintParse(de_ctx, "myvar, notset"); DetectFlowintPrintData(sfd); - if (sfd != NULL && !strcmp(sfd->name, "myvar") - && sfd->targettype == FLOWINT_TARGET_SELF - && sfd->modifier == FLOWINT_MODIFIER_NOTSET) { + if (sfd != NULL && !strcmp(sfd->name, "myvar") && sfd->targettype == FLOWINT_TARGET_SELF && + sfd->modifier == FLOWINT_MODIFIER_NOTSET) { result &= 1; } else { result = 0; } - if (sfd) DetectFlowintFree(NULL, sfd); + if (sfd) + DetectFlowintFree(NULL, sfd); DetectEngineCtxFree(de_ctx); return result; @@ -1029,59 +1028,72 @@ static int DetectFlowintTestParseInvalidSyntaxis01(void) sfd = DetectFlowintParse(de_ctx, "myvar,=,9999999999"); if (sfd != NULL) { - SCLogDebug("DetectFlowintTestParseInvalidSyntaxis01: ERROR: invalid option at myvar,=,9532458716234857"); + SCLogDebug("DetectFlowintTestParseInvalidSyntaxis01: ERROR: invalid option at " + "myvar,=,9532458716234857"); result = 0; } - if (sfd) DetectFlowintFree(NULL, sfd); + if (sfd) + DetectFlowintFree(NULL, sfd); sfd = DetectFlowintParse(de_ctx, "myvar,=,45targetvar"); if (sfd != NULL) { - SCLogDebug("DetectFlowintTestParseInvalidSyntaxis01: ERROR: invalid option at myvar,=,45targetvar "); + SCLogDebug("DetectFlowintTestParseInvalidSyntaxis01: ERROR: invalid option at " + "myvar,=,45targetvar "); result = 0; } - if (sfd) DetectFlowintFree(NULL, sfd); + if (sfd) + DetectFlowintFree(NULL, sfd); sfd = DetectFlowintParse(de_ctx, "657myvar,=,targetvar"); if (sfd != NULL) { - SCLogDebug("DetectFlowintTestParseInvalidSyntaxis01: ERROR: invalid option at 657myvar,=,targetvar "); + SCLogDebug("DetectFlowintTestParseInvalidSyntaxis01: ERROR: invalid option at " + "657myvar,=,targetvar "); result = 0; } - if (sfd) DetectFlowintFree(NULL, sfd); + if (sfd) + DetectFlowintFree(NULL, sfd); sfd = DetectFlowintParse(de_ctx, "myvar,=<,targetvar"); if (sfd != NULL) { - SCLogDebug("DetectFlowintTestParseInvalidSyntaxis01: ERROR: invalid option at myvar,=<,targetvar "); + SCLogDebug("DetectFlowintTestParseInvalidSyntaxis01: ERROR: invalid option at " + "myvar,=<,targetvar "); result = 0; } - if (sfd) DetectFlowintFree(NULL, sfd); + if (sfd) + DetectFlowintFree(NULL, sfd); sfd = DetectFlowintParse(de_ctx, "myvar,===,targetvar"); if (sfd != NULL) { - SCLogDebug("DetectFlowintTestParseInvalidSyntaxis01: ERROR: invalid option at myvar,===,targetvar "); + SCLogDebug("DetectFlowintTestParseInvalidSyntaxis01: ERROR: invalid option at " + "myvar,===,targetvar "); result = 0; } - if (sfd) DetectFlowintFree(NULL, sfd); + if (sfd) + DetectFlowintFree(NULL, sfd); sfd = DetectFlowintParse(de_ctx, "myvar,=="); if (sfd != NULL) { SCLogDebug("DetectFlowintTestParseInvalidSyntaxis01: ERROR: invalid option at myvar,=="); result = 0; } - if (sfd) DetectFlowintFree(NULL, sfd); + if (sfd) + DetectFlowintFree(NULL, sfd); sfd = DetectFlowintParse(de_ctx, "myvar,"); if (sfd != NULL) { SCLogDebug("DetectFlowintTestParseInvalidSyntaxis01: ERROR: invalid option at myvar,"); result = 0; } - if (sfd) DetectFlowintFree(NULL, sfd); + if (sfd) + DetectFlowintFree(NULL, sfd); sfd = DetectFlowintParse(de_ctx, "myvar"); if (sfd != NULL) { SCLogDebug("DetectFlowintTestParseInvalidSyntaxis01: ERROR: invalid option at myvar"); result = 0; } - if (sfd) DetectFlowintFree(NULL, sfd); + if (sfd) + DetectFlowintFree(NULL, sfd); DetectEngineCtxFree(de_ctx); @@ -1116,21 +1128,27 @@ static int DetectFlowintTestPacket01Real(void) de_ctx->flags |= DE_QUIET; const char *sigs[5]; - sigs[0] = "alert tcp any any -> any any (msg:\"Setting a flowint counter\"; content:\"GET\"; flowint:myvar,=,1; flowint:maxvar,=,6; sid:101;)"; - sigs[1] = "alert tcp any any -> any any (msg:\"Adding to flowint counter\"; content:\"Unauthorized\"; flowint: myvar,+,2; sid:102;)"; - sigs[2] = "alert tcp any any -> any any (msg:\"if the flowint counter is 3 create a new counter\"; content:\"Unauthorized\"; flowint: myvar,==,3; flowint: cntpackets, =, 0; sid:103;)"; - sigs[3] = "alert tcp any any -> any any (msg:\"and count the rest of the packets received without generating alerts!!!\"; flowint: myvar,==,3; flowint: cntpackets, +, 1; noalert;sid:104;)"; - sigs[4] = "alert tcp any any -> any any (msg:\" and fire this when it reach 6\"; flowint: cntpackets, ==, maxvar; sid:105;)"; + sigs[0] = "alert tcp any any -> any any (msg:\"Setting a flowint counter\"; content:\"GET\"; " + "flowint:myvar,=,1; flowint:maxvar,=,6; sid:101;)"; + sigs[1] = "alert tcp any any -> any any (msg:\"Adding to flowint counter\"; " + "content:\"Unauthorized\"; flowint: myvar,+,2; sid:102;)"; + sigs[2] = "alert tcp any any -> any any (msg:\"if the flowint counter is 3 create a new " + "counter\"; content:\"Unauthorized\"; flowint: myvar,==,3; flowint: cntpackets, =, " + "0; sid:103;)"; + sigs[3] = "alert tcp any any -> any any (msg:\"and count the rest of the packets received " + "without generating alerts!!!\"; flowint: myvar,==,3; flowint: cntpackets, +, 1; " + "noalert;sid:104;)"; + sigs[4] = "alert tcp any any -> any any (msg:\" and fire this when it reach 6\"; flowint: " + "cntpackets, ==, maxvar; sid:105;)"; FAIL_IF(UTHAppendSigs(de_ctx, sigs, 5) == 0); SCSigRegisterSignatureOrderingFuncs(de_ctx); SCSigOrderSignatures(de_ctx); SCSigSignatureOrderingModuleCleanup(de_ctx); SigGroupBuild(de_ctx); - DetectEngineThreadCtxInit(&th_v,(void *) de_ctx,(void *) &det_ctx); + DetectEngineThreadCtxInit(&th_v, (void *)de_ctx, (void *)&det_ctx); - Flow *f = UTHBuildFlow(AF_INET, "192.168.1.5", "192.168.1.1", - 41424, 80); + Flow *f = UTHBuildFlow(AF_INET, "192.168.1.5", "192.168.1.1", 41424, 80); FAIL_IF(f == NULL); f->proto = IPPROTO_TCP; @@ -1166,7 +1184,7 @@ static int DetectFlowintTestPacket01Real(void) UTHFreePacket(p); UTHFreeFlow(f); - DetectEngineThreadCtxDeinit(&th_v,(void *) det_ctx); + DetectEngineThreadCtxDeinit(&th_v, (void *)det_ctx); DetectEngineCtxFree(de_ctx); PASS; @@ -1189,21 +1207,29 @@ static int DetectFlowintTestPacket02Real(void) de_ctx->flags |= DE_QUIET; const char *sigs[5]; - sigs[0] = "alert tcp any any -> any any (msg:\"Setting a flowint counter\"; content:\"GET\"; flowint: myvar, notset; flowint:maxvar,notset; flowint: myvar,=,1; flowint: maxvar,=,6; sid:101;)"; - sigs[1] = "alert tcp any any -> any any (msg:\"Adding to flowint counter\"; content:\"Unauthorized\"; flowint:myvar,isset; flowint: myvar,+,2; sid:102;)"; - sigs[2] = "alert tcp any any -> any any (msg:\"if the flowint counter is 3 create a new counter\"; content:\"Unauthorized\"; flowint: myvar, isset; flowint: myvar,==,3; flowint:cntpackets,notset; flowint: cntpackets, =, 0; sid:103;)"; - sigs[3] = "alert tcp any any -> any any (msg:\"and count the rest of the packets received without generating alerts!!!\"; flowint: cntpackets,isset; flowint: cntpackets, +, 1; noalert;sid:104;)"; - sigs[4] = "alert tcp any any -> any any (msg:\" and fire this when it reach 6\"; flowint: cntpackets, isset; flowint: maxvar,isset; flowint: cntpackets, ==, maxvar; sid:105;)"; + sigs[0] = "alert tcp any any -> any any (msg:\"Setting a flowint counter\"; content:\"GET\"; " + "flowint: myvar, notset; flowint:maxvar,notset; flowint: myvar,=,1; flowint: " + "maxvar,=,6; sid:101;)"; + sigs[1] = "alert tcp any any -> any any (msg:\"Adding to flowint counter\"; " + "content:\"Unauthorized\"; flowint:myvar,isset; flowint: myvar,+,2; sid:102;)"; + sigs[2] = "alert tcp any any -> any any (msg:\"if the flowint counter is 3 create a new " + "counter\"; content:\"Unauthorized\"; flowint: myvar, isset; flowint: myvar,==,3; " + "flowint:cntpackets,notset; flowint: cntpackets, =, 0; sid:103;)"; + sigs[3] = "alert tcp any any -> any any (msg:\"and count the rest of the packets received " + "without generating alerts!!!\"; flowint: cntpackets,isset; flowint: cntpackets, +, " + "1; noalert;sid:104;)"; + sigs[4] = + "alert tcp any any -> any any (msg:\" and fire this when it reach 6\"; flowint: " + "cntpackets, isset; flowint: maxvar,isset; flowint: cntpackets, ==, maxvar; sid:105;)"; FAIL_IF(UTHAppendSigs(de_ctx, sigs, 5) == 0); SCSigRegisterSignatureOrderingFuncs(de_ctx); SCSigOrderSignatures(de_ctx); SCSigSignatureOrderingModuleCleanup(de_ctx); SigGroupBuild(de_ctx); - DetectEngineThreadCtxInit(&th_v,(void *) de_ctx,(void *) &det_ctx); + DetectEngineThreadCtxInit(&th_v, (void *)de_ctx, (void *)&det_ctx); - Flow *f = UTHBuildFlow(AF_INET, "192.168.1.5", "192.168.1.1", - 41424, 80); + Flow *f = UTHBuildFlow(AF_INET, "192.168.1.5", "192.168.1.1", 41424, 80); FAIL_IF(f == NULL); f->proto = IPPROTO_TCP; @@ -1239,7 +1265,7 @@ static int DetectFlowintTestPacket02Real(void) UTHFreePacket(p); UTHFreeFlow(f); - DetectEngineThreadCtxDeinit(&th_v,(void *) det_ctx); + DetectEngineThreadCtxDeinit(&th_v, (void *)det_ctx); DetectEngineCtxFree(de_ctx); PASS; @@ -1262,19 +1288,21 @@ static int DetectFlowintTestPacket03Real(void) de_ctx->flags |= DE_QUIET; const char *sigs[3]; - sigs[0] = "alert tcp any any -> any any (msg:\"check notset\"; content:\"GET\"; flowint: myvar, notset; flowint: myvar,=,0; flowint: other,=,10; sid:101;)"; - sigs[1] = "alert tcp any any -> any any (msg:\"check isset\"; content:\"Unauthorized\"; flowint:myvar,isset; flowint: other,isset; sid:102;)"; - sigs[2] = "alert tcp any any -> any any (msg:\"check notset\"; content:\"Unauthorized\"; flowint:lala,isset; sid:103;)"; + sigs[0] = "alert tcp any any -> any any (msg:\"check notset\"; content:\"GET\"; flowint: " + "myvar, notset; flowint: myvar,=,0; flowint: other,=,10; sid:101;)"; + sigs[1] = "alert tcp any any -> any any (msg:\"check isset\"; content:\"Unauthorized\"; " + "flowint:myvar,isset; flowint: other,isset; sid:102;)"; + sigs[2] = "alert tcp any any -> any any (msg:\"check notset\"; content:\"Unauthorized\"; " + "flowint:lala,isset; sid:103;)"; FAIL_IF(UTHAppendSigs(de_ctx, sigs, 3) == 0); SCSigRegisterSignatureOrderingFuncs(de_ctx); SCSigOrderSignatures(de_ctx); SCSigSignatureOrderingModuleCleanup(de_ctx); SigGroupBuild(de_ctx); - DetectEngineThreadCtxInit(&th_v,(void *) de_ctx,(void *) &det_ctx); + DetectEngineThreadCtxInit(&th_v, (void *)de_ctx, (void *)&det_ctx); - Flow *f = UTHBuildFlow(AF_INET, "192.168.1.5", "192.168.1.1", - 41424, 80); + Flow *f = UTHBuildFlow(AF_INET, "192.168.1.5", "192.168.1.1", 41424, 80); FAIL_IF(f == NULL); f->proto = IPPROTO_TCP; @@ -1302,7 +1330,7 @@ static int DetectFlowintTestPacket03Real(void) UTHFreePacket(p); UTHFreeFlow(f); - DetectEngineThreadCtxDeinit(&th_v,(void *) det_ctx); + DetectEngineThreadCtxDeinit(&th_v, (void *)det_ctx); DetectEngineCtxFree(de_ctx); PASS; @@ -1331,15 +1359,11 @@ void DetectFlowintRegisterTests(void) UtRegisterTest("DetectFlowintTestParseVar08", DetectFlowintTestParseVar08); UtRegisterTest("DetectFlowintTestParseVal09", DetectFlowintTestParseVal09); UtRegisterTest("DetectFlowintTestParseVar09", DetectFlowintTestParseVar09); - UtRegisterTest("DetectFlowintTestParseIsset10", - DetectFlowintTestParseIsset10); - UtRegisterTest("DetectFlowintTestParseInvalidSyntaxis01", - DetectFlowintTestParseInvalidSyntaxis01); - UtRegisterTest("DetectFlowintTestPacket01Real", - DetectFlowintTestPacket01Real); - UtRegisterTest("DetectFlowintTestPacket02Real", - DetectFlowintTestPacket02Real); - UtRegisterTest("DetectFlowintTestPacket03Real", - DetectFlowintTestPacket03Real); + UtRegisterTest("DetectFlowintTestParseIsset10", DetectFlowintTestParseIsset10); + UtRegisterTest( + "DetectFlowintTestParseInvalidSyntaxis01", DetectFlowintTestParseInvalidSyntaxis01); + UtRegisterTest("DetectFlowintTestPacket01Real", DetectFlowintTestPacket01Real); + UtRegisterTest("DetectFlowintTestPacket02Real", DetectFlowintTestPacket02Real); + UtRegisterTest("DetectFlowintTestPacket03Real", DetectFlowintTestPacket03Real); } #endif /* UNITTESTS */ diff --git a/src/detect-flowint.h b/src/detect-flowint.h index 6ffa1f093026..b1f683857330 100644 --- a/src/detect-flowint.h +++ b/src/detect-flowint.h @@ -60,13 +60,13 @@ typedef struct TargetVar_ { /** Context data for flowint vars */ typedef struct DetectFlowintData_ { /* This is the main var we are going to use - * against the target */ + * against the target */ char *name; /* Internal id of the var */ uint32_t idx; /* The modifier/operation/condition we are - * going to execute */ + * going to execute */ uint8_t modifier; uint8_t targettype; @@ -79,7 +79,6 @@ typedef struct DetectFlowintData_ { } DetectFlowintData; /* prototypes */ -void DetectFlowintRegister (void); +void DetectFlowintRegister(void); #endif /* __DETECT_FLOWINT_H__ */ - diff --git a/src/detect-flowvar.c b/src/detect-flowvar.c index c923be5d0b77..1398901abb2c 100644 --- a/src/detect-flowvar.c +++ b/src/detect-flowvar.c @@ -41,28 +41,27 @@ #include "util-debug.h" #include "util-print.h" -#define PARSE_REGEX "(.*),(.*)" +#define PARSE_REGEX "(.*),(.*)" static DetectParseRegex parse_regex; -int DetectFlowvarMatch (DetectEngineThreadCtx *, Packet *, - const Signature *, const SigMatchCtx *); -static int DetectFlowvarSetup (DetectEngineCtx *, Signature *, const char *); -static int DetectFlowvarPostMatch(DetectEngineThreadCtx *det_ctx, - Packet *p, const Signature *s, const SigMatchCtx *ctx); +int DetectFlowvarMatch(DetectEngineThreadCtx *, Packet *, const Signature *, const SigMatchCtx *); +static int DetectFlowvarSetup(DetectEngineCtx *, Signature *, const char *); +static int DetectFlowvarPostMatch( + DetectEngineThreadCtx *det_ctx, Packet *p, const Signature *s, const SigMatchCtx *ctx); static void DetectFlowvarDataFree(DetectEngineCtx *, void *ptr); -void DetectFlowvarRegister (void) +void DetectFlowvarRegister(void) { sigmatch_table[DETECT_FLOWVAR].name = "flowvar"; sigmatch_table[DETECT_FLOWVAR].Match = DetectFlowvarMatch; sigmatch_table[DETECT_FLOWVAR].Setup = DetectFlowvarSetup; - sigmatch_table[DETECT_FLOWVAR].Free = DetectFlowvarDataFree; + sigmatch_table[DETECT_FLOWVAR].Free = DetectFlowvarDataFree; /* post-match for flowvar storage */ sigmatch_table[DETECT_FLOWVAR_POSTMATCH].name = "__flowvar__postmatch__"; sigmatch_table[DETECT_FLOWVAR_POSTMATCH].Match = DetectFlowvarPostMatch; sigmatch_table[DETECT_FLOWVAR_POSTMATCH].Setup = NULL; - sigmatch_table[DETECT_FLOWVAR_POSTMATCH].Free = DetectFlowvarDataFree; + sigmatch_table[DETECT_FLOWVAR_POSTMATCH].Free = DetectFlowvarDataFree; DetectSetupParseRegexes(PARSE_REGEX, &parse_regex); } @@ -96,17 +95,16 @@ static void DetectFlowvarDataFree(DetectEngineCtx *de_ctx, void *ptr) * -1: error */ -int DetectFlowvarMatch (DetectEngineThreadCtx *det_ctx, Packet *p, - const Signature *s, const SigMatchCtx *ctx) +int DetectFlowvarMatch( + DetectEngineThreadCtx *det_ctx, Packet *p, const Signature *s, const SigMatchCtx *ctx) { int ret = 0; DetectFlowvarData *fd = (DetectFlowvarData *)ctx; FlowVar *fv = FlowVarGet(p->flow, fd->idx); if (fv != NULL) { - uint8_t *ptr = SpmSearch(fv->data.fv_str.value, - fv->data.fv_str.value_len, - fd->content, fd->content_len); + uint8_t *ptr = SpmSearch( + fv->data.fv_str.value, fv->data.fv_str.value_len, fd->content, fd->content_len); if (ptr != NULL) ret = 1; } @@ -114,7 +112,7 @@ int DetectFlowvarMatch (DetectEngineThreadCtx *det_ctx, Packet *p, return ret; } -static int DetectFlowvarSetup (DetectEngineCtx *de_ctx, Signature *s, const char *rawstr) +static int DetectFlowvarSetup(DetectEngineCtx *de_ctx, Signature *s, const char *rawstr) { DetectFlowvarData *fd = NULL; char varname[64], varcontent[64]; @@ -154,8 +152,8 @@ static int DetectFlowvarSetup (DetectEngineCtx *de_ctx, Signature *s, const char if (strlen(varcontent) >= 2) { if (varcontent[0] == '"') varcontent_index++; - if (varcontent[strlen(varcontent)-1] == '"') - varcontent[strlen(varcontent)-1] = '\0'; + if (varcontent[strlen(varcontent) - 1] == '"') + varcontent[strlen(varcontent) - 1] = '\0'; } SCLogDebug("varcontent %s", &varcontent[varcontent_index]); @@ -200,8 +198,7 @@ static int DetectFlowvarSetup (DetectEngineCtx *de_ctx, Signature *s, const char } /** \brief Store flowvar in det_ctx so we can exec it post-match */ -int DetectVarStoreMatchKeyValue(DetectEngineThreadCtx *det_ctx, - uint8_t *key, uint16_t key_len, +int DetectVarStoreMatchKeyValue(DetectEngineThreadCtx *det_ctx, uint8_t *key, uint16_t key_len, uint8_t *buffer, uint16_t len, int type) { DetectVarList *fs = SCCalloc(1, sizeof(*fs)); @@ -220,14 +217,13 @@ int DetectVarStoreMatchKeyValue(DetectEngineThreadCtx *det_ctx, } /** \brief Store flowvar in det_ctx so we can exec it post-match */ -int DetectVarStoreMatch(DetectEngineThreadCtx *det_ctx, - uint32_t idx, - uint8_t *buffer, uint16_t len, int type) +int DetectVarStoreMatch( + DetectEngineThreadCtx *det_ctx, uint32_t idx, uint8_t *buffer, uint16_t len, int type) { DetectVarList *fs = det_ctx->varlist; /* first check if we have had a previous match for this idx */ - for ( ; fs != NULL; fs = fs->next) { + for (; fs != NULL; fs = fs->next) { if (fs->idx == idx) { /* we're replacing the older store */ SCFree(fs->buffer); @@ -285,8 +281,7 @@ int DetectFlowvarPostMatchSetup(DetectEngineCtx *de_ctx, Signature *s, uint32_t * \retval 1 or -1 in case of error */ static int DetectFlowvarPostMatch( - DetectEngineThreadCtx *det_ctx, - Packet *p, const Signature *s, const SigMatchCtx *ctx) + DetectEngineThreadCtx *det_ctx, Packet *p, const Signature *s, const SigMatchCtx *ctx) { DetectVarList *fs, *prev; const DetectFlowvarData *fd; @@ -301,7 +296,7 @@ static int DetectFlowvarPostMatch( while (fs != NULL) { if (fd->idx == 0 || fd->idx == fs->idx) { SCLogDebug("adding to the flow %u:", fs->idx); - //PrintRawDataFp(stdout, fs->buffer, fs->len); + // PrintRawDataFp(stdout, fs->buffer, fs->len); if (fs->type == DETECT_VAR_TYPE_FLOW_POSTMATCH && p && p->flow) { FlowVarAddIdValue(p->flow, fs->idx, fs->buffer, fs->len); @@ -309,9 +304,8 @@ static int DetectFlowvarPostMatch( * the flowvar code. */ } else if (fs->type == DETECT_VAR_TYPE_PKT_POSTMATCH && fs->key && p) { /* pkt key/value */ - if (PktVarAddKeyValue(p, (uint8_t *)fs->key, fs->key_len, - (uint8_t *)fs->buffer, fs->len) == -1) - { + if (PktVarAddKeyValue(p, (uint8_t *)fs->key, fs->key_len, (uint8_t *)fs->buffer, + fs->len) == -1) { SCFree(fs->key); SCFree(fs->buffer); /* the rest of fs is freed below */ diff --git a/src/detect-flowvar.h b/src/detect-flowvar.h index b2988a63517a..0b745651c99d 100644 --- a/src/detect-flowvar.h +++ b/src/detect-flowvar.h @@ -35,13 +35,12 @@ typedef struct DetectFlowvarData_ { } DetectFlowvarData; /* prototypes */ -void DetectFlowvarRegister (void); +void DetectFlowvarRegister(void); int DetectFlowvarPostMatchSetup(DetectEngineCtx *de_ctx, Signature *s, uint32_t idx); -int DetectVarStoreMatch(DetectEngineThreadCtx *, - uint32_t, uint8_t *, uint16_t, int); -int DetectVarStoreMatchKeyValue(DetectEngineThreadCtx *, - uint8_t *, uint16_t, uint8_t *, uint16_t, int); +int DetectVarStoreMatch(DetectEngineThreadCtx *, uint32_t, uint8_t *, uint16_t, int); +int DetectVarStoreMatchKeyValue( + DetectEngineThreadCtx *, uint8_t *, uint16_t, uint8_t *, uint16_t, int); /* For use only by DetectFlowvarProcessList() */ void DetectVarProcessListInternal(DetectVarList *fs, Flow *f, Packet *p); diff --git a/src/detect-fragbits.c b/src/detect-fragbits.c index e03c9960e8a0..154908f6c5cc 100644 --- a/src/detect-fragbits.c +++ b/src/detect-fragbits.c @@ -61,15 +61,15 @@ #define MODIFIER_PLUS 2 #define MODIFIER_ANY 3 -#define FRAGBITS_HAVE_MF 0x01 -#define FRAGBITS_HAVE_DF 0x02 -#define FRAGBITS_HAVE_RF 0x04 +#define FRAGBITS_HAVE_MF 0x01 +#define FRAGBITS_HAVE_DF 0x02 +#define FRAGBITS_HAVE_RF 0x04 static DetectParseRegex parse_regex; -static int DetectFragBitsMatch (DetectEngineThreadCtx *, Packet *, - const Signature *, const SigMatchCtx *); -static int DetectFragBitsSetup (DetectEngineCtx *, Signature *, const char *); +static int DetectFragBitsMatch( + DetectEngineThreadCtx *, Packet *, const Signature *, const SigMatchCtx *); +static int DetectFragBitsSetup(DetectEngineCtx *, Signature *, const char *); static void DetectFragBitsFree(DetectEngineCtx *, void *); static int PrefilterSetupFragBits(DetectEngineCtx *de_ctx, SigGroupHead *sgh); @@ -82,14 +82,15 @@ static void FragBitsRegisterTests(void); * \brief Registration function for fragbits: keyword */ -void DetectFragBitsRegister (void) +void DetectFragBitsRegister(void) { sigmatch_table[DETECT_FRAGBITS].name = "fragbits"; - sigmatch_table[DETECT_FRAGBITS].desc = "check if the fragmentation and reserved bits are set in the IP header"; + sigmatch_table[DETECT_FRAGBITS].desc = + "check if the fragmentation and reserved bits are set in the IP header"; sigmatch_table[DETECT_FRAGBITS].url = "/rules/header-keywords.html#fragbits-ip-fragmentation"; sigmatch_table[DETECT_FRAGBITS].Match = DetectFragBitsMatch; sigmatch_table[DETECT_FRAGBITS].Setup = DetectFragBitsSetup; - sigmatch_table[DETECT_FRAGBITS].Free = DetectFragBitsFree; + sigmatch_table[DETECT_FRAGBITS].Free = DetectFragBitsFree; #ifdef UNITTESTS sigmatch_table[DETECT_FRAGBITS].RegisterTests = FragBitsRegisterTests; #endif @@ -99,9 +100,7 @@ void DetectFragBitsRegister (void) DetectSetupParseRegexes(PARSE_REGEX, &parse_regex); } -static inline int -FragBitsMatch(const uint8_t pbits, const uint8_t modifier, - const uint8_t dbits) +static inline int FragBitsMatch(const uint8_t pbits, const uint8_t modifier, const uint8_t dbits) { switch (modifier) { case MODIFIER_ANY: @@ -139,19 +138,19 @@ FragBitsMatch(const uint8_t pbits, const uint8_t modifier, * \retval 0 no match * \retval 1 match */ -static int DetectFragBitsMatch (DetectEngineThreadCtx *det_ctx, - Packet *p, const Signature *s, const SigMatchCtx *ctx) +static int DetectFragBitsMatch( + DetectEngineThreadCtx *det_ctx, Packet *p, const Signature *s, const SigMatchCtx *ctx) { if (!ctx || !PKT_IS_IPV4(p) || PKT_IS_PSEUDOPKT(p)) return 0; uint8_t fragbits = 0; const DetectFragBitsData *de = (const DetectFragBitsData *)ctx; - if(IPV4_GET_MF(p)) + if (IPV4_GET_MF(p)) fragbits |= FRAGBITS_HAVE_MF; - if(IPV4_GET_DF(p)) + if (IPV4_GET_DF(p)) fragbits |= FRAGBITS_HAVE_DF; - if(IPV4_GET_RF(p)) + if (IPV4_GET_RF(p)) fragbits |= FRAGBITS_HAVE_RF; return FragBitsMatch(fragbits, de->modifier, de->fragbits); @@ -166,13 +165,13 @@ static int DetectFragBitsMatch (DetectEngineThreadCtx *det_ctx, * \retval de pointer to DetectFragBitsData on success * \retval NULL on failure */ -static DetectFragBitsData *DetectFragBitsParse (const char *rawstr) +static DetectFragBitsData *DetectFragBitsParse(const char *rawstr) { DetectFragBitsData *de = NULL; int found = 0, res = 0; size_t pcre2_len; const char *str_ptr = NULL; - char *args[2] = { NULL, NULL}; + char *args[2] = { NULL, NULL }; char *ptr; int i; pcre2_match_data *match = NULL; @@ -247,7 +246,7 @@ static DetectFragBitsData *DetectFragBitsParse (const char *rawstr) ptr++; } - if(found == 0) + if (found == 0) goto error; for (i = 0; i < 2; i++) { @@ -282,7 +281,7 @@ static DetectFragBitsData *DetectFragBitsParse (const char *rawstr) * \retval 0 on Success * \retval -1 on Failure */ -static int DetectFragBitsSetup (DetectEngineCtx *de_ctx, Signature *s, const char *rawstr) +static int DetectFragBitsSetup(DetectEngineCtx *de_ctx, Signature *s, const char *rawstr) { DetectFragBitsData *de = NULL; @@ -313,11 +312,12 @@ static int DetectFragBitsSetup (DetectEngineCtx *de_ctx, Signature *s, const cha static void DetectFragBitsFree(DetectEngineCtx *de_ctx, void *de_ptr) { DetectFragBitsData *de = (DetectFragBitsData *)de_ptr; - if(de) SCFree(de); + if (de) + SCFree(de); } -static void -PrefilterPacketFragBitsMatch(DetectEngineThreadCtx *det_ctx, Packet *p, const void *pectx) +static void PrefilterPacketFragBitsMatch( + DetectEngineThreadCtx *det_ctx, Packet *p, const void *pectx) { const PrefilterPacketHeaderCtx *ctx = pectx; @@ -332,27 +332,22 @@ PrefilterPacketFragBitsMatch(DetectEngineThreadCtx *det_ctx, Packet *p, const vo if (IPV4_GET_RF(p)) fragbits |= FRAGBITS_HAVE_RF; - if (FragBitsMatch(fragbits, ctx->v1.u8[0], ctx->v1.u8[1])) - { + if (FragBitsMatch(fragbits, ctx->v1.u8[0], ctx->v1.u8[1])) { PrefilterAddSids(&det_ctx->pmq, ctx->sigs_array, ctx->sigs_cnt); } } -static void -PrefilterPacketFragBitsSet(PrefilterPacketHeaderValue *v, void *smctx) +static void PrefilterPacketFragBitsSet(PrefilterPacketHeaderValue *v, void *smctx) { const DetectFragBitsData *fb = smctx; v->u8[0] = fb->modifier; v->u8[1] = fb->fragbits; } -static bool -PrefilterPacketFragBitsCompare(PrefilterPacketHeaderValue v, void *smctx) +static bool PrefilterPacketFragBitsCompare(PrefilterPacketHeaderValue v, void *smctx) { const DetectFragBitsData *fb = smctx; - if (v.u8[0] == fb->modifier && - v.u8[1] == fb->fragbits) - { + if (v.u8[0] == fb->modifier && v.u8[1] == fb->fragbits) { return true; } return false; @@ -360,16 +355,14 @@ PrefilterPacketFragBitsCompare(PrefilterPacketHeaderValue v, void *smctx) static int PrefilterSetupFragBits(DetectEngineCtx *de_ctx, SigGroupHead *sgh) { - return PrefilterSetupPacketHeader(de_ctx, sgh, DETECT_FRAGBITS, - PrefilterPacketFragBitsSet, - PrefilterPacketFragBitsCompare, - PrefilterPacketFragBitsMatch); + return PrefilterSetupPacketHeader(de_ctx, sgh, DETECT_FRAGBITS, PrefilterPacketFragBitsSet, + PrefilterPacketFragBitsCompare, PrefilterPacketFragBitsMatch); } static bool PrefilterFragBitsIsPrefilterable(const Signature *s) { const SigMatch *sm; - for (sm = s->init_data->smlists[DETECT_SM_LIST_MATCH] ; sm != NULL; sm = sm->next) { + for (sm = s->init_data->smlists[DETECT_SM_LIST_MATCH]; sm != NULL; sm = sm->next) { switch (sm->type) { case DETECT_FRAGBITS: return true; @@ -392,11 +385,11 @@ static bool PrefilterFragBitsIsPrefilterable(const Signature *s) * \retval 1 on success * \retval 0 on failure */ -static int FragBitsTestParse01 (void) +static int FragBitsTestParse01(void) { DetectFragBitsData *de = NULL; de = DetectFragBitsParse("M"); - if (de && (de->fragbits == FRAGBITS_HAVE_MF) ) { + if (de && (de->fragbits == FRAGBITS_HAVE_MF)) { DetectFragBitsFree(NULL, de); return 1; } @@ -410,7 +403,7 @@ static int FragBitsTestParse01 (void) * \retval 1 on success * \retval 0 on failure */ -static int FragBitsTestParse02 (void) +static int FragBitsTestParse02(void) { DetectFragBitsData *de = NULL; de = DetectFragBitsParse("G"); @@ -428,7 +421,7 @@ static int FragBitsTestParse02 (void) * \retval 1 on success * \retval 0 on failure */ -static int FragBitsTestParse03 (void) +static int FragBitsTestParse03(void) { // clang-format off uint8_t raw_eth[] = { @@ -516,7 +509,7 @@ static int FragBitsTestParse03 (void) * \retval 1 on success * \retval 0 on failure */ -static int FragBitsTestParse04 (void) +static int FragBitsTestParse04(void) { // clang-format off uint8_t raw_eth[] = { @@ -578,7 +571,6 @@ static int FragBitsTestParse04 (void) DecodeEthernet(&tv, &dtv, p, raw_eth, sizeof(raw_eth)); - de = DetectFragBitsParse("!D"); FAIL_IF(de == NULL); diff --git a/src/detect-fragbits.h b/src/detect-fragbits.h index 1ab6cae310e3..72333790cca9 100644 --- a/src/detect-fragbits.h +++ b/src/detect-fragbits.h @@ -24,7 +24,6 @@ #ifndef __DETECT_FRAGBITS_H__ #define __DETECT_FRAGBITS_H__ - /** * \struct DetectFragBitsData_ * DetectFragBitsData_ is used to store fragbits: input value @@ -44,6 +43,6 @@ typedef struct DetectFragBitsData_ { * Registration function for fragbits: keyword */ -void DetectFragBitsRegister (void); +void DetectFragBitsRegister(void); #endif /*__DETECT_FRAGBITS_H__ */ diff --git a/src/detect-fragoffset.c b/src/detect-fragoffset.c index b4b21ff58ede..72d40c59f0e5 100644 --- a/src/detect-fragoffset.c +++ b/src/detect-fragoffset.c @@ -43,8 +43,8 @@ static DetectParseRegex parse_regex; -static int DetectFragOffsetMatch(DetectEngineThreadCtx *, - Packet *, const Signature *, const SigMatchCtx *); +static int DetectFragOffsetMatch( + DetectEngineThreadCtx *, Packet *, const Signature *, const SigMatchCtx *); static int DetectFragOffsetSetup(DetectEngineCtx *, Signature *, const char *); #ifdef UNITTESTS void DetectFragOffsetRegisterTests(void); @@ -57,10 +57,11 @@ static bool PrefilterFragOffsetIsPrefilterable(const Signature *s); /** * \brief Registration function for fragoffset */ -void DetectFragOffsetRegister (void) +void DetectFragOffsetRegister(void) { sigmatch_table[DETECT_FRAGOFFSET].name = "fragoffset"; - sigmatch_table[DETECT_FRAGOFFSET].desc = "match on specific decimal values of the IP fragment offset field"; + sigmatch_table[DETECT_FRAGOFFSET].desc = + "match on specific decimal values of the IP fragment offset field"; sigmatch_table[DETECT_FRAGOFFSET].url = "/rules/header-keywords.html#fragoffset"; sigmatch_table[DETECT_FRAGOFFSET].Match = DetectFragOffsetMatch; sigmatch_table[DETECT_FRAGOFFSET].Setup = DetectFragOffsetSetup; @@ -74,10 +75,10 @@ void DetectFragOffsetRegister (void) DetectSetupParseRegexes(PARSE_REGEX, &parse_regex); } -static inline int FragOffsetMatch(const uint16_t poffset, const uint8_t mode, - const uint16_t doffset) +static inline int FragOffsetMatch( + const uint16_t poffset, const uint8_t mode, const uint16_t doffset) { - switch (mode) { + switch (mode) { case FRAG_LESS: if (poffset < doffset) return 1; @@ -105,8 +106,8 @@ static inline int FragOffsetMatch(const uint16_t poffset, const uint8_t mode, * \retval 1 match * */ -static int DetectFragOffsetMatch (DetectEngineThreadCtx *det_ctx, - Packet *p, const Signature *s, const SigMatchCtx *ctx) +static int DetectFragOffsetMatch( + DetectEngineThreadCtx *det_ctx, Packet *p, const Signature *s, const SigMatchCtx *ctx) { uint16_t frag = 0; const DetectFragOffsetData *fragoff = (const DetectFragOffsetData *)ctx; @@ -139,10 +140,11 @@ static int DetectFragOffsetMatch (DetectEngineThreadCtx *det_ctx, * \retval fragoff pointer to DetectFragOffsetData on success * \retval NULL on failure */ -static DetectFragOffsetData *DetectFragOffsetParse (DetectEngineCtx *de_ctx, const char *fragoffsetstr) +static DetectFragOffsetData *DetectFragOffsetParse( + DetectEngineCtx *de_ctx, const char *fragoffsetstr) { DetectFragOffsetData *fragoff = NULL; - char *substr[3] = {NULL, NULL, NULL}; + char *substr[3] = { NULL, NULL, NULL }; int res = 0; size_t pcre2_len; int i; @@ -162,7 +164,7 @@ static DetectFragOffsetData *DetectFragOffsetParse (DetectEngineCtx *de_ctx, con SCLogError("pcre2_substring_get_bynumber failed"); goto error; } - substr[i-1] = (char *)str_ptr; + substr[i - 1] = (char *)str_ptr; } fragoff = SCMalloc(sizeof(DetectFragOffsetData)); @@ -174,10 +176,10 @@ static DetectFragOffsetData *DetectFragOffsetParse (DetectEngineCtx *de_ctx, con mode = substr[0]; - if(mode != NULL) { + if (mode != NULL) { - while(*mode != '\0') { - switch(*mode) { + while (*mode != '\0') { + switch (*mode) { case '>': fragoff->mode = FRAG_MORE; break; @@ -212,9 +214,9 @@ static DetectFragOffsetData *DetectFragOffsetParse (DetectEngineCtx *de_ctx, con if (substr[i] != NULL) pcre2_substring_free((PCRE2_UCHAR8 *)substr[i]); } - if (fragoff != NULL) DetectFragOffsetFree(de_ctx, fragoff); + if (fragoff != NULL) + DetectFragOffsetFree(de_ctx, fragoff); return NULL; - } /** @@ -227,12 +229,13 @@ static DetectFragOffsetData *DetectFragOffsetParse (DetectEngineCtx *de_ctx, con * \retval 0 on Success * \retval -1 on Failure */ -static int DetectFragOffsetSetup (DetectEngineCtx *de_ctx, Signature *s, const char *fragoffsetstr) +static int DetectFragOffsetSetup(DetectEngineCtx *de_ctx, Signature *s, const char *fragoffsetstr) { DetectFragOffsetData *fragoff = NULL; fragoff = DetectFragOffsetParse(de_ctx, fragoffsetstr); - if (fragoff == NULL) goto error; + if (fragoff == NULL) + goto error; if (SigMatchAppendSMToList(de_ctx, s, DETECT_FRAGOFFSET, (SigMatchCtx *)fragoff, DETECT_SM_LIST_MATCH) == NULL) { @@ -246,7 +249,6 @@ static int DetectFragOffsetSetup (DetectEngineCtx *de_ctx, Signature *s, const c if (fragoff != NULL) DetectFragOffsetFree(de_ctx, fragoff); return -1; - } /** @@ -254,14 +256,14 @@ static int DetectFragOffsetSetup (DetectEngineCtx *de_ctx, Signature *s, const c * * \param ptr pointer to DetectFragOffsetData */ -void DetectFragOffsetFree (DetectEngineCtx *de_ctx, void *ptr) +void DetectFragOffsetFree(DetectEngineCtx *de_ctx, void *ptr) { DetectFragOffsetData *fragoff = (DetectFragOffsetData *)ptr; SCFree(fragoff); } -static void -PrefilterPacketFragOffsetMatch(DetectEngineThreadCtx *det_ctx, Packet *p, const void *pectx) +static void PrefilterPacketFragOffsetMatch( + DetectEngineThreadCtx *det_ctx, Packet *p, const void *pectx) { if (PKT_IS_PSEUDOPKT(p)) return; @@ -282,27 +284,22 @@ PrefilterPacketFragOffsetMatch(DetectEngineThreadCtx *det_ctx, Packet *p, const } const PrefilterPacketHeaderCtx *ctx = pectx; - if (FragOffsetMatch(frag, ctx->v1.u8[0], ctx->v1.u16[1])) - { + if (FragOffsetMatch(frag, ctx->v1.u8[0], ctx->v1.u16[1])) { PrefilterAddSids(&det_ctx->pmq, ctx->sigs_array, ctx->sigs_cnt); } } -static void -PrefilterPacketFragOffsetSet(PrefilterPacketHeaderValue *v, void *smctx) +static void PrefilterPacketFragOffsetSet(PrefilterPacketHeaderValue *v, void *smctx) { const DetectFragOffsetData *fb = smctx; v->u8[0] = fb->mode; v->u16[1] = fb->frag_off; } -static bool -PrefilterPacketFragOffsetCompare(PrefilterPacketHeaderValue v, void *smctx) +static bool PrefilterPacketFragOffsetCompare(PrefilterPacketHeaderValue v, void *smctx) { const DetectFragOffsetData *fb = smctx; - if (v.u8[0] == fb->mode && - v.u16[1] == fb->frag_off) - { + if (v.u8[0] == fb->mode && v.u16[1] == fb->frag_off) { return true; } return false; @@ -310,16 +307,14 @@ PrefilterPacketFragOffsetCompare(PrefilterPacketHeaderValue v, void *smctx) static int PrefilterSetupFragOffset(DetectEngineCtx *de_ctx, SigGroupHead *sgh) { - return PrefilterSetupPacketHeader(de_ctx, sgh, DETECT_FRAGOFFSET, - PrefilterPacketFragOffsetSet, - PrefilterPacketFragOffsetCompare, - PrefilterPacketFragOffsetMatch); + return PrefilterSetupPacketHeader(de_ctx, sgh, DETECT_FRAGOFFSET, PrefilterPacketFragOffsetSet, + PrefilterPacketFragOffsetCompare, PrefilterPacketFragOffsetMatch); } static bool PrefilterFragOffsetIsPrefilterable(const Signature *s) { const SigMatch *sm; - for (sm = s->init_data->smlists[DETECT_SM_LIST_MATCH] ; sm != NULL; sm = sm->next) { + for (sm = s->init_data->smlists[DETECT_SM_LIST_MATCH]; sm != NULL; sm = sm->next) { switch (sm->type) { case DETECT_FRAGOFFSET: return true; @@ -336,7 +331,7 @@ static bool PrefilterFragOffsetIsPrefilterable(const Signature *s) /** * \test DetectFragOffsetParseTest01 is a test for setting a valid fragoffset value */ -static int DetectFragOffsetParseTest01 (void) +static int DetectFragOffsetParseTest01(void) { DetectFragOffsetData *fragoff = DetectFragOffsetParse(NULL, "300"); @@ -352,7 +347,7 @@ static int DetectFragOffsetParseTest01 (void) * \test DetectFragOffsetParseTest02 is a test for setting a valid fragoffset value * with spaces all around */ -static int DetectFragOffsetParseTest02 (void) +static int DetectFragOffsetParseTest02(void) { DetectFragOffsetData *fragoff = DetectFragOffsetParse(NULL, ">300"); @@ -368,7 +363,7 @@ static int DetectFragOffsetParseTest02 (void) /** * \test DetectFragOffsetParseTest03 is a test for setting an invalid fragoffset value */ -static int DetectFragOffsetParseTest03 (void) +static int DetectFragOffsetParseTest03(void) { DetectFragOffsetData *fragoff = DetectFragOffsetParse(NULL, "badc"); @@ -382,7 +377,7 @@ static int DetectFragOffsetParseTest03 (void) * fragoffset keyword by creating 2 rules and matching a crafted packet * against them. Only the first one shall trigger. */ -static int DetectFragOffsetMatchTest01 (void) +static int DetectFragOffsetMatchTest01(void) { Packet *p = PacketGetFromAlloc(); @@ -437,7 +432,7 @@ static int DetectFragOffsetMatchTest01 (void) PASS; } -void DetectFragOffsetRegisterTests (void) +void DetectFragOffsetRegisterTests(void) { UtRegisterTest("DetectFragOffsetParseTest01", DetectFragOffsetParseTest01); UtRegisterTest("DetectFragOffsetParseTest02", DetectFragOffsetParseTest02); diff --git a/src/detect-ftpbounce.c b/src/detect-ftpbounce.c index 79b0f1b579e2..fd8808e14397 100644 --- a/src/detect-ftpbounce.c +++ b/src/detect-ftpbounce.c @@ -47,8 +47,7 @@ #include "stream-tcp.h" #include "util-byte.h" -static int DetectFtpbounceALMatch(DetectEngineThreadCtx *, - Flow *, uint8_t, void *, void *, +static int DetectFtpbounceALMatch(DetectEngineThreadCtx *, Flow *, uint8_t, void *, void *, const Signature *, const SigMatchCtx *); static int DetectFtpbounceSetup(DetectEngineCtx *, Signature *, const char *); @@ -107,7 +106,7 @@ static int DetectFtpbounceMatchArgs( if (offset + 7 >= payload_len) return 0; - c =(char*) payload; + c = (char *)payload; if (c == NULL) { SCLogDebug("No payload to check"); return 0; @@ -115,11 +114,12 @@ static int DetectFtpbounceMatchArgs( i = offset; /* Search for the first IP octect(Skips "PORT ") */ - while (i < payload_len && !isdigit((unsigned char)c[i])) i++; + while (i < payload_len && !isdigit((unsigned char)c[i])) + i++; - for (;i < payload_len && octet_ascii_len < 4 ;i++) { + for (; i < payload_len && octet_ascii_len < 4; i++) { if (isdigit((unsigned char)c[i])) { - octet =(c[i] - '0') + octet * 10; + octet = (c[i] - '0') + octet * 10; octet_ascii_len++; } else { if (octet > 256) { @@ -128,12 +128,13 @@ static int DetectFtpbounceMatchArgs( } if (isspace((unsigned char)c[i])) - while (i < payload_len && isspace((unsigned char)c[i]) ) i++; + while (i < payload_len && isspace((unsigned char)c[i])) + i++; if (i < payload_len && c[i] == ',') { /* we have an octet */ noctet++; octet_ascii_len = 0; - ip =(ip << 8) + octet; + ip = (ip << 8) + octet; octet = 0; } else { SCLogDebug("Unrecognized character '%c'", c[i]); @@ -144,8 +145,7 @@ static int DetectFtpbounceMatchArgs( ip = SCNtohl(ip); if (ip != ip_orig) { - SCLogDebug("Different ip, so Matched ip:%d <-> ip_orig:%d", - ip, ip_orig); + SCLogDebug("Different ip, so Matched ip:%d <-> ip_orig:%d", ip, ip_orig); return 1; } SCLogDebug("Same ip, so no match here"); @@ -168,10 +168,8 @@ static int DetectFtpbounceMatchArgs( * \retval 0 no match * \retval 1 match */ -static int DetectFtpbounceALMatch(DetectEngineThreadCtx *det_ctx, - Flow *f, uint8_t flags, - void *state, void *txv, - const Signature *s, const SigMatchCtx *m) +static int DetectFtpbounceALMatch(DetectEngineThreadCtx *det_ctx, Flow *f, uint8_t flags, + void *state, void *txv, const Signature *s, const SigMatchCtx *m) { SCEnter(); @@ -183,9 +181,8 @@ static int DetectFtpbounceALMatch(DetectEngineThreadCtx *det_ctx, int ret = 0; if (ftp_state->command == FTP_COMMAND_PORT) { - ret = DetectFtpbounceMatchArgs(ftp_state->port_line, - ftp_state->port_line_len, f->src.address.address_un_data32[0], - ftp_state->arg_offset); + ret = DetectFtpbounceMatchArgs(ftp_state->port_line, ftp_state->port_line_len, + f->src.address.address_un_data32[0], ftp_state->arg_offset); } SCReturnInt(ret); diff --git a/src/detect-ftpbounce.h b/src/detect-ftpbounce.h index f9cdfe390c11..c3aab0840ea4 100644 --- a/src/detect-ftpbounce.h +++ b/src/detect-ftpbounce.h @@ -25,7 +25,6 @@ #define __DETECT_FTPBOUNCE_H__ /* prototypes */ -void DetectFtpbounceRegister (void); +void DetectFtpbounceRegister(void); #endif /* __DETECT_FTPBOUNCE_H__ */ - diff --git a/src/detect-ftpdata.c b/src/detect-ftpdata.c index ce9e5c3c211c..6637dc6aa112 100644 --- a/src/detect-ftpdata.c +++ b/src/detect-ftpdata.c @@ -37,17 +37,16 @@ /** * \brief Regex for parsing our keyword options */ -#define PARSE_REGEX "^\\s*(stor|retr)\\s*$" +#define PARSE_REGEX "^\\s*(stor|retr)\\s*$" static DetectParseRegex parse_regex; /* Prototypes of functions registered in DetectFtpdataRegister below */ -static int DetectFtpdataMatch(DetectEngineThreadCtx *, - Flow *, uint8_t, void *, void *, +static int DetectFtpdataMatch(DetectEngineThreadCtx *, Flow *, uint8_t, void *, void *, const Signature *, const SigMatchCtx *); -static int DetectFtpdataSetup (DetectEngineCtx *, Signature *, const char *); -static void DetectFtpdataFree (DetectEngineCtx *, void *); +static int DetectFtpdataSetup(DetectEngineCtx *, Signature *, const char *); +static void DetectFtpdataFree(DetectEngineCtx *, void *); #ifdef UNITTESTS -static void DetectFtpdataRegisterTests (void); +static void DetectFtpdataRegisterTests(void); #endif static int g_ftpdata_buffer_id = 0; @@ -56,7 +55,8 @@ static int g_ftpdata_buffer_id = 0; * * This function is called once in the 'lifetime' of the engine. */ -void DetectFtpdataRegister(void) { +void DetectFtpdataRegister(void) +{ /* keyword name: this is how the keyword is used in a rule */ sigmatch_table[DETECT_FTPDATA].name = "ftpdata_command"; /* description: listed in "suricata --list-keywords=all" */ @@ -94,12 +94,10 @@ void DetectFtpdataRegister(void) { * \retval 0 no match * \retval 1 match */ -static int DetectFtpdataMatch(DetectEngineThreadCtx *det_ctx, - Flow *f, uint8_t flags, - void *state, void *txv, - const Signature *s, const SigMatchCtx *m) +static int DetectFtpdataMatch(DetectEngineThreadCtx *det_ctx, Flow *f, uint8_t flags, void *state, + void *txv, const Signature *s, const SigMatchCtx *m) { - const DetectFtpdataData *ftpcommandd = (const DetectFtpdataData *) m; + const DetectFtpdataData *ftpcommandd = (const DetectFtpdataData *)m; const FtpDataState *ftp_state = (const FtpDataState *)state; if (ftp_state == NULL) @@ -147,7 +145,7 @@ static DetectFtpdataData *DetectFtpdataParse(const char *ftpcommandstr) } SCLogDebug("Arg1 \"%s\"", arg1); - ftpcommandd = SCMalloc(sizeof (DetectFtpdataData)); + ftpcommandd = SCMalloc(sizeof(DetectFtpdataData)); if (unlikely(ftpcommandd == NULL)) goto error; if (!strcmp(arg1, "stor")) { @@ -204,7 +202,8 @@ static int DetectFtpdataSetup(DetectEngineCtx *de_ctx, Signature *s, const char * * \param ptr pointer to DetectFtpdataData */ -static void DetectFtpdataFree(DetectEngineCtx *de_ctx, void *ptr) { +static void DetectFtpdataFree(DetectEngineCtx *de_ctx, void *ptr) +{ DetectFtpdataData *ftpcommandd = (DetectFtpdataData *)ptr; /* do more specific cleanup here, if needed */ @@ -228,11 +227,14 @@ static int DetectFtpdataSignatureTest01(void) DetectEngineCtx *de_ctx = DetectEngineCtxInit(); FAIL_IF_NULL(de_ctx); - Signature *sig = DetectEngineAppendSig(de_ctx, "alert ip any any -> any any (ftpdata_command:stor; sid:1; rev:1;)"); + Signature *sig = DetectEngineAppendSig( + de_ctx, "alert ip any any -> any any (ftpdata_command:stor; sid:1; rev:1;)"); FAIL_IF_NULL(sig); - sig = DetectEngineAppendSig(de_ctx, "alert ip any any -> any any (ftpdata_command:retr; sid:2; rev:1;)"); + sig = DetectEngineAppendSig( + de_ctx, "alert ip any any -> any any (ftpdata_command:retr; sid:2; rev:1;)"); FAIL_IF_NULL(sig); - sig = DetectEngineAppendSig(de_ctx, "alert ip any any -> any any (ftpdata_command:xxx; sid:3; rev:1;)"); + sig = DetectEngineAppendSig( + de_ctx, "alert ip any any -> any any (ftpdata_command:xxx; sid:3; rev:1;)"); FAIL_IF_NOT_NULL(sig); DetectEngineCtxFree(de_ctx); @@ -245,7 +247,6 @@ static int DetectFtpdataSignatureTest01(void) static void DetectFtpdataRegisterTests(void) { UtRegisterTest("DetectFtpdataParseTest01", DetectFtpdataParseTest01); - UtRegisterTest("DetectFtpdataSignatureTest01", - DetectFtpdataSignatureTest01); + UtRegisterTest("DetectFtpdataSignatureTest01", DetectFtpdataSignatureTest01); } #endif /* UNITTESTS */ diff --git a/src/detect-geoip.c b/src/detect-geoip.c index 9198b9e45129..8a8515e37d9d 100644 --- a/src/detect-geoip.c +++ b/src/detect-geoip.c @@ -41,7 +41,7 @@ #ifndef HAVE_GEOIP -static int DetectGeoipSetupNoSupport (DetectEngineCtx *a, Signature *b, const char *c) +static int DetectGeoipSetupNoSupport(DetectEngineCtx *a, Signature *b, const char *c) { SCLogError("no GeoIP support built in, needed for geoip keyword"); return -1; @@ -54,7 +54,9 @@ static int DetectGeoipSetupNoSupport (DetectEngineCtx *a, Signature *b, const ch void DetectGeoipRegister(void) { sigmatch_table[DETECT_GEOIP].name = "geoip"; - sigmatch_table[DETECT_GEOIP].desc = "match on the source, destination or source and destination IP addresses of network traffic, and to see to which country it belongs"; + sigmatch_table[DETECT_GEOIP].desc = + "match on the source, destination or source and destination IP addresses of network " + "traffic, and to see to which country it belongs"; sigmatch_table[DETECT_GEOIP].url = "/rules/header-keywords.html#geoip"; sigmatch_table[DETECT_GEOIP].Setup = DetectGeoipSetupNoSupport; sigmatch_table[DETECT_GEOIP].Free = NULL; @@ -64,8 +66,8 @@ void DetectGeoipRegister(void) #include -static int DetectGeoipMatch(DetectEngineThreadCtx *, Packet *, - const Signature *, const SigMatchCtx *); +static int DetectGeoipMatch( + DetectEngineThreadCtx *, Packet *, const Signature *, const SigMatchCtx *); static int DetectGeoipSetup(DetectEngineCtx *, Signature *, const char *); #ifdef UNITTESTS static void DetectGeoipRegisterTests(void); @@ -149,24 +151,22 @@ static const char *GeolocateIPv4(const DetectGeoipData *geoipdata, uint32_t ip) return NULL; /* Attempt to find the IPv4 address in the database */ - result = MMDB_lookup_sockaddr((MMDB_s *)&geoipdata->mmdb, - (struct sockaddr*)&sa, &mmdb_error); + result = MMDB_lookup_sockaddr((MMDB_s *)&geoipdata->mmdb, (struct sockaddr *)&sa, &mmdb_error); if (mmdb_error != MMDB_SUCCESS) return NULL; /* The IPv4 address was found, so grab ISO country code if available */ if (result.found_entry) { - mmdb_error = MMDB_get_value(&result.entry, &entry_data, "country", - "iso_code", NULL); + mmdb_error = MMDB_get_value(&result.entry, &entry_data, "country", "iso_code", NULL); if (mmdb_error != MMDB_SUCCESS) return NULL; /* If ISO country code was found, then return it */ if (entry_data.has_data) { if (entry_data.type == MMDB_DATA_TYPE_UTF8_STRING) { - char *country_code = SCStrndup((char *)entry_data.utf8_string, - entry_data.data_size); - return country_code; + char *country_code = + SCStrndup((char *)entry_data.utf8_string, entry_data.data_size); + return country_code; } } } @@ -176,17 +176,17 @@ static const char *GeolocateIPv4(const DetectGeoipData *geoipdata, uint32_t ip) } /* Match-on conditions supported */ -#define GEOIP_MATCH_SRC_STR "src" -#define GEOIP_MATCH_DST_STR "dst" -#define GEOIP_MATCH_BOTH_STR "both" -#define GEOIP_MATCH_ANY_STR "any" - -#define GEOIP_MATCH_NO_FLAG 0 -#define GEOIP_MATCH_SRC_FLAG 1 -#define GEOIP_MATCH_DST_FLAG 2 -#define GEOIP_MATCH_ANY_FLAG 3 /* default src and dst*/ -#define GEOIP_MATCH_BOTH_FLAG 4 -#define GEOIP_MATCH_NEGATED 8 +#define GEOIP_MATCH_SRC_STR "src" +#define GEOIP_MATCH_DST_STR "dst" +#define GEOIP_MATCH_BOTH_STR "both" +#define GEOIP_MATCH_ANY_STR "any" + +#define GEOIP_MATCH_NO_FLAG 0 +#define GEOIP_MATCH_SRC_FLAG 1 +#define GEOIP_MATCH_DST_FLAG 2 +#define GEOIP_MATCH_ANY_FLAG 3 /* default src and dst*/ +#define GEOIP_MATCH_BOTH_FLAG 4 +#define GEOIP_MATCH_NEGATED 8 /** * \internal @@ -209,10 +209,9 @@ static int CheckGeoMatchIPv4(const DetectGeoipData *geoipdata, uint32_t ip) return 0; /* Check if NOT NEGATED match-on condition */ - if ((geoipdata->flags & GEOIP_MATCH_NEGATED) == 0) - { + if ((geoipdata->flags & GEOIP_MATCH_NEGATED) == 0) { for (i = 0; i < geoipdata->nlocations; i++) { - if (strcmp(country, (char *)geoipdata->location[i])==0) { + if (strcmp(country, (char *)geoipdata->location[i]) == 0) { SCFree((void *)country); return 1; } @@ -220,7 +219,7 @@ static int CheckGeoMatchIPv4(const DetectGeoipData *geoipdata, uint32_t ip) } else { /* Check if NEGATED match-on condition */ for (i = 0; i < geoipdata->nlocations; i++) { - if (strcmp(country, (char *)geoipdata->location[i])==0) { + if (strcmp(country, (char *)geoipdata->location[i]) == 0) { SCFree((void *)country); return 0; /* if one matches, rule does NOT match (negated) */ } @@ -244,8 +243,8 @@ static int CheckGeoMatchIPv4(const DetectGeoipData *geoipdata, uint32_t ip) * \retval 0 no match * \retval 1 match */ -static int DetectGeoipMatch(DetectEngineThreadCtx *det_ctx, - Packet *p, const Signature *s, const SigMatchCtx *ctx) +static int DetectGeoipMatch( + DetectEngineThreadCtx *det_ctx, Packet *p, const Signature *s, const SigMatchCtx *ctx) { const DetectGeoipData *geoipdata = (const DetectGeoipData *)ctx; int matches = 0; @@ -253,22 +252,17 @@ static int DetectGeoipMatch(DetectEngineThreadCtx *det_ctx, if (PKT_IS_PSEUDOPKT(p)) return 0; - if (PKT_IS_IPV4(p)) - { - if (geoipdata->flags & ( GEOIP_MATCH_SRC_FLAG | GEOIP_MATCH_BOTH_FLAG )) - { - if (CheckGeoMatchIPv4(geoipdata, GET_IPV4_SRC_ADDR_U32(p))) - { + if (PKT_IS_IPV4(p)) { + if (geoipdata->flags & (GEOIP_MATCH_SRC_FLAG | GEOIP_MATCH_BOTH_FLAG)) { + if (CheckGeoMatchIPv4(geoipdata, GET_IPV4_SRC_ADDR_U32(p))) { if (geoipdata->flags & GEOIP_MATCH_BOTH_FLAG) matches++; else return 1; } } - if (geoipdata->flags & ( GEOIP_MATCH_DST_FLAG | GEOIP_MATCH_BOTH_FLAG )) - { - if (CheckGeoMatchIPv4(geoipdata, GET_IPV4_DST_ADDR_U32(p))) - { + if (geoipdata->flags & (GEOIP_MATCH_DST_FLAG | GEOIP_MATCH_BOTH_FLAG)) { + if (CheckGeoMatchIPv4(geoipdata, GET_IPV4_DST_ADDR_U32(p))) { if (geoipdata->flags & GEOIP_MATCH_BOTH_FLAG) matches++; else @@ -292,7 +286,7 @@ static int DetectGeoipMatch(DetectEngineThreadCtx *det_ctx, * \retval pointer to DetectGeoipData on success * \retval NULL on failure */ -static DetectGeoipData *DetectGeoipDataParse (DetectEngineCtx *de_ctx, const char *str) +static DetectGeoipData *DetectGeoipDataParse(DetectEngineCtx *de_ctx, const char *str) { DetectGeoipData *geoipdata = NULL; uint16_t pos = 0; @@ -310,13 +304,10 @@ static DetectGeoipData *DetectGeoipDataParse (DetectEngineCtx *de_ctx, const cha goto error; /* Parse the geoip option string */ - while (pos <= slen) - { + while (pos <= slen) { /* search for ',' or end of string */ - if (str[pos] == ',' || pos == slen) - { - if (geoipdata->flags == GEOIP_MATCH_NO_FLAG) - { + if (str[pos] == ',' || pos == slen) { + if (geoipdata->flags == GEOIP_MATCH_NO_FLAG) { /* Parse match-on condition */ if (pos == slen) /* if end of option str then there are no match-on cond. */ { @@ -325,13 +316,13 @@ static DetectGeoipData *DetectGeoipDataParse (DetectEngineCtx *de_ctx, const cha geoipdata->flags |= GEOIP_MATCH_ANY_FLAG; } else { skiplocationparsing = 1; - if (strncmp(&str[prevpos], GEOIP_MATCH_SRC_STR, pos-prevpos) == 0) + if (strncmp(&str[prevpos], GEOIP_MATCH_SRC_STR, pos - prevpos) == 0) geoipdata->flags |= GEOIP_MATCH_SRC_FLAG; - else if (strncmp(&str[prevpos], GEOIP_MATCH_DST_STR, pos-prevpos) == 0) + else if (strncmp(&str[prevpos], GEOIP_MATCH_DST_STR, pos - prevpos) == 0) geoipdata->flags |= GEOIP_MATCH_DST_FLAG; - else if (strncmp(&str[prevpos], GEOIP_MATCH_BOTH_STR, pos-prevpos) == 0) + else if (strncmp(&str[prevpos], GEOIP_MATCH_BOTH_STR, pos - prevpos) == 0) geoipdata->flags |= GEOIP_MATCH_BOTH_FLAG; - else if (strncmp(&str[prevpos], GEOIP_MATCH_ANY_STR, pos-prevpos) == 0) + else if (strncmp(&str[prevpos], GEOIP_MATCH_ANY_STR, pos - prevpos) == 0) geoipdata->flags |= GEOIP_MATCH_ANY_FLAG; else { /* There was NO match-on condition! we default to ANY*/ @@ -340,8 +331,7 @@ static DetectGeoipData *DetectGeoipDataParse (DetectEngineCtx *de_ctx, const cha } } } - if (geoipdata->flags != GEOIP_MATCH_NO_FLAG && skiplocationparsing == 0) - { + if (geoipdata->flags != GEOIP_MATCH_NO_FLAG && skiplocationparsing == 0) { /* Parse location string: for now just the country code(s) */ if (str[prevpos] == '!') { geoipdata->flags |= GEOIP_MATCH_NEGATED; @@ -353,24 +343,24 @@ static DetectGeoipData *DetectGeoipDataParse (DetectEngineCtx *de_ctx, const cha goto error; } - if (pos-prevpos > GEOOPTION_MAXSIZE) + if (pos - prevpos > GEOOPTION_MAXSIZE) strlcpy((char *)geoipdata->location[geoipdata->nlocations], &str[prevpos], - GEOOPTION_MAXSIZE); + GEOOPTION_MAXSIZE); else strlcpy((char *)geoipdata->location[geoipdata->nlocations], &str[prevpos], - pos-prevpos+1); + pos - prevpos + 1); if (geoipdata->nlocations < GEOOPTION_MAXLOCATIONS) geoipdata->nlocations++; } - prevpos = pos+1; + prevpos = pos + 1; skiplocationparsing = 0; /* match-on condition for sure has been parsed already */ } pos++; } - SCLogDebug("GeoIP: %"PRIu32" countries loaded", geoipdata->nlocations); - for (int i=0; inlocations; i++) + SCLogDebug("GeoIP: %" PRIu32 " countries loaded", geoipdata->nlocations); + for (int i = 0; i < geoipdata->nlocations; i++) SCLogDebug("GeoIP country code: %s", geoipdata->location[i]); SCLogDebug("flags %02X", geoipdata->flags); @@ -426,7 +416,6 @@ static int DetectGeoipSetup(DetectEngineCtx *de_ctx, Signature *s, const char *o if (geoipdata != NULL) DetectGeoipDataFree(de_ctx, geoipdata); return -1; - } /** @@ -467,11 +456,10 @@ static int GeoipParseTest(const char *rule, int ncountries, const char **countri data = (DetectGeoipData *)s->init_data->smlists_tail[DETECT_SM_LIST_MATCH]->ctx; FAIL_IF(data->flags != flags); - FAIL_IF(data->nlocations!=ncountries); + FAIL_IF(data->nlocations != ncountries); - for (int i=0; ilocation[i],countries[i])!=0); + for (int i = 0; i < ncountries; i++) { + FAIL_IF(strcmp((char *)data->location[i], countries[i]) != 0); } DetectEngineCtxFree(de_ctx); @@ -480,51 +468,51 @@ static int GeoipParseTest(const char *rule, int ncountries, const char **countri static int GeoipParseTest01(void) { - const char *ccodes[1] = {"US"}; - return GeoipParseTest("alert tcp any any -> any any (geoip:US;sid:1;)", 1, ccodes, - GEOIP_MATCH_ANY_FLAG); + const char *ccodes[1] = { "US" }; + return GeoipParseTest( + "alert tcp any any -> any any (geoip:US;sid:1;)", 1, ccodes, GEOIP_MATCH_ANY_FLAG); } static int GeoipParseTest02(void) { - const char *ccodes[1] = {"US"}; + const char *ccodes[1] = { "US" }; return GeoipParseTest("alert tcp any any -> any any (geoip:!US;sid:1;)", 1, ccodes, - GEOIP_MATCH_ANY_FLAG | GEOIP_MATCH_NEGATED); + GEOIP_MATCH_ANY_FLAG | GEOIP_MATCH_NEGATED); } static int GeoipParseTest03(void) { - const char *ccodes[1] = {"US"}; + const char *ccodes[1] = { "US" }; return GeoipParseTest("alert tcp any any -> any any (geoip:!US;sid:1;)", 1, ccodes, - GEOIP_MATCH_ANY_FLAG | GEOIP_MATCH_NEGATED); + GEOIP_MATCH_ANY_FLAG | GEOIP_MATCH_NEGATED); } static int GeoipParseTest04(void) { - const char *ccodes[1] = {"US"}; - return GeoipParseTest("alert tcp any any -> any any (geoip:src,US;sid:1;)", 1, ccodes, - GEOIP_MATCH_SRC_FLAG); + const char *ccodes[1] = { "US" }; + return GeoipParseTest( + "alert tcp any any -> any any (geoip:src,US;sid:1;)", 1, ccodes, GEOIP_MATCH_SRC_FLAG); } static int GeoipParseTest05(void) { - const char *ccodes[1] = {"US"}; + const char *ccodes[1] = { "US" }; return GeoipParseTest("alert tcp any any -> any any (geoip:dst,!US;sid:1;)", 1, ccodes, - GEOIP_MATCH_DST_FLAG | GEOIP_MATCH_NEGATED); + GEOIP_MATCH_DST_FLAG | GEOIP_MATCH_NEGATED); } static int GeoipParseTest06(void) { - const char *ccodes[3] = {"US", "ES", "UK"}; + const char *ccodes[3] = { "US", "ES", "UK" }; return GeoipParseTest("alert tcp any any -> any any (geoip:US,ES,UK;sid:1;)", 3, ccodes, - GEOIP_MATCH_ANY_FLAG); + GEOIP_MATCH_ANY_FLAG); } static int GeoipParseTest07(void) { - const char *ccodes[3] = {"US", "ES", "UK"}; + const char *ccodes[3] = { "US", "ES", "UK" }; return GeoipParseTest("alert tcp any any -> any any (geoip:both,!US,ES,UK;sid:1;)", 3, ccodes, - GEOIP_MATCH_BOTH_FLAG | GEOIP_MATCH_NEGATED); + GEOIP_MATCH_BOTH_FLAG | GEOIP_MATCH_NEGATED); } /** diff --git a/src/detect-geoip.h b/src/detect-geoip.h index 4ec97b5df868..911c89f5d2b7 100644 --- a/src/detect-geoip.h +++ b/src/detect-geoip.h @@ -29,12 +29,13 @@ #include -#define GEOOPTION_MAXSIZE 3 /* Country Code (2 chars) + NULL */ +#define GEOOPTION_MAXSIZE 3 /* Country Code (2 chars) + NULL */ #define GEOOPTION_MAXLOCATIONS 64 typedef struct DetectGeoipData_ { - uint8_t location[GEOOPTION_MAXLOCATIONS][GEOOPTION_MAXSIZE]; /** country code for now, null term.*/ - int nlocations; /** number of location strings parsed */ + uint8_t location[GEOOPTION_MAXLOCATIONS] + [GEOOPTION_MAXSIZE]; /** country code for now, null term.*/ + int nlocations; /** number of location strings parsed */ uint32_t flags; int mmdb_status; /** Status of DB open call, MMDB_SUCCESS or error */ MMDB_s mmdb; /** MaxMind DB file handle structure */ diff --git a/src/detect-gid.c b/src/detect-gid.c index a278edbc2666..bb2734c217bb 100644 --- a/src/detect-gid.c +++ b/src/detect-gid.c @@ -36,7 +36,7 @@ #include "util-unittest.h" #include "util-debug.h" -static int DetectGidSetup (DetectEngineCtx *, Signature *, const char *); +static int DetectGidSetup(DetectEngineCtx *, Signature *, const char *); #ifdef UNITTESTS static void GidRegisterTests(void); #endif @@ -45,14 +45,14 @@ static void GidRegisterTests(void); * \brief Registration function for gid: keyword */ -void DetectGidRegister (void) +void DetectGidRegister(void) { sigmatch_table[DETECT_GID].name = "gid"; sigmatch_table[DETECT_GID].desc = "give different groups of signatures another id value"; sigmatch_table[DETECT_GID].url = "/rules/meta.html#gid-group-id"; sigmatch_table[DETECT_GID].Match = NULL; sigmatch_table[DETECT_GID].Setup = DetectGidSetup; - sigmatch_table[DETECT_GID].Free = NULL; + sigmatch_table[DETECT_GID].Free = NULL; #ifdef UNITTESTS sigmatch_table[DETECT_GID].RegisterTests = GidRegisterTests; #endif @@ -69,7 +69,7 @@ void DetectGidRegister (void) * \retval 0 on Success * \retval -1 on Failure */ -static int DetectGidSetup (DetectEngineCtx *de_ctx, Signature *s, const char *rawstr) +static int DetectGidSetup(DetectEngineCtx *de_ctx, Signature *s, const char *rawstr) { unsigned long gid = 0; char *endptr = NULL; @@ -88,7 +88,7 @@ static int DetectGidSetup (DetectEngineCtx *de_ctx, Signature *s, const char *ra return 0; - error: +error: return -1; } @@ -100,7 +100,7 @@ static int DetectGidSetup (DetectEngineCtx *de_ctx, Signature *s, const char *ra /** * \test GidTestParse01 is a test for a valid gid value */ -static int GidTestParse01 (void) +static int GidTestParse01(void) { DetectEngineCtx *de_ctx = DetectEngineCtxInit(); FAIL_IF_NULL(de_ctx); @@ -118,7 +118,7 @@ static int GidTestParse01 (void) /** * \test GidTestParse02 is a test for an invalid gid value */ -static int GidTestParse02 (void) +static int GidTestParse02(void) { DetectEngineCtx *de_ctx = DetectEngineCtxInit(); FAIL_IF_NULL(de_ctx); @@ -133,7 +133,7 @@ static int GidTestParse02 (void) /** * \test Test a gid consisting of a single quote. */ -static int GidTestParse03 (void) +static int GidTestParse03(void) { DetectEngineCtx *de_ctx = DetectEngineCtxInit(); FAIL_IF_NULL(de_ctx); diff --git a/src/detect-gid.h b/src/detect-gid.h index fa714ef8f5cf..f952d8cbc78f 100644 --- a/src/detect-gid.h +++ b/src/detect-gid.h @@ -26,11 +26,10 @@ #ifndef __DETECT_GID_H__ #define __DETECT_GID_H__ - /** * Registration function for gid: keyword */ -void DetectGidRegister (void); +void DetectGidRegister(void); #endif /*__DETECT_GID_H__ */ \ No newline at end of file diff --git a/src/detect-hostbits.c b/src/detect-hostbits.c index 571510325aea..5dd70af1665d 100644 --- a/src/detect-hostbits.c +++ b/src/detect-hostbits.c @@ -69,22 +69,22 @@ "(.+)?" /* Any remaining data. */ static DetectParseRegex parse_regex; -static int DetectHostbitMatch (DetectEngineThreadCtx *, Packet *, - const Signature *, const SigMatchCtx *); -static int DetectHostbitSetup (DetectEngineCtx *, Signature *, const char *); -void DetectHostbitFree (DetectEngineCtx *, void *); +static int DetectHostbitMatch( + DetectEngineThreadCtx *, Packet *, const Signature *, const SigMatchCtx *); +static int DetectHostbitSetup(DetectEngineCtx *, Signature *, const char *); +void DetectHostbitFree(DetectEngineCtx *, void *); #ifdef UNITTESTS void HostBitsRegisterTests(void); #endif -void DetectHostbitsRegister (void) +void DetectHostbitsRegister(void) { sigmatch_table[DETECT_HOSTBITS].name = "hostbits"; sigmatch_table[DETECT_HOSTBITS].desc = "operate on host flag"; -// sigmatch_table[DETECT_HOSTBITS].url = "/rules/flow-keywords.html#flowbits"; + // sigmatch_table[DETECT_HOSTBITS].url = "/rules/flow-keywords.html#flowbits"; sigmatch_table[DETECT_HOSTBITS].Match = DetectHostbitMatch; sigmatch_table[DETECT_HOSTBITS].Setup = DetectHostbitSetup; - sigmatch_table[DETECT_HOSTBITS].Free = DetectHostbitFree; + sigmatch_table[DETECT_HOSTBITS].Free = DetectHostbitFree; #ifdef UNITTESTS sigmatch_table[DETECT_HOSTBITS].RegisterTests = HostBitsRegisterTests; #endif @@ -94,7 +94,7 @@ void DetectHostbitsRegister (void) DetectSetupParseRegexes(PARSE_REGEX, &parse_regex); } -static int DetectHostbitMatchToggle (Packet *p, const DetectXbitsData *fd) +static int DetectHostbitMatchToggle(Packet *p, const DetectXbitsData *fd) { switch (fd->tracker) { case DETECT_XBITS_TRACK_IPSRC: @@ -102,8 +102,7 @@ static int DetectHostbitMatchToggle (Packet *p, const DetectXbitsData *fd) p->host_src = HostGetHostFromHash(&p->src); if (p->host_src == NULL) return 0; - } - else + } else HostLock(p->host_src); HostBitToggle(p->host_src, fd->idx, SCTIME_SECS(p->ts) + fd->expire); @@ -114,8 +113,7 @@ static int DetectHostbitMatchToggle (Packet *p, const DetectXbitsData *fd) p->host_dst = HostGetHostFromHash(&p->dst); if (p->host_dst == NULL) return 0; - } - else + } else HostLock(p->host_dst); HostBitToggle(p->host_dst, fd->idx, SCTIME_SECS(p->ts) + fd->expire); @@ -126,7 +124,7 @@ static int DetectHostbitMatchToggle (Packet *p, const DetectXbitsData *fd) } /* return true even if bit not found */ -static int DetectHostbitMatchUnset (Packet *p, const DetectXbitsData *fd) +static int DetectHostbitMatchUnset(Packet *p, const DetectXbitsData *fd) { switch (fd->tracker) { case DETECT_XBITS_TRACK_IPSRC: @@ -137,7 +135,7 @@ static int DetectHostbitMatchUnset (Packet *p, const DetectXbitsData *fd) } else HostLock(p->host_src); - HostBitUnset(p->host_src,fd->idx); + HostBitUnset(p->host_src, fd->idx); HostUnlock(p->host_src); break; case DETECT_XBITS_TRACK_IPDST: @@ -148,14 +146,14 @@ static int DetectHostbitMatchUnset (Packet *p, const DetectXbitsData *fd) } else HostLock(p->host_dst); - HostBitUnset(p->host_dst,fd->idx); + HostBitUnset(p->host_dst, fd->idx); HostUnlock(p->host_dst); break; } return 1; } -static int DetectHostbitMatchSet (Packet *p, const DetectXbitsData *fd) +static int DetectHostbitMatchSet(Packet *p, const DetectXbitsData *fd) { switch (fd->tracker) { case DETECT_XBITS_TRACK_IPSRC: @@ -184,7 +182,7 @@ static int DetectHostbitMatchSet (Packet *p, const DetectXbitsData *fd) return 1; } -static int DetectHostbitMatchIsset (Packet *p, const DetectXbitsData *fd) +static int DetectHostbitMatchIsset(Packet *p, const DetectXbitsData *fd) { int r = 0; switch (fd->tracker) { @@ -214,7 +212,7 @@ static int DetectHostbitMatchIsset (Packet *p, const DetectXbitsData *fd) return 0; } -static int DetectHostbitMatchIsnotset (Packet *p, const DetectXbitsData *fd) +static int DetectHostbitMatchIsnotset(Packet *p, const DetectXbitsData *fd) { int r = 0; switch (fd->tracker) { @@ -248,15 +246,15 @@ int DetectXbitMatchHost(Packet *p, const DetectXbitsData *xd) { switch (xd->cmd) { case DETECT_XBITS_CMD_ISSET: - return DetectHostbitMatchIsset(p,xd); + return DetectHostbitMatchIsset(p, xd); case DETECT_XBITS_CMD_ISNOTSET: - return DetectHostbitMatchIsnotset(p,xd); + return DetectHostbitMatchIsnotset(p, xd); case DETECT_XBITS_CMD_SET: - return DetectHostbitMatchSet(p,xd); + return DetectHostbitMatchSet(p, xd); case DETECT_XBITS_CMD_UNSET: - return DetectHostbitMatchUnset(p,xd); + return DetectHostbitMatchUnset(p, xd); case DETECT_XBITS_CMD_TOGGLE: - return DetectHostbitMatchToggle(p,xd); + return DetectHostbitMatchToggle(p, xd); default: SCLogError("unknown cmd %" PRIu32 "", xd->cmd); return 0; @@ -271,8 +269,8 @@ int DetectXbitMatchHost(Packet *p, const DetectXbitsData *xd) * -1: error */ -static int DetectHostbitMatch (DetectEngineThreadCtx *det_ctx, Packet *p, - const Signature *s, const SigMatchCtx *ctx) +static int DetectHostbitMatch( + DetectEngineThreadCtx *det_ctx, Packet *p, const Signature *s, const SigMatchCtx *ctx) { const DetectXbitsData *xd = (const DetectXbitsData *)ctx; if (xd == NULL) @@ -281,8 +279,8 @@ static int DetectHostbitMatch (DetectEngineThreadCtx *det_ctx, Packet *p, return DetectXbitMatchHost(p, xd); } -static int DetectHostbitParse(const char *str, char *cmd, int cmd_len, - char *name, int name_len, char *dir, int dir_len) +static int DetectHostbitParse( + const char *str, char *cmd, int cmd_len, char *name, int name_len, char *dir, int dir_len) { int rc; size_t pcre2len; @@ -328,7 +326,7 @@ static int DetectHostbitParse(const char *str, char *cmd, int cmd_len, return 0; } -int DetectHostbitSetup (DetectEngineCtx *de_ctx, Signature *s, const char *rawstr) +int DetectHostbitSetup(DetectEngineCtx *de_ctx, Signature *s, const char *rawstr) { DetectXbitsData *cd = NULL; uint8_t fb_cmd = 0; @@ -336,8 +334,8 @@ int DetectHostbitSetup (DetectEngineCtx *de_ctx, Signature *s, const char *rawst char fb_cmd_str[16] = "", fb_name[256] = ""; char hb_dir_str[16] = ""; - if (!DetectHostbitParse(rawstr, fb_cmd_str, sizeof(fb_cmd_str), - fb_name, sizeof(fb_name), hb_dir_str, sizeof(hb_dir_str))) { + if (!DetectHostbitParse(rawstr, fb_cmd_str, sizeof(fb_cmd_str), fb_name, sizeof(fb_name), + hb_dir_str, sizeof(hb_dir_str))) { return -1; } @@ -347,7 +345,7 @@ int DetectHostbitSetup (DetectEngineCtx *de_ctx, Signature *s, const char *rawst else if (strcmp(hb_dir_str, "dst") == 0) hb_dir = DETECT_XBITS_TRACK_IPDST; else if (strcmp(hb_dir_str, "both") == 0) { - //hb_dir = DETECT_XBITS_TRACK_IPBOTH; + // hb_dir = DETECT_XBITS_TRACK_IPBOTH; SCLogError("'both' not implemented"); goto error; } else { @@ -356,17 +354,17 @@ int DetectHostbitSetup (DetectEngineCtx *de_ctx, Signature *s, const char *rawst } } - if (strcmp(fb_cmd_str,"noalert") == 0) { + if (strcmp(fb_cmd_str, "noalert") == 0) { fb_cmd = DETECT_XBITS_CMD_NOALERT; - } else if (strcmp(fb_cmd_str,"isset") == 0) { + } else if (strcmp(fb_cmd_str, "isset") == 0) { fb_cmd = DETECT_XBITS_CMD_ISSET; - } else if (strcmp(fb_cmd_str,"isnotset") == 0) { + } else if (strcmp(fb_cmd_str, "isnotset") == 0) { fb_cmd = DETECT_XBITS_CMD_ISNOTSET; - } else if (strcmp(fb_cmd_str,"set") == 0) { + } else if (strcmp(fb_cmd_str, "set") == 0) { fb_cmd = DETECT_XBITS_CMD_SET; - } else if (strcmp(fb_cmd_str,"unset") == 0) { + } else if (strcmp(fb_cmd_str, "unset") == 0) { fb_cmd = DETECT_XBITS_CMD_UNSET; - } else if (strcmp(fb_cmd_str,"toggle") == 0) { + } else if (strcmp(fb_cmd_str, "toggle") == 0) { fb_cmd = DETECT_XBITS_CMD_TOGGLE; } else { SCLogError("ERROR: flowbits action \"%s\" is not supported.", fb_cmd_str); @@ -400,14 +398,14 @@ int DetectHostbitSetup (DetectEngineCtx *de_ctx, Signature *s, const char *rawst cd->type = VAR_TYPE_HOST_BIT; cd->expire = 300; - SCLogDebug("idx %" PRIu32 ", cmd %s, name %s", - cd->idx, fb_cmd_str, strlen(fb_name) ? fb_name : "(none)"); + SCLogDebug("idx %" PRIu32 ", cmd %s, name %s", cd->idx, fb_cmd_str, + strlen(fb_name) ? fb_name : "(none)"); /* Okay so far so good, lets get this into a SigMatch * and put it in the Signature. */ switch (fb_cmd) { - /* case DETECT_XBITS_CMD_NOALERT can't happen here */ + /* case DETECT_XBITS_CMD_NOALERT can't happen here */ case DETECT_XBITS_CMD_ISNOTSET: case DETECT_XBITS_CMD_ISSET: @@ -442,7 +440,7 @@ int DetectHostbitSetup (DetectEngineCtx *de_ctx, Signature *s, const char *rawst return -1; } -void DetectHostbitFree (DetectEngineCtx *de_ctx, void *ptr) +void DetectHostbitFree(DetectEngineCtx *de_ctx, void *ptr) { DetectXbitsData *fd = (DetectXbitsData *)ptr; @@ -474,8 +472,8 @@ static int HostBitsTestParse01(void) char cmd[16] = "", name[256] = "", dir[16] = ""; /* No direction. */ - FAIL_IF(!DetectHostbitParse("isset,name", cmd, sizeof(cmd), name, - sizeof(name), dir, sizeof(dir))); + FAIL_IF(!DetectHostbitParse( + "isset,name", cmd, sizeof(cmd), name, sizeof(name), dir, sizeof(dir))); FAIL_IF(strcmp(cmd, "isset") != 0); FAIL_IF(strcmp(name, "name") != 0); FAIL_IF(strlen(dir)); @@ -484,8 +482,8 @@ static int HostBitsTestParse01(void) *cmd = '\0'; *name = '\0'; *dir = '\0'; - FAIL_IF(!DetectHostbitParse("isset, name", cmd, sizeof(cmd), name, - sizeof(name), dir, sizeof(dir))); + FAIL_IF(!DetectHostbitParse( + "isset, name", cmd, sizeof(cmd), name, sizeof(name), dir, sizeof(dir))); FAIL_IF(strcmp(cmd, "isset") != 0); FAIL_IF(strcmp(name, "name") != 0); @@ -493,8 +491,8 @@ static int HostBitsTestParse01(void) *cmd = '\0'; *name = '\0'; *dir = '\0'; - FAIL_IF(!DetectHostbitParse("isset,name ", cmd, sizeof(cmd), name, - sizeof(name), dir, sizeof(dir))); + FAIL_IF(!DetectHostbitParse( + "isset,name ", cmd, sizeof(cmd), name, sizeof(name), dir, sizeof(dir))); FAIL_IF(strcmp(cmd, "isset") != 0); FAIL_IF(strcmp(name, "name") != 0); @@ -502,8 +500,8 @@ static int HostBitsTestParse01(void) *cmd = '\0'; *name = '\0'; *dir = '\0'; - FAIL_IF(!DetectHostbitParse("isset, name ", cmd, sizeof(cmd), name, - sizeof(name), dir, sizeof(dir))); + FAIL_IF(!DetectHostbitParse( + "isset, name ", cmd, sizeof(cmd), name, sizeof(name), dir, sizeof(dir))); FAIL_IF(strcmp(cmd, "isset") != 0); FAIL_IF(strcmp(name, "name") != 0); @@ -511,8 +509,8 @@ static int HostBitsTestParse01(void) *cmd = '\0'; *name = '\0'; *dir = '\0'; - FAIL_IF(!DetectHostbitParse("isset,name,src", cmd, sizeof(cmd), name, - sizeof(name), dir, sizeof(dir))); + FAIL_IF(!DetectHostbitParse( + "isset,name,src", cmd, sizeof(cmd), name, sizeof(name), dir, sizeof(dir))); FAIL_IF(strcmp(cmd, "isset") != 0); FAIL_IF(strcmp(name, "name") != 0); FAIL_IF(strcmp(dir, "src") != 0); @@ -521,8 +519,8 @@ static int HostBitsTestParse01(void) *cmd = '\0'; *name = '\0'; *dir = '\0'; - FAIL_IF(!DetectHostbitParse("isset, name ,src", cmd, sizeof(cmd), name, - sizeof(name), dir, sizeof(dir))); + FAIL_IF(!DetectHostbitParse( + "isset, name ,src", cmd, sizeof(cmd), name, sizeof(name), dir, sizeof(dir))); FAIL_IF(strcmp(cmd, "isset") != 0); FAIL_IF(strcmp(name, "name") != 0); FAIL_IF(strcmp(dir, "src") != 0); @@ -531,8 +529,8 @@ static int HostBitsTestParse01(void) *cmd = '\0'; *name = '\0'; *dir = '\0'; - FAIL_IF(!DetectHostbitParse("isset, name , src ", cmd, sizeof(cmd), name, - sizeof(name), dir, sizeof(dir))); + FAIL_IF(!DetectHostbitParse( + "isset, name , src ", cmd, sizeof(cmd), name, sizeof(name), dir, sizeof(dir))); FAIL_IF(strcmp(cmd, "isset") != 0); FAIL_IF(strcmp(name, "name") != 0); FAIL_IF(strcmp(dir, "src") != 0); @@ -541,8 +539,8 @@ static int HostBitsTestParse01(void) *cmd = '\0'; *name = '\0'; *dir = '\0'; - FAIL_IF(DetectHostbitParse("isset, name withspace ", cmd, sizeof(cmd), name, - sizeof(name), dir, sizeof(dir))); + FAIL_IF(DetectHostbitParse( + "isset, name withspace ", cmd, sizeof(cmd), name, sizeof(name), dir, sizeof(dir))); PASS; } @@ -556,10 +554,9 @@ static int HostBitsTestParse01(void) static int HostBitsTestSig01(void) { - uint8_t *buf = (uint8_t *) - "GET /one/ HTTP/1.1\r\n" - "Host: one.example.org\r\n" - "\r\n"; + uint8_t *buf = (uint8_t *)"GET /one/ HTTP/1.1\r\n" + "Host: one.example.org\r\n" + "\r\n"; uint16_t buflen = strlen((char *)buf); Packet *p = PacketGetFromAlloc(); FAIL_IF_NULL(p); @@ -582,7 +579,8 @@ static int HostBitsTestSig01(void) de_ctx->flags |= DE_QUIET; - s = de_ctx->sig_list = SigInit(de_ctx,"alert ip any any -> any any (hostbits:set,abc; content:\"GET \"; sid:1;)"); + s = de_ctx->sig_list = SigInit( + de_ctx, "alert ip any any -> any any (hostbits:set,abc; content:\"GET \"; sid:1;)"); FAIL_IF_NULL(s); SigGroupBuild(de_ctx); @@ -629,11 +627,11 @@ static int HostBitsTestSig02(void) "alert ip any any -> any any (hostbits:!isset,abc,dst; content:\"GET \"; sid:3;)"); FAIL_IF_NOT_NULL(s); -/* TODO reenable after both is supported - s = DetectEngineAppendSig(de_ctx, - "alert ip any any -> any any (hostbits:set,abc,both; content:\"GET \"; sid:3;)"); - FAIL_IF_NULL(s); -*/ + /* TODO reenable after both is supported + s = DetectEngineAppendSig(de_ctx, + "alert ip any any -> any any (hostbits:set,abc,both; content:\"GET \"; sid:3;)"); + FAIL_IF_NULL(s); + */ s = DetectEngineAppendSig(de_ctx, "alert ip any any -> any any (hostbits:unset,abc,src; content:\"GET \"; sid:4;)"); FAIL_IF_NULL(s); @@ -655,10 +653,9 @@ static int HostBitsTestSig02(void) static int HostBitsTestSig03(void) { - uint8_t *buf = (uint8_t *) - "GET /one/ HTTP/1.1\r\n" - "Host: one.example.org\r\n" - "\r\n"; + uint8_t *buf = (uint8_t *)"GET /one/ HTTP/1.1\r\n" + "Host: one.example.org\r\n" + "\r\n"; uint16_t buflen = strlen((char *)buf); Packet *p = PacketGetFromAlloc(); if (unlikely(p == NULL)) @@ -683,7 +680,8 @@ static int HostBitsTestSig03(void) de_ctx->flags |= DE_QUIET; - s = de_ctx->sig_list = SigInit(de_ctx,"alert ip any any -> any any (msg:\"isset option\"; hostbits:isset,fbt; content:\"GET \"; sid:1;)"); + s = de_ctx->sig_list = SigInit(de_ctx, "alert ip any any -> any any (msg:\"isset option\"; " + "hostbits:isset,fbt; content:\"GET \"; sid:1;)"); FAIL_IF_NULL(s); idx = VarNameStoreRegister("fbt", VAR_TYPE_HOST_BIT); diff --git a/src/detect-hostbits.h b/src/detect-hostbits.h index 6e9c7f5f0e42..f6df2143b27f 100644 --- a/src/detect-hostbits.h +++ b/src/detect-hostbits.h @@ -29,6 +29,6 @@ int DetectXbitMatchHost(Packet *p, const DetectXbitsData *xd); /* prototypes */ -void DetectHostbitsRegister (void); +void DetectHostbitsRegister(void); #endif /* __DETECT_HOSTBITS_H__ */ diff --git a/src/detect-http-accept-enc.c b/src/detect-http-accept-enc.c index 277e7142a278..41420d1e0a9a 100644 --- a/src/detect-http-accept-enc.c +++ b/src/detect-http-accept-enc.c @@ -21,7 +21,6 @@ * @{ */ - /** * \file * @@ -31,13 +30,13 @@ */ #define KEYWORD_NAME_LEGACY "http_accept_enc" -#define KEYWORD_NAME "http.accept_enc" -#define KEYWORD_DOC "http-keywords.html#http-accept-enc" -#define BUFFER_NAME "http_accept_enc" -#define BUFFER_DESC "http accept encoding header" -#define HEADER_NAME "Accept-Encoding" -#define KEYWORD_ID DETECT_AL_HTTP_HEADER_ACCEPT_ENC -#define KEYWORD_TOSERVER 1 +#define KEYWORD_NAME "http.accept_enc" +#define KEYWORD_DOC "http-keywords.html#http-accept-enc" +#define BUFFER_NAME "http_accept_enc" +#define BUFFER_DESC "http accept encoding header" +#define HEADER_NAME "Accept-Encoding" +#define KEYWORD_ID DETECT_AL_HTTP_HEADER_ACCEPT_ENC +#define KEYWORD_TOSERVER 1 #include "detect-http-headers-stub.h" #include "detect-http-accept-enc.h" diff --git a/src/detect-http-accept-lang.c b/src/detect-http-accept-lang.c index c83847e69a9e..db5b701fd017 100644 --- a/src/detect-http-accept-lang.c +++ b/src/detect-http-accept-lang.c @@ -21,7 +21,6 @@ * @{ */ - /** * \file * @@ -31,13 +30,13 @@ */ #define KEYWORD_NAME_LEGACY "http_accept_lang" -#define KEYWORD_NAME "http.accept_lang" -#define KEYWORD_DOC "http-keywords.html#http-accept-lang" -#define BUFFER_NAME "http_accept_lang" -#define BUFFER_DESC "http accept language header" -#define HEADER_NAME "Accept-Language" -#define KEYWORD_ID DETECT_AL_HTTP_HEADER_ACCEPT_LANG -#define KEYWORD_TOSERVER 1 +#define KEYWORD_NAME "http.accept_lang" +#define KEYWORD_DOC "http-keywords.html#http-accept-lang" +#define BUFFER_NAME "http_accept_lang" +#define BUFFER_DESC "http accept language header" +#define HEADER_NAME "Accept-Language" +#define KEYWORD_ID DETECT_AL_HTTP_HEADER_ACCEPT_LANG +#define KEYWORD_TOSERVER 1 #include "detect-http-headers-stub.h" #include "detect-http-accept-lang.h" diff --git a/src/detect-http-accept.c b/src/detect-http-accept.c index db6bec4455ca..b027bd9cfbd5 100644 --- a/src/detect-http-accept.c +++ b/src/detect-http-accept.c @@ -21,7 +21,6 @@ * @{ */ - /** * \file * @@ -31,13 +30,13 @@ */ #define KEYWORD_NAME_LEGACY "http_accept" -#define KEYWORD_NAME "http.accept" -#define KEYWORD_DOC "http-keywords.html#http-accept" -#define BUFFER_NAME "http_accept" -#define BUFFER_DESC "http accept header" -#define HEADER_NAME "Accept" -#define KEYWORD_ID DETECT_AL_HTTP_HEADER_ACCEPT -#define KEYWORD_TOSERVER 1 +#define KEYWORD_NAME "http.accept" +#define KEYWORD_DOC "http-keywords.html#http-accept" +#define BUFFER_NAME "http_accept" +#define BUFFER_DESC "http accept header" +#define HEADER_NAME "Accept" +#define KEYWORD_ID DETECT_AL_HTTP_HEADER_ACCEPT +#define KEYWORD_TOSERVER 1 #include "detect-http-headers-stub.h" #include "detect-http-accept.h" diff --git a/src/detect-http-client-body.c b/src/detect-http-client-body.c index 1d3d7a87cc88..0006c35ec958 100644 --- a/src/detect-http-client-body.c +++ b/src/detect-http-client-body.c @@ -21,7 +21,6 @@ * @{ */ - /** * \file * @@ -67,8 +66,7 @@ static int DetectHttpClientBodySetupSticky(DetectEngineCtx *de_ctx, Signature *s #ifdef UNITTESTS static void DetectHttpClientBodyRegisterTests(void); #endif -static void DetectHttpClientBodySetupCallback(const DetectEngineCtx *de_ctx, - Signature *s); +static void DetectHttpClientBodySetupCallback(const DetectEngineCtx *de_ctx, Signature *s); static int g_http_client_body_buffer_id = 0; static uint8_t DetectEngineInspectBufferHttpBody(DetectEngineCtx *de_ctx, @@ -85,19 +83,21 @@ void DetectHttpClientBodyRegister(void) { /* http_client_body content modifier */ sigmatch_table[DETECT_AL_HTTP_CLIENT_BODY].name = "http_client_body"; - sigmatch_table[DETECT_AL_HTTP_CLIENT_BODY].desc = "content modifier to match only on HTTP request-body"; + sigmatch_table[DETECT_AL_HTTP_CLIENT_BODY].desc = + "content modifier to match only on HTTP request-body"; sigmatch_table[DETECT_AL_HTTP_CLIENT_BODY].url = "/rules/http-keywords.html#http-client-body"; sigmatch_table[DETECT_AL_HTTP_CLIENT_BODY].Setup = DetectHttpClientBodySetup; #ifdef UNITTESTS sigmatch_table[DETECT_AL_HTTP_CLIENT_BODY].RegisterTests = DetectHttpClientBodyRegisterTests; #endif - sigmatch_table[DETECT_AL_HTTP_CLIENT_BODY].flags |= SIGMATCH_NOOPT ; + sigmatch_table[DETECT_AL_HTTP_CLIENT_BODY].flags |= SIGMATCH_NOOPT; sigmatch_table[DETECT_AL_HTTP_CLIENT_BODY].flags |= SIGMATCH_INFO_CONTENT_MODIFIER; sigmatch_table[DETECT_AL_HTTP_CLIENT_BODY].alternative = DETECT_HTTP_REQUEST_BODY; /* http.request_body sticky buffer */ sigmatch_table[DETECT_HTTP_REQUEST_BODY].name = "http.request_body"; - sigmatch_table[DETECT_HTTP_REQUEST_BODY].desc = "sticky buffer to match the HTTP request body buffer"; + sigmatch_table[DETECT_HTTP_REQUEST_BODY].desc = + "sticky buffer to match the HTTP request body buffer"; sigmatch_table[DETECT_HTTP_REQUEST_BODY].url = "/rules/http-keywords.html#http-client-body"; sigmatch_table[DETECT_HTTP_REQUEST_BODY].Setup = DetectHttpClientBodySetupSticky; sigmatch_table[DETECT_HTTP_REQUEST_BODY].flags |= SIGMATCH_NOOPT; @@ -114,17 +114,14 @@ void DetectHttpClientBodyRegister(void) DetectAppLayerMpmRegister2("http_client_body", SIG_FLAG_TOSERVER, 2, PrefilterMpmFiledataRegister, NULL, ALPROTO_HTTP2, HTTP2StateDataClient); - DetectBufferTypeSetDescriptionByName("http_client_body", - "http request body"); + DetectBufferTypeSetDescriptionByName("http_client_body", "http request body"); - DetectBufferTypeRegisterSetupCallback("http_client_body", - DetectHttpClientBodySetupCallback); + DetectBufferTypeRegisterSetupCallback("http_client_body", DetectHttpClientBodySetupCallback); g_http_client_body_buffer_id = DetectBufferTypeGetByName("http_client_body"); } -static void DetectHttpClientBodySetupCallback(const DetectEngineCtx *de_ctx, - Signature *s) +static void DetectHttpClientBodySetupCallback(const DetectEngineCtx *de_ctx, Signature *s) { SCLogDebug("callback invoked by %u", s->id); AppLayerHtpEnableRequestBodyCallback(); @@ -251,7 +248,7 @@ static InspectionBuffer *HttpRequestBodyGetDataCallback(DetectEngineThreadCtx *d if (!htp_state->cfg->http_body_inline) { /* inspect the body if the transfer is complete or we have hit - * our body size limit */ + * our body size limit */ if ((htp_state->cfg->request.body_limit == 0 || body->content_len_so_far < htp_state->cfg->request.body_limit) && body->content_len_so_far < htp_state->cfg->request.inspect_min_size && @@ -275,7 +272,7 @@ static InspectionBuffer *HttpRequestBodyGetDataCallback(DetectEngineThreadCtx *d if (body->body_inspected > htp_state->cfg->request.inspect_min_size) { BUG_ON(body->content_len_so_far < body->body_inspected); uint64_t inspect_win = body->content_len_so_far - body->body_inspected; - SCLogDebug("inspect_win %"PRIu64, inspect_win); + SCLogDebug("inspect_win %" PRIu64, inspect_win); if (inspect_win < htp_state->cfg->request.inspect_window) { uint64_t inspect_short = htp_state->cfg->request.inspect_window - inspect_win; if (body->body_inspected < inspect_short) @@ -290,8 +287,7 @@ static InspectionBuffer *HttpRequestBodyGetDataCallback(DetectEngineThreadCtx *d const uint8_t *data; uint32_t data_len; - StreamingBufferGetDataAtOffset(body->sb, - &data, &data_len, offset); + StreamingBufferGetDataAtOffset(body->sb, &data, &data_len, offset); InspectionBufferSetup(det_ctx, base_id, buffer, data, data_len); buffer->inspect_offset = offset; body->body_inspected = body->content_len_so_far; diff --git a/src/detect-http-connection.c b/src/detect-http-connection.c index 2db451236721..2b8e4d67b925 100644 --- a/src/detect-http-connection.c +++ b/src/detect-http-connection.c @@ -21,7 +21,6 @@ * @{ */ - /** * \file * @@ -31,13 +30,13 @@ */ #define KEYWORD_NAME_LEGACY "http_connection" -#define KEYWORD_NAME "http.connection" -#define KEYWORD_DOC "http-keywords.html#http-connection" -#define BUFFER_NAME "http_connection" -#define BUFFER_DESC "http connection header" -#define HEADER_NAME "Connection" -#define KEYWORD_ID DETECT_AL_HTTP_HEADER_CONNECTION -#define KEYWORD_TOSERVER 1 +#define KEYWORD_NAME "http.connection" +#define KEYWORD_DOC "http-keywords.html#http-connection" +#define BUFFER_NAME "http_connection" +#define BUFFER_DESC "http connection header" +#define HEADER_NAME "Connection" +#define KEYWORD_ID DETECT_AL_HTTP_HEADER_CONNECTION +#define KEYWORD_TOSERVER 1 #define KEYWORD_TOCLIENT 1 #include "detect-http-headers-stub.h" diff --git a/src/detect-http-content-len.c b/src/detect-http-content-len.c index b9203e2c738d..26cf44ac1d85 100644 --- a/src/detect-http-content-len.c +++ b/src/detect-http-content-len.c @@ -21,7 +21,6 @@ * @{ */ - /** * \file * @@ -31,14 +30,14 @@ */ #define KEYWORD_NAME_LEGACY "http_content_len" -#define KEYWORD_NAME "http.content_len" -#define KEYWORD_DOC "http-keywords.html#http-content-len" -#define BUFFER_NAME "http_content_len" -#define BUFFER_DESC "http content length header" -#define HEADER_NAME "Content-Length" -#define KEYWORD_ID DETECT_AL_HTTP_HEADER_CONTENT_LEN -#define KEYWORD_TOSERVER 1 -#define KEYWORD_TOCLIENT 1 +#define KEYWORD_NAME "http.content_len" +#define KEYWORD_DOC "http-keywords.html#http-content-len" +#define BUFFER_NAME "http_content_len" +#define BUFFER_DESC "http content length header" +#define HEADER_NAME "Content-Length" +#define KEYWORD_ID DETECT_AL_HTTP_HEADER_CONTENT_LEN +#define KEYWORD_TOSERVER 1 +#define KEYWORD_TOCLIENT 1 #include "detect-http-headers-stub.h" #include "detect-http-content-len.h" diff --git a/src/detect-http-content-type.c b/src/detect-http-content-type.c index 66d5b9567519..d1c37f1a0280 100644 --- a/src/detect-http-content-type.c +++ b/src/detect-http-content-type.c @@ -21,7 +21,6 @@ * @{ */ - /** * \file * @@ -31,14 +30,14 @@ */ #define KEYWORD_NAME_LEGACY "http_content_type" -#define KEYWORD_NAME "http.content_type" -#define KEYWORD_DOC "http-keywords.html#http-content-type" -#define BUFFER_NAME "http_content_type" -#define BUFFER_DESC "http content type header" -#define HEADER_NAME "Content-Type" -#define KEYWORD_ID DETECT_AL_HTTP_HEADER_CONTENT_TYPE -#define KEYWORD_TOSERVER 1 -#define KEYWORD_TOCLIENT 1 +#define KEYWORD_NAME "http.content_type" +#define KEYWORD_DOC "http-keywords.html#http-content-type" +#define BUFFER_NAME "http_content_type" +#define BUFFER_DESC "http content type header" +#define HEADER_NAME "Content-Type" +#define KEYWORD_ID DETECT_AL_HTTP_HEADER_CONTENT_TYPE +#define KEYWORD_TOSERVER 1 +#define KEYWORD_TOCLIENT 1 #include "detect-http-headers-stub.h" #include "detect-http-content-type.h" diff --git a/src/detect-http-cookie.c b/src/detect-http-cookie.c index e2754138fd44..d663d3a47221 100644 --- a/src/detect-http-cookie.c +++ b/src/detect-http-cookie.c @@ -21,7 +21,6 @@ * @{ */ - /** * \file * @@ -60,21 +59,19 @@ #include "detect-http-cookie.h" #include "stream-tcp.h" -static int DetectHttpCookieSetup (DetectEngineCtx *, Signature *, const char *); -static int DetectHttpCookieSetupSticky (DetectEngineCtx *, Signature *, const char *); +static int DetectHttpCookieSetup(DetectEngineCtx *, Signature *, const char *); +static int DetectHttpCookieSetupSticky(DetectEngineCtx *, Signature *, const char *); #ifdef UNITTESTS static void DetectHttpCookieRegisterTests(void); #endif static int g_http_cookie_buffer_id = 0; static InspectionBuffer *GetRequestData(DetectEngineThreadCtx *det_ctx, - const DetectEngineTransforms *transforms, - Flow *_f, const uint8_t _flow_flags, - void *txv, const int list_id); + const DetectEngineTransforms *transforms, Flow *_f, const uint8_t _flow_flags, void *txv, + const int list_id); static InspectionBuffer *GetResponseData(DetectEngineThreadCtx *det_ctx, - const DetectEngineTransforms *transforms, - Flow *_f, const uint8_t _flow_flags, - void *txv, const int list_id); + const DetectEngineTransforms *transforms, Flow *_f, const uint8_t _flow_flags, void *txv, + const int list_id); static InspectionBuffer *GetRequestData2(DetectEngineThreadCtx *det_ctx, const DetectEngineTransforms *transforms, Flow *_f, const uint8_t _flow_flags, void *txv, const int list_id); @@ -88,7 +85,8 @@ void DetectHttpCookieRegister(void) { /* http_cookie content modifier */ sigmatch_table[DETECT_AL_HTTP_COOKIE].name = "http_cookie"; - sigmatch_table[DETECT_AL_HTTP_COOKIE].desc = "content modifier to match only on the HTTP cookie-buffer"; + sigmatch_table[DETECT_AL_HTTP_COOKIE].desc = + "content modifier to match only on the HTTP cookie-buffer"; sigmatch_table[DETECT_AL_HTTP_COOKIE].url = "/rules/http-keywords.html#http-cookie"; sigmatch_table[DETECT_AL_HTTP_COOKIE].Setup = DetectHttpCookieSetup; #ifdef UNITTESTS @@ -100,7 +98,8 @@ void DetectHttpCookieRegister(void) /* http.cookie sticky buffer */ sigmatch_table[DETECT_HTTP_COOKIE].name = "http.cookie"; - sigmatch_table[DETECT_HTTP_COOKIE].desc = "sticky buffer to match on the HTTP Cookie/Set-Cookie buffers"; + sigmatch_table[DETECT_HTTP_COOKIE].desc = + "sticky buffer to match on the HTTP Cookie/Set-Cookie buffers"; sigmatch_table[DETECT_HTTP_COOKIE].url = "/rules/http-keywords.html#http-cookie"; sigmatch_table[DETECT_HTTP_COOKIE].Setup = DetectHttpCookieSetupSticky; sigmatch_table[DETECT_HTTP_COOKIE].flags |= SIGMATCH_NOOPT; @@ -126,8 +125,7 @@ void DetectHttpCookieRegister(void) DetectAppLayerMpmRegister2("http_cookie", SIG_FLAG_TOCLIENT, 2, PrefilterGenericMpmRegister, GetResponseData2, ALPROTO_HTTP2, HTTP2StateDataServer); - DetectBufferTypeSetDescriptionByName("http_cookie", - "http cookie header"); + DetectBufferTypeSetDescriptionByName("http_cookie", "http cookie header"); g_http_cookie_buffer_id = DetectBufferTypeGetByName("http_cookie"); } @@ -170,8 +168,8 @@ static int DetectHttpCookieSetupSticky(DetectEngineCtx *de_ctx, Signature *s, co } static InspectionBuffer *GetRequestData(DetectEngineThreadCtx *det_ctx, - const DetectEngineTransforms *transforms, Flow *_f, - const uint8_t _flow_flags, void *txv, const int list_id) + const DetectEngineTransforms *transforms, Flow *_f, const uint8_t _flow_flags, void *txv, + const int list_id) { InspectionBuffer *buffer = InspectionBufferGet(det_ctx, list_id); if (buffer->inspect == NULL) { @@ -180,8 +178,7 @@ static InspectionBuffer *GetRequestData(DetectEngineThreadCtx *det_ctx, if (tx->request_headers == NULL) return NULL; - htp_header_t *h = (htp_header_t *)htp_table_get_c(tx->request_headers, - "Cookie"); + htp_header_t *h = (htp_header_t *)htp_table_get_c(tx->request_headers, "Cookie"); if (h == NULL || h->value == NULL) { SCLogDebug("HTTP cookie header not present in this request"); return NULL; @@ -198,8 +195,8 @@ static InspectionBuffer *GetRequestData(DetectEngineThreadCtx *det_ctx, } static InspectionBuffer *GetResponseData(DetectEngineThreadCtx *det_ctx, - const DetectEngineTransforms *transforms, Flow *_f, - const uint8_t _flow_flags, void *txv, const int list_id) + const DetectEngineTransforms *transforms, Flow *_f, const uint8_t _flow_flags, void *txv, + const int list_id) { InspectionBuffer *buffer = InspectionBufferGet(det_ctx, list_id); if (buffer->inspect == NULL) { @@ -208,8 +205,7 @@ static InspectionBuffer *GetResponseData(DetectEngineThreadCtx *det_ctx, if (tx->response_headers == NULL) return NULL; - htp_header_t *h = (htp_header_t *)htp_table_get_c(tx->response_headers, - "Set-Cookie"); + htp_header_t *h = (htp_header_t *)htp_table_get_c(tx->response_headers, "Set-Cookie"); if (h == NULL || h->value == NULL) { SCLogDebug("HTTP cookie header not present in this request"); return NULL; diff --git a/src/detect-http-cookie.h b/src/detect-http-cookie.h index 0ed3fa5c66c7..10c1d5be1af8 100644 --- a/src/detect-http-cookie.h +++ b/src/detect-http-cookie.h @@ -22,10 +22,9 @@ */ #ifndef _DETECT_HTTP_COOKIE_H -#define _DETECT_HTTP_COOKIE_H +#define _DETECT_HTTP_COOKIE_H /* prototypes */ void DetectHttpCookieRegister(void); -#endif /* _DETECT_HTTP_COOKIE_H */ - +#endif /* _DETECT_HTTP_COOKIE_H */ diff --git a/src/detect-http-header-common.c b/src/detect-http-header-common.c index 401a50fcf54d..ff9c8a363b81 100644 --- a/src/detect-http-header-common.c +++ b/src/detect-http-header-common.c @@ -78,14 +78,13 @@ void HttpHeaderThreadDataFree(void *data) SCFree(hdrnames); } -int HttpHeaderExpandBuffer(HttpHeaderThreadData *td, - HttpHeaderBuffer *buf, uint32_t size) +int HttpHeaderExpandBuffer(HttpHeaderThreadData *td, HttpHeaderBuffer *buf, uint32_t size) { size_t extra = td->size_step; while ((buf->size + extra) < (size + buf->len)) { extra += td->size_step; } - SCLogDebug("adding %"PRIuMAX" to the buffer", (uintmax_t)extra); + SCLogDebug("adding %" PRIuMAX " to the buffer", (uintmax_t)extra); uint8_t *new_buffer = SCRealloc(buf->buffer, buf->size + extra); if (unlikely(new_buffer == NULL)) { @@ -102,8 +101,7 @@ HttpHeaderBuffer *HttpHeaderGetBufferSpace(DetectEngineThreadCtx *det_ctx, Flow { *ret_hdr_td = NULL; - HttpHeaderThreadData *hdr_td = - DetectThreadCtxGetGlobalKeywordThreadCtx(det_ctx, keyword_id); + HttpHeaderThreadData *hdr_td = DetectThreadCtxGetGlobalKeywordThreadCtx(det_ctx, keyword_id); if (hdr_td == NULL) return NULL; *ret_hdr_td = hdr_td; diff --git a/src/detect-http-header-common.h b/src/detect-http-header-common.h index a9c830e2a235..f83ad15a2d82 100644 --- a/src/detect-http-header-common.h +++ b/src/detect-http-header-common.h @@ -26,8 +26,8 @@ typedef struct HttpHeaderBuffer_ { uint8_t *buffer; - uint32_t size; /**< buffer size */ - uint32_t len; /**< part of buffer in use */ + uint32_t size; /**< buffer size */ + uint32_t len; /**< part of buffer in use */ } HttpHeaderBuffer; typedef struct HttpHeaderThreadConfig_ { @@ -35,8 +35,8 @@ typedef struct HttpHeaderThreadConfig_ { } HttpHeaderThreadDataConfig; typedef struct HttpHeaderThreadData_ { - HttpHeaderBuffer buffer; /**< array of buffers */ - uint16_t size_step; /**< increase size of HttpHeaderBuffer::buffer with this */ + HttpHeaderBuffer buffer; /**< array of buffers */ + uint16_t size_step; /**< increase size of HttpHeaderBuffer::buffer with this */ } HttpHeaderThreadData; void *HttpHeaderThreadDataInit(void *data); @@ -45,7 +45,6 @@ void HttpHeaderThreadDataFree(void *data); HttpHeaderBuffer *HttpHeaderGetBufferSpace(DetectEngineThreadCtx *det_ctx, Flow *f, uint8_t flags, const int keyword_id, HttpHeaderThreadData **ret_hdr_td); -int HttpHeaderExpandBuffer(HttpHeaderThreadData *td, - HttpHeaderBuffer *buf, uint32_t size); +int HttpHeaderExpandBuffer(HttpHeaderThreadData *td, HttpHeaderBuffer *buf, uint32_t size); #endif /* __DETECT_HTTP_HEADER_COMMON_H__ */ diff --git a/src/detect-http-header-names.c b/src/detect-http-header-names.c index 58989a1825df..43951c558593 100644 --- a/src/detect-http-header-names.c +++ b/src/detect-http-header-names.c @@ -21,7 +21,6 @@ * @{ */ - /** * \file * @@ -63,15 +62,15 @@ #include "detect-http-header.h" #include "stream-tcp.h" -#define KEYWORD_NAME "http.header_names" +#define KEYWORD_NAME "http.header_names" #define KEYWORD_NAME_LEGACY "http_header_names" -#define KEYWORD_DOC "http-keywords.html#http-header-names" -#define BUFFER_NAME "http_header_names" -#define BUFFER_DESC "http header names" +#define KEYWORD_DOC "http-keywords.html#http-header-names" +#define BUFFER_NAME "http_header_names" +#define BUFFER_DESC "http header names" static int g_buffer_id = 0; static int g_keyword_thread_id = 0; -#define BUFFER_SIZE_STEP 256 +#define BUFFER_SIZE_STEP 256 static HttpHeaderThreadDataConfig g_td_config = { BUFFER_SIZE_STEP }; static uint8_t *GetBufferForTX( @@ -112,8 +111,8 @@ static uint8_t *GetBufferForTX( if (i + 1 == no_of_headers) size += 2; - SCLogDebug("size %"PRIuMAX" + buf->len %u vs buf->size %u", - (uintmax_t)size, buf->len, buf->size); + SCLogDebug("size %" PRIuMAX " + buf->len %u vs buf->size %u", (uintmax_t)size, buf->len, + buf->size); if (size + buf->len > buf->size) { if (HttpHeaderExpandBuffer(hdr_td, buf, size) != 0) { return NULL; @@ -216,7 +215,8 @@ void DetectHttpHeaderNamesRegister(void) sigmatch_table[DETECT_AL_HTTP_HEADER_NAMES].url = "/rules/" KEYWORD_DOC; sigmatch_table[DETECT_AL_HTTP_HEADER_NAMES].Setup = DetectHttpHeaderNamesSetup; - sigmatch_table[DETECT_AL_HTTP_HEADER_NAMES].flags |= SIGMATCH_NOOPT | SIGMATCH_INFO_STICKY_BUFFER; + sigmatch_table[DETECT_AL_HTTP_HEADER_NAMES].flags |= + SIGMATCH_NOOPT | SIGMATCH_INFO_STICKY_BUFFER; /* http1 */ DetectAppLayerMpmRegister2(BUFFER_NAME, SIG_FLAG_TOSERVER, 2, PrefilterGenericMpmRegister, @@ -240,16 +240,14 @@ void DetectHttpHeaderNamesRegister(void) DetectAppLayerInspectEngineRegister2(BUFFER_NAME, ALPROTO_HTTP2, SIG_FLAG_TOCLIENT, HTTP2StateDataServer, DetectEngineInspectBufferGeneric, GetBuffer2ForTX); - DetectBufferTypeSetDescriptionByName(BUFFER_NAME, - BUFFER_DESC); + DetectBufferTypeSetDescriptionByName(BUFFER_NAME, BUFFER_DESC); g_buffer_id = DetectBufferTypeGetByName(BUFFER_NAME); - g_keyword_thread_id = DetectRegisterThreadCtxGlobalFuncs(KEYWORD_NAME, - HttpHeaderThreadDataInit, &g_td_config, HttpHeaderThreadDataFree); + g_keyword_thread_id = DetectRegisterThreadCtxGlobalFuncs( + KEYWORD_NAME, HttpHeaderThreadDataInit, &g_td_config, HttpHeaderThreadDataFree); SCLogDebug("keyword %s registered. Thread id %d. " - "Buffer %s registered. Buffer id %d", - KEYWORD_NAME, g_keyword_thread_id, - BUFFER_NAME, g_buffer_id); + "Buffer %s registered. Buffer id %d", + KEYWORD_NAME, g_keyword_thread_id, BUFFER_NAME, g_buffer_id); } diff --git a/src/detect-http-header.c b/src/detect-http-header.c index a4596c4085f2..15b029c96b50 100644 --- a/src/detect-http-header.c +++ b/src/detect-http-header.c @@ -21,7 +21,6 @@ * @{ */ - /** * \file * @@ -63,7 +62,7 @@ static void DetectHttpHeaderRegisterTests(void); static int g_http_header_buffer_id = 0; static int g_keyword_thread_id = 0; -#define BUFFER_SIZE_STEP 1024 +#define BUFFER_SIZE_STEP 1024 static HttpHeaderThreadDataConfig g_td_config = { BUFFER_SIZE_STEP }; static uint8_t *GetBufferForTX( @@ -101,13 +100,11 @@ static uint8_t *GetBufferForTX( size_t size2 = bstr_size(h->value); if (flags & STREAM_TOSERVER) { - if (size1 == 6 && - SCMemcmpLowercase("cookie", bstr_ptr(h->name), 6) == 0) { + if (size1 == 6 && SCMemcmpLowercase("cookie", bstr_ptr(h->name), 6) == 0) { continue; } } else { - if (size1 == 10 && - SCMemcmpLowercase("set-cookie", bstr_ptr(h->name), 10) == 0) { + if (size1 == 10 && SCMemcmpLowercase("set-cookie", bstr_ptr(h->name), 10) == 0) { continue; } } @@ -260,7 +257,7 @@ static void PrefilterMpmHttpHeader(DetectEngineThreadCtx *det_ctx, const void *p const uint8_t *data = buffer->inspect; SCLogDebug("mpm'ing buffer:"); - //PrintRawDataFp(stdout, data, data_len); + // PrintRawDataFp(stdout, data, data_len); if (data != NULL && data_len >= mpm_ctx->minlen) { (void)mpm_table[mpm_ctx->mpm_type].Search( @@ -277,9 +274,8 @@ static void PrefilterMpmHttpTrailer(DetectEngineThreadCtx *det_ctx, const void * htp_tx_t *tx = txv; const HtpTxUserData *htud = (const HtpTxUserData *)htp_tx_get_user_data(tx); /* if the request wasn't flagged as having a trailer, we skip */ - if (htud && ( - ((flags & STREAM_TOSERVER) && !htud->request_has_trailers) || - ((flags & STREAM_TOCLIENT) && !htud->response_has_trailers))) { + if (htud && (((flags & STREAM_TOSERVER) && !htud->request_has_trailers) || + ((flags & STREAM_TOCLIENT) && !htud->response_has_trailers))) { SCReturn; } PrefilterMpmHttpHeader(det_ctx, pectx, p, f, txv, idx, _txd, flags); @@ -304,9 +300,8 @@ static int PrefilterMpmHttpHeaderRequestRegister(DetectEngineCtx *de_ctx, SigGro pectx->mpm_ctx = mpm_ctx; pectx->transforms = &mpm_reg->transforms; - int r = PrefilterAppendTxEngine(de_ctx, sgh, PrefilterMpmHttpHeader, - mpm_reg->app_v2.alproto, HTP_REQUEST_HEADERS, - pectx, PrefilterMpmHttpHeaderFree, mpm_reg->pname); + int r = PrefilterAppendTxEngine(de_ctx, sgh, PrefilterMpmHttpHeader, mpm_reg->app_v2.alproto, + HTP_REQUEST_HEADERS, pectx, PrefilterMpmHttpHeaderFree, mpm_reg->pname); if (r != 0) { SCFree(pectx); return r; @@ -320,9 +315,8 @@ static int PrefilterMpmHttpHeaderRequestRegister(DetectEngineCtx *de_ctx, SigGro pectx->mpm_ctx = mpm_ctx; pectx->transforms = &mpm_reg->transforms; - r = PrefilterAppendTxEngine(de_ctx, sgh, PrefilterMpmHttpTrailer, - mpm_reg->app_v2.alproto, HTP_REQUEST_TRAILER, - pectx, PrefilterMpmHttpHeaderFree, mpm_reg->pname); + r = PrefilterAppendTxEngine(de_ctx, sgh, PrefilterMpmHttpTrailer, mpm_reg->app_v2.alproto, + HTP_REQUEST_TRAILER, pectx, PrefilterMpmHttpHeaderFree, mpm_reg->pname); if (r != 0) { SCFree(pectx); } @@ -342,9 +336,8 @@ static int PrefilterMpmHttpHeaderResponseRegister(DetectEngineCtx *de_ctx, SigGr pectx->mpm_ctx = mpm_ctx; pectx->transforms = &mpm_reg->transforms; - int r = PrefilterAppendTxEngine(de_ctx, sgh, PrefilterMpmHttpHeader, - mpm_reg->app_v2.alproto, HTP_RESPONSE_HEADERS, - pectx, PrefilterMpmHttpHeaderFree, mpm_reg->pname); + int r = PrefilterAppendTxEngine(de_ctx, sgh, PrefilterMpmHttpHeader, mpm_reg->app_v2.alproto, + HTP_RESPONSE_HEADERS, pectx, PrefilterMpmHttpHeaderFree, mpm_reg->pname); if (r != 0) { SCFree(pectx); return r; @@ -358,9 +351,8 @@ static int PrefilterMpmHttpHeaderResponseRegister(DetectEngineCtx *de_ctx, SigGr pectx->mpm_ctx = mpm_ctx; pectx->transforms = &mpm_reg->transforms; - r = PrefilterAppendTxEngine(de_ctx, sgh, PrefilterMpmHttpTrailer, - mpm_reg->app_v2.alproto, HTP_RESPONSE_TRAILER, - pectx, PrefilterMpmHttpHeaderFree, mpm_reg->pname); + r = PrefilterAppendTxEngine(de_ctx, sgh, PrefilterMpmHttpTrailer, mpm_reg->app_v2.alproto, + HTP_RESPONSE_TRAILER, pectx, PrefilterMpmHttpHeaderFree, mpm_reg->pname); if (r != 0) { SCFree(pectx); } @@ -411,20 +403,24 @@ void DetectHttpHeaderRegister(void) { /* http_header content modifier */ sigmatch_table[DETECT_AL_HTTP_HEADER].name = "http_header"; - sigmatch_table[DETECT_AL_HTTP_HEADER].desc = "content modifier to match only on the HTTP header-buffer"; - sigmatch_table[DETECT_AL_HTTP_HEADER].url = "/rules/http-keywords.html#http-header-and-http-raw-header"; + sigmatch_table[DETECT_AL_HTTP_HEADER].desc = + "content modifier to match only on the HTTP header-buffer"; + sigmatch_table[DETECT_AL_HTTP_HEADER].url = + "/rules/http-keywords.html#http-header-and-http-raw-header"; sigmatch_table[DETECT_AL_HTTP_HEADER].Setup = DetectHttpHeaderSetup; #ifdef UNITTESTS sigmatch_table[DETECT_AL_HTTP_HEADER].RegisterTests = DetectHttpHeaderRegisterTests; #endif - sigmatch_table[DETECT_AL_HTTP_HEADER].flags |= SIGMATCH_NOOPT ; + sigmatch_table[DETECT_AL_HTTP_HEADER].flags |= SIGMATCH_NOOPT; sigmatch_table[DETECT_AL_HTTP_HEADER].flags |= SIGMATCH_INFO_CONTENT_MODIFIER; sigmatch_table[DETECT_AL_HTTP_HEADER].alternative = DETECT_HTTP_HEADER; /* http.header sticky buffer */ sigmatch_table[DETECT_HTTP_HEADER].name = "http.header"; - sigmatch_table[DETECT_HTTP_HEADER].desc = "sticky buffer to match on the normalized HTTP header-buffer"; - sigmatch_table[DETECT_HTTP_HEADER].url = "/rules/http-keywords.html#http-header-and-http-raw-header"; + sigmatch_table[DETECT_HTTP_HEADER].desc = + "sticky buffer to match on the normalized HTTP header-buffer"; + sigmatch_table[DETECT_HTTP_HEADER].url = + "/rules/http-keywords.html#http-header-and-http-raw-header"; sigmatch_table[DETECT_HTTP_HEADER].Setup = DetectHttpHeaderSetupSticky; sigmatch_table[DETECT_HTTP_HEADER].flags |= SIGMATCH_NOOPT; sigmatch_table[DETECT_HTTP_HEADER].flags |= SIGMATCH_INFO_STICKY_BUFFER; @@ -451,13 +447,12 @@ void DetectHttpHeaderRegister(void) DetectAppLayerMpmRegister2("http_header", SIG_FLAG_TOCLIENT, 2, PrefilterGenericMpmRegister, GetBuffer2ForTX, ALPROTO_HTTP2, HTTP2StateDataServer); - DetectBufferTypeSetDescriptionByName("http_header", - "http headers"); + DetectBufferTypeSetDescriptionByName("http_header", "http headers"); g_http_header_buffer_id = DetectBufferTypeGetByName("http_header"); - g_keyword_thread_id = DetectRegisterThreadCtxGlobalFuncs("http_header", - HttpHeaderThreadDataInit, &g_td_config, HttpHeaderThreadDataFree); + g_keyword_thread_id = DetectRegisterThreadCtxGlobalFuncs( + "http_header", HttpHeaderThreadDataInit, &g_td_config, HttpHeaderThreadDataFree); } static int g_http_request_header_buffer_id = 0; diff --git a/src/detect-http-headers-stub.h b/src/detect-http-headers-stub.h index 3a036d62209e..086f916578cf 100644 --- a/src/detect-http-headers-stub.h +++ b/src/detect-http-headers-stub.h @@ -44,8 +44,8 @@ static int g_buffer_id = 0; #ifdef KEYWORD_TOSERVER static InspectionBuffer *GetRequestData(DetectEngineThreadCtx *det_ctx, - const DetectEngineTransforms *transforms, Flow *_f, - const uint8_t _flow_flags, void *txv, const int list_id) + const DetectEngineTransforms *transforms, Flow *_f, const uint8_t _flow_flags, void *txv, + const int list_id) { SCEnter(); @@ -56,11 +56,9 @@ static InspectionBuffer *GetRequestData(DetectEngineThreadCtx *det_ctx, if (tx->request_headers == NULL) return NULL; - htp_header_t *h = (htp_header_t *)htp_table_get_c(tx->request_headers, - HEADER_NAME); + htp_header_t *h = (htp_header_t *)htp_table_get_c(tx->request_headers, HEADER_NAME); if (h == NULL || h->value == NULL) { - SCLogDebug("HTTP %s header not present in this request", - HEADER_NAME); + SCLogDebug("HTTP %s header not present in this request", HEADER_NAME); return NULL; } @@ -100,8 +98,8 @@ static InspectionBuffer *GetRequestData2(DetectEngineThreadCtx *det_ctx, #endif #ifdef KEYWORD_TOCLIENT static InspectionBuffer *GetResponseData(DetectEngineThreadCtx *det_ctx, - const DetectEngineTransforms *transforms, Flow *_f, - const uint8_t _flow_flags, void *txv, const int list_id) + const DetectEngineTransforms *transforms, Flow *_f, const uint8_t _flow_flags, void *txv, + const int list_id) { SCEnter(); @@ -112,11 +110,9 @@ static InspectionBuffer *GetResponseData(DetectEngineThreadCtx *det_ctx, if (tx->response_headers == NULL) return NULL; - htp_header_t *h = (htp_header_t *)htp_table_get_c(tx->response_headers, - HEADER_NAME); + htp_header_t *h = (htp_header_t *)htp_table_get_c(tx->response_headers, HEADER_NAME); if (h == NULL || h->value == NULL) { - SCLogDebug("HTTP %s header not present in this request", - HEADER_NAME); + SCLogDebug("HTTP %s header not present in this request", HEADER_NAME); return NULL; } diff --git a/src/detect-http-headers.c b/src/detect-http-headers.c index f9e8580606bb..eb52fb840b27 100644 --- a/src/detect-http-headers.c +++ b/src/detect-http-headers.c @@ -38,4 +38,3 @@ void DetectHttpHeadersRegister(void) RegisterHttpHeadersServer(); RegisterHttpHeadersLocation(); } - diff --git a/src/detect-http-host.c b/src/detect-http-host.c index 6f32044a112c..355db7d6a0f3 100644 --- a/src/detect-http-host.c +++ b/src/detect-http-host.c @@ -21,7 +21,6 @@ * @{ */ - /** * \file * @@ -65,9 +64,8 @@ static void DetectHttpHHRegisterTests(void); static bool DetectHttpHostValidateCallback(const Signature *s, const char **sigerror); static int DetectHttpHostSetup(DetectEngineCtx *, Signature *, const char *); static InspectionBuffer *GetData(DetectEngineThreadCtx *det_ctx, - const DetectEngineTransforms *transforms, - Flow *_f, const uint8_t _flow_flags, - void *txv, const int list_id); + const DetectEngineTransforms *transforms, Flow *_f, const uint8_t _flow_flags, void *txv, + const int list_id); static InspectionBuffer *GetData2(DetectEngineThreadCtx *det_ctx, const DetectEngineTransforms *transforms, Flow *_f, const uint8_t _flow_flags, void *txv, const int list_id); @@ -75,8 +73,8 @@ static int DetectHttpHRHSetup(DetectEngineCtx *, Signature *, const char *); static int g_http_raw_host_buffer_id = 0; static int DetectHttpHostRawSetupSticky(DetectEngineCtx *de_ctx, Signature *s, const char *str); static InspectionBuffer *GetRawData(DetectEngineThreadCtx *det_ctx, - const DetectEngineTransforms *transforms, Flow *_f, - const uint8_t _flow_flags, void *txv, const int list_id); + const DetectEngineTransforms *transforms, Flow *_f, const uint8_t _flow_flags, void *txv, + const int list_id); static InspectionBuffer *GetRawData2(DetectEngineThreadCtx *det_ctx, const DetectEngineTransforms *transforms, Flow *_f, const uint8_t _flow_flags, void *txv, const int list_id); @@ -90,12 +88,13 @@ void DetectHttpHHRegister(void) /* http_host content modifier */ sigmatch_table[DETECT_AL_HTTP_HOST].name = "http_host"; sigmatch_table[DETECT_AL_HTTP_HOST].desc = "content modifier to match on the HTTP hostname"; - sigmatch_table[DETECT_AL_HTTP_HOST].url = "/rules/http-keywords.html#http-host-and-http-raw-host"; + sigmatch_table[DETECT_AL_HTTP_HOST].url = + "/rules/http-keywords.html#http-host-and-http-raw-host"; sigmatch_table[DETECT_AL_HTTP_HOST].Setup = DetectHttpHHSetup; #ifdef UNITTESTS sigmatch_table[DETECT_AL_HTTP_HOST].RegisterTests = DetectHttpHHRegisterTests; #endif - sigmatch_table[DETECT_AL_HTTP_HOST].flags |= SIGMATCH_NOOPT|SIGMATCH_INFO_CONTENT_MODIFIER; + sigmatch_table[DETECT_AL_HTTP_HOST].flags |= SIGMATCH_NOOPT | SIGMATCH_INFO_CONTENT_MODIFIER; sigmatch_table[DETECT_AL_HTTP_HOST].alternative = DETECT_HTTP_HOST; /* http.host sticky buffer */ @@ -103,7 +102,7 @@ void DetectHttpHHRegister(void) sigmatch_table[DETECT_HTTP_HOST].desc = "sticky buffer to match on the HTTP Host buffer"; sigmatch_table[DETECT_HTTP_HOST].url = "/rules/http-keywords.html#http-host-and-http-raw-host"; sigmatch_table[DETECT_HTTP_HOST].Setup = DetectHttpHostSetup; - sigmatch_table[DETECT_HTTP_HOST].flags |= SIGMATCH_NOOPT|SIGMATCH_INFO_STICKY_BUFFER; + sigmatch_table[DETECT_HTTP_HOST].flags |= SIGMATCH_NOOPT | SIGMATCH_INFO_STICKY_BUFFER; DetectAppLayerInspectEngineRegister2("http_host", ALPROTO_HTTP1, SIG_FLAG_TOSERVER, HTP_REQUEST_HEADERS, DetectEngineInspectBufferGeneric, GetData); @@ -117,28 +116,31 @@ void DetectHttpHHRegister(void) DetectAppLayerMpmRegister2("http_host", SIG_FLAG_TOSERVER, 2, PrefilterGenericMpmRegister, GetData2, ALPROTO_HTTP2, HTTP2StateDataClient); - DetectBufferTypeRegisterValidateCallback("http_host", - DetectHttpHostValidateCallback); + DetectBufferTypeRegisterValidateCallback("http_host", DetectHttpHostValidateCallback); - DetectBufferTypeSetDescriptionByName("http_host", - "http host"); + DetectBufferTypeSetDescriptionByName("http_host", "http host"); g_http_host_buffer_id = DetectBufferTypeGetByName("http_host"); /* http_raw_host content modifier */ sigmatch_table[DETECT_AL_HTTP_RAW_HOST].name = "http_raw_host"; - sigmatch_table[DETECT_AL_HTTP_RAW_HOST].desc = "content modifier to match on the HTTP host header or the raw hostname from the HTTP uri"; - sigmatch_table[DETECT_AL_HTTP_RAW_HOST].url = "/rules/http-keywords.html#http-host-and-http-raw-host"; + sigmatch_table[DETECT_AL_HTTP_RAW_HOST].desc = "content modifier to match on the HTTP host " + "header or the raw hostname from the HTTP uri"; + sigmatch_table[DETECT_AL_HTTP_RAW_HOST].url = + "/rules/http-keywords.html#http-host-and-http-raw-host"; sigmatch_table[DETECT_AL_HTTP_RAW_HOST].Setup = DetectHttpHRHSetup; - sigmatch_table[DETECT_AL_HTTP_RAW_HOST].flags |= SIGMATCH_NOOPT|SIGMATCH_INFO_CONTENT_MODIFIER; + sigmatch_table[DETECT_AL_HTTP_RAW_HOST].flags |= + SIGMATCH_NOOPT | SIGMATCH_INFO_CONTENT_MODIFIER; sigmatch_table[DETECT_AL_HTTP_RAW_HOST].alternative = DETECT_HTTP_HOST_RAW; /* http.host sticky buffer */ sigmatch_table[DETECT_HTTP_HOST_RAW].name = "http.host.raw"; - sigmatch_table[DETECT_HTTP_HOST_RAW].desc = "sticky buffer to match on the HTTP host header or the raw hostname from the HTTP uri"; - sigmatch_table[DETECT_HTTP_HOST_RAW].url = "/rules/http-keywords.html#http-host-and-http-raw-host"; + sigmatch_table[DETECT_HTTP_HOST_RAW].desc = + "sticky buffer to match on the HTTP host header or the raw hostname from the HTTP uri"; + sigmatch_table[DETECT_HTTP_HOST_RAW].url = + "/rules/http-keywords.html#http-host-and-http-raw-host"; sigmatch_table[DETECT_HTTP_HOST_RAW].Setup = DetectHttpHostRawSetupSticky; - sigmatch_table[DETECT_HTTP_HOST_RAW].flags |= SIGMATCH_NOOPT|SIGMATCH_INFO_STICKY_BUFFER; + sigmatch_table[DETECT_HTTP_HOST_RAW].flags |= SIGMATCH_NOOPT | SIGMATCH_INFO_STICKY_BUFFER; DetectAppLayerInspectEngineRegister2("http_raw_host", ALPROTO_HTTP1, SIG_FLAG_TOSERVER, HTP_REQUEST_HEADERS, DetectEngineInspectBufferGeneric, GetRawData); @@ -152,8 +154,7 @@ void DetectHttpHHRegister(void) DetectAppLayerMpmRegister2("http_raw_host", SIG_FLAG_TOSERVER, 2, PrefilterGenericMpmRegister, GetRawData2, ALPROTO_HTTP2, HTTP2StateDataClient); - DetectBufferTypeSetDescriptionByName("http_raw_host", - "http raw host header"); + DetectBufferTypeSetDescriptionByName("http_raw_host", "http raw host header"); g_http_raw_host_buffer_id = DetectBufferTypeGetByName("http_raw_host"); } @@ -235,8 +236,8 @@ static int DetectHttpHostSetup(DetectEngineCtx *de_ctx, Signature *s, const char } static InspectionBuffer *GetData(DetectEngineThreadCtx *det_ctx, - const DetectEngineTransforms *transforms, Flow *_f, - const uint8_t _flow_flags, void *txv, const int list_id) + const DetectEngineTransforms *transforms, Flow *_f, const uint8_t _flow_flags, void *txv, + const int list_id) { InspectionBuffer *buffer = InspectionBufferGet(det_ctx, list_id); if (buffer->inspect == NULL) { @@ -335,8 +336,8 @@ static int DetectHttpHostRawSetupSticky(DetectEngineCtx *de_ctx, Signature *s, c } static InspectionBuffer *GetRawData(DetectEngineThreadCtx *det_ctx, - const DetectEngineTransforms *transforms, Flow *_f, - const uint8_t _flow_flags, void *txv, const int list_id) + const DetectEngineTransforms *transforms, Flow *_f, const uint8_t _flow_flags, void *txv, + const int list_id) { InspectionBuffer *buffer = InspectionBufferGet(det_ctx, list_id); if (buffer->inspect == NULL) { @@ -349,8 +350,7 @@ static InspectionBuffer *GetRawData(DetectEngineThreadCtx *det_ctx, if (tx->request_headers == NULL) return NULL; - htp_header_t *h = (htp_header_t *)htp_table_get_c(tx->request_headers, - "Host"); + htp_header_t *h = (htp_header_t *)htp_table_get_c(tx->request_headers, "Host"); if (h == NULL || h->value == NULL) return NULL; diff --git a/src/detect-http-location.c b/src/detect-http-location.c index bd4eb15dc9c3..ed716f6eb6d7 100644 --- a/src/detect-http-location.c +++ b/src/detect-http-location.c @@ -21,7 +21,6 @@ * @{ */ - /** * \file * @@ -33,12 +32,12 @@ * a location other than the Request-URI for request completion. */ -#define KEYWORD_NAME "http.location" -#define KEYWORD_DOC "http-keywords.html#http-location" -#define BUFFER_NAME "http.location" -#define BUFFER_DESC "http location header" -#define HEADER_NAME "Location" -#define KEYWORD_ID DETECT_AL_HTTP_HEADER_LOCATION +#define KEYWORD_NAME "http.location" +#define KEYWORD_DOC "http-keywords.html#http-location" +#define BUFFER_NAME "http.location" +#define BUFFER_DESC "http location header" +#define HEADER_NAME "Location" +#define KEYWORD_ID DETECT_AL_HTTP_HEADER_LOCATION #define KEYWORD_TOCLIENT 1 #include "detect-http-headers-stub.h" diff --git a/src/detect-http-method.c b/src/detect-http-method.c index 0ce246359ce9..43881fe48844 100644 --- a/src/detect-http-method.c +++ b/src/detect-http-method.c @@ -21,7 +21,6 @@ * @{ */ - /** * \file * @@ -67,8 +66,8 @@ void DetectHttpMethodRegisterTests(void); void DetectHttpMethodFree(void *); static bool DetectHttpMethodValidateCallback(const Signature *s, const char **sigerror); static InspectionBuffer *GetData(DetectEngineThreadCtx *det_ctx, - const DetectEngineTransforms *transforms, Flow *_f, - const uint8_t _flow_flags, void *txv, const int list_id); + const DetectEngineTransforms *transforms, Flow *_f, const uint8_t _flow_flags, void *txv, + const int list_id); static InspectionBuffer *GetData2(DetectEngineThreadCtx *det_ctx, const DetectEngineTransforms *transforms, Flow *_f, const uint8_t _flow_flags, void *txv, const int list_id); @@ -80,22 +79,24 @@ void DetectHttpMethodRegister(void) { /* http_method content modifier */ sigmatch_table[DETECT_AL_HTTP_METHOD].name = "http_method"; - sigmatch_table[DETECT_AL_HTTP_METHOD].desc = "content modifier to match only on the HTTP method-buffer"; + sigmatch_table[DETECT_AL_HTTP_METHOD].desc = + "content modifier to match only on the HTTP method-buffer"; sigmatch_table[DETECT_AL_HTTP_METHOD].url = "/rules/http-keywords.html#http-method"; sigmatch_table[DETECT_AL_HTTP_METHOD].Match = NULL; sigmatch_table[DETECT_AL_HTTP_METHOD].Setup = DetectHttpMethodSetup; #ifdef UNITTESTS sigmatch_table[DETECT_AL_HTTP_METHOD].RegisterTests = DetectHttpMethodRegisterTests; #endif - sigmatch_table[DETECT_AL_HTTP_METHOD].flags |= SIGMATCH_NOOPT|SIGMATCH_INFO_CONTENT_MODIFIER; + sigmatch_table[DETECT_AL_HTTP_METHOD].flags |= SIGMATCH_NOOPT | SIGMATCH_INFO_CONTENT_MODIFIER; sigmatch_table[DETECT_AL_HTTP_METHOD].alternative = DETECT_HTTP_METHOD; /* http.method sticky buffer */ sigmatch_table[DETECT_HTTP_METHOD].name = "http.method"; - sigmatch_table[DETECT_HTTP_METHOD].desc = "sticky buffer to match specifically and only on the HTTP method buffer"; + sigmatch_table[DETECT_HTTP_METHOD].desc = + "sticky buffer to match specifically and only on the HTTP method buffer"; sigmatch_table[DETECT_HTTP_METHOD].url = "/rules/http-keywords.html#http-method"; sigmatch_table[DETECT_HTTP_METHOD].Setup = DetectHttpMethodSetupSticky; - sigmatch_table[DETECT_HTTP_METHOD].flags |= SIGMATCH_NOOPT|SIGMATCH_INFO_STICKY_BUFFER; + sigmatch_table[DETECT_HTTP_METHOD].flags |= SIGMATCH_NOOPT | SIGMATCH_INFO_STICKY_BUFFER; DetectAppLayerInspectEngineRegister2("http_method", ALPROTO_HTTP1, SIG_FLAG_TOSERVER, HTP_REQUEST_LINE, DetectEngineInspectBufferGeneric, GetData); @@ -109,11 +110,9 @@ void DetectHttpMethodRegister(void) DetectAppLayerMpmRegister2("http_method", SIG_FLAG_TOSERVER, 4, PrefilterGenericMpmRegister, GetData2, ALPROTO_HTTP2, HTTP2StateDataClient); - DetectBufferTypeSetDescriptionByName("http_method", - "http request method"); + DetectBufferTypeSetDescriptionByName("http_method", "http request method"); - DetectBufferTypeRegisterValidateCallback("http_method", - DetectHttpMethodValidateCallback); + DetectBufferTypeRegisterValidateCallback("http_method", DetectHttpMethodValidateCallback); g_http_method_buffer_id = DetectBufferTypeGetByName("http_method"); @@ -196,8 +195,8 @@ static bool DetectHttpMethodValidateCallback(const Signature *s, const char **si } static InspectionBuffer *GetData(DetectEngineThreadCtx *det_ctx, - const DetectEngineTransforms *transforms, Flow *_f, - const uint8_t _flow_flags, void *txv, const int list_id) + const DetectEngineTransforms *transforms, Flow *_f, const uint8_t _flow_flags, void *txv, + const int list_id) { InspectionBuffer *buffer = InspectionBufferGet(det_ctx, list_id); if (buffer->inspect == NULL) { diff --git a/src/detect-http-method.h b/src/detect-http-method.h index 871177b58749..afe949a1d8ae 100644 --- a/src/detect-http-method.h +++ b/src/detect-http-method.h @@ -28,4 +28,3 @@ void DetectHttpMethodRegister(void); #endif /* __DETECT_HTTP_METHOD_H__ */ - diff --git a/src/detect-http-protocol.c b/src/detect-http-protocol.c index 9dc3455d2149..d5dd994479a9 100644 --- a/src/detect-http-protocol.c +++ b/src/detect-http-protocol.c @@ -21,7 +21,6 @@ * @{ */ - /** * \file * @@ -63,11 +62,11 @@ #include "detect-http-header.h" #include "stream-tcp.h" -#define KEYWORD_NAME "http.protocol" +#define KEYWORD_NAME "http.protocol" #define KEYWORD_NAME_LEGACY "http_protocol" -#define KEYWORD_DOC "http-keywords.html#http-protocol" -#define BUFFER_NAME "http_protocol" -#define BUFFER_DESC "http protocol" +#define KEYWORD_DOC "http-keywords.html#http-protocol" +#define BUFFER_NAME "http_protocol" +#define BUFFER_DESC "http protocol" static int g_buffer_id = 0; static int DetectHttpProtocolSetup(DetectEngineCtx *de_ctx, Signature *s, const char *arg) @@ -82,8 +81,8 @@ static int DetectHttpProtocolSetup(DetectEngineCtx *de_ctx, Signature *s, const } static InspectionBuffer *GetData(DetectEngineThreadCtx *det_ctx, - const DetectEngineTransforms *transforms, Flow *_f, - const uint8_t flow_flags, void *txv, const int list_id) + const DetectEngineTransforms *transforms, Flow *_f, const uint8_t flow_flags, void *txv, + const int list_id) { InspectionBuffer *buffer = InspectionBufferGet(det_ctx, list_id); if (buffer->inspect == NULL) { @@ -158,8 +157,7 @@ void DetectHttpProtocolRegister(void) DetectAppLayerMpmRegister2(BUFFER_NAME, SIG_FLAG_TOCLIENT, 2, PrefilterGenericMpmRegister, GetData2, ALPROTO_HTTP2, HTTP2StateDataServer); - DetectBufferTypeSetDescriptionByName(BUFFER_NAME, - BUFFER_DESC); + DetectBufferTypeSetDescriptionByName(BUFFER_NAME, BUFFER_DESC); g_buffer_id = DetectBufferTypeGetByName(BUFFER_NAME); } diff --git a/src/detect-http-raw-header.c b/src/detect-http-raw-header.c index 1494f02d22d7..8a9e3506552d 100644 --- a/src/detect-http-raw-header.c +++ b/src/detect-http-raw-header.c @@ -21,7 +21,6 @@ * @{ */ - /** * \file * @@ -61,8 +60,8 @@ static void DetectHttpRawHeaderRegisterTests(void); static bool DetectHttpRawHeaderValidateCallback(const Signature *s, const char **sigerror); static int g_http_raw_header_buffer_id = 0; static InspectionBuffer *GetData(DetectEngineThreadCtx *det_ctx, - const DetectEngineTransforms *transforms, Flow *_f, - const uint8_t flow_flags, void *txv, const int list_id); + const DetectEngineTransforms *transforms, Flow *_f, const uint8_t flow_flags, void *txv, + const int list_id); static InspectionBuffer *GetData2(DetectEngineThreadCtx *det_ctx, const DetectEngineTransforms *transforms, Flow *_f, const uint8_t flow_flags, void *txv, const int list_id); @@ -79,21 +78,26 @@ void DetectHttpRawHeaderRegister(void) { /* http_raw_header content modifier */ sigmatch_table[DETECT_AL_HTTP_RAW_HEADER].name = "http_raw_header"; - sigmatch_table[DETECT_AL_HTTP_RAW_HEADER].desc = "content modifier to match the raw HTTP header buffer"; - sigmatch_table[DETECT_AL_HTTP_RAW_HEADER].url = "/rules/http-keywords.html#http-header-and-http-raw-header"; + sigmatch_table[DETECT_AL_HTTP_RAW_HEADER].desc = + "content modifier to match the raw HTTP header buffer"; + sigmatch_table[DETECT_AL_HTTP_RAW_HEADER].url = + "/rules/http-keywords.html#http-header-and-http-raw-header"; sigmatch_table[DETECT_AL_HTTP_RAW_HEADER].Setup = DetectHttpRawHeaderSetup; #ifdef UNITTESTS sigmatch_table[DETECT_AL_HTTP_RAW_HEADER].RegisterTests = DetectHttpRawHeaderRegisterTests; #endif - sigmatch_table[DETECT_AL_HTTP_RAW_HEADER].flags |= SIGMATCH_NOOPT|SIGMATCH_INFO_CONTENT_MODIFIER; + sigmatch_table[DETECT_AL_HTTP_RAW_HEADER].flags |= + SIGMATCH_NOOPT | SIGMATCH_INFO_CONTENT_MODIFIER; sigmatch_table[DETECT_AL_HTTP_RAW_HEADER].alternative = DETECT_HTTP_RAW_HEADER; /* http.header.raw sticky buffer */ sigmatch_table[DETECT_HTTP_RAW_HEADER].name = "http.header.raw"; - sigmatch_table[DETECT_HTTP_RAW_HEADER].desc = "sticky buffer to match the raw HTTP header buffer"; - sigmatch_table[DETECT_HTTP_RAW_HEADER].url = "/rules/http-keywords.html#http-header-and-http-raw-header"; + sigmatch_table[DETECT_HTTP_RAW_HEADER].desc = + "sticky buffer to match the raw HTTP header buffer"; + sigmatch_table[DETECT_HTTP_RAW_HEADER].url = + "/rules/http-keywords.html#http-header-and-http-raw-header"; sigmatch_table[DETECT_HTTP_RAW_HEADER].Setup = DetectHttpRawHeaderSetupSticky; - sigmatch_table[DETECT_HTTP_RAW_HEADER].flags |= SIGMATCH_NOOPT|SIGMATCH_INFO_STICKY_BUFFER; + sigmatch_table[DETECT_HTTP_RAW_HEADER].flags |= SIGMATCH_NOOPT | SIGMATCH_INFO_STICKY_BUFFER; DetectAppLayerInspectEngineRegister2("http_raw_header", ALPROTO_HTTP1, SIG_FLAG_TOSERVER, HTP_REQUEST_HEADERS + 1, DetectEngineInspectBufferGeneric, GetData); @@ -117,11 +121,10 @@ void DetectHttpRawHeaderRegister(void) DetectAppLayerMpmRegister2("http_raw_header", SIG_FLAG_TOCLIENT, 2, PrefilterGenericMpmRegister, GetData2, ALPROTO_HTTP2, HTTP2StateDataServer); - DetectBufferTypeSetDescriptionByName("http_raw_header", - "raw http headers"); + DetectBufferTypeSetDescriptionByName("http_raw_header", "raw http headers"); - DetectBufferTypeRegisterValidateCallback("http_raw_header", - DetectHttpRawHeaderValidateCallback); + DetectBufferTypeRegisterValidateCallback( + "http_raw_header", DetectHttpRawHeaderValidateCallback); g_http_raw_header_buffer_id = DetectBufferTypeGetByName("http_raw_header"); } @@ -165,11 +168,12 @@ static int DetectHttpRawHeaderSetupSticky(DetectEngineCtx *de_ctx, Signature *s, static bool DetectHttpRawHeaderValidateCallback(const Signature *s, const char **sigerror) { - if ((s->flags & (SIG_FLAG_TOCLIENT|SIG_FLAG_TOSERVER)) == (SIG_FLAG_TOCLIENT|SIG_FLAG_TOSERVER)) { + if ((s->flags & (SIG_FLAG_TOCLIENT | SIG_FLAG_TOSERVER)) == + (SIG_FLAG_TOCLIENT | SIG_FLAG_TOSERVER)) { *sigerror = "http_raw_header signature " - "without a flow direction. Use flow:to_server for " - "inspecting request headers or flow:to_client for " - "inspecting response headers."; + "without a flow direction. Use flow:to_server for " + "inspecting request headers or flow:to_client for " + "inspecting response headers."; SCLogError("%s", *sigerror); SCReturnInt(false); @@ -178,8 +182,8 @@ static bool DetectHttpRawHeaderValidateCallback(const Signature *s, const char * } static InspectionBuffer *GetData(DetectEngineThreadCtx *det_ctx, - const DetectEngineTransforms *transforms, Flow *_f, - const uint8_t flow_flags, void *txv, const int list_id) + const DetectEngineTransforms *transforms, Flow *_f, const uint8_t flow_flags, void *txv, + const int list_id) { InspectionBuffer *buffer = InspectionBufferGet(det_ctx, list_id); if (buffer->inspect == NULL) { @@ -190,12 +194,11 @@ static InspectionBuffer *GetData(DetectEngineThreadCtx *det_ctx, return NULL; const bool ts = ((flow_flags & STREAM_TOSERVER) != 0); - const uint8_t *data = ts ? - tx_ud->request_headers_raw : tx_ud->response_headers_raw; + const uint8_t *data = ts ? tx_ud->request_headers_raw : tx_ud->response_headers_raw; if (data == NULL) return NULL; - const uint32_t data_len = ts ? - tx_ud->request_headers_raw_len : tx_ud->response_headers_raw_len; + const uint32_t data_len = + ts ? tx_ud->request_headers_raw_len : tx_ud->response_headers_raw_len; InspectionBufferSetup(det_ctx, list_id, buffer, data, data_len); InspectionBufferApplyTransforms(buffer, transforms); @@ -250,8 +253,7 @@ static void PrefilterMpmHttpHeaderRaw(DetectEngineThreadCtx *det_ctx, const void const int list_id = ctx->list_id; - InspectionBuffer *buffer = GetData(det_ctx, ctx->transforms, f, - flags, txv, list_id); + InspectionBuffer *buffer = GetData(det_ctx, ctx->transforms, f, flags, txv, list_id); if (buffer == NULL) return; @@ -259,7 +261,7 @@ static void PrefilterMpmHttpHeaderRaw(DetectEngineThreadCtx *det_ctx, const void const uint8_t *data = buffer->inspect; SCLogDebug("mpm'ing buffer:"); - //PrintRawDataFp(stdout, data, data_len); + // PrintRawDataFp(stdout, data, data_len); if (data != NULL && data_len >= mpm_ctx->minlen) { (void)mpm_table[mpm_ctx->mpm_type].Search( @@ -276,9 +278,8 @@ static void PrefilterMpmHttpTrailerRaw(DetectEngineThreadCtx *det_ctx, const voi htp_tx_t *tx = txv; const HtpTxUserData *htud = (const HtpTxUserData *)htp_tx_get_user_data(tx); /* if the request wasn't flagged as having a trailer, we skip */ - if (htud && ( - ((flags & STREAM_TOSERVER) && !htud->request_has_trailers) || - ((flags & STREAM_TOCLIENT) && !htud->response_has_trailers))) { + if (htud && (((flags & STREAM_TOSERVER) && !htud->request_has_trailers) || + ((flags & STREAM_TOCLIENT) && !htud->response_has_trailers))) { SCReturn; } PrefilterMpmHttpHeaderRaw(det_ctx, pectx, p, f, txv, idx, _txd, flags); @@ -303,9 +304,8 @@ static int PrefilterMpmHttpHeaderRawRequestRegister(DetectEngineCtx *de_ctx, Sig pectx->mpm_ctx = mpm_ctx; pectx->transforms = &mpm_reg->transforms; - int r = PrefilterAppendTxEngine(de_ctx, sgh, PrefilterMpmHttpHeaderRaw, - mpm_reg->app_v2.alproto, HTP_REQUEST_HEADERS+1, - pectx, PrefilterMpmHttpHeaderRawFree, mpm_reg->pname); + int r = PrefilterAppendTxEngine(de_ctx, sgh, PrefilterMpmHttpHeaderRaw, mpm_reg->app_v2.alproto, + HTP_REQUEST_HEADERS + 1, pectx, PrefilterMpmHttpHeaderRawFree, mpm_reg->pname); if (r != 0) { SCFree(pectx); return r; @@ -319,9 +319,8 @@ static int PrefilterMpmHttpHeaderRawRequestRegister(DetectEngineCtx *de_ctx, Sig pectx->mpm_ctx = mpm_ctx; pectx->transforms = &mpm_reg->transforms; - r = PrefilterAppendTxEngine(de_ctx, sgh, PrefilterMpmHttpTrailerRaw, - mpm_reg->app_v2.alproto, HTP_REQUEST_TRAILER+1, - pectx, PrefilterMpmHttpHeaderRawFree, mpm_reg->pname); + r = PrefilterAppendTxEngine(de_ctx, sgh, PrefilterMpmHttpTrailerRaw, mpm_reg->app_v2.alproto, + HTP_REQUEST_TRAILER + 1, pectx, PrefilterMpmHttpHeaderRawFree, mpm_reg->pname); if (r != 0) { SCFree(pectx); } @@ -341,9 +340,8 @@ static int PrefilterMpmHttpHeaderRawResponseRegister(DetectEngineCtx *de_ctx, Si pectx->mpm_ctx = mpm_ctx; pectx->transforms = &mpm_reg->transforms; - int r = PrefilterAppendTxEngine(de_ctx, sgh, PrefilterMpmHttpHeaderRaw, - mpm_reg->app_v2.alproto, HTP_RESPONSE_HEADERS, - pectx, PrefilterMpmHttpHeaderRawFree, mpm_reg->pname); + int r = PrefilterAppendTxEngine(de_ctx, sgh, PrefilterMpmHttpHeaderRaw, mpm_reg->app_v2.alproto, + HTP_RESPONSE_HEADERS, pectx, PrefilterMpmHttpHeaderRawFree, mpm_reg->pname); if (r != 0) { SCFree(pectx); return r; @@ -357,9 +355,8 @@ static int PrefilterMpmHttpHeaderRawResponseRegister(DetectEngineCtx *de_ctx, Si pectx->mpm_ctx = mpm_ctx; pectx->transforms = &mpm_reg->transforms; - r = PrefilterAppendTxEngine(de_ctx, sgh, PrefilterMpmHttpTrailerRaw, - mpm_reg->app_v2.alproto, HTP_RESPONSE_TRAILER, - pectx, PrefilterMpmHttpHeaderRawFree, mpm_reg->pname); + r = PrefilterAppendTxEngine(de_ctx, sgh, PrefilterMpmHttpTrailerRaw, mpm_reg->app_v2.alproto, + HTP_RESPONSE_TRAILER, pectx, PrefilterMpmHttpHeaderRawFree, mpm_reg->pname); if (r != 0) { SCFree(pectx); } diff --git a/src/detect-http-referer.c b/src/detect-http-referer.c index 5ade2071a314..2b0c7c020c34 100644 --- a/src/detect-http-referer.c +++ b/src/detect-http-referer.c @@ -21,7 +21,6 @@ * @{ */ - /** * \file * @@ -31,13 +30,13 @@ */ #define KEYWORD_NAME_LEGACY "http_referer" -#define KEYWORD_NAME "http.referer" -#define KEYWORD_DOC "http-keywords.html#http-referer" -#define BUFFER_NAME "http_referer" -#define BUFFER_DESC "http referer header" -#define HEADER_NAME "Referer" -#define KEYWORD_ID DETECT_AL_HTTP_HEADER_REFERER -#define KEYWORD_TOSERVER 1 +#define KEYWORD_NAME "http.referer" +#define KEYWORD_DOC "http-keywords.html#http-referer" +#define BUFFER_NAME "http_referer" +#define BUFFER_DESC "http referer header" +#define HEADER_NAME "Referer" +#define KEYWORD_ID DETECT_AL_HTTP_HEADER_REFERER +#define KEYWORD_TOSERVER 1 #include "detect-http-headers-stub.h" #include "detect-http-referer.h" diff --git a/src/detect-http-request-line.c b/src/detect-http-request-line.c index 89d38cbd0a8a..4be9c42e3e71 100644 --- a/src/detect-http-request-line.c +++ b/src/detect-http-request-line.c @@ -21,7 +21,6 @@ * @{ */ - /** * \file * @@ -65,9 +64,8 @@ static int DetectHttpRequestLineSetup(DetectEngineCtx *, Signature *, const char static void DetectHttpRequestLineRegisterTests(void); #endif static InspectionBuffer *GetData(DetectEngineThreadCtx *det_ctx, - const DetectEngineTransforms *transforms, - Flow *_f, const uint8_t _flow_flags, - void *txv, const int list_id); + const DetectEngineTransforms *transforms, Flow *_f, const uint8_t _flow_flags, void *txv, + const int list_id); static int g_http_request_line_buffer_id = 0; static InspectionBuffer *GetData2(DetectEngineThreadCtx *det_ctx, @@ -100,14 +98,16 @@ void DetectHttpRequestLineRegister(void) { sigmatch_table[DETECT_AL_HTTP_REQUEST_LINE].name = "http.request_line"; sigmatch_table[DETECT_AL_HTTP_REQUEST_LINE].alias = "http_request_line"; - sigmatch_table[DETECT_AL_HTTP_REQUEST_LINE].desc = "sticky buffer to match on the HTTP request line"; + sigmatch_table[DETECT_AL_HTTP_REQUEST_LINE].desc = + "sticky buffer to match on the HTTP request line"; sigmatch_table[DETECT_AL_HTTP_REQUEST_LINE].url = "/rules/http-keywords.html#http-request-line"; sigmatch_table[DETECT_AL_HTTP_REQUEST_LINE].Match = NULL; sigmatch_table[DETECT_AL_HTTP_REQUEST_LINE].Setup = DetectHttpRequestLineSetup; #ifdef UNITTESTS sigmatch_table[DETECT_AL_HTTP_REQUEST_LINE].RegisterTests = DetectHttpRequestLineRegisterTests; #endif - sigmatch_table[DETECT_AL_HTTP_REQUEST_LINE].flags |= SIGMATCH_NOOPT|SIGMATCH_INFO_STICKY_BUFFER; + sigmatch_table[DETECT_AL_HTTP_REQUEST_LINE].flags |= + SIGMATCH_NOOPT | SIGMATCH_INFO_STICKY_BUFFER; DetectAppLayerInspectEngineRegister2("http_request_line", ALPROTO_HTTP1, SIG_FLAG_TOSERVER, HTP_REQUEST_LINE, DetectEngineInspectBufferGeneric, GetData); @@ -120,8 +120,7 @@ void DetectHttpRequestLineRegister(void) DetectAppLayerMpmRegister2("http_request_line", SIG_FLAG_TOSERVER, 2, PrefilterGenericMpmRegister, GetData2, ALPROTO_HTTP2, HTTP2StateDataClient); - DetectBufferTypeSetDescriptionByName("http_request_line", - "http request line"); + DetectBufferTypeSetDescriptionByName("http_request_line", "http request line"); g_http_request_line_buffer_id = DetectBufferTypeGetByName("http_request_line"); } @@ -151,9 +150,8 @@ static int DetectHttpRequestLineSetup(DetectEngineCtx *de_ctx, Signature *s, con } static InspectionBuffer *GetData(DetectEngineThreadCtx *det_ctx, - const DetectEngineTransforms *transforms, - Flow *_f, const uint8_t _flow_flags, - void *txv, const int list_id) + const DetectEngineTransforms *transforms, Flow *_f, const uint8_t _flow_flags, void *txv, + const int list_id) { InspectionBuffer *buffer = InspectionBufferGet(det_ctx, list_id); if (buffer->inspect == NULL) { @@ -187,7 +185,7 @@ static int DetectHttpRequestLineTest01(void) de_ctx->flags |= DE_QUIET; de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " - "(http_request_line; content:\"GET /\"; sid:1;)"); + "(http_request_line; content:\"GET /\"; sid:1;)"); FAIL_IF_NULL(de_ctx->sig_list); DetectEngineCtxFree(de_ctx); diff --git a/src/detect-http-response-line.c b/src/detect-http-response-line.c index 8758644681c7..01b6336a27a4 100644 --- a/src/detect-http-response-line.c +++ b/src/detect-http-response-line.c @@ -21,7 +21,6 @@ * @{ */ - /** * \file * @@ -65,9 +64,8 @@ static int DetectHttpResponseLineSetup(DetectEngineCtx *, Signature *, const cha static void DetectHttpResponseLineRegisterTests(void); #endif static InspectionBuffer *GetData(DetectEngineThreadCtx *det_ctx, - const DetectEngineTransforms *transforms, - Flow *_f, const uint8_t _flow_flags, - void *txv, const int list_id); + const DetectEngineTransforms *transforms, Flow *_f, const uint8_t _flow_flags, void *txv, + const int list_id); static int g_http_response_line_id = 0; static InspectionBuffer *GetData2(DetectEngineThreadCtx *det_ctx, @@ -100,13 +98,17 @@ void DetectHttpResponseLineRegister(void) { sigmatch_table[DETECT_AL_HTTP_RESPONSE_LINE].name = "http.response_line"; sigmatch_table[DETECT_AL_HTTP_RESPONSE_LINE].alias = "http_response_line"; - sigmatch_table[DETECT_AL_HTTP_RESPONSE_LINE].desc = "content modifier to match only on the HTTP response line"; - sigmatch_table[DETECT_AL_HTTP_RESPONSE_LINE].url = "/rules/http-keywords.html#http-response-line"; + sigmatch_table[DETECT_AL_HTTP_RESPONSE_LINE].desc = + "content modifier to match only on the HTTP response line"; + sigmatch_table[DETECT_AL_HTTP_RESPONSE_LINE].url = + "/rules/http-keywords.html#http-response-line"; sigmatch_table[DETECT_AL_HTTP_RESPONSE_LINE].Setup = DetectHttpResponseLineSetup; #ifdef UNITTESTS - sigmatch_table[DETECT_AL_HTTP_RESPONSE_LINE].RegisterTests = DetectHttpResponseLineRegisterTests; + sigmatch_table[DETECT_AL_HTTP_RESPONSE_LINE].RegisterTests = + DetectHttpResponseLineRegisterTests; #endif - sigmatch_table[DETECT_AL_HTTP_RESPONSE_LINE].flags |= SIGMATCH_NOOPT|SIGMATCH_INFO_STICKY_BUFFER; + sigmatch_table[DETECT_AL_HTTP_RESPONSE_LINE].flags |= + SIGMATCH_NOOPT | SIGMATCH_INFO_STICKY_BUFFER; DetectAppLayerInspectEngineRegister2("http_response_line", ALPROTO_HTTP1, SIG_FLAG_TOCLIENT, HTP_RESPONSE_LINE, DetectEngineInspectBufferGeneric, GetData); @@ -119,8 +121,7 @@ void DetectHttpResponseLineRegister(void) DetectAppLayerMpmRegister2("http_response_line", SIG_FLAG_TOCLIENT, 2, PrefilterGenericMpmRegister, GetData2, ALPROTO_HTTP2, HTTP2StateDataServer); - DetectBufferTypeSetDescriptionByName("http_response_line", - "http response line"); + DetectBufferTypeSetDescriptionByName("http_response_line", "http response line"); g_http_response_line_id = DetectBufferTypeGetByName("http_response_line"); } @@ -150,9 +151,8 @@ static int DetectHttpResponseLineSetup(DetectEngineCtx *de_ctx, Signature *s, co } static InspectionBuffer *GetData(DetectEngineThreadCtx *det_ctx, - const DetectEngineTransforms *transforms, - Flow *_f, const uint8_t _flow_flags, - void *txv, const int list_id) + const DetectEngineTransforms *transforms, Flow *_f, const uint8_t _flow_flags, void *txv, + const int list_id) { InspectionBuffer *buffer = InspectionBufferGet(det_ctx, list_id); if (buffer->inspect == NULL) { @@ -186,7 +186,7 @@ static int DetectHttpResponseLineTest01(void) de_ctx->flags |= DE_QUIET; de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " - "(http_response_line; content:\"200 OK\"; sid:1;)"); + "(http_response_line; content:\"200 OK\"; sid:1;)"); FAIL_IF_NULL(de_ctx->sig_list); DetectEngineCtxFree(de_ctx); diff --git a/src/detect-http-server-body.c b/src/detect-http-server-body.c index 98f0ec581e94..eb2a89fe4443 100644 --- a/src/detect-http-server-body.c +++ b/src/detect-http-server-body.c @@ -21,7 +21,6 @@ * @{ */ - /** * \file * @@ -69,7 +68,8 @@ void DetectHttpServerBodyRegister(void) { /* http_server_body content modifier */ sigmatch_table[DETECT_AL_HTTP_SERVER_BODY].name = "http_server_body"; - sigmatch_table[DETECT_AL_HTTP_SERVER_BODY].desc = "content modifier to match on the HTTP response-body"; + sigmatch_table[DETECT_AL_HTTP_SERVER_BODY].desc = + "content modifier to match on the HTTP response-body"; sigmatch_table[DETECT_AL_HTTP_SERVER_BODY].url = "/rules/http-keywords.html#http-server-body"; sigmatch_table[DETECT_AL_HTTP_SERVER_BODY].Setup = DetectHttpServerBodySetup; #ifdef UNITTESTS @@ -81,7 +81,8 @@ void DetectHttpServerBodyRegister(void) /* http.request_body sticky buffer */ sigmatch_table[DETECT_HTTP_RESPONSE_BODY].name = "http.response_body"; - sigmatch_table[DETECT_HTTP_RESPONSE_BODY].desc = "sticky buffer to match the HTTP response body buffer"; + sigmatch_table[DETECT_HTTP_RESPONSE_BODY].desc = + "sticky buffer to match the HTTP response body buffer"; sigmatch_table[DETECT_HTTP_RESPONSE_BODY].url = "/rules/http-keywords.html#http-server-body"; sigmatch_table[DETECT_HTTP_RESPONSE_BODY].Setup = DetectHttpServerBodySetupSticky; sigmatch_table[DETECT_HTTP_RESPONSE_BODY].flags |= SIGMATCH_NOOPT; diff --git a/src/detect-http-server.c b/src/detect-http-server.c index d0d598419acb..71c274aca892 100644 --- a/src/detect-http-server.c +++ b/src/detect-http-server.c @@ -21,7 +21,6 @@ * @{ */ - /** * \file * @@ -33,12 +32,12 @@ * used by the origin server to handle the request. */ -#define KEYWORD_NAME "http.server" -#define KEYWORD_DOC "http-keywords.html#http-server" -#define BUFFER_NAME "http.server" -#define BUFFER_DESC "http server header" -#define HEADER_NAME "Server" -#define KEYWORD_ID DETECT_AL_HTTP_HEADER_SERVER +#define KEYWORD_NAME "http.server" +#define KEYWORD_DOC "http-keywords.html#http-server" +#define BUFFER_NAME "http.server" +#define BUFFER_DESC "http server header" +#define HEADER_NAME "Server" +#define KEYWORD_ID DETECT_AL_HTTP_HEADER_SERVER #define KEYWORD_TOCLIENT 1 #include "detect-http-headers-stub.h" diff --git a/src/detect-http-start.c b/src/detect-http-start.c index fed1abc96256..8032b9fdd5fe 100644 --- a/src/detect-http-start.c +++ b/src/detect-http-start.c @@ -62,15 +62,15 @@ #include "detect-http-header.h" #include "stream-tcp.h" -#define KEYWORD_NAME "http.start" +#define KEYWORD_NAME "http.start" #define KEYWORD_NAME_LEGACY "http_start" -#define KEYWORD_DOC "http-keywords.html#http-start" -#define BUFFER_NAME "http_start" -#define BUFFER_DESC "http start: request/response line + headers" +#define KEYWORD_DOC "http-keywords.html#http-start" +#define BUFFER_NAME "http_start" +#define BUFFER_DESC "http start: request/response line + headers" static int g_buffer_id = 0; static int g_keyword_thread_id = 0; -#define BUFFER_SIZE_STEP 2048 +#define BUFFER_SIZE_STEP 2048 static HttpHeaderThreadDataConfig g_td_config = { BUFFER_SIZE_STEP }; static uint8_t *GetBufferForTX( @@ -186,7 +186,7 @@ void DetectHttpStartRegister(void) sigmatch_table[DETECT_AL_HTTP_START].desc = BUFFER_NAME " sticky buffer"; sigmatch_table[DETECT_AL_HTTP_START].url = "/rules/" KEYWORD_DOC; sigmatch_table[DETECT_AL_HTTP_START].Setup = DetectHttpStartSetup; - sigmatch_table[DETECT_AL_HTTP_START].flags |= SIGMATCH_NOOPT|SIGMATCH_INFO_STICKY_BUFFER; + sigmatch_table[DETECT_AL_HTTP_START].flags |= SIGMATCH_NOOPT | SIGMATCH_INFO_STICKY_BUFFER; DetectAppLayerMpmRegister2(BUFFER_NAME, SIG_FLAG_TOSERVER, 2, PrefilterGenericMpmRegister, GetBuffer1ForTX, ALPROTO_HTTP1, HTP_REQUEST_HEADERS); @@ -198,16 +198,14 @@ void DetectHttpStartRegister(void) DetectAppLayerInspectEngineRegister2(BUFFER_NAME, ALPROTO_HTTP1, SIG_FLAG_TOCLIENT, HTP_RESPONSE_HEADERS, DetectEngineInspectBufferGeneric, GetBuffer1ForTX); - DetectBufferTypeSetDescriptionByName(BUFFER_NAME, - BUFFER_DESC); + DetectBufferTypeSetDescriptionByName(BUFFER_NAME, BUFFER_DESC); g_buffer_id = DetectBufferTypeGetByName(BUFFER_NAME); - g_keyword_thread_id = DetectRegisterThreadCtxGlobalFuncs(KEYWORD_NAME, - HttpHeaderThreadDataInit, &g_td_config, HttpHeaderThreadDataFree); + g_keyword_thread_id = DetectRegisterThreadCtxGlobalFuncs( + KEYWORD_NAME, HttpHeaderThreadDataInit, &g_td_config, HttpHeaderThreadDataFree); SCLogDebug("keyword %s registered. Thread id %d. " - "Buffer %s registered. Buffer id %d", - KEYWORD_NAME, g_keyword_thread_id, - BUFFER_NAME, g_buffer_id); + "Buffer %s registered. Buffer id %d", + KEYWORD_NAME, g_keyword_thread_id, BUFFER_NAME, g_buffer_id); } diff --git a/src/detect-http-stat-code.c b/src/detect-http-stat-code.c index 1e7087a318b3..f803b45903e9 100644 --- a/src/detect-http-stat-code.c +++ b/src/detect-http-stat-code.c @@ -21,7 +21,6 @@ * @{ */ - /** * \file * @@ -69,8 +68,8 @@ static void DetectHttpStatCodeRegisterTests(void); #endif static int g_http_stat_code_buffer_id = 0; static InspectionBuffer *GetData(DetectEngineThreadCtx *det_ctx, - const DetectEngineTransforms *transforms, Flow *_f, - const uint8_t _flow_flags, void *txv, const int list_id); + const DetectEngineTransforms *transforms, Flow *_f, const uint8_t _flow_flags, void *txv, + const int list_id); static InspectionBuffer *GetData2(DetectEngineThreadCtx *det_ctx, const DetectEngineTransforms *transforms, Flow *_f, const uint8_t _flow_flags, void *txv, const int list_id); @@ -78,25 +77,28 @@ static InspectionBuffer *GetData2(DetectEngineThreadCtx *det_ctx, /** * \brief Registration function for keyword: http_stat_code */ -void DetectHttpStatCodeRegister (void) +void DetectHttpStatCodeRegister(void) { /* http_stat_code content modifier */ sigmatch_table[DETECT_AL_HTTP_STAT_CODE].name = "http_stat_code"; - sigmatch_table[DETECT_AL_HTTP_STAT_CODE].desc = "content modifier to match only on HTTP stat-code-buffer"; + sigmatch_table[DETECT_AL_HTTP_STAT_CODE].desc = + "content modifier to match only on HTTP stat-code-buffer"; sigmatch_table[DETECT_AL_HTTP_STAT_CODE].url = "/rules/http-keywords.html#http-stat-code"; sigmatch_table[DETECT_AL_HTTP_STAT_CODE].Setup = DetectHttpStatCodeSetup; #ifdef UNITTESTS sigmatch_table[DETECT_AL_HTTP_STAT_CODE].RegisterTests = DetectHttpStatCodeRegisterTests; #endif - sigmatch_table[DETECT_AL_HTTP_STAT_CODE].flags |= SIGMATCH_NOOPT|SIGMATCH_INFO_CONTENT_MODIFIER; + sigmatch_table[DETECT_AL_HTTP_STAT_CODE].flags |= + SIGMATCH_NOOPT | SIGMATCH_INFO_CONTENT_MODIFIER; sigmatch_table[DETECT_AL_HTTP_STAT_CODE].alternative = DETECT_HTTP_STAT_CODE; /* http.stat_code content modifier */ sigmatch_table[DETECT_HTTP_STAT_CODE].name = "http.stat_code"; - sigmatch_table[DETECT_HTTP_STAT_CODE].desc = "sticky buffer to match only on HTTP stat-code-buffer"; + sigmatch_table[DETECT_HTTP_STAT_CODE].desc = + "sticky buffer to match only on HTTP stat-code-buffer"; sigmatch_table[DETECT_HTTP_STAT_CODE].url = "/rules/http-keywords.html#http-stat-code"; sigmatch_table[DETECT_HTTP_STAT_CODE].Setup = DetectHttpStatCodeSetupSticky; - sigmatch_table[DETECT_HTTP_STAT_CODE].flags |= SIGMATCH_NOOPT|SIGMATCH_INFO_STICKY_BUFFER; + sigmatch_table[DETECT_HTTP_STAT_CODE].flags |= SIGMATCH_NOOPT | SIGMATCH_INFO_STICKY_BUFFER; DetectAppLayerInspectEngineRegister2("http_stat_code", ALPROTO_HTTP1, SIG_FLAG_TOCLIENT, HTP_RESPONSE_LINE, DetectEngineInspectBufferGeneric, GetData); @@ -110,8 +112,7 @@ void DetectHttpStatCodeRegister (void) DetectAppLayerMpmRegister2("http_stat_code", SIG_FLAG_TOCLIENT, 4, PrefilterGenericMpmRegister, GetData2, ALPROTO_HTTP2, HTTP2StateDataServer); - DetectBufferTypeSetDescriptionByName("http_stat_code", - "http response status code"); + DetectBufferTypeSetDescriptionByName("http_stat_code", "http response status code"); g_http_stat_code_buffer_id = DetectBufferTypeGetByName("http_stat_code"); } @@ -152,8 +153,8 @@ static int DetectHttpStatCodeSetupSticky(DetectEngineCtx *de_ctx, Signature *s, } static InspectionBuffer *GetData(DetectEngineThreadCtx *det_ctx, - const DetectEngineTransforms *transforms, Flow *_f, - const uint8_t _flow_flags, void *txv, const int list_id) + const DetectEngineTransforms *transforms, Flow *_f, const uint8_t _flow_flags, void *txv, + const int list_id) { SCEnter(); diff --git a/src/detect-http-stat-code.h b/src/detect-http-stat-code.h index e813b6a75fc0..dbfe6ca28f3c 100644 --- a/src/detect-http-stat-code.h +++ b/src/detect-http-stat-code.h @@ -22,10 +22,9 @@ */ #ifndef _DETECT_HTTP_STAT_CODE_H -#define _DETECT_HTTP_STAT_CODE_H +#define _DETECT_HTTP_STAT_CODE_H /* prototypes */ void DetectHttpStatCodeRegister(void); -#endif /* _DETECT_HTTP_STAT_CODE_H */ - +#endif /* _DETECT_HTTP_STAT_CODE_H */ diff --git a/src/detect-http-stat-msg.c b/src/detect-http-stat-msg.c index 6be7de64f756..2f2e35f94d92 100644 --- a/src/detect-http-stat-msg.c +++ b/src/detect-http-stat-msg.c @@ -21,7 +21,6 @@ * @{ */ - /** * \file * @@ -68,8 +67,8 @@ static void DetectHttpStatMsgRegisterTests(void); #endif static int g_http_stat_msg_buffer_id = 0; static InspectionBuffer *GetData(DetectEngineThreadCtx *det_ctx, - const DetectEngineTransforms *transforms, Flow *_f, - const uint8_t _flow_flags, void *txv, const int list_id); + const DetectEngineTransforms *transforms, Flow *_f, const uint8_t _flow_flags, void *txv, + const int list_id); static int DetectHttpStatMsgSetupSticky(DetectEngineCtx *de_ctx, Signature *s, const char *str); static InspectionBuffer *GetData2(DetectEngineThreadCtx *det_ctx, @@ -88,25 +87,28 @@ static InspectionBuffer *GetData2(DetectEngineThreadCtx *det_ctx, /** * \brief Registration function for keyword: http_stat_msg */ -void DetectHttpStatMsgRegister (void) +void DetectHttpStatMsgRegister(void) { /* http_stat_msg content modifier */ sigmatch_table[DETECT_AL_HTTP_STAT_MSG].name = "http_stat_msg"; - sigmatch_table[DETECT_AL_HTTP_STAT_MSG].desc = "content modifier to match on HTTP stat-msg-buffer"; + sigmatch_table[DETECT_AL_HTTP_STAT_MSG].desc = + "content modifier to match on HTTP stat-msg-buffer"; sigmatch_table[DETECT_AL_HTTP_STAT_MSG].url = "/rules/http-keywords.html#http-stat-msg"; sigmatch_table[DETECT_AL_HTTP_STAT_MSG].Setup = DetectHttpStatMsgSetup; #ifdef UNITTESTS sigmatch_table[DETECT_AL_HTTP_STAT_MSG].RegisterTests = DetectHttpStatMsgRegisterTests; #endif - sigmatch_table[DETECT_AL_HTTP_STAT_MSG].flags |= SIGMATCH_NOOPT|SIGMATCH_INFO_CONTENT_MODIFIER; + sigmatch_table[DETECT_AL_HTTP_STAT_MSG].flags |= + SIGMATCH_NOOPT | SIGMATCH_INFO_CONTENT_MODIFIER; sigmatch_table[DETECT_AL_HTTP_STAT_MSG].alternative = DETECT_HTTP_STAT_MSG; /* http.stat_msg sticky buffer */ sigmatch_table[DETECT_HTTP_STAT_MSG].name = "http.stat_msg"; - sigmatch_table[DETECT_HTTP_STAT_MSG].desc = "sticky buffer to match on the HTTP response status message"; + sigmatch_table[DETECT_HTTP_STAT_MSG].desc = + "sticky buffer to match on the HTTP response status message"; sigmatch_table[DETECT_HTTP_STAT_MSG].url = "/rules/http-keywords.html#http-stat-msg"; sigmatch_table[DETECT_HTTP_STAT_MSG].Setup = DetectHttpStatMsgSetupSticky; - sigmatch_table[DETECT_HTTP_STAT_MSG].flags |= SIGMATCH_NOOPT|SIGMATCH_INFO_STICKY_BUFFER; + sigmatch_table[DETECT_HTTP_STAT_MSG].flags |= SIGMATCH_NOOPT | SIGMATCH_INFO_STICKY_BUFFER; DetectAppLayerInspectEngineRegister2("http_stat_msg", ALPROTO_HTTP1, SIG_FLAG_TOCLIENT, HTP_RESPONSE_LINE, DetectEngineInspectBufferGeneric, GetData); @@ -119,8 +121,7 @@ void DetectHttpStatMsgRegister (void) DetectAppLayerMpmRegister2("http_stat_msg", SIG_FLAG_TOCLIENT, 2, PrefilterGenericMpmRegister, GetData2, ALPROTO_HTTP2, HTTP2StateDataServer); - DetectBufferTypeSetDescriptionByName("http_stat_msg", - "http response status message"); + DetectBufferTypeSetDescriptionByName("http_stat_msg", "http response status message"); g_http_stat_msg_buffer_id = DetectBufferTypeGetByName("http_stat_msg"); } @@ -161,8 +162,8 @@ static int DetectHttpStatMsgSetupSticky(DetectEngineCtx *de_ctx, Signature *s, c } static InspectionBuffer *GetData(DetectEngineThreadCtx *det_ctx, - const DetectEngineTransforms *transforms, Flow *_f, - const uint8_t _flow_flags, void *txv, const int list_id) + const DetectEngineTransforms *transforms, Flow *_f, const uint8_t _flow_flags, void *txv, + const int list_id) { SCEnter(); diff --git a/src/detect-http-stat-msg.h b/src/detect-http-stat-msg.h index fe82089db4bf..34b30a6c618c 100644 --- a/src/detect-http-stat-msg.h +++ b/src/detect-http-stat-msg.h @@ -22,10 +22,9 @@ */ #ifndef _DETECT_HTTP_STAT_MSG_H -#define _DETECT_HTTP_STAT_MSG_H +#define _DETECT_HTTP_STAT_MSG_H /* prototypes */ void DetectHttpStatMsgRegister(void); -#endif /* _DETECT_HTTP_STAT_MSG_H */ - +#endif /* _DETECT_HTTP_STAT_MSG_H */ diff --git a/src/detect-http-ua.c b/src/detect-http-ua.c index 7138cf93fea4..d8239077ed3e 100644 --- a/src/detect-http-ua.c +++ b/src/detect-http-ua.c @@ -21,7 +21,6 @@ * @{ */ - /** * \file * @@ -66,9 +65,8 @@ static void DetectHttpUARegisterTests(void); static int g_http_ua_buffer_id = 0; static int DetectHttpUserAgentSetup(DetectEngineCtx *, Signature *, const char *); static InspectionBuffer *GetData(DetectEngineThreadCtx *det_ctx, - const DetectEngineTransforms *transforms, - Flow *_f, const uint8_t _flow_flags, - void *txv, const int list_id); + const DetectEngineTransforms *transforms, Flow *_f, const uint8_t _flow_flags, void *txv, + const int list_id); static InspectionBuffer *GetData2(DetectEngineThreadCtx *det_ctx, const DetectEngineTransforms *transforms, Flow *_f, const uint8_t _flow_flags, void *txv, const int list_id); @@ -80,7 +78,8 @@ void DetectHttpUARegister(void) { /* http_user_agent content modifier */ sigmatch_table[DETECT_AL_HTTP_USER_AGENT].name = "http_user_agent"; - sigmatch_table[DETECT_AL_HTTP_USER_AGENT].desc = "content modifier to match only on the HTTP User-Agent header"; + sigmatch_table[DETECT_AL_HTTP_USER_AGENT].desc = + "content modifier to match only on the HTTP User-Agent header"; sigmatch_table[DETECT_AL_HTTP_USER_AGENT].url = "/rules/http-keywords.html#http-user-agent"; sigmatch_table[DETECT_AL_HTTP_USER_AGENT].Setup = DetectHttpUASetup; #ifdef UNITTESTS @@ -92,7 +91,8 @@ void DetectHttpUARegister(void) /* http.user_agent sticky buffer */ sigmatch_table[DETECT_HTTP_UA].name = "http.user_agent"; - sigmatch_table[DETECT_HTTP_UA].desc = "sticky buffer to match specifically and only on the HTTP User Agent buffer"; + sigmatch_table[DETECT_HTTP_UA].desc = + "sticky buffer to match specifically and only on the HTTP User Agent buffer"; sigmatch_table[DETECT_HTTP_UA].url = "/rules/http-keywords.html#http-user-agent"; sigmatch_table[DETECT_HTTP_UA].Setup = DetectHttpUserAgentSetup; sigmatch_table[DETECT_HTTP_UA].flags |= SIGMATCH_NOOPT; @@ -110,8 +110,7 @@ void DetectHttpUARegister(void) DetectAppLayerMpmRegister2("http_user_agent", SIG_FLAG_TOSERVER, 2, PrefilterGenericMpmRegister, GetData2, ALPROTO_HTTP2, HTTP2StateDataClient); - DetectBufferTypeSetDescriptionByName("http_user_agent", - "http user agent"); + DetectBufferTypeSetDescriptionByName("http_user_agent", "http user agent"); g_http_ua_buffer_id = DetectBufferTypeGetByName("http_user_agent"); } @@ -154,8 +153,8 @@ static int DetectHttpUserAgentSetup(DetectEngineCtx *de_ctx, Signature *s, const } static InspectionBuffer *GetData(DetectEngineThreadCtx *det_ctx, - const DetectEngineTransforms *transforms, Flow *_f, - const uint8_t _flow_flags, void *txv, const int list_id) + const DetectEngineTransforms *transforms, Flow *_f, const uint8_t _flow_flags, void *txv, + const int list_id) { InspectionBuffer *buffer = InspectionBufferGet(det_ctx, list_id); if (buffer->inspect == NULL) { @@ -164,8 +163,7 @@ static InspectionBuffer *GetData(DetectEngineThreadCtx *det_ctx, if (tx->request_headers == NULL) return NULL; - htp_header_t *h = (htp_header_t *)htp_table_get_c(tx->request_headers, - "User-Agent"); + htp_header_t *h = (htp_header_t *)htp_table_get_c(tx->request_headers, "User-Agent"); if (h == NULL || h->value == NULL) { SCLogDebug("HTTP UA header not present in this request"); return NULL; diff --git a/src/detect-http-uri.c b/src/detect-http-uri.c index cc43023a783a..f71dbcd2f122 100644 --- a/src/detect-http-uri.c +++ b/src/detect-http-uri.c @@ -21,7 +21,6 @@ * @{ */ - /** * \file * @@ -59,25 +58,21 @@ #ifdef UNITTESTS static void DetectHttpUriRegisterTests(void); #endif -static void DetectHttpUriSetupCallback(const DetectEngineCtx *de_ctx, - Signature *s); +static void DetectHttpUriSetupCallback(const DetectEngineCtx *de_ctx, Signature *s); static bool DetectHttpUriValidateCallback(const Signature *s, const char **sigerror); static InspectionBuffer *GetData(DetectEngineThreadCtx *det_ctx, - const DetectEngineTransforms *transforms, - Flow *_f, const uint8_t _flow_flags, - void *txv, const int list_id); + const DetectEngineTransforms *transforms, Flow *_f, const uint8_t _flow_flags, void *txv, + const int list_id); static InspectionBuffer *GetData2(DetectEngineThreadCtx *det_ctx, const DetectEngineTransforms *transforms, Flow *_f, const uint8_t _flow_flags, void *txv, const int list_id); static int DetectHttpUriSetupSticky(DetectEngineCtx *de_ctx, Signature *s, const char *str); static int DetectHttpRawUriSetup(DetectEngineCtx *, Signature *, const char *); -static void DetectHttpRawUriSetupCallback(const DetectEngineCtx *de_ctx, - Signature *s); +static void DetectHttpRawUriSetupCallback(const DetectEngineCtx *de_ctx, Signature *s); static bool DetectHttpRawUriValidateCallback(const Signature *s, const char **); static InspectionBuffer *GetRawData(DetectEngineThreadCtx *det_ctx, - const DetectEngineTransforms *transforms, - Flow *_f, const uint8_t _flow_flags, - void *txv, const int list_id); + const DetectEngineTransforms *transforms, Flow *_f, const uint8_t _flow_flags, void *txv, + const int list_id); static int DetectHttpRawUriSetupSticky(DetectEngineCtx *de_ctx, Signature *s, const char *str); static int g_http_raw_uri_buffer_id = 0; @@ -86,26 +81,28 @@ static int g_http_uri_buffer_id = 0; /** * \brief Registration function for keywords: http_uri and http.uri */ -void DetectHttpUriRegister (void) +void DetectHttpUriRegister(void) { /* http_uri content modifier */ sigmatch_table[DETECT_AL_HTTP_URI].name = "http_uri"; - sigmatch_table[DETECT_AL_HTTP_URI].desc = "content modifier to match specifically and only on the HTTP uri-buffer"; + sigmatch_table[DETECT_AL_HTTP_URI].desc = + "content modifier to match specifically and only on the HTTP uri-buffer"; sigmatch_table[DETECT_AL_HTTP_URI].url = "/rules/http-keywords.html#http-uri-and-http-uri-raw"; sigmatch_table[DETECT_AL_HTTP_URI].Setup = DetectHttpUriSetup; #ifdef UNITTESTS sigmatch_table[DETECT_AL_HTTP_URI].RegisterTests = DetectHttpUriRegisterTests; #endif - sigmatch_table[DETECT_AL_HTTP_URI].flags |= SIGMATCH_NOOPT|SIGMATCH_INFO_CONTENT_MODIFIER; + sigmatch_table[DETECT_AL_HTTP_URI].flags |= SIGMATCH_NOOPT | SIGMATCH_INFO_CONTENT_MODIFIER; sigmatch_table[DETECT_AL_HTTP_URI].alternative = DETECT_HTTP_URI; /* http.uri sticky buffer */ sigmatch_table[DETECT_HTTP_URI].name = "http.uri"; sigmatch_table[DETECT_HTTP_URI].alias = "http.uri.normalized"; - sigmatch_table[DETECT_HTTP_URI].desc = "sticky buffer to match specifically and only on the normalized HTTP URI buffer"; + sigmatch_table[DETECT_HTTP_URI].desc = + "sticky buffer to match specifically and only on the normalized HTTP URI buffer"; sigmatch_table[DETECT_HTTP_URI].url = "/rules/http-keywords.html#http-uri-and-http-uri-raw"; sigmatch_table[DETECT_HTTP_URI].Setup = DetectHttpUriSetupSticky; - sigmatch_table[DETECT_HTTP_URI].flags |= SIGMATCH_NOOPT|SIGMATCH_INFO_STICKY_BUFFER; + sigmatch_table[DETECT_HTTP_URI].flags |= SIGMATCH_NOOPT | SIGMATCH_INFO_STICKY_BUFFER; DetectAppLayerInspectEngineRegister2("http_uri", ALPROTO_HTTP1, SIG_FLAG_TOSERVER, HTP_REQUEST_LINE, DetectEngineInspectBufferGeneric, GetData); @@ -119,31 +116,30 @@ void DetectHttpUriRegister (void) DetectAppLayerMpmRegister2("http_uri", SIG_FLAG_TOSERVER, 2, PrefilterGenericMpmRegister, GetData2, ALPROTO_HTTP2, HTTP2StateDataClient); - DetectBufferTypeSetDescriptionByName("http_uri", - "http request uri"); + DetectBufferTypeSetDescriptionByName("http_uri", "http request uri"); - DetectBufferTypeRegisterSetupCallback("http_uri", - DetectHttpUriSetupCallback); + DetectBufferTypeRegisterSetupCallback("http_uri", DetectHttpUriSetupCallback); - DetectBufferTypeRegisterValidateCallback("http_uri", - DetectHttpUriValidateCallback); + DetectBufferTypeRegisterValidateCallback("http_uri", DetectHttpUriValidateCallback); g_http_uri_buffer_id = DetectBufferTypeGetByName("http_uri"); /* http_raw_uri content modifier */ sigmatch_table[DETECT_AL_HTTP_RAW_URI].name = "http_raw_uri"; sigmatch_table[DETECT_AL_HTTP_RAW_URI].desc = "content modifier to match on the raw HTTP uri"; - sigmatch_table[DETECT_AL_HTTP_RAW_URI].url = "/rules/http-keywords.html#http_uri-and-http_raw-uri"; + sigmatch_table[DETECT_AL_HTTP_RAW_URI].url = + "/rules/http-keywords.html#http_uri-and-http_raw-uri"; sigmatch_table[DETECT_AL_HTTP_RAW_URI].Setup = DetectHttpRawUriSetup; - sigmatch_table[DETECT_AL_HTTP_RAW_URI].flags |= SIGMATCH_NOOPT|SIGMATCH_INFO_CONTENT_MODIFIER; + sigmatch_table[DETECT_AL_HTTP_RAW_URI].flags |= SIGMATCH_NOOPT | SIGMATCH_INFO_CONTENT_MODIFIER; sigmatch_table[DETECT_AL_HTTP_RAW_URI].alternative = DETECT_HTTP_URI_RAW; /* http.uri.raw sticky buffer */ sigmatch_table[DETECT_HTTP_URI_RAW].name = "http.uri.raw"; - sigmatch_table[DETECT_HTTP_URI_RAW].desc = "sticky buffer to match specifically and only on the raw HTTP URI buffer"; + sigmatch_table[DETECT_HTTP_URI_RAW].desc = + "sticky buffer to match specifically and only on the raw HTTP URI buffer"; sigmatch_table[DETECT_HTTP_URI_RAW].url = "/rules/http-keywords.html#http-uri-and-http-raw-uri"; sigmatch_table[DETECT_HTTP_URI_RAW].Setup = DetectHttpRawUriSetupSticky; - sigmatch_table[DETECT_HTTP_URI_RAW].flags |= SIGMATCH_NOOPT|SIGMATCH_INFO_STICKY_BUFFER; + sigmatch_table[DETECT_HTTP_URI_RAW].flags |= SIGMATCH_NOOPT | SIGMATCH_INFO_STICKY_BUFFER; DetectAppLayerInspectEngineRegister2("http_raw_uri", ALPROTO_HTTP1, SIG_FLAG_TOSERVER, HTP_REQUEST_LINE, DetectEngineInspectBufferGeneric, GetRawData); @@ -158,14 +154,11 @@ void DetectHttpUriRegister (void) DetectAppLayerMpmRegister2("http_raw_uri", SIG_FLAG_TOSERVER, 2, PrefilterGenericMpmRegister, GetData2, ALPROTO_HTTP2, HTTP2StateDataClient); - DetectBufferTypeSetDescriptionByName("http_raw_uri", - "raw http uri"); + DetectBufferTypeSetDescriptionByName("http_raw_uri", "raw http uri"); - DetectBufferTypeRegisterSetupCallback("http_raw_uri", - DetectHttpRawUriSetupCallback); + DetectBufferTypeRegisterSetupCallback("http_raw_uri", DetectHttpRawUriSetupCallback); - DetectBufferTypeRegisterValidateCallback("http_raw_uri", - DetectHttpRawUriValidateCallback); + DetectBufferTypeRegisterValidateCallback("http_raw_uri", DetectHttpRawUriValidateCallback); g_http_raw_uri_buffer_id = DetectBufferTypeGetByName("http_raw_uri"); } @@ -192,8 +185,7 @@ static bool DetectHttpUriValidateCallback(const Signature *s, const char **siger return DetectUrilenValidateContent(s, g_http_uri_buffer_id, sigerror); } -static void DetectHttpUriSetupCallback(const DetectEngineCtx *de_ctx, - Signature *s) +static void DetectHttpUriSetupCallback(const DetectEngineCtx *de_ctx, Signature *s) { SCLogDebug("callback invoked by %u", s->id); DetectUrilenApplyToContent(s, g_http_uri_buffer_id); @@ -218,8 +210,8 @@ static int DetectHttpUriSetupSticky(DetectEngineCtx *de_ctx, Signature *s, const } static InspectionBuffer *GetData(DetectEngineThreadCtx *det_ctx, - const DetectEngineTransforms *transforms, Flow *_f, - const uint8_t _flow_flags, void *txv, const int list_id) + const DetectEngineTransforms *transforms, Flow *_f, const uint8_t _flow_flags, void *txv, + const int list_id) { SCEnter(); @@ -287,8 +279,7 @@ static bool DetectHttpRawUriValidateCallback(const Signature *s, const char **si return DetectUrilenValidateContent(s, g_http_raw_uri_buffer_id, sigerror); } -static void DetectHttpRawUriSetupCallback(const DetectEngineCtx *de_ctx, - Signature *s) +static void DetectHttpRawUriSetupCallback(const DetectEngineCtx *de_ctx, Signature *s) { SCLogDebug("callback invoked by %u", s->id); DetectUrilenApplyToContent(s, g_http_raw_uri_buffer_id); @@ -313,8 +304,8 @@ static int DetectHttpRawUriSetupSticky(DetectEngineCtx *de_ctx, Signature *s, co } static InspectionBuffer *GetRawData(DetectEngineThreadCtx *det_ctx, - const DetectEngineTransforms *transforms, Flow *_f, - const uint8_t _flow_flags, void *txv, const int list_id) + const DetectEngineTransforms *transforms, Flow *_f, const uint8_t _flow_flags, void *txv, + const int list_id) { SCEnter(); diff --git a/src/detect-http-uri.h b/src/detect-http-uri.h index 4db00ac2d5c3..b05b37ed0fa6 100644 --- a/src/detect-http-uri.h +++ b/src/detect-http-uri.h @@ -25,7 +25,7 @@ #define _DETECT_HTTP_URI_H /* prototypes */ -int DetectHttpUriSetup (DetectEngineCtx *, Signature *, const char *); -void DetectHttpUriRegister (void); +int DetectHttpUriSetup(DetectEngineCtx *, Signature *, const char *); +void DetectHttpUriRegister(void); #endif /* _DETECT_HTTP_URI_H */ diff --git a/src/detect-http2.c b/src/detect-http2.c index a1ede963825e..26f515520c11 100644 --- a/src/detect-http2.c +++ b/src/detect-http2.c @@ -40,50 +40,44 @@ #include "util-profiling.h" #ifdef UNITTESTS -void DetectHTTP2frameTypeRegisterTests (void); -void DetectHTTP2errorCodeRegisterTests (void); -void DetectHTTP2priorityRegisterTests (void); -void DetectHTTP2windowRegisterTests (void); -void DetectHTTP2settingsRegisterTests (void); -void DetectHTTP2sizeUpdateRegisterTests (void); +void DetectHTTP2frameTypeRegisterTests(void); +void DetectHTTP2errorCodeRegisterTests(void); +void DetectHTTP2priorityRegisterTests(void); +void DetectHTTP2windowRegisterTests(void); +void DetectHTTP2settingsRegisterTests(void); +void DetectHTTP2sizeUpdateRegisterTests(void); #endif /* prototypes */ -static int DetectHTTP2frametypeMatch(DetectEngineThreadCtx *det_ctx, - Flow *f, uint8_t flags, void *state, void *txv, const Signature *s, - const SigMatchCtx *ctx); -static int DetectHTTP2frametypeSetup (DetectEngineCtx *, Signature *, const char *); -void DetectHTTP2frametypeFree (DetectEngineCtx *, void *); - -static int DetectHTTP2errorcodeMatch(DetectEngineThreadCtx *det_ctx, - Flow *f, uint8_t flags, void *state, void *txv, const Signature *s, - const SigMatchCtx *ctx); -static int DetectHTTP2errorcodeSetup (DetectEngineCtx *, Signature *, const char *); -void DetectHTTP2errorcodeFree (DetectEngineCtx *, void *); - -static int DetectHTTP2priorityMatch(DetectEngineThreadCtx *det_ctx, - Flow *f, uint8_t flags, void *state, void *txv, const Signature *s, - const SigMatchCtx *ctx); -static int DetectHTTP2prioritySetup (DetectEngineCtx *, Signature *, const char *); -void DetectHTTP2priorityFree (DetectEngineCtx *, void *); - -static int DetectHTTP2windowMatch(DetectEngineThreadCtx *det_ctx, - Flow *f, uint8_t flags, void *state, void *txv, const Signature *s, - const SigMatchCtx *ctx); -static int DetectHTTP2windowSetup (DetectEngineCtx *, Signature *, const char *); -void DetectHTTP2windowFree (DetectEngineCtx *, void *); - -static int DetectHTTP2sizeUpdateMatch(DetectEngineThreadCtx *det_ctx, - Flow *f, uint8_t flags, void *state, void *txv, const Signature *s, - const SigMatchCtx *ctx); -static int DetectHTTP2sizeUpdateSetup (DetectEngineCtx *, Signature *, const char *); -void DetectHTTP2sizeUpdateFree (DetectEngineCtx *, void *); - -static int DetectHTTP2settingsMatch(DetectEngineThreadCtx *det_ctx, - Flow *f, uint8_t flags, void *state, void *txv, const Signature *s, - const SigMatchCtx *ctx); -static int DetectHTTP2settingsSetup (DetectEngineCtx *, Signature *, const char *); -void DetectHTTP2settingsFree (DetectEngineCtx *, void *); +static int DetectHTTP2frametypeMatch(DetectEngineThreadCtx *det_ctx, Flow *f, uint8_t flags, + void *state, void *txv, const Signature *s, const SigMatchCtx *ctx); +static int DetectHTTP2frametypeSetup(DetectEngineCtx *, Signature *, const char *); +void DetectHTTP2frametypeFree(DetectEngineCtx *, void *); + +static int DetectHTTP2errorcodeMatch(DetectEngineThreadCtx *det_ctx, Flow *f, uint8_t flags, + void *state, void *txv, const Signature *s, const SigMatchCtx *ctx); +static int DetectHTTP2errorcodeSetup(DetectEngineCtx *, Signature *, const char *); +void DetectHTTP2errorcodeFree(DetectEngineCtx *, void *); + +static int DetectHTTP2priorityMatch(DetectEngineThreadCtx *det_ctx, Flow *f, uint8_t flags, + void *state, void *txv, const Signature *s, const SigMatchCtx *ctx); +static int DetectHTTP2prioritySetup(DetectEngineCtx *, Signature *, const char *); +void DetectHTTP2priorityFree(DetectEngineCtx *, void *); + +static int DetectHTTP2windowMatch(DetectEngineThreadCtx *det_ctx, Flow *f, uint8_t flags, + void *state, void *txv, const Signature *s, const SigMatchCtx *ctx); +static int DetectHTTP2windowSetup(DetectEngineCtx *, Signature *, const char *); +void DetectHTTP2windowFree(DetectEngineCtx *, void *); + +static int DetectHTTP2sizeUpdateMatch(DetectEngineThreadCtx *det_ctx, Flow *f, uint8_t flags, + void *state, void *txv, const Signature *s, const SigMatchCtx *ctx); +static int DetectHTTP2sizeUpdateSetup(DetectEngineCtx *, Signature *, const char *); +void DetectHTTP2sizeUpdateFree(DetectEngineCtx *, void *); + +static int DetectHTTP2settingsMatch(DetectEngineThreadCtx *det_ctx, Flow *f, uint8_t flags, + void *state, void *txv, const Signature *s, const SigMatchCtx *ctx); +static int DetectHTTP2settingsSetup(DetectEngineCtx *, Signature *, const char *); +void DetectHTTP2settingsFree(DetectEngineCtx *, void *); static int DetectHTTP2headerNameSetup(DetectEngineCtx *de_ctx, Signature *s, const char *arg); static int PrefilterMpmHttp2HeaderNameRegister(DetectEngineCtx *de_ctx, SigGroupHead *sgh, @@ -93,7 +87,7 @@ static uint8_t DetectEngineInspectHttp2HeaderName(DetectEngineCtx *de_ctx, const Signature *s, Flow *f, uint8_t flags, void *alstate, void *txv, uint64_t tx_id); #ifdef UNITTESTS -void DetectHTTP2RegisterTests (void); +void DetectHTTP2RegisterTests(void); #endif static int g_http2_match_buffer_id = 0; @@ -150,7 +144,8 @@ void DetectHttp2Register(void) #endif sigmatch_table[DETECT_HTTP2_SIZEUPDATE].name = "http2.size_update"; - sigmatch_table[DETECT_HTTP2_SIZEUPDATE].desc = "match on HTTP2 dynamic headers table size update"; + sigmatch_table[DETECT_HTTP2_SIZEUPDATE].desc = + "match on HTTP2 dynamic headers table size update"; sigmatch_table[DETECT_HTTP2_SIZEUPDATE].url = "/rules/http2-keywords.html#sizeupdate"; sigmatch_table[DETECT_HTTP2_SIZEUPDATE].Match = NULL; sigmatch_table[DETECT_HTTP2_SIZEUPDATE].AppLayerTxMatch = DetectHTTP2sizeUpdateMatch; @@ -161,7 +156,8 @@ void DetectHttp2Register(void) #endif sigmatch_table[DETECT_HTTP2_SETTINGS].name = "http2.settings"; - sigmatch_table[DETECT_HTTP2_SETTINGS].desc = "match on HTTP2 settings identifier and value fields"; + sigmatch_table[DETECT_HTTP2_SETTINGS].desc = + "match on HTTP2 settings identifier and value fields"; sigmatch_table[DETECT_HTTP2_SETTINGS].url = "/rules/http2-keywords.html#settings"; sigmatch_table[DETECT_HTTP2_SETTINGS].Match = NULL; sigmatch_table[DETECT_HTTP2_SETTINGS].AppLayerTxMatch = DetectHTTP2settingsMatch; @@ -172,26 +168,22 @@ void DetectHttp2Register(void) #endif sigmatch_table[DETECT_HTTP2_HEADERNAME].name = "http2.header_name"; - sigmatch_table[DETECT_HTTP2_HEADERNAME].desc = "sticky buffer to match on one HTTP2 header name"; + sigmatch_table[DETECT_HTTP2_HEADERNAME].desc = + "sticky buffer to match on one HTTP2 header name"; sigmatch_table[DETECT_HTTP2_HEADERNAME].url = "/rules/http2-keywords.html#header_name"; sigmatch_table[DETECT_HTTP2_HEADERNAME].Setup = DetectHTTP2headerNameSetup; sigmatch_table[DETECT_HTTP2_HEADERNAME].flags |= SIGMATCH_NOOPT | SIGMATCH_INFO_STICKY_BUFFER; DetectAppLayerMpmRegister2("http2_header_name", SIG_FLAG_TOCLIENT, 2, - PrefilterMpmHttp2HeaderNameRegister, NULL, - ALPROTO_HTTP2, HTTP2StateOpen); - DetectAppLayerInspectEngineRegister2("http2_header_name", - ALPROTO_HTTP2, SIG_FLAG_TOCLIENT, HTTP2StateOpen, - DetectEngineInspectHttp2HeaderName, NULL); + PrefilterMpmHttp2HeaderNameRegister, NULL, ALPROTO_HTTP2, HTTP2StateOpen); + DetectAppLayerInspectEngineRegister2("http2_header_name", ALPROTO_HTTP2, SIG_FLAG_TOCLIENT, + HTTP2StateOpen, DetectEngineInspectHttp2HeaderName, NULL); DetectAppLayerMpmRegister2("http2_header_name", SIG_FLAG_TOSERVER, 2, - PrefilterMpmHttp2HeaderNameRegister, NULL, - ALPROTO_HTTP2, HTTP2StateOpen); - DetectAppLayerInspectEngineRegister2("http2_header_name", - ALPROTO_HTTP2, SIG_FLAG_TOSERVER, HTTP2StateOpen, - DetectEngineInspectHttp2HeaderName, NULL); + PrefilterMpmHttp2HeaderNameRegister, NULL, ALPROTO_HTTP2, HTTP2StateOpen); + DetectAppLayerInspectEngineRegister2("http2_header_name", ALPROTO_HTTP2, SIG_FLAG_TOSERVER, + HTTP2StateOpen, DetectEngineInspectHttp2HeaderName, NULL); DetectBufferTypeSupportsMultiInstance("http2_header_name"); - DetectBufferTypeSetDescriptionByName("http2_header_name", - "HTTP2 header name"); + DetectBufferTypeSetDescriptionByName("http2_header_name", "HTTP2 header name"); g_http2_header_name_buffer_id = DetectBufferTypeGetByName("http2_header_name"); DetectAppLayerInspectEngineRegister2( @@ -204,14 +196,14 @@ void DetectHttp2Register(void) } /** - * \brief This function is used to match HTTP2 frame type rule option on a transaction with those passed via http2.frametype: + * \brief This function is used to match HTTP2 frame type rule option on a transaction with those + * passed via http2.frametype: * * \retval 0 no match * \retval 1 match */ -static int DetectHTTP2frametypeMatch(DetectEngineThreadCtx *det_ctx, - Flow *f, uint8_t flags, void *state, void *txv, const Signature *s, - const SigMatchCtx *ctx) +static int DetectHTTP2frametypeMatch(DetectEngineThreadCtx *det_ctx, Flow *f, uint8_t flags, + void *state, void *txv, const Signature *s, const SigMatchCtx *ctx) { uint8_t *detect = (uint8_t *)ctx; @@ -246,7 +238,7 @@ static int DetectHTTP2FuncParseFrameType(const char *str, uint8_t *ft) * \retval 0 on Success * \retval -1 on Failure */ -static int DetectHTTP2frametypeSetup (DetectEngineCtx *de_ctx, Signature *s, const char *str) +static int DetectHTTP2frametypeSetup(DetectEngineCtx *de_ctx, Signature *s, const char *str) { uint8_t frame_type; @@ -283,20 +275,20 @@ void DetectHTTP2frametypeFree(DetectEngineCtx *de_ctx, void *ptr) } /** - * \brief This function is used to match HTTP2 error code rule option on a transaction with those passed via http2.errorcode: + * \brief This function is used to match HTTP2 error code rule option on a transaction with those + * passed via http2.errorcode: * * \retval 0 no match * \retval 1 match */ -static int DetectHTTP2errorcodeMatch(DetectEngineThreadCtx *det_ctx, - Flow *f, uint8_t flags, void *state, void *txv, const Signature *s, - const SigMatchCtx *ctx) +static int DetectHTTP2errorcodeMatch(DetectEngineThreadCtx *det_ctx, Flow *f, uint8_t flags, + void *state, void *txv, const Signature *s, const SigMatchCtx *ctx) { uint32_t *detect = (uint32_t *)ctx; return rs_http2_tx_has_errorcode(txv, flags, *detect); - //TODOask handle negation rules + // TODOask handle negation rules } static int DetectHTTP2FuncParseErrorCode(const char *str, uint32_t *ec) @@ -326,7 +318,7 @@ static int DetectHTTP2FuncParseErrorCode(const char *str, uint32_t *ec) * \retval 0 on Success * \retval -1 on Failure */ -static int DetectHTTP2errorcodeSetup (DetectEngineCtx *de_ctx, Signature *s, const char *str) +static int DetectHTTP2errorcodeSetup(DetectEngineCtx *de_ctx, Signature *s, const char *str) { uint32_t error_code; @@ -363,14 +355,14 @@ void DetectHTTP2errorcodeFree(DetectEngineCtx *de_ctx, void *ptr) } /** - * \brief This function is used to match HTTP2 error code rule option on a transaction with those passed via http2.priority: + * \brief This function is used to match HTTP2 error code rule option on a transaction with those + * passed via http2.priority: * * \retval 0 no match * \retval 1 match */ -static int DetectHTTP2priorityMatch(DetectEngineThreadCtx *det_ctx, - Flow *f, uint8_t flags, void *state, void *txv, const Signature *s, - const SigMatchCtx *ctx) +static int DetectHTTP2priorityMatch(DetectEngineThreadCtx *det_ctx, Flow *f, uint8_t flags, + void *state, void *txv, const Signature *s, const SigMatchCtx *ctx) { uint32_t nb = 0; @@ -396,7 +388,7 @@ static int DetectHTTP2priorityMatch(DetectEngineThreadCtx *det_ctx, * \retval 0 on Success * \retval -1 on Failure */ -static int DetectHTTP2prioritySetup (DetectEngineCtx *de_ctx, Signature *s, const char *str) +static int DetectHTTP2prioritySetup(DetectEngineCtx *de_ctx, Signature *s, const char *str) { if (DetectSignatureSetAppProto(s, ALPROTO_HTTP2) != 0) return -1; @@ -425,14 +417,14 @@ void DetectHTTP2priorityFree(DetectEngineCtx *de_ctx, void *ptr) } /** - * \brief This function is used to match HTTP2 window rule option on a transaction with those passed via http2.window: + * \brief This function is used to match HTTP2 window rule option on a transaction with those passed + * via http2.window: * * \retval 0 no match * \retval 1 match */ -static int DetectHTTP2windowMatch(DetectEngineThreadCtx *det_ctx, - Flow *f, uint8_t flags, void *state, void *txv, const Signature *s, - const SigMatchCtx *ctx) +static int DetectHTTP2windowMatch(DetectEngineThreadCtx *det_ctx, Flow *f, uint8_t flags, + void *state, void *txv, const Signature *s, const SigMatchCtx *ctx) { uint32_t nb = 0; @@ -458,7 +450,7 @@ static int DetectHTTP2windowMatch(DetectEngineThreadCtx *det_ctx, * \retval 0 on Success * \retval -1 on Failure */ -static int DetectHTTP2windowSetup (DetectEngineCtx *de_ctx, Signature *s, const char *str) +static int DetectHTTP2windowSetup(DetectEngineCtx *de_ctx, Signature *s, const char *str) { if (DetectSignatureSetAppProto(s, ALPROTO_HTTP2) != 0) return -1; @@ -487,21 +479,22 @@ void DetectHTTP2windowFree(DetectEngineCtx *de_ctx, void *ptr) } /** - * \brief This function is used to match HTTP2 size update rule option on a transaction with those passed via http2.size_update: + * \brief This function is used to match HTTP2 size update rule option on a transaction with those + * passed via http2.size_update: * * \retval 0 no match * \retval 1 match */ -static int DetectHTTP2sizeUpdateMatch(DetectEngineThreadCtx *det_ctx, - Flow *f, uint8_t flags, void *state, void *txv, const Signature *s, - const SigMatchCtx *ctx) +static int DetectHTTP2sizeUpdateMatch(DetectEngineThreadCtx *det_ctx, Flow *f, uint8_t flags, + void *state, void *txv, const Signature *s, const SigMatchCtx *ctx) { return rs_http2_detect_sizeupdatectx_match(ctx, txv, flags); } /** - * \brief this function is used to attach the parsed http2.size_update data into the current signature + * \brief this function is used to attach the parsed http2.size_update data into the current + * signature * * \param de_ctx pointer to the Detection Engine Context * \param s pointer to the Current Signature @@ -510,7 +503,7 @@ static int DetectHTTP2sizeUpdateMatch(DetectEngineThreadCtx *det_ctx, * \retval 0 on Success * \retval -1 on Failure */ -static int DetectHTTP2sizeUpdateSetup (DetectEngineCtx *de_ctx, Signature *s, const char *str) +static int DetectHTTP2sizeUpdateSetup(DetectEngineCtx *de_ctx, Signature *s, const char *str) { if (DetectSignatureSetAppProto(s, ALPROTO_HTTP2) != 0) return -1; @@ -539,14 +532,14 @@ void DetectHTTP2sizeUpdateFree(DetectEngineCtx *de_ctx, void *ptr) } /** - * \brief This function is used to match HTTP2 error code rule option on a transaction with those passed via http2.settings: + * \brief This function is used to match HTTP2 error code rule option on a transaction with those + * passed via http2.settings: * * \retval 0 no match * \retval 1 match */ -static int DetectHTTP2settingsMatch(DetectEngineThreadCtx *det_ctx, - Flow *f, uint8_t flags, void *state, void *txv, const Signature *s, - const SigMatchCtx *ctx) +static int DetectHTTP2settingsMatch(DetectEngineThreadCtx *det_ctx, Flow *f, uint8_t flags, + void *state, void *txv, const Signature *s, const SigMatchCtx *ctx) { return rs_http2_detect_settingsctx_match(ctx, txv, flags); @@ -562,7 +555,7 @@ static int DetectHTTP2settingsMatch(DetectEngineThreadCtx *det_ctx, * \retval 0 on Success * \retval -1 on Failure */ -static int DetectHTTP2settingsSetup (DetectEngineCtx *de_ctx, Signature *s, const char *str) +static int DetectHTTP2settingsSetup(DetectEngineCtx *de_ctx, Signature *s, const char *str) { if (DetectSignatureSetAppProto(s, ALPROTO_HTTP2) != 0) return -1; @@ -647,7 +640,7 @@ static void PrefilterTxHttp2HName(DetectEngineThreadCtx *det_ctx, const void *pe uint32_t local_id = 0; - while(1) { + while (1) { // loop until we get a NULL struct MpmListIdDataArgs cbdata = { local_id, txv }; @@ -669,7 +662,7 @@ static void PrefilterTxHttp2HName(DetectEngineThreadCtx *det_ctx, const void *pe static int PrefilterMpmHttp2HeaderNameRegister(DetectEngineCtx *de_ctx, SigGroupHead *sgh, MpmCtx *mpm_ctx, const DetectBufferMpmRegistry *mpm_reg, int list_id) { - //TODOask use PrefilterMpmListId elsewhere + // TODOask use PrefilterMpmListId elsewhere PrefilterMpmListId *pectx = SCCalloc(1, sizeof(*pectx)); if (pectx == NULL) return -1; @@ -677,9 +670,8 @@ static int PrefilterMpmHttp2HeaderNameRegister(DetectEngineCtx *de_ctx, SigGroup pectx->mpm_ctx = mpm_ctx; pectx->transforms = &mpm_reg->transforms; - return PrefilterAppendTxEngine(de_ctx, sgh, PrefilterTxHttp2HName, - mpm_reg->app_v2.alproto, mpm_reg->app_v2.tx_min_progress, - pectx, PrefilterMpmHttp2HNameFree, mpm_reg->name); + return PrefilterAppendTxEngine(de_ctx, sgh, PrefilterTxHttp2HName, mpm_reg->app_v2.alproto, + mpm_reg->app_v2.tx_min_progress, pectx, PrefilterMpmHttp2HNameFree, mpm_reg->name); } static uint8_t DetectEngineInspectHttp2HeaderName(DetectEngineCtx *de_ctx, @@ -694,8 +686,11 @@ static uint8_t DetectEngineInspectHttp2HeaderName(DetectEngineCtx *de_ctx, } while (1) { - //TODOask use MpmListIdDataArgs elsewhere - struct MpmListIdDataArgs cbdata = { local_id, txv, }; + // TODOask use MpmListIdDataArgs elsewhere + struct MpmListIdDataArgs cbdata = { + local_id, + txv, + }; InspectionBuffer *buffer = GetHttp2HNameData(det_ctx, flags, transforms, f, &cbdata, engine->sm_list); diff --git a/src/detect-icmp-id.c b/src/detect-icmp-id.c index 9e8921ec3bbd..47e6843313ee 100644 --- a/src/detect-icmp-id.c +++ b/src/detect-icmp-id.c @@ -43,8 +43,8 @@ static DetectParseRegex parse_regex; -static int DetectIcmpIdMatch(DetectEngineThreadCtx *, Packet *, - const Signature *, const SigMatchCtx *); +static int DetectIcmpIdMatch( + DetectEngineThreadCtx *, Packet *, const Signature *, const SigMatchCtx *); static int DetectIcmpIdSetup(DetectEngineCtx *, Signature *, const char *); #ifdef UNITTESTS static void DetectIcmpIdRegisterTests(void); @@ -56,7 +56,7 @@ static bool PrefilterIcmpIdIsPrefilterable(const Signature *s); /** * \brief Registration function for icode: icmp_id */ -void DetectIcmpIdRegister (void) +void DetectIcmpIdRegister(void) { sigmatch_table[DETECT_ICMP_ID].name = "icmp_id"; sigmatch_table[DETECT_ICMP_ID].desc = "check for a ICMP ID"; @@ -80,7 +80,7 @@ static inline bool GetIcmpId(Packet *p, uint16_t *id) uint16_t pid; if (PKT_IS_ICMPV4(p)) { - switch (ICMPV4_GET_TYPE(p)){ + switch (ICMPV4_GET_TYPE(p)) { case ICMP_ECHOREPLY: case ICMP_ECHO: case ICMP_TIMESTAMP: @@ -89,9 +89,9 @@ static inline bool GetIcmpId(Packet *p, uint16_t *id) case ICMP_INFO_REPLY: case ICMP_ADDRESS: case ICMP_ADDRESSREPLY: - SCLogDebug("ICMPV4_GET_ID(p) %"PRIu16" (network byte order), " - "%"PRIu16" (host byte order)", ICMPV4_GET_ID(p), - SCNtohs(ICMPV4_GET_ID(p))); + SCLogDebug("ICMPV4_GET_ID(p) %" PRIu16 " (network byte order), " + "%" PRIu16 " (host byte order)", + ICMPV4_GET_ID(p), SCNtohs(ICMPV4_GET_ID(p))); pid = ICMPV4_GET_ID(p); break; @@ -103,9 +103,9 @@ static inline bool GetIcmpId(Packet *p, uint16_t *id) switch (ICMPV6_GET_TYPE(p)) { case ICMP6_ECHO_REQUEST: case ICMP6_ECHO_REPLY: - SCLogDebug("ICMPV6_GET_ID(p) %"PRIu16" (network byte order), " - "%"PRIu16" (host byte order)", ICMPV6_GET_ID(p), - SCNtohs(ICMPV6_GET_ID(p))); + SCLogDebug("ICMPV6_GET_ID(p) %" PRIu16 " (network byte order), " + "%" PRIu16 " (host byte order)", + ICMPV6_GET_ID(p), SCNtohs(ICMPV6_GET_ID(p))); pid = ICMPV6_GET_ID(p); break; @@ -133,8 +133,8 @@ static inline bool GetIcmpId(Packet *p, uint16_t *id) * \retval 0 no match * \retval 1 match */ -static int DetectIcmpIdMatch (DetectEngineThreadCtx *det_ctx, Packet *p, - const Signature *s, const SigMatchCtx *ctx) +static int DetectIcmpIdMatch( + DetectEngineThreadCtx *det_ctx, Packet *p, const Signature *s, const SigMatchCtx *ctx) { uint16_t pid; @@ -157,10 +157,10 @@ static int DetectIcmpIdMatch (DetectEngineThreadCtx *det_ctx, Packet *p, * \retval iid pointer to DetectIcmpIdData on success * \retval NULL on failure */ -static DetectIcmpIdData *DetectIcmpIdParse (DetectEngineCtx *de_ctx, const char *icmpidstr) +static DetectIcmpIdData *DetectIcmpIdParse(DetectEngineCtx *de_ctx, const char *icmpidstr) { DetectIcmpIdData *iid = NULL; - char *substr[3] = {NULL, NULL, NULL}; + char *substr[3] = { NULL, NULL, NULL }; int res = 0; size_t pcre2_len; @@ -179,7 +179,7 @@ static DetectIcmpIdData *DetectIcmpIdParse (DetectEngineCtx *de_ctx, const char SCLogError("pcre2_substring_get_bynumber failed"); goto error; } - substr[i-1] = (char *)str_ptr; + substr[i - 1] = (char *)str_ptr; } iid = SCMalloc(sizeof(DetectIcmpIdData)); @@ -187,7 +187,7 @@ static DetectIcmpIdData *DetectIcmpIdParse (DetectEngineCtx *de_ctx, const char goto error; iid->id = 0; - if (substr[0]!= NULL && strlen(substr[0]) != 0) { + if (substr[0] != NULL && strlen(substr[0]) != 0) { if (substr[2] == NULL) { SCLogError("Missing close quote in input"); goto error; @@ -223,9 +223,9 @@ static DetectIcmpIdData *DetectIcmpIdParse (DetectEngineCtx *de_ctx, const char if (substr[i] != NULL) pcre2_substring_free((PCRE2_UCHAR8 *)substr[i]); } - if (iid != NULL) DetectIcmpIdFree(de_ctx, iid); + if (iid != NULL) + DetectIcmpIdFree(de_ctx, iid); return NULL; - } /** @@ -238,12 +238,13 @@ static DetectIcmpIdData *DetectIcmpIdParse (DetectEngineCtx *de_ctx, const char * \retval 0 on Success * \retval -1 on Failure */ -static int DetectIcmpIdSetup (DetectEngineCtx *de_ctx, Signature *s, const char *icmpidstr) +static int DetectIcmpIdSetup(DetectEngineCtx *de_ctx, Signature *s, const char *icmpidstr) { DetectIcmpIdData *iid = NULL; iid = DetectIcmpIdParse(de_ctx, icmpidstr); - if (iid == NULL) goto error; + if (iid == NULL) + goto error; if (SigMatchAppendSMToList( de_ctx, s, DETECT_ICMP_ID, (SigMatchCtx *)iid, DETECT_SM_LIST_MATCH) == NULL) { @@ -257,7 +258,6 @@ static int DetectIcmpIdSetup (DetectEngineCtx *de_ctx, Signature *s, const char if (iid != NULL) DetectIcmpIdFree(de_ctx, iid); return -1; - } /** @@ -265,7 +265,7 @@ static int DetectIcmpIdSetup (DetectEngineCtx *de_ctx, Signature *s, const char * * \param ptr pointer to DetectIcmpIdData */ -void DetectIcmpIdFree (DetectEngineCtx *de_ctx, void *ptr) +void DetectIcmpIdFree(DetectEngineCtx *de_ctx, void *ptr) { DetectIcmpIdData *iid = (DetectIcmpIdData *)ptr; SCFree(iid); @@ -273,8 +273,7 @@ void DetectIcmpIdFree (DetectEngineCtx *de_ctx, void *ptr) /* prefilter code */ -static void -PrefilterPacketIcmpIdMatch(DetectEngineThreadCtx *det_ctx, Packet *p, const void *pectx) +static void PrefilterPacketIcmpIdMatch(DetectEngineThreadCtx *det_ctx, Packet *p, const void *pectx) { const PrefilterPacketHeaderCtx *ctx = pectx; @@ -282,22 +281,19 @@ PrefilterPacketIcmpIdMatch(DetectEngineThreadCtx *det_ctx, Packet *p, const void if (!GetIcmpId(p, &pid)) return; - if (pid == ctx->v1.u16[0]) - { + if (pid == ctx->v1.u16[0]) { SCLogDebug("packet matches ICMP ID %u", ctx->v1.u16[0]); PrefilterAddSids(&det_ctx->pmq, ctx->sigs_array, ctx->sigs_cnt); } } -static void -PrefilterPacketIcmpIdSet(PrefilterPacketHeaderValue *v, void *smctx) +static void PrefilterPacketIcmpIdSet(PrefilterPacketHeaderValue *v, void *smctx) { const DetectIcmpIdData *a = smctx; v->u16[0] = a->id; } -static bool -PrefilterPacketIcmpIdCompare(PrefilterPacketHeaderValue v, void *smctx) +static bool PrefilterPacketIcmpIdCompare(PrefilterPacketHeaderValue v, void *smctx) { const DetectIcmpIdData *a = smctx; if (v.u16[0] == a->id) @@ -307,16 +303,14 @@ PrefilterPacketIcmpIdCompare(PrefilterPacketHeaderValue v, void *smctx) static int PrefilterSetupIcmpId(DetectEngineCtx *de_ctx, SigGroupHead *sgh) { - return PrefilterSetupPacketHeader(de_ctx, sgh, DETECT_ICMP_ID, - PrefilterPacketIcmpIdSet, - PrefilterPacketIcmpIdCompare, - PrefilterPacketIcmpIdMatch); + return PrefilterSetupPacketHeader(de_ctx, sgh, DETECT_ICMP_ID, PrefilterPacketIcmpIdSet, + PrefilterPacketIcmpIdCompare, PrefilterPacketIcmpIdMatch); } static bool PrefilterIcmpIdIsPrefilterable(const Signature *s) { const SigMatch *sm; - for (sm = s->init_data->smlists[DETECT_SM_LIST_MATCH] ; sm != NULL; sm = sm->next) { + for (sm = s->init_data->smlists[DETECT_SM_LIST_MATCH]; sm != NULL; sm = sm->next) { switch (sm->type) { case DETECT_ICMP_ID: return true; @@ -332,7 +326,7 @@ static bool PrefilterIcmpIdIsPrefilterable(const Signature *s) /** * \test DetectIcmpIdParseTest01 is a test for setting a valid icmp_id value */ -static int DetectIcmpIdParseTest01 (void) +static int DetectIcmpIdParseTest01(void) { DetectIcmpIdData *iid = DetectIcmpIdParse(NULL, "300"); FAIL_IF_NULL(iid); @@ -345,7 +339,7 @@ static int DetectIcmpIdParseTest01 (void) * \test DetectIcmpIdParseTest02 is a test for setting a valid icmp_id value * with spaces all around */ -static int DetectIcmpIdParseTest02 (void) +static int DetectIcmpIdParseTest02(void) { DetectIcmpIdData *iid = DetectIcmpIdParse(NULL, " 300 "); FAIL_IF_NULL(iid); @@ -358,7 +352,7 @@ static int DetectIcmpIdParseTest02 (void) * \test DetectIcmpIdParseTest03 is a test for setting a valid icmp_id value * with quotation marks */ -static int DetectIcmpIdParseTest03 (void) +static int DetectIcmpIdParseTest03(void) { DetectIcmpIdData *iid = DetectIcmpIdParse(NULL, "\"300\""); FAIL_IF_NULL(iid); @@ -371,7 +365,7 @@ static int DetectIcmpIdParseTest03 (void) * \test DetectIcmpIdParseTest04 is a test for setting a valid icmp_id value * with quotation marks and spaces all around */ -static int DetectIcmpIdParseTest04 (void) +static int DetectIcmpIdParseTest04(void) { DetectIcmpIdData *iid = DetectIcmpIdParse(NULL, " \" 300 \""); FAIL_IF_NULL(iid); @@ -384,7 +378,7 @@ static int DetectIcmpIdParseTest04 (void) * \test DetectIcmpIdParseTest05 is a test for setting an invalid icmp_id * value with missing quotation marks */ -static int DetectIcmpIdParseTest05 (void) +static int DetectIcmpIdParseTest05(void) { DetectIcmpIdData *iid = DetectIcmpIdParse(NULL, "\"300"); FAIL_IF_NOT_NULL(iid); @@ -396,7 +390,7 @@ static int DetectIcmpIdParseTest05 (void) * icmp_id keyword by creating 2 rules and matching a crafted packet * against them. Only the first one shall trigger. */ -static int DetectIcmpIdMatchTest01 (void) +static int DetectIcmpIdMatchTest01(void) { int result = 0; Packet *p = NULL; @@ -450,7 +444,6 @@ static int DetectIcmpIdMatchTest01 (void) UTHFreePackets(&p, 1); end: return result; - } /** @@ -459,7 +452,7 @@ static int DetectIcmpIdMatchTest01 (void) * against them. The packet is an ICMP packet with no "id" field, * therefore the rule should not trigger. */ -static int DetectIcmpIdMatchTest02 (void) +static int DetectIcmpIdMatchTest02(void) { int result = 0; @@ -532,7 +525,7 @@ static int DetectIcmpIdMatchTest02 (void) return result; } -static void DetectIcmpIdRegisterTests (void) +static void DetectIcmpIdRegisterTests(void) { UtRegisterTest("DetectIcmpIdParseTest01", DetectIcmpIdParseTest01); UtRegisterTest("DetectIcmpIdParseTest02", DetectIcmpIdParseTest02); diff --git a/src/detect-icmp-seq.c b/src/detect-icmp-seq.c index ca32d2cec7ac..e52500b37241 100644 --- a/src/detect-icmp-seq.c +++ b/src/detect-icmp-seq.c @@ -42,8 +42,8 @@ static DetectParseRegex parse_regex; -static int DetectIcmpSeqMatch(DetectEngineThreadCtx *, Packet *, - const Signature *, const SigMatchCtx *); +static int DetectIcmpSeqMatch( + DetectEngineThreadCtx *, Packet *, const Signature *, const SigMatchCtx *); static int DetectIcmpSeqSetup(DetectEngineCtx *, Signature *, const char *); #ifdef UNITTESTS static void DetectIcmpSeqRegisterTests(void); @@ -55,7 +55,7 @@ static bool PrefilterIcmpSeqIsPrefilterable(const Signature *s); /** * \brief Registration function for icmp_seq */ -void DetectIcmpSeqRegister (void) +void DetectIcmpSeqRegister(void) { sigmatch_table[DETECT_ICMP_SEQ].name = "icmp_seq"; sigmatch_table[DETECT_ICMP_SEQ].desc = "check for a ICMP sequence number"; @@ -80,7 +80,7 @@ static inline bool GetIcmpSeq(Packet *p, uint16_t *seq) return false; if (PKT_IS_ICMPV4(p)) { - switch (ICMPV4_GET_TYPE(p)){ + switch (ICMPV4_GET_TYPE(p)) { case ICMP_ECHOREPLY: case ICMP_ECHO: case ICMP_TIMESTAMP: @@ -89,9 +89,9 @@ static inline bool GetIcmpSeq(Packet *p, uint16_t *seq) case ICMP_INFO_REPLY: case ICMP_ADDRESS: case ICMP_ADDRESSREPLY: - SCLogDebug("ICMPV4_GET_SEQ(p) %"PRIu16" (network byte order), " - "%"PRIu16" (host byte order)", ICMPV4_GET_SEQ(p), - SCNtohs(ICMPV4_GET_SEQ(p))); + SCLogDebug("ICMPV4_GET_SEQ(p) %" PRIu16 " (network byte order), " + "%" PRIu16 " (host byte order)", + ICMPV4_GET_SEQ(p), SCNtohs(ICMPV4_GET_SEQ(p))); seqn = ICMPV4_GET_SEQ(p); break; @@ -104,9 +104,9 @@ static inline bool GetIcmpSeq(Packet *p, uint16_t *seq) switch (ICMPV6_GET_TYPE(p)) { case ICMP6_ECHO_REQUEST: case ICMP6_ECHO_REPLY: - SCLogDebug("ICMPV6_GET_SEQ(p) %"PRIu16" (network byte order), " - "%"PRIu16" (host byte order)", ICMPV6_GET_SEQ(p), - SCNtohs(ICMPV6_GET_SEQ(p))); + SCLogDebug("ICMPV6_GET_SEQ(p) %" PRIu16 " (network byte order), " + "%" PRIu16 " (host byte order)", + ICMPV6_GET_SEQ(p), SCNtohs(ICMPV6_GET_SEQ(p))); seqn = ICMPV6_GET_SEQ(p); break; @@ -134,8 +134,8 @@ static inline bool GetIcmpSeq(Packet *p, uint16_t *seq) * \retval 0 no match * \retval 1 match */ -static int DetectIcmpSeqMatch (DetectEngineThreadCtx *det_ctx, Packet *p, - const Signature *s, const SigMatchCtx *ctx) +static int DetectIcmpSeqMatch( + DetectEngineThreadCtx *det_ctx, Packet *p, const Signature *s, const SigMatchCtx *ctx) { uint16_t seqn; @@ -158,10 +158,10 @@ static int DetectIcmpSeqMatch (DetectEngineThreadCtx *det_ctx, Packet *p, * \retval iseq pointer to DetectIcmpSeqData on success * \retval NULL on failure */ -static DetectIcmpSeqData *DetectIcmpSeqParse (DetectEngineCtx *de_ctx, const char *icmpseqstr) +static DetectIcmpSeqData *DetectIcmpSeqParse(DetectEngineCtx *de_ctx, const char *icmpseqstr) { DetectIcmpSeqData *iseq = NULL; - char *substr[3] = {NULL, NULL, NULL}; + char *substr[3] = { NULL, NULL, NULL }; int res = 0; size_t pcre2_len; int i; @@ -180,7 +180,7 @@ static DetectIcmpSeqData *DetectIcmpSeqParse (DetectEngineCtx *de_ctx, const cha SCLogError("pcre2_substring_get_bynumber failed"); goto error; } - substr[i-1] = (char *)str_ptr; + substr[i - 1] = (char *)str_ptr; } iseq = SCMalloc(sizeof(DetectIcmpSeqData)); @@ -226,9 +226,9 @@ static DetectIcmpSeqData *DetectIcmpSeqParse (DetectEngineCtx *de_ctx, const cha if (substr[i] != NULL) pcre2_substring_free((PCRE2_UCHAR8 *)substr[i]); } - if (iseq != NULL) DetectIcmpSeqFree(de_ctx, iseq); + if (iseq != NULL) + DetectIcmpSeqFree(de_ctx, iseq); return NULL; - } /** @@ -241,12 +241,13 @@ static DetectIcmpSeqData *DetectIcmpSeqParse (DetectEngineCtx *de_ctx, const cha * \retval 0 on Success * \retval -1 on Failure */ -static int DetectIcmpSeqSetup (DetectEngineCtx *de_ctx, Signature *s, const char *icmpseqstr) +static int DetectIcmpSeqSetup(DetectEngineCtx *de_ctx, Signature *s, const char *icmpseqstr) { DetectIcmpSeqData *iseq = NULL; iseq = DetectIcmpSeqParse(de_ctx, icmpseqstr); - if (iseq == NULL) goto error; + if (iseq == NULL) + goto error; if (SigMatchAppendSMToList( de_ctx, s, DETECT_ICMP_SEQ, (SigMatchCtx *)iseq, DETECT_SM_LIST_MATCH) == NULL) { @@ -259,7 +260,6 @@ static int DetectIcmpSeqSetup (DetectEngineCtx *de_ctx, Signature *s, const char if (iseq != NULL) DetectIcmpSeqFree(de_ctx, iseq); return -1; - } /** @@ -267,7 +267,7 @@ static int DetectIcmpSeqSetup (DetectEngineCtx *de_ctx, Signature *s, const char * * \param ptr pointer to DetectIcmpSeqData */ -void DetectIcmpSeqFree (DetectEngineCtx *de_ctx, void *ptr) +void DetectIcmpSeqFree(DetectEngineCtx *de_ctx, void *ptr) { DetectIcmpSeqData *iseq = (DetectIcmpSeqData *)ptr; SCFree(iseq); @@ -275,8 +275,8 @@ void DetectIcmpSeqFree (DetectEngineCtx *de_ctx, void *ptr) /* prefilter code */ -static void -PrefilterPacketIcmpSeqMatch(DetectEngineThreadCtx *det_ctx, Packet *p, const void *pectx) +static void PrefilterPacketIcmpSeqMatch( + DetectEngineThreadCtx *det_ctx, Packet *p, const void *pectx) { const PrefilterPacketHeaderCtx *ctx = pectx; @@ -285,22 +285,19 @@ PrefilterPacketIcmpSeqMatch(DetectEngineThreadCtx *det_ctx, Packet *p, const voi if (!GetIcmpSeq(p, &seqn)) return; - if (seqn == ctx->v1.u16[0]) - { + if (seqn == ctx->v1.u16[0]) { SCLogDebug("packet matches ICMP SEQ %u", ctx->v1.u16[0]); PrefilterAddSids(&det_ctx->pmq, ctx->sigs_array, ctx->sigs_cnt); } } -static void -PrefilterPacketIcmpSeqSet(PrefilterPacketHeaderValue *v, void *smctx) +static void PrefilterPacketIcmpSeqSet(PrefilterPacketHeaderValue *v, void *smctx) { const DetectIcmpSeqData *a = smctx; v->u16[0] = a->seq; } -static bool -PrefilterPacketIcmpSeqCompare(PrefilterPacketHeaderValue v, void *smctx) +static bool PrefilterPacketIcmpSeqCompare(PrefilterPacketHeaderValue v, void *smctx) { const DetectIcmpSeqData *a = smctx; if (v.u16[0] == a->seq) @@ -310,16 +307,14 @@ PrefilterPacketIcmpSeqCompare(PrefilterPacketHeaderValue v, void *smctx) static int PrefilterSetupIcmpSeq(DetectEngineCtx *de_ctx, SigGroupHead *sgh) { - return PrefilterSetupPacketHeader(de_ctx, sgh, DETECT_ICMP_SEQ, - PrefilterPacketIcmpSeqSet, - PrefilterPacketIcmpSeqCompare, - PrefilterPacketIcmpSeqMatch); + return PrefilterSetupPacketHeader(de_ctx, sgh, DETECT_ICMP_SEQ, PrefilterPacketIcmpSeqSet, + PrefilterPacketIcmpSeqCompare, PrefilterPacketIcmpSeqMatch); } static bool PrefilterIcmpSeqIsPrefilterable(const Signature *s) { const SigMatch *sm; - for (sm = s->init_data->smlists[DETECT_SM_LIST_MATCH] ; sm != NULL; sm = sm->next) { + for (sm = s->init_data->smlists[DETECT_SM_LIST_MATCH]; sm != NULL; sm = sm->next) { switch (sm->type) { case DETECT_ICMP_SEQ: return true; @@ -336,7 +331,7 @@ static bool PrefilterIcmpSeqIsPrefilterable(const Signature *s) /** * \test DetectIcmpSeqParseTest01 is a test for setting a valid icmp_seq value */ -static int DetectIcmpSeqParseTest01 (void) +static int DetectIcmpSeqParseTest01(void) { DetectIcmpSeqData *iseq = NULL; iseq = DetectIcmpSeqParse(NULL, "300"); @@ -350,7 +345,7 @@ static int DetectIcmpSeqParseTest01 (void) * \test DetectIcmpSeqParseTest02 is a test for setting a valid icmp_seq value * with spaces all around */ -static int DetectIcmpSeqParseTest02 (void) +static int DetectIcmpSeqParseTest02(void) { DetectIcmpSeqData *iseq = NULL; iseq = DetectIcmpSeqParse(NULL, " 300 "); @@ -363,14 +358,14 @@ static int DetectIcmpSeqParseTest02 (void) /** * \test DetectIcmpSeqParseTest03 is a test for setting an invalid icmp_seq value */ -static int DetectIcmpSeqParseTest03 (void) +static int DetectIcmpSeqParseTest03(void) { DetectIcmpSeqData *iseq = DetectIcmpSeqParse(NULL, "badc"); FAIL_IF_NOT_NULL(iseq); PASS; } -static void DetectIcmpSeqRegisterTests (void) +static void DetectIcmpSeqRegisterTests(void) { UtRegisterTest("DetectIcmpSeqParseTest01", DetectIcmpSeqParseTest01); UtRegisterTest("DetectIcmpSeqParseTest02", DetectIcmpSeqParseTest02); diff --git a/src/detect-icmp-seq.h b/src/detect-icmp-seq.h index e148177b8dad..569552d65702 100644 --- a/src/detect-icmp-seq.h +++ b/src/detect-icmp-seq.h @@ -13,7 +13,7 @@ * version 2 along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. -*/ + */ /** * \file diff --git a/src/detect-icmpv6-mtu.c b/src/detect-icmpv6-mtu.c index f84e484e90ae..2ac3c7577948 100644 --- a/src/detect-icmpv6-mtu.c +++ b/src/detect-icmpv6-mtu.c @@ -31,12 +31,12 @@ #include "detect-engine-uint.h" /* prototypes */ -static int DetectICMPv6mtuMatch (DetectEngineThreadCtx *, Packet *, - const Signature *, const SigMatchCtx *); -static int DetectICMPv6mtuSetup (DetectEngineCtx *, Signature *, const char *); -void DetectICMPv6mtuFree (DetectEngineCtx *de_ctx, void *); +static int DetectICMPv6mtuMatch( + DetectEngineThreadCtx *, Packet *, const Signature *, const SigMatchCtx *); +static int DetectICMPv6mtuSetup(DetectEngineCtx *, Signature *, const char *); +void DetectICMPv6mtuFree(DetectEngineCtx *de_ctx, void *); #ifdef UNITTESTS -void DetectICMPv6mtuRegisterTests (void); +void DetectICMPv6mtuRegisterTests(void); #endif static int PrefilterSetupIcmpv6mtu(DetectEngineCtx *de_ctx, SigGroupHead *sgh); static bool PrefilterIcmpv6mtuIsPrefilterable(const Signature *s); @@ -76,7 +76,8 @@ static inline int DetectICMPv6mtuGetValue(Packet *p, uint32_t *picmpv6mtu) } /** - * \brief This function is used to match ICMPV6 MTU rule option on a packet with those passed via icmpv6.mtu: + * \brief This function is used to match ICMPV6 MTU rule option on a packet with those passed via + * icmpv6.mtu: * * \param det_ctx pointer to the pattern matcher thread * \param p pointer to the current packet @@ -86,8 +87,8 @@ static inline int DetectICMPv6mtuGetValue(Packet *p, uint32_t *picmpv6mtu) * \retval 0 no match * \retval 1 match */ -static int DetectICMPv6mtuMatch (DetectEngineThreadCtx *det_ctx, Packet *p, - const Signature *s, const SigMatchCtx *ctx) +static int DetectICMPv6mtuMatch( + DetectEngineThreadCtx *det_ctx, Packet *p, const Signature *s, const SigMatchCtx *ctx) { uint32_t picmpv6mtu; if (DetectICMPv6mtuGetValue(p, &picmpv6mtu) == 0) { @@ -108,7 +109,7 @@ static int DetectICMPv6mtuMatch (DetectEngineThreadCtx *det_ctx, Packet *p, * \retval 0 on Success * \retval -1 on Failure */ -static int DetectICMPv6mtuSetup (DetectEngineCtx *de_ctx, Signature *s, const char *icmpv6mtustr) +static int DetectICMPv6mtuSetup(DetectEngineCtx *de_ctx, Signature *s, const char *icmpv6mtustr) { DetectU32Data *icmpv6mtud = DetectU32Parse(icmpv6mtustr); if (icmpv6mtud == NULL) @@ -137,8 +138,8 @@ void DetectICMPv6mtuFree(DetectEngineCtx *de_ctx, void *ptr) /* prefilter code */ -static void -PrefilterPacketIcmpv6mtuMatch(DetectEngineThreadCtx *det_ctx, Packet *p, const void *pectx) +static void PrefilterPacketIcmpv6mtuMatch( + DetectEngineThreadCtx *det_ctx, Packet *p, const void *pectx) { uint32_t picmpv6mtu; if (DetectICMPv6mtuGetValue(p, &picmpv6mtu) == 0) { @@ -157,8 +158,7 @@ PrefilterPacketIcmpv6mtuMatch(DetectEngineThreadCtx *det_ctx, Packet *p, const v du32.mode = ctx->v1.u8[0]; du32.arg1 = ctx->v1.u32[1]; du32.arg2 = ctx->v1.u32[2]; - if (DetectU32Match(picmpv6mtu, &du32)) - { + if (DetectU32Match(picmpv6mtu, &du32)) { SCLogDebug("packet matches icmpv6.mtu/hl %u", picmpv6mtu); PrefilterAddSids(&det_ctx->pmq, ctx->sigs_array, ctx->sigs_cnt); } @@ -166,10 +166,8 @@ PrefilterPacketIcmpv6mtuMatch(DetectEngineThreadCtx *det_ctx, Packet *p, const v static int PrefilterSetupIcmpv6mtu(DetectEngineCtx *de_ctx, SigGroupHead *sgh) { - return PrefilterSetupPacketHeader(de_ctx, sgh, DETECT_ICMPV6MTU, - PrefilterPacketU32Set, - PrefilterPacketU32Compare, - PrefilterPacketIcmpv6mtuMatch); + return PrefilterSetupPacketHeader(de_ctx, sgh, DETECT_ICMPV6MTU, PrefilterPacketU32Set, + PrefilterPacketU32Compare, PrefilterPacketIcmpv6mtuMatch); } static bool PrefilterIcmpv6mtuIsPrefilterable(const Signature *s) diff --git a/src/detect-icmpv6hdr.c b/src/detect-icmpv6hdr.c index 0d990e110866..5c8d790e1395 100644 --- a/src/detect-icmpv6hdr.c +++ b/src/detect-icmpv6hdr.c @@ -35,9 +35,9 @@ #include "util-validate.h" /* prototypes */ -static int DetectICMPv6hdrSetup (DetectEngineCtx *, Signature *, const char *); +static int DetectICMPv6hdrSetup(DetectEngineCtx *, Signature *, const char *); #ifdef UNITTESTS -void DetectICMPv6hdrRegisterTests (void); +void DetectICMPv6hdrRegisterTests(void); #endif static int g_icmpv6hdr_buffer_id = 0; @@ -66,8 +66,7 @@ void DetectICMPv6hdrRegister(void) DetectPktMpmRegister("icmpv6.hdr", 2, PrefilterGenericMpmPktRegister, GetData); - DetectPktInspectEngineRegister("icmpv6.hdr", GetData, - DetectEngineInspectPktBufferGeneric); + DetectPktInspectEngineRegister("icmpv6.hdr", GetData, DetectEngineInspectPktBufferGeneric); return; } @@ -82,7 +81,7 @@ void DetectICMPv6hdrRegister(void) * \retval 0 on Success * \retval -1 on Failure */ -static int DetectICMPv6hdrSetup (DetectEngineCtx *de_ctx, Signature *s, const char *_unused) +static int DetectICMPv6hdrSetup(DetectEngineCtx *de_ctx, Signature *s, const char *_unused) { // ICMPv6 comes only with IPv6 s->proto.flags |= DETECT_PROTO_IPV6; @@ -110,10 +109,8 @@ static InspectionBuffer *GetData(DetectEngineThreadCtx *det_ctx, return NULL; } if (((uint8_t *)p->icmpv6h + (ptrdiff_t)hlen) > - ((uint8_t *)GET_PKT_DATA(p) + (ptrdiff_t)GET_PKT_LEN(p))) - { - SCLogDebug("data out of range: %p > %p", - ((uint8_t *)p->icmpv6h + (ptrdiff_t)hlen), + ((uint8_t *)GET_PKT_DATA(p) + (ptrdiff_t)GET_PKT_LEN(p))) { + SCLogDebug("data out of range: %p > %p", ((uint8_t *)p->icmpv6h + (ptrdiff_t)hlen), ((uint8_t *)GET_PKT_DATA(p) + (ptrdiff_t)GET_PKT_LEN(p))); SCReturnPtr(NULL, "InspectionBuffer"); } diff --git a/src/detect-icmpv6hdr.h b/src/detect-icmpv6hdr.h index 18e91ae3c3c0..ad47f6395d98 100644 --- a/src/detect-icmpv6hdr.h +++ b/src/detect-icmpv6hdr.h @@ -26,4 +26,4 @@ void DetectICMPv6hdrRegister(void); -#endif /* _DETECT_ICMPV6HDR_H */ +#endif /* _DETECT_ICMPV6HDR_H */ diff --git a/src/detect-icode.c b/src/detect-icode.c index 1e7d1cc060af..621887dd2257 100644 --- a/src/detect-icode.c +++ b/src/detect-icode.c @@ -43,8 +43,8 @@ *\brief Regex for parsing our icode options */ -static int DetectICodeMatch(DetectEngineThreadCtx *, Packet *, - const Signature *, const SigMatchCtx *); +static int DetectICodeMatch( + DetectEngineThreadCtx *, Packet *, const Signature *, const SigMatchCtx *); static int DetectICodeSetup(DetectEngineCtx *, Signature *, const char *); #ifdef UNITTESTS static void DetectICodeRegisterTests(void); @@ -57,7 +57,7 @@ static bool PrefilterICodeIsPrefilterable(const Signature *s); /** * \brief Registration function for icode: keyword */ -void DetectICodeRegister (void) +void DetectICodeRegister(void) { sigmatch_table[DETECT_ICODE].name = "icode"; sigmatch_table[DETECT_ICODE].desc = "match on specific ICMP id-value"; @@ -84,8 +84,8 @@ void DetectICodeRegister (void) * \retval 0 no match * \retval 1 match */ -static int DetectICodeMatch (DetectEngineThreadCtx *det_ctx, Packet *p, - const Signature *s, const SigMatchCtx *ctx) +static int DetectICodeMatch( + DetectEngineThreadCtx *det_ctx, Packet *p, const Signature *s, const SigMatchCtx *ctx) { if (PKT_IS_PSEUDOPKT(p)) return 0; @@ -120,7 +120,8 @@ static int DetectICodeSetup(DetectEngineCtx *de_ctx, Signature *s, const char *i DetectU8Data *icd = NULL; icd = DetectU8Parse(icodestr); - if (icd == NULL) goto error; + if (icd == NULL) + goto error; if (SigMatchAppendSMToList(de_ctx, s, DETECT_ICODE, (SigMatchCtx *)icd, DETECT_SM_LIST_MATCH) == NULL) { @@ -148,8 +149,7 @@ void DetectICodeFree(DetectEngineCtx *de_ctx, void *ptr) /* prefilter code */ -static void PrefilterPacketICodeMatch(DetectEngineThreadCtx *det_ctx, - Packet *p, const void *pectx) +static void PrefilterPacketICodeMatch(DetectEngineThreadCtx *det_ctx, Packet *p, const void *pectx) { if (PKT_IS_PSEUDOPKT(p)) { SCReturn; @@ -181,7 +181,7 @@ static int PrefilterSetupICode(DetectEngineCtx *de_ctx, SigGroupHead *sgh) static bool PrefilterICodeIsPrefilterable(const Signature *s) { const SigMatch *sm; - for (sm = s->init_data->smlists[DETECT_SM_LIST_MATCH] ; sm != NULL; sm = sm->next) { + for (sm = s->init_data->smlists[DETECT_SM_LIST_MATCH]; sm != NULL; sm = sm->next) { switch (sm->type) { case DETECT_ICODE: return true; diff --git a/src/detect-id.c b/src/detect-id.c index 6725b7c1367e..0a1f5d8ff5fa 100644 --- a/src/detect-id.c +++ b/src/detect-id.c @@ -44,13 +44,12 @@ /** * \brief Regex for parsing "id" option, matching number or "number" */ -#define PARSE_REGEX "^\\s*([0-9]{1,5}|\"[0-9]{1,5}\")\\s*$" +#define PARSE_REGEX "^\\s*([0-9]{1,5}|\"[0-9]{1,5}\")\\s*$" static DetectParseRegex parse_regex; -static int DetectIdMatch (DetectEngineThreadCtx *, Packet *, - const Signature *, const SigMatchCtx *); -static int DetectIdSetup (DetectEngineCtx *, Signature *, const char *); +static int DetectIdMatch(DetectEngineThreadCtx *, Packet *, const Signature *, const SigMatchCtx *); +static int DetectIdSetup(DetectEngineCtx *, Signature *, const char *); #ifdef UNITTESTS static void DetectIdRegisterTests(void); #endif @@ -62,14 +61,14 @@ static bool PrefilterIdIsPrefilterable(const Signature *s); /** * \brief Registration function for keyword: id */ -void DetectIdRegister (void) +void DetectIdRegister(void) { sigmatch_table[DETECT_ID].name = "id"; sigmatch_table[DETECT_ID].desc = "match on a specific IP ID value"; sigmatch_table[DETECT_ID].url = "/rules/header-keywords.html#id"; sigmatch_table[DETECT_ID].Match = DetectIdMatch; sigmatch_table[DETECT_ID].Setup = DetectIdSetup; - sigmatch_table[DETECT_ID].Free = DetectIdFree; + sigmatch_table[DETECT_ID].Free = DetectIdFree; #ifdef UNITTESTS sigmatch_table[DETECT_ID].RegisterTests = DetectIdRegisterTests; #endif @@ -90,8 +89,8 @@ void DetectIdRegister (void) * \retval 0 no match * \retval 1 match */ -static int DetectIdMatch (DetectEngineThreadCtx *det_ctx, Packet *p, - const Signature *s, const SigMatchCtx *ctx) +static int DetectIdMatch( + DetectEngineThreadCtx *det_ctx, Packet *p, const Signature *s, const SigMatchCtx *ctx) { const DetectIdData *id_d = (const DetectIdData *)ctx; @@ -103,8 +102,7 @@ static int DetectIdMatch (DetectEngineThreadCtx *det_ctx, Packet *p, } if (id_d->id == IPV4_GET_IPID(p)) { - SCLogDebug("IPV4 Proto and matched with ip_id: %u.\n", - id_d->id); + SCLogDebug("IPV4 Proto and matched with ip_id: %u.\n", id_d->id); return 1; } @@ -119,7 +117,7 @@ static int DetectIdMatch (DetectEngineThreadCtx *det_ctx, Packet *p, * \retval id_d pointer to DetectIdData on success * \retval NULL on failure */ -static DetectIdData *DetectIdParse (const char *idstr) +static DetectIdData *DetectIdParse(const char *idstr) { uint16_t temp; DetectIdData *id_d = NULL; @@ -147,8 +145,7 @@ static DetectIdData *DetectIdParse (const char *idstr) tmp_str = copy_str; /* Let's see if we need to scape "'s */ - if (tmp_str[0] == '"') - { + if (tmp_str[0] == '"') { tmp_str[strlen(tmp_str) - 1] = '\0'; tmp_str += 1; } @@ -188,7 +185,7 @@ static DetectIdData *DetectIdParse (const char *idstr) * \retval 0 on Success * \retval -1 on Failure */ -int DetectIdSetup (DetectEngineCtx *de_ctx, Signature *s, const char *idstr) +int DetectIdSetup(DetectEngineCtx *de_ctx, Signature *s, const char *idstr) { DetectIdData *id_d = NULL; @@ -220,8 +217,7 @@ void DetectIdFree(DetectEngineCtx *de_ctx, void *ptr) /* prefilter code */ -static void -PrefilterPacketIdMatch(DetectEngineThreadCtx *det_ctx, Packet *p, const void *pectx) +static void PrefilterPacketIdMatch(DetectEngineThreadCtx *det_ctx, Packet *p, const void *pectx) { const PrefilterPacketHeaderCtx *ctx = pectx; @@ -232,22 +228,19 @@ PrefilterPacketIdMatch(DetectEngineThreadCtx *det_ctx, Packet *p, const void *pe if (!PrefilterPacketHeaderExtraMatch(ctx, p)) return; - if (IPV4_GET_IPID(p) == ctx->v1.u16[0]) - { + if (IPV4_GET_IPID(p) == ctx->v1.u16[0]) { SCLogDebug("packet matches IP id %u", ctx->v1.u16[0]); PrefilterAddSids(&det_ctx->pmq, ctx->sigs_array, ctx->sigs_cnt); } } -static void -PrefilterPacketIdSet(PrefilterPacketHeaderValue *v, void *smctx) +static void PrefilterPacketIdSet(PrefilterPacketHeaderValue *v, void *smctx) { const DetectIdData *a = smctx; v->u16[0] = a->id; } -static bool -PrefilterPacketIdCompare(PrefilterPacketHeaderValue v, void *smctx) +static bool PrefilterPacketIdCompare(PrefilterPacketHeaderValue v, void *smctx) { const DetectIdData *a = smctx; if (v.u16[0] == a->id) @@ -257,16 +250,14 @@ PrefilterPacketIdCompare(PrefilterPacketHeaderValue v, void *smctx) static int PrefilterSetupId(DetectEngineCtx *de_ctx, SigGroupHead *sgh) { - return PrefilterSetupPacketHeader(de_ctx, sgh, DETECT_ID, - PrefilterPacketIdSet, - PrefilterPacketIdCompare, - PrefilterPacketIdMatch); + return PrefilterSetupPacketHeader(de_ctx, sgh, DETECT_ID, PrefilterPacketIdSet, + PrefilterPacketIdCompare, PrefilterPacketIdMatch); } static bool PrefilterIdIsPrefilterable(const Signature *s) { const SigMatch *sm; - for (sm = s->init_data->smlists[DETECT_SM_LIST_MATCH] ; sm != NULL; sm = sm->next) { + for (sm = s->init_data->smlists[DETECT_SM_LIST_MATCH]; sm != NULL; sm = sm->next) { switch (sm->type) { case DETECT_ID: return true; @@ -281,7 +272,7 @@ static bool PrefilterIdIsPrefilterable(const Signature *s) * \test DetectIdTestParse01 is a test to make sure that we parse the "id" * option correctly when given valid id option */ -static int DetectIdTestParse01 (void) +static int DetectIdTestParse01(void) { DetectIdData *id_d = DetectIdParse(" 35402 "); @@ -298,7 +289,7 @@ static int DetectIdTestParse01 (void) * option correctly when given an invalid id option * it should return id_d = NULL */ -static int DetectIdTestParse02 (void) +static int DetectIdTestParse02(void) { DetectIdData *id_d = DetectIdParse("65537"); @@ -312,7 +303,7 @@ static int DetectIdTestParse02 (void) * option correctly when given an invalid id option * it should return id_d = NULL */ -static int DetectIdTestParse03 (void) +static int DetectIdTestParse03(void) { DetectIdData *id_d = DetectIdParse("12what?"); @@ -325,7 +316,7 @@ static int DetectIdTestParse03 (void) * \test DetectIdTestParse04 is a test to make sure that we parse the "id" * option correctly when given valid id option but wrapped with "'s */ -static int DetectIdTestParse04 (void) +static int DetectIdTestParse04(void) { /* yep, look if we trim blank spaces correctly and ignore "'s */ DetectIdData *id_d = DetectIdParse(" \"35402\" "); @@ -365,19 +356,19 @@ static int DetectIdTestMatch01(void) p[2]->ip4h->ip_id = htons(5101); const char *sigs[3]; - sigs[0]= "alert ip any any -> any any (msg:\"Testing id 1\"; id:1234; sid:1;)"; - sigs[1]= "alert ip any any -> any any (msg:\"Testing id 2\"; id:5678; sid:2;)"; - sigs[2]= "alert ip any any -> any any (msg:\"Testing id 3\"; id:5101; sid:3;)"; + sigs[0] = "alert ip any any -> any any (msg:\"Testing id 1\"; id:1234; sid:1;)"; + sigs[1] = "alert ip any any -> any any (msg:\"Testing id 2\"; id:5678; sid:2;)"; + sigs[2] = "alert ip any any -> any any (msg:\"Testing id 3\"; id:5101; sid:3;)"; - uint32_t sid[3] = {1, 2, 3}; + uint32_t sid[3] = { 1, 2, 3 }; - uint32_t results[3][3] = { - /* packet 0 match sid 1 but should not match sid 2 */ - {1, 0, 0}, - /* packet 1 should not match */ - {0, 1, 0}, - /* packet 2 should not match */ - {0, 0, 1} }; + uint32_t results[3][3] = { /* packet 0 match sid 1 but should not match sid 2 */ + { 1, 0, 0 }, + /* packet 1 should not match */ + { 0, 1, 0 }, + /* packet 2 should not match */ + { 0, 0, 1 } + }; FAIL_IF_NOT(UTHGenericTest(p, 3, sigs, sid, (uint32_t *)results, 3)); @@ -396,6 +387,5 @@ void DetectIdRegisterTests(void) UtRegisterTest("DetectIdTestParse03", DetectIdTestParse03); UtRegisterTest("DetectIdTestParse04", DetectIdTestParse04); UtRegisterTest("DetectIdTestMatch01", DetectIdTestMatch01); - } #endif /* UNITTESTS */ diff --git a/src/detect-id.h b/src/detect-id.h index 3198c9c31e0d..f5d58ee9fd04 100644 --- a/src/detect-id.h +++ b/src/detect-id.h @@ -24,16 +24,14 @@ #ifndef __DETECT_ID_H__ #define __DETECT_ID_H__ - #define DETECT_IPID_MIN 0 #define DETECT_IPID_MAX 65536 typedef struct DetectIdData_ { - uint16_t id; /** ip->id to match */ + uint16_t id; /** ip->id to match */ } DetectIdData; /* prototypes */ -void DetectIdRegister (void); +void DetectIdRegister(void); #endif /* __DETECT_ID_H__ */ - diff --git a/src/detect-ipopts.c b/src/detect-ipopts.c index e4e9e22a36a3..2856dfd16318 100644 --- a/src/detect-ipopts.c +++ b/src/detect-ipopts.c @@ -42,9 +42,9 @@ static DetectParseRegex parse_regex; -static int DetectIpOptsMatch (DetectEngineThreadCtx *, Packet *, - const Signature *, const SigMatchCtx *); -static int DetectIpOptsSetup (DetectEngineCtx *, Signature *, const char *); +static int DetectIpOptsMatch( + DetectEngineThreadCtx *, Packet *, const Signature *, const SigMatchCtx *); +static int DetectIpOptsSetup(DetectEngineCtx *, Signature *, const char *); #ifdef UNITTESTS static void IpOptsRegisterTests(void); #endif @@ -53,14 +53,14 @@ void DetectIpOptsFree(DetectEngineCtx *, void *); /** * \brief Registration function for ipopts: keyword */ -void DetectIpOptsRegister (void) +void DetectIpOptsRegister(void) { sigmatch_table[DETECT_IPOPTS].name = "ipopts"; sigmatch_table[DETECT_IPOPTS].desc = "check if a specific IP option is set"; sigmatch_table[DETECT_IPOPTS].url = "/rules/header-keywords.html#ipopts"; sigmatch_table[DETECT_IPOPTS].Match = DetectIpOptsMatch; sigmatch_table[DETECT_IPOPTS].Setup = DetectIpOptsSetup; - sigmatch_table[DETECT_IPOPTS].Free = DetectIpOptsFree; + sigmatch_table[DETECT_IPOPTS].Free = DetectIpOptsFree; #ifdef UNITTESTS sigmatch_table[DETECT_IPOPTS].RegisterTests = IpOptsRegisterTests; #endif @@ -73,8 +73,8 @@ void DetectIpOptsRegister (void) */ struct DetectIpOpts_ { - const char *ipopt_name; /**< ip option name */ - uint16_t code; /**< ip option flag value */ + const char *ipopt_name; /**< ip option name */ + uint16_t code; /**< ip option flag value */ } ipopts[] = { { "rr", @@ -165,8 +165,8 @@ const char *IpOptsFlagToString(uint16_t flag) * \retval 0 no match * \retval 1 match */ -static int DetectIpOptsMatch (DetectEngineThreadCtx *det_ctx, Packet *p, - const Signature *s, const SigMatchCtx *ctx) +static int DetectIpOptsMatch( + DetectEngineThreadCtx *det_ctx, Packet *p, const Signature *s, const SigMatchCtx *ctx) { const DetectIpOptsData *de = (const DetectIpOptsData *)ctx; @@ -189,7 +189,7 @@ static int DetectIpOptsMatch (DetectEngineThreadCtx *det_ctx, Packet *p, * \retval de pointer to DetectIpOptsData on success * \retval NULL on failure */ -static DetectIpOptsData *DetectIpOptsParse (const char *rawstr) +static DetectIpOptsData *DetectIpOptsParse(const char *rawstr) { int i; DetectIpOptsData *de = NULL; @@ -202,14 +202,14 @@ static DetectIpOptsData *DetectIpOptsParse (const char *rawstr) goto error; } - for(i = 0; ipopts[i].ipopt_name != NULL; i++) { - if((strcasecmp(ipopts[i].ipopt_name,rawstr)) == 0) { + for (i = 0; ipopts[i].ipopt_name != NULL; i++) { + if ((strcasecmp(ipopts[i].ipopt_name, rawstr)) == 0) { found = 1; break; } } - if(found == 0) + if (found == 0) goto error; de = SCMalloc(sizeof(DetectIpOptsData)); @@ -225,7 +225,8 @@ static DetectIpOptsData *DetectIpOptsParse (const char *rawstr) if (match) { pcre2_match_data_free(match); } - if (de) SCFree(de); + if (de) + SCFree(de); return NULL; } @@ -240,7 +241,7 @@ static DetectIpOptsData *DetectIpOptsParse (const char *rawstr) * \retval 0 on Success * \retval -1 on Failure */ -static int DetectIpOptsSetup (DetectEngineCtx *de_ctx, Signature *s, const char *rawstr) +static int DetectIpOptsSetup(DetectEngineCtx *de_ctx, Signature *s, const char *rawstr) { DetectIpOptsData *de = NULL; @@ -271,7 +272,8 @@ static int DetectIpOptsSetup (DetectEngineCtx *de_ctx, Signature *s, const char void DetectIpOptsFree(DetectEngineCtx *de_ctx, void *de_ptr) { DetectIpOptsData *de = (DetectIpOptsData *)de_ptr; - if(de) SCFree(de); + if (de) + SCFree(de); } /* @@ -282,7 +284,7 @@ void DetectIpOptsFree(DetectEngineCtx *de_ctx, void *de_ptr) /** * \test IpOptsTestParse01 is a test for a valid ipopts value */ -static int IpOptsTestParse01 (void) +static int IpOptsTestParse01(void) { DetectIpOptsData *de = DetectIpOptsParse("lsrr"); @@ -296,7 +298,7 @@ static int IpOptsTestParse01 (void) /** * \test IpOptsTestParse02 is a test for an invalid ipopts value */ -static int IpOptsTestParse02 (void) +static int IpOptsTestParse02(void) { DetectIpOptsData *de = DetectIpOptsParse("invalidopt"); @@ -310,7 +312,7 @@ static int IpOptsTestParse02 (void) /** * \test IpOptsTestParse03 test the match function on a packet that needs to match */ -static int IpOptsTestParse03 (void) +static int IpOptsTestParse03(void) { Packet *p = PacketGetFromAlloc(); FAIL_IF_NULL(p); @@ -344,7 +346,7 @@ static int IpOptsTestParse03 (void) /** * \test IpOptsTestParse04 test the match function on a packet that needs to not match */ -static int IpOptsTestParse04 (void) +static int IpOptsTestParse04(void) { Packet *p = PacketGetFromAlloc(); FAIL_IF_NULL(p); diff --git a/src/detect-ipopts.h b/src/detect-ipopts.h index a4009252d0b5..99757f38c46b 100644 --- a/src/detect-ipopts.h +++ b/src/detect-ipopts.h @@ -24,7 +24,6 @@ #ifndef __DETECT_IPOPTS_H__ #define __DETECT_IPOPTS_H__ - /** * \struct DetectIpOptsData_ * DetectIpOptsData_ is used to store ipopts: input value @@ -43,9 +42,8 @@ typedef struct DetectIpOptsData_ { * Registration function for ipopts: keyword */ -void DetectIpOptsRegister (void); +void DetectIpOptsRegister(void); const char *IpOptsFlagToString(uint16_t flag); #endif /*__DETECT_IPOPTS_H__ */ - diff --git a/src/detect-ipproto.c b/src/detect-ipproto.c index 1f895ce68c2b..620fff40baab 100644 --- a/src/detect-ipproto.c +++ b/src/detect-ipproto.c @@ -47,7 +47,7 @@ /** * \brief Regex for parsing our options */ -#define PARSE_REGEX "^([!<>]?)\\s*([^\\s]+)$" +#define PARSE_REGEX "^([!<>]?)\\s*([^\\s]+)$" static DetectParseRegex parse_regex; @@ -64,7 +64,7 @@ void DetectIPProtoRegister(void) sigmatch_table[DETECT_IPPROTO].url = "/rules/header-keywords.html#ip-proto"; sigmatch_table[DETECT_IPPROTO].Match = NULL; sigmatch_table[DETECT_IPPROTO].Setup = DetectIPProtoSetup; - sigmatch_table[DETECT_IPPROTO].Free = DetectIPProtoFree; + sigmatch_table[DETECT_IPPROTO].Free = DetectIPProtoFree; #ifdef UNITTESTS sigmatch_table[DETECT_IPPROTO].RegisterTests = DetectIPProtoRegisterTests; #endif @@ -129,15 +129,14 @@ static DetectIPProtoData *DetectIPProtoParse(const char *optstr) goto error; } data->proto = proto; - } - else { + } else { if (StringParseUint8(&data->proto, 10, 0, args[1]) <= 0) { SCLogError("Malformed protocol number: %s", str_ptr); goto error; } } - for (i = 0; i < (ret - 1); i++){ + for (i = 0; i < (ret - 1); i++) { if (args[i] != NULL) pcre2_substring_free((PCRE2_UCHAR8 *)args[i]); } @@ -149,7 +148,7 @@ static DetectIPProtoData *DetectIPProtoParse(const char *optstr) if (match) { pcre2_match_data_free(match); } - for (i = 0; i < (ret - 1) && i < 2; i++){ + for (i = 0; i < (ret - 1) && i < 2; i++) { if (args[i] != NULL) pcre2_substring_free((PCRE2_UCHAR8 *)args[i]); } @@ -257,7 +256,7 @@ static int DetectIPProtoSetup(DetectEngineCtx *de_ctx, Signature *s, const char temp_sm = temp_sm->next; } if (temp_sm != NULL) { - DetectIPProtoData *data_temp = (DetectIPProtoData *)temp_sm->ctx; + DetectIPProtoData *data_temp = (DetectIPProtoData *)temp_sm->ctx; if (data_temp->proto <= data->proto) { SCLogError("can't have " "both gt and lt ipprotos, with the lt being " @@ -286,7 +285,7 @@ static int DetectIPProtoSetup(DetectEngineCtx *de_ctx, Signature *s, const char SigMatch *temp_sm = s->init_data->smlists[DETECT_SM_LIST_MATCH]; while (temp_sm != NULL) { if (temp_sm->type == DETECT_IPPROTO && - ((DetectIPProtoData *)temp_sm->ctx)->op == DETECT_IPPROTO_OP_LT) { + ((DetectIPProtoData *)temp_sm->ctx)->op == DETECT_IPPROTO_OP_LT) { break; } temp_sm = temp_sm->next; @@ -332,7 +331,7 @@ static int DetectIPProtoSetup(DetectEngineCtx *de_ctx, Signature *s, const char temp_sm = temp_sm->next; } if (temp_sm != NULL) { - DetectIPProtoData *data_temp = (DetectIPProtoData *)temp_sm->ctx; + DetectIPProtoData *data_temp = (DetectIPProtoData *)temp_sm->ctx; if (data_temp->proto >= data->proto) { SCLogError("can't use a have " "both gt and lt ipprotos, with the lt being " @@ -361,13 +360,13 @@ static int DetectIPProtoSetup(DetectEngineCtx *de_ctx, Signature *s, const char SigMatch *temp_sm = s->init_data->smlists[DETECT_SM_LIST_MATCH]; while (temp_sm != NULL) { if (temp_sm->type == DETECT_IPPROTO && - ((DetectIPProtoData *)temp_sm->ctx)->op == DETECT_IPPROTO_OP_GT) { + ((DetectIPProtoData *)temp_sm->ctx)->op == DETECT_IPPROTO_OP_GT) { break; } temp_sm = temp_sm->next; } if (temp_sm != NULL) { - data_temp = (DetectIPProtoData *)temp_sm->ctx; + data_temp = (DetectIPProtoData *)temp_sm->ctx; if (data_temp->proto >= data->proto) { SCLogError("can't have " "both gt and lt ipprotos, with the lt being " @@ -421,7 +420,7 @@ static int DetectIPProtoSetup(DetectEngineCtx *de_ctx, Signature *s, const char return 0; - error: +error: DetectIPProtoFree(de_ctx, data); return -1; @@ -539,7 +538,7 @@ static int DetectIPProtoTestSetup02(void) result = 1; - end: +end: if (sig != NULL) SigFree(NULL, sig); return result; @@ -576,7 +575,7 @@ static int DetectIPProtoTestSetup03(void) result = 1; - end: +end: SigFree(NULL, sig); return result; } @@ -612,7 +611,7 @@ static int DetectIPProtoTestSetup04(void) result = 1; - end: +end: SigFree(NULL, sig); return result; } @@ -648,7 +647,7 @@ static int DetectIPProtoTestSetup05(void) result = 1; - end: +end: SigFree(NULL, sig); return result; } @@ -675,7 +674,7 @@ static int DetectIPProtoTestSetup06(void) result = 1; - end: +end: SigFree(NULL, sig); return result; } @@ -702,7 +701,7 @@ static int DetectIPProtoTestSetup07(void) result = 1; - end: +end: SigFree(NULL, sig); return result; } @@ -729,7 +728,7 @@ static int DetectIPProtoTestSetup08(void) result = 1; - end: +end: SigFree(NULL, sig); return result; } @@ -756,7 +755,7 @@ static int DetectIPProtoTestSetup09(void) result = 1; - end: +end: SigFree(NULL, sig); return result; } @@ -783,7 +782,7 @@ static int DetectIPProtoTestSetup10(void) result = 1; - end: +end: SigFree(NULL, sig); return result; } @@ -810,7 +809,7 @@ static int DetectIPProtoTestSetup11(void) result = 1; - end: +end: SigFree(NULL, sig); return result; } @@ -837,7 +836,7 @@ static int DetectIPProtoTestSetup12(void) result = 1; - end: +end: SigFree(NULL, sig); return result; } @@ -864,7 +863,7 @@ static int DetectIPProtoTestSetup13(void) result = 1; - end: +end: SigFree(NULL, sig); return result; } @@ -888,7 +887,7 @@ static int DetectIPProtoTestSetup14(void) result = 1; - end: +end: SigFree(NULL, sig); return result; } @@ -925,10 +924,9 @@ static int DetectIPProtoTestSetup15(void) result = 1; - end: +end: SigFree(NULL, sig); return result; - } static int DetectIPProtoTestSetup16(void) @@ -963,10 +961,9 @@ static int DetectIPProtoTestSetup16(void) result = 1; - end: +end: SigFree(NULL, sig); return result; - } static int DetectIPProtoTestSetup17(void) @@ -1001,10 +998,9 @@ static int DetectIPProtoTestSetup17(void) result = 1; - end: +end: SigFree(NULL, sig); return result; - } static int DetectIPProtoTestSetup18(void) @@ -1039,10 +1035,9 @@ static int DetectIPProtoTestSetup18(void) result = 1; - end: +end: SigFree(NULL, sig); return result; - } static int DetectIPProtoTestSetup19(void) @@ -1080,7 +1075,7 @@ static int DetectIPProtoTestSetup19(void) result = 1; - end: +end: SigFree(NULL, sig); return result; } @@ -1117,7 +1112,7 @@ static int DetectIPProtoTestSetup20(void) result = 1; - end: +end: SigFree(NULL, sig); return result; } @@ -1157,7 +1152,7 @@ static int DetectIPProtoTestSetup21(void) result = 1; - end: +end: SigFree(NULL, sig); return result; } @@ -1197,7 +1192,7 @@ static int DetectIPProtoTestSetup22(void) result = 1; - end: +end: SigFree(NULL, sig); return result; } @@ -1234,7 +1229,7 @@ static int DetectIPProtoTestSetup23(void) result = 1; - end: +end: SigFree(NULL, sig); return result; } @@ -1274,7 +1269,7 @@ static int DetectIPProtoTestSetup24(void) result = 1; - end: +end: SigFree(NULL, sig); return result; } @@ -1314,7 +1309,7 @@ static int DetectIPProtoTestSetup33(void) result = 1; - end: +end: SigFree(NULL, sig); return result; } @@ -1355,7 +1350,7 @@ static int DetectIPProtoTestSetup34(void) result = 1; - end: +end: SigFree(NULL, sig); return result; } @@ -1395,7 +1390,7 @@ static int DetectIPProtoTestSetup36(void) result = 1; - end: +end: SigFree(NULL, sig); return result; } @@ -1439,7 +1434,7 @@ static int DetectIPProtoTestSetup43(void) result = 1; - end: +end: SigFree(NULL, sig); return result; } @@ -1479,7 +1474,7 @@ static int DetectIPProtoTestSetup44(void) result = 1; - end: +end: SigFree(NULL, sig); return result; } @@ -1523,7 +1518,7 @@ static int DetectIPProtoTestSetup45(void) result = 1; - end: +end: SigFree(NULL, sig); return result; } @@ -1563,7 +1558,7 @@ static int DetectIPProtoTestSetup56(void) result = 1; - end: +end: SigFree(NULL, sig); return result; } @@ -1600,7 +1595,7 @@ static int DetectIPProtoTestSetup75(void) result = 1; - end: +end: SigFree(NULL, sig); return result; } @@ -1637,7 +1632,7 @@ static int DetectIPProtoTestSetup76(void) result = 1; - end: +end: SigFree(NULL, sig); return result; } @@ -1674,7 +1669,7 @@ static int DetectIPProtoTestSetup129(void) result = 1; - end: +end: SigFree(NULL, sig); return result; } @@ -1711,7 +1706,7 @@ static int DetectIPProtoTestSetup130(void) result = 1; - end: +end: SigFree(NULL, sig); return result; } @@ -1748,7 +1743,7 @@ static int DetectIPProtoTestSetup131(void) result = 1; - end: +end: SigFree(NULL, sig); return result; } @@ -1785,7 +1780,7 @@ static int DetectIPProtoTestSetup132(void) result = 1; - end: +end: SigFree(NULL, sig); return result; } @@ -1855,7 +1850,7 @@ static int DetectIPProtoTestSetup145(void) result = 1; - end: +end: SigFree(NULL, sig); return result; } @@ -1863,10 +1858,9 @@ static int DetectIPProtoTestSetup145(void) static int DetectIPProtoTestSig1(void) { int result = 0; - uint8_t *buf = (uint8_t *) - "GET /one/ HTTP/1.1\r\n" - "Host: one.example.org\r\n" - "\r\n"; + uint8_t *buf = (uint8_t *)"GET /one/ HTTP/1.1\r\n" + "Host: one.example.org\r\n" + "\r\n"; uint16_t buflen = strlen((char *)buf); Packet *p = UTHBuildPacket((uint8_t *)buf, buflen, IPPROTO_TCP); if (p == NULL) @@ -1874,18 +1868,18 @@ static int DetectIPProtoTestSig1(void) const char *sigs[4]; sigs[0] = "alert ip any any -> any any " - "(msg:\"Not tcp\"; ip_proto:!tcp; content:\"GET \"; sid:1;)"; + "(msg:\"Not tcp\"; ip_proto:!tcp; content:\"GET \"; sid:1;)"; sigs[1] = "alert ip any any -> any any " - "(msg:\"Less than 7\"; content:\"GET \"; ip_proto:<7; sid:2;)"; + "(msg:\"Less than 7\"; content:\"GET \"; ip_proto:<7; sid:2;)"; sigs[2] = "alert ip any any -> any any " - "(msg:\"Greater than 5\"; content:\"GET \"; ip_proto:>5; sid:3;)"; + "(msg:\"Greater than 5\"; content:\"GET \"; ip_proto:>5; sid:3;)"; sigs[3] = "alert ip any any -> any any " - "(msg:\"Equals tcp\"; content:\"GET \"; ip_proto:tcp; sid:4;)"; + "(msg:\"Equals tcp\"; content:\"GET \"; ip_proto:tcp; sid:4;)"; /* sids to match */ - uint32_t sid[4] = {1, 2, 3, 4}; + uint32_t sid[4] = { 1, 2, 3, 4 }; /* expected matches for each sid within this packet we are testing */ - uint32_t results[4] = {0, 1, 1, 1}; + uint32_t results[4] = { 0, 1, 1, 1 }; /* remember that UTHGenericTest expect the first parameter * as an array of packet pointers. And also a bidimensional array of results @@ -1941,9 +1935,8 @@ static int DetectIPProtoTestSig2(void) de_ctx->mpm_matcher = mpm_default_matcher; de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx, - "alert ip any any -> any any (msg:\"Check ipproto usage\"; " - "ip_proto:!103; sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert ip any any -> any any (msg:\"Check ipproto usage\"; " + "ip_proto:!103; sid:1;)"); if (de_ctx->sig_list == NULL) { result = 0; goto end; @@ -2028,9 +2021,8 @@ static int DetectIPProtoTestSig3(void) de_ctx->mpm_matcher = mpm_default_matcher; de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx, - "alert ip any any -> any any (msg:\"Check ipproto usage\"; " - "ip_proto:103; sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert ip any any -> any any (msg:\"Check ipproto usage\"; " + "ip_proto:103; sid:1;)"); if (de_ctx->sig_list == NULL) { result = 0; goto end; diff --git a/src/detect-ipproto.h b/src/detect-ipproto.h index eeac35a5c14b..d2c1de1f406e 100644 --- a/src/detect-ipproto.h +++ b/src/detect-ipproto.h @@ -25,15 +25,15 @@ #define __DETECT_IPPROTO_H__ /** IPProto Operators */ -#define DETECT_IPPROTO_OP_EQ '=' /**< "equals" operator (default) */ -#define DETECT_IPPROTO_OP_NOT '!' /**< "not" operator */ -#define DETECT_IPPROTO_OP_LT '<' /**< "less than" operator */ -#define DETECT_IPPROTO_OP_GT '>' /**< "greater than" operator */ +#define DETECT_IPPROTO_OP_EQ '=' /**< "equals" operator (default) */ +#define DETECT_IPPROTO_OP_NOT '!' /**< "not" operator */ +#define DETECT_IPPROTO_OP_LT '<' /**< "less than" operator */ +#define DETECT_IPPROTO_OP_GT '>' /**< "greater than" operator */ /** ip_proto data */ typedef struct DetectIPProtoData_ { - uint8_t op; /**< Operator used to compare */ - uint8_t proto; /**< Protocol used to compare */ + uint8_t op; /**< Operator used to compare */ + uint8_t proto; /**< Protocol used to compare */ } DetectIPProtoData; /* prototypes */ @@ -41,8 +41,7 @@ typedef struct DetectIPProtoData_ { /** * \brief Registration function for ip_proto keyword. */ -void DetectIPProtoRegister (void); +void DetectIPProtoRegister(void); void DetectIPProtoRemoveAllSMs(DetectEngineCtx *, Signature *); #endif /* __DETECT_IPPROTO_H__ */ - diff --git a/src/detect-iprep.c b/src/detect-iprep.c index 068619405bce..8fef15bac0f9 100644 --- a/src/detect-iprep.c +++ b/src/detect-iprep.c @@ -52,22 +52,22 @@ #include "reputation.h" #include "host.h" -static int DetectIPRepMatch (DetectEngineThreadCtx *, Packet *, - const Signature *, const SigMatchCtx *); -static int DetectIPRepSetup (DetectEngineCtx *, Signature *, const char *); -void DetectIPRepFree (DetectEngineCtx *, void *); +static int DetectIPRepMatch( + DetectEngineThreadCtx *, Packet *, const Signature *, const SigMatchCtx *); +static int DetectIPRepSetup(DetectEngineCtx *, Signature *, const char *); +void DetectIPRepFree(DetectEngineCtx *, void *); #ifdef UNITTESTS static void IPRepRegisterTests(void); #endif -void DetectIPRepRegister (void) +void DetectIPRepRegister(void) { sigmatch_table[DETECT_IPREP].name = "iprep"; sigmatch_table[DETECT_IPREP].desc = "match on the IP reputation information for a host"; sigmatch_table[DETECT_IPREP].url = "/rules/ip-reputation-rules.html#iprep"; sigmatch_table[DETECT_IPREP].Match = DetectIPRepMatch; sigmatch_table[DETECT_IPREP].Setup = DetectIPRepSetup; - sigmatch_table[DETECT_IPREP].Free = DetectIPRepFree; + sigmatch_table[DETECT_IPREP].Free = DetectIPRepFree; #ifdef UNITTESTS sigmatch_table[DETECT_IPREP].RegisterTests = IPRepRegisterTests; #endif @@ -144,8 +144,8 @@ static uint8_t GetHostRepDst(Packet *p, uint8_t cat, uint32_t version) * 1: match * -1: error */ -static int DetectIPRepMatch (DetectEngineThreadCtx *det_ctx, Packet *p, - const Signature *s, const SigMatchCtx *ctx) +static int DetectIPRepMatch( + DetectEngineThreadCtx *det_ctx, Packet *p, const Signature *s, const SigMatchCtx *ctx) { const DetectIPRepData *rd = (const DetectIPRepData *)ctx; if (rd == NULL) @@ -155,7 +155,7 @@ static int DetectIPRepMatch (DetectEngineThreadCtx *det_ctx, Packet *p, uint8_t val = 0; SCLogDebug("rd->cmd %u", rd->cmd); - switch(rd->cmd) { + switch (rd->cmd) { case IPRepCmdAny: val = GetHostRepSrc(p, rd->cat, version); if (val == 0) @@ -211,7 +211,7 @@ static int DetectIPRepMatch (DetectEngineThreadCtx *det_ctx, Packet *p, return 0; } -int DetectIPRepSetup (DetectEngineCtx *de_ctx, Signature *s, const char *rawstr) +int DetectIPRepSetup(DetectEngineCtx *de_ctx, Signature *s, const char *rawstr) { DetectIPRepData *cd = rs_detect_iprep_parse(rawstr); @@ -238,7 +238,7 @@ int DetectIPRepSetup (DetectEngineCtx *de_ctx, Signature *s, const char *rawstr) return -1; } -void DetectIPRepFree (DetectEngineCtx *de_ctx, void *ptr) +void DetectIPRepFree(DetectEngineCtx *de_ctx, void *ptr) { DetectIPRepData *fd = (DetectIPRepData *)ptr; @@ -267,9 +267,8 @@ static FILE *DetectIPRepGenerateCategoriesDummy(void) static FILE *DetectIPRepGenerateCategoriesDummy2(void) { FILE *fd = NULL; - const char *buffer = - "1,BadHosts,Know bad hosts\n" - "2,GoodHosts,Know good hosts\n"; + const char *buffer = "1,BadHosts,Know bad hosts\n" + "2,GoodHosts,Know good hosts\n"; fd = SCFmemopen((void *)buffer, strlen(buffer), "r"); if (fd == NULL) @@ -293,9 +292,8 @@ static FILE *DetectIPRepGenerateNetworksDummy(void) static FILE *DetectIPRepGenerateNetworksDummy2(void) { FILE *fd = NULL; - const char *buffer = - "0.0.0.0/0,1,10\n" - "192.168.0.0/16,2,127"; + const char *buffer = "0.0.0.0/0,1,10\n" + "192.168.0.0/16,2,127"; fd = SCFmemopen((void *)buffer, strlen(buffer), "r"); if (fd == NULL) diff --git a/src/detect-iprep.h b/src/detect-iprep.h index 07cd5c7f606f..2fe3d47a37d3 100644 --- a/src/detect-iprep.h +++ b/src/detect-iprep.h @@ -25,6 +25,6 @@ #define __DETECT_IPREP_H__ /* prototypes */ -void DetectIPRepRegister (void); +void DetectIPRepRegister(void); #endif /* __DETECT_IPREP_H__ */ diff --git a/src/detect-ipv4hdr.c b/src/detect-ipv4hdr.c index 76334410e33f..50acd08e6624 100644 --- a/src/detect-ipv4hdr.c +++ b/src/detect-ipv4hdr.c @@ -34,9 +34,9 @@ #include "detect-ipv4hdr.h" /* prototypes */ -static int DetectIpv4hdrSetup (DetectEngineCtx *, Signature *, const char *); +static int DetectIpv4hdrSetup(DetectEngineCtx *, Signature *, const char *); #ifdef UNITTESTS -void DetectIpv4hdrRegisterTests (void); +void DetectIpv4hdrRegisterTests(void); #endif static int g_ipv4hdr_buffer_id = 0; @@ -65,8 +65,7 @@ void DetectIpv4hdrRegister(void) DetectPktMpmRegister("ipv4.hdr", 2, PrefilterGenericMpmPktRegister, GetData); - DetectPktInspectEngineRegister("ipv4.hdr", GetData, - DetectEngineInspectPktBufferGeneric); + DetectPktInspectEngineRegister("ipv4.hdr", GetData, DetectEngineInspectPktBufferGeneric); return; } @@ -81,7 +80,7 @@ void DetectIpv4hdrRegister(void) * \retval 0 on Success * \retval -1 on Failure */ -static int DetectIpv4hdrSetup (DetectEngineCtx *de_ctx, Signature *s, const char *_unused) +static int DetectIpv4hdrSetup(DetectEngineCtx *de_ctx, Signature *s, const char *_unused) { s->proto.flags |= DETECT_PROTO_IPV4; // TODO @@ -106,10 +105,8 @@ static InspectionBuffer *GetData(DetectEngineThreadCtx *det_ctx, } uint32_t hlen = IPV4_GET_HLEN(p); if (((uint8_t *)p->ip4h + (ptrdiff_t)hlen) > - ((uint8_t *)GET_PKT_DATA(p) + (ptrdiff_t)GET_PKT_LEN(p))) - { - SCLogDebug("data out of range: %p > %p", - ((uint8_t *)p->ip4h + (ptrdiff_t)hlen), + ((uint8_t *)GET_PKT_DATA(p) + (ptrdiff_t)GET_PKT_LEN(p))) { + SCLogDebug("data out of range: %p > %p", ((uint8_t *)p->ip4h + (ptrdiff_t)hlen), ((uint8_t *)GET_PKT_DATA(p) + (ptrdiff_t)GET_PKT_LEN(p))); return NULL; } diff --git a/src/detect-ipv4hdr.h b/src/detect-ipv4hdr.h index aa30c45a3277..bd9279896527 100644 --- a/src/detect-ipv4hdr.h +++ b/src/detect-ipv4hdr.h @@ -26,4 +26,4 @@ void DetectIpv4hdrRegister(void); -#endif /* _DETECT_IPV4HDR_H */ +#endif /* _DETECT_IPV4HDR_H */ diff --git a/src/detect-ipv6hdr.c b/src/detect-ipv6hdr.c index eacff043a9f1..b1f60b5ac764 100644 --- a/src/detect-ipv6hdr.c +++ b/src/detect-ipv6hdr.c @@ -34,9 +34,9 @@ #include "detect-ipv6hdr.h" /* prototypes */ -static int DetectIpv6hdrSetup (DetectEngineCtx *, Signature *, const char *); +static int DetectIpv6hdrSetup(DetectEngineCtx *, Signature *, const char *); #ifdef UNITTESTS -void DetectIpv6hdrRegisterTests (void); +void DetectIpv6hdrRegisterTests(void); #endif static int g_ipv6hdr_buffer_id = 0; @@ -65,8 +65,7 @@ void DetectIpv6hdrRegister(void) DetectPktMpmRegister("ipv6.hdr", 2, PrefilterGenericMpmPktRegister, GetData); - DetectPktInspectEngineRegister("ipv6.hdr", GetData, - DetectEngineInspectPktBufferGeneric); + DetectPktInspectEngineRegister("ipv6.hdr", GetData, DetectEngineInspectPktBufferGeneric); return; } @@ -81,7 +80,7 @@ void DetectIpv6hdrRegister(void) * \retval 0 on Success * \retval -1 on Failure */ -static int DetectIpv6hdrSetup (DetectEngineCtx *de_ctx, Signature *s, const char *_unused) +static int DetectIpv6hdrSetup(DetectEngineCtx *de_ctx, Signature *s, const char *_unused) { s->proto.flags |= DETECT_PROTO_IPV6; // TODO @@ -106,8 +105,7 @@ static InspectionBuffer *GetData(DetectEngineThreadCtx *det_ctx, } uint32_t hlen = IPV6_HEADER_LEN + IPV6_GET_EXTHDRS_LEN(p); if (((uint8_t *)p->ip6h + (ptrdiff_t)hlen) > - ((uint8_t *)GET_PKT_DATA(p) + (ptrdiff_t)GET_PKT_LEN(p))) - { + ((uint8_t *)GET_PKT_DATA(p) + (ptrdiff_t)GET_PKT_LEN(p))) { SCLogDebug("data out of range: %p > %p (exthdrs_len %u)", ((uint8_t *)p->ip6h + (ptrdiff_t)hlen), ((uint8_t *)GET_PKT_DATA(p) + (ptrdiff_t)GET_PKT_LEN(p)), diff --git a/src/detect-ipv6hdr.h b/src/detect-ipv6hdr.h index 0ff454d6bc3b..6b0c9d61acb8 100644 --- a/src/detect-ipv6hdr.h +++ b/src/detect-ipv6hdr.h @@ -26,4 +26,4 @@ void DetectIpv6hdrRegister(void); -#endif /* _DETECT_IPV6HDR_H */ +#endif /* _DETECT_IPV6HDR_H */ diff --git a/src/detect-isdataat.c b/src/detect-isdataat.c index 7b4d629ad3a1..44487e6ee4fd 100644 --- a/src/detect-isdataat.c +++ b/src/detect-isdataat.c @@ -49,17 +49,17 @@ /** * \brief Regex for parsing our isdataat options */ -#define PARSE_REGEX "^\\s*!?([^\\s,]+)\\s*(,\\s*relative)?\\s*(,\\s*rawbytes\\s*)?\\s*$" +#define PARSE_REGEX "^\\s*!?([^\\s,]+)\\s*(,\\s*relative)?\\s*(,\\s*rawbytes\\s*)?\\s*$" static DetectParseRegex parse_regex; -int DetectIsdataatSetup (DetectEngineCtx *, Signature *, const char *); +int DetectIsdataatSetup(DetectEngineCtx *, Signature *, const char *); #ifdef UNITTESTS static void DetectIsdataatRegisterTests(void); #endif void DetectIsdataatFree(DetectEngineCtx *, void *); -static int DetectEndsWithSetup (DetectEngineCtx *de_ctx, Signature *s, const char *nullstr); +static int DetectEndsWithSetup(DetectEngineCtx *de_ctx, Signature *s, const char *nullstr); /** * \brief Registration function for isdataat: keyword @@ -67,17 +67,19 @@ static int DetectEndsWithSetup (DetectEngineCtx *de_ctx, Signature *s, const cha void DetectIsdataatRegister(void) { sigmatch_table[DETECT_ISDATAAT].name = "isdataat"; - sigmatch_table[DETECT_ISDATAAT].desc = "check if there is still data at a specific part of the payload"; + sigmatch_table[DETECT_ISDATAAT].desc = + "check if there is still data at a specific part of the payload"; sigmatch_table[DETECT_ISDATAAT].url = "/rules/payload-keywords.html#isdataat"; /* match is handled in DetectEngineContentInspection() */ sigmatch_table[DETECT_ISDATAAT].Match = NULL; sigmatch_table[DETECT_ISDATAAT].Setup = DetectIsdataatSetup; - sigmatch_table[DETECT_ISDATAAT].Free = DetectIsdataatFree; + sigmatch_table[DETECT_ISDATAAT].Free = DetectIsdataatFree; #ifdef UNITTESTS sigmatch_table[DETECT_ISDATAAT].RegisterTests = DetectIsdataatRegisterTests; #endif sigmatch_table[DETECT_ENDS_WITH].name = "endswith"; - sigmatch_table[DETECT_ENDS_WITH].desc = "make sure the previous content matches exactly at the end of the buffer"; + sigmatch_table[DETECT_ENDS_WITH].desc = + "make sure the previous content matches exactly at the end of the buffer"; sigmatch_table[DETECT_ENDS_WITH].url = "/rules/payload-keywords.html#endswith"; sigmatch_table[DETECT_ENDS_WITH].Setup = DetectEndsWithSetup; sigmatch_table[DETECT_ENDS_WITH].flags = SIGMATCH_NOOPT; @@ -94,13 +96,14 @@ void DetectIsdataatRegister(void) * \retval idad pointer to DetectIsdataatData on success * \retval NULL on failure */ -static DetectIsdataatData *DetectIsdataatParse (DetectEngineCtx *de_ctx, const char *isdataatstr, char **offset) +static DetectIsdataatData *DetectIsdataatParse( + DetectEngineCtx *de_ctx, const char *isdataatstr, char **offset) { DetectIsdataatData *idad = NULL; - char *args[3] = {NULL,NULL,NULL}; + char *args[3] = { NULL, NULL, NULL }; int res = 0; size_t pcre2_len; - int i=0; + int i = 0; pcre2_match_data *match = NULL; int ret = DetectParsePcreExec(&parse_regex, &match, isdataatstr, 0, 0); @@ -118,7 +121,6 @@ static DetectIsdataatData *DetectIsdataatParse (DetectEngineCtx *de_ctx, const c } args[0] = (char *)str_ptr; - if (ret > 2) { res = pcre2_substring_get_bynumber(match, 2, (PCRE2_UCHAR8 **)&str_ptr, &pcre2_len); if (res < 0) { @@ -154,8 +156,7 @@ static DetectIsdataatData *DetectIsdataatParse (DetectEngineCtx *de_ctx, const c if (*offset == NULL) goto error; } else { - if (StringParseUint16(&idad->dataat, 10, - strlen(args[0]), args[0]) < 0 ) { + if (StringParseUint16(&idad->dataat, 10, strlen(args[0]), args[0]) < 0) { SCLogError("isdataat out of range"); SCFree(idad); idad = NULL; @@ -163,10 +164,10 @@ static DetectIsdataatData *DetectIsdataatParse (DetectEngineCtx *de_ctx, const c } } - if (args[1] !=NULL) { + if (args[1] != NULL) { idad->flags |= ISDATAAT_RELATIVE; - if(args[2] !=NULL) + if (args[2] != NULL) idad->flags |= ISDATAAT_RAWBYTES; } @@ -174,21 +175,20 @@ static DetectIsdataatData *DetectIsdataatParse (DetectEngineCtx *de_ctx, const c idad->flags |= ISDATAAT_NEGATED; } - for (i = 0; i < (ret -1); i++) { + for (i = 0; i < (ret - 1); i++) { if (args[i] != NULL) pcre2_substring_free((PCRE2_UCHAR8 *)args[i]); } pcre2_match_data_free(match); return idad; - } error: if (match) { pcre2_match_data_free(match); } - for (i = 0; i < (ret -1) && i < 3; i++){ + for (i = 0; i < (ret - 1) && i < 3; i++) { if (args[i] != NULL) pcre2_substring_free((PCRE2_UCHAR8 *)args[i]); } @@ -196,7 +196,6 @@ static DetectIsdataatData *DetectIsdataatParse (DetectEngineCtx *de_ctx, const c if (idad != NULL) DetectIsdataatFree(de_ctx, idad); return NULL; - } /** @@ -209,7 +208,7 @@ static DetectIsdataatData *DetectIsdataatParse (DetectEngineCtx *de_ctx, const c * \retval 0 on Success * \retval -1 on Failure */ -int DetectIsdataatSetup (DetectEngineCtx *de_ctx, Signature *s, const char *isdataatstr) +int DetectIsdataatSetup(DetectEngineCtx *de_ctx, Signature *s, const char *isdataatstr) { SigMatch *prev_pm = NULL; DetectIsdataatData *idad = NULL; @@ -230,10 +229,8 @@ int DetectIsdataatSetup (DetectEngineCtx *de_ctx, Signature *s, const char *isda prev_pm = DetectGetLastSMFromLists(s, DETECT_CONTENT, DETECT_PCRE, -1); } } else if (idad->flags & ISDATAAT_RELATIVE) { - prev_pm = DetectGetLastSMFromLists(s, - DETECT_CONTENT, DETECT_PCRE, - DETECT_BYTETEST, DETECT_BYTEJUMP, DETECT_BYTE_EXTRACT, - DETECT_ISDATAAT, DETECT_BYTEMATH, -1); + prev_pm = DetectGetLastSMFromLists(s, DETECT_CONTENT, DETECT_PCRE, DETECT_BYTETEST, + DETECT_BYTEJUMP, DETECT_BYTE_EXTRACT, DETECT_ISDATAAT, DETECT_BYTEMATH, -1); if (prev_pm == NULL) sm_list = DETECT_SM_LIST_PMATCH; else { @@ -261,10 +258,9 @@ int DetectIsdataatSetup (DetectEngineCtx *de_ctx, Signature *s, const char *isda } /* 'ends with' scenario */ - if (prev_pm != NULL && prev_pm->type == DETECT_CONTENT && - idad->dataat == 1 && - (idad->flags & (ISDATAAT_RELATIVE|ISDATAAT_NEGATED)) == (ISDATAAT_RELATIVE|ISDATAAT_NEGATED)) - { + if (prev_pm != NULL && prev_pm->type == DETECT_CONTENT && idad->dataat == 1 && + (idad->flags & (ISDATAAT_RELATIVE | ISDATAAT_NEGATED)) == + (ISDATAAT_RELATIVE | ISDATAAT_NEGATED)) { DetectIsdataatFree(de_ctx, idad); DetectContentData *cd = (DetectContentData *)prev_pm->ctx; cd->flags |= DETECT_CONTENT_ENDS_WITH; @@ -315,7 +311,7 @@ void DetectIsdataatFree(DetectEngineCtx *de_ctx, void *ptr) SCFree(idad); } -static int DetectEndsWithSetup (DetectEngineCtx *de_ctx, Signature *s, const char *nullstr) +static int DetectEndsWithSetup(DetectEngineCtx *de_ctx, Signature *s, const char *nullstr) { SigMatch *pm = NULL; int ret = -1; @@ -334,7 +330,7 @@ static int DetectEndsWithSetup (DetectEngineCtx *de_ctx, Signature *s, const cha cd->flags |= DETECT_CONTENT_ENDS_WITH; ret = 0; - end: +end: return ret; } @@ -342,10 +338,10 @@ static int DetectEndsWithSetup (DetectEngineCtx *de_ctx, Signature *s, const cha static int g_dce_stub_data_buffer_id = 0; /** - * \test DetectIsdataatTestParse01 is a test to make sure that we return a correct IsdataatData structure - * when given valid isdataat opt + * \test DetectIsdataatTestParse01 is a test to make sure that we return a correct IsdataatData + * structure when given valid isdataat opt */ -static int DetectIsdataatTestParse01 (void) +static int DetectIsdataatTestParse01(void) { int result = 0; DetectIsdataatData *idad = NULL; @@ -359,10 +355,10 @@ static int DetectIsdataatTestParse01 (void) } /** - * \test DetectIsdataatTestParse02 is a test to make sure that we return a correct IsdataatData structure - * when given valid isdataat opt + * \test DetectIsdataatTestParse02 is a test to make sure that we return a correct IsdataatData + * structure when given valid isdataat opt */ -static int DetectIsdataatTestParse02 (void) +static int DetectIsdataatTestParse02(void) { int result = 0; DetectIsdataatData *idad = NULL; @@ -376,10 +372,10 @@ static int DetectIsdataatTestParse02 (void) } /** - * \test DetectIsdataatTestParse03 is a test to make sure that we return a correct IsdataatData structure - * when given valid isdataat opt + * \test DetectIsdataatTestParse03 is a test to make sure that we return a correct IsdataatData + * structure when given valid isdataat opt */ -static int DetectIsdataatTestParse03 (void) +static int DetectIsdataatTestParse03(void) { int result = 0; DetectIsdataatData *idad = NULL; @@ -428,9 +424,9 @@ static int DetectIsdataatTestParse06(void) de_ctx->flags |= DE_QUIET; Signature *s = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any " - "(msg:\"Testing bytejump_body\"; " - "content:\"one\"; " - "isdataat:!4,relative; sid:1;)"); + "(msg:\"Testing bytejump_body\"; " + "content:\"one\"; " + "isdataat:!4,relative; sid:1;)"); FAIL_IF(s == NULL); FAIL_IF(s->init_data->smlists_tail[DETECT_SM_LIST_PMATCH] == NULL); @@ -444,9 +440,9 @@ static int DetectIsdataatTestParse06(void) FAIL_IF_NOT(data->flags & ISDATAAT_NEGATED); s = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any " - "(msg:\"Testing bytejump_body\"; " - "content:\"one\"; " - "isdataat: !4,relative; sid:2;)"); + "(msg:\"Testing bytejump_body\"; " + "content:\"one\"; " + "isdataat: !4,relative; sid:2;)"); FAIL_IF(s == NULL); FAIL_IF(s->init_data->smlists_tail[DETECT_SM_LIST_PMATCH] == NULL); @@ -466,7 +462,7 @@ static int DetectIsdataatTestParse06(void) * \test DetectIsdataatTestPacket01 is a test to check matches of * isdataat, and isdataat relative */ -static int DetectIsdataatTestPacket01 (void) +static int DetectIsdataatTestPacket01(void) { int result = 0; uint8_t *buf = (uint8_t *)"Hi all!"; @@ -476,27 +472,30 @@ static int DetectIsdataatTestPacket01 (void) p[1] = UTHBuildPacket((uint8_t *)buf, buflen, IPPROTO_UDP); p[2] = UTHBuildPacket((uint8_t *)buf, buflen, IPPROTO_ICMP); - if (p[0] == NULL || p[1] == NULL ||p[2] == NULL) + if (p[0] == NULL || p[1] == NULL || p[2] == NULL) goto end; const char *sigs[5]; - sigs[0]= "alert ip any any -> any any (msg:\"Testing window 1\"; isdataat:6; sid:1;)"; - sigs[1]= "alert ip any any -> any any (msg:\"Testing window 2\"; content:\"all\"; isdataat:1, relative; isdataat:6; sid:2;)"; - sigs[2]= "alert ip any any -> any any (msg:\"Testing window 3\"; isdataat:8; sid:3;)"; - sigs[3]= "alert ip any any -> any any (msg:\"Testing window 4\"; content:\"Hi\"; isdataat:5, relative; sid:4;)"; - sigs[4]= "alert ip any any -> any any (msg:\"Testing window 4\"; content:\"Hi\"; isdataat:6, relative; sid:5;)"; - - uint32_t sid[5] = {1, 2, 3, 4, 5}; - - uint32_t results[3][5] = { - /* packet 0 match sid 1 but should not match sid 2 */ - {1, 1, 0, 1, 0}, - /* packet 1 should not match */ - {1, 1, 0, 1, 0}, - /* packet 2 should not match */ - {1, 1, 0, 1, 0} }; - - result = UTHGenericTest(p, 3, sigs, sid, (uint32_t *) results, 5); + sigs[0] = "alert ip any any -> any any (msg:\"Testing window 1\"; isdataat:6; sid:1;)"; + sigs[1] = "alert ip any any -> any any (msg:\"Testing window 2\"; content:\"all\"; isdataat:1, " + "relative; isdataat:6; sid:2;)"; + sigs[2] = "alert ip any any -> any any (msg:\"Testing window 3\"; isdataat:8; sid:3;)"; + sigs[3] = "alert ip any any -> any any (msg:\"Testing window 4\"; content:\"Hi\"; isdataat:5, " + "relative; sid:4;)"; + sigs[4] = "alert ip any any -> any any (msg:\"Testing window 4\"; content:\"Hi\"; isdataat:6, " + "relative; sid:5;)"; + + uint32_t sid[5] = { 1, 2, 3, 4, 5 }; + + uint32_t results[3][5] = { /* packet 0 match sid 1 but should not match sid 2 */ + { 1, 1, 0, 1, 0 }, + /* packet 1 should not match */ + { 1, 1, 0, 1, 0 }, + /* packet 2 should not match */ + { 1, 1, 0, 1, 0 } + }; + + result = UTHGenericTest(p, 3, sigs, sid, (uint32_t *)results, 5); UTHFreePackets(p, 3); end: @@ -508,15 +507,15 @@ static int DetectIsdataatTestPacket01 (void) * isdataat, and isdataat relative works if the previous keyword is pcre * (bug 144) */ -static int DetectIsdataatTestPacket02 (void) +static int DetectIsdataatTestPacket02(void) { int result = 0; uint8_t *buf = (uint8_t *)"GET /AllWorkAndNoPlayMakesWillADullBoy HTTP/1.0" - "User-Agent: Wget/1.11.4" - "Accept: */*" - "Host: www.google.com" - "Connection: Keep-Alive" - "Date: Mon, 04 Jan 2010 17:29:39 GMT"; + "User-Agent: Wget/1.11.4" + "Accept: */*" + "Host: www.google.com" + "Connection: Keep-Alive" + "Date: Mon, 04 Jan 2010 17:29:39 GMT"; uint16_t buflen = strlen((char *)buf); Packet *p; p = UTHBuildPacket((uint8_t *)buf, buflen, IPPROTO_TCP); @@ -525,8 +524,8 @@ static int DetectIsdataatTestPacket02 (void) goto end; char sig[] = "alert tcp any any -> any any (msg:\"pcre with" - " isdataat + relative\"; pcre:\"/A(ll|pp)WorkAndNoPlayMakesWillA" - "DullBoy/\"; isdataat:96,relative; sid:1;)"; + " isdataat + relative\"; pcre:\"/A(ll|pp)WorkAndNoPlayMakesWillA" + "DullBoy/\"; isdataat:96,relative; sid:1;)"; result = UTHPacketMatchSig(p, sig); @@ -540,15 +539,15 @@ static int DetectIsdataatTestPacket02 (void) * isdataat, and isdataat relative works if the previous keyword is byte_jump * (bug 146) */ -static int DetectIsdataatTestPacket03 (void) +static int DetectIsdataatTestPacket03(void) { int result = 0; uint8_t *buf = (uint8_t *)"GET /AllWorkAndNoPlayMakesWillADullBoy HTTP/1.0" - "User-Agent: Wget/1.11.4" - "Accept: */*" - "Host: www.google.com" - "Connection: Keep-Alive" - "Date: Mon, 04 Jan 2010 17:29:39 GMT"; + "User-Agent: Wget/1.11.4" + "Accept: */*" + "Host: www.google.com" + "Connection: Keep-Alive" + "Date: Mon, 04 Jan 2010 17:29:39 GMT"; uint16_t buflen = strlen((char *)buf); Packet *p; p = UTHBuildPacket((uint8_t *)buf, buflen, IPPROTO_TCP); @@ -557,8 +556,8 @@ static int DetectIsdataatTestPacket03 (void) goto end; char sig[] = "alert tcp any any -> any any (msg:\"byte_jump match = 0 " - "with distance content HTTP/1. relative against HTTP/1.0\"; byte_jump:1," - "46,string,dec; isdataat:87,relative; sid:109; rev:1;)"; + "with distance content HTTP/1. relative against HTTP/1.0\"; byte_jump:1," + "46,string,dec; isdataat:87,relative; sid:109; rev:1;)"; result = UTHPacketMatchSig(p, sig); diff --git a/src/detect-isdataat.h b/src/detect-isdataat.h index 60b138822921..b4493fdfa6a3 100644 --- a/src/detect-isdataat.h +++ b/src/detect-isdataat.h @@ -30,12 +30,11 @@ #define ISDATAAT_OFFSET_VAR 0x08 typedef struct DetectIsdataatData_ { - uint16_t dataat; /* data offset to match */ - uint8_t flags; /* isdataat options*/ + uint16_t dataat; /* data offset to match */ + uint8_t flags; /* isdataat options*/ } DetectIsdataatData; /* prototypes */ -void DetectIsdataatRegister (void); +void DetectIsdataatRegister(void); #endif /* __DETECT_ISDATAAT_H__ */ - diff --git a/src/detect-itype.c b/src/detect-itype.c index 3f8da9568aec..67f858655101 100644 --- a/src/detect-itype.c +++ b/src/detect-itype.c @@ -39,9 +39,8 @@ #include "util-unittest-helper.h" #include "util-debug.h" - -static int DetectITypeMatch(DetectEngineThreadCtx *, Packet *, - const Signature *, const SigMatchCtx *); +static int DetectITypeMatch( + DetectEngineThreadCtx *, Packet *, const Signature *, const SigMatchCtx *); static int DetectITypeSetup(DetectEngineCtx *, Signature *, const char *); #ifdef UNITTESTS static void DetectITypeRegisterTests(void); @@ -54,7 +53,7 @@ static bool PrefilterITypeIsPrefilterable(const Signature *s); /** * \brief Registration function for itype: keyword */ -void DetectITypeRegister (void) +void DetectITypeRegister(void) { sigmatch_table[DETECT_ITYPE].name = "itype"; sigmatch_table[DETECT_ITYPE].desc = "match on a specific ICMP type"; @@ -81,8 +80,8 @@ void DetectITypeRegister (void) * \retval 0 no match * \retval 1 match */ -static int DetectITypeMatch (DetectEngineThreadCtx *det_ctx, Packet *p, - const Signature *s, const SigMatchCtx *ctx) +static int DetectITypeMatch( + DetectEngineThreadCtx *det_ctx, Packet *p, const Signature *s, const SigMatchCtx *ctx) { if (PKT_IS_PSEUDOPKT(p)) return 0; @@ -131,7 +130,8 @@ static int DetectITypeSetup(DetectEngineCtx *de_ctx, Signature *s, const char *i DetectU8Data *itd = NULL; itd = DetectITypeParse(de_ctx, itypestr); - if (itd == NULL) goto error; + if (itd == NULL) + goto error; if (SigMatchAppendSMToList(de_ctx, s, DETECT_ITYPE, (SigMatchCtx *)itd, DETECT_SM_LIST_MATCH) == NULL) { @@ -164,8 +164,7 @@ void DetectITypeFree(DetectEngineCtx *de_ctx, void *ptr) * for each ICMP type. Each array element has the list of signatures * that need to be inspected. */ -static void PrefilterPacketITypeMatch(DetectEngineThreadCtx *det_ctx, - Packet *p, const void *pectx) +static void PrefilterPacketITypeMatch(DetectEngineThreadCtx *det_ctx, Packet *p, const void *pectx) { if (PKT_IS_PSEUDOPKT(p)) { SCReturn; @@ -197,7 +196,7 @@ static int PrefilterSetupIType(DetectEngineCtx *de_ctx, SigGroupHead *sgh) static bool PrefilterITypeIsPrefilterable(const Signature *s) { const SigMatch *sm; - for (sm = s->init_data->smlists[DETECT_SM_LIST_MATCH] ; sm != NULL; sm = sm->next) { + for (sm = s->init_data->smlists[DETECT_SM_LIST_MATCH]; sm != NULL; sm = sm->next) { switch (sm->type) { case DETECT_ITYPE: return true; diff --git a/src/detect-krb5-cname.c b/src/detect-krb5-cname.c index 8664f2bc2877..31ce05fc41cb 100644 --- a/src/detect-krb5-cname.c +++ b/src/detect-krb5-cname.c @@ -97,7 +97,10 @@ static uint8_t DetectEngineInspectKrb5CName(DetectEngineCtx *de_ctx, DetectEngin } while (1) { - struct Krb5PrincipalNameDataArgs cbdata = { local_id, txv, }; + struct Krb5PrincipalNameDataArgs cbdata = { + local_id, + txv, + }; InspectionBuffer *buffer = GetKrb5CNameData(det_ctx, transforms, f, &cbdata, engine->sm_list); if (buffer == NULL || buffer->inspect == NULL) @@ -140,7 +143,7 @@ static void PrefilterTxKrb5CName(DetectEngineThreadCtx *det_ctx, const void *pec uint32_t local_id = 0; - while(1) { + while (1) { // loop until we get a NULL struct Krb5PrincipalNameDataArgs cbdata = { local_id, txv }; @@ -173,9 +176,8 @@ static int PrefilterMpmKrb5CNameRegister(DetectEngineCtx *de_ctx, SigGroupHead * pectx->mpm_ctx = mpm_ctx; pectx->transforms = &mpm_reg->transforms; - return PrefilterAppendTxEngine(de_ctx, sgh, PrefilterTxKrb5CName, - mpm_reg->app_v2.alproto, mpm_reg->app_v2.tx_min_progress, - pectx, PrefilterMpmKrb5NameFree, mpm_reg->name); + return PrefilterAppendTxEngine(de_ctx, sgh, PrefilterTxKrb5CName, mpm_reg->app_v2.alproto, + mpm_reg->app_v2.tx_min_progress, pectx, PrefilterMpmKrb5NameFree, mpm_reg->name); } void DetectKrb5CNameRegister(void) @@ -184,19 +186,16 @@ void DetectKrb5CNameRegister(void) sigmatch_table[DETECT_AL_KRB5_CNAME].alias = "krb5_cname"; sigmatch_table[DETECT_AL_KRB5_CNAME].url = "/rules/kerberos-keywords.html#krb5-cname"; sigmatch_table[DETECT_AL_KRB5_CNAME].Setup = DetectKrb5CNameSetup; - sigmatch_table[DETECT_AL_KRB5_CNAME].flags |= SIGMATCH_NOOPT|SIGMATCH_INFO_STICKY_BUFFER; + sigmatch_table[DETECT_AL_KRB5_CNAME].flags |= SIGMATCH_NOOPT | SIGMATCH_INFO_STICKY_BUFFER; sigmatch_table[DETECT_AL_KRB5_CNAME].desc = "sticky buffer to match on Kerberos 5 client name"; - DetectAppLayerMpmRegister2("krb5_cname", SIG_FLAG_TOCLIENT, 2, - PrefilterMpmKrb5CNameRegister, NULL, - ALPROTO_KRB5, 1); + DetectAppLayerMpmRegister2("krb5_cname", SIG_FLAG_TOCLIENT, 2, PrefilterMpmKrb5CNameRegister, + NULL, ALPROTO_KRB5, 1); - DetectAppLayerInspectEngineRegister2("krb5_cname", - ALPROTO_KRB5, SIG_FLAG_TOCLIENT, 0, - DetectEngineInspectKrb5CName, NULL); + DetectAppLayerInspectEngineRegister2( + "krb5_cname", ALPROTO_KRB5, SIG_FLAG_TOCLIENT, 0, DetectEngineInspectKrb5CName, NULL); - DetectBufferTypeSetDescriptionByName("krb5_cname", - "Kerberos 5 ticket client name"); + DetectBufferTypeSetDescriptionByName("krb5_cname", "Kerberos 5 ticket client name"); g_krb5_cname_buffer_id = DetectBufferTypeGetByName("krb5_cname"); diff --git a/src/detect-krb5-errcode.c b/src/detect-krb5-errcode.c index f9d22cbede5d..df013a6c7826 100644 --- a/src/detect-krb5-errcode.c +++ b/src/detect-krb5-errcode.c @@ -36,17 +36,16 @@ /** * \brief Regex for parsing our keyword options */ -#define PARSE_REGEX "^\\s*([A-z0-9\\.]+|\"[A-z0-9_\\.]+\")\\s*$" +#define PARSE_REGEX "^\\s*([A-z0-9\\.]+|\"[A-z0-9_\\.]+\")\\s*$" static DetectParseRegex parse_regex; /* Prototypes of functions registered in DetectKrb5ErrCodeRegister below */ -static int DetectKrb5ErrCodeMatch (DetectEngineThreadCtx *, Flow *, - uint8_t, void *, void *, const Signature *, - const SigMatchCtx *); -static int DetectKrb5ErrCodeSetup (DetectEngineCtx *, Signature *, const char *); -static void DetectKrb5ErrCodeFree (DetectEngineCtx *, void *); +static int DetectKrb5ErrCodeMatch(DetectEngineThreadCtx *, Flow *, uint8_t, void *, void *, + const Signature *, const SigMatchCtx *); +static int DetectKrb5ErrCodeSetup(DetectEngineCtx *, Signature *, const char *); +static void DetectKrb5ErrCodeFree(DetectEngineCtx *, void *); #ifdef UNITTESTS -static void DetectKrb5ErrCodeRegisterTests (void); +static void DetectKrb5ErrCodeRegisterTests(void); #endif static int g_krb5_err_code_list_id = 0; @@ -93,10 +92,8 @@ void DetectKrb5ErrCodeRegister(void) * \retval 0 no match * \retval 1 match */ -static int DetectKrb5ErrCodeMatch (DetectEngineThreadCtx *det_ctx, - Flow *f, uint8_t flags, void *state, - void *txv, const Signature *s, - const SigMatchCtx *ctx) +static int DetectKrb5ErrCodeMatch(DetectEngineThreadCtx *det_ctx, Flow *f, uint8_t flags, + void *state, void *txv, const Signature *s, const SigMatchCtx *ctx) { int32_t err_code; int ret; @@ -122,7 +119,7 @@ static int DetectKrb5ErrCodeMatch (DetectEngineThreadCtx *det_ctx, * \retval krb5d pointer to DetectKrb5Data on success * \retval NULL on failure */ -static DetectKrb5ErrCodeData *DetectKrb5ErrCodeParse (const char *krb5str) +static DetectKrb5ErrCodeData *DetectKrb5ErrCodeParse(const char *krb5str) { DetectKrb5ErrCodeData *krb5d = NULL; char arg1[4] = ""; @@ -143,11 +140,10 @@ static DetectKrb5ErrCodeData *DetectKrb5ErrCodeParse (const char *krb5str) goto error; } - krb5d = SCMalloc(sizeof (DetectKrb5ErrCodeData)); + krb5d = SCMalloc(sizeof(DetectKrb5ErrCodeData)); if (unlikely(krb5d == NULL)) goto error; - if (StringParseInt32(&krb5d->err_code, 10, 0, - (const char *)arg1) < 0) { + if (StringParseInt32(&krb5d->err_code, 10, 0, (const char *)arg1) < 0) { goto error; } pcre2_match_data_free(match); @@ -173,7 +169,7 @@ static DetectKrb5ErrCodeData *DetectKrb5ErrCodeParse (const char *krb5str) * \retval 0 on Success * \retval -1 on Failure */ -static int DetectKrb5ErrCodeSetup (DetectEngineCtx *de_ctx, Signature *s, const char *krb5str) +static int DetectKrb5ErrCodeSetup(DetectEngineCtx *de_ctx, Signature *s, const char *krb5str) { DetectKrb5ErrCodeData *krb5d = NULL; @@ -202,7 +198,8 @@ static int DetectKrb5ErrCodeSetup (DetectEngineCtx *de_ctx, Signature *s, const * * \param ptr pointer to DetectKrb5Data */ -static void DetectKrb5ErrCodeFree(DetectEngineCtx *de_ctx, void *ptr) { +static void DetectKrb5ErrCodeFree(DetectEngineCtx *de_ctx, void *ptr) +{ DetectKrb5ErrCodeData *krb5d = (DetectKrb5ErrCodeData *)ptr; SCFree(krb5d); @@ -213,7 +210,7 @@ static void DetectKrb5ErrCodeFree(DetectEngineCtx *de_ctx, void *ptr) { * \test description of the test */ -static int DetectKrb5ErrCodeParseTest01 (void) +static int DetectKrb5ErrCodeParseTest01(void) { DetectKrb5ErrCodeData *krb5d = DetectKrb5ErrCodeParse("10"); FAIL_IF_NULL(krb5d); @@ -222,12 +219,13 @@ static int DetectKrb5ErrCodeParseTest01 (void) PASS; } -static int DetectKrb5ErrCodeSignatureTest01 (void) +static int DetectKrb5ErrCodeSignatureTest01(void) { DetectEngineCtx *de_ctx = DetectEngineCtxInit(); FAIL_IF_NULL(de_ctx); - Signature *sig = DetectEngineAppendSig(de_ctx, "alert krb5 any any -> any any (krb5_err_code:10; sid:1; rev:1;)"); + Signature *sig = DetectEngineAppendSig( + de_ctx, "alert krb5 any any -> any any (krb5_err_code:10; sid:1; rev:1;)"); FAIL_IF_NULL(sig); DetectEngineCtxFree(de_ctx); @@ -240,7 +238,6 @@ static int DetectKrb5ErrCodeSignatureTest01 (void) static void DetectKrb5ErrCodeRegisterTests(void) { UtRegisterTest("DetectKrb5ErrCodeParseTest01", DetectKrb5ErrCodeParseTest01); - UtRegisterTest("DetectKrb5ErrCodeSignatureTest01", - DetectKrb5ErrCodeSignatureTest01); + UtRegisterTest("DetectKrb5ErrCodeSignatureTest01", DetectKrb5ErrCodeSignatureTest01); } #endif /* UNITTESTS */ diff --git a/src/detect-krb5-msgtype.c b/src/detect-krb5-msgtype.c index 4e2ae85848ed..f088d97e58a6 100644 --- a/src/detect-krb5-msgtype.c +++ b/src/detect-krb5-msgtype.c @@ -36,17 +36,16 @@ /** * \brief Regex for parsing our keyword options */ -#define PARSE_REGEX "^\\s*([A-z0-9\\.]+|\"[A-z0-9_\\.]+\")\\s*$" +#define PARSE_REGEX "^\\s*([A-z0-9\\.]+|\"[A-z0-9_\\.]+\")\\s*$" static DetectParseRegex parse_regex; /* Prototypes of functions registered in DetectKrb5MsgTypeRegister below */ -static int DetectKrb5MsgTypeMatch (DetectEngineThreadCtx *, Flow *, - uint8_t, void *, void *, const Signature *, - const SigMatchCtx *); -static int DetectKrb5MsgTypeSetup (DetectEngineCtx *, Signature *, const char *); -static void DetectKrb5MsgTypeFree (DetectEngineCtx *, void *); +static int DetectKrb5MsgTypeMatch(DetectEngineThreadCtx *, Flow *, uint8_t, void *, void *, + const Signature *, const SigMatchCtx *); +static int DetectKrb5MsgTypeSetup(DetectEngineCtx *, Signature *, const char *); +static void DetectKrb5MsgTypeFree(DetectEngineCtx *, void *); #ifdef UNITTESTS -static void DetectKrb5MsgTypeRegisterTests (void); +static void DetectKrb5MsgTypeRegisterTests(void); #endif static int g_krb5_msg_type_list_id = 0; @@ -93,10 +92,8 @@ void DetectKrb5MsgTypeRegister(void) * \retval 0 no match * \retval 1 match */ -static int DetectKrb5MsgTypeMatch (DetectEngineThreadCtx *det_ctx, - Flow *f, uint8_t flags, void *state, - void *txv, const Signature *s, - const SigMatchCtx *ctx) +static int DetectKrb5MsgTypeMatch(DetectEngineThreadCtx *det_ctx, Flow *f, uint8_t flags, + void *state, void *txv, const Signature *s, const SigMatchCtx *ctx) { uint32_t msg_type; const DetectKrb5MsgTypeData *dd = (const DetectKrb5MsgTypeData *)ctx; @@ -119,7 +116,7 @@ static int DetectKrb5MsgTypeMatch (DetectEngineThreadCtx *det_ctx, * \retval krb5d pointer to DetectKrb5Data on success * \retval NULL on failure */ -static DetectKrb5MsgTypeData *DetectKrb5MsgTypeParse (const char *krb5str) +static DetectKrb5MsgTypeData *DetectKrb5MsgTypeParse(const char *krb5str) { DetectKrb5MsgTypeData *krb5d = NULL; char arg1[4] = ""; @@ -140,11 +137,10 @@ static DetectKrb5MsgTypeData *DetectKrb5MsgTypeParse (const char *krb5str) goto error; } - krb5d = SCMalloc(sizeof (DetectKrb5MsgTypeData)); + krb5d = SCMalloc(sizeof(DetectKrb5MsgTypeData)); if (unlikely(krb5d == NULL)) goto error; - if (StringParseUint8(&krb5d->msg_type, 10, 0, - (const char *)arg1) < 0) { + if (StringParseUint8(&krb5d->msg_type, 10, 0, (const char *)arg1) < 0) { goto error; } pcre2_match_data_free(match); @@ -170,7 +166,7 @@ static DetectKrb5MsgTypeData *DetectKrb5MsgTypeParse (const char *krb5str) * \retval 0 on Success * \retval -1 on Failure */ -static int DetectKrb5MsgTypeSetup (DetectEngineCtx *de_ctx, Signature *s, const char *krb5str) +static int DetectKrb5MsgTypeSetup(DetectEngineCtx *de_ctx, Signature *s, const char *krb5str) { DetectKrb5MsgTypeData *krb5d = NULL; @@ -199,7 +195,8 @@ static int DetectKrb5MsgTypeSetup (DetectEngineCtx *de_ctx, Signature *s, const * * \param ptr pointer to DetectKrb5Data */ -static void DetectKrb5MsgTypeFree(DetectEngineCtx *de_ctx, void *ptr) { +static void DetectKrb5MsgTypeFree(DetectEngineCtx *de_ctx, void *ptr) +{ DetectKrb5MsgTypeData *krb5d = (DetectKrb5MsgTypeData *)ptr; SCFree(krb5d); @@ -211,7 +208,7 @@ static void DetectKrb5MsgTypeFree(DetectEngineCtx *de_ctx, void *ptr) { * \test description of the test */ -static int DetectKrb5MsgTypeParseTest01 (void) +static int DetectKrb5MsgTypeParseTest01(void) { DetectKrb5MsgTypeData *krb5d = DetectKrb5MsgTypeParse("10"); FAIL_IF_NULL(krb5d); @@ -220,12 +217,13 @@ static int DetectKrb5MsgTypeParseTest01 (void) PASS; } -static int DetectKrb5MsgTypeSignatureTest01 (void) +static int DetectKrb5MsgTypeSignatureTest01(void) { DetectEngineCtx *de_ctx = DetectEngineCtxInit(); FAIL_IF_NULL(de_ctx); - Signature *sig = DetectEngineAppendSig(de_ctx, "alert krb5 any any -> any any (krb5_msg_type:10; sid:1; rev:1;)"); + Signature *sig = DetectEngineAppendSig( + de_ctx, "alert krb5 any any -> any any (krb5_msg_type:10; sid:1; rev:1;)"); FAIL_IF_NULL(sig); DetectEngineCtxFree(de_ctx); @@ -238,7 +236,6 @@ static int DetectKrb5MsgTypeSignatureTest01 (void) static void DetectKrb5MsgTypeRegisterTests(void) { UtRegisterTest("DetectKrb5MsgTypeParseTest01", DetectKrb5MsgTypeParseTest01); - UtRegisterTest("DetectKrb5MsgTypeSignatureTest01", - DetectKrb5MsgTypeSignatureTest01); + UtRegisterTest("DetectKrb5MsgTypeSignatureTest01", DetectKrb5MsgTypeSignatureTest01); } #endif /* UNITTESTS */ diff --git a/src/detect-krb5-sname.c b/src/detect-krb5-sname.c index 1e4ae24a4bd1..b0caabbca072 100644 --- a/src/detect-krb5-sname.c +++ b/src/detect-krb5-sname.c @@ -97,7 +97,10 @@ static uint8_t DetectEngineInspectKrb5SName(DetectEngineCtx *de_ctx, DetectEngin } while (1) { - struct Krb5PrincipalNameDataArgs cbdata = { local_id, txv, }; + struct Krb5PrincipalNameDataArgs cbdata = { + local_id, + txv, + }; InspectionBuffer *buffer = GetKrb5SNameData(det_ctx, transforms, f, &cbdata, engine->sm_list); @@ -141,7 +144,7 @@ static void PrefilterTxKrb5SName(DetectEngineThreadCtx *det_ctx, const void *pec uint32_t local_id = 0; - while(1) { + while (1) { // loop until we get a NULL struct Krb5PrincipalNameDataArgs cbdata = { local_id, txv }; @@ -174,9 +177,8 @@ static int PrefilterMpmKrb5SNameRegister(DetectEngineCtx *de_ctx, SigGroupHead * pectx->mpm_ctx = mpm_ctx; pectx->transforms = &mpm_reg->transforms; - return PrefilterAppendTxEngine(de_ctx, sgh, PrefilterTxKrb5SName, - mpm_reg->app_v2.alproto, mpm_reg->app_v2.tx_min_progress, - pectx, PrefilterMpmKrb5NameFree, mpm_reg->name); + return PrefilterAppendTxEngine(de_ctx, sgh, PrefilterTxKrb5SName, mpm_reg->app_v2.alproto, + mpm_reg->app_v2.tx_min_progress, pectx, PrefilterMpmKrb5NameFree, mpm_reg->name); } void DetectKrb5SNameRegister(void) @@ -185,19 +187,16 @@ void DetectKrb5SNameRegister(void) sigmatch_table[DETECT_AL_KRB5_SNAME].alias = "krb5_sname"; sigmatch_table[DETECT_AL_KRB5_SNAME].url = "/rules/kerberos-keywords.html#krb5-sname"; sigmatch_table[DETECT_AL_KRB5_SNAME].Setup = DetectKrb5SNameSetup; - sigmatch_table[DETECT_AL_KRB5_SNAME].flags |= SIGMATCH_NOOPT|SIGMATCH_INFO_STICKY_BUFFER; + sigmatch_table[DETECT_AL_KRB5_SNAME].flags |= SIGMATCH_NOOPT | SIGMATCH_INFO_STICKY_BUFFER; sigmatch_table[DETECT_AL_KRB5_SNAME].desc = "sticky buffer to match on Kerberos 5 server name"; - DetectAppLayerMpmRegister2("krb5_sname", SIG_FLAG_TOCLIENT, 2, - PrefilterMpmKrb5SNameRegister, NULL, - ALPROTO_KRB5, 1); + DetectAppLayerMpmRegister2("krb5_sname", SIG_FLAG_TOCLIENT, 2, PrefilterMpmKrb5SNameRegister, + NULL, ALPROTO_KRB5, 1); - DetectAppLayerInspectEngineRegister2("krb5_sname", - ALPROTO_KRB5, SIG_FLAG_TOCLIENT, 0, - DetectEngineInspectKrb5SName, NULL); + DetectAppLayerInspectEngineRegister2( + "krb5_sname", ALPROTO_KRB5, SIG_FLAG_TOCLIENT, 0, DetectEngineInspectKrb5SName, NULL); - DetectBufferTypeSetDescriptionByName("krb5_sname", - "Kerberos 5 ticket server name"); + DetectBufferTypeSetDescriptionByName("krb5_sname", "Kerberos 5 ticket server name"); g_krb5_sname_buffer_id = DetectBufferTypeGetByName("krb5_sname"); diff --git a/src/detect-l3proto.c b/src/detect-l3proto.c index 6e08cf978b78..78b32d04308e 100644 --- a/src/detect-l3proto.c +++ b/src/detect-l3proto.c @@ -56,7 +56,7 @@ void DetectL3ProtoRegister(void) sigmatch_table[DETECT_L3PROTO].name = "l3_proto"; sigmatch_table[DETECT_L3PROTO].Match = NULL; sigmatch_table[DETECT_L3PROTO].Setup = DetectL3ProtoSetup; - sigmatch_table[DETECT_L3PROTO].Free = NULL; + sigmatch_table[DETECT_L3PROTO].Free = NULL; #ifdef UNITTESTS sigmatch_table[DETECT_L3PROTO].RegisterTests = DetectL3protoRegisterTests; #endif @@ -81,16 +81,14 @@ static int DetectL3ProtoSetup(DetectEngineCtx *de_ctx, Signature *s, const char } /* authorized value, ip, any, ip4, ipv4, ip6, ipv6 */ - if (strcasecmp(str,"ipv4") == 0 || - strcasecmp(str,"ip4") == 0 ) { + if (strcasecmp(str, "ipv4") == 0 || strcasecmp(str, "ip4") == 0) { if (s->proto.flags & DETECT_PROTO_IPV6) { SCLogError("Conflicting l3 proto specified"); goto error; } s->proto.flags |= DETECT_PROTO_IPV4; SCLogDebug("IPv4 protocol detected"); - } else if (strcasecmp(str,"ipv6") == 0 || - strcasecmp(str,"ip6") == 0 ) { + } else if (strcasecmp(str, "ipv6") == 0 || strcasecmp(str, "ip6") == 0) { if (s->proto.flags & DETECT_PROTO_IPV6) { SCLogError("Conflicting l3 proto specified"); goto error; diff --git a/src/detect-l3proto.h b/src/detect-l3proto.h index 447cd95d0925..3b8e4c1c9881 100644 --- a/src/detect-l3proto.h +++ b/src/detect-l3proto.h @@ -28,6 +28,6 @@ /** * \brief Registration function for ip_proto keyword. */ -void DetectL3ProtoRegister (void); +void DetectL3ProtoRegister(void); #endif /* __DETECT_L3PROTO_H__ */ diff --git a/src/detect-lua-extensions.c b/src/detect-lua-extensions.c index 897b0874021a..260acc991b7b 100644 --- a/src/detect-lua-extensions.c +++ b/src/detect-lua-extensions.c @@ -78,8 +78,8 @@ static const char luaext_key_ld[] = "suricata:luadata"; /* hack to please scan-build. Even though LuaCallbackError *always* * returns 2, scan-build doesn't accept it and generates false * positives */ -#define LUA_ERROR(msg) \ - LuaCallbackError(luastate, (msg)); \ +#define LUA_ERROR(msg) \ + LuaCallbackError(luastate, (msg)); \ return 2 static int GetLuaData(lua_State *luastate, DetectLuaData **ret_ld) @@ -107,8 +107,8 @@ static int GetFlow(lua_State *luastate, Flow **ret_f) return 0; } -static int GetFlowVarById(lua_State *luastate, Flow *f, - FlowVar **ret_fv, bool fv_may_be_null, uint32_t *ret_idx) +static int GetFlowVarById( + lua_State *luastate, Flow *f, FlowVar **ret_fv, bool fv_may_be_null, uint32_t *ret_idx) { DetectLuaData *ld = NULL; if (ret_idx) @@ -168,8 +168,8 @@ static int GetFlowVarByKey(lua_State *luastate, Flow *f, FlowVar **ret_fv) return 0; } -static int GetFlowIntById(lua_State *luastate, Flow *f, - FlowVar **ret_fv, bool fv_may_be_null, uint32_t *ret_idx) +static int GetFlowIntById( + lua_State *luastate, Flow *f, FlowVar **ret_fv, bool fv_may_be_null, uint32_t *ret_idx) { DetectLuaData *ld = NULL; if (ret_idx) @@ -225,9 +225,8 @@ static int LuaGetFlowvar(lua_State *luastate) LUA_ERROR("invalid data type as first argument"); } - LuaPushStringBuffer(luastate, - (const uint8_t *)fv->data.fv_str.value, - (size_t)fv->data.fv_str.value_len); + LuaPushStringBuffer( + luastate, (const uint8_t *)fv->data.fv_str.value, (size_t)fv->data.fv_str.value_len); return 1; } @@ -265,7 +264,7 @@ static int LuaSetFlowvarById(lua_State *luastate) LUA_ERROR("len out of range: max 64k"); } - buffer = SCMalloc(len+1); + buffer = SCMalloc(len + 1); if (unlikely(buffer == NULL)) { LUA_ERROR("out of memory"); } @@ -319,14 +318,14 @@ static int LuaSetFlowvarByKey(lua_State *luastate) LUA_ERROR("len out of range: max 64k"); } - buffer = SCMalloc(len+1); + buffer = SCMalloc(len + 1); if (unlikely(buffer == NULL)) { LUA_ERROR("out of memory"); } memcpy(buffer, str, len); buffer[len] = '\0'; - uint8_t *keybuf = SCMalloc(keylen+1); + uint8_t *keybuf = SCMalloc(keylen + 1); if (unlikely(keybuf == NULL)) { SCFree(buffer); LUA_ERROR("out of memory"); @@ -367,7 +366,6 @@ static int LuaGetFlowint(lua_State *luastate) /* return value through luastate, as a luanumber */ lua_pushnumber(luastate, (lua_Number)number); return 1; - } static int LuaSetFlowint(lua_State *luastate) @@ -401,7 +399,7 @@ static int LuaSetFlowint(lua_State *luastate) lua_Number luanumber = lua_tonumber(luastate, 2); if (luanumber < 0 || id > (double)UINT_MAX) { LUA_ERROR("value out of range, " - "value must be unsigned 32bit int"); + "value must be unsigned 32bit int"); } uint32_t number = (uint32_t)luanumber; @@ -445,7 +443,6 @@ static int LuaIncrFlowint(lua_State *luastate) lua_pushnumber(luastate, (lua_Number)number); SCLogDebug("incremented flow:%p idx:%u value:%u", f, idx, number); return 1; - } static int LuaDecrFlowint(lua_State *luastate) @@ -477,7 +474,6 @@ static int LuaDecrFlowint(lua_State *luastate) lua_pushnumber(luastate, (lua_Number)number); SCLogDebug("decremented flow:%p idx:%u value:%u", f, idx, number); return 1; - } static int LuaGetByteVar(lua_State *luastate) diff --git a/src/detect-lua.c b/src/detect-lua.c index 0ea74452739e..ce8f5f5ea031 100644 --- a/src/detect-lua.c +++ b/src/detect-lua.c @@ -65,7 +65,7 @@ #ifndef HAVE_LUA -static int DetectLuaSetupNoSupport (DetectEngineCtx *a, Signature *b, const char *c) +static int DetectLuaSetupNoSupport(DetectEngineCtx *a, Signature *b, const char *c) { SCLogError("no Lua support built in, needed for lua/luajit keyword"); return -1; @@ -81,10 +81,10 @@ void DetectLuaRegister(void) sigmatch_table[DETECT_LUA].desc = "support for lua scripting"; sigmatch_table[DETECT_LUA].url = "/rules/rule-lua-scripting.html"; sigmatch_table[DETECT_LUA].Setup = DetectLuaSetupNoSupport; - sigmatch_table[DETECT_LUA].Free = NULL; + sigmatch_table[DETECT_LUA].Free = NULL; sigmatch_table[DETECT_LUA].flags = SIGMATCH_NOT_BUILT; - SCLogDebug("registering lua rule option"); + SCLogDebug("registering lua rule option"); return; } @@ -92,13 +92,11 @@ void DetectLuaRegister(void) #include "util-lua.h" -static int DetectLuaMatch (DetectEngineThreadCtx *, - Packet *, const Signature *, const SigMatchCtx *); -static int DetectLuaAppTxMatch (DetectEngineThreadCtx *det_ctx, - Flow *f, uint8_t flags, - void *state, void *txv, const Signature *s, - const SigMatchCtx *ctx); -static int DetectLuaSetup (DetectEngineCtx *, Signature *, const char *); +static int DetectLuaMatch( + DetectEngineThreadCtx *, Packet *, const Signature *, const SigMatchCtx *); +static int DetectLuaAppTxMatch(DetectEngineThreadCtx *det_ctx, Flow *f, uint8_t flags, void *state, + void *txv, const Signature *s, const SigMatchCtx *ctx); +static int DetectLuaSetup(DetectEngineCtx *, Signature *, const char *); #ifdef UNITTESTS static void DetectLuaRegisterTests(void); #endif @@ -117,7 +115,7 @@ void DetectLuaRegister(void) sigmatch_table[DETECT_LUA].Match = DetectLuaMatch; sigmatch_table[DETECT_LUA].AppLayerTxMatch = DetectLuaAppTxMatch; sigmatch_table[DETECT_LUA].Setup = DetectLuaSetup; - sigmatch_table[DETECT_LUA].Free = DetectLuaFree; + sigmatch_table[DETECT_LUA].Free = DetectLuaFree; #ifdef UNITTESTS sigmatch_table[DETECT_LUA].RegisterTests = DetectLuaRegisterTests; #endif @@ -202,9 +200,8 @@ void LuaDumpStack(lua_State *state) } #endif -int DetectLuaMatchBuffer(DetectEngineThreadCtx *det_ctx, - const Signature *s, const SigMatchData *smd, - const uint8_t *buffer, uint32_t buffer_len, uint32_t offset, +int DetectLuaMatchBuffer(DetectEngineThreadCtx *det_ctx, const Signature *s, + const SigMatchData *smd, const uint8_t *buffer, uint32_t buffer_len, uint32_t offset, Flow *f) { SCEnter(); @@ -217,7 +214,8 @@ int DetectLuaMatchBuffer(DetectEngineThreadCtx *det_ctx, if (lua == NULL) SCReturnInt(0); - DetectLuaThreadData *tlua = (DetectLuaThreadData *)DetectThreadCtxGetKeywordThreadCtx(det_ctx, lua->thread_ctx_id); + DetectLuaThreadData *tlua = + (DetectLuaThreadData *)DetectThreadCtxGetKeywordThreadCtx(det_ctx, lua->thread_ctx_id); if (tlua == NULL) SCReturnInt(0); @@ -227,11 +225,11 @@ int DetectLuaMatchBuffer(DetectEngineThreadCtx *det_ctx, lua_getglobal(tlua->luastate, "match"); lua_newtable(tlua->luastate); /* stack at -1 */ - lua_pushliteral (tlua->luastate, "offset"); /* stack at -2 */ - lua_pushnumber (tlua->luastate, (int)(offset + 1)); + lua_pushliteral(tlua->luastate, "offset"); /* stack at -2 */ + lua_pushnumber(tlua->luastate, (int)(offset + 1)); lua_settable(tlua->luastate, -3); - lua_pushstring (tlua->luastate, lua->buffername); /* stack at -2 */ + lua_pushstring(tlua->luastate, lua->buffername); /* stack at -2 */ LuaPushStringBuffer(tlua->luastate, (const uint8_t *)buffer, (size_t)buffer_len); lua_settable(tlua->luastate, -3); @@ -251,7 +249,7 @@ int DetectLuaMatchBuffer(DetectEngineThreadCtx *det_ctx, if (script_ret == 1.0) ret = 1; - /* script returns a table */ + /* script returns a table */ } else if (lua_type(tlua->luastate, 1) == LUA_TTABLE) { lua_pushnil(tlua->luastate); const char *k, *v; @@ -272,8 +270,7 @@ int DetectLuaMatchBuffer(DetectEngineThreadCtx *det_ctx, "for \"retval\" from LUA return table: '%s'", v); ret = 0; - } - else if (val == 1) { + } else if (val == 1) { ret = 1; } } else { @@ -315,8 +312,8 @@ int DetectLuaMatchBuffer(DetectEngineThreadCtx *det_ctx, * \retval 0 no match * \retval 1 match */ -static int DetectLuaMatch (DetectEngineThreadCtx *det_ctx, - Packet *p, const Signature *s, const SigMatchCtx *ctx) +static int DetectLuaMatch( + DetectEngineThreadCtx *det_ctx, Packet *p, const Signature *s, const SigMatchCtx *ctx) { SCEnter(); int ret = 0; @@ -324,7 +321,8 @@ static int DetectLuaMatch (DetectEngineThreadCtx *det_ctx, if (lua == NULL) SCReturnInt(0); - DetectLuaThreadData *tlua = (DetectLuaThreadData *)DetectThreadCtxGetKeywordThreadCtx(det_ctx, lua->thread_ctx_id); + DetectLuaThreadData *tlua = + (DetectLuaThreadData *)DetectThreadCtxGetKeywordThreadCtx(det_ctx, lua->thread_ctx_id); if (tlua == NULL) SCReturnInt(0); @@ -357,32 +355,33 @@ static int DetectLuaMatch (DetectEngineThreadCtx *det_ctx, if ((tlua->flags & DATATYPE_PAYLOAD) && p->payload_len) { lua_pushliteral(tlua->luastate, "payload"); /* stack at -2 */ - LuaPushStringBuffer (tlua->luastate, (const uint8_t *)p->payload, (size_t)p->payload_len); /* stack at -3 */ + LuaPushStringBuffer(tlua->luastate, (const uint8_t *)p->payload, + (size_t)p->payload_len); /* stack at -3 */ lua_settable(tlua->luastate, -3); } if ((tlua->flags & DATATYPE_PACKET) && GET_PKT_LEN(p)) { lua_pushliteral(tlua->luastate, "packet"); /* stack at -2 */ - LuaPushStringBuffer (tlua->luastate, (const uint8_t *)GET_PKT_DATA(p), (size_t)GET_PKT_LEN(p)); /* stack at -3 */ + LuaPushStringBuffer(tlua->luastate, (const uint8_t *)GET_PKT_DATA(p), + (size_t)GET_PKT_LEN(p)); /* stack at -3 */ lua_settable(tlua->luastate, -3); } if (tlua->alproto == ALPROTO_HTTP1) { HtpState *htp_state = p->flow->alstate; if (htp_state != NULL && htp_state->connp != NULL) { htp_tx_t *tx = NULL; - uint64_t idx = AppLayerParserGetTransactionInspectId(p->flow->alparser, - STREAM_TOSERVER); - uint64_t total_txs= AppLayerParserGetTxCnt(p->flow, htp_state); - for ( ; idx < total_txs; idx++) { + uint64_t idx = + AppLayerParserGetTransactionInspectId(p->flow->alparser, STREAM_TOSERVER); + uint64_t total_txs = AppLayerParserGetTxCnt(p->flow, htp_state); + for (; idx < total_txs; idx++) { tx = AppLayerParserGetTx(IPPROTO_TCP, ALPROTO_HTTP1, htp_state, idx); if (tx == NULL) continue; if ((tlua->flags & DATATYPE_HTTP_REQUEST_LINE) && tx->request_line != NULL && - bstr_len(tx->request_line) > 0) { + bstr_len(tx->request_line) > 0) { lua_pushliteral(tlua->luastate, "http.request_line"); /* stack at -2 */ - LuaPushStringBuffer(tlua->luastate, - (const uint8_t *)bstr_ptr(tx->request_line), - bstr_len(tx->request_line)); + LuaPushStringBuffer(tlua->luastate, (const uint8_t *)bstr_ptr(tx->request_line), + bstr_len(tx->request_line)); lua_settable(tlua->luastate, -3); } } @@ -406,7 +405,7 @@ static int DetectLuaMatch (DetectEngineThreadCtx *det_ctx, if (script_ret == 1.0) ret = 1; - /* script returns a table */ + /* script returns a table */ } else if (lua_type(tlua->luastate, 1) == LUA_TTABLE) { lua_pushnil(tlua->luastate); const char *k, *v; @@ -422,14 +421,12 @@ static int DetectLuaMatch (DetectEngineThreadCtx *det_ctx, if (strcmp(k, "retval") == 0) { int val; - if (StringParseInt32(&val, 10, 0, - (const char *)v) < 0) { + if (StringParseInt32(&val, 10, 0, (const char *)v) < 0) { SCLogError("Invalid value " "for \"retval\" from LUA return table: '%s'", v); ret = 0; - } - else if (val == 1) { + } else if (val == 1) { ret = 1; } } else { @@ -455,9 +452,8 @@ static int DetectLuaMatch (DetectEngineThreadCtx *det_ctx, SCReturnInt(ret); } -static int DetectLuaAppMatchCommon (DetectEngineThreadCtx *det_ctx, - Flow *f, uint8_t flags, void *state, - const Signature *s, const SigMatchCtx *ctx) +static int DetectLuaAppMatchCommon(DetectEngineThreadCtx *det_ctx, Flow *f, uint8_t flags, + void *state, const Signature *s, const SigMatchCtx *ctx) { SCEnter(); int ret = 0; @@ -465,7 +461,8 @@ static int DetectLuaAppMatchCommon (DetectEngineThreadCtx *det_ctx, if (lua == NULL) SCReturnInt(0); - DetectLuaThreadData *tlua = (DetectLuaThreadData *)DetectThreadCtxGetKeywordThreadCtx(det_ctx, lua->thread_ctx_id); + DetectLuaThreadData *tlua = + (DetectLuaThreadData *)DetectThreadCtxGetKeywordThreadCtx(det_ctx, lua->thread_ctx_id); if (tlua == NULL) SCReturnInt(0); @@ -488,11 +485,10 @@ static int DetectLuaAppMatchCommon (DetectEngineThreadCtx *det_ctx, tx = AppLayerParserGetTx(IPPROTO_TCP, ALPROTO_HTTP1, htp_state, det_ctx->tx_id); if (tx != NULL) { if ((tlua->flags & DATATYPE_HTTP_REQUEST_LINE) && tx->request_line != NULL && - bstr_len(tx->request_line) > 0) { + bstr_len(tx->request_line) > 0) { lua_pushliteral(tlua->luastate, "http.request_line"); /* stack at -2 */ - LuaPushStringBuffer(tlua->luastate, - (const uint8_t *)bstr_ptr(tx->request_line), - bstr_len(tx->request_line)); + LuaPushStringBuffer(tlua->luastate, (const uint8_t *)bstr_ptr(tx->request_line), + bstr_len(tx->request_line)); lua_settable(tlua->luastate, -3); } } @@ -516,7 +512,7 @@ static int DetectLuaAppMatchCommon (DetectEngineThreadCtx *det_ctx, if (script_ret == 1.0) ret = 1; - /* script returns a table */ + /* script returns a table */ } else if (lua_type(tlua->luastate, 1) == LUA_TTABLE) { lua_pushnil(tlua->luastate); const char *k, *v; @@ -532,14 +528,12 @@ static int DetectLuaAppMatchCommon (DetectEngineThreadCtx *det_ctx, if (strcmp(k, "retval") == 0) { int val; - if (StringParseInt32(&val, 10, 0, - (const char *)v) < 0) { + if (StringParseInt32(&val, 10, 0, (const char *)v) < 0) { SCLogError("Invalid value " "for \"retval\" from LUA return table: '%s'", v); ret = 0; - } - else if (val == 1) { + } else if (val == 1) { ret = 1; } } else { @@ -576,10 +570,8 @@ static int DetectLuaAppMatchCommon (DetectEngineThreadCtx *det_ctx, * \retval 0 no match * \retval 1 match */ -static int DetectLuaAppTxMatch (DetectEngineThreadCtx *det_ctx, - Flow *f, uint8_t flags, - void *state, void *txv, const Signature *s, - const SigMatchCtx *ctx) +static int DetectLuaAppTxMatch(DetectEngineThreadCtx *det_ctx, Flow *f, uint8_t flags, void *state, + void *txv, const Signature *s, const SigMatchCtx *ctx) { return DetectLuaAppMatchCommon(det_ctx, f, flags, state, s, ctx); } @@ -675,7 +667,7 @@ static void DetectLuaThreadFree(void *ctx) * \retval lua pointer to DetectLuaData on success * \retval NULL on failure */ -static DetectLuaData *DetectLuaParse (DetectEngineCtx *de_ctx, const char *str) +static DetectLuaData *DetectLuaParse(DetectEngineCtx *de_ctx, const char *str) { DetectLuaData *lua = NULL; @@ -750,7 +742,7 @@ static int DetectLuaSetupPrime(DetectEngineCtx *de_ctx, DetectLuaData *ld, const } lua_pushliteral(luastate, "script_api_ver"); /* stack at -2 */ - lua_pushnumber (luastate, 1); /* stack at -3 */ + lua_pushnumber(luastate, 1); /* stack at -3 */ lua_settable(luastate, -3); if (lua_pcall(luastate, 1, 1, 0) != 0) { @@ -1007,7 +999,7 @@ static int DetectLuaSetupPrime(DetectEngineCtx *de_ctx, DetectLuaData *ld, const * \retval 0 on Success * \retval -1 on Failure */ -static int DetectLuaSetup (DetectEngineCtx *de_ctx, Signature *s, const char *str) +static int DetectLuaSetup(DetectEngineCtx *de_ctx, Signature *s, const char *str) { DetectLuaData *lua = NULL; @@ -1028,9 +1020,8 @@ static int DetectLuaSetup (DetectEngineCtx *de_ctx, Signature *s, const char *st goto error; } - lua->thread_ctx_id = DetectRegisterThreadCtxFuncs(de_ctx, "lua", - DetectLuaThreadInit, (void *)lua, - DetectLuaThreadFree, 0); + lua->thread_ctx_id = DetectRegisterThreadCtxFuncs( + de_ctx, "lua", DetectLuaThreadInit, (void *)lua, DetectLuaThreadFree, 0); if (lua->thread_ctx_id == -1) goto error; @@ -1070,14 +1061,14 @@ static int DetectLuaSetup (DetectEngineCtx *de_ctx, Signature *s, const char *st } else if (lua->flags & DATATYPE_HTTP_URI_RAW) { list = DetectBufferTypeGetByName("http_raw_uri"); } else if (lua->flags & DATATYPE_HTTP_REQUEST_COOKIE || - lua->flags & DATATYPE_HTTP_RESPONSE_COOKIE) - { + lua->flags & DATATYPE_HTTP_RESPONSE_COOKIE) { list = DetectBufferTypeGetByName("http_cookie"); } else if (lua->flags & DATATYPE_HTTP_REQUEST_UA) { list = DetectBufferTypeGetByName("http_user_agent"); - } else if (lua->flags & (DATATYPE_HTTP_REQUEST_HEADERS|DATATYPE_HTTP_RESPONSE_HEADERS)) { + } else if (lua->flags & (DATATYPE_HTTP_REQUEST_HEADERS | DATATYPE_HTTP_RESPONSE_HEADERS)) { list = DetectBufferTypeGetByName("http_header"); - } else if (lua->flags & (DATATYPE_HTTP_REQUEST_HEADERS_RAW|DATATYPE_HTTP_RESPONSE_HEADERS_RAW)) { + } else if (lua->flags & + (DATATYPE_HTTP_REQUEST_HEADERS_RAW | DATATYPE_HTTP_RESPONSE_HEADERS_RAW)) { list = DetectBufferTypeGetByName("http_raw_header"); } else { list = DetectBufferTypeGetByName("http_request_line"); @@ -1177,41 +1168,38 @@ static int LuaMatchTest01(void) { ConfSetFinal("security.lua.allow-rules", "true"); - const char script[] = - "function init (args)\n" - " local needs = {}\n" - " needs[\"http.request_headers\"] = tostring(true)\n" - " needs[\"flowvar\"] = {\"cnt\"}\n" - " return needs\n" - "end\n" - "\n" - "function match(args)\n" - " a = ScFlowvarGet(0)\n" - " if a then\n" - " a = tostring(tonumber(a)+1)\n" - " print (a)\n" - " ScFlowvarSet(0, a, #a)\n" - " else\n" - " a = tostring(1)\n" - " print (a)\n" - " ScFlowvarSet(0, a, #a)\n" - " end\n" - " \n" - " print (\"pre check: \" .. (a))\n" - " if tonumber(a) == 2 then\n" - " print \"match\"\n" - " return 1\n" - " end\n" - " return 0\n" - "end\n" - "return 0\n"; + const char script[] = "function init (args)\n" + " local needs = {}\n" + " needs[\"http.request_headers\"] = tostring(true)\n" + " needs[\"flowvar\"] = {\"cnt\"}\n" + " return needs\n" + "end\n" + "\n" + "function match(args)\n" + " a = ScFlowvarGet(0)\n" + " if a then\n" + " a = tostring(tonumber(a)+1)\n" + " print (a)\n" + " ScFlowvarSet(0, a, #a)\n" + " else\n" + " a = tostring(1)\n" + " print (a)\n" + " ScFlowvarSet(0, a, #a)\n" + " end\n" + " \n" + " print (\"pre check: \" .. (a))\n" + " if tonumber(a) == 2 then\n" + " print \"match\"\n" + " return 1\n" + " end\n" + " return 0\n" + "end\n" + "return 0\n"; char sig[] = "alert http any any -> any any (flow:to_server; lua:unittest; sid:1;)"; - uint8_t httpbuf1[] = - "POST / HTTP/1.1\r\n" - "Host: www.emergingthreats.net\r\n\r\n"; - uint8_t httpbuf2[] = - "POST / HTTP/1.1\r\n" - "Host: www.openinfosecfoundation.org\r\n\r\n"; + uint8_t httpbuf1[] = "POST / HTTP/1.1\r\n" + "Host: www.emergingthreats.net\r\n\r\n"; + uint8_t httpbuf2[] = "POST / HTTP/1.1\r\n" + "Host: www.openinfosecfoundation.org\r\n\r\n"; uint32_t httplen1 = sizeof(httpbuf1) - 1; /* minus the \0 */ uint32_t httplen2 = sizeof(httpbuf2) - 1; /* minus the \0 */ TcpSession ssn; @@ -1239,11 +1227,11 @@ static int LuaMatchTest01(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOSERVER; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; StreamTcpInitConfig(true); @@ -1986,12 +1974,10 @@ static int LuaMatchTest04a(void) "end\n" "return 0\n"; char sig[] = "alert http any any -> any any (flow:to_server; lua:unittest; sid:1;)"; - uint8_t httpbuf1[] = - "POST / HTTP/1.1\r\n" - "Host: www.emergingthreats.net\r\n\r\n"; - uint8_t httpbuf2[] = - "POST / HTTP/1.1\r\n" - "Host: www.openinfosecfoundation.org\r\n\r\n"; + uint8_t httpbuf1[] = "POST / HTTP/1.1\r\n" + "Host: www.emergingthreats.net\r\n\r\n"; + uint8_t httpbuf2[] = "POST / HTTP/1.1\r\n" + "Host: www.openinfosecfoundation.org\r\n\r\n"; uint32_t httplen1 = sizeof(httpbuf1) - 1; /* minus the \0 */ uint32_t httplen2 = sizeof(httpbuf2) - 1; /* minus the \0 */ TcpSession ssn; @@ -2019,12 +2005,12 @@ static int LuaMatchTest04a(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOSERVER; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; StreamTcpInitConfig(true); @@ -2097,12 +2083,10 @@ static int LuaMatchTest05(void) "end\n" "return 0\n"; char sig[] = "alert http any any -> any any (flow:to_server; lua:unittest; sid:1;)"; - uint8_t httpbuf1[] = - "POST / HTTP/1.1\r\n" - "Host: www.emergingthreats.net\r\n\r\n"; - uint8_t httpbuf2[] = - "POST / HTTP/1.1\r\n" - "Host: www.openinfosecfoundation.org\r\n\r\n"; + uint8_t httpbuf1[] = "POST / HTTP/1.1\r\n" + "Host: www.emergingthreats.net\r\n\r\n"; + uint8_t httpbuf2[] = "POST / HTTP/1.1\r\n" + "Host: www.openinfosecfoundation.org\r\n\r\n"; uint32_t httplen1 = sizeof(httpbuf1) - 1; /* minus the \0 */ uint32_t httplen2 = sizeof(httpbuf2) - 1; /* minus the \0 */ TcpSession ssn; @@ -2130,12 +2114,12 @@ static int LuaMatchTest05(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOSERVER; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; StreamTcpInitConfig(true); @@ -2208,12 +2192,10 @@ static int LuaMatchTest05a(void) "end\n" "return 0\n"; char sig[] = "alert http any any -> any any (flow:to_server; lua:unittest; sid:1;)"; - uint8_t httpbuf1[] = - "POST / HTTP/1.1\r\n" - "Host: www.emergingthreats.net\r\n\r\n"; - uint8_t httpbuf2[] = - "POST / HTTP/1.1\r\n" - "Host: www.openinfosecfoundation.org\r\n\r\n"; + uint8_t httpbuf1[] = "POST / HTTP/1.1\r\n" + "Host: www.emergingthreats.net\r\n\r\n"; + uint8_t httpbuf2[] = "POST / HTTP/1.1\r\n" + "Host: www.openinfosecfoundation.org\r\n\r\n"; uint32_t httplen1 = sizeof(httpbuf1) - 1; /* minus the \0 */ uint32_t httplen2 = sizeof(httpbuf2) - 1; /* minus the \0 */ TcpSession ssn; @@ -2241,12 +2223,12 @@ static int LuaMatchTest05a(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOSERVER; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; StreamTcpInitConfig(true); @@ -2324,12 +2306,10 @@ static int LuaMatchTest06(void) "end\n" "return 0\n"; char sig[] = "alert http any any -> any any (flow:to_server; lua:unittest; sid:1;)"; - uint8_t httpbuf1[] = - "POST / HTTP/1.1\r\n" - "Host: www.emergingthreats.net\r\n\r\n"; - uint8_t httpbuf2[] = - "POST / HTTP/1.1\r\n" - "Host: www.openinfosecfoundation.org\r\n\r\n"; + uint8_t httpbuf1[] = "POST / HTTP/1.1\r\n" + "Host: www.emergingthreats.net\r\n\r\n"; + uint8_t httpbuf2[] = "POST / HTTP/1.1\r\n" + "Host: www.openinfosecfoundation.org\r\n\r\n"; uint32_t httplen1 = sizeof(httpbuf1) - 1; /* minus the \0 */ uint32_t httplen2 = sizeof(httpbuf2) - 1; /* minus the \0 */ TcpSession ssn; @@ -2357,12 +2337,12 @@ static int LuaMatchTest06(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOSERVER; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; StreamTcpInitConfig(true); @@ -2440,12 +2420,10 @@ static int LuaMatchTest06a(void) "end\n" "return 0\n"; char sig[] = "alert http any any -> any any (flow:to_server; lua:unittest; sid:1;)"; - uint8_t httpbuf1[] = - "POST / HTTP/1.1\r\n" - "Host: www.emergingthreats.net\r\n\r\n"; - uint8_t httpbuf2[] = - "POST / HTTP/1.1\r\n" - "Host: www.openinfosecfoundation.org\r\n\r\n"; + uint8_t httpbuf1[] = "POST / HTTP/1.1\r\n" + "Host: www.emergingthreats.net\r\n\r\n"; + uint8_t httpbuf2[] = "POST / HTTP/1.1\r\n" + "Host: www.openinfosecfoundation.org\r\n\r\n"; uint32_t httplen1 = sizeof(httpbuf1) - 1; /* minus the \0 */ uint32_t httplen2 = sizeof(httpbuf2) - 1; /* minus the \0 */ TcpSession ssn; @@ -2473,12 +2451,12 @@ static int LuaMatchTest06a(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOSERVER; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; StreamTcpInitConfig(true); diff --git a/src/detect-lua.h b/src/detect-lua.h index dcf99b6c3f43..7a0853f3f691 100644 --- a/src/detect-lua.h +++ b/src/detect-lua.h @@ -34,9 +34,9 @@ typedef struct DetectLuaThreadData { int alproto; } DetectLuaThreadData; -#define DETECT_LUAJIT_MAX_FLOWVARS 15 -#define DETECT_LUAJIT_MAX_FLOWINTS 15 -#define DETECT_LUAJIT_MAX_BYTEVARS 15 +#define DETECT_LUAJIT_MAX_FLOWVARS 15 +#define DETECT_LUAJIT_MAX_FLOWINTS 15 +#define DETECT_LUAJIT_MAX_BYTEVARS 15 typedef struct DetectLuaData { int thread_ctx_id; @@ -59,10 +59,9 @@ typedef struct DetectLuaData { #endif /* HAVE_LUA */ /* prototypes */ -void DetectLuaRegister (void); -int DetectLuaMatchBuffer(DetectEngineThreadCtx *det_ctx, - const Signature *s, const SigMatchData *smd, - const uint8_t *buffer, uint32_t buffer_len, uint32_t offset, +void DetectLuaRegister(void); +int DetectLuaMatchBuffer(DetectEngineThreadCtx *det_ctx, const Signature *s, + const SigMatchData *smd, const uint8_t *buffer, uint32_t buffer_len, uint32_t offset, Flow *f); void DetectLuaPostSetup(Signature *s); diff --git a/src/detect-mark.c b/src/detect-mark.c index 90ed7750a4e5..b6b3c75fa41d 100644 --- a/src/detect-mark.c +++ b/src/detect-mark.c @@ -41,9 +41,9 @@ static DetectParseRegex parse_regex; -static int DetectMarkSetup (DetectEngineCtx *, Signature *, const char *); -static int DetectMarkPacket(DetectEngineThreadCtx *det_ctx, Packet *p, - const Signature *s, const SigMatchCtx *ctx); +static int DetectMarkSetup(DetectEngineCtx *, Signature *, const char *); +static int DetectMarkPacket( + DetectEngineThreadCtx *det_ctx, Packet *p, const Signature *s, const SigMatchCtx *ctx); void DetectMarkDataFree(DetectEngineCtx *, void *ptr); #if defined UNITTESTS && defined NFQ static void MarkRegisterTests(void); @@ -53,12 +53,12 @@ static void MarkRegisterTests(void); * \brief Registration function for nfq_set_mark: keyword */ -void DetectMarkRegister (void) +void DetectMarkRegister(void) { sigmatch_table[DETECT_MARK].name = "nfq_set_mark"; sigmatch_table[DETECT_MARK].Match = DetectMarkPacket; sigmatch_table[DETECT_MARK].Setup = DetectMarkSetup; - sigmatch_table[DETECT_MARK].Free = DetectMarkDataFree; + sigmatch_table[DETECT_MARK].Free = DetectMarkDataFree; #if defined UNITTESTS && defined NFQ sigmatch_table[DETECT_MARK].RegisterTests = MarkRegisterTests; #endif @@ -75,7 +75,7 @@ void DetectMarkRegister (void) * \retval 0 on success * \retval < 0 on failure */ -static void * DetectMarkParse (const char *rawstr) +static void *DetectMarkParse(const char *rawstr) { int res = 0; size_t pcre2_len; @@ -111,8 +111,8 @@ static void * DetectMarkParse (const char *rawstr) SCLogError("Numeric value out of range"); pcre2_substring_free((PCRE2_UCHAR8 *)ptr); goto error; - } /* If there is no numeric value in the given string then strtoull(), makes - endptr equals to ptr and return 0 as result */ + } /* If there is no numeric value in the given string then strtoull(), makes + endptr equals to ptr and return 0 as result */ else if (endptr == ptr && mark == 0) { SCLogError("No numeric value"); pcre2_substring_free((PCRE2_UCHAR8 *)ptr); @@ -149,14 +149,13 @@ static void * DetectMarkParse (const char *rawstr) SCLogError("Numeric value out of range"); pcre2_substring_free((PCRE2_UCHAR8 *)ptr); goto error; - } /* If there is no numeric value in the given string then strtoull(), makes - endptr equals to ptr and return 0 as result */ + } /* If there is no numeric value in the given string then strtoull(), makes + endptr equals to ptr and return 0 as result */ else if (endptr == ptr && mask == 0) { SCLogError("No numeric value"); pcre2_substring_free((PCRE2_UCHAR8 *)ptr); goto error; - } - else if (endptr == ptr) { + } else if (endptr == ptr) { SCLogError("Invalid numeric value"); pcre2_substring_free((PCRE2_UCHAR8 *)ptr); goto error; @@ -194,7 +193,7 @@ static void * DetectMarkParse (const char *rawstr) * \retval 0 on Success * \retval -1 on Failure */ -static int DetectMarkSetup (DetectEngineCtx *de_ctx, Signature *s, const char *rawstr) +static int DetectMarkSetup(DetectEngineCtx *de_ctx, Signature *s, const char *rawstr) { #ifndef NFQ return 0; @@ -221,17 +220,15 @@ void DetectMarkDataFree(DetectEngineCtx *de_ctx, void *ptr) SCFree(data); } - -static int DetectMarkPacket(DetectEngineThreadCtx *det_ctx, Packet *p, - const Signature *s, const SigMatchCtx *ctx) +static int DetectMarkPacket( + DetectEngineThreadCtx *det_ctx, Packet *p, const Signature *s, const SigMatchCtx *ctx) { #ifdef NFQ const DetectMarkData *nf_data = (const DetectMarkData *)ctx; if (nf_data->mask) { if (!(IS_TUNNEL_PKT(p))) { /* coverity[missing_lock] */ - p->nfq_v.mark = (nf_data->mark & nf_data->mask) - | (p->nfq_v.mark & ~(nf_data->mask)); + p->nfq_v.mark = (nf_data->mark & nf_data->mask) | (p->nfq_v.mark & ~(nf_data->mask)); p->flags |= PKT_MARK_MODIFIED; } else { /* real tunnels may have multiple flows inside them, so marking @@ -240,8 +237,8 @@ static int DetectMarkPacket(DetectEngineThreadCtx *det_ctx, Packet *p, if (p->flags & PKT_REBUILT_FRAGMENT) { Packet *tp = p->root ? p->root : p; SCSpinLock(&tp->persistent.tunnel_lock); - tp->nfq_v.mark = (nf_data->mark & nf_data->mask) - | (tp->nfq_v.mark & ~(nf_data->mask)); + tp->nfq_v.mark = + (nf_data->mark & nf_data->mask) | (tp->nfq_v.mark & ~(nf_data->mask)); tp->flags |= PKT_MARK_MODIFIED; SCSpinUnlock(&tp->persistent.tunnel_lock); } @@ -260,7 +257,7 @@ static int DetectMarkPacket(DetectEngineThreadCtx *det_ctx, Packet *p, * \test MarkTestParse01 is a test for a valid mark value * */ -static int MarkTestParse01 (void) +static int MarkTestParse01(void) { DetectMarkData *data; @@ -276,7 +273,7 @@ static int MarkTestParse01 (void) * \test MarkTestParse02 is a test for an invalid mark value * */ -static int MarkTestParse02 (void) +static int MarkTestParse02(void) { DetectMarkData *data; @@ -292,7 +289,7 @@ static int MarkTestParse02 (void) * \test MarkTestParse03 is a test for a valid mark value * */ -static int MarkTestParse03 (void) +static int MarkTestParse03(void) { DetectMarkData *data; @@ -308,7 +305,7 @@ static int MarkTestParse03 (void) * \test MarkTestParse04 is a test for a invalid mark value * */ -static int MarkTestParse04 (void) +static int MarkTestParse04(void) { DetectMarkData *data; diff --git a/src/detect-mark.h b/src/detect-mark.h index b8de378fd20d..f97299b5fff0 100644 --- a/src/detect-mark.h +++ b/src/detect-mark.h @@ -28,7 +28,6 @@ #ifndef __DETECT_MARK_H__ #define __DETECT_MARK_H__ - /** * \struct DetectMarkData_ * DetectMarkData_ is used to store nfq_set_mark: input value @@ -40,14 +39,14 @@ */ typedef struct DetectMarkData_ { - uint32_t mark; /**< Rule mark */ - uint32_t mask; /**< Rule mask */ + uint32_t mark; /**< Rule mark */ + uint32_t mask; /**< Rule mask */ } DetectMarkData; /** * Registration function for nfq_set_mark: keyword */ -void DetectMarkRegister (void); +void DetectMarkRegister(void); #endif /*__DETECT_MARK_H__ */ diff --git a/src/detect-metadata.c b/src/detect-metadata.c index 6c6c8de7ff72..653a6d441f46 100644 --- a/src/detect-metadata.c +++ b/src/detect-metadata.c @@ -36,19 +36,19 @@ #include "rust.h" #include "util-validate.h" -static int DetectMetadataSetup (DetectEngineCtx *, Signature *, const char *); +static int DetectMetadataSetup(DetectEngineCtx *, Signature *, const char *); #ifdef UNITTESTS static void DetectMetadataRegisterTests(void); #endif -void DetectMetadataRegister (void) +void DetectMetadataRegister(void) { sigmatch_table[DETECT_METADATA].name = "metadata"; sigmatch_table[DETECT_METADATA].desc = "used for logging"; sigmatch_table[DETECT_METADATA].url = "/rules/meta.html#metadata"; sigmatch_table[DETECT_METADATA].Match = NULL; sigmatch_table[DETECT_METADATA].Setup = DetectMetadataSetup; - sigmatch_table[DETECT_METADATA].Free = NULL; + sigmatch_table[DETECT_METADATA].Free = NULL; #ifdef UNITTESTS sigmatch_table[DETECT_METADATA].RegisterTests = DetectMetadataRegisterTests; #endif @@ -68,10 +68,11 @@ void DetectMetadataFree(DetectMetadata *mdata) int DetectMetadataHashInit(DetectEngineCtx *de_ctx) { - if (! DetectEngineMustParseMetadata()) + if (!DetectEngineMustParseMetadata()) return 0; - de_ctx->metadata_table = HashTableInit(4096, StringHashFunc, StringHashCompareFunc, StringHashFreeFunc); + de_ctx->metadata_table = + HashTableInit(4096, StringHashFunc, StringHashCompareFunc, StringHashFreeFunc); if (de_ctx->metadata_table == NULL) return -1; return 0; @@ -159,7 +160,7 @@ static char *CraftPreformattedJSON(const DetectMetadata *head) jb_close(js); /* we have a complete json builder. Now store it as a C string */ const size_t len = jb_len(js); -#define MD_STR "\"metadata\":" +#define MD_STR "\"metadata\":" #define MD_STR_LEN (sizeof(MD_STR) - 1) char *str = SCMalloc(len + MD_STR_LEN + 1); if (str == NULL) { @@ -181,7 +182,7 @@ static char *CraftPreformattedJSON(const DetectMetadata *head) static int DetectMetadataParse(DetectEngineCtx *de_ctx, Signature *s, const char *metadatastr) { DetectMetadata *head = s->metadata ? s->metadata->list : NULL; - char copy[strlen(metadatastr)+1]; + char copy[strlen(metadatastr) + 1]; strlcpy(copy, metadatastr, sizeof(copy)); char *xsaveptr = NULL; char *key = strtok_r(copy, ",", &xsaveptr); @@ -235,7 +236,7 @@ static int DetectMetadataParse(DetectEngineCtx *de_ctx, Signature *s, const char if (s->metadata == NULL) { s->metadata = SCCalloc(1, sizeof(*s->metadata)); if (s->metadata == NULL) { - for (DetectMetadata *m = head; m != NULL; ) { + for (DetectMetadata *m = head; m != NULL;) { DetectMetadata *next_m = m->next; DetectMetadataFree(m); m = next_m; @@ -267,11 +268,10 @@ static int DetectMetadataParseTest01(void) DetectEngineCtx *de_ctx = DetectEngineCtxInit(); FAIL_IF_NULL(de_ctx); - Signature *sig = DetectEngineAppendSig(de_ctx, - "alert tcp any any -> any any " - "(metadata: toto 1; sid:1; rev:1;)"); + Signature *sig = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any " + "(metadata: toto 1; sid:1; rev:1;)"); FAIL_IF_NULL(sig); - FAIL_IF(sig->metadata); + FAIL_IF(sig->metadata); DetectEngineCtxFree(de_ctx); PASS; @@ -282,25 +282,24 @@ static int DetectMetadataParseTest02(void) DetectEngineSetParseMetadata(); DetectEngineCtx *de_ctx = DetectEngineCtxInit(); FAIL_IF_NULL(de_ctx); - Signature *sig = DetectEngineAppendSig(de_ctx, - "alert tcp any any -> any any " - "(metadata: toto 1; " - "metadata: titi 2, jaivu gros_minet;" - "sid:1; rev:1;)"); + Signature *sig = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any " + "(metadata: toto 1; " + "metadata: titi 2, jaivu gros_minet;" + "sid:1; rev:1;)"); FAIL_IF_NULL(sig); - FAIL_IF_NULL(sig->metadata); - FAIL_IF_NULL(sig->metadata->list); - FAIL_IF_NULL(sig->metadata->list->key); + FAIL_IF_NULL(sig->metadata); + FAIL_IF_NULL(sig->metadata->list); + FAIL_IF_NULL(sig->metadata->list->key); FAIL_IF(strcmp("jaivu", sig->metadata->list->key)); FAIL_IF(strcmp("gros_minet", sig->metadata->list->value)); - FAIL_IF_NULL(sig->metadata->list->next); + FAIL_IF_NULL(sig->metadata->list->next); DetectMetadata *dm = sig->metadata->list->next; FAIL_IF(strcmp("titi", dm->key)); dm = dm->next; FAIL_IF_NULL(dm); FAIL_IF(strcmp("toto", dm->key)); - FAIL_IF_NOT(strcmp(sig->metadata->json_str, - "\"metadata\":{\"jaivu\":[\"gros_minet\"],\"titi\":[\"2\"],\"toto\":[\"1\"]}") == 0); + FAIL_IF_NOT(strcmp(sig->metadata->json_str, "\"metadata\":{\"jaivu\":[\"gros_minet\"],\"titi\":" + "[\"2\"],\"toto\":[\"1\"]}") == 0); DetectEngineCtxFree(de_ctx); PASS; } diff --git a/src/detect-metadata.h b/src/detect-metadata.h index fafa63f5ae80..c0b0663a4ea4 100644 --- a/src/detect-metadata.h +++ b/src/detect-metadata.h @@ -42,9 +42,8 @@ typedef struct DetectMetadataHead { } DetectMetadataHead; /* prototypes */ -void DetectMetadataRegister (void); +void DetectMetadataRegister(void); void DetectMetadataFree(DetectMetadata *mdata); #endif /* __DETECT_METADATA_H__ */ - diff --git a/src/detect-modbus.c b/src/detect-modbus.c index f4e6d4fd03ff..a596ab1110b1 100644 --- a/src/detect-modbus.c +++ b/src/detect-modbus.c @@ -63,7 +63,8 @@ static int g_modbus_buffer_id = 0; * * \param ptr pointer to DetectModbus */ -static void DetectModbusFree(DetectEngineCtx *de_ctx, void *ptr) { +static void DetectModbusFree(DetectEngineCtx *de_ctx, void *ptr) +{ SCEnter(); if (ptr != NULL) { rs_modbus_free(ptr); diff --git a/src/detect-mqtt-connack-sessionpresent.c b/src/detect-mqtt-connack-sessionpresent.c index 4b29158b1f89..245d44c9a031 100644 --- a/src/detect-mqtt-connack-sessionpresent.c +++ b/src/detect-mqtt-connack-sessionpresent.c @@ -37,27 +37,31 @@ static DetectParseRegex parse_regex; static int mqtt_connack_session_present_id = 0; -static int DetectMQTTConnackSessionPresentMatch(DetectEngineThreadCtx *det_ctx, - Flow *f, uint8_t flags, void *state, - void *txv, const Signature *s, - const SigMatchCtx *ctx); -static int DetectMQTTConnackSessionPresentSetup (DetectEngineCtx *, Signature *, const char *); +static int DetectMQTTConnackSessionPresentMatch(DetectEngineThreadCtx *det_ctx, Flow *f, + uint8_t flags, void *state, void *txv, const Signature *s, const SigMatchCtx *ctx); +static int DetectMQTTConnackSessionPresentSetup(DetectEngineCtx *, Signature *, const char *); void MQTTConnackSessionPresentRegisterTests(void); void DetectMQTTConnackSessionPresentFree(DetectEngineCtx *de_ctx, void *); /** * \brief Registration function for mqtt.connack.session_present: keyword */ -void DetectMQTTConnackSessionPresentRegister (void) +void DetectMQTTConnackSessionPresentRegister(void) { sigmatch_table[DETECT_AL_MQTT_CONNACK_SESSION_PRESENT].name = "mqtt.connack.session_present"; - sigmatch_table[DETECT_AL_MQTT_CONNACK_SESSION_PRESENT].desc = "match MQTT CONNACK session present flag"; - sigmatch_table[DETECT_AL_MQTT_CONNACK_SESSION_PRESENT].url = "/rules/mqtt-keywords.html#mqtt-connack-session-present"; - sigmatch_table[DETECT_AL_MQTT_CONNACK_SESSION_PRESENT].AppLayerTxMatch = DetectMQTTConnackSessionPresentMatch; - sigmatch_table[DETECT_AL_MQTT_CONNACK_SESSION_PRESENT].Setup = DetectMQTTConnackSessionPresentSetup; - sigmatch_table[DETECT_AL_MQTT_CONNACK_SESSION_PRESENT].Free = DetectMQTTConnackSessionPresentFree; + sigmatch_table[DETECT_AL_MQTT_CONNACK_SESSION_PRESENT].desc = + "match MQTT CONNACK session present flag"; + sigmatch_table[DETECT_AL_MQTT_CONNACK_SESSION_PRESENT].url = + "/rules/mqtt-keywords.html#mqtt-connack-session-present"; + sigmatch_table[DETECT_AL_MQTT_CONNACK_SESSION_PRESENT].AppLayerTxMatch = + DetectMQTTConnackSessionPresentMatch; + sigmatch_table[DETECT_AL_MQTT_CONNACK_SESSION_PRESENT].Setup = + DetectMQTTConnackSessionPresentSetup; + sigmatch_table[DETECT_AL_MQTT_CONNACK_SESSION_PRESENT].Free = + DetectMQTTConnackSessionPresentFree; #ifdef UNITTESTS - sigmatch_table[DETECT_AL_MQTT_CONNACK_SESSION_PRESENT].RegisterTests = MQTTConnackSessionPresentRegisterTests; + sigmatch_table[DETECT_AL_MQTT_CONNACK_SESSION_PRESENT].RegisterTests = + MQTTConnackSessionPresentRegisterTests; #endif DetectSetupParseRegexes(PARSE_REGEX, &parse_regex); @@ -78,15 +82,14 @@ void DetectMQTTConnackSessionPresentRegister (void) * \param state App layer state. * \param txv Pointer to the transaction. * \param s Pointer to the Signature. - * \param ctx Pointer to the sigmatch that we will cast into DetectMQTTConnackSessionPresentData. + * \param ctx Pointer to the sigmatch that we will cast into + * DetectMQTTConnackSessionPresentData. * * \retval 0 no match. * \retval 1 match. */ -static int DetectMQTTConnackSessionPresentMatch(DetectEngineThreadCtx *det_ctx, - Flow *f, uint8_t flags, void *state, - void *txv, const Signature *s, - const SigMatchCtx *ctx) +static int DetectMQTTConnackSessionPresentMatch(DetectEngineThreadCtx *det_ctx, Flow *f, + uint8_t flags, void *state, void *txv, const Signature *s, const SigMatchCtx *ctx) { const bool *de = (const bool *)ctx; bool value = false; @@ -94,7 +97,7 @@ static int DetectMQTTConnackSessionPresentMatch(DetectEngineThreadCtx *det_ctx, if (!de) return 0; - if (rs_mqtt_tx_get_connack_sessionpresent(txv, &value) ==0 ) { + if (rs_mqtt_tx_get_connack_sessionpresent(txv, &value) == 0) { return 0; } if (value != *de) { @@ -153,7 +156,8 @@ static bool *DetectMQTTConnackSessionPresentParse(const char *rawstr) * \retval 0 on Success * \retval -1 on Failure */ -static int DetectMQTTConnackSessionPresentSetup (DetectEngineCtx *de_ctx, Signature *s, const char *rawstr) +static int DetectMQTTConnackSessionPresentSetup( + DetectEngineCtx *de_ctx, Signature *s, const char *rawstr) { bool *de = NULL; @@ -200,7 +204,7 @@ void DetectMQTTConnackSessionPresentFree(DetectEngineCtx *de_ctx, void *de_ptr) * \retval 1 on success * \retval 0 on failure */ -static int MQTTConnackSessionPresentTestParse01 (void) +static int MQTTConnackSessionPresentTestParse01(void) { bool *de = NULL; @@ -229,7 +233,7 @@ static int MQTTConnackSessionPresentTestParse01 (void) * \retval 1 on success * \retval 0 on failure */ -static int MQTTConnackSessionPresentTestParse02 (void) +static int MQTTConnackSessionPresentTestParse02(void) { bool *de = NULL; de = DetectMQTTConnackSessionPresentParse("nix"); @@ -247,7 +251,7 @@ static int MQTTConnackSessionPresentTestParse02 (void) * \retval 1 on success * \retval 0 on failure */ -static int MQTTConnackSessionPresentTestParse03 (void) +static int MQTTConnackSessionPresentTestParse03(void) { bool *de = NULL; de = DetectMQTTConnackSessionPresentParse(""); @@ -265,7 +269,7 @@ static int MQTTConnackSessionPresentTestParse03 (void) * \retval 1 on success * \retval 0 on failure */ -static int MQTTConnackSessionPresentTestParse04 (void) +static int MQTTConnackSessionPresentTestParse04(void) { bool *de = NULL; de = DetectMQTTConnackSessionPresentParse(","); @@ -277,7 +281,6 @@ static int MQTTConnackSessionPresentTestParse04 (void) PASS; } - #endif /* UNITTESTS */ /** diff --git a/src/detect-mqtt-connect-clientid.c b/src/detect-mqtt-connect-clientid.c index 1acebf9943bc..8d2accbf137e 100644 --- a/src/detect-mqtt-connect-clientid.c +++ b/src/detect-mqtt-connect-clientid.c @@ -49,9 +49,8 @@ static int DetectMQTTConnectClientIDSetup(DetectEngineCtx *de_ctx, Signature *s, } static InspectionBuffer *GetData(DetectEngineThreadCtx *det_ctx, - const DetectEngineTransforms *transforms, - Flow *_f, const uint8_t _flow_flags, - void *txv, const int list_id) + const DetectEngineTransforms *transforms, Flow *_f, const uint8_t _flow_flags, void *txv, + const int list_id) { InspectionBuffer *buffer = InspectionBufferGet(det_ctx, list_id); if (buffer->inspect == NULL) { @@ -73,18 +72,17 @@ void DetectMQTTConnectClientIDRegister(void) { /* mqtt.connect.clientid sticky buffer */ sigmatch_table[DETECT_AL_MQTT_CONNECT_CLIENTID].name = KEYWORD_NAME; - sigmatch_table[DETECT_AL_MQTT_CONNECT_CLIENTID].desc = "sticky buffer to match on the MQTT CONNECT client ID"; + sigmatch_table[DETECT_AL_MQTT_CONNECT_CLIENTID].desc = + "sticky buffer to match on the MQTT CONNECT client ID"; sigmatch_table[DETECT_AL_MQTT_CONNECT_CLIENTID].url = "/rules/" KEYWORD_DOC; sigmatch_table[DETECT_AL_MQTT_CONNECT_CLIENTID].Setup = DetectMQTTConnectClientIDSetup; sigmatch_table[DETECT_AL_MQTT_CONNECT_CLIENTID].flags |= SIGMATCH_NOOPT; - DetectAppLayerInspectEngineRegister2(BUFFER_NAME, ALPROTO_MQTT, - SIG_FLAG_TOSERVER, 0, + DetectAppLayerInspectEngineRegister2(BUFFER_NAME, ALPROTO_MQTT, SIG_FLAG_TOSERVER, 0, DetectEngineInspectBufferGeneric, GetData); - DetectAppLayerMpmRegister2(BUFFER_NAME, SIG_FLAG_TOSERVER, 2, - PrefilterGenericMpmRegister, GetData, ALPROTO_MQTT, - 1); + DetectAppLayerMpmRegister2(BUFFER_NAME, SIG_FLAG_TOSERVER, 2, PrefilterGenericMpmRegister, + GetData, ALPROTO_MQTT, 1); DetectBufferTypeSetDescriptionByName(BUFFER_NAME, BUFFER_DESC); diff --git a/src/detect-mqtt-connect-flags.c b/src/detect-mqtt-connect-flags.c index ce543ecdaa41..688d1b5045ea 100644 --- a/src/detect-mqtt-connect-flags.c +++ b/src/detect-mqtt-connect-flags.c @@ -37,33 +37,28 @@ static DetectParseRegex parse_regex; static int mqtt_connect_flags_id = 0; -static int DetectMQTTConnectFlagsMatch(DetectEngineThreadCtx *det_ctx, - Flow *f, uint8_t flags, void *state, - void *txv, const Signature *s, - const SigMatchCtx *ctx); -static int DetectMQTTConnectFlagsSetup (DetectEngineCtx *, Signature *, const char *); +static int DetectMQTTConnectFlagsMatch(DetectEngineThreadCtx *det_ctx, Flow *f, uint8_t flags, + void *state, void *txv, const Signature *s, const SigMatchCtx *ctx); +static int DetectMQTTConnectFlagsSetup(DetectEngineCtx *, Signature *, const char *); void MQTTConnectFlagsRegisterTests(void); void DetectMQTTConnectFlagsFree(DetectEngineCtx *de_ctx, void *); typedef struct DetectMQTTConnectFlagsData_ { - MQTTFlagState username, - password, - will, - will_retain, - clean_session; + MQTTFlagState username, password, will, will_retain, clean_session; } DetectMQTTConnectFlagsData; /** * \brief Registration function for mqtt.connect.flags: keyword */ -void DetectMQTTConnectFlagsRegister (void) +void DetectMQTTConnectFlagsRegister(void) { sigmatch_table[DETECT_AL_MQTT_CONNECT_FLAGS].name = "mqtt.connect.flags"; sigmatch_table[DETECT_AL_MQTT_CONNECT_FLAGS].desc = "match MQTT CONNECT variable header flags"; - sigmatch_table[DETECT_AL_MQTT_CONNECT_FLAGS].url = "/rules/mqtt-keywords.html#mqtt-connect-flags"; + sigmatch_table[DETECT_AL_MQTT_CONNECT_FLAGS].url = + "/rules/mqtt-keywords.html#mqtt-connect-flags"; sigmatch_table[DETECT_AL_MQTT_CONNECT_FLAGS].AppLayerTxMatch = DetectMQTTConnectFlagsMatch; sigmatch_table[DETECT_AL_MQTT_CONNECT_FLAGS].Setup = DetectMQTTConnectFlagsSetup; - sigmatch_table[DETECT_AL_MQTT_CONNECT_FLAGS].Free = DetectMQTTConnectFlagsFree; + sigmatch_table[DETECT_AL_MQTT_CONNECT_FLAGS].Free = DetectMQTTConnectFlagsFree; #ifdef UNITTESTS sigmatch_table[DETECT_AL_MQTT_CONNECT_FLAGS].RegisterTests = MQTTConnectFlagsRegisterTests; #endif @@ -91,19 +86,17 @@ void DetectMQTTConnectFlagsRegister (void) * \retval 0 no match. * \retval 1 match. */ -static int DetectMQTTConnectFlagsMatch(DetectEngineThreadCtx *det_ctx, - Flow *f, uint8_t flags, void *state, - void *txv, const Signature *s, - const SigMatchCtx *ctx) +static int DetectMQTTConnectFlagsMatch(DetectEngineThreadCtx *det_ctx, Flow *f, uint8_t flags, + void *state, void *txv, const Signature *s, const SigMatchCtx *ctx) { const DetectMQTTConnectFlagsData *de = (const DetectMQTTConnectFlagsData *)ctx; if (!de) return 0; - return rs_mqtt_tx_has_connect_flags(txv, de->username, de->password, de->will, - de->will_retain, de->clean_session); - } + return rs_mqtt_tx_has_connect_flags( + txv, de->username, de->password, de->will, de->will_retain, de->clean_session); +} /** * \internal @@ -142,39 +135,39 @@ static DetectMQTTConnectFlagsData *DetectMQTTConnectFlagsParse(const char *rawst if (strlen(flagv) < 2) { SCLogError("malformed flag value: %s", flagv); goto error; - } else { + } else { int offset = 0; MQTTFlagState fs_to_set = MQTT_MUST_BE_SET; if (flagv[0] == '!') { /* negated flag */ - offset = 1; /* skip negation operator during comparison */ + offset = 1; /* skip negation operator during comparison */ fs_to_set = MQTT_CANT_BE_SET; } - if (strcmp(flagv+offset, "username") == 0) { + if (strcmp(flagv + offset, "username") == 0) { if (de->username != MQTT_DONT_CARE) { SCLogError("duplicate flag definition: %s", flagv); goto error; } de->username = fs_to_set; - } else if (strcmp(flagv+offset, "password") == 0) { + } else if (strcmp(flagv + offset, "password") == 0) { if (de->password != MQTT_DONT_CARE) { SCLogError("duplicate flag definition: %s", flagv); goto error; } de->password = fs_to_set; - } else if (strcmp(flagv+offset, "will") == 0) { + } else if (strcmp(flagv + offset, "will") == 0) { if (de->will != MQTT_DONT_CARE) { SCLogError("duplicate flag definition: %s", flagv); goto error; } de->will = fs_to_set; - } else if (strcmp(flagv+offset, "will_retain") == 0) { + } else if (strcmp(flagv + offset, "will_retain") == 0) { if (de->will_retain != MQTT_DONT_CARE) { SCLogError("duplicate flag definition: %s", flagv); goto error; } de->will_retain = fs_to_set; - } else if (strcmp(flagv+offset, "clean_session") == 0) { + } else if (strcmp(flagv + offset, "clean_session") == 0) { if (de->clean_session != MQTT_DONT_CARE) { SCLogError("duplicate flag definition: %s", flagv); goto error; @@ -258,7 +251,7 @@ void DetectMQTTConnectFlagsFree(DetectEngineCtx *de_ctx, void *de_ptr) * \retval 1 on success * \retval 0 on failure */ -static int MQTTConnectFlagsTestParse01 (void) +static int MQTTConnectFlagsTestParse01(void) { DetectMQTTConnectFlagsData *de = NULL; de = DetectMQTTConnectFlagsParse("username"); @@ -286,7 +279,7 @@ static int MQTTConnectFlagsTestParse01 (void) * \retval 1 on success * \retval 0 on failure */ -static int MQTTConnectFlagsTestParse02 (void) +static int MQTTConnectFlagsTestParse02(void) { DetectMQTTConnectFlagsData *de = NULL; de = DetectMQTTConnectFlagsParse("foobar"); @@ -304,7 +297,7 @@ static int MQTTConnectFlagsTestParse02 (void) * \retval 1 on success * \retval 0 on failure */ -static int MQTTConnectFlagsTestParse03 (void) +static int MQTTConnectFlagsTestParse03(void) { DetectMQTTConnectFlagsData *de = NULL; de = DetectMQTTConnectFlagsParse("will,!"); @@ -322,7 +315,7 @@ static int MQTTConnectFlagsTestParse03 (void) * \retval 1 on success * \retval 0 on failure */ -static int MQTTConnectFlagsTestParse04 (void) +static int MQTTConnectFlagsTestParse04(void) { DetectMQTTConnectFlagsData *de = NULL; de = DetectMQTTConnectFlagsParse(""); @@ -340,7 +333,7 @@ static int MQTTConnectFlagsTestParse04 (void) * \retval 1 on success * \retval 0 on failure */ -static int MQTTConnectFlagsTestParse05 (void) +static int MQTTConnectFlagsTestParse05(void) { DetectMQTTConnectFlagsData *de = NULL; de = DetectMQTTConnectFlagsParse("username, username"); @@ -367,7 +360,6 @@ static int MQTTConnectFlagsTestParse05 (void) PASS; } - #endif /* UNITTESTS */ /** diff --git a/src/detect-mqtt-connect-password.c b/src/detect-mqtt-connect-password.c index c08390748fe0..25d3f539f8aa 100644 --- a/src/detect-mqtt-connect-password.c +++ b/src/detect-mqtt-connect-password.c @@ -49,9 +49,8 @@ static int DetectMQTTConnectPasswordSetup(DetectEngineCtx *de_ctx, Signature *s, } static InspectionBuffer *GetData(DetectEngineThreadCtx *det_ctx, - const DetectEngineTransforms *transforms, - Flow *_f, const uint8_t _flow_flags, - void *txv, const int list_id) + const DetectEngineTransforms *transforms, Flow *_f, const uint8_t _flow_flags, void *txv, + const int list_id) { InspectionBuffer *buffer = InspectionBufferGet(det_ctx, list_id); if (buffer->inspect == NULL) { @@ -73,18 +72,17 @@ void DetectMQTTConnectPasswordRegister(void) { /* mqtt.connect.password sticky buffer */ sigmatch_table[DETECT_AL_MQTT_CONNECT_PASSWORD].name = KEYWORD_NAME; - sigmatch_table[DETECT_AL_MQTT_CONNECT_PASSWORD].desc = "sticky buffer to match on the MQTT CONNECT password"; + sigmatch_table[DETECT_AL_MQTT_CONNECT_PASSWORD].desc = + "sticky buffer to match on the MQTT CONNECT password"; sigmatch_table[DETECT_AL_MQTT_CONNECT_PASSWORD].url = "/rules/" KEYWORD_DOC; sigmatch_table[DETECT_AL_MQTT_CONNECT_PASSWORD].Setup = DetectMQTTConnectPasswordSetup; sigmatch_table[DETECT_AL_MQTT_CONNECT_PASSWORD].flags |= SIGMATCH_NOOPT; - DetectAppLayerInspectEngineRegister2(BUFFER_NAME, ALPROTO_MQTT, - SIG_FLAG_TOSERVER, 0, + DetectAppLayerInspectEngineRegister2(BUFFER_NAME, ALPROTO_MQTT, SIG_FLAG_TOSERVER, 0, DetectEngineInspectBufferGeneric, GetData); - DetectAppLayerMpmRegister2(BUFFER_NAME, SIG_FLAG_TOSERVER, 2, - PrefilterGenericMpmRegister, GetData, ALPROTO_MQTT, - 1); + DetectAppLayerMpmRegister2(BUFFER_NAME, SIG_FLAG_TOSERVER, 2, PrefilterGenericMpmRegister, + GetData, ALPROTO_MQTT, 1); DetectBufferTypeSetDescriptionByName(BUFFER_NAME, BUFFER_DESC); diff --git a/src/detect-mqtt-connect-username.c b/src/detect-mqtt-connect-username.c index dbc772d22058..d648b130f635 100644 --- a/src/detect-mqtt-connect-username.c +++ b/src/detect-mqtt-connect-username.c @@ -49,9 +49,8 @@ static int DetectMQTTConnectUsernameSetup(DetectEngineCtx *de_ctx, Signature *s, } static InspectionBuffer *GetData(DetectEngineThreadCtx *det_ctx, - const DetectEngineTransforms *transforms, - Flow *_f, const uint8_t _flow_flags, - void *txv, const int list_id) + const DetectEngineTransforms *transforms, Flow *_f, const uint8_t _flow_flags, void *txv, + const int list_id) { InspectionBuffer *buffer = InspectionBufferGet(det_ctx, list_id); if (buffer->inspect == NULL) { @@ -73,18 +72,17 @@ void DetectMQTTConnectUsernameRegister(void) { /* mqtt.connect.username sticky buffer */ sigmatch_table[DETECT_AL_MQTT_CONNECT_USERNAME].name = KEYWORD_NAME; - sigmatch_table[DETECT_AL_MQTT_CONNECT_USERNAME].desc = "sticky buffer to match on the MQTT CONNECT username"; + sigmatch_table[DETECT_AL_MQTT_CONNECT_USERNAME].desc = + "sticky buffer to match on the MQTT CONNECT username"; sigmatch_table[DETECT_AL_MQTT_CONNECT_USERNAME].url = "/rules/" KEYWORD_DOC; sigmatch_table[DETECT_AL_MQTT_CONNECT_USERNAME].Setup = DetectMQTTConnectUsernameSetup; sigmatch_table[DETECT_AL_MQTT_CONNECT_USERNAME].flags |= SIGMATCH_NOOPT; - DetectAppLayerInspectEngineRegister2(BUFFER_NAME, ALPROTO_MQTT, - SIG_FLAG_TOSERVER, 0, + DetectAppLayerInspectEngineRegister2(BUFFER_NAME, ALPROTO_MQTT, SIG_FLAG_TOSERVER, 0, DetectEngineInspectBufferGeneric, GetData); - DetectAppLayerMpmRegister2(BUFFER_NAME, SIG_FLAG_TOSERVER, 2, - PrefilterGenericMpmRegister, GetData, ALPROTO_MQTT, - 1); + DetectAppLayerMpmRegister2(BUFFER_NAME, SIG_FLAG_TOSERVER, 2, PrefilterGenericMpmRegister, + GetData, ALPROTO_MQTT, 1); DetectBufferTypeSetDescriptionByName(BUFFER_NAME, BUFFER_DESC); diff --git a/src/detect-mqtt-connect-willmessage.c b/src/detect-mqtt-connect-willmessage.c index 48d851d3209e..32e5ac0696ac 100644 --- a/src/detect-mqtt-connect-willmessage.c +++ b/src/detect-mqtt-connect-willmessage.c @@ -49,9 +49,8 @@ static int DetectMQTTConnectWillMessageSetup(DetectEngineCtx *de_ctx, Signature } static InspectionBuffer *GetData(DetectEngineThreadCtx *det_ctx, - const DetectEngineTransforms *transforms, - Flow *_f, const uint8_t _flow_flags, - void *txv, const int list_id) + const DetectEngineTransforms *transforms, Flow *_f, const uint8_t _flow_flags, void *txv, + const int list_id) { InspectionBuffer *buffer = InspectionBufferGet(det_ctx, list_id); if (buffer->inspect == NULL) { @@ -73,18 +72,17 @@ void DetectMQTTConnectWillMessageRegister(void) { /* mqtt.connect.willmessage sticky buffer */ sigmatch_table[DETECT_AL_MQTT_CONNECT_WILLMESSAGE].name = KEYWORD_NAME; - sigmatch_table[DETECT_AL_MQTT_CONNECT_WILLMESSAGE].desc = "sticky buffer to match on the MQTT CONNECT will message"; + sigmatch_table[DETECT_AL_MQTT_CONNECT_WILLMESSAGE].desc = + "sticky buffer to match on the MQTT CONNECT will message"; sigmatch_table[DETECT_AL_MQTT_CONNECT_WILLMESSAGE].url = "/rules/" KEYWORD_DOC; sigmatch_table[DETECT_AL_MQTT_CONNECT_WILLMESSAGE].Setup = DetectMQTTConnectWillMessageSetup; sigmatch_table[DETECT_AL_MQTT_CONNECT_WILLMESSAGE].flags |= SIGMATCH_NOOPT; - DetectAppLayerInspectEngineRegister2(BUFFER_NAME, ALPROTO_MQTT, - SIG_FLAG_TOSERVER, 0, + DetectAppLayerInspectEngineRegister2(BUFFER_NAME, ALPROTO_MQTT, SIG_FLAG_TOSERVER, 0, DetectEngineInspectBufferGeneric, GetData); - DetectAppLayerMpmRegister2(BUFFER_NAME, SIG_FLAG_TOSERVER, 2, - PrefilterGenericMpmRegister, GetData, ALPROTO_MQTT, - 1); + DetectAppLayerMpmRegister2(BUFFER_NAME, SIG_FLAG_TOSERVER, 2, PrefilterGenericMpmRegister, + GetData, ALPROTO_MQTT, 1); DetectBufferTypeSetDescriptionByName(BUFFER_NAME, BUFFER_DESC); diff --git a/src/detect-mqtt-connect-willtopic.c b/src/detect-mqtt-connect-willtopic.c index da3d2640dd96..25cbadd8fca9 100644 --- a/src/detect-mqtt-connect-willtopic.c +++ b/src/detect-mqtt-connect-willtopic.c @@ -49,9 +49,8 @@ static int DetectMQTTConnectWillTopicSetup(DetectEngineCtx *de_ctx, Signature *s } static InspectionBuffer *GetData(DetectEngineThreadCtx *det_ctx, - const DetectEngineTransforms *transforms, - Flow *_f, const uint8_t _flow_flags, - void *txv, const int list_id) + const DetectEngineTransforms *transforms, Flow *_f, const uint8_t _flow_flags, void *txv, + const int list_id) { InspectionBuffer *buffer = InspectionBufferGet(det_ctx, list_id); if (buffer->inspect == NULL) { @@ -73,18 +72,17 @@ void DetectMQTTConnectWillTopicRegister(void) { /* mqtt.connect.willtopic sticky buffer */ sigmatch_table[DETECT_AL_MQTT_CONNECT_WILLTOPIC].name = KEYWORD_NAME; - sigmatch_table[DETECT_AL_MQTT_CONNECT_WILLTOPIC].desc = "sticky buffer to match on the MQTT CONNECT will topic"; + sigmatch_table[DETECT_AL_MQTT_CONNECT_WILLTOPIC].desc = + "sticky buffer to match on the MQTT CONNECT will topic"; sigmatch_table[DETECT_AL_MQTT_CONNECT_WILLTOPIC].url = "/rules/" KEYWORD_DOC; sigmatch_table[DETECT_AL_MQTT_CONNECT_WILLTOPIC].Setup = DetectMQTTConnectWillTopicSetup; sigmatch_table[DETECT_AL_MQTT_CONNECT_WILLTOPIC].flags |= SIGMATCH_NOOPT; - DetectAppLayerInspectEngineRegister2(BUFFER_NAME, ALPROTO_MQTT, - SIG_FLAG_TOSERVER, 0, + DetectAppLayerInspectEngineRegister2(BUFFER_NAME, ALPROTO_MQTT, SIG_FLAG_TOSERVER, 0, DetectEngineInspectBufferGeneric, GetData); - DetectAppLayerMpmRegister2(BUFFER_NAME, SIG_FLAG_TOSERVER, 2, - PrefilterGenericMpmRegister, GetData, ALPROTO_MQTT, - 1); + DetectAppLayerMpmRegister2(BUFFER_NAME, SIG_FLAG_TOSERVER, 2, PrefilterGenericMpmRegister, + GetData, ALPROTO_MQTT, 1); DetectBufferTypeSetDescriptionByName(BUFFER_NAME, BUFFER_DESC); diff --git a/src/detect-mqtt-flags.c b/src/detect-mqtt-flags.c index d0614061416d..8c001aa83b3e 100644 --- a/src/detect-mqtt-flags.c +++ b/src/detect-mqtt-flags.c @@ -37,11 +37,9 @@ static DetectParseRegex parse_regex; static int mqtt_flags_id = 0; -static int DetectMQTTFlagsMatch(DetectEngineThreadCtx *det_ctx, - Flow *f, uint8_t flags, void *state, - void *txv, const Signature *s, - const SigMatchCtx *ctx); -static int DetectMQTTFlagsSetup (DetectEngineCtx *, Signature *, const char *); +static int DetectMQTTFlagsMatch(DetectEngineThreadCtx *det_ctx, Flow *f, uint8_t flags, void *state, + void *txv, const Signature *s, const SigMatchCtx *ctx); +static int DetectMQTTFlagsSetup(DetectEngineCtx *, Signature *, const char *); void MQTTFlagsRegisterTests(void); void DetectMQTTFlagsFree(DetectEngineCtx *de_ctx, void *); @@ -52,14 +50,14 @@ typedef struct DetectMQTTFlagsData_ { /** * \brief Registration function for mqtt.flags: keyword */ -void DetectMQTTFlagsRegister (void) +void DetectMQTTFlagsRegister(void) { sigmatch_table[DETECT_AL_MQTT_FLAGS].name = "mqtt.flags"; sigmatch_table[DETECT_AL_MQTT_FLAGS].desc = "match MQTT fixed header flags"; sigmatch_table[DETECT_AL_MQTT_FLAGS].url = "/rules/mqtt-keywords.html#mqtt-flags"; sigmatch_table[DETECT_AL_MQTT_FLAGS].AppLayerTxMatch = DetectMQTTFlagsMatch; sigmatch_table[DETECT_AL_MQTT_FLAGS].Setup = DetectMQTTFlagsSetup; - sigmatch_table[DETECT_AL_MQTT_FLAGS].Free = DetectMQTTFlagsFree; + sigmatch_table[DETECT_AL_MQTT_FLAGS].Free = DetectMQTTFlagsFree; #ifdef UNITTESTS sigmatch_table[DETECT_AL_MQTT_FLAGS].RegisterTests = MQTTFlagsRegisterTests; #endif @@ -87,10 +85,8 @@ void DetectMQTTFlagsRegister (void) * \retval 0 no match. * \retval 1 match. */ -static int DetectMQTTFlagsMatch(DetectEngineThreadCtx *det_ctx, - Flow *f, uint8_t flags, void *state, - void *txv, const Signature *s, - const SigMatchCtx *ctx) +static int DetectMQTTFlagsMatch(DetectEngineThreadCtx *det_ctx, Flow *f, uint8_t flags, void *state, + void *txv, const Signature *s, const SigMatchCtx *ctx) { const DetectMQTTFlagsData *de = (const DetectMQTTFlagsData *)ctx; @@ -129,7 +125,7 @@ static DetectMQTTFlagsData *DetectMQTTFlagsParse(const char *rawstr) de->retain = de->dup = MQTT_DONT_CARE; - char copy[strlen(rawstr)+1]; + char copy[strlen(rawstr) + 1]; strlcpy(copy, rawstr, sizeof(copy)); char *xsaveptr = NULL; @@ -144,21 +140,21 @@ static DetectMQTTFlagsData *DetectMQTTFlagsParse(const char *rawstr) /* flags have a minimum length */ SCLogError("malformed flag value: %s", flagv); goto error; - } else { + } else { int offset = 0; MQTTFlagState fs_to_set = MQTT_MUST_BE_SET; if (flagv[0] == '!') { /* negated flag */ - offset = 1; /* skip negation operator during comparison */ + offset = 1; /* skip negation operator during comparison */ fs_to_set = MQTT_CANT_BE_SET; } - if (strcmp(flagv+offset, "dup") == 0) { + if (strcmp(flagv + offset, "dup") == 0) { if (de->dup != MQTT_DONT_CARE) { SCLogError("duplicate flag definition: %s", flagv); goto error; } de->dup = fs_to_set; - } else if (strcmp(flagv+offset, "retain") == 0) { + } else if (strcmp(flagv + offset, "retain") == 0) { if (de->retain != MQTT_DONT_CARE) { SCLogError("duplicate flag definition: %s", flagv); goto error; @@ -242,7 +238,7 @@ void DetectMQTTFlagsFree(DetectEngineCtx *de_ctx, void *de_ptr) * \retval 1 on success * \retval 0 on failure */ -static int MQTTFlagsTestParse01 (void) +static int MQTTFlagsTestParse01(void) { DetectMQTTFlagsData *de = NULL; @@ -271,7 +267,7 @@ static int MQTTFlagsTestParse01 (void) * \retval 1 on success * \retval 0 on failure */ -static int MQTTFlagsTestParse02 (void) +static int MQTTFlagsTestParse02(void) { DetectMQTTFlagsData *de = NULL; de = DetectMQTTFlagsParse("retain,!dup"); @@ -287,7 +283,7 @@ static int MQTTFlagsTestParse02 (void) * \retval 1 on success * \retval 0 on failure */ -static int MQTTFlagsTestParse03 (void) +static int MQTTFlagsTestParse03(void) { DetectMQTTFlagsData *de = NULL; de = DetectMQTTFlagsParse("ref"); @@ -305,7 +301,7 @@ static int MQTTFlagsTestParse03 (void) * \retval 1 on success * \retval 0 on failure */ -static int MQTTFlagsTestParse04 (void) +static int MQTTFlagsTestParse04(void) { DetectMQTTFlagsData *de = NULL; de = DetectMQTTFlagsParse("dup,!"); @@ -323,7 +319,7 @@ static int MQTTFlagsTestParse04 (void) * \retval 1 on success * \retval 0 on failure */ -static int MQTTFlagsTestParse05 (void) +static int MQTTFlagsTestParse05(void) { DetectMQTTFlagsData *de = NULL; de = DetectMQTTFlagsParse("dup,!dup"); @@ -341,7 +337,6 @@ static int MQTTFlagsTestParse05 (void) PASS; } - #endif /* UNITTESTS */ /** diff --git a/src/detect-mqtt-protocol-version.c b/src/detect-mqtt-protocol-version.c index 6ba183d75c8a..cf3ffb283c35 100644 --- a/src/detect-mqtt-protocol-version.c +++ b/src/detect-mqtt-protocol-version.c @@ -36,27 +36,28 @@ static int mqtt_protocol_version_id = 0; -static int DetectMQTTProtocolVersionMatch(DetectEngineThreadCtx *det_ctx, - Flow *f, uint8_t flags, void *state, - void *txv, const Signature *s, - const SigMatchCtx *ctx); -static int DetectMQTTProtocolVersionSetup (DetectEngineCtx *, Signature *, const char *); +static int DetectMQTTProtocolVersionMatch(DetectEngineThreadCtx *det_ctx, Flow *f, uint8_t flags, + void *state, void *txv, const Signature *s, const SigMatchCtx *ctx); +static int DetectMQTTProtocolVersionSetup(DetectEngineCtx *, Signature *, const char *); void MQTTProtocolVersionRegisterTests(void); void DetectMQTTProtocolVersionFree(DetectEngineCtx *de_ctx, void *); /** * \brief Registration function for mqtt.protocol_version: keyword */ -void DetectMQTTProtocolVersionRegister (void) +void DetectMQTTProtocolVersionRegister(void) { sigmatch_table[DETECT_AL_MQTT_PROTOCOL_VERSION].name = "mqtt.protocol_version"; sigmatch_table[DETECT_AL_MQTT_PROTOCOL_VERSION].desc = "match MQTT protocol version"; - sigmatch_table[DETECT_AL_MQTT_PROTOCOL_VERSION].url = "/rules/mqtt-keywords.html#mqtt-protocol-version"; - sigmatch_table[DETECT_AL_MQTT_PROTOCOL_VERSION].AppLayerTxMatch = DetectMQTTProtocolVersionMatch; + sigmatch_table[DETECT_AL_MQTT_PROTOCOL_VERSION].url = + "/rules/mqtt-keywords.html#mqtt-protocol-version"; + sigmatch_table[DETECT_AL_MQTT_PROTOCOL_VERSION].AppLayerTxMatch = + DetectMQTTProtocolVersionMatch; sigmatch_table[DETECT_AL_MQTT_PROTOCOL_VERSION].Setup = DetectMQTTProtocolVersionSetup; - sigmatch_table[DETECT_AL_MQTT_PROTOCOL_VERSION].Free = DetectMQTTProtocolVersionFree; + sigmatch_table[DETECT_AL_MQTT_PROTOCOL_VERSION].Free = DetectMQTTProtocolVersionFree; #ifdef UNITTESTS - sigmatch_table[DETECT_AL_MQTT_PROTOCOL_VERSION].RegisterTests = MQTTProtocolVersionRegisterTests; + sigmatch_table[DETECT_AL_MQTT_PROTOCOL_VERSION].RegisterTests = + MQTTProtocolVersionRegisterTests; #endif DetectAppLayerInspectEngineRegister2("mqtt.protocol_version", ALPROTO_MQTT, SIG_FLAG_TOSERVER, @@ -80,10 +81,8 @@ void DetectMQTTProtocolVersionRegister (void) * \retval 0 no match. * \retval 1 match. */ -static int DetectMQTTProtocolVersionMatch(DetectEngineThreadCtx *det_ctx, - Flow *f, uint8_t flags, void *state, - void *txv, const Signature *s, - const SigMatchCtx *ctx) +static int DetectMQTTProtocolVersionMatch(DetectEngineThreadCtx *det_ctx, Flow *f, uint8_t flags, + void *state, void *txv, const Signature *s, const SigMatchCtx *ctx) { const DetectU8Data *de = (const DetectU8Data *)ctx; uint8_t version; @@ -150,17 +149,17 @@ void DetectMQTTProtocolVersionFree(DetectEngineCtx *de_ctx, void *de_ptr) * \retval 1 on success * \retval 0 on failure */ -static int MQTTProtocolVersionTestParse01 (void) +static int MQTTProtocolVersionTestParse01(void) { DetectEngineCtx *de_ctx = DetectEngineCtxInit(); FAIL_IF_NULL(de_ctx); - Signature *sig = DetectEngineAppendSig(de_ctx, - "alert ip any any -> any any (mqtt.protocol_version:3; sid:1; rev:1;)"); + Signature *sig = DetectEngineAppendSig( + de_ctx, "alert ip any any -> any any (mqtt.protocol_version:3; sid:1; rev:1;)"); FAIL_IF_NULL(sig); - sig = DetectEngineAppendSig(de_ctx, - "alert ip any any -> any any (mqtt.protocol_version:3; sid:2; rev:1;)"); + sig = DetectEngineAppendSig( + de_ctx, "alert ip any any -> any any (mqtt.protocol_version:3; sid:2; rev:1;)"); FAIL_IF_NULL(sig); DetectEngineCtxFree(de_ctx); @@ -174,17 +173,17 @@ static int MQTTProtocolVersionTestParse01 (void) * \retval 1 on success * \retval 0 on failure */ -static int MQTTProtocolVersionTestParse02 (void) +static int MQTTProtocolVersionTestParse02(void) { DetectEngineCtx *de_ctx = DetectEngineCtxInit(); FAIL_IF_NULL(de_ctx); - Signature *sig = DetectEngineAppendSig(de_ctx, - "alert ip any any -> any any (mqtt.protocol_version:>3; sid:1; rev:1;)"); + Signature *sig = DetectEngineAppendSig( + de_ctx, "alert ip any any -> any any (mqtt.protocol_version:>3; sid:1; rev:1;)"); FAIL_IF_NULL(sig); - sig = DetectEngineAppendSig(de_ctx, - "alert ip any any -> any any (mqtt.protocol_version:<44; sid:2; rev:1;)"); + sig = DetectEngineAppendSig( + de_ctx, "alert ip any any -> any any (mqtt.protocol_version:<44; sid:2; rev:1;)"); FAIL_IF_NULL(sig); DetectEngineCtxFree(de_ctx); @@ -198,13 +197,13 @@ static int MQTTProtocolVersionTestParse02 (void) * \retval 1 on success * \retval 0 on failure */ -static int MQTTProtocolVersionTestParse03 (void) +static int MQTTProtocolVersionTestParse03(void) { DetectEngineCtx *de_ctx = DetectEngineCtxInit(); FAIL_IF_NULL(de_ctx); - Signature *sig = DetectEngineAppendSig(de_ctx, - "alert ip any any -> any any (mqtt.protocol_version:; sid:1; rev:1;)"); + Signature *sig = DetectEngineAppendSig( + de_ctx, "alert ip any any -> any any (mqtt.protocol_version:; sid:1; rev:1;)"); FAIL_IF_NOT_NULL(sig); DetectEngineCtxFree(de_ctx); @@ -218,13 +217,13 @@ static int MQTTProtocolVersionTestParse03 (void) * \retval 1 on success * \retval 0 on failure */ -static int MQTTProtocolVersionTestParse04 (void) +static int MQTTProtocolVersionTestParse04(void) { DetectEngineCtx *de_ctx = DetectEngineCtxInit(); FAIL_IF_NULL(de_ctx); - Signature *sig = DetectEngineAppendSig(de_ctx, - "alert ip any any -> any any (mqtt.protocol_version:<444; sid:1; rev:1;)"); + Signature *sig = DetectEngineAppendSig( + de_ctx, "alert ip any any -> any any (mqtt.protocol_version:<444; sid:1; rev:1;)"); FAIL_IF_NOT_NULL(sig); DetectEngineCtxFree(de_ctx); diff --git a/src/detect-mqtt-publish-message.c b/src/detect-mqtt-publish-message.c index 32f3bd6460ad..50afaaa62b70 100644 --- a/src/detect-mqtt-publish-message.c +++ b/src/detect-mqtt-publish-message.c @@ -49,9 +49,8 @@ static int DetectMQTTPublishMessageSetup(DetectEngineCtx *de_ctx, Signature *s, } static InspectionBuffer *GetData(DetectEngineThreadCtx *det_ctx, - const DetectEngineTransforms *transforms, - Flow *_f, const uint8_t _flow_flags, - void *txv, const int list_id) + const DetectEngineTransforms *transforms, Flow *_f, const uint8_t _flow_flags, void *txv, + const int list_id) { InspectionBuffer *buffer = InspectionBufferGet(det_ctx, list_id); if (buffer->inspect == NULL) { @@ -73,18 +72,17 @@ void DetectMQTTPublishMessageRegister(void) { /* mqtt.publish.message sticky buffer */ sigmatch_table[DETECT_AL_MQTT_PUBLISH_MESSAGE].name = KEYWORD_NAME; - sigmatch_table[DETECT_AL_MQTT_PUBLISH_MESSAGE].desc = "sticky buffer to match on the MQTT PUBLISH message"; + sigmatch_table[DETECT_AL_MQTT_PUBLISH_MESSAGE].desc = + "sticky buffer to match on the MQTT PUBLISH message"; sigmatch_table[DETECT_AL_MQTT_PUBLISH_MESSAGE].url = "/rules/" KEYWORD_DOC; sigmatch_table[DETECT_AL_MQTT_PUBLISH_MESSAGE].Setup = DetectMQTTPublishMessageSetup; sigmatch_table[DETECT_AL_MQTT_PUBLISH_MESSAGE].flags |= SIGMATCH_NOOPT; - DetectAppLayerInspectEngineRegister2(BUFFER_NAME, ALPROTO_MQTT, - SIG_FLAG_TOSERVER, 0, + DetectAppLayerInspectEngineRegister2(BUFFER_NAME, ALPROTO_MQTT, SIG_FLAG_TOSERVER, 0, DetectEngineInspectBufferGeneric, GetData); - DetectAppLayerMpmRegister2(BUFFER_NAME, SIG_FLAG_TOSERVER, 2, - PrefilterGenericMpmRegister, GetData, ALPROTO_MQTT, - 1); + DetectAppLayerMpmRegister2(BUFFER_NAME, SIG_FLAG_TOSERVER, 2, PrefilterGenericMpmRegister, + GetData, ALPROTO_MQTT, 1); DetectBufferTypeSetDescriptionByName(BUFFER_NAME, BUFFER_DESC); diff --git a/src/detect-mqtt-publish-topic.c b/src/detect-mqtt-publish-topic.c index c03a47b5eda7..f106f8ebd2b4 100644 --- a/src/detect-mqtt-publish-topic.c +++ b/src/detect-mqtt-publish-topic.c @@ -49,9 +49,8 @@ static int DetectMQTTPublishTopicSetup(DetectEngineCtx *de_ctx, Signature *s, co } static InspectionBuffer *GetData(DetectEngineThreadCtx *det_ctx, - const DetectEngineTransforms *transforms, - Flow *_f, const uint8_t _flow_flags, - void *txv, const int list_id) + const DetectEngineTransforms *transforms, Flow *_f, const uint8_t _flow_flags, void *txv, + const int list_id) { InspectionBuffer *buffer = InspectionBufferGet(det_ctx, list_id); if (buffer->inspect == NULL) { @@ -73,18 +72,17 @@ void DetectMQTTPublishTopicRegister(void) { /* mqtt.publish.topic sticky buffer */ sigmatch_table[DETECT_AL_MQTT_PUBLISH_TOPIC].name = KEYWORD_NAME; - sigmatch_table[DETECT_AL_MQTT_PUBLISH_TOPIC].desc = "sticky buffer to match on the MQTT PUBLISH topic"; + sigmatch_table[DETECT_AL_MQTT_PUBLISH_TOPIC].desc = + "sticky buffer to match on the MQTT PUBLISH topic"; sigmatch_table[DETECT_AL_MQTT_PUBLISH_TOPIC].url = "/rules/" KEYWORD_DOC; sigmatch_table[DETECT_AL_MQTT_PUBLISH_TOPIC].Setup = DetectMQTTPublishTopicSetup; sigmatch_table[DETECT_AL_MQTT_PUBLISH_TOPIC].flags |= SIGMATCH_NOOPT; - DetectAppLayerInspectEngineRegister2(BUFFER_NAME, ALPROTO_MQTT, - SIG_FLAG_TOSERVER, 0, + DetectAppLayerInspectEngineRegister2(BUFFER_NAME, ALPROTO_MQTT, SIG_FLAG_TOSERVER, 0, DetectEngineInspectBufferGeneric, GetData); - DetectAppLayerMpmRegister2(BUFFER_NAME, SIG_FLAG_TOSERVER, 2, - PrefilterGenericMpmRegister, GetData, ALPROTO_MQTT, - 1); + DetectAppLayerMpmRegister2(BUFFER_NAME, SIG_FLAG_TOSERVER, 2, PrefilterGenericMpmRegister, + GetData, ALPROTO_MQTT, 1); DetectBufferTypeSetDescriptionByName(BUFFER_NAME, BUFFER_DESC); diff --git a/src/detect-mqtt-qos.c b/src/detect-mqtt-qos.c index a00eaee185a2..10165492b285 100644 --- a/src/detect-mqtt-qos.c +++ b/src/detect-mqtt-qos.c @@ -35,25 +35,23 @@ static int mqtt_qos_id = 0; -static int DetectMQTTQosMatch(DetectEngineThreadCtx *det_ctx, - Flow *f, uint8_t flags, void *state, - void *txv, const Signature *s, - const SigMatchCtx *ctx); -static int DetectMQTTQosSetup (DetectEngineCtx *, Signature *, const char *); +static int DetectMQTTQosMatch(DetectEngineThreadCtx *det_ctx, Flow *f, uint8_t flags, void *state, + void *txv, const Signature *s, const SigMatchCtx *ctx); +static int DetectMQTTQosSetup(DetectEngineCtx *, Signature *, const char *); void MQTTQosRegisterTests(void); void DetectMQTTQosFree(DetectEngineCtx *de_ctx, void *); /** * \brief Registration function for mqtt.qos: keyword */ -void DetectMQTTQosRegister (void) +void DetectMQTTQosRegister(void) { sigmatch_table[DETECT_AL_MQTT_QOS].name = "mqtt.qos"; sigmatch_table[DETECT_AL_MQTT_QOS].desc = "match MQTT fixed header QOS level"; sigmatch_table[DETECT_AL_MQTT_QOS].url = "/rules/mqtt-keywords.html#mqtt-qos"; sigmatch_table[DETECT_AL_MQTT_QOS].AppLayerTxMatch = DetectMQTTQosMatch; sigmatch_table[DETECT_AL_MQTT_QOS].Setup = DetectMQTTQosSetup; - sigmatch_table[DETECT_AL_MQTT_QOS].Free = DetectMQTTQosFree; + sigmatch_table[DETECT_AL_MQTT_QOS].Free = DetectMQTTQosFree; #ifdef UNITTESTS sigmatch_table[DETECT_AL_MQTT_QOS].RegisterTests = MQTTQosRegisterTests; #endif @@ -79,10 +77,8 @@ void DetectMQTTQosRegister (void) * \retval 0 no match. * \retval 1 match. */ -static int DetectMQTTQosMatch(DetectEngineThreadCtx *det_ctx, - Flow *f, uint8_t flags, void *state, - void *txv, const Signature *s, - const SigMatchCtx *ctx) +static int DetectMQTTQosMatch(DetectEngineThreadCtx *det_ctx, Flow *f, uint8_t flags, void *state, + void *txv, const Signature *s, const SigMatchCtx *ctx) { const uint8_t *de = (const uint8_t *)ctx; @@ -179,7 +175,7 @@ void DetectMQTTQosFree(DetectEngineCtx *de_ctx, void *de_ptr) * \retval 1 on success * \retval 0 on failure */ -static int MQTTQosTestParse01 (void) +static int MQTTQosTestParse01(void) { uint8_t *de = NULL; @@ -212,7 +208,7 @@ static int MQTTQosTestParse01 (void) * \retval 1 on success * \retval 0 on failure */ -static int MQTTQosTestParse02 (void) +static int MQTTQosTestParse02(void) { uint8_t *de = NULL; de = DetectMQTTQosParse("3"); @@ -230,7 +226,7 @@ static int MQTTQosTestParse02 (void) * \retval 1 on success * \retval 0 on failure */ -static int MQTTQosTestParse03 (void) +static int MQTTQosTestParse03(void) { uint8_t *de = NULL; de = DetectMQTTQosParse("12"); @@ -242,7 +238,6 @@ static int MQTTQosTestParse03 (void) PASS; } - #endif /* UNITTESTS */ /** diff --git a/src/detect-mqtt-reason-code.c b/src/detect-mqtt-reason-code.c index e6ecba44cc26..7ffbc7fb0036 100644 --- a/src/detect-mqtt-reason-code.c +++ b/src/detect-mqtt-reason-code.c @@ -38,18 +38,16 @@ static DetectParseRegex parse_regex; static int mqtt_reason_code_id = 0; -static int DetectMQTTReasonCodeMatch(DetectEngineThreadCtx *det_ctx, - Flow *f, uint8_t flags, void *state, - void *txv, const Signature *s, - const SigMatchCtx *ctx); -static int DetectMQTTReasonCodeSetup (DetectEngineCtx *, Signature *, const char *); +static int DetectMQTTReasonCodeMatch(DetectEngineThreadCtx *det_ctx, Flow *f, uint8_t flags, + void *state, void *txv, const Signature *s, const SigMatchCtx *ctx); +static int DetectMQTTReasonCodeSetup(DetectEngineCtx *, Signature *, const char *); void MQTTReasonCodeRegisterTests(void); void DetectMQTTReasonCodeFree(DetectEngineCtx *de_ctx, void *); /** * \brief Registration function for mqtt.reason_code: keyword */ -void DetectMQTTReasonCodeRegister (void) +void DetectMQTTReasonCodeRegister(void) { sigmatch_table[DETECT_AL_MQTT_REASON_CODE].name = "mqtt.reason_code"; sigmatch_table[DETECT_AL_MQTT_REASON_CODE].alias = "mqtt.connack.return_code"; @@ -57,7 +55,7 @@ void DetectMQTTReasonCodeRegister (void) sigmatch_table[DETECT_AL_MQTT_REASON_CODE].url = "/rules/mqtt-keywords.html#mqtt-reason-code"; sigmatch_table[DETECT_AL_MQTT_REASON_CODE].AppLayerTxMatch = DetectMQTTReasonCodeMatch; sigmatch_table[DETECT_AL_MQTT_REASON_CODE].Setup = DetectMQTTReasonCodeSetup; - sigmatch_table[DETECT_AL_MQTT_REASON_CODE].Free = DetectMQTTReasonCodeFree; + sigmatch_table[DETECT_AL_MQTT_REASON_CODE].Free = DetectMQTTReasonCodeFree; #ifdef UNITTESTS sigmatch_table[DETECT_AL_MQTT_REASON_CODE].RegisterTests = MQTTReasonCodeRegisterTests; #endif @@ -85,10 +83,8 @@ void DetectMQTTReasonCodeRegister (void) * \retval 0 no match. * \retval 1 match. */ -static int DetectMQTTReasonCodeMatch(DetectEngineThreadCtx *det_ctx, - Flow *f, uint8_t flags, void *state, - void *txv, const Signature *s, - const SigMatchCtx *ctx) +static int DetectMQTTReasonCodeMatch(DetectEngineThreadCtx *det_ctx, Flow *f, uint8_t flags, + void *state, void *txv, const Signature *s, const SigMatchCtx *ctx) { const uint8_t *de = (const uint8_t *)ctx; uint8_t code; @@ -132,7 +128,7 @@ static uint8_t *DetectMQTTReasonCodeParse(const char *rawstr) de = SCMalloc(sizeof(uint8_t)); if (unlikely(de == NULL)) return NULL; - *de = (uint8_t) val; + *de = (uint8_t)val; return de; } @@ -148,7 +144,7 @@ static uint8_t *DetectMQTTReasonCodeParse(const char *rawstr) * \retval 0 on Success * \retval -1 on Failure */ -static int DetectMQTTReasonCodeSetup (DetectEngineCtx *de_ctx, Signature *s, const char *rawstr) +static int DetectMQTTReasonCodeSetup(DetectEngineCtx *de_ctx, Signature *s, const char *rawstr) { uint8_t *de = NULL; @@ -195,7 +191,7 @@ void DetectMQTTReasonCodeFree(DetectEngineCtx *de_ctx, void *de_ptr) * \retval 1 on success * \retval 0 on failure */ -static int MQTTReasonCodeTestParse01 (void) +static int MQTTReasonCodeTestParse01(void) { uint8_t *de = NULL; @@ -228,7 +224,7 @@ static int MQTTReasonCodeTestParse01 (void) * \retval 1 on success * \retval 0 on failure */ -static int MQTTReasonCodeTestParse02 (void) +static int MQTTReasonCodeTestParse02(void) { uint8_t *de = NULL; de = DetectMQTTReasonCodeParse("6X"); @@ -246,7 +242,7 @@ static int MQTTReasonCodeTestParse02 (void) * \retval 1 on success * \retval 0 on failure */ -static int MQTTReasonCodeTestParse03 (void) +static int MQTTReasonCodeTestParse03(void) { uint8_t *de = NULL; de = DetectMQTTReasonCodeParse(""); @@ -264,7 +260,7 @@ static int MQTTReasonCodeTestParse03 (void) * \retval 1 on success * \retval 0 on failure */ -static int MQTTReasonCodeTestParse04 (void) +static int MQTTReasonCodeTestParse04(void) { uint8_t *de = NULL; de = DetectMQTTReasonCodeParse("256"); @@ -276,8 +272,6 @@ static int MQTTReasonCodeTestParse04 (void) PASS; } - - #endif /* UNITTESTS */ /** diff --git a/src/detect-mqtt-subscribe-topic.c b/src/detect-mqtt-subscribe-topic.c index 9eaf39d3029c..900d63d886ae 100644 --- a/src/detect-mqtt-subscribe-topic.c +++ b/src/detect-mqtt-subscribe-topic.c @@ -101,7 +101,10 @@ static uint8_t DetectEngineInspectMQTTSubscribeTopic(DetectEngineCtx *de_ctx, } while ((subscribe_topic_match_limit == 0) || local_id < subscribe_topic_match_limit) { - struct MQTTSubscribeTopicGetDataArgs cbdata = { local_id, txv, }; + struct MQTTSubscribeTopicGetDataArgs cbdata = { + local_id, + txv, + }; InspectionBuffer *buffer = MQTTSubscribeTopicGetData(det_ctx, transforms, f, &cbdata, engine->sm_list); if (buffer == NULL || buffer->inspect == NULL) @@ -176,18 +179,20 @@ static int PrefilterMpmMQTTSubscribeTopicRegister(DetectEngineCtx *de_ctx, SigGr pectx->transforms = &mpm_reg->transforms; return PrefilterAppendTxEngine(de_ctx, sgh, PrefilterTxMQTTSubscribeTopic, - mpm_reg->app_v2.alproto, mpm_reg->app_v2.tx_min_progress, - pectx, PrefilterMpmMQTTSubscribeTopicFree, mpm_reg->pname); + mpm_reg->app_v2.alproto, mpm_reg->app_v2.tx_min_progress, pectx, + PrefilterMpmMQTTSubscribeTopicFree, mpm_reg->pname); } /** * \brief Registration function for keyword: mqtt.subscribe.topic */ -void DetectMQTTSubscribeTopicRegister (void) +void DetectMQTTSubscribeTopicRegister(void) { sigmatch_table[DETECT_AL_MQTT_SUBSCRIBE_TOPIC].name = "mqtt.subscribe.topic"; - sigmatch_table[DETECT_AL_MQTT_SUBSCRIBE_TOPIC].desc = "sticky buffer to match MQTT SUBSCRIBE topic"; - sigmatch_table[DETECT_AL_MQTT_SUBSCRIBE_TOPIC].url = "/rules/mqtt-keywords.html#mqtt-subscribe-topic"; + sigmatch_table[DETECT_AL_MQTT_SUBSCRIBE_TOPIC].desc = + "sticky buffer to match MQTT SUBSCRIBE topic"; + sigmatch_table[DETECT_AL_MQTT_SUBSCRIBE_TOPIC].url = + "/rules/mqtt-keywords.html#mqtt-subscribe-topic"; sigmatch_table[DETECT_AL_MQTT_SUBSCRIBE_TOPIC].Setup = DetectMQTTSubscribeTopicSetup; sigmatch_table[DETECT_AL_MQTT_SUBSCRIBE_TOPIC].flags |= SIGMATCH_NOOPT; sigmatch_table[DETECT_AL_MQTT_SUBSCRIBE_TOPIC].flags |= SIGMATCH_INFO_STICKY_BUFFER; @@ -204,15 +209,12 @@ void DetectMQTTSubscribeTopicRegister (void) } DetectAppLayerMpmRegister2("mqtt.subscribe.topic", SIG_FLAG_TOSERVER, 1, - PrefilterMpmMQTTSubscribeTopicRegister, NULL, - ALPROTO_MQTT, 1); + PrefilterMpmMQTTSubscribeTopicRegister, NULL, ALPROTO_MQTT, 1); - DetectAppLayerInspectEngineRegister2("mqtt.subscribe.topic", - ALPROTO_MQTT, SIG_FLAG_TOSERVER, 1, + DetectAppLayerInspectEngineRegister2("mqtt.subscribe.topic", ALPROTO_MQTT, SIG_FLAG_TOSERVER, 1, DetectEngineInspectMQTTSubscribeTopic, NULL); - DetectBufferTypeSetDescriptionByName("mqtt.subscribe.topic", - "subscribe topic query"); + DetectBufferTypeSetDescriptionByName("mqtt.subscribe.topic", "subscribe topic query"); g_mqtt_subscribe_topic_buffer_id = DetectBufferTypeGetByName("mqtt.subscribe.topic"); diff --git a/src/detect-mqtt-type.c b/src/detect-mqtt-type.c index 5e23a509ca7c..1ad14014c81f 100644 --- a/src/detect-mqtt-type.c +++ b/src/detect-mqtt-type.c @@ -34,25 +34,23 @@ static int mqtt_type_id = 0; -static int DetectMQTTTypeMatch(DetectEngineThreadCtx *det_ctx, - Flow *f, uint8_t flags, void *state, - void *txv, const Signature *s, - const SigMatchCtx *ctx); -static int DetectMQTTTypeSetup (DetectEngineCtx *, Signature *, const char *); +static int DetectMQTTTypeMatch(DetectEngineThreadCtx *det_ctx, Flow *f, uint8_t flags, void *state, + void *txv, const Signature *s, const SigMatchCtx *ctx); +static int DetectMQTTTypeSetup(DetectEngineCtx *, Signature *, const char *); void MQTTTypeRegisterTests(void); void DetectMQTTTypeFree(DetectEngineCtx *de_ctx, void *); /** * \brief Registration function for mqtt.type: keyword */ -void DetectMQTTTypeRegister (void) +void DetectMQTTTypeRegister(void) { sigmatch_table[DETECT_AL_MQTT_TYPE].name = "mqtt.type"; sigmatch_table[DETECT_AL_MQTT_TYPE].desc = "match MQTT control packet type"; sigmatch_table[DETECT_AL_MQTT_TYPE].url = "/rules/mqtt-keywords.html#mqtt-type"; sigmatch_table[DETECT_AL_MQTT_TYPE].AppLayerTxMatch = DetectMQTTTypeMatch; sigmatch_table[DETECT_AL_MQTT_TYPE].Setup = DetectMQTTTypeSetup; - sigmatch_table[DETECT_AL_MQTT_TYPE].Free = DetectMQTTTypeFree; + sigmatch_table[DETECT_AL_MQTT_TYPE].Free = DetectMQTTTypeFree; #ifdef UNITTESTS sigmatch_table[DETECT_AL_MQTT_TYPE].RegisterTests = MQTTTypeRegisterTests; #endif @@ -78,10 +76,8 @@ void DetectMQTTTypeRegister (void) * \retval 0 no match. * \retval 1 match. */ -static int DetectMQTTTypeMatch(DetectEngineThreadCtx *det_ctx, - Flow *f, uint8_t flags, void *state, - void *txv, const Signature *s, - const SigMatchCtx *ctx) +static int DetectMQTTTypeMatch(DetectEngineThreadCtx *det_ctx, Flow *f, uint8_t flags, void *state, + void *txv, const Signature *s, const SigMatchCtx *ctx) { const uint8_t *de = (const uint8_t *)ctx; @@ -107,7 +103,7 @@ static uint8_t *DetectMQTTTypeParse(const char *rawstr) ret = rs_mqtt_cstr_message_code(rawstr); // negative value denotes invalid input - if(ret < 0) { + if (ret < 0) { SCLogError("unknown mqtt.type value %s", rawstr); goto error; } @@ -116,7 +112,7 @@ static uint8_t *DetectMQTTTypeParse(const char *rawstr) if (unlikely(de == NULL)) goto error; - *de = (uint8_t) ret; + *de = (uint8_t)ret; return de; @@ -137,7 +133,7 @@ static uint8_t *DetectMQTTTypeParse(const char *rawstr) * \retval 0 on Success * \retval -1 on Failure */ -static int DetectMQTTTypeSetup (DetectEngineCtx *de_ctx, Signature *s, const char *rawstr) +static int DetectMQTTTypeSetup(DetectEngineCtx *de_ctx, Signature *s, const char *rawstr) { uint8_t *de = NULL; @@ -184,7 +180,7 @@ void DetectMQTTTypeFree(DetectEngineCtx *de_ctx, void *de_ptr) * \retval 1 on success * \retval 0 on failure */ -static int MQTTTypeTestParse01 (void) +static int MQTTTypeTestParse01(void) { uint8_t *de = NULL; de = DetectMQTTTypeParse("CONNECT"); @@ -206,7 +202,7 @@ static int MQTTTypeTestParse01 (void) * \retval 1 on success * \retval 0 on failure */ -static int MQTTTypeTestParse02 (void) +static int MQTTTypeTestParse02(void) { uint8_t *de = NULL; de = DetectMQTTTypeParse("auth"); @@ -223,7 +219,7 @@ static int MQTTTypeTestParse02 (void) * \retval 1 on success * \retval 0 on failure */ -static int MQTTTypeTestParse03 (void) +static int MQTTTypeTestParse03(void) { uint8_t *de = NULL; de = DetectMQTTTypeParse("invalidopt"); diff --git a/src/detect-mqtt-unsubscribe-topic.c b/src/detect-mqtt-unsubscribe-topic.c index 268d72bc8789..36184c94335c 100644 --- a/src/detect-mqtt-unsubscribe-topic.c +++ b/src/detect-mqtt-unsubscribe-topic.c @@ -101,7 +101,10 @@ static uint8_t DetectEngineInspectMQTTUnsubscribeTopic(DetectEngineCtx *de_ctx, } while ((unsubscribe_topic_match_limit == 0) || local_id < unsubscribe_topic_match_limit) { - struct MQTTUnsubscribeTopicGetDataArgs cbdata = { local_id, txv, }; + struct MQTTUnsubscribeTopicGetDataArgs cbdata = { + local_id, + txv, + }; InspectionBuffer *buffer = MQTTUnsubscribeTopicGetData(det_ctx, transforms, f, &cbdata, engine->sm_list); if (buffer == NULL || buffer->inspect == NULL) @@ -176,18 +179,20 @@ static int PrefilterMpmMQTTUnsubscribeTopicRegister(DetectEngineCtx *de_ctx, Sig pectx->transforms = &mpm_reg->transforms; return PrefilterAppendTxEngine(de_ctx, sgh, PrefilterTxMQTTUnsubscribeTopic, - mpm_reg->app_v2.alproto, mpm_reg->app_v2.tx_min_progress, - pectx, PrefilterMpmMQTTUnsubscribeTopicFree, mpm_reg->pname); + mpm_reg->app_v2.alproto, mpm_reg->app_v2.tx_min_progress, pectx, + PrefilterMpmMQTTUnsubscribeTopicFree, mpm_reg->pname); } /** * \brief Registration function for keyword: mqtt.unsubscribe.topic */ -void DetectMQTTUnsubscribeTopicRegister (void) +void DetectMQTTUnsubscribeTopicRegister(void) { sigmatch_table[DETECT_AL_MQTT_UNSUBSCRIBE_TOPIC].name = "mqtt.unsubscribe.topic"; - sigmatch_table[DETECT_AL_MQTT_UNSUBSCRIBE_TOPIC].desc = "sticky buffer to match MQTT UNSUBSCRIBE topic"; - sigmatch_table[DETECT_AL_MQTT_UNSUBSCRIBE_TOPIC].url = "/rules/mqtt-keywords.html#mqtt-unsubscribe-topic"; + sigmatch_table[DETECT_AL_MQTT_UNSUBSCRIBE_TOPIC].desc = + "sticky buffer to match MQTT UNSUBSCRIBE topic"; + sigmatch_table[DETECT_AL_MQTT_UNSUBSCRIBE_TOPIC].url = + "/rules/mqtt-keywords.html#mqtt-unsubscribe-topic"; sigmatch_table[DETECT_AL_MQTT_UNSUBSCRIBE_TOPIC].Setup = DetectMQTTUnsubscribeTopicSetup; sigmatch_table[DETECT_AL_MQTT_UNSUBSCRIBE_TOPIC].flags |= SIGMATCH_NOOPT; sigmatch_table[DETECT_AL_MQTT_UNSUBSCRIBE_TOPIC].flags |= SIGMATCH_INFO_STICKY_BUFFER; @@ -204,15 +209,12 @@ void DetectMQTTUnsubscribeTopicRegister (void) } DetectAppLayerMpmRegister2("mqtt.unsubscribe.topic", SIG_FLAG_TOSERVER, 1, - PrefilterMpmMQTTUnsubscribeTopicRegister, NULL, - ALPROTO_MQTT, 1); + PrefilterMpmMQTTUnsubscribeTopicRegister, NULL, ALPROTO_MQTT, 1); - DetectAppLayerInspectEngineRegister2("mqtt.unsubscribe.topic", - ALPROTO_MQTT, SIG_FLAG_TOSERVER, 1, - DetectEngineInspectMQTTUnsubscribeTopic, NULL); + DetectAppLayerInspectEngineRegister2("mqtt.unsubscribe.topic", ALPROTO_MQTT, SIG_FLAG_TOSERVER, + 1, DetectEngineInspectMQTTUnsubscribeTopic, NULL); - DetectBufferTypeSetDescriptionByName("mqtt.unsubscribe.topic", - "unsubscribe topic query"); + DetectBufferTypeSetDescriptionByName("mqtt.unsubscribe.topic", "unsubscribe topic query"); g_mqtt_unsubscribe_topic_buffer_id = DetectBufferTypeGetByName("mqtt.unsubscribe.topic"); diff --git a/src/detect-msg.c b/src/detect-msg.c index 7f67d62497e2..b924dfa889ee 100644 --- a/src/detect-msg.c +++ b/src/detect-msg.c @@ -34,12 +34,12 @@ #include "detect-engine-mpm.h" #include "detect-msg.h" -static int DetectMsgSetup (DetectEngineCtx *, Signature *, const char *); +static int DetectMsgSetup(DetectEngineCtx *, Signature *, const char *); #ifdef UNITTESTS static void DetectMsgRegisterTests(void); #endif -void DetectMsgRegister (void) +void DetectMsgRegister(void) { sigmatch_table[DETECT_MSG].name = "msg"; sigmatch_table[DETECT_MSG].desc = "information about the rule and the possible alert"; @@ -53,7 +53,7 @@ void DetectMsgRegister (void) sigmatch_table[DETECT_MSG].flags = SIGMATCH_QUOTES_MANDATORY; } -static int DetectMsgSetup (DetectEngineCtx *de_ctx, Signature *s, const char *msgstr) +static int DetectMsgSetup(DetectEngineCtx *de_ctx, Signature *s, const char *msgstr) { size_t slen = strlen(msgstr); if (slen == 0) @@ -70,29 +70,24 @@ static int DetectMsgSetup (DetectEngineCtx *de_ctx, Signature *s, const char *ms /* it doesn't matter if we need to escape or not we remove the extra "\" to mimic snort */ for (i = 0, x = 0; i < slen; i++) { - //printf("str[%02u]: %c\n", i, str[i]); - if(!escape && str[i] == '\\') { + // printf("str[%02u]: %c\n", i, str[i]); + if (!escape && str[i] == '\\') { escape = 1; } else if (escape) { - if (str[i] != ':' && - str[i] != ';' && - str[i] != '\\' && - str[i] != '\"') - { - SCLogDebug("character \"%c\" does not need to be escaped but is" ,str[i]); + if (str[i] != ':' && str[i] != ';' && str[i] != '\\' && str[i] != '\"') { + SCLogDebug("character \"%c\" does not need to be escaped but is", str[i]); } escape = 0; converted = 1; str[x] = str[i]; x++; - }else{ + } else { str[x] = str[i]; x++; } - } -#if 0 //def DEBUG +#if 0 // def DEBUG if (SCLogDebugEnabled()) { for (i = 0; i < x; i++) { printf("%c", str[i]); diff --git a/src/detect-msg.h b/src/detect-msg.h index a21d51103524..ca571c0b3c5a 100644 --- a/src/detect-msg.h +++ b/src/detect-msg.h @@ -25,7 +25,6 @@ #define __DETECT_MSG_H__ /* prototypes */ -void DetectMsgRegister (void); +void DetectMsgRegister(void); #endif /* __DETECT_MSG_H__ */ - diff --git a/src/detect-nfs-procedure.c b/src/detect-nfs-procedure.c index 24c1563df18f..e425a7abeff2 100644 --- a/src/detect-nfs-procedure.c +++ b/src/detect-nfs-procedure.c @@ -47,21 +47,20 @@ #include "app-layer-nfs-tcp.h" #include "rust.h" -static int DetectNfsProcedureSetup (DetectEngineCtx *, Signature *s, const char *str); +static int DetectNfsProcedureSetup(DetectEngineCtx *, Signature *s, const char *str); static void DetectNfsProcedureFree(DetectEngineCtx *, void *); #ifdef UNITTESTS static void DetectNfsProcedureRegisterTests(void); #endif static int g_nfs_request_buffer_id = 0; -static int DetectNfsProcedureMatch (DetectEngineThreadCtx *, Flow *, - uint8_t, void *, void *, const Signature *, - const SigMatchCtx *); +static int DetectNfsProcedureMatch(DetectEngineThreadCtx *, Flow *, uint8_t, void *, void *, + const Signature *, const SigMatchCtx *); /** * \brief Registration function for nfs_procedure keyword. */ -void DetectNfsProcedureRegister (void) +void DetectNfsProcedureRegister(void) { sigmatch_table[DETECT_AL_NFS_PROCEDURE].name = "nfs_procedure"; sigmatch_table[DETECT_AL_NFS_PROCEDURE].desc = "match NFS procedure"; @@ -100,10 +99,8 @@ void DetectNfsProcedureRegister (void) * \retval 0 no match. * \retval 1 match. */ -static int DetectNfsProcedureMatch (DetectEngineThreadCtx *det_ctx, - Flow *f, uint8_t flags, void *state, - void *txv, const Signature *s, - const SigMatchCtx *ctx) +static int DetectNfsProcedureMatch(DetectEngineThreadCtx *det_ctx, Flow *f, uint8_t flags, + void *state, void *txv, const Signature *s, const SigMatchCtx *ctx) { SCEnter(); @@ -136,8 +133,6 @@ static DetectU32Data *DetectNfsProcedureParse(const char *rawstr) return rs_detect_u32_parse_inclusive(rawstr); } - - /** * \brief Function to add the parsed tls validity field into the current signature. * @@ -149,8 +144,7 @@ static DetectU32Data *DetectNfsProcedureParse(const char *rawstr) * \retval 0 on Success. * \retval -1 on Failure. */ -static int DetectNfsProcedureSetup (DetectEngineCtx *de_ctx, Signature *s, - const char *rawstr) +static int DetectNfsProcedureSetup(DetectEngineCtx *de_ctx, Signature *s, const char *rawstr) { DetectU32Data *dd = NULL; @@ -199,7 +193,7 @@ void DetectNfsProcedureFree(DetectEngineCtx *de_ctx, void *ptr) * \retval 1 on success. * \retval 0 on failure. */ -static int ValidityTestParse01 (void) +static int ValidityTestParse01(void) { DetectU32Data *dd = NULL; dd = DetectNfsProcedureParse("1430000000"); @@ -215,7 +209,7 @@ static int ValidityTestParse01 (void) * \retval 1 on success. * \retval 0 on failure. */ -static int ValidityTestParse02 (void) +static int ValidityTestParse02(void) { DetectU32Data *dd = NULL; dd = DetectNfsProcedureParse(">1430000000"); @@ -231,7 +225,7 @@ static int ValidityTestParse02 (void) * \retval 1 on success. * \retval 0 on failure. */ -static int ValidityTestParse03 (void) +static int ValidityTestParse03(void) { DetectU32Data *dd = NULL; dd = DetectNfsProcedureParse("<1430000000"); @@ -247,7 +241,7 @@ static int ValidityTestParse03 (void) * \retval 1 on success. * \retval 0 on failure. */ -static int ValidityTestParse04 (void) +static int ValidityTestParse04(void) { DetectU32Data *dd = NULL; dd = DetectNfsProcedureParse("1430000001<>1470000000"); @@ -263,7 +257,7 @@ static int ValidityTestParse04 (void) * \retval 1 on success. * \retval 0 on failure. */ -static int ValidityTestParse05 (void) +static int ValidityTestParse05(void) { DetectU32Data *dd = NULL; dd = DetectNfsProcedureParse("A"); @@ -277,7 +271,7 @@ static int ValidityTestParse05 (void) * \retval 1 on success. * \retval 0 on failure. */ -static int ValidityTestParse06 (void) +static int ValidityTestParse06(void) { DetectU32Data *dd = NULL; dd = DetectNfsProcedureParse(">1430000000<>1470000000"); @@ -291,7 +285,7 @@ static int ValidityTestParse06 (void) * \retval 1 on success. * \retval 0 on failure. */ -static int ValidityTestParse07 (void) +static int ValidityTestParse07(void) { DetectU32Data *dd = NULL; dd = DetectNfsProcedureParse("1430000000<>"); @@ -305,7 +299,7 @@ static int ValidityTestParse07 (void) * \retval 1 on success. * \retval 0 on failure. */ -static int ValidityTestParse08 (void) +static int ValidityTestParse08(void) { DetectU32Data *dd = NULL; dd = DetectNfsProcedureParse("<>1430000000"); @@ -319,7 +313,7 @@ static int ValidityTestParse08 (void) * \retval 1 on success. * \retval 0 on failure. */ -static int ValidityTestParse09 (void) +static int ValidityTestParse09(void) { DetectU32Data *dd = NULL; dd = DetectNfsProcedureParse(""); @@ -333,7 +327,7 @@ static int ValidityTestParse09 (void) * \retval 1 on success. * \retval 0 on failure. */ -static int ValidityTestParse10 (void) +static int ValidityTestParse10(void) { DetectU32Data *dd = NULL; dd = DetectNfsProcedureParse(" "); @@ -347,7 +341,7 @@ static int ValidityTestParse10 (void) * \retval 1 on success. * \retval 0 on failure. */ -static int ValidityTestParse11 (void) +static int ValidityTestParse11(void) { DetectU32Data *dd = NULL; dd = DetectNfsProcedureParse("1490000000<>1430000000"); @@ -361,7 +355,7 @@ static int ValidityTestParse11 (void) * \retval 1 on success. * \retval 0 on failure. */ -static int ValidityTestParse12 (void) +static int ValidityTestParse12(void) { DetectU32Data *dd = NULL; dd = DetectNfsProcedureParse("1430000001 <> 1490000000"); @@ -377,7 +371,7 @@ static int ValidityTestParse12 (void) * \retval 1 on success. * \retval 0 on failure. */ -static int ValidityTestParse13 (void) +static int ValidityTestParse13(void) { DetectU32Data *dd = NULL; dd = DetectNfsProcedureParse("> 1430000000 "); @@ -393,7 +387,7 @@ static int ValidityTestParse13 (void) * \retval 1 on success. * \retval 0 on failure. */ -static int ValidityTestParse14 (void) +static int ValidityTestParse14(void) { DetectU32Data *dd = NULL; dd = DetectNfsProcedureParse("< 1490000000 "); @@ -409,7 +403,7 @@ static int ValidityTestParse14 (void) * \retval 1 on success. * \retval 0 on failure. */ -static int ValidityTestParse15 (void) +static int ValidityTestParse15(void) { DetectU32Data *dd = NULL; dd = DetectNfsProcedureParse(" 1490000000 "); diff --git a/src/detect-nfs-procedure.h b/src/detect-nfs-procedure.h index e7b225677899..722b0be5cd71 100644 --- a/src/detect-nfs-procedure.h +++ b/src/detect-nfs-procedure.h @@ -25,6 +25,6 @@ #define __DETECT_NFS_PROCEDURE_H__ /* prototypes */ -void DetectNfsProcedureRegister (void); +void DetectNfsProcedureRegister(void); #endif /* __DETECT_NFS_PROCEDURE_H__ */ diff --git a/src/detect-nfs-version.c b/src/detect-nfs-version.c index 99c88149a73e..5af8a5ce9a17 100644 --- a/src/detect-nfs-version.c +++ b/src/detect-nfs-version.c @@ -47,19 +47,17 @@ #include "app-layer-nfs-tcp.h" #include "rust.h" - -static int DetectNfsVersionSetup (DetectEngineCtx *, Signature *s, const char *str); +static int DetectNfsVersionSetup(DetectEngineCtx *, Signature *s, const char *str); static void DetectNfsVersionFree(DetectEngineCtx *de_ctx, void *); static int g_nfs_request_buffer_id = 0; -static int DetectNfsVersionMatch (DetectEngineThreadCtx *, Flow *, - uint8_t, void *, void *, const Signature *, - const SigMatchCtx *); +static int DetectNfsVersionMatch(DetectEngineThreadCtx *, Flow *, uint8_t, void *, void *, + const Signature *, const SigMatchCtx *); /** * \brief Registration function for nfs_procedure keyword. */ -void DetectNfsVersionRegister (void) +void DetectNfsVersionRegister(void) { sigmatch_table[DETECT_AL_NFS_VERSION].name = "nfs.version"; sigmatch_table[DETECT_AL_NFS_VERSION].alias = "nfs_version"; @@ -93,10 +91,8 @@ void DetectNfsVersionRegister (void) * \retval 0 no match. * \retval 1 match. */ -static int DetectNfsVersionMatch (DetectEngineThreadCtx *det_ctx, - Flow *f, uint8_t flags, void *state, - void *txv, const Signature *s, - const SigMatchCtx *ctx) +static int DetectNfsVersionMatch(DetectEngineThreadCtx *det_ctx, Flow *f, uint8_t flags, + void *state, void *txv, const Signature *s, const SigMatchCtx *ctx) { SCEnter(); @@ -123,8 +119,6 @@ static DetectU32Data *DetectNfsVersionParse(const char *rawstr) return rs_detect_u32_parse_inclusive(rawstr); } - - /** * \brief Function to add the parsed tls validity field into the current signature. * @@ -136,8 +130,7 @@ static DetectU32Data *DetectNfsVersionParse(const char *rawstr) * \retval 0 on Success. * \retval -1 on Failure. */ -static int DetectNfsVersionSetup (DetectEngineCtx *de_ctx, Signature *s, - const char *rawstr) +static int DetectNfsVersionSetup(DetectEngineCtx *de_ctx, Signature *s, const char *rawstr) { SCLogDebug("\'%s\'", rawstr); diff --git a/src/detect-nfs-version.h b/src/detect-nfs-version.h index 84eda946119b..bba2738d2d99 100644 --- a/src/detect-nfs-version.h +++ b/src/detect-nfs-version.h @@ -25,6 +25,6 @@ #define __DETECT_NFS_VERSION_H__ /* prototypes */ -void DetectNfsVersionRegister (void); +void DetectNfsVersionRegister(void); #endif /* __DETECT_NFS_VERSION_H__ */ diff --git a/src/detect-noalert.c b/src/detect-noalert.c index dda060a4f069..f421b91971d1 100644 --- a/src/detect-noalert.c +++ b/src/detect-noalert.c @@ -28,9 +28,9 @@ #include "detect-noalert.h" #include "util-debug.h" -static int DetectNoalertSetup (DetectEngineCtx *, Signature *, const char *); +static int DetectNoalertSetup(DetectEngineCtx *, Signature *, const char *); -void DetectNoalertRegister (void) +void DetectNoalertRegister(void) { sigmatch_table[DETECT_NOALERT].name = "noalert"; sigmatch_table[DETECT_NOALERT].desc = "no alert will be generated by the rule"; @@ -39,7 +39,7 @@ void DetectNoalertRegister (void) sigmatch_table[DETECT_NOALERT].flags |= SIGMATCH_NOOPT; } -static int DetectNoalertSetup (DetectEngineCtx *de_ctx, Signature *s, const char *nullstr) +static int DetectNoalertSetup(DetectEngineCtx *de_ctx, Signature *s, const char *nullstr) { if (nullstr != NULL) { SCLogError("nocase has no value"); @@ -49,4 +49,3 @@ static int DetectNoalertSetup (DetectEngineCtx *de_ctx, Signature *s, const char s->flags |= SIG_FLAG_NOALERT; return 0; } - diff --git a/src/detect-noalert.h b/src/detect-noalert.h index abe39efcb9b9..ba8f2d4917d5 100644 --- a/src/detect-noalert.h +++ b/src/detect-noalert.h @@ -25,7 +25,6 @@ #define __DETECT_NOALERT_H__ /* prototypes */ -void DetectNoalertRegister (void); +void DetectNoalertRegister(void); #endif /* __DETECT_NOALERT_H__ */ - diff --git a/src/detect-nocase.c b/src/detect-nocase.c index deed7b2513da..55b74842bf79 100644 --- a/src/detect-nocase.c +++ b/src/detect-nocase.c @@ -34,7 +34,7 @@ #include "util-debug.h" -static int DetectNocaseSetup (DetectEngineCtx *, Signature *, const char *); +static int DetectNocaseSetup(DetectEngineCtx *, Signature *, const char *); void DetectNocaseRegister(void) { @@ -54,7 +54,7 @@ void DetectNocaseRegister(void) * \retval 0 ok * \retval -1 failure */ -static int DetectNocaseSetup (DetectEngineCtx *de_ctx, Signature *s, const char *nullstr) +static int DetectNocaseSetup(DetectEngineCtx *de_ctx, Signature *s, const char *nullstr) { SCEnter(); @@ -76,6 +76,6 @@ static int DetectNocaseSetup (DetectEngineCtx *de_ctx, Signature *s, const char DetectContentData *cd = (DetectContentData *)pm->ctx; ret = DetectContentConvertToNocase(de_ctx, cd); - end: +end: SCReturnInt(ret); } diff --git a/src/detect-nocase.h b/src/detect-nocase.h index 4ba6723eb7f2..b84c23121ecb 100644 --- a/src/detect-nocase.h +++ b/src/detect-nocase.h @@ -25,7 +25,6 @@ #define __DETECT_NOCASE_H__ /* prototypes */ -void DetectNocaseRegister (void); +void DetectNocaseRegister(void); #endif /* __DETECT_NOCASE_H__ */ - diff --git a/src/detect-offset.c b/src/detect-offset.c index dd56e9a48260..ce0053dee559 100644 --- a/src/detect-offset.c +++ b/src/detect-offset.c @@ -43,15 +43,16 @@ static int DetectOffsetSetup(DetectEngineCtx *, Signature *, const char *); -void DetectOffsetRegister (void) +void DetectOffsetRegister(void) { sigmatch_table[DETECT_OFFSET].name = "offset"; - sigmatch_table[DETECT_OFFSET].desc = "designate from which byte in the payload will be checked to find a match"; + sigmatch_table[DETECT_OFFSET].desc = + "designate from which byte in the payload will be checked to find a match"; sigmatch_table[DETECT_OFFSET].url = "/rules/payload-keywords.html#offset"; sigmatch_table[DETECT_OFFSET].Setup = DetectOffsetSetup; } -int DetectOffsetSetup (DetectEngineCtx *de_ctx, Signature *s, const char *offsetstr) +int DetectOffsetSetup(DetectEngineCtx *de_ctx, Signature *s, const char *offsetstr) { const char *str = offsetstr; @@ -101,15 +102,13 @@ int DetectOffsetSetup (DetectEngineCtx *de_ctx, Signature *s, const char *offset cd->offset = index; cd->flags |= DETECT_CONTENT_OFFSET_VAR; } else { - if (StringParseUint16(&cd->offset, 0, 0, str) < 0) - { + if (StringParseUint16(&cd->offset, 0, 0, str) < 0) { SCLogError("invalid value for offset: %s.", str); return -1; } if (cd->depth != 0) { if (cd->depth < cd->content_len) { - SCLogDebug("depth increased to %"PRIu32" to match pattern len", - cd->content_len); + SCLogDebug("depth increased to %" PRIu32 " to match pattern len", cd->content_len); cd->depth = cd->content_len; } /* Updating the depth as is relative to the offset */ @@ -119,4 +118,3 @@ int DetectOffsetSetup (DetectEngineCtx *de_ctx, Signature *s, const char *offset cd->flags |= DETECT_CONTENT_OFFSET; return 0; } - diff --git a/src/detect-offset.h b/src/detect-offset.h index 76befe17de3a..96f5ba064742 100644 --- a/src/detect-offset.h +++ b/src/detect-offset.h @@ -25,7 +25,6 @@ #define __DETECT_OFFSET_H__ /* prototypes */ -void DetectOffsetRegister (void); +void DetectOffsetRegister(void); #endif /* __DETECT_OFFSET_H__ */ - diff --git a/src/detect-parse.c b/src/detect-parse.c index ddee68c8513d..f2e6448c5067 100644 --- a/src/detect-parse.c +++ b/src/detect-parse.c @@ -130,9 +130,8 @@ SigTableElmt sigmatch_table[DETECT_TBLSIZE]; extern bool sc_set_caps; -static void SigMatchTransferSigMatchAcrossLists(SigMatch *sm, - SigMatch **src_sm_list, SigMatch **src_sm_list_tail, - SigMatch **dst_sm_list, SigMatch **dst_sm_list_tail); +static void SigMatchTransferSigMatchAcrossLists(SigMatch *sm, SigMatch **src_sm_list, + SigMatch **src_sm_list_tail, SigMatch **dst_sm_list, SigMatch **dst_sm_list_tail); /** * \brief Registration table for file handlers @@ -172,7 +171,10 @@ typedef struct SignatureParser_ { const char *DetectListToHumanString(int list) { -#define CASE_CODE_STRING(E, S) case E: return S; break +#define CASE_CODE_STRING(E, S) \ + case E: \ + return S; \ + break switch (list) { CASE_CODE_STRING(DETECT_SM_LIST_MATCH, "packet"); CASE_CODE_STRING(DETECT_SM_LIST_PMATCH, "payload"); @@ -187,7 +189,9 @@ const char *DetectListToHumanString(int list) return "unknown"; } -#define CASE_CODE(E) case E: return #E +#define CASE_CODE(E) \ + case E: \ + return #E const char *DetectListToString(int list) { switch (list) { @@ -204,9 +208,8 @@ const char *DetectListToString(int list) } /** \param arg NULL or empty string */ -int DetectEngineContentModifierBufferSetup(DetectEngineCtx *de_ctx, - Signature *s, const char *arg, int sm_type, int sm_list, - AppProto alproto) +int DetectEngineContentModifierBufferSetup(DetectEngineCtx *de_ctx, Signature *s, const char *arg, + int sm_type, int sm_list, AppProto alproto) { SigMatch *sm = NULL; int ret = -1; @@ -231,8 +234,7 @@ int DetectEngineContentModifierBufferSetup(DetectEngineCtx *de_ctx, goto end; } - sm = DetectGetLastSMByListId(s, - DETECT_SM_LIST_PMATCH, DETECT_CONTENT, -1); + sm = DetectGetLastSMByListId(s, DETECT_SM_LIST_PMATCH, DETECT_CONTENT, -1); if (sm == NULL) { SCLogError("\"%s\" keyword " "found inside the rule without a content context. " @@ -255,8 +257,7 @@ int DetectEngineContentModifierBufferSetup(DetectEngineCtx *de_ctx, goto end; } if (cd->flags & (DETECT_CONTENT_WITHIN | DETECT_CONTENT_DISTANCE)) { - SigMatch *pm = DetectGetLastSMByListPtr(s, sm->prev, - DETECT_CONTENT, DETECT_PCRE, -1); + SigMatch *pm = DetectGetLastSMByListPtr(s, sm->prev, DETECT_CONTENT, DETECT_PCRE, -1); if (pm != NULL) { if (pm->type == DETECT_CONTENT) { DetectContentData *tmp_cd = (DetectContentData *)pm->ctx; @@ -328,7 +329,7 @@ int DetectEngineContentModifierBufferSetup(DetectEngineCtx *de_ctx, } ret = 0; - end: +end: return ret; } @@ -378,9 +379,9 @@ static SigTableElmt *SigTableGet(char *name) st = &sigmatch_table[i]; if (st->name != NULL) { - if (strcasecmp(name,st->name) == 0) + if (strcasecmp(name, st->name) == 0) return st; - if (st->alias != NULL && strcasecmp(name,st->alias) == 0) + if (st->alias != NULL && strcasecmp(name, st->alias) == 0) return st; } } @@ -388,8 +389,7 @@ static SigTableElmt *SigTableGet(char *name) return NULL; } -bool SigMatchSilentErrorEnabled(const DetectEngineCtx *de_ctx, - const enum DetectKeywordId id) +bool SigMatchSilentErrorEnabled(const DetectEngineCtx *de_ctx, const enum DetectKeywordId id) { return de_ctx->sm_types_silent_error[id]; } @@ -649,16 +649,14 @@ SigMatch *DetectGetLastSMFromLists(const Signature *s, ...) for (int buf_type = 0; buf_type < DETECT_SM_LIST_MAX; buf_type++) { if (s->init_data->smlists[buf_type] == NULL) continue; - if (s->init_data->list != DETECT_SM_LIST_NOTSET && - buf_type != s->init_data->list) + if (s->init_data->list != DETECT_SM_LIST_NOTSET && buf_type != s->init_data->list) continue; int sm_type; va_list ap; va_start(ap, s); - for (sm_type = va_arg(ap, int); sm_type != -1; sm_type = va_arg(ap, int)) - { + for (sm_type = va_arg(ap, int); sm_type != -1; sm_type = va_arg(ap, int)) { sm_new = SigMatchGetLastSMByType(s->init_data->smlists_tail[buf_type], sm_type); if (sm_new == NULL) continue; @@ -689,8 +687,7 @@ SigMatch *DetectGetLastSMByListPtr(const Signature *s, SigMatch *sm_list, ...) va_list ap; va_start(ap, sm_list); - for (sm_type = va_arg(ap, int); sm_type != -1; sm_type = va_arg(ap, int)) - { + for (sm_type = va_arg(ap, int); sm_type != -1; sm_type = va_arg(ap, int)) { sm_new = SigMatchGetLastSMByType(sm_list, sm_type); if (sm_new == NULL) continue; @@ -787,9 +784,8 @@ SigMatch *DetectGetLastSM(const Signature *s) return sm_last; } -static void SigMatchTransferSigMatchAcrossLists(SigMatch *sm, - SigMatch **src_sm_list, SigMatch **src_sm_list_tail, - SigMatch **dst_sm_list, SigMatch **dst_sm_list_tail) +static void SigMatchTransferSigMatchAcrossLists(SigMatch *sm, SigMatch **src_sm_list, + SigMatch **src_sm_list_tail, SigMatch **dst_sm_list, SigMatch **dst_sm_list_tail) { /* we won't do any checks for args */ @@ -847,7 +843,8 @@ int SigMatchListSMBelongsTo(const Signature *s, const SigMatch *key_sm) return -1; } -static int SigParseOptions(DetectEngineCtx *de_ctx, Signature *s, char *optstr, char *output, size_t output_size) +static int SigParseOptions( + DetectEngineCtx *de_ctx, Signature *s, char *optstr, char *output, size_t output_size) { SigTableElmt *st = NULL; char *optname = NULL; @@ -865,8 +862,7 @@ static int SigParseOptions(DetectEngineCtx *de_ctx, Signature *s, char *optstr, if (optend == NULL) { SCLogError("no terminating \";\" found"); goto error; - } - else if (optend > optstr && *(optend -1 ) == '\\') { + } else if (optend > optstr && *(optend - 1) == '\\') { optend++; } else { break; @@ -908,7 +904,7 @@ static int SigParseOptions(DetectEngineCtx *de_ctx, Signature *s, char *optstr, goto error; } - if (!(st->flags & (SIGMATCH_NOOPT|SIGMATCH_OPTIONAL_OPT))) { + if (!(st->flags & (SIGMATCH_NOOPT | SIGMATCH_OPTIONAL_OPT))) { if (optvalue == NULL || strlen(optvalue) == 0) { SCLogError( "invalid formatting or malformed option to %s keyword: '%s'", optname, optstr); @@ -982,9 +978,8 @@ static int SigParseOptions(DetectEngineCtx *de_ctx, Signature *s, char *optstr, goto error; } - if ((st->flags & (SIGMATCH_QUOTES_OPTIONAL|SIGMATCH_QUOTES_MANDATORY)) - && ovlen && *ptr == '"') - { + if ((st->flags & (SIGMATCH_QUOTES_OPTIONAL | SIGMATCH_QUOTES_MANDATORY)) && ovlen && + *ptr == '"') { for (; ovlen > 0; ovlen--) { if (isblank(ptr[ovlen - 1])) { ptr[ovlen - 1] = '\0'; @@ -1055,8 +1050,7 @@ static int SigParseOptions(DetectEngineCtx *de_ctx, Signature *s, char *optstr, * * \retval 0 ok, -1 error */ -static int SigParseAddress(DetectEngineCtx *de_ctx, - Signature *s, const char *addrstr, char flag) +static int SigParseAddress(DetectEngineCtx *de_ctx, Signature *s, const char *addrstr, char flag) { SCLogDebug("Address Group \"%s\" to be parsed now", addrstr); @@ -1065,16 +1059,16 @@ static int SigParseAddress(DetectEngineCtx *de_ctx, if (strcasecmp(addrstr, "any") == 0) s->flags |= SIG_FLAG_SRC_ANY; - s->init_data->src = DetectParseAddress(de_ctx, addrstr, - &s->init_data->src_contains_negation); + s->init_data->src = + DetectParseAddress(de_ctx, addrstr, &s->init_data->src_contains_negation); if (s->init_data->src == NULL) goto error; } else { if (strcasecmp(addrstr, "any") == 0) s->flags |= SIG_FLAG_DST_ANY; - s->init_data->dst = DetectParseAddress(de_ctx, addrstr, - &s->init_data->dst_contains_negation); + s->init_data->dst = + DetectParseAddress(de_ctx, addrstr, &s->init_data->dst_contains_negation); if (s->init_data->dst == NULL) goto error; } @@ -1109,8 +1103,7 @@ static int SigParseProto(Signature *s, const char *protostr) s->flags |= SIG_FLAG_APPLAYER; AppLayerProtoDetectSupportedIpprotos(s->alproto, s->proto.proto); - } - else { + } else { SCLogError("protocol \"%s\" cannot be used " "in a signature. Either detection for this protocol " "is not yet supported OR detection has been disabled for " @@ -1144,8 +1137,7 @@ static int SigParseProto(Signature *s, const char *protostr) * \retval 0 On success. * \retval -1 On failure. */ -static int SigParsePort(const DetectEngineCtx *de_ctx, - Signature *s, const char *portstr, char flag) +static int SigParsePort(const DetectEngineCtx *de_ctx, Signature *s, const char *portstr, char flag) { int r = 0; @@ -1213,20 +1205,18 @@ static int SigParseAction(Signature *s, const char *action) s->action = ACTION_DROP; } else if (strcasecmp(action, "pass") == 0) { s->action = ACTION_PASS; - } else if (strcasecmp(action, "reject") == 0 || - strcasecmp(action, "rejectsrc") == 0) - { + } else if (strcasecmp(action, "reject") == 0 || strcasecmp(action, "rejectsrc") == 0) { if (!(SigParseActionRejectValidate(action))) return -1; - s->action = ACTION_REJECT|ACTION_DROP; + s->action = ACTION_REJECT | ACTION_DROP; } else if (strcasecmp(action, "rejectdst") == 0) { if (!(SigParseActionRejectValidate(action))) return -1; - s->action = ACTION_REJECT_DST|ACTION_DROP; + s->action = ACTION_REJECT_DST | ACTION_DROP; } else if (strcasecmp(action, "rejectboth") == 0) { if (!(SigParseActionRejectValidate(action))) return -1; - s->action = ACTION_REJECT_BOTH|ACTION_DROP; + s->action = ACTION_REJECT_BOTH | ACTION_DROP; } else if (strcasecmp(action, "config") == 0) { s->action = ACTION_CONFIG; s->flags |= SIG_FLAG_NOALERT; @@ -1248,8 +1238,7 @@ static int SigParseAction(Signature *s, const char *action) * \param output buffer to copy token into. * \param output_size length of output buffer. */ -static inline int SigParseToken(char **input, char *output, - const size_t output_size) +static inline int SigParseToken(char **input, char *output, const size_t output_size) { size_t len = *input == NULL ? 0 : strlen(*input); @@ -1283,8 +1272,7 @@ static inline int SigParseToken(char **input, char *output, * \param output buffer to copy token into. * \param output_size length of output buffer. */ -static inline int SigParseList(char **input, char *output, - const size_t output_size) +static inline int SigParseList(char **input, char *output, const size_t output_size) { int in_list = 0; size_t len = *input != NULL ? strlen(*input) : 0; @@ -1326,8 +1314,8 @@ static inline int SigParseList(char **input, char *output, * \internal * \brief split a signature string into a few blocks for further parsing */ -static int SigParseBasics(DetectEngineCtx *de_ctx, - Signature *s, const char *sigstr, SignatureParser *parser, uint8_t addrs_direction) +static int SigParseBasics(DetectEngineCtx *de_ctx, Signature *s, const char *sigstr, + SignatureParser *parser, uint8_t addrs_direction) { char *index, dup[DETECT_MAX_RULE_SIZE]; @@ -1390,7 +1378,7 @@ static int SigParseBasics(DetectEngineCtx *de_ctx, /* Parse Address & Ports */ if (SigParseAddress(de_ctx, s, parser->src, SIG_DIREC_SRC ^ addrs_direction) < 0) - goto error; + goto error; if (SigParseAddress(de_ctx, s, parser->dst, SIG_DIREC_DST ^ addrs_direction) < 0) goto error; @@ -1437,8 +1425,8 @@ static inline bool CheckAscii(const char *str) * \param -1 parse error * \param 0 ok */ -static int SigParse(DetectEngineCtx *de_ctx, Signature *s, - const char *sigstr, uint8_t addrs_direction, SignatureParser *parser) +static int SigParse(DetectEngineCtx *de_ctx, Signature *s, const char *sigstr, + uint8_t addrs_direction, SignatureParser *parser) { SCEnter(); @@ -1469,7 +1457,7 @@ static int SigParse(DetectEngineCtx *de_ctx, Signature *s, char input[buffer_size]; char output[buffer_size]; memset(input, 0x00, buffer_size); - memcpy(input, parser->opts, strlen(parser->opts)+1); + memcpy(input, parser->opts, strlen(parser->opts) + 1); /* loop the option parsing. Each run processes one option * and returns the rest of the option string through the @@ -1511,7 +1499,7 @@ int SignatureInitDataBufferCheckExpand(Signature *s) return 0; } -Signature *SigAlloc (void) +Signature *SigAlloc(void) { Signature *sig = SCCalloc(1, sizeof(Signature)); if (unlikely(sig == NULL)) @@ -1559,7 +1547,7 @@ static void SigMetadataFree(Signature *s) SCLogDebug("s %p, s->metadata %p", s, s->metadata); - for (mdata = s->metadata->list; mdata != NULL;) { + for (mdata = s->metadata->list; mdata != NULL;) { next_mdata = mdata->next; DetectMetadataFree(mdata); mdata = next_mdata; @@ -1577,7 +1565,7 @@ static void SigMetadataFree(Signature *s) * * \param s Pointer to the signature */ -static void SigRefFree (Signature *s) +static void SigRefFree(Signature *s) { SCEnter(); @@ -1590,7 +1578,7 @@ static void SigRefFree (Signature *s) SCLogDebug("s %p, s->references %p", s, s->references); - for (ref = s->references; ref != NULL;) { + for (ref = s->references; ref != NULL;) { next_ref = ref->next; DetectReferenceFree(ref); ref = next_ref; @@ -1609,7 +1597,7 @@ static void SigMatchFreeArrays(DetectEngineCtx *de_ctx, Signature *s, int ctxs) if (s->sm_arrays[type] != NULL) { if (ctxs) { SigMatchData *smd = s->sm_arrays[type]; - while(1) { + while (1) { if (sigmatch_table[smd->type].Free != NULL) { sigmatch_table[smd->type].Free(de_ctx, smd->ctx); } @@ -1639,7 +1627,7 @@ void SigFree(DetectEngineCtx *de_ctx, Signature *s) int i; if (s->init_data && s->init_data->transforms.cnt) { - for(i = 0; i < s->init_data->transforms.cnt; i++) { + for (i = 0; i < s->init_data->transforms.cnt; i++) { if (s->init_data->transforms.transforms[i].options) { int transform = s->init_data->transforms.transforms[i].transform; sigmatch_table[transform].Free( @@ -1727,17 +1715,14 @@ int DetectSignatureAddTransform(Signature *s, int transform, void *options) s->init_data->transforms.transforms[s->init_data->transforms.cnt].options = options; s->init_data->transforms.cnt++; - SCLogDebug("Added transform #%d [%s]", - s->init_data->transforms.cnt, - s->sig_str); + SCLogDebug("Added transform #%d [%s]", s->init_data->transforms.cnt, s->sig_str); SCReturnInt(0); } int DetectSignatureSetAppProto(Signature *s, AppProto alproto) { - if (alproto == ALPROTO_UNKNOWN || - alproto >= ALPROTO_FAILED) { + if (alproto == ALPROTO_UNKNOWN || alproto >= ALPROTO_FAILED) { SCLogError("invalid alproto %u", alproto); return -1; } @@ -1783,7 +1768,7 @@ static void SigBuildAddressMatchArray(Signature *s) uint16_t cnt = 0; uint16_t idx = 0; DetectAddress *da = s->init_data->src->ipv4_head; - for ( ; da != NULL; da = da->next) { + for (; da != NULL; da = da->next) { cnt++; } if (cnt > 0) { @@ -1804,7 +1789,7 @@ static void SigBuildAddressMatchArray(Signature *s) cnt = 0; idx = 0; da = s->init_data->dst->ipv4_head; - for ( ; da != NULL; da = da->next) { + for (; da != NULL; da = da->next) { cnt++; } if (cnt > 0) { @@ -1825,7 +1810,7 @@ static void SigBuildAddressMatchArray(Signature *s) cnt = 0; idx = 0; da = s->init_data->src->ipv6_head; - for ( ; da != NULL; da = da->next) { + for (; da != NULL; da = da->next) { cnt++; } if (cnt > 0) { @@ -1852,7 +1837,7 @@ static void SigBuildAddressMatchArray(Signature *s) cnt = 0; idx = 0; da = s->init_data->dst->ipv6_head; - for ( ; da != NULL; da = da->next) { + for (; da != NULL; da = da->next) { cnt++; } if (cnt > 0) { @@ -1888,7 +1873,7 @@ static int SigMatchListLen(SigMatch *sm) /** \brief convert SigMatch list to SigMatchData array * \note ownership of sm->ctx is transferred to smd->ctx */ -SigMatchData* SigMatchList2DataArray(SigMatch *head) +SigMatchData *SigMatchList2DataArray(SigMatch *head) { int len = SigMatchListLen(head); if (len == 0) @@ -2040,14 +2025,14 @@ static int SigValidate(DetectEngineCtx *de_ctx, Signature *s) SCLogDebug("%u: rule direction cannot be deduced from keywords", s->id); } - if ((s->flags & SIG_FLAG_REQUIRE_PACKET) && - (s->flags & SIG_FLAG_REQUIRE_STREAM)) { + if ((s->flags & SIG_FLAG_REQUIRE_PACKET) && (s->flags & SIG_FLAG_REQUIRE_STREAM)) { SCLogError("can't mix packet keywords with " "tcp-stream or flow:only_stream. Invalidating signature."); SCReturnInt(0); } - if ((sig_flags & (SIG_FLAG_TOCLIENT | SIG_FLAG_TOSERVER)) == (SIG_FLAG_TOCLIENT | SIG_FLAG_TOSERVER)) { + if ((sig_flags & (SIG_FLAG_TOCLIENT | SIG_FLAG_TOSERVER)) == + (SIG_FLAG_TOCLIENT | SIG_FLAG_TOSERVER)) { SCLogError("You seem to have mixed keywords " "that require inspection in both directions. Atm we only " "support keywords in one direction within a rule."); @@ -2079,7 +2064,7 @@ static int SigValidate(DetectEngineCtx *de_ctx, Signature *s) sm = sm->next) { if (sm->type == DETECT_CONTENT && (((DetectContentData *)(sm->ctx))->flags & - (DETECT_CONTENT_DEPTH | DETECT_CONTENT_OFFSET))) { + (DETECT_CONTENT_DEPTH | DETECT_CONTENT_OFFSET))) { s->flags |= SIG_FLAG_REQUIRE_PACKET; break; } @@ -2105,10 +2090,9 @@ static int SigValidate(DetectEngineCtx *de_ctx, Signature *s) SCReturnInt(0); } if ((s->flags & SIG_FLAG_FILESTORE) || s->file_flags != 0 || - (s->init_data->init_flags & SIG_FLAG_INIT_FILEDATA)) { + (s->init_data->init_flags & SIG_FLAG_INIT_FILEDATA)) { if (s->alproto != ALPROTO_UNKNOWN && - !AppLayerParserSupportsFiles(IPPROTO_TCP, s->alproto)) - { + !AppLayerParserSupportsFiles(IPPROTO_TCP, s->alproto)) { SCLogError("protocol %s doesn't " "support file matching", AppProtoToString(s->alproto)); @@ -2134,8 +2118,7 @@ static int SigValidate(DetectEngineCtx *de_ctx, Signature *s) * \internal * \brief Helper function for SigInit(). */ -static Signature *SigInitHelper(DetectEngineCtx *de_ctx, const char *sigstr, - uint8_t dir) +static Signature *SigInitHelper(DetectEngineCtx *de_ctx, const char *sigstr, uint8_t dir) { SignatureParser parser; memset(&parser, 0x00, sizeof(parser)); @@ -2152,8 +2135,7 @@ static Signature *SigInitHelper(DetectEngineCtx *de_ctx, const char *sigstr, de_ctx->sigerror_silent = true; de_ctx->sigerror_ok = true; goto error; - } - else if (ret == -2) { + } else if (ret == -2) { de_ctx->sigerror_silent = true; goto error; } else if (ret < 0) { @@ -2197,7 +2179,7 @@ static Signature *SigInitHelper(DetectEngineCtx *de_ctx, const char *sigstr, if (!(sig->flags & SIG_FLAG_APPLAYER)) { if (sig->init_data->smlists[DETECT_SM_LIST_MATCH] != NULL) { SigMatch *sm = sig->init_data->smlists[DETECT_SM_LIST_MATCH]; - for ( ; sm != NULL; sm = sm->next) { + for (; sm != NULL; sm = sm->next) { if (sigmatch_table[sm->type].Match != NULL) sig->init_data->init_flags |= SIG_FLAG_INIT_PACKET; } @@ -2207,15 +2189,15 @@ static Signature *SigInitHelper(DetectEngineCtx *de_ctx, const char *sigstr, } if (!(sig->init_data->init_flags & SIG_FLAG_INIT_FLOW)) { - if ((sig->flags & (SIG_FLAG_TOSERVER|SIG_FLAG_TOCLIENT)) == 0) { + if ((sig->flags & (SIG_FLAG_TOSERVER | SIG_FLAG_TOCLIENT)) == 0) { sig->flags |= SIG_FLAG_TOSERVER; sig->flags |= SIG_FLAG_TOCLIENT; } } - SCLogDebug("sig %"PRIu32" SIG_FLAG_APPLAYER: %s, SIG_FLAG_PACKET: %s", - sig->id, sig->flags & SIG_FLAG_APPLAYER ? "set" : "not set", - sig->init_data->init_flags & SIG_FLAG_INIT_PACKET ? "set" : "not set"); + SCLogDebug("sig %" PRIu32 " SIG_FLAG_APPLAYER: %s, SIG_FLAG_PACKET: %s", sig->id, + sig->flags & SIG_FLAG_APPLAYER ? "set" : "not set", + sig->init_data->init_flags & SIG_FLAG_INIT_PACKET ? "set" : "not set"); SigBuildAddressMatchArray(sig); @@ -2311,7 +2293,8 @@ Signature *SigInit(DetectEngineCtx *de_ctx, const char *sigstr) if (sig->init_data->init_flags & SIG_FLAG_INIT_BIDIREC) { if (SigHasSameSourceAndDestination(sig)) { SCLogInfo("Rule with ID %u is bidirectional, but source and destination are the same, " - "treating the rule as unidirectional", sig->id); + "treating the rule as unidirectional", + sig->id); sig->init_data->init_flags &= ~SIG_FLAG_INIT_BIDIREC; } else { @@ -2378,18 +2361,17 @@ static uint32_t DetectParseDupSigHashFunc(HashListTable *ht, void *data, uint16_ * \retval 1 If the 2 SigDuplWrappers sent as args match. * \retval 0 If the 2 SigDuplWrappers sent as args do not match. */ -static char DetectParseDupSigCompareFunc(void *data1, uint16_t len1, void *data2, - uint16_t len2) +static char DetectParseDupSigCompareFunc(void *data1, uint16_t len1, void *data2, uint16_t len2) { SigDuplWrapper *sw1 = (SigDuplWrapper *)data1; SigDuplWrapper *sw2 = (SigDuplWrapper *)data2; - if (sw1 == NULL || sw2 == NULL || - sw1->s == NULL || sw2->s == NULL) + if (sw1 == NULL || sw2 == NULL || sw1->s == NULL || sw2->s == NULL) return 0; /* sid and gid match required */ - if (sw1->s->id == sw2->s->id && sw1->s->gid == sw2->s->gid) return 1; + if (sw1->s->id == sw2->s->id && sw1->s->gid == sw2->s->gid) + return 1; return 0; } @@ -2404,10 +2386,8 @@ static char DetectParseDupSigCompareFunc(void *data1, uint16_t len1, void *data2 */ int DetectParseDupSigHashInit(DetectEngineCtx *de_ctx) { - de_ctx->dup_sig_hash_table = HashListTableInit(15000, - DetectParseDupSigHashFunc, - DetectParseDupSigCompareFunc, - DetectParseDupSigFreeFunc); + de_ctx->dup_sig_hash_table = HashListTableInit(15000, DetectParseDupSigHashFunc, + DetectParseDupSigCompareFunc, DetectParseDupSigFreeFunc); if (de_ctx->dup_sig_hash_table == NULL) return -1; @@ -2449,8 +2429,7 @@ void DetectParseDupSigHashFree(DetectEngineCtx *de_ctx) * \retval 1 If Signature is duplicate, and should be chucked out. * \retval 0 If Signature is not a duplicate. */ -static inline int DetectEngineSignatureIsDuplicate(DetectEngineCtx *de_ctx, - Signature *sig) +static inline int DetectEngineSignatureIsDuplicate(DetectEngineCtx *de_ctx, Signature *sig) { /* we won't do any NULL checks on the args */ @@ -2482,8 +2461,7 @@ static inline int DetectEngineSignatureIsDuplicate(DetectEngineCtx *de_ctx, /* the topmost sig would be the last loaded sig */ sw_tmp.s = de_ctx->sig_list; - sw_old = HashListTableLookup(de_ctx->dup_sig_hash_table, - (void *)&sw_tmp, 0); + sw_old = HashListTableLookup(de_ctx->dup_sig_hash_table, (void *)&sw_tmp, 0); /* sw_old == NULL case is impossible */ sw_old->s_prev = sig; } @@ -2517,8 +2495,7 @@ static inline int DetectEngineSignatureIsDuplicate(DetectEngineCtx *de_ctx, } SigDuplWrapper *sw_next = NULL; if (sw_temp.s != NULL) { - sw_next = HashListTableLookup(de_ctx->dup_sig_hash_table, - (void *)&sw_temp, 0); + sw_next = HashListTableLookup(de_ctx->dup_sig_hash_table, (void *)&sw_temp, 0); sw_next->s_prev = sw_dup->s_prev; } SigFree(de_ctx, sw_dup->s); @@ -2547,8 +2524,7 @@ static inline int DetectEngineSignatureIsDuplicate(DetectEngineCtx *de_ctx, } SigDuplWrapper *sw_next = NULL; if (sw_temp.s != NULL) { - sw_next = HashListTableLookup(de_ctx->dup_sig_hash_table, - (void *)&sw_temp, 0); + sw_next = HashListTableLookup(de_ctx->dup_sig_hash_table, (void *)&sw_temp, 0); sw_next->s_prev = sw_dup->s_prev; } SigFree(de_ctx, sw_dup->s); @@ -2562,8 +2538,8 @@ static inline int DetectEngineSignatureIsDuplicate(DetectEngineCtx *de_ctx, SigDuplWrapper sw_tmp; memset(&sw_tmp, 0, sizeof(SigDuplWrapper)); sw_tmp.s = de_ctx->sig_list; - SigDuplWrapper *sw_old = HashListTableLookup(de_ctx->dup_sig_hash_table, - (void *)&sw_tmp, 0); + SigDuplWrapper *sw_old = + HashListTableLookup(de_ctx->dup_sig_hash_table, (void *)&sw_tmp, 0); if (sw_old->s != sw_dup->s) { // Link on top of the list if there was another element sw_old->s_prev = sig; @@ -2784,7 +2760,6 @@ void DetectSetupParseRegexes(const char *parse_str, DetectParseRegex *detect_par } } - /* * TESTS */ @@ -2793,7 +2768,7 @@ void DetectSetupParseRegexes(const char *parse_str, DetectParseRegex *detect_par #include "detect-engine-alert.h" #include "packet.h" -static int SigParseTest01 (void) +static int SigParseTest01(void) { int result = 1; Signature *sig = NULL; @@ -2807,12 +2782,14 @@ static int SigParseTest01 (void) result = 0; end: - if (sig != NULL) SigFree(de_ctx, sig); - if (de_ctx != NULL) DetectEngineCtxFree(de_ctx); + if (sig != NULL) + SigFree(de_ctx, sig); + if (de_ctx != NULL) + DetectEngineCtxFree(de_ctx); return result; } -static int SigParseTest02 (void) +static int SigParseTest02(void) { int result = 0; Signature *sig = NULL; @@ -2826,7 +2803,9 @@ static int SigParseTest02 (void) FILE *fd = SCClassConfGenerateValidDummyClassConfigFD01(); SCClassConfLoadClassificationConfigFile(de_ctx, fd); - sig = SigInit(de_ctx, "alert tcp any !21:902 -> any any (msg:\"ET MALWARE Suspicious 220 Banner on Local Port\"; content:\"220\"; offset:0; depth:4; pcre:\"/220[- ]/\"; sid:2003055; rev:4;)"); + sig = SigInit(de_ctx, + "alert tcp any !21:902 -> any any (msg:\"ET MALWARE Suspicious 220 Banner on Local " + "Port\"; content:\"220\"; offset:0; depth:4; pcre:\"/220[- ]/\"; sid:2003055; rev:4;)"); if (sig == NULL) { goto end; } @@ -2838,7 +2817,10 @@ static int SigParseTest02 (void) if (DetectPortCmp(sig->sp, port) == PORT_EQ) { result = 1; } else { - DetectPortPrint(port); printf(" != "); DetectPortPrint(sig->sp); printf(": "); + DetectPortPrint(port); + printf(" != "); + DetectPortPrint(sig->sp); + printf(": "); } end: @@ -2854,7 +2836,7 @@ static int SigParseTest02 (void) /** * \test SigParseTest03 test for invalid direction operator in rule */ -static int SigParseTest03 (void) +static int SigParseTest03(void) { int result = 1; Signature *sig = NULL; @@ -2866,16 +2848,18 @@ static int SigParseTest03 (void) sig = SigInit(de_ctx, "alert tcp 1.2.3.4 any <- !1.2.3.4 any (msg:\"SigParseTest03\"; sid:1;)"); if (sig != NULL) { result = 0; - printf("expected NULL got sig ptr %p: ",sig); + printf("expected NULL got sig ptr %p: ", sig); } end: - if (sig != NULL) SigFree(de_ctx, sig); - if (de_ctx != NULL) DetectEngineCtxFree(de_ctx); + if (sig != NULL) + SigFree(de_ctx, sig); + if (de_ctx != NULL) + DetectEngineCtxFree(de_ctx); return result; } -static int SigParseTest04 (void) +static int SigParseTest04(void) { int result = 1; Signature *sig = NULL; @@ -2884,18 +2868,21 @@ static int SigParseTest04 (void) if (de_ctx == NULL) goto end; - sig = SigInit(de_ctx, "alert tcp 1.2.3.4 1024: -> !1.2.3.4 1024: (msg:\"SigParseTest04\"; sid:1;)"); + sig = SigInit( + de_ctx, "alert tcp 1.2.3.4 1024: -> !1.2.3.4 1024: (msg:\"SigParseTest04\"; sid:1;)"); if (sig == NULL) result = 0; end: - if (sig != NULL) SigFree(de_ctx, sig); - if (de_ctx != NULL) DetectEngineCtxFree(de_ctx); + if (sig != NULL) + SigFree(de_ctx, sig); + if (de_ctx != NULL) + DetectEngineCtxFree(de_ctx); return result; } /** \test Port validation */ -static int SigParseTest05 (void) +static int SigParseTest05(void) { int result = 0; Signature *sig = NULL; @@ -2904,7 +2891,8 @@ static int SigParseTest05 (void) if (de_ctx == NULL) goto end; - sig = SigInit(de_ctx, "alert tcp 1.2.3.4 1024:65536 -> !1.2.3.4 any (msg:\"SigParseTest05\"; sid:1;)"); + sig = SigInit(de_ctx, + "alert tcp 1.2.3.4 1024:65536 -> !1.2.3.4 any (msg:\"SigParseTest05\"; sid:1;)"); if (sig == NULL) { result = 1; } else { @@ -2912,13 +2900,15 @@ static int SigParseTest05 (void) } end: - if (sig != NULL) SigFree(de_ctx, sig); - if (de_ctx != NULL) DetectEngineCtxFree(de_ctx); + if (sig != NULL) + SigFree(de_ctx, sig); + if (de_ctx != NULL) + DetectEngineCtxFree(de_ctx); return result; } /** \test Parsing bug debugging at 2010-03-18 */ -static int SigParseTest06 (void) +static int SigParseTest06(void) { int result = 0; Signature *sig = NULL; @@ -2927,7 +2917,9 @@ static int SigParseTest06 (void) if (de_ctx == NULL) goto end; - sig = SigInit(de_ctx, "alert tcp any any -> any any (flow:to_server; content:\"GET\"; nocase; http_method; uricontent:\"/uri/\"; nocase; content:\"Host|3A| abc\"; nocase; sid:1; rev:1;)"); + sig = SigInit(de_ctx, + "alert tcp any any -> any any (flow:to_server; content:\"GET\"; nocase; http_method; " + "uricontent:\"/uri/\"; nocase; content:\"Host|3A| abc\"; nocase; sid:1; rev:1;)"); if (sig != NULL) { result = 1; } else { @@ -3003,8 +2995,7 @@ static int SigParseTest09(void) DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any (msg:\"boo\"; sid:1; rev:6;)"); DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any (msg:\"boo\"; sid:1; rev:4;)"); DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any (msg:\"boo\"; sid:2; rev:2;)"); - result &= (de_ctx->sig_list != NULL && de_ctx->sig_list->id == 2 && - de_ctx->sig_list->rev == 2); + result &= (de_ctx->sig_list != NULL && de_ctx->sig_list->id == 2 && de_ctx->sig_list->rev == 2); if (result == 0) goto end; result &= (de_ctx->sig_list->next != NULL && de_ctx->sig_list->next->id == 1 && @@ -3013,8 +3004,7 @@ static int SigParseTest09(void) goto end; DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any (msg:\"boo\"; sid:2; rev:1;)"); - result &= (de_ctx->sig_list != NULL && de_ctx->sig_list->id == 2 && - de_ctx->sig_list->rev == 2); + result &= (de_ctx->sig_list != NULL && de_ctx->sig_list->id == 2 && de_ctx->sig_list->rev == 2); if (result == 0) goto end; result &= (de_ctx->sig_list->next != NULL && de_ctx->sig_list->next->id == 1 && @@ -3023,8 +3013,7 @@ static int SigParseTest09(void) goto end; DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any (msg:\"boo\"; sid:2; rev:4;)"); - result &= (de_ctx->sig_list != NULL && de_ctx->sig_list->id == 2 && - de_ctx->sig_list->rev == 4); + result &= (de_ctx->sig_list != NULL && de_ctx->sig_list->id == 2 && de_ctx->sig_list->rev == 4); if (result == 0) goto end; result &= (de_ctx->sig_list->next != NULL && de_ctx->sig_list->next->id == 1 && @@ -3057,8 +3046,7 @@ static int SigParseTest10(void) DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any (msg:\"boo\"; sid:3; rev:2;)"); DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any (msg:\"boo\"; sid:2; rev:2;)"); - result &= ((de_ctx->sig_list->id == 2) && - (de_ctx->sig_list->next->id == 3) && + result &= ((de_ctx->sig_list->id == 2) && (de_ctx->sig_list->next->id == 3) && (de_ctx->sig_list->next->next->id == 5) && (de_ctx->sig_list->next->next->next->id == 4) && (de_ctx->sig_list->next->next->next->next->id == 1)); @@ -3117,7 +3105,8 @@ static int SigParseTest12(void) Signature *s = NULL; - s = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any (file_data; content:\"abc\"; rawbytes; sid:1;)"); + s = DetectEngineAppendSig( + de_ctx, "alert tcp any any -> any any (file_data; content:\"abc\"; rawbytes; sid:1;)"); if (s != NULL) { printf("sig 1 should have given an error: "); goto end; @@ -3180,7 +3169,8 @@ static int SigParseTest14(void) Signature *s = NULL; - s = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any (content:\"abc\"; dsize:>0; sid:1;)"); + s = DetectEngineAppendSig( + de_ctx, "alert tcp any any -> any any (content:\"abc\"; dsize:>0; sid:1;)"); if (s == NULL) { printf("sig 1 invalidated: failure"); goto end; @@ -3217,7 +3207,8 @@ static int SigParseTest15(void) Signature *s = NULL; - s = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any (content:\"abc\"; offset:5; sid:1;)"); + s = DetectEngineAppendSig( + de_ctx, "alert tcp any any -> any any (content:\"abc\"; offset:5; sid:1;)"); if (s == NULL) { printf("sig 1 invalidated: failure"); goto end; @@ -3254,7 +3245,8 @@ static int SigParseTest16(void) Signature *s = NULL; - s = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any (content:\"abc\"; depth:5; sid:1;)"); + s = DetectEngineAppendSig( + de_ctx, "alert tcp any any -> any any (content:\"abc\"; depth:5; sid:1;)"); if (s == NULL) { printf("sig 1 invalidated: failure"); goto end; @@ -3291,7 +3283,8 @@ static int SigParseTest17(void) Signature *s = NULL; - s = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any (content:\"abc\"; offset:1; depth:5; sid:1;)"); + s = DetectEngineAppendSig( + de_ctx, "alert tcp any any -> any any (content:\"abc\"; offset:1; depth:5; sid:1;)"); if (s == NULL) { printf("sig 1 invalidated: failure"); goto end; @@ -3316,7 +3309,7 @@ static int SigParseTest17(void) } /** \test sid value too large. Bug #779 */ -static int SigParseTest18 (void) +static int SigParseTest18(void) { int result = 0; @@ -3324,7 +3317,9 @@ static int SigParseTest18 (void) if (de_ctx == NULL) goto end; - if (DetectEngineAppendSig(de_ctx, "alert tcp 1.2.3.4 any -> !1.2.3.4 any (msg:\"SigParseTest01\"; sid:99999999999999999999;)") != NULL) + if (DetectEngineAppendSig(de_ctx, "alert tcp 1.2.3.4 any -> !1.2.3.4 any " + "(msg:\"SigParseTest01\"; sid:99999999999999999999;)") != + NULL) goto end; result = 1; @@ -3335,7 +3330,7 @@ static int SigParseTest18 (void) } /** \test gid value too large. Related to bug #779 */ -static int SigParseTest19 (void) +static int SigParseTest19(void) { int result = 0; @@ -3343,7 +3338,9 @@ static int SigParseTest19 (void) if (de_ctx == NULL) goto end; - if (DetectEngineAppendSig(de_ctx, "alert tcp 1.2.3.4 any -> !1.2.3.4 any (msg:\"SigParseTest01\"; sid:1; gid:99999999999999999999;)") != NULL) + if (DetectEngineAppendSig( + de_ctx, "alert tcp 1.2.3.4 any -> !1.2.3.4 any (msg:\"SigParseTest01\"; sid:1; " + "gid:99999999999999999999;)") != NULL) goto end; result = 1; @@ -3354,7 +3351,7 @@ static int SigParseTest19 (void) } /** \test rev value too large. Related to bug #779 */ -static int SigParseTest20 (void) +static int SigParseTest20(void) { int result = 0; @@ -3362,7 +3359,9 @@ static int SigParseTest20 (void) if (de_ctx == NULL) goto end; - if (DetectEngineAppendSig(de_ctx, "alert tcp 1.2.3.4 any -> !1.2.3.4 any (msg:\"SigParseTest01\"; sid:1; rev:99999999999999999999;)") != NULL) + if (DetectEngineAppendSig( + de_ctx, "alert tcp 1.2.3.4 any -> !1.2.3.4 any (msg:\"SigParseTest01\"; sid:1; " + "rev:99999999999999999999;)") != NULL) goto end; result = 1; @@ -3373,7 +3372,7 @@ static int SigParseTest20 (void) } /** \test address parsing */ -static int SigParseTest21 (void) +static int SigParseTest21(void) { int result = 0; @@ -3381,7 +3380,8 @@ static int SigParseTest21 (void) if (de_ctx == NULL) goto end; - if (DetectEngineAppendSig(de_ctx, "alert tcp [1.2.3.4, 1.2.3.5] any -> !1.2.3.4 any (sid:1;)") == NULL) + if (DetectEngineAppendSig( + de_ctx, "alert tcp [1.2.3.4, 1.2.3.5] any -> !1.2.3.4 any (sid:1;)") == NULL) goto end; result = 1; @@ -3392,7 +3392,7 @@ static int SigParseTest21 (void) } /** \test address parsing */ -static int SigParseTest22 (void) +static int SigParseTest22(void) { int result = 0; @@ -3400,7 +3400,8 @@ static int SigParseTest22 (void) if (de_ctx == NULL) goto end; - if (DetectEngineAppendSig(de_ctx, "alert tcp [10.10.10.0/24, !10.10.10.247] any -> [10.10.10.0/24, !10.10.10.247] any (sid:1;)") == NULL) + if (DetectEngineAppendSig(de_ctx, "alert tcp [10.10.10.0/24, !10.10.10.247] any -> " + "[10.10.10.0/24, !10.10.10.247] any (sid:1;)") == NULL) goto end; result = 1; @@ -3420,7 +3421,8 @@ static int SigParseTest23(void) Signature *s = NULL; - s = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any (content:\"abc\"; offset:1; depth:5; sid:1;)\r"); + s = DetectEngineAppendSig( + de_ctx, "alert tcp any any -> any any (content:\"abc\"; offset:1; depth:5; sid:1;)\r"); FAIL_IF_NULL(s); DetectEngineCtxFree(de_ctx); @@ -3428,7 +3430,7 @@ static int SigParseTest23(void) } /** \test Direction operator validation (invalid) */ -static int SigParseBidirecTest06 (void) +static int SigParseBidirecTest06(void) { int result = 1; Signature *sig = NULL; @@ -3437,18 +3439,21 @@ static int SigParseBidirecTest06 (void) if (de_ctx == NULL) goto end; - sig = DetectEngineAppendSig(de_ctx, "alert tcp 192.168.1.1 any - 192.168.1.5 any (msg:\"SigParseBidirecTest05\"; sid:1;)"); + sig = DetectEngineAppendSig(de_ctx, + "alert tcp 192.168.1.1 any - 192.168.1.5 any (msg:\"SigParseBidirecTest05\"; sid:1;)"); if (sig == NULL) result = 1; end: - if (sig != NULL) SigFree(de_ctx, sig); - if (de_ctx != NULL) DetectEngineCtxFree(de_ctx); + if (sig != NULL) + SigFree(de_ctx, sig); + if (de_ctx != NULL) + DetectEngineCtxFree(de_ctx); return result; } /** \test Direction operator validation (invalid) */ -static int SigParseBidirecTest07 (void) +static int SigParseBidirecTest07(void) { int result = 1; Signature *sig = NULL; @@ -3457,18 +3462,21 @@ static int SigParseBidirecTest07 (void) if (de_ctx == NULL) goto end; - sig = DetectEngineAppendSig(de_ctx, "alert tcp 192.168.1.1 any <- 192.168.1.5 any (msg:\"SigParseBidirecTest05\"; sid:1;)"); + sig = DetectEngineAppendSig(de_ctx, + "alert tcp 192.168.1.1 any <- 192.168.1.5 any (msg:\"SigParseBidirecTest05\"; sid:1;)"); if (sig == NULL) result = 1; end: - if (sig != NULL) SigFree(de_ctx, sig); - if (de_ctx != NULL) DetectEngineCtxFree(de_ctx); + if (sig != NULL) + SigFree(de_ctx, sig); + if (de_ctx != NULL) + DetectEngineCtxFree(de_ctx); return result; } /** \test Direction operator validation (invalid) */ -static int SigParseBidirecTest08 (void) +static int SigParseBidirecTest08(void) { int result = 1; Signature *sig = NULL; @@ -3477,18 +3485,21 @@ static int SigParseBidirecTest08 (void) if (de_ctx == NULL) goto end; - sig = DetectEngineAppendSig(de_ctx, "alert tcp 192.168.1.1 any < 192.168.1.5 any (msg:\"SigParseBidirecTest05\"; sid:1;)"); + sig = DetectEngineAppendSig(de_ctx, + "alert tcp 192.168.1.1 any < 192.168.1.5 any (msg:\"SigParseBidirecTest05\"; sid:1;)"); if (sig == NULL) result = 1; end: - if (sig != NULL) SigFree(de_ctx, sig); - if (de_ctx != NULL) DetectEngineCtxFree(de_ctx); + if (sig != NULL) + SigFree(de_ctx, sig); + if (de_ctx != NULL) + DetectEngineCtxFree(de_ctx); return result; } /** \test Direction operator validation (invalid) */ -static int SigParseBidirecTest09 (void) +static int SigParseBidirecTest09(void) { int result = 1; Signature *sig = NULL; @@ -3497,18 +3508,21 @@ static int SigParseBidirecTest09 (void) if (de_ctx == NULL) goto end; - sig = DetectEngineAppendSig(de_ctx, "alert tcp 192.168.1.1 any > 192.168.1.5 any (msg:\"SigParseBidirecTest05\"; sid:1;)"); + sig = DetectEngineAppendSig(de_ctx, + "alert tcp 192.168.1.1 any > 192.168.1.5 any (msg:\"SigParseBidirecTest05\"; sid:1;)"); if (sig == NULL) result = 1; end: - if (sig != NULL) SigFree(de_ctx, sig); - if (de_ctx != NULL) DetectEngineCtxFree(de_ctx); + if (sig != NULL) + SigFree(de_ctx, sig); + if (de_ctx != NULL) + DetectEngineCtxFree(de_ctx); return result; } /** \test Direction operator validation (invalid) */ -static int SigParseBidirecTest10 (void) +static int SigParseBidirecTest10(void) { int result = 1; Signature *sig = NULL; @@ -3517,18 +3531,21 @@ static int SigParseBidirecTest10 (void) if (de_ctx == NULL) goto end; - sig = DetectEngineAppendSig(de_ctx, "alert tcp 192.168.1.1 any -< 192.168.1.5 any (msg:\"SigParseBidirecTest05\"; sid:1;)"); + sig = DetectEngineAppendSig(de_ctx, + "alert tcp 192.168.1.1 any -< 192.168.1.5 any (msg:\"SigParseBidirecTest05\"; sid:1;)"); if (sig == NULL) result = 1; end: - if (sig != NULL) SigFree(de_ctx, sig); - if (de_ctx != NULL) DetectEngineCtxFree(de_ctx); + if (sig != NULL) + SigFree(de_ctx, sig); + if (de_ctx != NULL) + DetectEngineCtxFree(de_ctx); return result; } /** \test Direction operator validation (invalid) */ -static int SigParseBidirecTest11 (void) +static int SigParseBidirecTest11(void) { int result = 1; Signature *sig = NULL; @@ -3537,18 +3554,21 @@ static int SigParseBidirecTest11 (void) if (de_ctx == NULL) goto end; - sig = DetectEngineAppendSig(de_ctx, "alert tcp 192.168.1.1 any >- 192.168.1.5 any (msg:\"SigParseBidirecTest05\"; sid:1;)"); + sig = DetectEngineAppendSig(de_ctx, + "alert tcp 192.168.1.1 any >- 192.168.1.5 any (msg:\"SigParseBidirecTest05\"; sid:1;)"); if (sig == NULL) result = 1; end: - if (sig != NULL) SigFree(de_ctx, sig); - if (de_ctx != NULL) DetectEngineCtxFree(de_ctx); + if (sig != NULL) + SigFree(de_ctx, sig); + if (de_ctx != NULL) + DetectEngineCtxFree(de_ctx); return result; } /** \test Direction operator validation (invalid) */ -static int SigParseBidirecTest12 (void) +static int SigParseBidirecTest12(void) { int result = 1; Signature *sig = NULL; @@ -3557,18 +3577,21 @@ static int SigParseBidirecTest12 (void) if (de_ctx == NULL) goto end; - sig = DetectEngineAppendSig(de_ctx, "alert tcp 192.168.1.1 any >< 192.168.1.5 any (msg:\"SigParseBidirecTest05\"; sid:1;)"); + sig = DetectEngineAppendSig(de_ctx, + "alert tcp 192.168.1.1 any >< 192.168.1.5 any (msg:\"SigParseBidirecTest05\"; sid:1;)"); if (sig == NULL) result = 1; end: - if (sig != NULL) SigFree(de_ctx, sig); - if (de_ctx != NULL) DetectEngineCtxFree(de_ctx); + if (sig != NULL) + SigFree(de_ctx, sig); + if (de_ctx != NULL) + DetectEngineCtxFree(de_ctx); return result; } /** \test Direction operator validation (valid) */ -static int SigParseBidirecTest13 (void) +static int SigParseBidirecTest13(void) { int result = 1; Signature *sig = NULL; @@ -3577,17 +3600,19 @@ static int SigParseBidirecTest13 (void) if (de_ctx == NULL) goto end; - sig = DetectEngineAppendSig(de_ctx, "alert tcp 192.168.1.1 any <> 192.168.1.5 any (msg:\"SigParseBidirecTest05\"; sid:1;)"); + sig = DetectEngineAppendSig(de_ctx, + "alert tcp 192.168.1.1 any <> 192.168.1.5 any (msg:\"SigParseBidirecTest05\"; sid:1;)"); if (sig != NULL) result = 1; end: - if (de_ctx != NULL) DetectEngineCtxFree(de_ctx); + if (de_ctx != NULL) + DetectEngineCtxFree(de_ctx); return result; } /** \test Direction operator validation (valid) */ -static int SigParseBidirecTest14 (void) +static int SigParseBidirecTest14(void) { int result = 1; Signature *sig = NULL; @@ -3596,19 +3621,21 @@ static int SigParseBidirecTest14 (void) if (de_ctx == NULL) goto end; - sig = DetectEngineAppendSig(de_ctx, "alert tcp 192.168.1.1 any -> 192.168.1.5 any (msg:\"SigParseBidirecTest05\"; sid:1;)"); + sig = DetectEngineAppendSig(de_ctx, + "alert tcp 192.168.1.1 any -> 192.168.1.5 any (msg:\"SigParseBidirecTest05\"; sid:1;)"); if (sig != NULL) result = 1; end: - if (de_ctx != NULL) DetectEngineCtxFree(de_ctx); + if (de_ctx != NULL) + DetectEngineCtxFree(de_ctx); return result; } /** \test Ensure that we don't set bidirectional in a * normal (one direction) Signature */ -static int SigTestBidirec01 (void) +static int SigTestBidirec01(void) { Signature *sig = NULL; int result = 0; @@ -3617,7 +3644,8 @@ static int SigTestBidirec01 (void) if (de_ctx == NULL) goto end; - sig = DetectEngineAppendSig(de_ctx, "alert tcp 1.2.3.4 1024:65535 -> !1.2.3.4 any (msg:\"SigTestBidirec01\"; sid:1;)"); + sig = DetectEngineAppendSig(de_ctx, + "alert tcp 1.2.3.4 1024:65535 -> !1.2.3.4 any (msg:\"SigTestBidirec01\"; sid:1;)"); if (sig == NULL) goto end; if (sig->next != NULL) @@ -3639,7 +3667,7 @@ static int SigTestBidirec01 (void) } /** \test Ensure that we set a bidirectional Signature correctly */ -static int SigTestBidirec02 (void) +static int SigTestBidirec02(void) { int result = 0; Signature *sig = NULL; @@ -3651,7 +3679,8 @@ static int SigTestBidirec02 (void) de_ctx->flags |= DE_QUIET; - sig = DetectEngineAppendSig(de_ctx, "alert tcp 1.2.3.4 1024:65535 <> !1.2.3.4 any (msg:\"SigTestBidirec02\"; sid:1;)"); + sig = DetectEngineAppendSig(de_ctx, + "alert tcp 1.2.3.4 1024:65535 <> !1.2.3.4 any (msg:\"SigTestBidirec02\"; sid:1;)"); if (sig == NULL) goto end; if (de_ctx->sig_list != sig) @@ -3681,10 +3710,10 @@ static int SigTestBidirec02 (void) } /** \test Ensure that we set a bidirectional Signature correctly -* and we install it with the rest of the signatures, checking -* also that it match with the correct addr directions -*/ -static int SigTestBidirec03 (void) + * and we install it with the rest of the signatures, checking + * also that it match with the correct addr directions + */ +static int SigTestBidirec03(void) { int result = 0; Signature *sig = NULL; @@ -3698,7 +3727,8 @@ static int SigTestBidirec03 (void) const char *sigs[3]; sigs[0] = "alert tcp any any -> 192.168.1.1 any (msg:\"SigTestBidirec03 sid 1\"; sid:1;)"; - sigs[1] = "alert tcp any any <> 192.168.1.1 any (msg:\"SigTestBidirec03 sid 2 bidirectional\"; sid:2;)"; + sigs[1] = "alert tcp any any <> 192.168.1.1 any (msg:\"SigTestBidirec03 sid 2 bidirectional\"; " + "sid:2;)"; sigs[2] = "alert tcp any any -> 192.168.1.1 any (msg:\"SigTestBidirec03 sid 3\"; sid:3;)"; UTHAppendSigs(de_ctx, sigs, 3); diff --git a/src/detect-parse.h b/src/detect-parse.h index 2eecd286f631..524e42194910 100644 --- a/src/detect-parse.h +++ b/src/detect-parse.h @@ -45,19 +45,13 @@ void DetectFileRegisterFileProtocols(DetectFileHandlerTableElmt *entry); extern DetectFileHandlerTableElmt filehandler_table[DETECT_TBLSIZE]; /** Flags to indicate if the Signature parsing must be done -* switching the source and dest (for ip addresses and ports) -* or otherwise as normal */ -enum { - SIG_DIREC_NORMAL, - SIG_DIREC_SWITCHED -}; + * switching the source and dest (for ip addresses and ports) + * or otherwise as normal */ +enum { SIG_DIREC_NORMAL, SIG_DIREC_SWITCHED }; /** Flags to indicate if are referencing the source of the Signature -* or the destination (for ip addresses and ports)*/ -enum { - SIG_DIREC_SRC, - SIG_DIREC_DST -}; + * or the destination (for ip addresses and ports)*/ +enum { SIG_DIREC_SRC, SIG_DIREC_DST }; typedef struct DetectParseRegex { pcre2_code *regex; @@ -71,7 +65,7 @@ int SignatureInitDataBufferCheckExpand(Signature *s); Signature *SigAlloc(void); void SigFree(DetectEngineCtx *de_ctx, Signature *s); Signature *SigInit(DetectEngineCtx *, const char *sigstr); -SigMatchData* SigMatchList2DataArray(SigMatch *head); +SigMatchData *SigMatchList2DataArray(SigMatch *head); void SigParseRegisterTests(void); Signature *DetectEngineAppendSig(DetectEngineCtx *, const char *); @@ -82,12 +76,10 @@ int SigMatchListSMBelongsTo(const Signature *, const SigMatch *); int DetectParseDupSigHashInit(DetectEngineCtx *); void DetectParseDupSigHashFree(DetectEngineCtx *); -int DetectEngineContentModifierBufferSetup(DetectEngineCtx *de_ctx, - Signature *s, const char *arg, int sm_type, int sm_list, - AppProto alproto); +int DetectEngineContentModifierBufferSetup(DetectEngineCtx *de_ctx, Signature *s, const char *arg, + int sm_type, int sm_list, AppProto alproto); -bool SigMatchSilentErrorEnabled(const DetectEngineCtx *de_ctx, - const enum DetectKeywordId id); +bool SigMatchSilentErrorEnabled(const DetectEngineCtx *de_ctx, const enum DetectKeywordId id); bool SigMatchStrictEnabled(const enum DetectKeywordId id); const char *DetectListToHumanString(int list); diff --git a/src/detect-pcre.c b/src/detect-pcre.c index 848f6b9680fe..a0568429581e 100644 --- a/src/detect-pcre.c +++ b/src/detect-pcre.c @@ -87,32 +87,32 @@ static inline int DetectPcreExec(DetectEngineThreadCtx *det_ctx, const DetectPcr match, pd->parse_regex.context); } -static int DetectPcreSetup (DetectEngineCtx *, Signature *, const char *); +static int DetectPcreSetup(DetectEngineCtx *, Signature *, const char *); static void DetectPcreFree(DetectEngineCtx *, void *); #ifdef UNITTESTS static void DetectPcreRegisterTests(void); #endif -void DetectPcreRegister (void) +void DetectPcreRegister(void) { sigmatch_table[DETECT_PCRE].name = "pcre"; sigmatch_table[DETECT_PCRE].desc = "match on regular expression"; - sigmatch_table[DETECT_PCRE].url = "/rules/payload-keywords.html#pcre-perl-compatible-regular-expressions"; + sigmatch_table[DETECT_PCRE].url = + "/rules/payload-keywords.html#pcre-perl-compatible-regular-expressions"; sigmatch_table[DETECT_PCRE].Match = NULL; sigmatch_table[DETECT_PCRE].Setup = DetectPcreSetup; - sigmatch_table[DETECT_PCRE].Free = DetectPcreFree; + sigmatch_table[DETECT_PCRE].Free = DetectPcreFree; #ifdef UNITTESTS - sigmatch_table[DETECT_PCRE].RegisterTests = DetectPcreRegisterTests; + sigmatch_table[DETECT_PCRE].RegisterTests = DetectPcreRegisterTests; #endif - sigmatch_table[DETECT_PCRE].flags = (SIGMATCH_QUOTES_OPTIONAL|SIGMATCH_HANDLE_NEGATION); + sigmatch_table[DETECT_PCRE].flags = (SIGMATCH_QUOTES_OPTIONAL | SIGMATCH_HANDLE_NEGATION); intmax_t val = 0; if (!ConfGetInt("pcre.match-limit", &val)) { pcre_match_limit = SC_MATCH_LIMIT_DEFAULT; SCLogDebug("Using PCRE match-limit setting of: %i", pcre_match_limit); - } - else { + } else { pcre_match_limit = val; if (pcre_match_limit != SC_MATCH_LIMIT_DEFAULT) { SCLogInfo("Using PCRE match-limit setting of: %i", pcre_match_limit); @@ -126,13 +126,14 @@ void DetectPcreRegister (void) if (!ConfGetInt("pcre.match-limit-recursion", &val)) { pcre_match_limit_recursion = SC_MATCH_LIMIT_RECURSION_DEFAULT; SCLogDebug("Using PCRE match-limit-recursion setting of: %i", pcre_match_limit_recursion); - } - else { + } else { pcre_match_limit_recursion = val; if (pcre_match_limit_recursion != SC_MATCH_LIMIT_RECURSION_DEFAULT) { - SCLogInfo("Using PCRE match-limit-recursion setting of: %i", pcre_match_limit_recursion); + SCLogInfo( + "Using PCRE match-limit-recursion setting of: %i", pcre_match_limit_recursion); } else { - SCLogDebug("Using PCRE match-limit-recursion setting of: %i", pcre_match_limit_recursion); + SCLogDebug( + "Using PCRE match-limit-recursion setting of: %i", pcre_match_limit_recursion); } } @@ -173,8 +174,7 @@ void DetectPcreRegister (void) * \retval 0 No match. */ int DetectPcrePayloadMatch(DetectEngineThreadCtx *det_ctx, const Signature *s, - const SigMatchData *smd, Packet *p, Flow *f, - const uint8_t *payload, uint32_t payload_len) + const SigMatchData *smd, Packet *p, Flow *f, const uint8_t *payload, uint32_t payload_len) { SCEnter(); int ret = 0; @@ -245,8 +245,8 @@ int DetectPcrePayloadMatch(DetectEngineThreadCtx *det_ctx, const Signature *s, memcpy(str_ptr, pcre2_str_ptr, capture_len); pcre2_substring_free((PCRE2_UCHAR8 *)pcre2_str_ptr); - SCLogDebug("data %p/%u, type %u id %u p %p", - str_ptr, ret, pe->captypes[x], pe->capids[x], p); + SCLogDebug("data %p/%u, type %u id %u p %p", str_ptr, ret, pe->captypes[x], + pe->capids[x], p); if (pe->captypes[x] == VAR_TYPE_PKT_VAR_KV) { /* get the value, as first capture is the key */ @@ -334,11 +334,9 @@ static int DetectPcreHasUpperCase(const char *re) } else { is_meta = false; } - } - else if (re[i] == '\\') { + } else if (re[i] == '\\') { is_meta = true; - } - else if (isupper((unsigned char)re[i])) { + } else if (isupper((unsigned char)re[i])) { return 1; } } @@ -346,9 +344,8 @@ static int DetectPcreHasUpperCase(const char *re) return 0; } -static DetectPcreData *DetectPcreParse (DetectEngineCtx *de_ctx, - const char *regexstr, int *sm_list, char *capture_names, - size_t capture_names_size, bool negate, AppProto *alproto) +static DetectPcreData *DetectPcreParse(DetectEngineCtx *de_ctx, const char *regexstr, int *sm_list, + char *capture_names, size_t capture_names_size, bool negate, AppProto *alproto) { pcre2_match_data *match = NULL; int en; @@ -387,8 +384,7 @@ static DetectPcreData *DetectPcreParse (DetectEngineCtx *de_ctx, SCLogDebug("regexstr[offset] %c", regexstr[offset]); if (regexstr[offset] == ',' || regexstr[offset] == ' ') { offset--; - } - else + } else break; } @@ -396,9 +392,9 @@ static DetectPcreData *DetectPcreParse (DetectEngineCtx *de_ctx, SCLogDebug("missing separators, assume it's part of the regex"); } else { slen = offset + 1; - strlcpy(capture_names, regexstr+cut_capture, capture_names_size); - if (capture_names[strlen(capture_names)-1] == '"') - capture_names[strlen(capture_names)-1] = '\0'; + strlcpy(capture_names, regexstr + cut_capture, capture_names_size); + if (capture_names[strlen(capture_names) - 1] == '"') + capture_names[strlen(capture_names) - 1] = '\0'; } } } @@ -433,7 +429,7 @@ static DetectPcreData *DetectPcreParse (DetectEngineCtx *de_ctx, } op = op_str; } - //printf("ret %" PRId32 " re \'%s\', op \'%s\'\n", ret, re, op); + // printf("ret %" PRId32 " re \'%s\', op \'%s\'\n", ret, re, op); pd = SCCalloc(1, sizeof(DetectPcreData)); if (unlikely(pd == NULL)) @@ -486,7 +482,7 @@ static DetectPcreData *DetectPcreParse (DetectEngineCtx *de_ctx, pd->flags |= DETECT_PCRE_RELATIVE; break; - /* buffer selection */ + /* buffer selection */ case 'U': { /* snort's option */ if (pd->flags & DETECT_PCRE_RAWBYTES) { @@ -538,7 +534,8 @@ static DetectPcreData *DetectPcreParse (DetectEngineCtx *de_ctx, *sm_list = DetectPcreSetList(*sm_list, list); *alproto = ALPROTO_HTTP1; break; - } case 'I': { /* snort's option */ + } + case 'I': { /* snort's option */ if (pd->flags & DETECT_PCRE_RAWBYTES) { SCLogError("regex modifier 'I' inconsistent with 'B'"); goto error; @@ -622,8 +619,7 @@ static DetectPcreData *DetectPcreParse (DetectEngineCtx *de_ctx, "Since the hostname buffer we match against " "is actually lowercase, having a " "nocase is redundant."); - } - else if (DetectPcreHasUpperCase(re)) { + } else if (DetectPcreHasUpperCase(re)) { SCLogError("pcre host(\"W\") " "specified has an uppercase char. " "Since the hostname buffer we match against " @@ -648,7 +644,7 @@ static DetectPcreData *DetectPcreParse (DetectEngineCtx *de_ctx, pd->parse_regex.regex = pcre2_compile((PCRE2_SPTR8)re, PCRE2_ZERO_TERMINATED, opts, &en, &eo2, NULL); } - if (pd->parse_regex.regex == NULL) { + if (pd->parse_regex.regex == NULL) { PCRE2_UCHAR errbuffer[256]; pcre2_get_error_message(en, errbuffer, sizeof(errbuffer)); SCLogError("pcre2 compile of \"%s\" failed at " @@ -703,8 +699,8 @@ static DetectPcreData *DetectPcreParse (DetectEngineCtx *de_ctx, /** \internal * \brief check if we need to extract capture settings and set them up if needed */ -static int DetectPcreParseCapture(const char *regexstr, DetectEngineCtx *de_ctx, DetectPcreData *pd, - char *capture_names) +static int DetectPcreParseCapture( + const char *regexstr, DetectEngineCtx *de_ctx, DetectPcreData *pd, char *capture_names) { int ret = 0, res = 0; char type_str[16] = ""; @@ -720,10 +716,10 @@ static int DetectPcreParseCapture(const char *regexstr, DetectEngineCtx *de_ctx, ret = pcre2_pattern_info(pd->parse_regex.regex, PCRE2_INFO_CAPTURECOUNT, &capture_cnt); SCLogDebug("ret %d capture_cnt %d", ret, capture_cnt); - if (ret == 0 && capture_cnt && strlen(capture_names) > 0) - { + if (ret == 0 && capture_cnt && strlen(capture_names) > 0) { char *ptr = NULL; - while ((name_array[name_idx] = strtok_r(name_idx == 0 ? capture_names : NULL, " ,", &ptr))){ + while ((name_array[name_idx] = + strtok_r(name_idx == 0 ? capture_names : NULL, " ,", &ptr))) { if (name_idx > (capture_cnt - 1)) { SCLogError("more pkt/flow " "var capture names than capturing substrings"); @@ -743,7 +739,7 @@ static int DetectPcreParseCapture(const char *regexstr, DetectEngineCtx *de_ctx, SCLogDebug("key-value/value"); key = 0; - /* kv error conditions */ + /* kv error conditions */ } else if (key == 0 && strcmp(name_array[name_idx], "pkt:value") == 0) { return -1; } else if (key == 1) { @@ -829,7 +825,7 @@ static int DetectPcreParseCapture(const char *regexstr, DetectEngineCtx *de_ctx, pd->idx++; } - //SCLogNotice("pd->capname %s", pd->capname); + // SCLogNotice("pd->capname %s", pd->capname); PCRE2_SIZE *ov = pcre2_get_ovector_pointer(match); regexstr += ov[1]; @@ -861,7 +857,7 @@ static void DetectPcreThreadFree(void *ctx) } } -static int DetectPcreSetup (DetectEngineCtx *de_ctx, Signature *s, const char *regexstr) +static int DetectPcreSetup(DetectEngineCtx *de_ctx, Signature *s, const char *regexstr) { SCEnter(); DetectPcreData *pd = NULL; @@ -869,9 +865,8 @@ static int DetectPcreSetup (DetectEngineCtx *de_ctx, Signature *s, const char *r char capture_names[1024] = ""; AppProto alproto = ALPROTO_UNKNOWN; - pd = DetectPcreParse(de_ctx, regexstr, &parsed_sm_list, - capture_names, sizeof(capture_names), s->init_data->negated, - &alproto); + pd = DetectPcreParse(de_ctx, regexstr, &parsed_sm_list, capture_names, sizeof(capture_names), + s->init_data->negated, &alproto); if (pd == NULL) goto error; if (DetectPcreParseCapture(regexstr, de_ctx, pd, capture_names) < 0) @@ -932,13 +927,12 @@ static int DetectPcreSetup (DetectEngineCtx *de_ctx, Signature *s, const char *r /* errors below shouldn't free pd */ - SigMatch *prev_pm = DetectGetLastSMByListPtr(s, sm->prev, - DETECT_CONTENT, DETECT_PCRE, -1); + SigMatch *prev_pm = DetectGetLastSMByListPtr(s, sm->prev, DETECT_CONTENT, DETECT_PCRE, -1); if (s->init_data->list == DETECT_SM_LIST_NOTSET && prev_pm == NULL) { SCLogError("pcre with /R (relative) needs " "preceding match in the same buffer"); goto error_nofree; - /* null is allowed when we use a sticky buffer */ + /* null is allowed when we use a sticky buffer */ } else if (prev_pm == NULL) { goto okay; } @@ -950,11 +944,11 @@ static int DetectPcreSetup (DetectEngineCtx *de_ctx, Signature *s, const char *r tmp->flags |= DETECT_PCRE_RELATIVE_NEXT; } - okay: +okay: SCReturnInt(0); - error: +error: DetectPcreFree(de_ctx, pd); - error_nofree: +error_nofree: SCReturnInt(-1); } @@ -984,7 +978,7 @@ static int g_dce_stub_data_buffer_id = 0; /** * \test DetectPcreParseTest01 make sure we don't allow invalid opts 7. */ -static int DetectPcreParseTest01 (void) +static int DetectPcreParseTest01(void) { int result = 1; DetectPcreData *pd = NULL; @@ -1004,7 +998,7 @@ static int DetectPcreParseTest01 (void) /** * \test DetectPcreParseTest02 make sure we don't allow invalid opts Ui$. */ -static int DetectPcreParseTest02 (void) +static int DetectPcreParseTest02(void) { int result = 1; DetectPcreData *pd = NULL; @@ -1025,7 +1019,7 @@ static int DetectPcreParseTest02 (void) /** * \test DetectPcreParseTest03 make sure we don't allow invalid opts UZi. */ -static int DetectPcreParseTest03 (void) +static int DetectPcreParseTest03(void) { int result = 1; DetectPcreData *pd = NULL; @@ -1045,7 +1039,7 @@ static int DetectPcreParseTest03 (void) /** * \test DetectPcreParseTest04 make sure we allow escaped " */ -static int DetectPcreParseTest04 (void) +static int DetectPcreParseTest04(void) { int result = 1; DetectPcreData *pd = NULL; @@ -1067,7 +1061,7 @@ static int DetectPcreParseTest04 (void) /** * \test DetectPcreParseTest05 make sure we parse pcre with no opts */ -static int DetectPcreParseTest05 (void) +static int DetectPcreParseTest05(void) { int result = 1; DetectPcreData *pd = NULL; @@ -1089,7 +1083,7 @@ static int DetectPcreParseTest05 (void) /** * \test DetectPcreParseTest06 make sure we parse pcre with smi opts */ -static int DetectPcreParseTest06 (void) +static int DetectPcreParseTest06(void) { int result = 1; DetectPcreData *pd = NULL; @@ -1111,7 +1105,7 @@ static int DetectPcreParseTest06 (void) /** * \test DetectPcreParseTest07 make sure we parse pcre with /Ui opts */ -static int DetectPcreParseTest07 (void) +static int DetectPcreParseTest07(void) { int result = 1; DetectPcreData *pd = NULL; @@ -1133,7 +1127,7 @@ static int DetectPcreParseTest07 (void) /** * \test DetectPcreParseTest08 make sure we parse pcre with O opts */ -static int DetectPcreParseTest08 (void) +static int DetectPcreParseTest08(void) { int result = 1; DetectPcreData *pd = NULL; @@ -1156,7 +1150,7 @@ static int DetectPcreParseTest08 (void) * \test DetectPcreParseTest09 make sure we parse pcre with a content * that has slashes */ -static int DetectPcreParseTest09 (void) +static int DetectPcreParseTest09(void) { DetectPcreData *pd = NULL; const char *teststring = "/lala\\\\/"; @@ -1209,14 +1203,13 @@ static int DetectPcreParseTest15(void) { DetectEngineCtx *de_ctx = NULL; - FAIL_IF( (de_ctx = DetectEngineCtxInit()) == NULL); + FAIL_IF((de_ctx = DetectEngineCtxInit()) == NULL); de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx, - "alert tcp any any -> any any " - "(msg:\"Testing pcre relative http_method\"; " - "content:\"GET\"; " - "http_method; pcre:\"/abc/RM\"; sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " + "(msg:\"Testing pcre relative http_method\"; " + "content:\"GET\"; " + "http_method; pcre:\"/abc/RM\"; sid:1;)"); FAIL_IF_NULL(de_ctx->sig_list); if (de_ctx != NULL) @@ -1226,20 +1219,18 @@ static int DetectPcreParseTest15(void) PASS; } - /** \test Check a signature with pcre relative cookie */ static int DetectPcreParseTest16(void) { DetectEngineCtx *de_ctx = NULL; - FAIL_IF( (de_ctx = DetectEngineCtxInit()) == NULL); + FAIL_IF((de_ctx = DetectEngineCtxInit()) == NULL); de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx, - "alert tcp any any -> any any " - "(msg:\"Testing pcre relative http_cookie\"; " - "content:\"test\"; " - "http_cookie; pcre:\"/abc/RC\"; sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " + "(msg:\"Testing pcre relative http_cookie\"; " + "content:\"test\"; " + "http_cookie; pcre:\"/abc/RC\"; sid:1;)"); FAIL_IF_NULL(de_ctx->sig_list); if (de_ctx != NULL) @@ -1254,14 +1245,13 @@ static int DetectPcreParseTest17(void) { DetectEngineCtx *de_ctx = NULL; - FAIL_IF( (de_ctx = DetectEngineCtxInit()) == NULL); + FAIL_IF((de_ctx = DetectEngineCtxInit()) == NULL); de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx, - "alert tcp any any -> any any " - "(msg:\"Testing pcre relative http_raw_header\"; " - "flow:to_server; content:\"test\"; " - "http_raw_header; pcre:\"/abc/RD\"; sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " + "(msg:\"Testing pcre relative http_raw_header\"; " + "flow:to_server; content:\"test\"; " + "http_raw_header; pcre:\"/abc/RD\"; sid:1;)"); FAIL_IF_NULL(de_ctx->sig_list); if (de_ctx != NULL) @@ -1276,14 +1266,13 @@ static int DetectPcreParseTest18(void) { DetectEngineCtx *de_ctx = NULL; - FAIL_IF( (de_ctx = DetectEngineCtxInit()) == NULL); + FAIL_IF((de_ctx = DetectEngineCtxInit()) == NULL); de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx, - "alert tcp any any -> any any " - "(msg:\"Testing pcre relative http_header\"; " - "content:\"test\"; " - "http_header; pcre:\"/abc/RH\"; sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " + "(msg:\"Testing pcre relative http_header\"; " + "content:\"test\"; " + "http_header; pcre:\"/abc/RH\"; sid:1;)"); FAIL_IF_NULL(de_ctx->sig_list); if (de_ctx != NULL) @@ -1298,14 +1287,13 @@ static int DetectPcreParseTest19(void) { DetectEngineCtx *de_ctx = NULL; - FAIL_IF( (de_ctx = DetectEngineCtxInit()) == NULL); + FAIL_IF((de_ctx = DetectEngineCtxInit()) == NULL); de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx, - "alert tcp any any -> any any " - "(msg:\"Testing pcre relative http_client_body\"; " - "content:\"test\"; " - "http_client_body; pcre:\"/abc/RP\"; sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " + "(msg:\"Testing pcre relative http_client_body\"; " + "content:\"test\"; " + "http_client_body; pcre:\"/abc/RP\"; sid:1;)"); FAIL_IF_NULL(de_ctx->sig_list); if (de_ctx != NULL) @@ -1320,14 +1308,13 @@ static int DetectPcreParseTest20(void) { DetectEngineCtx *de_ctx = NULL; - FAIL_IF( (de_ctx = DetectEngineCtxInit()) == NULL); + FAIL_IF((de_ctx = DetectEngineCtxInit()) == NULL); de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx, - "alert tcp any any -> any any " - "(msg:\"Testing http_raw_uri\"; " - "content:\"test\"; " - "http_raw_uri; pcre:\"/abc/RI\"; sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " + "(msg:\"Testing http_raw_uri\"; " + "content:\"test\"; " + "http_raw_uri; pcre:\"/abc/RI\"; sid:1;)"); FAIL_IF_NULL(de_ctx->sig_list); if (de_ctx != NULL) @@ -1342,14 +1329,13 @@ static int DetectPcreParseTest21(void) { DetectEngineCtx *de_ctx = NULL; - FAIL_IF( (de_ctx = DetectEngineCtxInit()) == NULL); + FAIL_IF((de_ctx = DetectEngineCtxInit()) == NULL); de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx, - "alert tcp any any -> any any " - "(msg:\"Testing pcre relative uricontent\"; " - "uricontent:\"test\"; " - "pcre:\"/abc/RU\"; sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " + "(msg:\"Testing pcre relative uricontent\"; " + "uricontent:\"test\"; " + "pcre:\"/abc/RU\"; sid:1;)"); FAIL_IF_NULL(de_ctx->sig_list); if (de_ctx != NULL) @@ -1364,14 +1350,13 @@ static int DetectPcreParseTest22(void) { DetectEngineCtx *de_ctx = NULL; - FAIL_IF( (de_ctx = DetectEngineCtxInit()) == NULL); + FAIL_IF((de_ctx = DetectEngineCtxInit()) == NULL); de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx, - "alert tcp any any -> any any " - "(msg:\"Testing pcre relative http_uri\"; " - "content:\"test\"; " - "http_uri; pcre:\"/abc/RU\"; sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " + "(msg:\"Testing pcre relative http_uri\"; " + "content:\"test\"; " + "http_uri; pcre:\"/abc/RU\"; sid:1;)"); FAIL_IF_NULL(de_ctx->sig_list); if (de_ctx != NULL) @@ -1386,14 +1371,13 @@ static int DetectPcreParseTest23(void) { DetectEngineCtx *de_ctx = NULL; - FAIL_IF( (de_ctx = DetectEngineCtxInit()) == NULL); + FAIL_IF((de_ctx = DetectEngineCtxInit()) == NULL); de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx, - "alert tcp any any -> any any " - "(msg:\"Testing inconsistent pcre relative\"; " - "content:\"GET\"; " - "http_cookie; pcre:\"/abc/RM\"; sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " + "(msg:\"Testing inconsistent pcre relative\"; " + "content:\"GET\"; " + "http_cookie; pcre:\"/abc/RM\"; sid:1;)"); FAIL_IF_NOT_NULL(de_ctx->sig_list); if (de_ctx != NULL) @@ -1408,13 +1392,12 @@ static int DetectPcreParseTest24(void) { DetectEngineCtx *de_ctx = NULL; - FAIL_IF( (de_ctx = DetectEngineCtxInit()) == NULL); + FAIL_IF((de_ctx = DetectEngineCtxInit()) == NULL); de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx, - "alert tcp any any -> any any " - "(msg:\"Testing inconsistent pcre modifiers\"; " - "pcre:\"/abc/UI\"; sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " + "(msg:\"Testing inconsistent pcre modifiers\"; " + "pcre:\"/abc/UI\"; sid:1;)"); FAIL_IF_NOT_NULL(de_ctx->sig_list); if (de_ctx != NULL) @@ -1429,13 +1412,12 @@ static int DetectPcreParseTest25(void) { DetectEngineCtx *de_ctx = NULL; - FAIL_IF( (de_ctx = DetectEngineCtxInit()) == NULL); + FAIL_IF((de_ctx = DetectEngineCtxInit()) == NULL); de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx, - "alert tcp any any -> any any " - "(msg:\"Testing inconsistent pcre modifiers\"; " - "pcre:\"/abc/DH\"; sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " + "(msg:\"Testing inconsistent pcre modifiers\"; " + "pcre:\"/abc/DH\"; sid:1;)"); FAIL_IF_NOT_NULL(de_ctx->sig_list); if (de_ctx != NULL) @@ -1450,13 +1432,12 @@ static int DetectPcreParseTest26(void) { DetectEngineCtx *de_ctx = NULL; - FAIL_IF( (de_ctx = DetectEngineCtxInit()) == NULL); + FAIL_IF((de_ctx = DetectEngineCtxInit()) == NULL); de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx, - "alert http any any -> any any " - "(msg:\"Testing inconsistent pcre modifiers\"; " - "pcre:\"/abc/F\"; sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"Testing inconsistent pcre modifiers\"; " + "pcre:\"/abc/F\"; sid:1;)"); FAIL_IF_NOT_NULL(de_ctx->sig_list); if (de_ctx != NULL) @@ -1471,12 +1452,12 @@ static int DetectPcreParseTest27(void) { DetectEngineCtx *de_ctx = NULL; - FAIL_IF( (de_ctx = DetectEngineCtxInit()) == NULL); + FAIL_IF((de_ctx = DetectEngineCtxInit()) == NULL); de_ctx->flags |= DE_QUIET; de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any 80 " - "(content:\"baduricontent\"; http_raw_uri; " - "pcre:\"/^[a-z]{5}\\.html/R\"; sid:2; rev:2;)"); + "(content:\"baduricontent\"; http_raw_uri; " + "pcre:\"/^[a-z]{5}\\.html/R\"; sid:2; rev:2;)"); FAIL_IF_NOT(de_ctx->sig_list == NULL); if (de_ctx != NULL) @@ -1491,12 +1472,13 @@ static int DetectPcreParseTest28(void) { DetectEngineCtx *de_ctx = NULL; - FAIL_IF( (de_ctx = DetectEngineCtxInit()) == NULL); + FAIL_IF((de_ctx = DetectEngineCtxInit()) == NULL); de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any 80 " - "(content:\"|2E|suricata\"; http_host; pcre:\"/\\x2Esuricata$/W\"; " - "sid:2; rev:2;)"); + de_ctx->sig_list = + SigInit(de_ctx, "alert tcp any any -> any 80 " + "(content:\"|2E|suricata\"; http_host; pcre:\"/\\x2Esuricata$/W\"; " + "sid:2; rev:2;)"); FAIL_IF_NULL(de_ctx->sig_list); DetectEngineCtxFree(de_ctx); @@ -1592,7 +1574,7 @@ static int DetectPcreTxBodyChunksTest01(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1633,20 +1615,22 @@ static int DetectPcreTxBodyChunksTest01(void) htp_tx_t *t1 = AppLayerParserGetTx(IPPROTO_TCP, ALPROTO_HTTP1, htp_state, 0); htp_tx_t *t2 = AppLayerParserGetTx(IPPROTO_TCP, ALPROTO_HTTP1, htp_state, 1); - HtpTxUserData *htud = (HtpTxUserData *) htp_tx_get_user_data(t1); + HtpTxUserData *htud = (HtpTxUserData *)htp_tx_get_user_data(t1); FAIL_IF(htud == NULL); HtpBodyChunk *cur = htud->request_body.first; FAIL_IF(htud->request_body.first == NULL); - FAIL_IF(StreamingBufferSegmentCompareRawData(htud->request_body.sb, &cur->sbseg, (uint8_t *)"Body one!!", 10) != 1); + FAIL_IF(StreamingBufferSegmentCompareRawData( + htud->request_body.sb, &cur->sbseg, (uint8_t *)"Body one!!", 10) != 1); - htud = (HtpTxUserData *) htp_tx_get_user_data(t2); + htud = (HtpTxUserData *)htp_tx_get_user_data(t2); cur = htud->request_body.first; FAIL_IF(htud->request_body.first == NULL); - FAIL_IF(StreamingBufferSegmentCompareRawData(htud->request_body.sb, &cur->sbseg, (uint8_t *)"Body two!!", 10) != 1); + FAIL_IF(StreamingBufferSegmentCompareRawData( + htud->request_body.sb, &cur->sbseg, (uint8_t *)"Body two!!", 10) != 1); if (alp_tctx != NULL) AppLayerParserThreadCtxFree(alp_tctx); @@ -1695,7 +1679,7 @@ static int DetectPcreTxBodyChunksTest02(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1705,9 +1689,13 @@ static int DetectPcreTxBodyChunksTest02(void) de_ctx->flags |= DE_QUIET; - s = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any (content:\"POST\"; http_method; content:\"Mozilla\"; http_header; content:\"dummy\"; http_cookie; pcre:\"/one/P\"; sid:1; rev:1;)"); + s = DetectEngineAppendSig(de_ctx, + "alert tcp any any -> any any (content:\"POST\"; http_method; content:\"Mozilla\"; " + "http_header; content:\"dummy\"; http_cookie; pcre:\"/one/P\"; sid:1; rev:1;)"); FAIL_IF(s == NULL); - s = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any (content:\"GET\"; http_method; content:\"Firefox\"; http_header; content:\"dummy2\"; http_cookie; pcre:\"/two/P\"; sid:2; rev:1;)"); + s = DetectEngineAppendSig(de_ctx, + "alert tcp any any -> any any (content:\"GET\"; http_method; content:\"Firefox\"; " + "http_header; content:\"dummy2\"; http_cookie; pcre:\"/two/P\"; sid:2; rev:1;)"); FAIL_IF(s == NULL); SigGroupBuild(de_ctx); @@ -1781,19 +1769,21 @@ static int DetectPcreTxBodyChunksTest02(void) htp_tx_t *t1 = AppLayerParserGetTx(IPPROTO_TCP, ALPROTO_HTTP1, htp_state, 0); htp_tx_t *t2 = AppLayerParserGetTx(IPPROTO_TCP, ALPROTO_HTTP1, htp_state, 1); - HtpTxUserData *htud = (HtpTxUserData *) htp_tx_get_user_data(t1); + HtpTxUserData *htud = (HtpTxUserData *)htp_tx_get_user_data(t1); HtpBodyChunk *cur = htud->request_body.first; FAIL_IF(htud->request_body.first == NULL); - FAIL_IF(StreamingBufferSegmentCompareRawData(htud->request_body.sb, &cur->sbseg, (uint8_t *)"Body one!!", 10) != 1); + FAIL_IF(StreamingBufferSegmentCompareRawData( + htud->request_body.sb, &cur->sbseg, (uint8_t *)"Body one!!", 10) != 1); - htud = (HtpTxUserData *) htp_tx_get_user_data(t2); + htud = (HtpTxUserData *)htp_tx_get_user_data(t2); cur = htud->request_body.first; FAIL_IF(htud->request_body.first == NULL); - FAIL_IF(StreamingBufferSegmentCompareRawData(htud->request_body.sb, &cur->sbseg, (uint8_t *)"Body two!!", 10) != 1); + FAIL_IF(StreamingBufferSegmentCompareRawData( + htud->request_body.sb, &cur->sbseg, (uint8_t *)"Body two!!", 10) != 1); if (alp_tctx != NULL) AppLayerParserThreadCtxFree(alp_tctx); @@ -1850,7 +1840,7 @@ static int DetectPcreTxBodyChunksTest03(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1860,9 +1850,13 @@ static int DetectPcreTxBodyChunksTest03(void) de_ctx->flags |= DE_QUIET; - s = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any (content:\"POST\"; http_method; content:\"Mozilla\"; http_header; content:\"dummy\"; http_cookie; pcre:\"/one/P\"; sid:1; rev:1;)"); + s = DetectEngineAppendSig(de_ctx, + "alert tcp any any -> any any (content:\"POST\"; http_method; content:\"Mozilla\"; " + "http_header; content:\"dummy\"; http_cookie; pcre:\"/one/P\"; sid:1; rev:1;)"); FAIL_IF(s == NULL); - s = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any (content:\"GET\"; http_method; content:\"Firefox\"; http_header; content:\"dummy2\"; http_cookie; pcre:\"/two/P\"; sid:2; rev:1;)"); + s = DetectEngineAppendSig(de_ctx, + "alert tcp any any -> any any (content:\"GET\"; http_method; content:\"Firefox\"; " + "http_header; content:\"dummy2\"; http_cookie; pcre:\"/two/P\"; sid:2; rev:1;)"); FAIL_IF(s == NULL); SigGroupBuild(de_ctx); @@ -1959,7 +1953,8 @@ static int DetectPcreParseHttpHost(void) FAIL_IF(de_ctx == NULL); - DetectPcreData *pd = DetectPcreParse(de_ctx, "/domain\\.com/W", &list, NULL, 0, false, &alproto); + DetectPcreData *pd = + DetectPcreParse(de_ctx, "/domain\\.com/W", &list, NULL, 0, false, &alproto); FAIL_IF(pd == NULL); DetectPcreFree(de_ctx, pd); @@ -1991,14 +1986,20 @@ static int DetectPcreParseCaptureTest(void) DetectEngineCtx *de_ctx = DetectEngineCtxInit(); FAIL_IF(de_ctx == NULL); - Signature *s = DetectEngineAppendSig(de_ctx, "alert http any any -> any any " - "(content:\"Server: \"; http_header; pcre:\"/(.*)\\r\\n/HR, flow:somecapture\"; content:\"xyz\"; http_header; sid:1;)"); + Signature *s = DetectEngineAppendSig(de_ctx, + "alert http any any -> any any " + "(content:\"Server: \"; http_header; pcre:\"/(.*)\\r\\n/HR, flow:somecapture\"; " + "content:\"xyz\"; http_header; sid:1;)"); FAIL_IF(s == NULL); - s = DetectEngineAppendSig(de_ctx, "alert http any any -> any any " - "(content:\"Server: \"; http_header; pcre:\"/(flow:.*)\\r\\n/HR\"; content:\"xyz\"; http_header; sid:2;)"); + s = DetectEngineAppendSig(de_ctx, + "alert http any any -> any any " + "(content:\"Server: \"; http_header; pcre:\"/(flow:.*)\\r\\n/HR\"; content:\"xyz\"; " + "http_header; sid:2;)"); FAIL_IF(s == NULL); - s = DetectEngineAppendSig(de_ctx, "alert http any any -> any any " - "(content:\"Server: \"; http_header; pcre:\"/([a-z]+)([0-9]+)\\r\\n/HR, flow:somecapture, pkt:anothercap\"; content:\"xyz\"; http_header; sid:3;)"); + s = DetectEngineAppendSig(de_ctx, + "alert http any any -> any any " + "(content:\"Server: \"; http_header; pcre:\"/([a-z]+)([0-9]+)\\r\\n/HR, " + "flow:somecapture, pkt:anothercap\"; content:\"xyz\"; http_header; sid:3;)"); FAIL_IF(s == NULL); s = DetectEngineAppendSig(de_ctx, "alert http any any -> any any " @@ -2056,15 +2057,13 @@ static void DetectPcreRegisterTests(void) UtRegisterTest("DetectPcreTestSig02 -- anchored pcre", DetectPcreTestSig02); UtRegisterTest("DetectPcreTestSig03 -- anchored pcre", DetectPcreTestSig03); - UtRegisterTest("DetectPcreTxBodyChunksTest01", - DetectPcreTxBodyChunksTest01); + UtRegisterTest("DetectPcreTxBodyChunksTest01", DetectPcreTxBodyChunksTest01); UtRegisterTest("DetectPcreTxBodyChunksTest02 -- modifier P, body chunks per tx", - DetectPcreTxBodyChunksTest02); + DetectPcreTxBodyChunksTest02); UtRegisterTest("DetectPcreTxBodyChunksTest03 -- modifier P, body chunks per tx", - DetectPcreTxBodyChunksTest03); + DetectPcreTxBodyChunksTest03); UtRegisterTest("DetectPcreParseHttpHost", DetectPcreParseHttpHost); UtRegisterTest("DetectPcreParseCaptureTest", DetectPcreParseCaptureTest); - } #endif /* UNITTESTS */ diff --git a/src/detect-pcre.h b/src/detect-pcre.h index 79fd1af74ae2..ea95a06fa662 100644 --- a/src/detect-pcre.h +++ b/src/detect-pcre.h @@ -26,16 +26,16 @@ #include "detect-parse.h" -#define DETECT_PCRE_RELATIVE 0x00001 +#define DETECT_PCRE_RELATIVE 0x00001 /* no-op other than in parsing */ -#define DETECT_PCRE_RAWBYTES 0x00002 -#define DETECT_PCRE_CASELESS 0x00004 +#define DETECT_PCRE_RAWBYTES 0x00002 +#define DETECT_PCRE_CASELESS 0x00004 -#define DETECT_PCRE_MATCH_LIMIT 0x00020 -#define DETECT_PCRE_RELATIVE_NEXT 0x00040 -#define DETECT_PCRE_NEGATE 0x00080 +#define DETECT_PCRE_MATCH_LIMIT 0x00020 +#define DETECT_PCRE_RELATIVE_NEXT 0x00040 +#define DETECT_PCRE_NEGATE 0x00080 -#define DETECT_PCRE_CAPTURE_MAX 8 +#define DETECT_PCRE_CAPTURE_MAX 8 #define SC_MATCH_LIMIT_DEFAULT 3500 #define SC_MATCH_LIMIT_RECURSION_DEFAULT 1500 @@ -54,11 +54,9 @@ typedef struct DetectPcreData_ { /* prototypes */ -int DetectPcrePayloadMatch(DetectEngineThreadCtx *, - const Signature *, const SigMatchData *, +int DetectPcrePayloadMatch(DetectEngineThreadCtx *, const Signature *, const SigMatchData *, Packet *, Flow *, const uint8_t *, uint32_t); -void DetectPcreRegister (void); +void DetectPcreRegister(void); #endif /* __DETECT_PCRE_H__ */ - diff --git a/src/detect-pkt-data.c b/src/detect-pkt-data.c index 80673979ad11..1a360b2c4b11 100644 --- a/src/detect-pkt-data.c +++ b/src/detect-pkt-data.c @@ -42,7 +42,7 @@ #include "util-unittest.h" #include "util-unittest-helper.h" -static int DetectPktDataSetup (DetectEngineCtx *, Signature *, const char *); +static int DetectPktDataSetup(DetectEngineCtx *, Signature *, const char *); #ifdef UNITTESTS static void DetectPktDataTestRegister(void); #endif @@ -71,7 +71,7 @@ void DetectPktDataRegister(void) * \retval 0 on Success * \retval -1 on Failure */ -static int DetectPktDataSetup (DetectEngineCtx *de_ctx, Signature *s, const char *unused) +static int DetectPktDataSetup(DetectEngineCtx *de_ctx, Signature *s, const char *unused) { SCEnter(); if (s->init_data->transforms.cnt) { @@ -92,8 +92,8 @@ static int DetectPktDataTest02(void) de_ctx->flags |= DE_QUIET; Signature *sig = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any " - "(file_data; compress_whitespace; " - " pkt_data; content:\"in pkt data\"; sid:1;)"); + "(file_data; compress_whitespace; " + " pkt_data; content:\"in pkt data\"; sid:1;)"); FAIL_IF_NOT_NULL(sig); DetectEngineCtxFree(de_ctx); PASS; diff --git a/src/detect-pkt-data.h b/src/detect-pkt-data.h index fbaf8b98e6a3..1d0681e34524 100644 --- a/src/detect-pkt-data.h +++ b/src/detect-pkt-data.h @@ -25,6 +25,6 @@ #define __DETECT_PKTDATA_H__ /* prototypes */ -void DetectPktDataRegister (void); +void DetectPktDataRegister(void); #endif /* __DETECT_PKTDATA_H__ */ diff --git a/src/detect-pktvar.c b/src/detect-pktvar.c index 7166188eb256..2e7208129c4b 100644 --- a/src/detect-pktvar.c +++ b/src/detect-pktvar.c @@ -37,20 +37,20 @@ #include "util-debug.h" #include "util-var-name.h" -#define PARSE_REGEX "(.*),(.*)" +#define PARSE_REGEX "(.*),(.*)" static DetectParseRegex parse_regex; -static int DetectPktvarMatch (DetectEngineThreadCtx *, Packet *, - const Signature *, const SigMatchCtx *); -static int DetectPktvarSetup (DetectEngineCtx *, Signature *, const char *); +static int DetectPktvarMatch( + DetectEngineThreadCtx *, Packet *, const Signature *, const SigMatchCtx *); +static int DetectPktvarSetup(DetectEngineCtx *, Signature *, const char *); static void DetectPktvarFree(DetectEngineCtx *, void *data); -void DetectPktvarRegister (void) +void DetectPktvarRegister(void) { sigmatch_table[DETECT_PKTVAR].name = "pktvar"; sigmatch_table[DETECT_PKTVAR].Match = DetectPktvarMatch; sigmatch_table[DETECT_PKTVAR].Setup = DetectPktvarSetup; - sigmatch_table[DETECT_PKTVAR].Free = DetectPktvarFree; + sigmatch_table[DETECT_PKTVAR].Free = DetectPktvarFree; DetectSetupParseRegexes(PARSE_REGEX, &parse_regex); } @@ -61,8 +61,8 @@ void DetectPktvarRegister (void) * -1: error */ -static int DetectPktvarMatch (DetectEngineThreadCtx *det_ctx, Packet *p, - const Signature *s, const SigMatchCtx *ctx) +static int DetectPktvarMatch( + DetectEngineThreadCtx *det_ctx, Packet *p, const Signature *s, const SigMatchCtx *ctx) { int ret = 0; const DetectPktvarData *pd = (const DetectPktvarData *)ctx; @@ -87,7 +87,7 @@ static void DetectPktvarFree(DetectEngineCtx *de_ctx, void *ptr) } } -static int DetectPktvarSetup (DetectEngineCtx *de_ctx, Signature *s, const char *rawstr) +static int DetectPktvarSetup(DetectEngineCtx *de_ctx, Signature *s, const char *rawstr) { char *varname = NULL, *varcontent = NULL; int res = 0; @@ -122,8 +122,7 @@ static int DetectPktvarSetup (DetectEngineCtx *de_ctx, Signature *s, const char char *parse_content; if (strlen(varcontent) >= 2 && varcontent[0] == '"' && - varcontent[strlen(varcontent) - 1] == '"') - { + varcontent[strlen(varcontent) - 1] == '"') { parse_content = varcontent + 1; varcontent[strlen(varcontent) - 1] = '\0'; } else { diff --git a/src/detect-pktvar.h b/src/detect-pktvar.h index ecd0243904a7..94de8a0466b4 100644 --- a/src/detect-pktvar.h +++ b/src/detect-pktvar.h @@ -32,7 +32,6 @@ typedef struct DetectPktvarData_ { } DetectPktvarData; /* prototypes */ -void DetectPktvarRegister (void); +void DetectPktvarRegister(void); #endif /* __DETECT_PKTVAR_H__ */ - diff --git a/src/detect-prefilter.c b/src/detect-prefilter.c index f38b56bf8b9c..ee7702bae17e 100644 --- a/src/detect-prefilter.c +++ b/src/detect-prefilter.c @@ -32,7 +32,7 @@ #include "detect-prefilter.h" #include "util-debug.h" -static int DetectPrefilterSetup (DetectEngineCtx *, Signature *, const char *); +static int DetectPrefilterSetup(DetectEngineCtx *, Signature *, const char *); void DetectPrefilterRegister(void) { @@ -52,7 +52,7 @@ void DetectPrefilterRegister(void) * \retval 0 ok * \retval -1 failure */ -static int DetectPrefilterSetup (DetectEngineCtx *de_ctx, Signature *s, const char *nullstr) +static int DetectPrefilterSetup(DetectEngineCtx *de_ctx, Signature *s, const char *nullstr) { SCEnter(); @@ -77,11 +77,9 @@ static int DetectPrefilterSetup (DetectEngineCtx *de_ctx, Signature *s, const ch if (sm->type == DETECT_CONTENT) { DetectContentData *cd = (DetectContentData *)sm->ctx; if ((cd->flags & DETECT_CONTENT_NEGATED) && - ((cd->flags & DETECT_CONTENT_DISTANCE) || - (cd->flags & DETECT_CONTENT_WITHIN) || - (cd->flags & DETECT_CONTENT_OFFSET) || - (cd->flags & DETECT_CONTENT_DEPTH))) - { + ((cd->flags & DETECT_CONTENT_DISTANCE) || (cd->flags & DETECT_CONTENT_WITHIN) || + (cd->flags & DETECT_CONTENT_OFFSET) || + (cd->flags & DETECT_CONTENT_DEPTH))) { SCLogError("prefilter; cannot be " "used with negated content, along with relative modifiers"); SCReturnInt(-1); diff --git a/src/detect-prefilter.h b/src/detect-prefilter.h index afc64db43f8f..3884faaa3045 100644 --- a/src/detect-prefilter.h +++ b/src/detect-prefilter.h @@ -25,6 +25,6 @@ #define __DETECT_PREFILTER_H__ /* prototypes */ -void DetectPrefilterRegister (void); +void DetectPrefilterRegister(void); #endif /* __DETECT_PREFILTER_H__ */ diff --git a/src/detect-priority.c b/src/detect-priority.c index 81ee72966fb5..700393da2670 100644 --- a/src/detect-priority.c +++ b/src/detect-priority.c @@ -38,7 +38,7 @@ static DetectParseRegex parse_regex; -static int DetectPrioritySetup (DetectEngineCtx *, Signature *, const char *); +static int DetectPrioritySetup(DetectEngineCtx *, Signature *, const char *); #ifdef UNITTESTS static void PriorityRegisterTests(void); #endif @@ -46,7 +46,7 @@ static void PriorityRegisterTests(void); /** * \brief Registers the handler functions for the "priority" keyword */ -void DetectPriorityRegister (void) +void DetectPriorityRegister(void) { sigmatch_table[DETECT_PRIORITY].name = "priority"; sigmatch_table[DETECT_PRIORITY].desc = "rules with a higher priority will be examined first"; @@ -58,7 +58,7 @@ void DetectPriorityRegister (void) DetectSetupParseRegexes(PARSE_REGEX, &parse_regex); } -static int DetectPrioritySetup (DetectEngineCtx *de_ctx, Signature *s, const char *rawstr) +static int DetectPrioritySetup(DetectEngineCtx *de_ctx, Signature *s, const char *rawstr) { char copy_str[128] = ""; size_t pcre2len; @@ -112,7 +112,7 @@ static int DetectPriorityTest01(void) FAIL_IF_NULL(de_ctx); de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"Priority test\"; priority:2; sid:1;)"); + "(msg:\"Priority test\"; priority:2; sid:1;)"); FAIL_IF_NULL(de_ctx->sig_list); FAIL_IF_NOT(de_ctx->sig_list->prio == 2); @@ -127,43 +127,43 @@ static int DetectPriorityTest02(void) FAIL_IF_NULL(de_ctx); Signature *sig = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any " - "(msg:\"Priority test\"; priority:1; sid:1;)"); + "(msg:\"Priority test\"; priority:1; sid:1;)"); FAIL_IF_NULL(sig); FAIL_IF_NOT(sig->prio == 1); sig = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any " - "(msg:\"Priority test\"; priority:boo; sid:2;)"); + "(msg:\"Priority test\"; priority:boo; sid:2;)"); FAIL_IF_NOT_NULL(sig); sig = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any " - "(msg:\"Priority test\"; priority:10boo; sid:3;)"); + "(msg:\"Priority test\"; priority:10boo; sid:3;)"); FAIL_IF_NOT_NULL(sig); sig = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any " - "(msg:\"Priority test\"; priority:b10oo; sid:4;)"); + "(msg:\"Priority test\"; priority:b10oo; sid:4;)"); FAIL_IF_NOT_NULL(sig); sig = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any " - "(msg:\"Priority test\"; priority:boo10; sid:5;)"); + "(msg:\"Priority test\"; priority:boo10; sid:5;)"); FAIL_IF_NOT_NULL(sig); sig = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any " - "(msg:\"Priority test\"; priority:-1; sid:6;)"); + "(msg:\"Priority test\"; priority:-1; sid:6;)"); FAIL_IF_NOT_NULL(sig); sig = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any " - "(msg:\"Priority test\"; sid:7;)"); + "(msg:\"Priority test\"; sid:7;)"); FAIL_IF_NULL(sig); FAIL_IF_NOT(sig->prio == 3); sig = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any " - "(msg:\"Priority test\"; priority:5; priority:4; sid:8;)"); + "(msg:\"Priority test\"; priority:5; priority:4; sid:8;)"); FAIL_IF_NULL(sig); FAIL_IF_NOT(sig->prio == 4); sig = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any " - "(msg:\"Priority test\"; priority:5; priority:4; " - "priority:1; sid:9;)"); + "(msg:\"Priority test\"; priority:5; priority:4; " + "priority:1; sid:9;)"); FAIL_IF_NULL(sig); FAIL_IF_NOT(sig->prio == 1); diff --git a/src/detect-priority.h b/src/detect-priority.h index 0ec877e521b8..09f020015adc 100644 --- a/src/detect-priority.h +++ b/src/detect-priority.h @@ -28,7 +28,6 @@ #define __DETECT_PRIORITY_H__ /* prototypes */ -void DetectPriorityRegister (void); +void DetectPriorityRegister(void); #endif /* __DETECT_PRIORITY_H__ */ - diff --git a/src/detect-rawbytes.h b/src/detect-rawbytes.h index 8716e56a31f0..8b79a02bcfe0 100644 --- a/src/detect-rawbytes.h +++ b/src/detect-rawbytes.h @@ -25,7 +25,6 @@ #define __DETECT_RAWBYTES_H__ /* prototypes */ -void DetectRawbytesRegister (void); +void DetectRawbytesRegister(void); #endif /* __DETECT_RAWBYTES_H__ */ - diff --git a/src/detect-reference.c b/src/detect-reference.c index aaa723db4963..7d1091c10054 100644 --- a/src/detect-reference.c +++ b/src/detect-reference.c @@ -58,7 +58,8 @@ static int DetectReferenceSetup(DetectEngineCtx *, Signature *s, const char *str void DetectReferenceRegister(void) { sigmatch_table[DETECT_REFERENCE].name = "reference"; - sigmatch_table[DETECT_REFERENCE].desc = "direct to places where information about the rule can be found"; + sigmatch_table[DETECT_REFERENCE].desc = + "direct to places where information about the rule can be found"; sigmatch_table[DETECT_REFERENCE].url = "/rules/meta.html#reference"; sigmatch_table[DETECT_REFERENCE].Setup = DetectReferenceSetup; #ifdef UNITTESTS @@ -187,8 +188,7 @@ static DetectReference *DetectReferenceParse(const char *rawstr, DetectEngineCtx * \retval 0 On Success. * \retval -1 On Failure. */ -static int DetectReferenceSetup(DetectEngineCtx *de_ctx, Signature *s, - const char *rawstr) +static int DetectReferenceSetup(DetectEngineCtx *de_ctx, Signature *s, const char *rawstr) { SCEnter(); @@ -200,7 +200,7 @@ static int DetectReferenceSetup(DetectEngineCtx *de_ctx, Signature *s, SCLogDebug("ref %s %s", ref->key, ref->reference); - if (s->references == NULL) { + if (s->references == NULL) { s->references = ref; } else { sig_refs = s->references; @@ -234,14 +234,15 @@ static int DetectReferenceParseTest01(void) FAIL_IF_NULL(fd); SCRConfLoadReferenceConfigFile(de_ctx, fd); - Signature *s = DetectEngineAppendSig(de_ctx, "alert icmp any any -> any any " + Signature *s = DetectEngineAppendSig(de_ctx, + "alert icmp any any -> any any " "(msg:\"One reference\"; reference:one,001-2010; sid:2;)"); FAIL_IF_NULL(s); FAIL_IF_NULL(s->references); DetectReference *ref = s->references; - FAIL_IF (strcmp(ref->key, "http://www.one.com") != 0); - FAIL_IF (strcmp(ref->reference, "001-2010") != 0); + FAIL_IF(strcmp(ref->key, "http://www.one.com") != 0); + FAIL_IF(strcmp(ref->reference, "001-2010") != 0); DetectEngineCtxFree(de_ctx); PASS; @@ -264,20 +265,20 @@ static int DetectReferenceParseTest02(void) SCRConfLoadReferenceConfigFile(de_ctx, fd); Signature *s = DetectEngineAppendSig(de_ctx, "alert icmp any any -> any any " - "(msg:\"Two references\"; " - "reference:one,openinfosecdoundation.txt; " - "reference:two,001-2010; sid:2;)"); + "(msg:\"Two references\"; " + "reference:one,openinfosecdoundation.txt; " + "reference:two,001-2010; sid:2;)"); FAIL_IF_NULL(s); FAIL_IF_NULL(s->references); FAIL_IF_NULL(s->references->next); DetectReference *ref = s->references; - FAIL_IF (strcmp(ref->key, "http://www.one.com") != 0); - FAIL_IF (strcmp(ref->reference, "openinfosecdoundation.txt") != 0); + FAIL_IF(strcmp(ref->key, "http://www.one.com") != 0); + FAIL_IF(strcmp(ref->reference, "openinfosecdoundation.txt") != 0); ref = s->references->next; - FAIL_IF (strcmp(ref->key, "http://www.two.com") != 0); - FAIL_IF (strcmp(ref->reference, "001-2010") != 0); + FAIL_IF(strcmp(ref->key, "http://www.two.com") != 0); + FAIL_IF(strcmp(ref->reference, "001-2010") != 0); DetectEngineCtxFree(de_ctx); PASS; @@ -300,8 +301,8 @@ static int DetectReferenceParseTest03(void) SCRConfLoadReferenceConfigFile(de_ctx, fd); Signature *s = DetectEngineAppendSig(de_ctx, "alert icmp any any -> any any " - "(msg:\"invalid ref\"; " - "reference:unknownkey,001-2010; sid:2;)"); + "(msg:\"invalid ref\"; " + "reference:unknownkey,001-2010; sid:2;)"); FAIL_IF_NULL(s); DetectEngineCtxFree(de_ctx); PASS; diff --git a/src/detect-reference.h b/src/detect-reference.h index ddf9233987cb..d8ecc604dab9 100644 --- a/src/detect-reference.h +++ b/src/detect-reference.h @@ -24,7 +24,6 @@ #ifndef __DETECT_REFERENCE_H__ #define __DETECT_REFERENCE_H__ - /** * \brief Signature reference list. */ diff --git a/src/detect-replace.c b/src/detect-replace.c index f9c467d97216..e97780d87d60 100644 --- a/src/detect-replace.c +++ b/src/detect-replace.c @@ -64,24 +64,25 @@ static int DetectReplaceSetup(DetectEngineCtx *, Signature *, const char *); #ifdef UNITTESTS static void DetectReplaceRegisterTests(void); #endif -static int DetectReplacePostMatch(DetectEngineThreadCtx *det_ctx, - Packet *p, const Signature *s, const SigMatchCtx *ctx); +static int DetectReplacePostMatch( + DetectEngineThreadCtx *det_ctx, Packet *p, const Signature *s, const SigMatchCtx *ctx); -void DetectReplaceRegister (void) +void DetectReplaceRegister(void) { sigmatch_table[DETECT_REPLACE].name = "replace"; - sigmatch_table[DETECT_REPLACE].desc = "only to be used in IPS-mode. Change the following content into another"; + sigmatch_table[DETECT_REPLACE].desc = + "only to be used in IPS-mode. Change the following content into another"; sigmatch_table[DETECT_REPLACE].url = "/rules/payload-keywords.html#replace"; sigmatch_table[DETECT_REPLACE].Match = DetectReplacePostMatch; sigmatch_table[DETECT_REPLACE].Setup = DetectReplaceSetup; #ifdef UNITTESTS sigmatch_table[DETECT_REPLACE].RegisterTests = DetectReplaceRegisterTests; #endif - sigmatch_table[DETECT_REPLACE].flags = (SIGMATCH_QUOTES_MANDATORY|SIGMATCH_HANDLE_NEGATION); + sigmatch_table[DETECT_REPLACE].flags = (SIGMATCH_QUOTES_MANDATORY | SIGMATCH_HANDLE_NEGATION); } -static int DetectReplacePostMatch(DetectEngineThreadCtx *det_ctx, - Packet *p, const Signature *s, const SigMatchCtx *ctx) +static int DetectReplacePostMatch( + DetectEngineThreadCtx *det_ctx, Packet *p, const Signature *s, const SigMatchCtx *ctx) { if (det_ctx->replist) { DetectReplaceExecuteInternal(p, det_ctx->replist); @@ -115,8 +116,7 @@ int DetectReplaceSetup(DetectEngineCtx *de_ctx, Signature *s, const char *replac return -1; /* add to the latest "content" keyword from pmatch */ - const SigMatch *pm = DetectGetLastSMByListId(s, DETECT_SM_LIST_PMATCH, - DETECT_CONTENT, -1); + const SigMatch *pm = DetectGetLastSMByListId(s, DETECT_SM_LIST_PMATCH, DETECT_CONTENT, -1); if (pm == NULL) { SCLogError("replace needs" "preceding content option for raw sig"); @@ -209,7 +209,6 @@ void DetectReplaceExecuteInternal(Packet *p, DetectReplaceList *replist) } } - void DetectReplaceFreeInternal(DetectReplaceList *replist) { DetectReplaceList *tlist = NULL; @@ -234,10 +233,8 @@ void DetectReplaceFreeInternal(DetectReplaceList *replist) * \retval return 1 if match * \retval return 0 if not */ -static -int DetectReplaceLongPatternMatchTest(uint8_t *raw_eth_pkt, uint16_t pktsize, - const char *sig, uint32_t sid, uint8_t *pp, - uint16_t *len) +static int DetectReplaceLongPatternMatchTest(uint8_t *raw_eth_pkt, uint16_t pktsize, + const char *sig, uint32_t sid, uint8_t *pp, uint16_t *len) { int result = 0; @@ -303,7 +300,6 @@ int DetectReplaceLongPatternMatchTest(uint8_t *raw_eth_pkt, uint16_t pktsize, SCLogDebug("replace: copying %d on %p", *len, pp); } - result = 1; end: if (dtv.app_tctx != NULL) @@ -315,15 +311,14 @@ int DetectReplaceLongPatternMatchTest(uint8_t *raw_eth_pkt, uint16_t pktsize, FlowShutdown(); SCFree(p); - return result; } - /** * \brief Wrapper for DetectContentLongPatternMatchTest */ -static int DetectReplaceLongPatternMatchTestWrp(const char *sig, uint32_t sid, const char *sig_rep, uint32_t sid_rep) +static int DetectReplaceLongPatternMatchTestWrp( + const char *sig, uint32_t sid, const char *sig_rep, uint32_t sid_rep) { int ret; /** Real packet with the following tcp data: @@ -396,10 +391,11 @@ static int DetectReplaceLongPatternMatchTestUDPWrp(const char *sig, uint32_t sid int run_mode_backup = run_mode; run_mode = RUNMODE_NFQ; - ret = DetectReplaceLongPatternMatchTest(raw_eth_pkt, (uint16_t)sizeof(raw_eth_pkt), - sig, sid, p, &psize); + ret = DetectReplaceLongPatternMatchTest( + raw_eth_pkt, (uint16_t)sizeof(raw_eth_pkt), sig, sid, p, &psize); if (ret == 1) { - SCLogDebug("replace: test1 phase1 ok: %" PRIuMAX" vs %d",(uintmax_t)sizeof(raw_eth_pkt),psize); + SCLogDebug("replace: test1 phase1 ok: %" PRIuMAX " vs %d", (uintmax_t)sizeof(raw_eth_pkt), + psize); ret = DetectReplaceLongPatternMatchTest(p, psize, sig_rep, sid_rep, NULL, NULL); } run_mode = run_mode_backup; @@ -412,9 +408,9 @@ static int DetectReplaceLongPatternMatchTestUDPWrp(const char *sig, uint32_t sid static int DetectReplaceMatchTest01(void) { const char *sig = "alert tcp any any -> any any (msg:\"Nothing..\";" - " content:\"big\"; replace:\"pig\"; sid:1;)"; + " content:\"big\"; replace:\"pig\"; sid:1;)"; const char *sig_rep = "alert tcp any any -> any any (msg:\"replace worked\";" - " content:\"this is a pig test\"; sid:2;)"; + " content:\"this is a pig test\"; sid:2;)"; FAIL_IF_NOT(DetectReplaceLongPatternMatchTestWrp(sig, 1, sig_rep, 2)); PASS; } @@ -425,9 +421,9 @@ static int DetectReplaceMatchTest01(void) static int DetectReplaceMatchTest02(void) { const char *sig = "alert tcp any any -> any any (msg:\"Nothing..\";" - " content:\"th\"; offset: 4; replace:\"TH\"; sid:1;)"; + " content:\"th\"; offset: 4; replace:\"TH\"; sid:1;)"; const char *sig_rep = "alert tcp any any -> any any (msg:\"replace worked\";" - " content:\"THis\"; offset:4; sid:2;)"; + " content:\"THis\"; offset:4; sid:2;)"; FAIL_IF_NOT(DetectReplaceLongPatternMatchTestWrp(sig, 1, sig_rep, 2)); PASS; } @@ -438,9 +434,9 @@ static int DetectReplaceMatchTest02(void) static int DetectReplaceMatchTest03(void) { const char *sig = "alert tcp any any -> any any (msg:\"Nothing..\";" - " content:\"th\"; replace:\"TH\"; offset: 4; sid:1;)"; + " content:\"th\"; replace:\"TH\"; offset: 4; sid:1;)"; const char *sig_rep = "alert tcp any any -> any any (msg:\"replace worked\";" - " content:\"THis\"; offset:4; sid:2;)"; + " content:\"THis\"; offset:4; sid:2;)"; FAIL_IF_NOT(DetectReplaceLongPatternMatchTestWrp(sig, 1, sig_rep, 2)); PASS; } @@ -450,10 +446,11 @@ static int DetectReplaceMatchTest03(void) */ static int DetectReplaceMatchTest04(void) { - const char *sig = "alert tcp any any -> any any (msg:\"Nothing..\";" - " content:\"th\"; replace:\"TH\"; content:\"patter\"; replace:\"matter\"; sid:1;)"; + const char *sig = + "alert tcp any any -> any any (msg:\"Nothing..\";" + " content:\"th\"; replace:\"TH\"; content:\"patter\"; replace:\"matter\"; sid:1;)"; const char *sig_rep = "alert tcp any any -> any any (msg:\"replace worked\";" - " content:\"THis\"; content:\"matterns\"; sid:2;)"; + " content:\"THis\"; content:\"matterns\"; sid:2;)"; FAIL_IF_NOT(DetectReplaceLongPatternMatchTestWrp(sig, 1, sig_rep, 2)); PASS; } @@ -464,9 +461,9 @@ static int DetectReplaceMatchTest04(void) static int DetectReplaceMatchTest05(void) { const char *sig = "alert tcp any any -> any any (msg:\"Nothing..\";" - " content:\"th\"; replace:\"TH\"; content:\"nutella\"; sid:1;)"; + " content:\"th\"; replace:\"TH\"; content:\"nutella\"; sid:1;)"; const char *sig_rep = "alert tcp any any -> any any (msg:\"replace worked\";" - " content:\"TH\"; sid:2;)"; + " content:\"TH\"; sid:2;)"; FAIL_IF(DetectReplaceLongPatternMatchTestWrp(sig, 1, sig_rep, 2)); PASS; } @@ -478,9 +475,9 @@ static int DetectReplaceMatchTest05(void) static int DetectReplaceMatchTest06(void) { const char *sig = "alert tcp any any -> any any (msg:\"Nothing..\";" - " content:\"nutella\"; replace:\"commode\"; content:\"this is\"; sid:1;)"; + " content:\"nutella\"; replace:\"commode\"; content:\"this is\"; sid:1;)"; const char *sig_rep = "alert tcp any any -> any any (msg:\"replace worked\";" - " content:\"commode\"; sid:2;)"; + " content:\"commode\"; sid:2;)"; FAIL_IF(DetectReplaceLongPatternMatchTestWrp(sig, 1, sig_rep, 2)); PASS; } @@ -491,9 +488,9 @@ static int DetectReplaceMatchTest06(void) static int DetectReplaceMatchTest07(void) { const char *sig = "alert tcp any any -> any any (msg:\"Nothing..\";" - " content:\"BiG\"; nocase; replace:\"pig\"; sid:1;)"; + " content:\"BiG\"; nocase; replace:\"pig\"; sid:1;)"; const char *sig_rep = "alert tcp any any -> any any (msg:\"replace worked\";" - " content:\"this is a pig test\"; sid:2;)"; + " content:\"this is a pig test\"; sid:2;)"; FAIL_IF_NOT(DetectReplaceLongPatternMatchTestWrp(sig, 1, sig_rep, 2)); PASS; } @@ -504,9 +501,9 @@ static int DetectReplaceMatchTest07(void) static int DetectReplaceMatchTest08(void) { const char *sig = "alert tcp any any -> any any (msg:\"Nothing..\";" - " content:\"big\"; depth:17; replace:\"pig\"; sid:1;)"; + " content:\"big\"; depth:17; replace:\"pig\"; sid:1;)"; const char *sig_rep = "alert tcp any any -> any any (msg:\"replace worked\";" - " content:\"this is a pig test\"; sid:2;)"; + " content:\"this is a pig test\"; sid:2;)"; FAIL_IF_NOT(DetectReplaceLongPatternMatchTestWrp(sig, 1, sig_rep, 2)); PASS; } @@ -517,9 +514,9 @@ static int DetectReplaceMatchTest08(void) static int DetectReplaceMatchTest09(void) { const char *sig = "alert tcp any any -> any any (msg:\"Nothing..\";" - " content:\"big\"; depth:16; replace:\"pig\"; sid:1;)"; + " content:\"big\"; depth:16; replace:\"pig\"; sid:1;)"; const char *sig_rep = "alert tcp any any -> any any (msg:\"replace worked\";" - " content:\"this is a pig test\"; sid:2;)"; + " content:\"this is a pig test\"; sid:2;)"; FAIL_IF(DetectReplaceLongPatternMatchTestWrp(sig, 1, sig_rep, 2)); PASS; } @@ -530,9 +527,9 @@ static int DetectReplaceMatchTest09(void) static int DetectReplaceMatchTest10(void) { const char *sig = "alert tcp any any -> any any (msg:\"Nothing..\";" - " content:\"big\"; depth:17; replace:\"pig\"; offset: 14; sid:1;)"; + " content:\"big\"; depth:17; replace:\"pig\"; offset: 14; sid:1;)"; const char *sig_rep = "alert tcp any any -> any any (msg:\"replace worked\";" - " content:\"pig\"; depth:17; offset:14; sid:2;)"; + " content:\"pig\"; depth:17; offset:14; sid:2;)"; FAIL_IF_NOT(DetectReplaceLongPatternMatchTestWrp(sig, 1, sig_rep, 2)); PASS; } @@ -543,9 +540,9 @@ static int DetectReplaceMatchTest10(void) static int DetectReplaceMatchTest11(void) { const char *sig = "alert tcp any any -> any any (msg:\"Nothing..\";" - " content:\"big\"; replace:\"pig\"; content:\"to\"; within: 11; sid:1;)"; + " content:\"big\"; replace:\"pig\"; content:\"to\"; within: 11; sid:1;)"; const char *sig_rep = "alert tcp any any -> any any (msg:\"replace worked\";" - " content:\"pig\"; depth:17; offset:14; sid:2;)"; + " content:\"pig\"; depth:17; offset:14; sid:2;)"; FAIL_IF_NOT(DetectReplaceLongPatternMatchTestWrp(sig, 1, sig_rep, 2)); PASS; @@ -557,9 +554,9 @@ static int DetectReplaceMatchTest11(void) static int DetectReplaceMatchTest12(void) { const char *sig = "alert tcp any any -> any any (msg:\"Nothing..\";" - " content:\"big\"; replace:\"pig\"; content:\"to\"; within: 4; sid:1;)"; + " content:\"big\"; replace:\"pig\"; content:\"to\"; within: 4; sid:1;)"; const char *sig_rep = "alert tcp any any -> any any (msg:\"replace worked\";" - " content:\"pig\"; depth:17; offset:14; sid:2;)"; + " content:\"pig\"; depth:17; offset:14; sid:2;)"; FAIL_IF(DetectReplaceLongPatternMatchTestWrp(sig, 1, sig_rep, 2)); PASS; } @@ -570,9 +567,9 @@ static int DetectReplaceMatchTest12(void) static int DetectReplaceMatchTest13(void) { const char *sig = "alert tcp any any -> any any (msg:\"Nothing..\";" - " content:\"big\"; replace:\"pig\"; content:\"test\"; distance: 1; sid:1;)"; + " content:\"big\"; replace:\"pig\"; content:\"test\"; distance: 1; sid:1;)"; const char *sig_rep = "alert tcp any any -> any any (msg:\"replace worked\";" - " content:\"pig\"; depth:17; offset:14; sid:2;)"; + " content:\"pig\"; depth:17; offset:14; sid:2;)"; FAIL_IF_NOT(DetectReplaceLongPatternMatchTestWrp(sig, 1, sig_rep, 2)); PASS; } @@ -583,9 +580,9 @@ static int DetectReplaceMatchTest13(void) static int DetectReplaceMatchTest14(void) { const char *sig = "alert tcp any any -> any any (msg:\"Nothing..\";" - " content:\"big\"; replace:\"pig\"; content:\"test\"; distance: 2; sid:1;)"; + " content:\"big\"; replace:\"pig\"; content:\"test\"; distance: 2; sid:1;)"; const char *sig_rep = "alert tcp any any -> any any (msg:\"replace worked\";" - " content:\"pig\"; depth:17; offset:14; sid:2;)"; + " content:\"pig\"; depth:17; offset:14; sid:2;)"; FAIL_IF(DetectReplaceLongPatternMatchTestWrp(sig, 1, sig_rep, 2)); PASS; } @@ -596,14 +593,13 @@ static int DetectReplaceMatchTest14(void) static int DetectReplaceMatchTest15(void) { const char *sig = "alert udp any any -> any any (msg:\"Nothing..\";" - " content:\"com\"; replace:\"org\"; sid:1;)"; + " content:\"com\"; replace:\"org\"; sid:1;)"; const char *sig_rep = "alert udp any any -> any any (msg:\"replace worked\";" - " content:\"twimg|03|org\"; sid:2;)"; + " content:\"twimg|03|org\"; sid:2;)"; FAIL_IF_NOT(DetectReplaceLongPatternMatchTestUDPWrp(sig, 1, sig_rep, 2)); PASS; } - /** * \test Parsing test */ @@ -758,7 +754,7 @@ static int DetectReplaceParseTest07(void) */ void DetectReplaceRegisterTests(void) { -/* matching */ + /* matching */ UtRegisterTest("DetectReplaceMatchTest01", DetectReplaceMatchTest01); UtRegisterTest("DetectReplaceMatchTest02", DetectReplaceMatchTest02); UtRegisterTest("DetectReplaceMatchTest03", DetectReplaceMatchTest03); @@ -774,7 +770,7 @@ void DetectReplaceRegisterTests(void) UtRegisterTest("DetectReplaceMatchTest13", DetectReplaceMatchTest13); UtRegisterTest("DetectReplaceMatchTest14", DetectReplaceMatchTest14); UtRegisterTest("DetectReplaceMatchTest15", DetectReplaceMatchTest15); -/* parsing */ + /* parsing */ UtRegisterTest("DetectReplaceParseTest01", DetectReplaceParseTest01); UtRegisterTest("DetectReplaceParseTest02", DetectReplaceParseTest02); UtRegisterTest("DetectReplaceParseTest03", DetectReplaceParseTest03); diff --git a/src/detect-replace.h b/src/detect-replace.h index 4944420527e8..b95b06a6042b 100644 --- a/src/detect-replace.h +++ b/src/detect-replace.h @@ -41,6 +41,6 @@ static inline void DetectReplaceFree(DetectEngineThreadCtx *det_ctx) } } -void DetectReplaceRegister (void); +void DetectReplaceRegister(void); #endif diff --git a/src/detect-rev.c b/src/detect-rev.c index dda513cc0a9f..5b2e049e50cd 100644 --- a/src/detect-rev.c +++ b/src/detect-rev.c @@ -29,9 +29,9 @@ #include "util-debug.h" #include "util-error.h" -static int DetectRevSetup (DetectEngineCtx *, Signature *, const char *); +static int DetectRevSetup(DetectEngineCtx *, Signature *, const char *); -void DetectRevRegister (void) +void DetectRevRegister(void) { sigmatch_table[DETECT_REV].name = "rev"; sigmatch_table[DETECT_REV].desc = "set version of the rule"; @@ -39,7 +39,7 @@ void DetectRevRegister (void) sigmatch_table[DETECT_REV].Setup = DetectRevSetup; } -static int DetectRevSetup (DetectEngineCtx *de_ctx, Signature *s, const char *rawstr) +static int DetectRevSetup(DetectEngineCtx *de_ctx, Signature *s, const char *rawstr) { unsigned long rev = 0; char *endptr = NULL; @@ -66,6 +66,6 @@ static int DetectRevSetup (DetectEngineCtx *de_ctx, Signature *s, const char *ra return 0; - error: +error: return -1; } \ No newline at end of file diff --git a/src/detect-rev.h b/src/detect-rev.h index 24ae202f1274..e0324b64394f 100644 --- a/src/detect-rev.h +++ b/src/detect-rev.h @@ -25,7 +25,6 @@ #define __DETECT_REV_H__ /* prototypes */ -void DetectRevRegister (void); +void DetectRevRegister(void); #endif /* __DETECT_REV_H__ */ - diff --git a/src/detect-rfb-name.c b/src/detect-rfb-name.c index 5e8251d51a5a..24c9c388342b 100644 --- a/src/detect-rfb-name.c +++ b/src/detect-rfb-name.c @@ -68,8 +68,8 @@ static int DetectRfbNameSetup(DetectEngineCtx *de_ctx, Signature *s, const char } static InspectionBuffer *GetData(DetectEngineThreadCtx *det_ctx, - const DetectEngineTransforms *transforms, Flow *_f, - const uint8_t _flow_flags, void *txv, const int list_id) + const DetectEngineTransforms *transforms, Flow *_f, const uint8_t _flow_flags, void *txv, + const int list_id) { InspectionBuffer *buffer = InspectionBufferGet(det_ctx, list_id); if (buffer->inspect == NULL) { @@ -91,18 +91,17 @@ static InspectionBuffer *GetData(DetectEngineThreadCtx *det_ctx, void DetectRfbNameRegister(void) { sigmatch_table[DETECT_AL_RFB_NAME].name = KEYWORD_NAME; - sigmatch_table[DETECT_AL_RFB_NAME].url = "/rules/" KEYWORD_DOC - sigmatch_table[DETECT_AL_RFB_NAME].desc = "sticky buffer to match on the RFB desktop name"; + sigmatch_table[DETECT_AL_RFB_NAME].url = + "/rules/" KEYWORD_DOC sigmatch_table[DETECT_AL_RFB_NAME].desc = + "sticky buffer to match on the RFB desktop name"; sigmatch_table[DETECT_AL_RFB_NAME].Setup = DetectRfbNameSetup; - sigmatch_table[DETECT_AL_RFB_NAME].flags |= SIGMATCH_NOOPT|SIGMATCH_INFO_STICKY_BUFFER; + sigmatch_table[DETECT_AL_RFB_NAME].flags |= SIGMATCH_NOOPT | SIGMATCH_INFO_STICKY_BUFFER; - DetectAppLayerInspectEngineRegister2(BUFFER_NAME, ALPROTO_RFB, - SIG_FLAG_TOCLIENT, 1, + DetectAppLayerInspectEngineRegister2(BUFFER_NAME, ALPROTO_RFB, SIG_FLAG_TOCLIENT, 1, DetectEngineInspectBufferGeneric, GetData); - DetectAppLayerMpmRegister2(BUFFER_NAME, SIG_FLAG_TOCLIENT, 1, - PrefilterGenericMpmRegister, GetData, ALPROTO_RFB, - 1); + DetectAppLayerMpmRegister2(BUFFER_NAME, SIG_FLAG_TOCLIENT, 1, PrefilterGenericMpmRegister, + GetData, ALPROTO_RFB, 1); DetectBufferTypeSetDescriptionByName(BUFFER_NAME, BUFFER_DESC); diff --git a/src/detect-rfb-secresult.c b/src/detect-rfb-secresult.c index 403c16d08aa5..05fecaea0172 100644 --- a/src/detect-rfb-secresult.c +++ b/src/detect-rfb-secresult.c @@ -37,11 +37,9 @@ static DetectParseRegex parse_regex; static int rfb_secresult_id = 0; -static int DetectRfbSecresultMatch(DetectEngineThreadCtx *det_ctx, - Flow *f, uint8_t flags, void *state, - void *txv, const Signature *s, - const SigMatchCtx *ctx); -static int DetectRfbSecresultSetup (DetectEngineCtx *, Signature *, const char *); +static int DetectRfbSecresultMatch(DetectEngineThreadCtx *det_ctx, Flow *f, uint8_t flags, + void *state, void *txv, const Signature *s, const SigMatchCtx *ctx); +static int DetectRfbSecresultSetup(DetectEngineCtx *, Signature *, const char *); #ifdef UNITTESTS static void RfbSecresultRegisterTests(void); #endif @@ -54,14 +52,14 @@ typedef struct DetectRfbSecresultData_ { /** * \brief Registration function for rfb.secresult: keyword */ -void DetectRfbSecresultRegister (void) +void DetectRfbSecresultRegister(void) { sigmatch_table[DETECT_AL_RFB_SECRESULT].name = "rfb.secresult"; sigmatch_table[DETECT_AL_RFB_SECRESULT].desc = "match RFB security result"; sigmatch_table[DETECT_AL_RFB_SECRESULT].url = "/rules/rfb-keywords.html#rfb-secresult"; sigmatch_table[DETECT_AL_RFB_SECRESULT].AppLayerTxMatch = DetectRfbSecresultMatch; sigmatch_table[DETECT_AL_RFB_SECRESULT].Setup = DetectRfbSecresultSetup; - sigmatch_table[DETECT_AL_RFB_SECRESULT].Free = DetectRfbSecresultFree; + sigmatch_table[DETECT_AL_RFB_SECRESULT].Free = DetectRfbSecresultFree; #ifdef UNITTESTS sigmatch_table[DETECT_AL_RFB_SECRESULT].RegisterTests = RfbSecresultRegisterTests; #endif @@ -73,12 +71,7 @@ void DetectRfbSecresultRegister (void) rfb_secresult_id = DetectBufferTypeGetByName("rfb.secresult"); } -enum { - RFB_SECRESULT_OK = 0, - RFB_SECRESULT_FAIL, - RFB_SECRESULT_TOOMANY, - RFB_SECRESULT_UNKNOWN -}; +enum { RFB_SECRESULT_OK = 0, RFB_SECRESULT_FAIL, RFB_SECRESULT_TOOMANY, RFB_SECRESULT_UNKNOWN }; /** * \struct DetectRfbSecresult_ @@ -89,10 +82,22 @@ struct DetectRfbSecresult_ { const char *result; uint16_t code; } results[] = { - { "ok", RFB_SECRESULT_OK, }, - { "fail", RFB_SECRESULT_FAIL, }, - { "toomany", RFB_SECRESULT_TOOMANY, }, - { "unknown", RFB_SECRESULT_UNKNOWN, }, + { + "ok", + RFB_SECRESULT_OK, + }, + { + "fail", + RFB_SECRESULT_FAIL, + }, + { + "toomany", + RFB_SECRESULT_TOOMANY, + }, + { + "unknown", + RFB_SECRESULT_UNKNOWN, + }, { NULL, 0 }, }; @@ -111,10 +116,8 @@ struct DetectRfbSecresult_ { * \retval 0 no match. * \retval 1 match. */ -static int DetectRfbSecresultMatch(DetectEngineThreadCtx *det_ctx, - Flow *f, uint8_t flags, void *state, - void *txv, const Signature *s, - const SigMatchCtx *ctx) +static int DetectRfbSecresultMatch(DetectEngineThreadCtx *det_ctx, Flow *f, uint8_t flags, + void *state, void *txv, const Signature *s, const SigMatchCtx *ctx) { const DetectRfbSecresultData *de = (const DetectRfbSecresultData *)ctx; uint32_t resultcode; @@ -154,7 +157,7 @@ static int DetectRfbSecresultMatch(DetectEngineThreadCtx *det_ctx, * \retval de pointer to DetectRfbSecresultData on success * \retval NULL on failure */ -static DetectRfbSecresultData *DetectRfbSecresultParse (const char *rawstr) +static DetectRfbSecresultData *DetectRfbSecresultParse(const char *rawstr) { int i; DetectRfbSecresultData *de = NULL; @@ -167,14 +170,14 @@ static DetectRfbSecresultData *DetectRfbSecresultParse (const char *rawstr) goto error; } - for(i = 0; results[i].result != NULL; i++) { - if((strcasecmp(results[i].result,rawstr)) == 0) { + for (i = 0; results[i].result != NULL; i++) { + if ((strcasecmp(results[i].result, rawstr)) == 0) { found = 1; break; } } - if(found == 0) { + if (found == 0) { SCLogError("unknown secresult value %s", rawstr); goto error; } @@ -192,7 +195,8 @@ static DetectRfbSecresultData *DetectRfbSecresultParse (const char *rawstr) if (match) { pcre2_match_data_free(match); } - if (de) SCFree(de); + if (de) + SCFree(de); return NULL; } @@ -207,7 +211,7 @@ static DetectRfbSecresultData *DetectRfbSecresultParse (const char *rawstr) * \retval 0 on Success * \retval -1 on Failure */ -static int DetectRfbSecresultSetup (DetectEngineCtx *de_ctx, Signature *s, const char *rawstr) +static int DetectRfbSecresultSetup(DetectEngineCtx *de_ctx, Signature *s, const char *rawstr) { DetectRfbSecresultData *de = NULL; @@ -240,7 +244,8 @@ static int DetectRfbSecresultSetup (DetectEngineCtx *de_ctx, Signature *s, const void DetectRfbSecresultFree(DetectEngineCtx *de_ctx, void *de_ptr) { DetectRfbSecresultData *de = (DetectRfbSecresultData *)de_ptr; - if(de) SCFree(de); + if (de) + SCFree(de); } /* @@ -251,7 +256,7 @@ void DetectRfbSecresultFree(DetectEngineCtx *de_ctx, void *de_ptr) /** * \test RfbSecresultTestParse01 is a test for a valid secresult value */ -static int RfbSecresultTestParse01 (void) +static int RfbSecresultTestParse01(void) { DetectRfbSecresultData *de = DetectRfbSecresultParse("fail"); @@ -265,7 +270,7 @@ static int RfbSecresultTestParse01 (void) /** * \test RfbSecresultTestParse02 is a test for an invalid secresult value */ -static int RfbSecresultTestParse02 (void) +static int RfbSecresultTestParse02(void) { DetectRfbSecresultData *de = DetectRfbSecresultParse("invalidopt"); diff --git a/src/detect-rfb-sectype.c b/src/detect-rfb-sectype.c index d942a4503a49..8dae6f26edd8 100644 --- a/src/detect-rfb-sectype.c +++ b/src/detect-rfb-sectype.c @@ -33,19 +33,17 @@ #include "rust-bindings.h" - -static int DetectRfbSectypeSetup (DetectEngineCtx *, Signature *s, const char *str); +static int DetectRfbSectypeSetup(DetectEngineCtx *, Signature *s, const char *str); static void DetectRfbSectypeFree(DetectEngineCtx *, void *); static int g_rfb_sectype_buffer_id = 0; -static int DetectRfbSectypeMatch (DetectEngineThreadCtx *, Flow *, - uint8_t, void *, void *, const Signature *, - const SigMatchCtx *); +static int DetectRfbSectypeMatch(DetectEngineThreadCtx *, Flow *, uint8_t, void *, void *, + const Signature *, const SigMatchCtx *); /** * \brief Registration function for rfb.sectype keyword. */ -void DetectRfbSectypeRegister (void) +void DetectRfbSectypeRegister(void) { sigmatch_table[DETECT_AL_RFB_SECTYPE].name = "rfb.sectype"; sigmatch_table[DETECT_AL_RFB_SECTYPE].desc = "match RFB security type"; @@ -75,10 +73,8 @@ void DetectRfbSectypeRegister (void) * \retval 0 no match. * \retval 1 match. */ -static int DetectRfbSectypeMatch (DetectEngineThreadCtx *det_ctx, - Flow *f, uint8_t flags, void *state, - void *txv, const Signature *s, - const SigMatchCtx *ctx) +static int DetectRfbSectypeMatch(DetectEngineThreadCtx *det_ctx, Flow *f, uint8_t flags, + void *state, void *txv, const Signature *s, const SigMatchCtx *ctx) { SCEnter(); @@ -114,7 +110,7 @@ static DetectU32Data *DetectRfbSectypeParse(const char *rawstr) * \retval 0 on Success. * \retval -1 on Failure. */ -static int DetectRfbSectypeSetup (DetectEngineCtx *de_ctx, Signature *s, const char *rawstr) +static int DetectRfbSectypeSetup(DetectEngineCtx *de_ctx, Signature *s, const char *rawstr) { if (DetectSignatureSetAppProto(s, ALPROTO_RFB) != 0) return -1; diff --git a/src/detect-rpc.c b/src/detect-rpc.c index 7ca84925305c..21e6f2f0aea5 100644 --- a/src/detect-rpc.c +++ b/src/detect-rpc.c @@ -43,13 +43,14 @@ /** * \brief Regex for parsing our rpc options */ -#define PARSE_REGEX "^\\s*([0-9]{0,10})\\s*(?:,\\s*([0-9]{0,10}|[*])\\s*(?:,\\s*([0-9]{0,10}|[*]))?)?\\s*$" +#define PARSE_REGEX \ + "^\\s*([0-9]{0,10})\\s*(?:,\\s*([0-9]{0,10}|[*])\\s*(?:,\\s*([0-9]{0,10}|[*]))?)?\\s*$" static DetectParseRegex parse_regex; -static int DetectRpcMatch (DetectEngineThreadCtx *, Packet *, - const Signature *, const SigMatchCtx *); -static int DetectRpcSetup (DetectEngineCtx *, Signature *, const char *); +static int DetectRpcMatch( + DetectEngineThreadCtx *, Packet *, const Signature *, const SigMatchCtx *); +static int DetectRpcSetup(DetectEngineCtx *, Signature *, const char *); #ifdef UNITTESTS static void DetectRpcRegisterTests(void); #endif @@ -58,14 +59,14 @@ void DetectRpcFree(DetectEngineCtx *, void *); /** * \brief Registration function for rpc keyword */ -void DetectRpcRegister (void) +void DetectRpcRegister(void) { sigmatch_table[DETECT_RPC].name = "rpc"; sigmatch_table[DETECT_RPC].desc = "match RPC procedure numbers and RPC version"; sigmatch_table[DETECT_RPC].url = "/rules/payload-keywords.html#rpc"; sigmatch_table[DETECT_RPC].Match = DetectRpcMatch; sigmatch_table[DETECT_RPC].Setup = DetectRpcSetup; - sigmatch_table[DETECT_RPC].Free = DetectRpcFree; + sigmatch_table[DETECT_RPC].Free = DetectRpcFree; #ifdef UNITTESTS sigmatch_table[DETECT_RPC].RegisterTests = DetectRpcRegisterTests; #endif @@ -89,8 +90,8 @@ void DetectRpcRegister (void) * \retval 0 no match * \retval 1 match */ -static int DetectRpcMatch (DetectEngineThreadCtx *det_ctx, Packet *p, - const Signature *s, const SigMatchCtx *ctx) +static int DetectRpcMatch( + DetectEngineThreadCtx *det_ctx, Packet *p, const Signature *s, const SigMatchCtx *ctx) { /* PrintRawDataFp(stdout, p->payload, p->payload_len); */ const DetectRpcData *rd = (const DetectRpcData *)ctx; @@ -132,7 +133,8 @@ static int DetectRpcMatch (DetectEngineThreadCtx *det_ctx, Packet *p, if ((rd->flags & DETECT_RPC_CHECK_PROCEDURE) && SCNtohl(msg->proc) != rd->procedure) return 0; - SCLogDebug("prog:%u pver:%u proc:%u matched", SCNtohl(msg->prog), SCNtohl(msg->vers), SCNtohl(msg->proc)); + SCLogDebug("prog:%u pver:%u proc:%u matched", SCNtohl(msg->prog), SCNtohl(msg->vers), + SCNtohl(msg->proc)); return 1; } @@ -145,10 +147,10 @@ static int DetectRpcMatch (DetectEngineThreadCtx *det_ctx, Packet *p, * \retval rd pointer to DetectRpcData on success * \retval NULL on failure */ -static DetectRpcData *DetectRpcParse (DetectEngineCtx *de_ctx, const char *rpcstr) +static DetectRpcData *DetectRpcParse(DetectEngineCtx *de_ctx, const char *rpcstr) { DetectRpcData *rd = NULL; - char *args[3] = {NULL,NULL,NULL}; + char *args[3] = { NULL, NULL, NULL }; int res = 0; size_t pcre2_len; @@ -207,7 +209,8 @@ static DetectRpcData *DetectRpcParse (DetectEngineCtx *de_ctx, const char *rpcst break; case 1: if (args[i][0] != '*') { - if (StringParseUint32(&rd->program_version, 10, strlen(args[i]), args[i]) <= 0) { + if (StringParseUint32(&rd->program_version, 10, strlen(args[i]), args[i]) <= + 0) { SCLogError( "Invalid size specified for the rpc version:\"%s\"", args[i]); goto error; @@ -224,14 +227,14 @@ static DetectRpcData *DetectRpcParse (DetectEngineCtx *de_ctx, const char *rpcst } rd->flags |= DETECT_RPC_CHECK_PROCEDURE; } - break; + break; } } else { SCLogError("invalid rpc option %s", rpcstr); goto error; } } - for (i = 0; i < (ret -1); i++){ + for (i = 0; i < (ret - 1); i++) { if (args[i] != NULL) pcre2_substring_free((PCRE2_UCHAR8 *)args[i]); } @@ -242,14 +245,13 @@ static DetectRpcData *DetectRpcParse (DetectEngineCtx *de_ctx, const char *rpcst if (match) { pcre2_match_data_free(match); } - for (i = 0; i < (ret -1) && i < 3; i++){ + for (i = 0; i < (ret - 1) && i < 3; i++) { if (args[i] != NULL) pcre2_substring_free((PCRE2_UCHAR8 *)args[i]); } if (rd != NULL) DetectRpcFree(de_ctx, rd); return NULL; - } /** @@ -263,12 +265,13 @@ static DetectRpcData *DetectRpcParse (DetectEngineCtx *de_ctx, const char *rpcst * \retval 0 on Success * \retval -1 on Failure */ -int DetectRpcSetup (DetectEngineCtx *de_ctx, Signature *s, const char *rpcstr) +int DetectRpcSetup(DetectEngineCtx *de_ctx, Signature *s, const char *rpcstr) { DetectRpcData *rd = NULL; rd = DetectRpcParse(de_ctx, rpcstr); - if (rd == NULL) goto error; + if (rd == NULL) + goto error; if (SigMatchAppendSMToList(de_ctx, s, DETECT_RPC, (SigMatchCtx *)rd, DETECT_SM_LIST_MATCH) == NULL) { @@ -282,7 +285,6 @@ int DetectRpcSetup (DetectEngineCtx *de_ctx, Signature *s, const char *rpcstr) if (rd != NULL) DetectRpcFree(de_ctx, rd); return -1; - } /** @@ -310,7 +312,7 @@ void DetectRpcFree(DetectEngineCtx *de_ctx, void *ptr) * \test DetectRpcTestParse01 is a test to make sure that we return "something" * when given valid rpc opt */ -static int DetectRpcTestParse01 (void) +static int DetectRpcTestParse01(void) { DetectRpcData *rd = DetectRpcParse(NULL, "123,444,555"); FAIL_IF_NULL(rd); @@ -322,7 +324,7 @@ static int DetectRpcTestParse01 (void) /** * \test DetectRpcTestParse02 is a test for setting the established rpc opt */ -static int DetectRpcTestParse02 (void) +static int DetectRpcTestParse02(void) { DetectRpcData *rd = NULL; rd = DetectRpcParse(NULL, "111,222,333"); @@ -343,7 +345,7 @@ static int DetectRpcTestParse02 (void) * \test DetectRpcTestParse03 is a test for checking the wildcards * and not specified fields */ -static int DetectRpcTestParse03 (void) +static int DetectRpcTestParse03(void) { DetectRpcData *rd = NULL; @@ -412,7 +414,7 @@ static int DetectRpcTestParse03 (void) /** * \test DetectRpcTestParse04 is a test for check the discarding of empty options */ -static int DetectRpcTestParse04 (void) +static int DetectRpcTestParse04(void) { DetectRpcData *rd = NULL; rd = DetectRpcParse(NULL, ""); @@ -426,7 +428,7 @@ static int DetectRpcTestParse04 (void) /** * \test DetectRpcTestParse05 is a test for check invalid values */ -static int DetectRpcTestParse05 (void) +static int DetectRpcTestParse05(void) { DetectRpcData *rd = NULL; rd = DetectRpcParse(NULL, "111,aaa,*"); diff --git a/src/detect-rpc.h b/src/detect-rpc.h index 4b4e60b1603d..bae6ce5ae2de 100644 --- a/src/detect-rpc.h +++ b/src/detect-rpc.h @@ -27,18 +27,18 @@ /* At least we check the program, the version is optional, * and the procedure is optional if we are checking the version. * If we parse the wildcard "*" we will allow any value (no check) */ -#define DETECT_RPC_CHECK_PROGRAM 0x01 -#define DETECT_RPC_CHECK_VERSION 0x02 -#define DETECT_RPC_CHECK_PROCEDURE 0x04 +#define DETECT_RPC_CHECK_PROGRAM 0x01 +#define DETECT_RPC_CHECK_VERSION 0x02 +#define DETECT_RPC_CHECK_PROCEDURE 0x04 /** Simple struct for a rpc msg call */ typedef struct RpcMsg_ { - uint32_t xid; - uint32_t type; /**< CALL = 0 (We only search for CALLS */ - uint32_t rpcvers; /**< must be equal to two (2) */ - uint32_t prog; - uint32_t vers; - uint32_t proc; + uint32_t xid; + uint32_t type; /**< CALL = 0 (We only search for CALLS */ + uint32_t rpcvers; /**< must be equal to two (2) */ + uint32_t prog; + uint32_t vers; + uint32_t proc; } RpcMsg; typedef struct DetectRpcData_ { @@ -49,7 +49,6 @@ typedef struct DetectRpcData_ { } DetectRpcData; /* prototypes */ -void DetectRpcRegister (void); +void DetectRpcRegister(void); #endif /* __DETECT_RPC_H__ */ - diff --git a/src/detect-sameip.c b/src/detect-sameip.c index 2ed72cf00e3a..c12b32b2088a 100644 --- a/src/detect-sameip.c +++ b/src/detect-sameip.c @@ -37,8 +37,8 @@ #include "util-unittest.h" #include "util-unittest-helper.h" -static int DetectSameipMatch(DetectEngineThreadCtx *, Packet *, - const Signature *, const SigMatchCtx *); +static int DetectSameipMatch( + DetectEngineThreadCtx *, Packet *, const Signature *, const SigMatchCtx *); static int DetectSameipSetup(DetectEngineCtx *, Signature *, const char *); #ifdef UNITTESTS static void DetectSameipRegisterTests(void); @@ -51,7 +51,8 @@ static void DetectSameipRegisterTests(void); void DetectSameipRegister(void) { sigmatch_table[DETECT_SAMEIP].name = "sameip"; - sigmatch_table[DETECT_SAMEIP].desc = "check if the IP address of the source is the same as the IP address of the destination"; + sigmatch_table[DETECT_SAMEIP].desc = "check if the IP address of the source is the same as the " + "IP address of the destination"; sigmatch_table[DETECT_SAMEIP].url = "/rules/header-keywords.html#sameip"; sigmatch_table[DETECT_SAMEIP].Match = DetectSameipMatch; sigmatch_table[DETECT_SAMEIP].Setup = DetectSameipSetup; @@ -73,8 +74,8 @@ void DetectSameipRegister(void) * \retval 0 no match * \retval 1 match */ -static int DetectSameipMatch(DetectEngineThreadCtx *det_ctx, - Packet *p, const Signature *s, const SigMatchCtx *ctx) +static int DetectSameipMatch( + DetectEngineThreadCtx *det_ctx, Packet *p, const Signature *s, const SigMatchCtx *ctx) { return CMP_ADDR(&p->src, &p->dst) ? 1 : 0; } @@ -117,9 +118,8 @@ static int DetectSameipSetup(DetectEngineCtx *de_ctx, Signature *s, const char * */ static int DetectSameipSigTest01(void) { - uint8_t *buf = (uint8_t *) - "GET / HTTP/1.0\r\n" - "\r\n"; + uint8_t *buf = (uint8_t *)"GET / HTTP/1.0\r\n" + "\r\n"; uint16_t buflen = strlen((char *)buf); Packet *p1 = NULL; Packet *p2 = NULL; @@ -139,9 +139,8 @@ static int DetectSameipSigTest01(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx, - "alert tcp any any -> any any " - "(msg:\"Testing sameip\"; sameip; sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " + "(msg:\"Testing sameip\"; sameip; sid:1;)"); FAIL_IF_NULL(de_ctx->sig_list); SigGroupBuild(de_ctx); diff --git a/src/detect-sid.c b/src/detect-sid.c index 0002e1066384..42211c7de280 100644 --- a/src/detect-sid.c +++ b/src/detect-sid.c @@ -32,12 +32,12 @@ #include "util-error.h" #include "util-unittest.h" -static int DetectSidSetup (DetectEngineCtx *, Signature *, const char *); +static int DetectSidSetup(DetectEngineCtx *, Signature *, const char *); #ifdef UNITTESTS static void DetectSidRegisterTests(void); #endif -void DetectSidRegister (void) +void DetectSidRegister(void) { sigmatch_table[DETECT_SID].name = "sid"; sigmatch_table[DETECT_SID].desc = "set rule ID"; @@ -49,7 +49,7 @@ void DetectSidRegister (void) #endif } -static int DetectSidSetup (DetectEngineCtx *de_ctx, Signature *s, const char *sidstr) +static int DetectSidSetup(DetectEngineCtx *de_ctx, Signature *s, const char *sidstr) { unsigned long id = 0; char *endptr = NULL; @@ -75,7 +75,7 @@ static int DetectSidSetup (DetectEngineCtx *de_ctx, Signature *s, const char *si s->id = (uint32_t)id; return 0; - error: +error: return -1; } diff --git a/src/detect-sid.h b/src/detect-sid.h index f7389d105ded..e74cf871df97 100644 --- a/src/detect-sid.h +++ b/src/detect-sid.h @@ -25,7 +25,6 @@ #define __DETECT_SID_H__ /* prototypes */ -void DetectSidRegister (void); +void DetectSidRegister(void); #endif /* __DETECT_SID_H__ */ - diff --git a/src/detect-sip-method.c b/src/detect-sip-method.c index fccc8a73f9fc..d8b55b69e483 100644 --- a/src/detect-sip-method.c +++ b/src/detect-sip-method.c @@ -105,8 +105,8 @@ static bool DetectSipMethodValidateCallback(const Signature *s, const char **sig } static InspectionBuffer *GetData(DetectEngineThreadCtx *det_ctx, - const DetectEngineTransforms *transforms, Flow *_f, - const uint8_t _flow_flags, void *txv, const int list_id) + const DetectEngineTransforms *transforms, Flow *_f, const uint8_t _flow_flags, void *txv, + const int list_id) { InspectionBuffer *buffer = InspectionBufferGet(det_ctx, list_id); if (buffer->inspect == NULL) { @@ -134,18 +134,15 @@ void DetectSipMethodRegister(void) sigmatch_table[DETECT_AL_SIP_METHOD].Setup = DetectSipMethodSetup; sigmatch_table[DETECT_AL_SIP_METHOD].flags |= SIGMATCH_NOOPT; - DetectAppLayerInspectEngineRegister2(BUFFER_NAME, ALPROTO_SIP, - SIG_FLAG_TOSERVER, 0, + DetectAppLayerInspectEngineRegister2(BUFFER_NAME, ALPROTO_SIP, SIG_FLAG_TOSERVER, 0, DetectEngineInspectBufferGeneric, GetData); - DetectAppLayerMpmRegister2(BUFFER_NAME, SIG_FLAG_TOSERVER, 2, - PrefilterGenericMpmRegister, GetData, ALPROTO_SIP, - 1); + DetectAppLayerMpmRegister2(BUFFER_NAME, SIG_FLAG_TOSERVER, 2, PrefilterGenericMpmRegister, + GetData, ALPROTO_SIP, 1); DetectBufferTypeSetDescriptionByName(BUFFER_NAME, BUFFER_DESC); - DetectBufferTypeRegisterValidateCallback(BUFFER_NAME, - DetectSipMethodValidateCallback); + DetectBufferTypeRegisterValidateCallback(BUFFER_NAME, DetectSipMethodValidateCallback); g_buffer_id = DetectBufferTypeGetByName(BUFFER_NAME); diff --git a/src/detect-sip-protocol.c b/src/detect-sip-protocol.c index 41fdcac538b3..bf7031fee1da 100644 --- a/src/detect-sip-protocol.c +++ b/src/detect-sip-protocol.c @@ -1,4 +1,4 @@ - /* Copyright (C) 2019 Open Information Security Foundation +/* Copyright (C) 2019 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free @@ -72,8 +72,8 @@ static int DetectSipProtocolSetup(DetectEngineCtx *de_ctx, Signature *s, const c } static InspectionBuffer *GetData(DetectEngineThreadCtx *det_ctx, - const DetectEngineTransforms *transforms, Flow *_f, - const uint8_t flow_flags, void *txv, const int list_id) + const DetectEngineTransforms *transforms, Flow *_f, const uint8_t flow_flags, void *txv, + const int list_id) { InspectionBuffer *buffer = InspectionBufferGet(det_ctx, list_id); if (buffer->inspect == NULL) { @@ -100,17 +100,13 @@ void DetectSipProtocolRegister(void) sigmatch_table[DETECT_AL_SIP_PROTOCOL].Setup = DetectSipProtocolSetup; sigmatch_table[DETECT_AL_SIP_PROTOCOL].flags |= SIGMATCH_NOOPT; - DetectAppLayerMpmRegister2(BUFFER_NAME, SIG_FLAG_TOSERVER, 2, - PrefilterGenericMpmRegister, GetData, ALPROTO_SIP, - 1); - DetectAppLayerMpmRegister2(BUFFER_NAME, SIG_FLAG_TOCLIENT, 2, - PrefilterGenericMpmRegister, GetData, ALPROTO_SIP, - 1); - DetectAppLayerInspectEngineRegister2(BUFFER_NAME, - ALPROTO_SIP, SIG_FLAG_TOSERVER, 1, + DetectAppLayerMpmRegister2(BUFFER_NAME, SIG_FLAG_TOSERVER, 2, PrefilterGenericMpmRegister, + GetData, ALPROTO_SIP, 1); + DetectAppLayerMpmRegister2(BUFFER_NAME, SIG_FLAG_TOCLIENT, 2, PrefilterGenericMpmRegister, + GetData, ALPROTO_SIP, 1); + DetectAppLayerInspectEngineRegister2(BUFFER_NAME, ALPROTO_SIP, SIG_FLAG_TOSERVER, 1, DetectEngineInspectBufferGeneric, GetData); - DetectAppLayerInspectEngineRegister2(BUFFER_NAME, - ALPROTO_SIP, SIG_FLAG_TOCLIENT, 1, + DetectAppLayerInspectEngineRegister2(BUFFER_NAME, ALPROTO_SIP, SIG_FLAG_TOCLIENT, 1, DetectEngineInspectBufferGeneric, GetData); DetectBufferTypeSetDescriptionByName(BUFFER_NAME, BUFFER_DESC); diff --git a/src/detect-sip-request-line.c b/src/detect-sip-request-line.c index 9d9f4c9c5fe5..2e862e68d6ee 100644 --- a/src/detect-sip-request-line.c +++ b/src/detect-sip-request-line.c @@ -71,9 +71,8 @@ static int DetectSipRequestLineSetup(DetectEngineCtx *de_ctx, Signature *s, cons } static InspectionBuffer *GetData(DetectEngineThreadCtx *det_ctx, - const DetectEngineTransforms *transforms, - Flow *_f, const uint8_t _flow_flags, - void *txv, const int list_id) + const DetectEngineTransforms *transforms, Flow *_f, const uint8_t _flow_flags, void *txv, + const int list_id) { InspectionBuffer *buffer = InspectionBufferGet(det_ctx, list_id); if (buffer->inspect == NULL) { @@ -95,18 +94,17 @@ void DetectSipRequestLineRegister(void) { /* sip.request_line sticky buffer */ sigmatch_table[DETECT_AL_SIP_REQUEST_LINE].name = KEYWORD_NAME; - sigmatch_table[DETECT_AL_SIP_REQUEST_LINE].desc = "sticky buffer to match on the SIP request line"; + sigmatch_table[DETECT_AL_SIP_REQUEST_LINE].desc = + "sticky buffer to match on the SIP request line"; sigmatch_table[DETECT_AL_SIP_REQUEST_LINE].url = "/rules/" KEYWORD_DOC; sigmatch_table[DETECT_AL_SIP_REQUEST_LINE].Setup = DetectSipRequestLineSetup; sigmatch_table[DETECT_AL_SIP_REQUEST_LINE].flags |= SIGMATCH_NOOPT; - DetectAppLayerInspectEngineRegister2(BUFFER_NAME, ALPROTO_SIP, - SIG_FLAG_TOSERVER, 0, + DetectAppLayerInspectEngineRegister2(BUFFER_NAME, ALPROTO_SIP, SIG_FLAG_TOSERVER, 0, DetectEngineInspectBufferGeneric, GetData); - DetectAppLayerMpmRegister2(BUFFER_NAME, SIG_FLAG_TOSERVER, 2, - PrefilterGenericMpmRegister, GetData, ALPROTO_SIP, - 1); + DetectAppLayerMpmRegister2(BUFFER_NAME, SIG_FLAG_TOSERVER, 2, PrefilterGenericMpmRegister, + GetData, ALPROTO_SIP, 1); DetectBufferTypeSetDescriptionByName(BUFFER_NAME, BUFFER_DESC); diff --git a/src/detect-sip-response-line.c b/src/detect-sip-response-line.c index 99061f951d5a..013e554eca7a 100644 --- a/src/detect-sip-response-line.c +++ b/src/detect-sip-response-line.c @@ -71,9 +71,8 @@ static int DetectSipResponseLineSetup(DetectEngineCtx *de_ctx, Signature *s, con } static InspectionBuffer *GetData(DetectEngineThreadCtx *det_ctx, - const DetectEngineTransforms *transforms, - Flow *_f, const uint8_t _flow_flags, - void *txv, const int list_id) + const DetectEngineTransforms *transforms, Flow *_f, const uint8_t _flow_flags, void *txv, + const int list_id) { InspectionBuffer *buffer = InspectionBufferGet(det_ctx, list_id); if (buffer->inspect == NULL) { @@ -95,18 +94,17 @@ void DetectSipResponseLineRegister(void) { /* sip.response_line sticky buffer */ sigmatch_table[DETECT_AL_SIP_RESPONSE_LINE].name = KEYWORD_NAME; - sigmatch_table[DETECT_AL_SIP_RESPONSE_LINE].desc = "sticky buffer to match on the SIP response line"; + sigmatch_table[DETECT_AL_SIP_RESPONSE_LINE].desc = + "sticky buffer to match on the SIP response line"; sigmatch_table[DETECT_AL_SIP_RESPONSE_LINE].url = "/rules/" KEYWORD_DOC; sigmatch_table[DETECT_AL_SIP_RESPONSE_LINE].Setup = DetectSipResponseLineSetup; sigmatch_table[DETECT_AL_SIP_RESPONSE_LINE].flags |= SIGMATCH_NOOPT; - DetectAppLayerInspectEngineRegister2(BUFFER_NAME, ALPROTO_SIP, - SIG_FLAG_TOCLIENT, 0, + DetectAppLayerInspectEngineRegister2(BUFFER_NAME, ALPROTO_SIP, SIG_FLAG_TOCLIENT, 0, DetectEngineInspectBufferGeneric, GetData); - DetectAppLayerMpmRegister2(BUFFER_NAME, SIG_FLAG_TOCLIENT, 2, - PrefilterGenericMpmRegister, GetData, ALPROTO_SIP, - 1); + DetectAppLayerMpmRegister2(BUFFER_NAME, SIG_FLAG_TOCLIENT, 2, PrefilterGenericMpmRegister, + GetData, ALPROTO_SIP, 1); DetectBufferTypeSetDescriptionByName(BUFFER_NAME, BUFFER_DESC); diff --git a/src/detect-sip-stat-code.c b/src/detect-sip-stat-code.c index 9b663c971e8e..5e565ab89f31 100644 --- a/src/detect-sip-stat-code.c +++ b/src/detect-sip-stat-code.c @@ -72,8 +72,8 @@ static int DetectSipStatCodeSetup(DetectEngineCtx *de_ctx, Signature *s, const c } static InspectionBuffer *GetData(DetectEngineThreadCtx *det_ctx, - const DetectEngineTransforms *transforms, Flow *_f, - const uint8_t _flow_flags, void *txv, const int list_id) + const DetectEngineTransforms *transforms, Flow *_f, const uint8_t _flow_flags, void *txv, + const int list_id) { SCEnter(); @@ -94,7 +94,7 @@ static InspectionBuffer *GetData(DetectEngineThreadCtx *det_ctx, return buffer; } -void DetectSipStatCodeRegister (void) +void DetectSipStatCodeRegister(void) { /* sip.stat_code sticky buffer */ sigmatch_table[DETECT_AL_SIP_STAT_CODE].name = KEYWORD_NAME; @@ -103,13 +103,11 @@ void DetectSipStatCodeRegister (void) sigmatch_table[DETECT_AL_SIP_STAT_CODE].Setup = DetectSipStatCodeSetup; sigmatch_table[DETECT_AL_SIP_STAT_CODE].flags |= SIGMATCH_NOOPT; - DetectAppLayerInspectEngineRegister2(BUFFER_NAME, ALPROTO_SIP, - SIG_FLAG_TOCLIENT, 1, + DetectAppLayerInspectEngineRegister2(BUFFER_NAME, ALPROTO_SIP, SIG_FLAG_TOCLIENT, 1, DetectEngineInspectBufferGeneric, GetData); - DetectAppLayerMpmRegister2(BUFFER_NAME, SIG_FLAG_TOCLIENT, 4, - PrefilterGenericMpmRegister, GetData, ALPROTO_SIP, - 1); + DetectAppLayerMpmRegister2(BUFFER_NAME, SIG_FLAG_TOCLIENT, 4, PrefilterGenericMpmRegister, + GetData, ALPROTO_SIP, 1); DetectBufferTypeSetDescriptionByName(BUFFER_NAME, BUFFER_DESC); diff --git a/src/detect-sip-stat-msg.c b/src/detect-sip-stat-msg.c index a9b9247a5d70..e8a187e7db13 100644 --- a/src/detect-sip-stat-msg.c +++ b/src/detect-sip-stat-msg.c @@ -72,8 +72,8 @@ static int DetectSipStatMsgSetup(DetectEngineCtx *de_ctx, Signature *s, const ch } static InspectionBuffer *GetData(DetectEngineThreadCtx *det_ctx, - const DetectEngineTransforms *transforms, Flow *_f, - const uint8_t _flow_flags, void *txv, const int list_id) + const DetectEngineTransforms *transforms, Flow *_f, const uint8_t _flow_flags, void *txv, + const int list_id) { SCEnter(); @@ -94,22 +94,21 @@ static InspectionBuffer *GetData(DetectEngineThreadCtx *det_ctx, return buffer; } -void DetectSipStatMsgRegister (void) +void DetectSipStatMsgRegister(void) { /* sip.stat_msg sticky buffer */ sigmatch_table[DETECT_AL_SIP_STAT_MSG].name = KEYWORD_NAME; - sigmatch_table[DETECT_AL_SIP_STAT_MSG].desc = "sticky buffer to match on the SIP status message"; + sigmatch_table[DETECT_AL_SIP_STAT_MSG].desc = + "sticky buffer to match on the SIP status message"; sigmatch_table[DETECT_AL_SIP_STAT_MSG].url = "/rules/" KEYWORD_DOC; sigmatch_table[DETECT_AL_SIP_STAT_MSG].Setup = DetectSipStatMsgSetup; sigmatch_table[DETECT_AL_SIP_STAT_MSG].flags |= SIGMATCH_NOOPT; - DetectAppLayerInspectEngineRegister2(BUFFER_NAME, ALPROTO_SIP, - SIG_FLAG_TOCLIENT, 1, + DetectAppLayerInspectEngineRegister2(BUFFER_NAME, ALPROTO_SIP, SIG_FLAG_TOCLIENT, 1, DetectEngineInspectBufferGeneric, GetData); - DetectAppLayerMpmRegister2(BUFFER_NAME, SIG_FLAG_TOCLIENT, 3, - PrefilterGenericMpmRegister, GetData, ALPROTO_SIP, - 1); + DetectAppLayerMpmRegister2(BUFFER_NAME, SIG_FLAG_TOCLIENT, 3, PrefilterGenericMpmRegister, + GetData, ALPROTO_SIP, 1); DetectBufferTypeSetDescriptionByName(BUFFER_NAME, BUFFER_DESC); diff --git a/src/detect-sip-uri.c b/src/detect-sip-uri.c index 1a000fdb543a..43c6f6f904ca 100644 --- a/src/detect-sip-uri.c +++ b/src/detect-sip-uri.c @@ -65,8 +65,7 @@ static bool DetectSipUriValidateCallback(const Signature *s, const char **sigerr return DetectUrilenValidateContent(s, g_buffer_id, sigerror); } -static void DetectSipUriSetupCallback(const DetectEngineCtx *de_ctx, - Signature *s) +static void DetectSipUriSetupCallback(const DetectEngineCtx *de_ctx, Signature *s) { SCLogDebug("callback invoked by %u", s->id); DetectUrilenApplyToContent(s, g_buffer_id); @@ -84,8 +83,8 @@ static int DetectSipUriSetup(DetectEngineCtx *de_ctx, Signature *s, const char * } static InspectionBuffer *GetData(DetectEngineThreadCtx *det_ctx, - const DetectEngineTransforms *transforms, Flow *_f, - const uint8_t _flow_flags, void *txv, const int list_id) + const DetectEngineTransforms *transforms, Flow *_f, const uint8_t _flow_flags, void *txv, + const int list_id) { InspectionBuffer *buffer = InspectionBufferGet(det_ctx, list_id); if (buffer->inspect == NULL) { @@ -112,21 +111,17 @@ void DetectSipUriRegister(void) sigmatch_table[DETECT_AL_SIP_URI].Setup = DetectSipUriSetup; sigmatch_table[DETECT_AL_SIP_URI].flags |= SIGMATCH_NOOPT; - DetectAppLayerInspectEngineRegister2(BUFFER_NAME, ALPROTO_SIP, - SIG_FLAG_TOSERVER, 0, + DetectAppLayerInspectEngineRegister2(BUFFER_NAME, ALPROTO_SIP, SIG_FLAG_TOSERVER, 0, DetectEngineInspectBufferGeneric, GetData); - DetectAppLayerMpmRegister2(BUFFER_NAME, SIG_FLAG_TOSERVER, 2, - PrefilterGenericMpmRegister, GetData, ALPROTO_SIP, - 1); + DetectAppLayerMpmRegister2(BUFFER_NAME, SIG_FLAG_TOSERVER, 2, PrefilterGenericMpmRegister, + GetData, ALPROTO_SIP, 1); DetectBufferTypeSetDescriptionByName(BUFFER_NAME, BUFFER_DESC); - DetectBufferTypeRegisterSetupCallback(BUFFER_NAME, - DetectSipUriSetupCallback); + DetectBufferTypeRegisterSetupCallback(BUFFER_NAME, DetectSipUriSetupCallback); - DetectBufferTypeRegisterValidateCallback(BUFFER_NAME, - DetectSipUriValidateCallback); + DetectBufferTypeRegisterValidateCallback(BUFFER_NAME, DetectSipUriValidateCallback); g_buffer_id = DetectBufferTypeGetByName(BUFFER_NAME); diff --git a/src/detect-smb-share.c b/src/detect-smb-share.c index 8d4d145fad8c..19333b24f4f0 100644 --- a/src/detect-smb-share.c +++ b/src/detect-smb-share.c @@ -36,10 +36,10 @@ #include "detect-smb-share.h" #include "rust.h" -#define BUFFER_NAME "smb_named_pipe" -#define KEYWORD_NAME "smb.named_pipe" +#define BUFFER_NAME "smb_named_pipe" +#define KEYWORD_NAME "smb.named_pipe" #define KEYWORD_NAME_LEGACY BUFFER_NAME -#define KEYWORD_ID DETECT_SMB_NAMED_PIPE +#define KEYWORD_ID DETECT_SMB_NAMED_PIPE static int g_smb_named_pipe_buffer_id = 0; @@ -55,9 +55,8 @@ static int DetectSmbNamedPipeSetup(DetectEngineCtx *de_ctx, Signature *s, const } static InspectionBuffer *GetNamedPipeData(DetectEngineThreadCtx *det_ctx, - const DetectEngineTransforms *transforms, - Flow *_f, const uint8_t _flow_flags, - void *txv, const int list_id) + const DetectEngineTransforms *transforms, Flow *_f, const uint8_t _flow_flags, void *txv, + const int list_id) { InspectionBuffer *buffer = InspectionBufferGet(det_ctx, list_id); if (buffer->inspect == NULL) { @@ -80,15 +79,13 @@ void DetectSmbNamedPipeRegister(void) sigmatch_table[KEYWORD_ID].name = KEYWORD_NAME; sigmatch_table[KEYWORD_ID].alias = KEYWORD_NAME_LEGACY; sigmatch_table[KEYWORD_ID].Setup = DetectSmbNamedPipeSetup; - sigmatch_table[KEYWORD_ID].flags |= SIGMATCH_NOOPT|SIGMATCH_INFO_STICKY_BUFFER; + sigmatch_table[KEYWORD_ID].flags |= SIGMATCH_NOOPT | SIGMATCH_INFO_STICKY_BUFFER; sigmatch_table[KEYWORD_ID].desc = "sticky buffer to match on SMB named pipe in tree connect"; - DetectAppLayerMpmRegister2(BUFFER_NAME, SIG_FLAG_TOSERVER, 2, - PrefilterGenericMpmRegister, GetNamedPipeData, - ALPROTO_SMB, 1); + DetectAppLayerMpmRegister2(BUFFER_NAME, SIG_FLAG_TOSERVER, 2, PrefilterGenericMpmRegister, + GetNamedPipeData, ALPROTO_SMB, 1); - DetectAppLayerInspectEngineRegister2(BUFFER_NAME, - ALPROTO_SMB, SIG_FLAG_TOSERVER, 0, + DetectAppLayerInspectEngineRegister2(BUFFER_NAME, ALPROTO_SMB, SIG_FLAG_TOSERVER, 0, DetectEngineInspectBufferGeneric, GetNamedPipeData); g_smb_named_pipe_buffer_id = DetectBufferTypeGetByName(BUFFER_NAME); @@ -99,10 +96,10 @@ void DetectSmbNamedPipeRegister(void) #undef KEYWORD_NAME_LEGACY #undef KEYWORD_ID -#define BUFFER_NAME "smb_share" -#define KEYWORD_NAME "smb.share" +#define BUFFER_NAME "smb_share" +#define KEYWORD_NAME "smb.share" #define KEYWORD_NAME_LEGACY BUFFER_NAME -#define KEYWORD_ID DETECT_SMB_SHARE +#define KEYWORD_ID DETECT_SMB_SHARE static int g_smb_share_buffer_id = 0; @@ -118,9 +115,8 @@ static int DetectSmbShareSetup(DetectEngineCtx *de_ctx, Signature *s, const char } static InspectionBuffer *GetShareData(DetectEngineThreadCtx *det_ctx, - const DetectEngineTransforms *transforms, - Flow *_f, const uint8_t _flow_flags, - void *txv, const int list_id) + const DetectEngineTransforms *transforms, Flow *_f, const uint8_t _flow_flags, void *txv, + const int list_id) { InspectionBuffer *buffer = InspectionBufferGet(det_ctx, list_id); if (buffer->inspect == NULL) { @@ -143,15 +139,13 @@ void DetectSmbShareRegister(void) sigmatch_table[KEYWORD_ID].name = KEYWORD_NAME; sigmatch_table[KEYWORD_ID].alias = KEYWORD_NAME_LEGACY; sigmatch_table[KEYWORD_ID].Setup = DetectSmbShareSetup; - sigmatch_table[KEYWORD_ID].flags |= SIGMATCH_NOOPT|SIGMATCH_INFO_STICKY_BUFFER; + sigmatch_table[KEYWORD_ID].flags |= SIGMATCH_NOOPT | SIGMATCH_INFO_STICKY_BUFFER; sigmatch_table[KEYWORD_ID].desc = "sticky buffer to match on SMB share name in tree connect"; - DetectAppLayerMpmRegister2(BUFFER_NAME, SIG_FLAG_TOSERVER, 2, - PrefilterGenericMpmRegister, GetShareData, - ALPROTO_SMB, 1); + DetectAppLayerMpmRegister2(BUFFER_NAME, SIG_FLAG_TOSERVER, 2, PrefilterGenericMpmRegister, + GetShareData, ALPROTO_SMB, 1); - DetectAppLayerInspectEngineRegister2(BUFFER_NAME, - ALPROTO_SMB, SIG_FLAG_TOSERVER, 0, + DetectAppLayerInspectEngineRegister2(BUFFER_NAME, ALPROTO_SMB, SIG_FLAG_TOSERVER, 0, DetectEngineInspectBufferGeneric, GetShareData); g_smb_share_buffer_id = DetectBufferTypeGetByName(BUFFER_NAME); diff --git a/src/detect-snmp-community.c b/src/detect-snmp-community.c index 93e7d21671ab..273dbedd57d2 100644 --- a/src/detect-snmp-community.c +++ b/src/detect-snmp-community.c @@ -36,12 +36,10 @@ #include "app-layer-parser.h" #include "rust.h" -static int DetectSNMPCommunitySetup(DetectEngineCtx *, Signature *, - const char *); +static int DetectSNMPCommunitySetup(DetectEngineCtx *, Signature *, const char *); static InspectionBuffer *GetData(DetectEngineThreadCtx *det_ctx, - const DetectEngineTransforms *transforms, - Flow *f, const uint8_t flow_flags, - void *txv, const int list_id); + const DetectEngineTransforms *transforms, Flow *f, const uint8_t flow_flags, void *txv, + const int list_id); #ifdef UNITTESTS static void DetectSNMPCommunityRegisterTests(void); #endif @@ -51,35 +49,31 @@ void DetectSNMPCommunityRegister(void) { sigmatch_table[DETECT_AL_SNMP_COMMUNITY].name = "snmp.community"; sigmatch_table[DETECT_AL_SNMP_COMMUNITY].desc = - "SNMP content modifier to match on the SNMP community"; - sigmatch_table[DETECT_AL_SNMP_COMMUNITY].Setup = - DetectSNMPCommunitySetup; + "SNMP content modifier to match on the SNMP community"; + sigmatch_table[DETECT_AL_SNMP_COMMUNITY].Setup = DetectSNMPCommunitySetup; #ifdef UNITTESTS sigmatch_table[DETECT_AL_SNMP_COMMUNITY].RegisterTests = DetectSNMPCommunityRegisterTests; #endif sigmatch_table[DETECT_AL_SNMP_COMMUNITY].url = "/rules/snmp-keywords.html#snmp-community"; - sigmatch_table[DETECT_AL_SNMP_COMMUNITY].flags |= SIGMATCH_NOOPT|SIGMATCH_INFO_STICKY_BUFFER; + sigmatch_table[DETECT_AL_SNMP_COMMUNITY].flags |= SIGMATCH_NOOPT | SIGMATCH_INFO_STICKY_BUFFER; /* register inspect engines */ - DetectAppLayerInspectEngineRegister2("snmp.community", - ALPROTO_SNMP, SIG_FLAG_TOSERVER, 0, + DetectAppLayerInspectEngineRegister2("snmp.community", ALPROTO_SNMP, SIG_FLAG_TOSERVER, 0, DetectEngineInspectBufferGeneric, GetData); - DetectAppLayerMpmRegister2("snmp.community", SIG_FLAG_TOSERVER, 2, - PrefilterGenericMpmRegister, GetData, ALPROTO_SNMP, 0); - DetectAppLayerInspectEngineRegister2("snmp.community", - ALPROTO_SNMP, SIG_FLAG_TOCLIENT, 0, + DetectAppLayerMpmRegister2("snmp.community", SIG_FLAG_TOSERVER, 2, PrefilterGenericMpmRegister, + GetData, ALPROTO_SNMP, 0); + DetectAppLayerInspectEngineRegister2("snmp.community", ALPROTO_SNMP, SIG_FLAG_TOCLIENT, 0, DetectEngineInspectBufferGeneric, GetData); - DetectAppLayerMpmRegister2("snmp.community", SIG_FLAG_TOCLIENT, 2, - PrefilterGenericMpmRegister, GetData, ALPROTO_SNMP, 0); + DetectAppLayerMpmRegister2("snmp.community", SIG_FLAG_TOCLIENT, 2, PrefilterGenericMpmRegister, + GetData, ALPROTO_SNMP, 0); DetectBufferTypeSetDescriptionByName("snmp.community", "SNMP Community identifier"); g_snmp_rust_id = DetectBufferTypeGetByName("snmp.community"); } -static int DetectSNMPCommunitySetup(DetectEngineCtx *de_ctx, Signature *s, - const char *str) +static int DetectSNMPCommunitySetup(DetectEngineCtx *de_ctx, Signature *s, const char *str) { if (DetectBufferSetActiveList(de_ctx, s, g_snmp_rust_id) < 0) return -1; @@ -91,8 +85,8 @@ static int DetectSNMPCommunitySetup(DetectEngineCtx *de_ctx, Signature *s, } static InspectionBuffer *GetData(DetectEngineThreadCtx *det_ctx, - const DetectEngineTransforms *transforms, Flow *f, - const uint8_t flow_flags, void *txv, const int list_id) + const DetectEngineTransforms *transforms, Flow *f, const uint8_t flow_flags, void *txv, + const int list_id) { InspectionBuffer *buffer = InspectionBufferGet(det_ctx, list_id); if (buffer->inspect == NULL) { diff --git a/src/detect-snmp-community.h b/src/detect-snmp-community.h index 11de2abbf99a..16243ccc7e57 100644 --- a/src/detect-snmp-community.h +++ b/src/detect-snmp-community.h @@ -24,7 +24,6 @@ #ifndef __DETECT_SNMP_COMMUNITY_H__ #define __DETECT_SNMP_COMMUNITY_H__ - void DetectSNMPCommunityRegister(void); #endif /* __DETECT_SNMP_COMMUNITY_H__ */ diff --git a/src/detect-snmp-pdu_type.c b/src/detect-snmp-pdu_type.c index 243d6c323be8..3bb85bddaba9 100644 --- a/src/detect-snmp-pdu_type.c +++ b/src/detect-snmp-pdu_type.c @@ -41,17 +41,16 @@ typedef struct DetectSNMPPduTypeData_ { uint32_t pdu_type; } DetectSNMPPduTypeData; -static DetectSNMPPduTypeData *DetectSNMPPduTypeParse (const char *); -static int DetectSNMPPduTypeSetup (DetectEngineCtx *, Signature *s, const char *str); +static DetectSNMPPduTypeData *DetectSNMPPduTypeParse(const char *); +static int DetectSNMPPduTypeSetup(DetectEngineCtx *, Signature *s, const char *str); static void DetectSNMPPduTypeFree(DetectEngineCtx *, void *); #ifdef UNITTESTS static void DetectSNMPPduTypeRegisterTests(void); #endif static int g_snmp_pdu_type_buffer_id = 0; -static int DetectSNMPPduTypeMatch (DetectEngineThreadCtx *, Flow *, - uint8_t, void *, void *, const Signature *, - const SigMatchCtx *); +static int DetectSNMPPduTypeMatch(DetectEngineThreadCtx *, Flow *, uint8_t, void *, void *, + const Signature *, const SigMatchCtx *); void DetectSNMPPduTypeRegister(void) { @@ -93,18 +92,15 @@ void DetectSNMPPduTypeRegister(void) * \retval 0 no match. * \retval 1 match. */ -static int DetectSNMPPduTypeMatch (DetectEngineThreadCtx *det_ctx, - Flow *f, uint8_t flags, void *state, - void *txv, const Signature *s, - const SigMatchCtx *ctx) +static int DetectSNMPPduTypeMatch(DetectEngineThreadCtx *det_ctx, Flow *f, uint8_t flags, + void *state, void *txv, const Signature *s, const SigMatchCtx *ctx) { SCEnter(); const DetectSNMPPduTypeData *dd = (const DetectSNMPPduTypeData *)ctx; uint32_t pdu_type; rs_snmp_tx_get_pdu_type(txv, &pdu_type); - SCLogDebug("pdu_type %u ref_pdu_type %d", - pdu_type, dd->pdu_type); + SCLogDebug("pdu_type %u ref_pdu_type %d", pdu_type, dd->pdu_type); if (pdu_type == dd->pdu_type) SCReturnInt(1); SCReturnInt(0); @@ -119,7 +115,7 @@ static int DetectSNMPPduTypeMatch (DetectEngineThreadCtx *det_ctx, * \retval dd pointer to DetectSNMPPduTypeData on success. * \retval NULL on failure. */ -static DetectSNMPPduTypeData *DetectSNMPPduTypeParse (const char *rawstr) +static DetectSNMPPduTypeData *DetectSNMPPduTypeParse(const char *rawstr) { DetectSNMPPduTypeData *dd = NULL; int res = 0; @@ -176,8 +172,7 @@ static DetectSNMPPduTypeData *DetectSNMPPduTypeParse (const char *rawstr) * \retval 0 on Success. * \retval -1 on Failure. */ -static int DetectSNMPPduTypeSetup (DetectEngineCtx *de_ctx, Signature *s, - const char *rawstr) +static int DetectSNMPPduTypeSetup(DetectEngineCtx *de_ctx, Signature *s, const char *rawstr) { DetectSNMPPduTypeData *dd = NULL; diff --git a/src/detect-snmp-pdu_type.h b/src/detect-snmp-pdu_type.h index 5197885a588b..a97992cfeeec 100644 --- a/src/detect-snmp-pdu_type.h +++ b/src/detect-snmp-pdu_type.h @@ -24,7 +24,6 @@ #ifndef __DETECT_SNMP_PDU_TYPE_H__ #define __DETECT_SNMP_PDU_TYPE_H__ - void DetectSNMPPduTypeRegister(void); #endif /* __DETECT_SNMP_PDU_TYPE_H__ */ diff --git a/src/detect-snmp-version.c b/src/detect-snmp-version.c index 64029659381e..1c3337d33a7a 100644 --- a/src/detect-snmp-version.c +++ b/src/detect-snmp-version.c @@ -32,22 +32,20 @@ #include "app-layer-parser.h" #include "rust.h" - -static int DetectSNMPVersionSetup (DetectEngineCtx *, Signature *s, const char *str); +static int DetectSNMPVersionSetup(DetectEngineCtx *, Signature *s, const char *str); static void DetectSNMPVersionFree(DetectEngineCtx *, void *); #ifdef UNITTESTS static void DetectSNMPVersionRegisterTests(void); #endif static int g_snmp_version_buffer_id = 0; -static int DetectSNMPVersionMatch (DetectEngineThreadCtx *, Flow *, - uint8_t, void *, void *, const Signature *, - const SigMatchCtx *); +static int DetectSNMPVersionMatch(DetectEngineThreadCtx *, Flow *, uint8_t, void *, void *, + const Signature *, const SigMatchCtx *); /** * \brief Registration function for snmp.procedure keyword. */ -void DetectSNMPVersionRegister (void) +void DetectSNMPVersionRegister(void) { sigmatch_table[DETECT_AL_SNMP_VERSION].name = "snmp.version"; sigmatch_table[DETECT_AL_SNMP_VERSION].desc = "match SNMP version"; @@ -85,10 +83,8 @@ void DetectSNMPVersionRegister (void) * \retval 0 no match. * \retval 1 match. */ -static int DetectSNMPVersionMatch (DetectEngineThreadCtx *det_ctx, - Flow *f, uint8_t flags, void *state, - void *txv, const Signature *s, - const SigMatchCtx *ctx) +static int DetectSNMPVersionMatch(DetectEngineThreadCtx *det_ctx, Flow *f, uint8_t flags, + void *state, void *txv, const Signature *s, const SigMatchCtx *ctx) { SCEnter(); @@ -115,8 +111,6 @@ static DetectU32Data *DetectSNMPVersionParse(const char *rawstr) return DetectU32Parse(rawstr); } - - /** * \brief Function to add the parsed snmp version field into the current signature. * @@ -128,8 +122,7 @@ static DetectU32Data *DetectSNMPVersionParse(const char *rawstr) * \retval 0 on Success. * \retval -1 on Failure. */ -static int DetectSNMPVersionSetup (DetectEngineCtx *de_ctx, Signature *s, - const char *rawstr) +static int DetectSNMPVersionSetup(DetectEngineCtx *de_ctx, Signature *s, const char *rawstr) { DetectU32Data *dd = NULL; @@ -168,7 +161,6 @@ static void DetectSNMPVersionFree(DetectEngineCtx *de_ctx, void *ptr) rs_detect_u32_free(ptr); } - #ifdef UNITTESTS #include "tests/detect-snmp-version.c" #endif /* UNITTESTS */ diff --git a/src/detect-snmp-version.h b/src/detect-snmp-version.h index 3c8d5915d82e..45fde57e494b 100644 --- a/src/detect-snmp-version.h +++ b/src/detect-snmp-version.h @@ -24,7 +24,6 @@ #ifndef __DETECT_SNMP_VERSION_H__ #define __DETECT_SNMP_VERSION_H__ - void DetectSNMPVersionRegister(void); #endif /* __DETECT_SNMP_VERSION_H__ */ diff --git a/src/detect-ssh-hassh-server-string.c b/src/detect-ssh-hassh-server-string.c index 27b0e0cb7595..72d85b589302 100644 --- a/src/detect-ssh-hassh-server-string.c +++ b/src/detect-ssh-hassh-server-string.c @@ -47,20 +47,18 @@ #include "detect-ssh-hassh-server-string.h" #include "rust.h" - -#define KEYWORD_NAME "ssh.hassh.server.string" +#define KEYWORD_NAME "ssh.hassh.server.string" #define KEYWORD_ALIAS "ssh-hassh-server-string" -#define KEYWORD_DOC "ssh-keywords.html#ssh.hassh.server.string" -#define BUFFER_NAME "ssh.hassh.server.string" -#define BUFFER_DESC "Ssh Client Key Exchange methods For ssh Servers" +#define KEYWORD_DOC "ssh-keywords.html#ssh.hassh.server.string" +#define BUFFER_NAME "ssh.hassh.server.string" +#define BUFFER_DESC "Ssh Client Key Exchange methods For ssh Servers" static int g_ssh_hassh_server_string_buffer_id = 0; - static InspectionBuffer *GetSshData(DetectEngineThreadCtx *det_ctx, - const DetectEngineTransforms *transforms, Flow *_f, - const uint8_t flow_flags, void *txv, const int list_id) + const DetectEngineTransforms *transforms, Flow *_f, const uint8_t flow_flags, void *txv, + const int list_id) { - + SCEnter(); InspectionBuffer *buffer = InspectionBufferGet(det_ctx, list_id); @@ -101,7 +99,7 @@ static int DetectSshHasshServerStringSetup(DetectEngineCtx *de_ctx, Signature *s if (DetectSignatureSetAppProto(s, ALPROTO_SSH) < 0) return -1; - + /* try to enable Hassh */ rs_ssh_enable_hassh(); @@ -114,28 +112,25 @@ static int DetectSshHasshServerStringSetup(DetectEngineCtx *de_ctx, Signature *s } return 0; - } /** * \brief Registration function for hasshServer.string keyword. */ -void DetectSshHasshServerStringRegister(void) +void DetectSshHasshServerStringRegister(void) { sigmatch_table[DETECT_AL_SSH_HASSH_SERVER_STRING].name = KEYWORD_NAME; sigmatch_table[DETECT_AL_SSH_HASSH_SERVER_STRING].alias = KEYWORD_ALIAS; sigmatch_table[DETECT_AL_SSH_HASSH_SERVER_STRING].desc = BUFFER_NAME " sticky buffer"; sigmatch_table[DETECT_AL_SSH_HASSH_SERVER_STRING].url = "/rules/" KEYWORD_DOC; sigmatch_table[DETECT_AL_SSH_HASSH_SERVER_STRING].Setup = DetectSshHasshServerStringSetup; - sigmatch_table[DETECT_AL_SSH_HASSH_SERVER_STRING].flags |= SIGMATCH_INFO_STICKY_BUFFER | SIGMATCH_NOOPT; - + sigmatch_table[DETECT_AL_SSH_HASSH_SERVER_STRING].flags |= + SIGMATCH_INFO_STICKY_BUFFER | SIGMATCH_NOOPT; - DetectAppLayerMpmRegister2(BUFFER_NAME, SIG_FLAG_TOCLIENT, 2, - PrefilterGenericMpmRegister, GetSshData, - ALPROTO_SSH, SshStateBannerDone); - DetectAppLayerInspectEngineRegister2(BUFFER_NAME, ALPROTO_SSH, - SIG_FLAG_TOCLIENT, SshStateBannerDone, - DetectEngineInspectBufferGeneric, GetSshData); + DetectAppLayerMpmRegister2(BUFFER_NAME, SIG_FLAG_TOCLIENT, 2, PrefilterGenericMpmRegister, + GetSshData, ALPROTO_SSH, SshStateBannerDone); + DetectAppLayerInspectEngineRegister2(BUFFER_NAME, ALPROTO_SSH, SIG_FLAG_TOCLIENT, + SshStateBannerDone, DetectEngineInspectBufferGeneric, GetSshData); DetectBufferTypeSetDescriptionByName(BUFFER_NAME, BUFFER_DESC); diff --git a/src/detect-ssh-hassh-server-string.h b/src/detect-ssh-hassh-server-string.h index 4c2adbb097de..f79cd33d6af5 100644 --- a/src/detect-ssh-hassh-server-string.h +++ b/src/detect-ssh-hassh-server-string.h @@ -25,6 +25,6 @@ #define __DETECT_SSH_HASSH_SERVER_STRING_H__ /* prototypes */ -void DetectSshHasshServerStringRegister (void); +void DetectSshHasshServerStringRegister(void); #endif /* __DETECT_SSH_HASSH_SERVER_STRING_H__ */ diff --git a/src/detect-ssh-hassh-server.c b/src/detect-ssh-hassh-server.c index 295284108f10..e65a8736c2f8 100644 --- a/src/detect-ssh-hassh-server.c +++ b/src/detect-ssh-hassh-server.c @@ -48,20 +48,18 @@ #include "detect-ssh-hassh-server.h" #include "rust.h" - -#define KEYWORD_NAME "ssh.hassh.server" +#define KEYWORD_NAME "ssh.hassh.server" #define KEYWORD_ALIAS "ssh-hassh-server" -#define KEYWORD_DOC "ssh-keywords.html#ssh.hassh.server" -#define BUFFER_NAME "ssh.hassh.server" -#define BUFFER_DESC "Ssh Client Fingerprinting For Ssh Servers" +#define KEYWORD_DOC "ssh-keywords.html#ssh.hassh.server" +#define BUFFER_NAME "ssh.hassh.server" +#define BUFFER_DESC "Ssh Client Fingerprinting For Ssh Servers" static int g_ssh_hassh_buffer_id = 0; - static InspectionBuffer *GetSshData(DetectEngineThreadCtx *det_ctx, - const DetectEngineTransforms *transforms, Flow *_f, - const uint8_t flow_flags, void *txv, const int list_id) + const DetectEngineTransforms *transforms, Flow *_f, const uint8_t flow_flags, void *txv, + const int list_id) { - + SCEnter(); InspectionBuffer *buffer = InspectionBufferGet(det_ctx, list_id); @@ -102,7 +100,7 @@ static int DetectSshHasshServerSetup(DetectEngineCtx *de_ctx, Signature *s, cons if (DetectSignatureSetAppProto(s, ALPROTO_SSH) < 0) return -1; - + /* try to enable Hassh */ rs_ssh_enable_hassh(); @@ -115,7 +113,6 @@ static int DetectSshHasshServerSetup(DetectEngineCtx *de_ctx, Signature *s, cons } return 0; - } static bool DetectSshHasshServerHashValidateCallback(const Signature *s, const char **sigerror) @@ -158,8 +155,7 @@ static bool DetectSshHasshServerHashValidateCallback(const Signature *s, const c return true; } -static void DetectSshHasshServerHashSetupCallback(const DetectEngineCtx *de_ctx, - Signature *s) +static void DetectSshHasshServerHashSetupCallback(const DetectEngineCtx *de_ctx, Signature *s) { for (uint32_t x = 0; x < s->init_data->buffer_index; x++) { if (s->init_data->buffers[x].id != (uint32_t)g_ssh_hassh_buffer_id) @@ -188,21 +184,20 @@ static void DetectSshHasshServerHashSetupCallback(const DetectEngineCtx *de_ctx, /** * \brief Registration function for hasshServer keyword. */ -void DetectSshHasshServerRegister(void) +void DetectSshHasshServerRegister(void) { sigmatch_table[DETECT_AL_SSH_HASSH_SERVER].name = KEYWORD_NAME; sigmatch_table[DETECT_AL_SSH_HASSH_SERVER].alias = KEYWORD_ALIAS; sigmatch_table[DETECT_AL_SSH_HASSH_SERVER].desc = BUFFER_NAME " sticky buffer"; sigmatch_table[DETECT_AL_SSH_HASSH_SERVER].url = "/rules/" KEYWORD_DOC; sigmatch_table[DETECT_AL_SSH_HASSH_SERVER].Setup = DetectSshHasshServerSetup; - sigmatch_table[DETECT_AL_SSH_HASSH_SERVER].flags |= SIGMATCH_INFO_STICKY_BUFFER | SIGMATCH_NOOPT; - - DetectAppLayerMpmRegister2(BUFFER_NAME, SIG_FLAG_TOCLIENT, 2, - PrefilterGenericMpmRegister, GetSshData, - ALPROTO_SSH, SshStateBannerDone); - DetectAppLayerInspectEngineRegister2(BUFFER_NAME, ALPROTO_SSH, - SIG_FLAG_TOCLIENT, SshStateBannerDone, - DetectEngineInspectBufferGeneric, GetSshData); + sigmatch_table[DETECT_AL_SSH_HASSH_SERVER].flags |= + SIGMATCH_INFO_STICKY_BUFFER | SIGMATCH_NOOPT; + + DetectAppLayerMpmRegister2(BUFFER_NAME, SIG_FLAG_TOCLIENT, 2, PrefilterGenericMpmRegister, + GetSshData, ALPROTO_SSH, SshStateBannerDone); + DetectAppLayerInspectEngineRegister2(BUFFER_NAME, ALPROTO_SSH, SIG_FLAG_TOCLIENT, + SshStateBannerDone, DetectEngineInspectBufferGeneric, GetSshData); DetectBufferTypeSetDescriptionByName(BUFFER_NAME, BUFFER_DESC); g_ssh_hassh_buffer_id = DetectBufferTypeGetByName(BUFFER_NAME); diff --git a/src/detect-ssh-hassh-server.h b/src/detect-ssh-hassh-server.h index 6be1055ae159..040601749da4 100644 --- a/src/detect-ssh-hassh-server.h +++ b/src/detect-ssh-hassh-server.h @@ -22,10 +22,9 @@ */ #ifndef __DETECT_SSH_HASSH_SERVER_H__ -#define __DETECT_SSH_HASSH_SERVER_H__ +#define __DETECT_SSH_HASSH_SERVER_H__ /* prototypes */ -void DetectSshHasshServerRegister (void); +void DetectSshHasshServerRegister(void); #endif /* __DETECT_SSH_HASSH_SERVER_H__ */ - diff --git a/src/detect-ssh-hassh-string.c b/src/detect-ssh-hassh-string.c index e639e64b134f..e6d7294f92bb 100644 --- a/src/detect-ssh-hassh-string.c +++ b/src/detect-ssh-hassh-string.c @@ -47,20 +47,18 @@ #include "detect-ssh-hassh-string.h" #include "rust.h" - -#define KEYWORD_NAME "ssh.hassh.string" +#define KEYWORD_NAME "ssh.hassh.string" #define KEYWORD_ALIAS "ssh-hassh-string" -#define KEYWORD_DOC "ssh-keywords.html#hassh.string" -#define BUFFER_NAME "ssh.hassh.string" -#define BUFFER_DESC "Ssh Client Key Exchange methods For ssh Clients " +#define KEYWORD_DOC "ssh-keywords.html#hassh.string" +#define BUFFER_NAME "ssh.hassh.string" +#define BUFFER_DESC "Ssh Client Key Exchange methods For ssh Clients " static int g_ssh_hassh_string_buffer_id = 0; - static InspectionBuffer *GetSshData(DetectEngineThreadCtx *det_ctx, - const DetectEngineTransforms *transforms, Flow *_f, - const uint8_t flow_flags, void *txv, const int list_id) + const DetectEngineTransforms *transforms, Flow *_f, const uint8_t flow_flags, void *txv, + const int list_id) { - + SCEnter(); InspectionBuffer *buffer = InspectionBufferGet(det_ctx, list_id); @@ -101,7 +99,7 @@ static int DetectSshHasshStringSetup(DetectEngineCtx *de_ctx, Signature *s, cons if (DetectSignatureSetAppProto(s, ALPROTO_SSH) < 0) return -1; - + /* try to enable Hassh */ rs_ssh_enable_hassh(); @@ -114,28 +112,25 @@ static int DetectSshHasshStringSetup(DetectEngineCtx *de_ctx, Signature *s, cons } return 0; - } /** * \brief Registration function for hassh.string keyword. */ -void DetectSshHasshStringRegister(void) +void DetectSshHasshStringRegister(void) { sigmatch_table[DETECT_AL_SSH_HASSH_STRING].name = KEYWORD_NAME; sigmatch_table[DETECT_AL_SSH_HASSH_STRING].alias = KEYWORD_ALIAS; sigmatch_table[DETECT_AL_SSH_HASSH_STRING].desc = BUFFER_NAME " sticky buffer"; sigmatch_table[DETECT_AL_SSH_HASSH_STRING].url = "/rules/" KEYWORD_DOC; sigmatch_table[DETECT_AL_SSH_HASSH_STRING].Setup = DetectSshHasshStringSetup; - sigmatch_table[DETECT_AL_SSH_HASSH_STRING].flags |= SIGMATCH_INFO_STICKY_BUFFER | SIGMATCH_NOOPT; - + sigmatch_table[DETECT_AL_SSH_HASSH_STRING].flags |= + SIGMATCH_INFO_STICKY_BUFFER | SIGMATCH_NOOPT; - DetectAppLayerMpmRegister2(BUFFER_NAME, SIG_FLAG_TOSERVER, 2, - PrefilterGenericMpmRegister, GetSshData, - ALPROTO_SSH, SshStateBannerDone); - DetectAppLayerInspectEngineRegister2(BUFFER_NAME, ALPROTO_SSH, - SIG_FLAG_TOSERVER, SshStateBannerDone, - DetectEngineInspectBufferGeneric, GetSshData); + DetectAppLayerMpmRegister2(BUFFER_NAME, SIG_FLAG_TOSERVER, 2, PrefilterGenericMpmRegister, + GetSshData, ALPROTO_SSH, SshStateBannerDone); + DetectAppLayerInspectEngineRegister2(BUFFER_NAME, ALPROTO_SSH, SIG_FLAG_TOSERVER, + SshStateBannerDone, DetectEngineInspectBufferGeneric, GetSshData); DetectBufferTypeSetDescriptionByName(BUFFER_NAME, BUFFER_DESC); diff --git a/src/detect-ssh-hassh-string.h b/src/detect-ssh-hassh-string.h index b3cebcd709c7..d76533b3725e 100644 --- a/src/detect-ssh-hassh-string.h +++ b/src/detect-ssh-hassh-string.h @@ -25,6 +25,6 @@ #define __DETECT_SSH_HASSH_STRING_H__ /* prototypes */ -void DetectSshHasshStringRegister (void); +void DetectSshHasshStringRegister(void); #endif /* __DETECT_SSH_HASSH_STRING_H__ */ diff --git a/src/detect-ssh-hassh.c b/src/detect-ssh-hassh.c index b410a5ffee84..1d50be750ef0 100644 --- a/src/detect-ssh-hassh.c +++ b/src/detect-ssh-hassh.c @@ -48,20 +48,18 @@ #include "detect-ssh-hassh.h" #include "rust.h" - -#define KEYWORD_NAME "ssh.hassh" +#define KEYWORD_NAME "ssh.hassh" #define KEYWORD_ALIAS "ssh-hassh" -#define KEYWORD_DOC "ssh-keywords.html#hassh" -#define BUFFER_NAME "ssh.hassh" -#define BUFFER_DESC "Ssh Client Fingerprinting For Ssh Clients " +#define KEYWORD_DOC "ssh-keywords.html#hassh" +#define BUFFER_NAME "ssh.hassh" +#define BUFFER_DESC "Ssh Client Fingerprinting For Ssh Clients " static int g_ssh_hassh_buffer_id = 0; - static InspectionBuffer *GetSshData(DetectEngineThreadCtx *det_ctx, - const DetectEngineTransforms *transforms, Flow *_f, - const uint8_t flow_flags, void *txv, const int list_id) + const DetectEngineTransforms *transforms, Flow *_f, const uint8_t flow_flags, void *txv, + const int list_id) { - + SCEnter(); InspectionBuffer *buffer = InspectionBufferGet(det_ctx, list_id); @@ -102,7 +100,7 @@ static int DetectSshHasshSetup(DetectEngineCtx *de_ctx, Signature *s, const char if (DetectSignatureSetAppProto(s, ALPROTO_SSH) < 0) return -1; - + /* try to enable Hassh */ rs_ssh_enable_hassh(); @@ -115,12 +113,9 @@ static int DetectSshHasshSetup(DetectEngineCtx *de_ctx, Signature *s, const char } return 0; - } - -static bool DetectSshHasshHashValidateCallback(const Signature *s, - const char **sigerror) +static bool DetectSshHasshHashValidateCallback(const Signature *s, const char **sigerror) { for (uint32_t x = 0; x < s->init_data->buffer_index; x++) { if (s->init_data->buffers[x].id != (uint32_t)g_ssh_hassh_buffer_id) @@ -160,8 +155,7 @@ static bool DetectSshHasshHashValidateCallback(const Signature *s, return true; } -static void DetectSshHasshHashSetupCallback(const DetectEngineCtx *de_ctx, - Signature *s) +static void DetectSshHasshHashSetupCallback(const DetectEngineCtx *de_ctx, Signature *s) { for (uint32_t x = 0; x < s->init_data->buffer_index; x++) { if (s->init_data->buffers[x].id != (uint32_t)g_ssh_hassh_buffer_id) @@ -190,7 +184,7 @@ static void DetectSshHasshHashSetupCallback(const DetectEngineCtx *de_ctx, /** * \brief Registration function for hassh keyword. */ -void DetectSshHasshRegister(void) +void DetectSshHasshRegister(void) { sigmatch_table[DETECT_AL_SSH_HASSH].name = KEYWORD_NAME; sigmatch_table[DETECT_AL_SSH_HASSH].alias = KEYWORD_ALIAS; @@ -199,13 +193,10 @@ void DetectSshHasshRegister(void) sigmatch_table[DETECT_AL_SSH_HASSH].Setup = DetectSshHasshSetup; sigmatch_table[DETECT_AL_SSH_HASSH].flags |= SIGMATCH_INFO_STICKY_BUFFER | SIGMATCH_NOOPT; - - DetectAppLayerMpmRegister2(BUFFER_NAME, SIG_FLAG_TOSERVER, 2, - PrefilterGenericMpmRegister, GetSshData, - ALPROTO_SSH, SshStateBannerDone), - DetectAppLayerInspectEngineRegister2(BUFFER_NAME, ALPROTO_SSH, - SIG_FLAG_TOSERVER, SshStateBannerDone, - DetectEngineInspectBufferGeneric, GetSshData); + DetectAppLayerMpmRegister2(BUFFER_NAME, SIG_FLAG_TOSERVER, 2, PrefilterGenericMpmRegister, + GetSshData, ALPROTO_SSH, SshStateBannerDone), + DetectAppLayerInspectEngineRegister2(BUFFER_NAME, ALPROTO_SSH, SIG_FLAG_TOSERVER, + SshStateBannerDone, DetectEngineInspectBufferGeneric, GetSshData); DetectBufferTypeSetDescriptionByName(BUFFER_NAME, BUFFER_DESC); g_ssh_hassh_buffer_id = DetectBufferTypeGetByName(BUFFER_NAME); @@ -213,4 +204,3 @@ void DetectSshHasshRegister(void) DetectBufferTypeRegisterSetupCallback(BUFFER_NAME, DetectSshHasshHashSetupCallback); DetectBufferTypeRegisterValidateCallback(BUFFER_NAME, DetectSshHasshHashValidateCallback); } - diff --git a/src/detect-ssh-hassh.h b/src/detect-ssh-hassh.h index 07eb091258c0..a97dd55a41b2 100644 --- a/src/detect-ssh-hassh.h +++ b/src/detect-ssh-hassh.h @@ -25,6 +25,6 @@ #define __DETECT_SSH_HASSH_H__ /* prototypes */ -void DetectSshHasshRegister (void); +void DetectSshHasshRegister(void); #endif /* __DETECT_SSH_HASSH_H__ */ diff --git a/src/detect-ssh-proto-version.c b/src/detect-ssh-proto-version.c index 6a852f89ef13..a7d151aa42c1 100644 --- a/src/detect-ssh-proto-version.c +++ b/src/detect-ssh-proto-version.c @@ -58,14 +58,13 @@ /** * \brief Regex for parsing the protoversion string */ -#define PARSE_REGEX "^\\s*\"?\\s*([0-9]+([\\.\\-0-9]+)?|2_compat)\\s*\"?\\s*$" +#define PARSE_REGEX "^\\s*\"?\\s*([0-9]+([\\.\\-0-9]+)?|2_compat)\\s*\"?\\s*$" static DetectParseRegex parse_regex; -static int DetectSshVersionMatch (DetectEngineThreadCtx *, - Flow *, uint8_t, void *, void *, +static int DetectSshVersionMatch(DetectEngineThreadCtx *, Flow *, uint8_t, void *, void *, const Signature *, const SigMatchCtx *); -static int DetectSshVersionSetup (DetectEngineCtx *, Signature *, const char *); +static int DetectSshVersionSetup(DetectEngineCtx *, Signature *, const char *); #ifdef UNITTESTS static void DetectSshVersionRegisterTests(void); #endif @@ -82,11 +81,12 @@ void DetectSshVersionRegister(void) sigmatch_table[DETECT_AL_SSH_PROTOVERSION].url = "/rules/ssh-keywords.html#ssh-protoversion"; sigmatch_table[DETECT_AL_SSH_PROTOVERSION].AppLayerTxMatch = DetectSshVersionMatch; sigmatch_table[DETECT_AL_SSH_PROTOVERSION].Setup = DetectSshVersionSetup; - sigmatch_table[DETECT_AL_SSH_PROTOVERSION].Free = DetectSshVersionFree; + sigmatch_table[DETECT_AL_SSH_PROTOVERSION].Free = DetectSshVersionFree; #ifdef UNITTESTS sigmatch_table[DETECT_AL_SSH_PROTOVERSION].RegisterTests = DetectSshVersionRegisterTests; #endif - sigmatch_table[DETECT_AL_SSH_PROTOVERSION].flags = SIGMATCH_QUOTES_OPTIONAL|SIGMATCH_INFO_DEPRECATED; + sigmatch_table[DETECT_AL_SSH_PROTOVERSION].flags = + SIGMATCH_QUOTES_OPTIONAL | SIGMATCH_INFO_DEPRECATED; sigmatch_table[DETECT_AL_SSH_PROTOVERSION].alternative = DETECT_AL_SSH_PROTOCOL; DetectSetupParseRegexes(PARSE_REGEX, &parse_regex); @@ -105,9 +105,8 @@ void DetectSshVersionRegister(void) * \retval 0 no match * \retval 1 match */ -static int DetectSshVersionMatch (DetectEngineThreadCtx *det_ctx, - Flow *f, uint8_t flags, void *state, void *txv, - const Signature *s, const SigMatchCtx *m) +static int DetectSshVersionMatch(DetectEngineThreadCtx *det_ctx, Flow *f, uint8_t flags, + void *state, void *txv, const Signature *s, const SigMatchCtx *m) { SCEnter(); @@ -133,12 +132,12 @@ static int DetectSshVersionMatch (DetectEngineThreadCtx *det_ctx, if (protocol[0] == '2') { ret = 1; } else if (b_len >= 4) { - if (memcmp(protocol, "1.99", 4) == 0) { + if (memcmp(protocol, "1.99", 4) == 0) { ret = 1; } } } else { - SCLogDebug("looking for ssh protoversion %s length %"PRIu16"", ssh->ver, ssh->len); + SCLogDebug("looking for ssh protoversion %s length %" PRIu16 "", ssh->ver, ssh->len); if (b_len == ssh->len) { if (memcmp(protocol, ssh->ver, ssh->len) == 0) { ret = 1; @@ -157,7 +156,7 @@ static int DetectSshVersionMatch (DetectEngineThreadCtx *det_ctx, * \retval id_d pointer to DetectSshVersionData on success * \retval NULL on failure */ -static DetectSshVersionData *DetectSshVersionParse (DetectEngineCtx *de_ctx, const char *str) +static DetectSshVersionData *DetectSshVersionParse(DetectEngineCtx *de_ctx, const char *str) { DetectSshVersionData *ssh = NULL; int res = 0; @@ -194,7 +193,7 @@ static DetectSshVersionData *DetectSshVersionParse (DetectEngineCtx *de_ctx, con return ssh; } - ssh->ver = (uint8_t *)SCStrdup((char*)str_ptr); + ssh->ver = (uint8_t *)SCStrdup((char *)str_ptr); if (ssh->ver == NULL) { pcre2_substring_free((PCRE2_UCHAR *)str_ptr); goto error; @@ -215,7 +214,6 @@ static DetectSshVersionData *DetectSshVersionParse (DetectEngineCtx *de_ctx, con if (ssh != NULL) DetectSshVersionFree(de_ctx, ssh); return NULL; - } /** @@ -229,7 +227,7 @@ static DetectSshVersionData *DetectSshVersionParse (DetectEngineCtx *de_ctx, con * \retval 0 on Success * \retval -1 on Failure */ -static int DetectSshVersionSetup (DetectEngineCtx *de_ctx, Signature *s, const char *str) +static int DetectSshVersionSetup(DetectEngineCtx *de_ctx, Signature *s, const char *str) { DetectSshVersionData *ssh = NULL; @@ -253,7 +251,6 @@ static int DetectSshVersionSetup (DetectEngineCtx *de_ctx, Signature *s, const c if (ssh != NULL) DetectSshVersionFree(de_ctx, ssh); return -1; - } /** @@ -275,7 +272,7 @@ void DetectSshVersionFree(DetectEngineCtx *de_ctx, void *ptr) * \test DetectSshVersionTestParse01 is a test to make sure that we parse * a proto version correctly */ -static int DetectSshVersionTestParse01 (void) +static int DetectSshVersionTestParse01(void) { DetectSshVersionData *ssh = NULL; ssh = DetectSshVersionParse(NULL, "1.0"); @@ -290,7 +287,7 @@ static int DetectSshVersionTestParse01 (void) * \test DetectSshVersionTestParse02 is a test to make sure that we parse * the proto version (compatible with proto version 2) correctly */ -static int DetectSshVersionTestParse02 (void) +static int DetectSshVersionTestParse02(void) { DetectSshVersionData *ssh = NULL; ssh = DetectSshVersionParse(NULL, "2_compat"); @@ -304,7 +301,7 @@ static int DetectSshVersionTestParse02 (void) * \test DetectSshVersionTestParse03 is a test to make sure that we * don't return a ssh_data with an invalid value specified */ -static int DetectSshVersionTestParse03 (void) +static int DetectSshVersionTestParse03(void) { DetectSshVersionData *ssh = NULL; ssh = DetectSshVersionParse(NULL, "2_com"); @@ -319,7 +316,6 @@ static int DetectSshVersionTestParse03 (void) PASS; } - #include "stream-tcp-reassemble.h" #include "stream-tcp-util.h" @@ -333,12 +329,13 @@ static int DetectSshVersionTestDetect01(void) Packet *p = NULL; uint8_t sshbuf1[] = "SSH-1."; - uint8_t sshbuf2[] = "10-PuTTY_2.123" ; + uint8_t sshbuf2[] = "10-PuTTY_2.123"; uint8_t sshbuf3[] = "\n"; uint8_t sshbuf4[] = "whatever..."; - uint8_t* sshbufs[4] = {sshbuf1, sshbuf2, sshbuf3, sshbuf4}; - uint32_t sshlens[4] = {sizeof(sshbuf1) - 1, sizeof(sshbuf2) - 1, sizeof(sshbuf3) - 1, sizeof(sshbuf4) - 1}; + uint8_t *sshbufs[4] = { sshbuf1, sshbuf2, sshbuf3, sshbuf4 }; + uint32_t sshlens[4] = { sizeof(sshbuf1) - 1, sizeof(sshbuf2) - 1, sizeof(sshbuf3) - 1, + sizeof(sshbuf4) - 1 }; memset(&tv, 0x00, sizeof(tv)); @@ -369,17 +366,20 @@ static int DetectSshVersionTestDetect01(void) de_ctx->flags |= DE_QUIET; - s = de_ctx->sig_list = SigInit(de_ctx,"alert ssh any any -> any any (msg:\"SSH\"; ssh.protoversion:1.10; sid:1;)"); + s = de_ctx->sig_list = SigInit( + de_ctx, "alert ssh any any -> any any (msg:\"SSH\"; ssh.protoversion:1.10; sid:1;)"); FAIL_IF_NULL(s); SigGroupBuild(de_ctx); DetectEngineThreadCtxInit(&th_v, (void *)de_ctx, (void *)&det_ctx); uint32_t seq = 2; - for (int i=0; i<4; i++) { - FAIL_IF(StreamTcpUTAddSegmentWithPayload(&tv, ra_ctx, &ssn.server, seq, sshbufs[i], sshlens[i]) == -1); + for (int i = 0; i < 4; i++) { + FAIL_IF(StreamTcpUTAddSegmentWithPayload( + &tv, ra_ctx, &ssn.server, seq, sshbufs[i], sshlens[i]) == -1); seq += sshlens[i]; - FAIL_IF(StreamTcpReassembleAppLayer(&tv, ra_ctx, &ssn, &ssn.server, p, UPDATE_DIR_PACKET) < 0); + FAIL_IF(StreamTcpReassembleAppLayer(&tv, ra_ctx, &ssn, &ssn.server, p, UPDATE_DIR_PACKET) < + 0); } void *ssh_state = f->alstate; @@ -410,12 +410,13 @@ static int DetectSshVersionTestDetect02(void) Packet *p = NULL; uint8_t sshbuf1[] = "SSH-1.99-Pu"; - uint8_t sshbuf2[] = "TTY_2.123" ; + uint8_t sshbuf2[] = "TTY_2.123"; uint8_t sshbuf3[] = "\n"; uint8_t sshbuf4[] = "whatever..."; - uint8_t* sshbufs[4] = {sshbuf1, sshbuf2, sshbuf3, sshbuf4}; - uint32_t sshlens[4] = {sizeof(sshbuf1) - 1, sizeof(sshbuf2) - 1, sizeof(sshbuf3) - 1, sizeof(sshbuf4) - 1}; + uint8_t *sshbufs[4] = { sshbuf1, sshbuf2, sshbuf3, sshbuf4 }; + uint32_t sshlens[4] = { sizeof(sshbuf1) - 1, sizeof(sshbuf2) - 1, sizeof(sshbuf3) - 1, + sizeof(sshbuf4) - 1 }; memset(&tv, 0x00, sizeof(tv)); @@ -446,17 +447,20 @@ static int DetectSshVersionTestDetect02(void) de_ctx->flags |= DE_QUIET; - s = de_ctx->sig_list = SigInit(de_ctx,"alert ssh any any -> any any (msg:\"SSH\"; ssh.protoversion:2_compat; sid:1;)"); + s = de_ctx->sig_list = SigInit(de_ctx, + "alert ssh any any -> any any (msg:\"SSH\"; ssh.protoversion:2_compat; sid:1;)"); FAIL_IF_NULL(s); SigGroupBuild(de_ctx); DetectEngineThreadCtxInit(&th_v, (void *)de_ctx, (void *)&det_ctx); uint32_t seq = 2; - for (int i=0; i<4; i++) { - FAIL_IF(StreamTcpUTAddSegmentWithPayload(&tv, ra_ctx, &ssn.server, seq, sshbufs[i], sshlens[i]) == -1); + for (int i = 0; i < 4; i++) { + FAIL_IF(StreamTcpUTAddSegmentWithPayload( + &tv, ra_ctx, &ssn.server, seq, sshbufs[i], sshlens[i]) == -1); seq += sshlens[i]; - FAIL_IF(StreamTcpReassembleAppLayer(&tv, ra_ctx, &ssn, &ssn.server, p, UPDATE_DIR_PACKET) < 0); + FAIL_IF(StreamTcpReassembleAppLayer(&tv, ra_ctx, &ssn, &ssn.server, p, UPDATE_DIR_PACKET) < + 0); } void *ssh_state = f->alstate; @@ -487,12 +491,13 @@ static int DetectSshVersionTestDetect03(void) Packet *p = NULL; uint8_t sshbuf1[] = "SSH-1."; - uint8_t sshbuf2[] = "7-PuTTY_2.123" ; + uint8_t sshbuf2[] = "7-PuTTY_2.123"; uint8_t sshbuf3[] = "\n"; uint8_t sshbuf4[] = "whatever..."; - uint8_t* sshbufs[4] = {sshbuf1, sshbuf2, sshbuf3, sshbuf4}; - uint32_t sshlens[4] = {sizeof(sshbuf1) - 1, sizeof(sshbuf2) - 1, sizeof(sshbuf3) - 1, sizeof(sshbuf4) - 1}; + uint8_t *sshbufs[4] = { sshbuf1, sshbuf2, sshbuf3, sshbuf4 }; + uint32_t sshlens[4] = { sizeof(sshbuf1) - 1, sizeof(sshbuf2) - 1, sizeof(sshbuf3) - 1, + sizeof(sshbuf4) - 1 }; memset(&tv, 0x00, sizeof(tv)); @@ -523,17 +528,20 @@ static int DetectSshVersionTestDetect03(void) de_ctx->flags |= DE_QUIET; - s = de_ctx->sig_list = SigInit(de_ctx,"alert ssh any any -> any any (msg:\"SSH\"; ssh.protoversion:2_compat; sid:1;)"); + s = de_ctx->sig_list = SigInit(de_ctx, + "alert ssh any any -> any any (msg:\"SSH\"; ssh.protoversion:2_compat; sid:1;)"); FAIL_IF_NULL(s); SigGroupBuild(de_ctx); DetectEngineThreadCtxInit(&th_v, (void *)de_ctx, (void *)&det_ctx); uint32_t seq = 2; - for (int i=0; i<4; i++) { - FAIL_IF(StreamTcpUTAddSegmentWithPayload(&tv, ra_ctx, &ssn.server, seq, sshbufs[i], sshlens[i]) == -1); + for (int i = 0; i < 4; i++) { + FAIL_IF(StreamTcpUTAddSegmentWithPayload( + &tv, ra_ctx, &ssn.server, seq, sshbufs[i], sshlens[i]) == -1); seq += sshlens[i]; - FAIL_IF(StreamTcpReassembleAppLayer(&tv, ra_ctx, &ssn, &ssn.server, p, UPDATE_DIR_PACKET) < 0); + FAIL_IF(StreamTcpReassembleAppLayer(&tv, ra_ctx, &ssn, &ssn.server, p, UPDATE_DIR_PACKET) < + 0); } void *ssh_state = f->alstate; @@ -562,11 +570,8 @@ static void DetectSshVersionRegisterTests(void) UtRegisterTest("DetectSshVersionTestParse01", DetectSshVersionTestParse01); UtRegisterTest("DetectSshVersionTestParse02", DetectSshVersionTestParse02); UtRegisterTest("DetectSshVersionTestParse03", DetectSshVersionTestParse03); - UtRegisterTest("DetectSshVersionTestDetect01", - DetectSshVersionTestDetect01); - UtRegisterTest("DetectSshVersionTestDetect02", - DetectSshVersionTestDetect02); - UtRegisterTest("DetectSshVersionTestDetect03", - DetectSshVersionTestDetect03); + UtRegisterTest("DetectSshVersionTestDetect01", DetectSshVersionTestDetect01); + UtRegisterTest("DetectSshVersionTestDetect02", DetectSshVersionTestDetect02); + UtRegisterTest("DetectSshVersionTestDetect03", DetectSshVersionTestDetect03); } #endif /* UNITTESTS */ diff --git a/src/detect-ssh-proto-version.h b/src/detect-ssh-proto-version.h index a4c8eddbbe34..7edf66ae3f70 100644 --- a/src/detect-ssh-proto-version.h +++ b/src/detect-ssh-proto-version.h @@ -34,7 +34,6 @@ typedef struct DetectSshVersionData_ { } DetectSshVersionData; /* prototypes */ -void DetectSshVersionRegister (void); +void DetectSshVersionRegister(void); #endif /* __DETECT_SSH_VERSION_H__ */ - diff --git a/src/detect-ssh-proto.c b/src/detect-ssh-proto.c index a979190de1a9..ac82d3424355 100644 --- a/src/detect-ssh-proto.c +++ b/src/detect-ssh-proto.c @@ -21,7 +21,6 @@ * @{ */ - /** * \file * @@ -48,16 +47,16 @@ #include "detect-ssh-proto.h" #include "rust.h" -#define KEYWORD_NAME "ssh.proto" +#define KEYWORD_NAME "ssh.proto" #define KEYWORD_NAME_LEGACY "ssh_proto" -#define KEYWORD_DOC "ssh-keywords.html#ssh-proto" -#define BUFFER_NAME "ssh.proto" -#define BUFFER_DESC "ssh protocol version field" +#define KEYWORD_DOC "ssh-keywords.html#ssh-proto" +#define BUFFER_NAME "ssh.proto" +#define BUFFER_DESC "ssh protocol version field" static int g_buffer_id = 0; static InspectionBuffer *GetSshData(DetectEngineThreadCtx *det_ctx, - const DetectEngineTransforms *transforms, Flow *_f, - const uint8_t flow_flags, void *txv, const int list_id) + const DetectEngineTransforms *transforms, Flow *_f, const uint8_t flow_flags, void *txv, + const int list_id) { SCEnter(); @@ -101,20 +100,15 @@ void DetectSshProtocolRegister(void) sigmatch_table[DETECT_AL_SSH_PROTOCOL].Setup = DetectSshProtocolSetup; sigmatch_table[DETECT_AL_SSH_PROTOCOL].flags |= SIGMATCH_INFO_STICKY_BUFFER | SIGMATCH_NOOPT; + DetectAppLayerMpmRegister2(BUFFER_NAME, SIG_FLAG_TOSERVER, 2, PrefilterGenericMpmRegister, + GetSshData, ALPROTO_SSH, SshStateBannerDone), + DetectAppLayerMpmRegister2(BUFFER_NAME, SIG_FLAG_TOCLIENT, 2, + PrefilterGenericMpmRegister, GetSshData, ALPROTO_SSH, SshStateBannerDone), - DetectAppLayerMpmRegister2(BUFFER_NAME, SIG_FLAG_TOSERVER, 2, - PrefilterGenericMpmRegister, GetSshData, - ALPROTO_SSH, SshStateBannerDone), - DetectAppLayerMpmRegister2(BUFFER_NAME, SIG_FLAG_TOCLIENT, 2, - PrefilterGenericMpmRegister, GetSshData, - ALPROTO_SSH, SshStateBannerDone), - - DetectAppLayerInspectEngineRegister2(BUFFER_NAME, - ALPROTO_SSH, SIG_FLAG_TOSERVER, SshStateBannerDone, - DetectEngineInspectBufferGeneric, GetSshData); - DetectAppLayerInspectEngineRegister2(BUFFER_NAME, - ALPROTO_SSH, SIG_FLAG_TOCLIENT, SshStateBannerDone, - DetectEngineInspectBufferGeneric, GetSshData); + DetectAppLayerInspectEngineRegister2(BUFFER_NAME, ALPROTO_SSH, SIG_FLAG_TOSERVER, + SshStateBannerDone, DetectEngineInspectBufferGeneric, GetSshData); + DetectAppLayerInspectEngineRegister2(BUFFER_NAME, ALPROTO_SSH, SIG_FLAG_TOCLIENT, + SshStateBannerDone, DetectEngineInspectBufferGeneric, GetSshData); DetectBufferTypeSetDescriptionByName(BUFFER_NAME, BUFFER_DESC); diff --git a/src/detect-ssh-software-version.c b/src/detect-ssh-software-version.c index c2ba4ba888ef..9340106c38a5 100644 --- a/src/detect-ssh-software-version.c +++ b/src/detect-ssh-software-version.c @@ -62,21 +62,19 @@ /** * \brief Regex for parsing the softwareversion string */ -#define PARSE_REGEX "^\\s*\"?\\s*?([0-9a-zA-Z\\:\\.\\-\\_\\+\\s+]+)\\s*\"?\\s*$" +#define PARSE_REGEX "^\\s*\"?\\s*?([0-9a-zA-Z\\:\\.\\-\\_\\+\\s+]+)\\s*\"?\\s*$" static DetectParseRegex parse_regex; -static int DetectSshSoftwareVersionMatch (DetectEngineThreadCtx *, - Flow *, uint8_t, void *, void *, +static int DetectSshSoftwareVersionMatch(DetectEngineThreadCtx *, Flow *, uint8_t, void *, void *, const Signature *, const SigMatchCtx *); -static int DetectSshSoftwareVersionSetup (DetectEngineCtx *, Signature *, const char *); +static int DetectSshSoftwareVersionSetup(DetectEngineCtx *, Signature *, const char *); #ifdef UNITTESTS static void DetectSshSoftwareVersionRegisterTests(void); #endif static void DetectSshSoftwareVersionFree(DetectEngineCtx *de_ctx, void *); static int g_ssh_banner_list_id = 0; - /** * \brief Registration function for keyword: ssh.softwareversion */ @@ -84,14 +82,17 @@ void DetectSshSoftwareVersionRegister(void) { sigmatch_table[DETECT_AL_SSH_SOFTWAREVERSION].name = "ssh.softwareversion"; sigmatch_table[DETECT_AL_SSH_SOFTWAREVERSION].desc = "match SSH software string"; - sigmatch_table[DETECT_AL_SSH_SOFTWAREVERSION].url = "/rules/ssh-keywords.html#ssh-softwareversion"; + sigmatch_table[DETECT_AL_SSH_SOFTWAREVERSION].url = + "/rules/ssh-keywords.html#ssh-softwareversion"; sigmatch_table[DETECT_AL_SSH_SOFTWAREVERSION].AppLayerTxMatch = DetectSshSoftwareVersionMatch; sigmatch_table[DETECT_AL_SSH_SOFTWAREVERSION].Setup = DetectSshSoftwareVersionSetup; - sigmatch_table[DETECT_AL_SSH_SOFTWAREVERSION].Free = DetectSshSoftwareVersionFree; + sigmatch_table[DETECT_AL_SSH_SOFTWAREVERSION].Free = DetectSshSoftwareVersionFree; #ifdef UNITTESTS - sigmatch_table[DETECT_AL_SSH_SOFTWAREVERSION].RegisterTests = DetectSshSoftwareVersionRegisterTests; + sigmatch_table[DETECT_AL_SSH_SOFTWAREVERSION].RegisterTests = + DetectSshSoftwareVersionRegisterTests; #endif - sigmatch_table[DETECT_AL_SSH_SOFTWAREVERSION].flags = SIGMATCH_QUOTES_OPTIONAL|SIGMATCH_INFO_DEPRECATED; + sigmatch_table[DETECT_AL_SSH_SOFTWAREVERSION].flags = + SIGMATCH_QUOTES_OPTIONAL | SIGMATCH_INFO_DEPRECATED; sigmatch_table[DETECT_AL_SSH_SOFTWAREVERSION].alternative = DETECT_AL_SSH_SOFTWARE; DetectSetupParseRegexes(PARSE_REGEX, &parse_regex); @@ -115,9 +116,8 @@ void DetectSshSoftwareVersionRegister(void) * \retval 0 no match * \retval 1 match */ -static int DetectSshSoftwareVersionMatch (DetectEngineThreadCtx *det_ctx, - Flow *f, uint8_t flags, void *state, void *txv, - const Signature *s, const SigMatchCtx *m) +static int DetectSshSoftwareVersionMatch(DetectEngineThreadCtx *det_ctx, Flow *f, uint8_t flags, + void *state, void *txv, const Signature *s, const SigMatchCtx *m) { SCEnter(); @@ -153,7 +153,8 @@ static int DetectSshSoftwareVersionMatch (DetectEngineThreadCtx *det_ctx, * \retval id_d pointer to DetectSshSoftwareVersionData on success * \retval NULL on failure */ -static DetectSshSoftwareVersionData *DetectSshSoftwareVersionParse (DetectEngineCtx *de_ctx, const char *str) +static DetectSshSoftwareVersionData *DetectSshSoftwareVersionParse( + DetectEngineCtx *de_ctx, const char *str) { DetectSshSoftwareVersionData *ssh = NULL; int res = 0; @@ -203,7 +204,6 @@ static DetectSshSoftwareVersionData *DetectSshSoftwareVersionParse (DetectEngine if (ssh != NULL) DetectSshSoftwareVersionFree(de_ctx, ssh); return NULL; - } /** @@ -217,7 +217,7 @@ static DetectSshSoftwareVersionData *DetectSshSoftwareVersionParse (DetectEngine * \retval 0 on Success * \retval -1 on Failure */ -static int DetectSshSoftwareVersionSetup (DetectEngineCtx *de_ctx, Signature *s, const char *str) +static int DetectSshSoftwareVersionSetup(DetectEngineCtx *de_ctx, Signature *s, const char *str) { DetectSshSoftwareVersionData *ssh = NULL; @@ -241,7 +241,6 @@ static int DetectSshSoftwareVersionSetup (DetectEngineCtx *de_ctx, Signature *s, if (ssh != NULL) DetectSshSoftwareVersionFree(de_ctx, ssh); return -1; - } /** @@ -267,11 +266,11 @@ static void DetectSshSoftwareVersionFree(DetectEngineCtx *de_ctx, void *ptr) * \test DetectSshSoftwareVersionTestParse01 is a test to make sure that we parse * a software version correctly */ -static int DetectSshSoftwareVersionTestParse01 (void) +static int DetectSshSoftwareVersionTestParse01(void) { DetectSshSoftwareVersionData *ssh = NULL; ssh = DetectSshSoftwareVersionParse(NULL, "PuTTY_1.0"); - if (ssh != NULL && strncmp((char *) ssh->software_ver, "PuTTY_1.0", 9) == 0) { + if (ssh != NULL && strncmp((char *)ssh->software_ver, "PuTTY_1.0", 9) == 0) { DetectSshSoftwareVersionFree(NULL, ssh); return 1; } @@ -283,11 +282,11 @@ static int DetectSshSoftwareVersionTestParse01 (void) * \test DetectSshSoftwareVersionTestParse02 is a test to make sure that we parse * the software version correctly */ -static int DetectSshSoftwareVersionTestParse02 (void) +static int DetectSshSoftwareVersionTestParse02(void) { DetectSshSoftwareVersionData *ssh = NULL; ssh = DetectSshSoftwareVersionParse(NULL, "\"SecureCRT-4.0\""); - if (ssh != NULL && strncmp((char *) ssh->software_ver, "SecureCRT-4.0", 13) == 0) { + if (ssh != NULL && strncmp((char *)ssh->software_ver, "SecureCRT-4.0", 13) == 0) { DetectSshSoftwareVersionFree(NULL, ssh); return 1; } @@ -299,7 +298,7 @@ static int DetectSshSoftwareVersionTestParse02 (void) * \test DetectSshSoftwareVersionTestParse03 is a test to make sure that we * don't return a ssh_data with an empty value specified */ -static int DetectSshSoftwareVersionTestParse03 (void) +static int DetectSshSoftwareVersionTestParse03(void) { DetectSshSoftwareVersionData *ssh = NULL; ssh = DetectSshSoftwareVersionParse(NULL, ""); @@ -311,7 +310,6 @@ static int DetectSshSoftwareVersionTestParse03 (void) return 1; } - #include "stream-tcp-reassemble.h" #include "stream-tcp-util.h" @@ -325,12 +323,13 @@ static int DetectSshSoftwareVersionTestDetect01(void) Packet *p = NULL; uint8_t sshbuf1[] = "SSH-1."; - uint8_t sshbuf2[] = "10-PuTTY_2.123" ; + uint8_t sshbuf2[] = "10-PuTTY_2.123"; uint8_t sshbuf3[] = "\n"; uint8_t sshbuf4[] = "whatever..."; - uint8_t* sshbufs[4] = {sshbuf1, sshbuf2, sshbuf3, sshbuf4}; - uint32_t sshlens[4] = {sizeof(sshbuf1) - 1, sizeof(sshbuf2) - 1, sizeof(sshbuf3) - 1, sizeof(sshbuf4) - 1}; + uint8_t *sshbufs[4] = { sshbuf1, sshbuf2, sshbuf3, sshbuf4 }; + uint32_t sshlens[4] = { sizeof(sshbuf1) - 1, sizeof(sshbuf2) - 1, sizeof(sshbuf3) - 1, + sizeof(sshbuf4) - 1 }; memset(&tv, 0x00, sizeof(tv)); @@ -361,17 +360,20 @@ static int DetectSshSoftwareVersionTestDetect01(void) de_ctx->flags |= DE_QUIET; - s = de_ctx->sig_list = SigInit(de_ctx,"alert ssh any any -> any any (msg:\"SSH\"; ssh.softwareversion:PuTTY_2.123; sid:1;)"); + s = de_ctx->sig_list = SigInit(de_ctx, + "alert ssh any any -> any any (msg:\"SSH\"; ssh.softwareversion:PuTTY_2.123; sid:1;)"); FAIL_IF_NULL(s); SigGroupBuild(de_ctx); DetectEngineThreadCtxInit(&th_v, (void *)de_ctx, (void *)&det_ctx); uint32_t seq = 2; - for (int i=0; i<4; i++) { - FAIL_IF(StreamTcpUTAddSegmentWithPayload(&tv, ra_ctx, &ssn.server, seq, sshbufs[i], sshlens[i]) == -1); + for (int i = 0; i < 4; i++) { + FAIL_IF(StreamTcpUTAddSegmentWithPayload( + &tv, ra_ctx, &ssn.server, seq, sshbufs[i], sshlens[i]) == -1); seq += sshlens[i]; - FAIL_IF(StreamTcpReassembleAppLayer(&tv, ra_ctx, &ssn, &ssn.server, p, UPDATE_DIR_PACKET) < 0); + FAIL_IF(StreamTcpReassembleAppLayer(&tv, ra_ctx, &ssn, &ssn.server, p, UPDATE_DIR_PACKET) < + 0); } void *ssh_state = f->alstate; @@ -402,12 +404,13 @@ static int DetectSshSoftwareVersionTestDetect02(void) Packet *p = NULL; uint8_t sshbuf1[] = "SSH-1.99-Pu"; - uint8_t sshbuf2[] = "TTY_2.123" ; + uint8_t sshbuf2[] = "TTY_2.123"; uint8_t sshbuf3[] = "\n"; uint8_t sshbuf4[] = "whatever..."; - uint8_t* sshbufs[4] = {sshbuf1, sshbuf2, sshbuf3, sshbuf4}; - uint32_t sshlens[4] = {sizeof(sshbuf1) - 1, sizeof(sshbuf2) - 1, sizeof(sshbuf3) - 1, sizeof(sshbuf4) - 1}; + uint8_t *sshbufs[4] = { sshbuf1, sshbuf2, sshbuf3, sshbuf4 }; + uint32_t sshlens[4] = { sizeof(sshbuf1) - 1, sizeof(sshbuf2) - 1, sizeof(sshbuf3) - 1, + sizeof(sshbuf4) - 1 }; memset(&tv, 0x00, sizeof(tv)); @@ -438,17 +441,20 @@ static int DetectSshSoftwareVersionTestDetect02(void) de_ctx->flags |= DE_QUIET; - s = de_ctx->sig_list = SigInit(de_ctx,"alert ssh any any -> any any (msg:\"SSH\"; ssh.softwareversion:PuTTY_2.123; sid:1;)"); + s = de_ctx->sig_list = SigInit(de_ctx, + "alert ssh any any -> any any (msg:\"SSH\"; ssh.softwareversion:PuTTY_2.123; sid:1;)"); FAIL_IF_NULL(s); SigGroupBuild(de_ctx); DetectEngineThreadCtxInit(&th_v, (void *)de_ctx, (void *)&det_ctx); uint32_t seq = 2; - for (int i=0; i<4; i++) { - FAIL_IF(StreamTcpUTAddSegmentWithPayload(&tv, ra_ctx, &ssn.server, seq, sshbufs[i], sshlens[i]) == -1); + for (int i = 0; i < 4; i++) { + FAIL_IF(StreamTcpUTAddSegmentWithPayload( + &tv, ra_ctx, &ssn.server, seq, sshbufs[i], sshlens[i]) == -1); seq += sshlens[i]; - FAIL_IF(StreamTcpReassembleAppLayer(&tv, ra_ctx, &ssn, &ssn.server, p, UPDATE_DIR_PACKET) < 0); + FAIL_IF(StreamTcpReassembleAppLayer(&tv, ra_ctx, &ssn, &ssn.server, p, UPDATE_DIR_PACKET) < + 0); } void *ssh_state = f->alstate; @@ -479,12 +485,13 @@ static int DetectSshSoftwareVersionTestDetect03(void) Packet *p = NULL; uint8_t sshbuf1[] = "SSH-1."; - uint8_t sshbuf2[] = "7-PuTTY_2.123" ; + uint8_t sshbuf2[] = "7-PuTTY_2.123"; uint8_t sshbuf3[] = "\n"; uint8_t sshbuf4[] = "whatever..."; - uint8_t* sshbufs[4] = {sshbuf1, sshbuf2, sshbuf3, sshbuf4}; - uint32_t sshlens[4] = {sizeof(sshbuf1) - 1, sizeof(sshbuf2) - 1, sizeof(sshbuf3) - 1, sizeof(sshbuf4) - 1}; + uint8_t *sshbufs[4] = { sshbuf1, sshbuf2, sshbuf3, sshbuf4 }; + uint32_t sshlens[4] = { sizeof(sshbuf1) - 1, sizeof(sshbuf2) - 1, sizeof(sshbuf3) - 1, + sizeof(sshbuf4) - 1 }; memset(&tv, 0x00, sizeof(tv)); @@ -515,17 +522,20 @@ static int DetectSshSoftwareVersionTestDetect03(void) de_ctx->flags |= DE_QUIET; - s = de_ctx->sig_list = SigInit(de_ctx,"alert ssh any any -> any any (msg:\"SSH\"; ssh.softwareversion:lalala-3.1.4; sid:1;)"); + s = de_ctx->sig_list = SigInit(de_ctx, + "alert ssh any any -> any any (msg:\"SSH\"; ssh.softwareversion:lalala-3.1.4; sid:1;)"); FAIL_IF_NULL(s); SigGroupBuild(de_ctx); DetectEngineThreadCtxInit(&th_v, (void *)de_ctx, (void *)&det_ctx); uint32_t seq = 2; - for (int i=0; i<4; i++) { - FAIL_IF(StreamTcpUTAddSegmentWithPayload(&tv, ra_ctx, &ssn.server, seq, sshbufs[i], sshlens[i]) == -1); + for (int i = 0; i < 4; i++) { + FAIL_IF(StreamTcpUTAddSegmentWithPayload( + &tv, ra_ctx, &ssn.server, seq, sshbufs[i], sshlens[i]) == -1); seq += sshlens[i]; - FAIL_IF(StreamTcpReassembleAppLayer(&tv, ra_ctx, &ssn, &ssn.server, p, UPDATE_DIR_PACKET) < 0); + FAIL_IF(StreamTcpReassembleAppLayer(&tv, ra_ctx, &ssn, &ssn.server, p, UPDATE_DIR_PACKET) < + 0); } void *ssh_state = f->alstate; @@ -551,17 +561,11 @@ static int DetectSshSoftwareVersionTestDetect03(void) */ static void DetectSshSoftwareVersionRegisterTests(void) { - UtRegisterTest("DetectSshSoftwareVersionTestParse01", - DetectSshSoftwareVersionTestParse01); - UtRegisterTest("DetectSshSoftwareVersionTestParse02", - DetectSshSoftwareVersionTestParse02); - UtRegisterTest("DetectSshSoftwareVersionTestParse03", - DetectSshSoftwareVersionTestParse03); - UtRegisterTest("DetectSshSoftwareVersionTestDetect01", - DetectSshSoftwareVersionTestDetect01); - UtRegisterTest("DetectSshSoftwareVersionTestDetect02", - DetectSshSoftwareVersionTestDetect02); - UtRegisterTest("DetectSshSoftwareVersionTestDetect03", - DetectSshSoftwareVersionTestDetect03); + UtRegisterTest("DetectSshSoftwareVersionTestParse01", DetectSshSoftwareVersionTestParse01); + UtRegisterTest("DetectSshSoftwareVersionTestParse02", DetectSshSoftwareVersionTestParse02); + UtRegisterTest("DetectSshSoftwareVersionTestParse03", DetectSshSoftwareVersionTestParse03); + UtRegisterTest("DetectSshSoftwareVersionTestDetect01", DetectSshSoftwareVersionTestDetect01); + UtRegisterTest("DetectSshSoftwareVersionTestDetect02", DetectSshSoftwareVersionTestDetect02); + UtRegisterTest("DetectSshSoftwareVersionTestDetect03", DetectSshSoftwareVersionTestDetect03); } #endif /* UNITTESTS */ diff --git a/src/detect-ssh-software-version.h b/src/detect-ssh-software-version.h index 7cf311167731..d740c78b146f 100644 --- a/src/detect-ssh-software-version.h +++ b/src/detect-ssh-software-version.h @@ -26,11 +26,10 @@ typedef struct DetectSshSoftwareVersionData_ { uint8_t *software_ver; /** ssh version to match */ - uint16_t len; /** ssh version length to match */ + uint16_t len; /** ssh version length to match */ } DetectSshSoftwareVersionData; /* prototypes */ void DetectSshSoftwareVersionRegister(void); #endif /* __DETECT_SSH_SOFTWARE_VERSION_H__ */ - diff --git a/src/detect-ssh-software.c b/src/detect-ssh-software.c index cd11c5c20904..888592c2b502 100644 --- a/src/detect-ssh-software.c +++ b/src/detect-ssh-software.c @@ -21,7 +21,6 @@ * @{ */ - /** * \file * @@ -48,16 +47,16 @@ #include "detect-ssh-software.h" #include "rust.h" -#define KEYWORD_NAME "ssh.software" +#define KEYWORD_NAME "ssh.software" #define KEYWORD_NAME_LEGACY "ssh_software" -#define KEYWORD_DOC "ssh-keywords.html#ssh-software" -#define BUFFER_NAME "ssh_software" -#define BUFFER_DESC "ssh software field" +#define KEYWORD_DOC "ssh-keywords.html#ssh-software" +#define BUFFER_NAME "ssh_software" +#define BUFFER_DESC "ssh software field" static int g_buffer_id = 0; static InspectionBuffer *GetSshData(DetectEngineThreadCtx *det_ctx, - const DetectEngineTransforms *transforms, Flow *_f, - const uint8_t flow_flags, void *txv, const int list_id) + const DetectEngineTransforms *transforms, Flow *_f, const uint8_t flow_flags, void *txv, + const int list_id) { SCEnter(); @@ -92,7 +91,6 @@ static int DetectSshSoftwareSetup(DetectEngineCtx *de_ctx, Signature *s, const c return 0; } - void DetectSshSoftwareRegister(void) { sigmatch_table[DETECT_AL_SSH_SOFTWARE].name = KEYWORD_NAME; @@ -102,19 +100,15 @@ void DetectSshSoftwareRegister(void) sigmatch_table[DETECT_AL_SSH_SOFTWARE].Setup = DetectSshSoftwareSetup; sigmatch_table[DETECT_AL_SSH_SOFTWARE].flags |= SIGMATCH_INFO_STICKY_BUFFER | SIGMATCH_NOOPT; - DetectAppLayerMpmRegister2(BUFFER_NAME, SIG_FLAG_TOSERVER, 2, - PrefilterGenericMpmRegister, GetSshData, - ALPROTO_SSH, SshStateBannerDone), - DetectAppLayerMpmRegister2(BUFFER_NAME, SIG_FLAG_TOCLIENT, 2, - PrefilterGenericMpmRegister, GetSshData, - ALPROTO_SSH, SshStateBannerDone), - - DetectAppLayerInspectEngineRegister2(BUFFER_NAME, - ALPROTO_SSH, SIG_FLAG_TOSERVER, SshStateBannerDone, - DetectEngineInspectBufferGeneric, GetSshData); - DetectAppLayerInspectEngineRegister2(BUFFER_NAME, - ALPROTO_SSH, SIG_FLAG_TOCLIENT, SshStateBannerDone, - DetectEngineInspectBufferGeneric, GetSshData); + DetectAppLayerMpmRegister2(BUFFER_NAME, SIG_FLAG_TOSERVER, 2, PrefilterGenericMpmRegister, + GetSshData, ALPROTO_SSH, SshStateBannerDone), + DetectAppLayerMpmRegister2(BUFFER_NAME, SIG_FLAG_TOCLIENT, 2, + PrefilterGenericMpmRegister, GetSshData, ALPROTO_SSH, SshStateBannerDone), + + DetectAppLayerInspectEngineRegister2(BUFFER_NAME, ALPROTO_SSH, SIG_FLAG_TOSERVER, + SshStateBannerDone, DetectEngineInspectBufferGeneric, GetSshData); + DetectAppLayerInspectEngineRegister2(BUFFER_NAME, ALPROTO_SSH, SIG_FLAG_TOCLIENT, + SshStateBannerDone, DetectEngineInspectBufferGeneric, GetSshData); DetectBufferTypeSetDescriptionByName(BUFFER_NAME, BUFFER_DESC); diff --git a/src/detect-ssl-state.c b/src/detect-ssl-state.c index fd60f045a4c3..3e537e9ba93c 100644 --- a/src/detect-ssl-state.c +++ b/src/detect-ssl-state.c @@ -56,8 +56,7 @@ static DetectParseRegex parse_regex1; #define PARSE_REGEX2 "^(?:\\s*[|,]\\s*(!?)([_a-zA-Z0-9]+))(.*)$" static DetectParseRegex parse_regex2; -static int DetectSslStateMatch(DetectEngineThreadCtx *, - Flow *, uint8_t, void *, void *, +static int DetectSslStateMatch(DetectEngineThreadCtx *, Flow *, uint8_t, void *, void *, const Signature *, const SigMatchCtx *); static int DetectSslStateSetup(DetectEngineCtx *, Signature *, const char *); #ifdef UNITTESTS @@ -77,7 +76,7 @@ void DetectSslStateRegister(void) sigmatch_table[DETECT_AL_SSL_STATE].url = "/rules/tls-keywords.html#ssl-state"; sigmatch_table[DETECT_AL_SSL_STATE].AppLayerTxMatch = DetectSslStateMatch; sigmatch_table[DETECT_AL_SSL_STATE].Setup = DetectSslStateSetup; - sigmatch_table[DETECT_AL_SSL_STATE].Free = DetectSslStateFree; + sigmatch_table[DETECT_AL_SSL_STATE].Free = DetectSslStateFree; #ifdef UNITTESTS sigmatch_table[DETECT_AL_SSL_STATE].RegisterTests = DetectSslStateRegisterTests; #endif @@ -86,8 +85,7 @@ void DetectSslStateRegister(void) g_tls_generic_list_id = DetectBufferTypeRegister("tls_generic"); - DetectBufferTypeSetDescriptionByName("tls_generic", - "generic ssl/tls inspection"); + DetectBufferTypeSetDescriptionByName("tls_generic", "generic ssl/tls inspection"); DetectAppLayerInspectEngineRegister2( "tls_generic", ALPROTO_TLS, SIG_FLAG_TOSERVER, 0, DetectEngineInspectGenericList, NULL); @@ -109,9 +107,8 @@ void DetectSslStateRegister(void) * \retval 1 Match. * \retval 0 No match. */ -static int DetectSslStateMatch(DetectEngineThreadCtx *det_ctx, - Flow *f, uint8_t flags, void *alstate, void *txv, - const Signature *s, const SigMatchCtx *m) +static int DetectSslStateMatch(DetectEngineThreadCtx *det_ctx, Flow *f, uint8_t flags, + void *alstate, void *txv, const Signature *s, const SigMatchCtx *m) { const DetectSslStateData *ssd = (const DetectSslStateData *)m; SSLState *ssl_state = (SSLState *)alstate; @@ -273,7 +270,7 @@ static DetectSslStateData *DetectSslStateParse(const char *arg) pcre2_match_data_free(match2); } - if ( (ssd = SCMalloc(sizeof(DetectSslStateData))) == NULL) { + if ((ssd = SCMalloc(sizeof(DetectSslStateData))) == NULL) { goto error; } ssd->flags = flags; @@ -289,7 +286,7 @@ static DetectSslStateData *DetectSslStateParse(const char *arg) return NULL; } - /** +/** * \internal * \brief Setup function for ssl_state keyword. * diff --git a/src/detect-ssl-state.h b/src/detect-ssl-state.h index 2196ae019de5..925f27c2f752 100644 --- a/src/detect-ssl-state.h +++ b/src/detect-ssl-state.h @@ -22,7 +22,7 @@ */ #ifndef DETECT_SSL_STATE_H -#define DETECT_SSL_STATE_H +#define DETECT_SSL_STATE_H /* we pick these flags from the parser */ #define DETECT_SSL_STATE_CLIENT_HELLO SSL_AL_FLAG_STATE_CLIENT_HELLO diff --git a/src/detect-ssl-version.c b/src/detect-ssl-version.c index 1326da49dd1c..40f3d5f5ab44 100644 --- a/src/detect-ssl-version.c +++ b/src/detect-ssl-version.c @@ -50,9 +50,7 @@ #include "stream-tcp.h" #include "app-layer-ssl.h" - -static int DetectSslVersionMatch(DetectEngineThreadCtx *, - Flow *, uint8_t, void *, void *, +static int DetectSslVersionMatch(DetectEngineThreadCtx *, Flow *, uint8_t, void *, void *, const Signature *, const SigMatchCtx *); static int DetectSslVersionSetup(DetectEngineCtx *, Signature *, const char *); #ifdef UNITTESTS @@ -71,7 +69,7 @@ void DetectSslVersionRegister(void) sigmatch_table[DETECT_AL_SSL_VERSION].url = "/rules/tls-keywords.html#ssl-version"; sigmatch_table[DETECT_AL_SSL_VERSION].AppLayerTxMatch = DetectSslVersionMatch; sigmatch_table[DETECT_AL_SSL_VERSION].Setup = DetectSslVersionSetup; - sigmatch_table[DETECT_AL_SSL_VERSION].Free = DetectSslVersionFree; + sigmatch_table[DETECT_AL_SSL_VERSION].Free = DetectSslVersionFree; #ifdef UNITTESTS sigmatch_table[DETECT_AL_SSL_VERSION].RegisterTests = DetectSslVersionRegisterTests; #endif @@ -90,9 +88,8 @@ void DetectSslVersionRegister(void) * \retval 0 no match * \retval 1 match */ -static int DetectSslVersionMatch(DetectEngineThreadCtx *det_ctx, - Flow *f, uint8_t flags, void *state, void *txv, - const Signature *s, const SigMatchCtx *m) +static int DetectSslVersionMatch(DetectEngineThreadCtx *det_ctx, Flow *f, uint8_t flags, + void *state, void *txv, const Signature *s, const SigMatchCtx *m) { SCEnter(); @@ -108,12 +105,10 @@ static int DetectSslVersionMatch(DetectEngineThreadCtx *det_ctx, } if (flags & STREAM_TOCLIENT) { - SCLogDebug("server (toclient) version is 0x%02X", - app_state->server_connp.version); + SCLogDebug("server (toclient) version is 0x%02X", app_state->server_connp.version); ver = app_state->server_connp.version; } else if (flags & STREAM_TOSERVER) { - SCLogDebug("client (toserver) version is 0x%02X", - app_state->client_connp.version); + SCLogDebug("client (toserver) version is 0x%02X", app_state->client_connp.version); ver = app_state->client_connp.version; } @@ -273,7 +268,6 @@ static DetectSslVersionData *DetectSslVersionParse(DetectEngineCtx *de_ctx, cons if (ssl != NULL) DetectSslVersionFree(de_ctx, ssl); return NULL; - } /** @@ -287,7 +281,7 @@ static DetectSslVersionData *DetectSslVersionParse(DetectEngineCtx *de_ctx, cons * \retval 0 on Success * \retval -1 on Failure */ -static int DetectSslVersionSetup (DetectEngineCtx *de_ctx, Signature *s, const char *str) +static int DetectSslVersionSetup(DetectEngineCtx *de_ctx, Signature *s, const char *str) { DetectSslVersionData *ssl = NULL; diff --git a/src/detect-ssl-version.h b/src/detect-ssl-version.h index 6809178c5f0f..1605a9ebf156 100644 --- a/src/detect-ssl-version.h +++ b/src/detect-ssl-version.h @@ -23,9 +23,9 @@ */ #ifndef DETECT_SSL_VERSION_H -#define DETECT_SSL_VERSION_H +#define DETECT_SSL_VERSION_H -#define DETECT_SSL_VERSION_NEGATED 0x01 +#define DETECT_SSL_VERSION_NEGATED 0x01 enum { SSLv2 = 0, @@ -49,6 +49,6 @@ typedef struct DetectSslVersionData_ { } DetectSslVersionData; /* prototypes */ -void DetectSslVersionRegister (void); +void DetectSslVersionRegister(void); -#endif /* DETECT_SSL_VERSION_H */ +#endif /* DETECT_SSL_VERSION_H */ diff --git a/src/detect-stream_size.c b/src/detect-stream_size.c index 196439aa3131..0328ef706a11 100644 --- a/src/detect-stream_size.c +++ b/src/detect-stream_size.c @@ -38,11 +38,10 @@ #include "util-debug.h" #include "util-byte.h" - /*prototypes*/ -static int DetectStreamSizeMatch (DetectEngineThreadCtx *, Packet *, - const Signature *, const SigMatchCtx *); -static int DetectStreamSizeSetup (DetectEngineCtx *, Signature *, const char *); +static int DetectStreamSizeMatch( + DetectEngineThreadCtx *, Packet *, const Signature *, const SigMatchCtx *); +static int DetectStreamSizeSetup(DetectEngineCtx *, Signature *, const char *); void DetectStreamSizeFree(DetectEngineCtx *de_ctx, void *); #ifdef UNITTESTS static void DetectStreamSizeRegisterTests(void); @@ -140,7 +139,7 @@ static int DetectStreamSizeMatch( * \retval 0 on Success * \retval -1 on Failure */ -static int DetectStreamSizeSetup (DetectEngineCtx *de_ctx, Signature *s, const char *streamstr) +static int DetectStreamSizeSetup(DetectEngineCtx *de_ctx, Signature *s, const char *streamstr) { DetectStreamSizeData *sd = rs_detect_stream_size_parse(streamstr); if (sd == NULL) @@ -233,7 +232,7 @@ static bool PrefilterStreamSizeIsPrefilterable(const Signature *s) * user options correctly, when given valid stream_size options. */ -static int DetectStreamSizeParseTest01 (void) +static int DetectStreamSizeParseTest01(void) { int result = 0; DetectStreamSizeData *sd = NULL; @@ -252,7 +251,7 @@ static int DetectStreamSizeParseTest01 (void) * invalid stream_size options. */ -static int DetectStreamSizeParseTest02 (void) +static int DetectStreamSizeParseTest02(void) { int result = 1; DetectStreamSizeData *sd = NULL; @@ -271,7 +270,7 @@ static int DetectStreamSizeParseTest02 (void) * packet correctly provided valid stream size. */ -static int DetectStreamSizeParseTest03 (void) +static int DetectStreamSizeParseTest03(void) { int result = 0; @@ -331,7 +330,7 @@ static int DetectStreamSizeParseTest03 (void) f.protoctx = &ssn; p->flow = &f; p->tcph = &tcph; - sm.ctx = (SigMatchCtx*)sd; + sm.ctx = (SigMatchCtx *)sd; result = DetectStreamSizeMatch(&dtx, p, &s, sm.ctx); if (result == 0) { @@ -347,7 +346,7 @@ static int DetectStreamSizeParseTest03 (void) * stream_size against invalid packet parameters. */ -static int DetectStreamSizeParseTest04 (void) +static int DetectStreamSizeParseTest04(void) { int result = 0; @@ -380,11 +379,10 @@ static int DetectStreamSizeParseTest04 (void) SCFree(p); return 0; } - } else - { + } else { SCFree(p); return 0; - } + } client.next_seq = 20; client.isn = 12; @@ -392,7 +390,7 @@ static int DetectStreamSizeParseTest04 (void) f.protoctx = &ssn; p->flow = &f; p->ip4h = &ip4h; - sm.ctx = (SigMatchCtx*)sd; + sm.ctx = (SigMatchCtx *)sd; if (!DetectStreamSizeMatch(&dtx, p, &s, sm.ctx)) result = 1; diff --git a/src/detect-stream_size.h b/src/detect-stream_size.h index 3a460bf5e28b..8a12d4e671cb 100644 --- a/src/detect-stream_size.h +++ b/src/detect-stream_size.h @@ -22,9 +22,8 @@ */ #ifndef _DETECT_STREAM_SIZE_H -#define _DETECT_STREAM_SIZE_H +#define _DETECT_STREAM_SIZE_H void DetectStreamSizeRegister(void); -#endif /* _DETECT_STREAM_SIZE_H */ - +#endif /* _DETECT_STREAM_SIZE_H */ diff --git a/src/detect-tag.c b/src/detect-tag.c index bab756b3b601..39216d9d3ebb 100644 --- a/src/detect-tag.c +++ b/src/detect-tag.c @@ -51,12 +51,14 @@ SC_ATOMIC_EXTERN(unsigned int, num_tags); /* format: tag: , , , [direction]; */ -#define PARSE_REGEX "^\\s*(host|session)\\s*(,\\s*(\\d+)\\s*,\\s*(packets|bytes|seconds)\\s*(,\\s*(src|dst))?\\s*)?$" +#define PARSE_REGEX \ + "^\\s*(host|session)\\s*(,\\s*(\\d+)\\s*,\\s*(packets|bytes|seconds)\\s*(,\\s*(src|dst))?\\s*" \ + ")?$" static DetectParseRegex parse_regex; -static int DetectTagMatch(DetectEngineThreadCtx *, Packet *, - const Signature *, const SigMatchCtx *); +static int DetectTagMatch( + DetectEngineThreadCtx *, Packet *, const Signature *, const SigMatchCtx *); static int DetectTagSetup(DetectEngineCtx *, Signature *, const char *); #ifdef UNITTESTS static void DetectTagRegisterTests(void); @@ -71,7 +73,7 @@ void DetectTagRegister(void) sigmatch_table[DETECT_TAG].name = "tag"; sigmatch_table[DETECT_TAG].Match = DetectTagMatch; sigmatch_table[DETECT_TAG].Setup = DetectTagSetup; - sigmatch_table[DETECT_TAG].Free = DetectTagDataFree; + sigmatch_table[DETECT_TAG].Free = DetectTagDataFree; #ifdef UNITTESTS sigmatch_table[DETECT_TAG].RegisterTests = DetectTagRegisterTests; #endif @@ -91,8 +93,8 @@ void DetectTagRegister(void) * \retval 0 no match * \retval 1 match */ -static int DetectTagMatch(DetectEngineThreadCtx *det_ctx, Packet *p, - const Signature *s, const SigMatchCtx *ctx) +static int DetectTagMatch( + DetectEngineThreadCtx *det_ctx, Packet *p, const Signature *s, const SigMatchCtx *ctx) { const DetectTagData *td = (const DetectTagData *)ctx; DetectTagDataEntry tde; @@ -114,7 +116,7 @@ static int DetectTagMatch(DetectEngineThreadCtx *det_ctx, Packet *p, else if (td->direction == DETECT_TAG_DIR_DST) tde.flags |= TAG_ENTRY_FLAG_DIR_DST; - SCLogDebug("Tagging Host with sid %"PRIu32":%"PRIu32"", s->id, s->gid); + SCLogDebug("Tagging Host with sid %" PRIu32 ":%" PRIu32 "", s->id, s->gid); TagHashAddTag(&tde, p); break; case DETECT_TAG_TYPE_SESSION: @@ -127,8 +129,8 @@ static int DetectTagMatch(DetectEngineThreadCtx *det_ctx, Packet *p, tde.metric = td->metric; tde.count = td->count; - SCLogDebug("Adding to or updating flow; first_ts %u count %u", - tde.first_ts, tde.count); + SCLogDebug("Adding to or updating flow; first_ts %u count %u", tde.first_ts, + tde.count); TagFlowAdd(p, &tde); } else { SCLogDebug("No flow to append the session tag"); @@ -197,8 +199,7 @@ static DetectTagData *DetectTagParse(const char *tagstr) } /* count */ - if (StringParseUint32(&td.count, 10, strlen(str_ptr), - str_ptr) <= 0) { + if (StringParseUint32(&td.count, 10, strlen(str_ptr), str_ptr) <= 0) { SCLogError("Invalid argument for count. Must be a value in the range of 0 to %" PRIu32 " (%s)", UINT32_MAX, tagstr); @@ -326,7 +327,6 @@ static void DetectTagDataEntryFree(void *ptr) } } - /** * \brief this function will free all the entries of a list * DetectTagDataEntry @@ -341,7 +341,7 @@ void DetectTagDataListFree(void *ptr) while (entry != NULL) { DetectTagDataEntry *next_entry = entry->next; DetectTagDataEntryFree(entry); - (void) SC_ATOMIC_SUB(num_tags, 1); + (void)SC_ATOMIC_SUB(num_tags, 1); entry = next_entry; } } @@ -369,9 +369,8 @@ static int DetectTagTestParse01(void) int result = 0; DetectTagData *td = NULL; td = DetectTagParse("session, 123, packets"); - if (td != NULL && td->type == DETECT_TAG_TYPE_SESSION - && td->count == 123 - && td->metric == DETECT_TAG_METRIC_PACKET) { + if (td != NULL && td->type == DETECT_TAG_TYPE_SESSION && td->count == 123 && + td->metric == DETECT_TAG_METRIC_PACKET) { DetectTagDataFree(NULL, td); result = 1; } @@ -387,11 +386,9 @@ static int DetectTagTestParse02(void) int result = 0; DetectTagData *td = NULL; td = DetectTagParse("host, 200, bytes, src"); - if (td != NULL && td->type == DETECT_TAG_TYPE_HOST - && td->count == 200 - && td->metric == DETECT_TAG_METRIC_BYTES - && td->direction == DETECT_TAG_DIR_SRC) { - result = 1; + if (td != NULL && td->type == DETECT_TAG_TYPE_HOST && td->count == 200 && + td->metric == DETECT_TAG_METRIC_BYTES && td->direction == DETECT_TAG_DIR_SRC) { + result = 1; DetectTagDataFree(NULL, td); } @@ -406,11 +403,9 @@ static int DetectTagTestParse03(void) int result = 0; DetectTagData *td = NULL; td = DetectTagParse("host, 200, bytes, dst"); - if (td != NULL && td->type == DETECT_TAG_TYPE_HOST - && td->count == 200 - && td->metric == DETECT_TAG_METRIC_BYTES - && td->direction == DETECT_TAG_DIR_DST) { - result = 1; + if (td != NULL && td->type == DETECT_TAG_TYPE_HOST && td->count == 200 && + td->metric == DETECT_TAG_METRIC_BYTES && td->direction == DETECT_TAG_DIR_DST) { + result = 1; DetectTagDataFree(NULL, td); } @@ -425,10 +420,9 @@ static int DetectTagTestParse04(void) int result = 0; DetectTagData *td = NULL; td = DetectTagParse("session"); - if (td != NULL && td->type == DETECT_TAG_TYPE_SESSION - && td->count == DETECT_TAG_MAX_PKTS - && td->metric == DETECT_TAG_METRIC_PACKET) { - result = 1; + if (td != NULL && td->type == DETECT_TAG_TYPE_SESSION && td->count == DETECT_TAG_MAX_PKTS && + td->metric == DETECT_TAG_METRIC_PACKET) { + result = 1; DetectTagDataFree(NULL, td); } @@ -443,11 +437,9 @@ static int DetectTagTestParse05(void) int result = 0; DetectTagData *td = NULL; td = DetectTagParse("host"); - if (td != NULL && td->type == DETECT_TAG_TYPE_HOST - && td->count == DETECT_TAG_MAX_PKTS - && td->metric == DETECT_TAG_METRIC_PACKET - && td->direction == DETECT_TAG_DIR_DST) { - result = 1; + if (td != NULL && td->type == DETECT_TAG_TYPE_HOST && td->count == DETECT_TAG_MAX_PKTS && + td->metric == DETECT_TAG_METRIC_PACKET && td->direction == DETECT_TAG_DIR_DST) { + result = 1; DetectTagDataFree(NULL, td); } diff --git a/src/detect-tag.h b/src/detect-tag.h index 0a03584b610c..8053e5a61d27 100644 --- a/src/detect-tag.h +++ b/src/detect-tag.h @@ -40,11 +40,7 @@ #define DETECT_TAG_MAX_PKTS 256 /* Type of tag: session or host */ -enum { - DETECT_TAG_TYPE_SESSION, - DETECT_TAG_TYPE_HOST, - DETECT_TAG_TYPE_MAX -}; +enum { DETECT_TAG_TYPE_SESSION, DETECT_TAG_TYPE_HOST, DETECT_TAG_TYPE_MAX }; enum { DETECT_TAG_DIR_SRC, @@ -59,44 +55,43 @@ enum { /** This will be the rule options/parameters */ typedef struct DetectTagData_ { - uint8_t type; /**< tag type */ - uint8_t direction; /**< host direction */ - uint32_t count; /**< count */ - uint8_t metric; /**< metric */ + uint8_t type; /**< tag type */ + uint8_t direction; /**< host direction */ + uint32_t count; /**< count */ + uint8_t metric; /**< metric */ } DetectTagData; /** This is the installed data at the session/global or host table */ typedef struct DetectTagDataEntry_ { - uint8_t flags:3; - uint8_t metric:5; + uint8_t flags : 3; + uint8_t metric : 5; uint8_t pad0; - uint16_t cnt_match; /**< number of times this tag was reset/updated */ + uint16_t cnt_match; /**< number of times this tag was reset/updated */ - uint32_t count; /**< count setting from rule */ - uint32_t sid; /**< sid originating the tag */ - uint32_t gid; /**< gid originating the tag */ + uint32_t count; /**< count setting from rule */ + uint32_t sid; /**< sid originating the tag */ + uint32_t gid; /**< gid originating the tag */ union { - uint32_t packets; /**< number of packets (metric packets) */ - uint32_t bytes; /**< number of bytes (metric bytes) */ + uint32_t packets; /**< number of packets (metric packets) */ + uint32_t bytes; /**< number of bytes (metric bytes) */ }; - uint32_t first_ts; /**< First time seen (for metric = seconds) */ - uint32_t last_ts; /**< Last time seen (to prune old sessions) */ + uint32_t first_ts; /**< First time seen (for metric = seconds) */ + uint32_t last_ts; /**< Last time seen (to prune old sessions) */ #if __WORDSIZE == 64 uint32_t pad1; #endif - struct DetectTagDataEntry_ *next; /**< Pointer to the next tag of this - * session/src_host/dst_host (if any from other rule) */ + struct DetectTagDataEntry_ *next; /**< Pointer to the next tag of this + * session/src_host/dst_host (if any from other rule) */ } DetectTagDataEntry; -#define TAG_ENTRY_FLAG_DIR_SRC 0x01 -#define TAG_ENTRY_FLAG_DIR_DST 0x02 -#define TAG_ENTRY_FLAG_SKIPPED_FIRST 0x04 +#define TAG_ENTRY_FLAG_DIR_SRC 0x01 +#define TAG_ENTRY_FLAG_DIR_DST 0x02 +#define TAG_ENTRY_FLAG_SKIPPED_FIRST 0x04 /* prototypes */ -struct DetectEngineCtx_ ; +struct DetectEngineCtx_; void DetectTagRegister(void); void DetectTagDataFree(struct DetectEngineCtx_ *, void *ptr); void DetectTagDataListFree(void *ptr); #endif /* __DETECT_TAG_H__ */ - diff --git a/src/detect-target.c b/src/detect-target.c index b34b6e0d7066..b23edc9bf9df 100644 --- a/src/detect-target.c +++ b/src/detect-target.c @@ -34,27 +34,29 @@ /** * \brief Regex for parsing our keyword options */ -#define PARSE_REGEX "^\\s*(src_ip|dest_ip)\\s*$" +#define PARSE_REGEX "^\\s*(src_ip|dest_ip)\\s*$" static DetectParseRegex parse_regex; /* Prototypes of functions registered in DetectTargetRegister below */ -static int DetectTargetSetup (DetectEngineCtx *, Signature *, const char *); +static int DetectTargetSetup(DetectEngineCtx *, Signature *, const char *); #ifdef UNITTESTS -static void DetectTargetRegisterTests (void); +static void DetectTargetRegisterTests(void); #endif /** * \brief Registration function for target keyword * */ -void DetectTargetRegister(void) { +void DetectTargetRegister(void) +{ /* keyword name: this is how the keyword is used in a rule */ sigmatch_table[DETECT_TARGET].name = "target"; /* description: listed in "suricata --list-keywords=all" */ - sigmatch_table[DETECT_TARGET].desc = "indicate to output module which side is the target of the attack"; + sigmatch_table[DETECT_TARGET].desc = + "indicate to output module which side is the target of the attack"; /* link to further documentation of the keyword. Normally on the Suricata redmine/wiki */ - sigmatch_table[DETECT_TARGET].url = "/rules/meta.html#target"; + sigmatch_table[DETECT_TARGET].url = "/rules/meta.html#target"; /* match function is called when the signature is inspected on a packet */ sigmatch_table[DETECT_TARGET].Match = NULL; /* setup function is called during signature parsing, when the target @@ -152,7 +154,8 @@ static int DetectTargetSignatureTest01(void) DetectEngineCtx *de_ctx = DetectEngineCtxInit(); FAIL_IF_NULL(de_ctx); - Signature *sig = DetectEngineAppendSig(de_ctx, "alert ip any any -> any any (target: dest_ip; sid:1; rev:1;)"); + Signature *sig = DetectEngineAppendSig( + de_ctx, "alert ip any any -> any any (target: dest_ip; sid:1; rev:1;)"); FAIL_IF_NULL(sig); DetectEngineCtxFree(de_ctx); @@ -164,7 +167,6 @@ static int DetectTargetSignatureTest01(void) */ static void DetectTargetRegisterTests(void) { - UtRegisterTest("DetectTargetSignatureTest01", - DetectTargetSignatureTest01); + UtRegisterTest("DetectTargetSignatureTest01", DetectTargetSignatureTest01); } #endif /* UNITTESTS */ diff --git a/src/detect-tcp-ack.c b/src/detect-tcp-ack.c index b2e35ca813d2..b7d33086cacc 100644 --- a/src/detect-tcp-ack.c +++ b/src/detect-tcp-ack.c @@ -44,8 +44,8 @@ /* prototypes */ static int DetectAckSetup(DetectEngineCtx *, Signature *, const char *); -static int DetectAckMatch(DetectEngineThreadCtx *, - Packet *, const Signature *, const SigMatchCtx *); +static int DetectAckMatch( + DetectEngineThreadCtx *, Packet *, const Signature *, const SigMatchCtx *); #ifdef UNITTESTS static void DetectAckRegisterTests(void); #endif @@ -82,8 +82,8 @@ void DetectAckRegister(void) * \retval 0 no match * \retval 1 match */ -static int DetectAckMatch(DetectEngineThreadCtx *det_ctx, - Packet *p, const Signature *s, const SigMatchCtx *ctx) +static int DetectAckMatch( + DetectEngineThreadCtx *det_ctx, Packet *p, const Signature *s, const SigMatchCtx *ctx) { const DetectAckData *data = (const DetectAckData *)ctx; @@ -131,7 +131,6 @@ static int DetectAckSetup(DetectEngineCtx *de_ctx, Signature *s, const char *opt if (data) SCFree(data); return -1; - } /** @@ -148,31 +147,27 @@ static void DetectAckFree(DetectEngineCtx *de_ctx, void *ptr) /* prefilter code */ -static void -PrefilterPacketAckMatch(DetectEngineThreadCtx *det_ctx, Packet *p, const void *pectx) +static void PrefilterPacketAckMatch(DetectEngineThreadCtx *det_ctx, Packet *p, const void *pectx) { const PrefilterPacketHeaderCtx *ctx = pectx; if (!PrefilterPacketHeaderExtraMatch(ctx, p)) return; - if ((p->proto) == IPPROTO_TCP && !(PKT_IS_PSEUDOPKT(p)) && - (p->tcph != NULL) && (TCP_GET_ACK(p) == ctx->v1.u32[0])) - { + if ((p->proto) == IPPROTO_TCP && !(PKT_IS_PSEUDOPKT(p)) && (p->tcph != NULL) && + (TCP_GET_ACK(p) == ctx->v1.u32[0])) { SCLogDebug("packet matches TCP ack %u", ctx->v1.u32[0]); PrefilterAddSids(&det_ctx->pmq, ctx->sigs_array, ctx->sigs_cnt); } } -static void -PrefilterPacketAckSet(PrefilterPacketHeaderValue *v, void *smctx) +static void PrefilterPacketAckSet(PrefilterPacketHeaderValue *v, void *smctx) { const DetectAckData *a = smctx; v->u32[0] = a->ack; } -static bool -PrefilterPacketAckCompare(PrefilterPacketHeaderValue v, void *smctx) +static bool PrefilterPacketAckCompare(PrefilterPacketHeaderValue v, void *smctx) { const DetectAckData *a = smctx; if (v.u32[0] == a->ack) @@ -182,16 +177,14 @@ PrefilterPacketAckCompare(PrefilterPacketHeaderValue v, void *smctx) static int PrefilterSetupTcpAck(DetectEngineCtx *de_ctx, SigGroupHead *sgh) { - return PrefilterSetupPacketHeader(de_ctx, sgh, DETECT_ACK, - PrefilterPacketAckSet, - PrefilterPacketAckCompare, - PrefilterPacketAckMatch); + return PrefilterSetupPacketHeader(de_ctx, sgh, DETECT_ACK, PrefilterPacketAckSet, + PrefilterPacketAckCompare, PrefilterPacketAckMatch); } static bool PrefilterTcpAckIsPrefilterable(const Signature *s) { const SigMatch *sm; - for (sm = s->init_data->smlists[DETECT_SM_LIST_MATCH] ; sm != NULL; sm = sm->next) { + for (sm = s->init_data->smlists[DETECT_SM_LIST_MATCH]; sm != NULL; sm = sm->next) { switch (sm->type) { case DETECT_ACK: return true; @@ -236,38 +229,30 @@ static int DetectAckSigTest01(void) de_ctx->flags |= DE_QUIET; /* These three are crammed in here as there is no Parse */ - if (SigInit(de_ctx, - "alert tcp any any -> any any " - "(msg:\"Testing ack\";ack:foo;sid:1;)") != NULL) - { + if (SigInit(de_ctx, "alert tcp any any -> any any " + "(msg:\"Testing ack\";ack:foo;sid:1;)") != NULL) { printf("invalid ack accepted: "); goto cleanup_engine; } - if (SigInit(de_ctx, - "alert tcp any any -> any any " - "(msg:\"Testing ack\";ack:9999999999;sid:1;)") != NULL) - { + if (SigInit(de_ctx, "alert tcp any any -> any any " + "(msg:\"Testing ack\";ack:9999999999;sid:1;)") != NULL) { printf("overflowing ack accepted: "); goto cleanup_engine; } - if (SigInit(de_ctx, - "alert tcp any any -> any any " - "(msg:\"Testing ack\";ack:-100;sid:1;)") != NULL) - { + if (SigInit(de_ctx, "alert tcp any any -> any any " + "(msg:\"Testing ack\";ack:-100;sid:1;)") != NULL) { printf("negative ack accepted: "); goto cleanup_engine; } - de_ctx->sig_list = SigInit(de_ctx, - "alert tcp any any -> any any " - "(msg:\"Testing ack\";ack:41;sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " + "(msg:\"Testing ack\";ack:41;sid:1;)"); if (de_ctx->sig_list == NULL) { goto cleanup_engine; } - de_ctx->sig_list->next = SigInit(de_ctx, - "alert tcp any any -> any any " - "(msg:\"Testing ack\";ack:42;sid:2;)"); + de_ctx->sig_list->next = SigInit(de_ctx, "alert tcp any any -> any any " + "(msg:\"Testing ack\";ack:42;sid:2;)"); if (de_ctx->sig_list->next == NULL) { goto cleanup_engine; } diff --git a/src/detect-tcp-ack.h b/src/detect-tcp-ack.h index e1bb7c710c77..24a23517bca0 100644 --- a/src/detect-tcp-ack.h +++ b/src/detect-tcp-ack.h @@ -28,7 +28,7 @@ * \brief ack data */ typedef struct DetectAckData_ { - uint32_t ack; /**< ack to match */ + uint32_t ack; /**< ack to match */ } DetectAckData; /** diff --git a/src/detect-tcp-flags.c b/src/detect-tcp-flags.c index 5809a5dce983..c9f1c5658c41 100644 --- a/src/detect-tcp-flags.c +++ b/src/detect-tcp-flags.c @@ -44,7 +44,8 @@ * Regex (by Brian Rectanus) * flags: [!+*](SAPRFU120)[,SAPRFU12] */ -#define PARSE_REGEX "^\\s*(?:([\\+\\*!]))?\\s*([SAPRFU120CE\\+\\*!]+)(?:\\s*,\\s*([SAPRFU12CE]+))?\\s*$" +#define PARSE_REGEX \ + "^\\s*(?:([\\+\\*!]))?\\s*([SAPRFU120CE\\+\\*!]+)(?:\\s*,\\s*([SAPRFU12CE]+))?\\s*$" /** * Flags args[0] *(3) +(2) !(1) @@ -57,9 +58,9 @@ static DetectParseRegex parse_regex; -static int DetectFlagsMatch (DetectEngineThreadCtx *, Packet *, - const Signature *, const SigMatchCtx *); -static int DetectFlagsSetup (DetectEngineCtx *, Signature *, const char *); +static int DetectFlagsMatch( + DetectEngineThreadCtx *, Packet *, const Signature *, const SigMatchCtx *); +static int DetectFlagsSetup(DetectEngineCtx *, Signature *, const char *); static void DetectFlagsFree(DetectEngineCtx *, void *); static bool PrefilterTcpFlagsIsPrefilterable(const Signature *s); @@ -72,7 +73,7 @@ static void FlagsRegisterTests(void); * \brief Registration function for flags: keyword */ -void DetectFlagsRegister (void) +void DetectFlagsRegister(void) { sigmatch_table[DETECT_FLAGS].name = "tcp.flags"; sigmatch_table[DETECT_FLAGS].alias = "flags"; @@ -80,7 +81,7 @@ void DetectFlagsRegister (void) sigmatch_table[DETECT_FLAGS].url = "/rules/header-keywords.html#tcp-flags"; sigmatch_table[DETECT_FLAGS].Match = DetectFlagsMatch; sigmatch_table[DETECT_FLAGS].Setup = DetectFlagsSetup; - sigmatch_table[DETECT_FLAGS].Free = DetectFlagsFree; + sigmatch_table[DETECT_FLAGS].Free = DetectFlagsFree; #ifdef UNITTESTS sigmatch_table[DETECT_FLAGS].RegisterTests = FlagsRegisterTests; #endif @@ -90,11 +91,11 @@ void DetectFlagsRegister (void) DetectSetupParseRegexes(PARSE_REGEX, &parse_regex); } -static inline int FlagsMatch(const uint8_t pflags, const uint8_t modifier, - const uint8_t dflags, const uint8_t iflags) +static inline int FlagsMatch( + const uint8_t pflags, const uint8_t modifier, const uint8_t dflags, const uint8_t iflags) { if (!dflags && pflags) { - if(modifier == MODIFIER_NOT) { + if (modifier == MODIFIER_NOT) { SCReturnInt(1); } @@ -123,7 +124,7 @@ static inline int FlagsMatch(const uint8_t pflags, const uint8_t modifier, SCReturnInt(0); default: - SCLogDebug("flags %"PRIu8" and de->flags %"PRIu8"", flags, dflags); + SCLogDebug("flags %" PRIu8 " and de->flags %" PRIu8 "", flags, dflags); if (flags == dflags) { SCReturnInt(1); } @@ -145,8 +146,8 @@ static inline int FlagsMatch(const uint8_t pflags, const uint8_t modifier, * \retval 0 no match * \retval 1 match */ -static int DetectFlagsMatch (DetectEngineThreadCtx *det_ctx, Packet *p, - const Signature *s, const SigMatchCtx *ctx) +static int DetectFlagsMatch( + DetectEngineThreadCtx *det_ctx, Packet *p, const Signature *s, const SigMatchCtx *ctx) { SCEnter(); @@ -169,7 +170,7 @@ static int DetectFlagsMatch (DetectEngineThreadCtx *det_ctx, Packet *p, * \retval de pointer to DetectFlagsData on success * \retval NULL on failure */ -static DetectFlagsData *DetectFlagsParse (const char *rawstr) +static DetectFlagsData *DetectFlagsParse(const char *rawstr) { SCEnter(); @@ -451,7 +452,7 @@ static DetectFlagsData *DetectFlagsParse (const char *rawstr) } pcre2_match_data_free(match); - SCLogDebug("found %"PRId32" ignore %"PRId32"", found, ignore); + SCLogDebug("found %" PRId32 " ignore %" PRId32 "", found, ignore); SCReturnPtr(de, "DetectFlagsData"); error: @@ -476,7 +477,7 @@ static DetectFlagsData *DetectFlagsParse (const char *rawstr) * \retval 0 on Success * \retval -1 on Failure */ -static int DetectFlagsSetup (DetectEngineCtx *de_ctx, Signature *s, const char *rawstr) +static int DetectFlagsSetup(DetectEngineCtx *de_ctx, Signature *s, const char *rawstr) { DetectFlagsData *de = NULL; @@ -507,16 +508,16 @@ static int DetectFlagsSetup (DetectEngineCtx *de_ctx, Signature *s, const char * static void DetectFlagsFree(DetectEngineCtx *de_ctx, void *de_ptr) { DetectFlagsData *de = (DetectFlagsData *)de_ptr; - if(de) SCFree(de); + if (de) + SCFree(de); } int DetectFlagsSignatureNeedsSynPackets(const Signature *s) { const SigMatch *sm; - for (sm = s->init_data->smlists[DETECT_SM_LIST_MATCH] ; sm != NULL; sm = sm->next) { + for (sm = s->init_data->smlists[DETECT_SM_LIST_MATCH]; sm != NULL; sm = sm->next) { switch (sm->type) { - case DETECT_FLAGS: - { + case DETECT_FLAGS: { const DetectFlagsData *fl = (const DetectFlagsData *)sm->ctx; if (!(fl->modifier == MODIFIER_NOT) && (fl->flags & TH_SYN)) { @@ -532,10 +533,9 @@ int DetectFlagsSignatureNeedsSynPackets(const Signature *s) int DetectFlagsSignatureNeedsSynOnlyPackets(const Signature *s) { const SigMatch *sm; - for (sm = s->init_data->smlists[DETECT_SM_LIST_MATCH] ; sm != NULL; sm = sm->next) { + for (sm = s->init_data->smlists[DETECT_SM_LIST_MATCH]; sm != NULL; sm = sm->next) { switch (sm->type) { - case DETECT_FLAGS: - { + case DETECT_FLAGS: { const DetectFlagsData *fl = (const DetectFlagsData *)sm->ctx; if (!(fl->modifier == MODIFIER_NOT) && (fl->flags == TH_SYN)) { @@ -548,8 +548,7 @@ int DetectFlagsSignatureNeedsSynOnlyPackets(const Signature *s) return 0; } -static void -PrefilterPacketFlagsMatch(DetectEngineThreadCtx *det_ctx, Packet *p, const void *pectx) +static void PrefilterPacketFlagsMatch(DetectEngineThreadCtx *det_ctx, Packet *p, const void *pectx) { if (!(PKT_IS_TCP(p)) || PKT_IS_PSEUDOPKT(p)) { SCReturn; @@ -560,15 +559,13 @@ PrefilterPacketFlagsMatch(DetectEngineThreadCtx *det_ctx, Packet *p, const void return; const uint8_t flags = p->tcph->th_flags; - if (FlagsMatch(flags, ctx->v1.u8[0], ctx->v1.u8[1], ctx->v1.u8[2])) - { + if (FlagsMatch(flags, ctx->v1.u8[0], ctx->v1.u8[1], ctx->v1.u8[2])) { SCLogDebug("packet matches TCP flags %02x", ctx->v1.u8[1]); PrefilterAddSids(&det_ctx->pmq, ctx->sigs_array, ctx->sigs_cnt); } } -static void -PrefilterPacketFlagsSet(PrefilterPacketHeaderValue *v, void *smctx) +static void PrefilterPacketFlagsSet(PrefilterPacketHeaderValue *v, void *smctx) { const DetectFlagsData *a = smctx; v->u8[0] = a->modifier; @@ -577,30 +574,24 @@ PrefilterPacketFlagsSet(PrefilterPacketHeaderValue *v, void *smctx) SCLogDebug("v->u8[0] = %02x", v->u8[0]); } -static bool -PrefilterPacketFlagsCompare(PrefilterPacketHeaderValue v, void *smctx) +static bool PrefilterPacketFlagsCompare(PrefilterPacketHeaderValue v, void *smctx) { const DetectFlagsData *a = smctx; - if (v.u8[0] == a->modifier && - v.u8[1] == a->flags && - v.u8[2] == a->ignored_flags) + if (v.u8[0] == a->modifier && v.u8[1] == a->flags && v.u8[2] == a->ignored_flags) return true; return false; } static int PrefilterSetupTcpFlags(DetectEngineCtx *de_ctx, SigGroupHead *sgh) { - return PrefilterSetupPacketHeader(de_ctx, sgh, DETECT_FLAGS, - PrefilterPacketFlagsSet, - PrefilterPacketFlagsCompare, - PrefilterPacketFlagsMatch); - + return PrefilterSetupPacketHeader(de_ctx, sgh, DETECT_FLAGS, PrefilterPacketFlagsSet, + PrefilterPacketFlagsCompare, PrefilterPacketFlagsMatch); } static bool PrefilterTcpFlagsIsPrefilterable(const Signature *s) { const SigMatch *sm; - for (sm = s->init_data->smlists[DETECT_SM_LIST_MATCH] ; sm != NULL; sm = sm->next) { + for (sm = s->init_data->smlists[DETECT_SM_LIST_MATCH]; sm != NULL; sm = sm->next) { switch (sm->type) { case DETECT_FLAGS: return true; @@ -620,7 +611,7 @@ static bool PrefilterTcpFlagsIsPrefilterable(const Signature *s) * \retval 1 on success * \retval 0 on failure */ -static int FlagsTestParse01 (void) +static int FlagsTestParse01(void) { DetectFlagsData *de = DetectFlagsParse("S"); FAIL_IF_NULL(de); @@ -635,7 +626,7 @@ static int FlagsTestParse01 (void) * \retval 1 on success * \retval 0 on failure */ -static int FlagsTestParse02 (void) +static int FlagsTestParse02(void) { DetectFlagsData *de = NULL; de = DetectFlagsParse("G"); @@ -653,7 +644,7 @@ static int FlagsTestParse02 (void) * \retval 1 on success * \retval 0 on failure */ -static int FlagsTestParse03 (void) +static int FlagsTestParse03(void) { Packet *p = PacketGetFromAlloc(); if (unlikely(p == NULL)) @@ -671,11 +662,11 @@ static int FlagsTestParse03 (void) p->ip4h = &ipv4h; p->tcph = &tcph; - p->tcph->th_flags = TH_ACK|TH_PUSH|TH_SYN|TH_RST; + p->tcph->th_flags = TH_ACK | TH_PUSH | TH_SYN | TH_RST; de = DetectFlagsParse("AP+"); - if (de == NULL || (de->flags != (TH_ACK|TH_PUSH)) ) + if (de == NULL || (de->flags != (TH_ACK | TH_PUSH))) goto error; sm = SigMatchAlloc(); @@ -687,16 +678,20 @@ static int FlagsTestParse03 (void) ret = DetectFlagsMatch(NULL, p, NULL, sm->ctx); - if(ret) { - if (de) SCFree(de); - if (sm) SCFree(sm); + if (ret) { + if (de) + SCFree(de); + if (sm) + SCFree(sm); SCFree(p); return 1; } error: - if (de) SCFree(de); - if (sm) SCFree(sm); + if (de) + SCFree(de); + if (sm) + SCFree(sm); SCFree(p); return 0; } @@ -707,7 +702,7 @@ static int FlagsTestParse03 (void) * \retval 1 on success * \retval 0 on failure */ -static int FlagsTestParse04 (void) +static int FlagsTestParse04(void) { Packet *p = PacketGetFromAlloc(); if (unlikely(p == NULL)) @@ -741,17 +736,21 @@ static int FlagsTestParse04 (void) ret = DetectFlagsMatch(NULL, p, NULL, sm->ctx); - if(ret) { - if (de) SCFree(de); - if (sm) SCFree(sm); + if (ret) { + if (de) + SCFree(de); + if (sm) + SCFree(sm); SCFree(p); return 0; } /* Error expected. */ error: - if (de) SCFree(de); - if (sm) SCFree(sm); + if (de) + SCFree(de); + if (sm) + SCFree(sm); SCFree(p); return 1; } @@ -762,7 +761,7 @@ static int FlagsTestParse04 (void) * \retval 1 on success * \retval 0 on failure */ -static int FlagsTestParse05 (void) +static int FlagsTestParse05(void) { Packet *p = PacketGetFromAlloc(); if (unlikely(p == NULL)) @@ -780,11 +779,12 @@ static int FlagsTestParse05 (void) p->ip4h = &ipv4h; p->tcph = &tcph; - p->tcph->th_flags = TH_ACK|TH_PUSH|TH_SYN|TH_RST; + p->tcph->th_flags = TH_ACK | TH_PUSH | TH_SYN | TH_RST; de = DetectFlagsParse("+AP,SR"); - if (de == NULL || (de->modifier != MODIFIER_PLUS) || (de->flags != (TH_ACK|TH_PUSH)) || (de->ignored_flags != (TH_SYN|TH_RST))) + if (de == NULL || (de->modifier != MODIFIER_PLUS) || (de->flags != (TH_ACK | TH_PUSH)) || + (de->ignored_flags != (TH_SYN | TH_RST))) goto error; sm = SigMatchAlloc(); @@ -796,17 +796,21 @@ static int FlagsTestParse05 (void) ret = DetectFlagsMatch(NULL, p, NULL, sm->ctx); - if(ret) { - if (de) SCFree(de); - if (sm) SCFree(sm); + if (ret) { + if (de) + SCFree(de); + if (sm) + SCFree(sm); SCFree(p); return 0; } /* Error expected. */ error: - if (de) SCFree(de); - if (sm) SCFree(sm); + if (de) + SCFree(de); + if (sm) + SCFree(sm); SCFree(p); return 1; } @@ -817,7 +821,7 @@ static int FlagsTestParse05 (void) * \retval 1 on success * \retval 0 on failure */ -static int FlagsTestParse06 (void) +static int FlagsTestParse06(void) { Packet *p = PacketGetFromAlloc(); if (unlikely(p == NULL)) @@ -835,11 +839,12 @@ static int FlagsTestParse06 (void) p->ip4h = &ipv4h; p->tcph = &tcph; - p->tcph->th_flags = TH_ACK|TH_PUSH|TH_SYN|TH_RST; + p->tcph->th_flags = TH_ACK | TH_PUSH | TH_SYN | TH_RST; de = DetectFlagsParse("+AP,UR"); - if (de == NULL || (de->modifier != MODIFIER_PLUS) || (de->flags != (TH_ACK|TH_PUSH)) || ((0xff - de->ignored_flags) != (TH_URG|TH_RST))) + if (de == NULL || (de->modifier != MODIFIER_PLUS) || (de->flags != (TH_ACK | TH_PUSH)) || + ((0xff - de->ignored_flags) != (TH_URG | TH_RST))) goto error; sm = SigMatchAlloc(); @@ -851,16 +856,20 @@ static int FlagsTestParse06 (void) ret = DetectFlagsMatch(NULL, p, NULL, sm->ctx); - if(ret) { - if (de) SCFree(de); - if (sm) SCFree(sm); + if (ret) { + if (de) + SCFree(de); + if (sm) + SCFree(sm); SCFree(p); return 1; } error: - if (de) SCFree(de); - if (sm) SCFree(sm); + if (de) + SCFree(de); + if (sm) + SCFree(sm); SCFree(p); return 0; } @@ -871,7 +880,7 @@ static int FlagsTestParse06 (void) * \retval 1 on success * \retval 0 on failure */ -static int FlagsTestParse07 (void) +static int FlagsTestParse07(void) { Packet *p = PacketGetFromAlloc(); if (unlikely(p == NULL)) @@ -889,11 +898,11 @@ static int FlagsTestParse07 (void) p->ip4h = &ipv4h; p->tcph = &tcph; - p->tcph->th_flags = TH_SYN|TH_RST; + p->tcph->th_flags = TH_SYN | TH_RST; de = DetectFlagsParse("*AP"); - if (de == NULL || (de->modifier != MODIFIER_ANY) || (de->flags != (TH_ACK|TH_PUSH))) + if (de == NULL || (de->modifier != MODIFIER_ANY) || (de->flags != (TH_ACK | TH_PUSH))) goto error; sm = SigMatchAlloc(); @@ -905,17 +914,21 @@ static int FlagsTestParse07 (void) ret = DetectFlagsMatch(NULL, p, NULL, sm->ctx); - if(ret) { - if (de) SCFree(de); - if (sm) SCFree(sm); + if (ret) { + if (de) + SCFree(de); + if (sm) + SCFree(sm); SCFree(p); return 0; } /* Error expected. */ error: - if (de) SCFree(de); - if (sm) SCFree(sm); + if (de) + SCFree(de); + if (sm) + SCFree(sm); SCFree(p); return 1; } @@ -926,7 +939,7 @@ static int FlagsTestParse07 (void) * \retval 1 on success * \retval 0 on failure */ -static int FlagsTestParse08 (void) +static int FlagsTestParse08(void) { Packet *p = PacketGetFromAlloc(); if (unlikely(p == NULL)) @@ -944,11 +957,11 @@ static int FlagsTestParse08 (void) p->ip4h = &ipv4h; p->tcph = &tcph; - p->tcph->th_flags = TH_SYN|TH_RST; + p->tcph->th_flags = TH_SYN | TH_RST; de = DetectFlagsParse("*SA"); - if (de == NULL || (de->modifier != MODIFIER_ANY) || (de->flags != (TH_ACK|TH_SYN))) + if (de == NULL || (de->modifier != MODIFIER_ANY) || (de->flags != (TH_ACK | TH_SYN))) goto error; sm = SigMatchAlloc(); @@ -960,16 +973,20 @@ static int FlagsTestParse08 (void) ret = DetectFlagsMatch(NULL, p, NULL, sm->ctx); - if(ret) { - if (de) SCFree(de); - if (sm) SCFree(sm); + if (ret) { + if (de) + SCFree(de); + if (sm) + SCFree(sm); SCFree(p); return 1; } error: - if (de) SCFree(de); - if (sm) SCFree(sm); + if (de) + SCFree(de); + if (sm) + SCFree(sm); SCFree(p); return 0; } @@ -980,7 +997,7 @@ static int FlagsTestParse08 (void) * \retval 1 on success * \retval 0 on failure */ -static int FlagsTestParse09 (void) +static int FlagsTestParse09(void) { Packet *p = PacketGetFromAlloc(); if (unlikely(p == NULL)) @@ -998,11 +1015,11 @@ static int FlagsTestParse09 (void) p->ip4h = &ipv4h; p->tcph = &tcph; - p->tcph->th_flags = TH_SYN|TH_RST; + p->tcph->th_flags = TH_SYN | TH_RST; de = DetectFlagsParse("!PA"); - if (de == NULL || (de->modifier != MODIFIER_NOT) || (de->flags != (TH_ACK|TH_PUSH))) + if (de == NULL || (de->modifier != MODIFIER_NOT) || (de->flags != (TH_ACK | TH_PUSH))) goto error; sm = SigMatchAlloc(); @@ -1014,16 +1031,20 @@ static int FlagsTestParse09 (void) ret = DetectFlagsMatch(NULL, p, NULL, sm->ctx); - if(ret) { - if (de) SCFree(de); - if (sm) SCFree(sm); + if (ret) { + if (de) + SCFree(de); + if (sm) + SCFree(sm); SCFree(p); return 1; } error: - if (de) SCFree(de); - if (sm) SCFree(sm); + if (de) + SCFree(de); + if (sm) + SCFree(sm); SCFree(p); return 0; } @@ -1034,7 +1055,7 @@ static int FlagsTestParse09 (void) * \retval 1 on success * \retval 0 on failure */ -static int FlagsTestParse10 (void) +static int FlagsTestParse10(void) { Packet *p = PacketGetFromAlloc(); if (unlikely(p == NULL)) @@ -1052,11 +1073,11 @@ static int FlagsTestParse10 (void) p->ip4h = &ipv4h; p->tcph = &tcph; - p->tcph->th_flags = TH_SYN|TH_RST; + p->tcph->th_flags = TH_SYN | TH_RST; de = DetectFlagsParse("!AP"); - if (de == NULL || (de->modifier != MODIFIER_NOT) || (de->flags != (TH_ACK|TH_PUSH))) + if (de == NULL || (de->modifier != MODIFIER_NOT) || (de->flags != (TH_ACK | TH_PUSH))) goto error; sm = SigMatchAlloc(); @@ -1068,16 +1089,20 @@ static int FlagsTestParse10 (void) ret = DetectFlagsMatch(NULL, p, NULL, sm->ctx); - if(ret) { - if (de) SCFree(de); - if (sm) SCFree(sm); + if (ret) { + if (de) + SCFree(de); + if (sm) + SCFree(sm); SCFree(p); return 1; } error: - if (de) SCFree(de); - if (sm) SCFree(sm); + if (de) + SCFree(de); + if (sm) + SCFree(sm); SCFree(p); return 0; } @@ -1088,7 +1113,7 @@ static int FlagsTestParse10 (void) * \retval 1 on success * \retval 0 on failure */ -static int FlagsTestParse11 (void) +static int FlagsTestParse11(void) { Packet *p = PacketGetFromAlloc(); if (unlikely(p == NULL)) @@ -1106,11 +1131,12 @@ static int FlagsTestParse11 (void) p->ip4h = &ipv4h; p->tcph = &tcph; - p->tcph->th_flags = TH_SYN|TH_RST|TH_URG; + p->tcph->th_flags = TH_SYN | TH_RST | TH_URG; de = DetectFlagsParse("*AP,SR"); - if (de == NULL || (de->modifier != MODIFIER_ANY) || (de->flags != (TH_ACK|TH_PUSH)) || ((0xff - de->ignored_flags) != (TH_SYN|TH_RST))) + if (de == NULL || (de->modifier != MODIFIER_ANY) || (de->flags != (TH_ACK | TH_PUSH)) || + ((0xff - de->ignored_flags) != (TH_SYN | TH_RST))) goto error; sm = SigMatchAlloc(); @@ -1122,17 +1148,21 @@ static int FlagsTestParse11 (void) ret = DetectFlagsMatch(NULL, p, NULL, sm->ctx); - if(ret) { - if (de) SCFree(de); - if (sm) SCFree(sm); + if (ret) { + if (de) + SCFree(de); + if (sm) + SCFree(sm); SCFree(p); return 0; } /* Expected. */ error: - if (de) SCFree(de); - if (sm) SCFree(sm); + if (de) + SCFree(de); + if (sm) + SCFree(sm); SCFree(p); return 1; } @@ -1143,7 +1173,7 @@ static int FlagsTestParse11 (void) * \retval 1 on success * \retval 0 on failure */ -static int FlagsTestParse12 (void) +static int FlagsTestParse12(void) { Packet *p = PacketGetFromAlloc(); if (unlikely(p == NULL)) @@ -1179,17 +1209,21 @@ static int FlagsTestParse12 (void) ret = DetectFlagsMatch(NULL, p, NULL, sm->ctx); - if(ret) { - if (de) SCFree(de); - if (sm) SCFree(sm); + if (ret) { + if (de) + SCFree(de); + if (sm) + SCFree(sm); SCFree(p); return 0; } /* Expected. */ error: - if (de) SCFree(de); - if (sm) SCFree(sm); + if (de) + SCFree(de); + if (sm) + SCFree(sm); SCFree(p); return 1; } @@ -1200,7 +1234,7 @@ static int FlagsTestParse12 (void) * \retval 1 on success * \retval 0 on failure */ -static int FlagsTestParse13 (void) +static int FlagsTestParse13(void) { DetectFlagsData *de = NULL; de = DetectFlagsParse("+S*"); @@ -1221,7 +1255,7 @@ static int FlagsTestParse13 (void) static int FlagsTestParse14(void) { DetectFlagsData *de = DetectFlagsParse("CE"); - if (de != NULL && (de->flags == (TH_CWR | TH_ECN)) ) { + if (de != NULL && (de->flags == (TH_CWR | TH_ECN))) { DetectFlagsFree(NULL, de); return 1; } @@ -1251,7 +1285,7 @@ static int FlagsTestParse15(void) de = DetectFlagsParse("EC+"); - if (de == NULL || (de->flags != (TH_ECN | TH_CWR)) ) + if (de == NULL || (de->flags != (TH_ECN | TH_CWR))) goto error; sm = SigMatchAlloc(); @@ -1303,7 +1337,7 @@ static int FlagsTestParse16(void) de = DetectFlagsParse("EC*"); - if (de == NULL || (de->flags != (TH_ECN | TH_CWR)) ) + if (de == NULL || (de->flags != (TH_ECN | TH_CWR))) goto error; sm = SigMatchAlloc(); @@ -1358,7 +1392,7 @@ static int FlagsTestParse17(void) de = DetectFlagsParse("EC+"); - if (de == NULL || (de->flags != (TH_ECN | TH_CWR)) ) + if (de == NULL || (de->flags != (TH_ECN | TH_CWR))) goto error; sm = SigMatchAlloc(); diff --git a/src/detect-tcp-flags.h b/src/detect-tcp-flags.h index e5920b9c5555..585244d4d184 100644 --- a/src/detect-tcp-flags.h +++ b/src/detect-tcp-flags.h @@ -24,7 +24,6 @@ #ifndef __DETECT_FLAGS_H__ #define __DETECT_FLAGS_H__ - /** * \struct DetectFlagsData_ * DetectFlagsData_ is used to store flags: input value @@ -36,8 +35,8 @@ */ typedef struct DetectFlagsData_ { - uint8_t flags; /**< TCP flags */ - uint8_t modifier; /**< !(1) +(2) *(3) modifiers */ + uint8_t flags; /**< TCP flags */ + uint8_t modifier; /**< !(1) +(2) *(3) modifiers */ uint8_t ignored_flags; /**< Ignored TCP flags defined by modifier , */ } DetectFlagsData; @@ -45,7 +44,7 @@ typedef struct DetectFlagsData_ { * Registration function for flags: keyword */ -void DetectFlagsRegister (void); +void DetectFlagsRegister(void); int DetectFlagsSignatureNeedsSynPackets(const Signature *s); int DetectFlagsSignatureNeedsSynOnlyPackets(const Signature *s); diff --git a/src/detect-tcp-seq.c b/src/detect-tcp-seq.c index 0a34f5633de9..d61a0db68513 100644 --- a/src/detect-tcp-seq.c +++ b/src/detect-tcp-seq.c @@ -41,8 +41,8 @@ #include "util-debug.h" static int DetectSeqSetup(DetectEngineCtx *, Signature *, const char *); -static int DetectSeqMatch(DetectEngineThreadCtx *, - Packet *, const Signature *, const SigMatchCtx *); +static int DetectSeqMatch( + DetectEngineThreadCtx *, Packet *, const Signature *, const SigMatchCtx *); #ifdef UNITTESTS static void DetectSeqRegisterTests(void); #endif @@ -78,8 +78,8 @@ void DetectSeqRegister(void) * \retval 0 no match * \retval 1 match */ -static int DetectSeqMatch(DetectEngineThreadCtx *det_ctx, - Packet *p, const Signature *s, const SigMatchCtx *ctx) +static int DetectSeqMatch( + DetectEngineThreadCtx *det_ctx, Packet *p, const Signature *s, const SigMatchCtx *ctx) { const DetectSeqData *data = (const DetectSeqData *)ctx; @@ -102,7 +102,7 @@ static int DetectSeqMatch(DetectEngineThreadCtx *det_ctx, * \retval 0 on Success * \retval -1 on Failure */ -static int DetectSeqSetup (DetectEngineCtx *de_ctx, Signature *s, const char *optstr) +static int DetectSeqSetup(DetectEngineCtx *de_ctx, Signature *s, const char *optstr) { DetectSeqData *data = NULL; @@ -126,7 +126,6 @@ static int DetectSeqSetup (DetectEngineCtx *de_ctx, Signature *s, const char *op if (data) SCFree(data); return -1; - } /** @@ -143,31 +142,27 @@ static void DetectSeqFree(DetectEngineCtx *de_ctx, void *ptr) /* prefilter code */ -static void -PrefilterPacketSeqMatch(DetectEngineThreadCtx *det_ctx, Packet *p, const void *pectx) +static void PrefilterPacketSeqMatch(DetectEngineThreadCtx *det_ctx, Packet *p, const void *pectx) { const PrefilterPacketHeaderCtx *ctx = pectx; if (!PrefilterPacketHeaderExtraMatch(ctx, p)) return; - if ((p->proto) == IPPROTO_TCP && !(PKT_IS_PSEUDOPKT(p)) && - (p->tcph != NULL) && (TCP_GET_SEQ(p) == ctx->v1.u32[0])) - { + if ((p->proto) == IPPROTO_TCP && !(PKT_IS_PSEUDOPKT(p)) && (p->tcph != NULL) && + (TCP_GET_SEQ(p) == ctx->v1.u32[0])) { SCLogDebug("packet matches TCP seq %u", ctx->v1.u32[0]); PrefilterAddSids(&det_ctx->pmq, ctx->sigs_array, ctx->sigs_cnt); } } -static void -PrefilterPacketSeqSet(PrefilterPacketHeaderValue *v, void *smctx) +static void PrefilterPacketSeqSet(PrefilterPacketHeaderValue *v, void *smctx) { const DetectSeqData *a = smctx; v->u32[0] = a->seq; } -static bool -PrefilterPacketSeqCompare(PrefilterPacketHeaderValue v, void *smctx) +static bool PrefilterPacketSeqCompare(PrefilterPacketHeaderValue v, void *smctx) { const DetectSeqData *a = smctx; if (v.u32[0] == a->seq) @@ -177,16 +172,14 @@ PrefilterPacketSeqCompare(PrefilterPacketHeaderValue v, void *smctx) static int PrefilterSetupTcpSeq(DetectEngineCtx *de_ctx, SigGroupHead *sgh) { - return PrefilterSetupPacketHeader(de_ctx, sgh, DETECT_SEQ, - PrefilterPacketSeqSet, - PrefilterPacketSeqCompare, - PrefilterPacketSeqMatch); + return PrefilterSetupPacketHeader(de_ctx, sgh, DETECT_SEQ, PrefilterPacketSeqSet, + PrefilterPacketSeqCompare, PrefilterPacketSeqMatch); } static bool PrefilterTcpSeqIsPrefilterable(const Signature *s) { const SigMatch *sm; - for (sm = s->init_data->smlists[DETECT_SM_LIST_MATCH] ; sm != NULL; sm = sm->next) { + for (sm = s->init_data->smlists[DETECT_SM_LIST_MATCH]; sm != NULL; sm = sm->next) { switch (sm->type) { case DETECT_SEQ: return true; @@ -195,7 +188,6 @@ static bool PrefilterTcpSeqIsPrefilterable(const Signature *s) return false; } - #ifdef UNITTESTS /** @@ -209,24 +201,18 @@ static int DetectSeqSigTest01(void) goto end; /* These three are crammed in here as there is no Parse */ - if (SigInit(de_ctx, - "alert tcp any any -> any any " - "(msg:\"Testing seq\";seq:foo;sid:1;)") != NULL) - { + if (SigInit(de_ctx, "alert tcp any any -> any any " + "(msg:\"Testing seq\";seq:foo;sid:1;)") != NULL) { printf("invalid seq accepted: "); goto cleanup; } - if (SigInit(de_ctx, - "alert tcp any any -> any any " - "(msg:\"Testing seq\";seq:9999999999;sid:1;)") != NULL) - { + if (SigInit(de_ctx, "alert tcp any any -> any any " + "(msg:\"Testing seq\";seq:9999999999;sid:1;)") != NULL) { printf("overflowing seq accepted: "); goto cleanup; } - if (SigInit(de_ctx, - "alert tcp any any -> any any " - "(msg:\"Testing seq\";seq:-100;sid:1;)") != NULL) - { + if (SigInit(de_ctx, "alert tcp any any -> any any " + "(msg:\"Testing seq\";seq:-100;sid:1;)") != NULL) { printf("negative seq accepted: "); goto cleanup; } @@ -254,7 +240,7 @@ static int DetectSeqSigTest02(void) p[0] = UTHBuildPacket((uint8_t *)buf, buflen, IPPROTO_TCP); p[1] = UTHBuildPacket((uint8_t *)buf, buflen, IPPROTO_TCP); p[2] = UTHBuildPacket((uint8_t *)buf, buflen, IPPROTO_ICMP); - if (p[0] == NULL || p[1] == NULL ||p[2] == NULL) + if (p[0] == NULL || p[1] == NULL || p[2] == NULL) goto end; /* TCP w/seq=42 */ @@ -264,20 +250,20 @@ static int DetectSeqSigTest02(void) p[1]->tcph->th_seq = htonl(100); const char *sigs[2]; - sigs[0]= "alert tcp any any -> any any (msg:\"Testing seq\"; seq:41; sid:1;)"; - sigs[1]= "alert tcp any any -> any any (msg:\"Testing seq\"; seq:42; sid:2;)"; + sigs[0] = "alert tcp any any -> any any (msg:\"Testing seq\"; seq:41; sid:1;)"; + sigs[1] = "alert tcp any any -> any any (msg:\"Testing seq\"; seq:42; sid:2;)"; - uint32_t sid[2] = {1, 2}; + uint32_t sid[2] = { 1, 2 }; - uint32_t results[3][2] = { - /* packet 0 match sid 1 but should not match sid 2 */ - {0, 1}, - /* packet 1 should not match */ - {0, 0}, - /* packet 2 should not match */ - {0, 0} }; + uint32_t results[3][2] = { /* packet 0 match sid 1 but should not match sid 2 */ + { 0, 1 }, + /* packet 1 should not match */ + { 0, 0 }, + /* packet 2 should not match */ + { 0, 0 } + }; - result = UTHGenericTest(p, 3, sigs, sid, (uint32_t *) results, 2); + result = UTHGenericTest(p, 3, sigs, sid, (uint32_t *)results, 2); UTHFreePackets(p, 3); end: return result; diff --git a/src/detect-tcp-seq.h b/src/detect-tcp-seq.h index 688b6c2c39da..2f52f157e3b3 100644 --- a/src/detect-tcp-seq.h +++ b/src/detect-tcp-seq.h @@ -28,7 +28,7 @@ * \brief seq data */ typedef struct DetectSeqData_ { - uint32_t seq; /**< seq to match */ + uint32_t seq; /**< seq to match */ } DetectSeqData; /** diff --git a/src/detect-tcp-window.c b/src/detect-tcp-window.c index c0a7bb7e1b05..7c03dc72cf8c 100644 --- a/src/detect-tcp-window.c +++ b/src/detect-tcp-window.c @@ -41,12 +41,12 @@ /** * \brief Regex for parsing our window option */ -#define PARSE_REGEX "^\\s*([!])?\\s*([0-9]{1,9}+)\\s*$" +#define PARSE_REGEX "^\\s*([!])?\\s*([0-9]{1,9}+)\\s*$" static DetectParseRegex parse_regex; -static int DetectWindowMatch(DetectEngineThreadCtx *, Packet *, - const Signature *, const SigMatchCtx *); +static int DetectWindowMatch( + DetectEngineThreadCtx *, Packet *, const Signature *, const SigMatchCtx *); static int DetectWindowSetup(DetectEngineCtx *, Signature *, const char *); #ifdef UNITTESTS static void DetectWindowRegisterTests(void); @@ -56,7 +56,7 @@ void DetectWindowFree(DetectEngineCtx *, void *); /** * \brief Registration function for window: keyword */ -void DetectWindowRegister (void) +void DetectWindowRegister(void) { sigmatch_table[DETECT_WINDOW].name = "tcp.window"; sigmatch_table[DETECT_WINDOW].alias = "window"; @@ -64,7 +64,7 @@ void DetectWindowRegister (void) sigmatch_table[DETECT_WINDOW].url = "/rules/header-keywords.html#window"; sigmatch_table[DETECT_WINDOW].Match = DetectWindowMatch; sigmatch_table[DETECT_WINDOW].Setup = DetectWindowSetup; - sigmatch_table[DETECT_WINDOW].Free = DetectWindowFree; + sigmatch_table[DETECT_WINDOW].Free = DetectWindowFree; #ifdef UNITTESTS sigmatch_table[DETECT_WINDOW].RegisterTests = DetectWindowRegisterTests; #endif @@ -82,16 +82,17 @@ void DetectWindowRegister (void) * \retval 0 no match * \retval 1 match */ -static int DetectWindowMatch(DetectEngineThreadCtx *det_ctx, Packet *p, - const Signature *s, const SigMatchCtx *ctx) +static int DetectWindowMatch( + DetectEngineThreadCtx *det_ctx, Packet *p, const Signature *s, const SigMatchCtx *ctx) { const DetectWindowData *wd = (const DetectWindowData *)ctx; - if ( !(PKT_IS_TCP(p)) || wd == NULL || PKT_IS_PSEUDOPKT(p)) { + if (!(PKT_IS_TCP(p)) || wd == NULL || PKT_IS_PSEUDOPKT(p)) { return 0; } - if ( (!wd->negated && wd->size == TCP_GET_WINDOW(p)) || (wd->negated && wd->size != TCP_GET_WINDOW(p))) { + if ((!wd->negated && wd->size == TCP_GET_WINDOW(p)) || + (wd->negated && wd->size != TCP_GET_WINDOW(p))) { return 1; } @@ -165,7 +166,6 @@ static DetectWindowData *DetectWindowParse(DetectEngineCtx *de_ctx, const char * if (wd != NULL) DetectWindowFree(de_ctx, wd); return NULL; - } /** @@ -178,12 +178,13 @@ static DetectWindowData *DetectWindowParse(DetectEngineCtx *de_ctx, const char * * \retval 0 on Success * \retval -1 on Failure */ -static int DetectWindowSetup (DetectEngineCtx *de_ctx, Signature *s, const char *windowstr) +static int DetectWindowSetup(DetectEngineCtx *de_ctx, Signature *s, const char *windowstr) { DetectWindowData *wd = NULL; wd = DetectWindowParse(de_ctx, windowstr); - if (wd == NULL) goto error; + if (wd == NULL) + goto error; /* Okay so far so good, lets get this into a SigMatch * and put it in the Signature. */ @@ -200,7 +201,6 @@ static int DetectWindowSetup (DetectEngineCtx *de_ctx, Signature *s, const char if (wd != NULL) DetectWindowFree(de_ctx, wd); return -1; - } /** @@ -220,7 +220,7 @@ void DetectWindowFree(DetectEngineCtx *de_ctx, void *ptr) * \test DetectWindowTestParse01 is a test to make sure that we set the size correctly * when given valid window opt */ -static int DetectWindowTestParse01 (void) +static int DetectWindowTestParse01(void) { DetectWindowData *wd = NULL; wd = DetectWindowParse(NULL, "35402"); @@ -234,7 +234,7 @@ static int DetectWindowTestParse01 (void) /** * \test DetectWindowTestParse02 is a test for setting the window opt negated */ -static int DetectWindowTestParse02 (void) +static int DetectWindowTestParse02(void) { DetectWindowData *wd = NULL; wd = DetectWindowParse(NULL, "!35402"); @@ -249,7 +249,7 @@ static int DetectWindowTestParse02 (void) /** * \test DetectWindowTestParse03 is a test to check for an empty value */ -static int DetectWindowTestParse03 (void) +static int DetectWindowTestParse03(void) { DetectWindowData *wd = NULL; wd = DetectWindowParse(NULL, ""); @@ -262,7 +262,7 @@ static int DetectWindowTestParse03 (void) /** * \test DetectWindowTestParse03 is a test to check for a big value */ -static int DetectWindowTestParse04 (void) +static int DetectWindowTestParse04(void) { DetectWindowData *wd = NULL; wd = DetectWindowParse(NULL, "1235402"); @@ -275,7 +275,7 @@ static int DetectWindowTestParse04 (void) /** * \test DetectWindowTestPacket01 is a test to check window with constructed packets */ -static int DetectWindowTestPacket01 (void) +static int DetectWindowTestPacket01(void) { uint8_t *buf = (uint8_t *)"Hi all!"; uint16_t buflen = strlen((char *)buf); @@ -293,18 +293,18 @@ static int DetectWindowTestPacket01 (void) p[1]->tcph->th_win = htons(41); const char *sigs[2]; - sigs[0]= "alert tcp any any -> any any (msg:\"Testing window 1\"; window:40; sid:1;)"; - sigs[1]= "alert tcp any any -> any any (msg:\"Testing window 2\"; window:41; sid:2;)"; - - uint32_t sid[2] = {1, 2}; - - uint32_t results[3][2] = { - /* packet 0 match sid 1 but should not match sid 2 */ - {1, 0}, - /* packet 1 should not match */ - {0, 1}, - /* packet 2 should not match */ - {0, 0} }; + sigs[0] = "alert tcp any any -> any any (msg:\"Testing window 1\"; window:40; sid:1;)"; + sigs[1] = "alert tcp any any -> any any (msg:\"Testing window 2\"; window:41; sid:2;)"; + + uint32_t sid[2] = { 1, 2 }; + + uint32_t results[3][2] = { /* packet 0 match sid 1 but should not match sid 2 */ + { 1, 0 }, + /* packet 1 should not match */ + { 0, 1 }, + /* packet 2 should not match */ + { 0, 0 } + }; FAIL_IF(UTHGenericTest(p, 3, sigs, sid, (uint32_t *)results, 2) == 0); UTHFreePackets(p, 3); diff --git a/src/detect-tcp-window.h b/src/detect-tcp-window.h index 51f85398dbe5..a418a25ae37b 100644 --- a/src/detect-tcp-window.h +++ b/src/detect-tcp-window.h @@ -19,11 +19,11 @@ #define __DETECT_WINDOW_H__ typedef struct DetectWindowData_ { - uint8_t negated; /** negated? 1=True : 0=False */ - uint16_t size; /** window size to match */ + uint8_t negated; /** negated? 1=True : 0=False */ + uint16_t size; /** window size to match */ } DetectWindowData; /* prototypes */ -void DetectWindowRegister (void); +void DetectWindowRegister(void); #endif /* __DETECT_WINDOW_H__ */ diff --git a/src/detect-tcphdr.c b/src/detect-tcphdr.c index f054e3550970..bcc4d51251d0 100644 --- a/src/detect-tcphdr.c +++ b/src/detect-tcphdr.c @@ -34,9 +34,9 @@ #include "detect-tcphdr.h" /* prototypes */ -static int DetectTcphdrSetup (DetectEngineCtx *, Signature *, const char *); +static int DetectTcphdrSetup(DetectEngineCtx *, Signature *, const char *); #ifdef UNITTESTS -void DetectTcphdrRegisterTests (void); +void DetectTcphdrRegisterTests(void); #endif static int g_tcphdr_buffer_id = 0; @@ -65,8 +65,7 @@ void DetectTcphdrRegister(void) DetectPktMpmRegister("tcp.hdr", 2, PrefilterGenericMpmPktRegister, GetData); - DetectPktInspectEngineRegister("tcp.hdr", GetData, - DetectEngineInspectPktBufferGeneric); + DetectPktInspectEngineRegister("tcp.hdr", GetData, DetectEngineInspectPktBufferGeneric); return; } @@ -81,7 +80,7 @@ void DetectTcphdrRegister(void) * \retval 0 on Success * \retval -1 on Failure */ -static int DetectTcphdrSetup (DetectEngineCtx *de_ctx, Signature *s, const char *_unused) +static int DetectTcphdrSetup(DetectEngineCtx *de_ctx, Signature *s, const char *_unused) { if (!(DetectProtoContainsProto(&s->proto, IPPROTO_TCP))) return -1; @@ -108,10 +107,8 @@ static InspectionBuffer *GetData(DetectEngineThreadCtx *det_ctx, } uint32_t hlen = TCP_GET_HLEN(p); if (((uint8_t *)p->tcph + (ptrdiff_t)hlen) > - ((uint8_t *)GET_PKT_DATA(p) + (ptrdiff_t)GET_PKT_LEN(p))) - { - SCLogDebug("data out of range: %p > %p", - ((uint8_t *)p->tcph + (ptrdiff_t)hlen), + ((uint8_t *)GET_PKT_DATA(p) + (ptrdiff_t)GET_PKT_LEN(p))) { + SCLogDebug("data out of range: %p > %p", ((uint8_t *)p->tcph + (ptrdiff_t)hlen), ((uint8_t *)GET_PKT_DATA(p) + (ptrdiff_t)GET_PKT_LEN(p))); return NULL; } diff --git a/src/detect-tcphdr.h b/src/detect-tcphdr.h index 2f83f1734b09..147f397fe8d6 100644 --- a/src/detect-tcphdr.h +++ b/src/detect-tcphdr.h @@ -26,4 +26,4 @@ void DetectTcphdrRegister(void); -#endif /* _DETECT_TCPHDR_H */ +#endif /* _DETECT_TCPHDR_H */ diff --git a/src/detect-tcpmss.c b/src/detect-tcpmss.c index c04a9be09ecc..f7c6cb12cdd3 100644 --- a/src/detect-tcpmss.c +++ b/src/detect-tcpmss.c @@ -32,14 +32,13 @@ #include "detect-tcpmss.h" - /* prototypes */ -static int DetectTcpmssMatch (DetectEngineThreadCtx *, Packet *, - const Signature *, const SigMatchCtx *); -static int DetectTcpmssSetup (DetectEngineCtx *, Signature *, const char *); -void DetectTcpmssFree (DetectEngineCtx *, void *); +static int DetectTcpmssMatch( + DetectEngineThreadCtx *, Packet *, const Signature *, const SigMatchCtx *); +static int DetectTcpmssSetup(DetectEngineCtx *, Signature *, const char *); +void DetectTcpmssFree(DetectEngineCtx *, void *); #ifdef UNITTESTS -void DetectTcpmssRegisterTests (void); +void DetectTcpmssRegisterTests(void); #endif static int PrefilterSetupTcpmss(DetectEngineCtx *de_ctx, SigGroupHead *sgh); static bool PrefilterTcpmssIsPrefilterable(const Signature *s); @@ -73,8 +72,8 @@ void DetectTcpmssRegister(void) * \retval 0 no match * \retval 1 match */ -static int DetectTcpmssMatch (DetectEngineThreadCtx *det_ctx, Packet *p, - const Signature *s, const SigMatchCtx *ctx) +static int DetectTcpmssMatch( + DetectEngineThreadCtx *det_ctx, Packet *p, const Signature *s, const SigMatchCtx *ctx) { if (!(PKT_IS_TCP(p)) || PKT_IS_PSEUDOPKT(p)) @@ -99,7 +98,7 @@ static int DetectTcpmssMatch (DetectEngineThreadCtx *det_ctx, Packet *p, * \retval 0 on Success * \retval -1 on Failure */ -static int DetectTcpmssSetup (DetectEngineCtx *de_ctx, Signature *s, const char *tcpmssstr) +static int DetectTcpmssSetup(DetectEngineCtx *de_ctx, Signature *s, const char *tcpmssstr) { DetectU16Data *tcpmssd = DetectU16Parse(tcpmssstr); if (tcpmssd == NULL) @@ -127,8 +126,7 @@ void DetectTcpmssFree(DetectEngineCtx *de_ctx, void *ptr) /* prefilter code */ -static void -PrefilterPacketTcpmssMatch(DetectEngineThreadCtx *det_ctx, Packet *p, const void *pectx) +static void PrefilterPacketTcpmssMatch(DetectEngineThreadCtx *det_ctx, Packet *p, const void *pectx) { if (!(PKT_IS_TCP(p)) || PKT_IS_PSEUDOPKT(p)) return; @@ -165,7 +163,7 @@ static int PrefilterSetupTcpmss(DetectEngineCtx *de_ctx, SigGroupHead *sgh) static bool PrefilterTcpmssIsPrefilterable(const Signature *s) { const SigMatch *sm; - for (sm = s->init_data->smlists[DETECT_SM_LIST_MATCH] ; sm != NULL; sm = sm->next) { + for (sm = s->init_data->smlists[DETECT_SM_LIST_MATCH]; sm != NULL; sm = sm->next) { switch (sm->type) { case DETECT_TCPMSS: return true; diff --git a/src/detect-tcpmss.h b/src/detect-tcpmss.h index d01f2819b563..93f2b395db29 100644 --- a/src/detect-tcpmss.h +++ b/src/detect-tcpmss.h @@ -22,8 +22,8 @@ */ #ifndef _DETECT_TCPMSS_H -#define _DETECT_TCPMSS_H +#define _DETECT_TCPMSS_H void DetectTcpmssRegister(void); -#endif /* _DETECT_TCPMSS_H */ +#endif /* _DETECT_TCPMSS_H */ diff --git a/src/detect-template-rust-buffer.c b/src/detect-template-rust-buffer.c index f1c8c97bb278..347bf60a30e5 100644 --- a/src/detect-template-rust-buffer.c +++ b/src/detect-template-rust-buffer.c @@ -198,7 +198,6 @@ static int DetectTemplateRustBufferTest(void) static void DetectTemplateRustBufferRegisterTests(void) { - UtRegisterTest("DetectTemplateRustBufferTest", - DetectTemplateRustBufferTest); + UtRegisterTest("DetectTemplateRustBufferTest", DetectTemplateRustBufferTest); } #endif /* UNITTESTS */ diff --git a/src/detect-template.c b/src/detect-template.c index 5e09170d82a3..d2ff14114409 100644 --- a/src/detect-template.c +++ b/src/detect-template.c @@ -35,16 +35,16 @@ /** * \brief Regex for parsing our keyword options */ -#define PARSE_REGEX "^\\s*([0-9]+)?\\s*,s*([0-9]+)?\\s*$" +#define PARSE_REGEX "^\\s*([0-9]+)?\\s*,s*([0-9]+)?\\s*$" static DetectParseRegex parse_regex; /* Prototypes of functions registered in DetectTemplateRegister below */ -static int DetectTemplateMatch (DetectEngineThreadCtx *, - Packet *, const Signature *, const SigMatchCtx *); -static int DetectTemplateSetup (DetectEngineCtx *, Signature *, const char *); -static void DetectTemplateFree (DetectEngineCtx *, void *); +static int DetectTemplateMatch( + DetectEngineThreadCtx *, Packet *, const Signature *, const SigMatchCtx *); +static int DetectTemplateSetup(DetectEngineCtx *, Signature *, const char *); +static void DetectTemplateFree(DetectEngineCtx *, void *); #ifdef UNITTESTS -static void DetectTemplateRegisterTests (void); +static void DetectTemplateRegisterTests(void); #endif /** @@ -52,13 +52,15 @@ static void DetectTemplateRegisterTests (void); * * This function is called once in the 'lifetime' of the engine. */ -void DetectTemplateRegister(void) { +void DetectTemplateRegister(void) +{ /* keyword name: this is how the keyword is used in a rule */ sigmatch_table[DETECT_TEMPLATE].name = "template"; /* description: listed in "suricata --list-keywords=all" */ sigmatch_table[DETECT_TEMPLATE].desc = "give an introduction into how a detection module works"; /* link to further documentation of the keyword. Normally on the Suricata redmine/wiki */ - sigmatch_table[DETECT_TEMPLATE].url = "https://redmine.openinfosecfoundation.org/projects/suricata/wiki/Suricata_Developers_Guide"; + sigmatch_table[DETECT_TEMPLATE].url = "https://redmine.openinfosecfoundation.org/projects/" + "suricata/wiki/Suricata_Developers_Guide"; /* match function is called when the signature is inspected on a packet */ sigmatch_table[DETECT_TEMPLATE].Match = DetectTemplateMatch; /* setup function is called during signature parsing, when the template @@ -86,11 +88,11 @@ void DetectTemplateRegister(void) { * \retval 0 no match * \retval 1 match */ -static int DetectTemplateMatch (DetectEngineThreadCtx *det_ctx, Packet *p, - const Signature *s, const SigMatchCtx *ctx) +static int DetectTemplateMatch( + DetectEngineThreadCtx *det_ctx, Packet *p, const Signature *s, const SigMatchCtx *ctx) { int ret = 0; - const DetectTemplateData *templated = (const DetectTemplateData *) ctx; + const DetectTemplateData *templated = (const DetectTemplateData *)ctx; #if 0 if (PKT_IS_PSEUDOPKT(p)) { /* fake pkt */ @@ -107,9 +109,7 @@ static int DetectTemplateMatch (DetectEngineThreadCtx *det_ctx, Packet *p, #endif /* packet payload access */ if (p->payload != NULL && p->payload_len > 0) { - if (templated->arg1 == p->payload[0] && - templated->arg2 == p->payload[p->payload_len - 1]) - { + if (templated->arg1 == p->payload[0] && templated->arg2 == p->payload[p->payload_len - 1]) { ret = 1; } } @@ -125,7 +125,7 @@ static int DetectTemplateMatch (DetectEngineThreadCtx *det_ctx, Packet *p, * \retval templated pointer to DetectTemplateData on success * \retval NULL on failure */ -static DetectTemplateData *DetectTemplateParse (const char *templatestr) +static DetectTemplateData *DetectTemplateParse(const char *templatestr) { char arg1[4] = ""; char arg2[4] = ""; @@ -153,7 +153,7 @@ static DetectTemplateData *DetectTemplateParse (const char *templatestr) } SCLogDebug("Arg2 \"%s\"", arg2); - DetectTemplateData *templated = SCMalloc(sizeof (DetectTemplateData)); + DetectTemplateData *templated = SCMalloc(sizeof(DetectTemplateData)); if (unlikely(templated == NULL)) goto error; @@ -186,7 +186,7 @@ static DetectTemplateData *DetectTemplateParse (const char *templatestr) * \retval 0 on Success * \retval -1 on Failure */ -static int DetectTemplateSetup (DetectEngineCtx *de_ctx, Signature *s, const char *templatestr) +static int DetectTemplateSetup(DetectEngineCtx *de_ctx, Signature *s, const char *templatestr) { DetectTemplateData *templated = DetectTemplateParse(templatestr); if (templated == NULL) diff --git a/src/detect-template2.c b/src/detect-template2.c index df93a535e6b9..c5595d9f2661 100644 --- a/src/detect-template2.c +++ b/src/detect-template2.c @@ -32,14 +32,13 @@ #include "detect-template2.h" - /* prototypes */ -static int DetectTemplate2Match (DetectEngineThreadCtx *, Packet *, - const Signature *, const SigMatchCtx *); -static int DetectTemplate2Setup (DetectEngineCtx *, Signature *, const char *); -void DetectTemplate2Free (DetectEngineCtx *, void *); +static int DetectTemplate2Match( + DetectEngineThreadCtx *, Packet *, const Signature *, const SigMatchCtx *); +static int DetectTemplate2Setup(DetectEngineCtx *, Signature *, const char *); +void DetectTemplate2Free(DetectEngineCtx *, void *); #ifdef UNITTESTS -void DetectTemplate2RegisterTests (void); +void DetectTemplate2RegisterTests(void); #endif static int PrefilterSetupTemplate2(DetectEngineCtx *de_ctx, SigGroupHead *sgh); static bool PrefilterTemplate2IsPrefilterable(const Signature *s); @@ -74,8 +73,8 @@ void DetectTemplate2Register(void) * \retval 0 no match * \retval 1 match */ -static int DetectTemplate2Match (DetectEngineThreadCtx *det_ctx, Packet *p, - const Signature *s, const SigMatchCtx *ctx) +static int DetectTemplate2Match( + DetectEngineThreadCtx *det_ctx, Packet *p, const Signature *s, const SigMatchCtx *ctx) { if (PKT_IS_PSEUDOPKT(p)) @@ -106,7 +105,7 @@ static int DetectTemplate2Match (DetectEngineThreadCtx *det_ctx, Packet *p, * \retval 0 on Success * \retval -1 on Failure */ -static int DetectTemplate2Setup (DetectEngineCtx *de_ctx, Signature *s, const char *template2str) +static int DetectTemplate2Setup(DetectEngineCtx *de_ctx, Signature *s, const char *template2str) { DetectU8Data *template2d = DetectU8Parse(template2str); if (template2d == NULL) @@ -134,15 +133,15 @@ void DetectTemplate2Free(DetectEngineCtx *de_ctx, void *ptr) /* prefilter code */ -static void -PrefilterPacketTemplate2Match(DetectEngineThreadCtx *det_ctx, Packet *p, const void *pectx) +static void PrefilterPacketTemplate2Match( + DetectEngineThreadCtx *det_ctx, Packet *p, const void *pectx) { if (PKT_IS_PSEUDOPKT(p)) { SCReturn; } uint8_t ptemplate2; -/* TODO update */ + /* TODO update */ if (PKT_IS_IPV4(p)) { ptemplate2 = IPV4_GET_IPTTL(p); } else if (PKT_IS_IPV6(p)) { @@ -179,7 +178,7 @@ static int PrefilterSetupTemplate2(DetectEngineCtx *de_ctx, SigGroupHead *sgh) static bool PrefilterTemplate2IsPrefilterable(const Signature *s) { const SigMatch *sm; - for (sm = s->init_data->smlists[DETECT_SM_LIST_MATCH] ; sm != NULL; sm = sm->next) { + for (sm = s->init_data->smlists[DETECT_SM_LIST_MATCH]; sm != NULL; sm = sm->next) { switch (sm->type) { case DETECT_TEMPLATE2: return true; diff --git a/src/detect-template2.h b/src/detect-template2.h index b7ea8af34a6d..ee290644cd75 100644 --- a/src/detect-template2.h +++ b/src/detect-template2.h @@ -22,10 +22,8 @@ */ #ifndef _DETECT_TEMPLATE2_H -#define _DETECT_TEMPLATE2_H - +#define _DETECT_TEMPLATE2_H void DetectTemplate2Register(void); -#endif /* _DETECT_TEMPLATE2_H */ - +#endif /* _DETECT_TEMPLATE2_H */ diff --git a/src/detect-threshold.c b/src/detect-threshold.c index 98eb3ce8dc03..bf53d32063cd 100644 --- a/src/detect-threshold.c +++ b/src/detect-threshold.c @@ -60,12 +60,17 @@ #include "util-cpu.h" #endif -#define PARSE_REGEX "^\\s*(track|type|count|seconds)\\s+(limit|both|threshold|by_dst|by_src|by_both|by_rule|\\d+)\\s*,\\s*(track|type|count|seconds)\\s+(limit|both|threshold|by_dst|by_src|by_both|by_rule|\\d+)\\s*,\\s*(track|type|count|seconds)\\s+(limit|both|threshold|by_dst|by_src|by_both|by_rule|\\d+)\\s*,\\s*(track|type|count|seconds)\\s+(limit|both|threshold|by_dst|by_src|by_both|by_rule|\\d+)\\s*" +#define PARSE_REGEX \ + "^\\s*(track|type|count|seconds)\\s+(limit|both|threshold|by_dst|by_src|by_both|by_rule|\\d+)" \ + "\\s*,\\s*(track|type|count|seconds)\\s+(limit|both|threshold|by_dst|by_src|by_both|by_rule|" \ + "\\d+)\\s*,\\s*(track|type|count|seconds)\\s+(limit|both|threshold|by_dst|by_src|by_both|by_" \ + "rule|\\d+)\\s*,\\s*(track|type|count|seconds)\\s+(limit|both|threshold|by_dst|by_src|by_" \ + "both|by_rule|\\d+)\\s*" static DetectParseRegex parse_regex; -static int DetectThresholdMatch(DetectEngineThreadCtx *, Packet *, - const Signature *, const SigMatchCtx *); +static int DetectThresholdMatch( + DetectEngineThreadCtx *, Packet *, const Signature *, const SigMatchCtx *); static int DetectThresholdSetup(DetectEngineCtx *, Signature *, const char *); static void DetectThresholdFree(DetectEngineCtx *, void *); #ifdef UNITTESTS @@ -83,7 +88,7 @@ void DetectThresholdRegister(void) sigmatch_table[DETECT_THRESHOLD].url = "/rules/thresholding.html#threshold"; sigmatch_table[DETECT_THRESHOLD].Match = DetectThresholdMatch; sigmatch_table[DETECT_THRESHOLD].Setup = DetectThresholdSetup; - sigmatch_table[DETECT_THRESHOLD].Free = DetectThresholdFree; + sigmatch_table[DETECT_THRESHOLD].Free = DetectThresholdFree; #ifdef UNITTESTS sigmatch_table[DETECT_THRESHOLD].RegisterTests = ThresholdRegisterTests; #endif @@ -93,8 +98,8 @@ void DetectThresholdRegister(void) DetectSetupParseRegexes(PARSE_REGEX, &parse_regex); } -static int DetectThresholdMatch(DetectEngineThreadCtx *det_ctx, Packet *p, - const Signature *s, const SigMatchCtx *ctx) +static int DetectThresholdMatch( + DetectEngineThreadCtx *det_ctx, Packet *p, const Signature *s, const SigMatchCtx *ctx) { return 1; } @@ -129,23 +134,22 @@ static DetectThresholdData *DetectThresholdParse(const char *rawstr) } char *saveptr = NULL; - for (pos = 0, threshold_opt = strtok_r(copy_str,",", &saveptr); - pos < strlen(copy_str) && threshold_opt != NULL; - pos++, threshold_opt = strtok_r(NULL,"," , &saveptr)) - { - if(strstr(threshold_opt,"count")) + for (pos = 0, threshold_opt = strtok_r(copy_str, ",", &saveptr); + pos < strlen(copy_str) && threshold_opt != NULL; + pos++, threshold_opt = strtok_r(NULL, ",", &saveptr)) { + if (strstr(threshold_opt, "count")) count_found++; - if(strstr(threshold_opt,"second")) + if (strstr(threshold_opt, "second")) second_found++; - if(strstr(threshold_opt,"type")) + if (strstr(threshold_opt, "type")) type_found++; - if(strstr(threshold_opt,"track")) + if (strstr(threshold_opt, "track")) track_found++; } SCFree(copy_str); copy_str = NULL; - if(count_found != 1 || second_found != 1 || type_found != 1 || track_found != 1) + if (count_found != 1 || second_found != 1 || type_found != 1 || track_found != 1) goto error; ret = DetectParsePcreExec(&parse_regex, &match, rawstr, 0, 0); @@ -169,41 +173,39 @@ static DetectThresholdData *DetectThresholdParse(const char *rawstr) args[i] = (char *)str_ptr; - if (strncasecmp(args[i],"limit",strlen("limit")) == 0) + if (strncasecmp(args[i], "limit", strlen("limit")) == 0) de->type = TYPE_LIMIT; - if (strncasecmp(args[i],"both",strlen("both")) == 0) + if (strncasecmp(args[i], "both", strlen("both")) == 0) de->type = TYPE_BOTH; - if (strncasecmp(args[i],"threshold",strlen("threshold")) == 0) + if (strncasecmp(args[i], "threshold", strlen("threshold")) == 0) de->type = TYPE_THRESHOLD; - if (strncasecmp(args[i],"by_dst",strlen("by_dst")) == 0) + if (strncasecmp(args[i], "by_dst", strlen("by_dst")) == 0) de->track = TRACK_DST; - if (strncasecmp(args[i],"by_src",strlen("by_src")) == 0) + if (strncasecmp(args[i], "by_src", strlen("by_src")) == 0) de->track = TRACK_SRC; - if (strncasecmp(args[i],"by_both",strlen("by_both")) == 0) + if (strncasecmp(args[i], "by_both", strlen("by_both")) == 0) de->track = TRACK_BOTH; - if (strncasecmp(args[i],"by_rule",strlen("by_rule")) == 0) + if (strncasecmp(args[i], "by_rule", strlen("by_rule")) == 0) de->track = TRACK_RULE; - if (strncasecmp(args[i],"count",strlen("count")) == 0) - count_pos = i+1; - if (strncasecmp(args[i],"seconds",strlen("seconds")) == 0) - second_pos = i+1; + if (strncasecmp(args[i], "count", strlen("count")) == 0) + count_pos = i + 1; + if (strncasecmp(args[i], "seconds", strlen("seconds")) == 0) + second_pos = i + 1; } if (args[count_pos] == NULL || args[second_pos] == NULL) { goto error; } - if (StringParseUint32(&de->count, 10, strlen(args[count_pos]), - args[count_pos]) <= 0) { + if (StringParseUint32(&de->count, 10, strlen(args[count_pos]), args[count_pos]) <= 0) { goto error; } - if (StringParseUint32(&de->seconds, 10, strlen(args[second_pos]), - args[second_pos]) <= 0) { + if (StringParseUint32(&de->seconds, 10, strlen(args[second_pos]), args[second_pos]) <= 0) { goto error; } - for (i = 0; i < (ret - 1); i++){ + for (i = 0; i < (ret - 1); i++) { if (args[i] != NULL) pcre2_substring_free((PCRE2_UCHAR8 *)args[i]); } @@ -214,7 +216,7 @@ static DetectThresholdData *DetectThresholdParse(const char *rawstr) if (match) { pcre2_match_data_free(match); } - for (i = 0; i < (ret - 1); i++){ + for (i = 0; i < (ret - 1); i++) { if (args[i] != NULL) pcre2_substring_free((PCRE2_UCHAR8 *)args[i]); } @@ -352,7 +354,8 @@ static int ThresholdTestParse01(void) { DetectThresholdData *de = NULL; de = DetectThresholdParse("type limit,track by_dst,count 10,seconds 60"); - if (de && (de->type == TYPE_LIMIT) && (de->track == TRACK_DST) && (de->count == 10) && (de->seconds == 60)) { + if (de && (de->type == TYPE_LIMIT) && (de->track == TRACK_DST) && (de->count == 10) && + (de->seconds == 60)) { DetectThresholdFree(NULL, de); return 1; } @@ -370,7 +373,8 @@ static int ThresholdTestParse02(void) { DetectThresholdData *de = NULL; de = DetectThresholdParse("type any,track by_dst,count 10,seconds 60"); - if (de && (de->type == TYPE_LIMIT) && (de->track == TRACK_DST) && (de->count == 10) && (de->seconds == 60)) { + if (de && (de->type == TYPE_LIMIT) && (de->track == TRACK_DST) && (de->count == 10) && + (de->seconds == 60)) { DetectThresholdFree(NULL, de); return 0; } @@ -388,7 +392,8 @@ static int ThresholdTestParse03(void) { DetectThresholdData *de = NULL; de = DetectThresholdParse("track by_dst, type limit, seconds 60, count 10"); - if (de && (de->type == TYPE_LIMIT) && (de->track == TRACK_DST) && (de->count == 10) && (de->seconds == 60)) { + if (de && (de->type == TYPE_LIMIT) && (de->track == TRACK_DST) && (de->count == 10) && + (de->seconds == 60)) { DetectThresholdFree(NULL, de); return 1; } @@ -396,7 +401,6 @@ static int ThresholdTestParse03(void) return 0; } - /** * \test ThresholdTestParse04 is a test for an invalid threshold options in any order * @@ -407,7 +411,8 @@ static int ThresholdTestParse04(void) { DetectThresholdData *de = NULL; de = DetectThresholdParse("count 10, track by_dst, seconds 60, type both, count 10"); - if (de && (de->type == TYPE_BOTH) && (de->track == TRACK_DST) && (de->count == 10) && (de->seconds == 60)) { + if (de && (de->type == TYPE_BOTH) && (de->track == TRACK_DST) && (de->count == 10) && + (de->seconds == 60)) { DetectThresholdFree(NULL, de); return 0; } @@ -425,7 +430,8 @@ static int ThresholdTestParse05(void) { DetectThresholdData *de = NULL; de = DetectThresholdParse("count 10, track by_dst, seconds 60, type both"); - if (de && (de->type == TYPE_BOTH) && (de->track == TRACK_DST) && (de->count == 10) && (de->seconds == 60)) { + if (de && (de->type == TYPE_BOTH) && (de->track == TRACK_DST) && (de->count == 10) && + (de->seconds == 60)) { DetectThresholdFree(NULL, de); return 1; } @@ -493,7 +499,7 @@ static int DetectThresholdTestSig1(void) memset(&th_v, 0, sizeof(th_v)); - p = UTHBuildPacketReal((uint8_t *)"A",1,IPPROTO_TCP, "1.1.1.1", "2.2.2.2", 1024, 80); + p = UTHBuildPacketReal((uint8_t *)"A", 1, IPPROTO_TCP, "1.1.1.1", "2.2.2.2", 1024, 80); DetectEngineCtx *de_ctx = DetectEngineCtxInit(); if (de_ctx == NULL) { @@ -502,7 +508,9 @@ static int DetectThresholdTestSig1(void) de_ctx->flags |= DE_QUIET; - s = de_ctx->sig_list = SigInit(de_ctx,"alert tcp any any -> any 80 (msg:\"Threshold limit\"; content:\"A\"; threshold: type limit, track by_dst, count 5, seconds 60; sid:1;)"); + s = de_ctx->sig_list = + SigInit(de_ctx, "alert tcp any any -> any 80 (msg:\"Threshold limit\"; content:\"A\"; " + "threshold: type limit, track by_dst, count 5, seconds 60; sid:1;)"); if (s == NULL) { goto end; } @@ -516,48 +524,48 @@ static int DetectThresholdTestSig1(void) SigMatchSignatures(&th_v, de_ctx, det_ctx, p); alerts = PacketAlertCheck(p, 1); if (alerts != 1) { - printf("alerts %"PRIi32", expected 1: ", alerts); + printf("alerts %" PRIi32 ", expected 1: ", alerts); } SigMatchSignatures(&th_v, de_ctx, det_ctx, p); alerts += PacketAlertCheck(p, 1); if (alerts != 2) { - printf("alerts %"PRIi32", expected 2: ", alerts); + printf("alerts %" PRIi32 ", expected 2: ", alerts); } SigMatchSignatures(&th_v, de_ctx, det_ctx, p); alerts += PacketAlertCheck(p, 1); if (alerts != 3) { - printf("alerts %"PRIi32", expected 3: ", alerts); + printf("alerts %" PRIi32 ", expected 3: ", alerts); } SigMatchSignatures(&th_v, de_ctx, det_ctx, p); alerts += PacketAlertCheck(p, 1); if (alerts != 4) { - printf("alerts %"PRIi32", expected 4: ", alerts); + printf("alerts %" PRIi32 ", expected 4: ", alerts); } SigMatchSignatures(&th_v, de_ctx, det_ctx, p); alerts += PacketAlertCheck(p, 1); if (alerts != 5) { - printf("alerts %"PRIi32", expected 5: ", alerts); + printf("alerts %" PRIi32 ", expected 5: ", alerts); } SigMatchSignatures(&th_v, de_ctx, det_ctx, p); alerts += PacketAlertCheck(p, 1); if (alerts != 5) { - printf("alerts %"PRIi32", expected 5: ", alerts); + printf("alerts %" PRIi32 ", expected 5: ", alerts); } SigMatchSignatures(&th_v, de_ctx, det_ctx, p); alerts += PacketAlertCheck(p, 1); if (alerts != 5) { - printf("alerts %"PRIi32", expected 5: ", alerts); + printf("alerts %" PRIi32 ", expected 5: ", alerts); } SigMatchSignatures(&th_v, de_ctx, det_ctx, p); alerts += PacketAlertCheck(p, 1); if (alerts != 5) { - printf("alerts %"PRIi32", expected 5: ", alerts); + printf("alerts %" PRIi32 ", expected 5: ", alerts); } - if(alerts == 5) + if (alerts == 5) result = 1; else - printf("alerts %"PRIi32", expected 5: ", alerts); + printf("alerts %" PRIi32 ", expected 5: ", alerts); SigGroupCleanup(de_ctx); SigCleanSignatures(de_ctx); @@ -594,7 +602,7 @@ static int DetectThresholdTestSig2(void) memset(&th_v, 0, sizeof(th_v)); - p = UTHBuildPacketReal((uint8_t *)"A",1,IPPROTO_TCP, "1.1.1.1", "2.2.2.2", 1024, 80); + p = UTHBuildPacketReal((uint8_t *)"A", 1, IPPROTO_TCP, "1.1.1.1", "2.2.2.2", 1024, 80); DetectEngineCtx *de_ctx = DetectEngineCtxInit(); if (de_ctx == NULL) { @@ -603,7 +611,9 @@ static int DetectThresholdTestSig2(void) de_ctx->flags |= DE_QUIET; - s = de_ctx->sig_list = SigInit(de_ctx,"alert tcp any any -> any 80 (msg:\"Threshold\"; threshold: type threshold, track by_dst, count 5, seconds 60; sid:1;)"); + s = de_ctx->sig_list = + SigInit(de_ctx, "alert tcp any any -> any 80 (msg:\"Threshold\"; threshold: type " + "threshold, track by_dst, count 5, seconds 60; sid:1;)"); if (s == NULL) { goto end; } @@ -673,7 +683,7 @@ static int DetectThresholdTestSig3(void) memset(&th_v, 0, sizeof(th_v)); - p = UTHBuildPacketReal((uint8_t *)"A",1,IPPROTO_TCP, "1.1.1.1", "2.2.2.2", 1024, 80); + p = UTHBuildPacketReal((uint8_t *)"A", 1, IPPROTO_TCP, "1.1.1.1", "2.2.2.2", 1024, 80); DetectEngineCtx *de_ctx = DetectEngineCtxInit(); if (de_ctx == NULL) { @@ -682,7 +692,9 @@ static int DetectThresholdTestSig3(void) de_ctx->flags |= DE_QUIET; - s = de_ctx->sig_list = SigInit(de_ctx,"alert tcp any any -> any 80 (msg:\"Threshold limit\"; threshold: type limit, track by_dst, count 5, seconds 60; sid:10;)"); + s = de_ctx->sig_list = + SigInit(de_ctx, "alert tcp any any -> any 80 (msg:\"Threshold limit\"; threshold: type " + "limit, track by_dst, count 5, seconds 60; sid:10;)"); if (s == NULL) { goto end; } @@ -773,7 +785,7 @@ static int DetectThresholdTestSig4(void) memset(&th_v, 0, sizeof(th_v)); - p = UTHBuildPacketReal((uint8_t *)"A",1,IPPROTO_TCP, "1.1.1.1", "2.2.2.2", 1024, 80); + p = UTHBuildPacketReal((uint8_t *)"A", 1, IPPROTO_TCP, "1.1.1.1", "2.2.2.2", 1024, 80); DetectEngineCtx *de_ctx = DetectEngineCtxInit(); if (de_ctx == NULL) { @@ -782,7 +794,9 @@ static int DetectThresholdTestSig4(void) de_ctx->flags |= DE_QUIET; - s = de_ctx->sig_list = SigInit(de_ctx,"alert tcp any any -> any 80 (msg:\"Threshold both\"; threshold: type both, track by_dst, count 2, seconds 60; sid:10;)"); + s = de_ctx->sig_list = + SigInit(de_ctx, "alert tcp any any -> any 80 (msg:\"Threshold both\"; threshold: type " + "both, track by_dst, count 2, seconds 60; sid:10;)"); if (s == NULL) { goto end; } @@ -846,7 +860,7 @@ static int DetectThresholdTestSig5(void) HostInitConfig(HOST_QUIET); memset(&th_v, 0, sizeof(th_v)); - p = UTHBuildPacketReal((uint8_t *)"A",1,IPPROTO_TCP, "1.1.1.1", "2.2.2.2", 1024, 80); + p = UTHBuildPacketReal((uint8_t *)"A", 1, IPPROTO_TCP, "1.1.1.1", "2.2.2.2", 1024, 80); DetectEngineCtx *de_ctx = DetectEngineCtxInit(); if (de_ctx == NULL) { @@ -855,12 +869,16 @@ static int DetectThresholdTestSig5(void) de_ctx->flags |= DE_QUIET; - s = de_ctx->sig_list = SigInit(de_ctx,"alert tcp any any -> any 80 (msg:\"Threshold limit sid 1\"; threshold: type limit, track by_dst, count 5, seconds 60; sid:1;)"); + s = de_ctx->sig_list = + SigInit(de_ctx, "alert tcp any any -> any 80 (msg:\"Threshold limit sid 1\"; " + "threshold: type limit, track by_dst, count 5, seconds 60; sid:1;)"); if (s == NULL) { goto end; } - s = s->next = SigInit(de_ctx,"alert tcp any any -> any 80 (msg:\"Threshold limit sid 1000\"; threshold: type limit, track by_dst, count 5, seconds 60; sid:1000;)"); + s = s->next = + SigInit(de_ctx, "alert tcp any any -> any 80 (msg:\"Threshold limit sid 1000\"; " + "threshold: type limit, track by_dst, count 5, seconds 60; sid:1000;)"); if (s == NULL) { goto end; } @@ -893,7 +911,7 @@ static int DetectThresholdTestSig5(void) alerts += PacketAlertCheck(p, 1); alerts += PacketAlertCheck(p, 1000); - if(alerts == 10) + if (alerts == 10) result = 1; else { printf("alerts %d != 10: ", alerts); @@ -925,7 +943,7 @@ static int DetectThresholdTestSig6Ticks(void) HostInitConfig(HOST_QUIET); memset(&th_v, 0, sizeof(th_v)); - p = UTHBuildPacketReal((uint8_t *)"A",1,IPPROTO_TCP, "1.1.1.1", "2.2.2.2", 1024, 80); + p = UTHBuildPacketReal((uint8_t *)"A", 1, IPPROTO_TCP, "1.1.1.1", "2.2.2.2", 1024, 80); DetectEngineCtx *de_ctx = DetectEngineCtxInit(); if (de_ctx == NULL) { @@ -934,12 +952,16 @@ static int DetectThresholdTestSig6Ticks(void) de_ctx->flags |= DE_QUIET; - s = de_ctx->sig_list = SigInit(de_ctx,"alert tcp any any -> any 80 (msg:\"Threshold limit sid 1\"; threshold: type limit, track by_dst, count 5, seconds 60; sid:1;)"); + s = de_ctx->sig_list = + SigInit(de_ctx, "alert tcp any any -> any 80 (msg:\"Threshold limit sid 1\"; " + "threshold: type limit, track by_dst, count 5, seconds 60; sid:1;)"); if (s == NULL) { goto end; } - s = s->next = SigInit(de_ctx,"alert tcp any any -> any 80 (msg:\"Threshold limit sid 1000\"; threshold: type limit, track by_dst, count 5, seconds 60; sid:1000;)"); + s = s->next = + SigInit(de_ctx, "alert tcp any any -> any 80 (msg:\"Threshold limit sid 1000\"; " + "threshold: type limit, track by_dst, count 5, seconds 60; sid:1000;)"); if (s == NULL) { goto end; } @@ -976,9 +998,9 @@ static int DetectThresholdTestSig6Ticks(void) alerts += PacketAlertCheck(p, 1); alerts += PacketAlertCheck(p, 1000); ticks_end = UtilCpuGetTicks(); - printf("test run %"PRIu64"\n", (ticks_end - ticks_start)); + printf("test run %" PRIu64 "\n", (ticks_end - ticks_start)); - if(alerts == 10) + if (alerts == 10) result = 1; else goto cleanup; @@ -1013,7 +1035,7 @@ static int DetectThresholdTestSig7(void) memset(&th_v, 0, sizeof(th_v)); - p = UTHBuildPacketReal((uint8_t *)"A",1,IPPROTO_TCP, "1.1.1.1", "2.2.2.2", 1024, 80); + p = UTHBuildPacketReal((uint8_t *)"A", 1, IPPROTO_TCP, "1.1.1.1", "2.2.2.2", 1024, 80); DetectEngineCtx *de_ctx = DetectEngineCtxInit(); if (de_ctx == NULL) { @@ -1022,7 +1044,8 @@ static int DetectThresholdTestSig7(void) de_ctx->flags |= DE_QUIET; - s = de_ctx->sig_list = SigInit(de_ctx,"drop tcp any any -> any 80 (threshold: type limit, track by_src, count 1, seconds 300; sid:10;)"); + s = de_ctx->sig_list = SigInit(de_ctx, "drop tcp any any -> any 80 (threshold: type limit, " + "track by_src, count 1, seconds 300; sid:10;)"); if (s == NULL) { goto end; } @@ -1103,7 +1126,7 @@ static int DetectThresholdTestSig8(void) memset(&th_v, 0, sizeof(th_v)); - p = UTHBuildPacketReal((uint8_t *)"A",1,IPPROTO_TCP, "1.1.1.1", "2.2.2.2", 1024, 80); + p = UTHBuildPacketReal((uint8_t *)"A", 1, IPPROTO_TCP, "1.1.1.1", "2.2.2.2", 1024, 80); DetectEngineCtx *de_ctx = DetectEngineCtxInit(); if (de_ctx == NULL) { @@ -1112,7 +1135,8 @@ static int DetectThresholdTestSig8(void) de_ctx->flags |= DE_QUIET; - s = de_ctx->sig_list = SigInit(de_ctx,"drop tcp any any -> any 80 (threshold: type limit, track by_src, count 2, seconds 300; sid:10;)"); + s = de_ctx->sig_list = SigInit(de_ctx, "drop tcp any any -> any 80 (threshold: type limit, " + "track by_src, count 2, seconds 300; sid:10;)"); if (s == NULL) { goto end; } @@ -1193,7 +1217,7 @@ static int DetectThresholdTestSig9(void) memset(&th_v, 0, sizeof(th_v)); - p = UTHBuildPacketReal((uint8_t *)"A",1,IPPROTO_TCP, "1.1.1.1", "2.2.2.2", 1024, 80); + p = UTHBuildPacketReal((uint8_t *)"A", 1, IPPROTO_TCP, "1.1.1.1", "2.2.2.2", 1024, 80); DetectEngineCtx *de_ctx = DetectEngineCtxInit(); if (de_ctx == NULL) { @@ -1202,7 +1226,8 @@ static int DetectThresholdTestSig9(void) de_ctx->flags |= DE_QUIET; - s = de_ctx->sig_list = SigInit(de_ctx,"drop tcp any any -> any 80 (threshold: type threshold, track by_src, count 3, seconds 100; sid:10;)"); + s = de_ctx->sig_list = SigInit(de_ctx, "drop tcp any any -> any 80 (threshold: type threshold, " + "track by_src, count 3, seconds 100; sid:10;)"); if (s == NULL) { goto end; } @@ -1283,7 +1308,7 @@ static int DetectThresholdTestSig10(void) memset(&th_v, 0, sizeof(th_v)); - p = UTHBuildPacketReal((uint8_t *)"A",1,IPPROTO_TCP, "1.1.1.1", "2.2.2.2", 1024, 80); + p = UTHBuildPacketReal((uint8_t *)"A", 1, IPPROTO_TCP, "1.1.1.1", "2.2.2.2", 1024, 80); DetectEngineCtx *de_ctx = DetectEngineCtxInit(); if (de_ctx == NULL) { @@ -1292,7 +1317,8 @@ static int DetectThresholdTestSig10(void) de_ctx->flags |= DE_QUIET; - s = de_ctx->sig_list = SigInit(de_ctx,"drop tcp any any -> any 80 (threshold: type threshold, track by_src, count 5, seconds 300; sid:10;)"); + s = de_ctx->sig_list = SigInit(de_ctx, "drop tcp any any -> any 80 (threshold: type threshold, " + "track by_src, count 5, seconds 300; sid:10;)"); if (s == NULL) { goto end; } @@ -1373,7 +1399,7 @@ static int DetectThresholdTestSig11(void) memset(&th_v, 0, sizeof(th_v)); - p = UTHBuildPacketReal((uint8_t *)"A",1,IPPROTO_TCP, "1.1.1.1", "2.2.2.2", 1024, 80); + p = UTHBuildPacketReal((uint8_t *)"A", 1, IPPROTO_TCP, "1.1.1.1", "2.2.2.2", 1024, 80); DetectEngineCtx *de_ctx = DetectEngineCtxInit(); if (de_ctx == NULL) { @@ -1382,7 +1408,8 @@ static int DetectThresholdTestSig11(void) de_ctx->flags |= DE_QUIET; - s = de_ctx->sig_list = SigInit(de_ctx,"drop tcp any any -> any 80 (threshold: type both, track by_src, count 3, seconds 300; sid:10;)"); + s = de_ctx->sig_list = SigInit(de_ctx, "drop tcp any any -> any 80 (threshold: type both, " + "track by_src, count 3, seconds 300; sid:10;)"); if (s == NULL) { goto end; } @@ -1463,7 +1490,7 @@ static int DetectThresholdTestSig12(void) memset(&th_v, 0, sizeof(th_v)); - p = UTHBuildPacketReal((uint8_t *)"A",1,IPPROTO_TCP, "1.1.1.1", "2.2.2.2", 1024, 80); + p = UTHBuildPacketReal((uint8_t *)"A", 1, IPPROTO_TCP, "1.1.1.1", "2.2.2.2", 1024, 80); DetectEngineCtx *de_ctx = DetectEngineCtxInit(); if (de_ctx == NULL) { @@ -1472,7 +1499,8 @@ static int DetectThresholdTestSig12(void) de_ctx->flags |= DE_QUIET; - s = de_ctx->sig_list = SigInit(de_ctx,"drop tcp any any -> any 80 (threshold: type both, track by_src, count 5, seconds 300; sid:10;)"); + s = de_ctx->sig_list = SigInit(de_ctx, "drop tcp any any -> any 80 (threshold: type both, " + "track by_src, count 5, seconds 300; sid:10;)"); if (s == NULL) { goto end; } @@ -1528,7 +1556,7 @@ static int DetectThresholdTestSig12(void) SigGroupCleanup(de_ctx); SigCleanSignatures(de_ctx); - DetectEngineThreadCtxDeinit(&th_v, (void*)det_ctx); + DetectEngineThreadCtxDeinit(&th_v, (void *)det_ctx); DetectEngineCtxFree(de_ctx); end: UTHFreePackets(&p, 1); @@ -1556,7 +1584,7 @@ static int DetectThresholdTestSig13(void) HostInitConfig(HOST_QUIET); memset(&th_v, 0, sizeof(th_v)); - p = UTHBuildPacketReal((uint8_t *)"A",1,IPPROTO_TCP, "1.1.1.1", "2.2.2.2", 1024, 80); + p = UTHBuildPacketReal((uint8_t *)"A", 1, IPPROTO_TCP, "1.1.1.1", "2.2.2.2", 1024, 80); FAIL_IF_NULL(p); DetectEngineCtx *de_ctx = DetectEngineCtxInit(); @@ -1564,7 +1592,9 @@ static int DetectThresholdTestSig13(void) de_ctx->flags |= DE_QUIET; - s = de_ctx->sig_list = SigInit(de_ctx,"alert tcp any any -> any 80 (msg:\"Threshold limit sid 1\"; threshold: type limit, track by_rule, count 2, seconds 60; sid:1;)"); + s = de_ctx->sig_list = + SigInit(de_ctx, "alert tcp any any -> any 80 (msg:\"Threshold limit sid 1\"; " + "threshold: type limit, track by_rule, count 2, seconds 60; sid:1;)"); FAIL_IF_NULL(s); SigGroupBuild(de_ctx); @@ -1628,8 +1658,8 @@ static int DetectThresholdTestSig14(void) IPPairInitConfig(IPPAIR_QUIET); memset(&th_v, 0, sizeof(th_v)); - p1 = UTHBuildPacketReal((uint8_t *)"A",1,IPPROTO_TCP, "1.1.1.1", "2.2.2.2", 1024, 80); - p2 = UTHBuildPacketReal((uint8_t *)"A",1,IPPROTO_TCP, "1.1.1.1", "3.3.3.3", 1024, 80); + p1 = UTHBuildPacketReal((uint8_t *)"A", 1, IPPROTO_TCP, "1.1.1.1", "2.2.2.2", 1024, 80); + p2 = UTHBuildPacketReal((uint8_t *)"A", 1, IPPROTO_TCP, "1.1.1.1", "3.3.3.3", 1024, 80); FAIL_IF_NULL(p1); FAIL_IF_NULL(p2); @@ -1638,7 +1668,9 @@ static int DetectThresholdTestSig14(void) de_ctx->flags |= DE_QUIET; - s = de_ctx->sig_list = SigInit(de_ctx,"alert tcp any any -> any 80 (msg:\"Threshold limit sid 1\"; threshold: type limit, track by_both, count 2, seconds 60; sid:1;)"); + s = de_ctx->sig_list = + SigInit(de_ctx, "alert tcp any any -> any 80 (msg:\"Threshold limit sid 1\"; " + "threshold: type limit, track by_both, count 2, seconds 60; sid:1;)"); FAIL_IF_NULL(s); SigGroupBuild(de_ctx); @@ -1703,8 +1735,7 @@ static void ThresholdRegisterTests(void) UtRegisterTest("DetectThresholdTestSig3", DetectThresholdTestSig3); UtRegisterTest("DetectThresholdTestSig4", DetectThresholdTestSig4); UtRegisterTest("DetectThresholdTestSig5", DetectThresholdTestSig5); - UtRegisterTest("DetectThresholdTestSig6Ticks", - DetectThresholdTestSig6Ticks); + UtRegisterTest("DetectThresholdTestSig6Ticks", DetectThresholdTestSig6Ticks); UtRegisterTest("DetectThresholdTestSig7", DetectThresholdTestSig7); UtRegisterTest("DetectThresholdTestSig8", DetectThresholdTestSig8); UtRegisterTest("DetectThresholdTestSig9", DetectThresholdTestSig9); diff --git a/src/detect-threshold.h b/src/detect-threshold.h index 751c0e1ac762..55c9548cd7c8 100644 --- a/src/detect-threshold.h +++ b/src/detect-threshold.h @@ -24,7 +24,6 @@ #ifndef __DETECT_THRESHOLD_H__ #define __DETECT_THRESHOLD_H__ - #define TYPE_LIMIT 1 #define TYPE_BOTH 2 #define TYPE_THRESHOLD 3 @@ -32,19 +31,19 @@ #define TYPE_RATE 5 #define TYPE_SUPPRESS 6 -#define TRACK_DST 1 -#define TRACK_SRC 2 -#define TRACK_RULE 3 -#define TRACK_EITHER 4 /**< either src or dst: only used by suppress */ -#define TRACK_BOTH 5 /* used by rate_filter to match detections by both src and dst addresses */ +#define TRACK_DST 1 +#define TRACK_SRC 2 +#define TRACK_RULE 3 +#define TRACK_EITHER 4 /**< either src or dst: only used by suppress */ +#define TRACK_BOTH 5 /* used by rate_filter to match detections by both src and dst addresses */ /* Get the new action to take */ -#define TH_ACTION_ALERT 0x01 -#define TH_ACTION_DROP 0x02 -#define TH_ACTION_PASS 0x04 -#define TH_ACTION_LOG 0x08 -#define TH_ACTION_SDROP 0x10 -#define TH_ACTION_REJECT 0x20 +#define TH_ACTION_ALERT 0x01 +#define TH_ACTION_DROP 0x02 +#define TH_ACTION_PASS 0x04 +#define TH_ACTION_LOG 0x08 +#define TH_ACTION_SDROP 0x10 +#define TH_ACTION_REJECT 0x20 /** * \typedef DetectThresholdData @@ -63,20 +62,19 @@ typedef struct DetectThresholdData_ { } DetectThresholdData; typedef struct DetectThresholdEntry_ { - uint32_t sid; /**< Signature id */ - uint32_t gid; /**< Signature group id */ + uint32_t sid; /**< Signature id */ + uint32_t gid; /**< Signature group id */ uint32_t tv_timeout; /**< Timeout for new_action (for rate_filter) its not "seconds", that define the time interval */ uint32_t seconds; /**< Event seconds */ uint32_t current_count; /**< Var for count control */ - int track; /**< Track type: by_src, by_src */ + int track; /**< Track type: by_src, by_src */ SCTime_t tv1; /**< Var for time control */ struct DetectThresholdEntry_ *next; } DetectThresholdEntry; - /** * Registration function for threshold: keyword */ diff --git a/src/detect-tls-cert-fingerprint.c b/src/detect-tls-cert-fingerprint.c index 98ba46143db4..584ee48d2bae 100644 --- a/src/detect-tls-cert-fingerprint.c +++ b/src/detect-tls-cert-fingerprint.c @@ -57,13 +57,10 @@ static int DetectTlsFingerprintSetup(DetectEngineCtx *, Signature *, const char static void DetectTlsFingerprintRegisterTests(void); #endif static InspectionBuffer *GetData(DetectEngineThreadCtx *det_ctx, - const DetectEngineTransforms *transforms, - Flow *f, const uint8_t flow_flags, - void *txv, const int list_id); -static void DetectTlsFingerprintSetupCallback(const DetectEngineCtx *de_ctx, - Signature *s); -static bool DetectTlsFingerprintValidateCallback(const Signature *s, - const char **sigerror); + const DetectEngineTransforms *transforms, Flow *f, const uint8_t flow_flags, void *txv, + const int list_id); +static void DetectTlsFingerprintSetupCallback(const DetectEngineCtx *de_ctx, Signature *s); +static bool DetectTlsFingerprintValidateCallback(const Signature *s, const char **sigerror); static int g_tls_cert_fingerprint_buffer_id = 0; /** @@ -75,21 +72,21 @@ void DetectTlsFingerprintRegister(void) sigmatch_table[DETECT_AL_TLS_CERT_FINGERPRINT].alias = "tls_cert_fingerprint"; sigmatch_table[DETECT_AL_TLS_CERT_FINGERPRINT].desc = "sticky buffer to match the TLS cert fingerprint buffer"; - sigmatch_table[DETECT_AL_TLS_CERT_FINGERPRINT].url = "/rules/tls-keywords.html#tls-cert-fingerprint"; + sigmatch_table[DETECT_AL_TLS_CERT_FINGERPRINT].url = + "/rules/tls-keywords.html#tls-cert-fingerprint"; sigmatch_table[DETECT_AL_TLS_CERT_FINGERPRINT].Setup = DetectTlsFingerprintSetup; #ifdef UNITTESTS - sigmatch_table[DETECT_AL_TLS_CERT_FINGERPRINT].RegisterTests = DetectTlsFingerprintRegisterTests; + sigmatch_table[DETECT_AL_TLS_CERT_FINGERPRINT].RegisterTests = + DetectTlsFingerprintRegisterTests; #endif sigmatch_table[DETECT_AL_TLS_CERT_FINGERPRINT].flags |= SIGMATCH_NOOPT; sigmatch_table[DETECT_AL_TLS_CERT_FINGERPRINT].flags |= SIGMATCH_INFO_STICKY_BUFFER; - DetectAppLayerInspectEngineRegister2("tls.cert_fingerprint", ALPROTO_TLS, - SIG_FLAG_TOCLIENT, TLS_STATE_CERT_READY, - DetectEngineInspectBufferGeneric, GetData); + DetectAppLayerInspectEngineRegister2("tls.cert_fingerprint", ALPROTO_TLS, SIG_FLAG_TOCLIENT, + TLS_STATE_CERT_READY, DetectEngineInspectBufferGeneric, GetData); DetectAppLayerMpmRegister2("tls.cert_fingerprint", SIG_FLAG_TOCLIENT, 2, - PrefilterGenericMpmRegister, GetData, ALPROTO_TLS, - TLS_STATE_CERT_READY); + PrefilterGenericMpmRegister, GetData, ALPROTO_TLS, TLS_STATE_CERT_READY); DetectAppLayerInspectEngineRegister2("tls.cert_fingerprint", ALPROTO_TLS, SIG_FLAG_TOSERVER, TLS_STATE_CERT_READY, DetectEngineInspectBufferGeneric, GetData); @@ -97,14 +94,13 @@ void DetectTlsFingerprintRegister(void) DetectAppLayerMpmRegister2("tls.cert_fingerprint", SIG_FLAG_TOSERVER, 2, PrefilterGenericMpmRegister, GetData, ALPROTO_TLS, TLS_STATE_CERT_READY); - DetectBufferTypeSetDescriptionByName("tls.cert_fingerprint", - "TLS certificate fingerprint"); + DetectBufferTypeSetDescriptionByName("tls.cert_fingerprint", "TLS certificate fingerprint"); - DetectBufferTypeRegisterSetupCallback("tls.cert_fingerprint", - DetectTlsFingerprintSetupCallback); + DetectBufferTypeRegisterSetupCallback( + "tls.cert_fingerprint", DetectTlsFingerprintSetupCallback); - DetectBufferTypeRegisterValidateCallback("tls.cert_fingerprint", - DetectTlsFingerprintValidateCallback); + DetectBufferTypeRegisterValidateCallback( + "tls.cert_fingerprint", DetectTlsFingerprintValidateCallback); g_tls_cert_fingerprint_buffer_id = DetectBufferTypeGetByName("tls.cert_fingerprint"); } @@ -119,8 +115,7 @@ void DetectTlsFingerprintRegister(void) * \retval 0 On success * \retval -1 On failure */ -static int DetectTlsFingerprintSetup(DetectEngineCtx *de_ctx, Signature *s, - const char *str) +static int DetectTlsFingerprintSetup(DetectEngineCtx *de_ctx, Signature *s, const char *str) { if (DetectBufferSetActiveList(de_ctx, s, g_tls_cert_fingerprint_buffer_id) < 0) return -1; @@ -132,8 +127,8 @@ static int DetectTlsFingerprintSetup(DetectEngineCtx *de_ctx, Signature *s, } static InspectionBuffer *GetData(DetectEngineThreadCtx *det_ctx, - const DetectEngineTransforms *transforms, Flow *f, - const uint8_t flow_flags, void *txv, const int list_id) + const DetectEngineTransforms *transforms, Flow *f, const uint8_t flow_flags, void *txv, + const int list_id) { InspectionBuffer *buffer = InspectionBufferGet(det_ctx, list_id); if (buffer->inspect == NULL) { @@ -160,8 +155,7 @@ static InspectionBuffer *GetData(DetectEngineThreadCtx *det_ctx, return buffer; } -static bool DetectTlsFingerprintValidateCallback(const Signature *s, - const char **sigerror) +static bool DetectTlsFingerprintValidateCallback(const Signature *s, const char **sigerror) { for (uint32_t x = 0; x < s->init_data->buffer_index; x++) { if (s->init_data->buffers[x].id != (uint32_t)g_tls_cert_fingerprint_buffer_id) @@ -208,8 +202,7 @@ static bool DetectTlsFingerprintValidateCallback(const Signature *s, return true; } -static void DetectTlsFingerprintSetupCallback(const DetectEngineCtx *de_ctx, - Signature *s) +static void DetectTlsFingerprintSetupCallback(const DetectEngineCtx *de_ctx, Signature *s) { for (uint32_t x = 0; x < s->init_data->buffer_index; x++) { if (s->init_data->buffers[x].id != (uint32_t)g_tls_cert_fingerprint_buffer_id) diff --git a/src/detect-tls-cert-issuer.c b/src/detect-tls-cert-issuer.c index 9146f8d0f40b..97c0de9341f0 100644 --- a/src/detect-tls-cert-issuer.c +++ b/src/detect-tls-cert-issuer.c @@ -57,9 +57,8 @@ static int DetectTlsIssuerSetup(DetectEngineCtx *, Signature *, const char *); static void DetectTlsIssuerRegisterTests(void); #endif static InspectionBuffer *GetData(DetectEngineThreadCtx *det_ctx, - const DetectEngineTransforms *transforms, - Flow *f, const uint8_t flow_flags, - void *txv, const int list_id); + const DetectEngineTransforms *transforms, Flow *f, const uint8_t flow_flags, void *txv, + const int list_id); static int g_tls_cert_issuer_buffer_id = 0; /** @@ -85,21 +84,17 @@ void DetectTlsIssuerRegister(void) DetectAppLayerMpmRegister2("tls.cert_issuer", SIG_FLAG_TOSERVER, 2, PrefilterGenericMpmRegister, GetData, ALPROTO_TLS, TLS_STATE_CERT_READY); - DetectAppLayerInspectEngineRegister2("tls.cert_issuer", ALPROTO_TLS, - SIG_FLAG_TOCLIENT, TLS_STATE_CERT_READY, - DetectEngineInspectBufferGeneric, GetData); + DetectAppLayerInspectEngineRegister2("tls.cert_issuer", ALPROTO_TLS, SIG_FLAG_TOCLIENT, + TLS_STATE_CERT_READY, DetectEngineInspectBufferGeneric, GetData); - DetectAppLayerMpmRegister2("tls.cert_issuer", SIG_FLAG_TOCLIENT, 2, - PrefilterGenericMpmRegister, GetData, ALPROTO_TLS, - TLS_STATE_CERT_READY); + DetectAppLayerMpmRegister2("tls.cert_issuer", SIG_FLAG_TOCLIENT, 2, PrefilterGenericMpmRegister, + GetData, ALPROTO_TLS, TLS_STATE_CERT_READY); - DetectBufferTypeSetDescriptionByName("tls.cert_issuer", - "TLS certificate issuer"); + DetectBufferTypeSetDescriptionByName("tls.cert_issuer", "TLS certificate issuer"); g_tls_cert_issuer_buffer_id = DetectBufferTypeGetByName("tls.cert_issuer"); } - /** * \brief this function setup the tls_cert_issuer modifier keyword used in the rule * @@ -122,8 +117,8 @@ static int DetectTlsIssuerSetup(DetectEngineCtx *de_ctx, Signature *s, const cha } static InspectionBuffer *GetData(DetectEngineThreadCtx *det_ctx, - const DetectEngineTransforms *transforms, Flow *f, - const uint8_t flow_flags, void *txv, const int list_id) + const DetectEngineTransforms *transforms, Flow *f, const uint8_t flow_flags, void *txv, + const int list_id) { InspectionBuffer *buffer = InspectionBufferGet(det_ctx, list_id); if (buffer->inspect == NULL) { diff --git a/src/detect-tls-cert-issuer.h b/src/detect-tls-cert-issuer.h index fdfda510da26..4fbe9c6557ef 100644 --- a/src/detect-tls-cert-issuer.h +++ b/src/detect-tls-cert-issuer.h @@ -24,7 +24,6 @@ #ifndef __DETECT_TLS_ISSUER_H__ #define __DETECT_TLS_ISSUER_H__ - void DetectTlsIssuerRegister(void); #endif /* __DETECT_TLS_ISSUER_H__ */ diff --git a/src/detect-tls-cert-serial.c b/src/detect-tls-cert-serial.c index 19c86be80e24..a44762e2fcb0 100644 --- a/src/detect-tls-cert-serial.c +++ b/src/detect-tls-cert-serial.c @@ -57,13 +57,10 @@ static int DetectTlsSerialSetup(DetectEngineCtx *, Signature *, const char *); static void DetectTlsSerialRegisterTests(void); #endif static InspectionBuffer *GetData(DetectEngineThreadCtx *det_ctx, - const DetectEngineTransforms *transforms, - Flow *f, const uint8_t flow_flags, - void *txv, const int list_id); -static void DetectTlsSerialSetupCallback(const DetectEngineCtx *de_ctx, - Signature *s); -static bool DetectTlsSerialValidateCallback(const Signature *s, - const char **sigerror); + const DetectEngineTransforms *transforms, Flow *f, const uint8_t flow_flags, void *txv, + const int list_id); +static void DetectTlsSerialSetupCallback(const DetectEngineCtx *de_ctx, Signature *s); +static bool DetectTlsSerialValidateCallback(const Signature *s, const char **sigerror); static int g_tls_cert_serial_buffer_id = 0; /** @@ -83,13 +80,11 @@ void DetectTlsSerialRegister(void) sigmatch_table[DETECT_AL_TLS_CERT_SERIAL].flags |= SIGMATCH_NOOPT; sigmatch_table[DETECT_AL_TLS_CERT_SERIAL].flags |= SIGMATCH_INFO_STICKY_BUFFER; - DetectAppLayerInspectEngineRegister2("tls.cert_serial", ALPROTO_TLS, - SIG_FLAG_TOCLIENT, TLS_STATE_CERT_READY, - DetectEngineInspectBufferGeneric, GetData); + DetectAppLayerInspectEngineRegister2("tls.cert_serial", ALPROTO_TLS, SIG_FLAG_TOCLIENT, + TLS_STATE_CERT_READY, DetectEngineInspectBufferGeneric, GetData); - DetectAppLayerMpmRegister2("tls.cert_serial", SIG_FLAG_TOCLIENT, 2, - PrefilterGenericMpmRegister, GetData, ALPROTO_TLS, - TLS_STATE_CERT_READY); + DetectAppLayerMpmRegister2("tls.cert_serial", SIG_FLAG_TOCLIENT, 2, PrefilterGenericMpmRegister, + GetData, ALPROTO_TLS, TLS_STATE_CERT_READY); DetectAppLayerInspectEngineRegister2("tls.cert_serial", ALPROTO_TLS, SIG_FLAG_TOSERVER, TLS_STATE_CERT_READY, DetectEngineInspectBufferGeneric, GetData); @@ -97,14 +92,11 @@ void DetectTlsSerialRegister(void) DetectAppLayerMpmRegister2("tls.cert_serial", SIG_FLAG_TOSERVER, 2, PrefilterGenericMpmRegister, GetData, ALPROTO_TLS, TLS_STATE_CERT_READY); - DetectBufferTypeSetDescriptionByName("tls.cert_serial", - "TLS certificate serial number"); + DetectBufferTypeSetDescriptionByName("tls.cert_serial", "TLS certificate serial number"); - DetectBufferTypeRegisterSetupCallback("tls.cert_serial", - DetectTlsSerialSetupCallback); + DetectBufferTypeRegisterSetupCallback("tls.cert_serial", DetectTlsSerialSetupCallback); - DetectBufferTypeRegisterValidateCallback("tls.cert_serial", - DetectTlsSerialValidateCallback); + DetectBufferTypeRegisterValidateCallback("tls.cert_serial", DetectTlsSerialValidateCallback); g_tls_cert_serial_buffer_id = DetectBufferTypeGetByName("tls.cert_serial"); } @@ -131,8 +123,8 @@ static int DetectTlsSerialSetup(DetectEngineCtx *de_ctx, Signature *s, const cha } static InspectionBuffer *GetData(DetectEngineThreadCtx *det_ctx, - const DetectEngineTransforms *transforms, Flow *f, - const uint8_t flow_flags, void *txv, const int list_id) + const DetectEngineTransforms *transforms, Flow *f, const uint8_t flow_flags, void *txv, + const int list_id) { InspectionBuffer *buffer = InspectionBufferGet(det_ctx, list_id); if (buffer->inspect == NULL) { @@ -159,8 +151,7 @@ static InspectionBuffer *GetData(DetectEngineThreadCtx *det_ctx, return buffer; } -static bool DetectTlsSerialValidateCallback(const Signature *s, - const char **sigerror) +static bool DetectTlsSerialValidateCallback(const Signature *s, const char **sigerror) { for (uint32_t x = 0; x < s->init_data->buffer_index; x++) { if (s->init_data->buffers[x].id != (uint32_t)g_tls_cert_serial_buffer_id) @@ -199,8 +190,7 @@ static bool DetectTlsSerialValidateCallback(const Signature *s, return true; } -static void DetectTlsSerialSetupCallback(const DetectEngineCtx *de_ctx, - Signature *s) +static void DetectTlsSerialSetupCallback(const DetectEngineCtx *de_ctx, Signature *s) { for (uint32_t x = 0; x < s->init_data->buffer_index; x++) { if (s->init_data->buffers[x].id != (uint32_t)g_tls_cert_serial_buffer_id) diff --git a/src/detect-tls-cert-serial.h b/src/detect-tls-cert-serial.h index 9fe018e90872..4fcc89b06a0a 100644 --- a/src/detect-tls-cert-serial.h +++ b/src/detect-tls-cert-serial.h @@ -25,6 +25,6 @@ #define __DETECT_TLS_CERT_SERIAL_H__ /* prototypes */ -void DetectTlsSerialRegister (void); +void DetectTlsSerialRegister(void); #endif /* __DETECT_TLS_CERT_SERIAL_H__ */ diff --git a/src/detect-tls-cert-subject.c b/src/detect-tls-cert-subject.c index 9ec7fb96fb1f..dca7f50536b2 100644 --- a/src/detect-tls-cert-subject.c +++ b/src/detect-tls-cert-subject.c @@ -57,9 +57,8 @@ static int DetectTlsSubjectSetup(DetectEngineCtx *, Signature *, const char *); static void DetectTlsSubjectRegisterTests(void); #endif static InspectionBuffer *GetData(DetectEngineThreadCtx *det_ctx, - const DetectEngineTransforms *transforms, - Flow *f, const uint8_t flow_flags, - void *txv, const int list_id); + const DetectEngineTransforms *transforms, Flow *f, const uint8_t flow_flags, void *txv, + const int list_id); static int g_tls_cert_subject_buffer_id = 0; /** @@ -89,13 +88,11 @@ void DetectTlsSubjectRegister(void) TLS_STATE_CERT_READY, DetectEngineInspectBufferGeneric, GetData); DetectAppLayerMpmRegister2("tls.cert_subject", SIG_FLAG_TOCLIENT, 2, - PrefilterGenericMpmRegister, GetData, ALPROTO_TLS, - TLS_STATE_CERT_READY); + PrefilterGenericMpmRegister, GetData, ALPROTO_TLS, TLS_STATE_CERT_READY); DetectBufferTypeSupportsMultiInstance("tls.cert_subject"); - DetectBufferTypeSetDescriptionByName("tls.cert_subject", - "TLS certificate subject"); + DetectBufferTypeSetDescriptionByName("tls.cert_subject", "TLS certificate subject"); g_tls_cert_subject_buffer_id = DetectBufferTypeGetByName("tls.cert_subject"); } @@ -122,8 +119,8 @@ static int DetectTlsSubjectSetup(DetectEngineCtx *de_ctx, Signature *s, const ch } static InspectionBuffer *GetData(DetectEngineThreadCtx *det_ctx, - const DetectEngineTransforms *transforms, Flow *f, - const uint8_t flow_flags, void *txv, const int list_id) + const DetectEngineTransforms *transforms, Flow *f, const uint8_t flow_flags, void *txv, + const int list_id) { InspectionBuffer *buffer = InspectionBufferGet(det_ctx, list_id); if (buffer->inspect == NULL) { diff --git a/src/detect-tls-cert-subject.h b/src/detect-tls-cert-subject.h index 23f3e77859c7..abe7d6e229da 100644 --- a/src/detect-tls-cert-subject.h +++ b/src/detect-tls-cert-subject.h @@ -24,7 +24,6 @@ #ifndef __DETECT_TLS_SUBJECT_H__ #define __DETECT_TLS_SUBJECT_H__ - void DetectTlsSubjectRegister(void); #endif /* __DETECT_TLS_SUBJECT_H__ */ diff --git a/src/detect-tls-cert-validity.c b/src/detect-tls-cert-validity.c index 3720d287db5c..8b18e0f227a1 100644 --- a/src/detect-tls-cert-validity.c +++ b/src/detect-tls-cert-validity.c @@ -54,17 +54,16 @@ #define PARSE_REGEX "^\\s*(<|>)?\\s*([ -:TW0-9]+)\\s*(?:(<>)\\s*([ -:TW0-9]+))?\\s*$" static DetectParseRegex parse_regex; -static int DetectTlsValidityMatch (DetectEngineThreadCtx *, Flow *, - uint8_t, void *, void *, const Signature *, - const SigMatchCtx *); - -static time_t DateStringToEpoch (char *); -static DetectTlsValidityData *DetectTlsValidityParse (const char *); -static int DetectTlsExpiredSetup (DetectEngineCtx *, Signature *s, const char *str); -static int DetectTlsValidSetup (DetectEngineCtx *, Signature *s, const char *str); -static int DetectTlsNotBeforeSetup (DetectEngineCtx *, Signature *s, const char *str); -static int DetectTlsNotAfterSetup (DetectEngineCtx *, Signature *s, const char *str); -static int DetectTlsValiditySetup (DetectEngineCtx *, Signature *s, const char *str, uint8_t); +static int DetectTlsValidityMatch(DetectEngineThreadCtx *, Flow *, uint8_t, void *, void *, + const Signature *, const SigMatchCtx *); + +static time_t DateStringToEpoch(char *); +static DetectTlsValidityData *DetectTlsValidityParse(const char *); +static int DetectTlsExpiredSetup(DetectEngineCtx *, Signature *s, const char *str); +static int DetectTlsValidSetup(DetectEngineCtx *, Signature *s, const char *str); +static int DetectTlsNotBeforeSetup(DetectEngineCtx *, Signature *s, const char *str); +static int DetectTlsNotAfterSetup(DetectEngineCtx *, Signature *s, const char *str); +static int DetectTlsValiditySetup(DetectEngineCtx *, Signature *s, const char *str, uint8_t); #ifdef UNITTESTS static void TlsNotBeforeRegisterTests(void); static void TlsNotAfterRegisterTests(void); @@ -77,7 +76,7 @@ static int g_tls_validity_buffer_id = 0; /** * \brief Registration function for tls validity keywords. */ -void DetectTlsValidityRegister (void) +void DetectTlsValidityRegister(void) { sigmatch_table[DETECT_AL_TLS_NOTBEFORE].name = "tls_cert_notbefore"; sigmatch_table[DETECT_AL_TLS_NOTBEFORE].desc = "match TLS certificate notBefore field"; @@ -145,10 +144,8 @@ void DetectTlsValidityRegister (void) * \retval 0 no match. * \retval 1 match. */ -static int DetectTlsValidityMatch (DetectEngineThreadCtx *det_ctx, - Flow *f, uint8_t flags, void *state, - void *txv, const Signature *s, - const SigMatchCtx *ctx) +static int DetectTlsValidityMatch(DetectEngineThreadCtx *det_ctx, Flow *f, uint8_t flags, + void *state, void *txv, const Signature *s, const SigMatchCtx *ctx) { SCEnter(); @@ -183,8 +180,8 @@ static int DetectTlsValidityMatch (DetectEngineThreadCtx *det_ctx, ret = 1; else if ((dd->mode & DETECT_TLS_VALIDITY_GT) && cert_epoch >= dd->epoch) ret = 1; - else if ((dd->mode & DETECT_TLS_VALIDITY_RA) && - cert_epoch >= dd->epoch && cert_epoch <= dd->epoch2) + else if ((dd->mode & DETECT_TLS_VALIDITY_RA) && cert_epoch >= dd->epoch && + cert_epoch <= dd->epoch2) ret = 1; else if ((dd->mode & DETECT_TLS_VALIDITY_EX) && (time_t)SCTIME_SECS(f->lastts) > cert_epoch) ret = 1; @@ -203,7 +200,7 @@ static int DetectTlsValidityMatch (DetectEngineThreadCtx *det_ctx, * \retval epoch time on success. * \retval LONG_MIN on failure. */ -static time_t StringIsEpoch (char *string) +static time_t StringIsEpoch(char *string) { if (strlen(string) == 0) return LONG_MIN; @@ -228,22 +225,22 @@ static time_t StringIsEpoch (char *string) * \retval epoch on success. * \retval 0 on failure. */ -static time_t DateStringToEpoch (char *string) +static time_t DateStringToEpoch(char *string) { int r = 0; struct tm tm; const char *patterns[] = { - /* ISO 8601 */ - "%Y-%m", - "%Y-%m-%d", - "%Y-%m-%d %H", - "%Y-%m-%d %H:%M", - "%Y-%m-%d %H:%M:%S", - "%Y-%m-%dT%H", - "%Y-%m-%dT%H:%M", - "%Y-%m-%dT%H:%M:%S", - "%H:%M", - "%H:%M:%S", + /* ISO 8601 */ + "%Y-%m", + "%Y-%m-%d", + "%Y-%m-%d %H", + "%Y-%m-%d %H:%M", + "%Y-%m-%d %H:%M:%S", + "%Y-%m-%dT%H", + "%Y-%m-%dT%H:%M", + "%Y-%m-%dT%H:%M:%S", + "%H:%M", + "%H:%M:%S", }; /* Skip leading whitespace. */ @@ -287,7 +284,7 @@ static time_t DateStringToEpoch (char *string) * \retval dd pointer to DetectTlsValidityData on success. * \retval NULL on failure. */ -static DetectTlsValidityData *DetectTlsValidityParse (const char *rawstr) +static DetectTlsValidityData *DetectTlsValidityParse(const char *rawstr) { DetectTlsValidityData *dd = NULL; char mode[2] = ""; @@ -410,8 +407,7 @@ static DetectTlsValidityData *DetectTlsValidityParse (const char *rawstr) * \retval 0 on Success. * \retval -1 on Failure. */ -static int DetectTlsExpiredSetup (DetectEngineCtx *de_ctx, Signature *s, - const char *rawstr) +static int DetectTlsExpiredSetup(DetectEngineCtx *de_ctx, Signature *s, const char *rawstr) { DetectTlsValidityData *dd = NULL; @@ -455,8 +451,7 @@ static int DetectTlsExpiredSetup (DetectEngineCtx *de_ctx, Signature *s, * \retval 0 on Success. * \retval -1 on Failure. */ -static int DetectTlsValidSetup (DetectEngineCtx *de_ctx, Signature *s, - const char *rawstr) +static int DetectTlsValidSetup(DetectEngineCtx *de_ctx, Signature *s, const char *rawstr) { DetectTlsValidityData *dd = NULL; @@ -500,8 +495,7 @@ static int DetectTlsValidSetup (DetectEngineCtx *de_ctx, Signature *s, * \retval 0 on Success. * \retval -1 on Failure. */ -static int DetectTlsNotBeforeSetup (DetectEngineCtx *de_ctx, Signature *s, - const char *rawstr) +static int DetectTlsNotBeforeSetup(DetectEngineCtx *de_ctx, Signature *s, const char *rawstr) { uint8_t type = DETECT_TLS_TYPE_NOTBEFORE; int r = DetectTlsValiditySetup(de_ctx, s, rawstr, type); @@ -519,8 +513,7 @@ static int DetectTlsNotBeforeSetup (DetectEngineCtx *de_ctx, Signature *s, * \retval 0 on Success. * \retval -1 on Failure. */ -static int DetectTlsNotAfterSetup (DetectEngineCtx *de_ctx, Signature *s, - const char *rawstr) +static int DetectTlsNotAfterSetup(DetectEngineCtx *de_ctx, Signature *s, const char *rawstr) { uint8_t type = DETECT_TLS_TYPE_NOTAFTER; int r = DetectTlsValiditySetup(de_ctx, s, rawstr, type); @@ -539,8 +532,8 @@ static int DetectTlsNotAfterSetup (DetectEngineCtx *de_ctx, Signature *s, * \retval 0 on Success. * \retval -1 on Failure. */ -static int DetectTlsValiditySetup (DetectEngineCtx *de_ctx, Signature *s, - const char *rawstr, uint8_t type) +static int DetectTlsValiditySetup( + DetectEngineCtx *de_ctx, Signature *s, const char *rawstr, uint8_t type) { DetectTlsValidityData *dd = NULL; @@ -560,11 +553,9 @@ static int DetectTlsValiditySetup (DetectEngineCtx *de_ctx, Signature *s, if (type == DETECT_TLS_TYPE_NOTBEFORE) { dd->type = DETECT_TLS_TYPE_NOTBEFORE; - } - else if (type == DETECT_TLS_TYPE_NOTAFTER) { + } else if (type == DETECT_TLS_TYPE_NOTAFTER) { dd->type = DETECT_TLS_TYPE_NOTAFTER; - } - else { + } else { goto error; } diff --git a/src/detect-tls-cert-validity.h b/src/detect-tls-cert-validity.h index 256be6b4b2b5..8d7b3c88355c 100644 --- a/src/detect-tls-cert-validity.h +++ b/src/detect-tls-cert-validity.h @@ -24,16 +24,16 @@ #ifndef __DETECT_TLS_VALIDITY_H__ #define __DETECT_TLS_VALIDITY_H__ -#define DETECT_TLS_VALIDITY_EQ (1) /* equal */ -#define DETECT_TLS_VALIDITY_LT (1<<1) /* less than */ -#define DETECT_TLS_VALIDITY_GT (1<<2) /* greater than */ -#define DETECT_TLS_VALIDITY_RA (1<<3) /* range */ +#define DETECT_TLS_VALIDITY_EQ (1) /* equal */ +#define DETECT_TLS_VALIDITY_LT (1 << 1) /* less than */ +#define DETECT_TLS_VALIDITY_GT (1 << 2) /* greater than */ +#define DETECT_TLS_VALIDITY_RA (1 << 3) /* range */ /* Used by tls_cert_expired */ -#define DETECT_TLS_VALIDITY_EX (1<<4) /* expired */ +#define DETECT_TLS_VALIDITY_EX (1 << 4) /* expired */ /* Used by tls_cert_valid */ -#define DETECT_TLS_VALIDITY_VA (1<<5) /* valid */ +#define DETECT_TLS_VALIDITY_VA (1 << 5) /* valid */ #define DETECT_TLS_TYPE_NOTBEFORE 0 #define DETECT_TLS_TYPE_NOTAFTER 1 @@ -46,6 +46,6 @@ typedef struct DetectTlsValidityData_ { } DetectTlsValidityData; /* prototypes */ -void DetectTlsValidityRegister (void); +void DetectTlsValidityRegister(void); #endif /* __DETECT_TLS_VALIDITY_H__ */ diff --git a/src/detect-tls-certs.c b/src/detect-tls-certs.c index 9ff185c494d6..7b073fef398c 100644 --- a/src/detect-tls-certs.c +++ b/src/detect-tls-certs.c @@ -93,13 +93,11 @@ void DetectTlsCertsRegister(void) sigmatch_table[DETECT_AL_TLS_CERTS].flags |= SIGMATCH_NOOPT; sigmatch_table[DETECT_AL_TLS_CERTS].flags |= SIGMATCH_INFO_STICKY_BUFFER; - DetectAppLayerInspectEngineRegister2("tls.certs", ALPROTO_TLS, - SIG_FLAG_TOCLIENT, TLS_STATE_CERT_READY, - DetectEngineInspectTlsCerts, NULL); + DetectAppLayerInspectEngineRegister2("tls.certs", ALPROTO_TLS, SIG_FLAG_TOCLIENT, + TLS_STATE_CERT_READY, DetectEngineInspectTlsCerts, NULL); - DetectAppLayerMpmRegister2("tls.certs", SIG_FLAG_TOCLIENT, 2, - PrefilterMpmTlsCertsRegister, NULL, ALPROTO_TLS, - TLS_STATE_CERT_READY); + DetectAppLayerMpmRegister2("tls.certs", SIG_FLAG_TOCLIENT, 2, PrefilterMpmTlsCertsRegister, + NULL, ALPROTO_TLS, TLS_STATE_CERT_READY); DetectAppLayerInspectEngineRegister2("tls.certs", ALPROTO_TLS, SIG_FLAG_TOSERVER, TLS_STATE_CERT_READY, DetectEngineInspectTlsCerts, NULL); @@ -124,8 +122,7 @@ void DetectTlsCertsRegister(void) * \retval 0 On success * \retval -1 On failure */ -static int DetectTlsCertsSetup(DetectEngineCtx *de_ctx, Signature *s, - const char *str) +static int DetectTlsCertsSetup(DetectEngineCtx *de_ctx, Signature *s, const char *str) { if (DetectBufferSetActiveList(de_ctx, s, g_tls_certs_buffer_id) < 0) return -1; @@ -137,8 +134,8 @@ static int DetectTlsCertsSetup(DetectEngineCtx *de_ctx, Signature *s, } static InspectionBuffer *TlsCertsGetData(DetectEngineThreadCtx *det_ctx, - const DetectEngineTransforms *transforms, Flow *f, - struct TlsCertsGetDataArgs *cbdata, int list_id) + const DetectEngineTransforms *transforms, Flow *f, struct TlsCertsGetDataArgs *cbdata, + int list_id) { SCEnter(); @@ -187,10 +184,9 @@ static uint8_t DetectEngineInspectTlsCerts(DetectEngineCtx *de_ctx, DetectEngine struct TlsCertsGetDataArgs cbdata = { 0, NULL }; - while (1) - { - InspectionBuffer *buffer = TlsCertsGetData(det_ctx, transforms, f, - &cbdata, engine->sm_list); + while (1) { + InspectionBuffer *buffer = + TlsCertsGetData(det_ctx, transforms, f, &cbdata, engine->sm_list); if (buffer == NULL || buffer->inspect == NULL) break; @@ -218,10 +214,8 @@ static void PrefilterTxTlsCerts(DetectEngineThreadCtx *det_ctx, const void *pect struct TlsCertsGetDataArgs cbdata = { 0, NULL }; - while (1) - { - InspectionBuffer *buffer = TlsCertsGetData(det_ctx, ctx->transforms, - f, &cbdata, list_id); + while (1) { + InspectionBuffer *buffer = TlsCertsGetData(det_ctx, ctx->transforms, f, &cbdata, list_id); if (buffer == NULL) break; @@ -251,9 +245,8 @@ static int PrefilterMpmTlsCertsRegister(DetectEngineCtx *de_ctx, SigGroupHead *s pectx->mpm_ctx = mpm_ctx; pectx->transforms = &mpm_reg->transforms; - return PrefilterAppendTxEngine(de_ctx, sgh, PrefilterTxTlsCerts, - mpm_reg->app_v2.alproto, mpm_reg->app_v2.tx_min_progress, - pectx, PrefilterMpmTlsCertsFree, mpm_reg->name); + return PrefilterAppendTxEngine(de_ctx, sgh, PrefilterTxTlsCerts, mpm_reg->app_v2.alproto, + mpm_reg->app_v2.tx_min_progress, pectx, PrefilterMpmTlsCertsFree, mpm_reg->name); } static int g_tls_cert_buffer_id = 0; diff --git a/src/detect-tls-ja3-hash.c b/src/detect-tls-ja3-hash.c index 7660fde4c2a0..79084d0dfed4 100644 --- a/src/detect-tls-ja3-hash.c +++ b/src/detect-tls-ja3-hash.c @@ -58,13 +58,10 @@ static int DetectTlsJa3HashSetup(DetectEngineCtx *, Signature *, const char *); static InspectionBuffer *GetData(DetectEngineThreadCtx *det_ctx, - const DetectEngineTransforms *transforms, - Flow *f, const uint8_t flow_flags, - void *txv, const int list_id); -static void DetectTlsJa3HashSetupCallback(const DetectEngineCtx *de_ctx, - Signature *s); -static bool DetectTlsJa3HashValidateCallback(const Signature *s, - const char **sigerror); + const DetectEngineTransforms *transforms, Flow *f, const uint8_t flow_flags, void *txv, + const int list_id); +static void DetectTlsJa3HashSetupCallback(const DetectEngineCtx *de_ctx, Signature *s); +static bool DetectTlsJa3HashValidateCallback(const Signature *s, const char **sigerror); static int g_tls_ja3_hash_buffer_id = 0; /** @@ -83,8 +80,8 @@ void DetectTlsJa3HashRegister(void) DetectAppLayerInspectEngineRegister2("ja3.hash", ALPROTO_TLS, SIG_FLAG_TOSERVER, 0, DetectEngineInspectBufferGeneric, GetData); - DetectAppLayerMpmRegister2("ja3.hash", SIG_FLAG_TOSERVER, 2, - PrefilterGenericMpmRegister, GetData, ALPROTO_TLS, 0); + DetectAppLayerMpmRegister2( + "ja3.hash", SIG_FLAG_TOSERVER, 2, PrefilterGenericMpmRegister, GetData, ALPROTO_TLS, 0); DetectAppLayerMpmRegister2("ja3.hash", SIG_FLAG_TOSERVER, 2, PrefilterGenericMpmRegister, Ja3DetectGetHash, ALPROTO_QUIC, 1); @@ -94,11 +91,9 @@ void DetectTlsJa3HashRegister(void) DetectBufferTypeSetDescriptionByName("ja3.hash", "TLS JA3 hash"); - DetectBufferTypeRegisterSetupCallback("ja3.hash", - DetectTlsJa3HashSetupCallback); + DetectBufferTypeRegisterSetupCallback("ja3.hash", DetectTlsJa3HashSetupCallback); - DetectBufferTypeRegisterValidateCallback("ja3.hash", - DetectTlsJa3HashValidateCallback); + DetectBufferTypeRegisterValidateCallback("ja3.hash", DetectTlsJa3HashValidateCallback); g_tls_ja3_hash_buffer_id = DetectBufferTypeGetByName("ja3.hash"); } @@ -140,8 +135,8 @@ static int DetectTlsJa3HashSetup(DetectEngineCtx *de_ctx, Signature *s, const ch } static InspectionBuffer *GetData(DetectEngineThreadCtx *det_ctx, - const DetectEngineTransforms *transforms, Flow *f, - const uint8_t flow_flags, void *txv, const int list_id) + const DetectEngineTransforms *transforms, Flow *f, const uint8_t flow_flags, void *txv, + const int list_id) { InspectionBuffer *buffer = InspectionBufferGet(det_ctx, list_id); if (buffer->inspect == NULL) { @@ -161,8 +156,7 @@ static InspectionBuffer *GetData(DetectEngineThreadCtx *det_ctx, return buffer; } -static bool DetectTlsJa3HashValidateCallback(const Signature *s, - const char **sigerror) +static bool DetectTlsJa3HashValidateCallback(const Signature *s, const char **sigerror) { for (uint32_t x = 0; x < s->init_data->buffer_index; x++) { if (s->init_data->buffers[x].id != (uint32_t)g_tls_ja3_hash_buffer_id) @@ -194,8 +188,7 @@ static bool DetectTlsJa3HashValidateCallback(const Signature *s, return true; } -static void DetectTlsJa3HashSetupCallback(const DetectEngineCtx *de_ctx, - Signature *s) +static void DetectTlsJa3HashSetupCallback(const DetectEngineCtx *de_ctx, Signature *s) { for (uint32_t x = 0; x < s->init_data->buffer_index; x++) { if (s->init_data->buffers[x].id != (uint32_t)g_tls_ja3_hash_buffer_id) diff --git a/src/detect-tls-ja3-string.c b/src/detect-tls-ja3-string.c index 87a61bfd8738..d5845158817c 100644 --- a/src/detect-tls-ja3-string.c +++ b/src/detect-tls-ja3-string.c @@ -58,9 +58,8 @@ static int DetectTlsJa3StringSetup(DetectEngineCtx *, Signature *, const char *); static InspectionBuffer *GetData(DetectEngineThreadCtx *det_ctx, - const DetectEngineTransforms *transforms, - Flow *f, const uint8_t flow_flags, - void *txv, const int list_id); + const DetectEngineTransforms *transforms, Flow *f, const uint8_t flow_flags, void *txv, + const int list_id); static int g_tls_ja3_str_buffer_id = 0; /** @@ -79,8 +78,8 @@ void DetectTlsJa3StringRegister(void) DetectAppLayerInspectEngineRegister2("ja3.string", ALPROTO_TLS, SIG_FLAG_TOSERVER, 0, DetectEngineInspectBufferGeneric, GetData); - DetectAppLayerMpmRegister2("ja3.string", SIG_FLAG_TOSERVER, 2, - PrefilterGenericMpmRegister, GetData, ALPROTO_TLS, 0); + DetectAppLayerMpmRegister2("ja3.string", SIG_FLAG_TOSERVER, 2, PrefilterGenericMpmRegister, + GetData, ALPROTO_TLS, 0); DetectAppLayerMpmRegister2("ja3.string", SIG_FLAG_TOSERVER, 2, PrefilterGenericMpmRegister, Ja3DetectGetString, ALPROTO_QUIC, 1); @@ -129,8 +128,8 @@ static int DetectTlsJa3StringSetup(DetectEngineCtx *de_ctx, Signature *s, const } static InspectionBuffer *GetData(DetectEngineThreadCtx *det_ctx, - const DetectEngineTransforms *transforms, Flow *f, - const uint8_t flow_flags, void *txv, const int list_id) + const DetectEngineTransforms *transforms, Flow *f, const uint8_t flow_flags, void *txv, + const int list_id) { InspectionBuffer *buffer = InspectionBufferGet(det_ctx, list_id); if (buffer->inspect == NULL) { diff --git a/src/detect-tls-ja3s-hash.c b/src/detect-tls-ja3s-hash.c index 583566012d08..06a6767bb9d2 100644 --- a/src/detect-tls-ja3s-hash.c +++ b/src/detect-tls-ja3s-hash.c @@ -58,13 +58,10 @@ static int DetectTlsJa3SHashSetup(DetectEngineCtx *, Signature *, const char *); static InspectionBuffer *GetData(DetectEngineThreadCtx *det_ctx, - const DetectEngineTransforms *transforms, - Flow *f, const uint8_t flow_flags, - void *txv, const int list_id); -static void DetectTlsJa3SHashSetupCallback(const DetectEngineCtx *de_ctx, - Signature *s); -static bool DetectTlsJa3SHashValidateCallback(const Signature *s, - const char **sigerror); + const DetectEngineTransforms *transforms, Flow *f, const uint8_t flow_flags, void *txv, + const int list_id); +static void DetectTlsJa3SHashSetupCallback(const DetectEngineCtx *de_ctx, Signature *s); +static bool DetectTlsJa3SHashValidateCallback(const Signature *s, const char **sigerror); static int g_tls_ja3s_hash_buffer_id = 0; /** @@ -82,8 +79,8 @@ void DetectTlsJa3SHashRegister(void) DetectAppLayerInspectEngineRegister2("ja3s.hash", ALPROTO_TLS, SIG_FLAG_TOCLIENT, 0, DetectEngineInspectBufferGeneric, GetData); - DetectAppLayerMpmRegister2("ja3s.hash", SIG_FLAG_TOCLIENT, 2, - PrefilterGenericMpmRegister, GetData, ALPROTO_TLS, 0); + DetectAppLayerMpmRegister2("ja3s.hash", SIG_FLAG_TOCLIENT, 2, PrefilterGenericMpmRegister, + GetData, ALPROTO_TLS, 0); DetectAppLayerMpmRegister2("ja3s.hash", SIG_FLAG_TOCLIENT, 2, PrefilterGenericMpmRegister, Ja3DetectGetHash, ALPROTO_QUIC, 1); @@ -93,11 +90,9 @@ void DetectTlsJa3SHashRegister(void) DetectBufferTypeSetDescriptionByName("ja3s.hash", "TLS JA3S hash"); - DetectBufferTypeRegisterSetupCallback("ja3s.hash", - DetectTlsJa3SHashSetupCallback); + DetectBufferTypeRegisterSetupCallback("ja3s.hash", DetectTlsJa3SHashSetupCallback); - DetectBufferTypeRegisterValidateCallback("ja3s.hash", - DetectTlsJa3SHashValidateCallback); + DetectBufferTypeRegisterValidateCallback("ja3s.hash", DetectTlsJa3SHashValidateCallback); g_tls_ja3s_hash_buffer_id = DetectBufferTypeGetByName("ja3s.hash"); } @@ -138,8 +133,8 @@ static int DetectTlsJa3SHashSetup(DetectEngineCtx *de_ctx, Signature *s, const c } static InspectionBuffer *GetData(DetectEngineThreadCtx *det_ctx, - const DetectEngineTransforms *transforms, Flow *f, - const uint8_t flow_flags, void *txv, const int list_id) + const DetectEngineTransforms *transforms, Flow *f, const uint8_t flow_flags, void *txv, + const int list_id) { InspectionBuffer *buffer = InspectionBufferGet(det_ctx, list_id); if (buffer->inspect == NULL) { @@ -159,8 +154,7 @@ static InspectionBuffer *GetData(DetectEngineThreadCtx *det_ctx, return buffer; } -static bool DetectTlsJa3SHashValidateCallback(const Signature *s, - const char **sigerror) +static bool DetectTlsJa3SHashValidateCallback(const Signature *s, const char **sigerror) { for (uint32_t x = 0; x < s->init_data->buffer_index; x++) { if (s->init_data->buffers[x].id != (uint32_t)g_tls_ja3s_hash_buffer_id) @@ -192,8 +186,7 @@ static bool DetectTlsJa3SHashValidateCallback(const Signature *s, return true; } -static void DetectTlsJa3SHashSetupCallback(const DetectEngineCtx *de_ctx, - Signature *s) +static void DetectTlsJa3SHashSetupCallback(const DetectEngineCtx *de_ctx, Signature *s) { for (uint32_t x = 0; x < s->init_data->buffer_index; x++) { if (s->init_data->buffers[x].id != (uint32_t)g_tls_ja3s_hash_buffer_id) diff --git a/src/detect-tls-ja3s-string.c b/src/detect-tls-ja3s-string.c index 0f7f7d61d067..55c79ebdbb0c 100644 --- a/src/detect-tls-ja3s-string.c +++ b/src/detect-tls-ja3s-string.c @@ -58,9 +58,8 @@ static int DetectTlsJa3SStringSetup(DetectEngineCtx *, Signature *, const char *); static InspectionBuffer *GetData(DetectEngineThreadCtx *det_ctx, - const DetectEngineTransforms *transforms, - Flow *f, const uint8_t flow_flags, - void *txv, const int list_id); + const DetectEngineTransforms *transforms, Flow *f, const uint8_t flow_flags, void *txv, + const int list_id); static int g_tls_ja3s_str_buffer_id = 0; /** @@ -79,8 +78,8 @@ void DetectTlsJa3SStringRegister(void) DetectAppLayerInspectEngineRegister2("ja3s.string", ALPROTO_TLS, SIG_FLAG_TOCLIENT, 0, DetectEngineInspectBufferGeneric, GetData); - DetectAppLayerMpmRegister2("ja3s.string", SIG_FLAG_TOCLIENT, 2, - PrefilterGenericMpmRegister, GetData, ALPROTO_TLS, 0); + DetectAppLayerMpmRegister2("ja3s.string", SIG_FLAG_TOCLIENT, 2, PrefilterGenericMpmRegister, + GetData, ALPROTO_TLS, 0); DetectAppLayerMpmRegister2("ja3s.string", SIG_FLAG_TOCLIENT, 2, PrefilterGenericMpmRegister, Ja3DetectGetString, ALPROTO_QUIC, 1); @@ -129,8 +128,8 @@ static int DetectTlsJa3SStringSetup(DetectEngineCtx *de_ctx, Signature *s, const } static InspectionBuffer *GetData(DetectEngineThreadCtx *det_ctx, - const DetectEngineTransforms *transforms, Flow *f, - const uint8_t flow_flags, void *txv, const int list_id) + const DetectEngineTransforms *transforms, Flow *f, const uint8_t flow_flags, void *txv, + const int list_id) { InspectionBuffer *buffer = InspectionBufferGet(det_ctx, list_id); if (buffer->inspect == NULL) { diff --git a/src/detect-tls-sni.c b/src/detect-tls-sni.c index 69b066e8e979..536fdbc40dc5 100644 --- a/src/detect-tls-sni.c +++ b/src/detect-tls-sni.c @@ -54,9 +54,8 @@ static int DetectTlsSniSetup(DetectEngineCtx *, Signature *, const char *); static InspectionBuffer *GetData(DetectEngineThreadCtx *det_ctx, - const DetectEngineTransforms *transforms, - Flow *f, const uint8_t flow_flags, - void *txv, const int list_id); + const DetectEngineTransforms *transforms, Flow *f, const uint8_t flow_flags, void *txv, + const int list_id); static int g_tls_sni_buffer_id = 0; /** @@ -76,16 +75,14 @@ void DetectTlsSniRegister(void) DetectAppLayerInspectEngineRegister2("tls.sni", ALPROTO_TLS, SIG_FLAG_TOSERVER, 0, DetectEngineInspectBufferGeneric, GetData); - DetectAppLayerMpmRegister2("tls.sni", SIG_FLAG_TOSERVER, 2, - PrefilterGenericMpmRegister, GetData, ALPROTO_TLS, 0); + DetectAppLayerMpmRegister2( + "tls.sni", SIG_FLAG_TOSERVER, 2, PrefilterGenericMpmRegister, GetData, ALPROTO_TLS, 0); - DetectBufferTypeSetDescriptionByName("tls.sni", - "TLS Server Name Indication (SNI) extension"); + DetectBufferTypeSetDescriptionByName("tls.sni", "TLS Server Name Indication (SNI) extension"); g_tls_sni_buffer_id = DetectBufferTypeGetByName("tls.sni"); } - /** * \brief this function setup the tls.sni modifier keyword used in the rule * @@ -108,8 +105,8 @@ static int DetectTlsSniSetup(DetectEngineCtx *de_ctx, Signature *s, const char * } static InspectionBuffer *GetData(DetectEngineThreadCtx *det_ctx, - const DetectEngineTransforms *transforms, Flow *f, - const uint8_t flow_flags, void *txv, const int list_id) + const DetectEngineTransforms *transforms, Flow *f, const uint8_t flow_flags, void *txv, + const int list_id) { InspectionBuffer *buffer = InspectionBufferGet(det_ctx, list_id); if (buffer->inspect == NULL) { diff --git a/src/detect-tls-version.c b/src/detect-tls-version.c index f3a119d5a226..a012d10e7304 100644 --- a/src/detect-tls-version.c +++ b/src/detect-tls-version.c @@ -53,14 +53,13 @@ /** * \brief Regex for parsing "id" option, matching number or "number" */ -#define PARSE_REGEX "^\\s*([A-z0-9\\.]+|\"[A-z0-9\\.]+\")\\s*$" +#define PARSE_REGEX "^\\s*([A-z0-9\\.]+|\"[A-z0-9\\.]+\")\\s*$" static DetectParseRegex parse_regex; -static int DetectTlsVersionMatch (DetectEngineThreadCtx *, - Flow *, uint8_t, void *, void *, +static int DetectTlsVersionMatch(DetectEngineThreadCtx *, Flow *, uint8_t, void *, void *, const Signature *, const SigMatchCtx *); -static int DetectTlsVersionSetup (DetectEngineCtx *, Signature *, const char *); +static int DetectTlsVersionSetup(DetectEngineCtx *, Signature *, const char *); #ifdef UNITTESTS static void DetectTlsVersionRegisterTests(void); #endif @@ -70,14 +69,14 @@ static int g_tls_generic_list_id = 0; /** * \brief Registration function for keyword: tls.version */ -void DetectTlsVersionRegister (void) +void DetectTlsVersionRegister(void) { sigmatch_table[DETECT_AL_TLS_VERSION].name = "tls.version"; sigmatch_table[DETECT_AL_TLS_VERSION].desc = "match on TLS/SSL version"; sigmatch_table[DETECT_AL_TLS_VERSION].url = "/rules/tls-keywords.html#tls-version"; sigmatch_table[DETECT_AL_TLS_VERSION].AppLayerTxMatch = DetectTlsVersionMatch; sigmatch_table[DETECT_AL_TLS_VERSION].Setup = DetectTlsVersionSetup; - sigmatch_table[DETECT_AL_TLS_VERSION].Free = DetectTlsVersionFree; + sigmatch_table[DETECT_AL_TLS_VERSION].Free = DetectTlsVersionFree; #ifdef UNITTESTS sigmatch_table[DETECT_AL_TLS_VERSION].RegisterTests = DetectTlsVersionRegisterTests; #endif @@ -98,9 +97,8 @@ void DetectTlsVersionRegister (void) * \retval 0 no match * \retval 1 match */ -static int DetectTlsVersionMatch (DetectEngineThreadCtx *det_ctx, - Flow *f, uint8_t flags, void *state, void *txv, - const Signature *s, const SigMatchCtx *m) +static int DetectTlsVersionMatch(DetectEngineThreadCtx *det_ctx, Flow *f, uint8_t flags, + void *state, void *txv, const Signature *s, const SigMatchCtx *m) { SCEnter(); @@ -119,7 +117,7 @@ static int DetectTlsVersionMatch (DetectEngineThreadCtx *det_ctx, version = ssl_state->server_connp.version; SCLogDebug("server (toclient) version is 0x%02X", version); } else if (flags & STREAM_TOSERVER) { - version = ssl_state->client_connp.version; + version = ssl_state->client_connp.version; SCLogDebug("client (toserver) version is 0x%02X", version); } @@ -146,7 +144,7 @@ static int DetectTlsVersionMatch (DetectEngineThreadCtx *det_ctx, * \retval id_d pointer to DetectTlsVersionData on success * \retval NULL on failure */ -static DetectTlsVersionData *DetectTlsVersionParse (DetectEngineCtx *de_ctx, const char *str) +static DetectTlsVersionData *DetectTlsVersionParse(DetectEngineCtx *de_ctx, const char *str) { uint16_t temp; DetectTlsVersionData *tls = NULL; @@ -178,8 +176,7 @@ static DetectTlsVersionData *DetectTlsVersionParse (DetectEngineCtx *de_ctx, con tmp_str = ver_ptr; /* Let's see if we need to scape "'s */ - if (tmp_str[0] == '"') - { + if (tmp_str[0] == '"') { tmp_str[strlen(tmp_str) - 1] = '\0'; tmp_str += 1; } @@ -202,7 +199,7 @@ static DetectTlsVersionData *DetectTlsVersionParse (DetectEngineCtx *de_ctx, con tls->ver = temp; - SCLogDebug("will look for tls %"PRIu16"", tls->ver); + SCLogDebug("will look for tls %" PRIu16 "", tls->ver); } pcre2_match_data_free(match); @@ -215,7 +212,6 @@ static DetectTlsVersionData *DetectTlsVersionParse (DetectEngineCtx *de_ctx, con if (tls != NULL) DetectTlsVersionFree(de_ctx, tls); return NULL; - } /** @@ -229,7 +225,7 @@ static DetectTlsVersionData *DetectTlsVersionParse (DetectEngineCtx *de_ctx, con * \retval 0 on Success * \retval -1 on Failure */ -static int DetectTlsVersionSetup (DetectEngineCtx *de_ctx, Signature *s, const char *str) +static int DetectTlsVersionSetup(DetectEngineCtx *de_ctx, Signature *s, const char *str) { DetectTlsVersionData *tls = NULL; @@ -254,7 +250,6 @@ static int DetectTlsVersionSetup (DetectEngineCtx *de_ctx, Signature *s, const c if (tls != NULL) DetectTlsVersionFree(de_ctx, tls); return -1; - } /** diff --git a/src/detect-tls-version.h b/src/detect-tls-version.h index fa808f39409d..bfcfb2466e05 100644 --- a/src/detect-tls-version.h +++ b/src/detect-tls-version.h @@ -24,7 +24,7 @@ #ifndef __DETECT_TLS_VERSION_H__ #define __DETECT_TLS_VERSION_H__ -#define DETECT_TLS_VERSION_FLAG_RAW BIT_U8(0) +#define DETECT_TLS_VERSION_FLAG_RAW BIT_U8(0) typedef struct DetectTlsVersionData_ { uint16_t ver; /** tls version to match */ @@ -32,7 +32,6 @@ typedef struct DetectTlsVersionData_ { } DetectTlsVersionData; /* prototypes */ -void DetectTlsVersionRegister (void); +void DetectTlsVersionRegister(void); #endif /* __DETECT_TLS_VERSION_H__ */ - diff --git a/src/detect-tls.c b/src/detect-tls.c index 8a9c98fac795..4c3f267f92b1 100644 --- a/src/detect-tls.c +++ b/src/detect-tls.c @@ -66,31 +66,29 @@ * \brief Regex for parsing "id" option, matching number or "number" */ -#define PARSE_REGEX "^([A-z0-9\\s\\-\\.=,\\*@]+|\"[A-z0-9\\s\\-\\.=,\\*@]+\")\\s*$" -#define PARSE_REGEX_FINGERPRINT "^([A-z0-9\\:\\*]+|\"[A-z0-9\\:\\* ]+\")\\s*$" +#define PARSE_REGEX "^([A-z0-9\\s\\-\\.=,\\*@]+|\"[A-z0-9\\s\\-\\.=,\\*@]+\")\\s*$" +#define PARSE_REGEX_FINGERPRINT "^([A-z0-9\\:\\*]+|\"[A-z0-9\\:\\* ]+\")\\s*$" static DetectParseRegex subject_parse_regex; static DetectParseRegex issuerdn_parse_regex; static DetectParseRegex fingerprint_parse_regex; -static int DetectTlsSubjectMatch (DetectEngineThreadCtx *, - Flow *, uint8_t, void *, void *, +static int DetectTlsSubjectMatch(DetectEngineThreadCtx *, Flow *, uint8_t, void *, void *, const Signature *, const SigMatchCtx *); -static int DetectTlsSubjectSetup (DetectEngineCtx *, Signature *, const char *); +static int DetectTlsSubjectSetup(DetectEngineCtx *, Signature *, const char *); static void DetectTlsSubjectFree(DetectEngineCtx *, void *); -static int DetectTlsIssuerDNMatch (DetectEngineThreadCtx *, - Flow *, uint8_t, void *, void *, +static int DetectTlsIssuerDNMatch(DetectEngineThreadCtx *, Flow *, uint8_t, void *, void *, const Signature *, const SigMatchCtx *); -static int DetectTlsIssuerDNSetup (DetectEngineCtx *, Signature *, const char *); +static int DetectTlsIssuerDNSetup(DetectEngineCtx *, Signature *, const char *); static void DetectTlsIssuerDNFree(DetectEngineCtx *, void *); -static int DetectTlsFingerprintSetup (DetectEngineCtx *, Signature *, const char *); +static int DetectTlsFingerprintSetup(DetectEngineCtx *, Signature *, const char *); static void DetectTlsFingerprintFree(DetectEngineCtx *, void *); -static int DetectTlsStoreSetup (DetectEngineCtx *, Signature *, const char *); -static int DetectTlsStorePostMatch (DetectEngineThreadCtx *det_ctx, - Packet *, const Signature *s, const SigMatchCtx *unused); +static int DetectTlsStoreSetup(DetectEngineCtx *, Signature *, const char *); +static int DetectTlsStorePostMatch( + DetectEngineThreadCtx *det_ctx, Packet *, const Signature *s, const SigMatchCtx *unused); static int g_tls_cert_list_id = 0; static int g_tls_cert_fingerprint_list_id = 0; @@ -98,15 +96,16 @@ static int g_tls_cert_fingerprint_list_id = 0; /** * \brief Registration function for keyword: tls.version */ -void DetectTlsRegister (void) +void DetectTlsRegister(void) { sigmatch_table[DETECT_AL_TLS_SUBJECT].name = "tls.subject"; sigmatch_table[DETECT_AL_TLS_SUBJECT].desc = "match TLS/SSL certificate Subject field"; sigmatch_table[DETECT_AL_TLS_SUBJECT].url = "/rules/tls-keywords.html#tls-subject"; sigmatch_table[DETECT_AL_TLS_SUBJECT].AppLayerTxMatch = DetectTlsSubjectMatch; sigmatch_table[DETECT_AL_TLS_SUBJECT].Setup = DetectTlsSubjectSetup; - sigmatch_table[DETECT_AL_TLS_SUBJECT].Free = DetectTlsSubjectFree; - sigmatch_table[DETECT_AL_TLS_SUBJECT].flags = SIGMATCH_QUOTES_MANDATORY|SIGMATCH_HANDLE_NEGATION; + sigmatch_table[DETECT_AL_TLS_SUBJECT].Free = DetectTlsSubjectFree; + sigmatch_table[DETECT_AL_TLS_SUBJECT].flags = + SIGMATCH_QUOTES_MANDATORY | SIGMATCH_HANDLE_NEGATION; sigmatch_table[DETECT_AL_TLS_SUBJECT].alternative = DETECT_AL_TLS_CERT_SUBJECT; sigmatch_table[DETECT_AL_TLS_ISSUERDN].name = "tls.issuerdn"; @@ -114,16 +113,18 @@ void DetectTlsRegister (void) sigmatch_table[DETECT_AL_TLS_ISSUERDN].url = "/rules/tls-keywords.html#tls-issuerdn"; sigmatch_table[DETECT_AL_TLS_ISSUERDN].AppLayerTxMatch = DetectTlsIssuerDNMatch; sigmatch_table[DETECT_AL_TLS_ISSUERDN].Setup = DetectTlsIssuerDNSetup; - sigmatch_table[DETECT_AL_TLS_ISSUERDN].Free = DetectTlsIssuerDNFree; - sigmatch_table[DETECT_AL_TLS_ISSUERDN].flags = SIGMATCH_QUOTES_MANDATORY|SIGMATCH_HANDLE_NEGATION; + sigmatch_table[DETECT_AL_TLS_ISSUERDN].Free = DetectTlsIssuerDNFree; + sigmatch_table[DETECT_AL_TLS_ISSUERDN].flags = + SIGMATCH_QUOTES_MANDATORY | SIGMATCH_HANDLE_NEGATION; sigmatch_table[DETECT_AL_TLS_ISSUERDN].alternative = DETECT_AL_TLS_CERT_ISSUER; sigmatch_table[DETECT_AL_TLS_FINGERPRINT].name = "tls.fingerprint"; sigmatch_table[DETECT_AL_TLS_FINGERPRINT].desc = "match TLS/SSL certificate SHA1 fingerprint"; sigmatch_table[DETECT_AL_TLS_FINGERPRINT].url = "/rules/tls-keywords.html#tls-fingerprint"; sigmatch_table[DETECT_AL_TLS_FINGERPRINT].Setup = DetectTlsFingerprintSetup; - sigmatch_table[DETECT_AL_TLS_FINGERPRINT].Free = DetectTlsFingerprintFree; - sigmatch_table[DETECT_AL_TLS_FINGERPRINT].flags = SIGMATCH_QUOTES_MANDATORY|SIGMATCH_HANDLE_NEGATION; + sigmatch_table[DETECT_AL_TLS_FINGERPRINT].Free = DetectTlsFingerprintFree; + sigmatch_table[DETECT_AL_TLS_FINGERPRINT].flags = + SIGMATCH_QUOTES_MANDATORY | SIGMATCH_HANDLE_NEGATION; sigmatch_table[DETECT_AL_TLS_FINGERPRINT].alternative = DETECT_AL_TLS_CERT_FINGERPRINT; sigmatch_table[DETECT_AL_TLS_STORE].name = "tls_store"; @@ -159,9 +160,8 @@ void DetectTlsRegister (void) * \retval 0 no match * \retval 1 match */ -static int DetectTlsSubjectMatch (DetectEngineThreadCtx *det_ctx, - Flow *f, uint8_t flags, void *state, void *txv, - const Signature *s, const SigMatchCtx *m) +static int DetectTlsSubjectMatch(DetectEngineThreadCtx *det_ctx, Flow *f, uint8_t flags, + void *state, void *txv, const Signature *s, const SigMatchCtx *m) { SCEnter(); @@ -182,8 +182,8 @@ static int DetectTlsSubjectMatch (DetectEngineThreadCtx *det_ctx, } if (connp->cert0_subject != NULL) { - SCLogDebug("TLS: Subject is [%s], looking for [%s]\n", - connp->cert0_subject, tls_data->subject); + SCLogDebug("TLS: Subject is [%s], looking for [%s]\n", connp->cert0_subject, + tls_data->subject); if (strstr(connp->cert0_subject, tls_data->subject) != NULL) { if (tls_data->flags & DETECT_CONTENT_NEGATED) { @@ -214,7 +214,7 @@ static int DetectTlsSubjectMatch (DetectEngineThreadCtx *det_ctx, * \retval id_d pointer to DetectTlsData on success * \retval NULL on failure */ -static DetectTlsData *DetectTlsSubjectParse (DetectEngineCtx *de_ctx, const char *str, bool negate) +static DetectTlsData *DetectTlsSubjectParse(DetectEngineCtx *de_ctx, const char *str, bool negate) { DetectTlsData *tls = NULL; size_t pcre2_len; @@ -246,13 +246,13 @@ static DetectTlsData *DetectTlsSubjectParse (DetectEngineCtx *de_ctx, const char tls->subject = NULL; tls->flags = flag; - orig = SCStrdup((char*)str_ptr); + orig = SCStrdup((char *)str_ptr); if (unlikely(orig == NULL)) { goto error; } pcre2_substring_free((PCRE2_UCHAR *)str_ptr); - tmp_str=orig; + tmp_str = orig; /* Let's see if we need to escape "'s */ if (tmp_str[0] == '"') { @@ -281,7 +281,6 @@ static DetectTlsData *DetectTlsSubjectParse (DetectEngineCtx *de_ctx, const char if (tls != NULL) DetectTlsSubjectFree(de_ctx, tls); return NULL; - } /** @@ -295,7 +294,7 @@ static DetectTlsData *DetectTlsSubjectParse (DetectEngineCtx *de_ctx, const char * \retval 0 on Success * \retval -1 on Failure */ -static int DetectTlsSubjectSetup (DetectEngineCtx *de_ctx, Signature *s, const char *str) +static int DetectTlsSubjectSetup(DetectEngineCtx *de_ctx, Signature *s, const char *str) { DetectTlsData *tls = NULL; @@ -319,7 +318,6 @@ static int DetectTlsSubjectSetup (DetectEngineCtx *de_ctx, Signature *s, const c if (tls != NULL) DetectTlsSubjectFree(de_ctx, tls); return -1; - } /** @@ -348,9 +346,8 @@ static void DetectTlsSubjectFree(DetectEngineCtx *de_ctx, void *ptr) * \retval 0 no match * \retval 1 match */ -static int DetectTlsIssuerDNMatch (DetectEngineThreadCtx *det_ctx, - Flow *f, uint8_t flags, void *state, void *txv, - const Signature *s, const SigMatchCtx *m) +static int DetectTlsIssuerDNMatch(DetectEngineThreadCtx *det_ctx, Flow *f, uint8_t flags, + void *state, void *txv, const Signature *s, const SigMatchCtx *m) { SCEnter(); @@ -371,8 +368,8 @@ static int DetectTlsIssuerDNMatch (DetectEngineThreadCtx *det_ctx, } if (connp->cert0_issuerdn != NULL) { - SCLogDebug("TLS: IssuerDN is [%s], looking for [%s]\n", - connp->cert0_issuerdn, tls_data->issuerdn); + SCLogDebug("TLS: IssuerDN is [%s], looking for [%s]\n", connp->cert0_issuerdn, + tls_data->issuerdn); if (strstr(connp->cert0_issuerdn, tls_data->issuerdn) != NULL) { if (tls_data->flags & DETECT_CONTENT_NEGATED) { @@ -435,17 +432,16 @@ static DetectTlsData *DetectTlsIssuerDNParse(DetectEngineCtx *de_ctx, const char tls->issuerdn = NULL; tls->flags = flag; - orig = SCStrdup((char*)str_ptr); + orig = SCStrdup((char *)str_ptr); if (unlikely(orig == NULL)) { goto error; } pcre2_substring_free((PCRE2_UCHAR *)str_ptr); - tmp_str=orig; + tmp_str = orig; /* Let's see if we need to escape "'s */ - if (tmp_str[0] == '"') - { + if (tmp_str[0] == '"') { tmp_str[strlen(tmp_str) - 1] = '\0'; tmp_str += 1; } @@ -471,7 +467,6 @@ static DetectTlsData *DetectTlsIssuerDNParse(DetectEngineCtx *de_ctx, const char if (tls != NULL) DetectTlsIssuerDNFree(de_ctx, tls); return NULL; - } /** @@ -485,7 +480,7 @@ static DetectTlsData *DetectTlsIssuerDNParse(DetectEngineCtx *de_ctx, const char * \retval 0 on Success * \retval -1 on Failure */ -static int DetectTlsIssuerDNSetup (DetectEngineCtx *de_ctx, Signature *s, const char *str) +static int DetectTlsIssuerDNSetup(DetectEngineCtx *de_ctx, Signature *s, const char *str) { DetectTlsData *tls = NULL; @@ -509,7 +504,6 @@ static int DetectTlsIssuerDNSetup (DetectEngineCtx *de_ctx, Signature *s, const if (tls != NULL) DetectTlsIssuerDNFree(de_ctx, tls); return -1; - } /** @@ -545,7 +539,7 @@ static void DetectTlsIssuerDNFree(DetectEngineCtx *de_ctx, void *ptr) * \retval 0 on Success * \retval -1 on Failure */ -static int DetectTlsFingerprintSetup (DetectEngineCtx *de_ctx, Signature *s, const char *str) +static int DetectTlsFingerprintSetup(DetectEngineCtx *de_ctx, Signature *s, const char *str) { if (DetectContentSetup(de_ctx, s, str) < 0) { return -1; @@ -580,7 +574,7 @@ static void DetectTlsFingerprintFree(DetectEngineCtx *de_ctx, void *ptr) * \retval 0 on Success * \retval -1 on Failure */ -static int DetectTlsStoreSetup (DetectEngineCtx *de_ctx, Signature *s, const char *str) +static int DetectTlsStoreSetup(DetectEngineCtx *de_ctx, Signature *s, const char *str) { if (DetectSignatureSetAppProto(s, ALPROTO_TLS) != 0) @@ -596,8 +590,8 @@ static int DetectTlsStoreSetup (DetectEngineCtx *de_ctx, Signature *s, const cha } /** \warning modifies Flow::alstate */ -static int DetectTlsStorePostMatch (DetectEngineThreadCtx *det_ctx, - Packet *p, const Signature *s, const SigMatchCtx *unused) +static int DetectTlsStorePostMatch( + DetectEngineThreadCtx *det_ctx, Packet *p, const Signature *s, const SigMatchCtx *unused) { SCEnter(); diff --git a/src/detect-tls.h b/src/detect-tls.h index 70d58d56c1de..d5b2442d1f53 100644 --- a/src/detect-tls.h +++ b/src/detect-tls.h @@ -35,13 +35,13 @@ #define __DETECT_TLS_H__ typedef struct DetectTlsData_ { - uint16_t ver; /** tls version to match */ + uint16_t ver; /** tls version to match */ uint32_t flags; /** flags containing match variant (Negation for example) */ - char * subject; /** tls certificate subject substring to match */ + char *subject; /** tls certificate subject substring to match */ char *issuerdn; /** tls certificate issuerDN substring to match */ } DetectTlsData; /* prototypes */ -void DetectTlsRegister (void); +void DetectTlsRegister(void); #endif /* __DETECT_TLS_H__ */ diff --git a/src/detect-tos.c b/src/detect-tos.c index e8c1fe6f62d7..ecfa61cb4f96 100644 --- a/src/detect-tos.c +++ b/src/detect-tos.c @@ -43,13 +43,13 @@ #include "util-unittest.h" #include "util-unittest-helper.h" -#define PARSE_REGEX "^\\s*(!?\\s*[0-9]{1,3}|!?\\s*[xX][0-9a-fA-F]{1,2})\\s*$" +#define PARSE_REGEX "^\\s*(!?\\s*[0-9]{1,3}|!?\\s*[xX][0-9a-fA-F]{1,2})\\s*$" static DetectParseRegex parse_regex; static int DetectTosSetup(DetectEngineCtx *, Signature *, const char *); -static int DetectTosMatch(DetectEngineThreadCtx *, Packet *, - const Signature *, const SigMatchCtx *); +static int DetectTosMatch( + DetectEngineThreadCtx *, Packet *, const Signature *, const SigMatchCtx *); #ifdef UNITTESTS static void DetectTosRegisterTests(void); #endif @@ -71,10 +71,8 @@ void DetectTosRegister(void) #ifdef UNITTESTS sigmatch_table[DETECT_TOS].RegisterTests = DetectTosRegisterTests; #endif - sigmatch_table[DETECT_TOS].flags = - (SIGMATCH_QUOTES_OPTIONAL|SIGMATCH_HANDLE_NEGATION); - sigmatch_table[DETECT_TOS].url = - "/rules/header-keywords.html#tos"; + sigmatch_table[DETECT_TOS].flags = (SIGMATCH_QUOTES_OPTIONAL | SIGMATCH_HANDLE_NEGATION); + sigmatch_table[DETECT_TOS].url = "/rules/header-keywords.html#tos"; DetectSetupParseRegexes(PARSE_REGEX, &parse_regex); } @@ -90,8 +88,8 @@ void DetectTosRegister(void) * \retval 0 no match * \retval 1 match */ -static int DetectTosMatch(DetectEngineThreadCtx *det_ctx, Packet *p, - const Signature *s, const SigMatchCtx *ctx) +static int DetectTosMatch( + DetectEngineThreadCtx *det_ctx, Packet *p, const Signature *s, const SigMatchCtx *ctx) { const DetectTosData *tosd = (const DetectTosData *)ctx; int result = 0; @@ -331,19 +329,18 @@ static int DetectTosTest12(void) IPV4_SET_RAW_IPTOS(p->ip4h, 10); const char *sigs[4]; - sigs[0]= "alert ip any any -> any any (msg:\"Testing id 1\"; tos: 10 ; sid:1;)"; - sigs[1]= "alert ip any any -> any any (msg:\"Testing id 2\"; tos: ! 10; sid:2;)"; - sigs[2]= "alert ip any any -> any any (msg:\"Testing id 3\"; tos:20 ; sid:3;)"; - sigs[3]= "alert ip any any -> any any (msg:\"Testing id 3\"; tos:! 20; sid:4;)"; + sigs[0] = "alert ip any any -> any any (msg:\"Testing id 1\"; tos: 10 ; sid:1;)"; + sigs[1] = "alert ip any any -> any any (msg:\"Testing id 2\"; tos: ! 10; sid:2;)"; + sigs[2] = "alert ip any any -> any any (msg:\"Testing id 3\"; tos:20 ; sid:3;)"; + sigs[3] = "alert ip any any -> any any (msg:\"Testing id 3\"; tos:! 20; sid:4;)"; - uint32_t sid[4] = {1, 2, 3, 4}; + uint32_t sid[4] = { 1, 2, 3, 4 }; - uint32_t results[1][4] = - { - {1, 0, 0, 1}, - }; + uint32_t results[1][4] = { + { 1, 0, 0, 1 }, + }; - result = UTHGenericTest(&p, 1, sigs, sid, (uint32_t *) results, 4); + result = UTHGenericTest(&p, 1, sigs, sid, (uint32_t *)results, 4); UTHFreePackets(&p, 1); diff --git a/src/detect-transform-compress-whitespace.c b/src/detect-transform-compress-whitespace.c index 5cbf0fd896f5..d9d60be6c68a 100644 --- a/src/detect-transform-compress-whitespace.c +++ b/src/detect-transform-compress-whitespace.c @@ -34,7 +34,7 @@ #include "util-unittest.h" #include "util-print.h" -static int DetectTransformCompressWhitespaceSetup (DetectEngineCtx *, Signature *, const char *); +static int DetectTransformCompressWhitespaceSetup(DetectEngineCtx *, Signature *, const char *); #ifdef UNITTESTS static void DetectTransformCompressWhitespaceRegisterTests(void); #endif @@ -46,19 +46,18 @@ void DetectTransformCompressWhitespaceRegister(void) { sigmatch_table[DETECT_TRANSFORM_COMPRESS_WHITESPACE].name = "compress_whitespace"; sigmatch_table[DETECT_TRANSFORM_COMPRESS_WHITESPACE].desc = - "modify buffer to compress consecutive whitespace characters " - "into a single one before inspection"; + "modify buffer to compress consecutive whitespace characters " + "into a single one before inspection"; sigmatch_table[DETECT_TRANSFORM_COMPRESS_WHITESPACE].url = - "/rules/transforms.html#compress-whitespace"; - sigmatch_table[DETECT_TRANSFORM_COMPRESS_WHITESPACE].Transform = - TransformCompressWhitespace; + "/rules/transforms.html#compress-whitespace"; + sigmatch_table[DETECT_TRANSFORM_COMPRESS_WHITESPACE].Transform = TransformCompressWhitespace; sigmatch_table[DETECT_TRANSFORM_COMPRESS_WHITESPACE].TransformValidate = TransformCompressWhitespaceValidate; sigmatch_table[DETECT_TRANSFORM_COMPRESS_WHITESPACE].Setup = - DetectTransformCompressWhitespaceSetup; + DetectTransformCompressWhitespaceSetup; #ifdef UNITTESTS sigmatch_table[DETECT_TRANSFORM_COMPRESS_WHITESPACE].RegisterTests = - DetectTransformCompressWhitespaceRegisterTests; + DetectTransformCompressWhitespaceRegisterTests; #endif sigmatch_table[DETECT_TRANSFORM_COMPRESS_WHITESPACE].flags |= SIGMATCH_NOOPT; } @@ -72,7 +71,8 @@ void DetectTransformCompressWhitespaceRegister(void) * \retval 0 ok * \retval -1 failure */ -static int DetectTransformCompressWhitespaceSetup (DetectEngineCtx *de_ctx, Signature *s, const char *nullstr) +static int DetectTransformCompressWhitespaceSetup( + DetectEngineCtx *de_ctx, Signature *s, const char *nullstr) { SCEnter(); int r = DetectSignatureAddTransform(s, DETECT_TRANSFORM_COMPRESS_WHITESPACE, NULL); @@ -114,8 +114,8 @@ static void TransformCompressWhitespace(InspectionBuffer *buffer, void *options) uint8_t output[input_len]; // we can only shrink uint8_t *oi = output, *os = output; - //PrintRawDataFp(stdout, input, input_len); - for (uint32_t i = 0; i < input_len; ) { + // PrintRawDataFp(stdout, input, input_len); + for (uint32_t i = 0; i < input_len;) { if (!(isspace(*input))) { *oi++ = *input++; i++; @@ -130,7 +130,7 @@ static void TransformCompressWhitespace(InspectionBuffer *buffer, void *options) } } uint32_t output_size = oi - os; - //PrintRawDataFp(stdout, output, output_size); + // PrintRawDataFp(stdout, output, output_size); InspectionBufferCopy(buffer, os, output_size); } @@ -221,10 +221,10 @@ static int DetectTransformCompressWhitespaceTest04(void) static void DetectTransformCompressWhitespaceRegisterTests(void) { - UtRegisterTest("DetectTransformCompressWhitespaceTest01", - DetectTransformCompressWhitespaceTest01); - UtRegisterTest("DetectTransformCompressWhitespaceTest02", - DetectTransformCompressWhitespaceTest02); + UtRegisterTest( + "DetectTransformCompressWhitespaceTest01", DetectTransformCompressWhitespaceTest01); + UtRegisterTest( + "DetectTransformCompressWhitespaceTest02", DetectTransformCompressWhitespaceTest02); UtRegisterTest( "DetectTransformCompressWhitespaceTest03", DetectTransformCompressWhitespaceTest03); UtRegisterTest( diff --git a/src/detect-transform-compress-whitespace.h b/src/detect-transform-compress-whitespace.h index 800d9a7272c1..adaeea07694c 100644 --- a/src/detect-transform-compress-whitespace.h +++ b/src/detect-transform-compress-whitespace.h @@ -25,6 +25,6 @@ #define __DETECT_TRANSFORM_COMPRESS_WHITESPACE_H__ /* prototypes */ -void DetectTransformCompressWhitespaceRegister (void); +void DetectTransformCompressWhitespaceRegister(void); #endif /* __DETECT_TRANSFORM_COMPRESS_WHITESPACE_H__ */ diff --git a/src/detect-transform-dotprefix.c b/src/detect-transform-dotprefix.c index 52a263372b43..9e3bda00b652 100644 --- a/src/detect-transform-dotprefix.c +++ b/src/detect-transform-dotprefix.c @@ -37,7 +37,7 @@ #include "util-memrchr.h" #include "util-memcpy.h" -static int DetectTransformDotPrefixSetup (DetectEngineCtx *, Signature *, const char *); +static int DetectTransformDotPrefixSetup(DetectEngineCtx *, Signature *, const char *); #ifdef UNITTESTS static void DetectTransformDotPrefixRegisterTests(void); #endif @@ -46,15 +46,13 @@ static void TransformDotPrefix(InspectionBuffer *buffer, void *options); void DetectTransformDotPrefixRegister(void) { sigmatch_table[DETECT_TRANSFORM_DOTPREFIX].name = "dotprefix"; - sigmatch_table[DETECT_TRANSFORM_DOTPREFIX].desc = - "modify buffer to extract the dotprefix"; - sigmatch_table[DETECT_TRANSFORM_DOTPREFIX].url = - "/rules/transforms.html#dotprefix"; + sigmatch_table[DETECT_TRANSFORM_DOTPREFIX].desc = "modify buffer to extract the dotprefix"; + sigmatch_table[DETECT_TRANSFORM_DOTPREFIX].url = "/rules/transforms.html#dotprefix"; sigmatch_table[DETECT_TRANSFORM_DOTPREFIX].Transform = TransformDotPrefix; sigmatch_table[DETECT_TRANSFORM_DOTPREFIX].Setup = DetectTransformDotPrefixSetup; #ifdef UNITTESTS sigmatch_table[DETECT_TRANSFORM_DOTPREFIX].RegisterTests = - DetectTransformDotPrefixRegisterTests; + DetectTransformDotPrefixRegisterTests; #endif sigmatch_table[DETECT_TRANSFORM_DOTPREFIX].flags |= SIGMATCH_NOOPT; } @@ -68,7 +66,7 @@ void DetectTransformDotPrefixRegister(void) * \retval 0 ok * \retval -1 failure */ -static int DetectTransformDotPrefixSetup (DetectEngineCtx *de_ctx, Signature *s, const char *nullstr) +static int DetectTransformDotPrefixSetup(DetectEngineCtx *de_ctx, Signature *s, const char *nullstr) { SCEnter(); int r = DetectSignatureAddTransform(s, DETECT_TRANSFORM_DOTPREFIX, NULL); @@ -88,7 +86,8 @@ static int DetectTransformDotPrefixSetup (DetectEngineCtx *de_ctx, Signature *s, * 5. google.com --> match * * To match on the dotprefix only: - * Rule: "alert dns any any -> any any (dns_query; dotprefix; content:".google.com"; endswith; sid:1;)" + * Rule: "alert dns any any -> any any (dns_query; dotprefix; content:".google.com"; endswith; + * sid:1;)" * * 1. hello.google.com --> match * 2. hey.agoogle.com --> no match @@ -161,7 +160,8 @@ static int DetectTransformDotPrefixTest02(void) static int DetectTransformDotPrefixTest03(void) { - const char rule[] = "alert dns any any -> any any (dns.query; dotprefix; content:\".google.com\"; sid:1;)"; + const char rule[] = + "alert dns any any -> any any (dns.query; dotprefix; content:\".google.com\"; sid:1;)"; ThreadVars th_v; DetectEngineThreadCtx *det_ctx = NULL; memset(&th_v, 0, sizeof(th_v)); diff --git a/src/detect-transform-dotprefix.h b/src/detect-transform-dotprefix.h index 3512689b644e..ec124c948281 100644 --- a/src/detect-transform-dotprefix.h +++ b/src/detect-transform-dotprefix.h @@ -25,6 +25,6 @@ #define __DETECT_TRANSFORM_DOTPREFIX_H__ /* prototypes */ -void DetectTransformDotPrefixRegister (void); +void DetectTransformDotPrefixRegister(void); #endif /* __DETECT_TRANSFORM_DOTPREFIX_H__ */ diff --git a/src/detect-transform-md5.c b/src/detect-transform-md5.c index 9e6ee1986a5b..e43fc01917fc 100644 --- a/src/detect-transform-md5.c +++ b/src/detect-transform-md5.c @@ -35,7 +35,7 @@ #include "util-print.h" #include "rust.h" -static int DetectTransformToMd5Setup (DetectEngineCtx *, Signature *, const char *); +static int DetectTransformToMd5Setup(DetectEngineCtx *, Signature *, const char *); #ifdef UNITTESTS static void DetectTransformToMd5RegisterTests(void); #endif @@ -44,17 +44,12 @@ static void TransformToMd5(InspectionBuffer *buffer, void *options); void DetectTransformMd5Register(void) { sigmatch_table[DETECT_TRANSFORM_MD5].name = "to_md5"; - sigmatch_table[DETECT_TRANSFORM_MD5].desc = - "convert to md5 hash of the buffer"; - sigmatch_table[DETECT_TRANSFORM_MD5].url = - "/rules/transforms.html#to-md5"; - sigmatch_table[DETECT_TRANSFORM_MD5].Setup = - DetectTransformToMd5Setup; - sigmatch_table[DETECT_TRANSFORM_MD5].Transform = - TransformToMd5; + sigmatch_table[DETECT_TRANSFORM_MD5].desc = "convert to md5 hash of the buffer"; + sigmatch_table[DETECT_TRANSFORM_MD5].url = "/rules/transforms.html#to-md5"; + sigmatch_table[DETECT_TRANSFORM_MD5].Setup = DetectTransformToMd5Setup; + sigmatch_table[DETECT_TRANSFORM_MD5].Transform = TransformToMd5; #ifdef UNITTESTS - sigmatch_table[DETECT_TRANSFORM_MD5].RegisterTests = - DetectTransformToMd5RegisterTests; + sigmatch_table[DETECT_TRANSFORM_MD5].RegisterTests = DetectTransformToMd5RegisterTests; #endif sigmatch_table[DETECT_TRANSFORM_MD5].flags |= SIGMATCH_NOOPT; } @@ -68,7 +63,7 @@ void DetectTransformMd5Register(void) * \retval 0 ok * \retval -1 failure */ -static int DetectTransformToMd5Setup (DetectEngineCtx *de_ctx, Signature *s, const char *nullstr) +static int DetectTransformToMd5Setup(DetectEngineCtx *de_ctx, Signature *s, const char *nullstr) { SCEnter(); if (g_disable_hashing) { @@ -86,7 +81,7 @@ static void TransformToMd5(InspectionBuffer *buffer, void *options) const uint32_t input_len = buffer->inspect_len; uint8_t output[SC_MD5_LEN]; - //PrintRawDataFp(stdout, input, input_len); + // PrintRawDataFp(stdout, input, input_len); SCMd5HashBuffer(input, input_len, output, sizeof(output)); InspectionBufferCopy(buffer, output, sizeof(output)); } @@ -109,7 +104,6 @@ static int DetectTransformToMd5Test01(void) static void DetectTransformToMd5RegisterTests(void) { - UtRegisterTest("DetectTransformToMd5Test01", - DetectTransformToMd5Test01); + UtRegisterTest("DetectTransformToMd5Test01", DetectTransformToMd5Test01); } #endif diff --git a/src/detect-transform-md5.h b/src/detect-transform-md5.h index a65bb387f233..c3e00023520a 100644 --- a/src/detect-transform-md5.h +++ b/src/detect-transform-md5.h @@ -25,6 +25,6 @@ #define __DETECT_TRANSFORM_MD5_H__ /* prototypes */ -void DetectTransformMd5Register (void); +void DetectTransformMd5Register(void); #endif /* __DETECT_TRANSFORM_MD5_H__ */ diff --git a/src/detect-transform-pcrexform.c b/src/detect-transform-pcrexform.c index c517175b8722..22a6aabe1c27 100644 --- a/src/detect-transform-pcrexform.c +++ b/src/detect-transform-pcrexform.c @@ -36,27 +36,24 @@ typedef struct DetectTransformPcrexformData { pcre2_match_context *context; } DetectTransformPcrexformData; -static int DetectTransformPcrexformSetup (DetectEngineCtx *, Signature *, const char *); +static int DetectTransformPcrexformSetup(DetectEngineCtx *, Signature *, const char *); static void DetectTransformPcrexformFree(DetectEngineCtx *, void *); static void DetectTransformPcrexform(InspectionBuffer *buffer, void *options); #ifdef UNITTESTS -void DetectTransformPcrexformRegisterTests (void); +void DetectTransformPcrexformRegisterTests(void); #endif void DetectTransformPcrexformRegister(void) { sigmatch_table[DETECT_TRANSFORM_PCREXFORM].name = "pcrexform"; - sigmatch_table[DETECT_TRANSFORM_PCREXFORM].desc = - "modify buffer via PCRE before inspection"; + sigmatch_table[DETECT_TRANSFORM_PCREXFORM].desc = "modify buffer via PCRE before inspection"; sigmatch_table[DETECT_TRANSFORM_PCREXFORM].url = "/rules/transforms.html#pcre-xform"; - sigmatch_table[DETECT_TRANSFORM_PCREXFORM].Transform = - DetectTransformPcrexform; - sigmatch_table[DETECT_TRANSFORM_PCREXFORM].Free = - DetectTransformPcrexformFree; - sigmatch_table[DETECT_TRANSFORM_PCREXFORM].Setup = - DetectTransformPcrexformSetup; + sigmatch_table[DETECT_TRANSFORM_PCREXFORM].Transform = DetectTransformPcrexform; + sigmatch_table[DETECT_TRANSFORM_PCREXFORM].Free = DetectTransformPcrexformFree; + sigmatch_table[DETECT_TRANSFORM_PCREXFORM].Setup = DetectTransformPcrexformSetup; #ifdef UNITTESTS - sigmatch_table[DETECT_TRANSFORM_PCREXFORM].RegisterTests = DetectTransformPcrexformRegisterTests; + sigmatch_table[DETECT_TRANSFORM_PCREXFORM].RegisterTests = + DetectTransformPcrexformRegisterTests; #endif sigmatch_table[DETECT_TRANSFORM_PCREXFORM].flags |= SIGMATCH_QUOTES_MANDATORY; } @@ -64,7 +61,7 @@ void DetectTransformPcrexformRegister(void) static void DetectTransformPcrexformFree(DetectEngineCtx *de_ctx, void *ptr) { if (ptr != NULL) { - DetectTransformPcrexformData *pxd = (DetectTransformPcrexformData *) ptr; + DetectTransformPcrexformData *pxd = (DetectTransformPcrexformData *)ptr; pcre2_match_context_free(pxd->context); pcre2_code_free(pxd->regex); SCFree(pxd); @@ -80,7 +77,8 @@ static void DetectTransformPcrexformFree(DetectEngineCtx *de_ctx, void *ptr) * \retval 0 ok * \retval -1 failure */ -static int DetectTransformPcrexformSetup (DetectEngineCtx *de_ctx, Signature *s, const char *regexstr) +static int DetectTransformPcrexformSetup( + DetectEngineCtx *de_ctx, Signature *s, const char *regexstr) { SCEnter(); diff --git a/src/detect-transform-pcrexform.h b/src/detect-transform-pcrexform.h index 0a807d751b8d..18db68ee6122 100644 --- a/src/detect-transform-pcrexform.h +++ b/src/detect-transform-pcrexform.h @@ -25,6 +25,6 @@ #define __DETECT_TRANSFORM_PCREXFORM_H__ /* prototypes */ -void DetectTransformPcrexformRegister (void); +void DetectTransformPcrexformRegister(void); #endif /* __DETECT_TRANSFORM_PCREXFORM_H__ */ diff --git a/src/detect-transform-sha1.c b/src/detect-transform-sha1.c index 927b25e97abd..72bf3a5df1eb 100644 --- a/src/detect-transform-sha1.c +++ b/src/detect-transform-sha1.c @@ -36,7 +36,7 @@ #include "rust.h" -static int DetectTransformToSha1Setup (DetectEngineCtx *, Signature *, const char *); +static int DetectTransformToSha1Setup(DetectEngineCtx *, Signature *, const char *); #ifdef UNITTESTS static void DetectTransformToSha1RegisterTests(void); #endif @@ -45,17 +45,12 @@ static void TransformToSha1(InspectionBuffer *buffer, void *options); void DetectTransformSha1Register(void) { sigmatch_table[DETECT_TRANSFORM_SHA1].name = "to_sha1"; - sigmatch_table[DETECT_TRANSFORM_SHA1].desc = - "convert to sha1 hash of the buffer"; - sigmatch_table[DETECT_TRANSFORM_SHA1].url = - "/rules/transforms.html#to-sha1"; - sigmatch_table[DETECT_TRANSFORM_SHA1].Setup = - DetectTransformToSha1Setup; - sigmatch_table[DETECT_TRANSFORM_SHA1].Transform = - TransformToSha1; + sigmatch_table[DETECT_TRANSFORM_SHA1].desc = "convert to sha1 hash of the buffer"; + sigmatch_table[DETECT_TRANSFORM_SHA1].url = "/rules/transforms.html#to-sha1"; + sigmatch_table[DETECT_TRANSFORM_SHA1].Setup = DetectTransformToSha1Setup; + sigmatch_table[DETECT_TRANSFORM_SHA1].Transform = TransformToSha1; #ifdef UNITTESTS - sigmatch_table[DETECT_TRANSFORM_SHA1].RegisterTests = - DetectTransformToSha1RegisterTests; + sigmatch_table[DETECT_TRANSFORM_SHA1].RegisterTests = DetectTransformToSha1RegisterTests; #endif sigmatch_table[DETECT_TRANSFORM_SHA1].flags |= SIGMATCH_NOOPT; } @@ -69,7 +64,7 @@ void DetectTransformSha1Register(void) * \retval 0 ok * \retval -1 failure */ -static int DetectTransformToSha1Setup (DetectEngineCtx *de_ctx, Signature *s, const char *nullstr) +static int DetectTransformToSha1Setup(DetectEngineCtx *de_ctx, Signature *s, const char *nullstr) { SCEnter(); if (g_disable_hashing) { @@ -87,7 +82,7 @@ static void TransformToSha1(InspectionBuffer *buffer, void *options) const uint32_t input_len = buffer->inspect_len; uint8_t output[SC_SHA1_LEN]; - //PrintRawDataFp(stdout, input, input_len); + // PrintRawDataFp(stdout, input, input_len); SCSha1HashBuffer(input, input_len, output, sizeof(output)); InspectionBufferCopy(buffer, output, sizeof(output)); } @@ -110,7 +105,6 @@ static int DetectTransformToSha1Test01(void) static void DetectTransformToSha1RegisterTests(void) { - UtRegisterTest("DetectTransformToSha1Test01", - DetectTransformToSha1Test01); + UtRegisterTest("DetectTransformToSha1Test01", DetectTransformToSha1Test01); } #endif diff --git a/src/detect-transform-sha1.h b/src/detect-transform-sha1.h index 4d53caedf911..6e39dfbc3d45 100644 --- a/src/detect-transform-sha1.h +++ b/src/detect-transform-sha1.h @@ -25,6 +25,6 @@ #define __DETECT_TRANSFORM_SHA1_H__ /* prototypes */ -void DetectTransformSha1Register (void); +void DetectTransformSha1Register(void); #endif /* __DETECT_TRANSFORM_SHA1_H__ */ diff --git a/src/detect-transform-sha256.c b/src/detect-transform-sha256.c index 3eeb582a8361..e1b6c70842ae 100644 --- a/src/detect-transform-sha256.c +++ b/src/detect-transform-sha256.c @@ -36,7 +36,7 @@ #include "rust.h" -static int DetectTransformToSha256Setup (DetectEngineCtx *, Signature *, const char *); +static int DetectTransformToSha256Setup(DetectEngineCtx *, Signature *, const char *); #ifdef UNITTESTS static void DetectTransformToSha256RegisterTests(void); #endif @@ -45,17 +45,12 @@ static void TransformToSha256(InspectionBuffer *buffer, void *options); void DetectTransformSha256Register(void) { sigmatch_table[DETECT_TRANSFORM_SHA256].name = "to_sha256"; - sigmatch_table[DETECT_TRANSFORM_SHA256].desc = - "convert to sha256 hash of the buffer"; - sigmatch_table[DETECT_TRANSFORM_SHA256].url = - "/rules/transforms.html#to-sha256"; - sigmatch_table[DETECT_TRANSFORM_SHA256].Setup = - DetectTransformToSha256Setup; - sigmatch_table[DETECT_TRANSFORM_SHA256].Transform = - TransformToSha256; + sigmatch_table[DETECT_TRANSFORM_SHA256].desc = "convert to sha256 hash of the buffer"; + sigmatch_table[DETECT_TRANSFORM_SHA256].url = "/rules/transforms.html#to-sha256"; + sigmatch_table[DETECT_TRANSFORM_SHA256].Setup = DetectTransformToSha256Setup; + sigmatch_table[DETECT_TRANSFORM_SHA256].Transform = TransformToSha256; #ifdef UNITTESTS - sigmatch_table[DETECT_TRANSFORM_SHA256].RegisterTests = - DetectTransformToSha256RegisterTests; + sigmatch_table[DETECT_TRANSFORM_SHA256].RegisterTests = DetectTransformToSha256RegisterTests; #endif sigmatch_table[DETECT_TRANSFORM_SHA256].flags |= SIGMATCH_NOOPT; } @@ -69,7 +64,7 @@ void DetectTransformSha256Register(void) * \retval 0 ok * \retval -1 failure */ -static int DetectTransformToSha256Setup (DetectEngineCtx *de_ctx, Signature *s, const char *nullstr) +static int DetectTransformToSha256Setup(DetectEngineCtx *de_ctx, Signature *s, const char *nullstr) { SCEnter(); if (g_disable_hashing) { @@ -87,7 +82,7 @@ static void TransformToSha256(InspectionBuffer *buffer, void *options) const uint32_t input_len = buffer->inspect_len; uint8_t output[SC_SHA256_LEN]; - //PrintRawDataFp(stdout, input, input_len); + // PrintRawDataFp(stdout, input, input_len); SCSha256HashBuffer(input, input_len, output, sizeof(output)); InspectionBufferCopy(buffer, output, sizeof(output)); } @@ -110,7 +105,6 @@ static int DetectTransformToSha256Test01(void) static void DetectTransformToSha256RegisterTests(void) { - UtRegisterTest("DetectTransformToSha256Test01", - DetectTransformToSha256Test01); + UtRegisterTest("DetectTransformToSha256Test01", DetectTransformToSha256Test01); } #endif diff --git a/src/detect-transform-sha256.h b/src/detect-transform-sha256.h index e8b4f0b3b027..34279d90d65e 100644 --- a/src/detect-transform-sha256.h +++ b/src/detect-transform-sha256.h @@ -25,6 +25,6 @@ #define __DETECT_TRANSFORM_SHA256_H__ /* prototypes */ -void DetectTransformSha256Register (void); +void DetectTransformSha256Register(void); #endif /* __DETECT_TRANSFORM_SHA256_H__ */ diff --git a/src/detect-transform-strip-whitespace.c b/src/detect-transform-strip-whitespace.c index 32fb96f06ea0..ca84df6a8bf3 100644 --- a/src/detect-transform-strip-whitespace.c +++ b/src/detect-transform-strip-whitespace.c @@ -35,29 +35,28 @@ #include "util-unittest.h" #include "util-print.h" -static int DetectTransformStripWhitespaceSetup (DetectEngineCtx *, Signature *, const char *); +static int DetectTransformStripWhitespaceSetup(DetectEngineCtx *, Signature *, const char *); #ifdef UNITTESTS static void DetectTransformStripWhitespaceRegisterTests(void); #endif static void TransformStripWhitespace(InspectionBuffer *buffer, void *options); -static bool TransformStripWhitespaceValidate(const uint8_t *content, uint16_t content_len, void *options); +static bool TransformStripWhitespaceValidate( + const uint8_t *content, uint16_t content_len, void *options); void DetectTransformStripWhitespaceRegister(void) { sigmatch_table[DETECT_TRANSFORM_STRIP_WHITESPACE].name = "strip_whitespace"; sigmatch_table[DETECT_TRANSFORM_STRIP_WHITESPACE].desc = - "modify buffer to strip whitespace before inspection"; + "modify buffer to strip whitespace before inspection"; sigmatch_table[DETECT_TRANSFORM_STRIP_WHITESPACE].url = - "/rules/transforms.html#strip-whitespace"; - sigmatch_table[DETECT_TRANSFORM_STRIP_WHITESPACE].Transform = - TransformStripWhitespace; + "/rules/transforms.html#strip-whitespace"; + sigmatch_table[DETECT_TRANSFORM_STRIP_WHITESPACE].Transform = TransformStripWhitespace; sigmatch_table[DETECT_TRANSFORM_STRIP_WHITESPACE].TransformValidate = - TransformStripWhitespaceValidate; - sigmatch_table[DETECT_TRANSFORM_STRIP_WHITESPACE].Setup = - DetectTransformStripWhitespaceSetup; + TransformStripWhitespaceValidate; + sigmatch_table[DETECT_TRANSFORM_STRIP_WHITESPACE].Setup = DetectTransformStripWhitespaceSetup; #ifdef UNITTESTS sigmatch_table[DETECT_TRANSFORM_STRIP_WHITESPACE].RegisterTests = - DetectTransformStripWhitespaceRegisterTests; + DetectTransformStripWhitespaceRegisterTests; #endif sigmatch_table[DETECT_TRANSFORM_STRIP_WHITESPACE].flags |= SIGMATCH_NOOPT; } @@ -71,7 +70,8 @@ void DetectTransformStripWhitespaceRegister(void) * \retval 0 ok * \retval -1 failure */ -static int DetectTransformStripWhitespaceSetup (DetectEngineCtx *de_ctx, Signature *s, const char *nullstr) +static int DetectTransformStripWhitespaceSetup( + DetectEngineCtx *de_ctx, Signature *s, const char *nullstr) { SCEnter(); int r = DetectSignatureAddTransform(s, DETECT_TRANSFORM_STRIP_WHITESPACE, NULL); @@ -86,8 +86,8 @@ static int DetectTransformStripWhitespaceSetup (DetectEngineCtx *de_ctx, Signatu * \retval false If the string contains spaces * \retval true Otherwise. */ -static bool TransformStripWhitespaceValidate(const uint8_t *content, - uint16_t content_len, void *options) +static bool TransformStripWhitespaceValidate( + const uint8_t *content, uint16_t content_len, void *options) { if (content) { for (uint32_t i = 0; i < content_len; i++) { @@ -109,7 +109,7 @@ static void TransformStripWhitespace(InspectionBuffer *buffer, void *options) uint8_t output[input_len]; // we can only shrink uint8_t *oi = output, *os = output; - //PrintRawDataFp(stdout, input, input_len); + // PrintRawDataFp(stdout, input, input_len); for (uint32_t i = 0; i < input_len; i++) { if (!isspace(*input)) { *oi++ = *input; @@ -117,7 +117,7 @@ static void TransformStripWhitespace(InspectionBuffer *buffer, void *options) input++; } uint32_t output_size = oi - os; - //PrintRawDataFp(stdout, output, output_size); + // PrintRawDataFp(stdout, output, output_size); InspectionBufferCopy(buffer, os, output_size); } @@ -181,7 +181,8 @@ static int DetectTransformStripWhitespaceTest02(void) static int DetectTransformStripWhitespaceTest03(void) { - const char rule[] = "alert http any any -> any any (http_request_line; strip_whitespace; content:\"GET/HTTP\"; sid:1;)"; + const char rule[] = "alert http any any -> any any (http_request_line; strip_whitespace; " + "content:\"GET/HTTP\"; sid:1;)"; ThreadVars th_v; DetectEngineThreadCtx *det_ctx = NULL; memset(&th_v, 0, sizeof(th_v)); @@ -199,11 +200,8 @@ static int DetectTransformStripWhitespaceTest03(void) static void DetectTransformStripWhitespaceRegisterTests(void) { - UtRegisterTest("DetectTransformStripWhitespaceTest01", - DetectTransformStripWhitespaceTest01); - UtRegisterTest("DetectTransformStripWhitespaceTest02", - DetectTransformStripWhitespaceTest02); - UtRegisterTest("DetectTransformStripWhitespaceTest03", - DetectTransformStripWhitespaceTest03); + UtRegisterTest("DetectTransformStripWhitespaceTest01", DetectTransformStripWhitespaceTest01); + UtRegisterTest("DetectTransformStripWhitespaceTest02", DetectTransformStripWhitespaceTest02); + UtRegisterTest("DetectTransformStripWhitespaceTest03", DetectTransformStripWhitespaceTest03); } #endif diff --git a/src/detect-transform-strip-whitespace.h b/src/detect-transform-strip-whitespace.h index 274f24100ccc..cc74c03a849f 100644 --- a/src/detect-transform-strip-whitespace.h +++ b/src/detect-transform-strip-whitespace.h @@ -25,6 +25,6 @@ #define __DETECT_TRANSFORM_STRIPWHITESPACE_H__ /* prototypes */ -void DetectTransformStripWhitespaceRegister (void); +void DetectTransformStripWhitespaceRegister(void); #endif /* __DETECT_TRANSFORM_STRIPWHITESPACE_H__ */ diff --git a/src/detect-transform-urldecode.c b/src/detect-transform-urldecode.c index 13ef03372f5f..3c9cd735e9ed 100644 --- a/src/detect-transform-urldecode.c +++ b/src/detect-transform-urldecode.c @@ -35,7 +35,7 @@ #include "util-unittest.h" #include "util-print.h" -static int DetectTransformUrlDecodeSetup (DetectEngineCtx *, Signature *, const char *); +static int DetectTransformUrlDecodeSetup(DetectEngineCtx *, Signature *, const char *); #ifdef UNITTESTS static void DetectTransformUrlDecodeRegisterTests(void); #endif @@ -46,15 +46,13 @@ void DetectTransformUrlDecodeRegister(void) { sigmatch_table[DETECT_TRANSFORM_URL_DECODE].name = "url_decode"; sigmatch_table[DETECT_TRANSFORM_URL_DECODE].desc = - "modify buffer to decode urlencoded data before inspection"; + "modify buffer to decode urlencoded data before inspection"; sigmatch_table[DETECT_TRANSFORM_URL_DECODE].url = "/rules/transforms.html#url-decode"; - sigmatch_table[DETECT_TRANSFORM_URL_DECODE].Transform = - TransformUrlDecode; - sigmatch_table[DETECT_TRANSFORM_URL_DECODE].Setup = - DetectTransformUrlDecodeSetup; + sigmatch_table[DETECT_TRANSFORM_URL_DECODE].Transform = TransformUrlDecode; + sigmatch_table[DETECT_TRANSFORM_URL_DECODE].Setup = DetectTransformUrlDecodeSetup; #ifdef UNITTESTS sigmatch_table[DETECT_TRANSFORM_URL_DECODE].RegisterTests = - DetectTransformUrlDecodeRegisterTests; + DetectTransformUrlDecodeRegisterTests; #endif sigmatch_table[DETECT_TRANSFORM_URL_DECODE].flags |= SIGMATCH_NOOPT; @@ -69,7 +67,7 @@ void DetectTransformUrlDecodeRegister(void) * \retval 0 ok * \retval -1 failure */ -static int DetectTransformUrlDecodeSetup (DetectEngineCtx *de_ctx, Signature *s, const char *nullstr) +static int DetectTransformUrlDecodeSetup(DetectEngineCtx *de_ctx, Signature *s, const char *nullstr) { SCEnter(); int r = DetectSignatureAddTransform(s, DETECT_TRANSFORM_URL_DECODE, NULL); @@ -77,20 +75,22 @@ static int DetectTransformUrlDecodeSetup (DetectEngineCtx *de_ctx, Signature *s, } // util function so as to ease reuse sometimes -static bool BufferUrlDecode(const uint8_t *input, const uint32_t input_len, uint8_t *output, uint32_t *output_size) +static bool BufferUrlDecode( + const uint8_t *input, const uint32_t input_len, uint8_t *output, uint32_t *output_size) { bool changed = false; uint8_t *oi = output; - //PrintRawDataFp(stdout, input, input_len); + // PrintRawDataFp(stdout, input, input_len); for (uint32_t i = 0; i < input_len; i++) { if (input[i] == '%') { if (i + 2 < input_len) { - if ((isxdigit(input[i+1])) && (isxdigit(input[i+2]))) { + if ((isxdigit(input[i + 1])) && (isxdigit(input[i + 2]))) { // Decode %HH encoding. *oi = (uint8_t)((input[i + 1] >= 'A' ? ((input[i + 1] & 0xdf) - 'A') + 10 : (input[i + 1] - '0')) << 4); - *oi |= (input[i+2] >= 'A' ? ((input[i+2] & 0xdf) - 'A') + 10 : (input[i+2] - '0')); + *oi |= (input[i + 2] >= 'A' ? ((input[i + 2] & 0xdf) - 'A') + 10 + : (input[i + 2] - '0')); oi++; // one more increment before looping i += 2; @@ -146,15 +146,16 @@ static int DetectTransformUrlDecodeTest01(void) PrintRawDataFp(stdout, buffer.inspect, buffer.inspect_len); TransformUrlDecode(&buffer, NULL); PrintRawDataFp(stdout, buffer.inspect, buffer.inspect_len); - FAIL_IF (buffer.inspect_len != strlen("Suricata is 'awesome!'%00%ZZ%4")); - FAIL_IF (memcmp(buffer.inspect, "Suricata is 'awesome!'%00%ZZ%4", buffer.inspect_len) != 0); + FAIL_IF(buffer.inspect_len != strlen("Suricata is 'awesome!'%00%ZZ%4")); + FAIL_IF(memcmp(buffer.inspect, "Suricata is 'awesome!'%00%ZZ%4", buffer.inspect_len) != 0); InspectionBufferFree(&buffer); PASS; } static int DetectTransformUrlDecodeTest02(void) { - const char rule[] = "alert http any any -> any any (http.request_body; url_decode; content:\"mail=test@oisf.net\"; sid:1;)"; + const char rule[] = "alert http any any -> any any (http.request_body; url_decode; " + "content:\"mail=test@oisf.net\"; sid:1;)"; ThreadVars th_v; DetectEngineThreadCtx *det_ctx = NULL; memset(&th_v, 0, sizeof(th_v)); @@ -172,9 +173,7 @@ static int DetectTransformUrlDecodeTest02(void) static void DetectTransformUrlDecodeRegisterTests(void) { - UtRegisterTest("DetectTransformUrlDecodeTest01", - DetectTransformUrlDecodeTest01); - UtRegisterTest("DetectTransformUrlDecodeTest02", - DetectTransformUrlDecodeTest02); + UtRegisterTest("DetectTransformUrlDecodeTest01", DetectTransformUrlDecodeTest01); + UtRegisterTest("DetectTransformUrlDecodeTest02", DetectTransformUrlDecodeTest02); } #endif diff --git a/src/detect-transform-urldecode.h b/src/detect-transform-urldecode.h index 79f886f94da7..71d37a30e70f 100644 --- a/src/detect-transform-urldecode.h +++ b/src/detect-transform-urldecode.h @@ -25,6 +25,6 @@ #define __DETECT_TRANSFORM_URLDECODE_H__ /* prototypes */ -void DetectTransformUrlDecodeRegister (void); +void DetectTransformUrlDecodeRegister(void); #endif /* __DETECT_TRANSFORM_URLDECODE_H__ */ diff --git a/src/detect-ttl.c b/src/detect-ttl.c index 6d0a25311803..9880d04e0b32 100644 --- a/src/detect-ttl.c +++ b/src/detect-ttl.c @@ -37,12 +37,12 @@ #include "util-byte.h" /* prototypes */ -static int DetectTtlMatch (DetectEngineThreadCtx *, Packet *, - const Signature *, const SigMatchCtx *); -static int DetectTtlSetup (DetectEngineCtx *, Signature *, const char *); -void DetectTtlFree (DetectEngineCtx *, void *); +static int DetectTtlMatch( + DetectEngineThreadCtx *, Packet *, const Signature *, const SigMatchCtx *); +static int DetectTtlSetup(DetectEngineCtx *, Signature *, const char *); +void DetectTtlFree(DetectEngineCtx *, void *); #ifdef UNITTESTS -void DetectTtlRegisterTests (void); +void DetectTtlRegisterTests(void); #endif static int PrefilterSetupTtl(DetectEngineCtx *de_ctx, SigGroupHead *sgh); static bool PrefilterTtlIsPrefilterable(const Signature *s); @@ -80,8 +80,8 @@ void DetectTtlRegister(void) * \retval 0 no match * \retval 1 match */ -static int DetectTtlMatch (DetectEngineThreadCtx *det_ctx, Packet *p, - const Signature *s, const SigMatchCtx *ctx) +static int DetectTtlMatch( + DetectEngineThreadCtx *det_ctx, Packet *p, const Signature *s, const SigMatchCtx *ctx) { if (PKT_IS_PSEUDOPKT(p)) return 0; @@ -110,7 +110,7 @@ static int DetectTtlMatch (DetectEngineThreadCtx *det_ctx, Packet *p, * \retval 0 on Success * \retval -1 on Failure */ -static int DetectTtlSetup (DetectEngineCtx *de_ctx, Signature *s, const char *ttlstr) +static int DetectTtlSetup(DetectEngineCtx *de_ctx, Signature *s, const char *ttlstr) { DetectU8Data *ttld = DetectU8Parse(ttlstr); if (ttld == NULL) @@ -137,8 +137,7 @@ void DetectTtlFree(DetectEngineCtx *de_ctx, void *ptr) /* prefilter code */ -static void -PrefilterPacketTtlMatch(DetectEngineThreadCtx *det_ctx, Packet *p, const void *pectx) +static void PrefilterPacketTtlMatch(DetectEngineThreadCtx *det_ctx, Packet *p, const void *pectx) { if (PKT_IS_PSEUDOPKT(p)) { SCReturn; @@ -177,7 +176,7 @@ static int PrefilterSetupTtl(DetectEngineCtx *de_ctx, SigGroupHead *sgh) static bool PrefilterTtlIsPrefilterable(const Signature *s) { const SigMatch *sm; - for (sm = s->init_data->smlists[DETECT_SM_LIST_MATCH] ; sm != NULL; sm = sm->next) { + for (sm = s->init_data->smlists[DETECT_SM_LIST_MATCH]; sm != NULL; sm = sm->next) { switch (sm->type) { case DETECT_TTL: return true; diff --git a/src/detect-ttl.h b/src/detect-ttl.h index 0e561a1efe16..c2878c8f3954 100644 --- a/src/detect-ttl.h +++ b/src/detect-ttl.h @@ -22,10 +22,8 @@ */ #ifndef _DETECT_TTL_H -#define _DETECT_TTL_H - +#define _DETECT_TTL_H void DetectTtlRegister(void); -#endif /* _DETECT_TTL_H */ - +#endif /* _DETECT_TTL_H */ diff --git a/src/detect-udphdr.c b/src/detect-udphdr.c index 8aa645b92641..90e8f42cadb6 100644 --- a/src/detect-udphdr.c +++ b/src/detect-udphdr.c @@ -34,9 +34,9 @@ #include "detect-udphdr.h" /* prototypes */ -static int DetectUdphdrSetup (DetectEngineCtx *, Signature *, const char *); +static int DetectUdphdrSetup(DetectEngineCtx *, Signature *, const char *); #ifdef UNITTESTS -void DetectUdphdrRegisterTests (void); +void DetectUdphdrRegisterTests(void); #endif static int g_udphdr_buffer_id = 0; @@ -64,8 +64,7 @@ void DetectUdphdrRegister(void) DetectPktMpmRegister("udp.hdr", 2, PrefilterGenericMpmPktRegister, GetData); - DetectPktInspectEngineRegister("udp.hdr", GetData, - DetectEngineInspectPktBufferGeneric); + DetectPktInspectEngineRegister("udp.hdr", GetData, DetectEngineInspectPktBufferGeneric); return; } @@ -79,7 +78,7 @@ void DetectUdphdrRegister(void) * \retval 0 on Success * \retval -1 on Failure */ -static int DetectUdphdrSetup (DetectEngineCtx *de_ctx, Signature *s, const char *_unused) +static int DetectUdphdrSetup(DetectEngineCtx *de_ctx, Signature *s, const char *_unused) { if (!(DetectProtoContainsProto(&s->proto, IPPROTO_UDP))) return -1; @@ -103,8 +102,7 @@ static InspectionBuffer *GetData(DetectEngineThreadCtx *det_ctx, return NULL; } if (((uint8_t *)p->udph + (ptrdiff_t)UDP_HEADER_LEN) > - ((uint8_t *)GET_PKT_DATA(p) + (ptrdiff_t)GET_PKT_LEN(p))) - { + ((uint8_t *)GET_PKT_DATA(p) + (ptrdiff_t)GET_PKT_LEN(p))) { SCLogDebug("data out of range: %p > %p", ((uint8_t *)p->udph + (ptrdiff_t)UDP_HEADER_LEN), ((uint8_t *)GET_PKT_DATA(p) + (ptrdiff_t)GET_PKT_LEN(p))); diff --git a/src/detect-udphdr.h b/src/detect-udphdr.h index 85aff554101e..e6ce8b533130 100644 --- a/src/detect-udphdr.h +++ b/src/detect-udphdr.h @@ -26,4 +26,4 @@ void DetectUdphdrRegister(void); -#endif /* _DETECT_UDPHDR_H */ +#endif /* _DETECT_UDPHDR_H */ diff --git a/src/detect-uricontent.c b/src/detect-uricontent.c index 65d2c868f7e3..2a5ce0bef4dc 100644 --- a/src/detect-uricontent.c +++ b/src/detect-uricontent.c @@ -64,7 +64,7 @@ static int g_http_uri_buffer_id = 0; /** * \brief Registration function for uricontent: keyword */ -void DetectUricontentRegister (void) +void DetectUricontentRegister(void) { sigmatch_table[DETECT_URICONTENT].name = "uricontent"; sigmatch_table[DETECT_URICONTENT].desc = "legacy keyword to match on the request URI buffer"; @@ -72,7 +72,8 @@ void DetectUricontentRegister (void) sigmatch_table[DETECT_URICONTENT].Match = NULL; sigmatch_table[DETECT_URICONTENT].Setup = DetectUricontentSetup; sigmatch_table[DETECT_URICONTENT].Free = DetectUricontentFree; - sigmatch_table[DETECT_URICONTENT].flags = (SIGMATCH_QUOTES_MANDATORY|SIGMATCH_HANDLE_NEGATION); + sigmatch_table[DETECT_URICONTENT].flags = + (SIGMATCH_QUOTES_MANDATORY | SIGMATCH_HANDLE_NEGATION); sigmatch_table[DETECT_URICONTENT].alternative = DETECT_HTTP_URI; g_http_uri_buffer_id = DetectBufferTypeRegister("http_uri"); diff --git a/src/detect-uricontent.h b/src/detect-uricontent.h index 289afff33a4f..6f0e5a65f83a 100644 --- a/src/detect-uricontent.h +++ b/src/detect-uricontent.h @@ -26,6 +26,6 @@ #define __DETECT_URICONTENT_H__ /* prototypes */ -void DetectUricontentRegister (void); +void DetectUricontentRegister(void); #endif /* __DETECT_URICONTENT_H__ */ diff --git a/src/detect-urilen.c b/src/detect-urilen.c index 67acda5d5c58..654a82f012eb 100644 --- a/src/detect-urilen.c +++ b/src/detect-urilen.c @@ -44,12 +44,11 @@ #include "flow-util.h" #include "stream-tcp.h" - /*prototypes*/ -static int DetectUrilenSetup (DetectEngineCtx *, Signature *, const char *); -static void DetectUrilenFree (DetectEngineCtx *, void *); +static int DetectUrilenSetup(DetectEngineCtx *, Signature *, const char *); +static void DetectUrilenFree(DetectEngineCtx *, void *); #ifdef UNITTESTS -static void DetectUrilenRegisterTests (void); +static void DetectUrilenRegisterTests(void); #endif static int g_http_uri_buffer_id = 0; static int g_http_raw_uri_buffer_id = 0; @@ -83,7 +82,7 @@ void DetectUrilenRegister(void) * \retval NULL on failure */ -static DetectUrilenData *DetectUrilenParse (const char *urilenstr) +static DetectUrilenData *DetectUrilenParse(const char *urilenstr) { return rs_detect_urilen_parse(urilenstr); } @@ -98,7 +97,7 @@ static DetectUrilenData *DetectUrilenParse (const char *urilenstr) * \retval 0 on Success * \retval -1 on Failure */ -static int DetectUrilenSetup (DetectEngineCtx *de_ctx, Signature *s, const char *urilenstr) +static int DetectUrilenSetup(DetectEngineCtx *de_ctx, Signature *s, const char *urilenstr) { SCEnter(); DetectUrilenData *urilend = NULL; @@ -423,8 +422,8 @@ static int DetectUrilenParseTest10(void) * */ -static int DetectUrilenInitTest(DetectEngineCtx **de_ctx, Signature **sig, - DetectUrilenData **urilend, const char *str) +static int DetectUrilenInitTest( + DetectEngineCtx **de_ctx, Signature **sig, DetectUrilenData **urilend, const char *str) { char fullstr[1024]; int result = 0; @@ -432,8 +431,10 @@ static int DetectUrilenInitTest(DetectEngineCtx **de_ctx, Signature **sig, *de_ctx = NULL; *sig = NULL; - if (snprintf(fullstr, 1024, "alert ip any any -> any any (msg:\"Urilen " - "test\"; urilen:%s; sid:1;)", str) >= 1024) { + if (snprintf(fullstr, 1024, + "alert ip any any -> any any (msg:\"Urilen " + "test\"; urilen:%s; sid:1;)", + str) >= 1024) { goto end; } @@ -479,7 +480,7 @@ static int DetectUrilenSetpTest01(void) goto end; } - if(urilend == NULL) + if (urilend == NULL) goto cleanup; if (urilend != NULL) { @@ -528,7 +529,7 @@ static int DetectUrilenSigTest01(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -540,18 +541,16 @@ static int DetectUrilenSigTest01(void) de_ctx->flags |= DE_QUIET; - s = de_ctx->sig_list = SigInit(de_ctx, - "alert tcp any any -> any any " - "(msg:\"Testing urilen\"; " - "urilen: <5; sid:1;)"); + s = de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " + "(msg:\"Testing urilen\"; " + "urilen: <5; sid:1;)"); if (s == NULL) { goto end; } - s = s->next = SigInit(de_ctx, - "alert tcp any any -> any any " - "(msg:\"Testing http_method\"; " - "urilen: >5; sid:2;)"); + s = s->next = SigInit(de_ctx, "alert tcp any any -> any any " + "(msg:\"Testing http_method\"; " + "urilen: >5; sid:2;)"); if (s == NULL) { goto end; } @@ -588,9 +587,12 @@ static int DetectUrilenSigTest01(void) end: if (alp_tctx != NULL) AppLayerParserThreadCtxFree(alp_tctx); - if (de_ctx != NULL) SigGroupCleanup(de_ctx); - if (de_ctx != NULL) SigCleanSignatures(de_ctx); - if (de_ctx != NULL) DetectEngineCtxFree(de_ctx); + if (de_ctx != NULL) + SigGroupCleanup(de_ctx); + if (de_ctx != NULL) + SigCleanSignatures(de_ctx); + if (de_ctx != NULL) + DetectEngineCtxFree(de_ctx); StreamTcpFreeConfig(true); FLOW_DESTROY(&f); diff --git a/src/detect-urilen.h b/src/detect-urilen.h index ccd319c75513..752255fb9dcb 100644 --- a/src/detect-urilen.h +++ b/src/detect-urilen.h @@ -22,11 +22,10 @@ */ #ifndef _DETECT_URILEN_H -#define _DETECT_URILEN_H +#define _DETECT_URILEN_H bool DetectUrilenValidateContent(const Signature *s, int list, const char **); void DetectUrilenApplyToContent(Signature *s, int list); void DetectUrilenRegister(void); -#endif /* _DETECT_URILEN_H */ - +#endif /* _DETECT_URILEN_H */ diff --git a/src/detect-within.c b/src/detect-within.c index 91662e070fde..644a1dbfc538 100644 --- a/src/detect-within.c +++ b/src/detect-within.c @@ -52,7 +52,8 @@ static void DetectWithinRegisterTests(void); void DetectWithinRegister(void) { sigmatch_table[DETECT_WITHIN].name = "within"; - sigmatch_table[DETECT_WITHIN].desc = "indicate that this content match has to be within a certain distance of the previous content keyword match"; + sigmatch_table[DETECT_WITHIN].desc = "indicate that this content match has to be within a " + "certain distance of the previous content keyword match"; sigmatch_table[DETECT_WITHIN].url = "/rules/payload-keywords.html#within"; sigmatch_table[DETECT_WITHIN].Match = NULL; sigmatch_table[DETECT_WITHIN].Setup = DetectWithinSetup; @@ -132,8 +133,7 @@ static int DetectWithinSetup(DetectEngineCtx *de_ctx, Signature *s, const char * /* these are the only ones against which we set a flag. We have other * relative keywords like byttest, isdataat, bytejump, but we don't * set a flag against them */ - SigMatch *prev_pm = DetectGetLastSMByListPtr(s, pm->prev, - DETECT_CONTENT, DETECT_PCRE, -1); + SigMatch *prev_pm = DetectGetLastSMByListPtr(s, pm->prev, DETECT_CONTENT, DETECT_PCRE, -1); if (prev_pm == NULL) { return 0; } @@ -158,18 +158,18 @@ static int DetectWithinSetup(DetectEngineCtx *de_ctx, Signature *s, const char * #ifdef UNITTESTS #include "util-unittest-helper.h" - /** +/** * \test DetectWithinTestPacket01 is a test to check matches of * within, if the previous keyword is pcre (bug 145) */ -static int DetectWithinTestPacket01 (void) +static int DetectWithinTestPacket01(void) { uint8_t *buf = (uint8_t *)"GET /AllWorkAndNoPlayMakesWillADullBoy HTTP/1.0" - "User-Agent: Wget/1.11.4" - "Accept: */*" - "Host: www.google.com" - "Connection: Keep-Alive" - "Date: Mon, 04 Jan 2010 17:29:39 GMT"; + "User-Agent: Wget/1.11.4" + "Accept: */*" + "Host: www.google.com" + "Connection: Keep-Alive" + "Date: Mon, 04 Jan 2010 17:29:39 GMT"; uint16_t buflen = strlen((char *)buf); Packet *p = UTHBuildPacket((uint8_t *)buf, buflen, IPPROTO_TCP); @@ -185,8 +185,7 @@ static int DetectWithinTestPacket01 (void) PASS; } - -static int DetectWithinTestPacket02 (void) +static int DetectWithinTestPacket02(void) { uint8_t *buf = (uint8_t *)"Zero Five Ten Fourteen"; uint16_t buflen = strlen((char *)buf); @@ -207,14 +206,14 @@ static int DetectWithinTestPacket02 (void) static int DetectWithinTestVarSetup(void) { char sig[] = "alert tcp any any -> any any ( " - "msg:\"test rule\"; " - "content:\"abc\"; " - "http_client_body; " - "byte_extract:2,0,somevar,relative; " - "content:\"def\"; " - "within:somevar; " - "http_client_body; " - "sid:4; rev:1;)"; + "msg:\"test rule\"; " + "content:\"abc\"; " + "http_client_body; " + "byte_extract:2,0,somevar,relative; " + "content:\"def\"; " + "within:somevar; " + "http_client_body; " + "sid:4; rev:1;)"; DetectEngineCtx *de_ctx = DetectEngineCtxInit(); FAIL_IF_NULL(de_ctx); diff --git a/src/detect-within.h b/src/detect-within.h index 7ccaf2648ae3..c5ec8c06f2f2 100644 --- a/src/detect-within.h +++ b/src/detect-within.h @@ -25,7 +25,6 @@ #define __DETECT_WITHIN_H__ /* prototypes */ -void DetectWithinRegister (void); +void DetectWithinRegister(void); #endif /* __DETECT_WITHIN_H__ */ - diff --git a/src/detect-xbits.c b/src/detect-xbits.c index a3f67dbfc9b7..f47376c8a4b1 100644 --- a/src/detect-xbits.c +++ b/src/detect-xbits.c @@ -55,24 +55,29 @@ xbits:set,bitname,track ip_pair,expire 60 */ -#define PARSE_REGEX "^([a-z]+)" "(?:,\\s*([^,]+))?" "(?:,\\s*(?:track\\s+([^,]+)))" "(?:,\\s*(?:expire\\s+([^,]+)))?" +#define PARSE_REGEX \ + "^([a-z]+)" \ + "(?:,\\s*([^,]+))?" \ + "(?:,\\s*(?:track\\s+([^,]+)))" \ + "(?:,\\s*(?:expire\\s+([^,]+)))?" static DetectParseRegex parse_regex; -static int DetectXbitMatch (DetectEngineThreadCtx *, Packet *, const Signature *, const SigMatchCtx *); -static int DetectXbitSetup (DetectEngineCtx *, Signature *, const char *); +static int DetectXbitMatch( + DetectEngineThreadCtx *, Packet *, const Signature *, const SigMatchCtx *); +static int DetectXbitSetup(DetectEngineCtx *, Signature *, const char *); #ifdef UNITTESTS static void XBitsRegisterTests(void); #endif -static void DetectXbitFree (DetectEngineCtx *, void *); +static void DetectXbitFree(DetectEngineCtx *, void *); -void DetectXbitsRegister (void) +void DetectXbitsRegister(void) { sigmatch_table[DETECT_XBITS].name = "xbits"; sigmatch_table[DETECT_XBITS].desc = "operate on bits"; sigmatch_table[DETECT_XBITS].url = "/rules/xbits.html"; sigmatch_table[DETECT_XBITS].Match = DetectXbitMatch; sigmatch_table[DETECT_XBITS].Setup = DetectXbitSetup; - sigmatch_table[DETECT_XBITS].Free = DetectXbitFree; + sigmatch_table[DETECT_XBITS].Free = DetectXbitFree; #ifdef UNITTESTS sigmatch_table[DETECT_XBITS].RegisterTests = XBitsRegisterTests; #endif @@ -82,7 +87,7 @@ void DetectXbitsRegister (void) DetectSetupParseRegexes(PARSE_REGEX, &parse_regex); } -static int DetectIPPairbitMatchToggle (Packet *p, const DetectXbitsData *fd) +static int DetectIPPairbitMatchToggle(Packet *p, const DetectXbitsData *fd) { IPPair *pair = IPPairGetIPPairFromHash(&p->src, &p->dst); if (pair == NULL) @@ -94,18 +99,18 @@ static int DetectIPPairbitMatchToggle (Packet *p, const DetectXbitsData *fd) } /* return true even if bit not found */ -static int DetectIPPairbitMatchUnset (Packet *p, const DetectXbitsData *fd) +static int DetectIPPairbitMatchUnset(Packet *p, const DetectXbitsData *fd) { IPPair *pair = IPPairLookupIPPairFromHash(&p->src, &p->dst); if (pair == NULL) return 1; - IPPairBitUnset(pair,fd->idx); + IPPairBitUnset(pair, fd->idx); IPPairRelease(pair); return 1; } -static int DetectIPPairbitMatchSet (Packet *p, const DetectXbitsData *fd) +static int DetectIPPairbitMatchSet(Packet *p, const DetectXbitsData *fd) { IPPair *pair = IPPairGetIPPairFromHash(&p->src, &p->dst); if (pair == NULL) @@ -116,7 +121,7 @@ static int DetectIPPairbitMatchSet (Packet *p, const DetectXbitsData *fd) return 1; } -static int DetectIPPairbitMatchIsset (Packet *p, const DetectXbitsData *fd) +static int DetectIPPairbitMatchIsset(Packet *p, const DetectXbitsData *fd) { int r = 0; IPPair *pair = IPPairLookupIPPairFromHash(&p->src, &p->dst); @@ -128,7 +133,7 @@ static int DetectIPPairbitMatchIsset (Packet *p, const DetectXbitsData *fd) return r; } -static int DetectIPPairbitMatchIsnotset (Packet *p, const DetectXbitsData *fd) +static int DetectIPPairbitMatchIsnotset(Packet *p, const DetectXbitsData *fd) { int r = 0; IPPair *pair = IPPairLookupIPPairFromHash(&p->src, &p->dst); @@ -144,15 +149,15 @@ static int DetectXbitMatchIPPair(Packet *p, const DetectXbitsData *xd) { switch (xd->cmd) { case DETECT_XBITS_CMD_ISSET: - return DetectIPPairbitMatchIsset(p,xd); + return DetectIPPairbitMatchIsset(p, xd); case DETECT_XBITS_CMD_ISNOTSET: - return DetectIPPairbitMatchIsnotset(p,xd); + return DetectIPPairbitMatchIsnotset(p, xd); case DETECT_XBITS_CMD_SET: - return DetectIPPairbitMatchSet(p,xd); + return DetectIPPairbitMatchSet(p, xd); case DETECT_XBITS_CMD_UNSET: - return DetectIPPairbitMatchUnset(p,xd); + return DetectIPPairbitMatchUnset(p, xd); case DETECT_XBITS_CMD_TOGGLE: - return DetectIPPairbitMatchToggle(p,xd); + return DetectIPPairbitMatchToggle(p, xd); } return 0; } @@ -163,7 +168,8 @@ static int DetectXbitMatchIPPair(Packet *p, const DetectXbitsData *xd) * -1: error */ -static int DetectXbitMatch (DetectEngineThreadCtx *det_ctx, Packet *p, const Signature *s, const SigMatchCtx *ctx) +static int DetectXbitMatch( + DetectEngineThreadCtx *det_ctx, Packet *p, const Signature *s, const SigMatchCtx *ctx) { const DetectXbitsData *fd = (const DetectXbitsData *)ctx; if (fd == NULL) @@ -188,8 +194,7 @@ static int DetectXbitMatch (DetectEngineThreadCtx *det_ctx, Packet *p, const Sig * \retval -1 bad * \param[out] cdout return DetectXbitsData structure or NULL if noalert */ -static int DetectXbitParse(DetectEngineCtx *de_ctx, - const char *rawstr, DetectXbitsData **cdout) +static int DetectXbitParse(DetectEngineCtx *de_ctx, const char *rawstr, DetectXbitsData **cdout) { DetectXbitsData *cd = NULL; uint8_t fb_cmd = 0; @@ -281,17 +286,17 @@ static int DetectXbitParse(DetectEngineCtx *de_ctx, } pcre2_match_data_free(match); - if (strcmp(fb_cmd_str,"noalert") == 0) { + if (strcmp(fb_cmd_str, "noalert") == 0) { fb_cmd = DETECT_XBITS_CMD_NOALERT; - } else if (strcmp(fb_cmd_str,"isset") == 0) { + } else if (strcmp(fb_cmd_str, "isset") == 0) { fb_cmd = DETECT_XBITS_CMD_ISSET; - } else if (strcmp(fb_cmd_str,"isnotset") == 0) { + } else if (strcmp(fb_cmd_str, "isnotset") == 0) { fb_cmd = DETECT_XBITS_CMD_ISNOTSET; - } else if (strcmp(fb_cmd_str,"set") == 0) { + } else if (strcmp(fb_cmd_str, "set") == 0) { fb_cmd = DETECT_XBITS_CMD_SET; - } else if (strcmp(fb_cmd_str,"unset") == 0) { + } else if (strcmp(fb_cmd_str, "unset") == 0) { fb_cmd = DETECT_XBITS_CMD_UNSET; - } else if (strcmp(fb_cmd_str,"toggle") == 0) { + } else if (strcmp(fb_cmd_str, "toggle") == 0) { fb_cmd = DETECT_XBITS_CMD_TOGGLE; } else { SCLogError("xbits action \"%s\" is not supported.", fb_cmd_str); @@ -326,14 +331,14 @@ static int DetectXbitParse(DetectEngineCtx *de_ctx, cd->type = var_type; cd->expire = expire; - SCLogDebug("idx %" PRIu32 ", cmd %s, name %s", - cd->idx, fb_cmd_str, strlen(fb_name) ? fb_name : "(none)"); + SCLogDebug("idx %" PRIu32 ", cmd %s, name %s", cd->idx, fb_cmd_str, + strlen(fb_name) ? fb_name : "(none)"); *cdout = cd; return 0; } -int DetectXbitSetup (DetectEngineCtx *de_ctx, Signature *s, const char *rawstr) +int DetectXbitSetup(DetectEngineCtx *de_ctx, Signature *s, const char *rawstr) { DetectXbitsData *cd = NULL; @@ -375,7 +380,7 @@ int DetectXbitSetup (DetectEngineCtx *de_ctx, Signature *s, const char *rawstr) return 0; } -static void DetectXbitFree (DetectEngineCtx *de_ctx, void *ptr) +static void DetectXbitFree(DetectEngineCtx *de_ctx, void *ptr) { DetectXbitsData *fd = (DetectXbitsData *)ptr; @@ -405,7 +410,6 @@ static void XBitsTestShutdown(void) StorageCleanup(); } - static int XBitsTestParse01(void) { DetectEngineCtx *de_ctx = NULL; @@ -414,8 +418,7 @@ static int XBitsTestParse01(void) de_ctx->flags |= DE_QUIET; DetectXbitsData *cd = NULL; -#define BAD_INPUT(str) \ - FAIL_IF_NOT(DetectXbitParse(de_ctx, (str), &cd) == -1); +#define BAD_INPUT(str) FAIL_IF_NOT(DetectXbitParse(de_ctx, (str), &cd) == -1); BAD_INPUT("alert"); BAD_INPUT("n0alert"); @@ -427,28 +430,22 @@ static int XBitsTestParse01(void) #undef BAD_INPUT -#define GOOD_INPUT(str, command, trk, typ, exp) \ - FAIL_IF_NOT(DetectXbitParse(de_ctx, (str), &cd) == 0); \ - FAIL_IF_NULL(cd); \ - FAIL_IF_NOT(cd->cmd == (command)); \ - FAIL_IF_NOT(cd->tracker == (trk)); \ - FAIL_IF_NOT(cd->type == (typ)); \ - FAIL_IF_NOT(cd->expire == (exp)); \ - DetectXbitFree(NULL, cd); \ +#define GOOD_INPUT(str, command, trk, typ, exp) \ + FAIL_IF_NOT(DetectXbitParse(de_ctx, (str), &cd) == 0); \ + FAIL_IF_NULL(cd); \ + FAIL_IF_NOT(cd->cmd == (command)); \ + FAIL_IF_NOT(cd->tracker == (trk)); \ + FAIL_IF_NOT(cd->type == (typ)); \ + FAIL_IF_NOT(cd->expire == (exp)); \ + DetectXbitFree(NULL, cd); \ cd = NULL; - GOOD_INPUT("set,abc,track ip_pair", - DETECT_XBITS_CMD_SET, - DETECT_XBITS_TRACK_IPPAIR, VAR_TYPE_IPPAIR_BIT, - DETECT_XBITS_EXPIRE_DEFAULT); - GOOD_INPUT("set,abc,track ip_pair, expire 3600", - DETECT_XBITS_CMD_SET, - DETECT_XBITS_TRACK_IPPAIR, VAR_TYPE_IPPAIR_BIT, - 3600); - GOOD_INPUT("set,abc,track ip_src, expire 1234", - DETECT_XBITS_CMD_SET, - DETECT_XBITS_TRACK_IPSRC, VAR_TYPE_HOST_BIT, - 1234); + GOOD_INPUT("set,abc,track ip_pair", DETECT_XBITS_CMD_SET, DETECT_XBITS_TRACK_IPPAIR, + VAR_TYPE_IPPAIR_BIT, DETECT_XBITS_EXPIRE_DEFAULT); + GOOD_INPUT("set,abc,track ip_pair, expire 3600", DETECT_XBITS_CMD_SET, + DETECT_XBITS_TRACK_IPPAIR, VAR_TYPE_IPPAIR_BIT, 3600); + GOOD_INPUT("set,abc,track ip_src, expire 1234", DETECT_XBITS_CMD_SET, DETECT_XBITS_TRACK_IPSRC, + VAR_TYPE_HOST_BIT, 1234); #undef GOOD_INPUT @@ -462,10 +459,9 @@ static int XBitsTestParse01(void) static int XBitsTestSig01(void) { - uint8_t *buf = (uint8_t *) - "GET /one/ HTTP/1.1\r\n" - "Host: one.example.org\r\n" - "\r\n"; + uint8_t *buf = (uint8_t *)"GET /one/ HTTP/1.1\r\n" + "Host: one.example.org\r\n" + "\r\n"; uint16_t buflen = strlen((char *)buf); Packet *p = PacketGetFromAlloc(); FAIL_IF_NULL(p); @@ -522,8 +518,8 @@ static int XBitsTestSig02(void) "alert ip any any -> any any (xbits:isset,abc,track ip_src; content:\"GET \"; sid:1;)"); FAIL_IF_NULL(s); - s = DetectEngineAppendSig(de_ctx, - "alert ip any any -> any any (xbits:isnotset,abc,track ip_dst; content:\"GET \"; sid:2;)"); + s = DetectEngineAppendSig(de_ctx, "alert ip any any -> any any (xbits:isnotset,abc,track " + "ip_dst; content:\"GET \"; sid:2;)"); FAIL_IF_NULL(s); s = DetectEngineAppendSig(de_ctx, @@ -534,8 +530,8 @@ static int XBitsTestSig02(void) "alert ip any any -> any any (xbits:unset,abc,track ip_src; content:\"GET \"; sid:4;)"); FAIL_IF_NULL(s); - s = DetectEngineAppendSig(de_ctx, - "alert ip any any -> any any (xbits:toggle,abc,track ip_dst; content:\"GET \"; sid:5;)"); + s = DetectEngineAppendSig(de_ctx, "alert ip any any -> any any (xbits:toggle,abc,track ip_dst; " + "content:\"GET \"; sid:5;)"); FAIL_IF_NULL(s); s = DetectEngineAppendSig(de_ctx, diff --git a/src/detect-xbits.h b/src/detect-xbits.h index 516bfdcfd1bc..b8cacf1f4114 100644 --- a/src/detect-xbits.h +++ b/src/detect-xbits.h @@ -47,6 +47,6 @@ typedef struct DetectXbitsData_ { } DetectXbitsData; /* prototypes */ -void DetectXbitsRegister (void); +void DetectXbitsRegister(void); #endif /* __DETECT_XBITS_H__ */ diff --git a/src/detect.c b/src/detect.c index 5cb4e6bfbc44..8007190613ad 100644 --- a/src/detect.c +++ b/src/detect.c @@ -77,33 +77,29 @@ typedef struct DetectRunScratchpad { /* prototypes */ static DetectRunScratchpad DetectRunSetup(const DetectEngineCtx *de_ctx, - DetectEngineThreadCtx *det_ctx, Packet * const p, Flow * const pflow); + DetectEngineThreadCtx *det_ctx, Packet *const p, Flow *const pflow); static void DetectRunInspectIPOnly(ThreadVars *tv, const DetectEngineCtx *de_ctx, - DetectEngineThreadCtx *det_ctx, Flow * const pflow, Packet * const p); -static inline void DetectRunGetRuleGroup(const DetectEngineCtx *de_ctx, - Packet * const p, Flow * const pflow, DetectRunScratchpad *scratch); -static inline void DetectRunPrefilterPkt(ThreadVars *tv, - DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx, Packet *p, - DetectRunScratchpad *scratch); -static inline void DetectRulePacketRules(ThreadVars * const tv, - DetectEngineCtx * const de_ctx, DetectEngineThreadCtx * const det_ctx, - Packet * const p, Flow * const pflow, const DetectRunScratchpad *scratch); -static void DetectRunTx(ThreadVars *tv, DetectEngineCtx *de_ctx, - DetectEngineThreadCtx *det_ctx, Packet *p, - Flow *f, DetectRunScratchpad *scratch); + DetectEngineThreadCtx *det_ctx, Flow *const pflow, Packet *const p); +static inline void DetectRunGetRuleGroup(const DetectEngineCtx *de_ctx, Packet *const p, + Flow *const pflow, DetectRunScratchpad *scratch); +static inline void DetectRunPrefilterPkt(ThreadVars *tv, DetectEngineCtx *de_ctx, + DetectEngineThreadCtx *det_ctx, Packet *p, DetectRunScratchpad *scratch); +static inline void DetectRulePacketRules(ThreadVars *const tv, DetectEngineCtx *const de_ctx, + DetectEngineThreadCtx *const det_ctx, Packet *const p, Flow *const pflow, + const DetectRunScratchpad *scratch); +static void DetectRunTx(ThreadVars *tv, DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx, + Packet *p, Flow *f, DetectRunScratchpad *scratch); static void DetectRunFrames(ThreadVars *tv, DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx, Packet *p, Flow *f, DetectRunScratchpad *scratch); static inline void DetectRunPostRules(ThreadVars *tv, DetectEngineCtx *de_ctx, - DetectEngineThreadCtx *det_ctx, Packet * const p, Flow * const pflow, + DetectEngineThreadCtx *det_ctx, Packet *const p, Flow *const pflow, DetectRunScratchpad *scratch); -static void DetectRunCleanup(DetectEngineThreadCtx *det_ctx, - Packet *p, Flow * const pflow); +static void DetectRunCleanup(DetectEngineThreadCtx *det_ctx, Packet *p, Flow *const pflow); /** \internal */ -static void DetectRun(ThreadVars *th_v, - DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx, - Packet *p) +static void DetectRun( + ThreadVars *th_v, DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx, Packet *p) { SCEnter(); SCLogDebug("p->pcap_cnt %" PRIu64 " direction %s pkt_src %s", p->pcap_cnt, @@ -119,7 +115,7 @@ static void DetectRun(ThreadVars *th_v, /* Load the Packet's flow early, even though it might not be needed. * Mark as a constant pointer, although the flow itself can change. */ - Flow * const pflow = p->flow; + Flow *const pflow = p->flow; DetectRunScratchpad scratch = DetectRunSetup(de_ctx, det_ctx, p, pflow); @@ -168,9 +164,8 @@ static void DetectRun(ThreadVars *th_v, SCReturn; } -static void DetectRunPostMatch(ThreadVars *tv, - DetectEngineThreadCtx *det_ctx, Packet *p, - const Signature *s) +static void DetectRunPostMatch( + ThreadVars *tv, DetectEngineThreadCtx *det_ctx, Packet *p, const Signature *s) { /* run the packet match functions */ const SigMatchData *smd = s->sm_arrays[DETECT_SM_LIST_POSTMATCH]; @@ -198,8 +193,7 @@ static void DetectRunPostMatch(ThreadVars *tv, * * \retval sgh the SigGroupHead or NULL if non applies to the packet */ -const SigGroupHead *SigMatchSignaturesGetSgh(const DetectEngineCtx *de_ctx, - const Packet *p) +const SigGroupHead *SigMatchSignaturesGetSgh(const DetectEngineCtx *de_ctx, const Packet *p) { SCEnter(); @@ -226,23 +220,23 @@ const SigGroupHead *SigMatchSignaturesGetSgh(const DetectEngineCtx *de_ctx, int proto = IP_GET_IPPROTO(p); if (proto == IPPROTO_TCP) { DetectPort *list = de_ctx->flow_gh[f].tcp; - SCLogDebug("tcp toserver %p, tcp toclient %p: going to use %p", - de_ctx->flow_gh[1].tcp, de_ctx->flow_gh[0].tcp, de_ctx->flow_gh[f].tcp); + SCLogDebug("tcp toserver %p, tcp toclient %p: going to use %p", de_ctx->flow_gh[1].tcp, + de_ctx->flow_gh[0].tcp, de_ctx->flow_gh[f].tcp); uint16_t port = f ? p->dp : p->sp; SCLogDebug("tcp port %u -> %u:%u", port, p->sp, p->dp); DetectPort *sghport = DetectPortLookupGroup(list, port); if (sghport != NULL) sgh = sghport->sh; - SCLogDebug("TCP list %p, port %u, direction %s, sghport %p, sgh %p", - list, port, f ? "toserver" : "toclient", sghport, sgh); + SCLogDebug("TCP list %p, port %u, direction %s, sghport %p, sgh %p", list, port, + f ? "toserver" : "toclient", sghport, sgh); } else if (proto == IPPROTO_UDP) { DetectPort *list = de_ctx->flow_gh[f].udp; uint16_t port = f ? p->dp : p->sp; DetectPort *sghport = DetectPortLookupGroup(list, port); if (sghport != NULL) sgh = sghport->sh; - SCLogDebug("UDP list %p, port %u, direction %s, sghport %p, sgh %p", - list, port, f ? "toserver" : "toclient", sghport, sgh); + SCLogDebug("UDP list %p, port %u, direction %s, sghport %p, sgh %p", list, port, + f ? "toserver" : "toclient", sghport, sgh); } else { sgh = de_ctx->flow_gh[f].sgh[proto]; } @@ -250,8 +244,7 @@ const SigGroupHead *SigMatchSignaturesGetSgh(const DetectEngineCtx *de_ctx, SCReturnPtr(sgh, "SigGroupHead"); } -static inline void DetectPrefilterMergeSort(DetectEngineCtx *de_ctx, - DetectEngineThreadCtx *det_ctx) +static inline void DetectPrefilterMergeSort(DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx) { SigIntId mpm, nonmpm; SigIntId *mpm_ptr = det_ctx->pmq.rule_id_array; @@ -301,25 +294,25 @@ static inline void DetectPrefilterMergeSort(DetectEngineCtx *de_ctx, final_ptr = nonmpm_ptr; final_cnt = n_cnt; goto final; - } - mpm_ptr++; - mpm = *mpm_ptr; - } else if (mpm > nonmpm) { - id = nonmpm; - - s = sig_array[id]; - /* As the mpm list can contain duplicates, check for that here. */ - if (likely(id != previous_id)) { - *match_array++ = s; - previous_id = id; - } - if (unlikely(--n_cnt == 0)) { - final_ptr = mpm_ptr; - final_cnt = m_cnt; - goto final; - } - nonmpm_ptr++; - nonmpm = *nonmpm_ptr; + } + mpm_ptr++; + mpm = *mpm_ptr; + } else if (mpm > nonmpm) { + id = nonmpm; + + s = sig_array[id]; + /* As the mpm list can contain duplicates, check for that here. */ + if (likely(id != previous_id)) { + *match_array++ = s; + previous_id = id; + } + if (unlikely(--n_cnt == 0)) { + final_ptr = mpm_ptr; + final_cnt = m_cnt; + goto final; + } + nonmpm_ptr++; + nonmpm = *nonmpm_ptr; } else { /* implied mpm == nonmpm */ /* special case: if on both lists, it's a negated mpm pattern */ @@ -355,7 +348,7 @@ static inline void DetectPrefilterMergeSort(DetectEngineCtx *de_ctx, } } - final: /* Only one list remaining. Just walk that list. */ +final: /* Only one list remaining. Just walk that list. */ while (final_cnt-- > 0) { id = *final_ptr++; @@ -369,7 +362,8 @@ static inline void DetectPrefilterMergeSort(DetectEngineCtx *de_ctx, } det_ctx->match_array_cnt = match_array - det_ctx->match_array; - DEBUG_VALIDATE_BUG_ON((det_ctx->pmq.rule_id_array_cnt + det_ctx->non_pf_id_cnt) < det_ctx->match_array_cnt); + DEBUG_VALIDATE_BUG_ON( + (det_ctx->pmq.rule_id_array_cnt + det_ctx->non_pf_id_cnt) < det_ctx->match_array_cnt); PMQ_RESET(&det_ctx->pmq); } @@ -395,8 +389,8 @@ static inline void DetectPrefilterBuildNonPrefilterList( * \brief select non-mpm list * Based on the packet properties, select the non-mpm list to use * \todo move non_pf_store* into scratchpad */ -static inline void -DetectPrefilterSetNonPrefilterList(const Packet *p, DetectEngineThreadCtx *det_ctx, DetectRunScratchpad *scratch) +static inline void DetectPrefilterSetNonPrefilterList( + const Packet *p, DetectEngineThreadCtx *det_ctx, DetectRunScratchpad *scratch) { if ((p->proto == IPPROTO_TCP) && (p->tcph != NULL) && (p->tcph->th_flags & TH_SYN)) { det_ctx->non_pf_store_ptr = scratch->sgh->non_pf_syn_store_array; @@ -405,10 +399,10 @@ DetectPrefilterSetNonPrefilterList(const Packet *p, DetectEngineThreadCtx *det_c det_ctx->non_pf_store_ptr = scratch->sgh->non_pf_other_store_array; det_ctx->non_pf_store_cnt = scratch->sgh->non_pf_other_store_cnt; } - SCLogDebug("sgh non_pf ptr %p cnt %u (syn %p/%u, other %p/%u)", - det_ctx->non_pf_store_ptr, det_ctx->non_pf_store_cnt, - scratch->sgh->non_pf_syn_store_array, scratch->sgh->non_pf_syn_store_cnt, - scratch->sgh->non_pf_other_store_array, scratch->sgh->non_pf_other_store_cnt); + SCLogDebug("sgh non_pf ptr %p cnt %u (syn %p/%u, other %p/%u)", det_ctx->non_pf_store_ptr, + det_ctx->non_pf_store_cnt, scratch->sgh->non_pf_syn_store_array, + scratch->sgh->non_pf_syn_store_cnt, scratch->sgh->non_pf_other_store_array, + scratch->sgh->non_pf_other_store_cnt); } /** \internal @@ -416,8 +410,8 @@ DetectPrefilterSetNonPrefilterList(const Packet *p, DetectEngineThreadCtx *det_c * A set of flags is prepared that is sent to the File API. The File API may reject one or more based on the global force settings. */ -static inline void -DetectPostInspectFileFlagsUpdate(Flow *f, const SigGroupHead *sgh, uint8_t direction) +static inline void DetectPostInspectFileFlagsUpdate( + Flow *f, const SigGroupHead *sgh, uint8_t direction) { uint16_t flow_file_flags = FLOWFILE_INIT; @@ -427,29 +421,29 @@ DetectPostInspectFileFlagsUpdate(Flow *f, const SigGroupHead *sgh, uint8_t direc } else { if (sgh->filestore_cnt == 0) { SCLogDebug("requesting disabling filestore for flow"); - flow_file_flags |= (FLOWFILE_NO_STORE_TS|FLOWFILE_NO_STORE_TC); + flow_file_flags |= (FLOWFILE_NO_STORE_TS | FLOWFILE_NO_STORE_TC); } #ifdef HAVE_MAGIC if (!(sgh->flags & SIG_GROUP_HEAD_HAVEFILEMAGIC)) { SCLogDebug("requesting disabling magic for flow"); - flow_file_flags |= (FLOWFILE_NO_MAGIC_TS|FLOWFILE_NO_MAGIC_TC); + flow_file_flags |= (FLOWFILE_NO_MAGIC_TS | FLOWFILE_NO_MAGIC_TC); } #endif if (!(sgh->flags & SIG_GROUP_HEAD_HAVEFILEMD5)) { SCLogDebug("requesting disabling md5 for flow"); - flow_file_flags |= (FLOWFILE_NO_MD5_TS|FLOWFILE_NO_MD5_TC); + flow_file_flags |= (FLOWFILE_NO_MD5_TS | FLOWFILE_NO_MD5_TC); } if (!(sgh->flags & SIG_GROUP_HEAD_HAVEFILESHA1)) { SCLogDebug("requesting disabling sha1 for flow"); - flow_file_flags |= (FLOWFILE_NO_SHA1_TS|FLOWFILE_NO_SHA1_TC); + flow_file_flags |= (FLOWFILE_NO_SHA1_TS | FLOWFILE_NO_SHA1_TC); } if (!(sgh->flags & SIG_GROUP_HEAD_HAVEFILESHA256)) { SCLogDebug("requesting disabling sha256 for flow"); - flow_file_flags |= (FLOWFILE_NO_SHA256_TS|FLOWFILE_NO_SHA256_TC); + flow_file_flags |= (FLOWFILE_NO_SHA256_TS | FLOWFILE_NO_SHA256_TC); } if (!(sgh->flags & SIG_GROUP_HEAD_HAVEFILESIZE)) { SCLogDebug("requesting disabling filesize for flow"); - flow_file_flags |= (FLOWFILE_NO_SIZE_TS|FLOWFILE_NO_SIZE_TC); + flow_file_flags |= (FLOWFILE_NO_SIZE_TS | FLOWFILE_NO_SIZE_TC); } } if (flow_file_flags != 0) { @@ -457,15 +451,16 @@ DetectPostInspectFileFlagsUpdate(Flow *f, const SigGroupHead *sgh, uint8_t direc } } -static inline void -DetectRunPostGetFirstRuleGroup(const Packet *p, Flow *pflow, const SigGroupHead *sgh) +static inline void DetectRunPostGetFirstRuleGroup( + const Packet *p, Flow *pflow, const SigGroupHead *sgh) { if ((p->flowflags & FLOW_PKT_TOSERVER) && !(pflow->flags & FLOW_SGH_TOSERVER)) { /* first time we see this toserver sgh, store it */ pflow->sgh_toserver = sgh; pflow->flags |= FLOW_SGH_TOSERVER; - if (p->proto == IPPROTO_TCP && (sgh == NULL || !(sgh->flags & SIG_GROUP_HEAD_HAVERAWSTREAM))) { + if (p->proto == IPPROTO_TCP && + (sgh == NULL || !(sgh->flags & SIG_GROUP_HEAD_HAVERAWSTREAM))) { if (pflow->protoctx != NULL) { TcpSession *ssn = pflow->protoctx; SCLogDebug("STREAMTCP_STREAM_FLAG_DISABLE_RAW ssn.client"); @@ -473,14 +468,14 @@ DetectRunPostGetFirstRuleGroup(const Packet *p, Flow *pflow, const SigGroupHead } } - DetectPostInspectFileFlagsUpdate(pflow, - pflow->sgh_toserver, STREAM_TOSERVER); + DetectPostInspectFileFlagsUpdate(pflow, pflow->sgh_toserver, STREAM_TOSERVER); } else if ((p->flowflags & FLOW_PKT_TOCLIENT) && !(pflow->flags & FLOW_SGH_TOCLIENT)) { pflow->sgh_toclient = sgh; pflow->flags |= FLOW_SGH_TOCLIENT; - if (p->proto == IPPROTO_TCP && (sgh == NULL || !(sgh->flags & SIG_GROUP_HEAD_HAVERAWSTREAM))) { + if (p->proto == IPPROTO_TCP && + (sgh == NULL || !(sgh->flags & SIG_GROUP_HEAD_HAVERAWSTREAM))) { if (pflow->protoctx != NULL) { TcpSession *ssn = pflow->protoctx; SCLogDebug("STREAMTCP_STREAM_FLAG_DISABLE_RAW ssn.server"); @@ -488,15 +483,12 @@ DetectRunPostGetFirstRuleGroup(const Packet *p, Flow *pflow, const SigGroupHead } } - DetectPostInspectFileFlagsUpdate(pflow, - pflow->sgh_toclient, STREAM_TOCLIENT); + DetectPostInspectFileFlagsUpdate(pflow, pflow->sgh_toclient, STREAM_TOCLIENT); } } -static inline void DetectRunGetRuleGroup( - const DetectEngineCtx *de_ctx, - Packet * const p, Flow * const pflow, - DetectRunScratchpad *scratch) +static inline void DetectRunGetRuleGroup(const DetectEngineCtx *de_ctx, Packet *const p, + Flow *const pflow, DetectRunScratchpad *scratch) { const SigGroupHead *sgh = NULL; @@ -546,8 +538,7 @@ static inline void DetectRunGetRuleGroup( } static void DetectRunInspectIPOnly(ThreadVars *tv, const DetectEngineCtx *de_ctx, - DetectEngineThreadCtx *det_ctx, - Flow * const pflow, Packet * const p) + DetectEngineThreadCtx *det_ctx, Flow *const pflow, Packet *const p) { if (pflow) { /* set the iponly stuff */ @@ -556,9 +547,10 @@ static void DetectRunInspectIPOnly(ThreadVars *tv, const DetectEngineCtx *de_ctx if (pflow->flags & FLOW_TOSERVER_IPONLY_SET) p->flowflags |= FLOW_PKT_TOSERVER_IPONLY_SET; - if (((p->flowflags & FLOW_PKT_TOSERVER) && !(p->flowflags & FLOW_PKT_TOSERVER_IPONLY_SET)) || - ((p->flowflags & FLOW_PKT_TOCLIENT) && !(p->flowflags & FLOW_PKT_TOCLIENT_IPONLY_SET))) - { + if (((p->flowflags & FLOW_PKT_TOSERVER) && + !(p->flowflags & FLOW_PKT_TOSERVER_IPONLY_SET)) || + ((p->flowflags & FLOW_PKT_TOCLIENT) && + !(p->flowflags & FLOW_PKT_TOCLIENT_IPONLY_SET))) { SCLogDebug("testing against \"ip-only\" signatures"); PACKET_PROFILING_DETECT_START(p, PROF_DETECT_IPONLY); @@ -579,12 +571,8 @@ static void DetectRunInspectIPOnly(ThreadVars *tv, const DetectEngineCtx *de_ctx } /* returns 0 if no match, 1 if match */ -static inline int DetectRunInspectRuleHeader( - const Packet *p, - const Flow *f, - const Signature *s, - const uint32_t sflags, - const uint8_t s_proto_flags) +static inline int DetectRunInspectRuleHeader(const Packet *p, const Flow *f, const Signature *s, + const uint32_t sflags, const uint8_t s_proto_flags) { /* check if this signature has a requirement for flowvars of some type * and if so, if we actually have any in the flow. If not, the sig @@ -592,12 +580,12 @@ static inline int DetectRunInspectRuleHeader( if ((p->flags & PKT_HAS_FLOW) && (sflags & SIG_FLAG_REQUIRE_FLOWVAR)) { DEBUG_VALIDATE_BUG_ON(f == NULL); - int m = f->flowvar ? 1 : 0; + int m = f->flowvar ? 1 : 0; /* no flowvars? skip this sig */ if (m == 0) { SCLogDebug("skipping sig as the flow has no flowvars and sig " - "has SIG_FLAG_REQUIRE_FLOWVAR flag set."); + "has SIG_FLAG_REQUIRE_FLOWVAR flag set."); return 0; } } @@ -621,7 +609,7 @@ static inline int DetectRunInspectRuleHeader( if (!(sflags & SIG_FLAG_DP_ANY)) { if (p->flags & PKT_IS_FRAGMENT) return 0; - DetectPort *dport = DetectPortLookupGroup(s->dp,p->dp); + DetectPort *dport = DetectPortLookupGroup(s->dp, p->dp); if (dport == NULL) { SCLogDebug("dport didn't match."); return 0; @@ -630,13 +618,14 @@ static inline int DetectRunInspectRuleHeader( if (!(sflags & SIG_FLAG_SP_ANY)) { if (p->flags & PKT_IS_FRAGMENT) return 0; - DetectPort *sport = DetectPortLookupGroup(s->sp,p->sp); + DetectPort *sport = DetectPortLookupGroup(s->sp, p->sp); if (sport == NULL) { SCLogDebug("sport didn't match."); return 0; } } - } else if ((sflags & (SIG_FLAG_DP_ANY|SIG_FLAG_SP_ANY)) != (SIG_FLAG_DP_ANY|SIG_FLAG_SP_ANY)) { + } else if ((sflags & (SIG_FLAG_DP_ANY | SIG_FLAG_SP_ANY)) != + (SIG_FLAG_DP_ANY | SIG_FLAG_SP_ANY)) { SCLogDebug("port-less protocol and sig needs ports"); return 0; } @@ -668,13 +657,8 @@ static inline int DetectRunInspectRuleHeader( /** \internal * \brief run packet/stream prefilter engines */ -static inline void DetectRunPrefilterPkt( - ThreadVars *tv, - DetectEngineCtx *de_ctx, - DetectEngineThreadCtx *det_ctx, - Packet *p, - DetectRunScratchpad *scratch -) +static inline void DetectRunPrefilterPkt(ThreadVars *tv, DetectEngineCtx *de_ctx, + DetectEngineThreadCtx *det_ctx, Packet *p, DetectRunScratchpad *scratch) { DetectPrefilterSetNonPrefilterList(p, det_ctx, scratch); @@ -705,23 +689,16 @@ static inline void DetectRunPrefilterPkt( #ifdef PROFILING if (tv) { - StatsAddUI64(tv, det_ctx->counter_nonmpm_list, - (uint64_t)det_ctx->non_pf_store_cnt); + StatsAddUI64(tv, det_ctx->counter_nonmpm_list, (uint64_t)det_ctx->non_pf_store_cnt); /* non mpm sigs after mask prefilter */ - StatsAddUI64(tv, det_ctx->counter_fnonmpm_list, - (uint64_t)det_ctx->non_pf_id_cnt); + StatsAddUI64(tv, det_ctx->counter_fnonmpm_list, (uint64_t)det_ctx->non_pf_id_cnt); } #endif } -static inline void DetectRulePacketRules( - ThreadVars * const tv, - DetectEngineCtx * const de_ctx, - DetectEngineThreadCtx * const det_ctx, - Packet * const p, - Flow * const pflow, - const DetectRunScratchpad *scratch -) +static inline void DetectRulePacketRules(ThreadVars *const tv, DetectEngineCtx *const de_ctx, + DetectEngineThreadCtx *const det_ctx, Packet *const p, Flow *const pflow, + const DetectRunScratchpad *scratch) { const Signature *s = NULL; const Signature *next_s = NULL; @@ -731,8 +708,7 @@ static inline void DetectRulePacketRules( SigIntId match_cnt = det_ctx->match_array_cnt; #ifdef PROFILING if (tv) { - StatsAddUI64(tv, det_ctx->counter_match_list, - (uint64_t)match_cnt); + StatsAddUI64(tv, det_ctx->counter_match_list, (uint64_t)match_cnt); } #endif Signature **match_array = det_ctx->match_array; @@ -762,7 +738,7 @@ static inline void DetectRulePacketRules( } const uint8_t s_proto_flags = s->proto.flags; - SCLogDebug("inspecting signature id %"PRIu32"", s->id); + SCLogDebug("inspecting signature id %" PRIu32 "", s->id); if (s->app_inspect != NULL) { goto next; // handle sig in DetectRunTx @@ -803,7 +779,7 @@ static inline void DetectRulePacketRules( DetectRunPostMatch(tv, det_ctx, p, s); AlertQueueAppend(det_ctx, s, p, 0, alert_flags); -next: + next: DetectVarProcessList(det_ctx, pflow, p); DetectReplaceFree(det_ctx); RULE_PROFILING_END(det_ctx, s, smatch, p); @@ -813,10 +789,8 @@ static inline void DetectRulePacketRules( } } -static DetectRunScratchpad DetectRunSetup( - const DetectEngineCtx *de_ctx, - DetectEngineThreadCtx *det_ctx, - Packet * const p, Flow * const pflow) +static DetectRunScratchpad DetectRunSetup(const DetectEngineCtx *de_ctx, + DetectEngineThreadCtx *det_ctx, Packet *const p, Flow *const pflow) { AppProto alproto = ALPROTO_UNKNOWN; uint8_t flow_flags = 0; /* flow/state flags */ @@ -887,10 +861,8 @@ static DetectRunScratchpad DetectRunSetup( /* Retrieve the app layer state and protocol and the tcp reassembled * stream chunks. */ - if ((p->proto == IPPROTO_TCP && (p->flags & PKT_STREAM_EST)) || - (p->proto == IPPROTO_UDP) || - (p->proto == IPPROTO_SCTP && (p->flowflags & FLOW_PKT_ESTABLISHED))) - { + if ((p->proto == IPPROTO_TCP && (p->flags & PKT_STREAM_EST)) || (p->proto == IPPROTO_UDP) || + (p->proto == IPPROTO_SCTP && (p->flowflags & FLOW_PKT_ESTABLISHED))) { /* update flow flags with knowledge on disruptions */ flow_flags = FlowGetDisruptionFlags(pflow, flow_flags); alproto = FlowGetAppProtocol(pflow); @@ -911,13 +883,9 @@ static DetectRunScratchpad DetectRunSetup( return pad; } -static inline void DetectRunPostRules( - ThreadVars *tv, - DetectEngineCtx *de_ctx, - DetectEngineThreadCtx *det_ctx, - Packet * const p, - Flow * const pflow, - DetectRunScratchpad *scratch) +static inline void DetectRunPostRules(ThreadVars *tv, DetectEngineCtx *de_ctx, + DetectEngineThreadCtx *det_ctx, Packet *const p, Flow *const pflow, + DetectRunScratchpad *scratch) { /* see if we need to increment the inspect_id and reset the de_state */ if (pflow && pflow->alstate) { @@ -945,8 +913,7 @@ static inline void DetectRunPostRules( PACKET_PROFILING_DETECT_END(p, PROF_DETECT_ALERT); } -static void DetectRunCleanup(DetectEngineThreadCtx *det_ctx, - Packet *p, Flow * const pflow) +static void DetectRunCleanup(DetectEngineThreadCtx *det_ctx, Packet *p, Flow *const pflow) { PACKET_PROFILING_DETECT_START(p, PROF_DETECT_CLEANUP); InspectionBufferClean(det_ctx); @@ -955,8 +922,7 @@ static void DetectRunCleanup(DetectEngineThreadCtx *det_ctx, /* update inspected tracker for raw reassembly */ if (p->proto == IPPROTO_TCP && pflow->protoctx != NULL && (p->flags & PKT_DETECT_HAS_STREAMDATA)) { - StreamReassembleRawUpdateProgress(pflow->protoctx, p, - det_ctx->raw_stream_progress); + StreamReassembleRawUpdateProgress(pflow->protoctx, p, det_ctx->raw_stream_progress); } } PACKET_PROFILING_DETECT_END(p, PROF_DETECT_CLEANUP); @@ -972,8 +938,8 @@ void RuleMatchCandidateTxArrayInit(DetectEngineThreadCtx *det_ctx, uint32_t size (uint64_t)(size * sizeof(RuleMatchCandidateTx))); } det_ctx->tx_candidates_size = size; - SCLogDebug("array initialized to %u elements (%"PRIu64" bytes)", - size, (uint64_t)(size * sizeof(RuleMatchCandidateTx))); + SCLogDebug("array initialized to %u elements (%" PRIu64 " bytes)", size, + (uint64_t)(size * sizeof(RuleMatchCandidateTx))); } void RuleMatchCandidateTxArrayFree(DetectEngineThreadCtx *det_ctx) @@ -983,8 +949,8 @@ void RuleMatchCandidateTxArrayFree(DetectEngineThreadCtx *det_ctx) } /* if size >= cur_space */ -static inline bool RuleMatchCandidateTxArrayHasSpace(const DetectEngineThreadCtx *det_ctx, - const uint32_t need) +static inline bool RuleMatchCandidateTxArrayHasSpace( + const DetectEngineThreadCtx *det_ctx, const uint32_t need) { if (det_ctx->tx_candidates_size >= need) return 1; @@ -1004,9 +970,10 @@ static int RuleMatchCandidateTxArrayExpand(DetectEngineThreadCtx *det_ctx, const } det_ctx->tx_candidates = ptmp; det_ctx->tx_candidates_size = new_size; - SCLogDebug("array expanded from %u to %u elements (%"PRIu64" bytes -> %"PRIu64" bytes)", + SCLogDebug("array expanded from %u to %u elements (%" PRIu64 " bytes -> %" PRIu64 " bytes)", old_size, new_size, (uint64_t)(old_size * sizeof(RuleMatchCandidateTx)), - (uint64_t)(new_size * sizeof(RuleMatchCandidateTx))); (void)old_size; + (uint64_t)(new_size * sizeof(RuleMatchCandidateTx))); + (void)old_size; return 1; } @@ -1016,8 +983,7 @@ static int RuleMatchCandidateTxArrayExpand(DetectEngineThreadCtx *det_ctx, const * The id field is set from Signature::num, so we sort the candidates to match the signature * sort order (ascending), where candidates that have flags go first. */ -static int -DetectRunTxSortHelper(const void *a, const void *b) +static int DetectRunTxSortHelper(const void *a, const void *b) { const RuleMatchCandidateTx *s0 = a; const RuleMatchCandidateTx *s1 = b; @@ -1032,14 +998,14 @@ DetectRunTxSortHelper(const void *a, const void *b) } #if 0 -#define TRACE_SID_TXS(sid,txs,...) \ - do { \ - char _trace_buf[2048]; \ - snprintf(_trace_buf, sizeof(_trace_buf), __VA_ARGS__); \ - SCLogNotice("%p/%"PRIu64"/%u: %s", txs->tx_ptr, txs->tx_id, sid, _trace_buf); \ - } while(0) +#define TRACE_SID_TXS(sid, txs, ...) \ + do { \ + char _trace_buf[2048]; \ + snprintf(_trace_buf, sizeof(_trace_buf), __VA_ARGS__); \ + SCLogNotice("%p/%" PRIu64 "/%u: %s", txs->tx_ptr, txs->tx_id, sid, _trace_buf); \ + } while (0) #else -#define TRACE_SID_TXS(sid,txs,...) +#define TRACE_SID_TXS(sid, txs, ...) #endif /** \internal @@ -1054,18 +1020,11 @@ DetectRunTxSortHelper(const void *a, const void *b) * * \retval bool true sig matched, false didn't match */ -static bool DetectRunTxInspectRule(ThreadVars *tv, - DetectEngineCtx *de_ctx, - DetectEngineThreadCtx *det_ctx, - Packet *p, - Flow *f, - const uint8_t in_flow_flags, // direction, EOF, etc - void *alstate, - DetectTransaction *tx, - const Signature *s, - uint32_t *stored_flags, - RuleMatchCandidateTx *can, - DetectRunScratchpad *scratch) +static bool DetectRunTxInspectRule(ThreadVars *tv, DetectEngineCtx *de_ctx, + DetectEngineThreadCtx *det_ctx, Packet *p, Flow *f, + const uint8_t in_flow_flags, // direction, EOF, etc + void *alstate, DetectTransaction *tx, const Signature *s, uint32_t *stored_flags, + RuleMatchCandidateTx *can, DetectRunScratchpad *scratch) { uint8_t flow_flags = in_flow_flags; const int direction = (flow_flags & STREAM_TOSERVER) ? 0 : 1; @@ -1073,8 +1032,8 @@ static bool DetectRunTxInspectRule(ThreadVars *tv, int total_matches = 0; uint16_t file_no_match = 0; bool retval = false; - bool mpm_before_progress = false; // is mpm engine before progress? - bool mpm_in_progress = false; // is mpm engine in a buffer we will revisit? + bool mpm_before_progress = false; // is mpm engine before progress? + bool mpm_in_progress = false; // is mpm engine in a buffer we will revisit? TRACE_SID_TXS(s->id, tx, "starting %s", direction ? "toclient" : "toserver"); @@ -1099,9 +1058,7 @@ static bool DetectRunTxInspectRule(ThreadVars *tv, const DetectEngineAppInspectionEngine *engine = s->app_inspect; while (engine != NULL) { // TODO could be do {} while as s->app_inspect cannot be null TRACE_SID_TXS(s->id, tx, "engine %p inspect_flags %x", engine, inspect_flags); - if (!(inspect_flags & BIT_U32(engine->id)) && - direction == engine->dir) - { + if (!(inspect_flags & BIT_U32(engine->id)) && direction == engine->dir) { const bool skip_engine = (engine->alproto != 0 && engine->alproto != f->alproto); /* special case: file_data on 'alert tcp' will have engines * in the list that are not for us. */ @@ -1113,8 +1070,8 @@ static bool DetectRunTxInspectRule(ThreadVars *tv, /* engines are sorted per progress, except that the one with * mpm/prefilter enabled is first */ if (tx->tx_progress < engine->progress) { - SCLogDebug("tx progress %d < engine progress %d", - tx->tx_progress, engine->progress); + SCLogDebug( + "tx progress %d < engine progress %d", tx->tx_progress, engine->progress); break; } if (engine->mpm) { @@ -1147,7 +1104,8 @@ static bool DetectRunTxInspectRule(ThreadVars *tv, if (engine->stream) { can->stream_stored = true; can->stream_result = match; - TRACE_SID_TXS(s->id, tx, "stream ran, store result %d for next tx (if any)", match); + TRACE_SID_TXS( + s->id, tx, "stream ran, store result %d for next tx (if any)", match); } } if (match == DETECT_ENGINE_INSPECT_SIG_MATCH) { @@ -1179,8 +1137,8 @@ static bool DetectRunTxInspectRule(ThreadVars *tv, } engine = engine->next; } - TRACE_SID_TXS(s->id, tx, "inspect_flags %x, total_matches %u, engine %p", - inspect_flags, total_matches, engine); + TRACE_SID_TXS(s->id, tx, "inspect_flags %x, total_matches %u, engine %p", inspect_flags, + total_matches, engine); if (engine == NULL && total_matches) { inspect_flags |= DE_STATE_FLAG_FULL_INSPECT; @@ -1207,26 +1165,29 @@ static bool DetectRunTxInspectRule(ThreadVars *tv, * other matches? E.g. 'POST + filename', is different than * just 'filename'. */ - DetectRunStoreStateTx(scratch->sgh, f, tx->tx_ptr, tx->tx_id, s, - inspect_flags, flow_flags, file_no_match); + DetectRunStoreStateTx(scratch->sgh, f, tx->tx_ptr, tx->tx_id, s, inspect_flags, + flow_flags, file_no_match); } } else if ((inspect_flags & DE_STATE_FLAG_FULL_INSPECT) && mpm_before_progress) { - TRACE_SID_TXS(s->id, tx, "no need to store match sig, " + TRACE_SID_TXS(s->id, tx, + "no need to store match sig, " "mpm won't trigger for it anymore"); if (inspect_flags & DE_STATE_FLAG_FILE_INSPECT) { - TRACE_SID_TXS(s->id, tx, "except that for new files, " + TRACE_SID_TXS(s->id, tx, + "except that for new files, " "we may have to revisit anyway"); - DetectRunStoreStateTx(scratch->sgh, f, tx->tx_ptr, tx->tx_id, s, - inspect_flags, flow_flags, file_no_match); + DetectRunStoreStateTx(scratch->sgh, f, tx->tx_ptr, tx->tx_id, s, inspect_flags, + flow_flags, file_no_match); } } else if ((inspect_flags & DE_STATE_FLAG_FULL_INSPECT) == 0 && mpm_in_progress) { - TRACE_SID_TXS(s->id, tx, "no need to store no-match sig, " + TRACE_SID_TXS(s->id, tx, + "no need to store no-match sig, " "mpm will revisit it"); } else { TRACE_SID_TXS(s->id, tx, "storing state: flags %08x", inspect_flags); - DetectRunStoreStateTx(scratch->sgh, f, tx->tx_ptr, tx->tx_id, s, - inspect_flags, flow_flags, file_no_match); + DetectRunStoreStateTx(scratch->sgh, f, tx->tx_ptr, tx->tx_id, s, inspect_flags, + flow_flags, file_no_match); } } @@ -1242,9 +1203,8 @@ static bool DetectRunTxInspectRule(ThreadVars *tv, * \brief get a DetectTransaction object * \retval struct filled with relevant info or all nulls/0s */ -static DetectTransaction GetDetectTx(const uint8_t ipproto, const AppProto alproto, - void *alstate, const uint64_t tx_id, void *tx_ptr, const int tx_end_state, - const uint8_t flow_flags) +static DetectTransaction GetDetectTx(const uint8_t ipproto, const AppProto alproto, void *alstate, + const uint64_t tx_id, void *tx_ptr, const int tx_end_state, const uint8_t flow_flags) { AppLayerTxData *txd = AppLayerParserGetTxData(ipproto, alproto, tx_ptr); if (unlikely(txd == NULL)) { @@ -1254,9 +1214,8 @@ static DetectTransaction GetDetectTx(const uint8_t ipproto, const AppProto alpro uint64_t detect_flags = (flow_flags & STREAM_TOSERVER) ? txd->detect_flags_ts : txd->detect_flags_tc; if (detect_flags & APP_LAYER_TX_INSPECTED_FLAG) { - SCLogDebug("%"PRIu64" tx already fully inspected for %s. Flags %016"PRIx64, - tx_id, flow_flags & STREAM_TOSERVER ? "toserver" : "toclient", - detect_flags); + SCLogDebug("%" PRIu64 " tx already fully inspected for %s. Flags %016" PRIx64, tx_id, + flow_flags & STREAM_TOSERVER ? "toserver" : "toclient", detect_flags); DetectTransaction no_tx = NO_TX; return no_tx; } @@ -1270,21 +1229,22 @@ static DetectTransaction GetDetectTx(const uint8_t ipproto, const AppProto alpro const int tx_progress = AppLayerParserGetStateProgress(ipproto, alproto, tx_ptr, flow_flags); const int dir_int = (flow_flags & STREAM_TOSERVER) ? 0 : 1; DetectEngineState *tx_de_state = txd->de_state; - DetectEngineStateDirection *tx_dir_state = tx_de_state ? &tx_de_state->dir_state[dir_int] : NULL; + DetectEngineStateDirection *tx_dir_state = + tx_de_state ? &tx_de_state->dir_state[dir_int] : NULL; uint64_t prefilter_flags = detect_flags & APP_LAYER_TX_PREFILTER_MASK; DEBUG_VALIDATE_BUG_ON(prefilter_flags & APP_LAYER_TX_RESERVED_FLAGS); DetectTransaction tx = { - .tx_ptr = tx_ptr, - .tx_id = tx_id, - .tx_data_ptr = (struct AppLayerTxData *)txd, - .de_state = tx_dir_state, - .detect_flags = detect_flags, - .prefilter_flags = prefilter_flags, - .prefilter_flags_orig = prefilter_flags, - .tx_progress = tx_progress, - .tx_end_state = tx_end_state, - }; + .tx_ptr = tx_ptr, + .tx_id = tx_id, + .tx_data_ptr = (struct AppLayerTxData *)txd, + .de_state = tx_dir_state, + .detect_flags = detect_flags, + .prefilter_flags = prefilter_flags, + .prefilter_flags_orig = prefilter_flags, + .tx_progress = tx_progress, + .tx_end_state = tx_end_state, + }; return tx; } @@ -1301,16 +1261,12 @@ static inline void StoreDetectFlags(DetectTransaction *tx, const uint8_t flow_fl } } -static void DetectRunTx(ThreadVars *tv, - DetectEngineCtx *de_ctx, - DetectEngineThreadCtx *det_ctx, - Packet *p, - Flow *f, - DetectRunScratchpad *scratch) +static void DetectRunTx(ThreadVars *tv, DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx, + Packet *p, Flow *f, DetectRunScratchpad *scratch) { const uint8_t flow_flags = scratch->flow_flags; - const SigGroupHead * const sgh = scratch->sgh; - void * const alstate = f->alstate; + const SigGroupHead *const sgh = scratch->sgh; + void *const alstate = f->alstate; const uint8_t ipproto = f->proto; const AppProto alproto = f->alproto; @@ -1323,15 +1279,15 @@ static void DetectRunTx(ThreadVars *tv, memset(&state, 0, sizeof(state)); while (1) { - AppLayerGetTxIterTuple ires = IterFunc(ipproto, alproto, alstate, tx_id_min, total_txs, &state); + AppLayerGetTxIterTuple ires = + IterFunc(ipproto, alproto, alstate, tx_id_min, total_txs, &state); if (ires.tx_ptr == NULL) break; - DetectTransaction tx = GetDetectTx(ipproto, alproto, - alstate, ires.tx_id, ires.tx_ptr, tx_end_state, flow_flags); + DetectTransaction tx = GetDetectTx( + ipproto, alproto, alstate, ires.tx_id, ires.tx_ptr, tx_end_state, flow_flags); if (tx.tx_ptr == NULL) { - SCLogDebug("%p/%"PRIu64" no transaction to inspect", - tx.tx_ptr, tx_id_min); + SCLogDebug("%p/%" PRIu64 " no transaction to inspect", tx.tx_ptr, tx_id_min); tx_id_min++; // next (if any) run look for +1 goto next; @@ -1346,11 +1302,10 @@ static void DetectRunTx(ThreadVars *tv, /* run prefilter engines and merge results into a candidates array */ if (sgh->tx_engines) { PACKET_PROFILING_DETECT_START(p, PROF_DETECT_PF_TX); - DetectRunPrefilterTx(det_ctx, sgh, p, ipproto, flow_flags, alproto, - alstate, &tx); + DetectRunPrefilterTx(det_ctx, sgh, p, ipproto, flow_flags, alproto, alstate, &tx); PACKET_PROFILING_DETECT_END(p, PROF_DETECT_PF_TX); - SCLogDebug("%p/%"PRIu64" rules added from prefilter: %u candidates", - tx.tx_ptr, tx.tx_id, det_ctx->pmq.rule_id_array_cnt); + SCLogDebug("%p/%" PRIu64 " rules added from prefilter: %u candidates", tx.tx_ptr, + tx.tx_id, det_ctx->pmq.rule_id_array_cnt); total_rules += det_ctx->pmq.rule_id_array_cnt; if (!(RuleMatchCandidateTxArrayHasSpace(det_ctx, total_rules))) { @@ -1385,8 +1340,8 @@ static void DetectRunTx(ThreadVars *tv, det_ctx->tx_candidates[array_idx].stream_reset = 0; array_idx++; - SCLogDebug("%p/%"PRIu64" rule %u (%u) added from 'match' list", - tx.tx_ptr, tx.tx_id, s->id, id); + SCLogDebug("%p/%" PRIu64 " rule %u (%u) added from 'match' list", tx.tx_ptr, + tx.tx_id, s->id, id); } } do_sort = (array_idx > x); // sort if match added anything @@ -1401,8 +1356,8 @@ static void DetectRunTx(ThreadVars *tv, * 'file inspected' flag, reset the file part of the state */ const bool have_new_file = (tx.de_state->flags & DETECT_ENGINE_STATE_FLAG_FILE_NEW); if (have_new_file) { - SCLogDebug("%p/%"PRIu64" destate: need to consider new file", - tx.tx_ptr, tx.tx_id); + SCLogDebug( + "%p/%" PRIu64 " destate: need to consider new file", tx.tx_ptr, tx.tx_id); tx.de_state->flags &= ~DETECT_ENGINE_STATE_FLAG_FILE_NEW; } @@ -1412,17 +1367,17 @@ static void DetectRunTx(ThreadVars *tv, SCLogDebug("tx_store %p", tx_store); SigIntId store_cnt = 0; - for (store_cnt = 0; - store_cnt < DE_STATE_CHUNK_SIZE && state_cnt < tx.de_state->cnt; - store_cnt++, state_cnt++) - { + for (store_cnt = 0; store_cnt < DE_STATE_CHUNK_SIZE && state_cnt < tx.de_state->cnt; + store_cnt++, state_cnt++) { DeStateStoreItem *item = &tx_store->store[store_cnt]; SCLogDebug("rule id %u, inspect_flags %u", item->sid, item->flags); if (have_new_file && (item->flags & DE_STATE_FLAG_FILE_INSPECT)) { /* remove part of the state. File inspect engine will now * be able to run again */ - item->flags &= ~(DE_STATE_FLAG_SIG_CANT_MATCH|DE_STATE_FLAG_FULL_INSPECT|DE_STATE_FLAG_FILE_INSPECT); - SCLogDebug("rule id %u, post file reset inspect_flags %u", item->sid, item->flags); + item->flags &= ~(DE_STATE_FLAG_SIG_CANT_MATCH | DE_STATE_FLAG_FULL_INSPECT | + DE_STATE_FLAG_FILE_INSPECT); + SCLogDebug("rule id %u, post file reset inspect_flags %u", item->sid, + item->flags); } det_ctx->tx_candidates[array_idx].s = de_ctx->sig_array[item->sid]; det_ctx->tx_candidates[array_idx].id = item->sid; @@ -1473,12 +1428,13 @@ static void DetectRunTx(ThreadVars *tv, i++; } - SCLogDebug("%p/%"PRIu64" inspecting: sid %u (%u), flags %08x", - tx.tx_ptr, tx.tx_id, s->id, s->num, inspect_flags ? *inspect_flags : 0); + SCLogDebug("%p/%" PRIu64 " inspecting: sid %u (%u), flags %08x", tx.tx_ptr, tx.tx_id, + s->id, s->num, inspect_flags ? *inspect_flags : 0); if (inspect_flags) { - if (*inspect_flags & (DE_STATE_FLAG_FULL_INSPECT|DE_STATE_FLAG_SIG_CANT_MATCH)) { - SCLogDebug("%p/%"PRIu64" inspecting: sid %u (%u), flags %08x ALREADY COMPLETE", + if (*inspect_flags & (DE_STATE_FLAG_FULL_INSPECT | DE_STATE_FLAG_SIG_CANT_MATCH)) { + SCLogDebug("%p/%" PRIu64 + " inspecting: sid %u (%u), flags %08x ALREADY COMPLETE", tx.tx_ptr, tx.tx_id, s->id, s->num, *inspect_flags); continue; } @@ -1489,19 +1445,20 @@ static void DetectRunTx(ThreadVars *tv, SCLogDebug("%p/%" PRIu64 " Continuing sid %u", tx.tx_ptr, tx.tx_id, s->id); } else { /* start new inspection */ - SCLogDebug("%p/%"PRIu64" Start sid %u", tx.tx_ptr, tx.tx_id, s->id); + SCLogDebug("%p/%" PRIu64 " Start sid %u", tx.tx_ptr, tx.tx_id, s->id); } /* call individual rule inspection */ RULE_PROFILING_START(p); - const int r = DetectRunTxInspectRule(tv, de_ctx, det_ctx, p, f, flow_flags, - alstate, &tx, s, inspect_flags, can, scratch); + const int r = DetectRunTxInspectRule(tv, de_ctx, det_ctx, p, f, flow_flags, alstate, + &tx, s, inspect_flags, can, scratch); if (r == 1) { /* match */ DetectRunPostMatch(tv, det_ctx, p, s); const uint8_t alert_flags = (PACKET_ALERT_FLAG_STATE_MATCH | PACKET_ALERT_FLAG_TX); - SCLogDebug("%p/%"PRIu64" sig %u (%u) matched", tx.tx_ptr, tx.tx_id, s->id, s->num); + SCLogDebug( + "%p/%" PRIu64 " sig %u (%u) matched", tx.tx_ptr, tx.tx_id, s->id, s->num); AlertQueueAppend(det_ctx, s, p, tx.tx_id, alert_flags); } DetectVarProcessList(det_ctx, p->flow, p); @@ -1518,31 +1475,27 @@ static void DetectRunTx(ThreadVars *tv, /* this side of the tx is done */ if (tx.tx_progress >= tx.tx_end_state) { new_detect_flags |= APP_LAYER_TX_INSPECTED_FLAG; - SCLogDebug("%p/%"PRIu64" tx is done for direction %s. Flag %016"PRIx64, - tx.tx_ptr, tx.tx_id, - flow_flags & STREAM_TOSERVER ? "toserver" : "toclient", + SCLogDebug("%p/%" PRIu64 " tx is done for direction %s. Flag %016" PRIx64, tx.tx_ptr, + tx.tx_id, flow_flags & STREAM_TOSERVER ? "toserver" : "toclient", new_detect_flags); } if (tx.prefilter_flags != tx.prefilter_flags_orig) { new_detect_flags |= tx.prefilter_flags; DEBUG_VALIDATE_BUG_ON(new_detect_flags & APP_LAYER_TX_RESERVED_FLAGS); - SCLogDebug("%p/%"PRIu64" updated prefilter flags %016"PRIx64" " - "(was: %016"PRIx64") for direction %s. Flag %016"PRIx64, + SCLogDebug("%p/%" PRIu64 " updated prefilter flags %016" PRIx64 " " + "(was: %016" PRIx64 ") for direction %s. Flag %016" PRIx64, tx.tx_ptr, tx.tx_id, tx.prefilter_flags, tx.prefilter_flags_orig, - flow_flags & STREAM_TOSERVER ? "toserver" : "toclient", - new_detect_flags); + flow_flags & STREAM_TOSERVER ? "toserver" : "toclient", new_detect_flags); } - if (new_detect_flags != 0 && - (new_detect_flags | tx.detect_flags) != tx.detect_flags) - { + if (new_detect_flags != 0 && (new_detect_flags | tx.detect_flags) != tx.detect_flags) { new_detect_flags |= tx.detect_flags; DEBUG_VALIDATE_BUG_ON(new_detect_flags & APP_LAYER_TX_RESERVED_FLAGS); - SCLogDebug("%p/%"PRIu64" Storing new flags %016"PRIx64" (was %016"PRIx64")", + SCLogDebug("%p/%" PRIu64 " Storing new flags %016" PRIx64 " (was %016" PRIx64 ")", tx.tx_ptr, tx.tx_id, new_detect_flags, tx.detect_flags); StoreDetectFlags(&tx, flow_flags, ipproto, alproto, new_detect_flags); } -next: + next: InspectionBufferClean(det_ctx); if (!ires.has_next) @@ -1686,9 +1639,8 @@ static DetectEngineThreadCtx *GetTenantById(HashTable *h, uint32_t id) return HashTableLookup(h, &id, 0); } -static void DetectFlow(ThreadVars *tv, - DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx, - Packet *p) +static void DetectFlow( + ThreadVars *tv, DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx, Packet *p) { Flow *const f = p->flow; @@ -1704,8 +1656,9 @@ static void DetectFlow(ThreadVars *tv, AppLayerParserSetTransactionInspectId(f, f->alparser, f->alstate, flags, true); } } - SCLogDebug("p->pcap %"PRIu64": no detection on packet, " - "PKT_NOPACKET_INSPECTION is set", p->pcap_cnt); + SCLogDebug("p->pcap %" PRIu64 ": no detection on packet, " + "PKT_NOPACKET_INSPECTION is set", + p->pcap_cnt); return; } @@ -1721,10 +1674,8 @@ static void DetectFlow(ThreadVars *tv, (void)DetectRun(tv, de_ctx, det_ctx, p); } - -static void DetectNoFlow(ThreadVars *tv, - DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx, - Packet *p) +static void DetectNoFlow( + ThreadVars *tv, DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx, Packet *p) { /* No need to perform any detection on this packet, if the given flag is set.*/ if ((p->flags & PKT_NOPACKET_INSPECTION) || (PacketCheckAction(p, ACTION_DROP))) { @@ -1757,14 +1708,12 @@ TmEcode Detect(ThreadVars *tv, Packet *p, void *data) if (unlikely(SC_ATOMIC_GET(det_ctx->so_far_used_by_detect) == 0)) { (void)SC_ATOMIC_SET(det_ctx->so_far_used_by_detect, 1); - SCLogDebug("Detect Engine using new det_ctx - %p", - det_ctx); + SCLogDebug("Detect Engine using new det_ctx - %p", det_ctx); } /* if in MT mode _and_ we have tenants registered, use * MT logic. */ - if (det_ctx->mt_det_ctxs_cnt > 0 && det_ctx->TenantGetId != NULL) - { + if (det_ctx->mt_det_ctxs_cnt > 0 && det_ctx->TenantGetId != NULL) { uint32_t tenant_id = p->tenant_id; if (tenant_id == 0) tenant_id = det_ctx->TenantGetId(det_ctx, p); @@ -1839,4 +1788,3 @@ void SigMatchSignatures( #ifdef UNITTESTS #include "tests/detect.c" #endif - diff --git a/src/detect.h b/src/detect.h index 53ca2b0931f6..033d78683e99 100644 --- a/src/detect.h +++ b/src/detect.h @@ -150,7 +150,7 @@ enum { ADDRESS_GT, /**< bigger [bbb] [aaa] */ }; -#define ADDRESS_FLAG_NOT 0x01 /**< address is negated */ +#define ADDRESS_FLAG_NOT 0x01 /**< address is negated */ /** \brief address structure for use in the detection engine. * @@ -176,10 +176,9 @@ typedef struct DetectAddressHead_ { DetectAddress *ipv6_head; } DetectAddressHead; - typedef struct DetectMatchAddressIPv4_ { - uint32_t ip; /**< address in host order, start of range */ - uint32_t ip2; /**< address in host order, end of range */ + uint32_t ip; /**< address in host order, start of range */ + uint32_t ip2; /**< address in host order, end of range */ } DetectMatchAddressIPv4; typedef struct DetectMatchAddressIPv6_ { @@ -203,16 +202,16 @@ enum { PORT_GT, /* bigger [bbb] [aaa] */ }; -#define PORT_FLAG_ANY 0x01 /**< 'any' special port */ -#define PORT_FLAG_NOT 0x02 /**< negated port */ -#define PORT_SIGGROUPHEAD_COPY 0x04 /**< sgh is a ptr copy */ +#define PORT_FLAG_ANY 0x01 /**< 'any' special port */ +#define PORT_FLAG_NOT 0x02 /**< negated port */ +#define PORT_SIGGROUPHEAD_COPY 0x04 /**< sgh is a ptr copy */ /** \brief Port structure for detection engine */ typedef struct DetectPort_ { uint16_t port; uint16_t port2; - uint8_t flags; /**< flags for this port */ + uint8_t flags; /**< flags for this port */ /* signatures that belong in this group * @@ -228,23 +227,23 @@ typedef struct DetectPort_ { /* Signature flags */ /** \note: additions should be added to the rule analyzer as well */ -#define SIG_FLAG_SRC_ANY BIT_U32(0) /**< source is any */ -#define SIG_FLAG_DST_ANY BIT_U32(1) /**< destination is any */ -#define SIG_FLAG_SP_ANY BIT_U32(2) /**< source port is any */ -#define SIG_FLAG_DP_ANY BIT_U32(3) /**< destination port is any */ +#define SIG_FLAG_SRC_ANY BIT_U32(0) /**< source is any */ +#define SIG_FLAG_DST_ANY BIT_U32(1) /**< destination is any */ +#define SIG_FLAG_SP_ANY BIT_U32(2) /**< source port is any */ +#define SIG_FLAG_DP_ANY BIT_U32(3) /**< destination port is any */ -#define SIG_FLAG_NOALERT BIT_U32(4) /**< no alert flag is set */ -#define SIG_FLAG_DSIZE BIT_U32(5) /**< signature has a dsize setting */ -#define SIG_FLAG_APPLAYER BIT_U32(6) /**< signature applies to app layer instead of packets */ +#define SIG_FLAG_NOALERT BIT_U32(4) /**< no alert flag is set */ +#define SIG_FLAG_DSIZE BIT_U32(5) /**< signature has a dsize setting */ +#define SIG_FLAG_APPLAYER BIT_U32(6) /**< signature applies to app layer instead of packets */ // vacancy -#define SIG_FLAG_REQUIRE_PACKET BIT_U32(9) /**< signature is requiring packet match */ -#define SIG_FLAG_REQUIRE_STREAM BIT_U32(10) /**< signature is requiring stream match */ +#define SIG_FLAG_REQUIRE_PACKET BIT_U32(9) /**< signature is requiring packet match */ +#define SIG_FLAG_REQUIRE_STREAM BIT_U32(10) /**< signature is requiring stream match */ -#define SIG_FLAG_MPM_NEG BIT_U32(11) +#define SIG_FLAG_MPM_NEG BIT_U32(11) -#define SIG_FLAG_FLUSH BIT_U32(12) /**< detection logic needs stream flush notification */ +#define SIG_FLAG_FLUSH BIT_U32(12) /**< detection logic needs stream flush notification */ #define SIG_FLAG_REQUIRE_STREAM_ONLY \ BIT_U32(13) /**< signature is requiring stream match. Stream match is not optional, so no \ @@ -252,52 +251,55 @@ typedef struct DetectPort_ { // vacancies -#define SIG_FLAG_REQUIRE_FLOWVAR BIT_U32(17) /**< signature can only match if a flowbit, flowvar or flowint is available. */ +#define SIG_FLAG_REQUIRE_FLOWVAR \ + BIT_U32(17) /**< signature can only match if a flowbit, flowvar or flowint is available. */ -#define SIG_FLAG_FILESTORE BIT_U32(18) /**< signature has filestore keyword */ +#define SIG_FLAG_FILESTORE BIT_U32(18) /**< signature has filestore keyword */ -#define SIG_FLAG_TOSERVER BIT_U32(19) -#define SIG_FLAG_TOCLIENT BIT_U32(20) +#define SIG_FLAG_TOSERVER BIT_U32(19) +#define SIG_FLAG_TOCLIENT BIT_U32(20) -#define SIG_FLAG_TLSSTORE BIT_U32(21) +#define SIG_FLAG_TLSSTORE BIT_U32(21) -#define SIG_FLAG_BYPASS BIT_U32(22) +#define SIG_FLAG_BYPASS BIT_U32(22) -#define SIG_FLAG_PREFILTER BIT_U32(23) /**< sig is part of a prefilter engine */ +#define SIG_FLAG_PREFILTER BIT_U32(23) /**< sig is part of a prefilter engine */ // vacancy /** Info for Source and Target identification */ -#define SIG_FLAG_SRC_IS_TARGET BIT_U32(25) +#define SIG_FLAG_SRC_IS_TARGET BIT_U32(25) /** Info for Source and Target identification */ -#define SIG_FLAG_DEST_IS_TARGET BIT_U32(26) +#define SIG_FLAG_DEST_IS_TARGET BIT_U32(26) -#define SIG_FLAG_HAS_TARGET (SIG_FLAG_DEST_IS_TARGET|SIG_FLAG_SRC_IS_TARGET) +#define SIG_FLAG_HAS_TARGET (SIG_FLAG_DEST_IS_TARGET | SIG_FLAG_SRC_IS_TARGET) /* signature init flags */ // available 0 -#define SIG_FLAG_INIT_PACKET BIT_U32(1) /**< signature has matches against a packet (as opposed to app layer) */ -#define SIG_FLAG_INIT_FLOW BIT_U32(2) /**< signature has a flow setting */ -#define SIG_FLAG_INIT_BIDIREC BIT_U32(3) /**< signature has bidirectional operator */ +#define SIG_FLAG_INIT_PACKET \ + BIT_U32(1) /**< signature has matches against a packet (as opposed to app layer) */ +#define SIG_FLAG_INIT_FLOW BIT_U32(2) /**< signature has a flow setting */ +#define SIG_FLAG_INIT_BIDIREC BIT_U32(3) /**< signature has bidirectional operator */ #define SIG_FLAG_INIT_FIRST_IPPROTO_SEEN \ BIT_U32(4) /** < signature has seen the first ip_proto keyword */ -#define SIG_FLAG_INIT_STATE_MATCH BIT_U32(6) /**< signature has matches that require stateful inspection */ -#define SIG_FLAG_INIT_NEED_FLUSH BIT_U32(7) +#define SIG_FLAG_INIT_STATE_MATCH \ + BIT_U32(6) /**< signature has matches that require stateful inspection */ +#define SIG_FLAG_INIT_NEED_FLUSH BIT_U32(7) #define SIG_FLAG_INIT_PRIO_EXPLICIT \ - BIT_U32(8) /**< priority is explicitly set by the priority keyword */ -#define SIG_FLAG_INIT_FILEDATA BIT_U32(9) /**< signature has filedata keyword */ -#define SIG_FLAG_INIT_JA3 BIT_U32(10) /**< signature has ja3 keyword */ + BIT_U32(8) /**< priority is explicitly set by the priority keyword */ +#define SIG_FLAG_INIT_FILEDATA BIT_U32(9) /**< signature has filedata keyword */ +#define SIG_FLAG_INIT_JA3 BIT_U32(10) /**< signature has ja3 keyword */ /* signature mask flags */ /** \note: additions should be added to the rule analyzer as well */ -#define SIG_MASK_REQUIRE_PAYLOAD BIT_U8(0) -#define SIG_MASK_REQUIRE_FLOW BIT_U8(1) -#define SIG_MASK_REQUIRE_FLAGS_INITDEINIT BIT_U8(2) /* SYN, FIN, RST */ -#define SIG_MASK_REQUIRE_FLAGS_UNUSUAL BIT_U8(3) /* URG, ECN, CWR */ -#define SIG_MASK_REQUIRE_NO_PAYLOAD BIT_U8(4) -#define SIG_MASK_REQUIRE_DCERPC BIT_U8(5) /* require either SMB+DCE or raw DCE */ +#define SIG_MASK_REQUIRE_PAYLOAD BIT_U8(0) +#define SIG_MASK_REQUIRE_FLOW BIT_U8(1) +#define SIG_MASK_REQUIRE_FLAGS_INITDEINIT BIT_U8(2) /* SYN, FIN, RST */ +#define SIG_MASK_REQUIRE_FLAGS_UNUSUAL BIT_U8(3) /* URG, ECN, CWR */ +#define SIG_MASK_REQUIRE_NO_PAYLOAD BIT_U8(4) +#define SIG_MASK_REQUIRE_DCERPC BIT_U8(5) /* require either SMB+DCE or raw DCE */ // vacancy -#define SIG_MASK_REQUIRE_ENGINE_EVENT BIT_U8(7) +#define SIG_MASK_REQUIRE_ENGINE_EVENT BIT_U8(7) /* for now a uint8_t is enough */ #define SignatureMask uint8_t @@ -305,17 +307,17 @@ typedef struct DetectPort_ { #define DETECT_ENGINE_THREAD_CTX_FRAME_ID_SET 0x0001 #define DETECT_ENGINE_THREAD_CTX_STREAM_CONTENT_MATCH 0x0004 -#define FILE_SIG_NEED_FILE 0x01 -#define FILE_SIG_NEED_FILENAME 0x02 -#define FILE_SIG_NEED_MAGIC 0x04 /**< need the start of the file */ -#define FILE_SIG_NEED_FILECONTENT 0x08 -#define FILE_SIG_NEED_MD5 0x10 -#define FILE_SIG_NEED_SHA1 0x20 -#define FILE_SIG_NEED_SHA256 0x40 -#define FILE_SIG_NEED_SIZE 0x80 +#define FILE_SIG_NEED_FILE 0x01 +#define FILE_SIG_NEED_FILENAME 0x02 +#define FILE_SIG_NEED_MAGIC 0x04 /**< need the start of the file */ +#define FILE_SIG_NEED_FILECONTENT 0x08 +#define FILE_SIG_NEED_MD5 0x10 +#define FILE_SIG_NEED_SHA1 0x20 +#define FILE_SIG_NEED_SHA256 0x40 +#define FILE_SIG_NEED_SIZE 0x80 /* Detection Engine flags */ -#define DE_QUIET 0x01 /**< DE is quiet (esp for unittests) */ +#define DE_QUIET 0x01 /**< DE is quiet (esp for unittests) */ typedef struct IPOnlyCIDRItem_ { /* address data for this item */ @@ -342,8 +344,8 @@ typedef struct SigMatchCtx_ { /** \brief a single match condition for a signature */ typedef struct SigMatch_ { - uint16_t type; /**< match type */ - uint16_t idx; /**< position in the signature */ + uint16_t type; /**< match type */ + uint16_t idx; /**< position in the signature */ SigMatchCtx *ctx; /**< plugin specific data */ struct SigMatch_ *next; struct SigMatch_ *prev; @@ -351,12 +353,12 @@ typedef struct SigMatch_ { /** \brief Data needed for Match() */ typedef struct SigMatchData_ { - uint16_t type; /**< match type */ - uint8_t is_last; /**< Last element of the list */ + uint16_t type; /**< match type */ + uint8_t is_last; /**< Last element of the list */ SigMatchCtx *ctx; /**< plugin specific data */ } SigMatchData; -struct DetectEngineThreadCtx_;// DetectEngineThreadCtx; +struct DetectEngineThreadCtx_; // DetectEngineThreadCtx; /* inspection buffer is a simple structure that is passed between prefilter, * transformation functions and inspection functions. @@ -368,15 +370,15 @@ struct DetectEngineThreadCtx_;// DetectEngineThreadCtx; typedef struct InspectionBuffer { const uint8_t *inspect; /**< active pointer, points either to ::buf or ::orig */ uint64_t inspect_offset; - uint32_t inspect_len; /**< size of active data. See to ::len or ::orig_len */ + uint32_t inspect_len; /**< size of active data. See to ::len or ::orig_len */ bool initialized; /**< is initialized. ::inspect might be NULL if transform lead to 0 size */ - uint8_t flags; /**< DETECT_CI_FLAGS_* for use with DetectEngineContentInspection */ + uint8_t flags; /**< DETECT_CI_FLAGS_* for use with DetectEngineContentInspection */ #ifdef DEBUG_VALIDATION bool multi; #endif - uint32_t len; /**< how much is in use */ + uint32_t len; /**< how much is in use */ uint8_t *buf; - uint32_t size; /**< size of the memory allocation */ + uint32_t size; /**< size of the memory allocation */ uint32_t orig_len; const uint8_t *orig; @@ -390,9 +392,9 @@ typedef struct InspectionBuffer { typedef struct InspectionBufferMultipleForList { InspectionBuffer *inspection_buffers; - uint32_t size; /**< size in number of elements */ - uint32_t max:31; /**< max id in use in this run */ - uint32_t init:1; /**< first time used this run. Used for clean logic */ + uint32_t size; /**< size in number of elements */ + uint32_t max : 31; /**< max id in use in this run */ + uint32_t init : 1; /**< first time used this run. Used for clean logic */ } InspectionBufferMultipleForList; typedef struct TransformData_ { @@ -406,11 +408,9 @@ typedef struct DetectEngineTransforms { } DetectEngineTransforms; /** callback for getting the buffer we need to prefilter/inspect */ -typedef InspectionBuffer *(*InspectionBufferGetDataPtr)( - struct DetectEngineThreadCtx_ *det_ctx, - const DetectEngineTransforms *transforms, - Flow *f, const uint8_t flow_flags, - void *txv, const int list_id); +typedef InspectionBuffer *(*InspectionBufferGetDataPtr)(struct DetectEngineThreadCtx_ *det_ctx, + const DetectEngineTransforms *transforms, Flow *f, const uint8_t flow_flags, void *txv, + const int list_id); struct DetectEngineAppInspectionEngine_; typedef uint8_t (*InspectEngineFuncPtr2)(struct DetectEngineCtx_ *de_ctx, @@ -421,7 +421,7 @@ typedef uint8_t (*InspectEngineFuncPtr2)(struct DetectEngineCtx_ *de_ctx, typedef struct DetectEngineAppInspectionEngine_ { AppProto alproto; uint8_t dir; - uint8_t id; /**< per sig id used in state keeping */ + uint8_t id; /**< per sig id used in state keeping */ bool mpm; bool stream; uint16_t sm_list; @@ -460,17 +460,13 @@ struct DetectEnginePktInspectionEngine; /** * \param alert_flags[out] for setting PACKET_ALERT_FLAG_* */ -typedef int (*InspectionBufferPktInspectFunc)( - struct DetectEngineThreadCtx_ *, - const struct DetectEnginePktInspectionEngine *engine, - const struct Signature_ *s, - Packet *p, uint8_t *alert_flags); +typedef int (*InspectionBufferPktInspectFunc)(struct DetectEngineThreadCtx_ *, + const struct DetectEnginePktInspectionEngine *engine, const struct Signature_ *s, Packet *p, + uint8_t *alert_flags); /** callback for getting the buffer we need to prefilter/inspect */ -typedef InspectionBuffer *(*InspectionBufferGetPktDataPtr)( - struct DetectEngineThreadCtx_ *det_ctx, - const DetectEngineTransforms *transforms, - Packet *p, const int list_id); +typedef InspectionBuffer *(*InspectionBufferGetPktDataPtr)(struct DetectEngineThreadCtx_ *det_ctx, + const DetectEngineTransforms *transforms, Packet *p, const int list_id); typedef struct DetectEnginePktInspectionEngine { SigMatchData *smd; @@ -673,12 +669,12 @@ enum DetectBufferMpmType { /** \brief one time registration of keywords at start up */ typedef struct DetectBufferMpmRegistry_ { const char *name; - char pname[32]; /**< name used in profiling */ - int direction; /**< SIG_FLAG_TOSERVER or SIG_FLAG_TOCLIENT */ + char pname[32]; /**< name used in profiling */ + int direction; /**< SIG_FLAG_TOSERVER or SIG_FLAG_TOCLIENT */ int16_t sm_list; int16_t sm_list_base; int priority; - int id; /**< index into this array and result arrays */ + int id; /**< index into this array and result arrays */ enum DetectBufferMpmType type; int sgh_mpm_context; @@ -727,19 +723,19 @@ typedef struct DetectReplaceList_ { } DetectReplaceList; /** only execute flowvar storage if rule matched */ -#define DETECT_VAR_TYPE_FLOW_POSTMATCH 1 -#define DETECT_VAR_TYPE_PKT_POSTMATCH 2 +#define DETECT_VAR_TYPE_FLOW_POSTMATCH 1 +#define DETECT_VAR_TYPE_PKT_POSTMATCH 2 /** list for flowvar store candidates, to be stored from * post-match function */ typedef struct DetectVarList_ { - uint32_t idx; /**< flowvar name idx */ - uint16_t len; /**< data len */ + uint32_t idx; /**< flowvar name idx */ + uint16_t len; /**< data len */ uint16_t key_len; - int type; /**< type of store candidate POSTMATCH or ALWAYS */ + int type; /**< type of store candidate POSTMATCH or ALWAYS */ uint8_t *key; - uint8_t *buffer; /**< alloc'd buffer, may be freed by - post-match, post-non-match */ + uint8_t *buffer; /**< alloc'd buffer, may be freed by + post-match, post-non-match */ struct DetectVarList_ *next; } DetectVarList; @@ -774,8 +770,8 @@ typedef struct DetectEngineLookupFlow_ { #include "detect-threshold.h" /** \brief threshold ctx */ -typedef struct ThresholdCtx_ { - SCMutex threshold_table_lock; /**< Mutex for hash table */ +typedef struct ThresholdCtx_ { + SCMutex threshold_table_lock; /**< Mutex for hash table */ /** to support rate_filter "by_rule" option */ DetectThresholdEntry **th_entry; @@ -808,14 +804,12 @@ typedef struct DetectEngineThreadKeywordCtxItem_ { const char *name; /* keyword name, for error printing */ } DetectEngineThreadKeywordCtxItem; -enum DetectEnginePrefilterSetting -{ - DETECT_PREFILTER_MPM = 0, /**< use only mpm / fast_pattern */ - DETECT_PREFILTER_AUTO = 1, /**< use mpm + keyword prefilters */ +enum DetectEnginePrefilterSetting { + DETECT_PREFILTER_MPM = 0, /**< use only mpm / fast_pattern */ + DETECT_PREFILTER_AUTO = 1, /**< use mpm + keyword prefilters */ }; -enum DetectEngineType -{ +enum DetectEngineType { DETECT_ENGINE_TYPE_NORMAL = 0, DETECT_ENGINE_TYPE_DD_STUB = 1, /* delayed detect stub: can be reloaded */ DETECT_ENGINE_TYPE_MT_STUB = 2, /* multi-tenant stub: cannot be reloaded */ @@ -1061,8 +1055,8 @@ typedef struct SignatureNonPrefilterStore_ { /** array of TX inspect rule candidates */ typedef struct RuleMatchCandidateTx { - SigIntId id; /**< internal signature id */ - uint32_t *flags; /**< inspect flags ptr */ + SigIntId id; /**< internal signature id */ + uint32_t *flags; /**< inspect flags ptr */ union { struct { bool stream_stored; @@ -1071,12 +1065,12 @@ typedef struct RuleMatchCandidateTx { uint32_t stream_reset; }; - const Signature *s; /**< ptr to sig */ + const Signature *s; /**< ptr to sig */ } RuleMatchCandidateTx; /** - * Detection engine thread data. - */ + * Detection engine thread data. + */ typedef struct DetectEngineThreadCtx_ { /** \note multi-tenant hash lookup code from Detect() *depends* * on this being the first member */ @@ -1128,7 +1122,7 @@ typedef struct DetectEngineThreadCtx_ { struct { InspectionBuffer *buffers; - uint32_t buffers_size; /**< in number of elements */ + uint32_t buffers_size; /**< in number of elements */ uint32_t to_clear_idx; uint32_t *to_clear_queue; } inspect; @@ -1137,7 +1131,7 @@ typedef struct DetectEngineThreadCtx_ { /** inspection buffers for more complex case. As we can inspect multiple * buffers in parallel, we need this extra wrapper struct */ InspectionBufferMultipleForList *buffers; - uint32_t buffers_size; /**< in number of elements */ + uint32_t buffers_size; /**< in number of elements */ uint32_t to_clear_idx; uint32_t *to_clear_queue; } multi_inspect; @@ -1252,14 +1246,12 @@ typedef struct SigTableElmt_ { int (*Match)(DetectEngineThreadCtx *, Packet *, const Signature *, const SigMatchCtx *); /** AppLayer TX match function pointer */ - int (*AppLayerTxMatch)(DetectEngineThreadCtx *, Flow *, - uint8_t flags, void *alstate, void *txv, + int (*AppLayerTxMatch)(DetectEngineThreadCtx *, Flow *, uint8_t flags, void *alstate, void *txv, const Signature *, const SigMatchCtx *); /** File match function pointer */ - int (*FileMatch)(DetectEngineThreadCtx *, - Flow *, /**< *LOCKED* flow */ - uint8_t flags, File *, const Signature *, const SigMatchCtx *); + int (*FileMatch)(DetectEngineThreadCtx *, Flow *, /**< *LOCKED* flow */ + uint8_t flags, File *, const Signature *, const SigMatchCtx *); /** InspectionBuffer transformation callback */ void (*Transform)(InspectionBuffer *, void *context); @@ -1281,8 +1273,8 @@ typedef struct SigTableElmt_ { /** better keyword to replace the current one */ uint16_t alternative; - const char *name; /**< keyword name alias */ - const char *alias; /**< name alias */ + const char *name; /**< keyword name alias */ + const char *alias; /**< name alias */ const char *desc; const char *url; @@ -1307,14 +1299,14 @@ enum { DETECT_EVENT_TOO_MANY_BUFFERS, }; -#define SIG_GROUP_HEAD_HAVERAWSTREAM BIT_U32(0) +#define SIG_GROUP_HEAD_HAVERAWSTREAM BIT_U32(0) #ifdef HAVE_MAGIC -#define SIG_GROUP_HEAD_HAVEFILEMAGIC BIT_U32(20) +#define SIG_GROUP_HEAD_HAVEFILEMAGIC BIT_U32(20) #endif -#define SIG_GROUP_HEAD_HAVEFILEMD5 BIT_U32(21) -#define SIG_GROUP_HEAD_HAVEFILESIZE BIT_U32(22) -#define SIG_GROUP_HEAD_HAVEFILESHA1 BIT_U32(23) -#define SIG_GROUP_HEAD_HAVEFILESHA256 BIT_U32(24) +#define SIG_GROUP_HEAD_HAVEFILEMD5 BIT_U32(21) +#define SIG_GROUP_HEAD_HAVEFILESIZE BIT_U32(22) +#define SIG_GROUP_HEAD_HAVEFILESHA1 BIT_U32(23) +#define SIG_GROUP_HEAD_HAVEFILESHA256 BIT_U32(24) enum MpmBuiltinBuffers { MPMB_TCP_PKT_TS, @@ -1409,11 +1401,11 @@ typedef struct SigGroupHeadInitData_ { MpmStore mpm_store[MPMB_MAX]; uint8_t *sig_array; /**< bit array of sig nums (internal id's) */ - uint32_t sig_size; /**< size in bytes */ + uint32_t sig_size; /**< size in bytes */ - uint8_t protos[256]; /**< proto(s) this sgh is for */ - uint32_t direction; /**< set to SIG_FLAG_TOSERVER, SIG_FLAG_TOCLIENT or both */ - int whitelist; /**< try to make this group a unique one */ + uint8_t protos[256]; /**< proto(s) this sgh is for */ + uint32_t direction; /**< set to SIG_FLAG_TOSERVER, SIG_FLAG_TOCLIENT or both */ + int whitelist; /**< try to make this group a unique one */ MpmCtx **app_mpms; MpmCtx **pkt_mpms; @@ -1442,9 +1434,11 @@ typedef struct SigGroupHead_ { /* non prefilter list excluding SYN rules */ uint32_t non_pf_other_store_cnt; uint32_t non_pf_syn_store_cnt; - SignatureNonPrefilterStore *non_pf_other_store_array; // size is non_mpm_store_cnt * sizeof(SignatureNonPrefilterStore) + SignatureNonPrefilterStore *non_pf_other_store_array; // size is non_mpm_store_cnt * + // sizeof(SignatureNonPrefilterStore) /* non mpm list including SYN rules */ - SignatureNonPrefilterStore *non_pf_syn_store_array; // size is non_mpm_syn_store_cnt * sizeof(SignatureNonPrefilterStore) + SignatureNonPrefilterStore *non_pf_syn_store_array; // size is non_mpm_syn_store_cnt * + // sizeof(SignatureNonPrefilterStore) /** the number of signatures in this sgh that have the filestore keyword * set. */ @@ -1463,42 +1457,41 @@ typedef struct SigGroupHead_ { } SigGroupHead; /** sigmatch has no options, so the parser shouldn't expect any */ -#define SIGMATCH_NOOPT BIT_U16(0) +#define SIGMATCH_NOOPT BIT_U16(0) /** sigmatch is compatible with a ip only rule */ -#define SIGMATCH_IPONLY_COMPAT BIT_U16(1) +#define SIGMATCH_IPONLY_COMPAT BIT_U16(1) /** sigmatch is compatible with a decode event only rule */ -#define SIGMATCH_DEONLY_COMPAT BIT_U16(2) +#define SIGMATCH_DEONLY_COMPAT BIT_U16(2) /**< Flag to indicate that the signature is not built-in */ -#define SIGMATCH_NOT_BUILT BIT_U16(3) +#define SIGMATCH_NOT_BUILT BIT_U16(3) /** sigmatch may have options, so the parser should be ready to * deal with both cases */ -#define SIGMATCH_OPTIONAL_OPT BIT_U16(4) +#define SIGMATCH_OPTIONAL_OPT BIT_U16(4) /** input may be wrapped in double quotes. They will be stripped before * input data is passed to keyword parser */ -#define SIGMATCH_QUOTES_OPTIONAL BIT_U16(5) +#define SIGMATCH_QUOTES_OPTIONAL BIT_U16(5) /** input MUST be wrapped in double quotes. They will be stripped before * input data is passed to keyword parser. Missing double quotes lead to * error and signature invalidation. */ -#define SIGMATCH_QUOTES_MANDATORY BIT_U16(6) +#define SIGMATCH_QUOTES_MANDATORY BIT_U16(6) /** negation parsing is handled by the rule parser. Signature::init_data::negated * will be set to true or false prior to calling the keyword parser. Exclamation * mark is stripped from the input to the keyword parser. */ -#define SIGMATCH_HANDLE_NEGATION BIT_U16(7) +#define SIGMATCH_HANDLE_NEGATION BIT_U16(7) /** keyword is a content modifier */ -#define SIGMATCH_INFO_CONTENT_MODIFIER BIT_U16(8) +#define SIGMATCH_INFO_CONTENT_MODIFIER BIT_U16(8) /** keyword is a sticky buffer */ -#define SIGMATCH_INFO_STICKY_BUFFER BIT_U16(9) +#define SIGMATCH_INFO_STICKY_BUFFER BIT_U16(9) /** keyword is deprecated: used to suggest an alternative */ -#define SIGMATCH_INFO_DEPRECATED BIT_U16(10) +#define SIGMATCH_INFO_DEPRECATED BIT_U16(10) /** strict parsing is enabled */ -#define SIGMATCH_STRICT_PARSING BIT_U16(11) - -enum DetectEngineTenantSelectors -{ - TENANT_SELECTOR_UNKNOWN = 0, /**< not set */ - TENANT_SELECTOR_DIRECT, /**< method provides direct tenant id */ - TENANT_SELECTOR_VLAN, /**< map vlan to tenant id */ - TENANT_SELECTOR_LIVEDEV, /**< map livedev to tenant id */ +#define SIGMATCH_STRICT_PARSING BIT_U16(11) + +enum DetectEngineTenantSelectors { + TENANT_SELECTOR_UNKNOWN = 0, /**< not set */ + TENANT_SELECTOR_DIRECT, /**< method provides direct tenant id */ + TENANT_SELECTOR_VLAN, /**< map vlan to tenant id */ + TENANT_SELECTOR_LIVEDEV, /**< map livedev to tenant id */ }; typedef struct DetectEngineTenantMapping_ { @@ -1544,7 +1537,8 @@ typedef struct DetectEngineMasterCtx_ { /* Table with all SigMatch registrations */ extern SigTableElmt sigmatch_table[DETECT_TBLSIZE]; -/** Remember to add the options in SignatureIsIPOnly() at detect.c otherwise it wont be part of a signature group */ +/** Remember to add the options in SignatureIsIPOnly() at detect.c otherwise it wont be part of a + * signature group */ /* detection api */ TmEcode Detect(ThreadVars *tv, Packet *p, void *data); @@ -1558,14 +1552,15 @@ void SigRegisterTests(void); void DisableDetectFlowFileFlags(Flow *f); char *DetectLoadCompleteSigPath(const DetectEngineCtx *, const char *sig_file); int SigLoadSignatures(DetectEngineCtx *, char *, bool); -void SigMatchSignatures(ThreadVars *th_v, DetectEngineCtx *de_ctx, - DetectEngineThreadCtx *det_ctx, Packet *p); +void SigMatchSignatures( + ThreadVars *th_v, DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx, Packet *p); int SignatureIsIPOnly(DetectEngineCtx *de_ctx, const Signature *s); const SigGroupHead *SigMatchSignaturesGetSgh(const DetectEngineCtx *de_ctx, const Packet *p); int DetectUnregisterThreadCtxFuncs(DetectEngineCtx *, void *data, const char *name); -int DetectRegisterThreadCtxFuncs(DetectEngineCtx *, const char *name, void *(*InitFunc)(void *), void *data, void (*FreeFunc)(void *), int); +int DetectRegisterThreadCtxFuncs(DetectEngineCtx *, const char *name, void *(*InitFunc)(void *), + void *data, void (*FreeFunc)(void *), int); void *DetectThreadCtxGetKeywordThreadCtx(DetectEngineThreadCtx *, int); void RuleMatchCandidateTxArrayInit(DetectEngineThreadCtx *det_ctx, uint32_t size); @@ -1587,6 +1582,4 @@ AppLayerDecoderEvents *DetectEngineGetEvents(DetectEngineThreadCtx *det_ctx); void DumpPatterns(DetectEngineCtx *de_ctx); - #endif /* __DETECT_H__ */ - diff --git a/src/device-storage.c b/src/device-storage.c index d4314c021ea5..b23ea3de2c27 100644 --- a/src/device-storage.c +++ b/src/device-storage.c @@ -112,5 +112,3 @@ void LiveDevFreeStorage(LiveDevice *d) if (LiveDevStorageSize() > 0) StorageFreeAll(d->storage, STORAGE_DEVICE); } - - diff --git a/src/feature.c b/src/feature.c index 0edf9433aca9..d4b66f133d6d 100644 --- a/src/feature.c +++ b/src/feature.c @@ -31,14 +31,13 @@ #include "util-hashlist.h" typedef struct FeatureEntryType { - const char *feature; + const char *feature; } FeatureEntryType; static SCMutex feature_table_mutex = SCMUTEX_INITIALIZER; static HashListTable *feature_hash_table; -static uint32_t FeatureHashFunc(HashListTable *ht, void *data, - uint16_t datalen) +static uint32_t FeatureHashFunc(HashListTable *ht, void *data, uint16_t datalen) { FeatureEntryType *f = (FeatureEntryType *)data; uint32_t hash = 0; @@ -50,8 +49,7 @@ static uint32_t FeatureHashFunc(HashListTable *ht, void *data, return (hash % ht->array_size); } -static char FeatureHashCompareFunc(void *data1, uint16_t datalen1, - void *data2, uint16_t datalen2) +static char FeatureHashCompareFunc(void *data1, uint16_t datalen1, void *data2, uint16_t datalen2) { FeatureEntryType *f1 = (FeatureEntryType *)data1; FeatureEntryType *f2 = (FeatureEntryType *)data2; @@ -79,10 +77,10 @@ static void FeatureHashFreeFunc(void *data) SCFree(data); } -static void FeatureInit(void) { - feature_hash_table = HashListTableInit(256, FeatureHashFunc, - FeatureHashCompareFunc, - FeatureHashFreeFunc); +static void FeatureInit(void) +{ + feature_hash_table = + HashListTableInit(256, FeatureHashFunc, FeatureHashCompareFunc, FeatureHashFreeFunc); if (!feature_hash_table) { FatalError("Unable to allocate feature hash table."); diff --git a/src/feature.h b/src/feature.h index 6549c5bbeab5..82251cbeb80a 100644 --- a/src/feature.h +++ b/src/feature.h @@ -25,7 +25,7 @@ #define __FEATURE_H__ /* Provided feature names */ -#define FEATURE_OUTPUT_FILESTORE "output::file-store" +#define FEATURE_OUTPUT_FILESTORE "output::file-store" void ProvidesFeature(const char *); bool RequiresFeature(const char *); diff --git a/src/flow-bit.c b/src/flow-bit.c index f59e7eae943e..e345e7b2fcae 100644 --- a/src/flow-bit.c +++ b/src/flow-bit.c @@ -46,7 +46,7 @@ static FlowBit *FlowBitGet(Flow *f, uint32_t idx) { GenericVar *gv = f->flowvar; - for ( ; gv != NULL; gv = gv->next) { + for (; gv != NULL; gv = gv->next) { if (gv->type == DETECT_FLOWBITS && gv->idx == idx) { return (FlowBit *)gv; } @@ -133,10 +133,9 @@ void FlowBitFree(FlowBit *fb) SCFree(fb); } - /* TESTS */ #ifdef UNITTESTS -static int FlowBitTest01 (void) +static int FlowBitTest01(void) { Flow f; memset(&f, 0, sizeof(Flow)); @@ -150,7 +149,7 @@ static int FlowBitTest01 (void) PASS; } -static int FlowBitTest02 (void) +static int FlowBitTest02(void) { Flow f; memset(&f, 0, sizeof(Flow)); @@ -162,14 +161,14 @@ static int FlowBitTest02 (void) PASS; } -static int FlowBitTest03 (void) +static int FlowBitTest03(void) { Flow f; memset(&f, 0, sizeof(Flow)); FlowBitAdd(&f, 0); - FlowBit *fb = FlowBitGet(&f,0); + FlowBit *fb = FlowBitGet(&f, 0); FAIL_IF_NULL(fb); FlowBitRemove(&f, 0); @@ -181,7 +180,7 @@ static int FlowBitTest03 (void) PASS; } -static int FlowBitTest04 (void) +static int FlowBitTest04(void) { Flow f; memset(&f, 0, sizeof(Flow)); @@ -198,7 +197,7 @@ static int FlowBitTest04 (void) PASS; } -static int FlowBitTest05 (void) +static int FlowBitTest05(void) { Flow f; memset(&f, 0, sizeof(Flow)); @@ -215,7 +214,7 @@ static int FlowBitTest05 (void) PASS; } -static int FlowBitTest06 (void) +static int FlowBitTest06(void) { Flow f; memset(&f, 0, sizeof(Flow)); @@ -232,7 +231,7 @@ static int FlowBitTest06 (void) PASS; } -static int FlowBitTest07 (void) +static int FlowBitTest07(void) { Flow f; memset(&f, 0, sizeof(Flow)); @@ -249,7 +248,7 @@ static int FlowBitTest07 (void) PASS; } -static int FlowBitTest08 (void) +static int FlowBitTest08(void) { Flow f; memset(&f, 0, sizeof(Flow)); @@ -259,10 +258,10 @@ static int FlowBitTest08 (void) FlowBitAdd(&f, 2); FlowBitAdd(&f, 3); - FlowBit *fb = FlowBitGet(&f,0); + FlowBit *fb = FlowBitGet(&f, 0); FAIL_IF_NULL(fb); - FlowBitRemove(&f,0); + FlowBitRemove(&f, 0); fb = FlowBitGet(&f, 0); FAIL_IF_NOT_NULL(fb); @@ -271,7 +270,7 @@ static int FlowBitTest08 (void) PASS; } -static int FlowBitTest09 (void) +static int FlowBitTest09(void) { Flow f; memset(&f, 0, sizeof(Flow)); @@ -281,10 +280,10 @@ static int FlowBitTest09 (void) FlowBitAdd(&f, 2); FlowBitAdd(&f, 3); - FlowBit *fb = FlowBitGet(&f,1); + FlowBit *fb = FlowBitGet(&f, 1); FAIL_IF_NULL(fb); - FlowBitRemove(&f,1); + FlowBitRemove(&f, 1); fb = FlowBitGet(&f, 1); FAIL_IF_NOT_NULL(fb); @@ -293,7 +292,7 @@ static int FlowBitTest09 (void) PASS; } -static int FlowBitTest10 (void) +static int FlowBitTest10(void) { Flow f; memset(&f, 0, sizeof(Flow)); @@ -303,10 +302,10 @@ static int FlowBitTest10 (void) FlowBitAdd(&f, 2); FlowBitAdd(&f, 3); - FlowBit *fb = FlowBitGet(&f,2); + FlowBit *fb = FlowBitGet(&f, 2); FAIL_IF_NULL(fb); - FlowBitRemove(&f,2); + FlowBitRemove(&f, 2); fb = FlowBitGet(&f, 2); FAIL_IF_NOT_NULL(fb); @@ -315,7 +314,7 @@ static int FlowBitTest10 (void) PASS; } -static int FlowBitTest11 (void) +static int FlowBitTest11(void) { Flow f; memset(&f, 0, sizeof(Flow)); @@ -325,10 +324,10 @@ static int FlowBitTest11 (void) FlowBitAdd(&f, 2); FlowBitAdd(&f, 3); - FlowBit *fb = FlowBitGet(&f,3); + FlowBit *fb = FlowBitGet(&f, 3); FAIL_IF_NULL(fb); - FlowBitRemove(&f,3); + FlowBitRemove(&f, 3); fb = FlowBitGet(&f, 3); FAIL_IF_NOT_NULL(fb); @@ -355,4 +354,3 @@ void FlowBitRegisterTests(void) UtRegisterTest("FlowBitTest11", FlowBitTest11); #endif /* UNITTESTS */ } - diff --git a/src/flow-bit.h b/src/flow-bit.h index 2362d5180795..a9ae0b65b4ac 100644 --- a/src/flow-bit.h +++ b/src/flow-bit.h @@ -30,7 +30,7 @@ typedef struct FlowBit_ { uint8_t type; /* type, DETECT_FLOWBITS in this case */ uint8_t pad[3]; - uint32_t idx; /* name idx */ + uint32_t idx; /* name idx */ GenericVar *next; /* right now just implement this as a list, * in the long run we have think of something * faster. */ @@ -45,4 +45,3 @@ void FlowBitToggle(Flow *, uint32_t); int FlowBitIsset(Flow *, uint32_t); int FlowBitIsnotset(Flow *, uint32_t); #endif /* __FLOW_BIT_H__ */ - diff --git a/src/flow-bypass.c b/src/flow-bypass.c index 8dbb5ab17d74..a14b89aac021 100644 --- a/src/flow-bypass.c +++ b/src/flow-bypass.c @@ -31,13 +31,14 @@ #ifdef CAPTURE_OFFLOAD_MANAGER -#define FLOW_BYPASS_DELAY 10 +#define FLOW_BYPASS_DELAY 10 #ifndef TIMEVAL_TO_TIMESPEC -#define TIMEVAL_TO_TIMESPEC(tv, ts) { \ - (ts)->tv_sec = (tv)->tv_sec; \ - (ts)->tv_nsec = (tv)->tv_usec * 1000; \ -} +#define TIMEVAL_TO_TIMESPEC(tv, ts) \ + { \ + (ts)->tv_sec = (tv)->tv_sec; \ + (ts)->tv_nsec = (tv)->tv_usec * 1000; \ + } #endif typedef struct BypassedFlowManagerThreadData_ { @@ -46,7 +47,7 @@ typedef struct BypassedFlowManagerThreadData_ { uint16_t flow_bypassed_bytes; } BypassedFlowManagerThreadData; -#define BYPASSFUNCMAX 4 +#define BYPASSFUNCMAX 4 typedef struct BypassedCheckFuncItem_ { BypassedCheckFunc Func; @@ -70,7 +71,7 @@ static TmEcode BypassedFlowManager(ThreadVars *th_v, void *thread_data) int tcount = 0; int i; BypassedFlowManagerThreadData *ftd = thread_data; - struct timespec curtime = {0, 0}; + struct timespec curtime = { 0, 0 }; struct timeval tv; gettimeofday(&tv, NULL); @@ -99,10 +100,11 @@ static TmEcode BypassedFlowManager(ThreadVars *th_v, void *thread_data) TIMEVAL_TO_TIMESPEC(&tv, &curtime); for (i = 0; i < g_bypassed_func_max_index; i++) { - struct flows_stats bypassstats = { 0, 0, 0}; + struct flows_stats bypassstats = { 0, 0, 0 }; if (bypassedfunclist[i].Func == NULL) continue; - tcount = bypassedfunclist[i].Func(th_v, &bypassstats, &curtime, bypassedfunclist[i].data); + tcount = bypassedfunclist[i].Func( + th_v, &bypassstats, &curtime, bypassedfunclist[i].data); if (tcount) { StatsAddUI64(th_v, ftd->flow_bypassed_cnt_clo, (uint64_t)bypassstats.count); } @@ -148,9 +150,8 @@ static TmEcode BypassedFlowManagerThreadDeinit(ThreadVars *t, void *data) return TM_ECODE_OK; } -int BypassedFlowManagerRegisterCheckFunc(BypassedCheckFunc CheckFunc, - BypassedCheckFuncInit CheckFuncInit, - void *data) +int BypassedFlowManagerRegisterCheckFunc( + BypassedCheckFunc CheckFunc, BypassedCheckFuncInit CheckFuncInit, void *data) { if (g_bypassed_func_max_index < BYPASSFUNCMAX) { bypassedfunclist[g_bypassed_func_max_index].Func = CheckFunc; @@ -163,8 +164,7 @@ int BypassedFlowManagerRegisterCheckFunc(BypassedCheckFunc CheckFunc, return 0; } -int BypassedFlowManagerRegisterUpdateFunc(BypassedUpdateFunc UpdateFunc, - void *data) +int BypassedFlowManagerRegisterUpdateFunc(BypassedUpdateFunc UpdateFunc, void *data) { if (!UpdateFunc) { return -1; @@ -186,8 +186,7 @@ void BypassedFlowManagerThreadSpawn(void) #ifdef CAPTURE_OFFLOAD_MANAGER ThreadVars *tv_flowmgr = NULL; - tv_flowmgr = TmThreadCreateMgmtThreadByName(thread_name_flow_bypass, - "BypassedFlowManager", 0); + tv_flowmgr = TmThreadCreateMgmtThreadByName(thread_name_flow_bypass, "BypassedFlowManager", 0); BUG_ON(tv_flowmgr == NULL); if (tv_flowmgr == NULL) { @@ -212,7 +211,7 @@ void BypassedFlowUpdate(Flow *f, Packet *p) #endif } -void TmModuleBypassedFlowManagerRegister (void) +void TmModuleBypassedFlowManagerRegister(void) { #ifdef CAPTURE_OFFLOAD_MANAGER tmm_modules[TMM_BYPASSEDFLOWMANAGER].name = "BypassedFlowManager"; @@ -224,4 +223,3 @@ void TmModuleBypassedFlowManagerRegister (void) SCLogDebug("%s registered", tmm_modules[TMM_BYPASSEDFLOWMANAGER].name); #endif } - diff --git a/src/flow-bypass.h b/src/flow-bypass.h index 58ca76663655..9e4523872b1b 100644 --- a/src/flow-bypass.h +++ b/src/flow-bypass.h @@ -32,22 +32,18 @@ struct flows_stats { uint64_t bytes; }; -typedef int (*BypassedCheckFunc)(ThreadVars *th_v, - struct flows_stats *bypassstats, - struct timespec *curtime, void *data); -typedef int (*BypassedCheckFuncInit)(ThreadVars *th_v, - struct timespec *curtime, void *data); +typedef int (*BypassedCheckFunc)( + ThreadVars *th_v, struct flows_stats *bypassstats, struct timespec *curtime, void *data); +typedef int (*BypassedCheckFuncInit)(ThreadVars *th_v, struct timespec *curtime, void *data); typedef int (*BypassedUpdateFunc)(Flow *f, Packet *p, void *data); void BypassedFlowManagerThreadSpawn(void); void TmModuleBypassedFlowManagerRegister(void); -int BypassedFlowManagerRegisterCheckFunc(BypassedCheckFunc CheckFunc, - BypassedCheckFuncInit CheckFuncInit, void *data); +int BypassedFlowManagerRegisterCheckFunc( + BypassedCheckFunc CheckFunc, BypassedCheckFuncInit CheckFuncInit, void *data); int BypassedFlowManagerRegisterUpdateFunc(BypassedUpdateFunc UpdateFunc, void *data); void BypassedFlowUpdate(Flow *f, Packet *p); #endif - - diff --git a/src/flow-hash.c b/src/flow-hash.c index 3b221e2ffffc..f8feedd99f3b 100644 --- a/src/flow-hash.c +++ b/src/flow-hash.c @@ -54,7 +54,6 @@ extern TcpStreamCnf stream_config; - FlowBucket *flow_hash; SC_ATOMIC_EXTERN(unsigned int, flow_prune_idx); SC_ATOMIC_EXTERN(unsigned int, flow_flags); @@ -196,11 +195,11 @@ static inline uint32_t FlowGetHash(const Packet *p) FlowHashKey4 fhk = { .pad[0] = 0 }; int ai = (p->src.addr_data32[0] > p->dst.addr_data32[0]); - fhk.addrs[1-ai] = p->src.addr_data32[0]; + fhk.addrs[1 - ai] = p->src.addr_data32[0]; fhk.addrs[ai] = p->dst.addr_data32[0]; const int pi = (p->sp > p->dp); - fhk.ports[1-pi] = p->sp; + fhk.ports[1 - pi] = p->sp; fhk.ports[pi] = p->dp; fhk.proto = p->proto; @@ -223,11 +222,11 @@ static inline uint32_t FlowGetHash(const Packet *p) FlowHashKey4 fhk = { .pad[0] = 0 }; const int ai = (psrc > pdst); - fhk.addrs[1-ai] = psrc; + fhk.addrs[1 - ai] = psrc; fhk.addrs[ai] = pdst; const int pi = (p->icmpv4vars.emb_sport > p->icmpv4vars.emb_dport); - fhk.ports[1-pi] = p->icmpv4vars.emb_sport; + fhk.ports[1 - pi] = p->icmpv4vars.emb_sport; fhk.ports[pi] = p->icmpv4vars.emb_dport; fhk.proto = ICMPV4_GET_EMB_PROTO(p); @@ -243,7 +242,7 @@ static inline uint32_t FlowGetHash(const Packet *p) } else { FlowHashKey4 fhk = { .pad[0] = 0 }; const int ai = (p->src.addr_data32[0] > p->dst.addr_data32[0]); - fhk.addrs[1-ai] = p->src.addr_data32[0]; + fhk.addrs[1 - ai] = p->src.addr_data32[0]; fhk.addrs[ai] = p->dst.addr_data32[0]; fhk.ports[0] = 0xfeed; fhk.ports[1] = 0xbeef; @@ -280,7 +279,7 @@ static inline uint32_t FlowGetHash(const Packet *p) } const int pi = (p->sp > p->dp); - fhk.ports[1-pi] = p->sp; + fhk.ports[1 - pi] = p->sp; fhk.ports[pi] = p->dp; fhk.proto = p->proto; fhk.recur = p->recursion_level; @@ -313,11 +312,11 @@ uint32_t FlowKeyGetHash(FlowKey *fk) .pad[0] = 0, }; int ai = (fk->src.address.address_un_data32[0] > fk->dst.address.address_un_data32[0]); - fhk.addrs[1-ai] = fk->src.address.address_un_data32[0]; + fhk.addrs[1 - ai] = fk->src.address.address_un_data32[0]; fhk.addrs[ai] = fk->dst.address.address_un_data32[0]; const int pi = (fk->sp > fk->dp); - fhk.ports[1-pi] = fk->sp; + fhk.ports[1 - pi] = fk->sp; fhk.ports[pi] = fk->dp; fhk.proto = fk->proto; @@ -332,8 +331,8 @@ uint32_t FlowKeyGetHash(FlowKey *fk) FlowHashKey6 fhk = { .pad[0] = 0, }; - if (FlowHashRawAddressIPv6GtU32(fk->src.address.address_un_data32, - fk->dst.address.address_un_data32)) { + if (FlowHashRawAddressIPv6GtU32( + fk->src.address.address_un_data32, fk->dst.address.address_un_data32)) { fhk.src[0] = fk->src.address.address_un_data32[0]; fhk.src[1] = fk->src.address.address_un_data32[1]; fhk.src[2] = fk->src.address.address_un_data32[2]; @@ -354,7 +353,7 @@ uint32_t FlowKeyGetHash(FlowKey *fk) } const int pi = (fk->sp > fk->dp); - fhk.ports[1-pi] = fk->sp; + fhk.ports[1 - pi] = fk->sp; fhk.ports[pi] = fk->dp; fhk.proto = fk->proto; fhk.recur = fk->recursion_level; @@ -370,22 +369,21 @@ uint32_t FlowKeyGetHash(FlowKey *fk) static inline bool CmpAddrs(const uint32_t addr1[4], const uint32_t addr2[4]) { - return addr1[0] == addr2[0] && addr1[1] == addr2[1] && - addr1[2] == addr2[2] && addr1[3] == addr2[3]; + return addr1[0] == addr2[0] && addr1[1] == addr2[1] && addr1[2] == addr2[2] && + addr1[3] == addr2[3]; } -static inline bool CmpAddrsAndPorts(const uint32_t src1[4], - const uint32_t dst1[4], Port src_port1, Port dst_port1, - const uint32_t src2[4], const uint32_t dst2[4], Port src_port2, - Port dst_port2) +static inline bool CmpAddrsAndPorts(const uint32_t src1[4], const uint32_t dst1[4], Port src_port1, + Port dst_port1, const uint32_t src2[4], const uint32_t dst2[4], Port src_port2, + Port dst_port2) { /* Compare the source and destination addresses. If they are not equal, * compare the first source address with the second destination address, * and vice versa. Likewise for ports. */ - return (CmpAddrs(src1, src2) && CmpAddrs(dst1, dst2) && - src_port1 == src_port2 && dst_port1 == dst_port2) || - (CmpAddrs(src1, dst2) && CmpAddrs(dst1, src2) && - src_port1 == dst_port2 && dst_port1 == src_port2); + return (CmpAddrs(src1, src2) && CmpAddrs(dst1, dst2) && src_port1 == src_port2 && + dst_port1 == dst_port2) || + (CmpAddrs(src1, dst2) && CmpAddrs(dst1, src2) && src_port1 == dst_port2 && + dst_port1 == src_port2); } static inline bool CmpVlanIds( @@ -426,18 +424,17 @@ static inline bool CmpFlowKey(const Flow *f, const FlowKey *k) CmpVlanIds(f->vlan_id, k->vlan_id) && CmpLiveDevIds(f->livedev, k->livedev_id); } -static inline bool CmpAddrsAndICMPTypes(const uint32_t src1[4], - const uint32_t dst1[4], uint8_t icmp_s_type1, uint8_t icmp_d_type1, - const uint32_t src2[4], const uint32_t dst2[4], uint8_t icmp_s_type2, - uint8_t icmp_d_type2) +static inline bool CmpAddrsAndICMPTypes(const uint32_t src1[4], const uint32_t dst1[4], + uint8_t icmp_s_type1, uint8_t icmp_d_type1, const uint32_t src2[4], const uint32_t dst2[4], + uint8_t icmp_s_type2, uint8_t icmp_d_type2) { /* Compare the source and destination addresses. If they are not equal, * compare the first source address with the second destination address, * and vice versa. Likewise for icmp types. */ - return (CmpAddrs(src1, src2) && CmpAddrs(dst1, dst2) && - icmp_s_type1 == icmp_s_type2 && icmp_d_type1 == icmp_d_type2) || - (CmpAddrs(src1, dst2) && CmpAddrs(dst1, src2) && - icmp_s_type1 == icmp_d_type2 && icmp_d_type1 == icmp_s_type2); + return (CmpAddrs(src1, src2) && CmpAddrs(dst1, dst2) && icmp_s_type1 == icmp_s_type2 && + icmp_d_type1 == icmp_d_type2) || + (CmpAddrs(src1, dst2) && CmpAddrs(dst1, src2) && icmp_s_type1 == icmp_d_type2 && + icmp_d_type1 == icmp_s_type2); } static inline bool CmpFlowICMPPacket(const Flow *f, const Packet *p) @@ -476,8 +473,8 @@ static inline int FlowCompareICMPv4(Flow *f, const Packet *p) (f->livedev == p->livedev || g_livedev_mask == 0)) { return 1; - /* check the less likely case where the ICMP error was a response to - * a packet from the server. */ + /* check the less likely case where the ICMP error was a response to + * a packet from the server. */ } else if ((f->dst.addr_data32[0] == IPV4_GET_RAW_IPSRC_U32(ICMPV4_GET_EMB_IPV4(p))) && (f->src.addr_data32[0] == IPV4_GET_RAW_IPDST_U32(ICMPV4_GET_EMB_IPV4(p))) && f->dp == p->icmpv4vars.emb_sport && f->sp == p->icmpv4vars.emb_dport && @@ -569,15 +566,14 @@ static inline int FlowCreateCheck(const Packet *p, const bool emerg) return 1; } -static inline void FlowUpdateCounter(ThreadVars *tv, DecodeThreadVars *dtv, - uint8_t proto) +static inline void FlowUpdateCounter(ThreadVars *tv, DecodeThreadVars *dtv, uint8_t proto) { #ifdef UNITTESTS if (tv && dtv) { #endif StatsIncr(tv, dtv->counter_flow_total); StatsIncr(tv, dtv->counter_flow_active); - switch (proto){ + switch (proto) { case IPPROTO_UDP: StatsIncr(tv, dtv->counter_flow_udp); break; @@ -601,8 +597,8 @@ static inline void FlowUpdateCounter(ThreadVars *tv, DecodeThreadVars *dtv, * * If in emergency mode, do this only once a second at max to avoid trying * to synchronise per packet in the worse case. */ -static inline Flow *FlowSpareSync(ThreadVars *tv, FlowLookupStruct *fls, - const Packet *p, const bool emerg) +static inline Flow *FlowSpareSync( + ThreadVars *tv, FlowLookupStruct *fls, const Packet *p, const bool emerg) { Flow *f = NULL; bool spare_sync = false; @@ -626,7 +622,7 @@ static inline Flow *FlowSpareSync(ThreadVars *tv, FlowLookupStruct *fls, #endif if (spare_sync) { if (f != NULL) { - StatsAddUI64(tv, fls->dtv->counter_flow_spare_sync_avg, fls->spare_queue.len+1); + StatsAddUI64(tv, fls->dtv->counter_flow_spare_sync_avg, fls->spare_queue.len + 1); if (fls->spare_queue.len < 99) { StatsIncr(tv, fls->dtv->counter_flow_spare_sync_incomplete); } @@ -780,8 +776,8 @@ static inline bool FlowBelongsToUs(const ThreadVars *tv, const Flow *f) return f->thread_id[0] == tv->id; } -static inline void MoveToWorkQueue(ThreadVars *tv, FlowLookupStruct *fls, - FlowBucket *fb, Flow *f, Flow *prev_f) +static inline void MoveToWorkQueue( + ThreadVars *tv, FlowLookupStruct *fls, FlowBucket *fb, Flow *f, Flow *prev_f) { f->flow_end_flags |= FLOW_END_FLAG_TIMEOUT; @@ -815,8 +811,8 @@ static inline bool FlowIsTimedOut(const Flow *f, const uint32_t sec, const bool } else if (unlikely(emerg)) { extern FlowProtoTimeout flow_timeouts_delta[FLOW_PROTO_MAX]; - int64_t timeout_at = f->timeout_at - - FlowGetFlowTimeoutDirect(flow_timeouts_delta, f->flow_state, f->protomap); + int64_t timeout_at = f->timeout_at - FlowGetFlowTimeoutDirect(flow_timeouts_delta, + f->flow_state, f->protomap); if ((int64_t)sec >= timeout_at) return true; } @@ -897,7 +893,7 @@ Flow *FlowGetFlowFromHash(ThreadVars *tv, FlowLookupStruct *fls, Packet *p, Flow if (prev_f == NULL) /* if we have no prev it means new_f is now our prev */ prev_f = new_f; MoveToWorkQueue(tv, fls, fb, f, prev_f); /* evict old flow */ - FLOWLOCK_UNLOCK(f); /* unlock old replaced flow */ + FLOWLOCK_UNLOCK(f); /* unlock old replaced flow */ if (new_f == NULL) { FBLOCK_UNLOCK(fb); @@ -914,7 +910,7 @@ Flow *FlowGetFlowFromHash(ThreadVars *tv, FlowLookupStruct *fls, Packet *p, Flow prev_f = f; next_f = f->next; -flow_removed: + flow_removed: if (next_f == NULL) { f = FlowGetNew(tv, fls, p); if (f == NULL) { @@ -1096,7 +1092,7 @@ static inline int GetUsedTryLockFlow(Flow *f) } static inline uint32_t GetUsedAtomicUpdate(const uint32_t val) { - uint32_t r = SC_ATOMIC_ADD(flow_prune_idx, val); + uint32_t r = SC_ATOMIC_ADD(flow_prune_idx, val); return r; } @@ -1131,13 +1127,12 @@ static inline bool StillAlive(const Flow *f, const SCTime_t ts) } #ifdef UNITTESTS - #define STATSADDUI64(cnt, value) \ - if (tv && dtv) { \ - StatsAddUI64(tv, dtv->cnt, (value)); \ - } +#define STATSADDUI64(cnt, value) \ + if (tv && dtv) { \ + StatsAddUI64(tv, dtv->cnt, (value)); \ + } #else - #define STATSADDUI64(cnt, value) \ - StatsAddUI64(tv, dtv->cnt, (value)); +#define STATSADDUI64(cnt, value) StatsAddUI64(tv, dtv->cnt, (value)); #endif /** \internal @@ -1208,7 +1203,7 @@ static Flow *FlowGetUsedFlow(ThreadVars *tv, DecodeThreadVars *dtv, const SCTime if (SC_ATOMIC_GET(flow_flags) & FLOW_EMERGENCY) f->flow_end_flags |= FLOW_END_FLAG_EMERGENCY; - /* invoke flow log api */ + /* invoke flow log api */ #ifdef UNITTESTS if (dtv) { #endif diff --git a/src/flow-hash.h b/src/flow-hash.h index 201eb6414543..6294c6beb03d 100644 --- a/src/flow-hash.h +++ b/src/flow-hash.h @@ -31,9 +31,9 @@ #define FBLOCK_MUTEX #ifdef FBLOCK_SPIN - #ifdef FBLOCK_MUTEX - #error Cannot enable both FBLOCK_SPIN and FBLOCK_MUTEX - #endif +#ifdef FBLOCK_MUTEX +#error Cannot enable both FBLOCK_SPIN and FBLOCK_MUTEX +#endif #endif /* flow hash bucket -- the hash is basically an array of these buckets. @@ -51,7 +51,7 @@ typedef struct FlowBucket_ { #elif defined FBLOCK_SPIN SCSpinlock s; #else - #error Enable FBLOCK_SPIN or FBLOCK_MUTEX +#error Enable FBLOCK_SPIN or FBLOCK_MUTEX #endif /** timestamp in seconds of the earliest possible moment a flow * will time out in this row. Set by the flow manager. Cleared @@ -62,19 +62,19 @@ typedef struct FlowBucket_ { } __attribute__((aligned(CLS))) FlowBucket; #ifdef FBLOCK_SPIN - #define FBLOCK_INIT(fb) SCSpinInit(&(fb)->s, 0) - #define FBLOCK_DESTROY(fb) SCSpinDestroy(&(fb)->s) - #define FBLOCK_LOCK(fb) SCSpinLock(&(fb)->s) - #define FBLOCK_TRYLOCK(fb) SCSpinTrylock(&(fb)->s) - #define FBLOCK_UNLOCK(fb) SCSpinUnlock(&(fb)->s) +#define FBLOCK_INIT(fb) SCSpinInit(&(fb)->s, 0) +#define FBLOCK_DESTROY(fb) SCSpinDestroy(&(fb)->s) +#define FBLOCK_LOCK(fb) SCSpinLock(&(fb)->s) +#define FBLOCK_TRYLOCK(fb) SCSpinTrylock(&(fb)->s) +#define FBLOCK_UNLOCK(fb) SCSpinUnlock(&(fb)->s) #elif defined FBLOCK_MUTEX - #define FBLOCK_INIT(fb) SCMutexInit(&(fb)->m, NULL) - #define FBLOCK_DESTROY(fb) SCMutexDestroy(&(fb)->m) - #define FBLOCK_LOCK(fb) SCMutexLock(&(fb)->m) - #define FBLOCK_TRYLOCK(fb) SCMutexTrylock(&(fb)->m) - #define FBLOCK_UNLOCK(fb) SCMutexUnlock(&(fb)->m) +#define FBLOCK_INIT(fb) SCMutexInit(&(fb)->m, NULL) +#define FBLOCK_DESTROY(fb) SCMutexDestroy(&(fb)->m) +#define FBLOCK_LOCK(fb) SCMutexLock(&(fb)->m) +#define FBLOCK_TRYLOCK(fb) SCMutexTrylock(&(fb)->m) +#define FBLOCK_UNLOCK(fb) SCMutexUnlock(&(fb)->m) #else - #error Enable FBLOCK_SPIN or FBLOCK_MUTEX +#error Enable FBLOCK_SPIN or FBLOCK_MUTEX #endif /* prototypes */ @@ -103,4 +103,3 @@ static inline void RemoveFromHash(Flow *f, Flow *prev_f) } #endif /* __FLOW_HASH_H__ */ - diff --git a/src/flow-manager.c b/src/flow-manager.c index bcc1498c8bd8..893e6d0d675d 100644 --- a/src/flow-manager.c +++ b/src/flow-manager.c @@ -114,12 +114,12 @@ void FlowTimeoutsEmergency(void) } /* 1 seconds */ -#define FLOW_NORMAL_MODE_UPDATE_DELAY_SEC 1 +#define FLOW_NORMAL_MODE_UPDATE_DELAY_SEC 1 #define FLOW_NORMAL_MODE_UPDATE_DELAY_NSEC 0 /* 0.3 seconds */ -#define FLOW_EMERG_MODE_UPDATE_DELAY_SEC 0 +#define FLOW_EMERG_MODE_UPDATE_DELAY_SEC 0 #define FLOW_EMERG_MODE_UPDATE_DELAY_NSEC 300000 -#define NEW_FLOW_COUNT_COND 10 +#define NEW_FLOW_COUNT_COND 10 typedef struct FlowTimeoutCounters_ { uint32_t rows_checked; @@ -150,9 +150,7 @@ void FlowDisableFlowManagerThread(void) SCMutexLock(&tv_root_lock); /* flow manager thread(s) is/are a part of mgmt threads */ for (ThreadVars *tv = tv_root[TVT_MGMT]; tv != NULL; tv = tv->next) { - if (strncasecmp(tv->name, thread_name_flow_mgr, - strlen(thread_name_flow_mgr)) == 0) - { + if (strncasecmp(tv->name, thread_name_flow_mgr, strlen(thread_name_flow_mgr)) == 0) { TmThreadsSetFlag(tv, THV_KILL); } } @@ -171,9 +169,7 @@ void FlowDisableFlowManagerThread(void) SCMutexLock(&tv_root_lock); for (ThreadVars *tv = tv_root[TVT_MGMT]; tv != NULL; tv = tv->next) { - if (strncasecmp(tv->name, thread_name_flow_mgr, - strlen(thread_name_flow_mgr)) == 0) - { + if (strncasecmp(tv->name, thread_name_flow_mgr, strlen(thread_name_flow_mgr)) == 0) { if (!TmThreadsCheckFlag(tv, THV_RUNNING_DONE)) { SCMutexUnlock(&tv_root_lock); /* sleep outside lock */ @@ -203,7 +199,8 @@ static int FlowManagerFlowTimeout(Flow *f, SCTime_t ts, uint32_t *next_ts, const uint32_t flow_times_out_at = f->timeout_at; if (emerg) { extern FlowProtoTimeout flow_timeouts_delta[FLOW_PROTO_MAX]; - flow_times_out_at -= FlowGetFlowTimeoutDirect(flow_timeouts_delta, f->flow_state, f->protomap); + flow_times_out_at -= + FlowGetFlowTimeoutDirect(flow_timeouts_delta, f->flow_state, f->protomap); } if (*next_ts == 0 || flow_times_out_at < *next_ts) *next_ts = flow_times_out_at; @@ -242,20 +239,19 @@ static inline int FlowBypassedTimeout(Flow *f, SCTime_t ts, FlowTimeoutCounters uint64_t bytes_todst = fc->todstbytecnt; bool update = fc->BypassUpdate(f, fc->bypass_data, SCTIME_SECS(ts)); if (update) { - SCLogDebug("Updated flow: %"PRId64"", FlowGetId(f)); + SCLogDebug("Updated flow: %" PRId64 "", FlowGetId(f)); pkts_tosrc = fc->tosrcpktcnt - pkts_tosrc; bytes_tosrc = fc->tosrcbytecnt - bytes_tosrc; pkts_todst = fc->todstpktcnt - pkts_todst; bytes_todst = fc->todstbytecnt - bytes_todst; if (f->livedev) { - SC_ATOMIC_ADD(f->livedev->bypassed, - pkts_tosrc + pkts_todst); + SC_ATOMIC_ADD(f->livedev->bypassed, pkts_tosrc + pkts_todst); } counters->bypassed_pkts += pkts_tosrc + pkts_todst; counters->bypassed_bytes += bytes_tosrc + bytes_todst; return 0; } else { - SCLogDebug("No new packet, dead flow %"PRId64"", FlowGetId(f)); + SCLogDebug("No new packet, dead flow %" PRId64 "", FlowGetId(f)); if (f->livedev) { if (FLOW_IS_IPV4(f)) { LiveDevSubBypassStats(f->livedev, 1, AF_INET); @@ -413,7 +409,7 @@ static uint32_t FlowTimeoutHash(FlowManagerTimeoutThread *td, SCTime_t ts, const uint32_t rows_skipped = 0; uint32_t rows_empty = 0; -#if __WORDSIZE==64 +#if __WORDSIZE == 64 #define BITS 64 #define TYPE uint64_t #else @@ -422,11 +418,11 @@ static uint32_t FlowTimeoutHash(FlowManagerTimeoutThread *td, SCTime_t ts, const #endif const uint32_t ts_secs = SCTIME_SECS(ts); - for (uint32_t idx = hash_min; idx < hash_max; idx+=BITS) { + for (uint32_t idx = hash_min; idx < hash_max; idx += BITS) { TYPE check_bits = 0; const uint32_t check = MIN(BITS, (hash_max - idx)); for (uint32_t i = 0; i < check; i++) { - FlowBucket *fb = &flow_hash[idx+i]; + FlowBucket *fb = &flow_hash[idx + i]; check_bits |= (TYPE)(SC_ATOMIC_LOAD_EXPLICIT( fb->next_ts, SC_ATOMIC_MEMORY_ORDER_RELAXED) <= ts_secs) << (TYPE)i; @@ -435,7 +431,7 @@ static uint32_t FlowTimeoutHash(FlowManagerTimeoutThread *td, SCTime_t ts, const continue; for (uint32_t i = 0; i < check; i++) { - FlowBucket *fb = &flow_hash[idx+i]; + FlowBucket *fb = &flow_hash[idx + i]; if ((check_bits & ((TYPE)1 << (TYPE)i)) != 0 && SC_ATOMIC_GET(fb->next_ts) <= ts_secs) { FBLOCK_LOCK(fb); Flow *evicted = NULL; @@ -648,7 +644,8 @@ static void FlowCountersInit(ThreadVars *t, FlowCounters *fc) fc->flow_mgr_flows_notimeout = StatsRegisterCounter("flow.mgr.flows_notimeout", t); fc->flow_mgr_flows_timeout = StatsRegisterCounter("flow.mgr.flows_timeout", t); fc->flow_mgr_flows_aside = StatsRegisterCounter("flow.mgr.flows_evicted", t); - fc->flow_mgr_flows_aside_needs_work = StatsRegisterCounter("flow.mgr.flows_evicted_needs_work", t); + fc->flow_mgr_flows_aside_needs_work = + StatsRegisterCounter("flow.mgr.flows_evicted_needs_work", t); fc->flow_bypassed_cnt_clo = StatsRegisterCounter("flow_bypassed.closed", t); fc->flow_bypassed_pkts = StatsRegisterCounter("flow_bypassed.pkts", t); @@ -795,8 +792,7 @@ static TmEcode FlowManager(ThreadVars *th_v, void *thread_data) TmThreadsSetFlag(th_v, THV_RUNNING); - while (1) - { + while (1) { if (TmThreadsCheckFlag(th_v, THV_PAUSE)) { TmThreadsSetFlag(th_v, THV_PAUSED); TmThreadTestThreadUnPaused(th_v); @@ -938,7 +934,7 @@ static TmEcode FlowManager(ThreadVars *th_v, void *thread_data) SCCtrlMutexUnlock(&flow_manager_ctrl_mutex); } - SCLogDebug("woke up... %s", SC_ATOMIC_GET(flow_flags) & FLOW_EMERGENCY ? "emergency":""); + SCLogDebug("woke up... %s", SC_ATOMIC_GET(flow_flags) & FLOW_EMERGENCY ? "emergency" : ""); StatsSyncCountersIfSignalled(th_v); } @@ -961,10 +957,9 @@ void FlowManagerThreadSpawn(void) for (uint32_t u = 0; u < flowmgr_number; u++) { char name[TM_THREAD_NAME_MAX]; - snprintf(name, sizeof(name), "%s#%02u", thread_name_flow_mgr, u+1); + snprintf(name, sizeof(name), "%s#%02u", thread_name_flow_mgr, u + 1); - ThreadVars *tv_flowmgr = TmThreadCreateMgmtThreadByName(name, - "FlowManager", 0); + ThreadVars *tv_flowmgr = TmThreadCreateMgmtThreadByName(name, "FlowManager", 0); BUG_ON(tv_flowmgr == NULL); if (tv_flowmgr == NULL) { @@ -1058,14 +1053,13 @@ static TmEcode FlowRecycler(ThreadVars *th_v, void *thread_data) TmThreadsSetFlag(th_v, THV_RUNNING); - while (1) - { + while (1) { if (TmThreadsCheckFlag(th_v, THV_PAUSE)) { TmThreadsSetFlag(th_v, THV_PAUSED); TmThreadTestThreadUnPaused(th_v); TmThreadsUnsetFlag(th_v, THV_PAUSED); } - SC_ATOMIC_ADD(flowrec_busy,1); + SC_ATOMIC_ADD(flowrec_busy, 1); FlowQueuePrivate list = FlowQueueExtractPrivate(&flow_recycle_q); StatsAddUI64(th_v, ftd->counter_queue_avg, list.len); @@ -1095,7 +1089,7 @@ static TmEcode FlowRecycler(ThreadVars *th_v, void *thread_data) recycled_cnt += cnt; StatsAddUI64(th_v, ftd->counter_flows, cnt); } - SC_ATOMIC_SUB(flowrec_busy,1); + SC_ATOMIC_SUB(flowrec_busy, 1); if (bail) { break; @@ -1131,7 +1125,7 @@ static TmEcode FlowRecycler(ThreadVars *th_v, void *thread_data) StatsSyncCountersIfSignalled(th_v); } StatsSyncCounters(th_v); - SCLogPerf("%"PRIu64" flows processed", recycled_cnt); + SCLogPerf("%" PRIu64 " flows processed", recycled_cnt); return TM_ECODE_OK; } @@ -1163,10 +1157,9 @@ void FlowRecyclerThreadSpawn(void) for (uint32_t u = 0; u < flowrec_number; u++) { char name[TM_THREAD_NAME_MAX]; - snprintf(name, sizeof(name), "%s#%02u", thread_name_flow_rec, u+1); + snprintf(name, sizeof(name), "%s#%02u", thread_name_flow_rec, u + 1); - ThreadVars *tv_flowrec = TmThreadCreateMgmtThreadByName(name, - "FlowRecycler", 0); + ThreadVars *tv_flowrec = TmThreadCreateMgmtThreadByName(name, "FlowRecycler", 0); if (tv_flowrec == NULL) { FatalError("flow recycler thread creation failed"); @@ -1205,9 +1198,7 @@ void FlowDisableFlowRecyclerThread(void) SCMutexLock(&tv_root_lock); /* flow recycler thread(s) is/are a part of mgmt threads */ for (ThreadVars *tv = tv_root[TVT_MGMT]; tv != NULL; tv = tv->next) { - if (strncasecmp(tv->name, thread_name_flow_rec, - strlen(thread_name_flow_rec)) == 0) - { + if (strncasecmp(tv->name, thread_name_flow_rec, strlen(thread_name_flow_rec)) == 0) { TmThreadsSetFlag(tv, THV_KILL); } } @@ -1226,9 +1217,7 @@ void FlowDisableFlowRecyclerThread(void) SCMutexLock(&tv_root_lock); for (ThreadVars *tv = tv_root[TVT_MGMT]; tv != NULL; tv = tv->next) { - if (strncasecmp(tv->name, thread_name_flow_rec, - strlen(thread_name_flow_rec)) == 0) - { + if (strncasecmp(tv->name, thread_name_flow_rec, strlen(thread_name_flow_rec)) == 0) { if (!TmThreadsCheckFlag(tv, THV_RUNNING_DONE)) { SCMutexUnlock(&tv_root_lock); FlowWakeupFlowRecyclerThread(); @@ -1245,7 +1234,7 @@ void FlowDisableFlowRecyclerThread(void) return; } -void TmModuleFlowManagerRegister (void) +void TmModuleFlowManagerRegister(void) { tmm_modules[TMM_FLOWMANAGER].name = "FlowManager"; tmm_modules[TMM_FLOWMANAGER].ThreadInit = FlowManagerThreadInit; @@ -1259,7 +1248,7 @@ void TmModuleFlowManagerRegister (void) SC_ATOMIC_INITPTR(flow_timeouts); } -void TmModuleFlowRecyclerRegister (void) +void TmModuleFlowRecyclerRegister(void) { tmm_modules[TMM_FLOWRECYCLER].name = "FlowRecycler"; tmm_modules[TMM_FLOWRECYCLER].ThreadInit = FlowRecyclerThreadInit; diff --git a/src/flow-manager.h b/src/flow-manager.h index 7cdd017000aa..82c3c47b4cf6 100644 --- a/src/flow-manager.h +++ b/src/flow-manager.h @@ -34,7 +34,7 @@ void FlowManagerThreadSpawn(void); void FlowDisableFlowManagerThread(void); void FlowRecyclerThreadSpawn(void); void FlowDisableFlowRecyclerThread(void); -void TmModuleFlowManagerRegister (void); -void TmModuleFlowRecyclerRegister (void); +void TmModuleFlowManagerRegister(void); +void TmModuleFlowRecyclerRegister(void); #endif /* __FLOW_MANAGER_H__ */ diff --git a/src/flow-private.h b/src/flow-private.h index d3899f6dfbc0..760d67fac7da 100644 --- a/src/flow-private.h +++ b/src/flow-private.h @@ -34,35 +34,35 @@ /** Flow engine is in emergency mode. This means it doesn't have enough spare * flows for new flows and/or it's memcap limit it reached. In this state the * flow engine with evaluate flows with lower timeout settings. */ -#define FLOW_EMERGENCY 0x01 +#define FLOW_EMERGENCY 0x01 /* Flow Time out values */ -#define FLOW_DEFAULT_NEW_TIMEOUT 30 +#define FLOW_DEFAULT_NEW_TIMEOUT 30 #define FLOW_DEFAULT_EST_TIMEOUT 300 -#define FLOW_DEFAULT_BYPASSED_TIMEOUT 100 -#define FLOW_IPPROTO_TCP_NEW_TIMEOUT 30 -#define FLOW_IPPROTO_TCP_EST_TIMEOUT 300 -#define FLOW_IPPROTO_TCP_CLOSED_TIMEOUT 10 -#define FLOW_IPPROTO_TCP_BYPASSED_TIMEOUT 100 -#define FLOW_IPPROTO_UDP_NEW_TIMEOUT 30 -#define FLOW_IPPROTO_UDP_EST_TIMEOUT 300 -#define FLOW_IPPROTO_UDP_BYPASSED_TIMEOUT 100 -#define FLOW_IPPROTO_ICMP_NEW_TIMEOUT 30 -#define FLOW_IPPROTO_ICMP_EST_TIMEOUT 300 +#define FLOW_DEFAULT_BYPASSED_TIMEOUT 100 +#define FLOW_IPPROTO_TCP_NEW_TIMEOUT 30 +#define FLOW_IPPROTO_TCP_EST_TIMEOUT 300 +#define FLOW_IPPROTO_TCP_CLOSED_TIMEOUT 10 +#define FLOW_IPPROTO_TCP_BYPASSED_TIMEOUT 100 +#define FLOW_IPPROTO_UDP_NEW_TIMEOUT 30 +#define FLOW_IPPROTO_UDP_EST_TIMEOUT 300 +#define FLOW_IPPROTO_UDP_BYPASSED_TIMEOUT 100 +#define FLOW_IPPROTO_ICMP_NEW_TIMEOUT 30 +#define FLOW_IPPROTO_ICMP_EST_TIMEOUT 300 #define FLOW_IPPROTO_ICMP_BYPASSED_TIMEOUT 100 -#define FLOW_DEFAULT_EMERG_NEW_TIMEOUT 10 +#define FLOW_DEFAULT_EMERG_NEW_TIMEOUT 10 #define FLOW_DEFAULT_EMERG_EST_TIMEOUT 100 -#define FLOW_DEFAULT_EMERG_BYPASSED_TIMEOUT 50 -#define FLOW_IPPROTO_TCP_EMERG_NEW_TIMEOUT 10 -#define FLOW_IPPROTO_TCP_EMERG_EST_TIMEOUT 100 +#define FLOW_DEFAULT_EMERG_BYPASSED_TIMEOUT 50 +#define FLOW_IPPROTO_TCP_EMERG_NEW_TIMEOUT 10 +#define FLOW_IPPROTO_TCP_EMERG_EST_TIMEOUT 100 #define FLOW_IPPROTO_TCP_EMERG_CLOSED_TIMEOUT 5 -#define FLOW_IPPROTO_UDP_EMERG_NEW_TIMEOUT 10 -#define FLOW_IPPROTO_UDP_EMERG_EST_TIMEOUT 100 -#define FLOW_IPPROTO_ICMP_EMERG_NEW_TIMEOUT 10 -#define FLOW_IPPROTO_ICMP_EMERG_EST_TIMEOUT 100 +#define FLOW_IPPROTO_UDP_EMERG_NEW_TIMEOUT 10 +#define FLOW_IPPROTO_UDP_EMERG_EST_TIMEOUT 100 +#define FLOW_IPPROTO_ICMP_EMERG_NEW_TIMEOUT 10 +#define FLOW_IPPROTO_ICMP_EMERG_EST_TIMEOUT 100 -#define FLOW_BYPASSED_TIMEOUT 100 +#define FLOW_BYPASSED_TIMEOUT 100 enum { FLOW_PROTO_TCP = 0, @@ -87,7 +87,7 @@ extern FlowProtoTimeout flow_timeouts_emerg[FLOW_PROTO_MAX]; extern FlowProtoFreeFunc flow_freefuncs[FLOW_PROTO_MAX]; /** spare/unused/prealloced flows live here */ -//extern FlowQueue flow_spare_q; +// extern FlowQueue flow_spare_q; /** queue to pass flows to cleanup/log thread(s) */ extern FlowQueue flow_recycle_q; @@ -102,8 +102,7 @@ typedef FlowProtoTimeout *FlowProtoTimeoutPtr; SC_ATOMIC_EXTERN(FlowProtoTimeoutPtr, flow_timeouts); static inline uint32_t FlowGetFlowTimeoutDirect( - const FlowProtoTimeoutPtr flow_timeouts, - const enum FlowState state, const uint8_t protomap) + const FlowProtoTimeoutPtr flow_timeouts, const enum FlowState state, const uint8_t protomap) { uint32_t timeout; switch (state) { diff --git a/src/flow-queue.c b/src/flow-queue.c index 1d4653b3bf30..b683916d5523 100644 --- a/src/flow-queue.c +++ b/src/flow-queue.c @@ -43,7 +43,7 @@ FlowQueue *FlowQueueNew(void) return q; } -FlowQueue *FlowQueueInit (FlowQueue *q) +FlowQueue *FlowQueueInit(FlowQueue *q) { if (q != NULL) { memset(q, 0, sizeof(FlowQueue)); @@ -57,7 +57,7 @@ FlowQueue *FlowQueueInit (FlowQueue *q) * * \param q the flow queue to destroy */ -void FlowQueueDestroy (FlowQueue *q) +void FlowQueueDestroy(FlowQueue *q) { FQLOCK_DESTROY(q); } @@ -170,7 +170,7 @@ Flow *FlowQueuePrivateGetFromTop(FlowQueuePrivate *fqc) * \param q queue * \param f flow */ -void FlowEnqueue (FlowQueue *q, Flow *f) +void FlowEnqueue(FlowQueue *q, Flow *f) { #ifdef DEBUG BUG_ON(q == NULL || f == NULL); @@ -188,7 +188,7 @@ void FlowEnqueue (FlowQueue *q, Flow *f) * * \retval f flow or NULL if empty list. */ -Flow *FlowDequeue (FlowQueue *q) +Flow *FlowDequeue(FlowQueue *q) { FQLOCK_LOCK(q); Flow *f = FlowQueuePrivateGetFromTop(&q->priv); diff --git a/src/flow-queue.h b/src/flow-queue.h index 0523546ce8a9..d2ee9c1ff436 100644 --- a/src/flow-queue.h +++ b/src/flow-queue.h @@ -32,29 +32,27 @@ #define FQLOCK_MUTEX #ifdef FQLOCK_SPIN - #ifdef FQLOCK_MUTEX - #error Cannot enable both FQLOCK_SPIN and FQLOCK_MUTEX - #endif +#ifdef FQLOCK_MUTEX +#error Cannot enable both FQLOCK_SPIN and FQLOCK_MUTEX +#endif #endif -typedef struct FlowQueuePrivate_ -{ +typedef struct FlowQueuePrivate_ { Flow *top; Flow *bot; uint32_t len; } FlowQueuePrivate; /* Define a queue for storing flows */ -typedef struct FlowQueue_ -{ +typedef struct FlowQueue_ { FlowQueuePrivate priv; - SC_ATOMIC_DECLARE(bool,non_empty); + SC_ATOMIC_DECLARE(bool, non_empty); #ifdef FQLOCK_MUTEX SCMutex m; #elif defined FQLOCK_SPIN SCSpinlock s; #else - #error Enable FQLOCK_SPIN or FQLOCK_MUTEX +#error Enable FQLOCK_SPIN or FQLOCK_MUTEX #endif } FlowQueue; #define qtop priv.top @@ -62,28 +60,28 @@ typedef struct FlowQueue_ #define qlen priv.len #ifdef FQLOCK_SPIN - #define FQLOCK_INIT(q) SCSpinInit(&(q)->s, 0) - #define FQLOCK_DESTROY(q) SCSpinDestroy(&(q)->s) - #define FQLOCK_LOCK(q) SCSpinLock(&(q)->s) - #define FQLOCK_TRYLOCK(q) SCSpinTrylock(&(q)->s) - #define FQLOCK_UNLOCK(q) SCSpinUnlock(&(q)->s) +#define FQLOCK_INIT(q) SCSpinInit(&(q)->s, 0) +#define FQLOCK_DESTROY(q) SCSpinDestroy(&(q)->s) +#define FQLOCK_LOCK(q) SCSpinLock(&(q)->s) +#define FQLOCK_TRYLOCK(q) SCSpinTrylock(&(q)->s) +#define FQLOCK_UNLOCK(q) SCSpinUnlock(&(q)->s) #elif defined FQLOCK_MUTEX - #define FQLOCK_INIT(q) SCMutexInit(&(q)->m, NULL) - #define FQLOCK_DESTROY(q) SCMutexDestroy(&(q)->m) - #define FQLOCK_LOCK(q) SCMutexLock(&(q)->m) - #define FQLOCK_TRYLOCK(q) SCMutexTrylock(&(q)->m) - #define FQLOCK_UNLOCK(q) SCMutexUnlock(&(q)->m) +#define FQLOCK_INIT(q) SCMutexInit(&(q)->m, NULL) +#define FQLOCK_DESTROY(q) SCMutexDestroy(&(q)->m) +#define FQLOCK_LOCK(q) SCMutexLock(&(q)->m) +#define FQLOCK_TRYLOCK(q) SCMutexTrylock(&(q)->m) +#define FQLOCK_UNLOCK(q) SCMutexUnlock(&(q)->m) #else - #error Enable FQLOCK_SPIN or FQLOCK_MUTEX +#error Enable FQLOCK_SPIN or FQLOCK_MUTEX #endif /* prototypes */ FlowQueue *FlowQueueNew(void); FlowQueue *FlowQueueInit(FlowQueue *); -void FlowQueueDestroy (FlowQueue *); +void FlowQueueDestroy(FlowQueue *); -void FlowEnqueue (FlowQueue *, Flow *); -Flow *FlowDequeue (FlowQueue *); +void FlowEnqueue(FlowQueue *, Flow *); +Flow *FlowDequeue(FlowQueue *); void FlowQueueRemove(FlowQueue *fq, Flow *f); void FlowQueuePrivateAppendFlow(FlowQueuePrivate *fqc, Flow *f); @@ -95,4 +93,3 @@ FlowQueuePrivate FlowQueueExtractPrivate(FlowQueue *fq); Flow *FlowQueuePrivateGetFromTop(FlowQueuePrivate *fqp); #endif /* __FLOW_QUEUE_H__ */ - diff --git a/src/flow-spare-pool.c b/src/flow-spare-pool.c index e47b983b8e04..0fbc70ed2b79 100644 --- a/src/flow-spare-pool.c +++ b/src/flow-spare-pool.c @@ -65,8 +65,7 @@ static bool FlowSparePoolUpdateBlock(FlowSparePool *p) { DEBUG_VALIDATE_BUG_ON(p == NULL); - for (uint32_t i = p->queue.len; i < flow_spare_pool_block_size; i++) - { + for (uint32_t i = p->queue.len; i < flow_spare_pool_block_size; i++) { Flow *f = FlowAlloc(); if (f == NULL) return false; @@ -84,12 +83,11 @@ static void Validate(FlowSparePool *top, const uint32_t target) } assert(top->queue.len >= 1); - //if (top->next != NULL) + // if (top->next != NULL) // assert(top->next->queue.len == flow_spare_pool_block_size); uint32_t cnt = 0; - for (FlowSparePool *p = top; p != NULL; p = p->next) - { + for (FlowSparePool *p = top; p != NULL; p = p->next) { assert(p->queue.len); cnt += p->queue.len; } @@ -195,7 +193,7 @@ FlowQueuePrivate FlowSpareGetFromPool(void) FlowQueuePrivate ret = p->queue; SCFree(p); return ret; - /* next should always be full if it exists */ + /* next should always be full if it exists */ } else if (flow_spare_pool->next != NULL) { FlowSparePool *p = flow_spare_pool->next; flow_spare_pool->next = p->next; @@ -293,7 +291,7 @@ void FlowSparePoolUpdate(uint32_t size) void FlowSparePoolInit(void) { SCMutexLock(&flow_spare_pool_m); - for (uint32_t cnt = 0; cnt < flow_config.prealloc; ) { + for (uint32_t cnt = 0; cnt < flow_config.prealloc;) { FlowSparePool *p = FlowSpareGetPool(); if (p == NULL) { FatalError("failed to initialize flow pool"); @@ -312,7 +310,7 @@ void FlowSparePoolInit(void) void FlowSparePoolDestroy(void) { SCMutexLock(&flow_spare_pool_m); - for (FlowSparePool *p = flow_spare_pool; p != NULL; ) { + for (FlowSparePool *p = flow_spare_pool; p != NULL;) { uint32_t cnt = 0; Flow *f; while ((f = FlowQueuePrivateGetFromTop(&p->queue))) { diff --git a/src/flow-storage.c b/src/flow-storage.c index 53b67ba63048..99d070f78df0 100644 --- a/src/flow-storage.c +++ b/src/flow-storage.c @@ -200,7 +200,6 @@ static int FlowStorageTest02(void) goto error; } - FlowClearMemory(f, 0); FlowFree(f); FlowShutdown(); diff --git a/src/flow-timeout.c b/src/flow-timeout.c index 90a97fa66688..342c76c112ae 100644 --- a/src/flow-timeout.c +++ b/src/flow-timeout.c @@ -126,7 +126,7 @@ static inline Packet *FlowForceReassemblyPseudoPacketSetup( /* Check if we have enough room in direct data. We need ipv4 hdr + tcp hdr. * Force an allocation if it is not the case. */ - if (GET_PKT_DIRECT_MAX_SIZE(p) < 40) { + if (GET_PKT_DIRECT_MAX_SIZE(p) < 40) { if (PacketCallocExtPkt(p, 40) == -1) { goto error; } @@ -141,7 +141,7 @@ static inline Packet *FlowForceReassemblyPseudoPacketSetup( p->ip4h->ip_off = 0; p->ip4h->ip_ttl = 64; p->ip4h->ip_proto = IPPROTO_TCP; - //p->ip4h->ip_csum = + // p->ip4h->ip_csum = if (direction == 0) { p->ip4h->s_ip_src.s_addr = f->src.addr_data32[0]; p->ip4h->s_ip_dst.s_addr = f->dst.addr_data32[0]; @@ -171,7 +171,7 @@ static inline Packet *FlowForceReassemblyPseudoPacketSetup( /* Check if we have enough room in direct data. We need ipv6 hdr + tcp hdr. * Force an allocation if it is not the case. */ - if (GET_PKT_DIRECT_MAX_SIZE(p) < 60) { + if (GET_PKT_DIRECT_MAX_SIZE(p) < 60) { if (PacketCallocExtPkt(p, 60) == -1) { goto error; } @@ -233,15 +233,12 @@ static inline Packet *FlowForceReassemblyPseudoPacketSetup( } if (FLOW_IS_IPV4(f)) { - p->tcph->th_sum = TCPChecksum(p->ip4h->s_ip_addrs, - (uint16_t *)p->tcph, 20, 0); + p->tcph->th_sum = TCPChecksum(p->ip4h->s_ip_addrs, (uint16_t *)p->tcph, 20, 0); /* calc ipv4 csum as we may log it and barnyard might reject * a wrong checksum */ - p->ip4h->ip_csum = IPV4Checksum((uint16_t *)p->ip4h, - IPV4_GET_RAW_HLEN(p->ip4h), 0); + p->ip4h->ip_csum = IPV4Checksum((uint16_t *)p->ip4h, IPV4_GET_RAW_HLEN(p->ip4h), 0); } else if (FLOW_IS_IPV6(f)) { - p->tcph->th_sum = TCPChecksum(p->ip6h->s_ip6_addrs, - (uint16_t *)p->tcph, 20, 0); + p->tcph->th_sum = TCPChecksum(p->ip6h->s_ip6_addrs, (uint16_t *)p->tcph, 20, 0); } p->ts = TimeGet(); @@ -297,8 +294,7 @@ int FlowForceReassemblyNeedReassembly(Flow *f) /* if state is not fully closed we assume that we haven't fully * inspected the app layer state yet */ - if (ssn->state >= TCP_ESTABLISHED && ssn->state != TCP_CLOSED) - { + if (ssn->state >= TCP_ESTABLISHED && ssn->state != TCP_CLOSED) { client = STREAM_HAS_UNPROCESSED_SEGMENTS_NEED_ONLY_DETECTION; server = STREAM_HAS_UNPROCESSED_SEGMENTS_NEED_ONLY_DETECTION; } @@ -307,19 +303,17 @@ int FlowForceReassemblyNeedReassembly(Flow *f) if (f->alproto != ALPROTO_UNKNOWN && f->alstate != NULL) { const uint64_t total_txs = AppLayerParserGetTxCnt(f, f->alstate); - if (AppLayerParserGetTransactionActive(f, f->alparser, STREAM_TOCLIENT) < total_txs) - { + if (AppLayerParserGetTransactionActive(f, f->alparser, STREAM_TOCLIENT) < total_txs) { server = STREAM_HAS_UNPROCESSED_SEGMENTS_NEED_ONLY_DETECTION; } - if (AppLayerParserGetTransactionActive(f, f->alparser, STREAM_TOSERVER) < total_txs) - { + if (AppLayerParserGetTransactionActive(f, f->alparser, STREAM_TOSERVER) < total_txs) { client = STREAM_HAS_UNPROCESSED_SEGMENTS_NEED_ONLY_DETECTION; } } /* nothing to do */ if (client == STREAM_HAS_UNPROCESSED_SEGMENTS_NONE && - server == STREAM_HAS_UNPROCESSED_SEGMENTS_NONE) { + server == STREAM_HAS_UNPROCESSED_SEGMENTS_NONE) { SCReturnInt(0); } diff --git a/src/flow-util.c b/src/flow-util.c index 672abc23d2ba..fceb25a04bd2 100644 --- a/src/flow-util.c +++ b/src/flow-util.c @@ -60,7 +60,7 @@ Flow *FlowAlloc(void) return NULL; } - (void) SC_ATOMIC_ADD(flow_memuse, size); + (void)SC_ATOMIC_ADD(flow_memuse, size); f = SCCalloc(1, size); if (unlikely(f == NULL)) { @@ -73,7 +73,6 @@ Flow *FlowAlloc(void) return f; } - /** * \brief cleanup & free the memory of a flow * @@ -85,7 +84,7 @@ void FlowFree(Flow *f) SCFree(f); size_t size = sizeof(Flow) + FlowStorageSize(); - (void) SC_ATOMIC_SUB(flow_memuse, size); + (void)SC_ATOMIC_SUB(flow_memuse, size); } /** @@ -169,11 +168,11 @@ void FlowInit(Flow *f, const Packet *p) } if (p->tcph != NULL) { /* XXX MACRO */ - SET_TCP_SRC_PORT(p,&f->sp); - SET_TCP_DST_PORT(p,&f->dp); + SET_TCP_SRC_PORT(p, &f->sp); + SET_TCP_DST_PORT(p, &f->dp); } else if (p->udph != NULL) { /* XXX MACRO */ - SET_UDP_SRC_PORT(p,&f->sp); - SET_UDP_DST_PORT(p,&f->dp); + SET_UDP_SRC_PORT(p, &f->sp); + SET_UDP_DST_PORT(p, &f->dp); } else if (p->icmpv4h != NULL) { f->icmp_s.type = p->icmp_s.type; f->icmp_s.code = p->icmp_s.code; @@ -183,8 +182,8 @@ void FlowInit(Flow *f, const Packet *p) f->icmp_s.code = p->icmp_s.code; FlowSetICMPv6CounterPart(f); } else if (p->sctph != NULL) { /* XXX MACRO */ - SET_SCTP_SRC_PORT(p,&f->sp); - SET_SCTP_DST_PORT(p,&f->dp); + SET_SCTP_SRC_PORT(p, &f->sp); + SET_SCTP_DST_PORT(p, &f->dp); } else if (p->esph != NULL) { f->esp.spi = ESP_GET_SPI(p); } else { @@ -216,7 +215,7 @@ FlowStorageId GetFlowBypassInfoID(void) static void FlowBypassFree(void *x) { - FlowBypassInfo *fb = (FlowBypassInfo *) x; + FlowBypassInfo *fb = (FlowBypassInfo *)x; if (fb == NULL) return; @@ -229,8 +228,7 @@ static void FlowBypassFree(void *x) void RegisterFlowBypassInfo(void) { - g_bypass_info_id = FlowStorageRegister("bypass_counters", sizeof(void *), - NULL, FlowBypassFree); + g_bypass_info_id = FlowStorageRegister("bypass_counters", sizeof(void *), NULL, FlowBypassFree); } void FlowEndCountersRegister(ThreadVars *t, FlowEndCounters *fec) diff --git a/src/flow-var.c b/src/flow-var.c index a92358f27144..5f4e0600592a 100644 --- a/src/flow-var.c +++ b/src/flow-var.c @@ -58,7 +58,7 @@ FlowVar *FlowVarGetByKey(Flow *f, const uint8_t *key, uint16_t keylen) GenericVar *gv = f->flowvar; - for ( ; gv != NULL; gv = gv->next) { + for (; gv != NULL; gv = gv->next) { if (gv->type == DETECT_FLOWVAR && gv->idx == 0) { FlowVar *fv = (FlowVar *)gv; @@ -82,7 +82,7 @@ FlowVar *FlowVarGet(Flow *f, uint32_t idx) GenericVar *gv = f->flowvar; - for ( ; gv != NULL; gv = gv->next) { + for (; gv != NULL; gv = gv->next) { if (gv->type == DETECT_FLOWVAR && gv->idx == idx) return (FlowVar *)gv; } @@ -143,7 +143,7 @@ void FlowVarAddIntNoLock(Flow *f, uint32_t idx, uint32_t value) fv->type = DETECT_FLOWVAR; fv->datatype = FLOWVAR_TYPE_INT; fv->idx = idx; - fv->data.fv_int.value= value; + fv->data.fv_int.value = value; fv->next = NULL; GenericVarAppend(&f->flowvar, (GenericVar *)fv); @@ -201,4 +201,3 @@ void FlowVarPrint(GenericVar *gv) } FlowVarPrint(gv->next); } - diff --git a/src/flow-var.h b/src/flow-var.h index f0bcf3c0c3f6..15f64e757441 100644 --- a/src/flow-var.h +++ b/src/flow-var.h @@ -46,13 +46,13 @@ typedef struct FlowVarTypeInt_ { /** Generic Flowvar Structure */ typedef struct FlowVar_ { - uint8_t type; /* type, DETECT_FLOWVAR in this case */ + uint8_t type; /* type, DETECT_FLOWVAR in this case */ uint8_t datatype; uint16_t keylen; - uint32_t idx; /* name idx */ - GenericVar *next; /* right now just implement this as a list, - * in the long run we have think of something - * faster. */ + uint32_t idx; /* name idx */ + GenericVar *next; /* right now just implement this as a list, + * in the long run we have think of something + * faster. */ union { FlowVarTypeStr fv_str; FlowVarTypeInt fv_int; @@ -73,4 +73,3 @@ void FlowVarFree(FlowVar *); void FlowVarPrint(GenericVar *); #endif /* __FLOW_VAR_H__ */ - diff --git a/src/flow-worker.c b/src/flow-worker.c index 6980570d3ce1..5a9fc7ad362b 100644 --- a/src/flow-worker.c +++ b/src/flow-worker.c @@ -73,7 +73,7 @@ typedef struct FlowWorkerThreadData_ { SC_ATOMIC_DECLARE(DetectEngineThreadCtxPtr, detect_thread); - void *output_thread; /* Output thread data. */ + void *output_thread; /* Output thread data. */ void *output_thread_flow; /* Output thread data. */ uint16_t local_bypass_pkts; @@ -162,7 +162,7 @@ static void CheckWorkQueue(ThreadVars *tv, FlowWorkerThreadData *fw, FlowTimeout Flow *f; while ((f = FlowQueuePrivateGetFromTop(fq)) != NULL) { FLOWLOCK_WRLOCK(f); - f->flow_end_flags |= FLOW_END_FLAG_TIMEOUT; //TODO emerg + f->flow_end_flags |= FLOW_END_FLAG_TIMEOUT; // TODO emerg if (f->proto == IPPROTO_TCP) { if (!(f->flags & (FLOW_TIMEOUT_REASSEMBLY_DONE | FLOW_ACTION_DROP)) && @@ -188,7 +188,7 @@ static void CheckWorkQueue(ThreadVars *tv, FlowWorkerThreadData *fw, FlowTimeout } StatsDecr(tv, fw->dtv->counter_flow_active); - FlowClearMemory (f, f->protomap); + FlowClearMemory(f, f->protomap); FLOWLOCK_UNLOCK(f); if (fw->fls.spare_queue.len >= (flow_spare_pool_block_size * 2)) { @@ -341,18 +341,18 @@ static TmEcode FlowWorkerThreadDeinit(ThreadVars *tv, void *data) } TmEcode Detect(ThreadVars *tv, Packet *p, void *data); -TmEcode StreamTcp (ThreadVars *, Packet *, void *, PacketQueueNoLock *pq); +TmEcode StreamTcp(ThreadVars *, Packet *, void *, PacketQueueNoLock *pq); -static inline void UpdateCounters(ThreadVars *tv, - FlowWorkerThreadData *fw, const FlowTimeoutCounters *counters) +static inline void UpdateCounters( + ThreadVars *tv, FlowWorkerThreadData *fw, const FlowTimeoutCounters *counters) { if (counters->flows_aside_needs_work) { - StatsAddUI64(tv, fw->cnt.flows_aside_needs_work, - (uint64_t)counters->flows_aside_needs_work); + StatsAddUI64( + tv, fw->cnt.flows_aside_needs_work, (uint64_t)counters->flows_aside_needs_work); } if (counters->flows_aside_pkt_inject) { - StatsAddUI64(tv, fw->cnt.flows_aside_pkt_inject, - (uint64_t)counters->flows_aside_pkt_inject); + StatsAddUI64( + tv, fw->cnt.flows_aside_pkt_inject, (uint64_t)counters->flows_aside_pkt_inject); } } @@ -378,10 +378,10 @@ static inline void FlowWorkerStreamTCPUpdate(ThreadVars *tv, FlowWorkerThreadDat } /* Packets here can safely access p->flow as it's locked */ - SCLogDebug("packet %"PRIu64": extra packets %u", p->pcap_cnt, fw->pq.len); + SCLogDebug("packet %" PRIu64 ": extra packets %u", p->pcap_cnt, fw->pq.len); Packet *x; while ((x = PacketDequeueNoLock(&fw->pq))) { - SCLogDebug("packet %"PRIu64" extra packet %p", p->pcap_cnt, x); + SCLogDebug("packet %" PRIu64 " extra packet %p", p->pcap_cnt, x); if (detect_thread != NULL) { FLOWWORKER_PROFILING_START(x, PROFILE_FLOWWORKER_DETECT); @@ -412,12 +412,13 @@ static inline void FlowWorkerStreamTCPUpdate(ThreadVars *tv, FlowWorkerThreadDat } } -static void FlowWorkerFlowTimeout(ThreadVars *tv, Packet *p, FlowWorkerThreadData *fw, - void *detect_thread) +static void FlowWorkerFlowTimeout( + ThreadVars *tv, Packet *p, FlowWorkerThreadData *fw, void *detect_thread) { DEBUG_VALIDATE_BUG_ON(p->pkt_src != PKT_SRC_FFR); - SCLogDebug("packet %"PRIu64" is TCP. Direction %s", p->pcap_cnt, PKT_IS_TOSERVER(p) ? "TOSERVER" : "TOCLIENT"); + SCLogDebug("packet %" PRIu64 " is TCP. Direction %s", p->pcap_cnt, + PKT_IS_TOSERVER(p) ? "TOSERVER" : "TOCLIENT"); DEBUG_VALIDATE_BUG_ON(!(p->flow && PKT_IS_TCP(p))); DEBUG_ASSERT_FLOW_LOCKED(p->flow); @@ -427,7 +428,7 @@ static void FlowWorkerFlowTimeout(ThreadVars *tv, Packet *p, FlowWorkerThreadDat PacketUpdateEngineEventCounters(tv, fw->dtv, p); /* handle Detect */ - SCLogDebug("packet %"PRIu64" calling Detect", p->pcap_cnt); + SCLogDebug("packet %" PRIu64 " calling Detect", p->pcap_cnt); if (detect_thread != NULL) { FLOWWORKER_PROFILING_START(p, PROFILE_FLOWWORKER_DETECT); Detect(tv, p, detect_thread); @@ -441,8 +442,8 @@ static void FlowWorkerFlowTimeout(ThreadVars *tv, Packet *p, FlowWorkerThreadDat /* Release tcp segments. Done here after alerting can use them. */ FLOWWORKER_PROFILING_START(p, PROFILE_FLOWWORKER_TCPPRUNE); - StreamTcpPruneSession(p->flow, p->flowflags & FLOW_PKT_TOSERVER ? - STREAM_TOSERVER : STREAM_TOCLIENT); + StreamTcpPruneSession( + p->flow, p->flowflags & FLOW_PKT_TOSERVER ? STREAM_TOSERVER : STREAM_TOCLIENT); FLOWWORKER_PROFILING_END(p, PROFILE_FLOWWORKER_TCPPRUNE); /* run tx cleanup last */ @@ -485,7 +486,10 @@ static inline void FlowWorkerProcessLocalFlows(ThreadVars *tv, FlowWorkerThreadD FLOWWORKER_PROFILING_START(p, PROFILE_FLOWWORKER_FLOW_EVICTED); if (fw->fls.work_queue.len) { - FlowTimeoutCounters counters = { 0, 0, }; + FlowTimeoutCounters counters = { + 0, + 0, + }; CheckWorkQueue(tv, fw, &counters, &fw->fls.work_queue, max_work); UpdateCounters(tv, fw, &counters); } @@ -538,7 +542,7 @@ static TmEcode FlowWorker(ThreadVars *tv, Packet *p, void *data) DEBUG_VALIDATE_BUG_ON(p == NULL); DEBUG_VALIDATE_BUG_ON(tv->flow_queue == NULL); - SCLogDebug("packet %"PRIu64, p->pcap_cnt); + SCLogDebug("packet %" PRIu64, p->pcap_cnt); /* update time */ if (!(PKT_IS_PSEUDOPKT(p))) { @@ -560,14 +564,14 @@ static TmEcode FlowWorker(ThreadVars *tv, Packet *p, void *data) FLOWWORKER_PROFILING_END(p, PROFILE_FLOWWORKER_FLOW); - /* if PKT_WANTS_FLOW is not set, but PKT_HAS_FLOW is, then this is a - * pseudo packet created by the flow manager. */ + /* if PKT_WANTS_FLOW is not set, but PKT_HAS_FLOW is, then this is a + * pseudo packet created by the flow manager. */ } else if (p->flags & PKT_HAS_FLOW) { FLOWLOCK_WRLOCK(p->flow); DEBUG_VALIDATE_BUG_ON(p->pkt_src != PKT_SRC_FFR); } - SCLogDebug("packet %"PRIu64" has flow? %s", p->pcap_cnt, p->flow ? "yes" : "no"); + SCLogDebug("packet %" PRIu64 " has flow? %s", p->pcap_cnt, p->flow ? "yes" : "no"); /* handle TCP and app layer */ if (p->flow) { @@ -600,7 +604,7 @@ static TmEcode FlowWorker(ThreadVars *tv, Packet *p, void *data) /* handle Detect */ DEBUG_ASSERT_FLOW_LOCKED(p->flow); - SCLogDebug("packet %"PRIu64" calling Detect", p->pcap_cnt); + SCLogDebug("packet %" PRIu64 " calling Detect", p->pcap_cnt); if (detect_thread != NULL) { FLOWWORKER_PROFILING_START(p, PROFILE_FLOWWORKER_DETECT); Detect(tv, p, detect_thread); @@ -622,8 +626,8 @@ static TmEcode FlowWorker(ThreadVars *tv, Packet *p, void *data) } else if (p->proto == IPPROTO_TCP && p->flow->protoctx) { FramesPrune(p->flow, p); FLOWWORKER_PROFILING_START(p, PROFILE_FLOWWORKER_TCPPRUNE); - StreamTcpPruneSession(p->flow, p->flowflags & FLOW_PKT_TOSERVER ? - STREAM_TOSERVER : STREAM_TOCLIENT); + StreamTcpPruneSession( + p->flow, p->flowflags & FLOW_PKT_TOSERVER ? STREAM_TOSERVER : STREAM_TOCLIENT); FLOWWORKER_PROFILING_END(p, PROFILE_FLOWWORKER_TCPPRUNE); } else if (p->proto == IPPROTO_UDP) { FramesPrune(p->flow, p); @@ -731,7 +735,7 @@ static bool FlowWorkerIsBusy(ThreadVars *tv, void *flow_worker) return false; } -void TmModuleFlowWorkerRegister (void) +void TmModuleFlowWorkerRegister(void) { tmm_modules[TMM_FLOWWORKER].name = "FlowWorker"; tmm_modules[TMM_FLOWWORKER].ThreadInit = FlowWorkerThreadInit; @@ -740,5 +744,5 @@ void TmModuleFlowWorkerRegister (void) tmm_modules[TMM_FLOWWORKER].ThreadDeinit = FlowWorkerThreadDeinit; tmm_modules[TMM_FLOWWORKER].ThreadExitPrintStats = FlowWorkerExitPrintStats; tmm_modules[TMM_FLOWWORKER].cap_flags = 0; - tmm_modules[TMM_FLOWWORKER].flags = TM_FLAG_STREAM_TM|TM_FLAG_DETECT_TM; + tmm_modules[TMM_FLOWWORKER].flags = TM_FLAG_STREAM_TM | TM_FLAG_DETECT_TM; } diff --git a/src/flow-worker.h b/src/flow-worker.h index 9187602dec2c..c233a8cb6912 100644 --- a/src/flow-worker.h +++ b/src/flow-worker.h @@ -33,6 +33,6 @@ const char *ProfileFlowWorkerIdToString(enum ProfileFlowWorkerId fwi); void FlowWorkerReplaceDetectCtx(void *flow_worker, void *detect_ctx); void *FlowWorkerGetDetectCtxPtr(void *flow_worker); -void TmModuleFlowWorkerRegister (void); +void TmModuleFlowWorkerRegister(void); #endif /* __FLOW_WORKER_H__ */ diff --git a/src/flow.c b/src/flow.c index 9783b7883b0b..2f018e23f3d7 100644 --- a/src/flow.c +++ b/src/flow.c @@ -73,11 +73,11 @@ #define FLOW_DEFAULT_EMERGENCY_RECOVERY 30 //#define FLOW_DEFAULT_HASHSIZE 262144 -#define FLOW_DEFAULT_HASHSIZE 65536 +#define FLOW_DEFAULT_HASHSIZE 65536 //#define FLOW_DEFAULT_MEMCAP 128 * 1024 * 1024 /* 128 MB */ -#define FLOW_DEFAULT_MEMCAP (32 * 1024 * 1024) /* 32 MB */ +#define FLOW_DEFAULT_MEMCAP (32 * 1024 * 1024) /* 32 MB */ -#define FLOW_DEFAULT_PREALLOC 10000 +#define FLOW_DEFAULT_PREALLOC 10000 SC_ATOMIC_DECLARE(FlowProtoTimeoutPtr, flow_timeouts); @@ -155,14 +155,13 @@ void FlowCleanupAppLayer(Flow *f) } /** \brief Set the IPOnly scanned flag for 'direction'. - * - * \param f Flow to set the flag in - * \param direction direction to set the flag in - */ + * + * \param f Flow to set the flag in + * \param direction direction to set the flag in + */ void FlowSetIPOnlyFlag(Flow *f, int direction) { - direction ? (f->flags |= FLOW_TOSERVER_IPONLY_SET) : - (f->flags |= FLOW_TOCLIENT_IPONLY_SET); + direction ? (f->flags |= FLOW_TOSERVER_IPONLY_SET) : (f->flags |= FLOW_TOCLIENT_IPONLY_SET); return; } @@ -286,7 +285,7 @@ void FlowSwap(Flow *f) f->flags |= FLOW_DIR_REVERSED; SWAP_VARS(uint32_t, f->probing_parser_toserver_alproto_masks, - f->probing_parser_toclient_alproto_masks); + f->probing_parser_toclient_alproto_masks); FlowSwapFlags(f); FlowSwapFileFlags(f); @@ -317,23 +316,23 @@ int FlowGetPacketDirection(const Flow *f, const Packet *p) const int reverse = (f->flags & FLOW_DIR_REVERSED) != 0; if (p->proto == IPPROTO_TCP || p->proto == IPPROTO_UDP || p->proto == IPPROTO_SCTP) { - if (!(CMP_PORT(p->sp,p->dp))) { + if (!(CMP_PORT(p->sp, p->dp))) { /* update flags and counters */ - if (CMP_PORT(f->sp,p->sp)) { + if (CMP_PORT(f->sp, p->sp)) { return TOSERVER ^ reverse; } else { return TOCLIENT ^ reverse; } } else { - if (CMP_ADDR(&f->src,&p->src)) { + if (CMP_ADDR(&f->src, &p->src)) { return TOSERVER ^ reverse; } else { return TOCLIENT ^ reverse; } } } else if (p->proto == IPPROTO_ICMP || p->proto == IPPROTO_ICMPV6) { - if (CMP_ADDR(&f->src,&p->src)) { - return TOSERVER ^ reverse; + if (CMP_ADDR(&f->src, &p->src)) { + return TOSERVER ^ reverse; } else { return TOCLIENT ^ reverse; } @@ -382,20 +381,18 @@ static inline void FlowUpdateTtlTC(Flow *f, Packet *p, uint8_t ttl) f->max_ttl_toclient = MAX(f->max_ttl_toclient, ttl); } -static inline void FlowUpdateEthernet(ThreadVars *tv, DecodeThreadVars *dtv, - Flow *f, EthernetHdr *ethh, bool toserver) +static inline void FlowUpdateEthernet( + ThreadVars *tv, DecodeThreadVars *dtv, Flow *f, EthernetHdr *ethh, bool toserver) { if (ethh && MacSetFlowStorageEnabled()) { MacSet *ms = FlowGetStorageById(f, MacSetGetFlowStorageID()); if (ms != NULL) { if (toserver) { MacSetAddWithCtr(ms, ethh->eth_src, ethh->eth_dst, tv, - dtv->counter_max_mac_addrs_src, - dtv->counter_max_mac_addrs_dst); + dtv->counter_max_mac_addrs_src, dtv->counter_max_mac_addrs_dst); } else { MacSetAddWithCtr(ms, ethh->eth_dst, ethh->eth_src, tv, - dtv->counter_max_mac_addrs_dst, - dtv->counter_max_mac_addrs_src); + dtv->counter_max_mac_addrs_dst, dtv->counter_max_mac_addrs_src); } } } @@ -412,7 +409,7 @@ static inline void FlowUpdateEthernet(ThreadVars *tv, DecodeThreadVars *dtv, */ void FlowHandlePacketUpdate(Flow *f, Packet *p, ThreadVars *tv, DecodeThreadVars *dtv) { - SCLogDebug("packet %"PRIu64" -- flow %p", p->pcap_cnt, f); + SCLogDebug("packet %" PRIu64 " -- flow %p", p->pcap_cnt, f); const int pkt_dir = FlowGetPacketDirection(f, p); #ifdef CAPTURE_OFFLOAD @@ -500,8 +497,8 @@ void FlowHandlePacketUpdate(Flow *f, Packet *p, ThreadVars *tv, DecodeThreadVars if (ssn != NULL && ssn->state >= TCP_ESTABLISHED) { p->flowflags |= FLOW_PKT_ESTABLISHED; } - } else if ((f->flags & (FLOW_TO_DST_SEEN|FLOW_TO_SRC_SEEN)) == - (FLOW_TO_DST_SEEN|FLOW_TO_SRC_SEEN)) { + } else if ((f->flags & (FLOW_TO_DST_SEEN | FLOW_TO_SRC_SEEN)) == + (FLOW_TO_DST_SEEN | FLOW_TO_SRC_SEEN)) { SCLogDebug("pkt %p FLOW_PKT_ESTABLISHED", p); p->flowflags |= FLOW_PKT_ESTABLISHED; @@ -550,7 +547,7 @@ void FlowInitConfig(bool quiet) { SCLogDebug("initializing flow engine..."); - memset(&flow_config, 0, sizeof(flow_config)); + memset(&flow_config, 0, sizeof(flow_config)); SC_ATOMIC_INIT(flow_flags); SC_ATOMIC_INIT(flow_memuse); SC_ATOMIC_INIT(flow_prune_idx); @@ -558,9 +555,9 @@ void FlowInitConfig(bool quiet) FlowQueueInit(&flow_recycle_q); /* set defaults */ - flow_config.hash_rand = (uint32_t)RandomGet(); - flow_config.hash_size = FLOW_DEFAULT_HASHSIZE; - flow_config.prealloc = FLOW_DEFAULT_PREALLOC; + flow_config.hash_rand = (uint32_t)RandomGet(); + flow_config.hash_size = FLOW_DEFAULT_HASHSIZE; + flow_config.prealloc = FLOW_DEFAULT_PREALLOC; SC_ATOMIC_SET(flow_config.memcap, FLOW_DEFAULT_MEMCAP); /* If we have specific config, overwrite the defaults with them, @@ -585,8 +582,7 @@ void FlowInitConfig(bool quiet) /** set config values for memcap, prealloc and hash_size */ uint64_t flow_memcap_copy = 0; - if ((ConfGet("flow.memcap", &conf_val)) == 1) - { + if ((ConfGet("flow.memcap", &conf_val)) == 1) { if (conf_val == NULL) { FatalError("Invalid value for flow.memcap: NULL"); } @@ -600,8 +596,7 @@ void FlowInitConfig(bool quiet) SC_ATOMIC_SET(flow_config.memcap, flow_memcap_copy); } } - if ((ConfGet("flow.hash-size", &conf_val)) == 1) - { + if ((ConfGet("flow.hash-size", &conf_val)) == 1) { if (conf_val == NULL) { FatalError("Invalid value for flow.hash-size: NULL"); } @@ -613,23 +608,21 @@ void FlowInitConfig(bool quiet) "1-4294967295"); } } - if ((ConfGet("flow.prealloc", &conf_val)) == 1) - { + if ((ConfGet("flow.prealloc", &conf_val)) == 1) { if (conf_val == NULL) { FatalError("Invalid value for flow.prealloc: NULL"); } - if (StringParseUint32(&configval, 10, strlen(conf_val), - conf_val) > 0) { + if (StringParseUint32(&configval, 10, strlen(conf_val), conf_val) > 0) { flow_config.prealloc = configval; } } flow_config.memcap_policy = ExceptionPolicyParse("flow.memcap-policy", false); - SCLogDebug("Flow config from suricata.yaml: memcap: %"PRIu64", hash-size: " - "%"PRIu32", prealloc: %"PRIu32, SC_ATOMIC_GET(flow_config.memcap), - flow_config.hash_size, flow_config.prealloc); + SCLogDebug("Flow config from suricata.yaml: memcap: %" PRIu64 ", hash-size: " + "%" PRIu32 ", prealloc: %" PRIu32, + SC_ATOMIC_GET(flow_config.memcap), flow_config.hash_size, flow_config.prealloc); /* alloc hash memory */ uint64_t hash_size = flow_config.hash_size * sizeof(FlowBucket); @@ -653,17 +646,16 @@ void FlowInitConfig(bool quiet) FBLOCK_INIT(&flow_hash[i]); SC_ATOMIC_INIT(flow_hash[i].next_ts); } - (void) SC_ATOMIC_ADD(flow_memuse, (flow_config.hash_size * sizeof(FlowBucket))); + (void)SC_ATOMIC_ADD(flow_memuse, (flow_config.hash_size * sizeof(FlowBucket))); if (!quiet) { - SCLogConfig("allocated %"PRIu64" bytes of memory for the flow hash... " - "%" PRIu32 " buckets of size %" PRIuMAX "", - SC_ATOMIC_GET(flow_memuse), flow_config.hash_size, - (uintmax_t)sizeof(FlowBucket)); + SCLogConfig("allocated %" PRIu64 " bytes of memory for the flow hash... " + "%" PRIu32 " buckets of size %" PRIuMAX "", + SC_ATOMIC_GET(flow_memuse), flow_config.hash_size, (uintmax_t)sizeof(FlowBucket)); } FlowSparePoolInit(); if (!quiet) { - SCLogConfig("flow memory usage: %"PRIu64" bytes, maximum: %"PRIu64, + SCLogConfig("flow memory usage: %" PRIu64 " bytes, maximum: %" PRIu64, SC_ATOMIC_GET(flow_memuse), SC_ATOMIC_GET(flow_config.memcap)); } @@ -727,7 +719,7 @@ void FlowShutdown(void) SCFreeAligned(flow_hash); flow_hash = NULL; } - (void) SC_ATOMIC_SUB(flow_memuse, flow_config.hash_size * sizeof(FlowBucket)); + (void)SC_ATOMIC_SUB(flow_memuse, flow_config.hash_size * sizeof(FlowBucket)); FlowQueueDestroy(&flow_recycle_q); FlowSparePoolDestroy(); return; @@ -742,36 +734,29 @@ void FlowInitFlowProto(void) { FlowTimeoutsInit(); -#define SET_DEFAULTS(p, n, e, c, b, ne, ee, ce, be) \ - flow_timeouts_normal[(p)].new_timeout = (n); \ - flow_timeouts_normal[(p)].est_timeout = (e); \ - flow_timeouts_normal[(p)].closed_timeout = (c); \ - flow_timeouts_normal[(p)].bypassed_timeout = (b); \ - flow_timeouts_emerg[(p)].new_timeout = (ne); \ - flow_timeouts_emerg[(p)].est_timeout = (ee); \ - flow_timeouts_emerg[(p)].closed_timeout = (ce); \ - flow_timeouts_emerg[(p)].bypassed_timeout = (be); \ - - SET_DEFAULTS(FLOW_PROTO_DEFAULT, - FLOW_DEFAULT_NEW_TIMEOUT, FLOW_DEFAULT_EST_TIMEOUT, - 0, FLOW_DEFAULT_BYPASSED_TIMEOUT, - FLOW_DEFAULT_EMERG_NEW_TIMEOUT, FLOW_DEFAULT_EMERG_EST_TIMEOUT, - 0, FLOW_DEFAULT_EMERG_BYPASSED_TIMEOUT); - SET_DEFAULTS(FLOW_PROTO_TCP, - FLOW_IPPROTO_TCP_NEW_TIMEOUT, FLOW_IPPROTO_TCP_EST_TIMEOUT, - FLOW_IPPROTO_TCP_CLOSED_TIMEOUT, FLOW_IPPROTO_TCP_BYPASSED_TIMEOUT, - FLOW_IPPROTO_TCP_EMERG_NEW_TIMEOUT, FLOW_IPPROTO_TCP_EMERG_EST_TIMEOUT, - FLOW_IPPROTO_TCP_EMERG_CLOSED_TIMEOUT, FLOW_DEFAULT_EMERG_BYPASSED_TIMEOUT); - SET_DEFAULTS(FLOW_PROTO_UDP, - FLOW_IPPROTO_UDP_NEW_TIMEOUT, FLOW_IPPROTO_UDP_EST_TIMEOUT, - 0, FLOW_IPPROTO_UDP_BYPASSED_TIMEOUT, - FLOW_IPPROTO_UDP_EMERG_NEW_TIMEOUT, FLOW_IPPROTO_UDP_EMERG_EST_TIMEOUT, - 0, FLOW_DEFAULT_EMERG_BYPASSED_TIMEOUT); - SET_DEFAULTS(FLOW_PROTO_ICMP, - FLOW_IPPROTO_ICMP_NEW_TIMEOUT, FLOW_IPPROTO_ICMP_EST_TIMEOUT, - 0, FLOW_IPPROTO_ICMP_BYPASSED_TIMEOUT, - FLOW_IPPROTO_ICMP_EMERG_NEW_TIMEOUT, FLOW_IPPROTO_ICMP_EMERG_EST_TIMEOUT, - 0, FLOW_DEFAULT_EMERG_BYPASSED_TIMEOUT); +#define SET_DEFAULTS(p, n, e, c, b, ne, ee, ce, be) \ + flow_timeouts_normal[(p)].new_timeout = (n); \ + flow_timeouts_normal[(p)].est_timeout = (e); \ + flow_timeouts_normal[(p)].closed_timeout = (c); \ + flow_timeouts_normal[(p)].bypassed_timeout = (b); \ + flow_timeouts_emerg[(p)].new_timeout = (ne); \ + flow_timeouts_emerg[(p)].est_timeout = (ee); \ + flow_timeouts_emerg[(p)].closed_timeout = (ce); \ + flow_timeouts_emerg[(p)].bypassed_timeout = (be); + + SET_DEFAULTS(FLOW_PROTO_DEFAULT, FLOW_DEFAULT_NEW_TIMEOUT, FLOW_DEFAULT_EST_TIMEOUT, 0, + FLOW_DEFAULT_BYPASSED_TIMEOUT, FLOW_DEFAULT_EMERG_NEW_TIMEOUT, + FLOW_DEFAULT_EMERG_EST_TIMEOUT, 0, FLOW_DEFAULT_EMERG_BYPASSED_TIMEOUT); + SET_DEFAULTS(FLOW_PROTO_TCP, FLOW_IPPROTO_TCP_NEW_TIMEOUT, FLOW_IPPROTO_TCP_EST_TIMEOUT, + FLOW_IPPROTO_TCP_CLOSED_TIMEOUT, FLOW_IPPROTO_TCP_BYPASSED_TIMEOUT, + FLOW_IPPROTO_TCP_EMERG_NEW_TIMEOUT, FLOW_IPPROTO_TCP_EMERG_EST_TIMEOUT, + FLOW_IPPROTO_TCP_EMERG_CLOSED_TIMEOUT, FLOW_DEFAULT_EMERG_BYPASSED_TIMEOUT); + SET_DEFAULTS(FLOW_PROTO_UDP, FLOW_IPPROTO_UDP_NEW_TIMEOUT, FLOW_IPPROTO_UDP_EST_TIMEOUT, 0, + FLOW_IPPROTO_UDP_BYPASSED_TIMEOUT, FLOW_IPPROTO_UDP_EMERG_NEW_TIMEOUT, + FLOW_IPPROTO_UDP_EMERG_EST_TIMEOUT, 0, FLOW_DEFAULT_EMERG_BYPASSED_TIMEOUT); + SET_DEFAULTS(FLOW_PROTO_ICMP, FLOW_IPPROTO_ICMP_NEW_TIMEOUT, FLOW_IPPROTO_ICMP_EST_TIMEOUT, 0, + FLOW_IPPROTO_ICMP_BYPASSED_TIMEOUT, FLOW_IPPROTO_ICMP_EMERG_NEW_TIMEOUT, + FLOW_IPPROTO_ICMP_EMERG_EST_TIMEOUT, 0, FLOW_DEFAULT_EMERG_BYPASSED_TIMEOUT); flow_freefuncs[FLOW_PROTO_DEFAULT].Freefunc = NULL; flow_freefuncs[FLOW_PROTO_TCP].Freefunc = NULL; @@ -801,61 +786,48 @@ void FlowInitFlowProto(void) closed = ConfNodeLookupChildValue(proto, "closed"); bypassed = ConfNodeLookupChildValue(proto, "bypassed"); emergency_new = ConfNodeLookupChildValue(proto, "emergency-new"); - emergency_established = ConfNodeLookupChildValue(proto, - "emergency-established"); - emergency_closed = ConfNodeLookupChildValue(proto, - "emergency-closed"); - emergency_bypassed = ConfNodeLookupChildValue(proto, - "emergency-bypassed"); + emergency_established = ConfNodeLookupChildValue(proto, "emergency-established"); + emergency_closed = ConfNodeLookupChildValue(proto, "emergency-closed"); + emergency_bypassed = ConfNodeLookupChildValue(proto, "emergency-bypassed"); - if (new != NULL && - StringParseUint32(&configval, 10, strlen(new), new) > 0) { + if (new != NULL && StringParseUint32(&configval, 10, strlen(new), new) > 0) { - flow_timeouts_normal[FLOW_PROTO_DEFAULT].new_timeout = configval; + flow_timeouts_normal[FLOW_PROTO_DEFAULT].new_timeout = configval; } if (established != NULL && - StringParseUint32(&configval, 10, strlen(established), - established) > 0) { + StringParseUint32(&configval, 10, strlen(established), established) > 0) { flow_timeouts_normal[FLOW_PROTO_DEFAULT].est_timeout = configval; } - if (closed != NULL && - StringParseUint32(&configval, 10, strlen(closed), - closed) > 0) { + if (closed != NULL && StringParseUint32(&configval, 10, strlen(closed), closed) > 0) { flow_timeouts_normal[FLOW_PROTO_DEFAULT].closed_timeout = configval; } if (bypassed != NULL && - StringParseUint32(&configval, 10, - strlen(bypassed), - bypassed) > 0) { + StringParseUint32(&configval, 10, strlen(bypassed), bypassed) > 0) { flow_timeouts_normal[FLOW_PROTO_DEFAULT].bypassed_timeout = configval; } if (emergency_new != NULL && - StringParseUint32(&configval, 10, strlen(emergency_new), - emergency_new) > 0) { + StringParseUint32(&configval, 10, strlen(emergency_new), emergency_new) > 0) { flow_timeouts_emerg[FLOW_PROTO_DEFAULT].new_timeout = configval; } if (emergency_established != NULL && - StringParseUint32(&configval, 10, - strlen(emergency_established), - emergency_established) > 0) { + StringParseUint32(&configval, 10, strlen(emergency_established), + emergency_established) > 0) { - flow_timeouts_emerg[FLOW_PROTO_DEFAULT].est_timeout= configval; + flow_timeouts_emerg[FLOW_PROTO_DEFAULT].est_timeout = configval; } if (emergency_closed != NULL && - StringParseUint32(&configval, 10, - strlen(emergency_closed), - emergency_closed) > 0) { + StringParseUint32(&configval, 10, strlen(emergency_closed), emergency_closed) > + 0) { flow_timeouts_emerg[FLOW_PROTO_DEFAULT].closed_timeout = configval; } if (emergency_bypassed != NULL && - StringParseUint32(&configval, 10, - strlen(emergency_bypassed), - emergency_bypassed) > 0) { + StringParseUint32( + &configval, 10, strlen(emergency_bypassed), emergency_bypassed) > 0) { flow_timeouts_emerg[FLOW_PROTO_DEFAULT].bypassed_timeout = configval; } @@ -869,61 +841,48 @@ void FlowInitFlowProto(void) closed = ConfNodeLookupChildValue(proto, "closed"); bypassed = ConfNodeLookupChildValue(proto, "bypassed"); emergency_new = ConfNodeLookupChildValue(proto, "emergency-new"); - emergency_established = ConfNodeLookupChildValue(proto, - "emergency-established"); - emergency_closed = ConfNodeLookupChildValue(proto, - "emergency-closed"); - emergency_bypassed = ConfNodeLookupChildValue(proto, - "emergency-bypassed"); + emergency_established = ConfNodeLookupChildValue(proto, "emergency-established"); + emergency_closed = ConfNodeLookupChildValue(proto, "emergency-closed"); + emergency_bypassed = ConfNodeLookupChildValue(proto, "emergency-bypassed"); - if (new != NULL && - StringParseUint32(&configval, 10, strlen(new), new) > 0) { + if (new != NULL && StringParseUint32(&configval, 10, strlen(new), new) > 0) { flow_timeouts_normal[FLOW_PROTO_TCP].new_timeout = configval; } if (established != NULL && - StringParseUint32(&configval, 10, strlen(established), - established) > 0) { + StringParseUint32(&configval, 10, strlen(established), established) > 0) { flow_timeouts_normal[FLOW_PROTO_TCP].est_timeout = configval; } - if (closed != NULL && - StringParseUint32(&configval, 10, strlen(closed), - closed) > 0) { + if (closed != NULL && StringParseUint32(&configval, 10, strlen(closed), closed) > 0) { flow_timeouts_normal[FLOW_PROTO_TCP].closed_timeout = configval; } if (bypassed != NULL && - StringParseUint32(&configval, 10, - strlen(bypassed), - bypassed) > 0) { + StringParseUint32(&configval, 10, strlen(bypassed), bypassed) > 0) { flow_timeouts_normal[FLOW_PROTO_TCP].bypassed_timeout = configval; } if (emergency_new != NULL && - StringParseUint32(&configval, 10, strlen(emergency_new), - emergency_new) > 0) { + StringParseUint32(&configval, 10, strlen(emergency_new), emergency_new) > 0) { flow_timeouts_emerg[FLOW_PROTO_TCP].new_timeout = configval; } if (emergency_established != NULL && - StringParseUint32(&configval, 10, - strlen(emergency_established), - emergency_established) > 0) { + StringParseUint32(&configval, 10, strlen(emergency_established), + emergency_established) > 0) { flow_timeouts_emerg[FLOW_PROTO_TCP].est_timeout = configval; } if (emergency_closed != NULL && - StringParseUint32(&configval, 10, - strlen(emergency_closed), - emergency_closed) > 0) { + StringParseUint32(&configval, 10, strlen(emergency_closed), emergency_closed) > + 0) { flow_timeouts_emerg[FLOW_PROTO_TCP].closed_timeout = configval; } if (emergency_bypassed != NULL && - StringParseUint32(&configval, 10, - strlen(emergency_bypassed), - emergency_bypassed) > 0) { + StringParseUint32( + &configval, 10, strlen(emergency_bypassed), emergency_bypassed) > 0) { flow_timeouts_emerg[FLOW_PROTO_TCP].bypassed_timeout = configval; } @@ -936,46 +895,37 @@ void FlowInitFlowProto(void) established = ConfNodeLookupChildValue(proto, "established"); bypassed = ConfNodeLookupChildValue(proto, "bypassed"); emergency_new = ConfNodeLookupChildValue(proto, "emergency-new"); - emergency_established = ConfNodeLookupChildValue(proto, - "emergency-established"); - emergency_bypassed = ConfNodeLookupChildValue(proto, - "emergency-bypassed"); + emergency_established = ConfNodeLookupChildValue(proto, "emergency-established"); + emergency_bypassed = ConfNodeLookupChildValue(proto, "emergency-bypassed"); - if (new != NULL && - StringParseUint32(&configval, 10, strlen(new), new) > 0) { + if (new != NULL && StringParseUint32(&configval, 10, strlen(new), new) > 0) { flow_timeouts_normal[FLOW_PROTO_UDP].new_timeout = configval; } if (established != NULL && - StringParseUint32(&configval, 10, strlen(established), - established) > 0) { + StringParseUint32(&configval, 10, strlen(established), established) > 0) { flow_timeouts_normal[FLOW_PROTO_UDP].est_timeout = configval; } if (bypassed != NULL && - StringParseUint32(&configval, 10, - strlen(bypassed), - bypassed) > 0) { + StringParseUint32(&configval, 10, strlen(bypassed), bypassed) > 0) { flow_timeouts_normal[FLOW_PROTO_UDP].bypassed_timeout = configval; } if (emergency_new != NULL && - StringParseUint32(&configval, 10, strlen(emergency_new), - emergency_new) > 0) { + StringParseUint32(&configval, 10, strlen(emergency_new), emergency_new) > 0) { flow_timeouts_emerg[FLOW_PROTO_UDP].new_timeout = configval; } if (emergency_established != NULL && - StringParseUint32(&configval, 10, - strlen(emergency_established), - emergency_established) > 0) { + StringParseUint32(&configval, 10, strlen(emergency_established), + emergency_established) > 0) { flow_timeouts_emerg[FLOW_PROTO_UDP].est_timeout = configval; } if (emergency_bypassed != NULL && - StringParseUint32(&configval, 10, - strlen(emergency_bypassed), - emergency_bypassed) > 0) { + StringParseUint32( + &configval, 10, strlen(emergency_bypassed), emergency_bypassed) > 0) { flow_timeouts_emerg[FLOW_PROTO_UDP].bypassed_timeout = configval; } @@ -988,46 +938,37 @@ void FlowInitFlowProto(void) established = ConfNodeLookupChildValue(proto, "established"); bypassed = ConfNodeLookupChildValue(proto, "bypassed"); emergency_new = ConfNodeLookupChildValue(proto, "emergency-new"); - emergency_established = ConfNodeLookupChildValue(proto, - "emergency-established"); - emergency_bypassed = ConfNodeLookupChildValue(proto, - "emergency-bypassed"); + emergency_established = ConfNodeLookupChildValue(proto, "emergency-established"); + emergency_bypassed = ConfNodeLookupChildValue(proto, "emergency-bypassed"); - if (new != NULL && - StringParseUint32(&configval, 10, strlen(new), new) > 0) { + if (new != NULL && StringParseUint32(&configval, 10, strlen(new), new) > 0) { flow_timeouts_normal[FLOW_PROTO_ICMP].new_timeout = configval; } if (established != NULL && - StringParseUint32(&configval, 10, strlen(established), - established) > 0) { + StringParseUint32(&configval, 10, strlen(established), established) > 0) { flow_timeouts_normal[FLOW_PROTO_ICMP].est_timeout = configval; } if (bypassed != NULL && - StringParseUint32(&configval, 10, - strlen(bypassed), - bypassed) > 0) { + StringParseUint32(&configval, 10, strlen(bypassed), bypassed) > 0) { flow_timeouts_normal[FLOW_PROTO_ICMP].bypassed_timeout = configval; } if (emergency_new != NULL && - StringParseUint32(&configval, 10, strlen(emergency_new), - emergency_new) > 0) { + StringParseUint32(&configval, 10, strlen(emergency_new), emergency_new) > 0) { flow_timeouts_emerg[FLOW_PROTO_ICMP].new_timeout = configval; } if (emergency_established != NULL && - StringParseUint32(&configval, 10, - strlen(emergency_established), - emergency_established) > 0) { + StringParseUint32(&configval, 10, strlen(emergency_established), + emergency_established) > 0) { flow_timeouts_emerg[FLOW_PROTO_ICMP].est_timeout = configval; } if (emergency_bypassed != NULL && - StringParseUint32(&configval, 10, - strlen(emergency_bypassed), - emergency_bypassed) > 0) { + StringParseUint32( + &configval, 10, strlen(emergency_bypassed), emergency_bypassed) > 0) { flow_timeouts_emerg[FLOW_PROTO_ICMP].bypassed_timeout = configval; } @@ -1097,8 +1038,8 @@ void FlowInitFlowProto(void) } d->bypassed_timeout = n->bypassed_timeout - e->bypassed_timeout; - SCLogDebug("deltas: new: -%u est: -%u closed: -%u bypassed: -%u", - d->new_timeout, d->est_timeout, d->closed_timeout, d->bypassed_timeout); + SCLogDebug("deltas: new: -%u est: -%u closed: -%u bypassed: -%u", d->new_timeout, + d->est_timeout, d->closed_timeout, d->bypassed_timeout); } return; @@ -1112,7 +1053,7 @@ void FlowInitFlowProto(void) * \param proto_map mapped value of the protocol to FLOW_PROTO's. */ -int FlowClearMemory(Flow* f, uint8_t proto_map) +int FlowClearMemory(Flow *f, uint8_t proto_map) { SCEnter(); @@ -1140,7 +1081,7 @@ int FlowClearMemory(Flow* f, uint8_t proto_map) * specific memory. */ -int FlowSetProtoFreeFunc (uint8_t proto, void (*Free)(void *)) +int FlowSetProtoFreeFunc(uint8_t proto, void (*Free)(void *)) { uint8_t proto_map; proto_map = FlowGetProtoMapping(proto); @@ -1261,7 +1202,7 @@ uint32_t FlowGetFlags(Flow *flow) * \retval On success it returns 1 and on failure 0. */ -static int FlowTest01 (void) +static int FlowTest01(void) { uint8_t proto_map; @@ -1295,7 +1236,9 @@ static int FlowTest01 (void) /*Test function for the unit test FlowTest02*/ -static void test(void *f) {} +static void test(void *f) +{ +} /** * \test Test the setting of the per protocol free function to free the @@ -1304,7 +1247,7 @@ static void test(void *f) {} * \retval On success it returns 1 and on failure 0. */ -static int FlowTest02 (void) +static int FlowTest02(void) { FlowSetProtoFreeFunc(IPPROTO_DCCP, test); FlowSetProtoFreeFunc(IPPROTO_TCP, test); @@ -1326,7 +1269,7 @@ static int FlowTest02 (void) * \retval On success it returns 1 and on failure 0. */ -static int FlowTest07 (void) +static int FlowTest07(void) { int result = 0; FlowInitConfig(FLOW_QUIET); @@ -1372,7 +1315,7 @@ static int FlowTest07 (void) * \retval On success it returns 1 and on failure 0. */ -static int FlowTest08 (void) +static int FlowTest08(void) { int result = 0; @@ -1419,7 +1362,7 @@ static int FlowTest08 (void) * \retval On success it returns 1 and on failure 0. */ -static int FlowTest09 (void) +static int FlowTest09(void) { int result = 0; @@ -1463,18 +1406,14 @@ static int FlowTest09 (void) /** * \brief Function to register the Flow Unitests. */ -void FlowRegisterTests (void) +void FlowRegisterTests(void) { #ifdef UNITTESTS UtRegisterTest("FlowTest01 -- Protocol Specific Timeouts", FlowTest01); - UtRegisterTest("FlowTest02 -- Setting Protocol Specific Free Function", - FlowTest02); - UtRegisterTest("FlowTest07 -- Test flow Allocations when it reach memcap", - FlowTest07); - UtRegisterTest("FlowTest08 -- Test flow Allocations when it reach memcap", - FlowTest08); - UtRegisterTest("FlowTest09 -- Test flow Allocations when it reach memcap", - FlowTest09); + UtRegisterTest("FlowTest02 -- Setting Protocol Specific Free Function", FlowTest02); + UtRegisterTest("FlowTest07 -- Test flow Allocations when it reach memcap", FlowTest07); + UtRegisterTest("FlowTest08 -- Test flow Allocations when it reach memcap", FlowTest08); + UtRegisterTest("FlowTest09 -- Test flow Allocations when it reach memcap", FlowTest09); RegisterFlowStorageTests(); #endif /* UNITTESTS */ diff --git a/src/flow.h b/src/flow.h index c7b5867ea896..6c6c6cd04057 100644 --- a/src/flow.h +++ b/src/flow.h @@ -46,68 +46,68 @@ typedef struct AppLayerParserState_ AppLayerParserState; /* per flow flags */ /** At least one packet from the source address was seen */ -#define FLOW_TO_SRC_SEEN BIT_U32(0) +#define FLOW_TO_SRC_SEEN BIT_U32(0) /** At least one packet from the destination address was seen */ -#define FLOW_TO_DST_SEEN BIT_U32(1) +#define FLOW_TO_DST_SEEN BIT_U32(1) // vacancy /** Flow was inspected against IP-Only sigs in the toserver direction */ -#define FLOW_TOSERVER_IPONLY_SET BIT_U32(3) +#define FLOW_TOSERVER_IPONLY_SET BIT_U32(3) /** Flow was inspected against IP-Only sigs in the toclient direction */ -#define FLOW_TOCLIENT_IPONLY_SET BIT_U32(4) +#define FLOW_TOCLIENT_IPONLY_SET BIT_U32(4) /** Packet belonging to this flow should not be inspected at all */ -#define FLOW_NOPACKET_INSPECTION BIT_U32(5) +#define FLOW_NOPACKET_INSPECTION BIT_U32(5) /** Packet payloads belonging to this flow should not be inspected */ -#define FLOW_NOPAYLOAD_INSPECTION BIT_U32(6) +#define FLOW_NOPAYLOAD_INSPECTION BIT_U32(6) /** All packets in this flow should be dropped */ -#define FLOW_ACTION_DROP BIT_U32(7) +#define FLOW_ACTION_DROP BIT_U32(7) /** Sgh for toserver direction set (even if it's NULL) */ -#define FLOW_SGH_TOSERVER BIT_U32(8) +#define FLOW_SGH_TOSERVER BIT_U32(8) /** Sgh for toclient direction set (even if it's NULL) */ -#define FLOW_SGH_TOCLIENT BIT_U32(9) +#define FLOW_SGH_TOCLIENT BIT_U32(9) /** packet to server direction has been logged in drop file (only in IPS mode) */ -#define FLOW_TOSERVER_DROP_LOGGED BIT_U32(10) +#define FLOW_TOSERVER_DROP_LOGGED BIT_U32(10) /** packet to client direction has been logged in drop file (only in IPS mode) */ -#define FLOW_TOCLIENT_DROP_LOGGED BIT_U32(11) +#define FLOW_TOCLIENT_DROP_LOGGED BIT_U32(11) /** flow has alerts */ -#define FLOW_HAS_ALERTS BIT_U32(12) +#define FLOW_HAS_ALERTS BIT_U32(12) /** Pattern matcher alproto detection done */ -#define FLOW_TS_PM_ALPROTO_DETECT_DONE BIT_U32(13) +#define FLOW_TS_PM_ALPROTO_DETECT_DONE BIT_U32(13) /** Probing parser alproto detection done */ -#define FLOW_TS_PP_ALPROTO_DETECT_DONE BIT_U32(14) +#define FLOW_TS_PP_ALPROTO_DETECT_DONE BIT_U32(14) /** Expectation alproto detection done */ -#define FLOW_TS_PE_ALPROTO_DETECT_DONE BIT_U32(15) +#define FLOW_TS_PE_ALPROTO_DETECT_DONE BIT_U32(15) /** Pattern matcher alproto detection done */ -#define FLOW_TC_PM_ALPROTO_DETECT_DONE BIT_U32(16) +#define FLOW_TC_PM_ALPROTO_DETECT_DONE BIT_U32(16) /** Probing parser alproto detection done */ -#define FLOW_TC_PP_ALPROTO_DETECT_DONE BIT_U32(17) +#define FLOW_TC_PP_ALPROTO_DETECT_DONE BIT_U32(17) /** Expectation alproto detection done */ -#define FLOW_TC_PE_ALPROTO_DETECT_DONE BIT_U32(18) -#define FLOW_TIMEOUT_REASSEMBLY_DONE BIT_U32(19) +#define FLOW_TC_PE_ALPROTO_DETECT_DONE BIT_U32(18) +#define FLOW_TIMEOUT_REASSEMBLY_DONE BIT_U32(19) /** flow is ipv4 */ -#define FLOW_IPV4 BIT_U32(20) +#define FLOW_IPV4 BIT_U32(20) /** flow is ipv6 */ -#define FLOW_IPV6 BIT_U32(21) +#define FLOW_IPV6 BIT_U32(21) -#define FLOW_PROTO_DETECT_TS_DONE BIT_U32(22) -#define FLOW_PROTO_DETECT_TC_DONE BIT_U32(23) +#define FLOW_PROTO_DETECT_TS_DONE BIT_U32(22) +#define FLOW_PROTO_DETECT_TC_DONE BIT_U32(23) /** Indicate that alproto detection for flow should be done again */ -#define FLOW_CHANGE_PROTO BIT_U32(24) +#define FLOW_CHANGE_PROTO BIT_U32(24) -#define FLOW_WRONG_THREAD BIT_U32(25) +#define FLOW_WRONG_THREAD BIT_U32(25) /** Protocol detection told us flow is picked up in wrong direction (midstream) */ -#define FLOW_DIR_REVERSED BIT_U32(26) +#define FLOW_DIR_REVERSED BIT_U32(26) /** Indicate that the flow did trigger an expectation creation */ -#define FLOW_HAS_EXPECTATION BIT_U32(27) +#define FLOW_HAS_EXPECTATION BIT_U32(27) /** All packets in this flow should be passed */ #define FLOW_ACTION_PASS BIT_U32(28) @@ -117,69 +117,61 @@ typedef struct AppLayerParserState_ AppLayerParserState; /* File flags */ -#define FLOWFILE_INIT 0 +#define FLOWFILE_INIT 0 /** no magic on files in this flow */ -#define FLOWFILE_NO_MAGIC_TS BIT_U16(0) -#define FLOWFILE_NO_MAGIC_TC BIT_U16(1) +#define FLOWFILE_NO_MAGIC_TS BIT_U16(0) +#define FLOWFILE_NO_MAGIC_TC BIT_U16(1) /** even if the flow has files, don't store 'm */ -#define FLOWFILE_NO_STORE_TS BIT_U16(2) -#define FLOWFILE_NO_STORE_TC BIT_U16(3) +#define FLOWFILE_NO_STORE_TS BIT_U16(2) +#define FLOWFILE_NO_STORE_TC BIT_U16(3) /** no md5 on files in this flow */ -#define FLOWFILE_NO_MD5_TS BIT_U16(4) -#define FLOWFILE_NO_MD5_TC BIT_U16(5) +#define FLOWFILE_NO_MD5_TS BIT_U16(4) +#define FLOWFILE_NO_MD5_TC BIT_U16(5) /** no sha1 on files in this flow */ -#define FLOWFILE_NO_SHA1_TS BIT_U16(6) -#define FLOWFILE_NO_SHA1_TC BIT_U16(7) +#define FLOWFILE_NO_SHA1_TS BIT_U16(6) +#define FLOWFILE_NO_SHA1_TC BIT_U16(7) /** no sha256 on files in this flow */ -#define FLOWFILE_NO_SHA256_TS BIT_U16(8) -#define FLOWFILE_NO_SHA256_TC BIT_U16(9) +#define FLOWFILE_NO_SHA256_TS BIT_U16(8) +#define FLOWFILE_NO_SHA256_TC BIT_U16(9) /** no size tracking of files in this flow */ -#define FLOWFILE_NO_SIZE_TS BIT_U16(10) -#define FLOWFILE_NO_SIZE_TC BIT_U16(11) +#define FLOWFILE_NO_SIZE_TS BIT_U16(10) +#define FLOWFILE_NO_SIZE_TC BIT_U16(11) /** store all files in the flow */ #define FLOWFILE_STORE BIT_U16(12) -#define FLOWFILE_NONE_TS (FLOWFILE_NO_MAGIC_TS | \ - FLOWFILE_NO_STORE_TS | \ - FLOWFILE_NO_MD5_TS | \ - FLOWFILE_NO_SHA1_TS | \ - FLOWFILE_NO_SHA256_TS| \ - FLOWFILE_NO_SIZE_TS) -#define FLOWFILE_NONE_TC (FLOWFILE_NO_MAGIC_TC | \ - FLOWFILE_NO_STORE_TC | \ - FLOWFILE_NO_MD5_TC | \ - FLOWFILE_NO_SHA1_TC | \ - FLOWFILE_NO_SHA256_TC| \ - FLOWFILE_NO_SIZE_TC) -#define FLOWFILE_NONE (FLOWFILE_NONE_TS|FLOWFILE_NONE_TC) - -#define FLOW_IS_IPV4(f) \ - (((f)->flags & FLOW_IPV4) == FLOW_IPV4) -#define FLOW_IS_IPV6(f) \ - (((f)->flags & FLOW_IPV6) == FLOW_IPV6) - -#define FLOW_GET_SP(f) \ - ((f)->flags & FLOW_DIR_REVERSED) ? (f)->dp : (f)->sp; -#define FLOW_GET_DP(f) \ - ((f)->flags & FLOW_DIR_REVERSED) ? (f)->sp : (f)->dp; - -#define FLOW_COPY_IPV4_ADDR_TO_PACKET(fa, pa) do { \ - (pa)->family = AF_INET; \ - (pa)->addr_data32[0] = (fa)->addr_data32[0]; \ +#define FLOWFILE_NONE_TS \ + (FLOWFILE_NO_MAGIC_TS | FLOWFILE_NO_STORE_TS | FLOWFILE_NO_MD5_TS | FLOWFILE_NO_SHA1_TS | \ + FLOWFILE_NO_SHA256_TS | FLOWFILE_NO_SIZE_TS) +#define FLOWFILE_NONE_TC \ + (FLOWFILE_NO_MAGIC_TC | FLOWFILE_NO_STORE_TC | FLOWFILE_NO_MD5_TC | FLOWFILE_NO_SHA1_TC | \ + FLOWFILE_NO_SHA256_TC | FLOWFILE_NO_SIZE_TC) +#define FLOWFILE_NONE (FLOWFILE_NONE_TS | FLOWFILE_NONE_TC) + +#define FLOW_IS_IPV4(f) (((f)->flags & FLOW_IPV4) == FLOW_IPV4) +#define FLOW_IS_IPV6(f) (((f)->flags & FLOW_IPV6) == FLOW_IPV6) + +#define FLOW_GET_SP(f) ((f)->flags & FLOW_DIR_REVERSED) ? (f)->dp : (f)->sp; +#define FLOW_GET_DP(f) ((f)->flags & FLOW_DIR_REVERSED) ? (f)->sp : (f)->dp; + +#define FLOW_COPY_IPV4_ADDR_TO_PACKET(fa, pa) \ + do { \ + (pa)->family = AF_INET; \ + (pa)->addr_data32[0] = (fa)->addr_data32[0]; \ } while (0) -#define FLOW_COPY_IPV6_ADDR_TO_PACKET(fa, pa) do { \ - (pa)->family = AF_INET6; \ - (pa)->addr_data32[0] = (fa)->addr_data32[0]; \ - (pa)->addr_data32[1] = (fa)->addr_data32[1]; \ - (pa)->addr_data32[2] = (fa)->addr_data32[2]; \ - (pa)->addr_data32[3] = (fa)->addr_data32[3]; \ +#define FLOW_COPY_IPV6_ADDR_TO_PACKET(fa, pa) \ + do { \ + (pa)->family = AF_INET6; \ + (pa)->addr_data32[0] = (fa)->addr_data32[0]; \ + (pa)->addr_data32[1] = (fa)->addr_data32[1]; \ + (pa)->addr_data32[2] = (fa)->addr_data32[2]; \ + (pa)->addr_data32[3] = (fa)->addr_data32[3]; \ } while (0) /* Set the IPv4 addressesinto the Addrs of the Packet. @@ -187,47 +179,51 @@ typedef struct AppLayerParserState_ AppLayerParserState; * * We set the rest of the struct to 0 so we can * prevent using memset. */ -#define FLOW_SET_IPV4_SRC_ADDR_FROM_PACKET(p, a) do { \ - (a)->addr_data32[0] = (uint32_t)(p)->ip4h->s_ip_src.s_addr; \ - (a)->addr_data32[1] = 0; \ - (a)->addr_data32[2] = 0; \ - (a)->addr_data32[3] = 0; \ +#define FLOW_SET_IPV4_SRC_ADDR_FROM_PACKET(p, a) \ + do { \ + (a)->addr_data32[0] = (uint32_t)(p)->ip4h->s_ip_src.s_addr; \ + (a)->addr_data32[1] = 0; \ + (a)->addr_data32[2] = 0; \ + (a)->addr_data32[3] = 0; \ } while (0) -#define FLOW_SET_IPV4_DST_ADDR_FROM_PACKET(p, a) do { \ - (a)->addr_data32[0] = (uint32_t)(p)->ip4h->s_ip_dst.s_addr; \ - (a)->addr_data32[1] = 0; \ - (a)->addr_data32[2] = 0; \ - (a)->addr_data32[3] = 0; \ +#define FLOW_SET_IPV4_DST_ADDR_FROM_PACKET(p, a) \ + do { \ + (a)->addr_data32[0] = (uint32_t)(p)->ip4h->s_ip_dst.s_addr; \ + (a)->addr_data32[1] = 0; \ + (a)->addr_data32[2] = 0; \ + (a)->addr_data32[3] = 0; \ } while (0) /* Set the IPv6 addressesinto the Addrs of the Packet. * Make sure p->ip6h is initialized and validated. */ -#define FLOW_SET_IPV6_SRC_ADDR_FROM_PACKET(p, a) do { \ - (a)->addr_data32[0] = (p)->ip6h->s_ip6_src[0]; \ - (a)->addr_data32[1] = (p)->ip6h->s_ip6_src[1]; \ - (a)->addr_data32[2] = (p)->ip6h->s_ip6_src[2]; \ - (a)->addr_data32[3] = (p)->ip6h->s_ip6_src[3]; \ +#define FLOW_SET_IPV6_SRC_ADDR_FROM_PACKET(p, a) \ + do { \ + (a)->addr_data32[0] = (p)->ip6h->s_ip6_src[0]; \ + (a)->addr_data32[1] = (p)->ip6h->s_ip6_src[1]; \ + (a)->addr_data32[2] = (p)->ip6h->s_ip6_src[2]; \ + (a)->addr_data32[3] = (p)->ip6h->s_ip6_src[3]; \ } while (0) -#define FLOW_SET_IPV6_DST_ADDR_FROM_PACKET(p, a) do { \ - (a)->addr_data32[0] = (p)->ip6h->s_ip6_dst[0]; \ - (a)->addr_data32[1] = (p)->ip6h->s_ip6_dst[1]; \ - (a)->addr_data32[2] = (p)->ip6h->s_ip6_dst[2]; \ - (a)->addr_data32[3] = (p)->ip6h->s_ip6_dst[3]; \ +#define FLOW_SET_IPV6_DST_ADDR_FROM_PACKET(p, a) \ + do { \ + (a)->addr_data32[0] = (p)->ip6h->s_ip6_dst[0]; \ + (a)->addr_data32[1] = (p)->ip6h->s_ip6_dst[1]; \ + (a)->addr_data32[2] = (p)->ip6h->s_ip6_dst[2]; \ + (a)->addr_data32[3] = (p)->ip6h->s_ip6_dst[3]; \ } while (0) /* pkt flow flags */ -#define FLOW_PKT_TOSERVER 0x01 -#define FLOW_PKT_TOCLIENT 0x02 -#define FLOW_PKT_ESTABLISHED 0x04 -#define FLOW_PKT_TOSERVER_IPONLY_SET 0x08 -#define FLOW_PKT_TOCLIENT_IPONLY_SET 0x10 -#define FLOW_PKT_TOSERVER_FIRST 0x20 -#define FLOW_PKT_TOCLIENT_FIRST 0x40 +#define FLOW_PKT_TOSERVER 0x01 +#define FLOW_PKT_TOCLIENT 0x02 +#define FLOW_PKT_ESTABLISHED 0x04 +#define FLOW_PKT_TOSERVER_IPONLY_SET 0x08 +#define FLOW_PKT_TOCLIENT_IPONLY_SET 0x10 +#define FLOW_PKT_TOSERVER_FIRST 0x20 +#define FLOW_PKT_TOCLIENT_FIRST 0x40 /** last pseudo packet in the flow. Can be used to trigger final clean, * logging, etc. */ -#define FLOW_PKT_LAST_PSEUDO 0x80 +#define FLOW_PKT_LAST_PSEUDO 0x80 #define FLOW_END_FLAG_STATE_NEW 0x01 #define FLOW_END_FLAG_STATE_ESTABLISHED 0x02 @@ -243,46 +239,63 @@ typedef struct AppLayerParserState_ AppLayerParserState; #define FLOWLOCK_MUTEX #ifdef FLOWLOCK_RWLOCK - #ifdef FLOWLOCK_MUTEX - #error Cannot enable both FLOWLOCK_RWLOCK and FLOWLOCK_MUTEX - #endif +#ifdef FLOWLOCK_MUTEX +#error Cannot enable both FLOWLOCK_RWLOCK and FLOWLOCK_MUTEX +#endif #endif #ifdef FLOWLOCK_RWLOCK - #define FLOWLOCK_INIT(fb) SCRWLockInit(&(fb)->r, NULL) - #define FLOWLOCK_DESTROY(fb) SCRWLockDestroy(&(fb)->r) - #define FLOWLOCK_RDLOCK(fb) SCRWLockRDLock(&(fb)->r) - #define FLOWLOCK_WRLOCK(fb) SCRWLockWRLock(&(fb)->r) - #define FLOWLOCK_TRYRDLOCK(fb) SCRWLockTryRDLock(&(fb)->r) - #define FLOWLOCK_TRYWRLOCK(fb) SCRWLockTryWRLock(&(fb)->r) - #define FLOWLOCK_UNLOCK(fb) SCRWLockUnlock(&(fb)->r) +#define FLOWLOCK_INIT(fb) SCRWLockInit(&(fb)->r, NULL) +#define FLOWLOCK_DESTROY(fb) SCRWLockDestroy(&(fb)->r) +#define FLOWLOCK_RDLOCK(fb) SCRWLockRDLock(&(fb)->r) +#define FLOWLOCK_WRLOCK(fb) SCRWLockWRLock(&(fb)->r) +#define FLOWLOCK_TRYRDLOCK(fb) SCRWLockTryRDLock(&(fb)->r) +#define FLOWLOCK_TRYWRLOCK(fb) SCRWLockTryWRLock(&(fb)->r) +#define FLOWLOCK_UNLOCK(fb) SCRWLockUnlock(&(fb)->r) #elif defined FLOWLOCK_MUTEX - #define FLOWLOCK_INIT(fb) SCMutexInit(&(fb)->m, NULL) - #define FLOWLOCK_DESTROY(fb) SCMutexDestroy(&(fb)->m) - #define FLOWLOCK_RDLOCK(fb) SCMutexLock(&(fb)->m) - #define FLOWLOCK_WRLOCK(fb) SCMutexLock(&(fb)->m) - #define FLOWLOCK_TRYRDLOCK(fb) SCMutexTrylock(&(fb)->m) - #define FLOWLOCK_TRYWRLOCK(fb) SCMutexTrylock(&(fb)->m) - #define FLOWLOCK_UNLOCK(fb) SCMutexUnlock(&(fb)->m) +#define FLOWLOCK_INIT(fb) SCMutexInit(&(fb)->m, NULL) +#define FLOWLOCK_DESTROY(fb) SCMutexDestroy(&(fb)->m) +#define FLOWLOCK_RDLOCK(fb) SCMutexLock(&(fb)->m) +#define FLOWLOCK_WRLOCK(fb) SCMutexLock(&(fb)->m) +#define FLOWLOCK_TRYRDLOCK(fb) SCMutexTrylock(&(fb)->m) +#define FLOWLOCK_TRYWRLOCK(fb) SCMutexTrylock(&(fb)->m) +#define FLOWLOCK_UNLOCK(fb) SCMutexUnlock(&(fb)->m) #else - #error Enable FLOWLOCK_RWLOCK or FLOWLOCK_MUTEX +#error Enable FLOWLOCK_RWLOCK or FLOWLOCK_MUTEX #endif -#define FLOW_IS_PM_DONE(f, dir) (((dir) & STREAM_TOSERVER) ? ((f)->flags & FLOW_TS_PM_ALPROTO_DETECT_DONE) : ((f)->flags & FLOW_TC_PM_ALPROTO_DETECT_DONE)) -#define FLOW_IS_PP_DONE(f, dir) (((dir) & STREAM_TOSERVER) ? ((f)->flags & FLOW_TS_PP_ALPROTO_DETECT_DONE) : ((f)->flags & FLOW_TC_PP_ALPROTO_DETECT_DONE)) -#define FLOW_IS_PE_DONE(f, dir) (((dir) & STREAM_TOSERVER) ? ((f)->flags & FLOW_TS_PE_ALPROTO_DETECT_DONE) : ((f)->flags & FLOW_TC_PE_ALPROTO_DETECT_DONE)) - -#define FLOW_SET_PM_DONE(f, dir) (((dir) & STREAM_TOSERVER) ? ((f)->flags |= FLOW_TS_PM_ALPROTO_DETECT_DONE) : ((f)->flags |= FLOW_TC_PM_ALPROTO_DETECT_DONE)) -#define FLOW_SET_PP_DONE(f, dir) (((dir) & STREAM_TOSERVER) ? ((f)->flags |= FLOW_TS_PP_ALPROTO_DETECT_DONE) : ((f)->flags |= FLOW_TC_PP_ALPROTO_DETECT_DONE)) -#define FLOW_SET_PE_DONE(f, dir) (((dir) & STREAM_TOSERVER) ? ((f)->flags |= FLOW_TS_PE_ALPROTO_DETECT_DONE) : ((f)->flags |= FLOW_TC_PE_ALPROTO_DETECT_DONE)) - -#define FLOW_RESET_PM_DONE(f, dir) (((dir) & STREAM_TOSERVER) ? ((f)->flags &= ~FLOW_TS_PM_ALPROTO_DETECT_DONE) : ((f)->flags &= ~FLOW_TC_PM_ALPROTO_DETECT_DONE)) -#define FLOW_RESET_PP_DONE(f, dir) (((dir) & STREAM_TOSERVER) ? ((f)->flags &= ~FLOW_TS_PP_ALPROTO_DETECT_DONE) : ((f)->flags &= ~FLOW_TC_PP_ALPROTO_DETECT_DONE)) -#define FLOW_RESET_PE_DONE(f, dir) (((dir) & STREAM_TOSERVER) ? ((f)->flags &= ~FLOW_TS_PE_ALPROTO_DETECT_DONE) : ((f)->flags &= ~FLOW_TC_PE_ALPROTO_DETECT_DONE)) +#define FLOW_IS_PM_DONE(f, dir) \ + (((dir)&STREAM_TOSERVER) ? ((f)->flags & FLOW_TS_PM_ALPROTO_DETECT_DONE) \ + : ((f)->flags & FLOW_TC_PM_ALPROTO_DETECT_DONE)) +#define FLOW_IS_PP_DONE(f, dir) \ + (((dir)&STREAM_TOSERVER) ? ((f)->flags & FLOW_TS_PP_ALPROTO_DETECT_DONE) \ + : ((f)->flags & FLOW_TC_PP_ALPROTO_DETECT_DONE)) +#define FLOW_IS_PE_DONE(f, dir) \ + (((dir)&STREAM_TOSERVER) ? ((f)->flags & FLOW_TS_PE_ALPROTO_DETECT_DONE) \ + : ((f)->flags & FLOW_TC_PE_ALPROTO_DETECT_DONE)) + +#define FLOW_SET_PM_DONE(f, dir) \ + (((dir)&STREAM_TOSERVER) ? ((f)->flags |= FLOW_TS_PM_ALPROTO_DETECT_DONE) \ + : ((f)->flags |= FLOW_TC_PM_ALPROTO_DETECT_DONE)) +#define FLOW_SET_PP_DONE(f, dir) \ + (((dir)&STREAM_TOSERVER) ? ((f)->flags |= FLOW_TS_PP_ALPROTO_DETECT_DONE) \ + : ((f)->flags |= FLOW_TC_PP_ALPROTO_DETECT_DONE)) +#define FLOW_SET_PE_DONE(f, dir) \ + (((dir)&STREAM_TOSERVER) ? ((f)->flags |= FLOW_TS_PE_ALPROTO_DETECT_DONE) \ + : ((f)->flags |= FLOW_TC_PE_ALPROTO_DETECT_DONE)) + +#define FLOW_RESET_PM_DONE(f, dir) \ + (((dir)&STREAM_TOSERVER) ? ((f)->flags &= ~FLOW_TS_PM_ALPROTO_DETECT_DONE) \ + : ((f)->flags &= ~FLOW_TC_PM_ALPROTO_DETECT_DONE)) +#define FLOW_RESET_PP_DONE(f, dir) \ + (((dir)&STREAM_TOSERVER) ? ((f)->flags &= ~FLOW_TS_PP_ALPROTO_DETECT_DONE) \ + : ((f)->flags &= ~FLOW_TC_PP_ALPROTO_DETECT_DONE)) +#define FLOW_RESET_PE_DONE(f, dir) \ + (((dir)&STREAM_TOSERVER) ? ((f)->flags &= ~FLOW_TS_PE_ALPROTO_DETECT_DONE) \ + : ((f)->flags &= ~FLOW_TC_PE_ALPROTO_DETECT_DONE)) /* global flow config */ -typedef struct FlowCnf_ -{ +typedef struct FlowCnf_ { uint32_t hash_rand; uint32_t hash_size; uint32_t prealloc; @@ -298,8 +311,7 @@ typedef struct FlowCnf_ } FlowConfig; /* Hash key for the flow hash */ -typedef struct FlowKey_ -{ +typedef struct FlowKey_ { Address src, dst; Port sp, dp; uint8_t proto; @@ -310,9 +322,9 @@ typedef struct FlowKey_ typedef struct FlowAddress_ { union { - uint32_t address_un_data32[4]; /* type-specific field */ - uint16_t address_un_data16[8]; /* type-specific field */ - uint8_t address_un_data8[16]; /* type-specific field */ + uint32_t address_un_data32[4]; /* type-specific field */ + uint16_t address_un_data16[8]; /* type-specific field */ + uint8_t address_un_data8[16]; /* type-specific field */ } address; } FlowAddress; @@ -345,16 +357,15 @@ typedef uint16_t FlowThreadId; * of a flow. This is why we can access those without protection of the lock. */ -typedef struct Flow_ -{ +typedef struct Flow_ { /* flow "header", used for hashing and flow lookup. Static after init, * so safe to look at without lock */ FlowAddress src, dst; union { - Port sp; /**< tcp/udp source port */ + Port sp; /**< tcp/udp source port */ struct { - uint8_t type; /**< icmp type */ - uint8_t code; /**< icmp code */ + uint8_t type; /**< icmp type */ + uint8_t code; /**< icmp code */ } icmp_s; struct { @@ -362,10 +373,10 @@ typedef struct Flow_ } esp; }; union { - Port dp; /**< tcp/udp destination port */ + Port dp; /**< tcp/udp destination port */ struct { - uint8_t type; /**< icmp type */ - uint8_t code; /**< icmp code */ + uint8_t type; /**< icmp type */ + uint8_t code; /**< icmp code */ } icmp_d; }; uint8_t proto; @@ -377,8 +388,8 @@ typedef struct Flow_ /* track toserver/toclient flow timeout needs */ union { struct { - uint8_t ffr_ts:4; - uint8_t ffr_tc:4; + uint8_t ffr_ts : 4; + uint8_t ffr_tc : 4; }; uint8_t ffr; }; @@ -416,9 +427,9 @@ typedef struct Flow_ uint32_t probing_parser_toserver_alproto_masks; uint32_t probing_parser_toclient_alproto_masks; - uint32_t flags; /**< generic flags */ + uint32_t flags; /**< generic flags */ - uint16_t file_flags; /**< file tracking/extraction flags */ + uint16_t file_flags; /**< file tracking/extraction flags */ /** destination port to be used in protocol detection. This is meant * for use with STARTTLS and HTTP CONNECT detection */ @@ -432,7 +443,7 @@ typedef struct Flow_ #elif defined FLOWLOCK_MUTEX SCMutex m; #else - #error Enable FLOWLOCK_RWLOCK or FLOWLOCK_MUTEX +#error Enable FLOWLOCK_RWLOCK or FLOWLOCK_MUTEX #endif /** protocol specific data pointer, e.g. for TcpSession */ @@ -470,8 +481,8 @@ typedef struct Flow_ /** application level storage ptrs. * */ - AppLayerParserState *alparser; /**< parser internal state */ - void *alstate; /**< application layer state */ + AppLayerParserState *alparser; /**< parser internal state */ + void *alstate; /**< application layer state */ /** toclient sgh for this flow. Only use when FLOW_SGH_TOCLIENT flow flag * has been set. */ @@ -522,8 +533,8 @@ typedef struct FlowProtoFreeFunc_ { } FlowProtoFreeFunc; typedef struct FlowBypassInfo_ { - bool (* BypassUpdate)(Flow *f, void *data, time_t tsec); - void (* BypassFree)(void *data); + bool (*BypassUpdate)(Flow *f, void *data, time_t tsec); + void (*BypassFree)(void *data); void *bypass_data; uint64_t tosrcpktcnt; uint64_t tosrcbytecnt; @@ -547,7 +558,7 @@ typedef struct FlowLookupStruct_ // TODO name * and calc the hash value to be used in the lookup and autofp flow * balancing. */ void FlowSetupPacket(Packet *p); -void FlowHandlePacket (ThreadVars *, FlowLookupStruct *, Packet *); +void FlowHandlePacket(ThreadVars *, FlowLookupStruct *, Packet *); void FlowInitConfig(bool); void FlowReset(void); void FlowShutdown(void); @@ -600,7 +611,7 @@ static inline void *FlowGetAppState(const Flow *f) * * \param f Flow to set the flag in */ -static inline void FlowSetNoPacketInspectionFlag(Flow *f) +static inline void FlowSetNoPacketInspectionFlag(Flow *f) { SCEnter(); @@ -691,7 +702,7 @@ static inline bool FlowIsBypassed(const Flow *f) return false; } -int FlowClearMemory(Flow *,uint8_t ); +int FlowClearMemory(Flow *, uint8_t); AppProto FlowGetAppProtocol(const Flow *f); void *FlowGetAppState(const Flow *f); diff --git a/src/host-bit.c b/src/host-bit.c index 3b03d50efe8e..c98280643e92 100644 --- a/src/host-bit.c +++ b/src/host-bit.c @@ -63,11 +63,11 @@ int HostHasHostBits(Host *host) } /** \retval 1 host timed out wrt xbits - * \retval 0 host still has active (non-expired) xbits */ + * \retval 0 host still has active (non-expired) xbits */ int HostBitsTimedoutCheck(Host *h, SCTime_t ts) { GenericVar *gv = HostGetStorageById(h, host_bit_id); - for ( ; gv != NULL; gv = gv->next) { + for (; gv != NULL; gv = gv->next) { if (gv->type == DETECT_XBITS) { XBit *xb = (XBit *)gv; if (xb->expire > (uint32_t)SCTIME_SECS(ts)) @@ -81,7 +81,7 @@ int HostBitsTimedoutCheck(Host *h, SCTime_t ts) static XBit *HostBitGet(Host *h, uint32_t idx) { GenericVar *gv = HostGetStorageById(h, host_bit_id); - for ( ; gv != NULL; gv = gv->next) { + for (; gv != NULL; gv = gv->next) { if (gv->type == DETECT_XBITS && gv->idx == idx) { return (XBit *)gv; } @@ -108,7 +108,7 @@ static void HostBitAdd(Host *h, uint32_t idx, uint32_t expire) GenericVarAppend(&gv, (GenericVar *)fb); HostSetStorageById(h, host_bit_id, gv); - // bit already set, lets update it's time + // bit already set, lets update it's time } else { fb->expire = expire; } @@ -159,7 +159,7 @@ int HostBitIsset(Host *h, uint32_t idx, uint32_t ts) XBit *fb = HostBitGet(h, idx); if (fb != NULL) { if (fb->expire < ts) { - HostBitRemove(h,idx); + HostBitRemove(h, idx); return 0; } return 1; @@ -175,7 +175,7 @@ int HostBitIsnotset(Host *h, uint32_t idx, uint32_t ts) } if (fb->expire < ts) { - HostBitRemove(h,idx); + HostBitRemove(h, idx); return 1; } return 0; @@ -190,7 +190,7 @@ int HostBitList(Host *h, XBit **iter) gv = gv->next; } - for ( ; gv != NULL; gv = gv->next) { + for (; gv != NULL; gv = gv->next) { if (gv->type == DETECT_XBITS) { *iter = (XBit *)gv; return 1; @@ -202,7 +202,7 @@ int HostBitList(Host *h, XBit **iter) /* TESTS */ #ifdef UNITTESTS -static int HostBitTest01 (void) +static int HostBitTest01(void) { int ret = 0; @@ -213,7 +213,7 @@ static int HostBitTest01 (void) HostBitAdd(h, 0, 0); - XBit *fb = HostBitGet(h,0); + XBit *fb = HostBitGet(h, 0); if (fb != NULL) ret = 1; @@ -223,7 +223,7 @@ static int HostBitTest01 (void) return ret; } -static int HostBitTest02 (void) +static int HostBitTest02(void) { int ret = 0; @@ -232,7 +232,7 @@ static int HostBitTest02 (void) if (h == NULL) goto end; - XBit *fb = HostBitGet(h,0); + XBit *fb = HostBitGet(h, 0); if (fb == NULL) ret = 1; @@ -242,7 +242,7 @@ static int HostBitTest02 (void) return ret; } -static int HostBitTest03 (void) +static int HostBitTest03(void) { int ret = 0; @@ -253,7 +253,7 @@ static int HostBitTest03 (void) HostBitAdd(h, 0, 30); - XBit *fb = HostBitGet(h,0); + XBit *fb = HostBitGet(h, 0); if (fb == NULL) { printf("fb == NULL although it was just added: "); goto end; @@ -261,7 +261,7 @@ static int HostBitTest03 (void) HostBitRemove(h, 0); - fb = HostBitGet(h,0); + fb = HostBitGet(h, 0); if (fb != NULL) { printf("fb != NULL although it was just removed: "); goto end; @@ -275,7 +275,7 @@ static int HostBitTest03 (void) return ret; } -static int HostBitTest04 (void) +static int HostBitTest04(void) { int ret = 0; @@ -289,7 +289,7 @@ static int HostBitTest04 (void) HostBitAdd(h, 2, 30); HostBitAdd(h, 3, 30); - XBit *fb = HostBitGet(h,0); + XBit *fb = HostBitGet(h, 0); if (fb != NULL) ret = 1; @@ -299,7 +299,7 @@ static int HostBitTest04 (void) return ret; } -static int HostBitTest05 (void) +static int HostBitTest05(void) { int ret = 0; @@ -313,7 +313,7 @@ static int HostBitTest05 (void) HostBitAdd(h, 2, 30); HostBitAdd(h, 3, 30); - XBit *fb = HostBitGet(h,1); + XBit *fb = HostBitGet(h, 1); if (fb != NULL) ret = 1; @@ -323,7 +323,7 @@ static int HostBitTest05 (void) return ret; } -static int HostBitTest06 (void) +static int HostBitTest06(void) { int ret = 0; @@ -337,7 +337,7 @@ static int HostBitTest06 (void) HostBitAdd(h, 2, 90); HostBitAdd(h, 3, 90); - XBit *fb = HostBitGet(h,2); + XBit *fb = HostBitGet(h, 2); if (fb != NULL) ret = 1; @@ -347,7 +347,7 @@ static int HostBitTest06 (void) return ret; } -static int HostBitTest07 (void) +static int HostBitTest07(void) { int ret = 0; @@ -361,7 +361,7 @@ static int HostBitTest07 (void) HostBitAdd(h, 2, 90); HostBitAdd(h, 3, 90); - XBit *fb = HostBitGet(h,3); + XBit *fb = HostBitGet(h, 3); if (fb != NULL) ret = 1; @@ -371,7 +371,7 @@ static int HostBitTest07 (void) return ret; } -static int HostBitTest08 (void) +static int HostBitTest08(void) { int ret = 0; @@ -385,13 +385,13 @@ static int HostBitTest08 (void) HostBitAdd(h, 2, 90); HostBitAdd(h, 3, 90); - XBit *fb = HostBitGet(h,0); + XBit *fb = HostBitGet(h, 0); if (fb == NULL) goto end; - HostBitRemove(h,0); + HostBitRemove(h, 0); - fb = HostBitGet(h,0); + fb = HostBitGet(h, 0); if (fb != NULL) { printf("fb != NULL even though it was removed: "); goto end; @@ -404,7 +404,7 @@ static int HostBitTest08 (void) return ret; } -static int HostBitTest09 (void) +static int HostBitTest09(void) { int ret = 0; @@ -418,13 +418,13 @@ static int HostBitTest09 (void) HostBitAdd(h, 2, 90); HostBitAdd(h, 3, 90); - XBit *fb = HostBitGet(h,1); + XBit *fb = HostBitGet(h, 1); if (fb == NULL) goto end; - HostBitRemove(h,1); + HostBitRemove(h, 1); - fb = HostBitGet(h,1); + fb = HostBitGet(h, 1); if (fb != NULL) { printf("fb != NULL even though it was removed: "); goto end; @@ -437,7 +437,7 @@ static int HostBitTest09 (void) return ret; } -static int HostBitTest10 (void) +static int HostBitTest10(void) { int ret = 0; @@ -451,13 +451,13 @@ static int HostBitTest10 (void) HostBitAdd(h, 2, 90); HostBitAdd(h, 3, 90); - XBit *fb = HostBitGet(h,2); + XBit *fb = HostBitGet(h, 2); if (fb == NULL) goto end; - HostBitRemove(h,2); + HostBitRemove(h, 2); - fb = HostBitGet(h,2); + fb = HostBitGet(h, 2); if (fb != NULL) { printf("fb != NULL even though it was removed: "); goto end; @@ -470,7 +470,7 @@ static int HostBitTest10 (void) return ret; } -static int HostBitTest11 (void) +static int HostBitTest11(void) { int ret = 0; @@ -484,13 +484,13 @@ static int HostBitTest11 (void) HostBitAdd(h, 2, 90); HostBitAdd(h, 3, 90); - XBit *fb = HostBitGet(h,3); + XBit *fb = HostBitGet(h, 3); if (fb == NULL) goto end; - HostBitRemove(h,3); + HostBitRemove(h, 3); - fb = HostBitGet(h,3); + fb = HostBitGet(h, 3); if (fb != NULL) { printf("fb != NULL even though it was removed: "); goto end; diff --git a/src/host-queue.c b/src/host-queue.c index f81cb54c7713..8c7af86ccafd 100644 --- a/src/host-queue.c +++ b/src/host-queue.c @@ -30,7 +30,7 @@ #include "util-debug.h" #include "util-print.h" -HostQueue *HostQueueInit (HostQueue *q) +HostQueue *HostQueueInit(HostQueue *q) { if (q != NULL) { memset(q, 0, sizeof(HostQueue)); @@ -55,7 +55,7 @@ HostQueue *HostQueueNew(void) * * \param q the host queue to destroy */ -void HostQueueDestroy (HostQueue *q) +void HostQueueDestroy(HostQueue *q) { HQLOCK_DESTROY(q); } @@ -66,7 +66,7 @@ void HostQueueDestroy (HostQueue *q) * \param q queue * \param h host */ -void HostEnqueue (HostQueue *q, Host *h) +void HostEnqueue(HostQueue *q, Host *h) { #ifdef DEBUG BUG_ON(q == NULL || h == NULL); @@ -79,7 +79,7 @@ void HostEnqueue (HostQueue *q, Host *h) h->lnext = q->top; q->top->lprev = h; q->top = h; - /* only host */ + /* only host */ } else { q->top = h; q->bot = h; @@ -99,7 +99,7 @@ void HostEnqueue (HostQueue *q, Host *h) * * \retval h host or NULL if empty list. */ -Host *HostDequeue (HostQueue *q) +Host *HostDequeue(HostQueue *q) { HQLOCK_LOCK(q); @@ -113,7 +113,7 @@ Host *HostDequeue (HostQueue *q) if (q->bot->lprev != NULL) { q->bot = q->bot->lprev; q->bot->lnext = NULL; - /* just the one we remove, so now empty */ + /* just the one we remove, so now empty */ } else { q->top = NULL; q->bot = NULL; @@ -140,4 +140,3 @@ uint32_t HostQueueLen(HostQueue *q) HQLOCK_UNLOCK(q); return len; } - diff --git a/src/host-queue.h b/src/host-queue.h index 2edd169d22f2..244d6f25229d 100644 --- a/src/host-queue.h +++ b/src/host-queue.h @@ -32,14 +32,13 @@ #define HQLOCK_MUTEX #ifdef HQLOCK_SPIN - #ifdef HQLOCK_MUTEX - #error Cannot enable both HQLOCK_SPIN and HQLOCK_MUTEX - #endif +#ifdef HQLOCK_MUTEX +#error Cannot enable both HQLOCK_SPIN and HQLOCK_MUTEX +#endif #endif /* Define a queue for storing hosts */ -typedef struct HostQueue_ -{ +typedef struct HostQueue_ { Host *top; Host *bot; uint32_t len; @@ -51,34 +50,33 @@ typedef struct HostQueue_ #elif defined HQLOCK_SPIN SCSpinlock s; #else - #error Enable HQLOCK_SPIN or HQLOCK_MUTEX +#error Enable HQLOCK_SPIN or HQLOCK_MUTEX #endif } HostQueue; #ifdef HQLOCK_SPIN - #define HQLOCK_INIT(q) SCSpinInit(&(q)->s, 0) - #define HQLOCK_DESTROY(q) SCSpinDestroy(&(q)->s) - #define HQLOCK_LOCK(q) SCSpinLock(&(q)->s) - #define HQLOCK_TRYLOCK(q) SCSpinTrylock(&(q)->s) - #define HQLOCK_UNLOCK(q) SCSpinUnlock(&(q)->s) +#define HQLOCK_INIT(q) SCSpinInit(&(q)->s, 0) +#define HQLOCK_DESTROY(q) SCSpinDestroy(&(q)->s) +#define HQLOCK_LOCK(q) SCSpinLock(&(q)->s) +#define HQLOCK_TRYLOCK(q) SCSpinTrylock(&(q)->s) +#define HQLOCK_UNLOCK(q) SCSpinUnlock(&(q)->s) #elif defined HQLOCK_MUTEX - #define HQLOCK_INIT(q) SCMutexInit(&(q)->m, NULL) - #define HQLOCK_DESTROY(q) SCMutexDestroy(&(q)->m) - #define HQLOCK_LOCK(q) SCMutexLock(&(q)->m) - #define HQLOCK_TRYLOCK(q) SCMutexTrylock(&(q)->m) - #define HQLOCK_UNLOCK(q) SCMutexUnlock(&(q)->m) +#define HQLOCK_INIT(q) SCMutexInit(&(q)->m, NULL) +#define HQLOCK_DESTROY(q) SCMutexDestroy(&(q)->m) +#define HQLOCK_LOCK(q) SCMutexLock(&(q)->m) +#define HQLOCK_TRYLOCK(q) SCMutexTrylock(&(q)->m) +#define HQLOCK_UNLOCK(q) SCMutexUnlock(&(q)->m) #else - #error Enable HQLOCK_SPIN or HQLOCK_MUTEX +#error Enable HQLOCK_SPIN or HQLOCK_MUTEX #endif /* prototypes */ HostQueue *HostQueueNew(void); HostQueue *HostQueueInit(HostQueue *); -void HostQueueDestroy (HostQueue *); +void HostQueueDestroy(HostQueue *); -void HostEnqueue (HostQueue *, Host *); -Host *HostDequeue (HostQueue *); +void HostEnqueue(HostQueue *, Host *); +Host *HostDequeue(HostQueue *); uint32_t HostQueueLen(HostQueue *); #endif /* __HOST_QUEUE_H__ */ - diff --git a/src/host-storage.c b/src/host-storage.c index 234c67112edf..6e6a379ddd45 100644 --- a/src/host-storage.c +++ b/src/host-storage.c @@ -112,7 +112,6 @@ void HostFreeStorage(Host *h) StorageFreeAll(h->storage, STORAGE_HOST); } - #ifdef UNITTESTS static void *StorageTestAlloc(unsigned int size) diff --git a/src/host-timeout.c b/src/host-timeout.c index 8542d5f78abb..37549a85aa2b 100644 --- a/src/host-timeout.c +++ b/src/host-timeout.c @@ -108,7 +108,7 @@ static uint32_t HostHashRowTimeout(HostHashRow *hb, Host *h, SCTime_t ts) h->hnext = NULL; h->hprev = NULL; - HostClearMemory (h); + HostClearMemory(h); /* no one is referring to this host, use_cnt 0, removed from hash * so we can unlock it and move it back to the spare queue. */ @@ -160,4 +160,3 @@ uint32_t HostTimeoutHash(SCTime_t ts) return cnt; } - diff --git a/src/host-timeout.h b/src/host-timeout.h index 044c44d970bb..7b8dc75e0f33 100644 --- a/src/host-timeout.h +++ b/src/host-timeout.h @@ -30,4 +30,3 @@ uint32_t HostGetSpareCount(void); uint32_t HostGetActiveCount(void); #endif - diff --git a/src/host.c b/src/host.c index 37c0f4dad479..b63c5ed3f7bb 100644 --- a/src/host.c +++ b/src/host.c @@ -52,9 +52,9 @@ HostHashRow *host_hash; static HostQueue host_spare_q; HostConfig host_config; -SC_ATOMIC_DECLARE(uint64_t,host_memuse); -SC_ATOMIC_DECLARE(uint32_t,host_counter); -SC_ATOMIC_DECLARE(uint32_t,host_prune_idx); +SC_ATOMIC_DECLARE(uint64_t, host_memuse); +SC_ATOMIC_DECLARE(uint32_t, host_counter); +SC_ATOMIC_DECLARE(uint32_t, host_prune_idx); /** size of the host object. Maybe updated in HostInitConfig to include * the storage APIs additions. */ @@ -105,7 +105,7 @@ uint32_t HostSpareQueueGetSize(void) void HostMoveToSpare(Host *h) { HostEnqueue(&host_spare_q, h); - (void) SC_ATOMIC_SUB(host_counter, 1); + (void)SC_ATOMIC_SUB(host_counter, 1); } Host *HostAlloc(void) @@ -113,7 +113,7 @@ Host *HostAlloc(void) if (!(HOST_CHECK_MEMCAP(g_host_size))) { return NULL; } - (void) SC_ATOMIC_ADD(host_memuse, g_host_size); + (void)SC_ATOMIC_ADD(host_memuse, g_host_size); Host *h = SCCalloc(1, g_host_size); if (unlikely(h == NULL)) @@ -133,7 +133,7 @@ void HostFree(Host *h) HostClearMemory(h); SCMutexDestroy(&h->m); SCFree(h); - (void) SC_ATOMIC_SUB(host_memuse, g_host_size); + (void)SC_ATOMIC_SUB(host_memuse, g_host_size); } } @@ -165,7 +165,7 @@ void HostClearMemory(Host *h) } #define HOST_DEFAULT_HASHSIZE 4096 -#define HOST_DEFAULT_MEMCAP 16777216 +#define HOST_DEFAULT_MEMCAP 16777216 #define HOST_DEFAULT_PREALLOC 1000 /** \brief initialize the configuration @@ -178,8 +178,8 @@ void HostInitConfig(bool quiet) g_host_size = (uint16_t)(sizeof(Host) + HostStorageSize()); } - memset(&host_config, 0, sizeof(host_config)); - //SC_ATOMIC_INIT(flow_flags); + memset(&host_config, 0, sizeof(host_config)); + // SC_ATOMIC_INIT(flow_flags); SC_ATOMIC_INIT(host_counter); SC_ATOMIC_INIT(host_memuse); SC_ATOMIC_INIT(host_prune_idx); @@ -187,9 +187,9 @@ void HostInitConfig(bool quiet) HostQueueInit(&host_spare_q); /* set defaults */ - host_config.hash_rand = (uint32_t)RandomGet(); - host_config.hash_size = HOST_DEFAULT_HASHSIZE; - host_config.prealloc = HOST_DEFAULT_PREALLOC; + host_config.hash_rand = (uint32_t)RandomGet(); + host_config.hash_size = HOST_DEFAULT_HASHSIZE; + host_config.prealloc = HOST_DEFAULT_PREALLOC; SC_ATOMIC_SET(host_config.memcap, HOST_DEFAULT_MEMCAP); /* Check if we have memcap and hash_size defined at config */ @@ -209,23 +209,21 @@ void HostInitConfig(bool quiet) } } if ((ConfGet("host.hash-size", &conf_val)) == 1) { - if (StringParseUint32(&configval, 10, strlen(conf_val), - conf_val) > 0) { + if (StringParseUint32(&configval, 10, strlen(conf_val), conf_val) > 0) { host_config.hash_size = configval; } } if ((ConfGet("host.prealloc", &conf_val)) == 1) { - if (StringParseUint32(&configval, 10, strlen(conf_val), - conf_val) > 0) { + if (StringParseUint32(&configval, 10, strlen(conf_val), conf_val) > 0) { host_config.prealloc = configval; } else { - WarnInvalidConfEntry("host.prealloc", "%"PRIu32, host_config.prealloc); + WarnInvalidConfEntry("host.prealloc", "%" PRIu32, host_config.prealloc); } } - SCLogDebug("Host config from suricata.yaml: memcap: %"PRIu64", hash-size: " - "%"PRIu32", prealloc: %"PRIu32, SC_ATOMIC_GET(host_config.memcap), - host_config.hash_size, host_config.prealloc); + SCLogDebug("Host config from suricata.yaml: memcap: %" PRIu64 ", hash-size: " + "%" PRIu32 ", prealloc: %" PRIu32, + SC_ATOMIC_GET(host_config.memcap), host_config.hash_size, host_config.prealloc); /* alloc hash memory */ uint64_t hash_size = host_config.hash_size * sizeof(HostHashRow); @@ -248,13 +246,12 @@ void HostInitConfig(bool quiet) for (i = 0; i < host_config.hash_size; i++) { HRLOCK_INIT(&host_hash[i]); } - (void) SC_ATOMIC_ADD(host_memuse, (host_config.hash_size * sizeof(HostHashRow))); + (void)SC_ATOMIC_ADD(host_memuse, (host_config.hash_size * sizeof(HostHashRow))); if (!quiet) { - SCLogConfig("allocated %"PRIu64" bytes of memory for the host hash... " - "%" PRIu32 " buckets of size %" PRIuMAX "", - SC_ATOMIC_GET(host_memuse), host_config.hash_size, - (uintmax_t)sizeof(HostHashRow)); + SCLogConfig("allocated %" PRIu64 " bytes of memory for the host hash... " + "%" PRIu32 " buckets of size %" PRIuMAX "", + SC_ATOMIC_GET(host_memuse), host_config.hash_size, (uintmax_t)sizeof(HostHashRow)); } /* pre allocate hosts */ @@ -273,13 +270,13 @@ void HostInitConfig(bool quiet) SCLogError("preallocating host failed: %s", strerror(errno)); exit(EXIT_FAILURE); } - HostEnqueue(&host_spare_q,h); + HostEnqueue(&host_spare_q, h); } if (!quiet) { - SCLogConfig("preallocated %" PRIu32 " hosts of size %" PRIu16 "", - host_spare_q.len, g_host_size); - SCLogConfig("host memory usage: %"PRIu64" bytes, maximum: %"PRIu64, + SCLogConfig("preallocated %" PRIu32 " hosts of size %" PRIu16 "", host_spare_q.len, + g_host_size); + SCLogConfig("host memory usage: %" PRIu64 " bytes, maximum: %" PRIu64, SC_ATOMIC_GET(host_memuse), SC_ATOMIC_GET(host_config.memcap)); } @@ -288,14 +285,14 @@ void HostInitConfig(bool quiet) /** \brief print some host stats * \warning Not thread safe */ -void HostPrintStats (void) +void HostPrintStats(void) { #ifdef HOSTBITS_STATS SCLogPerf("hostbits added: %" PRIu32 ", removed: %" PRIu32 ", max memory usage: %" PRIu32 "", - hostbits_added, hostbits_removed, hostbits_memuse_max); + hostbits_added, hostbits_removed, hostbits_memuse_max); #endif /* HOSTBITS_STATS */ - SCLogPerf("host memory usage: %"PRIu64" bytes, maximum: %"PRIu64, - SC_ATOMIC_GET(host_memuse), SC_ATOMIC_GET(host_config.memcap)); + SCLogPerf("host memory usage: %" PRIu64 " bytes, maximum: %" PRIu64, SC_ATOMIC_GET(host_memuse), + SC_ATOMIC_GET(host_config.memcap)); return; } @@ -309,7 +306,7 @@ void HostShutdown(void) HostPrintStats(); /* free spare queue */ - while((h = HostDequeue(&host_spare_q))) { + while ((h = HostDequeue(&host_spare_q))) { HostFree(h); } @@ -328,7 +325,7 @@ void HostShutdown(void) SCFreeAligned(host_hash); host_hash = NULL; } - (void) SC_ATOMIC_SUB(host_memuse, host_config.hash_size * sizeof(HostHashRow)); + (void)SC_ATOMIC_SUB(host_memuse, host_config.hash_size * sizeof(HostHashRow)); HostQueueDestroy(&host_spare_q); return; } @@ -428,12 +425,12 @@ static Host *HostGetNew(Address *a) /* If we reached the max memcap, we get a used host */ if (!(HOST_CHECK_MEMCAP(g_host_size))) { /* declare state of emergency */ - //if (!(SC_ATOMIC_GET(host_flags) & HOST_EMERGENCY)) { + // if (!(SC_ATOMIC_GET(host_flags) & HOST_EMERGENCY)) { // SC_ATOMIC_OR(host_flags, HOST_EMERGENCY); - /* under high load, waking up the flow mgr each time leads - * to high cpu usage. Flows are not timed out much faster if - * we check a 1000 times a second. */ + /* under high load, waking up the flow mgr each time leads + * to high cpu usage. Flows are not timed out much faster if + * we check a 1000 times a second. */ // FlowWakeupFlowManagerThread(); //} @@ -458,7 +455,7 @@ static Host *HostGetNew(Address *a) /* host is initialized (recycled) but *unlocked* */ } - (void) SC_ATOMIC_ADD(host_counter, 1); + (void)SC_ATOMIC_ADD(host_counter, 1); SCMutexLock(&h->m); return h; } @@ -466,12 +463,12 @@ static Host *HostGetNew(Address *a) static void HostInit(Host *h, Address *a) { COPY_ADDRESS(a, &h->a); - (void) HostIncrUsecnt(h); + (void)HostIncrUsecnt(h); } void HostRelease(Host *h) { - (void) HostDecrUsecnt(h); + (void)HostDecrUsecnt(h); SCMutexUnlock(&h->m); } @@ -485,7 +482,6 @@ void HostUnlock(Host *h) SCMutexUnlock(&h->m); } - /* HostGetHostFromHash * * Hash retrieval function for hosts. Looks up the hash bucket containing the @@ -494,7 +490,7 @@ void HostUnlock(Host *h) * * returns a *LOCKED* host or NULL */ -Host *HostGetHostFromHash (Address *a) +Host *HostGetHostFromHash(Address *a) { Host *h = NULL; @@ -517,7 +513,7 @@ Host *HostGetHostFromHash (Address *a) hb->tail = h; /* got one, now lock, initialize and return */ - HostInit(h,a); + HostInit(h, a); HRLOCK_UNLOCK(hb); return h; @@ -547,7 +543,7 @@ Host *HostGetHostFromHash (Address *a) h->hprev = ph; /* initialize and return */ - HostInit(h,a); + HostInit(h, a); HRLOCK_UNLOCK(hb); return h; @@ -573,7 +569,7 @@ Host *HostGetHostFromHash (Address *a) /* found our host, lock & return */ SCMutexLock(&h->m); - (void) HostIncrUsecnt(h); + (void)HostIncrUsecnt(h); HRLOCK_UNLOCK(hb); return h; } @@ -582,7 +578,7 @@ Host *HostGetHostFromHash (Address *a) /* lock & return */ SCMutexLock(&h->m); - (void) HostIncrUsecnt(h); + (void)HostIncrUsecnt(h); HRLOCK_UNLOCK(hb); return h; } @@ -593,7 +589,7 @@ Host *HostGetHostFromHash (Address *a) * * \retval h *LOCKED* host or NULL */ -Host *HostLookupHostFromHash (Address *a) +Host *HostLookupHostFromHash(Address *a) { Host *h = NULL; @@ -642,7 +638,7 @@ Host *HostLookupHostFromHash (Address *a) /* found our host, lock & return */ SCMutexLock(&h->m); - (void) HostIncrUsecnt(h); + (void)HostIncrUsecnt(h); HRLOCK_UNLOCK(hb); return h; } @@ -651,7 +647,7 @@ Host *HostLookupHostFromHash (Address *a) /* lock & return */ SCMutexLock(&h->m); - (void) HostIncrUsecnt(h); + (void)HostIncrUsecnt(h); HRLOCK_UNLOCK(hb); return h; } @@ -714,11 +710,11 @@ static Host *HostGetUsedHost(void) h->hprev = NULL; HRLOCK_UNLOCK(hb); - HostClearMemory (h); + HostClearMemory(h); SCMutexUnlock(&h->m); - (void) SC_ATOMIC_ADD(host_prune_idx, (host_config.hash_size - cnt)); + (void)SC_ATOMIC_ADD(host_prune_idx, (host_config.hash_size - cnt)); return h; } @@ -729,4 +725,3 @@ void HostRegisterUnittests(void) { RegisterHostStorageTests(); } - diff --git a/src/host.h b/src/host.h index f4f248b5eec6..c1ec9bbbf1d7 100644 --- a/src/host.h +++ b/src/host.h @@ -32,27 +32,27 @@ #define HRLOCK_MUTEX #ifdef HRLOCK_SPIN - #ifdef HRLOCK_MUTEX - #error Cannot enable both HRLOCK_SPIN and HRLOCK_MUTEX - #endif +#ifdef HRLOCK_MUTEX +#error Cannot enable both HRLOCK_SPIN and HRLOCK_MUTEX +#endif #endif #ifdef HRLOCK_SPIN - #define HRLOCK_TYPE SCSpinlock - #define HRLOCK_INIT(fb) SCSpinInit(&(fb)->lock, 0) - #define HRLOCK_DESTROY(fb) SCSpinDestroy(&(fb)->lock) - #define HRLOCK_LOCK(fb) SCSpinLock(&(fb)->lock) - #define HRLOCK_TRYLOCK(fb) SCSpinTrylock(&(fb)->lock) - #define HRLOCK_UNLOCK(fb) SCSpinUnlock(&(fb)->lock) +#define HRLOCK_TYPE SCSpinlock +#define HRLOCK_INIT(fb) SCSpinInit(&(fb)->lock, 0) +#define HRLOCK_DESTROY(fb) SCSpinDestroy(&(fb)->lock) +#define HRLOCK_LOCK(fb) SCSpinLock(&(fb)->lock) +#define HRLOCK_TRYLOCK(fb) SCSpinTrylock(&(fb)->lock) +#define HRLOCK_UNLOCK(fb) SCSpinUnlock(&(fb)->lock) #elif defined HRLOCK_MUTEX - #define HRLOCK_TYPE SCMutex - #define HRLOCK_INIT(fb) SCMutexInit(&(fb)->lock, NULL) - #define HRLOCK_DESTROY(fb) SCMutexDestroy(&(fb)->lock) - #define HRLOCK_LOCK(fb) SCMutexLock(&(fb)->lock) - #define HRLOCK_TRYLOCK(fb) SCMutexTrylock(&(fb)->lock) - #define HRLOCK_UNLOCK(fb) SCMutexUnlock(&(fb)->lock) +#define HRLOCK_TYPE SCMutex +#define HRLOCK_INIT(fb) SCMutexInit(&(fb)->lock, NULL) +#define HRLOCK_DESTROY(fb) SCMutexDestroy(&(fb)->lock) +#define HRLOCK_LOCK(fb) SCMutexLock(&(fb)->lock) +#define HRLOCK_TRYLOCK(fb) SCMutexTrylock(&(fb)->lock) +#define HRLOCK_UNLOCK(fb) SCMutexUnlock(&(fb)->lock) #else - #error Enable HRLOCK_SPIN or HRLOCK_MUTEX +#error Enable HRLOCK_SPIN or HRLOCK_MUTEX #endif typedef struct Host_ { @@ -89,8 +89,8 @@ typedef struct HostHashRow_ { /** host hash table */ extern HostHashRow *host_hash; -#define HOST_VERBOSE 0 -#define HOST_QUIET 1 +#define HOST_VERBOSE 0 +#define HOST_QUIET 1 typedef struct HostConfig_ { SC_ATOMIC_DECLARE(uint64_t, memcap); @@ -106,45 +106,46 @@ typedef struct HostConfig_ { * \retval 1 it fits * \retval 0 no fit */ -#define HOST_CHECK_MEMCAP(size) \ - ((((uint64_t)SC_ATOMIC_GET(host_memuse) + (uint64_t)(size)) <= SC_ATOMIC_GET(host_config.memcap))) - -#define HostIncrUsecnt(h) \ - (void)SC_ATOMIC_ADD((h)->use_cnt, 1) -#define HostDecrUsecnt(h) \ - (void)SC_ATOMIC_SUB((h)->use_cnt, 1) - -#define HostReference(dst_h_ptr, h) do { \ - if ((h) != NULL) { \ - HostIncrUsecnt((h)); \ - *(dst_h_ptr) = h; \ - } \ +#define HOST_CHECK_MEMCAP(size) \ + ((((uint64_t)SC_ATOMIC_GET(host_memuse) + (uint64_t)(size)) <= \ + SC_ATOMIC_GET(host_config.memcap))) + +#define HostIncrUsecnt(h) (void)SC_ATOMIC_ADD((h)->use_cnt, 1) +#define HostDecrUsecnt(h) (void)SC_ATOMIC_SUB((h)->use_cnt, 1) + +#define HostReference(dst_h_ptr, h) \ + do { \ + if ((h) != NULL) { \ + HostIncrUsecnt((h)); \ + *(dst_h_ptr) = h; \ + } \ } while (0) -#define HostDeReference(src_h_ptr) do { \ - if (*(src_h_ptr) != NULL) { \ - HostDecrUsecnt(*(src_h_ptr)); \ - *(src_h_ptr) = NULL; \ - } \ +#define HostDeReference(src_h_ptr) \ + do { \ + if (*(src_h_ptr) != NULL) { \ + HostDecrUsecnt(*(src_h_ptr)); \ + *(src_h_ptr) = NULL; \ + } \ } while (0) extern HostConfig host_config; -SC_ATOMIC_EXTERN(uint64_t,host_memuse); -SC_ATOMIC_EXTERN(uint32_t,host_counter); -SC_ATOMIC_EXTERN(uint32_t,host_prune_idx); +SC_ATOMIC_EXTERN(uint64_t, host_memuse); +SC_ATOMIC_EXTERN(uint32_t, host_counter); +SC_ATOMIC_EXTERN(uint32_t, host_prune_idx); void HostInitConfig(bool quiet); void HostShutdown(void); void HostCleanup(void); -Host *HostLookupHostFromHash (Address *); -Host *HostGetHostFromHash (Address *); +Host *HostLookupHostFromHash(Address *); +Host *HostGetHostFromHash(Address *); void HostRelease(Host *); void HostLock(Host *); void HostClearMemory(Host *); void HostMoveToSpare(Host *); uint32_t HostSpareQueueGetSize(void); -void HostPrintStats (void); +void HostPrintStats(void); void HostRegisterUnittests(void); @@ -158,4 +159,3 @@ uint64_t HostGetMemcap(void); uint64_t HostGetMemuse(void); #endif /* __HOST_H__ */ - diff --git a/src/ippair-bit.c b/src/ippair-bit.c index 1d3d8fa9bbd2..532b2490360e 100644 --- a/src/ippair-bit.c +++ b/src/ippair-bit.c @@ -63,11 +63,11 @@ int IPPairHasBits(IPPair *ippair) } /** \retval 1 ippair timed out wrt xbits - * \retval 0 ippair still has active (non-expired) xbits */ + * \retval 0 ippair still has active (non-expired) xbits */ int IPPairBitsTimedoutCheck(IPPair *h, SCTime_t ts) { GenericVar *gv = IPPairGetStorageById(h, g_ippair_bit_storage_id); - for ( ; gv != NULL; gv = gv->next) { + for (; gv != NULL; gv = gv->next) { if (gv->type == DETECT_XBITS) { XBit *xb = (XBit *)gv; if (xb->expire > (uint32_t)SCTIME_SECS(ts)) @@ -81,7 +81,7 @@ int IPPairBitsTimedoutCheck(IPPair *h, SCTime_t ts) static XBit *IPPairBitGet(IPPair *h, uint32_t idx) { GenericVar *gv = IPPairGetStorageById(h, g_ippair_bit_storage_id); - for ( ; gv != NULL; gv = gv->next) { + for (; gv != NULL; gv = gv->next) { if (gv->type == DETECT_XBITS && gv->idx == idx) { return (XBit *)gv; } @@ -183,10 +183,9 @@ int IPPairBitIsnotset(IPPair *h, uint32_t idx, uint32_t ts) return 0; } - /* TESTS */ #ifdef UNITTESTS -static int IPPairBitTest01 (void) +static int IPPairBitTest01(void) { int ret = 0; @@ -197,7 +196,7 @@ static int IPPairBitTest01 (void) IPPairBitAdd(h, 0, 0); - XBit *fb = IPPairBitGet(h,0); + XBit *fb = IPPairBitGet(h, 0); if (fb != NULL) ret = 1; @@ -207,7 +206,7 @@ static int IPPairBitTest01 (void) return ret; } -static int IPPairBitTest02 (void) +static int IPPairBitTest02(void) { int ret = 0; @@ -216,7 +215,7 @@ static int IPPairBitTest02 (void) if (h == NULL) goto end; - XBit *fb = IPPairBitGet(h,0); + XBit *fb = IPPairBitGet(h, 0); if (fb == NULL) ret = 1; @@ -226,7 +225,7 @@ static int IPPairBitTest02 (void) return ret; } -static int IPPairBitTest03 (void) +static int IPPairBitTest03(void) { int ret = 0; @@ -237,7 +236,7 @@ static int IPPairBitTest03 (void) IPPairBitAdd(h, 0, 30); - XBit *fb = IPPairBitGet(h,0); + XBit *fb = IPPairBitGet(h, 0); if (fb == NULL) { printf("fb == NULL although it was just added: "); goto end; @@ -245,7 +244,7 @@ static int IPPairBitTest03 (void) IPPairBitRemove(h, 0); - fb = IPPairBitGet(h,0); + fb = IPPairBitGet(h, 0); if (fb != NULL) { printf("fb != NULL although it was just removed: "); goto end; @@ -259,7 +258,7 @@ static int IPPairBitTest03 (void) return ret; } -static int IPPairBitTest04 (void) +static int IPPairBitTest04(void) { int ret = 0; @@ -268,12 +267,12 @@ static int IPPairBitTest04 (void) if (h == NULL) goto end; - IPPairBitAdd(h, 0,30); - IPPairBitAdd(h, 1,30); - IPPairBitAdd(h, 2,30); - IPPairBitAdd(h, 3,30); + IPPairBitAdd(h, 0, 30); + IPPairBitAdd(h, 1, 30); + IPPairBitAdd(h, 2, 30); + IPPairBitAdd(h, 3, 30); - XBit *fb = IPPairBitGet(h,0); + XBit *fb = IPPairBitGet(h, 0); if (fb != NULL) ret = 1; @@ -283,7 +282,7 @@ static int IPPairBitTest04 (void) return ret; } -static int IPPairBitTest05 (void) +static int IPPairBitTest05(void) { int ret = 0; @@ -292,12 +291,12 @@ static int IPPairBitTest05 (void) if (h == NULL) goto end; - IPPairBitAdd(h, 0,90); - IPPairBitAdd(h, 1,90); - IPPairBitAdd(h, 2,90); - IPPairBitAdd(h, 3,90); + IPPairBitAdd(h, 0, 90); + IPPairBitAdd(h, 1, 90); + IPPairBitAdd(h, 2, 90); + IPPairBitAdd(h, 3, 90); - XBit *fb = IPPairBitGet(h,1); + XBit *fb = IPPairBitGet(h, 1); if (fb != NULL) ret = 1; @@ -307,7 +306,7 @@ static int IPPairBitTest05 (void) return ret; } -static int IPPairBitTest06 (void) +static int IPPairBitTest06(void) { int ret = 0; @@ -316,12 +315,12 @@ static int IPPairBitTest06 (void) if (h == NULL) goto end; - IPPairBitAdd(h, 0,90); - IPPairBitAdd(h, 1,90); - IPPairBitAdd(h, 2,90); - IPPairBitAdd(h, 3,90); + IPPairBitAdd(h, 0, 90); + IPPairBitAdd(h, 1, 90); + IPPairBitAdd(h, 2, 90); + IPPairBitAdd(h, 3, 90); - XBit *fb = IPPairBitGet(h,2); + XBit *fb = IPPairBitGet(h, 2); if (fb != NULL) ret = 1; @@ -331,7 +330,7 @@ static int IPPairBitTest06 (void) return ret; } -static int IPPairBitTest07 (void) +static int IPPairBitTest07(void) { int ret = 0; @@ -340,12 +339,12 @@ static int IPPairBitTest07 (void) if (h == NULL) goto end; - IPPairBitAdd(h, 0,90); - IPPairBitAdd(h, 1,90); - IPPairBitAdd(h, 2,90); - IPPairBitAdd(h, 3,90); + IPPairBitAdd(h, 0, 90); + IPPairBitAdd(h, 1, 90); + IPPairBitAdd(h, 2, 90); + IPPairBitAdd(h, 3, 90); - XBit *fb = IPPairBitGet(h,3); + XBit *fb = IPPairBitGet(h, 3); if (fb != NULL) ret = 1; @@ -355,7 +354,7 @@ static int IPPairBitTest07 (void) return ret; } -static int IPPairBitTest08 (void) +static int IPPairBitTest08(void) { int ret = 0; @@ -364,18 +363,18 @@ static int IPPairBitTest08 (void) if (h == NULL) goto end; - IPPairBitAdd(h, 0,90); - IPPairBitAdd(h, 1,90); - IPPairBitAdd(h, 2,90); - IPPairBitAdd(h, 3,90); + IPPairBitAdd(h, 0, 90); + IPPairBitAdd(h, 1, 90); + IPPairBitAdd(h, 2, 90); + IPPairBitAdd(h, 3, 90); - XBit *fb = IPPairBitGet(h,0); + XBit *fb = IPPairBitGet(h, 0); if (fb == NULL) goto end; - IPPairBitRemove(h,0); + IPPairBitRemove(h, 0); - fb = IPPairBitGet(h,0); + fb = IPPairBitGet(h, 0); if (fb != NULL) { printf("fb != NULL even though it was removed: "); goto end; @@ -388,7 +387,7 @@ static int IPPairBitTest08 (void) return ret; } -static int IPPairBitTest09 (void) +static int IPPairBitTest09(void) { int ret = 0; @@ -397,18 +396,18 @@ static int IPPairBitTest09 (void) if (h == NULL) goto end; - IPPairBitAdd(h, 0,90); - IPPairBitAdd(h, 1,90); - IPPairBitAdd(h, 2,90); - IPPairBitAdd(h, 3,90); + IPPairBitAdd(h, 0, 90); + IPPairBitAdd(h, 1, 90); + IPPairBitAdd(h, 2, 90); + IPPairBitAdd(h, 3, 90); - XBit *fb = IPPairBitGet(h,1); + XBit *fb = IPPairBitGet(h, 1); if (fb == NULL) goto end; - IPPairBitRemove(h,1); + IPPairBitRemove(h, 1); - fb = IPPairBitGet(h,1); + fb = IPPairBitGet(h, 1); if (fb != NULL) { printf("fb != NULL even though it was removed: "); goto end; @@ -421,7 +420,7 @@ static int IPPairBitTest09 (void) return ret; } -static int IPPairBitTest10 (void) +static int IPPairBitTest10(void) { int ret = 0; @@ -430,18 +429,18 @@ static int IPPairBitTest10 (void) if (h == NULL) goto end; - IPPairBitAdd(h, 0,90); - IPPairBitAdd(h, 1,90); - IPPairBitAdd(h, 2,90); - IPPairBitAdd(h, 3,90); + IPPairBitAdd(h, 0, 90); + IPPairBitAdd(h, 1, 90); + IPPairBitAdd(h, 2, 90); + IPPairBitAdd(h, 3, 90); - XBit *fb = IPPairBitGet(h,2); + XBit *fb = IPPairBitGet(h, 2); if (fb == NULL) goto end; - IPPairBitRemove(h,2); + IPPairBitRemove(h, 2); - fb = IPPairBitGet(h,2); + fb = IPPairBitGet(h, 2); if (fb != NULL) { printf("fb != NULL even though it was removed: "); goto end; @@ -454,7 +453,7 @@ static int IPPairBitTest10 (void) return ret; } -static int IPPairBitTest11 (void) +static int IPPairBitTest11(void) { int ret = 0; @@ -463,18 +462,18 @@ static int IPPairBitTest11 (void) if (h == NULL) goto end; - IPPairBitAdd(h, 0,90); - IPPairBitAdd(h, 1,90); - IPPairBitAdd(h, 2,90); - IPPairBitAdd(h, 3,90); + IPPairBitAdd(h, 0, 90); + IPPairBitAdd(h, 1, 90); + IPPairBitAdd(h, 2, 90); + IPPairBitAdd(h, 3, 90); - XBit *fb = IPPairBitGet(h,3); + XBit *fb = IPPairBitGet(h, 3); if (fb == NULL) goto end; - IPPairBitRemove(h,3); + IPPairBitRemove(h, 3); - fb = IPPairBitGet(h,3); + fb = IPPairBitGet(h, 3); if (fb != NULL) { printf("fb != NULL even though it was removed: "); goto end; diff --git a/src/ippair-queue.c b/src/ippair-queue.c index dac6b7e9c935..7939b91b88a2 100644 --- a/src/ippair-queue.c +++ b/src/ippair-queue.c @@ -30,7 +30,7 @@ #include "util-debug.h" #include "util-print.h" -IPPairQueue *IPPairQueueInit (IPPairQueue *q) +IPPairQueue *IPPairQueueInit(IPPairQueue *q) { if (q != NULL) { memset(q, 0, sizeof(IPPairQueue)); @@ -55,7 +55,7 @@ IPPairQueue *IPPairQueueNew(void) * * \param q the ippair queue to destroy */ -void IPPairQueueDestroy (IPPairQueue *q) +void IPPairQueueDestroy(IPPairQueue *q) { HQLOCK_DESTROY(q); } @@ -66,7 +66,7 @@ void IPPairQueueDestroy (IPPairQueue *q) * \param q queue * \param h ippair */ -void IPPairEnqueue (IPPairQueue *q, IPPair *h) +void IPPairEnqueue(IPPairQueue *q, IPPair *h) { #ifdef DEBUG BUG_ON(q == NULL || h == NULL); @@ -79,7 +79,7 @@ void IPPairEnqueue (IPPairQueue *q, IPPair *h) h->lnext = q->top; q->top->lprev = h; q->top = h; - /* only ippair */ + /* only ippair */ } else { q->top = h; q->bot = h; @@ -99,7 +99,7 @@ void IPPairEnqueue (IPPairQueue *q, IPPair *h) * * \retval h ippair or NULL if empty list. */ -IPPair *IPPairDequeue (IPPairQueue *q) +IPPair *IPPairDequeue(IPPairQueue *q) { HQLOCK_LOCK(q); @@ -113,7 +113,7 @@ IPPair *IPPairDequeue (IPPairQueue *q) if (q->bot->lprev != NULL) { q->bot = q->bot->lprev; q->bot->lnext = NULL; - /* just the one we remove, so now empty */ + /* just the one we remove, so now empty */ } else { q->top = NULL; q->bot = NULL; diff --git a/src/ippair-queue.h b/src/ippair-queue.h index cc3814b34f44..0c7bd077ed0f 100644 --- a/src/ippair-queue.h +++ b/src/ippair-queue.h @@ -32,14 +32,13 @@ #define HQLOCK_MUTEX #ifdef HQLOCK_SPIN - #ifdef HQLOCK_MUTEX - #error Cannot enable both HQLOCK_SPIN and HQLOCK_MUTEX - #endif +#ifdef HQLOCK_MUTEX +#error Cannot enable both HQLOCK_SPIN and HQLOCK_MUTEX +#endif #endif /* Define a queue for storing ippairs */ -typedef struct IPPairQueue_ -{ +typedef struct IPPairQueue_ { IPPair *top; IPPair *bot; uint32_t len; @@ -51,33 +50,33 @@ typedef struct IPPairQueue_ #elif defined HQLOCK_SPIN SCSpinlock s; #else - #error Enable HQLOCK_SPIN or HQLOCK_MUTEX +#error Enable HQLOCK_SPIN or HQLOCK_MUTEX #endif } IPPairQueue; #ifdef HQLOCK_SPIN - #define HQLOCK_INIT(q) SCSpinInit(&(q)->s, 0) - #define HQLOCK_DESTROY(q) SCSpinDestroy(&(q)->s) - #define HQLOCK_LOCK(q) SCSpinLock(&(q)->s) - #define HQLOCK_TRYLOCK(q) SCSpinTrylock(&(q)->s) - #define HQLOCK_UNLOCK(q) SCSpinUnlock(&(q)->s) +#define HQLOCK_INIT(q) SCSpinInit(&(q)->s, 0) +#define HQLOCK_DESTROY(q) SCSpinDestroy(&(q)->s) +#define HQLOCK_LOCK(q) SCSpinLock(&(q)->s) +#define HQLOCK_TRYLOCK(q) SCSpinTrylock(&(q)->s) +#define HQLOCK_UNLOCK(q) SCSpinUnlock(&(q)->s) #elif defined HQLOCK_MUTEX - #define HQLOCK_INIT(q) SCMutexInit(&(q)->m, NULL) - #define HQLOCK_DESTROY(q) SCMutexDestroy(&(q)->m) - #define HQLOCK_LOCK(q) SCMutexLock(&(q)->m) - #define HQLOCK_TRYLOCK(q) SCMutexTrylock(&(q)->m) - #define HQLOCK_UNLOCK(q) SCMutexUnlock(&(q)->m) +#define HQLOCK_INIT(q) SCMutexInit(&(q)->m, NULL) +#define HQLOCK_DESTROY(q) SCMutexDestroy(&(q)->m) +#define HQLOCK_LOCK(q) SCMutexLock(&(q)->m) +#define HQLOCK_TRYLOCK(q) SCMutexTrylock(&(q)->m) +#define HQLOCK_UNLOCK(q) SCMutexUnlock(&(q)->m) #else - #error Enable HQLOCK_SPIN or HQLOCK_MUTEX +#error Enable HQLOCK_SPIN or HQLOCK_MUTEX #endif /* prototypes */ IPPairQueue *IPPairQueueNew(void); IPPairQueue *IPPairQueueInit(IPPairQueue *); -void IPPairQueueDestroy (IPPairQueue *); +void IPPairQueueDestroy(IPPairQueue *); -void IPPairEnqueue (IPPairQueue *, IPPair *); -IPPair *IPPairDequeue (IPPairQueue *); +void IPPairEnqueue(IPPairQueue *, IPPair *); +IPPair *IPPairDequeue(IPPairQueue *); uint32_t IPPairQueueLen(IPPairQueue *); #endif /* __IPPAIR_QUEUE_H__ */ diff --git a/src/ippair-timeout.c b/src/ippair-timeout.c index 0f510fbd7d5d..ae49e2e71da7 100644 --- a/src/ippair-timeout.c +++ b/src/ippair-timeout.c @@ -112,7 +112,7 @@ static uint32_t IPPairHashRowTimeout(IPPairHashRow *hb, IPPair *h, SCTime_t ts) h->hnext = NULL; h->hprev = NULL; - IPPairClearMemory (h); + IPPairClearMemory(h); /* no one is referring to this ippair, use_cnt 0, removed from hash * so we can unlock it and move it back to the spare queue. */ diff --git a/src/ippair.c b/src/ippair.c index b06f3d164414..8e61dff8a87e 100644 --- a/src/ippair.c +++ b/src/ippair.c @@ -50,9 +50,9 @@ IPPairHashRow *ippair_hash; /** queue with spare ippairs */ static IPPairQueue ippair_spare_q; IPPairConfig ippair_config; -SC_ATOMIC_DECLARE(uint64_t,ippair_memuse); -SC_ATOMIC_DECLARE(uint32_t,ippair_counter); -SC_ATOMIC_DECLARE(uint32_t,ippair_prune_idx); +SC_ATOMIC_DECLARE(uint64_t, ippair_memuse); +SC_ATOMIC_DECLARE(uint32_t, ippair_counter); +SC_ATOMIC_DECLARE(uint32_t, ippair_prune_idx); /** size of the ippair object. Maybe updated in IPPairInitConfig to include * the storage APIs additions. */ @@ -103,7 +103,7 @@ uint32_t IPPairSpareQueueGetSize(void) void IPPairMoveToSpare(IPPair *h) { IPPairEnqueue(&ippair_spare_q, h); - (void) SC_ATOMIC_SUB(ippair_counter, 1); + (void)SC_ATOMIC_SUB(ippair_counter, 1); } IPPair *IPPairAlloc(void) @@ -112,7 +112,7 @@ IPPair *IPPairAlloc(void) return NULL; } - (void) SC_ATOMIC_ADD(ippair_memuse, g_ippair_size); + (void)SC_ATOMIC_ADD(ippair_memuse, g_ippair_size); IPPair *h = SCCalloc(1, g_ippair_size); if (unlikely(h == NULL)) @@ -132,7 +132,7 @@ void IPPairFree(IPPair *h) IPPairClearMemory(h); SCMutexDestroy(&h->m); SCFree(h); - (void) SC_ATOMIC_SUB(ippair_memuse, g_ippair_size); + (void)SC_ATOMIC_SUB(ippair_memuse, g_ippair_size); } } @@ -159,7 +159,7 @@ void IPPairClearMemory(IPPair *h) } #define IPPAIR_DEFAULT_HASHSIZE 4096 -#define IPPAIR_DEFAULT_MEMCAP 16777216 +#define IPPAIR_DEFAULT_MEMCAP 16777216 #define IPPAIR_DEFAULT_PREALLOC 1000 /** \brief initialize the configuration @@ -172,8 +172,8 @@ void IPPairInitConfig(bool quiet) g_ippair_size = (uint16_t)(sizeof(IPPair) + IPPairStorageSize()); } - memset(&ippair_config, 0, sizeof(ippair_config)); - //SC_ATOMIC_INIT(flow_flags); + memset(&ippair_config, 0, sizeof(ippair_config)); + // SC_ATOMIC_INIT(flow_flags); SC_ATOMIC_INIT(ippair_counter); SC_ATOMIC_INIT(ippair_memuse); SC_ATOMIC_INIT(ippair_prune_idx); @@ -181,9 +181,9 @@ void IPPairInitConfig(bool quiet) IPPairQueueInit(&ippair_spare_q); /* set defaults */ - ippair_config.hash_rand = (uint32_t)RandomGet(); - ippair_config.hash_size = IPPAIR_DEFAULT_HASHSIZE; - ippair_config.prealloc = IPPAIR_DEFAULT_PREALLOC; + ippair_config.hash_rand = (uint32_t)RandomGet(); + ippair_config.hash_size = IPPAIR_DEFAULT_HASHSIZE; + ippair_config.prealloc = IPPAIR_DEFAULT_PREALLOC; SC_ATOMIC_SET(ippair_config.memcap, IPPAIR_DEFAULT_MEMCAP); /* Check if we have memcap and hash_size defined at config */ @@ -192,8 +192,7 @@ void IPPairInitConfig(bool quiet) /** set config values for memcap, prealloc and hash_size */ uint64_t ippair_memcap; - if ((ConfGet("ippair.memcap", &conf_val)) == 1) - { + if ((ConfGet("ippair.memcap", &conf_val)) == 1) { if (ParseSizeStringU64(conf_val, &ippair_memcap) < 0) { SCLogError("Error parsing ippair.memcap " "from conf file - %s. Killing engine", @@ -203,26 +202,22 @@ void IPPairInitConfig(bool quiet) SC_ATOMIC_SET(ippair_config.memcap, ippair_memcap); } } - if ((ConfGet("ippair.hash-size", &conf_val)) == 1) - { - if (StringParseUint32(&configval, 10, strlen(conf_val), - conf_val) > 0) { + if ((ConfGet("ippair.hash-size", &conf_val)) == 1) { + if (StringParseUint32(&configval, 10, strlen(conf_val), conf_val) > 0) { ippair_config.hash_size = configval; } } - if ((ConfGet("ippair.prealloc", &conf_val)) == 1) - { - if (StringParseUint32(&configval, 10, strlen(conf_val), - conf_val) > 0) { + if ((ConfGet("ippair.prealloc", &conf_val)) == 1) { + if (StringParseUint32(&configval, 10, strlen(conf_val), conf_val) > 0) { ippair_config.prealloc = configval; } else { - WarnInvalidConfEntry("ippair.prealloc", "%"PRIu32, ippair_config.prealloc); + WarnInvalidConfEntry("ippair.prealloc", "%" PRIu32, ippair_config.prealloc); } } - SCLogDebug("IPPair config from suricata.yaml: memcap: %"PRIu64", hash-size: " - "%"PRIu32", prealloc: %"PRIu32, SC_ATOMIC_GET(ippair_config.memcap), - ippair_config.hash_size, ippair_config.prealloc); + SCLogDebug("IPPair config from suricata.yaml: memcap: %" PRIu64 ", hash-size: " + "%" PRIu32 ", prealloc: %" PRIu32, + SC_ATOMIC_GET(ippair_config.memcap), ippair_config.hash_size, ippair_config.prealloc); /* alloc hash memory */ uint64_t hash_size = ippair_config.hash_size * sizeof(IPPairHashRow); @@ -245,13 +240,13 @@ void IPPairInitConfig(bool quiet) for (i = 0; i < ippair_config.hash_size; i++) { HRLOCK_INIT(&ippair_hash[i]); } - (void) SC_ATOMIC_ADD(ippair_memuse, (ippair_config.hash_size * sizeof(IPPairHashRow))); + (void)SC_ATOMIC_ADD(ippair_memuse, (ippair_config.hash_size * sizeof(IPPairHashRow))); if (!quiet) { - SCLogConfig("allocated %"PRIu64" bytes of memory for the ippair hash... " - "%" PRIu32 " buckets of size %" PRIuMAX "", - SC_ATOMIC_GET(ippair_memuse), ippair_config.hash_size, - (uintmax_t)sizeof(IPPairHashRow)); + SCLogConfig("allocated %" PRIu64 " bytes of memory for the ippair hash... " + "%" PRIu32 " buckets of size %" PRIuMAX "", + SC_ATOMIC_GET(ippair_memuse), ippair_config.hash_size, + (uintmax_t)sizeof(IPPairHashRow)); } /* pre allocate ippairs */ @@ -270,13 +265,13 @@ void IPPairInitConfig(bool quiet) SCLogError("preallocating ippair failed: %s", strerror(errno)); exit(EXIT_FAILURE); } - IPPairEnqueue(&ippair_spare_q,h); + IPPairEnqueue(&ippair_spare_q, h); } if (!quiet) { - SCLogConfig("preallocated %" PRIu32 " ippairs of size %" PRIu16 "", - ippair_spare_q.len, g_ippair_size); - SCLogConfig("ippair memory usage: %"PRIu64" bytes, maximum: %"PRIu64, + SCLogConfig("preallocated %" PRIu32 " ippairs of size %" PRIu16 "", ippair_spare_q.len, + g_ippair_size); + SCLogConfig("ippair memory usage: %" PRIu64 " bytes, maximum: %" PRIu64, SC_ATOMIC_GET(ippair_memuse), SC_ATOMIC_GET(ippair_config.memcap)); } @@ -285,13 +280,13 @@ void IPPairInitConfig(bool quiet) /** \brief print some ippair stats * \warning Not thread safe */ -void IPPairPrintStats (void) +void IPPairPrintStats(void) { #ifdef IPPAIRBITS_STATS SCLogPerf("ippairbits added: %" PRIu32 ", removed: %" PRIu32 ", max memory usage: %" PRIu32 "", - ippairbits_added, ippairbits_removed, ippairbits_memuse_max); + ippairbits_added, ippairbits_removed, ippairbits_memuse_max); #endif /* IPPAIRBITS_STATS */ - SCLogPerf("ippair memory usage: %"PRIu64" bytes, maximum: %"PRIu64, + SCLogPerf("ippair memory usage: %" PRIu64 " bytes, maximum: %" PRIu64, SC_ATOMIC_GET(ippair_memuse), SC_ATOMIC_GET(ippair_config.memcap)); return; } @@ -306,7 +301,7 @@ void IPPairShutdown(void) IPPairPrintStats(); /* free spare queue */ - while((h = IPPairDequeue(&ippair_spare_q))) { + while ((h = IPPairDequeue(&ippair_spare_q))) { BUG_ON(SC_ATOMIC_GET(h->use_cnt) > 0); IPPairFree(h); } @@ -326,7 +321,7 @@ void IPPairShutdown(void) SCFreeAligned(ippair_hash); ippair_hash = NULL; } - (void) SC_ATOMIC_SUB(ippair_memuse, ippair_config.hash_size * sizeof(IPPairHashRow)); + (void)SC_ATOMIC_SUB(ippair_memuse, ippair_config.hash_size * sizeof(IPPairHashRow)); IPPairQueueDestroy(&ippair_spare_q); return; } @@ -410,12 +405,12 @@ static uint32_t IPPairGetKey(Address *a, Address *b) if (a->family == AF_INET) { uint32_t addrs[2] = { MIN(a->addr_data32[0], b->addr_data32[0]), - MAX(a->addr_data32[0], b->addr_data32[0]) }; + MAX(a->addr_data32[0], b->addr_data32[0]) }; uint32_t hash = hashword(addrs, 2, ippair_config.hash_rand); key = hash % ippair_config.hash_size; } else if (a->family == AF_INET6) { uint32_t addrs[8]; - if (IPPairHashRawAddressIPv6GtU32(&a->addr_data32[0],&b->addr_data32[0])) { + if (IPPairHashRawAddressIPv6GtU32(&a->addr_data32[0], &b->addr_data32[0])) { addrs[0] = b->addr_data32[0]; addrs[1] = b->addr_data32[1]; addrs[2] = b->addr_data32[2]; @@ -448,7 +443,7 @@ static inline int IPPairCompare(IPPair *p, Address *a, Address *b) { /* compare in both directions */ if ((CMP_ADDR(&p->a[0], a) && CMP_ADDR(&p->a[1], b)) || - (CMP_ADDR(&p->a[0], b) && CMP_ADDR(&p->a[1], a))) + (CMP_ADDR(&p->a[0], b) && CMP_ADDR(&p->a[1], a))) return 1; return 0; } @@ -471,12 +466,12 @@ static IPPair *IPPairGetNew(Address *a, Address *b) /* If we reached the max memcap, we get a used ippair */ if (!(IPPAIR_CHECK_MEMCAP(g_ippair_size))) { /* declare state of emergency */ - //if (!(SC_ATOMIC_GET(ippair_flags) & IPPAIR_EMERGENCY)) { + // if (!(SC_ATOMIC_GET(ippair_flags) & IPPAIR_EMERGENCY)) { // SC_ATOMIC_OR(ippair_flags, IPPAIR_EMERGENCY); - /* under high load, waking up the flow mgr each time leads - * to high cpu usage. Flows are not timed out much faster if - * we check a 1000 times a second. */ + /* under high load, waking up the flow mgr each time leads + * to high cpu usage. Flows are not timed out much faster if + * we check a 1000 times a second. */ // FlowWakeupFlowManagerThread(); //} @@ -488,7 +483,7 @@ static IPPair *IPPairGetNew(Address *a, Address *b) /* freed a ippair, but it's unlocked */ } else { /* now see if we can alloc a new ippair */ - h = IPPairNew(a,b); + h = IPPairNew(a, b); if (h == NULL) { return NULL; } @@ -501,7 +496,7 @@ static IPPair *IPPairGetNew(Address *a, Address *b) /* ippair is initialized (recycled) but *unlocked* */ } - (void) SC_ATOMIC_ADD(ippair_counter, 1); + (void)SC_ATOMIC_ADD(ippair_counter, 1); SCMutexLock(&h->m); return h; } @@ -510,12 +505,12 @@ static void IPPairInit(IPPair *h, Address *a, Address *b) { COPY_ADDRESS(a, &h->a[0]); COPY_ADDRESS(b, &h->a[1]); - (void) IPPairIncrUsecnt(h); + (void)IPPairIncrUsecnt(h); } void IPPairRelease(IPPair *h) { - (void) IPPairDecrUsecnt(h); + (void)IPPairDecrUsecnt(h); SCMutexUnlock(&h->m); } @@ -537,7 +532,7 @@ void IPPairUnlock(IPPair *h) * * returns a *LOCKED* ippair or NULL */ -IPPair *IPPairGetIPPairFromHash (Address *a, Address *b) +IPPair *IPPairGetIPPairFromHash(Address *a, Address *b) { IPPair *h = NULL; @@ -549,7 +544,7 @@ IPPair *IPPairGetIPPairFromHash (Address *a, Address *b) /* see if the bucket already has a ippair */ if (hb->head == NULL) { - h = IPPairGetNew(a,b); + h = IPPairGetNew(a, b); if (h == NULL) { HRLOCK_UNLOCK(hb); return NULL; @@ -560,7 +555,7 @@ IPPair *IPPairGetIPPairFromHash (Address *a, Address *b) hb->tail = h; /* got one, now lock, initialize and return */ - IPPairInit(h,a,b); + IPPairInit(h, a, b); HRLOCK_UNLOCK(hb); return h; @@ -578,7 +573,7 @@ IPPair *IPPairGetIPPairFromHash (Address *a, Address *b) h = h->hnext; if (h == NULL) { - h = ph->hnext = IPPairGetNew(a,b); + h = ph->hnext = IPPairGetNew(a, b); if (h == NULL) { HRLOCK_UNLOCK(hb); return NULL; @@ -590,7 +585,7 @@ IPPair *IPPairGetIPPairFromHash (Address *a, Address *b) h->hprev = ph; /* initialize and return */ - IPPairInit(h,a,b); + IPPairInit(h, a, b); HRLOCK_UNLOCK(hb); return h; @@ -616,7 +611,7 @@ IPPair *IPPairGetIPPairFromHash (Address *a, Address *b) /* found our ippair, lock & return */ SCMutexLock(&h->m); - (void) IPPairIncrUsecnt(h); + (void)IPPairIncrUsecnt(h); HRLOCK_UNLOCK(hb); return h; } @@ -625,7 +620,7 @@ IPPair *IPPairGetIPPairFromHash (Address *a, Address *b) /* lock & return */ SCMutexLock(&h->m); - (void) IPPairIncrUsecnt(h); + (void)IPPairIncrUsecnt(h); HRLOCK_UNLOCK(hb); return h; } @@ -636,7 +631,7 @@ IPPair *IPPairGetIPPairFromHash (Address *a, Address *b) * * \retval h *LOCKED* ippair or NULL */ -IPPair *IPPairLookupIPPairFromHash (Address *a, Address *b) +IPPair *IPPairLookupIPPairFromHash(Address *a, Address *b) { IPPair *h = NULL; @@ -685,7 +680,7 @@ IPPair *IPPairLookupIPPairFromHash (Address *a, Address *b) /* found our ippair, lock & return */ SCMutexLock(&h->m); - (void) IPPairIncrUsecnt(h); + (void)IPPairIncrUsecnt(h); HRLOCK_UNLOCK(hb); return h; } @@ -694,7 +689,7 @@ IPPair *IPPairLookupIPPairFromHash (Address *a, Address *b) /* lock & return */ SCMutexLock(&h->m); - (void) IPPairIncrUsecnt(h); + (void)IPPairIncrUsecnt(h); HRLOCK_UNLOCK(hb); return h; } @@ -757,11 +752,11 @@ static IPPair *IPPairGetUsedIPPair(void) h->hprev = NULL; HRLOCK_UNLOCK(hb); - IPPairClearMemory (h); + IPPairClearMemory(h); SCMutexUnlock(&h->m); - (void) SC_ATOMIC_ADD(ippair_prune_idx, (ippair_config.hash_size - cnt)); + (void)SC_ATOMIC_ADD(ippair_prune_idx, (ippair_config.hash_size - cnt)); return h; } diff --git a/src/ippair.h b/src/ippair.h index 3eef45ad8fcc..0b5960871cf1 100644 --- a/src/ippair.h +++ b/src/ippair.h @@ -32,27 +32,27 @@ #define HRLOCK_MUTEX #ifdef HRLOCK_SPIN - #ifdef HRLOCK_MUTEX - #error Cannot enable both HRLOCK_SPIN and HRLOCK_MUTEX - #endif +#ifdef HRLOCK_MUTEX +#error Cannot enable both HRLOCK_SPIN and HRLOCK_MUTEX +#endif #endif #ifdef HRLOCK_SPIN - #define HRLOCK_TYPE SCSpinlock - #define HRLOCK_INIT(fb) SCSpinInit(&(fb)->lock, 0) - #define HRLOCK_DESTROY(fb) SCSpinDestroy(&(fb)->lock) - #define HRLOCK_LOCK(fb) SCSpinLock(&(fb)->lock) - #define HRLOCK_TRYLOCK(fb) SCSpinTrylock(&(fb)->lock) - #define HRLOCK_UNLOCK(fb) SCSpinUnlock(&(fb)->lock) +#define HRLOCK_TYPE SCSpinlock +#define HRLOCK_INIT(fb) SCSpinInit(&(fb)->lock, 0) +#define HRLOCK_DESTROY(fb) SCSpinDestroy(&(fb)->lock) +#define HRLOCK_LOCK(fb) SCSpinLock(&(fb)->lock) +#define HRLOCK_TRYLOCK(fb) SCSpinTrylock(&(fb)->lock) +#define HRLOCK_UNLOCK(fb) SCSpinUnlock(&(fb)->lock) #elif defined HRLOCK_MUTEX - #define HRLOCK_TYPE SCMutex - #define HRLOCK_INIT(fb) SCMutexInit(&(fb)->lock, NULL) - #define HRLOCK_DESTROY(fb) SCMutexDestroy(&(fb)->lock) - #define HRLOCK_LOCK(fb) SCMutexLock(&(fb)->lock) - #define HRLOCK_TRYLOCK(fb) SCMutexTrylock(&(fb)->lock) - #define HRLOCK_UNLOCK(fb) SCMutexUnlock(&(fb)->lock) +#define HRLOCK_TYPE SCMutex +#define HRLOCK_INIT(fb) SCMutexInit(&(fb)->lock, NULL) +#define HRLOCK_DESTROY(fb) SCMutexDestroy(&(fb)->lock) +#define HRLOCK_LOCK(fb) SCMutexLock(&(fb)->lock) +#define HRLOCK_TRYLOCK(fb) SCMutexTrylock(&(fb)->lock) +#define HRLOCK_UNLOCK(fb) SCMutexUnlock(&(fb)->lock) #else - #error Enable HRLOCK_SPIN or HRLOCK_MUTEX +#error Enable HRLOCK_SPIN or HRLOCK_MUTEX #endif typedef struct IPPair_ { @@ -86,7 +86,7 @@ typedef struct IPPairHashRow_ { /** ippair hash table */ extern IPPairHashRow *ippair_hash; -#define IPPAIR_QUIET 1 +#define IPPAIR_QUIET 1 typedef struct IPPairConfig_ { SC_ATOMIC_DECLARE(uint64_t, memcap); @@ -102,31 +102,30 @@ typedef struct IPPairConfig_ { * \retval 1 it fits * \retval 0 no fit */ -#define IPPAIR_CHECK_MEMCAP(size) \ - ((((uint64_t)SC_ATOMIC_GET(ippair_memuse) + (uint64_t)(size)) <= SC_ATOMIC_GET(ippair_config.memcap))) +#define IPPAIR_CHECK_MEMCAP(size) \ + ((((uint64_t)SC_ATOMIC_GET(ippair_memuse) + (uint64_t)(size)) <= \ + SC_ATOMIC_GET(ippair_config.memcap))) -#define IPPairIncrUsecnt(h) \ - (void)SC_ATOMIC_ADD((h)->use_cnt, 1) -#define IPPairDecrUsecnt(h) \ - (void)SC_ATOMIC_SUB((h)->use_cnt, 1) +#define IPPairIncrUsecnt(h) (void)SC_ATOMIC_ADD((h)->use_cnt, 1) +#define IPPairDecrUsecnt(h) (void)SC_ATOMIC_SUB((h)->use_cnt, 1) extern IPPairConfig ippair_config; -SC_ATOMIC_EXTERN(uint64_t,ippair_memuse); -SC_ATOMIC_EXTERN(uint32_t,ippair_counter); -SC_ATOMIC_EXTERN(uint32_t,ippair_prune_idx); +SC_ATOMIC_EXTERN(uint64_t, ippair_memuse); +SC_ATOMIC_EXTERN(uint32_t, ippair_counter); +SC_ATOMIC_EXTERN(uint32_t, ippair_prune_idx); void IPPairInitConfig(bool quiet); void IPPairShutdown(void); void IPPairCleanup(void); -IPPair *IPPairLookupIPPairFromHash (Address *, Address *); -IPPair *IPPairGetIPPairFromHash (Address *, Address *); +IPPair *IPPairLookupIPPairFromHash(Address *, Address *); +IPPair *IPPairGetIPPairFromHash(Address *, Address *); void IPPairRelease(IPPair *); void IPPairLock(IPPair *); void IPPairClearMemory(IPPair *); void IPPairMoveToSpare(IPPair *); uint32_t IPPairSpareQueueGetSize(void); -void IPPairPrintStats (void); +void IPPairPrintStats(void); void IPPairRegisterUnittests(void); diff --git a/src/log-cf-common.c b/src/log-cf-common.c index 077813501c32..466e2e37c430 100644 --- a/src/log-cf-common.c +++ b/src/log-cf-common.c @@ -38,7 +38,7 @@ */ LogCustomFormatNode *LogCustomFormatNodeAlloc(void) { - LogCustomFormatNode * node = SCCalloc(1, sizeof(LogCustomFormatNode)); + LogCustomFormatNode *node = SCCalloc(1, sizeof(LogCustomFormatNode)); if (unlikely(node == NULL)) { SCLogError("Failed to alloc custom format node"); return NULL; @@ -53,7 +53,7 @@ LogCustomFormatNode *LogCustomFormatNodeAlloc(void) */ LogCustomFormat *LogCustomFormatAlloc(void) { - LogCustomFormat * cf = SCCalloc(1, sizeof(LogCustomFormat)); + LogCustomFormat *cf = SCCalloc(1, sizeof(LogCustomFormat)); if (unlikely(cf == NULL)) { SCLogError("Failed to alloc custom format"); return NULL; @@ -67,7 +67,7 @@ LogCustomFormat *LogCustomFormatAlloc(void) */ void LogCustomFormatNodeFree(LogCustomFormatNode *node) { - if (node==NULL) + if (node == NULL) return; SCFree(node); @@ -79,7 +79,7 @@ void LogCustomFormatNodeFree(LogCustomFormatNode *node) */ void LogCustomFormatFree(LogCustomFormat *cf) { - if (cf==NULL) + if (cf == NULL) return; for (size_t i = 0; i < cf->cf_n; ++i) { @@ -99,15 +99,15 @@ int LogCustomFormatParse(LogCustomFormat *cf, const char *format) uint32_t n; LogCustomFormatNode *node = NULL; - if (cf==NULL) + if (cf == NULL) return 0; - if (format==NULL) + if (format == NULL) return 0; - p=format; + p = format; - for (cf->cf_n = 0; cf->cf_n < LOG_MAXN_NODES-1 && p && *p != '\0';){ + for (cf->cf_n = 0; cf->cf_n < LOG_MAXN_NODES - 1 && p && *p != '\0';) { node = LogCustomFormatNodeAlloc(); if (node == NULL) { @@ -115,17 +115,17 @@ int LogCustomFormatParse(LogCustomFormat *cf, const char *format) } node->maxlen = 0; - if (*p != '%'){ + if (*p != '%') { /* Literal found in format string */ node->type = LOG_CF_LITERAL; np = strchr(p, '%'); - if (np == NULL){ - n = LOG_NODE_STRLEN-2; + if (np == NULL) { + n = LOG_NODE_STRLEN - 2; np = NULL; /* End */ - }else{ - n = np-p; + } else { + n = np - p; } - strlcpy(node->data,p,n+1); + strlcpy(node->data, p, n + 1); p = np; } else { /* Non Literal found in format string */ @@ -134,10 +134,10 @@ int LogCustomFormatParse(LogCustomFormat *cf, const char *format) p++; np = strchr(p, ']'); if (np != NULL) { - if (np-p > 0 && np-p < 10){ - long maxlen = strtol(p,NULL,10); + if (np - p > 0 && np - p < 10) { + long maxlen = strtol(p, NULL, 10); if (maxlen > 0 && maxlen < LOG_NODE_MAXOUTPUTLEN) { - node->maxlen = (uint32_t) maxlen; + node->maxlen = (uint32_t)maxlen; } } else { goto parsererror; @@ -149,10 +149,10 @@ int LogCustomFormatParse(LogCustomFormat *cf, const char *format) } if (*p == '{') { /* Simple format char */ np = strchr(p, '}'); - if (np != NULL && np-p > 1 && np-p < LOG_NODE_STRLEN-2) { + if (np != NULL && np - p > 1 && np - p < LOG_NODE_STRLEN - 2) { p++; - n = np-p; - strlcpy(node->data, p, n+1); + n = np - p; + strlcpy(node->data, p, n + 1); p = np; } else { goto parsererror; @@ -162,7 +162,7 @@ int LogCustomFormatParse(LogCustomFormat *cf, const char *format) node->data[0] = '\0'; } node->type = *p; - if (*p == '%'){ + if (*p == '%') { node->type = LOG_CF_LITERAL; strlcpy(node->data, "%", 2); } @@ -193,8 +193,8 @@ void LogCustomFormatAddNode(LogCustomFormat *cf, LogCustomFormatNode *node) } #ifdef DEBUG - SCLogDebug("%d-> n.type=[%d] n.maxlen=[%d] n.data=[%s]", - cf->cf_n, node->type, node->maxlen, node->data); + SCLogDebug("%d-> n.type=[%d] n.maxlen=[%d] n.data=[%s]", cf->cf_n, node->type, node->maxlen, + node->data); #endif cf->cf_nodes[cf->cf_n] = node; @@ -214,16 +214,16 @@ void LogCustomFormatWriteTimestamp(MemBuffer *buffer, const char *fmt, const SCT time_t time = SCTIME_SECS(ts); struct tm local_tm; struct tm *timestamp = SCLocalTime(time, &local_tm); - char buf[128] = {0}; - const char * fmt_to_use = TIMESTAMP_DEFAULT_FORMAT; + char buf[128] = { 0 }; + const char *fmt_to_use = TIMESTAMP_DEFAULT_FORMAT; if (fmt && *fmt != '\0') { fmt_to_use = fmt; } - CreateFormattedTimeString (timestamp, fmt_to_use, buf, sizeof(buf)); - PrintRawUriBuf((char *)buffer->buffer, &buffer->offset, - buffer->size, (uint8_t *)buf,strlen(buf)); + CreateFormattedTimeString(timestamp, fmt_to_use, buf, sizeof(buf)); + PrintRawUriBuf( + (char *)buffer->buffer, &buffer->offset, buffer->size, (uint8_t *)buf, strlen(buf)); } #ifdef UNITTESTS @@ -254,7 +254,7 @@ static int LogCustomFormatTest01(void) /* * {buffer = "01/13/14-04:30:00", size = 62, offset = 17} */ - FAIL_IF_NOT( buffer->offset == 17); + FAIL_IF_NOT(buffer->offset == 17); FAIL_IF(strcmp((char *)buffer->buffer, "01/13/14-04:30:00") != 0); MemBufferFree(buffer); diff --git a/src/log-cf-common.h b/src/log-cf-common.h index 61d2d55af874..aac940bf7a56 100644 --- a/src/log-cf-common.h +++ b/src/log-cf-common.h @@ -28,34 +28,32 @@ #ifndef __LOG_CF_COMMON_H__ #define __LOG_CF_COMMON_H__ -#define LOG_MAXN_NODES 64 -#define LOG_NODE_STRLEN 256 +#define LOG_MAXN_NODES 64 +#define LOG_NODE_STRLEN 256 #define LOG_NODE_MAXOUTPUTLEN 8192 #define TIMESTAMP_DEFAULT_FORMAT "%D-%H:%M:%S" /* Common format nodes */ -#define LOG_CF_NONE "-" -#define LOG_CF_LITERAL '%' -#define LOG_CF_TIMESTAMP 't' +#define LOG_CF_NONE "-" +#define LOG_CF_LITERAL '%' +#define LOG_CF_TIMESTAMP 't' #define LOG_CF_TIMESTAMP_U 'z' -#define LOG_CF_CLIENT_IP 'a' -#define LOG_CF_SERVER_IP 'A' +#define LOG_CF_CLIENT_IP 'a' +#define LOG_CF_SERVER_IP 'A' #define LOG_CF_CLIENT_PORT 'p' #define LOG_CF_SERVER_PORT 'P' /* Line log common separators **/ -#define LOG_CF_STAR_SEPARATOR "[**]" +#define LOG_CF_STAR_SEPARATOR "[**]" #define LOG_CF_SPACE_SEPARATOR " " -#define LOG_CF_UNKNOWN_VALUE "-" +#define LOG_CF_UNKNOWN_VALUE "-" #define LOG_CF_WRITE_STAR_SEPARATOR(buffer) MemBufferWriteString(buffer, LOG_CF_STAR_SEPARATOR); -#define LOG_CF_WRITE_SPACE_SEPARATOR(buffer) \ - MemBufferWriteString(buffer, LOG_CF_SPACE_SEPARATOR); +#define LOG_CF_WRITE_SPACE_SEPARATOR(buffer) MemBufferWriteString(buffer, LOG_CF_SPACE_SEPARATOR); -#define LOG_CF_WRITE_UNKNOWN_VALUE(buffer) \ - MemBufferWriteString(buffer, LOG_CF_UNKNOWN_VALUE); +#define LOG_CF_WRITE_UNKNOWN_VALUE(buffer) MemBufferWriteString(buffer, LOG_CF_UNKNOWN_VALUE); /* Include */ #include "suricata-common.h" @@ -67,14 +65,13 @@ typedef struct LogCustomFormatNode_ { char data[LOG_NODE_STRLEN]; /**< optional data. ie: http header name */ } LogCustomFormatNode; - typedef struct LogCustomFormat_ { - uint32_t cf_n; /**< Total number of custom string format nodes */ - LogCustomFormatNode *cf_nodes[LOG_MAXN_NODES]; /**< Custom format string nodes */ + uint32_t cf_n; /**< Total number of custom string format nodes */ + LogCustomFormatNode *cf_nodes[LOG_MAXN_NODES]; /**< Custom format string nodes */ } LogCustomFormat; -LogCustomFormatNode * LogCustomFormatNodeAlloc(void); -LogCustomFormat * LogCustomFormatAlloc(void); +LogCustomFormatNode *LogCustomFormatNodeAlloc(void); +LogCustomFormat *LogCustomFormatAlloc(void); void LogCustomFormatNodeFree(LogCustomFormatNode *node); void LogCustomFormatFree(LogCustomFormat *cf); diff --git a/src/log-httplog.c b/src/log-httplog.c index 68fa62e95b7f..c9b1d884a445 100644 --- a/src/log-httplog.c +++ b/src/log-httplog.c @@ -60,26 +60,26 @@ TmEcode LogHttpLogThreadInit(ThreadVars *, const void *, void **); TmEcode LogHttpLogThreadDeinit(ThreadVars *, void *); static void LogHttpLogDeInitCtx(OutputCtx *); -int LogHttpLogger(ThreadVars *tv, void *thread_data, const Packet *, Flow *f, void *state, void *tx, uint64_t tx_id); +int LogHttpLogger(ThreadVars *tv, void *thread_data, const Packet *, Flow *f, void *state, void *tx, + uint64_t tx_id); -void LogHttpLogRegister (void) +void LogHttpLogRegister(void) { OutputRegisterTxModule(LOGGER_HTTP, MODULE_NAME, "http-log", LogHttpLogInitCtx, ALPROTO_HTTP1, LogHttpLogger, LogHttpLogThreadInit, LogHttpLogThreadDeinit, NULL); } -#define LOG_HTTP_CF_REQUEST_HOST 'h' +#define LOG_HTTP_CF_REQUEST_HOST 'h' #define LOG_HTTP_CF_REQUEST_PROTOCOL 'H' -#define LOG_HTTP_CF_REQUEST_METHOD 'm' -#define LOG_HTTP_CF_REQUEST_URI 'u' -#define LOG_HTTP_CF_REQUEST_TIME 't' -#define LOG_HTTP_CF_REQUEST_HEADER 'i' -#define LOG_HTTP_CF_REQUEST_COOKIE 'C' -#define LOG_HTTP_CF_REQUEST_LEN 'b' -#define LOG_HTTP_CF_RESPONSE_STATUS 's' -#define LOG_HTTP_CF_RESPONSE_HEADER 'o' -#define LOG_HTTP_CF_RESPONSE_LEN 'B' - +#define LOG_HTTP_CF_REQUEST_METHOD 'm' +#define LOG_HTTP_CF_REQUEST_URI 'u' +#define LOG_HTTP_CF_REQUEST_TIME 't' +#define LOG_HTTP_CF_REQUEST_HEADER 'i' +#define LOG_HTTP_CF_REQUEST_COOKIE 'C' +#define LOG_HTTP_CF_REQUEST_LEN 'b' +#define LOG_HTTP_CF_RESPONSE_STATUS 's' +#define LOG_HTTP_CF_RESPONSE_HEADER 'o' +#define LOG_HTTP_CF_RESPONSE_LEN 'B' typedef struct LogHttpFileCtx_ { LogFileCtx *file_ctx; @@ -87,9 +87,9 @@ typedef struct LogHttpFileCtx_ { LogCustomFormat *cf; } LogHttpFileCtx; -#define LOG_HTTP_DEFAULT 0 +#define LOG_HTTP_DEFAULT 0 #define LOG_HTTP_EXTENDED 1 -#define LOG_HTTP_CUSTOM 2 +#define LOG_HTTP_CUSTOM 2 typedef struct LogHttpLogThread_ { LogHttpFileCtx *httplog_ctx; @@ -100,22 +100,22 @@ typedef struct LogHttpLogThread_ { } LogHttpLogThread; /* Retrieves the selected cookie value */ -static uint32_t GetCookieValue(uint8_t *rawcookies, uint32_t rawcookies_len, char *cookiename, - uint8_t **cookievalue) +static uint32_t GetCookieValue( + uint8_t *rawcookies, uint32_t rawcookies_len, char *cookiename, uint8_t **cookievalue) { uint8_t *p = rawcookies; - uint8_t *cn = p; /* ptr to cookie name start */ + uint8_t *cn = p; /* ptr to cookie name start */ uint8_t *cv = NULL; /* ptr to cookie value start */ while (p < rawcookies + rawcookies_len) { if (cv == NULL && *p == '=') { cv = p + 1; - } else if (cv != NULL && (*p == ';' || p == rawcookies + rawcookies_len - 1) ) { + } else if (cv != NULL && (*p == ';' || p == rawcookies + rawcookies_len - 1)) { /* Found end of cookie */ p++; - if (strlen(cookiename) == (unsigned int) (cv-cn-1) && - strncmp(cookiename, (char *) cn, cv-cn-1) == 0) { + if (strlen(cookiename) == (unsigned int)(cv - cn - 1) && + strncmp(cookiename, (char *)cn, cv - cn - 1) == 0) { *cookievalue = cv; - return (uint32_t) (p-cv); + return (uint32_t)(p - cv); } cv = NULL; cn = p + 1; @@ -144,94 +144,91 @@ static void LogHttpLogCustom(LogHttpLogThread *aft, htp_tx_t *tx, const SCTime_t h_request_hdr = NULL; h_response_hdr = NULL; - LogCustomFormatNode * node = httplog_ctx->cf->cf_nodes[i]; - if (! node) /* Should never happen */ + LogCustomFormatNode *node = httplog_ctx->cf->cf_nodes[i]; + if (!node) /* Should never happen */ continue; - switch (node->type){ + switch (node->type) { case LOG_CF_LITERAL: - /* LITERAL */ + /* LITERAL */ MemBufferWriteString(aft->buffer, "%s", node->data); break; case LOG_CF_TIMESTAMP: - /* TIMESTAMP */ - LogCustomFormatWriteTimestamp(aft->buffer, node->data, ts); - break; + /* TIMESTAMP */ + LogCustomFormatWriteTimestamp(aft->buffer, node->data, ts); + break; case LOG_CF_TIMESTAMP_U: - /* TIMESTAMP USECONDS */ - snprintf(buf, sizeof(buf), "%06u", (unsigned int)SCTIME_USECS(ts)); - PrintRawUriBuf((char *)aft->buffer->buffer, &aft->buffer->offset, aft->buffer->size, - (uint8_t *)buf, MIN(strlen(buf), 6)); - break; + /* TIMESTAMP USECONDS */ + snprintf(buf, sizeof(buf), "%06u", (unsigned int)SCTIME_USECS(ts)); + PrintRawUriBuf((char *)aft->buffer->buffer, &aft->buffer->offset, aft->buffer->size, + (uint8_t *)buf, MIN(strlen(buf), 6)); + break; case LOG_CF_CLIENT_IP: - /* CLIENT IP ADDRESS */ - PrintRawUriBuf((char *)aft->buffer->buffer, &aft->buffer->offset, - aft->buffer->size, (uint8_t *)srcip,strlen(srcip)); + /* CLIENT IP ADDRESS */ + PrintRawUriBuf((char *)aft->buffer->buffer, &aft->buffer->offset, aft->buffer->size, + (uint8_t *)srcip, strlen(srcip)); break; case LOG_CF_SERVER_IP: - /* SERVER IP ADDRESS */ - PrintRawUriBuf((char *)aft->buffer->buffer, &aft->buffer->offset, - aft->buffer->size, (uint8_t *)dstip,strlen(dstip)); + /* SERVER IP ADDRESS */ + PrintRawUriBuf((char *)aft->buffer->buffer, &aft->buffer->offset, aft->buffer->size, + (uint8_t *)dstip, strlen(dstip)); break; case LOG_CF_CLIENT_PORT: - /* CLIENT PORT */ + /* CLIENT PORT */ MemBufferWriteString(aft->buffer, "%" PRIu16 "", sp); break; case LOG_CF_SERVER_PORT: - /* SERVER PORT */ + /* SERVER PORT */ MemBufferWriteString(aft->buffer, "%" PRIu16 "", dp); break; case LOG_HTTP_CF_REQUEST_METHOD: - /* METHOD */ + /* METHOD */ if (tx->request_method != NULL) { PrintRawUriBuf((char *)aft->buffer->buffer, &aft->buffer->offset, - aft->buffer->size, (uint8_t *)bstr_ptr(tx->request_method), - bstr_len(tx->request_method)); + aft->buffer->size, (uint8_t *)bstr_ptr(tx->request_method), + bstr_len(tx->request_method)); } else { MemBufferWriteString(aft->buffer, LOG_CF_NONE); } break; case LOG_HTTP_CF_REQUEST_URI: - /* URI */ + /* URI */ if (tx->request_uri != NULL) { datalen = node->maxlen; if (datalen == 0 || datalen > bstr_len(tx->request_uri)) { datalen = bstr_len(tx->request_uri); } PrintRawUriBuf((char *)aft->buffer->buffer, &aft->buffer->offset, - aft->buffer->size, (uint8_t *)bstr_ptr(tx->request_uri), - datalen); + aft->buffer->size, (uint8_t *)bstr_ptr(tx->request_uri), datalen); } else { MemBufferWriteString(aft->buffer, LOG_CF_NONE); } break; case LOG_HTTP_CF_REQUEST_HOST: - /* HOSTNAME */ - if (tx->request_hostname != NULL) - { + /* HOSTNAME */ + if (tx->request_hostname != NULL) { datalen = node->maxlen; if (datalen == 0 || datalen > bstr_len(tx->request_hostname)) { datalen = bstr_len(tx->request_hostname); } PrintRawUriBuf((char *)aft->buffer->buffer, &aft->buffer->offset, - aft->buffer->size, (uint8_t *)bstr_ptr(tx->request_hostname), - datalen); + aft->buffer->size, (uint8_t *)bstr_ptr(tx->request_hostname), datalen); } else { MemBufferWriteString(aft->buffer, LOG_CF_NONE); } break; case LOG_HTTP_CF_REQUEST_PROTOCOL: - /* PROTOCOL */ + /* PROTOCOL */ if (tx->request_protocol != NULL) { PrintRawUriBuf((char *)aft->buffer->buffer, &aft->buffer->offset, - aft->buffer->size, (uint8_t *)bstr_ptr(tx->request_protocol), - bstr_len(tx->request_protocol)); + aft->buffer->size, (uint8_t *)bstr_ptr(tx->request_protocol), + bstr_len(tx->request_protocol)); } else { MemBufferWriteString(aft->buffer, LOG_CF_NONE); } break; case LOG_HTTP_CF_REQUEST_HEADER: - /* REQUEST HEADER */ + /* REQUEST HEADER */ if (tx->request_headers != NULL) { h_request_hdr = htp_table_get_c(tx->request_headers, node->data); } @@ -241,20 +238,18 @@ static void LogHttpLogCustom(LogHttpLogThread *aft, htp_tx_t *tx, const SCTime_t datalen = bstr_len(h_request_hdr->value); } PrintRawUriBuf((char *)aft->buffer->buffer, &aft->buffer->offset, - aft->buffer->size, (uint8_t *)bstr_ptr(h_request_hdr->value), - datalen); + aft->buffer->size, (uint8_t *)bstr_ptr(h_request_hdr->value), datalen); } else { MemBufferWriteString(aft->buffer, LOG_CF_NONE); } break; case LOG_HTTP_CF_REQUEST_COOKIE: - /* REQUEST COOKIE */ + /* REQUEST COOKIE */ if (tx->request_headers != NULL) { h_request_hdr = htp_table_get_c(tx->request_headers, "Cookie"); if (h_request_hdr != NULL) { - cvalue_len = GetCookieValue((uint8_t *) bstr_ptr(h_request_hdr->value), - bstr_len(h_request_hdr->value), (char *) node->data, - &cvalue); + cvalue_len = GetCookieValue((uint8_t *)bstr_ptr(h_request_hdr->value), + bstr_len(h_request_hdr->value), (char *)node->data, &cvalue); } } if (cvalue_len > 0 && cvalue != NULL) { @@ -263,30 +258,30 @@ static void LogHttpLogCustom(LogHttpLogThread *aft, htp_tx_t *tx, const SCTime_t datalen = cvalue_len; } PrintRawUriBuf((char *)aft->buffer->buffer, &aft->buffer->offset, - aft->buffer->size, cvalue, datalen); + aft->buffer->size, cvalue, datalen); } else { MemBufferWriteString(aft->buffer, LOG_CF_NONE); } break; case LOG_HTTP_CF_REQUEST_LEN: - /* REQUEST LEN */ - MemBufferWriteString(aft->buffer, "%"PRIuMAX"", (uintmax_t)tx->request_message_len); + /* REQUEST LEN */ + MemBufferWriteString( + aft->buffer, "%" PRIuMAX "", (uintmax_t)tx->request_message_len); break; case LOG_HTTP_CF_RESPONSE_STATUS: - /* RESPONSE STATUS */ + /* RESPONSE STATUS */ if (tx->response_status != NULL) { PrintRawUriBuf((char *)aft->buffer->buffer, &aft->buffer->offset, - aft->buffer->size, (uint8_t *)bstr_ptr(tx->response_status), - bstr_len(tx->response_status)); + aft->buffer->size, (uint8_t *)bstr_ptr(tx->response_status), + bstr_len(tx->response_status)); } else { MemBufferWriteString(aft->buffer, LOG_CF_NONE); } break; case LOG_HTTP_CF_RESPONSE_HEADER: - /* RESPONSE HEADER */ + /* RESPONSE HEADER */ if (tx->response_headers != NULL) { - h_response_hdr = htp_table_get_c(tx->response_headers, - node->data); + h_response_hdr = htp_table_get_c(tx->response_headers, node->data); } if (h_response_hdr != NULL) { datalen = node->maxlen; @@ -294,18 +289,18 @@ static void LogHttpLogCustom(LogHttpLogThread *aft, htp_tx_t *tx, const SCTime_t datalen = bstr_len(h_response_hdr->value); } PrintRawUriBuf((char *)aft->buffer->buffer, &aft->buffer->offset, - aft->buffer->size, (uint8_t *)bstr_ptr(h_response_hdr->value), - datalen); + aft->buffer->size, (uint8_t *)bstr_ptr(h_response_hdr->value), datalen); } else { MemBufferWriteString(aft->buffer, LOG_CF_NONE); } break; case LOG_HTTP_CF_RESPONSE_LEN: - /* RESPONSE LEN */ - MemBufferWriteString(aft->buffer, "%"PRIuMAX"", (uintmax_t)tx->response_message_len); + /* RESPONSE LEN */ + MemBufferWriteString( + aft->buffer, "%" PRIuMAX "", (uintmax_t)tx->response_message_len); break; default: - /* NO MATCH */ + /* NO MATCH */ MemBufferWriteString(aft->buffer, LOG_CF_NONE); SCLogDebug("No matching parameter %%%c for custom http log.", node->type); break; @@ -325,8 +320,7 @@ static void LogHttpLogExtended(LogHttpLogThread *aft, htp_tx_t *tx) } if (h_referer != NULL) { PrintRawUriBuf((char *)aft->buffer->buffer, &aft->buffer->offset, aft->buffer->size, - (uint8_t *)bstr_ptr(h_referer->value), - bstr_len(h_referer->value)); + (uint8_t *)bstr_ptr(h_referer->value), bstr_len(h_referer->value)); } else { MemBufferWriteString(aft->buffer, ""); } @@ -336,16 +330,14 @@ static void LogHttpLogExtended(LogHttpLogThread *aft, htp_tx_t *tx) /* method */ if (tx->request_method != NULL) { PrintRawUriBuf((char *)aft->buffer->buffer, &aft->buffer->offset, aft->buffer->size, - (uint8_t *)bstr_ptr(tx->request_method), - bstr_len(tx->request_method)); + (uint8_t *)bstr_ptr(tx->request_method), bstr_len(tx->request_method)); } LOG_CF_WRITE_STAR_SEPARATOR(aft->buffer); /* protocol */ if (tx->request_protocol != NULL) { PrintRawUriBuf((char *)aft->buffer->buffer, &aft->buffer->offset, aft->buffer->size, - (uint8_t *)bstr_ptr(tx->request_protocol), - bstr_len(tx->request_protocol)); + (uint8_t *)bstr_ptr(tx->request_protocol), bstr_len(tx->request_protocol)); } else { MemBufferWriteString(aft->buffer, ""); } @@ -354,8 +346,7 @@ static void LogHttpLogExtended(LogHttpLogThread *aft, htp_tx_t *tx) /* response status */ if (tx->response_status != NULL) { PrintRawUriBuf((char *)aft->buffer->buffer, &aft->buffer->offset, aft->buffer->size, - (uint8_t *)bstr_ptr(tx->response_status), - bstr_len(tx->response_status)); + (uint8_t *)bstr_ptr(tx->response_status), bstr_len(tx->response_status)); /* Redirect? */ if ((tx->response_status_number > 300) && ((tx->response_status_number) < 303)) { htp_header_t *h_location = htp_table_get_c(tx->response_headers, "location"); @@ -363,8 +354,7 @@ static void LogHttpLogExtended(LogHttpLogThread *aft, htp_tx_t *tx) MemBufferWriteString(aft->buffer, " => "); PrintRawUriBuf((char *)aft->buffer->buffer, &aft->buffer->offset, aft->buffer->size, - (uint8_t *)bstr_ptr(h_location->value), - bstr_len(h_location->value)); + (uint8_t *)bstr_ptr(h_location->value), bstr_len(h_location->value)); } } } else { @@ -373,10 +363,11 @@ static void LogHttpLogExtended(LogHttpLogThread *aft, htp_tx_t *tx) /* length */ LOG_CF_WRITE_STAR_SEPARATOR(aft->buffer); - MemBufferWriteString(aft->buffer, "%"PRIuMAX" bytes", (uintmax_t)tx->response_message_len); + MemBufferWriteString(aft->buffer, "%" PRIuMAX " bytes", (uintmax_t)tx->response_message_len); } -static TmEcode LogHttpLogIPWrapper(ThreadVars *tv, void *data, const Packet *p, Flow *f, HtpState *htp_state, htp_tx_t *tx, uint64_t tx_id, int ipproto) +static TmEcode LogHttpLogIPWrapper(ThreadVars *tv, void *data, const Packet *p, Flow *f, + HtpState *htp_state, htp_tx_t *tx, uint64_t tx_id, int ipproto) { SCEnter(); @@ -435,8 +426,7 @@ static TmEcode LogHttpLogIPWrapper(ThreadVars *tv, void *data, const Packet *p, /* hostname */ if (tx->request_hostname != NULL) { PrintRawUriBuf((char *)aft->buffer->buffer, &aft->buffer->offset, aft->buffer->size, - (uint8_t *)bstr_ptr(tx->request_hostname), - bstr_len(tx->request_hostname)); + (uint8_t *)bstr_ptr(tx->request_hostname), bstr_len(tx->request_hostname)); } else { MemBufferWriteString(aft->buffer, ""); } @@ -445,8 +435,7 @@ static TmEcode LogHttpLogIPWrapper(ThreadVars *tv, void *data, const Packet *p, /* uri */ if (tx->request_uri != NULL) { PrintRawUriBuf((char *)aft->buffer->buffer, &aft->buffer->offset, aft->buffer->size, - (uint8_t *)bstr_ptr(tx->request_uri), - bstr_len(tx->request_uri)); + (uint8_t *)bstr_ptr(tx->request_uri), bstr_len(tx->request_uri)); } LOG_CF_WRITE_STAR_SEPARATOR(aft->buffer); @@ -457,8 +446,7 @@ static TmEcode LogHttpLogIPWrapper(ThreadVars *tv, void *data, const Packet *p, } if (h_user_agent != NULL) { PrintRawUriBuf((char *)aft->buffer->buffer, &aft->buffer->offset, aft->buffer->size, - (uint8_t *)bstr_ptr(h_user_agent->value), - bstr_len(h_user_agent->value)); + (uint8_t *)bstr_ptr(h_user_agent->value), bstr_len(h_user_agent->value)); } else { MemBufferWriteString(aft->buffer, ""); } @@ -468,22 +456,21 @@ static TmEcode LogHttpLogIPWrapper(ThreadVars *tv, void *data, const Packet *p, /* ip/tcp header info */ LOG_CF_WRITE_STAR_SEPARATOR(aft->buffer); - MemBufferWriteString(aft->buffer, - "%s:%" PRIu16 " -> %s:%" PRIu16 "\n", - srcip, sp, dstip, dp); + MemBufferWriteString( + aft->buffer, "%s:%" PRIu16 " -> %s:%" PRIu16 "\n", srcip, sp, dstip, dp); } - aft->uri_cnt ++; + aft->uri_cnt++; hlog->file_ctx->Write((const char *)MEMBUFFER_BUFFER(aft->buffer), - MEMBUFFER_OFFSET(aft->buffer), hlog->file_ctx); + MEMBUFFER_OFFSET(aft->buffer), hlog->file_ctx); end: SCReturnInt(0); - } -int LogHttpLogger(ThreadVars *tv, void *thread_data, const Packet *p, Flow *f, void *state, void *tx, uint64_t tx_id) +int LogHttpLogger(ThreadVars *tv, void *thread_data, const Packet *p, Flow *f, void *state, + void *tx, uint64_t tx_id) { SCEnter(); @@ -493,9 +480,11 @@ int LogHttpLogger(ThreadVars *tv, void *thread_data, const Packet *p, Flow *f, v int r = 0; if (PKT_IS_IPV4(p)) { - r = LogHttpLogIPWrapper(tv, thread_data, p, f, (HtpState *)state, (htp_tx_t *)tx, tx_id, AF_INET); + r = LogHttpLogIPWrapper( + tv, thread_data, p, f, (HtpState *)state, (htp_tx_t *)tx, tx_id, AF_INET); } else if (PKT_IS_IPV6(p)) { - r = LogHttpLogIPWrapper(tv, thread_data, p, f, (HtpState *)state, (htp_tx_t *)tx, tx_id, AF_INET6); + r = LogHttpLogIPWrapper( + tv, thread_data, p, f, (HtpState *)state, (htp_tx_t *)tx, tx_id, AF_INET6); } SCReturnInt(r); @@ -507,8 +496,7 @@ TmEcode LogHttpLogThreadInit(ThreadVars *t, const void *initdata, void **data) if (unlikely(aft == NULL)) return TM_ECODE_FAILED; - if(initdata == NULL) - { + if (initdata == NULL) { SCLogDebug("Error getting context for LogHTTPLog. \"initdata\" argument NULL"); SCFree(aft); return TM_ECODE_FAILED; @@ -521,7 +509,7 @@ TmEcode LogHttpLogThreadInit(ThreadVars *t, const void *initdata, void **data) } /* Use the Output Context (file pointer and mutex) */ - aft->httplog_ctx= ((OutputCtx *)initdata)->data; + aft->httplog_ctx = ((OutputCtx *)initdata)->data; *data = (void *)aft; return TM_ECODE_OK; @@ -549,8 +537,8 @@ TmEcode LogHttpLogThreadDeinit(ThreadVars *t, void *data) OutputInitResult LogHttpLogInitCtx(ConfNode *conf) { OutputInitResult result = { NULL, false }; - LogFileCtx* file_ctx = LogFileNewCtx(); - if(file_ctx == NULL) { + LogFileCtx *file_ctx = LogFileNewCtx(); + if (file_ctx == NULL) { SCLogError("couldn't create new file_ctx"); return result; } @@ -583,7 +571,7 @@ OutputInitResult LogHttpLogInitCtx(ConfNode *conf) httplog_ctx->flags |= LOG_HTTP_CUSTOM; /* Parsing */ - if ( ! LogCustomFormatParse(httplog_ctx->cf, customformat)) { + if (!LogCustomFormatParse(httplog_ctx->cf, customformat)) { goto parsererror; } } else { @@ -620,7 +608,6 @@ OutputInitResult LogHttpLogInitCtx(ConfNode *conf) LogFileFreeCtx(file_ctx); SCFree(httplog_ctx); return result; - } static void LogHttpLogDeInitCtx(OutputCtx *output_ctx) diff --git a/src/log-httplog.h b/src/log-httplog.h index 580191fb99c4..53aaceee7c04 100644 --- a/src/log-httplog.h +++ b/src/log-httplog.h @@ -28,4 +28,3 @@ void LogHttpLogRegister(void); OutputInitResult LogHttpLogInitCtx(ConfNode *); #endif /* __LOG_HTTPLOG_H__ */ - diff --git a/src/log-pcap.c b/src/log-pcap.c index 6039e057b8a4..843a0b532770 100644 --- a/src/log-pcap.c +++ b/src/log-pcap.c @@ -56,15 +56,15 @@ #include "util-profiling.h" #include "util-time.h" -#define DEFAULT_LOG_FILENAME "pcaplog" -#define MODULE_NAME "PcapLog" -#define MIN_LIMIT 4 * 1024 * 1024 -#define DEFAULT_LIMIT 100 * 1024 * 1024 -#define DEFAULT_FILE_LIMIT 0 +#define DEFAULT_LOG_FILENAME "pcaplog" +#define MODULE_NAME "PcapLog" +#define MIN_LIMIT 4 * 1024 * 1024 +#define DEFAULT_LIMIT 100 * 1024 * 1024 +#define DEFAULT_FILE_LIMIT 0 -#define LOGMODE_NORMAL 0 -#define LOGMODE_SGUIL 1 -#define LOGMODE_MULTI 2 +#define LOGMODE_NORMAL 0 +#define LOGMODE_SGUIL 1 +#define LOGMODE_MULTI 2 typedef enum LogModeConditionalType_ { LOGMODE_COND_ALL, @@ -72,20 +72,20 @@ typedef enum LogModeConditionalType_ { LOGMODE_COND_TAG } LogModeConditionalType; -#define RING_BUFFER_MODE_DISABLED 0 -#define RING_BUFFER_MODE_ENABLED 1 +#define RING_BUFFER_MODE_DISABLED 0 +#define RING_BUFFER_MODE_ENABLED 1 -#define TS_FORMAT_SEC 0 -#define TS_FORMAT_USEC 1 +#define TS_FORMAT_SEC 0 +#define TS_FORMAT_USEC 1 -#define USE_STREAM_DEPTH_DISABLED 0 -#define USE_STREAM_DEPTH_ENABLED 1 +#define USE_STREAM_DEPTH_DISABLED 0 +#define USE_STREAM_DEPTH_ENABLED 1 -#define HONOR_PASS_RULES_DISABLED 0 -#define HONOR_PASS_RULES_ENABLED 1 +#define HONOR_PASS_RULES_DISABLED 0 +#define HONOR_PASS_RULES_ENABLED 1 -#define PCAP_SNAPLEN 262144 -#define PCAP_BUFFER_TIMEOUT 1000000 // microseconds +#define PCAP_SNAPLEN 262144 +#define PCAP_BUFFER_TIMEOUT 1000000 // microseconds SC_ATOMIC_DECLARE(uint32_t, thread_cnt); @@ -110,7 +110,7 @@ typedef struct PcapLogProfileData_ { uint64_t cnt; } PcapLogProfileData; -#define MAX_TOKS 9 +#define MAX_TOKS 9 #define MAX_FILENAMELEN 513 enum PcapLogCompressionFormat { @@ -139,10 +139,10 @@ typedef struct PcapLogCompressionData_ { * Used for storing file options. */ typedef struct PcapLogData_ { - int use_stream_depth; /**< use stream depth i.e. ignore packets that reach limit */ - int honor_pass_rules; /**< don't log if pass rules have matched */ + int use_stream_depth; /**< use stream depth i.e. ignore packets that reach limit */ + int honor_pass_rules; /**< don't log if pass rules have matched */ SCMutex plog_lock; - uint64_t pkt_cnt; /**< total number of packets */ + uint64_t pkt_cnt; /**< total number of packets */ struct pcap_pkthdr *h; /**< pcap header struct */ char *filename; /**< current filename */ int mode; /**< normal or sguil */ @@ -168,14 +168,14 @@ typedef struct PcapLogData_ { TAILQ_HEAD(, PcapFileName_) pcap_file_list; - uint32_t thread_number; /**< thread number, first thread is 1, second 2, etc */ - int use_ringbuffer; /**< ring buffer mode enabled or disabled */ - int timestamp_format; /**< timestamp format sec or usec */ - char *prefix; /**< filename prefix */ - const char *suffix; /**< filename suffix */ - char dir[PATH_MAX]; /**< pcap log directory */ + uint32_t thread_number; /**< thread number, first thread is 1, second 2, etc */ + int use_ringbuffer; /**< ring buffer mode enabled or disabled */ + int timestamp_format; /**< timestamp format sec or usec */ + char *prefix; /**< filename prefix */ + const char *suffix; /**< filename suffix */ + char dir[PATH_MAX]; /**< pcap log directory */ int reported; - int threads; /**< number of threads (only set in the global) */ + int threads; /**< number of threads (only set in the global) */ char *filename_parts[MAX_TOKS]; int filename_part_cnt; struct timeval last_pcap_dump; @@ -210,20 +210,18 @@ static bool PcapLogCondition(ThreadVars *, void *, const Packet *); void PcapLogRegister(void) { - OutputRegisterPacketModule(LOGGER_PCAP, MODULE_NAME, "pcap-log", - PcapLogInitCtx, PcapLog, PcapLogCondition, PcapLogDataInit, - PcapLogDataDeinit, NULL); + OutputRegisterPacketModule(LOGGER_PCAP, MODULE_NAME, "pcap-log", PcapLogInitCtx, PcapLog, + PcapLogCondition, PcapLogDataInit, PcapLogDataDeinit, NULL); PcapLogProfileSetup(); SC_ATOMIC_INIT(thread_cnt); SC_ATOMIC_SET(thread_cnt, 1); /* first id is 1 */ return; } -#define PCAPLOG_PROFILE_START \ - uint64_t pcaplog_profile_ticks = UtilCpuGetTicks() +#define PCAPLOG_PROFILE_START uint64_t pcaplog_profile_ticks = UtilCpuGetTicks() -#define PCAPLOG_PROFILE_END(prof) \ - (prof).total += (UtilCpuGetTicks() - pcaplog_profile_ticks); \ +#define PCAPLOG_PROFILE_END(prof) \ + (prof).total += (UtilCpuGetTicks() - pcaplog_profile_ticks); \ (prof).cnt++ static bool PcapLogCondition(ThreadVars *tv, void *thread_data, const Packet *p) @@ -271,8 +269,7 @@ static int PcapLogCloseFile(ThreadVars *t, PcapLogData *pl) /* pcap_dump_close() has closed its output ``file'', * so we need to call fmemopen again. */ - comp->pcap_buf_wrapper = SCFmemopen(comp->pcap_buf, - comp->pcap_buf_size, "w"); + comp->pcap_buf_wrapper = SCFmemopen(comp->pcap_buf, comp->pcap_buf_size, "w"); if (comp->pcap_buf_wrapper == NULL) { SCLogError("SCFmemopen failed: %s", strerror(errno)); return TM_ECODE_FAILED; @@ -293,8 +290,8 @@ static int PcapLogCloseFile(ThreadVars *t, PcapLogData *pl) /* pcap_dump_close did not write any data because we call * pcap_dump_flush() after every write when writing * compressed output. */ - uint64_t bytes_written = LZ4F_compressEnd(comp->lz4f_context, - comp->buffer, comp->buffer_size, NULL); + uint64_t bytes_written = + LZ4F_compressEnd(comp->lz4f_context, comp->buffer, comp->buffer_size, NULL); if (LZ4F_isError(bytes_written)) { SCLogError("LZ4F_compressEnd: %s", LZ4F_getErrorName(bytes_written)); return TM_ECODE_FAILED; @@ -345,7 +342,7 @@ static int PcapLogRotateFile(ThreadVars *t, PcapLogData *pl) PCAPLOG_PROFILE_START; - if (PcapLogCloseFile(t,pl) < 0) { + if (PcapLogCloseFile(t, pl) < 0) { SCLogDebug("PcapLogCloseFile failed"); return -1; } @@ -362,15 +359,15 @@ static int PcapLogRotateFile(ThreadVars *t, PcapLogData *pl) /* Remove directory if Sguil mode and no files left in sguil dir */ if (pl->mode == LOGMODE_SGUIL) { - pfnext = TAILQ_NEXT(pf,next); + pfnext = TAILQ_NEXT(pf, next); if (strcmp(pf->dirname, pfnext->dirname) == 0) { SCLogDebug("Current entry dir %s and next entry %s " - "are equal: not removing dir", + "are equal: not removing dir", pf->dirname, pfnext->dirname); } else { SCLogDebug("current entry %s and %s are " - "not equal: removing dir", + "not equal: removing dir", pf->dirname, pfnext->dirname); if (remove(pf->dirname) != 0) { @@ -414,8 +411,7 @@ static int PcapLogOpenHandles(PcapLogData *pl, const Packet *p) if (pl->pcap_dumper == NULL) { if (pl->compression.format == PCAP_LOG_COMPRESSION_FORMAT_NONE) { - if ((pl->pcap_dumper = pcap_dump_open(pl->pcap_dead_handle, - pl->filename)) == NULL) { + if ((pl->pcap_dumper = pcap_dump_open(pl->pcap_dead_handle, pl->filename)) == NULL) { if (!pl->pcap_open_err) { SCLogError("Error opening dump file %s", pcap_geterr(pl->pcap_dead_handle)); pl->pcap_open_err = true; @@ -453,8 +449,8 @@ static int PcapLogOpenHandles(PcapLogData *pl, const Packet *p) pl->pcap_open_err = false; } - uint64_t bytes_written = LZ4F_compressBegin(comp->lz4f_context, - comp->buffer, comp->buffer_size, NULL); + uint64_t bytes_written = + LZ4F_compressBegin(comp->lz4f_context, comp->buffer, comp->buffer_size, NULL); if (LZ4F_isError(bytes_written)) { SCLogError("LZ4F_compressBegin: %s", LZ4F_getErrorName(bytes_written)); return TM_ECODE_FAILED; @@ -589,7 +585,7 @@ static void PcapLogDumpSegments( * \retval TM_ECODE_OK on succes * \retval TM_ECODE_FAILED on serious error */ -static int PcapLog (ThreadVars *t, void *thread_data, const Packet *p) +static int PcapLog(ThreadVars *t, void *thread_data, const Packet *p) { size_t len; int rotate = 0; @@ -641,7 +637,7 @@ static int PcapLog (ThreadVars *t, void *thread_data, const Packet *p) PcapLogCompressionData *comp = &pl->compression; if (comp->format == PCAP_LOG_COMPRESSION_FORMAT_NONE) { if ((pl->size_current + len) > pl->size_limit || rotate) { - if (PcapLogRotateFile(t,pl) < 0) { + if (PcapLogRotateFile(t, pl) < 0) { PcapLogUnlock(pl); SCLogDebug("rotation of pcap failed"); return TM_ECODE_FAILED; @@ -656,9 +652,8 @@ static int PcapLog (ThreadVars *t, void *thread_data, const Packet *p) * bytes that have been fed into lz4 since the last write, and * act as if they would be written uncompressed. */ - if ((pl->size_current + comp->bytes_in_block + len) > pl->size_limit || - rotate) { - if (PcapLogRotateFile(t,pl) < 0) { + if ((pl->size_current + comp->bytes_in_block + len) > pl->size_limit || rotate) { + if (PcapLogRotateFile(t, pl) < 0) { PcapLogUnlock(pl); SCLogDebug("rotation of pcap failed"); return TM_ECODE_FAILED; @@ -732,8 +727,8 @@ static int PcapLog (ThreadVars *t, void *thread_data, const Packet *p) PCAPLOG_PROFILE_END(pl->profile_write); pl->profile_data_size += len; - SCLogDebug("pl->size_current %"PRIu64", pl->size_limit %"PRIu64, - pl->size_current, pl->size_limit); + SCLogDebug("pl->size_current %" PRIu64 ", pl->size_limit %" PRIu64, pl->size_current, + pl->size_limit); PcapLogUnlock(pl); return TM_ECODE_OK; @@ -801,8 +796,8 @@ static PcapLogData *PcapLogDataCopy(const PcapLogData *pl) SCFree(copy); return NULL; } - copy_comp->pcap_buf_wrapper = SCFmemopen(copy_comp->pcap_buf, - copy_comp->pcap_buf_size, "w"); + copy_comp->pcap_buf_wrapper = + SCFmemopen(copy_comp->pcap_buf, copy_comp->pcap_buf_size, "w"); if (copy_comp->pcap_buf_wrapper == NULL) { SCLogError("SCFmemopen failed: %s", strerror(errno)); SCFree(copy_comp->buffer); @@ -814,8 +809,7 @@ static PcapLogData *PcapLogDataCopy(const PcapLogData *pl) /* Initialize a new compression context. */ - LZ4F_errorCode_t errcode = - LZ4F_createCompressionContext(©_comp->lz4f_context, 1); + LZ4F_errorCode_t errcode = LZ4F_createCompressionContext(©_comp->lz4f_context, 1); if (LZ4F_isError(errcode)) { SCLogError("LZ4F_createCompressionContext failed: %s", LZ4F_getErrorName(errcode)); fclose(copy_comp->pcap_buf_wrapper); @@ -851,8 +845,7 @@ static PcapLogData *PcapLogDataCopy(const PcapLogData *pl) } #ifdef INIT_RING_BUFFER -static int PcapLogGetTimeOfFile(const char *filename, uint64_t *secs, - uint32_t *usecs) +static int PcapLogGetTimeOfFile(const char *filename, uint64_t *secs, uint32_t *usecs) { char buf[PATH_MAX]; size_t copylen; @@ -894,8 +887,7 @@ static TmEcode PcapLogInitRingBuffer(PcapLogData *pl) { char pattern[PATH_MAX]; - SCLogInfo("Initializing PCAP ring buffer for %s/%s.", - pl->dir, pl->prefix); + SCLogInfo("Initializing PCAP ring buffer for %s/%s.", pl->dir, pl->prefix); strlcpy(pattern, pl->dir, PATH_MAX); if (pattern[strlen(pattern) - 1] != '/') { @@ -917,7 +909,7 @@ static TmEcode PcapLogInitRingBuffer(PcapLogData *pl) return TM_ECODE_FAILED; case 'n': { char tmp[PATH_MAX]; - snprintf(tmp, PATH_MAX, "%"PRIu32, pl->thread_number); + snprintf(tmp, PATH_MAX, "%" PRIu32, pl->thread_number); strlcat(pattern, tmp, PATH_MAX); break; } @@ -985,7 +977,7 @@ static TmEcode PcapLogInitRingBuffer(PcapLogData *pl) } else { /* Ordered insert. */ PcapFileName *it = NULL; - TAILQ_FOREACH(it, &pl->pcap_file_list, next) { + TAILQ_FOREACH (it, &pl->pcap_file_list, next) { if (pf->secs < it->secs) { break; } else if (pf->secs == it->secs && pf->usecs < it->usecs) { @@ -1188,8 +1180,7 @@ static void PcapLogDataFree(PcapLogData *pl) SCFree(pl->compression.buffer); fclose(pl->compression.pcap_buf_wrapper); SCFree(pl->compression.pcap_buf); - LZ4F_errorCode_t errcode = - LZ4F_freeCompressionContext(pl->compression.lz4f_context); + LZ4F_errorCode_t errcode = LZ4F_freeCompressionContext(pl->compression.lz4f_context); if (LZ4F_isError(errcode)) { SCLogWarning("Error freeing lz4 context."); } @@ -1212,7 +1203,7 @@ static TmEcode PcapLogDataDeinit(ThreadVars *t, void *thread_data) PcapLogData *pl = td->pcap_log; if (pl->pcap_dumper != NULL) { - if (PcapLogCloseFile(t,pl) < 0) { + if (PcapLogCloseFile(t, pl) < 0) { SCLogDebug("PcapLogCloseFile failed"); } } @@ -1242,7 +1233,6 @@ static TmEcode PcapLogDataDeinit(ThreadVars *t, void *thread_data) return TM_ECODE_OK; } - static int ParseFilename(PcapLogData *pl, const char *filename) { char *toks[MAX_TOKS] = { NULL }; @@ -1255,7 +1245,7 @@ static int ParseFilename(PcapLogData *pl, const char *filename) if (filename) { filename_len = strlen(filename); - if (filename_len > (MAX_FILENAMELEN-1)) { + if (filename_len > (MAX_FILENAMELEN - 1)) { SCLogError("invalid filename option. Max filename-length: %d", MAX_FILENAMELEN - 1); goto error; } @@ -1269,7 +1259,7 @@ static int ParseFilename(PcapLogData *pl, const char *filename) str[s++] = filename[i]; if (filename[i] == '%') { - str[s-1] = '\0'; + str[s - 1] = '\0'; SCLogDebug("filename with %%-sign: %s", str); p = SCStrdup(str); @@ -1279,19 +1269,20 @@ static int ParseFilename(PcapLogData *pl, const char *filename) s = 0; - if (i+1 < (int)strlen(filename)) { + if (i + 1 < (int)strlen(filename)) { if (tok >= MAX_TOKS) { SCLogError("invalid filename option. Max 2 %%-sign options"); goto error; } - if (filename[i+1] != 'n' && filename[i+1] != 't' && filename[i+1] != 'i') { + if (filename[i + 1] != 'n' && filename[i + 1] != 't' && + filename[i + 1] != 'i') { SCLogError( "invalid filename option. Valid %%-sign options: %%n, %%i and %%t"); goto error; } str[0] = '%'; - str[1] = filename[i+1]; + str[1] = filename[i + 1]; str[2] = '\0'; p = SCStrdup(str); if (p == NULL) @@ -1311,7 +1302,6 @@ static int ParseFilename(PcapLogData *pl, const char *filename) if (tok >= MAX_TOKS) { SCLogError("invalid filename option. Max 3 %%-sign options"); goto error; - } str[s++] = '\0'; p = SCStrdup(str); @@ -1410,8 +1400,9 @@ static OutputInitResult PcapLogInitCtx(ConfNode *conf) exit(EXIT_FAILURE); } if (pl->size_limit < 4096) { - SCLogInfo("pcap-log \"limit\" value of %"PRIu64" assumed to be pre-1.2 " - "style: setting limit to %"PRIu64"mb", pl->size_limit, pl->size_limit); + SCLogInfo("pcap-log \"limit\" value of %" PRIu64 " assumed to be pre-1.2 " + "style: setting limit to %" PRIu64 "mb", + pl->size_limit, pl->size_limit); uint64_t size = pl->size_limit * 1024 * 1024; pl->size_limit = size; } else if (pl->size_limit < MIN_LIMIT) { @@ -1451,20 +1442,17 @@ static OutputInitResult PcapLogInitCtx(ConfNode *conf) const char *log_dir = NULL; log_dir = ConfigGetLogDirectory(); - strlcpy(pl->dir, - log_dir, sizeof(pl->dir)); - SCLogInfo("Using log dir %s", pl->dir); + strlcpy(pl->dir, log_dir, sizeof(pl->dir)); + SCLogInfo("Using log dir %s", pl->dir); } } else { if (PathIsAbsolute(s_dir)) { - strlcpy(pl->dir, - s_dir, sizeof(pl->dir)); + strlcpy(pl->dir, s_dir, sizeof(pl->dir)); } else { const char *log_dir = NULL; log_dir = ConfigGetLogDirectory(); - snprintf(pl->dir, sizeof(pl->dir), "%s/%s", - log_dir, s_dir); + snprintf(pl->dir, sizeof(pl->dir), "%s/%s", log_dir, s_dir); } struct stat stat_buf; @@ -1477,8 +1465,7 @@ static OutputInitResult PcapLogInitCtx(ConfNode *conf) SCLogInfo("Using log dir %s", pl->dir); } - const char *compression_str = ConfNodeLookupChildValue(conf, - "compression"); + const char *compression_str = ConfNodeLookupChildValue(conf, "compression"); PcapLogCompressionData *comp = &pl->compression; if (compression_str == NULL || strcmp(compression_str, "none") == 0) { @@ -1502,15 +1489,14 @@ static OutputInitResult PcapLogInitCtx(ConfNode *conf) /* Use SCFmemopen so we can make pcap_dump write to a buffer. */ - comp->pcap_buf_size = sizeof(struct pcap_file_header) + - sizeof(struct pcap_pkthdr) + PCAP_SNAPLEN; + comp->pcap_buf_size = + sizeof(struct pcap_file_header) + sizeof(struct pcap_pkthdr) + PCAP_SNAPLEN; comp->pcap_buf = SCMalloc(comp->pcap_buf_size); if (comp->pcap_buf == NULL) { SCLogError("SCMalloc failed: %s", strerror(errno)); exit(EXIT_FAILURE); } - comp->pcap_buf_wrapper = SCFmemopen(comp->pcap_buf, - comp->pcap_buf_size, "w"); + comp->pcap_buf_wrapper = SCFmemopen(comp->pcap_buf, comp->pcap_buf_size, "w"); if (comp->pcap_buf_wrapper == NULL) { SCLogError("SCFmemopen failed: %s", strerror(errno)); exit(EXIT_FAILURE); @@ -1523,8 +1509,7 @@ static OutputInitResult PcapLogInitCtx(ConfNode *conf) comp->lz4f_prefs.frameInfo.blockMode = LZ4F_blockLinked; if (ConfNodeChildValueIsTrue(conf, "lz4-checksum")) { comp->lz4f_prefs.frameInfo.contentChecksumFlag = 1; - } - else { + } else { comp->lz4f_prefs.frameInfo.contentChecksumFlag = 0; } intmax_t lvl = 0; @@ -1542,7 +1527,7 @@ static OutputInitResult PcapLogInitCtx(ConfNode *conf) /* Allocate resources for lz4. */ LZ4F_errorCode_t errcode = - LZ4F_createCompressionContext(&pl->compression.lz4f_context, 1); + LZ4F_createCompressionContext(&pl->compression.lz4f_context, 1); if (LZ4F_isError(errcode)) { SCLogError("LZ4F_createCompressionContext failed: %s", LZ4F_getErrorName(errcode)); @@ -1551,8 +1536,7 @@ static OutputInitResult PcapLogInitCtx(ConfNode *conf) /* Calculate the size of the lz4 output buffer. */ - comp->buffer_size = LZ4F_compressBound(comp->pcap_buf_size, - &comp->lz4f_prefs); + comp->buffer_size = LZ4F_compressBound(comp->pcap_buf_size, &comp->lz4f_prefs); comp->buffer = SCMalloc(comp->buffer_size); if (unlikely(comp->buffer == NULL)) { @@ -1572,8 +1556,7 @@ static OutputInitResult PcapLogInitCtx(ConfNode *conf) PcapLogDataFree(pl); return result; #endif /* HAVE_LIBLZ4 */ - } - else { + } else { SCLogError("Unsupported pcap-log " "compression format: %s", compression_str); @@ -1606,16 +1589,16 @@ static OutputInitResult PcapLogInitCtx(ConfNode *conf) if (ParseFilename(pl, filename) != 0) exit(EXIT_FAILURE); - SCLogInfo("using %s logging", pl->mode == LOGMODE_SGUIL ? - "Sguil compatible" : (pl->mode == LOGMODE_MULTI ? "multi" : "normal")); + SCLogInfo("using %s logging", pl->mode == LOGMODE_SGUIL + ? "Sguil compatible" + : (pl->mode == LOGMODE_MULTI ? "multi" : "normal")); uint32_t max_file_limit = DEFAULT_FILE_LIMIT; if (conf != NULL) { const char *max_number_of_files_s = NULL; max_number_of_files_s = ConfNodeLookupChildValue(conf, "max-files"); if (max_number_of_files_s != NULL) { - if (StringParseUint32(&max_file_limit, 10, 0, - max_number_of_files_s) == -1) { + if (StringParseUint32(&max_file_limit, 10, 0, max_number_of_files_s) == -1) { SCLogError("Failed to initialize " "pcap-log output, invalid number of files limit: %s", max_number_of_files_s); @@ -1696,7 +1679,7 @@ static void PcapLogFileDeInitCtx(OutputCtx *output_ctx) PcapLogData *pl = output_ctx->data; PcapFileName *pf = NULL; - TAILQ_FOREACH(pf, &pl->pcap_file_list, next) { + TAILQ_FOREACH (pf, &pl->pcap_file_list, next) { SCLogDebug("PCAP files left at exit: %s\n", pf->filename); } PcapLogDataFree(pl); @@ -1747,8 +1730,8 @@ static int PcapLogOpenFileCtx(PcapLogData *pl) char dirname[32], dirfull[PATH_MAX] = ""; - snprintf(dirname, sizeof(dirname), "%04d-%02d-%02d", - tms->tm_year + 1900, tms->tm_mon + 1, tms->tm_mday); + snprintf(dirname, sizeof(dirname), "%04d-%02d-%02d", tms->tm_year + 1900, tms->tm_mon + 1, + tms->tm_mday); /* create the filename to use */ int ret = snprintf(dirfull, sizeof(dirfull), "%s/%s", pl->dir, dirname); @@ -1801,7 +1784,7 @@ static int PcapLogOpenFileCtx(PcapLogData *pl) int i; for (i = 0; i < pl->filename_part_cnt; i++) { - if (pl->filename_parts[i] == NULL ||strlen(pl->filename_parts[i]) == 0) + if (pl->filename_parts[i] == NULL || strlen(pl->filename_parts[i]) == 0) continue; /* handle variables */ @@ -1810,28 +1793,27 @@ static int PcapLogOpenFileCtx(PcapLogData *pl) if (strlen(pl->filename_parts[i]) < 2) continue; - switch(pl->filename_parts[i][1]) { + switch (pl->filename_parts[i][1]) { case 'n': snprintf(str, sizeof(str), "%u", pl->thread_number); break; - case 'i': - { + case 'i': { long thread_id = SCGetThreadIdLong(); - snprintf(str, sizeof(str), "%"PRIu64, (uint64_t)thread_id); + snprintf(str, sizeof(str), "%" PRIu64, (uint64_t)thread_id); break; } case 't': - /* create the filename to use */ - if (pl->timestamp_format == TS_FORMAT_SEC) { - snprintf(str, sizeof(str), "%" PRIu32, (uint32_t)SCTIME_SECS(ts)); - } else { - snprintf(str, sizeof(str), "%" PRIu32 ".%" PRIu32, - (uint32_t)SCTIME_SECS(ts), (uint32_t)SCTIME_USECS(ts)); - } + /* create the filename to use */ + if (pl->timestamp_format == TS_FORMAT_SEC) { + snprintf(str, sizeof(str), "%" PRIu32, (uint32_t)SCTIME_SECS(ts)); + } else { + snprintf(str, sizeof(str), "%" PRIu32 ".%" PRIu32, + (uint32_t)SCTIME_SECS(ts), (uint32_t)SCTIME_USECS(ts)); + } } strlcat(filename, str, PATH_MAX); - /* copy the rest over */ + /* copy the rest over */ } else { strlcat(filename, pl->filename_parts[i], PATH_MAX); } @@ -1891,13 +1873,13 @@ static const char *profiling_pcaplog_file_mode = "a"; static void FormatNumber(uint64_t num, char *str, size_t size) { if (num < 1000UL) - snprintf(str, size, "%"PRIu64, num); + snprintf(str, size, "%" PRIu64, num); else if (num < 1000000UL) - snprintf(str, size, "%3.1fk", (float)num/1000UL); + snprintf(str, size, "%3.1fk", (float)num / 1000UL); else if (num < 1000000000UL) - snprintf(str, size, "%3.1fm", (float)num/1000000UL); + snprintf(str, size, "%3.1fm", (float)num / 1000000UL); else - snprintf(str, size, "%3.1fb", (float)num/1000000000UL); + snprintf(str, size, "%3.1fb", (float)num / 1000000000UL); } static void ProfileReportPair(FILE *fp, const char *name, PcapLogProfileData *p) @@ -1909,7 +1891,7 @@ static void ProfileReportPair(FILE *fp, const char *name, PcapLogProfileData *p) FormatNumber((uint64_t)p->cnt, cnt_str, sizeof(cnt_str)); FormatNumber((uint64_t)p->total, ticks_str, sizeof(ticks_str)); if (p->cnt && p->total) - FormatNumber((uint64_t)(p->total/p->cnt), avg_str, sizeof(avg_str)); + FormatNumber((uint64_t)(p->total / p->cnt), avg_str, sizeof(avg_str)); fprintf(fp, "%-28s %-10s %-10s %-10s\n", name, cnt_str, avg_str, ticks_str); } @@ -1928,13 +1910,13 @@ static void ProfileReport(FILE *fp, PcapLogData *pl) static void FormatBytes(uint64_t num, char *str, size_t size) { if (num < 1000UL) - snprintf(str, size, "%"PRIu64, num); + snprintf(str, size, "%" PRIu64, num); else if (num < 1048576UL) - snprintf(str, size, "%3.1fKiB", (float)num/1000UL); + snprintf(str, size, "%3.1fKiB", (float)num / 1000UL); else if (num < 1073741824UL) - snprintf(str, size, "%3.1fMiB", (float)num/1000000UL); + snprintf(str, size, "%3.1fMiB", (float)num / 1000000UL); else - snprintf(str, size, "%3.1fGiB", (float)num/1000000000UL); + snprintf(str, size, "%3.1fGiB", (float)num / 1000000000UL); } static void PcapLogProfilingDump(PcapLogData *pl) @@ -1951,25 +1933,24 @@ static void PcapLogProfilingDump(PcapLogData *pl) return; } } else { - fp = stdout; + fp = stdout; } /* counters */ fprintf(fp, "\n\nOperation Cnt Avg ticks Total ticks\n"); - fprintf(fp, "---------------------------- ---------- ---------- -----------\n"); + fprintf(fp, "---------------------------- ---------- ---------- -----------\n"); ProfileReport(fp, pl); uint64_t total = pl->profile_write.total + pl->profile_rotate.total + - pl->profile_handles.total + pl->profile_open.total + - pl->profile_close.total + pl->profile_lock.total + - pl->profile_unlock.total; + pl->profile_handles.total + pl->profile_open.total + pl->profile_close.total + + pl->profile_lock.total + pl->profile_unlock.total; /* overall stats */ - fprintf(fp, "\nOverall: %"PRIu64" bytes written, average %d bytes per write.\n", - pl->profile_data_size, pl->profile_write.cnt ? - (int)(pl->profile_data_size / pl->profile_write.cnt) : 0); - fprintf(fp, " PCAP data structure overhead: %"PRIuMAX" per write.\n", - (uintmax_t)sizeof(struct pcap_pkthdr)); + fprintf(fp, "\nOverall: %" PRIu64 " bytes written, average %d bytes per write.\n", + pl->profile_data_size, + pl->profile_write.cnt ? (int)(pl->profile_data_size / pl->profile_write.cnt) : 0); + fprintf(fp, " PCAP data structure overhead: %" PRIuMAX " per write.\n", + (uintmax_t)sizeof(struct pcap_pkthdr)); /* print total bytes written */ char bytes_str[32]; @@ -1978,17 +1959,17 @@ static void PcapLogProfilingDump(PcapLogData *pl) /* ticks per MiB and GiB */ uint64_t ticks_per_mib = 0, ticks_per_gib = 0; - uint64_t mib = pl->profile_data_size/(1024*1024); + uint64_t mib = pl->profile_data_size / (1024 * 1024); if (mib) - ticks_per_mib = total/mib; + ticks_per_mib = total / mib; char ticks_per_mib_str[32] = "n/a"; if (ticks_per_mib > 0) FormatNumber(ticks_per_mib, ticks_per_mib_str, sizeof(ticks_per_mib_str)); fprintf(fp, " Ticks per MiB: %s\n", ticks_per_mib_str); - uint64_t gib = pl->profile_data_size/(1024*1024*1024); + uint64_t gib = pl->profile_data_size / (1024 * 1024 * 1024); if (gib) - ticks_per_gib = total/gib; + ticks_per_gib = total / gib; char ticks_per_gib_str[32] = "n/a"; if (ticks_per_gib > 0) FormatNumber(ticks_per_gib, ticks_per_gib_str, sizeof(ticks_per_gib_str)); @@ -2025,8 +2006,8 @@ void PcapLogProfileSetup(void) } profiling_pcaplog_output_to_file = 1; - SCLogInfo("pcap-log profiling output goes to %s (mode %s)", - profiling_pcaplog_file_name, profiling_pcaplog_file_mode); + SCLogInfo("pcap-log profiling output goes to %s (mode %s)", profiling_pcaplog_file_name, + profiling_pcaplog_file_mode); } } } diff --git a/src/log-pcap.h b/src/log-pcap.h index 731a365b854c..e5b271d10238 100644 --- a/src/log-pcap.h +++ b/src/log-pcap.h @@ -15,7 +15,6 @@ * 02110-1301, USA. */ - /** * \file * diff --git a/src/log-stats.c b/src/log-stats.c index 69669e9c2257..7b09cf1cb3e0 100644 --- a/src/log-stats.c +++ b/src/log-stats.c @@ -45,12 +45,12 @@ #include "util-time.h" #define DEFAULT_LOG_FILENAME "stats.log" -#define MODULE_NAME "LogStatsLog" -#define OUTPUT_BUFFER_SIZE 16384 +#define MODULE_NAME "LogStatsLog" +#define OUTPUT_BUFFER_SIZE 16384 -#define LOG_STATS_TOTALS (1<<0) -#define LOG_STATS_THREADS (1<<1) -#define LOG_STATS_NULLS (1<<2) +#define LOG_STATS_TOTALS (1 << 0) +#define LOG_STATS_THREADS (1 << 1) +#define LOG_STATS_NULLS (1 << 2) TmEcode LogStatsLogThreadInit(ThreadVars *, const void *, void **); TmEcode LogStatsLogThreadDeinit(ThreadVars *, void *); @@ -81,25 +81,25 @@ static int LogStatsLogger(ThreadVars *tv, void *thread_data, const StatsTable *s /* Calculate the Engine uptime */ double up_time_d = difftime(tval.tv_sec, st->start_time); int up_time = (int)up_time_d; // ignoring risk of overflow here - int sec = up_time % 60; // Seconds in a minute + int sec = up_time % 60; // Seconds in a minute int in_min = up_time / 60; - int min = in_min % 60; // Minutes in a hour + int min = in_min % 60; // Minutes in a hour int in_hours = in_min / 60; - int hours = in_hours % 24; // Hours in a day + int hours = in_hours % 24; // Hours in a day int days = in_hours / 24; MemBufferWriteString(aft->buffer, "----------------------------------------------" - "--------------------------------------\n"); - MemBufferWriteString(aft->buffer, "Date: %" PRId32 "/%" PRId32 "/%04d -- " - "%02d:%02d:%02d (uptime: %"PRId32"d, %02dh %02dm %02ds)\n", - tms->tm_mon + 1, tms->tm_mday, tms->tm_year + 1900, tms->tm_hour, - tms->tm_min, tms->tm_sec, days, hours, min, sec); + "--------------------------------------\n"); + MemBufferWriteString(aft->buffer, + "Date: %" PRId32 "/%" PRId32 "/%04d -- " + "%02d:%02d:%02d (uptime: %" PRId32 "d, %02dh %02dm %02ds)\n", + tms->tm_mon + 1, tms->tm_mday, tms->tm_year + 1900, tms->tm_hour, tms->tm_min, + tms->tm_sec, days, hours, min, sec); MemBufferWriteString(aft->buffer, "----------------------------------------------" - "--------------------------------------\n"); - MemBufferWriteString(aft->buffer, "%-45s | %-25s | %-s\n", "Counter", "TM Name", - "Value"); + "--------------------------------------\n"); + MemBufferWriteString(aft->buffer, "%-45s | %-25s | %-s\n", "Counter", "TM Name", "Value"); MemBufferWriteString(aft->buffer, "----------------------------------------------" - "--------------------------------------\n"); + "--------------------------------------\n"); /* global stats */ uint32_t u = 0; @@ -156,7 +156,7 @@ static int LogStatsLogger(ThreadVars *tv, void *thread_data, const StatsTable *s } aft->statslog_ctx->file_ctx->Write((const char *)MEMBUFFER_BUFFER(aft->buffer), - MEMBUFFER_OFFSET(aft->buffer), aft->statslog_ctx->file_ctx); + MEMBUFFER_OFFSET(aft->buffer), aft->statslog_ctx->file_ctx); MemBufferReset(aft->buffer); @@ -169,8 +169,7 @@ TmEcode LogStatsLogThreadInit(ThreadVars *t, const void *initdata, void **data) if (unlikely(aft == NULL)) return TM_ECODE_FAILED; - if(initdata == NULL) - { + if (initdata == NULL) { SCLogDebug("Error getting context for LogStats. \"initdata\" argument NULL"); SCFree(aft); return TM_ECODE_FAILED; @@ -183,7 +182,7 @@ TmEcode LogStatsLogThreadInit(ThreadVars *t, const void *initdata, void **data) } /* Use the Output Context (file pointer and mutex) */ - aft->statslog_ctx= ((OutputCtx *)initdata)->data; + aft->statslog_ctx = ((OutputCtx *)initdata)->data; *data = (void *)aft; return TM_ECODE_OK; @@ -283,9 +282,8 @@ static void LogStatsLogDeInitCtx(OutputCtx *output_ctx) SCFree(output_ctx); } -void LogStatsLogRegister (void) +void LogStatsLogRegister(void) { - OutputRegisterStatsModule(LOGGER_STATS, MODULE_NAME, "stats", - LogStatsLogInitCtx, LogStatsLogger, LogStatsLogThreadInit, - LogStatsLogThreadDeinit, NULL); + OutputRegisterStatsModule(LOGGER_STATS, MODULE_NAME, "stats", LogStatsLogInitCtx, + LogStatsLogger, LogStatsLogThreadInit, LogStatsLogThreadDeinit, NULL); } diff --git a/src/log-tcp-data.c b/src/log-tcp-data.c index 9c67497c16c6..5ba60fc63cb1 100644 --- a/src/log-tcp-data.c +++ b/src/log-tcp-data.c @@ -41,15 +41,17 @@ TmEcode LogTcpDataLogThreadInit(ThreadVars *, const void *, void **); TmEcode LogTcpDataLogThreadDeinit(ThreadVars *, void *); static void LogTcpDataLogDeInitCtx(OutputCtx *); -int LogTcpDataLogger(ThreadVars *tv, void *thread_data, const Flow *f, const uint8_t *data, uint32_t data_len, uint64_t tx_id, uint8_t flags); +int LogTcpDataLogger(ThreadVars *tv, void *thread_data, const Flow *f, const uint8_t *data, + uint32_t data_len, uint64_t tx_id, uint8_t flags); -void LogTcpDataLogRegister (void) { - OutputRegisterStreamingModule(LOGGER_TCP_DATA, MODULE_NAME, "tcp-data", - LogTcpDataLogInitCtx, LogTcpDataLogger, STREAMING_TCP_DATA, - LogTcpDataLogThreadInit, LogTcpDataLogThreadDeinit, NULL); +void LogTcpDataLogRegister(void) +{ + OutputRegisterStreamingModule(LOGGER_TCP_DATA, MODULE_NAME, "tcp-data", LogTcpDataLogInitCtx, + LogTcpDataLogger, STREAMING_TCP_DATA, LogTcpDataLogThreadInit, + LogTcpDataLogThreadDeinit, NULL); OutputRegisterStreamingModule(LOGGER_TCP_DATA, MODULE_NAME, "http-body-data", - LogTcpDataLogInitCtx, LogTcpDataLogger, STREAMING_HTTP_BODIES, - LogTcpDataLogThreadInit, LogTcpDataLogThreadDeinit, NULL); + LogTcpDataLogInitCtx, LogTcpDataLogger, STREAMING_HTTP_BODIES, LogTcpDataLogThreadInit, + LogTcpDataLogThreadDeinit, NULL); } typedef struct LogTcpDataFileCtx_ { @@ -91,13 +93,11 @@ static int LogTcpDataLoggerDir(ThreadVars *tv, void *thread_data, const Flow *f, char tx[64] = { 0 }; if (flags & OUTPUT_STREAMING_FLAG_TRANSACTION) { - snprintf(tx, sizeof(tx), "%"PRIu64, tx_id); + snprintf(tx, sizeof(tx), "%" PRIu64, tx_id); } - snprintf(name, sizeof(name), "%s/%s/%s_%u-%s_%u-%s-%s.data", - td->log_dir, - td->type == STREAMING_HTTP_BODIES ? "http" : "tcp", - srcip, f->sp, dstip, f->dp, tx, + snprintf(name, sizeof(name), "%s/%s/%s_%u-%s_%u-%s-%s.data", td->log_dir, + td->type == STREAMING_HTTP_BODIES ? "http" : "tcp", srcip, f->sp, dstip, f->dp, tx, flags & OUTPUT_STREAMING_FLAG_TOSERVER ? "ts" : "tc"); FILE *fp = fopen(name, mode); @@ -131,16 +131,15 @@ static int LogTcpDataLoggerFile(ThreadVars *tv, void *thread_data, const Flow *f } char name[PATH_MAX]; - snprintf(name, sizeof(name), "%s_%u-%s_%u-%s:", - srcip, f->sp, dstip, f->dp, + snprintf(name, sizeof(name), "%s_%u-%s_%u-%s:", srcip, f->sp, dstip, f->dp, flags & OUTPUT_STREAMING_FLAG_TOSERVER ? "ts" : "tc"); - PrintRawUriBuf((char *)aft->buffer->buffer, &aft->buffer->offset, - aft->buffer->size, (uint8_t *)name,strlen(name)); + PrintRawUriBuf((char *)aft->buffer->buffer, &aft->buffer->offset, aft->buffer->size, + (uint8_t *)name, strlen(name)); MemBufferWriteString(aft->buffer, "\n"); - PrintRawDataToBuffer(aft->buffer->buffer, &aft->buffer->offset, - aft->buffer->size, (uint8_t *)data,data_len); + PrintRawDataToBuffer(aft->buffer->buffer, &aft->buffer->offset, aft->buffer->size, + (uint8_t *)data, data_len); td->file_ctx->Write((const char *)MEMBUFFER_BUFFER(aft->buffer), MEMBUFFER_OFFSET(aft->buffer), td->file_ctx); @@ -148,8 +147,8 @@ static int LogTcpDataLoggerFile(ThreadVars *tv, void *thread_data, const Flow *f SCReturnInt(TM_ECODE_OK); } -int LogTcpDataLogger(ThreadVars *tv, void *thread_data, const Flow *f, - const uint8_t *data, uint32_t data_len, uint64_t tx_id, uint8_t flags) +int LogTcpDataLogger(ThreadVars *tv, void *thread_data, const Flow *f, const uint8_t *data, + uint32_t data_len, uint64_t tx_id, uint8_t flags) { SCEnter(); LogTcpDataLogThread *aft = thread_data; @@ -169,8 +168,7 @@ TmEcode LogTcpDataLogThreadInit(ThreadVars *t, const void *initdata, void **data if (unlikely(aft == NULL)) return TM_ECODE_FAILED; - if(initdata == NULL) - { + if (initdata == NULL) { SCLogDebug("Error getting context. \"initdata\" argument NULL"); SCFree(aft); return TM_ECODE_FAILED; @@ -183,7 +181,7 @@ TmEcode LogTcpDataLogThreadInit(ThreadVars *t, const void *initdata, void **data } /* Use the Output Context (file pointer and mutex) */ - aft->tcpdatalog_ctx= ((OutputCtx *)initdata)->data; + aft->tcpdatalog_ctx = ((OutputCtx *)initdata)->data; *data = (void *)aft; return TM_ECODE_OK; @@ -216,7 +214,7 @@ OutputInitResult LogTcpDataLogInitCtx(ConfNode *conf) strlcpy(filename, DEFAULT_LOG_FILENAME, sizeof(filename)); LogFileCtx *file_ctx = LogFileNewCtx(); - if(file_ctx == NULL) { + if (file_ctx == NULL) { SCLogError("couldn't create new file_ctx"); return result; } @@ -299,7 +297,6 @@ OutputInitResult LogTcpDataLogInitCtx(ConfNode *conf) SCFree(tcpdatalog_ctx); SCLogError("Syntax error in custom http log format string."); return result; - } static void LogTcpDataLogDeInitCtx(OutputCtx *output_ctx) diff --git a/src/log-tlslog.c b/src/log-tlslog.c index 6217c5fe9813..178df2c180a7 100644 --- a/src/log-tlslog.c +++ b/src/log-tlslog.c @@ -78,7 +78,7 @@ typedef struct LogTlsFileCtx_ { LogFileCtx *file_ctx; - uint32_t flags; /** Store mode */ + uint32_t flags; /** Store mode */ LogCustomFormat *cf; } LogTlsFileCtx; @@ -92,23 +92,18 @@ typedef struct LogTlsLogThread_ { MemBuffer *buffer; } LogTlsLogThread; -int TLSGetIPInformations(const Packet *p, char* srcip, size_t srcip_len, - Port* sp, char* dstip, size_t dstip_len, Port* dp, - int ipproto) +int TLSGetIPInformations(const Packet *p, char *srcip, size_t srcip_len, Port *sp, char *dstip, + size_t dstip_len, Port *dp, int ipproto) { if ((PKT_IS_TOSERVER(p))) { switch (ipproto) { case AF_INET: - PrintInet(AF_INET, (const void *) GET_IPV4_SRC_ADDR_PTR(p), - srcip, srcip_len); - PrintInet(AF_INET, (const void *) GET_IPV4_DST_ADDR_PTR(p), - dstip, dstip_len); + PrintInet(AF_INET, (const void *)GET_IPV4_SRC_ADDR_PTR(p), srcip, srcip_len); + PrintInet(AF_INET, (const void *)GET_IPV4_DST_ADDR_PTR(p), dstip, dstip_len); break; case AF_INET6: - PrintInet(AF_INET6, (const void *) GET_IPV6_SRC_ADDR(p), srcip, - srcip_len); - PrintInet(AF_INET6, (const void *) GET_IPV6_DST_ADDR(p), dstip, - dstip_len); + PrintInet(AF_INET6, (const void *)GET_IPV6_SRC_ADDR(p), srcip, srcip_len); + PrintInet(AF_INET6, (const void *)GET_IPV6_DST_ADDR(p), dstip, dstip_len); break; default: return 0; @@ -118,16 +113,12 @@ int TLSGetIPInformations(const Packet *p, char* srcip, size_t srcip_len, } else { switch (ipproto) { case AF_INET: - PrintInet(AF_INET, (const void *) GET_IPV4_DST_ADDR_PTR(p), - srcip, srcip_len); - PrintInet(AF_INET, (const void *) GET_IPV4_SRC_ADDR_PTR(p), - dstip, dstip_len); + PrintInet(AF_INET, (const void *)GET_IPV4_DST_ADDR_PTR(p), srcip, srcip_len); + PrintInet(AF_INET, (const void *)GET_IPV4_SRC_ADDR_PTR(p), dstip, dstip_len); break; case AF_INET6: - PrintInet(AF_INET6, (const void *) GET_IPV6_DST_ADDR(p), srcip, - srcip_len); - PrintInet(AF_INET6, (const void *) GET_IPV6_SRC_ADDR(p), dstip, - dstip_len); + PrintInet(AF_INET6, (const void *)GET_IPV6_DST_ADDR(p), srcip, srcip_len); + PrintInet(AF_INET6, (const void *)GET_IPV6_SRC_ADDR(p), dstip, dstip_len); break; default: return 0; @@ -138,8 +129,7 @@ int TLSGetIPInformations(const Packet *p, char* srcip, size_t srcip_len, return 1; } -static TmEcode LogTlsLogThreadInit(ThreadVars *t, const void *initdata, - void **data) +static TmEcode LogTlsLogThreadInit(ThreadVars *t, const void *initdata, void **data) { LogTlsLogThread *aft = SCCalloc(1, sizeof(LogTlsLogThread)); if (unlikely(aft == NULL)) @@ -158,7 +148,7 @@ static TmEcode LogTlsLogThreadInit(ThreadVars *t, const void *initdata, } /* Use the Output Context (file pointer and mutex) */ - aft->tlslog_ctx = ((OutputCtx *) initdata)->data; + aft->tlslog_ctx = ((OutputCtx *)initdata)->data; *data = (void *)aft; return TM_ECODE_OK; @@ -180,7 +170,7 @@ static TmEcode LogTlsLogThreadDeinit(ThreadVars *t, void *data) static void LogTlsLogDeInitCtx(OutputCtx *output_ctx) { - LogTlsFileCtx *tlslog_ctx = (LogTlsFileCtx *) output_ctx->data; + LogTlsFileCtx *tlslog_ctx = (LogTlsFileCtx *)output_ctx->data; LogFileFreeCtx(tlslog_ctx->file_ctx); LogCustomFormatFree(tlslog_ctx->cf); SCFree(tlslog_ctx); @@ -204,7 +194,7 @@ static void LogTlsLogExitPrintStats(ThreadVars *tv, void *data) static OutputInitResult LogTlsLogInitCtx(ConfNode *conf) { OutputInitResult result = { NULL, false }; - LogFileCtx* file_ctx = LogFileNewCtx(); + LogFileCtx *file_ctx = LogFileNewCtx(); if (file_ctx == NULL) { SCLogError("LogTlsLogInitCtx: Couldn't " @@ -248,8 +238,7 @@ static OutputInitResult LogTlsLogInitCtx(ConfNode *conf) } } - const char *resumption = ConfNodeLookupChildValue(conf, - "session-resumption"); + const char *resumption = ConfNodeLookupChildValue(conf, "session-resumption"); if (resumption == NULL || ConfValIsTrue(resumption)) { tlslog_ctx->flags |= LOG_TLS_SESSION_RESUMPTION; } @@ -290,14 +279,13 @@ static void LogTlsLogVersion(MemBuffer *buffer, uint16_t version) static void LogTlsLogDate(MemBuffer *buffer, const char *title, int64_t *date) { - char timebuf[64] = {0}; + char timebuf[64] = { 0 }; if (sc_x509_format_timestamp(*date, timebuf, sizeof(timebuf))) { MemBufferWriteString(buffer, "%s='%s'", title, timebuf); } } -static void LogTlsLogString(MemBuffer *buffer, const char *title, - const char *value) +static void LogTlsLogString(MemBuffer *buffer, const char *title, const char *value) { MemBufferWriteString(buffer, "%s='%s'", title, value); } @@ -307,18 +295,14 @@ static void LogTlsLogBasic(LogTlsLogThread *aft, SSLState *ssl_state, const SCTi { char timebuf[64]; CreateTimeString(ts, timebuf, sizeof(timebuf)); - MemBufferWriteString(aft->buffer, - "%s %s:%d -> %s:%d TLS:", - timebuf, srcip, sp, dstip, dp); + MemBufferWriteString(aft->buffer, "%s %s:%d -> %s:%d TLS:", timebuf, srcip, sp, dstip, dp); if (ssl_state->server_connp.cert0_subject != NULL) { - MemBufferWriteString(aft->buffer, " Subject='%s'", - ssl_state->server_connp.cert0_subject); + MemBufferWriteString(aft->buffer, " Subject='%s'", ssl_state->server_connp.cert0_subject); } if (ssl_state->server_connp.cert0_issuerdn != NULL) { - MemBufferWriteString(aft->buffer, " Issuerdn='%s'", - ssl_state->server_connp.cert0_issuerdn); + MemBufferWriteString(aft->buffer, " Issuerdn='%s'", ssl_state->server_connp.cert0_issuerdn); } if (ssl_state->flags & SSL_AL_FLAG_SESSION_RESUMED) { @@ -338,8 +322,7 @@ static void LogTlsLogExtended(LogTlsLogThread *aft, SSLState *ssl_state, const S { if (ssl_state->server_connp.cert0_fingerprint != NULL) { LOG_CF_WRITE_SPACE_SEPARATOR(aft->buffer); - LogTlsLogString(aft->buffer, "SHA1", - ssl_state->server_connp.cert0_fingerprint); + LogTlsLogString(aft->buffer, "SHA1", ssl_state->server_connp.cert0_fingerprint); } if (ssl_state->client_connp.sni != NULL) { LOG_CF_WRITE_SPACE_SEPARATOR(aft->buffer); @@ -347,8 +330,7 @@ static void LogTlsLogExtended(LogTlsLogThread *aft, SSLState *ssl_state, const S } if (ssl_state->server_connp.cert0_serial != NULL) { LOG_CF_WRITE_SPACE_SEPARATOR(aft->buffer); - LogTlsLogString(aft->buffer, "SERIAL", - ssl_state->server_connp.cert0_serial); + LogTlsLogString(aft->buffer, "SERIAL", ssl_state->server_connp.cert0_serial); } LOG_CF_WRITE_SPACE_SEPARATOR(aft->buffer); @@ -356,13 +338,11 @@ static void LogTlsLogExtended(LogTlsLogThread *aft, SSLState *ssl_state, const S if (ssl_state->server_connp.cert0_not_before != 0) { LOG_CF_WRITE_SPACE_SEPARATOR(aft->buffer); - LogTlsLogDate(aft->buffer, "NOTBEFORE", - &ssl_state->server_connp.cert0_not_before); + LogTlsLogDate(aft->buffer, "NOTBEFORE", &ssl_state->server_connp.cert0_not_before); } if (ssl_state->server_connp.cert0_not_after != 0) { LOG_CF_WRITE_SPACE_SEPARATOR(aft->buffer); - LogTlsLogDate(aft->buffer, "NOTAFTER", - &ssl_state->server_connp.cert0_not_after); + LogTlsLogDate(aft->buffer, "NOTAFTER", &ssl_state->server_connp.cert0_not_after); } } @@ -374,107 +354,97 @@ static void LogTlsLogCustom(LogTlsLogThread *aft, SSLState *ssl_state, const SCT uint32_t i; char buf[64]; - for (i = 0; i < tlslog_ctx->cf->cf_n; i++) - { + for (i = 0; i < tlslog_ctx->cf->cf_n; i++) { LogCustomFormatNode *node = tlslog_ctx->cf->cf_nodes[i]; if (!node) /* Should never happen */ continue; switch (node->type) { case LOG_CF_LITERAL: - /* LITERAL */ + /* LITERAL */ MemBufferWriteString(aft->buffer, "%s", node->data); break; case LOG_CF_TIMESTAMP: - /* TIMESTAMP */ + /* TIMESTAMP */ LogCustomFormatWriteTimestamp(aft->buffer, node->data, ts); break; case LOG_CF_TIMESTAMP_U: - /* TIMESTAMP USECONDS */ - snprintf(buf, sizeof(buf), "%06u", (unsigned int)SCTIME_USECS(ts)); - PrintRawUriBuf((char *)aft->buffer->buffer, &aft->buffer->offset, aft->buffer->size, - (uint8_t *)buf, MIN(strlen(buf), 6)); - break; + /* TIMESTAMP USECONDS */ + snprintf(buf, sizeof(buf), "%06u", (unsigned int)SCTIME_USECS(ts)); + PrintRawUriBuf((char *)aft->buffer->buffer, &aft->buffer->offset, aft->buffer->size, + (uint8_t *)buf, MIN(strlen(buf), 6)); + break; case LOG_CF_CLIENT_IP: - /* CLIENT IP ADDRESS */ - PrintRawUriBuf((char *)aft->buffer->buffer, - &aft->buffer->offset, aft->buffer->size, - (uint8_t *)srcip,strlen(srcip)); + /* CLIENT IP ADDRESS */ + PrintRawUriBuf((char *)aft->buffer->buffer, &aft->buffer->offset, aft->buffer->size, + (uint8_t *)srcip, strlen(srcip)); break; case LOG_CF_SERVER_IP: - /* SERVER IP ADDRESS */ - PrintRawUriBuf((char *)aft->buffer->buffer, - &aft->buffer->offset, aft->buffer->size, - (uint8_t *)dstip, strlen(dstip)); + /* SERVER IP ADDRESS */ + PrintRawUriBuf((char *)aft->buffer->buffer, &aft->buffer->offset, aft->buffer->size, + (uint8_t *)dstip, strlen(dstip)); break; case LOG_CF_CLIENT_PORT: - /* CLIENT PORT */ + /* CLIENT PORT */ MemBufferWriteString(aft->buffer, "%" PRIu16 "", sp); break; case LOG_CF_SERVER_PORT: - /* SERVER PORT */ + /* SERVER PORT */ MemBufferWriteString(aft->buffer, "%" PRIu16 "", dp); break; case LOG_TLS_CF_VERSION: LogTlsLogVersion(aft->buffer, ssl_state->server_connp.version); break; case LOG_TLS_CF_DATE_NOT_BEFORE: - LogTlsLogDate(aft->buffer, "NOTBEFORE", - &ssl_state->server_connp.cert0_not_before); + LogTlsLogDate(aft->buffer, "NOTBEFORE", &ssl_state->server_connp.cert0_not_before); break; case LOG_TLS_CF_DATE_NOT_AFTER: - LogTlsLogDate(aft->buffer, "NOTAFTER", - &ssl_state->server_connp.cert0_not_after); + LogTlsLogDate(aft->buffer, "NOTAFTER", &ssl_state->server_connp.cert0_not_after); break; case LOG_TLS_CF_SHA1: if (ssl_state->server_connp.cert0_fingerprint != NULL) { - MemBufferWriteString(aft->buffer, "%s", - ssl_state->server_connp.cert0_fingerprint); + MemBufferWriteString( + aft->buffer, "%s", ssl_state->server_connp.cert0_fingerprint); } else { LOG_CF_WRITE_UNKNOWN_VALUE(aft->buffer); } break; case LOG_TLS_CF_SNI: if (ssl_state->client_connp.sni != NULL) { - MemBufferWriteString(aft->buffer, "%s", - ssl_state->client_connp.sni); + MemBufferWriteString(aft->buffer, "%s", ssl_state->client_connp.sni); } else { LOG_CF_WRITE_UNKNOWN_VALUE(aft->buffer); } break; case LOG_TLS_CF_SUBJECT: if (ssl_state->server_connp.cert0_subject != NULL) { - MemBufferWriteString(aft->buffer, "%s", - ssl_state->server_connp.cert0_subject); + MemBufferWriteString(aft->buffer, "%s", ssl_state->server_connp.cert0_subject); } else { LOG_CF_WRITE_UNKNOWN_VALUE(aft->buffer); } break; case LOG_TLS_CF_ISSUER: if (ssl_state->server_connp.cert0_issuerdn != NULL) { - MemBufferWriteString(aft->buffer, "%s", - ssl_state->server_connp.cert0_issuerdn); + MemBufferWriteString(aft->buffer, "%s", ssl_state->server_connp.cert0_issuerdn); } else { LOG_CF_WRITE_UNKNOWN_VALUE(aft->buffer); } break; case LOG_TLS_CF_EXTENDED: - /* Extended format */ + /* Extended format */ LogTlsLogExtended(aft, ssl_state, ts, srcip, sp, dstip, dp); break; default: - /* NO MATCH */ + /* NO MATCH */ MemBufferWriteString(aft->buffer, LOG_CF_NONE); - SCLogDebug("No matching parameter %%%c for custom tls log.", - node->type); + SCLogDebug("No matching parameter %%%c for custom tls log.", node->type); break; } } } - -static int LogTlsLogger(ThreadVars *tv, void *thread_data, const Packet *p, - Flow *f, void *state, void *tx, uint64_t tx_id) +static int LogTlsLogger(ThreadVars *tv, void *thread_data, const Packet *p, Flow *f, void *state, + void *tx, uint64_t tx_id) { LogTlsLogThread *aft = (LogTlsLogThread *)thread_data; LogTlsFileCtx *hlog = aft->tlslog_ctx; @@ -486,9 +456,9 @@ static int LogTlsLogger(ThreadVars *tv, void *thread_data, const Packet *p, } if (((hlog->flags & LOG_TLS_SESSION_RESUMPTION) == 0 || - (ssl_state->flags & SSL_AL_FLAG_SESSION_RESUMED) == 0) && + (ssl_state->flags & SSL_AL_FLAG_SESSION_RESUMED) == 0) && (ssl_state->server_connp.cert0_issuerdn == NULL || - ssl_state->server_connp.cert0_subject == NULL) && + ssl_state->server_connp.cert0_subject == NULL) && ((ssl_state->flags & SSL_AL_FLAG_LOG_WITHOUT_CERT) == 0)) { return 0; } @@ -496,8 +466,7 @@ static int LogTlsLogger(ThreadVars *tv, void *thread_data, const Packet *p, char srcip[PRINT_BUF_LEN], dstip[PRINT_BUF_LEN]; Port sp, dp; - if (!TLSGetIPInformations(p, srcip, PRINT_BUF_LEN, &sp, dstip, - PRINT_BUF_LEN, &dp, ipproto)) { + if (!TLSGetIPInformations(p, srcip, PRINT_BUF_LEN, &sp, dstip, PRINT_BUF_LEN, &dp, ipproto)) { return 0; } @@ -517,15 +486,14 @@ static int LogTlsLogger(ThreadVars *tv, void *thread_data, const Packet *p, aft->tls_cnt++; hlog->file_ctx->Write((const char *)MEMBUFFER_BUFFER(aft->buffer), - MEMBUFFER_OFFSET(aft->buffer), hlog->file_ctx); + MEMBUFFER_OFFSET(aft->buffer), hlog->file_ctx); return 0; } void LogTlsLogRegister(void) { - OutputRegisterTxModuleWithProgress(LOGGER_TLS, MODULE_NAME, "tls-log", - LogTlsLogInitCtx, ALPROTO_TLS, LogTlsLogger, TLS_HANDSHAKE_DONE, - TLS_HANDSHAKE_DONE, LogTlsLogThreadInit, LogTlsLogThreadDeinit, - LogTlsLogExitPrintStats); + OutputRegisterTxModuleWithProgress(LOGGER_TLS, MODULE_NAME, "tls-log", LogTlsLogInitCtx, + ALPROTO_TLS, LogTlsLogger, TLS_HANDSHAKE_DONE, TLS_HANDSHAKE_DONE, LogTlsLogThreadInit, + LogTlsLogThreadDeinit, LogTlsLogExitPrintStats); } diff --git a/src/log-tlslog.h b/src/log-tlslog.h index 87c2fbcf5db7..8fef9d146ca3 100644 --- a/src/log-tlslog.h +++ b/src/log-tlslog.h @@ -27,9 +27,7 @@ void LogTlsLogRegister(void); -int TLSGetIPInformations(const Packet *p, char* srcip, size_t srcip_len, - Port* sp, char* dstip, size_t dstip_len, - Port* dp, int ipproto); +int TLSGetIPInformations(const Packet *p, char *srcip, size_t srcip_len, Port *sp, char *dstip, + size_t dstip_len, Port *dp, int ipproto); #endif /* __LOG_TLSLOG_H__ */ - diff --git a/src/log-tlsstore.c b/src/log-tlsstore.c index 50e6c6e5c481..12f254c3f4f9 100644 --- a/src/log-tlsstore.c +++ b/src/log-tlsstore.c @@ -52,8 +52,8 @@ static char logging_dir_not_writable; typedef struct LogTlsStoreLogThread_ { uint32_t tls_cnt; - uint8_t* enc_buf; - size_t enc_buf_len; + uint8_t *enc_buf; + size_t enc_buf_len; } LogTlsStoreLogThread; static int CreateFileName(const Packet *p, SSLState *state, char *filename, size_t filename_size) @@ -77,12 +77,12 @@ static void LogTlsLogPem(LogTlsStoreLogThread *aft, const Packet *p, SSLState *s { #define PEMHEADER "-----BEGIN CERTIFICATE-----\n" #define PEMFOOTER "-----END CERTIFICATE-----\n" - //Logging pem certificate + // Logging pem certificate char filename[PATH_MAX] = ""; - FILE* fp = NULL; - FILE* fpmeta = NULL; + FILE *fp = NULL; + FILE *fpmeta = NULL; unsigned long pemlen; - unsigned char* pembase64ptr = NULL; + unsigned char *pembase64ptr = NULL; int ret; uint8_t *ptmp; SSLCertsChain *cert; @@ -106,10 +106,10 @@ static void LogTlsLogPem(LogTlsStoreLogThread *aft, const Packet *p, SSLState *s SCReturn; } - TAILQ_FOREACH(cert, &state->server_connp.certs, next) { + TAILQ_FOREACH (cert, &state->server_connp.certs, next) { pemlen = Base64EncodeBufferSize(cert->cert_len); if (pemlen > aft->enc_buf_len) { - ptmp = (uint8_t*) SCRealloc(aft->enc_buf, sizeof(uint8_t) * pemlen); + ptmp = (uint8_t *)SCRealloc(aft->enc_buf, sizeof(uint8_t) * pemlen); if (ptmp == NULL) { SCFree(aft->enc_buf); aft->enc_buf = NULL; @@ -123,7 +123,7 @@ static void LogTlsLogPem(LogTlsStoreLogThread *aft, const Packet *p, SSLState *s memset(aft->enc_buf, 0, aft->enc_buf_len); - ret = Base64Encode((unsigned char*) cert->cert_data, cert->cert_len, aft->enc_buf, &pemlen); + ret = Base64Encode((unsigned char *)cert->cert_data, cert->cert_len, aft->enc_buf, &pemlen); if (ret != SC_BASE64_OK) { SCLogWarning("Invalid return of Base64Encode function"); goto end_fwrite_fp; @@ -150,11 +150,11 @@ static void LogTlsLogPem(LogTlsStoreLogThread *aft, const Packet *p, SSLState *s } fclose(fp); - //Logging certificate informations + // Logging certificate informations memcpy(filename + (strlen(filename) - 3), "meta", 4); fpmeta = fopen(filename, "w"); if (fpmeta != NULL) { - #define PRINT_BUF_LEN 46 +#define PRINT_BUF_LEN 46 char srcip[PRINT_BUF_LEN], dstip[PRINT_BUF_LEN]; char timebuf[64]; Port sp, dp; @@ -164,7 +164,7 @@ static void LogTlsLogPem(LogTlsStoreLogThread *aft, const Packet *p, SSLState *s if (fprintf(fpmeta, "TIME: %s\n", timebuf) < 0) goto end_fwrite_fpmeta; if (p->pcap_cnt > 0) { - if (fprintf(fpmeta, "PCAP PKT NUM: %"PRIu64"\n", p->pcap_cnt) < 0) + if (fprintf(fpmeta, "PCAP PKT NUM: %" PRIu64 "\n", p->pcap_cnt) < 0) goto end_fwrite_fpmeta; } if (fprintf(fpmeta, "SRC IP: %s\n", srcip) < 0) @@ -180,12 +180,12 @@ static void LogTlsLogPem(LogTlsStoreLogThread *aft, const Packet *p, SSLState *s goto end_fwrite_fpmeta; } - if (fprintf(fpmeta, "TLS SUBJECT: %s\n" + if (fprintf(fpmeta, + "TLS SUBJECT: %s\n" "TLS ISSUERDN: %s\n" "TLS FINGERPRINT: %s\n", - state->server_connp.cert0_subject, - state->server_connp.cert0_issuerdn, - state->server_connp.cert0_fingerprint) < 0) + state->server_connp.cert0_subject, state->server_connp.cert0_issuerdn, + state->server_connp.cert0_fingerprint) < 0) goto end_fwrite_fpmeta; fclose(fpmeta); @@ -255,8 +255,8 @@ static bool LogTlsStoreCondition( return false; } -static int LogTlsStoreLogger(ThreadVars *tv, void *thread_data, const Packet *p, - Flow *f, void *state, void *tx, uint64_t tx_id) +static int LogTlsStoreLogger(ThreadVars *tv, void *thread_data, const Packet *p, Flow *f, + void *state, void *tx, uint64_t tx_id) { LogTlsStoreLogThread *aft = (LogTlsStoreLogThread *)thread_data; int ipproto = (PKT_IS_IPV4(p)) ? AF_INET : AF_INET6; @@ -290,7 +290,7 @@ static TmEcode LogTlsStoreLogThreadInit(ThreadVars *t, const void *initdata, voi if (stat(tls_logfile_base_dir, &stat_buf) != 0) { int ret; /* coverity[toctou] */ - ret = SCMkDir(tls_logfile_base_dir, S_IRWXU|S_IXGRP|S_IRGRP); + ret = SCMkDir(tls_logfile_base_dir, S_IRWXU | S_IXGRP | S_IRGRP); if (ret != 0) { int err = errno; if (err != EEXIST) { @@ -299,10 +299,8 @@ static TmEcode LogTlsStoreLogThreadInit(ThreadVars *t, const void *initdata, voi exit(EXIT_FAILURE); } } else { - SCLogInfo("Created certs drop directory %s", - tls_logfile_base_dir); + SCLogInfo("Created certs drop directory %s", tls_logfile_base_dir); } - } *data = (void *)aft; @@ -369,15 +367,13 @@ static OutputInitResult LogTlsStoreLogInitCtx(ConfNode *conf) const char *s_base_dir = NULL; s_base_dir = ConfNodeLookupChildValue(conf, "certs-log-dir"); if (s_base_dir == NULL || strlen(s_base_dir) == 0) { - strlcpy(tls_logfile_base_dir, - s_default_log_dir, sizeof(tls_logfile_base_dir)); + strlcpy(tls_logfile_base_dir, s_default_log_dir, sizeof(tls_logfile_base_dir)); } else { if (PathIsAbsolute(s_base_dir)) { - strlcpy(tls_logfile_base_dir, - s_base_dir, sizeof(tls_logfile_base_dir)); + strlcpy(tls_logfile_base_dir, s_base_dir, sizeof(tls_logfile_base_dir)); } else { - snprintf(tls_logfile_base_dir, sizeof(tls_logfile_base_dir), - "%s/%s", s_default_log_dir, s_base_dir); + snprintf(tls_logfile_base_dir, sizeof(tls_logfile_base_dir), "%s/%s", s_default_log_dir, + s_base_dir); } } @@ -391,12 +387,11 @@ static OutputInitResult LogTlsStoreLogInitCtx(ConfNode *conf) SCReturnCT(result, "OutputInitResult"); } -void LogTlsStoreRegister (void) +void LogTlsStoreRegister(void) { - OutputRegisterTxModuleWithCondition(LOGGER_TLS_STORE, MODULE_NAME, - "tls-store", LogTlsStoreLogInitCtx, ALPROTO_TLS, LogTlsStoreLogger, - LogTlsStoreCondition, LogTlsStoreLogThreadInit, - LogTlsStoreLogThreadDeinit, LogTlsStoreLogExitPrintStats); + OutputRegisterTxModuleWithCondition(LOGGER_TLS_STORE, MODULE_NAME, "tls-store", + LogTlsStoreLogInitCtx, ALPROTO_TLS, LogTlsStoreLogger, LogTlsStoreCondition, + LogTlsStoreLogThreadInit, LogTlsStoreLogThreadDeinit, LogTlsStoreLogExitPrintStats); SC_ATOMIC_INIT(cert_id); SC_ATOMIC_SET(cert_id, 1); diff --git a/src/output-file.c b/src/output-file.c index ff8b83739443..706607729f0f 100644 --- a/src/output-file.c +++ b/src/output-file.c @@ -55,9 +55,8 @@ typedef struct OutputFileLogger_ { static OutputFileLogger *list = NULL; int OutputRegisterFileLogger(LoggerId id, const char *name, FileLogger LogFunc, - OutputCtx *output_ctx, ThreadInitFunc ThreadInit, - ThreadDeinitFunc ThreadDeinit, - ThreadExitPrintStatsFunc ThreadExitPrintStats) + OutputCtx *output_ctx, ThreadInitFunc ThreadInit, ThreadDeinitFunc ThreadDeinit, + ThreadExitPrintStatsFunc ThreadExitPrintStats) { OutputFileLogger *op = SCCalloc(1, sizeof(*op)); if (op == NULL) diff --git a/src/output-file.h b/src/output-file.h index 13735b282de0..48323d177928 100644 --- a/src/output-file.h +++ b/src/output-file.h @@ -48,9 +48,9 @@ void OutputFileLogFfc(ThreadVars *tv, OutputFileLoggerThreadData *op_thread_data typedef int (*FileLogger)(ThreadVars *, void *thread_data, const Packet *, const File *, void *tx, const uint64_t tx_id, uint8_t direction); -int OutputRegisterFileLogger(LoggerId id, const char *name, FileLogger LogFunc, - OutputCtx *, ThreadInitFunc ThreadInit, ThreadDeinitFunc ThreadDeinit, - ThreadExitPrintStatsFunc ThreadExitPrintStats); +int OutputRegisterFileLogger(LoggerId id, const char *name, FileLogger LogFunc, OutputCtx *, + ThreadInitFunc ThreadInit, ThreadDeinitFunc ThreadDeinit, + ThreadExitPrintStatsFunc ThreadExitPrintStats); void OutputFileLoggerRegister(void); diff --git a/src/output-filedata.c b/src/output-filedata.c index daaab1bcc48d..50f075aa3fac 100644 --- a/src/output-filedata.c +++ b/src/output-filedata.c @@ -52,10 +52,9 @@ typedef struct OutputFiledataLogger_ { static OutputFiledataLogger *list = NULL; -int OutputRegisterFiledataLogger(LoggerId id, const char *name, - FiledataLogger LogFunc, OutputCtx *output_ctx, ThreadInitFunc ThreadInit, - ThreadDeinitFunc ThreadDeinit, - ThreadExitPrintStatsFunc ThreadExitPrintStats) +int OutputRegisterFiledataLogger(LoggerId id, const char *name, FiledataLogger LogFunc, + OutputCtx *output_ctx, ThreadInitFunc ThreadInit, ThreadDeinitFunc ThreadDeinit, + ThreadExitPrintStatsFunc ThreadExitPrintStats) { OutputFiledataLogger *op = SCCalloc(1, sizeof(*op)); if (op == NULL) diff --git a/src/output-filedata.h b/src/output-filedata.h index 58764aa81e03..e2d256551a30 100644 --- a/src/output-filedata.h +++ b/src/output-filedata.h @@ -49,10 +49,9 @@ void OutputFiledataLogFfc(ThreadVars *tv, OutputFiledataLoggerThreadData *td, Pa typedef int (*FiledataLogger)(ThreadVars *, void *thread_data, const Packet *, File *, void *tx, const uint64_t tx_id, const uint8_t *, uint32_t, uint8_t, uint8_t dir); -int OutputRegisterFiledataLogger(LoggerId id, const char *name, - FiledataLogger LogFunc, OutputCtx *, ThreadInitFunc ThreadInit, - ThreadDeinitFunc ThreadDeinit, - ThreadExitPrintStatsFunc ThreadExitPrintStats); +int OutputRegisterFiledataLogger(LoggerId id, const char *name, FiledataLogger LogFunc, OutputCtx *, + ThreadInitFunc ThreadInit, ThreadDeinitFunc ThreadDeinit, + ThreadExitPrintStatsFunc ThreadExitPrintStats); void OutputFiledataLoggerRegister(void); diff --git a/src/output-filestore.c b/src/output-filestore.c index 607fe292ffc1..e877d0691e2e 100644 --- a/src/output-filestore.c +++ b/src/output-filestore.c @@ -35,7 +35,7 @@ /* Create a filestore specific PATH_MAX that is less than the system * PATH_MAX to prevent newer gcc truncation warnings with snprint. */ #define SHA256_STRING_LEN (SC_SHA256_LEN * 2) -#define LEAF_DIR_MAX_LEN 4 +#define LEAF_DIR_MAX_LEN 4 #define FILESTORE_PREFIX_MAX (PATH_MAX - SHA256_STRING_LEN - LEAF_DIR_MAX_LEN) /* The default log directory, relative to the default log @@ -104,8 +104,7 @@ static uint32_t FileGetMaxOpenFiles(void) * \param src_filename Filename to use as timestamp source. * \param filename Filename to apply timestamps to. */ -static void OutputFilestoreUpdateFileTime(const char *src_filename, - const char *filename) +static void OutputFilestoreUpdateFileTime(const char *src_filename, const char *filename) { struct stat sb; if (stat(src_filename, &sb) != 0) { @@ -117,8 +116,7 @@ static void OutputFilestoreUpdateFileTime(const char *src_filename, .modtime = sb.st_mtime, }; if (utime(filename, &utimbuf) != 0) { - SCLogDebug("Failed to update file timestamps: %s: %s", filename, - strerror(errno)); + SCLogDebug("Failed to update file timestamps: %s: %s", filename, strerror(errno)); } } @@ -129,16 +127,14 @@ static void OutputFilestoreFinalizeFiles(ThreadVars *tv, const OutputFilestoreLo /* Stringify the SHA256 which will be used in the final * filename. */ char sha256string[(SC_SHA256_LEN * 2) + 1]; - PrintHexString(sha256string, sizeof(sha256string), ff->sha256, - sizeof(ff->sha256)); + PrintHexString(sha256string, sizeof(sha256string), ff->sha256, sizeof(ff->sha256)); char tmp_filename[PATH_MAX] = ""; - snprintf(tmp_filename, sizeof(tmp_filename), "%s/file.%u", ctx->tmpdir, - ff->file_store_id); + snprintf(tmp_filename, sizeof(tmp_filename), "%s/file.%u", ctx->tmpdir, ff->file_store_id); char final_filename[PATH_MAX] = ""; - snprintf(final_filename, sizeof(final_filename), "%s/%c%c/%s", - ctx->prefix, sha256string[0], sha256string[1], sha256string); + snprintf(final_filename, sizeof(final_filename), "%s/%c%c/%s", ctx->prefix, sha256string[0], + sha256string[1], sha256string); if (SCPathExists(final_filename)) { OutputFilestoreUpdateFileTime(tmp_filename, final_filename); @@ -195,13 +191,11 @@ static int OutputFilestoreLogger(ThreadVars *tv, void *thread_data, const Packet SCLogDebug("ff %p, data %p, data_len %u", ff, data, data_len); char base_filename[PATH_MAX] = ""; - snprintf(base_filename, sizeof(base_filename), "%s/file.%u", - ctx->tmpdir, ff->file_store_id); + snprintf(base_filename, sizeof(base_filename), "%s/file.%u", ctx->tmpdir, ff->file_store_id); snprintf(filename, sizeof(filename), "%s", base_filename); if (flags & OUTPUT_FILEDATA_FLAG_OPEN) { - file_fd = open(filename, O_CREAT | O_TRUNC | O_NOFOLLOW | O_WRONLY, - 0644); + file_fd = open(filename, O_CREAT | O_TRUNC | O_NOFOLLOW | O_WRONLY, 0644); if (file_fd == -1) { StatsIncr(tv, aft->fs_error_counter); SCLogWarning("Filestore (v2) failed to create %s: %s", filename, strerror(errno)); @@ -217,7 +211,7 @@ static int OutputFilestoreLogger(ThreadVars *tv, void *thread_data, const Packet } ff->fd = -1; } - /* we can get called with a NULL ffd when we need to close */ + /* we can get called with a NULL ffd when we need to close */ } else if (data != NULL) { if (ff->fd == -1) { file_fd = open(filename, O_APPEND | O_NOFOLLOW | O_WRONLY); @@ -260,8 +254,7 @@ static int OutputFilestoreLogger(ThreadVars *tv, void *thread_data, const Packet return 0; } -static TmEcode OutputFilestoreLogThreadInit(ThreadVars *t, const void *initdata, - void **data) +static TmEcode OutputFilestoreLogThreadInit(ThreadVars *t, const void *initdata, void **data) { OutputFilestoreLogThread *aft = SCCalloc(1, sizeof(OutputFilestoreLogThread)); if (unlikely(aft == NULL)) @@ -276,8 +269,7 @@ static TmEcode OutputFilestoreLogThreadInit(ThreadVars *t, const void *initdata, OutputFilestoreCtx *ctx = ((OutputCtx *)initdata)->data; aft->ctx = ctx; - aft->counter_max_hits = - StatsRegisterCounter("file_store.open_files_max_hit", t); + aft->counter_max_hits = StatsRegisterCounter("file_store.open_files_max_hit", t); /* File system type errors (open, write, rename) will only be * logged once. But this stat will be incremented for every @@ -407,8 +399,7 @@ static OutputInitResult OutputFilestoreLogInitCtx(ConfNode *conf) } strlcpy(ctx->prefix, log_directory, sizeof(ctx->prefix)); - int written = snprintf(ctx->tmpdir, sizeof(ctx->tmpdir) - 1, "%s/tmp", - log_directory); + int written = snprintf(ctx->tmpdir, sizeof(ctx->tmpdir) - 1, "%s/tmp", log_directory); if (written == sizeof(ctx->tmpdir)) { SCLogError("File-store output directory overflow."); SCFree(ctx); @@ -429,15 +420,13 @@ static OutputInitResult OutputFilestoreLogInitCtx(ConfNode *conf) output_ctx->data = ctx; output_ctx->DeInit = OutputFilestoreLogDeInitCtx; - const char *write_fileinfo = ConfNodeLookupChildValue(conf, - "write-fileinfo"); + const char *write_fileinfo = ConfNodeLookupChildValue(conf, "write-fileinfo"); if (write_fileinfo != NULL && ConfValIsTrue(write_fileinfo)) { SCLogConfig("Filestore (v2) will output fileinfo records."); ctx->fileinfo = true; } - const char *force_filestore = ConfNodeLookupChildValue(conf, - "force-filestore"); + const char *force_filestore = ConfNodeLookupChildValue(conf, "force-filestore"); if (force_filestore != NULL && ConfValIsTrue(force_filestore)) { FileForceFilestoreEnable(); SCLogInfo("forcing filestore of all files"); @@ -456,12 +445,10 @@ static OutputInitResult OutputFilestoreLogInitCtx(ConfNode *conf) ProvidesFeature(FEATURE_OUTPUT_FILESTORE); - const char *stream_depth_str = ConfNodeLookupChildValue(conf, - "stream-depth"); + const char *stream_depth_str = ConfNodeLookupChildValue(conf, "stream-depth"); if (stream_depth_str != NULL && strcmp(stream_depth_str, "no")) { uint32_t stream_depth = 0; - if (ParseSizeStringU32(stream_depth_str, - &stream_depth) < 0) { + if (ParseSizeStringU32(stream_depth_str, &stream_depth) < 0) { SCLogError("Error parsing " "file-store.stream-depth " "from conf file - %s. Killing engine", @@ -480,12 +467,10 @@ static OutputInitResult OutputFilestoreLogInitCtx(ConfNode *conf) } } - const char *file_count_str = ConfNodeLookupChildValue(conf, - "max-open-files"); + const char *file_count_str = ConfNodeLookupChildValue(conf, "max-open-files"); if (file_count_str != NULL) { uint32_t file_count = 0; - if (ParseSizeStringU32(file_count_str, - &file_count) < 0) { + if (ParseSizeStringU32(file_count_str, &file_count) < 0) { SCLogError("Error parsing " "file-store.max-open-files " "from conf file - %s. Killing engine", @@ -495,7 +480,8 @@ static OutputInitResult OutputFilestoreLogInitCtx(ConfNode *conf) if (file_count != 0) { FileSetMaxOpenFiles(file_count); SCLogConfig("Filestore (v2) will keep a max of %d " - "simultaneously open files", file_count); + "simultaneously open files", + file_count); } } } @@ -508,9 +494,8 @@ static OutputInitResult OutputFilestoreLogInitCtx(ConfNode *conf) void OutputFilestoreRegister(void) { OutputRegisterFiledataModule(LOGGER_FILE_STORE, MODULE_NAME, "file-store", - OutputFilestoreLogInitCtx, OutputFilestoreLogger, - OutputFilestoreLogThreadInit, OutputFilestoreLogThreadDeinit, - NULL); + OutputFilestoreLogInitCtx, OutputFilestoreLogger, OutputFilestoreLogThreadInit, + OutputFilestoreLogThreadDeinit, NULL); SC_ATOMIC_INIT(filestore_open_file_cnt); SC_ATOMIC_SET(filestore_open_file_cnt, 0); diff --git a/src/output-flow.c b/src/output-flow.c index 5231a3667942..abd9986c58ab 100644 --- a/src/output-flow.c +++ b/src/output-flow.c @@ -50,10 +50,9 @@ typedef struct OutputFlowLogger_ { static OutputFlowLogger *list = NULL; -int OutputRegisterFlowLogger(const char *name, FlowLogger LogFunc, - OutputCtx *output_ctx, ThreadInitFunc ThreadInit, - ThreadDeinitFunc ThreadDeinit, - ThreadExitPrintStatsFunc ThreadExitPrintStats) +int OutputRegisterFlowLogger(const char *name, FlowLogger LogFunc, OutputCtx *output_ctx, + ThreadInitFunc ThreadInit, ThreadDeinitFunc ThreadDeinit, + ThreadExitPrintStatsFunc ThreadExitPrintStats) { OutputFlowLogger *op = SCCalloc(1, sizeof(*op)); if (op == NULL) @@ -103,9 +102,9 @@ TmEcode OutputFlowLog(ThreadVars *tv, void *thread_data, Flow *f) DEBUG_VALIDATE_BUG_ON(logger->LogFunc == NULL); SCLogDebug("logger %p", logger); - //PACKET_PROFILING_LOGGER_START(p, logger->module_id); + // PACKET_PROFILING_LOGGER_START(p, logger->module_id); logger->LogFunc(tv, store->thread_data, f); - //PACKET_PROFILING_LOGGER_END(p, logger->module_id); + // PACKET_PROFILING_LOGGER_END(p, logger->module_id); logger = logger->next; store = store->next; diff --git a/src/output-flow.h b/src/output-flow.h index 2fa26660fee7..c53fb8e26f02 100644 --- a/src/output-flow.h +++ b/src/output-flow.h @@ -31,9 +31,9 @@ /** flow logger function pointer type */ typedef int (*FlowLogger)(ThreadVars *, void *thread_data, Flow *f); -int OutputRegisterFlowLogger(const char *name, FlowLogger LogFunc, - OutputCtx *, ThreadInitFunc ThreadInit, ThreadDeinitFunc ThreadDeinit, - ThreadExitPrintStatsFunc ThreadExitPrintStats); +int OutputRegisterFlowLogger(const char *name, FlowLogger LogFunc, OutputCtx *, + ThreadInitFunc ThreadInit, ThreadDeinitFunc ThreadDeinit, + ThreadExitPrintStatsFunc ThreadExitPrintStats); void OutputFlowShutdown(void); diff --git a/src/output-json-alert.c b/src/output-json-alert.c index c7acfe64d140..bad30b5c164a 100644 --- a/src/output-json-alert.c +++ b/src/output-json-alert.c @@ -91,28 +91,26 @@ #define MODULE_NAME "JsonAlertLog" -#define LOG_JSON_PAYLOAD BIT_U16(0) -#define LOG_JSON_PACKET BIT_U16(1) -#define LOG_JSON_PAYLOAD_BASE64 BIT_U16(2) -#define LOG_JSON_TAGGED_PACKETS BIT_U16(3) -#define LOG_JSON_APP_LAYER BIT_U16(4) -#define LOG_JSON_FLOW BIT_U16(5) -#define LOG_JSON_HTTP_BODY BIT_U16(6) -#define LOG_JSON_HTTP_BODY_BASE64 BIT_U16(7) -#define LOG_JSON_RULE_METADATA BIT_U16(8) -#define LOG_JSON_RULE BIT_U16(9) -#define LOG_JSON_VERDICT BIT_U16(10) - -#define METADATA_DEFAULTS ( LOG_JSON_FLOW | \ - LOG_JSON_APP_LAYER | \ - LOG_JSON_RULE_METADATA) - -#define JSON_BODY_LOGGING (LOG_JSON_HTTP_BODY | LOG_JSON_HTTP_BODY_BASE64) +#define LOG_JSON_PAYLOAD BIT_U16(0) +#define LOG_JSON_PACKET BIT_U16(1) +#define LOG_JSON_PAYLOAD_BASE64 BIT_U16(2) +#define LOG_JSON_TAGGED_PACKETS BIT_U16(3) +#define LOG_JSON_APP_LAYER BIT_U16(4) +#define LOG_JSON_FLOW BIT_U16(5) +#define LOG_JSON_HTTP_BODY BIT_U16(6) +#define LOG_JSON_HTTP_BODY_BASE64 BIT_U16(7) +#define LOG_JSON_RULE_METADATA BIT_U16(8) +#define LOG_JSON_RULE BIT_U16(9) +#define LOG_JSON_VERDICT BIT_U16(10) + +#define METADATA_DEFAULTS (LOG_JSON_FLOW | LOG_JSON_APP_LAYER | LOG_JSON_RULE_METADATA) + +#define JSON_BODY_LOGGING (LOG_JSON_HTTP_BODY | LOG_JSON_HTTP_BODY_BASE64) #define JSON_STREAM_BUFFER_SIZE 4096 typedef struct AlertJsonOutputCtx_ { - LogFileCtx* file_ctx; + LogFileCtx *file_ctx; uint16_t flags; uint32_t payload_buffer_size; HttpXFFCfg *xff_cfg; @@ -122,7 +120,7 @@ typedef struct AlertJsonOutputCtx_ { typedef struct JsonAlertLogThread_ { MemBuffer *payload_buffer; - AlertJsonOutputCtx* json_output_ctx; + AlertJsonOutputCtx *json_output_ctx; OutputJsonThreadCtx *ctx; } JsonAlertLogThread; @@ -137,8 +135,8 @@ static int AlertJsonDumpStreamSegmentCallback( return 1; } -static void AlertJsonSourceTarget(const Packet *p, const PacketAlert *pa, - JsonBuilder *js, JsonAddrInfo *addr) +static void AlertJsonSourceTarget( + const Packet *p, const PacketAlert *pa, JsonBuilder *js, JsonAddrInfo *addr) { jb_open_object(js, "source"); if (pa->s->flags & SIG_FLAG_DEST_IS_TARGET) { @@ -197,8 +195,8 @@ static void AlertJsonSourceTarget(const Packet *p, const PacketAlert *pa, jb_close(js); } -static void AlertJsonMetadata(AlertJsonOutputCtx *json_output_ctx, - const PacketAlert *pa, JsonBuilder *js) +static void AlertJsonMetadata( + AlertJsonOutputCtx *json_output_ctx, const PacketAlert *pa, JsonBuilder *js) { if (pa->s->metadata && pa->s->metadata->json_str) { jb_set_formatted(js, pa->s->metadata->json_str); @@ -237,8 +235,8 @@ void AlertJsonHeader(void *ctx, const Packet *p, const PacketAlert *pa, JsonBuil jb_set_uint(js, "rev", pa->s->rev); /* TODO: JsonBuilder should handle unprintable characters like * SCJsonString. */ - jb_set_string(js, "signature", pa->s->msg ? pa->s->msg: ""); - jb_set_string(js, "category", pa->s->class_msg ? pa->s->class_msg: ""); + jb_set_string(js, "signature", pa->s->msg ? pa->s->msg : ""); + jb_set_string(js, "category", pa->s->class_msg ? pa->s->class_msg : ""); jb_set_uint(js, "severity", pa->s->prio); if (p->tenant_id > 0) { @@ -301,16 +299,15 @@ static void AlertAddPayload(AlertJsonOutputCtx *json_output_ctx, JsonBuilder *js if (json_output_ctx->flags & LOG_JSON_PAYLOAD) { uint8_t printable_buf[p->payload_len + 1]; uint32_t offset = 0; - PrintStringsToBuffer(printable_buf, &offset, - p->payload_len + 1, - p->payload, p->payload_len); + PrintStringsToBuffer( + printable_buf, &offset, p->payload_len + 1, p->payload, p->payload_len); printable_buf[p->payload_len] = '\0'; jb_set_string(js, "payload_printable", (char *)printable_buf); } } -static void AlertAddAppLayer(const Packet *p, JsonBuilder *jb, - const uint64_t tx_id, const uint16_t option_flags) +static void AlertAddAppLayer( + const Packet *p, JsonBuilder *jb, const uint64_t tx_id, const uint16_t option_flags) { const AppProto proto = FlowGetAppProtocol(p->flow); EveJsonSimpleAppLayerLogger *al = SCEveJsonSimpleGetLogger(proto); @@ -543,11 +540,10 @@ static int AlertJson(ThreadVars *tv, JsonAlertLogThread *aft, const Packet *p) if ((xff_cfg != NULL) && !(xff_cfg->flags & XFF_DISABLED) && p->flow != NULL) { if (FlowGetAppProtocol(p->flow) == ALPROTO_HTTP1) { if (pa->flags & PACKET_ALERT_FLAG_TX) { - have_xff_ip = HttpXFFGetIPFromTx(p->flow, pa->tx_id, xff_cfg, - xff_buffer, XFF_MAXLEN); + have_xff_ip = + HttpXFFGetIPFromTx(p->flow, pa->tx_id, xff_cfg, xff_buffer, XFF_MAXLEN); } else { - have_xff_ip = HttpXFFGetIP(p->flow, xff_cfg, xff_buffer, - XFF_MAXLEN); + have_xff_ip = HttpXFFGetIP(p->flow, xff_cfg, xff_buffer, XFF_MAXLEN); } } @@ -572,7 +568,6 @@ static int AlertJson(ThreadVars *tv, JsonAlertLogThread *aft, const Packet *p) if (unlikely(jb == NULL)) return TM_ECODE_OK; - /* alert */ AlertJsonHeader(json_output_ctx, p, pa, jb, json_output_ctx->flags, &addr, xff_buffer); @@ -621,9 +616,12 @@ static int AlertJson(ThreadVars *tv, JsonAlertLogThread *aft, const Packet *p) /* payload */ if (json_output_ctx->flags & (LOG_JSON_PAYLOAD | LOG_JSON_PAYLOAD_BASE64)) { - int stream = (p->proto == IPPROTO_TCP) ? - (pa->flags & (PACKET_ALERT_FLAG_STATE_MATCH | PACKET_ALERT_FLAG_STREAM_MATCH) ? - 1 : 0) : 0; + int stream = (p->proto == IPPROTO_TCP) + ? (pa->flags & (PACKET_ALERT_FLAG_STATE_MATCH | + PACKET_ALERT_FLAG_STREAM_MATCH) + ? 1 + : 0) + : 0; /* Is this a stream? If so, pack part of it into the payload field */ if (stream) { @@ -637,9 +635,8 @@ static int AlertJson(ThreadVars *tv, JsonAlertLogThread *aft, const Packet *p) flag = STREAM_DUMP_TOSERVER; } - StreamSegmentForEach((const Packet *)p, flag, - AlertJsonDumpStreamSegmentCallback, - (void *)payload); + StreamSegmentForEach((const Packet *)p, flag, AlertJsonDumpStreamSegmentCallback, + (void *)payload); if (payload->offset) { if (json_output_ctx->flags & LOG_JSON_PAYLOAD_BASE64) { jb_set_base64(jb, "payload", payload->buffer, payload->offset); @@ -648,8 +645,7 @@ static int AlertJson(ThreadVars *tv, JsonAlertLogThread *aft, const Packet *p) if (json_output_ctx->flags & LOG_JSON_PAYLOAD) { uint8_t printable_buf[payload->offset + 1]; uint32_t offset = 0; - PrintStringsToBuffer(printable_buf, &offset, - sizeof(printable_buf), + PrintStringsToBuffer(printable_buf, &offset, sizeof(printable_buf), payload->buffer, payload->offset); jb_set_string(jb, "payload_printable", (char *)printable_buf); } @@ -687,8 +683,7 @@ static int AlertJson(ThreadVars *tv, JsonAlertLogThread *aft, const Packet *p) jb_free(jb); } - if ((p->flags & PKT_HAS_TAG) && (json_output_ctx->flags & - LOG_JSON_TAGGED_PACKETS)) { + if ((p->flags & PKT_HAS_TAG) && (json_output_ctx->flags & LOG_JSON_TAGGED_PACKETS)) { JsonBuilder *packetjs = CreateEveHeader(p, LOG_DIR_PACKET, "packet", NULL, json_output_ctx->eve_ctx); if (unlikely(packetjs != NULL)) { @@ -757,8 +752,7 @@ static TmEcode JsonAlertLogThreadInit(ThreadVars *t, const void *initdata, void if (unlikely(aft == NULL)) return TM_ECODE_FAILED; - if (initdata == NULL) - { + if (initdata == NULL) { SCLogDebug("Error getting context for EveLogAlert. \"initdata\" argument NULL"); goto error_exit; } @@ -809,7 +803,7 @@ static void JsonAlertLogDeInitCtxSub(OutputCtx *output_ctx) { SCLogDebug("cleaning up sub output_ctx %p", output_ctx); - AlertJsonOutputCtx *json_output_ctx = (AlertJsonOutputCtx *) output_ctx->data; + AlertJsonOutputCtx *json_output_ctx = (AlertJsonOutputCtx *)output_ctx->data; if (json_output_ctx != NULL) { HttpXFFCfg *xff_cfg = json_output_ctx->xff_cfg; @@ -836,8 +830,7 @@ static void SetFlag(const ConfNode *conf, const char *name, uint16_t flag, uint1 #define DEFAULT_LOG_FILENAME "alert.json" -static void JsonAlertLogSetupMetadata(AlertJsonOutputCtx *json_output_ctx, - ConfNode *conf) +static void JsonAlertLogSetupMetadata(AlertJsonOutputCtx *json_output_ctx, ConfNode *conf) { static bool warn_no_meta = false; uint32_t payload_buffer_size = JSON_STREAM_BUFFER_SIZE; @@ -853,8 +846,7 @@ static void JsonAlertLogSetupMetadata(AlertJsonOutputCtx *json_output_ctx, ConfNode *rule_metadata = ConfNodeLookupChild(metadata, "rule"); if (rule_metadata) { SetFlag(rule_metadata, "raw", LOG_JSON_RULE, &flags); - SetFlag(rule_metadata, "metadata", LOG_JSON_RULE_METADATA, - &flags); + SetFlag(rule_metadata, "metadata", LOG_JSON_RULE_METADATA, &flags); } SetFlag(metadata, "flow", LOG_JSON_FLOW, &flags); SetFlag(metadata, "app-layer", LOG_JSON_APP_LAYER, &flags); @@ -973,10 +965,9 @@ static OutputInitResult JsonAlertLogInitCtxSub(ConfNode *conf, OutputCtx *parent return result; } -void JsonAlertLogRegister (void) +void JsonAlertLogRegister(void) { - OutputRegisterPacketSubModule(LOGGER_JSON_ALERT, "eve-log", MODULE_NAME, - "eve-log.alert", JsonAlertLogInitCtxSub, JsonAlertLogger, - JsonAlertLogCondition, JsonAlertLogThreadInit, JsonAlertLogThreadDeinit, - NULL); + OutputRegisterPacketSubModule(LOGGER_JSON_ALERT, "eve-log", MODULE_NAME, "eve-log.alert", + JsonAlertLogInitCtxSub, JsonAlertLogger, JsonAlertLogCondition, JsonAlertLogThreadInit, + JsonAlertLogThreadDeinit, NULL); } diff --git a/src/output-json-alert.h b/src/output-json-alert.h index 6a65cc3d2730..8d7f31e25b4d 100644 --- a/src/output-json-alert.h +++ b/src/output-json-alert.h @@ -33,4 +33,3 @@ void AlertJsonHeader(void *ctx, const Packet *p, const PacketAlert *pa, JsonBuil void EveAddVerdict(JsonBuilder *jb, const Packet *p); #endif /* __OUTPUT_JSON_ALERT_H__ */ - diff --git a/src/output-json-anomaly.c b/src/output-json-anomaly.c index ffe931a73ed6..91fe41f7f172 100644 --- a/src/output-json-anomaly.c +++ b/src/output-json-anomaly.c @@ -58,14 +58,14 @@ #define MODULE_NAME "JsonAnomalyLog" -#define ANOMALY_EVENT_TYPE "anomaly" -#define LOG_JSON_DECODE_TYPE BIT_U16(0) -#define LOG_JSON_STREAM_TYPE BIT_U16(1) -#define LOG_JSON_APPLAYER_TYPE BIT_U16(2) -#define LOG_JSON_PACKETHDR BIT_U16(3) +#define ANOMALY_EVENT_TYPE "anomaly" +#define LOG_JSON_DECODE_TYPE BIT_U16(0) +#define LOG_JSON_STREAM_TYPE BIT_U16(1) +#define LOG_JSON_APPLAYER_TYPE BIT_U16(2) +#define LOG_JSON_PACKETHDR BIT_U16(3) -#define LOG_JSON_PACKET_TYPE (LOG_JSON_DECODE_TYPE | LOG_JSON_STREAM_TYPE) -#define ANOMALY_DEFAULTS LOG_JSON_APPLAYER_TYPE +#define LOG_JSON_PACKET_TYPE (LOG_JSON_DECODE_TYPE | LOG_JSON_STREAM_TYPE) +#define ANOMALY_DEFAULTS LOG_JSON_APPLAYER_TYPE #define TX_ID_UNUSED UINT64_MAX @@ -75,7 +75,7 @@ typedef struct AnomalyJsonOutputCtx_ { } AnomalyJsonOutputCtx; typedef struct JsonAnomalyLogThread_ { - AnomalyJsonOutputCtx* json_output_ctx; + AnomalyJsonOutputCtx *json_output_ctx; OutputJsonThreadCtx *ctx; } JsonAnomalyLogThread; @@ -100,8 +100,7 @@ static void OutputAnomalyLoggerDisable(void) anomaly_loggers--; } -static int AnomalyDecodeEventJson(ThreadVars *tv, JsonAnomalyLogThread *aft, - const Packet *p) +static int AnomalyDecodeEventJson(ThreadVars *tv, JsonAnomalyLogThread *aft, const Packet *p) { const uint16_t log_type = aft->json_output_ctx->flags; const bool log_stream = log_type & LOG_JSON_STREAM_TYPE; @@ -150,16 +149,14 @@ static int AnomalyDecodeEventJson(ThreadVars *tv, JsonAnomalyLogThread *aft, return TM_ECODE_OK; } -static int AnomalyAppLayerDecoderEventJson(JsonAnomalyLogThread *aft, - const Packet *p, AppLayerDecoderEvents *decoder_events, - bool is_pktlayer, const char *layer, uint64_t tx_id) +static int AnomalyAppLayerDecoderEventJson(JsonAnomalyLogThread *aft, const Packet *p, + AppLayerDecoderEvents *decoder_events, bool is_pktlayer, const char *layer, uint64_t tx_id) { const char *alprotoname = AppLayerGetProtoName(p->flow->alproto); - SCLogDebug("decoder_events %p event_count %d (last logged %d) %s", - decoder_events, decoder_events->cnt, - decoder_events->event_last_logged, - tx_id != TX_ID_UNUSED ? "tx" : "no-tx"); + SCLogDebug("decoder_events %p event_count %d (last logged %d) %s", decoder_events, + decoder_events->cnt, decoder_events->event_last_logged, + tx_id != TX_ID_UNUSED ? "tx" : "no-tx"); for (int i = decoder_events->event_last_logged; i < decoder_events->cnt; i++) { JsonBuilder *js; @@ -174,7 +171,6 @@ static int AnomalyAppLayerDecoderEventJson(JsonAnomalyLogThread *aft, return TM_ECODE_OK; } - jb_open_object(js, ANOMALY_EVENT_TYPE); jb_set_string(js, "app_proto", alprotoname); @@ -186,8 +182,8 @@ static int AnomalyAppLayerDecoderEventJson(JsonAnomalyLogThread *aft, if (is_pktlayer) { r = AppLayerGetEventInfoById(event_code, &event_name, &event_type); } else { - r = AppLayerParserGetEventInfoById(p->flow->proto, p->flow->alproto, - event_code, &event_name, &event_type); + r = AppLayerParserGetEventInfoById( + p->flow->proto, p->flow->alproto, event_code, &event_name, &event_type); } if (r == 0) { JB_SET_STRING(js, "type", "applayer"); @@ -211,8 +207,8 @@ static int AnomalyAppLayerDecoderEventJson(JsonAnomalyLogThread *aft, return TM_ECODE_OK; } -static int JsonAnomalyTxLogger(ThreadVars *tv, void *thread_data, const Packet *p, - Flow *f, void *state, void *tx, uint64_t tx_id) +static int JsonAnomalyTxLogger(ThreadVars *tv, void *thread_data, const Packet *p, Flow *f, + void *state, void *tx, uint64_t tx_id) { JsonAnomalyLogThread *aft = thread_data; if (!(aft->json_output_ctx->flags & LOG_JSON_APPLAYER_TYPE)) { @@ -222,17 +218,15 @@ static int JsonAnomalyTxLogger(ThreadVars *tv, void *thread_data, const Packet * AppLayerDecoderEvents *decoder_events; decoder_events = AppLayerParserGetEventsByTx(f->proto, f->alproto, tx); if (decoder_events && decoder_events->event_last_logged < decoder_events->cnt) { - SCLogDebug("state %p, tx: %p, tx_id: %"PRIu64, state, tx, tx_id); - AnomalyAppLayerDecoderEventJson(aft, p, decoder_events, false, - "proto_parser", tx_id); + SCLogDebug("state %p, tx: %p, tx_id: %" PRIu64, state, tx, tx_id); + AnomalyAppLayerDecoderEventJson(aft, p, decoder_events, false, "proto_parser", tx_id); } return TM_ECODE_OK; } static inline bool AnomalyHasParserEvents(const Packet *p) { - return (p->flow && p->flow->alparser && - AppLayerParserHasDecoderEvents(p->flow->alparser)); + return (p->flow && p->flow->alparser && AppLayerParserHasDecoderEvents(p->flow->alparser)); } static inline bool AnomalyHasPacketAppLayerEvents(const Packet *p) @@ -255,17 +249,18 @@ static int AnomalyJson(ThreadVars *tv, JsonAnomalyLogThread *aft, const Packet * if (aft->json_output_ctx->flags & LOG_JSON_APPLAYER_TYPE) { /* app layer proto detect events */ if (rc == TM_ECODE_OK && AnomalyHasPacketAppLayerEvents(p)) { - rc = AnomalyAppLayerDecoderEventJson(aft, p, p->app_layer_events, - true, "proto_detect", TX_ID_UNUSED); + rc = AnomalyAppLayerDecoderEventJson( + aft, p, p->app_layer_events, true, "proto_detect", TX_ID_UNUSED); } /* parser state events */ if (rc == TM_ECODE_OK && AnomalyHasParserEvents(p)) { SCLogDebug("Checking for anomaly events; alproto %d", p->flow->alproto); - AppLayerDecoderEvents *parser_events = AppLayerParserGetDecoderEvents(p->flow->alparser); + AppLayerDecoderEvents *parser_events = + AppLayerParserGetDecoderEvents(p->flow->alparser); if (parser_events && (parser_events->event_last_logged < parser_events->cnt)) { - rc = AnomalyAppLayerDecoderEventJson(aft, p, parser_events, - false, "parser", TX_ID_UNUSED); + rc = AnomalyAppLayerDecoderEventJson( + aft, p, parser_events, false, "parser", TX_ID_UNUSED); } } } @@ -281,8 +276,7 @@ static int JsonAnomalyLogger(ThreadVars *tv, void *thread_data, const Packet *p) static bool JsonAnomalyLogCondition(ThreadVars *tv, void *thread_data, const Packet *p) { - return p->events.cnt > 0 || - (p->app_layer_events && p->app_layer_events->cnt > 0) || + return p->events.cnt > 0 || (p->app_layer_events && p->app_layer_events->cnt > 0) || AnomalyHasParserEvents(p); } @@ -335,7 +329,7 @@ static void JsonAnomalyLogDeInitCtxSubHelper(OutputCtx *output_ctx) { SCLogDebug("cleaning up sub output_ctx %p", output_ctx); - AnomalyJsonOutputCtx *json_output_ctx = (AnomalyJsonOutputCtx *) output_ctx->data; + AnomalyJsonOutputCtx *json_output_ctx = (AnomalyJsonOutputCtx *)output_ctx->data; if (json_output_ctx != NULL) { SCFree(json_output_ctx); @@ -364,8 +358,7 @@ static void SetFlag(const ConfNode *conf, const char *name, uint16_t flag, uint1 } } -static void JsonAnomalyLogConf(AnomalyJsonOutputCtx *json_output_ctx, - ConfNode *conf) +static void JsonAnomalyLogConf(AnomalyJsonOutputCtx *json_output_ctx, ConfNode *conf) { static bool warn_no_flags = false; static bool warn_no_packet = false; @@ -380,7 +373,8 @@ static void JsonAnomalyLogConf(AnomalyJsonOutputCtx *json_output_ctx, } SetFlag(conf, "packethdr", LOG_JSON_PACKETHDR, &flags); } - if (((flags & (LOG_JSON_DECODE_TYPE | LOG_JSON_PACKETHDR)) == LOG_JSON_PACKETHDR) && !warn_no_packet) { + if (((flags & (LOG_JSON_DECODE_TYPE | LOG_JSON_PACKETHDR)) == LOG_JSON_PACKETHDR) && + !warn_no_packet) { SCLogWarning("Anomaly logging configured to include packet headers, however decode " "type logging has not been selected. Packet headers will not be logged."); warn_no_packet = true; @@ -449,15 +443,13 @@ static OutputInitResult JsonAnomalyLogInitCtxSub(ConfNode *conf, OutputCtx *pare return result; } -void JsonAnomalyLogRegister (void) +void JsonAnomalyLogRegister(void) { - OutputRegisterPacketSubModule(LOGGER_JSON_ANOMALY, "eve-log", MODULE_NAME, - "eve-log.anomaly", JsonAnomalyLogInitCtxSub, JsonAnomalyLogger, - JsonAnomalyLogCondition, JsonAnomalyLogThreadInit, JsonAnomalyLogThreadDeinit, - NULL); - - OutputRegisterTxSubModule(LOGGER_JSON_ANOMALY, "eve-log", MODULE_NAME, - "eve-log.anomaly", JsonAnomalyLogInitCtxHelper, ALPROTO_UNKNOWN, - JsonAnomalyTxLogger, JsonAnomalyLogThreadInit, - JsonAnomalyLogThreadDeinit, NULL); + OutputRegisterPacketSubModule(LOGGER_JSON_ANOMALY, "eve-log", MODULE_NAME, "eve-log.anomaly", + JsonAnomalyLogInitCtxSub, JsonAnomalyLogger, JsonAnomalyLogCondition, + JsonAnomalyLogThreadInit, JsonAnomalyLogThreadDeinit, NULL); + + OutputRegisterTxSubModule(LOGGER_JSON_ANOMALY, "eve-log", MODULE_NAME, "eve-log.anomaly", + JsonAnomalyLogInitCtxHelper, ALPROTO_UNKNOWN, JsonAnomalyTxLogger, + JsonAnomalyLogThreadInit, JsonAnomalyLogThreadDeinit, NULL); } diff --git a/src/output-json-anomaly.h b/src/output-json-anomaly.h index 4ca32b21ec59..475efbfc0b6c 100644 --- a/src/output-json-anomaly.h +++ b/src/output-json-anomaly.h @@ -30,4 +30,3 @@ void JsonAnomalyLogRegister(void); #endif /* __OUTPUT_JSON_ALERT_H__ */ - diff --git a/src/output-json-common.c b/src/output-json-common.c index 42595c3dde25..fcd7d0f7afd8 100644 --- a/src/output-json-common.c +++ b/src/output-json-common.c @@ -86,7 +86,6 @@ OutputInitResult OutputJsonLogInitSub(ConfNode *conf, OutputCtx *parent_ctx) return result; } - TmEcode JsonLogThreadInit(ThreadVars *t, const void *initdata, void **data) { if (initdata == NULL) { diff --git a/src/output-json-dcerpc.c b/src/output-json-dcerpc.c index 6ec19a0b849c..1b290882a34c 100644 --- a/src/output-json-dcerpc.c +++ b/src/output-json-dcerpc.c @@ -23,9 +23,8 @@ #include "output-json-dcerpc.h" #include "rust.h" - -static int JsonDCERPCLogger(ThreadVars *tv, void *thread_data, - const Packet *p, Flow *f, void *state, void *tx, uint64_t tx_id) +static int JsonDCERPCLogger(ThreadVars *tv, void *thread_data, const Packet *p, Flow *f, + void *state, void *tx, uint64_t tx_id) { OutputJsonThreadCtx *thread = thread_data; diff --git a/src/output-json-dhcp.c b/src/output-json-dhcp.c index d6a2111291aa..6b4e21e6e605 100644 --- a/src/output-json-dhcp.c +++ b/src/output-json-dhcp.c @@ -44,9 +44,8 @@ #include "output-json-dhcp.h" #include "rust.h" - typedef struct LogDHCPFileCtx_ { - void *rs_logger; + void *rs_logger; OutputJsonCtx *eve_ctx; } LogDHCPFileCtx; @@ -55,8 +54,8 @@ typedef struct LogDHCPLogThread_ { OutputJsonThreadCtx *thread; } LogDHCPLogThread; -static int JsonDHCPLogger(ThreadVars *tv, void *thread_data, - const Packet *p, Flow *f, void *state, void *tx, uint64_t tx_id) +static int JsonDHCPLogger(ThreadVars *tv, void *thread_data, const Packet *p, Flow *f, void *state, + void *tx, uint64_t tx_id) { LogDHCPLogThread *thread = thread_data; LogDHCPFileCtx *ctx = thread->dhcplog_ctx; @@ -86,8 +85,7 @@ static void OutputDHCPLogDeInitCtxSub(OutputCtx *output_ctx) SCFree(output_ctx); } -static OutputInitResult OutputDHCPLogInitSub(ConfNode *conf, - OutputCtx *parent_ctx) +static OutputInitResult OutputDHCPLogInitSub(ConfNode *conf, OutputCtx *parent_ctx) { OutputInitResult result = { NULL, false }; diff --git a/src/output-json-dnp3-objects.h b/src/output-json-dnp3-objects.h index debe115689ab..a8ac428f35b4 100644 --- a/src/output-json-dnp3-objects.h +++ b/src/output-json-dnp3-objects.h @@ -20,7 +20,6 @@ #include "rust-bindings.h" -void OutputJsonDNP3SetItem(JsonBuilder *js, DNP3Object *object, - DNP3Point *item); +void OutputJsonDNP3SetItem(JsonBuilder *js, DNP3Object *object, DNP3Point *item); #endif /* __OUTPUT_JSON_DNP3_OBJECTS_H__ */ diff --git a/src/output-json-dnp3.c b/src/output-json-dnp3.c index a091937a6ee8..80ff112b65a1 100644 --- a/src/output-json-dnp3.c +++ b/src/output-json-dnp3.c @@ -41,8 +41,8 @@ #include "output-json-dnp3-objects.h" typedef struct LogDNP3FileCtx_ { - uint32_t flags; - uint8_t include_object_data; + uint32_t flags; + uint8_t include_object_data; OutputJsonCtx *eve_ctx; } LogDNP3FileCtx; @@ -94,7 +94,7 @@ static void JsonDNP3LogObjectItems(JsonBuilder *js, DNP3Object *object) { DNP3Point *item; - TAILQ_FOREACH(item, object->points, next) { + TAILQ_FOREACH (item, object->points, next) { jb_start_object(js); jb_set_uint(js, "prefix", item->prefix); @@ -118,13 +118,13 @@ static void JsonDNP3LogObjects(JsonBuilder *js, DNP3ObjectList *objects) { DNP3Object *object; - TAILQ_FOREACH(object, objects, next) { + TAILQ_FOREACH (object, objects, next) { jb_start_object(js); jb_set_uint(js, "group", object->group); jb_set_uint(js, "variation", object->variation); jb_set_uint(js, "qualifier", object->qualifier); jb_set_uint(js, "prefix_code", object->prefix_code); - jb_set_uint(js, "range_code", object->range_code); + jb_set_uint(js, "range_code", object->range_code); jb_set_uint(js, "start", object->start); jb_set_uint(js, "stop", object->stop); jb_set_uint(js, "count", object->count); @@ -230,8 +230,8 @@ bool AlertJsonDnp3(void *vtx, JsonBuilder *js) return logged; } -static int JsonDNP3LoggerToServer(ThreadVars *tv, void *thread_data, - const Packet *p, Flow *f, void *state, void *vtx, uint64_t tx_id) +static int JsonDNP3LoggerToServer(ThreadVars *tv, void *thread_data, const Packet *p, Flow *f, + void *state, void *vtx, uint64_t tx_id) { SCEnter(); LogDNP3LogThread *thread = (LogDNP3LogThread *)thread_data; @@ -251,8 +251,8 @@ static int JsonDNP3LoggerToServer(ThreadVars *tv, void *thread_data, SCReturnInt(TM_ECODE_OK); } -static int JsonDNP3LoggerToClient(ThreadVars *tv, void *thread_data, - const Packet *p, Flow *f, void *state, void *vtx, uint64_t tx_id) +static int JsonDNP3LoggerToClient(ThreadVars *tv, void *thread_data, const Packet *p, Flow *f, + void *state, void *vtx, uint64_t tx_id) { SCEnter(); LogDNP3LogThread *thread = (LogDNP3LogThread *)thread_data; @@ -323,7 +323,6 @@ static OutputInitResult OutputDNP3LogInitSub(ConfNode *conf, OutputCtx *parent_c return result; } - static TmEcode JsonDNP3LogThreadInit(ThreadVars *t, const void *initdata, void **data) { LogDNP3LogThread *thread = SCCalloc(1, sizeof(*thread)); diff --git a/src/output-json-dns.c b/src/output-json-dns.c index 27aa55d8e305..59b9d842d08e 100644 --- a/src/output-json-dns.c +++ b/src/output-json-dns.c @@ -54,8 +54,8 @@ * TX id handling doesn't expect it */ #define QUERY 0 -#define LOG_QUERIES BIT_U64(0) -#define LOG_ANSWERS BIT_U64(1) +#define LOG_QUERIES BIT_U64(0) +#define LOG_ANSWERS BIT_U64(1) #define LOG_A BIT_U64(2) #define LOG_NS BIT_U64(3) @@ -116,12 +116,13 @@ #define LOG_ANY BIT_U64(58) #define LOG_URI BIT_U64(59) -#define LOG_FORMAT_GROUPED BIT_U64(60) -#define LOG_FORMAT_DETAILED BIT_U64(61) -#define LOG_HTTPS BIT_U64(62) +#define LOG_FORMAT_GROUPED BIT_U64(60) +#define LOG_FORMAT_DETAILED BIT_U64(61) +#define LOG_HTTPS BIT_U64(62) -#define LOG_FORMAT_ALL (LOG_FORMAT_GROUPED|LOG_FORMAT_DETAILED) -#define LOG_ALL_RRTYPES (~(uint64_t)(LOG_QUERIES|LOG_ANSWERS|LOG_FORMAT_DETAILED|LOG_FORMAT_GROUPED)) +#define LOG_FORMAT_ALL (LOG_FORMAT_GROUPED | LOG_FORMAT_DETAILED) +#define LOG_ALL_RRTYPES \ + (~(uint64_t)(LOG_QUERIES | LOG_ANSWERS | LOG_FORMAT_DETAILED | LOG_FORMAT_GROUPED)) typedef enum { DNS_RRTYPE_A = 0, @@ -321,8 +322,8 @@ bool AlertJsonDns(void *txptr, JsonBuilder *js) return true; } -static int JsonDnsLoggerToServer(ThreadVars *tv, void *thread_data, - const Packet *p, Flow *f, void *alstate, void *txptr, uint64_t tx_id) +static int JsonDnsLoggerToServer(ThreadVars *tv, void *thread_data, const Packet *p, Flow *f, + void *alstate, void *txptr, uint64_t tx_id) { SCEnter(); @@ -353,8 +354,8 @@ static int JsonDnsLoggerToServer(ThreadVars *tv, void *thread_data, SCReturnInt(TM_ECODE_OK); } -static int JsonDnsLoggerToClient(ThreadVars *tv, void *thread_data, - const Packet *p, Flow *f, void *alstate, void *txptr, uint64_t tx_id) +static int JsonDnsLoggerToClient(ThreadVars *tv, void *thread_data, const Packet *p, Flow *f, + void *alstate, void *txptr, uint64_t tx_id) { SCEnter(); @@ -398,8 +399,7 @@ static TmEcode LogDnsLogThreadInit(ThreadVars *t, const void *initdata, void **d if (unlikely(aft == NULL)) return TM_ECODE_FAILED; - if(initdata == NULL) - { + if (initdata == NULL) { SCLogDebug("Error getting context for EveLogDNS. \"initdata\" argument NULL"); goto error_exit; } @@ -442,9 +442,8 @@ static void LogDnsLogDeInitCtxSub(OutputCtx *output_ctx) SCFree(output_ctx); } -static void JsonDnsLogParseConfig(LogDnsFileCtx *dnslog_ctx, ConfNode *conf, - const char *query_key, const char *answer_key, - const char *answer_types_key) +static void JsonDnsLogParseConfig(LogDnsFileCtx *dnslog_ctx, ConfNode *conf, const char *query_key, + const char *answer_key, const char *answer_types_key) { const char *query = ConfNodeLookupChildValue(conf, query_key); if (query != NULL) { @@ -498,7 +497,7 @@ static void JsonDnsCheckVersion(ConfNode *conf) bool invalid = false; intmax_t config_version; if (ConfGetChildValueInt(conf, "version", &config_version)) { - switch(config_version) { + switch (config_version) { case 2: break; case 1: @@ -596,9 +595,8 @@ static OutputInitResult JsonDnsLogInitCtxSub(ConfNode *conf, OutputCtx *parent_c return result; } - #define MODULE_NAME "JsonDnsLog" -void JsonDnsLogRegister (void) +void JsonDnsLogRegister(void) { OutputRegisterTxSubModule(LOGGER_JSON_TX, "eve-log", MODULE_NAME, "eve-log.dns", JsonDnsLogInitCtxSub, ALPROTO_DNS, JsonDnsLogger, LogDnsLogThreadInit, diff --git a/src/output-json-drop.c b/src/output-json-drop.c index edce3793d100..ca106466ac66 100644 --- a/src/output-json-drop.c +++ b/src/output-json-drop.c @@ -85,7 +85,7 @@ static int g_droplog_flows_start = 1; * * \return return TM_ECODE_OK on success */ -static int DropLogJSON (JsonDropLogThread *aft, const Packet *p) +static int DropLogJSON(JsonDropLogThread *aft, const Packet *p) { JsonDropOutputCtx *drop_ctx = aft->drop_ctx; @@ -132,7 +132,7 @@ static int DropLogJSON (JsonDropLogThread *aft, const Packet *p) jb_set_bool(js, "rst", TCP_ISSET_FLAG_RST(p) ? true : false); jb_set_bool(js, "urg", TCP_ISSET_FLAG_URG(p) ? true : false); jb_set_bool(js, "fin", TCP_ISSET_FLAG_FIN(p) ? true : false); - jb_set_uint(js, "tcpres", TCP_GET_RAW_X2(p->tcph)); + jb_set_uint(js, "tcpres", TCP_GET_RAW_X2(p->tcph)); jb_set_uint(js, "tcpurgp", TCP_GET_URG_POINTER(p)); } break; @@ -145,7 +145,7 @@ static int DropLogJSON (JsonDropLogThread *aft, const Packet *p) if (PKT_IS_ICMPV4(p)) { jb_set_uint(js, "icmp_id", ICMPV4_GET_ID(p)); jb_set_uint(js, "icmp_seq", ICMPV4_GET_SEQ(p)); - } else if(PKT_IS_ICMPV6(p)) { + } else if (PKT_IS_ICMPV6(p)) { jb_set_uint(js, "icmp_id", ICMPV6_GET_ID(p)); jb_set_uint(js, "icmp_seq", ICMPV6_GET_SEQ(p)); } @@ -171,9 +171,8 @@ static int DropLogJSON (JsonDropLogThread *aft, const Packet *p) if (unlikely(pa->s == NULL)) { continue; } - if ((pa->action & (ACTION_REJECT|ACTION_REJECT_DST|ACTION_REJECT_BOTH)) || - ((pa->action & ACTION_DROP) && EngineModeIsIPS())) - { + if ((pa->action & (ACTION_REJECT | ACTION_REJECT_DST | ACTION_REJECT_BOTH)) || + ((pa->action & ACTION_DROP) && EngineModeIsIPS())) { AlertJsonHeader(NULL, p, pa, js, 0, &addr, NULL); logged = 1; break; @@ -199,8 +198,7 @@ static TmEcode JsonDropLogThreadInit(ThreadVars *t, const void *initdata, void * if (unlikely(aft == NULL)) return TM_ECODE_FAILED; - if(initdata == NULL) - { + if (initdata == NULL) { SCLogDebug("Error getting context for EveLogDrop. \"initdata\" argument NULL"); goto error_exit; } @@ -384,10 +382,9 @@ static bool JsonDropLogCondition(ThreadVars *tv, void *data, const Packet *p) return true; } -void JsonDropLogRegister (void) +void JsonDropLogRegister(void) { - OutputRegisterPacketSubModule(LOGGER_JSON_DROP, "eve-log", MODULE_NAME, - "eve-log.drop", JsonDropLogInitCtxSub, JsonDropLogger, - JsonDropLogCondition, JsonDropLogThreadInit, JsonDropLogThreadDeinit, - NULL); + OutputRegisterPacketSubModule(LOGGER_JSON_DROP, "eve-log", MODULE_NAME, "eve-log.drop", + JsonDropLogInitCtxSub, JsonDropLogger, JsonDropLogCondition, JsonDropLogThreadInit, + JsonDropLogThreadDeinit, NULL); } diff --git a/src/output-json-email-common.c b/src/output-json-email-common.c index 31d855758579..6c0d6e05bfaa 100644 --- a/src/output-json-email-common.c +++ b/src/output-json-email-common.c @@ -52,35 +52,35 @@ #include "output-json.h" #include "output-json-email-common.h" -#define LOG_EMAIL_DEFAULT 0 -#define LOG_EMAIL_EXTENDED (1<<0) -#define LOG_EMAIL_ARRAY (1<<1) /* require array handling */ -#define LOG_EMAIL_COMMA (1<<2) /* require array handling */ -#define LOG_EMAIL_BODY_MD5 (1<<3) -#define LOG_EMAIL_SUBJECT_MD5 (1<<4) +#define LOG_EMAIL_DEFAULT 0 +#define LOG_EMAIL_EXTENDED (1 << 0) +#define LOG_EMAIL_ARRAY (1 << 1) /* require array handling */ +#define LOG_EMAIL_COMMA (1 << 2) /* require array handling */ +#define LOG_EMAIL_BODY_MD5 (1 << 3) +#define LOG_EMAIL_SUBJECT_MD5 (1 << 4) struct { const char *config_field; const char *email_field; uint32_t flags; -} email_fields[] = { +} email_fields[] = { { "reply_to", "reply-to", LOG_EMAIL_DEFAULT }, - { "bcc", "bcc", LOG_EMAIL_COMMA|LOG_EMAIL_EXTENDED }, + { "bcc", "bcc", LOG_EMAIL_COMMA | LOG_EMAIL_EXTENDED }, { "message_id", "message-id", LOG_EMAIL_EXTENDED }, { "subject", "subject", LOG_EMAIL_EXTENDED }, { "x_mailer", "x-mailer", LOG_EMAIL_EXTENDED }, { "user_agent", "user-agent", LOG_EMAIL_EXTENDED }, { "received", "received", LOG_EMAIL_ARRAY }, { "x_originating_ip", "x-originating-ip", LOG_EMAIL_DEFAULT }, - { "in_reply_to", "in-reply-to", LOG_EMAIL_DEFAULT }, - { "references", "references", LOG_EMAIL_DEFAULT }, - { "importance", "importance", LOG_EMAIL_DEFAULT }, - { "priority", "priority", LOG_EMAIL_DEFAULT }, - { "sensitivity", "sensitivity", LOG_EMAIL_DEFAULT }, - { "organization", "organization", LOG_EMAIL_DEFAULT }, - { "content_md5", "content-md5", LOG_EMAIL_DEFAULT }, + { "in_reply_to", "in-reply-to", LOG_EMAIL_DEFAULT }, + { "references", "references", LOG_EMAIL_DEFAULT }, + { "importance", "importance", LOG_EMAIL_DEFAULT }, + { "priority", "priority", LOG_EMAIL_DEFAULT }, + { "sensitivity", "sensitivity", LOG_EMAIL_DEFAULT }, + { "organization", "organization", LOG_EMAIL_DEFAULT }, + { "content_md5", "content-md5", LOG_EMAIL_DEFAULT }, { "date", "date", LOG_EMAIL_DEFAULT }, - { NULL, NULL, LOG_EMAIL_DEFAULT}, + { NULL, NULL, LOG_EMAIL_DEFAULT }, }; static inline char *SkipWhiteSpaceTill(char *p, char *savep) @@ -155,7 +155,8 @@ static int JsonEmailAddToJsonArray(const uint8_t *val, size_t len, void *data) return 1; } -static void EveEmailLogJSONCustom(OutputJsonEmailCtx *email_ctx, JsonBuilder *js, SMTPTransaction *tx) +static void EveEmailLogJSONCustom( + OutputJsonEmailCtx *email_ctx, JsonBuilder *js, SMTPTransaction *tx) { int f = 0; JsonBuilderMark mark = { 0, 0, 0 }; @@ -165,15 +166,15 @@ static void EveEmailLogJSONCustom(OutputJsonEmailCtx *email_ctx, JsonBuilder *js return; } - while(email_fields[f].config_field) { - if (((email_ctx->fields & (1ULL<flags & LOG_EMAIL_EXTENDED) && (email_fields[f].flags & LOG_EMAIL_EXTENDED)) - ) { + while (email_fields[f].config_field) { + if (((email_ctx->fields & (1ULL << f)) != 0) || + ((email_ctx->flags & LOG_EMAIL_EXTENDED) && + (email_fields[f].flags & LOG_EMAIL_EXTENDED))) { if (email_fields[f].flags & LOG_EMAIL_ARRAY) { jb_get_mark(js, &mark); jb_open_array(js, email_fields[f].config_field); - int found = MimeDecFindFieldsForEach(entity, email_fields[f].email_field, JsonEmailAddToJsonArray, js); + int found = MimeDecFindFieldsForEach( + entity, email_fields[f].email_field, JsonEmailAddToJsonArray, js); if (found > 0) { jb_close(js); } else { @@ -193,22 +194,21 @@ static void EveEmailLogJSONCustom(OutputJsonEmailCtx *email_ctx, JsonBuilder *js } else { field = MimeDecFindField(entity, email_fields[f].email_field); if (field != NULL) { - char *s = BytesToString((uint8_t *)field->value, - (size_t)field->value_len); + char *s = BytesToString((uint8_t *)field->value, (size_t)field->value_len); if (likely(s != NULL)) { jb_set_string(js, email_fields[f].config_field, s); SCFree(s); } } } - } f++; } } /* JSON format logging */ -static bool EveEmailLogJsonData(const Flow *f, void *state, void *vtx, uint64_t tx_id, JsonBuilder *sjs) +static bool EveEmailLogJsonData( + const Flow *f, void *state, void *vtx, uint64_t tx_id, JsonBuilder *sjs) { SMTPState *smtp_state; MimeDecParseState *mime_state; @@ -228,7 +228,8 @@ static bool EveEmailLogJsonData(const Flow *f, void *state, void *vtx, uint64_t SMTPTransaction *tx = vtx; mime_state = tx->mime_state; entity = tx->msg_tail; - SCLogDebug("lets go mime_state %p, entity %p, state_flag %u", mime_state, entity, mime_state ? mime_state->state_flag : 0); + SCLogDebug("lets go mime_state %p, entity %p, state_flag %u", mime_state, entity, + mime_state ? mime_state->state_flag : 0); break; default: /* don't know how we got here */ @@ -246,11 +247,10 @@ static bool EveEmailLogJsonData(const Flow *f, void *state, void *vtx, uint64_t /* From: */ field = MimeDecFindField(entity, "from"); if (field != NULL) { - char *s = BytesToString((uint8_t *)field->value, - (size_t)field->value_len); + char *s = BytesToString((uint8_t *)field->value, (size_t)field->value_len); if (likely(s != NULL)) { - //printf("From: \"%s\"\n", s); - char * sp = SkipWhiteSpaceTill(s, s + strlen(s)); + // printf("From: \"%s\"\n", s); + char *sp = SkipWhiteSpaceTill(s, s + strlen(s)); jb_set_string(sjs, "from", sp); SCFree(s); } @@ -280,7 +280,8 @@ static bool EveEmailLogJsonData(const Flow *f, void *state, void *vtx, uint64_t } } - if (mime_state->stack == NULL || mime_state->stack->top == NULL || mime_state->stack->top->data == NULL) { + if (mime_state->stack == NULL || mime_state->stack->top == NULL || + mime_state->stack->top->data == NULL) { SCReturnBool(false); } @@ -295,8 +296,7 @@ static bool EveEmailLogJsonData(const Flow *f, void *state, void *vtx, uint64_t bool has_ipv4_url = false; bool has_exe_url = false; for (url = entity->url_list; url != NULL; url = url->next) { - char *s = BytesToString((uint8_t *)url->url, - (size_t)url->url_len); + char *s = BytesToString((uint8_t *)url->url, (size_t)url->url_len); if (s != NULL) { jb_append_string(js_url, s); if (url->url_flags & URL_IS_EXE) @@ -316,8 +316,7 @@ static bool EveEmailLogJsonData(const Flow *f, void *state, void *vtx, uint64_t for (entity = entity->child; entity != NULL; entity = entity->next) { if (entity->ctnt_flags & CTNT_IS_ATTACHMENT) { - char *s = BytesToString((uint8_t *)entity->filename, - (size_t)entity->filename_len); + char *s = BytesToString((uint8_t *)entity->filename, (size_t)entity->filename_len); jb_append_string(js_attach, s); SCFree(s); attach_cnt += 1; @@ -325,8 +324,7 @@ static bool EveEmailLogJsonData(const Flow *f, void *state, void *vtx, uint64_t if (entity->url_list != NULL) { MimeDecUrl *url; for (url = entity->url_list; url != NULL; url = url->next) { - char *s = BytesToString((uint8_t *)url->url, - (size_t)url->url_len); + char *s = BytesToString((uint8_t *)url->url, (size_t)url->url_len); if (s != NULL) { jb_append_string(js_url, s); SCFree(s); @@ -352,10 +350,11 @@ static bool EveEmailLogJsonData(const Flow *f, void *state, void *vtx, uint64_t } /* JSON format logging */ -TmEcode EveEmailLogJson(JsonEmailLogThread *aft, JsonBuilder *js, const Packet *p, Flow *f, void *state, void *vtx, uint64_t tx_id) +TmEcode EveEmailLogJson(JsonEmailLogThread *aft, JsonBuilder *js, const Packet *p, Flow *f, + void *state, void *vtx, uint64_t tx_id) { OutputJsonEmailCtx *email_ctx = aft->emaillog_ctx; - SMTPTransaction *tx = (SMTPTransaction *) vtx; + SMTPTransaction *tx = (SMTPTransaction *)vtx; JsonBuilderMark mark = { 0, 0, 0 }; jb_get_mark(js, &mark); @@ -400,7 +399,7 @@ void OutputEmailInitConf(ConfNode *conf, OutputJsonEmailCtx *email_ctx) } } - email_ctx->fields = 0; + email_ctx->fields = 0; ConfNode *custom; if ((custom = ConfNodeLookupChild(conf, "custom")) != NULL) { ConfNode *field; @@ -417,7 +416,7 @@ void OutputEmailInitConf(ConfNode *conf, OutputJsonEmailCtx *email_ctx) } } - email_ctx->flags = 0; + email_ctx->flags = 0; ConfNode *md5_conf; if ((md5_conf = ConfNodeLookupChild(conf, "md5")) != NULL) { ConfNode *field; diff --git a/src/output-json-email-common.h b/src/output-json-email-common.h index e225f28822f6..c8a645d68a02 100644 --- a/src/output-json-email-common.h +++ b/src/output-json-email-common.h @@ -25,8 +25,8 @@ #define __OUTPUT_JSON_EMAIL_COMMON_H__ typedef struct OutputJsonEmailCtx_ { - uint32_t flags; /** Store mode */ - uint64_t fields;/** Store fields */ + uint32_t flags; /** Store mode */ + uint64_t fields; /** Store fields */ OutputJsonCtx *eve_ctx; } OutputJsonEmailCtx; @@ -35,7 +35,8 @@ typedef struct JsonEmailLogThread_ { OutputJsonThreadCtx *ctx; } JsonEmailLogThread; -TmEcode EveEmailLogJson(JsonEmailLogThread *aft, JsonBuilder *js, const Packet *p, Flow *f, void *state, void *vtx, uint64_t tx_id); +TmEcode EveEmailLogJson(JsonEmailLogThread *aft, JsonBuilder *js, const Packet *p, Flow *f, + void *state, void *vtx, uint64_t tx_id); bool EveEmailAddMetadata(const Flow *f, uint32_t tx_id, JsonBuilder *js); void OutputEmailInitConf(ConfNode *conf, OutputJsonEmailCtx *email_ctx); diff --git a/src/output-json-file.c b/src/output-json-file.c index 1018be06ee80..f29e16b3dd8c 100644 --- a/src/output-json-file.c +++ b/src/output-json-file.c @@ -86,7 +86,7 @@ JsonBuilder *JsonBuildFileInfoRecord(const Packet *p, const File *ff, void *tx, { enum OutputJsonLogDirection fdir = LOG_DIR_FLOW; - switch(dir) { + switch (dir) { case STREAM_TOCLIENT: fdir = LOG_DIR_FLOW_TOCLIENT; break; @@ -242,15 +242,13 @@ static int JsonFileLogger(ThreadVars *tv, void *thread_data, const Packet *p, co return 0; } - static TmEcode JsonFileLogThreadInit(ThreadVars *t, const void *initdata, void **data) { JsonFileLogThread *aft = SCCalloc(1, sizeof(JsonFileLogThread)); if (unlikely(aft == NULL)) return TM_ECODE_FAILED; - if(initdata == NULL) - { + if (initdata == NULL) { SCLogDebug("Error getting context for EveLogFile. \"initdata\" argument NULL"); goto error_exit; } @@ -350,10 +348,10 @@ static OutputInitResult OutputFileLogInitSub(ConfNode *conf, OutputCtx *parent_c return result; } -void JsonFileLogRegister (void) +void JsonFileLogRegister(void) { /* register as child of eve-log */ - OutputRegisterFileSubModule(LOGGER_JSON_FILE, "eve-log", "JsonFileLog", - "eve-log.files", OutputFileLogInitSub, JsonFileLogger, - JsonFileLogThreadInit, JsonFileLogThreadDeinit, NULL); + OutputRegisterFileSubModule(LOGGER_JSON_FILE, "eve-log", "JsonFileLog", "eve-log.files", + OutputFileLogInitSub, JsonFileLogger, JsonFileLogThreadInit, JsonFileLogThreadDeinit, + NULL); } diff --git a/src/output-json-flow.c b/src/output-json-flow.c index 07bcd954f2f5..ce7efb98f22a 100644 --- a/src/output-json-flow.c +++ b/src/output-json-flow.c @@ -54,7 +54,7 @@ static JsonBuilder *CreateEveHeaderFromFlow(const Flow *f) { char timebuf[64]; - char srcip[46] = {0}, dstip[46] = {0}; + char srcip[46] = { 0 }, dstip[46] = { 0 }; Port sp, dp; JsonBuilder *jb = jb_new_object(); @@ -121,7 +121,7 @@ static JsonBuilder *CreateEveHeaderFromFlow(const Flow *f) /* tuple */ jb_set_string(jb, "src_ip", srcip); - switch(f->proto) { + switch (f->proto) { case IPPROTO_ICMP: break; case IPPROTO_UDP: @@ -131,7 +131,7 @@ static JsonBuilder *CreateEveHeaderFromFlow(const Flow *f) break; } jb_set_string(jb, "dest_ip", dstip); - switch(f->proto) { + switch (f->proto) { case IPPROTO_ICMP: break; case IPPROTO_UDP: @@ -145,7 +145,7 @@ static JsonBuilder *CreateEveHeaderFromFlow(const Flow *f) jb_set_string(jb, "proto", known_proto[f->proto]); } else { char proto[4]; - snprintf(proto, sizeof(proto), "%"PRIu8"", f->proto); + snprintf(proto, sizeof(proto), "%" PRIu8 "", f->proto); jb_set_string(jb, "proto", proto); } @@ -181,10 +181,8 @@ void EveAddAppProto(Flow *f, JsonBuilder *js) jb_set_string(js, "app_proto_orig", AppProtoToString(f->alproto_orig)); } if (f->alproto_expect != f->alproto && f->alproto_expect != ALPROTO_UNKNOWN) { - jb_set_string(js, "app_proto_expected", - AppProtoToString(f->alproto_expect)); + jb_set_string(js, "app_proto_expected", AppProtoToString(f->alproto_expect)); } - } void EveAddFlow(Flow *f, JsonBuilder *js) @@ -290,16 +288,13 @@ static void EveFlowLogJSON(OutputJsonThreadCtx *aft, JsonBuilder *jb, Flow *f) TcpSession *ssn = f->protoctx; char hexflags[3]; - snprintf(hexflags, sizeof(hexflags), "%02x", - ssn ? ssn->tcp_packet_flags : 0); + snprintf(hexflags, sizeof(hexflags), "%02x", ssn ? ssn->tcp_packet_flags : 0); jb_set_string(jb, "tcp_flags", hexflags); - snprintf(hexflags, sizeof(hexflags), "%02x", - ssn ? ssn->client.tcp_flags : 0); + snprintf(hexflags, sizeof(hexflags), "%02x", ssn ? ssn->client.tcp_flags : 0); jb_set_string(jb, "tcp_flags_ts", hexflags); - snprintf(hexflags, sizeof(hexflags), "%02x", - ssn ? ssn->server.tcp_flags : 0); + snprintf(hexflags, sizeof(hexflags), "%02x", ssn ? ssn->server.tcp_flags : 0); jb_set_string(jb, "tcp_flags_tc", hexflags); EveTcpFlags(ssn ? ssn->tcp_packet_flags : 0, jb); @@ -345,7 +340,7 @@ static int JsonFlowLogger(ThreadVars *tv, void *thread_data, Flow *f) SCReturnInt(TM_ECODE_OK); } -void JsonFlowLogRegister (void) +void JsonFlowLogRegister(void) { /* register as child of eve-log */ OutputRegisterFlowSubModule(LOGGER_JSON_FLOW, "eve-log", "JsonFlowLog", "eve-log.flow", diff --git a/src/output-json-ftp.c b/src/output-json-ftp.c index 34422f72f4af..c31a6b1392a1 100644 --- a/src/output-json-ftp.c +++ b/src/output-json-ftp.c @@ -62,9 +62,7 @@ bool EveFTPLogCommand(void *vtx, JsonBuilder *jb) jb_set_string(jb, "command", tx->command_descriptor->command_name); uint32_t min_length = tx->command_descriptor->command_length + 1; /* command + space */ if (tx->request_length > min_length) { - jb_set_string_from_bytes(jb, - "command_data", - (const uint8_t *)tx->request + min_length, + jb_set_string_from_bytes(jb, "command_data", (const uint8_t *)tx->request + min_length, tx->request_length - min_length - 1); if (tx->request_truncated) { JB_SET_TRUE(jb, "command_truncated"); @@ -79,7 +77,7 @@ bool EveFTPLogCommand(void *vtx, JsonBuilder *jb) int resp_cnt = 0; FTPString *response; bool is_cc_array_open = false; - TAILQ_FOREACH(response, &tx->response_list, next) { + TAILQ_FOREACH (response, &tx->response_list, next) { /* handle multiple lines within the response, \r\n delimited */ uint8_t *where = response->str; uint16_t length = 0; @@ -95,7 +93,7 @@ bool EveFTPLogCommand(void *vtx, JsonBuilder *jb) while ((pos = JsonGetNextLineFromBuffer((const char *)where, length)) != UINT16_MAX) { uint16_t offset = 0; /* Try to find a completion code for this line */ - if (pos >= 3) { + if (pos >= 3) { /* Gather the completion code if present */ if (isdigit(where[0]) && isdigit(where[1]) && isdigit(where[2])) { if (!is_cc_array_open) { @@ -108,7 +106,8 @@ bool EveFTPLogCommand(void *vtx, JsonBuilder *jb) } /* move past 3 character completion code */ if (pos >= offset) { - jb_append_string_from_bytes(js_resplist, (const uint8_t *)where + offset, pos - offset); + jb_append_string_from_bytes( + js_resplist, (const uint8_t *)where + offset, pos - offset); resp_cnt++; } @@ -132,7 +131,7 @@ bool EveFTPLogCommand(void *vtx, JsonBuilder *jb) } if (tx->command_descriptor->command == FTP_COMMAND_PORT || - tx->command_descriptor->command == FTP_COMMAND_EPRT) { + tx->command_descriptor->command == FTP_COMMAND_EPRT) { if (tx->active) { JB_SET_STRING(jb, "mode", "active"); } else { @@ -155,9 +154,8 @@ bool EveFTPLogCommand(void *vtx, JsonBuilder *jb) return true; } - -static int JsonFTPLogger(ThreadVars *tv, void *thread_data, - const Packet *p, Flow *f, void *state, void *vtx, uint64_t tx_id) +static int JsonFTPLogger(ThreadVars *tv, void *thread_data, const Packet *p, Flow *f, void *state, + void *vtx, uint64_t tx_id) { SCEnter(); OutputJsonThreadCtx *thread = thread_data; @@ -191,8 +189,7 @@ static int JsonFTPLogger(ThreadVars *tv, void *thread_data, return TM_ECODE_FAILED; } -static OutputInitResult OutputFTPLogInitSub(ConfNode *conf, - OutputCtx *parent_ctx) +static OutputInitResult OutputFTPLogInitSub(ConfNode *conf, OutputCtx *parent_ctx) { AppLayerParserRegisterLogger(IPPROTO_TCP, ALPROTO_FTP); AppLayerParserRegisterLogger(IPPROTO_TCP, ALPROTO_FTPDATA); diff --git a/src/output-json-http.c b/src/output-json-http.c index 5f44e955573d..316c08305b00 100644 --- a/src/output-json-http.c +++ b/src/output-json-http.c @@ -54,8 +54,8 @@ #include "util-byte.h" typedef struct LogHttpFileCtx_ { - uint32_t flags; /** Store mode */ - uint64_t fields;/** Store fields */ + uint32_t flags; /** Store mode */ + uint64_t fields; /** Store fields */ HttpXFFCfg *xff_cfg; HttpXFFCfg *parent_xff_cfg; OutputJsonCtx *eve_ctx; @@ -67,13 +67,13 @@ typedef struct JsonHttpLogThread_ { OutputJsonThreadCtx *ctx; } JsonHttpLogThread; -#define MAX_SIZE_HEADER_NAME 256 +#define MAX_SIZE_HEADER_NAME 256 #define MAX_SIZE_HEADER_VALUE 2048 -#define LOG_HTTP_DEFAULT 0 -#define LOG_HTTP_EXTENDED 1 -#define LOG_HTTP_REQUEST 2 /* request field */ -#define LOG_HTTP_ARRAY 4 /* require array handling */ +#define LOG_HTTP_DEFAULT 0 +#define LOG_HTTP_EXTENDED 1 +#define LOG_HTTP_REQUEST 2 /* request field */ +#define LOG_HTTP_ARRAY 4 /* require array handling */ #define LOG_HTTP_REQ_HEADERS 8 #define LOG_HTTP_RES_HEADERS 16 @@ -239,7 +239,8 @@ static void EveHttpLogJSONBasic(JsonBuilder *js, htp_tx_t *tx) if (h_content_type != NULL) { const size_t size = bstr_len(h_content_type->value) * 2 + 1; char string[size]; - BytesToStringBuffer(bstr_ptr(h_content_type->value), bstr_len(h_content_type->value), string, size); + BytesToStringBuffer( + bstr_ptr(h_content_type->value), bstr_len(h_content_type->value), string, size); char *p = strchr(string, ';'); if (p != NULL) *p = '\0'; @@ -311,10 +312,10 @@ static void EveHttpLogJSONExtended(JsonBuilder *js, htp_tx_t *tx) static void EveHttpLogJSONHeaders( JsonBuilder *js, uint32_t direction, htp_tx_t *tx, LogHttpFileCtx *http_ctx) { - htp_table_t * headers = direction & LOG_HTTP_REQ_HEADERS ? - tx->request_headers : tx->response_headers; - char name[MAX_SIZE_HEADER_NAME] = {0}; - char value[MAX_SIZE_HEADER_VALUE] = {0}; + htp_table_t *headers = + direction & LOG_HTTP_REQ_HEADERS ? tx->request_headers : tx->response_headers; + char name[MAX_SIZE_HEADER_NAME] = { 0 }; + char value[MAX_SIZE_HEADER_VALUE] = { 0 }; size_t n = htp_table_size(headers); JsonBuilderMark mark = { 0, 0, 0 }; jb_get_mark(js, &mark); @@ -344,13 +345,14 @@ static void EveHttpLogJSONHeaders( } array_empty = false; jb_start_object(js); - size_t size_name = bstr_len(h->name) < MAX_SIZE_HEADER_NAME - 1 ? - bstr_len(h->name) : MAX_SIZE_HEADER_NAME - 1; + size_t size_name = bstr_len(h->name) < MAX_SIZE_HEADER_NAME - 1 ? bstr_len(h->name) + : MAX_SIZE_HEADER_NAME - 1; memcpy(name, bstr_ptr(h->name), size_name); name[size_name] = '\0'; jb_set_string(js, "name", name); - size_t size_value = bstr_len(h->value) < MAX_SIZE_HEADER_VALUE - 1 ? - bstr_len(h->value) : MAX_SIZE_HEADER_VALUE - 1; + size_t size_value = bstr_len(h->value) < MAX_SIZE_HEADER_VALUE - 1 + ? bstr_len(h->value) + : MAX_SIZE_HEADER_VALUE - 1; memcpy(value, bstr_ptr(h->value), size_value); value[size_value] = '\0'; jb_set_string(js, "value", value); @@ -372,15 +374,13 @@ static void BodyPrintableBuffer(JsonBuilder *js, HtpBody *body, const char *key) uint32_t body_data_len; uint64_t body_offset; - if (StreamingBufferGetData(body->sb, &body_data, - &body_data_len, &body_offset) == 0) { + if (StreamingBufferGetData(body->sb, &body_data, &body_data_len, &body_offset) == 0) { return; } uint8_t printable_buf[body_data_len + 1]; - PrintStringsToBuffer(printable_buf, &offset, - sizeof(printable_buf), - body_data, body_data_len); + PrintStringsToBuffer( + printable_buf, &offset, sizeof(printable_buf), body_data, body_data_len); if (offset > 0) { jb_set_string(js, key, (char *)printable_buf); } @@ -409,8 +409,7 @@ static void BodyBase64Buffer(JsonBuilder *js, HtpBody *body, const char *key) uint32_t body_data_len; uint64_t body_offset; - if (StreamingBufferGetData(body->sb, &body_data, - &body_data_len, &body_offset) == 0) { + if (StreamingBufferGetData(body->sb, &body_data, &body_data_len, &body_offset) == 0) { return; } @@ -450,7 +449,8 @@ static void EveHttpLogJSON(JsonHttpLogThread *aft, JsonBuilder *js, htp_tx_t *tx jb_close(js); } -static int JsonHttpLogger(ThreadVars *tv, void *thread_data, const Packet *p, Flow *f, void *alstate, void *txptr, uint64_t tx_id) +static int JsonHttpLogger(ThreadVars *tv, void *thread_data, const Packet *p, Flow *f, + void *alstate, void *txptr, uint64_t tx_id) { SCEnter(); @@ -465,8 +465,8 @@ static int JsonHttpLogger(ThreadVars *tv, void *thread_data, const Packet *p, Fl SCLogDebug("got a HTTP request and now logging !!"); EveHttpLogJSON(jhl, js, tx, tx_id); - HttpXFFCfg *xff_cfg = jhl->httplog_ctx->xff_cfg != NULL ? - jhl->httplog_ctx->xff_cfg : jhl->httplog_ctx->parent_xff_cfg; + HttpXFFCfg *xff_cfg = jhl->httplog_ctx->xff_cfg != NULL ? jhl->httplog_ctx->xff_cfg + : jhl->httplog_ctx->parent_xff_cfg; /* xff header */ if ((xff_cfg != NULL) && !(xff_cfg->flags & XFF_DISABLED) && p->flow != NULL) { @@ -478,8 +478,7 @@ static int JsonHttpLogger(ThreadVars *tv, void *thread_data, const Packet *p, Fl if (have_xff_ip) { if (xff_cfg->flags & XFF_EXTRADATA) { jb_set_string(js, "xff", buffer); - } - else if (xff_cfg->flags & XFF_OVERWRITE) { + } else if (xff_cfg->flags & XFF_OVERWRITE) { if (p->flowflags & FLOW_PKT_TOCLIENT) { jb_set_string(js, "dest_ip", buffer); } else { @@ -606,14 +605,13 @@ static TmEcode JsonHttpLogThreadInit(ThreadVars *t, const void *initdata, void * if (unlikely(aft == NULL)) return TM_ECODE_FAILED; - if(initdata == NULL) - { + if (initdata == NULL) { SCLogDebug("Error getting context for EveLogHTTP. \"initdata\" argument NULL"); goto error_exit; } /* Use the Output Context (file pointer and mutex) */ - aft->httplog_ctx = ((OutputCtx *)initdata)->data; //TODO + aft->httplog_ctx = ((OutputCtx *)initdata)->data; // TODO aft->ctx = CreateEveThreadCtx(t, aft->httplog_ctx->eve_ctx); if (!aft->ctx) { @@ -644,7 +642,7 @@ static TmEcode JsonHttpLogThreadDeinit(ThreadVars *t, void *data) return TM_ECODE_OK; } -void JsonHttpLogRegister (void) +void JsonHttpLogRegister(void) { /* register as child of eve-log */ OutputRegisterTxSubModule(LOGGER_JSON_TX, "eve-log", "JsonHttpLog", "eve-log.http", diff --git a/src/output-json-http.h b/src/output-json-http.h index cb358a4b314f..f4eb7a84c2d6 100644 --- a/src/output-json-http.h +++ b/src/output-json-http.h @@ -31,4 +31,3 @@ void EveHttpLogJSONBodyPrintable(JsonBuilder *js, Flow *f, uint64_t tx_id); void EveHttpLogJSONBodyBase64(JsonBuilder *js, Flow *f, uint64_t tx_id); #endif /* __OUTPUT_JSON_HTTP_H__ */ - diff --git a/src/output-json-http2.c b/src/output-json-http2.c index cb096f37a043..6171aba441cd 100644 --- a/src/output-json-http2.c +++ b/src/output-json-http2.c @@ -55,14 +55,13 @@ typedef struct OutputHttp2Ctx_ { OutputJsonCtx *eve_ctx; } OutputHttp2Ctx; - typedef struct JsonHttp2LogThread_ { OutputHttp2Ctx *http2log_ctx; OutputJsonThreadCtx *ctx; } JsonHttp2LogThread; -static int JsonHttp2Logger(ThreadVars *tv, void *thread_data, const Packet *p, - Flow *f, void *state, void *txptr, uint64_t tx_id) +static int JsonHttp2Logger(ThreadVars *tv, void *thread_data, const Packet *p, Flow *f, void *state, + void *txptr, uint64_t tx_id) { JsonHttp2LogThread *aft = (JsonHttp2LogThread *)thread_data; @@ -90,8 +89,7 @@ static TmEcode JsonHttp2LogThreadInit(ThreadVars *t, const void *initdata, void if (unlikely(aft == NULL)) return TM_ECODE_FAILED; - if(initdata == NULL) - { + if (initdata == NULL) { SCLogDebug("Error getting context for EveLogHTTP2. \"initdata\" argument NULL"); goto error_exit; } @@ -160,7 +158,7 @@ static OutputInitResult OutputHttp2LogInitSub(ConfNode *conf, OutputCtx *parent_ return result; } -void JsonHttp2LogRegister (void) +void JsonHttp2LogRegister(void) { /* also register as child of eve-log */ OutputRegisterTxSubModuleWithProgress(LOGGER_JSON_TX, "eve-log", MODULE_NAME, "eve-log.http2", diff --git a/src/output-json-krb5.c b/src/output-json-krb5.c index 9fc45c5d3c53..f958f606e6be 100644 --- a/src/output-json-krb5.c +++ b/src/output-json-krb5.c @@ -48,8 +48,8 @@ #include "rust.h" -static int JsonKRB5Logger(ThreadVars *tv, void *thread_data, - const Packet *p, Flow *f, void *state, void *tx, uint64_t tx_id) +static int JsonKRB5Logger(ThreadVars *tv, void *thread_data, const Packet *p, Flow *f, void *state, + void *tx, uint64_t tx_id) { KRB5Transaction *krb5tx = tx; OutputJsonThreadCtx *thread = thread_data; @@ -73,8 +73,7 @@ static int JsonKRB5Logger(ThreadVars *tv, void *thread_data, return TM_ECODE_FAILED; } -static OutputInitResult OutputKRB5LogInitSub(ConfNode *conf, - OutputCtx *parent_ctx) +static OutputInitResult OutputKRB5LogInitSub(ConfNode *conf, OutputCtx *parent_ctx) { AppLayerParserRegisterLogger(IPPROTO_TCP, ALPROTO_KRB5); AppLayerParserRegisterLogger(IPPROTO_UDP, ALPROTO_KRB5); diff --git a/src/output-json-metadata.c b/src/output-json-metadata.c index 772b2ccb06f2..b61e5cc97008 100644 --- a/src/output-json-metadata.c +++ b/src/output-json-metadata.c @@ -92,7 +92,7 @@ static bool JsonMetadataLogCondition(ThreadVars *tv, void *data, const Packet *p return p->pktvar != NULL; } -void JsonMetadataLogRegister (void) +void JsonMetadataLogRegister(void) { OutputRegisterPacketSubModule(LOGGER_JSON_METADATA, "eve-log", MODULE_NAME, "eve-log.metadata", OutputJsonLogInitSub, JsonMetadataLogger, JsonMetadataLogCondition, JsonLogThreadInit, diff --git a/src/output-json-mqtt.c b/src/output-json-mqtt.c index 2f600343e20d..7ebed4945b1b 100644 --- a/src/output-json-mqtt.c +++ b/src/output-json-mqtt.c @@ -46,16 +46,16 @@ #include "rust.h" #define MQTT_LOG_PASSWORDS BIT_U32(0) -#define MQTT_DEFAULTS (MQTT_LOG_PASSWORDS) +#define MQTT_DEFAULTS (MQTT_LOG_PASSWORDS) typedef struct LogMQTTFileCtx_ { - uint32_t flags; + uint32_t flags; OutputJsonCtx *eve_ctx; } LogMQTTFileCtx; typedef struct LogMQTTLogThread_ { LogMQTTFileCtx *mqttlog_ctx; - uint32_t count; + uint32_t count; OutputJsonThreadCtx *ctx; } LogMQTTLogThread; @@ -64,13 +64,13 @@ bool JsonMQTTAddMetadata(void *vtx, JsonBuilder *js) return rs_mqtt_logger_log(vtx, MQTT_DEFAULTS, js); } -static int JsonMQTTLogger(ThreadVars *tv, void *thread_data, - const Packet *p, Flow *f, void *state, void *tx, uint64_t tx_id) +static int JsonMQTTLogger(ThreadVars *tv, void *thread_data, const Packet *p, Flow *f, void *state, + void *tx, uint64_t tx_id) { LogMQTTLogThread *thread = thread_data; enum OutputJsonLogDirection dir; - if (rs_mqtt_tx_is_toclient((MQTTTransaction*) tx)) { + if (rs_mqtt_tx_is_toclient((MQTTTransaction *)tx)) { dir = LOG_DIR_FLOW_TOCLIENT; } else { dir = LOG_DIR_FLOW_TOSERVER; @@ -115,8 +115,7 @@ static void JsonMQTTLogParseConfig(ConfNode *conf, LogMQTTFileCtx *mqttlog_ctx) } } -static OutputInitResult OutputMQTTLogInitSub(ConfNode *conf, - OutputCtx *parent_ctx) +static OutputInitResult OutputMQTTLogInitSub(ConfNode *conf, OutputCtx *parent_ctx) { OutputInitResult result = { NULL, false }; OutputJsonCtx *ajt = parent_ctx->data; diff --git a/src/output-json-netflow.c b/src/output-json-netflow.c index 2ac6995cfad6..79c705c4d73e 100644 --- a/src/output-json-netflow.c +++ b/src/output-json-netflow.c @@ -52,7 +52,7 @@ static JsonBuilder *CreateEveHeaderFromNetFlow(const Flow *f, int dir) { char timebuf[64]; - char srcip[46] = {0}, dstip[46] = {0}; + char srcip[46] = { 0 }, dstip[46] = { 0 }; Port sp, dp; JsonBuilder *js = jb_new_object(); @@ -125,7 +125,7 @@ static JsonBuilder *CreateEveHeaderFromNetFlow(const Flow *f, int dir) /* tuple */ jb_set_string(js, "src_ip", srcip); - switch(f->proto) { + switch (f->proto) { case IPPROTO_ICMP: break; case IPPROTO_UDP: @@ -135,7 +135,7 @@ static JsonBuilder *CreateEveHeaderFromNetFlow(const Flow *f, int dir) break; } jb_set_string(js, "dest_ip", dstip); - switch(f->proto) { + switch (f->proto) { case IPPROTO_ICMP: break; case IPPROTO_UDP: @@ -149,7 +149,7 @@ static JsonBuilder *CreateEveHeaderFromNetFlow(const Flow *f, int dir) jb_set_string(js, "proto", known_proto[f->proto]); } else { char proto[4]; - snprintf(proto, sizeof(proto), "%"PRIu8"", f->proto); + snprintf(proto, sizeof(proto), "%" PRIu8 "", f->proto); jb_set_string(js, "proto", proto); } @@ -161,7 +161,6 @@ static JsonBuilder *CreateEveHeaderFromNetFlow(const Flow *f, int dir) if (dir == 1) { type = f->icmp_d.type; code = f->icmp_d.code; - } jb_set_uint(js, "icmp_type", type); jb_set_uint(js, "icmp_code", code); @@ -177,8 +176,7 @@ static JsonBuilder *CreateEveHeaderFromNetFlow(const Flow *f, int dir) /* JSON format logging */ static void NetFlowLogEveToServer(JsonBuilder *js, Flow *f) { - jb_set_string(js, "app_proto", - AppProtoToString(f->alproto_ts ? f->alproto_ts : f->alproto)); + jb_set_string(js, "app_proto", AppProtoToString(f->alproto_ts ? f->alproto_ts : f->alproto)); jb_open_object(js, "netflow"); @@ -209,8 +207,7 @@ static void NetFlowLogEveToServer(JsonBuilder *js, Flow *f) TcpSession *ssn = f->protoctx; char hexflags[3]; - snprintf(hexflags, sizeof(hexflags), "%02x", - ssn ? ssn->client.tcp_flags : 0); + snprintf(hexflags, sizeof(hexflags), "%02x", ssn ? ssn->client.tcp_flags : 0); jb_set_string(js, "tcp_flags", hexflags); EveTcpFlags(ssn ? ssn->client.tcp_flags : 0, js); @@ -221,8 +218,7 @@ static void NetFlowLogEveToServer(JsonBuilder *js, Flow *f) static void NetFlowLogEveToClient(JsonBuilder *js, Flow *f) { - jb_set_string(js, "app_proto", - AppProtoToString(f->alproto_tc ? f->alproto_tc : f->alproto)); + jb_set_string(js, "app_proto", AppProtoToString(f->alproto_tc ? f->alproto_tc : f->alproto)); jb_open_object(js, "netflow"); @@ -256,8 +252,7 @@ static void NetFlowLogEveToClient(JsonBuilder *js, Flow *f) TcpSession *ssn = f->protoctx; char hexflags[3]; - snprintf(hexflags, sizeof(hexflags), "%02x", - ssn ? ssn->server.tcp_flags : 0); + snprintf(hexflags, sizeof(hexflags), "%02x", ssn ? ssn->server.tcp_flags : 0); jb_set_string(js, "tcp_flags", hexflags); EveTcpFlags(ssn ? ssn->server.tcp_flags : 0, js); diff --git a/src/output-json-nfs.c b/src/output-json-nfs.c index 946f85cdbbd5..706dae414d69 100644 --- a/src/output-json-nfs.c +++ b/src/output-json-nfs.c @@ -71,8 +71,8 @@ bool EveNFSAddMetadata(const Flow *f, uint64_t tx_id, JsonBuilder *jb) return false; } -static int JsonNFSLogger(ThreadVars *tv, void *thread_data, - const Packet *p, Flow *f, void *state, void *tx, uint64_t tx_id) +static int JsonNFSLogger(ThreadVars *tv, void *thread_data, const Packet *p, Flow *f, void *state, + void *tx, uint64_t tx_id) { NFSTransaction *nfstx = tx; OutputJsonThreadCtx *thread = thread_data; @@ -99,8 +99,7 @@ static int JsonNFSLogger(ThreadVars *tv, void *thread_data, return TM_ECODE_OK; } -static OutputInitResult NFSLogInitSub(ConfNode *conf, - OutputCtx *parent_ctx) +static OutputInitResult NFSLogInitSub(ConfNode *conf, OutputCtx *parent_ctx) { AppLayerParserRegisterLogger(IPPROTO_TCP, ALPROTO_NFS); AppLayerParserRegisterLogger(IPPROTO_UDP, ALPROTO_NFS); diff --git a/src/output-json-rdp.c b/src/output-json-rdp.c index bc5d9ae9df89..95e63ac815c9 100644 --- a/src/output-json-rdp.c +++ b/src/output-json-rdp.c @@ -42,8 +42,8 @@ #include "output-json-rdp.h" #include "rust.h" -static int JsonRdpLogger(ThreadVars *tv, void *thread_data, - const Packet *p, Flow *f, void *state, void *tx, uint64_t tx_id) +static int JsonRdpLogger(ThreadVars *tv, void *thread_data, const Packet *p, Flow *f, void *state, + void *tx, uint64_t tx_id) { OutputJsonThreadCtx *thread = thread_data; @@ -61,8 +61,7 @@ static int JsonRdpLogger(ThreadVars *tv, void *thread_data, return TM_ECODE_OK; } -static OutputInitResult OutputRdpLogInitSub(ConfNode *conf, - OutputCtx *parent_ctx) +static OutputInitResult OutputRdpLogInitSub(ConfNode *conf, OutputCtx *parent_ctx) { AppLayerParserRegisterLogger(IPPROTO_TCP, ALPROTO_RDP); return OutputJsonLogInitSub(conf, parent_ctx); diff --git a/src/output-json-rfb.c b/src/output-json-rfb.c index e2b832bece13..c3222a90724e 100644 --- a/src/output-json-rfb.c +++ b/src/output-json-rfb.c @@ -46,8 +46,8 @@ #include "rust-bindings.h" -static int JsonRFBLogger(ThreadVars *tv, void *thread_data, - const Packet *p, Flow *f, void *state, void *tx, uint64_t tx_id) +static int JsonRFBLogger(ThreadVars *tv, void *thread_data, const Packet *p, Flow *f, void *state, + void *tx, uint64_t tx_id) { OutputJsonThreadCtx *thread = thread_data; @@ -70,8 +70,7 @@ static int JsonRFBLogger(ThreadVars *tv, void *thread_data, return TM_ECODE_FAILED; } -static OutputInitResult OutputRFBLogInitSub(ConfNode *conf, - OutputCtx *parent_ctx) +static OutputInitResult OutputRFBLogInitSub(ConfNode *conf, OutputCtx *parent_ctx) { AppLayerParserRegisterLogger(IPPROTO_TCP, ALPROTO_RFB); return OutputJsonLogInitSub(conf, parent_ctx); diff --git a/src/output-json-sip.c b/src/output-json-sip.c index 7dd442cf6aba..6f5d79ba57d2 100644 --- a/src/output-json-sip.c +++ b/src/output-json-sip.c @@ -48,8 +48,8 @@ #include "rust.h" -static int JsonSIPLogger(ThreadVars *tv, void *thread_data, - const Packet *p, Flow *f, void *state, void *tx, uint64_t tx_id) +static int JsonSIPLogger(ThreadVars *tv, void *thread_data, const Packet *p, Flow *f, void *state, + void *tx, uint64_t tx_id) { SIPTransaction *siptx = tx; OutputJsonThreadCtx *thread = thread_data; @@ -73,8 +73,7 @@ static int JsonSIPLogger(ThreadVars *tv, void *thread_data, return TM_ECODE_FAILED; } -static OutputInitResult OutputSIPLogInitSub(ConfNode *conf, - OutputCtx *parent_ctx) +static OutputInitResult OutputSIPLogInitSub(ConfNode *conf, OutputCtx *parent_ctx) { AppLayerParserRegisterLogger(IPPROTO_UDP, ALPROTO_SIP); return OutputJsonLogInitSub(conf, parent_ctx); diff --git a/src/output-json-smb.c b/src/output-json-smb.c index 492c50fe27a1..d53a2b73096b 100644 --- a/src/output-json-smb.c +++ b/src/output-json-smb.c @@ -43,8 +43,8 @@ bool EveSMBAddMetadata(const Flow *f, uint64_t tx_id, JsonBuilder *jb) return false; } -static int JsonSMBLogger(ThreadVars *tv, void *thread_data, - const Packet *p, Flow *f, void *state, void *tx, uint64_t tx_id) +static int JsonSMBLogger(ThreadVars *tv, void *thread_data, const Packet *p, Flow *f, void *state, + void *tx, uint64_t tx_id) { OutputJsonThreadCtx *thread = thread_data; diff --git a/src/output-json-smtp.c b/src/output-json-smtp.c index f7674687c5c4..8d96b4bcd8a2 100644 --- a/src/output-json-smtp.c +++ b/src/output-json-smtp.c @@ -63,14 +63,15 @@ static void EveSmtpDataLogger(void *state, void *vtx, JsonBuilder *js) } if (!TAILQ_EMPTY(&tx->rcpt_to_list)) { jb_open_array(js, "rcpt_to"); - TAILQ_FOREACH(rcptto_str, &tx->rcpt_to_list, next) { + TAILQ_FOREACH (rcptto_str, &tx->rcpt_to_list, next) { jb_append_string(js, (char *)rcptto_str->str); } jb_close(js); } } -static int JsonSmtpLogger(ThreadVars *tv, void *thread_data, const Packet *p, Flow *f, void *state, void *tx, uint64_t tx_id) +static int JsonSmtpLogger(ThreadVars *tv, void *thread_data, const Packet *p, Flow *f, void *state, + void *tx, uint64_t tx_id) { SCEnter(); JsonEmailLogThread *jhl = (JsonEmailLogThread *)thread_data; @@ -90,7 +91,6 @@ static int JsonSmtpLogger(ThreadVars *tv, void *thread_data, const Packet *p, Fl jb_free(jb); SCReturnInt(TM_ECODE_OK); - } bool EveSMTPAddMetadata(const Flow *f, uint64_t tx_id, JsonBuilder *js) @@ -153,7 +153,7 @@ static TmEcode JsonSmtpLogThreadInit(ThreadVars *t, const void *initdata, void * if (unlikely(aft == NULL)) return TM_ECODE_FAILED; - if(initdata == NULL) { + if (initdata == NULL) { SCLogDebug("Error getting context for EveLogSMTP. \"initdata\" argument NULL"); goto error_exit; } @@ -189,7 +189,8 @@ static TmEcode JsonSmtpLogThreadDeinit(ThreadVars *t, void *data) return TM_ECODE_OK; } -void JsonSmtpLogRegister (void) { +void JsonSmtpLogRegister(void) +{ /* register as child of eve-log */ OutputRegisterTxSubModule(LOGGER_JSON_TX, "eve-log", "JsonSmtpLog", "eve-log.smtp", OutputSmtpLogInitSub, ALPROTO_SMTP, JsonSmtpLogger, JsonSmtpLogThreadInit, diff --git a/src/output-json-snmp.c b/src/output-json-snmp.c index cbf0a7c992e4..8fc739d244e7 100644 --- a/src/output-json-snmp.c +++ b/src/output-json-snmp.c @@ -48,8 +48,8 @@ #include "rust.h" -static int JsonSNMPLogger(ThreadVars *tv, void *thread_data, - const Packet *p, Flow *f, void *state, void *tx, uint64_t tx_id) +static int JsonSNMPLogger(ThreadVars *tv, void *thread_data, const Packet *p, Flow *f, void *state, + void *tx, uint64_t tx_id) { SNMPTransaction *snmptx = tx; OutputJsonThreadCtx *thread = thread_data; @@ -73,8 +73,7 @@ static int JsonSNMPLogger(ThreadVars *tv, void *thread_data, return TM_ECODE_FAILED; } -static OutputInitResult OutputSNMPLogInitSub(ConfNode *conf, - OutputCtx *parent_ctx) +static OutputInitResult OutputSNMPLogInitSub(ConfNode *conf, OutputCtx *parent_ctx) { AppLayerParserRegisterLogger(IPPROTO_UDP, ALPROTO_SNMP); return OutputJsonLogInitSub(conf, parent_ctx); diff --git a/src/output-json-ssh.c b/src/output-json-ssh.c index 45a8d8eab333..3ec32c0db6e1 100644 --- a/src/output-json-ssh.c +++ b/src/output-json-ssh.c @@ -51,8 +51,8 @@ #define MODULE_NAME "LogSshLog" -static int JsonSshLogger(ThreadVars *tv, void *thread_data, const Packet *p, - Flow *f, void *state, void *txptr, uint64_t tx_id) +static int JsonSshLogger(ThreadVars *tv, void *thread_data, const Packet *p, Flow *f, void *state, + void *txptr, uint64_t tx_id) { OutputJsonThreadCtx *thread = thread_data; @@ -80,7 +80,7 @@ static OutputInitResult OutputSshLogInitSub(ConfNode *conf, OutputCtx *parent_ct return OutputJsonLogInitSub(conf, parent_ctx); } -void JsonSshLogRegister (void) +void JsonSshLogRegister(void) { /* register as child of eve-log */ OutputRegisterTxSubModuleWithCondition(LOGGER_JSON_TX, "eve-log", "JsonSshLog", "eve-log.ssh", diff --git a/src/output-json-stats.c b/src/output-json-stats.c index 7bfcfc58cad2..305a72d62154 100644 --- a/src/output-json-stats.c +++ b/src/output-json-stats.c @@ -73,8 +73,7 @@ typedef struct JsonStatsLogThread_ { MemBuffer *buffer; } JsonStatsLogThread; -static json_t *EngineStats2Json(const DetectEngineCtx *de_ctx, - const OutputEngineInfo output) +static json_t *EngineStats2Json(const DetectEngineCtx *de_ctx, const OutputEngineInfo output) { char timebuf[64]; const SigFileLoaderStat *sig_stat = NULL; @@ -91,13 +90,9 @@ static json_t *EngineStats2Json(const DetectEngineCtx *de_ctx, } sig_stat = &de_ctx->sig_stat; - if ((output == OUTPUT_ENGINE_RULESET || output == OUTPUT_ENGINE_ALL) && - sig_stat != NULL) - { - json_object_set_new(jdata, "rules_loaded", - json_integer(sig_stat->good_sigs_total)); - json_object_set_new(jdata, "rules_failed", - json_integer(sig_stat->bad_sigs_total)); + if ((output == OUTPUT_ENGINE_RULESET || output == OUTPUT_ENGINE_ALL) && sig_stat != NULL) { + json_object_set_new(jdata, "rules_loaded", json_integer(sig_stat->good_sigs_total)); + json_object_set_new(jdata, "rules_failed", json_integer(sig_stat->bad_sigs_total)); } return jdata; @@ -119,7 +114,7 @@ static TmEcode OutputEngineStats2Json(json_t **jdata, const OutputEngineInfo out goto err2; } - while(list) { + while (list) { js_tenant = json_object(); if (js_tenant == NULL) { goto err3; @@ -156,11 +151,13 @@ static TmEcode OutputEngineStats2Json(json_t **jdata, const OutputEngineInfo out return TM_ECODE_FAILED; } -TmEcode OutputEngineStatsReloadTime(json_t **jdata) { +TmEcode OutputEngineStatsReloadTime(json_t **jdata) +{ return OutputEngineStats2Json(jdata, OUTPUT_ENGINE_LAST_RELOAD); } -TmEcode OutputEngineStatsRuleset(json_t **jdata) { +TmEcode OutputEngineStatsRuleset(json_t **jdata) +{ return OutputEngineStats2Json(jdata, OUTPUT_ENGINE_RULESET); } @@ -181,7 +178,7 @@ static json_t *OutputStats2Json(json_t *js, const char *key) strlcpy(s, key, predot_len); iter = json_object_iter_at(js, s); - const char *s2 = strchr(dot+1, '.'); + const char *s2 = strchr(dot + 1, '.'); json_t *value = json_object_iter_value(iter); if (value == NULL) { @@ -198,7 +195,7 @@ static json_t *OutputStats2Json(json_t *js, const char *key) json_object_set_new(js, s, value); } if (s2 != NULL) { - return OutputStats2Json(value, &key[dot-key+1]); + return OutputStats2Json(value, &key[dot - key + 1]); } return value; } @@ -219,8 +216,7 @@ json_t *StatsToJSON(const StatsTable *st, uint8_t flags) /* Uptime, in seconds. */ double up_time_d = difftime(tval.tv_sec, st->start_time); - json_object_set_new(js_stats, "uptime", - json_integer((int)up_time_d)); + json_object_set_new(js_stats, "uptime", json_integer((int)up_time_d)); uint32_t u = 0; if (flags & JSON_STATS_TOTALS) { @@ -246,7 +242,7 @@ json_t *StatsToJSON(const StatsTable *st, uint8_t flags) char deltaname[strlen(stat_name) + strlen(delta_suffix) + 1]; snprintf(deltaname, sizeof(deltaname), "%s%s", stat_name, delta_suffix); json_object_set_new(js_type, deltaname, - json_integer(st->stats[u].value - st->stats[u].pvalue)); + json_integer(st->stats[u].value - st->stats[u].pvalue)); } } } @@ -287,7 +283,7 @@ json_t *StatsToJSON(const StatsTable *st, uint8_t flags) char deltaname[strlen(stat_name) + strlen(delta_suffix) + 1]; snprintf(deltaname, sizeof(deltaname), "%s%s", stat_name, delta_suffix); json_object_set_new(js_type, deltaname, - json_integer(st->tstats[u].value - st->tstats[u].pvalue)); + json_integer(st->tstats[u].value - st->tstats[u].pvalue)); } } } @@ -338,8 +334,7 @@ static TmEcode JsonStatsLogThreadInit(ThreadVars *t, const void *initdata, void if (unlikely(aft == NULL)) return TM_ECODE_FAILED; - if(initdata == NULL) - { + if (initdata == NULL) { SCLogDebug("Error getting context for EveLogStats. \"initdata\" argument NULL"); goto error_exit; } @@ -407,8 +402,7 @@ static OutputInitResult OutputStatsLogInitSub(ConfNode *conf, OutputCtx *parent_ if (unlikely(stats_ctx == NULL)) return result; - if (stats_decoder_events && - strcmp(stats_decoder_events_prefix, "decoder") == 0) { + if (stats_decoder_events && strcmp(stats_decoder_events_prefix, "decoder") == 0) { SCLogWarning("eve.stats will not display " "all decoder events correctly. See ticket #2225. Set a prefix in " "stats.decoder-events-prefix."); @@ -464,9 +458,10 @@ static OutputInitResult OutputStatsLogInitSub(ConfNode *conf, OutputCtx *parent_ return result; } -void JsonStatsLogRegister(void) { +void JsonStatsLogRegister(void) +{ /* register as child of eve-log */ - OutputRegisterStatsSubModule(LOGGER_JSON_STATS, "eve-log", MODULE_NAME, - "eve-log.stats", OutputStatsLogInitSub, JsonStatsLogger, - JsonStatsLogThreadInit, JsonStatsLogThreadDeinit, NULL); + OutputRegisterStatsSubModule(LOGGER_JSON_STATS, "eve-log", MODULE_NAME, "eve-log.stats", + OutputStatsLogInitSub, JsonStatsLogger, JsonStatsLogThreadInit, + JsonStatsLogThreadDeinit, NULL); } diff --git a/src/output-json-stats.h b/src/output-json-stats.h index 9b96d5001298..80f5cc2430d0 100644 --- a/src/output-json-stats.h +++ b/src/output-json-stats.h @@ -26,9 +26,9 @@ #include "output-stats.h" -#define JSON_STATS_TOTALS (1<<0) -#define JSON_STATS_THREADS (1<<1) -#define JSON_STATS_DELTAS (1<<2) +#define JSON_STATS_TOTALS (1 << 0) +#define JSON_STATS_THREADS (1 << 1) +#define JSON_STATS_DELTAS (1 << 2) json_t *StatsToJSON(const StatsTable *st, uint8_t flags); TmEcode OutputEngineStatsReloadTime(json_t **jdata); diff --git a/src/output-json-tftp.c b/src/output-json-tftp.c index a0bc9ee1809e..0fb9def19f06 100644 --- a/src/output-json-tftp.c +++ b/src/output-json-tftp.c @@ -48,8 +48,8 @@ #include "rust.h" -static int JsonTFTPLogger(ThreadVars *tv, void *thread_data, - const Packet *p, Flow *f, void *state, void *tx, uint64_t tx_id) +static int JsonTFTPLogger(ThreadVars *tv, void *thread_data, const Packet *p, Flow *f, void *state, + void *tx, uint64_t tx_id) { OutputJsonThreadCtx *thread = thread_data; @@ -72,8 +72,7 @@ static int JsonTFTPLogger(ThreadVars *tv, void *thread_data, return TM_ECODE_FAILED; } -static OutputInitResult OutputTFTPLogInitSub(ConfNode *conf, - OutputCtx *parent_ctx) +static OutputInitResult OutputTFTPLogInitSub(ConfNode *conf, OutputCtx *parent_ctx) { AppLayerParserRegisterLogger(IPPROTO_UDP, ALPROTO_TFTP); return OutputJsonLogInitSub(conf, parent_ctx); diff --git a/src/output-json-tls.c b/src/output-json-tls.c index 7460a32f2574..2eec132fb1d2 100644 --- a/src/output-json-tls.c +++ b/src/output-json-tls.c @@ -52,30 +52,30 @@ SC_ATOMIC_EXTERN(unsigned int, cert_id); -#define MODULE_NAME "LogTlsLog" +#define MODULE_NAME "LogTlsLog" #define DEFAULT_LOG_FILENAME "tls.json" -#define LOG_TLS_DEFAULT 0 -#define LOG_TLS_EXTENDED (1 << 0) -#define LOG_TLS_CUSTOM (1 << 1) -#define LOG_TLS_SESSION_RESUMPTION (1 << 2) - -#define LOG_TLS_FIELD_VERSION (1 << 0) -#define LOG_TLS_FIELD_SUBJECT (1 << 1) -#define LOG_TLS_FIELD_ISSUER (1 << 2) -#define LOG_TLS_FIELD_SERIAL (1 << 3) -#define LOG_TLS_FIELD_FINGERPRINT (1 << 4) -#define LOG_TLS_FIELD_NOTBEFORE (1 << 5) -#define LOG_TLS_FIELD_NOTAFTER (1 << 6) -#define LOG_TLS_FIELD_SNI (1 << 7) -#define LOG_TLS_FIELD_CERTIFICATE (1 << 8) -#define LOG_TLS_FIELD_CHAIN (1 << 9) -#define LOG_TLS_FIELD_SESSION_RESUMED (1 << 10) -#define LOG_TLS_FIELD_JA3 (1 << 11) -#define LOG_TLS_FIELD_JA3S (1 << 12) -#define LOG_TLS_FIELD_CLIENT (1 << 13) /**< client fields (issuer, subject, etc) */ -#define LOG_TLS_FIELD_CLIENT_CERT (1 << 14) -#define LOG_TLS_FIELD_CLIENT_CHAIN (1 << 15) +#define LOG_TLS_DEFAULT 0 +#define LOG_TLS_EXTENDED (1 << 0) +#define LOG_TLS_CUSTOM (1 << 1) +#define LOG_TLS_SESSION_RESUMPTION (1 << 2) + +#define LOG_TLS_FIELD_VERSION (1 << 0) +#define LOG_TLS_FIELD_SUBJECT (1 << 1) +#define LOG_TLS_FIELD_ISSUER (1 << 2) +#define LOG_TLS_FIELD_SERIAL (1 << 3) +#define LOG_TLS_FIELD_FINGERPRINT (1 << 4) +#define LOG_TLS_FIELD_NOTBEFORE (1 << 5) +#define LOG_TLS_FIELD_NOTAFTER (1 << 6) +#define LOG_TLS_FIELD_SNI (1 << 7) +#define LOG_TLS_FIELD_CERTIFICATE (1 << 8) +#define LOG_TLS_FIELD_CHAIN (1 << 9) +#define LOG_TLS_FIELD_SESSION_RESUMED (1 << 10) +#define LOG_TLS_FIELD_JA3 (1 << 11) +#define LOG_TLS_FIELD_JA3S (1 << 12) +#define LOG_TLS_FIELD_CLIENT (1 << 13) /**< client fields (issuer, subject, etc) */ +#define LOG_TLS_FIELD_CLIENT_CERT (1 << 14) +#define LOG_TLS_FIELD_CLIENT_CHAIN (1 << 15) typedef struct { const char *name; @@ -98,7 +98,6 @@ typedef struct OutputTlsCtx_ { OutputJsonCtx *eve_ctx; } OutputTlsCtx; - typedef struct JsonTlsLogThread_ { OutputTlsCtx *tlslog_ctx; OutputJsonThreadCtx *ctx; @@ -107,16 +106,14 @@ typedef struct JsonTlsLogThread_ { static void JsonTlsLogSubject(JsonBuilder *js, SSLState *ssl_state) { if (ssl_state->server_connp.cert0_subject) { - jb_set_string(js, "subject", - ssl_state->server_connp.cert0_subject); + jb_set_string(js, "subject", ssl_state->server_connp.cert0_subject); } } static void JsonTlsLogIssuer(JsonBuilder *js, SSLState *ssl_state) { if (ssl_state->server_connp.cert0_issuerdn) { - jb_set_string(js, "issuerdn", - ssl_state->server_connp.cert0_issuerdn); + jb_set_string(js, "issuerdn", ssl_state->server_connp.cert0_issuerdn); } } @@ -126,9 +123,9 @@ static void JsonTlsLogSessionResumed(JsonBuilder *js, SSLState *ssl_state) /* Only log a session as 'resumed' if a certificate has not been seen, and the session is not TLSv1.3 or later. */ if ((ssl_state->server_connp.cert0_issuerdn == NULL && - ssl_state->server_connp.cert0_subject == NULL) && - (ssl_state->flags & SSL_AL_FLAG_STATE_SERVER_HELLO) && - ((ssl_state->flags & SSL_AL_FLAG_LOG_WITHOUT_CERT) == 0)) { + ssl_state->server_connp.cert0_subject == NULL) && + (ssl_state->flags & SSL_AL_FLAG_STATE_SERVER_HELLO) && + ((ssl_state->flags & SSL_AL_FLAG_LOG_WITHOUT_CERT) == 0)) { jb_set_bool(js, "session_resumed", true); } } @@ -137,24 +134,21 @@ static void JsonTlsLogSessionResumed(JsonBuilder *js, SSLState *ssl_state) static void JsonTlsLogFingerprint(JsonBuilder *js, SSLState *ssl_state) { if (ssl_state->server_connp.cert0_fingerprint) { - jb_set_string(js, "fingerprint", - ssl_state->server_connp.cert0_fingerprint); + jb_set_string(js, "fingerprint", ssl_state->server_connp.cert0_fingerprint); } } static void JsonTlsLogSni(JsonBuilder *js, SSLState *ssl_state) { if (ssl_state->client_connp.sni) { - jb_set_string(js, "sni", - ssl_state->client_connp.sni); + jb_set_string(js, "sni", ssl_state->client_connp.sni); } } static void JsonTlsLogSerial(JsonBuilder *js, SSLState *ssl_state) { if (ssl_state->server_connp.cert0_serial) { - jb_set_string(js, "serial", - ssl_state->server_connp.cert0_serial); + jb_set_string(js, "serial", ssl_state->server_connp.cert0_serial); } } @@ -182,8 +176,7 @@ static void JsonTlsLogNotAfter(JsonBuilder *js, SSLState *ssl_state) static void JsonTlsLogJa3Hash(JsonBuilder *js, SSLState *ssl_state) { if (ssl_state->client_connp.ja3_hash != NULL) { - jb_set_string(js, "hash", - ssl_state->client_connp.ja3_hash); + jb_set_string(js, "hash", ssl_state->client_connp.ja3_hash); } } @@ -191,8 +184,7 @@ static void JsonTlsLogJa3String(JsonBuilder *js, SSLState *ssl_state) { if ((ssl_state->client_connp.ja3_str != NULL) && ssl_state->client_connp.ja3_str->data != NULL) { - jb_set_string(js, "string", - ssl_state->client_connp.ja3_str->data); + jb_set_string(js, "string", ssl_state->client_connp.ja3_str->data); } } @@ -213,8 +205,7 @@ static void JsonTlsLogJa3(JsonBuilder *js, SSLState *ssl_state) static void JsonTlsLogJa3SHash(JsonBuilder *js, SSLState *ssl_state) { if (ssl_state->server_connp.ja3_hash != NULL) { - jb_set_string(js, "hash", - ssl_state->server_connp.ja3_hash); + jb_set_string(js, "hash", ssl_state->server_connp.ja3_hash); } } @@ -222,8 +213,7 @@ static void JsonTlsLogJa3SString(JsonBuilder *js, SSLState *ssl_state) { if ((ssl_state->server_connp.ja3_str != NULL) && ssl_state->server_connp.ja3_str->data != NULL) { - jb_set_string(js, "string", - ssl_state->server_connp.ja3_str->data); + jb_set_string(js, "string", ssl_state->server_connp.ja3_str->data); } } @@ -326,8 +316,7 @@ void JsonTlsLogJSONBasic(JsonBuilder *js, SSLState *ssl_state) JsonTlsLogSessionResumed(js, ssl_state); } -static void JsonTlsLogJSONCustom(OutputTlsCtx *tls_ctx, JsonBuilder *js, - SSLState *ssl_state) +static void JsonTlsLogJSONCustom(OutputTlsCtx *tls_ctx, JsonBuilder *js, SSLState *ssl_state) { /* tls subject */ if (tls_ctx->fields & LOG_TLS_FIELD_SUBJECT) @@ -437,8 +426,8 @@ bool JsonTlsLogJSONExtended(void *vtx, JsonBuilder *tjs) return r; } -static int JsonTlsLogger(ThreadVars *tv, void *thread_data, const Packet *p, - Flow *f, void *state, void *txptr, uint64_t tx_id) +static int JsonTlsLogger(ThreadVars *tv, void *thread_data, const Packet *p, Flow *f, void *state, + void *txptr, uint64_t tx_id) { JsonTlsLogThread *aft = (JsonTlsLogThread *)thread_data; OutputTlsCtx *tls_ctx = aft->tlslog_ctx; @@ -449,9 +438,9 @@ static int JsonTlsLogger(ThreadVars *tv, void *thread_data, const Packet *p, } if ((ssl_state->server_connp.cert0_issuerdn == NULL || - ssl_state->server_connp.cert0_subject == NULL) && + ssl_state->server_connp.cert0_subject == NULL) && ((ssl_state->flags & SSL_AL_FLAG_SESSION_RESUMED) == 0 || - (tls_ctx->flags & LOG_TLS_SESSION_RESUMPTION) == 0) && + (tls_ctx->flags & LOG_TLS_SESSION_RESUMPTION) == 0) && ((ssl_state->flags & SSL_AL_FLAG_LOG_WITHOUT_CERT) == 0)) { return 0; } @@ -479,8 +468,7 @@ static int JsonTlsLogger(ThreadVars *tv, void *thread_data, const Packet *p, /* print original application level protocol when it have been changed because of STARTTLS, HTTP CONNECT, or similar. */ if (f->alproto_orig != ALPROTO_UNKNOWN) { - jb_set_string(js, "from_proto", - AppLayerGetProtoName(f->alproto_orig)); + jb_set_string(js, "from_proto", AppLayerGetProtoName(f->alproto_orig)); } /* Close the tls object. */ @@ -558,11 +546,10 @@ static OutputTlsCtx *OutputTlsInitCtx(ConfNode *conf) if (custom) { tls_ctx->flags = LOG_TLS_CUSTOM; ConfNode *field; - TAILQ_FOREACH(field, &custom->head, next) - { + TAILQ_FOREACH (field, &custom->head, next) { bool valid = false; TlsFields *valid_fields = tls_fields; - for ( ; valid_fields->name != NULL; valid_fields++) { + for (; valid_fields->name != NULL; valid_fields++) { if (strcasecmp(field->val, valid_fields->name) == 0) { tls_ctx->fields |= valid_fields->flag; SCLogDebug("enabled %s", field->val); @@ -581,15 +568,13 @@ static OutputTlsCtx *OutputTlsInitCtx(ConfNode *conf) tls_ctx->flags |= LOG_TLS_SESSION_RESUMPTION; } - if ((tls_ctx->fields & LOG_TLS_FIELD_JA3) && - Ja3IsDisabled("fields")) { + if ((tls_ctx->fields & LOG_TLS_FIELD_JA3) && Ja3IsDisabled("fields")) { /* JA3 is disabled, so don't log any JA3 fields */ tls_ctx->fields &= ~LOG_TLS_FIELD_JA3; tls_ctx->fields &= ~LOG_TLS_FIELD_JA3S; } - if ((tls_ctx->fields & LOG_TLS_FIELD_CERTIFICATE) && - (tls_ctx->fields & LOG_TLS_FIELD_CHAIN)) { + if ((tls_ctx->fields & LOG_TLS_FIELD_CERTIFICATE) && (tls_ctx->fields & LOG_TLS_FIELD_CHAIN)) { SCLogWarning("Both 'certificate' and 'chain' contains the top " "certificate, so only one of them should be enabled " "at a time"); @@ -639,8 +624,7 @@ static OutputInitResult OutputTlsLogInitSub(ConfNode *conf, OutputCtx *parent_ct tls_ctx->eve_ctx = ojc; - if ((tls_ctx->fields & LOG_TLS_FIELD_CERTIFICATE) && - (tls_ctx->fields & LOG_TLS_FIELD_CHAIN)) { + if ((tls_ctx->fields & LOG_TLS_FIELD_CERTIFICATE) && (tls_ctx->fields & LOG_TLS_FIELD_CHAIN)) { SCLogWarning("Both 'certificate' and 'chain' contains the top " "certificate, so only one of them should be enabled " "at a time"); @@ -656,7 +640,7 @@ static OutputInitResult OutputTlsLogInitSub(ConfNode *conf, OutputCtx *parent_ct return result; } -void JsonTlsLogRegister (void) +void JsonTlsLogRegister(void) { /* register as child of eve-log */ OutputRegisterTxSubModuleWithProgress(LOGGER_JSON_TX, "eve-log", "JsonTlsLog", "eve-log.tls", diff --git a/src/output-json.c b/src/output-json.c index 1dd2f948aba3..223a03d31f99 100644 --- a/src/output-json.c +++ b/src/output-json.c @@ -76,7 +76,7 @@ #include "suricata-plugin.h" #define DEFAULT_LOG_FILENAME "eve.json" -#define MODULE_NAME "OutputJSON" +#define MODULE_NAME "OutputJSON" #define MAX_JSON_SIZE 2048 @@ -91,7 +91,7 @@ static size_t traffic_label_prefix_len = 0; const JsonAddrInfo json_addr_info_zero; -void OutputJsonRegister (void) +void OutputJsonRegister(void) { OutputRegisterModule(MODULE_NAME, "eve-log", OutputJsonInitCtx); @@ -106,21 +106,19 @@ void OutputJsonRegister (void) json_t *SCJsonString(const char *val) { - if (val == NULL){ + if (val == NULL) { return NULL; } - json_t * retval = json_string(val); - char retbuf[MAX_JSON_SIZE] = {0}; + json_t *retval = json_string(val); + char retbuf[MAX_JSON_SIZE] = { 0 }; if (retval == NULL) { uint32_t u = 0; uint32_t offset = 0; for (u = 0; u < strlen(val); u++) { if (isprint(val[u])) { - PrintBufferData(retbuf, &offset, MAX_JSON_SIZE-1, "%c", - val[u]); + PrintBufferData(retbuf, &offset, MAX_JSON_SIZE - 1, "%c", val[u]); } else { - PrintBufferData(retbuf, &offset, MAX_JSON_SIZE-1, - "\\x%02X", val[u]); + PrintBufferData(retbuf, &offset, MAX_JSON_SIZE - 1, "\\x%02X", val[u]); } } retbuf[offset] = '\0'; @@ -210,24 +208,20 @@ static void EveAddPacketVars(const Packet *p, JsonBuilder *js_vars) if (pv->key != NULL) { uint32_t offset = 0; uint8_t keybuf[pv->key_len + 1]; - PrintStringsToBuffer(keybuf, &offset, - sizeof(keybuf), - pv->key, pv->key_len); + PrintStringsToBuffer(keybuf, &offset, sizeof(keybuf), pv->key, pv->key_len); uint32_t len = pv->value_len; uint8_t printable_buf[len + 1]; offset = 0; - PrintStringsToBuffer(printable_buf, &offset, - sizeof(printable_buf), - pv->value, pv->value_len); + PrintStringsToBuffer( + printable_buf, &offset, sizeof(printable_buf), pv->value, pv->value_len); jb_set_string(js_vars, (char *)keybuf, (char *)printable_buf); } else { const char *varname = VarNameStoreLookupById(pv->id, VAR_TYPE_PKT_VAR); uint32_t len = pv->value_len; uint8_t printable_buf[len + 1]; uint32_t offset = 0; - PrintStringsToBuffer(printable_buf, &offset, - sizeof(printable_buf), - pv->value, pv->value_len); + PrintStringsToBuffer( + printable_buf, &offset, sizeof(printable_buf), pv->value, pv->value_len); jb_set_string(js_vars, varname, (char *)printable_buf); } jb_close(js_vars); @@ -270,8 +264,7 @@ static void EveAddFlowVars(const Flow *f, JsonBuilder *js_root, JsonBuilder **js if (gv->type == DETECT_FLOWVAR || gv->type == DETECT_FLOWINT) { FlowVar *fv = (FlowVar *)gv; if (fv->datatype == FLOWVAR_TYPE_STR && fv->key == NULL) { - const char *varname = VarNameStoreLookupById(fv->idx, - VAR_TYPE_FLOW_VAR); + const char *varname = VarNameStoreLookupById(fv->idx, VAR_TYPE_FLOW_VAR); if (varname) { if (js_flowvars == NULL) { js_flowvars = jb_new_array(); @@ -282,8 +275,7 @@ static void EveAddFlowVars(const Flow *f, JsonBuilder *js_root, JsonBuilder **js uint32_t len = fv->data.fv_str.value_len; uint8_t printable_buf[len + 1]; uint32_t offset = 0; - PrintStringsToBuffer(printable_buf, &offset, - sizeof(printable_buf), + PrintStringsToBuffer(printable_buf, &offset, sizeof(printable_buf), fv->data.fv_str.value, fv->data.fv_str.value_len); jb_start_object(js_flowvars); @@ -299,23 +291,19 @@ static void EveAddFlowVars(const Flow *f, JsonBuilder *js_root, JsonBuilder **js uint8_t keybuf[fv->keylen + 1]; uint32_t offset = 0; - PrintStringsToBuffer(keybuf, &offset, - sizeof(keybuf), - fv->key, fv->keylen); + PrintStringsToBuffer(keybuf, &offset, sizeof(keybuf), fv->key, fv->keylen); uint32_t len = fv->data.fv_str.value_len; uint8_t printable_buf[len + 1]; offset = 0; - PrintStringsToBuffer(printable_buf, &offset, - sizeof(printable_buf), + PrintStringsToBuffer(printable_buf, &offset, sizeof(printable_buf), fv->data.fv_str.value, fv->data.fv_str.value_len); jb_start_object(js_flowvars); jb_set_string(js_flowvars, (const char *)keybuf, (char *)printable_buf); jb_close(js_flowvars); } else if (fv->datatype == FLOWVAR_TYPE_INT) { - const char *varname = VarNameStoreLookupById(fv->idx, - VAR_TYPE_FLOW_INT); + const char *varname = VarNameStoreLookupById(fv->idx, VAR_TYPE_FLOW_INT); if (varname) { if (js_flowints == NULL) { js_flowints = jb_new_object(); @@ -324,12 +312,10 @@ static void EveAddFlowVars(const Flow *f, JsonBuilder *js_root, JsonBuilder **js } jb_set_uint(js_flowints, varname, fv->data.fv_int.value); } - } } else if (gv->type == DETECT_FLOWBITS) { FlowBit *fb = (FlowBit *)gv; - const char *varname = VarNameStoreLookupById(fb->idx, - VAR_TYPE_FLOW_BIT); + const char *varname = VarNameStoreLookupById(fb->idx, VAR_TYPE_FLOW_BIT); if (varname) { if (SCStringHasPrefix(varname, TRAFFIC_ID_PREFIX)) { if (js_traffic_id == NULL) { @@ -416,8 +402,8 @@ void EveAddMetadata(const Packet *p, const Flow *f, JsonBuilder *js) } } -void EveAddCommonOptions(const OutputJsonCommonSettings *cfg, - const Packet *p, const Flow *f, JsonBuilder *js) +void EveAddCommonOptions( + const OutputJsonCommonSettings *cfg, const Packet *p, const Flow *f, JsonBuilder *js) { if (cfg->include_metadata) { EveAddMetadata(p, f, js); @@ -479,21 +465,17 @@ void EveTcpFlags(const uint8_t flags, JsonBuilder *js) void JsonAddrInfoInit(const Packet *p, enum OutputJsonLogDirection dir, JsonAddrInfo *addr) { - char srcip[46] = {0}, dstip[46] = {0}; + char srcip[46] = { 0 }, dstip[46] = { 0 }; Port sp, dp; switch (dir) { case LOG_DIR_PACKET: if (PKT_IS_IPV4(p)) { - PrintInet(AF_INET, (const void *)GET_IPV4_SRC_ADDR_PTR(p), - srcip, sizeof(srcip)); - PrintInet(AF_INET, (const void *)GET_IPV4_DST_ADDR_PTR(p), - dstip, sizeof(dstip)); + PrintInet(AF_INET, (const void *)GET_IPV4_SRC_ADDR_PTR(p), srcip, sizeof(srcip)); + PrintInet(AF_INET, (const void *)GET_IPV4_DST_ADDR_PTR(p), dstip, sizeof(dstip)); } else if (PKT_IS_IPV6(p)) { - PrintInet(AF_INET6, (const void *)GET_IPV6_SRC_ADDR(p), - srcip, sizeof(srcip)); - PrintInet(AF_INET6, (const void *)GET_IPV6_DST_ADDR(p), - dstip, sizeof(dstip)); + PrintInet(AF_INET6, (const void *)GET_IPV6_SRC_ADDR(p), srcip, sizeof(srcip)); + PrintInet(AF_INET6, (const void *)GET_IPV6_DST_ADDR(p), dstip, sizeof(dstip)); } else { /* Not an IP packet so don't do anything */ return; @@ -505,29 +487,25 @@ void JsonAddrInfoInit(const Packet *p, enum OutputJsonLogDirection dir, JsonAddr case LOG_DIR_FLOW_TOSERVER: if ((PKT_IS_TOSERVER(p))) { if (PKT_IS_IPV4(p)) { - PrintInet(AF_INET, (const void *)GET_IPV4_SRC_ADDR_PTR(p), - srcip, sizeof(srcip)); - PrintInet(AF_INET, (const void *)GET_IPV4_DST_ADDR_PTR(p), - dstip, sizeof(dstip)); + PrintInet( + AF_INET, (const void *)GET_IPV4_SRC_ADDR_PTR(p), srcip, sizeof(srcip)); + PrintInet( + AF_INET, (const void *)GET_IPV4_DST_ADDR_PTR(p), dstip, sizeof(dstip)); } else if (PKT_IS_IPV6(p)) { - PrintInet(AF_INET6, (const void *)GET_IPV6_SRC_ADDR(p), - srcip, sizeof(srcip)); - PrintInet(AF_INET6, (const void *)GET_IPV6_DST_ADDR(p), - dstip, sizeof(dstip)); + PrintInet(AF_INET6, (const void *)GET_IPV6_SRC_ADDR(p), srcip, sizeof(srcip)); + PrintInet(AF_INET6, (const void *)GET_IPV6_DST_ADDR(p), dstip, sizeof(dstip)); } sp = p->sp; dp = p->dp; } else { if (PKT_IS_IPV4(p)) { - PrintInet(AF_INET, (const void *)GET_IPV4_DST_ADDR_PTR(p), - srcip, sizeof(srcip)); - PrintInet(AF_INET, (const void *)GET_IPV4_SRC_ADDR_PTR(p), - dstip, sizeof(dstip)); + PrintInet( + AF_INET, (const void *)GET_IPV4_DST_ADDR_PTR(p), srcip, sizeof(srcip)); + PrintInet( + AF_INET, (const void *)GET_IPV4_SRC_ADDR_PTR(p), dstip, sizeof(dstip)); } else if (PKT_IS_IPV6(p)) { - PrintInet(AF_INET6, (const void *)GET_IPV6_DST_ADDR(p), - srcip, sizeof(srcip)); - PrintInet(AF_INET6, (const void *)GET_IPV6_SRC_ADDR(p), - dstip, sizeof(dstip)); + PrintInet(AF_INET6, (const void *)GET_IPV6_DST_ADDR(p), srcip, sizeof(srcip)); + PrintInet(AF_INET6, (const void *)GET_IPV6_SRC_ADDR(p), dstip, sizeof(dstip)); } sp = p->dp; dp = p->sp; @@ -536,29 +514,25 @@ void JsonAddrInfoInit(const Packet *p, enum OutputJsonLogDirection dir, JsonAddr case LOG_DIR_FLOW_TOCLIENT: if ((PKT_IS_TOCLIENT(p))) { if (PKT_IS_IPV4(p)) { - PrintInet(AF_INET, (const void *)GET_IPV4_SRC_ADDR_PTR(p), - srcip, sizeof(srcip)); - PrintInet(AF_INET, (const void *)GET_IPV4_DST_ADDR_PTR(p), - dstip, sizeof(dstip)); + PrintInet( + AF_INET, (const void *)GET_IPV4_SRC_ADDR_PTR(p), srcip, sizeof(srcip)); + PrintInet( + AF_INET, (const void *)GET_IPV4_DST_ADDR_PTR(p), dstip, sizeof(dstip)); } else if (PKT_IS_IPV6(p)) { - PrintInet(AF_INET6, (const void *)GET_IPV6_SRC_ADDR(p), - srcip, sizeof(srcip)); - PrintInet(AF_INET6, (const void *)GET_IPV6_DST_ADDR(p), - dstip, sizeof(dstip)); + PrintInet(AF_INET6, (const void *)GET_IPV6_SRC_ADDR(p), srcip, sizeof(srcip)); + PrintInet(AF_INET6, (const void *)GET_IPV6_DST_ADDR(p), dstip, sizeof(dstip)); } sp = p->sp; dp = p->dp; } else { if (PKT_IS_IPV4(p)) { - PrintInet(AF_INET, (const void *)GET_IPV4_DST_ADDR_PTR(p), - srcip, sizeof(srcip)); - PrintInet(AF_INET, (const void *)GET_IPV4_SRC_ADDR_PTR(p), - dstip, sizeof(dstip)); + PrintInet( + AF_INET, (const void *)GET_IPV4_DST_ADDR_PTR(p), srcip, sizeof(srcip)); + PrintInet( + AF_INET, (const void *)GET_IPV4_SRC_ADDR_PTR(p), dstip, sizeof(dstip)); } else if (PKT_IS_IPV6(p)) { - PrintInet(AF_INET6, (const void *)GET_IPV6_DST_ADDR(p), - srcip, sizeof(srcip)); - PrintInet(AF_INET6, (const void *)GET_IPV6_SRC_ADDR(p), - dstip, sizeof(dstip)); + PrintInet(AF_INET6, (const void *)GET_IPV6_DST_ADDR(p), srcip, sizeof(srcip)); + PrintInet(AF_INET6, (const void *)GET_IPV6_SRC_ADDR(p), dstip, sizeof(dstip)); } sp = p->dp; dp = p->sp; @@ -592,8 +566,7 @@ void JsonAddrInfoInit(const Packet *p, enum OutputJsonLogDirection dir, JsonAddr #define COMMUNITY_ID_BUF_SIZE 64 -static bool CalculateCommunityFlowIdv4(const Flow *f, - const uint16_t seed, unsigned char *base64buf) +static bool CalculateCommunityFlowIdv4(const Flow *f, const uint16_t seed, unsigned char *base64buf) { struct { uint16_t seed; @@ -635,15 +608,14 @@ static bool CalculateCommunityFlowIdv4(const Flow *f, if (SCSha1HashBuffer((const uint8_t *)&ipv4, sizeof(ipv4), hash, sizeof(hash)) == 1) { strlcpy((char *)base64buf, "1:", COMMUNITY_ID_BUF_SIZE); unsigned long out_len = COMMUNITY_ID_BUF_SIZE - 2; - if (Base64Encode(hash, sizeof(hash), base64buf+2, &out_len) == SC_BASE64_OK) { + if (Base64Encode(hash, sizeof(hash), base64buf + 2, &out_len) == SC_BASE64_OK) { return true; } } return false; } -static bool CalculateCommunityFlowIdv6(const Flow *f, - const uint16_t seed, unsigned char *base64buf) +static bool CalculateCommunityFlowIdv6(const Flow *f, const uint16_t seed, unsigned char *base64buf) { struct { uint16_t seed; @@ -684,7 +656,7 @@ static bool CalculateCommunityFlowIdv6(const Flow *f, if (SCSha1HashBuffer((const uint8_t *)&ipv6, sizeof(ipv6), hash, sizeof(hash)) == 1) { strlcpy((char *)base64buf, "1:", COMMUNITY_ID_BUF_SIZE); unsigned long out_len = COMMUNITY_ID_BUF_SIZE - 2; - if (Base64Encode(hash, sizeof(hash), base64buf+2, &out_len) == SC_BASE64_OK) { + if (Base64Encode(hash, sizeof(hash), base64buf + 2, &out_len) == SC_BASE64_OK) { return true; } } @@ -717,12 +689,12 @@ void CreateEveFlowId(JsonBuilder *js, const Flow *f) } } -static inline void JSONFormatAndAddMACAddr(JsonBuilder *js, const char *key, - uint8_t *val, bool is_array) +static inline void JSONFormatAndAddMACAddr( + JsonBuilder *js, const char *key, uint8_t *val, bool is_array) { char eth_addr[19]; - (void) snprintf(eth_addr, 19, "%02x:%02x:%02x:%02x:%02x:%02x", - val[0], val[1], val[2], val[3], val[4], val[5]); + (void)snprintf(eth_addr, 19, "%02x:%02x:%02x:%02x:%02x:%02x", val[0], val[1], val[2], val[3], + val[4], val[5]); if (is_array) { jb_append_string(js, eth_addr); } else { @@ -737,7 +709,7 @@ typedef struct JSONMACAddrInfo { static int MacSetIterateToJSON(uint8_t *val, MacSetSide side, void *data) { - JSONMACAddrInfo *info = (JSONMACAddrInfo*) data; + JSONMACAddrInfo *info = (JSONMACAddrInfo *)data; if (side == MAC_SET_DST) { JSONFormatAndAddMACAddr(info->dst, NULL, val, true); } else { @@ -902,8 +874,7 @@ int OutputJSONMemBufferCallback(const char *str, size_t size, void *data) int OutputJSONBuffer(json_t *js, LogFileCtx *file_ctx, MemBuffer **buffer) { if (file_ctx->sensor_name) { - json_object_set_new(js, "host", - json_string(file_ctx->sensor_name)); + json_object_set_new(js, "host", json_string(file_ctx->sensor_name)); } if (file_ctx->is_pcap_offline) { @@ -914,13 +885,9 @@ int OutputJSONBuffer(json_t *js, LogFileCtx *file_ctx, MemBuffer **buffer) MemBufferWriteRaw((*buffer), file_ctx->prefix, file_ctx->prefix_len); } - OutputJSONMemBufferWrapper wrapper = { - .buffer = buffer, - .expand_by = JSON_OUTPUT_BUFFER_SIZE - }; + OutputJSONMemBufferWrapper wrapper = { .buffer = buffer, .expand_by = JSON_OUTPUT_BUFFER_SIZE }; - int r = json_dump_callback(js, OutputJSONMemBufferCallback, &wrapper, - file_ctx->json_flags); + int r = json_dump_callback(js, OutputJSONMemBufferCallback, &wrapper, file_ctx->json_flags); if (r != 0) return TM_ECODE_OK; @@ -1051,8 +1018,7 @@ OutputInitResult OutputJsonInitCtx(ConfNode *conf) if (sensor_name != NULL) { SCLogWarning("Found deprecated eve-log setting \"sensor-name\". " "Please set sensor-name globally."); - } - else { + } else { (void)ConfGet("sensor-name", &sensor_name); } @@ -1099,12 +1065,10 @@ OutputInitResult OutputJsonInitCtx(ConfNode *conf) } const char *prefix = ConfNodeLookupChildValue(conf, "prefix"); - if (prefix != NULL) - { + if (prefix != NULL) { SCLogInfo("Using prefix '%s' for JSON messages", prefix); json_ctx->file_ctx->prefix = SCStrdup(prefix); - if (json_ctx->file_ctx->prefix == NULL) - { + if (json_ctx->file_ctx->prefix == NULL) { FatalError("Failed to allocate memory for eve-log.prefix setting."); } json_ctx->file_ctx->prefix_len = strlen(prefix); @@ -1159,9 +1123,7 @@ OutputInitResult OutputJsonInitCtx(ConfNode *conf) } const char *cid_seed = ConfNodeLookupChildValue(conf, "community-id-seed"); if (cid_seed != NULL) { - if (StringParseUint16(&json_ctx->cfg.community_id_seed, - 10, 0, cid_seed) < 0) - { + if (StringParseUint16(&json_ctx->cfg.community_id_seed, 10, 0, cid_seed) < 0) { FatalError("Failed to initialize JSON output, " "invalid community-id-seed: %s", cid_seed); @@ -1179,9 +1141,8 @@ OutputInitResult OutputJsonInitCtx(ConfNode *conf) const char *pcapfile_s = ConfNodeLookupChildValue(conf, "pcap-file"); if (pcapfile_s != NULL && ConfValIsTrue(pcapfile_s)) { - json_ctx->file_ctx->is_pcap_offline = - (RunmodeGetCurrent() == RUNMODE_PCAP_FILE || - RunmodeGetCurrent() == RUNMODE_UNIX_SOCKET); + json_ctx->file_ctx->is_pcap_offline = (RunmodeGetCurrent() == RUNMODE_PCAP_FILE || + RunmodeGetCurrent() == RUNMODE_UNIX_SOCKET); } json_ctx->file_ctx->type = log_filetype; } diff --git a/src/output-json.h b/src/output-json.h index 6fe6c5898d74..0d2affd76d4b 100644 --- a/src/output-json.h +++ b/src/output-json.h @@ -42,7 +42,7 @@ enum OutputJsonLogDirection { LOG_DIR_FLOW_TOSERVER, }; -#define JSON_ADDR_LEN 46 +#define JSON_ADDR_LEN 46 #define JSON_PROTO_LEN 16 /* A struct to contain address info for rendering to JSON. */ @@ -56,8 +56,7 @@ typedef struct JsonAddrInfo_ { extern const JsonAddrInfo json_addr_info_zero; -void JsonAddrInfoInit(const Packet *p, enum OutputJsonLogDirection dir, - JsonAddrInfo *addr); +void JsonAddrInfoInit(const Packet *p, enum OutputJsonLogDirection dir, JsonAddrInfo *addr); /* Suggested output buffer size */ #define JSON_OUTPUT_BUFFER_SIZE 65535 @@ -110,8 +109,8 @@ OutputInitResult OutputJsonLogInitSub(ConfNode *conf, OutputCtx *parent_ctx); TmEcode JsonLogThreadInit(ThreadVars *t, const void *initdata, void **data); TmEcode JsonLogThreadDeinit(ThreadVars *t, void *data); -void EveAddCommonOptions(const OutputJsonCommonSettings *cfg, - const Packet *p, const Flow *f, JsonBuilder *js); +void EveAddCommonOptions( + const OutputJsonCommonSettings *cfg, const Packet *p, const Flow *f, JsonBuilder *js); void EveAddMetadata(const Packet *p, const Flow *f, JsonBuilder *js); int OutputJSONMemBufferCallback(const char *str, size_t size, void *data); diff --git a/src/output-lua.c b/src/output-lua.c index 776cf51b9c9b..8f2c1beaa492 100644 --- a/src/output-lua.c +++ b/src/output-lua.c @@ -82,7 +82,8 @@ static TmEcode LuaLogThreadDeinit(ThreadVars *t, void *data); * * NOTE: The flow (f) also referenced by p->flow is locked. */ -static int LuaTxLogger(ThreadVars *tv, void *thread_data, const Packet *p, Flow *f, void *alstate, void *txptr, uint64_t tx_id) +static int LuaTxLogger(ThreadVars *tv, void *thread_data, const Packet *p, Flow *f, void *alstate, + void *txptr, uint64_t tx_id) { SCEnter(); @@ -115,8 +116,8 @@ static int LuaTxLogger(ThreadVars *tv, void *thread_data, const Packet *p, Flow * Hooks into the Streaming Logger API. Gets called for each chunk of new * streaming data. */ -static int LuaStreamingLogger(ThreadVars *tv, void *thread_data, const Flow *f, - const uint8_t *data, uint32_t data_len, uint64_t tx_id, uint8_t flags) +static int LuaStreamingLogger(ThreadVars *tv, void *thread_data, const Flow *f, const uint8_t *data, + uint32_t data_len, uint64_t tx_id, uint8_t flags) { SCEnter(); @@ -203,7 +204,7 @@ static int LuaPacketLoggerAlerts(ThreadVars *tv, void *thread_data, const Packet LuaStateSetPacketAlert(td->lua_ctx->luastate, (PacketAlert *)pa); /* prepare data to pass to script */ - //lua_newtable(td->lua_ctx->luastate); + // lua_newtable(td->lua_ctx->luastate); int retval = lua_pcall(td->lua_ctx->luastate, 0, 0, 0); if (retval != 0) { @@ -337,8 +338,6 @@ static int LuaFlowLogger(ThreadVars *tv, void *thread_data, Flow *f) return 0; } - - static int LuaStatsLogger(ThreadVars *tv, void *thread_data, const StatsTable *st) { SCEnter(); @@ -388,7 +387,6 @@ static int LuaStatsLogger(ThreadVars *tv, void *thread_data, const StatsTable *s } SCMutexUnlock(&td->lua_ctx->m); return 0; - } typedef struct LogLuaScriptOptions_ { @@ -413,7 +411,8 @@ typedef struct LogLuaScriptOptions_ { * \param options struct to pass script requirements/options back to caller * \retval errcode 0 ok, -1 error */ -static int LuaScriptInit(const char *filename, LogLuaScriptOptions *options) { +static int LuaScriptInit(const char *filename, LogLuaScriptOptions *options) +{ lua_State *luastate = LuaGetState(); if (luastate == NULL) goto error; @@ -444,7 +443,7 @@ static int LuaScriptInit(const char *filename, LogLuaScriptOptions *options) { } lua_pushliteral(luastate, "script_api_ver"); - lua_pushnumber (luastate, 1); + lua_pushnumber(luastate, 1); lua_settable(luastate, -3); if (lua_pcall(luastate, 1, 1, 0) != 0) { @@ -476,15 +475,15 @@ static int LuaScriptInit(const char *filename, LogLuaScriptOptions *options) { SCLogDebug("k='%s', v='%s'", k, v); - if (strcmp(k,"protocol") == 0 && strcmp(v, "http") == 0) + if (strcmp(k, "protocol") == 0 && strcmp(v, "http") == 0) options->alproto = ALPROTO_HTTP1; - else if (strcmp(k,"protocol") == 0 && strcmp(v, "dns") == 0) + else if (strcmp(k, "protocol") == 0 && strcmp(v, "dns") == 0) options->alproto = ALPROTO_DNS; - else if (strcmp(k,"protocol") == 0 && strcmp(v, "tls") == 0) + else if (strcmp(k, "protocol") == 0 && strcmp(v, "tls") == 0) options->alproto = ALPROTO_TLS; - else if (strcmp(k,"protocol") == 0 && strcmp(v, "ssh") == 0) + else if (strcmp(k, "protocol") == 0 && strcmp(v, "ssh") == 0) options->alproto = ALPROTO_SSH; - else if (strcmp(k,"protocol") == 0 && strcmp(v, "smtp") == 0) + else if (strcmp(k, "protocol") == 0 && strcmp(v, "smtp") == 0) options->alproto = ALPROTO_SMTP; else if (strcmp(k, "type") == 0 && strcmp(v, "packet") == 0) options->packet = 1; @@ -590,7 +589,8 @@ static lua_State *LuaScriptSetup(const char *filename) return NULL; } -static void LogLuaSubFree(OutputCtx *oc) { +static void LogLuaSubFree(OutputCtx *oc) +{ if (oc->data) SCFree(oc->data); SCFree(oc); @@ -625,7 +625,7 @@ static OutputInitResult OutputLuaLogInitSub(ConfNode *conf, OutputCtx *parent_ct } char path[PATH_MAX] = ""; - int ret = snprintf(path, sizeof(path),"%s%s%s", dir, strlen(dir) ? "/" : "", conf->val); + int ret = snprintf(path, sizeof(path), "%s%s%s", dir, strlen(dir) ? "/" : "", conf->val); if (ret < 0 || ret == sizeof(path)) { SCLogError("failed to construct lua script path"); goto error; @@ -659,7 +659,7 @@ static void LogLuaMasterFree(OutputCtx *oc) SCFree(oc->data); OutputModule *om, *tom; - TAILQ_FOREACH_SAFE(om, &oc->submodules, entries, tom) { + TAILQ_FOREACH_SAFE (om, &oc->submodules, entries, tom) { SCFree(om); } SCFree(oc); @@ -703,13 +703,13 @@ static OutputInitResult OutputLuaLogInit(ConfNode *conf) /* check the enables scripts and set them up as submodules */ ConfNode *script; - TAILQ_FOREACH(script, &scripts->head, next) { + TAILQ_FOREACH (script, &scripts->head, next) { SCLogInfo("enabling script %s", script->val); LogLuaScriptOptions opts; memset(&opts, 0x00, sizeof(opts)); char path[PATH_MAX] = ""; - snprintf(path, sizeof(path),"%s%s%s", dir, strlen(dir) ? "/" : "", script->val); + snprintf(path, sizeof(path), "%s%s%s", dir, strlen(dir) ? "/" : "", script->val); SCLogDebug("script full path %s", path); int r = LuaScriptInit(path, &opts); @@ -825,7 +825,7 @@ static void OutputLuaLogDoDeinit(LogLuaCtx *lua_ctx) SCLogError("no deinit function in script"); return; } - //LuaPrintStack(luastate); + // LuaPrintStack(luastate); if (lua_pcall(luastate, 0, 0, 0) != 0) { SCLogError("couldn't run script 'deinit' function: %s", lua_tostring(luastate, -1)); @@ -884,14 +884,16 @@ static TmEcode LuaLogThreadDeinit(ThreadVars *t, void *data) return TM_ECODE_OK; } -void LuaLogRegister(void) { +void LuaLogRegister(void) +{ /* register as separate module */ OutputRegisterModule(MODULE_NAME, "lua", OutputLuaLogInit); } #else /* HAVE_LUA */ -void LuaLogRegister (void) { +void LuaLogRegister(void) +{ /* no-op */ } diff --git a/src/output-packet.c b/src/output-packet.c index 98ccf7b6b081..92ea7b50257e 100644 --- a/src/output-packet.c +++ b/src/output-packet.c @@ -52,11 +52,9 @@ typedef struct OutputPacketLogger_ { static OutputPacketLogger *list = NULL; -int OutputRegisterPacketLogger(LoggerId logger_id, const char *name, - PacketLogger LogFunc, PacketLogCondition ConditionFunc, - OutputCtx *output_ctx, ThreadInitFunc ThreadInit, - ThreadDeinitFunc ThreadDeinit, - ThreadExitPrintStatsFunc ThreadExitPrintStats) +int OutputRegisterPacketLogger(LoggerId logger_id, const char *name, PacketLogger LogFunc, + PacketLogCondition ConditionFunc, OutputCtx *output_ctx, ThreadInitFunc ThreadInit, + ThreadDeinitFunc ThreadDeinit, ThreadExitPrintStatsFunc ThreadExitPrintStats) { OutputPacketLogger *op = SCCalloc(1, sizeof(*op)); if (op == NULL) @@ -212,9 +210,8 @@ static uint32_t OutputPacketLoggerGetActiveCount(void) void OutputPacketLoggerRegister(void) { - OutputRegisterRootLogger(OutputPacketLogThreadInit, - OutputPacketLogThreadDeinit, OutputPacketLogExitPrintStats, - OutputPacketLog, OutputPacketLoggerGetActiveCount); + OutputRegisterRootLogger(OutputPacketLogThreadInit, OutputPacketLogThreadDeinit, + OutputPacketLogExitPrintStats, OutputPacketLog, OutputPacketLoggerGetActiveCount); } void OutputPacketShutdown(void) diff --git a/src/output-packet.h b/src/output-packet.h index 1e468669f137..c10cb82de253 100644 --- a/src/output-packet.h +++ b/src/output-packet.h @@ -34,9 +34,9 @@ typedef int (*PacketLogger)(ThreadVars *, void *thread_data, const Packet *); */ typedef bool (*PacketLogCondition)(ThreadVars *, void *thread_data, const Packet *); -int OutputRegisterPacketLogger(LoggerId logger_id, const char *name, - PacketLogger LogFunc, PacketLogCondition ConditionFunc, OutputCtx *, - ThreadInitFunc, ThreadDeinitFunc, ThreadExitPrintStatsFunc); +int OutputRegisterPacketLogger(LoggerId logger_id, const char *name, PacketLogger LogFunc, + PacketLogCondition ConditionFunc, OutputCtx *, ThreadInitFunc, ThreadDeinitFunc, + ThreadExitPrintStatsFunc); void OutputPacketLoggerRegister(void); diff --git a/src/output-stats.c b/src/output-stats.c index b59432bac4a2..8c27b4dc9076 100644 --- a/src/output-stats.c +++ b/src/output-stats.c @@ -49,10 +49,9 @@ typedef struct OutputStatsLogger_ { static OutputStatsLogger *list = NULL; -int OutputRegisterStatsLogger(const char *name, StatsLogger LogFunc, - OutputCtx *output_ctx, ThreadInitFunc ThreadInit, - ThreadDeinitFunc ThreadDeinit, - ThreadExitPrintStatsFunc ThreadExitPrintStats) +int OutputRegisterStatsLogger(const char *name, StatsLogger LogFunc, OutputCtx *output_ctx, + ThreadInitFunc ThreadInit, ThreadDeinitFunc ThreadDeinit, + ThreadExitPrintStatsFunc ThreadExitPrintStats) { OutputStatsLogger *op = SCCalloc(1, sizeof(*op)); if (op == NULL) @@ -186,7 +185,7 @@ static void OutputStatsLogExitPrintStats(ThreadVars *tv, void *thread_data) } } -void TmModuleStatsLoggerRegister (void) +void TmModuleStatsLoggerRegister(void) { tmm_modules[TMM_STATSLOGGER].name = "__stats_logger__"; tmm_modules[TMM_STATSLOGGER].ThreadInit = OutputStatsLogThreadInit; diff --git a/src/output-stats.h b/src/output-stats.h index f6fc6a8b2716..1c18e5a66d8e 100644 --- a/src/output-stats.h +++ b/src/output-stats.h @@ -37,10 +37,10 @@ typedef struct StatsRecord_ { } StatsRecord; typedef struct StatsTable_ { - StatsRecord *stats; /**< array of global stats, indexed by counters gid */ - StatsRecord *tstats; /**< array of arrays with per thread stats */ - uint32_t nstats; /**< size in records of 'stats' */ - uint32_t ntstats; /**< number of threads for which tstats stores stats */ + StatsRecord *stats; /**< array of global stats, indexed by counters gid */ + StatsRecord *tstats; /**< array of arrays with per thread stats */ + uint32_t nstats; /**< size in records of 'stats' */ + uint32_t ntstats; /**< number of threads for which tstats stores stats */ time_t start_time; struct timeval ts; } StatsTable; @@ -49,11 +49,11 @@ TmEcode OutputStatsLog(ThreadVars *tv, void *thread_data, StatsTable *st); typedef int (*StatsLogger)(ThreadVars *, void *thread_data, const StatsTable *); -int OutputRegisterStatsLogger(const char *name, StatsLogger LogFunc, - OutputCtx *, ThreadInitFunc ThreadInit, ThreadDeinitFunc ThreadDeinit, - ThreadExitPrintStatsFunc ThreadExitPrintStats); +int OutputRegisterStatsLogger(const char *name, StatsLogger LogFunc, OutputCtx *, + ThreadInitFunc ThreadInit, ThreadDeinitFunc ThreadDeinit, + ThreadExitPrintStatsFunc ThreadExitPrintStats); -void TmModuleStatsLoggerRegister (void); +void TmModuleStatsLoggerRegister(void); int OutputStatsLoggersRegistered(void); diff --git a/src/output-streaming.c b/src/output-streaming.c index 75ee211022f6..7fc0c137e08c 100644 --- a/src/output-streaming.c +++ b/src/output-streaming.c @@ -61,11 +61,9 @@ typedef struct OutputStreamingLogger_ { static OutputStreamingLogger *list = NULL; -int OutputRegisterStreamingLogger(LoggerId id, const char *name, - StreamingLogger LogFunc, OutputCtx *output_ctx, - enum OutputStreamingType type, ThreadInitFunc ThreadInit, - ThreadDeinitFunc ThreadDeinit, - ThreadExitPrintStatsFunc ThreadExitPrintStats) +int OutputRegisterStreamingLogger(LoggerId id, const char *name, StreamingLogger LogFunc, + OutputCtx *output_ctx, enum OutputStreamingType type, ThreadInitFunc ThreadInit, + ThreadDeinitFunc ThreadDeinit, ThreadExitPrintStatsFunc ThreadExitPrintStats) { OutputStreamingLogger *op = SCCalloc(1, sizeof(*op)); if (op == NULL) @@ -105,7 +103,8 @@ typedef struct StreamerCallbackData_ { enum OutputStreamingType type; } StreamerCallbackData; -static int Streamer(void *cbdata, Flow *f, const uint8_t *data, uint32_t data_len, uint64_t tx_id, uint8_t flags) +static int Streamer(void *cbdata, Flow *f, const uint8_t *data, uint32_t data_len, uint64_t tx_id, + uint8_t flags) { StreamerCallbackData *streamer_cbdata = (StreamerCallbackData *)cbdata; DEBUG_VALIDATE_BUG_ON(streamer_cbdata == NULL); @@ -182,7 +181,7 @@ static int HttpBodyIterator(Flow *f, int close, void *cbdata, uint8_t iflags) } SCLogDebug("tx %p", tx); - HtpTxUserData *htud = (HtpTxUserData *) htp_tx_get_user_data(tx); + HtpTxUserData *htud = (HtpTxUserData *)htp_tx_get_user_data(tx); if (htud != NULL) { SCLogDebug("htud %p", htud); HtpBody *body = NULL; @@ -206,7 +205,7 @@ static int HttpBodyIterator(Flow *f, int close, void *cbdata, uint8_t iflags) // for each chunk HtpBodyChunk *chunk = body->first; - for ( ; chunk != NULL; chunk = chunk->next) { + for (; chunk != NULL; chunk = chunk->next) { if (chunk->logged) { SCLogDebug("logged %d", chunk->logged); continue; @@ -227,7 +226,7 @@ static int HttpBodyIterator(Flow *f, int close, void *cbdata, uint8_t iflags) // invoke Streamer Streamer(cbdata, f, data, data_len, tx_id, flags); - //PrintRawDataFp(stdout, data, data_len); + // PrintRawDataFp(stdout, data, data_len); chunk->logged = 1; tx_logged = 1; } @@ -236,9 +235,9 @@ static int HttpBodyIterator(Flow *f, int close, void *cbdata, uint8_t iflags) /* if we need to close we need to invoke the Streamer for sure. If we * logged no chunks, we call the Streamer with NULL data so it can * close up. */ - if (tx_logged == 0 && (close||tx_done)) { + if (tx_logged == 0 && (close || tx_done)) { Streamer(cbdata, f, NULL, 0, tx_id, - iflags|OUTPUT_STREAMING_FLAG_CLOSE|OUTPUT_STREAMING_FLAG_TRANSACTION); + iflags | OUTPUT_STREAMING_FLAG_CLOSE | OUTPUT_STREAMING_FLAG_TRANSACTION); } } } @@ -264,8 +263,8 @@ static int StreamLogFunc( return 0; } -static int TcpDataLogger (Flow *f, TcpSession *ssn, TcpStream *stream, - bool eof, uint8_t iflags, void *streamer_cbdata) +static int TcpDataLogger(Flow *f, TcpSession *ssn, TcpStream *stream, bool eof, uint8_t iflags, + void *streamer_cbdata) { uint8_t flags = iflags; uint64_t progress = STREAM_LOG_PROGRESS(stream); @@ -274,9 +273,7 @@ static int TcpDataLogger (Flow *f, TcpSession *ssn, TcpStream *stream, flags |= OUTPUT_STREAMING_FLAG_OPEN; struct StreamLogData log_data = { flags, streamer_cbdata, f }; - StreamReassembleLog(ssn, stream, - StreamLogFunc, &log_data, - progress, &progress, eof); + StreamReassembleLog(ssn, stream, StreamLogFunc, &log_data, progress, &progress, eof); if (progress > STREAM_LOG_PROGRESS(stream)) { uint32_t slide = progress - STREAM_LOG_PROGRESS(stream); @@ -284,7 +281,7 @@ static int TcpDataLogger (Flow *f, TcpSession *ssn, TcpStream *stream, } if (eof) { - Streamer(streamer_cbdata, f, NULL, 0, 0, flags|OUTPUT_STREAMING_FLAG_CLOSE); + Streamer(streamer_cbdata, f, NULL, 0, 0, flags | OUTPUT_STREAMING_FLAG_CLOSE); } return 0; } @@ -303,14 +300,14 @@ static TmEcode OutputStreamingLog(ThreadVars *tv, Packet *p, void *thread_data) OutputStreamingLogger *logger = list; OutputLoggerThreadStore *store = op_thread_data->store; - StreamerCallbackData streamer_cbdata = { logger, store, tv, p , 0}; + StreamerCallbackData streamer_cbdata = { logger, store, tv, p, 0 }; DEBUG_VALIDATE_BUG_ON(logger == NULL && store != NULL); DEBUG_VALIDATE_BUG_ON(logger != NULL && store == NULL); DEBUG_VALIDATE_BUG_ON(logger == NULL && store == NULL); uint8_t flags = 0; - Flow * const f = p->flow; + Flow *const f = p->flow; /* no flow, no streaming */ if (f == NULL) { @@ -331,19 +328,20 @@ static TmEcode OutputStreamingLog(ThreadVars *tv, Packet *p, void *thread_data) } } - if (op_thread_data->loggers & (1<loggers & (1 << STREAMING_TCP_DATA)) { TcpSession *ssn = f->protoctx; if (ssn) { int close = (ssn->state >= TCP_CLOSED); close |= ((p->flags & PKT_PSEUDO_STREAM_END) ? 1 : 0); SCLogDebug("close ? %s", close ? "yes" : "no"); - TcpStream *stream = flags & OUTPUT_STREAMING_FLAG_TOSERVER ? &ssn->client : &ssn->server; + TcpStream *stream = + flags & OUTPUT_STREAMING_FLAG_TOSERVER ? &ssn->client : &ssn->server; streamer_cbdata.type = STREAMING_TCP_DATA; TcpDataLogger(f, ssn, stream, close, flags, (void *)&streamer_cbdata); } } - if (op_thread_data->loggers & (1<loggers & (1 << STREAMING_HTTP_BODIES)) { if (f->alproto == ALPROTO_HTTP1 && f->alstate != NULL) { int close = 0; TcpSession *ssn = f->protoctx; @@ -363,7 +361,8 @@ static TmEcode OutputStreamingLog(ThreadVars *tv, Packet *p, void *thread_data) /** \brief thread init for the tx logger * This will run the thread init functions for the individual registered * loggers */ -static TmEcode OutputStreamingLogThreadInit(ThreadVars *tv, const void *initdata, void **data) { +static TmEcode OutputStreamingLogThreadInit(ThreadVars *tv, const void *initdata, void **data) +{ OutputStreamingLoggerThreadData *td = SCCalloc(1, sizeof(*td)); if (td == NULL) return TM_ECODE_FAILED; @@ -396,7 +395,7 @@ static TmEcode OutputStreamingLogThreadInit(ThreadVars *tv, const void *initdata } } - td->loggers |= (1<type); + td->loggers |= (1 << logger->type); logger = logger->next; } @@ -404,7 +403,8 @@ static TmEcode OutputStreamingLogThreadInit(ThreadVars *tv, const void *initdata return TM_ECODE_OK; } -static TmEcode OutputStreamingLogThreadDeinit(ThreadVars *tv, void *thread_data) { +static TmEcode OutputStreamingLogThreadDeinit(ThreadVars *tv, void *thread_data) +{ OutputStreamingLoggerThreadData *op_thread_data = (OutputStreamingLoggerThreadData *)thread_data; OutputLoggerThreadStore *store = op_thread_data->store; @@ -425,7 +425,8 @@ static TmEcode OutputStreamingLogThreadDeinit(ThreadVars *tv, void *thread_data) return TM_ECODE_OK; } -static void OutputStreamingLogExitPrintStats(ThreadVars *tv, void *thread_data) { +static void OutputStreamingLogExitPrintStats(ThreadVars *tv, void *thread_data) +{ OutputStreamingLoggerThreadData *op_thread_data = (OutputStreamingLoggerThreadData *)thread_data; OutputLoggerThreadStore *store = op_thread_data->store; @@ -450,10 +451,11 @@ static uint32_t OutputStreamingLoggerGetActiveCount(void) return cnt; } -void OutputStreamingLoggerRegister(void) { - OutputRegisterRootLogger(OutputStreamingLogThreadInit, - OutputStreamingLogThreadDeinit, OutputStreamingLogExitPrintStats, - OutputStreamingLog, OutputStreamingLoggerGetActiveCount); +void OutputStreamingLoggerRegister(void) +{ + OutputRegisterRootLogger(OutputStreamingLogThreadInit, OutputStreamingLogThreadDeinit, + OutputStreamingLogExitPrintStats, OutputStreamingLog, + OutputStreamingLoggerGetActiveCount); } void OutputStreamingShutdown(void) diff --git a/src/output-streaming.h b/src/output-streaming.h index 07c3722d8e3d..348c9784c5bc 100644 --- a/src/output-streaming.h +++ b/src/output-streaming.h @@ -26,12 +26,11 @@ #ifndef __OUTPUT_STREAMING_H__ #define __OUTPUT_STREAMING_H__ - -#define OUTPUT_STREAMING_FLAG_OPEN 0x01 -#define OUTPUT_STREAMING_FLAG_CLOSE 0x02 -#define OUTPUT_STREAMING_FLAG_TOSERVER 0x04 -#define OUTPUT_STREAMING_FLAG_TOCLIENT 0x08 -#define OUTPUT_STREAMING_FLAG_TRANSACTION 0x10 +#define OUTPUT_STREAMING_FLAG_OPEN 0x01 +#define OUTPUT_STREAMING_FLAG_CLOSE 0x02 +#define OUTPUT_STREAMING_FLAG_TOSERVER 0x04 +#define OUTPUT_STREAMING_FLAG_TOCLIENT 0x08 +#define OUTPUT_STREAMING_FLAG_TRANSACTION 0x10 enum OutputStreamingType { STREAMING_TCP_DATA, @@ -39,16 +38,14 @@ enum OutputStreamingType { }; /** streaming logger function pointer type */ -typedef int (*StreamingLogger)(ThreadVars *, void *thread_data, - const Flow *f, const uint8_t *data, uint32_t data_len, - uint64_t tx_id, uint8_t flags); +typedef int (*StreamingLogger)(ThreadVars *, void *thread_data, const Flow *f, const uint8_t *data, + uint32_t data_len, uint64_t tx_id, uint8_t flags); -int OutputRegisterStreamingLogger(LoggerId id, const char *name, - StreamingLogger LogFunc, OutputCtx *, enum OutputStreamingType, - ThreadInitFunc ThreadInit, ThreadDeinitFunc ThreadDeinit, - ThreadExitPrintStatsFunc ThreadExitPrintStats); +int OutputRegisterStreamingLogger(LoggerId id, const char *name, StreamingLogger LogFunc, + OutputCtx *, enum OutputStreamingType, ThreadInitFunc ThreadInit, + ThreadDeinitFunc ThreadDeinit, ThreadExitPrintStatsFunc ThreadExitPrintStats); -void OutputStreamingLoggerRegister (void); +void OutputStreamingLoggerRegister(void); void OutputStreamingShutdown(void); diff --git a/src/output-tx.c b/src/output-tx.c index cf9a1bd11dae..bb58d032ed31 100644 --- a/src/output-tx.c +++ b/src/output-tx.c @@ -64,13 +64,10 @@ typedef struct OutputTxLogger_ { static OutputTxLogger *list[ALPROTO_MAX] = { NULL }; -int OutputRegisterTxLogger(LoggerId id, const char *name, AppProto alproto, - TxLogger LogFunc, - OutputCtx *output_ctx, int tc_log_progress, - int ts_log_progress, TxLoggerCondition LogCondition, - ThreadInitFunc ThreadInit, - ThreadDeinitFunc ThreadDeinit, - void (*ThreadExitPrintStats)(ThreadVars *, void *)) +int OutputRegisterTxLogger(LoggerId id, const char *name, AppProto alproto, TxLogger LogFunc, + OutputCtx *output_ctx, int tc_log_progress, int ts_log_progress, + TxLoggerCondition LogCondition, ThreadInitFunc ThreadInit, ThreadDeinitFunc ThreadDeinit, + void (*ThreadExitPrintStats)(ThreadVars *, void *)) { if (alproto != ALPROTO_UNKNOWN && !(AppLayerParserIsEnabled(alproto))) { SCLogDebug( @@ -95,8 +92,7 @@ int OutputRegisterTxLogger(LoggerId id, const char *name, AppProto alproto, op->tc_log_progress = 0; } else if (tc_log_progress < 0) { op->tc_log_progress = - AppLayerParserGetStateProgressCompletionStatus(alproto, - STREAM_TOCLIENT); + AppLayerParserGetStateProgressCompletionStatus(alproto, STREAM_TOCLIENT); } else { op->tc_log_progress = tc_log_progress; } @@ -105,8 +101,7 @@ int OutputRegisterTxLogger(LoggerId id, const char *name, AppProto alproto, op->ts_log_progress = 0; } else if (ts_log_progress < 0) { op->ts_log_progress = - AppLayerParserGetStateProgressCompletionStatus(alproto, - STREAM_TOSERVER); + AppLayerParserGetStateProgressCompletionStatus(alproto, STREAM_TOSERVER); } else { op->ts_log_progress = ts_log_progress; } @@ -253,7 +248,7 @@ static void OutputTxLogList0(ThreadVars *tv, OutputTxLoggerThreadData *op_thread SCLogDebug("logger %p", logger); /* always invoke "wild card" tx loggers */ - SCLogDebug("Logging tx_id %"PRIu64" to logger %d", tx_id, logger->logger_id); + SCLogDebug("Logging tx_id %" PRIu64 " to logger %d", tx_id, logger->logger_id); PACKET_PROFILING_LOGGER_START(p, logger->logger_id); logger->LogFunc(tv, store->thread_data, p, f, f->alstate, tx, tx_id); PACKET_PROFILING_LOGGER_END(p, logger->logger_id); @@ -345,7 +340,7 @@ static TmEcode OutputTxLog(ThreadVars *tv, Packet *p, void *thread_data) OutputTxLoggerThreadData *op_thread_data = (OutputTxLoggerThreadData *)thread_data; - Flow * const f = p->flow; + Flow *const f = p->flow; const uint8_t ipproto = f->proto; const AppProto alproto = f->alproto; SCLogDebug("pcap_cnt %u tx logging %u/%s", (uint32_t)p->pcap_cnt, alproto, @@ -409,7 +404,7 @@ static TmEcode OutputTxLog(ThreadVars *tv, Packet *p, void *thread_data) AppLayerGetTxIterTuple ires = IterFunc(ipproto, alproto, alstate, tx_id, total_txs, &state); if (ires.tx_ptr == NULL) break; - void * const tx = ires.tx_ptr; + void *const tx = ires.tx_ptr; tx_id = ires.tx_id; SCLogDebug("STARTING tx_id %" PRIu64 ", tx %p", tx_id, tx); @@ -475,7 +470,7 @@ static TmEcode OutputTxLog(ThreadVars *tv, Packet *p, void *thread_data) SCLogDebug("tx %p/%" PRIu64 " txd %p: log_flags %x logger_expectation %x", tx, tx_id, txd, txd->config.log_flags, logger_expectation); if (txd->config.log_flags & BIT_U8(CONFIG_TYPE_TX)) { - SCLogDebug("SKIP tx %p/%"PRIu64, tx, tx_id); + SCLogDebug("SKIP tx %p/%" PRIu64, tx, tx_id); // so that AppLayerParserTransactionsCleanup can clean this tx txd->logged.flags |= logger_expectation; goto next_tx; @@ -517,7 +512,7 @@ static TmEcode OutputTxLog(ThreadVars *tv, Packet *p, void *thread_data) } else { gap = 1; } -next_tx: + next_tx: if (!ires.has_next) break; tx_id++; @@ -526,7 +521,7 @@ static TmEcode OutputTxLog(ThreadVars *tv, Packet *p, void *thread_data) /* Update the last ID that has been logged with all * transactions before it. */ if (logged) { - SCLogDebug("updating log tx_id %"PRIu64, max_id); + SCLogDebug("updating log tx_id %" PRIu64, max_id); AppLayerParserSetTransactionLogId(f->alparser, max_id + 1); } @@ -662,11 +657,10 @@ static uint32_t OutputTxLoggerGetActiveCount(void) return cnt; } - -void OutputTxLoggerRegister (void) +void OutputTxLoggerRegister(void) { OutputRegisterRootLogger(OutputTxLogThreadInit, OutputTxLogThreadDeinit, - OutputTxLogExitPrintStats, OutputTxLog, OutputTxLoggerGetActiveCount); + OutputTxLogExitPrintStats, OutputTxLog, OutputTxLoggerGetActiveCount); } void OutputTxShutdown(void) diff --git a/src/output-tx.h b/src/output-tx.h index 88c12ff25f68..239ba484f35a 100644 --- a/src/output-tx.h +++ b/src/output-tx.h @@ -30,7 +30,8 @@ #include "flow.h" /** tx logger function pointer type */ -typedef int (*TxLogger)(ThreadVars *, void *thread_data, const Packet *, Flow *f, void *state, void *tx, uint64_t tx_id); +typedef int (*TxLogger)(ThreadVars *, void *thread_data, const Packet *, Flow *f, void *state, + void *tx, uint64_t tx_id); /** tx logger condition function pointer type, * must return true for tx that should be logged @@ -38,14 +39,11 @@ typedef int (*TxLogger)(ThreadVars *, void *thread_data, const Packet *, Flow *f typedef bool (*TxLoggerCondition)( ThreadVars *, const Packet *, void *state, void *tx, uint64_t tx_id); -int OutputRegisterTxLogger(LoggerId id, const char *name, AppProto alproto, - TxLogger LogFunc, - OutputCtx *, int tc_log_progress, int ts_log_progress, - TxLoggerCondition LogCondition, - ThreadInitFunc, ThreadDeinitFunc, - void (*ThreadExitPrintStats)(ThreadVars *, void *)); +int OutputRegisterTxLogger(LoggerId id, const char *name, AppProto alproto, TxLogger LogFunc, + OutputCtx *, int tc_log_progress, int ts_log_progress, TxLoggerCondition LogCondition, + ThreadInitFunc, ThreadDeinitFunc, void (*ThreadExitPrintStats)(ThreadVars *, void *)); -void OutputTxLoggerRegister (void); +void OutputTxLoggerRegister(void); void OutputTxShutdown(void); diff --git a/src/output.c b/src/output.c index 149dda58c284..46291c631f60 100644 --- a/src/output.c +++ b/src/output.c @@ -104,13 +104,11 @@ typedef struct RootLogger_ { /* List of registered root loggers. These are registered at start up and * are independent of configuration. Later we will build a list of active * loggers based on configuration. */ -static TAILQ_HEAD(, RootLogger_) registered_loggers = - TAILQ_HEAD_INITIALIZER(registered_loggers); +static TAILQ_HEAD(, RootLogger_) registered_loggers = TAILQ_HEAD_INITIALIZER(registered_loggers); /* List of active root loggers. This means that at least one logger is enabled * for each root logger type in the config. */ -static TAILQ_HEAD(, RootLogger_) active_loggers = - TAILQ_HEAD_INITIALIZER(active_loggers); +static TAILQ_HEAD(, RootLogger_) active_loggers = TAILQ_HEAD_INITIALIZER(active_loggers); typedef struct LoggerThreadStoreNode_ { void *thread_data; @@ -133,8 +131,8 @@ typedef struct OutputFileRolloverFlag_ { TAILQ_ENTRY(OutputFileRolloverFlag_) entries; } OutputFileRolloverFlag; -TAILQ_HEAD(, OutputFileRolloverFlag_) output_file_rotation_flags = - TAILQ_HEAD_INITIALIZER(output_file_rotation_flags); +TAILQ_HEAD(, OutputFileRolloverFlag_) +output_file_rotation_flags = TAILQ_HEAD_INITIALIZER(output_file_rotation_flags); void OutputRegisterRootLoggers(void); void OutputRegisterLoggers(void); @@ -147,8 +145,7 @@ void OutputRegisterLoggers(void); * * \retval Returns 0 on success, -1 on failure. */ -void OutputRegisterModule(const char *name, const char *conf_name, - OutputInitFunc InitFunc) +void OutputRegisterModule(const char *name, const char *conf_name, OutputInitFunc InitFunc) { OutputModule *module = SCCalloc(1, sizeof(*module)); if (unlikely(module == NULL)) @@ -175,11 +172,10 @@ void OutputRegisterModule(const char *name, const char *conf_name, * * \retval Returns 0 on success, -1 on failure. */ -void OutputRegisterPacketModule(LoggerId id, const char *name, - const char *conf_name, OutputInitFunc InitFunc, - PacketLogger PacketLogFunc, PacketLogCondition PacketConditionFunc, - ThreadInitFunc ThreadInit, ThreadDeinitFunc ThreadDeinit, - ThreadExitPrintStatsFunc ThreadExitPrintStats) +void OutputRegisterPacketModule(LoggerId id, const char *name, const char *conf_name, + OutputInitFunc InitFunc, PacketLogger PacketLogFunc, PacketLogCondition PacketConditionFunc, + ThreadInitFunc ThreadInit, ThreadDeinitFunc ThreadDeinit, + ThreadExitPrintStatsFunc ThreadExitPrintStats) { if (unlikely(PacketLogFunc == NULL || PacketConditionFunc == NULL)) { goto error; @@ -215,11 +211,10 @@ void OutputRegisterPacketModule(LoggerId id, const char *name, * * \retval Returns 0 on success, -1 on failure. */ -void OutputRegisterPacketSubModule(LoggerId id, const char *parent_name, - const char *name, const char *conf_name, OutputInitSubFunc InitFunc, - PacketLogger PacketLogFunc, PacketLogCondition PacketConditionFunc, - ThreadInitFunc ThreadInit, ThreadDeinitFunc ThreadDeinit, - ThreadExitPrintStatsFunc ThreadExitPrintStats) +void OutputRegisterPacketSubModule(LoggerId id, const char *parent_name, const char *name, + const char *conf_name, OutputInitSubFunc InitFunc, PacketLogger PacketLogFunc, + PacketLogCondition PacketConditionFunc, ThreadInitFunc ThreadInit, + ThreadDeinitFunc ThreadDeinit, ThreadExitPrintStatsFunc ThreadExitPrintStats) { if (unlikely(PacketLogFunc == NULL || PacketConditionFunc == NULL)) { goto error; @@ -256,12 +251,10 @@ void OutputRegisterPacketSubModule(LoggerId id, const char *parent_name, * * \retval Returns 0 on success, -1 on failure. */ -static void OutputRegisterTxModuleWrapper(LoggerId id, const char *name, - const char *conf_name, OutputInitFunc InitFunc, AppProto alproto, - TxLogger TxLogFunc, int tc_log_progress, int ts_log_progress, - TxLoggerCondition TxLogCondition, ThreadInitFunc ThreadInit, - ThreadDeinitFunc ThreadDeinit, - ThreadExitPrintStatsFunc ThreadExitPrintStats) +static void OutputRegisterTxModuleWrapper(LoggerId id, const char *name, const char *conf_name, + OutputInitFunc InitFunc, AppProto alproto, TxLogger TxLogFunc, int tc_log_progress, + int ts_log_progress, TxLoggerCondition TxLogCondition, ThreadInitFunc ThreadInit, + ThreadDeinitFunc ThreadDeinit, ThreadExitPrintStatsFunc ThreadExitPrintStats) { if (unlikely(TxLogFunc == NULL)) { goto error; @@ -292,12 +285,11 @@ static void OutputRegisterTxModuleWrapper(LoggerId id, const char *name, FatalError("Fatal error encountered. Exiting..."); } -static void OutputRegisterTxSubModuleWrapper(LoggerId id, const char *parent_name, - const char *name, const char *conf_name, OutputInitSubFunc InitFunc, - AppProto alproto, TxLogger TxLogFunc, int tc_log_progress, - int ts_log_progress, TxLoggerCondition TxLogCondition, - ThreadInitFunc ThreadInit, ThreadDeinitFunc ThreadDeinit, - ThreadExitPrintStatsFunc ThreadExitPrintStats) +static void OutputRegisterTxSubModuleWrapper(LoggerId id, const char *parent_name, const char *name, + const char *conf_name, OutputInitSubFunc InitFunc, AppProto alproto, TxLogger TxLogFunc, + int tc_log_progress, int ts_log_progress, TxLoggerCondition TxLogCondition, + ThreadInitFunc ThreadInit, ThreadDeinitFunc ThreadDeinit, + ThreadExitPrintStatsFunc ThreadExitPrintStats) { if (unlikely(TxLogFunc == NULL)) { goto error; @@ -337,27 +329,22 @@ static void OutputRegisterTxSubModuleWrapper(LoggerId id, const char *parent_nam * * \retval Returns 0 on success, -1 on failure. */ -void OutputRegisterTxModuleWithCondition(LoggerId id, const char *name, - const char *conf_name, OutputInitFunc InitFunc, AppProto alproto, - TxLogger TxLogFunc, TxLoggerCondition TxLogCondition, - ThreadInitFunc ThreadInit, ThreadDeinitFunc ThreadDeinit, - ThreadExitPrintStatsFunc ThreadExitPrintStats) +void OutputRegisterTxModuleWithCondition(LoggerId id, const char *name, const char *conf_name, + OutputInitFunc InitFunc, AppProto alproto, TxLogger TxLogFunc, + TxLoggerCondition TxLogCondition, ThreadInitFunc ThreadInit, ThreadDeinitFunc ThreadDeinit, + ThreadExitPrintStatsFunc ThreadExitPrintStats) { - OutputRegisterTxModuleWrapper(id, name, conf_name, InitFunc, alproto, - TxLogFunc, -1, -1, TxLogCondition, ThreadInit, ThreadDeinit, - ThreadExitPrintStats); + OutputRegisterTxModuleWrapper(id, name, conf_name, InitFunc, alproto, TxLogFunc, -1, -1, + TxLogCondition, ThreadInit, ThreadDeinit, ThreadExitPrintStats); } -void OutputRegisterTxSubModuleWithCondition(LoggerId id, - const char *parent_name, const char *name, const char *conf_name, - OutputInitSubFunc InitFunc, AppProto alproto, TxLogger TxLogFunc, - TxLoggerCondition TxLogCondition, ThreadInitFunc ThreadInit, - ThreadDeinitFunc ThreadDeinit, - ThreadExitPrintStatsFunc ThreadExitPrintStats) +void OutputRegisterTxSubModuleWithCondition(LoggerId id, const char *parent_name, const char *name, + const char *conf_name, OutputInitSubFunc InitFunc, AppProto alproto, TxLogger TxLogFunc, + TxLoggerCondition TxLogCondition, ThreadInitFunc ThreadInit, ThreadDeinitFunc ThreadDeinit, + ThreadExitPrintStatsFunc ThreadExitPrintStats) { - OutputRegisterTxSubModuleWrapper(id, parent_name, name, conf_name, InitFunc, - alproto, TxLogFunc, -1, -1, TxLogCondition, ThreadInit, ThreadDeinit, - ThreadExitPrintStats); + OutputRegisterTxSubModuleWrapper(id, parent_name, name, conf_name, InitFunc, alproto, TxLogFunc, + -1, -1, TxLogCondition, ThreadInit, ThreadDeinit, ThreadExitPrintStats); } /** @@ -368,27 +355,22 @@ void OutputRegisterTxSubModuleWithCondition(LoggerId id, * * \retval Returns 0 on success, -1 on failure. */ -void OutputRegisterTxModuleWithProgress(LoggerId id, const char *name, - const char *conf_name, OutputInitFunc InitFunc, AppProto alproto, - TxLogger TxLogFunc, int tc_log_progress, int ts_log_progress, - ThreadInitFunc ThreadInit, ThreadDeinitFunc ThreadDeinit, - ThreadExitPrintStatsFunc ThreadExitPrintStats) +void OutputRegisterTxModuleWithProgress(LoggerId id, const char *name, const char *conf_name, + OutputInitFunc InitFunc, AppProto alproto, TxLogger TxLogFunc, int tc_log_progress, + int ts_log_progress, ThreadInitFunc ThreadInit, ThreadDeinitFunc ThreadDeinit, + ThreadExitPrintStatsFunc ThreadExitPrintStats) { - OutputRegisterTxModuleWrapper(id, name, conf_name, InitFunc, alproto, - TxLogFunc, tc_log_progress, ts_log_progress, NULL, ThreadInit, - ThreadDeinit, ThreadExitPrintStats); + OutputRegisterTxModuleWrapper(id, name, conf_name, InitFunc, alproto, TxLogFunc, + tc_log_progress, ts_log_progress, NULL, ThreadInit, ThreadDeinit, ThreadExitPrintStats); } -void OutputRegisterTxSubModuleWithProgress(LoggerId id, const char *parent_name, - const char *name, const char *conf_name, OutputInitSubFunc InitFunc, - AppProto alproto, TxLogger TxLogFunc, int tc_log_progress, - int ts_log_progress, ThreadInitFunc ThreadInit, - ThreadDeinitFunc ThreadDeinit, - ThreadExitPrintStatsFunc ThreadExitPrintStats) +void OutputRegisterTxSubModuleWithProgress(LoggerId id, const char *parent_name, const char *name, + const char *conf_name, OutputInitSubFunc InitFunc, AppProto alproto, TxLogger TxLogFunc, + int tc_log_progress, int ts_log_progress, ThreadInitFunc ThreadInit, + ThreadDeinitFunc ThreadDeinit, ThreadExitPrintStatsFunc ThreadExitPrintStats) { - OutputRegisterTxSubModuleWrapper(id, parent_name, name, conf_name, InitFunc, - alproto, TxLogFunc, tc_log_progress, ts_log_progress, NULL, ThreadInit, - ThreadDeinit, ThreadExitPrintStats); + OutputRegisterTxSubModuleWrapper(id, parent_name, name, conf_name, InitFunc, alproto, TxLogFunc, + tc_log_progress, ts_log_progress, NULL, ThreadInit, ThreadDeinit, ThreadExitPrintStats); } /** @@ -399,26 +381,21 @@ void OutputRegisterTxSubModuleWithProgress(LoggerId id, const char *parent_name, * * \retval Returns 0 on success, -1 on failure. */ -void OutputRegisterTxModule(LoggerId id, const char *name, - const char *conf_name, OutputInitFunc InitFunc, AppProto alproto, - TxLogger TxLogFunc, ThreadInitFunc ThreadInit, - ThreadDeinitFunc ThreadDeinit, - ThreadExitPrintStatsFunc ThreadExitPrintStats) +void OutputRegisterTxModule(LoggerId id, const char *name, const char *conf_name, + OutputInitFunc InitFunc, AppProto alproto, TxLogger TxLogFunc, ThreadInitFunc ThreadInit, + ThreadDeinitFunc ThreadDeinit, ThreadExitPrintStatsFunc ThreadExitPrintStats) { - OutputRegisterTxModuleWrapper(id, name, conf_name, InitFunc, alproto, - TxLogFunc, -1, -1, NULL, ThreadInit, ThreadDeinit, - ThreadExitPrintStats); + OutputRegisterTxModuleWrapper(id, name, conf_name, InitFunc, alproto, TxLogFunc, -1, -1, NULL, + ThreadInit, ThreadDeinit, ThreadExitPrintStats); } -void OutputRegisterTxSubModule(LoggerId id, const char *parent_name, - const char *name, const char *conf_name, - OutputInitSubFunc InitFunc, AppProto alproto, TxLogger TxLogFunc, - ThreadInitFunc ThreadInit, ThreadDeinitFunc ThreadDeinit, - ThreadExitPrintStatsFunc ThreadExitPrintStats) +void OutputRegisterTxSubModule(LoggerId id, const char *parent_name, const char *name, + const char *conf_name, OutputInitSubFunc InitFunc, AppProto alproto, TxLogger TxLogFunc, + ThreadInitFunc ThreadInit, ThreadDeinitFunc ThreadDeinit, + ThreadExitPrintStatsFunc ThreadExitPrintStats) { - OutputRegisterTxSubModuleWrapper(id, parent_name, name, conf_name, - InitFunc, alproto, TxLogFunc, -1, -1, NULL, ThreadInit, ThreadDeinit, - ThreadExitPrintStats); + OutputRegisterTxSubModuleWrapper(id, parent_name, name, conf_name, InitFunc, alproto, TxLogFunc, + -1, -1, NULL, ThreadInit, ThreadDeinit, ThreadExitPrintStats); } /** @@ -429,10 +406,9 @@ void OutputRegisterTxSubModule(LoggerId id, const char *parent_name, * * \retval Returns 0 on success, -1 on failure. */ -void OutputRegisterFileModule(LoggerId id, const char *name, - const char *conf_name, OutputInitFunc InitFunc, FileLogger FileLogFunc, - ThreadInitFunc ThreadInit, ThreadDeinitFunc ThreadDeinit, - ThreadExitPrintStatsFunc ThreadExitPrintStats) +void OutputRegisterFileModule(LoggerId id, const char *name, const char *conf_name, + OutputInitFunc InitFunc, FileLogger FileLogFunc, ThreadInitFunc ThreadInit, + ThreadDeinitFunc ThreadDeinit, ThreadExitPrintStatsFunc ThreadExitPrintStats) { if (unlikely(FileLogFunc == NULL)) { goto error; @@ -467,11 +443,10 @@ void OutputRegisterFileModule(LoggerId id, const char *name, * * \retval Returns 0 on success, -1 on failure. */ -void OutputRegisterFileSubModule(LoggerId id, const char *parent_name, - const char *name, const char *conf_name, OutputInitSubFunc InitFunc, - FileLogger FileLogFunc, ThreadInitFunc ThreadInit, - ThreadDeinitFunc ThreadDeinit, - ThreadExitPrintStatsFunc ThreadExitPrintStats) +void OutputRegisterFileSubModule(LoggerId id, const char *parent_name, const char *name, + const char *conf_name, OutputInitSubFunc InitFunc, FileLogger FileLogFunc, + ThreadInitFunc ThreadInit, ThreadDeinitFunc ThreadDeinit, + ThreadExitPrintStatsFunc ThreadExitPrintStats) { if (unlikely(FileLogFunc == NULL)) { goto error; @@ -507,11 +482,9 @@ void OutputRegisterFileSubModule(LoggerId id, const char *parent_name, * * \retval Returns 0 on success, -1 on failure. */ -void OutputRegisterFiledataModule(LoggerId id, const char *name, - const char *conf_name, OutputInitFunc InitFunc, - FiledataLogger FiledataLogFunc, ThreadInitFunc ThreadInit, - ThreadDeinitFunc ThreadDeinit, - ThreadExitPrintStatsFunc ThreadExitPrintStats) +void OutputRegisterFiledataModule(LoggerId id, const char *name, const char *conf_name, + OutputInitFunc InitFunc, FiledataLogger FiledataLogFunc, ThreadInitFunc ThreadInit, + ThreadDeinitFunc ThreadDeinit, ThreadExitPrintStatsFunc ThreadExitPrintStats) { if (unlikely(FiledataLogFunc == NULL)) { goto error; @@ -546,11 +519,10 @@ void OutputRegisterFiledataModule(LoggerId id, const char *name, * * \retval Returns 0 on success, -1 on failure. */ -void OutputRegisterFiledataSubModule(LoggerId id, const char *parent_name, - const char *name, const char *conf_name, OutputInitSubFunc InitFunc, - FiledataLogger FiledataLogFunc, ThreadInitFunc ThreadInit, - ThreadDeinitFunc ThreadDeinit, - ThreadExitPrintStatsFunc ThreadExitPrintStats) +void OutputRegisterFiledataSubModule(LoggerId id, const char *parent_name, const char *name, + const char *conf_name, OutputInitSubFunc InitFunc, FiledataLogger FiledataLogFunc, + ThreadInitFunc ThreadInit, ThreadDeinitFunc ThreadDeinit, + ThreadExitPrintStatsFunc ThreadExitPrintStats) { if (unlikely(FiledataLogFunc == NULL)) { goto error; @@ -586,11 +558,10 @@ void OutputRegisterFiledataSubModule(LoggerId id, const char *parent_name, * * \retval Returns 0 on success, -1 on failure. */ -void OutputRegisterFlowSubModule(LoggerId id, const char *parent_name, - const char *name, const char *conf_name, OutputInitSubFunc InitFunc, - FlowLogger FlowLogFunc, ThreadInitFunc ThreadInit, - ThreadDeinitFunc ThreadDeinit, - ThreadExitPrintStatsFunc ThreadExitPrintStats) +void OutputRegisterFlowSubModule(LoggerId id, const char *parent_name, const char *name, + const char *conf_name, OutputInitSubFunc InitFunc, FlowLogger FlowLogFunc, + ThreadInitFunc ThreadInit, ThreadDeinitFunc ThreadDeinit, + ThreadExitPrintStatsFunc ThreadExitPrintStats) { if (unlikely(FlowLogFunc == NULL)) { goto error; @@ -626,12 +597,10 @@ void OutputRegisterFlowSubModule(LoggerId id, const char *parent_name, * * \retval Returns 0 on success, -1 on failure. */ -void OutputRegisterStreamingModule(LoggerId id, const char *name, - const char *conf_name, OutputInitFunc InitFunc, - StreamingLogger StreamingLogFunc, - enum OutputStreamingType stream_type, ThreadInitFunc ThreadInit, - ThreadDeinitFunc ThreadDeinit, - ThreadExitPrintStatsFunc ThreadExitPrintStats) +void OutputRegisterStreamingModule(LoggerId id, const char *name, const char *conf_name, + OutputInitFunc InitFunc, StreamingLogger StreamingLogFunc, + enum OutputStreamingType stream_type, ThreadInitFunc ThreadInit, + ThreadDeinitFunc ThreadDeinit, ThreadExitPrintStatsFunc ThreadExitPrintStats) { if (unlikely(StreamingLogFunc == NULL)) { goto error; @@ -667,11 +636,10 @@ void OutputRegisterStreamingModule(LoggerId id, const char *name, * * \retval Returns 0 on success, -1 on failure. */ -void OutputRegisterStreamingSubModule(LoggerId id, const char *parent_name, - const char *name, const char *conf_name, OutputInitSubFunc InitFunc, - StreamingLogger StreamingLogFunc, enum OutputStreamingType stream_type, - ThreadInitFunc ThreadInit, ThreadDeinitFunc ThreadDeinit, - ThreadExitPrintStatsFunc ThreadExitPrintStats) +void OutputRegisterStreamingSubModule(LoggerId id, const char *parent_name, const char *name, + const char *conf_name, OutputInitSubFunc InitFunc, StreamingLogger StreamingLogFunc, + enum OutputStreamingType stream_type, ThreadInitFunc ThreadInit, + ThreadDeinitFunc ThreadDeinit, ThreadExitPrintStatsFunc ThreadExitPrintStats) { if (unlikely(StreamingLogFunc == NULL)) { goto error; @@ -708,10 +676,9 @@ void OutputRegisterStreamingSubModule(LoggerId id, const char *parent_name, * * \retval Returns 0 on success, -1 on failure. */ -void OutputRegisterStatsModule(LoggerId id, const char *name, - const char *conf_name, OutputInitFunc InitFunc, StatsLogger StatsLogFunc, - ThreadInitFunc ThreadInit, ThreadDeinitFunc ThreadDeinit, - ThreadExitPrintStatsFunc ThreadExitPrintStats) +void OutputRegisterStatsModule(LoggerId id, const char *name, const char *conf_name, + OutputInitFunc InitFunc, StatsLogger StatsLogFunc, ThreadInitFunc ThreadInit, + ThreadDeinitFunc ThreadDeinit, ThreadExitPrintStatsFunc ThreadExitPrintStats) { if (unlikely(StatsLogFunc == NULL)) { goto error; @@ -746,11 +713,10 @@ void OutputRegisterStatsModule(LoggerId id, const char *name, * * \retval Returns 0 on success, -1 on failure. */ -void OutputRegisterStatsSubModule(LoggerId id, const char *parent_name, - const char *name, const char *conf_name, OutputInitSubFunc InitFunc, - StatsLogger StatsLogFunc, ThreadInitFunc ThreadInit, - ThreadDeinitFunc ThreadDeinit, - ThreadExitPrintStatsFunc ThreadExitPrintStats) +void OutputRegisterStatsSubModule(LoggerId id, const char *parent_name, const char *name, + const char *conf_name, OutputInitSubFunc InitFunc, StatsLogger StatsLogFunc, + ThreadInitFunc ThreadInit, ThreadDeinitFunc ThreadDeinit, + ThreadExitPrintStatsFunc ThreadExitPrintStats) { if (unlikely(StatsLogFunc == NULL)) { goto error; @@ -788,7 +754,7 @@ OutputModule *OutputGetModuleByConfName(const char *conf_name) { OutputModule *module; - TAILQ_FOREACH(module, &output_modules, entries) { + TAILQ_FOREACH (module, &output_modules, entries) { if (strcmp(module->conf_name, conf_name) == 0) return module; } @@ -855,8 +821,7 @@ void OutputRegisterFileRotationFlag(int *flag) void OutputUnregisterFileRotationFlag(int *flag) { OutputFileRolloverFlag *entry, *next; - for (entry = TAILQ_FIRST(&output_file_rotation_flags); entry != NULL; - entry = next) { + for (entry = TAILQ_FIRST(&output_file_rotation_flags); entry != NULL; entry = next) { next = TAILQ_NEXT(entry, entries); if (entry->flag == flag) { TAILQ_REMOVE(&output_file_rotation_flags, entry, entries); @@ -869,9 +834,10 @@ void OutputUnregisterFileRotationFlag(int *flag) /** * \brief Notifies all registered file rotation notification flags. */ -void OutputNotifyFileRotation(void) { +void OutputNotifyFileRotation(void) +{ OutputFileRolloverFlag *flag; - TAILQ_FOREACH(flag, &output_file_rotation_flags, entries) { + TAILQ_FOREACH (flag, &output_file_rotation_flags, entries) { *(flag->flag) = 1; } } @@ -900,13 +866,12 @@ TmEcode OutputLoggerThreadInit(ThreadVars *tv, const void *initdata, void **data *data = (void *)thread_store; RootLogger *logger; - TAILQ_FOREACH(logger, &active_loggers, entries) { + TAILQ_FOREACH (logger, &active_loggers, entries) { void *child_thread_data = NULL; if (logger->ThreadInit != NULL) { if (logger->ThreadInit(tv, initdata, &child_thread_data) == TM_ECODE_OK) { - LoggerThreadStoreNode *thread_store_node = - SCCalloc(1, sizeof(*thread_store_node)); + LoggerThreadStoreNode *thread_store_node = SCCalloc(1, sizeof(*thread_store_node)); if (thread_store_node == NULL) { /* Undo everything, calling de-init will take care * of that. */ @@ -961,10 +926,9 @@ void OutputLoggerExitPrintStats(ThreadVars *tv, void *thread_data) } } -void OutputRegisterRootLogger(ThreadInitFunc ThreadInit, - ThreadDeinitFunc ThreadDeinit, - ThreadExitPrintStatsFunc ThreadExitPrintStats, - OutputLogFunc LogFunc, OutputGetActiveCountFunc ActiveCntFunc) +void OutputRegisterRootLogger(ThreadInitFunc ThreadInit, ThreadDeinitFunc ThreadDeinit, + ThreadExitPrintStatsFunc ThreadExitPrintStats, OutputLogFunc LogFunc, + OutputGetActiveCountFunc ActiveCntFunc) { BUG_ON(LogFunc == NULL); diff --git a/src/output.h b/src/output.h index 815b2f20ed73..d1e1dbf49c69 100644 --- a/src/output.h +++ b/src/output.h @@ -27,8 +27,8 @@ #include "decode.h" #include "tm-modules.h" -#define DEFAULT_LOG_MODE_APPEND "yes" -#define DEFAULT_LOG_FILETYPE "regular" +#define DEFAULT_LOG_MODE_APPEND "yes" +#define DEFAULT_LOG_FILETYPE "regular" typedef struct OutputLoggerThreadStore_ { void *thread_data; @@ -87,102 +87,77 @@ extern OutputModuleList output_modules; void OutputRegisterModule(const char *, const char *, OutputInitFunc); -void OutputRegisterPacketModule(LoggerId id, const char *name, - const char *conf_name, OutputInitFunc InitFunc, PacketLogger LogFunc, - PacketLogCondition ConditionFunc, ThreadInitFunc, ThreadDeinitFunc, - ThreadExitPrintStatsFunc); -void OutputRegisterPacketSubModule(LoggerId id, const char *parent_name, - const char *name, const char *conf_name, OutputInitSubFunc InitFunc, - PacketLogger LogFunc, PacketLogCondition ConditionFunc, - ThreadInitFunc ThreadInit, ThreadDeinitFunc ThreadDeinit, - ThreadExitPrintStatsFunc ThreadExitPrintStats); - -void OutputRegisterTxModule(LoggerId id, const char *name, - const char *conf_name, OutputInitFunc InitFunc, AppProto alproto, - TxLogger TxLogFunc, ThreadInitFunc ThreadInit, - ThreadDeinitFunc ThreadDeinit, - ThreadExitPrintStatsFunc ThreadExitPrintStats); -void OutputRegisterTxSubModule(LoggerId id, const char *parent_name, - const char *name, const char *conf_name, - OutputInitSubFunc InitFunc, AppProto alproto, TxLogger TxLogFunc, - ThreadInitFunc ThreadInit, ThreadDeinitFunc ThreadDeinit, - ThreadExitPrintStatsFunc ThreadExitPrintStats); - -void OutputRegisterTxModuleWithCondition(LoggerId id, const char *name, - const char *conf_name, OutputInitFunc InitFunc, AppProto alproto, - TxLogger TxLogFunc, TxLoggerCondition TxLogCondition, - ThreadInitFunc ThreadInit, ThreadDeinitFunc ThreadDeinit, - ThreadExitPrintStatsFunc ThreadExitPrintStats); -void OutputRegisterTxSubModuleWithCondition(LoggerId id, - const char *parent_name, const char *name, const char *conf_name, - OutputInitSubFunc InitFunc, AppProto alproto, - TxLogger TxLogFunc, TxLoggerCondition TxLogCondition, - ThreadInitFunc ThreadInit, ThreadDeinitFunc ThreadDeinit, - ThreadExitPrintStatsFunc ThreadExitPrintStats); - -void OutputRegisterTxModuleWithProgress(LoggerId id, const char *name, - const char *conf_name, OutputInitFunc InitFunc, AppProto alproto, - TxLogger TxLogFunc, int tc_log_progress, int ts_log_progress, - ThreadInitFunc ThreadInit, ThreadDeinitFunc ThreadDeinit, - ThreadExitPrintStatsFunc ThreadExitPrintStats); -void OutputRegisterTxSubModuleWithProgress(LoggerId id, const char *parent_name, - const char *name, const char *conf_name, - OutputInitSubFunc InitFunc, AppProto alproto, TxLogger TxLogFunc, - int tc_log_progress, int ts_log_progress, ThreadInitFunc ThreadInit, - ThreadDeinitFunc ThreadDeinit, - ThreadExitPrintStatsFunc ThreadExitPrintStats); - -void OutputRegisterFileModule(LoggerId id, const char *name, - const char *conf_name, OutputInitFunc InitFunc, - FileLogger FileLogFunc, ThreadInitFunc ThreadInit, - ThreadDeinitFunc ThreadDeinit, - ThreadExitPrintStatsFunc ThreadExitPrintStats); -void OutputRegisterFileSubModule(LoggerId id, const char *parent_name, - const char *name, const char *conf_name, - OutputInitSubFunc InitFunc, FileLogger FileLogFunc, - ThreadInitFunc ThreadInit, ThreadDeinitFunc ThreadDeinit, - ThreadExitPrintStatsFunc ThreadExitPrintStats); - -void OutputRegisterFiledataModule(LoggerId id, const char *name, - const char *conf_name, OutputInitFunc InitFunc, - FiledataLogger FiledataLogFunc, ThreadInitFunc ThreadInit, - ThreadDeinitFunc ThreadDeinit, - ThreadExitPrintStatsFunc ThreadExitPrintStats); -void OutputRegisterFiledataSubModule(LoggerId, const char *parent_name, - const char *name, const char *conf_name, OutputInitSubFunc InitFunc, - FiledataLogger FiledataLogFunc, ThreadInitFunc ThreadInit, - ThreadDeinitFunc ThreadDeinit, - ThreadExitPrintStatsFunc ThreadExitPrintStats); - -void OutputRegisterFlowSubModule(LoggerId id, const char *parent_name, - const char *name, const char *conf_name, OutputInitSubFunc InitFunc, - FlowLogger FlowLogFunc, ThreadInitFunc ThreadInit, - ThreadDeinitFunc ThreadDeinit, - ThreadExitPrintStatsFunc ThreadExitPrintStats); - -void OutputRegisterStreamingModule(LoggerId id, const char *name, - const char *conf_name, OutputInitFunc InitFunc, - StreamingLogger StreamingLogFunc, enum OutputStreamingType stream_type, - ThreadInitFunc ThreadInit, ThreadDeinitFunc ThreadDeinit, - ThreadExitPrintStatsFunc ThreadExitPrintStats); -void OutputRegisterStreamingSubModule(LoggerId id, const char *parent_name, - const char *name, const char *conf_name, - OutputInitSubFunc InitFunc, StreamingLogger StreamingLogFunc, - enum OutputStreamingType stream_type, - ThreadInitFunc ThreadInit, ThreadDeinitFunc ThreadDeinit, - ThreadExitPrintStatsFunc ThreadExitPrintStats); - -void OutputRegisterStatsModule(LoggerId id, const char *name, - const char *conf_name, OutputInitFunc InitFunc, - StatsLogger StatsLogFunc, ThreadInitFunc ThreadInit, - ThreadDeinitFunc ThreadDeinit, - ThreadExitPrintStatsFunc ThreadExitPrintStats); -void OutputRegisterStatsSubModule(LoggerId id, const char *parent_name, - const char *name, const char *conf_name, - OutputInitSubFunc InitFunc, - StatsLogger StatsLogFunc, ThreadInitFunc ThreadInit, - ThreadDeinitFunc ThreadDeinit, - ThreadExitPrintStatsFunc ThreadExitPrintStats); +void OutputRegisterPacketModule(LoggerId id, const char *name, const char *conf_name, + OutputInitFunc InitFunc, PacketLogger LogFunc, PacketLogCondition ConditionFunc, + ThreadInitFunc, ThreadDeinitFunc, ThreadExitPrintStatsFunc); +void OutputRegisterPacketSubModule(LoggerId id, const char *parent_name, const char *name, + const char *conf_name, OutputInitSubFunc InitFunc, PacketLogger LogFunc, + PacketLogCondition ConditionFunc, ThreadInitFunc ThreadInit, ThreadDeinitFunc ThreadDeinit, + ThreadExitPrintStatsFunc ThreadExitPrintStats); + +void OutputRegisterTxModule(LoggerId id, const char *name, const char *conf_name, + OutputInitFunc InitFunc, AppProto alproto, TxLogger TxLogFunc, ThreadInitFunc ThreadInit, + ThreadDeinitFunc ThreadDeinit, ThreadExitPrintStatsFunc ThreadExitPrintStats); +void OutputRegisterTxSubModule(LoggerId id, const char *parent_name, const char *name, + const char *conf_name, OutputInitSubFunc InitFunc, AppProto alproto, TxLogger TxLogFunc, + ThreadInitFunc ThreadInit, ThreadDeinitFunc ThreadDeinit, + ThreadExitPrintStatsFunc ThreadExitPrintStats); + +void OutputRegisterTxModuleWithCondition(LoggerId id, const char *name, const char *conf_name, + OutputInitFunc InitFunc, AppProto alproto, TxLogger TxLogFunc, + TxLoggerCondition TxLogCondition, ThreadInitFunc ThreadInit, ThreadDeinitFunc ThreadDeinit, + ThreadExitPrintStatsFunc ThreadExitPrintStats); +void OutputRegisterTxSubModuleWithCondition(LoggerId id, const char *parent_name, const char *name, + const char *conf_name, OutputInitSubFunc InitFunc, AppProto alproto, TxLogger TxLogFunc, + TxLoggerCondition TxLogCondition, ThreadInitFunc ThreadInit, ThreadDeinitFunc ThreadDeinit, + ThreadExitPrintStatsFunc ThreadExitPrintStats); + +void OutputRegisterTxModuleWithProgress(LoggerId id, const char *name, const char *conf_name, + OutputInitFunc InitFunc, AppProto alproto, TxLogger TxLogFunc, int tc_log_progress, + int ts_log_progress, ThreadInitFunc ThreadInit, ThreadDeinitFunc ThreadDeinit, + ThreadExitPrintStatsFunc ThreadExitPrintStats); +void OutputRegisterTxSubModuleWithProgress(LoggerId id, const char *parent_name, const char *name, + const char *conf_name, OutputInitSubFunc InitFunc, AppProto alproto, TxLogger TxLogFunc, + int tc_log_progress, int ts_log_progress, ThreadInitFunc ThreadInit, + ThreadDeinitFunc ThreadDeinit, ThreadExitPrintStatsFunc ThreadExitPrintStats); + +void OutputRegisterFileModule(LoggerId id, const char *name, const char *conf_name, + OutputInitFunc InitFunc, FileLogger FileLogFunc, ThreadInitFunc ThreadInit, + ThreadDeinitFunc ThreadDeinit, ThreadExitPrintStatsFunc ThreadExitPrintStats); +void OutputRegisterFileSubModule(LoggerId id, const char *parent_name, const char *name, + const char *conf_name, OutputInitSubFunc InitFunc, FileLogger FileLogFunc, + ThreadInitFunc ThreadInit, ThreadDeinitFunc ThreadDeinit, + ThreadExitPrintStatsFunc ThreadExitPrintStats); + +void OutputRegisterFiledataModule(LoggerId id, const char *name, const char *conf_name, + OutputInitFunc InitFunc, FiledataLogger FiledataLogFunc, ThreadInitFunc ThreadInit, + ThreadDeinitFunc ThreadDeinit, ThreadExitPrintStatsFunc ThreadExitPrintStats); +void OutputRegisterFiledataSubModule(LoggerId, const char *parent_name, const char *name, + const char *conf_name, OutputInitSubFunc InitFunc, FiledataLogger FiledataLogFunc, + ThreadInitFunc ThreadInit, ThreadDeinitFunc ThreadDeinit, + ThreadExitPrintStatsFunc ThreadExitPrintStats); + +void OutputRegisterFlowSubModule(LoggerId id, const char *parent_name, const char *name, + const char *conf_name, OutputInitSubFunc InitFunc, FlowLogger FlowLogFunc, + ThreadInitFunc ThreadInit, ThreadDeinitFunc ThreadDeinit, + ThreadExitPrintStatsFunc ThreadExitPrintStats); + +void OutputRegisterStreamingModule(LoggerId id, const char *name, const char *conf_name, + OutputInitFunc InitFunc, StreamingLogger StreamingLogFunc, + enum OutputStreamingType stream_type, ThreadInitFunc ThreadInit, + ThreadDeinitFunc ThreadDeinit, ThreadExitPrintStatsFunc ThreadExitPrintStats); +void OutputRegisterStreamingSubModule(LoggerId id, const char *parent_name, const char *name, + const char *conf_name, OutputInitSubFunc InitFunc, StreamingLogger StreamingLogFunc, + enum OutputStreamingType stream_type, ThreadInitFunc ThreadInit, + ThreadDeinitFunc ThreadDeinit, ThreadExitPrintStatsFunc ThreadExitPrintStats); + +void OutputRegisterStatsModule(LoggerId id, const char *name, const char *conf_name, + OutputInitFunc InitFunc, StatsLogger StatsLogFunc, ThreadInitFunc ThreadInit, + ThreadDeinitFunc ThreadDeinit, ThreadExitPrintStatsFunc ThreadExitPrintStats); +void OutputRegisterStatsSubModule(LoggerId id, const char *parent_name, const char *name, + const char *conf_name, OutputInitSubFunc InitFunc, StatsLogger StatsLogFunc, + ThreadInitFunc ThreadInit, ThreadDeinitFunc ThreadDeinit, + ThreadExitPrintStatsFunc ThreadExitPrintStats); OutputModule *OutputGetModuleByConfName(const char *name); void OutputDeregisterAll(void); @@ -194,10 +169,9 @@ void OutputRegisterFileRotationFlag(int *flag); void OutputUnregisterFileRotationFlag(int *flag); void OutputNotifyFileRotation(void); -void OutputRegisterRootLogger(ThreadInitFunc ThreadInit, - ThreadDeinitFunc ThreadDeinit, - ThreadExitPrintStatsFunc ThreadExitPrintStats, - OutputLogFunc LogFunc, OutputGetActiveCountFunc ActiveCntFunc); +void OutputRegisterRootLogger(ThreadInitFunc ThreadInit, ThreadDeinitFunc ThreadDeinit, + ThreadExitPrintStatsFunc ThreadExitPrintStats, OutputLogFunc LogFunc, + OutputGetActiveCountFunc ActiveCntFunc); void TmModuleLoggerRegister(void); TmEcode OutputLoggerLog(ThreadVars *, Packet *, void *); diff --git a/src/packet-queue.c b/src/packet-queue.c index 81c7798ef708..a145922e006f 100644 --- a/src/packet-queue.c +++ b/src/packet-queue.c @@ -43,7 +43,7 @@ void PacketQueueValidateDebug(PacketQueue *q) if (q->len == 0) { BUG_ON(q->top != NULL); BUG_ON(q->bot != NULL); - } else if(q->len == 1) { + } else if (q->len == 1) { SCLogDebug("q->top->next %p, q->top->prev %p", q->top->next, q->top->prev); SCLogDebug("q->bot->next %p, q->bot->prev %p", q->bot->next, q->bot->prev); @@ -85,22 +85,22 @@ void PacketQueueValidateDebug(PacketQueue *q) SCLogDebug("p %p, pp %p, p->next %p, p->prev %p", p, pp, p->next, p->prev); BUG_ON(pp != p->prev); } - } } -#define BUGGER_ON(cond) { \ - if ((cond)) { \ - PacketQueueValidateDebug(q); \ - } \ -} +#define BUGGER_ON(cond) \ + { \ + if ((cond)) { \ + PacketQueueValidateDebug(q); \ + } \ + } void PacketQueueValidate(PacketQueue *q) { if (q->len == 0) { BUGGER_ON(q->top != NULL); BUGGER_ON(q->bot != NULL); - } else if(q->len == 1) { + } else if (q->len == 1) { BUGGER_ON(q->top != q->bot); BUGGER_ON(q->top->next != NULL); BUGGER_ON(q->bot->next != NULL); @@ -132,14 +132,13 @@ void PacketQueueValidate(PacketQueue *q) for (p = q->top, pp = p->prev; p != NULL; pp = p, p = p->next) { BUGGER_ON(pp != p->prev); } - } } #endif /* DEBUG */ static inline void PacketEnqueueDo(PacketQueue *q, Packet *p) { - //PacketQueueValidateDebug(q); + // PacketQueueValidateDebug(q); if (p == NULL) return; @@ -150,7 +149,7 @@ static inline void PacketEnqueueDo(PacketQueue *q, Packet *p) p->next = q->top; q->top->prev = p; q->top = p; - /* only packet */ + /* only packet */ } else { p->prev = NULL; p->next = NULL; @@ -162,7 +161,7 @@ static inline void PacketEnqueueDo(PacketQueue *q, Packet *p) if (q->len > q->dbg_maxlen) q->dbg_maxlen = q->len; #endif /* DBG_PERF */ - //PacketQueueValidateDebug(q); + // PacketQueueValidateDebug(q); } void PacketEnqueueNoLock(PacketQueueNoLock *qnl, Packet *p) @@ -172,14 +171,14 @@ void PacketEnqueueNoLock(PacketQueueNoLock *qnl, Packet *p) PacketEnqueueDo(q, p); } -void PacketEnqueue (PacketQueue *q, Packet *p) +void PacketEnqueue(PacketQueue *q, Packet *p) { PacketEnqueueDo(q, p); } -static inline Packet *PacketDequeueDo (PacketQueue *q) +static inline Packet *PacketDequeueDo(PacketQueue *q) { - //PacketQueueValidateDebug(q); + // PacketQueueValidateDebug(q); /* if the queue is empty there are no packets left. */ if (q->len == 0) { return NULL; @@ -199,13 +198,13 @@ static inline Packet *PacketDequeueDo (PacketQueue *q) q->bot = NULL; } - //PacketQueueValidateDebug(q); + // PacketQueueValidateDebug(q); p->next = NULL; p->prev = NULL; return p; } -Packet *PacketDequeueNoLock (PacketQueueNoLock *qnl) +Packet *PacketDequeueNoLock(PacketQueueNoLock *qnl) { PacketQueue *q = (PacketQueue *)qnl; Packet *p = PacketDequeueDo(q); @@ -213,7 +212,7 @@ Packet *PacketDequeueNoLock (PacketQueueNoLock *qnl) return p; } -Packet *PacketDequeue (PacketQueue *q) +Packet *PacketDequeue(PacketQueue *q) { return PacketDequeueDo(q); } diff --git a/src/packet-queue.h b/src/packet-queue.h index 408987064380..a11659e792bb 100644 --- a/src/packet-queue.h +++ b/src/packet-queue.h @@ -57,15 +57,13 @@ typedef struct PacketQueue_ { SCCondT cond_q; } PacketQueue; - void PacketEnqueueNoLock(PacketQueueNoLock *qnl, struct Packet_ *p); -void PacketEnqueue (PacketQueue *, struct Packet_ *); +void PacketEnqueue(PacketQueue *, struct Packet_ *); -struct Packet_ *PacketDequeueNoLock (PacketQueueNoLock *qnl); -struct Packet_ *PacketDequeue (PacketQueue *); +struct Packet_ *PacketDequeueNoLock(PacketQueueNoLock *qnl); +struct Packet_ *PacketDequeue(PacketQueue *); PacketQueue *PacketQueueAlloc(void); void PacketQueueFree(PacketQueue *); #endif /* __PACKET_QUEUE_H__ */ - diff --git a/src/pkt-var.c b/src/pkt-var.c index a81af35e1af2..5c14f4f41c6a 100644 --- a/src/pkt-var.c +++ b/src/pkt-var.c @@ -41,7 +41,7 @@ PktVar *PktVarGet(Packet *p, uint32_t id) { PktVar *pv = p->pktvar; - for (;pv != NULL; pv = pv->next) { + for (; pv != NULL; pv = pv->next) { if (pv->id == id) return pv; } @@ -68,7 +68,7 @@ int PktVarAddKeyValue(Packet *p, uint8_t *key, uint16_t ksize, uint8_t *value, u if (p->pktvar == NULL) p->pktvar = pv; else { - while(tpv) { + while (tpv) { if (tpv->next == NULL) { tpv->next = pv; return 0; @@ -97,7 +97,7 @@ int PktVarAdd(Packet *p, uint32_t id, uint8_t *value, uint16_t size) if (p->pktvar == NULL) p->pktvar = pv; else { - while(tpv) { + while (tpv) { if (tpv->next == NULL) { tpv->next = pv; return 0; diff --git a/src/pkt-var.h b/src/pkt-var.h index 0a261c9ffaaf..ea4ec672d51f 100644 --- a/src/pkt-var.h +++ b/src/pkt-var.h @@ -30,4 +30,3 @@ PktVar *PktVarGet(Packet *, uint32_t id); void PktVarFree(PktVar *); #endif /* __PKT_VAR_H__ */ - diff --git a/src/reputation.c b/src/reputation.c index 17f43ca37178..3a01ad59a287 100644 --- a/src/reputation.c +++ b/src/reputation.c @@ -173,7 +173,7 @@ uint8_t SRepCIDRGetIPRepDst(SRepCIDRTree *cidr_ctx, Packet *p, uint8_t cat, uint * a rule/reputation reload is complete. */ void SRepReloadComplete(void) { - (void) SC_ATOMIC_ADD(srep_eversion, 1); + (void)SC_ATOMIC_ADD(srep_eversion, 1); SCLogDebug("effective Reputation version %u", SRepGetEffectiveVersion()); } @@ -189,7 +189,7 @@ void SRepFreeHostData(Host *h) * reputation initialization is complete. */ static void SRepInitComplete(void) { - (void) SC_ATOMIC_SET(srep_eversion, 1); + (void)SC_ATOMIC_SET(srep_eversion, 1); SCLogDebug("effective Reputation version %u", SRepGetEffectiveVersion()); } @@ -214,7 +214,8 @@ int SRepHostTimedOut(Host *h) SReputation *r = h->iprep; if (r->version < eversion) { SCLogDebug("host %p has reputation version %u, " - "effective version is %u", h, r->version, eversion); + "effective version is %u", + h, r->version, eversion); SRepFreeHostData(h); return 1; } @@ -225,7 +226,7 @@ int SRepHostTimedOut(Host *h) static int SRepCatSplitLine(char *line, uint8_t *cat, char *shortname, size_t shortname_len) { size_t line_len = strlen(line); - char *ptrs[2] = {NULL,NULL}; + char *ptrs[2] = { NULL, NULL }; int i = 0; int idx = 0; char *origline = line; @@ -237,7 +238,7 @@ static int SRepCatSplitLine(char *line, uint8_t *cat, char *shortname, size_t sh ptrs[idx] = line; idx++; - line += (i+1); + line += (i + 1); i = 0; if (line >= origline + line_len) @@ -264,7 +265,6 @@ static int SRepCatSplitLine(char *line, uint8_t *cat, char *shortname, size_t sh *cat = (uint8_t)c; strlcpy(shortname, ptrs[1], shortname_len); return 0; - } /** @@ -272,10 +272,11 @@ static int SRepCatSplitLine(char *line, uint8_t *cat, char *shortname, size_t sh * \retval 1 header * \retval -1 bad line */ -static int SRepSplitLine(SRepCIDRTree *cidr_ctx, char *line, Address *ip, uint8_t *cat, uint8_t *value) +static int SRepSplitLine( + SRepCIDRTree *cidr_ctx, char *line, Address *ip, uint8_t *cat, uint8_t *value) { size_t line_len = strlen(line); - char *ptrs[3] = {NULL,NULL,NULL}; + char *ptrs[3] = { NULL, NULL, NULL }; int i = 0; int idx = 0; char *origline = line; @@ -288,7 +289,7 @@ static int SRepSplitLine(SRepCIDRTree *cidr_ctx, char *line, Address *ip, uint8_ ptrs[idx] = line; idx++; - line += (i+1); + line += (i + 1); i = 0; if (line >= origline + line_len) @@ -306,7 +307,7 @@ static int SRepSplitLine(SRepCIDRTree *cidr_ctx, char *line, Address *ip, uint8_ return -1; } - //SCLogInfo("%s, %s, %s", ptrs[0], ptrs[1], ptrs[2]); + // SCLogInfo("%s, %s, %s", ptrs[0], ptrs[1], ptrs[2]); if (strcmp(ptrs[0], "ip") == 0) return 1; @@ -378,16 +379,18 @@ int SRepLoadCatFileFromFD(FILE *fp) BUG_ON(SRepGetVersion() > 0); - while(fgets(line, (int)sizeof(line), fp) != NULL) { + while (fgets(line, (int)sizeof(line), fp) != NULL) { size_t len = strlen(line); if (len == 0) continue; /* ignore comments and empty lines */ - if (line[0] == '\n' || line [0] == '\r' || line[0] == ' ' || line[0] == '#' || line[0] == '\t') + if (line[0] == '\n' || line[0] == '\r' || line[0] == ' ' || line[0] == '#' || + line[0] == '\t') continue; - while (isspace((unsigned char)line[--len])); + while (isspace((unsigned char)line[--len])) + ; /* Check if we have a trailing newline, and remove it */ len = strlen(line); @@ -432,23 +435,24 @@ static int SRepLoadFile(SRepCIDRTree *cidr_ctx, char *filename) fclose(fp); fp = NULL; return r; - } int SRepLoadFileFromFD(SRepCIDRTree *cidr_ctx, FILE *fp) { char line[8192] = ""; - while(fgets(line, (int)sizeof(line), fp) != NULL) { + while (fgets(line, (int)sizeof(line), fp) != NULL) { size_t len = strlen(line); if (len == 0) continue; /* ignore comments and empty lines */ - if (line[0] == '\n' || line [0] == '\r' || line[0] == ' ' || line[0] == '#' || line[0] == '\t') + if (line[0] == '\n' || line[0] == '\r' || line[0] == ' ' || line[0] == '#' || + line[0] == '\t') continue; - while (isspace((unsigned char)line[--len])); + while (isspace((unsigned char)line[--len])) + ; /* Check if we have a trailing newline, and remove it */ len = strlen(line); @@ -483,7 +487,7 @@ int SRepLoadFileFromFD(SRepCIDRTree *cidr_ctx, FILE *fp) SCLogError("failed to get a host, increase host.memcap"); break; } else { - //SCLogInfo("host %p", h); + // SCLogInfo("host %p", h); if (h->iprep == NULL) { h->iprep = SCCalloc(1, sizeof(SReputation)); @@ -503,8 +507,8 @@ int SRepLoadFileFromFD(SRepCIDRTree *cidr_ctx, FILE *fp) rep->version = SRepGetVersion(); rep->rep[cat] = value; - SCLogDebug("host %p iprep %p setting cat %u to value %u", - h, h->iprep, cat, value); + SCLogDebug( + "host %p iprep %p setting cat %u to value %u", h, h->iprep, cat, value); #ifdef DEBUG if (SCLogDebugEnabled()) { int i; @@ -512,8 +516,8 @@ int SRepLoadFileFromFD(SRepCIDRTree *cidr_ctx, FILE *fp) if (rep->rep[i] == 0) continue; - SCLogDebug("--> host %p iprep %p cat %d to value %u", - h, h->iprep, i, rep->rep[i]); + SCLogDebug("--> host %p iprep %p cat %d to value %u", h, h->iprep, i, + rep->rep[i]); } } #endif @@ -541,8 +545,7 @@ static char *SRepCompleteFilePath(char *file) if (PathIsRelative(file)) { if (ConfGet("default-reputation-path", &defaultpath) == 1) { SCLogDebug("Default path: %s", defaultpath); - size_t path_len = sizeof(char) * (strlen(defaultpath) + - strlen(file) + 2); + size_t path_len = sizeof(char) * (strlen(defaultpath) + strlen(file) + 2); path = SCMalloc(path_len); if (unlikely(path == NULL)) return NULL; @@ -635,13 +638,13 @@ int SRepInit(DetectEngineCtx *de_ctx) /* ok, let's load reputation files from the general config */ if (files != NULL) { - TAILQ_FOREACH(file, &files->head, next) { + TAILQ_FOREACH (file, &files->head, next) { char *sfile = SRepCompleteFilePath(file->val); if (sfile) { SCLogInfo("Loading reputation file: %s", sfile); int r = SRepLoadFile(cidr_ctx, sfile); - if (r < 0){ + if (r < 0) { if (de_ctx->failure_fatal) { exit(EXIT_FAILURE); } @@ -661,7 +664,8 @@ int SRepInit(DetectEngineCtx *de_ctx) return 0; } -void SRepDestroy(DetectEngineCtx *de_ctx) { +void SRepDestroy(DetectEngineCtx *de_ctx) +{ if (de_ctx->srepCIDR_ctx != NULL) { int i; for (i = 0; i < SREP_MAX_CATS; i++) { diff --git a/src/reputation.h b/src/reputation.h index 3ed94d985159..d2856106e650 100644 --- a/src/reputation.h +++ b/src/reputation.h @@ -30,7 +30,7 @@ #include "util-radix-tree.h" #define SREP_MAX_CATS 60 -#define SREP_MAX_VAL 127 +#define SREP_MAX_VAL 127 typedef struct SRepCIDRTree_ { SCRadixTree *srepIPV4_tree[SREP_MAX_CATS]; diff --git a/src/respond-reject-libnet11.c b/src/respond-reject-libnet11.c index 634fa3b8b545..84d3ebc88806 100644 --- a/src/respond-reject-libnet11.c +++ b/src/respond-reject-libnet11.c @@ -61,7 +61,7 @@ const char *g_reject_dev = NULL; uint16_t g_reject_dev_mtu = 0; /** set to true in main if we're setting caps. We need it here if we're using - * reject rules as libnet 1.1 is not compatible with caps. */ + * reject rules as libnet 1.1 is not compatible with caps. */ extern bool sc_set_caps; #include @@ -163,26 +163,25 @@ static inline void SetupTCP(Packet *p, Libnet11Packet *lpacket, enum RejectDirec break; } lpacket->window = TCP_GET_WINDOW(p); - //lpacket.seq += lpacket.dsize; + // lpacket.seq += lpacket.dsize; } static inline int BuildTCP(libnet_t *c, Libnet11Packet *lpacket) { /* build the package */ - if ((libnet_build_tcp( - lpacket->sp, /* source port */ - lpacket->dp, /* dst port */ - lpacket->seq, /* seq number */ - lpacket->ack, /* ack number */ - TH_RST|TH_ACK, /* flags */ - lpacket->window, /* window size */ - 0, /* checksum */ - 0, /* urgent flag */ - LIBNET_TCP_H, /* header length */ - NULL, /* payload */ - 0, /* payload length */ - c, /* libnet context */ - 0)) < 0) /* libnet ptag */ + if ((libnet_build_tcp(lpacket->sp, /* source port */ + lpacket->dp, /* dst port */ + lpacket->seq, /* seq number */ + lpacket->ack, /* ack number */ + TH_RST | TH_ACK, /* flags */ + lpacket->window, /* window size */ + 0, /* checksum */ + 0, /* urgent flag */ + LIBNET_TCP_H, /* header length */ + NULL, /* payload */ + 0, /* payload length */ + c, /* libnet context */ + 0)) < 0) /* libnet ptag */ { SCLogError("libnet_build_tcp %s", libnet_geterror(c)); return -1; @@ -192,20 +191,19 @@ static inline int BuildTCP(libnet_t *c, Libnet11Packet *lpacket) static inline int BuildIPv4(libnet_t *c, Libnet11Packet *lpacket, const uint8_t proto) { - if ((libnet_build_ipv4( - lpacket->len, /* entire packet length */ - 0, /* tos */ - lpacket->id, /* ID */ - 0, /* fragmentation flags and offset */ - lpacket->ttl, /* TTL */ - proto, /* protocol */ - 0, /* checksum */ - lpacket->src4, /* source address */ - lpacket->dst4, /* destination address */ - NULL, /* pointer to packet data (or NULL) */ - 0, /* payload length */ - c, /* libnet context pointer */ - 0)) < 0) /* packet id */ + if ((libnet_build_ipv4(lpacket->len, /* entire packet length */ + 0, /* tos */ + lpacket->id, /* ID */ + 0, /* fragmentation flags and offset */ + lpacket->ttl, /* TTL */ + proto, /* protocol */ + 0, /* checksum */ + lpacket->src4, /* source address */ + lpacket->dst4, /* destination address */ + NULL, /* pointer to packet data (or NULL) */ + 0, /* payload length */ + c, /* libnet context pointer */ + 0)) < 0) /* packet id */ { SCLogError("libnet_build_ipv4 %s", libnet_geterror(c)); return -1; @@ -215,18 +213,17 @@ static inline int BuildIPv4(libnet_t *c, Libnet11Packet *lpacket, const uint8_t static inline int BuildIPv6(libnet_t *c, Libnet11Packet *lpacket, const uint8_t proto) { - if ((libnet_build_ipv6( - lpacket->class, /* traffic class */ - lpacket->flow, /* Flow label */ - lpacket->len, /* payload length */ - proto, /* next header */ - lpacket->ttl, /* TTL */ - lpacket->src6, /* source address */ - lpacket->dst6, /* destination address */ - NULL, /* pointer to packet data (or NULL) */ - 0, /* payload length */ - c, /* libnet context pointer */ - 0)) < 0) /* packet id */ + if ((libnet_build_ipv6(lpacket->class, /* traffic class */ + lpacket->flow, /* Flow label */ + lpacket->len, /* payload length */ + proto, /* next header */ + lpacket->ttl, /* TTL */ + lpacket->src6, /* source address */ + lpacket->dst6, /* destination address */ + NULL, /* pointer to packet data (or NULL) */ + 0, /* payload length */ + c, /* libnet context pointer */ + 0)) < 0) /* packet id */ { SCLogError("libnet_build_ipv6 %s", libnet_geterror(c)); return -1; @@ -251,14 +248,15 @@ static inline void SetupEthernet(Packet *p, Libnet11Packet *lpacket, enum Reject static inline int BuildEthernet(libnet_t *c, Libnet11Packet *lpacket, uint16_t proto) { - if ((libnet_build_ethernet(lpacket->dmac,lpacket->smac, proto , NULL, 0, c, 0)) < 0) { + if ((libnet_build_ethernet(lpacket->dmac, lpacket->smac, proto, NULL, 0, c, 0)) < 0) { SCLogError("libnet_build_ethernet %s", libnet_geterror(c)); return -1; } return 0; } -static inline int BuildEthernetVLAN(libnet_t *c, Libnet11Packet *lpacket, uint16_t proto, uint16_t vlan_id) +static inline int BuildEthernetVLAN( + libnet_t *c, Libnet11Packet *lpacket, uint16_t proto, uint16_t vlan_id) { if (libnet_build_802_1q(lpacket->dmac, lpacket->smac, ETHERTYPE_VLAN, 0, 0, vlan_id, proto, NULL, /* payload */ @@ -351,7 +349,7 @@ int RejectSendLibnet11IPv4ICMP(ThreadVars *tv, Packet *p, void *data, enum Rejec if (g_reject_dev_mtu >= ETHERNET_HEADER_LEN + LIBNET_IPV4_H + 8) { lpacket.len = MIN(g_reject_dev_mtu - ETHERNET_HEADER_LEN, (LIBNET_IPV4_H + iplen)); } else { - lpacket.len = LIBNET_IPV4_H + MIN(8,iplen); // 8 bytes is the minimum we have to attach + lpacket.len = LIBNET_IPV4_H + MIN(8, iplen); // 8 bytes is the minimum we have to attach } lpacket.dsize = lpacket.len - (LIBNET_IPV4_H + LIBNET_ICMPV4_H); @@ -375,14 +373,13 @@ int RejectSendLibnet11IPv4ICMP(ThreadVars *tv, Packet *p, void *data, enum Rejec lpacket.ttl = 64; /* build the package */ - if ((libnet_build_icmpv4_unreach( - ICMP_DEST_UNREACH, /* type */ - ICMP_HOST_ANO, /* code */ - 0, /* checksum */ - (uint8_t *)p->ip4h, /* payload */ - lpacket.dsize, /* payload length */ - c, /* libnet context */ - 0)) < 0) /* libnet ptag */ + if ((libnet_build_icmpv4_unreach(ICMP_DEST_UNREACH, /* type */ + ICMP_HOST_ANO, /* code */ + 0, /* checksum */ + (uint8_t *)p->ip4h, /* payload */ + lpacket.dsize, /* payload length */ + c, /* libnet context */ + 0)) < 0) /* libnet ptag */ { SCLogError("libnet_build_icmpv4_unreach %s", libnet_geterror(c)); goto cleanup; @@ -426,7 +423,7 @@ int RejectSendLibnet11IPv6TCP(ThreadVars *tv, Packet *p, void *data, enum Reject lpacket.class = 0; if (p->tcph == NULL) - return 1; + return 1; libnet_t *c = GetCtx(p, LIBNET_RAW6); if (c == NULL) @@ -517,14 +514,13 @@ int RejectSendLibnet11IPv6ICMP(ThreadVars *tv, Packet *p, void *data, enum Rejec lpacket.ttl = 64; /* build the package */ - if ((libnet_build_icmpv6_unreach( - ICMP6_DST_UNREACH, /* type */ - ICMP6_DST_UNREACH_ADMIN, /* code */ - 0, /* checksum */ - (uint8_t *)p->ip6h, /* payload */ - lpacket.dsize, /* payload length */ - c, /* libnet context */ - 0)) < 0) /* libnet ptag */ + if ((libnet_build_icmpv6_unreach(ICMP6_DST_UNREACH, /* type */ + ICMP6_DST_UNREACH_ADMIN, /* code */ + 0, /* checksum */ + (uint8_t *)p->ip6h, /* payload */ + lpacket.dsize, /* payload length */ + c, /* libnet context */ + 0)) < 0) /* libnet ptag */ { SCLogError("libnet_build_icmpv6_unreach %s", libnet_geterror(c)); goto cleanup; @@ -555,7 +551,7 @@ int RejectSendLibnet11IPv6ICMP(ThreadVars *tv, Packet *p, void *data, enum Rejec return 0; } -#else /* HAVE_LIBNET_ICMPV6_UNREACH */ +#else /* HAVE_LIBNET_ICMPV6_UNREACH */ int RejectSendLibnet11IPv6ICMP(ThreadVars *tv, Packet *p, void *data, enum RejectDirection dir) { @@ -566,7 +562,6 @@ int RejectSendLibnet11IPv6ICMP(ThreadVars *tv, Packet *p, void *data, enum Rejec } #endif /* HAVE_LIBNET_ICMPV6_UNREACH */ - #else int RejectSendLibnet11IPv4TCP(ThreadVars *tv, Packet *p, void *data, enum RejectDirection dir) diff --git a/src/respond-reject.c b/src/respond-reject.c index b53fad9d3f31..e5e8edc9c97a 100644 --- a/src/respond-reject.c +++ b/src/respond-reject.c @@ -47,7 +47,7 @@ int RejectSendIPv6ICMP(ThreadVars *, Packet *, void *); static TmEcode RespondRejectFunc(ThreadVars *tv, Packet *p, void *data); static TmEcode RespondRejectThreadDeinit(ThreadVars *tv, void *data); -void TmModuleRespondRejectRegister (void) +void TmModuleRespondRejectRegister(void) { tmm_modules[TMM_RESPONDREJECT].name = "RespondReject"; tmm_modules[TMM_RESPONDREJECT].ThreadInit = NULL; diff --git a/src/respond-reject.h b/src/respond-reject.h index 0df165591cee..57cdeb8be681 100644 --- a/src/respond-reject.h +++ b/src/respond-reject.h @@ -24,12 +24,11 @@ #ifndef __RESPOND_REJECT_H__ #define __RESPOND_REJECT_H__ - enum RejectDirection { REJECT_DIR_SRC = 0, REJECT_DIR_DST = 1, }; -void TmModuleRespondRejectRegister (void); +void TmModuleRespondRejectRegister(void); #endif /* __RESPOND_REJECT_H__ */ diff --git a/src/runmode-af-packet.c b/src/runmode-af-packet.c index b8ad0bfac0c3..8a1528bfc199 100644 --- a/src/runmode-af-packet.c +++ b/src/runmode-af-packet.c @@ -169,7 +169,6 @@ void RunModeIdsAFPRegister(void) return; } - #ifdef HAVE_AF_PACKET static void AFPDerefConfig(void *conf) @@ -223,7 +222,7 @@ static void *ParseAFPConfig(const char *iface) strlcpy(aconf->iface, iface, sizeof(aconf->iface)); aconf->threads = 0; SC_ATOMIC_INIT(aconf->ref); - (void) SC_ATOMIC_ADD(aconf->ref, 1); + (void)SC_ATOMIC_ADD(aconf->ref, 1); aconf->buffer_size = 0; aconf->cluster_id = 1; aconf->cluster_type = cluster_type | PACKET_FANOUT_FLAG_DEFRAG; @@ -449,15 +448,15 @@ static void *ParseAFPConfig(const char *iface) #ifdef HAVE_PACKET_EBPF boolval = false; - if (ConfGetChildValueBoolWithDefault(if_root, if_default, "pinned-maps", (int *)&boolval) == 1) { + if (ConfGetChildValueBoolWithDefault(if_root, if_default, "pinned-maps", (int *)&boolval) == + 1) { if (boolval) { SCLogConfig("%s: using pinned maps", aconf->iface); aconf->ebpf_t_config.flags |= EBPF_PINNED_MAPS; } const char *pinned_maps_name = NULL; - if (ConfGetChildValueWithDefault(if_root, if_default, - "pinned-maps-name", - &pinned_maps_name) != 1) { + if (ConfGetChildValueWithDefault( + if_root, if_default, "pinned-maps-name", &pinned_maps_name) != 1) { aconf->ebpf_t_config.pinned_maps_name = pinned_maps_name; } else { aconf->ebpf_t_config.pinned_maps_name = NULL; @@ -471,8 +470,7 @@ static void *ParseAFPConfig(const char *iface) /* One shot loading of the eBPF file */ if (aconf->ebpf_lb_file && cluster_type == PACKET_FANOUT_EBPF) { int ret = EBPFLoadFile(aconf->iface, aconf->ebpf_lb_file, "loadbalancer", - &aconf->ebpf_lb_fd, - &aconf->ebpf_t_config); + &aconf->ebpf_lb_fd, &aconf->ebpf_t_config); if (ret != 0) { SCLogWarning("%s: failed to load eBPF lb file", iface); } @@ -508,8 +506,7 @@ static void *ParseAFPConfig(const char *iface) if (aconf->ebpf_filter_file) { #ifdef HAVE_PACKET_EBPF int ret = EBPFLoadFile(aconf->iface, aconf->ebpf_filter_file, "filter", - &aconf->ebpf_filter_fd, - &aconf->ebpf_t_config); + &aconf->ebpf_filter_fd, &aconf->ebpf_t_config); if (ret != 0) { SCLogWarning("%s: failed to load eBPF filter file", iface); } @@ -537,9 +534,8 @@ static void *ParseAFPConfig(const char *iface) SCLogError("%s: flow bypass alloc error", iface); } else { memcpy(ebt, &(aconf->ebpf_t_config), sizeof(struct ebpf_timeout_config)); - BypassedFlowManagerRegisterCheckFunc(NULL, - EBPFCheckBypassedFlowCreate, - (void *)ebt); + BypassedFlowManagerRegisterCheckFunc( + NULL, EBPFCheckBypassedFlowCreate, (void *)ebt); } } BypassedFlowManagerRegisterUpdateFunc(EBPFUpdateFlow, NULL); @@ -565,7 +561,8 @@ static void *ParseAFPConfig(const char *iface) } boolval = true; - if (ConfGetChildValueBoolWithDefault(if_root, if_default, "use-percpu-hash", (int *)&boolval) == 1) { + if (ConfGetChildValueBoolWithDefault( + if_root, if_default, "use-percpu-hash", (int *)&boolval) == 1) { if (boolval == false) { SCLogConfig("%s: not using percpu hash", aconf->iface); aconf->ebpf_t_config.cpus_count = 1; @@ -577,9 +574,8 @@ static void *ParseAFPConfig(const char *iface) /* One shot loading of the eBPF file */ if (aconf->xdp_filter_file) { #ifdef HAVE_PACKET_XDP - int ret = EBPFLoadFile(aconf->iface, aconf->xdp_filter_file, "xdp", - &aconf->xdp_filter_fd, - &aconf->ebpf_t_config); + int ret = EBPFLoadFile(aconf->iface, aconf->xdp_filter_file, "xdp", &aconf->xdp_filter_fd, + &aconf->ebpf_t_config); switch (ret) { case 1: SCLogInfo("%s: loaded pinned maps from sysfs", iface); @@ -594,10 +590,11 @@ static void *ParseAFPConfig(const char *iface) } else { /* Try to get the xdp-cpu-redirect key */ const char *cpuset; - if (ConfGetChildValueWithDefault(if_root, if_default, - "xdp-cpu-redirect", &cpuset) == 1) { + if (ConfGetChildValueWithDefault( + if_root, if_default, "xdp-cpu-redirect", &cpuset) == 1) { SCLogConfig("%s: Setting up CPU map XDP", iface); - ConfNode *node = ConfGetChildWithDefault(if_root, if_default, "xdp-cpu-redirect"); + ConfNode *node = + ConfGetChildWithDefault(if_root, if_default, "xdp-cpu-redirect"); if (node == NULL) { SCLogError("Previously found node has disappeared"); } else { @@ -703,7 +700,7 @@ static void *ParseAFPConfig(const char *iface) aconf->threads = 1; } SC_ATOMIC_RESET(aconf->ref); - (void) SC_ATOMIC_ADD(aconf->ref, aconf->threads); + (void)SC_ATOMIC_ADD(aconf->ref, aconf->threads); if (aconf->ring_size != 0) { if (aconf->ring_size * aconf->threads < max_pending_packets) { @@ -810,11 +807,8 @@ int RunModeIdsAFPSingle(void) FatalError("Unable to init peers list."); } - ret = RunModeSetLiveCaptureSingle(ParseAFPConfig, - AFPConfigGeThreadsCount, - "ReceiveAFP", - "DecodeAFP", thread_name_single, - live_dev); + ret = RunModeSetLiveCaptureSingle(ParseAFPConfig, AFPConfigGeThreadsCount, "ReceiveAFP", + "DecodeAFP", thread_name_single, live_dev); if (ret != 0) { FatalError("Unable to start runmode"); } diff --git a/src/runmode-erf-dag.c b/src/runmode-erf-dag.c index 503d1a15562a..7a7313b0e0fe 100644 --- a/src/runmode-erf-dag.c +++ b/src/runmode-erf-dag.c @@ -74,12 +74,8 @@ int RunModeIdsErfDagSingle(void) TimeModeSetLive(); - ret = RunModeSetLiveCaptureSingle(ParseDagConfig, - DagConfigGetThreadCount, - "ReceiveErfDag", - "DecodeErfDag", - thread_name_single, - NULL); + ret = RunModeSetLiveCaptureSingle(ParseDagConfig, DagConfigGetThreadCount, "ReceiveErfDag", + "DecodeErfDag", thread_name_single, NULL); if (ret != 0) { FatalError("DAG single runmode failed to start"); } diff --git a/src/runmode-erf-file.c b/src/runmode-erf-file.c index dc09509d0411..d85bb343c35a 100644 --- a/src/runmode-erf-file.c +++ b/src/runmode-erf-file.c @@ -63,10 +63,8 @@ int RunModeErfFileSingle(void) /* Basically the same setup as PCAP files. */ - ThreadVars *tv = TmThreadCreatePacketHandler(thread_name_single, - "packetpool", "packetpool", - "packetpool", "packetpool", - "pktacqloop"); + ThreadVars *tv = TmThreadCreatePacketHandler(thread_name_single, "packetpool", "packetpool", + "packetpool", "packetpool", "pktacqloop"); if (tv == NULL) { printf("ERROR: TmThreadsCreate failed\n"); exit(EXIT_FAILURE); @@ -141,11 +139,8 @@ int RunModeErfFileAutoFp(void) } /* create the threads */ - ThreadVars *tv = - TmThreadCreatePacketHandler(thread_name_autofp, - "packetpool", "packetpool", - queues, "flow", - "pktacqloop"); + ThreadVars *tv = TmThreadCreatePacketHandler( + thread_name_autofp, "packetpool", "packetpool", queues, "flow", "pktacqloop"); SCFree(queues); if (tv == NULL) { @@ -185,11 +180,8 @@ int RunModeErfFileAutoFp(void) SCLogDebug("Assigning %s affinity to cpu %u", tname, cpu); - ThreadVars *tv_detect_ncpu = - TmThreadCreatePacketHandler(tname, - qname, "flow", - "packetpool", "packetpool", - "varslot"); + ThreadVars *tv_detect_ncpu = TmThreadCreatePacketHandler( + tname, qname, "flow", "packetpool", "packetpool", "varslot"); if (tv_detect_ncpu == NULL) { printf("ERROR: TmThreadsCreate failed\n"); exit(EXIT_FAILURE); diff --git a/src/runmode-ipfw.c b/src/runmode-ipfw.c index de72f0623d06..ca61aed35b1f 100644 --- a/src/runmode-ipfw.c +++ b/src/runmode-ipfw.c @@ -24,8 +24,6 @@ * Handling of ipfw runmodes. */ - - #include "suricata-common.h" #include "tm-threads.h" #include "conf.h" @@ -67,10 +65,7 @@ int RunModeIpsIPFWAutoFp(void) LiveDeviceHasNoStats(); - ret = RunModeSetIPSAutoFp(IPFWGetThread, - "ReceiveIPFW", - "VerdictIPFW", - "DecodeIPFW"); + ret = RunModeSetIPSAutoFp(IPFWGetThread, "ReceiveIPFW", "VerdictIPFW", "DecodeIPFW"); #endif /* IPFW */ return ret; } @@ -85,10 +80,7 @@ int RunModeIpsIPFWWorker(void) LiveDeviceHasNoStats(); - ret = RunModeSetIPSWorker(IPFWGetThread, - "ReceiveIPFW", - "VerdictIPFW", - "DecodeIPFW"); + ret = RunModeSetIPSWorker(IPFWGetThread, "ReceiveIPFW", "VerdictIPFW", "DecodeIPFW"); #endif /* IPFW */ return ret; } diff --git a/src/runmode-napatech.c b/src/runmode-napatech.c index 3d503b965573..d59212f2a80c 100644 --- a/src/runmode-napatech.c +++ b/src/runmode-napatech.c @@ -95,7 +95,6 @@ void RunModeNapatechRegister(void) #endif } - #ifdef HAVE_NAPATECH static int NapatechRegisterDeviceStreams(void) @@ -154,8 +153,8 @@ static int NapatechRegisterDeviceStreams(void) FatalError("or disable auto-config in the conf file before running."); } } else { - SCLogInfo("Registering Napatech device: %s - active stream%sfound.", - plive_dev_buf, stream_config[inst].is_active ? " " : " NOT "); + SCLogInfo("Registering Napatech device: %s - active stream%sfound.", plive_dev_buf, + stream_config[inst].is_active ? " " : " NOT "); } LiveRegisterDevice(plive_dev_buf); @@ -181,7 +180,7 @@ static void *NapatechConfigParser(const char *device) return NULL; } - struct NapatechStreamDevConf *conf = SCCalloc(1, sizeof (struct NapatechStreamDevConf)); + struct NapatechStreamDevConf *conf = SCCalloc(1, sizeof(struct NapatechStreamDevConf)); if (unlikely(conf == NULL)) { SCLogError("Failed to allocate memory for NAPATECH device name."); return NULL; @@ -194,7 +193,7 @@ static void *NapatechConfigParser(const char *device) return NULL; } - return (void *) conf; + return (void *)conf; } static int NapatechGetThreadsCount(void *conf __attribute__((unused))) @@ -221,8 +220,7 @@ static int NapatechInit(int runmode) FatalError("Unable to find existing Napatech Streams"); } - struct NapatechStreamDevConf *conf = - SCCalloc(1, sizeof (struct NapatechStreamDevConf)); + struct NapatechStreamDevConf *conf = SCCalloc(1, sizeof(struct NapatechStreamDevConf)); if (unlikely(conf == NULL)) { FatalError("Failed to allocate memory for NAPATECH device."); } diff --git a/src/runmode-napatech.h b/src/runmode-napatech.h index d77133addaa2..029611daf54b 100644 --- a/src/runmode-napatech.h +++ b/src/runmode-napatech.h @@ -22,7 +22,6 @@ * \author Matt Keeler */ - #ifndef __RUNMODE_NAPATECH_H__ #define __RUNMODE_NAPATECH_H__ @@ -41,5 +40,4 @@ uint16_t NapatechGetNumLastStream(void); bool NapatechIsAutoConfigEnabled(void); bool NapatechUseHWBypass(void); - #endif /* __RUNMODE_NAPATECH_H__ */ diff --git a/src/runmode-netmap.c b/src/runmode-netmap.c index 927dc718856c..9938ba46c9f8 100644 --- a/src/runmode-netmap.c +++ b/src/runmode-netmap.c @@ -16,10 +16,10 @@ */ /** -* \ingroup netmap -* -* @{ -*/ + * \ingroup netmap + * + * @{ + */ /** * \file @@ -171,8 +171,8 @@ static void NetmapDerefConfig(void *conf) } } -static int ParseNetmapSettings(NetmapIfaceSettings *ns, const char *iface, - ConfNode *if_root, ConfNode *if_default) +static int ParseNetmapSettings( + NetmapIfaceSettings *ns, const char *iface, ConfNode *if_root, ConfNode *if_default) { ns->threads = 0; ns->promisc = true; @@ -182,11 +182,11 @@ static int ParseNetmapSettings(NetmapIfaceSettings *ns, const char *iface, if (ns->iface[0]) { size_t len = strlen(ns->iface); - if (ns->iface[len-1] == '+') { + if (ns->iface[len - 1] == '+') { SCLogWarning("%s: interface uses obsolete '+' notation. Using '^' instead", ns->iface); - ns->iface[len-1] = '^'; + ns->iface[len - 1] = '^'; ns->sw_ring = true; - } else if (ns->iface[len-1] == '^') { + } else if (ns->iface[len - 1] == '^') { ns->sw_ring = true; } } @@ -201,8 +201,7 @@ static int ParseNetmapSettings(NetmapIfaceSettings *ns, const char *iface, /* prefixed with netmap or vale means it's not a real interface * and we don't check offloading. */ - if (strncmp(ns->iface, "netmap:", 7) != 0 && - strncmp(ns->iface, "vale", 4) != 0) { + if (strncmp(ns->iface, "netmap:", 7) != 0 && strncmp(ns->iface, "vale", 4) != 0) { ns->real = true; } @@ -212,7 +211,7 @@ static int ParseNetmapSettings(NetmapIfaceSettings *ns, const char *iface, iface, iface); goto finalize; - /* If there is no setting for current interface use default one as main iface */ + /* If there is no setting for current interface use default one as main iface */ } else if (if_root == NULL) { if_root = if_default; if_default = NULL; @@ -245,9 +244,7 @@ static int ParseNetmapSettings(NetmapIfaceSettings *ns, const char *iface, } const char *tmpctype; - if (ConfGetChildValueWithDefault(if_root, if_default, - "checksum-checks", &tmpctype) == 1) - { + if (ConfGetChildValueWithDefault(if_root, if_default, "checksum-checks", &tmpctype) == 1) { if (strcmp(tmpctype, "auto") == 0) { ns->checksum_mode = CHECKSUM_VALIDATION_AUTO; } else if (ConfValIsTrue(tmpctype)) { @@ -260,9 +257,7 @@ static int ParseNetmapSettings(NetmapIfaceSettings *ns, const char *iface, } const char *copymodestr; - if (ConfGetChildValueWithDefault(if_root, if_default, - "copy-mode", ©modestr) == 1) - { + if (ConfGetChildValueWithDefault(if_root, if_default, "copy-mode", ©modestr) == 1) { if (strcmp(copymodestr, "ips") == 0) { ns->copy_mode = NETMAP_COPY_MODE_IPS; } else if (strcmp(copymodestr, "tap") == 0) { @@ -320,7 +315,7 @@ static void *ParseNetmapConfig(const char *iface_name) aconf->DerefFunc = NetmapDerefConfig; strlcpy(aconf->iface_name, iface_name, sizeof(aconf->iface_name)); SC_ATOMIC_INIT(aconf->ref); - (void) SC_ATOMIC_ADD(aconf->ref, 1); + (void)SC_ATOMIC_ADD(aconf->ref, 1); /* Find initial node */ ConfNode *netmap_node = ConfGetNode("netmap"); @@ -336,8 +331,7 @@ static void *ParseNetmapConfig(const char *iface_name) /* if we have a copy iface, parse that as well */ if (netmap_node != NULL && - ConfGetChildValueWithDefault(if_root, if_default, "copy-iface", &out_iface) == 1) - { + ConfGetChildValueWithDefault(if_root, if_default, "copy-iface", &out_iface) == 1) { if (strlen(out_iface) > 0) { if_root = ConfFindDeviceConfig(netmap_node, out_iface); ParseNetmapSettings(&aconf->out, out_iface, if_root, if_default); @@ -380,7 +374,7 @@ static void *ParseNetmapConfig(const char *iface_name) } SC_ATOMIC_RESET(aconf->ref); - (void) SC_ATOMIC_ADD(aconf->ref, aconf->in.threads); + (void)SC_ATOMIC_ADD(aconf->ref, aconf->in.threads); SCLogPerf("%s: using %d threads", aconf->iface_name, aconf->in.threads); LiveDeviceHasNoStats(); @@ -438,8 +432,8 @@ int RunModeIdsNetmapAutoFp(void) } /** -* \brief Single thread version of the netmap processing. -*/ + * \brief Single thread version of the netmap processing. + */ int RunModeIdsNetmapSingle(void) { return NetmapRunModeInit(NETMAP_SINGLE); @@ -474,11 +468,11 @@ int RunModeIdsNetmapSingle(void) } /** -* \brief Workers version of the netmap processing. -* -* Start N threads with each thread doing all the work. -* -*/ + * \brief Workers version of the netmap processing. + * + * Start N threads with each thread doing all the work. + * + */ int RunModeIdsNetmapWorkers(void) { SCEnter(); @@ -488,5 +482,5 @@ int RunModeIdsNetmapWorkers(void) #endif // #ifdef HAVE_NETMAP /** -* @} -*/ + * @} + */ diff --git a/src/runmode-netmap.h b/src/runmode-netmap.h index 6ba9445b086d..26194226c00c 100644 --- a/src/runmode-netmap.h +++ b/src/runmode-netmap.h @@ -16,9 +16,9 @@ */ /** \file -* -* \author Aleksey Katargin -*/ + * + * \author Aleksey Katargin + */ #ifndef __RUNMODE_NETMAP_H__ #define __RUNMODE_NETMAP_H__ diff --git a/src/runmode-nflog.c b/src/runmode-nflog.c index 28b9ae5efd64..989d4d9c784f 100644 --- a/src/runmode-nflog.c +++ b/src/runmode-nflog.c @@ -77,7 +77,7 @@ static void *ParseNflogConfig(const char *group) if (group_root == NULL && group_default == NULL) { SCLogInfo("Unable to find nflog config for " "group \"%s\" or \"default\", using default value", - group); + group); return nflogconf; } @@ -88,8 +88,7 @@ static void *ParseNflogConfig(const char *group) FatalError("NFLOG's group number invalid."); } - boolval = ConfGetChildValueIntWithDefault(group_root, group_default, - "buffer-size", &bufsize); + boolval = ConfGetChildValueIntWithDefault(group_root, group_default, "buffer-size", &bufsize); if (boolval) nflogconf->nlbufsiz = bufsize; @@ -99,8 +98,7 @@ static void *ParseNflogConfig(const char *group) return NULL; } - boolval = ConfGetChildValueIntWithDefault(group_root, group_default, - "max-size", &bufsize_max); + boolval = ConfGetChildValueIntWithDefault(group_root, group_default, "max-size", &bufsize_max); if (boolval) nflogconf->nlbufsiz_max = bufsize_max; @@ -116,8 +114,7 @@ static void *ParseNflogConfig(const char *group) nflogconf->nlbufsiz = nflogconf->nlbufsiz_max; } - boolval = ConfGetChildValueIntWithDefault(group_root, group_default, - "qthreshold", &qthreshold); + boolval = ConfGetChildValueIntWithDefault(group_root, group_default, "qthreshold", &qthreshold); if (boolval) nflogconf->qthreshold = qthreshold; @@ -127,8 +124,7 @@ static void *ParseNflogConfig(const char *group) return NULL; } - boolval = ConfGetChildValueIntWithDefault(group_root, group_default, - "qtimeout", &qtimeout); + boolval = ConfGetChildValueIntWithDefault(group_root, group_default, "qtimeout", &qtimeout); if (boolval) nflogconf->qtimeout = qtimeout; diff --git a/src/runmode-nfq.c b/src/runmode-nfq.c index d9ea93c746f3..ff4ce8fa0814 100644 --- a/src/runmode-nfq.c +++ b/src/runmode-nfq.c @@ -24,7 +24,6 @@ * Handling of NFQ runmodes. */ - #include "suricata-common.h" #include "tm-threads.h" #include "conf.h" @@ -64,10 +63,7 @@ int RunModeIpsNFQAutoFp(void) LiveDeviceHasNoStats(); - ret = RunModeSetIPSAutoFp(NFQGetThread, - "ReceiveNFQ", - "VerdictNFQ", - "DecodeNFQ"); + ret = RunModeSetIPSAutoFp(NFQGetThread, "ReceiveNFQ", "VerdictNFQ", "DecodeNFQ"); #endif /* NFQ */ return ret; } @@ -82,10 +78,7 @@ int RunModeIpsNFQWorker(void) LiveDeviceHasNoStats(); - ret = RunModeSetIPSWorker(NFQGetThread, - "ReceiveNFQ", - "VerdictNFQ", - "DecodeNFQ"); + ret = RunModeSetIPSWorker(NFQGetThread, "ReceiveNFQ", "VerdictNFQ", "DecodeNFQ"); #endif /* NFQ */ return ret; } diff --git a/src/runmode-pcap-file.c b/src/runmode-pcap-file.c index 7c5bfcc4c38a..a24dd3865e47 100644 --- a/src/runmode-pcap-file.c +++ b/src/runmode-pcap-file.c @@ -68,10 +68,8 @@ int RunModeFilePcapSingle(void) snprintf(tname, sizeof(tname), "%s#01", thread_name_single); /* create the threads */ - ThreadVars *tv = TmThreadCreatePacketHandler(tname, - "packetpool", "packetpool", - "packetpool", "packetpool", - "pktacqloop"); + ThreadVars *tv = TmThreadCreatePacketHandler( + tname, "packetpool", "packetpool", "packetpool", "packetpool", "pktacqloop"); if (tv == NULL) { FatalError("threading setup failed"); } @@ -161,11 +159,8 @@ int RunModeFilePcapAutoFp(void) snprintf(tname, sizeof(tname), "%s#01", thread_name_autofp); /* create the threads */ - ThreadVars *tv_receivepcap = - TmThreadCreatePacketHandler(tname, - "packetpool", "packetpool", - queues, "flow", - "pktacqloop"); + ThreadVars *tv_receivepcap = TmThreadCreatePacketHandler( + tname, "packetpool", "packetpool", queues, "flow", "pktacqloop"); SCFree(queues); if (tv_receivepcap == NULL) { @@ -196,11 +191,8 @@ int RunModeFilePcapAutoFp(void) SCLogDebug("tname %s, qname %s", tname, qname); SCLogDebug("Assigning %s affinity to cpu %u", tname, cpu); - ThreadVars *tv_detect_ncpu = - TmThreadCreatePacketHandler(tname, - qname, "flow", - "packetpool", "packetpool", - "varslot"); + ThreadVars *tv_detect_ncpu = TmThreadCreatePacketHandler( + tname, qname, "flow", "packetpool", "packetpool", "varslot"); if (tv_detect_ncpu == NULL) { FatalError("TmThreadsCreate failed"); } diff --git a/src/runmode-pcap.c b/src/runmode-pcap.c index 21c32846b737..5d4892d76f05 100644 --- a/src/runmode-pcap.c +++ b/src/runmode-pcap.c @@ -124,7 +124,7 @@ static void *ParsePcapConfig(const char *iface) if (if_root == NULL && if_default == NULL) { SCLogInfo("Unable to find pcap config for " "interface %s, using default value", - iface); + iface); return aconf; } @@ -149,7 +149,7 @@ static void *ParsePcapConfig(const char *iface) if (aconf->threads == 0) { aconf->threads = 1; } - (void) SC_ATOMIC_ADD(aconf->ref, aconf->threads); + (void)SC_ATOMIC_ADD(aconf->ref, aconf->threads); if (aconf->buffer_size == 0) { const char *s_limit = NULL; @@ -236,11 +236,8 @@ int RunModeIdsPcapSingle(void) (void)ConfGet("pcap.single-pcap-dev", &live_dev); - ret = RunModeSetLiveCaptureSingle(ParsePcapConfig, - PcapConfigGeThreadsCount, - "ReceivePcap", - "DecodePcap", thread_name_single, - live_dev); + ret = RunModeSetLiveCaptureSingle(ParsePcapConfig, PcapConfigGeThreadsCount, "ReceivePcap", + "DecodePcap", thread_name_single, live_dev); if (ret != 0) { FatalError("Runmode start failed"); } @@ -273,7 +270,7 @@ int RunModeIdsPcapAutoFp(void) SCEnter(); TimeModeSetLive(); - (void) ConfGet("pcap.single-pcap-dev", &live_dev); + (void)ConfGet("pcap.single-pcap-dev", &live_dev); ret = RunModeSetLiveCaptureAutoFp(ParsePcapConfig, PcapConfigGeThreadsCount, "ReceivePcap", "DecodePcap", thread_name_autofp, live_dev); @@ -300,7 +297,7 @@ int RunModeIdsPcapWorkers(void) TimeModeSetLive(); - (void) ConfGet("pcap.single-pcap-dev", &live_dev); + (void)ConfGet("pcap.single-pcap-dev", &live_dev); ret = RunModeSetLiveCaptureWorkers(ParsePcapConfig, PcapConfigGeThreadsCount, "ReceivePcap", "DecodePcap", thread_name_workers, live_dev); diff --git a/src/runmode-pfring.c b/src/runmode-pfring.c index b0af83b4bfc2..67d9740c7d1d 100644 --- a/src/runmode-pfring.c +++ b/src/runmode-pfring.c @@ -113,7 +113,7 @@ static void *OldParsePfringConfig(const char *iface) pfconf->DerefFunc = PfringDerefConfig; pfconf->checksum_mode = CHECKSUM_VALIDATION_AUTO; SC_ATOMIC_INIT(pfconf->ref); - (void) SC_ATOMIC_ADD(pfconf->ref, 1); + (void)SC_ATOMIC_ADD(pfconf->ref, 1); /* Find initial node */ if (ConfGet("pfring.threads", &threadsstr) != 1) { @@ -133,12 +133,11 @@ static void *OldParsePfringConfig(const char *iface) } SC_ATOMIC_RESET(pfconf->ref); - (void) SC_ATOMIC_ADD(pfconf->ref, pfconf->threads); + (void)SC_ATOMIC_ADD(pfconf->ref, pfconf->threads); if (strncmp(pfconf->iface, "zc", 2) == 0) { SCLogInfo("%s: ZC interface detected, not setting cluster-id", pfconf->iface); - } - else if ((pfconf->threads == 1) && (strncmp(pfconf->iface, "dna", 3) == 0)) { + } else if ((pfconf->threads == 1) && (strncmp(pfconf->iface, "dna", 3) == 0)) { SCLogInfo("DNA interface detected, not setting cluster-id"); } else if (ConfGet("pfring.cluster-id", &tmpclusterid) != 1) { SCLogError("Could not get cluster-id from config"); @@ -217,7 +216,7 @@ static void *ParsePfringConfig(const char *iface) pfconf->ctype = (cluster_type)default_ctype; pfconf->DerefFunc = PfringDerefConfig; SC_ATOMIC_INIT(pfconf->ref); - (void) SC_ATOMIC_ADD(pfconf->ref, 1); + (void)SC_ATOMIC_ADD(pfconf->ref, 1); /* Find initial node */ pf_ring_node = ConfGetNode("pfring"); @@ -234,7 +233,7 @@ static void *ParsePfringConfig(const char *iface) SCLogInfo("Unable to find pfring config for " "interface %s, using default value or 1.0 " "configuration system. ", - iface); + iface); return pfconf; } @@ -254,7 +253,8 @@ static void *ParsePfringConfig(const char *iface) } else { pfconf->threads = GetIfaceRSSQueuesNum(iface); if (pfconf->threads > 0) { - SCLogPerf("%d RSS queues, so using %u threads", pfconf->threads, pfconf->threads); + SCLogPerf( + "%d RSS queues, so using %u threads", pfconf->threads, pfconf->threads); } } } else { @@ -274,7 +274,7 @@ static void *ParsePfringConfig(const char *iface) } SC_ATOMIC_RESET(pfconf->ref); - (void) SC_ATOMIC_ADD(pfconf->ref, pfconf->threads); + (void)SC_ATOMIC_ADD(pfconf->ref, pfconf->threads); /* command line value has precedence */ if (ConfGet("pfring.cluster-id", &tmpclusterid) == 1) { @@ -285,8 +285,7 @@ static void *ParsePfringConfig(const char *iface) pfconf->cluster_id = 1; } pfconf->flags |= PFRING_CONF_FLAGS_CLUSTER; - SCLogDebug("Going to use command-line provided cluster-id %" PRId32, - pfconf->cluster_id); + SCLogDebug("Going to use command-line provided cluster-id %" PRId32, pfconf->cluster_id); } else { if (strncmp(pfconf->iface, "zc", 2) == 0) { @@ -295,7 +294,8 @@ static void *ParsePfringConfig(const char *iface) } else if ((pfconf->threads == 1) && (strncmp(pfconf->iface, "dna", 3) == 0)) { SCLogInfo("%s: DNA interface detected, not setting cluster-id for PF_RING", pfconf->iface); - } else if (ConfGetChildValueWithDefault(if_root, if_default, "cluster-id", &tmpclusterid) != 1) { + } else if (ConfGetChildValueWithDefault(if_root, if_default, "cluster-id", &tmpclusterid) != + 1) { SCLogError("Could not get cluster-id from config"); } else { if (StringParseInt32(&pfconf->cluster_id, 10, 0, (const char *)tmpclusterid) < 0) { @@ -325,7 +325,8 @@ static void *ParsePfringConfig(const char *iface) } else if ((pfconf->threads == 1) && (strncmp(pfconf->iface, "dna", 3) == 0)) { SCLogInfo("%s: DNA interface detected, not setting cluster type for PF_RING", pfconf->iface); - } else if (ConfGetChildValueWithDefault(if_root, if_default, "cluster-type", &tmpctype) != 1) { + } else if (ConfGetChildValueWithDefault(if_root, if_default, "cluster-type", &tmpctype) != + 1) { SCLogError("Could not get cluster-type from config"); } else { getctype = 1; @@ -416,7 +417,7 @@ static int PfringConfLevel(void) static int GetDevAndParser(const char **live_dev, ConfigIfaceParserFunc *parser) { - ConfGet("pfring.live-interface", live_dev); + ConfGet("pfring.live-interface", live_dev); /* determine which config type we have */ if (PfringConfLevel() > PFRING_CONF_V1) { @@ -486,11 +487,8 @@ int RunModeIdsPfringSingle(void) FatalError("Unable to get parser and interface params"); } - ret = RunModeSetLiveCaptureSingle(tparser, - PfringConfigGetThreadsCount, - "ReceivePfring", - "DecodePfring", thread_name_single, - live_dev); + ret = RunModeSetLiveCaptureSingle(tparser, PfringConfigGetThreadsCount, "ReceivePfring", + "DecodePfring", thread_name_single, live_dev); if (ret != 0) { FatalError("Runmode start failed"); } diff --git a/src/runmode-unittests.c b/src/runmode-unittests.c index 1150bad89580..68fa4e29397a 100644 --- a/src/runmode-unittests.c +++ b/src/runmode-unittests.c @@ -124,7 +124,7 @@ #endif /* UNITTESTS */ -void TmqhSetup (void); +void TmqhSetup(void); #ifdef UNITTESTS static void RegisterUnittests(void) @@ -262,7 +262,7 @@ void RunUnittests(int list_unittests, const char *regex_arg) StorageFinalize(); /* test and initialize the unit testing subsystem */ - if (regex_arg == NULL){ + if (regex_arg == NULL) { regex_arg = ".*"; UtRunSelftest(regex_arg); /* inits and cleans up again */ } diff --git a/src/runmode-unittests.h b/src/runmode-unittests.h index 928e22bd5ed6..2ae310eee66a 100644 --- a/src/runmode-unittests.h +++ b/src/runmode-unittests.h @@ -20,11 +20,9 @@ * \author Eric Leblond */ - #ifndef __UTIL_RUNMODE_UNITTESTS_H__ #define __UTIL_RUNMODE_UNITTESTS_H__ -__attribute__((noreturn)) -void RunUnittests(int list_unittests, const char *regex_arg); +__attribute__((noreturn)) void RunUnittests(int list_unittests, const char *regex_arg); #endif /* __UTIL_RUNMODE_UNITTESTS_H__ */ diff --git a/src/runmode-unix-socket.c b/src/runmode-unix-socket.c index 099d56cbda2d..edd0edc7d6bc 100644 --- a/src/runmode-unix-socket.c +++ b/src/runmode-unix-socket.c @@ -89,47 +89,18 @@ const char *RunModeUnixSocketGetDefaultMode(void) #define MEMCAPS_MAX 7 static MemcapCommand memcaps[MEMCAPS_MAX] = { { - "stream", - StreamTcpSetMemcap, - StreamTcpGetMemcap, - StreamTcpMemuseCounter, - }, - { - "stream-reassembly", - StreamTcpReassembleSetMemcap, - StreamTcpReassembleGetMemcap, - StreamTcpReassembleMemuseGlobalCounter - }, - { - "flow", - FlowSetMemcap, - FlowGetMemcap, - FlowGetMemuse - }, - { - "applayer-proto-http", - HTPSetMemcap, - HTPGetMemcap, - HTPMemuseGlobalCounter - }, - { - "defrag", - DefragTrackerSetMemcap, - DefragTrackerGetMemcap, - DefragTrackerGetMemuse - }, - { - "ippair", - IPPairSetMemcap, - IPPairGetMemcap, - IPPairGetMemuse - }, - { - "host", - HostSetMemcap, - HostGetMemcap, - HostGetMemuse + "stream", + StreamTcpSetMemcap, + StreamTcpGetMemcap, + StreamTcpMemuseCounter, }, + { "stream-reassembly", StreamTcpReassembleSetMemcap, StreamTcpReassembleGetMemcap, + StreamTcpReassembleMemuseGlobalCounter }, + { "flow", FlowSetMemcap, FlowGetMemcap, FlowGetMemuse }, + { "applayer-proto-http", HTPSetMemcap, HTPGetMemcap, HTPMemuseGlobalCounter }, + { "defrag", DefragTrackerSetMemcap, DefragTrackerGetMemcap, DefragTrackerGetMemuse }, + { "ippair", IPPairSetMemcap, IPPairGetMemcap, IPPairGetMemuse }, + { "host", HostSetMemcap, HostGetMemcap, HostGetMemuse }, }; float MemcapsGetPressure(void) @@ -162,9 +133,9 @@ static SCCtrlMutex unix_manager_pcap_last_processed_mutex; * * \retval 0 in case of error, 1 in case of success */ -static TmEcode UnixSocketPcapFilesList(json_t *cmd, json_t* answer, void *data) +static TmEcode UnixSocketPcapFilesList(json_t *cmd, json_t *answer, void *data) { - PcapCommand *this = (PcapCommand *) data; + PcapCommand *this = (PcapCommand *)data; int i = 0; PcapFiles *file; json_t *jdata; @@ -172,18 +143,18 @@ static TmEcode UnixSocketPcapFilesList(json_t *cmd, json_t* answer, void *data) jdata = json_object(); if (jdata == NULL) { - json_object_set_new(answer, "message", - json_string("internal error at json object creation")); + json_object_set_new( + answer, "message", json_string("internal error at json object creation")); return TM_ECODE_FAILED; } jarray = json_array(); if (jarray == NULL) { json_decref(jdata); - json_object_set_new(answer, "message", - json_string("internal error at json object creation")); + json_object_set_new( + answer, "message", json_string("internal error at json object creation")); return TM_ECODE_FAILED; } - TAILQ_FOREACH(file, &this->files, next) { + TAILQ_FOREACH (file, &this->files, next) { json_array_append_new(jarray, SCJsonString(file->filename)); i++; } @@ -193,26 +164,25 @@ static TmEcode UnixSocketPcapFilesList(json_t *cmd, json_t* answer, void *data) return TM_ECODE_OK; } -static TmEcode UnixSocketPcapFilesNumber(json_t *cmd, json_t* answer, void *data) +static TmEcode UnixSocketPcapFilesNumber(json_t *cmd, json_t *answer, void *data) { - PcapCommand *this = (PcapCommand *) data; + PcapCommand *this = (PcapCommand *)data; int i = 0; PcapFiles *file; - TAILQ_FOREACH(file, &this->files, next) { + TAILQ_FOREACH (file, &this->files, next) { i++; } json_object_set_new(answer, "message", json_integer(i)); return TM_ECODE_OK; } -static TmEcode UnixSocketPcapCurrent(json_t *cmd, json_t* answer, void *data) +static TmEcode UnixSocketPcapCurrent(json_t *cmd, json_t *answer, void *data) { - PcapCommand *this = (PcapCommand *) data; + PcapCommand *this = (PcapCommand *)data; if (this->current_file != NULL && this->current_file->filename != NULL) { - json_object_set_new(answer, "message", - json_string(this->current_file->filename)); + json_object_set_new(answer, "message", json_string(this->current_file->filename)); } else { json_object_set_new(answer, "message", json_string("None")); } @@ -226,8 +196,7 @@ static TmEcode UnixSocketPcapLastProcessed(json_t *cmd, json_t *answer, void *da epoch_millis = SCTimespecAsEpochMillis(&unix_manager_pcap_last_processed); SCCtrlMutexUnlock(&unix_manager_pcap_last_processed_mutex); - json_object_set_new(answer, "message", - json_integer(epoch_millis)); + json_object_set_new(answer, "message", json_integer(epoch_millis)); return TM_ECODE_OK; } @@ -313,10 +282,9 @@ static TmEcode UnixListAddFile(PcapCommand *this, const char *filename, const ch * \param data pointer to data defining the context here a PcapCommand:: * \param continuous If this should run in continuous mode */ -static TmEcode UnixSocketAddPcapFileImpl(json_t *cmd, json_t* answer, void *data, - bool continuous) +static TmEcode UnixSocketAddPcapFileImpl(json_t *cmd, json_t *answer, void *data, bool continuous) { - PcapCommand *this = (PcapCommand *) data; + PcapCommand *this = (PcapCommand *)data; const char *filename; const char *output_dir; uint32_t tenant_id = 0; @@ -328,14 +296,12 @@ static TmEcode UnixSocketAddPcapFileImpl(json_t *cmd, json_t* answer, void *data json_t *jarg = json_object_get(cmd, "filename"); if (!json_is_string(jarg)) { SCLogError("filename is not a string"); - json_object_set_new(answer, "message", - json_string("filename is not a string")); + json_object_set_new(answer, "message", json_string("filename is not a string")); return TM_ECODE_FAILED; } filename = json_string_value(jarg); if (SCStatFn(filename, &st) != 0) { - json_object_set_new(answer, "message", - json_string("filename does not exist")); + json_object_set_new(answer, "message", json_string("filename does not exist")); return TM_ECODE_FAILED; } @@ -344,30 +310,26 @@ static TmEcode UnixSocketAddPcapFileImpl(json_t *cmd, json_t* answer, void *data if (!json_is_string(oarg)) { SCLogError("output-dir is not a string"); - json_object_set_new(answer, "message", - json_string("output-dir is not a string")); + json_object_set_new(answer, "message", json_string("output-dir is not a string")); return TM_ECODE_FAILED; } output_dir = json_string_value(oarg); } else { SCLogError("can't get output-dir"); - json_object_set_new(answer, "message", - json_string("output-dir param is mandatory")); + json_object_set_new(answer, "message", json_string("output-dir param is mandatory")); return TM_ECODE_FAILED; } if (SCStatFn(output_dir, &st) != 0) { - json_object_set_new(answer, "message", - json_string("output-dir does not exist")); + json_object_set_new(answer, "message", json_string("output-dir does not exist")); return TM_ECODE_FAILED; } json_t *targ = json_object_get(cmd, "tenant"); if (targ != NULL) { if (!json_is_integer(targ)) { - json_object_set_new(answer, "message", - json_string("tenant is not a number")); + json_object_set_new(answer, "message", json_string("tenant is not a number")); return TM_ECODE_FAILED; } tenant_id = json_number_value(targ); @@ -382,8 +344,7 @@ static TmEcode UnixSocketAddPcapFileImpl(json_t *cmd, json_t* answer, void *data if (delay_arg != NULL) { if (!json_is_integer(delay_arg)) { SCLogError("delay is not a integer"); - json_object_set_new(answer, "message", - json_string("delay is not a integer")); + json_object_set_new(answer, "message", json_string("delay is not a integer")); return TM_ECODE_FAILED; } delay = json_integer_value(delay_arg); @@ -394,24 +355,21 @@ static TmEcode UnixSocketAddPcapFileImpl(json_t *cmd, json_t* answer, void *data if (!json_is_integer(interval_arg)) { SCLogError("poll-interval is not a integer"); - json_object_set_new(answer, "message", - json_string("poll-interval is not a integer")); + json_object_set_new(answer, "message", json_string("poll-interval is not a integer")); return TM_ECODE_FAILED; } poll_interval = json_integer_value(interval_arg); } - switch (UnixListAddFile(this, filename, output_dir, tenant_id, continuous, - should_delete, delay, poll_interval)) { + switch (UnixListAddFile(this, filename, output_dir, tenant_id, continuous, should_delete, delay, + poll_interval)) { case TM_ECODE_FAILED: case TM_ECODE_DONE: - json_object_set_new(answer, "message", - json_string("Unable to add file to list")); + json_object_set_new(answer, "message", json_string("Unable to add file to list")); return TM_ECODE_FAILED; case TM_ECODE_OK: SCLogInfo("Added file '%s' to list", filename); - json_object_set_new(answer, "message", - json_string("Successfully added file to list")); + json_object_set_new(answer, "message", json_string("Successfully added file to list")); return TM_ECODE_OK; } return TM_ECODE_OK; @@ -424,7 +382,7 @@ static TmEcode UnixSocketAddPcapFileImpl(json_t *cmd, json_t* answer, void *data * \param answer the json_t object that has to be used to answer * \param data pointer to data defining the context here a PcapCommand:: */ -static TmEcode UnixSocketAddPcapFile(json_t *cmd, json_t* answer, void *data) +static TmEcode UnixSocketAddPcapFile(json_t *cmd, json_t *answer, void *data) { bool continuous = false; @@ -443,7 +401,7 @@ static TmEcode UnixSocketAddPcapFile(json_t *cmd, json_t* answer, void *data) * \param answer the json_t object that has to be used to answer * \param data pointer to data defining the context here a PcapCommand:: */ -static TmEcode UnixSocketAddPcapFileContinuous(json_t *cmd, json_t* answer, void *data) +static TmEcode UnixSocketAddPcapFileContinuous(json_t *cmd, json_t *answer, void *data) { return UnixSocketAddPcapFileImpl(cmd, answer, data, true); } @@ -463,7 +421,7 @@ static TmEcode UnixSocketAddPcapFileContinuous(json_t *cmd, json_t* answer, void */ static TmEcode UnixSocketPcapFilesCheck(void *data) { - PcapCommand *this = (PcapCommand *) data; + PcapCommand *this = (PcapCommand *)data; if (unix_manager_pcap_task_running == 1) { return TM_ECODE_OK; } @@ -593,7 +551,7 @@ void RunModeUnixSocketRegister(void) TmEcode UnixSocketPcapFile(TmEcode tm, struct timespec *last_processed) { #ifdef BUILD_UNIX_SOCKET - if(last_processed) { + if (last_processed) { SCCtrlMutexLock(&unix_manager_pcap_last_processed_mutex); unix_manager_pcap_last_processed.tv_sec = last_processed->tv_sec; unix_manager_pcap_last_processed.tv_nsec = last_processed->tv_nsec; @@ -608,7 +566,7 @@ TmEcode UnixSocketPcapFile(TmEcode tm, struct timespec *last_processed) SCLogInfo("Marking current task as failed"); unix_manager_pcap_task_running = 0; unix_manager_pcap_task_failed = 1; - //if we return failed, we can't stop the thread and suricata will fail to close + // if we return failed, we can't stop the thread and suricata will fail to close return TM_ECODE_FAILED; case TM_ECODE_OK: if (unix_manager_pcap_task_interrupted == 1) { @@ -631,7 +589,7 @@ TmEcode UnixSocketPcapFile(TmEcode tm, struct timespec *last_processed) * \param answer the json_t object that has to be used to answer * \param data pointer to data defining the context here a PcapCommand:: */ -TmEcode UnixSocketDatasetAdd(json_t *cmd, json_t* answer, void *data) +TmEcode UnixSocketDatasetAdd(json_t *cmd, json_t *answer, void *data) { /* 1 get dataset name */ json_t *narg = json_object_get(cmd, "setname"); @@ -684,7 +642,7 @@ TmEcode UnixSocketDatasetAdd(json_t *cmd, json_t* answer, void *data) } } -TmEcode UnixSocketDatasetRemove(json_t *cmd, json_t* answer, void *data) +TmEcode UnixSocketDatasetRemove(json_t *cmd, json_t *answer, void *data) { /* 1 get dataset name */ json_t *narg = json_object_get(cmd, "setname"); @@ -838,7 +796,7 @@ TmEcode UnixSocketDatasetLookup(json_t *cmd, json_t *answer, void *data) * \param answer the json_t object that has to be used to answer * \param data pointer to data defining the context here a PcapCommand:: */ -TmEcode UnixSocketRegisterTenantHandler(json_t *cmd, json_t* answer, void *data) +TmEcode UnixSocketRegisterTenantHandler(json_t *cmd, json_t *answer, void *data) { const char *htype; json_int_t traffic_id = -1; @@ -919,7 +877,7 @@ TmEcode UnixSocketRegisterTenantHandler(json_t *cmd, json_t* answer, void *data) * \param answer the json_t object that has to be used to answer * \param data pointer to data defining the context here a PcapCommand:: */ -TmEcode UnixSocketUnregisterTenantHandler(json_t *cmd, json_t* answer, void *data) +TmEcode UnixSocketUnregisterTenantHandler(json_t *cmd, json_t *answer, void *data) { const char *htype; json_int_t traffic_id = -1; @@ -975,7 +933,8 @@ TmEcode UnixSocketUnregisterTenantHandler(json_t *cmd, json_t* answer, void *dat return TM_ECODE_FAILED; } - SCLogInfo("VLAN handler: removing mapping of %u to tenant %u", (uint32_t)traffic_id, tenant_id); + SCLogInfo("VLAN handler: removing mapping of %u to tenant %u", (uint32_t)traffic_id, + tenant_id); r = DetectEngineTenantUnregisterVlanId(tenant_id, (uint16_t)traffic_id); } if (r != 0) { @@ -1001,7 +960,7 @@ TmEcode UnixSocketUnregisterTenantHandler(json_t *cmd, json_t* answer, void *dat * \param answer the json_t object that has to be used to answer * \param data pointer to data defining the context here a PcapCommand:: */ -TmEcode UnixSocketRegisterTenant(json_t *cmd, json_t* answer, void *data) +TmEcode UnixSocketRegisterTenant(json_t *cmd, json_t *answer, void *data) { const char *filename; SCStat st; @@ -1069,7 +1028,7 @@ static int reload_cnt = 1; * \param answer the json_t object that has to be used to answer * \param data pointer to data defining the context here a PcapCommand:: */ -TmEcode UnixSocketReloadTenant(json_t *cmd, json_t* answer, void *data) +TmEcode UnixSocketReloadTenant(json_t *cmd, json_t *answer, void *data) { const char *filename = NULL; SCStat st; @@ -1165,7 +1124,7 @@ TmEcode UnixSocketReloadTenants(json_t *cmd, json_t *answer, void *data) * \param answer the json_t object that has to be used to answer * \param data pointer to data defining the context here a PcapCommand:: */ -TmEcode UnixSocketUnregisterTenant(json_t *cmd, json_t* answer, void *data) +TmEcode UnixSocketUnregisterTenant(json_t *cmd, json_t *answer, void *data) { if (!(DetectEngineMultiTenantEnabled())) { SCLogInfo("error: multi-tenant support not enabled"); @@ -1218,7 +1177,7 @@ TmEcode UnixSocketUnregisterTenant(json_t *cmd, json_t* answer, void *data) * \param cmd the content of command Arguments as a json_t object * \param answer the json_t object that has to be used to answer */ -TmEcode UnixSocketHostbitAdd(json_t *cmd, json_t* answer, void *data_usused) +TmEcode UnixSocketHostbitAdd(json_t *cmd, json_t *answer, void *data_usused) { /* 1 get ip address */ json_t *jarg = json_object_get(cmd, "ipaddress"); @@ -1295,7 +1254,7 @@ TmEcode UnixSocketHostbitAdd(json_t *cmd, json_t* answer, void *data_usused) * \param cmd the content of command Arguments as a json_t object * \param answer the json_t object that has to be used to answer */ -TmEcode UnixSocketHostbitRemove(json_t *cmd, json_t* answer, void *data_unused) +TmEcode UnixSocketHostbitRemove(json_t *cmd, json_t *answer, void *data_unused) { /* 1 get ip address */ json_t *jarg = json_object_get(cmd, "ipaddress"); @@ -1364,11 +1323,12 @@ TmEcode UnixSocketHostbitRemove(json_t *cmd, json_t* answer, void *data_unused) * \param answer the json_t object that has to be used to answer * * Message looks like: - * {"message": {"count": 1, "hostbits": [{"expire": 3222, "name": "firefox-users"}]}, "return": "OK"} + * {"message": {"count": 1, "hostbits": [{"expire": 3222, "name": "firefox-users"}]}, "return": + * "OK"} * * \retval r TM_ECODE_OK or TM_ECODE_FAILED */ -TmEcode UnixSocketHostbitList(json_t *cmd, json_t* answer, void *data_unused) +TmEcode UnixSocketHostbitList(json_t *cmd, json_t *answer, void *data_unused) { /* 1 get ip address */ json_t *jarg = json_object_get(cmd, "ipaddress"); @@ -1434,8 +1394,8 @@ TmEcode UnixSocketHostbitList(json_t *cmd, json_t* answer, void *data_unused) json_decref(jdata); if (jarray != NULL) json_decref(jarray); - json_object_set_new(answer, "message", - json_string("internal error at json object creation")); + json_object_set_new( + answer, "message", json_string("internal error at json object creation")); return TM_ECODE_FAILED; } @@ -1465,15 +1425,15 @@ TmEcode UnixSocketHostbitList(json_t *cmd, json_t* answer, void *data_unused) static void MemcapBuildValue(uint64_t val, char *str, uint32_t str_len) { if ((val / (1024 * 1024 * 1024)) != 0) { - snprintf(str, str_len, "%"PRIu64"gb", val / (1024*1024*1024)); + snprintf(str, str_len, "%" PRIu64 "gb", val / (1024 * 1024 * 1024)); } else if ((val / (1024 * 1024)) != 0) { - snprintf(str, str_len, "%"PRIu64"mb", val / (1024*1024)); + snprintf(str, str_len, "%" PRIu64 "mb", val / (1024 * 1024)); } else { - snprintf(str, str_len, "%"PRIu64"kb", val / (1024)); + snprintf(str, str_len, "%" PRIu64 "kb", val / (1024)); } } -TmEcode UnixSocketSetMemcap(json_t *cmd, json_t* answer, void *data) +TmEcode UnixSocketSetMemcap(json_t *cmd, json_t *answer, void *data) { char *memcap = NULL; char *value_str = NULL; @@ -1499,8 +1459,8 @@ TmEcode UnixSocketSetMemcap(json_t *cmd, json_t* answer, void *data) "memcap from unix socket: %s", value_str); json_object_set_new(answer, "message", - json_string("error parsing memcap specified, " - "value not changed")); + json_string("error parsing memcap specified, " + "value not changed")); return TM_ECODE_FAILED; } @@ -1510,27 +1470,26 @@ TmEcode UnixSocketSetMemcap(json_t *cmd, json_t* answer, void *data) char message[150]; if (updated) { - snprintf(message, sizeof(message), - "memcap value for '%s' updated: %"PRIu64" %s", - memcaps[i].name, value, - (value == 0) ? "(unlimited)" : ""); + snprintf(message, sizeof(message), "memcap value for '%s' updated: %" PRIu64 " %s", + memcaps[i].name, value, (value == 0) ? "(unlimited)" : ""); json_object_set_new(answer, "message", json_string(message)); return TM_ECODE_OK; } else { if (value == 0) { - snprintf(message, sizeof(message), - "Unlimited value is not allowed for '%s'", memcaps[i].name); + snprintf(message, sizeof(message), "Unlimited value is not allowed for '%s'", + memcaps[i].name); } else { if (memcaps[i].GetMemuseFunc()) { char memuse[50]; MemcapBuildValue(memcaps[i].GetMemuseFunc(), memuse, sizeof(memuse)); snprintf(message, sizeof(message), - "memcap value specified for '%s' is less than the memory in use: %s", - memcaps[i].name, memuse); + "memcap value specified for '%s' is less than the memory in use: " + "%s", + memcaps[i].name, memuse); } else { snprintf(message, sizeof(message), - "memcap value specified for '%s' is less than the memory in use", - memcaps[i].name); + "memcap value specified for '%s' is less than the memory in use", + memcaps[i].name); } } json_object_set_new(answer, "message", json_string(message)); @@ -1540,7 +1499,7 @@ TmEcode UnixSocketSetMemcap(json_t *cmd, json_t* answer, void *data) } json_object_set_new(answer, "message", - json_string("Memcap value not found. Use 'memcap-list' to show all")); + json_string("Memcap value not found. Use 'memcap-list' to show all")); return TM_ECODE_FAILED; } @@ -1562,8 +1521,8 @@ TmEcode UnixSocketShowMemcap(json_t *cmd, json_t *answer, void *data) uint64_t val = memcaps[i].GetFunc(); json_t *jobj = json_object(); if (jobj == NULL) { - json_object_set_new(answer, "message", - json_string("internal error at json object creation")); + json_object_set_new( + answer, "message", json_string("internal error at json object creation")); return TM_ECODE_FAILED; } @@ -1580,7 +1539,7 @@ TmEcode UnixSocketShowMemcap(json_t *cmd, json_t *answer, void *data) } json_object_set_new(answer, "message", - json_string("Memcap value not found. Use 'memcap-list' to show all")); + json_string("Memcap value not found. Use 'memcap-list' to show all")); return TM_ECODE_FAILED; } @@ -1590,8 +1549,8 @@ TmEcode UnixSocketShowAllMemcap(json_t *cmd, json_t *answer, void *data) int i; if (jmemcaps == NULL) { - json_object_set_new(answer, "message", - json_string("internal error at json array creation")); + json_object_set_new( + answer, "message", json_string("internal error at json array creation")); return TM_ECODE_FAILED; } @@ -1599,8 +1558,8 @@ TmEcode UnixSocketShowAllMemcap(json_t *cmd, json_t *answer, void *data) json_t *jobj = json_object(); if (jobj == NULL) { json_decref(jmemcaps); - json_object_set_new(answer, "message", - json_string("internal error at json object creation")); + json_object_set_new( + answer, "message", json_string("internal error at json object creation")); return TM_ECODE_FAILED; } char str[50]; @@ -1681,7 +1640,8 @@ static int RunModeUnixSocketMaster(void) SCCtrlMutexInit(&unix_manager_pcap_last_processed_mutex, NULL); UnixManagerRegisterCommand("pcap-file", UnixSocketAddPcapFile, pcapcmd, UNIX_CMD_TAKE_ARGS); - UnixManagerRegisterCommand("pcap-file-continuous", UnixSocketAddPcapFileContinuous, pcapcmd, UNIX_CMD_TAKE_ARGS); + UnixManagerRegisterCommand( + "pcap-file-continuous", UnixSocketAddPcapFileContinuous, pcapcmd, UNIX_CMD_TAKE_ARGS); UnixManagerRegisterCommand("pcap-file-number", UnixSocketPcapFilesNumber, pcapcmd, 0); UnixManagerRegisterCommand("pcap-file-list", UnixSocketPcapFilesList, pcapcmd, 0); UnixManagerRegisterCommand("pcap-last-processed", UnixSocketPcapLastProcessed, pcapcmd, 0); @@ -1701,7 +1661,3 @@ int RunModeUnixSocketIsActive(void) { return unix_socket_mode_is_running; } - - - - diff --git a/src/runmode-unix-socket.h b/src/runmode-unix-socket.h index af0651f5910b..0366af945649 100644 --- a/src/runmode-unix-socket.h +++ b/src/runmode-unix-socket.h @@ -33,21 +33,21 @@ TmEcode UnixSocketPcapFile(TmEcode tm, struct timespec *last_processed); float MemcapsGetPressure(void); #ifdef BUILD_UNIX_SOCKET -TmEcode UnixSocketDatasetAdd(json_t *cmd, json_t* answer, void *data); -TmEcode UnixSocketDatasetRemove(json_t *cmd, json_t* answer, void *data); +TmEcode UnixSocketDatasetAdd(json_t *cmd, json_t *answer, void *data); +TmEcode UnixSocketDatasetRemove(json_t *cmd, json_t *answer, void *data); TmEcode UnixSocketDatasetDump(json_t *cmd, json_t *answer, void *data); TmEcode UnixSocketDatasetClear(json_t *cmd, json_t *answer, void *data); TmEcode UnixSocketDatasetLookup(json_t *cmd, json_t *answer, void *data); -TmEcode UnixSocketRegisterTenantHandler(json_t *cmd, json_t* answer, void *data); -TmEcode UnixSocketUnregisterTenantHandler(json_t *cmd, json_t* answer, void *data); -TmEcode UnixSocketRegisterTenant(json_t *cmd, json_t* answer, void *data); -TmEcode UnixSocketReloadTenant(json_t *cmd, json_t* answer, void *data); +TmEcode UnixSocketRegisterTenantHandler(json_t *cmd, json_t *answer, void *data); +TmEcode UnixSocketUnregisterTenantHandler(json_t *cmd, json_t *answer, void *data); +TmEcode UnixSocketRegisterTenant(json_t *cmd, json_t *answer, void *data); +TmEcode UnixSocketReloadTenant(json_t *cmd, json_t *answer, void *data); TmEcode UnixSocketReloadTenants(json_t *cmd, json_t *answer, void *data); -TmEcode UnixSocketUnregisterTenant(json_t *cmd, json_t* answer, void *data); -TmEcode UnixSocketHostbitAdd(json_t *cmd, json_t* answer, void *data); -TmEcode UnixSocketHostbitRemove(json_t *cmd, json_t* answer, void *data); -TmEcode UnixSocketHostbitList(json_t *cmd, json_t* answer, void *data); -TmEcode UnixSocketSetMemcap(json_t *cmd, json_t* answer, void *data); +TmEcode UnixSocketUnregisterTenant(json_t *cmd, json_t *answer, void *data); +TmEcode UnixSocketHostbitAdd(json_t *cmd, json_t *answer, void *data); +TmEcode UnixSocketHostbitRemove(json_t *cmd, json_t *answer, void *data); +TmEcode UnixSocketHostbitList(json_t *cmd, json_t *answer, void *data); +TmEcode UnixSocketSetMemcap(json_t *cmd, json_t *answer, void *data); TmEcode UnixSocketShowMemcap(json_t *cmd, json_t *answer, void *data); TmEcode UnixSocketShowAllMemcap(json_t *cmd, json_t *answer, void *data); TmEcode UnixSocketGetFlowStatsById(json_t *cmd, json_t *answer, void *data); diff --git a/src/runmode-windivert.c b/src/runmode-windivert.c index a4514270e964..0d604440bc2d 100644 --- a/src/runmode-windivert.c +++ b/src/runmode-windivert.c @@ -58,8 +58,8 @@ int RunModeIpsWinDivertAutoFp(void) LiveDeviceHasNoStats(); - ret = RunModeSetIPSAutoFp(WinDivertGetThread, "ReceiveWinDivert", - "VerdictWinDivert", "DecodeWinDivert"); + ret = RunModeSetIPSAutoFp( + WinDivertGetThread, "ReceiveWinDivert", "VerdictWinDivert", "DecodeWinDivert"); #endif /* WINDIVERT */ return ret; } diff --git a/src/runmodes.c b/src/runmodes.c index 852155332d75..8d36b539676e 100644 --- a/src/runmodes.c +++ b/src/runmodes.c @@ -117,8 +117,7 @@ typedef struct OutputFreeList_ { TAILQ_ENTRY(OutputFreeList_) entries; } OutputFreeList; -static TAILQ_HEAD(, OutputFreeList_) output_free_list = - TAILQ_HEAD_INITIALIZER(output_free_list); +static TAILQ_HEAD(, OutputFreeList_) output_free_list = TAILQ_HEAD_INITIALIZER(output_free_list); /** * \internal @@ -206,7 +205,6 @@ static RunMode *RunModeGetCustomMode(enum RunModes runmode, const char *custom_m return NULL; } - /** * Return the running mode * @@ -269,29 +267,23 @@ void RunModeListRunmodes(void) printf("------------------------------------- Runmodes -------------------" "-----------------------\n"); - printf("| %-17s | %-17s | %-10s \n", - "RunMode Type", "Custom Mode ", "Description"); + printf("| %-17s | %-17s | %-10s \n", "RunMode Type", "Custom Mode ", "Description"); printf("|-----------------------------------------------------------------" "-----------------------\n"); int i = RUNMODE_UNKNOWN + 1; int j = 0; - for ( ; i < RUNMODE_USER_MAX; i++) { + for (; i < RUNMODE_USER_MAX; i++) { int mode_displayed = 0; for (j = 0; j < runmodes[i].cnt; j++) { if (mode_displayed == 1) { printf("| ----------------------------------------------" "-----------------------\n"); RunMode *runmode = &runmodes[i].runmodes[j]; - printf("| %-17s | %-17s | %-27s \n", - "", - runmode->name, - runmode->description); + printf("| %-17s | %-17s | %-27s \n", "", runmode->name, runmode->description); } else { RunMode *runmode = &runmodes[i].runmodes[j]; - printf("| %-17s | %-17s | %-27s \n", - RunModeTranslateModeToName(runmode->runmode), - runmode->name, - runmode->description); + printf("| %-17s | %-17s | %-27s \n", RunModeTranslateModeToName(runmode->runmode), + runmode->name, runmode->description); } if (mode_displayed == 0) mode_displayed = 1; @@ -477,8 +469,6 @@ int RunModeNeedsBypassManager(void) return g_runmode_needs_bypass; } - - /** * \brief Registers a new runmode. * @@ -497,8 +487,8 @@ void RunModeRegisterNewRunMode(enum RunModes runmode, const char *name, const ch name); } - void *ptmp = SCRealloc(runmodes[runmode].runmodes, - (runmodes[runmode].cnt + 1) * sizeof(RunMode)); + void *ptmp = + SCRealloc(runmodes[runmode].runmodes, (runmodes[runmode].cnt + 1) * sizeof(RunMode)); if (ptmp == NULL) { SCFree(runmodes[runmode].runmodes); runmodes[runmode].runmodes = NULL; @@ -573,7 +563,7 @@ bool IsRunModeSystem(enum RunModes run_mode_to_check) bool IsRunModeOffline(enum RunModes run_mode_to_check) { - switch(run_mode_to_check) { + switch (run_mode_to_check) { case RUNMODE_CONF_TEST: case RUNMODE_PCAP_FILE: case RUNMODE_ERF_FILE: @@ -626,16 +616,14 @@ static void SetupOutput(const char *name, OutputModule *module, OutputCtx *outpu { /* flow logger doesn't run in the packet path */ if (module->FlowLogFunc) { - OutputRegisterFlowLogger(module->name, module->FlowLogFunc, - output_ctx, module->ThreadInit, module->ThreadDeinit, - module->ThreadExitPrintStats); + OutputRegisterFlowLogger(module->name, module->FlowLogFunc, output_ctx, module->ThreadInit, + module->ThreadDeinit, module->ThreadExitPrintStats); return; } /* stats logger doesn't run in the packet path */ if (module->StatsLogFunc) { - OutputRegisterStatsLogger(module->name, module->StatsLogFunc, - output_ctx,module->ThreadInit, module->ThreadDeinit, - module->ThreadExitPrintStats); + OutputRegisterStatsLogger(module->name, module->StatsLogFunc, output_ctx, + module->ThreadInit, module->ThreadDeinit, module->ThreadExitPrintStats); return; } @@ -645,16 +633,14 @@ static void SetupOutput(const char *name, OutputModule *module, OutputCtx *outpu if (module->PacketLogFunc) { SCLogDebug("%s is a packet logger", module->name); - OutputRegisterPacketLogger(module->logger_id, module->name, - module->PacketLogFunc, module->PacketConditionFunc, output_ctx, - module->ThreadInit, module->ThreadDeinit, - module->ThreadExitPrintStats); + OutputRegisterPacketLogger(module->logger_id, module->name, module->PacketLogFunc, + module->PacketConditionFunc, output_ctx, module->ThreadInit, module->ThreadDeinit, + module->ThreadExitPrintStats); } else if (module->TxLogFunc) { SCLogDebug("%s is a tx logger", module->name); - OutputRegisterTxLogger(module->logger_id, module->name, module->alproto, - module->TxLogFunc, output_ctx, module->tc_log_progress, - module->ts_log_progress, module->TxLogCondition, - module->ThreadInit, module->ThreadDeinit, + OutputRegisterTxLogger(module->logger_id, module->name, module->alproto, module->TxLogFunc, + output_ctx, module->tc_log_progress, module->ts_log_progress, + module->TxLogCondition, module->ThreadInit, module->ThreadDeinit, module->ThreadExitPrintStats); /* Not used with wild card loggers */ if (module->alproto != ALPROTO_UNKNOWN) { @@ -662,22 +648,19 @@ static void SetupOutput(const char *name, OutputModule *module, OutputCtx *outpu } } else if (module->FiledataLogFunc) { SCLogDebug("%s is a filedata logger", module->name); - OutputRegisterFiledataLogger(module->logger_id, module->name, - module->FiledataLogFunc, output_ctx, module->ThreadInit, - module->ThreadDeinit, module->ThreadExitPrintStats); + OutputRegisterFiledataLogger(module->logger_id, module->name, module->FiledataLogFunc, + output_ctx, module->ThreadInit, module->ThreadDeinit, module->ThreadExitPrintStats); filedata_logger_count++; } else if (module->FileLogFunc) { SCLogDebug("%s is a file logger", module->name); - OutputRegisterFileLogger(module->logger_id, module->name, - module->FileLogFunc, output_ctx, module->ThreadInit, - module->ThreadDeinit, module->ThreadExitPrintStats); + OutputRegisterFileLogger(module->logger_id, module->name, module->FileLogFunc, output_ctx, + module->ThreadInit, module->ThreadDeinit, module->ThreadExitPrintStats); file_logger_count++; } else if (module->StreamingLogFunc) { SCLogDebug("%s is a streaming logger", module->name); - OutputRegisterStreamingLogger(module->logger_id, module->name, - module->StreamingLogFunc, output_ctx, module->stream_type, - module->ThreadInit, module->ThreadDeinit, - module->ThreadExitPrintStats); + OutputRegisterStreamingLogger(module->logger_id, module->name, module->StreamingLogFunc, + output_ctx, module->stream_type, module->ThreadInit, module->ThreadDeinit, + module->ThreadExitPrintStats); } else { SCLogError("Unknown logger type: name=%s", module->name); } @@ -692,7 +675,7 @@ static void RunModeInitializeEveOutput(ConfNode *conf, OutputCtx *parent_ctx) } ConfNode *type = NULL; - TAILQ_FOREACH(type, &types->head, next) { + TAILQ_FOREACH (type, &types->head, next) { int sub_count = 0; char subname[256]; @@ -707,8 +690,7 @@ static void RunModeInitializeEveOutput(ConfNode *conf, OutputCtx *parent_ctx) ConfNode *sub_output_config = ConfNodeLookupChild(type, type->val); if (sub_output_config != NULL) { - const char *enabled = ConfNodeLookupChildValue( - sub_output_config, "enabled"); + const char *enabled = ConfNodeLookupChildValue(sub_output_config, "enabled"); if (enabled != NULL && !ConfValIsTrue(enabled)) { continue; } @@ -716,7 +698,7 @@ static void RunModeInitializeEveOutput(ConfNode *conf, OutputCtx *parent_ctx) /* Now setup all registers logger of this name. */ OutputModule *sub_module; - TAILQ_FOREACH(sub_module, &output_modules, entries) { + TAILQ_FOREACH (sub_module, &output_modules, entries) { if (strcmp(subname, sub_module->conf_name) == 0) { sub_count++; @@ -729,15 +711,13 @@ static void RunModeInitializeEveOutput(ConfNode *conf, OutputCtx *parent_ctx) } /* pass on parent output_ctx */ - OutputInitResult result = - sub_module->InitSubFunc(sub_output_config, parent_ctx); + OutputInitResult result = sub_module->InitSubFunc(sub_output_config, parent_ctx); if (!result.ok || result.ctx == NULL) { FatalError("unable to initialize sub-module %s", subname); } AddOutputToFreeList(sub_module, result.ctx); - SetupOutput(sub_module->name, sub_module, - result.ctx); + SetupOutput(sub_module->name, sub_module, result.ctx); } } @@ -756,14 +736,14 @@ static void RunModeInitializeLuaOutput(ConfNode *conf, OutputCtx *parent_ctx) BUG_ON(lua_module == NULL); ConfNode *scripts = ConfNodeLookupChild(conf, "scripts"); - BUG_ON(scripts == NULL); //TODO + BUG_ON(scripts == NULL); // TODO OutputModule *m; - TAILQ_FOREACH(m, &parent_ctx->submodules, entries) { + TAILQ_FOREACH (m, &parent_ctx->submodules, entries) { SCLogDebug("m %p %s:%s", m, m->name, m->conf_name); ConfNode *script = NULL; - TAILQ_FOREACH(script, &scripts->head, next) { + TAILQ_FOREACH (script, &scripts->head, next) { SCLogDebug("script %s", script->val); if (strcmp(script->val, m->conf_name) == 0) { break; @@ -803,7 +783,7 @@ void RunModeInitializeOutputs(void) memset(&logger_bits, 0, sizeof(logger_bits)); - TAILQ_FOREACH(output, &outputs->head, next) { + TAILQ_FOREACH (output, &outputs->head, next) { output_config = ConfNodeLookupChild(output, output->val); if (output_config == NULL) { @@ -851,7 +831,7 @@ void RunModeInitializeOutputs(void) OutputModule *module; int count = 0; - TAILQ_FOREACH(module, &output_modules, entries) { + TAILQ_FOREACH (module, &output_modules, entries) { if (strcmp(module->conf_name, output->val) != 0) { continue; } @@ -904,7 +884,7 @@ void RunModeInitializeOutputs(void) * to be started using 'tls-log' config as own config */ SCLogWarning("Please use 'tls-store' in YAML to configure TLS storage"); - TAILQ_FOREACH(output, &outputs->head, next) { + TAILQ_FOREACH (output, &outputs->head, next) { output_config = ConfNodeLookupChild(output, output->val); if (strcmp(output->val, "tls-log") == 0) { @@ -962,15 +942,14 @@ void RunModeInitializeOutputs(void) (g_filedata_logger_enabled); SCLogDebug("tcp %d udp %d", tcp, udp); - SCLogDebug("logger for %s: %s %s", AppProtoToString(a), - tcp ? "true" : "false", udp ? "true" : "false"); + SCLogDebug("logger for %s: %s %s", AppProtoToString(a), tcp ? "true" : "false", + udp ? "true" : "false"); SCLogDebug("logger bits for %s: %08x", AppProtoToString(a), logger_bits[a]); if (tcp) AppLayerParserRegisterLoggerBits(IPPROTO_TCP, a, logger_bits[a]); if (udp) AppLayerParserRegisterLoggerBits(IPPROTO_UDP, a, logger_bits[a]); - } OutputSetupActiveLoggers(); } diff --git a/src/runmodes.h b/src/runmodes.h index 668896dc17c5..2b7cdb401b22 100644 --- a/src/runmodes.h +++ b/src/runmodes.h @@ -81,7 +81,8 @@ const char *RunModeGetMainMode(void); void RunModeListRunmodes(void); void RunModeEngineIsIPS(int capture_mode, const char *runmode, const char *capture_plugin_name); -void RunModeDispatch(int, const char *, const char *capture_plugin_name, const char *capture_plugin_args); +void RunModeDispatch( + int, const char *, const char *capture_plugin_name, const char *capture_plugin_args); void RunModeRegisterRunModes(void); void RunModeRegisterNewRunMode(enum RunModes, const char *, const char *, int (*RunModeFunc)(void), void (*RunModeIsIPSEnabled)(void)); diff --git a/src/rust-context.h b/src/rust-context.h index ba99ac6b7286..f969dea232b7 100644 --- a/src/rust-context.h +++ b/src/rust-context.h @@ -24,7 +24,7 @@ #include "app-layer-krb5.h" //KRB5State, KRB5Transaction #include "app-layer-ike.h" //IKEState, IKETransaction -#include "app-layer-ntp.h" //NTPState, NTPTransaction +#include "app-layer-ntp.h" //NTPState, NTPTransaction #include "app-layer-snmp.h" //SNMPState, SNMPTransaction #include "app-layer-tftp.h" //TFTPState, TFTPTransaction @@ -40,8 +40,7 @@ typedef struct SuricataContext_ { SCError (*SCLogMessage)(const SCLogLevel, const char *, const unsigned int, const char *, const char *, const char *message); void (*DetectEngineStateFree)(DetectEngineState *); - void (*AppLayerDecoderEventsSetEventRaw)(AppLayerDecoderEvents **, - uint8_t); + void (*AppLayerDecoderEventsSetEventRaw)(AppLayerDecoderEvents **, uint8_t); void (*AppLayerDecoderEventsFreeEvents)(AppLayerDecoderEvents **); void (*AppLayerParserTriggerRawStreamReassembly)(Flow *, int direction); @@ -49,9 +48,9 @@ typedef struct SuricataContext_ { bool (*HTPFileCloseHandleRange)(const StreamingBufferConfig *sbcfg, FileContainer *, const uint16_t, HttpRangeContainerBlock *, const uint8_t *, uint32_t); - int (*FileOpenFileWithId)(FileContainer *, const StreamingBufferConfig *, - uint32_t track_id, const uint8_t *name, uint16_t name_len, - const uint8_t *data, uint32_t data_len, uint16_t flags); + int (*FileOpenFileWithId)(FileContainer *, const StreamingBufferConfig *, uint32_t track_id, + const uint8_t *name, uint16_t name_len, const uint8_t *data, uint32_t data_len, + uint16_t flags); int (*FileCloseFileById)(FileContainer *, const StreamingBufferConfig *, uint32_t track_id, const uint8_t *data, uint32_t data_len, uint16_t flags); int (*FileAppendDataById)(FileContainer *, const StreamingBufferConfig *, uint32_t track_id, diff --git a/src/rust.h b/src/rust.h index 12c90e67f30d..07315c592ae7 100644 --- a/src/rust.h +++ b/src/rust.h @@ -26,7 +26,7 @@ typedef struct HttpRangeContainerBlock HttpRangeContainerBlock; #include "rust-bindings.h" #define JB_SET_STRING(jb, key, val) jb_set_formatted((jb), "\"" key "\":\"" val "\"") -#define JB_SET_TRUE(jb, key) jb_set_formatted((jb), "\"" key "\":true") -#define JB_SET_FALSE(jb, key) jb_set_formatted((jb), "\"" key "\":false") +#define JB_SET_TRUE(jb, key) jb_set_formatted((jb), "\"" key "\":true") +#define JB_SET_FALSE(jb, key) jb_set_formatted((jb), "\"" key "\":false") #endif /* !__RUST_H__ */ diff --git a/src/source-af-packet.c b/src/source-af-packet.c index 3c783a149029..be2607c4d105 100644 --- a/src/source-af-packet.c +++ b/src/source-af-packet.c @@ -31,7 +31,7 @@ */ #define PCAP_DONT_INCLUDE_PCAP_BPF_H 1 -#define SC_PCAP_DONT_INCLUDE_PCAP_H 1 +#define SC_PCAP_DONT_INCLUDE_PCAP_H 1 #include "suricata-common.h" #include "suricata.h" #include "packet.h" @@ -124,7 +124,7 @@ extern uint16_t max_pending_packets; TmEcode NoAFPSupportExit(ThreadVars *, const void *, void **); -void TmModuleReceiveAFPRegister (void) +void TmModuleReceiveAFPRegister(void) { tmm_modules[TMM_RECEIVEAFP].name = "ReceiveAFP"; tmm_modules[TMM_RECEIVEAFP].ThreadInit = NoAFPSupportExit; @@ -138,7 +138,7 @@ void TmModuleReceiveAFPRegister (void) /** * \brief Registration Function for DecodeAFP. */ -void TmModuleDecodeAFPRegister (void) +void TmModuleDecodeAFPRegister(void) { tmm_modules[TMM_DECODEAFP].name = "DecodeAFP"; tmm_modules[TMM_DECODEAFP].ThreadInit = NoAFPSupportExit; @@ -166,9 +166,9 @@ TmEcode NoAFPSupportExit(ThreadVars *tv, const void *initdata, void **data) #define AFP_IFACE_NAME_LENGTH 48 #define AFP_STATE_DOWN 0 -#define AFP_STATE_UP 1 +#define AFP_STATE_UP 1 -#define AFP_RECONNECT_TIMEOUT 500000 +#define AFP_RECONNECT_TIMEOUT 500000 #define AFP_DOWN_COUNTER_INTERVAL 40 #define POLL_TIMEOUT 100 @@ -261,8 +261,7 @@ static int AFPXDPBypassCallback(Packet *p); /** * \brief Structure to hold thread specific variables. */ -typedef struct AFPThreadVars_ -{ +typedef struct AFPThreadVars_ { union AFPRing { union thdr **v2; struct iovec *v3; @@ -373,15 +372,14 @@ static TmEcode DecodeAFP(ThreadVars *, Packet *, void *); static TmEcode AFPSetBPFFilter(AFPThreadVars *ptv); static int AFPGetIfnumByDev(int fd, const char *ifname, int verbose); static int AFPGetDevFlags(int fd, const char *ifname); -static int AFPDerefSocket(AFPPeer* peer); -static int AFPRefSocket(AFPPeer* peer); - +static int AFPDerefSocket(AFPPeer *peer); +static int AFPRefSocket(AFPPeer *peer); /** * \brief Registration Function for RecieveAFP. * \todo Unit tests are needed for this module. */ -void TmModuleReceiveAFPRegister (void) +void TmModuleReceiveAFPRegister(void) { tmm_modules[TMM_RECEIVEAFP].name = "ReceiveAFP"; tmm_modules[TMM_RECEIVEAFP].ThreadInit = ReceiveAFPThreadInit; @@ -392,7 +390,6 @@ void TmModuleReceiveAFPRegister (void) tmm_modules[TMM_RECEIVEAFP].ThreadDeinit = ReceiveAFPThreadDeinit; tmm_modules[TMM_RECEIVEAFP].cap_flags = SC_CAP_NET_RAW; tmm_modules[TMM_RECEIVEAFP].flags = TM_FLAG_RECEIVE_TM; - } /** @@ -412,7 +409,7 @@ typedef struct AFPPeersList_ { TAILQ_HEAD(, AFPPeer_) peers; /**< Head of list of fragments. */ int cnt; int peered; - int turn; /**< Next value for initialisation order */ + int turn; /**< Next value for initialisation order */ SC_ATOMIC_DECLARE(int, reached); /**< Counter used to synchronize start */ } AFPPeersList; @@ -445,7 +442,6 @@ static void AFPPeerClean(AFPPeer *peer) AFPPeersList peerslist; - /** * \brief Init the global list of ::AFPPeer */ @@ -457,7 +453,7 @@ TmEcode AFPPeersListInit(void) peerslist.cnt = 0; peerslist.turn = 0; SC_ATOMIC_INIT(peerslist.reached); - (void) SC_ATOMIC_SET(peerslist.reached, 0); + (void)SC_ATOMIC_SET(peerslist.reached, 0); SCReturnInt(TM_ECODE_OK); } @@ -469,8 +465,10 @@ TmEcode AFPPeersListInit(void) TmEcode AFPPeersListCheck(void) { #define AFP_PEERS_MAX_TRY 4 -#define AFP_PEERS_WAIT 20000 - int try = 0; +#define AFP_PEERS_WAIT 20000 + int + try + = 0; SCEnter(); while (try < AFP_PEERS_MAX_TRY) { if (peerslist.cnt != peerslist.peered) { @@ -478,7 +476,8 @@ TmEcode AFPPeersListCheck(void) } else { SCReturnInt(TM_ECODE_OK); } - try++; + try + ++; } SCLogError("thread number not equal"); SCReturnInt(TM_ECODE_FAILED); @@ -518,7 +517,7 @@ static TmEcode AFPPeersListAdd(AFPThreadVars *ptv) peerslist.cnt++; /* Iter to find a peer */ - TAILQ_FOREACH(pitem, &peerslist.peers, next) { + TAILQ_FOREACH (pitem, &peerslist.peers, next) { if (pitem->peer) continue; if (strcmp(pitem->iface, ptv->out_iface)) @@ -599,7 +598,7 @@ void AFPPeersListClean(void) * \brief Registration Function for DecodeAFP. * \todo Unit tests are needed for this module. */ -void TmModuleDecodeAFPRegister (void) +void TmModuleDecodeAFPRegister(void) { tmm_modules[TMM_DECODEAFP].name = "DecodeAFP"; tmm_modules[TMM_DECODEAFP].ThreadInit = DecodeAFPThreadInit; @@ -610,23 +609,20 @@ void TmModuleDecodeAFPRegister (void) tmm_modules[TMM_DECODEAFP].flags = TM_FLAG_DECODE_TM; } - static int AFPCreateSocket(AFPThreadVars *ptv, char *devname, int verbose); static inline void AFPDumpCounters(AFPThreadVars *ptv) { #ifdef PACKET_STATISTICS struct tpacket_stats kstats; - socklen_t len = sizeof (struct tpacket_stats); - if (getsockopt(ptv->socket, SOL_PACKET, PACKET_STATISTICS, - &kstats, &len) > -1) { - SCLogDebug("(%s) Kernel: Packets %" PRIu32 ", dropped %" PRIu32 "", - ptv->tv->name, + socklen_t len = sizeof(struct tpacket_stats); + if (getsockopt(ptv->socket, SOL_PACKET, PACKET_STATISTICS, &kstats, &len) > -1) { + SCLogDebug("(%s) Kernel: Packets %" PRIu32 ", dropped %" PRIu32 "", ptv->tv->name, kstats.tp_packets, kstats.tp_drops); StatsAddUI64(ptv->tv, ptv->capture_kernel_packets, kstats.tp_packets); StatsAddUI64(ptv->tv, ptv->capture_kernel_drops, kstats.tp_drops); - (void) SC_ATOMIC_ADD(ptv->livedev->drop, (uint64_t) kstats.tp_drops); - (void) SC_ATOMIC_ADD(ptv->livedev->pkts, (uint64_t) kstats.tp_packets); + (void)SC_ATOMIC_ADD(ptv->livedev->drop, (uint64_t)kstats.tp_drops); + (void)SC_ATOMIC_ADD(ptv->livedev->pkts, (uint64_t)kstats.tp_packets); const uint64_t value = SC_ATOMIC_GET(ptv->mpeer->send_errors); if (value > ptv->send_errors_logged) { @@ -939,7 +935,7 @@ static int AFPReadFromRing(AFPThreadVars *ptv) if (TmThreadsSlotProcessPkt(ptv->tv, ptv->slot, p) != TM_ECODE_OK) { return AFPSuriFailure(ptv, h); } -next_frame: + next_frame: if (++ptv->frame_offset >= ptv->req.v2.tp_frame_nr) { ptv->frame_offset = 0; /* Get out of loop to be sure we will reach maintenance tasks */ @@ -959,7 +955,8 @@ static inline void AFPFlushBlock(struct tpacket_block_desc *pbd) pbd->hdr.bh1.block_status = TP_STATUS_KERNEL; } -static inline int AFPParsePacketV3(AFPThreadVars *ptv, struct tpacket_block_desc *pbd, struct tpacket3_hdr *ppd) +static inline int AFPParsePacketV3( + AFPThreadVars *ptv, struct tpacket_block_desc *pbd, struct tpacket3_hdr *ppd) { Packet *p = PacketGetFromQueueOrAlloc(); if (p == NULL) { @@ -990,15 +987,13 @@ static inline int AFPParsePacketV3(AFPThreadVars *ptv, struct tpacket_block_desc /* Timestamp */ p->ts = (SCTime_t){ .secs = ppd->tp_sec, .usecs = ppd->tp_nsec / 1000 }; - SCLogDebug("pktlen: %" PRIu32 " (pkt %p, pkt data %p)", - GET_PKT_LEN(p), p, GET_PKT_DATA(p)); + SCLogDebug("pktlen: %" PRIu32 " (pkt %p, pkt data %p)", GET_PKT_LEN(p), p, GET_PKT_DATA(p)); /* We only check for checksum disable */ if (ptv->checksum_mode == CHECKSUM_VALIDATION_DISABLE) { p->flags |= PKT_IGNORE_CHECKSUM; } else if (ptv->checksum_mode == CHECKSUM_VALIDATION_AUTO) { - if (ChecksumAutoModeCheck(ptv->pkts, - SC_ATOMIC_GET(ptv->livedev->pkts), + if (ChecksumAutoModeCheck(ptv->pkts, SC_ATOMIC_GET(ptv->livedev->pkts), SC_ATOMIC_GET(ptv->livedev->invalid_checksums))) { ptv->checksum_mode = CHECKSUM_VALIDATION_DISABLE; p->flags |= PKT_IGNORE_CHECKSUM; @@ -1097,7 +1092,7 @@ static int AFPReadFromRingV3(AFPThreadVars *ptv) * * \retval O in case of failure, 1 in case of success */ -static int AFPRefSocket(AFPPeer* peer) +static int AFPRefSocket(AFPPeer *peer) { if (unlikely(peer == NULL)) return 0; @@ -1106,13 +1101,12 @@ static int AFPRefSocket(AFPPeer* peer) return 1; } - /** * \brief Dereference socket * * \retval 1 if socket is still alive, 0 if not */ -static int AFPDerefSocket(AFPPeer* peer) +static int AFPDerefSocket(AFPPeer *peer) { if (peer == NULL) return 1; @@ -1167,8 +1161,8 @@ static void AFPSwitchState(AFPThreadVars *ptv, uint8_t state) } } -static int AFPReadAndDiscardFromRing(AFPThreadVars *ptv, struct timeval *synctv, - uint64_t *discarded_pkts) +static int AFPReadAndDiscardFromRing( + AFPThreadVars *ptv, struct timeval *synctv, uint64_t *discarded_pkts) { if (unlikely(suricata_ctl_flags != 0)) { return 1; @@ -1181,10 +1175,10 @@ static int AFPReadAndDiscardFromRing(AFPThreadVars *ptv, struct timeval *synctv, (struct tpacket_block_desc *)ptv->ring.v3[ptv->frame_offset].iov_base; *discarded_pkts += pbd->hdr.bh1.num_pkts; struct tpacket3_hdr *ppd = - (struct tpacket3_hdr *)((uint8_t *)pbd + pbd->hdr.bh1.offset_to_first_pkt); + (struct tpacket3_hdr *)((uint8_t *)pbd + pbd->hdr.bh1.offset_to_first_pkt); if (((time_t)ppd->tp_sec > synctv->tv_sec) || ((time_t)ppd->tp_sec == synctv->tv_sec && - (suseconds_t) (ppd->tp_nsec / 1000) > (suseconds_t)synctv->tv_usec)) { + (suseconds_t)(ppd->tp_nsec / 1000) > (suseconds_t)synctv->tv_usec)) { ret = 1; } AFPFlushBlock(pbd); @@ -1205,7 +1199,7 @@ static int AFPReadAndDiscardFromRing(AFPThreadVars *ptv, struct timeval *synctv, if (((time_t)h.h2->tp_sec > synctv->tv_sec) || ((time_t)h.h2->tp_sec == synctv->tv_sec && - (suseconds_t) (h.h2->tp_nsec / 1000) > synctv->tv_usec)) { + (suseconds_t)(h.h2->tp_nsec / 1000) > synctv->tv_usec)) { return 1; } @@ -1242,13 +1236,12 @@ static int AFPSynchronizeStart(AFPThreadVars *ptv, uint64_t *discarded_pkts) while (1) { int r = poll(&fds, 1, POLL_TIMEOUT); - if (r > 0 && - (fds.revents & (POLLHUP|POLLRDHUP|POLLERR|POLLNVAL))) { + if (r > 0 && (fds.revents & (POLLHUP | POLLRDHUP | POLLERR | POLLNVAL))) { SCLogWarning("%s: poll failed %02x", ptv->iface, fds.revents & (POLLHUP | POLLRDHUP | POLLERR | POLLNVAL)); return 0; } else if (r > 0) { - if (AFPPeersListStarted() && synctv.tv_sec == (time_t) 0xffffffff) { + if (AFPPeersListStarted() && synctv.tv_sec == (time_t)0xffffffff) { gettimeofday(&synctv, NULL); } r = AFPReadAndDiscardFromRing(ptv, &synctv, discarded_pkts); @@ -1260,7 +1253,7 @@ static int AFPSynchronizeStart(AFPThreadVars *ptv, uint64_t *discarded_pkts) case -1: return r; } - /* no packets */ + /* no packets */ } else if (r == 0 && AFPPeersListStarted()) { SCLogDebug("Starting to read on %s", ptv->tv->name); return 1; @@ -1315,7 +1308,7 @@ TmEcode ReceiveAFPLoop(ThreadVars *tv, void *data, void *slot) TmSlot *s = (TmSlot *)slot; time_t last_dump = 0; time_t current_time; - int (*AFPReadFunc) (AFPThreadVars *); + int (*AFPReadFunc)(AFPThreadVars *); uint64_t discarded_pkts = 0; ptv->slot = s->slot_next; @@ -1353,19 +1346,16 @@ TmEcode ReceiveAFPLoop(ThreadVars *tv, void *data, void *slot) /* let's reset counter as we will start the capture at the * next function call */ #ifdef PACKET_STATISTICS - struct tpacket_stats kstats; - socklen_t len = sizeof (struct tpacket_stats); - if (getsockopt(ptv->socket, SOL_PACKET, PACKET_STATISTICS, - &kstats, &len) > -1) { - uint64_t pkts = 0; - SCLogDebug("(%s) Kernel socket startup: Packets %" PRIu32 - ", dropped %" PRIu32 "", - ptv->tv->name, - kstats.tp_packets, kstats.tp_drops); - pkts = kstats.tp_packets - discarded_pkts - kstats.tp_drops; - StatsAddUI64(ptv->tv, ptv->capture_kernel_packets, pkts); - (void) SC_ATOMIC_ADD(ptv->livedev->pkts, pkts); - } + struct tpacket_stats kstats; + socklen_t len = sizeof(struct tpacket_stats); + if (getsockopt(ptv->socket, SOL_PACKET, PACKET_STATISTICS, &kstats, &len) > -1) { + uint64_t pkts = 0; + SCLogDebug("(%s) Kernel socket startup: Packets %" PRIu32 ", dropped %" PRIu32 "", + ptv->tv->name, kstats.tp_packets, kstats.tp_drops); + pkts = kstats.tp_packets - discarded_pkts - kstats.tp_drops; + StatsAddUI64(ptv->tv, ptv->capture_kernel_packets, pkts); + (void)SC_ATOMIC_ADD(ptv->livedev->pkts, pkts); + } #endif } @@ -1406,8 +1396,7 @@ TmEcode ReceiveAFPLoop(ThreadVars *tv, void *data, void *slot) break; } - if (r > 0 && - (fds.revents & (POLLHUP|POLLRDHUP|POLLERR|POLLNVAL))) { + if (r > 0 && (fds.revents & (POLLHUP | POLLRDHUP | POLLERR | POLLNVAL))) { StatsIncr(ptv->tv, ptv->capture_afp_poll_signal); if (fds.revents & (POLLHUP | POLLRDHUP)) { AFPSwitchState(ptv, AFP_STATE_DOWN); @@ -1489,7 +1478,6 @@ static int AFPGetDevFlags(int fd, const char *ifname) return ifr.ifr_flags; } - static int AFPGetIfnumByDev(int fd, const char *ifname, int verbose) { struct ifreq ifr; @@ -1539,7 +1527,7 @@ int AFPGetLinkType(const char *ifname) return LINKTYPE_RAW; } - ltype = AFPGetDevLinktype(fd, ifname); + ltype = AFPGetDevLinktype(fd, ifname); close(fd); DatalinkSetGlobalType(ltype); @@ -1584,7 +1572,10 @@ sockaddr_ll) + ETH_HLEN) - ETH_HLEN); } } - ptv->req.v2.tp_frame_size = TPACKET_ALIGN(snaplen +TPACKET_ALIGN(TPACKET_ALIGN(tp_hdrlen) + sizeof(struct sockaddr_ll) + ETH_HLEN) - ETH_HLEN); + ptv->req.v2.tp_frame_size = TPACKET_ALIGN( + snaplen + + TPACKET_ALIGN(TPACKET_ALIGN(tp_hdrlen) + sizeof(struct sockaddr_ll) + ETH_HLEN) - + ETH_HLEN); ptv->req.v2.tp_block_size = getpagesize() << order; int frames_per_block = ptv->req.v2.tp_block_size / ptv->req.v2.tp_frame_size; if (frames_per_block == 0) { @@ -1618,7 +1609,10 @@ static int AFPComputeRingParamsV3(AFPThreadVars *ptv) } } - ptv->req.v3.tp_frame_size = TPACKET_ALIGN(snaplen +TPACKET_ALIGN(TPACKET_ALIGN(tp_hdrlen) + sizeof(struct sockaddr_ll) + ETH_HLEN) - ETH_HLEN); + ptv->req.v3.tp_frame_size = TPACKET_ALIGN( + snaplen + + TPACKET_ALIGN(TPACKET_ALIGN(tp_hdrlen) + sizeof(struct sockaddr_ll) + ETH_HLEN) - + ETH_HLEN); frames_per_block = ptv->req.v3.tp_block_size / ptv->req.v3.tp_frame_size; if (frames_per_block == 0) { @@ -1672,8 +1666,7 @@ static int AFPSetupRing(AFPThreadVars *ptv, char *devname) val = TPACKET_V3; } #endif - if (setsockopt(ptv->socket, SOL_PACKET, PACKET_VERSION, &val, - sizeof(val)) < 0) { + if (setsockopt(ptv->socket, SOL_PACKET, PACKET_VERSION, &val, sizeof(val)) < 0) { SCLogError("%s: failed to activate TPACKET_V2/TPACKET_V3 on packet socket: %s", devname, strerror(errno)); return AFP_FATAL_ERROR; @@ -1681,8 +1674,7 @@ static int AFPSetupRing(AFPThreadVars *ptv, char *devname) #ifdef HAVE_HW_TIMESTAMPING int req = SOF_TIMESTAMPING_RAW_HARDWARE; - if (setsockopt(ptv->socket, SOL_PACKET, PACKET_TIMESTAMP, (void *) &req, - sizeof(req)) < 0) { + if (setsockopt(ptv->socket, SOL_PACKET, PACKET_TIMESTAMP, (void *)&req, sizeof(req)) < 0) { SCLogWarning("%s: failed to activate hardware timestamping on packet socket: %s", devname, strerror(errno)); } @@ -1703,8 +1695,8 @@ static int AFPSetupRing(AFPThreadVars *ptv, char *devname) if (AFPComputeRingParamsV3(ptv) != 1) { return AFP_FATAL_ERROR; } - r = setsockopt(ptv->socket, SOL_PACKET, PACKET_RX_RING, - (void *) &ptv->req.v3, sizeof(ptv->req.v3)); + r = setsockopt( + ptv->socket, SOL_PACKET, PACKET_RX_RING, (void *)&ptv->req.v3, sizeof(ptv->req.v3)); if (r < 0) { SCLogError("%s: failed to allocate RX Ring: %s", devname, strerror(errno)); return AFP_FATAL_ERROR; @@ -1717,8 +1709,8 @@ static int AFPSetupRing(AFPThreadVars *ptv, char *devname) return AFP_FATAL_ERROR; } - r = setsockopt(ptv->socket, SOL_PACKET, PACKET_RX_RING, - (void *) &ptv->req, sizeof(ptv->req)); + r = setsockopt( + ptv->socket, SOL_PACKET, PACKET_RX_RING, (void *)&ptv->req, sizeof(ptv->req)); if (r < 0) { if (errno == ENOMEM) { @@ -1752,8 +1744,7 @@ static int AFPSetupRing(AFPThreadVars *ptv, char *devname) mmap_flag = MAP_SHARED; if (ptv->flags & AFP_MMAP_LOCKED) mmap_flag |= MAP_LOCKED; - ptv->ring_buf = mmap(0, ptv->ring_buflen, PROT_READ|PROT_WRITE, - mmap_flag, ptv->socket, 0); + ptv->ring_buf = mmap(0, ptv->ring_buflen, PROT_READ | PROT_WRITE, mmap_flag, ptv->socket, 0); if (ptv->ring_buf == MAP_FAILED) { SCLogError("%s: failed to mmap: %s", devname, strerror(errno)); goto mmap_err; @@ -1782,7 +1773,8 @@ static int AFPSetupRing(AFPThreadVars *ptv, char *devname) for (i = 0; i < ptv->req.v2.tp_block_nr; ++i) { void *base = &(ptv->ring_buf[i * ptv->req.v2.tp_block_size]); unsigned int j; - for (j = 0; j < ptv->req.v2.tp_block_size / ptv->req.v2.tp_frame_size; ++j, ++ptv->frame_offset) { + for (j = 0; j < ptv->req.v2.tp_block_size / ptv->req.v2.tp_frame_size; + ++j, ++ptv->frame_offset) { (((union thdr **)ptv->ring.v2)[ptv->frame_offset]) = base; base += ptv->req.v2.tp_frame_size; } @@ -1817,7 +1809,7 @@ int AFPIsFanoutSupported(uint16_t cluster_id) uint32_t mode = PACKET_FANOUT_HASH | PACKET_FANOUT_FLAG_DEFRAG; uint32_t option = (mode << 16) | cluster_id; - int r = setsockopt(fd, SOL_PACKET, PACKET_FANOUT,(void *)&option, sizeof(option)); + int r = setsockopt(fd, SOL_PACKET, PACKET_FANOUT, (void *)&option, sizeof(option)); close(fd); if (r < 0) { @@ -1925,7 +1917,8 @@ static int AFPCreateSocket(AFPThreadVars *ptv, char *devname, int verbose) memset(&sock_params, 0, sizeof(sock_params)); sock_params.mr_type = PACKET_MR_PROMISC; sock_params.mr_ifindex = bind_address.sll_ifindex; - r = setsockopt(ptv->socket, SOL_PACKET, PACKET_ADD_MEMBERSHIP,(void *)&sock_params, sizeof(sock_params)); + r = setsockopt(ptv->socket, SOL_PACKET, PACKET_ADD_MEMBERSHIP, (void *)&sock_params, + sizeof(sock_params)); if (r < 0) { SCLogError("%s: failed to set promisc mode: %s", devname, strerror(errno)); goto socket_err; @@ -1934,8 +1927,8 @@ static int AFPCreateSocket(AFPThreadVars *ptv, char *devname, int verbose) if (ptv->checksum_mode == CHECKSUM_VALIDATION_KERNEL) { int val = 1; - if (setsockopt(ptv->socket, SOL_PACKET, PACKET_AUXDATA, &val, - sizeof(val)) == -1 && errno != ENOPROTOOPT) { + if (setsockopt(ptv->socket, SOL_PACKET, PACKET_AUXDATA, &val, sizeof(val)) == -1 && + errno != ENOPROTOOPT) { SCLogWarning( "%s: 'kernel' checksum mode not supported, falling back to full mode", devname); ptv->checksum_mode = CHECKSUM_VALIDATION_ENABLE; @@ -1948,9 +1941,8 @@ static int AFPCreateSocket(AFPThreadVars *ptv, char *devname, int verbose) * Set the socket buffer size to the specified value. */ SCLogPerf("%s: setting socket buffer to %d", devname, ptv->buffer_size); - if (setsockopt(ptv->socket, SOL_SOCKET, SO_RCVBUF, - &ptv->buffer_size, - sizeof(ptv->buffer_size)) == -1) { + if (setsockopt(ptv->socket, SOL_SOCKET, SO_RCVBUF, &ptv->buffer_size, + sizeof(ptv->buffer_size)) == -1) { SCLogError("%s: failed to set buffer size to %d: %s", devname, ptv->buffer_size, strerror(errno)); goto socket_err; @@ -1970,14 +1962,13 @@ static int AFPCreateSocket(AFPThreadVars *ptv, char *devname, int verbose) goto socket_err; } - #ifdef HAVE_PACKET_FANOUT /* add bound socket to fanout group */ if (ptv->threads > 1) { uint32_t mode = ptv->cluster_type; uint16_t id = ptv->cluster_id; uint32_t option = (mode << 16) | (id & 0xffff); - r = setsockopt(ptv->socket, SOL_PACKET, PACKET_FANOUT,(void *)&option, sizeof(option)); + r = setsockopt(ptv->socket, SOL_PACKET, PACKET_FANOUT, (void *)&option, sizeof(option)); if (r < 0) { SCLogError("%s: failed to set fanout mode: %s", devname, strerror(errno)); goto socket_err; @@ -2035,7 +2026,7 @@ static int AFPCreateSocket(AFPThreadVars *ptv, char *devname, int verbose) TmEcode AFPSetBPFFilter(AFPThreadVars *ptv) { struct bpf_program filter; - struct sock_fprog fcode; + struct sock_fprog fcode; int rc; #ifdef HAVE_PACKET_EBPF @@ -2050,14 +2041,13 @@ TmEcode AFPSetBPFFilter(AFPThreadVars *ptv) SCLogInfo("%s: using BPF '%s'", ptv->iface, ptv->bpf_filter); char errbuf[PCAP_ERRBUF_SIZE]; - if (SCBPFCompile(default_packet_size, /* snaplen_arg */ - ptv->datalink, /* linktype_arg */ - &filter, /* program */ - ptv->bpf_filter, /* const char *buf */ - 1, /* optimize */ - 0, /* mask */ - errbuf, - sizeof(errbuf)) == -1) { + if (SCBPFCompile(default_packet_size, /* snaplen_arg */ + ptv->datalink, /* linktype_arg */ + &filter, /* program */ + ptv->bpf_filter, /* const char *buf */ + 1, /* optimize */ + 0, /* mask */ + errbuf, sizeof(errbuf)) == -1) { SCLogError("%s: failed to compile BPF \"%s\": %s", ptv->iface, ptv->bpf_filter, errbuf); return TM_ECODE_FAILED; } @@ -2066,12 +2056,12 @@ TmEcode AFPSetBPFFilter(AFPThreadVars *ptv) return TM_ECODE_FAILED; } fcode.len = (unsigned short)filter.bf_len; - fcode.filter = (struct sock_filter*)filter.bf_insns; + fcode.filter = (struct sock_filter *)filter.bf_insns; rc = setsockopt(ptv->socket, SOL_SOCKET, SO_ATTACH_FILTER, &fcode, sizeof(fcode)); SCBPFFree(&filter); - if(rc == -1) { + if (rc == -1) { SCLogError("%s: failed to attach filter: %s", ptv->iface, strerror(errno)); return TM_ECODE_FAILED; } @@ -2122,8 +2112,7 @@ static int AFPInsertHalfFlow(int mapd, void *key, unsigned int nr_cpus) return 1; } -static int AFPSetFlowStorage(Packet *p, int map_fd, void *key0, void* key1, - int family) +static int AFPSetFlowStorage(Packet *p, int map_fd, void *key0, void *key1, int family) { FlowBypassInfo *fc = FlowGetStorageById(p->flow, GetFlowBypassInfoID()); if (fc) { @@ -2220,13 +2209,12 @@ static int AFPBypassCallback(Packet *p) } else { keys[0]->ip_proto = 0; } - if (AFPInsertHalfFlow(p->afp_v.v4_map_fd, keys[0], - p->afp_v.nr_cpus) == 0) { + if (AFPInsertHalfFlow(p->afp_v.v4_map_fd, keys[0], p->afp_v.nr_cpus) == 0) { LiveDevAddBypassFail(p->livedev, 1, AF_INET); SCFree(keys[0]); return 0; } - keys[1]= SCCalloc(1, sizeof(struct flowv4_keys)); + keys[1] = SCCalloc(1, sizeof(struct flowv4_keys)); if (keys[1] == NULL) { EBPFDeleteKey(p->afp_v.v4_map_fd, keys[0]); LiveDevAddBypassFail(p->livedev, 1, AF_INET); @@ -2242,8 +2230,7 @@ static int AFPBypassCallback(Packet *p) keys[1]->vlan2 = p->vlan_id[2]; keys[1]->ip_proto = keys[0]->ip_proto; - if (AFPInsertHalfFlow(p->afp_v.v4_map_fd, keys[1], - p->afp_v.nr_cpus) == 0) { + if (AFPInsertHalfFlow(p->afp_v.v4_map_fd, keys[1], p->afp_v.nr_cpus) == 0) { EBPFDeleteKey(p->afp_v.v4_map_fd, keys[0]); LiveDevAddBypassFail(p->livedev, 1, AF_INET); SCFree(keys[0]); @@ -2254,8 +2241,7 @@ static int AFPBypassCallback(Packet *p) return AFPSetFlowStorage(p, p->afp_v.v4_map_fd, keys[0], keys[1], AF_INET); } /* For IPv6 case we don't handle extended header in eBPF */ - if (PKT_IS_IPV6(p) && - ((IPV6_GET_NH(p) == IPPROTO_TCP) || (IPV6_GET_NH(p) == IPPROTO_UDP))) { + if (PKT_IS_IPV6(p) && ((IPV6_GET_NH(p) == IPPROTO_TCP) || (IPV6_GET_NH(p) == IPPROTO_UDP))) { int i; if (p->afp_v.v6_map_fd == -1) { return 0; @@ -2282,13 +2268,12 @@ static int AFPBypassCallback(Packet *p) } else { keys[0]->ip_proto = 0; } - if (AFPInsertHalfFlow(p->afp_v.v6_map_fd, keys[0], - p->afp_v.nr_cpus) == 0) { + if (AFPInsertHalfFlow(p->afp_v.v6_map_fd, keys[0], p->afp_v.nr_cpus) == 0) { LiveDevAddBypassFail(p->livedev, 1, AF_INET6); SCFree(keys[0]); return 0; } - keys[1]= SCCalloc(1, sizeof(struct flowv6_keys)); + keys[1] = SCCalloc(1, sizeof(struct flowv6_keys)); if (keys[1] == NULL) { EBPFDeleteKey(p->afp_v.v6_map_fd, keys[0]); LiveDevAddBypassFail(p->livedev, 1, AF_INET6); @@ -2306,8 +2291,7 @@ static int AFPBypassCallback(Packet *p) keys[1]->vlan2 = p->vlan_id[2]; keys[1]->ip_proto = keys[0]->ip_proto; - if (AFPInsertHalfFlow(p->afp_v.v6_map_fd, keys[1], - p->afp_v.nr_cpus) == 0) { + if (AFPInsertHalfFlow(p->afp_v.v6_map_fd, keys[1], p->afp_v.nr_cpus) == 0) { EBPFDeleteKey(p->afp_v.v6_map_fd, keys[0]); LiveDevAddBypassFail(p->livedev, 1, AF_INET6); SCFree(keys[0]); @@ -2354,7 +2338,7 @@ static int AFPXDPBypassCallback(Packet *p) } if (PKT_IS_IPV4(p)) { struct flowv4_keys *keys[2]; - keys[0]= SCCalloc(1, sizeof(struct flowv4_keys)); + keys[0] = SCCalloc(1, sizeof(struct flowv4_keys)); if (keys[0] == NULL) { LiveDevAddBypassFail(p->livedev, 1, AF_INET); return 0; @@ -2377,13 +2361,12 @@ static int AFPXDPBypassCallback(Packet *p) } else { keys[0]->ip_proto = 0; } - if (AFPInsertHalfFlow(p->afp_v.v4_map_fd, keys[0], - p->afp_v.nr_cpus) == 0) { + if (AFPInsertHalfFlow(p->afp_v.v4_map_fd, keys[0], p->afp_v.nr_cpus) == 0) { LiveDevAddBypassFail(p->livedev, 1, AF_INET); SCFree(keys[0]); return 0; } - keys[1]= SCCalloc(1, sizeof(struct flowv4_keys)); + keys[1] = SCCalloc(1, sizeof(struct flowv4_keys)); if (keys[1] == NULL) { EBPFDeleteKey(p->afp_v.v4_map_fd, keys[0]); LiveDevAddBypassFail(p->livedev, 1, AF_INET); @@ -2398,8 +2381,7 @@ static int AFPXDPBypassCallback(Packet *p) keys[1]->vlan1 = p->vlan_id[1]; keys[1]->vlan2 = p->vlan_id[2]; keys[1]->ip_proto = keys[0]->ip_proto; - if (AFPInsertHalfFlow(p->afp_v.v4_map_fd, keys[1], - p->afp_v.nr_cpus) == 0) { + if (AFPInsertHalfFlow(p->afp_v.v4_map_fd, keys[1], p->afp_v.nr_cpus) == 0) { EBPFDeleteKey(p->afp_v.v4_map_fd, keys[0]); LiveDevAddBypassFail(p->livedev, 1, AF_INET); SCFree(keys[0]); @@ -2409,8 +2391,7 @@ static int AFPXDPBypassCallback(Packet *p) return AFPSetFlowStorage(p, p->afp_v.v4_map_fd, keys[0], keys[1], AF_INET); } /* For IPv6 case we don't handle extended header in eBPF */ - if (PKT_IS_IPV6(p) && - ((IPV6_GET_NH(p) == IPPROTO_TCP) || (IPV6_GET_NH(p) == IPPROTO_UDP))) { + if (PKT_IS_IPV6(p) && ((IPV6_GET_NH(p) == IPPROTO_TCP) || (IPV6_GET_NH(p) == IPPROTO_UDP))) { SCLogDebug("add an IPv6"); if (p->afp_v.v6_map_fd == -1) { return 0; @@ -2436,13 +2417,12 @@ static int AFPXDPBypassCallback(Packet *p) } else { keys[0]->ip_proto = 0; } - if (AFPInsertHalfFlow(p->afp_v.v6_map_fd, keys[0], - p->afp_v.nr_cpus) == 0) { + if (AFPInsertHalfFlow(p->afp_v.v6_map_fd, keys[0], p->afp_v.nr_cpus) == 0) { LiveDevAddBypassFail(p->livedev, 1, AF_INET6); SCFree(keys[0]); return 0; } - keys[1]= SCCalloc(1, sizeof(struct flowv6_keys)); + keys[1] = SCCalloc(1, sizeof(struct flowv6_keys)); if (keys[1] == NULL) { EBPFDeleteKey(p->afp_v.v6_map_fd, keys[0]); LiveDevAddBypassFail(p->livedev, 1, AF_INET6); @@ -2459,8 +2439,7 @@ static int AFPXDPBypassCallback(Packet *p) keys[1]->vlan1 = p->vlan_id[1]; keys[1]->vlan2 = p->vlan_id[2]; keys[1]->ip_proto = keys[0]->ip_proto; - if (AFPInsertHalfFlow(p->afp_v.v6_map_fd, keys[1], - p->afp_v.nr_cpus) == 0) { + if (AFPInsertHalfFlow(p->afp_v.v6_map_fd, keys[1], p->afp_v.nr_cpus) == 0) { EBPFDeleteKey(p->afp_v.v6_map_fd, keys[0]); LiveDevAddBypassFail(p->livedev, 1, AF_INET6); SCFree(keys[0]); @@ -2505,7 +2484,7 @@ TmEcode ReceiveAFPThreadInit(ThreadVars *tv, const void *initdata, void **data) ptv->tv = tv; strlcpy(ptv->iface, afpconfig->iface, AFP_IFACE_NAME_LENGTH); - ptv->iface[AFP_IFACE_NAME_LENGTH - 1]= '\0'; + ptv->iface[AFP_IFACE_NAME_LENGTH - 1] = '\0'; ptv->livedev = LiveGetDevice(ptv->iface); if (ptv->livedev == NULL) { @@ -2545,7 +2524,7 @@ TmEcode ReceiveAFPThreadInit(ThreadVars *tv, const void *initdata, void **data) ptv->xdp_mode = afpconfig->xdp_mode; ptv->ebpf_t_config.cpus_count = UtilCpuGetNumProcessorsConfigured(); - if (ptv->flags & (AFP_BYPASS|AFP_XDPBYPASS)) { + if (ptv->flags & (AFP_BYPASS | AFP_XDPBYPASS)) { ptv->v4_map_fd = EBPFGetMapFDByName(ptv->iface, "flow_table_v4"); if (ptv->v4_map_fd == -1) { if (g_flowv4_ok == false) { @@ -2554,7 +2533,7 @@ TmEcode ReceiveAFPThreadInit(ThreadVars *tv, const void *initdata, void **data) } } ptv->v6_map_fd = EBPFGetMapFDByName(ptv->iface, "flow_table_v6"); - if (ptv->v6_map_fd == -1) { + if (ptv->v6_map_fd == -1) { if (g_flowv6_ok) { SCLogError("Can't find eBPF map fd for '%s'", "flow_table_v6"); g_flowv6_ok = false; @@ -2565,12 +2544,9 @@ TmEcode ReceiveAFPThreadInit(ThreadVars *tv, const void *initdata, void **data) #endif #ifdef PACKET_STATISTICS - ptv->capture_kernel_packets = StatsRegisterCounter("capture.kernel_packets", - ptv->tv); - ptv->capture_kernel_drops = StatsRegisterCounter("capture.kernel_drops", - ptv->tv); - ptv->capture_errors = StatsRegisterCounter("capture.errors", - ptv->tv); + ptv->capture_kernel_packets = StatsRegisterCounter("capture.kernel_packets", ptv->tv); + ptv->capture_kernel_drops = StatsRegisterCounter("capture.kernel_drops", ptv->tv); + ptv->capture_errors = StatsRegisterCounter("capture.errors", ptv->tv); ptv->afpacket_spin = StatsRegisterAvgCounter("capture.afpacket.busy_loop_avg", ptv->tv); @@ -2585,7 +2561,7 @@ TmEcode ReceiveAFPThreadInit(ThreadVars *tv, const void *initdata, void **data) ptv->copy_mode = afpconfig->copy_mode; if (ptv->copy_mode != AFP_COPY_MODE_NONE) { strlcpy(ptv->out_iface, afpconfig->out_iface, AFP_IFACE_NAME_LENGTH); - ptv->out_iface[AFP_IFACE_NAME_LENGTH - 1]= '\0'; + ptv->out_iface[AFP_IFACE_NAME_LENGTH - 1] = '\0'; /* Warn about BPF filter consequence */ if (ptv->bpf_filter) { SCLogWarning("Enabling a BPF filter in IPS mode result" @@ -2593,7 +2569,6 @@ TmEcode ReceiveAFPThreadInit(ThreadVars *tv, const void *initdata, void **data) } } - if (AFPPeersListAdd(ptv) == TM_ECODE_FAILED) { SCFree(ptv); afpconfig->DerefFunc(afpconfig); @@ -2645,7 +2620,7 @@ TmEcode ReceiveAFPThreadDeinit(ThreadVars *tv, void *data) #ifdef HAVE_PACKET_XDP if ((ptv->ebpf_t_config.flags & EBPF_XDP_CODE) && - (!(ptv->ebpf_t_config.flags & EBPF_PINNED_MAPS))) { + (!(ptv->ebpf_t_config.flags & EBPF_PINNED_MAPS))) { EBPFSetupXDP(ptv->iface, -1, ptv->xdp_mode); } #endif diff --git a/src/source-af-packet.h b/src/source-af-packet.h index d91d0cb25232..8fd959b247bf 100644 --- a/src/source-af-packet.h +++ b/src/source-af-packet.h @@ -27,24 +27,24 @@ #ifndef HAVE_PACKET_FANOUT /* not defined if linux/if_packet.h trying to force */ #define HAVE_PACKET_FANOUT 1 -#define PACKET_FANOUT 18 +#define PACKET_FANOUT 18 -#define PACKET_FANOUT_HASH 0 -#define PACKET_FANOUT_LB 1 -#define PACKET_FANOUT_CPU 2 -#define PACKET_FANOUT_ROLLOVER 3 -#define PACKET_FANOUT_RND 4 -#define PACKET_FANOUT_QM 5 +#define PACKET_FANOUT_HASH 0 +#define PACKET_FANOUT_LB 1 +#define PACKET_FANOUT_CPU 2 +#define PACKET_FANOUT_ROLLOVER 3 +#define PACKET_FANOUT_RND 4 +#define PACKET_FANOUT_QM 5 -#define PACKET_FANOUT_FLAG_ROLLOVER 0x1000 -#define PACKET_FANOUT_FLAG_DEFRAG 0x8000 +#define PACKET_FANOUT_FLAG_ROLLOVER 0x1000 +#define PACKET_FANOUT_FLAG_DEFRAG 0x8000 #else /* HAVE_PACKET_FANOUT */ #include #endif /* HAVE_PACKET_FANOUT */ #include "queue.h" #ifdef HAVE_PACKET_EBPF -#define AFP_MODE_XDP_BYPASS 1 +#define AFP_MODE_XDP_BYPASS 1 #define AFP_MODE_EBPF_BYPASS 2 struct ebpf_timeout_config { const char *pinned_maps_name; @@ -57,17 +57,17 @@ struct ebpf_timeout_config { /* value for flags */ #define AFP_NEED_PEER (1 << 0) // (1<<1) vacant -#define AFP_SOCK_PROTECT (1<<2) -#define AFP_EMERGENCY_MODE (1<<3) -#define AFP_TPACKET_V3 (1<<4) -#define AFP_VLAN_IN_HEADER (1<<5) -#define AFP_MMAP_LOCKED (1<<6) -#define AFP_BYPASS (1<<7) -#define AFP_XDPBYPASS (1<<8) - -#define AFP_COPY_MODE_NONE 0 -#define AFP_COPY_MODE_TAP 1 -#define AFP_COPY_MODE_IPS 2 +#define AFP_SOCK_PROTECT (1 << 2) +#define AFP_EMERGENCY_MODE (1 << 3) +#define AFP_TPACKET_V3 (1 << 4) +#define AFP_VLAN_IN_HEADER (1 << 5) +#define AFP_MMAP_LOCKED (1 << 6) +#define AFP_BYPASS (1 << 7) +#define AFP_XDPBYPASS (1 << 8) + +#define AFP_COPY_MODE_NONE 0 +#define AFP_COPY_MODE_TAP 1 +#define AFP_COPY_MODE_IPS 2 #define AFP_IFACE_NAME_LENGTH 48 @@ -77,8 +77,7 @@ struct ebpf_timeout_config { * to standard frame size */ #define AFP_BLOCK_SIZE_DEFAULT_ORDER 3 -typedef struct AFPIfaceConfig_ -{ +typedef struct AFPIfaceConfig_ { char iface[AFP_IFACE_NAME_LENGTH]; /* number of threads */ int threads; @@ -140,8 +139,7 @@ typedef struct AFPPeer_ { * This structure is used y the release data system and is cleaned * up by the AFPV_CLEANUP macro below. */ -typedef struct AFPPacketVars_ -{ +typedef struct AFPPacketVars_ { void *relptr; AFPPeer *peer; /**< Sending peer for IPS/TAP mode */ /** Pointer to ::AFPPeer used for capture. Field is used to be able @@ -183,8 +181,8 @@ typedef struct AFPPacketVars_ * @} */ -void TmModuleReceiveAFPRegister (void); -void TmModuleDecodeAFPRegister (void); +void TmModuleReceiveAFPRegister(void); +void TmModuleDecodeAFPRegister(void); TmEcode AFPPeersListInit(void); TmEcode AFPPeersListCheck(void); diff --git a/src/source-af-xdp.c b/src/source-af-xdp.c index 17fa0efeec4f..451adfe7c28c 100644 --- a/src/source-af-xdp.c +++ b/src/source-af-xdp.c @@ -969,7 +969,7 @@ static TmEcode DecodeAFXDPThreadDeinit(ThreadVars *tv, void *data) } #endif /* HAVE_AF_XDP */ -/* eof */ -/** - * @} - */ \ No newline at end of file + /* eof */ + /** + * @} + */ \ No newline at end of file diff --git a/src/source-erf-dag.c b/src/source-erf-dag.c index e3c820dc4c08..4915c087f14d 100644 --- a/src/source-erf-dag.c +++ b/src/source-erf-dag.c @@ -40,8 +40,7 @@ TmEcode NoErfDagSupportExit(ThreadVars *, const void *, void **); -void -TmModuleReceiveErfDagRegister(void) +void TmModuleReceiveErfDagRegister(void) { tmm_modules[TMM_RECEIVEERFDAG].name = "ReceiveErfDag"; tmm_modules[TMM_RECEIVEERFDAG].ThreadInit = NoErfDagSupportExit; @@ -52,8 +51,7 @@ TmModuleReceiveErfDagRegister(void) tmm_modules[TMM_RECEIVEERFDAG].flags = TM_FLAG_RECEIVE_TM; } -void -TmModuleDecodeErfDagRegister(void) +void TmModuleDecodeErfDagRegister(void) { tmm_modules[TMM_DECODEERFDAG].name = "DecodeErfDag"; tmm_modules[TMM_DECODEERFDAG].ThreadInit = NoErfDagSupportExit; @@ -64,8 +62,7 @@ TmModuleDecodeErfDagRegister(void) tmm_modules[TMM_DECODEERFDAG].flags = TM_FLAG_DECODE_TM; } -TmEcode -NoErfDagSupportExit(ThreadVars *tv, const void *initdata, void **data) +TmEcode NoErfDagSupportExit(ThreadVars *tv, const void *initdata, void **data) { SCLogError("Error creating thread %s: you do not have support for DAG cards " "enabled please recompile with --enable-dag", @@ -78,13 +75,13 @@ NoErfDagSupportExit(ThreadVars *tv, const void *initdata, void **data) #include /* Minimum amount of data to read from the DAG at a time. */ -#define MINDATA 32768 +#define MINDATA 32768 /* Maximum time (us) to wait for MINDATA to be read. */ -#define MAXWAIT 20000 +#define MAXWAIT 20000 /* Poll interval in microseconds. */ -#define POLL_INTERVAL 1000; +#define POLL_INTERVAL 1000; /* Number of bytes per loop to process before fetching more data. */ #define BYTES_PER_LOOP (4 * 1024 * 1024) /* 4 MB */ @@ -99,7 +96,7 @@ typedef struct ErfDagThreadVars_ { int dagstream; char dagname[DAGNAME_BUFSIZE]; - struct timeval maxwait, poll; /* Could possibly be made static */ + struct timeval maxwait, poll; /* Could possibly be made static */ LiveDevice *livedev; @@ -114,8 +111,8 @@ typedef struct ErfDagThreadVars_ { } ErfDagThreadVars; -static inline TmEcode ProcessErfDagRecords(ErfDagThreadVars *ewtn, uint8_t *top, - uint32_t *pkts_read); +static inline TmEcode ProcessErfDagRecords( + ErfDagThreadVars *ewtn, uint8_t *top, uint32_t *pkts_read); static inline TmEcode ProcessErfDagRecord(ErfDagThreadVars *ewtn, char *prec); TmEcode ReceiveErfDagLoop(ThreadVars *, void *data, void *slot); TmEcode ReceiveErfDagThreadInit(ThreadVars *, void *, void **); @@ -129,16 +126,14 @@ void ReceiveErfDagCloseStream(int dagfd, int stream); /** * \brief Register the ERF file receiver (reader) module. */ -void -TmModuleReceiveErfDagRegister(void) +void TmModuleReceiveErfDagRegister(void) { tmm_modules[TMM_RECEIVEERFDAG].name = "ReceiveErfDag"; tmm_modules[TMM_RECEIVEERFDAG].ThreadInit = ReceiveErfDagThreadInit; tmm_modules[TMM_RECEIVEERFDAG].Func = NULL; tmm_modules[TMM_RECEIVEERFDAG].PktAcqLoop = ReceiveErfDagLoop; tmm_modules[TMM_RECEIVEERFDAG].PktAcqBreakLoop = NULL; - tmm_modules[TMM_RECEIVEERFDAG].ThreadExitPrintStats = - ReceiveErfDagThreadExitStats; + tmm_modules[TMM_RECEIVEERFDAG].ThreadExitPrintStats = ReceiveErfDagThreadExitStats; tmm_modules[TMM_RECEIVEERFDAG].ThreadDeinit = NULL; tmm_modules[TMM_RECEIVEERFDAG].cap_flags = 0; tmm_modules[TMM_RECEIVEERFDAG].flags = TM_FLAG_RECEIVE_TM; @@ -147,8 +142,7 @@ TmModuleReceiveErfDagRegister(void) /** * \brief Register the ERF file decoder module. */ -void -TmModuleDecodeErfDagRegister(void) +void TmModuleDecodeErfDagRegister(void) { tmm_modules[TMM_DECODEERFDAG].name = "DecodeErfDag"; tmm_modules[TMM_DECODEERFDAG].ThreadInit = DecodeErfDagThreadInit; @@ -175,8 +169,7 @@ TmModuleDecodeErfDagRegister(void) * \param data data pointer gets populated with * */ -TmEcode -ReceiveErfDagThreadInit(ThreadVars *tv, void *initdata, void **data) +TmEcode ReceiveErfDagThreadInit(ThreadVars *tv, void *initdata, void **data) { SCEnter(); int stream_count = 0; @@ -194,8 +187,7 @@ ReceiveErfDagThreadInit(ThreadVars *tv, void *initdata, void **data) /* dag_parse_name will return a DAG device name and stream number * to open for this thread. */ - if (dag_parse_name(initdata, ewtn->dagname, DAGNAME_BUFSIZE, - &ewtn->dagstream) < 0) { + if (dag_parse_name(initdata, ewtn->dagname, DAGNAME_BUFSIZE, &ewtn->dagstream) < 0) { SCLogError("Failed to parse DAG interface: %s", (char *)initdata); SCFree(ewtn); exit(EXIT_FAILURE); @@ -208,8 +200,7 @@ ReceiveErfDagThreadInit(ThreadVars *tv, void *initdata, void **data) SCReturnInt(TM_ECODE_FAILED); } - SCLogInfo("Opening DAG: %s on stream: %d for processing", - ewtn->dagname, ewtn->dagstream); + SCLogInfo("Opening DAG: %s on stream: %d for processing", ewtn->dagname, ewtn->dagstream); if ((ewtn->dagfd = dag_open(ewtn->dagname)) < 0) { SCLogError("Failed to open DAG: %s", ewtn->dagname); @@ -262,8 +253,7 @@ ReceiveErfDagThreadInit(ThreadVars *tv, void *initdata, void **data) SCReturnInt(TM_ECODE_FAILED); } - SCLogInfo("Attached and started stream: %d on DAG: %s", - ewtn->dagstream, ewtn->dagname); + SCLogInfo("Attached and started stream: %d on DAG: %s", ewtn->dagstream, ewtn->dagname); /* * Initialise DAG Polling parameters. @@ -276,8 +266,8 @@ ReceiveErfDagThreadInit(ThreadVars *tv, void *initdata, void **data) /* 32kB minimum data to return -- we still restrict the number of * pkts that are processed to a maximum of dag_max_read_packets. */ - if (dag_set_stream_poll(ewtn->dagfd, ewtn->dagstream, MINDATA, - &(ewtn->maxwait), &(ewtn->poll)) < 0) { + if (dag_set_stream_poll( + ewtn->dagfd, ewtn->dagstream, MINDATA, &(ewtn->maxwait), &(ewtn->poll)) < 0) { SCLogError("Failed to set poll parameters for stream: %d, DAG: %s", ewtn->dagstream, ewtn->dagname); SCFree(ewtn); @@ -292,8 +282,8 @@ ReceiveErfDagThreadInit(ThreadVars *tv, void *initdata, void **data) DatalinkSetGlobalType(LINKTYPE_ETHERNET); - SCLogInfo("Starting processing packets from stream: %d on DAG: %s", - ewtn->dagstream, ewtn->dagname); + SCLogInfo("Starting processing packets from stream: %d on DAG: %s", ewtn->dagstream, + ewtn->dagname); SCReturnInt(TM_ECODE_OK); } @@ -308,15 +298,14 @@ ReceiveErfDagThreadInit(ThreadVars *tv, void *initdata, void **data) * \retval TM_ECODE_OK on success * \retval TM_ECODE_FAILED on failure */ -TmEcode -ReceiveErfDagLoop(ThreadVars *tv, void *data, void *slot) +TmEcode ReceiveErfDagLoop(ThreadVars *tv, void *data, void *slot) { SCEnter(); ErfDagThreadVars *dtv = (ErfDagThreadVars *)data; uint32_t diff = 0; - int err; - uint8_t *top = NULL; + int err; + uint8_t *top = NULL; uint32_t pkts_read = 0; TmSlot *s = (TmSlot *)slot; @@ -365,8 +354,8 @@ ReceiveErfDagLoop(ThreadVars *tv, void *data, void *slot) StatsSyncCountersIfSignalled(tv); - SCLogDebug("Read %d records from stream: %d, DAG: %s", - pkts_read, dtv->dagstream, dtv->dagname); + SCLogDebug("Read %d records from stream: %d, DAG: %s", pkts_read, dtv->dagstream, + dtv->dagname); } SCReturnInt(TM_ECODE_OK); @@ -378,8 +367,8 @@ ReceiveErfDagLoop(ThreadVars *tv, void *data, void *slot) * This function takes a pointer to buffer read from the DAG interface * and processes it individual records. */ -static inline TmEcode -ProcessErfDagRecords(ErfDagThreadVars *ewtn, uint8_t *top, uint32_t *pkts_read) +static inline TmEcode ProcessErfDagRecords( + ErfDagThreadVars *ewtn, uint8_t *top, uint32_t *pkts_read) { SCEnter(); @@ -393,14 +382,14 @@ ProcessErfDagRecords(ErfDagThreadVars *ewtn, uint8_t *top, uint32_t *pkts_read) *pkts_read = 0; while (((top - ewtn->btm) >= dag_record_size) && - ((processed + dag_record_size) < BYTES_PER_LOOP)) { + ((processed + dag_record_size) < BYTES_PER_LOOP)) { /* Make sure we have at least one packet in the packet pool, * to prevent us from alloc'ing packets at line rate. */ PacketPoolWait(); prec = (char *)ewtn->btm; - dr = (dag_record_t*)prec; + dr = (dag_record_t *)prec; rlen = SCNtohs(dr->rlen); hdr_type = dr->type; @@ -415,24 +404,24 @@ ProcessErfDagRecords(ErfDagThreadVars *ewtn, uint8_t *top, uint32_t *pkts_read) /* Only support ethernet at this time. */ switch (hdr_type & 0x7f) { - case ERF_TYPE_PAD: - case ERF_TYPE_META: - /* Skip. */ - continue; - case ERF_TYPE_DSM_COLOR_ETH: - case ERF_TYPE_COLOR_ETH: - case ERF_TYPE_COLOR_HASH_ETH: - /* In these types the color value overwrites the lctr - * (drop count). */ - break; - case ERF_TYPE_ETH: - if (dr->lctr) { - StatsAddUI64(ewtn->tv, ewtn->drops, SCNtohs(dr->lctr)); - } - break; - default: - SCLogError("Processing of DAG record type: %d not implemented.", dr->type); - SCReturnInt(TM_ECODE_FAILED); + case ERF_TYPE_PAD: + case ERF_TYPE_META: + /* Skip. */ + continue; + case ERF_TYPE_DSM_COLOR_ETH: + case ERF_TYPE_COLOR_ETH: + case ERF_TYPE_COLOR_HASH_ETH: + /* In these types the color value overwrites the lctr + * (drop count). */ + break; + case ERF_TYPE_ETH: + if (dr->lctr) { + StatsAddUI64(ewtn->tv, ewtn->drops, SCNtohs(dr->lctr)); + } + break; + default: + SCLogError("Processing of DAG record type: %d not implemented.", dr->type); + SCReturnInt(TM_ECODE_FAILED); } err = ProcessErfDagRecord(ewtn, prec); @@ -451,8 +440,7 @@ ProcessErfDagRecords(ErfDagThreadVars *ewtn, uint8_t *top, uint32_t *pkts_read) * \param prec pointer to a DAG record. * \param */ -static inline TmEcode -ProcessErfDagRecord(ErfDagThreadVars *ewtn, char *prec) +static inline TmEcode ProcessErfDagRecord(ErfDagThreadVars *ewtn, char *prec) { SCEnter(); @@ -460,7 +448,7 @@ ProcessErfDagRecord(ErfDagThreadVars *ewtn, char *prec) int rlen = 0; int hdr_num = 0; char hdr_type = 0; - dag_record_t *dr = (dag_record_t*)prec; + dag_record_t *dr = (dag_record_t *)prec; erf_payload_t *pload; Packet *p; @@ -534,22 +522,16 @@ ProcessErfDagRecord(ErfDagThreadVars *ewtn, char *prec) * \param tv Pointer to ThreadVars. * \param data Pointer to data, ErfFileThreadVars. */ -void -ReceiveErfDagThreadExitStats(ThreadVars *tv, void *data) +void ReceiveErfDagThreadExitStats(ThreadVars *tv, void *data) { ErfDagThreadVars *ewtn = (ErfDagThreadVars *)data; - (void)SC_ATOMIC_SET(ewtn->livedev->pkts, - StatsGetLocalCounterValue(tv, ewtn->packets)); - (void)SC_ATOMIC_SET(ewtn->livedev->drop, - StatsGetLocalCounterValue(tv, ewtn->drops)); - - SCLogInfo("Stream: %d; Bytes: %"PRIu64"; Packets: %"PRIu64 - "; Drops: %"PRIu64, - ewtn->dagstream, - ewtn->bytes, - StatsGetLocalCounterValue(tv, ewtn->packets), - StatsGetLocalCounterValue(tv, ewtn->drops)); + (void)SC_ATOMIC_SET(ewtn->livedev->pkts, StatsGetLocalCounterValue(tv, ewtn->packets)); + (void)SC_ATOMIC_SET(ewtn->livedev->drop, StatsGetLocalCounterValue(tv, ewtn->drops)); + + SCLogInfo("Stream: %d; Bytes: %" PRIu64 "; Packets: %" PRIu64 "; Drops: %" PRIu64, + ewtn->dagstream, ewtn->bytes, StatsGetLocalCounterValue(tv, ewtn->packets), + StatsGetLocalCounterValue(tv, ewtn->drops)); } /** @@ -557,8 +539,7 @@ ReceiveErfDagThreadExitStats(ThreadVars *tv, void *data) * \param tv pointer to ThreadVars * \param data pointer that gets cast into PcapThreadVars for ptv */ -TmEcode -ReceiveErfDagThreadDeinit(ThreadVars *tv, void *data) +TmEcode ReceiveErfDagThreadDeinit(ThreadVars *tv, void *data) { SCEnter(); @@ -569,8 +550,7 @@ ReceiveErfDagThreadDeinit(ThreadVars *tv, void *data) SCReturnInt(TM_ECODE_OK); } -void -ReceiveErfDagCloseStream(int dagfd, int stream) +void ReceiveErfDagCloseStream(int dagfd, int stream) { dag_stop_stream(dagfd, stream); dag_detach_stream(dagfd, stream); @@ -589,8 +569,7 @@ ReceiveErfDagCloseStream(int dagfd, int stream) * \param p pointer to the current packet * \param data pointer that gets cast into PcapThreadVars for ptv */ -TmEcode -DecodeErfDag(ThreadVars *tv, Packet *p, void *data) +TmEcode DecodeErfDag(ThreadVars *tv, Packet *p, void *data) { SCEnter(); DecodeThreadVars *dtv = (DecodeThreadVars *)data; @@ -600,8 +579,8 @@ DecodeErfDag(ThreadVars *tv, Packet *p, void *data) /* update counters */ DecodeUpdatePacketCounters(tv, dtv, p); - /* call the decoder */ - switch(p->datalink) { + /* call the decoder */ + switch (p->datalink) { case LINKTYPE_ETHERNET: DecodeEthernet(tv, dtv, p, GET_PKT_DATA(p), GET_PKT_LEN(p)); break; @@ -616,8 +595,7 @@ DecodeErfDag(ThreadVars *tv, Packet *p, void *data) SCReturnInt(TM_ECODE_OK); } -TmEcode -DecodeErfDagThreadInit(ThreadVars *tv, void *initdata, void **data) +TmEcode DecodeErfDagThreadInit(ThreadVars *tv, void *initdata, void **data) { SCEnter(); DecodeThreadVars *dtv = NULL; @@ -634,8 +612,7 @@ DecodeErfDagThreadInit(ThreadVars *tv, void *initdata, void **data) SCReturnInt(TM_ECODE_OK); } -TmEcode -DecodeErfDagThreadDeinit(ThreadVars *tv, void *data) +TmEcode DecodeErfDagThreadDeinit(ThreadVars *tv, void *data) { if (data != NULL) DecodeThreadVarsFree(tv, data); diff --git a/src/source-erf-dag.h b/src/source-erf-dag.h index e712798b8701..b95410b7310c 100644 --- a/src/source-erf-dag.h +++ b/src/source-erf-dag.h @@ -29,4 +29,3 @@ void TmModuleReceiveErfDagRegister(void); void TmModuleDecodeErfDagRegister(void); #endif /* __SOURCE_ERF_DAG_H__ */ - diff --git a/src/source-erf-file.c b/src/source-erf-file.c index 4803f8b3e28f..4c881bf37d8b 100644 --- a/src/source-erf-file.c +++ b/src/source-erf-file.c @@ -34,13 +34,13 @@ #define DAG_TYPE_ETH 2 typedef struct DagFlags_ { - uint8_t iface:2; - uint8_t vlen:1; - uint8_t trunc:1; - uint8_t rxerror:1; - uint8_t dserror:1; - uint8_t reserved:1; - uint8_t direction:1; + uint8_t iface : 2; + uint8_t vlen : 1; + uint8_t trunc : 1; + uint8_t rxerror : 1; + uint8_t dserror : 1; + uint8_t reserved : 1; + uint8_t direction : 1; } DagFlags; typedef struct DagRecord_ { @@ -76,16 +76,14 @@ static TmEcode DecodeErfFile(ThreadVars *, Packet *, void *); /** * \brief Register the ERF file receiver (reader) module. */ -void -TmModuleReceiveErfFileRegister(void) +void TmModuleReceiveErfFileRegister(void) { tmm_modules[TMM_RECEIVEERFFILE].name = "ReceiveErfFile"; tmm_modules[TMM_RECEIVEERFFILE].ThreadInit = ReceiveErfFileThreadInit; tmm_modules[TMM_RECEIVEERFFILE].Func = NULL; tmm_modules[TMM_RECEIVEERFFILE].PktAcqLoop = ReceiveErfFileLoop; tmm_modules[TMM_RECEIVEERFFILE].PktAcqBreakLoop = NULL; - tmm_modules[TMM_RECEIVEERFFILE].ThreadExitPrintStats = - ReceiveErfFileThreadExitStats; + tmm_modules[TMM_RECEIVEERFFILE].ThreadExitPrintStats = ReceiveErfFileThreadExitStats; tmm_modules[TMM_RECEIVEERFFILE].ThreadDeinit = NULL; tmm_modules[TMM_RECEIVEERFFILE].cap_flags = 0; tmm_modules[TMM_RECEIVEERFFILE].flags = TM_FLAG_RECEIVE_TM; @@ -94,8 +92,7 @@ TmModuleReceiveErfFileRegister(void) /** * \brief Register the ERF file decoder module. */ -void -TmModuleDecodeErfFileRegister(void) +void TmModuleDecodeErfFileRegister(void) { tmm_modules[TMM_DECODEERFFILE].name = "DecodeErfFile"; tmm_modules[TMM_DECODEERFFILE].ThreadInit = DecodeErfFileThreadInit; @@ -162,8 +159,7 @@ static inline TmEcode ReadErfRecord(ThreadVars *tv, Packet *p, void *data) if (r < 1) { if (feof(etv->erf)) { SCLogInfo("End of ERF file reached"); - } - else { + } else { SCLogInfo("Error reading ERF record"); } SCReturnInt(TM_ECODE_FAILED); @@ -179,8 +175,7 @@ static inline TmEcode ReadErfRecord(ThreadVars *tv, Packet *p, void *data) if (r < 1) { if (feof(etv->erf)) { SCLogInfo("End of ERF file reached"); - } - else { + } else { SCLogInfo("Error reading ERF record"); } SCReturnInt(TM_ECODE_FAILED); @@ -217,8 +212,7 @@ static inline TmEcode ReadErfRecord(ThreadVars *tv, Packet *p, void *data) /** * \brief Initialize the ERF receiver thread. */ -TmEcode -ReceiveErfFileThreadInit(ThreadVars *tv, const void *initdata, void **data) +TmEcode ReceiveErfFileThreadInit(ThreadVars *tv, const void *initdata, void **data) { SCEnter(); @@ -253,8 +247,7 @@ ReceiveErfFileThreadInit(ThreadVars *tv, const void *initdata, void **data) /** * \brief Initialize the ERF decoder thread. */ -TmEcode -DecodeErfFileThreadInit(ThreadVars *tv, const void *initdata, void **data) +TmEcode DecodeErfFileThreadInit(ThreadVars *tv, const void *initdata, void **data) { SCEnter(); DecodeThreadVars *dtv = NULL; @@ -283,8 +276,7 @@ TmEcode DecodeErfFileThreadDeinit(ThreadVars *tv, void *data) * This function ups the decoder counters and then passes the packet * off to the ethernet decoder. */ -TmEcode -DecodeErfFile(ThreadVars *tv, Packet *p, void *data) +TmEcode DecodeErfFile(ThreadVars *tv, Packet *p, void *data) { SCEnter(); DecodeThreadVars *dtv = (DecodeThreadVars *)data; @@ -307,10 +299,9 @@ DecodeErfFile(ThreadVars *tv, Packet *p, void *data) * \param tv Pointer to ThreadVars. * \param data Pointer to data, ErfFileThreadVars. */ -void -ReceiveErfFileThreadExitStats(ThreadVars *tv, void *data) +void ReceiveErfFileThreadExitStats(ThreadVars *tv, void *data) { ErfFileThreadVars *etv = (ErfFileThreadVars *)data; - SCLogInfo("Packets: %"PRIu32"; Bytes: %"PRIu64, etv->pkts, etv->bytes); + SCLogInfo("Packets: %" PRIu32 "; Bytes: %" PRIu64, etv->pkts, etv->bytes); } diff --git a/src/source-ipfw.c b/src/source-ipfw.c index 6d0f67c11572..3089624e5d60 100644 --- a/src/source-ipfw.c +++ b/src/source-ipfw.c @@ -43,7 +43,7 @@ #include "runmodes.h" #define IPFW_ACCEPT 0 -#define IPFW_DROP 1 +#define IPFW_DROP 1 #define IPFW_SOCKET_POLL_MSEC 300 @@ -58,7 +58,7 @@ TmEcode NoIPFWSupportExit(ThreadVars *, const void *, void **); -void TmModuleReceiveIPFWRegister (void) +void TmModuleReceiveIPFWRegister(void) { tmm_modules[TMM_RECEIVEIPFW].name = "ReceiveIPFW"; @@ -69,7 +69,7 @@ void TmModuleReceiveIPFWRegister (void) tmm_modules[TMM_RECEIVEIPFW].flags = TM_FLAG_RECEIVE_TM; } -void TmModuleVerdictIPFWRegister (void) +void TmModuleVerdictIPFWRegister(void) { tmm_modules[TMM_VERDICTIPFW].name = "VerdictIPFW"; tmm_modules[TMM_VERDICTIPFW].ThreadInit = NoIPFWSupportExit; @@ -78,7 +78,7 @@ void TmModuleVerdictIPFWRegister (void) tmm_modules[TMM_VERDICTIPFW].ThreadDeinit = NULL; } -void TmModuleDecodeIPFWRegister (void) +void TmModuleDecodeIPFWRegister(void) { tmm_modules[TMM_DECODEIPFW].name = "DecodeIPFW"; tmm_modules[TMM_DECODEIPFW].ThreadInit = NoIPFWSupportExit; @@ -107,8 +107,7 @@ extern uint16_t max_pending_packets; /** * \brief Structure to hold thread specific variables. */ -typedef struct IPFWThreadVars_ -{ +typedef struct IPFWThreadVars_ { /* data link type for the thread, probably not needed */ int datalink; @@ -151,7 +150,7 @@ static TmEcode DecodeIPFW(ThreadVars *, Packet *, void *); * \brief Registration Function for RecieveIPFW. * \todo Unit tests are needed for this module. */ -void TmModuleReceiveIPFWRegister (void) +void TmModuleReceiveIPFWRegister(void) { SCMutexInit(&ipfw_init_lock, NULL); @@ -172,22 +171,22 @@ void TmModuleReceiveIPFWRegister (void) * \brief Registration Function for VerdictIPFW. * \todo Unit tests are needed for this module. */ -void TmModuleVerdictIPFWRegister (void) +void TmModuleVerdictIPFWRegister(void) { tmm_modules[TMM_VERDICTIPFW].name = "VerdictIPFW"; tmm_modules[TMM_VERDICTIPFW].ThreadInit = VerdictIPFWThreadInit; tmm_modules[TMM_VERDICTIPFW].Func = VerdictIPFW; tmm_modules[TMM_VERDICTIPFW].ThreadExitPrintStats = VerdictIPFWThreadExitStats; tmm_modules[TMM_VERDICTIPFW].ThreadDeinit = VerdictIPFWThreadDeinit; - tmm_modules[TMM_VERDICTIPFW].cap_flags = SC_CAP_NET_ADMIN | SC_CAP_NET_RAW | - SC_CAP_NET_BIND_SERVICE; /** \todo untested */ + tmm_modules[TMM_VERDICTIPFW].cap_flags = + SC_CAP_NET_ADMIN | SC_CAP_NET_RAW | SC_CAP_NET_BIND_SERVICE; /** \todo untested */ } /** * \brief Registration Function for DecodeIPFW. * \todo Unit tests are needed for this module. */ -void TmModuleDecodeIPFWRegister (void) +void TmModuleDecodeIPFWRegister(void) { tmm_modules[TMM_DECODEIPFW].name = "DecodeIPFW"; tmm_modules[TMM_DECODEIPFW].ThreadInit = DecodeIPFWThreadInit; @@ -230,7 +229,7 @@ TmEcode ReceiveIPFWLoop(ThreadVars *tv, void *data, void *slot) IPFWThreadVars *ptv = (IPFWThreadVars *)data; IPFWQueueVars *nq = NULL; uint8_t pkt[IP_MAXPACKET]; - int pktlen=0; + int pktlen = 0; struct pollfd IPFWpoll; struct timeval IPFWts; Packet *p = NULL; @@ -241,8 +240,7 @@ TmEcode ReceiveIPFWLoop(ThreadVars *tv, void *data, void *slot) SCReturnInt(TM_ECODE_FAILED); } - SCLogInfo("Thread '%s' will run on port %d (item %d)", - tv->name, nq->port_num, ptv->ipfw_index); + SCLogInfo("Thread '%s' will run on port %d (item %d)", tv->name, nq->port_num, ptv->ipfw_index); // Indicate that the thread is actually running its application level code (i.e., it can poll // packets) @@ -256,14 +254,13 @@ TmEcode ReceiveIPFWLoop(ThreadVars *tv, void *data, void *slot) IPFWpoll.fd = nq->fd; IPFWpoll.events = POLLRDNORM; /* Poll the socket for status */ - if ( (poll(&IPFWpoll, 1, IPFW_SOCKET_POLL_MSEC)) > 0) { + if ((poll(&IPFWpoll, 1, IPFW_SOCKET_POLL_MSEC)) > 0) { if (!(IPFWpoll.revents & (POLLRDNORM | POLLERR))) continue; } - if ((pktlen = recvfrom(nq->fd, pkt, sizeof(pkt), 0, - (struct sockaddr *)&nq->ipfw_sin, - &nq->ipfw_sinlen)) == -1) { + if ((pktlen = recvfrom(nq->fd, pkt, sizeof(pkt), 0, (struct sockaddr *)&nq->ipfw_sin, + &nq->ipfw_sinlen)) == -1) { /* We received an error on socket read */ if (errno == EINTR || errno == EWOULDBLOCK) { /* Nothing for us to process */ @@ -274,7 +271,7 @@ TmEcode ReceiveIPFWLoop(ThreadVars *tv, void *data, void *slot) } } /* We have a packet to process */ - memset (&IPFWts, 0, sizeof(struct timeval)); + memset(&IPFWts, 0, sizeof(struct timeval)); gettimeofday(&IPFWts, NULL); /* make sure we have at least one packet in the packet pool, to prevent @@ -299,11 +296,10 @@ TmEcode ReceiveIPFWLoop(ThreadVars *tv, void *data, void *slot) p->ipfw_v.ipfw_index = ptv->ipfw_index; PacketCopyData(p, pkt, pktlen); - SCLogDebug("Packet info: pkt_len: %" PRIu32 " (pkt %02x, pkt_data %02x)", - GET_PKT_LEN(p), *pkt, *(GET_PKT_DATA(p))); + SCLogDebug("Packet info: pkt_len: %" PRIu32 " (pkt %02x, pkt_data %02x)", GET_PKT_LEN(p), + *pkt, *(GET_PKT_DATA(p))); - if (TmThreadsSlotProcessPkt(tv, ((TmSlot *) slot)->slot_next, p) - != TM_ECODE_OK) { + if (TmThreadsSlotProcessPkt(tv, ((TmSlot *)slot)->slot_next, p) != TM_ECODE_OK) { SCReturnInt(TM_ECODE_FAILED); } @@ -328,7 +324,7 @@ TmEcode ReceiveIPFWLoop(ThreadVars *tv, void *data, void *slot) TmEcode ReceiveIPFWThreadInit(ThreadVars *tv, const void *initdata, void **data) { struct timeval timev; - IPFWThreadVars *ntv = (IPFWThreadVars *) initdata; + IPFWThreadVars *ntv = (IPFWThreadVars *)initdata; IPFWQueueVars *nq = IPFWGetQueue(ntv->ipfw_index); sigset_t sigs; @@ -358,7 +354,7 @@ TmEcode ReceiveIPFWThreadInit(ThreadVars *tv, const void *initdata, void **data) SCReturnInt(TM_ECODE_FAILED); } - nq->ipfw_sinlen=sizeof(nq->ipfw_sin); + nq->ipfw_sinlen = sizeof(nq->ipfw_sin); memset(&nq->ipfw_sin, 0, nq->ipfw_sinlen); nq->ipfw_sin.sin_family = PF_INET; nq->ipfw_sin.sin_addr.s_addr = INADDR_ANY; @@ -390,11 +386,10 @@ void ReceiveIPFWThreadExitStats(ThreadVars *tv, void *data) SCEnter(); - SCLogNotice("(%s) Treated: Pkts %" PRIu32 ", Bytes %" PRIu64 ", Errors %" PRIu32 "", - tv->name, ptv->pkts, ptv->bytes, ptv->errs); - SCLogNotice("(%s) Verdict: Accepted %"PRIu32", Dropped %"PRIu32 "", - tv->name, ptv->accepted, ptv->dropped); - + SCLogNotice("(%s) Treated: Pkts %" PRIu32 ", Bytes %" PRIu64 ", Errors %" PRIu32 "", tv->name, + ptv->pkts, ptv->bytes, ptv->errs); + SCLogNotice("(%s) Verdict: Accepted %" PRIu32 ", Dropped %" PRIu32 "", tv->name, ptv->accepted, + ptv->dropped); SCReturn; } @@ -453,7 +448,7 @@ TmEcode DecodeIPFW(ThreadVars *tv, Packet *p, void *data) SCLogDebug("DecodeIPFW ip4 processing"); DecodeIPV4(tv, dtv, p, GET_PKT_DATA(p), GET_PKT_LEN(p)); - } else if(IPV6_GET_RAW_VER(ip6h) == 6) { + } else if (IPV6_GET_RAW_VER(ip6h) == 6) { if (unlikely(GET_PKT_LEN(p) > USHRT_MAX)) { return TM_ECODE_FAILED; } @@ -463,7 +458,7 @@ TmEcode DecodeIPFW(ThreadVars *tv, Packet *p, void *data) } else { /* We don't support anything besides IP packets for now, bridged packets? */ SCLogInfo("IPFW unknown protocol support %02x", *GET_PKT_DATA(p)); - SCReturnInt(TM_ECODE_FAILED); + SCReturnInt(TM_ECODE_FAILED); } PacketDecodeFinalize(tv, dtv, p); @@ -547,7 +542,8 @@ TmEcode IPFWSetVerdict(ThreadVars *tv, IPFWThreadVars *ptv, Packet *p) /* For divert sockets, accepting means writing the * packet back to the socket for ipfw to pick up */ - SCLogDebug("IPFWSetVerdict writing to socket %d, %p, %u", nq->fd, GET_PKT_DATA(p),GET_PKT_LEN(p)); + SCLogDebug("IPFWSetVerdict writing to socket %d, %p, %u", nq->fd, GET_PKT_DATA(p), + GET_PKT_LEN(p)); #if 0 while ((poll(&IPFWpoll,1,IPFW_SOCKET_POLL_MSEC)) < 1) { @@ -560,7 +556,8 @@ TmEcode IPFWSetVerdict(ThreadVars *tv, IPFWThreadVars *ptv, Packet *p) #endif IPFWMutexLock(nq); - if (sendto(nq->fd, GET_PKT_DATA(p), GET_PKT_LEN(p), 0,(struct sockaddr *)&nq->ipfw_sin, nq->ipfw_sinlen) == -1) { + if (sendto(nq->fd, GET_PKT_DATA(p), GET_PKT_LEN(p), 0, (struct sockaddr *)&nq->ipfw_sin, + nq->ipfw_sinlen) == -1) { int r = errno; switch (r) { default: @@ -575,11 +572,10 @@ TmEcode IPFWSetVerdict(ThreadVars *tv, IPFWThreadVars *ptv, Packet *p) IPFWMutexUnlock(nq); - SCLogDebug("Sent Packet back into IPFW Len: %d",GET_PKT_LEN(p)); + SCLogDebug("Sent Packet back into IPFW Len: %d", GET_PKT_LEN(p)); } /* end IPFW_ACCEPT */ - if (verdict == IPFW_DROP) { SCLogDebug("IPFW SetVerdict is to DROP"); ptv->dropped++; @@ -592,7 +588,6 @@ TmEcode IPFWSetVerdict(ThreadVars *tv, IPFWThreadVars *ptv, Packet *p) SCReturnInt(TM_ECODE_OK); } - /** * \brief This function handles the Verdict processing * \todo Unit tests are needed for this module. @@ -672,7 +667,6 @@ TmEcode VerdictIPFWThreadDeinit(ThreadVars *tv, void *data) /* We don't need to do anything...not sure quite yet */ - SCReturnInt(TM_ECODE_OK); } @@ -686,7 +680,8 @@ TmEcode VerdictIPFWThreadDeinit(ThreadVars *tv, void *data) void VerdictIPFWThreadExitStats(ThreadVars *tv, void *data) { IPFWThreadVars *ptv = (IPFWThreadVars *)data; - SCLogInfo("IPFW Processing: - (%s) Pkts accepted %" PRIu32 ", dropped %" PRIu32 "", tv->name, ptv->accepted, ptv->dropped); + SCLogInfo("IPFW Processing: - (%s) Pkts accepted %" PRIu32 ", dropped %" PRIu32 "", tv->name, + ptv->accepted, ptv->dropped); } /** @@ -703,8 +698,7 @@ int IPFWRegisterQueue(char *queue) IPFWQueueVars *nq = NULL; /* Extract the queue number from the specified command line argument */ uint16_t port_num = 0; - if ((StringParseUint16(&port_num, 10, strlen(queue), queue)) < 0) - { + if ((StringParseUint16(&port_num, 10, strlen(queue), queue)) < 0) { SCLogError("specified queue number %s is not " "valid", queue); @@ -772,4 +766,3 @@ void *IPFWGetThread(int number) #endif /* End ifdef IPFW */ /* eof */ - diff --git a/src/source-ipfw.h b/src/source-ipfw.h index 94c560a4ba7f..94662ce8f5cd 100644 --- a/src/source-ipfw.h +++ b/src/source-ipfw.h @@ -28,13 +28,11 @@ #define IPFW_MAX_QUEUE 16 /* per packet IPFW vars (Not used) */ -typedef struct IPFWPacketVars_ -{ +typedef struct IPFWPacketVars_ { int ipfw_index; } IPFWPacketVars; -typedef struct IPFWQueueVars_ -{ +typedef struct IPFWQueueVars_ { int fd; SCMutex socket_lock; uint8_t use_mutex; @@ -62,9 +60,8 @@ typedef struct IPFWQueueVars_ void *IPFWGetThread(int number); int IPFWRegisterQueue(char *queue); -void TmModuleReceiveIPFWRegister (void); -void TmModuleVerdictIPFWRegister (void); -void TmModuleDecodeIPFWRegister (void); - +void TmModuleReceiveIPFWRegister(void); +void TmModuleVerdictIPFWRegister(void); +void TmModuleDecodeIPFWRegister(void); #endif /* __SOURCE_IPFW_H__ */ diff --git a/src/source-napatech.c b/src/source-napatech.c index 071d9ae68416..d6f2aae9aaa5 100644 --- a/src/source-napatech.c +++ b/src/source-napatech.c @@ -44,7 +44,7 @@ #ifndef HAVE_NAPATECH -TmEcode NoNapatechSupportExit(ThreadVars*, const void*, void**); +TmEcode NoNapatechSupportExit(ThreadVars *, const void *, void **); void TmModuleNapatechStreamRegister(void) { @@ -77,14 +77,12 @@ TmEcode NoNapatechSupportExit(ThreadVars *tv, const void *initdata, void **data) #else /* Implied we do have NAPATECH support */ - #include #include extern uint16_t max_pending_packets; -typedef struct NapatechThreadVars_ -{ +typedef struct NapatechThreadVars_ { ThreadVars *tv; NtNetStreamRx_t rx_stream; uint16_t stream_id; @@ -204,79 +202,74 @@ void TmModuleNapatechDecodeRegister(void) /** * \brief template of IPv4 header */ -struct ipv4_hdr -{ - uint8_t version_ihl; /**< version and header length */ - uint8_t type_of_service; /**< type of service */ - uint16_t total_length; /**< length of packet */ - uint16_t packet_id; /**< packet ID */ +struct ipv4_hdr { + uint8_t version_ihl; /**< version and header length */ + uint8_t type_of_service; /**< type of service */ + uint16_t total_length; /**< length of packet */ + uint16_t packet_id; /**< packet ID */ uint16_t fragment_offset; /**< fragmentation offset */ - uint8_t time_to_live; /**< time to live */ - uint8_t next_proto_id; /**< protocol ID */ - uint16_t hdr_checksum; /**< header checksum */ - uint32_t src_addr; /**< source address */ - uint32_t dst_addr; /**< destination address */ -} __attribute__ ((__packed__)); + uint8_t time_to_live; /**< time to live */ + uint8_t next_proto_id; /**< protocol ID */ + uint16_t hdr_checksum; /**< header checksum */ + uint32_t src_addr; /**< source address */ + uint32_t dst_addr; /**< destination address */ +} __attribute__((__packed__)); /** * \brief template of IPv6 header */ -struct ipv6_hdr -{ - uint32_t vtc_flow; /**< IP version, traffic class & flow label. */ +struct ipv6_hdr { + uint32_t vtc_flow; /**< IP version, traffic class & flow label. */ uint16_t payload_len; /**< IP packet length - includes sizeof(ip_header). */ - uint8_t proto; /**< Protocol, next header. */ - uint8_t hop_limits; /**< Hop limits. */ + uint8_t proto; /**< Protocol, next header. */ + uint8_t hop_limits; /**< Hop limits. */ uint8_t src_addr[16]; /**< IP address of source host. */ uint8_t dst_addr[16]; /**< IP address of destination host(s). */ -} __attribute__ ((__packed__)); +} __attribute__((__packed__)); /** * \brief template of UDP header */ -struct udp_hdr -{ - uint16_t src_port; /**< UDP source port. */ - uint16_t dst_port; /**< UDP destination port. */ - uint16_t dgram_len; /**< UDP datagram length */ +struct udp_hdr { + uint16_t src_port; /**< UDP source port. */ + uint16_t dst_port; /**< UDP destination port. */ + uint16_t dgram_len; /**< UDP datagram length */ uint16_t dgram_cksum; /**< UDP datagram checksum */ -} __attribute__ ((__packed__)); +} __attribute__((__packed__)); /** * \brief template of TCP header */ -struct tcp_hdr -{ +struct tcp_hdr { uint16_t src_port; /**< TCP source port. */ uint16_t dst_port; /**< TCP destination port. */ uint32_t sent_seq; /**< TX data sequence number. */ uint32_t recv_ack; /**< RX data acknowledgement sequence number. */ - uint8_t data_off; /**< Data offset. */ + uint8_t data_off; /**< Data offset. */ uint8_t tcp_flags; /**< TCP flags */ - uint16_t rx_win; /**< RX flow control window. */ - uint16_t cksum; /**< TCP checksum. */ - uint16_t tcp_urp; /**< TCP urgent pointer, if any. */ -} __attribute__ ((__packed__)); - + uint16_t rx_win; /**< RX flow control window. */ + uint16_t cksum; /**< TCP checksum. */ + uint16_t tcp_urp; /**< TCP urgent pointer, if any. */ +} __attribute__((__packed__)); /* The hardware will assign a "color" value indicating what filters are matched * by a given packet. These constants indicate what bits are set in the color * field for different protocols * */ -#define RTE_PTYPE_L2_ETHER 0x10000000 -#define RTE_PTYPE_L3_IPV4 0x01000000 -#define RTE_PTYPE_L3_IPV6 0x04000000 -#define RTE_PTYPE_L4_TCP 0x00100000 -#define RTE_PTYPE_L4_UDP 0x00200000 +#define RTE_PTYPE_L2_ETHER 0x10000000 +#define RTE_PTYPE_L3_IPV4 0x01000000 +#define RTE_PTYPE_L3_IPV6 0x04000000 +#define RTE_PTYPE_L4_TCP 0x00100000 +#define RTE_PTYPE_L4_UDP 0x00200000 /* These masks are used to extract layer 3 and layer 4 protocol * values from the color field in the packet descriptor. */ -#define RTE_PTYPE_L3_MASK 0x0f000000 -#define RTE_PTYPE_L4_MASK 0x00f00000 +#define RTE_PTYPE_L3_MASK 0x0f000000 +#define RTE_PTYPE_L4_MASK 0x00f00000 -#define COLOR_IS_SPAN 0x00001000 +#define COLOR_IS_SPAN 0x00001000 static int is_inline = 0; static int inline_port_map[MAX_PORTS] = { -1 }; @@ -316,7 +309,7 @@ int NapatechGetAdapter(uint8_t port) { static int port_adapter_map[MAX_PORTS] = { -1 }; int status; - NtInfo_t h_info; /* Info handle */ + NtInfo_t h_info; /* Info handle */ NtInfoStream_t h_info_stream; /* Info stream handle */ if (unlikely(port_adapter_map[port] == -1)) { @@ -326,7 +319,7 @@ int NapatechGetAdapter(uint8_t port) } /* Read the system info */ h_info.cmd = NT_INFO_CMD_READ_PORT_V9; - h_info.u.port_v9.portNo = (uint8_t) port; + h_info.u.port_v9.portNo = (uint8_t)port; if ((status = NT_InfoRead(h_info_stream, &h_info)) != NT_SUCCESS) { /* Get the status code as text */ NAPATECH_ERROR(status); @@ -341,8 +334,7 @@ int NapatechGetAdapter(uint8_t port) /** * \brief IPv4 4-tuple convenience structure */ -struct IPv4Tuple4 -{ +struct IPv4Tuple4 { uint32_t sa; /*!< Source address */ uint32_t da; /*!< Destination address */ uint16_t sp; /*!< Source port */ @@ -352,8 +344,7 @@ struct IPv4Tuple4 /** * \brief IPv6 4-tuple convenience structure */ -struct IPv6Tuple4 -{ +struct IPv6Tuple4 { uint8_t sa[16]; /*!< Source address */ uint8_t da[16]; /*!< Destination address */ uint16_t sp; /*!< Source port */ @@ -371,7 +362,8 @@ struct IPv6Tuple4 * 1 if addr_a > addr_b * 0 if addr_a == addr_b */ -static int CompareIPv6Addr(uint8_t addr_a[16], uint8_t addr_b[16]) { +static int CompareIPv6Addr(uint8_t addr_a[16], uint8_t addr_b[16]) +{ uint16_t pos; for (pos = 0; pos < 16; ++pos) { if (addr_a[pos] < addr_b[pos]) { @@ -405,7 +397,7 @@ static NtFlowStream_t InitFlowStream(int adapter, int stream_id) NT_FlowOpenAttrInit(&attr); NT_FlowOpenAttrSetAdapterNo(&attr, adapter); - snprintf(flow_name, sizeof(flow_name), "Flow_stream_%d", stream_id ); + snprintf(flow_name, sizeof(flow_name), "Flow_stream_%d", stream_id); SCLogDebug("Opening flow programming stream: %s", flow_name); if ((status = NT_FlowOpen_Attr(&hFlowStream, flow_name, &attr)) != NT_SUCCESS) { SCLogWarning("Napatech bypass functionality not supported by the FPGA version on adapter " @@ -442,7 +434,7 @@ static int ProgramFlow(Packet *p, int inline_mode) * the protocols and if the packet is coming in from a SPAN port. */ uint32_t packet_type = ((ntpv->dyn3->color_hi << 14) & 0xFFFFC000) | ntpv->dyn3->color_lo; - uint8_t *packet = (uint8_t *) ntpv->dyn3 + ntpv->dyn3->descrLength; + uint8_t *packet = (uint8_t *)ntpv->dyn3 + ntpv->dyn3->descrLength; uint32_t layer3 = packet_type & RTE_PTYPE_L3_MASK; uint32_t layer4 = packet_type & RTE_PTYPE_L4_MASK; @@ -464,9 +456,12 @@ static int ProgramFlow(Packet *p, int inline_mode) /* Only bypass TCP and UDP */ if (PKT_IS_TCP(p)) { SC_ATOMIC_ADD(flow_callback_tcp_pkts, 1); - } else if PKT_IS_UDP(p) { - SC_ATOMIC_ADD(flow_callback_udp_pkts, 1); - } else { + } else if + PKT_IS_UDP(p) + { + SC_ATOMIC_ADD(flow_callback_udp_pkts, 1); + } + else { SC_ATOMIC_ADD(flow_callback_unhandled_pkts, 1); } @@ -476,9 +471,8 @@ static int ProgramFlow(Packet *p, int inline_mode) struct ipv6_hdr *pIPv6_hdr = NULL; switch (layer3) { - case RTE_PTYPE_L3_IPV4: - { - pIPv4_hdr = (struct ipv4_hdr *) (packet + ntpv->dyn3->offset0); + case RTE_PTYPE_L3_IPV4: { + pIPv4_hdr = (struct ipv4_hdr *)(packet + ntpv->dyn3->offset0); if (!is_span) { v4Tuple.sa = pIPv4_hdr->src_addr; v4Tuple.da = pIPv4_hdr->dst_addr; @@ -495,9 +489,8 @@ static int ProgramFlow(Packet *p, int inline_mode) } break; } - case RTE_PTYPE_L3_IPV6: - { - pIPv6_hdr = (struct ipv6_hdr *) (packet + ntpv->dyn3->offset0); + case RTE_PTYPE_L3_IPV6: { + pIPv6_hdr = (struct ipv6_hdr *)(packet + ntpv->dyn3->offset0); do_swap = (CompareIPv6Addr(pIPv6_hdr->src_addr, pIPv6_hdr->dst_addr) > 0); if (!is_span) { @@ -516,16 +509,14 @@ static int ProgramFlow(Packet *p, int inline_mode) } break; } - default: - { + default: { return 0; } } switch (layer4) { - case RTE_PTYPE_L4_TCP: - { - struct tcp_hdr *tcp_hdr = (struct tcp_hdr *) (packet + ntpv->dyn3->offset1); + case RTE_PTYPE_L4_TCP: { + struct tcp_hdr *tcp_hdr = (struct tcp_hdr *)(packet + ntpv->dyn3->offset1); if (layer3 == RTE_PTYPE_L3_IPV4) { if (!is_span) { v4Tuple.dp = tcp_hdr->dst_port; @@ -562,9 +553,8 @@ static int ProgramFlow(Packet *p, int inline_mode) flow_match.ipProtocolField = 6; break; } - case RTE_PTYPE_L4_UDP: - { - struct udp_hdr *udp_hdr = (struct udp_hdr *) (packet + ntpv->dyn3->offset1); + case RTE_PTYPE_L4_UDP: { + struct udp_hdr *udp_hdr = (struct udp_hdr *)(packet + ntpv->dyn3->offset1); if (layer3 == RTE_PTYPE_L3_IPV4) { if (!is_span) { v4Tuple.dp = udp_hdr->dst_port; @@ -601,8 +591,7 @@ static int ProgramFlow(Packet *p, int inline_mode) flow_match.ipProtocolField = 17; break; } - default: - { + default: { return 0; } } @@ -672,16 +661,16 @@ static int NapatechBypassCallback(Packet *p) TmEcode NapatechStreamThreadInit(ThreadVars *tv, const void *initdata, void **data) { SCEnter(); - struct NapatechStreamDevConf *conf = (struct NapatechStreamDevConf *) initdata; + struct NapatechStreamDevConf *conf = (struct NapatechStreamDevConf *)initdata; uint16_t stream_id = conf->stream_id; *data = NULL; - NapatechThreadVars *ntv = SCCalloc(1, sizeof (NapatechThreadVars)); + NapatechThreadVars *ntv = SCCalloc(1, sizeof(NapatechThreadVars)); if (unlikely(ntv == NULL)) { FatalError("Failed to allocate memory for NAPATECH thread vars."); } - memset(ntv, 0, sizeof (NapatechThreadVars)); + memset(ntv, 0, sizeof(NapatechThreadVars)); ntv->stream_id = stream_id; ntv->tv = tv; @@ -689,7 +678,7 @@ TmEcode NapatechStreamThreadInit(ThreadVars *tv, const void *initdata, void **da SCLogDebug("Started processing packets from NAPATECH Stream: %u", ntv->stream_id); - *data = (void *) ntv; + *data = (void *)ntv; SCReturnInt(TM_ECODE_OK); } @@ -855,8 +844,7 @@ TmEcode NapatechPacketLoop(ThreadVars *tv, void *data, void *slot) } #endif /* The last thread to run sets up and deletes the streams */ - status = NapatechSetupTraffic(NapatechGetNumFirstStream(), - NapatechGetNumLastStream()); + status = NapatechSetupTraffic(NapatechGetNumFirstStream(), NapatechGetNumLastStream()); closer = 1; @@ -871,8 +859,7 @@ TmEcode NapatechPacketLoop(ThreadVars *tv, void *data, void *slot) } } // is_autoconfig - SCLogInfo( - "Napatech Packet Loop Started - cpu: %3d, cpu_numa: %3d stream: %3u ", + SCLogInfo("Napatech Packet Loop Started - cpu: %3d, cpu_numa: %3d stream: %3u ", sched_getcpu(), numa_node, ntv->stream_id); SCLogDebug("Opening NAPATECH Stream: %u for processing", ntv->stream_id); @@ -884,7 +871,7 @@ TmEcode NapatechPacketLoop(ThreadVars *tv, void *data, void *slot) SCFree(ntv); SCReturnInt(TM_ECODE_FAILED); } - TmSlot *s = (TmSlot *) slot; + TmSlot *s = (TmSlot *)slot; ntv->slot = s->slot_next; // Indicate that the thread is actually running its application level code (i.e., it can poll @@ -898,16 +885,14 @@ TmEcode NapatechPacketLoop(ThreadVars *tv, void *data, void *slot) /* Napatech returns packets 1 at a time */ status = NT_NetRxGet(ntv->rx_stream, &packet_buffer, 1000); - if (unlikely( - status == NT_STATUS_TIMEOUT || status == NT_STATUS_TRYAGAIN)) { + if (unlikely(status == NT_STATUS_TIMEOUT || status == NT_STATUS_TRYAGAIN)) { if (status == NT_STATUS_TIMEOUT) { TmThreadsCaptureHandleTimeout(tv, NULL); } continue; } else if (unlikely(status != NT_SUCCESS)) { NAPATECH_ERROR(status); - SCLogInfo("Failed to read from Napatech Stream %d: %s", - ntv->stream_id, error_buffer); + SCLogInfo("Failed to read from Napatech Stream %d: %s", ntv->stream_id, error_buffer); break; } @@ -967,7 +952,8 @@ TmEcode NapatechPacketLoop(ThreadVars *tv, void *data, void *slot) p->ntpv.stream_id = ntv->stream_id; p->datalink = LINKTYPE_ETHERNET; - if (unlikely(PacketSetData(p, (uint8_t *)NT_NET_GET_PKT_L2_PTR(packet_buffer), NT_NET_GET_PKT_WIRE_LENGTH(packet_buffer)))) { + if (unlikely(PacketSetData(p, (uint8_t *)NT_NET_GET_PKT_L2_PTR(packet_buffer), + NT_NET_GET_PKT_WIRE_LENGTH(packet_buffer)))) { TmqhOutputPacketpool(ntv->tv, p); SCReturnInt(TM_ECODE_FAILED); } @@ -999,17 +985,17 @@ TmEcode NapatechPacketLoop(ThreadVars *tv, void *data, void *slot) */ void NapatechStreamThreadExitStats(ThreadVars *tv, void *data) { - NapatechThreadVars *ntv = (NapatechThreadVars *) data; + NapatechThreadVars *ntv = (NapatechThreadVars *)data; NapatechCurrentStats stat = NapatechGetCurrentStats(ntv->stream_id); double percent = 0; if (stat.current_drop_packets > 0) - percent = (((double) stat.current_drop_packets) - / (stat.current_packets + stat.current_drop_packets)) * 100; + percent = (((double)stat.current_drop_packets) / + (stat.current_packets + stat.current_drop_packets)) * + 100; - SCLogInfo("nt%lu - pkts: %lu; drop: %lu (%5.2f%%); bytes: %lu", - (uint64_t) ntv->stream_id, stat.current_packets, - stat.current_drop_packets, percent, stat.current_bytes); + SCLogInfo("nt%lu - pkts: %lu; drop: %lu (%5.2f%%); bytes: %lu", (uint64_t)ntv->stream_id, + stat.current_packets, stat.current_drop_packets, percent, stat.current_bytes); SC_ATOMIC_ADD(total_packets, stat.current_packets); SC_ATOMIC_ADD(total_drops, stat.current_drop_packets); @@ -1017,8 +1003,9 @@ void NapatechStreamThreadExitStats(ThreadVars *tv, void *data) if (SC_ATOMIC_GET(total_tallied) == NapatechGetNumConfiguredStreams()) { if (SC_ATOMIC_GET(total_drops) > 0) - percent = (((double) SC_ATOMIC_GET(total_drops)) / (SC_ATOMIC_GET(total_packets) - + SC_ATOMIC_GET(total_drops))) * 100; + percent = (((double)SC_ATOMIC_GET(total_drops)) / + (SC_ATOMIC_GET(total_packets) + SC_ATOMIC_GET(total_drops))) * + 100; SCLogInfo(" "); SCLogInfo("--- Total Packets: %ld Total Dropped: %ld (%5.2f%%)", @@ -1026,10 +1013,8 @@ void NapatechStreamThreadExitStats(ThreadVars *tv, void *data) #ifdef NAPATECH_ENABLE_BYPASS SCLogInfo("--- BypassCB - Total: %ld, UDP: %ld, TCP: %ld, Unhandled: %ld", - SC_ATOMIC_GET(flow_callback_cnt), - SC_ATOMIC_GET(flow_callback_udp_pkts), - SC_ATOMIC_GET(flow_callback_tcp_pkts), - SC_ATOMIC_GET(flow_callback_unhandled_pkts)); + SC_ATOMIC_GET(flow_callback_cnt), SC_ATOMIC_GET(flow_callback_udp_pkts), + SC_ATOMIC_GET(flow_callback_tcp_pkts), SC_ATOMIC_GET(flow_callback_unhandled_pkts)); #endif } } @@ -1042,7 +1027,7 @@ void NapatechStreamThreadExitStats(ThreadVars *tv, void *data) TmEcode NapatechStreamThreadDeinit(ThreadVars *tv, void *data) { SCEnter(); - NapatechThreadVars *ntv = (NapatechThreadVars *) data; + NapatechThreadVars *ntv = (NapatechThreadVars *)data; SCLogDebug("Closing Napatech Stream: %d", ntv->stream_id); NT_NetRxClose(ntv->rx_stream); @@ -1064,7 +1049,7 @@ TmEcode NapatechDecode(ThreadVars *tv, Packet *p, void *data) { SCEnter(); - DecodeThreadVars *dtv = (DecodeThreadVars *) data; + DecodeThreadVars *dtv = (DecodeThreadVars *)data; BUG_ON(PKT_IS_PSEUDOPKT(p)); @@ -1102,7 +1087,7 @@ TmEcode NapatechDecodeThreadInit(ThreadVars *tv, const void *initdata, void **da } DecodeRegisterPerfCounters(dtv, tv); - *data = (void *) dtv; + *data = (void *)dtv; SCReturnInt(TM_ECODE_OK); } diff --git a/src/source-napatech.h b/src/source-napatech.h index c638f89dae64..cfae5f5b6b6c 100644 --- a/src/source-napatech.h +++ b/src/source-napatech.h @@ -31,8 +31,7 @@ void TmModuleNapatechDecodeRegister(void); #ifdef HAVE_NAPATECH #include -struct NapatechStreamDevConf -{ +struct NapatechStreamDevConf { uint16_t stream_id; }; diff --git a/src/source-netmap.c b/src/source-netmap.c index 0b04b41b52d6..764d20c1530a 100644 --- a/src/source-netmap.c +++ b/src/source-netmap.c @@ -16,10 +16,10 @@ */ /** -* \defgroup netmap Netmap running mode -* -* @{ -*/ + * \defgroup netmap Netmap running mode + * + * @{ + */ /** * \file @@ -62,8 +62,8 @@ #ifndef HAVE_NETMAP /** -* \brief this function prints an error message and exits. -*/ + * \brief this function prints an error message and exits. + */ static TmEcode NoNetmapSupportExit(ThreadVars *tv, const void *initdata, void **data) { FatalError("Error creating thread %s: Netmap is not enabled. " @@ -71,7 +71,7 @@ static TmEcode NoNetmapSupportExit(ThreadVars *tv, const void *initdata, void ** tv->name); } -void TmModuleReceiveNetmapRegister (void) +void TmModuleReceiveNetmapRegister(void) { tmm_modules[TMM_RECEIVENETMAP].name = "ReceiveNetmap"; tmm_modules[TMM_RECEIVENETMAP].ThreadInit = NoNetmapSupportExit; @@ -79,9 +79,9 @@ void TmModuleReceiveNetmapRegister (void) } /** -* \brief Registration Function for DecodeNetmap. -*/ -void TmModuleDecodeNetmapRegister (void) + * \brief Registration Function for DecodeNetmap. + */ +void TmModuleDecodeNetmapRegister(void) { tmm_modules[TMM_DECODENETMAP].name = "DecodeNetmap"; tmm_modules[TMM_DECODENETMAP].ThreadInit = NoNetmapSupportExit; @@ -95,14 +95,14 @@ void TmModuleDecodeNetmapRegister (void) #define POLL_TIMEOUT 100 #if defined(__linux__) -#define POLL_EVENTS (POLLHUP|POLLRDHUP|POLLERR|POLLNVAL) +#define POLL_EVENTS (POLLHUP | POLLRDHUP | POLLERR | POLLNVAL) #ifndef IFF_PPROMISC #define IFF_PPROMISC IFF_PROMISC #endif #else -#define POLL_EVENTS (POLLHUP|POLLERR|POLLNVAL) +#define POLL_EVENTS (POLLHUP | POLLERR | POLLNVAL) #endif enum { NETMAP_FLAG_ZERO_COPY = 1, NETMAP_FLAG_EXCL_RING_ACCESS = 2 }; @@ -111,8 +111,7 @@ enum { NETMAP_FLAG_ZERO_COPY = 1, NETMAP_FLAG_EXCL_RING_ACCESS = 2 }; * \brief Netmap device instance. Each ring for each device gets its own * device. */ -typedef struct NetmapDevice_ -{ +typedef struct NetmapDevice_ { struct nmport_d *nmd; unsigned int ref; SC_ATOMIC_DECLARE(unsigned int, threads_run); @@ -130,8 +129,7 @@ typedef struct NetmapDevice_ /** * \brief Module thread local variables. */ -typedef struct NetmapThreadVars_ -{ +typedef struct NetmapThreadVars_ { /* receive interface */ NetmapDevice *ifsrc; /* dst interface for IPS mode */ @@ -283,10 +281,8 @@ static int NetmapOpen(NetmapIfaceSettings *ns, NetmapDevice **pdevice, int verbo char base_name[IFNAMSIZ]; strlcpy(base_name, ns->iface, sizeof(base_name)); if (strlen(base_name) > 0 && - (base_name[strlen(base_name)-1] == '^' || - base_name[strlen(base_name)-1] == '*')) - { - base_name[strlen(base_name)-1] = '\0'; + (base_name[strlen(base_name) - 1] == '^' || base_name[strlen(base_name) - 1] == '*')) { + base_name[strlen(base_name) - 1] = '\0'; } if (ns->real) { @@ -305,7 +301,7 @@ static int NetmapOpen(NetmapIfaceSettings *ns, NetmapDevice **pdevice, int verbo goto error; } /* if needed, try to set iface in promisc mode */ - if (ns->promisc && (if_flags & (IFF_PROMISC|IFF_PPROMISC)) == 0) { + if (ns->promisc && (if_flags & (IFF_PROMISC | IFF_PPROMISC)) == 0) { if_flags |= IFF_PPROMISC; SetIfaceFlags(base_name, if_flags); // TODO reset at exit // TODO move to parse config? @@ -326,7 +322,7 @@ static int NetmapOpen(NetmapIfaceSettings *ns, NetmapDevice **pdevice, int verbo /* Search for interface in our already opened list. */ /* We will find it when opening multiple rings on */ /* the device when it exposes multiple RSS queues. */ - TAILQ_FOREACH(spdev, &netmap_devlist, next) { + TAILQ_FOREACH (spdev, &netmap_devlist, next) { SCLogDebug("spdev %s", spdev->ifname); if (direction == spdev->direction && strcmp(ns->iface, spdev->ifname) == 0) { ring = spdev->ring + 1; @@ -379,14 +375,15 @@ static int NetmapOpen(NetmapIfaceSettings *ns, NetmapDevice **pdevice, int verbo char devname[128]; if (strncmp(ns->iface, "netmap:", 7) == 0) { - snprintf(devname, sizeof(devname), "%s}%d%s%s", - ns->iface, ring, strlen(optstr) ? "/" : "", optstr); - } else if (strlen(ns->iface) > 5 && strncmp(ns->iface, "vale", 4) == 0 && isdigit(ns->iface[4])) { + snprintf(devname, sizeof(devname), "%s}%d%s%s", ns->iface, ring, strlen(optstr) ? "/" : "", + optstr); + } else if (strlen(ns->iface) > 5 && strncmp(ns->iface, "vale", 4) == 0 && + isdigit(ns->iface[4])) { snprintf(devname, sizeof(devname), "%s", ns->iface); } else if (ring == 0 && ns->threads == 1) { /* just a single thread and ring, so don't use ring param */ - snprintf(devname, sizeof(devname), "netmap:%s%s%s", - ns->iface, strlen(optstr) ? "/" : "", optstr); + snprintf(devname, sizeof(devname), "netmap:%s%s%s", ns->iface, strlen(optstr) ? "/" : "", + optstr); SCLogDebug("device with %s-ring enabled (devname): %s", soft ? "SW" : "HW", devname); } else { /* Going to be using multiple threads and rings */ @@ -486,8 +483,8 @@ static inline void NetmapDumpCounters(NetmapThreadVars *ntv) { StatsAddUI64(ntv->tv, ntv->capture_kernel_packets, ntv->pkts); StatsAddUI64(ntv->tv, ntv->capture_kernel_drops, ntv->drops); - (void) SC_ATOMIC_ADD(ntv->livedev->drop, ntv->drops); - (void) SC_ATOMIC_ADD(ntv->livedev->pkts, ntv->pkts); + (void)SC_ATOMIC_ADD(ntv->livedev->drop, ntv->drops); + (void)SC_ATOMIC_ADD(ntv->livedev->pkts, ntv->pkts); ntv->drops = 0; ntv->pkts = 0; } @@ -548,23 +545,19 @@ static TmEcode ReceiveNetmapThreadInit(ThreadVars *tv, const void *initdata, voi } /* basic counters */ - ntv->capture_kernel_packets = StatsRegisterCounter("capture.kernel_packets", - ntv->tv); - ntv->capture_kernel_drops = StatsRegisterCounter("capture.kernel_drops", - ntv->tv); + ntv->capture_kernel_packets = StatsRegisterCounter("capture.kernel_packets", ntv->tv); + ntv->capture_kernel_drops = StatsRegisterCounter("capture.kernel_drops", ntv->tv); if (aconf->in.bpf_filter) { SCLogConfig("%s: using BPF '%s'", ntv->ifsrc->ifname, aconf->in.bpf_filter); char errbuf[PCAP_ERRBUF_SIZE]; - if (SCBPFCompile(default_packet_size, /* snaplen_arg */ - LINKTYPE_ETHERNET, /* linktype_arg */ - &ntv->bpf_prog, /* program */ - aconf->in.bpf_filter, /* const char *buf */ - 1, /* optimize */ - PCAP_NETMASK_UNKNOWN, /* mask */ - errbuf, - sizeof(errbuf)) == -1) - { + if (SCBPFCompile(default_packet_size, /* snaplen_arg */ + LINKTYPE_ETHERNET, /* linktype_arg */ + &ntv->bpf_prog, /* program */ + aconf->in.bpf_filter, /* const char *buf */ + 1, /* optimize */ + PCAP_NETMASK_UNKNOWN, /* mask */ + errbuf, sizeof(errbuf)) == -1) { SCLogError("%s: failed to compile BPF \"%s\": %s", ntv->ifsrc->ifname, aconf->in.bpf_filter, errbuf); goto error_dst; @@ -666,7 +659,7 @@ static void NetmapReleasePacket(Packet *p) static void NetmapProcessPacket(NetmapThreadVars *ntv, const struct nm_pkthdr *ph) { if (ntv->bpf_prog.bf_len) { - struct pcap_pkthdr pkthdr = { {0, 0}, ph->len, ph->len }; + struct pcap_pkthdr pkthdr = { { 0, 0 }, ph->len, ph->len }; if (pcap_offline_filter(&ntv->bpf_prog, &pkthdr, ph->buf) == 0) { return; } @@ -699,8 +692,7 @@ static void NetmapProcessPacket(NetmapThreadVars *ntv, const struct nm_pkthdr *p p->ReleasePacket = NetmapReleasePacket; p->netmap_v.ntv = ntv; - SCLogDebug("pktlen: %" PRIu32 " (pkt %p, pkt data %p)", - GET_PKT_LEN(p), p, GET_PKT_DATA(p)); + SCLogDebug("pktlen: %" PRIu32 " (pkt %p, pkt data %p)", GET_PKT_LEN(p), p, GET_PKT_DATA(p)); (void)TmThreadsSlotProcessPkt(ntv->tv, ntv->slot, p); } @@ -803,7 +795,7 @@ static TmEcode ReceiveNetmapLoop(ThreadVars *tv, void *data, void *slot) // packets) TmThreadsSetFlag(tv, THV_RUNNING); - for(;;) { + for (;;) { if (unlikely(suricata_ctl_flags != 0)) { break; } @@ -990,5 +982,5 @@ void TmModuleDecodeNetmapRegister(void) #endif /* HAVE_NETMAP */ /** -* @} -*/ + * @} + */ diff --git a/src/source-netmap.h b/src/source-netmap.h index b60d544d5c28..3be1d31e23c4 100644 --- a/src/source-netmap.h +++ b/src/source-netmap.h @@ -16,11 +16,11 @@ */ /** -* \file -* -* \author Aleksey Katargin -* \author Victor Julien -*/ + * \file + * + * \author Aleksey Katargin + * \author Victor Julien + */ #ifndef __SOURCE_NETMAP_H__ #define __SOURCE_NETMAP_H__ @@ -32,18 +32,17 @@ enum { NETMAP_COPY_MODE_IPS, }; -#define NETMAP_IFACE_NAME_LENGTH 48 +#define NETMAP_IFACE_NAME_LENGTH 48 -typedef struct NetmapIfaceSettings_ -{ +typedef struct NetmapIfaceSettings_ { /* real inner interface name */ char iface[NETMAP_IFACE_NAME_LENGTH]; /* sw ring flag for out_iface */ bool sw_ring; bool promisc; - bool real; /**< real iface or not. Not in case of vale, pipe */ - bool ips; /**< set to true if checksum_mode != NETMAP_COPY_MODE_NONE */ + bool real; /**< real iface or not. Not in case of vale, pipe */ + bool ips; /**< set to true if checksum_mode != NETMAP_COPY_MODE_NONE */ bool threads_auto; uint16_t threads; @@ -52,8 +51,7 @@ typedef struct NetmapIfaceSettings_ const char *bpf_filter; } NetmapIfaceSettings; -typedef struct NetmapIfaceConfig_ -{ +typedef struct NetmapIfaceConfig_ { /* semantic interface name */ char iface_name[NETMAP_IFACE_NAME_LENGTH]; @@ -67,15 +65,14 @@ typedef struct NetmapIfaceConfig_ void (*DerefFunc)(void *); } NetmapIfaceConfig; -typedef struct NetmapPacketVars_ -{ +typedef struct NetmapPacketVars_ { /* NetmapThreadVars */ void *ntv; } NetmapPacketVars; int NetmapGetRSSCount(const char *ifname); -void TmModuleReceiveNetmapRegister (void); -void TmModuleDecodeNetmapRegister (void); +void TmModuleReceiveNetmapRegister(void); +void TmModuleDecodeNetmapRegister(void); #endif /* __SOURCE_NETMAP_H__ */ diff --git a/src/source-nflog.c b/src/source-nflog.c index f7d3616c621d..e595ccbc3ac8 100644 --- a/src/source-nflog.c +++ b/src/source-nflog.c @@ -46,13 +46,13 @@ TmEcode NoNFLOGSupportExit(ThreadVars *, const void *, void **); -void TmModuleReceiveNFLOGRegister (void) +void TmModuleReceiveNFLOGRegister(void) { tmm_modules[TMM_RECEIVENFLOG].name = "ReceiveNFLOG"; tmm_modules[TMM_RECEIVENFLOG].ThreadInit = NoNFLOGSupportExit; } -void TmModuleDecodeNFLOGRegister (void) +void TmModuleDecodeNFLOGRegister(void) { tmm_modules[TMM_DECODENFLOG].name = "DecodeNFLOG"; tmm_modules[TMM_DECODENFLOG].ThreadInit = NoNFLOGSupportExit; @@ -113,7 +113,7 @@ typedef struct NFLOGThreadVars_ { /** * \brief Registration function for ReceiveNFLOG */ -void TmModuleReceiveNFLOGRegister (void) +void TmModuleReceiveNFLOGRegister(void) { tmm_modules[TMM_RECEIVENFLOG].name = "ReceiveNFLOG"; tmm_modules[TMM_RECEIVENFLOG].ThreadInit = ReceiveNFLOGThreadInit; @@ -128,7 +128,7 @@ void TmModuleReceiveNFLOGRegister (void) /** * \brief Registration function for DecodeNFLOG */ -void TmModuleDecodeNFLOGRegister (void) +void TmModuleDecodeNFLOGRegister(void) { tmm_modules[TMM_DECODENFLOG].name = "DecodeNFLOG"; tmm_modules[TMM_DECODENFLOG].ThreadInit = DecodeNFLOGThreadInit; @@ -142,10 +142,10 @@ void TmModuleDecodeNFLOGRegister (void) * \brief NFLOG callback function * This function setup a packet from a nflog message */ -static int NFLOGCallback(struct nflog_g_handle *gh, struct nfgenmsg *msg, - struct nflog_data *nfa, void *data) +static int NFLOGCallback( + struct nflog_g_handle *gh, struct nfgenmsg *msg, struct nflog_data *nfa, void *data) { - NFLOGThreadVars *ntv = (NFLOGThreadVars *) data; + NFLOGThreadVars *ntv = (NFLOGThreadVars *)data; struct nfulnl_msg_packet_hdr *ph; char *payload; int ret; @@ -192,7 +192,7 @@ static int NFLOGCallback(struct nflog_g_handle *gh, struct nfgenmsg *msg, ntv->pkts++; ntv->bytes += GET_PKT_LEN(p); #endif - (void) SC_ATOMIC_ADD(ntv->livedev->pkts, 1); + (void)SC_ATOMIC_ADD(ntv->livedev->pkts, 1); if (TmThreadsSlotProcessPkt(ntv->tv, ntv->slot, p) != TM_ECODE_OK) { return -1; @@ -274,18 +274,14 @@ TmEcode ReceiveNFLOGThreadInit(ThreadVars *tv, const void *initdata, void **data } if (nflog_set_qthresh(ntv->gh, ntv->qthreshold) >= 0) - SCLogDebug("NFLOG netlink queue threshold has been set to %d", - ntv->qthreshold); + SCLogDebug("NFLOG netlink queue threshold has been set to %d", ntv->qthreshold); else - SCLogDebug("NFLOG netlink queue threshold can't be set to %d", - ntv->qthreshold); + SCLogDebug("NFLOG netlink queue threshold can't be set to %d", ntv->qthreshold); if (nflog_set_timeout(ntv->gh, ntv->qtimeout) >= 0) - SCLogDebug("NFLOG netlink queue timeout has been set to %d", - ntv->qtimeout); + SCLogDebug("NFLOG netlink queue timeout has been set to %d", ntv->qtimeout); else - SCLogDebug("NFLOG netlink queue timeout can't be set to %d", - ntv->qtimeout); + SCLogDebug("NFLOG netlink queue timeout can't be set to %d", ntv->qtimeout); ntv->livedev = LiveGetDevice(nflconfig->numgroup); if (ntv->livedev == NULL) { @@ -308,10 +304,8 @@ TmEcode ReceiveNFLOGThreadInit(ThreadVars *tv, const void *initdata, void **data } #ifdef PACKET_STATISTICS - ntv->capture_kernel_packets = StatsRegisterCounter("capture.kernel_packets", - ntv->tv); - ntv->capture_kernel_drops = StatsRegisterCounter("capture.kernel_drops", - ntv->tv); + ntv->capture_kernel_packets = StatsRegisterCounter("capture.kernel_packets", ntv->tv); + ntv->capture_kernel_drops = StatsRegisterCounter("capture.kernel_drops", ntv->tv); #endif char *active_runmode = RunmodeGetActive(); @@ -403,7 +397,6 @@ static int NFLOGSetnlbufsiz(void *data, unsigned int size) "`buffer-size` and `max-size` in nflog configuration", ntv->nlbufsiz); return 0; - } /** @@ -425,7 +418,7 @@ TmEcode ReceiveNFLOGLoop(ThreadVars *tv, void *data, void *slot) int rv, fd; int ret = -1; - ntv->slot = ((TmSlot *) slot)->slot_next; + ntv->slot = ((TmSlot *)slot)->slot_next; fd = nflog_fd(ntv->h); if (fd < 0) { @@ -486,11 +479,9 @@ void ReceiveNFLOGThreadExitStats(ThreadVars *tv, void *data) SCEnter(); NFLOGThreadVars *ntv = (NFLOGThreadVars *)data; - SCLogNotice("(%s) Pkts %" PRIu32 ", Bytes %" PRIu64 "", - tv->name, ntv->pkts, ntv->bytes); + SCLogNotice("(%s) Pkts %" PRIu32 ", Bytes %" PRIu64 "", tv->name, ntv->pkts, ntv->bytes); } - /** * \brief Decode IPv4/v6 packets. * @@ -515,7 +506,7 @@ TmEcode DecodeNFLOG(ThreadVars *tv, Packet *p, void *data) } SCLogDebug("IPv4 packet"); DecodeIPV4(tv, dtv, p, GET_PKT_DATA(p), GET_PKT_LEN(p)); - } else if(IPV6_GET_RAW_VER(ip6h) == 6) { + } else if (IPV6_GET_RAW_VER(ip6h) == 6) { if (unlikely(GET_PKT_LEN(p) > USHRT_MAX)) { return TM_ECODE_FAILED; } diff --git a/src/source-nflog.h b/src/source-nflog.h index 98dd9edf20eb..86bc87dc7513 100644 --- a/src/source-nflog.h +++ b/src/source-nflog.h @@ -30,8 +30,7 @@ #endif /* HAVE_NFLOG */ #define NFLOG_GROUP_NAME_LENGTH 48 -typedef struct NflogGroupConfig_ -{ +typedef struct NflogGroupConfig_ { /* nflog's group */ uint16_t group; /* netlink buffer size */ @@ -51,8 +50,7 @@ typedef struct NflogGroupConfig_ void (*DerefFunc)(void *); } NflogGroupConfig; -typedef struct NFLOGPacketVars_ -{ +typedef struct NFLOGPacketVars_ { uint32_t mark; uint32_t ifi; uint32_t ifo; diff --git a/src/source-nfq-prototypes.h b/src/source-nfq-prototypes.h index eef25884b79d..ee7ce43ef9de 100644 --- a/src/source-nfq-prototypes.h +++ b/src/source-nfq-prototypes.h @@ -24,9 +24,8 @@ #ifndef __SOURCE_NFQ_PROTOTYPES_H__ #define __SOURCE_NFQ_PROTOTYPES_H__ -void TmModuleReceiveNFQRegister (void); -void TmModuleVerdictNFQRegister (void); -void TmModuleDecodeNFQRegister (void); +void TmModuleReceiveNFQRegister(void); +void TmModuleVerdictNFQRegister(void); +void TmModuleDecodeNFQRegister(void); #endif /* __SOURCE_NFQ_PROTOTYPES_H__ */ - diff --git a/src/source-nfq.c b/src/source-nfq.c index 5293f2529a4c..3da083bade26 100644 --- a/src/source-nfq.c +++ b/src/source-nfq.c @@ -58,7 +58,7 @@ #ifndef NFQ static TmEcode NoNFQSupportExit(ThreadVars *, const void *, void **); -void TmModuleReceiveNFQRegister (void) +void TmModuleReceiveNFQRegister(void) { tmm_modules[TMM_RECEIVENFQ].name = "ReceiveNFQ"; tmm_modules[TMM_RECEIVENFQ].ThreadInit = NoNFQSupportExit; @@ -68,7 +68,7 @@ void TmModuleReceiveNFQRegister (void) tmm_modules[TMM_RECEIVENFQ].flags = TM_FLAG_RECEIVE_TM; } -void TmModuleVerdictNFQRegister (void) +void TmModuleVerdictNFQRegister(void) { tmm_modules[TMM_VERDICTNFQ].name = "VerdictNFQ"; tmm_modules[TMM_VERDICTNFQ].ThreadInit = NoNFQSupportExit; @@ -77,7 +77,7 @@ void TmModuleVerdictNFQRegister (void) tmm_modules[TMM_VERDICTNFQ].cap_flags = SC_CAP_NET_ADMIN; } -void TmModuleDecodeNFQRegister (void) +void TmModuleDecodeNFQRegister(void) { tmm_modules[TMM_DECODENFQ].name = "DecodeNFQ"; tmm_modules[TMM_DECODENFQ].ThreadInit = NoNFQSupportExit; @@ -99,7 +99,7 @@ static TmEcode NoNFQSupportExit(ThreadVars *tv, const void *initdata, void **dat extern uint16_t max_pending_packets; -#define MAX_ALREADY_TREATED 5 +#define MAX_ALREADY_TREATED 5 #define NFQ_VERDICT_RETRY_COUNT 3 static int already_seen_warning; static int runmode_workers; @@ -110,15 +110,14 @@ static int runmode_workers; #define SOL_NETLINK 270 #endif -typedef struct NFQThreadVars_ -{ +typedef struct NFQThreadVars_ { uint16_t nfq_index; ThreadVars *tv; TmSlot *slot; LiveDevice *livedev; - char *data; /** Per function and thread data */ + char *data; /** Per function and thread data */ int datalen; /** Length of per function and thread data */ } NFQThreadVars; /* shared vars for all for nfq queues and threads */ @@ -151,7 +150,7 @@ typedef enum NFQMode_ { NFQ_ROUTE_MODE, } NFQMode; -#define NFQ_FLAG_FAIL_OPEN (1 << 0) +#define NFQ_FLAG_FAIL_OPEN (1 << 0) typedef struct NFQCnf_ { NFQMode mode; @@ -166,7 +165,7 @@ typedef struct NFQCnf_ { NFQCnf nfq_config; -void TmModuleReceiveNFQRegister (void) +void TmModuleReceiveNFQRegister(void) { /* XXX create a general NFQ setup function */ memset(&nfq_g, 0, sizeof(nfq_g)); @@ -181,7 +180,7 @@ void TmModuleReceiveNFQRegister (void) tmm_modules[TMM_RECEIVENFQ].flags = TM_FLAG_RECEIVE_TM; } -void TmModuleVerdictNFQRegister (void) +void TmModuleVerdictNFQRegister(void) { tmm_modules[TMM_VERDICTNFQ].name = "VerdictNFQ"; tmm_modules[TMM_VERDICTNFQ].ThreadInit = VerdictNFQThreadInit; @@ -189,7 +188,7 @@ void TmModuleVerdictNFQRegister (void) tmm_modules[TMM_VERDICTNFQ].ThreadDeinit = VerdictNFQThreadDeinit; } -void TmModuleDecodeNFQRegister (void) +void TmModuleDecodeNFQRegister(void) { tmm_modules[TMM_DECODENFQ].name = "DecodeNFQ"; tmm_modules[TMM_DECODENFQ].ThreadInit = DecodeNFQThreadInit; @@ -211,7 +210,7 @@ void NFQInitConfig(bool quiet) SCLogDebug("Initializing NFQ"); - memset(&nfq_config, 0, sizeof(nfq_config)); + memset(&nfq_config, 0, sizeof(nfq_config)); if ((ConfGet("nfq.mode", &nfq_mode)) == 0) { nfq_config.mode = NFQ_ACCEPT_MODE; @@ -220,7 +219,7 @@ void NFQInitConfig(bool quiet) nfq_config.mode = NFQ_ACCEPT_MODE; } else if (!strcmp("repeat", nfq_mode)) { nfq_config.mode = NFQ_REPEAT_MODE; - } else if (!strcmp("route", nfq_mode)) { + } else if (!strcmp("route", nfq_mode)) { nfq_config.mode = NFQ_ROUTE_MODE; } else { FatalError("Unknown nfq.mode"); @@ -264,7 +263,7 @@ void NFQInitConfig(bool quiet) value = 255; } if (value > 1) - nfq_config.batchcount = (uint8_t) (value - 1); + nfq_config.batchcount = (uint8_t)(value - 1); #else SCLogWarning("nfq.%s set but NFQ library has no support for it.", "batchcount"); #endif @@ -276,16 +275,15 @@ void NFQInitConfig(bool quiet) SCLogInfo("NFQ running in standard ACCEPT/DROP mode"); break; case NFQ_REPEAT_MODE: - SCLogInfo("NFQ running in REPEAT mode with mark %"PRIu32"/%"PRIu32, + SCLogInfo("NFQ running in REPEAT mode with mark %" PRIu32 "/%" PRIu32, nfq_config.mark, nfq_config.mask); break; case NFQ_ROUTE_MODE: - SCLogInfo("NFQ running in route mode with next queue %"PRIu32, + SCLogInfo("NFQ running in route mode with next queue %" PRIu32, nfq_config.next_queue >> 16); - break; + break; } } - } static uint8_t NFQVerdictCacheLen(NFQQueueVars *t) @@ -305,14 +303,11 @@ static void NFQVerdictCacheFlush(NFQQueueVars *t) do { if (t->verdict_cache.mark_valid) - ret = nfq_set_verdict_batch2(t->qh, - t->verdict_cache.packet_id, - t->verdict_cache.verdict, - t->verdict_cache.mark); + ret = nfq_set_verdict_batch2(t->qh, t->verdict_cache.packet_id, + t->verdict_cache.verdict, t->verdict_cache.mark); else - ret = nfq_set_verdict_batch(t->qh, - t->verdict_cache.packet_id, - t->verdict_cache.verdict); + ret = nfq_set_verdict_batch( + t->qh, t->verdict_cache.packet_id, t->verdict_cache.verdict); } while ((ret < 0) && (iter++ < NFQ_VERDICT_RETRY_COUNT)); if (ret < 0) { @@ -359,7 +354,7 @@ static int NFQVerdictCacheAdd(NFQQueueVars *t, Packet *p, uint32_t verdict) else t->verdict_cache.len++; return 0; - flush: +flush: /* can't cache. Flush current cache and signal caller it should send single verdict */ if (NFQVerdictCacheLen(t) > 0) NFQVerdictCacheFlush(t); @@ -382,15 +377,17 @@ static inline void NFQMutexInit(NFQQueueVars *nq) } } -#define NFQMutexLock(nq) do { \ - if ((nq)->use_mutex) \ - SCMutexLock(&(nq)->mutex_qh); \ -} while (0) +#define NFQMutexLock(nq) \ + do { \ + if ((nq)->use_mutex) \ + SCMutexLock(&(nq)->mutex_qh); \ + } while (0) -#define NFQMutexUnlock(nq) do { \ - if ((nq)->use_mutex) \ - SCMutexUnlock(&(nq)->mutex_qh); \ -} while (0) +#define NFQMutexUnlock(nq) \ + do { \ + if ((nq)->use_mutex) \ + SCMutexUnlock(&(nq)->mutex_qh); \ + } while (0) /** * \brief Read data from nfq message and setup Packet @@ -399,7 +396,7 @@ static inline void NFQMutexInit(NFQQueueVars *nq) * In case of error, this function verdict the packet * to avoid skb to get stuck in kernel. */ -static int NFQSetupPkt (Packet *p, struct nfq_q_handle *qh, void *data) +static int NFQSetupPkt(Packet *p, struct nfq_q_handle *qh, void *data) { struct nfq_data *tb = (struct nfq_data *)data; int ret; @@ -418,8 +415,7 @@ static int NFQSetupPkt (Packet *p, struct nfq_q_handle *qh, void *data) /* coverity[missing_lock] */ p->nfq_v.mark = nfq_get_nfmark(tb); if (nfq_config.mode == NFQ_REPEAT_MODE) { - if ((nfq_config.mark & nfq_config.mask) == - (p->nfq_v.mark & nfq_config.mask)) { + if ((nfq_config.mark & nfq_config.mask) == (p->nfq_v.mark & nfq_config.mask)) { int iter = 0; if (already_seen_warning < MAX_ALREADY_TREATED) SCLogInfo("Packet seems already treated by suricata"); @@ -431,20 +427,20 @@ static int NFQSetupPkt (Packet *p, struct nfq_q_handle *qh, void *data) SCLogWarning( "nfq_set_verdict of %p failed %" PRId32 ": %s", p, ret, strerror(errno)); } - return -1 ; + return -1; } } // Switch to full featured release function p->ReleasePacket = NFQReleasePacket; - p->nfq_v.ifi = nfq_get_indev(tb); - p->nfq_v.ifo = nfq_get_outdev(tb); + p->nfq_v.ifi = nfq_get_indev(tb); + p->nfq_v.ifo = nfq_get_outdev(tb); p->nfq_v.verdicted = 0; #ifdef NFQ_GET_PAYLOAD_SIGNED ret = nfq_get_payload(tb, &pktdata); #else - ret = nfq_get_payload(tb, (unsigned char **) &pktdata); + ret = nfq_get_payload(tb, (unsigned char **)&pktdata); #endif /* NFQ_GET_PAYLOAD_SIGNED */ if (ret > 0) { /* nfq_get_payload returns a pointer to a part of memory @@ -461,7 +457,7 @@ static int NFQSetupPkt (Packet *p, struct nfq_q_handle *qh, void *data) } else { PacketCopyData(p, (uint8_t *)pktdata, ret); } - } else if (ret == -1) { + } else if (ret == -1) { /* unable to get pointer to data, ensure packet length is zero. * This will trigger an error in packet decoding */ SET_PKT_LEN(p, 0); @@ -502,8 +498,8 @@ static int NFQBypassCallback(Packet *p) if (p->flags & PKT_REBUILT_FRAGMENT) { Packet *tp = p->root ? p->root : p; SCSpinLock(&tp->persistent.tunnel_lock); - tp->nfq_v.mark = (nfq_config.bypass_mark & nfq_config.bypass_mask) - | (tp->nfq_v.mark & ~nfq_config.bypass_mask); + tp->nfq_v.mark = (nfq_config.bypass_mark & nfq_config.bypass_mask) | + (tp->nfq_v.mark & ~nfq_config.bypass_mask); tp->flags |= PKT_MARK_MODIFIED; SCSpinUnlock(&tp->persistent.tunnel_lock); return 1; @@ -511,16 +507,16 @@ static int NFQBypassCallback(Packet *p) return 0; } else { /* coverity[missing_lock] */ - p->nfq_v.mark = (nfq_config.bypass_mark & nfq_config.bypass_mask) - | (p->nfq_v.mark & ~nfq_config.bypass_mask); + p->nfq_v.mark = (nfq_config.bypass_mark & nfq_config.bypass_mask) | + (p->nfq_v.mark & ~nfq_config.bypass_mask); p->flags |= PKT_MARK_MODIFIED; } return 1; } -static int NFQCallBack(struct nfq_q_handle *qh, struct nfgenmsg *nfmsg, - struct nfq_data *nfa, void *data) +static int NFQCallBack( + struct nfq_q_handle *qh, struct nfgenmsg *nfmsg, struct nfq_data *nfa, void *data) { NFQThreadVars *ntv = (NFQThreadVars *)data; ThreadVars *tv = ntv->tv; @@ -547,7 +543,7 @@ static int NFQCallBack(struct nfq_q_handle *qh, struct nfgenmsg *nfmsg, q->pkts++; q->bytes += GET_PKT_LEN(p); #endif /* COUNTERS */ - (void) SC_ATOMIC_ADD(ntv->livedev->pkts, 1); + (void)SC_ATOMIC_ADD(ntv->livedev->pkts, 1); /* NFQSetupPkt is issuing a verdict so we only recycle Packet and leave */ @@ -560,7 +556,7 @@ static int NFQCallBack(struct nfq_q_handle *qh, struct nfgenmsg *nfmsg, q->pkts++; q->bytes += GET_PKT_LEN(p); #endif /* COUNTERS */ - (void) SC_ATOMIC_ADD(ntv->livedev->pkts, 1); + (void)SC_ATOMIC_ADD(ntv->livedev->pkts, 1); if (TmThreadsSlotProcessPkt(tv, ntv->slot, p) != TM_ECODE_OK) { return -1; @@ -585,8 +581,7 @@ static TmEcode NFQInitThread(NFQThreadVars *t, uint32_t queue_maxlen) return TM_ECODE_FAILED; } - if (nfq_g.unbind == 0) - { + if (nfq_g.unbind == 0) { /* VJ: on my Ubuntu Hardy system this fails the first time it's * run. Ignoring the error seems to have no bad effects. */ SCLogDebug("unbinding existing nf_queue handler for AF_INET (if any)"); @@ -621,7 +616,7 @@ static TmEcode NFQInitThread(NFQThreadVars *t, uint32_t queue_maxlen) SCLogDebug("setting copy_packet mode"); /* 05DC = 1500 */ - //if (nfq_set_mode(nfq_t->qh, NFQNL_COPY_PACKET, 0x05DC) < 0) { + // if (nfq_set_mode(nfq_t->qh, NFQNL_COPY_PACKET, 0x05DC) < 0) { if (nfq_set_mode(q->qh, NFQNL_COPY_PACKET, 0xFFFF) < 0) { SCLogError("can't set packet_copy mode"); return TM_ECODE_FAILED; @@ -648,19 +643,17 @@ static TmEcode NFQInitThread(NFQThreadVars *t, uint32_t queue_maxlen) NFQMutexInit(q); /* Set some netlink specific option on the socket to increase - performance */ + performance */ opt = 1; #ifdef NETLINK_BROADCAST_SEND_ERROR - if (setsockopt(q->fd, SOL_NETLINK, - NETLINK_BROADCAST_SEND_ERROR, &opt, sizeof(int)) == -1) { + if (setsockopt(q->fd, SOL_NETLINK, NETLINK_BROADCAST_SEND_ERROR, &opt, sizeof(int)) == -1) { SCLogWarning("can't set netlink broadcast error: %s", strerror(errno)); } #endif /* Don't send error about no buffer space available but drop the - packets instead */ + packets instead */ #ifdef NETLINK_NO_ENOBUFS - if (setsockopt(q->fd, SOL_NETLINK, - NETLINK_NO_ENOBUFS, &opt, sizeof(int)) == -1) { + if (setsockopt(q->fd, SOL_NETLINK, NETLINK_NO_ENOBUFS, &opt, sizeof(int)) == -1) { SCLogWarning("can't set netlink enobufs: %s", strerror(errno)); } #endif @@ -692,12 +685,12 @@ static TmEcode NFQInitThread(NFQThreadVars *t, uint32_t queue_maxlen) tv.tv_sec = 1; tv.tv_usec = 0; - if(setsockopt(q->fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) == -1) { + if (setsockopt(q->fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) == -1) { SCLogWarning("can't set socket timeout: %s", strerror(errno)); } - SCLogDebug("nfq_q->h %p, nfq_q->nh %p, nfq_q->qh %p, nfq_q->fd %" PRId32 "", - q->h, q->nh, q->qh, q->fd); + SCLogDebug("nfq_q->h %p, nfq_q->nh %p, nfq_q->qh %p, nfq_q->fd %" PRId32 "", q->h, q->nh, q->qh, + q->fd); return TM_ECODE_OK; } @@ -710,7 +703,7 @@ TmEcode ReceiveNFQThreadInit(ThreadVars *tv, const void *initdata, void **data) sigfillset(&sigs); pthread_sigmask(SIG_BLOCK, &sigs, NULL); - NFQThreadVars *ntv = (NFQThreadVars *) initdata; + NFQThreadVars *ntv = (NFQThreadVars *)initdata; /* store the ThreadVars pointer in our NFQ thread context * as we will need it in our callback function */ ntv->tv = tv; @@ -858,7 +851,7 @@ int NFQParseAndRegisterQueues(const char *queues) { uint16_t queue_start = 0; uint16_t queue_end = 0; - uint16_t num_queues = 1; // if argument is correct, at least one queue will be created + uint16_t num_queues = 1; // if argument is correct, at least one queue will be created // Either "id" or "start:end" format (e.g., "12" or "0:5") int count = sscanf(queues, "%hu:%hu", &queue_start, &queue_end); @@ -971,7 +964,7 @@ static void NFQRecvPkt(NFQQueueVars *t, NFQThreadVars *tv) NFQMutexUnlock(t); #endif /* COUNTERS */ } - } else if(rv == 0) { + } else if (rv == 0) { SCLogWarning("recv got returncode 0"); } else { #ifdef DBG_PERF @@ -988,7 +981,7 @@ static void NFQRecvPkt(NFQQueueVars *t, NFQThreadVars *tv) } NFQMutexUnlock(t); if (ret != 0) { - SCLogDebug("nfq_handle_packet error %"PRId32, ret); + SCLogDebug("nfq_handle_packet error %" PRId32, ret); } } } @@ -1002,13 +995,13 @@ TmEcode ReceiveNFQLoop(ThreadVars *tv, void *data, void *slot) NFQThreadVars *ntv = (NFQThreadVars *)data; NFQQueueVars *nq = NFQGetQueue(ntv->nfq_index); - ntv->slot = ((TmSlot *) slot)->slot_next; + ntv->slot = ((TmSlot *)slot)->slot_next; // Indicate that the thread is actually running its application level code (i.e., it can poll // packets) TmThreadsSetFlag(tv, THV_RUNNING); - while(1) { + while (1) { if (unlikely(suricata_ctl_flags != 0)) { NFQDestroyQueue(nq); break; @@ -1028,9 +1021,9 @@ void ReceiveNFQThreadExitStats(ThreadVars *tv, void *data) NFQThreadVars *ntv = (NFQThreadVars *)data; NFQQueueVars *nq = NFQGetQueue(ntv->nfq_index); #ifdef COUNTERS - SCLogNotice("(%s) Treated: Pkts %" PRIu32 ", Bytes %" PRIu64 ", Errors %" PRIu32 "", - tv->name, nq->pkts, nq->bytes, nq->errs); - SCLogNotice("(%s) Verdict: Accepted %"PRIu32", Dropped %"PRIu32", Replaced %"PRIu32, + SCLogNotice("(%s) Treated: Pkts %" PRIu32 ", Bytes %" PRIu64 ", Errors %" PRIu32 "", tv->name, + nq->pkts, nq->bytes, nq->errs); + SCLogNotice("(%s) Verdict: Accepted %" PRIu32 ", Dropped %" PRIu32 ", Replaced %" PRIu32, tv->name, nq->accepted, nq->dropped, nq->replaced); #endif } @@ -1051,7 +1044,7 @@ static inline uint32_t GetVerdict(const Packet *p) verdict = NF_REPEAT; break; case NFQ_ROUTE_MODE: - verdict = ((uint32_t) NF_QUEUE) | nfq_config.next_queue; + verdict = ((uint32_t)NF_QUEUE) | nfq_config.next_queue; break; } } @@ -1089,7 +1082,7 @@ TmEcode NFQSetVerdict(Packet *p) return TM_ECODE_OK; } - //printf("%p verdicting on queue %" PRIu32 "\n", t, t->queue_num); + // printf("%p verdicting on queue %" PRIu32 "\n", t, t->queue_num); NFQMutexLock(t); if (t->qh == NULL) { @@ -1117,54 +1110,52 @@ TmEcode NFQSetVerdict(Packet *p) if (p->flags & PKT_MARK_MODIFIED) { #ifdef HAVE_NFQ_SET_VERDICT2 if (p->flags & PKT_STREAM_MODIFIED) { - ret = nfq_set_verdict2(t->qh, p->nfq_v.id, verdict, - p->nfq_v.mark, + ret = nfq_set_verdict2(t->qh, p->nfq_v.id, verdict, p->nfq_v.mark, GET_PKT_LEN(p), GET_PKT_DATA(p)); } else { - ret = nfq_set_verdict2(t->qh, p->nfq_v.id, verdict, - p->nfq_v.mark, - 0, NULL); + ret = nfq_set_verdict2(t->qh, p->nfq_v.id, verdict, p->nfq_v.mark, 0, NULL); } -#else /* fall back to old function */ +#else /* fall back to old function */ if (p->flags & PKT_STREAM_MODIFIED) { ret = nfq_set_verdict_mark(t->qh, p->nfq_v.id, verdict, - htonl(p->nfq_v.mark), - GET_PKT_LEN(p), GET_PKT_DATA(p)); + htonl(p->nfq_v.mark), GET_PKT_LEN(p), GET_PKT_DATA(p)); } else { - ret = nfq_set_verdict_mark(t->qh, p->nfq_v.id, verdict, - htonl(p->nfq_v.mark), - 0, NULL); + ret = nfq_set_verdict_mark( + t->qh, p->nfq_v.id, verdict, htonl(p->nfq_v.mark), 0, NULL); } #endif /* HAVE_NFQ_SET_VERDICT2 */ } else { if (p->flags & PKT_STREAM_MODIFIED) { - ret = nfq_set_verdict(t->qh, p->nfq_v.id, verdict, - GET_PKT_LEN(p), GET_PKT_DATA(p)); + ret = nfq_set_verdict( + t->qh, p->nfq_v.id, verdict, GET_PKT_LEN(p), GET_PKT_DATA(p)); } else { ret = nfq_set_verdict(t->qh, p->nfq_v.id, verdict, 0, NULL); } - } break; case NFQ_REPEAT_MODE: #ifdef HAVE_NFQ_SET_VERDICT2 if (p->flags & PKT_STREAM_MODIFIED) { ret = nfq_set_verdict2(t->qh, p->nfq_v.id, verdict, - (nfq_config.mark & nfq_config.mask) | (p->nfq_v.mark & ~nfq_config.mask), + (nfq_config.mark & nfq_config.mask) | + (p->nfq_v.mark & ~nfq_config.mask), GET_PKT_LEN(p), GET_PKT_DATA(p)); } else { ret = nfq_set_verdict2(t->qh, p->nfq_v.id, verdict, - (nfq_config.mark & nfq_config.mask) | (p->nfq_v.mark & ~nfq_config.mask), + (nfq_config.mark & nfq_config.mask) | + (p->nfq_v.mark & ~nfq_config.mask), 0, NULL); } -#else /* fall back to old function */ +#else /* fall back to old function */ if (p->flags & PKT_STREAM_MODIFIED) { ret = nfq_set_verdict_mark(t->qh, p->nfq_v.id, verdict, - htonl((nfq_config.mark & nfq_config.mask) | (p->nfq_v.mark & ~nfq_config.mask)), + htonl((nfq_config.mark & nfq_config.mask) | + (p->nfq_v.mark & ~nfq_config.mask)), GET_PKT_LEN(p), GET_PKT_DATA(p)); } else { ret = nfq_set_verdict_mark(t->qh, p->nfq_v.id, verdict, - htonl((nfq_config.mark & nfq_config.mask) | (p->nfq_v.mark & ~nfq_config.mask)), + htonl((nfq_config.mark & nfq_config.mask) | + (p->nfq_v.mark & ~nfq_config.mask)), 0, NULL); } #endif /* HAVE_NFQ_SET_VERDICT2 */ diff --git a/src/source-nfq.h b/src/source-nfq.h index b60e6d9cc537..d675ff0e3605 100644 --- a/src/source-nfq.h +++ b/src/source-nfq.h @@ -27,7 +27,7 @@ #ifdef NFQ #include "threads.h" -#include /* for NF_ACCEPT */ +#include /* for NF_ACCEPT */ #include // Netfilter's limit @@ -36,9 +36,8 @@ /* idea: set the recv-thread id in the packet to * select an verdict-queue */ -typedef struct NFQPacketVars_ -{ - int id; /* this nfq packets id */ +typedef struct NFQPacketVars_ { + int id; /* this nfq packets id */ uint16_t nfq_index; /* index in NFQ array */ uint8_t verdicted; @@ -48,8 +47,7 @@ typedef struct NFQPacketVars_ uint16_t hw_protocol; } NFQPacketVars; -typedef struct NFQQueueVars_ -{ +typedef struct NFQQueueVars_ { struct nfq_handle *h; struct nfnl_handle *nh; int fd; @@ -77,15 +75,14 @@ typedef struct NFQQueueVars_ uint32_t packet_id; /* id of last processed packet */ uint32_t verdict; uint32_t mark; - uint8_t mark_valid:1; + uint8_t mark_valid : 1; uint8_t len; uint8_t maxlen; } verdict_cache; } NFQQueueVars; -typedef struct NFQGlobalVars_ -{ +typedef struct NFQGlobalVars_ { char unbind; } NFQGlobalVars; @@ -97,4 +94,3 @@ void *NFQGetThread(int number); void NFQContextsClean(void); #endif /* NFQ */ #endif /* __SOURCE_NFQ_H__ */ - diff --git a/src/source-pcap-file-directory-helper.c b/src/source-pcap-file-directory-helper.c index 59c2116f99df..3291b3d532d6 100644 --- a/src/source-pcap-file-directory-helper.c +++ b/src/source-pcap-file-directory-helper.c @@ -37,19 +37,17 @@ static int CompareTimes(struct timespec *left, struct timespec *right); static TmEcode PcapRunStatus(PcapFileDirectoryVars *); static TmEcode PcapDirectoryFailure(PcapFileDirectoryVars *ptv); static TmEcode PcapDirectoryDone(PcapFileDirectoryVars *ptv); -static int PcapDirectoryGetModifiedTime(char const * file, struct timespec * out); -static TmEcode PcapDirectoryInsertFile(PcapFileDirectoryVars *pv, - PendingFile *file_to_add); -static TmEcode PcapDirectoryPopulateBuffer(PcapFileDirectoryVars *ptv, - struct timespec * older_than); -static TmEcode PcapDirectoryDispatchForTimeRange(PcapFileDirectoryVars *pv, - struct timespec *older_than); +static int PcapDirectoryGetModifiedTime(char const *file, struct timespec *out); +static TmEcode PcapDirectoryInsertFile(PcapFileDirectoryVars *pv, PendingFile *file_to_add); +static TmEcode PcapDirectoryPopulateBuffer(PcapFileDirectoryVars *ptv, struct timespec *older_than); +static TmEcode PcapDirectoryDispatchForTimeRange( + PcapFileDirectoryVars *pv, struct timespec *older_than); void GetTime(struct timespec *tm) { struct timeval now; - if(gettimeofday(&now, NULL) == 0) { - tm->tv_sec = now.tv_sec; + if (gettimeofday(&now, NULL) == 0) { + tm->tv_sec = now.tv_sec; tm->tv_nsec = now.tv_usec * 1000L; } } @@ -84,7 +82,7 @@ TmEcode PcapRunStatus(PcapFileDirectoryVars *ptv) { if (RunModeUnixSocketIsActive()) { TmEcode done = UnixSocketPcapFile(TM_ECODE_OK, &ptv->shared->last_processed); - if ( (suricata_ctl_flags & SURICATA_STOP) || done != TM_ECODE_OK) { + if ((suricata_ctl_flags & SURICATA_STOP) || done != TM_ECODE_OK) { SCReturnInt(TM_ECODE_DONE); } } else { @@ -95,7 +93,8 @@ TmEcode PcapRunStatus(PcapFileDirectoryVars *ptv) SCReturnInt(TM_ECODE_OK); } -void CleanupPendingFile(PendingFile *pending) { +void CleanupPendingFile(PendingFile *pending) +{ if (pending != NULL) { if (pending->filename != NULL) { SCFree(pending->filename); @@ -176,7 +175,7 @@ TmEcode PcapDetermineDirectoryOrFile(char *filename, DIR **directory) temp_dir = opendir(filename); - if (temp_dir == NULL) {//if null, our filename may just be a normal file + if (temp_dir == NULL) { // if null, our filename may just be a normal file switch (errno) { case EACCES: SCLogError("%s: Permission denied", filename); @@ -201,7 +200,7 @@ TmEcode PcapDetermineDirectoryOrFile(char *filename, DIR **directory) SCLogError("%s: Insufficient memory to complete the operation", filename); break; - case ENOTDIR: //no error checking the directory, just is a plain file + case ENOTDIR: // no error checking the directory, just is a plain file SCLogDebug("%s: plain file, not a directory", filename); return_code = TM_ECODE_OK; break; @@ -210,7 +209,7 @@ TmEcode PcapDetermineDirectoryOrFile(char *filename, DIR **directory) SCLogError("%s: %" PRId32, filename, errno); } } else { - //no error, filename references a directory + // no error, filename references a directory *directory = temp_dir; return_code = TM_ECODE_OK; } @@ -242,9 +241,8 @@ int PcapDirectoryGetModifiedTime(char const *file, struct timespec *out) return ret; } -TmEcode PcapDirectoryInsertFile(PcapFileDirectoryVars *pv, - PendingFile *file_to_add -) { +TmEcode PcapDirectoryInsertFile(PcapFileDirectoryVars *pv, PendingFile *file_to_add) +{ PendingFile *file_to_compare = NULL; PendingFile *next_file_to_compare = NULL; @@ -269,15 +267,14 @@ TmEcode PcapDirectoryInsertFile(PcapFileDirectoryVars *pv, TAILQ_INSERT_TAIL(&pv->directory_content, file_to_add, next); } else { file_to_compare = TAILQ_FIRST(&pv->directory_content); - while(file_to_compare != NULL) { + while (file_to_compare != NULL) { if (CompareTimes(&file_to_add->modified_time, &file_to_compare->modified_time) < 0) { TAILQ_INSERT_BEFORE(file_to_compare, file_to_add, next); file_to_compare = NULL; } else { next_file_to_compare = TAILQ_NEXT(file_to_compare, next); if (next_file_to_compare == NULL) { - TAILQ_INSERT_AFTER(&pv->directory_content, file_to_compare, - file_to_add, next); + TAILQ_INSERT_AFTER(&pv->directory_content, file_to_compare, file_to_add, next); } file_to_compare = next_file_to_compare; } @@ -287,9 +284,8 @@ TmEcode PcapDirectoryInsertFile(PcapFileDirectoryVars *pv, SCReturnInt(TM_ECODE_OK); } -TmEcode PcapDirectoryPopulateBuffer(PcapFileDirectoryVars *pv, - struct timespec *older_than -) { +TmEcode PcapDirectoryPopulateBuffer(PcapFileDirectoryVars *pv, struct timespec *older_than) +{ if (unlikely(pv == NULL)) { SCLogError("No directory vars passed"); SCReturnInt(TM_ECODE_FAILED); @@ -298,7 +294,7 @@ TmEcode PcapDirectoryPopulateBuffer(PcapFileDirectoryVars *pv, SCLogError("No directory filename was passed"); SCReturnInt(TM_ECODE_FAILED); } - struct dirent * dir = NULL; + struct dirent *dir = NULL; PendingFile *file_to_add = NULL; while ((dir = readdir(pv->directory)) != NULL) { @@ -307,12 +303,11 @@ TmEcode PcapDirectoryPopulateBuffer(PcapFileDirectoryVars *pv, continue; } #endif - if (strcmp(dir->d_name, ".") == 0 || - strcmp(dir->d_name, "..") == 0) { + if (strcmp(dir->d_name, ".") == 0 || strcmp(dir->d_name, "..") == 0) { continue; } - char pathbuff[PATH_MAX] = {0}; + char pathbuff[PATH_MAX] = { 0 }; int written = 0; @@ -328,17 +323,15 @@ TmEcode PcapDirectoryPopulateBuffer(PcapFileDirectoryVars *pv, if (PcapDirectoryGetModifiedTime(pathbuff, &temp_time) == 0) { SCLogDebug("%" PRIuMAX " < %" PRIuMAX "(%s) < %" PRIuMAX ")", - (uintmax_t)SCTimespecAsEpochMillis(&pv->shared->last_processed), - (uintmax_t)SCTimespecAsEpochMillis(&temp_time), - pathbuff, - (uintmax_t)SCTimespecAsEpochMillis(older_than)); + (uintmax_t)SCTimespecAsEpochMillis(&pv->shared->last_processed), + (uintmax_t)SCTimespecAsEpochMillis(&temp_time), pathbuff, + (uintmax_t)SCTimespecAsEpochMillis(older_than)); // Skip files outside of our time range if (CompareTimes(&temp_time, &pv->shared->last_processed) <= 0) { SCLogDebug("Skipping old file %s", pathbuff); continue; - } - else if (CompareTimes(&temp_time, older_than) >= 0) { + } else if (CompareTimes(&temp_time, older_than) >= 0) { SCLogDebug("Skipping new file %s", pathbuff); continue; } @@ -366,7 +359,7 @@ TmEcode PcapDirectoryPopulateBuffer(PcapFileDirectoryVars *pv, CopyTime(&temp_time, &file_to_add->modified_time); SCLogInfo("Found \"%s\" at %" PRIuMAX, file_to_add->filename, - (uintmax_t)SCTimespecAsEpochMillis(&file_to_add->modified_time)); + (uintmax_t)SCTimespecAsEpochMillis(&file_to_add->modified_time)); if (PcapDirectoryInsertFile(pv, file_to_add) == TM_ECODE_FAILED) { SCLogError("Failed to add file"); @@ -380,9 +373,7 @@ TmEcode PcapDirectoryPopulateBuffer(PcapFileDirectoryVars *pv, SCReturnInt(TM_ECODE_OK); } - -TmEcode PcapDirectoryDispatchForTimeRange(PcapFileDirectoryVars *pv, - struct timespec *older_than) +TmEcode PcapDirectoryDispatchForTimeRange(PcapFileDirectoryVars *pv, struct timespec *older_than) { if (PcapDirectoryPopulateBuffer(pv, older_than) == TM_ECODE_FAILED) { SCLogError("Failed to populate directory buffer"); @@ -446,10 +437,10 @@ TmEcode PcapDirectoryDispatchForTimeRange(PcapFileDirectoryVars *pv, } SCLogInfo("Processed file %s, processed up to %" PRIuMAX, - current_file->filename, - (uintmax_t)SCTimespecAsEpochMillis(¤t_file->modified_time)); + current_file->filename, + (uintmax_t)SCTimespecAsEpochMillis(¤t_file->modified_time)); - if(CompareTimes(¤t_file->modified_time, &last_time_seen) > 0) { + if (CompareTimes(¤t_file->modified_time, &last_time_seen) > 0) { CopyTime(¤t_file->modified_time, &last_time_seen); } @@ -461,9 +452,9 @@ TmEcode PcapDirectoryDispatchForTimeRange(PcapFileDirectoryVars *pv, } } - if(CompareTimes(&last_time_seen, &pv->shared->last_processed) > 0) { + if (CompareTimes(&last_time_seen, &pv->shared->last_processed) > 0) { SCLogInfo("Updating processed to %" PRIuMAX, - (uintmax_t)SCTimespecAsEpochMillis(&last_time_seen)); + (uintmax_t)SCTimespecAsEpochMillis(&last_time_seen)); CopyTime(&last_time_seen, &pv->shared->last_processed); status = PcapRunStatus(pv); } @@ -492,29 +483,29 @@ TmEcode PcapDirectoryDispatch(PcapFileDirectoryVars *ptv) TmEcode status = TM_ECODE_OK; while (status == TM_ECODE_OK) { - //loop while directory is ok - SCLogInfo("Processing pcaps directory %s, files must be newer than %" PRIuMAX " and older than %" PRIuMAX, - ptv->filename, (uintmax_t)SCTimespecAsEpochMillis(&ptv->shared->last_processed), - (uintmax_t)SCTimespecAsEpochMillis(&older_than)); + // loop while directory is ok + SCLogInfo("Processing pcaps directory %s, files must be newer than %" PRIuMAX + " and older than %" PRIuMAX, + ptv->filename, (uintmax_t)SCTimespecAsEpochMillis(&ptv->shared->last_processed), + (uintmax_t)SCTimespecAsEpochMillis(&older_than)); status = PcapDirectoryDispatchForTimeRange(ptv, &older_than); if (ptv->should_loop && status == TM_ECODE_OK) { sleep(poll_seconds); - //update our status based on suricata control flags or unix command socket + // update our status based on suricata control flags or unix command socket status = PcapRunStatus(ptv); if (status == TM_ECODE_OK) { SCLogDebug("Checking if directory %s still exists", ptv->filename); - //check directory - if (PcapDetermineDirectoryOrFile(ptv->filename, - &directory_check) == TM_ECODE_FAILED) { - SCLogInfo("Directory %s no longer exists, stopping", - ptv->filename); + // check directory + if (PcapDetermineDirectoryOrFile(ptv->filename, &directory_check) == + TM_ECODE_FAILED) { + SCLogInfo("Directory %s no longer exists, stopping", ptv->filename); status = TM_ECODE_DONE; - } else if(directory_check != NULL) { + } else if (directory_check != NULL) { closedir(directory_check); directory_check = NULL; } } - } else if (status == TM_ECODE_OK) { //not looping, mark done + } else if (status == TM_ECODE_OK) { // not looping, mark done SCLogDebug("Not looping, stopping directory mode"); status = TM_ECODE_DONE; } diff --git a/src/source-pcap-file-directory-helper.h b/src/source-pcap-file-directory-helper.h index 6e32c044d83b..a3d0e1b5f2b8 100644 --- a/src/source-pcap-file-directory-helper.h +++ b/src/source-pcap-file-directory-helper.h @@ -28,8 +28,7 @@ #ifndef __SOURCE_PCAP_FILE_DIRECTORY_HELPER_H__ #define __SOURCE_PCAP_FILE_DIRECTORY_HELPER_H__ -typedef struct PendingFile_ -{ +typedef struct PendingFile_ { char *filename; struct timespec modified_time; TAILQ_ENTRY(PendingFile_) next; @@ -37,8 +36,7 @@ typedef struct PendingFile_ /** * Data specific to a directory of pcap files */ -typedef struct PcapFileDirectoryVars_ -{ +typedef struct PcapFileDirectoryVars_ { char *filename; DIR *directory; PcapFileFileVars *current_file; diff --git a/src/source-pcap-file-helper.c b/src/source-pcap-file-helper.c index 936b65fb3d9f..33b9c866e95e 100644 --- a/src/source-pcap-file-helper.c +++ b/src/source-pcap-file-helper.c @@ -96,8 +96,8 @@ void PcapFileCallbackLoop(char *user, struct pcap_pkthdr *h, u_char *pkt) if (pcap_g.checksum_mode == CHECKSUM_VALIDATION_DISABLE) { p->flags |= PKT_IGNORE_CHECKSUM; } else if (pcap_g.checksum_mode == CHECKSUM_VALIDATION_AUTO) { - if (ChecksumAutoModeCheck(ptv->shared->pkts, p->pcap_cnt, - SC_ATOMIC_GET(pcap_g.invalid_checksums))) { + if (ChecksumAutoModeCheck( + ptv->shared->pkts, p->pcap_cnt, SC_ATOMIC_GET(pcap_g.invalid_checksums))) { pcap_g.checksum_mode = CHECKSUM_VALIDATION_DISABLE; p->flags |= PKT_IGNORE_CHECKSUM; } @@ -130,8 +130,7 @@ TmEcode PcapFileDispatch(PcapFileFileVars *ptv) /* initialize all the thread's initial timestamp */ if (likely(ptv->first_pkt_hdr != NULL)) { TmThreadsInitThreadsTimestamp(SCTIME_FROM_TIMEVAL(&ptv->first_pkt_ts)); - PcapFileCallbackLoop((char *)ptv, ptv->first_pkt_hdr, - (u_char *)ptv->first_pkt_data); + PcapFileCallbackLoop((char *)ptv, ptv->first_pkt_hdr, (u_char *)ptv->first_pkt_data); ptv->first_pkt_hdr = NULL; ptv->first_pkt_data = NULL; } @@ -150,8 +149,8 @@ TmEcode PcapFileDispatch(PcapFileFileVars *ptv) PacketPoolWait(); /* Right now we just support reading packets one at a time. */ - int r = pcap_dispatch(ptv->pcap_handle, packet_q_len, - (pcap_handler)PcapFileCallbackLoop, (u_char *)ptv); + int r = pcap_dispatch( + ptv->pcap_handle, packet_q_len, (pcap_handler)PcapFileCallbackLoop, (u_char *)ptv); if (unlikely(r == -1)) { SCLogError("error code %" PRId32 " %s for %s", r, pcap_geterr(ptv->pcap_handle), ptv->filename); @@ -160,8 +159,8 @@ TmEcode PcapFileDispatch(PcapFileFileVars *ptv) } loop_result = TM_ECODE_DONE; } else if (unlikely(r == 0)) { - SCLogInfo("pcap file %s end of file reached (pcap err code %" PRId32 ")", - ptv->filename, r); + SCLogInfo("pcap file %s end of file reached (pcap err code %" PRId32 ")", ptv->filename, + r); ptv->shared->files++; loop_result = TM_ECODE_DONE; } else if (ptv->shared->cb_result == TM_ECODE_FAILED) { @@ -197,7 +196,7 @@ TmEcode InitPcapFile(PcapFileFileVars *pfv) { char errbuf[PCAP_ERRBUF_SIZE] = ""; - if(unlikely(pfv->filename == NULL)) { + if (unlikely(pfv->filename == NULL)) { SCLogError("Filename was null"); SCReturnInt(TM_ECODE_FAILED); } diff --git a/src/source-pcap-file-helper.h b/src/source-pcap-file-helper.h index 7db83b1559bf..10e7dd02da6f 100644 --- a/src/source-pcap-file-helper.h +++ b/src/source-pcap-file-helper.h @@ -37,8 +37,7 @@ typedef struct PcapFileGlobalVars_ { /** * Data that is shared amongst File, Directory, and Thread level vars */ -typedef struct PcapFileSharedVars_ -{ +typedef struct PcapFileSharedVars_ { char *bpf_string; uint32_t tenant_id; @@ -65,8 +64,7 @@ typedef struct PcapFileSharedVars_ /** * Data specific to a single pcap file */ -typedef struct PcapFileFileVars_ -{ +typedef struct PcapFileFileVars_ { char *filename; pcap_t *pcap_handle; diff --git a/src/source-pcap-file.c b/src/source-pcap-file.c index c4f97bc0c4c1..11bdcdd2ed00 100644 --- a/src/source-pcap-file.c +++ b/src/source-pcap-file.c @@ -38,8 +38,7 @@ PcapFileGlobalVars pcap_g; /** * Union determining whether the behavior of the thread is file or directory */ -typedef union PcapFileBehaviorVar_ -{ +typedef union PcapFileBehaviorVar_ { PcapFileDirectoryVars *directory; PcapFileFileVars *file; } PcapFileBehaviorVar; @@ -47,8 +46,7 @@ typedef union PcapFileBehaviorVar_ /** * Data specific to the thread */ -typedef struct PcapFileThreadVars_ -{ +typedef struct PcapFileThreadVars_ { PcapFileBehaviorVar behavior; bool is_directory; @@ -64,8 +62,7 @@ static TmEcode DecodePcapFile(ThreadVars *, Packet *, void *); static TmEcode DecodePcapFileThreadInit(ThreadVars *, const void *, void **); static TmEcode DecodePcapFileThreadDeinit(ThreadVars *tv, void *data); -static void CleanupPcapDirectoryFromThreadVars(PcapFileThreadVars *tv, - PcapFileDirectoryVars *ptv); +static void CleanupPcapDirectoryFromThreadVars(PcapFileThreadVars *tv, PcapFileDirectoryVars *ptv); static void CleanupPcapFileFromThreadVars(PcapFileThreadVars *tv, PcapFileFileVars *pfv); static void CleanupPcapFileThreadVars(PcapFileThreadVars *tv); static TmEcode PcapFileExit(TmEcode status, struct timespec *last_processed); @@ -111,7 +108,7 @@ void CleanupPcapFileThreadVars(PcapFileThreadVars *ptv) /** * Pcap File Functionality */ -void TmModuleReceivePcapFileRegister (void) +void TmModuleReceivePcapFileRegister(void) { tmm_modules[TMM_RECEIVEPCAPFILE].name = "ReceivePcapFile"; tmm_modules[TMM_RECEIVEPCAPFILE].ThreadInit = ReceivePcapFileThreadInit; @@ -124,7 +121,7 @@ void TmModuleReceivePcapFileRegister (void) tmm_modules[TMM_RECEIVEPCAPFILE].flags = TM_FLAG_RECEIVE_TM; } -void TmModuleDecodePcapFileRegister (void) +void TmModuleDecodePcapFileRegister(void) { tmm_modules[TMM_DECODEPCAPFILE].name = "DecodePcapFile"; tmm_modules[TMM_DECODEPCAPFILE].ThreadInit = DecodePcapFileThreadInit; @@ -143,7 +140,7 @@ void PcapFileGlobalInit(void) TmEcode PcapFileExit(TmEcode status, struct timespec *last_processed) { - if(RunModeUnixSocketIsActive()) { + if (RunModeUnixSocketIsActive()) { status = UnixSocketPcapFile(status, last_processed); SCReturnInt(status); } else { @@ -156,7 +153,7 @@ TmEcode ReceivePcapFileLoop(ThreadVars *tv, void *data, void *slot) { SCEnter(); - if(unlikely(data == NULL)) { + if (unlikely(data == NULL)) { SCLogError("pcap file reader thread failed to initialize"); PcapFileExit(TM_ECODE_FAILED, NULL); @@ -165,7 +162,7 @@ TmEcode ReceivePcapFileLoop(ThreadVars *tv, void *data, void *slot) } TmEcode status = TM_ECODE_OK; - PcapFileThreadVars *ptv = (PcapFileThreadVars *) data; + PcapFileThreadVars *ptv = (PcapFileThreadVars *)data; TmSlot *s = (TmSlot *)slot; ptv->shared.slot = s->slot_next; @@ -175,7 +172,7 @@ TmEcode ReceivePcapFileLoop(ThreadVars *tv, void *data, void *slot) // packets) TmThreadsSetFlag(tv, THV_RUNNING); - if(ptv->is_directory == 0) { + if (ptv->is_directory == 0) { SCLogInfo("Starting file run for %s", ptv->behavior.file->filename); status = PcapFileDispatch(ptv->behavior.file); CleanupPcapFileFromThreadVars(ptv, ptv->behavior.file); @@ -241,13 +238,13 @@ TmEcode ReceivePcapFileThreadInit(ThreadVars *tv, const void *initdata, void **d } DIR *directory = NULL; - SCLogDebug("checking file or directory %s", (char*)initdata); - if(PcapDetermineDirectoryOrFile((char *)initdata, &directory) == TM_ECODE_FAILED) { + SCLogDebug("checking file or directory %s", (char *)initdata); + if (PcapDetermineDirectoryOrFile((char *)initdata, &directory) == TM_ECODE_FAILED) { CleanupPcapFileThreadVars(ptv); SCReturnInt(TM_ECODE_OK); } - if(directory == NULL) { + if (directory == NULL) { SCLogDebug("argument %s was a file", (char *)initdata); PcapFileFileVars *pv = SCCalloc(1, sizeof(PcapFileFileVars)); if (unlikely(pv == NULL)) { @@ -266,7 +263,7 @@ TmEcode ReceivePcapFileThreadInit(ThreadVars *tv, const void *initdata, void **d pv->shared = &ptv->shared; status = InitPcapFile(pv); - if(status == TM_ECODE_OK) { + if (status == TM_ECODE_OK) { ptv->is_directory = 0; ptv->behavior.file = pv; } else { @@ -285,7 +282,7 @@ TmEcode ReceivePcapFileThreadInit(ThreadVars *tv, const void *initdata, void **d SCReturnInt(TM_ECODE_OK); } - pv->filename = SCStrdup((char*)initdata); + pv->filename = SCStrdup((char *)initdata); if (unlikely(pv->filename == NULL)) { SCLogError("Failed to allocate filename"); closedir(directory); @@ -351,7 +348,7 @@ TmEcode ReceivePcapFileThreadInit(ThreadVars *tv, const void *initdata, void **d } else { if (strcmp(tmpstring, "auto") == 0) { pcap_g.conf_checksum_mode = CHECKSUM_VALIDATION_AUTO; - } else if (ConfValIsTrue(tmpstring)){ + } else if (ConfValIsTrue(tmpstring)) { pcap_g.conf_checksum_mode = CHECKSUM_VALIDATION_ENABLE; } else if (ConfValIsFalse(tmpstring)) { pcap_g.conf_checksum_mode = CHECKSUM_VALIDATION_DISABLE; @@ -368,12 +365,11 @@ TmEcode ReceivePcapFileThreadInit(ThreadVars *tv, const void *initdata, void **d void ReceivePcapFileThreadExitStats(ThreadVars *tv, void *data) { SCEnter(); - if(data != NULL) { + if (data != NULL) { PcapFileThreadVars *ptv = (PcapFileThreadVars *)data; if (pcap_g.conf_checksum_mode == CHECKSUM_VALIDATION_AUTO && - pcap_g.cnt < CHECKSUM_SAMPLE_COUNT && - SC_ATOMIC_GET(pcap_g.invalid_checksums)) { + pcap_g.cnt < CHECKSUM_SAMPLE_COUNT && SC_ATOMIC_GET(pcap_g.invalid_checksums)) { uint64_t chrate = pcap_g.cnt / SC_ATOMIC_GET(pcap_g.invalid_checksums); if (chrate < CHECKSUM_INVALID_RATIO) SCLogWarning("1/%" PRIu64 "th of packets have an invalid checksum," @@ -381,8 +377,7 @@ void ReceivePcapFileThreadExitStats(ThreadVars *tv, void *data) " or use '-k none' option on command line.", chrate); else - SCLogInfo("1/%" PRIu64 "th of packets have an invalid checksum", - chrate); + SCLogInfo("1/%" PRIu64 "th of packets have an invalid checksum", chrate); } SCLogNotice("read %" PRIu64 " file%s, %" PRIu64 " packets, %" PRIu64 " bytes", ptv->shared.files, ptv->shared.files == 1 ? "" : "s", ptv->shared.pkts, @@ -393,8 +388,8 @@ void ReceivePcapFileThreadExitStats(ThreadVars *tv, void *data) TmEcode ReceivePcapFileThreadDeinit(ThreadVars *tv, void *data) { SCEnter(); - if(data != NULL) { - PcapFileThreadVars *ptv = (PcapFileThreadVars *) data; + if (data != NULL) { + PcapFileThreadVars *ptv = (PcapFileThreadVars *)data; CleanupPcapFileThreadVars(ptv); } SCReturnInt(TM_ECODE_OK); @@ -411,7 +406,7 @@ static TmEcode DecodePcapFile(ThreadVars *tv, Packet *p, void *data) DecodeUpdatePacketCounters(tv, dtv, p); DecoderFunc decoder; - if(ValidateLinkType(p->datalink, &decoder) == TM_ECODE_OK) { + if (ValidateLinkType(p->datalink, &decoder) == TM_ECODE_OK) { /* call the decoder */ decoder(tv, dtv, p, GET_PKT_DATA(p), GET_PKT_LEN(p)); @@ -453,7 +448,7 @@ TmEcode DecodePcapFileThreadDeinit(ThreadVars *tv, void *data) void PcapIncreaseInvalidChecksum(void) { - (void) SC_ATOMIC_ADD(pcap_g.invalid_checksums, 1); + (void)SC_ATOMIC_ADD(pcap_g.invalid_checksums, 1); } /* eof */ diff --git a/src/source-pcap-file.h b/src/source-pcap-file.h index 30a3c2ec69c0..9e4ecb34f4ab 100644 --- a/src/source-pcap-file.h +++ b/src/source-pcap-file.h @@ -24,12 +24,11 @@ #ifndef __SOURCE_PCAP_FILE_H__ #define __SOURCE_PCAP_FILE_H__ -void TmModuleReceivePcapFileRegister (void); -void TmModuleDecodePcapFileRegister (void); +void TmModuleReceivePcapFileRegister(void); +void TmModuleDecodePcapFileRegister(void); void PcapIncreaseInvalidChecksum(void); void PcapFileGlobalInit(void); #endif /* __SOURCE_PCAP_FILE_H__ */ - diff --git a/src/source-pcap.c b/src/source-pcap.c index f916d69354c7..775009187777 100644 --- a/src/source-pcap.c +++ b/src/source-pcap.c @@ -46,7 +46,7 @@ #include "tmqh-packetpool.h" #define PCAP_STATE_DOWN 0 -#define PCAP_STATE_UP 1 +#define PCAP_STATE_UP 1 #define PCAP_RECONNECT_TIMEOUT 500000 @@ -69,8 +69,7 @@ typedef struct PcapStats64_ { /** * \brief Structure to hold thread specific variables. */ -typedef struct PcapThreadVars_ -{ +typedef struct PcapThreadVars_ { /* thread specific handle */ pcap_t *pcap_handle; /* handle state */ @@ -132,7 +131,7 @@ static SCMutex pcap_bpf_compile_lock = SCMUTEX_INITIALIZER; /** * \brief Registration Function for ReceivePcap. */ -void TmModuleReceivePcapRegister (void) +void TmModuleReceivePcapRegister(void) { tmm_modules[TMM_RECEIVEPCAP].name = "ReceivePcap"; tmm_modules[TMM_RECEIVEPCAP].ThreadInit = ReceivePcapThreadInit; @@ -150,7 +149,7 @@ void TmModuleReceivePcapRegister (void) /** * \brief Registration Function for DecodePcap. */ -void TmModuleDecodePcapRegister (void) +void TmModuleDecodePcapRegister(void) { tmm_modules[TMM_DECODEPCAP].name = "DecodePcap"; tmm_modules[TMM_DECODEPCAP].ThreadInit = DecodePcapThreadInit; @@ -184,8 +183,7 @@ static inline void UpdatePcapStatsValue64(uint64_t *last, uint32_t current32) * \brief Update 64 bit |last| stat values with values from |current| * 32 bit pcap_stat. */ -static inline void UpdatePcapStats64( - PcapStats64 *last, const struct pcap_stat *current) +static inline void UpdatePcapStats64(PcapStats64 *last, const struct pcap_stat *current) { UpdatePcapStatsValue64(&last->ps_recv, current->ps_recv); UpdatePcapStatsValue64(&last->ps_drop, current->ps_drop); @@ -198,13 +196,10 @@ static inline void PcapDumpCounters(PcapThreadVars *ptv) if (likely((pcap_stats(ptv->pcap_handle, &pcap_s) >= 0))) { UpdatePcapStats64(&ptv->last_stats64, &pcap_s); - StatsSetUI64(ptv->tv, ptv->capture_kernel_packets, - ptv->last_stats64.ps_recv); - StatsSetUI64( - ptv->tv, ptv->capture_kernel_drops, ptv->last_stats64.ps_drop); + StatsSetUI64(ptv->tv, ptv->capture_kernel_packets, ptv->last_stats64.ps_recv); + StatsSetUI64(ptv->tv, ptv->capture_kernel_drops, ptv->last_stats64.ps_drop); (void)SC_ATOMIC_SET(ptv->livedev->drop, ptv->last_stats64.ps_drop); - StatsSetUI64(ptv->tv, ptv->capture_kernel_ifdrops, - ptv->last_stats64.ps_ifdrop); + StatsSetUI64(ptv->tv, ptv->capture_kernel_ifdrops, ptv->last_stats64.ps_ifdrop); } } @@ -341,7 +336,7 @@ static void PcapCallbackLoop(char *user, struct pcap_pkthdr *h, u_char *pkt) ptv->pkts++; ptv->bytes += h->caplen; - (void) SC_ATOMIC_ADD(ptv->livedev->pkts, 1); + (void)SC_ATOMIC_ADD(ptv->livedev->pkts, 1); p->livedev = ptv->livedev; if (unlikely(PacketCopyData(p, pkt, h->caplen))) { @@ -351,8 +346,7 @@ static void PcapCallbackLoop(char *user, struct pcap_pkthdr *h, u_char *pkt) switch (ptv->checksum_mode) { case CHECKSUM_VALIDATION_AUTO: - if (ChecksumAutoModeCheck(ptv->pkts, - SC_ATOMIC_GET(ptv->livedev->pkts), + if (ChecksumAutoModeCheck(ptv->pkts, SC_ATOMIC_GET(ptv->livedev->pkts), SC_ATOMIC_GET(ptv->livedev->invalid_checksums))) { ptv->checksum_mode = CHECKSUM_VALIDATION_DISABLE; p->flags |= PKT_IGNORE_CHECKSUM; @@ -411,8 +405,8 @@ static TmEcode ReceivePcapLoop(ThreadVars *tv, void *data, void *slot) * us from alloc'ing packets at line rate */ PacketPoolWait(); - int r = pcap_dispatch(ptv->pcap_handle, packet_q_len, - (pcap_handler)PcapCallbackLoop, (u_char *)ptv); + int r = pcap_dispatch( + ptv->pcap_handle, packet_q_len, (pcap_handler)PcapCallbackLoop, (u_char *)ptv); if (unlikely(r == 0 || r == PCAP_ERROR_BREAK || (r > 0 && r < packet_q_len))) { if (r == PCAP_ERROR_BREAK && ptv->cb_result == TM_ECODE_FAILED) { SCReturnInt(TM_ECODE_FAILED); @@ -535,12 +529,9 @@ static TmEcode ReceivePcapThreadInit(ThreadVars *tv, const void *initdata, void pcapconfig->DerefFunc(pcapconfig); - ptv->capture_kernel_packets = StatsRegisterCounter("capture.kernel_packets", - ptv->tv); - ptv->capture_kernel_drops = StatsRegisterCounter("capture.kernel_drops", - ptv->tv); - ptv->capture_kernel_ifdrops = StatsRegisterCounter("capture.kernel_ifdrops", - ptv->tv); + ptv->capture_kernel_packets = StatsRegisterCounter("capture.kernel_packets", ptv->tv); + ptv->capture_kernel_drops = StatsRegisterCounter("capture.kernel_drops", ptv->tv); + ptv->capture_kernel_ifdrops = StatsRegisterCounter("capture.kernel_ifdrops", ptv->tv); *data = (void *)ptv; SCReturnInt(TM_ECODE_OK); @@ -577,8 +568,7 @@ static void ReceivePcapThreadExitStats(ThreadVars *tv, void *data) UpdatePcapStats64(&ptv->last_stats64, &pcap_s); float drop_percent = likely(ptv->last_stats64.ps_recv > 0) - ? (((float)ptv->last_stats64.ps_drop) / - (float)ptv->last_stats64.ps_recv) * + ? (((float)ptv->last_stats64.ps_drop) / (float)ptv->last_stats64.ps_recv) * 100 : 0; SCLogInfo("%s: pcap total:%" PRIu64 " recv:%" PRIu64 " drop:%" PRIu64 " (%02.1f%%)", @@ -675,25 +665,22 @@ void PcapTranslateIPToDevice(char *pcap_dev, size_t len) return; } - for (pcap_if_t *devsp = alldevsp; devsp ; devsp = devsp->next) { - for (pcap_addr_t *ip = devsp->addresses; ip ; ip = ip->next) { + for (pcap_if_t *devsp = alldevsp; devsp; devsp = devsp->next) { + for (pcap_addr_t *ip = devsp->addresses; ip; ip = ip->next) { if (ai_list->ai_family != ip->addr->sa_family) { continue; } if (ip->addr->sa_family == AF_INET) { - if (memcmp(&((struct sockaddr_in*)ai_list->ai_addr)->sin_addr, - &((struct sockaddr_in*)ip->addr)->sin_addr, - sizeof(struct in_addr))) - { + if (memcmp(&((struct sockaddr_in *)ai_list->ai_addr)->sin_addr, + &((struct sockaddr_in *)ip->addr)->sin_addr, sizeof(struct in_addr))) { continue; } } else if (ip->addr->sa_family == AF_INET6) { - if (memcmp(&((struct sockaddr_in6*)ai_list->ai_addr)->sin6_addr, - &((struct sockaddr_in6*)ip->addr)->sin6_addr, - sizeof(struct in6_addr))) - { + if (memcmp(&((struct sockaddr_in6 *)ai_list->ai_addr)->sin6_addr, + &((struct sockaddr_in6 *)ip->addr)->sin6_addr, + sizeof(struct in6_addr))) { continue; } } else { diff --git a/src/source-pcap.h b/src/source-pcap.h index 5ac36f9bacf5..625bcf31211e 100644 --- a/src/source-pcap.h +++ b/src/source-pcap.h @@ -24,16 +24,15 @@ #ifndef __SOURCE_PCAP_H__ #define __SOURCE_PCAP_H__ -void TmModuleReceivePcapRegister (void); -void TmModuleDecodePcapRegister (void); +void TmModuleReceivePcapRegister(void); +void TmModuleDecodePcapRegister(void); void PcapTranslateIPToDevice(char *pcap_dev, size_t len); -#define LIBPCAP_COPYWAIT 500 -#define LIBPCAP_PROMISC 1 +#define LIBPCAP_COPYWAIT 500 +#define LIBPCAP_PROMISC 1 /* per packet Pcap vars */ -typedef struct PcapPacketVars_ -{ +typedef struct PcapPacketVars_ { uint32_t tenant_id; } PcapPacketVars; @@ -41,8 +40,7 @@ typedef struct PcapPacketVars_ * must be quite long. */ #define PCAP_IFACE_NAME_LENGTH 128 -typedef struct PcapIfaceConfig_ -{ +typedef struct PcapIfaceConfig_ { char iface[PCAP_IFACE_NAME_LENGTH]; /* number of threads */ int threads; diff --git a/src/source-pfring.c b/src/source-pfring.c index 40a42723d6a7..753e11273321 100644 --- a/src/source-pfring.c +++ b/src/source-pfring.c @@ -64,19 +64,19 @@ extern uint16_t max_pending_packets; /*Handle cases where we don't have PF_RING support built-in*/ TmEcode NoPfringSupportExit(ThreadVars *, const void *, void **); -void TmModuleReceivePfringRegister (void) +void TmModuleReceivePfringRegister(void) { tmm_modules[TMM_RECEIVEPFRING].name = "ReceivePfring"; tmm_modules[TMM_RECEIVEPFRING].ThreadInit = NoPfringSupportExit; tmm_modules[TMM_RECEIVEPFRING].Func = NULL; tmm_modules[TMM_RECEIVEPFRING].ThreadExitPrintStats = NULL; tmm_modules[TMM_RECEIVEPFRING].ThreadDeinit = NULL; - tmm_modules[TMM_RECEIVEPFRING].cap_flags = SC_CAP_NET_ADMIN | SC_CAP_NET_RAW | - SC_CAP_NET_BIND_SERVICE | SC_CAP_NET_BROADCAST; + tmm_modules[TMM_RECEIVEPFRING].cap_flags = + SC_CAP_NET_ADMIN | SC_CAP_NET_RAW | SC_CAP_NET_BIND_SERVICE | SC_CAP_NET_BROADCAST; tmm_modules[TMM_RECEIVEPFRING].flags = TM_FLAG_RECEIVE_TM; } -void TmModuleDecodePfringRegister (void) +void TmModuleDecodePfringRegister(void) { tmm_modules[TMM_DECODEPFRING].name = "DecodePfring"; tmm_modules[TMM_DECODEPFRING].ThreadInit = NoPfringSupportExit; @@ -109,19 +109,18 @@ TmEcode NoPfringSupportExit(ThreadVars *tv, const void *initdata, void **data) static SCMutex pfring_bpf_set_filter_lock = SCMUTEX_INITIALIZER; /* XXX replace with user configurable options */ -#define LIBPFRING_PROMISC 1 -#define LIBPFRING_REENTRANT 0 +#define LIBPFRING_PROMISC 1 +#define LIBPFRING_REENTRANT 0 #define LIBPFRING_WAIT_FOR_INCOMING 1 /* PfringThreadVars flags */ -#define PFRING_FLAGS_ZERO_COPY (1 << 0) -#define PFRING_FLAGS_BYPASS (1 << 1) +#define PFRING_FLAGS_ZERO_COPY (1 << 0) +#define PFRING_FLAGS_BYPASS (1 << 1) /** * \brief Structure to hold thread specific variables. */ -struct PfringThreadVars_ -{ +struct PfringThreadVars_ { /* thread specific handle */ pfring *pd; @@ -151,7 +150,7 @@ struct PfringThreadVars_ char *bpf_filter; - ChecksumValidationMode checksum_mode; + ChecksumValidationMode checksum_mode; bool vlan_hdr_warned; }; @@ -160,7 +159,7 @@ struct PfringThreadVars_ * \brief Registration Function for ReceivePfring. * \todo Unit tests are needed for this module. */ -void TmModuleReceivePfringRegister (void) +void TmModuleReceivePfringRegister(void) { tmm_modules[TMM_RECEIVEPFRING].name = "ReceivePfring"; tmm_modules[TMM_RECEIVEPFRING].ThreadInit = ReceivePfringThreadInit; @@ -176,7 +175,7 @@ void TmModuleReceivePfringRegister (void) * \brief Registration Function for DecodePfring. * \todo Unit tests are needed for this module. */ -void TmModuleDecodePfringRegister (void) +void TmModuleDecodePfringRegister(void) { tmm_modules[TMM_DECODEPFRING].name = "DecodePfring"; tmm_modules[TMM_DECODEPFRING].ThreadInit = DecodePfringThreadInit; @@ -255,10 +254,8 @@ static inline void PfringProcessPacket(void *user, struct pfring_pkthdr *h, Pack * So if it is not set, use the parsed info from PF_RING's * extended header. */ - if (ptv->vlan_in_ext_header && - h->extended_hdr.parsed_pkt.offset.vlan_offset == 0 && - h->extended_hdr.parsed_pkt.vlan_id) - { + if (ptv->vlan_in_ext_header && h->extended_hdr.parsed_pkt.offset.vlan_offset == 0 && + h->extended_hdr.parsed_pkt.vlan_id) { p->vlan_id[0] = h->extended_hdr.parsed_pkt.vlan_id & 0x0fff; p->vlan_idx = 1; @@ -279,8 +276,7 @@ static inline void PfringProcessPacket(void *user, struct pfring_pkthdr *h, Pack p->flags |= PKT_IGNORE_CHECKSUM; break; case CHECKSUM_VALIDATION_AUTO: - if (ChecksumAutoModeCheck(ptv->pkts, - SC_ATOMIC_GET(ptv->livedev->pkts), + if (ChecksumAutoModeCheck(ptv->pkts, SC_ATOMIC_GET(ptv->livedev->pkts), SC_ATOMIC_GET(ptv->livedev->invalid_checksums))) { ptv->checksum_mode = CHECKSUM_VALIDATION_DISABLE; p->flags |= PKT_IGNORE_CHECKSUM; @@ -367,7 +363,7 @@ TmEcode ReceivePfringLoop(ThreadVars *tv, void *data, void *slot) // packets) TmThreadsSetFlag(tv, THV_RUNNING); - while(1) { + while (1) { if (suricata_ctl_flags & SURICATA_STOP) { SCReturnInt(TM_ECODE_OK); } @@ -394,10 +390,7 @@ TmEcode ReceivePfringLoop(ThreadVars *tv, void *data, void *slot) pkt_buffer = GET_PKT_DIRECT_DATA(p); } - int r = pfring_recv(ptv->pd, &pkt_buffer, - buffer_size, - &hdr, - LIBPFRING_WAIT_FOR_INCOMING); + int r = pfring_recv(ptv->pd, &pkt_buffer, buffer_size, &hdr, LIBPFRING_WAIT_FOR_INCOMING); if (likely(r == 1)) { /* profiling started before blocking pfring_recv call, so * reset it here */ @@ -490,7 +483,7 @@ TmEcode ReceivePfringThreadInit(ThreadVars *tv, const void *initdata, void **dat { int rc; u_int32_t version = 0; - PfringIfaceConfig *pfconf = (PfringIfaceConfig *) initdata; + PfringIfaceConfig *pfconf = (PfringIfaceConfig *)initdata; unsigned int opflag; char const *active_runmode = RunmodeGetActive(); @@ -591,11 +584,12 @@ TmEcode ReceivePfringThreadInit(ThreadVars *tv, const void *initdata, void **dat } if (ptv->threads > 1) { - SCLogPerf("(%s) Using PF_RING v.%d.%d.%d, interface %s, cluster-id %d", - tv->name, (version & 0xFFFF0000) >> 16, (version & 0x0000FF00) >> 8, - version & 0x000000FF, ptv->interface, ptv->cluster_id); + SCLogPerf("(%s) Using PF_RING v.%d.%d.%d, interface %s, cluster-id %d", tv->name, + (version & 0xFFFF0000) >> 16, (version & 0x0000FF00) >> 8, version & 0x000000FF, + ptv->interface, ptv->cluster_id); } else { - SCLogPerf("(%s) Using PF_RING v.%d.%d.%d, interface %s, cluster-id %d, single-pfring-thread", + SCLogPerf( + "(%s) Using PF_RING v.%d.%d.%d, interface %s, cluster-id %d, single-pfring-thread", tv->name, (version & 0xFFFF0000) >> 16, (version & 0x0000FF00) >> 8, version & 0x000000FF, ptv->interface, ptv->cluster_id); } @@ -616,26 +610,23 @@ TmEcode ReceivePfringThreadInit(ThreadVars *tv, const void *initdata, void **dat } } - ptv->capture_kernel_packets = StatsRegisterCounter("capture.kernel_packets", - ptv->tv); - ptv->capture_kernel_drops = StatsRegisterCounter("capture.kernel_drops", - ptv->tv); + ptv->capture_kernel_packets = StatsRegisterCounter("capture.kernel_packets", ptv->tv); + ptv->capture_kernel_drops = StatsRegisterCounter("capture.kernel_drops", ptv->tv); #ifdef HAVE_PF_RING_FLOW_OFFLOAD - ptv->capture_bypassed = StatsRegisterCounter("capture.bypassed", - ptv->tv); + ptv->capture_bypassed = StatsRegisterCounter("capture.bypassed", ptv->tv); #endif /* If kernel is older than 3.0, VLAN is not stripped so we don't * get the info from packet extended header but we will use a standard * parsing */ ptv->vlan_in_ext_header = 1; - if (! SCKernelVersionIsAtLeast(3, 0)) { + if (!SCKernelVersionIsAtLeast(3, 0)) { ptv->vlan_in_ext_header = 0; } /* If VLAN tags are not in the extended header, set cluster type to 5-tuple * or in case of a ZC interface, do nothing */ - if ((! ptv->vlan_in_ext_header) && ptv->ctype == CLUSTER_FLOW && + if ((!ptv->vlan_in_ext_header) && ptv->ctype == CLUSTER_FLOW && strncmp(ptv->interface, "zc", 2) != 0) { SCLogPerf("VLAN not in extended header, setting cluster type to CLUSTER_FLOW_5_TUPLE"); rc = pfring_set_cluster(ptv->pd, ptv->cluster_id, CLUSTER_FLOW_5_TUPLE); @@ -667,15 +658,13 @@ void ReceivePfringThreadExitStats(ThreadVars *tv, void *data) PfringThreadVars *ptv = (PfringThreadVars *)data; PfringDumpCounters(ptv); - SCLogPerf("(%s) Kernel: Packets %" PRIu64 ", dropped %" PRIu64 "", - tv->name, + SCLogPerf("(%s) Kernel: Packets %" PRIu64 ", dropped %" PRIu64 "", tv->name, StatsGetLocalCounterValue(tv, ptv->capture_kernel_packets), StatsGetLocalCounterValue(tv, ptv->capture_kernel_drops)); SCLogPerf("(%s) Packets %" PRIu64 ", bytes %" PRIu64 "", tv->name, ptv->pkts, ptv->bytes); #ifdef HAVE_PF_RING_FLOW_OFFLOAD if (ptv->flags & PFRING_FLAGS_BYPASS) { - SCLogPerf("(%s) Bypass: Packets %" PRIu64 "", - tv->name, + SCLogPerf("(%s) Bypass: Packets %" PRIu64 "", tv->name, StatsGetLocalCounterValue(tv, ptv->capture_bypassed)); } #endif diff --git a/src/source-pfring.h b/src/source-pfring.h index 6b170ee78d52..b2eb17133028 100644 --- a/src/source-pfring.h +++ b/src/source-pfring.h @@ -32,8 +32,7 @@ typedef struct PfringThreadVars_ PfringThreadVars; #define PFRING_CONF_FLAGS_CLUSTER (1 << 0) #define PFRING_CONF_FLAGS_BYPASS (1 << 1) -typedef struct PfringIfaceConfig_ -{ +typedef struct PfringIfaceConfig_ { uint32_t flags; /* cluster param */ @@ -56,15 +55,13 @@ typedef struct PfringIfaceConfig_ * * This structure is used to pass packet metadata in callbacks. */ -typedef struct PfringPacketVars_ -{ +typedef struct PfringPacketVars_ { PfringThreadVars *ptv; uint32_t flow_id; } PfringPacketVars; - -void TmModuleReceivePfringRegister (void); -void TmModuleDecodePfringRegister (void); +void TmModuleReceivePfringRegister(void); +void TmModuleDecodePfringRegister(void); int PfringConfGetThreads(void); void PfringLoadConfig(void); @@ -74,9 +71,9 @@ void PfringLoadConfig(void); * these values must match with cluster_type in the kernel * include file pf_ring.h */ -#define CLUSTER_FLOW 0 -#define CLUSTER_ROUND_ROBIN 1 -#define CLUSTER_FLOW_5_TUPLE 4 +#define CLUSTER_FLOW 0 +#define CLUSTER_ROUND_ROBIN 1 +#define CLUSTER_FLOW_5_TUPLE 4 #define CLUSTER_INNER_FLOW 6 #define CLUSTER_INNER_FLOW_2_TUPLE 7 #define CLUSTER_INNER_FLOW_4_TUPLE 8 diff --git a/src/source-windivert.c b/src/source-windivert.c index 347d2e7a0f2d..3e18d1648563 100644 --- a/src/source-windivert.c +++ b/src/source-windivert.c @@ -78,8 +78,7 @@ void TmModuleDecodeWinDivertRegister(void) tmm_modules[TMM_DECODEWINDIVERT].flags = TM_FLAG_DECODE_TM; } -TmEcode NoWinDivertSupportExit(ThreadVars *tv, const void *initdata, - void **data) +TmEcode NoWinDivertSupportExit(ThreadVars *tv, const void *initdata, void **data) { SCLogError("Error creating thread %s: you do not have support for WinDivert " "enabled; please recompile with --enable-windivert", @@ -257,14 +256,12 @@ int WinDivertRegisterQueue(bool forward, char *filter_str) SCEnter(); int ret = 0; - WINDIVERT_LAYER layer = - forward ? WINDIVERT_LAYER_NETWORK_FORWARD : WINDIVERT_LAYER_NETWORK; + WINDIVERT_LAYER layer = forward ? WINDIVERT_LAYER_NETWORK_FORWARD : WINDIVERT_LAYER_NETWORK; /* validate the filter string */ const char *error_str; uint32_t error_pos; - bool valid = WinDivertHelperCheckFilter(filter_str, layer, &error_str, - &error_pos); + bool valid = WinDivertHelperCheckFilter(filter_str, layer, &error_str, &error_pos); if (!valid) { SCLogWarning("Invalid filter \"%s\" supplied to WinDivert: %s at position " "%" PRId32 "", @@ -298,8 +295,7 @@ int WinDivertRegisterQueue(bool forward, char *filter_str) /* copy filter to persistent storage */ size_t filter_len = strlen(filter_str); - size_t copy_len = - strlcpy(wd_qv->filter_str, filter_str, sizeof(wd_qv->filter_str)); + size_t copy_len = strlcpy(wd_qv->filter_str, filter_str, sizeof(wd_qv->filter_str)); if (filter_len > copy_len) { SCLogWarning("Queue length exceeds storage by %" PRId32 " bytes", (int32_t)(filter_len - copy_len)); @@ -308,9 +304,8 @@ int WinDivertRegisterQueue(bool forward, char *filter_str) } wd_qv->layer = layer; - wd_qv->priority = - g_wd_num; /* priority set in the order filters are defined */ - wd_qv->flags = 0; /* normal inline function */ + wd_qv->priority = g_wd_num; /* priority set in the order filters are defined */ + wd_qv->flags = 0; /* normal inline function */ SCMutexInit(&wd_qv->filter_init_mutex, NULL); SCMutexInit(&wd_qv->counters_mutex, NULL); @@ -356,8 +351,7 @@ static TmEcode WinDivertRecvHelper(ThreadVars *tv, WinDivertThreadVars *); static TmEcode WinDivertVerdictHelper(ThreadVars *tv, Packet *p); static TmEcode WinDivertCloseHelper(WinDivertThreadVars *); -static TmEcode WinDivertCollectFilterDevices(WinDivertThreadVars *, - WinDivertQueueVars *); +static TmEcode WinDivertCollectFilterDevices(WinDivertThreadVars *, WinDivertQueueVars *); static bool WinDivertIfaceMatchFilter(const char *filter_string, int if_index); static void WinDivertDisableOffloading(WinDivertThreadVars *); static void WinDivertRestoreOffloading(WinDivertThreadVars *); @@ -440,8 +434,7 @@ static TmEcode WinDivertRecvHelper(ThreadVars *tv, WinDivertThreadVars *wd_tv) /* obtain a packet buffer */ Packet *p = PacketGetFromQueueOrAlloc(); if (unlikely(p == NULL)) { - SCLogDebug( - "PacketGetFromQueueOrAlloc() - failed to obtain Packet buffer"); + SCLogDebug("PacketGetFromQueueOrAlloc() - failed to obtain Packet buffer"); SCReturnInt(TM_ECODE_FAILED); } PKT_SET_SRC(p, PKT_SRC_WIRE); @@ -455,13 +448,11 @@ static TmEcode WinDivertRecvHelper(ThreadVars *tv, WinDivertThreadVars *wd_tv) /* allocate external, if not already */ PacketCallocExtPkt(p, MAX_PAYLOAD_SIZE); - success = - WinDivertRecv(wd_tv->filter_handle, p->ext_pkt, - MAX_PAYLOAD_SIZE, &p->windivert_v.addr, &pktlen); + success = WinDivertRecv( + wd_tv->filter_handle, p->ext_pkt, MAX_PAYLOAD_SIZE, &p->windivert_v.addr, &pktlen); } else { success = WinDivertRecv(wd_tv->filter_handle, GET_PKT_DIRECT_DATA(p), - GET_PKT_DIRECT_MAX_SIZE(p), - &p->windivert_v.addr, &pktlen); + GET_PKT_DIRECT_MAX_SIZE(p), &p->windivert_v.addr, &pktlen); } SET_PKT_LEN(p, pktlen); @@ -476,8 +467,7 @@ static TmEcode WinDivertRecvHelper(ThreadVars *tv, WinDivertThreadVars *wd_tv) */ SET_PKT_LEN(p, 0); - SCLogInfo("WinDivertRecv failed: error %" PRIu32 "", - (uint32_t)(GetLastError())); + SCLogInfo("WinDivertRecv failed: error %" PRIu32 "", (uint32_t)(GetLastError())); SCReturnInt(TM_ECODE_FAILED); } SCLogDebug("Packet received, length %" PRId32 "", GET_PKT_LEN(p)); @@ -512,8 +502,7 @@ static TmEcode WinDivertRecvHelper(ThreadVars *tv, WinDivertThreadVars *wd_tv) * \param initdata pointer to the interface passed from the user * \param data out-pointer to the WinDivert-specific thread vars */ -TmEcode ReceiveWinDivertThreadInit(ThreadVars *tv, const void *initdata, - void **data) +TmEcode ReceiveWinDivertThreadInit(ThreadVars *tv, const void *initdata, void **data) { SCEnter(); TmEcode ret = TM_ECODE_OK; @@ -534,8 +523,7 @@ TmEcode ReceiveWinDivertThreadInit(ThreadVars *tv, const void *initdata, SCMutexLock(&wd_qv->filter_init_mutex); /* does the queue already have an active handle? */ - if (wd_qv->filter_handle != NULL && - wd_qv->filter_handle != INVALID_HANDLE_VALUE) { + if (wd_qv->filter_handle != NULL && wd_qv->filter_handle != INVALID_HANDLE_VALUE) { goto unlock; } @@ -550,8 +538,8 @@ TmEcode ReceiveWinDivertThreadInit(ThreadVars *tv, const void *initdata, /* we open now so that we can immediately start handling packets, * instead of losing however many would occur between registering the * queue and starting a receive thread. */ - wd_qv->filter_handle = WinDivertOpen(wd_qv->filter_str, wd_qv->layer, - wd_qv->priority, wd_qv->flags); + wd_qv->filter_handle = + WinDivertOpen(wd_qv->filter_str, wd_qv->layer, wd_qv->priority, wd_qv->flags); if (wd_qv->filter_handle == INVALID_HANDLE_VALUE) { WinDivertLogError(GetLastError()); ret = TM_ECODE_FAILED; @@ -577,8 +565,7 @@ TmEcode ReceiveWinDivertThreadInit(ThreadVars *tv, const void *initdata, * \param wd_tv pointer to WinDivert thread vars * \param wd_qv pointer to WinDivert queue vars */ -static TmEcode WinDivertCollectFilterDevices(WinDivertThreadVars *wd_tv, - WinDivertQueueVars *wd_qv) +static TmEcode WinDivertCollectFilterDevices(WinDivertThreadVars *wd_tv, WinDivertQueueVars *wd_qv) { SCEnter(); TmEcode ret = TM_ECODE_OK; @@ -590,12 +577,11 @@ static TmEcode WinDivertCollectFilterDevices(WinDivertThreadVars *wd_tv, goto release; } - for (IP_ADAPTER_ADDRESSES *if_info = if_info_list; if_info != NULL; - if_info = if_info->Next) { + for (IP_ADAPTER_ADDRESSES *if_info = if_info_list; if_info != NULL; if_info = if_info->Next) { if (WinDivertIfaceMatchFilter(wd_qv->filter_str, if_info->IfIndex)) { - SCLogConfig("Found adapter %s matching WinDivert filter %s", - if_info->AdapterName, wd_qv->filter_str); + SCLogConfig("Found adapter %s matching WinDivert filter %s", if_info->AdapterName, + wd_qv->filter_str); LiveDevice *new_ldev = SCCalloc(1, sizeof(LiveDevice)); if (new_ldev == NULL) { @@ -609,8 +595,8 @@ static TmEcode WinDivertCollectFilterDevices(WinDivertThreadVars *wd_tv, } TAILQ_INSERT_TAIL(&wd_tv->live_devices, new_ldev, next); } else { - SCLogDebug("Adapter %s does not match WinDivert filter %s", - if_info->AdapterName, wd_qv->filter_str); + SCLogDebug("Adapter %s does not match WinDivert filter %s", if_info->AdapterName, + wd_qv->filter_str); } } @@ -630,10 +616,10 @@ static bool WinDivertIfaceMatchFilter(const char *filter_string, int if_index) WINDIVERT_ADDRESS if_addr = {}; if_addr.IfIdx = if_index; - uint8_t dummy[4] = {4, 4, 4, 4}; + uint8_t dummy[4] = { 4, 4, 4, 4 }; - match = WinDivertHelperEvalFilter(filter_string, WINDIVERT_LAYER_NETWORK, - dummy, sizeof(dummy), &if_addr); + match = WinDivertHelperEvalFilter( + filter_string, WINDIVERT_LAYER_NETWORK, dummy, sizeof(dummy), &if_addr); if (!match) { int err = GetLastError(); if (err != 0) { @@ -652,7 +638,7 @@ static bool WinDivertIfaceMatchFilter(const char *filter_string, int if_index) static void WinDivertDisableOffloading(WinDivertThreadVars *wd_tv) { for (LiveDevice *ldev = TAILQ_FIRST(&wd_tv->live_devices); ldev != NULL; - ldev = TAILQ_NEXT(ldev, next)) { + ldev = TAILQ_NEXT(ldev, next)) { if (LiveGetOffload() == 0) { if (GetIfaceOffloading(ldev->dev, 1, 1) == 1) { @@ -674,7 +660,7 @@ static void WinDivertDisableOffloading(WinDivertThreadVars *wd_tv) static void WinDivertRestoreOffloading(WinDivertThreadVars *wd_tv) { for (LiveDevice *ldev = TAILQ_FIRST(&wd_tv->live_devices); ldev != NULL; - ldev = TAILQ_NEXT(ldev, next)) { + ldev = TAILQ_NEXT(ldev, next)) { RestoreIfaceOffloading(ldev); } @@ -715,11 +701,10 @@ void ReceiveWinDivertThreadExitStats(ThreadVars *tv, void *data) SCMutexLock(&wd_qv->counters_mutex); - SCLogInfo("(%s) Packets %" PRIu32 ", Bytes %" PRIu64 ", Errors %" PRIu32 "", - tv->name, wd_qv->pkts, wd_qv->bytes, wd_qv->errs); - SCLogInfo("(%s) Verdict: Accepted %" PRIu32 ", Dropped %" PRIu32 - ", Replaced %" PRIu32 "", - tv->name, wd_qv->accepted, wd_qv->dropped, wd_qv->replaced); + SCLogInfo("(%s) Packets %" PRIu32 ", Bytes %" PRIu64 ", Errors %" PRIu32 "", tv->name, + wd_qv->pkts, wd_qv->bytes, wd_qv->errs); + SCLogInfo("(%s) Verdict: Accepted %" PRIu32 ", Dropped %" PRIu32 ", Replaced %" PRIu32 "", + tv->name, wd_qv->accepted, wd_qv->dropped, wd_qv->replaced); SCMutexUnlock(&wd_qv->counters_mutex); SCReturn; @@ -762,8 +747,7 @@ static TmEcode WinDivertVerdictHelper(ThreadVars *tv, Packet *p) } /* the handle has been closed and we can no longer use it */ - if (wd_tv->filter_handle == INVALID_HANDLE_VALUE || - wd_tv->filter_handle == NULL) { + if (wd_tv->filter_handle == INVALID_HANDLE_VALUE || wd_tv->filter_handle == NULL) { SCReturnInt(TM_ECODE_OK); } @@ -793,8 +777,8 @@ static TmEcode WinDivertVerdictHelper(ThreadVars *tv, Packet *p) SCReturnInt(TM_ECODE_OK); } - bool success = WinDivertSend(wd_tv->filter_handle, GET_PKT_DATA(p), - GET_PKT_LEN(p), &p->windivert_v.addr, NULL); + bool success = WinDivertSend( + wd_tv->filter_handle, GET_PKT_DATA(p), GET_PKT_LEN(p), &p->windivert_v.addr, NULL); if (unlikely(!success)) { WinDivertLogError(GetLastError()); @@ -814,8 +798,7 @@ static TmEcode WinDivertVerdictHelper(ThreadVars *tv, Packet *p) * \brief init the verdict thread, which is piggybacked off the receive * thread */ -TmEcode VerdictWinDivertThreadInit(ThreadVars *tv, const void *initdata, - void **data) +TmEcode VerdictWinDivertThreadInit(ThreadVars *tv, const void *initdata, void **data) { SCEnter(); @@ -865,8 +848,7 @@ TmEcode DecodeWinDivert(ThreadVars *tv, Packet *p, void *data) SCLogDebug("IPv6 packet"); DecodeIPV6(tv, d_tv, p, GET_PKT_DATA(p), GET_PKT_LEN(p)); } else { - SCLogDebug("packet unsupported by WinDivert, first byte: %02x", - *GET_PKT_DATA(p)); + SCLogDebug("packet unsupported by WinDivert, first byte: %02x", *GET_PKT_DATA(p)); } PacketDecodeFinalize(tv, d_tv, p); @@ -874,8 +856,7 @@ TmEcode DecodeWinDivert(ThreadVars *tv, Packet *p, void *data) SCReturnInt(TM_ECODE_OK); } -TmEcode DecodeWinDivertThreadInit(ThreadVars *tv, const void *initdata, - void **data) +TmEcode DecodeWinDivertThreadInit(ThreadVars *tv, const void *initdata, void **data) { SCEnter(); @@ -912,16 +893,14 @@ static TmEcode WinDivertCloseHelper(WinDivertThreadVars *wd_tv) WinDivertQueueVars *wd_qv = WinDivertGetQueue(wd_tv->thread_num); if (wd_qv == NULL) { - SCLogDebug("No queue could be found for thread num %" PRId32 "", - wd_tv->thread_num); + SCLogDebug("No queue could be found for thread num %" PRId32 "", wd_tv->thread_num); SCReturnInt(TM_ECODE_FAILED); } SCMutexLock(&wd_qv->filter_init_mutex); /* check if there's nothing to close */ - if (wd_qv->filter_handle == INVALID_HANDLE_VALUE || - wd_qv->filter_handle == NULL) { + if (wd_qv->filter_handle == INVALID_HANDLE_VALUE || wd_qv->filter_handle == NULL) { goto unlock; } @@ -955,21 +934,13 @@ static int SourceWinDivertTestIfaceMatchFilter(void) bool expected; }; - struct testdata tests[] = { - {"true", 11, true}, - {"ifIdx=11", 11, true}, - {"ifIdx==11", 11, true}, - {"ifIdx!=11", 1, true}, - {"ifIdx!=11", 11, false}, - {"ifIdx=3", 4, false}, - {"ifIdx=11 || ifIdx=5", 5, true}, - {"ifIdx=11 || ifIdx=4", 5, false}, - {"ifIdx<3 || ifIdx>7", 8, true}, - {"ifIdx<3 || ifIdx>7", 5, false}, - {"ifIdx>3 or ifIdx<7", 5, true}, - {"ifIdx>3 && ifIdx<7", 5, true}, - {"ifIdx>3 && ifIdx<7", 1, false}, - {"(ifIdx > 3 && ifIdx < 7) or ifIdx == 11", 11, true}}; + struct testdata tests[] = { { "true", 11, true }, { "ifIdx=11", 11, true }, + { "ifIdx==11", 11, true }, { "ifIdx!=11", 1, true }, { "ifIdx!=11", 11, false }, + { "ifIdx=3", 4, false }, { "ifIdx=11 || ifIdx=5", 5, true }, + { "ifIdx=11 || ifIdx=4", 5, false }, { "ifIdx<3 || ifIdx>7", 8, true }, + { "ifIdx<3 || ifIdx>7", 5, false }, { "ifIdx>3 or ifIdx<7", 5, true }, + { "ifIdx>3 && ifIdx<7", 5, true }, { "ifIdx>3 && ifIdx<7", 1, false }, + { "(ifIdx > 3 && ifIdx < 7) or ifIdx == 11", 11, true } }; size_t count = (sizeof(tests) / sizeof(tests[0])); @@ -978,8 +949,8 @@ static int SourceWinDivertTestIfaceMatchFilter(void) bool actual = WinDivertIfaceMatchFilter(test.filter, test.if_index); if (actual != test.expected) { - printf("WinDivertIfaceMatchFilter(\"%s\", %d) == %d, expected %d\n", - test.filter, test.if_index, actual, test.expected); + printf("WinDivertIfaceMatchFilter(\"%s\", %d) == %d, expected %d\n", test.filter, + test.if_index, actual, test.expected); FAIL; } } @@ -993,8 +964,7 @@ static int SourceWinDivertTestIfaceMatchFilter(void) void SourceWinDivertRegisterTests(void) { #ifdef UNITTESTS - UtRegisterTest("SourceWinDivertTestIfaceMatchFilter", - SourceWinDivertTestIfaceMatchFilter); + UtRegisterTest("SourceWinDivertTestIfaceMatchFilter", SourceWinDivertTestIfaceMatchFilter); #endif } diff --git a/src/source-windivert.h b/src/source-windivert.h index 71574993ec91..f3f4b31d30eb 100644 --- a/src/source-windivert.h +++ b/src/source-windivert.h @@ -40,8 +40,7 @@ typedef void *WinDivertHandle; * * see https://reqrypt.org/windivert-doc.html#divert_open for more info */ -typedef struct WinDivertQueueVars_ -{ +typedef struct WinDivertQueueVars_ { int queue_num; /* see https://reqrypt.org/windivert-doc.html#filter_language */ @@ -64,8 +63,7 @@ typedef struct WinDivertQueueVars_ SCMutex counters_mutex; } WinDivertQueueVars; -typedef struct WinDivertPacketVars_ -{ +typedef struct WinDivertPacketVars_ { int thread_num; WINDIVERT_ADDRESS addr; diff --git a/src/stream-tcp-inline.c b/src/stream-tcp-inline.c index 80783ef035a6..b2cce093a5d7 100644 --- a/src/stream-tcp-inline.c +++ b/src/stream-tcp-inline.c @@ -46,8 +46,7 @@ * \retval 0 shared data is the same (or no data is shared) * \retval 1 shared data is different */ -int StreamTcpInlineSegmentCompare(const TcpStream *stream, - const Packet *p, const TcpSegment *seg) +int StreamTcpInlineSegmentCompare(const TcpStream *stream, const Packet *p, const TcpSegment *seg) { SCEnter(); @@ -73,8 +72,7 @@ int StreamTcpInlineSegmentCompare(const TcpStream *stream, } else if (SEQ_GT(seg->seq, (pkt_seq + p->payload_len))) { SCReturnInt(0); } else { - SCLogDebug("p %u (%u), seg2 %u (%u)", pkt_seq, - p->payload_len, seg->seq, seg_datalen); + SCLogDebug("p %u (%u), seg2 %u (%u)", pkt_seq, p->payload_len, seg->seq, seg_datalen); uint32_t seg_seq = seg->seq; if (SEQ_LT(seg_seq, stream->base_seq)) { @@ -117,8 +115,7 @@ int StreamTcpInlineSegmentCompare(const TcpStream *stream, * \todo What about reassembled fragments? * \todo What about unwrapped tunnel packets? */ -void StreamTcpInlineSegmentReplacePacket(const TcpStream *stream, - Packet *p, const TcpSegment *seg) +void StreamTcpInlineSegmentReplacePacket(const TcpStream *stream, Packet *p, const TcpSegment *seg) { SCEnter(); @@ -157,7 +154,7 @@ void StreamTcpInlineSegmentReplacePacket(const TcpStream *stream, if (range) { /* update the packets payload. As payload is a ptr to either * p->pkt or p->ext_pkt that is updated as well */ - memcpy(p->payload+poff, seg_data+toff, range); + memcpy(p->payload + poff, seg_data + toff, range); /* flag as modified so we can reinject / replace after * recalculating the checksum */ diff --git a/src/stream-tcp-inline.h b/src/stream-tcp-inline.h index 515c6fd6503b..bb528ef33b73 100644 --- a/src/stream-tcp-inline.h +++ b/src/stream-tcp-inline.h @@ -26,12 +26,9 @@ #include "stream-tcp-private.h" -int StreamTcpInlineSegmentCompare(const TcpStream *, - const Packet *, const TcpSegment *); -void StreamTcpInlineSegmentReplacePacket(const TcpStream *, - Packet *, const TcpSegment *); +int StreamTcpInlineSegmentCompare(const TcpStream *, const Packet *, const TcpSegment *); +void StreamTcpInlineSegmentReplacePacket(const TcpStream *, Packet *, const TcpSegment *); void StreamTcpInlineRegisterTests(void); #endif /* __STREAM_TCP_INLINE_H__ */ - diff --git a/src/stream-tcp-list.c b/src/stream-tcp-list.c index 2b8a4d079cef..46c5abe94184 100644 --- a/src/stream-tcp-list.c +++ b/src/stream-tcp-list.c @@ -73,7 +73,8 @@ int TcpSegmentCompare(struct TcpSegment *a, struct TcpSegment *b) * \return SC_OK on success * \return SC_ENOMEM on error (memory allocation error) */ -static inline int InsertSegmentDataCustom(TcpStream *stream, TcpSegment *seg, uint8_t *data, uint16_t data_len) +static inline int InsertSegmentDataCustom( + TcpStream *stream, TcpSegment *seg, uint8_t *data, uint16_t data_len) { uint64_t stream_offset; uint32_t data_offset; @@ -87,10 +88,9 @@ static inline int InsertSegmentDataCustom(TcpStream *stream, TcpSegment *seg, ui stream_offset = STREAM_BASE_OFFSET(stream); } - SCLogDebug("stream %p buffer %p, stream_offset %"PRIu64", " - "data_offset %"PRIu16", SEQ %u BASE %u, data_len %u", - stream, &stream->sb, stream_offset, - data_offset, seg->seq, stream->base_seq, data_len); + SCLogDebug("stream %p buffer %p, stream_offset %" PRIu64 ", " + "data_offset %" PRIu16 ", SEQ %u BASE %u, data_len %u", + stream, &stream->sb, stream_offset, data_offset, seg->seq, stream->base_seq, data_len); DEBUG_VALIDATE_BUG_ON(data_offset > data_len); if (data_len <= data_offset) { SCReturnInt(SC_OK); @@ -108,9 +108,9 @@ static inline int InsertSegmentDataCustom(TcpStream *stream, TcpSegment *seg, ui uint64_t mydata_offset; StreamingBufferGetData(&stream->sb, &mydata, &mydata_len, &mydata_offset); - SCLogDebug("stream %p seg %p data in buffer %p of len %u and offset %"PRIu64, - stream, seg, &stream->sb, mydata_len, mydata_offset); - //PrintRawDataFp(stdout, mydata, mydata_len); + SCLogDebug("stream %p seg %p data in buffer %p of len %u and offset %" PRIu64, stream, seg, + &stream->sb, mydata_len, mydata_offset); + // PrintRawDataFp(stdout, mydata, mydata_len); } #endif SCReturnInt(SC_OK); @@ -124,8 +124,8 @@ static inline int InsertSegmentDataCustom(TcpStream *stream, TcpSegment *seg, ui static inline bool CheckOverlap(struct TCPSEG *tree, TcpSegment *seg) { const uint32_t re = SEG_SEQ_RIGHT_EDGE(seg); - SCLogDebug("start. SEQ %u payload_len %u. Right edge: %u. Seg %p", - seg->seq, seg->payload_len, re, seg); + SCLogDebug("start. SEQ %u payload_len %u. Right edge: %u. Seg %p", seg->seq, seg->payload_len, + re, seg); /* check forward */ TcpSegment *next = TCPSEG_RB_NEXT(seg); @@ -162,7 +162,7 @@ static inline bool CheckOverlap(struct TCPSEG *tree, TcpSegment *seg) * \retval 0 inserted, no overlap * \retval -EINVAL seg out of seq range */ -static int DoInsertSegment (TcpStream *stream, TcpSegment *seg, TcpSegment **dup_seg, Packet *p) +static int DoInsertSegment(TcpStream *stream, TcpSegment *seg, TcpSegment **dup_seg, Packet *p) { /* in lossy traffic, we can get here with the wrong sequence numbers */ if (SEQ_LEQ(SEG_SEQ_RIGHT_EDGE(seg), stream->base_seq)) { @@ -172,7 +172,8 @@ static int DoInsertSegment (TcpStream *stream, TcpSegment *seg, TcpSegment **dup /* fast track */ if (RB_EMPTY(&stream->seg_tree)) { SCLogDebug("empty tree, inserting seg %p seq %" PRIu32 ", " - "len %" PRIu32 "", seg, seg->seq, TCP_SEG_LEN(seg)); + "len %" PRIu32 "", + seg, seg->seq, TCP_SEG_LEN(seg)); TCPSEG_RB_INSERT(&stream->seg_tree, seg); stream->segs_right_edge = SEG_SEQ_RIGHT_EDGE(seg); return 0; @@ -181,8 +182,7 @@ static int DoInsertSegment (TcpStream *stream, TcpSegment *seg, TcpSegment **dup /* insert and then check if there was any overlap with other segments */ TcpSegment *res = TCPSEG_RB_INSERT(&stream->seg_tree, seg); if (res) { - SCLogDebug("seg has a duplicate in the tree seq %u/%u", - res->seq, res->payload_len); + SCLogDebug("seg has a duplicate in the tree seq %u/%u", res->seq, res->payload_len); /* exact duplicate SEQ + payload_len */ *dup_seg = res; return 2; // duplicate has overlap by definition. @@ -218,13 +218,13 @@ static int DoInsertSegment (TcpStream *stream, TcpSegment *seg, TcpSegment **dup * \retval 1 if data was different * \retval 0 data was the same or we didn't check for differences */ -static int DoHandleDataOverlap(TcpStream *stream, const TcpSegment *list, - const TcpSegment *seg, uint8_t *buf, Packet *p) +static int DoHandleDataOverlap( + TcpStream *stream, const TcpSegment *list, const TcpSegment *seg, uint8_t *buf, Packet *p) { SCLogDebug("handle overlap for segment %p seq %u len %u re %u, " - "list segment %p seq %u len %u re %u", seg, seg->seq, - p->payload_len, SEG_SEQ_RIGHT_EDGE(seg), - list, list->seq, TCP_SEG_LEN(list), SEG_SEQ_RIGHT_EDGE(list)); + "list segment %p seq %u len %u re %u", + seg, seg->seq, p->payload_len, SEG_SEQ_RIGHT_EDGE(seg), list, list->seq, + TCP_SEG_LEN(list), SEG_SEQ_RIGHT_EDGE(list)); int data_is_different = 0; int use_new_data = 0; @@ -243,7 +243,7 @@ static int DoHandleDataOverlap(TcpStream *stream, const TcpSegment *list, } } - /* IDS mode */ + /* IDS mode */ } else { if (check_overlap_different_data) { if (StreamTcpInlineSegmentCompare(stream, p, list) != 0) { @@ -333,7 +333,7 @@ static int DoHandleDataOverlap(TcpStream *stream, const TcpSegment *list, } /* new seg starts after list segment */ - } else { //if (SEQ_GT(seg->seq, list->seq)) { + } else { // if (SEQ_GT(seg->seq, list->seq)) { SCLogDebug("seg starts after list segment"); if (SEQ_EQ(SEG_SEQ_RIGHT_EDGE(seg), SEG_SEQ_RIGHT_EDGE(list))) { @@ -351,14 +351,12 @@ static int DoHandleDataOverlap(TcpStream *stream, const TcpSegment *list, } } else { SCLogDebug("seg starts after list and ends before list end"); - } } } - SCLogDebug("data_is_different %s, use_new_data %s", - data_is_different ? "yes" : "no", - use_new_data ? "yes" : "no"); + SCLogDebug("data_is_different %s, use_new_data %s", data_is_different ? "yes" : "no", + use_new_data ? "yes" : "no"); /* if the data is different and we don't want to use the new (seg) * data, we have to update buf with the list data */ @@ -396,13 +394,14 @@ static int DoHandleDataOverlap(TcpStream *stream, const TcpSegment *list, if (SEQ_LT(seg->seq + seg_offset + seg_len, list_seq + list_offset + list_len)) { list_len -= (list_seq + list_offset + list_len) - (seg->seq + seg_offset + seg_len); } - SCLogDebug("here goes nothing: list %u %u, seg %u %u", list_offset, list_len, seg_offset, seg_len); + SCLogDebug("here goes nothing: list %u %u, seg %u %u", list_offset, list_len, seg_offset, + seg_len); - //PrintRawDataFp(stdout, list_data + list_offset, list_len); - //PrintRawDataFp(stdout, buf + seg_offset, seg_len); + // PrintRawDataFp(stdout, list_data + list_offset, list_len); + // PrintRawDataFp(stdout, buf + seg_offset, seg_len); memcpy(buf + seg_offset, list_data + list_offset, list_len); - //PrintRawDataFp(stdout, buf, p->payload_len); + // PrintRawDataFp(stdout, buf, p->payload_len); } return (check_overlap_different_data && data_is_different); } @@ -413,17 +412,16 @@ static int DoHandleDataOverlap(TcpStream *stream, const TcpSegment *list, * Walk back from the current segment which is already in the tree. * We walk until we can't possibly overlap anymore. */ -static int DoHandleDataCheckBackwards(TcpStream *stream, - TcpSegment *seg, uint8_t *buf, Packet *p) +static int DoHandleDataCheckBackwards(TcpStream *stream, TcpSegment *seg, uint8_t *buf, Packet *p) { int retval = 0; - SCLogDebug("check tree backwards: insert data for segment %p seq %u len %u re %u", - seg, seg->seq, TCP_SEG_LEN(seg), SEG_SEQ_RIGHT_EDGE(seg)); + SCLogDebug("check tree backwards: insert data for segment %p seq %u len %u re %u", seg, + seg->seq, TCP_SEG_LEN(seg), SEG_SEQ_RIGHT_EDGE(seg)); /* check backwards */ TcpSegment *tree_seg = NULL, *s = seg; - RB_FOREACH_REVERSE_FROM(tree_seg, TCPSEG, s) { + RB_FOREACH_REVERSE_FROM (tree_seg, TCPSEG, s) { if (tree_seg == seg) continue; @@ -438,9 +436,8 @@ static int DoHandleDataCheckBackwards(TcpStream *stream, overlap = 1; } - SCLogDebug("(back) tree seg %u len %u re %u overlap? %s", - tree_seg->seq, TCP_SEG_LEN(tree_seg), - SEG_SEQ_RIGHT_EDGE(tree_seg), overlap ? "yes" : "no"); + SCLogDebug("(back) tree seg %u len %u re %u overlap? %s", tree_seg->seq, + TCP_SEG_LEN(tree_seg), SEG_SEQ_RIGHT_EDGE(tree_seg), overlap ? "yes" : "no"); if (overlap) { retval |= DoHandleDataOverlap(stream, tree_seg, seg, buf, p); @@ -458,18 +455,17 @@ static int DoHandleDataCheckBackwards(TcpStream *stream, * \retval 1 data was different * \retval 0 data was the same */ -static int DoHandleDataCheckForward(TcpStream *stream, - TcpSegment *seg, uint8_t *buf, Packet *p) +static int DoHandleDataCheckForward(TcpStream *stream, TcpSegment *seg, uint8_t *buf, Packet *p) { int retval = 0; uint32_t seg_re = SEG_SEQ_RIGHT_EDGE(seg); - SCLogDebug("check list forward: insert data for segment %p seq %u len %u re %u", - seg, seg->seq, TCP_SEG_LEN(seg), seg_re); + SCLogDebug("check list forward: insert data for segment %p seq %u len %u re %u", seg, seg->seq, + TCP_SEG_LEN(seg), seg_re); TcpSegment *tree_seg = NULL, *s = seg; - RB_FOREACH_FROM(tree_seg, TCPSEG, s) { + RB_FOREACH_FROM (tree_seg, TCPSEG, s) { if (tree_seg == seg) continue; @@ -478,13 +474,13 @@ static int DoHandleDataCheckForward(TcpStream *stream, overlap = 1; else if (SEQ_LEQ(seg_re, tree_seg->seq)) { SCLogDebug("tree segment %u too far ahead, " - "no more overlaps can happen", tree_seg->seq); + "no more overlaps can happen", + tree_seg->seq); break; } - SCLogDebug("(fwd) in-tree seg %u len %u re %u overlap? %s", - tree_seg->seq, TCP_SEG_LEN(tree_seg), - SEG_SEQ_RIGHT_EDGE(tree_seg), overlap ? "yes" : "no"); + SCLogDebug("(fwd) in-tree seg %u len %u re %u overlap? %s", tree_seg->seq, + TCP_SEG_LEN(tree_seg), SEG_SEQ_RIGHT_EDGE(tree_seg), overlap ? "yes" : "no"); if (overlap) { retval |= DoHandleDataOverlap(stream, tree_seg, seg, buf, p); @@ -497,14 +493,14 @@ static int DoHandleDataCheckForward(TcpStream *stream, * \param tree_seg in-tree duplicate of `seg` * \retval res 0 ok, -1 insertion error due to memcap */ -static int DoHandleData(ThreadVars *tv, TcpReassemblyThreadCtx *ra_ctx, - TcpStream *stream, TcpSegment *seg, TcpSegment *tree_seg, Packet *p) +static int DoHandleData(ThreadVars *tv, TcpReassemblyThreadCtx *ra_ctx, TcpStream *stream, + TcpSegment *seg, TcpSegment *tree_seg, Packet *p) { int result = 0; TcpSegment *handle = seg; - SCLogDebug("insert data for segment %p seq %u len %u re %u", - seg, seg->seq, TCP_SEG_LEN(seg), SEG_SEQ_RIGHT_EDGE(seg)); + SCLogDebug("insert data for segment %p seq %u len %u re %u", seg, seg->seq, TCP_SEG_LEN(seg), + SEG_SEQ_RIGHT_EDGE(seg)); /* create temporary buffer to contain the data we will insert. Overlap * handling may update it. By using this we don't have to track whether @@ -525,11 +521,11 @@ static int DoHandleData(ThreadVars *tv, TcpReassemblyThreadCtx *ra_ctx, if (is_head && !is_tail) { result = DoHandleDataCheckForward(stream, handle, buf, p); - /* new list tail */ + /* new list tail */ } else if (!is_head && is_tail) { result = DoHandleDataCheckBackwards(stream, handle, buf, p); - /* middle of the list */ + /* middle of the list */ } else if (!is_head && !is_tail) { result = DoHandleDataCheckBackwards(stream, handle, buf, p); result |= DoHandleDataCheckForward(stream, handle, buf, p); @@ -635,15 +631,15 @@ static void StreamTcpSegmentAddPacketData( * In case of error, this function returns the segment to the pool */ int StreamTcpReassembleInsertSegment(ThreadVars *tv, TcpReassemblyThreadCtx *ra_ctx, - TcpStream *stream, TcpSegment *seg, Packet *p, - uint32_t pkt_seq, uint8_t *pkt_data, uint16_t pkt_datalen) + TcpStream *stream, TcpSegment *seg, Packet *p, uint32_t pkt_seq, uint8_t *pkt_data, + uint16_t pkt_datalen) { SCEnter(); TcpSegment *dup_seg = NULL; /* insert segment into list. Note: doesn't handle the data */ - int r = DoInsertSegment (stream, seg, &dup_seg, p); + int r = DoInsertSegment(stream, seg, &dup_seg, p); if (IsTcpSessionDumpingEnabled()) { StreamTcpSegmentAddPacketData(seg, p, tv, ra_ctx); @@ -685,18 +681,16 @@ int StreamTcpReassembleInsertSegment(ThreadVars *tv, TcpReassemblyThreadCtx *ra_ SCReturnInt(-1); } if (r == 2) { - SCLogDebug("duplicate segment %u/%u, discard it", - seg->seq, seg->payload_len); + SCLogDebug("duplicate segment %u/%u, discard it", seg->seq, seg->payload_len); StreamTcpSegmentReturntoPool(seg); #ifdef DEBUG if (SCLogDebugEnabled()) { TcpSegment *s = NULL, *safe = NULL; - RB_FOREACH_SAFE(s, TCPSEG, &stream->seg_tree, safe) - { - SCLogDebug("tree: seg %p, SEQ %"PRIu32", LEN %"PRIu16", SUM %"PRIu32"%s%s%s", - s, s->seq, TCP_SEG_LEN(s), - (uint32_t)(s->seq + TCP_SEG_LEN(s)), + RB_FOREACH_SAFE (s, TCPSEG, &stream->seg_tree, safe) { + SCLogDebug("tree: seg %p, SEQ %" PRIu32 ", LEN %" PRIu16 ", SUM %" PRIu32 + "%s%s%s", + s, s->seq, TCP_SEG_LEN(s), (uint32_t)(s->seq + TCP_SEG_LEN(s)), s->seq == seg->seq ? " DUPLICATE" : "", TCPSEG_RB_PREV(s) == NULL ? " HEAD" : "", TCPSEG_RB_NEXT(s) == NULL ? " TAIL" : ""); @@ -712,12 +706,10 @@ int StreamTcpReassembleInsertSegment(ThreadVars *tv, TcpReassemblyThreadCtx *ra_ SCReturnInt(0); } - /* * Pruning & removal */ - static inline bool SegmentInUse(const TcpStream *stream, const TcpSegment *seg) { /* if proto detect isn't done, we're not returning */ @@ -730,7 +722,6 @@ static inline bool SegmentInUse(const TcpStream *stream, const TcpSegment *seg) SCReturnInt(false); } - /** \internal * \brief check if we can remove a segment from our segment list * @@ -780,9 +771,9 @@ static inline uint64_t GetLeftEdge(Flow *f, TcpSession *ssn, TcpStream *stream) uint64_t raw_progress = STREAM_RAW_PROGRESS(stream); if (StreamTcpInlineMode()) { - uint32_t chunk_size = (stream == &ssn->client) ? - stream_config.reassembly_toserver_chunk_size : - stream_config.reassembly_toclient_chunk_size; + uint32_t chunk_size = (stream == &ssn->client) + ? stream_config.reassembly_toserver_chunk_size + : stream_config.reassembly_toclient_chunk_size; if (raw_progress < (uint64_t)chunk_size) { raw_progress = 0; } else { @@ -798,7 +789,7 @@ static inline uint64_t GetLeftEdge(Flow *f, TcpSession *ssn, TcpStream *stream) else raw_progress -= stream->min_inspect_depth; - SCLogDebug("stream->min_inspect_depth %u, raw_progress %"PRIu64, + SCLogDebug("stream->min_inspect_depth %u, raw_progress %" PRIu64, stream->min_inspect_depth, raw_progress); } @@ -809,8 +800,7 @@ static inline uint64_t GetLeftEdge(Flow *f, TcpSession *ssn, TcpStream *stream) app_le, raw_progress); } else { left_edge = raw_progress; - SCLogDebug("left_edge %"PRIu64", using only raw:%"PRIu64, - left_edge, raw_progress); + SCLogDebug("left_edge %" PRIu64 ", using only raw:%" PRIu64, left_edge, raw_progress); } } else if (use_app) { const uint64_t app_le = GetLeftEdgeForApp(f, ssn, stream); @@ -818,7 +808,7 @@ static inline uint64_t GetLeftEdge(Flow *f, TcpSession *ssn, TcpStream *stream) SCLogDebug("left_edge %" PRIu64 ", using only app:%" PRIu64, left_edge, app_le); } else { left_edge = StreamingBufferGetConsecutiveDataRightEdge(&stream->sb); - SCLogDebug("no app & raw: left_edge %"PRIu64" (full stream)", left_edge); + SCLogDebug("no app & raw: left_edge %" PRIu64 " (full stream)", left_edge); } if (use_log) { @@ -848,7 +838,7 @@ static inline uint64_t GetLeftEdge(Flow *f, TcpSession *ssn, TcpStream *stream) else left_edge = 0; - SCLogDebug("stream:%p left_edge %"PRIu64, stream, left_edge); + SCLogDebug("stream:%p left_edge %" PRIu64, stream, left_edge); } if (left_edge > 0) { @@ -856,7 +846,8 @@ static inline uint64_t GetLeftEdge(Flow *f, TcpSession *ssn, TcpStream *stream) * lets adjust it to make sure in-use segments still have * data */ TcpSegment *seg = NULL; - RB_FOREACH(seg, TCPSEG, &stream->seg_tree) { + RB_FOREACH(seg, TCPSEG, &stream->seg_tree) + { if (TCP_SEG_OFFSET(seg) > left_edge) { SCLogDebug("seg beyond left_edge, we're done"); break; @@ -864,7 +855,8 @@ static inline uint64_t GetLeftEdge(Flow *f, TcpSession *ssn, TcpStream *stream) if (SegmentInUse(stream, seg)) { left_edge = TCP_SEG_OFFSET(seg); - SCLogDebug("in-use seg before left_edge, adjust to %"PRIu64" and bail", left_edge); + SCLogDebug( + "in-use seg before left_edge, adjust to %" PRIu64 " and bail", left_edge); break; } } @@ -913,7 +905,8 @@ void StreamTcpPruneSession(Flow *f, uint8_t flags) if (stream->flags & STREAMTCP_STREAM_FLAG_DEPTH_REACHED) { stream->flags |= STREAMTCP_STREAM_FLAG_NOREASSEMBLY; SCLogDebug("ssn %p / stream %p: reassembly depth reached, " - "STREAMTCP_STREAM_FLAG_NOREASSEMBLY set", ssn, stream); + "STREAMTCP_STREAM_FLAG_NOREASSEMBLY set", + ssn, stream); StreamTcpReturnStreamSegments(stream); StreamingBufferClear(&stream->sb, &stream_config.sbcnf); return; @@ -921,7 +914,8 @@ void StreamTcpPruneSession(Flow *f, uint8_t flags) } else if ((ssn->flags & STREAMTCP_FLAG_APP_LAYER_DISABLED) && (stream->flags & STREAMTCP_STREAM_FLAG_DISABLE_RAW)) { SCLogDebug("ssn %p / stream %p: both app and raw are done, " - "STREAMTCP_STREAM_FLAG_NOREASSEMBLY set", ssn, stream); + "STREAMTCP_STREAM_FLAG_NOREASSEMBLY set", + ssn, stream); stream->flags |= STREAMTCP_STREAM_FLAG_NOREASSEMBLY; StreamTcpReturnStreamSegments(stream); StreamingBufferClear(&stream->sb, &stream_config.sbcnf); @@ -932,7 +926,7 @@ void StreamTcpPruneSession(Flow *f, uint8_t flags) SCLogDebug("buffer left_edge %" PRIu64, left_edge); if (left_edge && left_edge > STREAM_BASE_OFFSET(stream)) { uint32_t slide = left_edge - STREAM_BASE_OFFSET(stream); - SCLogDebug("buffer sliding %u to offset %"PRIu64, slide, left_edge); + SCLogDebug("buffer sliding %u to offset %" PRIu64, slide, left_edge); if (!(ssn->flags & STREAMTCP_FLAG_APP_LAYER_DISABLED)) { AppLayerFramesSlide(f, slide, flags & (STREAM_TOSERVER | STREAM_TOCLIENT)); @@ -956,17 +950,15 @@ void StreamTcpPruneSession(Flow *f, uint8_t flags) stream->log_progress_rel = 0; } - SCLogDebug("stream base_seq %u at stream offset %"PRIu64, - stream->base_seq, STREAM_BASE_OFFSET(stream)); + SCLogDebug("stream base_seq %u at stream offset %" PRIu64, stream->base_seq, + STREAM_BASE_OFFSET(stream)); } /* loop through the segments and remove all not in use */ TcpSegment *seg = NULL, *safe = NULL; - RB_FOREACH_SAFE(seg, TCPSEG, &stream->seg_tree, safe) - { - SCLogDebug("seg %p, SEQ %"PRIu32", LEN %"PRIu16", SUM %"PRIu32, - seg, seg->seq, TCP_SEG_LEN(seg), - (uint32_t)(seg->seq + TCP_SEG_LEN(seg))); + RB_FOREACH_SAFE (seg, TCPSEG, &stream->seg_tree, safe) { + SCLogDebug("seg %p, SEQ %" PRIu32 ", LEN %" PRIu16 ", SUM %" PRIu32, seg, seg->seq, + TCP_SEG_LEN(seg), (uint32_t)(seg->seq + TCP_SEG_LEN(seg))); if (StreamTcpReturnSegmentCheck(stream, seg) == 0) { SCLogDebug("not removing segment"); @@ -982,7 +974,6 @@ void StreamTcpPruneSession(Flow *f, uint8_t flags) SCReturn; } - /* * unittests */ diff --git a/src/stream-tcp-list.h b/src/stream-tcp-list.h index 5612354a86a1..8caf493c850d 100644 --- a/src/stream-tcp-list.h +++ b/src/stream-tcp-list.h @@ -24,7 +24,6 @@ #ifndef __STREAM_TCP_LIST_H__ #define __STREAM_TCP_LIST_H__ - #ifdef UNITTESTS void StreamTcpListRegisterTests(void); #endif diff --git a/src/stream-tcp-private.h b/src/stream-tcp-private.h index 619398deb7c9..845972d36bcb 100644 --- a/src/stream-tcp-private.h +++ b/src/stream-tcp-private.h @@ -27,9 +27,9 @@ #include "util-pool-thread.h" #include "util-streaming-buffer.h" -#define STREAMTCP_QUEUE_FLAG_TS 0x01 -#define STREAMTCP_QUEUE_FLAG_WS 0x02 -#define STREAMTCP_QUEUE_FLAG_SACK 0x04 +#define STREAMTCP_QUEUE_FLAG_TS 0x01 +#define STREAMTCP_QUEUE_FLAG_WS 0x02 +#define STREAMTCP_QUEUE_FLAG_SACK 0x04 /** Tracking SYNs and SYN/ACKs */ typedef struct TcpStateQueue_ { @@ -44,8 +44,8 @@ typedef struct TcpStateQueue_ { } TcpStateQueue; typedef struct StreamTcpSackRecord { - uint32_t le; /**< left edge, host order */ - uint32_t re; /**< right edge, host order */ + uint32_t le; /**< left edge, host order */ + uint32_t re; /**< right edge, host order */ RB_ENTRY(StreamTcpSackRecord) rb; } StreamTcpSackRecord; @@ -71,7 +71,7 @@ typedef struct TcpSegmentPcapHdrStorage_ { typedef struct TcpSegment { PoolThreadId pool_id; - uint16_t payload_len; /**< actual size of the payload */ + uint16_t payload_len; /**< actual size of the payload */ uint32_t seq; RB_ENTRY(TcpSegment) __attribute__((__packed__)) rb; StreamingBufferSegment sbseg; @@ -91,54 +91,57 @@ int TcpSegmentCompare(struct TcpSegment *a, struct TcpSegment *b); RB_HEAD(TCPSEG, TcpSegment); RB_PROTOTYPE(TCPSEG, TcpSegment, rb, TcpSegmentCompare); -#define TCP_SEG_LEN(seg) (seg)->payload_len -#define TCP_SEG_OFFSET(seg) (seg)->sbseg.stream_offset +#define TCP_SEG_LEN(seg) (seg)->payload_len +#define TCP_SEG_OFFSET(seg) (seg)->sbseg.stream_offset #define SEG_SEQ_RIGHT_EDGE(seg) ((seg)->seq + TCP_SEG_LEN((seg))) /* get right edge of sequence space of seen segments. * Only use if STREAM_HAS_SEEN_DATA is true. */ -#define STREAM_SEQ_RIGHT_EDGE(stream) (stream)->segs_right_edge -#define STREAM_RIGHT_EDGE(stream) (STREAM_BASE_OFFSET((stream)) + (STREAM_SEQ_RIGHT_EDGE((stream)) - (stream)->base_seq)) +#define STREAM_SEQ_RIGHT_EDGE(stream) (stream)->segs_right_edge +#define STREAM_RIGHT_EDGE(stream) \ + (STREAM_BASE_OFFSET((stream)) + (STREAM_SEQ_RIGHT_EDGE((stream)) - (stream)->base_seq)) /* return true if we have seen data. */ #define STREAM_HAS_SEEN_DATA(stream) StreamingBufferHasData(&(stream)->sb) typedef struct TcpStream_ { - uint16_t flags:12; /**< Flag specific to the stream e.g. Timestamp */ + uint16_t flags : 12; /**< Flag specific to the stream e.g. Timestamp */ /* coccinelle: TcpStream:flags:STREAMTCP_STREAM_FLAG_ */ - uint16_t wscale:4; /**< wscale setting in this direction, 4 bits as max val is 15 */ - uint8_t os_policy; /**< target based OS policy used for reassembly and handling packets*/ - uint8_t tcp_flags; /**< TCP flags seen */ - - uint32_t isn; /**< initial sequence number */ - uint32_t next_seq; /**< next expected sequence number */ - uint32_t last_ack; /**< last ack'd sequence number in this stream */ - uint32_t next_win; /**< next max seq within window */ - uint32_t window; /**< current window setting, after wscale is applied */ - - uint32_t last_ts; /**< Time stamp (TSVAL) of the last seen packet for this stream*/ - uint32_t last_pkt_ts; /**< Time of last seen packet for this stream (needed for PAWS update) - This will be used to validate the last_ts, when connection has been idle for - longer time.(RFC 1323)*/ + uint16_t wscale : 4; /**< wscale setting in this direction, 4 bits as max val is 15 */ + uint8_t os_policy; /**< target based OS policy used for reassembly and handling packets*/ + uint8_t tcp_flags; /**< TCP flags seen */ + + uint32_t isn; /**< initial sequence number */ + uint32_t next_seq; /**< next expected sequence number */ + uint32_t last_ack; /**< last ack'd sequence number in this stream */ + uint32_t next_win; /**< next max seq within window */ + uint32_t window; /**< current window setting, after wscale is applied */ + + uint32_t last_ts; /**< Time stamp (TSVAL) of the last seen packet for this stream*/ + uint32_t last_pkt_ts; /**< Time of last seen packet for this stream (needed for PAWS update) + This will be used to validate the last_ts, when connection has been + idle for longer time.(RFC 1323)*/ /* reassembly */ uint32_t base_seq; /**< seq where we are left with reassembly. Matches STREAM_BASE_OFFSET below. */ - uint32_t app_progress_rel; /**< app-layer progress relative to STREAM_BASE_OFFSET */ - uint32_t raw_progress_rel; /**< raw reassembly progress relative to STREAM_BASE_OFFSET */ - uint32_t log_progress_rel; /**< streaming logger progress relative to STREAM_BASE_OFFSET */ + uint32_t app_progress_rel; /**< app-layer progress relative to STREAM_BASE_OFFSET */ + uint32_t raw_progress_rel; /**< raw reassembly progress relative to STREAM_BASE_OFFSET */ + uint32_t log_progress_rel; /**< streaming logger progress relative to STREAM_BASE_OFFSET */ - uint32_t min_inspect_depth; /**< min inspect size set by the app layer, to make sure enough data - * remains available for inspection together with app layer buffers */ - uint32_t data_required; /**< data required from STREAM_APP_PROGRESS before calling app-layer again */ + uint32_t min_inspect_depth; /**< min inspect size set by the app layer, to make sure enough data + * remains available for inspection together with app layer + * buffers */ + uint32_t data_required; /**< data required from STREAM_APP_PROGRESS before calling app-layer + again */ StreamingBuffer sb; - struct TCPSEG seg_tree; /**< red black tree of TCP segments. Data is stored in TcpStream::sb */ + struct TCPSEG seg_tree; /**< red black tree of TCP segments. Data is stored in TcpStream::sb */ uint32_t segs_right_edge; - uint32_t sack_size; /**< combined size of the SACK ranges currently in our tree. Updated - * at INSERT/REMOVE time. */ - struct TCPSACK sack_tree; /**< red back tree of TCP SACK records. */ + uint32_t sack_size; /**< combined size of the SACK ranges currently in our tree. Updated + * at INSERT/REMOVE time. */ + struct TCPSACK sack_tree; /**< red back tree of TCP SACK records. */ } TcpStream; #define STREAM_BASE_OFFSET(stream) ((stream)->sb.region.stream_offset) @@ -181,7 +184,8 @@ enum TcpState { /** Flag to indicate that the session is handling asynchronous stream.*/ #define STREAMTCP_FLAG_ASYNC BIT_U32(6) /** Flag to indicate we're dealing with 4WHS: SYN, SYN, SYN/ACK, ACK - * (http://www.breakingpointsystems.com/community/blog/tcp-portals-the-three-way-handshake-is-a-lie) */ + * (http://www.breakingpointsystems.com/community/blog/tcp-portals-the-three-way-handshake-is-a-lie) + */ #define STREAMTCP_FLAG_4WHS BIT_U32(7) /** Flag to indicate that this session is possible trying to evade the detection * (http://www.packetstan.com/2010/06/recently-ive-been-on-campaign-to-make.html) */ @@ -216,56 +220,57 @@ enum TcpState { /** Flag to indicate that we have seen gap on the stream */ #define STREAMTCP_STREAM_FLAG_HAS_GAP BIT_U16(0) /** Flag to avoid stream reassembly/app layer inspection for the stream */ -#define STREAMTCP_STREAM_FLAG_NOREASSEMBLY BIT_U16(1) +#define STREAMTCP_STREAM_FLAG_NOREASSEMBLY BIT_U16(1) /** we received a keep alive */ -#define STREAMTCP_STREAM_FLAG_KEEPALIVE BIT_U16(2) +#define STREAMTCP_STREAM_FLAG_KEEPALIVE BIT_U16(2) /** Stream has reached it's reassembly depth, all further packets are ignored */ -#define STREAMTCP_STREAM_FLAG_DEPTH_REACHED BIT_U16(3) +#define STREAMTCP_STREAM_FLAG_DEPTH_REACHED BIT_U16(3) /** Trigger reassembly next time we need 'raw' */ -#define STREAMTCP_STREAM_FLAG_TRIGGER_RAW BIT_U16(4) +#define STREAMTCP_STREAM_FLAG_TRIGGER_RAW BIT_U16(4) /** Stream supports TIMESTAMP -- used to set ssn STREAMTCP_FLAG_TIMESTAMP * flag. */ -#define STREAMTCP_STREAM_FLAG_TIMESTAMP BIT_U16(5) +#define STREAMTCP_STREAM_FLAG_TIMESTAMP BIT_U16(5) /** Flag to indicate the zero value of timestamp */ -#define STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP BIT_U16(6) +#define STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP BIT_U16(6) /** App proto detection completed */ -#define STREAMTCP_STREAM_FLAG_APPPROTO_DETECTION_COMPLETED BIT_U16(7) +#define STREAMTCP_STREAM_FLAG_APPPROTO_DETECTION_COMPLETED BIT_U16(7) /** App proto detection skipped */ -#define STREAMTCP_STREAM_FLAG_APPPROTO_DETECTION_SKIPPED BIT_U16(8) +#define STREAMTCP_STREAM_FLAG_APPPROTO_DETECTION_SKIPPED BIT_U16(8) /** Raw reassembly disabled for new segments */ -#define STREAMTCP_STREAM_FLAG_NEW_RAW_DISABLED BIT_U16(9) +#define STREAMTCP_STREAM_FLAG_NEW_RAW_DISABLED BIT_U16(9) /** Raw reassembly disabled completely */ -#define STREAMTCP_STREAM_FLAG_DISABLE_RAW BIT_U16(10) +#define STREAMTCP_STREAM_FLAG_DISABLE_RAW BIT_U16(10) -#define STREAMTCP_STREAM_FLAG_RST_RECV BIT_U16(11) +#define STREAMTCP_STREAM_FLAG_RST_RECV BIT_U16(11) /** NOTE: flags field is 12 bits */ +#define PAWS_24DAYS 2073600 /**< 24 days in seconds */ - - -#define PAWS_24DAYS 2073600 /**< 24 days in seconds */ - -#define PKT_IS_IN_RIGHT_DIR(ssn, p) ((ssn)->flags & STREAMTCP_FLAG_MIDSTREAM_SYNACK ? \ - PKT_IS_TOSERVER(p) ? (p)->flowflags &= ~FLOW_PKT_TOSERVER \ - (p)->flowflags |= FLOW_PKT_TOCLIENT : (p)->flowflags &= ~FLOW_PKT_TOCLIENT \ - (p)->flowflags |= FLOW_PKT_TOSERVER : 0) +#define PKT_IS_IN_RIGHT_DIR(ssn, p) \ + ((ssn)->flags & STREAMTCP_FLAG_MIDSTREAM_SYNACK \ + ? PKT_IS_TOSERVER(p) ? (p)->flowflags &= ~FLOW_PKT_TOSERVER(p)->flowflags |= \ + FLOW_PKT_TOCLIENT \ + : (p)->flowflags &= ~FLOW_PKT_TOCLIENT(p)->flowflags |= \ + FLOW_PKT_TOSERVER \ + : 0) /* Macro's for comparing Sequence numbers * Page 810 from TCP/IP Illustrated, Volume 2. */ -#define SEQ_EQ(a,b) ((int32_t)((a) - (b)) == 0) -#define SEQ_LT(a,b) ((int32_t)((a) - (b)) < 0) -#define SEQ_LEQ(a,b) ((int32_t)((a) - (b)) <= 0) -#define SEQ_GT(a,b) ((int32_t)((a) - (b)) > 0) -#define SEQ_GEQ(a,b) ((int32_t)((a) - (b)) >= 0) +#define SEQ_EQ(a, b) ((int32_t)((a) - (b)) == 0) +#define SEQ_LT(a, b) ((int32_t)((a) - (b)) < 0) +#define SEQ_LEQ(a, b) ((int32_t)((a) - (b)) <= 0) +#define SEQ_GT(a, b) ((int32_t)((a) - (b)) > 0) +#define SEQ_GEQ(a, b) ((int32_t)((a) - (b)) >= 0) #define SEQ_MIN(a, b) (SEQ_LT((a), (b)) ? (a) : (b)) #define SEQ_MAX(a, b) (SEQ_GT((a), (b)) ? (a) : (b)) -#define STREAMTCP_SET_RA_BASE_SEQ(stream, seq) { \ - do { \ - (stream)->base_seq = (seq) + 1; \ - } while(0); \ -} +#define STREAMTCP_SET_RA_BASE_SEQ(stream, seq) \ + { \ + do { \ + (stream)->base_seq = (seq) + 1; \ + } while (0); \ + } #define StreamTcpSetEvent(p, e) \ { \ @@ -282,9 +287,9 @@ enum TcpState { typedef struct TcpSession_ { PoolThreadId pool_id; - uint8_t state:4; /**< tcp state from state enum */ - uint8_t pstate:4; /**< previous state */ - uint8_t queue_len; /**< length of queue list below */ + uint8_t state : 4; /**< tcp state from state enum */ + uint8_t pstate : 4; /**< previous state */ + uint8_t queue_len; /**< length of queue list below */ int8_t data_first_seen_dir; /** track all the tcp flags we've seen */ uint8_t tcp_packet_flags; @@ -293,18 +298,19 @@ typedef struct TcpSession_ { uint32_t reassembly_depth; /**< reassembly depth for the stream */ TcpStream server; TcpStream client; - TcpStateQueue *queue; /**< list of SYN/ACK candidates */ + TcpStateQueue *queue; /**< list of SYN/ACK candidates */ } TcpSession; -#define StreamTcpSetStreamFlagAppProtoDetectionCompleted(stream) \ +#define StreamTcpSetStreamFlagAppProtoDetectionCompleted(stream) \ ((stream)->flags |= STREAMTCP_STREAM_FLAG_APPPROTO_DETECTION_COMPLETED) -#define StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(stream) \ +#define StreamTcpIsSetStreamFlagAppProtoDetectionCompleted(stream) \ ((stream)->flags & STREAMTCP_STREAM_FLAG_APPPROTO_DETECTION_COMPLETED) -#define StreamTcpResetStreamFlagAppProtoDetectionCompleted(stream) \ +#define StreamTcpResetStreamFlagAppProtoDetectionCompleted(stream) \ ((stream)->flags &= ~STREAMTCP_STREAM_FLAG_APPPROTO_DETECTION_COMPLETED); -#define StreamTcpDisableAppLayerReassembly(ssn) do { \ - SCLogDebug("setting STREAMTCP_FLAG_APP_LAYER_DISABLED on ssn %p", ssn); \ - ((ssn)->flags |= STREAMTCP_FLAG_APP_LAYER_DISABLED); \ +#define StreamTcpDisableAppLayerReassembly(ssn) \ + do { \ + SCLogDebug("setting STREAMTCP_FLAG_APP_LAYER_DISABLED on ssn %p", ssn); \ + ((ssn)->flags |= STREAMTCP_FLAG_APP_LAYER_DISABLED); \ } while (0); #define STREAM_PKT_FLAG_RETRANSMISSION BIT_U16(0) diff --git a/src/stream-tcp-reassemble.c b/src/stream-tcp-reassemble.c index 51796be591a6..89578e4a1c66 100644 --- a/src/stream-tcp-reassemble.c +++ b/src/stream-tcp-reassemble.c @@ -113,8 +113,9 @@ void StreamTcpReassembleInitMemuse(void) */ void StreamTcpReassembleIncrMemuse(uint64_t size) { - (void) SC_ATOMIC_ADD(ra_memuse, size); - SCLogDebug("REASSEMBLY %"PRIu64", incr %"PRIu64, StreamTcpReassembleMemuseGlobalCounter(), size); + (void)SC_ATOMIC_ADD(ra_memuse, size); + SCLogDebug("REASSEMBLY %" PRIu64 ", incr %" PRIu64, StreamTcpReassembleMemuseGlobalCounter(), + size); return; } @@ -133,7 +134,7 @@ void StreamTcpReassembleDecrMemuse(uint64_t size) } #endif - (void) SC_ATOMIC_SUB(ra_memuse, size); + (void)SC_ATOMIC_SUB(ra_memuse, size); #ifdef UNITTESTS if (RunmodeIsUnittests()) { @@ -141,7 +142,8 @@ void StreamTcpReassembleDecrMemuse(uint64_t size) BUG_ON(postsize > presize); } #endif - SCLogDebug("REASSEMBLY %"PRIu64", decr %"PRIu64, StreamTcpReassembleMemuseGlobalCounter(), size); + SCLogDebug("REASSEMBLY %" PRIu64 ", decr %" PRIu64, StreamTcpReassembleMemuseGlobalCounter(), + size); return; } @@ -169,8 +171,7 @@ int StreamTcpReassembleCheckMemcap(uint64_t size) } #endif uint64_t memcapcopy = SC_ATOMIC_GET(stream_config.reassembly_memcap); - if (memcapcopy == 0 || - (uint64_t)((uint64_t)size + SC_ATOMIC_GET(ra_memuse)) <= memcapcopy) + if (memcapcopy == 0 || (uint64_t)((uint64_t)size + SC_ATOMIC_GET(ra_memuse)) <= memcapcopy) return 1; return 0; } @@ -266,7 +267,7 @@ static void *TcpSegmentPoolAlloc(void) TcpSegment *seg = NULL; - seg = SCMalloc(sizeof (TcpSegment)); + seg = SCMalloc(sizeof(TcpSegment)); if (unlikely(seg == NULL)) return NULL; @@ -308,14 +309,14 @@ static void *TcpSegmentPoolAlloc(void) static int TcpSegmentPoolInit(void *data, void *initdata) { - TcpSegment *seg = (TcpSegment *) data; + TcpSegment *seg = (TcpSegment *)data; TcpSegmentPcapHdrStorage *pcap_hdr; pcap_hdr = seg->pcap_hdr_storage; /* do this before the can bail, so TcpSegmentPoolCleanup * won't have uninitialized memory to consider. */ - memset(seg, 0, sizeof (TcpSegment)); + memset(seg, 0, sizeof(TcpSegment)); if (IsTcpSessionDumpingEnabled()) { uint32_t memuse = @@ -335,7 +336,7 @@ static int TcpSegmentPoolInit(void *data, void *initdata) SCMutexLock(&segment_pool_memuse_mutex); segment_pool_memuse += sizeof(TcpSegment); segment_pool_memcnt++; - SCLogDebug("segment_pool_memcnt %"PRIu64"", segment_pool_memcnt); + SCLogDebug("segment_pool_memcnt %" PRIu64 "", segment_pool_memcnt); SCMutexUnlock(&segment_pool_memuse_mutex); #endif @@ -366,7 +367,7 @@ static void TcpSegmentPoolCleanup(void *ptr) SCMutexLock(&segment_pool_memuse_mutex); segment_pool_memuse -= sizeof(TcpSegment); segment_pool_memcnt--; - SCLogDebug("segment_pool_memcnt %"PRIu64"", segment_pool_memcnt); + SCLogDebug("segment_pool_memcnt %" PRIu64 "", segment_pool_memcnt); SCMutexUnlock(&segment_pool_memuse_mutex); #endif } @@ -393,11 +394,10 @@ void StreamTcpSegmentReturntoPool(TcpSegment *seg) * * \param stream the stream to cleanup */ -void StreamTcpReturnStreamSegments (TcpStream *stream) +void StreamTcpReturnStreamSegments(TcpStream *stream) { TcpSegment *seg = NULL, *safe = NULL; - RB_FOREACH_SAFE(seg, TCPSEG, &stream->seg_tree, safe) - { + RB_FOREACH_SAFE (seg, TCPSEG, &stream->seg_tree, safe) { RB_REMOVE(TCPSEG, &stream->seg_tree, seg); StreamTcpSegmentReturntoPool(seg); } @@ -458,8 +458,8 @@ void StreamTcpDisableAppLayer(Flow *f) StreamTcpSetStreamFlagAppProtoDetectionCompleted(&ssn->server); StreamTcpDisableAppLayerReassembly(ssn); if (f->alparser) { - AppLayerParserStateSetFlag(f->alparser, - (APP_LAYER_PARSER_EOF_TS|APP_LAYER_PARSER_EOF_TC)); + AppLayerParserStateSetFlag( + f->alparser, (APP_LAYER_PARSER_EOF_TS | APP_LAYER_PARSER_EOF_TC)); } } @@ -535,8 +535,7 @@ int StreamTcpReassembleInit(bool quiet) #ifdef DEBUG SCMutexInit(&segment_pool_memuse_mutex, NULL); #endif - StatsRegisterGlobalCounter("tcp.reassembly_memuse", - StreamTcpReassembleMemuseGlobalCounter); + StatsRegisterGlobalCounter("tcp.reassembly_memuse", StreamTcpReassembleMemuseGlobalCounter); return 0; } @@ -570,22 +569,17 @@ TcpReassemblyThreadCtx *StreamTcpReassembleInitThreadCtx(ThreadVars *tv) SCMutexLock(&segment_thread_pool_mutex); if (segment_thread_pool == NULL) { segment_thread_pool = PoolThreadInit(1, /* thread */ - 0, /* unlimited */ - stream_config.prealloc_segments, - sizeof(TcpSegment), - TcpSegmentPoolAlloc, - TcpSegmentPoolInit, NULL, - TcpSegmentPoolCleanup, NULL); + 0, /* unlimited */ + stream_config.prealloc_segments, sizeof(TcpSegment), TcpSegmentPoolAlloc, + TcpSegmentPoolInit, NULL, TcpSegmentPoolCleanup, NULL); ra_ctx->segment_thread_pool_id = 0; SCLogDebug("pool size %d, thread segment_thread_pool_id %d", - PoolThreadSize(segment_thread_pool), - ra_ctx->segment_thread_pool_id); + PoolThreadSize(segment_thread_pool), ra_ctx->segment_thread_pool_id); } else { /* grow segment_thread_pool until we have an element for our thread id */ ra_ctx->segment_thread_pool_id = PoolThreadExpand(segment_thread_pool); SCLogDebug("pool size %d, thread segment_thread_pool_id %d", - PoolThreadSize(segment_thread_pool), - ra_ctx->segment_thread_pool_id); + PoolThreadSize(segment_thread_pool), ra_ctx->segment_thread_pool_id); } SCMutexUnlock(&segment_thread_pool_mutex); if (ra_ctx->segment_thread_pool_id < 0 || segment_thread_pool == NULL) { @@ -645,8 +639,8 @@ int StreamTcpReassembleDepthReached(Packet *p) * * \retval size Part of the size that fits in the depth, 0 if none */ -static uint32_t StreamTcpReassembleCheckDepth(TcpSession *ssn, TcpStream *stream, - uint32_t seq, uint32_t size) +static uint32_t StreamTcpReassembleCheckDepth( + TcpSession *ssn, TcpStream *stream, uint32_t seq, uint32_t size) { SCEnter(); @@ -663,9 +657,9 @@ static uint32_t StreamTcpReassembleCheckDepth(TcpSession *ssn, TcpStream *stream uint64_t seg_depth; if (SEQ_GT(stream->base_seq, seq)) { - if (SEQ_LEQ(seq+size, stream->base_seq)) { + if (SEQ_LEQ(seq + size, stream->base_seq)) { SCLogDebug("segment entirely before base_seq, weird: base %u, seq %u, re %u", - stream->base_seq, seq, seq+size); + stream->base_seq, seq, seq + size); SCReturnUInt(0); } @@ -678,9 +672,8 @@ static uint32_t StreamTcpReassembleCheckDepth(TcpSession *ssn, TcpStream *stream * checking and just reject the rest of the packets including * retransmissions. Saves us the hassle of dealing with sequence * wraps as well */ - SCLogDebug("seq + size %u, base %u, seg_depth %"PRIu64" limit %u", (seq + size), - stream->base_seq, seg_depth, - ssn->reassembly_depth); + SCLogDebug("seq + size %u, base %u, seg_depth %" PRIu64 " limit %u", (seq + size), + stream->base_seq, seg_depth, ssn->reassembly_depth); if (seg_depth > (uint64_t)ssn->reassembly_depth) { SCLogDebug("STREAMTCP_STREAM_FLAG_DEPTH_REACHED"); @@ -688,7 +681,7 @@ static uint32_t StreamTcpReassembleCheckDepth(TcpSession *ssn, TcpStream *stream SCReturnUInt(0); } SCLogDebug("NOT STREAMTCP_STREAM_FLAG_DEPTH_REACHED"); - SCLogDebug("%"PRIu64" <= %u", seg_depth, ssn->reassembly_depth); + SCLogDebug("%" PRIu64 " <= %u", seg_depth, ssn->reassembly_depth); #if 0 SCLogDebug("full depth not yet reached: %"PRIu64" <= %"PRIu32, (stream->base_seq_offset + stream->base_seq + size), @@ -697,7 +690,7 @@ static uint32_t StreamTcpReassembleCheckDepth(TcpSession *ssn, TcpStream *stream if (SEQ_GEQ(seq, stream->isn) && SEQ_LT(seq, (stream->isn + ssn->reassembly_depth))) { /* packet (partly?) fits the depth window */ - if (SEQ_LEQ((seq + size),(stream->isn + 1 + ssn->reassembly_depth))) { + if (SEQ_LEQ((seq + size), (stream->isn + 1 + ssn->reassembly_depth))) { /* complete fit */ SCReturnUInt(size); } else { @@ -739,7 +732,7 @@ uint32_t StreamDataAvailableForProtoDetect(TcpStream *stream) * */ int StreamTcpReassembleHandleSegmentHandleData(ThreadVars *tv, TcpReassemblyThreadCtx *ra_ctx, - TcpSession *ssn, TcpStream *stream, Packet *p) + TcpSession *ssn, TcpStream *stream, Packet *p) { SCEnter(); @@ -757,7 +750,7 @@ int StreamTcpReassembleHandleSegmentHandleData(ThreadVars *tv, TcpReassemblyThre } if ((ssn->flags & STREAMTCP_FLAG_APP_LAYER_DISABLED) && - (stream->flags & STREAMTCP_STREAM_FLAG_NEW_RAW_DISABLED)) { + (stream->flags & STREAMTCP_STREAM_FLAG_NEW_RAW_DISABLED)) { SCLogDebug("ssn %p: both app and raw reassembly disabled, not reassembling", ssn); SCReturnInt(0); } @@ -765,7 +758,7 @@ int StreamTcpReassembleHandleSegmentHandleData(ThreadVars *tv, TcpReassemblyThre /* If we have reached the defined depth for either of the stream, then stop reassembling the TCP session */ uint32_t size = StreamTcpReassembleCheckDepth(ssn, stream, TCP_GET_SEQ(p), p->payload_len); - SCLogDebug("ssn %p: check depth returned %"PRIu32, ssn, size); + SCLogDebug("ssn %p: check depth returned %" PRIu32, ssn, size); if (stream->flags & STREAMTCP_STREAM_FLAG_DEPTH_REACHED) { StreamTcpSetEvent(p, STREAM_REASSEMBLY_DEPTH_REACHED); @@ -800,10 +793,9 @@ int StreamTcpReassembleHandleSegmentHandleData(ThreadVars *tv, TcpReassemblyThre /* proto detection skipped, but now we do get data. Set event. */ if (RB_EMPTY(&stream->seg_tree) && - stream->flags & STREAMTCP_STREAM_FLAG_APPPROTO_DETECTION_SKIPPED) { + stream->flags & STREAMTCP_STREAM_FLAG_APPPROTO_DETECTION_SKIPPED) { - AppLayerDecoderEventsSetEventRaw(&p->app_layer_events, - APPLAYER_PROTO_DETECTION_SKIPPED); + AppLayerDecoderEventsSetEventRaw(&p->app_layer_events, APPLAYER_PROTO_DETECTION_SKIPPED); } int r = StreamTcpReassembleInsertSegment( @@ -818,8 +810,7 @@ int StreamTcpReassembleHandleSegmentHandleData(ThreadVars *tv, TcpReassemblyThre SCReturnInt(0); } -static uint8_t StreamGetAppLayerFlags(TcpSession *ssn, TcpStream *stream, - Packet *p) +static uint8_t StreamGetAppLayerFlags(TcpSession *ssn, TcpStream *stream, Packet *p) { uint8_t flag = 0; @@ -856,28 +847,27 @@ static uint8_t StreamGetAppLayerFlags(TcpSession *ssn, TcpStream *stream, * \retval 0 don't reassemble yet * \retval 1 do reassemble */ -static int StreamTcpReassembleRawCheckLimit(const TcpSession *ssn, - const TcpStream *stream, const Packet *p) +static int StreamTcpReassembleRawCheckLimit( + const TcpSession *ssn, const TcpStream *stream, const Packet *p) { SCEnter(); /* if any of these flags is set we always inspect immediately */ -#define STREAMTCP_STREAM_FLAG_FLUSH_FLAGS \ - ( STREAMTCP_STREAM_FLAG_DEPTH_REACHED \ - | STREAMTCP_STREAM_FLAG_TRIGGER_RAW \ - | STREAMTCP_STREAM_FLAG_NEW_RAW_DISABLED) +#define STREAMTCP_STREAM_FLAG_FLUSH_FLAGS \ + (STREAMTCP_STREAM_FLAG_DEPTH_REACHED | STREAMTCP_STREAM_FLAG_TRIGGER_RAW | \ + STREAMTCP_STREAM_FLAG_NEW_RAW_DISABLED) if (stream->flags & STREAMTCP_STREAM_FLAG_FLUSH_FLAGS) { if (stream->flags & STREAMTCP_STREAM_FLAG_DEPTH_REACHED) { SCLogDebug("reassembling now as STREAMTCP_STREAM_FLAG_DEPTH_REACHED " - "is set, so not expecting any new data segments"); + "is set, so not expecting any new data segments"); } if (stream->flags & STREAMTCP_STREAM_FLAG_TRIGGER_RAW) { SCLogDebug("reassembling now as STREAMTCP_STREAM_FLAG_TRIGGER_RAW is set"); } if (stream->flags & STREAMTCP_STREAM_FLAG_NEW_RAW_DISABLED) { SCLogDebug("reassembling now as STREAMTCP_STREAM_FLAG_NEW_RAW_DISABLED is set, " - "so no new segments will be considered"); + "so no new segments will be considered"); } SCReturnInt(1); } @@ -982,7 +972,8 @@ static uint64_t GetStreamSize(TcpStream *stream) SCLogDebug("stream_offset %" PRIu64, stream->sb.region.stream_offset); TcpSegment *seg; - RB_FOREACH(seg, TCPSEG, &stream->seg_tree) { + RB_FOREACH(seg, TCPSEG, &stream->seg_tree) + { const uint64_t seg_abs = STREAM_BASE_OFFSET(stream) + (uint64_t)(seg->seq - stream->base_seq); if (last_re != 0 && last_re < seg_abs) { @@ -1015,7 +1006,7 @@ static uint64_t GetStreamSize(TcpStream *stream) size += (uint64_t)TCP_SEG_LEN(seg); } - SCLogDebug("size %"PRIu64", cnt %"PRIu32, size, cnt); + SCLogDebug("size %" PRIu64 ", cnt %" PRIu32, size, cnt); return size; } return (uint64_t)0; @@ -1028,9 +1019,9 @@ static void GetSessionSize(TcpSession *ssn, Packet *p) size = GetStreamSize(&ssn->client); size += GetStreamSize(&ssn->server); - //if (size > 900000) + // if (size > 900000) // SCLogInfo("size %"PRIu64", packet %"PRIu64, size, p->pcap_cnt); - SCLogDebug("size %"PRIu64", packet %"PRIu64, size, p->pcap_cnt); + SCLogDebug("size %" PRIu64 ", packet %" PRIu64, size, p->pcap_cnt); } } #endif @@ -1041,7 +1032,7 @@ static StreamingBufferBlock *GetBlock(const StreamingBuffer *sb, const uint64_t if (blk == NULL) return NULL; - for ( ; blk != NULL; blk = SBB_RB_NEXT(blk)) { + for (; blk != NULL; blk = SBB_RB_NEXT(blk)) { if (blk->offset >= offset) return blk; else if ((blk->offset + blk->len) > offset) { @@ -1103,18 +1094,18 @@ static bool GetAppBuffer(const TcpStream *stream, const uint8_t **data, uint32_t gap_ahead = check_for_gap && GapAhead(stream, blk); - /* block past out offset */ + /* block past out offset */ } else if (blk->offset > offset) { - SCLogDebug("gap, want data at offset %"PRIu64", " - "got data at %"PRIu64". GAP of size %"PRIu64, + SCLogDebug("gap, want data at offset %" PRIu64 ", " + "got data at %" PRIu64 ". GAP of size %" PRIu64, offset, blk->offset, blk->offset - offset); *data = NULL; *data_len = blk->offset - offset; - /* block starts before offset, but ends after */ + /* block starts before offset, but ends after */ } else if (offset > blk->offset && offset <= (blk->offset + blk->len)) { - SCLogDebug("get data from offset %"PRIu64". SBB %"PRIu64"/%u", - offset, blk->offset, blk->len); + SCLogDebug("get data from offset %" PRIu64 ". SBB %" PRIu64 "/%u", offset, blk->offset, + blk->len); StreamingBufferSBBGetDataAtOffset(&stream->sb, blk, data, data_len, offset); SCLogDebug("data %p, data_len %u", *data, *data_len); @@ -1174,15 +1165,14 @@ static inline bool CheckGap(TcpSession *ssn, TcpStream *stream, Packet *p) p->pcap_cnt, last_ack_abs, app_progress); return true; } - SCLogDebug("packet %"PRIu64": no GAP. " - "last_ack_abs %"PRIu64" <= app_progress %"PRIu64, + SCLogDebug("packet %" PRIu64 ": no GAP. " + "last_ack_abs %" PRIu64 " <= app_progress %" PRIu64, p->pcap_cnt, last_ack_abs, app_progress); return false; } -static inline uint32_t AdjustToAcked(const Packet *p, - const TcpSession *ssn, const TcpStream *stream, - const uint64_t app_progress, const uint32_t data_len) +static inline uint32_t AdjustToAcked(const Packet *p, const TcpSession *ssn, + const TcpStream *stream, const uint64_t app_progress, const uint32_t data_len) { uint32_t adjusted = data_len; @@ -1204,7 +1194,8 @@ static inline uint32_t AdjustToAcked(const Packet *p, adjusted = last_ack_abs - app_progress; BUG_ON(adjusted > check); SCLogDebug("data len adjusted to %u to make sure only ACK'd " - "data is considered", adjusted); + "data is considered", + adjusted); } } } @@ -1216,14 +1207,12 @@ static inline uint32_t AdjustToAcked(const Packet *p, * \param stream pointer to pointer as app-layer can switch flow dir * \retval 0 success */ -static int ReassembleUpdateAppLayer (ThreadVars *tv, - TcpReassemblyThreadCtx *ra_ctx, - TcpSession *ssn, TcpStream **stream, - Packet *p, enum StreamUpdateDir dir) +static int ReassembleUpdateAppLayer(ThreadVars *tv, TcpReassemblyThreadCtx *ra_ctx, TcpSession *ssn, + TcpStream **stream, Packet *p, enum StreamUpdateDir dir) { uint64_t app_progress = STREAM_APP_PROGRESS(*stream); - SCLogDebug("app progress %"PRIu64, app_progress); + SCLogDebug("app progress %" PRIu64, app_progress); #ifdef DEBUG uint64_t last_ack_abs = GetAbsLastAck(*stream); SCLogDebug("last_ack %u (abs %" PRIu64 "), base_seq %u", (*stream)->last_ack, last_ack_abs, @@ -1293,13 +1282,13 @@ static int ReassembleUpdateAppLayer (ThreadVars *tv, mydata = NULL; mydata_len = 0; - SCLogDebug("%"PRIu64" got %p/%u", p->pcap_cnt, mydata, mydata_len); + SCLogDebug("%" PRIu64 " got %p/%u", p->pcap_cnt, mydata, mydata_len); break; } DEBUG_VALIDATE_BUG_ON(mydata == NULL && mydata_len > 0); - SCLogDebug("stream %p data in buffer %p of len %u and offset %"PRIu64, - *stream, &(*stream)->sb, mydata_len, app_progress); + SCLogDebug("stream %p data in buffer %p of len %u and offset %" PRIu64, *stream, + &(*stream)->sb, mydata_len, app_progress); if ((p->flags & PKT_PSEUDO_STREAM_END) == 0 || ssn->state < TCP_CLOSED) { SCLogDebug("GAP?2"); @@ -1350,16 +1339,15 @@ static int ReassembleUpdateAppLayer (ThreadVars *tv, * any issues, since processing of each stream is independent of the * other stream. */ -int StreamTcpReassembleAppLayer (ThreadVars *tv, TcpReassemblyThreadCtx *ra_ctx, - TcpSession *ssn, TcpStream *stream, - Packet *p, enum StreamUpdateDir dir) +int StreamTcpReassembleAppLayer(ThreadVars *tv, TcpReassemblyThreadCtx *ra_ctx, TcpSession *ssn, + TcpStream *stream, Packet *p, enum StreamUpdateDir dir) { SCEnter(); /* this function can be directly called by app layer protocol * detection. */ if ((ssn->flags & STREAMTCP_FLAG_APP_LAYER_DISABLED) || - (stream->flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY)) { + (stream->flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY)) { SCLogDebug("stream no reassembly flag set or app-layer disabled."); SCReturnInt(0); } @@ -1370,8 +1358,7 @@ int StreamTcpReassembleAppLayer (ThreadVars *tv, TcpReassemblyThreadCtx *ra_ctx, #endif /* if no segments are in the list or all are already processed, * and state is beyond established, we send an empty msg */ - if (!STREAM_HAS_SEEN_DATA(stream) || STREAM_RIGHT_EDGE(stream) <= STREAM_APP_PROGRESS(stream)) - { + if (!STREAM_HAS_SEEN_DATA(stream) || STREAM_RIGHT_EDGE(stream) <= STREAM_APP_PROGRESS(stream)) { /* send an empty EOF msg if we have no segments but TCP state * is beyond ESTABLISHED */ if (ssn->state >= TCP_CLOSING || (p->flags & PKT_PSEUDO_STREAM_END)) { @@ -1398,7 +1385,7 @@ static int GetRawBuffer(TcpStream *stream, const uint8_t **data, uint32_t *data_ const uint8_t *mydata; uint32_t mydata_len; if (RB_EMPTY(&stream->sb.sbb_tree)) { - SCLogDebug("getting one blob for offset %"PRIu64, offset); + SCLogDebug("getting one blob for offset %" PRIu64, offset); uint64_t roffset = offset; if (offset) @@ -1411,8 +1398,8 @@ static int GetRawBuffer(TcpStream *stream, const uint8_t **data, uint32_t *data_ *data_len = mydata_len; *data_offset = roffset; } else { - SCLogDebug("multiblob %s. Want offset %"PRIu64, - *iter == NULL ? "starting" : "continuing", offset); + SCLogDebug("multiblob %s. Want offset %" PRIu64, *iter == NULL ? "starting" : "continuing", + offset); if (*iter == NULL) { StreamingBufferBlock key = { .offset = offset, .len = 0 }; *iter = SBB_RB_FIND_INCLUSIVE(&stream->sb.sbb_tree, &key); @@ -1425,7 +1412,8 @@ static int GetRawBuffer(TcpStream *stream, const uint8_t **data, uint32_t *data_ *data_offset = 0; return 0; } - SCLogDebug("getting multiple blobs. Iter %p, %"PRIu64"/%u", *iter, (*iter)->offset, (*iter)->len); + SCLogDebug("getting multiple blobs. Iter %p, %" PRIu64 "/%u", *iter, (*iter)->offset, + (*iter)->len); StreamingBufferSBBGetData(&stream->sb, (*iter), &mydata, &mydata_len); SCLogDebug("mydata %p", mydata); @@ -1475,8 +1463,7 @@ bool StreamReassembleRawHasDataReady(TcpSession *ssn, Packet *p) return false; } - if (stream->flags & (STREAMTCP_STREAM_FLAG_NOREASSEMBLY| - STREAMTCP_STREAM_FLAG_DISABLE_RAW)) + if (stream->flags & (STREAMTCP_STREAM_FLAG_NOREASSEMBLY | STREAMTCP_STREAM_FLAG_DISABLE_RAW)) return false; if (!StreamTcpInlineMode()) { @@ -1536,9 +1523,10 @@ void StreamReassembleRawUpdateProgress(TcpSession *ssn, Packet *p, const uint64_ stream->flags &= ~STREAMTCP_STREAM_FLAG_TRIGGER_RAW; } else { - SCLogDebug("p->pcap_cnt %"PRIu64": progress %"PRIu64" app %"PRIu64" raw %"PRIu64" tcp win %"PRIu32, - p->pcap_cnt, progress, STREAM_APP_PROGRESS(stream), - STREAM_RAW_PROGRESS(stream), stream->window); + SCLogDebug("p->pcap_cnt %" PRIu64 ": progress %" PRIu64 " app %" PRIu64 " raw %" PRIu64 + " tcp win %" PRIu32, + p->pcap_cnt, progress, STREAM_APP_PROGRESS(stream), STREAM_RAW_PROGRESS(stream), + stream->window); } /* if we were told to accept no more raw data, we can mark raw as @@ -1546,27 +1534,28 @@ void StreamReassembleRawUpdateProgress(TcpSession *ssn, Packet *p, const uint64_ if (stream->flags & STREAMTCP_STREAM_FLAG_NEW_RAW_DISABLED) { stream->flags |= STREAMTCP_STREAM_FLAG_DISABLE_RAW; SCLogDebug("ssn %p: STREAMTCP_STREAM_FLAG_NEW_RAW_DISABLED set, " - "now that detect ran also set STREAMTCP_STREAM_FLAG_DISABLE_RAW", ssn); + "now that detect ran also set STREAMTCP_STREAM_FLAG_DISABLE_RAW", + ssn); } - SCLogDebug("stream raw progress now %"PRIu64, STREAM_RAW_PROGRESS(stream)); + SCLogDebug("stream raw progress now %" PRIu64, STREAM_RAW_PROGRESS(stream)); } /** \internal - * \brief get a buffer around the current packet and run the callback on it - * - * The inline/IPS scanning method takes the current payload and wraps it in - * data from other segments. - * - * How much data is inspected is controlled by the available data, chunk_size - * and the payload size of the packet. - * - * Large packets: if payload size is close to the chunk_size, where close is - * defined as more than 67% of the chunk_size, a larger chunk_size will be - * used: payload_len + 33% of the chunk_size. - * If the payload size if equal to or bigger than the chunk_size, we use - * payload len + 33% of the chunk size. - */ + * \brief get a buffer around the current packet and run the callback on it + * + * The inline/IPS scanning method takes the current payload and wraps it in + * data from other segments. + * + * How much data is inspected is controlled by the available data, chunk_size + * and the payload size of the packet. + * + * Large packets: if payload size is close to the chunk_size, where close is + * defined as more than 67% of the chunk_size, a larger chunk_size will be + * used: payload_len + 33% of the chunk_size. + * If the payload size if equal to or bigger than the chunk_size, we use + * payload len + 33% of the chunk size. + */ static int StreamReassembleRawInline(TcpSession *ssn, const Packet *p, StreamReassembleRawFunc Callback, void *cb_data, uint64_t *progress_out) { @@ -1581,29 +1570,27 @@ static int StreamReassembleRawInline(TcpSession *ssn, const Packet *p, } if (p->payload_len == 0 || (p->flags & PKT_STREAM_ADD) == 0 || - (stream->flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY)) - { + (stream->flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY)) { *progress_out = STREAM_RAW_PROGRESS(stream); return 0; } - uint32_t chunk_size = PKT_IS_TOSERVER(p) ? - stream_config.reassembly_toserver_chunk_size : - stream_config.reassembly_toclient_chunk_size; + uint32_t chunk_size = PKT_IS_TOSERVER(p) ? stream_config.reassembly_toserver_chunk_size + : stream_config.reassembly_toclient_chunk_size; if (chunk_size <= p->payload_len) { chunk_size = p->payload_len + (chunk_size / 3); - SCLogDebug("packet payload len %u, so chunk_size adjusted to %u", - p->payload_len, chunk_size); - } else if (((chunk_size / 3 ) * 2) < p->payload_len) { + SCLogDebug( + "packet payload len %u, so chunk_size adjusted to %u", p->payload_len, chunk_size); + } else if (((chunk_size / 3) * 2) < p->payload_len) { chunk_size = p->payload_len + ((chunk_size / 3)); - SCLogDebug("packet payload len %u, so chunk_size adjusted to %u", - p->payload_len, chunk_size); + SCLogDebug( + "packet payload len %u, so chunk_size adjusted to %u", p->payload_len, chunk_size); } uint64_t packet_leftedge_abs = STREAM_BASE_OFFSET(stream) + (TCP_GET_SEQ(p) - stream->base_seq); uint64_t packet_rightedge_abs = packet_leftedge_abs + p->payload_len; - SCLogDebug("packet_leftedge_abs %"PRIu64", rightedge %"PRIu64, - packet_leftedge_abs, packet_rightedge_abs); + SCLogDebug("packet_leftedge_abs %" PRIu64 ", rightedge %" PRIu64, packet_leftedge_abs, + packet_rightedge_abs); const uint8_t *mydata = NULL; uint32_t mydata_len = 0; @@ -1617,12 +1604,12 @@ static int StreamReassembleRawInline(TcpSession *ssn, const Packet *p, return_progress = true; } else { - SCLogDebug("finding our SBB from offset %"PRIu64, packet_leftedge_abs); + SCLogDebug("finding our SBB from offset %" PRIu64, packet_leftedge_abs); /* find our block */ StreamingBufferBlock key = { .offset = packet_leftedge_abs, .len = p->payload_len }; StreamingBufferBlock *sbb = SBB_RB_FIND_INCLUSIVE(&stream->sb.sbb_tree, &key); if (sbb) { - SCLogDebug("found %p offset %"PRIu64" len %u", sbb, sbb->offset, sbb->len); + SCLogDebug("found %p offset %" PRIu64 " len %u", sbb, sbb->offset, sbb->len); StreamingBufferSBBGetData(&stream->sb, sbb, &mydata, &mydata_len); mydata_offset = sbb->offset; } @@ -1630,17 +1617,17 @@ static int StreamReassembleRawInline(TcpSession *ssn, const Packet *p, /* this can only happen if the segment insert of our current 'p' failed */ uint64_t mydata_rightedge_abs = mydata_offset + mydata_len; - if ((mydata == NULL || mydata_len == 0) || /* no data */ - (mydata_offset >= packet_rightedge_abs || /* data all to the right */ - packet_leftedge_abs >= mydata_rightedge_abs) || /* data all to the left */ - (packet_leftedge_abs < mydata_offset || /* data missing at the start */ - packet_rightedge_abs > mydata_rightedge_abs)) /* data missing at the end */ + if ((mydata == NULL || mydata_len == 0) || /* no data */ + (mydata_offset >= packet_rightedge_abs || /* data all to the right */ + packet_leftedge_abs >= mydata_rightedge_abs) || /* data all to the left */ + (packet_leftedge_abs < mydata_offset || /* data missing at the start */ + packet_rightedge_abs > mydata_rightedge_abs)) /* data missing at the end */ { /* no data, or data is incomplete or wrong: use packet data */ mydata = p->payload; mydata_len = p->payload_len; mydata_offset = packet_leftedge_abs; - //mydata_rightedge_abs = packet_rightedge_abs; + // mydata_rightedge_abs = packet_rightedge_abs; } else { /* adjust buffer to match chunk_size */ SCLogDebug("chunk_size %u mydata_len %u", chunk_size, mydata_len); @@ -1708,7 +1695,7 @@ static int StreamReassembleRawInline(TcpSession *ssn, const Packet *p, * our block. */ const uint64_t last_ack_abs = GetAbsLastAck(stream); - SCLogDebug("last_ack_abs %"PRIu64, last_ack_abs); + SCLogDebug("last_ack_abs %" PRIu64, last_ack_abs); if (STREAM_RAW_PROGRESS(stream) < last_ack_abs) { if (mydata_offset > last_ack_abs) { @@ -1778,11 +1765,11 @@ static int StreamReassembleRawDo(TcpSession *ssn, TcpStream *stream, SCLogDebug("no data"); break; } - //PrintRawDataFp(stdout, mydata, mydata_len); + // PrintRawDataFp(stdout, mydata, mydata_len); - SCLogDebug("raw progress %"PRIu64, progress); - SCLogDebug("stream %p data in buffer %p of len %u and offset %"PRIu64, - stream, &stream->sb, mydata_len, progress); + SCLogDebug("raw progress %" PRIu64, progress); + SCLogDebug("stream %p data in buffer %p of len %u and offset %" PRIu64, stream, &stream->sb, + mydata_len, progress); if (eof) { // inspect all remaining data, ack'd or not @@ -1802,7 +1789,8 @@ static int StreamReassembleRawDo(TcpSession *ssn, TcpStream *stream, mydata_len = re - progress; BUG_ON(check < mydata_len); SCLogDebug("data len adjusted to %u to make sure only ACK'd " - "data is considered", mydata_len); + "data is considered", + mydata_len); } } if (mydata_len == 0) @@ -1815,22 +1803,25 @@ static int StreamReassembleRawDo(TcpSession *ssn, TcpStream *stream, BUG_ON(r < 0); if (mydata_offset == progress) { - SCLogDebug("progress %"PRIu64" increasing with data len %u to %"PRIu64, - progress, mydata_len, progress_in + mydata_len); + SCLogDebug("progress %" PRIu64 " increasing with data len %u to %" PRIu64, progress, + mydata_len, progress_in + mydata_len); progress += mydata_len; - SCLogDebug("raw progress now %"PRIu64, progress); + SCLogDebug("raw progress now %" PRIu64, progress); - /* data is beyond the progress we'd like, and before last ack. Gap. */ + /* data is beyond the progress we'd like, and before last ack. Gap. */ } else if (mydata_offset > progress && mydata_offset < re) { - SCLogDebug("GAP: data is missing from %"PRIu64" (%u bytes), setting to first data we have: %"PRIu64, progress, (uint32_t)(mydata_offset - progress), mydata_offset); + SCLogDebug("GAP: data is missing from %" PRIu64 + " (%u bytes), setting to first data we have: %" PRIu64, + progress, (uint32_t)(mydata_offset - progress), mydata_offset); SCLogDebug("re %" PRIu64, re); progress = mydata_offset; - SCLogDebug("raw progress now %"PRIu64, progress); + SCLogDebug("raw progress now %" PRIu64, progress); } else { SCLogDebug("not increasing progress, data gap => mydata_offset " - "%"PRIu64" != progress %"PRIu64, mydata_offset, progress); + "%" PRIu64 " != progress %" PRIu64, + mydata_offset, progress); } if (iter == NULL || r == 1) @@ -1853,9 +1844,8 @@ int StreamReassembleForFrame(TcpSession *ssn, TcpStream *stream, StreamReassembl ssn, stream, Callback, cb_data, offset, app_progress, &unused, eof, false); } -int StreamReassembleRaw(TcpSession *ssn, const Packet *p, - StreamReassembleRawFunc Callback, void *cb_data, - uint64_t *progress_out, bool respect_inspect_depth) +int StreamReassembleRaw(TcpSession *ssn, const Packet *p, StreamReassembleRawFunc Callback, + void *cb_data, uint64_t *progress_out, bool respect_inspect_depth) { /* handle inline separately as the logic is very different */ if (StreamTcpInlineMode()) { @@ -1869,9 +1859,9 @@ int StreamReassembleRaw(TcpSession *ssn, const Packet *p, stream = &ssn->server; } - if ((stream->flags & (STREAMTCP_STREAM_FLAG_NOREASSEMBLY|STREAMTCP_STREAM_FLAG_DISABLE_RAW)) || - StreamTcpReassembleRawCheckLimit(ssn, stream, p) == 0) - { + if ((stream->flags & + (STREAMTCP_STREAM_FLAG_NOREASSEMBLY | STREAMTCP_STREAM_FLAG_DISABLE_RAW)) || + StreamTcpReassembleRawCheckLimit(ssn, stream, p) == 0) { *progress_out = STREAM_RAW_PROGRESS(stream); return 0; } @@ -1918,10 +1908,8 @@ int StreamReassembleRaw(TcpSession *ssn, const Packet *p, progress_out, (p->flags & PKT_PSEUDO_STREAM_END), respect_inspect_depth); } -int StreamReassembleLog(TcpSession *ssn, TcpStream *stream, - StreamReassembleRawFunc Callback, void *cb_data, - uint64_t progress_in, - uint64_t *progress_out, bool eof) +int StreamReassembleLog(TcpSession *ssn, TcpStream *stream, StreamReassembleRawFunc Callback, + void *cb_data, uint64_t progress_in, uint64_t *progress_out, bool eof) { if (stream->flags & (STREAMTCP_STREAM_FLAG_NOREASSEMBLY)) return 0; @@ -1939,8 +1927,8 @@ int StreamReassembleLog(TcpSession *ssn, TcpStream *stream, * * \retval r 0 on success, -1 on error */ -static int StreamTcpReassembleHandleSegmentUpdateACK (ThreadVars *tv, - TcpReassemblyThreadCtx *ra_ctx, TcpSession *ssn, TcpStream *stream, Packet *p) +static int StreamTcpReassembleHandleSegmentUpdateACK(ThreadVars *tv, TcpReassemblyThreadCtx *ra_ctx, + TcpSession *ssn, TcpStream *stream, Packet *p) { SCEnter(); @@ -1957,8 +1945,8 @@ int StreamTcpReassembleHandleSegment(ThreadVars *tv, TcpReassemblyThreadCtx *ra_ DEBUG_VALIDATE_BUG_ON(p->tcph == NULL); - SCLogDebug("ssn %p, stream %p, p %p, p->payload_len %"PRIu16"", - ssn, stream, p, p->payload_len); + SCLogDebug( + "ssn %p, stream %p, p %p, p->payload_len %" PRIu16 "", ssn, stream, p, p->payload_len); /* default IDS: update opposing side (triggered by ACK) */ enum StreamUpdateDir dir = UPDATE_DIR_OPPOSING; @@ -2019,7 +2007,7 @@ int StreamTcpReassembleHandleSegment(ThreadVars *tv, TcpReassemblyThreadCtx *ra_ SCReturnInt(-1); } - SCLogDebug("packet %"PRIu64" set PKT_STREAM_ADD", p->pcap_cnt); + SCLogDebug("packet %" PRIu64 " set PKT_STREAM_ADD", p->pcap_cnt); p->flags |= PKT_STREAM_ADD; } else { SCLogDebug("ssn %p / stream %p: not calling StreamTcpReassembleHandleSegmentHandleData:" @@ -2034,13 +2022,12 @@ int StreamTcpReassembleHandleSegment(ThreadVars *tv, TcpReassemblyThreadCtx *ra_ * logic, to inform the applayer no more data in this direction is * to be expected. */ if ((stream->flags & - (STREAMTCP_STREAM_FLAG_DEPTH_REACHED|STREAMTCP_STREAM_FLAG_NOREASSEMBLY)) == - STREAMTCP_STREAM_FLAG_DEPTH_REACHED) - { + (STREAMTCP_STREAM_FLAG_DEPTH_REACHED | STREAMTCP_STREAM_FLAG_NOREASSEMBLY)) == + STREAMTCP_STREAM_FLAG_DEPTH_REACHED) { SCLogDebug("STREAMTCP_STREAM_FLAG_DEPTH_REACHED, truncate applayer"); if (dir != UPDATE_DIR_PACKET) { SCLogDebug("override: direction now UPDATE_DIR_PACKET so we " - "can trigger Truncate"); + "can trigger Truncate"); dir = UPDATE_DIR_PACKET; } } @@ -2049,8 +2036,8 @@ int StreamTcpReassembleHandleSegment(ThreadVars *tv, TcpReassemblyThreadCtx *ra_ * functions to handle EOF */ if (dir == UPDATE_DIR_PACKET || dir == UPDATE_DIR_BOTH) { SCLogDebug("inline (%s) or PKT_PSEUDO_STREAM_END (%s)", - StreamTcpInlineMode()?"true":"false", - (p->flags & PKT_PSEUDO_STREAM_END) ?"true":"false"); + StreamTcpInlineMode() ? "true" : "false", + (p->flags & PKT_PSEUDO_STREAM_END) ? "true" : "false"); if (StreamTcpReassembleAppLayer(tv, ra_ctx, ssn, stream, p, dir) < 0) { SCReturnInt(-1); } @@ -2137,8 +2124,8 @@ void StreamTcpReassemblySetMinInspectDepth(TcpSession *ssn, int direction, uint3 #ifdef UNITTESTS /** unit tests and it's support functions below */ -#define SET_ISN(stream, setseq) \ - (stream)->isn = (setseq); \ +#define SET_ISN(stream, setseq) \ + (stream)->isn = (setseq); \ (stream)->base_seq = (setseq) + 1 /** \brief The Function to create the packet with given payload, which is used @@ -2151,8 +2138,7 @@ void StreamTcpReassemblySetMinInspectDepth(TcpSession *ssn, int direction, uint3 * \param len Length of the payload array */ -void StreamTcpCreateTestPacket(uint8_t *payload, uint8_t value, - uint8_t payload_len, uint8_t len) +void StreamTcpCreateTestPacket(uint8_t *payload, uint8_t value, uint8_t payload_len, uint8_t len) { uint8_t i; for (i = 0; i < payload_len; i++) @@ -2170,9 +2156,8 @@ void StreamTcpCreateTestPacket(uint8_t *payload, uint8_t value, int StreamTcpCheckStreamContents(uint8_t *stream_policy, uint16_t sp_size, TcpStream *stream) { - if (StreamingBufferCompareRawData(&stream->sb, stream_policy,(uint32_t)sp_size) == 0) - { - //PrintRawDataFp(stdout, stream_policy, sp_size); + if (StreamingBufferCompareRawData(&stream->sb, stream_policy, (uint32_t)sp_size) == 0) { + // PrintRawDataFp(stdout, stream_policy, sp_size); return 0; } return 1; @@ -2180,9 +2165,7 @@ int StreamTcpCheckStreamContents(uint8_t *stream_policy, uint16_t sp_size, TcpSt static int VALIDATE(TcpStream *stream, uint8_t *data, uint32_t data_len) { - if (StreamingBufferCompareRawData(&stream->sb, - data, data_len) == 0) - { + if (StreamingBufferCompareRawData(&stream->sb, data, data_len) == 0) { SCReturnInt(0); } SCLogInfo("OK"); @@ -2190,27 +2173,27 @@ static int VALIDATE(TcpStream *stream, uint8_t *data, uint32_t data_len) return 1; } -#define MISSED_START(isn) \ - TcpReassemblyThreadCtx *ra_ctx = NULL; \ - TcpSession ssn; \ - ThreadVars tv; \ - memset(&tv, 0, sizeof(tv)); \ - \ - StreamTcpUTInit(&ra_ctx); \ - \ - StreamTcpUTSetupSession(&ssn); \ - StreamTcpUTSetupStream(&ssn.server, (isn)); \ - StreamTcpUTSetupStream(&ssn.client, (isn)); \ - \ +#define MISSED_START(isn) \ + TcpReassemblyThreadCtx *ra_ctx = NULL; \ + TcpSession ssn; \ + ThreadVars tv; \ + memset(&tv, 0, sizeof(tv)); \ + \ + StreamTcpUTInit(&ra_ctx); \ + \ + StreamTcpUTSetupSession(&ssn); \ + StreamTcpUTSetupStream(&ssn.server, (isn)); \ + StreamTcpUTSetupStream(&ssn.client, (isn)); \ + \ TcpStream *stream = &ssn.client; -#define MISSED_END \ - StreamTcpUTClearSession(&ssn); \ - StreamTcpUTDeinit(ra_ctx); \ +#define MISSED_END \ + StreamTcpUTClearSession(&ssn); \ + StreamTcpUTDeinit(ra_ctx); \ PASS -#define MISSED_STEP(seq, seg, seglen, buf, buflen) \ - StreamTcpUTAddPayload(&tv, ra_ctx, &ssn, stream, (seq), (uint8_t *)(seg), (seglen)); \ +#define MISSED_STEP(seq, seg, seglen, buf, buflen) \ + StreamTcpUTAddPayload(&tv, ra_ctx, &ssn, stream, (seq), (uint8_t *)(seg), (seglen)); \ FAIL_IF(!(VALIDATE(stream, (uint8_t *)(buf), (buflen)))); #define MISSED_ADD_PAYLOAD(seq, seg, seglen) \ @@ -2277,7 +2260,7 @@ int UTHCheckDataAtPosition( * \retval On success it returns 1 and on failure 0. */ -static int StreamTcpReassembleTest25 (void) +static int StreamTcpReassembleTest25(void) { MISSED_START(6); MISSED_ADD_PAYLOAD(10, "BB", 2); @@ -2298,7 +2281,7 @@ static int StreamTcpReassembleTest25 (void) * \retval On success it returns 1 and on failure 0. */ -static int StreamTcpReassembleTest26 (void) +static int StreamTcpReassembleTest26(void) { MISSED_START(9); MISSED_STEP(10, "AAA", 3, "AAA", 3); @@ -2317,7 +2300,7 @@ static int StreamTcpReassembleTest26 (void) * \retval On success it returns 1 and on failure 0. */ -static int StreamTcpReassembleTest27 (void) +static int StreamTcpReassembleTest27(void) { MISSED_START(9); MISSED_STEP(10, "AAA", 3, "AAA", 3); @@ -2334,7 +2317,7 @@ static int StreamTcpReassembleTest27 (void) * \retval On success it returns 1 and on failure 0. */ -static int StreamTcpReassembleTest28 (void) +static int StreamTcpReassembleTest28(void) { MISSED_START(6); MISSED_ADD_PAYLOAD(10, "AAA", 3); @@ -2358,7 +2341,7 @@ static int StreamTcpReassembleTest28 (void) * \retval On success it returns 1 and on failure 0. */ -static int StreamTcpReassembleTest29 (void) +static int StreamTcpReassembleTest29(void) { MISSED_START(9); MISSED_STEP(10, "AAA", 3, "AAA", 3); @@ -2384,10 +2367,10 @@ static int StreamTcpReassembleTest33(void) StreamTcpUTInit(&ra_ctx); StreamTcpUTSetupSession(&ssn); - memset(&f, 0, sizeof (Flow)); - memset(&tcph, 0, sizeof (TCPHdr)); + memset(&f, 0, sizeof(Flow)); + memset(&tcph, 0, sizeof(TCPHdr)); ThreadVars tv; - memset(&tv, 0, sizeof (ThreadVars)); + memset(&tv, 0, sizeof(ThreadVars)); FLOW_INITIALIZE(&f); f.protoctx = &ssn; f.proto = IPPROTO_TCP; @@ -2444,10 +2427,10 @@ static int StreamTcpReassembleTest34(void) StreamTcpUTInit(&ra_ctx); StreamTcpUTSetupSession(&ssn); - memset(&f, 0, sizeof (Flow)); - memset(&tcph, 0, sizeof (TCPHdr)); + memset(&f, 0, sizeof(Flow)); + memset(&tcph, 0, sizeof(TCPHdr)); ThreadVars tv; - memset(&tv, 0, sizeof (ThreadVars)); + memset(&tv, 0, sizeof(ThreadVars)); FLOW_INITIALIZE(&f); f.protoctx = &ssn; f.proto = IPPROTO_TCP; @@ -2500,7 +2483,7 @@ static int StreamTcpReassembleTest34(void) * \retval On success it returns 1 and on failure 0. */ -static int StreamTcpReassembleTest39 (void) +static int StreamTcpReassembleTest39(void) { Packet *p = PacketGetFromAlloc(); FAIL_IF(unlikely(p == NULL)); @@ -2509,11 +2492,11 @@ static int StreamTcpReassembleTest39 (void) StreamTcpThread stt; TCPHdr tcph; PacketQueueNoLock pq; - memset(&pq,0,sizeof(PacketQueueNoLock)); - memset (&f, 0, sizeof(Flow)); - memset(&tv, 0, sizeof (ThreadVars)); - memset(&stt, 0, sizeof (stt)); - memset(&tcph, 0, sizeof (TCPHdr)); + memset(&pq, 0, sizeof(PacketQueueNoLock)); + memset(&f, 0, sizeof(Flow)); + memset(&tv, 0, sizeof(ThreadVars)); + memset(&stt, 0, sizeof(stt)); + memset(&tcph, 0, sizeof(TCPHdr)); FLOW_INITIALIZE(&f); f.flags = FLOW_IPV4; @@ -2990,16 +2973,16 @@ static int StreamTcpReassembleTest39 (void) * \retval On success it returns 1 and on failure 0. */ -static int StreamTcpReassembleTest40 (void) +static int StreamTcpReassembleTest40(void) { Packet *p = PacketGetFromAlloc(); FAIL_IF_NULL(p); Flow *f = NULL; TCPHdr tcph; TcpSession ssn; - memset(&tcph, 0, sizeof (TCPHdr)); + memset(&tcph, 0, sizeof(TCPHdr)); ThreadVars tv; - memset(&tv, 0, sizeof (ThreadVars)); + memset(&tv, 0, sizeof(ThreadVars)); StreamTcpInitConfig(true); StreamTcpUTSetupSession(&ssn); @@ -3033,7 +3016,7 @@ static int StreamTcpReassembleTest40 (void) tcph.th_win = htons(5480); tcph.th_seq = htonl(10); tcph.th_ack = htonl(10); - tcph.th_flags = TH_ACK|TH_PUSH; + tcph.th_flags = TH_ACK | TH_PUSH; p->tcph = &tcph; p->flowflags = FLOW_PKT_TOSERVER; p->payload = httpbuf1; @@ -3133,11 +3116,12 @@ static int StreamTcpReassembleTest44(void) StreamTcpInitConfig(true); uint32_t memuse = SC_ATOMIC_GET(ra_memuse); StreamTcpReassembleIncrMemuse(500); - FAIL_IF(SC_ATOMIC_GET(ra_memuse) != (memuse+500)); + FAIL_IF(SC_ATOMIC_GET(ra_memuse) != (memuse + 500)); StreamTcpReassembleDecrMemuse(500); FAIL_IF(SC_ATOMIC_GET(ra_memuse) != memuse); FAIL_IF(StreamTcpReassembleCheckMemcap(500) != 1); - FAIL_IF(StreamTcpReassembleCheckMemcap((1 + memuse + SC_ATOMIC_GET(stream_config.reassembly_memcap))) != 0); + FAIL_IF(StreamTcpReassembleCheckMemcap( + (1 + memuse + SC_ATOMIC_GET(stream_config.reassembly_memcap))) != 0); StreamTcpFreeConfig(true); FAIL_IF(SC_ATOMIC_GET(ra_memuse) != 0); PASS; @@ -3149,13 +3133,13 @@ static int StreamTcpReassembleTest44(void) * \retval On success it returns 1 and on failure 0. */ -static int StreamTcpReassembleTest45 (void) +static int StreamTcpReassembleTest45(void) { TcpReassemblyThreadCtx *ra_ctx = NULL; TcpSession ssn; ThreadVars tv; memset(&tv, 0, sizeof(tv)); - uint8_t payload[100] = {0}; + uint8_t payload[100] = { 0 }; uint16_t payload_size = 100; StreamTcpUTInit(&ra_ctx); @@ -3187,14 +3171,14 @@ static int StreamTcpReassembleTest45 (void) * \retval On success it returns 1 and on failure 0. */ -static int StreamTcpReassembleTest46 (void) +static int StreamTcpReassembleTest46(void) { int result = 0; TcpReassemblyThreadCtx *ra_ctx = NULL; TcpSession ssn; ThreadVars tv; memset(&tv, 0, sizeof(tv)); - uint8_t payload[100] = {0}; + uint8_t payload[100] = { 0 }; uint16_t payload_size = 100; StreamTcpUTInit(&ra_ctx); @@ -3236,7 +3220,7 @@ static int StreamTcpReassembleTest46 (void) * \retval On success it returns 1 and on failure 0. */ -static int StreamTcpReassembleTest47 (void) +static int StreamTcpReassembleTest47(void) { Packet *p = PacketGetFromAlloc(); FAIL_IF(unlikely(p == NULL)); @@ -3244,8 +3228,8 @@ static int StreamTcpReassembleTest47 (void) TCPHdr tcph; TcpSession ssn; ThreadVars tv; - memset(&tcph, 0, sizeof (TCPHdr)); - memset(&tv, 0, sizeof (ThreadVars)); + memset(&tcph, 0, sizeof(TCPHdr)); + memset(&tv, 0, sizeof(ThreadVars)); StreamTcpInitConfig(true); StreamTcpUTSetupSession(&ssn); TcpReassemblyThreadCtx *ra_ctx = StreamTcpReassembleInitThreadCtx(&tv); @@ -3270,10 +3254,10 @@ static int StreamTcpReassembleTest47 (void) TcpStream *s = NULL; uint8_t cnt = 0; - for (cnt=0; cnt < httplen1; cnt++) { + for (cnt = 0; cnt < httplen1; cnt++) { tcph.th_seq = htonl(ssn.client.isn + 1 + cnt); tcph.th_ack = htonl(572799782UL); - tcph.th_flags = TH_ACK|TH_PUSH; + tcph.th_flags = TH_ACK | TH_PUSH; p->tcph = &tcph; p->flowflags = FLOW_PKT_TOSERVER; p->payload = &httpbuf1[cnt]; @@ -3332,11 +3316,11 @@ static int StreamTcpReassembleInlineTest01(void) p->tcph->th_seq = htonl(12); p->flow = &f; - if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 2, 'A', 5) == -1) { + if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 2, 'A', 5) == -1) { printf("failed to add segment 1: "); goto end; } - if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 7, 'B', 5) == -1) { + if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 7, 'B', 5) == -1) { printf("failed to add segment 2: "); goto end; } @@ -3384,11 +3368,11 @@ static int StreamTcpReassembleInlineTest02(void) p->tcph->th_seq = htonl(12); p->flow = &f; - if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 2, 'A', 5) == -1) { + if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 2, 'A', 5) == -1) { printf("failed to add segment 1: "); goto end; } - if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 7, 'B', 5) == -1) { + if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 7, 'B', 5) == -1) { printf("failed to add segment 2: "); goto end; } @@ -3445,11 +3429,11 @@ static int StreamTcpReassembleInlineTest03(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; - if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 2, 'A', 5) == -1) { + if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 2, 'A', 5) == -1) { printf("failed to add segment 1: "); goto end; } - if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 7, 'B', 5) == -1) { + if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 7, 'B', 5) == -1) { printf("failed to add segment 2: "); goto end; } @@ -3508,11 +3492,11 @@ static int StreamTcpReassembleInlineTest04(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; - if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 2, 'A', 5) == -1) { + if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 2, 'A', 5) == -1) { printf("failed to add segment 1: "); goto end; } - if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 7, 'B', 5) == -1) { + if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 7, 'B', 5) == -1) { printf("failed to add segment 2: "); goto end; } @@ -3567,8 +3551,8 @@ static int StreamTcpReassembleInlineTest08(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; - FAIL_IF(StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 2, 'A', 5) == -1); - FAIL_IF(StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 7, 'B', 5) == -1); + FAIL_IF(StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 2, 'A', 5) == -1); + FAIL_IF(StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 7, 'B', 5) == -1); FAIL_IF(StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 12, 'C', 5) == -1); ssn.client.next_seq = 17; FAIL_IF(StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 17, 'D', 5) == -1); @@ -3622,11 +3606,11 @@ static int StreamTcpReassembleInlineTest09(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; - if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 2, 'A', 5) == -1) { + if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 2, 'A', 5) == -1) { printf("failed to add segment 1: "); goto end; } - if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 7, 'B', 5) == -1) { + if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 7, 'B', 5) == -1) { printf("failed to add segment 2: "); goto end; } @@ -3700,7 +3684,7 @@ static int StreamTcpReassembleInlineTest10(void) p->flow = f; p->flowflags = FLOW_PKT_TOSERVER; - if (StreamTcpUTAddSegmentWithPayload(&tv, ra_ctx, &ssn.client, 2, stream_payload1, 2) == -1) { + if (StreamTcpUTAddSegmentWithPayload(&tv, ra_ctx, &ssn.client, 2, stream_payload1, 2) == -1) { printf("failed to add segment 1: "); goto end; } @@ -3713,16 +3697,16 @@ static int StreamTcpReassembleInlineTest10(void) } /* ssn.server.ra_app_base_seq should be isn here. */ - if (ssn.client.base_seq != 2 || ssn.client.base_seq != ssn.client.isn+1) { + if (ssn.client.base_seq != 2 || ssn.client.base_seq != ssn.client.isn + 1) { printf("expected ra_app_base_seq 1, got %u: ", ssn.client.base_seq); goto end; } - if (StreamTcpUTAddSegmentWithPayload(&tv, ra_ctx, &ssn.client, 4, stream_payload2, 3) == -1) { + if (StreamTcpUTAddSegmentWithPayload(&tv, ra_ctx, &ssn.client, 4, stream_payload2, 3) == -1) { printf("failed to add segment 2: "); goto end; } - if (StreamTcpUTAddSegmentWithPayload(&tv, ra_ctx, &ssn.client, 7, stream_payload3, 12) == -1) { + if (StreamTcpUTAddSegmentWithPayload(&tv, ra_ctx, &ssn.client, 7, stream_payload3, 12) == -1) { printf("failed to add segment 3: "); goto end; } @@ -3770,8 +3754,8 @@ static int StreamTcpReassembleInsertTest01(void) p->tcph->th_seq = htonl(12); p->flow = &f; - FAIL_IF(StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 2, 'A', 5) == -1); - FAIL_IF(StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 7, 'B', 5) == -1); + FAIL_IF(StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 2, 'A', 5) == -1); + FAIL_IF(StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 7, 'B', 5) == -1); FAIL_IF(StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 14, 'D', 2) == -1); FAIL_IF(StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 16, 'D', 6) == -1); FAIL_IF(StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 12, 'C', 5) == -1); @@ -3810,12 +3794,12 @@ static int StreamTcpReassembleInsertTest02(void) if (seq < 2) seq = 2; - if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, seq, 'A', len) == -1) { + if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, seq, 'A', len) == -1) { printf("failed to add segment 1: "); goto end; } } - if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 2, 'B', 1024) == -1) { + if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 2, 'B', 1024) == -1) { printf("failed to add segment 2: "); goto end; } @@ -3842,7 +3826,7 @@ static int StreamTcpReassembleInsertTest03(void) StreamTcpUTSetupSession(&ssn); StreamTcpUTSetupStream(&ssn.client, 1); - if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 2, 'A', 1024) == -1) { + if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, 2, 'A', 1024) == -1) { printf("failed to add segment 2: "); goto end; } @@ -3858,7 +3842,7 @@ static int StreamTcpReassembleInsertTest03(void) if (seq < 2) seq = 2; - if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, seq, 'B', len) == -1) { + if (StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &ssn.client, seq, 'B', len) == -1) { printf("failed to add segment 2: "); goto end; } @@ -3880,55 +3864,48 @@ static int StreamTcpReassembleInsertTest03(void) void StreamTcpReassembleRegisterTests(void) { #ifdef UNITTESTS - UtRegisterTest("StreamTcpReassembleTest25 -- Gap at Start Reassembly Test", - StreamTcpReassembleTest25); + UtRegisterTest( + "StreamTcpReassembleTest25 -- Gap at Start Reassembly Test", StreamTcpReassembleTest25); UtRegisterTest("StreamTcpReassembleTest26 -- Gap at middle Reassembly Test", - StreamTcpReassembleTest26); + StreamTcpReassembleTest26); UtRegisterTest("StreamTcpReassembleTest27 -- Gap at after Reassembly Test", - StreamTcpReassembleTest27); + StreamTcpReassembleTest27); UtRegisterTest("StreamTcpReassembleTest28 -- Gap at Start IDS missed packet Reassembly Test", - StreamTcpReassembleTest28); + StreamTcpReassembleTest28); UtRegisterTest("StreamTcpReassembleTest29 -- Gap at Middle IDS missed packet Reassembly Test", - StreamTcpReassembleTest29); - UtRegisterTest("StreamTcpReassembleTest33 -- Bug test", - StreamTcpReassembleTest33); - UtRegisterTest("StreamTcpReassembleTest34 -- Bug test", - StreamTcpReassembleTest34); - UtRegisterTest("StreamTcpReassembleTest39 -- app proto test", - StreamTcpReassembleTest39); - UtRegisterTest("StreamTcpReassembleTest40 -- app proto test", - StreamTcpReassembleTest40); - UtRegisterTest("StreamTcpReassembleTest44 -- Memcap Test", - StreamTcpReassembleTest44); - UtRegisterTest("StreamTcpReassembleTest45 -- Depth Test", - StreamTcpReassembleTest45); - UtRegisterTest("StreamTcpReassembleTest46 -- Depth Test", - StreamTcpReassembleTest46); - UtRegisterTest("StreamTcpReassembleTest47 -- TCP Sequence Wraparound Test", - StreamTcpReassembleTest47); - - UtRegisterTest("StreamTcpReassembleInlineTest01 -- inline RAW ra", - StreamTcpReassembleInlineTest01); - UtRegisterTest("StreamTcpReassembleInlineTest02 -- inline RAW ra 2", - StreamTcpReassembleInlineTest02); - UtRegisterTest("StreamTcpReassembleInlineTest03 -- inline RAW ra 3", - StreamTcpReassembleInlineTest03); - UtRegisterTest("StreamTcpReassembleInlineTest04 -- inline RAW ra 4", - StreamTcpReassembleInlineTest04); + StreamTcpReassembleTest29); + UtRegisterTest("StreamTcpReassembleTest33 -- Bug test", StreamTcpReassembleTest33); + UtRegisterTest("StreamTcpReassembleTest34 -- Bug test", StreamTcpReassembleTest34); + UtRegisterTest("StreamTcpReassembleTest39 -- app proto test", StreamTcpReassembleTest39); + UtRegisterTest("StreamTcpReassembleTest40 -- app proto test", StreamTcpReassembleTest40); + UtRegisterTest("StreamTcpReassembleTest44 -- Memcap Test", StreamTcpReassembleTest44); + UtRegisterTest("StreamTcpReassembleTest45 -- Depth Test", StreamTcpReassembleTest45); + UtRegisterTest("StreamTcpReassembleTest46 -- Depth Test", StreamTcpReassembleTest46); + UtRegisterTest( + "StreamTcpReassembleTest47 -- TCP Sequence Wraparound Test", StreamTcpReassembleTest47); + + UtRegisterTest( + "StreamTcpReassembleInlineTest01 -- inline RAW ra", StreamTcpReassembleInlineTest01); + UtRegisterTest( + "StreamTcpReassembleInlineTest02 -- inline RAW ra 2", StreamTcpReassembleInlineTest02); + UtRegisterTest( + "StreamTcpReassembleInlineTest03 -- inline RAW ra 3", StreamTcpReassembleInlineTest03); + UtRegisterTest( + "StreamTcpReassembleInlineTest04 -- inline RAW ra 4", StreamTcpReassembleInlineTest04); UtRegisterTest("StreamTcpReassembleInlineTest08 -- inline RAW ra 8 cleanup", - StreamTcpReassembleInlineTest08); + StreamTcpReassembleInlineTest08); UtRegisterTest("StreamTcpReassembleInlineTest09 -- inline RAW ra 9 GAP cleanup", - StreamTcpReassembleInlineTest09); + StreamTcpReassembleInlineTest09); - UtRegisterTest("StreamTcpReassembleInlineTest10 -- inline APP ra 10", - StreamTcpReassembleInlineTest10); + UtRegisterTest( + "StreamTcpReassembleInlineTest10 -- inline APP ra 10", StreamTcpReassembleInlineTest10); UtRegisterTest("StreamTcpReassembleInsertTest01 -- insert with overlap", - StreamTcpReassembleInsertTest01); + StreamTcpReassembleInsertTest01); UtRegisterTest("StreamTcpReassembleInsertTest02 -- insert with overlap", - StreamTcpReassembleInsertTest02); + StreamTcpReassembleInsertTest02); UtRegisterTest("StreamTcpReassembleInsertTest03 -- insert with overlap", - StreamTcpReassembleInsertTest03); + StreamTcpReassembleInsertTest03); StreamTcpInlineRegisterTests(); StreamTcpUtilRegisterTests(); diff --git a/src/stream-tcp-reassemble.h b/src/stream-tcp-reassemble.h index 6f761fc0b4e4..32526d0e58dd 100644 --- a/src/stream-tcp-reassemble.h +++ b/src/stream-tcp-reassemble.h @@ -30,8 +30,7 @@ #include "stream-tcp-private.h" /** Supported OS list and default OS policy is BSD */ -enum -{ +enum { OS_POLICY_NONE = 1, OS_POLICY_BSD, OS_POLICY_BSD_RIGHT, @@ -82,7 +81,7 @@ typedef struct TcpReassemblyThreadCtx_ { uint16_t counter_tcp_reass_data_overlap_fail; } TcpReassemblyThreadCtx; -#define OS_POLICY_DEFAULT OS_POLICY_BSD +#define OS_POLICY_DEFAULT OS_POLICY_BSD void StreamTcpReassembleInitMemuse(void); int StreamTcpReassembleHandleSegment( @@ -93,9 +92,8 @@ void *StreamTcpReassembleRealloc(void *optr, size_t orig_size, size_t size); void StreamTcpReassembleRegisterTests(void); TcpReassemblyThreadCtx *StreamTcpReassembleInitThreadCtx(ThreadVars *tv); void StreamTcpReassembleFreeThreadCtx(TcpReassemblyThreadCtx *); -int StreamTcpReassembleAppLayer (ThreadVars *tv, TcpReassemblyThreadCtx *ra_ctx, - TcpSession *ssn, TcpStream *stream, - Packet *p, enum StreamUpdateDir dir); +int StreamTcpReassembleAppLayer(ThreadVars *tv, TcpReassemblyThreadCtx *ra_ctx, TcpSession *ssn, + TcpStream *stream, Packet *p, enum StreamUpdateDir dir); void StreamTcpCreateTestPacket(uint8_t *, uint8_t, uint8_t, uint8_t); @@ -107,7 +105,8 @@ void StreamTcpSetOSPolicy(TcpStream *, Packet *); int StreamTcpReassembleHandleSegmentHandleData(ThreadVars *tv, TcpReassemblyThreadCtx *ra_ctx, TcpSession *ssn, TcpStream *stream, Packet *p); -int StreamTcpReassembleInsertSegment(ThreadVars *, TcpReassemblyThreadCtx *, TcpStream *, TcpSegment *, Packet *, uint32_t pkt_seq, uint8_t *pkt_data, uint16_t pkt_datalen); +int StreamTcpReassembleInsertSegment(ThreadVars *, TcpReassemblyThreadCtx *, TcpStream *, + TcpSegment *, Packet *, uint32_t pkt_seq, uint8_t *pkt_data, uint16_t pkt_datalen); TcpSegment *StreamTcpGetSegment(ThreadVars *, TcpReassemblyThreadCtx *); void StreamTcpReturnStreamSegments(TcpStream *); @@ -129,7 +128,7 @@ void StreamTcpDisableAppLayer(Flow *f); int StreamTcpAppLayerIsDisabled(Flow *f); #ifdef UNITTESTS -int StreamTcpCheckStreamContents(uint8_t *, uint16_t , TcpStream *); +int StreamTcpCheckStreamContents(uint8_t *, uint16_t, TcpStream *); #endif bool StreamReassembleRawHasDataReady(TcpSession *ssn, Packet *p); @@ -157,4 +156,3 @@ static inline bool STREAM_LASTACK_GT_BASESEQ(const TcpStream *stream) uint32_t StreamDataAvailableForProtoDetect(TcpStream *stream); #endif /* __STREAM_TCP_REASSEMBLE_H__ */ - diff --git a/src/stream-tcp-sack.c b/src/stream-tcp-sack.c index f97dfc4afdcd..0d9a3ce4f9c8 100644 --- a/src/stream-tcp-sack.c +++ b/src/stream-tcp-sack.c @@ -51,7 +51,8 @@ static void StreamTcpSackPrintList(TcpStream *stream) { SCLogDebug("size %u", stream->sack_size); StreamTcpSackRecord *rec = NULL; - RB_FOREACH(rec, TCPSACK, &stream->sack_tree) { + RB_FOREACH(rec, TCPSACK, &stream->sack_tree) + { SCLogDebug("- record %8u - %8u", rec->le, rec->re); } } @@ -76,10 +77,11 @@ static inline void StreamTcpSackRecordFree(StreamTcpSackRecord *rec) StreamTcpDecrMemuse((uint64_t)sizeof(*rec)); } -static inline void ConsolidateFwd(TcpStream *stream, struct TCPSACK *tree, struct StreamTcpSackRecord *sa) +static inline void ConsolidateFwd( + TcpStream *stream, struct TCPSACK *tree, struct StreamTcpSackRecord *sa) { struct StreamTcpSackRecord *tr, *s = sa; - RB_FOREACH_FROM(tr, TCPSACK, s) { + RB_FOREACH_FROM (tr, TCPSACK, s) { if (sa == tr) continue; SCLogDebug("-> (fwd) tr %p %u/%u", tr, tr->le, tr->re); @@ -96,28 +98,28 @@ static inline void ConsolidateFwd(TcpStream *stream, struct TCPSACK *tree, struc SCLogDebug("-> (fwd) tr %p %u/%u REMOVED ECLIPSED2", tr, tr->le, tr->re); TCPSACK_RB_REMOVE(tree, tr); StreamTcpSackRecordFree(tr); - /* - sa: [ ] - tr: [ ] - sa: [ ] - tr: [ ] - sa: [ ] - tr: [ ] - */ + /* + sa: [ ] + tr: [ ] + sa: [ ] + tr: [ ] + sa: [ ] + tr: [ ] + */ } else if (SEQ_LEQ(sa->le, tr->le) && SEQ_GEQ(sa->re, tr->re)) { SCLogDebug("-> (fwd) tr %p %u/%u REMOVED ECLIPSED", tr, tr->le, tr->re); stream->sack_size -= (tr->re - tr->le); TCPSACK_RB_REMOVE(tree, tr); StreamTcpSackRecordFree(tr); - /* - sa: [ ] - tr: [ ] - sa: [ ] - tr: [ ] - */ - } else if (SEQ_LT(sa->le, tr->le) && // starts before + /* + sa: [ ] + tr: [ ] + sa: [ ] + tr: [ ] + */ + } else if (SEQ_LT(sa->le, tr->le) && // starts before SEQ_GEQ(sa->re, tr->le) && SEQ_LT(sa->re, tr->re) // ends inside - ) { + ) { // merge stream->sack_size -= (tr->re - tr->le); stream->sack_size -= (sa->re - sa->le); @@ -130,11 +132,11 @@ static inline void ConsolidateFwd(TcpStream *stream, struct TCPSACK *tree, struc } } -static inline void ConsolidateBackward(TcpStream *stream, - struct TCPSACK *tree, struct StreamTcpSackRecord *sa) +static inline void ConsolidateBackward( + TcpStream *stream, struct TCPSACK *tree, struct StreamTcpSackRecord *sa) { struct StreamTcpSackRecord *tr, *s = sa; - RB_FOREACH_REVERSE_FROM(tr, TCPSACK, s) { + RB_FOREACH_REVERSE_FROM (tr, TCPSACK, s) { if (sa == tr) continue; SCLogDebug("-> (bwd) tr %p %u/%u", tr, tr->le, tr->re); @@ -150,26 +152,26 @@ static inline void ConsolidateBackward(TcpStream *stream, SCLogDebug("-> (bwd) tr %p %u/%u REMOVED ECLIPSED2", tr, tr->le, tr->re); TCPSACK_RB_REMOVE(tree, tr); StreamTcpSackRecordFree(tr); - /* - sa: [ ] - tr: [ ] - sa: [ ] - tr: [ ] - sa: [ ] - tr: [ ] - */ + /* + sa: [ ] + tr: [ ] + sa: [ ] + tr: [ ] + sa: [ ] + tr: [ ] + */ } else if (SEQ_LEQ(sa->le, tr->le) && SEQ_GEQ(sa->re, tr->re)) { SCLogDebug("-> (bwd) tr %p %u/%u REMOVED ECLIPSED", tr, tr->le, tr->re); stream->sack_size -= (tr->re - tr->le); TCPSACK_RB_REMOVE(tree, tr); StreamTcpSackRecordFree(tr); - /* - sa: [ ] - tr: [ ] - sa: [ ] - tr: [ ] - */ - } else if (SEQ_GT(sa->le, tr->le) && SEQ_GT(sa->re, tr->re) && SEQ_LEQ(sa->le,tr->re)) { + /* + sa: [ ] + tr: [ ] + sa: [ ] + tr: [ ] + */ + } else if (SEQ_GT(sa->le, tr->le) && SEQ_GT(sa->re, tr->re) && SEQ_LEQ(sa->le, tr->re)) { // merge stream->sack_size -= (tr->re - tr->le); stream->sack_size -= (sa->re - sa->le); @@ -295,8 +297,7 @@ int StreamTcpSackUpdatePacket(TcpStream *stream, Packet *p) } if (SEQ_GT(re, stream->next_win)) { - SCLogDebug("record %u:%u beyond next_win %u", - le, re, stream->next_win); + SCLogDebug("record %u:%u beyond next_win %u", le, re, stream->next_win); goto next; } @@ -403,7 +404,7 @@ void StreamTcpSackPruneList(TcpStream *stream) SCEnter(); StreamTcpSackRecord *rec = NULL, *safe = NULL; - RB_FOREACH_SAFE(rec, TCPSACK, &stream->sack_tree, safe) { + RB_FOREACH_SAFE (rec, TCPSACK, &stream->sack_tree, safe) { if (SEQ_LT(rec->re, stream->last_ack)) { SCLogDebug("removing le %u re %u", rec->le, rec->re); stream->sack_size -= (rec->re - rec->le); @@ -438,7 +439,7 @@ void StreamTcpSackFreeList(TcpStream *stream) SCEnter(); StreamTcpSackRecord *rec = NULL, *safe = NULL; - RB_FOREACH_SAFE(rec, TCPSACK, &stream->sack_tree, safe) { + RB_FOREACH_SAFE (rec, TCPSACK, &stream->sack_tree, safe) { stream->sack_size -= (rec->re - rec->le); TCPSACK_RB_REMOVE(&stream->sack_tree, rec); StreamTcpSackRecordFree(rec); @@ -447,7 +448,6 @@ void StreamTcpSackFreeList(TcpStream *stream) SCReturn; } - #ifdef UNITTESTS /** @@ -456,7 +456,7 @@ void StreamTcpSackFreeList(TcpStream *stream) * \retval On success it returns 1 and on failure 0. */ -static int StreamTcpSackTest01 (void) +static int StreamTcpSackTest01(void) { TcpStream stream; memset(&stream, 0, sizeof(stream)); @@ -491,7 +491,7 @@ static int StreamTcpSackTest01 (void) * \retval On success it returns 1 and on failure 0. */ -static int StreamTcpSackTest02 (void) +static int StreamTcpSackTest02(void) { TcpStream stream; memset(&stream, 0, sizeof(stream)); @@ -520,14 +520,14 @@ static int StreamTcpSackTest02 (void) * \retval On success it returns 1 and on failure 0. */ -static int StreamTcpSackTest03 (void) +static int StreamTcpSackTest03(void) { TcpStream stream; memset(&stream, 0, sizeof(stream)); stream.window = 100; StreamTcpSackInsertRange(&stream, 10, 20); - StreamTcpSackInsertRange(&stream, 5, 15); + StreamTcpSackInsertRange(&stream, 5, 15); #ifdef DEBUG StreamTcpSackPrintList(&stream); #endif /* DEBUG */ @@ -553,13 +553,13 @@ static int StreamTcpSackTest03 (void) * \retval On success it returns 1 and on failure 0. */ -static int StreamTcpSackTest04 (void) +static int StreamTcpSackTest04(void) { TcpStream stream; memset(&stream, 0, sizeof(stream)); stream.window = 100; - StreamTcpSackInsertRange(&stream, 0, 20); + StreamTcpSackInsertRange(&stream, 0, 20); StreamTcpSackInsertRange(&stream, 30, 50); StreamTcpSackInsertRange(&stream, 10, 25); #ifdef DEBUG @@ -583,13 +583,13 @@ static int StreamTcpSackTest04 (void) * \retval On success it returns 1 and on failure 0. */ -static int StreamTcpSackTest05 (void) +static int StreamTcpSackTest05(void) { TcpStream stream; memset(&stream, 0, sizeof(stream)); stream.window = 100; - StreamTcpSackInsertRange(&stream, 0, 20); + StreamTcpSackInsertRange(&stream, 0, 20); StreamTcpSackInsertRange(&stream, 30, 50); StreamTcpSackInsertRange(&stream, 10, 35); #ifdef DEBUG @@ -613,13 +613,13 @@ static int StreamTcpSackTest05 (void) * \retval On success it returns 1 and on failure 0. */ -static int StreamTcpSackTest06 (void) +static int StreamTcpSackTest06(void) { TcpStream stream; memset(&stream, 0, sizeof(stream)); stream.window = 100; - StreamTcpSackInsertRange(&stream, 0, 9); + StreamTcpSackInsertRange(&stream, 0, 9); StreamTcpSackInsertRange(&stream, 11, 19); StreamTcpSackInsertRange(&stream, 21, 29); StreamTcpSackInsertRange(&stream, 31, 39); @@ -645,13 +645,13 @@ static int StreamTcpSackTest06 (void) * \retval On success it returns 1 and on failure 0. */ -static int StreamTcpSackTest07 (void) +static int StreamTcpSackTest07(void) { TcpStream stream; memset(&stream, 0, sizeof(stream)); stream.window = 100; - StreamTcpSackInsertRange(&stream, 0, 9); + StreamTcpSackInsertRange(&stream, 0, 9); StreamTcpSackInsertRange(&stream, 11, 19); StreamTcpSackInsertRange(&stream, 21, 29); StreamTcpSackInsertRange(&stream, 31, 39); @@ -680,13 +680,13 @@ static int StreamTcpSackTest07 (void) * \retval On success it returns 1 and on failure 0. */ -static int StreamTcpSackTest08 (void) +static int StreamTcpSackTest08(void) { TcpStream stream; memset(&stream, 0, sizeof(stream)); stream.window = 100; - StreamTcpSackInsertRange(&stream, 0, 9); + StreamTcpSackInsertRange(&stream, 0, 9); StreamTcpSackInsertRange(&stream, 11, 19); StreamTcpSackInsertRange(&stream, 21, 29); StreamTcpSackInsertRange(&stream, 31, 39); @@ -715,13 +715,13 @@ static int StreamTcpSackTest08 (void) * \retval On success it returns 1 and on failure 0. */ -static int StreamTcpSackTest09 (void) +static int StreamTcpSackTest09(void) { TcpStream stream; memset(&stream, 0, sizeof(stream)); stream.window = 100; - StreamTcpSackInsertRange(&stream, 0, 9); + StreamTcpSackInsertRange(&stream, 0, 9); StreamTcpSackInsertRange(&stream, 11, 19); StreamTcpSackInsertRange(&stream, 21, 29); StreamTcpSackInsertRange(&stream, 31, 39); @@ -751,7 +751,7 @@ static int StreamTcpSackTest09 (void) * \retval On success it returns 1 and on failure 0. */ -static int StreamTcpSackTest10 (void) +static int StreamTcpSackTest10(void) { TcpStream stream; memset(&stream, 0, sizeof(stream)); @@ -786,7 +786,7 @@ static int StreamTcpSackTest10 (void) * \retval On success it returns 1 and on failure 0. */ -static int StreamTcpSackTest11 (void) +static int StreamTcpSackTest11(void) { TcpStream stream; memset(&stream, 0, sizeof(stream)); @@ -821,7 +821,7 @@ static int StreamTcpSackTest11 (void) * \retval On success it returns 1 and on failure 0. */ -static int StreamTcpSackTest12 (void) +static int StreamTcpSackTest12(void) { TcpStream stream; memset(&stream, 0, sizeof(stream)); @@ -859,14 +859,15 @@ static int StreamTcpSackTest12 (void) * \retval On success it returns 1 and on failure 0. */ -static int StreamTcpSackTest13 (void) { +static int StreamTcpSackTest13(void) +{ TcpStream stream; memset(&stream, 0, sizeof(stream)); stream.last_ack = 10000; stream.window = 2000; for (int i = 0; i < 10; i++) { - StreamTcpSackInsertRange(&stream, 100+(20*i), 110+(20*i)); + StreamTcpSackInsertRange(&stream, 100 + (20 * i), 110 + (20 * i)); } #ifdef DEBUG StreamTcpSackPrintList(&stream); @@ -884,14 +885,15 @@ static int StreamTcpSackTest13 (void) { * \retval On success it returns 1 and on failure 0. */ -static int StreamTcpSackTest14 (void) { +static int StreamTcpSackTest14(void) +{ TcpStream stream; memset(&stream, 0, sizeof(stream)); stream.last_ack = 1000; stream.window = 2000; for (int i = 0; i < 10; i++) { - StreamTcpSackInsertRange(&stream, 4000+(20*i), 4010+(20*i)); + StreamTcpSackInsertRange(&stream, 4000 + (20 * i), 4010 + (20 * i)); } #ifdef DEBUG StreamTcpSackPrintList(&stream); @@ -905,7 +907,7 @@ static int StreamTcpSackTest14 (void) { #endif /* UNITTESTS */ -void StreamTcpSackRegisterTests (void) +void StreamTcpSackRegisterTests(void) { #ifdef UNITTESTS UtRegisterTest("StreamTcpSackTest01 -- Insertion", StreamTcpSackTest01); @@ -918,13 +920,9 @@ void StreamTcpSackRegisterTests (void) UtRegisterTest("StreamTcpSackTest08 -- Pruning", StreamTcpSackTest08); UtRegisterTest("StreamTcpSackTest09 -- Pruning", StreamTcpSackTest09); UtRegisterTest("StreamTcpSackTest10 -- Pruning", StreamTcpSackTest10); - UtRegisterTest("StreamTcpSackTest11 -- Insertion && Pruning", - StreamTcpSackTest11); - UtRegisterTest("StreamTcpSackTest12 -- Insertion && Pruning", - StreamTcpSackTest12); - UtRegisterTest("StreamTcpSackTest13 -- Insertion out of window", - StreamTcpSackTest13); - UtRegisterTest("StreamTcpSackTest14 -- Insertion out of window", - StreamTcpSackTest14); + UtRegisterTest("StreamTcpSackTest11 -- Insertion && Pruning", StreamTcpSackTest11); + UtRegisterTest("StreamTcpSackTest12 -- Insertion && Pruning", StreamTcpSackTest12); + UtRegisterTest("StreamTcpSackTest13 -- Insertion out of window", StreamTcpSackTest13); + UtRegisterTest("StreamTcpSackTest14 -- Insertion out of window", StreamTcpSackTest14); #endif } diff --git a/src/stream-tcp-sack.h b/src/stream-tcp-sack.h index 84e7cb1bdfe3..18902a1f2447 100644 --- a/src/stream-tcp-sack.h +++ b/src/stream-tcp-sack.h @@ -42,6 +42,6 @@ int StreamTcpSackUpdatePacket(TcpStream *, Packet *); bool StreamTcpSackPacketIsOutdated(TcpStream *stream, Packet *p); void StreamTcpSackPruneList(TcpStream *); void StreamTcpSackFreeList(TcpStream *); -void StreamTcpSackRegisterTests (void); +void StreamTcpSackRegisterTests(void); #endif /* __STREAM_TCP_SACK_H__*/ diff --git a/src/stream-tcp-util.c b/src/stream-tcp-util.c index 4d8bf8a89313..6c8777e62ede 100644 --- a/src/stream-tcp-util.c +++ b/src/stream-tcp-util.c @@ -55,7 +55,8 @@ void StreamTcpUTDeinit(TcpReassemblyThreadCtx *ra_ctx) stream_config.flags &= ~STREAMTCP_INIT_FLAG_INLINE; } -void StreamTcpUTInitInline(void) { +void StreamTcpUTInitInline(void) +{ stream_config.flags |= STREAMTCP_INIT_FLAG_INLINE; } @@ -82,7 +83,7 @@ void StreamTcpUTSetupStream(TcpStream *s, uint32_t isn) s->isn = isn; STREAMTCP_SET_RA_BASE_SEQ(s, isn); - s->base_seq = isn+1; + s->base_seq = isn + 1; StreamingBuffer x = STREAMING_BUFFER_INITIALIZER; s->sb = x; @@ -94,7 +95,8 @@ void StreamTcpUTClearStream(TcpStream *s) } /** \brief wrapper for StreamTcpReassembleHandleSegmentHandleData */ -int StreamTcpUTAddPayload(ThreadVars *tv, TcpReassemblyThreadCtx *ra_ctx, TcpSession *ssn, TcpStream *stream, uint32_t seq, uint8_t *payload, uint16_t len) +int StreamTcpUTAddPayload(ThreadVars *tv, TcpReassemblyThreadCtx *ra_ctx, TcpSession *ssn, + TcpStream *stream, uint32_t seq, uint8_t *payload, uint16_t len) { Packet *p = UTHBuildPacketReal(payload, len, IPPROTO_TCP, "1.1.1.1", "2.2.2.2", 1024, 80); if (p == NULL) { @@ -110,7 +112,8 @@ int StreamTcpUTAddPayload(ThreadVars *tv, TcpReassemblyThreadCtx *ra_ctx, TcpSes return 0; } -int StreamTcpUTAddSegmentWithPayload(ThreadVars *tv, TcpReassemblyThreadCtx *ra_ctx, TcpStream *stream, uint32_t seq, uint8_t *payload, uint16_t len) +int StreamTcpUTAddSegmentWithPayload(ThreadVars *tv, TcpReassemblyThreadCtx *ra_ctx, + TcpStream *stream, uint32_t seq, uint8_t *payload, uint16_t len) { TcpSegment *s = StreamTcpGetSegment(tv, ra_ctx); if (s == NULL) { @@ -126,14 +129,16 @@ int StreamTcpUTAddSegmentWithPayload(ThreadVars *tv, TcpReassemblyThreadCtx *ra_ } p->tcph->th_seq = htonl(seq); - if (StreamTcpReassembleInsertSegment(tv, ra_ctx, stream, s, p, TCP_GET_SEQ(p), p->payload, p->payload_len) < 0) + if (StreamTcpReassembleInsertSegment( + tv, ra_ctx, stream, s, p, TCP_GET_SEQ(p), p->payload, p->payload_len) < 0) return -1; UTHFreePacket(p); return 0; } -int StreamTcpUTAddSegmentWithByte(ThreadVars *tv, TcpReassemblyThreadCtx *ra_ctx, TcpStream *stream, uint32_t seq, uint8_t byte, uint16_t len) +int StreamTcpUTAddSegmentWithByte(ThreadVars *tv, TcpReassemblyThreadCtx *ra_ctx, TcpStream *stream, + uint32_t seq, uint8_t byte, uint16_t len) { TcpSegment *s = StreamTcpGetSegment(tv, ra_ctx); if (s == NULL) { @@ -151,7 +156,8 @@ int StreamTcpUTAddSegmentWithByte(ThreadVars *tv, TcpReassemblyThreadCtx *ra_ctx } p->tcph->th_seq = htonl(seq); - if (StreamTcpReassembleInsertSegment(tv, ra_ctx, stream, s, p, TCP_GET_SEQ(p), p->payload, p->payload_len) < 0) + if (StreamTcpReassembleInsertSegment( + tv, ra_ctx, stream, s, p, TCP_GET_SEQ(p), p->payload, p->payload_len) < 0) return -1; UTHFreePacket(p); return 0; @@ -177,7 +183,6 @@ static int StreamTcpUtilTest01(void) return ret; } - static int StreamTcpUtilStreamTest01(void) { TcpReassemblyThreadCtx *ra_ctx = NULL; @@ -188,8 +193,8 @@ static int StreamTcpUtilStreamTest01(void) StreamTcpUTInit(&ra_ctx); StreamTcpUTSetupStream(&stream, 1); - FAIL_IF(StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &stream, 2, 'A', 5) == -1); - FAIL_IF(StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &stream, 7, 'B', 5) == -1); + FAIL_IF(StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &stream, 2, 'A', 5) == -1); + FAIL_IF(StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &stream, 7, 'B', 5) == -1); FAIL_IF(StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &stream, 12, 'C', 5) == -1); TcpSegment *seg = RB_MIN(TCPSEG, &stream.seg_tree); @@ -219,9 +224,9 @@ static int StreamTcpUtilStreamTest02(void) StreamTcpUTInit(&ra_ctx); StreamTcpUTSetupStream(&stream, 1); - FAIL_IF(StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &stream, 7, 'B', 5) == -1); + FAIL_IF(StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &stream, 7, 'B', 5) == -1); FAIL_IF(StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &stream, 12, 'C', 5) == -1); - FAIL_IF(StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &stream, 2, 'A', 5) == -1); + FAIL_IF(StreamTcpUTAddSegmentWithByte(&tv, ra_ctx, &stream, 2, 'A', 5) == -1); TcpSegment *seg = RB_MIN(TCPSEG, &stream.seg_tree); FAIL_IF_NULL(seg); @@ -250,4 +255,3 @@ void StreamTcpUtilRegisterTests(void) UtRegisterTest("StreamTcpUtilStreamTest02", StreamTcpUtilStreamTest02); #endif /* UNITTESTS */ } - diff --git a/src/stream-tcp-util.h b/src/stream-tcp-util.h index fe05537e33ef..97a3f4d61209 100644 --- a/src/stream-tcp-util.h +++ b/src/stream-tcp-util.h @@ -38,11 +38,13 @@ void StreamTcpUTClearSession(TcpSession *); void StreamTcpUTSetupStream(TcpStream *, uint32_t isn); void StreamTcpUTClearStream(TcpStream *); -int StreamTcpUTAddSegmentWithByte(ThreadVars *, TcpReassemblyThreadCtx *, TcpStream *, uint32_t, uint8_t, uint16_t); -int StreamTcpUTAddSegmentWithPayload(ThreadVars *, TcpReassemblyThreadCtx *, TcpStream *, uint32_t, uint8_t *, uint16_t); -int StreamTcpUTAddPayload(ThreadVars *tv, TcpReassemblyThreadCtx *ra_ctx, TcpSession *ssn, TcpStream *stream, uint32_t seq, uint8_t *payload, uint16_t len); +int StreamTcpUTAddSegmentWithByte( + ThreadVars *, TcpReassemblyThreadCtx *, TcpStream *, uint32_t, uint8_t, uint16_t); +int StreamTcpUTAddSegmentWithPayload( + ThreadVars *, TcpReassemblyThreadCtx *, TcpStream *, uint32_t, uint8_t *, uint16_t); +int StreamTcpUTAddPayload(ThreadVars *tv, TcpReassemblyThreadCtx *ra_ctx, TcpSession *ssn, + TcpStream *stream, uint32_t seq, uint8_t *payload, uint16_t len); void StreamTcpUtilRegisterTests(void); #endif /* __STREAM_TCP_UTIL_H__ */ - diff --git a/src/stream-tcp.c b/src/stream-tcp.c index b77423161800..00f4b03f939f 100644 --- a/src/stream-tcp.c +++ b/src/stream-tcp.c @@ -82,23 +82,23 @@ //#define DEBUG -#define STREAMTCP_DEFAULT_PREALLOC 2048 -#define STREAMTCP_DEFAULT_MEMCAP (64 * 1024 * 1024) /* 64mb */ -#define STREAMTCP_DEFAULT_REASSEMBLY_MEMCAP (256 * 1024 * 1024) /* 256mb */ -#define STREAMTCP_DEFAULT_TOSERVER_CHUNK_SIZE 2560 -#define STREAMTCP_DEFAULT_TOCLIENT_CHUNK_SIZE 2560 -#define STREAMTCP_DEFAULT_MAX_SYN_QUEUED 10 -#define STREAMTCP_DEFAULT_MAX_SYNACK_QUEUED 5 +#define STREAMTCP_DEFAULT_PREALLOC 2048 +#define STREAMTCP_DEFAULT_MEMCAP (64 * 1024 * 1024) /* 64mb */ +#define STREAMTCP_DEFAULT_REASSEMBLY_MEMCAP (256 * 1024 * 1024) /* 256mb */ +#define STREAMTCP_DEFAULT_TOSERVER_CHUNK_SIZE 2560 +#define STREAMTCP_DEFAULT_TOCLIENT_CHUNK_SIZE 2560 +#define STREAMTCP_DEFAULT_MAX_SYN_QUEUED 10 +#define STREAMTCP_DEFAULT_MAX_SYNACK_QUEUED 5 static int StreamTcpHandleFin(ThreadVars *tv, StreamTcpThread *, TcpSession *, Packet *); -void StreamTcpReturnStreamSegments (TcpStream *); +void StreamTcpReturnStreamSegments(TcpStream *); void StreamTcpInitConfig(bool); int StreamTcpGetFlowState(void *); -void StreamTcpSetOSPolicy(TcpStream*, Packet*); +void StreamTcpSetOSPolicy(TcpStream *, Packet *); -static int StreamTcpValidateTimestamp(TcpSession * , Packet *); -static int StreamTcpHandleTimestamp(TcpSession * , Packet *); -static int StreamTcpValidateRst(TcpSession * , Packet *); +static int StreamTcpValidateTimestamp(TcpSession *, Packet *); +static int StreamTcpHandleTimestamp(TcpSession *, Packet *); +static int StreamTcpValidateRst(TcpSession *, Packet *); static inline int StreamTcpValidateAck(TcpSession *ssn, TcpStream *, Packet *); static int StreamTcpStateDispatch( ThreadVars *tv, Packet *p, StreamTcpThread *stt, TcpSession *ssn, const uint8_t state); @@ -107,7 +107,8 @@ extern thread_local uint64_t t_pcapcnt; extern int g_detect_disabled; PoolThread *ssn_pool = NULL; -static SCMutex ssn_pool_mutex = SCMUTEX_INITIALIZER; /**< init only, protect initializing and growing pool */ +static SCMutex ssn_pool_mutex = + SCMUTEX_INITIALIZER; /**< init only, protect initializing and growing pool */ #ifdef DEBUG static uint64_t ssn_pool_cnt = 0; /** counts ssns, protected by ssn_pool_mutex */ #endif @@ -123,8 +124,8 @@ void StreamTcpInitMemuse(void) void StreamTcpIncrMemuse(uint64_t size) { - (void) SC_ATOMIC_ADD(st_memuse, size); - SCLogDebug("STREAM %"PRIu64", incr %"PRIu64, StreamTcpMemuseCounter(), size); + (void)SC_ATOMIC_ADD(st_memuse, size); + SCLogDebug("STREAM %" PRIu64 ", incr %" PRIu64, StreamTcpMemuseCounter(), size); return; } @@ -137,7 +138,7 @@ void StreamTcpDecrMemuse(uint64_t size) } #endif - (void) SC_ATOMIC_SUB(st_memuse, size); + (void)SC_ATOMIC_SUB(st_memuse, size); #if defined(DEBUG_VALIDATION) && defined(UNITTESTS) if (RunmodeIsUnittests()) { @@ -145,7 +146,7 @@ void StreamTcpDecrMemuse(uint64_t size) BUG_ON(postsize > presize); } #endif - SCLogDebug("STREAM %"PRIu64", decr %"PRIu64, StreamTcpMemuseCounter(), size); + SCLogDebug("STREAM %" PRIu64 ", decr %" PRIu64, StreamTcpMemuseCounter(), size); return; } @@ -275,7 +276,7 @@ void StreamTcpSessionClear(void *ssnptr) * * \param p Packet used to identify the stream. */ -void StreamTcpSessionPktFree (Packet *p) +void StreamTcpSessionPktFree(Packet *p) { SCEnter(); @@ -306,7 +307,7 @@ static void *StreamTcpSessionPoolAlloc(void) return ptr; } -static int StreamTcpSessionPoolInit(void *data, void* initdata) +static int StreamTcpSessionPoolInit(void *data, void *initdata) { memset(data, 0, sizeof(TcpSession)); StreamTcpIncrMemuse((uint64_t)sizeof(TcpSession)); @@ -332,8 +333,8 @@ static void StreamTcpSessionPoolCleanup(void *s) */ static inline bool StreamTcpInlineDropInvalid(void) { - return ((stream_config.flags & STREAMTCP_INIT_FLAG_INLINE) - && (stream_config.flags & STREAMTCP_INIT_FLAG_DROP_INVALID)); + return ((stream_config.flags & STREAMTCP_INIT_FLAG_INLINE) && + (stream_config.flags & STREAMTCP_INIT_FLAG_DROP_INVALID)); } /* hack: stream random range code expects random values in range of 0-RAND_MAX, @@ -345,7 +346,7 @@ static int RandomGetWrap(void) do { r = RandomGet(); - } while(r >= ULONG_MAX - (ULONG_MAX % RAND_MAX)); + } while (r >= ULONG_MAX - (ULONG_MAX % RAND_MAX)); return r % RAND_MAX; } @@ -363,7 +364,7 @@ void StreamTcpInitConfig(bool quiet) SCLogDebug("Initializing Stream"); - memset(&stream_config, 0, sizeof(stream_config)); + memset(&stream_config, 0, sizeof(stream_config)); SC_ATOMIC_INIT(stream_config.memcap); SC_ATOMIC_INIT(stream_config.reassembly_memcap); @@ -382,14 +383,13 @@ void StreamTcpInitConfig(bool quiet) } else { stream_config.prealloc_sessions = STREAMTCP_DEFAULT_PREALLOC; if (ConfGetNode("stream.prealloc-sessions") != NULL) { - WarnInvalidConfEntry("stream.prealloc_sessions", - "%"PRIu32, - stream_config.prealloc_sessions); + WarnInvalidConfEntry( + "stream.prealloc_sessions", "%" PRIu32, stream_config.prealloc_sessions); } } } if (!quiet) { - SCLogConfig("stream \"prealloc-sessions\": %"PRIu32" (per thread)", + SCLogConfig("stream \"prealloc-sessions\": %" PRIu32 " (per thread)", stream_config.prealloc_sessions); } @@ -409,7 +409,7 @@ void StreamTcpInitConfig(bool quiet) } if (!quiet) { - SCLogConfig("stream \"memcap\": %"PRIu64, SC_ATOMIC_GET(stream_config.memcap)); + SCLogConfig("stream \"memcap\": %" PRIu64, SC_ATOMIC_GET(stream_config.memcap)); } int imidstream; @@ -417,7 +417,8 @@ void StreamTcpInitConfig(bool quiet) stream_config.midstream = imidstream != 0; if (!quiet) { - SCLogConfig("stream \"midstream\" session pickups: %s", stream_config.midstream ? "enabled" : "disabled"); + SCLogConfig("stream \"midstream\" session pickups: %s", + stream_config.midstream ? "enabled" : "disabled"); } int async_oneside; @@ -425,7 +426,8 @@ void StreamTcpInitConfig(bool quiet) stream_config.async_oneside = async_oneside != 0; if (!quiet) { - SCLogConfig("stream \"async-oneside\": %s", stream_config.async_oneside ? "enabled" : "disabled"); + SCLogConfig("stream \"async-oneside\": %s", + stream_config.async_oneside ? "enabled" : "disabled"); } int csum = 0; @@ -434,15 +436,15 @@ void StreamTcpInitConfig(bool quiet) if (csum == 1) { stream_config.flags |= STREAMTCP_INIT_FLAG_CHECKSUM_VALIDATION; } - /* Default is that we validate the checksum of all the packets */ + /* Default is that we validate the checksum of all the packets */ } else { stream_config.flags |= STREAMTCP_INIT_FLAG_CHECKSUM_VALIDATION; } if (!quiet) { SCLogConfig("stream \"checksum-validation\": %s", - stream_config.flags & STREAMTCP_INIT_FLAG_CHECKSUM_VALIDATION ? - "enabled" : "disabled"); + stream_config.flags & STREAMTCP_INIT_FLAG_CHECKSUM_VALIDATION ? "enabled" + : "disabled"); } const char *temp_stream_inline_str; @@ -473,8 +475,7 @@ void StreamTcpInitConfig(bool quiet) if (!quiet) { SCLogConfig("stream.\"inline\": %s", - stream_config.flags & STREAMTCP_INIT_FLAG_INLINE - ? "enabled" : "disabled"); + stream_config.flags & STREAMTCP_INIT_FLAG_INLINE ? "enabled" : "disabled"); } int bypass = 0; @@ -486,8 +487,7 @@ void StreamTcpInitConfig(bool quiet) if (!quiet) { SCLogConfig("stream \"bypass\": %s", - (stream_config.flags & STREAMTCP_INIT_FLAG_BYPASS) - ? "enabled" : "disabled"); + (stream_config.flags & STREAMTCP_INIT_FLAG_BYPASS) ? "enabled" : "disabled"); } int drop_invalid = 0; @@ -522,14 +522,14 @@ void StreamTcpInitConfig(bool quiet) stream_config.max_synack_queued = (uint8_t)STREAMTCP_DEFAULT_MAX_SYNACK_QUEUED; } if (!quiet) { - SCLogConfig("stream \"max-synack-queued\": %"PRIu8, stream_config.max_synack_queued); + SCLogConfig("stream \"max-synack-queued\": %" PRIu8, stream_config.max_synack_queued); } const char *temp_stream_reassembly_memcap_str; if (ConfGet("stream.reassembly.memcap", &temp_stream_reassembly_memcap_str) == 1) { uint64_t stream_reassembly_memcap_copy; - if (ParseSizeStringU64(temp_stream_reassembly_memcap_str, - &stream_reassembly_memcap_copy) < 0) { + if (ParseSizeStringU64(temp_stream_reassembly_memcap_str, &stream_reassembly_memcap_copy) < + 0) { SCLogError("Error parsing " "stream.reassembly.memcap " "from conf file - %s. Killing engine", @@ -539,18 +539,18 @@ void StreamTcpInitConfig(bool quiet) SC_ATOMIC_SET(stream_config.reassembly_memcap, stream_reassembly_memcap_copy); } } else { - SC_ATOMIC_SET(stream_config.reassembly_memcap , STREAMTCP_DEFAULT_REASSEMBLY_MEMCAP); + SC_ATOMIC_SET(stream_config.reassembly_memcap, STREAMTCP_DEFAULT_REASSEMBLY_MEMCAP); } if (!quiet) { - SCLogConfig("stream.reassembly \"memcap\": %"PRIu64"", - SC_ATOMIC_GET(stream_config.reassembly_memcap)); + SCLogConfig("stream.reassembly \"memcap\": %" PRIu64 "", + SC_ATOMIC_GET(stream_config.reassembly_memcap)); } const char *temp_stream_reassembly_depth_str; if (ConfGet("stream.reassembly.depth", &temp_stream_reassembly_depth_str) == 1) { - if (ParseSizeStringU32(temp_stream_reassembly_depth_str, - &stream_config.reassembly_depth) < 0) { + if (ParseSizeStringU32(temp_stream_reassembly_depth_str, &stream_config.reassembly_depth) < + 0) { SCLogError("Error parsing " "stream.reassembly.depth " "from conf file - %s. Killing engine", @@ -562,7 +562,7 @@ void StreamTcpInitConfig(bool quiet) } if (!quiet) { - SCLogConfig("stream.reassembly \"depth\": %"PRIu32"", stream_config.reassembly_depth); + SCLogConfig("stream.reassembly \"depth\": %" PRIu32 "", stream_config.reassembly_depth); } int randomize = 0; @@ -593,7 +593,7 @@ void StreamTcpInitConfig(bool quiet) if (ConfGet("stream.reassembly.toserver-chunk-size", &temp_stream_reassembly_toserver_chunk_size_str) == 1) { if (ParseSizeStringU16(temp_stream_reassembly_toserver_chunk_size_str, - &stream_config.reassembly_toserver_chunk_size) < 0) { + &stream_config.reassembly_toserver_chunk_size) < 0) { SCLogError("Error parsing " "stream.reassembly.toserver-chunk-size " "from conf file - %s. Killing engine", @@ -601,8 +601,7 @@ void StreamTcpInitConfig(bool quiet) exit(EXIT_FAILURE); } } else { - stream_config.reassembly_toserver_chunk_size = - STREAMTCP_DEFAULT_TOSERVER_CHUNK_SIZE; + stream_config.reassembly_toserver_chunk_size = STREAMTCP_DEFAULT_TOSERVER_CHUNK_SIZE; } if (randomize) { @@ -615,7 +614,7 @@ void StreamTcpInitConfig(bool quiet) if (ConfGet("stream.reassembly.toclient-chunk-size", &temp_stream_reassembly_toclient_chunk_size_str) == 1) { if (ParseSizeStringU16(temp_stream_reassembly_toclient_chunk_size_str, - &stream_config.reassembly_toclient_chunk_size) < 0) { + &stream_config.reassembly_toclient_chunk_size) < 0) { SCLogError("Error parsing " "stream.reassembly.toclient-chunk-size " "from conf file - %s. Killing engine", @@ -623,8 +622,7 @@ void StreamTcpInitConfig(bool quiet) exit(EXIT_FAILURE); } } else { - stream_config.reassembly_toclient_chunk_size = - STREAMTCP_DEFAULT_TOCLIENT_CHUNK_SIZE; + stream_config.reassembly_toclient_chunk_size = STREAMTCP_DEFAULT_TOCLIENT_CHUNK_SIZE; } if (randomize) { @@ -634,10 +632,10 @@ void StreamTcpInitConfig(bool quiet) rdrange / 100); } if (!quiet) { - SCLogConfig("stream.reassembly \"toserver-chunk-size\": %"PRIu16, - stream_config.reassembly_toserver_chunk_size); - SCLogConfig("stream.reassembly \"toclient-chunk-size\": %"PRIu16, - stream_config.reassembly_toclient_chunk_size); + SCLogConfig("stream.reassembly \"toserver-chunk-size\": %" PRIu16, + stream_config.reassembly_toserver_chunk_size); + SCLogConfig("stream.reassembly \"toclient-chunk-size\": %" PRIu16, + stream_config.reassembly_toclient_chunk_size); } int enable_raw = 1; @@ -675,12 +673,9 @@ void StreamTcpInitConfig(bool quiet) SCMutexLock(&ssn_pool_mutex); if (ssn_pool == NULL) { ssn_pool = PoolThreadInit(1, /* thread */ - 0, /* unlimited */ - stream_config.prealloc_sessions, - sizeof(TcpSession), - StreamTcpSessionPoolAlloc, - StreamTcpSessionPoolInit, NULL, - StreamTcpSessionPoolCleanup, NULL); + 0, /* unlimited */ + stream_config.prealloc_sessions, sizeof(TcpSession), StreamTcpSessionPoolAlloc, + StreamTcpSessionPoolInit, NULL, StreamTcpSessionPoolCleanup, NULL); } SCMutexUnlock(&ssn_pool_mutex); } @@ -699,7 +694,7 @@ void StreamTcpFreeConfig(bool quiet) SCMutexUnlock(&ssn_pool_mutex); SCMutexDestroy(&ssn_pool_mutex); - SCLogDebug("ssn_pool_cnt %"PRIu64"", ssn_pool_cnt); + SCLogDebug("ssn_pool_cnt %" PRIu64 "", ssn_pool_cnt); } /** \internal @@ -773,8 +768,7 @@ static TcpSession *StreamTcpNewSession(ThreadVars *tv, StreamTcpThread *stt, Pac return ssn; } -static void StreamTcpPacketSetState(Packet *p, TcpSession *ssn, - uint8_t state) +static void StreamTcpPacketSetState(Packet *p, TcpSession *ssn, uint8_t state) { if (state == ssn->state || PKT_IS_PSEUDOPKT(p)) return; @@ -784,7 +778,7 @@ static void StreamTcpPacketSetState(Packet *p, TcpSession *ssn, STREAM_PKT_FLAG_SET(p, STREAM_PKT_FLAG_STATE_UPDATE); /* update the flow state */ - switch(ssn->state) { + switch (ssn->state) { case TCP_ESTABLISHED: case TCP_FIN_WAIT1: case TCP_FIN_WAIT2: @@ -835,8 +829,7 @@ void StreamTcpSetOSPolicy(TcpStream *stream, Packet *p) else if (stream->os_policy == OS_POLICY_OLD_SOLARIS) stream->os_policy = OS_POLICY_SOLARIS; - SCLogDebug("Policy is %"PRIu8"", stream->os_policy); - + SCLogDebug("Policy is %" PRIu8 "", stream->os_policy); } /** @@ -846,39 +839,45 @@ void StreamTcpSetOSPolicy(TcpStream *stream, Packet *p) * \param stream stream to update * \param ack ACK value to test and set */ -#define StreamTcpUpdateLastAck(ssn, stream, ack) { \ - if (SEQ_GT((ack), (stream)->last_ack)) \ - { \ - SCLogDebug("ssn %p: last_ack set to %"PRIu32", moved %u forward", (ssn), (ack), (ack) - (stream)->last_ack); \ - if ((SEQ_LEQ((stream)->last_ack, (stream)->next_seq) && SEQ_GT((ack),(stream)->next_seq))) { \ - SCLogDebug("last_ack just passed next_seq: %u (was %u) > %u", (ack), (stream)->last_ack, (stream)->next_seq); \ - } else { \ - SCLogDebug("next_seq (%u) <> last_ack now %d", (stream)->next_seq, (int)(stream)->next_seq - (ack)); \ - }\ - (stream)->last_ack = (ack); \ - StreamTcpSackPruneList((stream)); \ - } else { \ - SCLogDebug("ssn %p: no update: ack %u, last_ack %"PRIu32", next_seq %u (state %u)", \ - (ssn), (ack), (stream)->last_ack, (stream)->next_seq, (ssn)->state); \ - }\ -} - -#define StreamTcpAsyncLastAckUpdate(ssn, stream) { \ - if ((ssn)->flags & STREAMTCP_FLAG_ASYNC) { \ - if (SEQ_GT((stream)->next_seq, (stream)->last_ack)) { \ - uint32_t ack_diff = (stream)->next_seq - (stream)->last_ack; \ - (stream)->last_ack += ack_diff; \ - SCLogDebug("ssn %p: ASYNC last_ack set to %"PRIu32", moved %u forward", \ - (ssn), (stream)->next_seq, ack_diff); \ - } \ - } \ -} - -#define StreamTcpUpdateNextSeq(ssn, stream, seq) { \ - (stream)->next_seq = seq; \ - SCLogDebug("ssn %p: next_seq %" PRIu32, (ssn), (stream)->next_seq); \ - StreamTcpAsyncLastAckUpdate((ssn), (stream)); \ -} +#define StreamTcpUpdateLastAck(ssn, stream, ack) \ + { \ + if (SEQ_GT((ack), (stream)->last_ack)) { \ + SCLogDebug("ssn %p: last_ack set to %" PRIu32 ", moved %u forward", (ssn), (ack), \ + (ack) - (stream)->last_ack); \ + if ((SEQ_LEQ((stream)->last_ack, (stream)->next_seq) && \ + SEQ_GT((ack), (stream)->next_seq))) { \ + SCLogDebug("last_ack just passed next_seq: %u (was %u) > %u", (ack), \ + (stream)->last_ack, (stream)->next_seq); \ + } else { \ + SCLogDebug("next_seq (%u) <> last_ack now %d", (stream)->next_seq, \ + (int)(stream)->next_seq - (ack)); \ + } \ + (stream)->last_ack = (ack); \ + StreamTcpSackPruneList((stream)); \ + } else { \ + SCLogDebug("ssn %p: no update: ack %u, last_ack %" PRIu32 ", next_seq %u (state %u)", \ + (ssn), (ack), (stream)->last_ack, (stream)->next_seq, (ssn)->state); \ + } \ + } + +#define StreamTcpAsyncLastAckUpdate(ssn, stream) \ + { \ + if ((ssn)->flags & STREAMTCP_FLAG_ASYNC) { \ + if (SEQ_GT((stream)->next_seq, (stream)->last_ack)) { \ + uint32_t ack_diff = (stream)->next_seq - (stream)->last_ack; \ + (stream)->last_ack += ack_diff; \ + SCLogDebug("ssn %p: ASYNC last_ack set to %" PRIu32 ", moved %u forward", (ssn), \ + (stream)->next_seq, ack_diff); \ + } \ + } \ + } + +#define StreamTcpUpdateNextSeq(ssn, stream, seq) \ + { \ + (stream)->next_seq = seq; \ + SCLogDebug("ssn %p: next_seq %" PRIu32, (ssn), (stream)->next_seq); \ + StreamTcpAsyncLastAckUpdate((ssn), (stream)); \ + } /** * \brief macro to update next_win only if the new value is higher @@ -887,20 +886,22 @@ void StreamTcpSetOSPolicy(TcpStream *stream, Packet *p) * \param stream stream to update * \param win window value to test and set */ -#define StreamTcpUpdateNextWin(ssn, stream, win) { \ - uint32_t sacked_size__ = StreamTcpSackedSize((stream)); \ - if (SEQ_GT(((win) + sacked_size__), (stream)->next_win)) { \ - (stream)->next_win = ((win) + sacked_size__); \ - SCLogDebug("ssn %p: next_win set to %"PRIu32, (ssn), (stream)->next_win); \ - } \ -} +#define StreamTcpUpdateNextWin(ssn, stream, win) \ + { \ + uint32_t sacked_size__ = StreamTcpSackedSize((stream)); \ + if (SEQ_GT(((win) + sacked_size__), (stream)->next_win)) { \ + (stream)->next_win = ((win) + sacked_size__); \ + SCLogDebug("ssn %p: next_win set to %" PRIu32, (ssn), (stream)->next_win); \ + } \ + } static inline void StreamTcpCloseSsnWithReset(Packet *p, TcpSession *ssn) { ssn->flags |= STREAMTCP_FLAG_CLOSED_BY_RST; StreamTcpPacketSetState(p, ssn, TCP_CLOSED); SCLogDebug("ssn %p: (state: %s) Reset received and state changed to " - "TCP_CLOSED", ssn, StreamTcpStateAsString(ssn->state)); + "TCP_CLOSED", + ssn, StreamTcpStateAsString(ssn->state)); } static int StreamTcpPacketIsRetransmission(TcpStream *stream, Packet *p) @@ -909,8 +910,8 @@ static int StreamTcpPacketIsRetransmission(TcpStream *stream, Packet *p) SCReturnInt(0); /* retransmission of already partially ack'd data */ - if (SEQ_LT(TCP_GET_SEQ(p), stream->last_ack) && SEQ_GT((TCP_GET_SEQ(p) + p->payload_len), stream->last_ack)) - { + if (SEQ_LT(TCP_GET_SEQ(p), stream->last_ack) && + SEQ_GT((TCP_GET_SEQ(p) + p->payload_len), stream->last_ack)) { StreamTcpSetEvent(p, STREAM_PKT_RETRANSMISSION); SCReturnInt(1); } @@ -1083,7 +1084,8 @@ static int StreamTcpPacketStateNone( /* set the state */ StreamTcpPacketSetState(p, ssn, TCP_SYN_RECV); SCLogDebug("ssn %p: =~ midstream picked ssn state is now " - "TCP_SYN_RECV", ssn); + "TCP_SYN_RECV", + ssn); ssn->flags |= STREAMTCP_FLAG_MIDSTREAM; /* Flag used to change the direct in the later stage in the session */ ssn->flags |= STREAMTCP_FLAG_MIDSTREAM_SYNACK; @@ -1114,27 +1116,25 @@ static int StreamTcpPacketStateNone( if (TCP_HAS_WSCALE(p)) { ssn->client.wscale = TCP_GET_WSCALE(p); ssn->server.wscale = TCP_WSCALE_MAX; - SCLogDebug("ssn %p: wscale enabled. client %u server %u", - ssn, ssn->client.wscale, ssn->server.wscale); + SCLogDebug("ssn %p: wscale enabled. client %u server %u", ssn, ssn->client.wscale, + ssn->server.wscale); } - SCLogDebug("ssn %p: ssn->client.isn %"PRIu32", ssn->client.next_seq" - " %"PRIu32", ssn->client.last_ack %"PRIu32"", ssn, - ssn->client.isn, ssn->client.next_seq, - ssn->client.last_ack); - SCLogDebug("ssn %p: ssn->server.isn %"PRIu32", ssn->server.next_seq" - " %"PRIu32", ssn->server.last_ack %"PRIu32"", ssn, - ssn->server.isn, ssn->server.next_seq, - ssn->server.last_ack); + SCLogDebug("ssn %p: ssn->client.isn %" PRIu32 ", ssn->client.next_seq" + " %" PRIu32 ", ssn->client.last_ack %" PRIu32 "", + ssn, ssn->client.isn, ssn->client.next_seq, ssn->client.last_ack); + SCLogDebug("ssn %p: ssn->server.isn %" PRIu32 ", ssn->server.next_seq" + " %" PRIu32 ", ssn->server.last_ack %" PRIu32 "", + ssn, ssn->server.isn, ssn->server.next_seq, ssn->server.last_ack); /* Set the timestamp value for both streams, if packet has timestamp * option enabled.*/ if (TCP_HAS_TS(p)) { ssn->server.last_ts = TCP_GET_TSVAL(p); ssn->client.last_ts = TCP_GET_TSECR(p); - SCLogDebug("ssn %p: ssn->server.last_ts %" PRIu32" " - "ssn->client.last_ts %" PRIu32"", ssn, - ssn->server.last_ts, ssn->client.last_ts); + SCLogDebug("ssn %p: ssn->server.last_ts %" PRIu32 " " + "ssn->client.last_ts %" PRIu32 "", + ssn, ssn->server.last_ts, ssn->client.last_ts); ssn->flags |= STREAMTCP_FLAG_TIMESTAMP; @@ -1152,7 +1152,8 @@ static int StreamTcpPacketStateNone( if (TCP_GET_SACKOK(p) == 1) { ssn->flags |= STREAMTCP_FLAG_SACKOK; SCLogDebug("ssn %p: SYN/ACK with SACK permitted, assuming " - "SACK permitted for both sides", ssn); + "SACK permitted for both sides", + ssn); } return 0; @@ -1211,15 +1212,16 @@ static int StreamTcpPacketStateNone( if (p->payload_len) { StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len)); SCLogDebug("ssn: %p (TFO) [len: %d] isn %u base_seq %u next_seq %u payload len %u", - ssn, p->tcpvars.tfo.len, ssn->client.isn, ssn->client.base_seq, ssn->client.next_seq, p->payload_len); + ssn, p->tcpvars.tfo.len, ssn->client.isn, ssn->client.base_seq, + ssn->client.next_seq, p->payload_len); StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->client, p); } } SCLogDebug("ssn %p: ssn->client.isn %" PRIu32 ", " - "ssn->client.next_seq %" PRIu32 ", ssn->client.last_ack " - "%"PRIu32"", ssn, ssn->client.isn, ssn->client.next_seq, - ssn->client.last_ack); + "ssn->client.next_seq %" PRIu32 ", ssn->client.last_ack " + "%" PRIu32 "", + ssn, ssn->client.isn, ssn->client.next_seq, ssn->client.last_ack); } else if (p->tcph->th_flags & TH_ACK) { /* Drop reason will only be used if midstream policy is set to fail closed */ @@ -1249,7 +1251,8 @@ static int StreamTcpPacketStateNone( /* set the state */ StreamTcpPacketSetState(p, ssn, TCP_ESTABLISHED); SCLogDebug("ssn %p: =~ midstream picked ssn state is now " - "TCP_ESTABLISHED", ssn); + "TCP_ESTABLISHED", + ssn); ssn->flags = STREAMTCP_FLAG_MIDSTREAM; ssn->flags |= STREAMTCP_FLAG_MIDSTREAM_ESTABLISHED; @@ -1270,8 +1273,8 @@ static int StreamTcpPacketStateNone( ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale; ssn->client.last_ack = TCP_GET_SEQ(p); ssn->client.next_win = ssn->client.last_ack + ssn->client.window; - SCLogDebug("ssn %p: ssn->client.isn %u, ssn->client.next_seq %u", - ssn, ssn->client.isn, ssn->client.next_seq); + SCLogDebug("ssn %p: ssn->client.isn %u, ssn->client.next_seq %u", ssn, ssn->client.isn, + ssn->client.next_seq); ssn->server.isn = TCP_GET_ACK(p) - 1; STREAMTCP_SET_RA_BASE_SEQ(&ssn->server, ssn->server.isn); @@ -1279,21 +1282,21 @@ static int StreamTcpPacketStateNone( ssn->server.last_ack = TCP_GET_ACK(p); ssn->server.next_win = ssn->server.last_ack; - SCLogDebug("ssn %p: ssn->client.next_win %"PRIu32", " - "ssn->server.next_win %"PRIu32"", ssn, - ssn->client.next_win, ssn->server.next_win); - SCLogDebug("ssn %p: ssn->client.last_ack %"PRIu32", " - "ssn->server.last_ack %"PRIu32"", ssn, - ssn->client.last_ack, ssn->server.last_ack); + SCLogDebug("ssn %p: ssn->client.next_win %" PRIu32 ", " + "ssn->server.next_win %" PRIu32 "", + ssn, ssn->client.next_win, ssn->server.next_win); + SCLogDebug("ssn %p: ssn->client.last_ack %" PRIu32 ", " + "ssn->server.last_ack %" PRIu32 "", + ssn, ssn->client.last_ack, ssn->server.last_ack); /* Set the timestamp value for both streams, if packet has timestamp * option enabled.*/ if (TCP_HAS_TS(p)) { ssn->client.last_ts = TCP_GET_TSVAL(p); ssn->server.last_ts = TCP_GET_TSECR(p); - SCLogDebug("ssn %p: ssn->server.last_ts %" PRIu32" " - "ssn->client.last_ts %" PRIu32"", ssn, - ssn->server.last_ts, ssn->client.last_ts); + SCLogDebug("ssn %p: ssn->server.last_ts %" PRIu32 " " + "ssn->client.last_ts %" PRIu32 "", + ssn, ssn->server.last_ts, ssn->client.last_ts); ssn->flags |= STREAMTCP_FLAG_TIMESTAMP; @@ -1357,12 +1360,8 @@ static TcpStateQueue *StreamTcp3whsFindSynAckBySynAck(TcpSession *ssn, Packet *p StreamTcp3whsSynAckToStateQueue(p, &search); while (q != NULL) { - if (search.flags == q->flags && - search.wscale == q->wscale && - search.win == q->win && - search.seq == q->seq && - search.ack == q->ack && - search.ts == q->ts) { + if (search.flags == q->flags && search.wscale == q->wscale && search.win == q->win && + search.seq == q->seq && search.ack == q->ack && search.ts == q->ts) { return q; } @@ -1415,8 +1414,7 @@ static TcpStateQueue *StreamTcp3whsFindSynAckByAck(TcpSession *ssn, Packet *p) TcpStateQueue *q = ssn->queue; while (q != NULL) { - if (seq == q->seq && - ack == q->ack) { + if (seq == q->seq && ack == q->ack) { return q; } @@ -1464,12 +1462,11 @@ static void StreamTcp3whsSynAckUpdate(TcpSession *ssn, Packet *p, TcpStateQueue /* Set the timestamp values used to validate the timestamp of * received packets.*/ if ((q->flags & STREAMTCP_QUEUE_FLAG_TS) && - (ssn->client.flags & STREAMTCP_STREAM_FLAG_TIMESTAMP)) - { + (ssn->client.flags & STREAMTCP_STREAM_FLAG_TIMESTAMP)) { ssn->server.last_ts = q->ts; - SCLogDebug("ssn %p: ssn->server.last_ts %" PRIu32" " - "ssn->client.last_ts %" PRIu32"", ssn, - ssn->server.last_ts, ssn->client.last_ts); + SCLogDebug("ssn %p: ssn->server.last_ts %" PRIu32 " " + "ssn->client.last_ts %" PRIu32 "", + ssn, ssn->server.last_ts, ssn->client.last_ts); ssn->flags |= STREAMTCP_FLAG_TIMESTAMP; ssn->server.last_pkt_ts = q->pkt_ts; if (ssn->server.last_ts == 0) @@ -1485,16 +1482,13 @@ static void StreamTcp3whsSynAckUpdate(TcpSession *ssn, Packet *p, TcpStateQueue /** check for the presence of the ws ptr to determine if we * support wscale at all */ - if ((ssn->flags & STREAMTCP_FLAG_SERVER_WSCALE) && - (q->flags & STREAMTCP_QUEUE_FLAG_WS)) - { + if ((ssn->flags & STREAMTCP_FLAG_SERVER_WSCALE) && (q->flags & STREAMTCP_QUEUE_FLAG_WS)) { ssn->client.wscale = q->wscale; } else { ssn->client.wscale = 0; } - if ((ssn->flags & STREAMTCP_FLAG_CLIENT_SACKOK) && - (q->flags & STREAMTCP_QUEUE_FLAG_SACK)) { + if ((ssn->flags & STREAMTCP_FLAG_CLIENT_SACKOK) && (q->flags & STREAMTCP_QUEUE_FLAG_SACK)) { ssn->flags |= STREAMTCP_FLAG_SACKOK; SCLogDebug("ssn %p: SACK permitted for session", ssn); } else { @@ -1503,24 +1497,22 @@ static void StreamTcp3whsSynAckUpdate(TcpSession *ssn, Packet *p, TcpStateQueue ssn->server.next_win = ssn->server.last_ack + ssn->server.window; ssn->client.next_win = ssn->client.last_ack + ssn->client.window; - SCLogDebug("ssn %p: ssn->server.next_win %" PRIu32 "", ssn, - ssn->server.next_win); - SCLogDebug("ssn %p: ssn->client.next_win %" PRIu32 "", ssn, - ssn->client.next_win); + SCLogDebug("ssn %p: ssn->server.next_win %" PRIu32 "", ssn, ssn->server.next_win); + SCLogDebug("ssn %p: ssn->client.next_win %" PRIu32 "", ssn, ssn->client.next_win); SCLogDebug("ssn %p: ssn->server.isn %" PRIu32 ", " - "ssn->server.next_seq %" PRIu32 ", " - "ssn->server.last_ack %" PRIu32 " " - "(ssn->client.last_ack %" PRIu32 ")", ssn, - ssn->server.isn, ssn->server.next_seq, - ssn->server.last_ack, ssn->client.last_ack); + "ssn->server.next_seq %" PRIu32 ", " + "ssn->server.last_ack %" PRIu32 " " + "(ssn->client.last_ack %" PRIu32 ")", + ssn, ssn->server.isn, ssn->server.next_seq, ssn->server.last_ack, ssn->client.last_ack); /* unset the 4WHS flag as we received this SYN/ACK as part of a * (so far) valid 3WHS */ if (ssn->flags & STREAMTCP_FLAG_4WHS) SCLogDebug("ssn %p: STREAMTCP_FLAG_4WHS unset, normal SYN/ACK" - " so considering 3WHS", ssn); + " so considering 3WHS", + ssn); - ssn->flags &=~ STREAMTCP_FLAG_4WHS; + ssn->flags &= ~STREAMTCP_FLAG_4WHS; } /** \internal @@ -1539,17 +1531,13 @@ static inline bool StateSynSentValidateTimestamp(TcpSession *ssn, Packet *p) TcpStream *receiver_stream = &ssn->client; const uint32_t ts_echo = TCP_GET_TSECR(p); if ((receiver_stream->flags & STREAMTCP_STREAM_FLAG_TIMESTAMP) != 0) { - if (receiver_stream->last_ts != 0 && ts_echo != 0 && - ts_echo != receiver_stream->last_ts) - { - SCLogDebug("ssn %p: BAD TSECR echo %u recv %u", ssn, - ts_echo, receiver_stream->last_ts); + if (receiver_stream->last_ts != 0 && ts_echo != 0 && ts_echo != receiver_stream->last_ts) { + SCLogDebug("ssn %p: BAD TSECR echo %u recv %u", ssn, ts_echo, receiver_stream->last_ts); return false; } } else { if (receiver_stream->last_ts == 0 && ts_echo != 0) { - SCLogDebug("ssn %p: BAD TSECR echo %u recv %u", ssn, - ts_echo, receiver_stream->last_ts); + SCLogDebug("ssn %p: BAD TSECR echo %u recv %u", ssn, ts_echo, receiver_stream->last_ts); return false; } } @@ -1750,8 +1738,8 @@ static int StreamTcpPacketStateSynSent( if (!(SEQ_EQ(TCP_GET_ACK(p), ssn->client.isn + 1))) { StreamTcpSetEvent(p, STREAM_3WHS_SYNACK_WITH_WRONG_ACK); SCLogDebug("ssn %p: ACK mismatch, packet ACK %" PRIu32 " != " - "%" PRIu32 " from stream", ssn, TCP_GET_ACK(p), - ssn->client.isn + 1); + "%" PRIu32 " from stream", + ssn, TCP_GET_ACK(p), ssn->client.isn + 1); return -1; } } else { @@ -1770,8 +1758,8 @@ static int StreamTcpPacketStateSynSent( } else { StreamTcpSetEvent(p, STREAM_3WHS_SYNACK_WITH_WRONG_ACK); SCLogDebug("ssn %p: (TFO) ACK mismatch, packet ACK %" PRIu32 " != " - "%" PRIu32 " from stream", ssn, TCP_GET_ACK(p), - ssn->client.next_seq); + "%" PRIu32 " from stream", + ssn, TCP_GET_ACK(p), ssn->client.next_seq); return -1; } ssn->flags |= STREAMTCP_FLAG_TCP_FAST_OPEN; @@ -1807,7 +1795,7 @@ static int StreamTcpPacketStateSynSent( /* clear ssn->queue on state change: TcpSession can be reused by SYN/ACK */ StreamTcp3wsFreeQueue(ssn); - StreamTcp3whsSynAckUpdate(ssn, p, /* no queue override */NULL); + StreamTcp3whsSynAckUpdate(ssn, p, /* no queue override */ NULL); return 0; } else if ((p->tcph->th_flags & (TH_SYN | TH_ACK)) == (TH_SYN | TH_ACK) && PKT_IS_TOSERVER(p)) { @@ -1937,7 +1925,8 @@ static int StreamTcpPacketStateSynSent( SCLogDebug("ssn %p: SYN packet on state SYN_SENT... resent", ssn); if (ssn->flags & STREAMTCP_FLAG_4WHS) { SCLogDebug("ssn %p: SYN packet on state SYN_SENT... resent of " - "4WHS SYN", ssn); + "4WHS SYN", + ssn); } if (PKT_IS_TOCLIENT(p)) { @@ -1987,15 +1976,13 @@ static int StreamTcpPacketStateSynSent( } SCLogDebug("ssn %p: 4WHS ssn->server.isn %" PRIu32 ", " - "ssn->server.next_seq %" PRIu32 ", " - "ssn->server.last_ack %"PRIu32"", ssn, - ssn->server.isn, ssn->server.next_seq, - ssn->server.last_ack); + "ssn->server.next_seq %" PRIu32 ", " + "ssn->server.last_ack %" PRIu32 "", + ssn, ssn->server.isn, ssn->server.next_seq, ssn->server.last_ack); SCLogDebug("ssn %p: 4WHS ssn->client.isn %" PRIu32 ", " - "ssn->client.next_seq %" PRIu32 ", " - "ssn->client.last_ack %"PRIu32"", ssn, - ssn->client.isn, ssn->client.next_seq, - ssn->client.last_ack); + "ssn->client.next_seq %" PRIu32 ", " + "ssn->client.last_ack %" PRIu32 "", + ssn, ssn->client.isn, ssn->client.next_seq, ssn->client.last_ack); } else if (PKT_IS_TOSERVER(p)) { /* on a SYN resend we queue up the SYN's until a SYN/ACK moves the state * to SYN_RECV. We update the ssn to the most recent, as it is most likely @@ -2029,8 +2016,8 @@ static int StreamTcpPacketStateSynSent( StreamTcpSetEvent(p, STREAM_3WHS_ASYNC_WRONG_SEQ); SCLogDebug("ssn %p: SEQ mismatch, packet SEQ %" PRIu32 " != " - "%" PRIu32 " from stream",ssn, TCP_GET_SEQ(p), - ssn->client.next_seq); + "%" PRIu32 " from stream", + ssn, TCP_GET_SEQ(p), ssn->client.next_seq); return -1; } @@ -2051,10 +2038,10 @@ static int StreamTcpPacketStateSynSent( ssn->server.next_win = ssn->server.last_ack; SCLogDebug("ssn %p: synsent => Asynchronous stream, packet SEQ" - " %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "), " - "ssn->client.next_seq %" PRIu32 "" - ,ssn, TCP_GET_SEQ(p), p->payload_len, TCP_GET_SEQ(p) - + p->payload_len, ssn->client.next_seq); + " %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "), " + "ssn->client.next_seq %" PRIu32 "", + ssn, TCP_GET_SEQ(p), p->payload_len, TCP_GET_SEQ(p) + p->payload_len, + ssn->client.next_seq); /* if SYN had wscale, assume it to be supported. Otherwise * we know it not to be supported. */ @@ -2064,9 +2051,7 @@ static int StreamTcpPacketStateSynSent( /* Set the timestamp values used to validate the timestamp of * received packets.*/ - if (TCP_HAS_TS(p) && - (ssn->client.flags & STREAMTCP_STREAM_FLAG_TIMESTAMP)) - { + if (TCP_HAS_TS(p) && (ssn->client.flags & STREAMTCP_STREAM_FLAG_TIMESTAMP)) { ssn->flags |= STREAMTCP_FLAG_TIMESTAMP; ssn->client.flags &= ~STREAMTCP_STREAM_FLAG_TIMESTAMP; ssn->client.last_pkt_ts = SCTIME_SECS(p->ts); @@ -2121,20 +2106,18 @@ static int StreamTcpPacketStateSynRecv( if (PKT_IS_TOSERVER(p)) { if ((ssn->server.os_policy == OS_POLICY_LINUX) || (ssn->server.os_policy == OS_POLICY_OLD_LINUX) || - (ssn->server.os_policy == OS_POLICY_SOLARIS)) - { + (ssn->server.os_policy == OS_POLICY_SOLARIS)) { reset = false; SCLogDebug("Detection evasion has been attempted, so" - " not resetting the connection !!"); + " not resetting the connection !!"); } } else { if ((ssn->client.os_policy == OS_POLICY_LINUX) || (ssn->client.os_policy == OS_POLICY_OLD_LINUX) || - (ssn->client.os_policy == OS_POLICY_SOLARIS)) - { + (ssn->client.os_policy == OS_POLICY_SOLARIS)) { reset = false; SCLogDebug("Detection evasion has been attempted, so" - " not resetting the connection !!"); + " not resetting the connection !!"); } } } @@ -2157,8 +2140,8 @@ static int StreamTcpPacketStateSynRecv( if ((StreamTcpHandleFin(tv, stt, ssn, p)) == -1) return -1; - /* SYN/ACK */ - } else if ((p->tcph->th_flags & (TH_SYN|TH_ACK)) == (TH_SYN|TH_ACK)) { + /* SYN/ACK */ + } else if ((p->tcph->th_flags & (TH_SYN | TH_ACK)) == (TH_SYN | TH_ACK)) { SCLogDebug("ssn %p: SYN/ACK packet on state SYN_RECV. resent", ssn); if (PKT_IS_TOSERVER(p)) { @@ -2172,8 +2155,8 @@ static int StreamTcpPacketStateSynRecv( * received SYN/ACK packet. */ if (!(SEQ_EQ(TCP_GET_ACK(p), ssn->client.last_ack))) { SCLogDebug("ssn %p: ACK mismatch, packet ACK %" PRIu32 " != " - "%" PRIu32 " from stream", ssn, TCP_GET_ACK(p), - ssn->client.isn + 1); + "%" PRIu32 " from stream", + ssn, TCP_GET_ACK(p), ssn->client.isn + 1); StreamTcpSetEvent(p, STREAM_3WHS_SYNACK_RESEND_WITH_DIFFERENT_ACK); return -1; @@ -2183,8 +2166,8 @@ static int StreamTcpPacketStateSynRecv( * received SYN/ACK packet, server resend with different ISN. */ if (!(SEQ_EQ(TCP_GET_SEQ(p), ssn->server.isn))) { SCLogDebug("ssn %p: SEQ mismatch, packet SEQ %" PRIu32 " != " - "%" PRIu32 " from stream", ssn, TCP_GET_SEQ(p), - ssn->client.isn); + "%" PRIu32 " from stream", + ssn, TCP_GET_SEQ(p), ssn->client.isn); if (StreamTcp3whsQueueSynAck(ssn, p) == -1) return -1; @@ -2214,13 +2197,13 @@ static int StreamTcpPacketStateSynRecv( TcpStateQueue *q = StreamTcp3whsFindSynAckByAck(ssn, p); if (q != NULL) { SCLogDebug("ssn %p: here we update state against queued SYN/ACK", ssn); - StreamTcp3whsSynAckUpdate(ssn, p, /* using queue to update state */q); + StreamTcp3whsSynAckUpdate(ssn, p, /* using queue to update state */ q); } else { - SCLogDebug("ssn %p: none found, now checking ACK against original SYN/ACK (state)", ssn); + SCLogDebug("ssn %p: none found, now checking ACK against original SYN/ACK (state)", + ssn); } } - /* If the timestamp option is enabled for both the streams, then * validate the received packet timestamp value against the * stream->last_ts. If the timestamp is valid then process the @@ -2232,7 +2215,7 @@ static int StreamTcpPacketStateSynRecv( } if ((ssn->flags & STREAMTCP_FLAG_4WHS) && PKT_IS_TOCLIENT(p)) { - SCLogDebug("ssn %p: ACK received on 4WHS session",ssn); + SCLogDebug("ssn %p: ACK received on 4WHS session", ssn); if (!(SEQ_EQ(TCP_GET_SEQ(p), ssn->server.next_seq))) { SCLogDebug("ssn %p: 4WHS wrong seq nr on packet", ssn); @@ -2248,8 +2231,8 @@ static int StreamTcpPacketStateSynRecv( SCLogDebug("4WHS normal pkt"); SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ " - "%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len, - TCP_GET_SEQ(p), TCP_GET_ACK(p)); + "%" PRIu32 ", ACK %" PRIu32 "", + ssn, p->payload_len, TCP_GET_SEQ(p), TCP_GET_ACK(p)); if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) { StreamTcpHandleTimestamp(ssn, p); @@ -2266,8 +2249,8 @@ static int StreamTcpPacketStateSynRecv( StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->server, p); SCLogDebug("ssn %p: ssn->client.next_win %" PRIu32 ", " - "ssn->client.last_ack %"PRIu32"", ssn, - ssn->client.next_win, ssn->client.last_ack); + "ssn->client.last_ack %" PRIu32 "", + ssn, ssn->client.next_win, ssn->client.last_ack); return 0; } @@ -2282,10 +2265,11 @@ static int StreamTcpPacketStateSynRecv( * direction */ if (ssn->flags & STREAMTCP_FLAG_MIDSTREAM_SYNACK) { SCLogDebug("ssn %p: ACK received on midstream SYN/ACK " - "pickup session",ssn); + "pickup session", + ssn); /* fall through */ } else if (ssn->flags & STREAMTCP_FLAG_TCP_FAST_OPEN) { - SCLogDebug("ssn %p: ACK received on TFO session",ssn); + SCLogDebug("ssn %p: ACK received on TFO session", ssn); /* fall through */ } else { @@ -2299,8 +2283,7 @@ static int StreamTcpPacketStateSynRecv( * careful. */ if (StreamTcpInlineMode()) { - if (p->payload_len > 0 && - SEQ_EQ(TCP_GET_ACK(p), ssn->client.last_ack) && + if (p->payload_len > 0 && SEQ_EQ(TCP_GET_ACK(p), ssn->client.last_ack) && SEQ_EQ(TCP_GET_SEQ(p), ssn->server.next_seq)) { /* packet loss is possible but unlikely here */ SCLogDebug("ssn %p: possible data injection", ssn); @@ -2308,8 +2291,7 @@ static int StreamTcpPacketStateSynRecv( return -1; } - SCLogDebug("ssn %p: ACK received in the wrong direction", - ssn); + SCLogDebug("ssn %p: ACK received in the wrong direction", ssn); StreamTcpSetEvent(p, STREAM_3WHS_ACK_IN_WRONG_DIR); return -1; } @@ -2318,8 +2300,8 @@ static int StreamTcpPacketStateSynRecv( } SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ %" PRIu32 "" - ", ACK %" PRIu32 "", ssn, p->payload_len, TCP_GET_SEQ(p), - TCP_GET_ACK(p)); + ", ACK %" PRIu32 "", + ssn, p->payload_len, TCP_GET_SEQ(p), TCP_GET_ACK(p)); /* Check both seq and ack number before accepting the packet and changing to ESTABLISHED state */ @@ -2342,8 +2324,7 @@ static int StreamTcpPacketStateSynRecv( if (ssn->flags & STREAMTCP_FLAG_MIDSTREAM) { ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale; ssn->client.next_win = ssn->client.last_ack + ssn->client.window; - ssn->server.next_win = ssn->server.last_ack + - ssn->server.window; + ssn->server.next_win = ssn->server.last_ack + ssn->server.window; if (!(ssn->flags & STREAMTCP_FLAG_MIDSTREAM_SYNACK)) { /* window scaling for midstream pickups, we can't do much * other than assume that it's set to the max value: 14 */ @@ -2385,10 +2366,10 @@ static int StreamTcpPacketStateSynRecv( } SCLogDebug("ssn %p: synrecv => Asynchronous stream, packet SEQ" - " %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "), " - "ssn->server.next_seq %" PRIu32 - , ssn, TCP_GET_SEQ(p), p->payload_len, TCP_GET_SEQ(p) - + p->payload_len, ssn->server.next_seq); + " %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "), " + "ssn->server.next_seq %" PRIu32, + ssn, TCP_GET_SEQ(p), p->payload_len, TCP_GET_SEQ(p) + p->payload_len, + ssn->server.next_seq); StreamTcpPacketSetState(p, ssn, TCP_ESTABLISHED); SCLogDebug("ssn %p: =~ ssn state is now TCP_ESTABLISHED", ssn); @@ -2400,8 +2381,7 @@ static int StreamTcpPacketStateSynRecv( likely to avoid the detection */ } else if (SEQ_EQ(TCP_GET_SEQ(p), ssn->client.next_seq)) { ssn->flags |= STREAMTCP_FLAG_DETECTION_EVASION_ATTEMPT; - SCLogDebug("ssn %p: wrong ack nr on packet, possible evasion!!", - ssn); + SCLogDebug("ssn %p: wrong ack nr on packet, possible evasion!!", ssn); StreamTcpSetEvent(p, STREAM_3WHS_RIGHT_SEQ_WRONG_ACK_EVASION); return -1; @@ -2447,14 +2427,14 @@ static int StreamTcpPacketStateSynRecv( ssn->client.next_seq = TCP_GET_SEQ(p) + p->payload_len; StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p)); - SCLogDebug("ssn %p: ACK for missing data: ssn->client.next_seq %u", ssn, ssn->client.next_seq); + SCLogDebug("ssn %p: ACK for missing data: ssn->client.next_seq %u", ssn, + ssn->client.next_seq); ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale; ssn->server.next_win = ssn->server.last_ack + ssn->server.window; if (ssn->flags & STREAMTCP_FLAG_MIDSTREAM) { ssn->client.window = TCP_GET_WINDOW(p); - ssn->server.next_win = ssn->server.last_ack + - ssn->server.window; + ssn->server.next_win = ssn->server.last_ack + ssn->server.window; /* window scaling for midstream pickups, we can't do much * other than assume that it's set to the max value: 14 */ ssn->server.wscale = TCP_WSCALE_MAX; @@ -2496,8 +2476,8 @@ static int StreamTcpPacketStateSynRecv( } SCLogDebug("ssn %p: ssn->server.next_win %" PRIu32 ", " - "ssn->server.last_ack %"PRIu32"", ssn, - ssn->server.next_win, ssn->server.last_ack); + "ssn->server.last_ack %" PRIu32 "", + ssn, ssn->server.next_win, ssn->server.last_ack); } else { SCLogDebug("ssn %p: default case", ssn); } @@ -2522,8 +2502,8 @@ static int HandleEstablishedPacketToServer( ThreadVars *tv, TcpSession *ssn, Packet *p, StreamTcpThread *stt) { SCLogDebug("ssn %p: =+ pkt (%" PRIu32 ") is to server: SEQ %" PRIu32 "," - "ACK %" PRIu32 ", WIN %"PRIu16"", ssn, p->payload_len, - TCP_GET_SEQ(p), TCP_GET_ACK(p), TCP_GET_WINDOW(p)); + "ACK %" PRIu32 ", WIN %" PRIu16 "", + ssn, p->payload_len, TCP_GET_SEQ(p), TCP_GET_ACK(p), TCP_GET_WINDOW(p)); const bool has_ack = (p->tcph->th_flags & TH_ACK) != 0; if (has_ack) { @@ -2543,8 +2523,8 @@ static int HandleEstablishedPacketToServer( (TCP_GET_SEQ(p) == (ssn->client.next_seq - 1))) { SCLogDebug("ssn %p: pkt is keep alive", ssn); - /* normal pkt */ - } else if (!(SEQ_GEQ((TCP_GET_SEQ(p)+p->payload_len), ssn->client.last_ack))) { + /* normal pkt */ + } else if (!(SEQ_GEQ((TCP_GET_SEQ(p) + p->payload_len), ssn->client.last_ack))) { if (ssn->flags & STREAMTCP_FLAG_ASYNC) { SCLogDebug("ssn %p: server => Asynchronous stream, packet SEQ" " %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 ")," @@ -2561,10 +2541,10 @@ static int HandleEstablishedPacketToServer( } else if (SEQ_EQ(ssn->client.next_seq, TCP_GET_SEQ(p)) && stream_config.async_oneside && (ssn->flags & STREAMTCP_FLAG_MIDSTREAM)) { SCLogDebug("ssn %p: server => Asynchronous stream, packet SEQ." - " %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "), " - "ssn->client.last_ack %" PRIu32 ", ssn->client.next_win " - "%" PRIu32 "(%"PRIu32")", ssn, TCP_GET_SEQ(p), - p->payload_len, TCP_GET_SEQ(p) + p->payload_len, + " %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "), " + "ssn->client.last_ack %" PRIu32 ", ssn->client.next_win " + "%" PRIu32 "(%" PRIu32 ")", + ssn, TCP_GET_SEQ(p), p->payload_len, TCP_GET_SEQ(p) + p->payload_len, ssn->client.last_ack, ssn->client.next_win, TCP_GET_SEQ(p) + p->payload_len - ssn->client.next_win); @@ -2577,10 +2557,10 @@ static int HandleEstablishedPacketToServer( } else if (SEQ_EQ(ssn->client.last_ack, (ssn->client.isn + 1)) && stream_config.async_oneside && (ssn->flags & STREAMTCP_FLAG_MIDSTREAM)) { SCLogDebug("ssn %p: server => Asynchronous stream, packet SEQ" - " %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "), " - "ssn->client.last_ack %" PRIu32 ", ssn->client.next_win " - "%" PRIu32 "(%"PRIu32")", ssn, TCP_GET_SEQ(p), - p->payload_len, TCP_GET_SEQ(p) + p->payload_len, + " %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "), " + "ssn->client.last_ack %" PRIu32 ", ssn->client.next_win " + "%" PRIu32 "(%" PRIu32 ")", + ssn, TCP_GET_SEQ(p), p->payload_len, TCP_GET_SEQ(p) + p->payload_len, ssn->client.last_ack, ssn->client.next_win, TCP_GET_SEQ(p) + p->payload_len - ssn->client.next_win); @@ -2590,9 +2570,9 @@ static int HandleEstablishedPacketToServer( StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_SEQ(p)); ssn->flags |= STREAMTCP_FLAG_ASYNC; - /* if last ack is beyond next_seq, we have accepted ack's for missing data. - * In this case we do accept the data before last_ack if it is (partly) - * beyond next seq */ + /* if last ack is beyond next_seq, we have accepted ack's for missing data. + * In this case we do accept the data before last_ack if it is (partly) + * beyond next seq */ } else if (SEQ_GT(ssn->client.last_ack, ssn->client.next_seq) && SEQ_GT((TCP_GET_SEQ(p) + p->payload_len), ssn->client.next_seq)) { SCLogDebug("ssn %p: PKT SEQ %" PRIu32 " payload_len %" PRIu16 @@ -2602,10 +2582,10 @@ static int HandleEstablishedPacketToServer( ssn->client.next_seq); } else { SCLogDebug("ssn %p: server => SEQ before last_ack, packet SEQ" - " %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "), " - "ssn->client.last_ack %" PRIu32 ", ssn->client.next_win " - "%" PRIu32 "(%"PRIu32")", ssn, TCP_GET_SEQ(p), - p->payload_len, TCP_GET_SEQ(p) + p->payload_len, + " %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "), " + "ssn->client.last_ack %" PRIu32 ", ssn->client.next_win " + "%" PRIu32 "(%" PRIu32 ")", + ssn, TCP_GET_SEQ(p), p->payload_len, TCP_GET_SEQ(p) + p->payload_len, ssn->client.last_ack, ssn->client.next_win, TCP_GET_SEQ(p) + p->payload_len - ssn->client.next_win); @@ -2632,14 +2612,13 @@ static int HandleEstablishedPacketToServer( if (zerowindowprobe) { SCLogDebug("ssn %p: zero window probe, skipping oow check", ssn); } else if (SEQ_LEQ(TCP_GET_SEQ(p) + p->payload_len, ssn->client.next_win) || - (ssn->flags & (STREAMTCP_FLAG_MIDSTREAM|STREAMTCP_FLAG_ASYNC))) - { - SCLogDebug("ssn %p: seq %"PRIu32" in window, ssn->client.next_win " - "%" PRIu32 "", ssn, TCP_GET_SEQ(p), ssn->client.next_win); + (ssn->flags & (STREAMTCP_FLAG_MIDSTREAM | STREAMTCP_FLAG_ASYNC))) { + SCLogDebug("ssn %p: seq %" PRIu32 " in window, ssn->client.next_win " + "%" PRIu32 "", + ssn, TCP_GET_SEQ(p), ssn->client.next_win); ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale; - SCLogDebug("ssn %p: ssn->server.window %"PRIu32"", ssn, - ssn->server.window); + SCLogDebug("ssn %p: ssn->server.window %" PRIu32 "", ssn, ssn->server.window); /* Check if the ACK value is sane and inside the window limit */ if (p->tcph->th_flags & TH_ACK) { @@ -2651,7 +2630,8 @@ static int HandleEstablishedPacketToServer( } } - SCLogDebug("ack %u last_ack %u next_seq %u", TCP_GET_ACK(p), ssn->server.last_ack, ssn->server.next_seq); + SCLogDebug("ack %u last_ack %u next_seq %u", TCP_GET_ACK(p), ssn->server.last_ack, + ssn->server.next_seq); if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) { StreamTcpHandleTimestamp(ssn, p); @@ -2667,10 +2647,10 @@ static int HandleEstablishedPacketToServer( } else { SCLogDebug("ssn %p: toserver => SEQ out of window, packet SEQ " - "%" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 ")," - "ssn->client.last_ack %" PRIu32 ", ssn->client.next_win " - "%" PRIu32 "(%"PRIu32")", ssn, TCP_GET_SEQ(p), - p->payload_len, TCP_GET_SEQ(p) + p->payload_len, + "%" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 ")," + "ssn->client.last_ack %" PRIu32 ", ssn->client.next_win " + "%" PRIu32 "(%" PRIu32 ")", + ssn, TCP_GET_SEQ(p), p->payload_len, TCP_GET_SEQ(p) + p->payload_len, ssn->client.last_ack, ssn->client.next_win, (TCP_GET_SEQ(p) + p->payload_len) - ssn->client.next_win); SCLogDebug("ssn %p: window %u sacked %u", ssn, ssn->client.window, @@ -2698,8 +2678,8 @@ static int HandleEstablishedPacketToClient( ThreadVars *tv, TcpSession *ssn, Packet *p, StreamTcpThread *stt) { SCLogDebug("ssn %p: =+ pkt (%" PRIu32 ") is to client: SEQ %" PRIu32 "," - " ACK %" PRIu32 ", WIN %"PRIu16"", ssn, p->payload_len, - TCP_GET_SEQ(p), TCP_GET_ACK(p), TCP_GET_WINDOW(p)); + " ACK %" PRIu32 ", WIN %" PRIu16 "", + ssn, p->payload_len, TCP_GET_SEQ(p), TCP_GET_ACK(p), TCP_GET_WINDOW(p)); const bool has_ack = (p->tcph->th_flags & TH_ACK) != 0; if (has_ack) { @@ -2717,13 +2697,13 @@ static int HandleEstablishedPacketToClient( /* To get the server window value from the servers packet, when connection is picked up as midstream */ if ((ssn->flags & STREAMTCP_FLAG_MIDSTREAM) && - (ssn->flags & STREAMTCP_FLAG_MIDSTREAM_ESTABLISHED)) - { + (ssn->flags & STREAMTCP_FLAG_MIDSTREAM_ESTABLISHED)) { ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale; ssn->server.next_win = ssn->server.last_ack + ssn->server.window; ssn->flags &= ~STREAMTCP_FLAG_MIDSTREAM_ESTABLISHED; SCLogDebug("ssn %p: adjusted midstream ssn->server.next_win to " - "%" PRIu32 "", ssn, ssn->server.next_win); + "%" PRIu32 "", + ssn, ssn->server.next_win); } /* check for Keep Alive */ @@ -2731,8 +2711,8 @@ static int HandleEstablishedPacketToClient( (TCP_GET_SEQ(p) == (ssn->server.next_seq - 1))) { SCLogDebug("ssn %p: pkt is keep alive", ssn); - /* normal pkt */ - } else if (!(SEQ_GEQ((TCP_GET_SEQ(p)+p->payload_len), ssn->server.last_ack))) { + /* normal pkt */ + } else if (!(SEQ_GEQ((TCP_GET_SEQ(p) + p->payload_len), ssn->server.last_ack))) { if (ssn->flags & STREAMTCP_FLAG_ASYNC) { SCLogDebug("ssn %p: client => Asynchronous stream, packet SEQ" @@ -2745,21 +2725,21 @@ static int HandleEstablishedPacketToClient( ssn->server.last_ack = TCP_GET_SEQ(p); - /* if last ack is beyond next_seq, we have accepted ack's for missing data. - * In this case we do accept the data before last_ack if it is (partly) - * beyond next seq */ + /* if last ack is beyond next_seq, we have accepted ack's for missing data. + * In this case we do accept the data before last_ack if it is (partly) + * beyond next seq */ } else if (SEQ_GT(ssn->server.last_ack, ssn->server.next_seq) && - SEQ_GT((TCP_GET_SEQ(p)+p->payload_len),ssn->server.next_seq)) - { + SEQ_GT((TCP_GET_SEQ(p) + p->payload_len), ssn->server.next_seq)) { SCLogDebug("ssn %p: PKT SEQ %" PRIu32 " payload_len %" PRIu16 " before last_ack %" PRIu32 ", after next_seq %" PRIu32 ":" " acked data that we haven't seen before", ssn, TCP_GET_SEQ(p), p->payload_len, ssn->server.last_ack, ssn->server.next_seq); } else { - SCLogDebug("ssn %p: PKT SEQ %"PRIu32" payload_len %"PRIu16 - " before last_ack %"PRIu32". next_seq %"PRIu32, - ssn, TCP_GET_SEQ(p), p->payload_len, ssn->server.last_ack, ssn->server.next_seq); + SCLogDebug("ssn %p: PKT SEQ %" PRIu32 " payload_len %" PRIu16 + " before last_ack %" PRIu32 ". next_seq %" PRIu32, + ssn, TCP_GET_SEQ(p), p->payload_len, ssn->server.last_ack, + ssn->server.next_seq); StreamTcpSetEvent(p, STREAM_EST_PKT_BEFORE_LAST_ACK); return -1; } @@ -2783,13 +2763,12 @@ static int HandleEstablishedPacketToClient( if (zerowindowprobe) { SCLogDebug("ssn %p: zero window probe, skipping oow check", ssn); } else if (SEQ_LEQ(TCP_GET_SEQ(p) + p->payload_len, ssn->server.next_win) || - (ssn->flags & (STREAMTCP_FLAG_MIDSTREAM|STREAMTCP_FLAG_ASYNC))) - { - SCLogDebug("ssn %p: seq %"PRIu32" in window, ssn->server.next_win " - "%" PRIu32 "", ssn, TCP_GET_SEQ(p), ssn->server.next_win); + (ssn->flags & (STREAMTCP_FLAG_MIDSTREAM | STREAMTCP_FLAG_ASYNC))) { + SCLogDebug("ssn %p: seq %" PRIu32 " in window, ssn->server.next_win " + "%" PRIu32 "", + ssn, TCP_GET_SEQ(p), ssn->server.next_win); ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale; - SCLogDebug("ssn %p: ssn->client.window %"PRIu32"", ssn, - ssn->client.window); + SCLogDebug("ssn %p: ssn->client.window %" PRIu32 "", ssn, ssn->client.window); if (p->tcph->th_flags & TH_ACK) { StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p)); @@ -2813,10 +2792,10 @@ static int HandleEstablishedPacketToClient( SCLogDebug("ssn %p: client => SEQ out of window, packet SEQ" "%" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 ")," " ssn->server.last_ack %" PRIu32 ", ssn->server.next_win " - "%" PRIu32 "(%"PRIu32")", ssn, TCP_GET_SEQ(p), - p->payload_len, TCP_GET_SEQ(p) + p->payload_len, - ssn->server.last_ack, ssn->server.next_win, - TCP_GET_SEQ(p) + p->payload_len - ssn->server.next_win); + "%" PRIu32 "(%" PRIu32 ")", + ssn, TCP_GET_SEQ(p), p->payload_len, TCP_GET_SEQ(p) + p->payload_len, + ssn->server.last_ack, ssn->server.next_win, + TCP_GET_SEQ(p) + p->payload_len - ssn->server.next_win); StreamTcpSetEvent(p, STREAM_EST_PACKET_OUT_OF_WINDOW); return -1; } @@ -3056,16 +3035,15 @@ static int StreamTcpPacketStateEstablished( ssn->server.next_seq = TCP_GET_ACK(p); ssn->client.next_seq = TCP_GET_SEQ(p) + p->payload_len; - SCLogDebug("ssn %p: ssn->server.next_seq %" PRIu32 "", ssn, - ssn->server.next_seq); + SCLogDebug("ssn %p: ssn->server.next_seq %" PRIu32 "", ssn, ssn->server.next_seq); ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale; if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->server, p) == 0) - StreamTcpUpdateLastAck(ssn, &ssn->server, - StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p))); + StreamTcpUpdateLastAck( + ssn, &ssn->server, StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p))); - StreamTcpUpdateLastAck(ssn, &ssn->client, - StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p))); + StreamTcpUpdateLastAck( + ssn, &ssn->client, StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p))); if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) { StreamTcpHandleTimestamp(ssn, p); @@ -3073,8 +3051,8 @@ static int StreamTcpPacketStateEstablished( StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->client, p); SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK " - "%" PRIu32 "", ssn, ssn->client.next_seq, - ssn->server.last_ack); + "%" PRIu32 "", + ssn, ssn->client.next_seq, ssn->server.last_ack); /* don't return packets to pools here just yet, the pseudo * packet will take care, otherwise the normal session @@ -3085,16 +3063,15 @@ static int StreamTcpPacketStateEstablished( ssn->server.next_seq = TCP_GET_SEQ(p) + p->payload_len + 1; ssn->client.next_seq = TCP_GET_ACK(p); - SCLogDebug("ssn %p: ssn->server.next_seq %" PRIu32 "", ssn, - ssn->server.next_seq); + SCLogDebug("ssn %p: ssn->server.next_seq %" PRIu32 "", ssn, ssn->server.next_seq); ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale; if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->client, p) == 0) - StreamTcpUpdateLastAck(ssn, &ssn->client, - StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p))); + StreamTcpUpdateLastAck( + ssn, &ssn->client, StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p))); - StreamTcpUpdateLastAck(ssn, &ssn->server, - StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p))); + StreamTcpUpdateLastAck( + ssn, &ssn->server, StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p))); if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) { StreamTcpHandleTimestamp(ssn, p); @@ -3102,8 +3079,8 @@ static int StreamTcpPacketStateEstablished( StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->server, p); SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK " - "%" PRIu32 "", ssn, ssn->server.next_seq, - ssn->client.last_ack); + "%" PRIu32 "", + ssn, ssn->server.next_seq, ssn->client.last_ack); /* don't return packets to pools here just yet, the pseudo * packet will take care, otherwise the normal session @@ -3117,18 +3094,17 @@ static int StreamTcpPacketStateEstablished( } SCLogDebug("ssn (%p: FIN received SEQ" - " %" PRIu32 ", last ACK %" PRIu32 ", next win %"PRIu32"," - " win %" PRIu32 "", ssn, ssn->server.next_seq, - ssn->client.last_ack, ssn->server.next_win, + " %" PRIu32 ", last ACK %" PRIu32 ", next win %" PRIu32 "," + " win %" PRIu32 "", + ssn, ssn->server.next_seq, ssn->client.last_ack, ssn->server.next_win, ssn->server.window); if ((StreamTcpHandleFin(tv, stt, ssn, p)) == -1) return -1; - /* SYN/ACK */ - } else if ((p->tcph->th_flags & (TH_SYN|TH_ACK)) == (TH_SYN|TH_ACK)) { - SCLogDebug("ssn %p: SYN/ACK packet on state ESTABLISHED... resent", - ssn); + /* SYN/ACK */ + } else if ((p->tcph->th_flags & (TH_SYN | TH_ACK)) == (TH_SYN | TH_ACK)) { + SCLogDebug("ssn %p: SYN/ACK packet on state ESTABLISHED... resent", ssn); if (PKT_IS_TOSERVER(p)) { SCLogDebug("ssn %p: SYN/ACK-pkt to server in ESTABLISHED state", ssn); @@ -3141,8 +3117,8 @@ static int StreamTcpPacketStateEstablished( * received SYN/ACK packet. */ if (!(SEQ_EQ(TCP_GET_ACK(p), ssn->client.last_ack))) { SCLogDebug("ssn %p: ACK mismatch, packet ACK %" PRIu32 " != " - "%" PRIu32 " from stream", ssn, TCP_GET_ACK(p), - ssn->client.isn + 1); + "%" PRIu32 " from stream", + ssn, TCP_GET_ACK(p), ssn->client.isn + 1); StreamTcpSetEvent(p, STREAM_EST_SYNACK_RESEND_WITH_DIFFERENT_ACK); return -1; @@ -3152,8 +3128,8 @@ static int StreamTcpPacketStateEstablished( * received SYN packet. */ if (!(SEQ_EQ(TCP_GET_SEQ(p), ssn->server.isn))) { SCLogDebug("ssn %p: SEQ mismatch, packet SEQ %" PRIu32 " != " - "%" PRIu32 " from stream", ssn, TCP_GET_ACK(p), - ssn->client.isn + 1); + "%" PRIu32 " from stream", + ssn, TCP_GET_ACK(p), ssn->client.isn + 1); StreamTcpSetEvent(p, STREAM_EST_SYNACK_RESEND_WITH_DIFF_SEQ); return -1; @@ -3166,7 +3142,8 @@ static int StreamTcpPacketStateEstablished( } SCLogDebug("ssn %p: SYN/ACK packet on state ESTABLISHED... resent. " - "Likely due server not receiving final ACK in 3whs", ssn); + "Likely due server not receiving final ACK in 3whs", + ssn); return 0; } else if (p->tcph->th_flags & TH_SYN) { @@ -3209,9 +3186,9 @@ static int StreamTcpPacketStateEstablished( HandleEstablishedPacketToServer(tv, ssn, p, stt); SCLogDebug("ssn %p: next SEQ %" PRIu32 ", last ACK %" PRIu32 "," - " next win %" PRIu32 ", win %" PRIu32 "", ssn, - ssn->client.next_seq, ssn->server.last_ack - ,ssn->client.next_win, ssn->client.window); + " next win %" PRIu32 ", win %" PRIu32 "", + ssn, ssn->client.next_seq, ssn->server.last_ack, ssn->client.next_win, + ssn->client.window); } else { /* implied to client */ if (!(ssn->flags & STREAMTCP_FLAG_3WHS_CONFIRMED)) { @@ -3223,9 +3200,9 @@ static int StreamTcpPacketStateEstablished( HandleEstablishedPacketToClient(tv, ssn, p, stt); SCLogDebug("ssn %p: next SEQ %" PRIu32 ", last ACK %" PRIu32 "," - " next win %" PRIu32 ", win %" PRIu32 "", ssn, - ssn->server.next_seq, ssn->client.last_ack, - ssn->server.next_win, ssn->server.window); + " next win %" PRIu32 ", win %" PRIu32 "", + ssn, ssn->server.next_seq, ssn->client.last_ack, ssn->server.next_win, + ssn->server.window); } } else { SCLogDebug("ssn %p: default case", ssn); @@ -3250,8 +3227,8 @@ static int StreamTcpHandleFin(ThreadVars *tv, StreamTcpThread *stt, TcpSession * { if (PKT_IS_TOSERVER(p)) { SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ %" PRIu32 "," - " ACK %" PRIu32 "", ssn, p->payload_len, TCP_GET_SEQ(p), - TCP_GET_ACK(p)); + " ACK %" PRIu32 "", + ssn, p->payload_len, TCP_GET_SEQ(p), TCP_GET_ACK(p)); if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) { SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn); @@ -3267,8 +3244,8 @@ static int StreamTcpHandleFin(ThreadVars *tv, StreamTcpThread *stt, TcpSession * // within expectations } else { SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 " != " - "%" PRIu32 " from stream", ssn, TCP_GET_SEQ(p), - ssn->client.next_seq); + "%" PRIu32 " from stream", + ssn, TCP_GET_SEQ(p), ssn->client.next_seq); StreamTcpSetEvent(p, STREAM_FIN_OUT_OF_WINDOW); return -1; @@ -3285,8 +3262,7 @@ static int StreamTcpHandleFin(ThreadVars *tv, StreamTcpThread *stt, TcpSession * /* if we accept the FIN, next_seq needs to reflect the FIN */ ssn->client.next_seq = TCP_GET_SEQ(p) + p->payload_len; - SCLogDebug("ssn %p: ssn->client.next_seq %" PRIu32 "", ssn, - ssn->client.next_seq); + SCLogDebug("ssn %p: ssn->client.next_seq %" PRIu32 "", ssn, ssn->client.next_seq); ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale; if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) { @@ -3303,12 +3279,12 @@ static int StreamTcpHandleFin(ThreadVars *tv, StreamTcpThread *stt, TcpSession * StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->client, p); - SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK %" PRIu32 "", - ssn, ssn->client.next_seq, ssn->server.last_ack); + SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK %" PRIu32 "", ssn, + ssn->client.next_seq, ssn->server.last_ack); } else { /* implied to client */ SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ %" PRIu32 ", " - "ACK %" PRIu32 "", ssn, p->payload_len, TCP_GET_SEQ(p), - TCP_GET_ACK(p)); + "ACK %" PRIu32 "", + ssn, p->payload_len, TCP_GET_SEQ(p), TCP_GET_ACK(p)); if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) { SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn); @@ -3324,8 +3300,9 @@ static int StreamTcpHandleFin(ThreadVars *tv, StreamTcpThread *stt, TcpSession * // within expectations } else { SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 " != " - "%" PRIu32 " from stream (last_ack %u win %u = %u)", ssn, TCP_GET_SEQ(p), - ssn->server.next_seq, ssn->server.last_ack, ssn->server.window, (ssn->server.last_ack + ssn->server.window)); + "%" PRIu32 " from stream (last_ack %u win %u = %u)", + ssn, TCP_GET_SEQ(p), ssn->server.next_seq, ssn->server.last_ack, + ssn->server.window, (ssn->server.last_ack + ssn->server.window)); StreamTcpSetEvent(p, STREAM_FIN_OUT_OF_WINDOW); return -1; @@ -3354,8 +3331,8 @@ static int StreamTcpHandleFin(ThreadVars *tv, StreamTcpThread *stt, TcpSession * StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->server, p); - SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK %" PRIu32 "", - ssn, ssn->server.next_seq, ssn->client.last_ack); + SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK %" PRIu32 "", ssn, + ssn->server.next_seq, ssn->client.last_ack); } return 0; @@ -3387,11 +3364,11 @@ static int StreamTcpPacketStateFinWait1( if (PKT_IS_TOSERVER(p)) { if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->server, p) == 0) - StreamTcpUpdateLastAck(ssn, &ssn->server, - StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p))); + StreamTcpUpdateLastAck( + ssn, &ssn->server, StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p))); - StreamTcpUpdateLastAck(ssn, &ssn->client, - StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p))); + StreamTcpUpdateLastAck( + ssn, &ssn->client, StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p))); if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) { StreamTcpHandleTimestamp(ssn, p); @@ -3400,11 +3377,11 @@ static int StreamTcpPacketStateFinWait1( StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->client, p); } else { if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->client, p) == 0) - StreamTcpUpdateLastAck(ssn, &ssn->client, - StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p))); + StreamTcpUpdateLastAck( + ssn, &ssn->client, StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p))); - StreamTcpUpdateLastAck(ssn, &ssn->server, - StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p))); + StreamTcpUpdateLastAck( + ssn, &ssn->server, StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p))); if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) { StreamTcpHandleTimestamp(ssn, p); @@ -3413,7 +3390,7 @@ static int StreamTcpPacketStateFinWait1( StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->server, p); } - } else if ((p->tcph->th_flags & (TH_FIN|TH_ACK)) == (TH_FIN|TH_ACK)) { + } else if ((p->tcph->th_flags & (TH_FIN | TH_ACK)) == (TH_FIN | TH_ACK)) { if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) { if (!StreamTcpValidateTimestamp(ssn, p)) return -1; @@ -3421,8 +3398,8 @@ static int StreamTcpPacketStateFinWait1( if (PKT_IS_TOSERVER(p)) { SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ " - "%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len, - TCP_GET_SEQ(p), TCP_GET_ACK(p)); + "%" PRIu32 ", ACK %" PRIu32 "", + ssn, p->payload_len, TCP_GET_SEQ(p), TCP_GET_ACK(p)); int retransmission = 0; if (StreamTcpPacketIsRetransmission(&ssn->client, p)) { @@ -3433,8 +3410,8 @@ static int StreamTcpPacketStateFinWait1( } else if (SEQ_LT(TCP_GET_SEQ(p), ssn->client.next_seq - 1) || SEQ_GT(TCP_GET_SEQ(p), (ssn->client.last_ack + ssn->client.window))) { SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 "" - " != %" PRIu32 " from stream", ssn, - TCP_GET_SEQ(p), ssn->client.next_seq); + " != %" PRIu32 " from stream", + ssn, TCP_GET_SEQ(p), ssn->client.next_seq); StreamTcpSetEvent(p, STREAM_FIN1_FIN_WRONG_SEQ); return -1; } @@ -3470,12 +3447,12 @@ static int StreamTcpPacketStateFinWait1( StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->client, p); SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK " - "%" PRIu32 "", ssn, ssn->client.next_seq, - ssn->server.last_ack); + "%" PRIu32 "", + ssn, ssn->client.next_seq, ssn->server.last_ack); } else { /* implied to client */ SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ " - "%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len, - TCP_GET_SEQ(p), TCP_GET_ACK(p)); + "%" PRIu32 ", ACK %" PRIu32 "", + ssn, p->payload_len, TCP_GET_SEQ(p), TCP_GET_ACK(p)); int retransmission = 0; if (StreamTcpPacketIsRetransmission(&ssn->server, p)) { @@ -3492,8 +3469,8 @@ static int StreamTcpPacketStateFinWait1( } else if (SEQ_LT(TCP_GET_SEQ(p), ssn->server.next_seq - 1) || SEQ_GT(TCP_GET_SEQ(p), (ssn->server.last_ack + ssn->server.window))) { SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 "" - " != %" PRIu32 " from stream", ssn, - TCP_GET_SEQ(p), ssn->server.next_seq); + " != %" PRIu32 " from stream", + ssn, TCP_GET_SEQ(p), ssn->server.next_seq); StreamTcpSetEvent(p, STREAM_FIN1_FIN_WRONG_SEQ); return -1; } @@ -3529,8 +3506,8 @@ static int StreamTcpPacketStateFinWait1( StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->server, p); SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK " - "%" PRIu32 "", ssn, ssn->server.next_seq, - ssn->client.last_ack); + "%" PRIu32 "", + ssn, ssn->server.next_seq, ssn->client.last_ack); } } else if (p->tcph->th_flags & TH_FIN) { @@ -3541,8 +3518,8 @@ static int StreamTcpPacketStateFinWait1( if (PKT_IS_TOSERVER(p)) { SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ " - "%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len, - TCP_GET_SEQ(p), TCP_GET_ACK(p)); + "%" PRIu32 ", ACK %" PRIu32 "", + ssn, p->payload_len, TCP_GET_SEQ(p), TCP_GET_ACK(p)); int retransmission = 0; if (StreamTcpPacketIsRetransmission(&ssn->client, p)) { @@ -3553,8 +3530,8 @@ static int StreamTcpPacketStateFinWait1( } else if (SEQ_LT(TCP_GET_SEQ(p), ssn->client.next_seq - 1) || SEQ_GT(TCP_GET_SEQ(p), (ssn->client.last_ack + ssn->client.window))) { SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 "" - " != %" PRIu32 " from stream", ssn, - TCP_GET_SEQ(p), ssn->client.next_seq); + " != %" PRIu32 " from stream", + ssn, TCP_GET_SEQ(p), ssn->client.next_seq); StreamTcpSetEvent(p, STREAM_FIN1_FIN_WRONG_SEQ); return -1; } @@ -3591,12 +3568,12 @@ static int StreamTcpPacketStateFinWait1( StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->client, p); SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK " - "%" PRIu32 "", ssn, ssn->client.next_seq, - ssn->server.last_ack); + "%" PRIu32 "", + ssn, ssn->client.next_seq, ssn->server.last_ack); } else { /* implied to client */ SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ " - "%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len, - TCP_GET_SEQ(p), TCP_GET_ACK(p)); + "%" PRIu32 ", ACK %" PRIu32 "", + ssn, p->payload_len, TCP_GET_SEQ(p), TCP_GET_ACK(p)); int retransmission = 0; @@ -3608,8 +3585,8 @@ static int StreamTcpPacketStateFinWait1( } else if (SEQ_LT(TCP_GET_SEQ(p), ssn->server.next_seq - 1) || SEQ_GT(TCP_GET_SEQ(p), (ssn->server.last_ack + ssn->server.window))) { SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 "" - " != %" PRIu32 " from stream", ssn, - TCP_GET_SEQ(p), ssn->server.next_seq); + " != %" PRIu32 " from stream", + ssn, TCP_GET_SEQ(p), ssn->server.next_seq); StreamTcpSetEvent(p, STREAM_FIN1_FIN_WRONG_SEQ); return -1; } @@ -3646,8 +3623,8 @@ static int StreamTcpPacketStateFinWait1( StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->server, p); SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK " - "%" PRIu32 "", ssn, ssn->server.next_seq, - ssn->client.last_ack); + "%" PRIu32 "", + ssn, ssn->server.next_seq, ssn->client.last_ack); } } else if (p->tcph->th_flags & TH_SYN) { SCLogDebug("ssn (%p): SYN pkt on FinWait1", ssn); @@ -3662,8 +3639,8 @@ static int StreamTcpPacketStateFinWait1( if (PKT_IS_TOSERVER(p)) { SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ " - "%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len, - TCP_GET_SEQ(p), TCP_GET_ACK(p)); + "%" PRIu32 ", ACK %" PRIu32 "", + ssn, p->payload_len, TCP_GET_SEQ(p), TCP_GET_ACK(p)); int retransmission = 0; if (StreamTcpPacketIsRetransmission(&ssn->client, p)) { @@ -3730,14 +3707,14 @@ static int StreamTcpPacketStateFinWait1( StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->client, p); SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK " - "%" PRIu32 "", ssn, ssn->client.next_seq, - ssn->server.last_ack); + "%" PRIu32 "", + ssn, ssn->client.next_seq, ssn->server.last_ack); } else { /* implied to client */ SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ " - "%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len, - TCP_GET_SEQ(p), TCP_GET_ACK(p)); + "%" PRIu32 ", ACK %" PRIu32 "", + ssn, p->payload_len, TCP_GET_SEQ(p), TCP_GET_ACK(p)); int retransmission = 0; @@ -3755,10 +3732,10 @@ static int StreamTcpPacketStateFinWait1( if (!retransmission) { if (SEQ_LEQ(TCP_GET_SEQ(p) + p->payload_len, ssn->server.next_win) || - (ssn->flags & (STREAMTCP_FLAG_MIDSTREAM|STREAMTCP_FLAG_ASYNC))) - { - SCLogDebug("ssn %p: seq %"PRIu32" in window, ssn->server.next_win " - "%" PRIu32 "", ssn, TCP_GET_SEQ(p), ssn->server.next_win); + (ssn->flags & (STREAMTCP_FLAG_MIDSTREAM | STREAMTCP_FLAG_ASYNC))) { + SCLogDebug("ssn %p: seq %" PRIu32 " in window, ssn->server.next_win " + "%" PRIu32 "", + ssn, TCP_GET_SEQ(p), ssn->server.next_win); if (TCP_GET_SEQ(p) == ssn->server.next_seq - 1) { StreamTcpPacketSetState(p, ssn, TCP_FIN_WAIT2); @@ -3766,8 +3743,8 @@ static int StreamTcpPacketStateFinWait1( } } else { SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 "" - " != %" PRIu32 " from stream", ssn, - TCP_GET_SEQ(p), ssn->server.next_seq); + " != %" PRIu32 " from stream", + ssn, TCP_GET_SEQ(p), ssn->server.next_seq); StreamTcpSetEvent(p, STREAM_FIN1_ACK_WRONG_SEQ); return -1; } @@ -3798,8 +3775,8 @@ static int StreamTcpPacketStateFinWait1( StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->server, p); SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK " - "%" PRIu32 "", ssn, ssn->server.next_seq, - ssn->client.last_ack); + "%" PRIu32 "", + ssn, ssn->server.next_seq, ssn->client.last_ack); } } else { SCLogDebug("ssn (%p): default case", ssn); @@ -3831,11 +3808,11 @@ static int StreamTcpPacketStateFinWait2( if (PKT_IS_TOSERVER(p)) { if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->server, p) == 0) - StreamTcpUpdateLastAck(ssn, &ssn->server, - StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p))); + StreamTcpUpdateLastAck( + ssn, &ssn->server, StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p))); - StreamTcpUpdateLastAck(ssn, &ssn->client, - StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p))); + StreamTcpUpdateLastAck( + ssn, &ssn->client, StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p))); if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) { StreamTcpHandleTimestamp(ssn, p); @@ -3844,11 +3821,11 @@ static int StreamTcpPacketStateFinWait2( StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->client, p); } else { if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->client, p) == 0) - StreamTcpUpdateLastAck(ssn, &ssn->client, - StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p))); + StreamTcpUpdateLastAck( + ssn, &ssn->client, StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p))); - StreamTcpUpdateLastAck(ssn, &ssn->server, - StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p))); + StreamTcpUpdateLastAck( + ssn, &ssn->server, StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p))); if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) { StreamTcpHandleTimestamp(ssn, p); @@ -3865,12 +3842,12 @@ static int StreamTcpPacketStateFinWait2( if (PKT_IS_TOSERVER(p)) { SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ " - "%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len, - TCP_GET_SEQ(p), TCP_GET_ACK(p)); + "%" PRIu32 ", ACK %" PRIu32 "", + ssn, p->payload_len, TCP_GET_SEQ(p), TCP_GET_ACK(p)); int retransmission = 0; if (SEQ_EQ(TCP_GET_SEQ(p), ssn->client.next_seq - 1) && - SEQ_EQ(TCP_GET_ACK(p), ssn->server.last_ack)) { + SEQ_EQ(TCP_GET_ACK(p), ssn->server.last_ack)) { SCLogDebug("ssn %p: retransmission", ssn); retransmission = 1; STREAM_PKT_FLAG_SET(p, STREAM_PKT_FLAG_RETRANSMISSION); @@ -3880,11 +3857,10 @@ static int StreamTcpPacketStateFinWait2( STREAM_PKT_FLAG_SET(p, STREAM_PKT_FLAG_RETRANSMISSION); } else if (SEQ_LT(TCP_GET_SEQ(p), ssn->client.next_seq) || - SEQ_GT(TCP_GET_SEQ(p), (ssn->client.last_ack + ssn->client.window))) - { + SEQ_GT(TCP_GET_SEQ(p), (ssn->client.last_ack + ssn->client.window))) { SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ " - "%" PRIu32 " != %" PRIu32 " from stream", ssn, - TCP_GET_SEQ(p), ssn->client.next_seq); + "%" PRIu32 " != %" PRIu32 " from stream", + ssn, TCP_GET_SEQ(p), ssn->client.next_seq); StreamTcpSetEvent(p, STREAM_FIN2_FIN_WRONG_SEQ); return -1; } @@ -3921,16 +3897,16 @@ static int StreamTcpPacketStateFinWait2( StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->client, p); SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK " - "%" PRIu32 "", ssn, ssn->client.next_seq, - ssn->server.last_ack); + "%" PRIu32 "", + ssn, ssn->client.next_seq, ssn->server.last_ack); } else { /* implied to client */ SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ " - "%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len, - TCP_GET_SEQ(p), TCP_GET_ACK(p)); + "%" PRIu32 ", ACK %" PRIu32 "", + ssn, p->payload_len, TCP_GET_SEQ(p), TCP_GET_ACK(p)); int retransmission = 0; if (SEQ_EQ(TCP_GET_SEQ(p), ssn->server.next_seq - 1) && - SEQ_EQ(TCP_GET_ACK(p), ssn->client.last_ack)) { + SEQ_EQ(TCP_GET_ACK(p), ssn->client.last_ack)) { SCLogDebug("ssn %p: retransmission", ssn); retransmission = 1; STREAM_PKT_FLAG_SET(p, STREAM_PKT_FLAG_RETRANSMISSION); @@ -3940,11 +3916,10 @@ static int StreamTcpPacketStateFinWait2( STREAM_PKT_FLAG_SET(p, STREAM_PKT_FLAG_RETRANSMISSION); } else if (SEQ_LT(TCP_GET_SEQ(p), ssn->server.next_seq) || - SEQ_GT(TCP_GET_SEQ(p), (ssn->server.last_ack + ssn->server.window))) - { + SEQ_GT(TCP_GET_SEQ(p), (ssn->server.last_ack + ssn->server.window))) { SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ " - "%" PRIu32 " != %" PRIu32 " from stream", ssn, - TCP_GET_SEQ(p), ssn->server.next_seq); + "%" PRIu32 " != %" PRIu32 " from stream", + ssn, TCP_GET_SEQ(p), ssn->server.next_seq); StreamTcpSetEvent(p, STREAM_FIN2_FIN_WRONG_SEQ); return -1; } @@ -3976,8 +3951,8 @@ static int StreamTcpPacketStateFinWait2( StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->server, p); SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK " - "%" PRIu32 "", ssn, ssn->server.next_seq, - ssn->client.last_ack); + "%" PRIu32 "", + ssn, ssn->server.next_seq, ssn->client.last_ack); } } else if (p->tcph->th_flags & TH_SYN) { @@ -3993,8 +3968,8 @@ static int StreamTcpPacketStateFinWait2( if (PKT_IS_TOSERVER(p)) { SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ " - "%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len, - TCP_GET_SEQ(p), TCP_GET_ACK(p)); + "%" PRIu32 ", ACK %" PRIu32 "", + ssn, p->payload_len, TCP_GET_SEQ(p), TCP_GET_ACK(p)); int retransmission = 0; if (StreamTcpPacketIsRetransmission(&ssn->client, p)) { @@ -4011,15 +3986,15 @@ static int StreamTcpPacketStateFinWait2( if (!retransmission) { if (SEQ_LEQ(TCP_GET_SEQ(p) + p->payload_len, ssn->client.next_win) || - (ssn->flags & (STREAMTCP_FLAG_MIDSTREAM|STREAMTCP_FLAG_ASYNC))) - { - SCLogDebug("ssn %p: seq %"PRIu32" in window, ssn->client.next_win " - "%" PRIu32 "", ssn, TCP_GET_SEQ(p), ssn->client.next_win); + (ssn->flags & (STREAMTCP_FLAG_MIDSTREAM | STREAMTCP_FLAG_ASYNC))) { + SCLogDebug("ssn %p: seq %" PRIu32 " in window, ssn->client.next_win " + "%" PRIu32 "", + ssn, TCP_GET_SEQ(p), ssn->client.next_win); } else { SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 "" - " != %" PRIu32 " from stream", ssn, - TCP_GET_SEQ(p), ssn->client.next_seq); + " != %" PRIu32 " from stream", + ssn, TCP_GET_SEQ(p), ssn->client.next_seq); StreamTcpSetEvent(p, STREAM_FIN2_ACK_WRONG_SEQ); return -1; } @@ -4045,12 +4020,12 @@ static int StreamTcpPacketStateFinWait2( StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->client, p); SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK " - "%" PRIu32 "", ssn, ssn->client.next_seq, - ssn->server.last_ack); + "%" PRIu32 "", + ssn, ssn->client.next_seq, ssn->server.last_ack); } else { /* implied to client */ SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ " - "%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len, - TCP_GET_SEQ(p), TCP_GET_ACK(p)); + "%" PRIu32 ", ACK %" PRIu32 "", + ssn, p->payload_len, TCP_GET_SEQ(p), TCP_GET_ACK(p)); int retransmission = 0; if (StreamTcpPacketIsRetransmission(&ssn->server, p)) { @@ -4067,14 +4042,14 @@ static int StreamTcpPacketStateFinWait2( if (!retransmission) { if (SEQ_LEQ(TCP_GET_SEQ(p) + p->payload_len, ssn->server.next_win) || - (ssn->flags & (STREAMTCP_FLAG_MIDSTREAM|STREAMTCP_FLAG_ASYNC))) - { - SCLogDebug("ssn %p: seq %"PRIu32" in window, ssn->server.next_win " - "%" PRIu32 "", ssn, TCP_GET_SEQ(p), ssn->server.next_win); + (ssn->flags & (STREAMTCP_FLAG_MIDSTREAM | STREAMTCP_FLAG_ASYNC))) { + SCLogDebug("ssn %p: seq %" PRIu32 " in window, ssn->server.next_win " + "%" PRIu32 "", + ssn, TCP_GET_SEQ(p), ssn->server.next_win); } else { SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 "" - " != %" PRIu32 " from stream", ssn, - TCP_GET_SEQ(p), ssn->server.next_seq); + " != %" PRIu32 " from stream", + ssn, TCP_GET_SEQ(p), ssn->server.next_seq); StreamTcpSetEvent(p, STREAM_FIN2_ACK_WRONG_SEQ); return -1; } @@ -4100,8 +4075,8 @@ static int StreamTcpPacketStateFinWait2( StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->server, p); SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK " - "%" PRIu32 "", ssn, ssn->server.next_seq, - ssn->client.last_ack); + "%" PRIu32 "", + ssn, ssn->server.next_seq, ssn->client.last_ack); } } else { SCLogDebug("ssn %p: default case", ssn); @@ -4133,11 +4108,11 @@ static int StreamTcpPacketStateClosing( if (PKT_IS_TOSERVER(p)) { if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->server, p) == 0) - StreamTcpUpdateLastAck(ssn, &ssn->server, - StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p))); + StreamTcpUpdateLastAck( + ssn, &ssn->server, StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p))); - StreamTcpUpdateLastAck(ssn, &ssn->client, - StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p))); + StreamTcpUpdateLastAck( + ssn, &ssn->client, StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p))); if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) { StreamTcpHandleTimestamp(ssn, p); @@ -4146,11 +4121,11 @@ static int StreamTcpPacketStateClosing( StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->client, p); } else { if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->client, p) == 0) - StreamTcpUpdateLastAck(ssn, &ssn->client, - StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p))); + StreamTcpUpdateLastAck( + ssn, &ssn->client, StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p))); - StreamTcpUpdateLastAck(ssn, &ssn->server, - StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p))); + StreamTcpUpdateLastAck( + ssn, &ssn->server, StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p))); if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) { StreamTcpHandleTimestamp(ssn, p); @@ -4172,8 +4147,8 @@ static int StreamTcpPacketStateClosing( if (PKT_IS_TOSERVER(p)) { SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ " - "%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len, - TCP_GET_SEQ(p), TCP_GET_ACK(p)); + "%" PRIu32 ", ACK %" PRIu32 "", + ssn, p->payload_len, TCP_GET_SEQ(p), TCP_GET_ACK(p)); int retransmission = 0; if (StreamTcpPacketIsRetransmission(&ssn->client, p)) { SCLogDebug("ssn %p: packet is retransmission", ssn); @@ -4183,8 +4158,8 @@ static int StreamTcpPacketStateClosing( if (TCP_GET_SEQ(p) != ssn->client.next_seq) { SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 "" - " != %" PRIu32 " from stream", ssn, - TCP_GET_SEQ(p), ssn->client.next_seq); + " != %" PRIu32 " from stream", + ssn, TCP_GET_SEQ(p), ssn->client.next_seq); StreamTcpSetEvent(p, STREAM_CLOSING_ACK_WRONG_SEQ); return -1; } @@ -4214,12 +4189,12 @@ static int StreamTcpPacketStateClosing( StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->client, p); SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK " - "%" PRIu32 "", ssn, ssn->client.next_seq, - ssn->server.last_ack); + "%" PRIu32 "", + ssn, ssn->client.next_seq, ssn->server.last_ack); } else { /* implied to client */ SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ " - "%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len, - TCP_GET_SEQ(p), TCP_GET_ACK(p)); + "%" PRIu32 ", ACK %" PRIu32 "", + ssn, p->payload_len, TCP_GET_SEQ(p), TCP_GET_ACK(p)); int retransmission = 0; if (StreamTcpPacketIsRetransmission(&ssn->server, p)) { SCLogDebug("ssn %p: packet is retransmission", ssn); @@ -4229,8 +4204,8 @@ static int StreamTcpPacketStateClosing( if (TCP_GET_SEQ(p) != ssn->server.next_seq) { SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 "" - " != %" PRIu32 " from stream", ssn, - TCP_GET_SEQ(p), ssn->server.next_seq); + " != %" PRIu32 " from stream", + ssn, TCP_GET_SEQ(p), ssn->server.next_seq); StreamTcpSetEvent(p, STREAM_CLOSING_ACK_WRONG_SEQ); return -1; } @@ -4261,8 +4236,8 @@ static int StreamTcpPacketStateClosing( StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->server, p); SCLogDebug("StreamTcpPacketStateClosing (%p): =+ next SEQ " - "%" PRIu32 ", last ACK %" PRIu32 "", ssn, - ssn->server.next_seq, ssn->client.last_ack); + "%" PRIu32 ", last ACK %" PRIu32 "", + ssn, ssn->server.next_seq, ssn->client.last_ack); } } else { SCLogDebug("ssn %p: default case", ssn); @@ -4290,12 +4265,12 @@ static int StreamTcpPacketStateCloseWait( if (PKT_IS_TOCLIENT(p)) { SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ " - "%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len, - TCP_GET_SEQ(p), TCP_GET_ACK(p)); + "%" PRIu32 ", ACK %" PRIu32 "", + ssn, p->payload_len, TCP_GET_SEQ(p), TCP_GET_ACK(p)); } else { SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ " - "%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len, - TCP_GET_SEQ(p), TCP_GET_ACK(p)); + "%" PRIu32 ", ACK %" PRIu32 "", + ssn, p->payload_len, TCP_GET_SEQ(p), TCP_GET_ACK(p)); } if (p->tcph->th_flags & TH_RST) { @@ -4306,11 +4281,11 @@ static int StreamTcpPacketStateCloseWait( if (PKT_IS_TOSERVER(p)) { if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->server, p) == 0) - StreamTcpUpdateLastAck(ssn, &ssn->server, - StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p))); + StreamTcpUpdateLastAck( + ssn, &ssn->server, StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p))); - StreamTcpUpdateLastAck(ssn, &ssn->client, - StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p))); + StreamTcpUpdateLastAck( + ssn, &ssn->client, StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p))); if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) { StreamTcpHandleTimestamp(ssn, p); @@ -4319,11 +4294,11 @@ static int StreamTcpPacketStateCloseWait( StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->client, p); } else { if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->client, p) == 0) - StreamTcpUpdateLastAck(ssn, &ssn->client, - StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p))); + StreamTcpUpdateLastAck( + ssn, &ssn->client, StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p))); - StreamTcpUpdateLastAck(ssn, &ssn->server, - StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p))); + StreamTcpUpdateLastAck( + ssn, &ssn->server, StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p))); if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) { StreamTcpHandleTimestamp(ssn, p); @@ -4340,8 +4315,8 @@ static int StreamTcpPacketStateCloseWait( if (PKT_IS_TOSERVER(p)) { SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ " - "%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len, - TCP_GET_SEQ(p), TCP_GET_ACK(p)); + "%" PRIu32 ", ACK %" PRIu32 "", + ssn, p->payload_len, TCP_GET_SEQ(p), TCP_GET_ACK(p)); int retransmission = 0; if (StreamTcpPacketIsRetransmission(&ssn->client, p)) { @@ -4352,11 +4327,10 @@ static int StreamTcpPacketStateCloseWait( if (!retransmission) { if (SEQ_LT(TCP_GET_SEQ(p), ssn->client.next_seq) || - SEQ_GT(TCP_GET_SEQ(p), (ssn->client.last_ack + ssn->client.window))) - { + SEQ_GT(TCP_GET_SEQ(p), (ssn->client.last_ack + ssn->client.window))) { SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 "" - " != %" PRIu32 " from stream", ssn, - TCP_GET_SEQ(p), ssn->client.next_seq); + " != %" PRIu32 " from stream", + ssn, TCP_GET_SEQ(p), ssn->client.next_seq); StreamTcpSetEvent(p, STREAM_CLOSEWAIT_FIN_OUT_OF_WINDOW); SCReturnInt(-1); } @@ -4387,12 +4361,12 @@ static int StreamTcpPacketStateCloseWait( StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->client, p); SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK " - "%" PRIu32 "", ssn, ssn->client.next_seq, - ssn->server.last_ack); + "%" PRIu32 "", + ssn, ssn->client.next_seq, ssn->server.last_ack); } else { SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ " - "%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len, - TCP_GET_SEQ(p), TCP_GET_ACK(p)); + "%" PRIu32 ", ACK %" PRIu32 "", + ssn, p->payload_len, TCP_GET_SEQ(p), TCP_GET_ACK(p)); int retransmission = 0; if (StreamTcpPacketIsRetransmission(&ssn->server, p)) { @@ -4403,11 +4377,10 @@ static int StreamTcpPacketStateCloseWait( if (!retransmission) { if (SEQ_LT(TCP_GET_SEQ(p), ssn->server.next_seq) || - SEQ_GT(TCP_GET_SEQ(p), (ssn->server.last_ack + ssn->server.window))) - { + SEQ_GT(TCP_GET_SEQ(p), (ssn->server.last_ack + ssn->server.window))) { SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 "" - " != %" PRIu32 " from stream", ssn, - TCP_GET_SEQ(p), ssn->server.next_seq); + " != %" PRIu32 " from stream", + ssn, TCP_GET_SEQ(p), ssn->server.next_seq); StreamTcpSetEvent(p, STREAM_CLOSEWAIT_FIN_OUT_OF_WINDOW); SCReturnInt(-1); } @@ -4440,8 +4413,8 @@ static int StreamTcpPacketStateCloseWait( StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->server, p); SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK " - "%" PRIu32 "", ssn, ssn->server.next_seq, - ssn->client.last_ack); + "%" PRIu32 "", + ssn, ssn->server.next_seq, ssn->client.last_ack); } } else if (p->tcph->th_flags & TH_SYN) { @@ -4457,8 +4430,8 @@ static int StreamTcpPacketStateCloseWait( if (PKT_IS_TOSERVER(p)) { SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ " - "%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len, - TCP_GET_SEQ(p), TCP_GET_ACK(p)); + "%" PRIu32 ", ACK %" PRIu32 "", + ssn, p->payload_len, TCP_GET_SEQ(p), TCP_GET_ACK(p)); int retransmission = 0; if (StreamTcpPacketIsRetransmission(&ssn->client, p)) { @@ -4467,16 +4440,16 @@ static int StreamTcpPacketStateCloseWait( STREAM_PKT_FLAG_SET(p, STREAM_PKT_FLAG_RETRANSMISSION); } - if (p->payload_len > 0 && (SEQ_LEQ((TCP_GET_SEQ(p) + p->payload_len), ssn->client.last_ack))) { + if (p->payload_len > 0 && + (SEQ_LEQ((TCP_GET_SEQ(p) + p->payload_len), ssn->client.last_ack))) { SCLogDebug("ssn %p: -> retransmission", ssn); StreamTcpSetEvent(p, STREAM_CLOSEWAIT_PKT_BEFORE_LAST_ACK); SCReturnInt(-1); - } else if (SEQ_GT(TCP_GET_SEQ(p), (ssn->client.last_ack + ssn->client.window))) - { + } else if (SEQ_GT(TCP_GET_SEQ(p), (ssn->client.last_ack + ssn->client.window))) { SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 "" - " != %" PRIu32 " from stream", ssn, - TCP_GET_SEQ(p), ssn->client.next_seq); + " != %" PRIu32 " from stream", + ssn, TCP_GET_SEQ(p), ssn->client.next_seq); StreamTcpSetEvent(p, STREAM_CLOSEWAIT_ACK_OUT_OF_WINDOW); SCReturnInt(-1); } @@ -4500,19 +4473,19 @@ static int StreamTcpPacketStateCloseWait( if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p))) ssn->server.next_seq = TCP_GET_ACK(p); - if (SEQ_EQ(TCP_GET_SEQ(p),ssn->client.next_seq)) + if (SEQ_EQ(TCP_GET_SEQ(p), ssn->client.next_seq)) StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len)); StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p)); StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->client, p); SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK " - "%" PRIu32 "", ssn, ssn->client.next_seq, - ssn->server.last_ack); + "%" PRIu32 "", + ssn, ssn->client.next_seq, ssn->server.last_ack); } else { SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ " - "%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len, - TCP_GET_SEQ(p), TCP_GET_ACK(p)); + "%" PRIu32 ", ACK %" PRIu32 "", + ssn, p->payload_len, TCP_GET_SEQ(p), TCP_GET_ACK(p)); int retransmission = 0; if (StreamTcpPacketIsRetransmission(&ssn->server, p)) { SCLogDebug("ssn %p: packet is retransmission", ssn); @@ -4520,16 +4493,16 @@ static int StreamTcpPacketStateCloseWait( STREAM_PKT_FLAG_SET(p, STREAM_PKT_FLAG_RETRANSMISSION); } - if (p->payload_len > 0 && (SEQ_LEQ((TCP_GET_SEQ(p) + p->payload_len), ssn->server.last_ack))) { + if (p->payload_len > 0 && + (SEQ_LEQ((TCP_GET_SEQ(p) + p->payload_len), ssn->server.last_ack))) { SCLogDebug("ssn %p: -> retransmission", ssn); StreamTcpSetEvent(p, STREAM_CLOSEWAIT_PKT_BEFORE_LAST_ACK); SCReturnInt(-1); - } else if (SEQ_GT(TCP_GET_SEQ(p), (ssn->server.last_ack + ssn->server.window))) - { + } else if (SEQ_GT(TCP_GET_SEQ(p), (ssn->server.last_ack + ssn->server.window))) { SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 "" - " != %" PRIu32 " from stream", ssn, - TCP_GET_SEQ(p), ssn->server.next_seq); + " != %" PRIu32 " from stream", + ssn, TCP_GET_SEQ(p), ssn->server.next_seq); StreamTcpSetEvent(p, STREAM_CLOSEWAIT_ACK_OUT_OF_WINDOW); SCReturnInt(-1); } @@ -4553,15 +4526,15 @@ static int StreamTcpPacketStateCloseWait( if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p))) ssn->client.next_seq = TCP_GET_ACK(p); - if (SEQ_EQ(TCP_GET_SEQ(p),ssn->server.next_seq)) + if (SEQ_EQ(TCP_GET_SEQ(p), ssn->server.next_seq)) StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len)); StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p)); StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->server, p); SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK " - "%" PRIu32 "", ssn, ssn->server.next_seq, - ssn->client.last_ack); + "%" PRIu32 "", + ssn, ssn->server.next_seq, ssn->client.last_ack); } } else { @@ -4593,11 +4566,11 @@ static int StreamTcpPacketStateLastAck( if (PKT_IS_TOSERVER(p)) { if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->server, p) == 0) - StreamTcpUpdateLastAck(ssn, &ssn->server, - StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p))); + StreamTcpUpdateLastAck( + ssn, &ssn->server, StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p))); - StreamTcpUpdateLastAck(ssn, &ssn->client, - StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p))); + StreamTcpUpdateLastAck( + ssn, &ssn->client, StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p))); if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) { StreamTcpHandleTimestamp(ssn, p); @@ -4606,11 +4579,11 @@ static int StreamTcpPacketStateLastAck( StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->client, p); } else { if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->client, p) == 0) - StreamTcpUpdateLastAck(ssn, &ssn->client, - StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p))); + StreamTcpUpdateLastAck( + ssn, &ssn->client, StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p))); - StreamTcpUpdateLastAck(ssn, &ssn->server, - StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p))); + StreamTcpUpdateLastAck( + ssn, &ssn->server, StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p))); if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) { StreamTcpHandleTimestamp(ssn, p); @@ -4636,8 +4609,8 @@ static int StreamTcpPacketStateLastAck( if (PKT_IS_TOSERVER(p)) { SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ " - "%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len, - TCP_GET_SEQ(p), TCP_GET_ACK(p)); + "%" PRIu32 ", ACK %" PRIu32 "", + ssn, p->payload_len, TCP_GET_SEQ(p), TCP_GET_ACK(p)); int retransmission = 0; if (StreamTcpPacketIsRetransmission(&ssn->client, p)) { @@ -4655,16 +4628,16 @@ static int StreamTcpPacketStateLastAck( if (!retransmission) { if (SEQ_LT(TCP_GET_SEQ(p), ssn->client.next_seq)) { SCLogDebug("ssn %p: not updating state as packet is before next_seq", ssn); - } else if (TCP_GET_SEQ(p) != ssn->client.next_seq && TCP_GET_SEQ(p) != ssn->client.next_seq + 1) { + } else if (TCP_GET_SEQ(p) != ssn->client.next_seq && + TCP_GET_SEQ(p) != ssn->client.next_seq + 1) { SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 "" - " != %" PRIu32 " from stream", ssn, - TCP_GET_SEQ(p), ssn->client.next_seq); + " != %" PRIu32 " from stream", + ssn, TCP_GET_SEQ(p), ssn->client.next_seq); StreamTcpSetEvent(p, STREAM_LASTACK_ACK_WRONG_SEQ); return -1; } else { StreamTcpPacketSetState(p, ssn, TCP_CLOSED); SCLogDebug("ssn %p: state changed to TCP_CLOSED", ssn); - } ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale; } @@ -4682,8 +4655,8 @@ static int StreamTcpPacketStateLastAck( StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->client, p); SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK " - "%" PRIu32 "", ssn, ssn->client.next_seq, - ssn->server.last_ack); + "%" PRIu32 "", + ssn, ssn->client.next_seq, ssn->server.last_ack); } } else { SCLogDebug("ssn %p: default case", ssn); @@ -4715,11 +4688,11 @@ static int StreamTcpPacketStateTimeWait( if (PKT_IS_TOSERVER(p)) { if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->server, p) == 0) - StreamTcpUpdateLastAck(ssn, &ssn->server, - StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p))); + StreamTcpUpdateLastAck( + ssn, &ssn->server, StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p))); - StreamTcpUpdateLastAck(ssn, &ssn->client, - StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p))); + StreamTcpUpdateLastAck( + ssn, &ssn->client, StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p))); if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) { StreamTcpHandleTimestamp(ssn, p); @@ -4728,11 +4701,11 @@ static int StreamTcpPacketStateTimeWait( StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->client, p); } else { if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->client, p) == 0) - StreamTcpUpdateLastAck(ssn, &ssn->client, - StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p))); + StreamTcpUpdateLastAck( + ssn, &ssn->client, StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p))); - StreamTcpUpdateLastAck(ssn, &ssn->server, - StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p))); + StreamTcpUpdateLastAck( + ssn, &ssn->server, StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p))); if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) { StreamTcpHandleTimestamp(ssn, p); @@ -4757,18 +4730,19 @@ static int StreamTcpPacketStateTimeWait( if (PKT_IS_TOSERVER(p)) { SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ " - "%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len, - TCP_GET_SEQ(p), TCP_GET_ACK(p)); + "%" PRIu32 ", ACK %" PRIu32 "", + ssn, p->payload_len, TCP_GET_SEQ(p), TCP_GET_ACK(p)); int retransmission = 0; if (StreamTcpPacketIsRetransmission(&ssn->client, p)) { SCLogDebug("ssn %p: packet is retransmission", ssn); retransmission = 1; STREAM_PKT_FLAG_SET(p, STREAM_PKT_FLAG_RETRANSMISSION); - } else if (TCP_GET_SEQ(p) != ssn->client.next_seq && TCP_GET_SEQ(p) != ssn->client.next_seq+1) { + } else if (TCP_GET_SEQ(p) != ssn->client.next_seq && + TCP_GET_SEQ(p) != ssn->client.next_seq + 1) { SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 "" - " != %" PRIu32 " from stream", ssn, - TCP_GET_SEQ(p), ssn->client.next_seq); + " != %" PRIu32 " from stream", + ssn, TCP_GET_SEQ(p), ssn->client.next_seq); StreamTcpSetEvent(p, STREAM_TIMEWAIT_ACK_WRONG_SEQ); return -1; } @@ -4799,12 +4773,12 @@ static int StreamTcpPacketStateTimeWait( StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->client, p); SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK " - "%" PRIu32 "", ssn, ssn->client.next_seq, - ssn->server.last_ack); + "%" PRIu32 "", + ssn, ssn->client.next_seq, ssn->server.last_ack); } else { SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ " - "%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len, - TCP_GET_SEQ(p), TCP_GET_ACK(p)); + "%" PRIu32 ", ACK %" PRIu32 "", + ssn, p->payload_len, TCP_GET_SEQ(p), TCP_GET_ACK(p)); int retransmission = 0; if (StreamTcpPacketIsRetransmission(&ssn->server, p)) { SCLogDebug("ssn %p: packet is retransmission", ssn); @@ -4817,8 +4791,8 @@ static int StreamTcpPacketStateTimeWait( SCReturnInt(0); } else { SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 "" - " != %" PRIu32 " from stream", ssn, - TCP_GET_SEQ(p), ssn->server.next_seq); + " != %" PRIu32 " from stream", + ssn, TCP_GET_SEQ(p), ssn->server.next_seq); StreamTcpSetEvent(p, STREAM_TIMEWAIT_ACK_WRONG_SEQ); return -1; } @@ -4850,8 +4824,8 @@ static int StreamTcpPacketStateTimeWait( StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->server, p); SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK " - "%" PRIu32 "", ssn, ssn->server.next_seq, - ssn->client.last_ack); + "%" PRIu32 "", + ssn, ssn->server.next_seq, ssn->client.last_ack); } } else { @@ -4881,8 +4855,8 @@ static int StreamTcpPacketStateClosed( } SCLogDebug("stream %s ostream %s", - stream->flags & STREAMTCP_STREAM_FLAG_RST_RECV?"true":"false", - ostream->flags & STREAMTCP_STREAM_FLAG_RST_RECV ? "true":"false"); + stream->flags & STREAMTCP_STREAM_FLAG_RST_RECV ? "true" : "false", + ostream->flags & STREAMTCP_STREAM_FLAG_RST_RECV ? "true" : "false"); /* if we've seen a RST on our direction, but not on the other * see if we perhaps need to continue processing anyway. */ @@ -4916,8 +4890,9 @@ static void StreamTcpPacketCheckPostRst(TcpSession *ssn, Packet *p) } if (ostream->flags & STREAMTCP_STREAM_FLAG_RST_RECV) { - SCLogDebug("regular packet %"PRIu64" from same sender as " - "the previous RST. Looks like it injected!", p->pcap_cnt); + SCLogDebug("regular packet %" PRIu64 " from same sender as " + "the previous RST. Looks like it injected!", + p->pcap_cnt); ostream->flags &= ~STREAMTCP_STREAM_FLAG_RST_RECV; ssn->flags &= ~STREAMTCP_FLAG_CLOSED_BY_RST; StreamTcpSetEvent(p, STREAM_SUSPECTED_RST_INJECT); @@ -4944,7 +4919,7 @@ static int StreamTcpPacketIsKeepAlive(TcpSession *ssn, Packet *p) if (p->payload_len > 1) return 0; - if ((p->tcph->th_flags & (TH_SYN|TH_FIN|TH_RST)) != 0) { + if ((p->tcph->th_flags & (TH_SYN | TH_FIN | TH_RST)) != 0) { return 0; } @@ -4960,12 +4935,12 @@ static int StreamTcpPacketIsKeepAlive(TcpSession *ssn, Packet *p) const uint32_t seq = TCP_GET_SEQ(p); const uint32_t ack = TCP_GET_ACK(p); if (ack == ostream->last_ack && seq == (stream->next_seq - 1)) { - SCLogDebug("packet is TCP keep-alive: %"PRIu64, p->pcap_cnt); + SCLogDebug("packet is TCP keep-alive: %" PRIu64, p->pcap_cnt); stream->flags |= STREAMTCP_STREAM_FLAG_KEEPALIVE; STREAM_PKT_FLAG_SET(p, STREAM_PKT_FLAG_KEEPALIVE); return 1; } - SCLogDebug("seq %u (%u), ack %u (%u)", seq, (stream->next_seq - 1), ack, ostream->last_ack); + SCLogDebug("seq %u (%u), ack %u (%u)", seq, (stream->next_seq - 1), ack, ostream->last_ack); return 0; } @@ -4986,7 +4961,7 @@ static int StreamTcpPacketIsKeepAliveACK(TcpSession *ssn, Packet *p) if (p->payload_len > 0) return 0; - if ((p->tcph->th_flags & (TH_SYN|TH_FIN|TH_RST)) != 0) + if ((p->tcph->th_flags & (TH_SYN | TH_FIN | TH_RST)) != 0) return 0; if (TCP_GET_WINDOW(p) == 0) @@ -5007,13 +4982,15 @@ static int StreamTcpPacketIsKeepAliveACK(TcpSession *ssn, Packet *p) if (pkt_win != ostream->window) return 0; - if ((ostream->flags & STREAMTCP_STREAM_FLAG_KEEPALIVE) && ack == ostream->last_ack && seq == stream->next_seq) { - SCLogDebug("packet is TCP keep-aliveACK: %"PRIu64, p->pcap_cnt); + if ((ostream->flags & STREAMTCP_STREAM_FLAG_KEEPALIVE) && ack == ostream->last_ack && + seq == stream->next_seq) { + SCLogDebug("packet is TCP keep-aliveACK: %" PRIu64, p->pcap_cnt); ostream->flags &= ~STREAMTCP_STREAM_FLAG_KEEPALIVE; STREAM_PKT_FLAG_SET(p, STREAM_PKT_FLAG_KEEPALIVEACK); return 1; } - SCLogDebug("seq %u (%u), ack %u (%u) FLAG_KEEPALIVE: %s", seq, stream->next_seq, ack, ostream->last_ack, + SCLogDebug("seq %u (%u), ack %u (%u) FLAG_KEEPALIVE: %s", seq, stream->next_seq, ack, + ostream->last_ack, ostream->flags & STREAMTCP_STREAM_FLAG_KEEPALIVE ? "set" : "not set"); return 0; } @@ -5057,7 +5034,7 @@ static int StreamTcpPacketIsWindowUpdate(TcpSession *ssn, Packet *p) if (p->payload_len > 0) return 0; - if ((p->tcph->th_flags & (TH_SYN|TH_FIN|TH_RST)) != 0) + if ((p->tcph->th_flags & (TH_SYN | TH_FIN | TH_RST)) != 0) return 0; if (TCP_GET_WINDOW(p) == 0) @@ -5079,7 +5056,7 @@ static int StreamTcpPacketIsWindowUpdate(TcpSession *ssn, Packet *p) return 0; if (ack == ostream->last_ack && seq == stream->next_seq) { - SCLogDebug("packet is TCP window update: %"PRIu64, p->pcap_cnt); + SCLogDebug("packet is TCP window update: %" PRIu64, p->pcap_cnt); STREAM_PKT_FLAG_SET(p, STREAM_PKT_FLAG_WINDOWUPDATE); return 1; } @@ -5099,7 +5076,8 @@ static int StreamTcpPacketIsFinShutdownAck(TcpSession *ssn, Packet *p) if (p->flags & PKT_PSEUDO_STREAM_END) return 0; - if (!(ssn->state == TCP_TIME_WAIT || ssn->state == TCP_CLOSE_WAIT || ssn->state == TCP_LAST_ACK)) + if (!(ssn->state == TCP_TIME_WAIT || ssn->state == TCP_CLOSE_WAIT || + ssn->state == TCP_LAST_ACK)) return 0; if (p->tcph->th_flags != TH_ACK) return 0; @@ -5117,8 +5095,8 @@ static int StreamTcpPacketIsFinShutdownAck(TcpSession *ssn, Packet *p) seq = TCP_GET_SEQ(p); ack = TCP_GET_ACK(p); - SCLogDebug("%"PRIu64", seq %u ack %u stream->next_seq %u ostream->next_seq %u", - p->pcap_cnt, seq, ack, stream->next_seq, ostream->next_seq); + SCLogDebug("%" PRIu64 ", seq %u ack %u stream->next_seq %u ostream->next_seq %u", p->pcap_cnt, + seq, ack, stream->next_seq, ostream->next_seq); if (SEQ_EQ(stream->next_seq + 1, seq) && SEQ_EQ(ack, ostream->next_seq + 1)) { return 1; @@ -5156,7 +5134,7 @@ static int StreamTcpPacketIsBadWindowUpdate(TcpSession *ssn, Packet *p) if (ssn->state < TCP_ESTABLISHED || ssn->state == TCP_CLOSED) return 0; - if ((p->tcph->th_flags & (TH_SYN|TH_FIN|TH_RST)) != 0) + if ((p->tcph->th_flags & (TH_SYN | TH_FIN | TH_RST)) != 0) return 0; if (PKT_IS_TOSERVER(p)) { @@ -5174,15 +5152,14 @@ static int StreamTcpPacketIsBadWindowUpdate(TcpSession *ssn, Packet *p) if (pkt_win < ostream->window) { uint32_t diff = ostream->window - pkt_win; - if (diff > p->payload_len && - SEQ_GT(ack, ostream->next_seq) && - SEQ_GT(seq, stream->next_seq)) - { - SCLogDebug("%"PRIu64", pkt_win %u, stream win %u, diff %u, dsize %u", - p->pcap_cnt, pkt_win, ostream->window, diff, p->payload_len); - SCLogDebug("%"PRIu64", pkt_win %u, stream win %u", - p->pcap_cnt, pkt_win, ostream->window); - SCLogDebug("%"PRIu64", seq %u ack %u ostream->next_seq %u ostream->last_ack %u, ostream->next_win %u, diff %u (%u)", + if (diff > p->payload_len && SEQ_GT(ack, ostream->next_seq) && + SEQ_GT(seq, stream->next_seq)) { + SCLogDebug("%" PRIu64 ", pkt_win %u, stream win %u, diff %u, dsize %u", p->pcap_cnt, + pkt_win, ostream->window, diff, p->payload_len); + SCLogDebug("%" PRIu64 ", pkt_win %u, stream win %u", p->pcap_cnt, pkt_win, + ostream->window); + SCLogDebug("%" PRIu64 ", seq %u ack %u ostream->next_seq %u ostream->last_ack %u, " + "ostream->next_win %u, diff %u (%u)", p->pcap_cnt, seq, ack, ostream->next_seq, ostream->last_ack, ostream->next_win, ostream->next_seq - ostream->last_ack, stream->next_seq - stream->last_ack); @@ -5193,16 +5170,15 @@ static int StreamTcpPacketIsBadWindowUpdate(TcpSession *ssn, Packet *p) * are rather arbitrary. */ uint32_t adiff = ack - ostream->last_ack; if (((pkt_win > 1024) && (diff > (adiff + 32))) || - ((pkt_win <= 1024) && (diff > adiff))) - { + ((pkt_win <= 1024) && (diff > adiff))) { SCLogDebug("pkt ACK %u is %u bytes beyond last_ack %u, shrinks window by %u " - "(allowing 32 bytes extra): pkt WIN %u", ack, adiff, ostream->last_ack, diff, pkt_win); + "(allowing 32 bytes extra): pkt WIN %u", + ack, adiff, ostream->last_ack, diff, pkt_win); SCLogDebug("%u - %u = %u (state %u)", diff, adiff, diff - adiff, ssn->state); StreamTcpSetEvent(p, STREAM_PKT_BAD_WINDOW_UPDATE); return 1; } } - } SCLogDebug("seq %u (%u), ack %u (%u)", seq, stream->next_seq, ack, ostream->last_ack); return 0; @@ -5309,14 +5285,13 @@ static inline void HandleThreadId(ThreadVars *tv, Packet *p, StreamTcpThread *st } /* flow is and stays locked */ -int StreamTcpPacket (ThreadVars *tv, Packet *p, StreamTcpThread *stt, - PacketQueueNoLock *pq) +int StreamTcpPacket(ThreadVars *tv, Packet *p, StreamTcpThread *stt, PacketQueueNoLock *pq) { SCEnter(); DEBUG_ASSERT_FLOW_LOCKED(p->flow); - SCLogDebug("p->pcap_cnt %"PRIu64, p->pcap_cnt); + SCLogDebug("p->pcap_cnt %" PRIu64, p->pcap_cnt); TcpSession *ssn = (TcpSession *)p->flow->protoctx; @@ -5329,16 +5304,16 @@ int StreamTcpPacket (ThreadVars *tv, Packet *p, StreamTcpThread *stt, ssn->server.tcp_flags |= p->tcph->th_flags; /* check if we need to unset the ASYNC flag */ - if (ssn->flags & STREAMTCP_FLAG_ASYNC && - ssn->client.tcp_flags != 0 && - ssn->server.tcp_flags != 0) - { + if (ssn->flags & STREAMTCP_FLAG_ASYNC && ssn->client.tcp_flags != 0 && + ssn->server.tcp_flags != 0) { SCLogDebug("ssn %p: removing ASYNC flag as we have packets on both sides", ssn); ssn->flags &= ~STREAMTCP_FLAG_ASYNC; } } - /* broken TCP http://ask.wireshark.org/questions/3183/acknowledgment-number-broken-tcp-the-acknowledge-field-is-nonzero-while-the-ack-flag-is-not-set */ + /* broken TCP + * http://ask.wireshark.org/questions/3183/acknowledgment-number-broken-tcp-the-acknowledge-field-is-nonzero-while-the-ack-flag-is-not-set + */ if (!(p->tcph->th_flags & TH_ACK) && TCP_GET_ACK(p) != 0) { StreamTcpSetEvent(p, STREAM_PKT_BROKEN_ACK); } @@ -5362,7 +5337,7 @@ int StreamTcpPacket (ThreadVars *tv, Packet *p, StreamTcpThread *stt, } if (ssn != NULL) - SCLogDebug("ssn->alproto %"PRIu16"", p->flow->alproto); + SCLogDebug("ssn->alproto %" PRIu16 "", p->flow->alproto); } else { /* special case for PKT_PSEUDO_STREAM_END packets: * bypass the state handling and various packet checks, @@ -5414,7 +5389,7 @@ int StreamTcpPacket (ThreadVars *tv, Packet *p, StreamTcpThread *stt, * a bad window update that we should ignore (and alert on) */ if (StreamTcpPacketIsFinShutdownAck(ssn, p) == 0) { if (StreamTcpPacketIsWindowUpdate(ssn, p) == 0) { - if (StreamTcpPacketIsBadWindowUpdate(ssn,p)) + if (StreamTcpPacketIsBadWindowUpdate(ssn, p)) goto skip; if (StreamTcpPacketIsOutdatedAck(ssn, p)) goto skip; @@ -5450,8 +5425,7 @@ int StreamTcpPacket (ThreadVars *tv, Packet *p, StreamTcpThread *stt, /* streams that hit depth */ if ((ssn->client.flags & STREAMTCP_STREAM_FLAG_DEPTH_REACHED) || - (ssn->server.flags & STREAMTCP_STREAM_FLAG_DEPTH_REACHED)) - { + (ssn->server.flags & STREAMTCP_STREAM_FLAG_DEPTH_REACHED)) { /* we can call bypass callback, if enabled */ if (StreamTcpBypassEnabled()) { PacketBypassCallback(p); @@ -5459,15 +5433,13 @@ int StreamTcpPacket (ThreadVars *tv, Packet *p, StreamTcpThread *stt, } if ((ssn->client.flags & STREAMTCP_STREAM_FLAG_DEPTH_REACHED) || - (ssn->server.flags & STREAMTCP_STREAM_FLAG_DEPTH_REACHED)) - { + (ssn->server.flags & STREAMTCP_STREAM_FLAG_DEPTH_REACHED)) { p->flags |= PKT_STREAM_NOPCAPLOG; } /* encrypted packets */ if ((PKT_IS_TOSERVER(p) && (ssn->client.flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY)) || - (PKT_IS_TOCLIENT(p) && (ssn->server.flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY))) - { + (PKT_IS_TOCLIENT(p) && (ssn->server.flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY))) { p->flags |= PKT_STREAM_NOPCAPLOG; } @@ -5477,12 +5449,10 @@ int StreamTcpPacket (ThreadVars *tv, Packet *p, StreamTcpThread *stt, PacketBypassCallback(p); } - /* if stream is dead and we have no detect engine at all, bypass. */ - } else if (g_detect_disabled && - (ssn->client.flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY) && - (ssn->server.flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY) && - StreamTcpBypassEnabled()) - { + /* if stream is dead and we have no detect engine at all, bypass. */ + } else if (g_detect_disabled && (ssn->client.flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY) && + (ssn->server.flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY) && + StreamTcpBypassEnabled()) { SCLogDebug("bypass as stream is dead and we have no rules"); PacketBypassCallback(p); } @@ -5523,24 +5493,18 @@ static inline int StreamTcpValidateChecksum(Packet *p) if (p->level4_comp_csum == -1) { if (PKT_IS_IPV4(p)) { - p->level4_comp_csum = TCPChecksum(p->ip4h->s_ip_addrs, - (uint16_t *)p->tcph, - (p->payload_len + - TCP_GET_HLEN(p)), - p->tcph->th_sum); + p->level4_comp_csum = TCPChecksum(p->ip4h->s_ip_addrs, (uint16_t *)p->tcph, + (p->payload_len + TCP_GET_HLEN(p)), p->tcph->th_sum); } else if (PKT_IS_IPV6(p)) { - p->level4_comp_csum = TCPV6Checksum(p->ip6h->s_ip6_addrs, - (uint16_t *)p->tcph, - (p->payload_len + - TCP_GET_HLEN(p)), - p->tcph->th_sum); + p->level4_comp_csum = TCPV6Checksum(p->ip6h->s_ip6_addrs, (uint16_t *)p->tcph, + (p->payload_len + TCP_GET_HLEN(p)), p->tcph->th_sum); } } if (p->level4_comp_csum != 0) { ret = 0; if (p->livedev) { - (void) SC_ATOMIC_ADD(p->livedev->invalid_checksums, 1); + (void)SC_ATOMIC_ADD(p->livedev->invalid_checksums, 1); } else if (p->pcap_cnt) { PcapIncreaseInvalidChecksum(); } @@ -5559,13 +5523,14 @@ static int TcpSessionPacketIsStreamStarter(const Packet *p) } if ((p->tcph->th_flags & (TH_SYN | TH_ACK)) == TH_SYN) { - SCLogDebug("packet %"PRIu64" is a stream starter: %02x", p->pcap_cnt, p->tcph->th_flags); + SCLogDebug("packet %" PRIu64 " is a stream starter: %02x", p->pcap_cnt, p->tcph->th_flags); return 1; } if (stream_config.midstream || stream_config.async_oneside) { if ((p->tcph->th_flags & (TH_SYN | TH_ACK)) == (TH_SYN | TH_ACK)) { - SCLogDebug("packet %"PRIu64" is a midstream stream starter: %02x", p->pcap_cnt, p->tcph->th_flags); + SCLogDebug("packet %" PRIu64 " is a midstream stream starter: %02x", p->pcap_cnt, + p->tcph->th_flags); return 1; } } @@ -5591,33 +5556,45 @@ static int TcpSessionReuseDoneEnoughSyn(const Packet *p, const Flow *f, const Tc return 1; } if (SEQ_EQ(ssn->client.isn, TCP_GET_SEQ(p))) { - SCLogDebug("steam starter packet %"PRIu64", ssn %p. Packet SEQ == Stream ISN. Retransmission. Don't reuse.", p->pcap_cnt, ssn); + SCLogDebug("steam starter packet %" PRIu64 + ", ssn %p. Packet SEQ == Stream ISN. Retransmission. Don't reuse.", + p->pcap_cnt, ssn); return 0; } if (ssn->state >= TCP_LAST_ACK) { - SCLogDebug("steam starter packet %"PRIu64", ssn %p state >= TCP_LAST_ACK (%u). Reuse.", p->pcap_cnt, ssn, ssn->state); + SCLogDebug("steam starter packet %" PRIu64 + ", ssn %p state >= TCP_LAST_ACK (%u). Reuse.", + p->pcap_cnt, ssn, ssn->state); return 1; } else if (ssn->state == TCP_NONE) { - SCLogDebug("steam starter packet %"PRIu64", ssn %p state == TCP_NONE (%u). Reuse.", p->pcap_cnt, ssn, ssn->state); + SCLogDebug("steam starter packet %" PRIu64 ", ssn %p state == TCP_NONE (%u). Reuse.", + p->pcap_cnt, ssn, ssn->state); return 1; } else { // < TCP_LAST_ACK - SCLogDebug("steam starter packet %"PRIu64", ssn %p state < TCP_LAST_ACK (%u). Don't reuse.", p->pcap_cnt, ssn, ssn->state); + SCLogDebug("steam starter packet %" PRIu64 + ", ssn %p state < TCP_LAST_ACK (%u). Don't reuse.", + p->pcap_cnt, ssn, ssn->state); return 0; } } else { if (ssn == NULL) { - SCLogDebug("steam starter packet %"PRIu64", ssn %p null. Reuse.", p->pcap_cnt, ssn); + SCLogDebug("steam starter packet %" PRIu64 ", ssn %p null. Reuse.", p->pcap_cnt, ssn); return 1; } if (ssn->state >= TCP_LAST_ACK) { - SCLogDebug("steam starter packet %"PRIu64", ssn %p state >= TCP_LAST_ACK (%u). Reuse.", p->pcap_cnt, ssn, ssn->state); + SCLogDebug("steam starter packet %" PRIu64 + ", ssn %p state >= TCP_LAST_ACK (%u). Reuse.", + p->pcap_cnt, ssn, ssn->state); return 1; } else if (ssn->state == TCP_NONE) { - SCLogDebug("steam starter packet %"PRIu64", ssn %p state == TCP_NONE (%u). Reuse.", p->pcap_cnt, ssn, ssn->state); + SCLogDebug("steam starter packet %" PRIu64 ", ssn %p state == TCP_NONE (%u). Reuse.", + p->pcap_cnt, ssn, ssn->state); return 1; } else { // < TCP_LAST_ACK - SCLogDebug("steam starter packet %"PRIu64", ssn %p state < TCP_LAST_ACK (%u). Don't reuse.", p->pcap_cnt, ssn, ssn->state); + SCLogDebug("steam starter packet %" PRIu64 + ", ssn %p state < TCP_LAST_ACK (%u). Don't reuse.", + p->pcap_cnt, ssn, ssn->state); return 0; } } @@ -5634,37 +5611,50 @@ static int TcpSessionReuseDoneEnoughSynAck(const Packet *p, const Flow *f, const { if (FlowGetPacketDirection(f, p) == TOCLIENT) { if (ssn == NULL) { - SCLogDebug("steam starter packet %"PRIu64", ssn %p null. No reuse.", p->pcap_cnt, ssn); + SCLogDebug( + "steam starter packet %" PRIu64 ", ssn %p null. No reuse.", p->pcap_cnt, ssn); return 0; } if (SEQ_EQ(ssn->server.isn, TCP_GET_SEQ(p))) { - SCLogDebug("steam starter packet %"PRIu64", ssn %p. Packet SEQ == Stream ISN. Retransmission. Don't reuse.", p->pcap_cnt, ssn); + SCLogDebug("steam starter packet %" PRIu64 + ", ssn %p. Packet SEQ == Stream ISN. Retransmission. Don't reuse.", + p->pcap_cnt, ssn); return 0; } if (ssn->state >= TCP_LAST_ACK) { - SCLogDebug("steam starter packet %"PRIu64", ssn %p state >= TCP_LAST_ACK (%u). Reuse.", p->pcap_cnt, ssn, ssn->state); + SCLogDebug("steam starter packet %" PRIu64 + ", ssn %p state >= TCP_LAST_ACK (%u). Reuse.", + p->pcap_cnt, ssn, ssn->state); return 1; } else if (ssn->state == TCP_NONE) { - SCLogDebug("steam starter packet %"PRIu64", ssn %p state == TCP_NONE (%u). Reuse.", p->pcap_cnt, ssn, ssn->state); + SCLogDebug("steam starter packet %" PRIu64 ", ssn %p state == TCP_NONE (%u). Reuse.", + p->pcap_cnt, ssn, ssn->state); return 1; } else { // < TCP_LAST_ACK - SCLogDebug("steam starter packet %"PRIu64", ssn %p state < TCP_LAST_ACK (%u). Don't reuse.", p->pcap_cnt, ssn, ssn->state); + SCLogDebug("steam starter packet %" PRIu64 + ", ssn %p state < TCP_LAST_ACK (%u). Don't reuse.", + p->pcap_cnt, ssn, ssn->state); return 0; } } else { if (ssn == NULL) { - SCLogDebug("steam starter packet %"PRIu64", ssn %p null. Reuse.", p->pcap_cnt, ssn); + SCLogDebug("steam starter packet %" PRIu64 ", ssn %p null. Reuse.", p->pcap_cnt, ssn); return 1; } if (ssn->state >= TCP_LAST_ACK) { - SCLogDebug("steam starter packet %"PRIu64", ssn %p state >= TCP_LAST_ACK (%u). Reuse.", p->pcap_cnt, ssn, ssn->state); + SCLogDebug("steam starter packet %" PRIu64 + ", ssn %p state >= TCP_LAST_ACK (%u). Reuse.", + p->pcap_cnt, ssn, ssn->state); return 1; } else if (ssn->state == TCP_NONE) { - SCLogDebug("steam starter packet %"PRIu64", ssn %p state == TCP_NONE (%u). Reuse.", p->pcap_cnt, ssn, ssn->state); + SCLogDebug("steam starter packet %" PRIu64 ", ssn %p state == TCP_NONE (%u). Reuse.", + p->pcap_cnt, ssn, ssn->state); return 1; } else { // < TCP_LAST_ACK - SCLogDebug("steam starter packet %"PRIu64", ssn %p state < TCP_LAST_ACK (%u). Don't reuse.", p->pcap_cnt, ssn, ssn->state); + SCLogDebug("steam starter packet %" PRIu64 + ", ssn %p state < TCP_LAST_ACK (%u). Don't reuse.", + p->pcap_cnt, ssn, ssn->state); return 0; } } @@ -5705,7 +5695,7 @@ int TcpSessionPacketSsnReuse(const Packet *p, const Flow *f, const void *tcp_ssn return 0; } -TmEcode StreamTcp (ThreadVars *tv, Packet *p, void *data, PacketQueueNoLock *pq) +TmEcode StreamTcp(ThreadVars *tv, Packet *p, void *data, PacketQueueNoLock *pq) { DEBUG_VALIDATE_BUG_ON(p->flow == NULL); if (unlikely(p->flow == NULL)) { @@ -5738,7 +5728,7 @@ TmEcode StreamTcp (ThreadVars *tv, Packet *p, void *data, PacketQueueNoLock *pq) p->flags |= PKT_IGNORE_CHECKSUM; } } else { - p->flags |= PKT_IGNORE_CHECKSUM; //TODO check that this is set at creation + p->flags |= PKT_IGNORE_CHECKSUM; // TODO check that this is set at creation } AppLayerProfilingReset(stt->ra_ctx->app_tctx); @@ -5782,29 +5772,30 @@ TmEcode StreamTcpThreadInit(ThreadVars *tv, void *initdata, void **data) stt->ra_ctx->counter_tcp_stream_depth = StatsRegisterCounter("tcp.stream_depth_reached", tv); stt->ra_ctx->counter_tcp_reass_gap = StatsRegisterCounter("tcp.reassembly_gap", tv); stt->ra_ctx->counter_tcp_reass_overlap = StatsRegisterCounter("tcp.overlap", tv); - stt->ra_ctx->counter_tcp_reass_overlap_diff_data = StatsRegisterCounter("tcp.overlap_diff_data", tv); + stt->ra_ctx->counter_tcp_reass_overlap_diff_data = + StatsRegisterCounter("tcp.overlap_diff_data", tv); - stt->ra_ctx->counter_tcp_reass_data_normal_fail = StatsRegisterCounter("tcp.insert_data_normal_fail", tv); - stt->ra_ctx->counter_tcp_reass_data_overlap_fail = StatsRegisterCounter("tcp.insert_data_overlap_fail", tv); + stt->ra_ctx->counter_tcp_reass_data_normal_fail = + StatsRegisterCounter("tcp.insert_data_normal_fail", tv); + stt->ra_ctx->counter_tcp_reass_data_overlap_fail = + StatsRegisterCounter("tcp.insert_data_overlap_fail", tv); - SCLogDebug("StreamTcp thread specific ctx online at %p, reassembly ctx %p", - stt, stt->ra_ctx); + SCLogDebug("StreamTcp thread specific ctx online at %p, reassembly ctx %p", stt, stt->ra_ctx); SCMutexLock(&ssn_pool_mutex); if (ssn_pool == NULL) { ssn_pool = PoolThreadInit(1, /* thread */ - 0, /* unlimited */ - stream_config.prealloc_sessions, - sizeof(TcpSession), - StreamTcpSessionPoolAlloc, - StreamTcpSessionPoolInit, NULL, - StreamTcpSessionPoolCleanup, NULL); + 0, /* unlimited */ + stream_config.prealloc_sessions, sizeof(TcpSession), StreamTcpSessionPoolAlloc, + StreamTcpSessionPoolInit, NULL, StreamTcpSessionPoolCleanup, NULL); stt->ssn_pool_id = 0; - SCLogDebug("pool size %d, thread ssn_pool_id %d", PoolThreadSize(ssn_pool), stt->ssn_pool_id); + SCLogDebug( + "pool size %d, thread ssn_pool_id %d", PoolThreadSize(ssn_pool), stt->ssn_pool_id); } else { /* grow ssn_pool until we have a element for our thread id */ stt->ssn_pool_id = PoolThreadExpand(ssn_pool); - SCLogDebug("pool size %d, thread ssn_pool_id %d", PoolThreadSize(ssn_pool), stt->ssn_pool_id); + SCLogDebug( + "pool size %d, thread ssn_pool_id %d", PoolThreadSize(ssn_pool), stt->ssn_pool_id); } SCMutexUnlock(&ssn_pool_mutex); if (stt->ssn_pool_id < 0 || ssn_pool == NULL) { @@ -5887,8 +5878,8 @@ static int StreamTcpValidateRst(TcpSession *ssn, Packet *p) os_policy = ssn->server.os_policy; - if (p->tcph->th_flags & TH_ACK && - TCP_GET_ACK(p) && StreamTcpValidateAck(ssn, &ssn->server, p) == -1) { + if (p->tcph->th_flags & TH_ACK && TCP_GET_ACK(p) && + StreamTcpValidateAck(ssn, &ssn->server, p) == -1) { SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn); StreamTcpSetEvent(p, STREAM_RST_INVALID_ACK); SCReturnInt(0); @@ -5900,8 +5891,8 @@ static int StreamTcpValidateRst(TcpSession *ssn, Packet *p) os_policy = ssn->client.os_policy; - if (p->tcph->th_flags & TH_ACK && - TCP_GET_ACK(p) && StreamTcpValidateAck(ssn, &ssn->client, p) == -1) { + if (p->tcph->th_flags & TH_ACK && TCP_GET_ACK(p) && + StreamTcpValidateAck(ssn, &ssn->client, p) == -1) { SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn); StreamTcpSetEvent(p, STREAM_RST_INVALID_ACK); SCReturnInt(0); @@ -5941,26 +5932,24 @@ static int StreamTcpValidateRst(TcpSession *ssn, Packet *p) switch (os_policy) { case OS_POLICY_HPUX11: - if(PKT_IS_TOSERVER(p)){ - if(SEQ_GEQ(TCP_GET_SEQ(p), ssn->client.next_seq)) { - SCLogDebug("reset is Valid! Packet SEQ: %" PRIu32 "", - TCP_GET_SEQ(p)); + if (PKT_IS_TOSERVER(p)) { + if (SEQ_GEQ(TCP_GET_SEQ(p), ssn->client.next_seq)) { + SCLogDebug("reset is Valid! Packet SEQ: %" PRIu32 "", TCP_GET_SEQ(p)); return 1; } else { SCLogDebug("reset is not Valid! Packet SEQ: %" PRIu32 " " - "and server SEQ: %" PRIu32 "", TCP_GET_SEQ(p), - ssn->client.next_seq); + "and server SEQ: %" PRIu32 "", + TCP_GET_SEQ(p), ssn->client.next_seq); return 0; } } else { /* implied to client */ - if(SEQ_GEQ(TCP_GET_SEQ(p), ssn->server.next_seq)) { - SCLogDebug("reset is valid! Packet SEQ: %" PRIu32 "", - TCP_GET_SEQ(p)); + if (SEQ_GEQ(TCP_GET_SEQ(p), ssn->server.next_seq)) { + SCLogDebug("reset is valid! Packet SEQ: %" PRIu32 "", TCP_GET_SEQ(p)); return 1; } else { SCLogDebug("reset is not valid! Packet SEQ: %" PRIu32 " " - "and client SEQ: %" PRIu32 "", TCP_GET_SEQ(p), - ssn->server.next_seq); + "and client SEQ: %" PRIu32 "", + TCP_GET_SEQ(p), ssn->server.next_seq); return 0; } } @@ -5968,38 +5957,30 @@ static int StreamTcpValidateRst(TcpSession *ssn, Packet *p) case OS_POLICY_OLD_LINUX: case OS_POLICY_LINUX: case OS_POLICY_SOLARIS: - if(PKT_IS_TOSERVER(p)){ - if(SEQ_GEQ((TCP_GET_SEQ(p)+p->payload_len), - ssn->client.last_ack)) - { /*window base is needed !!*/ - if(SEQ_LT(TCP_GET_SEQ(p), - (ssn->client.next_seq + ssn->client.window))) - { - SCLogDebug("reset is Valid! Packet SEQ: %" PRIu32 "", - TCP_GET_SEQ(p)); + if (PKT_IS_TOSERVER(p)) { + if (SEQ_GEQ((TCP_GET_SEQ(p) + p->payload_len), + ssn->client.last_ack)) { /*window base is needed !!*/ + if (SEQ_LT(TCP_GET_SEQ(p), (ssn->client.next_seq + ssn->client.window))) { + SCLogDebug("reset is Valid! Packet SEQ: %" PRIu32 "", TCP_GET_SEQ(p)); return 1; } } else { SCLogDebug("reset is not valid! Packet SEQ: %" PRIu32 " and" - " server SEQ: %" PRIu32 "", TCP_GET_SEQ(p), - ssn->client.next_seq); + " server SEQ: %" PRIu32 "", + TCP_GET_SEQ(p), ssn->client.next_seq); return 0; } } else { /* implied to client */ - if(SEQ_GEQ((TCP_GET_SEQ(p) + p->payload_len), - ssn->server.last_ack)) - { /*window base is needed !!*/ - if(SEQ_LT(TCP_GET_SEQ(p), - (ssn->server.next_seq + ssn->server.window))) - { - SCLogDebug("reset is Valid! Packet SEQ: %" PRIu32 "", - TCP_GET_SEQ(p)); + if (SEQ_GEQ((TCP_GET_SEQ(p) + p->payload_len), + ssn->server.last_ack)) { /*window base is needed !!*/ + if (SEQ_LT(TCP_GET_SEQ(p), (ssn->server.next_seq + ssn->server.window))) { + SCLogDebug("reset is Valid! Packet SEQ: %" PRIu32 "", TCP_GET_SEQ(p)); return 1; } } else { SCLogDebug("reset is not valid! Packet SEQ: %" PRIu32 " and" - " client SEQ: %" PRIu32 "", TCP_GET_SEQ(p), - ssn->server.next_seq); + " client SEQ: %" PRIu32 "", + TCP_GET_SEQ(p), ssn->server.next_seq); return 0; } } @@ -6014,26 +5995,25 @@ static int StreamTcpValidateRst(TcpSession *ssn, Packet *p) case OS_POLICY_WINDOWS: case OS_POLICY_WINDOWS2K3: case OS_POLICY_VISTA: - if(PKT_IS_TOSERVER(p)) { - if(SEQ_EQ(TCP_GET_SEQ(p), ssn->client.next_seq)) { - SCLogDebug("reset is valid! Packet SEQ: %" PRIu32 "", - TCP_GET_SEQ(p)); + if (PKT_IS_TOSERVER(p)) { + if (SEQ_EQ(TCP_GET_SEQ(p), ssn->client.next_seq)) { + SCLogDebug("reset is valid! Packet SEQ: %" PRIu32 "", TCP_GET_SEQ(p)); return 1; } else { SCLogDebug("reset is not valid! Packet SEQ: %" PRIu32 " " - "and server SEQ: %" PRIu32 "", TCP_GET_SEQ(p), - ssn->client.next_seq); + "and server SEQ: %" PRIu32 "", + TCP_GET_SEQ(p), ssn->client.next_seq); return 0; } } else { /* implied to client */ if (SEQ_EQ(TCP_GET_SEQ(p), ssn->server.next_seq)) { - SCLogDebug("reset is valid! Packet SEQ: %" PRIu32 " Stream %u", - TCP_GET_SEQ(p), ssn->server.next_seq); + SCLogDebug("reset is valid! Packet SEQ: %" PRIu32 " Stream %u", TCP_GET_SEQ(p), + ssn->server.next_seq); return 1; } else { SCLogDebug("reset is not valid! Packet SEQ: %" PRIu32 " and" " client SEQ: %" PRIu32 "", - TCP_GET_SEQ(p), ssn->server.next_seq); + TCP_GET_SEQ(p), ssn->server.next_seq); return 0; } } @@ -6056,7 +6036,7 @@ static int StreamTcpValidateRst(TcpSession *ssn, Packet *p) * \retval 1 if the timestamp is valid * \retval 0 if the timestamp is invalid */ -static int StreamTcpValidateTimestamp (TcpSession *ssn, Packet *p) +static int StreamTcpValidateTimestamp(TcpSession *ssn, Packet *p) { SCEnter(); @@ -6132,28 +6112,27 @@ static int StreamTcpValidateTimestamp (TcpSession *ssn, Packet *p) if (check_ts) { int32_t result = 0; - SCLogDebug("ts %"PRIu32", last_ts %"PRIu32"", ts, last_ts); + SCLogDebug("ts %" PRIu32 ", last_ts %" PRIu32 "", ts, last_ts); if (receiver_stream->os_policy == OS_POLICY_LINUX || stream_config.liberal_timestamps) { /* Linux accepts TS which are off by one.*/ - result = (int32_t) ((ts - last_ts) + 1); + result = (int32_t)((ts - last_ts) + 1); } else { - result = (int32_t) (ts - last_ts); + result = (int32_t)(ts - last_ts); } SCLogDebug("result %" PRIi32 ", p->ts(secs) %" PRIuMAX "", result, (uintmax_t)SCTIME_SECS(p->ts)); - if (last_pkt_ts == 0 && - (ssn->flags & STREAMTCP_FLAG_MIDSTREAM)) - { + if (last_pkt_ts == 0 && (ssn->flags & STREAMTCP_FLAG_MIDSTREAM)) { last_pkt_ts = SCTIME_SECS(p->ts); } if (result < 0) { SCLogDebug("timestamp is not valid last_ts " "%" PRIu32 " p->tcpvars->ts %" PRIu32 " result " - "%" PRId32 "", last_ts, ts, result); + "%" PRId32 "", + last_ts, ts, result); /* candidate for rejection */ ret = 0; } else if ((sender_stream->last_ts != 0) && @@ -6196,7 +6175,7 @@ static int StreamTcpValidateTimestamp (TcpSession *ssn, Packet *p) * \retval 1 if the timestamp is valid * \retval 0 if the timestamp is invalid */ -static int StreamTcpHandleTimestamp (TcpSession *ssn, Packet *p) +static int StreamTcpHandleTimestamp(TcpSession *ssn, Packet *p) { SCEnter(); @@ -6274,28 +6253,27 @@ static int StreamTcpHandleTimestamp (TcpSession *ssn, Packet *p) if (check_ts) { int32_t result = 0; - SCLogDebug("ts %"PRIu32", last_ts %"PRIu32"", ts, sender_stream->last_ts); + SCLogDebug("ts %" PRIu32 ", last_ts %" PRIu32 "", ts, sender_stream->last_ts); if (receiver_stream->os_policy == OS_POLICY_LINUX || stream_config.liberal_timestamps) { /* Linux accepts TS which are off by one.*/ - result = (int32_t) ((ts - sender_stream->last_ts) + 1); + result = (int32_t)((ts - sender_stream->last_ts) + 1); } else { - result = (int32_t) (ts - sender_stream->last_ts); + result = (int32_t)(ts - sender_stream->last_ts); } SCLogDebug("result %" PRIi32 ", p->ts(sec) %" PRIuMAX "", result, (uintmax_t)SCTIME_SECS(p->ts)); - if (sender_stream->last_pkt_ts == 0 && - (ssn->flags & STREAMTCP_FLAG_MIDSTREAM)) - { + if (sender_stream->last_pkt_ts == 0 && (ssn->flags & STREAMTCP_FLAG_MIDSTREAM)) { sender_stream->last_pkt_ts = SCTIME_SECS(p->ts); } if (result < 0) { SCLogDebug("timestamp is not valid sender_stream->last_ts " "%" PRIu32 " p->tcpvars->ts %" PRIu32 " result " - "%" PRId32 "", sender_stream->last_ts, ts, result); + "%" PRId32 "", + sender_stream->last_ts, ts, result); /* candidate for rejection */ ret = 0; } else if ((sender_stream->last_ts != 0) && @@ -6368,8 +6346,7 @@ static inline int StreamTcpValidateAck(TcpSession *ssn, TcpStream *stream, Packe const uint32_t ack = TCP_GET_ACK(p); /* fast track */ - if (SEQ_GT(ack, stream->last_ack) && SEQ_LEQ(ack, stream->next_win)) - { + if (SEQ_GT(ack, stream->last_ack) && SEQ_LEQ(ack, stream->next_win)) { SCLogDebug("ssn %p: ACK %u in bounds > %u <= %u", ssn, ack, stream->last_ack, stream->next_win); SCReturnInt(0); @@ -6383,15 +6360,16 @@ static inline int StreamTcpValidateAck(TcpSession *ssn, TcpStream *stream, Packe /* exception handling */ if (SEQ_LT(ack, stream->last_ack)) { - SCLogDebug("pkt ACK %"PRIu32" < stream last ACK %"PRIu32, TCP_GET_ACK(p), stream->last_ack); + SCLogDebug( + "pkt ACK %" PRIu32 " < stream last ACK %" PRIu32, TCP_GET_ACK(p), stream->last_ack); /* This is an attempt to get a 'left edge' value that we can check against. * It doesn't work when the window is 0, need to think of a better way. */ if (stream->window != 0 && SEQ_LT(ack, (stream->last_ack - stream->window))) { - SCLogDebug("ACK %"PRIu32" is before last_ack %"PRIu32" - window " - "%"PRIu32" = %"PRIu32, ack, stream->last_ack, - stream->window, stream->last_ack - stream->window); + SCLogDebug("ACK %" PRIu32 " is before last_ack %" PRIu32 " - window " + "%" PRIu32 " = %" PRIu32, + ack, stream->last_ack, stream->window, stream->last_ack - stream->window); goto invalid; } @@ -6404,18 +6382,18 @@ static inline int StreamTcpValidateAck(TcpSession *ssn, TcpStream *stream, Packe } if (ssn->state > TCP_SYN_SENT && SEQ_GT(ack, stream->next_win)) { - SCLogDebug("ACK %"PRIu32" is after next_win %"PRIu32, ack, stream->next_win); + SCLogDebug("ACK %" PRIu32 " is after next_win %" PRIu32, ack, stream->next_win); goto invalid; /* a toclient RST as a response to SYN, next_win is 0, ack will be isn+1, just like * the syn ack */ - } else if (ssn->state == TCP_SYN_SENT && PKT_IS_TOCLIENT(p) && - p->tcph->th_flags & TH_RST && - SEQ_EQ(ack, stream->isn + 1)) { + } else if (ssn->state == TCP_SYN_SENT && PKT_IS_TOCLIENT(p) && p->tcph->th_flags & TH_RST && + SEQ_EQ(ack, stream->isn + 1)) { SCReturnInt(0); } - SCLogDebug("default path leading to invalid: ACK %"PRIu32", last_ack %"PRIu32 - " next_win %"PRIu32, ack, stream->last_ack, stream->next_win); + SCLogDebug("default path leading to invalid: ACK %" PRIu32 ", last_ack %" PRIu32 + " next_win %" PRIu32, + ack, stream->last_ack, stream->next_win); invalid: StreamTcpSetEvent(p, STREAM_PKT_INVALID_ACK); SCReturnInt(-1); @@ -6426,8 +6404,7 @@ static inline int StreamTcpValidateAck(TcpSession *ssn, TcpStream *stream, Packe * \param ssn TCP Session * \param direction direction to set the flag in: 0 toserver, 1 toclient */ -void StreamTcpUpdateAppLayerProgress(TcpSession *ssn, char direction, - const uint32_t progress) +void StreamTcpUpdateAppLayerProgress(TcpSession *ssn, char direction, const uint32_t progress) { if (direction) { ssn->server.app_progress_rel += progress; @@ -6464,8 +6441,8 @@ void StreamTcpSetSessionNoReassemblyFlag(TcpSession *ssn, char direction) */ void StreamTcpSetDisableRawReassemblyFlag(TcpSession *ssn, char direction) { - direction ? (ssn->server.flags |= STREAMTCP_STREAM_FLAG_NEW_RAW_DISABLED) : - (ssn->client.flags |= STREAMTCP_STREAM_FLAG_NEW_RAW_DISABLED); + direction ? (ssn->server.flags |= STREAMTCP_STREAM_FLAG_NEW_RAW_DISABLED) + : (ssn->client.flags |= STREAMTCP_STREAM_FLAG_NEW_RAW_DISABLED); } /** \brief enable bypass @@ -6485,9 +6462,8 @@ void StreamTcpSetSessionBypassFlag(TcpSession *ssn) * \param pq packet queue to store the new pseudo packet in * \param dir 0 ts 1 tc */ -static void StreamTcpPseudoPacketCreateDetectLogFlush(ThreadVars *tv, - StreamTcpThread *stt, Packet *parent, - TcpSession *ssn, PacketQueueNoLock *pq, int dir) +static void StreamTcpPseudoPacketCreateDetectLogFlush(ThreadVars *tv, StreamTcpThread *stt, + Packet *parent, TcpSession *ssn, PacketQueueNoLock *pq, int dir) { SCEnter(); Flow *f = parent->flow; @@ -6548,7 +6524,7 @@ static void StreamTcpPseudoPacketCreateDetectLogFlush(ThreadVars *tv, /* Check if we have enough room in direct data. We need ipv4 hdr + tcp hdr. * Force an allocation if it is not the case. */ - if (GET_PKT_DIRECT_MAX_SIZE(np) < 40) { + if (GET_PKT_DIRECT_MAX_SIZE(np) < 40) { if (PacketCallocExtPkt(np, 40) == -1) { goto error; } @@ -6592,7 +6568,7 @@ static void StreamTcpPseudoPacketCreateDetectLogFlush(ThreadVars *tv, /* Check if we have enough room in direct data. We need ipv6 hdr + tcp hdr. * Force an allocation if it is not the case. */ - if (GET_PKT_DIRECT_MAX_SIZE(np) < 60) { + if (GET_PKT_DIRECT_MAX_SIZE(np) < 60) { if (PacketCallocExtPkt(np, 60) == -1) { goto error; } @@ -6644,7 +6620,7 @@ static void StreamTcpPseudoPacketCreateDetectLogFlush(ThreadVars *tv, np->tcph->th_seq = htonl(ssn->client.next_seq); np->tcph->th_ack = htonl(ssn->server.last_ack); - /* to client */ + /* to client */ } else { np->tcph->th_sport = htons(f->dp); np->tcph->th_dport = htons(f->sp); @@ -6673,16 +6649,16 @@ static void StreamTcpPseudoPacketCreateDetectLogFlush(ThreadVars *tv, * Flag TCP engine that data needs to be inspected regardless * of how far we are wrt inspect limits. */ -void StreamTcpDetectLogFlush(ThreadVars *tv, StreamTcpThread *stt, Flow *f, Packet *p, - PacketQueueNoLock *pq) +void StreamTcpDetectLogFlush( + ThreadVars *tv, StreamTcpThread *stt, Flow *f, Packet *p, PacketQueueNoLock *pq) { TcpSession *ssn = f->protoctx; ssn->client.flags |= STREAMTCP_STREAM_FLAG_TRIGGER_RAW; ssn->server.flags |= STREAMTCP_STREAM_FLAG_TRIGGER_RAW; bool ts = PKT_IS_TOSERVER(p) ? true : false; ts ^= StreamTcpInlineMode(); - StreamTcpPseudoPacketCreateDetectLogFlush(tv, stt, p, ssn, pq, ts^0); - StreamTcpPseudoPacketCreateDetectLogFlush(tv, stt, p, ssn, pq, ts^1); + StreamTcpPseudoPacketCreateDetectLogFlush(tv, stt, p, ssn, pq, ts ^ 0); + StreamTcpPseudoPacketCreateDetectLogFlush(tv, stt, p, ssn, pq, ts ^ 1); } /** @@ -6697,7 +6673,8 @@ void StreamTcpDetectLogFlush(ThreadVars *tv, StreamTcpThread *stt, Flow *f, Pack * \return -1 in case of error, the number of segment in case of success * */ -int StreamTcpSegmentForEach(const Packet *p, uint8_t flag, StreamSegmentCallback CallbackFunc, void *data) +int StreamTcpSegmentForEach( + const Packet *p, uint8_t flag, StreamSegmentCallback CallbackFunc, void *data) { TcpStream *stream = NULL; int cnt = 0; @@ -6718,7 +6695,8 @@ int StreamTcpSegmentForEach(const Packet *p, uint8_t flag, StreamSegmentCallback /* for IDS, return ack'd segments. For IPS all. */ TcpSegment *seg; - RB_FOREACH(seg, TCPSEG, &stream->seg_tree) { + RB_FOREACH(seg, TCPSEG, &stream->seg_tree) + { if (!(stream_config.flags & STREAMTCP_INIT_FLAG_INLINE)) { if (PKT_IS_PSEUDOPKT(p)) { /* use un-ACK'd data as well */ @@ -6855,7 +6833,6 @@ bool StreamTcpInlineMode(void) return (stream_config.flags & STREAMTCP_INIT_FLAG_INLINE); } - void TcpSessionSetReassemblyDepth(TcpSession *ssn, uint32_t size) { if (size > ssn->reassembly_depth || size == 0) { diff --git a/src/stream-tcp.h b/src/stream-tcp.h index ff8a0998cb4e..2d4713b4fd39 100644 --- a/src/stream-tcp.h +++ b/src/stream-tcp.h @@ -34,10 +34,10 @@ #define STREAM_VERBOSE false /* Flag to indicate that the checksum validation for the stream engine has been enabled */ -#define STREAMTCP_INIT_FLAG_CHECKSUM_VALIDATION BIT_U8(0) -#define STREAMTCP_INIT_FLAG_DROP_INVALID BIT_U8(1) -#define STREAMTCP_INIT_FLAG_BYPASS BIT_U8(2) -#define STREAMTCP_INIT_FLAG_INLINE BIT_U8(3) +#define STREAMTCP_INIT_FLAG_CHECKSUM_VALIDATION BIT_U8(0) +#define STREAMTCP_INIT_FLAG_DROP_INVALID BIT_U8(1) +#define STREAMTCP_INIT_FLAG_BYPASS BIT_U8(2) +#define STREAMTCP_INIT_FLAG_INLINE BIT_U8(3) /*global flow data*/ typedef struct TcpStreamCnf_ { @@ -61,7 +61,7 @@ typedef struct TcpStreamCnf_ { bool streaming_log_api; uint8_t max_syn_queued; - uint32_t reassembly_depth; /**< Depth until when we reassemble the stream */ + uint32_t reassembly_depth; /**< Depth until when we reassemble the stream */ uint16_t reassembly_toserver_chunk_size; uint16_t reassembly_toclient_chunk_size; @@ -105,9 +105,9 @@ typedef struct StreamTcpThread_ { extern TcpStreamCnf stream_config; void StreamTcpInitConfig(bool); void StreamTcpFreeConfig(bool); -void StreamTcpRegisterTests (void); +void StreamTcpRegisterTests(void); -void StreamTcpSessionPktFree (Packet *); +void StreamTcpSessionPktFree(Packet *); void StreamTcpInitMemuse(void); void StreamTcpIncrMemuse(uint64_t); @@ -118,9 +118,8 @@ int StreamTcpCheckMemcap(uint64_t); uint64_t StreamTcpMemuseCounter(void); uint64_t StreamTcpReassembleMemuseGlobalCounter(void); -int StreamTcpSegmentForEach(const Packet *p, uint8_t flag, - StreamSegmentCallback CallbackFunc, - void *data); +int StreamTcpSegmentForEach( + const Packet *p, uint8_t flag, StreamSegmentCallback CallbackFunc, void *data); int StreamTcpSegmentForSession( const Packet *p, uint8_t flag, StreamSegmentCallback CallbackFunc, void *data); void StreamTcpReassembleConfigEnableOverlapCheck(void); @@ -131,16 +130,14 @@ typedef int (*StreamReassembleRawFunc)( int StreamReassembleForFrame(TcpSession *ssn, TcpStream *stream, StreamReassembleRawFunc Callback, void *cb_data, const uint64_t offset, const bool eof); -int StreamReassembleLog(TcpSession *ssn, TcpStream *stream, - StreamReassembleRawFunc Callback, void *cb_data, - uint64_t progress_in, - uint64_t *progress_out, bool eof); -int StreamReassembleRaw(TcpSession *ssn, const Packet *p, - StreamReassembleRawFunc Callback, void *cb_data, - uint64_t *progress_out, bool respect_inspect_depth); +int StreamReassembleLog(TcpSession *ssn, TcpStream *stream, StreamReassembleRawFunc Callback, + void *cb_data, uint64_t progress_in, uint64_t *progress_out, bool eof); +int StreamReassembleRaw(TcpSession *ssn, const Packet *p, StreamReassembleRawFunc Callback, + void *cb_data, uint64_t *progress_out, bool respect_inspect_depth); void StreamReassembleRawUpdateProgress(TcpSession *ssn, Packet *p, const uint64_t progress); -void StreamTcpDetectLogFlush(ThreadVars *tv, StreamTcpThread *stt, Flow *f, Packet *p, PacketQueueNoLock *pq); +void StreamTcpDetectLogFlush( + ThreadVars *tv, StreamTcpThread *stt, Flow *f, Packet *p, PacketQueueNoLock *pq); const char *StreamTcpStateAsString(const enum TcpState); const char *StreamTcpSsnStateAsString(const TcpSession *ssn); @@ -148,14 +145,14 @@ const char *StreamTcpSsnStateAsString(const TcpSession *ssn); /** ------- Inline functions: ------ */ /** - * \brief If we are on IPS mode, and got a drop action triggered from - * the IP only module, or from a reassembled msg and/or from an - * applayer detection, then drop the rest of the packets of the - * same stream and avoid inspecting it any further - * \param p pointer to the Packet to check - * \retval 1 if we must drop this stream - * \retval 0 if the stream still legal - */ + * \brief If we are on IPS mode, and got a drop action triggered from + * the IP only module, or from a reassembled msg and/or from an + * applayer detection, then drop the rest of the packets of the + * same stream and avoid inspecting it any further + * \param p pointer to the Packet to check + * \retval 1 if we must drop this stream + * \retval 0 if the stream still legal + */ static inline int StreamTcpCheckFlowDrops(Packet *p) { /* If we are on IPS mode, and got a drop action triggered from @@ -176,13 +173,12 @@ enum { STREAM_HAS_UNPROCESSED_SEGMENTS_NEED_ONLY_DETECTION = 1, }; -TmEcode StreamTcp (ThreadVars *, Packet *, void *, PacketQueueNoLock *); +TmEcode StreamTcp(ThreadVars *, Packet *, void *, PacketQueueNoLock *); uint8_t StreamNeedsReassembly(const TcpSession *ssn, uint8_t direction); TmEcode StreamTcpThreadInit(ThreadVars *, void *, void **); TmEcode StreamTcpThreadDeinit(ThreadVars *tv, void *data); -int StreamTcpPacket (ThreadVars *tv, Packet *p, StreamTcpThread *stt, - PacketQueueNoLock *pq); +int StreamTcpPacket(ThreadVars *tv, Packet *p, StreamTcpThread *stt, PacketQueueNoLock *pq); /* clear ssn and return to pool */ void StreamTcpSessionClear(void *ssnptr); /* cleanup ssn, but don't free ssn */ @@ -195,8 +191,7 @@ bool StreamTcpInlineMode(void); int TcpSessionPacketSsnReuse(const Packet *p, const Flow *f, const void *tcp_ssn); -void StreamTcpUpdateAppLayerProgress(TcpSession *ssn, char direction, - const uint32_t progress); +void StreamTcpUpdateAppLayerProgress(TcpSession *ssn, char direction, const uint32_t progress); uint64_t StreamTcpGetAcked(const TcpStream *stream); uint64_t StreamTcpGetUsable(const TcpStream *stream, const bool eof); @@ -206,4 +201,3 @@ void StreamTcpThreadCacheEnable(void); void StreamTcpThreadCacheCleanup(void); #endif /* __STREAM_TCP_H__ */ - diff --git a/src/stream.c b/src/stream.c index 7fea5ba55c9e..94b6efe8bc85 100644 --- a/src/stream.c +++ b/src/stream.c @@ -37,9 +37,10 @@ * * \return -1 in case of error, the number of segment in case of success */ -int StreamSegmentForEach(const Packet *p, uint8_t flag, StreamSegmentCallback CallbackFunc, void *data) +int StreamSegmentForEach( + const Packet *p, uint8_t flag, StreamSegmentCallback CallbackFunc, void *data) { - switch(p->proto) { + switch (p->proto) { case IPPROTO_TCP: return StreamTcpSegmentForEach(p, flag, CallbackFunc, data); break; diff --git a/src/stream.h b/src/stream.h index 4821dc9981f5..53af26c4cf6a 100644 --- a/src/stream.h +++ b/src/stream.h @@ -35,11 +35,9 @@ typedef int (*StreamSegmentCallback)( const Packet *, TcpSegment *, void *, const uint8_t *, uint32_t); -int StreamSegmentForEach(const Packet *p, uint8_t flag, - StreamSegmentCallback CallbackFunc, - void *data); +int StreamSegmentForEach( + const Packet *p, uint8_t flag, StreamSegmentCallback CallbackFunc, void *data); int StreamSegmentForSession( const Packet *p, uint8_t flag, StreamSegmentCallback CallbackFunc, void *data); #endif /* __STREAM_H__ */ - diff --git a/src/suricata-common.h b/src/suricata-common.h index 297a6fc4521e..2bcfad6c25a4 100644 --- a/src/suricata-common.h +++ b/src/suricata-common.h @@ -133,7 +133,7 @@ #endif #if HAVE_SCHED_H -#include /* for sched_setaffinity(2) */ +#include /* for sched_setaffinity(2) */ #endif #ifdef HAVE_TYPE_U_LONG_NOT_DEFINED @@ -288,23 +288,26 @@ typedef unsigned char u_char; /* we need this to stringify the defines which are supplied at compiletime see: http://gcc.gnu.org/onlinedocs/gcc-3.4.1/cpp/Stringification.html#Stringification */ #define xstr(s) str(s) -#define str(s) #s +#define str(s) #s -#if CPPCHECK==1 - #define BUG_ON(x) if (((x))) exit(1) +#if CPPCHECK == 1 +#define BUG_ON(x) \ + if (((x))) \ + exit(1) #else - #if defined HAVE_ASSERT_H && !defined NDEBUG - #include - #define BUG_ON(x) assert(!(x)) - #else - #define BUG_ON(x) do { \ - if (((x))) { \ - fprintf(stderr, "BUG at %s:%d(%s)\n", __FILE__, __LINE__, __func__); \ - fprintf(stderr, "Code: '%s'\n", xstr((x))); \ - exit(EXIT_FAILURE); \ - } \ - } while(0) - #endif +#if defined HAVE_ASSERT_H && !defined NDEBUG +#include +#define BUG_ON(x) assert(!(x)) +#else +#define BUG_ON(x) \ + do { \ + if (((x))) { \ + fprintf(stderr, "BUG at %s:%d(%s)\n", __FILE__, __LINE__, __func__); \ + fprintf(stderr, "Code: '%s'\n", xstr((x))); \ + exit(EXIT_FAILURE); \ + } \ + } while (0) +#endif #endif /** type for the internal signature id. Since it's used in the matching engine @@ -319,85 +322,84 @@ typedef unsigned char u_char; /** FreeBSD does not define __WORDSIZE, but it uses __LONG_BIT */ #ifndef __WORDSIZE - #ifdef __LONG_BIT - #define __WORDSIZE __LONG_BIT - #else - #ifdef LONG_BIT - #define __WORDSIZE LONG_BIT - #endif - #endif +#ifdef __LONG_BIT +#define __WORDSIZE __LONG_BIT +#else +#ifdef LONG_BIT +#define __WORDSIZE LONG_BIT +#endif +#endif #endif /** Windows does not define __WORDSIZE, but it uses __X86__ */ #ifndef __WORDSIZE - #if defined(__X86__) || defined(_X86_) || defined(_M_IX86) - #define __WORDSIZE 32 - #else - #if defined(__X86_64__) || defined(_X86_64_) || \ - defined(__x86_64) || defined(__x86_64__) || \ - defined(__amd64) || defined(__amd64__) - #define __WORDSIZE 64 - #endif - #endif +#if defined(__X86__) || defined(_X86_) || defined(_M_IX86) +#define __WORDSIZE 32 +#else +#if defined(__X86_64__) || defined(_X86_64_) || defined(__x86_64) || defined(__x86_64__) || \ + defined(__amd64) || defined(__amd64__) +#define __WORDSIZE 64 +#endif +#endif #endif /** if not succesful yet try the data models */ #ifndef __WORDSIZE - #if defined(_ILP32) || defined(__ILP32__) - #define __WORDSIZE 32 - #endif - #if defined(_LP64) || defined(__LP64__) - #define __WORDSIZE 64 - #endif +#if defined(_ILP32) || defined(__ILP32__) +#define __WORDSIZE 32 +#endif +#if defined(_LP64) || defined(__LP64__) +#define __WORDSIZE 64 +#endif #endif #ifndef __WORDSIZE - #warning Defaulting to __WORDSIZE 32 - #define __WORDSIZE 32 +#warning Defaulting to __WORDSIZE 32 +#define __WORDSIZE 32 #endif /** darwin doesn't defined __BYTE_ORDER and friends, but BYTE_ORDER */ #ifndef __BYTE_ORDER - #if defined(BYTE_ORDER) - #define __BYTE_ORDER BYTE_ORDER - #elif defined(__BYTE_ORDER__) - #define __BYTE_ORDER __BYTE_ORDER__ - #else - #error "byte order not detected" - #endif +#if defined(BYTE_ORDER) +#define __BYTE_ORDER BYTE_ORDER +#elif defined(__BYTE_ORDER__) +#define __BYTE_ORDER __BYTE_ORDER__ +#else +#error "byte order not detected" +#endif #endif #ifndef __LITTLE_ENDIAN - #if defined(LITTLE_ENDIAN) - #define __LITTLE_ENDIAN LITTLE_ENDIAN - #elif defined(__ORDER_LITTLE_ENDIAN__) - #define __LITTLE_ENDIAN __ORDER_LITTLE_ENDIAN__ - #endif +#if defined(LITTLE_ENDIAN) +#define __LITTLE_ENDIAN LITTLE_ENDIAN +#elif defined(__ORDER_LITTLE_ENDIAN__) +#define __LITTLE_ENDIAN __ORDER_LITTLE_ENDIAN__ +#endif #endif #ifndef __BIG_ENDIAN - #if defined(BIG_ENDIAN) - #define __BIG_ENDIAN BIG_ENDIAN - #elif defined(__ORDER_BIG_ENDIAN__) - #define __BIG_ENDIAN __ORDER_BIG_ENDIAN__ - #endif +#if defined(BIG_ENDIAN) +#define __BIG_ENDIAN BIG_ENDIAN +#elif defined(__ORDER_BIG_ENDIAN__) +#define __BIG_ENDIAN __ORDER_BIG_ENDIAN__ +#endif #endif #if !defined(__LITTLE_ENDIAN) && !defined(__BIG_ENDIAN) - #error "byte order: can't figure out big or little" +#error "byte order: can't figure out big or little" #endif #ifndef MIN -#define MIN(x, y) (((x)<(y))?(x):(y)) +#define MIN(x, y) (((x) < (y)) ? (x) : (y)) #endif #ifndef MAX -#define MAX(x, y) (((x)<(y))?(y):(x)) +#define MAX(x, y) (((x) < (y)) ? (y) : (x)) #endif #define BIT_U8(n) ((uint8_t)(1 << (n))) #define BIT_U16(n) ((uint16_t)(1 << (n))) -#define BIT_U32(n) (1UL << (n)) +#define BIT_U32(n) (1UL << (n)) #define BIT_U64(n) (1ULL << (n)) #define WARN_UNUSED __attribute__((warn_unused_result)) @@ -410,26 +412,26 @@ typedef unsigned char u_char; #define ATTR_FMT_PRINTF(x, y) #endif -#define SCNtohl(x) (uint32_t)ntohl((x)) -#define SCNtohs(x) (uint16_t)ntohs((x)) +#define SCNtohl(x) (uint32_t) ntohl((x)) +#define SCNtohs(x) (uint16_t) ntohs((x)) /* swap flags if one of them is set, otherwise do nothing. */ -#define SWAP_FLAGS(flags, a, b) \ - do { \ - if (((flags) & ((a)|(b))) == (a)) { \ - (flags) &= ~(a); \ - (flags) |= (b); \ - } else if (((flags) & ((a)|(b))) == (b)) { \ - (flags) &= ~(b); \ - (flags) |= (a); \ - } \ - } while(0) - -#define SWAP_VARS(type, a, b) \ - do { \ - type t = (a); \ - (a) = (b); \ - (b) = t; \ +#define SWAP_FLAGS(flags, a, b) \ + do { \ + if (((flags) & ((a) | (b))) == (a)) { \ + (flags) &= ~(a); \ + (flags) |= (b); \ + } else if (((flags) & ((a) | (b))) == (b)) { \ + (flags) &= ~(b); \ + (flags) |= (a); \ + } \ + } while (0) + +#define SWAP_VARS(type, a, b) \ + do { \ + type t = (a); \ + (a) = (b); \ + (b) = t; \ } while (0) #include @@ -526,19 +528,19 @@ size_t strlcat(char *, const char *src, size_t siz); size_t strlcpy(char *dst, const char *src, size_t siz); #endif #ifndef HAVE_STRPTIME -char *strptime(const char * __restrict, const char * __restrict, struct tm * __restrict); +char *strptime(const char *__restrict, const char *__restrict, struct tm *__restrict); #endif #ifndef HAVE_FWRITE_UNLOCKED -#define SCFwriteUnlocked fwrite -#define SCFflushUnlocked fflush -#define SCClearErrUnlocked clearerr -#define SCFerrorUnlocked ferror +#define SCFwriteUnlocked fwrite +#define SCFflushUnlocked fflush +#define SCClearErrUnlocked clearerr +#define SCFerrorUnlocked ferror #else -#define SCFwriteUnlocked fwrite_unlocked -#define SCFflushUnlocked fflush_unlocked -#define SCClearErrUnlocked clearerr_unlocked -#define SCFerrorUnlocked ferror_unlocked +#define SCFwriteUnlocked fwrite_unlocked +#define SCFflushUnlocked fflush_unlocked +#define SCClearErrUnlocked clearerr_unlocked +#define SCFerrorUnlocked ferror_unlocked #endif extern int coverage_unittests; extern int g_ut_modules; diff --git a/src/suricata.c b/src/suricata.c index ffa970ae7297..5a7f55d1084c 100644 --- a/src/suricata.c +++ b/src/suricata.c @@ -175,7 +175,7 @@ volatile uint8_t suricata_ctl_flags = 0; int run_mode = RUNMODE_UNKNOWN; /** Engine mode: inline (ENGINE_MODE_IPS) or just - * detection mode (ENGINE_MODE_IDS by default) */ + * detection mode (ENGINE_MODE_IDS by default) */ static enum EngineMode g_engine_mode = ENGINE_MODE_UNKNOWN; /** Host mode: set if box is sniffing only @@ -201,7 +201,7 @@ int g_disable_randomness = 1; #endif /** determine (without branching) if we include the vlan_ids when hashing or - * comparing flows */ + * comparing flows */ uint16_t g_vlan_mask = 0xffff; /** determine (without branching) if we include the livedev ids when hashing or @@ -463,8 +463,8 @@ static int SetBpfString(int argc, char *argv[]) /* attempt to parse remaining args as bpf filter */ tmpindex = argc; - while(argv[tmpindex] != NULL) { - bpf_len+=strlen(argv[tmpindex]) + 1; + while (argv[tmpindex] != NULL) { + bpf_len += strlen(argv[tmpindex]) + 1; tmpindex++; } @@ -476,15 +476,15 @@ static int SetBpfString(int argc, char *argv[]) return TM_ECODE_FAILED; tmpindex = optind; - while(argv[tmpindex] != NULL) { - strlcat(bpf_filter, argv[tmpindex],bpf_len); - if(argv[tmpindex + 1] != NULL) { - strlcat(bpf_filter," ", bpf_len); + while (argv[tmpindex] != NULL) { + strlcat(bpf_filter, argv[tmpindex], bpf_len); + if (argv[tmpindex + 1] != NULL) { + strlcat(bpf_filter, " ", bpf_len); } tmpindex++; } - if(strlen(bpf_filter) > 0) { + if (strlen(bpf_filter) > 0) { if (ConfSetFinal("bpf-filter", bpf_filter) != 1) { SCLogError("Failed to set bpf filter."); SCFree(bpf_filter); @@ -500,7 +500,7 @@ static void SetBpfStringFromFile(char *filename) { char *bpf_filter = NULL; char *bpf_comment_tmp = NULL; - char *bpf_comment_start = NULL; + char *bpf_comment_start = NULL; uint32_t bpf_len = 0; SCStat st; FILE *fp = NULL; @@ -534,29 +534,26 @@ static void SetBpfStringFromFile(char *filename) fclose(fp); bpf_filter[nm] = '\0'; - if(strlen(bpf_filter) > 0) { + if (strlen(bpf_filter) > 0) { /*replace comments with space*/ bpf_comment_start = bpf_filter; - while((bpf_comment_tmp = strchr(bpf_comment_start, '#')) != NULL) { - while((*bpf_comment_tmp !='\0') && - (*bpf_comment_tmp != '\r') && (*bpf_comment_tmp != '\n')) - { + while ((bpf_comment_tmp = strchr(bpf_comment_start, '#')) != NULL) { + while ((*bpf_comment_tmp != '\0') && (*bpf_comment_tmp != '\r') && + (*bpf_comment_tmp != '\n')) { *bpf_comment_tmp++ = ' '; } bpf_comment_start = bpf_comment_tmp; } /*remove remaining '\r' and '\n' */ - while((bpf_comment_tmp = strchr(bpf_filter, '\r')) != NULL) { + while ((bpf_comment_tmp = strchr(bpf_filter, '\r')) != NULL) { *bpf_comment_tmp = ' '; } - while((bpf_comment_tmp = strchr(bpf_filter, '\n')) != NULL) { + while ((bpf_comment_tmp = strchr(bpf_filter, '\n')) != NULL) { *bpf_comment_tmp = ' '; } /* cut trailing spaces */ - while (strlen(bpf_filter) > 0 && - bpf_filter[strlen(bpf_filter)-1] == ' ') - { - bpf_filter[strlen(bpf_filter)-1] = '\0'; + while (strlen(bpf_filter) > 0 && bpf_filter[strlen(bpf_filter) - 1] == ' ') { + bpf_filter[strlen(bpf_filter) - 1] = '\0'; } if (strlen(bpf_filter) > 0) { if (ConfSetFinal("bpf-filter", bpf_filter) != 1) { @@ -582,13 +579,16 @@ static void PrintUsage(const char *progname) printf("\t-F : bpf filter file\n"); printf("\t-r : run in pcap file/offline mode\n"); #ifdef NFQ - printf("\t-q : run in inline nfqueue mode (use colon to specify a range of queues)\n"); + printf("\t-q : run in inline nfqueue mode (use colon to " + "specify a range of queues)\n"); #endif /* NFQ */ #ifdef IPFW printf("\t-d : run in inline ipfw divert mode\n"); #endif /* IPFW */ - printf("\t-s : path to signature file loaded in addition to suricata.yaml settings (optional)\n"); - printf("\t-S : path to signature file loaded exclusively (optional)\n"); + printf("\t-s : path to signature file loaded in addition to " + "suricata.yaml settings (optional)\n"); + printf("\t-S : path to signature file loaded exclusively " + "(optional)\n"); printf("\t-l : default log directory\n"); #ifndef OS_WIN32 printf("\t-D : run as daemon\n"); @@ -597,9 +597,11 @@ static void PrintUsage(const char *progname) printf("\t--service-remove : remove service\n"); printf("\t--service-change-params : change service startup parameters\n"); #endif /* OS_WIN32 */ - printf("\t-k [all|none] : force checksum check (all) or disabled it (none)\n"); + printf("\t-k [all|none] : force checksum check (all) or disabled it " + "(none)\n"); printf("\t-V : display Suricata version\n"); - printf("\t-v : be more verbose (use multiple times to increase verbosity)\n"); + printf("\t-v : be more verbose (use multiple times to " + "increase verbosity)\n"); #ifdef UNITTESTS printf("\t-u : run the unittests and exit\n"); printf("\t-U, --unittest-filter=REGEX : filter unittests with a regex\n"); @@ -610,44 +612,58 @@ static void PrintUsage(const char *progname) printf("\t--list-app-layer-protos : list supported app layer protocols\n"); printf("\t--list-keywords[=all|csv|] : list keywords implemented by the engine\n"); printf("\t--list-runmodes : list supported runmodes\n"); - printf("\t--runmode : specific runmode modification the engine should run. The argument\n" - "\t supplied should be the id for the runmode obtained by running\n" + printf("\t--runmode : specific runmode modification the engine " + "should run. The argument\n" + "\t supplied should be the id for the runmode " + "obtained by running\n" "\t --list-runmodes\n"); - printf("\t--engine-analysis : print reports on analysis of different sections in the engine and exit.\n" - "\t Please have a look at the conf parameter engine-analysis on what reports\n" + printf("\t--engine-analysis : print reports on analysis of different " + "sections in the engine and exit.\n" + "\t Please have a look at the conf parameter " + "engine-analysis on what reports\n" "\t can be printed\n"); printf("\t--pidfile : write pid to this file\n"); - printf("\t--init-errors-fatal : enable fatal failure on signature init error\n"); + printf("\t--init-errors-fatal : enable fatal failure on signature init " + "error\n"); printf("\t--disable-detection : disable detection engine\n"); printf("\t--dump-config : show the running configuration\n"); printf("\t--dump-features : display provided features\n"); printf("\t--build-info : display build information\n"); - printf("\t--pcap[=] : run in pcap mode, no value select interfaces from suricata.yaml\n"); - printf("\t--pcap-file-continuous : when running in pcap mode with a directory, continue checking directory for pcaps until interrupted\n"); - printf("\t--pcap-file-delete : when running in replay mode (-r with directory or file), will delete pcap files that have been processed when done\n"); - printf("\t--pcap-file-recursive : will descend into subdirectories when running in replay mode (-r)\n"); + printf("\t--pcap[=] : run in pcap mode, no value select interfaces " + "from suricata.yaml\n"); + printf("\t--pcap-file-continuous : when running in pcap mode with a directory, " + "continue checking directory for pcaps until interrupted\n"); + printf("\t--pcap-file-delete : when running in replay mode (-r with " + "directory or file), will delete pcap files that have been processed when done\n"); + printf("\t--pcap-file-recursive : will descend into subdirectories when running " + "in replay mode (-r)\n"); #ifdef HAVE_PCAP_SET_BUFF - printf("\t--pcap-buffer-size : size of the pcap buffer value from 0 - %i\n",INT_MAX); + printf("\t--pcap-buffer-size : size of the pcap buffer value from 0 - %i\n", + INT_MAX); #endif /* HAVE_SET_PCAP_BUFF */ #ifdef HAVE_DPDK printf("\t--dpdk : run in dpdk mode, uses interfaces from " "suricata.yaml\n"); #endif #ifdef HAVE_AF_PACKET - printf("\t--af-packet[=] : run in af-packet mode, no value select interfaces from suricata.yaml\n"); + printf("\t--af-packet[=] : run in af-packet mode, no value select " + "interfaces from suricata.yaml\n"); #endif #ifdef HAVE_AF_XDP printf("\t--af-xdp[=] : run in af-xdp mode, no value select " "interfaces from suricata.yaml\n"); #endif #ifdef HAVE_NETMAP - printf("\t--netmap[=] : run in netmap mode, no value select interfaces from suricata.yaml\n"); + printf("\t--netmap[=] : run in netmap mode, no value select " + "interfaces from suricata.yaml\n"); #endif #ifdef HAVE_PFRING - printf("\t--pfring[=] : run in pfring mode, use interfaces from suricata.yaml\n"); + printf("\t--pfring[=] : run in pfring mode, use interfaces from " + "suricata.yaml\n"); printf("\t--pfring-int : run in pfring mode, use interface \n"); printf("\t--pfring-cluster-id : pfring cluster id \n"); - printf("\t--pfring-cluster-type : pfring cluster type for PF_RING 4.1.2 and later cluster_round_robin|cluster_flow\n"); + printf("\t--pfring-cluster-type : pfring cluster type for PF_RING 4.1.2 and " + "later cluster_round_robin|cluster_flow\n"); #endif /* HAVE_PFRING */ printf("\t--simulate-ips : force engine into IPS mode. Useful for QA\n"); #ifdef HAVE_LIBCAP_NG @@ -656,7 +672,8 @@ static void PrintUsage(const char *progname) #endif /* HAVE_LIBCAP_NG */ printf("\t--erf-in : process an ERF file\n"); #ifdef HAVE_DAG - printf("\t--dag : process ERF records from DAG interface X, stream Y\n"); + printf("\t--dag : process ERF records from DAG interface X, " + "stream Y\n"); #endif #ifdef HAVE_NAPATECH printf("\t--napatech : run Napatech Streams using the API\n"); @@ -675,8 +692,8 @@ static void PrintUsage(const char *progname) printf("\t--set name=value : set a configuration value\n"); printf("\n"); printf("\nTo run the engine with default configuration on " - "interface eth0 with signature file \"signatures.rules\", run the " - "command as:\n\n%s -c suricata.yaml -s signatures.rules -i eth0 \n\n", + "interface eth0 with signature file \"signatures.rules\", run the " + "command as:\n\n%s -c suricata.yaml -s signatures.rules -i eth0 \n\n", progname); } @@ -829,9 +846,9 @@ static void PrintBuildInfo(void) printf("%s, %s architecture\n", bits, endian); #ifdef __GNUC__ - printf("GCC version %s, C version %"PRIiMAX"\n", __VERSION__, (intmax_t)__STDC_VERSION__); + printf("GCC version %s, C version %" PRIiMAX "\n", __VERSION__, (intmax_t)__STDC_VERSION__); #else - printf("C version %"PRIiMAX"\n", (intmax_t)__STDC_VERSION__); + printf("C version %" PRIiMAX "\n", (intmax_t)__STDC_VERSION__); #endif #if __SSP__ == 1 @@ -866,8 +883,7 @@ static void PrintBuildInfo(void) #endif printf("thread local storage method: %s\n", tls); - printf("compiled with %s, linked against %s\n", - HTP_VERSION_STRING_FULL, htp_get_version()); + printf("compiled with %s, linked against %s\n", HTP_VERSION_STRING_FULL, htp_get_version()); printf("\n"); #include "build-info.h" } @@ -1093,7 +1109,7 @@ static void SCInstanceInit(SCInstance *suri, const char *progname) suri->verbose = 0; /* use -1 as unknown */ suri->checksum_validation = -1; -#if HAVE_DETECT_DISABLED==1 +#if HAVE_DETECT_DISABLED == 1 g_detect_disabled = suri->disabled_detect = 1; #else g_detect_disabled = suri->disabled_detect = 0; @@ -1143,8 +1159,7 @@ static TmEcode PrintVersion(void) static TmEcode LogVersion(SCInstance *suri) { const char *mode = suri->system ? "SYSTEM" : "USER"; - SCLogNotice("This is %s version %s running in %s mode", - PROG_NAME, GetProgramVersion(), mode); + SCLogNotice("This is %s version %s running in %s mode", PROG_NAME, GetProgramVersion(), mode); return TM_ECODE_OK; } @@ -1162,8 +1177,8 @@ static void SCPrintElapsedTime(struct timeval *start_time) memset(&end_time, 0, sizeof(end_time)); gettimeofday(&end_time, NULL); uint64_t milliseconds = ((end_time.tv_sec - start_time->tv_sec) * 1000) + - (((1000000 + end_time.tv_usec - start_time->tv_usec) / 1000) - 1000); - SCLogInfo("time elapsed %.3fs", (float)milliseconds/(float)1000); + (((1000000 + end_time.tv_usec - start_time->tv_usec) / 1000) - 1000); + SCLogInfo("time elapsed %.3fs", (float)milliseconds / (float)1000); } static int ParseCommandLineAfpacket(SCInstance *suri, const char *in_arg) @@ -1262,7 +1277,7 @@ static int ParseCommandLinePcapLive(SCInstance *suri, const char *in_arg) /* some windows shells require escaping of the \ in \Device. Otherwise * the backslashes are stripped. We put them back here. */ if (strlen(in_arg) > 9 && strncmp(in_arg, "DeviceNPF", 9) == 0) { - snprintf(suri->pcap_dev, sizeof(suri->pcap_dev), "\\Device\\NPF%s", in_arg+9); + snprintf(suri->pcap_dev, sizeof(suri->pcap_dev), "\\Device\\NPF%s", in_arg + 9); } else { strlcpy(suri->pcap_dev, in_arg, sizeof(suri->pcap_dev)); PcapTranslateIPToDevice(suri->pcap_dev, sizeof(suri->pcap_dev)); @@ -1295,14 +1310,14 @@ static int ParseCommandLinePcapLive(SCInstance *suri, const char *in_arg) /** * Helper function to check if log directory is writable */ -static bool IsLogDirectoryWritable(const char* str) +static bool IsLogDirectoryWritable(const char *str) { if (access(str, W_OK) == 0) return true; return false; } -static TmEcode ParseCommandLine(int argc, char** argv, SCInstance *suri) +static TmEcode ParseCommandLine(int argc, char **argv, SCInstance *suri) { int opt; @@ -1409,624 +1424,615 @@ static TmEcode ParseCommandLine(int argc, char** argv, SCInstance *suri) while ((opt = getopt_long(argc, argv, short_opts, long_opts, &option_index)) != -1) { switch (opt) { - case 0: - if (strcmp((long_opts[option_index]).name , "pfring") == 0 || - strcmp((long_opts[option_index]).name , "pfring-int") == 0) { + case 0: + if (strcmp((long_opts[option_index]).name, "pfring") == 0 || + strcmp((long_opts[option_index]).name, "pfring-int") == 0) { #ifdef HAVE_PFRING - suri->run_mode = RUNMODE_PFRING; - if (optarg != NULL) { - memset(suri->pcap_dev, 0, sizeof(suri->pcap_dev)); - strlcpy(suri->pcap_dev, optarg, - ((strlen(optarg) < sizeof(suri->pcap_dev)) ? - (strlen(optarg) + 1) : sizeof(suri->pcap_dev))); - LiveRegisterDeviceName(optarg); - } + suri->run_mode = RUNMODE_PFRING; + if (optarg != NULL) { + memset(suri->pcap_dev, 0, sizeof(suri->pcap_dev)); + strlcpy(suri->pcap_dev, optarg, + ((strlen(optarg) < sizeof(suri->pcap_dev)) + ? (strlen(optarg) + 1) + : sizeof(suri->pcap_dev))); + LiveRegisterDeviceName(optarg); + } #else - SCLogError("PF_RING not enabled. Make sure " - "to pass --enable-pfring to configure when building."); - return TM_ECODE_FAILED; + SCLogError("PF_RING not enabled. Make sure " + "to pass --enable-pfring to configure when building."); + return TM_ECODE_FAILED; #endif /* HAVE_PFRING */ - } - else if(strcmp((long_opts[option_index]).name , "pfring-cluster-id") == 0){ + } else if (strcmp((long_opts[option_index]).name, "pfring-cluster-id") == 0) { #ifdef HAVE_PFRING - if (ConfSetFinal("pfring.cluster-id", optarg) != 1) { - SCLogError("failed to set pfring.cluster-id"); - return TM_ECODE_FAILED; - } + if (ConfSetFinal("pfring.cluster-id", optarg) != 1) { + SCLogError("failed to set pfring.cluster-id"); + return TM_ECODE_FAILED; + } #else - SCLogError("PF_RING not enabled. Make sure " - "to pass --enable-pfring to configure when building."); - return TM_ECODE_FAILED; + SCLogError("PF_RING not enabled. Make sure " + "to pass --enable-pfring to configure when building."); + return TM_ECODE_FAILED; #endif /* HAVE_PFRING */ - } - else if(strcmp((long_opts[option_index]).name , "pfring-cluster-type") == 0){ + } else if (strcmp((long_opts[option_index]).name, "pfring-cluster-type") == 0) { #ifdef HAVE_PFRING - if (ConfSetFinal("pfring.cluster-type", optarg) != 1) { - SCLogError("failed to set pfring.cluster-type"); - return TM_ECODE_FAILED; - } + if (ConfSetFinal("pfring.cluster-type", optarg) != 1) { + SCLogError("failed to set pfring.cluster-type"); + return TM_ECODE_FAILED; + } #else - SCLogError("PF_RING not enabled. Make sure " - "to pass --enable-pfring to configure when building."); - return TM_ECODE_FAILED; -#endif /* HAVE_PFRING */ - } - else if (strcmp((long_opts[option_index]).name , "capture-plugin") == 0){ - suri->run_mode = RUNMODE_PLUGIN; - suri->capture_plugin_name = optarg; - } - else if (strcmp((long_opts[option_index]).name , "capture-plugin-args") == 0){ - suri->capture_plugin_args = optarg; - } else if (strcmp((long_opts[option_index]).name, "dpdk") == 0) { - if (ParseCommandLineDpdk(suri, optarg) != TM_ECODE_OK) { - return TM_ECODE_FAILED; - } - } else if (strcmp((long_opts[option_index]).name, "af-packet") == 0) { - if (ParseCommandLineAfpacket(suri, optarg) != TM_ECODE_OK) { - return TM_ECODE_FAILED; - } - } else if (strcmp((long_opts[option_index]).name, "af-xdp") == 0) { - if (ParseCommandLineAfxdp(suri, optarg) != TM_ECODE_OK) { + SCLogError("PF_RING not enabled. Make sure " + "to pass --enable-pfring to configure when building."); return TM_ECODE_FAILED; - } - } else if (strcmp((long_opts[option_index]).name, "netmap") == 0) { -#ifdef HAVE_NETMAP - if (suri->run_mode == RUNMODE_UNKNOWN) { - suri->run_mode = RUNMODE_NETMAP; - if (optarg) { - LiveRegisterDeviceName(optarg); - memset(suri->pcap_dev, 0, sizeof(suri->pcap_dev)); - strlcpy(suri->pcap_dev, optarg, - ((strlen(optarg) < sizeof(suri->pcap_dev)) ? - (strlen(optarg) + 1) : sizeof(suri->pcap_dev))); +#endif /* HAVE_PFRING */ + } else if (strcmp((long_opts[option_index]).name, "capture-plugin") == 0) { + suri->run_mode = RUNMODE_PLUGIN; + suri->capture_plugin_name = optarg; + } else if (strcmp((long_opts[option_index]).name, "capture-plugin-args") == 0) { + suri->capture_plugin_args = optarg; + } else if (strcmp((long_opts[option_index]).name, "dpdk") == 0) { + if (ParseCommandLineDpdk(suri, optarg) != TM_ECODE_OK) { + return TM_ECODE_FAILED; } - } else if (suri->run_mode == RUNMODE_NETMAP) { - if (optarg) { - LiveRegisterDeviceName(optarg); + } else if (strcmp((long_opts[option_index]).name, "af-packet") == 0) { + if (ParseCommandLineAfpacket(suri, optarg) != TM_ECODE_OK) { + return TM_ECODE_FAILED; + } + } else if (strcmp((long_opts[option_index]).name, "af-xdp") == 0) { + if (ParseCommandLineAfxdp(suri, optarg) != TM_ECODE_OK) { + return TM_ECODE_FAILED; + } + } else if (strcmp((long_opts[option_index]).name, "netmap") == 0) { +#ifdef HAVE_NETMAP + if (suri->run_mode == RUNMODE_UNKNOWN) { + suri->run_mode = RUNMODE_NETMAP; + if (optarg) { + LiveRegisterDeviceName(optarg); + memset(suri->pcap_dev, 0, sizeof(suri->pcap_dev)); + strlcpy(suri->pcap_dev, optarg, + ((strlen(optarg) < sizeof(suri->pcap_dev)) + ? (strlen(optarg) + 1) + : sizeof(suri->pcap_dev))); + } + } else if (suri->run_mode == RUNMODE_NETMAP) { + if (optarg) { + LiveRegisterDeviceName(optarg); + } else { + SCLogInfo( + "Multiple netmap option without interface on each is useless"); + break; + } } else { - SCLogInfo("Multiple netmap option without interface on each is useless"); - break; + SCLogError("more than one run mode " + "has been specified"); + PrintUsage(argv[0]); + return TM_ECODE_FAILED; } - } else { - SCLogError("more than one run mode " - "has been specified"); - PrintUsage(argv[0]); - return TM_ECODE_FAILED; - } #else - SCLogError("NETMAP not enabled."); - return TM_ECODE_FAILED; + SCLogError("NETMAP not enabled."); + return TM_ECODE_FAILED; #endif - } else if (strcmp((long_opts[option_index]).name, "nflog") == 0) { + } else if (strcmp((long_opts[option_index]).name, "nflog") == 0) { #ifdef HAVE_NFLOG - if (suri->run_mode == RUNMODE_UNKNOWN) { - suri->run_mode = RUNMODE_NFLOG; - LiveBuildDeviceListCustom("nflog", "group"); - } + if (suri->run_mode == RUNMODE_UNKNOWN) { + suri->run_mode = RUNMODE_NFLOG; + LiveBuildDeviceListCustom("nflog", "group"); + } #else - SCLogError("NFLOG not enabled."); - return TM_ECODE_FAILED; -#endif /* HAVE_NFLOG */ - } else if (strcmp((long_opts[option_index]).name, "pcap") == 0) { - if (ParseCommandLinePcapLive(suri, optarg) != TM_ECODE_OK) { + SCLogError("NFLOG not enabled."); return TM_ECODE_FAILED; - } - } else if (strcmp((long_opts[option_index]).name, "simulate-ips") == 0) { - SCLogInfo("Setting IPS mode"); - EngineModeSetIPS(); - } else if (strcmp((long_opts[option_index]).name, "init-errors-fatal") == 0) { - if (ConfSetFinal("engine.init-failure-fatal", "1") != 1) { - SCLogError("failed to set engine init-failure-fatal"); - return TM_ECODE_FAILED; - } +#endif /* HAVE_NFLOG */ + } else if (strcmp((long_opts[option_index]).name, "pcap") == 0) { + if (ParseCommandLinePcapLive(suri, optarg) != TM_ECODE_OK) { + return TM_ECODE_FAILED; + } + } else if (strcmp((long_opts[option_index]).name, "simulate-ips") == 0) { + SCLogInfo("Setting IPS mode"); + EngineModeSetIPS(); + } else if (strcmp((long_opts[option_index]).name, "init-errors-fatal") == 0) { + if (ConfSetFinal("engine.init-failure-fatal", "1") != 1) { + SCLogError("failed to set engine init-failure-fatal"); + return TM_ECODE_FAILED; + } #ifdef BUILD_UNIX_SOCKET - } else if (strcmp((long_opts[option_index]).name , "unix-socket") == 0) { - if (suri->run_mode == RUNMODE_UNKNOWN) { - suri->run_mode = RUNMODE_UNIX_SOCKET; - if (optarg) { - if (ConfSetFinal("unix-command.filename", optarg) != 1) { - SCLogError("failed to set unix-command.filename"); - return TM_ECODE_FAILED; + } else if (strcmp((long_opts[option_index]).name, "unix-socket") == 0) { + if (suri->run_mode == RUNMODE_UNKNOWN) { + suri->run_mode = RUNMODE_UNIX_SOCKET; + if (optarg) { + if (ConfSetFinal("unix-command.filename", optarg) != 1) { + SCLogError("failed to set unix-command.filename"); + return TM_ECODE_FAILED; + } } - + } else { + SCLogError("more than one run mode " + "has been specified"); + PrintUsage(argv[0]); + return TM_ECODE_FAILED; } - } else { - SCLogError("more than one run mode " - "has been specified"); - PrintUsage(argv[0]); - return TM_ECODE_FAILED; - } #endif - } - else if(strcmp((long_opts[option_index]).name, "list-app-layer-protocols") == 0) { - /* listing all supported app layer protocols */ - } - else if(strcmp((long_opts[option_index]).name, "list-unittests") == 0) { + } else if (strcmp((long_opts[option_index]).name, "list-app-layer-protocols") == + 0) { + /* listing all supported app layer protocols */ + } else if (strcmp((long_opts[option_index]).name, "list-unittests") == 0) { #ifdef UNITTESTS - suri->run_mode = RUNMODE_LIST_UNITTEST; + suri->run_mode = RUNMODE_LIST_UNITTEST; #else - SCLogError("unit tests not enabled. Make sure to pass --enable-unittests to " - "configure when building"); - return TM_ECODE_FAILED; + SCLogError("unit tests not enabled. Make sure to pass --enable-unittests to " + "configure when building"); + return TM_ECODE_FAILED; #endif /* UNITTESTS */ - } else if (strcmp((long_opts[option_index]).name, "list-runmodes") == 0) { - suri->run_mode = RUNMODE_LIST_RUNMODES; - return TM_ECODE_OK; - } else if (strcmp((long_opts[option_index]).name, "list-keywords") == 0) { - if (optarg) { - if (strcmp("short",optarg)) { - suri->keyword_info = optarg; + } else if (strcmp((long_opts[option_index]).name, "list-runmodes") == 0) { + suri->run_mode = RUNMODE_LIST_RUNMODES; + return TM_ECODE_OK; + } else if (strcmp((long_opts[option_index]).name, "list-keywords") == 0) { + if (optarg) { + if (strcmp("short", optarg)) { + suri->keyword_info = optarg; + } } + } else if (strcmp((long_opts[option_index]).name, "runmode") == 0) { + suri->runmode_custom_mode = optarg; + } else if (strcmp((long_opts[option_index]).name, "engine-analysis") == 0) { + // do nothing for now } - } else if (strcmp((long_opts[option_index]).name, "runmode") == 0) { - suri->runmode_custom_mode = optarg; - } else if(strcmp((long_opts[option_index]).name, "engine-analysis") == 0) { - // do nothing for now - } #ifdef OS_WIN32 - else if(strcmp((long_opts[option_index]).name, "service-install") == 0) { - suri->run_mode = RUNMODE_INSTALL_SERVICE; - return TM_ECODE_OK; - } - else if(strcmp((long_opts[option_index]).name, "service-remove") == 0) { - suri->run_mode = RUNMODE_REMOVE_SERVICE; - return TM_ECODE_OK; - } - else if(strcmp((long_opts[option_index]).name, "service-change-params") == 0) { - suri->run_mode = RUNMODE_CHANGE_SERVICE_PARAMS; - return TM_ECODE_OK; - } -#endif /* OS_WIN32 */ - else if(strcmp((long_opts[option_index]).name, "pidfile") == 0) { - suri->pid_filename = SCStrdup(optarg); - if (suri->pid_filename == NULL) { - SCLogError("strdup failed: %s", strerror(errno)); - return TM_ECODE_FAILED; + else if (strcmp((long_opts[option_index]).name, "service-install") == 0) { + suri->run_mode = RUNMODE_INSTALL_SERVICE; + return TM_ECODE_OK; + } else if (strcmp((long_opts[option_index]).name, "service-remove") == 0) { + suri->run_mode = RUNMODE_REMOVE_SERVICE; + return TM_ECODE_OK; + } else if (strcmp((long_opts[option_index]).name, "service-change-params") == 0) { + suri->run_mode = RUNMODE_CHANGE_SERVICE_PARAMS; + return TM_ECODE_OK; } - } - else if(strcmp((long_opts[option_index]).name, "disable-detection") == 0) { - g_detect_disabled = suri->disabled_detect = 1; - } else if (strcmp((long_opts[option_index]).name, "disable-hashing") == 0) { - g_disable_hashing = true; - } else if (strcmp((long_opts[option_index]).name, "fatal-unittests") == 0) { +#endif /* OS_WIN32 */ + else if (strcmp((long_opts[option_index]).name, "pidfile") == 0) { + suri->pid_filename = SCStrdup(optarg); + if (suri->pid_filename == NULL) { + SCLogError("strdup failed: %s", strerror(errno)); + return TM_ECODE_FAILED; + } + } else if (strcmp((long_opts[option_index]).name, "disable-detection") == 0) { + g_detect_disabled = suri->disabled_detect = 1; + } else if (strcmp((long_opts[option_index]).name, "disable-hashing") == 0) { + g_disable_hashing = true; + } else if (strcmp((long_opts[option_index]).name, "fatal-unittests") == 0) { #ifdef UNITTESTS - unittests_fatal = 1; + unittests_fatal = 1; #else - SCLogError("unit tests not enabled. Make sure to pass --enable-unittests to " - "configure when building"); - return TM_ECODE_FAILED; + SCLogError("unit tests not enabled. Make sure to pass --enable-unittests to " + "configure when building"); + return TM_ECODE_FAILED; #endif /* UNITTESTS */ - } else if (strcmp((long_opts[option_index]).name, "user") == 0) { + } else if (strcmp((long_opts[option_index]).name, "user") == 0) { #ifndef HAVE_LIBCAP_NG - SCLogError("libcap-ng is required to" - " drop privileges, but it was not compiled into Suricata."); - return TM_ECODE_FAILED; + SCLogError("libcap-ng is required to" + " drop privileges, but it was not compiled into Suricata."); + return TM_ECODE_FAILED; #else - suri->user_name = optarg; - suri->do_setuid = true; + suri->user_name = optarg; + suri->do_setuid = true; #endif /* HAVE_LIBCAP_NG */ - } else if (strcmp((long_opts[option_index]).name, "group") == 0) { + } else if (strcmp((long_opts[option_index]).name, "group") == 0) { #ifndef HAVE_LIBCAP_NG - SCLogError("libcap-ng is required to" - " drop privileges, but it was not compiled into Suricata."); - return TM_ECODE_FAILED; + SCLogError("libcap-ng is required to" + " drop privileges, but it was not compiled into Suricata."); + return TM_ECODE_FAILED; #else - suri->group_name = optarg; - suri->do_setgid = true; + suri->group_name = optarg; + suri->do_setgid = true; #endif /* HAVE_LIBCAP_NG */ - } else if (strcmp((long_opts[option_index]).name, "erf-in") == 0) { - suri->run_mode = RUNMODE_ERF_FILE; - if (ConfSetFinal("erf-file.file", optarg) != 1) { - SCLogError("failed to set erf-file.file"); - return TM_ECODE_FAILED; - } - } else if (strcmp((long_opts[option_index]).name, "dag") == 0) { + } else if (strcmp((long_opts[option_index]).name, "erf-in") == 0) { + suri->run_mode = RUNMODE_ERF_FILE; + if (ConfSetFinal("erf-file.file", optarg) != 1) { + SCLogError("failed to set erf-file.file"); + return TM_ECODE_FAILED; + } + } else if (strcmp((long_opts[option_index]).name, "dag") == 0) { #ifdef HAVE_DAG - if (suri->run_mode == RUNMODE_UNKNOWN) { - suri->run_mode = RUNMODE_DAG; - } - else if (suri->run_mode != RUNMODE_DAG) { - SCLogError("more than one run mode has been specified"); - PrintUsage(argv[0]); - return TM_ECODE_FAILED; - } - LiveRegisterDeviceName(optarg); + if (suri->run_mode == RUNMODE_UNKNOWN) { + suri->run_mode = RUNMODE_DAG; + } else if (suri->run_mode != RUNMODE_DAG) { + SCLogError("more than one run mode has been specified"); + PrintUsage(argv[0]); + return TM_ECODE_FAILED; + } + LiveRegisterDeviceName(optarg); #else - SCLogError("libdag and a DAG card are required" - " to receive packets using --dag."); - return TM_ECODE_FAILED; + SCLogError("libdag and a DAG card are required" + " to receive packets using --dag."); + return TM_ECODE_FAILED; #endif /* HAVE_DAG */ - } else if (strcmp((long_opts[option_index]).name, "napatech") == 0) { + } else if (strcmp((long_opts[option_index]).name, "napatech") == 0) { #ifdef HAVE_NAPATECH - suri->run_mode = RUNMODE_NAPATECH; + suri->run_mode = RUNMODE_NAPATECH; #else - SCLogError("libntapi and a Napatech adapter are required" - " to capture packets using --napatech."); - return TM_ECODE_FAILED; + SCLogError("libntapi and a Napatech adapter are required" + " to capture packets using --napatech."); + return TM_ECODE_FAILED; #endif /* HAVE_NAPATECH */ - } else if (strcmp((long_opts[option_index]).name, "pcap-buffer-size") == 0) { + } else if (strcmp((long_opts[option_index]).name, "pcap-buffer-size") == 0) { #ifdef HAVE_PCAP_SET_BUFF - if (ConfSetFinal("pcap.buffer-size", optarg) != 1) { - SCLogError("failed to set pcap-buffer-size"); - return TM_ECODE_FAILED; - } + if (ConfSetFinal("pcap.buffer-size", optarg) != 1) { + SCLogError("failed to set pcap-buffer-size"); + return TM_ECODE_FAILED; + } #else - SCLogError("The version of libpcap you have" - " doesn't support setting buffer size."); + SCLogError("The version of libpcap you have" + " doesn't support setting buffer size."); #endif /* HAVE_PCAP_SET_BUFF */ - } else if (strcmp((long_opts[option_index]).name, "build-info") == 0) { - suri->run_mode = RUNMODE_PRINT_BUILDINFO; - return TM_ECODE_OK; - } else if (strcmp((long_opts[option_index]).name, "windivert-forward") == 0) { + } else if (strcmp((long_opts[option_index]).name, "build-info") == 0) { + suri->run_mode = RUNMODE_PRINT_BUILDINFO; + return TM_ECODE_OK; + } else if (strcmp((long_opts[option_index]).name, "windivert-forward") == 0) { #ifdef WINDIVERT - if (suri->run_mode == RUNMODE_UNKNOWN) { - suri->run_mode = RUNMODE_WINDIVERT; - if (WinDivertRegisterQueue(true, optarg) == -1) { - exit(EXIT_FAILURE); - } - } else if (suri->run_mode == RUNMODE_WINDIVERT) { - if (WinDivertRegisterQueue(true, optarg) == -1) { - exit(EXIT_FAILURE); - } - } else { - SCLogError("more than one run mode " - "has been specified"); - PrintUsage(argv[0]); - exit(EXIT_FAILURE); - } - } - else if(strcmp((long_opts[option_index]).name, "windivert") == 0) { - if (suri->run_mode == RUNMODE_UNKNOWN) { - suri->run_mode = RUNMODE_WINDIVERT; - if (WinDivertRegisterQueue(false, optarg) == -1) { + if (suri->run_mode == RUNMODE_UNKNOWN) { + suri->run_mode = RUNMODE_WINDIVERT; + if (WinDivertRegisterQueue(true, optarg) == -1) { + exit(EXIT_FAILURE); + } + } else if (suri->run_mode == RUNMODE_WINDIVERT) { + if (WinDivertRegisterQueue(true, optarg) == -1) { + exit(EXIT_FAILURE); + } + } else { + SCLogError("more than one run mode " + "has been specified"); + PrintUsage(argv[0]); exit(EXIT_FAILURE); } - } else if (suri->run_mode == RUNMODE_WINDIVERT) { - if (WinDivertRegisterQueue(false, optarg) == -1) { + } else if (strcmp((long_opts[option_index]).name, "windivert") == 0) { + if (suri->run_mode == RUNMODE_UNKNOWN) { + suri->run_mode = RUNMODE_WINDIVERT; + if (WinDivertRegisterQueue(false, optarg) == -1) { + exit(EXIT_FAILURE); + } + } else if (suri->run_mode == RUNMODE_WINDIVERT) { + if (WinDivertRegisterQueue(false, optarg) == -1) { + exit(EXIT_FAILURE); + } + } else { + SCLogError("more than one run mode " + "has been specified"); + PrintUsage(argv[0]); exit(EXIT_FAILURE); } - } else { - SCLogError("more than one run mode " - "has been specified"); - PrintUsage(argv[0]); - exit(EXIT_FAILURE); - } #else - SCLogError("WinDivert not enabled. Make sure to pass --enable-windivert to " - "configure when building."); - return TM_ECODE_FAILED; + SCLogError("WinDivert not enabled. Make sure to pass --enable-windivert to " + "configure when building."); + return TM_ECODE_FAILED; #endif /* WINDIVERT */ - } else if(strcmp((long_opts[option_index]).name, "reject-dev") == 0) { + } else if (strcmp((long_opts[option_index]).name, "reject-dev") == 0) { #ifdef HAVE_LIBNET11 - BUG_ON(optarg == NULL); /* for static analysis */ - extern char *g_reject_dev; - extern uint16_t g_reject_dev_mtu; - g_reject_dev = optarg; - int mtu = GetIfaceMTU(g_reject_dev); - if (mtu > 0) { - g_reject_dev_mtu = (uint16_t)mtu; - } + BUG_ON(optarg == NULL); /* for static analysis */ + extern char *g_reject_dev; + extern uint16_t g_reject_dev_mtu; + g_reject_dev = optarg; + int mtu = GetIfaceMTU(g_reject_dev); + if (mtu > 0) { + g_reject_dev_mtu = (uint16_t)mtu; + } #else - SCLogError("Libnet 1.1 support not enabled. Compile Suricata with libnet support."); - return TM_ECODE_FAILED; + SCLogError("Libnet 1.1 support not enabled. Compile Suricata with libnet " + "support."); + return TM_ECODE_FAILED; #endif - } - else if (strcmp((long_opts[option_index]).name, "set") == 0) { - if (optarg != NULL) { - /* Quick validation. */ - char *val = strchr(optarg, '='); - if (val == NULL) { - FatalError("Invalid argument for --set, must be key=val."); + } else if (strcmp((long_opts[option_index]).name, "set") == 0) { + if (optarg != NULL) { + /* Quick validation. */ + char *val = strchr(optarg, '='); + if (val == NULL) { + FatalError("Invalid argument for --set, must be key=val."); + } + if (!ConfSetFromString(optarg, 1)) { + FatalError("failed to set configuration value %s", optarg); + } } - if (!ConfSetFromString(optarg, 1)) { - FatalError("failed to set configuration value %s", optarg); + } else if (strcmp((long_opts[option_index]).name, "pcap-file-continuous") == 0) { + if (ConfSetFinal("pcap-file.continuous", "true") != 1) { + SCLogError("Failed to set pcap-file.continuous"); + return TM_ECODE_FAILED; + } + } else if (strcmp((long_opts[option_index]).name, "pcap-file-delete") == 0) { + if (ConfSetFinal("pcap-file.delete-when-done", "true") != 1) { + SCLogError("Failed to set pcap-file.delete-when-done"); + return TM_ECODE_FAILED; + } + } else if (strcmp((long_opts[option_index]).name, "pcap-file-recursive") == 0) { + if (ConfSetFinal("pcap-file.recursive", "true") != 1) { + SCLogError("failed to set pcap-file.recursive"); + return TM_ECODE_FAILED; + } + } else if (strcmp((long_opts[option_index]).name, "data-dir") == 0) { + if (optarg == NULL) { + SCLogError("no option argument (optarg) for -d"); + return TM_ECODE_FAILED; } - } - } - else if (strcmp((long_opts[option_index]).name, "pcap-file-continuous") == 0) { - if (ConfSetFinal("pcap-file.continuous", "true") != 1) { - SCLogError("Failed to set pcap-file.continuous"); - return TM_ECODE_FAILED; - } - } - else if (strcmp((long_opts[option_index]).name, "pcap-file-delete") == 0) { - if (ConfSetFinal("pcap-file.delete-when-done", "true") != 1) { - SCLogError("Failed to set pcap-file.delete-when-done"); - return TM_ECODE_FAILED; - } - } - else if (strcmp((long_opts[option_index]).name, "pcap-file-recursive") == 0) { - if (ConfSetFinal("pcap-file.recursive", "true") != 1) { - SCLogError("failed to set pcap-file.recursive"); - return TM_ECODE_FAILED; - } - } - else if (strcmp((long_opts[option_index]).name, "data-dir") == 0) { - if (optarg == NULL) { - SCLogError("no option argument (optarg) for -d"); - return TM_ECODE_FAILED; - } - if (ConfigSetDataDirectory(optarg) != TM_ECODE_OK) { - SCLogError("Failed to set data directory."); - return TM_ECODE_FAILED; - } - if (ConfigCheckDataDirectory(optarg) != TM_ECODE_OK) { - SCLogError("The data directory \"%s\"" - " supplied at the command-line (-d %s) doesn't " - "exist. Shutting down the engine.", - optarg, optarg); - return TM_ECODE_FAILED; - } - suri->set_datadir = true; - } else if (strcmp((long_opts[option_index]).name , "strict-rule-keywords") == 0){ - if (optarg == NULL) { - suri->strict_rule_parsing_string = SCStrdup("all"); - } else { - suri->strict_rule_parsing_string = SCStrdup(optarg); - } - if (suri->strict_rule_parsing_string == NULL) { - FatalError("failed to duplicate 'strict' string"); - } - } else if (strcmp((long_opts[option_index]).name, "include") == 0) { - if (suri->additional_configs == NULL) { - suri->additional_configs = SCCalloc(2, sizeof(char *)); - if (suri->additional_configs == NULL) { - FatalError( - "Failed to allocate memory for additional configuration files: %s", - strerror(errno)); + if (ConfigSetDataDirectory(optarg) != TM_ECODE_OK) { + SCLogError("Failed to set data directory."); + return TM_ECODE_FAILED; } - suri->additional_configs[0] = optarg; - } else { - for (int i = 0;; i++) { - if (suri->additional_configs[i] == NULL) { - const char **additional_configs = - SCRealloc(suri->additional_configs, (i + 2) * sizeof(char *)); - if (additional_configs == NULL) { - FatalError("Failed to allocate memory for additional configuration " - "files: %s", - strerror(errno)); - } else { - suri->additional_configs = additional_configs; + if (ConfigCheckDataDirectory(optarg) != TM_ECODE_OK) { + SCLogError("The data directory \"%s\"" + " supplied at the command-line (-d %s) doesn't " + "exist. Shutting down the engine.", + optarg, optarg); + return TM_ECODE_FAILED; + } + suri->set_datadir = true; + } else if (strcmp((long_opts[option_index]).name, "strict-rule-keywords") == 0) { + if (optarg == NULL) { + suri->strict_rule_parsing_string = SCStrdup("all"); + } else { + suri->strict_rule_parsing_string = SCStrdup(optarg); + } + if (suri->strict_rule_parsing_string == NULL) { + FatalError("failed to duplicate 'strict' string"); + } + } else if (strcmp((long_opts[option_index]).name, "include") == 0) { + if (suri->additional_configs == NULL) { + suri->additional_configs = SCCalloc(2, sizeof(char *)); + if (suri->additional_configs == NULL) { + FatalError("Failed to allocate memory for additional configuration " + "files: %s", + strerror(errno)); + } + suri->additional_configs[0] = optarg; + } else { + for (int i = 0;; i++) { + if (suri->additional_configs[i] == NULL) { + const char **additional_configs = SCRealloc( + suri->additional_configs, (i + 2) * sizeof(char *)); + if (additional_configs == NULL) { + FatalError("Failed to allocate memory for additional " + "configuration " + "files: %s", + strerror(errno)); + } else { + suri->additional_configs = additional_configs; + } + suri->additional_configs[i] = optarg; + suri->additional_configs[i + 1] = NULL; + break; } - suri->additional_configs[i] = optarg; - suri->additional_configs[i + 1] = NULL; - break; } } + } else { + int r = ExceptionSimulationCommandLineParser( + (long_opts[option_index]).name, optarg); + if (r < 0) + return TM_ECODE_FAILED; } - } else { - int r = ExceptionSimulationCommandLineParser( - (long_opts[option_index]).name, optarg); - if (r < 0) + break; + case 'c': + suri->conf_filename = optarg; + break; + case 'T': + conf_test = 1; + if (ConfSetFinal("engine.init-failure-fatal", "1") != 1) { + SCLogError("failed to set engine init-failure-fatal"); return TM_ECODE_FAILED; - } - break; - case 'c': - suri->conf_filename = optarg; - break; - case 'T': - conf_test = 1; - if (ConfSetFinal("engine.init-failure-fatal", "1") != 1) { - SCLogError("failed to set engine init-failure-fatal"); - return TM_ECODE_FAILED; - } - break; + } + break; #ifndef OS_WIN32 - case 'D': - suri->daemon = 1; - break; + case 'D': + suri->daemon = 1; + break; #endif /* OS_WIN32 */ - case 'h': - suri->run_mode = RUNMODE_PRINT_USAGE; - return TM_ECODE_OK; - case 'i': - if (optarg == NULL) { - SCLogError("no option argument (optarg) for -i"); - return TM_ECODE_FAILED; - } + case 'h': + suri->run_mode = RUNMODE_PRINT_USAGE; + return TM_ECODE_OK; + case 'i': + if (optarg == NULL) { + SCLogError("no option argument (optarg) for -i"); + return TM_ECODE_FAILED; + } #ifdef HAVE_AF_PACKET - if (ParseCommandLineAfpacket(suri, optarg) != TM_ECODE_OK) { - return TM_ECODE_FAILED; - } + if (ParseCommandLineAfpacket(suri, optarg) != TM_ECODE_OK) { + return TM_ECODE_FAILED; + } #else /* not afpacket */ - /* warn user if netmap or pf-ring are available */ + /* warn user if netmap or pf-ring are available */ #if defined HAVE_PFRING || HAVE_NETMAP - int i = 0; + int i = 0; #ifdef HAVE_PFRING - i++; + i++; #endif #ifdef HAVE_NETMAP - i++; + i++; #endif - SCLogWarning("faster capture " - "option%s %s available:" + SCLogWarning("faster capture " + "option%s %s available:" #ifdef HAVE_PFRING - " PF_RING (--pfring-int=%s)" + " PF_RING (--pfring-int=%s)" #endif #ifdef HAVE_NETMAP - " NETMAP (--netmap=%s)" + " NETMAP (--netmap=%s)" #endif - ". Use --pcap=%s to suppress this warning", - i == 1 ? "" : "s", i == 1 ? "is" : "are" + ". Use --pcap=%s to suppress this warning", + i == 1 ? "" : "s", i == 1 ? "is" : "are" #ifdef HAVE_PFRING - , - optarg + , + optarg #endif #ifdef HAVE_NETMAP - , - optarg + , + optarg #endif - , - optarg); + , + optarg); #endif /* have faster methods */ - if (ParseCommandLinePcapLive(suri, optarg) != TM_ECODE_OK) { - return TM_ECODE_FAILED; - } + if (ParseCommandLinePcapLive(suri, optarg) != TM_ECODE_OK) { + return TM_ECODE_FAILED; + } #endif - break; - case 'l': - if (optarg == NULL) { - SCLogError("no option argument (optarg) for -l"); - return TM_ECODE_FAILED; - } + break; + case 'l': + if (optarg == NULL) { + SCLogError("no option argument (optarg) for -l"); + return TM_ECODE_FAILED; + } - if (ConfigSetLogDirectory(optarg) != TM_ECODE_OK) { - SCLogError("Failed to set log directory."); - return TM_ECODE_FAILED; - } - if (ConfigCheckLogDirectoryExists(optarg) != TM_ECODE_OK) { - SCLogError("The logging directory \"%s\"" - " supplied at the command-line (-l %s) doesn't " - "exist. Shutting down the engine.", - optarg, optarg); - return TM_ECODE_FAILED; - } - if (!IsLogDirectoryWritable(optarg)) { - SCLogError("The logging directory \"%s\"" - " supplied at the command-line (-l %s) is not " - "writable. Shutting down the engine.", - optarg, optarg); - return TM_ECODE_FAILED; - } - suri->set_logdir = true; + if (ConfigSetLogDirectory(optarg) != TM_ECODE_OK) { + SCLogError("Failed to set log directory."); + return TM_ECODE_FAILED; + } + if (ConfigCheckLogDirectoryExists(optarg) != TM_ECODE_OK) { + SCLogError("The logging directory \"%s\"" + " supplied at the command-line (-l %s) doesn't " + "exist. Shutting down the engine.", + optarg, optarg); + return TM_ECODE_FAILED; + } + if (!IsLogDirectoryWritable(optarg)) { + SCLogError("The logging directory \"%s\"" + " supplied at the command-line (-l %s) is not " + "writable. Shutting down the engine.", + optarg, optarg); + return TM_ECODE_FAILED; + } + suri->set_logdir = true; - break; - case 'q': + break; + case 'q': #ifdef NFQ - if (suri->run_mode == RUNMODE_UNKNOWN) { - suri->run_mode = RUNMODE_NFQ; - EngineModeSetIPS(); - if (NFQParseAndRegisterQueues(optarg) == -1) - return TM_ECODE_FAILED; - } else if (suri->run_mode == RUNMODE_NFQ) { - if (NFQParseAndRegisterQueues(optarg) == -1) + if (suri->run_mode == RUNMODE_UNKNOWN) { + suri->run_mode = RUNMODE_NFQ; + EngineModeSetIPS(); + if (NFQParseAndRegisterQueues(optarg) == -1) + return TM_ECODE_FAILED; + } else if (suri->run_mode == RUNMODE_NFQ) { + if (NFQParseAndRegisterQueues(optarg) == -1) + return TM_ECODE_FAILED; + } else { + SCLogError("more than one run mode " + "has been specified"); + PrintUsage(argv[0]); return TM_ECODE_FAILED; - } else { - SCLogError("more than one run mode " - "has been specified"); - PrintUsage(argv[0]); - return TM_ECODE_FAILED; - } + } #else - SCLogError("NFQUEUE not enabled. Make sure to pass --enable-nfqueue to configure when " - "building."); - return TM_ECODE_FAILED; + SCLogError( + "NFQUEUE not enabled. Make sure to pass --enable-nfqueue to configure when " + "building."); + return TM_ECODE_FAILED; #endif /* NFQ */ - break; - case 'd': + break; + case 'd': #ifdef IPFW - if (suri->run_mode == RUNMODE_UNKNOWN) { - suri->run_mode = RUNMODE_IPFW; - EngineModeSetIPS(); - if (IPFWRegisterQueue(optarg) == -1) - return TM_ECODE_FAILED; - } else if (suri->run_mode == RUNMODE_IPFW) { - if (IPFWRegisterQueue(optarg) == -1) + if (suri->run_mode == RUNMODE_UNKNOWN) { + suri->run_mode = RUNMODE_IPFW; + EngineModeSetIPS(); + if (IPFWRegisterQueue(optarg) == -1) + return TM_ECODE_FAILED; + } else if (suri->run_mode == RUNMODE_IPFW) { + if (IPFWRegisterQueue(optarg) == -1) + return TM_ECODE_FAILED; + } else { + SCLogError("more than one run mode " + "has been specified"); + PrintUsage(argv[0]); return TM_ECODE_FAILED; - } else { - SCLogError("more than one run mode " - "has been specified"); - PrintUsage(argv[0]); - return TM_ECODE_FAILED; - } + } #else - SCLogError("IPFW not enabled. Make sure to pass --enable-ipfw to configure when " - "building."); - return TM_ECODE_FAILED; -#endif /* IPFW */ - break; - case 'r': - BUG_ON(optarg == NULL); /* for static analysis */ - if (suri->run_mode == RUNMODE_UNKNOWN) { - suri->run_mode = RUNMODE_PCAP_FILE; - } else { - SCLogError("more than one run mode " - "has been specified"); - PrintUsage(argv[0]); + SCLogError("IPFW not enabled. Make sure to pass --enable-ipfw to configure when " + "building."); return TM_ECODE_FAILED; - } - SCStat buf; - if (SCStatFn(optarg, &buf) != 0) { - SCLogError("pcap file '%s': %s", optarg, strerror(errno)); - return TM_ECODE_FAILED; - } - if (ConfSetFinal("pcap-file.file", optarg) != 1) { - SCLogError("ERROR: Failed to set pcap-file.file\n"); - return TM_ECODE_FAILED; - } +#endif /* IPFW */ + break; + case 'r': + BUG_ON(optarg == NULL); /* for static analysis */ + if (suri->run_mode == RUNMODE_UNKNOWN) { + suri->run_mode = RUNMODE_PCAP_FILE; + } else { + SCLogError("more than one run mode " + "has been specified"); + PrintUsage(argv[0]); + return TM_ECODE_FAILED; + } + SCStat buf; + if (SCStatFn(optarg, &buf) != 0) { + SCLogError("pcap file '%s': %s", optarg, strerror(errno)); + return TM_ECODE_FAILED; + } + if (ConfSetFinal("pcap-file.file", optarg) != 1) { + SCLogError("ERROR: Failed to set pcap-file.file\n"); + return TM_ECODE_FAILED; + } - break; - case 's': - if (suri->sig_file != NULL) { - SCLogError("can't have multiple -s options or mix -s and -S."); - return TM_ECODE_FAILED; - } - suri->sig_file = optarg; - break; - case 'S': - if (suri->sig_file != NULL) { - SCLogError("can't have multiple -S options or mix -s and -S."); - return TM_ECODE_FAILED; - } - suri->sig_file = optarg; - suri->sig_file_exclusive = true; - break; - case 'u': + break; + case 's': + if (suri->sig_file != NULL) { + SCLogError("can't have multiple -s options or mix -s and -S."); + return TM_ECODE_FAILED; + } + suri->sig_file = optarg; + break; + case 'S': + if (suri->sig_file != NULL) { + SCLogError("can't have multiple -S options or mix -s and -S."); + return TM_ECODE_FAILED; + } + suri->sig_file = optarg; + suri->sig_file_exclusive = true; + break; + case 'u': #ifdef UNITTESTS - if (suri->run_mode == RUNMODE_UNKNOWN) { - suri->run_mode = RUNMODE_UNITTEST; - } else { - SCLogError("more than one run mode has" - " been specified"); - PrintUsage(argv[0]); - return TM_ECODE_FAILED; - } + if (suri->run_mode == RUNMODE_UNKNOWN) { + suri->run_mode = RUNMODE_UNITTEST; + } else { + SCLogError("more than one run mode has" + " been specified"); + PrintUsage(argv[0]); + return TM_ECODE_FAILED; + } #else - SCLogError("unit tests not enabled. Make sure to pass --enable-unittests to configure " - "when building."); - return TM_ECODE_FAILED; + SCLogError( + "unit tests not enabled. Make sure to pass --enable-unittests to configure " + "when building."); + return TM_ECODE_FAILED; #endif /* UNITTESTS */ - break; - case 'U': + break; + case 'U': #ifdef UNITTESTS - suri->regex_arg = optarg; + suri->regex_arg = optarg; - if(strlen(suri->regex_arg) == 0) - suri->regex_arg = NULL; + if (strlen(suri->regex_arg) == 0) + suri->regex_arg = NULL; #endif - break; - case 'V': - suri->run_mode = RUNMODE_PRINT_VERSION; - return TM_ECODE_OK; - case 'F': - if (optarg == NULL) { - SCLogError("no option argument (optarg) for -F"); - return TM_ECODE_FAILED; - } + break; + case 'V': + suri->run_mode = RUNMODE_PRINT_VERSION; + return TM_ECODE_OK; + case 'F': + if (optarg == NULL) { + SCLogError("no option argument (optarg) for -F"); + return TM_ECODE_FAILED; + } - SetBpfStringFromFile(optarg); - break; - case 'v': - suri->verbose++; - break; - case 'k': - if (optarg == NULL) { - SCLogError("no option argument (optarg) for -k"); - return TM_ECODE_FAILED; - } - if (!strcmp("all", optarg)) - suri->checksum_validation = 1; - else if (!strcmp("none", optarg)) - suri->checksum_validation = 0; - else { - SCLogError("option '%s' invalid for -k", optarg); + SetBpfStringFromFile(optarg); + break; + case 'v': + suri->verbose++; + break; + case 'k': + if (optarg == NULL) { + SCLogError("no option argument (optarg) for -k"); + return TM_ECODE_FAILED; + } + if (!strcmp("all", optarg)) + suri->checksum_validation = 1; + else if (!strcmp("none", optarg)) + suri->checksum_validation = 0; + else { + SCLogError("option '%s' invalid for -k", optarg); + return TM_ECODE_FAILED; + } + break; + default: + PrintUsage(argv[0]); return TM_ECODE_FAILED; - } - break; - default: - PrintUsage(argv[0]); - return TM_ECODE_FAILED; } } @@ -2298,11 +2304,10 @@ void PostRunDeinit(const int runmode, struct timeval *start_time) #endif } - static int StartInternalRunMode(SCInstance *suri, int argc, char **argv) { /* Treat internal running mode */ - switch(suri->run_mode) { + switch (suri->run_mode) { case RUNMODE_LIST_KEYWORDS: return ListKeywords(suri->keyword_info); case RUNMODE_LIST_APP_LAYERS: @@ -2383,9 +2388,10 @@ static void SetupDelayedDetect(SCInstance *suri) ConfNode *denode = NULL; ConfNode *decnf = ConfGetNode("detect-engine"); if (decnf != NULL) { - TAILQ_FOREACH(denode, &decnf->head, next) { + TAILQ_FOREACH (denode, &decnf->head, next) { if (strcmp(denode->val, "delayed-detect") == 0) { - (void)ConfGetChildValueBool(denode, "delayed-detect", &suri->delayed_detect); + (void)ConfGetChildValueBool( + denode, "delayed-detect", &suri->delayed_detect); } } } @@ -2396,7 +2402,6 @@ static void SetupDelayedDetect(SCInstance *suri) if (suri->delayed_detect) { SCLogInfo("Packets will start being processed before signatures are active."); } - } static int LoadSignatures(DetectEngineCtx *de_ctx, SCInstance *suri) @@ -2467,12 +2472,9 @@ static int ConfigGetCaptureValue(SCInstance *suri) if (strip_trailing_plus) { size_t len = strlen(dev); - if (len && - (dev[len-1] == '+' || - dev[len-1] == '^' || - dev[len-1] == '*')) - { - dev[len-1] = '\0'; + if (len && (dev[len - 1] == '+' || dev[len - 1] == '^' || + dev[len - 1] == '*')) { + dev[len - 1] = '\0'; } } LiveDevice *ld = LiveGetDevice(dev); @@ -2495,7 +2497,7 @@ static int ConfigGetCaptureValue(SCInstance *suri) } } - SCLogDebug("Default packet size set to %"PRIu32, default_packet_size); + SCLogDebug("Default packet size set to %" PRIu32, default_packet_size); return TM_ECODE_OK; } @@ -2693,7 +2695,6 @@ int PostConfLoadedSetup(SCInstance *suri) } } - if (ConfigGetCaptureValue(suri) != TM_ECODE_OK) { SCReturnInt(TM_ECODE_FAILED); } @@ -2796,7 +2797,7 @@ int PostConfLoadedSetup(SCInstance *suri) static void SuricataMainLoop(SCInstance *suri) { - while(1) { + while (1) { if (sigterm_count || sigint_count) { suricata_ctl_flags |= SURICATA_STOP; } @@ -2826,7 +2827,7 @@ static void SuricataMainLoop(SCInstance *suri) DetectEngineReloadSetIdle(); } - usleep(10* 1000); + usleep(10 * 1000); } } @@ -2960,7 +2961,7 @@ int SuricataMain(int argc, char **argv) PostConfLoadedDetectSetup(&suricata); if (suricata.run_mode == RUNMODE_ENGINE_ANALYSIS) { goto out; - } else if (suricata.run_mode == RUNMODE_CONF_TEST){ + } else if (suricata.run_mode == RUNMODE_CONF_TEST) { SCLogNotice("Configuration provided was successfully loaded. Exiting."); goto out; } else if (suricata.run_mode == RUNMODE_DUMP_FEATURES) { @@ -2969,8 +2970,8 @@ int SuricataMain(int argc, char **argv) } SCSetStartTime(&suricata); - RunModeDispatch(suricata.run_mode, suricata.runmode_custom_mode, - suricata.capture_plugin_name, suricata.capture_plugin_args); + RunModeDispatch(suricata.run_mode, suricata.runmode_custom_mode, suricata.capture_plugin_name, + suricata.capture_plugin_args); if (suricata.run_mode != RUNMODE_UNIX_SOCKET) { UnixManagerThreadSpawnNonRunmode(suricata.unix_socket_enabled); } diff --git a/src/suricata.h b/src/suricata.h index 9d275edc5dd0..d1fb37eab9b8 100644 --- a/src/suricata.h +++ b/src/suricata.h @@ -68,17 +68,17 @@ /* the name of our binary */ #define PROG_NAME "Suricata" -#define PROG_VER PACKAGE_VERSION +#define PROG_VER PACKAGE_VERSION /* workaround SPlint error (don't know __gnuc_va_list) */ #ifdef S_SPLINT_S -# include -# define CONFIG_DIR "/etc/suricata" +#include +#define CONFIG_DIR "/etc/suricata" #endif #define DEFAULT_CONF_FILE CONFIG_DIR "/suricata.yaml" -#define DEFAULT_PID_DIR LOCAL_STATE_DIR "/run/" +#define DEFAULT_PID_DIR LOCAL_STATE_DIR "/run/" #define DEFAULT_PID_BASENAME "suricata.pid" #define DEFAULT_PID_FILENAME DEFAULT_PID_DIR DEFAULT_PID_BASENAME @@ -86,16 +86,13 @@ const char *GetDocURL(void); /* runtime engine control flags */ -#define SURICATA_STOP (1 << 0) /**< gracefully stop the engine: process all - outstanding packets first */ -#define SURICATA_DONE (1 << 2) /**< packets capture ended */ +#define SURICATA_STOP \ + (1 << 0) /**< gracefully stop the engine: process all \ + outstanding packets first */ +#define SURICATA_DONE (1 << 2) /**< packets capture ended */ /* Engine stage/status*/ -enum { - SURICATA_INIT = 0, - SURICATA_RUNTIME, - SURICATA_DEINIT -}; +enum { SURICATA_INIT = 0, SURICATA_RUNTIME, SURICATA_DEINIT }; /* Engine is acting as */ enum EngineMode { @@ -165,7 +162,6 @@ typedef struct SCInstance_ { const char *capture_plugin_args; } SCInstance; - /* memset to zeros, and mutex init! */ void GlobalsInitPreConfig(void); @@ -204,4 +200,3 @@ void RegisterAllModules(void); const char *GetProgramVersion(void); #endif /* __SURICATA_H__ */ - diff --git a/src/tests/app-layer-htp-file.c b/src/tests/app-layer-htp-file.c index 6f7891c80da9..9466fbefb121 100644 --- a/src/tests/app-layer-htp-file.c +++ b/src/tests/app-layer-htp-file.c @@ -23,10 +23,10 @@ * for setting up a valid range value. */ -static int AppLayerHtpFileParseContentRangeTest01 (void) +static int AppLayerHtpFileParseContentRangeTest01(void) { HTTPContentRange range; - bstr * rawvalue = bstr_dup_c("bytes 12-25/100"); + bstr *rawvalue = bstr_dup_c("bytes 12-25/100"); FAIL_IF_NOT(HTPParseContentRange(rawvalue, &range) == 0); FAIL_IF_NOT(range.start == 12); FAIL_IF_NOT(range.end == 25); @@ -40,10 +40,10 @@ static int AppLayerHtpFileParseContentRangeTest01 (void) * for setting up an invalid range value. */ -static int AppLayerHtpFileParseContentRangeTest02 (void) +static int AppLayerHtpFileParseContentRangeTest02(void) { HTTPContentRange range; - bstr * rawvalue = bstr_dup_c("bytes 15335424-27514354/"); + bstr *rawvalue = bstr_dup_c("bytes 15335424-27514354/"); FAIL_IF(HTPParseContentRange(rawvalue, &range) == 0); bstr_free(rawvalue); PASS; @@ -54,25 +54,24 @@ static int AppLayerHtpFileParseContentRangeTest02 (void) * for setting up an invalid range value. */ -static int AppLayerHtpFileParseContentRangeTest03 (void) +static int AppLayerHtpFileParseContentRangeTest03(void) { HTTPContentRange range; - bstr * rawvalue = bstr_dup_c("bytes 15335424-"); + bstr *rawvalue = bstr_dup_c("bytes 15335424-"); FAIL_IF(HTPParseContentRange(rawvalue, &range) == 0); bstr_free(rawvalue); PASS; } - /** * \test AppLayerHtpFileParseContentRangeTest04 is a test * for setting up a valid range value without the size. */ -static int AppLayerHtpFileParseContentRangeTest04 (void) +static int AppLayerHtpFileParseContentRangeTest04(void) { HTTPContentRange range; - bstr * rawvalue = bstr_dup_c("bytes 24-42/*"); + bstr *rawvalue = bstr_dup_c("bytes 24-42/*"); FAIL_IF_NOT(HTPParseContentRange(rawvalue, &range) == 0); FAIL_IF_NOT(range.start == 24); FAIL_IF_NOT(range.end == 42); @@ -85,8 +84,12 @@ static int AppLayerHtpFileParseContentRangeTest04 (void) */ void AppLayerHtpFileRegisterTests(void) { - UtRegisterTest("AppLayerHtpFileParseContentRangeTest01", AppLayerHtpFileParseContentRangeTest01); - UtRegisterTest("AppLayerHtpFileParseContentRangeTest02", AppLayerHtpFileParseContentRangeTest02); - UtRegisterTest("AppLayerHtpFileParseContentRangeTest03", AppLayerHtpFileParseContentRangeTest03); - UtRegisterTest("AppLayerHtpFileParseContentRangeTest04", AppLayerHtpFileParseContentRangeTest04); + UtRegisterTest( + "AppLayerHtpFileParseContentRangeTest01", AppLayerHtpFileParseContentRangeTest01); + UtRegisterTest( + "AppLayerHtpFileParseContentRangeTest02", AppLayerHtpFileParseContentRangeTest02); + UtRegisterTest( + "AppLayerHtpFileParseContentRangeTest03", AppLayerHtpFileParseContentRangeTest03); + UtRegisterTest( + "AppLayerHtpFileParseContentRangeTest04", AppLayerHtpFileParseContentRangeTest04); } diff --git a/src/tests/detect-engine-content-inspection.c b/src/tests/detect-engine-content-inspection.c index ee1b605f2c0d..7ba4f3b43fc9 100644 --- a/src/tests/detect-engine-content-inspection.c +++ b/src/tests/detect-engine-content-inspection.c @@ -29,38 +29,37 @@ #include "../detect.h" #include "detect-engine-build.h" -#define TEST_HEADER \ - ThreadVars tv; \ - memset(&tv, 0, sizeof(tv)); \ - Flow f; \ +#define TEST_HEADER \ + ThreadVars tv; \ + memset(&tv, 0, sizeof(tv)); \ + Flow f; \ memset(&f, 0, sizeof(f)); -#define TEST_RUN(buf, buflen, sig, match, steps) \ -{ \ - DetectEngineCtx *de_ctx = DetectEngineCtxInit(); \ - FAIL_IF_NULL(de_ctx); \ - DetectEngineThreadCtx *det_ctx = NULL; \ - char rule[2048]; \ - snprintf(rule, sizeof(rule), "alert tcp any any -> any any (%s sid:1; rev:1;)", (sig)); \ - Signature *s = DetectEngineAppendSig(de_ctx, rule); \ - FAIL_IF_NULL(s); \ - SigGroupBuild(de_ctx); \ - DetectEngineThreadCtxInit(&tv, (void *)de_ctx, (void *)&det_ctx); \ - FAIL_IF_NULL(det_ctx); \ - int r = DetectEngineContentInspection(de_ctx, det_ctx, \ - s, s->sm_arrays[DETECT_SM_LIST_PMATCH], NULL, &f, \ - (uint8_t *)(buf), (buflen), 0, DETECT_CI_FLAGS_SINGLE, \ - DETECT_ENGINE_CONTENT_INSPECTION_MODE_PAYLOAD); \ - FAIL_IF_NOT(r == (match)); \ - FAIL_IF_NOT(det_ctx->inspection_recursion_counter == (steps)); \ - DetectEngineThreadCtxDeinit(&tv, det_ctx); \ - DetectEngineCtxFree(de_ctx); \ -} -#define TEST_FOOTER \ - PASS +#define TEST_RUN(buf, buflen, sig, match, steps) \ + { \ + DetectEngineCtx *de_ctx = DetectEngineCtxInit(); \ + FAIL_IF_NULL(de_ctx); \ + DetectEngineThreadCtx *det_ctx = NULL; \ + char rule[2048]; \ + snprintf(rule, sizeof(rule), "alert tcp any any -> any any (%s sid:1; rev:1;)", (sig)); \ + Signature *s = DetectEngineAppendSig(de_ctx, rule); \ + FAIL_IF_NULL(s); \ + SigGroupBuild(de_ctx); \ + DetectEngineThreadCtxInit(&tv, (void *)de_ctx, (void *)&det_ctx); \ + FAIL_IF_NULL(det_ctx); \ + int r = DetectEngineContentInspection(de_ctx, det_ctx, s, \ + s->sm_arrays[DETECT_SM_LIST_PMATCH], NULL, &f, (uint8_t *)(buf), (buflen), 0, \ + DETECT_CI_FLAGS_SINGLE, DETECT_ENGINE_CONTENT_INSPECTION_MODE_PAYLOAD); \ + FAIL_IF_NOT(r == (match)); \ + FAIL_IF_NOT(det_ctx->inspection_recursion_counter == (steps)); \ + DetectEngineThreadCtxDeinit(&tv, det_ctx); \ + DetectEngineCtxFree(de_ctx); \ + } +#define TEST_FOOTER PASS /** \test simple match with distance */ -static int DetectEngineContentInspectionTest01(void) { +static int DetectEngineContentInspectionTest01(void) +{ TEST_HEADER; TEST_RUN("ab", 2, "content:\"a\"; content:\"b\";", true, 2); TEST_RUN("ab", 2, "content:\"a\"; content:\"b\"; distance:0; ", true, 2); @@ -69,7 +68,8 @@ static int DetectEngineContentInspectionTest01(void) { } /** \test simple match with pcre/R */ -static int DetectEngineContentInspectionTest02(void) { +static int DetectEngineContentInspectionTest02(void) +{ TEST_HEADER; TEST_RUN("ab", 2, "content:\"a\"; pcre:\"/b/\";", true, 2); TEST_RUN("ab", 2, "content:\"a\"; pcre:\"/b/R\";", true, 2); @@ -78,35 +78,56 @@ static int DetectEngineContentInspectionTest02(void) { } /** \test simple recursion logic */ -static int DetectEngineContentInspectionTest03(void) { +static int DetectEngineContentInspectionTest03(void) +{ TEST_HEADER; TEST_RUN("ababc", 5, "content:\"a\"; content:\"b\"; content:\"c\";", true, 3); TEST_RUN("ababc", 5, "content:\"a\"; content:\"b\"; content:\"d\";", false, 3); - TEST_RUN("ababc", 5, "content:\"a\"; content:\"b\"; distance:0; content:\"c\"; distance:0;", true, 3); - TEST_RUN("ababc", 5, "content:\"a\"; content:\"b\"; distance:0; content:\"d\"; distance:0;", false, 3); + TEST_RUN("ababc", 5, "content:\"a\"; content:\"b\"; distance:0; content:\"c\"; distance:0;", + true, 3); + TEST_RUN("ababc", 5, "content:\"a\"; content:\"b\"; distance:0; content:\"d\"; distance:0;", + false, 3); - TEST_RUN("ababc", 5, "content:\"a\"; content:\"b\"; distance:0; within:1; content:\"d\"; distance:0; within:1;", false, 5); + TEST_RUN("ababc", 5, + "content:\"a\"; content:\"b\"; distance:0; within:1; content:\"d\"; distance:0; " + "within:1;", + false, 5); // 5 steps: (1) a, (2) 1st b, (3) c not found, (4) 2nd b, (5) c found - TEST_RUN("ababc", 5, "content:\"a\"; content:\"b\"; distance:0; within:1; content:\"c\"; distance:0; within:1;", true, 5); + TEST_RUN("ababc", 5, + "content:\"a\"; content:\"b\"; distance:0; within:1; content:\"c\"; distance:0; " + "within:1;", + true, 5); // 6 steps: (1) a, (2) 1st b, (3) c not found, (4) 2nd b, (5) c found, (6) bab - TEST_RUN("ababc", 5, "content:\"a\"; content:\"b\"; distance:0; within:1; content:\"c\"; distance:0; within:1; content:\"bab\";", true, 6); + TEST_RUN("ababc", 5, + "content:\"a\"; content:\"b\"; distance:0; within:1; content:\"c\"; distance:0; " + "within:1; content:\"bab\";", + true, 6); // 6 steps: (1) a, (2) 1st b, (3) c not found, (4) 2nd b, (5) c found, (6) no not found - TEST_RUN("ababc", 5, "content:\"a\"; content:\"b\"; distance:0; within:1; content:\"c\"; distance:0; within:1; content:\"no\";", false, 6); + TEST_RUN("ababc", 5, + "content:\"a\"; content:\"b\"; distance:0; within:1; content:\"c\"; distance:0; " + "within:1; content:\"no\";", + false, 6); // 5 steps: (1) a, (2) 1st b, (3) c not found, (4) 2nd b, (5) c found - TEST_RUN("ababc", 5, "content:\"a\"; content:\"b\"; distance:0; within:1; pcre:\"/^c$/R\";", true, 5); + TEST_RUN("ababc", 5, "content:\"a\"; content:\"b\"; distance:0; within:1; pcre:\"/^c$/R\";", + true, 5); // 6 steps: (1) a, (2) 1st b, (3) c not found, (4) 2nd b, (5) c found, (6) bab - TEST_RUN("ababc", 5, "content:\"a\"; content:\"b\"; distance:0; within:1; pcre:\"/^c$/R\"; content:\"bab\";", true, 6); + TEST_RUN("ababc", 5, + "content:\"a\"; content:\"b\"; distance:0; within:1; pcre:\"/^c$/R\"; content:\"bab\";", + true, 6); // 6 steps: (1) a, (2) 1st b, (3) c not found, (4) 2nd b, (5) c found, (6) no not found - TEST_RUN("ababc", 5, "content:\"a\"; content:\"b\"; distance:0; within:1; pcre:\"/^c$/R\"; content:\"no\";", false, 6); + TEST_RUN("ababc", 5, + "content:\"a\"; content:\"b\"; distance:0; within:1; pcre:\"/^c$/R\"; content:\"no\";", + false, 6); TEST_FOOTER; } /** \test pcre recursion logic */ -static int DetectEngineContentInspectionTest04(void) { +static int DetectEngineContentInspectionTest04(void) +{ TEST_HEADER; TEST_RUN("ababc", 5, "content:\"a\"; content:\"b\"; content:\"c\";", true, 3); TEST_RUN("ababc", 5, "content:\"a\"; content:\"b\"; content:\"d\";", false, 3); @@ -121,74 +142,142 @@ static int DetectEngineContentInspectionTest04(void) { } /** \test multiple independent blocks recursion logic */ -static int DetectEngineContentInspectionTest05(void) { +static int DetectEngineContentInspectionTest05(void) +{ TEST_HEADER; TEST_RUN("ababc", 5, "content:\"a\"; content:\"b\"; content:\"c\";", true, 3); TEST_RUN("ababc", 5, "content:\"a\"; content:\"b\"; content:\"d\";", false, 3); // first block 2: (1) a, (2) b // second block 3: (1) b, (2) c not found, (x) b continues within loop, (3) c found - TEST_RUN("ababc", 5, "content:\"a\"; content:\"b\"; distance:0; within:1; content:\"b\"; content:\"c\"; distance:0; within:1;", true, 5); + TEST_RUN("ababc", 5, + "content:\"a\"; content:\"b\"; distance:0; within:1; content:\"b\"; content:\"c\"; " + "distance:0; within:1;", + true, 5); TEST_FOOTER; } /** \test isdataat recursion logic */ -static int DetectEngineContentInspectionTest06(void) { +static int DetectEngineContentInspectionTest06(void) +{ TEST_HEADER; TEST_RUN("ababc", 5, "content:\"a\"; content:\"b\"; content:\"c\";", true, 3); TEST_RUN("ababc", 5, "content:\"a\"; content:\"b\"; content:\"d\";", false, 3); // 6 steps: (1) a, (2) 1st b, (3) c not found, (4) 2nd b, (5) c found, isdataat - TEST_RUN("ababc", 5, "content:\"a\"; content:\"b\"; distance:0; within:1; content:\"c\"; distance:0; within:1; isdataat:!1,relative;", true, 5); - TEST_RUN("ababc", 5, "content:\"a\"; content:\"b\"; distance:0; within:1; content:\"c\"; distance:0; within:1; isdataat:1,relative;", false, 6); - - TEST_RUN("ababcabc", 8, "content:\"a\"; content:\"b\"; distance:0; within:1; content:\"c\"; distance:0; within:1; isdataat:!1,relative;", true, 7); - TEST_RUN("ababcabc", 8, "content:\"a\"; content:\"b\"; distance:0; within:1; content:\"c\"; distance:0; within:1; isdataat:1,relative;", true, 6); - - TEST_RUN("abcXYZ", 6, "content:\"abc\"; content:\"XYZ\"; distance:0; within:3; isdataat:!1,relative;", true, 2); + TEST_RUN("ababc", 5, + "content:\"a\"; content:\"b\"; distance:0; within:1; content:\"c\"; distance:0; " + "within:1; isdataat:!1,relative;", + true, 5); + TEST_RUN("ababc", 5, + "content:\"a\"; content:\"b\"; distance:0; within:1; content:\"c\"; distance:0; " + "within:1; isdataat:1,relative;", + false, 6); + + TEST_RUN("ababcabc", 8, + "content:\"a\"; content:\"b\"; distance:0; within:1; content:\"c\"; distance:0; " + "within:1; isdataat:!1,relative;", + true, 7); + TEST_RUN("ababcabc", 8, + "content:\"a\"; content:\"b\"; distance:0; within:1; content:\"c\"; distance:0; " + "within:1; isdataat:1,relative;", + true, 6); + + TEST_RUN("abcXYZ", 6, + "content:\"abc\"; content:\"XYZ\"; distance:0; within:3; isdataat:!1,relative;", true, + 2); TEST_RUN("abcXYZ", 6, "content:\"XYZ\"; distance:3; within:3; isdataat:!1,relative;", true, 1); TEST_RUN("abcXYZ", 6, "content:\"cXY\"; distance:2; within:3; isdataat:!1,relative;", false, 1); - TEST_RUN("xxxxxxxxxxxxxxxxxyYYYYYYYYYYYYYYYY", 34, "content:\"yYYYYYYYYYYYYYYYY\"; distance:9; within:29; isdataat:!1,relative;", true, 1); + TEST_RUN("xxxxxxxxxxxxxxxxxyYYYYYYYYYYYYYYYY", 34, + "content:\"yYYYYYYYYYYYYYYYY\"; distance:9; within:29; isdataat:!1,relative;", true, 1); TEST_FOOTER; } /** \test extreme recursion */ -static int DetectEngineContentInspectionTest07(void) { +static int DetectEngineContentInspectionTest07(void) +{ TEST_HEADER; - TEST_RUN("abcabcabcabcabcabcabcabcabcabcd", 31, "content:\"a\"; content:\"b\"; within:1; distance:0; content:\"c\"; distance:0; within:1; content:\"d\";", true, 4); - TEST_RUN("abcabcabcabcabcabcabcabcabcabcd", 31, "content:\"a\"; content:\"b\"; within:1; distance:0; content:\"c\"; distance:0; within:1; content:\"d\"; within:1; distance:0; ", true, 31); - TEST_RUN("abcabcabcabcabcabcabcabcabcabcx", 31, "content:\"a\"; content:\"b\"; within:1; distance:0; content:\"c\"; distance:0; within:1; content:\"d\"; within:1; distance:0; ", false, 31); - - TEST_RUN("abcabcabcabcabcabcabcabcabcabcx", 31, "content:\"a\"; content:\"b\"; distance:0; content:\"c\"; distance:0; content:\"d\"; distance:0; ", false, 4); - TEST_RUN("abcabcabcabcabcabcabcabcabcabcx", 31, "content:\"a\"; content:\"b\"; distance:0; content:\"c\"; distance:0; pcre:\"/^d/R\"; ", false, 13); - TEST_RUN("abcabcabcabcabcabcabcabcabcabcx", 31, "content:\"a\"; content:\"b\"; distance:0; content:\"c\"; distance:0; isdataat:!1,relative; ", false, 3); + TEST_RUN("abcabcabcabcabcabcabcabcabcabcd", 31, + "content:\"a\"; content:\"b\"; within:1; distance:0; content:\"c\"; distance:0; " + "within:1; content:\"d\";", + true, 4); + TEST_RUN("abcabcabcabcabcabcabcabcabcabcd", 31, + "content:\"a\"; content:\"b\"; within:1; distance:0; content:\"c\"; distance:0; " + "within:1; content:\"d\"; within:1; distance:0; ", + true, 31); + TEST_RUN("abcabcabcabcabcabcabcabcabcabcx", 31, + "content:\"a\"; content:\"b\"; within:1; distance:0; content:\"c\"; distance:0; " + "within:1; content:\"d\"; within:1; distance:0; ", + false, 31); + + TEST_RUN("abcabcabcabcabcabcabcabcabcabcx", 31, + "content:\"a\"; content:\"b\"; distance:0; content:\"c\"; distance:0; content:\"d\"; " + "distance:0; ", + false, 4); + TEST_RUN("abcabcabcabcabcabcabcabcabcabcx", 31, + "content:\"a\"; content:\"b\"; distance:0; content:\"c\"; distance:0; pcre:\"/^d/R\"; ", + false, 13); + TEST_RUN("abcabcabcabcabcabcabcabcabcabcx", 31, + "content:\"a\"; content:\"b\"; distance:0; content:\"c\"; distance:0; " + "isdataat:!1,relative; ", + false, 3); TEST_RUN("abcdabcdabcdabcdabcdabcdabcdabcdabcdabcdx", 41, - "content:\"a\"; content:\"b\"; distance:0; content:\"c\"; distance:0; content:\"d\"; distance:0; content:\"e\"; distance:0; ", false, 5); + "content:\"a\"; content:\"b\"; distance:0; content:\"c\"; distance:0; content:\"d\"; " + "distance:0; content:\"e\"; distance:0; ", + false, 5); TEST_RUN("abcdabcdabcdabcdabcdabcdabcdabcdabcdabcdx", 41, - "content:\"a\"; content:\"b\"; distance:0; content:\"c\"; distance:0; content:\"d\"; distance:0; pcre:\"/^e/R\"; ", false, 14); // TODO should be 5? + "content:\"a\"; content:\"b\"; distance:0; content:\"c\"; distance:0; content:\"d\"; " + "distance:0; pcre:\"/^e/R\"; ", + false, 14); // TODO should be 5? TEST_RUN("abcdabcdabcdabcdabcdabcdabcdabcdabcdabcdx", 41, - "content:\"a\"; content:\"b\"; distance:0; content:\"c\"; distance:0; content:\"d\"; distance:0; isdataat:!1,relative; ", false, 4); - - TEST_RUN("abcabcabcabcabcabcabcabcabcabcd", 31, "content:\"a\"; content:\"b\"; within:1; distance:0; content:\"c\"; distance:0; within:1; pcre:\"/d/\";", true, 4); - TEST_RUN("abcabcabcabcabcabcabcabcabcabcd", 31, "content:\"a\"; content:\"b\"; within:1; distance:0; content:\"c\"; distance:0; within:1; pcre:\"/d/R\";", true, 4); - TEST_RUN("abcabcabcabcabcabcabcabcabcabcd", 31, "content:\"a\"; content:\"b\"; within:1; distance:0; content:\"c\"; distance:0; within:1; pcre:\"/^d/R\";", true, 31); - - TEST_RUN("abcabcabcabcabcabcabcabcabcabcx", 31, "content:\"a\"; content:\"b\"; within:1; distance:0; content:\"c\"; distance:0; within:1; pcre:\"/d/\";", false, 4); - TEST_RUN("abcabcabcabcabcabcabcabcabcabcx", 31, "content:\"a\"; content:\"b\"; within:1; distance:0; content:\"c\"; distance:0; within:1; pcre:\"/d/R\";", false, 31); - TEST_RUN("abcabcabcabcabcabcabcabcabcabcx", 31, "content:\"a\"; content:\"b\"; within:1; distance:0; content:\"c\"; distance:0; within:1; pcre:\"/^d/R\";", false, 31); + "content:\"a\"; content:\"b\"; distance:0; content:\"c\"; distance:0; content:\"d\"; " + "distance:0; isdataat:!1,relative; ", + false, 4); + + TEST_RUN("abcabcabcabcabcabcabcabcabcabcd", 31, + "content:\"a\"; content:\"b\"; within:1; distance:0; content:\"c\"; distance:0; " + "within:1; pcre:\"/d/\";", + true, 4); + TEST_RUN("abcabcabcabcabcabcabcabcabcabcd", 31, + "content:\"a\"; content:\"b\"; within:1; distance:0; content:\"c\"; distance:0; " + "within:1; pcre:\"/d/R\";", + true, 4); + TEST_RUN("abcabcabcabcabcabcabcabcabcabcd", 31, + "content:\"a\"; content:\"b\"; within:1; distance:0; content:\"c\"; distance:0; " + "within:1; pcre:\"/^d/R\";", + true, 31); + + TEST_RUN("abcabcabcabcabcabcabcabcabcabcx", 31, + "content:\"a\"; content:\"b\"; within:1; distance:0; content:\"c\"; distance:0; " + "within:1; pcre:\"/d/\";", + false, 4); + TEST_RUN("abcabcabcabcabcabcabcabcabcabcx", 31, + "content:\"a\"; content:\"b\"; within:1; distance:0; content:\"c\"; distance:0; " + "within:1; pcre:\"/d/R\";", + false, 31); + TEST_RUN("abcabcabcabcabcabcabcabcabcabcx", 31, + "content:\"a\"; content:\"b\"; within:1; distance:0; content:\"c\"; distance:0; " + "within:1; pcre:\"/^d/R\";", + false, 31); TEST_FOOTER; } /** \test mix in negation */ -static int DetectEngineContentInspectionTest08(void) { +static int DetectEngineContentInspectionTest08(void) +{ TEST_HEADER; TEST_RUN("ababc", 5, "content:\"a\"; content:\"b\"; content:!\"d\";", true, 3); TEST_RUN("ababc", 5, "content:\"a\"; content:\"b\"; content:!\"c\";", false, 3); - TEST_RUN("ababc", 5, "content:\"a\"; content:\"b\"; distance:0; within:1; content:!\"a\"; distance:0; within:1;", true, 5); - TEST_RUN("ababc", 5, "content:\"a\"; content:\"b\"; distance:0; within:1; content:!\"a\"; distance:0; ", true, 5); + TEST_RUN("ababc", 5, + "content:\"a\"; content:\"b\"; distance:0; within:1; content:!\"a\"; distance:0; " + "within:1;", + true, 5); + TEST_RUN("ababc", 5, + "content:\"a\"; content:\"b\"; distance:0; within:1; content:!\"a\"; distance:0; ", + true, 5); TEST_RUN("abcdefghy", 9, "content:\"a\"; content:!\"x\"; content:\"c\"; distance:0; within:2; ", true, 3); @@ -201,39 +290,72 @@ static int DetectEngineContentInspectionTest08(void) { } /** \test mix in byte_jump */ -static int DetectEngineContentInspectionTest09(void) { +static int DetectEngineContentInspectionTest09(void) +{ TEST_HEADER; TEST_RUN("ababc", 5, "content:\"a\"; content:\"b\"; content:!\"d\";", true, 3); TEST_RUN("ababc", 5, "content:\"a\"; content:\"b\"; content:!\"c\";", false, 3); - TEST_RUN("abc03abcxyz", 11, "content:\"abc\"; byte_jump:2,0,relative,string,dec; content:\"xyz\"; within:3;", true, 3); - TEST_RUN("abc03abc03abcxyz", 16, "content:\"abc\"; byte_jump:2,0,relative,string,dec; content:\"xyz\"; within:3;", true, 5); - TEST_RUN("abc03abc03abcxyz", 16, "content:\"abc\"; byte_jump:2,0,relative,string,dec; content:\"xyz\"; within:3; isdataat:!1,relative;", true, 5); - TEST_RUN("abc03abc03abcxyz", 16, "content:\"abc\"; byte_jump:2,0,relative,string,dec; content:\"xyz\"; within:3; pcre:\"/klm$/R\";", false, 7); - TEST_RUN("abc03abc03abcxyzklm", 19, "content:\"abc\"; byte_jump:2,0,relative,string,dec; content:\"xyz\"; within:3; pcre:\"/klm$/R\";", true, 6); - TEST_RUN("abc03abc03abcxyzklx", 19, "content:\"abc\"; byte_jump:2,0,relative,string,dec; content:\"xyz\"; within:3; pcre:\"/^klm$/R\";", false, 7); - TEST_RUN("abc03abc03abc03abcxyzklm", 24, "content:\"abc\"; byte_jump:2,0,relative,string,dec; content:\"xyz\"; within:3; pcre:\"/^klm$/R\";", true, 8); + TEST_RUN("abc03abcxyz", 11, + "content:\"abc\"; byte_jump:2,0,relative,string,dec; content:\"xyz\"; within:3;", true, + 3); + TEST_RUN("abc03abc03abcxyz", 16, + "content:\"abc\"; byte_jump:2,0,relative,string,dec; content:\"xyz\"; within:3;", true, + 5); + TEST_RUN("abc03abc03abcxyz", 16, + "content:\"abc\"; byte_jump:2,0,relative,string,dec; content:\"xyz\"; within:3; " + "isdataat:!1,relative;", + true, 5); + TEST_RUN("abc03abc03abcxyz", 16, + "content:\"abc\"; byte_jump:2,0,relative,string,dec; content:\"xyz\"; within:3; " + "pcre:\"/klm$/R\";", + false, 7); + TEST_RUN("abc03abc03abcxyzklm", 19, + "content:\"abc\"; byte_jump:2,0,relative,string,dec; content:\"xyz\"; within:3; " + "pcre:\"/klm$/R\";", + true, 6); + TEST_RUN("abc03abc03abcxyzklx", 19, + "content:\"abc\"; byte_jump:2,0,relative,string,dec; content:\"xyz\"; within:3; " + "pcre:\"/^klm$/R\";", + false, 7); + TEST_RUN("abc03abc03abc03abcxyzklm", 24, + "content:\"abc\"; byte_jump:2,0,relative,string,dec; content:\"xyz\"; within:3; " + "pcre:\"/^klm$/R\";", + true, 8); TEST_FOOTER; } /** \test mix in byte_extract */ -static int DetectEngineContentInspectionTest10(void) { +static int DetectEngineContentInspectionTest10(void) +{ TEST_HEADER; /* extract first byte as length field and check with isdataat */ TEST_RUN("9abcdefghi", 10, "byte_extract:1,0,data_size,string; isdataat:data_size;", true, 2); TEST_RUN("9abcdefgh", 9, "byte_extract:1,0,data_size,string; isdataat:!data_size;", true, 2); /* anchor len field to pattern 'x' to test recursion */ - TEST_RUN("x9x9abcdefghi", 13, "content:\"x\"; byte_extract:1,0,data_size,string,relative; isdataat:data_size,relative;", true, 3); - TEST_RUN("x9x9abcdefgh", 12, "content:\"x\"; byte_extract:1,0,data_size,string,relative; isdataat:!data_size,relative;", true, 5); - TEST_RUN("x9x9abcdefgh", 12, "content:\"x\"; depth:1; byte_extract:1,0,data_size,string,relative; isdataat:!data_size,relative;", false, 3); + TEST_RUN("x9x9abcdefghi", 13, + "content:\"x\"; byte_extract:1,0,data_size,string,relative; " + "isdataat:data_size,relative;", + true, 3); + TEST_RUN("x9x9abcdefgh", 12, + "content:\"x\"; byte_extract:1,0,data_size,string,relative; " + "isdataat:!data_size,relative;", + true, 5); + TEST_RUN("x9x9abcdefgh", 12, + "content:\"x\"; depth:1; byte_extract:1,0,data_size,string,relative; " + "isdataat:!data_size,relative;", + false, 3); /* check for super high extracted values */ - TEST_RUN("100000000abcdefghi", 18, "byte_extract:0,0,data_size,string; isdataat:data_size;", false, 2); - TEST_RUN("100000000abcdefghi", 18, "byte_extract:0,0,data_size,string; isdataat:!data_size;", true, 2); + TEST_RUN("100000000abcdefghi", 18, "byte_extract:0,0,data_size,string; isdataat:data_size;", + false, 2); + TEST_RUN("100000000abcdefghi", 18, "byte_extract:0,0,data_size,string; isdataat:!data_size;", + true, 2); TEST_FOOTER; } -static int DetectEngineContentInspectionTest11(void) { +static int DetectEngineContentInspectionTest11(void) +{ TEST_HEADER; TEST_RUN("ab", 2, "content:\"a\"; startswith; content:\"b\";", true, 2); TEST_RUN("ab", 2, "content:\"a\"; startswith; content:\"b\"; within:1; distance:0;", true, 2); @@ -245,27 +367,38 @@ static int DetectEngineContentInspectionTest11(void) { /** \test endswith (isdataat) recursion logic * based on DetectEngineContentInspectionTest06 */ -static int DetectEngineContentInspectionTest12(void) { +static int DetectEngineContentInspectionTest12(void) +{ TEST_HEADER; // 6 steps: (1) a, (2) 1st b, (3) c not found, (4) 2nd b, (5) c found, endswith - TEST_RUN("ababc", 5, "content:\"a\"; content:\"b\"; distance:0; within:1; content:\"c\"; distance:0; within:1; endswith;", true, 5); - - TEST_RUN("ababcabc", 8, "content:\"a\"; content:\"b\"; distance:0; within:1; content:\"c\"; distance:0; within:1; endswith;", true, 7); - - TEST_RUN("abcXYZ", 6, "content:\"abc\"; content:\"XYZ\"; distance:0; within:3; endswith;", true, 2); + TEST_RUN("ababc", 5, + "content:\"a\"; content:\"b\"; distance:0; within:1; content:\"c\"; distance:0; " + "within:1; endswith;", + true, 5); + + TEST_RUN("ababcabc", 8, + "content:\"a\"; content:\"b\"; distance:0; within:1; content:\"c\"; distance:0; " + "within:1; endswith;", + true, 7); + + TEST_RUN("abcXYZ", 6, "content:\"abc\"; content:\"XYZ\"; distance:0; within:3; endswith;", true, + 2); TEST_RUN("abcXYZ", 6, "content:\"XYZ\"; distance:3; within:3; endswith;", true, 1); TEST_RUN("abcXYZ", 6, "content:\"cXY\"; distance:2; within:3; endswith;", false, 1); TEST_RUN("abcXYZ", 6, "content:!\"cXY\"; endswith;", true, 1); TEST_RUN("abcXYZ", 6, "content:!\"XYZ\"; endswith;", false, 1); - TEST_RUN("xxxxxxxxxxxxxxxxxyYYYYYYYYYYYYYYYY", 34, "content:\"yYYYYYYYYYYYYYYYY\"; distance:9; within:29; endswith;", true, 1); + TEST_RUN("xxxxxxxxxxxxxxxxxyYYYYYYYYYYYYYYYY", 34, + "content:\"yYYYYYYYYYYYYYYYY\"; distance:9; within:29; endswith;", true, 1); TEST_FOOTER; } -static int DetectEngineContentInspectionTest13(void) { +static int DetectEngineContentInspectionTest13(void) +{ TEST_HEADER; TEST_RUN("ab", 2, "content:\"a\"; startswith; content:\"b\"; endswith;", true, 2); - TEST_RUN("ab", 2, "content:\"a\"; startswith; content:\"b\"; within:1; distance:0; endswith;", true, 2); + TEST_RUN("ab", 2, "content:\"a\"; startswith; content:\"b\"; within:1; distance:0; endswith;", + true, 2); TEST_RUN("ab", 2, "content:\"ab\"; startswith; endswith;", true, 1); TEST_RUN("ab", 2, "content:\"a\"; startswith; endswith;", false, 1); TEST_RUN("ab", 2, "content:\"b\"; startswith;", false, 1); @@ -275,32 +408,22 @@ static int DetectEngineContentInspectionTest13(void) { void DetectEngineContentInspectionRegisterTests(void) { - UtRegisterTest("DetectEngineContentInspectionTest01", - DetectEngineContentInspectionTest01); - UtRegisterTest("DetectEngineContentInspectionTest02", - DetectEngineContentInspectionTest02); - UtRegisterTest("DetectEngineContentInspectionTest03", - DetectEngineContentInspectionTest03); - UtRegisterTest("DetectEngineContentInspectionTest04", - DetectEngineContentInspectionTest04); - UtRegisterTest("DetectEngineContentInspectionTest05", - DetectEngineContentInspectionTest05); - UtRegisterTest("DetectEngineContentInspectionTest06", - DetectEngineContentInspectionTest06); - UtRegisterTest("DetectEngineContentInspectionTest07", - DetectEngineContentInspectionTest07); - UtRegisterTest("DetectEngineContentInspectionTest08", - DetectEngineContentInspectionTest08); - UtRegisterTest("DetectEngineContentInspectionTest09", - DetectEngineContentInspectionTest09); - UtRegisterTest("DetectEngineContentInspectionTest10", - DetectEngineContentInspectionTest10); - UtRegisterTest("DetectEngineContentInspectionTest11 startswith", - DetectEngineContentInspectionTest11); - UtRegisterTest("DetectEngineContentInspectionTest12 endswith", - DetectEngineContentInspectionTest12); + UtRegisterTest("DetectEngineContentInspectionTest01", DetectEngineContentInspectionTest01); + UtRegisterTest("DetectEngineContentInspectionTest02", DetectEngineContentInspectionTest02); + UtRegisterTest("DetectEngineContentInspectionTest03", DetectEngineContentInspectionTest03); + UtRegisterTest("DetectEngineContentInspectionTest04", DetectEngineContentInspectionTest04); + UtRegisterTest("DetectEngineContentInspectionTest05", DetectEngineContentInspectionTest05); + UtRegisterTest("DetectEngineContentInspectionTest06", DetectEngineContentInspectionTest06); + UtRegisterTest("DetectEngineContentInspectionTest07", DetectEngineContentInspectionTest07); + UtRegisterTest("DetectEngineContentInspectionTest08", DetectEngineContentInspectionTest08); + UtRegisterTest("DetectEngineContentInspectionTest09", DetectEngineContentInspectionTest09); + UtRegisterTest("DetectEngineContentInspectionTest10", DetectEngineContentInspectionTest10); + UtRegisterTest( + "DetectEngineContentInspectionTest11 startswith", DetectEngineContentInspectionTest11); + UtRegisterTest( + "DetectEngineContentInspectionTest12 endswith", DetectEngineContentInspectionTest12); UtRegisterTest("DetectEngineContentInspectionTest13 mix startswith/endswith", - DetectEngineContentInspectionTest13); + DetectEngineContentInspectionTest13); } #undef TEST_HEADER diff --git a/src/tests/detect-http-client-body.c b/src/tests/detect-http-client-body.c index c87d66756b9f..f56ad3529db9 100644 --- a/src/tests/detect-http-client-body.c +++ b/src/tests/detect-http-client-body.c @@ -21,7 +21,6 @@ * @{ */ - /** \file * * \author Anoop Saldanha @@ -74,15 +73,30 @@ */ static int DetectHttpClientBodyParserTest01(void) { - FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_server; content:\"abc\"; http_client_body; sid:1;)", true)); - FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_server; content:\"abc\"; nocase; http_client_body; sid:1;)", true)); - FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_server; content:\"abc\"; endswith; http_client_body; sid:1;)", true)); - FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_server; content:\"abc\"; startswith; http_client_body; sid:1;)", true)); - FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_server; content:\"abc\"; startswith; endswith; http_client_body; sid:1;)", true)); - - FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_server; content:\"abc\"; rawbytes; http_client_body; sid:1;)", false)); - FAIL_IF_NOT(UTHParseSignature("alert tcp any any -> any any (flow:to_server; http_client_body; sid:1;)", false)); - FAIL_IF_NOT(UTHParseSignature("alert tls any any -> any any (flow:to_server; content:\"abc\"; http_client_body; sid:1;)", false)); + FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_server; content:\"abc\"; " + "http_client_body; sid:1;)", + true)); + FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_server; content:\"abc\"; " + "nocase; http_client_body; sid:1;)", + true)); + FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_server; content:\"abc\"; " + "endswith; http_client_body; sid:1;)", + true)); + FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_server; content:\"abc\"; " + "startswith; http_client_body; sid:1;)", + true)); + FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_server; content:\"abc\"; " + "startswith; endswith; http_client_body; sid:1;)", + true)); + + FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_server; content:\"abc\"; " + "rawbytes; http_client_body; sid:1;)", + false)); + FAIL_IF_NOT(UTHParseSignature( + "alert tcp any any -> any any (flow:to_server; http_client_body; sid:1;)", false)); + FAIL_IF_NOT(UTHParseSignature("alert tls any any -> any any (flow:to_server; content:\"abc\"; " + "http_client_body; sid:1;)", + false)); PASS; } @@ -91,27 +105,45 @@ static int DetectHttpClientBodyParserTest01(void) */ static int DetectHttpClientBodyParserTest02(void) { - FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_server; http.request_body; content:\"abc\"; sid:1;)", true)); - FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_server; http.request_body; content:\"abc\"; nocase; sid:1;)", true)); - FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_server; http.request_body; content:\"abc\"; endswith; sid:1;)", true)); - FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_server; http.request_body; content:\"abc\"; startswith; sid:1;)", true)); - FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_server; http.request_body; content:\"abc\"; startswith; endswith; sid:1;)", true)); - FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_server; http.request_body; bsize:10; sid:1;)", true)); - - FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_server; http.request_body; content:\"abc\"; rawbytes; sid:1;)", false)); - FAIL_IF_NOT(UTHParseSignature("alert tcp any any -> any any (flow:to_server; http.request_body; sid:1;)", false)); - FAIL_IF_NOT(UTHParseSignature("alert tls any any -> any any (flow:to_server; http.request_body; content:\"abc\"; sid:1;)", false)); + FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_server; " + "http.request_body; content:\"abc\"; sid:1;)", + true)); + FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_server; " + "http.request_body; content:\"abc\"; nocase; sid:1;)", + true)); + FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_server; " + "http.request_body; content:\"abc\"; endswith; sid:1;)", + true)); + FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_server; " + "http.request_body; content:\"abc\"; startswith; sid:1;)", + true)); + FAIL_IF_NOT( + UTHParseSignature("alert http any any -> any any (flow:to_server; http.request_body; " + "content:\"abc\"; startswith; endswith; sid:1;)", + true)); + FAIL_IF_NOT(UTHParseSignature( + "alert http any any -> any any (flow:to_server; http.request_body; bsize:10; sid:1;)", + true)); + + FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_server; " + "http.request_body; content:\"abc\"; rawbytes; sid:1;)", + false)); + FAIL_IF_NOT(UTHParseSignature( + "alert tcp any any -> any any (flow:to_server; http.request_body; sid:1;)", false)); + FAIL_IF_NOT(UTHParseSignature("alert tls any any -> any any (flow:to_server; " + "http.request_body; content:\"abc\"; sid:1;)", + false)); PASS; } struct TestSteps { const uint8_t *input; - size_t input_size; /**< if 0 strlen will be used */ - int direction; /**< STREAM_TOSERVER, STREAM_TOCLIENT */ + size_t input_size; /**< if 0 strlen will be used */ + int direction; /**< STREAM_TOSERVER, STREAM_TOCLIENT */ int expect; }; -static int RunTest (struct TestSteps *steps, const char *sig, const char *yaml) +static int RunTest(struct TestSteps *steps, const char *sig, const char *yaml) { TcpSession ssn; Flow f; @@ -162,7 +194,7 @@ static int RunTest (struct TestSteps *steps, const char *sig, const char *yaml) p->flow = &f; p->flowflags = (b->direction == STREAM_TOSERVER) ? FLOW_PKT_TOSERVER : FLOW_PKT_TOCLIENT; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_HTTP1, b->direction, (uint8_t *)b->input, @@ -173,7 +205,7 @@ static int RunTest (struct TestSteps *steps, const char *sig, const char *yaml) SigMatchSignatures(&th_v, de_ctx, det_ctx, p); int match = PacketAlertCheck(p, 1); - FAIL_IF_NOT (b->expect == match); + FAIL_IF_NOT(b->expect == match); UTHFreePackets(&p, 1); b++; @@ -197,522 +229,527 @@ static int RunTest (struct TestSteps *steps, const char *sig, const char *yaml) static int DetectEngineHttpClientBodyTest01(void) { struct TestSteps steps[] = { - { (const uint8_t *)"GET /index.html HTTP/1.1\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 46\r\n" - "\r\n" - "This is dummy body1", - 0, STREAM_TOSERVER, 0 }, - { (const uint8_t *)"This is dummy message body2", - 0, STREAM_TOSERVER, 1 }, - { NULL, 0, 0, 0 }, + { (const uint8_t *)"GET /index.html HTTP/1.1\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 46\r\n" + "\r\n" + "This is dummy body1", + 0, STREAM_TOSERVER, 0 }, + { (const uint8_t *)"This is dummy message body2", 0, STREAM_TOSERVER, 1 }, + { NULL, 0, 0, 0 }, }; - const char *sig = "alert http any any -> any any (content:\"body1This\"; http_client_body; sid:1;)"; + const char *sig = + "alert http any any -> any any (content:\"body1This\"; http_client_body; sid:1;)"; return RunTest(steps, sig, NULL); } static int DetectEngineHttpClientBodyTest02(void) { struct TestSteps steps[] = { - { (const uint8_t *)"GET /index.html HTTP/1.1\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 19\r\n" - "\r\n" - "This is dummy body1", - 0, STREAM_TOSERVER, 1 }, - { NULL, 0, 0, 0 }, + { (const uint8_t *)"GET /index.html HTTP/1.1\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 19\r\n" + "\r\n" + "This is dummy body1", + 0, STREAM_TOSERVER, 1 }, + { NULL, 0, 0, 0 }, }; - const char *sig = "alert http any any -> any any (content:\"body1\"; http_client_body; offset:5; sid:1;)"; + const char *sig = + "alert http any any -> any any (content:\"body1\"; http_client_body; offset:5; sid:1;)"; return RunTest(steps, sig, NULL); } static int DetectEngineHttpClientBodyTest03(void) { struct TestSteps steps[] = { - { (const uint8_t *)"GET /index.html HTTP/1.1\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 46\r\n" - "\r\n" - "This is dummy body1", - 0, STREAM_TOSERVER, 0 }, - { (const uint8_t *)"This is dummy message body2", - 0, STREAM_TOSERVER, 0 }, - { NULL, 0, 0, 0 }, + { (const uint8_t *)"GET /index.html HTTP/1.1\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 46\r\n" + "\r\n" + "This is dummy body1", + 0, STREAM_TOSERVER, 0 }, + { (const uint8_t *)"This is dummy message body2", 0, STREAM_TOSERVER, 0 }, + { NULL, 0, 0, 0 }, }; - const char *sig = "alert http any any -> any any (content:\"body1\"; http_client_body; offset:16; sid:1;)"; + const char *sig = "alert http any any -> any any (content:\"body1\"; http_client_body; " + "offset:16; sid:1;)"; return RunTest(steps, sig, NULL); } static int DetectEngineHttpClientBodyTest04(void) { struct TestSteps steps[] = { - { (const uint8_t *)"GET /index.html HTTP/1.1\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 46\r\n" - "\r\n" - "This is dummy body1", - 0, STREAM_TOSERVER, 0 }, - { (const uint8_t *)"This is dummy message body2", - 0, STREAM_TOSERVER, 1 }, - { NULL, 0, 0, 0 }, + { (const uint8_t *)"GET /index.html HTTP/1.1\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 46\r\n" + "\r\n" + "This is dummy body1", + 0, STREAM_TOSERVER, 0 }, + { (const uint8_t *)"This is dummy message body2", 0, STREAM_TOSERVER, 1 }, + { NULL, 0, 0, 0 }, }; - const char *sig = "alert http any any -> any any (content:!\"body1\"; http_client_body; offset:16; sid:1;)"; + const char *sig = "alert http any any -> any any (content:!\"body1\"; http_client_body; " + "offset:16; sid:1;)"; return RunTest(steps, sig, NULL); } static int DetectEngineHttpClientBodyTest05(void) { struct TestSteps steps[] = { - { (const uint8_t *)"GET /index.html HTTP/1.1\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 46\r\n" - "\r\n" - "This is dummy body1", - 0, STREAM_TOSERVER, 0 }, - { (const uint8_t *)"This is dummy message body2", - 0, STREAM_TOSERVER, 1 }, - { NULL, 0, 0, 0 }, + { (const uint8_t *)"GET /index.html HTTP/1.1\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 46\r\n" + "\r\n" + "This is dummy body1", + 0, STREAM_TOSERVER, 0 }, + { (const uint8_t *)"This is dummy message body2", 0, STREAM_TOSERVER, 1 }, + { NULL, 0, 0, 0 }, }; - const char *sig = "alert http any any -> any any (content:\"body1\"; http_client_body; depth:25; sid:1;)"; + const char *sig = + "alert http any any -> any any (content:\"body1\"; http_client_body; depth:25; sid:1;)"; return RunTest(steps, sig, NULL); } static int DetectEngineHttpClientBodyTest06(void) { struct TestSteps steps[] = { - { (const uint8_t *)"GET /index.html HTTP/1.1\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 46\r\n" - "\r\n" - "This is dummy body1", - 0, STREAM_TOSERVER, 0 }, - { (const uint8_t *)"This is dummy message body2", - 0, STREAM_TOSERVER, 0 }, - { NULL, 0, 0, 0 }, + { (const uint8_t *)"GET /index.html HTTP/1.1\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 46\r\n" + "\r\n" + "This is dummy body1", + 0, STREAM_TOSERVER, 0 }, + { (const uint8_t *)"This is dummy message body2", 0, STREAM_TOSERVER, 0 }, + { NULL, 0, 0, 0 }, }; - const char *sig = "alert http any any -> any any (content:!\"body1\"; http_client_body; depth:25; sid:1;)"; + const char *sig = "alert http any any -> any any (content:!\"body1\"; http_client_body; " + "depth:25; sid:1;)"; return RunTest(steps, sig, NULL); } static int DetectEngineHttpClientBodyTest07(void) { struct TestSteps steps[] = { - { (const uint8_t *)"GET /index.html HTTP/1.1\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 46\r\n" - "\r\n" - "This is dummy body1", - 0, STREAM_TOSERVER, 0 }, - { (const uint8_t *)"This is dummy message body2", - 0, STREAM_TOSERVER, 1 }, - { NULL, 0, 0, 0 }, + { (const uint8_t *)"GET /index.html HTTP/1.1\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 46\r\n" + "\r\n" + "This is dummy body1", + 0, STREAM_TOSERVER, 0 }, + { (const uint8_t *)"This is dummy message body2", 0, STREAM_TOSERVER, 1 }, + { NULL, 0, 0, 0 }, }; - const char *sig = "alert http any any -> any any (content:!\"body1\"; http_client_body; depth:15; sid:1;)"; + const char *sig = "alert http any any -> any any (content:!\"body1\"; http_client_body; " + "depth:15; sid:1;)"; return RunTest(steps, sig, NULL); } static int DetectEngineHttpClientBodyTest08(void) { struct TestSteps steps[] = { - { (const uint8_t *)"GET /index.html HTTP/1.1\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 46\r\n" - "\r\n" - "This is dummy body1", - 0, STREAM_TOSERVER, 0 }, - { (const uint8_t *)"This is dummy message body2", - 0, STREAM_TOSERVER, 1 }, - { NULL, 0, 0, 0 }, + { (const uint8_t *)"GET /index.html HTTP/1.1\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 46\r\n" + "\r\n" + "This is dummy body1", + 0, STREAM_TOSERVER, 0 }, + { (const uint8_t *)"This is dummy message body2", 0, STREAM_TOSERVER, 1 }, + { NULL, 0, 0, 0 }, }; - const char *sig = "alert http any any -> any any (content:\"This is dummy body1This is dummy message body2\"; http_client_body; sid:1;)"; + const char *sig = "alert http any any -> any any (content:\"This is dummy body1This is dummy " + "message body2\"; http_client_body; sid:1;)"; return RunTest(steps, sig, NULL); } static int DetectEngineHttpClientBodyTest09(void) { struct TestSteps steps[] = { - { (const uint8_t *)"GET /index.html HTTP/1.1\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 46\r\n" - "\r\n" - "This is dummy body1", - 0, STREAM_TOSERVER, 0 }, - { (const uint8_t *)"This is dummy message body2", - 0, STREAM_TOSERVER, 1 }, - { NULL, 0, 0, 0 }, + { (const uint8_t *)"GET /index.html HTTP/1.1\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 46\r\n" + "\r\n" + "This is dummy body1", + 0, STREAM_TOSERVER, 0 }, + { (const uint8_t *)"This is dummy message body2", 0, STREAM_TOSERVER, 1 }, + { NULL, 0, 0, 0 }, }; - const char *sig = "alert http any any -> any any (content:\"body1\"; http_client_body; content:\"This\"; http_client_body; within:5; sid:1;)"; + const char *sig = "alert http any any -> any any (content:\"body1\"; http_client_body; " + "content:\"This\"; http_client_body; within:5; sid:1;)"; return RunTest(steps, sig, NULL); } static int DetectEngineHttpClientBodyTest10(void) { struct TestSteps steps[] = { - { (const uint8_t *)"GET /index.html HTTP/1.1\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 46\r\n" - "\r\n" - "This is dummy body1", - 0, STREAM_TOSERVER, 0 }, - { (const uint8_t *)"This is dummy message body2", - 0, STREAM_TOSERVER, 1 }, - { NULL, 0, 0, 0 }, + { (const uint8_t *)"GET /index.html HTTP/1.1\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 46\r\n" + "\r\n" + "This is dummy body1", + 0, STREAM_TOSERVER, 0 }, + { (const uint8_t *)"This is dummy message body2", 0, STREAM_TOSERVER, 1 }, + { NULL, 0, 0, 0 }, }; - const char *sig = "alert http any any -> any any (content:\"body1\"; http_client_body; content:!\"boom\"; http_client_body; within:5; sid:1;)"; + const char *sig = "alert http any any -> any any (content:\"body1\"; http_client_body; " + "content:!\"boom\"; http_client_body; within:5; sid:1;)"; return RunTest(steps, sig, NULL); } static int DetectEngineHttpClientBodyTest11(void) { struct TestSteps steps[] = { - { (const uint8_t *)"GET /index.html HTTP/1.1\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 46\r\n" - "\r\n" - "This is dummy body1", - 0, STREAM_TOSERVER, 0 }, - { (const uint8_t *)"This is dummy message body2", - 0, STREAM_TOSERVER, 0 }, - { NULL, 0, 0, 0 }, + { (const uint8_t *)"GET /index.html HTTP/1.1\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 46\r\n" + "\r\n" + "This is dummy body1", + 0, STREAM_TOSERVER, 0 }, + { (const uint8_t *)"This is dummy message body2", 0, STREAM_TOSERVER, 0 }, + { NULL, 0, 0, 0 }, }; - const char *sig = "alert http any any -> any any (content:\"body1\"; http_client_body; content:\"boom\"; http_client_body; within:5; sid:1;)"; + const char *sig = "alert http any any -> any any (content:\"body1\"; http_client_body; " + "content:\"boom\"; http_client_body; within:5; sid:1;)"; return RunTest(steps, sig, NULL); } static int DetectEngineHttpClientBodyTest12(void) { struct TestSteps steps[] = { - { (const uint8_t *)"GET /index.html HTTP/1.1\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 46\r\n" - "\r\n" - "This is dummy body1", - 0, STREAM_TOSERVER, 0 }, - { (const uint8_t *)"This is dummy message body2", - 0, STREAM_TOSERVER, 0 }, - { NULL, 0, 0, 0 }, + { (const uint8_t *)"GET /index.html HTTP/1.1\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 46\r\n" + "\r\n" + "This is dummy body1", + 0, STREAM_TOSERVER, 0 }, + { (const uint8_t *)"This is dummy message body2", 0, STREAM_TOSERVER, 0 }, + { NULL, 0, 0, 0 }, }; - const char *sig = "alert http any any -> any any (content:\"body1\"; http_client_body; content:!\"This\"; http_client_body; within:5; sid:1;)"; + const char *sig = "alert http any any -> any any (content:\"body1\"; http_client_body; " + "content:!\"This\"; http_client_body; within:5; sid:1;)"; return RunTest(steps, sig, NULL); } static int DetectEngineHttpClientBodyTest13(void) { struct TestSteps steps[] = { - { (const uint8_t *)"GET /index.html HTTP/1.1\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 46\r\n" - "\r\n" - "This is dummy body1", - 0, STREAM_TOSERVER, 0 }, - { (const uint8_t *)"This is dummy message body2", - 0, STREAM_TOSERVER, 1 }, - { NULL, 0, 0, 0 }, + { (const uint8_t *)"GET /index.html HTTP/1.1\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 46\r\n" + "\r\n" + "This is dummy body1", + 0, STREAM_TOSERVER, 0 }, + { (const uint8_t *)"This is dummy message body2", 0, STREAM_TOSERVER, 1 }, + { NULL, 0, 0, 0 }, }; - const char *sig = "alert http any any -> any any (content:\"body1\"; http_client_body; content:\"dummy\"; http_client_body; distance:5; sid:1;)"; + const char *sig = "alert http any any -> any any (content:\"body1\"; http_client_body; " + "content:\"dummy\"; http_client_body; distance:5; sid:1;)"; return RunTest(steps, sig, NULL); } static int DetectEngineHttpClientBodyTest14(void) { struct TestSteps steps[] = { - { (const uint8_t *)"GET /index.html HTTP/1.1\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 46\r\n" - "\r\n" - "This is dummy body1", - 0, STREAM_TOSERVER, 0 }, - { (const uint8_t *)"This is dummy message body2", - 0, STREAM_TOSERVER, 1 }, - { NULL, 0, 0, 0 }, + { (const uint8_t *)"GET /index.html HTTP/1.1\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 46\r\n" + "\r\n" + "This is dummy body1", + 0, STREAM_TOSERVER, 0 }, + { (const uint8_t *)"This is dummy message body2", 0, STREAM_TOSERVER, 1 }, + { NULL, 0, 0, 0 }, }; - const char *sig = "alert http any any -> any any (content:\"body1\"; http_client_body; content:!\"dummy\"; http_client_body; distance:10; sid:1;)"; + const char *sig = "alert http any any -> any any (content:\"body1\"; http_client_body; " + "content:!\"dummy\"; http_client_body; distance:10; sid:1;)"; return RunTest(steps, sig, NULL); } static int DetectEngineHttpClientBodyTest15(void) { struct TestSteps steps[] = { - { (const uint8_t *)"GET /index.html HTTP/1.1\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 46\r\n" - "\r\n" - "This is dummy body1", - 0, STREAM_TOSERVER, 0 }, - { (const uint8_t *)"This is dummy message body2", - 0, STREAM_TOSERVER, 0 }, - { NULL, 0, 0, 0 }, + { (const uint8_t *)"GET /index.html HTTP/1.1\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 46\r\n" + "\r\n" + "This is dummy body1", + 0, STREAM_TOSERVER, 0 }, + { (const uint8_t *)"This is dummy message body2", 0, STREAM_TOSERVER, 0 }, + { NULL, 0, 0, 0 }, }; - const char *sig = "alert http any any -> any any (content:\"body1\"; http_client_body; content:\"dummy\"; http_client_body; distance:10; sid:1;)"; + const char *sig = "alert http any any -> any any (content:\"body1\"; http_client_body; " + "content:\"dummy\"; http_client_body; distance:10; sid:1;)"; return RunTest(steps, sig, NULL); } static int DetectEngineHttpClientBodyTest16(void) { struct TestSteps steps[] = { - { (const uint8_t *)"GET /index.html HTTP/1.1\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 46\r\n" - "\r\n" - "This is dummy body1", - 0, STREAM_TOSERVER, 0 }, - { (const uint8_t *)"This is dummy message body2", - 0, STREAM_TOSERVER, 0 }, - { NULL, 0, 0, 0 }, + { (const uint8_t *)"GET /index.html HTTP/1.1\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 46\r\n" + "\r\n" + "This is dummy body1", + 0, STREAM_TOSERVER, 0 }, + { (const uint8_t *)"This is dummy message body2", 0, STREAM_TOSERVER, 0 }, + { NULL, 0, 0, 0 }, }; - const char *sig = "alert http any any -> any any (content:\"body1\"; http_client_body; content:!\"dummy\"; http_client_body; distance:5; sid:1;)"; + const char *sig = "alert http any any -> any any (content:\"body1\"; http_client_body; " + "content:!\"dummy\"; http_client_body; distance:5; sid:1;)"; return RunTest(steps, sig, NULL); } static int DetectEngineHttpClientBodyTest17(void) { struct TestSteps steps[] = { - { (const uint8_t *)"GET /index.html HTTP/1.1\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 19\r\n" - "\r\n" - "This is dummy body1", - 0, STREAM_TOSERVER, 0 }, - { NULL, 0, 0, 0 }, + { (const uint8_t *)"GET /index.html HTTP/1.1\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 19\r\n" + "\r\n" + "This is dummy body1", + 0, STREAM_TOSERVER, 0 }, + { NULL, 0, 0, 0 }, }; - const char *sig = "alert http any any -> any any (content:\"body1\"; http_client_body; content:\"bambu\"; http_client_body; sid:1;)"; + const char *sig = "alert http any any -> any any (content:\"body1\"; http_client_body; " + "content:\"bambu\"; http_client_body; sid:1;)"; return RunTest(steps, sig, NULL); } static int DetectEngineHttpClientBodyTest18(void) { struct TestSteps steps[] = { - { (const uint8_t *)"GET /index.html HTTP/1.1\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 19\r\n" - "\r\n" - "This is dummy body1", - 0, STREAM_TOSERVER, 0 }, - { NULL, 0, 0, 0 }, + { (const uint8_t *)"GET /index.html HTTP/1.1\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 19\r\n" + "\r\n" + "This is dummy body1", + 0, STREAM_TOSERVER, 0 }, + { NULL, 0, 0, 0 }, }; - const char *sig = "alert http any any -> any any (content:\"body1\"; http_client_body; content:\"bambu\"; http_client_body; fast_pattern; sid:1;)"; + const char *sig = "alert http any any -> any any (content:\"body1\"; http_client_body; " + "content:\"bambu\"; http_client_body; fast_pattern; sid:1;)"; return RunTest(steps, sig, NULL); } static int DetectEngineHttpClientBodyTest19(void) { struct TestSteps steps[] = { - { (const uint8_t *)"GET /index.html HTTP/1.1\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 19\r\n" - "\r\n" - "This is dummy body1", - 0, STREAM_TOSERVER, 0 }, - { NULL, 0, 0, 0 }, + { (const uint8_t *)"GET /index.html HTTP/1.1\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 19\r\n" + "\r\n" + "This is dummy body1", + 0, STREAM_TOSERVER, 0 }, + { NULL, 0, 0, 0 }, }; - const char *sig = "alert http any any -> any any (content:\"bambu\"; http_client_body; content:\"is\"; http_client_body; sid:1;)"; + const char *sig = "alert http any any -> any any (content:\"bambu\"; http_client_body; " + "content:\"is\"; http_client_body; sid:1;)"; return RunTest(steps, sig, NULL); } static int DetectEngineHttpClientBodyTest20(void) { struct TestSteps steps[] = { - { (const uint8_t *)"GET /index.html HTTP/1.1\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 19\r\n" - "\r\n" - "This is dummy body1", - 0, STREAM_TOSERVER, 1 }, - { NULL, 0, 0, 0 }, + { (const uint8_t *)"GET /index.html HTTP/1.1\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 19\r\n" + "\r\n" + "This is dummy body1", + 0, STREAM_TOSERVER, 1 }, + { NULL, 0, 0, 0 }, }; - const char *sig = "alert http any any -> any any (content:\"is\"; http_client_body; fast_pattern; sid:1;)"; + const char *sig = "alert http any any -> any any (content:\"is\"; http_client_body; " + "fast_pattern; sid:1;)"; return RunTest(steps, sig, NULL); } static int DetectEngineHttpClientBodyTest21(void) { struct TestSteps steps[] = { - { (const uint8_t *)"GET /index.html HTTP/1.1\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 46\r\n" - "\r\n" - "This is dummy body1", - 0, STREAM_TOSERVER, 0 }, - { (const uint8_t *)"This is dummy message body2", - 0, STREAM_TOSERVER, 1 }, - { NULL, 0, 0, 0 }, + { (const uint8_t *)"GET /index.html HTTP/1.1\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 46\r\n" + "\r\n" + "This is dummy body1", + 0, STREAM_TOSERVER, 0 }, + { (const uint8_t *)"This is dummy message body2", 0, STREAM_TOSERVER, 1 }, + { NULL, 0, 0, 0 }, }; - const char *sig = "alert http any any -> any any (pcre:/body1/P; content:!\"dummy\"; http_client_body; within:7; sid:1;)"; + const char *sig = "alert http any any -> any any (pcre:/body1/P; content:!\"dummy\"; " + "http_client_body; within:7; sid:1;)"; return RunTest(steps, sig, NULL); } static int DetectEngineHttpClientBodyTest22(void) { struct TestSteps steps[] = { - { (const uint8_t *)"GET /index.html HTTP/1.1\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 46\r\n" - "\r\n" - "This is dummy body1", - 0, STREAM_TOSERVER, 0 }, - { (const uint8_t *)"This is dummy message body2", - 0, STREAM_TOSERVER, 1 }, - { NULL, 0, 0, 0 }, + { (const uint8_t *)"GET /index.html HTTP/1.1\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 46\r\n" + "\r\n" + "This is dummy body1", + 0, STREAM_TOSERVER, 0 }, + { (const uint8_t *)"This is dummy message body2", 0, STREAM_TOSERVER, 1 }, + { NULL, 0, 0, 0 }, }; - const char *sig = "alert http any any -> any any (pcre:/body1/P; content:!\"dummy\"; within:7; http_client_body; sid:1;)"; + const char *sig = "alert http any any -> any any (pcre:/body1/P; content:!\"dummy\"; within:7; " + "http_client_body; sid:1;)"; return RunTest(steps, sig, NULL); } static int DetectEngineHttpClientBodyTest23(void) { struct TestSteps steps[] = { - { (const uint8_t *)"GET /index.html HTTP/1.1\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 46\r\n" - "\r\n" - "This is dummy body1", - 0, STREAM_TOSERVER, 0 }, - { (const uint8_t *)"This is dummy message body2", - 0, STREAM_TOSERVER, 0 }, - { NULL, 0, 0, 0 }, + { (const uint8_t *)"GET /index.html HTTP/1.1\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 46\r\n" + "\r\n" + "This is dummy body1", + 0, STREAM_TOSERVER, 0 }, + { (const uint8_t *)"This is dummy message body2", 0, STREAM_TOSERVER, 0 }, + { NULL, 0, 0, 0 }, }; - const char *sig = "alert http any any -> any any (pcre:/body1/P; content:!\"dummy\"; distance:3; http_client_body; sid:1;)"; + const char *sig = "alert http any any -> any any (pcre:/body1/P; content:!\"dummy\"; " + "distance:3; http_client_body; sid:1;)"; return RunTest(steps, sig, NULL); } static int DetectEngineHttpClientBodyTest24(void) { struct TestSteps steps[] = { - { (const uint8_t *)"GET /index.html HTTP/1.1\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 46\r\n" - "\r\n" - "This is dummy body1", - 0, STREAM_TOSERVER, 0 }, - { (const uint8_t *)"This is dummy message body2", - 0, STREAM_TOSERVER, 1 }, - { NULL, 0, 0, 0 }, + { (const uint8_t *)"GET /index.html HTTP/1.1\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 46\r\n" + "\r\n" + "This is dummy body1", + 0, STREAM_TOSERVER, 0 }, + { (const uint8_t *)"This is dummy message body2", 0, STREAM_TOSERVER, 1 }, + { NULL, 0, 0, 0 }, }; - const char *sig = "alert http any any -> any any (pcre:/body1/P; content:!\"dummy\"; distance:13; http_client_body; sid:1;)"; + const char *sig = "alert http any any -> any any (pcre:/body1/P; content:!\"dummy\"; " + "distance:13; http_client_body; sid:1;)"; return RunTest(steps, sig, NULL); } static int DetectEngineHttpClientBodyTest25(void) { struct TestSteps steps[] = { - { (const uint8_t *)"GET /index.html HTTP/1.1\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 46\r\n" - "\r\n" - "This is dummy body1", - 0, STREAM_TOSERVER, 0 }, - { (const uint8_t *)"This is dummy message body2", - 0, STREAM_TOSERVER, 1 }, - { NULL, 0, 0, 0 }, + { (const uint8_t *)"GET /index.html HTTP/1.1\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 46\r\n" + "\r\n" + "This is dummy body1", + 0, STREAM_TOSERVER, 0 }, + { (const uint8_t *)"This is dummy message body2", 0, STREAM_TOSERVER, 1 }, + { NULL, 0, 0, 0 }, }; - const char *sig = "alert http any any -> any any (pcre:/body1/P; content:\"dummy\"; within:15; http_client_body; sid:1;)"; + const char *sig = "alert http any any -> any any (pcre:/body1/P; content:\"dummy\"; within:15; " + "http_client_body; sid:1;)"; return RunTest(steps, sig, NULL); } static int DetectEngineHttpClientBodyTest26(void) { struct TestSteps steps[] = { - { (const uint8_t *)"GET /index.html HTTP/1.1\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 46\r\n" - "\r\n" - "This is dummy body1", - 0, STREAM_TOSERVER, 0 }, - { (const uint8_t *)"This is dummy message body2", - 0, STREAM_TOSERVER, 0 }, - { NULL, 0, 0, 0 }, + { (const uint8_t *)"GET /index.html HTTP/1.1\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 46\r\n" + "\r\n" + "This is dummy body1", + 0, STREAM_TOSERVER, 0 }, + { (const uint8_t *)"This is dummy message body2", 0, STREAM_TOSERVER, 0 }, + { NULL, 0, 0, 0 }, }; - const char *sig = "alert http any any -> any any (pcre:/body1/P; content:\"dummy\"; within:10; http_client_body; sid:1;)"; + const char *sig = "alert http any any -> any any (pcre:/body1/P; content:\"dummy\"; within:10; " + "http_client_body; sid:1;)"; return RunTest(steps, sig, NULL); } static int DetectEngineHttpClientBodyTest27(void) { struct TestSteps steps[] = { - { (const uint8_t *)"GET /index.html HTTP/1.1\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 46\r\n" - "\r\n" - "This is dummy body1", - 0, STREAM_TOSERVER, 0 }, - { (const uint8_t *)"This is dummy message body2", - 0, STREAM_TOSERVER, 1 }, - { NULL, 0, 0, 0 }, + { (const uint8_t *)"GET /index.html HTTP/1.1\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 46\r\n" + "\r\n" + "This is dummy body1", + 0, STREAM_TOSERVER, 0 }, + { (const uint8_t *)"This is dummy message body2", 0, STREAM_TOSERVER, 1 }, + { NULL, 0, 0, 0 }, }; - const char *sig = "alert http any any -> any any (pcre:/body1/P; content:\"dummy\"; distance:8; http_client_body; sid:1;)"; + const char *sig = "alert http any any -> any any (pcre:/body1/P; content:\"dummy\"; " + "distance:8; http_client_body; sid:1;)"; return RunTest(steps, sig, NULL); } static int DetectEngineHttpClientBodyTest28(void) { struct TestSteps steps[] = { - { (const uint8_t *)"GET /index.html HTTP/1.1\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 46\r\n" - "\r\n" - "This is dummy body1", - 0, STREAM_TOSERVER, 0 }, - { (const uint8_t *)"This is dummy message body2", - 0, STREAM_TOSERVER, 0 }, - { NULL, 0, 0, 0 }, + { (const uint8_t *)"GET /index.html HTTP/1.1\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 46\r\n" + "\r\n" + "This is dummy body1", + 0, STREAM_TOSERVER, 0 }, + { (const uint8_t *)"This is dummy message body2", 0, STREAM_TOSERVER, 0 }, + { NULL, 0, 0, 0 }, }; - const char *sig = "alert http any any -> any any (pcre:/body1/P; content:\"dummy\"; distance:14; http_client_body; sid:1;)"; + const char *sig = "alert http any any -> any any (pcre:/body1/P; content:\"dummy\"; " + "distance:14; http_client_body; sid:1;)"; return RunTest(steps, sig, NULL); } @@ -725,27 +762,26 @@ static int DetectEngineHttpClientBodyTest29(void) if (unlikely(http_buf == NULL)) return 0; for (int i = 0; i < TOTAL_REQUESTS; i++) { - memcpy(http_buf + i * strlen(request_buffer), request_buffer, - strlen(request_buffer)); + memcpy(http_buf + i * strlen(request_buffer), request_buffer, strlen(request_buffer)); } uint32_t http_buf_len = TOTAL_REQUESTS * strlen(request_buffer); #undef TOTAL_REQUESTS struct TestSteps steps[] = { - { (const uint8_t *)http_buf, - (size_t)http_buf_len, STREAM_TOSERVER, 0 }, + { (const uint8_t *)http_buf, (size_t)http_buf_len, STREAM_TOSERVER, 0 }, - { (const uint8_t *)"HTTP/1.0 200 ok\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 5\r\n" - "\r\n" - "dummy", - 0, STREAM_TOCLIENT, 0 }, + { (const uint8_t *)"HTTP/1.0 200 ok\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 5\r\n" + "\r\n" + "dummy", + 0, STREAM_TOCLIENT, 0 }, - { NULL, 0, 0, 0 }, + { NULL, 0, 0, 0 }, }; - const char *sig = "alert http any any -> any any (content:\"dummyone\"; fast_pattern:0,3; http_server_body; sid:1;)"; + const char *sig = "alert http any any -> any any (content:\"dummyone\"; fast_pattern:0,3; " + "http_server_body; sid:1;)"; int result = RunTest(steps, sig, NULL); SCFree(http_buf); return result; @@ -769,19 +805,19 @@ libhtp:\n\ response-body-minimal-inspect-size: 0\n\ "; struct TestSteps steps[] = { - { (const uint8_t *)"GET /index.html HTTP/1.1\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 46\r\n" - "\r\n" - "This is dummy body1", - 0, STREAM_TOSERVER, 0 }, - { (const uint8_t *)"This is dummy message body2", - 0, STREAM_TOSERVER, 0 }, - { NULL, 0, 0, 0 }, + { (const uint8_t *)"GET /index.html HTTP/1.1\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 46\r\n" + "\r\n" + "This is dummy body1", + 0, STREAM_TOSERVER, 0 }, + { (const uint8_t *)"This is dummy message body2", 0, STREAM_TOSERVER, 0 }, + { NULL, 0, 0, 0 }, }; - const char *sig = "alert http any any -> any any (content:\"bags\"; within:4; http_client_body; sid:1;)"; + const char *sig = + "alert http any any -> any any (content:\"bags\"; within:4; http_client_body; sid:1;)"; return RunTest(steps, sig, yaml); } @@ -804,19 +840,19 @@ libhtp:\n\ "; struct TestSteps steps[] = { - { (const uint8_t *)"GET /index.html HTTP/1.1\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 46\r\n" - "\r\n" - "This is dummy body1", - 0, STREAM_TOSERVER, 0 }, - { (const uint8_t *)"This is dummy message body2", - 0, STREAM_TOSERVER, 0 }, - { NULL, 0, 0, 0 }, + { (const uint8_t *)"GET /index.html HTTP/1.1\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 46\r\n" + "\r\n" + "This is dummy body1", + 0, STREAM_TOSERVER, 0 }, + { (const uint8_t *)"This is dummy message body2", 0, STREAM_TOSERVER, 0 }, + { NULL, 0, 0, 0 }, }; - const char *sig = "alert http any any -> any any (content:\"bags\"; depth:4; http_client_body; sid:1;)"; + const char *sig = + "alert http any any -> any any (content:\"bags\"; depth:4; http_client_body; sid:1;)"; return RunTest(steps, sig, yaml); } @@ -923,14 +959,14 @@ static int DetectHttpClientBodyTest06(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 26\r\n" - "\r\n" - "This is dummy message body"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 26\r\n" + "\r\n" + "This is dummy message body"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -949,7 +985,7 @@ static int DetectHttpClientBodyTest06(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1019,16 +1055,15 @@ static int DetectHttpClientBodyTest07(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http1_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 54\r\n" - "\r\n" - "This is dummy message body1"; - uint8_t http2_buf[] = - "This is dummy message body2"; + uint8_t http1_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 54\r\n" + "\r\n" + "This is dummy message body1"; + uint8_t http2_buf[] = "This is dummy message body2"; uint32_t http1_len = sizeof(http1_buf) - 1; uint32_t http2_len = sizeof(http2_buf) - 1; int result = 0; @@ -1049,11 +1084,11 @@ static int DetectHttpClientBodyTest07(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOSERVER; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1137,16 +1172,15 @@ static int DetectHttpClientBodyTest08(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http1_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 46\r\n" - "\r\n" - "This is dummy body1"; - uint8_t http2_buf[] = - "This is dummy message body2"; + uint8_t http1_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 46\r\n" + "\r\n" + "This is dummy body1"; + uint8_t http2_buf[] = "This is dummy message body2"; uint32_t http1_len = sizeof(http1_buf) - 1; uint32_t http2_len = sizeof(http2_buf) - 1; int result = 0; @@ -1167,11 +1201,11 @@ static int DetectHttpClientBodyTest08(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOSERVER; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1258,16 +1292,15 @@ static int DetectHttpClientBodyTest09(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http1_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 46\r\n" - "\r\n" - "This is dummy body1"; - uint8_t http2_buf[] = - "This is dummy message body2"; + uint8_t http1_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 46\r\n" + "\r\n" + "This is dummy body1"; + uint8_t http2_buf[] = "This is dummy message body2"; uint32_t http1_len = sizeof(http1_buf) - 1; uint32_t http2_len = sizeof(http2_buf) - 1; int result = 0; @@ -1288,11 +1321,11 @@ static int DetectHttpClientBodyTest09(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOSERVER; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1379,16 +1412,15 @@ static int DetectHttpClientBodyTest10(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http1_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 46\r\n" - "\r\n" - "This is dummy bodY1"; - uint8_t http2_buf[] = - "This is dummy message body2"; + uint8_t http1_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 46\r\n" + "\r\n" + "This is dummy bodY1"; + uint8_t http2_buf[] = "This is dummy message body2"; uint32_t http1_len = sizeof(http1_buf) - 1; uint32_t http2_len = sizeof(http2_buf) - 1; int result = 0; @@ -1409,11 +1441,11 @@ static int DetectHttpClientBodyTest10(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOSERVER; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1499,14 +1531,14 @@ static int DetectHttpClientBodyTest11(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 26\r\n" - "\r\n" - "This is dummy message body"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 26\r\n" + "\r\n" + "This is dummy message body"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -1525,7 +1557,7 @@ static int DetectHttpClientBodyTest11(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1594,14 +1626,14 @@ static int DetectHttpClientBodyTest12(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 26\r\n" - "\r\n" - "This is dummy message body"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 26\r\n" + "\r\n" + "This is dummy message body"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -1620,7 +1652,7 @@ static int DetectHttpClientBodyTest12(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1689,14 +1721,14 @@ static int DetectHttpClientBodyTest13(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 55\r\n" - "\r\n" - "longbufferabcdefghijklmnopqrstuvwxyz0123456789bufferend"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 55\r\n" + "\r\n" + "longbufferabcdefghijklmnopqrstuvwxyz0123456789bufferend"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -1715,7 +1747,7 @@ static int DetectHttpClientBodyTest13(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1812,7 +1844,7 @@ static int DetectHttpClientBodyTest14(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1824,12 +1856,18 @@ static int DetectHttpClientBodyTest14(void) de_ctx->flags |= DE_QUIET; - s = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any (content:\"POST\"; http_method; content:\"Mozilla\"; http_header; content:\"dummy\"; http_cookie; content:\"one\"; http_client_body; sid:1; rev:1;)"); + s = DetectEngineAppendSig( + de_ctx, "alert tcp any any -> any any (content:\"POST\"; http_method; " + "content:\"Mozilla\"; http_header; content:\"dummy\"; http_cookie; " + "content:\"one\"; http_client_body; sid:1; rev:1;)"); if (s == NULL) { printf("sig parse failed: "); goto end; } - s = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any (content:\"GET\"; http_method; content:\"Firefox\"; http_header; content:\"dummy2\"; http_cookie; content:\"two\"; http_client_body; sid:2; rev:1;)"); + s = DetectEngineAppendSig( + de_ctx, "alert tcp any any -> any any (content:\"GET\"; http_method; " + "content:\"Firefox\"; http_header; content:\"dummy2\"; http_cookie; " + "content:\"two\"; http_client_body; sid:2; rev:1;)"); if (s == NULL) { printf("sig2 parse failed: "); goto end; @@ -2009,7 +2047,7 @@ static int DetectHttpClientBodyTest15(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -2021,12 +2059,18 @@ static int DetectHttpClientBodyTest15(void) de_ctx->flags |= DE_QUIET; - s = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any (content:\"POST\"; http_method; content:\"Mozilla\"; http_header; content:\"dummy\"; http_cookie; content:\"one\"; http_client_body; sid:1; rev:1;)"); + s = DetectEngineAppendSig( + de_ctx, "alert tcp any any -> any any (content:\"POST\"; http_method; " + "content:\"Mozilla\"; http_header; content:\"dummy\"; http_cookie; " + "content:\"one\"; http_client_body; sid:1; rev:1;)"); if (s == NULL) { printf("sig parse failed: "); goto end; } - s = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any (content:\"GET\"; http_method; content:\"Firefox\"; http_header; content:\"dummy2\"; http_cookie; content:\"two\"; http_client_body; sid:2; rev:1;)"); + s = DetectEngineAppendSig( + de_ctx, "alert tcp any any -> any any (content:\"GET\"; http_method; " + "content:\"Firefox\"; http_header; content:\"dummy2\"; http_cookie; " + "content:\"two\"; http_client_body; sid:2; rev:1;)"); if (s == NULL) { printf("sig2 parse failed: "); goto end; @@ -2153,7 +2197,7 @@ static int DetectHttpClientBodyTest15(void) htp_tx_t *t1 = AppLayerParserGetTx(IPPROTO_TCP, ALPROTO_HTTP1, htp_state, 0); htp_tx_t *t2 = AppLayerParserGetTx(IPPROTO_TCP, ALPROTO_HTTP1, htp_state, 1); - HtpTxUserData *htud = (HtpTxUserData *) htp_tx_get_user_data(t1); + HtpTxUserData *htud = (HtpTxUserData *)htp_tx_get_user_data(t1); HtpBodyChunk *cur = htud->request_body.first; if (htud->request_body.first == NULL) { @@ -2161,14 +2205,13 @@ static int DetectHttpClientBodyTest15(void) goto end; } - if (StreamingBufferSegmentCompareRawData(htud->request_body.sb, &cur->sbseg, - (uint8_t *)"Body one!!", 10) != 1) - { + if (StreamingBufferSegmentCompareRawData( + htud->request_body.sb, &cur->sbseg, (uint8_t *)"Body one!!", 10) != 1) { SCLogDebug("Body data in t1 is not correctly set: "); goto end; } - htud = (HtpTxUserData *) htp_tx_get_user_data(t2); + htud = (HtpTxUserData *)htp_tx_get_user_data(t2); cur = htud->request_body.first; if (htud->request_body.first == NULL) { @@ -2176,9 +2219,8 @@ static int DetectHttpClientBodyTest15(void) goto end; } - if (StreamingBufferSegmentCompareRawData(htud->request_body.sb, &cur->sbseg, - (uint8_t *)"Body two!!", 10) != 1) - { + if (StreamingBufferSegmentCompareRawData( + htud->request_body.sb, &cur->sbseg, (uint8_t *)"Body two!!", 10) != 1) { SCLogDebug("Body data in t1 is not correctly set: "); goto end; } @@ -2287,7 +2329,7 @@ static int DetectHttpClientBodyTest24(void) DetectEngineCtx *de_ctx = NULL; int result = 0; - if ( (de_ctx = DetectEngineCtxInit()) == NULL) + if ((de_ctx = DetectEngineCtxInit()) == NULL) goto end; de_ctx->flags |= DE_QUIET; @@ -2321,24 +2363,22 @@ static int DetectHttpClientBodyTest24(void) ->prev->ctx; DetectContentData *hcbd2 = (DetectContentData *)DetectBufferGetLastSigMatch(s, g_http_client_body_buffer_id)->ctx; - if (pd1->flags != 0 || - cd2->flags != 0 || memcmp(cd2->content, "four", cd2->content_len) != 0 || - hcbd1->flags != DETECT_CONTENT_RELATIVE_NEXT || - memcmp(hcbd1->content, "one", hcbd1->content_len) != 0 || - hcbd2->flags != (DETECT_CONTENT_DISTANCE | DETECT_CONTENT_WITHIN) || - memcmp(hcbd2->content, "three", hcbd1->content_len) != 0) { + if (pd1->flags != 0 || cd2->flags != 0 || memcmp(cd2->content, "four", cd2->content_len) != 0 || + hcbd1->flags != DETECT_CONTENT_RELATIVE_NEXT || + memcmp(hcbd1->content, "one", hcbd1->content_len) != 0 || + hcbd2->flags != (DETECT_CONTENT_DISTANCE | DETECT_CONTENT_WITHIN) || + memcmp(hcbd2->content, "three", hcbd1->content_len) != 0) { goto end; } - if (!DETECT_CONTENT_IS_SINGLE(cd2) || - DETECT_CONTENT_IS_SINGLE(hcbd1) || - DETECT_CONTENT_IS_SINGLE(hcbd2)) { + if (!DETECT_CONTENT_IS_SINGLE(cd2) || DETECT_CONTENT_IS_SINGLE(hcbd1) || + DETECT_CONTENT_IS_SINGLE(hcbd2)) { goto end; } result = 1; - end: +end: DetectEngineCtxFree(de_ctx); return result; } @@ -2348,7 +2388,7 @@ static int DetectHttpClientBodyTest25(void) DetectEngineCtx *de_ctx = NULL; int result = 0; - if ( (de_ctx = DetectEngineCtxInit()) == NULL) + if ((de_ctx = DetectEngineCtxInit()) == NULL) goto end; de_ctx->flags |= DE_QUIET; @@ -2383,25 +2423,23 @@ static int DetectHttpClientBodyTest25(void) ->prev->ctx; DetectContentData *hcbd2 = (DetectContentData *)DetectBufferGetLastSigMatch(s, g_http_client_body_buffer_id)->ctx; - if (pd1->flags != DETECT_PCRE_RELATIVE_NEXT || - cd2->flags != DETECT_CONTENT_DISTANCE || - memcmp(cd2->content, "four", cd2->content_len) != 0 || - hcbd1->flags != DETECT_CONTENT_RELATIVE_NEXT || - memcmp(hcbd1->content, "one", hcbd1->content_len) != 0 || - hcbd2->flags != DETECT_CONTENT_DISTANCE || - memcmp(hcbd2->content, "three", hcbd1->content_len) != 0) { + if (pd1->flags != DETECT_PCRE_RELATIVE_NEXT || cd2->flags != DETECT_CONTENT_DISTANCE || + memcmp(cd2->content, "four", cd2->content_len) != 0 || + hcbd1->flags != DETECT_CONTENT_RELATIVE_NEXT || + memcmp(hcbd1->content, "one", hcbd1->content_len) != 0 || + hcbd2->flags != DETECT_CONTENT_DISTANCE || + memcmp(hcbd2->content, "three", hcbd1->content_len) != 0) { goto end; } - if (DETECT_CONTENT_IS_SINGLE(cd2) || - DETECT_CONTENT_IS_SINGLE(hcbd1) || - DETECT_CONTENT_IS_SINGLE(hcbd2)) { + if (DETECT_CONTENT_IS_SINGLE(cd2) || DETECT_CONTENT_IS_SINGLE(hcbd1) || + DETECT_CONTENT_IS_SINGLE(hcbd2)) { goto end; } result = 1; - end: +end: DetectEngineCtxFree(de_ctx); return result; } @@ -2411,7 +2449,7 @@ static int DetectHttpClientBodyTest26(void) DetectEngineCtx *de_ctx = NULL; int result = 0; - if ( (de_ctx = DetectEngineCtxInit()) == NULL) + if ((de_ctx = DetectEngineCtxInit()) == NULL) goto end; de_ctx->flags |= DE_QUIET; @@ -2446,26 +2484,24 @@ static int DetectHttpClientBodyTest26(void) ->prev->ctx; DetectContentData *hcbd2 = (DetectContentData *)DetectBufferGetLastSigMatch(s, g_http_client_body_buffer_id)->ctx; - if (pd1->flags != (DETECT_PCRE_RELATIVE_NEXT) || - cd2->flags != DETECT_CONTENT_DISTANCE || - memcmp(cd2->content, "four", cd2->content_len) != 0 || - hcbd1->flags != (DETECT_CONTENT_RELATIVE_NEXT | DETECT_CONTENT_OFFSET) || - memcmp(hcbd1->content, "one", hcbd1->content_len) != 0 || - hcbd2->flags != (DETECT_CONTENT_DISTANCE | DETECT_CONTENT_WITHIN) || - memcmp(hcbd2->content, "three", hcbd1->content_len) != 0) { - printf ("failed: http_client_body incorrect flags"); + if (pd1->flags != (DETECT_PCRE_RELATIVE_NEXT) || cd2->flags != DETECT_CONTENT_DISTANCE || + memcmp(cd2->content, "four", cd2->content_len) != 0 || + hcbd1->flags != (DETECT_CONTENT_RELATIVE_NEXT | DETECT_CONTENT_OFFSET) || + memcmp(hcbd1->content, "one", hcbd1->content_len) != 0 || + hcbd2->flags != (DETECT_CONTENT_DISTANCE | DETECT_CONTENT_WITHIN) || + memcmp(hcbd2->content, "three", hcbd1->content_len) != 0) { + printf("failed: http_client_body incorrect flags"); goto end; } - if (DETECT_CONTENT_IS_SINGLE(cd2) || - DETECT_CONTENT_IS_SINGLE(hcbd1) || - DETECT_CONTENT_IS_SINGLE(hcbd2)) { + if (DETECT_CONTENT_IS_SINGLE(cd2) || DETECT_CONTENT_IS_SINGLE(hcbd1) || + DETECT_CONTENT_IS_SINGLE(hcbd2)) { goto end; } result = 1; - end: +end: DetectEngineCtxFree(de_ctx); return result; } @@ -2475,7 +2511,7 @@ static int DetectHttpClientBodyTest27(void) DetectEngineCtx *de_ctx = NULL; int result = 0; - if ( (de_ctx = DetectEngineCtxInit()) == NULL) + if ((de_ctx = DetectEngineCtxInit()) == NULL) goto end; de_ctx->flags |= DE_QUIET; @@ -2488,7 +2524,7 @@ static int DetectHttpClientBodyTest27(void) result = 1; - end: +end: DetectEngineCtxFree(de_ctx); return result; } @@ -2498,7 +2534,7 @@ static int DetectHttpClientBodyTest28(void) DetectEngineCtx *de_ctx = NULL; int result = 0; - if ( (de_ctx = DetectEngineCtxInit()) == NULL) + if ((de_ctx = DetectEngineCtxInit()) == NULL) goto end; de_ctx->flags |= DE_QUIET; @@ -2532,25 +2568,22 @@ static int DetectHttpClientBodyTest28(void) ->prev->ctx; DetectContentData *hcbd2 = (DetectContentData *)DetectBufferGetLastSigMatch(s, g_http_client_body_buffer_id)->ctx; - if (pd1->flags != (DETECT_PCRE_RELATIVE_NEXT) || - cd2->flags != DETECT_CONTENT_DISTANCE || - memcmp(cd2->content, "four", cd2->content_len) != 0 || - hcbd1->flags != 0 || - memcmp(hcbd1->content, "one", hcbd1->content_len) != 0 || - hcbd2->flags != DETECT_CONTENT_DEPTH || - memcmp(hcbd2->content, "three", hcbd1->content_len) != 0) { + if (pd1->flags != (DETECT_PCRE_RELATIVE_NEXT) || cd2->flags != DETECT_CONTENT_DISTANCE || + memcmp(cd2->content, "four", cd2->content_len) != 0 || hcbd1->flags != 0 || + memcmp(hcbd1->content, "one", hcbd1->content_len) != 0 || + hcbd2->flags != DETECT_CONTENT_DEPTH || + memcmp(hcbd2->content, "three", hcbd1->content_len) != 0) { goto end; } - if (DETECT_CONTENT_IS_SINGLE(cd2) || - !DETECT_CONTENT_IS_SINGLE(hcbd1) || - DETECT_CONTENT_IS_SINGLE(hcbd2)) { + if (DETECT_CONTENT_IS_SINGLE(cd2) || !DETECT_CONTENT_IS_SINGLE(hcbd1) || + DETECT_CONTENT_IS_SINGLE(hcbd2)) { goto end; } result = 1; - end: +end: DetectEngineCtxFree(de_ctx); return result; } @@ -2560,7 +2593,7 @@ static int DetectHttpClientBodyTest29(void) DetectEngineCtx *de_ctx = NULL; int result = 0; - if ( (de_ctx = DetectEngineCtxInit()) == NULL) + if ((de_ctx = DetectEngineCtxInit()) == NULL) goto end; de_ctx->flags |= DE_QUIET; @@ -2589,15 +2622,15 @@ static int DetectHttpClientBodyTest29(void) DetectContentData *hcbd2 = (DetectContentData *)DetectBufferGetLastSigMatch(s, g_http_client_body_buffer_id)->ctx; if (hcbd1->flags != DETECT_CONTENT_RELATIVE_NEXT || - memcmp(hcbd1->content, "one", hcbd1->content_len) != 0 || - hcbd2->flags != DETECT_CONTENT_DISTANCE || - memcmp(hcbd2->content, "two", hcbd1->content_len) != 0) { + memcmp(hcbd1->content, "one", hcbd1->content_len) != 0 || + hcbd2->flags != DETECT_CONTENT_DISTANCE || + memcmp(hcbd2->content, "two", hcbd1->content_len) != 0) { goto end; } result = 1; - end: +end: DetectEngineCtxFree(de_ctx); return result; } @@ -2607,7 +2640,7 @@ static int DetectHttpClientBodyTest30(void) DetectEngineCtx *de_ctx = NULL; int result = 0; - if ( (de_ctx = DetectEngineCtxInit()) == NULL) + if ((de_ctx = DetectEngineCtxInit()) == NULL) goto end; de_ctx->flags |= DE_QUIET; @@ -2636,15 +2669,15 @@ static int DetectHttpClientBodyTest30(void) DetectContentData *hcbd2 = (DetectContentData *)DetectBufferGetLastSigMatch(s, g_http_client_body_buffer_id)->ctx; if (hcbd1->flags != DETECT_CONTENT_RELATIVE_NEXT || - memcmp(hcbd1->content, "one", hcbd1->content_len) != 0 || - hcbd2->flags != DETECT_CONTENT_WITHIN || - memcmp(hcbd2->content, "two", hcbd1->content_len) != 0) { + memcmp(hcbd1->content, "one", hcbd1->content_len) != 0 || + hcbd2->flags != DETECT_CONTENT_WITHIN || + memcmp(hcbd2->content, "two", hcbd1->content_len) != 0) { goto end; } result = 1; - end: +end: DetectEngineCtxFree(de_ctx); return result; } @@ -2654,7 +2687,7 @@ static int DetectHttpClientBodyTest31(void) DetectEngineCtx *de_ctx = NULL; int result = 0; - if ( (de_ctx = DetectEngineCtxInit()) == NULL) + if ((de_ctx = DetectEngineCtxInit()) == NULL) goto end; de_ctx->flags |= DE_QUIET; @@ -2665,7 +2698,7 @@ static int DetectHttpClientBodyTest31(void) result = 1; - end: +end: DetectEngineCtxFree(de_ctx); return result; } @@ -2675,7 +2708,7 @@ static int DetectHttpClientBodyTest32(void) DetectEngineCtx *de_ctx = NULL; int result = 0; - if ( (de_ctx = DetectEngineCtxInit()) == NULL) + if ((de_ctx = DetectEngineCtxInit()) == NULL) goto end; de_ctx->flags |= DE_QUIET; @@ -2686,7 +2719,7 @@ static int DetectHttpClientBodyTest32(void) result = 1; - end: +end: DetectEngineCtxFree(de_ctx); return result; } @@ -2696,7 +2729,7 @@ static int DetectHttpClientBodyTest33(void) DetectEngineCtx *de_ctx = NULL; int result = 0; - if ( (de_ctx = DetectEngineCtxInit()) == NULL) + if ((de_ctx = DetectEngineCtxInit()) == NULL) goto end; de_ctx->flags |= DE_QUIET; @@ -2706,7 +2739,7 @@ static int DetectHttpClientBodyTest33(void) result = 1; - end: +end: DetectEngineCtxFree(de_ctx); return result; } @@ -2716,7 +2749,7 @@ static int DetectHttpClientBodyTest34(void) DetectEngineCtx *de_ctx = NULL; int result = 0; - if ( (de_ctx = DetectEngineCtxInit()) == NULL) + if ((de_ctx = DetectEngineCtxInit()) == NULL) goto end; de_ctx->flags |= DE_QUIET; @@ -2753,15 +2786,14 @@ static int DetectHttpClientBodyTest34(void) ->prev->ctx; DetectContentData *hcbd2 = (DetectContentData *)DetectBufferGetLastSigMatch(s, g_http_client_body_buffer_id)->ctx; - if (pd1->flags != (DETECT_PCRE_RELATIVE_NEXT) || - hcbd2->flags != DETECT_CONTENT_WITHIN || - memcmp(hcbd2->content, "two", hcbd2->content_len) != 0) { + if (pd1->flags != (DETECT_PCRE_RELATIVE_NEXT) || hcbd2->flags != DETECT_CONTENT_WITHIN || + memcmp(hcbd2->content, "two", hcbd2->content_len) != 0) { goto end; } result = 1; - end: +end: DetectEngineCtxFree(de_ctx); return result; } @@ -2771,7 +2803,7 @@ static int DetectHttpClientBodyTest35(void) DetectEngineCtx *de_ctx = NULL; int result = 0; - if ( (de_ctx = DetectEngineCtxInit()) == NULL) + if ((de_ctx = DetectEngineCtxInit()) == NULL) goto end; de_ctx->flags |= DE_QUIET; @@ -2807,15 +2839,14 @@ static int DetectHttpClientBodyTest35(void) ->prev->ctx; DetectPcreData *pd2 = (DetectPcreData *)DetectBufferGetLastSigMatch(s, g_http_client_body_buffer_id)->ctx; - if (pd2->flags != (DETECT_PCRE_RELATIVE) || - hcbd1->flags != DETECT_CONTENT_RELATIVE_NEXT || - memcmp(hcbd1->content, "two", hcbd1->content_len) != 0) { + if (pd2->flags != (DETECT_PCRE_RELATIVE) || hcbd1->flags != DETECT_CONTENT_RELATIVE_NEXT || + memcmp(hcbd1->content, "two", hcbd1->content_len) != 0) { goto end; } result = 1; - end: +end: DetectEngineCtxFree(de_ctx); return result; } @@ -2825,7 +2856,7 @@ static int DetectHttpClientBodyTest36(void) DetectEngineCtx *de_ctx = NULL; int result = 0; - if ( (de_ctx = DetectEngineCtxInit()) == NULL) + if ((de_ctx = DetectEngineCtxInit()) == NULL) goto end; de_ctx->flags |= DE_QUIET; @@ -2862,15 +2893,14 @@ static int DetectHttpClientBodyTest36(void) ->prev->ctx; DetectContentData *hcbd2 = (DetectContentData *)DetectBufferGetLastSigMatch(s, g_http_client_body_buffer_id)->ctx; - if (pd1->flags != (DETECT_PCRE_RELATIVE_NEXT) || - hcbd2->flags != DETECT_CONTENT_DISTANCE || - memcmp(hcbd2->content, "two", hcbd2->content_len) != 0) { + if (pd1->flags != (DETECT_PCRE_RELATIVE_NEXT) || hcbd2->flags != DETECT_CONTENT_DISTANCE || + memcmp(hcbd2->content, "two", hcbd2->content_len) != 0) { goto end; } result = 1; - end: +end: DetectEngineCtxFree(de_ctx); return result; } @@ -2881,10 +2911,9 @@ static int DetectHttpClientBodyIsdataatParseTest(void) FAIL_IF_NULL(de_ctx); de_ctx->flags |= DE_QUIET; - Signature *s = DetectEngineAppendSig(de_ctx, - "alert tcp any any -> any any (" - "content:\"one\"; http_client_body; " - "isdataat:!4,relative; sid:1;)"); + Signature *s = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any (" + "content:\"one\"; http_client_body; " + "isdataat:!4,relative; sid:1;)"); FAIL_IF_NULL(s); SigMatch *sm = DetectBufferGetLastSigMatch(s, g_http_client_body_buffer_id); @@ -2935,72 +2964,40 @@ void DetectHttpClientBodyRegisterTests(void) UtRegisterTest("DetectHttpClientBodyTest35", DetectHttpClientBodyTest35); UtRegisterTest("DetectHttpClientBodyTest36", DetectHttpClientBodyTest36); - UtRegisterTest("DetectHttpClientBodyIsdataatParseTest", - DetectHttpClientBodyIsdataatParseTest); - - UtRegisterTest("DetectEngineHttpClientBodyTest01", - DetectEngineHttpClientBodyTest01); - UtRegisterTest("DetectEngineHttpClientBodyTest02", - DetectEngineHttpClientBodyTest02); - UtRegisterTest("DetectEngineHttpClientBodyTest03", - DetectEngineHttpClientBodyTest03); - UtRegisterTest("DetectEngineHttpClientBodyTest04", - DetectEngineHttpClientBodyTest04); - UtRegisterTest("DetectEngineHttpClientBodyTest05", - DetectEngineHttpClientBodyTest05); - UtRegisterTest("DetectEngineHttpClientBodyTest06", - DetectEngineHttpClientBodyTest06); - UtRegisterTest("DetectEngineHttpClientBodyTest07", - DetectEngineHttpClientBodyTest07); - UtRegisterTest("DetectEngineHttpClientBodyTest08", - DetectEngineHttpClientBodyTest08); - UtRegisterTest("DetectEngineHttpClientBodyTest09", - DetectEngineHttpClientBodyTest09); - UtRegisterTest("DetectEngineHttpClientBodyTest10", - DetectEngineHttpClientBodyTest10); - UtRegisterTest("DetectEngineHttpClientBodyTest11", - DetectEngineHttpClientBodyTest11); - UtRegisterTest("DetectEngineHttpClientBodyTest12", - DetectEngineHttpClientBodyTest12); - UtRegisterTest("DetectEngineHttpClientBodyTest13", - DetectEngineHttpClientBodyTest13); - UtRegisterTest("DetectEngineHttpClientBodyTest14", - DetectEngineHttpClientBodyTest14); - UtRegisterTest("DetectEngineHttpClientBodyTest15", - DetectEngineHttpClientBodyTest15); - UtRegisterTest("DetectEngineHttpClientBodyTest16", - DetectEngineHttpClientBodyTest16); - UtRegisterTest("DetectEngineHttpClientBodyTest17", - DetectEngineHttpClientBodyTest17); - UtRegisterTest("DetectEngineHttpClientBodyTest18", - DetectEngineHttpClientBodyTest18); - UtRegisterTest("DetectEngineHttpClientBodyTest19", - DetectEngineHttpClientBodyTest19); - UtRegisterTest("DetectEngineHttpClientBodyTest20", - DetectEngineHttpClientBodyTest20); - UtRegisterTest("DetectEngineHttpClientBodyTest21", - DetectEngineHttpClientBodyTest21); - UtRegisterTest("DetectEngineHttpClientBodyTest22", - DetectEngineHttpClientBodyTest22); - UtRegisterTest("DetectEngineHttpClientBodyTest23", - DetectEngineHttpClientBodyTest23); - UtRegisterTest("DetectEngineHttpClientBodyTest24", - DetectEngineHttpClientBodyTest24); - UtRegisterTest("DetectEngineHttpClientBodyTest25", - DetectEngineHttpClientBodyTest25); - UtRegisterTest("DetectEngineHttpClientBodyTest26", - DetectEngineHttpClientBodyTest26); - UtRegisterTest("DetectEngineHttpClientBodyTest27", - DetectEngineHttpClientBodyTest27); - UtRegisterTest("DetectEngineHttpClientBodyTest28", - DetectEngineHttpClientBodyTest28); - UtRegisterTest("DetectEngineHttpClientBodyTest29", - DetectEngineHttpClientBodyTest29); - - UtRegisterTest("DetectEngineHttpClientBodyTest30", - DetectEngineHttpClientBodyTest30); - UtRegisterTest("DetectEngineHttpClientBodyTest31", - DetectEngineHttpClientBodyTest31); + UtRegisterTest("DetectHttpClientBodyIsdataatParseTest", DetectHttpClientBodyIsdataatParseTest); + + UtRegisterTest("DetectEngineHttpClientBodyTest01", DetectEngineHttpClientBodyTest01); + UtRegisterTest("DetectEngineHttpClientBodyTest02", DetectEngineHttpClientBodyTest02); + UtRegisterTest("DetectEngineHttpClientBodyTest03", DetectEngineHttpClientBodyTest03); + UtRegisterTest("DetectEngineHttpClientBodyTest04", DetectEngineHttpClientBodyTest04); + UtRegisterTest("DetectEngineHttpClientBodyTest05", DetectEngineHttpClientBodyTest05); + UtRegisterTest("DetectEngineHttpClientBodyTest06", DetectEngineHttpClientBodyTest06); + UtRegisterTest("DetectEngineHttpClientBodyTest07", DetectEngineHttpClientBodyTest07); + UtRegisterTest("DetectEngineHttpClientBodyTest08", DetectEngineHttpClientBodyTest08); + UtRegisterTest("DetectEngineHttpClientBodyTest09", DetectEngineHttpClientBodyTest09); + UtRegisterTest("DetectEngineHttpClientBodyTest10", DetectEngineHttpClientBodyTest10); + UtRegisterTest("DetectEngineHttpClientBodyTest11", DetectEngineHttpClientBodyTest11); + UtRegisterTest("DetectEngineHttpClientBodyTest12", DetectEngineHttpClientBodyTest12); + UtRegisterTest("DetectEngineHttpClientBodyTest13", DetectEngineHttpClientBodyTest13); + UtRegisterTest("DetectEngineHttpClientBodyTest14", DetectEngineHttpClientBodyTest14); + UtRegisterTest("DetectEngineHttpClientBodyTest15", DetectEngineHttpClientBodyTest15); + UtRegisterTest("DetectEngineHttpClientBodyTest16", DetectEngineHttpClientBodyTest16); + UtRegisterTest("DetectEngineHttpClientBodyTest17", DetectEngineHttpClientBodyTest17); + UtRegisterTest("DetectEngineHttpClientBodyTest18", DetectEngineHttpClientBodyTest18); + UtRegisterTest("DetectEngineHttpClientBodyTest19", DetectEngineHttpClientBodyTest19); + UtRegisterTest("DetectEngineHttpClientBodyTest20", DetectEngineHttpClientBodyTest20); + UtRegisterTest("DetectEngineHttpClientBodyTest21", DetectEngineHttpClientBodyTest21); + UtRegisterTest("DetectEngineHttpClientBodyTest22", DetectEngineHttpClientBodyTest22); + UtRegisterTest("DetectEngineHttpClientBodyTest23", DetectEngineHttpClientBodyTest23); + UtRegisterTest("DetectEngineHttpClientBodyTest24", DetectEngineHttpClientBodyTest24); + UtRegisterTest("DetectEngineHttpClientBodyTest25", DetectEngineHttpClientBodyTest25); + UtRegisterTest("DetectEngineHttpClientBodyTest26", DetectEngineHttpClientBodyTest26); + UtRegisterTest("DetectEngineHttpClientBodyTest27", DetectEngineHttpClientBodyTest27); + UtRegisterTest("DetectEngineHttpClientBodyTest28", DetectEngineHttpClientBodyTest28); + UtRegisterTest("DetectEngineHttpClientBodyTest29", DetectEngineHttpClientBodyTest29); + + UtRegisterTest("DetectEngineHttpClientBodyTest30", DetectEngineHttpClientBodyTest30); + UtRegisterTest("DetectEngineHttpClientBodyTest31", DetectEngineHttpClientBodyTest31); } #endif diff --git a/src/tests/detect-http-cookie.c b/src/tests/detect-http-cookie.c index 466722ee9ee5..18309a55398e 100644 --- a/src/tests/detect-http-cookie.c +++ b/src/tests/detect-http-cookie.c @@ -21,7 +21,6 @@ * @{ */ - /** \file * * \author Anoop Saldanha @@ -60,10 +59,9 @@ static int DetectEngineHttpCookieTest01(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Cookie: CONNECT\r\n" - "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Cookie: CONNECT\r\n" + "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -81,7 +79,7 @@ static int DetectEngineHttpCookieTest01(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -92,10 +90,10 @@ static int DetectEngineHttpCookieTest01(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; " - "content:\"CONNECT\"; http_cookie; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http header test\"; " + "content:\"CONNECT\"; http_cookie; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -152,10 +150,9 @@ static int DetectEngineHttpCookieTest02(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "CONNECT /index.html HTTP/1.0\r\n" - "Cookie: CONNECT\r\n" - "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "CONNECT /index.html HTTP/1.0\r\n" + "Cookie: CONNECT\r\n" + "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -173,7 +170,7 @@ static int DetectEngineHttpCookieTest02(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -184,10 +181,10 @@ static int DetectEngineHttpCookieTest02(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; " - "content:\"CO\"; depth:4; http_cookie; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http header test\"; " + "content:\"CO\"; depth:4; http_cookie; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -244,10 +241,9 @@ static int DetectEngineHttpCookieTest03(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "CONNECT /index.html HTTP/1.0\r\n" - "Cookie: CONNECT\r\n" - "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "CONNECT /index.html HTTP/1.0\r\n" + "Cookie: CONNECT\r\n" + "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -265,7 +261,7 @@ static int DetectEngineHttpCookieTest03(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -276,10 +272,10 @@ static int DetectEngineHttpCookieTest03(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; " - "content:!\"ECT\"; depth:4; http_cookie; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http header test\"; " + "content:!\"ECT\"; depth:4; http_cookie; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -336,10 +332,9 @@ static int DetectEngineHttpCookieTest04(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "CONNECT /index.html HTTP/1.0\r\n" - "Cookie: CONNECT\r\n" - "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "CONNECT /index.html HTTP/1.0\r\n" + "Cookie: CONNECT\r\n" + "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -357,7 +352,7 @@ static int DetectEngineHttpCookieTest04(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -368,10 +363,10 @@ static int DetectEngineHttpCookieTest04(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; " - "content:\"ECT\"; depth:4; http_cookie; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http header test\"; " + "content:\"ECT\"; depth:4; http_cookie; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -428,10 +423,9 @@ static int DetectEngineHttpCookieTest05(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "CONNECT /index.html HTTP/1.0\r\n" - "Cookie: CONNECT\r\n" - "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "CONNECT /index.html HTTP/1.0\r\n" + "Cookie: CONNECT\r\n" + "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -449,7 +443,7 @@ static int DetectEngineHttpCookieTest05(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -460,10 +454,10 @@ static int DetectEngineHttpCookieTest05(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; " - "content:!\"CON\"; depth:4; http_cookie; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http header test\"; " + "content:!\"CON\"; depth:4; http_cookie; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -520,10 +514,9 @@ static int DetectEngineHttpCookieTest06(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "CONNECT /index.html HTTP/1.0\r\n" - "Cookie: CONNECT\r\n" - "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "CONNECT /index.html HTTP/1.0\r\n" + "Cookie: CONNECT\r\n" + "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -541,7 +534,7 @@ static int DetectEngineHttpCookieTest06(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -552,10 +545,10 @@ static int DetectEngineHttpCookieTest06(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; " - "content:\"ECT\"; offset:3; http_cookie; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http header test\"; " + "content:\"ECT\"; offset:3; http_cookie; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -612,10 +605,9 @@ static int DetectEngineHttpCookieTest07(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "CONNECT /index.html HTTP/1.0\r\n" - "Cookie: CONNECT\r\n" - "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "CONNECT /index.html HTTP/1.0\r\n" + "Cookie: CONNECT\r\n" + "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -633,7 +625,7 @@ static int DetectEngineHttpCookieTest07(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -644,10 +636,10 @@ static int DetectEngineHttpCookieTest07(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; " - "content:!\"CO\"; offset:3; http_cookie; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http header test\"; " + "content:!\"CO\"; offset:3; http_cookie; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -704,10 +696,9 @@ static int DetectEngineHttpCookieTest08(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "CONNECT /index.html HTTP/1.0\r\n" - "Cookie: CONNECT\r\n" - "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "CONNECT /index.html HTTP/1.0\r\n" + "Cookie: CONNECT\r\n" + "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -725,7 +716,7 @@ static int DetectEngineHttpCookieTest08(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -736,10 +727,10 @@ static int DetectEngineHttpCookieTest08(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; " - "content:!\"ECT\"; offset:3; http_cookie; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http header test\"; " + "content:!\"ECT\"; offset:3; http_cookie; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -796,10 +787,9 @@ static int DetectEngineHttpCookieTest09(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "CONNECT /index.html HTTP/1.0\r\n" - "Cookie: CONNECT\r\n" - "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "CONNECT /index.html HTTP/1.0\r\n" + "Cookie: CONNECT\r\n" + "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -817,7 +807,7 @@ static int DetectEngineHttpCookieTest09(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -828,10 +818,10 @@ static int DetectEngineHttpCookieTest09(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; " - "content:\"CON\"; offset:3; http_cookie; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http header test\"; " + "content:\"CON\"; offset:3; http_cookie; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -888,10 +878,9 @@ static int DetectEngineHttpCookieTest10(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "CONNECT /index.html HTTP/1.0\r\n" - "Cookie: CONNECT\r\n" - "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "CONNECT /index.html HTTP/1.0\r\n" + "Cookie: CONNECT\r\n" + "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -909,7 +898,7 @@ static int DetectEngineHttpCookieTest10(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -920,11 +909,11 @@ static int DetectEngineHttpCookieTest10(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; " - "content:\"CO\"; http_cookie; " - "content:\"EC\"; within:4; http_cookie; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http header test\"; " + "content:\"CO\"; http_cookie; " + "content:\"EC\"; within:4; http_cookie; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -981,10 +970,9 @@ static int DetectEngineHttpCookieTest11(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "CONNECT /index.html HTTP/1.0\r\n" - "Cookie: CONNECT\r\n" - "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "CONNECT /index.html HTTP/1.0\r\n" + "Cookie: CONNECT\r\n" + "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -1002,7 +990,7 @@ static int DetectEngineHttpCookieTest11(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1013,11 +1001,11 @@ static int DetectEngineHttpCookieTest11(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; " - "content:\"CO\"; http_cookie; " - "content:!\"EC\"; within:3; http_cookie; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http header test\"; " + "content:\"CO\"; http_cookie; " + "content:!\"EC\"; within:3; http_cookie; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -1074,10 +1062,9 @@ static int DetectEngineHttpCookieTest12(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "CONNECT /index.html HTTP/1.0\r\n" - "Cookie: CONNECT\r\n" - "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "CONNECT /index.html HTTP/1.0\r\n" + "Cookie: CONNECT\r\n" + "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -1095,7 +1082,7 @@ static int DetectEngineHttpCookieTest12(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1106,11 +1093,11 @@ static int DetectEngineHttpCookieTest12(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; " - "content:\"CO\"; http_cookie; " - "content:\"EC\"; within:3; http_cookie; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http header test\"; " + "content:\"CO\"; http_cookie; " + "content:\"EC\"; within:3; http_cookie; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -1167,10 +1154,9 @@ static int DetectEngineHttpCookieTest13(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "CONNECT /index.html HTTP/1.0\r\n" - "Cookie: CONNECT\r\n" - "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "CONNECT /index.html HTTP/1.0\r\n" + "Cookie: CONNECT\r\n" + "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -1188,7 +1174,7 @@ static int DetectEngineHttpCookieTest13(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1199,11 +1185,11 @@ static int DetectEngineHttpCookieTest13(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; " - "content:\"CO\"; http_cookie; " - "content:!\"EC\"; within:4; http_cookie; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http header test\"; " + "content:\"CO\"; http_cookie; " + "content:!\"EC\"; within:4; http_cookie; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -1260,10 +1246,9 @@ static int DetectEngineHttpCookieTest14(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "CONNECT /index.html HTTP/1.0\r\n" - "Cookie: CONNECT\r\n" - "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "CONNECT /index.html HTTP/1.0\r\n" + "Cookie: CONNECT\r\n" + "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -1281,7 +1266,7 @@ static int DetectEngineHttpCookieTest14(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1292,11 +1277,11 @@ static int DetectEngineHttpCookieTest14(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; " - "content:\"CO\"; http_cookie; " - "content:\"EC\"; distance:2; http_cookie; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http header test\"; " + "content:\"CO\"; http_cookie; " + "content:\"EC\"; distance:2; http_cookie; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -1353,10 +1338,9 @@ static int DetectEngineHttpCookieTest15(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "CONNECT /index.html HTTP/1.0\r\n" - "Cookie: CONNECT\r\n" - "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "CONNECT /index.html HTTP/1.0\r\n" + "Cookie: CONNECT\r\n" + "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -1374,7 +1358,7 @@ static int DetectEngineHttpCookieTest15(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1385,11 +1369,11 @@ static int DetectEngineHttpCookieTest15(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; " - "content:\"CO\"; http_cookie; " - "content:!\"EC\"; distance:3; http_cookie; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http header test\"; " + "content:\"CO\"; http_cookie; " + "content:!\"EC\"; distance:3; http_cookie; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -1446,10 +1430,9 @@ static int DetectEngineHttpCookieTest16(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "CONNECT /index.html HTTP/1.0\r\n" - "Cookie: CONNECT\r\n" - "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "CONNECT /index.html HTTP/1.0\r\n" + "Cookie: CONNECT\r\n" + "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -1467,7 +1450,7 @@ static int DetectEngineHttpCookieTest16(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1478,11 +1461,11 @@ static int DetectEngineHttpCookieTest16(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; " - "content:\"CO\"; http_cookie; " - "content:\"EC\"; distance:3; http_cookie; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http header test\"; " + "content:\"CO\"; http_cookie; " + "content:\"EC\"; distance:3; http_cookie; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -1539,10 +1522,9 @@ static int DetectEngineHttpCookieTest17(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "CONNECT /index.html HTTP/1.0\r\n" - "Cookie: CONNECT\r\n" - "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "CONNECT /index.html HTTP/1.0\r\n" + "Cookie: CONNECT\r\n" + "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -1560,7 +1542,7 @@ static int DetectEngineHttpCookieTest17(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1571,11 +1553,11 @@ static int DetectEngineHttpCookieTest17(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; " - "content:\"CO\"; http_cookie; " - "content:!\"EC\"; distance:2; http_cookie; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http header test\"; " + "content:\"CO\"; http_cookie; " + "content:!\"EC\"; distance:2; http_cookie; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -1628,12 +1610,12 @@ static int DetectHttpCookieTest01(void) DetectEngineCtx *de_ctx = NULL; int result = 0; - if ( (de_ctx = DetectEngineCtxInit()) == NULL) + if ((de_ctx = DetectEngineCtxInit()) == NULL) goto end; de_ctx->flags |= DE_QUIET; de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"Testing http_cookie\"; http_cookie;sid:1;)"); + "(msg:\"Testing http_cookie\"; http_cookie;sid:1;)"); if (de_ctx->sig_list == NULL) result = 1; @@ -1652,13 +1634,13 @@ static int DetectHttpCookieTest02(void) DetectEngineCtx *de_ctx = NULL; int result = 0; - if ( (de_ctx = DetectEngineCtxInit()) == NULL) + if ((de_ctx = DetectEngineCtxInit()) == NULL) goto end; de_ctx->flags |= DE_QUIET; de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"Testing http_cookie\"; content:\"me\"; " - "http_cookie:woo; sid:1;)"); + "(msg:\"Testing http_cookie\"; content:\"me\"; " + "http_cookie:woo; sid:1;)"); if (de_ctx->sig_list == NULL) result = 1; @@ -1698,7 +1680,7 @@ static int DetectHttpCookieSigTest01(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1710,20 +1692,19 @@ static int DetectHttpCookieSigTest01(void) de_ctx->flags |= DE_QUIET; - s = de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any (msg:" - "\"HTTP cookie\"; content:\"me\"; " - "http_cookie; sid:1;)"); + s = de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any (msg:" + "\"HTTP cookie\"; content:\"me\"; " + "http_cookie; sid:1;)"); if (s == NULL) { goto end; } - s->next = SigInit(de_ctx,"alert http any any -> any any (msg:\"HTTP " - "cookie\"; content:\"go\"; http_cookie; sid:2;)"); + s->next = SigInit(de_ctx, "alert http any any -> any any (msg:\"HTTP " + "cookie\"; content:\"go\"; http_cookie; sid:2;)"); if (s->next == NULL) { goto end; } - SigGroupBuild(de_ctx); DetectEngineThreadCtxInit(&th_v, (void *)de_ctx, (void *)&det_ctx); @@ -1801,7 +1782,7 @@ static int DetectHttpCookieSigTest02(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1813,9 +1794,9 @@ static int DetectHttpCookieSigTest02(void) de_ctx->flags |= DE_QUIET; - s = de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any (msg:" - "\"HTTP cookie\"; content:\"me\"; " - "http_cookie; sid:1;)"); + s = de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any (msg:" + "\"HTTP cookie\"; content:\"me\"; " + "http_cookie; sid:1;)"); if (s == NULL) { goto end; } @@ -1867,7 +1848,7 @@ static int DetectHttpCookieSigTest03(void) int result = 0; Flow f; uint8_t httpbuf1[] = "POST / HTTP/1.0\r\nUser-Agent: Mozilla/1.0\r\n" - "Cookie: dummy\r\n\r\n"; + "Cookie: dummy\r\n\r\n"; uint32_t httplen1 = sizeof(httpbuf1) - 1; /* minus the \0 */ TcpSession ssn; Packet *p = NULL; @@ -1891,7 +1872,7 @@ static int DetectHttpCookieSigTest03(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1903,9 +1884,9 @@ static int DetectHttpCookieSigTest03(void) de_ctx->flags |= DE_QUIET; - s = de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any (msg:" - "\"HTTP cookie\"; content:\"boo\"; " - "http_cookie; sid:1;)"); + s = de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any (msg:" + "\"HTTP cookie\"; content:\"boo\"; " + "http_cookie; sid:1;)"); if (s == NULL) { goto end; } @@ -1957,7 +1938,7 @@ static int DetectHttpCookieSigTest04(void) int result = 0; Flow f; uint8_t httpbuf1[] = "POST / HTTP/1.0\r\nUser-Agent: Mozilla/1.0\r\n" - "Cookie: dummy\r\n\r\n"; + "Cookie: dummy\r\n\r\n"; uint32_t httplen1 = sizeof(httpbuf1) - 1; /* minus the \0 */ TcpSession ssn; Packet *p = NULL; @@ -1982,7 +1963,7 @@ static int DetectHttpCookieSigTest04(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1994,9 +1975,9 @@ static int DetectHttpCookieSigTest04(void) de_ctx->flags |= DE_QUIET; - s = de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any (msg:" - "\"HTTP cookie\"; content:!\"boo\"; " - "http_cookie; sid:1;)"); + s = de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any (msg:" + "\"HTTP cookie\"; content:!\"boo\"; " + "http_cookie; sid:1;)"); if (s == NULL) { goto end; } @@ -2048,7 +2029,7 @@ static int DetectHttpCookieSigTest05(void) int result = 0; Flow f; uint8_t httpbuf1[] = "POST / HTTP/1.0\r\nUser-Agent: Mozilla/1.0\r\n" - "Cookie: DuMmY\r\n\r\n"; + "Cookie: DuMmY\r\n\r\n"; uint32_t httplen1 = sizeof(httpbuf1) - 1; /* minus the \0 */ TcpSession ssn; Packet *p = NULL; @@ -2073,7 +2054,7 @@ static int DetectHttpCookieSigTest05(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -2085,9 +2066,9 @@ static int DetectHttpCookieSigTest05(void) de_ctx->flags |= DE_QUIET; - s = de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any (msg:" - "\"HTTP cookie\"; content:\"dummy\"; nocase; " - "http_cookie; sid:1;)"); + s = de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any (msg:" + "\"HTTP cookie\"; content:\"dummy\"; nocase; " + "http_cookie; sid:1;)"); if (s == NULL) { goto end; } @@ -2139,7 +2120,7 @@ static int DetectHttpCookieSigTest06(void) int result = 0; Flow f; uint8_t httpbuf1[] = "POST / HTTP/1.0\r\nUser-Agent: Mozilla/1.0\r\n" - "Cookie: DuMmY\r\n\r\n"; + "Cookie: DuMmY\r\n\r\n"; uint32_t httplen1 = sizeof(httpbuf1) - 1; /* minus the \0 */ TcpSession ssn; Packet *p = NULL; @@ -2164,7 +2145,7 @@ static int DetectHttpCookieSigTest06(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -2176,9 +2157,9 @@ static int DetectHttpCookieSigTest06(void) de_ctx->flags |= DE_QUIET; - s = de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any (msg:" - "\"HTTP cookie\"; content:\"dummy\"; " - "http_cookie; nocase; sid:1;)"); + s = de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any (msg:" + "\"HTTP cookie\"; content:\"dummy\"; " + "http_cookie; nocase; sid:1;)"); if (s == NULL) { printf("sig parse failed: "); goto end; @@ -2230,7 +2211,7 @@ static int DetectHttpCookieSigTest07(void) int result = 0; Flow f; uint8_t httpbuf1[] = "POST / HTTP/1.0\r\nUser-Agent: Mozilla/1.0\r\n" - "Cookie: dummy\r\n\r\n"; + "Cookie: dummy\r\n\r\n"; uint32_t httplen1 = sizeof(httpbuf1) - 1; /* minus the \0 */ TcpSession ssn; Packet *p = NULL; @@ -2254,7 +2235,7 @@ static int DetectHttpCookieSigTest07(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -2266,9 +2247,9 @@ static int DetectHttpCookieSigTest07(void) de_ctx->flags |= DE_QUIET; - s = de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any (msg:" - "\"HTTP cookie\"; content:!\"dummy\"; " - "http_cookie; sid:1;)"); + s = de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any (msg:" + "\"HTTP cookie\"; content:!\"dummy\"; " + "http_cookie; sid:1;)"); if (s == NULL) { goto end; } @@ -2322,16 +2303,14 @@ static int DetectHttpCookieSigTest08(void) int result = 0; Flow f; - uint8_t httpbuf_request[] = - "GET / HTTP/1.1\r\n" - "User-Agent: Mozilla/1.0\r\n" - "\r\n"; + uint8_t httpbuf_request[] = "GET / HTTP/1.1\r\n" + "User-Agent: Mozilla/1.0\r\n" + "\r\n"; uint32_t httpbuf_request_len = sizeof(httpbuf_request) - 1; /* minus the \0 */ - uint8_t httpbuf_response[] = - "HTTP/1.1 200 OK\r\n" - "Set-Cookie: response_user_agent\r\n" - "\r\n"; + uint8_t httpbuf_response[] = "HTTP/1.1 200 OK\r\n" + "Set-Cookie: response_user_agent\r\n" + "\r\n"; uint32_t httpbuf_response_len = sizeof(httpbuf_response) - 1; /* minus the \0 */ TcpSession ssn; @@ -2373,9 +2352,9 @@ static int DetectHttpCookieSigTest08(void) de_ctx->flags |= DE_QUIET; - s = de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(flow:to_client; content:\"response_user_agent\"; " - "http_cookie; sid:1;)"); + s = de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(flow:to_client; content:\"response_user_agent\"; " + "http_cookie; sid:1;)"); if (s == NULL) { goto end; } @@ -2445,17 +2424,15 @@ static int DetectHttpCookieSigTest09(void) int result = 0; Flow f; - uint8_t httpbuf_request[] = - "GET / HTTP/1.1\r\n" - "Cookie: request_user_agent\r\n" - "User-Agent: Mozilla/1.0\r\n" - "\r\n"; + uint8_t httpbuf_request[] = "GET / HTTP/1.1\r\n" + "Cookie: request_user_agent\r\n" + "User-Agent: Mozilla/1.0\r\n" + "\r\n"; uint32_t httpbuf_request_len = sizeof(httpbuf_request) - 1; /* minus the \0 */ - uint8_t httpbuf_response[] = - "HTTP/1.1 200 OK\r\n" - "Set-Cookie: response_user_agent\r\n" - "\r\n"; + uint8_t httpbuf_response[] = "HTTP/1.1 200 OK\r\n" + "Set-Cookie: response_user_agent\r\n" + "\r\n"; uint32_t httpbuf_response_len = sizeof(httpbuf_response) - 1; /* minus the \0 */ TcpSession ssn; @@ -2497,15 +2474,16 @@ static int DetectHttpCookieSigTest09(void) de_ctx->flags |= DE_QUIET; - s = de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(flow:to_server; content:\"request_user_agent\"; " - "http_cookie; sid:1;)"); + s = de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(flow:to_server; content:\"request_user_agent\"; " + "http_cookie; sid:1;)"); if (s == NULL) { goto end; } - s = de_ctx->sig_list->next = SigInit(de_ctx,"alert http any any -> any any " - "(flow:to_client; content:\"response_user_agent\"; " - "http_cookie; sid:2;)"); + s = de_ctx->sig_list->next = + SigInit(de_ctx, "alert http any any -> any any " + "(flow:to_client; content:\"response_user_agent\"; " + "http_cookie; sid:2;)"); if (s == NULL) { goto end; } @@ -2570,7 +2548,7 @@ static int DetectHttpCookieSigTest09(void) /** * \brief Register the UNITTESTS for the http_cookie keyword */ -void DetectHttpCookieRegisterTests (void) +void DetectHttpCookieRegisterTests(void) { UtRegisterTest("DetectHttpCookieTest01", DetectHttpCookieTest01); UtRegisterTest("DetectHttpCookieTest02", DetectHttpCookieTest02); @@ -2583,40 +2561,23 @@ void DetectHttpCookieRegisterTests (void) UtRegisterTest("DetectHttpCookieSigTest07", DetectHttpCookieSigTest07); UtRegisterTest("DetectHttpCookieSigTest08", DetectHttpCookieSigTest08); UtRegisterTest("DetectHttpCookieSigTest09", DetectHttpCookieSigTest09); - UtRegisterTest("DetectEngineHttpCookieTest01", - DetectEngineHttpCookieTest01); - UtRegisterTest("DetectEngineHttpCookieTest02", - DetectEngineHttpCookieTest02); - UtRegisterTest("DetectEngineHttpCookieTest03", - DetectEngineHttpCookieTest03); - UtRegisterTest("DetectEngineHttpCookieTest04", - DetectEngineHttpCookieTest04); - UtRegisterTest("DetectEngineHttpCookieTest05", - DetectEngineHttpCookieTest05); - UtRegisterTest("DetectEngineHttpCookieTest06", - DetectEngineHttpCookieTest06); - UtRegisterTest("DetectEngineHttpCookieTest07", - DetectEngineHttpCookieTest07); - UtRegisterTest("DetectEngineHttpCookieTest08", - DetectEngineHttpCookieTest08); - UtRegisterTest("DetectEngineHttpCookieTest09", - DetectEngineHttpCookieTest09); - UtRegisterTest("DetectEngineHttpCookieTest10", - DetectEngineHttpCookieTest10); - UtRegisterTest("DetectEngineHttpCookieTest11", - DetectEngineHttpCookieTest11); - UtRegisterTest("DetectEngineHttpCookieTest12", - DetectEngineHttpCookieTest12); - UtRegisterTest("DetectEngineHttpCookieTest13", - DetectEngineHttpCookieTest13); - UtRegisterTest("DetectEngineHttpCookieTest14", - DetectEngineHttpCookieTest14); - UtRegisterTest("DetectEngineHttpCookieTest15", - DetectEngineHttpCookieTest15); - UtRegisterTest("DetectEngineHttpCookieTest16", - DetectEngineHttpCookieTest16); - UtRegisterTest("DetectEngineHttpCookieTest17", - DetectEngineHttpCookieTest17); + UtRegisterTest("DetectEngineHttpCookieTest01", DetectEngineHttpCookieTest01); + UtRegisterTest("DetectEngineHttpCookieTest02", DetectEngineHttpCookieTest02); + UtRegisterTest("DetectEngineHttpCookieTest03", DetectEngineHttpCookieTest03); + UtRegisterTest("DetectEngineHttpCookieTest04", DetectEngineHttpCookieTest04); + UtRegisterTest("DetectEngineHttpCookieTest05", DetectEngineHttpCookieTest05); + UtRegisterTest("DetectEngineHttpCookieTest06", DetectEngineHttpCookieTest06); + UtRegisterTest("DetectEngineHttpCookieTest07", DetectEngineHttpCookieTest07); + UtRegisterTest("DetectEngineHttpCookieTest08", DetectEngineHttpCookieTest08); + UtRegisterTest("DetectEngineHttpCookieTest09", DetectEngineHttpCookieTest09); + UtRegisterTest("DetectEngineHttpCookieTest10", DetectEngineHttpCookieTest10); + UtRegisterTest("DetectEngineHttpCookieTest11", DetectEngineHttpCookieTest11); + UtRegisterTest("DetectEngineHttpCookieTest12", DetectEngineHttpCookieTest12); + UtRegisterTest("DetectEngineHttpCookieTest13", DetectEngineHttpCookieTest13); + UtRegisterTest("DetectEngineHttpCookieTest14", DetectEngineHttpCookieTest14); + UtRegisterTest("DetectEngineHttpCookieTest15", DetectEngineHttpCookieTest15); + UtRegisterTest("DetectEngineHttpCookieTest16", DetectEngineHttpCookieTest16); + UtRegisterTest("DetectEngineHttpCookieTest17", DetectEngineHttpCookieTest17); } /** * @} diff --git a/src/tests/detect-http-header.c b/src/tests/detect-http-header.c index 776d89113861..6867bd7b7654 100644 --- a/src/tests/detect-http-header.c +++ b/src/tests/detect-http-header.c @@ -21,7 +21,6 @@ * @{ */ - /** * \file * @@ -56,15 +55,26 @@ */ static int DetectHttpHeaderParserTest01(void) { - FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (content:\"abc\"; http_header; sid:1;)", true)); - FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (content:\"abc\"; nocase; http_header; sid:1;)", true)); - FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (content:\"abc\"; endswith; http_header; sid:1;)", true)); - FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (content:\"abc\"; startswith; http_header; sid:1;)", true)); - FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (content:\"abc\"; startswith; endswith; http_header; sid:1;)", true)); - - FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (content:\"abc\"; rawbytes; http_header; sid:1;)", false)); + FAIL_IF_NOT(UTHParseSignature( + "alert http any any -> any any (content:\"abc\"; http_header; sid:1;)", true)); + FAIL_IF_NOT(UTHParseSignature( + "alert http any any -> any any (content:\"abc\"; nocase; http_header; sid:1;)", true)); + FAIL_IF_NOT(UTHParseSignature( + "alert http any any -> any any (content:\"abc\"; endswith; http_header; sid:1;)", + true)); + FAIL_IF_NOT(UTHParseSignature( + "alert http any any -> any any (content:\"abc\"; startswith; http_header; sid:1;)", + true)); + FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (content:\"abc\"; startswith; " + "endswith; http_header; sid:1;)", + true)); + + FAIL_IF_NOT(UTHParseSignature( + "alert http any any -> any any (content:\"abc\"; rawbytes; http_header; sid:1;)", + false)); FAIL_IF_NOT(UTHParseSignature("alert tcp any any -> any any (http_header; sid:1;)", false)); - FAIL_IF_NOT(UTHParseSignature("alert tls any any -> any any (content:\"abc\"; http_header; sid:1;)", false)); + FAIL_IF_NOT(UTHParseSignature( + "alert tls any any -> any any (content:\"abc\"; http_header; sid:1;)", false)); PASS; } @@ -73,16 +83,28 @@ static int DetectHttpHeaderParserTest01(void) */ static int DetectHttpHeaderParserTest02(void) { - FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (http.header; content:\"abc\"; sid:1;)", true)); - FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (http.header; content:\"abc\"; nocase; sid:1;)", true)); - FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (http.header; content:\"abc\"; endswith; sid:1;)", true)); - FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (http.header; content:\"abc\"; startswith; sid:1;)", true)); - FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (http.header; content:\"abc\"; startswith; endswith; sid:1;)", true)); - FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (http.header; bsize:10; sid:1;)", true)); - - FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (http.header; content:\"abc\"; rawbytes; sid:1;)", false)); + FAIL_IF_NOT(UTHParseSignature( + "alert http any any -> any any (http.header; content:\"abc\"; sid:1;)", true)); + FAIL_IF_NOT(UTHParseSignature( + "alert http any any -> any any (http.header; content:\"abc\"; nocase; sid:1;)", true)); + FAIL_IF_NOT(UTHParseSignature( + "alert http any any -> any any (http.header; content:\"abc\"; endswith; sid:1;)", + true)); + FAIL_IF_NOT(UTHParseSignature( + "alert http any any -> any any (http.header; content:\"abc\"; startswith; sid:1;)", + true)); + FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (http.header; content:\"abc\"; " + "startswith; endswith; sid:1;)", + true)); + FAIL_IF_NOT(UTHParseSignature( + "alert http any any -> any any (http.header; bsize:10; sid:1;)", true)); + + FAIL_IF_NOT(UTHParseSignature( + "alert http any any -> any any (http.header; content:\"abc\"; rawbytes; sid:1;)", + false)); FAIL_IF_NOT(UTHParseSignature("alert tcp any any -> any any (http.header; sid:1;)", false)); - FAIL_IF_NOT(UTHParseSignature("alert tls any any -> any any (http.header; content:\"abc\"; sid:1;)", false)); + FAIL_IF_NOT(UTHParseSignature( + "alert tls any any -> any any (http.header; content:\"abc\"; sid:1;)", false)); PASS; } @@ -99,14 +121,14 @@ static int DetectHttpHeaderTest06(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 26\r\n" - "\r\n" - "This is dummy message body\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 26\r\n" + "\r\n" + "This is dummy message body\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -124,7 +146,7 @@ static int DetectHttpHeaderTest06(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -135,10 +157,10 @@ static int DetectHttpHeaderTest06(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; " - "content:\"Content-Type: text/html\"; http_header; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http header test\"; " + "content:\"Content-Type: text/html\"; http_header; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -193,15 +215,14 @@ static int DetectHttpHeaderTest07(void) ThreadVars th_v; DetectEngineThreadCtx *det_ctx = NULL; Flow f; - uint8_t http1_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozi"; - uint8_t http2_buf[] = - "lla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\nContent-Type: text/html\r\n" - "Content-Length: 67\r\n" - "\r\n" - "This is dummy message body1"; + uint8_t http1_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozi"; + uint8_t http2_buf[] = "lla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 " + "Firefox/3.5.7\r\nContent-Type: text/html\r\n" + "Content-Length: 67\r\n" + "\r\n" + "This is dummy message body1"; uint32_t http1_len = sizeof(http1_buf) - 1; uint32_t http2_len = sizeof(http2_buf) - 1; @@ -224,11 +245,11 @@ static int DetectHttpHeaderTest07(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOSERVER; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -237,10 +258,10 @@ static int DetectHttpHeaderTest07(void) FAIL_IF_NULL(de_ctx); de_ctx->flags |= DE_QUIET; - Signature *s = DetectEngineAppendSig(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; " - "content:\"Mozilla\"; http_header; " - "sid:1;)"); + Signature *s = DetectEngineAppendSig(de_ctx, "alert http any any -> any any " + "(msg:\"http header test\"; " + "content:\"Mozilla\"; http_header; " + "sid:1;)"); FAIL_IF_NULL(s); SigGroupBuild(de_ctx); @@ -256,7 +277,7 @@ static int DetectHttpHeaderTest07(void) /* do detect */ SigMatchSignatures(&th_v, de_ctx, det_ctx, p1); - FAIL_IF( (PacketAlertCheck(p1, 1))); + FAIL_IF((PacketAlertCheck(p1, 1))); r = AppLayerParserParse( NULL, alp_tctx, &f, ALPROTO_HTTP1, STREAM_TOSERVER, http2_buf, http2_len); @@ -291,14 +312,13 @@ static int DetectHttpHeaderTest08(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http1_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n"; - uint8_t http2_buf[] = - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 67\r\n" - "\r\n"; + uint8_t http1_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n"; + uint8_t http2_buf[] = "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 67\r\n" + "\r\n"; uint32_t http1_len = sizeof(http1_buf) - 1; uint32_t http2_len = sizeof(http2_buf) - 1; int result = 0; @@ -318,11 +338,11 @@ static int DetectHttpHeaderTest08(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOSERVER; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -333,10 +353,10 @@ static int DetectHttpHeaderTest08(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; " - "content:\"Gecko/20091221 Firefox/3.5.7\"; http_header; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http header test\"; " + "content:\"Gecko/20091221 Firefox/3.5.7\"; http_header; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -410,15 +430,14 @@ static int DetectHttpHeaderTest09(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http1_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n"; - uint8_t http2_buf[] = - "Content-Type: text/html\r\n" - "Content-Length: 67\r\n" - "\r\n" - "This is dummy body\r\n"; + uint8_t http1_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n"; + uint8_t http2_buf[] = "Content-Type: text/html\r\n" + "Content-Length: 67\r\n" + "\r\n" + "This is dummy body\r\n"; uint32_t http1_len = sizeof(http1_buf) - 1; uint32_t http2_len = sizeof(http2_buf) - 1; int result = 0; @@ -438,11 +457,11 @@ static int DetectHttpHeaderTest09(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOSERVER; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -454,10 +473,10 @@ static int DetectHttpHeaderTest09(void) de_ctx->flags |= DE_QUIET; de_ctx->mpm_matcher = mpm_default_matcher; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; " - "content:\"Firefox/3.5.7|0D 0A|Content\"; http_header; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http header test\"; " + "content:\"Firefox/3.5.7|0D 0A|Content\"; http_header; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -531,15 +550,14 @@ static int DetectHttpHeaderTest10(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http1_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n"; - uint8_t http2_buf[] = - "Content-Type: text/html\r\n" - "Content-Length: 67\r\n" - "\r\n" - "This is dummy body"; + uint8_t http1_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n"; + uint8_t http2_buf[] = "Content-Type: text/html\r\n" + "Content-Length: 67\r\n" + "\r\n" + "This is dummy body"; uint32_t http1_len = sizeof(http1_buf) - 1; uint32_t http2_len = sizeof(http2_buf) - 1; int result = 0; @@ -559,11 +577,11 @@ static int DetectHttpHeaderTest10(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOSERVER; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -574,10 +592,11 @@ static int DetectHttpHeaderTest10(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; " - "content:\"firefox/3.5.7|0D 0A|content\"; nocase; http_header;" - "sid:1;)"); + de_ctx->sig_list = + SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http header test\"; " + "content:\"firefox/3.5.7|0D 0A|content\"; nocase; http_header;" + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -650,14 +669,14 @@ static int DetectHttpHeaderTest11(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 26\r\n" - "\r\n" - "This is dummy message body\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 26\r\n" + "\r\n" + "This is dummy message body\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -675,7 +694,7 @@ static int DetectHttpHeaderTest11(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -686,10 +705,10 @@ static int DetectHttpHeaderTest11(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; " - "content:!\"lalalalala\"; http_header; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http header test\"; " + "content:!\"lalalalala\"; http_header; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -745,14 +764,14 @@ static int DetectHttpHeaderTest12(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 26\r\n" - "\r\n" - "This is dummy message body\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 26\r\n" + "\r\n" + "This is dummy message body\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -770,7 +789,7 @@ static int DetectHttpHeaderTest12(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -781,10 +800,10 @@ static int DetectHttpHeaderTest12(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; " - "content:!\"User-Agent: Mozilla/5.0 \"; http_header; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http header test\"; " + "content:!\"User-Agent: Mozilla/5.0 \"; http_header; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -840,14 +859,14 @@ static int DetectHttpHeaderTest13(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 100\r\n" - "\r\n" - "longbufferabcdefghijklmnopqrstuvwxyz0123456789bufferend\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 100\r\n" + "\r\n" + "longbufferabcdefghijklmnopqrstuvwxyz0123456789bufferend\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -866,7 +885,7 @@ static int DetectHttpHeaderTest13(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -877,10 +896,11 @@ static int DetectHttpHeaderTest13(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; " - "content:\"Host: www.openinfosecfoundation.org\"; http_header; " - "sid:1;)"); + de_ctx->sig_list = + SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http header test\"; " + "content:\"Host: www.openinfosecfoundation.org\"; http_header; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -933,11 +953,10 @@ static int DetectHttpHeaderTest28(void) DetectEngineCtx *de_ctx = NULL; DetectEngineThreadCtx *det_ctx = NULL; Flow f; - uint8_t http_buf[] = - "POST http://xxx.intranet.local:8000/xxx HTTP/1.1\r\n" - "User-Agent: Mozilla/4.0 (Windows XP 5.1) Java/1.6.0_29\r\n" - "Host: xxx.intranet.local:8000\r\n" - "\r\n"; + uint8_t http_buf[] = "POST http://xxx.intranet.local:8000/xxx HTTP/1.1\r\n" + "User-Agent: Mozilla/4.0 (Windows XP 5.1) Java/1.6.0_29\r\n" + "Host: xxx.intranet.local:8000\r\n" + "\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -955,7 +974,7 @@ static int DetectHttpHeaderTest28(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -966,9 +985,9 @@ static int DetectHttpHeaderTest28(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(app-layer-event:http.host_header_ambiguous; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(app-layer-event:http.host_header_ambiguous; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -992,7 +1011,7 @@ static int DetectHttpHeaderTest28(void) } result = 1; - end: +end: if (alp_tctx != NULL) AppLayerParserThreadCtxFree(alp_tctx); if (de_ctx != NULL) @@ -1014,11 +1033,10 @@ static int DetectHttpHeaderTest29(void) DetectEngineCtx *de_ctx = NULL; DetectEngineThreadCtx *det_ctx = NULL; Flow f; - uint8_t http_buf[] = - "POST http://xxx.intranet.local:8001/xxx HTTP/1.1\r\n" - "User-Agent: Mozilla/4.0 (Windows XP 5.1) Java/1.6.0_29\r\n" - "Host: xxx.intranet.local:8000\r\n" - "\r\n"; + uint8_t http_buf[] = "POST http://xxx.intranet.local:8001/xxx HTTP/1.1\r\n" + "User-Agent: Mozilla/4.0 (Windows XP 5.1) Java/1.6.0_29\r\n" + "Host: xxx.intranet.local:8000\r\n" + "\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -1036,7 +1054,7 @@ static int DetectHttpHeaderTest29(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1047,9 +1065,9 @@ static int DetectHttpHeaderTest29(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(app-layer-event:http.host_header_ambiguous; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(app-layer-event:http.host_header_ambiguous; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -1073,7 +1091,7 @@ static int DetectHttpHeaderTest29(void) } result = 1; - end: +end: if (alp_tctx != NULL) AppLayerParserThreadCtxFree(alp_tctx); if (de_ctx != NULL) @@ -1095,11 +1113,10 @@ static int DetectHttpHeaderTest30(void) DetectEngineCtx *de_ctx = NULL; DetectEngineThreadCtx *det_ctx = NULL; Flow f; - uint8_t http_buf[] = - "POST http://xxx.intranet.local:8000/xxx HTTP/1.1\r\n" - "User-Agent: Mozilla/4.0 (Windows XP 5.1) Java/1.6.0_29\r\n" - "Host: xyz.intranet.local:8000\r\n" - "\r\n"; + uint8_t http_buf[] = "POST http://xxx.intranet.local:8000/xxx HTTP/1.1\r\n" + "User-Agent: Mozilla/4.0 (Windows XP 5.1) Java/1.6.0_29\r\n" + "Host: xyz.intranet.local:8000\r\n" + "\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -1117,7 +1134,7 @@ static int DetectHttpHeaderTest30(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1128,9 +1145,9 @@ static int DetectHttpHeaderTest30(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(app-layer-event:http.host_header_ambiguous; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(app-layer-event:http.host_header_ambiguous; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -1154,7 +1171,7 @@ static int DetectHttpHeaderTest30(void) } result = 1; - end: +end: if (alp_tctx != NULL) AppLayerParserThreadCtxFree(alp_tctx); if (de_ctx != NULL) @@ -1172,11 +1189,10 @@ static int DetectHttpHeaderIsdataatParseTest(void) FAIL_IF_NULL(de_ctx); de_ctx->flags |= DE_QUIET; - Signature *s = DetectEngineAppendSig(de_ctx, - "alert tcp any any -> any any (" - "flow:to_server; " - "content:\"one\"; http_header; " - "isdataat:!4,relative; sid:1;)"); + Signature *s = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any (" + "flow:to_server; " + "content:\"one\"; http_header; " + "isdataat:!4,relative; sid:1;)"); FAIL_IF_NULL(s); SigMatch *sm = DetectBufferGetLastSigMatch(s, g_http_header_buffer_id); @@ -1205,9 +1221,8 @@ static int DetectEngineHttpHeaderTest01(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -1225,7 +1240,7 @@ static int DetectEngineHttpHeaderTest01(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1236,10 +1251,10 @@ static int DetectEngineHttpHeaderTest01(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; " - "content:\"one\"; http_header; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http header test\"; " + "content:\"one\"; http_header; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -1295,9 +1310,8 @@ static int DetectEngineHttpHeaderTest02(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -1315,7 +1329,7 @@ static int DetectEngineHttpHeaderTest02(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1326,10 +1340,10 @@ static int DetectEngineHttpHeaderTest02(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; " - "content:\"one\"; depth:15; http_header; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http header test\"; " + "content:\"one\"; depth:15; http_header; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -1385,9 +1399,8 @@ static int DetectEngineHttpHeaderTest03(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -1405,7 +1418,7 @@ static int DetectEngineHttpHeaderTest03(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1416,10 +1429,10 @@ static int DetectEngineHttpHeaderTest03(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; " - "content:!\"one\"; depth:5; http_header; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http header test\"; " + "content:!\"one\"; depth:5; http_header; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -1475,9 +1488,8 @@ static int DetectEngineHttpHeaderTest04(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -1495,7 +1507,7 @@ static int DetectEngineHttpHeaderTest04(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1506,10 +1518,10 @@ static int DetectEngineHttpHeaderTest04(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; " - "content:\"one\"; depth:5; http_header; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http header test\"; " + "content:\"one\"; depth:5; http_header; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -1565,9 +1577,8 @@ static int DetectEngineHttpHeaderTest05(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -1585,7 +1596,7 @@ static int DetectEngineHttpHeaderTest05(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1596,10 +1607,10 @@ static int DetectEngineHttpHeaderTest05(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; " - "content:!\"one\"; depth:15; http_header; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http header test\"; " + "content:!\"one\"; depth:15; http_header; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -1655,9 +1666,8 @@ static int DetectEngineHttpHeaderTest06(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -1675,7 +1685,7 @@ static int DetectEngineHttpHeaderTest06(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1686,10 +1696,10 @@ static int DetectEngineHttpHeaderTest06(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; " - "content:\"one\"; offset:10; http_header; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http header test\"; " + "content:\"one\"; offset:10; http_header; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -1745,9 +1755,8 @@ static int DetectEngineHttpHeaderTest07(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -1765,7 +1774,7 @@ static int DetectEngineHttpHeaderTest07(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1776,10 +1785,10 @@ static int DetectEngineHttpHeaderTest07(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; " - "content:!\"one\"; offset:15; http_header; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http header test\"; " + "content:!\"one\"; offset:15; http_header; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -1835,9 +1844,8 @@ static int DetectEngineHttpHeaderTest08(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -1855,7 +1863,7 @@ static int DetectEngineHttpHeaderTest08(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1866,10 +1874,10 @@ static int DetectEngineHttpHeaderTest08(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; " - "content:\"one\"; offset:15; http_header; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http header test\"; " + "content:\"one\"; offset:15; http_header; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -1925,9 +1933,8 @@ static int DetectEngineHttpHeaderTest09(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -1945,7 +1952,7 @@ static int DetectEngineHttpHeaderTest09(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1956,10 +1963,10 @@ static int DetectEngineHttpHeaderTest09(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; " - "content:!\"one\"; offset:10; http_header; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http header test\"; " + "content:!\"one\"; offset:10; http_header; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -2015,9 +2022,8 @@ static int DetectEngineHttpHeaderTest10(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -2035,7 +2041,7 @@ static int DetectEngineHttpHeaderTest10(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -2046,10 +2052,11 @@ static int DetectEngineHttpHeaderTest10(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; " - "content:\"one\"; http_header; content:\"three\"; http_header; within:10; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, + "alert http any any -> any any " + "(msg:\"http header test\"; " + "content:\"one\"; http_header; content:\"three\"; http_header; within:10; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -2105,9 +2112,8 @@ static int DetectEngineHttpHeaderTest11(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -2125,7 +2131,7 @@ static int DetectEngineHttpHeaderTest11(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -2136,10 +2142,11 @@ static int DetectEngineHttpHeaderTest11(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; " - "content:\"one\"; http_header; content:!\"three\"; http_header; within:5; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, + "alert http any any -> any any " + "(msg:\"http header test\"; " + "content:\"one\"; http_header; content:!\"three\"; http_header; within:5; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -2195,9 +2202,8 @@ static int DetectEngineHttpHeaderTest12(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -2215,7 +2221,7 @@ static int DetectEngineHttpHeaderTest12(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -2226,10 +2232,11 @@ static int DetectEngineHttpHeaderTest12(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; " - "content:\"one\"; http_header; content:!\"three\"; http_header; within:10; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, + "alert http any any -> any any " + "(msg:\"http header test\"; " + "content:\"one\"; http_header; content:!\"three\"; http_header; within:10; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -2285,9 +2292,8 @@ static int DetectEngineHttpHeaderTest13(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -2305,7 +2311,7 @@ static int DetectEngineHttpHeaderTest13(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -2316,10 +2322,11 @@ static int DetectEngineHttpHeaderTest13(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; " - "content:\"one\"; http_header; content:\"three\"; http_header; within:5; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, + "alert http any any -> any any " + "(msg:\"http header test\"; " + "content:\"one\"; http_header; content:\"three\"; http_header; within:5; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -2375,9 +2382,8 @@ static int DetectEngineHttpHeaderTest14(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -2395,7 +2401,7 @@ static int DetectEngineHttpHeaderTest14(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -2406,10 +2412,11 @@ static int DetectEngineHttpHeaderTest14(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; " - "content:\"one\"; http_header; content:\"five\"; http_header; distance:7; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, + "alert http any any -> any any " + "(msg:\"http header test\"; " + "content:\"one\"; http_header; content:\"five\"; http_header; distance:7; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -2465,9 +2472,8 @@ static int DetectEngineHttpHeaderTest15(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -2485,7 +2491,7 @@ static int DetectEngineHttpHeaderTest15(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -2496,10 +2502,11 @@ static int DetectEngineHttpHeaderTest15(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; " - "content:\"one\"; http_header; content:!\"five\"; http_header; distance:15; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, + "alert http any any -> any any " + "(msg:\"http header test\"; " + "content:\"one\"; http_header; content:!\"five\"; http_header; distance:15; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -2555,9 +2562,8 @@ static int DetectEngineHttpHeaderTest16(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -2575,7 +2581,7 @@ static int DetectEngineHttpHeaderTest16(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -2586,10 +2592,11 @@ static int DetectEngineHttpHeaderTest16(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; " - "content:\"one\"; http_header; content:!\"five\"; http_header; distance:7; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, + "alert http any any -> any any " + "(msg:\"http header test\"; " + "content:\"one\"; http_header; content:!\"five\"; http_header; distance:7; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -2645,9 +2652,8 @@ static int DetectEngineHttpHeaderTest17(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -2665,7 +2671,7 @@ static int DetectEngineHttpHeaderTest17(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -2676,10 +2682,11 @@ static int DetectEngineHttpHeaderTest17(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; " - "content:\"one\"; http_header; content:\"five\"; http_header; distance:15; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, + "alert http any any -> any any " + "(msg:\"http header test\"; " + "content:\"one\"; http_header; content:\"five\"; http_header; distance:15; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -2732,12 +2739,10 @@ static int DetectEngineHttpHeaderTest20(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http1_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: This_is_dummy_body1"; - uint8_t http2_buf[] = - "This_is_dummy_message_body2\r\n" - "\r\n"; + uint8_t http1_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: This_is_dummy_body1"; + uint8_t http2_buf[] = "This_is_dummy_message_body2\r\n" + "\r\n"; uint32_t http1_len = sizeof(http1_buf) - 1; uint32_t http2_len = sizeof(http2_buf) - 1; int result = 0; @@ -2758,11 +2763,11 @@ static int DetectEngineHttpHeaderTest20(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOSERVER; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -2773,11 +2778,11 @@ static int DetectEngineHttpHeaderTest20(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http client body test\"; " - "pcre:/body1/H; " - "content:!\"dummy\"; http_header; within:7; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http client body test\"; " + "pcre:/body1/H; " + "content:!\"dummy\"; http_header; within:7; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -2848,12 +2853,10 @@ static int DetectEngineHttpHeaderTest21(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http1_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: This_is_dummy_body1"; - uint8_t http2_buf[] = - "This_is_dummy_message_body2\r\n" - "\r\n"; + uint8_t http1_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: This_is_dummy_body1"; + uint8_t http2_buf[] = "This_is_dummy_message_body2\r\n" + "\r\n"; uint32_t http1_len = sizeof(http1_buf) - 1; uint32_t http2_len = sizeof(http2_buf) - 1; int result = 0; @@ -2874,11 +2877,11 @@ static int DetectEngineHttpHeaderTest21(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOSERVER; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -2889,11 +2892,11 @@ static int DetectEngineHttpHeaderTest21(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http client body test\"; " - "pcre:/body1/H; " - "content:!\"dummy\"; within:7; http_header; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http client body test\"; " + "pcre:/body1/H; " + "content:!\"dummy\"; within:7; http_header; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -2964,12 +2967,10 @@ static int DetectEngineHttpHeaderTest22(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http1_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: This_is_dummy_body1"; - uint8_t http2_buf[] = - "This_is_dummy_message_body2\r\n" - "\r\n"; + uint8_t http1_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: This_is_dummy_body1"; + uint8_t http2_buf[] = "This_is_dummy_message_body2\r\n" + "\r\n"; uint32_t http1_len = sizeof(http1_buf) - 1; uint32_t http2_len = sizeof(http2_buf) - 1; int result = 0; @@ -2990,11 +2991,11 @@ static int DetectEngineHttpHeaderTest22(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOSERVER; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -3005,11 +3006,11 @@ static int DetectEngineHttpHeaderTest22(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http client body test\"; " - "pcre:/body1/H; " - "content:!\"dummy\"; distance:3; http_header; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http client body test\"; " + "pcre:/body1/H; " + "content:!\"dummy\"; distance:3; http_header; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -3080,12 +3081,10 @@ static int DetectEngineHttpHeaderTest23(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http1_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: This_is_dummy_body1"; - uint8_t http2_buf[] = - "This_is_dummy_message_body2\r\n" - "\r\n"; + uint8_t http1_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: This_is_dummy_body1"; + uint8_t http2_buf[] = "This_is_dummy_message_body2\r\n" + "\r\n"; uint32_t http1_len = sizeof(http1_buf) - 1; uint32_t http2_len = sizeof(http2_buf) - 1; int result = 0; @@ -3106,11 +3105,11 @@ static int DetectEngineHttpHeaderTest23(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOSERVER; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -3121,11 +3120,11 @@ static int DetectEngineHttpHeaderTest23(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http client body test\"; " - "pcre:/body1/H; " - "content:!\"dummy\"; distance:13; http_header; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http client body test\"; " + "pcre:/body1/H; " + "content:!\"dummy\"; distance:13; http_header; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -3196,12 +3195,10 @@ static int DetectEngineHttpHeaderTest24(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http1_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: This_is_dummy_body1"; - uint8_t http2_buf[] = - "This_is_dummy_message_body2\r\n" - "\r\n"; + uint8_t http1_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: This_is_dummy_body1"; + uint8_t http2_buf[] = "This_is_dummy_message_body2\r\n" + "\r\n"; uint32_t http1_len = sizeof(http1_buf) - 1; uint32_t http2_len = sizeof(http2_buf) - 1; int result = 0; @@ -3222,11 +3219,11 @@ static int DetectEngineHttpHeaderTest24(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOSERVER; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -3237,11 +3234,11 @@ static int DetectEngineHttpHeaderTest24(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http client body test\"; " - "pcre:/body1/H; " - "content:\"dummy\"; within:15; http_header; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http client body test\"; " + "pcre:/body1/H; " + "content:\"dummy\"; within:15; http_header; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -3312,12 +3309,10 @@ static int DetectEngineHttpHeaderTest25(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http1_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: This_is_dummy_body1"; - uint8_t http2_buf[] = - "This_is_dummy_message_body2\r\n" - "\r\n"; + uint8_t http1_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: This_is_dummy_body1"; + uint8_t http2_buf[] = "This_is_dummy_message_body2\r\n" + "\r\n"; uint32_t http1_len = sizeof(http1_buf) - 1; uint32_t http2_len = sizeof(http2_buf) - 1; int result = 0; @@ -3338,11 +3333,11 @@ static int DetectEngineHttpHeaderTest25(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOSERVER; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -3353,11 +3348,11 @@ static int DetectEngineHttpHeaderTest25(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http client body test\"; " - "pcre:/body1/H; " - "content:\"dummy\"; within:10; http_header; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http client body test\"; " + "pcre:/body1/H; " + "content:\"dummy\"; within:10; http_header; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -3428,12 +3423,10 @@ static int DetectEngineHttpHeaderTest26(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http1_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: This_is_dummy_body1"; - uint8_t http2_buf[] = - "This_is_dummy_message_body2\r\n" - "\r\n"; + uint8_t http1_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: This_is_dummy_body1"; + uint8_t http2_buf[] = "This_is_dummy_message_body2\r\n" + "\r\n"; uint32_t http1_len = sizeof(http1_buf) - 1; uint32_t http2_len = sizeof(http2_buf) - 1; int result = 0; @@ -3454,11 +3447,11 @@ static int DetectEngineHttpHeaderTest26(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOSERVER; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -3469,11 +3462,11 @@ static int DetectEngineHttpHeaderTest26(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http client body test\"; " - "pcre:/body1/H; " - "content:\"dummy\"; distance:8; http_header; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http client body test\"; " + "pcre:/body1/H; " + "content:\"dummy\"; distance:8; http_header; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -3544,12 +3537,10 @@ static int DetectEngineHttpHeaderTest27(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http1_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: This_is_dummy_body1"; - uint8_t http2_buf[] = - "This_is_dummy_message_body2\r\n" - "\r\n"; + uint8_t http1_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: This_is_dummy_body1"; + uint8_t http2_buf[] = "This_is_dummy_message_body2\r\n" + "\r\n"; uint32_t http1_len = sizeof(http1_buf) - 1; uint32_t http2_len = sizeof(http2_buf) - 1; int result = 0; @@ -3570,11 +3561,11 @@ static int DetectEngineHttpHeaderTest27(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOSERVER; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -3585,11 +3576,11 @@ static int DetectEngineHttpHeaderTest27(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http client body test\"; " - "pcre:/body1/H; " - "content:\"dummy\"; distance:14; http_header; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http client body test\"; " + "pcre:/body1/H; " + "content:\"dummy\"; distance:14; http_header; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -3660,18 +3651,17 @@ static int DetectEngineHttpHeaderTest28(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf1[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_buf1_len = sizeof(http_buf1) - 1; - uint8_t http_buf2[] = - "HTTP/1.0 200 ok\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 6\r\n" - "\r\n" - "abcdef"; + uint8_t http_buf2[] = "HTTP/1.0 200 ok\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 6\r\n" + "\r\n" + "abcdef"; uint32_t http_buf2_len = sizeof(http_buf2) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -3706,10 +3696,10 @@ static int DetectEngineHttpHeaderTest28(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; " - "content:\"Content-Length: 6\"; http_header; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http header test\"; " + "content:\"Content-Length: 6\"; http_header; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -3777,18 +3767,17 @@ static int DetectEngineHttpHeaderTest29(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf1[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_buf1_len = sizeof(http_buf1) - 1; - uint8_t http_buf2[] = - "HTTP/1.0 200 ok\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 6\r\n" - "\r\n" - "abcdef"; + uint8_t http_buf2[] = "HTTP/1.0 200 ok\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 6\r\n" + "\r\n" + "abcdef"; uint32_t http_buf2_len = sizeof(http_buf2) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -3823,10 +3812,10 @@ static int DetectEngineHttpHeaderTest29(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; " - "content:\"Content-Length: 7\"; http_header; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http header test\"; " + "content:\"Content-Length: 7\"; http_header; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -3927,19 +3916,18 @@ static int DetectEngineHttpHeaderTest30(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf1[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_buf1_len = sizeof(http_buf1) - 1; - uint8_t http_buf2[] = - "HTTP/1.0 200 ok\r\n" - "Set-Cookie: dummycookieset\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 6\r\n" - "\r\n" - "abcdef"; + uint8_t http_buf2[] = "HTTP/1.0 200 ok\r\n" + "Set-Cookie: dummycookieset\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 6\r\n" + "\r\n" + "abcdef"; uint32_t http_buf2_len = sizeof(http_buf2) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -3974,10 +3962,10 @@ static int DetectEngineHttpHeaderTest30(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; " - "content:\"dummycookieset\"; http_header; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http header test\"; " + "content:\"dummycookieset\"; http_header; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -4039,8 +4027,8 @@ static int DetectEngineHttpHeaderTest30(void) } /** \test reassembly bug where headers with names of length 6 were - * skipped - */ + * skipped + */ static int DetectEngineHttpHeaderTest31(void) { TcpSession ssn; @@ -4050,12 +4038,11 @@ static int DetectEngineHttpHeaderTest31(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http1_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Accept: blah\r\n" - "Cookie: blah\r\n" - "Crazy6: blah\r\n" - "SixZix: blah\r\n\r\n"; + uint8_t http1_buf[] = "GET /index.html HTTP/1.0\r\n" + "Accept: blah\r\n" + "Cookie: blah\r\n" + "Crazy6: blah\r\n" + "SixZix: blah\r\n\r\n"; uint32_t http1_len = sizeof(http1_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -4074,7 +4061,7 @@ static int DetectEngineHttpHeaderTest31(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -4085,12 +4072,12 @@ static int DetectEngineHttpHeaderTest31(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(content:\"Accept|3a|\"; http_header; " - "content:!\"Cookie|3a|\"; http_header; " - "content:\"Crazy6|3a|\"; http_header; " - "content:\"SixZix|3a|\"; http_header; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(content:\"Accept|3a|\"; http_header; " + "content:!\"Cookie|3a|\"; http_header; " + "content:\"Crazy6|3a|\"; http_header; " + "content:\"SixZix|3a|\"; http_header; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -4146,16 +4133,15 @@ static int DetectEngineHttpHeaderTest32(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http1_buf[] = - "GET /index.html HTTP/1.0\r\n" - "host: boom\r\n" - "Transfer-Encoding: chunked\r\n" - "\r\n" - "13\r\n" - "This is dummy body1\r\n" - "0\r\n" - "Dummy-Header: kaboom\r\n" - "\r\n"; + uint8_t http1_buf[] = "GET /index.html HTTP/1.0\r\n" + "host: boom\r\n" + "Transfer-Encoding: chunked\r\n" + "\r\n" + "13\r\n" + "This is dummy body1\r\n" + "0\r\n" + "Dummy-Header: kaboom\r\n" + "\r\n"; uint32_t http1_len = sizeof(http1_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -4174,7 +4160,7 @@ static int DetectEngineHttpHeaderTest32(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -4185,9 +4171,9 @@ static int DetectEngineHttpHeaderTest32(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(content:\"Dummy\"; http_header; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(content:\"Dummy\"; http_header; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -4244,17 +4230,15 @@ static int DetectEngineHttpHeaderTest33(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http1_buf[] = - "GET /index.html HTTP/1.0\r\n" - "host: boom\r\n" - "Transfer-Encoding: chunked\r\n" - "\r\n" - "13\r\n" - "This is dummy body1\r\n" - "0\r\n"; - uint8_t http2_buf[] = - "Dummy-Header: kaboom\r\n" - "\r\n"; + uint8_t http1_buf[] = "GET /index.html HTTP/1.0\r\n" + "host: boom\r\n" + "Transfer-Encoding: chunked\r\n" + "\r\n" + "13\r\n" + "This is dummy body1\r\n" + "0\r\n"; + uint8_t http2_buf[] = "Dummy-Header: kaboom\r\n" + "\r\n"; uint32_t http1_len = sizeof(http1_buf) - 1; uint32_t http2_len = sizeof(http2_buf) - 1; @@ -4276,11 +4260,11 @@ static int DetectEngineHttpHeaderTest33(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOSERVER; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -4289,9 +4273,9 @@ static int DetectEngineHttpHeaderTest33(void) FAIL_IF(de_ctx == NULL); de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(content:\"Dummy\"; http_header; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(content:\"Dummy\"; http_header; " + "sid:1;)"); FAIL_IF(de_ctx->sig_list == NULL); SigGroupBuild(de_ctx); @@ -4339,19 +4323,16 @@ static int DetectEngineHttpHeaderTest34(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http1_buf[] = - "GET /index.html HTTP/1.0\r\n" - "host: boom\r\n" - "Dummy-Header1: blah\r\n" - "Transfer-Encoding: chunked\r\n" - "\r\n"; - uint8_t http2_buf[] = - "13\r\n" - "This is dummy body1\r\n" - "0\r\n"; - uint8_t http3_buf[] = - "Dummy-Header2: kaboom\r\n" - "\r\n"; + uint8_t http1_buf[] = "GET /index.html HTTP/1.0\r\n" + "host: boom\r\n" + "Dummy-Header1: blah\r\n" + "Transfer-Encoding: chunked\r\n" + "\r\n"; + uint8_t http2_buf[] = "13\r\n" + "This is dummy body1\r\n" + "0\r\n"; + uint8_t http3_buf[] = "Dummy-Header2: kaboom\r\n" + "\r\n"; uint32_t http1_len = sizeof(http1_buf) - 1; uint32_t http2_len = sizeof(http2_buf) - 1; uint32_t http3_len = sizeof(http3_buf) - 1; @@ -4375,17 +4356,17 @@ static int DetectEngineHttpHeaderTest34(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p1->pcap_cnt = 1; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOSERVER; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->pcap_cnt = 2; p3->flow = &f; p3->flowflags |= FLOW_PKT_TOSERVER; p3->flowflags |= FLOW_PKT_ESTABLISHED; - p3->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p3->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p3->pcap_cnt = 3; f.alproto = ALPROTO_HTTP1; @@ -4395,9 +4376,10 @@ static int DetectEngineHttpHeaderTest34(void) FAIL_IF(de_ctx == NULL); de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(content:\"Dummy\"; http_header; content:\"Header2\"; http_header; within:8; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, + "alert http any any -> any any " + "(content:\"Dummy\"; http_header; content:\"Header2\"; http_header; within:8; " + "sid:1;)"); FAIL_IF(de_ctx->sig_list == NULL); SigGroupBuild(de_ctx); @@ -4452,19 +4434,16 @@ static int DetectEngineHttpHeaderTest35(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http1_buf[] = - "GET /index.html HTTP/1.0\r\n" - "host: boom\r\n" - "Dummy-Header1: blah\r\n" - "Transfer-Encoding: chunked\r\n" - "\r\n"; - uint8_t http2_buf[] = - "13\r\n" - "This is dummy body1\r\n" - "0\r\n"; - uint8_t http3_buf[] = - "Dummy-Header2: kaboom\r\n" - "\r\n"; + uint8_t http1_buf[] = "GET /index.html HTTP/1.0\r\n" + "host: boom\r\n" + "Dummy-Header1: blah\r\n" + "Transfer-Encoding: chunked\r\n" + "\r\n"; + uint8_t http2_buf[] = "13\r\n" + "This is dummy body1\r\n" + "0\r\n"; + uint8_t http3_buf[] = "Dummy-Header2: kaboom\r\n" + "\r\n"; uint32_t http1_len = sizeof(http1_buf) - 1; uint32_t http2_len = sizeof(http2_buf) - 1; uint32_t http3_len = sizeof(http3_buf) - 1; @@ -4488,17 +4467,17 @@ static int DetectEngineHttpHeaderTest35(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p1->pcap_cnt = 1; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOSERVER; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->pcap_cnt = 2; p3->flow = &f; p3->flowflags |= FLOW_PKT_TOSERVER; p3->flowflags |= FLOW_PKT_ESTABLISHED; - p3->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p3->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p3->pcap_cnt = 3; f.alproto = ALPROTO_HTTP1; @@ -4508,9 +4487,10 @@ static int DetectEngineHttpHeaderTest35(void) FAIL_IF(de_ctx == NULL); de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(content:\"Dummy\"; http_header; fast_pattern; content:\"Header2\"; http_header; within:8; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(content:\"Dummy\"; http_header; fast_pattern; " + "content:\"Header2\"; http_header; within:8; " + "sid:1;)"); FAIL_IF(de_ctx->sig_list == NULL); SigGroupBuild(de_ctx); @@ -4571,79 +4551,45 @@ void DetectHttpHeaderRegisterTests(void) UtRegisterTest("DetectHttpHeaderTest29", DetectHttpHeaderTest29); UtRegisterTest("DetectHttpHeaderTest30", DetectHttpHeaderTest30); - UtRegisterTest("DetectHttpHeaderIsdataatParseTest", - DetectHttpHeaderIsdataatParseTest); - - UtRegisterTest("DetectEngineHttpHeaderTest01", - DetectEngineHttpHeaderTest01); - UtRegisterTest("DetectEngineHttpHeaderTest02", - DetectEngineHttpHeaderTest02); - UtRegisterTest("DetectEngineHttpHeaderTest03", - DetectEngineHttpHeaderTest03); - UtRegisterTest("DetectEngineHttpHeaderTest04", - DetectEngineHttpHeaderTest04); - UtRegisterTest("DetectEngineHttpHeaderTest05", - DetectEngineHttpHeaderTest05); - UtRegisterTest("DetectEngineHttpHeaderTest06", - DetectEngineHttpHeaderTest06); - UtRegisterTest("DetectEngineHttpHeaderTest07", - DetectEngineHttpHeaderTest07); - UtRegisterTest("DetectEngineHttpHeaderTest08", - DetectEngineHttpHeaderTest08); - UtRegisterTest("DetectEngineHttpHeaderTest09", - DetectEngineHttpHeaderTest09); - UtRegisterTest("DetectEngineHttpHeaderTest10", - DetectEngineHttpHeaderTest10); - UtRegisterTest("DetectEngineHttpHeaderTest11", - DetectEngineHttpHeaderTest11); - UtRegisterTest("DetectEngineHttpHeaderTest12", - DetectEngineHttpHeaderTest12); - UtRegisterTest("DetectEngineHttpHeaderTest13", - DetectEngineHttpHeaderTest13); - UtRegisterTest("DetectEngineHttpHeaderTest14", - DetectEngineHttpHeaderTest14); - UtRegisterTest("DetectEngineHttpHeaderTest15", - DetectEngineHttpHeaderTest15); - UtRegisterTest("DetectEngineHttpHeaderTest16", - DetectEngineHttpHeaderTest16); - UtRegisterTest("DetectEngineHttpHeaderTest17", - DetectEngineHttpHeaderTest17); - UtRegisterTest("DetectEngineHttpHeaderTest20", - DetectEngineHttpHeaderTest20); - UtRegisterTest("DetectEngineHttpHeaderTest21", - DetectEngineHttpHeaderTest21); - UtRegisterTest("DetectEngineHttpHeaderTest22", - DetectEngineHttpHeaderTest22); - UtRegisterTest("DetectEngineHttpHeaderTest23", - DetectEngineHttpHeaderTest23); - UtRegisterTest("DetectEngineHttpHeaderTest24", - DetectEngineHttpHeaderTest24); - UtRegisterTest("DetectEngineHttpHeaderTest25", - DetectEngineHttpHeaderTest25); - UtRegisterTest("DetectEngineHttpHeaderTest26", - DetectEngineHttpHeaderTest26); - UtRegisterTest("DetectEngineHttpHeaderTest27", - DetectEngineHttpHeaderTest27); - UtRegisterTest("DetectEngineHttpHeaderTest28", - DetectEngineHttpHeaderTest28); - UtRegisterTest("DetectEngineHttpHeaderTest29", - DetectEngineHttpHeaderTest29); - UtRegisterTest("DetectEngineHttpHeaderTest30", - DetectEngineHttpHeaderTest30); - UtRegisterTest("DetectEngineHttpHeaderTest31", - DetectEngineHttpHeaderTest31); + UtRegisterTest("DetectHttpHeaderIsdataatParseTest", DetectHttpHeaderIsdataatParseTest); + + UtRegisterTest("DetectEngineHttpHeaderTest01", DetectEngineHttpHeaderTest01); + UtRegisterTest("DetectEngineHttpHeaderTest02", DetectEngineHttpHeaderTest02); + UtRegisterTest("DetectEngineHttpHeaderTest03", DetectEngineHttpHeaderTest03); + UtRegisterTest("DetectEngineHttpHeaderTest04", DetectEngineHttpHeaderTest04); + UtRegisterTest("DetectEngineHttpHeaderTest05", DetectEngineHttpHeaderTest05); + UtRegisterTest("DetectEngineHttpHeaderTest06", DetectEngineHttpHeaderTest06); + UtRegisterTest("DetectEngineHttpHeaderTest07", DetectEngineHttpHeaderTest07); + UtRegisterTest("DetectEngineHttpHeaderTest08", DetectEngineHttpHeaderTest08); + UtRegisterTest("DetectEngineHttpHeaderTest09", DetectEngineHttpHeaderTest09); + UtRegisterTest("DetectEngineHttpHeaderTest10", DetectEngineHttpHeaderTest10); + UtRegisterTest("DetectEngineHttpHeaderTest11", DetectEngineHttpHeaderTest11); + UtRegisterTest("DetectEngineHttpHeaderTest12", DetectEngineHttpHeaderTest12); + UtRegisterTest("DetectEngineHttpHeaderTest13", DetectEngineHttpHeaderTest13); + UtRegisterTest("DetectEngineHttpHeaderTest14", DetectEngineHttpHeaderTest14); + UtRegisterTest("DetectEngineHttpHeaderTest15", DetectEngineHttpHeaderTest15); + UtRegisterTest("DetectEngineHttpHeaderTest16", DetectEngineHttpHeaderTest16); + UtRegisterTest("DetectEngineHttpHeaderTest17", DetectEngineHttpHeaderTest17); + UtRegisterTest("DetectEngineHttpHeaderTest20", DetectEngineHttpHeaderTest20); + UtRegisterTest("DetectEngineHttpHeaderTest21", DetectEngineHttpHeaderTest21); + UtRegisterTest("DetectEngineHttpHeaderTest22", DetectEngineHttpHeaderTest22); + UtRegisterTest("DetectEngineHttpHeaderTest23", DetectEngineHttpHeaderTest23); + UtRegisterTest("DetectEngineHttpHeaderTest24", DetectEngineHttpHeaderTest24); + UtRegisterTest("DetectEngineHttpHeaderTest25", DetectEngineHttpHeaderTest25); + UtRegisterTest("DetectEngineHttpHeaderTest26", DetectEngineHttpHeaderTest26); + UtRegisterTest("DetectEngineHttpHeaderTest27", DetectEngineHttpHeaderTest27); + UtRegisterTest("DetectEngineHttpHeaderTest28", DetectEngineHttpHeaderTest28); + UtRegisterTest("DetectEngineHttpHeaderTest29", DetectEngineHttpHeaderTest29); + UtRegisterTest("DetectEngineHttpHeaderTest30", DetectEngineHttpHeaderTest30); + UtRegisterTest("DetectEngineHttpHeaderTest31", DetectEngineHttpHeaderTest31); #if 0 UtRegisterTest("DetectEngineHttpHeaderTest30", DetectEngineHttpHeaderTest30, 1); #endif - UtRegisterTest("DetectEngineHttpHeaderTest32", - DetectEngineHttpHeaderTest32); - UtRegisterTest("DetectEngineHttpHeaderTest33 -- Trailer", - DetectEngineHttpHeaderTest33); - UtRegisterTest("DetectEngineHttpHeaderTest34 -- Trailer", - DetectEngineHttpHeaderTest34); - UtRegisterTest("DetectEngineHttpHeaderTest35 -- Trailer", - DetectEngineHttpHeaderTest35); + UtRegisterTest("DetectEngineHttpHeaderTest32", DetectEngineHttpHeaderTest32); + UtRegisterTest("DetectEngineHttpHeaderTest33 -- Trailer", DetectEngineHttpHeaderTest33); + UtRegisterTest("DetectEngineHttpHeaderTest34 -- Trailer", DetectEngineHttpHeaderTest34); + UtRegisterTest("DetectEngineHttpHeaderTest35 -- Trailer", DetectEngineHttpHeaderTest35); } /** diff --git a/src/tests/detect-http-host.c b/src/tests/detect-http-host.c index 4fbdff9b69cc..5ad81791573f 100644 --- a/src/tests/detect-http-host.c +++ b/src/tests/detect-http-host.c @@ -21,7 +21,6 @@ * @{ */ - /** \file * * \author Anoop Saldanha @@ -58,10 +57,9 @@ static int DetectEngineHttpHHTest01(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: CONNECT\r\n" - "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: CONNECT\r\n" + "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -79,7 +77,7 @@ static int DetectEngineHttpHHTest01(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -90,10 +88,10 @@ static int DetectEngineHttpHHTest01(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http host header test\"; " - "content:\"connect\"; http_host; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http host header test\"; " + "content:\"connect\"; http_host; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -154,10 +152,9 @@ static int DetectEngineHttpHHTest02(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: CONNECT\r\n" - "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: CONNECT\r\n" + "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -175,7 +172,7 @@ static int DetectEngineHttpHHTest02(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -186,10 +183,10 @@ static int DetectEngineHttpHHTest02(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http host header test\"; " - "content:\"co\"; depth:4; http_host; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http host header test\"; " + "content:\"co\"; depth:4; http_host; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -250,10 +247,9 @@ static int DetectEngineHttpHHTest03(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: CONNECT\r\n" - "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: CONNECT\r\n" + "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -271,7 +267,7 @@ static int DetectEngineHttpHHTest03(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -282,10 +278,10 @@ static int DetectEngineHttpHHTest03(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http_host header test\"; " - "content:!\"ect\"; depth:4; http_host; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http_host header test\"; " + "content:!\"ect\"; depth:4; http_host; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -346,10 +342,9 @@ static int DetectEngineHttpHHTest04(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: CONNECT\r\n" - "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: CONNECT\r\n" + "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -367,7 +362,7 @@ static int DetectEngineHttpHHTest04(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -378,10 +373,10 @@ static int DetectEngineHttpHHTest04(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http host header test\"; " - "content:\"ect\"; depth:4; http_host; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http host header test\"; " + "content:\"ect\"; depth:4; http_host; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -442,10 +437,9 @@ static int DetectEngineHttpHHTest05(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: CONNECT\r\n" - "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: CONNECT\r\n" + "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -463,7 +457,7 @@ static int DetectEngineHttpHHTest05(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -474,10 +468,10 @@ static int DetectEngineHttpHHTest05(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http host header test\"; " - "content:!\"con\"; depth:4; http_host; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http host header test\"; " + "content:!\"con\"; depth:4; http_host; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -538,10 +532,9 @@ static int DetectEngineHttpHHTest06(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: CONNECT\r\n" - "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: CONNECT\r\n" + "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -559,7 +552,7 @@ static int DetectEngineHttpHHTest06(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -570,10 +563,10 @@ static int DetectEngineHttpHHTest06(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http host header test\"; " - "content:\"ect\"; offset:3; http_host; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http host header test\"; " + "content:\"ect\"; offset:3; http_host; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -634,10 +627,9 @@ static int DetectEngineHttpHHTest07(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: CONNECT\r\n" - "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: CONNECT\r\n" + "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -655,7 +647,7 @@ static int DetectEngineHttpHHTest07(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -666,10 +658,10 @@ static int DetectEngineHttpHHTest07(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http host header test\"; " - "content:!\"co\"; offset:3; http_host; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http host header test\"; " + "content:!\"co\"; offset:3; http_host; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -730,10 +722,9 @@ static int DetectEngineHttpHHTest08(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: CONNECT\r\n" - "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: CONNECT\r\n" + "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -751,7 +742,7 @@ static int DetectEngineHttpHHTest08(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -762,10 +753,10 @@ static int DetectEngineHttpHHTest08(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http host header test\"; " - "content:!\"ect\"; offset:3; http_host; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http host header test\"; " + "content:!\"ect\"; offset:3; http_host; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -826,10 +817,9 @@ static int DetectEngineHttpHHTest09(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: CONNECT\r\n" - "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: CONNECT\r\n" + "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -847,7 +837,7 @@ static int DetectEngineHttpHHTest09(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -858,10 +848,10 @@ static int DetectEngineHttpHHTest09(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http host header test\"; " - "content:\"con\"; offset:3; http_host; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http host header test\"; " + "content:\"con\"; offset:3; http_host; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -922,10 +912,9 @@ static int DetectEngineHttpHHTest10(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: CONNECT\r\n" - "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: CONNECT\r\n" + "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -943,7 +932,7 @@ static int DetectEngineHttpHHTest10(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -954,11 +943,11 @@ static int DetectEngineHttpHHTest10(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http_host header test\"; " - "content:\"co\"; http_host; " - "content:\"ec\"; within:4; http_host; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http_host header test\"; " + "content:\"co\"; http_host; " + "content:\"ec\"; within:4; http_host; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -1019,10 +1008,9 @@ static int DetectEngineHttpHHTest11(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: CONNECT\r\n" - "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: CONNECT\r\n" + "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -1040,7 +1028,7 @@ static int DetectEngineHttpHHTest11(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1051,11 +1039,11 @@ static int DetectEngineHttpHHTest11(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http_host header test\"; " - "content:\"co\"; http_host; " - "content:!\"ec\"; within:3; http_host; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http_host header test\"; " + "content:\"co\"; http_host; " + "content:!\"ec\"; within:3; http_host; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -1116,10 +1104,9 @@ static int DetectEngineHttpHHTest12(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: CONNECT\r\n" - "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: CONNECT\r\n" + "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -1137,7 +1124,7 @@ static int DetectEngineHttpHHTest12(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1148,11 +1135,11 @@ static int DetectEngineHttpHHTest12(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http_host header test\"; " - "content:\"co\"; http_host; " - "content:\"ec\"; within:3; http_host; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http_host header test\"; " + "content:\"co\"; http_host; " + "content:\"ec\"; within:3; http_host; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -1213,10 +1200,9 @@ static int DetectEngineHttpHHTest13(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: CONNECT\r\n" - "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: CONNECT\r\n" + "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -1234,7 +1220,7 @@ static int DetectEngineHttpHHTest13(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1245,11 +1231,11 @@ static int DetectEngineHttpHHTest13(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http_host header test\"; " - "content:\"co\"; http_host; " - "content:!\"ec\"; within:4; http_host; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http_host header test\"; " + "content:\"co\"; http_host; " + "content:!\"ec\"; within:4; http_host; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -1310,10 +1296,9 @@ static int DetectEngineHttpHHTest14(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: CONNECT\r\n" - "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: CONNECT\r\n" + "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -1331,7 +1316,7 @@ static int DetectEngineHttpHHTest14(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1342,11 +1327,11 @@ static int DetectEngineHttpHHTest14(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http_host header test\"; " - "content:\"co\"; http_host; " - "content:\"ec\"; distance:2; http_host; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http_host header test\"; " + "content:\"co\"; http_host; " + "content:\"ec\"; distance:2; http_host; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -1407,10 +1392,9 @@ static int DetectEngineHttpHHTest15(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: CONNECT\r\n" - "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: CONNECT\r\n" + "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -1428,7 +1412,7 @@ static int DetectEngineHttpHHTest15(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1439,11 +1423,11 @@ static int DetectEngineHttpHHTest15(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http_host header test\"; " - "content:\"co\"; http_host; " - "content:!\"ec\"; distance:3; http_host; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http_host header test\"; " + "content:\"co\"; http_host; " + "content:!\"ec\"; distance:3; http_host; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -1504,10 +1488,9 @@ static int DetectEngineHttpHHTest16(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: CONNECT\r\n" - "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: CONNECT\r\n" + "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -1525,7 +1508,7 @@ static int DetectEngineHttpHHTest16(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1536,11 +1519,11 @@ static int DetectEngineHttpHHTest16(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http_host header test\"; " - "content:\"co\"; http_host; " - "content:\"ec\"; distance:3; http_host; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http_host header test\"; " + "content:\"co\"; http_host; " + "content:\"ec\"; distance:3; http_host; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -1601,10 +1584,9 @@ static int DetectEngineHttpHHTest17(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: CONNECT\r\n" - "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: CONNECT\r\n" + "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -1622,7 +1604,7 @@ static int DetectEngineHttpHHTest17(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1633,11 +1615,11 @@ static int DetectEngineHttpHHTest17(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http_host header test\"; " - "content:\"co\"; http_host; " - "content:!\"ec\"; distance:2; http_host; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http_host header test\"; " + "content:\"co\"; http_host; " + "content:!\"ec\"; distance:2; http_host; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -1694,10 +1676,9 @@ static int DetectEngineHttpHHTest18(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.kaboom.com\r\n" - "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.kaboom.com\r\n" + "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -1715,7 +1696,7 @@ static int DetectEngineHttpHHTest18(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1726,10 +1707,10 @@ static int DetectEngineHttpHHTest18(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http_host header test\"; " - "content:\"kaboom\"; http_host; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http_host header test\"; " + "content:\"kaboom\"; http_host; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -1786,10 +1767,9 @@ static int DetectEngineHttpHHTest19(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.kaboom.com:8080\r\n" - "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.kaboom.com:8080\r\n" + "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -1807,7 +1787,7 @@ static int DetectEngineHttpHHTest19(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1818,10 +1798,10 @@ static int DetectEngineHttpHHTest19(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http_host header test\"; " - "content:\"kaboom\"; http_host; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http_host header test\"; " + "content:\"kaboom\"; http_host; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -1878,10 +1858,9 @@ static int DetectEngineHttpHHTest20(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.kaboom.com:8080\r\n" - "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.kaboom.com:8080\r\n" + "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -1899,7 +1878,7 @@ static int DetectEngineHttpHHTest20(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1910,10 +1889,10 @@ static int DetectEngineHttpHHTest20(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http_host header test\"; " - "content:\"8080\"; http_host; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http_host header test\"; " + "content:\"8080\"; http_host; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -1970,9 +1949,8 @@ static int DetectEngineHttpHHTest21(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET http://www.kaboom.com/index.html HTTP/1.0\r\n" - "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET http://www.kaboom.com/index.html HTTP/1.0\r\n" + "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -1990,7 +1968,7 @@ static int DetectEngineHttpHHTest21(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -2001,10 +1979,10 @@ static int DetectEngineHttpHHTest21(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http_host header test\"; " - "content:\"kaboom\"; http_host; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http_host header test\"; " + "content:\"kaboom\"; http_host; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -2061,9 +2039,8 @@ static int DetectEngineHttpHHTest22(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET http://www.kaboom.com:8080/index.html HTTP/1.0\r\n" - "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET http://www.kaboom.com:8080/index.html HTTP/1.0\r\n" + "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -2081,7 +2058,7 @@ static int DetectEngineHttpHHTest22(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -2092,10 +2069,10 @@ static int DetectEngineHttpHHTest22(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http_host header test\"; " - "content:\"kaboom\"; http_host; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http_host header test\"; " + "content:\"kaboom\"; http_host; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -2152,9 +2129,8 @@ static int DetectEngineHttpHHTest23(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET http://www.kaboom.com:8080/index.html HTTP/1.0\r\n" - "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET http://www.kaboom.com:8080/index.html HTTP/1.0\r\n" + "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -2172,7 +2148,7 @@ static int DetectEngineHttpHHTest23(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -2183,10 +2159,10 @@ static int DetectEngineHttpHHTest23(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http_host header test\"; " - "content:\"8080\"; http_host; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http_host header test\"; " + "content:\"8080\"; http_host; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -2243,10 +2219,9 @@ static int DetectEngineHttpHHTest24(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET http://www.kaboom.com:8080/index.html HTTP/1.0\r\n" - "Host: www.rabbit.com\r\n" - "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET http://www.kaboom.com:8080/index.html HTTP/1.0\r\n" + "Host: www.rabbit.com\r\n" + "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -2264,7 +2239,7 @@ static int DetectEngineHttpHHTest24(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -2275,10 +2250,10 @@ static int DetectEngineHttpHHTest24(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http_host header test\"; " - "content:\"kaboom\"; http_host; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http_host header test\"; " + "content:\"kaboom\"; http_host; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -2335,10 +2310,9 @@ static int DetectEngineHttpHHTest25(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET http://www.kaboom.com:8080/index.html HTTP/1.0\r\n" - "Host: www.rabbit.com\r\n" - "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET http://www.kaboom.com:8080/index.html HTTP/1.0\r\n" + "Host: www.rabbit.com\r\n" + "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -2356,7 +2330,7 @@ static int DetectEngineHttpHHTest25(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -2367,10 +2341,10 @@ static int DetectEngineHttpHHTest25(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http_host header test\"; " - "content:\"rabbit\"; http_host; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http_host header test\"; " + "content:\"rabbit\"; http_host; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -2433,15 +2407,15 @@ static int DetectHttpHHTest01(void) de_ctx->flags |= DE_QUIET; de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"Testing http_host\"; " - "content:\"one\"; http_host; sid:1;)"); + "(msg:\"Testing http_host\"; " + "content:\"one\"; http_host; sid:1;)"); if (de_ctx->sig_list != NULL) { result = 1; } else { goto end; } - end: +end: DetectEngineCtxFree(de_ctx); return result; @@ -2462,12 +2436,12 @@ static int DetectHttpHHTest02(void) de_ctx->flags |= DE_QUIET; de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"Testing http_host\"; " - "content:\"one\"; http_host; sid:1;)"); + "(msg:\"Testing http_host\"; " + "content:\"one\"; http_host; sid:1;)"); if (de_ctx->sig_list != NULL) result = 1; - end: +end: DetectEngineCtxFree(de_ctx); return result; @@ -2488,12 +2462,12 @@ static int DetectHttpHHTest03(void) de_ctx->flags |= DE_QUIET; de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"Testing http_host\"; " - "http_host; sid:1;)"); + "(msg:\"Testing http_host\"; " + "http_host; sid:1;)"); if (de_ctx->sig_list == NULL) result = 1; - end: +end: DetectEngineCtxFree(de_ctx); return result; @@ -2514,12 +2488,12 @@ static int DetectHttpHHTest04(void) de_ctx->flags |= DE_QUIET; de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"Testing http_host\"; " - "content:\"one\"; rawbytes; http_host; sid:1;)"); + "(msg:\"Testing http_host\"; " + "content:\"one\"; rawbytes; http_host; sid:1;)"); if (de_ctx->sig_list == NULL) result = 1; - end: +end: DetectEngineCtxFree(de_ctx); return result; @@ -2539,12 +2513,12 @@ static int DetectHttpHHTest05(void) de_ctx->flags |= DE_QUIET; de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"Testing http_host\"; " - "content:\"one\"; http_host; sid:1;)"); + "(msg:\"Testing http_host\"; " + "content:\"one\"; http_host; sid:1;)"); if (de_ctx->sig_list != NULL) result = 1; - end: +end: DetectEngineCtxFree(de_ctx); return result; @@ -2557,9 +2531,8 @@ static int DetectHttpHHTest05a(void) FAIL_IF_NULL(de_ctx); de_ctx->flags |= DE_QUIET; - Signature *s = DetectEngineAppendSig(de_ctx, - "alert tcp any any -> any any " - "(content:\"ABC\"; http_host; sid:1;)"); + Signature *s = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any " + "(content:\"ABC\"; http_host; sid:1;)"); FAIL_IF_NOT_NULL(s); DetectEngineCtxFree(de_ctx); @@ -2579,12 +2552,11 @@ static int DetectHttpHHTest06(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "User-Agent: www.openinfosecfoundation.org\r\n" - "Host: This is dummy message body\r\n" - "Content-Type: text/html\r\n" - "\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "User-Agent: www.openinfosecfoundation.org\r\n" + "Host: This is dummy message body\r\n" + "Content-Type: text/html\r\n" + "\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -2614,10 +2586,10 @@ static int DetectHttpHHTest06(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http host test\"; " - "content:\"message\"; http_host; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http host test\"; " + "content:\"message\"; http_host; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -2674,12 +2646,10 @@ static int DetectHttpHHTest07(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http1_buf[] = - "GET /index.html HTTP/1.0\r\n" - "User-Agent: www.openinfosecfoundation.org\r\n" - "Host: This is dummy message"; - uint8_t http2_buf[] = - "body1\r\n\r\n"; + uint8_t http1_buf[] = "GET /index.html HTTP/1.0\r\n" + "User-Agent: www.openinfosecfoundation.org\r\n" + "Host: This is dummy message"; + uint8_t http2_buf[] = "body1\r\n\r\n"; uint32_t http1_len = sizeof(http1_buf) - 1; uint32_t http2_len = sizeof(http2_buf) - 1; int result = 0; @@ -2700,11 +2670,11 @@ static int DetectHttpHHTest07(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOSERVER; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -2715,10 +2685,10 @@ static int DetectHttpHHTest07(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http host test\"; " - "content:\"message\"; http_host; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http host test\"; " + "content:\"message\"; http_host; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -2789,12 +2759,10 @@ static int DetectHttpHHTest08(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http1_buf[] = - "GET /index.html HTTP/1.0\r\n" - "User-Agent: www.openinfosecfoundation.org\r\n" - "host: This is dummy mess"; - uint8_t http2_buf[] = - "age body\r\n\r\n"; + uint8_t http1_buf[] = "GET /index.html HTTP/1.0\r\n" + "User-Agent: www.openinfosecfoundation.org\r\n" + "host: This is dummy mess"; + uint8_t http2_buf[] = "age body\r\n\r\n"; uint32_t http1_len = sizeof(http1_buf) - 1; uint32_t http2_len = sizeof(http2_buf) - 1; int result = 0; @@ -2815,11 +2783,11 @@ static int DetectHttpHHTest08(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOSERVER; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -2830,10 +2798,10 @@ static int DetectHttpHHTest08(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http host test\"; " - "content:\"message\"; http_host; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http host test\"; " + "content:\"message\"; http_host; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -2907,16 +2875,14 @@ static int DetectHttpHHTest09(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http1_buf[] = - "GET /index.html HTTP/1.0\r\n" - "User-Agent: www.openinfosecfoundation.org\r\n" - "Host: This is dummy body1"; - uint8_t http2_buf[] = - "This is dummy message body2\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 46\r\n" - "\r\n" - "This is dummy body1"; + uint8_t http1_buf[] = "GET /index.html HTTP/1.0\r\n" + "User-Agent: www.openinfosecfoundation.org\r\n" + "Host: This is dummy body1"; + uint8_t http2_buf[] = "This is dummy message body2\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 46\r\n" + "\r\n" + "This is dummy body1"; uint32_t http1_len = sizeof(http1_buf) - 1; uint32_t http2_len = sizeof(http2_buf) - 1; int result = 0; @@ -2937,11 +2903,11 @@ static int DetectHttpHHTest09(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOSERVER; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -2952,10 +2918,10 @@ static int DetectHttpHHTest09(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http host test\"; " - "content:\"body1this\"; http_host; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http host test\"; " + "content:\"body1this\"; http_host; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -3029,16 +2995,14 @@ static int DetectHttpHHTest10(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http1_buf[] = - "GET /index.html HTTP/1.0\r\n" - "User-Agent: www.openinfosecfoundation.org\r\n" - "Host: This is dummy bodY1"; - uint8_t http2_buf[] = - "This is dummy message body2\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 46\r\n" - "\r\n" - "This is dummy bodY1"; + uint8_t http1_buf[] = "GET /index.html HTTP/1.0\r\n" + "User-Agent: www.openinfosecfoundation.org\r\n" + "Host: This is dummy bodY1"; + uint8_t http2_buf[] = "This is dummy message body2\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 46\r\n" + "\r\n" + "This is dummy bodY1"; uint32_t http1_len = sizeof(http1_buf) - 1; uint32_t http2_len = sizeof(http2_buf) - 1; int result = 0; @@ -3059,11 +3023,11 @@ static int DetectHttpHHTest10(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOSERVER; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -3074,10 +3038,10 @@ static int DetectHttpHHTest10(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http host test\"; " - "content:\"body1this\"; http_host; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http host test\"; " + "content:\"body1this\"; http_host; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -3115,7 +3079,6 @@ static int DetectHttpHHTest10(void) goto end; } - /* do detect */ SigMatchSignatures(&th_v, de_ctx, det_ctx, p2); @@ -3151,12 +3114,11 @@ static int DetectHttpHHTest11(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "User-Agent: www.openinfosecfoundation.org\r\n" - "Host: This is dummy message body\r\n" - "Content-Type: text/html\r\n" - "\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "User-Agent: www.openinfosecfoundation.org\r\n" + "Host: This is dummy message body\r\n" + "Content-Type: text/html\r\n" + "\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -3175,7 +3137,7 @@ static int DetectHttpHHTest11(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -3186,10 +3148,10 @@ static int DetectHttpHHTest11(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http host test\"; " - "content:!\"message\"; http_host; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http host test\"; " + "content:!\"message\"; http_host; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -3245,11 +3207,10 @@ static int DetectHttpHHTest12(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "User-Agent: www.openinfosecfoundation.org\r\n" - "Host: This is dummy body\r\n" - "\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "User-Agent: www.openinfosecfoundation.org\r\n" + "Host: This is dummy body\r\n" + "\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -3268,7 +3229,7 @@ static int DetectHttpHHTest12(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -3279,10 +3240,10 @@ static int DetectHttpHHTest12(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http host test\"; " - "content:!\"message\"; http_host; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http host test\"; " + "content:!\"message\"; http_host; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -3338,12 +3299,11 @@ static int DetectHttpHHTest13(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "User-Agent: www.openinfosecfoundation.org\r\n" - "Host: longbufferabcdefghijklmnopqrstuvwxyz0123456789bufferend\r\n" - "Content-Type: text/html\r\n" - "\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "User-Agent: www.openinfosecfoundation.org\r\n" + "Host: longbufferabcdefghijklmnopqrstuvwxyz0123456789bufferend\r\n" + "Content-Type: text/html\r\n" + "\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -3362,7 +3322,7 @@ static int DetectHttpHHTest13(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -3373,10 +3333,11 @@ static int DetectHttpHHTest13(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http host test\"; " - "content:\"abcdefghijklmnopqrstuvwxyz0123456789\"; http_host; " - "sid:1;)"); + de_ctx->sig_list = + SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http host test\"; " + "content:\"abcdefghijklmnopqrstuvwxyz0123456789\"; http_host; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -3459,7 +3420,7 @@ static int DetectHttpHHTest14(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -3471,12 +3432,16 @@ static int DetectHttpHHTest14(void) de_ctx->flags |= DE_QUIET; - s = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any (content:\"POST\"; http_method; content:\"dummy1\"; http_cookie; content:\"body one\"; http_host; sid:1; rev:1;)"); + s = DetectEngineAppendSig(de_ctx, + "alert tcp any any -> any any (content:\"POST\"; http_method; content:\"dummy1\"; " + "http_cookie; content:\"body one\"; http_host; sid:1; rev:1;)"); if (s == NULL) { printf("sig parse failed: "); goto end; } - s = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any (content:\"GET\"; http_method; content:\"dummy2\"; http_cookie; content:\"body two\"; http_host; sid:2; rev:1;)"); + s = DetectEngineAppendSig(de_ctx, + "alert tcp any any -> any any (content:\"GET\"; http_method; content:\"dummy2\"; " + "http_cookie; content:\"body two\"; http_host; sid:2; rev:1;)"); if (s == NULL) { printf("sig2 parse failed: "); goto end; @@ -4642,16 +4607,14 @@ static int DetectHttpHRHTest37(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http1_buf[] = - "GET /index.html HTTP/1.0\r\n" - "User-Agent: www.openinfosecfoundation.org\r\n" - "Host: This is dummy bodY1"; - uint8_t http2_buf[] = - "This is dummy message body2\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 46\r\n" - "\r\n" - "This is dummy bodY1"; + uint8_t http1_buf[] = "GET /index.html HTTP/1.0\r\n" + "User-Agent: www.openinfosecfoundation.org\r\n" + "Host: This is dummy bodY1"; + uint8_t http2_buf[] = "This is dummy message body2\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 46\r\n" + "\r\n" + "This is dummy bodY1"; uint32_t http1_len = sizeof(http1_buf) - 1; uint32_t http2_len = sizeof(http2_buf) - 1; int result = 0; @@ -4672,11 +4635,11 @@ static int DetectHttpHRHTest37(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOSERVER; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -4687,10 +4650,10 @@ static int DetectHttpHRHTest37(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http host test\"; " - "content:\"body1this\"; http_raw_host; nocase; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http host test\"; " + "content:\"body1this\"; http_raw_host; nocase; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -4763,10 +4726,9 @@ static int DetectEngineHttpHRHTest01(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: CONNECT\r\n" - "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: CONNECT\r\n" + "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -4784,7 +4746,7 @@ static int DetectEngineHttpHRHTest01(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -4795,10 +4757,10 @@ static int DetectEngineHttpHRHTest01(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http host header test\"; " - "content:\"CONNECT\"; http_raw_host; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http host header test\"; " + "content:\"CONNECT\"; http_raw_host; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -4855,10 +4817,9 @@ static int DetectEngineHttpHRHTest02(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: CONNECT\r\n" - "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: CONNECT\r\n" + "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -4876,7 +4837,7 @@ static int DetectEngineHttpHRHTest02(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -4887,10 +4848,10 @@ static int DetectEngineHttpHRHTest02(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http host header test\"; " - "content:\"CO\"; depth:4; http_raw_host; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http host header test\"; " + "content:\"CO\"; depth:4; http_raw_host; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -4947,10 +4908,9 @@ static int DetectEngineHttpHRHTest03(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: CONNECT\r\n" - "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: CONNECT\r\n" + "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -4968,7 +4928,7 @@ static int DetectEngineHttpHRHTest03(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -4979,10 +4939,10 @@ static int DetectEngineHttpHRHTest03(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http_raw_host header test\"; " - "content:!\"ECT\"; depth:4; http_raw_host; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http_raw_host header test\"; " + "content:!\"ECT\"; depth:4; http_raw_host; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -5039,10 +4999,9 @@ static int DetectEngineHttpHRHTest04(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: CONNECT\r\n" - "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: CONNECT\r\n" + "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -5060,7 +5019,7 @@ static int DetectEngineHttpHRHTest04(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -5071,10 +5030,10 @@ static int DetectEngineHttpHRHTest04(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http host header test\"; " - "content:\"ECT\"; depth:4; http_raw_host; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http host header test\"; " + "content:\"ECT\"; depth:4; http_raw_host; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -5131,10 +5090,9 @@ static int DetectEngineHttpHRHTest05(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: CONNECT\r\n" - "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: CONNECT\r\n" + "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -5152,7 +5110,7 @@ static int DetectEngineHttpHRHTest05(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -5163,10 +5121,10 @@ static int DetectEngineHttpHRHTest05(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http host header test\"; " - "content:!\"CON\"; depth:4; http_raw_host; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http host header test\"; " + "content:!\"CON\"; depth:4; http_raw_host; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -5223,10 +5181,9 @@ static int DetectEngineHttpHRHTest06(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: CONNECT\r\n" - "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: CONNECT\r\n" + "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -5244,7 +5201,7 @@ static int DetectEngineHttpHRHTest06(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -5255,10 +5212,10 @@ static int DetectEngineHttpHRHTest06(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http host header test\"; " - "content:\"ECT\"; offset:3; http_raw_host; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http host header test\"; " + "content:\"ECT\"; offset:3; http_raw_host; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -5315,10 +5272,9 @@ static int DetectEngineHttpHRHTest07(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: CONNECT\r\n" - "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: CONNECT\r\n" + "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -5336,7 +5292,7 @@ static int DetectEngineHttpHRHTest07(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -5347,10 +5303,10 @@ static int DetectEngineHttpHRHTest07(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http host header test\"; " - "content:!\"CO\"; offset:3; http_raw_host; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http host header test\"; " + "content:!\"CO\"; offset:3; http_raw_host; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -5407,10 +5363,9 @@ static int DetectEngineHttpHRHTest08(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: CONNECT\r\n" - "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: CONNECT\r\n" + "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -5428,7 +5383,7 @@ static int DetectEngineHttpHRHTest08(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -5439,10 +5394,10 @@ static int DetectEngineHttpHRHTest08(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http host header test\"; " - "content:!\"ECT\"; offset:3; http_raw_host; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http host header test\"; " + "content:!\"ECT\"; offset:3; http_raw_host; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -5499,10 +5454,9 @@ static int DetectEngineHttpHRHTest09(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: CONNECT\r\n" - "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: CONNECT\r\n" + "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -5520,7 +5474,7 @@ static int DetectEngineHttpHRHTest09(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -5531,10 +5485,10 @@ static int DetectEngineHttpHRHTest09(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http host header test\"; " - "content:\"CON\"; offset:3; http_raw_host; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http host header test\"; " + "content:\"CON\"; offset:3; http_raw_host; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -5591,10 +5545,9 @@ static int DetectEngineHttpHRHTest10(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: CONNECT\r\n" - "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: CONNECT\r\n" + "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -5612,7 +5565,7 @@ static int DetectEngineHttpHRHTest10(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -5623,11 +5576,11 @@ static int DetectEngineHttpHRHTest10(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http_raw_host header test\"; " - "content:\"CO\"; http_raw_host; " - "content:\"EC\"; within:4; http_raw_host; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http_raw_host header test\"; " + "content:\"CO\"; http_raw_host; " + "content:\"EC\"; within:4; http_raw_host; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -5684,10 +5637,9 @@ static int DetectEngineHttpHRHTest11(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: CONNECT\r\n" - "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: CONNECT\r\n" + "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -5705,7 +5657,7 @@ static int DetectEngineHttpHRHTest11(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -5716,11 +5668,11 @@ static int DetectEngineHttpHRHTest11(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http_raw_host header test\"; " - "content:\"CO\"; http_raw_host; " - "content:!\"EC\"; within:3; http_raw_host; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http_raw_host header test\"; " + "content:\"CO\"; http_raw_host; " + "content:!\"EC\"; within:3; http_raw_host; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -5777,10 +5729,9 @@ static int DetectEngineHttpHRHTest12(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: CONNECT\r\n" - "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: CONNECT\r\n" + "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -5798,7 +5749,7 @@ static int DetectEngineHttpHRHTest12(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -5809,11 +5760,11 @@ static int DetectEngineHttpHRHTest12(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http_raw_host header test\"; " - "content:\"CO\"; http_raw_host; " - "content:\"EC\"; within:3; http_raw_host; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http_raw_host header test\"; " + "content:\"CO\"; http_raw_host; " + "content:\"EC\"; within:3; http_raw_host; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -5870,10 +5821,9 @@ static int DetectEngineHttpHRHTest13(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: CONNECT\r\n" - "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: CONNECT\r\n" + "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -5891,7 +5841,7 @@ static int DetectEngineHttpHRHTest13(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -5902,11 +5852,11 @@ static int DetectEngineHttpHRHTest13(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http_raw_host header test\"; " - "content:\"CO\"; http_raw_host; " - "content:!\"EC\"; within:4; http_raw_host; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http_raw_host header test\"; " + "content:\"CO\"; http_raw_host; " + "content:!\"EC\"; within:4; http_raw_host; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -5963,10 +5913,9 @@ static int DetectEngineHttpHRHTest14(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: CONNECT\r\n" - "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: CONNECT\r\n" + "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -5984,7 +5933,7 @@ static int DetectEngineHttpHRHTest14(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -5995,11 +5944,11 @@ static int DetectEngineHttpHRHTest14(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http_raw_host header test\"; " - "content:\"CO\"; http_raw_host; " - "content:\"EC\"; distance:2; http_raw_host; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http_raw_host header test\"; " + "content:\"CO\"; http_raw_host; " + "content:\"EC\"; distance:2; http_raw_host; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -6056,10 +6005,9 @@ static int DetectEngineHttpHRHTest15(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: CONNECT\r\n" - "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: CONNECT\r\n" + "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -6077,7 +6025,7 @@ static int DetectEngineHttpHRHTest15(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -6088,11 +6036,11 @@ static int DetectEngineHttpHRHTest15(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http_raw_host header test\"; " - "content:\"CO\"; http_raw_host; " - "content:!\"EC\"; distance:3; http_raw_host; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http_raw_host header test\"; " + "content:\"CO\"; http_raw_host; " + "content:!\"EC\"; distance:3; http_raw_host; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -6149,10 +6097,9 @@ static int DetectEngineHttpHRHTest16(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: CONNECT\r\n" - "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: CONNECT\r\n" + "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -6170,7 +6117,7 @@ static int DetectEngineHttpHRHTest16(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -6181,11 +6128,11 @@ static int DetectEngineHttpHRHTest16(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http_raw_host header test\"; " - "content:\"CO\"; http_raw_host; " - "content:\"EC\"; distance:3; http_raw_host; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http_raw_host header test\"; " + "content:\"CO\"; http_raw_host; " + "content:\"EC\"; distance:3; http_raw_host; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -6242,10 +6189,9 @@ static int DetectEngineHttpHRHTest17(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: CONNECT\r\n" - "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: CONNECT\r\n" + "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -6263,7 +6209,7 @@ static int DetectEngineHttpHRHTest17(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -6274,11 +6220,11 @@ static int DetectEngineHttpHRHTest17(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http_raw_host header test\"; " - "content:\"CO\"; http_raw_host; " - "content:!\"EC\"; distance:2; http_raw_host; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http_raw_host header test\"; " + "content:\"CO\"; http_raw_host; " + "content:!\"EC\"; distance:2; http_raw_host; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -6331,10 +6277,9 @@ static int DetectEngineHttpHRHTest18(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.kaboom.com:8080\r\n" - "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.kaboom.com:8080\r\n" + "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -6352,7 +6297,7 @@ static int DetectEngineHttpHRHTest18(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -6363,10 +6308,10 @@ static int DetectEngineHttpHRHTest18(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http_raw_host header test\"; " - "content:\"kaboom\"; http_raw_host; nocase; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http_raw_host header test\"; " + "content:\"kaboom\"; http_raw_host; nocase; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -6419,10 +6364,9 @@ static int DetectEngineHttpHRHTest19(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.kaboom.com:8080\r\n" - "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.kaboom.com:8080\r\n" + "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -6440,7 +6384,7 @@ static int DetectEngineHttpHRHTest19(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -6451,10 +6395,10 @@ static int DetectEngineHttpHRHTest19(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http_raw_host header test\"; " - "content:\"kaboom\"; http_raw_host; nocase; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http_raw_host header test\"; " + "content:\"kaboom\"; http_raw_host; nocase; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -6507,10 +6451,9 @@ static int DetectEngineHttpHRHTest20(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.kaboom.com:8080\r\n" - "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.kaboom.com:8080\r\n" + "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -6528,7 +6471,7 @@ static int DetectEngineHttpHRHTest20(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -6539,10 +6482,10 @@ static int DetectEngineHttpHRHTest20(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http_raw_host header test\"; " - "content:\"8080\"; http_raw_host; nocase; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http_raw_host header test\"; " + "content:\"8080\"; http_raw_host; nocase; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -6595,9 +6538,8 @@ static int DetectEngineHttpHRHTest21(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET http://www.kaboom.com/index.html HTTP/1.0\r\n" - "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET http://www.kaboom.com/index.html HTTP/1.0\r\n" + "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -6615,7 +6557,7 @@ static int DetectEngineHttpHRHTest21(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -6626,10 +6568,10 @@ static int DetectEngineHttpHRHTest21(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http_raw_host header test\"; " - "content:\"kaboom\"; http_raw_host; nocase; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http_raw_host header test\"; " + "content:\"kaboom\"; http_raw_host; nocase; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -6682,9 +6624,8 @@ static int DetectEngineHttpHRHTest22(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET http://www.kaboom.com:8080/index.html HTTP/1.0\r\n" - "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET http://www.kaboom.com:8080/index.html HTTP/1.0\r\n" + "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -6702,7 +6643,7 @@ static int DetectEngineHttpHRHTest22(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -6713,10 +6654,10 @@ static int DetectEngineHttpHRHTest22(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http_raw_host header test\"; " - "content:\"kaboom\"; http_raw_host; nocase; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http_raw_host header test\"; " + "content:\"kaboom\"; http_raw_host; nocase; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -6769,9 +6710,8 @@ static int DetectEngineHttpHRHTest23(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET http://www.kaboom.com:8080/index.html HTTP/1.0\r\n" - "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET http://www.kaboom.com:8080/index.html HTTP/1.0\r\n" + "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -6789,7 +6729,7 @@ static int DetectEngineHttpHRHTest23(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -6800,10 +6740,10 @@ static int DetectEngineHttpHRHTest23(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http_raw_host header test\"; " - "content:\"8080\"; http_raw_host; nocase; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http_raw_host header test\"; " + "content:\"8080\"; http_raw_host; nocase; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -6856,10 +6796,9 @@ static int DetectEngineHttpHRHTest24(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET http://www.kaboom.com:8080/index.html HTTP/1.0\r\n" - "Host: www.rabbit.com\r\n" - "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET http://www.kaboom.com:8080/index.html HTTP/1.0\r\n" + "Host: www.rabbit.com\r\n" + "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -6877,7 +6816,7 @@ static int DetectEngineHttpHRHTest24(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -6888,10 +6827,10 @@ static int DetectEngineHttpHRHTest24(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http_raw_host header test\"; " - "content:\"kaboom\"; http_raw_host; nocase; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http_raw_host header test\"; " + "content:\"kaboom\"; http_raw_host; nocase; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -6944,10 +6883,9 @@ static int DetectEngineHttpHRHTest25(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET http://www.kaboom.com:8080/index.html HTTP/1.0\r\n" - "Host: www.rabbit.com\r\n" - "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET http://www.kaboom.com:8080/index.html HTTP/1.0\r\n" + "Host: www.rabbit.com\r\n" + "User-Agent: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -6965,7 +6903,7 @@ static int DetectEngineHttpHRHTest25(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -6976,10 +6914,10 @@ static int DetectEngineHttpHRHTest25(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http_raw_host header test\"; " - "content:\"rabbit\"; http_raw_host; nocase; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http_raw_host header test\"; " + "content:\"rabbit\"; http_raw_host; nocase; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; diff --git a/src/tests/detect-http-method.c b/src/tests/detect-http-method.c index 1da5c18917e3..450a91ee1421 100644 --- a/src/tests/detect-http-method.c +++ b/src/tests/detect-http-method.c @@ -21,7 +21,6 @@ * @{ */ - /** \file * * \author Anoop Saldanha @@ -58,9 +57,8 @@ static int DetectEngineHttpMethodTest01(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -78,7 +76,7 @@ static int DetectEngineHttpMethodTest01(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -89,10 +87,10 @@ static int DetectEngineHttpMethodTest01(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; " - "content:\"GET\"; http_method; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http header test\"; " + "content:\"GET\"; http_method; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -149,9 +147,8 @@ static int DetectEngineHttpMethodTest02(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "CONNECT /index.html HTTP/1.0\r\n" - "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "CONNECT /index.html HTTP/1.0\r\n" + "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -169,7 +166,7 @@ static int DetectEngineHttpMethodTest02(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -180,10 +177,10 @@ static int DetectEngineHttpMethodTest02(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; " - "content:\"CO\"; depth:4; http_method; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http header test\"; " + "content:\"CO\"; depth:4; http_method; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -240,9 +237,8 @@ static int DetectEngineHttpMethodTest03(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "CONNECT /index.html HTTP/1.0\r\n" - "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "CONNECT /index.html HTTP/1.0\r\n" + "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -260,7 +256,7 @@ static int DetectEngineHttpMethodTest03(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -271,10 +267,10 @@ static int DetectEngineHttpMethodTest03(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; " - "content:!\"ECT\"; depth:4; http_method; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http header test\"; " + "content:!\"ECT\"; depth:4; http_method; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -331,9 +327,8 @@ static int DetectEngineHttpMethodTest04(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "CONNECT /index.html HTTP/1.0\r\n" - "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "CONNECT /index.html HTTP/1.0\r\n" + "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -351,7 +346,7 @@ static int DetectEngineHttpMethodTest04(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -362,10 +357,10 @@ static int DetectEngineHttpMethodTest04(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; " - "content:\"ECT\"; depth:4; http_method; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http header test\"; " + "content:\"ECT\"; depth:4; http_method; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -422,9 +417,8 @@ static int DetectEngineHttpMethodTest05(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "CONNECT /index.html HTTP/1.0\r\n" - "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "CONNECT /index.html HTTP/1.0\r\n" + "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -442,7 +436,7 @@ static int DetectEngineHttpMethodTest05(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -453,10 +447,10 @@ static int DetectEngineHttpMethodTest05(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; " - "content:!\"CON\"; depth:4; http_method; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http header test\"; " + "content:!\"CON\"; depth:4; http_method; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -513,9 +507,8 @@ static int DetectEngineHttpMethodTest06(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "CONNECT /index.html HTTP/1.0\r\n" - "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "CONNECT /index.html HTTP/1.0\r\n" + "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -533,7 +526,7 @@ static int DetectEngineHttpMethodTest06(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -544,10 +537,10 @@ static int DetectEngineHttpMethodTest06(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; " - "content:\"ECT\"; offset:3; http_method; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http header test\"; " + "content:\"ECT\"; offset:3; http_method; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -604,9 +597,8 @@ static int DetectEngineHttpMethodTest07(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "CONNECT /index.html HTTP/1.0\r\n" - "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "CONNECT /index.html HTTP/1.0\r\n" + "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -624,7 +616,7 @@ static int DetectEngineHttpMethodTest07(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -635,10 +627,10 @@ static int DetectEngineHttpMethodTest07(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; " - "content:!\"CO\"; offset:3; http_method; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http header test\"; " + "content:!\"CO\"; offset:3; http_method; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -695,9 +687,8 @@ static int DetectEngineHttpMethodTest08(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "CONNECT /index.html HTTP/1.0\r\n" - "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "CONNECT /index.html HTTP/1.0\r\n" + "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -715,7 +706,7 @@ static int DetectEngineHttpMethodTest08(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -726,10 +717,10 @@ static int DetectEngineHttpMethodTest08(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; " - "content:!\"ECT\"; offset:3; http_method; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http header test\"; " + "content:!\"ECT\"; offset:3; http_method; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -786,9 +777,8 @@ static int DetectEngineHttpMethodTest09(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "CONNECT /index.html HTTP/1.0\r\n" - "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "CONNECT /index.html HTTP/1.0\r\n" + "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -806,7 +796,7 @@ static int DetectEngineHttpMethodTest09(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -817,10 +807,10 @@ static int DetectEngineHttpMethodTest09(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; " - "content:\"CON\"; offset:3; http_method; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http header test\"; " + "content:\"CON\"; offset:3; http_method; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -877,9 +867,8 @@ static int DetectEngineHttpMethodTest10(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "CONNECT /index.html HTTP/1.0\r\n" - "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "CONNECT /index.html HTTP/1.0\r\n" + "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -897,7 +886,7 @@ static int DetectEngineHttpMethodTest10(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -908,11 +897,11 @@ static int DetectEngineHttpMethodTest10(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; " - "content:\"CO\"; http_method; " - "content:\"EC\"; within:4; http_method; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http header test\"; " + "content:\"CO\"; http_method; " + "content:\"EC\"; within:4; http_method; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -969,9 +958,8 @@ static int DetectEngineHttpMethodTest11(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "CONNECT /index.html HTTP/1.0\r\n" - "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "CONNECT /index.html HTTP/1.0\r\n" + "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -989,7 +977,7 @@ static int DetectEngineHttpMethodTest11(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1000,11 +988,11 @@ static int DetectEngineHttpMethodTest11(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; " - "content:\"CO\"; http_method; " - "content:!\"EC\"; within:3; http_method; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http header test\"; " + "content:\"CO\"; http_method; " + "content:!\"EC\"; within:3; http_method; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -1061,9 +1049,8 @@ static int DetectEngineHttpMethodTest12(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "CONNECT /index.html HTTP/1.0\r\n" - "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "CONNECT /index.html HTTP/1.0\r\n" + "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -1081,7 +1068,7 @@ static int DetectEngineHttpMethodTest12(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1092,11 +1079,11 @@ static int DetectEngineHttpMethodTest12(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; " - "content:\"CO\"; http_method; " - "content:\"EC\"; within:3; http_method; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http header test\"; " + "content:\"CO\"; http_method; " + "content:\"EC\"; within:3; http_method; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -1153,9 +1140,8 @@ static int DetectEngineHttpMethodTest13(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "CONNECT /index.html HTTP/1.0\r\n" - "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "CONNECT /index.html HTTP/1.0\r\n" + "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -1173,7 +1159,7 @@ static int DetectEngineHttpMethodTest13(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1184,11 +1170,11 @@ static int DetectEngineHttpMethodTest13(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; " - "content:\"CO\"; http_method; " - "content:!\"EC\"; within:4; http_method; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http header test\"; " + "content:\"CO\"; http_method; " + "content:!\"EC\"; within:4; http_method; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -1245,9 +1231,8 @@ static int DetectEngineHttpMethodTest14(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "CONNECT /index.html HTTP/1.0\r\n" - "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "CONNECT /index.html HTTP/1.0\r\n" + "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -1265,7 +1250,7 @@ static int DetectEngineHttpMethodTest14(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1276,11 +1261,11 @@ static int DetectEngineHttpMethodTest14(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; " - "content:\"CO\"; http_method; " - "content:\"EC\"; distance:2; http_method; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http header test\"; " + "content:\"CO\"; http_method; " + "content:\"EC\"; distance:2; http_method; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -1337,9 +1322,8 @@ static int DetectEngineHttpMethodTest15(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "CONNECT /index.html HTTP/1.0\r\n" - "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "CONNECT /index.html HTTP/1.0\r\n" + "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -1357,7 +1341,7 @@ static int DetectEngineHttpMethodTest15(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1368,11 +1352,11 @@ static int DetectEngineHttpMethodTest15(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; " - "content:\"CO\"; http_method; " - "content:!\"EC\"; distance:3; http_method; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http header test\"; " + "content:\"CO\"; http_method; " + "content:!\"EC\"; distance:3; http_method; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -1429,9 +1413,8 @@ static int DetectEngineHttpMethodTest16(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "CONNECT /index.html HTTP/1.0\r\n" - "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "CONNECT /index.html HTTP/1.0\r\n" + "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -1449,7 +1432,7 @@ static int DetectEngineHttpMethodTest16(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1460,11 +1443,11 @@ static int DetectEngineHttpMethodTest16(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; " - "content:\"CO\"; http_method; " - "content:\"EC\"; distance:3; http_method; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http header test\"; " + "content:\"CO\"; http_method; " + "content:\"EC\"; distance:3; http_method; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -1521,9 +1504,8 @@ static int DetectEngineHttpMethodTest17(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "CONNECT /index.html HTTP/1.0\r\n" - "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "CONNECT /index.html HTTP/1.0\r\n" + "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -1541,7 +1523,7 @@ static int DetectEngineHttpMethodTest17(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1552,11 +1534,11 @@ static int DetectEngineHttpMethodTest17(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; " - "content:\"CO\"; http_method; " - "content:!\"EC\"; distance:2; http_method; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http header test\"; " + "content:\"CO\"; http_method; " + "content:!\"EC\"; distance:2; http_method; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -1606,15 +1588,14 @@ static int DetectHttpMethodTest01(void) DetectEngineCtx *de_ctx = NULL; int result = 0; - if ( (de_ctx = DetectEngineCtxInit()) == NULL) + if ((de_ctx = DetectEngineCtxInit()) == NULL) goto end; de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx, - "alert tcp any any -> any any " - "(msg:\"Testing http_method\"; " - "content:\"GET\"; " - "http_method; sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " + "(msg:\"Testing http_method\"; " + "content:\"GET\"; " + "http_method; sid:1;)"); if (de_ctx->sig_list != NULL) { result = 1; @@ -1622,7 +1603,7 @@ static int DetectHttpMethodTest01(void) printf("sig parse failed: "); } - end: +end: if (de_ctx != NULL) DetectEngineCtxFree(de_ctx); return result; @@ -1634,20 +1615,19 @@ static int DetectHttpMethodTest02(void) DetectEngineCtx *de_ctx = NULL; int result = 0; - if ( (de_ctx = DetectEngineCtxInit()) == NULL) + if ((de_ctx = DetectEngineCtxInit()) == NULL) goto end; de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx, - "alert tcp any any -> any any " - "(msg:\"Testing http_method\"; " - "http_method; sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " + "(msg:\"Testing http_method\"; " + "http_method; sid:1;)"); if (de_ctx->sig_list == NULL) { result = 1; } - end: +end: if (de_ctx != NULL) DetectEngineCtxFree(de_ctx); return result; @@ -1659,21 +1639,20 @@ static int DetectHttpMethodTest03(void) DetectEngineCtx *de_ctx = NULL; int result = 0; - if ( (de_ctx = DetectEngineCtxInit()) == NULL) + if ((de_ctx = DetectEngineCtxInit()) == NULL) goto end; de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx, - "alert tcp any any -> any any " - "(msg:\"Testing http_method\"; " - "content:\"foobar\"; " - "http_method:\"GET\"; sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " + "(msg:\"Testing http_method\"; " + "content:\"foobar\"; " + "http_method:\"GET\"; sid:1;)"); if (de_ctx->sig_list == NULL) { result = 1; } - end: +end: if (de_ctx != NULL) DetectEngineCtxFree(de_ctx); return result; @@ -1685,22 +1664,21 @@ static int DetectHttpMethodTest04(void) DetectEngineCtx *de_ctx = NULL; int result = 0; - if ( (de_ctx = DetectEngineCtxInit()) == NULL) + if ((de_ctx = DetectEngineCtxInit()) == NULL) goto end; de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx, - "alert tcp any any -> any any " - "(msg:\"Testing http_method\"; " - "content:\"GET\"; " - "fast_pattern; " - "http_method; sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " + "(msg:\"Testing http_method\"; " + "content:\"GET\"; " + "fast_pattern; " + "http_method; sid:1;)"); if (de_ctx->sig_list != NULL) { result = 1; } - end: +end: if (de_ctx != NULL) DetectEngineCtxFree(de_ctx); return result; @@ -1712,22 +1690,21 @@ static int DetectHttpMethodTest05(void) DetectEngineCtx *de_ctx = NULL; int result = 0; - if ( (de_ctx = DetectEngineCtxInit()) == NULL) + if ((de_ctx = DetectEngineCtxInit()) == NULL) goto end; de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx, - "alert tcp any any -> any any " - "(msg:\"Testing http_method\"; " - "content:\"GET\"; " - "rawbytes; " - "http_method; sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " + "(msg:\"Testing http_method\"; " + "content:\"GET\"; " + "rawbytes; " + "http_method; sid:1;)"); if (de_ctx->sig_list == NULL) { result = 1; } - end: +end: if (de_ctx != NULL) DetectEngineCtxFree(de_ctx); return result; @@ -1764,7 +1741,7 @@ static int DetectHttpMethodSigTest01(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1776,20 +1753,18 @@ static int DetectHttpMethodSigTest01(void) de_ctx->flags |= DE_QUIET; - s = de_ctx->sig_list = SigInit(de_ctx, - "alert tcp any any -> any any " - "(msg:\"Testing http_method\"; " - "content:\"GET\"; " - "http_method; sid:1;)"); + s = de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " + "(msg:\"Testing http_method\"; " + "content:\"GET\"; " + "http_method; sid:1;)"); if (s == NULL) { goto end; } - s = s->next = SigInit(de_ctx, - "alert tcp any any -> any any " - "(msg:\"Testing http_method\"; " - "content:\"POST\"; " - "http_method; sid:2;)"); + s = s->next = SigInit(de_ctx, "alert tcp any any -> any any " + "(msg:\"Testing http_method\"; " + "content:\"POST\"; " + "http_method; sid:2;)"); if (s == NULL) { goto end; } @@ -1864,7 +1839,7 @@ static int DetectHttpMethodSigTest02(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1876,20 +1851,18 @@ static int DetectHttpMethodSigTest02(void) de_ctx->flags |= DE_QUIET; - s = de_ctx->sig_list = SigInit(de_ctx, - "alert tcp any any -> any any " - "(msg:\"Testing http_method\"; " - "content:\"FOO\"; " - "http_method; sid:1;)"); + s = de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " + "(msg:\"Testing http_method\"; " + "content:\"FOO\"; " + "http_method; sid:1;)"); if (s == NULL) { goto end; } - s = s->next = SigInit(de_ctx, - "alert tcp any any -> any any " - "(msg:\"Testing http_method\"; " - "content:\"BAR\"; " - "http_method; sid:2;)"); + s = s->next = SigInit(de_ctx, "alert tcp any any -> any any " + "(msg:\"Testing http_method\"; " + "content:\"BAR\"; " + "http_method; sid:2;)"); if (s == NULL) { goto end; } @@ -1925,7 +1898,7 @@ static int DetectHttpMethodSigTest02(void) if (alp_tctx != NULL) AppLayerParserThreadCtxFree(alp_tctx); if (det_ctx != NULL) - DetectEngineThreadCtxDeinit(&th_v, (void *) det_ctx); + DetectEngineThreadCtxDeinit(&th_v, (void *)det_ctx); if (de_ctx != NULL) DetectEngineCtxFree(de_ctx); @@ -1964,7 +1937,7 @@ static int DetectHttpMethodSigTest03(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1976,11 +1949,10 @@ static int DetectHttpMethodSigTest03(void) de_ctx->flags |= DE_QUIET; - s = de_ctx->sig_list = SigInit(de_ctx, - "alert tcp any any -> any any " - "(msg:\"Testing http_method\"; " - "content:\"GET\"; " - "http_method; sid:1;)"); + s = de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " + "(msg:\"Testing http_method\"; " + "content:\"GET\"; " + "http_method; sid:1;)"); if (s == NULL) { SCLogDebug("Bad signature"); goto end; @@ -2053,7 +2025,7 @@ static int DetectHttpMethodSigTest04(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -2065,16 +2037,15 @@ static int DetectHttpMethodSigTest04(void) de_ctx->flags |= DE_QUIET; - s = de_ctx->sig_list = SigInit(de_ctx, - "alert tcp any any -> any any (msg:\"Testing http_method\"; " - "content:\"GET\"; http_method; sid:1;)"); + s = de_ctx->sig_list = + SigInit(de_ctx, "alert tcp any any -> any any (msg:\"Testing http_method\"; " + "content:\"GET\"; http_method; sid:1;)"); if (s == NULL) { goto end; } - s = s->next = SigInit(de_ctx, - "alert tcp any any -> any any (msg:\"Testing http_method\"; " - "content:!\"GET\"; http_method; sid:2;)"); + s = s->next = SigInit(de_ctx, "alert tcp any any -> any any (msg:\"Testing http_method\"; " + "content:!\"GET\"; http_method; sid:2;)"); if (s == NULL) { goto end; } @@ -2112,7 +2083,7 @@ static int DetectHttpMethodSigTest04(void) if (alp_tctx != NULL) AppLayerParserThreadCtxFree(alp_tctx); if (det_ctx != NULL) { - DetectEngineThreadCtxDeinit(&th_v, (void *) det_ctx); + DetectEngineThreadCtxDeinit(&th_v, (void *)det_ctx); } if (de_ctx != NULL) { DetectEngineCtxFree(de_ctx); @@ -2130,10 +2101,9 @@ static int DetectHttpMethodIsdataatParseTest(void) FAIL_IF_NULL(de_ctx); de_ctx->flags |= DE_QUIET; - Signature *s = DetectEngineAppendSig(de_ctx, - "alert tcp any any -> any any (" - "content:\"one\"; http_method; " - "isdataat:!4,relative; sid:1;)"); + Signature *s = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any (" + "content:\"one\"; http_method; " + "isdataat:!4,relative; sid:1;)"); FAIL_IF_NULL(s); SigMatch *sm = DetectBufferGetLastSigMatch(s, g_http_method_buffer_id); @@ -2164,42 +2134,24 @@ void DetectHttpMethodRegisterTests(void) UtRegisterTest("DetectHttpMethodSigTest03", DetectHttpMethodSigTest03); UtRegisterTest("DetectHttpMethodSigTest04", DetectHttpMethodSigTest04); - UtRegisterTest("DetectHttpMethodIsdataatParseTest", - DetectHttpMethodIsdataatParseTest); - UtRegisterTest("DetectEngineHttpMethodTest01", - DetectEngineHttpMethodTest01); - UtRegisterTest("DetectEngineHttpMethodTest02", - DetectEngineHttpMethodTest02); - UtRegisterTest("DetectEngineHttpMethodTest03", - DetectEngineHttpMethodTest03); - UtRegisterTest("DetectEngineHttpMethodTest04", - DetectEngineHttpMethodTest04); - UtRegisterTest("DetectEngineHttpMethodTest05", - DetectEngineHttpMethodTest05); - UtRegisterTest("DetectEngineHttpMethodTest06", - DetectEngineHttpMethodTest06); - UtRegisterTest("DetectEngineHttpMethodTest07", - DetectEngineHttpMethodTest07); - UtRegisterTest("DetectEngineHttpMethodTest08", - DetectEngineHttpMethodTest08); - UtRegisterTest("DetectEngineHttpMethodTest09", - DetectEngineHttpMethodTest09); - UtRegisterTest("DetectEngineHttpMethodTest10", - DetectEngineHttpMethodTest10); - UtRegisterTest("DetectEngineHttpMethodTest11", - DetectEngineHttpMethodTest11); - UtRegisterTest("DetectEngineHttpMethodTest12", - DetectEngineHttpMethodTest12); - UtRegisterTest("DetectEngineHttpMethodTest13", - DetectEngineHttpMethodTest13); - UtRegisterTest("DetectEngineHttpMethodTest14", - DetectEngineHttpMethodTest14); - UtRegisterTest("DetectEngineHttpMethodTest15", - DetectEngineHttpMethodTest15); - UtRegisterTest("DetectEngineHttpMethodTest16", - DetectEngineHttpMethodTest16); - UtRegisterTest("DetectEngineHttpMethodTest17", - DetectEngineHttpMethodTest17); + UtRegisterTest("DetectHttpMethodIsdataatParseTest", DetectHttpMethodIsdataatParseTest); + UtRegisterTest("DetectEngineHttpMethodTest01", DetectEngineHttpMethodTest01); + UtRegisterTest("DetectEngineHttpMethodTest02", DetectEngineHttpMethodTest02); + UtRegisterTest("DetectEngineHttpMethodTest03", DetectEngineHttpMethodTest03); + UtRegisterTest("DetectEngineHttpMethodTest04", DetectEngineHttpMethodTest04); + UtRegisterTest("DetectEngineHttpMethodTest05", DetectEngineHttpMethodTest05); + UtRegisterTest("DetectEngineHttpMethodTest06", DetectEngineHttpMethodTest06); + UtRegisterTest("DetectEngineHttpMethodTest07", DetectEngineHttpMethodTest07); + UtRegisterTest("DetectEngineHttpMethodTest08", DetectEngineHttpMethodTest08); + UtRegisterTest("DetectEngineHttpMethodTest09", DetectEngineHttpMethodTest09); + UtRegisterTest("DetectEngineHttpMethodTest10", DetectEngineHttpMethodTest10); + UtRegisterTest("DetectEngineHttpMethodTest11", DetectEngineHttpMethodTest11); + UtRegisterTest("DetectEngineHttpMethodTest12", DetectEngineHttpMethodTest12); + UtRegisterTest("DetectEngineHttpMethodTest13", DetectEngineHttpMethodTest13); + UtRegisterTest("DetectEngineHttpMethodTest14", DetectEngineHttpMethodTest14); + UtRegisterTest("DetectEngineHttpMethodTest15", DetectEngineHttpMethodTest15); + UtRegisterTest("DetectEngineHttpMethodTest16", DetectEngineHttpMethodTest16); + UtRegisterTest("DetectEngineHttpMethodTest17", DetectEngineHttpMethodTest17); } /** diff --git a/src/tests/detect-http-raw-header.c b/src/tests/detect-http-raw-header.c index de716cb35c5d..a52b0c838d6d 100644 --- a/src/tests/detect-http-raw-header.c +++ b/src/tests/detect-http-raw-header.c @@ -21,7 +21,6 @@ * @{ */ - /** \file * * \author Anoop Saldanha @@ -61,15 +60,30 @@ */ static int DetectHttpRawHeaderParserTest01(void) { - FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_server; content:\"abc\"; http_raw_header; sid:1;)", true)); - FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_server; content:\"abc\"; nocase; http_raw_header; sid:1;)", true)); - FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_server; content:\"abc\"; endswith; http_raw_header; sid:1;)", true)); - FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_server; content:\"abc\"; startswith; http_raw_header; sid:1;)", true)); - FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_server; content:\"abc\"; startswith; endswith; http_raw_header; sid:1;)", true)); - - FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_server; content:\"abc\"; rawbytes; http_raw_header; sid:1;)", false)); - FAIL_IF_NOT(UTHParseSignature("alert tcp any any -> any any (flow:to_server; http_raw_header; sid:1;)", false)); - FAIL_IF_NOT(UTHParseSignature("alert tls any any -> any any (flow:to_server; content:\"abc\"; http_raw_header; sid:1;)", false)); + FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_server; content:\"abc\"; " + "http_raw_header; sid:1;)", + true)); + FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_server; content:\"abc\"; " + "nocase; http_raw_header; sid:1;)", + true)); + FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_server; content:\"abc\"; " + "endswith; http_raw_header; sid:1;)", + true)); + FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_server; content:\"abc\"; " + "startswith; http_raw_header; sid:1;)", + true)); + FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_server; content:\"abc\"; " + "startswith; endswith; http_raw_header; sid:1;)", + true)); + + FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_server; content:\"abc\"; " + "rawbytes; http_raw_header; sid:1;)", + false)); + FAIL_IF_NOT(UTHParseSignature( + "alert tcp any any -> any any (flow:to_server; http_raw_header; sid:1;)", false)); + FAIL_IF_NOT(UTHParseSignature("alert tls any any -> any any (flow:to_server; content:\"abc\"; " + "http_raw_header; sid:1;)", + false)); PASS; } @@ -78,16 +92,33 @@ static int DetectHttpRawHeaderParserTest01(void) */ static int DetectHttpRawHeaderParserTest02(void) { - FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_server; http.header.raw; content:\"abc\"; sid:1;)", true)); - FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_server; http.header.raw; content:\"abc\"; nocase; sid:1;)", true)); - FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_server; http.header.raw; content:\"abc\"; endswith; sid:1;)", true)); - FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_server; http.header.raw; content:\"abc\"; startswith; sid:1;)", true)); - FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_server; http.header.raw; content:\"abc\"; startswith; endswith; sid:1;)", true)); - FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_server; http.header.raw; bsize:10; sid:1;)", true)); - - FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_server; http.header.raw; content:\"abc\"; rawbytes; sid:1;)", false)); - FAIL_IF_NOT(UTHParseSignature("alert tcp any any -> any any (flow:to_server; http.header.raw; sid:1;)", false)); - FAIL_IF_NOT(UTHParseSignature("alert tls any any -> any any (flow:to_server; http.header.raw; content:\"abc\"; sid:1;)", false)); + FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_server; http.header.raw; " + "content:\"abc\"; sid:1;)", + true)); + FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_server; http.header.raw; " + "content:\"abc\"; nocase; sid:1;)", + true)); + FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_server; http.header.raw; " + "content:\"abc\"; endswith; sid:1;)", + true)); + FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_server; http.header.raw; " + "content:\"abc\"; startswith; sid:1;)", + true)); + FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_server; http.header.raw; " + "content:\"abc\"; startswith; endswith; sid:1;)", + true)); + FAIL_IF_NOT(UTHParseSignature( + "alert http any any -> any any (flow:to_server; http.header.raw; bsize:10; sid:1;)", + true)); + + FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_server; http.header.raw; " + "content:\"abc\"; rawbytes; sid:1;)", + false)); + FAIL_IF_NOT(UTHParseSignature( + "alert tcp any any -> any any (flow:to_server; http.header.raw; sid:1;)", false)); + FAIL_IF_NOT(UTHParseSignature("alert tls any any -> any any (flow:to_server; http.header.raw; " + "content:\"abc\"; sid:1;)", + false)); PASS; } @@ -104,9 +135,8 @@ static int DetectEngineHttpRawHeaderTest01(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -124,7 +154,7 @@ static int DetectEngineHttpRawHeaderTest01(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -135,10 +165,10 @@ static int DetectEngineHttpRawHeaderTest01(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; flow:to_server; " - "content:\"one\"; http_raw_header; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http header test\"; flow:to_server; " + "content:\"one\"; http_raw_header; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -194,9 +224,8 @@ static int DetectEngineHttpRawHeaderTest02(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -214,7 +243,7 @@ static int DetectEngineHttpRawHeaderTest02(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -225,10 +254,10 @@ static int DetectEngineHttpRawHeaderTest02(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; flow:to_server; " - "content:\"one\"; depth:15; http_raw_header; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http header test\"; flow:to_server; " + "content:\"one\"; depth:15; http_raw_header; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -284,9 +313,8 @@ static int DetectEngineHttpRawHeaderTest03(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -304,7 +332,7 @@ static int DetectEngineHttpRawHeaderTest03(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -315,10 +343,10 @@ static int DetectEngineHttpRawHeaderTest03(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; flow:to_server; " - "content:!\"one\"; depth:5; http_raw_header; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http header test\"; flow:to_server; " + "content:!\"one\"; depth:5; http_raw_header; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -374,9 +402,8 @@ static int DetectEngineHttpRawHeaderTest04(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -394,7 +421,7 @@ static int DetectEngineHttpRawHeaderTest04(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -405,10 +432,10 @@ static int DetectEngineHttpRawHeaderTest04(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; flow:to_server; " - "content:\"one\"; depth:5; http_raw_header; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http header test\"; flow:to_server; " + "content:\"one\"; depth:5; http_raw_header; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -464,9 +491,8 @@ static int DetectEngineHttpRawHeaderTest05(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -484,7 +510,7 @@ static int DetectEngineHttpRawHeaderTest05(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -495,10 +521,10 @@ static int DetectEngineHttpRawHeaderTest05(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; flow:to_server; " - "content:!\"one\"; depth:15; http_raw_header; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http header test\"; flow:to_server; " + "content:!\"one\"; depth:15; http_raw_header; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -554,9 +580,8 @@ static int DetectEngineHttpRawHeaderTest06(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -574,7 +599,7 @@ static int DetectEngineHttpRawHeaderTest06(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -585,10 +610,10 @@ static int DetectEngineHttpRawHeaderTest06(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; flow:to_server; " - "content:\"one\"; offset:10; http_raw_header; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http header test\"; flow:to_server; " + "content:\"one\"; offset:10; http_raw_header; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -644,9 +669,8 @@ static int DetectEngineHttpRawHeaderTest07(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -664,7 +688,7 @@ static int DetectEngineHttpRawHeaderTest07(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -675,10 +699,10 @@ static int DetectEngineHttpRawHeaderTest07(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; flow:to_server; " - "content:!\"one\"; offset:15; http_raw_header; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http header test\"; flow:to_server; " + "content:!\"one\"; offset:15; http_raw_header; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -734,9 +758,8 @@ static int DetectEngineHttpRawHeaderTest08(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -754,7 +777,7 @@ static int DetectEngineHttpRawHeaderTest08(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -765,10 +788,10 @@ static int DetectEngineHttpRawHeaderTest08(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; flow:to_server; " - "content:\"one\"; offset:15; http_raw_header; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http header test\"; flow:to_server; " + "content:\"one\"; offset:15; http_raw_header; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -824,9 +847,8 @@ static int DetectEngineHttpRawHeaderTest09(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -844,7 +866,7 @@ static int DetectEngineHttpRawHeaderTest09(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -855,10 +877,10 @@ static int DetectEngineHttpRawHeaderTest09(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; flow:to_server; " - "content:!\"one\"; offset:10; http_raw_header; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http header test\"; flow:to_server; " + "content:!\"one\"; offset:10; http_raw_header; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -914,9 +936,8 @@ static int DetectEngineHttpRawHeaderTest10(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -934,7 +955,7 @@ static int DetectEngineHttpRawHeaderTest10(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -945,10 +966,11 @@ static int DetectEngineHttpRawHeaderTest10(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; flow:to_server; " - "content:\"one\"; http_raw_header; content:\"three\"; http_raw_header; within:10; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, + "alert http any any -> any any " + "(msg:\"http header test\"; flow:to_server; " + "content:\"one\"; http_raw_header; content:\"three\"; http_raw_header; within:10; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -1004,9 +1026,8 @@ static int DetectEngineHttpRawHeaderTest11(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -1024,7 +1045,7 @@ static int DetectEngineHttpRawHeaderTest11(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1035,10 +1056,11 @@ static int DetectEngineHttpRawHeaderTest11(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; flow:to_server; " - "content:\"one\"; http_raw_header; content:!\"three\"; http_raw_header; within:5; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, + "alert http any any -> any any " + "(msg:\"http header test\"; flow:to_server; " + "content:\"one\"; http_raw_header; content:!\"three\"; http_raw_header; within:5; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -1094,9 +1116,8 @@ static int DetectEngineHttpRawHeaderTest12(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -1114,7 +1135,7 @@ static int DetectEngineHttpRawHeaderTest12(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1125,10 +1146,11 @@ static int DetectEngineHttpRawHeaderTest12(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; flow:to_server; " - "content:\"one\"; http_raw_header; content:!\"three\"; http_raw_header; within:10; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, + "alert http any any -> any any " + "(msg:\"http header test\"; flow:to_server; " + "content:\"one\"; http_raw_header; content:!\"three\"; http_raw_header; within:10; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -1184,9 +1206,8 @@ static int DetectEngineHttpRawHeaderTest13(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -1204,7 +1225,7 @@ static int DetectEngineHttpRawHeaderTest13(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1215,10 +1236,11 @@ static int DetectEngineHttpRawHeaderTest13(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; flow:to_server; " - "content:\"one\"; http_raw_header; content:\"three\"; http_raw_header; within:5; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, + "alert http any any -> any any " + "(msg:\"http header test\"; flow:to_server; " + "content:\"one\"; http_raw_header; content:\"three\"; http_raw_header; within:5; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -1274,9 +1296,8 @@ static int DetectEngineHttpRawHeaderTest14(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -1294,7 +1315,7 @@ static int DetectEngineHttpRawHeaderTest14(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1305,10 +1326,11 @@ static int DetectEngineHttpRawHeaderTest14(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; flow:to_server; " - "content:\"one\"; http_raw_header; content:\"five\"; http_raw_header; distance:7; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, + "alert http any any -> any any " + "(msg:\"http header test\"; flow:to_server; " + "content:\"one\"; http_raw_header; content:\"five\"; http_raw_header; distance:7; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -1364,9 +1386,8 @@ static int DetectEngineHttpRawHeaderTest15(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -1384,7 +1405,7 @@ static int DetectEngineHttpRawHeaderTest15(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1395,10 +1416,11 @@ static int DetectEngineHttpRawHeaderTest15(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; flow:to_server; " - "content:\"one\"; http_raw_header; content:!\"five\"; http_raw_header; distance:15; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, + "alert http any any -> any any " + "(msg:\"http header test\"; flow:to_server; " + "content:\"one\"; http_raw_header; content:!\"five\"; http_raw_header; distance:15; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -1454,9 +1476,8 @@ static int DetectEngineHttpRawHeaderTest16(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -1474,7 +1495,7 @@ static int DetectEngineHttpRawHeaderTest16(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1485,10 +1506,11 @@ static int DetectEngineHttpRawHeaderTest16(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; flow:to_server; " - "content:\"one\"; http_raw_header; content:!\"five\"; http_raw_header; distance:7; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, + "alert http any any -> any any " + "(msg:\"http header test\"; flow:to_server; " + "content:\"one\"; http_raw_header; content:!\"five\"; http_raw_header; distance:7; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -1544,9 +1566,8 @@ static int DetectEngineHttpRawHeaderTest17(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.onetwothreefourfivesixseven.org\r\n\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -1564,7 +1585,7 @@ static int DetectEngineHttpRawHeaderTest17(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1575,10 +1596,11 @@ static int DetectEngineHttpRawHeaderTest17(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; flow:to_server; " - "content:\"one\"; http_raw_header; content:\"five\"; http_raw_header; distance:15; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, + "alert http any any -> any any " + "(msg:\"http header test\"; flow:to_server; " + "content:\"one\"; http_raw_header; content:\"five\"; http_raw_header; distance:15; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -1627,12 +1649,10 @@ static int DetectEngineHttpRawHeaderTest20(void) ThreadVars th_v; DetectEngineThreadCtx *det_ctx = NULL; Flow f; - uint8_t http1_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: This_is_dummy_body1"; - uint8_t http2_buf[] = - "This_is_dummy_message_body2\r\n" - "\r\n"; + uint8_t http1_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: This_is_dummy_body1"; + uint8_t http2_buf[] = "This_is_dummy_message_body2\r\n" + "\r\n"; uint32_t http1_len = sizeof(http1_buf) - 1; uint32_t http2_len = sizeof(http2_buf) - 1; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -1655,11 +1675,11 @@ static int DetectEngineHttpRawHeaderTest20(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOSERVER; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1669,9 +1689,9 @@ static int DetectEngineHttpRawHeaderTest20(void) de_ctx->flags |= DE_QUIET; Signature *s = DetectEngineAppendSig(de_ctx, "alert http any any -> any any " - "(flow:to_server; pcre:/body1/D; " - "content:!\"dummy\"; http_raw_header; within:7; " - "sid:1;)"); + "(flow:to_server; pcre:/body1/D; " + "content:!\"dummy\"; http_raw_header; within:7; " + "sid:1;)"); FAIL_IF_NULL(s); SigGroupBuild(de_ctx); @@ -1719,12 +1739,10 @@ static int DetectEngineHttpRawHeaderTest21(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http1_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: This_is_dummy_body1"; - uint8_t http2_buf[] = - "This_is_dummy_message_body2\r\n" - "\r\n"; + uint8_t http1_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: This_is_dummy_body1"; + uint8_t http2_buf[] = "This_is_dummy_message_body2\r\n" + "\r\n"; uint32_t http1_len = sizeof(http1_buf) - 1; uint32_t http2_len = sizeof(http2_buf) - 1; int result = 0; @@ -1745,11 +1763,11 @@ static int DetectEngineHttpRawHeaderTest21(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOSERVER; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1760,11 +1778,11 @@ static int DetectEngineHttpRawHeaderTest21(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http client body test\"; flow:to_server; " - "pcre:/body1/D; " - "content:!\"dummy\"; within:7; http_raw_header; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http client body test\"; flow:to_server; " + "pcre:/body1/D; " + "content:!\"dummy\"; within:7; http_raw_header; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -1835,12 +1853,10 @@ static int DetectEngineHttpRawHeaderTest22(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http1_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: This_is_dummy_body1"; - uint8_t http2_buf[] = - "This_is_dummy_message_body2\r\n" - "\r\n"; + uint8_t http1_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: This_is_dummy_body1"; + uint8_t http2_buf[] = "This_is_dummy_message_body2\r\n" + "\r\n"; uint32_t http1_len = sizeof(http1_buf) - 1; uint32_t http2_len = sizeof(http2_buf) - 1; int result = 0; @@ -1861,11 +1877,11 @@ static int DetectEngineHttpRawHeaderTest22(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOSERVER; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1876,11 +1892,11 @@ static int DetectEngineHttpRawHeaderTest22(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http client body test\"; flow:to_server; " - "pcre:/body1/D; " - "content:!\"dummy\"; distance:3; http_raw_header; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http client body test\"; flow:to_server; " + "pcre:/body1/D; " + "content:!\"dummy\"; distance:3; http_raw_header; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -1951,12 +1967,10 @@ static int DetectEngineHttpRawHeaderTest23(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http1_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: This_is_dummy_body1"; - uint8_t http2_buf[] = - "This_is_dummy_message_body2\r\n" - "\r\n"; + uint8_t http1_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: This_is_dummy_body1"; + uint8_t http2_buf[] = "This_is_dummy_message_body2\r\n" + "\r\n"; uint32_t http1_len = sizeof(http1_buf) - 1; uint32_t http2_len = sizeof(http2_buf) - 1; int result = 0; @@ -1977,11 +1991,11 @@ static int DetectEngineHttpRawHeaderTest23(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOSERVER; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1992,11 +2006,11 @@ static int DetectEngineHttpRawHeaderTest23(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http client body test\"; flow:to_server; " - "pcre:/body1/D; " - "content:!\"dummy\"; distance:13; http_raw_header; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http client body test\"; flow:to_server; " + "pcre:/body1/D; " + "content:!\"dummy\"; distance:13; http_raw_header; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -2067,12 +2081,10 @@ static int DetectEngineHttpRawHeaderTest24(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http1_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: This_is_dummy_body1"; - uint8_t http2_buf[] = - "This_is_dummy_message_body2\r\n" - "\r\n"; + uint8_t http1_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: This_is_dummy_body1"; + uint8_t http2_buf[] = "This_is_dummy_message_body2\r\n" + "\r\n"; uint32_t http1_len = sizeof(http1_buf) - 1; uint32_t http2_len = sizeof(http2_buf) - 1; int result = 0; @@ -2093,11 +2105,11 @@ static int DetectEngineHttpRawHeaderTest24(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOSERVER; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -2108,11 +2120,11 @@ static int DetectEngineHttpRawHeaderTest24(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http client body test\"; flow:to_server; " - "pcre:/body1/D; " - "content:\"dummy\"; within:15; http_raw_header; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http client body test\"; flow:to_server; " + "pcre:/body1/D; " + "content:\"dummy\"; within:15; http_raw_header; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -2183,12 +2195,10 @@ static int DetectEngineHttpRawHeaderTest25(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http1_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: This_is_dummy_body1"; - uint8_t http2_buf[] = - "This_is_dummy_message_body2\r\n" - "\r\n"; + uint8_t http1_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: This_is_dummy_body1"; + uint8_t http2_buf[] = "This_is_dummy_message_body2\r\n" + "\r\n"; uint32_t http1_len = sizeof(http1_buf) - 1; uint32_t http2_len = sizeof(http2_buf) - 1; int result = 0; @@ -2209,11 +2219,11 @@ static int DetectEngineHttpRawHeaderTest25(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOSERVER; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -2224,11 +2234,11 @@ static int DetectEngineHttpRawHeaderTest25(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http client body test\"; flow:to_server; " - "pcre:/body1/D; " - "content:\"dummy\"; within:10; http_raw_header; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http client body test\"; flow:to_server; " + "pcre:/body1/D; " + "content:\"dummy\"; within:10; http_raw_header; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -2299,12 +2309,10 @@ static int DetectEngineHttpRawHeaderTest26(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http1_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: This_is_dummy_body1"; - uint8_t http2_buf[] = - "This_is_dummy_message_body2\r\n" - "\r\n"; + uint8_t http1_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: This_is_dummy_body1"; + uint8_t http2_buf[] = "This_is_dummy_message_body2\r\n" + "\r\n"; uint32_t http1_len = sizeof(http1_buf) - 1; uint32_t http2_len = sizeof(http2_buf) - 1; int result = 0; @@ -2325,11 +2333,11 @@ static int DetectEngineHttpRawHeaderTest26(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOSERVER; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -2340,11 +2348,11 @@ static int DetectEngineHttpRawHeaderTest26(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http client body test\"; flow:to_server; " - "pcre:/body1/D; " - "content:\"dummy\"; distance:8; http_raw_header; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http client body test\"; flow:to_server; " + "pcre:/body1/D; " + "content:\"dummy\"; distance:8; http_raw_header; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -2413,12 +2421,10 @@ static int DetectEngineHttpRawHeaderTest27(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http1_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: This_is_dummy_body1"; - uint8_t http2_buf[] = - "This_is_dummy_message_body2\r\n" - "\r\n"; + uint8_t http1_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: This_is_dummy_body1"; + uint8_t http2_buf[] = "This_is_dummy_message_body2\r\n" + "\r\n"; uint32_t http1_len = sizeof(http1_buf) - 1; uint32_t http2_len = sizeof(http2_buf) - 1; int result = 0; @@ -2439,11 +2445,11 @@ static int DetectEngineHttpRawHeaderTest27(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOSERVER; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -2454,11 +2460,11 @@ static int DetectEngineHttpRawHeaderTest27(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http client body test\"; flow:to_server; " - "pcre:/body1/D; " - "content:\"dummy\"; distance:14; http_raw_header; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http client body test\"; flow:to_server; " + "pcre:/body1/D; " + "content:\"dummy\"; distance:14; http_raw_header; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -2529,18 +2535,17 @@ static int DetectEngineHttpRawHeaderTest28(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf1[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_buf1_len = sizeof(http_buf1) - 1; - uint8_t http_buf2[] = - "HTTP/1.0 200 ok\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 6\r\n" - "\r\n" - "abcdef"; + uint8_t http_buf2[] = "HTTP/1.0 200 ok\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 6\r\n" + "\r\n" + "abcdef"; uint32_t http_buf2_len = sizeof(http_buf2) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -2575,10 +2580,10 @@ static int DetectEngineHttpRawHeaderTest28(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; flow:to_client; " - "content:\"Content-Length: 6\"; http_raw_header; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http header test\"; flow:to_client; " + "content:\"Content-Length: 6\"; http_raw_header; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -2649,18 +2654,17 @@ static int DetectEngineHttpRawHeaderTest29(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf1[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_buf1_len = sizeof(http_buf1) - 1; - uint8_t http_buf2[] = - "HTTP/1.0 200 ok\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 6\r\n" - "\r\n" - "abcdef"; + uint8_t http_buf2[] = "HTTP/1.0 200 ok\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 6\r\n" + "\r\n" + "abcdef"; uint32_t http_buf2_len = sizeof(http_buf2) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -2695,10 +2699,10 @@ static int DetectEngineHttpRawHeaderTest29(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; flow:to_client; " - "content:\"Content-Length: 7\"; http_raw_header; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http header test\"; flow:to_client; " + "content:\"Content-Length: 7\"; http_raw_header; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -2803,16 +2807,15 @@ static int DetectEngineHttpRawHeaderTest31(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http1_buf[] = - "GET /index.html HTTP/1.0\r\n" - "host: boom\r\n" - "Transfer-Encoding: chunked\r\n" - "\r\n" - "13\r\n" - "This is dummy body1\r\n" - "0\r\n" - "Dummy-Header: kaboom\r\n" - "\r\n"; + uint8_t http1_buf[] = "GET /index.html HTTP/1.0\r\n" + "host: boom\r\n" + "Transfer-Encoding: chunked\r\n" + "\r\n" + "13\r\n" + "This is dummy body1\r\n" + "0\r\n" + "Dummy-Header: kaboom\r\n" + "\r\n"; uint32_t http1_len = sizeof(http1_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -2831,7 +2834,7 @@ static int DetectEngineHttpRawHeaderTest31(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -2842,10 +2845,10 @@ static int DetectEngineHttpRawHeaderTest31(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(flow:to_server; " - "content:\"Dummy\"; http_raw_header; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(flow:to_server; " + "content:\"Dummy\"; http_raw_header; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -2902,17 +2905,15 @@ static int DetectEngineHttpRawHeaderTest32(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http1_buf[] = - "GET /index.html HTTP/1.0\r\n" - "host: boom\r\n" - "Transfer-Encoding: chunked\r\n" - "\r\n" - "13\r\n" - "This is dummy body1\r\n" - "0\r\n"; - uint8_t http2_buf[] = - "Dummy-Header: kaboom\r\n" - "\r\n"; + uint8_t http1_buf[] = "GET /index.html HTTP/1.0\r\n" + "host: boom\r\n" + "Transfer-Encoding: chunked\r\n" + "\r\n" + "13\r\n" + "This is dummy body1\r\n" + "0\r\n"; + uint8_t http2_buf[] = "Dummy-Header: kaboom\r\n" + "\r\n"; uint32_t http1_len = sizeof(http1_buf) - 1; uint32_t http2_len = sizeof(http2_buf) - 1; int result = 0; @@ -2933,11 +2934,11 @@ static int DetectEngineHttpRawHeaderTest32(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOSERVER; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -2948,10 +2949,10 @@ static int DetectEngineHttpRawHeaderTest32(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(flow:to_server; " - "content:\"Dummy\"; http_raw_header; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(flow:to_server; " + "content:\"Dummy\"; http_raw_header; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -3025,14 +3026,14 @@ static int DetectHttpRawHeaderTest06(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 26\r\n" - "\r\n" - "This is dummy message body\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 26\r\n" + "\r\n" + "This is dummy message body\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -3050,7 +3051,7 @@ static int DetectHttpRawHeaderTest06(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -3061,10 +3062,10 @@ static int DetectHttpRawHeaderTest06(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; flow:to_server; " - "content:\"Content-Type: text/html\"; http_raw_header; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http header test\"; flow:to_server; " + "content:\"Content-Type: text/html\"; http_raw_header; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -3121,15 +3122,14 @@ static int DetectHttpRawHeaderTest07(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http1_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozi"; - uint8_t http2_buf[] = - "lla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\nContent-Type: text/html\r\n" - "Content-Length: 67\r\n" - "\r\n" - "This is dummy message body1"; + uint8_t http1_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozi"; + uint8_t http2_buf[] = "lla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 " + "Firefox/3.5.7\r\nContent-Type: text/html\r\n" + "Content-Length: 67\r\n" + "\r\n" + "This is dummy message body1"; uint32_t http1_len = sizeof(http1_buf) - 1; uint32_t http2_len = sizeof(http2_buf) - 1; int result = 0; @@ -3149,11 +3149,11 @@ static int DetectHttpRawHeaderTest07(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOSERVER; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -3164,10 +3164,10 @@ static int DetectHttpRawHeaderTest07(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; flow:to_server; " - "content:\"Mozilla\"; http_raw_header; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http header test\"; flow:to_server; " + "content:\"Mozilla\"; http_raw_header; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -3192,7 +3192,7 @@ static int DetectHttpRawHeaderTest07(void) /* do detect */ SigMatchSignatures(&th_v, de_ctx, det_ctx, p1); - if ( (PacketAlertCheck(p1, 1))) { + if ((PacketAlertCheck(p1, 1))) { printf("sid 1 matched but shouldn't have: "); goto end; } @@ -3241,14 +3241,13 @@ static int DetectHttpRawHeaderTest08(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http1_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n"; - uint8_t http2_buf[] = - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 67\r\n" - "\r\n"; + uint8_t http1_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n"; + uint8_t http2_buf[] = "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 67\r\n" + "\r\n"; uint32_t http1_len = sizeof(http1_buf) - 1; uint32_t http2_len = sizeof(http2_buf) - 1; int result = 0; @@ -3268,11 +3267,11 @@ static int DetectHttpRawHeaderTest08(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOSERVER; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -3283,10 +3282,10 @@ static int DetectHttpRawHeaderTest08(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; flow:to_server; " - "content:\"Gecko/20091221 Firefox/3.5.7\"; http_raw_header; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http header test\"; flow:to_server; " + "content:\"Gecko/20091221 Firefox/3.5.7\"; http_raw_header; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -3360,15 +3359,14 @@ static int DetectHttpRawHeaderTest09(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http1_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n"; - uint8_t http2_buf[] = - "Content-Type: text/html\r\n" - "Content-Length: 67\r\n" - "\r\n" - "This is dummy body\r\n"; + uint8_t http1_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n"; + uint8_t http2_buf[] = "Content-Type: text/html\r\n" + "Content-Length: 67\r\n" + "\r\n" + "This is dummy body\r\n"; uint32_t http1_len = sizeof(http1_buf) - 1; uint32_t http2_len = sizeof(http2_buf) - 1; int result = 0; @@ -3388,11 +3386,11 @@ static int DetectHttpRawHeaderTest09(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOSERVER; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -3403,10 +3401,10 @@ static int DetectHttpRawHeaderTest09(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; flow:to_server; " - "content:\"Firefox/3.5.7|0D 0A|Content\"; http_raw_header; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http header test\"; flow:to_server; " + "content:\"Firefox/3.5.7|0D 0A|Content\"; http_raw_header; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -3480,15 +3478,14 @@ static int DetectHttpRawHeaderTest10(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http1_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n"; - uint8_t http2_buf[] = - "Content-Type: text/html\r\n" - "Content-Length: 67\r\n" - "\r\n" - "This is dummy body"; + uint8_t http1_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n"; + uint8_t http2_buf[] = "Content-Type: text/html\r\n" + "Content-Length: 67\r\n" + "\r\n" + "This is dummy body"; uint32_t http1_len = sizeof(http1_buf) - 1; uint32_t http2_len = sizeof(http2_buf) - 1; int result = 0; @@ -3508,11 +3505,11 @@ static int DetectHttpRawHeaderTest10(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOSERVER; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -3523,10 +3520,11 @@ static int DetectHttpRawHeaderTest10(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; flow:to_server; " - "content:\"firefox/3.5.7|0D 0A|content\"; nocase; http_raw_header;" - "sid:1;)"); + de_ctx->sig_list = + SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http header test\"; flow:to_server; " + "content:\"firefox/3.5.7|0D 0A|content\"; nocase; http_raw_header;" + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -3599,14 +3597,14 @@ static int DetectHttpRawHeaderTest11(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 26\r\n" - "\r\n" - "This is dummy message body\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 26\r\n" + "\r\n" + "This is dummy message body\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -3624,7 +3622,7 @@ static int DetectHttpRawHeaderTest11(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -3635,10 +3633,10 @@ static int DetectHttpRawHeaderTest11(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; flow:to_server; " - "content:!\"lalalalala\"; http_raw_header; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http header test\"; flow:to_server; " + "content:!\"lalalalala\"; http_raw_header; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -3694,14 +3692,14 @@ static int DetectHttpRawHeaderTest12(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 26\r\n" - "\r\n" - "This is dummy message body\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 26\r\n" + "\r\n" + "This is dummy message body\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -3719,7 +3717,7 @@ static int DetectHttpRawHeaderTest12(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -3730,10 +3728,10 @@ static int DetectHttpRawHeaderTest12(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; flow:to_server; " - "content:!\"User-Agent: Mozilla/5.0 \"; http_raw_header; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http header test\"; flow:to_server; " + "content:!\"User-Agent: Mozilla/5.0 \"; http_raw_header; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -3789,14 +3787,14 @@ static int DetectHttpRawHeaderTest13(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 100\r\n" - "\r\n" - "longbufferabcdefghijklmnopqrstuvwxyz0123456789bufferend\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 100\r\n" + "\r\n" + "longbufferabcdefghijklmnopqrstuvwxyz0123456789bufferend\r\n"; uint32_t http_len = sizeof(http_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -3815,7 +3813,7 @@ static int DetectHttpRawHeaderTest13(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -3826,10 +3824,11 @@ static int DetectHttpRawHeaderTest13(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http header test\"; flow:to_server; " - "content:\"Host: www.openinfosecfoundation.org\"; http_raw_header; " - "sid:1;)"); + de_ctx->sig_list = + SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http header test\"; flow:to_server; " + "content:\"Host: www.openinfosecfoundation.org\"; http_raw_header; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -3875,73 +3874,42 @@ static int DetectHttpRawHeaderTest13(void) void DetectHttpRawHeaderRegisterTests(void) { - UtRegisterTest("DetectHttpRawHeaderParserTest01", - DetectHttpRawHeaderParserTest01); - UtRegisterTest("DetectHttpRawHeaderParserTest02", - DetectHttpRawHeaderParserTest02); - - UtRegisterTest("DetectEngineHttpRawHeaderTest01", - DetectEngineHttpRawHeaderTest01); - UtRegisterTest("DetectEngineHttpRawHeaderTest02", - DetectEngineHttpRawHeaderTest02); - UtRegisterTest("DetectEngineHttpRawHeaderTest03", - DetectEngineHttpRawHeaderTest03); - UtRegisterTest("DetectEngineHttpRawHeaderTest04", - DetectEngineHttpRawHeaderTest04); - UtRegisterTest("DetectEngineHttpRawHeaderTest05", - DetectEngineHttpRawHeaderTest05); - UtRegisterTest("DetectEngineHttpRawHeaderTest06", - DetectEngineHttpRawHeaderTest06); - UtRegisterTest("DetectEngineHttpRawHeaderTest07", - DetectEngineHttpRawHeaderTest07); - UtRegisterTest("DetectEngineHttpRawHeaderTest08", - DetectEngineHttpRawHeaderTest08); - UtRegisterTest("DetectEngineHttpRawHeaderTest09", - DetectEngineHttpRawHeaderTest09); - UtRegisterTest("DetectEngineHttpRawHeaderTest10", - DetectEngineHttpRawHeaderTest10); - UtRegisterTest("DetectEngineHttpRawHeaderTest11", - DetectEngineHttpRawHeaderTest11); - UtRegisterTest("DetectEngineHttpRawHeaderTest12", - DetectEngineHttpRawHeaderTest12); - UtRegisterTest("DetectEngineHttpRawHeaderTest13", - DetectEngineHttpRawHeaderTest13); - UtRegisterTest("DetectEngineHttpRawHeaderTest14", - DetectEngineHttpRawHeaderTest14); - UtRegisterTest("DetectEngineHttpRawHeaderTest15", - DetectEngineHttpRawHeaderTest15); - UtRegisterTest("DetectEngineHttpRawHeaderTest16", - DetectEngineHttpRawHeaderTest16); - UtRegisterTest("DetectEngineHttpRawHeaderTest17", - DetectEngineHttpRawHeaderTest17); - UtRegisterTest("DetectEngineHttpRawHeaderTest20", - DetectEngineHttpRawHeaderTest20); - UtRegisterTest("DetectEngineHttpRawHeaderTest21", - DetectEngineHttpRawHeaderTest21); - UtRegisterTest("DetectEngineHttpRawHeaderTest22", - DetectEngineHttpRawHeaderTest22); - UtRegisterTest("DetectEngineHttpRawHeaderTest23", - DetectEngineHttpRawHeaderTest23); - UtRegisterTest("DetectEngineHttpRawHeaderTest24", - DetectEngineHttpRawHeaderTest24); - UtRegisterTest("DetectEngineHttpRawHeaderTest25", - DetectEngineHttpRawHeaderTest25); - UtRegisterTest("DetectEngineHttpRawHeaderTest26", - DetectEngineHttpRawHeaderTest26); - UtRegisterTest("DetectEngineHttpRawHeaderTest27", - DetectEngineHttpRawHeaderTest27); - UtRegisterTest("DetectEngineHttpRawHeaderTest28", - DetectEngineHttpRawHeaderTest28); - UtRegisterTest("DetectEngineHttpRawHeaderTest29", - DetectEngineHttpRawHeaderTest29); + UtRegisterTest("DetectHttpRawHeaderParserTest01", DetectHttpRawHeaderParserTest01); + UtRegisterTest("DetectHttpRawHeaderParserTest02", DetectHttpRawHeaderParserTest02); + + UtRegisterTest("DetectEngineHttpRawHeaderTest01", DetectEngineHttpRawHeaderTest01); + UtRegisterTest("DetectEngineHttpRawHeaderTest02", DetectEngineHttpRawHeaderTest02); + UtRegisterTest("DetectEngineHttpRawHeaderTest03", DetectEngineHttpRawHeaderTest03); + UtRegisterTest("DetectEngineHttpRawHeaderTest04", DetectEngineHttpRawHeaderTest04); + UtRegisterTest("DetectEngineHttpRawHeaderTest05", DetectEngineHttpRawHeaderTest05); + UtRegisterTest("DetectEngineHttpRawHeaderTest06", DetectEngineHttpRawHeaderTest06); + UtRegisterTest("DetectEngineHttpRawHeaderTest07", DetectEngineHttpRawHeaderTest07); + UtRegisterTest("DetectEngineHttpRawHeaderTest08", DetectEngineHttpRawHeaderTest08); + UtRegisterTest("DetectEngineHttpRawHeaderTest09", DetectEngineHttpRawHeaderTest09); + UtRegisterTest("DetectEngineHttpRawHeaderTest10", DetectEngineHttpRawHeaderTest10); + UtRegisterTest("DetectEngineHttpRawHeaderTest11", DetectEngineHttpRawHeaderTest11); + UtRegisterTest("DetectEngineHttpRawHeaderTest12", DetectEngineHttpRawHeaderTest12); + UtRegisterTest("DetectEngineHttpRawHeaderTest13", DetectEngineHttpRawHeaderTest13); + UtRegisterTest("DetectEngineHttpRawHeaderTest14", DetectEngineHttpRawHeaderTest14); + UtRegisterTest("DetectEngineHttpRawHeaderTest15", DetectEngineHttpRawHeaderTest15); + UtRegisterTest("DetectEngineHttpRawHeaderTest16", DetectEngineHttpRawHeaderTest16); + UtRegisterTest("DetectEngineHttpRawHeaderTest17", DetectEngineHttpRawHeaderTest17); + UtRegisterTest("DetectEngineHttpRawHeaderTest20", DetectEngineHttpRawHeaderTest20); + UtRegisterTest("DetectEngineHttpRawHeaderTest21", DetectEngineHttpRawHeaderTest21); + UtRegisterTest("DetectEngineHttpRawHeaderTest22", DetectEngineHttpRawHeaderTest22); + UtRegisterTest("DetectEngineHttpRawHeaderTest23", DetectEngineHttpRawHeaderTest23); + UtRegisterTest("DetectEngineHttpRawHeaderTest24", DetectEngineHttpRawHeaderTest24); + UtRegisterTest("DetectEngineHttpRawHeaderTest25", DetectEngineHttpRawHeaderTest25); + UtRegisterTest("DetectEngineHttpRawHeaderTest26", DetectEngineHttpRawHeaderTest26); + UtRegisterTest("DetectEngineHttpRawHeaderTest27", DetectEngineHttpRawHeaderTest27); + UtRegisterTest("DetectEngineHttpRawHeaderTest28", DetectEngineHttpRawHeaderTest28); + UtRegisterTest("DetectEngineHttpRawHeaderTest29", DetectEngineHttpRawHeaderTest29); #if 0 UtRegisterTest("DetectEngineHttpRawHeaderTest30", DetectEngineHttpRawHeaderTest30, 1); #endif - UtRegisterTest("DetectEngineHttpRawHeaderTest31", - DetectEngineHttpRawHeaderTest31); - UtRegisterTest("DetectEngineHttpRawHeaderTest32", - DetectEngineHttpRawHeaderTest32); + UtRegisterTest("DetectEngineHttpRawHeaderTest31", DetectEngineHttpRawHeaderTest31); + UtRegisterTest("DetectEngineHttpRawHeaderTest32", DetectEngineHttpRawHeaderTest32); UtRegisterTest("DetectHttpRawHeaderTest06", DetectHttpRawHeaderTest06); UtRegisterTest("DetectHttpRawHeaderTest07", DetectHttpRawHeaderTest07); diff --git a/src/tests/detect-http-server-body.c b/src/tests/detect-http-server-body.c index fe8a16e777bd..1cbd7f463e69 100644 --- a/src/tests/detect-http-server-body.c +++ b/src/tests/detect-http-server-body.c @@ -36,15 +36,30 @@ */ static int DetectHttpServerBodyParserTest01(void) { - FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_client; content:\"abc\"; http_server_body; sid:1;)", true)); - FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_client; content:\"abc\"; nocase; http_server_body; sid:1;)", true)); - FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_client; content:\"abc\"; endswith; http_server_body; sid:1;)", true)); - FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_client; content:\"abc\"; startswith; http_server_body; sid:1;)", true)); - FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_client; content:\"abc\"; startswith; endswith; http_server_body; sid:1;)", true)); - - FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_client; content:\"abc\"; rawbytes; http_server_body; sid:1;)", false)); - FAIL_IF_NOT(UTHParseSignature("alert tcp any any -> any any (flow:to_client; http_server_body; sid:1;)", false)); - FAIL_IF_NOT(UTHParseSignature("alert tls any any -> any any (flow:to_client; content:\"abc\"; http_server_body; sid:1;)", false)); + FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_client; content:\"abc\"; " + "http_server_body; sid:1;)", + true)); + FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_client; content:\"abc\"; " + "nocase; http_server_body; sid:1;)", + true)); + FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_client; content:\"abc\"; " + "endswith; http_server_body; sid:1;)", + true)); + FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_client; content:\"abc\"; " + "startswith; http_server_body; sid:1;)", + true)); + FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_client; content:\"abc\"; " + "startswith; endswith; http_server_body; sid:1;)", + true)); + + FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_client; content:\"abc\"; " + "rawbytes; http_server_body; sid:1;)", + false)); + FAIL_IF_NOT(UTHParseSignature( + "alert tcp any any -> any any (flow:to_client; http_server_body; sid:1;)", false)); + FAIL_IF_NOT(UTHParseSignature("alert tls any any -> any any (flow:to_client; content:\"abc\"; " + "http_server_body; sid:1;)", + false)); PASS; } @@ -53,22 +68,40 @@ static int DetectHttpServerBodyParserTest01(void) */ static int DetectHttpServerBodyParserTest02(void) { - FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_client; http.response_body; content:\"abc\"; sid:1;)", true)); - FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_client; http.response_body; content:\"abc\"; nocase; sid:1;)", true)); - FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_client; http.response_body; content:\"abc\"; endswith; sid:1;)", true)); - FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_client; http.response_body; content:\"abc\"; startswith; sid:1;)", true)); - FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_client; http.response_body; content:\"abc\"; startswith; endswith; sid:1;)", true)); - FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_client; http.response_body; bsize:10; sid:1;)", true)); - - FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_client; http.response_body; content:\"abc\"; rawbytes; sid:1;)", false)); - FAIL_IF_NOT(UTHParseSignature("alert tcp any any -> any any (flow:to_client; http.response_body; sid:1;)", false)); - FAIL_IF_NOT(UTHParseSignature("alert tls any any -> any any (flow:to_client; http.response_body; content:\"abc\"; sid:1;)", false)); + FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_client; " + "http.response_body; content:\"abc\"; sid:1;)", + true)); + FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_client; " + "http.response_body; content:\"abc\"; nocase; sid:1;)", + true)); + FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_client; " + "http.response_body; content:\"abc\"; endswith; sid:1;)", + true)); + FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_client; " + "http.response_body; content:\"abc\"; startswith; sid:1;)", + true)); + FAIL_IF_NOT( + UTHParseSignature("alert http any any -> any any (flow:to_client; http.response_body; " + "content:\"abc\"; startswith; endswith; sid:1;)", + true)); + FAIL_IF_NOT(UTHParseSignature( + "alert http any any -> any any (flow:to_client; http.response_body; bsize:10; sid:1;)", + true)); + + FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_client; " + "http.response_body; content:\"abc\"; rawbytes; sid:1;)", + false)); + FAIL_IF_NOT(UTHParseSignature( + "alert tcp any any -> any any (flow:to_client; http.response_body; sid:1;)", false)); + FAIL_IF_NOT(UTHParseSignature("alert tls any any -> any any (flow:to_client; " + "http.response_body; content:\"abc\"; sid:1;)", + false)); PASS; } struct TestSteps { const uint8_t *input; - size_t input_size; /**< if 0 strlen will be used */ - int direction; /**< STREAM_TOSERVER, STREAM_TOCLIENT */ + size_t input_size; /**< if 0 strlen will be used */ + int direction; /**< STREAM_TOSERVER, STREAM_TOCLIENT */ int expect; }; @@ -124,7 +157,7 @@ static int RunTest(struct TestSteps *steps, const char *sig, const char *yaml) p->flow = &f; p->flowflags = (b->direction == STREAM_TOSERVER) ? FLOW_PKT_TOSERVER : FLOW_PKT_TOCLIENT; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_HTTP1, b->direction, (uint8_t *)b->input, @@ -167,18 +200,17 @@ static int DetectEngineHttpServerBodyTest01(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf1[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len1 = sizeof(http_buf1) - 1; - uint8_t http_buf2[] = - "HTTP/1.0 200 ok\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 7\r\n" - "\r\n" - "message"; + uint8_t http_buf2[] = "HTTP/1.0 200 ok\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 7\r\n" + "\r\n" + "message"; uint32_t http_len2 = sizeof(http_buf2) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -198,11 +230,11 @@ static int DetectEngineHttpServerBodyTest01(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOCLIENT; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -213,10 +245,10 @@ static int DetectEngineHttpServerBodyTest01(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http server body test\"; " - "content:\"message\"; http_server_body; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http server body test\"; " + "content:\"message\"; http_server_body; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -286,18 +318,17 @@ static int DetectEngineHttpServerBodyTest02(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf1[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len1 = sizeof(http_buf1) - 1; - uint8_t http_buf2[] = - "HTTP/1.0 200 ok\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 7\r\n" - "\r\n" - "xxxxABC"; + uint8_t http_buf2[] = "HTTP/1.0 200 ok\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 7\r\n" + "\r\n" + "xxxxABC"; uint32_t http_len2 = sizeof(http_buf2) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -316,7 +347,7 @@ static int DetectEngineHttpServerBodyTest02(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOCLIENT; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -327,10 +358,10 @@ static int DetectEngineHttpServerBodyTest02(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http server body test\"; " - "content:\"ABC\"; http_server_body; offset:4; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http server body test\"; " + "content:\"ABC\"; http_server_body; offset:4; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -393,21 +424,19 @@ static int DetectEngineHttpServerBodyTest03(void) HtpState *http_state = NULL; Flow f; int result = 0; - uint8_t http_buf1[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len1 = sizeof(http_buf1) - 1; - uint8_t http_buf2[] = - "HTTP/1.0 200 ok\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 17\r\n" - "\r\n" - "1234567"; + uint8_t http_buf2[] = "HTTP/1.0 200 ok\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 17\r\n" + "\r\n" + "1234567"; uint32_t http_len2 = sizeof(http_buf2) - 1; - uint8_t http_buf3[] = - "8901234ABC"; + uint8_t http_buf3[] = "8901234ABC"; uint32_t http_len3 = sizeof(http_buf3) - 1; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -426,11 +455,11 @@ static int DetectEngineHttpServerBodyTest03(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOCLIENT; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -441,10 +470,10 @@ static int DetectEngineHttpServerBodyTest03(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http server body test\"; " - "content:\"ABC\"; http_server_body; offset:14; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http server body test\"; " + "content:\"ABC\"; http_server_body; offset:14; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -523,18 +552,17 @@ static int DetectEngineHttpServerBodyTest04(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf1[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len1 = sizeof(http_buf1) - 1; - uint8_t http_buf2[] = - "HTTP/1.0 200 ok\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 6\r\n" - "\r\n" - "abcdef"; + uint8_t http_buf2[] = "HTTP/1.0 200 ok\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 6\r\n" + "\r\n" + "abcdef"; uint32_t http_len2 = sizeof(http_buf2) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -554,11 +582,11 @@ static int DetectEngineHttpServerBodyTest04(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOCLIENT; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -569,10 +597,10 @@ static int DetectEngineHttpServerBodyTest04(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http server body test\"; " - "content:!\"abc\"; http_server_body; offset:3; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http server body test\"; " + "content:!\"abc\"; http_server_body; offset:3; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -643,18 +671,17 @@ static int DetectEngineHttpServerBodyTest05(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf1[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len1 = sizeof(http_buf1) - 1; - uint8_t http_buf2[] = - "HTTP/1.0 200 ok\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 6\r\n" - "\r\n" - "abcdef"; + uint8_t http_buf2[] = "HTTP/1.0 200 ok\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 6\r\n" + "\r\n" + "abcdef"; uint32_t http_len2 = sizeof(http_buf2) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -674,11 +701,11 @@ static int DetectEngineHttpServerBodyTest05(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOCLIENT; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -689,10 +716,10 @@ static int DetectEngineHttpServerBodyTest05(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http server body test\"; " - "content:\"abc\"; http_server_body; depth:3; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http server body test\"; " + "content:\"abc\"; http_server_body; depth:3; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -763,18 +790,17 @@ static int DetectEngineHttpServerBodyTest06(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf1[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len1 = sizeof(http_buf1) - 1; - uint8_t http_buf2[] = - "HTTP/1.0 200 ok\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 6\r\n" - "\r\n" - "abcdef"; + uint8_t http_buf2[] = "HTTP/1.0 200 ok\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 6\r\n" + "\r\n" + "abcdef"; uint32_t http_len2 = sizeof(http_buf2) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -794,11 +820,11 @@ static int DetectEngineHttpServerBodyTest06(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOCLIENT; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -809,10 +835,10 @@ static int DetectEngineHttpServerBodyTest06(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http server body test\"; " - "content:!\"def\"; http_server_body; depth:3; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http server body test\"; " + "content:!\"def\"; http_server_body; depth:3; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -883,18 +909,17 @@ static int DetectEngineHttpServerBodyTest07(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf1[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len1 = sizeof(http_buf1) - 1; - uint8_t http_buf2[] = - "HTTP/1.0 200 ok\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 6\r\n" - "\r\n" - "abcdef"; + uint8_t http_buf2[] = "HTTP/1.0 200 ok\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 6\r\n" + "\r\n" + "abcdef"; uint32_t http_len2 = sizeof(http_buf2) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -914,11 +939,11 @@ static int DetectEngineHttpServerBodyTest07(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOCLIENT; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -929,10 +954,10 @@ static int DetectEngineHttpServerBodyTest07(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http server body test\"; " - "content:!\"def\"; http_server_body; offset:3; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http server body test\"; " + "content:!\"def\"; http_server_body; offset:3; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -1003,18 +1028,17 @@ static int DetectEngineHttpServerBodyTest08(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf1[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len1 = sizeof(http_buf1) - 1; - uint8_t http_buf2[] = - "HTTP/1.0 200 ok\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 6\r\n" - "\r\n" - "abcdef"; + uint8_t http_buf2[] = "HTTP/1.0 200 ok\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 6\r\n" + "\r\n" + "abcdef"; uint32_t http_len2 = sizeof(http_buf2) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -1034,11 +1058,11 @@ static int DetectEngineHttpServerBodyTest08(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOCLIENT; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1049,10 +1073,10 @@ static int DetectEngineHttpServerBodyTest08(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http server body test\"; " - "content:!\"abc\"; http_server_body; depth:3; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http server body test\"; " + "content:!\"abc\"; http_server_body; depth:3; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -1123,18 +1147,17 @@ static int DetectEngineHttpServerBodyTest09(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf1[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len1 = sizeof(http_buf1) - 1; - uint8_t http_buf2[] = - "HTTP/1.0 200 ok\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 6\r\n" - "\r\n" - "abcdef"; + uint8_t http_buf2[] = "HTTP/1.0 200 ok\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 6\r\n" + "\r\n" + "abcdef"; uint32_t http_len2 = sizeof(http_buf2) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -1154,11 +1177,11 @@ static int DetectEngineHttpServerBodyTest09(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOCLIENT; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1169,11 +1192,11 @@ static int DetectEngineHttpServerBodyTest09(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http server body test\"; " - "content:\"abc\"; http_server_body; depth:3; " - "content:\"def\"; http_server_body; within:3; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http server body test\"; " + "content:\"abc\"; http_server_body; depth:3; " + "content:\"def\"; http_server_body; within:3; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -1244,18 +1267,17 @@ static int DetectEngineHttpServerBodyTest10(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf1[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len1 = sizeof(http_buf1) - 1; - uint8_t http_buf2[] = - "HTTP/1.0 200 ok\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 6\r\n" - "\r\n" - "abcdef"; + uint8_t http_buf2[] = "HTTP/1.0 200 ok\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 6\r\n" + "\r\n" + "abcdef"; uint32_t http_len2 = sizeof(http_buf2) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -1275,11 +1297,11 @@ static int DetectEngineHttpServerBodyTest10(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOCLIENT; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1290,11 +1312,11 @@ static int DetectEngineHttpServerBodyTest10(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http server body test\"; " - "content:\"abc\"; http_server_body; depth:3; " - "content:!\"xyz\"; http_server_body; within:3; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http server body test\"; " + "content:\"abc\"; http_server_body; depth:3; " + "content:!\"xyz\"; http_server_body; within:3; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -1365,18 +1387,17 @@ static int DetectEngineHttpServerBodyTest11(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf1[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len1 = sizeof(http_buf1) - 1; - uint8_t http_buf2[] = - "HTTP/1.0 200 ok\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 6\r\n" - "\r\n" - "abcdef"; + uint8_t http_buf2[] = "HTTP/1.0 200 ok\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 6\r\n" + "\r\n" + "abcdef"; uint32_t http_len2 = sizeof(http_buf2) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -1396,11 +1417,11 @@ static int DetectEngineHttpServerBodyTest11(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOCLIENT; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1411,11 +1432,11 @@ static int DetectEngineHttpServerBodyTest11(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http server body test\"; " - "content:\"abc\"; http_server_body; depth:3; " - "content:\"xyz\"; http_server_body; within:3; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http server body test\"; " + "content:\"abc\"; http_server_body; depth:3; " + "content:\"xyz\"; http_server_body; within:3; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -1486,18 +1507,17 @@ static int DetectEngineHttpServerBodyTest12(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf1[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len1 = sizeof(http_buf1) - 1; - uint8_t http_buf2[] = - "HTTP/1.0 200 ok\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 6\r\n" - "\r\n" - "abcdef"; + uint8_t http_buf2[] = "HTTP/1.0 200 ok\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 6\r\n" + "\r\n" + "abcdef"; uint32_t http_len2 = sizeof(http_buf2) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -1517,11 +1537,11 @@ static int DetectEngineHttpServerBodyTest12(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOCLIENT; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1532,11 +1552,11 @@ static int DetectEngineHttpServerBodyTest12(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http server body test\"; " - "content:\"ab\"; http_server_body; depth:2; " - "content:\"ef\"; http_server_body; distance:2; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http server body test\"; " + "content:\"ab\"; http_server_body; depth:2; " + "content:\"ef\"; http_server_body; distance:2; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -1607,18 +1627,17 @@ static int DetectEngineHttpServerBodyTest13(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf1[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len1 = sizeof(http_buf1) - 1; - uint8_t http_buf2[] = - "HTTP/1.0 200 ok\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 6\r\n" - "\r\n" - "abcdef"; + uint8_t http_buf2[] = "HTTP/1.0 200 ok\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 6\r\n" + "\r\n" + "abcdef"; uint32_t http_len2 = sizeof(http_buf2) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -1638,11 +1657,11 @@ static int DetectEngineHttpServerBodyTest13(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOCLIENT; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1653,11 +1672,11 @@ static int DetectEngineHttpServerBodyTest13(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http server body test\"; " - "content:\"ab\"; http_server_body; depth:3; " - "content:!\"yz\"; http_server_body; distance:2; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http server body test\"; " + "content:\"ab\"; http_server_body; depth:3; " + "content:!\"yz\"; http_server_body; distance:2; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -1728,18 +1747,17 @@ static int DetectEngineHttpServerBodyTest14(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf1[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len1 = sizeof(http_buf1) - 1; - uint8_t http_buf2[] = - "HTTP/1.0 200 ok\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 6\r\n" - "\r\n" - "abcdef"; + uint8_t http_buf2[] = "HTTP/1.0 200 ok\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 6\r\n" + "\r\n" + "abcdef"; uint32_t http_len2 = sizeof(http_buf2) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -1759,11 +1777,11 @@ static int DetectEngineHttpServerBodyTest14(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOCLIENT; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1774,11 +1792,11 @@ static int DetectEngineHttpServerBodyTest14(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http server body test\"; " - "pcre:/ab/Q; " - "content:\"ef\"; http_server_body; distance:2; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http server body test\"; " + "pcre:/ab/Q; " + "content:\"ef\"; http_server_body; distance:2; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -1849,18 +1867,17 @@ static int DetectEngineHttpServerBodyTest15(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf1[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len1 = sizeof(http_buf1) - 1; - uint8_t http_buf2[] = - "HTTP/1.0 200 ok\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 6\r\n" - "\r\n" - "abcdef"; + uint8_t http_buf2[] = "HTTP/1.0 200 ok\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 6\r\n" + "\r\n" + "abcdef"; uint32_t http_len2 = sizeof(http_buf2) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -1880,11 +1897,11 @@ static int DetectEngineHttpServerBodyTest15(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOCLIENT; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1895,11 +1912,11 @@ static int DetectEngineHttpServerBodyTest15(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http server body test\"; " - "pcre:/abc/Q; " - "content:!\"xyz\"; http_server_body; distance:0; within:3; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http server body test\"; " + "pcre:/abc/Q; " + "content:!\"xyz\"; http_server_body; distance:0; within:3; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -1994,21 +2011,19 @@ libhtp:\n\ HtpState *http_state = NULL; Flow f; int result = 0; - uint8_t http_buf1[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len1 = sizeof(http_buf1) - 1; - uint8_t http_buf2[] = - "HTTP/1.0 200 ok\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 17\r\n" - "\r\n" - "1234567"; + uint8_t http_buf2[] = "HTTP/1.0 200 ok\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 17\r\n" + "\r\n" + "1234567"; uint32_t http_len2 = sizeof(http_buf2) - 1; - uint8_t http_buf3[] = - "8901234ABC"; + uint8_t http_buf3[] = "8901234ABC"; uint32_t http_len3 = sizeof(http_buf3) - 1; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -2027,11 +2042,11 @@ libhtp:\n\ p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOCLIENT; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -2042,10 +2057,10 @@ libhtp:\n\ de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http server body test\"; " - "content:\"890\"; within:3; http_server_body; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http server body test\"; " + "content:\"890\"; within:3; http_server_body; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -2159,21 +2174,19 @@ libhtp:\n\ DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf1[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len1 = sizeof(http_buf1) - 1; - uint8_t http_buf2[] = - "HTTP/1.0 200 ok\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 17\r\n" - "\r\n" - "1234567"; + uint8_t http_buf2[] = "HTTP/1.0 200 ok\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 17\r\n" + "\r\n" + "1234567"; uint32_t http_len2 = sizeof(http_buf2) - 1; - uint8_t http_buf3[] = - "8901234ABC"; + uint8_t http_buf3[] = "8901234ABC"; uint32_t http_len3 = sizeof(http_buf3) - 1; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -2192,11 +2205,11 @@ libhtp:\n\ p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOCLIENT; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -2269,11 +2282,11 @@ static int DetectEngineHttpServerBodyTest18(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf1[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len1 = sizeof(http_buf1) - 1; // clang-format off uint8_t http_buf2[] = { @@ -2309,11 +2322,11 @@ static int DetectEngineHttpServerBodyTest18(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOCLIENT; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -2324,10 +2337,10 @@ static int DetectEngineHttpServerBodyTest18(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http server body test\"; " - "content:\"file\"; http_server_body; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http server body test\"; " + "content:\"file\"; http_server_body; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -2401,11 +2414,11 @@ static int DetectEngineHttpServerBodyTest19(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf1[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len1 = sizeof(http_buf1) - 1; // clang-format off uint8_t http_buf2[] = { @@ -2439,11 +2452,11 @@ static int DetectEngineHttpServerBodyTest19(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOCLIENT; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -2454,10 +2467,10 @@ static int DetectEngineHttpServerBodyTest19(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http server body test\"; " - "content:\"file\"; http_server_body; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http server body test\"; " + "content:\"file\"; http_server_body; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -2531,11 +2544,11 @@ static int DetectEngineHttpServerBodyTest20(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf1[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len1 = sizeof(http_buf1) - 1; // clang-format off uint8_t http_buf2[] = { @@ -2569,11 +2582,11 @@ static int DetectEngineHttpServerBodyTest20(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOCLIENT; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -2584,10 +2597,10 @@ static int DetectEngineHttpServerBodyTest20(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http server body test\"; " - "content:\"file\"; http_server_body; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http server body test\"; " + "content:\"file\"; http_server_body; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -2660,11 +2673,11 @@ static int DetectEngineHttpServerBodyTest21(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf1[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len1 = sizeof(http_buf1) - 1; // clang-format off uint8_t http_buf2[] = { @@ -2700,11 +2713,11 @@ static int DetectEngineHttpServerBodyTest21(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOCLIENT; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -2715,10 +2728,10 @@ static int DetectEngineHttpServerBodyTest21(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http server body test\"; " - "content:\"file\"; http_server_body; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http server body test\"; " + "content:\"file\"; http_server_body; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -2792,11 +2805,11 @@ static int DetectEngineHttpServerBodyTest22(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf1[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len1 = sizeof(http_buf1) - 1; // clang-format off uint8_t http_buf2[] = { @@ -2833,11 +2846,11 @@ static int DetectEngineHttpServerBodyTest22(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOCLIENT; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -2848,10 +2861,10 @@ static int DetectEngineHttpServerBodyTest22(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http server body test\"; " - "content:\"file\"; http_server_body; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http server body test\"; " + "content:\"file\"; http_server_body; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -2921,18 +2934,17 @@ static int DetectEngineHttpServerBodyFileDataTest01(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf1[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len1 = sizeof(http_buf1) - 1; - uint8_t http_buf2[] = - "HTTP/1.0 200 ok\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 6\r\n" - "\r\n" - "abcdef"; + uint8_t http_buf2[] = "HTTP/1.0 200 ok\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 6\r\n" + "\r\n" + "abcdef"; uint32_t http_len2 = sizeof(http_buf2) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -2952,11 +2964,11 @@ static int DetectEngineHttpServerBodyFileDataTest01(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOCLIENT; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -2967,11 +2979,11 @@ static int DetectEngineHttpServerBodyFileDataTest01(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http server body test\"; " - "file_data; pcre:/ab/; " - "content:\"ef\"; distance:2; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http server body test\"; " + "file_data; pcre:/ab/; " + "content:\"ef\"; distance:2; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -3042,18 +3054,17 @@ static int DetectEngineHttpServerBodyFileDataTest02(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf1[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len1 = sizeof(http_buf1) - 1; - uint8_t http_buf2[] = - "HTTP/1.0 200 ok\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 6\r\n" - "\r\n" - "abcdef"; + uint8_t http_buf2[] = "HTTP/1.0 200 ok\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 6\r\n" + "\r\n" + "abcdef"; uint32_t http_len2 = sizeof(http_buf2) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -3073,11 +3084,11 @@ static int DetectEngineHttpServerBodyFileDataTest02(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOCLIENT; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -3088,11 +3099,11 @@ static int DetectEngineHttpServerBodyFileDataTest02(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http server body test\"; " - "file_data; pcre:/abc/; " - "content:!\"xyz\"; distance:0; within:3; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http server body test\"; " + "file_data; pcre:/abc/; " + "content:!\"xyz\"; distance:0; within:3; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -3163,18 +3174,17 @@ static int DetectEngineHttpServerBodyFileDataTest03(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf1[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len1 = sizeof(http_buf1) - 1; - uint8_t http_buf2[] = - "HTTP/1.0 200 ok\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 33\r\n" - "\r\n" - "XYZ_klm_1234abcd_XYZ_klm_5678abcd"; + uint8_t http_buf2[] = "HTTP/1.0 200 ok\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 33\r\n" + "\r\n" + "XYZ_klm_1234abcd_XYZ_klm_5678abcd"; uint32_t http_len2 = sizeof(http_buf2) - 1; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -3193,11 +3203,11 @@ static int DetectEngineHttpServerBodyFileDataTest03(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOCLIENT; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -3269,22 +3279,21 @@ libhtp:\n\ "; struct TestSteps steps[] = { - { (const uint8_t *)"GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n", - 0, STREAM_TOSERVER, 0 }, - { (const uint8_t *)"HTTP/1.0 200 ok\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 6\r\n" - "\r\n" - "ab", - 0, STREAM_TOCLIENT, 0 }, - { (const uint8_t *)"cd", - 0, STREAM_TOCLIENT, 1 }, - { (const uint8_t *)"ef", - 0, STREAM_TOCLIENT, 0 }, - { NULL, 0, 0, 0 }, + { (const uint8_t *)"GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n", + 0, STREAM_TOSERVER, 0 }, + { (const uint8_t *)"HTTP/1.0 200 ok\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 6\r\n" + "\r\n" + "ab", + 0, STREAM_TOCLIENT, 0 }, + { (const uint8_t *)"cd", 0, STREAM_TOCLIENT, 1 }, + { (const uint8_t *)"ef", 0, STREAM_TOCLIENT, 0 }, + { NULL, 0, 0, 0 }, }; const char *sig = "alert http any any -> any any (file_data; content:\"abcd\"; sid:1;)"; @@ -3307,22 +3316,21 @@ libhtp:\n\ "; struct TestSteps steps[] = { - { (const uint8_t *)"GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n", - 0, STREAM_TOSERVER, 0 }, - { (const uint8_t *)"HTTP/1.0 200 ok\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 6\r\n" - "\r\n" - "ab", - 0, STREAM_TOCLIENT, 0 }, - { (const uint8_t *)"cd", - 0, STREAM_TOCLIENT, 0 }, - { (const uint8_t *)"ef", - 0, STREAM_TOCLIENT, 1 }, - { NULL, 0, 0, 0 }, + { (const uint8_t *)"GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n", + 0, STREAM_TOSERVER, 0 }, + { (const uint8_t *)"HTTP/1.0 200 ok\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 6\r\n" + "\r\n" + "ab", + 0, STREAM_TOCLIENT, 0 }, + { (const uint8_t *)"cd", 0, STREAM_TOCLIENT, 0 }, + { (const uint8_t *)"ef", 0, STREAM_TOCLIENT, 1 }, + { NULL, 0, 0, 0 }, }; const char *sig = "alert http any any -> any any (file_data; content:\"abcdef\"; sid:1;)"; @@ -3345,25 +3353,25 @@ libhtp:\n\ "; struct TestSteps steps[] = { - { (const uint8_t *)"GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n", - 0, STREAM_TOSERVER, 0 }, - { (const uint8_t *)"HTTP/1.0 200 ok\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 6\r\n" - "\r\n" - "ab", - 0, STREAM_TOCLIENT, 0 }, - { (const uint8_t *)"cd", - 0, STREAM_TOCLIENT, 0 }, - { (const uint8_t *)"ef", - 0, STREAM_TOCLIENT, 1 }, - { NULL, 0, 0, 0 }, + { (const uint8_t *)"GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n", + 0, STREAM_TOSERVER, 0 }, + { (const uint8_t *)"HTTP/1.0 200 ok\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 6\r\n" + "\r\n" + "ab", + 0, STREAM_TOCLIENT, 0 }, + { (const uint8_t *)"cd", 0, STREAM_TOCLIENT, 0 }, + { (const uint8_t *)"ef", 0, STREAM_TOCLIENT, 1 }, + { NULL, 0, 0, 0 }, }; - const char *sig = "alert http any any -> any any (file_data; content:\"bcdef\"; offset:1; sid:1;)"; + const char *sig = + "alert http any any -> any any (file_data; content:\"bcdef\"; offset:1; sid:1;)"; return RunTest(steps, sig, yaml); } @@ -3383,25 +3391,25 @@ libhtp:\n\ "; struct TestSteps steps[] = { - { (const uint8_t *)"GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n", - 0, STREAM_TOSERVER, 0 }, - { (const uint8_t *)"HTTP/1.0 200 ok\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 13\r\n" - "\r\n" - "ab", - 0, STREAM_TOCLIENT, 0 }, - { (const uint8_t *)"cd", - 0, STREAM_TOCLIENT, 1 }, - { (const uint8_t *)"123456789", - 0, STREAM_TOCLIENT, 0 }, - { NULL, 0, 0, 0 }, + { (const uint8_t *)"GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n", + 0, STREAM_TOSERVER, 0 }, + { (const uint8_t *)"HTTP/1.0 200 ok\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 13\r\n" + "\r\n" + "ab", + 0, STREAM_TOCLIENT, 0 }, + { (const uint8_t *)"cd", 0, STREAM_TOCLIENT, 1 }, + { (const uint8_t *)"123456789", 0, STREAM_TOCLIENT, 0 }, + { NULL, 0, 0, 0 }, }; - const char *sig = "alert http any any -> any any (file_data; content:\"bc\"; offset:1; depth:2; sid:1;)"; + const char *sig = + "alert http any any -> any any (file_data; content:\"bc\"; offset:1; depth:2; sid:1;)"; return RunTest(steps, sig, yaml); } @@ -3421,25 +3429,25 @@ libhtp:\n\ "; struct TestSteps steps[] = { - { (const uint8_t *)"GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n", - 0, STREAM_TOSERVER, 0 }, - { (const uint8_t *)"HTTP/1.0 200 ok\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 14\r\n" - "\r\n" - "ab", - 0, STREAM_TOCLIENT, 0 }, - { (const uint8_t *)"cd", - 0, STREAM_TOCLIENT, 0 }, - { (const uint8_t *)"1234567890", - 0, STREAM_TOCLIENT, 1 }, - { NULL, 0, 0, 0 }, + { (const uint8_t *)"GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n", + 0, STREAM_TOSERVER, 0 }, + { (const uint8_t *)"HTTP/1.0 200 ok\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 14\r\n" + "\r\n" + "ab", + 0, STREAM_TOCLIENT, 0 }, + { (const uint8_t *)"cd", 0, STREAM_TOCLIENT, 0 }, + { (const uint8_t *)"1234567890", 0, STREAM_TOCLIENT, 1 }, + { NULL, 0, 0, 0 }, }; - const char *sig = "alert http any any -> any any (file_data; content:\"d123456789\"; offset:3; sid:1;)"; + const char *sig = + "alert http any any -> any any (file_data; content:\"d123456789\"; offset:3; sid:1;)"; return RunTest(steps, sig, yaml); } @@ -3459,25 +3467,25 @@ libhtp:\n\ "; struct TestSteps steps[] = { - { (const uint8_t *)"GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n", - 0, STREAM_TOSERVER, 0 }, - { (const uint8_t *)"HTTP/1.0 200 ok\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 13\r\n" - "\r\n" - "ab", - 0, STREAM_TOCLIENT, 0 }, - { (const uint8_t *)"cd", - 0, STREAM_TOCLIENT, 0 }, - { (const uint8_t *)"123456789", - 0, STREAM_TOCLIENT, 1 }, - { NULL, 0, 0, 0 }, + { (const uint8_t *)"GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n", + 0, STREAM_TOSERVER, 0 }, + { (const uint8_t *)"HTTP/1.0 200 ok\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 13\r\n" + "\r\n" + "ab", + 0, STREAM_TOCLIENT, 0 }, + { (const uint8_t *)"cd", 0, STREAM_TOCLIENT, 0 }, + { (const uint8_t *)"123456789", 0, STREAM_TOCLIENT, 1 }, + { NULL, 0, 0, 0 }, }; - const char *sig = "alert http any any -> any any (file_data; content:\"abcd12\"; depth:6; sid:1;)"; + const char *sig = + "alert http any any -> any any (file_data; content:\"abcd12\"; depth:6; sid:1;)"; return RunTest(steps, sig, yaml); } @@ -3497,22 +3505,21 @@ libhtp:\n\ "; struct TestSteps steps[] = { - { (const uint8_t *)"GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n", - 0, STREAM_TOSERVER, 0 }, - { (const uint8_t *)"HTTP/1.0 200 ok\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 5\r\n" - "\r\n" - "ab", - 0, STREAM_TOCLIENT, 0 }, - { (const uint8_t *)"c", - 0, STREAM_TOCLIENT, 1 }, - { (const uint8_t *)"de", - 0, STREAM_TOCLIENT, 0 }, - { NULL, 0, 0, 0 }, + { (const uint8_t *)"GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n", + 0, STREAM_TOSERVER, 0 }, + { (const uint8_t *)"HTTP/1.0 200 ok\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 5\r\n" + "\r\n" + "ab", + 0, STREAM_TOCLIENT, 0 }, + { (const uint8_t *)"c", 0, STREAM_TOCLIENT, 1 }, + { (const uint8_t *)"de", 0, STREAM_TOCLIENT, 0 }, + { NULL, 0, 0, 0 }, }; const char *sig = "alert http any any -> any any (file_data; content:\"abc\"; depth:3; sid:1;)"; @@ -3535,25 +3542,25 @@ libhtp:\n\ "; struct TestSteps steps[] = { - { (const uint8_t *)"GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n", - 0, STREAM_TOSERVER, 0 }, - { (const uint8_t *)"HTTP/1.0 200 ok\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 5\r\n" - "\r\n" - "ab", - 0, STREAM_TOCLIENT, 0 }, - { (const uint8_t *)"c", - 0, STREAM_TOCLIENT, 0 }, - { (const uint8_t *)"de", - 0, STREAM_TOCLIENT, 1 }, - { NULL, 0, 0, 0 }, + { (const uint8_t *)"GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n", + 0, STREAM_TOSERVER, 0 }, + { (const uint8_t *)"HTTP/1.0 200 ok\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 5\r\n" + "\r\n" + "ab", + 0, STREAM_TOCLIENT, 0 }, + { (const uint8_t *)"c", 0, STREAM_TOCLIENT, 0 }, + { (const uint8_t *)"de", 0, STREAM_TOCLIENT, 1 }, + { NULL, 0, 0, 0 }, }; - const char *sig = "alert http any any -> any any (file_data; content:\"bcde\"; offset:1; depth:4; sid:1;)"; + const char *sig = "alert http any any -> any any (file_data; content:\"bcde\"; offset:1; " + "depth:4; sid:1;)"; return RunTest(steps, sig, yaml); } @@ -3573,26 +3580,23 @@ libhtp:\n\ "; struct TestSteps steps[] = { - { (const uint8_t *)"GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n", - 0, STREAM_TOSERVER, 0 }, - { (const uint8_t *)"HTTP/1.0 200 ok\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 13\r\n" - "\r\n" - "a", - 0, STREAM_TOCLIENT, 0 }, - { (const uint8_t *)"b", - 0, STREAM_TOCLIENT, 0 }, - { (const uint8_t *)"c", - 0, STREAM_TOCLIENT, 0 }, - { (const uint8_t *)"d", - 0, STREAM_TOCLIENT, 1 }, - { (const uint8_t *)"efghijklm", - 0, STREAM_TOCLIENT, 0 }, - { NULL, 0, 0, 0 }, + { (const uint8_t *)"GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n", + 0, STREAM_TOSERVER, 0 }, + { (const uint8_t *)"HTTP/1.0 200 ok\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 13\r\n" + "\r\n" + "a", + 0, STREAM_TOCLIENT, 0 }, + { (const uint8_t *)"b", 0, STREAM_TOCLIENT, 0 }, + { (const uint8_t *)"c", 0, STREAM_TOCLIENT, 0 }, + { (const uint8_t *)"d", 0, STREAM_TOCLIENT, 1 }, + { (const uint8_t *)"efghijklm", 0, STREAM_TOCLIENT, 0 }, + { NULL, 0, 0, 0 }, }; const char *sig = "alert http any any -> any any (file_data; content:\"abcd\"; sid:1;)"; @@ -3615,29 +3619,27 @@ libhtp:\n\ "; struct TestSteps steps[] = { - { (const uint8_t *)"GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n", - 0, STREAM_TOSERVER, 0 }, - { (const uint8_t *)"HTTP/1.0 200 ok\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 13\r\n" - "\r\n" - "a", - 0, STREAM_TOCLIENT, 0 }, - { (const uint8_t *)"b", - 0, STREAM_TOCLIENT, 0 }, - { (const uint8_t *)"c", - 0, STREAM_TOCLIENT, 0 }, - { (const uint8_t *)"d", - 0, STREAM_TOCLIENT, 0 }, - { (const uint8_t *)"efghijklm", - 0, STREAM_TOCLIENT, 1 }, - { NULL, 0, 0, 0 }, + { (const uint8_t *)"GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n", + 0, STREAM_TOSERVER, 0 }, + { (const uint8_t *)"HTTP/1.0 200 ok\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 13\r\n" + "\r\n" + "a", + 0, STREAM_TOCLIENT, 0 }, + { (const uint8_t *)"b", 0, STREAM_TOCLIENT, 0 }, + { (const uint8_t *)"c", 0, STREAM_TOCLIENT, 0 }, + { (const uint8_t *)"d", 0, STREAM_TOCLIENT, 0 }, + { (const uint8_t *)"efghijklm", 0, STREAM_TOCLIENT, 1 }, + { NULL, 0, 0, 0 }, }; - const char *sig = "alert http any any -> any any (file_data; content:\"abcdefghijklm\"; sid:1;)"; + const char *sig = + "alert http any any -> any any (file_data; content:\"abcdefghijklm\"; sid:1;)"; return RunTest(steps, sig, yaml); } @@ -3657,20 +3659,20 @@ libhtp:\n\ "; struct TestSteps steps[] = { - { (const uint8_t *)"GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n", - 0, STREAM_TOSERVER, 0 }, - { (const uint8_t *)"HTTP/1.0 200 ok\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 20\r\n" - "\r\n" - "1234567890", - 0, STREAM_TOCLIENT, 0 }, - { (const uint8_t *)"abcdefghi", - 0, STREAM_TOCLIENT, 1 }, - { NULL, 0, 0, 0 }, + { (const uint8_t *)"GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n", + 0, STREAM_TOSERVER, 0 }, + { (const uint8_t *)"HTTP/1.0 200 ok\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 20\r\n" + "\r\n" + "1234567890", + 0, STREAM_TOCLIENT, 0 }, + { (const uint8_t *)"abcdefghi", 0, STREAM_TOCLIENT, 1 }, + { NULL, 0, 0, 0 }, }; const char *sig = "alert http any any -> any any (file_data; content:\"890abcdefghi\"; sid:1;)"; @@ -3693,23 +3695,24 @@ libhtp:\n\ "; struct TestSteps steps[] = { - { (const uint8_t *)"GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n", - 0, STREAM_TOSERVER, 0 }, - { (const uint8_t *)"HTTP/1.0 200 ok\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 20\r\n" - "\r\n" - "1234567890", - 0, STREAM_TOCLIENT, 0 }, - { (const uint8_t *)"abcdefghi", - 0, STREAM_TOCLIENT, 0 }, - { NULL, 0, 0, 0 }, + { (const uint8_t *)"GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n", + 0, STREAM_TOSERVER, 0 }, + { (const uint8_t *)"HTTP/1.0 200 ok\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 20\r\n" + "\r\n" + "1234567890", + 0, STREAM_TOCLIENT, 0 }, + { (const uint8_t *)"abcdefghi", 0, STREAM_TOCLIENT, 0 }, + { NULL, 0, 0, 0 }, }; - const char *sig = "alert http any any -> any any (file_data; content:\"7890ab\"; depth:6; sid:1;)"; + const char *sig = + "alert http any any -> any any (file_data; content:\"7890ab\"; depth:6; sid:1;)"; return RunTest(steps, sig, yaml); } @@ -3729,27 +3732,26 @@ libhtp:\n\ "; struct TestSteps steps[] = { - { (const uint8_t *)"GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n", - 0, STREAM_TOSERVER, 0 }, - { (const uint8_t *)"HTTP/1.0 200 ok\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 20\r\n" - "\r\n" - "aaaab", - 0, STREAM_TOCLIENT, 0 }, - { (const uint8_t *)"bbbbc", - 0, STREAM_TOCLIENT, 0 }, - { (const uint8_t *)"ccccd", - 0, STREAM_TOCLIENT, 0 }, - { (const uint8_t *)"dddde", - 0, STREAM_TOCLIENT, 0 }, - { NULL, 0, 0, 0 }, + { (const uint8_t *)"GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n", + 0, STREAM_TOSERVER, 0 }, + { (const uint8_t *)"HTTP/1.0 200 ok\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 20\r\n" + "\r\n" + "aaaab", + 0, STREAM_TOCLIENT, 0 }, + { (const uint8_t *)"bbbbc", 0, STREAM_TOCLIENT, 0 }, + { (const uint8_t *)"ccccd", 0, STREAM_TOCLIENT, 0 }, + { (const uint8_t *)"dddde", 0, STREAM_TOCLIENT, 0 }, + { NULL, 0, 0, 0 }, }; - const char *sig = "alert http any any -> any any (file_data; content:\"aabb\"; depth:4; sid:1;)"; + const char *sig = + "alert http any any -> any any (file_data; content:\"aabb\"; depth:4; sid:1;)"; return RunTest(steps, sig, yaml); } @@ -3769,27 +3771,26 @@ libhtp:\n\ "; struct TestSteps steps[] = { - { (const uint8_t *)"GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n", - 0, STREAM_TOSERVER, 0 }, - { (const uint8_t *)"HTTP/1.0 200 ok\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 20\r\n" - "\r\n" - "aaaab", - 0, STREAM_TOCLIENT, 0 }, - { (const uint8_t *)"bbbbc", - 0, STREAM_TOCLIENT, 0 }, - { (const uint8_t *)"ccccd", - 0, STREAM_TOCLIENT, 0 }, - { (const uint8_t *)"dddde", - 0, STREAM_TOCLIENT, 0 }, - { NULL, 0, 0, 0 }, + { (const uint8_t *)"GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n", + 0, STREAM_TOSERVER, 0 }, + { (const uint8_t *)"HTTP/1.0 200 ok\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 20\r\n" + "\r\n" + "aaaab", + 0, STREAM_TOCLIENT, 0 }, + { (const uint8_t *)"bbbbc", 0, STREAM_TOCLIENT, 0 }, + { (const uint8_t *)"ccccd", 0, STREAM_TOCLIENT, 0 }, + { (const uint8_t *)"dddde", 0, STREAM_TOCLIENT, 0 }, + { NULL, 0, 0, 0 }, }; - const char *sig = "alert http any any -> any any (file_data; content:\"bbbc\"; depth:4; sid:1;)"; + const char *sig = + "alert http any any -> any any (file_data; content:\"bbbc\"; depth:4; sid:1;)"; return RunTest(steps, sig, yaml); } @@ -3809,27 +3810,26 @@ libhtp:\n\ "; struct TestSteps steps[] = { - { (const uint8_t *)"GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n", - 0, STREAM_TOSERVER, 0 }, - { (const uint8_t *)"HTTP/1.0 200 ok\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 20\r\n" - "\r\n" - "aaaab", - 0, STREAM_TOCLIENT, 0 }, - { (const uint8_t *)"bbbbc", - 0, STREAM_TOCLIENT, 0 }, - { (const uint8_t *)"ccccd", - 0, STREAM_TOCLIENT, 0 }, - { (const uint8_t *)"dddde", - 0, STREAM_TOCLIENT, 0 }, - { NULL, 0, 0, 0 }, + { (const uint8_t *)"GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n", + 0, STREAM_TOSERVER, 0 }, + { (const uint8_t *)"HTTP/1.0 200 ok\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 20\r\n" + "\r\n" + "aaaab", + 0, STREAM_TOCLIENT, 0 }, + { (const uint8_t *)"bbbbc", 0, STREAM_TOCLIENT, 0 }, + { (const uint8_t *)"ccccd", 0, STREAM_TOCLIENT, 0 }, + { (const uint8_t *)"dddde", 0, STREAM_TOCLIENT, 0 }, + { NULL, 0, 0, 0 }, }; - const char *sig = "alert http any any -> any any (file_data; content:\"bccd\"; depth:4; sid:1;)"; + const char *sig = + "alert http any any -> any any (file_data; content:\"bccd\"; depth:4; sid:1;)"; return RunTest(steps, sig, yaml); } static int DetectEngineHttpServerBodyFileDataTest19(void) @@ -3860,11 +3860,11 @@ libhtp:\n\ DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf1[] = - "GET /file.swf HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /file.swf HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len1 = sizeof(http_buf1) - 1; // clang-format off uint8_t http_buf2[] = { @@ -3899,11 +3899,11 @@ libhtp:\n\ p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOCLIENT; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -3913,10 +3913,10 @@ libhtp:\n\ de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert tcp any any -> any any " - "(flow:established,from_server; " - "file_data; content:\"FWS\"; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " + "(flow:established,from_server; " + "file_data; content:\"FWS\"; " + "sid:1;)"); FAIL_IF_NULL(de_ctx->sig_list); SigGroupBuild(de_ctx); @@ -3989,11 +3989,11 @@ libhtp:\n\ DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf1[] = - "GET /file.swf HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /file.swf HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len1 = sizeof(http_buf1) - 1; // clang-format off uint8_t http_buf2[] = { @@ -4028,11 +4028,11 @@ libhtp:\n\ p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOCLIENT; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -4042,10 +4042,10 @@ libhtp:\n\ de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert tcp any any -> any any " - "(flow:established,from_server; " - "file_data; content:\"CWS\"; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " + "(flow:established,from_server; " + "file_data; content:\"CWS\"; " + "sid:1;)"); FAIL_IF_NULL(de_ctx->sig_list); SigGroupBuild(de_ctx); @@ -4118,11 +4118,11 @@ libhtp:\n\ DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf1[] = - "GET /file.swf HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /file.swf HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len1 = sizeof(http_buf1) - 1; // clang-format off uint8_t http_buf2[] = { @@ -4157,11 +4157,11 @@ libhtp:\n\ p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOCLIENT; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -4171,10 +4171,10 @@ libhtp:\n\ de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert tcp any any -> any any " - "(flow:established,from_server; " - "file_data; content:\"FWS\"; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " + "(flow:established,from_server; " + "file_data; content:\"FWS\"; " + "sid:1;)"); FAIL_IF_NULL(de_ctx->sig_list); SigGroupBuild(de_ctx); @@ -4247,11 +4247,11 @@ libhtp:\n\ DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf1[] = - "GET /file.swf HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /file.swf HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len1 = sizeof(http_buf1) - 1; // clang-format off uint8_t http_buf2[] = { @@ -4286,11 +4286,11 @@ libhtp:\n\ p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOCLIENT; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -4300,10 +4300,10 @@ libhtp:\n\ de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert tcp any any -> any any " - "(flow:established,from_server; " - "file_data; content:\"CWS\"; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " + "(flow:established,from_server; " + "file_data; content:\"CWS\"; " + "sid:1;)"); FAIL_IF_NULL(de_ctx->sig_list); SigGroupBuild(de_ctx); @@ -4376,11 +4376,11 @@ libhtp:\n\ DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf1[] = - "GET /file.swf HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /file.swf HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len1 = sizeof(http_buf1) - 1; // clang-format off uint8_t http_buf2[] = { @@ -4415,11 +4415,11 @@ libhtp:\n\ p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOCLIENT; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -4429,10 +4429,10 @@ libhtp:\n\ de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert tcp any any -> any any " - "(flow:established,from_server; " - "file_data; content:\"CWS\"; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " + "(flow:established,from_server; " + "file_data; content:\"CWS\"; " + "sid:1;)"); FAIL_IF_NULL(de_ctx->sig_list); SigGroupBuild(de_ctx); @@ -4505,11 +4505,11 @@ libhtp:\n\ DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf1[] = - "GET /file.swf HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /file.swf HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len1 = sizeof(http_buf1) - 1; // clang-format off uint8_t http_buf2[] = { @@ -4546,11 +4546,11 @@ libhtp:\n\ p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOCLIENT; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -4558,13 +4558,12 @@ libhtp:\n\ de_ctx = DetectEngineCtxInit(); FAIL_IF_NULL(de_ctx); - de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert tcp any any -> any any " - "(flow:established,from_server; " - "file_data; content:\"FWS\"; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " + "(flow:established,from_server; " + "file_data; content:\"FWS\"; " + "sid:1;)"); FAIL_IF_NULL(de_ctx->sig_list); SigGroupBuild(de_ctx); @@ -4637,11 +4636,11 @@ libhtp:\n\ DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf1[] = - "GET /file.swf HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /file.swf HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len1 = sizeof(http_buf1) - 1; // clang-format off uint8_t http_buf2[] = { @@ -4676,11 +4675,11 @@ libhtp:\n\ p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOCLIENT; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -4690,10 +4689,10 @@ libhtp:\n\ de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert tcp any any -> any any " - "(flow:established,from_server; " - "file_data; content:\"ZWS\"; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " + "(flow:established,from_server; " + "file_data; content:\"ZWS\"; " + "sid:1;)"); FAIL_IF_NULL(de_ctx->sig_list); SigGroupBuild(de_ctx); @@ -4766,11 +4765,11 @@ libhtp:\n\ DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf1[] = - "GET /file.swf HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /file.swf HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len1 = sizeof(http_buf1) - 1; // clang-format off uint8_t http_buf2[] = { @@ -4807,11 +4806,11 @@ libhtp:\n\ p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOCLIENT; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -4821,10 +4820,10 @@ libhtp:\n\ de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert tcp any any -> any any " - "(flow:established,from_server; " - "file_data; content:\"FWS\"; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " + "(flow:established,from_server; " + "file_data; content:\"FWS\"; " + "sid:1;)"); FAIL_IF_NULL(de_ctx->sig_list); SigGroupBuild(de_ctx); @@ -4897,11 +4896,11 @@ libhtp:\n\ DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf1[] = - "GET /file.swf HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /file.swf HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len1 = sizeof(http_buf1) - 1; // clang-format off uint8_t http_buf2[] = { @@ -4936,11 +4935,11 @@ libhtp:\n\ p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOCLIENT; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -4950,10 +4949,10 @@ libhtp:\n\ de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert tcp any any -> any any " - "(flow:established,from_server; " - "file_data; content:\"ZWS\"; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " + "(flow:established,from_server; " + "file_data; content:\"ZWS\"; " + "sid:1;)"); FAIL_IF_NULL(de_ctx->sig_list); SigGroupBuild(de_ctx); @@ -5026,11 +5025,11 @@ libhtp:\n\ DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf1[] = - "GET /file.swf HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /file.swf HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len1 = sizeof(http_buf1) - 1; // clang-format off uint8_t http_buf2[] = { @@ -5065,11 +5064,11 @@ libhtp:\n\ p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOCLIENT; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -5079,10 +5078,10 @@ libhtp:\n\ de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert tcp any any -> any any " - "(flow:established,from_server; " - "file_data; content:\"ZWS\"; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " + "(flow:established,from_server; " + "file_data; content:\"ZWS\"; " + "sid:1;)"); FAIL_IF_NULL(de_ctx->sig_list); SigGroupBuild(de_ctx); @@ -5154,11 +5153,11 @@ libhtp:\n\ DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf1[] = - "GET /file.swf HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /file.swf HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len1 = sizeof(http_buf1) - 1; // clang-format off uint8_t http_buf2[] = { @@ -5193,11 +5192,11 @@ libhtp:\n\ p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOCLIENT; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -5207,10 +5206,10 @@ libhtp:\n\ de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert tcp any any -> any any " - "(flow:established,from_server; " - "file_data; content:\"FWS\"; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " + "(flow:established,from_server; " + "file_data; content:\"FWS\"; " + "sid:1;)"); FAIL_IF_NULL(de_ctx->sig_list); SigGroupBuild(de_ctx); @@ -5265,18 +5264,17 @@ static int DetectHttpServerBodyTest06(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len = sizeof(http_buf) - 1; - uint8_t http_buf2[] = - "HTTP/1.0 200 ok\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 7\r\n" - "\r\n" - "message"; + uint8_t http_buf2[] = "HTTP/1.0 200 ok\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 7\r\n" + "\r\n" + "message"; uint32_t http_len2 = sizeof(http_buf2) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -5295,7 +5293,7 @@ static int DetectHttpServerBodyTest06(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOCLIENT; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -5306,10 +5304,10 @@ static int DetectHttpServerBodyTest06(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http server body test\"; " - "content:\"message\"; http_server_body; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http server body test\"; " + "content:\"message\"; http_server_body; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -5373,20 +5371,18 @@ static int DetectHttpServerBodyTest07(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf1[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len1 = sizeof(http_buf1) - 1; - uint8_t http_buf2[] = - "HTTP/1.0 200 ok\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 14\r\n" - "\r\n"; + uint8_t http_buf2[] = "HTTP/1.0 200 ok\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 14\r\n" + "\r\n"; uint32_t http_len2 = sizeof(http_buf2) - 1; - uint8_t http_buf3[] = - "message"; + uint8_t http_buf3[] = "message"; uint32_t http_len3 = sizeof(http_buf3) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -5406,12 +5402,12 @@ static int DetectHttpServerBodyTest07(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOCLIENT; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOCLIENT; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -5422,10 +5418,10 @@ static int DetectHttpServerBodyTest07(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http server body test\"; " - "content:\"message\"; http_server_body; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http server body test\"; " + "content:\"message\"; http_server_body; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -5502,21 +5498,19 @@ static int DetectHttpServerBodyTest08(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf1[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len1 = sizeof(http_buf1) - 1; - uint8_t http_buf2[] = - "HTTP/1.0 200 ok\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 14\r\n" - "\r\n" - "bigmes"; + uint8_t http_buf2[] = "HTTP/1.0 200 ok\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 14\r\n" + "\r\n" + "bigmes"; uint32_t http_len2 = sizeof(http_buf2) - 1; - uint8_t http_buf3[] = - "sage4u!!"; + uint8_t http_buf3[] = "sage4u!!"; uint32_t http_len3 = sizeof(http_buf3) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -5536,11 +5530,11 @@ static int DetectHttpServerBodyTest08(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOCLIENT; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOCLIENT; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -5551,10 +5545,10 @@ static int DetectHttpServerBodyTest08(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http client body test\"; " - "content:\"message\"; http_server_body; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http client body test\"; " + "content:\"message\"; http_server_body; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -5636,24 +5630,21 @@ static int DetectHttpServerBodyTest09(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf1[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len1 = sizeof(http_buf1) - 1; - uint8_t http_buf2[] = - "HTTP/1.0 200 ok\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 14\r\n" - "\r\n" - "bigmes"; + uint8_t http_buf2[] = "HTTP/1.0 200 ok\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 14\r\n" + "\r\n" + "bigmes"; uint32_t http_len2 = sizeof(http_buf2) - 1; - uint8_t http_buf3[] = - "sag"; + uint8_t http_buf3[] = "sag"; uint32_t http_len3 = sizeof(http_buf3) - 1; - uint8_t http_buf4[] = - "e4u!!"; + uint8_t http_buf4[] = "e4u!!"; uint32_t http_len4 = sizeof(http_buf4) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -5673,11 +5664,11 @@ static int DetectHttpServerBodyTest09(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOCLIENT; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOCLIENT; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -5688,10 +5679,10 @@ static int DetectHttpServerBodyTest09(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http client body test\"; " - "content:\"message\"; http_server_body; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http client body test\"; " + "content:\"message\"; http_server_body; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -5781,24 +5772,21 @@ static int DetectHttpServerBodyTest10(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf1[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len1 = sizeof(http_buf1) - 1; - uint8_t http_buf2[] = - "HTTP/1.0 200 ok\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 14\r\n" - "\r\n" - "bigmes"; + uint8_t http_buf2[] = "HTTP/1.0 200 ok\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 14\r\n" + "\r\n" + "bigmes"; uint32_t http_len2 = sizeof(http_buf2) - 1; - uint8_t http_buf3[] = - "sag"; + uint8_t http_buf3[] = "sag"; uint32_t http_len3 = sizeof(http_buf3) - 1; - uint8_t http_buf4[] = - "e4u!!"; + uint8_t http_buf4[] = "e4u!!"; uint32_t http_len4 = sizeof(http_buf4) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -5818,11 +5806,11 @@ static int DetectHttpServerBodyTest10(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOCLIENT; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOCLIENT; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -5833,10 +5821,10 @@ static int DetectHttpServerBodyTest10(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http client body test\"; " - "content:\"MeSSaGE\"; http_server_body; nocase; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http client body test\"; " + "content:\"MeSSaGE\"; http_server_body; nocase; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -5926,20 +5914,18 @@ static int DetectHttpServerBodyTest11(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf1[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len1 = sizeof(http_buf1) - 1; - uint8_t http_buf2[] = - "HTTP/1.0 200 ok\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 14\r\n" - "\r\n"; + uint8_t http_buf2[] = "HTTP/1.0 200 ok\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 14\r\n" + "\r\n"; uint32_t http_len2 = sizeof(http_buf2) - 1; - uint8_t http_buf3[] = - "bigmessage4u!!"; + uint8_t http_buf3[] = "bigmessage4u!!"; uint32_t http_len3 = sizeof(http_buf3) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -5959,11 +5945,11 @@ static int DetectHttpServerBodyTest11(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOCLIENT; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOCLIENT; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -5974,10 +5960,10 @@ static int DetectHttpServerBodyTest11(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http client body test\"; " - "content:!\"MaSSaGE\"; http_server_body; nocase; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http client body test\"; " + "content:!\"MaSSaGE\"; http_server_body; nocase; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -6059,20 +6045,18 @@ static int DetectHttpServerBodyTest12(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf1[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len1 = sizeof(http_buf1) - 1; - uint8_t http_buf2[] = - "HTTP/1.0 200 ok\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 14\r\n" - "\r\n"; + uint8_t http_buf2[] = "HTTP/1.0 200 ok\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 14\r\n" + "\r\n"; uint32_t http_len2 = sizeof(http_buf2) - 1; - uint8_t http_buf3[] = - "bigmessage4u!!"; + uint8_t http_buf3[] = "bigmessage4u!!"; uint32_t http_len3 = sizeof(http_buf3) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -6092,11 +6076,11 @@ static int DetectHttpServerBodyTest12(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOCLIENT; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOCLIENT; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -6107,10 +6091,10 @@ static int DetectHttpServerBodyTest12(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http client body test\"; " - "content:!\"MeSSaGE\"; http_server_body; nocase; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http client body test\"; " + "content:!\"MeSSaGE\"; http_server_body; nocase; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -6187,18 +6171,17 @@ static int DetectHttpServerBodyTest13(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len = sizeof(http_buf) - 1; - uint8_t http_buf2[] = - "HTTP/1.0 200 ok\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 55\r\n" - "\r\n" - "longbufferabcdefghijklmnopqrstuvwxyz0123456789bufferend"; + uint8_t http_buf2[] = "HTTP/1.0 200 ok\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 55\r\n" + "\r\n" + "longbufferabcdefghijklmnopqrstuvwxyz0123456789bufferend"; uint32_t http_len2 = sizeof(http_buf2) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -6217,7 +6200,7 @@ static int DetectHttpServerBodyTest13(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOCLIENT; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -6228,10 +6211,12 @@ static int DetectHttpServerBodyTest13(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http server body test\"; " - "content:\"longbufferabcdefghijklmnopqrstuvwxyz0123456789bufferend\"; http_server_body; " - "sid:1;)"); + de_ctx->sig_list = + SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http server body test\"; " + "content:\"longbufferabcdefghijklmnopqrstuvwxyz0123456789bufferend\"; " + "http_server_body; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -6292,28 +6277,28 @@ static int DetectHttpServerBodyTest14(void) TcpSession ssn; Packet *p = NULL; uint8_t httpbuf1[] = "GET /index1.html HTTP/1.1\r\n" - "User-Agent: Mozilla/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "Connection: keep-alive\r\n" - "Cookie: dummy1\r\n\r\n"; + "User-Agent: Mozilla/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "Connection: keep-alive\r\n" + "Cookie: dummy1\r\n\r\n"; uint32_t httplen1 = sizeof(httpbuf1) - 1; /* minus the \0 */ uint8_t httpbuf2[] = "HTTP/1.1 200 ok\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 3\r\n" - "\r\n" - "one"; + "Content-Type: text/html\r\n" + "Content-Length: 3\r\n" + "\r\n" + "one"; uint32_t httplen2 = sizeof(httpbuf2) - 1; /* minus the \0 */ uint8_t httpbuf3[] = "GET /index2.html HTTP/1.1\r\n" - "User-Agent: Firefox/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "Connection: keep-alive\r\n" - "Cookie: dummy2\r\n\r\n"; + "User-Agent: Firefox/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "Connection: keep-alive\r\n" + "Cookie: dummy2\r\n\r\n"; uint32_t httplen3 = sizeof(httpbuf3) - 1; /* minus the \0 */ uint8_t httpbuf4[] = "HTTP/1.1 200 ok\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 3\r\n" - "\r\n" - "two"; + "Content-Type: text/html\r\n" + "Content-Length: 3\r\n" + "\r\n" + "two"; uint32_t httplen4 = sizeof(httpbuf4) - 1; /* minus the \0 */ AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -6331,7 +6316,7 @@ static int DetectHttpServerBodyTest14(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOCLIENT; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -6343,12 +6328,14 @@ static int DetectHttpServerBodyTest14(void) de_ctx->flags |= DE_QUIET; - s = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any (flow:established,to_client; content:\"one\"; http_server_body; sid:1; rev:1;)"); + s = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any (flow:established,to_client; " + "content:\"one\"; http_server_body; sid:1; rev:1;)"); if (s == NULL) { printf("sig parse failed: "); goto end; } - s = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any (flow:established,to_client; content:\"two\"; http_server_body; sid:2; rev:1;)"); + s = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any (flow:established,to_client; " + "content:\"two\"; http_server_body; sid:2; rev:1;)"); if (s == NULL) { printf("sig2 parse failed: "); goto end; @@ -6453,28 +6440,28 @@ static int DetectHttpServerBodyTest15(void) TcpSession ssn; Packet *p = NULL; uint8_t httpbuf1[] = "GET /index1.html HTTP/1.1\r\n" - "User-Agent: Mozilla/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "Connection: keep-alive\r\n" - "Cookie: dummy1\r\n\r\n"; + "User-Agent: Mozilla/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "Connection: keep-alive\r\n" + "Cookie: dummy1\r\n\r\n"; uint32_t httplen1 = sizeof(httpbuf1) - 1; /* minus the \0 */ uint8_t httpbuf2[] = "HTTP/1.1 200 ok\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 3\r\n" - "\r\n" - "one"; + "Content-Type: text/html\r\n" + "Content-Length: 3\r\n" + "\r\n" + "one"; uint32_t httplen2 = sizeof(httpbuf2) - 1; /* minus the \0 */ uint8_t httpbuf3[] = "GET /index2.html HTTP/1.1\r\n" - "User-Agent: Firefox/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "Connection: keep-alive\r\n" - "Cookie: dummy2\r\n\r\n"; + "User-Agent: Firefox/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "Connection: keep-alive\r\n" + "Cookie: dummy2\r\n\r\n"; uint32_t httplen3 = sizeof(httpbuf3) - 1; /* minus the \0 */ uint8_t httpbuf4[] = "HTTP/1.1 200 ok\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 3\r\n" - "\r\n" - "two"; + "Content-Type: text/html\r\n" + "Content-Length: 3\r\n" + "\r\n" + "two"; uint32_t httplen4 = sizeof(httpbuf4) - 1; /* minus the \0 */ AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -6492,7 +6479,7 @@ static int DetectHttpServerBodyTest15(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOCLIENT; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -6504,12 +6491,14 @@ static int DetectHttpServerBodyTest15(void) de_ctx->flags |= DE_QUIET; - s = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any (flow:established,to_client; content:\"one\"; http_server_body; sid:1; rev:1;)"); + s = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any (flow:established,to_client; " + "content:\"one\"; http_server_body; sid:1; rev:1;)"); if (s == NULL) { printf("sig parse failed: "); goto end; } - s = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any (flow:established,to_client; content:\"two\"; http_server_body; sid:2; rev:1;)"); + s = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any (flow:established,to_client; " + "content:\"two\"; http_server_body; sid:2; rev:1;)"); if (s == NULL) { printf("sig2 parse failed: "); goto end; @@ -6609,18 +6598,17 @@ static int DetectHttpServerBodyFileDataTest01(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len = sizeof(http_buf) - 1; - uint8_t http_buf2[] = - "HTTP/1.0 200 ok\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 7\r\n" - "\r\n" - "message"; + uint8_t http_buf2[] = "HTTP/1.0 200 ok\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 7\r\n" + "\r\n" + "message"; uint32_t http_len2 = sizeof(http_buf2) - 1; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -6638,7 +6626,7 @@ static int DetectHttpServerBodyFileDataTest01(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOCLIENT; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -6647,10 +6635,10 @@ static int DetectHttpServerBodyFileDataTest01(void) FAIL_IF_NULL(de_ctx); de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http server body test\"; " - "file_data; content:\"message\"; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http server body test\"; " + "file_data; content:\"message\"; " + "sid:1;)"); FAIL_IF_NULL(de_ctx->sig_list); SigGroupBuild(de_ctx); @@ -6693,20 +6681,18 @@ static int DetectHttpServerBodyFileDataTest02(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf1[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len1 = sizeof(http_buf1) - 1; - uint8_t http_buf2[] = - "HTTP/1.0 200 ok\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 14\r\n" - "\r\n"; + uint8_t http_buf2[] = "HTTP/1.0 200 ok\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 14\r\n" + "\r\n"; uint32_t http_len2 = sizeof(http_buf2) - 1; - uint8_t http_buf3[] = - "message"; + uint8_t http_buf3[] = "message"; uint32_t http_len3 = sizeof(http_buf3) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -6726,12 +6712,12 @@ static int DetectHttpServerBodyFileDataTest02(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOCLIENT; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOCLIENT; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -6742,10 +6728,10 @@ static int DetectHttpServerBodyFileDataTest02(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http server body test\"; " - "file_data; content:\"message\"; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http server body test\"; " + "file_data; content:\"message\"; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -6824,21 +6810,19 @@ static int DetectHttpServerBodyFileDataTest03(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf1[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len1 = sizeof(http_buf1) - 1; - uint8_t http_buf2[] = - "HTTP/1.0 200 ok\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 14\r\n" - "\r\n" - "bigmes"; + uint8_t http_buf2[] = "HTTP/1.0 200 ok\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 14\r\n" + "\r\n" + "bigmes"; uint32_t http_len2 = sizeof(http_buf2) - 1; - uint8_t http_buf3[] = - "sage4u!!"; + uint8_t http_buf3[] = "sage4u!!"; uint32_t http_len3 = sizeof(http_buf3) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -6858,11 +6842,11 @@ static int DetectHttpServerBodyFileDataTest03(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOCLIENT; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOCLIENT; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -6873,10 +6857,10 @@ static int DetectHttpServerBodyFileDataTest03(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http client body test\"; " - "file_data; content:\"message\"; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http client body test\"; " + "file_data; content:\"message\"; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -6922,7 +6906,6 @@ static int DetectHttpServerBodyFileDataTest03(void) goto end; } - /* do detect */ SigMatchSignatures(&th_v, de_ctx, det_ctx, p2); @@ -6959,24 +6942,21 @@ static int DetectHttpServerBodyFileDataTest04(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf1[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len1 = sizeof(http_buf1) - 1; - uint8_t http_buf2[] = - "HTTP/1.0 200 ok\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 14\r\n" - "\r\n" - "bigmes"; + uint8_t http_buf2[] = "HTTP/1.0 200 ok\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 14\r\n" + "\r\n" + "bigmes"; uint32_t http_len2 = sizeof(http_buf2) - 1; - uint8_t http_buf3[] = - "sag"; + uint8_t http_buf3[] = "sag"; uint32_t http_len3 = sizeof(http_buf3) - 1; - uint8_t http_buf4[] = - "e4u!!"; + uint8_t http_buf4[] = "e4u!!"; uint32_t http_len4 = sizeof(http_buf4) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -6996,11 +6976,11 @@ static int DetectHttpServerBodyFileDataTest04(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOCLIENT; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOCLIENT; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -7011,10 +6991,10 @@ static int DetectHttpServerBodyFileDataTest04(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http client body test\"; " - "file_data; content:\"message\"; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http client body test\"; " + "file_data; content:\"message\"; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -7104,24 +7084,21 @@ static int DetectHttpServerBodyFileDataTest05(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf1[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len1 = sizeof(http_buf1) - 1; - uint8_t http_buf2[] = - "HTTP/1.0 200 ok\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 14\r\n" - "\r\n" - "bigmes"; + uint8_t http_buf2[] = "HTTP/1.0 200 ok\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 14\r\n" + "\r\n" + "bigmes"; uint32_t http_len2 = sizeof(http_buf2) - 1; - uint8_t http_buf3[] = - "sag"; + uint8_t http_buf3[] = "sag"; uint32_t http_len3 = sizeof(http_buf3) - 1; - uint8_t http_buf4[] = - "e4u!!"; + uint8_t http_buf4[] = "e4u!!"; uint32_t http_len4 = sizeof(http_buf4) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -7141,11 +7118,11 @@ static int DetectHttpServerBodyFileDataTest05(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOCLIENT; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOCLIENT; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -7156,10 +7133,10 @@ static int DetectHttpServerBodyFileDataTest05(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http client body test\"; " - "file_data; content:\"MeSSaGE\"; nocase; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http client body test\"; " + "file_data; content:\"MeSSaGE\"; nocase; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -7249,20 +7226,18 @@ static int DetectHttpServerBodyFileDataTest06(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf1[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len1 = sizeof(http_buf1) - 1; - uint8_t http_buf2[] = - "HTTP/1.0 200 ok\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 14\r\n" - "\r\n"; + uint8_t http_buf2[] = "HTTP/1.0 200 ok\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 14\r\n" + "\r\n"; uint32_t http_len2 = sizeof(http_buf2) - 1; - uint8_t http_buf3[] = - "bigmessage4u!!"; + uint8_t http_buf3[] = "bigmessage4u!!"; uint32_t http_len3 = sizeof(http_buf3) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -7282,11 +7257,11 @@ static int DetectHttpServerBodyFileDataTest06(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOCLIENT; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOCLIENT; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -7297,10 +7272,10 @@ static int DetectHttpServerBodyFileDataTest06(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http file_data test\"; " - "file_data; content:!\"MaSSaGE\"; nocase; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http file_data test\"; " + "file_data; content:!\"MaSSaGE\"; nocase; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -7382,20 +7357,18 @@ static int DetectHttpServerBodyFileDataTest07(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf1[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len1 = sizeof(http_buf1) - 1; - uint8_t http_buf2[] = - "HTTP/1.0 200 ok\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 14\r\n" - "\r\n"; + uint8_t http_buf2[] = "HTTP/1.0 200 ok\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 14\r\n" + "\r\n"; uint32_t http_len2 = sizeof(http_buf2) - 1; - uint8_t http_buf3[] = - "bigmessage4u!!"; + uint8_t http_buf3[] = "bigmessage4u!!"; uint32_t http_len3 = sizeof(http_buf3) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -7415,11 +7388,11 @@ static int DetectHttpServerBodyFileDataTest07(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOCLIENT; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOCLIENT; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -7430,10 +7403,10 @@ static int DetectHttpServerBodyFileDataTest07(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http file_data test\"; " - "file_data; content:!\"MeSSaGE\"; nocase; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http file_data test\"; " + "file_data; content:!\"MeSSaGE\"; nocase; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -7510,18 +7483,17 @@ static int DetectHttpServerBodyFileDataTest08(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len = sizeof(http_buf) - 1; - uint8_t http_buf2[] = - "HTTP/1.0 200 ok\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 55\r\n" - "\r\n" - "longbufferabcdefghijklmnopqrstuvwxyz0123456789bufferend"; + uint8_t http_buf2[] = "HTTP/1.0 200 ok\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 55\r\n" + "\r\n" + "longbufferabcdefghijklmnopqrstuvwxyz0123456789bufferend"; uint32_t http_len2 = sizeof(http_buf2) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -7540,7 +7512,7 @@ static int DetectHttpServerBodyFileDataTest08(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOCLIENT; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -7551,10 +7523,11 @@ static int DetectHttpServerBodyFileDataTest08(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http server body test\"; " - "file_data; content:\"longbufferabcdefghijklmnopqrstuvwxyz0123456789bufferend\"; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, + "alert http any any -> any any " + "(msg:\"http server body test\"; " + "file_data; content:\"longbufferabcdefghijklmnopqrstuvwxyz0123456789bufferend\"; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -7615,28 +7588,28 @@ static int DetectHttpServerBodyFileDataTest09(void) TcpSession ssn; Packet *p = NULL; uint8_t httpbuf1[] = "GET /index1.html HTTP/1.1\r\n" - "User-Agent: Mozilla/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "Connection: keep-alive\r\n" - "Cookie: dummy1\r\n\r\n"; + "User-Agent: Mozilla/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "Connection: keep-alive\r\n" + "Cookie: dummy1\r\n\r\n"; uint32_t httplen1 = sizeof(httpbuf1) - 1; /* minus the \0 */ uint8_t httpbuf2[] = "HTTP/1.1 200 ok\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 3\r\n" - "\r\n" - "one"; + "Content-Type: text/html\r\n" + "Content-Length: 3\r\n" + "\r\n" + "one"; uint32_t httplen2 = sizeof(httpbuf2) - 1; /* minus the \0 */ uint8_t httpbuf3[] = "GET /index2.html HTTP/1.1\r\n" - "User-Agent: Firefox/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "Connection: keep-alive\r\n" - "Cookie: dummy2\r\n\r\n"; + "User-Agent: Firefox/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "Connection: keep-alive\r\n" + "Cookie: dummy2\r\n\r\n"; uint32_t httplen3 = sizeof(httpbuf3) - 1; /* minus the \0 */ uint8_t httpbuf4[] = "HTTP/1.1 200 ok\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 3\r\n" - "\r\n" - "two"; + "Content-Type: text/html\r\n" + "Content-Length: 3\r\n" + "\r\n" + "two"; uint32_t httplen4 = sizeof(httpbuf4) - 1; /* minus the \0 */ AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -7654,7 +7627,7 @@ static int DetectHttpServerBodyFileDataTest09(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOCLIENT; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -7666,12 +7639,14 @@ static int DetectHttpServerBodyFileDataTest09(void) de_ctx->flags |= DE_QUIET; - s = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any (flow:established,to_client; file_data; content:\"one\"; sid:1; rev:1;)"); + s = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any (flow:established,to_client; " + "file_data; content:\"one\"; sid:1; rev:1;)"); if (s == NULL) { printf("sig parse failed: "); goto end; } - s = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any (flow:established,to_client; file_data; content:\"two\"; sid:2; rev:1;)"); + s = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any (flow:established,to_client; " + "file_data; content:\"two\"; sid:2; rev:1;)"); if (s == NULL) { printf("sig2 parse failed: "); goto end; @@ -7764,28 +7739,28 @@ static int DetectHttpServerBodyFileDataTest10(void) TcpSession ssn; Packet *p = NULL; uint8_t httpbuf1[] = "GET /index1.html HTTP/1.1\r\n" - "User-Agent: Mozilla/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "Connection: keep-alive\r\n" - "Cookie: dummy1\r\n\r\n"; + "User-Agent: Mozilla/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "Connection: keep-alive\r\n" + "Cookie: dummy1\r\n\r\n"; uint32_t httplen1 = sizeof(httpbuf1) - 1; /* minus the \0 */ uint8_t httpbuf2[] = "HTTP/1.1 200 ok\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 3\r\n" - "\r\n" - "one"; + "Content-Type: text/html\r\n" + "Content-Length: 3\r\n" + "\r\n" + "one"; uint32_t httplen2 = sizeof(httpbuf2) - 1; /* minus the \0 */ uint8_t httpbuf3[] = "GET /index2.html HTTP/1.1\r\n" - "User-Agent: Firefox/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "Connection: keep-alive\r\n" - "Cookie: dummy2\r\n\r\n"; + "User-Agent: Firefox/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "Connection: keep-alive\r\n" + "Cookie: dummy2\r\n\r\n"; uint32_t httplen3 = sizeof(httpbuf3) - 1; /* minus the \0 */ uint8_t httpbuf4[] = "HTTP/1.1 200 ok\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 3\r\n" - "\r\n" - "two"; + "Content-Type: text/html\r\n" + "Content-Length: 3\r\n" + "\r\n" + "two"; uint32_t httplen4 = sizeof(httpbuf4) - 1; /* minus the \0 */ AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -7803,7 +7778,7 @@ static int DetectHttpServerBodyFileDataTest10(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOCLIENT; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -7815,12 +7790,14 @@ static int DetectHttpServerBodyFileDataTest10(void) de_ctx->flags |= DE_QUIET; - s = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any (flow:established,to_client; file_data; content:\"one\"; sid:1; rev:1;)"); + s = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any (flow:established,to_client; " + "file_data; content:\"one\"; sid:1; rev:1;)"); if (s == NULL) { printf("sig parse failed: "); goto end; } - s = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any (flow:established,to_client; file_data; content:\"two\"; sid:2; rev:1;)"); + s = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any (flow:established,to_client; " + "file_data; content:\"two\"; sid:2; rev:1;)"); if (s == NULL) { printf("sig2 parse failed: "); goto end; @@ -7919,129 +7896,97 @@ void DetectHttpServerBodyRegisterTests(void) UtRegisterTest("DetectHttpServerBodyTest14", DetectHttpServerBodyTest14); UtRegisterTest("DetectHttpServerBodyTest15", DetectHttpServerBodyTest15); - UtRegisterTest("DetectHttpServerBodyFileDataTest01", - DetectHttpServerBodyFileDataTest01); - UtRegisterTest("DetectHttpServerBodyFileDataTest02", - DetectHttpServerBodyFileDataTest02); - UtRegisterTest("DetectHttpServerBodyFileDataTest03", - DetectHttpServerBodyFileDataTest03); - UtRegisterTest("DetectHttpServerBodyFileDataTest04", - DetectHttpServerBodyFileDataTest04); - UtRegisterTest("DetectHttpServerBodyFileDataTest05", - DetectHttpServerBodyFileDataTest05); - UtRegisterTest("DetectHttpServerBodyFileDataTest06", - DetectHttpServerBodyFileDataTest06); - UtRegisterTest("DetectHttpServerBodyFileDataTest07", - DetectHttpServerBodyFileDataTest07); - UtRegisterTest("DetectHttpServerBodyFileDataTest08", - DetectHttpServerBodyFileDataTest08); - UtRegisterTest("DetectHttpServerBodyFileDataTest09", - DetectHttpServerBodyFileDataTest09); - UtRegisterTest("DetectHttpServerBodyFileDataTest10", - DetectHttpServerBodyFileDataTest10); - - UtRegisterTest("DetectEngineHttpServerBodyTest01", - DetectEngineHttpServerBodyTest01); - UtRegisterTest("DetectEngineHttpServerBodyTest02", - DetectEngineHttpServerBodyTest02); - UtRegisterTest("DetectEngineHttpServerBodyTest03", - DetectEngineHttpServerBodyTest03); - UtRegisterTest("DetectEngineHttpServerBodyTest04", - DetectEngineHttpServerBodyTest04); - UtRegisterTest("DetectEngineHttpServerBodyTest05", - DetectEngineHttpServerBodyTest05); - UtRegisterTest("DetectEngineHttpServerBodyTest06", - DetectEngineHttpServerBodyTest06); - UtRegisterTest("DetectEngineHttpServerBodyTest07", - DetectEngineHttpServerBodyTest07); - UtRegisterTest("DetectEngineHttpServerBodyTest08", - DetectEngineHttpServerBodyTest08); - UtRegisterTest("DetectEngineHttpServerBodyTest09", - DetectEngineHttpServerBodyTest09); - UtRegisterTest("DetectEngineHttpServerBodyTest10", - DetectEngineHttpServerBodyTest10); - UtRegisterTest("DetectEngineHttpServerBodyTest11", - DetectEngineHttpServerBodyTest11); - UtRegisterTest("DetectEngineHttpServerBodyTest12", - DetectEngineHttpServerBodyTest12); - UtRegisterTest("DetectEngineHttpServerBodyTest13", - DetectEngineHttpServerBodyTest13); - UtRegisterTest("DetectEngineHttpServerBodyTest14", - DetectEngineHttpServerBodyTest14); - UtRegisterTest("DetectEngineHttpServerBodyTest15", - DetectEngineHttpServerBodyTest15); - UtRegisterTest("DetectEngineHttpServerBodyTest16", - DetectEngineHttpServerBodyTest16); - UtRegisterTest("DetectEngineHttpServerBodyTest17", - DetectEngineHttpServerBodyTest17); - UtRegisterTest("DetectEngineHttpServerBodyTest18", - DetectEngineHttpServerBodyTest18); - UtRegisterTest("DetectEngineHttpServerBodyTest19", - DetectEngineHttpServerBodyTest19); - UtRegisterTest("DetectEngineHttpServerBodyTest20", - DetectEngineHttpServerBodyTest20); - UtRegisterTest("DetectEngineHttpServerBodyTest21", - DetectEngineHttpServerBodyTest21); - UtRegisterTest("DetectEngineHttpServerBodyTest22", - DetectEngineHttpServerBodyTest22); - - UtRegisterTest("DetectEngineHttpServerBodyFileDataTest01", - DetectEngineHttpServerBodyFileDataTest01); - UtRegisterTest("DetectEngineHttpServerBodyFileDataTest02", - DetectEngineHttpServerBodyFileDataTest02); - UtRegisterTest("DetectEngineHttpServerBodyFileDataTest03", - DetectEngineHttpServerBodyFileDataTest03); - UtRegisterTest("DetectEngineHttpServerBodyFileDataTest04", - DetectEngineHttpServerBodyFileDataTest04); - UtRegisterTest("DetectEngineHttpServerBodyFileDataTest05", - DetectEngineHttpServerBodyFileDataTest05); - UtRegisterTest("DetectEngineHttpServerBodyFileDataTest06", - DetectEngineHttpServerBodyFileDataTest06); - UtRegisterTest("DetectEngineHttpServerBodyFileDataTest07", - DetectEngineHttpServerBodyFileDataTest07); - UtRegisterTest("DetectEngineHttpServerBodyFileDataTest08", - DetectEngineHttpServerBodyFileDataTest08); - UtRegisterTest("DetectEngineHttpServerBodyFileDataTest09", - DetectEngineHttpServerBodyFileDataTest09); - UtRegisterTest("DetectEngineHttpServerBodyFileDataTest10", - DetectEngineHttpServerBodyFileDataTest10); - UtRegisterTest("DetectEngineHttpServerBodyFileDataTest11", - DetectEngineHttpServerBodyFileDataTest11); - UtRegisterTest("DetectEngineHttpServerBodyFileDataTest12", - DetectEngineHttpServerBodyFileDataTest12); - UtRegisterTest("DetectEngineHttpServerBodyFileDataTest13", - DetectEngineHttpServerBodyFileDataTest13); - UtRegisterTest("DetectEngineHttpServerBodyFileDataTest14", - DetectEngineHttpServerBodyFileDataTest14); - UtRegisterTest("DetectEngineHttpServerBodyFileDataTest15", - DetectEngineHttpServerBodyFileDataTest15); - UtRegisterTest("DetectEngineHttpServerBodyFileDataTest16", - DetectEngineHttpServerBodyFileDataTest16); - UtRegisterTest("DetectEngineHttpServerBodyFileDataTest17", - DetectEngineHttpServerBodyFileDataTest17); - UtRegisterTest("DetectEngineHttpServerBodyFileDataTest18", - DetectEngineHttpServerBodyFileDataTest18); - - UtRegisterTest("DetectEngineHttpServerBodyFileDataTest19", - DetectEngineHttpServerBodyFileDataTest19); - UtRegisterTest("DetectEngineHttpServerBodyFileDataTest20", - DetectEngineHttpServerBodyFileDataTest20); - UtRegisterTest("DetectEngineHttpServerBodyFileDataTest21", - DetectEngineHttpServerBodyFileDataTest21); - UtRegisterTest("DetectEngineHttpServerBodyFileDataTest22", - DetectEngineHttpServerBodyFileDataTest22); - UtRegisterTest("DetectEngineHttpServerBodyFileDataTest23", - DetectEngineHttpServerBodyFileDataTest23); - UtRegisterTest("DetectEngineHttpServerBodyFileDataTest24", - DetectEngineHttpServerBodyFileDataTest24); - UtRegisterTest("DetectEngineHttpServerBodyFileDataTest25", - DetectEngineHttpServerBodyFileDataTest25); - UtRegisterTest("DetectEngineHttpServerBodyFileDataTest26", - DetectEngineHttpServerBodyFileDataTest26); - UtRegisterTest("DetectEngineHttpServerBodyFileDataTest27", - DetectEngineHttpServerBodyFileDataTest27); - UtRegisterTest("DetectEngineHttpServerBodyFileDataTest28", - DetectEngineHttpServerBodyFileDataTest28); - UtRegisterTest("DetectEngineHttpServerBodyFileDataTest29", - DetectEngineHttpServerBodyFileDataTest29); + UtRegisterTest("DetectHttpServerBodyFileDataTest01", DetectHttpServerBodyFileDataTest01); + UtRegisterTest("DetectHttpServerBodyFileDataTest02", DetectHttpServerBodyFileDataTest02); + UtRegisterTest("DetectHttpServerBodyFileDataTest03", DetectHttpServerBodyFileDataTest03); + UtRegisterTest("DetectHttpServerBodyFileDataTest04", DetectHttpServerBodyFileDataTest04); + UtRegisterTest("DetectHttpServerBodyFileDataTest05", DetectHttpServerBodyFileDataTest05); + UtRegisterTest("DetectHttpServerBodyFileDataTest06", DetectHttpServerBodyFileDataTest06); + UtRegisterTest("DetectHttpServerBodyFileDataTest07", DetectHttpServerBodyFileDataTest07); + UtRegisterTest("DetectHttpServerBodyFileDataTest08", DetectHttpServerBodyFileDataTest08); + UtRegisterTest("DetectHttpServerBodyFileDataTest09", DetectHttpServerBodyFileDataTest09); + UtRegisterTest("DetectHttpServerBodyFileDataTest10", DetectHttpServerBodyFileDataTest10); + + UtRegisterTest("DetectEngineHttpServerBodyTest01", DetectEngineHttpServerBodyTest01); + UtRegisterTest("DetectEngineHttpServerBodyTest02", DetectEngineHttpServerBodyTest02); + UtRegisterTest("DetectEngineHttpServerBodyTest03", DetectEngineHttpServerBodyTest03); + UtRegisterTest("DetectEngineHttpServerBodyTest04", DetectEngineHttpServerBodyTest04); + UtRegisterTest("DetectEngineHttpServerBodyTest05", DetectEngineHttpServerBodyTest05); + UtRegisterTest("DetectEngineHttpServerBodyTest06", DetectEngineHttpServerBodyTest06); + UtRegisterTest("DetectEngineHttpServerBodyTest07", DetectEngineHttpServerBodyTest07); + UtRegisterTest("DetectEngineHttpServerBodyTest08", DetectEngineHttpServerBodyTest08); + UtRegisterTest("DetectEngineHttpServerBodyTest09", DetectEngineHttpServerBodyTest09); + UtRegisterTest("DetectEngineHttpServerBodyTest10", DetectEngineHttpServerBodyTest10); + UtRegisterTest("DetectEngineHttpServerBodyTest11", DetectEngineHttpServerBodyTest11); + UtRegisterTest("DetectEngineHttpServerBodyTest12", DetectEngineHttpServerBodyTest12); + UtRegisterTest("DetectEngineHttpServerBodyTest13", DetectEngineHttpServerBodyTest13); + UtRegisterTest("DetectEngineHttpServerBodyTest14", DetectEngineHttpServerBodyTest14); + UtRegisterTest("DetectEngineHttpServerBodyTest15", DetectEngineHttpServerBodyTest15); + UtRegisterTest("DetectEngineHttpServerBodyTest16", DetectEngineHttpServerBodyTest16); + UtRegisterTest("DetectEngineHttpServerBodyTest17", DetectEngineHttpServerBodyTest17); + UtRegisterTest("DetectEngineHttpServerBodyTest18", DetectEngineHttpServerBodyTest18); + UtRegisterTest("DetectEngineHttpServerBodyTest19", DetectEngineHttpServerBodyTest19); + UtRegisterTest("DetectEngineHttpServerBodyTest20", DetectEngineHttpServerBodyTest20); + UtRegisterTest("DetectEngineHttpServerBodyTest21", DetectEngineHttpServerBodyTest21); + UtRegisterTest("DetectEngineHttpServerBodyTest22", DetectEngineHttpServerBodyTest22); + + UtRegisterTest( + "DetectEngineHttpServerBodyFileDataTest01", DetectEngineHttpServerBodyFileDataTest01); + UtRegisterTest( + "DetectEngineHttpServerBodyFileDataTest02", DetectEngineHttpServerBodyFileDataTest02); + UtRegisterTest( + "DetectEngineHttpServerBodyFileDataTest03", DetectEngineHttpServerBodyFileDataTest03); + UtRegisterTest( + "DetectEngineHttpServerBodyFileDataTest04", DetectEngineHttpServerBodyFileDataTest04); + UtRegisterTest( + "DetectEngineHttpServerBodyFileDataTest05", DetectEngineHttpServerBodyFileDataTest05); + UtRegisterTest( + "DetectEngineHttpServerBodyFileDataTest06", DetectEngineHttpServerBodyFileDataTest06); + UtRegisterTest( + "DetectEngineHttpServerBodyFileDataTest07", DetectEngineHttpServerBodyFileDataTest07); + UtRegisterTest( + "DetectEngineHttpServerBodyFileDataTest08", DetectEngineHttpServerBodyFileDataTest08); + UtRegisterTest( + "DetectEngineHttpServerBodyFileDataTest09", DetectEngineHttpServerBodyFileDataTest09); + UtRegisterTest( + "DetectEngineHttpServerBodyFileDataTest10", DetectEngineHttpServerBodyFileDataTest10); + UtRegisterTest( + "DetectEngineHttpServerBodyFileDataTest11", DetectEngineHttpServerBodyFileDataTest11); + UtRegisterTest( + "DetectEngineHttpServerBodyFileDataTest12", DetectEngineHttpServerBodyFileDataTest12); + UtRegisterTest( + "DetectEngineHttpServerBodyFileDataTest13", DetectEngineHttpServerBodyFileDataTest13); + UtRegisterTest( + "DetectEngineHttpServerBodyFileDataTest14", DetectEngineHttpServerBodyFileDataTest14); + UtRegisterTest( + "DetectEngineHttpServerBodyFileDataTest15", DetectEngineHttpServerBodyFileDataTest15); + UtRegisterTest( + "DetectEngineHttpServerBodyFileDataTest16", DetectEngineHttpServerBodyFileDataTest16); + UtRegisterTest( + "DetectEngineHttpServerBodyFileDataTest17", DetectEngineHttpServerBodyFileDataTest17); + UtRegisterTest( + "DetectEngineHttpServerBodyFileDataTest18", DetectEngineHttpServerBodyFileDataTest18); + + UtRegisterTest( + "DetectEngineHttpServerBodyFileDataTest19", DetectEngineHttpServerBodyFileDataTest19); + UtRegisterTest( + "DetectEngineHttpServerBodyFileDataTest20", DetectEngineHttpServerBodyFileDataTest20); + UtRegisterTest( + "DetectEngineHttpServerBodyFileDataTest21", DetectEngineHttpServerBodyFileDataTest21); + UtRegisterTest( + "DetectEngineHttpServerBodyFileDataTest22", DetectEngineHttpServerBodyFileDataTest22); + UtRegisterTest( + "DetectEngineHttpServerBodyFileDataTest23", DetectEngineHttpServerBodyFileDataTest23); + UtRegisterTest( + "DetectEngineHttpServerBodyFileDataTest24", DetectEngineHttpServerBodyFileDataTest24); + UtRegisterTest( + "DetectEngineHttpServerBodyFileDataTest25", DetectEngineHttpServerBodyFileDataTest25); + UtRegisterTest( + "DetectEngineHttpServerBodyFileDataTest26", DetectEngineHttpServerBodyFileDataTest26); + UtRegisterTest( + "DetectEngineHttpServerBodyFileDataTest27", DetectEngineHttpServerBodyFileDataTest27); + UtRegisterTest( + "DetectEngineHttpServerBodyFileDataTest28", DetectEngineHttpServerBodyFileDataTest28); + UtRegisterTest( + "DetectEngineHttpServerBodyFileDataTest29", DetectEngineHttpServerBodyFileDataTest29); } diff --git a/src/tests/detect-http-stat-code.c b/src/tests/detect-http-stat-code.c index 25a711545b39..67f22a679103 100644 --- a/src/tests/detect-http-stat-code.c +++ b/src/tests/detect-http-stat-code.c @@ -51,18 +51,17 @@ static int DetectEngineHttpStatCodeTest01(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf1[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len1 = sizeof(http_buf1) - 1; - uint8_t http_buf2[] = - "HTTP/1.0 200 message\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 7\r\n" - "\r\n" - "message"; + uint8_t http_buf2[] = "HTTP/1.0 200 message\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 7\r\n" + "\r\n" + "message"; uint32_t http_len2 = sizeof(http_buf2) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -82,11 +81,11 @@ static int DetectEngineHttpStatCodeTest01(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOCLIENT; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -97,10 +96,10 @@ static int DetectEngineHttpStatCodeTest01(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http stat code test\"; " - "content:\"200\"; http_stat_code; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http stat code test\"; " + "content:\"200\"; http_stat_code; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -170,18 +169,17 @@ static int DetectEngineHttpStatCodeTest02(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf1[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len1 = sizeof(http_buf1) - 1; - uint8_t http_buf2[] = - "HTTP/1.0 2000123 xxxxABC\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 7\r\n" - "\r\n" - "xxxxABC"; + uint8_t http_buf2[] = "HTTP/1.0 2000123 xxxxABC\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 7\r\n" + "\r\n" + "xxxxABC"; uint32_t http_len2 = sizeof(http_buf2) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -200,7 +198,7 @@ static int DetectEngineHttpStatCodeTest02(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOCLIENT; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -211,10 +209,10 @@ static int DetectEngineHttpStatCodeTest02(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http stat code test\"; " - "content:\"123\"; http_stat_code; offset:4; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http stat code test\"; " + "content:\"123\"; http_stat_code; offset:4; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -277,21 +275,19 @@ static int DetectEngineHttpStatCodeTest03(void) HtpState *http_state = NULL; Flow f; int result = 0; - uint8_t http_buf1[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len1 = sizeof(http_buf1) - 1; - uint8_t http_buf2[] = - "HTTP/1.0 123"; + uint8_t http_buf2[] = "HTTP/1.0 123"; uint32_t http_len2 = sizeof(http_buf2) - 1; - uint8_t http_buf3[] = - "456789\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 17\r\n" - "\r\n" - "12345678901234ABC"; + uint8_t http_buf3[] = "456789\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 17\r\n" + "\r\n" + "12345678901234ABC"; uint32_t http_len3 = sizeof(http_buf3) - 1; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -310,11 +306,11 @@ static int DetectEngineHttpStatCodeTest03(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOCLIENT; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -325,10 +321,10 @@ static int DetectEngineHttpStatCodeTest03(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http stat code test\"; " - "content:\"789\"; http_stat_code; offset:5; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http stat code test\"; " + "content:\"789\"; http_stat_code; offset:5; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -407,18 +403,17 @@ static int DetectEngineHttpStatCodeTest04(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf1[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len1 = sizeof(http_buf1) - 1; - uint8_t http_buf2[] = - "HTTP/1.0 200123 abcdef\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 6\r\n" - "\r\n" - "abcdef"; + uint8_t http_buf2[] = "HTTP/1.0 200123 abcdef\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 6\r\n" + "\r\n" + "abcdef"; uint32_t http_len2 = sizeof(http_buf2) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -438,11 +433,11 @@ static int DetectEngineHttpStatCodeTest04(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOCLIENT; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -453,10 +448,10 @@ static int DetectEngineHttpStatCodeTest04(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http stat code test\"; " - "content:!\"200\"; http_stat_code; offset:3; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http stat code test\"; " + "content:!\"200\"; http_stat_code; offset:3; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -527,18 +522,17 @@ static int DetectEngineHttpStatCodeTest05(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf1[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len1 = sizeof(http_buf1) - 1; - uint8_t http_buf2[] = - "HTTP/1.0 200123 abcdef\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 6\r\n" - "\r\n" - "abcdef"; + uint8_t http_buf2[] = "HTTP/1.0 200123 abcdef\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 6\r\n" + "\r\n" + "abcdef"; uint32_t http_len2 = sizeof(http_buf2) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -558,11 +552,11 @@ static int DetectEngineHttpStatCodeTest05(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOCLIENT; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -573,10 +567,10 @@ static int DetectEngineHttpStatCodeTest05(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http stat code test\"; " - "content:\"200\"; http_stat_code; depth:3; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http stat code test\"; " + "content:\"200\"; http_stat_code; depth:3; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -647,18 +641,17 @@ static int DetectEngineHttpStatCodeTest06(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf1[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len1 = sizeof(http_buf1) - 1; - uint8_t http_buf2[] = - "HTTP/1.0 200123 abcdef\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 6\r\n" - "\r\n" - "abcdef"; + uint8_t http_buf2[] = "HTTP/1.0 200123 abcdef\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 6\r\n" + "\r\n" + "abcdef"; uint32_t http_len2 = sizeof(http_buf2) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -678,11 +671,11 @@ static int DetectEngineHttpStatCodeTest06(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOCLIENT; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -693,10 +686,10 @@ static int DetectEngineHttpStatCodeTest06(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http stat code test\"; " - "content:!\"123\"; http_stat_code; depth:3; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http stat code test\"; " + "content:!\"123\"; http_stat_code; depth:3; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -767,18 +760,17 @@ static int DetectEngineHttpStatCodeTest07(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf1[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len1 = sizeof(http_buf1) - 1; - uint8_t http_buf2[] = - "HTTP/1.0 200123 abcdef\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 6\r\n" - "\r\n" - "abcdef"; + uint8_t http_buf2[] = "HTTP/1.0 200123 abcdef\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 6\r\n" + "\r\n" + "abcdef"; uint32_t http_len2 = sizeof(http_buf2) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -798,11 +790,11 @@ static int DetectEngineHttpStatCodeTest07(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOCLIENT; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -813,10 +805,10 @@ static int DetectEngineHttpStatCodeTest07(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http stat code test\"; " - "content:!\"123\"; http_stat_code; offset:3; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http stat code test\"; " + "content:!\"123\"; http_stat_code; offset:3; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -887,18 +879,17 @@ static int DetectEngineHttpStatCodeTest08(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf1[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len1 = sizeof(http_buf1) - 1; - uint8_t http_buf2[] = - "HTTP/1.0 200123 abcdef\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 6\r\n" - "\r\n" - "abcdef"; + uint8_t http_buf2[] = "HTTP/1.0 200123 abcdef\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 6\r\n" + "\r\n" + "abcdef"; uint32_t http_len2 = sizeof(http_buf2) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -918,11 +909,11 @@ static int DetectEngineHttpStatCodeTest08(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOCLIENT; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -933,10 +924,10 @@ static int DetectEngineHttpStatCodeTest08(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http stat code test\"; " - "content:!\"200\"; http_stat_code; depth:3; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http stat code test\"; " + "content:!\"200\"; http_stat_code; depth:3; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -1007,18 +998,17 @@ static int DetectEngineHttpStatCodeTest09(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf1[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len1 = sizeof(http_buf1) - 1; - uint8_t http_buf2[] = - "HTTP/1.0 200123 abcdef\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 6\r\n" - "\r\n" - "abcdef"; + uint8_t http_buf2[] = "HTTP/1.0 200123 abcdef\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 6\r\n" + "\r\n" + "abcdef"; uint32_t http_len2 = sizeof(http_buf2) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -1038,11 +1028,11 @@ static int DetectEngineHttpStatCodeTest09(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOCLIENT; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1053,11 +1043,11 @@ static int DetectEngineHttpStatCodeTest09(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http stat code test\"; " - "content:\"200\"; http_stat_code; depth:3; " - "content:\"123\"; http_stat_code; within:3; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http stat code test\"; " + "content:\"200\"; http_stat_code; depth:3; " + "content:\"123\"; http_stat_code; within:3; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -1128,18 +1118,17 @@ static int DetectEngineHttpStatCodeTest10(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf1[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len1 = sizeof(http_buf1) - 1; - uint8_t http_buf2[] = - "HTTP/1.0 200123 abcdef\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 6\r\n" - "\r\n" - "abcdef"; + uint8_t http_buf2[] = "HTTP/1.0 200123 abcdef\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 6\r\n" + "\r\n" + "abcdef"; uint32_t http_len2 = sizeof(http_buf2) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -1159,11 +1148,11 @@ static int DetectEngineHttpStatCodeTest10(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOCLIENT; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1174,11 +1163,11 @@ static int DetectEngineHttpStatCodeTest10(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http stat code test\"; " - "content:\"200\"; http_stat_code; depth:3; " - "content:!\"124\"; http_stat_code; within:3; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http stat code test\"; " + "content:\"200\"; http_stat_code; depth:3; " + "content:!\"124\"; http_stat_code; within:3; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -1249,18 +1238,17 @@ static int DetectEngineHttpStatCodeTest11(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf1[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len1 = sizeof(http_buf1) - 1; - uint8_t http_buf2[] = - "HTTP/1.0 200123 abcdef\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 6\r\n" - "\r\n" - "abcdef"; + uint8_t http_buf2[] = "HTTP/1.0 200123 abcdef\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 6\r\n" + "\r\n" + "abcdef"; uint32_t http_len2 = sizeof(http_buf2) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -1280,11 +1268,11 @@ static int DetectEngineHttpStatCodeTest11(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOCLIENT; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1295,11 +1283,11 @@ static int DetectEngineHttpStatCodeTest11(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http stat code test\"; " - "content:\"200\"; http_stat_code; depth:3; " - "content:\"124\"; http_stat_code; within:3; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http stat code test\"; " + "content:\"200\"; http_stat_code; depth:3; " + "content:\"124\"; http_stat_code; within:3; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -1370,18 +1358,17 @@ static int DetectEngineHttpStatCodeTest12(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf1[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len1 = sizeof(http_buf1) - 1; - uint8_t http_buf2[] = - "HTTP/1.0 200123 abcdef\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 6\r\n" - "\r\n" - "abcdef"; + uint8_t http_buf2[] = "HTTP/1.0 200123 abcdef\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 6\r\n" + "\r\n" + "abcdef"; uint32_t http_len2 = sizeof(http_buf2) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -1401,11 +1388,11 @@ static int DetectEngineHttpStatCodeTest12(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOCLIENT; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1416,11 +1403,11 @@ static int DetectEngineHttpStatCodeTest12(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http stat code test\"; " - "content:\"20\"; http_stat_code; depth:2; " - "content:\"23\"; http_stat_code; distance:2; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http stat code test\"; " + "content:\"20\"; http_stat_code; depth:2; " + "content:\"23\"; http_stat_code; distance:2; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -1491,18 +1478,17 @@ static int DetectEngineHttpStatCodeTest13(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf1[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len1 = sizeof(http_buf1) - 1; - uint8_t http_buf2[] = - "HTTP/1.0 200123 abcdef\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 6\r\n" - "\r\n" - "abcdef"; + uint8_t http_buf2[] = "HTTP/1.0 200123 abcdef\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 6\r\n" + "\r\n" + "abcdef"; uint32_t http_len2 = sizeof(http_buf2) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -1522,11 +1508,11 @@ static int DetectEngineHttpStatCodeTest13(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOCLIENT; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1537,11 +1523,11 @@ static int DetectEngineHttpStatCodeTest13(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http stat code test\"; " - "content:\"20\"; http_stat_code; depth:3; " - "content:!\"25\"; http_stat_code; distance:2; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http stat code test\"; " + "content:\"20\"; http_stat_code; depth:3; " + "content:!\"25\"; http_stat_code; distance:2; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -1612,18 +1598,17 @@ static int DetectEngineHttpStatCodeTest14(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf1[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len1 = sizeof(http_buf1) - 1; - uint8_t http_buf2[] = - "HTTP/1.0 200123 abcdef\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 6\r\n" - "\r\n" - "abcdef"; + uint8_t http_buf2[] = "HTTP/1.0 200123 abcdef\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 6\r\n" + "\r\n" + "abcdef"; uint32_t http_len2 = sizeof(http_buf2) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -1643,11 +1628,11 @@ static int DetectEngineHttpStatCodeTest14(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOCLIENT; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1658,11 +1643,11 @@ static int DetectEngineHttpStatCodeTest14(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http stat code test\"; " - "pcre:/20/S; " - "content:\"23\"; http_stat_code; distance:2; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http stat code test\"; " + "pcre:/20/S; " + "content:\"23\"; http_stat_code; distance:2; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -1733,18 +1718,17 @@ static int DetectEngineHttpStatCodeTest15(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf1[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len1 = sizeof(http_buf1) - 1; - uint8_t http_buf2[] = - "HTTP/1.0 200123 abcdef\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 6\r\n" - "\r\n" - "abcdef"; + uint8_t http_buf2[] = "HTTP/1.0 200123 abcdef\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 6\r\n" + "\r\n" + "abcdef"; uint32_t http_len2 = sizeof(http_buf2) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -1764,11 +1748,11 @@ static int DetectEngineHttpStatCodeTest15(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOCLIENT; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1779,11 +1763,11 @@ static int DetectEngineHttpStatCodeTest15(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http stat code test\"; " - "pcre:/200/S; " - "content:!\"124\"; http_stat_code; distance:0; within:3; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http stat code test\"; " + "pcre:/200/S; " + "content:!\"124\"; http_stat_code; distance:0; within:3; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -1875,7 +1859,7 @@ static int DetectHttpStatCodeSigTest01(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOCLIENT; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1888,8 +1872,9 @@ static int DetectHttpStatCodeSigTest01(void) de_ctx->flags |= DE_QUIET; - s = de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any (msg:" - "\"HTTP status code\"; content:\"200\"; http_stat_code; sid:1;)"); + s = de_ctx->sig_list = + SigInit(de_ctx, "alert http any any -> any any (msg:" + "\"HTTP status code\"; content:\"200\"; http_stat_code; sid:1;)"); if (s == NULL) { printf("sig parse failed: "); goto end; @@ -1973,7 +1958,7 @@ static int DetectHttpStatCodeSigTest02(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOCLIENT; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1985,16 +1970,16 @@ static int DetectHttpStatCodeSigTest02(void) de_ctx->flags |= DE_QUIET; - s = de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any (msg:" - "\"HTTP status code\"; content:\"no\"; " - "http_stat_code; sid:1;)"); + s = de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any (msg:" + "\"HTTP status code\"; content:\"no\"; " + "http_stat_code; sid:1;)"); if (s == NULL) { goto end; } - s->next = SigInit(de_ctx,"alert http any any -> any any (msg:\"HTTP " - "Status code\"; content:\"100\";" - "http_stat_code; sid:2;)"); + s->next = SigInit(de_ctx, "alert http any any -> any any (msg:\"HTTP " + "Status code\"; content:\"100\";" + "http_stat_code; sid:2;)"); if (s->next == NULL) { goto end; } @@ -2085,7 +2070,7 @@ static int DetectHttpStatCodeSigTest03(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOCLIENT; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -2097,16 +2082,16 @@ static int DetectHttpStatCodeSigTest03(void) de_ctx->flags |= DE_QUIET; - s = de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any (msg:" - "\"HTTP status code\"; content:\"FAIL\"; " - "http_stat_code; sid:1;)"); + s = de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any (msg:" + "\"HTTP status code\"; content:\"FAIL\"; " + "http_stat_code; sid:1;)"); if (s == NULL) { goto end; } - s->next = SigInit(de_ctx,"alert http any any -> any any (msg:\"HTTP " - "Status code nocase\"; content:\"fail\"; nocase; " - "http_stat_code; sid:2;)"); + s->next = SigInit(de_ctx, "alert http any any -> any any (msg:\"HTTP " + "Status code nocase\"; content:\"fail\"; nocase; " + "http_stat_code; sid:2;)"); if (s->next == NULL) { goto end; } @@ -2197,7 +2182,7 @@ static int DetectHttpStatCodeSigTest04(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOCLIENT; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -2209,16 +2194,16 @@ static int DetectHttpStatCodeSigTest04(void) de_ctx->flags |= DE_QUIET; - s = de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any (msg:" - "\"HTTP status code\"; content:\"200\"; " - "http_stat_code; sid:1;)"); + s = de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any (msg:" + "\"HTTP status code\"; content:\"200\"; " + "http_stat_code; sid:1;)"); if (s == NULL) { goto end; } - s->next = SigInit(de_ctx,"alert http any any -> any any (msg:\"HTTP " - "Status code negation\"; content:!\"100\"; nocase; " - "http_stat_code; sid:2;)"); + s->next = SigInit(de_ctx, "alert http any any -> any any (msg:\"HTTP " + "Status code negation\"; content:!\"100\"; nocase; " + "http_stat_code; sid:2;)"); if (s->next == NULL) { goto end; } @@ -2280,38 +2265,23 @@ static int DetectHttpStatCodeSigTest04(void) /** * \brief Register the UNITTESTS for the http_stat_code keyword */ -void DetectHttpStatCodeRegisterTests (void) +void DetectHttpStatCodeRegisterTests(void) { - UtRegisterTest("DetectEngineHttpStatCodeTest01", - DetectEngineHttpStatCodeTest01); - UtRegisterTest("DetectEngineHttpStatCodeTest02", - DetectEngineHttpStatCodeTest02); - UtRegisterTest("DetectEngineHttpStatCodeTest03", - DetectEngineHttpStatCodeTest03); - UtRegisterTest("DetectEngineHttpStatCodeTest04", - DetectEngineHttpStatCodeTest04); - UtRegisterTest("DetectEngineHttpStatCodeTest05", - DetectEngineHttpStatCodeTest05); - UtRegisterTest("DetectEngineHttpStatCodeTest06", - DetectEngineHttpStatCodeTest06); - UtRegisterTest("DetectEngineHttpStatCodeTest07", - DetectEngineHttpStatCodeTest07); - UtRegisterTest("DetectEngineHttpStatCodeTest08", - DetectEngineHttpStatCodeTest08); - UtRegisterTest("DetectEngineHttpStatCodeTest09", - DetectEngineHttpStatCodeTest09); - UtRegisterTest("DetectEngineHttpStatCodeTest10", - DetectEngineHttpStatCodeTest10); - UtRegisterTest("DetectEngineHttpStatCodeTest11", - DetectEngineHttpStatCodeTest11); - UtRegisterTest("DetectEngineHttpStatCodeTest12", - DetectEngineHttpStatCodeTest12); - UtRegisterTest("DetectEngineHttpStatCodeTest13", - DetectEngineHttpStatCodeTest13); - UtRegisterTest("DetectEngineHttpStatCodeTest14", - DetectEngineHttpStatCodeTest14); - UtRegisterTest("DetectEngineHttpStatCodeTest15", - DetectEngineHttpStatCodeTest15); + UtRegisterTest("DetectEngineHttpStatCodeTest01", DetectEngineHttpStatCodeTest01); + UtRegisterTest("DetectEngineHttpStatCodeTest02", DetectEngineHttpStatCodeTest02); + UtRegisterTest("DetectEngineHttpStatCodeTest03", DetectEngineHttpStatCodeTest03); + UtRegisterTest("DetectEngineHttpStatCodeTest04", DetectEngineHttpStatCodeTest04); + UtRegisterTest("DetectEngineHttpStatCodeTest05", DetectEngineHttpStatCodeTest05); + UtRegisterTest("DetectEngineHttpStatCodeTest06", DetectEngineHttpStatCodeTest06); + UtRegisterTest("DetectEngineHttpStatCodeTest07", DetectEngineHttpStatCodeTest07); + UtRegisterTest("DetectEngineHttpStatCodeTest08", DetectEngineHttpStatCodeTest08); + UtRegisterTest("DetectEngineHttpStatCodeTest09", DetectEngineHttpStatCodeTest09); + UtRegisterTest("DetectEngineHttpStatCodeTest10", DetectEngineHttpStatCodeTest10); + UtRegisterTest("DetectEngineHttpStatCodeTest11", DetectEngineHttpStatCodeTest11); + UtRegisterTest("DetectEngineHttpStatCodeTest12", DetectEngineHttpStatCodeTest12); + UtRegisterTest("DetectEngineHttpStatCodeTest13", DetectEngineHttpStatCodeTest13); + UtRegisterTest("DetectEngineHttpStatCodeTest14", DetectEngineHttpStatCodeTest14); + UtRegisterTest("DetectEngineHttpStatCodeTest15", DetectEngineHttpStatCodeTest15); UtRegisterTest("DetectHttpStatCodeSigTest01", DetectHttpStatCodeSigTest01); UtRegisterTest("DetectHttpStatCodeSigTest02", DetectHttpStatCodeSigTest02); diff --git a/src/tests/detect-http-stat-msg.c b/src/tests/detect-http-stat-msg.c index 60251ec8ede5..3b4c814fb3a9 100644 --- a/src/tests/detect-http-stat-msg.c +++ b/src/tests/detect-http-stat-msg.c @@ -42,7 +42,7 @@ #include "../detect-engine-alert.h" static int DetectEngineHttpStatMsgTest01(void) - { +{ TcpSession ssn; Packet *p1 = NULL; Packet *p2 = NULL; @@ -51,18 +51,17 @@ static int DetectEngineHttpStatMsgTest01(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf1[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len1 = sizeof(http_buf1) - 1; - uint8_t http_buf2[] = - "HTTP/1.0 200 message\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 7\r\n" - "\r\n" - "message"; + uint8_t http_buf2[] = "HTTP/1.0 200 message\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 7\r\n" + "\r\n" + "message"; uint32_t http_len2 = sizeof(http_buf2) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -82,11 +81,11 @@ static int DetectEngineHttpStatMsgTest01(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOCLIENT; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -97,10 +96,10 @@ static int DetectEngineHttpStatMsgTest01(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http stat msg test\"; " - "content:\"message\"; http_stat_msg; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http stat msg test\"; " + "content:\"message\"; http_stat_msg; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -170,18 +169,17 @@ static int DetectEngineHttpStatMsgTest02(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf1[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len1 = sizeof(http_buf1) - 1; - uint8_t http_buf2[] = - "HTTP/1.0 200 xxxxABC\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 7\r\n" - "\r\n" - "xxxxABC"; + uint8_t http_buf2[] = "HTTP/1.0 200 xxxxABC\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 7\r\n" + "\r\n" + "xxxxABC"; uint32_t http_len2 = sizeof(http_buf2) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -200,7 +198,7 @@ static int DetectEngineHttpStatMsgTest02(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOCLIENT; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -211,10 +209,10 @@ static int DetectEngineHttpStatMsgTest02(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http stat msg test\"; " - "content:\"ABC\"; http_stat_msg; offset:4; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http stat msg test\"; " + "content:\"ABC\"; http_stat_msg; offset:4; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -277,21 +275,19 @@ static int DetectEngineHttpStatMsgTest03(void) HtpState *http_state = NULL; Flow f; int result = 0; - uint8_t http_buf1[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len1 = sizeof(http_buf1) - 1; - uint8_t http_buf2[] = - "HTTP/1.0 200 1234567"; + uint8_t http_buf2[] = "HTTP/1.0 200 1234567"; uint32_t http_len2 = sizeof(http_buf2) - 1; - uint8_t http_buf3[] = - "8901234ABC\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 17\r\n" - "\r\n" - "12345678901234ABC"; + uint8_t http_buf3[] = "8901234ABC\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 17\r\n" + "\r\n" + "12345678901234ABC"; uint32_t http_len3 = sizeof(http_buf3) - 1; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -310,11 +306,11 @@ static int DetectEngineHttpStatMsgTest03(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOCLIENT; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -325,10 +321,10 @@ static int DetectEngineHttpStatMsgTest03(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http stat msg test\"; " - "content:\"ABC\"; http_stat_msg; offset:14; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http stat msg test\"; " + "content:\"ABC\"; http_stat_msg; offset:14; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -407,18 +403,17 @@ static int DetectEngineHttpStatMsgTest04(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf1[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len1 = sizeof(http_buf1) - 1; - uint8_t http_buf2[] = - "HTTP/1.0 200 abcdef\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 6\r\n" - "\r\n" - "abcdef"; + uint8_t http_buf2[] = "HTTP/1.0 200 abcdef\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 6\r\n" + "\r\n" + "abcdef"; uint32_t http_len2 = sizeof(http_buf2) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -438,11 +433,11 @@ static int DetectEngineHttpStatMsgTest04(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOCLIENT; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -453,10 +448,10 @@ static int DetectEngineHttpStatMsgTest04(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http stat msg test\"; " - "content:!\"abc\"; http_stat_msg; offset:3; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http stat msg test\"; " + "content:!\"abc\"; http_stat_msg; offset:3; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -527,18 +522,17 @@ static int DetectEngineHttpStatMsgTest05(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf1[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len1 = sizeof(http_buf1) - 1; - uint8_t http_buf2[] = - "HTTP/1.0 200 abcdef\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 6\r\n" - "\r\n" - "abcdef"; + uint8_t http_buf2[] = "HTTP/1.0 200 abcdef\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 6\r\n" + "\r\n" + "abcdef"; uint32_t http_len2 = sizeof(http_buf2) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -558,11 +552,11 @@ static int DetectEngineHttpStatMsgTest05(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOCLIENT; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -573,10 +567,10 @@ static int DetectEngineHttpStatMsgTest05(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http stat msg test\"; " - "content:\"abc\"; http_stat_msg; depth:3; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http stat msg test\"; " + "content:\"abc\"; http_stat_msg; depth:3; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -647,18 +641,17 @@ static int DetectEngineHttpStatMsgTest06(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf1[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len1 = sizeof(http_buf1) - 1; - uint8_t http_buf2[] = - "HTTP/1.0 200 abcdef\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 6\r\n" - "\r\n" - "abcdef"; + uint8_t http_buf2[] = "HTTP/1.0 200 abcdef\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 6\r\n" + "\r\n" + "abcdef"; uint32_t http_len2 = sizeof(http_buf2) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -678,11 +671,11 @@ static int DetectEngineHttpStatMsgTest06(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOCLIENT; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -693,10 +686,10 @@ static int DetectEngineHttpStatMsgTest06(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http stat msg test\"; " - "content:!\"def\"; http_stat_msg; depth:3; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http stat msg test\"; " + "content:!\"def\"; http_stat_msg; depth:3; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -767,18 +760,17 @@ static int DetectEngineHttpStatMsgTest07(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf1[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len1 = sizeof(http_buf1) - 1; - uint8_t http_buf2[] = - "HTTP/1.0 200 abcdef\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 6\r\n" - "\r\n" - "abcdef"; + uint8_t http_buf2[] = "HTTP/1.0 200 abcdef\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 6\r\n" + "\r\n" + "abcdef"; uint32_t http_len2 = sizeof(http_buf2) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -798,11 +790,11 @@ static int DetectEngineHttpStatMsgTest07(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOCLIENT; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -813,10 +805,10 @@ static int DetectEngineHttpStatMsgTest07(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http stat msg test\"; " - "content:!\"def\"; http_stat_msg; offset:3; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http stat msg test\"; " + "content:!\"def\"; http_stat_msg; offset:3; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -887,18 +879,17 @@ static int DetectEngineHttpStatMsgTest08(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf1[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len1 = sizeof(http_buf1) - 1; - uint8_t http_buf2[] = - "HTTP/1.0 200 abcdef\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 6\r\n" - "\r\n" - "abcdef"; + uint8_t http_buf2[] = "HTTP/1.0 200 abcdef\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 6\r\n" + "\r\n" + "abcdef"; uint32_t http_len2 = sizeof(http_buf2) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -918,11 +909,11 @@ static int DetectEngineHttpStatMsgTest08(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOCLIENT; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -933,10 +924,10 @@ static int DetectEngineHttpStatMsgTest08(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http stat msg test\"; " - "content:!\"abc\"; http_stat_msg; depth:3; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http stat msg test\"; " + "content:!\"abc\"; http_stat_msg; depth:3; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -1007,18 +998,17 @@ static int DetectEngineHttpStatMsgTest09(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf1[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len1 = sizeof(http_buf1) - 1; - uint8_t http_buf2[] = - "HTTP/1.0 200 abcdef\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 6\r\n" - "\r\n" - "abcdef"; + uint8_t http_buf2[] = "HTTP/1.0 200 abcdef\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 6\r\n" + "\r\n" + "abcdef"; uint32_t http_len2 = sizeof(http_buf2) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -1038,11 +1028,11 @@ static int DetectEngineHttpStatMsgTest09(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOCLIENT; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1053,11 +1043,11 @@ static int DetectEngineHttpStatMsgTest09(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http stat msg test\"; " - "content:\"abc\"; http_stat_msg; depth:3; " - "content:\"def\"; http_stat_msg; within:3; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http stat msg test\"; " + "content:\"abc\"; http_stat_msg; depth:3; " + "content:\"def\"; http_stat_msg; within:3; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -1128,18 +1118,17 @@ static int DetectEngineHttpStatMsgTest10(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf1[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len1 = sizeof(http_buf1) - 1; - uint8_t http_buf2[] = - "HTTP/1.0 200 abcdef\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 6\r\n" - "\r\n" - "abcdef"; + uint8_t http_buf2[] = "HTTP/1.0 200 abcdef\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 6\r\n" + "\r\n" + "abcdef"; uint32_t http_len2 = sizeof(http_buf2) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -1159,11 +1148,11 @@ static int DetectEngineHttpStatMsgTest10(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOCLIENT; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1174,11 +1163,11 @@ static int DetectEngineHttpStatMsgTest10(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http stat msg test\"; " - "content:\"abc\"; http_stat_msg; depth:3; " - "content:!\"xyz\"; http_stat_msg; within:3; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http stat msg test\"; " + "content:\"abc\"; http_stat_msg; depth:3; " + "content:!\"xyz\"; http_stat_msg; within:3; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -1249,18 +1238,17 @@ static int DetectEngineHttpStatMsgTest11(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf1[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len1 = sizeof(http_buf1) - 1; - uint8_t http_buf2[] = - "HTTP/1.0 200 abcdef\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 6\r\n" - "\r\n" - "abcdef"; + uint8_t http_buf2[] = "HTTP/1.0 200 abcdef\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 6\r\n" + "\r\n" + "abcdef"; uint32_t http_len2 = sizeof(http_buf2) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -1280,11 +1268,11 @@ static int DetectEngineHttpStatMsgTest11(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOCLIENT; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1295,11 +1283,11 @@ static int DetectEngineHttpStatMsgTest11(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http stat msg test\"; " - "content:\"abc\"; http_stat_msg; depth:3; " - "content:\"xyz\"; http_stat_msg; within:3; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http stat msg test\"; " + "content:\"abc\"; http_stat_msg; depth:3; " + "content:\"xyz\"; http_stat_msg; within:3; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -1370,18 +1358,17 @@ static int DetectEngineHttpStatMsgTest12(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf1[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len1 = sizeof(http_buf1) - 1; - uint8_t http_buf2[] = - "HTTP/1.0 200 abcdef\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 6\r\n" - "\r\n" - "abcdef"; + uint8_t http_buf2[] = "HTTP/1.0 200 abcdef\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 6\r\n" + "\r\n" + "abcdef"; uint32_t http_len2 = sizeof(http_buf2) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -1401,11 +1388,11 @@ static int DetectEngineHttpStatMsgTest12(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOCLIENT; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1416,11 +1403,11 @@ static int DetectEngineHttpStatMsgTest12(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http stat msg test\"; " - "content:\"ab\"; http_stat_msg; depth:2; " - "content:\"ef\"; http_stat_msg; distance:2; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http stat msg test\"; " + "content:\"ab\"; http_stat_msg; depth:2; " + "content:\"ef\"; http_stat_msg; distance:2; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -1491,18 +1478,17 @@ static int DetectEngineHttpStatMsgTest13(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf1[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len1 = sizeof(http_buf1) - 1; - uint8_t http_buf2[] = - "HTTP/1.0 200 abcdef\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 6\r\n" - "\r\n" - "abcdef"; + uint8_t http_buf2[] = "HTTP/1.0 200 abcdef\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 6\r\n" + "\r\n" + "abcdef"; uint32_t http_len2 = sizeof(http_buf2) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -1522,11 +1508,11 @@ static int DetectEngineHttpStatMsgTest13(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOCLIENT; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1537,11 +1523,11 @@ static int DetectEngineHttpStatMsgTest13(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http stat msg test\"; " - "content:\"ab\"; http_stat_msg; depth:3; " - "content:!\"yz\"; http_stat_msg; distance:2; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http stat msg test\"; " + "content:\"ab\"; http_stat_msg; depth:3; " + "content:!\"yz\"; http_stat_msg; distance:2; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -1612,18 +1598,17 @@ static int DetectEngineHttpStatMsgTest14(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf1[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len1 = sizeof(http_buf1) - 1; - uint8_t http_buf2[] = - "HTTP/1.0 200 abcdef\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 6\r\n" - "\r\n" - "abcdef"; + uint8_t http_buf2[] = "HTTP/1.0 200 abcdef\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 6\r\n" + "\r\n" + "abcdef"; uint32_t http_len2 = sizeof(http_buf2) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -1643,11 +1628,11 @@ static int DetectEngineHttpStatMsgTest14(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOCLIENT; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1658,11 +1643,11 @@ static int DetectEngineHttpStatMsgTest14(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http stat msg test\"; " - "pcre:/ab/Y; " - "content:\"ef\"; http_stat_msg; distance:2; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http stat msg test\"; " + "pcre:/ab/Y; " + "content:\"ef\"; http_stat_msg; distance:2; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -1733,18 +1718,17 @@ static int DetectEngineHttpStatMsgTest15(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http_buf1[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "\r\n"; + uint8_t http_buf1[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "\r\n"; uint32_t http_len1 = sizeof(http_buf1) - 1; - uint8_t http_buf2[] = - "HTTP/1.0 200 abcdef\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 6\r\n" - "\r\n" - "abcdef"; + uint8_t http_buf2[] = "HTTP/1.0 200 abcdef\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 6\r\n" + "\r\n" + "abcdef"; uint32_t http_len2 = sizeof(http_buf2) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -1764,11 +1748,11 @@ static int DetectEngineHttpStatMsgTest15(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOCLIENT; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1779,11 +1763,11 @@ static int DetectEngineHttpStatMsgTest15(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http stat msg test\"; " - "pcre:/abc/Y; " - "content:!\"xyz\"; http_stat_msg; distance:0; within:3; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http stat msg test\"; " + "pcre:/abc/Y; " + "content:!\"xyz\"; http_stat_msg; distance:0; within:3; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -1875,7 +1859,7 @@ static int DetectHttpStatMsgSigTest01(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOCLIENT; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1887,16 +1871,16 @@ static int DetectHttpStatMsgSigTest01(void) de_ctx->flags |= DE_QUIET; - s = de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any (msg:" - "\"HTTP status message\"; content:\"OK\"; " - "http_stat_msg; sid:1;)"); + s = de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any (msg:" + "\"HTTP status message\"; content:\"OK\"; " + "http_stat_msg; sid:1;)"); if (s == NULL) { goto end; } - s->next = SigInit(de_ctx,"alert http any any -> any any (msg:\"HTTP " - "Status message nocase\"; content:\"ok\"; nocase; " - "http_stat_msg; sid:2;)"); + s->next = SigInit(de_ctx, "alert http any any -> any any (msg:\"HTTP " + "Status message nocase\"; content:\"ok\"; nocase; " + "http_stat_msg; sid:2;)"); if (s->next == NULL) { goto end; } @@ -1986,7 +1970,7 @@ static int DetectHttpStatMsgSigTest02(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOCLIENT; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1998,9 +1982,9 @@ static int DetectHttpStatMsgSigTest02(void) de_ctx->flags |= DE_QUIET; - s = de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any (msg:" - "\"HTTP status message\"; content:\"no\"; " - "http_stat_msg; sid:1;)"); + s = de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any (msg:" + "\"HTTP status message\"; content:\"no\"; " + "http_stat_msg; sid:1;)"); if (s == NULL) { goto end; } @@ -2087,7 +2071,7 @@ static int DetectHttpStatMsgSigTest03(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOCLIENT; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -2099,16 +2083,16 @@ static int DetectHttpStatMsgSigTest03(void) de_ctx->flags |= DE_QUIET; - s = de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any (msg:" - "\"HTTP status message\"; content:\"ok\"; " - "nocase; http_stat_msg; sid:1;)"); + s = de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any (msg:" + "\"HTTP status message\"; content:\"ok\"; " + "nocase; http_stat_msg; sid:1;)"); if (s == NULL) { goto end; } - s->next = SigInit(de_ctx,"alert http any any -> any any (msg:\"HTTP " - "Status message nocase\"; content:!\"Not\"; " - "http_stat_msg; sid:2;)"); + s->next = SigInit(de_ctx, "alert http any any -> any any (msg:\"HTTP " + "Status message nocase\"; content:!\"Not\"; " + "http_stat_msg; sid:2;)"); if (s->next == NULL) { goto end; } @@ -2141,11 +2125,11 @@ static int DetectHttpStatMsgSigTest03(void) /* do detect */ SigMatchSignatures(&th_v, de_ctx, det_ctx, p); - if (! PacketAlertCheck(p, 1)) { + if (!PacketAlertCheck(p, 1)) { printf("sid 1 didn't matched but should have: "); goto end; } - if (! PacketAlertCheck(p, 2)) { + if (!PacketAlertCheck(p, 2)) { printf("sid 2 didn't matched but should have: "); goto end; } @@ -2170,42 +2154,27 @@ static int DetectHttpStatMsgSigTest03(void) /** * \brief Register the UNITTESTS for the http_stat_msg keyword */ -void DetectHttpStatMsgRegisterTests (void) +void DetectHttpStatMsgRegisterTests(void) { UtRegisterTest("DetectHttpStatMsgSigTest01", DetectHttpStatMsgSigTest01); UtRegisterTest("DetectHttpStatMsgSigTest02", DetectHttpStatMsgSigTest02); UtRegisterTest("DetectHttpStatMsgSigTest03", DetectHttpStatMsgSigTest03); - UtRegisterTest("DetectEngineHttpStatMsgTest01", - DetectEngineHttpStatMsgTest01); - UtRegisterTest("DetectEngineHttpStatMsgTest02", - DetectEngineHttpStatMsgTest02); - UtRegisterTest("DetectEngineHttpStatMsgTest03", - DetectEngineHttpStatMsgTest03); - UtRegisterTest("DetectEngineHttpStatMsgTest04", - DetectEngineHttpStatMsgTest04); - UtRegisterTest("DetectEngineHttpStatMsgTest05", - DetectEngineHttpStatMsgTest05); - UtRegisterTest("DetectEngineHttpStatMsgTest06", - DetectEngineHttpStatMsgTest06); - UtRegisterTest("DetectEngineHttpStatMsgTest07", - DetectEngineHttpStatMsgTest07); - UtRegisterTest("DetectEngineHttpStatMsgTest08", - DetectEngineHttpStatMsgTest08); - UtRegisterTest("DetectEngineHttpStatMsgTest09", - DetectEngineHttpStatMsgTest09); - UtRegisterTest("DetectEngineHttpStatMsgTest10", - DetectEngineHttpStatMsgTest10); - UtRegisterTest("DetectEngineHttpStatMsgTest11", - DetectEngineHttpStatMsgTest11); - UtRegisterTest("DetectEngineHttpStatMsgTest12", - DetectEngineHttpStatMsgTest12); - UtRegisterTest("DetectEngineHttpStatMsgTest13", - DetectEngineHttpStatMsgTest13); - UtRegisterTest("DetectEngineHttpStatMsgTest14", - DetectEngineHttpStatMsgTest14); - UtRegisterTest("DetectEngineHttpStatMsgTest15", - DetectEngineHttpStatMsgTest15); + UtRegisterTest("DetectEngineHttpStatMsgTest01", DetectEngineHttpStatMsgTest01); + UtRegisterTest("DetectEngineHttpStatMsgTest02", DetectEngineHttpStatMsgTest02); + UtRegisterTest("DetectEngineHttpStatMsgTest03", DetectEngineHttpStatMsgTest03); + UtRegisterTest("DetectEngineHttpStatMsgTest04", DetectEngineHttpStatMsgTest04); + UtRegisterTest("DetectEngineHttpStatMsgTest05", DetectEngineHttpStatMsgTest05); + UtRegisterTest("DetectEngineHttpStatMsgTest06", DetectEngineHttpStatMsgTest06); + UtRegisterTest("DetectEngineHttpStatMsgTest07", DetectEngineHttpStatMsgTest07); + UtRegisterTest("DetectEngineHttpStatMsgTest08", DetectEngineHttpStatMsgTest08); + UtRegisterTest("DetectEngineHttpStatMsgTest09", DetectEngineHttpStatMsgTest09); + UtRegisterTest("DetectEngineHttpStatMsgTest10", DetectEngineHttpStatMsgTest10); + UtRegisterTest("DetectEngineHttpStatMsgTest11", DetectEngineHttpStatMsgTest11); + UtRegisterTest("DetectEngineHttpStatMsgTest12", DetectEngineHttpStatMsgTest12); + UtRegisterTest("DetectEngineHttpStatMsgTest13", DetectEngineHttpStatMsgTest13); + UtRegisterTest("DetectEngineHttpStatMsgTest14", DetectEngineHttpStatMsgTest14); + UtRegisterTest("DetectEngineHttpStatMsgTest15", DetectEngineHttpStatMsgTest15); } /** diff --git a/src/tests/detect-http-uri.c b/src/tests/detect-http-uri.c index 8c60d430588e..afb08d69d4e4 100644 --- a/src/tests/detect-http-uri.c +++ b/src/tests/detect-http-uri.c @@ -42,12 +42,12 @@ static int UriTestSig01(void) Flow f; HtpState *http_state = NULL; uint8_t http_buf1[] = "POST /one HTTP/1.0\r\n" - "User-Agent: Mozilla/1.0\r\n" - "Cookie: hellocatch\r\n\r\n"; + "User-Agent: Mozilla/1.0\r\n" + "Cookie: hellocatch\r\n\r\n"; uint32_t http_buf1_len = sizeof(http_buf1) - 1; uint8_t http_buf2[] = "POST /oneself HTTP/1.0\r\n" - "User-Agent: Mozilla/1.0\r\n" - "Cookie: hellocatch\r\n\r\n"; + "User-Agent: Mozilla/1.0\r\n" + "Cookie: hellocatch\r\n\r\n"; uint32_t http_buf2_len = sizeof(http_buf2) - 1; TcpSession ssn; Packet *p = NULL; @@ -68,7 +68,7 @@ static int UriTestSig01(void) f.flags |= FLOW_IPV4; p->flow = &f; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; f.alproto = ALPROTO_HTTP1; @@ -82,8 +82,8 @@ static int UriTestSig01(void) de_ctx->flags |= DE_QUIET; s = de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"Test uricontent option\"; " - "uricontent:\"one\"; sid:1;)"); + "(msg:\"Test uricontent option\"; " + "uricontent:\"one\"; sid:1;)"); if (s == NULL) { goto end; } @@ -158,12 +158,12 @@ static int UriTestSig02(void) Flow f; HtpState *http_state = NULL; uint8_t http_buf1[] = "POST /on HTTP/1.0\r\n" - "User-Agent: Mozilla/1.0\r\n" - "Cookie: hellocatch\r\n\r\n"; + "User-Agent: Mozilla/1.0\r\n" + "Cookie: hellocatch\r\n\r\n"; uint32_t http_buf1_len = sizeof(http_buf1) - 1; uint8_t http_buf2[] = "POST /one HTTP/1.0\r\n" - "User-Agent: Mozilla/1.0\r\n" - "Cookie: hellocatch\r\n\r\n"; + "User-Agent: Mozilla/1.0\r\n" + "Cookie: hellocatch\r\n\r\n"; uint32_t http_buf2_len = sizeof(http_buf2) - 1; TcpSession ssn; Packet *p = NULL; @@ -184,7 +184,7 @@ static int UriTestSig02(void) f.flags |= FLOW_IPV4; p->flow = &f; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; f.alproto = ALPROTO_HTTP1; @@ -198,8 +198,8 @@ static int UriTestSig02(void) de_ctx->flags |= DE_QUIET; s = de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"Test pcre /U option\"; " - "pcre:/one/U; sid:1;)"); + "(msg:\"Test pcre /U option\"; " + "pcre:/one/U; sid:1;)"); if (s == NULL) { goto end; } @@ -274,12 +274,12 @@ static int UriTestSig03(void) Flow f; HtpState *http_state = NULL; uint8_t http_buf1[] = "POST /one HTTP/1.0\r\n" - "User-Agent: Mozilla/1.0\r\n" - "Cookie: hellocatch\r\n\r\n"; + "User-Agent: Mozilla/1.0\r\n" + "Cookie: hellocatch\r\n\r\n"; uint32_t http_buf1_len = sizeof(http_buf1) - 1; uint8_t http_buf2[] = "POST /oneself HTTP/1.0\r\n" - "User-Agent: Mozilla/1.0\r\n" - "Cookie: hellocatch\r\n\r\n"; + "User-Agent: Mozilla/1.0\r\n" + "Cookie: hellocatch\r\n\r\n"; uint32_t http_buf2_len = sizeof(http_buf2) - 1; TcpSession ssn; Packet *p = NULL; @@ -300,7 +300,7 @@ static int UriTestSig03(void) f.flags |= FLOW_IPV4; p->flow = &f; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; f.alproto = ALPROTO_HTTP1; @@ -314,8 +314,8 @@ static int UriTestSig03(void) de_ctx->flags |= DE_QUIET; s = de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"Test pcre /U option\"; " - "pcre:/blah/U; sid:1;)"); + "(msg:\"Test pcre /U option\"; " + "pcre:/blah/U; sid:1;)"); if (s == NULL) { goto end; } @@ -390,12 +390,12 @@ static int UriTestSig04(void) Flow f; HtpState *http_state = NULL; uint8_t http_buf1[] = "POST /one HTTP/1.0\r\n" - "User-Agent: Mozilla/1.0\r\n" - "Cookie: hellocatch\r\n\r\n"; + "User-Agent: Mozilla/1.0\r\n" + "Cookie: hellocatch\r\n\r\n"; uint32_t http_buf1_len = sizeof(http_buf1) - 1; uint8_t http_buf2[] = "POST /oneself HTTP/1.0\r\n" - "User-Agent: Mozilla/1.0\r\n" - "Cookie: hellocatch\r\n\r\n"; + "User-Agent: Mozilla/1.0\r\n" + "Cookie: hellocatch\r\n\r\n"; uint32_t http_buf2_len = sizeof(http_buf2) - 1; TcpSession ssn; Packet *p = NULL; @@ -416,7 +416,7 @@ static int UriTestSig04(void) f.flags |= FLOW_IPV4; p->flow = &f; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; f.alproto = ALPROTO_HTTP1; @@ -430,8 +430,8 @@ static int UriTestSig04(void) de_ctx->flags |= DE_QUIET; s = de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"Test urilen option\"; " - "urilen:>20; sid:1;)"); + "(msg:\"Test urilen option\"; " + "urilen:>20; sid:1;)"); if (s == NULL) { goto end; } @@ -506,12 +506,12 @@ static int UriTestSig05(void) Flow f; HtpState *http_state = NULL; uint8_t http_buf1[] = "POST /one HTTP/1.0\r\n" - "User-Agent: Mozilla/1.0\r\n" - "Cookie: hellocatch\r\n\r\n"; + "User-Agent: Mozilla/1.0\r\n" + "Cookie: hellocatch\r\n\r\n"; uint32_t http_buf1_len = sizeof(http_buf1) - 1; uint8_t http_buf2[] = "POST /oneself HTTP/1.0\r\n" - "User-Agent: Mozilla/1.0\r\n" - "Cookie: hellocatch\r\n\r\n"; + "User-Agent: Mozilla/1.0\r\n" + "Cookie: hellocatch\r\n\r\n"; uint32_t http_buf2_len = sizeof(http_buf2) - 1; TcpSession ssn; Packet *p = NULL; @@ -532,7 +532,7 @@ static int UriTestSig05(void) f.flags |= FLOW_IPV4; p->flow = &f; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; f.alproto = ALPROTO_HTTP1; @@ -546,8 +546,8 @@ static int UriTestSig05(void) de_ctx->flags |= DE_QUIET; s = de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"Test urilen option\"; " - "urilen:>4; sid:1;)"); + "(msg:\"Test urilen option\"; " + "urilen:>4; sid:1;)"); if (s == NULL) { goto end; } @@ -622,12 +622,12 @@ static int UriTestSig06(void) Flow f; HtpState *http_state = NULL; uint8_t http_buf1[] = "POST /oneoneoneone HTTP/1.0\r\n" - "User-Agent: Mozilla/1.0\r\n" - "Cookie: hellocatch\r\n\r\n"; + "User-Agent: Mozilla/1.0\r\n" + "Cookie: hellocatch\r\n\r\n"; uint32_t http_buf1_len = sizeof(http_buf1) - 1; uint8_t http_buf2[] = "POST /oneself HTTP/1.0\r\n" - "User-Agent: Mozilla/1.0\r\n" - "Cookie: hellocatch\r\n\r\n"; + "User-Agent: Mozilla/1.0\r\n" + "Cookie: hellocatch\r\n\r\n"; uint32_t http_buf2_len = sizeof(http_buf2) - 1; TcpSession ssn; Packet *p = NULL; @@ -648,7 +648,7 @@ static int UriTestSig06(void) f.flags |= FLOW_IPV4; p->flow = &f; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; f.alproto = ALPROTO_HTTP1; @@ -662,8 +662,8 @@ static int UriTestSig06(void) de_ctx->flags |= DE_QUIET; s = de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"Test pcre /U option\"; " - "pcre:/(oneself)+/U; sid:1;)"); + "(msg:\"Test pcre /U option\"; " + "pcre:/(oneself)+/U; sid:1;)"); if (s == NULL) { goto end; } @@ -738,12 +738,12 @@ static int UriTestSig07(void) Flow f; HtpState *http_state = NULL; uint8_t http_buf1[] = "POST /oneoneoneone HTTP/1.0\r\n" - "User-Agent: Mozilla/1.0\r\n" - "Cookie: hellocatch\r\n\r\n"; + "User-Agent: Mozilla/1.0\r\n" + "Cookie: hellocatch\r\n\r\n"; uint32_t http_buf1_len = sizeof(http_buf1) - 1; uint8_t http_buf2[] = "POST /oneoneself HTTP/1.0\r\n" - "User-Agent: Mozilla/1.0\r\n" - "Cookie: hellocatch\r\n\r\n"; + "User-Agent: Mozilla/1.0\r\n" + "Cookie: hellocatch\r\n\r\n"; uint32_t http_buf2_len = sizeof(http_buf2) - 1; TcpSession ssn; Packet *p = NULL; @@ -764,7 +764,7 @@ static int UriTestSig07(void) f.flags |= FLOW_IPV4; p->flow = &f; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; f.alproto = ALPROTO_HTTP1; @@ -778,8 +778,8 @@ static int UriTestSig07(void) de_ctx->flags |= DE_QUIET; s = de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"Test pcre /U option with urilen \"; " - "pcre:/(one){2,}(self)?/U; urilen:3<>20; sid:1;)"); + "(msg:\"Test pcre /U option with urilen \"; " + "pcre:/(one){2,}(self)?/U; urilen:3<>20; sid:1;)"); if (s == NULL) { goto end; } @@ -854,12 +854,12 @@ static int UriTestSig08(void) Flow f; HtpState *http_state = NULL; uint8_t http_buf1[] = "POST /oneoneoneone HTTP/1.0\r\n" - "User-Agent: Mozilla/1.0\r\n" - "Cookie: hellocatch\r\n\r\n"; + "User-Agent: Mozilla/1.0\r\n" + "Cookie: hellocatch\r\n\r\n"; uint32_t http_buf1_len = sizeof(http_buf1) - 1; uint8_t http_buf2[] = "POST /oneoneself HTTP/1.0\r\n" - "User-Agent: Mozilla/1.0\r\n" - "Cookie: hellocatch\r\n\r\n"; + "User-Agent: Mozilla/1.0\r\n" + "Cookie: hellocatch\r\n\r\n"; uint32_t http_buf2_len = sizeof(http_buf2) - 1; TcpSession ssn; Packet *p = NULL; @@ -880,7 +880,7 @@ static int UriTestSig08(void) f.flags |= FLOW_IPV4; p->flow = &f; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; f.alproto = ALPROTO_HTTP1; @@ -894,8 +894,8 @@ static int UriTestSig08(void) de_ctx->flags |= DE_QUIET; s = de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"Test pcre /U option with urilen\"; " - "pcre:/(blabla){2,}(self)?/U; urilen:3<>20; sid:1;)"); + "(msg:\"Test pcre /U option with urilen\"; " + "pcre:/(blabla){2,}(self)?/U; urilen:3<>20; sid:1;)"); if (s == NULL) { goto end; } @@ -970,12 +970,12 @@ static int UriTestSig09(void) Flow f; HtpState *http_state = NULL; uint8_t http_buf1[] = "POST /oneoneoneone HTTP/1.0\r\n" - "User-Agent: Mozilla/1.0\r\n" - "Cookie: hellocatch\r\n\r\n"; + "User-Agent: Mozilla/1.0\r\n" + "Cookie: hellocatch\r\n\r\n"; uint32_t http_buf1_len = sizeof(http_buf1) - 1; uint8_t http_buf2[] = "POST /oneoneself HTTP/1.0\r\n" - "User-Agent: Mozilla/1.0\r\n" - "Cookie: hellocatch\r\n\r\n"; + "User-Agent: Mozilla/1.0\r\n" + "Cookie: hellocatch\r\n\r\n"; uint32_t http_buf2_len = sizeof(http_buf2) - 1; TcpSession ssn; Packet *p = NULL; @@ -996,7 +996,7 @@ static int UriTestSig09(void) f.flags |= FLOW_IPV4; p->flow = &f; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; f.alproto = ALPROTO_HTTP1; @@ -1010,8 +1010,8 @@ static int UriTestSig09(void) de_ctx->flags |= DE_QUIET; s = de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"Test pcre /U option with urilen \"; " - "pcre:/(one){2,}(self)?/U; urilen:<2; sid:1;)"); + "(msg:\"Test pcre /U option with urilen \"; " + "pcre:/(one){2,}(self)?/U; urilen:<2; sid:1;)"); if (s == NULL) { goto end; } @@ -1086,12 +1086,12 @@ static int UriTestSig12(void) Flow f; HtpState *http_state = NULL; uint8_t http_buf1[] = "POST /oneoneoneone HTTP/1.0\r\n" - "User-Agent: Mozilla/1.0\r\n" - "Cookie: hellocatch\r\n\r\n"; + "User-Agent: Mozilla/1.0\r\n" + "Cookie: hellocatch\r\n\r\n"; uint32_t http_buf1_len = sizeof(http_buf1) - 1; uint8_t http_buf2[] = "POST /oneoneself HTTP/1.0\r\n" - "User-Agent: Mozilla/1.0\r\n" - "Cookie: hellocatch\r\n\r\n"; + "User-Agent: Mozilla/1.0\r\n" + "Cookie: hellocatch\r\n\r\n"; uint32_t http_buf2_len = sizeof(http_buf2) - 1; TcpSession ssn; Packet *p = NULL; @@ -1112,7 +1112,7 @@ static int UriTestSig12(void) f.flags |= FLOW_IPV4; p->flow = &f; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; f.alproto = ALPROTO_HTTP1; @@ -1126,9 +1126,9 @@ static int UriTestSig12(void) de_ctx->flags |= DE_QUIET; s = de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"Test pcre /U, uricontent and urilen option\"; " - "uricontent:\"one\"; " - "pcre:/(one)+self/U; urilen:>2; sid:1;)"); + "(msg:\"Test pcre /U, uricontent and urilen option\"; " + "uricontent:\"one\"; " + "pcre:/(one)+self/U; urilen:>2; sid:1;)"); if (s == NULL) { goto end; } @@ -1203,12 +1203,12 @@ static int UriTestSig13(void) Flow f; HtpState *http_state = NULL; uint8_t http_buf1[] = "POST /one HTTP/1.0\r\n" - "User-Agent: Mozilla/1.0\r\n" - "Cookie: hellocatch\r\n\r\n"; + "User-Agent: Mozilla/1.0\r\n" + "Cookie: hellocatch\r\n\r\n"; uint32_t http_buf1_len = sizeof(http_buf1) - 1; uint8_t http_buf2[] = "POST /oneself HTTP/1.0\r\n" - "User-Agent: Mozilla/1.0\r\n" - "Cookie: hellocatch\r\n\r\n"; + "User-Agent: Mozilla/1.0\r\n" + "Cookie: hellocatch\r\n\r\n"; uint32_t http_buf2_len = sizeof(http_buf2) - 1; TcpSession ssn; Packet *p = NULL; @@ -1229,7 +1229,7 @@ static int UriTestSig13(void) f.flags |= FLOW_IPV4; p->flow = &f; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; f.alproto = ALPROTO_HTTP1; @@ -1243,8 +1243,8 @@ static int UriTestSig13(void) de_ctx->flags |= DE_QUIET; s = de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"Test urilen option\"; " - "urilen:>2; uricontent:\"one\"; sid:1;)"); + "(msg:\"Test urilen option\"; " + "urilen:>2; uricontent:\"one\"; sid:1;)"); if (s == NULL) { goto end; } @@ -1289,7 +1289,6 @@ static int UriTestSig13(void) /* do detect */ SigMatchSignatures(&tv, de_ctx, det_ctx, p); - if (!PacketAlertCheck(p, 1)) { printf("sig 1 didnt alert with payload2, but it should: "); goto end; @@ -1320,12 +1319,12 @@ static int UriTestSig14(void) Flow f; HtpState *http_state = NULL; uint8_t http_buf1[] = "POST /one HTTP/1.0\r\n" - "User-Agent: Mozilla/1.0\r\n" - "Cookie: hellocatch\r\n\r\n"; + "User-Agent: Mozilla/1.0\r\n" + "Cookie: hellocatch\r\n\r\n"; uint32_t http_buf1_len = sizeof(http_buf1) - 1; uint8_t http_buf2[] = "POST /oneself HTTP/1.0\r\n" - "User-Agent: Mozilla/1.0\r\n" - "Cookie: hellocatch\r\n\r\n"; + "User-Agent: Mozilla/1.0\r\n" + "Cookie: hellocatch\r\n\r\n"; uint32_t http_buf2_len = sizeof(http_buf2) - 1; TcpSession ssn; Packet *p = NULL; @@ -1346,7 +1345,7 @@ static int UriTestSig14(void) f.flags |= FLOW_IPV4; p->flow = &f; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; f.alproto = ALPROTO_HTTP1; @@ -1360,8 +1359,8 @@ static int UriTestSig14(void) de_ctx->flags |= DE_QUIET; s = de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"Test uricontent option\"; " - "uricontent:\"one\"; pcre:/one(self)?/U;sid:1;)"); + "(msg:\"Test uricontent option\"; " + "uricontent:\"one\"; pcre:/one(self)?/U;sid:1;)"); if (s == NULL) { goto end; } @@ -1406,7 +1405,6 @@ static int UriTestSig14(void) /* do detect */ SigMatchSignatures(&tv, de_ctx, det_ctx, p); - if (!PacketAlertCheck(p, 1)) { printf("sig 1 didnt alert with payload2, but it should: "); goto end; @@ -1437,12 +1435,12 @@ static int UriTestSig15(void) Flow f; HtpState *http_state = NULL; uint8_t http_buf1[] = "POST /one HTTP/1.0\r\n" - "User-Agent: Mozilla/1.0\r\n" - "Cookie: hellocatch\r\n\r\n"; + "User-Agent: Mozilla/1.0\r\n" + "Cookie: hellocatch\r\n\r\n"; uint32_t http_buf1_len = sizeof(http_buf1) - 1; uint8_t http_buf2[] = "POST /oneself HTTP/1.0\r\n" - "User-Agent: Mozilla/1.0\r\n" - "Cookie: hellocatch\r\n\r\n"; + "User-Agent: Mozilla/1.0\r\n" + "Cookie: hellocatch\r\n\r\n"; uint32_t http_buf2_len = sizeof(http_buf2) - 1; TcpSession ssn; Packet *p = NULL; @@ -1463,7 +1461,7 @@ static int UriTestSig15(void) f.flags |= FLOW_IPV4; p->flow = &f; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; f.alproto = ALPROTO_HTTP1; @@ -1477,8 +1475,8 @@ static int UriTestSig15(void) de_ctx->flags |= DE_QUIET; s = de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"Test uricontent option\"; " - "uricontent:\"one\"; pcre:/^\\/one(self)?$/U;sid:1;)"); + "(msg:\"Test uricontent option\"; " + "uricontent:\"one\"; pcre:/^\\/one(self)?$/U;sid:1;)"); if (s == NULL) { goto end; } @@ -1523,7 +1521,6 @@ static int UriTestSig15(void) /* do detect */ SigMatchSignatures(&tv, de_ctx, det_ctx, p); - if (!PacketAlertCheck(p, 1)) { printf("sig 1 didnt alert with payload2, but it should: "); goto end; @@ -1552,12 +1549,12 @@ static int UriTestSig16(void) { HtpState *http_state = NULL; uint8_t http_buf1[] = "POST /search?q=123&aq=7123abcee HTTP/1.0\r\n" - "User-Agent: Mozilla/1.0/\r\n" - "Host: 1.2.3.4\r\n\r\n"; + "User-Agent: Mozilla/1.0/\r\n" + "Host: 1.2.3.4\r\n\r\n"; uint32_t http_buf1_len = sizeof(http_buf1) - 1; uint8_t http_buf2[] = "POST /search?q=123&aq=7123abcee HTTP/1.0\r\n" - "User-Agent: Mozilla/1.0\r\n" - "Cookie: hellocatch\r\n\r\n"; + "User-Agent: Mozilla/1.0\r\n" + "Cookie: hellocatch\r\n\r\n"; uint32_t http_buf2_len = sizeof(http_buf2) - 1; TcpSession ssn; Signature *s = NULL; @@ -1589,7 +1586,11 @@ static int UriTestSig16(void) FAIL_IF_NULL(de_ctx); de_ctx->flags |= DE_QUIET; - s = de_ctx->sig_list = SigInit(de_ctx, "drop tcp any any -> any any (flow:to_server,established; uricontent:\"/search?q=\"; pcre:\"/^\\/search\\?q=[0-9]{1,3}(&aq=7(\\?[0-9a-f]{8})?)?/U\"; pcre:\"/\\x0d\\x0aHost\\: \\d+\\.\\d+\\.\\d+\\.\\d+\\x0d\\x0a/\"; sid:2009024; rev:9;)"); + s = de_ctx->sig_list = SigInit(de_ctx, + "drop tcp any any -> any any (flow:to_server,established; uricontent:\"/search?q=\"; " + "pcre:\"/^\\/search\\?q=[0-9]{1,3}(&aq=7(\\?[0-9a-f]{8})?)?/U\"; " + "pcre:\"/\\x0d\\x0aHost\\: \\d+\\.\\d+\\.\\d+\\.\\d+\\x0d\\x0a/\"; sid:2009024; " + "rev:9;)"); FAIL_IF_NULL(s); SigGroupBuild(de_ctx); @@ -1642,7 +1643,7 @@ static int UriTestSig17(void) { int result = 0; uint8_t *http_buf = (uint8_t *)"POST /now_this_is_is_big_big_string_now HTTP/1.0\r\n" - "User-Agent: Mozilla/1.0\r\n"; + "User-Agent: Mozilla/1.0\r\n"; uint32_t http_buf_len = strlen((char *)http_buf); Flow f; TcpSession ssn; @@ -1664,7 +1665,7 @@ static int UriTestSig17(void) f.flags |= FLOW_IPV4; p->flow = &f; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; f.alproto = ALPROTO_HTTP1; @@ -1678,10 +1679,10 @@ static int UriTestSig17(void) de_ctx->flags |= DE_QUIET; de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"test multiple relative uricontents\"; " - "uricontent:\"this\"; uricontent:\"is\"; within:6; " - "uricontent:\"big\"; within:8; " - "uricontent:\"string\"; within:8; sid:1;)"); + "(msg:\"test multiple relative uricontents\"; " + "uricontent:\"this\"; uricontent:\"is\"; within:6; " + "uricontent:\"big\"; within:8; " + "uricontent:\"string\"; within:8; sid:1;)"); if (de_ctx->sig_list == NULL) { goto end; } @@ -1735,7 +1736,7 @@ static int UriTestSig18(void) { int result = 0; uint8_t *http_buf = (uint8_t *)"POST /now_this_is_is_is_big_big_big_string_now HTTP/1.0\r\n" - "User-Agent: Mozilla/1.0\r\n"; + "User-Agent: Mozilla/1.0\r\n"; uint32_t http_buf_len = strlen((char *)http_buf); Flow f; TcpSession ssn; @@ -1757,7 +1758,7 @@ static int UriTestSig18(void) f.flags |= FLOW_IPV4; p->flow = &f; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; f.alproto = ALPROTO_HTTP1; @@ -1771,10 +1772,10 @@ static int UriTestSig18(void) de_ctx->flags |= DE_QUIET; de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"test multiple relative uricontents\"; " - "uricontent:\"this\"; uricontent:\"is\"; within:9; " - "uricontent:\"big\"; within:12; " - "uricontent:\"string\"; within:8; sid:1;)"); + "(msg:\"test multiple relative uricontents\"; " + "uricontent:\"this\"; uricontent:\"is\"; within:9; " + "uricontent:\"big\"; within:12; " + "uricontent:\"string\"; within:8; sid:1;)"); if (de_ctx->sig_list == NULL) { goto end; } @@ -1828,7 +1829,7 @@ static int UriTestSig19(void) { int result = 0; uint8_t *http_buf = (uint8_t *)"POST /this_this_now_is_is_____big_string_now HTTP/1.0\r\n" - "User-Agent: Mozilla/1.0\r\n"; + "User-Agent: Mozilla/1.0\r\n"; uint32_t http_buf_len = strlen((char *)http_buf); Flow f; TcpSession ssn; @@ -1850,7 +1851,7 @@ static int UriTestSig19(void) f.flags |= FLOW_IPV4; p->flow = &f; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; f.alproto = ALPROTO_HTTP1; @@ -1864,11 +1865,11 @@ static int UriTestSig19(void) de_ctx->flags |= DE_QUIET; de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"test multiple relative uricontents\"; " - "uricontent:\"now\"; uricontent:\"this\"; " - "uricontent:\"is\"; within:12; " - "uricontent:\"big\"; within:8; " - "uricontent:\"string\"; within:8; sid:1;)"); + "(msg:\"test multiple relative uricontents\"; " + "uricontent:\"now\"; uricontent:\"this\"; " + "uricontent:\"is\"; within:12; " + "uricontent:\"big\"; within:8; " + "uricontent:\"string\"; within:8; sid:1;)"); if (de_ctx->sig_list == NULL) { goto end; } @@ -1922,7 +1923,7 @@ static int UriTestSig20(void) { int result = 0; uint8_t *http_buf = (uint8_t *)"POST /_________thus_thus_is_a_big HTTP/1.0\r\n" - "User-Agent: Mozilla/1.0\r\n"; + "User-Agent: Mozilla/1.0\r\n"; uint32_t http_buf_len = strlen((char *)http_buf); Flow f; TcpSession ssn; @@ -1944,7 +1945,7 @@ static int UriTestSig20(void) f.flags |= FLOW_IPV4; p->flow = &f; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; f.alproto = ALPROTO_HTTP1; @@ -1958,10 +1959,10 @@ static int UriTestSig20(void) de_ctx->flags |= DE_QUIET; de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"test multiple relative uricontents\"; " - "uricontent:\"thus\"; offset:8; " - "uricontent:\"is\"; within:6; " - "uricontent:\"big\"; within:8; sid:1;)"); + "(msg:\"test multiple relative uricontents\"; " + "uricontent:\"thus\"; offset:8; " + "uricontent:\"is\"; within:6; " + "uricontent:\"big\"; within:8; sid:1;)"); if (de_ctx->sig_list == NULL) { goto end; } @@ -2015,7 +2016,7 @@ static int UriTestSig21(void) { int result = 0; uint8_t *http_buf = (uint8_t *)"POST /we_need_to_fix_this_and_yes_fix_this_now HTTP/1.0\r\n" - "User-Agent: Mozilla/1.0\r\n"; + "User-Agent: Mozilla/1.0\r\n"; uint32_t http_buf_len = strlen((char *)http_buf); Flow f; TcpSession ssn; @@ -2037,7 +2038,7 @@ static int UriTestSig21(void) f.flags |= FLOW_IPV4; p->flow = &f; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; f.alproto = ALPROTO_HTTP1; @@ -2051,9 +2052,9 @@ static int UriTestSig21(void) de_ctx->flags |= DE_QUIET; de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"test multiple relative uricontents\"; " - "uricontent:\"fix\"; uricontent:\"this\"; within:6; " - "uricontent:!\"and\"; distance:0; sid:1;)"); + "(msg:\"test multiple relative uricontents\"; " + "uricontent:\"fix\"; uricontent:\"this\"; within:6; " + "uricontent:!\"and\"; distance:0; sid:1;)"); if (de_ctx->sig_list == NULL) { goto end; } @@ -2107,8 +2108,8 @@ static int UriTestSig22(void) { int result = 0; uint8_t *http_buf = (uint8_t *)"POST /this_is_a_super_duper_" - "nova_in_super_nova_now HTTP/1.0\r\n" - "User-Agent: Mozilla/1.0\r\n"; + "nova_in_super_nova_now HTTP/1.0\r\n" + "User-Agent: Mozilla/1.0\r\n"; uint32_t http_buf_len = strlen((char *)http_buf); Flow f; TcpSession ssn; @@ -2130,7 +2131,7 @@ static int UriTestSig22(void) f.flags |= FLOW_IPV4; p->flow = &f; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; f.alproto = ALPROTO_HTTP1; @@ -2144,8 +2145,8 @@ static int UriTestSig22(void) de_ctx->flags |= DE_QUIET; de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"test multiple relative uricontents\"; " - "pcre:/super/U; uricontent:\"nova\"; within:7; sid:1;)"); + "(msg:\"test multiple relative uricontents\"; " + "pcre:/super/U; uricontent:\"nova\"; within:7; sid:1;)"); if (de_ctx->sig_list == NULL) { goto end; } @@ -2199,7 +2200,7 @@ static int UriTestSig23(void) { int result = 0; uint8_t *http_buf = (uint8_t *)"POST /we_need_to_fix_this_and_yes_fix_this_now HTTP/1.0\r\n" - "User-Agent: Mozilla/1.0\r\n"; + "User-Agent: Mozilla/1.0\r\n"; uint32_t http_buf_len = strlen((char *)http_buf); Flow f; TcpSession ssn; @@ -2221,7 +2222,7 @@ static int UriTestSig23(void) f.flags |= FLOW_IPV4; p->flow = &f; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; f.alproto = ALPROTO_HTTP1; @@ -2235,8 +2236,8 @@ static int UriTestSig23(void) de_ctx->flags |= DE_QUIET; de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"test multiple relative uricontents\"; " - "uricontent:!\"fix_this_now\"; sid:1;)"); + "(msg:\"test multiple relative uricontents\"; " + "uricontent:!\"fix_this_now\"; sid:1;)"); if (de_ctx->sig_list == NULL) { goto end; } @@ -2290,7 +2291,7 @@ static int UriTestSig24(void) { int result = 0; uint8_t *http_buf = (uint8_t *)"POST /we_need_to_fix_this_and_yes_fix_this_now HTTP/1.0\r\n" - "User-Agent: Mozilla/1.0\r\n"; + "User-Agent: Mozilla/1.0\r\n"; uint32_t http_buf_len = strlen((char *)http_buf); Flow f; TcpSession ssn; @@ -2312,7 +2313,7 @@ static int UriTestSig24(void) f.flags |= FLOW_IPV4; p->flow = &f; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; f.alproto = ALPROTO_HTTP1; @@ -2325,9 +2326,10 @@ static int UriTestSig24(void) } de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"test multiple relative uricontents\"; " - "uricontent:\"we_need_to\"; uricontent:!\"fix_this_now\"; sid:1;)"); + de_ctx->sig_list = + SigInit(de_ctx, "alert tcp any any -> any any " + "(msg:\"test multiple relative uricontents\"; " + "uricontent:\"we_need_to\"; uricontent:!\"fix_this_now\"; sid:1;)"); if (de_ctx->sig_list == NULL) { goto end; } @@ -2381,7 +2383,7 @@ static int UriTestSig25(void) { int result = 0; uint8_t *http_buf = (uint8_t *)"POST /normalized%20uri " - "HTTP/1.0\r\nUser-Agent: Mozilla/1.0\r\n"; + "HTTP/1.0\r\nUser-Agent: Mozilla/1.0\r\n"; uint32_t http_buf_len = strlen((char *)http_buf); Flow f; TcpSession ssn; @@ -2406,7 +2408,7 @@ static int UriTestSig25(void) p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; f.alproto = ALPROTO_HTTP1; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; StreamTcpInitConfig(true); @@ -2416,9 +2418,10 @@ static int UriTestSig25(void) } de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"test multiple relative uricontents\"; " - "pcre:/normalized/U; uricontent:\"normalized uri\"; sid:1;)"); + de_ctx->sig_list = + SigInit(de_ctx, "alert tcp any any -> any any " + "(msg:\"test multiple relative uricontents\"; " + "pcre:/normalized/U; uricontent:\"normalized uri\"; sid:1;)"); if (de_ctx->sig_list == NULL) { goto end; } @@ -2472,7 +2475,7 @@ static int UriTestSig26(void) { int result = 0; uint8_t *http_buf = (uint8_t *)"POST /we_need_to_fix_this_and_yes_fix_this_now HTTP/1.0\r\n" - "User-Agent: Mozilla/1.0\r\n"; + "User-Agent: Mozilla/1.0\r\n"; uint32_t http_buf_len = strlen((char *)http_buf); Flow f; TcpSession ssn; @@ -2494,7 +2497,7 @@ static int UriTestSig26(void) f.flags |= FLOW_IPV4; p->flow = &f; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; f.alproto = ALPROTO_HTTP1; @@ -2508,8 +2511,8 @@ static int UriTestSig26(void) de_ctx->flags |= DE_QUIET; de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"test multiple relative uricontents\"; " - "uricontent:\"fix_this\"; isdataat:4,relative; sid:1;)"); + "(msg:\"test multiple relative uricontents\"; " + "uricontent:\"fix_this\"; isdataat:4,relative; sid:1;)"); if (de_ctx->sig_list == NULL) { goto end; } @@ -2562,7 +2565,7 @@ static int UriTestSig26(void) static int UriTestSig27(void) { uint8_t *http_buf = (uint8_t *)"POST /we_need_to_fix_this_and_yes_fix_this_now HTTP/1.0\r\n" - "User-Agent: Mozilla/1.0\r\n"; + "User-Agent: Mozilla/1.0\r\n"; uint32_t http_buf_len = strlen((char *)http_buf); Flow f; TcpSession ssn; @@ -2584,7 +2587,7 @@ static int UriTestSig27(void) f.flags |= FLOW_IPV4; p->flow = &f; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; f.alproto = ALPROTO_HTTP1; @@ -2627,7 +2630,7 @@ static int UriTestSig28(void) { int result = 0; uint8_t *http_buf = (uint8_t *)"POST /this_b5ig_string_now_in_http HTTP/1.0\r\n" - "User-Agent: Mozilla/1.0\r\n"; + "User-Agent: Mozilla/1.0\r\n"; uint32_t http_buf_len = strlen((char *)http_buf); Flow f; TcpSession ssn; @@ -2649,7 +2652,7 @@ static int UriTestSig28(void) f.flags |= FLOW_IPV4; p->flow = &f; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; f.alproto = ALPROTO_HTTP1; @@ -2662,11 +2665,10 @@ static int UriTestSig28(void) } de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx, - "alert tcp any any -> any any (msg:\"dummy\"; " - "uricontent:\"this\"; " - "byte_extract:1,2,one,string,dec,relative; " - "uricontent:\"ring\"; distance:one; sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any (msg:\"dummy\"; " + "uricontent:\"this\"; " + "byte_extract:1,2,one,string,dec,relative; " + "uricontent:\"ring\"; distance:one; sid:1;)"); if (de_ctx->sig_list == NULL) { goto end; } @@ -2717,7 +2719,7 @@ static int UriTestSig29(void) { int result = 0; uint8_t *http_buf = (uint8_t *)"POST /this_b5ig_string_now_in_http HTTP/1.0\r\n" - "User-Agent: Mozilla/1.0\r\n"; + "User-Agent: Mozilla/1.0\r\n"; uint32_t http_buf_len = strlen((char *)http_buf); Flow f; TcpSession ssn; @@ -2739,7 +2741,7 @@ static int UriTestSig29(void) f.flags |= FLOW_IPV4; p->flow = &f; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; f.alproto = ALPROTO_HTTP1; @@ -2752,11 +2754,10 @@ static int UriTestSig29(void) } de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx, - "alert tcp any any -> any any (msg:\"dummy\"; " - "uricontent:\"this\"; " - "byte_extract:1,2,one,string,dec,relative; " - "uricontent:\"ring\"; distance:one; sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any (msg:\"dummy\"; " + "uricontent:\"this\"; " + "byte_extract:1,2,one,string,dec,relative; " + "uricontent:\"ring\"; distance:one; sid:1;)"); if (de_ctx->sig_list == NULL) { goto end; } @@ -2807,7 +2808,7 @@ static int UriTestSig30(void) { int result = 0; uint8_t *http_buf = (uint8_t *)"POST /this_b5ig_string_now_in_http HTTP/1.0\r\n" - "User-Agent: Mozilla/1.0\r\n"; + "User-Agent: Mozilla/1.0\r\n"; uint32_t http_buf_len = strlen((char *)http_buf); Flow f; TcpSession ssn; @@ -2829,7 +2830,7 @@ static int UriTestSig30(void) f.flags |= FLOW_IPV4; p->flow = &f; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; f.alproto = ALPROTO_HTTP1; @@ -2842,11 +2843,10 @@ static int UriTestSig30(void) } de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx, - "alert tcp any any -> any any (msg:\"dummy\"; " - "uricontent:\"this\"; " - "byte_extract:1,2,one,string,dec,relative; " - "uricontent:\"_b5ig\"; offset:one; sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any (msg:\"dummy\"; " + "uricontent:\"this\"; " + "byte_extract:1,2,one,string,dec,relative; " + "uricontent:\"_b5ig\"; offset:one; sid:1;)"); if (de_ctx->sig_list == NULL) { goto end; } @@ -2897,7 +2897,7 @@ static int UriTestSig31(void) { int result = 0; uint8_t *http_buf = (uint8_t *)"POST /this_b5ig_string_now_in_http HTTP/1.0\r\n" - "User-Agent: Mozilla/1.0\r\n"; + "User-Agent: Mozilla/1.0\r\n"; uint32_t http_buf_len = strlen((char *)http_buf); Flow f; TcpSession ssn; @@ -2919,7 +2919,7 @@ static int UriTestSig31(void) f.flags |= FLOW_IPV4; p->flow = &f; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; f.alproto = ALPROTO_HTTP1; @@ -2932,11 +2932,10 @@ static int UriTestSig31(void) } de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx, - "alert tcp any any -> any any (msg:\"dummy\"; " - "uricontent:\"this\"; " - "byte_extract:1,2,one,string,dec,relative; " - "uricontent:\"his\"; depth:one; sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any (msg:\"dummy\"; " + "uricontent:\"this\"; " + "byte_extract:1,2,one,string,dec,relative; " + "uricontent:\"his\"; depth:one; sid:1;)"); if (de_ctx->sig_list == NULL) { goto end; } @@ -2987,7 +2986,7 @@ static int UriTestSig32(void) { int result = 0; uint8_t *http_buf = (uint8_t *)"POST /this_b5ig_string_now_in_http HTTP/1.0\r\n" - "User-Agent: Mozilla/1.0\r\n"; + "User-Agent: Mozilla/1.0\r\n"; uint32_t http_buf_len = strlen((char *)http_buf); Flow f; TcpSession ssn; @@ -3009,7 +3008,7 @@ static int UriTestSig32(void) f.flags |= FLOW_IPV4; p->flow = &f; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; f.alproto = ALPROTO_HTTP1; @@ -3022,11 +3021,10 @@ static int UriTestSig32(void) } de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx, - "alert tcp any any -> any any (msg:\"dummy\"; " - "uricontent:\"this\"; " - "byte_extract:1,2,one,string,dec,relative; " - "uricontent:\"g_st\"; within:one; sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any (msg:\"dummy\"; " + "uricontent:\"this\"; " + "byte_extract:1,2,one,string,dec,relative; " + "uricontent:\"g_st\"; within:one; sid:1;)"); if (de_ctx->sig_list == NULL) { goto end; } @@ -3077,7 +3075,7 @@ static int UriTestSig33(void) { int result = 0; uint8_t *http_buf = (uint8_t *)"POST /normalized%20uri " - "HTTP/1.0\r\nUser-Agent: Mozilla/1.0\r\n"; + "HTTP/1.0\r\nUser-Agent: Mozilla/1.0\r\n"; uint32_t http_buf_len = strlen((char *)http_buf); Flow f; TcpSession ssn; @@ -3102,7 +3100,7 @@ static int UriTestSig33(void) p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; f.alproto = ALPROTO_HTTP1; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; StreamTcpInitConfig(true); @@ -3113,8 +3111,8 @@ static int UriTestSig33(void) de_ctx->flags |= DE_QUIET; de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"test multiple relative uricontents\"; " - "urilen:15; sid:1;)"); + "(msg:\"test multiple relative uricontents\"; " + "urilen:15; sid:1;)"); if (de_ctx->sig_list == NULL) { goto end; } @@ -3165,7 +3163,7 @@ static int UriTestSig34(void) { int result = 0; uint8_t *http_buf = (uint8_t *)"POST /normalized%20uri " - "HTTP/1.0\r\nUser-Agent: Mozilla/1.0\r\n"; + "HTTP/1.0\r\nUser-Agent: Mozilla/1.0\r\n"; uint32_t http_buf_len = strlen((char *)http_buf); Flow f; TcpSession ssn; @@ -3190,7 +3188,7 @@ static int UriTestSig34(void) p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; f.alproto = ALPROTO_HTTP1; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; StreamTcpInitConfig(true); @@ -3201,8 +3199,8 @@ static int UriTestSig34(void) de_ctx->flags |= DE_QUIET; de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"test multiple relative uricontents\"; " - "urilen:15, norm; sid:1;)"); + "(msg:\"test multiple relative uricontents\"; " + "urilen:15, norm; sid:1;)"); if (de_ctx->sig_list == NULL) { goto end; } @@ -3253,7 +3251,7 @@ static int UriTestSig35(void) { int result = 0; uint8_t *http_buf = (uint8_t *)"POST /normalized%20uri " - "HTTP/1.0\r\nUser-Agent: Mozilla/1.0\r\n"; + "HTTP/1.0\r\nUser-Agent: Mozilla/1.0\r\n"; uint32_t http_buf_len = strlen((char *)http_buf); Flow f; TcpSession ssn; @@ -3278,7 +3276,7 @@ static int UriTestSig35(void) p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; f.alproto = ALPROTO_HTTP1; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; StreamTcpInitConfig(true); @@ -3289,8 +3287,8 @@ static int UriTestSig35(void) de_ctx->flags |= DE_QUIET; de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"test multiple relative uricontents\"; " - "urilen:16; sid:1;)"); + "(msg:\"test multiple relative uricontents\"; " + "urilen:16; sid:1;)"); if (de_ctx->sig_list == NULL) { goto end; } @@ -3322,7 +3320,7 @@ static int UriTestSig35(void) result = 1; end: - if (alp_tctx != NULL) + if (alp_tctx != NULL) AppLayerParserThreadCtxFree(alp_tctx); if (det_ctx != NULL) DetectEngineThreadCtxDeinit(&tv, det_ctx); @@ -3341,7 +3339,7 @@ static int UriTestSig36(void) { int result = 0; uint8_t *http_buf = (uint8_t *)"POST /normalized%20uri " - "HTTP/1.0\r\nUser-Agent: Mozilla/1.0\r\n"; + "HTTP/1.0\r\nUser-Agent: Mozilla/1.0\r\n"; uint32_t http_buf_len = strlen((char *)http_buf); Flow f; TcpSession ssn; @@ -3366,7 +3364,7 @@ static int UriTestSig36(void) p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; f.alproto = ALPROTO_HTTP1; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; StreamTcpInitConfig(true); @@ -3377,8 +3375,8 @@ static int UriTestSig36(void) de_ctx->flags |= DE_QUIET; de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"test multiple relative uricontents\"; " - "urilen:16, norm; sid:1;)"); + "(msg:\"test multiple relative uricontents\"; " + "urilen:16, norm; sid:1;)"); if (de_ctx->sig_list == NULL) { goto end; } @@ -3429,7 +3427,7 @@ static int UriTestSig37(void) { int result = 0; uint8_t *http_buf = (uint8_t *)"POST /normalized%20uri " - "HTTP/1.0\r\nUser-Agent: Mozilla/1.0\r\n"; + "HTTP/1.0\r\nUser-Agent: Mozilla/1.0\r\n"; uint32_t http_buf_len = strlen((char *)http_buf); Flow f; TcpSession ssn; @@ -3454,7 +3452,7 @@ static int UriTestSig37(void) p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; f.alproto = ALPROTO_HTTP1; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; StreamTcpInitConfig(true); @@ -3465,8 +3463,8 @@ static int UriTestSig37(void) de_ctx->flags |= DE_QUIET; de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"test multiple relative uricontents\"; " - "urilen:17, raw; sid:1;)"); + "(msg:\"test multiple relative uricontents\"; " + "urilen:17, raw; sid:1;)"); if (de_ctx->sig_list == NULL) { goto end; } @@ -3517,7 +3515,7 @@ static int UriTestSig38(void) { int result = 0; uint8_t *http_buf = (uint8_t *)"POST /normalized%20uri " - "HTTP/1.0\r\nUser-Agent: Mozilla/1.0\r\n"; + "HTTP/1.0\r\nUser-Agent: Mozilla/1.0\r\n"; uint32_t http_buf_len = strlen((char *)http_buf); Flow f; TcpSession ssn; @@ -3542,7 +3540,7 @@ static int UriTestSig38(void) p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; f.alproto = ALPROTO_HTTP1; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; StreamTcpInitConfig(true); @@ -3553,8 +3551,8 @@ static int UriTestSig38(void) de_ctx->flags |= DE_QUIET; de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"test multiple relative uricontents\"; " - "urilen:18, raw; sid:1;)"); + "(msg:\"test multiple relative uricontents\"; " + "urilen:18, raw; sid:1;)"); if (de_ctx->sig_list == NULL) { goto end; } @@ -3635,17 +3633,16 @@ static int DetectEngineHttpRawUriTest01(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http1_buf[] = - "GET /../a/b/../c"; - uint8_t http2_buf[] = - "/./d.html HTTP/1.1\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 46\r\n" - "\r\n" - "This is dummy body1" - "This is dummy message body2"; + uint8_t http1_buf[] = "GET /../a/b/../c"; + uint8_t http2_buf[] = "/./d.html HTTP/1.1\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 46\r\n" + "\r\n" + "This is dummy body1" + "This is dummy message body2"; uint32_t http1_len = sizeof(http1_buf) - 1; uint32_t http2_len = sizeof(http2_buf) - 1; int result = 0; @@ -3681,10 +3678,10 @@ static int DetectEngineHttpRawUriTest01(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http raw uri test\"; " - "content:\"../c/./d\"; http_raw_uri; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http raw uri test\"; " + "content:\"../c/./d\"; http_raw_uri; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -3759,14 +3756,14 @@ static int DetectEngineHttpRawUriTest02(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http1_buf[] = - "GET /../a/b/../c/./d.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 19\r\n" - "\r\n" - "This is dummy body1"; + uint8_t http1_buf[] = "GET /../a/b/../c/./d.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 19\r\n" + "\r\n" + "This is dummy body1"; uint32_t http1_len = sizeof(http1_buf) - 1; int result = 0; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -3801,10 +3798,10 @@ static int DetectEngineHttpRawUriTest02(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http raw uri test\"; " - "content:\"/c/./d\"; http_raw_uri; offset:5; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http raw uri test\"; " + "content:\"/c/./d\"; http_raw_uri; offset:5; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -3863,17 +3860,16 @@ static int DetectEngineHttpRawUriTest03(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http1_buf[] = - "GET /../a/b/../"; - uint8_t http2_buf[] = - "c/./d.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 46\r\n" - "\r\n" - "This is dummy body1" - "This is dummy message body2"; + uint8_t http1_buf[] = "GET /../a/b/../"; + uint8_t http2_buf[] = "c/./d.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 46\r\n" + "\r\n" + "This is dummy body1" + "This is dummy message body2"; uint32_t http1_len = sizeof(http1_buf) - 1; uint32_t http2_len = sizeof(http2_buf) - 1; int result = 0; @@ -3909,10 +3905,10 @@ static int DetectEngineHttpRawUriTest03(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http raw uri test\"; " - "content:\"/a/b\"; http_raw_uri; offset:10; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http raw uri test\"; " + "content:\"/a/b\"; http_raw_uri; offset:10; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -3987,17 +3983,16 @@ static int DetectEngineHttpRawUriTest04(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http1_buf[] = - "GET /../a/b/../"; - uint8_t http2_buf[] = - "c/./d.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 46\r\n" - "\r\n" - "This is dummy body1" - "This is dummy message body2"; + uint8_t http1_buf[] = "GET /../a/b/../"; + uint8_t http2_buf[] = "c/./d.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.7) " + "Gecko/20091221 Firefox/3.5.7\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 46\r\n" + "\r\n" + "This is dummy body1" + "This is dummy message body2"; uint32_t http1_len = sizeof(http1_buf) - 1; uint32_t http2_len = sizeof(http2_buf) - 1; int result = 0; @@ -4033,10 +4028,10 @@ static int DetectEngineHttpRawUriTest04(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http raw uri test\"; " - "content:!\"/a/b\"; http_raw_uri; offset:10; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http raw uri test\"; " + "content:!\"/a/b\"; http_raw_uri; offset:10; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -4111,16 +4106,14 @@ static int DetectEngineHttpRawUriTest05(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http1_buf[] = - "GET /../a/b/"; - uint8_t http2_buf[] = - "../c/./d.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 46\r\n" - "\r\n" - "This is dummy body1" - "This is dummy message body2"; + uint8_t http1_buf[] = "GET /../a/b/"; + uint8_t http2_buf[] = "../c/./d.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 46\r\n" + "\r\n" + "This is dummy body1" + "This is dummy message body2"; uint32_t http1_len = sizeof(http1_buf) - 1; uint32_t http2_len = sizeof(http2_buf) - 1; int result = 0; @@ -4156,10 +4149,10 @@ static int DetectEngineHttpRawUriTest05(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http raw uri test\"; " - "content:\"a/b\"; http_raw_uri; depth:10; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http raw uri test\"; " + "content:\"a/b\"; http_raw_uri; depth:10; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -4234,16 +4227,14 @@ static int DetectEngineHttpRawUriTest06(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http1_buf[] = - "GET /../a/b/"; - uint8_t http2_buf[] = - "../c/./d.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 46\r\n" - "\r\n" - "This is dummy body1" - "This is dummy message body2"; + uint8_t http1_buf[] = "GET /../a/b/"; + uint8_t http2_buf[] = "../c/./d.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 46\r\n" + "\r\n" + "This is dummy body1" + "This is dummy message body2"; uint32_t http1_len = sizeof(http1_buf) - 1; uint32_t http2_len = sizeof(http2_buf) - 1; int result = 0; @@ -4279,10 +4270,10 @@ static int DetectEngineHttpRawUriTest06(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http raw uri test\"; " - "content:!\"/a/b\"; http_raw_uri; depth:25; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http raw uri test\"; " + "content:!\"/a/b\"; http_raw_uri; depth:25; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -4357,16 +4348,14 @@ static int DetectEngineHttpRawUriTest07(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http1_buf[] = - "GET /../a/b/"; - uint8_t http2_buf[] = - "../c/./d.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 46\r\n" - "\r\n" - "This is dummy body1" - "This is dummy message body2"; + uint8_t http1_buf[] = "GET /../a/b/"; + uint8_t http2_buf[] = "../c/./d.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 46\r\n" + "\r\n" + "This is dummy body1" + "This is dummy message body2"; uint32_t http1_len = sizeof(http1_buf) - 1; uint32_t http2_len = sizeof(http2_buf) - 1; int result = 0; @@ -4402,10 +4391,10 @@ static int DetectEngineHttpRawUriTest07(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http raw uri test\"; " - "content:!\"/c/./d\"; http_raw_uri; depth:12; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http raw uri test\"; " + "content:!\"/c/./d\"; http_raw_uri; depth:12; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -4480,16 +4469,14 @@ static int DetectEngineHttpRawUriTest08(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http1_buf[] = - "GET /../a/"; - uint8_t http2_buf[] = - "b/../c/./d.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 46\r\n" - "\r\n" - "This is dummy body1" - "This is dummy message body2"; + uint8_t http1_buf[] = "GET /../a/"; + uint8_t http2_buf[] = "b/../c/./d.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 46\r\n" + "\r\n" + "This is dummy body1" + "This is dummy message body2"; uint32_t http1_len = sizeof(http1_buf) - 1; uint32_t http2_len = sizeof(http2_buf) - 1; int result = 0; @@ -4525,10 +4512,10 @@ static int DetectEngineHttpRawUriTest08(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http raw uri test\"; " - "content:!\"/c/./d\"; http_raw_uri; depth:18; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http raw uri test\"; " + "content:!\"/c/./d\"; http_raw_uri; depth:18; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -4603,16 +4590,14 @@ static int DetectEngineHttpRawUriTest09(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http1_buf[] = - "GET /../a"; - uint8_t http2_buf[] = - "/b/../c/./d.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 46\r\n" - "\r\n" - "This is dummy body1" - "This is dummy message body2"; + uint8_t http1_buf[] = "GET /../a"; + uint8_t http2_buf[] = "/b/../c/./d.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 46\r\n" + "\r\n" + "This is dummy body1" + "This is dummy message body2"; uint32_t http1_len = sizeof(http1_buf) - 1; uint32_t http2_len = sizeof(http2_buf) - 1; int result = 0; @@ -4648,11 +4633,11 @@ static int DetectEngineHttpRawUriTest09(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http raw uri test\"; " - "content:\"/a\"; http_raw_uri; " - "content:\"./c/.\"; http_raw_uri; within:9; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http raw uri test\"; " + "content:\"/a\"; http_raw_uri; " + "content:\"./c/.\"; http_raw_uri; within:9; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -4727,16 +4712,14 @@ static int DetectEngineHttpRawUriTest10(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http1_buf[] = - "GET /../a"; - uint8_t http2_buf[] = - "/b/../c/./d.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 46\r\n" - "\r\n" - "This is dummy body1" - "This is dummy message body2"; + uint8_t http1_buf[] = "GET /../a"; + uint8_t http2_buf[] = "/b/../c/./d.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 46\r\n" + "\r\n" + "This is dummy body1" + "This is dummy message body2"; uint32_t http1_len = sizeof(http1_buf) - 1; uint32_t http2_len = sizeof(http2_buf) - 1; int result = 0; @@ -4772,11 +4755,11 @@ static int DetectEngineHttpRawUriTest10(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http raw uri test\"; " - "content:\"/a\"; http_raw_uri; " - "content:!\"boom\"; http_raw_uri; within:5; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http raw uri test\"; " + "content:\"/a\"; http_raw_uri; " + "content:!\"boom\"; http_raw_uri; within:5; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -4851,16 +4834,14 @@ static int DetectEngineHttpRawUriTest11(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http1_buf[] = - "GET /../a"; - uint8_t http2_buf[] = - "/b/../c/./d.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 46\r\n" - "\r\n" - "This is dummy body1" - "This is dummy message body2"; + uint8_t http1_buf[] = "GET /../a"; + uint8_t http2_buf[] = "/b/../c/./d.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 46\r\n" + "\r\n" + "This is dummy body1" + "This is dummy message body2"; uint32_t http1_len = sizeof(http1_buf) - 1; uint32_t http2_len = sizeof(http2_buf) - 1; int result = 0; @@ -4896,11 +4877,11 @@ static int DetectEngineHttpRawUriTest11(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http raw uri test\"; " - "content:\"./a\"; http_raw_uri; " - "content:\"boom\"; http_raw_uri; within:5; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http raw uri test\"; " + "content:\"./a\"; http_raw_uri; " + "content:\"boom\"; http_raw_uri; within:5; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -4975,16 +4956,14 @@ static int DetectEngineHttpRawUriTest12(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http1_buf[] = - "GET /../a"; - uint8_t http2_buf[] = - "/b/../c/./d.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 46\r\n" - "\r\n" - "This is dummy body1" - "This is dummy message body2"; + uint8_t http1_buf[] = "GET /../a"; + uint8_t http2_buf[] = "/b/../c/./d.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 46\r\n" + "\r\n" + "This is dummy body1" + "This is dummy message body2"; uint32_t http1_len = sizeof(http1_buf) - 1; uint32_t http2_len = sizeof(http2_buf) - 1; int result = 0; @@ -5020,11 +4999,11 @@ static int DetectEngineHttpRawUriTest12(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http raw uri test\"; " - "content:\"./a\"; http_raw_uri; " - "content:!\"/b/..\"; http_raw_uri; within:5; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http raw uri test\"; " + "content:\"./a\"; http_raw_uri; " + "content:!\"/b/..\"; http_raw_uri; within:5; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -5099,16 +5078,14 @@ static int DetectEngineHttpRawUriTest13(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http1_buf[] = - "GET /../a"; - uint8_t http2_buf[] = - "/b/../c/./d.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 46\r\n" - "\r\n" - "This is dummy body1" - "This is dummy message body2"; + uint8_t http1_buf[] = "GET /../a"; + uint8_t http2_buf[] = "/b/../c/./d.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 46\r\n" + "\r\n" + "This is dummy body1" + "This is dummy message body2"; uint32_t http1_len = sizeof(http1_buf) - 1; uint32_t http2_len = sizeof(http2_buf) - 1; int result = 0; @@ -5144,11 +5121,11 @@ static int DetectEngineHttpRawUriTest13(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http raw uri test\"; " - "content:\"./a\"; http_raw_uri; " - "content:\"/c/.\"; http_raw_uri; distance:5; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http raw uri test\"; " + "content:\"./a\"; http_raw_uri; " + "content:\"/c/.\"; http_raw_uri; distance:5; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -5223,16 +5200,14 @@ static int DetectEngineHttpRawUriTest14(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http1_buf[] = - "GET /../a"; - uint8_t http2_buf[] = - "/b/../c/./d.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 46\r\n" - "\r\n" - "This is dummy body1" - "This is dummy message body2"; + uint8_t http1_buf[] = "GET /../a"; + uint8_t http2_buf[] = "/b/../c/./d.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 46\r\n" + "\r\n" + "This is dummy body1" + "This is dummy message body2"; uint32_t http1_len = sizeof(http1_buf) - 1; uint32_t http2_len = sizeof(http2_buf) - 1; int result = 0; @@ -5268,11 +5243,11 @@ static int DetectEngineHttpRawUriTest14(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http raw uri test\"; " - "content:\"./a\"; http_raw_uri; " - "content:!\"b/..\"; http_raw_uri; distance:5; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http raw uri test\"; " + "content:\"./a\"; http_raw_uri; " + "content:!\"b/..\"; http_raw_uri; distance:5; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -5347,16 +5322,14 @@ static int DetectEngineHttpRawUriTest15(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http1_buf[] = - "GET /../a"; - uint8_t http2_buf[] = - "/b/../c/./d.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 46\r\n" - "\r\n" - "This is dummy body1" - "This is dummy message body2"; + uint8_t http1_buf[] = "GET /../a"; + uint8_t http2_buf[] = "/b/../c/./d.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 46\r\n" + "\r\n" + "This is dummy body1" + "This is dummy message body2"; uint32_t http1_len = sizeof(http1_buf) - 1; uint32_t http2_len = sizeof(http2_buf) - 1; int result = 0; @@ -5392,11 +5365,11 @@ static int DetectEngineHttpRawUriTest15(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http raw uri test\"; " - "content:\"./a\"; http_raw_uri; " - "content:\"/c/\"; http_raw_uri; distance:7; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http raw uri test\"; " + "content:\"./a\"; http_raw_uri; " + "content:\"/c/\"; http_raw_uri; distance:7; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -5471,16 +5444,14 @@ static int DetectEngineHttpRawUriTest16(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http1_buf[] = - "GET /../a"; - uint8_t http2_buf[] = - "/b/../c/./d.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 46\r\n" - "\r\n" - "This is dummy body1" - "This is dummy message body2"; + uint8_t http1_buf[] = "GET /../a"; + uint8_t http2_buf[] = "/b/../c/./d.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 46\r\n" + "\r\n" + "This is dummy body1" + "This is dummy message body2"; uint32_t http1_len = sizeof(http1_buf) - 1; uint32_t http2_len = sizeof(http2_buf) - 1; int result = 0; @@ -5516,11 +5487,11 @@ static int DetectEngineHttpRawUriTest16(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http raw uri test\"; " - "content:\"./a\"; http_raw_uri; " - "content:!\"/c/\"; http_raw_uri; distance:4; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http raw uri test\"; " + "content:\"./a\"; http_raw_uri; " + "content:!\"/c/\"; http_raw_uri; distance:4; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -5595,16 +5566,14 @@ static int DetectEngineHttpRawUriTest21(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http1_buf[] = - "GET /../a"; - uint8_t http2_buf[] = - "/b/../c/./d.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 46\r\n" - "\r\n" - "This is dummy body1" - "This is dummy message body2"; + uint8_t http1_buf[] = "GET /../a"; + uint8_t http2_buf[] = "/b/../c/./d.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 46\r\n" + "\r\n" + "This is dummy body1" + "This is dummy message body2"; uint32_t http1_len = sizeof(http1_buf) - 1; uint32_t http2_len = sizeof(http2_buf) - 1; int result = 0; @@ -5640,11 +5609,11 @@ static int DetectEngineHttpRawUriTest21(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http raw uri test\"; " - "pcre:/\\.\\/a/I; " - "content:!\"/c/\"; http_raw_uri; within:5; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http raw uri test\"; " + "pcre:/\\.\\/a/I; " + "content:!\"/c/\"; http_raw_uri; within:5; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -5719,16 +5688,14 @@ static int DetectEngineHttpRawUriTest22(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http1_buf[] = - "GET /../a"; - uint8_t http2_buf[] = - "/b/../c/./d.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 46\r\n" - "\r\n" - "This is dummy body1" - "This is dummy message body2"; + uint8_t http1_buf[] = "GET /../a"; + uint8_t http2_buf[] = "/b/../c/./d.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 46\r\n" + "\r\n" + "This is dummy body1" + "This is dummy message body2"; uint32_t http1_len = sizeof(http1_buf) - 1; uint32_t http2_len = sizeof(http2_buf) - 1; int result = 0; @@ -5764,11 +5731,11 @@ static int DetectEngineHttpRawUriTest22(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http raw uri test\"; " - "pcre:/\\.\\/a/I; " - "content:!\"/c/\"; within:5; http_raw_uri; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http raw uri test\"; " + "pcre:/\\.\\/a/I; " + "content:!\"/c/\"; within:5; http_raw_uri; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -5843,16 +5810,14 @@ static int DetectEngineHttpRawUriTest23(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http1_buf[] = - "GET /../a"; - uint8_t http2_buf[] = - "/b/../c/./d.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 46\r\n" - "\r\n" - "This is dummy body1" - "This is dummy message body2"; + uint8_t http1_buf[] = "GET /../a"; + uint8_t http2_buf[] = "/b/../c/./d.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 46\r\n" + "\r\n" + "This is dummy body1" + "This is dummy message body2"; uint32_t http1_len = sizeof(http1_buf) - 1; uint32_t http2_len = sizeof(http2_buf) - 1; int result = 0; @@ -5888,11 +5853,11 @@ static int DetectEngineHttpRawUriTest23(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http raw uri test\"; " - "pcre:/\\.\\/a/I; " - "content:!\"/c/\"; distance:3; http_raw_uri; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http raw uri test\"; " + "pcre:/\\.\\/a/I; " + "content:!\"/c/\"; distance:3; http_raw_uri; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -5967,16 +5932,14 @@ static int DetectEngineHttpRawUriTest24(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http1_buf[] = - "GET /../a"; - uint8_t http2_buf[] = - "/b/../c/./d.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 46\r\n" - "\r\n" - "This is dummy body1" - "This is dummy message body2"; + uint8_t http1_buf[] = "GET /../a"; + uint8_t http2_buf[] = "/b/../c/./d.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 46\r\n" + "\r\n" + "This is dummy body1" + "This is dummy message body2"; uint32_t http1_len = sizeof(http1_buf) - 1; uint32_t http2_len = sizeof(http2_buf) - 1; int result = 0; @@ -6012,11 +5975,11 @@ static int DetectEngineHttpRawUriTest24(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http raw uri test\"; " - "pcre:/\\.\\/a/I; " - "content:!\"/c/\"; distance:10; http_raw_uri; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http raw uri test\"; " + "pcre:/\\.\\/a/I; " + "content:!\"/c/\"; distance:10; http_raw_uri; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -6091,16 +6054,14 @@ static int DetectEngineHttpRawUriTest25(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http1_buf[] = - "GET /../a"; - uint8_t http2_buf[] = - "/b/../c/./d.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 46\r\n" - "\r\n" - "This is dummy body1" - "This is dummy message body2"; + uint8_t http1_buf[] = "GET /../a"; + uint8_t http2_buf[] = "/b/../c/./d.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 46\r\n" + "\r\n" + "This is dummy body1" + "This is dummy message body2"; uint32_t http1_len = sizeof(http1_buf) - 1; uint32_t http2_len = sizeof(http2_buf) - 1; int result = 0; @@ -6136,11 +6097,11 @@ static int DetectEngineHttpRawUriTest25(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http raw uri test\"; " - "pcre:/\\.\\/a/I; " - "content:\"/c/\"; within:10; http_raw_uri; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http raw uri test\"; " + "pcre:/\\.\\/a/I; " + "content:\"/c/\"; within:10; http_raw_uri; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -6215,16 +6176,14 @@ static int DetectEngineHttpRawUriTest26(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http1_buf[] = - "GET /../a"; - uint8_t http2_buf[] = - "/b/../c/./d.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 46\r\n" - "\r\n" - "This is dummy body1" - "This is dummy message body2"; + uint8_t http1_buf[] = "GET /../a"; + uint8_t http2_buf[] = "/b/../c/./d.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 46\r\n" + "\r\n" + "This is dummy body1" + "This is dummy message body2"; uint32_t http1_len = sizeof(http1_buf) - 1; uint32_t http2_len = sizeof(http2_buf) - 1; int result = 0; @@ -6260,11 +6219,11 @@ static int DetectEngineHttpRawUriTest26(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http raw uri test\"; " - "pcre:/\\.\\/a/I; " - "content:\"/c/\"; within:5; http_raw_uri; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http raw uri test\"; " + "pcre:/\\.\\/a/I; " + "content:\"/c/\"; within:5; http_raw_uri; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -6339,16 +6298,14 @@ static int DetectEngineHttpRawUriTest27(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http1_buf[] = - "GET /../a"; - uint8_t http2_buf[] = - "/b/../c/./d.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 46\r\n" - "\r\n" - "This is dummy body1" - "This is dummy message body2"; + uint8_t http1_buf[] = "GET /../a"; + uint8_t http2_buf[] = "/b/../c/./d.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 46\r\n" + "\r\n" + "This is dummy body1" + "This is dummy message body2"; uint32_t http1_len = sizeof(http1_buf) - 1; uint32_t http2_len = sizeof(http2_buf) - 1; int result = 0; @@ -6384,11 +6341,11 @@ static int DetectEngineHttpRawUriTest27(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http raw uri test\"; " - "pcre:/\\.\\/a/I; " - "content:\"/c/\"; distance:5; http_raw_uri; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http raw uri test\"; " + "pcre:/\\.\\/a/I; " + "content:\"/c/\"; distance:5; http_raw_uri; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -6463,16 +6420,14 @@ static int DetectEngineHttpRawUriTest28(void) DetectEngineThreadCtx *det_ctx = NULL; HtpState *http_state = NULL; Flow f; - uint8_t http1_buf[] = - "GET /../a"; - uint8_t http2_buf[] = - "/b/../c/./d.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 46\r\n" - "\r\n" - "This is dummy body1" - "This is dummy message body2"; + uint8_t http1_buf[] = "GET /../a"; + uint8_t http2_buf[] = "/b/../c/./d.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 46\r\n" + "\r\n" + "This is dummy body1" + "This is dummy message body2"; uint32_t http1_len = sizeof(http1_buf) - 1; uint32_t http2_len = sizeof(http2_buf) - 1; int result = 0; @@ -6508,11 +6463,11 @@ static int DetectEngineHttpRawUriTest28(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any " - "(msg:\"http raw uri test\"; " - "pcre:/\\.\\/a/I; " - "content:\"/c/\"; distance:10; http_raw_uri; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert http any any -> any any " + "(msg:\"http raw uri test\"; " + "pcre:/\\.\\/a/I; " + "content:\"/c/\"; distance:10; http_raw_uri; " + "sid:1;)"); if (de_ctx->sig_list == NULL) goto end; @@ -6584,7 +6539,7 @@ static int DetectEngineHttpRawUriTest29(void) { int result = 0; uint8_t *http_buf = (uint8_t *)"POST /../a/b/../c/./d.html HTTP/1.0\r\n" - "User-Agent: Mozilla/1.0\r\n"; + "User-Agent: Mozilla/1.0\r\n"; uint32_t http_buf_len = strlen((char *)http_buf); Flow f; TcpSession ssn; @@ -6620,9 +6575,9 @@ static int DetectEngineHttpRawUriTest29(void) de_ctx->flags |= DE_QUIET; de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"test multiple relative raw uri contents\"; " - "content:\"/c/\"; http_raw_uri; " - "isdataat:4,relative; sid:1;)"); + "(msg:\"test multiple relative raw uri contents\"; " + "content:\"/c/\"; http_raw_uri; " + "isdataat:4,relative; sid:1;)"); if (de_ctx->sig_list == NULL) { goto end; } @@ -6676,7 +6631,7 @@ static int DetectEngineHttpRawUriTest30(void) { int result = 0; uint8_t *http_buf = (uint8_t *)"POST /../a/b/../c/./d.html HTTP/1.0\r\n" - "User-Agent: Mozilla/1.0\r\n"; + "User-Agent: Mozilla/1.0\r\n"; uint32_t http_buf_len = strlen((char *)http_buf); Flow f; TcpSession ssn; @@ -6698,7 +6653,7 @@ static int DetectEngineHttpRawUriTest30(void) f.flags |= FLOW_IPV4; p->flow = &f; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; f.alproto = ALPROTO_HTTP1; @@ -6712,8 +6667,8 @@ static int DetectEngineHttpRawUriTest30(void) de_ctx->flags |= DE_QUIET; de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " - "(msg:\"test multiple relative raw uri contents\"; " - "uricontent:\"/c/\"; isdataat:!10,relative; sid:1;)"); + "(msg:\"test multiple relative raw uri contents\"; " + "uricontent:\"/c/\"; isdataat:!10,relative; sid:1;)"); if (de_ctx->sig_list == NULL) { goto end; } @@ -6763,7 +6718,7 @@ static int DetectEngineHttpRawUriTest30(void) /** * \brief Register the UNITTESTS for the http_uri keyword */ -static void DetectHttpUriRegisterTests (void) +static void DetectHttpUriRegisterTests(void) { UtRegisterTest("UriTestSig01", UriTestSig01); UtRegisterTest("UriTestSig02", UriTestSig02); @@ -6803,59 +6758,32 @@ static void DetectHttpUriRegisterTests (void) UtRegisterTest("UriTestSig37", UriTestSig37); UtRegisterTest("UriTestSig38", UriTestSig38); - UtRegisterTest("DetectHttpUriIsdataatParseTest", - DetectHttpUriIsdataatParseTest); - - UtRegisterTest("DetectEngineHttpRawUriTest01", - DetectEngineHttpRawUriTest01); - UtRegisterTest("DetectEngineHttpRawUriTest02", - DetectEngineHttpRawUriTest02); - UtRegisterTest("DetectEngineHttpRawUriTest03", - DetectEngineHttpRawUriTest03); - UtRegisterTest("DetectEngineHttpRawUriTest04", - DetectEngineHttpRawUriTest04); - UtRegisterTest("DetectEngineHttpRawUriTest05", - DetectEngineHttpRawUriTest05); - UtRegisterTest("DetectEngineHttpRawUriTest06", - DetectEngineHttpRawUriTest06); - UtRegisterTest("DetectEngineHttpRawUriTest07", - DetectEngineHttpRawUriTest07); - UtRegisterTest("DetectEngineHttpRawUriTest08", - DetectEngineHttpRawUriTest08); - UtRegisterTest("DetectEngineHttpRawUriTest09", - DetectEngineHttpRawUriTest09); - UtRegisterTest("DetectEngineHttpRawUriTest10", - DetectEngineHttpRawUriTest10); - UtRegisterTest("DetectEngineHttpRawUriTest11", - DetectEngineHttpRawUriTest11); - UtRegisterTest("DetectEngineHttpRawUriTest12", - DetectEngineHttpRawUriTest12); - UtRegisterTest("DetectEngineHttpRawUriTest13", - DetectEngineHttpRawUriTest13); - UtRegisterTest("DetectEngineHttpRawUriTest14", - DetectEngineHttpRawUriTest14); - UtRegisterTest("DetectEngineHttpRawUriTest15", - DetectEngineHttpRawUriTest15); - UtRegisterTest("DetectEngineHttpRawUriTest16", - DetectEngineHttpRawUriTest16); - UtRegisterTest("DetectEngineHttpRawUriTest21", - DetectEngineHttpRawUriTest21); - UtRegisterTest("DetectEngineHttpRawUriTest22", - DetectEngineHttpRawUriTest22); - UtRegisterTest("DetectEngineHttpRawUriTest23", - DetectEngineHttpRawUriTest23); - UtRegisterTest("DetectEngineHttpRawUriTest24", - DetectEngineHttpRawUriTest24); - UtRegisterTest("DetectEngineHttpRawUriTest25", - DetectEngineHttpRawUriTest25); - UtRegisterTest("DetectEngineHttpRawUriTest26", - DetectEngineHttpRawUriTest26); - UtRegisterTest("DetectEngineHttpRawUriTest27", - DetectEngineHttpRawUriTest27); - UtRegisterTest("DetectEngineHttpRawUriTest28", - DetectEngineHttpRawUriTest28); - UtRegisterTest("DetectEngineHttpRawUriTest29", - DetectEngineHttpRawUriTest29); - UtRegisterTest("DetectEngineHttpRawUriTest30", - DetectEngineHttpRawUriTest30); + UtRegisterTest("DetectHttpUriIsdataatParseTest", DetectHttpUriIsdataatParseTest); + + UtRegisterTest("DetectEngineHttpRawUriTest01", DetectEngineHttpRawUriTest01); + UtRegisterTest("DetectEngineHttpRawUriTest02", DetectEngineHttpRawUriTest02); + UtRegisterTest("DetectEngineHttpRawUriTest03", DetectEngineHttpRawUriTest03); + UtRegisterTest("DetectEngineHttpRawUriTest04", DetectEngineHttpRawUriTest04); + UtRegisterTest("DetectEngineHttpRawUriTest05", DetectEngineHttpRawUriTest05); + UtRegisterTest("DetectEngineHttpRawUriTest06", DetectEngineHttpRawUriTest06); + UtRegisterTest("DetectEngineHttpRawUriTest07", DetectEngineHttpRawUriTest07); + UtRegisterTest("DetectEngineHttpRawUriTest08", DetectEngineHttpRawUriTest08); + UtRegisterTest("DetectEngineHttpRawUriTest09", DetectEngineHttpRawUriTest09); + UtRegisterTest("DetectEngineHttpRawUriTest10", DetectEngineHttpRawUriTest10); + UtRegisterTest("DetectEngineHttpRawUriTest11", DetectEngineHttpRawUriTest11); + UtRegisterTest("DetectEngineHttpRawUriTest12", DetectEngineHttpRawUriTest12); + UtRegisterTest("DetectEngineHttpRawUriTest13", DetectEngineHttpRawUriTest13); + UtRegisterTest("DetectEngineHttpRawUriTest14", DetectEngineHttpRawUriTest14); + UtRegisterTest("DetectEngineHttpRawUriTest15", DetectEngineHttpRawUriTest15); + UtRegisterTest("DetectEngineHttpRawUriTest16", DetectEngineHttpRawUriTest16); + UtRegisterTest("DetectEngineHttpRawUriTest21", DetectEngineHttpRawUriTest21); + UtRegisterTest("DetectEngineHttpRawUriTest22", DetectEngineHttpRawUriTest22); + UtRegisterTest("DetectEngineHttpRawUriTest23", DetectEngineHttpRawUriTest23); + UtRegisterTest("DetectEngineHttpRawUriTest24", DetectEngineHttpRawUriTest24); + UtRegisterTest("DetectEngineHttpRawUriTest25", DetectEngineHttpRawUriTest25); + UtRegisterTest("DetectEngineHttpRawUriTest26", DetectEngineHttpRawUriTest26); + UtRegisterTest("DetectEngineHttpRawUriTest27", DetectEngineHttpRawUriTest27); + UtRegisterTest("DetectEngineHttpRawUriTest28", DetectEngineHttpRawUriTest28); + UtRegisterTest("DetectEngineHttpRawUriTest29", DetectEngineHttpRawUriTest29); + UtRegisterTest("DetectEngineHttpRawUriTest30", DetectEngineHttpRawUriTest30); } diff --git a/src/tests/detect-http-user-agent.c b/src/tests/detect-http-user-agent.c index df9c9c169717..adc0bf82055a 100644 --- a/src/tests/detect-http-user-agent.c +++ b/src/tests/detect-http-user-agent.c @@ -21,7 +21,6 @@ * @{ */ - /** \file * * \author Anoop Saldanha @@ -69,7 +68,7 @@ static int DetectEngineHttpUATest( p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -432,12 +431,11 @@ static int DetectHttpUATest06(void) ThreadVars th_v; DetectEngineThreadCtx *det_ctx = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: This is dummy message body\r\n" - "Content-Type: text/html\r\n" - "\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: This is dummy message body\r\n" + "Content-Type: text/html\r\n" + "\r\n"; uint32_t http_len = sizeof(http_buf) - 1; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -505,12 +503,10 @@ static int DetectHttpUATest07(void) ThreadVars th_v; DetectEngineThreadCtx *det_ctx = NULL; Flow f; - uint8_t http1_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: This is dummy message"; - uint8_t http2_buf[] = - "body1\r\n\r\n"; + uint8_t http1_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: This is dummy message"; + uint8_t http2_buf[] = "body1\r\n\r\n"; uint32_t http1_len = sizeof(http1_buf) - 1; uint32_t http2_len = sizeof(http2_buf) - 1; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -530,11 +526,11 @@ static int DetectHttpUATest07(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOSERVER; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -593,12 +589,10 @@ static int DetectHttpUATest08(void) ThreadVars th_v; DetectEngineThreadCtx *det_ctx = NULL; Flow f; - uint8_t http1_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: This is dummy mess"; - uint8_t http2_buf[] = - "age body\r\n\r\n"; + uint8_t http1_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: This is dummy mess"; + uint8_t http2_buf[] = "age body\r\n\r\n"; uint32_t http1_len = sizeof(http1_buf) - 1; uint32_t http2_len = sizeof(http2_buf) - 1; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -618,11 +612,11 @@ static int DetectHttpUATest08(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOSERVER; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -681,16 +675,14 @@ static int DetectHttpUATest09(void) ThreadVars th_v; DetectEngineThreadCtx *det_ctx = NULL; Flow f; - uint8_t http1_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: This is dummy body1"; - uint8_t http2_buf[] = - "This is dummy message body2\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 46\r\n" - "\r\n" - "This is dummy body1"; + uint8_t http1_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: This is dummy body1"; + uint8_t http2_buf[] = "This is dummy message body2\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 46\r\n" + "\r\n" + "This is dummy body1"; uint32_t http1_len = sizeof(http1_buf) - 1; uint32_t http2_len = sizeof(http2_buf) - 1; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -710,11 +702,11 @@ static int DetectHttpUATest09(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOSERVER; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -772,16 +764,14 @@ static int DetectHttpUATest10(void) ThreadVars th_v; DetectEngineThreadCtx *det_ctx = NULL; Flow f; - uint8_t http1_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: This is dummy bodY1"; - uint8_t http2_buf[] = - "This is dummy message body2\r\n" - "Content-Type: text/html\r\n" - "Content-Length: 46\r\n" - "\r\n" - "This is dummy bodY1"; + uint8_t http1_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: This is dummy bodY1"; + uint8_t http2_buf[] = "This is dummy message body2\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 46\r\n" + "\r\n" + "This is dummy bodY1"; uint32_t http1_len = sizeof(http1_buf) - 1; uint32_t http2_len = sizeof(http2_buf) - 1; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -801,11 +791,11 @@ static int DetectHttpUATest10(void) p1->flow = &f; p1->flowflags |= FLOW_PKT_TOSERVER; p1->flowflags |= FLOW_PKT_ESTABLISHED; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2->flow = &f; p2->flowflags |= FLOW_PKT_TOSERVER; p2->flowflags |= FLOW_PKT_ESTABLISHED; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -861,12 +851,11 @@ static int DetectHttpUATest11(void) ThreadVars th_v; DetectEngineThreadCtx *det_ctx = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: This is dummy message body\r\n" - "Content-Type: text/html\r\n" - "\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: This is dummy message body\r\n" + "Content-Type: text/html\r\n" + "\r\n"; uint32_t http_len = sizeof(http_buf) - 1; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -884,7 +873,7 @@ static int DetectHttpUATest11(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -931,11 +920,10 @@ static int DetectHttpUATest12(void) ThreadVars th_v; DetectEngineThreadCtx *det_ctx = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: This is dummy body\r\n" - "\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: This is dummy body\r\n" + "\r\n"; uint32_t http_len = sizeof(http_buf) - 1; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -953,7 +941,7 @@ static int DetectHttpUATest12(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1000,12 +988,11 @@ static int DetectHttpUATest13(void) ThreadVars th_v; DetectEngineThreadCtx *det_ctx = NULL; Flow f; - uint8_t http_buf[] = - "GET /index.html HTTP/1.0\r\n" - "Host: www.openinfosecfoundation.org\r\n" - "User-Agent: longbufferabcdefghijklmnopqrstuvwxyz0123456789bufferend\r\n" - "Content-Type: text/html\r\n" - "\r\n"; + uint8_t http_buf[] = "GET /index.html HTTP/1.0\r\n" + "Host: www.openinfosecfoundation.org\r\n" + "User-Agent: longbufferabcdefghijklmnopqrstuvwxyz0123456789bufferend\r\n" + "Content-Type: text/html\r\n" + "\r\n"; uint32_t http_len = sizeof(http_buf) - 1; AppLayerParserThreadCtx *alp_tctx = AppLayerParserThreadCtxAlloc(); @@ -1023,7 +1010,7 @@ static int DetectHttpUATest13(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1099,7 +1086,7 @@ static int DetectHttpUATest14(void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -1108,9 +1095,13 @@ static int DetectHttpUATest14(void) FAIL_IF_NULL(de_ctx); de_ctx->flags |= DE_QUIET; - s = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any (content:\"POST\"; http_method; content:\"dummy1\"; http_cookie; content:\"Body one\"; http_user_agent; sid:1; rev:1;)"); + s = DetectEngineAppendSig(de_ctx, + "alert tcp any any -> any any (content:\"POST\"; http_method; content:\"dummy1\"; " + "http_cookie; content:\"Body one\"; http_user_agent; sid:1; rev:1;)"); FAIL_IF_NULL(s); - s = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any (content:\"GET\"; http_method; content:\"dummy2\"; http_cookie; content:\"Body two\"; http_user_agent; sid:2; rev:1;)"); + s = DetectEngineAppendSig(de_ctx, + "alert tcp any any -> any any (content:\"GET\"; http_method; content:\"dummy2\"; " + "http_cookie; content:\"Body two\"; http_user_agent; sid:2; rev:1;)"); FAIL_IF_NULL(s); SigGroupBuild(de_ctx); diff --git a/src/tests/detect-http2.c b/src/tests/detect-http2.c index 2ce1bd448162..6476c1e9a2f9 100644 --- a/src/tests/detect-http2.c +++ b/src/tests/detect-http2.c @@ -27,13 +27,13 @@ * \test signature with a valid http2.frametype value. */ -static int DetectHTTP2frameTypeParseTest01 (void) +static int DetectHTTP2frameTypeParseTest01(void) { DetectEngineCtx *de_ctx = DetectEngineCtxInit(); FAIL_IF_NULL(de_ctx); - Signature *sig = DetectEngineAppendSig(de_ctx, - "alert http2 any any -> any any (http2.frametype:GOAWAY; sid:1; rev:1;)"); + Signature *sig = DetectEngineAppendSig( + de_ctx, "alert http2 any any -> any any (http2.frametype:GOAWAY; sid:1; rev:1;)"); FAIL_IF_NULL(sig); DetectEngineCtxFree(de_ctx); @@ -52,13 +52,13 @@ void DetectHTTP2frameTypeRegisterTests(void) * \test signature with a valid http2.errorcode value. */ -static int DetectHTTP2errorCodeParseTest01 (void) +static int DetectHTTP2errorCodeParseTest01(void) { DetectEngineCtx *de_ctx = DetectEngineCtxInit(); FAIL_IF_NULL(de_ctx); - Signature *sig = DetectEngineAppendSig(de_ctx, - "alert http2 any any -> any any (http2.errorcode:NO_ERROR; sid:1; rev:1;)"); + Signature *sig = DetectEngineAppendSig( + de_ctx, "alert http2 any any -> any any (http2.errorcode:NO_ERROR; sid:1; rev:1;)"); FAIL_IF_NULL(sig); DetectEngineCtxFree(de_ctx); @@ -74,13 +74,13 @@ void DetectHTTP2errorCodeRegisterTests(void) * \test signature with a valid http2.priority value. */ -static int DetectHTTP2priorityParseTest01 (void) +static int DetectHTTP2priorityParseTest01(void) { DetectEngineCtx *de_ctx = DetectEngineCtxInit(); FAIL_IF_NULL(de_ctx); - Signature *sig = DetectEngineAppendSig(de_ctx, - "alert http2 any any -> any any (http2.priority:>100; sid:1; rev:1;)"); + Signature *sig = DetectEngineAppendSig( + de_ctx, "alert http2 any any -> any any (http2.priority:>100; sid:1; rev:1;)"); FAIL_IF_NULL(sig); DetectEngineCtxFree(de_ctx); @@ -96,13 +96,13 @@ void DetectHTTP2priorityRegisterTests(void) * \test signature with a valid http2.window value. */ -static int DetectHTTP2windowParseTest01 (void) +static int DetectHTTP2windowParseTest01(void) { DetectEngineCtx *de_ctx = DetectEngineCtxInit(); FAIL_IF_NULL(de_ctx); - Signature *sig = DetectEngineAppendSig(de_ctx, - "alert http2 any any -> any any (http2.window:<42; sid:1; rev:1;)"); + Signature *sig = DetectEngineAppendSig( + de_ctx, "alert http2 any any -> any any (http2.window:<42; sid:1; rev:1;)"); FAIL_IF_NULL(sig); DetectEngineCtxFree(de_ctx); @@ -114,18 +114,18 @@ void DetectHTTP2windowRegisterTests(void) UtRegisterTest("DetectHTTP2windowParseTest01", DetectHTTP2windowParseTest01); } - /** * \test signature with a valid http2.settings value. */ -static int DetectHTTP2settingsParseTest01 (void) +static int DetectHTTP2settingsParseTest01(void) { DetectEngineCtx *de_ctx = DetectEngineCtxInit(); FAIL_IF_NULL(de_ctx); - Signature *sig = DetectEngineAppendSig(de_ctx, - "alert http2 any any -> any any (http2.settings:SETTINGS_MAX_HEADER_LIST_SIZE >1024; sid:1; rev:1;)"); + Signature *sig = DetectEngineAppendSig( + de_ctx, "alert http2 any any -> any any (http2.settings:SETTINGS_MAX_HEADER_LIST_SIZE " + ">1024; sid:1; rev:1;)"); FAIL_IF_NULL(sig); DetectEngineCtxFree(de_ctx); @@ -137,18 +137,17 @@ void DetectHTTP2settingsRegisterTests(void) UtRegisterTest("DetectHTTP2settingsParseTest01", DetectHTTP2settingsParseTest01); } - /** -* \test signature with a valid http2.size_update value. -*/ + * \test signature with a valid http2.size_update value. + */ -static int DetectHTTP2sizeUpdateParseTest01 (void) +static int DetectHTTP2sizeUpdateParseTest01(void) { DetectEngineCtx *de_ctx = DetectEngineCtxInit(); FAIL_IF_NULL(de_ctx); - Signature *sig = DetectEngineAppendSig(de_ctx, - "alert http2 any any -> any any (http2.size_update:>4096; sid:1; rev:1;)"); + Signature *sig = DetectEngineAppendSig( + de_ctx, "alert http2 any any -> any any (http2.size_update:>4096; sid:1; rev:1;)"); FAIL_IF_NULL(sig); DetectEngineCtxFree(de_ctx); diff --git a/src/tests/detect-icmpv6-mtu.c b/src/tests/detect-icmpv6-mtu.c index 241a221d7231..be4eff33a110 100644 --- a/src/tests/detect-icmpv6-mtu.c +++ b/src/tests/detect-icmpv6-mtu.c @@ -27,18 +27,17 @@ * \test signature with a valid icmpv6.mtu value. */ -static int DetectICMPv6mtuParseTest01 (void) +static int DetectICMPv6mtuParseTest01(void) { DetectEngineCtx *de_ctx = DetectEngineCtxInit(); FAIL_IF_NULL(de_ctx); - Signature *sig = DetectEngineAppendSig(de_ctx, - "alert ip any any -> any any (icmpv6.mtu:<1280; sid:1; rev:1;)"); + Signature *sig = DetectEngineAppendSig( + de_ctx, "alert ip any any -> any any (icmpv6.mtu:<1280; sid:1; rev:1;)"); FAIL_IF_NULL(sig); DetectEngineCtxFree(de_ctx); PASS; - } /** diff --git a/src/tests/detect-icmpv6hdr.c b/src/tests/detect-icmpv6hdr.c index 84292a45b59b..e9857d26520b 100644 --- a/src/tests/detect-icmpv6hdr.c +++ b/src/tests/detect-icmpv6hdr.c @@ -25,13 +25,13 @@ #include "../util-unittest.h" -static int DetectICMPv6hdrParseTest01 (void) +static int DetectICMPv6hdrParseTest01(void) { DetectEngineCtx *de_ctx = DetectEngineCtxInit(); FAIL_IF_NULL(de_ctx); - Signature *sig = DetectEngineAppendSig(de_ctx, - "alert ip any any -> any any (icmpv6.hdr; content:\"A\"; sid:1; rev:1;)"); + Signature *sig = DetectEngineAppendSig( + de_ctx, "alert ip any any -> any any (icmpv6.hdr; content:\"A\"; sid:1; rev:1;)"); FAIL_IF_NULL(sig); DetectEngineCtxFree(de_ctx); diff --git a/src/tests/detect-ipv4hdr.c b/src/tests/detect-ipv4hdr.c index f86047e2ee45..beefca1d297e 100644 --- a/src/tests/detect-ipv4hdr.c +++ b/src/tests/detect-ipv4hdr.c @@ -25,13 +25,13 @@ #include "../util-unittest.h" -static int DetectIpv4hdrParseTest01 (void) +static int DetectIpv4hdrParseTest01(void) { DetectEngineCtx *de_ctx = DetectEngineCtxInit(); FAIL_IF_NULL(de_ctx); - Signature *sig = DetectEngineAppendSig(de_ctx, - "alert ip any any -> any any (ipv4.hdr; content:\"A\"; sid:1; rev:1;)"); + Signature *sig = DetectEngineAppendSig( + de_ctx, "alert ip any any -> any any (ipv4.hdr; content:\"A\"; sid:1; rev:1;)"); FAIL_IF_NULL(sig); DetectEngineCtxFree(de_ctx); diff --git a/src/tests/detect-ipv6hdr.c b/src/tests/detect-ipv6hdr.c index 1373ad7b5cfc..cd98ef487418 100644 --- a/src/tests/detect-ipv6hdr.c +++ b/src/tests/detect-ipv6hdr.c @@ -25,13 +25,13 @@ #include "../util-unittest.h" -static int DetectIpv6hdrParseTest01 (void) +static int DetectIpv6hdrParseTest01(void) { DetectEngineCtx *de_ctx = DetectEngineCtxInit(); FAIL_IF_NULL(de_ctx); - Signature *sig = DetectEngineAppendSig(de_ctx, - "alert ip any any -> any any (ipv6.hdr; content:\"A\"; sid:1; rev:1;)"); + Signature *sig = DetectEngineAppendSig( + de_ctx, "alert ip any any -> any any (ipv6.hdr; content:\"A\"; sid:1; rev:1;)"); FAIL_IF_NULL(sig); DetectEngineCtxFree(de_ctx); diff --git a/src/tests/detect-parse.c b/src/tests/detect-parse.c index 694e2ae236d2..4aa0da3d962e 100644 --- a/src/tests/detect-parse.c +++ b/src/tests/detect-parse.c @@ -28,13 +28,17 @@ * Leak happened in function DetectEngineSignatureIsDuplicate */ -static int DetectParseTest01 (void) +static int DetectParseTest01(void) { - DetectEngineCtx * de_ctx = DetectEngineCtxInit(); - FAIL_IF(DetectEngineAppendSig(de_ctx, "alert http any any -> any any (msg:\"sid 1 version 0\"; content:\"dummy1\"; sid:1;)") == NULL); - DetectEngineAppendSig(de_ctx, "alert http any any -> any any (msg:\"sid 2 version 0\"; content:\"dummy2\"; sid:2;)"); - DetectEngineAppendSig(de_ctx, "alert http any any -> any any (msg:\"sid 1 version 1\"; content:\"dummy1.1\"; sid:1; rev:1;)"); - DetectEngineAppendSig(de_ctx, "alert http any any -> any any (msg:\"sid 2 version 2\"; content:\"dummy2.1\"; sid:2; rev:1;)"); + DetectEngineCtx *de_ctx = DetectEngineCtxInit(); + FAIL_IF(DetectEngineAppendSig(de_ctx, "alert http any any -> any any (msg:\"sid 1 version 0\"; " + "content:\"dummy1\"; sid:1;)") == NULL); + DetectEngineAppendSig(de_ctx, + "alert http any any -> any any (msg:\"sid 2 version 0\"; content:\"dummy2\"; sid:2;)"); + DetectEngineAppendSig(de_ctx, "alert http any any -> any any (msg:\"sid 1 version 1\"; " + "content:\"dummy1.1\"; sid:1; rev:1;)"); + DetectEngineAppendSig(de_ctx, "alert http any any -> any any (msg:\"sid 2 version 2\"; " + "content:\"dummy2.1\"; sid:2; rev:1;)"); FAIL_IF(de_ctx->sig_list->next == NULL); DetectEngineCtxFree(de_ctx); diff --git a/src/tests/detect-snmp-community.c b/src/tests/detect-snmp-community.c index 87dad99644c9..47fdf7d7b1c7 100644 --- a/src/tests/detect-snmp-community.c +++ b/src/tests/detect-snmp-community.c @@ -67,26 +67,24 @@ static int DetectSNMPCommunityTest(void) FAIL_IF_NULL(de_ctx); /* This rule should match. */ - s = DetectEngineAppendSig(de_ctx, - "alert snmp any any -> any any (" - "msg:\"SNMP Test Rule\"; " - "snmp.community; content:\"[R0_C@cti!]\"; " - "sid:1; rev:1;)"); + s = DetectEngineAppendSig(de_ctx, "alert snmp any any -> any any (" + "msg:\"SNMP Test Rule\"; " + "snmp.community; content:\"[R0_C@cti!]\"; " + "sid:1; rev:1;)"); FAIL_IF_NULL(s); /* This rule should not match. */ - s = DetectEngineAppendSig(de_ctx, - "alert snmp any any -> any any (" - "msg:\"SNMP Test Rule\"; " - "snmp.community; content:\"private\"; " - "sid:2; rev:1;)"); + s = DetectEngineAppendSig(de_ctx, "alert snmp any any -> any any (" + "msg:\"SNMP Test Rule\"; " + "snmp.community; content:\"private\"; " + "sid:2; rev:1;)"); FAIL_IF_NULL(s); SigGroupBuild(de_ctx); DetectEngineThreadCtxInit(&tv, (void *)de_ctx, (void *)&det_ctx); - int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_SNMP, - STREAM_TOSERVER, request, sizeof(request)); + int r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_SNMP, STREAM_TOSERVER, request, sizeof(request)); FAIL_IF(r != 0); /* Check that we have app-layer state. */ @@ -110,6 +108,5 @@ static int DetectSNMPCommunityTest(void) static void DetectSNMPCommunityRegisterTests(void) { - UtRegisterTest("DetectSNMPCommunityTest", - DetectSNMPCommunityTest); + UtRegisterTest("DetectSNMPCommunityTest", DetectSNMPCommunityTest); } diff --git a/src/tests/detect-snmp-pdu_type.c b/src/tests/detect-snmp-pdu_type.c index 0e7693bcc625..0f25f4601f5d 100644 --- a/src/tests/detect-snmp-pdu_type.c +++ b/src/tests/detect-snmp-pdu_type.c @@ -24,7 +24,7 @@ * \retval 1 on success. * \retval 0 on failure. */ -static int SNMPValidityTestParse01 (void) +static int SNMPValidityTestParse01(void) { DetectSNMPPduTypeData *dd = NULL; dd = DetectSNMPPduTypeParse("2"); diff --git a/src/tests/detect-snmp-version.c b/src/tests/detect-snmp-version.c index 5da24b1b8700..eca25d4fe22e 100644 --- a/src/tests/detect-snmp-version.c +++ b/src/tests/detect-snmp-version.c @@ -24,7 +24,7 @@ * \retval 1 on success. * \retval 0 on failure. */ -static int SNMPValidityTestParse01 (void) +static int SNMPValidityTestParse01(void) { DetectU32Data *dd = NULL; dd = DetectSNMPVersionParse("2"); @@ -40,7 +40,7 @@ static int SNMPValidityTestParse01 (void) * \retval 1 on success. * \retval 0 on failure. */ -static int SNMPValidityTestParse02 (void) +static int SNMPValidityTestParse02(void) { DetectU32Data *dd = NULL; dd = DetectSNMPVersionParse(">2"); diff --git a/src/tests/detect-ssl-state.c b/src/tests/detect-ssl-state.c index 6be8ea8d89b9..2e9e5bc7ca7d 100644 --- a/src/tests/detect-ssl-state.c +++ b/src/tests/detect-ssl-state.c @@ -37,8 +37,7 @@ static int DetectSslStateTest02(void) { DetectSslStateData *ssd = DetectSslStateParse("server_hello , client_hello"); FAIL_IF_NULL(ssd); - FAIL_IF_NOT(ssd->flags == (DETECT_SSL_STATE_SERVER_HELLO | - DETECT_SSL_STATE_CLIENT_HELLO)); + FAIL_IF_NOT(ssd->flags == (DETECT_SSL_STATE_SERVER_HELLO | DETECT_SSL_STATE_CLIENT_HELLO)); SCFree(ssd); PASS; } @@ -48,9 +47,8 @@ static int DetectSslStateTest03(void) DetectSslStateData *ssd = DetectSslStateParse("server_hello , client_keyx , " "client_hello"); FAIL_IF_NULL(ssd); - FAIL_IF_NOT(ssd->flags == (DETECT_SSL_STATE_SERVER_HELLO | - DETECT_SSL_STATE_CLIENT_KEYX | - DETECT_SSL_STATE_CLIENT_HELLO)); + FAIL_IF_NOT(ssd->flags == (DETECT_SSL_STATE_SERVER_HELLO | DETECT_SSL_STATE_CLIENT_KEYX | + DETECT_SSL_STATE_CLIENT_HELLO)); SCFree(ssd); PASS; } @@ -61,11 +59,9 @@ static int DetectSslStateTest04(void) "client_hello , server_keyx , " "unknown"); FAIL_IF_NULL(ssd); - FAIL_IF_NOT(ssd->flags == (DETECT_SSL_STATE_SERVER_HELLO | - DETECT_SSL_STATE_CLIENT_KEYX | - DETECT_SSL_STATE_CLIENT_HELLO | - DETECT_SSL_STATE_SERVER_KEYX | - DETECT_SSL_STATE_UNKNOWN)); + FAIL_IF_NOT(ssd->flags == (DETECT_SSL_STATE_SERVER_HELLO | DETECT_SSL_STATE_CLIENT_KEYX | + DETECT_SSL_STATE_CLIENT_HELLO | DETECT_SSL_STATE_SERVER_KEYX | + DETECT_SSL_STATE_UNKNOWN)); SCFree(ssd); PASS; } @@ -97,8 +93,7 @@ static int DetectSslStateTest08(void) { DetectSslStateData *ssd = DetectSslStateParse("server_hello|client_hello"); FAIL_IF_NULL(ssd); - FAIL_IF_NOT(ssd->flags == (DETECT_SSL_STATE_SERVER_HELLO | - DETECT_SSL_STATE_CLIENT_HELLO)); + FAIL_IF_NOT(ssd->flags == (DETECT_SSL_STATE_SERVER_HELLO | DETECT_SSL_STATE_CLIENT_HELLO)); SCFree(ssd); PASS; } @@ -132,6 +127,5 @@ static void DetectSslStateRegisterTests(void) UtRegisterTest("DetectSslStateTest05", DetectSslStateTest05); UtRegisterTest("DetectSslStateTest06", DetectSslStateTest06); UtRegisterTest("DetectSslStateTest08", DetectSslStateTest08); - UtRegisterTest("DetectSslStateTestParseNegate", - DetectSslStateTestParseNegate); + UtRegisterTest("DetectSslStateTestParseNegate", DetectSslStateTestParseNegate); } diff --git a/src/tests/detect-tcphdr.c b/src/tests/detect-tcphdr.c index 6faa0d716f2f..a0367858ce2c 100644 --- a/src/tests/detect-tcphdr.c +++ b/src/tests/detect-tcphdr.c @@ -25,13 +25,13 @@ #include "../util-unittest.h" -static int DetectTcphdrParseTest01 (void) +static int DetectTcphdrParseTest01(void) { DetectEngineCtx *de_ctx = DetectEngineCtxInit(); FAIL_IF_NULL(de_ctx); - Signature *sig = DetectEngineAppendSig(de_ctx, - "alert tcp any any -> any any (tcp.hdr; content:\"A\"; sid:1; rev:1;)"); + Signature *sig = DetectEngineAppendSig( + de_ctx, "alert tcp any any -> any any (tcp.hdr; content:\"A\"; sid:1; rev:1;)"); FAIL_IF_NULL(sig); DetectEngineCtxFree(de_ctx); diff --git a/src/tests/detect-template-buffer.c b/src/tests/detect-template-buffer.c index 7e04025a96da..fbe046a967be 100644 --- a/src/tests/detect-template-buffer.c +++ b/src/tests/detect-template-buffer.c @@ -56,19 +56,17 @@ static int DetectTemplateBufferTest(void) FAIL_IF_NULL(de_ctx); /* This rule should match. */ - s = DetectEngineAppendSig(de_ctx, - "alert tcp any any -> any any (" - "msg:\"TEMPLATE Test Rule\"; " - "template_buffer; content:\"World!\"; " - "sid:1; rev:1;)"); + s = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any (" + "msg:\"TEMPLATE Test Rule\"; " + "template_buffer; content:\"World!\"; " + "sid:1; rev:1;)"); FAIL_IF_NULL(s); /* This rule should not match. */ - s = DetectEngineAppendSig(de_ctx, - "alert tcp any any -> any any (" - "msg:\"TEMPLATE Test Rule\"; " - "template_buffer; content:\"W0rld!\"; " - "sid:2; rev:1;)"); + s = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any (" + "msg:\"TEMPLATE Test Rule\"; " + "template_buffer; content:\"W0rld!\"; " + "sid:2; rev:1;)"); FAIL_IF_NULL(s); SigGroupBuild(de_ctx); @@ -77,8 +75,8 @@ static int DetectTemplateBufferTest(void) DetectEngineThreadCtxInit(&tv, (void *)de_ctx, (void *)&det_ctx); FAIL_IF_NULL(det_ctx); - AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_TEMPLATE, - STREAM_TOSERVER, request, sizeof(request)); + AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_TEMPLATE, STREAM_TOSERVER, request, sizeof(request)); /* Check that we have app-layer state. */ FAIL_IF_NULL(f.alstate); diff --git a/src/tests/detect-template.c b/src/tests/detect-template.c index c91a463b19c1..e2e9527e1c04 100644 --- a/src/tests/detect-template.c +++ b/src/tests/detect-template.c @@ -27,7 +27,7 @@ * \test test keyword parsing */ -static int DetectTemplateParseTest01 (void) +static int DetectTemplateParseTest01(void) { DetectTemplateData *templated = DetectTemplateParse("1,10"); FAIL_IF_NULL(templated); @@ -40,12 +40,13 @@ static int DetectTemplateParseTest01 (void) * \test test signature parsing */ -static int DetectTemplateSignatureTest01 (void) +static int DetectTemplateSignatureTest01(void) { DetectEngineCtx *de_ctx = DetectEngineCtxInit(); FAIL_IF_NULL(de_ctx); - Signature *sig = DetectEngineAppendSig(de_ctx, "alert ip any any -> any any (template:1,10; sid:1; rev:1;)"); + Signature *sig = DetectEngineAppendSig( + de_ctx, "alert ip any any -> any any (template:1,10; sid:1; rev:1;)"); FAIL_IF_NULL(sig); DetectEngineCtxFree(de_ctx); @@ -58,6 +59,5 @@ static int DetectTemplateSignatureTest01 (void) void DetectTemplateRegisterTests(void) { UtRegisterTest("DetectTemplateParseTest01", DetectTemplateParseTest01); - UtRegisterTest("DetectTemplateSignatureTest01", - DetectTemplateSignatureTest01); + UtRegisterTest("DetectTemplateSignatureTest01", DetectTemplateSignatureTest01); } diff --git a/src/tests/detect-tls-cert-fingerprint.c b/src/tests/detect-tls-cert-fingerprint.c index ba9d944395c6..f5be89483718 100644 --- a/src/tests/detect-tls-cert-fingerprint.c +++ b/src/tests/detect-tls-cert-fingerprint.c @@ -278,12 +278,12 @@ static int DetectTlsFingerprintTest02(void) memset(&f, 0, sizeof(Flow)); memset(&ssn, 0, sizeof(TcpSession)); - p1 = UTHBuildPacketReal(client_hello, sizeof(client_hello), IPPROTO_TCP, - "192.168.1.5", "192.168.1.1", 51251, 443); - p2 = UTHBuildPacketReal(server_hello, sizeof(server_hello), IPPROTO_TCP, - "192.168.1.1", "192.168.1.5", 443, 51251); - p3 = UTHBuildPacketReal(certificate, sizeof(certificate), IPPROTO_TCP, - "192.168.1.1", "192.168.1.5", 443, 51251); + p1 = UTHBuildPacketReal(client_hello, sizeof(client_hello), IPPROTO_TCP, "192.168.1.5", + "192.168.1.1", 51251, 443); + p2 = UTHBuildPacketReal(server_hello, sizeof(server_hello), IPPROTO_TCP, "192.168.1.1", + "192.168.1.5", 443, 51251); + p3 = UTHBuildPacketReal(certificate, sizeof(certificate), IPPROTO_TCP, "192.168.1.1", + "192.168.1.5", 443, 51251); FLOW_INITIALIZE(&f); f.flags |= FLOW_IPV4; @@ -317,19 +317,19 @@ static int DetectTlsFingerprintTest02(void) de_ctx->mpm_matcher = mpm_default_matcher; de_ctx->flags |= DE_QUIET; - Signature *s = DetectEngineAppendSig(de_ctx, "alert tls any any -> any any " - "(msg:\"Test tls.cert_fingerprint\"; " - "tls.cert_fingerprint; " - "content:\"4a:a3:66:76:82:cb:6b:23:bb:c3:58:47:23:a4:63:a7:78:a4:a1:18\"; " - "sid:1;)"); + Signature *s = DetectEngineAppendSig(de_ctx, + "alert tls any any -> any any " + "(msg:\"Test tls.cert_fingerprint\"; " + "tls.cert_fingerprint; " + "content:\"4a:a3:66:76:82:cb:6b:23:bb:c3:58:47:23:a4:63:a7:78:a4:a1:18\"; " + "sid:1;)"); FAIL_IF_NULL(s); SigGroupBuild(de_ctx); DetectEngineThreadCtxInit(&tv, (void *)de_ctx, (void *)&det_ctx); - int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_TLS, - STREAM_TOSERVER, client_hello, - sizeof(client_hello)); + int r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_TLS, STREAM_TOSERVER, client_hello, sizeof(client_hello)); FAIL_IF(r != 0); @@ -340,8 +340,8 @@ static int DetectTlsFingerprintTest02(void) FAIL_IF(PacketAlertCheck(p1, 1)); - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_TLS, STREAM_TOCLIENT, - server_hello, sizeof(server_hello)); + r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_TLS, STREAM_TOCLIENT, server_hello, sizeof(server_hello)); FAIL_IF(r != 0); @@ -349,8 +349,8 @@ static int DetectTlsFingerprintTest02(void) FAIL_IF(PacketAlertCheck(p2, 1)); - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_TLS, STREAM_TOCLIENT, - certificate, sizeof(certificate)); + r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_TLS, STREAM_TOCLIENT, certificate, sizeof(certificate)); FAIL_IF(r != 0); diff --git a/src/tests/detect-tls-cert-issuer.c b/src/tests/detect-tls-cert-issuer.c index f9e852aac1da..ad965ad32586 100644 --- a/src/tests/detect-tls-cert-issuer.c +++ b/src/tests/detect-tls-cert-issuer.c @@ -278,12 +278,12 @@ static int DetectTlsIssuerTest02(void) memset(&f, 0, sizeof(Flow)); memset(&ssn, 0, sizeof(TcpSession)); - p1 = UTHBuildPacketReal(client_hello, sizeof(client_hello), IPPROTO_TCP, - "192.168.1.5", "192.168.1.1", 51251, 443); - p2 = UTHBuildPacketReal(server_hello, sizeof(server_hello), IPPROTO_TCP, - "192.168.1.1", "192.168.1.5", 443, 51251); - p3 = UTHBuildPacketReal(certificate, sizeof(certificate), IPPROTO_TCP, - "192.168.1.1", "192.168.1.5", 443, 51251); + p1 = UTHBuildPacketReal(client_hello, sizeof(client_hello), IPPROTO_TCP, "192.168.1.5", + "192.168.1.1", 51251, 443); + p2 = UTHBuildPacketReal(server_hello, sizeof(server_hello), IPPROTO_TCP, "192.168.1.1", + "192.168.1.5", 443, 51251); + p3 = UTHBuildPacketReal(certificate, sizeof(certificate), IPPROTO_TCP, "192.168.1.1", + "192.168.1.5", 443, 51251); FLOW_INITIALIZE(&f); f.flags |= FLOW_IPV4; @@ -318,17 +318,16 @@ static int DetectTlsIssuerTest02(void) de_ctx->flags |= DE_QUIET; Signature *s = DetectEngineAppendSig(de_ctx, "alert tls any any -> any any " - "(msg:\"Test tls.cert_issuer\"; " - "tls.cert_issuer; content:\"google\"; nocase; " - "sid:1;)"); + "(msg:\"Test tls.cert_issuer\"; " + "tls.cert_issuer; content:\"google\"; nocase; " + "sid:1;)"); FAIL_IF_NULL(s); SigGroupBuild(de_ctx); DetectEngineThreadCtxInit(&tv, (void *)de_ctx, (void *)&det_ctx); - int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_TLS, - STREAM_TOSERVER, client_hello, - sizeof(client_hello)); + int r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_TLS, STREAM_TOSERVER, client_hello, sizeof(client_hello)); FAIL_IF(r != 0); @@ -339,8 +338,8 @@ static int DetectTlsIssuerTest02(void) FAIL_IF(PacketAlertCheck(p1, 1)); - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_TLS, STREAM_TOCLIENT, - server_hello, sizeof(server_hello)); + r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_TLS, STREAM_TOCLIENT, server_hello, sizeof(server_hello)); FAIL_IF(r != 0); @@ -348,8 +347,8 @@ static int DetectTlsIssuerTest02(void) FAIL_IF(PacketAlertCheck(p2, 1)); - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_TLS, STREAM_TOCLIENT, - certificate, sizeof(certificate)); + r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_TLS, STREAM_TOCLIENT, certificate, sizeof(certificate)); FAIL_IF(r != 0); diff --git a/src/tests/detect-tls-cert-serial.c b/src/tests/detect-tls-cert-serial.c index f69c96f7aea0..6126e0ec8365 100644 --- a/src/tests/detect-tls-cert-serial.c +++ b/src/tests/detect-tls-cert-serial.c @@ -275,12 +275,12 @@ static int DetectTlsSerialTest02(void) memset(&f, 0, sizeof(Flow)); memset(&ssn, 0, sizeof(TcpSession)); - p1 = UTHBuildPacketReal(client_hello, sizeof(client_hello), IPPROTO_TCP, - "192.168.1.5", "192.168.1.1", 51251, 443); - p2 = UTHBuildPacketReal(server_hello, sizeof(server_hello), IPPROTO_TCP, - "192.168.1.1", "192.168.1.5", 443, 51251); - p3 = UTHBuildPacketReal(certificate, sizeof(certificate), IPPROTO_TCP, - "192.168.1.1", "192.168.1.5", 443, 51251); + p1 = UTHBuildPacketReal(client_hello, sizeof(client_hello), IPPROTO_TCP, "192.168.1.5", + "192.168.1.1", 51251, 443); + p2 = UTHBuildPacketReal(server_hello, sizeof(server_hello), IPPROTO_TCP, "192.168.1.1", + "192.168.1.5", 443, 51251); + p3 = UTHBuildPacketReal(certificate, sizeof(certificate), IPPROTO_TCP, "192.168.1.1", + "192.168.1.5", 443, 51251); FLOW_INITIALIZE(&f); f.flags |= FLOW_IPV4; @@ -315,18 +315,17 @@ static int DetectTlsSerialTest02(void) de_ctx->flags |= DE_QUIET; Signature *s = DetectEngineAppendSig(de_ctx, "alert tls any any -> any any " - "(msg:\"Test tls.cert_serial\"; " - "tls.cert_serial; " - "content:\"5C:19:B7:B1:32:3B:1C:A1\"; " - "sid:1;)"); + "(msg:\"Test tls.cert_serial\"; " + "tls.cert_serial; " + "content:\"5C:19:B7:B1:32:3B:1C:A1\"; " + "sid:1;)"); FAIL_IF_NULL(s); SigGroupBuild(de_ctx); DetectEngineThreadCtxInit(&tv, (void *)de_ctx, (void *)&det_ctx); - int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_TLS, - STREAM_TOSERVER, client_hello, - sizeof(client_hello)); + int r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_TLS, STREAM_TOSERVER, client_hello, sizeof(client_hello)); FAIL_IF(r != 0); @@ -337,8 +336,8 @@ static int DetectTlsSerialTest02(void) FAIL_IF(PacketAlertCheck(p1, 1)); - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_TLS, STREAM_TOCLIENT, - server_hello, sizeof(server_hello)); + r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_TLS, STREAM_TOCLIENT, server_hello, sizeof(server_hello)); FAIL_IF(r != 0); @@ -346,8 +345,8 @@ static int DetectTlsSerialTest02(void) FAIL_IF(PacketAlertCheck(p2, 1)); - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_TLS, STREAM_TOCLIENT, - certificate, sizeof(certificate)); + r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_TLS, STREAM_TOCLIENT, certificate, sizeof(certificate)); FAIL_IF(r != 0); diff --git a/src/tests/detect-tls-cert-subject.c b/src/tests/detect-tls-cert-subject.c index e13fdb23fa14..97f45345bd41 100644 --- a/src/tests/detect-tls-cert-subject.c +++ b/src/tests/detect-tls-cert-subject.c @@ -278,12 +278,12 @@ static int DetectTlsSubjectTest02(void) memset(&f, 0, sizeof(Flow)); memset(&ssn, 0, sizeof(TcpSession)); - p1 = UTHBuildPacketReal(client_hello, sizeof(client_hello), IPPROTO_TCP, - "192.168.1.5", "192.168.1.1", 51251, 443); - p2 = UTHBuildPacketReal(server_hello, sizeof(server_hello), IPPROTO_TCP, - "192.168.1.1", "192.168.1.5", 443, 51251); - p3 = UTHBuildPacketReal(certificate, sizeof(certificate), IPPROTO_TCP, - "192.168.1.1", "192.168.1.5", 443, 51251); + p1 = UTHBuildPacketReal(client_hello, sizeof(client_hello), IPPROTO_TCP, "192.168.1.5", + "192.168.1.1", 51251, 443); + p2 = UTHBuildPacketReal(server_hello, sizeof(server_hello), IPPROTO_TCP, "192.168.1.1", + "192.168.1.5", 443, 51251); + p3 = UTHBuildPacketReal(certificate, sizeof(certificate), IPPROTO_TCP, "192.168.1.1", + "192.168.1.5", 443, 51251); FLOW_INITIALIZE(&f); f.flags |= FLOW_IPV4; @@ -318,17 +318,16 @@ static int DetectTlsSubjectTest02(void) de_ctx->flags |= DE_QUIET; Signature *s = DetectEngineAppendSig(de_ctx, "alert tls any any -> any any " - "(msg:\"Test tls.cert_subject\"; " - "tls.cert_subject; content:\"google\"; nocase; " - "sid:1;)"); + "(msg:\"Test tls.cert_subject\"; " + "tls.cert_subject; content:\"google\"; nocase; " + "sid:1;)"); FAIL_IF_NULL(s); SigGroupBuild(de_ctx); DetectEngineThreadCtxInit(&tv, (void *)de_ctx, (void *)&det_ctx); - int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_TLS, - STREAM_TOSERVER, client_hello, - sizeof(client_hello)); + int r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_TLS, STREAM_TOSERVER, client_hello, sizeof(client_hello)); FAIL_IF(r != 0); @@ -339,8 +338,8 @@ static int DetectTlsSubjectTest02(void) FAIL_IF(PacketAlertCheck(p1, 1)); - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_TLS, STREAM_TOCLIENT, - server_hello, sizeof(server_hello)); + r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_TLS, STREAM_TOCLIENT, server_hello, sizeof(server_hello)); FAIL_IF(r != 0); @@ -348,8 +347,8 @@ static int DetectTlsSubjectTest02(void) FAIL_IF(PacketAlertCheck(p2, 1)); - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_TLS, STREAM_TOCLIENT, - certificate, sizeof(certificate)); + r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_TLS, STREAM_TOCLIENT, certificate, sizeof(certificate)); FAIL_IF(r != 0); diff --git a/src/tests/detect-tls-cert-validity.c b/src/tests/detect-tls-cert-validity.c index cf28c8d6df5e..a7b28a191159 100644 --- a/src/tests/detect-tls-cert-validity.c +++ b/src/tests/detect-tls-cert-validity.c @@ -32,7 +32,7 @@ * \retval 1 on success. * \retval 0 on failure. */ -static int ValidityTestParse01 (void) +static int ValidityTestParse01(void) { DetectTlsValidityData *dd = NULL; dd = DetectTlsValidityParse("1430000000"); @@ -48,7 +48,7 @@ static int ValidityTestParse01 (void) * \retval 1 on success. * \retval 0 on failure. */ -static int ValidityTestParse02 (void) +static int ValidityTestParse02(void) { DetectTlsValidityData *dd = NULL; dd = DetectTlsValidityParse(">1430000000"); @@ -64,7 +64,7 @@ static int ValidityTestParse02 (void) * \retval 1 on success. * \retval 0 on failure. */ -static int ValidityTestParse03 (void) +static int ValidityTestParse03(void) { DetectTlsValidityData *dd = NULL; dd = DetectTlsValidityParse("<1430000000"); @@ -80,7 +80,7 @@ static int ValidityTestParse03 (void) * \retval 1 on success. * \retval 0 on failure. */ -static int ValidityTestParse04 (void) +static int ValidityTestParse04(void) { DetectTlsValidityData *dd = NULL; dd = DetectTlsValidityParse("1430000000<>1470000000"); @@ -97,7 +97,7 @@ static int ValidityTestParse04 (void) * \retval 1 on success. * \retval 0 on failure. */ -static int ValidityTestParse05 (void) +static int ValidityTestParse05(void) { DetectTlsValidityData *dd = NULL; dd = DetectTlsValidityParse("A"); @@ -111,7 +111,7 @@ static int ValidityTestParse05 (void) * \retval 1 on success. * \retval 0 on failure. */ -static int ValidityTestParse06 (void) +static int ValidityTestParse06(void) { DetectTlsValidityData *dd = NULL; dd = DetectTlsValidityParse(">1430000000<>1470000000"); @@ -125,7 +125,7 @@ static int ValidityTestParse06 (void) * \retval 1 on success. * \retval 0 on failure. */ -static int ValidityTestParse07 (void) +static int ValidityTestParse07(void) { DetectTlsValidityData *dd = NULL; dd = DetectTlsValidityParse("1430000000<>"); @@ -139,7 +139,7 @@ static int ValidityTestParse07 (void) * \retval 1 on success. * \retval 0 on failure. */ -static int ValidityTestParse08 (void) +static int ValidityTestParse08(void) { DetectTlsValidityData *dd = NULL; dd = DetectTlsValidityParse("<>1430000000"); @@ -153,7 +153,7 @@ static int ValidityTestParse08 (void) * \retval 1 on success. * \retval 0 on failure. */ -static int ValidityTestParse09 (void) +static int ValidityTestParse09(void) { DetectTlsValidityData *dd = NULL; dd = DetectTlsValidityParse(""); @@ -167,7 +167,7 @@ static int ValidityTestParse09 (void) * \retval 1 on success. * \retval 0 on failure. */ -static int ValidityTestParse10 (void) +static int ValidityTestParse10(void) { DetectTlsValidityData *dd = NULL; dd = DetectTlsValidityParse(" "); @@ -181,7 +181,7 @@ static int ValidityTestParse10 (void) * \retval 1 on success. * \retval 0 on failure. */ -static int ValidityTestParse11 (void) +static int ValidityTestParse11(void) { DetectTlsValidityData *dd = NULL; dd = DetectTlsValidityParse("1490000000<>1430000000"); @@ -195,7 +195,7 @@ static int ValidityTestParse11 (void) * \retval 1 on success. * \retval 0 on failure. */ -static int ValidityTestParse12 (void) +static int ValidityTestParse12(void) { DetectTlsValidityData *dd = NULL; dd = DetectTlsValidityParse("1430000000 <> 1490000000"); @@ -212,7 +212,7 @@ static int ValidityTestParse12 (void) * \retval 1 on success. * \retval 0 on failure. */ -static int ValidityTestParse13 (void) +static int ValidityTestParse13(void) { DetectTlsValidityData *dd = NULL; dd = DetectTlsValidityParse("> 1430000000 "); @@ -228,7 +228,7 @@ static int ValidityTestParse13 (void) * \retval 1 on success. * \retval 0 on failure. */ -static int ValidityTestParse14 (void) +static int ValidityTestParse14(void) { DetectTlsValidityData *dd = NULL; dd = DetectTlsValidityParse("< 1490000000 "); @@ -244,7 +244,7 @@ static int ValidityTestParse14 (void) * \retval 1 on success. * \retval 0 on failure. */ -static int ValidityTestParse15 (void) +static int ValidityTestParse15(void) { DetectTlsValidityData *dd = NULL; dd = DetectTlsValidityParse(" 1490000000 "); @@ -260,7 +260,7 @@ static int ValidityTestParse15 (void) * \retval 1 on success. * \retval 0 on failure. */ -static int ValidityTestParse16 (void) +static int ValidityTestParse16(void) { DetectTlsValidityData *dd = NULL; dd = DetectTlsValidityParse("2015-10"); @@ -276,7 +276,7 @@ static int ValidityTestParse16 (void) * \retval 1 on success. * \retval 0 on failure. */ -static int ValidityTestParse17 (void) +static int ValidityTestParse17(void) { DetectTlsValidityData *dd = NULL; dd = DetectTlsValidityParse(">2015-10-22"); @@ -292,7 +292,7 @@ static int ValidityTestParse17 (void) * \retval 1 on success. * \retval 0 on failure. */ -static int ValidityTestParse18 (void) +static int ValidityTestParse18(void) { DetectTlsValidityData *dd = NULL; dd = DetectTlsValidityParse("<2015-10-22 23"); @@ -308,7 +308,7 @@ static int ValidityTestParse18 (void) * \retval 1 on success. * \retval 0 on failure. */ -static int ValidityTestParse19 (void) +static int ValidityTestParse19(void) { DetectTlsValidityData *dd = NULL; dd = DetectTlsValidityParse("2015-10-22 23:59"); @@ -324,7 +324,7 @@ static int ValidityTestParse19 (void) * \retval 1 on success. * \retval 0 on failure. */ -static int ValidityTestParse20 (void) +static int ValidityTestParse20(void) { DetectTlsValidityData *dd = NULL; dd = DetectTlsValidityParse("2015-10-22 23:59:59"); @@ -340,7 +340,7 @@ static int ValidityTestParse20 (void) * \retval 1 on success. * \retval 0 on failure. */ -static int ValidityTestParse21 (void) +static int ValidityTestParse21(void) { DetectTlsValidityData *dd = NULL; dd = DetectTlsValidityParse("2015-10-22T23"); @@ -356,7 +356,7 @@ static int ValidityTestParse21 (void) * \retval 1 on success. * \retval 0 on failure. */ -static int ValidityTestParse22 (void) +static int ValidityTestParse22(void) { DetectTlsValidityData *dd = NULL; dd = DetectTlsValidityParse("2015-10-22T23:59"); @@ -372,7 +372,7 @@ static int ValidityTestParse22 (void) * \retval 1 on success. * \retval 0 on failure. */ -static int ValidityTestParse23 (void) +static int ValidityTestParse23(void) { DetectTlsValidityData *dd = NULL; dd = DetectTlsValidityParse("2015-10-22T23:59:59"); @@ -642,12 +642,12 @@ static int ValidityTestDetect01(void) memset(&f, 0, sizeof(Flow)); memset(&ssn, 0, sizeof(TcpSession)); - p1 = UTHBuildPacketReal(client_hello, sizeof(client_hello), IPPROTO_TCP, - "192.168.1.5", "192.168.1.1", 51251, 443); - p2 = UTHBuildPacketReal(server_hello, sizeof(server_hello), IPPROTO_TCP, - "192.168.1.1", "192.168.1.5", 443, 51251); - p3 = UTHBuildPacketReal(certificate, sizeof(certificate), IPPROTO_TCP, - "192.168.1.1", "192.168.1.5", 443, 51251); + p1 = UTHBuildPacketReal(client_hello, sizeof(client_hello), IPPROTO_TCP, "192.168.1.5", + "192.168.1.1", 51251, 443); + p2 = UTHBuildPacketReal(server_hello, sizeof(server_hello), IPPROTO_TCP, "192.168.1.1", + "192.168.1.5", 443, 51251); + p3 = UTHBuildPacketReal(certificate, sizeof(certificate), IPPROTO_TCP, "192.168.1.1", + "192.168.1.5", 443, 51251); FLOW_INITIALIZE(&f); f.flags |= FLOW_IPV4; @@ -681,21 +681,20 @@ static int ValidityTestDetect01(void) de_ctx->flags |= DE_QUIET; Signature *s = DetectEngineAppendSig(de_ctx, "alert tls any any -> any any " - "(msg:\"Test tls_cert_notbefore\"; " - "tls_cert_notbefore:<2016-07-20; sid:1;)"); + "(msg:\"Test tls_cert_notbefore\"; " + "tls_cert_notbefore:<2016-07-20; sid:1;)"); FAIL_IF_NULL(s); s = DetectEngineAppendSig(de_ctx, "alert tls any any -> any any " - "(msg:\"Test tls_cert_notafter\"; " - "tls_cert_notafter:>2016-09-01; sid:2;)"); + "(msg:\"Test tls_cert_notafter\"; " + "tls_cert_notafter:>2016-09-01; sid:2;)"); FAIL_IF_NULL(s); SigGroupBuild(de_ctx); DetectEngineThreadCtxInit(&tv, (void *)de_ctx, (void *)&det_ctx); - int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_TLS, - STREAM_TOSERVER, client_hello, - sizeof(client_hello)); + int r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_TLS, STREAM_TOSERVER, client_hello, sizeof(client_hello)); FAIL_IF(r != 0); @@ -707,8 +706,8 @@ static int ValidityTestDetect01(void) FAIL_IF(PacketAlertCheck(p1, 1)); FAIL_IF(PacketAlertCheck(p1, 2)); - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_TLS, STREAM_TOCLIENT, - server_hello, sizeof(server_hello)); + r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_TLS, STREAM_TOCLIENT, server_hello, sizeof(server_hello)); FAIL_IF(r != 0); @@ -717,8 +716,8 @@ static int ValidityTestDetect01(void) FAIL_IF(PacketAlertCheck(p2, 1)); FAIL_IF(PacketAlertCheck(p2, 2)); - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_TLS, STREAM_TOCLIENT, - certificate, sizeof(certificate)); + r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_TLS, STREAM_TOCLIENT, certificate, sizeof(certificate)); FAIL_IF(r != 0); @@ -978,12 +977,12 @@ static int ExpiredTestDetect01(void) memset(&f, 0, sizeof(Flow)); memset(&ssn, 0, sizeof(TcpSession)); - p1 = UTHBuildPacketReal(client_hello, sizeof(client_hello), IPPROTO_TCP, - "192.168.1.5", "192.168.1.1", 51251, 443); - p2 = UTHBuildPacketReal(server_hello, sizeof(server_hello), IPPROTO_TCP, - "192.168.1.1", "192.168.1.5", 443, 51251); - p3 = UTHBuildPacketReal(certificate, sizeof(certificate), IPPROTO_TCP, - "192.168.1.1", "192.168.1.5", 443, 51251); + p1 = UTHBuildPacketReal(client_hello, sizeof(client_hello), IPPROTO_TCP, "192.168.1.5", + "192.168.1.1", 51251, 443); + p2 = UTHBuildPacketReal(server_hello, sizeof(server_hello), IPPROTO_TCP, "192.168.1.1", + "192.168.1.5", 443, 51251); + p3 = UTHBuildPacketReal(certificate, sizeof(certificate), IPPROTO_TCP, "192.168.1.1", + "192.168.1.5", 443, 51251); FLOW_INITIALIZE(&f); f.flags |= FLOW_IPV4; @@ -1019,15 +1018,15 @@ static int ExpiredTestDetect01(void) de_ctx->flags |= DE_QUIET; Signature *s = DetectEngineAppendSig(de_ctx, "alert tls any any -> any any " - "(msg:\"Test tls_cert_expired\"; " - "tls_cert_expired; sid:1;)"); + "(msg:\"Test tls_cert_expired\"; " + "tls_cert_expired; sid:1;)"); FAIL_IF_NULL(s); SigGroupBuild(de_ctx); DetectEngineThreadCtxInit(&tv, (void *)de_ctx, (void *)&det_ctx); - int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_TLS, STREAM_TOSERVER, - client_hello, sizeof(client_hello)); + int r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_TLS, STREAM_TOSERVER, client_hello, sizeof(client_hello)); FAIL_IF(r != 0); @@ -1038,8 +1037,8 @@ static int ExpiredTestDetect01(void) FAIL_IF(PacketAlertCheck(p1, 1)); - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_TLS, STREAM_TOCLIENT, - server_hello, sizeof(server_hello)); + r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_TLS, STREAM_TOCLIENT, server_hello, sizeof(server_hello)); FAIL_IF(r != 0); @@ -1047,8 +1046,8 @@ static int ExpiredTestDetect01(void) FAIL_IF(PacketAlertCheck(p2, 1)); - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_TLS, STREAM_TOCLIENT, - certificate, sizeof(certificate)); + r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_TLS, STREAM_TOCLIENT, certificate, sizeof(certificate)); FAIL_IF(r != 0); @@ -1292,12 +1291,12 @@ static int ValidTestDetect01(void) memset(&f, 0, sizeof(Flow)); memset(&ssn, 0, sizeof(TcpSession)); - p1 = UTHBuildPacketReal(client_hello, sizeof(client_hello), IPPROTO_TCP, - "192.168.1.5", "192.168.1.1", 51251, 443); - p2 = UTHBuildPacketReal(server_hello, sizeof(server_hello), IPPROTO_TCP, - "192.168.1.1", "192.168.1.5", 443, 51251); - p3 = UTHBuildPacketReal(certificate, sizeof(certificate), IPPROTO_TCP, - "192.168.1.1", "192.168.1.5", 443, 51251); + p1 = UTHBuildPacketReal(client_hello, sizeof(client_hello), IPPROTO_TCP, "192.168.1.5", + "192.168.1.1", 51251, 443); + p2 = UTHBuildPacketReal(server_hello, sizeof(server_hello), IPPROTO_TCP, "192.168.1.1", + "192.168.1.5", 443, 51251); + p3 = UTHBuildPacketReal(certificate, sizeof(certificate), IPPROTO_TCP, "192.168.1.1", + "192.168.1.5", 443, 51251); FLOW_INITIALIZE(&f); f.flags |= FLOW_IPV4; @@ -1333,15 +1332,15 @@ static int ValidTestDetect01(void) de_ctx->flags |= DE_QUIET; Signature *s = DetectEngineAppendSig(de_ctx, "alert tls any any -> any any " - "(msg:\"Test tls_cert_valid\"; " - "tls_cert_valid; sid:1;)"); + "(msg:\"Test tls_cert_valid\"; " + "tls_cert_valid; sid:1;)"); FAIL_IF_NULL(s); SigGroupBuild(de_ctx); DetectEngineThreadCtxInit(&tv, (void *)de_ctx, (void *)&det_ctx); - int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_TLS, STREAM_TOSERVER, - client_hello, sizeof(client_hello)); + int r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_TLS, STREAM_TOSERVER, client_hello, sizeof(client_hello)); FAIL_IF(r != 0); @@ -1352,8 +1351,8 @@ static int ValidTestDetect01(void) FAIL_IF(PacketAlertCheck(p1, 1)); - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_TLS, STREAM_TOCLIENT, - server_hello, sizeof(server_hello)); + r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_TLS, STREAM_TOCLIENT, server_hello, sizeof(server_hello)); FAIL_IF(r != 0); @@ -1361,8 +1360,8 @@ static int ValidTestDetect01(void) FAIL_IF(PacketAlertCheck(p2, 1)); - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_TLS, STREAM_TOCLIENT, - certificate, sizeof(certificate)); + r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_TLS, STREAM_TOCLIENT, certificate, sizeof(certificate)); FAIL_IF(r != 0); diff --git a/src/tests/detect-tls-certs.c b/src/tests/detect-tls-certs.c index 09b3fa8342a6..ef96216e2fe3 100644 --- a/src/tests/detect-tls-certs.c +++ b/src/tests/detect-tls-certs.c @@ -274,12 +274,12 @@ static int DetectTlsCertsTest02(void) memset(&f, 0, sizeof(Flow)); memset(&ssn, 0, sizeof(TcpSession)); - p1 = UTHBuildPacketReal(client_hello, sizeof(client_hello), IPPROTO_TCP, - "192.168.1.5", "192.168.1.1", 51251, 443); - p2 = UTHBuildPacketReal(server_hello, sizeof(server_hello), IPPROTO_TCP, - "192.168.1.1", "192.168.1.5", 443, 51251); - p3 = UTHBuildPacketReal(certificate, sizeof(certificate), IPPROTO_TCP, - "192.168.1.1", "192.168.1.5", 443, 51251); + p1 = UTHBuildPacketReal(client_hello, sizeof(client_hello), IPPROTO_TCP, "192.168.1.5", + "192.168.1.1", 51251, 443); + p2 = UTHBuildPacketReal(server_hello, sizeof(server_hello), IPPROTO_TCP, "192.168.1.1", + "192.168.1.5", 443, 51251); + p3 = UTHBuildPacketReal(certificate, sizeof(certificate), IPPROTO_TCP, "192.168.1.1", + "192.168.1.5", 443, 51251); FLOW_INITIALIZE(&f); f.flags |= FLOW_IPV4; @@ -314,16 +314,15 @@ static int DetectTlsCertsTest02(void) de_ctx->flags |= DE_QUIET; Signature *s = DetectEngineAppendSig(de_ctx, "alert tls any any -> any any " - "(msg:\"Test tls.certs\"; tls.certs; " - "content:\"|06 09 2a 86 48|\"; sid:1;)"); + "(msg:\"Test tls.certs\"; tls.certs; " + "content:\"|06 09 2a 86 48|\"; sid:1;)"); FAIL_IF_NULL(s); SigGroupBuild(de_ctx); DetectEngineThreadCtxInit(&tv, (void *)de_ctx, (void *)&det_ctx); - int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_TLS, - STREAM_TOSERVER, client_hello, - sizeof(client_hello)); + int r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_TLS, STREAM_TOSERVER, client_hello, sizeof(client_hello)); FAIL_IF(r != 0); @@ -334,8 +333,8 @@ static int DetectTlsCertsTest02(void) FAIL_IF(PacketAlertCheck(p1, 1)); - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_TLS, STREAM_TOCLIENT, - server_hello, sizeof(server_hello)); + r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_TLS, STREAM_TOCLIENT, server_hello, sizeof(server_hello)); FAIL_IF(r != 0); @@ -343,8 +342,8 @@ static int DetectTlsCertsTest02(void) FAIL_IF(PacketAlertCheck(p2, 1)); - r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_TLS, STREAM_TOCLIENT, - certificate, sizeof(certificate)); + r = AppLayerParserParse( + NULL, alp_tctx, &f, ALPROTO_TLS, STREAM_TOCLIENT, certificate, sizeof(certificate)); FAIL_IF(r != 0); diff --git a/src/tests/detect-tls-version.c b/src/tests/detect-tls-version.c index 3f55faa89c0d..9e43b7056ada 100644 --- a/src/tests/detect-tls-version.c +++ b/src/tests/detect-tls-version.c @@ -29,7 +29,7 @@ * \test DetectTlsVersionTestParse01 is a test to make sure that we parse the "id" * option correctly when given valid id option */ -static int DetectTlsVersionTestParse01 (void) +static int DetectTlsVersionTestParse01(void) { DetectTlsVersionData *tls = NULL; tls = DetectTlsVersionParse(NULL, "1.0"); @@ -44,7 +44,7 @@ static int DetectTlsVersionTestParse01 (void) * option correctly when given an invalid id option * it should return id_d = NULL */ -static int DetectTlsVersionTestParse02 (void) +static int DetectTlsVersionTestParse02(void) { DetectTlsVersionData *tls = NULL; tls = DetectTlsVersionParse(NULL, "2.5"); diff --git a/src/tests/detect-transform-pcrexform.c b/src/tests/detect-transform-pcrexform.c index be236152681e..5fe724e92811 100644 --- a/src/tests/detect-transform-pcrexform.c +++ b/src/tests/detect-transform-pcrexform.c @@ -27,13 +27,12 @@ * \test signature with an invalid pcrexform value. */ -static int DetectTransformPcrexformParseTest01 (void) +static int DetectTransformPcrexformParseTest01(void) { DetectEngineCtx *de_ctx = DetectEngineCtxInit(); FAIL_IF_NULL(de_ctx); - Signature *sig = DetectEngineAppendSig(de_ctx, - "alert tcp any any <> any 1 pcrexform:\"[\";"); + Signature *sig = DetectEngineAppendSig(de_ctx, "alert tcp any any <> any 1 pcrexform:\"[\";"); FAIL_IF_NOT_NULL(sig); DetectEngineCtxFree(de_ctx); @@ -44,13 +43,14 @@ static int DetectTransformPcrexformParseTest01 (void) * \test signature with a valid pcrexform value. */ -static int DetectTransformPcrexformParseTest02 (void) +static int DetectTransformPcrexformParseTest02(void) { DetectEngineCtx *de_ctx = DetectEngineCtxInit(); FAIL_IF_NULL(de_ctx); Signature *sig = DetectEngineAppendSig(de_ctx, - "alert http any any -> any any (msg:\"HTTP with pcrexform\"; http.request_line; pcrexform:\"[a-zA-Z]+\\s+(.*)\\s+HTTP\"; content:\"/z4d4kWk.jpg\"; sid:1;)"); + "alert http any any -> any any (msg:\"HTTP with pcrexform\"; http.request_line; " + "pcrexform:\"[a-zA-Z]+\\s+(.*)\\s+HTTP\"; content:\"/z4d4kWk.jpg\"; sid:1;)"); FAIL_IF_NULL(sig); DetectEngineCtxFree(de_ctx); diff --git a/src/tests/detect-ttl.c b/src/tests/detect-ttl.c index 74949313c438..9d5a85d72e55 100644 --- a/src/tests/detect-ttl.c +++ b/src/tests/detect-ttl.c @@ -26,7 +26,7 @@ * \test DetectTtlParseTest01 is a test for setting up an valid ttl value. */ -static int DetectTtlParseTest01 (void) +static int DetectTtlParseTest01(void) { DetectU8Data *ttld = DetectU8Parse("10"); FAIL_IF_NULL(ttld); @@ -41,7 +41,7 @@ static int DetectTtlParseTest01 (void) * "<" operator. */ -static int DetectTtlParseTest02 (void) +static int DetectTtlParseTest02(void) { DetectU8Data *ttld = DetectU8Parse("<10"); FAIL_IF_NULL(ttld); @@ -56,7 +56,7 @@ static int DetectTtlParseTest02 (void) * "-" operator. */ -static int DetectTtlParseTest03 (void) +static int DetectTtlParseTest03(void) { DetectU8Data *ttld = DetectU8Parse("1-3"); FAIL_IF_NULL(ttld); @@ -72,7 +72,7 @@ static int DetectTtlParseTest03 (void) * ">" operator and include spaces arround the given values. */ -static int DetectTtlParseTest04 (void) +static int DetectTtlParseTest04(void) { DetectU8Data *ttld = DetectU8Parse(" > 10 "); FAIL_IF_NULL(ttld); @@ -87,7 +87,7 @@ static int DetectTtlParseTest04 (void) * "-" operator and include spaces arround the given values. */ -static int DetectTtlParseTest05 (void) +static int DetectTtlParseTest05(void) { DetectU8Data *ttld = DetectU8Parse(" 1 - 3 "); FAIL_IF_NULL(ttld); @@ -103,7 +103,7 @@ static int DetectTtlParseTest05 (void) * invalid "=" operator and include spaces arround the given values. */ -static int DetectTtlParseTest06 (void) +static int DetectTtlParseTest06(void) { DetectU8Data *ttld = DetectU8Parse(" 1 = 2 "); FAIL_IF_NOT_NULL(ttld); @@ -115,7 +115,7 @@ static int DetectTtlParseTest06 (void) * invalid "<>" operator and include spaces arround the given values. */ -static int DetectTtlParseTest07 (void) +static int DetectTtlParseTest07(void) { DetectU8Data *ttld = DetectU8Parse(" 1<>2 "); FAIL_IF_NOT_NULL(ttld); @@ -178,16 +178,20 @@ static int DetectTtlTestSig1(void) FAIL_IF_NULL(de_ctx); de_ctx->flags |= DE_QUIET; - s = DetectEngineAppendSig(de_ctx,"alert ip any any -> any any (msg:\"with in ttl limit\"; ttl: >16; sid:1;)"); + s = DetectEngineAppendSig( + de_ctx, "alert ip any any -> any any (msg:\"with in ttl limit\"; ttl: >16; sid:1;)"); FAIL_IF_NULL(s); - s = DetectEngineAppendSig(de_ctx,"alert ip any any -> any any (msg:\"Less than 17\"; ttl: <17; sid:2;)"); + s = DetectEngineAppendSig( + de_ctx, "alert ip any any -> any any (msg:\"Less than 17\"; ttl: <17; sid:2;)"); FAIL_IF_NULL(s); - s = DetectEngineAppendSig(de_ctx,"alert ip any any -> any any (msg:\"Greater than 5\"; ttl:15; sid:3;)"); + s = DetectEngineAppendSig( + de_ctx, "alert ip any any -> any any (msg:\"Greater than 5\"; ttl:15; sid:3;)"); FAIL_IF_NULL(s); - s = DetectEngineAppendSig(de_ctx,"alert ip any any -> any any (msg:\"Equals tcp\"; ttl: 1-30; sid:4;)"); + s = DetectEngineAppendSig( + de_ctx, "alert ip any any -> any any (msg:\"Equals tcp\"; ttl: 1-30; sid:4;)"); FAIL_IF_NULL(s); SigGroupBuild(de_ctx); diff --git a/src/tests/detect-udphdr.c b/src/tests/detect-udphdr.c index 5e661fb57bc5..5fa3bc8cc7cc 100644 --- a/src/tests/detect-udphdr.c +++ b/src/tests/detect-udphdr.c @@ -25,13 +25,13 @@ #include "../util-unittest.h" -static int DetectUdphdrParseTest01 (void) +static int DetectUdphdrParseTest01(void) { DetectEngineCtx *de_ctx = DetectEngineCtxInit(); FAIL_IF_NULL(de_ctx); - Signature *sig = DetectEngineAppendSig(de_ctx, - "alert udp any any -> any any (udp.hdr; content:\"A\"; sid:1; rev:1;)"); + Signature *sig = DetectEngineAppendSig( + de_ctx, "alert udp any any -> any any (udp.hdr; content:\"A\"; sid:1; rev:1;)"); FAIL_IF_NULL(sig); DetectEngineCtxFree(de_ctx); diff --git a/src/tests/detect.c b/src/tests/detect.c index 64811929edef..7ab23c65f6ea 100644 --- a/src/tests/detect.c +++ b/src/tests/detect.c @@ -30,85 +30,85 @@ #include "../util-unittest-helper.h" static const char *dummy_conf_string = - "%YAML 1.1\n" - "---\n" - "\n" - "default-log-dir: /var/log/suricata\n" - "\n" - "logging:\n" - "\n" - " default-log-level: debug\n" - "\n" - " default-format: \"<%t> - <%l>\"\n" - "\n" - " default-startup-message: Your IDS has started.\n" - "\n" - " default-output-filter:\n" - "\n" - " output:\n" - "\n" - " - interface: console\n" - " log-level: info\n" - "\n" - " - interface: file\n" - " filename: /var/log/suricata.log\n" - "\n" - " - interface: syslog\n" - " facility: local5\n" - " format: \"%l\"\n" - "\n" - "pfring:\n" - "\n" - " interface: eth0\n" - "\n" - " clusterid: 99\n" - "\n" - "vars:\n" - "\n" - " address-groups:\n" - "\n" - " HOME_NET: \"[192.168.0.0/16,10.8.0.0/16,127.0.0.1,2001:888:" - "13c5:5AFE::/64,2001:888:13c5:CAFE::/64]\"\n" - "\n" - " EXTERNAL_NET: \"[!192.168.0.0/16,2000::/3]\"\n" - "\n" - " HTTP_SERVERS: \"!192.168.0.0/16\"\n" - "\n" - " SMTP_SERVERS: \"!192.168.0.0/16\"\n" - "\n" - " SQL_SERVERS: \"!192.168.0.0/16\"\n" - "\n" - " DNS_SERVERS: any\n" - "\n" - " TELNET_SERVERS: any\n" - "\n" - " AIM_SERVERS: any\n" - "\n" - " port-groups:\n" - "\n" - " HTTP_PORTS: \"80:81,88\"\n" - "\n" - " SHELLCODE_PORTS: 80\n" - "\n" - " ORACLE_PORTS: 1521\n" - "\n" - " SSH_PORTS: 22\n" - "\n"; - -static int SigTest01 (void) + "%YAML 1.1\n" + "---\n" + "\n" + "default-log-dir: /var/log/suricata\n" + "\n" + "logging:\n" + "\n" + " default-log-level: debug\n" + "\n" + " default-format: \"<%t> - <%l>\"\n" + "\n" + " default-startup-message: Your IDS has started.\n" + "\n" + " default-output-filter:\n" + "\n" + " output:\n" + "\n" + " - interface: console\n" + " log-level: info\n" + "\n" + " - interface: file\n" + " filename: /var/log/suricata.log\n" + "\n" + " - interface: syslog\n" + " facility: local5\n" + " format: \"%l\"\n" + "\n" + "pfring:\n" + "\n" + " interface: eth0\n" + "\n" + " clusterid: 99\n" + "\n" + "vars:\n" + "\n" + " address-groups:\n" + "\n" + " HOME_NET: \"[192.168.0.0/16,10.8.0.0/16,127.0.0.1,2001:888:" + "13c5:5AFE::/64,2001:888:13c5:CAFE::/64]\"\n" + "\n" + " EXTERNAL_NET: \"[!192.168.0.0/16,2000::/3]\"\n" + "\n" + " HTTP_SERVERS: \"!192.168.0.0/16\"\n" + "\n" + " SMTP_SERVERS: \"!192.168.0.0/16\"\n" + "\n" + " SQL_SERVERS: \"!192.168.0.0/16\"\n" + "\n" + " DNS_SERVERS: any\n" + "\n" + " TELNET_SERVERS: any\n" + "\n" + " AIM_SERVERS: any\n" + "\n" + " port-groups:\n" + "\n" + " HTTP_PORTS: \"80:81,88\"\n" + "\n" + " SHELLCODE_PORTS: 80\n" + "\n" + " ORACLE_PORTS: 1521\n" + "\n" + " SSH_PORTS: 22\n" + "\n"; + +static int SigTest01(void) { - uint8_t *buf = (uint8_t *) - "GET /one/ HTTP/1.1\r\n" - "Host: one.example.org\r\n" - "\r\n\r\n" - "GET /two/ HTTP/1.1\r\n" - "Host: two.example.org\r\n" - "\r\n\r\n"; + uint8_t *buf = (uint8_t *)"GET /one/ HTTP/1.1\r\n" + "Host: one.example.org\r\n" + "\r\n\r\n" + "GET /two/ HTTP/1.1\r\n" + "Host: two.example.org\r\n" + "\r\n\r\n"; uint16_t buflen = strlen((char *)buf); - Packet *p = UTHBuildPacket( buf, buflen, IPPROTO_TCP); + Packet *p = UTHBuildPacket(buf, buflen, IPPROTO_TCP); int result = 0; - char sig[] = "alert tcp any any -> any any (msg:\"HTTP URI cap\"; content:\"GET \"; depth:4; pcre:\"/GET (?P.*) HTTP\\/\\d\\.\\d\\r\\n/G\"; sid:1;)"; + char sig[] = "alert tcp any any -> any any (msg:\"HTTP URI cap\"; content:\"GET \"; depth:4; " + "pcre:\"/GET (?P.*) HTTP\\/\\d\\.\\d\\r\\n/G\"; sid:1;)"; if (UTHPacketMatchSigMpm(p, sig, MPM_AC) == 0) { result = 0; goto end; @@ -133,32 +133,31 @@ static int SigTest01 (void) return result; } -static int SigTest02 (void) +static int SigTest02(void) { - uint8_t *buf = (uint8_t *) - "GET /one/ HTTP/1.1\r\n" - "Host: one.example.org\r\n" - "\r\n\r\n" - "GET /two/ HTTP/1.1\r\n" - "Host: two.example.org\r\n" - "\r\n\r\n"; + uint8_t *buf = (uint8_t *)"GET /one/ HTTP/1.1\r\n" + "Host: one.example.org\r\n" + "\r\n\r\n" + "GET /two/ HTTP/1.1\r\n" + "Host: two.example.org\r\n" + "\r\n\r\n"; uint16_t buflen = strlen((char *)buf); - Packet *p = UTHBuildPacket( buf, buflen, IPPROTO_TCP); - char sig[] = "alert tcp any any -> any any (msg:\"HTTP TEST\"; content:\"Host: one.example.org\"; offset:20; depth:41; sid:1;)"; + Packet *p = UTHBuildPacket(buf, buflen, IPPROTO_TCP); + char sig[] = "alert tcp any any -> any any (msg:\"HTTP TEST\"; content:\"Host: " + "one.example.org\"; offset:20; depth:41; sid:1;)"; int ret = UTHPacketMatchSigMpm(p, sig, MPM_AC); UTHFreePacket(p); return ret; } -static int SigTest03 (void) +static int SigTest03(void) { - uint8_t *buf = (uint8_t *) - "GET /one/ HTTP/1.1\r\n" - "Host: one.example.org\r\n" - "\r\n\r\n" - "GET /two/ HTTP/1.1\r\n" - "Host: two.example.org\r\n" - "\r\n\r\n"; + uint8_t *buf = (uint8_t *)"GET /one/ HTTP/1.1\r\n" + "Host: one.example.org\r\n" + "\r\n\r\n" + "GET /two/ HTTP/1.1\r\n" + "Host: two.example.org\r\n" + "\r\n\r\n"; uint16_t buflen = strlen((char *)buf); Packet *p = NULL; ThreadVars th_v; @@ -176,7 +175,9 @@ static int SigTest03 (void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert tcp any any -> any any (msg:\"HTTP TEST\"; content:\"Host: one.example.org\"; offset:20; depth:39; sid:1;)"); + de_ctx->sig_list = + SigInit(de_ctx, "alert tcp any any -> any any (msg:\"HTTP TEST\"; content:\"Host: " + "one.example.org\"; offset:20; depth:39; sid:1;)"); if (de_ctx->sig_list == NULL) { result = 0; goto end; @@ -199,15 +200,14 @@ static int SigTest03 (void) return result; } -static int SigTest04 (void) +static int SigTest04(void) { - uint8_t *buf = (uint8_t *) - "GET /one/ HTTP/1.1\r\n" /* 20*/ - "Host: one.example.org\r\n" /* 23, post "Host:" 18 */ - "\r\n\r\n" /* 4 */ - "GET /two/ HTTP/1.1\r\n" /* 20 */ - "Host: two.example.org\r\n" /* 23 */ - "\r\n\r\n"; /* 4 */ + uint8_t *buf = (uint8_t *)"GET /one/ HTTP/1.1\r\n" /* 20*/ + "Host: one.example.org\r\n" /* 23, post "Host:" 18 */ + "\r\n\r\n" /* 4 */ + "GET /two/ HTTP/1.1\r\n" /* 20 */ + "Host: two.example.org\r\n" /* 23 */ + "\r\n\r\n"; /* 4 */ uint16_t buflen = strlen((char *)buf); Packet *p = NULL; @@ -226,7 +226,9 @@ static int SigTest04 (void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert tcp any any -> any any (msg:\"HTTP TEST\"; content:\"Host:\"; offset:20; depth:25; content:\"Host:\"; distance:42; within:47; sid:1;)"); + de_ctx->sig_list = SigInit( + de_ctx, "alert tcp any any -> any any (msg:\"HTTP TEST\"; content:\"Host:\"; " + "offset:20; depth:25; content:\"Host:\"; distance:42; within:47; sid:1;)"); if (de_ctx->sig_list == NULL) { result = 0; goto end; @@ -249,15 +251,14 @@ static int SigTest04 (void) return result; } -static int SigTest05 (void) +static int SigTest05(void) { - uint8_t *buf = (uint8_t *) - "GET /one/ HTTP/1.1\r\n" /* 20 */ - "Host: one.example.org\r\n" /* 23, 43 */ - "\r\n\r\n" /* 4, 47 */ - "GET /two/ HTTP/1.1\r\n" /* 20, 67 */ - "Host: two.example.org\r\n" /* 23, 90 */ - "\r\n\r\n"; /* 4, 94 */ + uint8_t *buf = (uint8_t *)"GET /one/ HTTP/1.1\r\n" /* 20 */ + "Host: one.example.org\r\n" /* 23, 43 */ + "\r\n\r\n" /* 4, 47 */ + "GET /two/ HTTP/1.1\r\n" /* 20, 67 */ + "Host: two.example.org\r\n" /* 23, 90 */ + "\r\n\r\n"; /* 4, 94 */ uint16_t buflen = strlen((char *)buf); Packet *p = NULL; ThreadVars th_v; @@ -275,7 +276,9 @@ static int SigTest05 (void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert tcp any any -> any any (msg:\"HTTP TEST\"; content:\"Host:\"; offset:20; depth:25; content:\"Host:\"; distance:48; within:52; sid:1;)"); + de_ctx->sig_list = SigInit( + de_ctx, "alert tcp any any -> any any (msg:\"HTTP TEST\"; content:\"Host:\"; " + "offset:20; depth:25; content:\"Host:\"; distance:48; within:52; sid:1;)"); if (de_ctx->sig_list == NULL) { printf("sig parse failed: "); goto end; @@ -301,15 +304,14 @@ static int SigTest05 (void) return result; } -static int SigTest06 (void) +static int SigTest06(void) { - uint8_t *buf = (uint8_t *) - "GET /one/ HTTP/1.1\r\n" /* 20 */ - "Host: one.example.org\r\n" /* 23, 43 */ - "\r\n\r\n" /* 4, 47 */ - "GET /two/ HTTP/1.1\r\n" /* 20, 67 */ - "Host: two.example.org\r\n" /* 23, 90 */ - "\r\n\r\n"; /* 4, 94 */ + uint8_t *buf = (uint8_t *)"GET /one/ HTTP/1.1\r\n" /* 20 */ + "Host: one.example.org\r\n" /* 23, 43 */ + "\r\n\r\n" /* 4, 47 */ + "GET /two/ HTTP/1.1\r\n" /* 20, 67 */ + "Host: two.example.org\r\n" /* 23, 90 */ + "\r\n\r\n"; /* 4, 94 */ uint16_t buflen = strlen((char *)buf); Packet *p = NULL; ThreadVars th_v; @@ -333,7 +335,7 @@ static int SigTest06 (void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -342,10 +344,13 @@ static int SigTest06 (void) FAIL_IF_NULL(de_ctx); de_ctx->flags |= DE_QUIET; - Signature *s = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any (msg:\"HTTP URI cap\"; content:\"GET \"; depth:4; pcre:\"/GET (?P.*) HTTP\\/\\d\\.\\d\\r\\n/G\"; sid:1;)"); + Signature *s = DetectEngineAppendSig(de_ctx, + "alert tcp any any -> any any (msg:\"HTTP URI cap\"; content:\"GET \"; depth:4; " + "pcre:\"/GET (?P.*) HTTP\\/\\d\\.\\d\\r\\n/G\"; sid:1;)"); FAIL_IF_NULL(s); - s = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any (msg:\"HTTP URI test\"; uricontent:\"two\"; sid:2;)"); + s = DetectEngineAppendSig(de_ctx, + "alert tcp any any -> any any (msg:\"HTTP URI test\"; uricontent:\"two\"; sid:2;)"); FAIL_IF_NULL(s); SigGroupBuild(de_ctx); @@ -368,15 +373,14 @@ static int SigTest06 (void) PASS; } -static int SigTest07 (void) +static int SigTest07(void) { - uint8_t *buf = (uint8_t *) - "GET /one/ HTTP/1.1\r\n" /* 20 */ - "Host: one.example.org\r\n" /* 23, 43 */ - "\r\n\r\n" /* 4, 47 */ - "GET /two/ HTTP/1.1\r\n" /* 20, 67 */ - "Host: two.example.org\r\n" /* 23, 90 */ - "\r\n\r\n"; /* 4, 94 */ + uint8_t *buf = (uint8_t *)"GET /one/ HTTP/1.1\r\n" /* 20 */ + "Host: one.example.org\r\n" /* 23, 43 */ + "\r\n\r\n" /* 4, 47 */ + "GET /two/ HTTP/1.1\r\n" /* 20, 67 */ + "Host: two.example.org\r\n" /* 23, 90 */ + "\r\n\r\n"; /* 4, 94 */ uint16_t buflen = strlen((char *)buf); Packet *p = NULL; ThreadVars th_v; @@ -399,7 +403,7 @@ static int SigTest07 (void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -411,19 +415,22 @@ static int SigTest07 (void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert tcp any any -> any any (msg:\"HTTP URI cap\"; content:\"GET \"; depth:4; pcre:\"/GET (?P.*) HTTP\\/\\d\\.\\d\\r\\n/G\"; sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, + "alert tcp any any -> any any (msg:\"HTTP URI cap\"; content:\"GET \"; depth:4; " + "pcre:\"/GET (?P.*) HTTP\\/\\d\\.\\d\\r\\n/G\"; sid:1;)"); if (de_ctx->sig_list == NULL) { result = 0; goto end; } - de_ctx->sig_list->next = SigInit(de_ctx,"alert tcp any any -> any any (msg:\"HTTP URI test\"; uricontent:\"three\"; sid:2;)"); + de_ctx->sig_list->next = SigInit(de_ctx, + "alert tcp any any -> any any (msg:\"HTTP URI test\"; uricontent:\"three\"; sid:2;)"); if (de_ctx->sig_list->next == NULL) { result = 0; goto end; } SigGroupBuild(de_ctx); - DetectEngineThreadCtxInit(&th_v, (void *)de_ctx,(void *)&det_ctx); + DetectEngineThreadCtxInit(&th_v, (void *)de_ctx, (void *)&det_ctx); int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_HTTP1, STREAM_TOSERVER, buf, buflen); if (r != 0) { @@ -454,15 +461,14 @@ static int SigTest07 (void) return result; } -static int SigTest08 (void) +static int SigTest08(void) { - uint8_t *buf = (uint8_t *) - "GET /one/ HTTP/1.0\r\n" /* 20 */ - "Host: one.example.org\r\n" /* 23, 43 */ - "\r\n\r\n" /* 4, 47 */ - "GET /two/ HTTP/1.0\r\n" /* 20, 67 */ - "Host: two.example.org\r\n" /* 23, 90 */ - "\r\n\r\n"; /* 4, 94 */ + uint8_t *buf = (uint8_t *)"GET /one/ HTTP/1.0\r\n" /* 20 */ + "Host: one.example.org\r\n" /* 23, 43 */ + "\r\n\r\n" /* 4, 47 */ + "GET /two/ HTTP/1.0\r\n" /* 20, 67 */ + "Host: two.example.org\r\n" /* 23, 90 */ + "\r\n\r\n"; /* 4, 94 */ uint16_t buflen = strlen((char *)buf); Packet *p = NULL; ThreadVars th_v; @@ -485,7 +491,7 @@ static int SigTest08 (void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -497,19 +503,22 @@ static int SigTest08 (void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert tcp any any -> any any (msg:\"HTTP URI cap\"; content:\"GET \"; depth:4; pcre:\"/GET (?P.*) HTTP\\/1\\.0\\r\\n/G\"; sid:1;)"); + de_ctx->sig_list = SigInit( + de_ctx, "alert tcp any any -> any any (msg:\"HTTP URI cap\"; content:\"GET \"; " + "depth:4; pcre:\"/GET (?P.*) HTTP\\/1\\.0\\r\\n/G\"; sid:1;)"); if (de_ctx->sig_list == NULL) { result = 0; goto end; } - de_ctx->sig_list->next = SigInit(de_ctx,"alert tcp any any -> any any (msg:\"HTTP URI test\"; uricontent:\"one\"; sid:2;)"); + de_ctx->sig_list->next = SigInit(de_ctx, + "alert tcp any any -> any any (msg:\"HTTP URI test\"; uricontent:\"one\"; sid:2;)"); if (de_ctx->sig_list->next == NULL) { result = 0; goto end; } SigGroupBuild(de_ctx); - DetectEngineThreadCtxInit(&th_v, (void *)de_ctx,(void *)&det_ctx); + DetectEngineThreadCtxInit(&th_v, (void *)de_ctx, (void *)&det_ctx); int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_HTTP1, STREAM_TOSERVER, buf, buflen); if (r != 0) { @@ -522,9 +531,8 @@ static int SigTest08 (void) if (PacketAlertCheck(p, 1) && PacketAlertCheck(p, 2)) result = 1; else - printf("sid:1 %s, sid:2 %s: ", - PacketAlertCheck(p, 1) ? "OK" : "FAIL", - PacketAlertCheck(p, 2) ? "OK" : "FAIL"); + printf("sid:1 %s, sid:2 %s: ", PacketAlertCheck(p, 1) ? "OK" : "FAIL", + PacketAlertCheck(p, 2) ? "OK" : "FAIL"); end: FlowCleanupAppLayer(&f); @@ -542,15 +550,14 @@ static int SigTest08 (void) return result; } -static int SigTest09 (void) +static int SigTest09(void) { - uint8_t *buf = (uint8_t *) - "GET /one/ HTTP/1.0\r\n" /* 20 */ - "Host: one.example.org\r\n" /* 23, 43 */ - "\r\n\r\n" /* 4, 47 */ - "GET /two/ HTTP/1.0\r\n" /* 20, 67 */ - "Host: two.example.org\r\n" /* 23, 90 */ - "\r\n\r\n"; /* 4, 94 */ + uint8_t *buf = (uint8_t *)"GET /one/ HTTP/1.0\r\n" /* 20 */ + "Host: one.example.org\r\n" /* 23, 43 */ + "\r\n\r\n" /* 4, 47 */ + "GET /two/ HTTP/1.0\r\n" /* 20, 67 */ + "Host: two.example.org\r\n" /* 23, 90 */ + "\r\n\r\n"; /* 4, 94 */ uint16_t buflen = strlen((char *)buf); Packet *p = NULL; ThreadVars th_v; @@ -573,7 +580,7 @@ static int SigTest09 (void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -585,19 +592,22 @@ static int SigTest09 (void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert tcp any any -> any any (msg:\"HTTP URI cap\"; content:\"GET \"; depth:4; pcre:\"/GET (?P.*) HTTP\\/1\\.0\\r\\n/G\"; sid:1;)"); + de_ctx->sig_list = SigInit( + de_ctx, "alert tcp any any -> any any (msg:\"HTTP URI cap\"; content:\"GET \"; " + "depth:4; pcre:\"/GET (?P.*) HTTP\\/1\\.0\\r\\n/G\"; sid:1;)"); if (de_ctx->sig_list == NULL) { result = 0; goto end; } - de_ctx->sig_list->next = SigInit(de_ctx,"alert tcp any any -> any any (msg:\"HTTP URI test\"; uricontent:\"two\"; sid:2;)"); + de_ctx->sig_list->next = SigInit(de_ctx, + "alert tcp any any -> any any (msg:\"HTTP URI test\"; uricontent:\"two\"; sid:2;)"); if (de_ctx->sig_list->next == NULL) { result = 0; goto end; } SigGroupBuild(de_ctx); - DetectEngineThreadCtxInit(&th_v, (void *)de_ctx,(void *)&det_ctx); + DetectEngineThreadCtxInit(&th_v, (void *)de_ctx, (void *)&det_ctx); int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_HTTP1, STREAM_TOSERVER, buf, buflen); if (r != 0) { @@ -627,10 +637,9 @@ static int SigTest09 (void) return result; } -static int SigTest10 (void) +static int SigTest10(void) { - uint8_t *buf = (uint8_t *) - "ABC"; + uint8_t *buf = (uint8_t *)"ABC"; uint16_t buflen = strlen((char *)buf); Packet *p = NULL; ThreadVars th_v; @@ -653,7 +662,7 @@ static int SigTest10 (void) p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; p->flowflags |= FLOW_PKT_ESTABLISHED; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -665,19 +674,21 @@ static int SigTest10 (void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert tcp any any -> any any (msg:\"Long content test (1)\"; content:\"ABCD\"; depth:4; sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any (msg:\"Long content test " + "(1)\"; content:\"ABCD\"; depth:4; sid:1;)"); if (de_ctx->sig_list == NULL) { result = 0; goto end; } - de_ctx->sig_list->next = SigInit(de_ctx,"alert tcp any any -> any any (msg:\"Long content test (2)\"; content:\"VWXYZ\"; sid:2;)"); + de_ctx->sig_list->next = SigInit(de_ctx, "alert tcp any any -> any any (msg:\"Long content " + "test (2)\"; content:\"VWXYZ\"; sid:2;)"); if (de_ctx->sig_list->next == NULL) { result = 0; goto end; } SigGroupBuild(de_ctx); - DetectEngineThreadCtxInit(&th_v, (void *)de_ctx,(void *)&det_ctx); + DetectEngineThreadCtxInit(&th_v, (void *)de_ctx, (void *)&det_ctx); int r = AppLayerParserParse(NULL, alp_tctx, &f, ALPROTO_HTTP1, STREAM_TOSERVER, buf, buflen); if (r != 0) { @@ -692,7 +703,7 @@ static int SigTest10 (void) else result = 1; - end: +end: FlowCleanupAppLayer(&f); SigGroupCleanup(de_ctx); SigCleanSignatures(de_ctx); @@ -707,10 +718,10 @@ static int SigTest10 (void) return result; } -static int SigTest11 (void) +static int SigTest11(void) { - uint8_t *buf = (uint8_t *) - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_+"; + uint8_t *buf = + (uint8_t *)"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_+"; uint16_t buflen = strlen((char *)buf); Packet *p = NULL; ThreadVars th_v; @@ -731,7 +742,7 @@ static int SigTest11 (void) f.flags |= FLOW_IPV4; p->flow = &f; p->flowflags |= FLOW_PKT_TOSERVER; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; f.alproto = ALPROTO_HTTP1; StreamTcpInitConfig(true); @@ -743,23 +754,26 @@ static int SigTest11 (void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert tcp any any -> any any (content:\"ABCDEFGHIJ\"; content:\"klmnop\"; content:\"1234\"; sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any (content:\"ABCDEFGHIJ\"; " + "content:\"klmnop\"; content:\"1234\"; sid:1;)"); if (de_ctx->sig_list == NULL) { goto end; } - de_ctx->sig_list->next = SigInit(de_ctx,"alert tcp any any -> any any (content:\"VWXYZabcde\"; content:\"5678\"; content:\"89\"; sid:2;)"); + de_ctx->sig_list->next = + SigInit(de_ctx, "alert tcp any any -> any any (content:\"VWXYZabcde\"; " + "content:\"5678\"; content:\"89\"; sid:2;)"); if (de_ctx->sig_list->next == NULL) { goto end; } SigGroupBuild(de_ctx); - DetectEngineThreadCtxInit(&th_v, (void *)de_ctx,(void *)&det_ctx); + DetectEngineThreadCtxInit(&th_v, (void *)de_ctx, (void *)&det_ctx); SigMatchSignatures(&th_v, de_ctx, det_ctx, p); if (PacketAlertCheck(p, 1) && PacketAlertCheck(p, 2)) result = 1; - end: +end: FlowCleanupAppLayer(&f); SigGroupCleanup(de_ctx); if (det_ctx) @@ -771,10 +785,10 @@ static int SigTest11 (void) return result; } -static int SigTest12 (void) +static int SigTest12(void) { - uint8_t *buf = (uint8_t *) - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_+"; + uint8_t *buf = + (uint8_t *)"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_+"; uint16_t buflen = strlen((char *)buf); Packet *p = NULL; ThreadVars th_v; @@ -789,7 +803,7 @@ static int SigTest12 (void) p = UTHBuildPacket((uint8_t *)buf, buflen, IPPROTO_TCP); p->flow = &f; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; DetectEngineCtx *de_ctx = DetectEngineCtxInit(); if (de_ctx == NULL) { @@ -798,14 +812,16 @@ static int SigTest12 (void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert tcp any any -> any any (msg:\"Content order test\"; content:\"ABCDEFGHIJ\"; content:\"klmnop\"; content:\"1234\"; sid:1;)"); + de_ctx->sig_list = SigInit( + de_ctx, "alert tcp any any -> any any (msg:\"Content order test\"; " + "content:\"ABCDEFGHIJ\"; content:\"klmnop\"; content:\"1234\"; sid:1;)"); if (de_ctx->sig_list == NULL) { result = 0; goto end; } SigGroupBuild(de_ctx); - DetectEngineThreadCtxInit(&th_v, (void *)de_ctx,(void *)&det_ctx); + DetectEngineThreadCtxInit(&th_v, (void *)de_ctx, (void *)&det_ctx); SigMatchSignatures(&th_v, de_ctx, det_ctx, p); if (PacketAlertCheck(p, 1)) @@ -814,7 +830,7 @@ static int SigTest12 (void) result = 0; if (det_ctx != NULL) - DetectEngineThreadCtxDeinit(&th_v, (void *)det_ctx); + DetectEngineThreadCtxDeinit(&th_v, (void *)det_ctx); end: UTHFreePackets(&p, 1); if (de_ctx != NULL) { @@ -826,10 +842,10 @@ static int SigTest12 (void) return result; } -static int SigTest13 (void) +static int SigTest13(void) { - uint8_t *buf = (uint8_t *) - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_+"; + uint8_t *buf = + (uint8_t *)"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_+"; uint16_t buflen = strlen((char *)buf); Packet *p = NULL; ThreadVars th_v; @@ -844,7 +860,7 @@ static int SigTest13 (void) p = UTHBuildPacket((uint8_t *)buf, buflen, IPPROTO_TCP); p->flow = &f; - p->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; DetectEngineCtx *de_ctx = DetectEngineCtxInit(); if (de_ctx == NULL) { @@ -853,14 +869,16 @@ static int SigTest13 (void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert tcp any any -> any any (msg:\"Content order test\"; content:\"ABCDEFGHIJ\"; content:\"1234\"; content:\"klmnop\"; sid:1;)"); + de_ctx->sig_list = SigInit( + de_ctx, "alert tcp any any -> any any (msg:\"Content order test\"; " + "content:\"ABCDEFGHIJ\"; content:\"1234\"; content:\"klmnop\"; sid:1;)"); if (de_ctx->sig_list == NULL) { result = 0; goto end; } SigGroupBuild(de_ctx); - DetectEngineThreadCtxInit(&th_v, (void *)de_ctx,(void *)&det_ctx); + DetectEngineThreadCtxInit(&th_v, (void *)de_ctx, (void *)&det_ctx); SigMatchSignatures(&th_v, de_ctx, det_ctx, p); if (PacketAlertCheck(p, 1)) @@ -878,10 +896,10 @@ static int SigTest13 (void) return result; } -static int SigTest14 (void) +static int SigTest14(void) { - uint8_t *buf = (uint8_t *) - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_+"; + uint8_t *buf = + (uint8_t *)"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_+"; uint16_t buflen = strlen((char *)buf); Packet *p = NULL; ThreadVars th_v; @@ -899,14 +917,16 @@ static int SigTest14 (void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert tcp any any -> any any (msg:\"Content order test\"; content:\"ABCDEFGHIJ\"; content:\"1234\"; content:\"klmnop\"; distance:0; sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, + "alert tcp any any -> any any (msg:\"Content order test\"; content:\"ABCDEFGHIJ\"; " + "content:\"1234\"; content:\"klmnop\"; distance:0; sid:1;)"); if (de_ctx->sig_list == NULL) { result = 0; goto end; } SigGroupBuild(de_ctx); - DetectEngineThreadCtxInit(&th_v, (void *)de_ctx,(void *)&det_ctx); + DetectEngineThreadCtxInit(&th_v, (void *)de_ctx, (void *)&det_ctx); SigMatchSignatures(&th_v, de_ctx, det_ctx, p); if (PacketAlertCheck(p, 1)) @@ -923,10 +943,9 @@ static int SigTest14 (void) return result; } -static int SigTest15 (void) +static int SigTest15(void) { - uint8_t *buf = (uint8_t *) - "CONNECT 213.92.8.7:31204 HTTP/1.1"; + uint8_t *buf = (uint8_t *)"CONNECT 213.92.8.7:31204 HTTP/1.1"; uint16_t buflen = strlen((char *)buf); Packet *p = PacketGetFromAlloc(); if (unlikely(p == NULL)) @@ -954,14 +973,17 @@ static int SigTest15 (void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert tcp any any -> any !$HTTP_PORTS (msg:\"ET POLICY Inbound HTTP CONNECT Attempt on Off-Port\"; content:\"CONNECT \"; nocase; depth:8; content:\" HTTP/1.\"; nocase; within:1000; sid:2008284; rev:2;)"); + de_ctx->sig_list = + SigInit(de_ctx, "alert tcp any any -> any !$HTTP_PORTS (msg:\"ET POLICY Inbound HTTP " + "CONNECT Attempt on Off-Port\"; content:\"CONNECT \"; nocase; depth:8; " + "content:\" HTTP/1.\"; nocase; within:1000; sid:2008284; rev:2;)"); if (de_ctx->sig_list == NULL) { result = 0; goto end; } SigGroupBuild(de_ctx); - DetectEngineThreadCtxInit(&th_v, (void *)de_ctx,(void *)&det_ctx); + DetectEngineThreadCtxInit(&th_v, (void *)de_ctx, (void *)&det_ctx); SigMatchSignatures(&th_v, de_ctx, det_ctx, p); if (PacketAlertCheck(p, 2008284)) @@ -980,10 +1002,9 @@ static int SigTest15 (void) return result; } -static int SigTest16 (void) +static int SigTest16(void) { - uint8_t *buf = (uint8_t *) - "CONNECT 213.92.8.7:31204 HTTP/1.1"; + uint8_t *buf = (uint8_t *)"CONNECT 213.92.8.7:31204 HTTP/1.1"; uint16_t buflen = strlen((char *)buf); Packet *p = NULL; ThreadVars th_v; @@ -1006,13 +1027,16 @@ static int SigTest16 (void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert tcp any any -> any !$HTTP_PORTS (msg:\"ET POLICY Inbound HTTP CONNECT Attempt on Off-Port\"; content:\"CONNECT \"; nocase; depth:8; content:\" HTTP/1.\"; nocase; within:1000; sid:2008284; rev:2;)"); + de_ctx->sig_list = + SigInit(de_ctx, "alert tcp any any -> any !$HTTP_PORTS (msg:\"ET POLICY Inbound HTTP " + "CONNECT Attempt on Off-Port\"; content:\"CONNECT \"; nocase; depth:8; " + "content:\" HTTP/1.\"; nocase; within:1000; sid:2008284; rev:2;)"); if (de_ctx->sig_list == NULL) { goto end; } SigGroupBuild(de_ctx); - DetectEngineThreadCtxInit(&th_v, (void *)de_ctx,(void *)&det_ctx); + DetectEngineThreadCtxInit(&th_v, (void *)de_ctx, (void *)&det_ctx); SigMatchSignatures(&th_v, de_ctx, det_ctx, p); if (PacketAlertCheck(p, 2008284)) @@ -1030,15 +1054,14 @@ static int SigTest16 (void) return result; } -static int SigTest17 (void) +static int SigTest17(void) { - uint8_t *buf = (uint8_t *) - "GET /one/ HTTP/1.1\r\n" /* 20 */ - "Host: one.example.org\r\n" /* 23, 43 */ - "\r\n\r\n" /* 4, 47 */ - "GET /two/ HTTP/1.1\r\n" /* 20, 67 */ - "Host: two.example.org\r\n" /* 23, 90 */ - "\r\n\r\n"; /* 4, 94 */ + uint8_t *buf = (uint8_t *)"GET /one/ HTTP/1.1\r\n" /* 20 */ + "Host: one.example.org\r\n" /* 23, 43 */ + "\r\n\r\n" /* 4, 47 */ + "GET /two/ HTTP/1.1\r\n" /* 20, 67 */ + "Host: two.example.org\r\n" /* 23, 90 */ + "\r\n\r\n"; /* 4, 94 */ uint16_t buflen = strlen((char *)buf); Packet *p = NULL; ThreadVars th_v; @@ -1056,11 +1079,13 @@ static int SigTest17 (void) FAIL_IF_NULL(de_ctx); de_ctx->flags |= DE_QUIET; - Signature *s = DetectEngineAppendSig(de_ctx,"alert tcp any any -> any $HTTP_PORTS (msg:\"HTTP host cap\"; content:\"Host:\"; pcre:\"/^Host: (?P.*)\\r\\n/m\"; noalert; sid:1;)"); + Signature *s = DetectEngineAppendSig(de_ctx, + "alert tcp any any -> any $HTTP_PORTS (msg:\"HTTP host cap\"; content:\"Host:\"; " + "pcre:\"/^Host: (?P.*)\\r\\n/m\"; noalert; sid:1;)"); FAIL_IF_NULL(s); SigGroupBuild(de_ctx); - DetectEngineThreadCtxInit(&th_v, (void *)de_ctx,(void *)&det_ctx); + DetectEngineThreadCtxInit(&th_v, (void *)de_ctx, (void *)&det_ctx); SigMatchSignatures(&th_v, de_ctx, det_ctx, p); uint32_t capid = VarNameStoreLookupByName("http_host", VAR_TYPE_PKT_VAR); @@ -1078,10 +1103,9 @@ static int SigTest17 (void) PASS; } -static int SigTest18 (void) +static int SigTest18(void) { - uint8_t *buf = (uint8_t *) - "220 (vsFTPd 2.0.5)\r\n"; + uint8_t *buf = (uint8_t *)"220 (vsFTPd 2.0.5)\r\n"; uint16_t buflen = strlen((char *)buf); Packet *p = PacketGetFromAlloc(); if (unlikely(p == NULL)) @@ -1106,14 +1130,16 @@ static int SigTest18 (void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert tcp any !21:902 -> any any (msg:\"ET MALWARE Suspicious 220 Banner on Local Port\"; content:\"220\"; offset:0; depth:4; pcre:\"/220[- ]/\"; sid:2003055; rev:4;)"); + de_ctx->sig_list = SigInit(de_ctx, + "alert tcp any !21:902 -> any any (msg:\"ET MALWARE Suspicious 220 Banner on Local " + "Port\"; content:\"220\"; offset:0; depth:4; pcre:\"/220[- ]/\"; sid:2003055; rev:4;)"); if (de_ctx->sig_list == NULL) { result = 0; goto end; } SigGroupBuild(de_ctx); - DetectEngineThreadCtxInit(&th_v, (void *)de_ctx,(void *)&det_ctx); + DetectEngineThreadCtxInit(&th_v, (void *)de_ctx, (void *)&det_ctx); SigMatchSignatures(&th_v, de_ctx, det_ctx, p); if (!PacketAlertCheck(p, 2003055)) @@ -1130,10 +1156,9 @@ static int SigTest18 (void) return result; } -static int SigTest19 (void) +static int SigTest19(void) { - uint8_t *buf = (uint8_t *) - "220 (vsFTPd 2.0.5)\r\n"; + uint8_t *buf = (uint8_t *)"220 (vsFTPd 2.0.5)\r\n"; uint16_t buflen = strlen((char *)buf); Packet *p = PacketGetFromAlloc(); if (unlikely(p == NULL)) @@ -1165,14 +1190,15 @@ static int SigTest19 (void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert ip $HOME_NET any -> 1.2.3.4 any (msg:\"IP-ONLY test (1)\"; sid:999; rev:1;)"); + de_ctx->sig_list = SigInit(de_ctx, + "alert ip $HOME_NET any -> 1.2.3.4 any (msg:\"IP-ONLY test (1)\"; sid:999; rev:1;)"); if (de_ctx->sig_list == NULL) { result = 0; goto end; } SigGroupBuild(de_ctx); - DetectEngineThreadCtxInit(&th_v, (void *)de_ctx,(void *)&det_ctx); + DetectEngineThreadCtxInit(&th_v, (void *)de_ctx, (void *)&det_ctx); SigMatchSignatures(&th_v, de_ctx, det_ctx, p); if (PacketAlertCheck(p, 999)) @@ -1190,10 +1216,9 @@ static int SigTest19 (void) return result; } -static int SigTest20 (void) +static int SigTest20(void) { - uint8_t *buf = (uint8_t *) - "220 (vsFTPd 2.0.5)\r\n"; + uint8_t *buf = (uint8_t *)"220 (vsFTPd 2.0.5)\r\n"; uint16_t buflen = strlen((char *)buf); Packet *p = PacketGetFromAlloc(); if (unlikely(p == NULL)) @@ -1225,14 +1250,16 @@ static int SigTest20 (void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert ip $HOME_NET any -> [99.99.99.99,1.2.3.0/24,1.1.1.1,3.0.0.0/8] any (msg:\"IP-ONLY test (2)\"; sid:999; rev:1;)"); + de_ctx->sig_list = + SigInit(de_ctx, "alert ip $HOME_NET any -> [99.99.99.99,1.2.3.0/24,1.1.1.1,3.0.0.0/8] " + "any (msg:\"IP-ONLY test (2)\"; sid:999; rev:1;)"); if (de_ctx->sig_list == NULL) { result = 0; goto end; } SigGroupBuild(de_ctx); - DetectEngineThreadCtxInit(&th_v, (void *)de_ctx,(void *)&det_ctx); + DetectEngineThreadCtxInit(&th_v, (void *)de_ctx, (void *)&det_ctx); SigMatchSignatures(&th_v, de_ctx, det_ctx, p); if (PacketAlertCheck(p, 999)) @@ -1251,7 +1278,7 @@ static int SigTest20 (void) return result; } -static int SigTest21 (void) +static int SigTest21(void) { ThreadVars th_v; memset(&th_v, 0, sizeof(th_v)); @@ -1264,21 +1291,21 @@ static int SigTest21 (void) /* packet 1 */ uint8_t *buf1 = (uint8_t *)"GET /one/ HTTP/1.0\r\n" - "\r\n\r\n"; + "\r\n\r\n"; uint16_t buf1len = strlen((char *)buf1); Packet *p1 = NULL; /* packet 2 */ uint8_t *buf2 = (uint8_t *)"GET /two/ HTTP/1.0\r\n" - "\r\n\r\n"; + "\r\n\r\n"; uint16_t buf2len = strlen((char *)buf2); Packet *p2 = NULL; p1 = UTHBuildPacket((uint8_t *)buf1, buf1len, IPPROTO_TCP); p1->flow = &f; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; p2 = UTHBuildPacket((uint8_t *)buf2, buf2len, IPPROTO_TCP); p2->flow = &f; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; DetectEngineCtx *de_ctx = DetectEngineCtxInit(); if (de_ctx == NULL) { @@ -1287,12 +1314,15 @@ static int SigTest21 (void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert tcp any any -> any any (msg:\"FLOWBIT SET\"; content:\"/one/\"; flowbits:set,TEST.one; flowbits:noalert; sid:1;)"); + de_ctx->sig_list = + SigInit(de_ctx, "alert tcp any any -> any any (msg:\"FLOWBIT SET\"; content:\"/one/\"; " + "flowbits:set,TEST.one; flowbits:noalert; sid:1;)"); if (de_ctx->sig_list == NULL) { result = 0; goto end; } - de_ctx->sig_list->next = SigInit(de_ctx,"alert tcp any any -> any any (msg:\"FLOWBIT TEST\"; content:\"/two/\"; flowbits:isset,TEST.one; sid:2;)"); + de_ctx->sig_list->next = SigInit(de_ctx, "alert tcp any any -> any any (msg:\"FLOWBIT TEST\"; " + "content:\"/two/\"; flowbits:isset,TEST.one; sid:2;)"); if (de_ctx->sig_list == NULL) { result = 0; goto end; @@ -1329,7 +1359,7 @@ static int SigTest21 (void) return result; } -static int SigTest22 (void) +static int SigTest22(void) { ThreadVars th_v; memset(&th_v, 0, sizeof(th_v)); @@ -1342,23 +1372,23 @@ static int SigTest22 (void) /* packet 1 */ uint8_t *buf1 = (uint8_t *)"GET /one/ HTTP/1.0\r\n" - "\r\n\r\n"; + "\r\n\r\n"; uint16_t buf1len = strlen((char *)buf1); Packet *p1 = NULL; p1 = UTHBuildPacket((uint8_t *)buf1, buf1len, IPPROTO_TCP); p1->flow = &f; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; /* packet 2 */ uint8_t *buf2 = (uint8_t *)"GET /two/ HTTP/1.0\r\n" - "\r\n\r\n"; + "\r\n\r\n"; uint16_t buf2len = strlen((char *)buf2); Packet *p2 = NULL; p2 = UTHBuildPacket((uint8_t *)buf2, buf2len, IPPROTO_TCP); p2->flow = &f; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; DetectEngineCtx *de_ctx = DetectEngineCtxInit(); if (de_ctx == NULL) { @@ -1367,12 +1397,15 @@ static int SigTest22 (void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert tcp any any -> any any (msg:\"FLOWBIT SET\"; content:\"/one/\"; flowbits:set,TEST.one; flowbits:noalert; sid:1;)"); + de_ctx->sig_list = + SigInit(de_ctx, "alert tcp any any -> any any (msg:\"FLOWBIT SET\"; content:\"/one/\"; " + "flowbits:set,TEST.one; flowbits:noalert; sid:1;)"); if (de_ctx->sig_list == NULL) { result = 0; goto end; } - de_ctx->sig_list->next = SigInit(de_ctx,"alert tcp any any -> any any (msg:\"FLOWBIT TEST\"; content:\"/two/\"; flowbits:isset,TEST.abc; sid:2;)"); + de_ctx->sig_list->next = SigInit(de_ctx, "alert tcp any any -> any any (msg:\"FLOWBIT TEST\"; " + "content:\"/two/\"; flowbits:isset,TEST.abc; sid:2;)"); if (de_ctx->sig_list == NULL) { result = 0; goto end; @@ -1404,7 +1437,7 @@ static int SigTest22 (void) return result; } -static int SigTest23 (void) +static int SigTest23(void) { ThreadVars th_v; memset(&th_v, 0, sizeof(th_v)); @@ -1417,23 +1450,23 @@ static int SigTest23 (void) /* packet 1 */ uint8_t *buf1 = (uint8_t *)"GET /one/ HTTP/1.0\r\n" - "\r\n\r\n"; + "\r\n\r\n"; uint16_t buf1len = strlen((char *)buf1); Packet *p1 = NULL; p1 = UTHBuildPacket((uint8_t *)buf1, buf1len, IPPROTO_TCP); p1->flow = &f; - p1->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p1->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; /* packet 2 */ uint8_t *buf2 = (uint8_t *)"GET /two/ HTTP/1.0\r\n" - "\r\n\r\n"; + "\r\n\r\n"; uint16_t buf2len = strlen((char *)buf2); Packet *p2 = NULL; p2 = UTHBuildPacket((uint8_t *)buf2, buf2len, IPPROTO_TCP); p2->flow = &f; - p2->flags |= PKT_HAS_FLOW|PKT_STREAM_EST; + p2->flags |= PKT_HAS_FLOW | PKT_STREAM_EST; DetectEngineCtx *de_ctx = DetectEngineCtxInit(); if (de_ctx == NULL) { @@ -1442,12 +1475,15 @@ static int SigTest23 (void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert tcp any any -> any any (msg:\"FLOWBIT SET\"; content:\"/one/\"; flowbits:toggle,TEST.one; flowbits:noalert; sid:1;)"); + de_ctx->sig_list = + SigInit(de_ctx, "alert tcp any any -> any any (msg:\"FLOWBIT SET\"; content:\"/one/\"; " + "flowbits:toggle,TEST.one; flowbits:noalert; sid:1;)"); if (de_ctx->sig_list == NULL) { result = 0; goto end; } - de_ctx->sig_list->next = SigInit(de_ctx,"alert tcp any any -> any any (msg:\"FLOWBIT TEST\"; content:\"/two/\"; flowbits:isset,TEST.one; sid:2;)"); + de_ctx->sig_list->next = SigInit(de_ctx, "alert tcp any any -> any any (msg:\"FLOWBIT TEST\"; " + "content:\"/two/\"; flowbits:isset,TEST.one; sid:2;)"); if (de_ctx->sig_list == NULL) { result = 0; goto end; @@ -1508,7 +1544,7 @@ static int SigTest24IPV4Keyword(void) int result = 0; uint8_t *buf = (uint8_t *)"GET /one/ HTTP/1.0\r\n" - "\r\n\r\n"; + "\r\n\r\n"; uint16_t buflen = strlen((char *)buf); memset(&th_v, 0, sizeof(ThreadVars)); @@ -1538,27 +1574,25 @@ static int SigTest24IPV4Keyword(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx, - "alert ip any any -> any any " - "(content:\"/one/\"; ipv4-csum:valid; " - "msg:\"ipv4-csum keyword check(1)\"; sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert ip any any -> any any " + "(content:\"/one/\"; ipv4-csum:valid; " + "msg:\"ipv4-csum keyword check(1)\"; sid:1;)"); if (de_ctx->sig_list == NULL) { printf("sig 1 parse: "); goto end; } - de_ctx->sig_list->next = SigInit(de_ctx, - "alert ip any any -> any any " - "(content:\"/one/\"; ipv4-csum:invalid; " - "msg:\"ipv4-csum keyword check(1)\"; " - "sid:2;)"); + de_ctx->sig_list->next = SigInit(de_ctx, "alert ip any any -> any any " + "(content:\"/one/\"; ipv4-csum:invalid; " + "msg:\"ipv4-csum keyword check(1)\"; " + "sid:2;)"); if (de_ctx->sig_list->next == NULL) { printf("sig 2 parse: "); goto end; } SigGroupBuild(de_ctx); - DetectEngineThreadCtxInit(&th_v, (void *)de_ctx,(void *)&det_ctx); + DetectEngineThreadCtxInit(&th_v, (void *)de_ctx, (void *)&det_ctx); SigMatchSignatures(&th_v, de_ctx, det_ctx, p1); if (!(PacketAlertCheck(p1, 1))) { @@ -1614,7 +1648,7 @@ static int SigTest25NegativeIPV4Keyword(void) int result = 1; uint8_t *buf = (uint8_t *)"GET /one/ HTTP/1.0\r\n" - "\r\n\r\n"; + "\r\n\r\n"; uint16_t buflen = strlen((char *)buf); memset(&th_v, 0, sizeof(ThreadVars)); @@ -1644,27 +1678,25 @@ static int SigTest25NegativeIPV4Keyword(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx, - "alert ip any any -> any any " - "(content:\"/one/\"; ipv4-csum:invalid; " - "msg:\"ipv4-csum keyword check(1)\"; sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert ip any any -> any any " + "(content:\"/one/\"; ipv4-csum:invalid; " + "msg:\"ipv4-csum keyword check(1)\"; sid:1;)"); if (de_ctx->sig_list == NULL) { result &= 0; goto end; } - de_ctx->sig_list->next = SigInit(de_ctx, - "alert ip any any -> any any " - "(content:\"/one/\"; ipv4-csum:valid; " - "msg:\"ipv4-csum keyword check(1)\"; " - "sid:2;)"); + de_ctx->sig_list->next = SigInit(de_ctx, "alert ip any any -> any any " + "(content:\"/one/\"; ipv4-csum:valid; " + "msg:\"ipv4-csum keyword check(1)\"; " + "sid:2;)"); if (de_ctx->sig_list->next == NULL) { result &= 0; goto end; } SigGroupBuild(de_ctx); - DetectEngineThreadCtxInit(&th_v, (void *)de_ctx,(void *)&det_ctx); + DetectEngineThreadCtxInit(&th_v, (void *)de_ctx, (void *)&det_ctx); SigMatchSignatures(&th_v, de_ctx, det_ctx, p1); if (PacketAlertCheck(p1, 1)) @@ -1759,21 +1791,19 @@ static int SigTest26TCPV4Keyword(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx, - "alert ip any any -> any any " - "(content:\"|DE 01 03|\"; tcpv4-csum:valid; dsize:20; " - "msg:\"tcpv4-csum keyword check(1)\"; sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert ip any any -> any any " + "(content:\"|DE 01 03|\"; tcpv4-csum:valid; dsize:20; " + "msg:\"tcpv4-csum keyword check(1)\"; sid:1;)"); FAIL_IF_NULL(de_ctx->sig_list); - de_ctx->sig_list->next = SigInit(de_ctx, - "alert ip any any -> any any " - "(content:\"|DE 01 03|\"; tcpv4-csum:invalid; " - "msg:\"tcpv4-csum keyword check(1)\"; " - "sid:2;)"); + de_ctx->sig_list->next = SigInit(de_ctx, "alert ip any any -> any any " + "(content:\"|DE 01 03|\"; tcpv4-csum:invalid; " + "msg:\"tcpv4-csum keyword check(1)\"; " + "sid:2;)"); FAIL_IF_NULL(de_ctx->sig_list->next); SigGroupBuild(de_ctx); - DetectEngineThreadCtxInit(&th_v, (void *)de_ctx,(void *)&det_ctx); + DetectEngineThreadCtxInit(&th_v, (void *)de_ctx, (void *)&det_ctx); SigMatchSignatures(&th_v, de_ctx, det_ctx, p1); FAIL_IF(!(PacketAlertCheck(p1, 1))); @@ -1865,27 +1895,26 @@ static int SigTest26TCPV4AndNegativeIPV4Keyword(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx, - "alert ip any any -> any any " - "(content:\"|DE 01 03|\"; tcpv4-csum:valid; dsize:20; " - "ipv4-csum:invalid; " - "msg:\"tcpv4-csum and ipv4-csum keyword check(1)\"; sid:1;)"); + de_ctx->sig_list = + SigInit(de_ctx, "alert ip any any -> any any " + "(content:\"|DE 01 03|\"; tcpv4-csum:valid; dsize:20; " + "ipv4-csum:invalid; " + "msg:\"tcpv4-csum and ipv4-csum keyword check(1)\"; sid:1;)"); if (de_ctx->sig_list == NULL) { goto end; } - de_ctx->sig_list->next = SigInit(de_ctx, - "alert ip any any -> any any " - "(content:\"|DE 01 03|\"; tcpv4-csum:invalid; " - "ipv4-csum:invalid; " - "msg:\"tcpv4-csum keyword check(1)\"; " - "sid:2;)"); + de_ctx->sig_list->next = SigInit(de_ctx, "alert ip any any -> any any " + "(content:\"|DE 01 03|\"; tcpv4-csum:invalid; " + "ipv4-csum:invalid; " + "msg:\"tcpv4-csum keyword check(1)\"; " + "sid:2;)"); if (de_ctx->sig_list->next == NULL) { goto end; } SigGroupBuild(de_ctx); - DetectEngineThreadCtxInit(&th_v, (void *)de_ctx,(void *)&det_ctx); + DetectEngineThreadCtxInit(&th_v, (void *)de_ctx, (void *)&det_ctx); SigMatchSignatures(&th_v, de_ctx, det_ctx, p1); if (!(PacketAlertCheck(p1, 1))) { @@ -1995,27 +2024,26 @@ static int SigTest26TCPV4AndIPV4Keyword(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx, - "alert ip any any -> any any " - "(tcpv4-csum:valid; " - "ipv4-csum:valid; " - "msg:\"tcpv4-csum and ipv4-csum keyword check(1)\"; sid:1;)"); + de_ctx->sig_list = + SigInit(de_ctx, "alert ip any any -> any any " + "(tcpv4-csum:valid; " + "ipv4-csum:valid; " + "msg:\"tcpv4-csum and ipv4-csum keyword check(1)\"; sid:1;)"); if (de_ctx->sig_list == NULL) { goto end; } - de_ctx->sig_list->next = SigInit(de_ctx, - "alert ip any any -> any any " - "(tcpv4-csum:invalid; " - "ipv4-csum:valid; " - "msg:\"tcpv4-csum and ipv4-csum keyword check(1)\"; " - "sid:2;)"); + de_ctx->sig_list->next = SigInit(de_ctx, "alert ip any any -> any any " + "(tcpv4-csum:invalid; " + "ipv4-csum:valid; " + "msg:\"tcpv4-csum and ipv4-csum keyword check(1)\"; " + "sid:2;)"); if (de_ctx->sig_list->next == NULL) { goto end; } SigGroupBuild(de_ctx); - DetectEngineThreadCtxInit(&th_v, (void *)de_ctx,(void *)&det_ctx); + DetectEngineThreadCtxInit(&th_v, (void *)de_ctx, (void *)&det_ctx); SigMatchSignatures(&th_v, de_ctx, det_ctx, p1); if (!(PacketAlertCheck(p1, 1))) { @@ -2112,25 +2140,23 @@ static int SigTest27NegativeTCPV4Keyword(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx, - "alert tcp any any -> any any " - "(content:\"|DE 01 03|\"; tcpv4-csum:invalid; dsize:20; " - "msg:\"tcpv4-csum keyword check(1)\"; sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " + "(content:\"|DE 01 03|\"; tcpv4-csum:invalid; dsize:20; " + "msg:\"tcpv4-csum keyword check(1)\"; sid:1;)"); if (de_ctx->sig_list == NULL) { goto end; } - de_ctx->sig_list->next = SigInit(de_ctx, - "alert tcp any any -> any any " - "(content:\"|DE 01 03|\"; tcpv4-csum:valid; dsize:20; " - "msg:\"tcpv4-csum keyword check(2)\"; " - "sid:2;)"); + de_ctx->sig_list->next = SigInit(de_ctx, "alert tcp any any -> any any " + "(content:\"|DE 01 03|\"; tcpv4-csum:valid; dsize:20; " + "msg:\"tcpv4-csum keyword check(2)\"; " + "sid:2;)"); if (de_ctx->sig_list->next == NULL) { goto end; } SigGroupBuild(de_ctx); - DetectEngineThreadCtxInit(&th_v, (void *)de_ctx,(void *)&det_ctx); + DetectEngineThreadCtxInit(&th_v, (void *)de_ctx, (void *)&det_ctx); SigMatchSignatures(&th_v, de_ctx, det_ctx, p1); if (!PacketAlertCheck(p1, 1)) { @@ -2211,7 +2237,7 @@ static int SigTest28TCPV6Keyword(void) PACKET_RESET_CHECKSUMS(p1); p1->ip6h = (IPV6Hdr *)(valid_raw_ipv6 + 14); - p1->tcph = (TCPHdr *) (valid_raw_ipv6 + 54); + p1->tcph = (TCPHdr *)(valid_raw_ipv6 + 54); p1->src.family = AF_INET; p1->dst.family = AF_INET; p1->payload = valid_raw_ipv6 + 54 + 20; @@ -2224,7 +2250,7 @@ static int SigTest28TCPV6Keyword(void) PACKET_RESET_CHECKSUMS(p2); p2->ip6h = (IPV6Hdr *)(invalid_raw_ipv6 + 14); - p2->tcph = (TCPHdr *) (invalid_raw_ipv6 + 54); + p2->tcph = (TCPHdr *)(invalid_raw_ipv6 + 54); p2->src.family = AF_INET; p2->dst.family = AF_INET; p2->payload = invalid_raw_ipv6 + 54 + 20; @@ -2242,25 +2268,24 @@ static int SigTest28TCPV6Keyword(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx, - "alert tcp any any -> any any " - "(content:\"|00 01 69|\"; tcpv6-csum:valid; dsize:12; " - "msg:\"tcpv6-csum keyword check(1)\"; sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " + "(content:\"|00 01 69|\"; tcpv6-csum:valid; dsize:12; " + "msg:\"tcpv6-csum keyword check(1)\"; sid:1;)"); if (de_ctx->sig_list == NULL) { goto end; } - de_ctx->sig_list->next = SigInit(de_ctx, - "alert tcp any any -> any any " - "(content:\"|00 01 69|\"; tcpv6-csum:invalid; dsize:12; " - "msg:\"tcpv6-csum keyword check(1)\"; " - "sid:2;)"); + de_ctx->sig_list->next = + SigInit(de_ctx, "alert tcp any any -> any any " + "(content:\"|00 01 69|\"; tcpv6-csum:invalid; dsize:12; " + "msg:\"tcpv6-csum keyword check(1)\"; " + "sid:2;)"); if (de_ctx->sig_list->next == NULL) { goto end; } SigGroupBuild(de_ctx); - DetectEngineThreadCtxInit(&th_v, (void *)de_ctx,(void *)&det_ctx); + DetectEngineThreadCtxInit(&th_v, (void *)de_ctx, (void *)&det_ctx); SigMatchSignatures(&th_v, de_ctx, det_ctx, p1); if (!(PacketAlertCheck(p1, 1))) { @@ -2341,7 +2366,7 @@ static int SigTest29NegativeTCPV6Keyword(void) PACKET_RESET_CHECKSUMS(p1); p1->ip6h = (IPV6Hdr *)(valid_raw_ipv6 + 14); - p1->tcph = (TCPHdr *) (valid_raw_ipv6 + 54); + p1->tcph = (TCPHdr *)(valid_raw_ipv6 + 54); p1->src.family = AF_INET; p1->dst.family = AF_INET; p1->payload = valid_raw_ipv6 + 54 + 20; @@ -2354,7 +2379,7 @@ static int SigTest29NegativeTCPV6Keyword(void) PACKET_RESET_CHECKSUMS(p2); p2->ip6h = (IPV6Hdr *)(invalid_raw_ipv6 + 14); - p2->tcph = (TCPHdr *) (invalid_raw_ipv6 + 54); + p2->tcph = (TCPHdr *)(invalid_raw_ipv6 + 54); p2->src.family = AF_INET; p2->dst.family = AF_INET; p2->payload = invalid_raw_ipv6 + 54 + 20; @@ -2372,26 +2397,24 @@ static int SigTest29NegativeTCPV6Keyword(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx, - "alert tcp any any -> any any " - "(content:\"|00 01 69|\"; tcpv6-csum:invalid; dsize:12; " - "msg:\"tcpv6-csum keyword check(1)\"; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " + "(content:\"|00 01 69|\"; tcpv6-csum:invalid; dsize:12; " + "msg:\"tcpv6-csum keyword check(1)\"; " + "sid:1;)"); if (de_ctx->sig_list == NULL) { goto end; } - de_ctx->sig_list->next = SigInit(de_ctx, - "alert tcp any any -> any any " - "(content:\"|00 01 69|\"; tcpv6-csum:valid; dsize:12; " - "msg:\"tcpv6-csum keyword check(1)\"; " - "sid:2;)"); + de_ctx->sig_list->next = SigInit(de_ctx, "alert tcp any any -> any any " + "(content:\"|00 01 69|\"; tcpv6-csum:valid; dsize:12; " + "msg:\"tcpv6-csum keyword check(1)\"; " + "sid:2;)"); if (de_ctx->sig_list->next == NULL) { goto end; } SigGroupBuild(de_ctx); - DetectEngineThreadCtxInit(&th_v, (void *)de_ctx,(void *)&det_ctx); + DetectEngineThreadCtxInit(&th_v, (void *)de_ctx, (void *)&det_ctx); SigMatchSignatures(&th_v, de_ctx, det_ctx, p1); if (PacketAlertCheck(p1, 1)) @@ -2461,7 +2484,7 @@ static int SigTest30UDPV4Keyword(void) DetectEngineThreadCtx *det_ctx = NULL; uint8_t *buf = (uint8_t *)"GET /one/ HTTP/1.0yyyyyyyyyyyyyyyy\r\n" - "\r\n\r\nyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy"; + "\r\n\r\nyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy"; memset(&th_v, 0, sizeof(ThreadVars)); @@ -2488,22 +2511,20 @@ static int SigTest30UDPV4Keyword(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx, - "alert udp any any -> any any " - "(content:\"/one/\"; udpv4-csum:valid; " - "msg:\"udpv4-csum keyword check(1)\"; " - "sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert udp any any -> any any " + "(content:\"/one/\"; udpv4-csum:valid; " + "msg:\"udpv4-csum keyword check(1)\"; " + "sid:1;)"); FAIL_IF_NULL(de_ctx->sig_list); - de_ctx->sig_list->next = SigInit(de_ctx, - "alert udp any any -> any any " - "(content:\"/one/\"; udpv4-csum:invalid; " - "msg:\"udpv4-csum keyword check(1)\"; " - "sid:2;)"); + de_ctx->sig_list->next = SigInit(de_ctx, "alert udp any any -> any any " + "(content:\"/one/\"; udpv4-csum:invalid; " + "msg:\"udpv4-csum keyword check(1)\"; " + "sid:2;)"); FAIL_IF_NULL(de_ctx->sig_list->next); SigGroupBuild(de_ctx); - DetectEngineThreadCtxInit(&th_v, (void *)de_ctx,(void *)&det_ctx); + DetectEngineThreadCtxInit(&th_v, (void *)de_ctx, (void *)&det_ctx); SigMatchSignatures(&th_v, de_ctx, det_ctx, p1); FAIL_IF_NOT(PacketAlertCheck(p1, 1)); @@ -2573,7 +2594,7 @@ static int SigTest31NegativeUDPV4Keyword(void) int result = 1; uint8_t *buf = (uint8_t *)"GET /one/ HTTP/1.0yyyyyyyyyyyyyyyy\r\n" - "\r\n\r\nyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy"; + "\r\n\r\nyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy"; memset(&th_v, 0, sizeof(ThreadVars)); @@ -2602,27 +2623,25 @@ static int SigTest31NegativeUDPV4Keyword(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx, - "alert udp any any -> any any " - "(content:\"/one/\"; udpv4-csum:invalid; " - "msg:\"udpv4-csum keyword check(1)\"; sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert udp any any -> any any " + "(content:\"/one/\"; udpv4-csum:invalid; " + "msg:\"udpv4-csum keyword check(1)\"; sid:1;)"); if (de_ctx->sig_list == NULL) { result &= 0; goto end; } - de_ctx->sig_list->next = SigInit(de_ctx, - "alert udp any any -> any any " - "(content:\"/one/\"; udpv4-csum:valid; " - "msg:\"udpv4-csum keyword check(1)\"; " - "sid:2;)"); + de_ctx->sig_list->next = SigInit(de_ctx, "alert udp any any -> any any " + "(content:\"/one/\"; udpv4-csum:valid; " + "msg:\"udpv4-csum keyword check(1)\"; " + "sid:2;)"); if (de_ctx->sig_list->next == NULL) { result &= 0; goto end; } SigGroupBuild(de_ctx); - DetectEngineThreadCtxInit(&th_v, (void *)de_ctx,(void *)&det_ctx); + DetectEngineThreadCtxInit(&th_v, (void *)de_ctx, (void *)&det_ctx); SigMatchSignatures(&th_v, de_ctx, det_ctx, p1); if (PacketAlertCheck(p1, 1)) @@ -2633,8 +2652,7 @@ static int SigTest31NegativeUDPV4Keyword(void) SigMatchSignatures(&th_v, de_ctx, det_ctx, p2); if (PacketAlertCheck(p2, 2)) { result &= 0; - } - else + } else result &= 1; SigGroupCleanup(de_ctx); @@ -2648,7 +2666,6 @@ static int SigTest31NegativeUDPV4Keyword(void) return result; } - static int SigTest32UDPV6Keyword(void) { // clang-format off @@ -2688,13 +2705,13 @@ static int SigTest32UDPV6Keyword(void) DetectEngineThreadCtx *det_ctx = NULL; uint8_t *buf = (uint8_t *)"GET /one/ HTTP\r\n" - "\r\n\r\n"; + "\r\n\r\n"; memset(&th_v, 0, sizeof(ThreadVars)); PACKET_RESET_CHECKSUMS(p1); p1->ip6h = (IPV6Hdr *)(valid_raw_ipv6 + 14); - p1->udph = (UDPHdr *) (valid_raw_ipv6 + 54); + p1->udph = (UDPHdr *)(valid_raw_ipv6 + 54); p1->src.family = AF_INET; p1->dst.family = AF_INET; p1->payload = buf; @@ -2703,7 +2720,7 @@ static int SigTest32UDPV6Keyword(void) PACKET_RESET_CHECKSUMS(p2); p2->ip6h = (IPV6Hdr *)(invalid_raw_ipv6 + 14); - p2->udph = (UDPHdr *) (invalid_raw_ipv6 + 54); + p2->udph = (UDPHdr *)(invalid_raw_ipv6 + 54); p2->src.family = AF_INET; p2->dst.family = AF_INET; p2->payload = buf; @@ -2715,21 +2732,19 @@ static int SigTest32UDPV6Keyword(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx, - "alert udp any any -> any any " - "(content:\"/one/\"; udpv6-csum:valid; " - "msg:\"udpv6-csum keyword check(1)\"; sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert udp any any -> any any " + "(content:\"/one/\"; udpv6-csum:valid; " + "msg:\"udpv6-csum keyword check(1)\"; sid:1;)"); FAIL_IF_NULL(de_ctx->sig_list); - de_ctx->sig_list->next = SigInit(de_ctx, - "alert udp any any -> any any " - "(content:\"/one/\"; udpv6-csum:invalid; " - "msg:\"udpv6-csum keyword check(1)\"; " - "sid:2;)"); + de_ctx->sig_list->next = SigInit(de_ctx, "alert udp any any -> any any " + "(content:\"/one/\"; udpv6-csum:invalid; " + "msg:\"udpv6-csum keyword check(1)\"; " + "sid:2;)"); FAIL_IF_NULL(de_ctx->sig_list->next); SigGroupBuild(de_ctx); - DetectEngineThreadCtxInit(&th_v, (void *)de_ctx,(void *)&det_ctx); + DetectEngineThreadCtxInit(&th_v, (void *)de_ctx, (void *)&det_ctx); SigMatchSignatures(&th_v, de_ctx, det_ctx, p1); FAIL_IF_NOT(PacketAlertCheck(p1, 1)); @@ -2791,13 +2806,13 @@ static int SigTest33NegativeUDPV6Keyword(void) int result = 1; uint8_t *buf = (uint8_t *)"GET /one/ HTTP\r\n" - "\r\n\r\n"; + "\r\n\r\n"; memset(&th_v, 0, sizeof(ThreadVars)); PACKET_RESET_CHECKSUMS(p1); p1->ip6h = (IPV6Hdr *)(valid_raw_ipv6 + 14); - p1->udph = (UDPHdr *) (valid_raw_ipv6 + 54); + p1->udph = (UDPHdr *)(valid_raw_ipv6 + 54); p1->src.family = AF_INET; p1->dst.family = AF_INET; p1->payload = buf; @@ -2806,7 +2821,7 @@ static int SigTest33NegativeUDPV6Keyword(void) PACKET_RESET_CHECKSUMS(p2); p2->ip6h = (IPV6Hdr *)(invalid_raw_ipv6 + 14); - p2->udph = (UDPHdr *) (invalid_raw_ipv6 + 54); + p2->udph = (UDPHdr *)(invalid_raw_ipv6 + 54); p2->src.family = AF_INET; p2->dst.family = AF_INET; p2->payload = buf; @@ -2820,27 +2835,25 @@ static int SigTest33NegativeUDPV6Keyword(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx, - "alert udp any any -> any any " - "(content:\"/one/\"; udpv6-csum:invalid; " - "msg:\"udpv6-csum keyword check(1)\"; sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert udp any any -> any any " + "(content:\"/one/\"; udpv6-csum:invalid; " + "msg:\"udpv6-csum keyword check(1)\"; sid:1;)"); if (de_ctx->sig_list == NULL) { result &= 0; goto end; } - de_ctx->sig_list->next = SigInit(de_ctx, - "alert udp any any -> any any " - "(content:\"/one/\"; udpv6-csum:valid; " - "msg:\"udpv6-csum keyword check(1)\"; " - "sid:2;)"); + de_ctx->sig_list->next = SigInit(de_ctx, "alert udp any any -> any any " + "(content:\"/one/\"; udpv6-csum:valid; " + "msg:\"udpv6-csum keyword check(1)\"; " + "sid:2;)"); if (de_ctx->sig_list->next == NULL) { result &= 0; goto end; } SigGroupBuild(de_ctx); - DetectEngineThreadCtxInit(&th_v, (void *)de_ctx,(void *)&det_ctx); + DetectEngineThreadCtxInit(&th_v, (void *)de_ctx, (void *)&det_ctx); SigMatchSignatures(&th_v, de_ctx, det_ctx, p1); if (PacketAlertCheck(p1, 1)) @@ -2910,7 +2923,7 @@ static int SigTest34ICMPV4Keyword(void) int result = 1; uint8_t *buf = (uint8_t *)"GET /one/ HTTP/1.0\r\n" - "\r\n\r\n"; + "\r\n\r\n"; uint16_t buflen = strlen((char *)buf); memset(&th_v, 0, sizeof(ThreadVars)); @@ -2918,7 +2931,7 @@ static int SigTest34ICMPV4Keyword(void) PACKET_RESET_CHECKSUMS(p1); p1->ip4h = (IPV4Hdr *)(valid_raw_ipv4); p1->ip4h->ip_verhl = 69; - p1->icmpv4h = (ICMPV4Hdr *) (valid_raw_ipv4 + IPV4_GET_RAW_HLEN(p1->ip4h) * 4); + p1->icmpv4h = (ICMPV4Hdr *)(valid_raw_ipv4 + IPV4_GET_RAW_HLEN(p1->ip4h) * 4); p1->src.family = AF_INET; p1->dst.family = AF_INET; p1->payload = buf; @@ -2928,7 +2941,7 @@ static int SigTest34ICMPV4Keyword(void) PACKET_RESET_CHECKSUMS(p2); p2->ip4h = (IPV4Hdr *)(invalid_raw_ipv4); p2->ip4h->ip_verhl = 69; - p2->icmpv4h = (ICMPV4Hdr *) (invalid_raw_ipv4 + IPV4_GET_RAW_HLEN(p2->ip4h) * 4); + p2->icmpv4h = (ICMPV4Hdr *)(invalid_raw_ipv4 + IPV4_GET_RAW_HLEN(p2->ip4h) * 4); p2->src.family = AF_INET; p2->dst.family = AF_INET; p2->payload = buf; @@ -2942,27 +2955,25 @@ static int SigTest34ICMPV4Keyword(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx, - "alert icmp any any -> any any " - "(content:\"/one/\"; icmpv4-csum:valid; " - "msg:\"icmpv4-csum keyword check(1)\"; sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert icmp any any -> any any " + "(content:\"/one/\"; icmpv4-csum:valid; " + "msg:\"icmpv4-csum keyword check(1)\"; sid:1;)"); if (de_ctx->sig_list == NULL) { result &= 0; goto end; } - de_ctx->sig_list->next = SigInit(de_ctx, - "alert icmp any any -> any any " - "(content:\"/one/\"; icmpv4-csum:invalid; " - "msg:\"icmpv4-csum keyword check(1)\"; " - "sid:2;)"); + de_ctx->sig_list->next = SigInit(de_ctx, "alert icmp any any -> any any " + "(content:\"/one/\"; icmpv4-csum:invalid; " + "msg:\"icmpv4-csum keyword check(1)\"; " + "sid:2;)"); if (de_ctx->sig_list->next == NULL) { result = 0; goto end; } SigGroupBuild(de_ctx); - DetectEngineThreadCtxInit(&th_v, (void *)de_ctx,(void *)&det_ctx); + DetectEngineThreadCtxInit(&th_v, (void *)de_ctx, (void *)&det_ctx); SigMatchSignatures(&th_v, de_ctx, det_ctx, p1); if (PacketAlertCheck(p1, 1)) @@ -3032,7 +3043,7 @@ static int SigTest35NegativeICMPV4Keyword(void) int result = 1; uint8_t *buf = (uint8_t *)"GET /one/ HTTP/1.0\r\n" - "\r\n\r\n"; + "\r\n\r\n"; uint16_t buflen = strlen((char *)buf); memset(&th_v, 0, sizeof(ThreadVars)); @@ -3040,7 +3051,7 @@ static int SigTest35NegativeICMPV4Keyword(void) PACKET_RESET_CHECKSUMS(p1); p1->ip4h = (IPV4Hdr *)(valid_raw_ipv4); p1->ip4h->ip_verhl = 69; - p1->icmpv4h = (ICMPV4Hdr *) (valid_raw_ipv4 + IPV4_GET_RAW_HLEN(p1->ip4h) * 4); + p1->icmpv4h = (ICMPV4Hdr *)(valid_raw_ipv4 + IPV4_GET_RAW_HLEN(p1->ip4h) * 4); p1->src.family = AF_INET; p1->dst.family = AF_INET; p1->payload = buf; @@ -3050,7 +3061,7 @@ static int SigTest35NegativeICMPV4Keyword(void) PACKET_RESET_CHECKSUMS(p2); p2->ip4h = (IPV4Hdr *)(invalid_raw_ipv4); p2->ip4h->ip_verhl = 69; - p2->icmpv4h = (ICMPV4Hdr *) (invalid_raw_ipv4 + IPV4_GET_RAW_HLEN(p2->ip4h) * 4); + p2->icmpv4h = (ICMPV4Hdr *)(invalid_raw_ipv4 + IPV4_GET_RAW_HLEN(p2->ip4h) * 4); p2->src.family = AF_INET; p2->dst.family = AF_INET; p2->payload = buf; @@ -3064,27 +3075,25 @@ static int SigTest35NegativeICMPV4Keyword(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx, - "alert icmp any any -> any any " - "(content:\"/one/\"; icmpv4-csum:invalid; " - "msg:\"icmpv4-csum keyword check(1)\"; sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert icmp any any -> any any " + "(content:\"/one/\"; icmpv4-csum:invalid; " + "msg:\"icmpv4-csum keyword check(1)\"; sid:1;)"); if (de_ctx->sig_list == NULL) { result &= 0; goto end; } - de_ctx->sig_list->next = SigInit(de_ctx, - "alert icmp any any -> any any " - "(content:\"/one/\"; icmpv4-csum:valid; " - "msg:\"icmpv4-csum keyword check(1)\"; " - "sid:2;)"); + de_ctx->sig_list->next = SigInit(de_ctx, "alert icmp any any -> any any " + "(content:\"/one/\"; icmpv4-csum:valid; " + "msg:\"icmpv4-csum keyword check(1)\"; " + "sid:2;)"); if (de_ctx->sig_list->next == NULL) { result &= 0; goto end; } SigGroupBuild(de_ctx); - DetectEngineThreadCtxInit(&th_v, (void *)de_ctx,(void *)&det_ctx); + DetectEngineThreadCtxInit(&th_v, (void *)de_ctx, (void *)&det_ctx); SigMatchSignatures(&th_v, de_ctx, det_ctx, p1); if (PacketAlertCheck(p1, 1)) @@ -3197,20 +3206,18 @@ static int SigTest38(void) } de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx, - "alert tcp any any -> any any " - "(content:\"LEN1|20|\"; " - "byte_test:4,=,8,0; " - "msg:\"byte_test keyword check(1)\"; sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " + "(content:\"LEN1|20|\"; " + "byte_test:4,=,8,0; " + "msg:\"byte_test keyword check(1)\"; sid:1;)"); if (de_ctx->sig_list == NULL) { result &= 0; goto end; } - de_ctx->sig_list->next = SigInit(de_ctx, - "alert tcp any any -> any any " - "(content:\"LEN1|20|\"; " - "byte_test:4,=,8,5,relative,string,dec; " - "msg:\"byte_test keyword check(2)\"; sid:2;)"); + de_ctx->sig_list->next = SigInit(de_ctx, "alert tcp any any -> any any " + "(content:\"LEN1|20|\"; " + "byte_test:4,=,8,5,relative,string,dec; " + "msg:\"byte_test keyword check(2)\"; sid:2;)"); if (de_ctx->sig_list->next == NULL) { result &= 0; goto end; @@ -3353,43 +3360,44 @@ static int SigTest39(void) * \brief expecting to match a size */ -static int SigTest36ContentAndIsdataatKeywords01 (void) +static int SigTest36ContentAndIsdataatKeywords01(void) { int result = 0; // Build and decode the packet - uint8_t raw_eth [] = { - 0x00,0x25,0x00,0x9e,0xfa,0xfe,0x00,0x02,0xcf,0x74,0xfe,0xe1,0x08,0x00,0x45,0x00 - ,0x01,0xcc,0xcb,0x91,0x00,0x00,0x34,0x06,0xdf,0xa8,0xd1,0x55,0xe3,0x67,0xc0,0xa8 - ,0x64,0x8c,0x00,0x50,0xc0,0xb7,0xd1,0x11,0xed,0x63,0x81,0xa9,0x9a,0x05,0x80,0x18 - ,0x00,0x75,0x0a,0xdd,0x00,0x00,0x01,0x01,0x08,0x0a,0x09,0x8a,0x06,0xd0,0x12,0x21 - ,0x2a,0x3b,0x48,0x54,0x54,0x50,0x2f,0x31,0x2e,0x31,0x20,0x33,0x30,0x32,0x20,0x46 - ,0x6f,0x75,0x6e,0x64,0x0d,0x0a,0x4c,0x6f,0x63,0x61,0x74,0x69,0x6f,0x6e,0x3a,0x20 - ,0x68,0x74,0x74,0x70,0x3a,0x2f,0x2f,0x77,0x77,0x77,0x2e,0x67,0x6f,0x6f,0x67,0x6c - ,0x65,0x2e,0x65,0x73,0x2f,0x0d,0x0a,0x43,0x61,0x63,0x68,0x65,0x2d,0x43,0x6f,0x6e - ,0x74,0x72,0x6f,0x6c,0x3a,0x20,0x70,0x72,0x69,0x76,0x61,0x74,0x65,0x0d,0x0a,0x43 - ,0x6f,0x6e,0x74,0x65,0x6e,0x74,0x2d,0x54,0x79,0x70,0x65,0x3a,0x20,0x74,0x65,0x78 - ,0x74,0x2f,0x68,0x74,0x6d,0x6c,0x3b,0x20,0x63,0x68,0x61,0x72,0x73,0x65,0x74,0x3d - ,0x55,0x54,0x46,0x2d,0x38,0x0d,0x0a,0x44,0x61,0x74,0x65,0x3a,0x20,0x4d,0x6f,0x6e - ,0x2c,0x20,0x31,0x34,0x20,0x53,0x65,0x70,0x20,0x32,0x30,0x30,0x39,0x20,0x30,0x38 - ,0x3a,0x34,0x38,0x3a,0x33,0x31,0x20,0x47,0x4d,0x54,0x0d,0x0a,0x53,0x65,0x72,0x76 - ,0x65,0x72,0x3a,0x20,0x67,0x77,0x73,0x0d,0x0a,0x43,0x6f,0x6e,0x74,0x65,0x6e,0x74 - ,0x2d,0x4c,0x65,0x6e,0x67,0x74,0x68,0x3a,0x20,0x32,0x31,0x38,0x0d,0x0a,0x0d,0x0a - ,0x3c,0x48,0x54,0x4d,0x4c,0x3e,0x3c,0x48,0x45,0x41,0x44,0x3e,0x3c,0x6d,0x65,0x74 - ,0x61,0x20,0x68,0x74,0x74,0x70,0x2d,0x65,0x71,0x75,0x69,0x76,0x3d,0x22,0x63,0x6f - ,0x6e,0x74,0x65,0x6e,0x74,0x2d,0x74,0x79,0x70,0x65,0x22,0x20,0x63,0x6f,0x6e,0x74 - ,0x65,0x6e,0x74,0x3d,0x22,0x74,0x65,0x78,0x74,0x2f,0x68,0x74,0x6d,0x6c,0x3b,0x63 - ,0x68,0x61,0x72,0x73,0x65,0x74,0x3d,0x75,0x74,0x66,0x2d,0x38,0x22,0x3e,0x0a,0x3c - ,0x54,0x49,0x54,0x4c,0x45,0x3e,0x33,0x30,0x32,0x20,0x4d,0x6f,0x76,0x65,0x64,0x3c - ,0x2f,0x54,0x49,0x54,0x4c,0x45,0x3e,0x3c,0x2f,0x48,0x45,0x41,0x44,0x3e,0x3c,0x42 - ,0x4f,0x44,0x59,0x3e,0x0a,0x3c,0x48,0x31,0x3e,0x33,0x30,0x32,0x20,0x4d,0x6f,0x76 - ,0x65,0x64,0x3c,0x2f,0x48,0x31,0x3e,0x0a,0x54,0x68,0x65,0x20,0x64,0x6f,0x63,0x75 - ,0x6d,0x65,0x6e,0x74,0x20,0x68,0x61,0x73,0x20,0x6d,0x6f,0x76,0x65,0x64,0x0a,0x3c - ,0x41,0x20,0x48,0x52,0x45,0x46,0x3d,0x22,0x68,0x74,0x74,0x70,0x3a,0x2f,0x2f,0x77 - ,0x77,0x77,0x2e,0x67,0x6f,0x6f,0x67,0x6c,0x65,0x2e,0x65,0x73,0x2f,0x22,0x3e,0x68 - ,0x65,0x72,0x65,0x3c,0x2f,0x41,0x3e,0x2e,0x0d,0x0a,0x3c,0x2f,0x42,0x4f,0x44,0x59 - ,0x3e,0x3c,0x2f,0x48,0x54,0x4d,0x4c,0x3e,0x0d,0x0a }; + uint8_t raw_eth[] = { 0x00, 0x25, 0x00, 0x9e, 0xfa, 0xfe, 0x00, 0x02, 0xcf, 0x74, 0xfe, 0xe1, + 0x08, 0x00, 0x45, 0x00, 0x01, 0xcc, 0xcb, 0x91, 0x00, 0x00, 0x34, 0x06, 0xdf, 0xa8, 0xd1, + 0x55, 0xe3, 0x67, 0xc0, 0xa8, 0x64, 0x8c, 0x00, 0x50, 0xc0, 0xb7, 0xd1, 0x11, 0xed, 0x63, + 0x81, 0xa9, 0x9a, 0x05, 0x80, 0x18, 0x00, 0x75, 0x0a, 0xdd, 0x00, 0x00, 0x01, 0x01, 0x08, + 0x0a, 0x09, 0x8a, 0x06, 0xd0, 0x12, 0x21, 0x2a, 0x3b, 0x48, 0x54, 0x54, 0x50, 0x2f, 0x31, + 0x2e, 0x31, 0x20, 0x33, 0x30, 0x32, 0x20, 0x46, 0x6f, 0x75, 0x6e, 0x64, 0x0d, 0x0a, 0x4c, + 0x6f, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x3a, 0x20, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, + 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x65, 0x73, 0x2f, + 0x0d, 0x0a, 0x43, 0x61, 0x63, 0x68, 0x65, 0x2d, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, + 0x3a, 0x20, 0x70, 0x72, 0x69, 0x76, 0x61, 0x74, 0x65, 0x0d, 0x0a, 0x43, 0x6f, 0x6e, 0x74, + 0x65, 0x6e, 0x74, 0x2d, 0x54, 0x79, 0x70, 0x65, 0x3a, 0x20, 0x74, 0x65, 0x78, 0x74, 0x2f, + 0x68, 0x74, 0x6d, 0x6c, 0x3b, 0x20, 0x63, 0x68, 0x61, 0x72, 0x73, 0x65, 0x74, 0x3d, 0x55, + 0x54, 0x46, 0x2d, 0x38, 0x0d, 0x0a, 0x44, 0x61, 0x74, 0x65, 0x3a, 0x20, 0x4d, 0x6f, 0x6e, + 0x2c, 0x20, 0x31, 0x34, 0x20, 0x53, 0x65, 0x70, 0x20, 0x32, 0x30, 0x30, 0x39, 0x20, 0x30, + 0x38, 0x3a, 0x34, 0x38, 0x3a, 0x33, 0x31, 0x20, 0x47, 0x4d, 0x54, 0x0d, 0x0a, 0x53, 0x65, + 0x72, 0x76, 0x65, 0x72, 0x3a, 0x20, 0x67, 0x77, 0x73, 0x0d, 0x0a, 0x43, 0x6f, 0x6e, 0x74, + 0x65, 0x6e, 0x74, 0x2d, 0x4c, 0x65, 0x6e, 0x67, 0x74, 0x68, 0x3a, 0x20, 0x32, 0x31, 0x38, + 0x0d, 0x0a, 0x0d, 0x0a, 0x3c, 0x48, 0x54, 0x4d, 0x4c, 0x3e, 0x3c, 0x48, 0x45, 0x41, 0x44, + 0x3e, 0x3c, 0x6d, 0x65, 0x74, 0x61, 0x20, 0x68, 0x74, 0x74, 0x70, 0x2d, 0x65, 0x71, 0x75, + 0x69, 0x76, 0x3d, 0x22, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2d, 0x74, 0x79, 0x70, + 0x65, 0x22, 0x20, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x3d, 0x22, 0x74, 0x65, 0x78, + 0x74, 0x2f, 0x68, 0x74, 0x6d, 0x6c, 0x3b, 0x63, 0x68, 0x61, 0x72, 0x73, 0x65, 0x74, 0x3d, + 0x75, 0x74, 0x66, 0x2d, 0x38, 0x22, 0x3e, 0x0a, 0x3c, 0x54, 0x49, 0x54, 0x4c, 0x45, 0x3e, + 0x33, 0x30, 0x32, 0x20, 0x4d, 0x6f, 0x76, 0x65, 0x64, 0x3c, 0x2f, 0x54, 0x49, 0x54, 0x4c, + 0x45, 0x3e, 0x3c, 0x2f, 0x48, 0x45, 0x41, 0x44, 0x3e, 0x3c, 0x42, 0x4f, 0x44, 0x59, 0x3e, + 0x0a, 0x3c, 0x48, 0x31, 0x3e, 0x33, 0x30, 0x32, 0x20, 0x4d, 0x6f, 0x76, 0x65, 0x64, 0x3c, + 0x2f, 0x48, 0x31, 0x3e, 0x0a, 0x54, 0x68, 0x65, 0x20, 0x64, 0x6f, 0x63, 0x75, 0x6d, 0x65, + 0x6e, 0x74, 0x20, 0x68, 0x61, 0x73, 0x20, 0x6d, 0x6f, 0x76, 0x65, 0x64, 0x0a, 0x3c, 0x41, + 0x20, 0x48, 0x52, 0x45, 0x46, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x77, + 0x77, 0x77, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x65, 0x73, 0x2f, 0x22, 0x3e, + 0x68, 0x65, 0x72, 0x65, 0x3c, 0x2f, 0x41, 0x3e, 0x2e, 0x0d, 0x0a, 0x3c, 0x2f, 0x42, 0x4f, + 0x44, 0x59, 0x3e, 0x3c, 0x2f, 0x48, 0x54, 0x4d, 0x4c, 0x3e, 0x0d, 0x0a }; Packet *p = PacketGetFromAlloc(); if (unlikely(p == NULL)) @@ -3405,7 +3413,6 @@ static int SigTest36ContentAndIsdataatKeywords01 (void) FlowInitConfig(FLOW_QUIET); DecodeEthernet(&th_v, &dtv, p, raw_eth, sizeof(raw_eth)); - DetectEngineCtx *de_ctx = DetectEngineCtxInit(); if (de_ctx == NULL) { goto end; @@ -3413,7 +3420,9 @@ static int SigTest36ContentAndIsdataatKeywords01 (void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert tcp any any -> any any (msg:\"SigTest36ContentAndIsdataatKeywords01 \"; content:\"HTTP\"; isdataat:404, relative; sid:101;)"); + de_ctx->sig_list = SigInit( + de_ctx, "alert tcp any any -> any any (msg:\"SigTest36ContentAndIsdataatKeywords01 \"; " + "content:\"HTTP\"; isdataat:404, relative; sid:101;)"); if (de_ctx->sig_list == NULL) { result = 0; goto end; @@ -3427,7 +3436,7 @@ static int SigTest36ContentAndIsdataatKeywords01 (void) result = 0; goto end; } else { - result=1; + result = 1; } SigGroupCleanup(de_ctx); @@ -3442,19 +3451,18 @@ static int SigTest36ContentAndIsdataatKeywords01 (void) return result; end: - if(de_ctx) - { + if (de_ctx) { SigGroupCleanup(de_ctx); SigCleanSignatures(de_ctx); } - if(det_ctx) + if (det_ctx) DetectEngineThreadCtxDeinit(&th_v, (void *)det_ctx); - //PatternMatchDestroy(mpm_ctx); + // PatternMatchDestroy(mpm_ctx); - if(de_ctx) - DetectEngineCtxFree(de_ctx); + if (de_ctx) + DetectEngineCtxFree(de_ctx); if (p != NULL) PacketRecycle(p); @@ -3465,49 +3473,49 @@ static int SigTest36ContentAndIsdataatKeywords01 (void) return result; } - /** * \test SigTest37ContentAndIsdataatKeywords02 is a test to check window with constructed packets, * \brief not expecting to match a size */ -static int SigTest37ContentAndIsdataatKeywords02 (void) +static int SigTest37ContentAndIsdataatKeywords02(void) { int result = 0; // Build and decode the packet - uint8_t raw_eth [] = { - 0x00,0x25,0x00,0x9e,0xfa,0xfe,0x00,0x02,0xcf,0x74,0xfe,0xe1,0x08,0x00,0x45,0x00 - ,0x01,0xcc,0xcb,0x91,0x00,0x00,0x34,0x06,0xdf,0xa8,0xd1,0x55,0xe3,0x67,0xc0,0xa8 - ,0x64,0x8c,0x00,0x50,0xc0,0xb7,0xd1,0x11,0xed,0x63,0x81,0xa9,0x9a,0x05,0x80,0x18 - ,0x00,0x75,0x0a,0xdd,0x00,0x00,0x01,0x01,0x08,0x0a,0x09,0x8a,0x06,0xd0,0x12,0x21 - ,0x2a,0x3b,0x48,0x54,0x54,0x50,0x2f,0x31,0x2e,0x31,0x20,0x33,0x30,0x32,0x20,0x46 - ,0x6f,0x75,0x6e,0x64,0x0d,0x0a,0x4c,0x6f,0x63,0x61,0x74,0x69,0x6f,0x6e,0x3a,0x20 - ,0x68,0x74,0x74,0x70,0x3a,0x2f,0x2f,0x77,0x77,0x77,0x2e,0x67,0x6f,0x6f,0x67,0x6c - ,0x65,0x2e,0x65,0x73,0x2f,0x0d,0x0a,0x43,0x61,0x63,0x68,0x65,0x2d,0x43,0x6f,0x6e - ,0x74,0x72,0x6f,0x6c,0x3a,0x20,0x70,0x72,0x69,0x76,0x61,0x74,0x65,0x0d,0x0a,0x43 - ,0x6f,0x6e,0x74,0x65,0x6e,0x74,0x2d,0x54,0x79,0x70,0x65,0x3a,0x20,0x74,0x65,0x78 - ,0x74,0x2f,0x68,0x74,0x6d,0x6c,0x3b,0x20,0x63,0x68,0x61,0x72,0x73,0x65,0x74,0x3d - ,0x55,0x54,0x46,0x2d,0x38,0x0d,0x0a,0x44,0x61,0x74,0x65,0x3a,0x20,0x4d,0x6f,0x6e - ,0x2c,0x20,0x31,0x34,0x20,0x53,0x65,0x70,0x20,0x32,0x30,0x30,0x39,0x20,0x30,0x38 - ,0x3a,0x34,0x38,0x3a,0x33,0x31,0x20,0x47,0x4d,0x54,0x0d,0x0a,0x53,0x65,0x72,0x76 - ,0x65,0x72,0x3a,0x20,0x67,0x77,0x73,0x0d,0x0a,0x43,0x6f,0x6e,0x74,0x65,0x6e,0x74 - ,0x2d,0x4c,0x65,0x6e,0x67,0x74,0x68,0x3a,0x20,0x32,0x31,0x38,0x0d,0x0a,0x0d,0x0a - ,0x3c,0x48,0x54,0x4d,0x4c,0x3e,0x3c,0x48,0x45,0x41,0x44,0x3e,0x3c,0x6d,0x65,0x74 - ,0x61,0x20,0x68,0x74,0x74,0x70,0x2d,0x65,0x71,0x75,0x69,0x76,0x3d,0x22,0x63,0x6f - ,0x6e,0x74,0x65,0x6e,0x74,0x2d,0x74,0x79,0x70,0x65,0x22,0x20,0x63,0x6f,0x6e,0x74 - ,0x65,0x6e,0x74,0x3d,0x22,0x74,0x65,0x78,0x74,0x2f,0x68,0x74,0x6d,0x6c,0x3b,0x63 - ,0x68,0x61,0x72,0x73,0x65,0x74,0x3d,0x75,0x74,0x66,0x2d,0x38,0x22,0x3e,0x0a,0x3c - ,0x54,0x49,0x54,0x4c,0x45,0x3e,0x33,0x30,0x32,0x20,0x4d,0x6f,0x76,0x65,0x64,0x3c - ,0x2f,0x54,0x49,0x54,0x4c,0x45,0x3e,0x3c,0x2f,0x48,0x45,0x41,0x44,0x3e,0x3c,0x42 - ,0x4f,0x44,0x59,0x3e,0x0a,0x3c,0x48,0x31,0x3e,0x33,0x30,0x32,0x20,0x4d,0x6f,0x76 - ,0x65,0x64,0x3c,0x2f,0x48,0x31,0x3e,0x0a,0x54,0x68,0x65,0x20,0x64,0x6f,0x63,0x75 - ,0x6d,0x65,0x6e,0x74,0x20,0x68,0x61,0x73,0x20,0x6d,0x6f,0x76,0x65,0x64,0x0a,0x3c - ,0x41,0x20,0x48,0x52,0x45,0x46,0x3d,0x22,0x68,0x74,0x74,0x70,0x3a,0x2f,0x2f,0x77 - ,0x77,0x77,0x2e,0x67,0x6f,0x6f,0x67,0x6c,0x65,0x2e,0x65,0x73,0x2f,0x22,0x3e,0x68 - ,0x65,0x72,0x65,0x3c,0x2f,0x41,0x3e,0x2e,0x0d,0x0a,0x3c,0x2f,0x42,0x4f,0x44,0x59 - ,0x3e,0x3c,0x2f,0x48,0x54,0x4d,0x4c,0x3e,0x0d,0x0a }; + uint8_t raw_eth[] = { 0x00, 0x25, 0x00, 0x9e, 0xfa, 0xfe, 0x00, 0x02, 0xcf, 0x74, 0xfe, 0xe1, + 0x08, 0x00, 0x45, 0x00, 0x01, 0xcc, 0xcb, 0x91, 0x00, 0x00, 0x34, 0x06, 0xdf, 0xa8, 0xd1, + 0x55, 0xe3, 0x67, 0xc0, 0xa8, 0x64, 0x8c, 0x00, 0x50, 0xc0, 0xb7, 0xd1, 0x11, 0xed, 0x63, + 0x81, 0xa9, 0x9a, 0x05, 0x80, 0x18, 0x00, 0x75, 0x0a, 0xdd, 0x00, 0x00, 0x01, 0x01, 0x08, + 0x0a, 0x09, 0x8a, 0x06, 0xd0, 0x12, 0x21, 0x2a, 0x3b, 0x48, 0x54, 0x54, 0x50, 0x2f, 0x31, + 0x2e, 0x31, 0x20, 0x33, 0x30, 0x32, 0x20, 0x46, 0x6f, 0x75, 0x6e, 0x64, 0x0d, 0x0a, 0x4c, + 0x6f, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x3a, 0x20, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, + 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x65, 0x73, 0x2f, + 0x0d, 0x0a, 0x43, 0x61, 0x63, 0x68, 0x65, 0x2d, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x6f, 0x6c, + 0x3a, 0x20, 0x70, 0x72, 0x69, 0x76, 0x61, 0x74, 0x65, 0x0d, 0x0a, 0x43, 0x6f, 0x6e, 0x74, + 0x65, 0x6e, 0x74, 0x2d, 0x54, 0x79, 0x70, 0x65, 0x3a, 0x20, 0x74, 0x65, 0x78, 0x74, 0x2f, + 0x68, 0x74, 0x6d, 0x6c, 0x3b, 0x20, 0x63, 0x68, 0x61, 0x72, 0x73, 0x65, 0x74, 0x3d, 0x55, + 0x54, 0x46, 0x2d, 0x38, 0x0d, 0x0a, 0x44, 0x61, 0x74, 0x65, 0x3a, 0x20, 0x4d, 0x6f, 0x6e, + 0x2c, 0x20, 0x31, 0x34, 0x20, 0x53, 0x65, 0x70, 0x20, 0x32, 0x30, 0x30, 0x39, 0x20, 0x30, + 0x38, 0x3a, 0x34, 0x38, 0x3a, 0x33, 0x31, 0x20, 0x47, 0x4d, 0x54, 0x0d, 0x0a, 0x53, 0x65, + 0x72, 0x76, 0x65, 0x72, 0x3a, 0x20, 0x67, 0x77, 0x73, 0x0d, 0x0a, 0x43, 0x6f, 0x6e, 0x74, + 0x65, 0x6e, 0x74, 0x2d, 0x4c, 0x65, 0x6e, 0x67, 0x74, 0x68, 0x3a, 0x20, 0x32, 0x31, 0x38, + 0x0d, 0x0a, 0x0d, 0x0a, 0x3c, 0x48, 0x54, 0x4d, 0x4c, 0x3e, 0x3c, 0x48, 0x45, 0x41, 0x44, + 0x3e, 0x3c, 0x6d, 0x65, 0x74, 0x61, 0x20, 0x68, 0x74, 0x74, 0x70, 0x2d, 0x65, 0x71, 0x75, + 0x69, 0x76, 0x3d, 0x22, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2d, 0x74, 0x79, 0x70, + 0x65, 0x22, 0x20, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x3d, 0x22, 0x74, 0x65, 0x78, + 0x74, 0x2f, 0x68, 0x74, 0x6d, 0x6c, 0x3b, 0x63, 0x68, 0x61, 0x72, 0x73, 0x65, 0x74, 0x3d, + 0x75, 0x74, 0x66, 0x2d, 0x38, 0x22, 0x3e, 0x0a, 0x3c, 0x54, 0x49, 0x54, 0x4c, 0x45, 0x3e, + 0x33, 0x30, 0x32, 0x20, 0x4d, 0x6f, 0x76, 0x65, 0x64, 0x3c, 0x2f, 0x54, 0x49, 0x54, 0x4c, + 0x45, 0x3e, 0x3c, 0x2f, 0x48, 0x45, 0x41, 0x44, 0x3e, 0x3c, 0x42, 0x4f, 0x44, 0x59, 0x3e, + 0x0a, 0x3c, 0x48, 0x31, 0x3e, 0x33, 0x30, 0x32, 0x20, 0x4d, 0x6f, 0x76, 0x65, 0x64, 0x3c, + 0x2f, 0x48, 0x31, 0x3e, 0x0a, 0x54, 0x68, 0x65, 0x20, 0x64, 0x6f, 0x63, 0x75, 0x6d, 0x65, + 0x6e, 0x74, 0x20, 0x68, 0x61, 0x73, 0x20, 0x6d, 0x6f, 0x76, 0x65, 0x64, 0x0a, 0x3c, 0x41, + 0x20, 0x48, 0x52, 0x45, 0x46, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x77, + 0x77, 0x77, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x65, 0x73, 0x2f, 0x22, 0x3e, + 0x68, 0x65, 0x72, 0x65, 0x3c, 0x2f, 0x41, 0x3e, 0x2e, 0x0d, 0x0a, 0x3c, 0x2f, 0x42, 0x4f, + 0x44, 0x59, 0x3e, 0x3c, 0x2f, 0x48, 0x54, 0x4d, 0x4c, 0x3e, 0x0d, 0x0a }; Packet *p = PacketGetFromAlloc(); if (unlikely(p == NULL)) @@ -3523,7 +3531,6 @@ static int SigTest37ContentAndIsdataatKeywords02 (void) FlowInitConfig(FLOW_QUIET); DecodeEthernet(&th_v, &dtv, p, raw_eth, sizeof(raw_eth)); - DetectEngineCtx *de_ctx = DetectEngineCtxInit(); if (de_ctx == NULL) { goto end; @@ -3531,7 +3538,9 @@ static int SigTest37ContentAndIsdataatKeywords02 (void) de_ctx->flags |= DE_QUIET; - Signature *s = de_ctx->sig_list = SigInit(de_ctx,"alert tcp any any -> any any (msg:\"SigTest37ContentAndIsdataatKeywords01 \"; content:\"HTTP\"; isdataat:500, relative; sid:101;)"); + Signature *s = de_ctx->sig_list = SigInit( + de_ctx, "alert tcp any any -> any any (msg:\"SigTest37ContentAndIsdataatKeywords01 \"; " + "content:\"HTTP\"; isdataat:500, relative; sid:101;)"); if (de_ctx->sig_list == NULL) { printf("sig parse failed: "); result = 0; @@ -3551,7 +3560,7 @@ static int SigTest37ContentAndIsdataatKeywords02 (void) goto end; } else { printf("sig matched, but should not have: "); - result=0; + result = 0; } SigGroupCleanup(de_ctx); @@ -3567,16 +3576,15 @@ static int SigTest37ContentAndIsdataatKeywords02 (void) return result; end: - if(de_ctx) - { + if (de_ctx) { SigGroupCleanup(de_ctx); SigCleanSignatures(de_ctx); } - if(det_ctx) + if (det_ctx) DetectEngineThreadCtxDeinit(&th_v, (void *)det_ctx); - if(de_ctx) + if (de_ctx) DetectEngineCtxFree(de_ctx); if (p != NULL) @@ -3596,13 +3604,12 @@ static int SigTest37ContentAndIsdataatKeywords02 (void) static int SigTest40NoPacketInspection01(void) { - uint8_t *buf = (uint8_t *) - "220 (vsFTPd 2.0.5)\r\n"; + uint8_t *buf = (uint8_t *)"220 (vsFTPd 2.0.5)\r\n"; uint16_t buflen = strlen((char *)buf); Packet *p = PacketGetFromAlloc(); TCPHdr tcphdr; if (unlikely(p == NULL)) - return 0; + return 0; ThreadVars th_v; DetectEngineThreadCtx *det_ctx = NULL; PacketQueue pq; @@ -3637,14 +3644,15 @@ static int SigTest40NoPacketInspection01(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert tcp any any -> 1.2.3.4 any (msg:\"No Packet Inspection Test\"; flow:to_server; sid:2; rev:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> 1.2.3.4 any (msg:\"No Packet " + "Inspection Test\"; flow:to_server; sid:2; rev:1;)"); if (de_ctx->sig_list == NULL) { result = 0; goto end; } SigGroupBuild(de_ctx); - DetectEngineThreadCtxInit(&th_v, (void *)de_ctx,(void *)&det_ctx); + DetectEngineThreadCtxInit(&th_v, (void *)de_ctx, (void *)&det_ctx); det_ctx->de_ctx = de_ctx; Detect(&th_v, p, det_ctx); @@ -3656,7 +3664,7 @@ static int SigTest40NoPacketInspection01(void) SigGroupCleanup(de_ctx); SigCleanSignatures(de_ctx); DetectEngineThreadCtxDeinit(&th_v, (void *)det_ctx); - //PatternMatchDestroy(mpm_ctx); + // PatternMatchDestroy(mpm_ctx); DetectEngineCtxFree(de_ctx); end: SCFree(p); @@ -3671,8 +3679,7 @@ static int SigTest40NoPacketInspection01(void) static int SigTest40NoPayloadInspection02(void) { - uint8_t *buf = (uint8_t *) - "220 (vsFTPd 2.0.5)\r\n"; + uint8_t *buf = (uint8_t *)"220 (vsFTPd 2.0.5)\r\n"; uint16_t buflen = strlen((char *)buf); ThreadVars th_v; memset(&th_v, 0, sizeof(th_v)); @@ -3692,8 +3699,8 @@ static int SigTest40NoPayloadInspection02(void) FAIL_IF_NULL(de_ctx); de_ctx->flags |= DE_QUIET; - Signature *s = DetectEngineAppendSig(de_ctx, - "alert tcp any any -> any any (msg:\"No Payload TEST\"; content:\"220 (vsFTPd 2.0.5)\"; sid:1;)"); + Signature *s = DetectEngineAppendSig(de_ctx, "alert tcp any any -> any any (msg:\"No Payload " + "TEST\"; content:\"220 (vsFTPd 2.0.5)\"; sid:1;)"); FAIL_IF_NULL(s); SigGroupBuild(de_ctx); @@ -3709,15 +3716,14 @@ static int SigTest40NoPayloadInspection02(void) PASS; } -static int SigTestMemory01 (void) +static int SigTestMemory01(void) { - uint8_t *buf = (uint8_t *) - "GET /one/ HTTP/1.1\r\n" - "Host: one.example.org\r\n" - "\r\n\r\n" - "GET /two/ HTTP/1.1\r\n" - "Host: two.example.org\r\n" - "\r\n\r\n"; + uint8_t *buf = (uint8_t *)"GET /one/ HTTP/1.1\r\n" + "Host: one.example.org\r\n" + "\r\n\r\n" + "GET /two/ HTTP/1.1\r\n" + "Host: two.example.org\r\n" + "\r\n\r\n"; uint16_t buflen = strlen((char *)buf); Packet *p = PacketGetFromAlloc(); if (unlikely(p == NULL)) @@ -3740,7 +3746,9 @@ static int SigTestMemory01 (void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert tcp any any -> any any (msg:\"HTTP URI cap\"; content:\"GET \"; depth:4; pcre:\"/GET (?P.*) HTTP\\/\\d\\.\\d\\r\\n/G\"; sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, + "alert tcp any any -> any any (msg:\"HTTP URI cap\"; content:\"GET \"; depth:4; " + "pcre:\"/GET (?P.*) HTTP\\/\\d\\.\\d\\r\\n/G\"; sid:1;)"); if (de_ctx->sig_list == NULL) { result = 0; goto end; @@ -3759,7 +3767,7 @@ static int SigTestMemory01 (void) return result; } -static int SigTestMemory02 (void) +static int SigTestMemory02(void) { ThreadVars th_v; int result = 0; @@ -3772,12 +3780,16 @@ static int SigTestMemory02 (void) } de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert tcp any any -> any 456 (msg:\"HTTP URI cap\"; content:\"GET \"; depth:4; pcre:\"/GET (?P.*) HTTP\\/\\d\\.\\d\\r\\n/G\"; sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, + "alert tcp any any -> any 456 (msg:\"HTTP URI cap\"; content:\"GET \"; depth:4; " + "pcre:\"/GET (?P.*) HTTP\\/\\d\\.\\d\\r\\n/G\"; sid:1;)"); if (de_ctx->sig_list == NULL) { result = 0; goto end; } - de_ctx->sig_list->next = SigInit(de_ctx,"alert tcp any any -> any 1:1000 (msg:\"HTTP URI cap\"; content:\"GET \"; depth:4; pcre:\"/GET (?P.*) HTTP\\/\\d\\.\\d\\r\\n/G\"; sid:2;)"); + de_ctx->sig_list->next = SigInit(de_ctx, + "alert tcp any any -> any 1:1000 (msg:\"HTTP URI cap\"; content:\"GET \"; depth:4; " + "pcre:\"/GET (?P.*) HTTP\\/\\d\\.\\d\\r\\n/G\"; sid:2;)"); if (de_ctx->sig_list->next == NULL) { result = 0; goto end; @@ -3793,7 +3805,7 @@ static int SigTestMemory02 (void) return result; } -static int SigTestMemory03 (void) +static int SigTestMemory03(void) { ThreadVars th_v; int result = 0; @@ -3806,17 +3818,23 @@ static int SigTestMemory03 (void) } de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert tcp any any -> 1.2.3.4 456 (msg:\"HTTP URI cap\"; content:\"GET \"; depth:4; pcre:\"/GET (?P.*) HTTP\\/\\d\\.\\d\\r\\n/G\"; sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, + "alert tcp any any -> 1.2.3.4 456 (msg:\"HTTP URI cap\"; content:\"GET \"; depth:4; " + "pcre:\"/GET (?P.*) HTTP\\/\\d\\.\\d\\r\\n/G\"; sid:1;)"); if (de_ctx->sig_list == NULL) { result = 0; goto end; } - de_ctx->sig_list->next = SigInit(de_ctx,"alert tcp any any -> 1.2.3.3-1.2.3.6 1:1000 (msg:\"HTTP URI cap\"; content:\"GET \"; depth:4; pcre:\"/GET (?P.*) HTTP\\/\\d\\.\\d\\r\\n/G\"; sid:2;)"); + de_ctx->sig_list->next = SigInit(de_ctx, + "alert tcp any any -> 1.2.3.3-1.2.3.6 1:1000 (msg:\"HTTP URI cap\"; content:\"GET \"; " + "depth:4; pcre:\"/GET (?P.*) HTTP\\/\\d\\.\\d\\r\\n/G\"; sid:2;)"); if (de_ctx->sig_list->next == NULL) { result = 0; goto end; } - de_ctx->sig_list->next->next = SigInit(de_ctx,"alert tcp any any -> !1.2.3.5 1:990 (msg:\"HTTP URI cap\"; content:\"GET \"; depth:4; pcre:\"/GET (?P.*) HTTP\\/\\d\\.\\d\\r\\n/G\"; sid:3;)"); + de_ctx->sig_list->next->next = SigInit(de_ctx, + "alert tcp any any -> !1.2.3.5 1:990 (msg:\"HTTP URI cap\"; content:\"GET \"; depth:4; " + "pcre:\"/GET (?P.*) HTTP\\/\\d\\.\\d\\r\\n/G\"; sid:3;)"); if (de_ctx->sig_list->next->next == NULL) { result = 0; goto end; @@ -3832,7 +3850,7 @@ static int SigTestMemory03 (void) return result; } -static int SigTestContent01 (void) +static int SigTestContent01(void) { uint8_t *buf = (uint8_t *)"01234567890123456789012345678901"; uint16_t buflen = strlen((char *)buf); @@ -3851,7 +3869,8 @@ static int SigTestContent01 (void) } de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert tcp any any -> any any (msg:\"Test 32\"; content:\"01234567890123456789012345678901\"; sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any (msg:\"Test 32\"; " + "content:\"01234567890123456789012345678901\"; sid:1;)"); if (de_ctx->sig_list == NULL) { result = 0; goto end; @@ -3876,7 +3895,7 @@ static int SigTestContent01 (void) return result; } -static int SigTestContent02 (void) +static int SigTestContent02(void) { uint8_t *buf = (uint8_t *)"01234567890123456789012345678901"; uint16_t buflen = strlen((char *)buf); @@ -3894,13 +3913,16 @@ static int SigTestContent02 (void) } de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert tcp any any -> any any (msg:\"Test 32\"; content:\"01234567890123456789012345678901\"; sid:1;)"); + de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any (msg:\"Test 32\"; " + "content:\"01234567890123456789012345678901\"; sid:1;)"); if (de_ctx->sig_list == NULL) { result = 0; goto end; } - de_ctx->sig_list->next = SigInit(de_ctx,"alert tcp any any -> any any (msg:\"Test 31\"; content:\"0123456789012345678901234567890\"; sid:2;)"); + de_ctx->sig_list->next = + SigInit(de_ctx, "alert tcp any any -> any any (msg:\"Test 31\"; " + "content:\"0123456789012345678901234567890\"; sid:2;)"); if (de_ctx->sig_list->next == NULL) { result = 0; goto end; @@ -3915,8 +3937,7 @@ static int SigTestContent02 (void) result = 1; } else printf("sig 2 didn't match: "); - } - else + } else printf("sig 1 didn't match: "); SigGroupCleanup(de_ctx); @@ -3929,9 +3950,10 @@ static int SigTestContent02 (void) return result; } -static int SigTestContent03 (void) +static int SigTestContent03(void) { - uint8_t *buf = (uint8_t *)"01234567890123456789012345678901abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; + uint8_t *buf = (uint8_t *)"01234567890123456789012345678901abcdefghijklmnopqrstuvwxyzABCDEFGHIJ" + "KLMNOPQRSTUVWXYZ"; uint16_t buflen = strlen((char *)buf); ThreadVars th_v; DetectEngineThreadCtx *det_ctx = NULL; @@ -3948,7 +3970,10 @@ static int SigTestContent03 (void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert tcp any any -> any any (msg:\"Test 32\"; content:\"01234567890123456789012345678901\"; content:\"abcdefghijklmnopqrstuvwxyzABCDEF\"; distance:0; sid:1;)"); + de_ctx->sig_list = + SigInit(de_ctx, "alert tcp any any -> any any (msg:\"Test 32\"; " + "content:\"01234567890123456789012345678901\"; " + "content:\"abcdefghijklmnopqrstuvwxyzABCDEF\"; distance:0; sid:1;)"); if (de_ctx->sig_list == NULL) { result = 0; goto end; @@ -3973,9 +3998,10 @@ static int SigTestContent03 (void) return result; } -static int SigTestContent04 (void) +static int SigTestContent04(void) { - uint8_t *buf = (uint8_t *)"01234567890123456789012345678901abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; + uint8_t *buf = (uint8_t *)"01234567890123456789012345678901abcdefghijklmnopqrstuvwxyzABCDEFGHIJ" + "KLMNOPQRSTUVWXYZ"; uint16_t buflen = strlen((char *)buf); ThreadVars th_v; DetectEngineThreadCtx *det_ctx = NULL; @@ -3993,7 +4019,10 @@ static int SigTestContent04 (void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert tcp any any -> any any (msg:\"Test 32\"; content:\"01234567890123456789012345678901\"; content:\"abcdefghijklmnopqrstuvwxyzABCDEF\"; distance:0; within:32; sid:1;)"); + de_ctx->sig_list = SigInit( + de_ctx, "alert tcp any any -> any any (msg:\"Test 32\"; " + "content:\"01234567890123456789012345678901\"; " + "content:\"abcdefghijklmnopqrstuvwxyzABCDEF\"; distance:0; within:32; sid:1;)"); if (de_ctx->sig_list == NULL) { result = 0; goto end; @@ -4019,9 +4048,10 @@ static int SigTestContent04 (void) } /** \test sigs with patterns at the limit of the pm's size limit */ -static int SigTestContent05 (void) +static int SigTestContent05(void) { - uint8_t *buf = (uint8_t *)"01234567890123456789012345678901PADabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; + uint8_t *buf = (uint8_t *)"01234567890123456789012345678901PADabcdefghijklmnopqrstuvwxyzABCDEFG" + "HIJKLMNOPQRSTUVWXYZ"; uint16_t buflen = strlen((char *)buf); ThreadVars th_v; DetectEngineThreadCtx *det_ctx = NULL; @@ -4039,12 +4069,18 @@ static int SigTestContent05 (void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert tcp any any -> any any (msg:\"Test 32\"; content:\"01234567890123456789012345678901\"; content:\"abcdefghijklmnopqrstuvwxyzABCDEF\"; distance:0; within:32; sid:1;)"); + de_ctx->sig_list = SigInit( + de_ctx, "alert tcp any any -> any any (msg:\"Test 32\"; " + "content:\"01234567890123456789012345678901\"; " + "content:\"abcdefghijklmnopqrstuvwxyzABCDEF\"; distance:0; within:32; sid:1;)"); if (de_ctx->sig_list == NULL) { printf("sig1 parse failed: "); goto end; } - de_ctx->sig_list->next = SigInit(de_ctx,"alert tcp any any -> any any (msg:\"Test 32\"; content:\"01234567890123456789012345678901\"; content:\"abcdefghijklmnopqrstuvwxyzABCDEF\"; distance:1; within:32; sid:2;)"); + de_ctx->sig_list->next = SigInit( + de_ctx, "alert tcp any any -> any any (msg:\"Test 32\"; " + "content:\"01234567890123456789012345678901\"; " + "content:\"abcdefghijklmnopqrstuvwxyzABCDEF\"; distance:1; within:32; sid:2;)"); if (de_ctx->sig_list->next == NULL) { printf("sig2 parse failed: "); goto end; @@ -4080,9 +4116,10 @@ static int SigTestContent05 (void) return result; } -static int SigTestContent06 (void) +static int SigTestContent06(void) { - uint8_t *buf = (uint8_t *)"01234567890123456789012345678901abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; + uint8_t *buf = (uint8_t *)"01234567890123456789012345678901abcdefghijklmnopqrstuvwxyzABCDEFGHIJ" + "KLMNOPQRSTUVWXYZ"; uint16_t buflen = strlen((char *)buf); ThreadVars th_v; DetectEngineThreadCtx *det_ctx = NULL; @@ -4099,12 +4136,17 @@ static int SigTestContent06 (void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx,"alert ip any any -> any any (msg:\"Test 32 sig1\"; content:\"01234567890123456789012345678901\"; content:\"abcdefghijklmnopqrstuvwxyzABCDEF\"; distance:0; within:32; sid:1;)"); + de_ctx->sig_list = SigInit( + de_ctx, "alert ip any any -> any any (msg:\"Test 32 sig1\"; " + "content:\"01234567890123456789012345678901\"; " + "content:\"abcdefghijklmnopqrstuvwxyzABCDEF\"; distance:0; within:32; sid:1;)"); if (de_ctx->sig_list == NULL) { result = 0; goto end; } - de_ctx->sig_list->next = SigInit(de_ctx,"alert ip any any -> any any (msg:\"Test 32 sig2\"; content:\"01234567890123456789012345678901\"; content:\"abcdefg\"; sid:2;)"); + de_ctx->sig_list->next = SigInit( + de_ctx, "alert ip any any -> any any (msg:\"Test 32 sig2\"; " + "content:\"01234567890123456789012345678901\"; content:\"abcdefg\"; sid:2;)"); if (de_ctx->sig_list->next == NULL) { result = 0; goto end; @@ -4114,16 +4156,16 @@ static int SigTestContent06 (void) DetectEngineThreadCtxInit(&th_v, (void *)de_ctx, (void *)&det_ctx); SigMatchSignatures(&th_v, de_ctx, det_ctx, p); - if (PacketAlertCheck(p, 1)){ - //printf("sig 1 matched :"); - }else{ + if (PacketAlertCheck(p, 1)) { + // printf("sig 1 matched :"); + } else { printf("sig 1 didn't match: "); goto end; } - if (PacketAlertCheck(p, 2)){ + if (PacketAlertCheck(p, 2)) { result = 1; - }else{ + } else { printf("sig 2 didn't match: "); goto end; } @@ -4138,7 +4180,7 @@ static int SigTestContent06 (void) return result; } -static int SigTestWithin01 (void) +static int SigTestWithin01(void) { DecodeThreadVars dtv; ThreadVars th_v; diff --git a/src/tests/fuzz/fuzz_applayerparserparse.c b/src/tests/fuzz/fuzz_applayerparserparse.c index 4cea6a82636f..8745e1d3847c 100644 --- a/src/tests/fuzz/fuzz_applayerparserparse.c +++ b/src/tests/fuzz/fuzz_applayerparserparse.c @@ -73,17 +73,17 @@ int LLVMFuzzerInitialize(int *argc, char ***argv) int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { - Flow * f; + Flow *f; TcpSession ssn; - const uint8_t * albuffer; - uint8_t * alnext; + const uint8_t *albuffer; + uint8_t *alnext; size_t alsize; // used to find under and overflows // otherwise overflows do not fail as they read the next packet - uint8_t * isolatedBuffer; + uint8_t *isolatedBuffer; if (alp_tctx == NULL) { - //Redirects logs to /dev/null + // Redirects logs to /dev/null setenv("SC_LOG_OP_IFACE", "file", 0); setenv("SC_LOG_FILE", "/dev/null", 0); @@ -91,7 +91,7 @@ int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) run_mode = RUNMODE_PCAP_FILE; GlobalsInitPreConfig(); - //redirect logs to /tmp + // redirect logs to /tmp ConfigSetLogDirectory("/tmp/"); // disables checksums validation for fuzzing if (ConfYamlLoadString(configNoChecksum, strlen(configNoChecksum)) != 0) { @@ -110,7 +110,7 @@ int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) if (data[0] >= ALPROTO_MAX) { return 0; } - //no UTHBuildFlow to have storage + // no UTHBuildFlow to have storage f = FlowAlloc(); if (f == NULL) { return 0; @@ -160,7 +160,8 @@ int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) goto bail; } memcpy(isolatedBuffer, albuffer, alnext - albuffer); - (void) AppLayerParserParse(NULL, alp_tctx, f, f->alproto, flags, isolatedBuffer, alnext - albuffer); + (void)AppLayerParserParse( + NULL, alp_tctx, f, f->alproto, flags, isolatedBuffer, alnext - albuffer); free(isolatedBuffer); if (FlowChangeProto(f)) { // exits if a protocol change is requested @@ -169,11 +170,12 @@ int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) } flags &= ~(STREAM_START); if (f->alparser && - (((flags & STREAM_TOSERVER) != 0 && - AppLayerParserStateIssetFlag(f->alparser, APP_LAYER_PARSER_EOF_TS)) || - ((flags & STREAM_TOCLIENT) != 0 && - AppLayerParserStateIssetFlag(f->alparser, APP_LAYER_PARSER_EOF_TC)))) { - //no final chunk + (((flags & STREAM_TOSERVER) != 0 && + AppLayerParserStateIssetFlag(f->alparser, APP_LAYER_PARSER_EOF_TS)) || + ((flags & STREAM_TOCLIENT) != 0 && + AppLayerParserStateIssetFlag( + f->alparser, APP_LAYER_PARSER_EOF_TC)))) { + // no final chunk alsize = 0; break; } @@ -187,7 +189,7 @@ int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) } alnext = memmem(albuffer, alsize, separator, 4); } - if (alsize > 0 ) { + if (alsize > 0) { if (flip) { flags |= STREAM_TOCLIENT; flags &= ~(STREAM_TOSERVER); @@ -203,7 +205,7 @@ int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) goto bail; } memcpy(isolatedBuffer, albuffer, alsize); - (void) AppLayerParserParse(NULL, alp_tctx, f, f->alproto, flags, isolatedBuffer, alsize); + (void)AppLayerParserParse(NULL, alp_tctx, f, f->alproto, flags, isolatedBuffer, alsize); free(isolatedBuffer); } diff --git a/src/tests/fuzz/fuzz_applayerprotodetectgetproto.c b/src/tests/fuzz/fuzz_applayerprotodetectgetproto.c index 598e7cc03ff6..35ed96d2af75 100644 --- a/src/tests/fuzz/fuzz_applayerprotodetectgetproto.c +++ b/src/tests/fuzz/fuzz_applayerprotodetectgetproto.c @@ -4,7 +4,6 @@ * fuzz target for AppLayerProtoDetectGetProto */ - #include "suricata-common.h" #include "suricata.h" #include "app-layer-detect-proto.h" @@ -15,7 +14,7 @@ #define HEADER_LEN 6 -//rule of thumb constant, so as not to timeout target +// rule of thumb constant, so as not to timeout target #define PROTO_DETECT_MAX_LEN 1024 #include "confyaml.c" @@ -34,7 +33,7 @@ int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) AppProto alproto2; if (alpd_tctx == NULL) { - //global init + // global init InitGlobal(); run_mode = RUNMODE_UNITTEST; if (ConfYamlLoadString(configNoChecksum, strlen(configNoChecksum)) != 0) { @@ -76,7 +75,7 @@ int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) * we find the same protocol or ALPROTO_UNKNOWN. * Otherwise, we have evasion with TCP splitting */ - for (size_t i = 0; i < size-HEADER_LEN && i < PROTO_DETECT_MAX_LEN; i++) { + for (size_t i = 0; i < size - HEADER_LEN && i < PROTO_DETECT_MAX_LEN; i++) { // reset detection at each try cf probing_parser_toserver_alproto_masks AppLayerProtoDetectReset(f); alproto2 = AppLayerProtoDetectGetProto( diff --git a/src/tests/fuzz/fuzz_confyamlloadstring.c b/src/tests/fuzz/fuzz_confyamlloadstring.c index f5f9ed39831e..edc29406c072 100644 --- a/src/tests/fuzz/fuzz_confyamlloadstring.c +++ b/src/tests/fuzz/fuzz_confyamlloadstring.c @@ -4,7 +4,6 @@ * fuzz target for ConfYamlLoadString */ - #include "suricata-common.h" #include "suricata.h" #include "conf-yaml-loader.h" @@ -16,16 +15,16 @@ static int initialized = 0; int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { if (initialized == 0) { - //Redirects logs to /dev/null + // Redirects logs to /dev/null setenv("SC_LOG_OP_IFACE", "file", 0); setenv("SC_LOG_FILE", "/dev/null", 0); - //global init + // global init InitGlobal(); run_mode = RUNMODE_UNITTEST; initialized = 1; } - ConfYamlLoadString((const char *) data, size); + ConfYamlLoadString((const char *)data, size); return 0; } diff --git a/src/tests/fuzz/fuzz_decodepcapfile.c b/src/tests/fuzz/fuzz_decodepcapfile.c index cf508697f05b..6b3e16c7c5d5 100644 --- a/src/tests/fuzz/fuzz_decodepcapfile.c +++ b/src/tests/fuzz/fuzz_decodepcapfile.c @@ -38,16 +38,16 @@ int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) void *ptv = NULL; if (initialized == 0) { - //Redirects logs to /dev/null + // Redirects logs to /dev/null setenv("SC_LOG_OP_IFACE", "file", 0); setenv("SC_LOG_FILE", "/dev/null", 0); InitGlobal(); run_mode = RUNMODE_PCAP_FILE; - //redirect logs to /tmp + // redirect logs to /tmp ConfigSetLogDirectory("/tmp/"); - //disables checksums validation for fuzzing + // disables checksums validation for fuzzing if (ConfYamlLoadString(configNoChecksum, strlen(configNoChecksum)) != 0) { abort(); } @@ -58,10 +58,8 @@ int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) TimeModeSetOffline(); PcapFileGlobalInit(); - tv = TmThreadCreatePacketHandler("fuzz", - "packetpool", "packetpool", - "packetpool", "packetpool", - "pktacqloop"); + tv = TmThreadCreatePacketHandler( + "fuzz", "packetpool", "packetpool", "packetpool", "packetpool", "pktacqloop"); if (tv == NULL) { return 0; } @@ -75,7 +73,7 @@ int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) return 0; } TmSlotSetFuncAppend(tv, tm_module, NULL); - tmm_modules[TMM_DECODEPCAPFILE].ThreadInit(tv, NULL, (void **) &dtv); + tmm_modules[TMM_DECODEPCAPFILE].ThreadInit(tv, NULL, (void **)&dtv); (void)SC_ATOMIC_SET(tv->tm_slots->slot_next->slot_data, dtv); extern uint16_t max_pending_packets; @@ -86,12 +84,13 @@ int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) initialized = 1; } - //rewrite buffer to a file as libpcap does not have buffer inputs + // rewrite buffer to a file as libpcap does not have buffer inputs if (TestHelperBufferToFile("/tmp/fuzz.pcap", data, size) < 0) { return 0; } - if (tmm_modules[TMM_RECEIVEPCAPFILE].ThreadInit(tv, "/tmp/fuzz.pcap", &ptv) == TM_ECODE_OK && ptv != NULL) { + if (tmm_modules[TMM_RECEIVEPCAPFILE].ThreadInit(tv, "/tmp/fuzz.pcap", &ptv) == TM_ECODE_OK && + ptv != NULL) { suricata_ctl_flags = 0; tmm_modules[TMM_RECEIVEPCAPFILE].PktAcqLoop(tv, ptv, tv->tm_slots); tmm_modules[TMM_RECEIVEPCAPFILE].ThreadDeinit(tv, ptv); diff --git a/src/tests/fuzz/fuzz_mimedecparseline.c b/src/tests/fuzz/fuzz_mimedecparseline.c index 432ce7de9523..65f40dc1d50c 100644 --- a/src/tests/fuzz/fuzz_mimedecparseline.c +++ b/src/tests/fuzz/fuzz_mimedecparseline.c @@ -4,7 +4,6 @@ * fuzz target for ConfYamlLoadString */ - #include "suricata-common.h" #include "suricata.h" #include "util-decode-mime.h" @@ -14,10 +13,9 @@ int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size); static int initialized = 0; static int dummy = 0; -static int MimeParserDataFromFileCB(const uint8_t *chunk, uint32_t len, - MimeDecParseState *state) +static int MimeParserDataFromFileCB(const uint8_t *chunk, uint32_t len, MimeDecParseState *state) { - if (len > 0 && chunk[len-1] == 0) { + if (len > 0 && chunk[len - 1] == 0) { // do not get optimized away dummy++; } @@ -27,10 +25,10 @@ static int MimeParserDataFromFileCB(const uint8_t *chunk, uint32_t len, int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { if (initialized == 0) { - //Redirects logs to /dev/null + // Redirects logs to /dev/null setenv("SC_LOG_OP_IFACE", "file", 0); setenv("SC_LOG_FILE", "/dev/null", 0); - //global init + // global init InitGlobal(); run_mode = RUNMODE_UNITTEST; initialized = 1; @@ -40,15 +38,15 @@ int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) MimeDecParseState *state = MimeDecInitParser(&line_count, MimeParserDataFromFileCB); MimeDecEntity *msg_head = state->msg; - const uint8_t * buffer = data; + const uint8_t *buffer = data; while (1) { - uint8_t * next = memchr(buffer, '\n', size); + uint8_t *next = memchr(buffer, '\n', size); if (next == NULL) { if (state->state_flag >= BODY_STARTED) (void)MimeDecParseLine(buffer, size, 0, state); break; } else { - (void) MimeDecParseLine(buffer, next - buffer, 1, state); + (void)MimeDecParseLine(buffer, next - buffer, 1, state); if (buffer + size < next + 1) { break; } diff --git a/src/tests/fuzz/fuzz_siginit.c b/src/tests/fuzz/fuzz_siginit.c index 80514b2d9a52..21d2d2c0db38 100644 --- a/src/tests/fuzz/fuzz_siginit.c +++ b/src/tests/fuzz/fuzz_siginit.c @@ -4,7 +4,6 @@ * fuzz target for SigInit */ - #include "suricata-common.h" #include "util-reference-config.h" #include "util-classification-config.h" @@ -21,7 +20,7 @@ int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) if (de_ctx == NULL) { setenv("SC_LOG_OP_IFACE", "file", 0); setenv("SC_LOG_FILE", "/dev/null", 0); - //global init + // global init InitGlobal(); run_mode = RUNMODE_UNITTEST; MpmTableSetup(); @@ -41,10 +40,10 @@ int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) de_ctx->rule_file = (char *)"fuzzer"; } - char * buffer = malloc(size+1); + char *buffer = malloc(size + 1); if (buffer) { memcpy(buffer, data, size); - //null terminate string + // null terminate string buffer[size] = 0; Signature *s = SigInit(de_ctx, buffer); free(buffer); diff --git a/src/tests/fuzz/fuzz_sigpcap.c b/src/tests/fuzz/fuzz_sigpcap.c index e5bd56deb476..8a4619842192 100644 --- a/src/tests/fuzz/fuzz_sigpcap.c +++ b/src/tests/fuzz/fuzz_sigpcap.c @@ -33,11 +33,10 @@ int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size); - static int initialized = 0; ThreadVars tv; DecodeThreadVars *dtv; -//FlowWorkerThreadData +// FlowWorkerThreadData void *fwd; SCInstance surifuzz; SC_ATOMIC_EXTERN(unsigned int, engine_stage); @@ -46,7 +45,7 @@ SC_ATOMIC_EXTERN(unsigned int, engine_stage); int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { - pcap_t * pkts; + pcap_t *pkts; char errbuf[PCAP_ERRBUF_SIZE]; const u_char *pkt; struct pcap_pkthdr *header; @@ -56,7 +55,7 @@ int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) size_t pcap_cnt = 0; if (initialized == 0) { - //Redirects logs to /dev/null + // Redirects logs to /dev/null setenv("SC_LOG_OP_IFACE", "file", 0); setenv("SC_LOG_FILE", "/dev/null", 0); @@ -64,9 +63,9 @@ int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) GlobalsInitPreConfig(); run_mode = RUNMODE_PCAP_FILE; - //redirect logs to /tmp + // redirect logs to /tmp ConfigSetLogDirectory("/tmp/"); - //disables checksums validation for fuzzing + // disables checksums validation for fuzzing if (ConfYamlLoadString(configNoChecksum, strlen(configNoChecksum)) != 0) { abort(); } @@ -74,7 +73,7 @@ int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) remove("/tmp/fuzz.rules"); surifuzz.sig_file = strdup("/tmp/fuzz.rules"); surifuzz.sig_file_exclusive = 1; - //loads rules after init + // loads rules after init surifuzz.delayed_detect = 1; PostConfLoadedSetup(&surifuzz); @@ -113,14 +112,14 @@ int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) data += pos; size -= pos;*/ - for (pos=0; pos < size; pos++) { + for (pos = 0; pos < size; pos++) { if (data[pos] == 0) { break; } } if (pos > 0 && pos < size) { // dump signatures to a file so as to reuse SigLoadSignatures - if (TestHelperBufferToFile(surifuzz.sig_file, data, pos-1) < 0) { + if (TestHelperBufferToFile(surifuzz.sig_file, data, pos - 1) < 0) { return 0; } } else { @@ -142,24 +141,24 @@ int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) DetectEngineThreadCtxDeinit(NULL, old_det_ctx); if (pos < size) { - //skip zero + // skip zero pos++; } data += pos; size -= pos; - //rewrite buffer to a file as libpcap does not have buffer inputs + // rewrite buffer to a file as libpcap does not have buffer inputs if (TestHelperBufferToFile("/tmp/fuzz.pcap", data, size) < 0) { return 0; } - //initialize structure + // initialize structure pkts = pcap_open_offline("/tmp/fuzz.pcap", errbuf); if (pkts == NULL) { return 0; } - //loop over packets + // loop over packets r = pcap_next_ex(pkts, &header, &pkt); p = PacketGetFromAlloc(); if (r <= 0 || header->ts.tv_sec >= INT_MAX - 3600 || header->ts.tv_usec < 0) { @@ -199,7 +198,7 @@ int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) p->pcap_cnt = pcap_cnt; } bail: - //close structure + // close structure pcap_close(pkts); PacketFree(p); FlowReset(); diff --git a/src/tests/fuzz/onefile.c b/src/tests/fuzz/onefile.c index 344ef8ef6aad..a9c7b7448422 100644 --- a/src/tests/fuzz/onefile.c +++ b/src/tests/fuzz/onefile.c @@ -16,7 +16,7 @@ static int runOneFile(const char *fname) return 2; } size = ftell(fp); - if (size == (size_t) -1) { + if (size == (size_t)-1) { fclose(fp); return 2; } diff --git a/src/tests/reputation.c b/src/tests/reputation.c index 8b72a8a6b675..585092007808 100644 --- a/src/tests/reputation.c +++ b/src/tests/reputation.c @@ -28,12 +28,12 @@ #include "stream-tcp.h" #include "util-unittest-helper.h" -#define TEST_INIT \ - DetectEngineCtx *de_ctx = DetectEngineCtxInit(); \ - FAIL_IF(de_ctx == NULL); \ - SRepInit(de_ctx); \ - \ - Address a; \ +#define TEST_INIT \ + DetectEngineCtx *de_ctx = DetectEngineCtxInit(); \ + FAIL_IF(de_ctx == NULL); \ + SRepInit(de_ctx); \ + \ + Address a; \ uint8_t cat = 0, value = 0; #define TEST_INIT_WITH_PACKET_IPV6(src, dst) \ @@ -43,19 +43,18 @@ FAIL_IF(p == NULL); \ TEST_INIT -#define TEST_INIT_WITH_PACKET(ip) \ - uint8_t *buf = (uint8_t *)"Hi all!"; \ - uint16_t buflen = strlen((char *)buf); \ - Packet *p = UTHBuildPacket((uint8_t *)buf, buflen, IPPROTO_TCP); \ - FAIL_IF(p == NULL); \ - p->src.addr_data32[0] = UTHSetIPv4Address(ip); \ +#define TEST_INIT_WITH_PACKET(ip) \ + uint8_t *buf = (uint8_t *)"Hi all!"; \ + uint16_t buflen = strlen((char *)buf); \ + Packet *p = UTHBuildPacket((uint8_t *)buf, buflen, IPPROTO_TCP); \ + FAIL_IF(p == NULL); \ + p->src.addr_data32[0] = UTHSetIPv4Address(ip); \ TEST_INIT -#define TEST_CLEANUP \ - DetectEngineCtxFree(de_ctx); +#define TEST_CLEANUP DetectEngineCtxFree(de_ctx); -#define TEST_CLEANUP_WITH_PACKET \ - UTHFreePacket(p); \ +#define TEST_CLEANUP_WITH_PACKET \ + UTHFreePacket(p); \ TEST_CLEANUP static int SRepTest01(void) @@ -140,7 +139,8 @@ static int SRepTest06(void) PASS; } -static int SRepTest07(void) { +static int SRepTest07(void) +{ TEST_INIT; char str[] = "2000:0000:0000:0000:0000:0000:0000:0001,"; diff --git a/src/tests/source-pcap.c b/src/tests/source-pcap.c index fc1b275e3fb9..560a955170ad 100644 --- a/src/tests/source-pcap.c +++ b/src/tests/source-pcap.c @@ -41,9 +41,8 @@ static int UpdatePcapStatsValue64NoChange01(void) * No change in counter values. * Last count is within first 32bit range, i.e. same as pcap_stat range. */ - TestData data[] = {{.last = 0, .current = 0}, - {.last = 12345, .current = 12345}, - {.last = (uint64_t)UINT32_MAX, .current = UINT_MAX}}; + TestData data[] = { { .last = 0, .current = 0 }, { .last = 12345, .current = 12345 }, + { .last = (uint64_t)UINT32_MAX, .current = UINT_MAX } }; for (size_t i = 0; i < ARRAY_SIZE(data); ++i) { FAIL_IF_NOT(data[i].last == data[i].current); @@ -61,10 +60,10 @@ static int UpdatePcapStatsValue64NoChange02(void) * No change in counter values. * Last count is outside 32bits range. */ - TestData data[] = {{.last = (2ull << 32) + 0, .current = 0}, - {.last = (3ull << 32) + 12345, .current = 12345}, - {.last = (3ull << 32) + (uint64_t)UINT32_MAX, .current = UINT_MAX}, - {.last = UINT64_MAX, .current = UINT_MAX}}; + TestData data[] = { { .last = (2ull << 32) + 0, .current = 0 }, + { .last = (3ull << 32) + 12345, .current = 12345 }, + { .last = (3ull << 32) + (uint64_t)UINT32_MAX, .current = UINT_MAX }, + { .last = UINT64_MAX, .current = UINT_MAX } }; for (size_t i = 0; i < ARRAY_SIZE(data); ++i) { uint32_t upper = Upper32(data[i].last); @@ -85,9 +84,8 @@ static int UpdatePcapStatsValue64NoOverflow01(void) * Last count is within first 32bit range, i.e. same as pcap_stat range. * Also test edges and simple +1. */ - TestData data[] = {{.last = 0, .current = 1}, - {.last = 12345, .current = 34567}, - {.last = (uint64_t)UINT32_MAX - 1, .current = UINT_MAX}}; + TestData data[] = { { .last = 0, .current = 1 }, { .last = 12345, .current = 34567 }, + { .last = (uint64_t)UINT32_MAX - 1, .current = UINT_MAX } }; for (size_t i = 0; i < ARRAY_SIZE(data); ++i) { FAIL_IF_NOT(data[i].last < data[i].current); @@ -105,9 +103,9 @@ static int UpdatePcapStatsValue64NoOverflow02(void) * Non-overflowing counter value is simply taken over in lower 32bits. * Last count is outside 32bits range. */ - TestData data[] = {{.last = (2ull << 32) + 0, .current = 1}, - {.last = (3ull << 32) + 12345, .current = 34567}, - {.last = UINT64_MAX - 1, .current = UINT_MAX}}; + TestData data[] = { { .last = (2ull << 32) + 0, .current = 1 }, + { .last = (3ull << 32) + 12345, .current = 34567 }, + { .last = UINT64_MAX - 1, .current = UINT_MAX } }; for (size_t i = 0; i < ARRAY_SIZE(data); ++i) { uint32_t upper = Upper32(data[i].last); @@ -127,9 +125,9 @@ static int UpdatePcapStatsValue64Overflow01(void) * Overflowing counter value is simply taken over in lower 32bits. * Last count is within first 32bit range, i.e. same as pcap_stat range. */ - TestData data[] = {{.last = 1, .current = 0}, - {.last = 12345, .current = 22}, {.last = 12345, .current = 12344}, - {.last = (uint64_t)UINT32_MAX, .current = UINT_MAX - 1}}; + TestData data[] = { { .last = 1, .current = 0 }, { .last = 12345, .current = 22 }, + { .last = 12345, .current = 12344 }, + { .last = (uint64_t)UINT32_MAX, .current = UINT_MAX - 1 } }; for (size_t i = 0; i < ARRAY_SIZE(data); ++i) { FAIL_IF_NOT(data[i].last > data[i].current); @@ -148,10 +146,10 @@ static int UpdatePcapStatsValue64Overflow02(void) * Overflowing counter value is simply taken over in lower 32bits. * Last count is outside 32bits range. */ - TestData data[] = {{.last = (2ull << 32) + 1, .current = 0}, - {.last = (3ull << 32) + 12345, .current = 22}, - {.last = (3ull << 32) + 12345, .current = 12344}, - {.last = UINT64_MAX, .current = UINT_MAX - 1}}; + TestData data[] = { { .last = (2ull << 32) + 1, .current = 0 }, + { .last = (3ull << 32) + 12345, .current = 22 }, + { .last = (3ull << 32) + 12345, .current = 12344 }, + { .last = UINT64_MAX, .current = UINT_MAX - 1 } }; for (size_t i = 0; i < ARRAY_SIZE(data); ++i) { uint32_t upper = Upper32(data[i].last); @@ -171,8 +169,8 @@ static int UpdatePcapStatsValue64Overflow03(void) * Overflowing counter value is simply taken over in lower 32bits. * Edge cases where upper32 bit wrap around to 0. */ - TestData data[] = {{.last = UINT64_MAX, .current = 0}, - {.last = UINT64_MAX, .current = 3333}}; + TestData data[] = { { .last = UINT64_MAX, .current = 0 }, + { .last = UINT64_MAX, .current = 3333 } }; for (size_t i = 0; i < ARRAY_SIZE(data); ++i) { FAIL_IF_NOT(Lower32(data[i].last) > data[i].current); @@ -193,9 +191,8 @@ static int UpdatePcapStats64Assorted01(void) * Full testing of value behaviour is done in UpdatePcapStatsValue64...() * tests. */ - PcapStats64 last = {.ps_recv = 0, .ps_drop = 1234, .ps_ifdrop = 8765}; - struct pcap_stat current = { - .ps_recv = 12, .ps_drop = 2345, .ps_ifdrop = 9876}; + PcapStats64 last = { .ps_recv = 0, .ps_drop = 1234, .ps_ifdrop = 8765 }; + struct pcap_stat current = { .ps_recv = 12, .ps_drop = 2345, .ps_ifdrop = 9876 }; // test setup sanity check FAIL_IF_NOT(last.ps_recv < current.ps_recv); @@ -213,20 +210,13 @@ static int UpdatePcapStats64Assorted01(void) static void SourcePcapRegisterStatsTests(void) { - UtRegisterTest("UpdatePcapStatsValue64NoChange01", - UpdatePcapStatsValue64NoChange01); - UtRegisterTest("UpdatePcapStatsValue64NoChange02", - UpdatePcapStatsValue64NoChange02); - UtRegisterTest("UpdatePcapStatsValue64NoOverflow01", - UpdatePcapStatsValue64NoOverflow01); - UtRegisterTest("UpdatePcapStatsValue64NoOverflow02", - UpdatePcapStatsValue64NoOverflow02); - UtRegisterTest("UpdatePcapStatsValue64Overflow01", - UpdatePcapStatsValue64Overflow01); - UtRegisterTest("UpdatePcapStatsValue64Overflow02", - UpdatePcapStatsValue64Overflow02); - UtRegisterTest("UpdatePcapStatsValue64Overflow03", - UpdatePcapStatsValue64Overflow03); + UtRegisterTest("UpdatePcapStatsValue64NoChange01", UpdatePcapStatsValue64NoChange01); + UtRegisterTest("UpdatePcapStatsValue64NoChange02", UpdatePcapStatsValue64NoChange02); + UtRegisterTest("UpdatePcapStatsValue64NoOverflow01", UpdatePcapStatsValue64NoOverflow01); + UtRegisterTest("UpdatePcapStatsValue64NoOverflow02", UpdatePcapStatsValue64NoOverflow02); + UtRegisterTest("UpdatePcapStatsValue64Overflow01", UpdatePcapStatsValue64Overflow01); + UtRegisterTest("UpdatePcapStatsValue64Overflow02", UpdatePcapStatsValue64Overflow02); + UtRegisterTest("UpdatePcapStatsValue64Overflow03", UpdatePcapStatsValue64Overflow03); UtRegisterTest("UpdatePcapStats64Assorted01", UpdatePcapStats64Assorted01); } diff --git a/src/tests/stream-tcp-inline.c b/src/tests/stream-tcp-inline.c index 410451a833d0..69dbe19f52e5 100644 --- a/src/tests/stream-tcp-inline.c +++ b/src/tests/stream-tcp-inline.c @@ -28,9 +28,7 @@ static int VALIDATE(TcpStream *stream, uint8_t *data, uint32_t data_len) { - if (StreamingBufferCompareRawData(&stream->sb, - data, data_len) == 0) - { + if (StreamingBufferCompareRawData(&stream->sb, data, data_len) == 0) { SCReturnInt(0); } SCLogInfo("OK"); @@ -38,25 +36,25 @@ static int VALIDATE(TcpStream *stream, uint8_t *data, uint32_t data_len) return 1; } -#define INLINE_START(isn) \ - Packet *p; \ - TcpReassemblyThreadCtx *ra_ctx = NULL; \ - TcpSession ssn; \ - ThreadVars tv; \ - memset(&tv, 0, sizeof(tv)); \ - \ - StreamTcpUTInit(&ra_ctx); \ - StreamTcpUTInitInline(); \ - \ - StreamTcpUTSetupSession(&ssn); \ - StreamTcpUTSetupStream(&ssn.server, (isn)); \ - StreamTcpUTSetupStream(&ssn.client, (isn)); \ - \ +#define INLINE_START(isn) \ + Packet *p; \ + TcpReassemblyThreadCtx *ra_ctx = NULL; \ + TcpSession ssn; \ + ThreadVars tv; \ + memset(&tv, 0, sizeof(tv)); \ + \ + StreamTcpUTInit(&ra_ctx); \ + StreamTcpUTInitInline(); \ + \ + StreamTcpUTSetupSession(&ssn); \ + StreamTcpUTSetupStream(&ssn.server, (isn)); \ + StreamTcpUTSetupStream(&ssn.client, (isn)); \ + \ TcpStream *stream = &ssn.client; -#define INLINE_END \ - StreamTcpUTClearSession(&ssn); \ - StreamTcpUTDeinit(ra_ctx); \ +#define INLINE_END \ + StreamTcpUTClearSession(&ssn); \ + StreamTcpUTDeinit(ra_ctx); \ PASS #define INLINE_ADD_PAYLOAD(rseq, seg, seglen, packet, packetlen) \ diff --git a/src/tests/stream-tcp-list.c b/src/tests/stream-tcp-list.c index d10c756bd9c6..733ad0a97706 100644 --- a/src/tests/stream-tcp-list.c +++ b/src/tests/stream-tcp-list.c @@ -37,28 +37,29 @@ static int VALIDATE(TcpStream *stream, uint8_t *data, uint32_t data_len) return 1; } -#define OVERLAP_START(isn, policy) \ - TcpReassemblyThreadCtx *ra_ctx = NULL; \ - TcpSession ssn; \ - ThreadVars tv; \ - memset(&tv, 0, sizeof(tv)); \ - \ - StreamTcpUTInit(&ra_ctx); \ - \ - StreamTcpUTSetupSession(&ssn); \ - StreamTcpUTSetupStream(&ssn.server, (isn)); \ - StreamTcpUTSetupStream(&ssn.client, (isn)); \ - \ - TcpStream *stream = &ssn.client; \ +#define OVERLAP_START(isn, policy) \ + TcpReassemblyThreadCtx *ra_ctx = NULL; \ + TcpSession ssn; \ + ThreadVars tv; \ + memset(&tv, 0, sizeof(tv)); \ + \ + StreamTcpUTInit(&ra_ctx); \ + \ + StreamTcpUTSetupSession(&ssn); \ + StreamTcpUTSetupStream(&ssn.server, (isn)); \ + StreamTcpUTSetupStream(&ssn.client, (isn)); \ + \ + TcpStream *stream = &ssn.client; \ stream->os_policy = (policy); -#define OVERLAP_END \ - StreamTcpUTClearSession(&ssn); \ - StreamTcpUTDeinit(ra_ctx); \ +#define OVERLAP_END \ + StreamTcpUTClearSession(&ssn); \ + StreamTcpUTDeinit(ra_ctx); \ PASS -#define OVERLAP_STEP(rseq, seg, seglen, buf, buflen) \ - StreamTcpUTAddPayload(&tv, ra_ctx, &ssn, stream, stream->isn + (rseq), (uint8_t *)(seg), (seglen)); \ +#define OVERLAP_STEP(rseq, seg, seglen, buf, buflen) \ + StreamTcpUTAddPayload( \ + &tv, ra_ctx, &ssn, stream, stream->isn + (rseq), (uint8_t *)(seg), (seglen)); \ FAIL_IF(!(VALIDATE(stream, (uint8_t *)(buf), (buflen)))); static int OverlapBSD(uint32_t isn) @@ -105,7 +106,7 @@ static int OverlapBSDBefore(uint32_t isn) OVERLAP_STEP(2, "AA", 2, "\0AA\0\0\0\0\0D\0\0EE", 13); OVERLAP_STEP(1, "JJJJ", 4, "JJJJ\0\0\0\0D\0\0EE", 13); OVERLAP_STEP(8, "LLL", 3, "JJJJ\0\0\0LLL\0EE", 13); - OVERLAP_STEP(11,"MMM", 3, "JJJJ\0\0\0LLLMMM", 13); + OVERLAP_STEP(11, "MMM", 3, "JJJJ\0\0\0LLLMMM", 13); OVERLAP_END; } @@ -185,7 +186,7 @@ static int OverlapVISTABefore(uint32_t isn) OVERLAP_STEP(2, "AA", 2, "\0AB\0\0\0\0\0D\0\0EE", 13); OVERLAP_STEP(1, "JJJJ", 4, "JABJ\0\0\0\0D\0\0EE", 13); OVERLAP_STEP(8, "LLL", 3, "JABJ\0\0\0LDL\0EE", 13); - OVERLAP_STEP(11,"MMM", 3, "JABJ\0\0\0LDLMEE", 13); + OVERLAP_STEP(11, "MMM", 3, "JABJ\0\0\0LDLMEE", 13); OVERLAP_END; } @@ -263,7 +264,7 @@ static int OverlapLINUXBefore(uint32_t isn) OVERLAP_STEP(2, "AA", 2, "\0AA\0\0\0\0\0D\0\0EE", 13); OVERLAP_STEP(1, "JJJJ", 4, "JJJJ\0\0\0\0D\0\0EE", 13); OVERLAP_STEP(8, "LLL", 3, "JJJJ\0\0\0LLL\0EE", 13); - OVERLAP_STEP(11,"MMM", 3, "JJJJ\0\0\0LLLMMM", 13); + OVERLAP_STEP(11, "MMM", 3, "JJJJ\0\0\0LLLMMM", 13); OVERLAP_END; } @@ -341,7 +342,7 @@ static int OverlapLINUXOLDBefore(uint32_t isn) OVERLAP_STEP(2, "AA", 2, "\0AA\0\0\0\0\0D\0\0EE", 13); OVERLAP_STEP(1, "JJJJ", 4, "JJJJ\0\0\0\0D\0\0EE", 13); OVERLAP_STEP(8, "LLL", 3, "JJJJ\0\0\0LLL\0EE", 13); - OVERLAP_STEP(11,"MMM", 3, "JJJJ\0\0\0LLLMMM", 13); + OVERLAP_STEP(11, "MMM", 3, "JJJJ\0\0\0LLLMMM", 13); OVERLAP_END; } @@ -418,7 +419,7 @@ static int OverlapSOLARISBefore(uint32_t isn) OVERLAP_STEP(2, "AA", 2, "\0AA\0\0\0\0\0D\0\0EE", 13); OVERLAP_STEP(1, "JJJJ", 4, "JJJJ\0\0\0\0D\0\0EE", 13); OVERLAP_STEP(8, "LLL", 3, "JJJJ\0\0\0LLL\0EE", 13); - OVERLAP_STEP(11,"MMM", 3, "JJJJ\0\0\0LLLMMM", 13); + OVERLAP_STEP(11, "MMM", 3, "JJJJ\0\0\0LLLMMM", 13); OVERLAP_END; } @@ -488,7 +489,7 @@ static int OverlapLASTBefore(uint32_t isn) OVERLAP_STEP(2, "AA", 2, "\0AA\0\0\0\0\0D\0\0EE", 13); OVERLAP_STEP(1, "JJJJ", 4, "JJJJ\0\0\0\0D\0\0EE", 13); OVERLAP_STEP(8, "LLL", 3, "JJJJ\0\0\0LLL\0EE", 13); - OVERLAP_STEP(11,"MMM", 3, "JJJJ\0\0\0LLLMMM", 13); + OVERLAP_STEP(11, "MMM", 3, "JJJJ\0\0\0LLLMMM", 13); OVERLAP_END; } @@ -548,7 +549,6 @@ static int StreamTcpReassembleTest01(void) return 1; } - /** \test Vista Policy */ static int StreamTcpReassembleTest02(void) @@ -575,7 +575,6 @@ static int StreamTcpReassembleTest02(void) return 1; } - /** \test Linux policy */ static int StreamTcpReassembleTest03(void) @@ -680,7 +679,7 @@ static int StreamTcpReassembleTest06(void) return 1; } -static int StreamTcpReassembleTest30 (void) +static int StreamTcpReassembleTest30(void) { OVERLAP_START(9, OS_POLICY_BSD); OVERLAP_STEP(3, "BBB", 3, "\0\0BBB", 5); @@ -688,7 +687,7 @@ static int StreamTcpReassembleTest30 (void) OVERLAP_END; } -static int StreamTcpReassembleTest31 (void) +static int StreamTcpReassembleTest31(void) { OVERLAP_START(9, OS_POLICY_BSD); OVERLAP_STEP(1, "AA", 2, "AA", 2); @@ -701,32 +700,25 @@ static int StreamTcpReassembleTest32(void) OVERLAP_START(0, OS_POLICY_BSD); OVERLAP_STEP(11, "AAAAAAAAAA", 10, "\0\0\0\0\0\0\0\0\0\0AAAAAAAAAA", 20); OVERLAP_STEP(21, "BBBBBBBBBB", 10, "\0\0\0\0\0\0\0\0\0\0AAAAAAAAAABBBBBBBBBB", 30); - OVERLAP_STEP(41, "CCCCCCCCCC", 10, "\0\0\0\0\0\0\0\0\0\0AAAAAAAAAABBBBBBBBBB\0\0\0\0\0\0\0\0\0\0CCCCCCCCCC", 50); - OVERLAP_STEP(6, "aaaaaaaaaaaaaaaaaaaa", 20, "\0\0\0\0\0aaaaaaaaaaaaaaaaaaaaBBBBB\0\0\0\0\0\0\0\0\0\0CCCCCCCCCC", 50); - OVERLAP_STEP(1, "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", 50, "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", 50); + OVERLAP_STEP(41, "CCCCCCCCCC", 10, + "\0\0\0\0\0\0\0\0\0\0AAAAAAAAAABBBBBBBBBB\0\0\0\0\0\0\0\0\0\0CCCCCCCCCC", 50); + OVERLAP_STEP(6, "aaaaaaaaaaaaaaaaaaaa", 20, + "\0\0\0\0\0aaaaaaaaaaaaaaaaaaaaBBBBB\0\0\0\0\0\0\0\0\0\0CCCCCCCCCC", 50); + OVERLAP_STEP(1, "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", 50, + "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", 50); OVERLAP_END; } void StreamTcpListRegisterTests(void) { - UtRegisterTest("StreamTcpReassembleTest01 -- BSD policy", - StreamTcpReassembleTest01); - UtRegisterTest("StreamTcpReassembleTest02 -- VISTA policy", - StreamTcpReassembleTest02); - UtRegisterTest("StreamTcpReassembleTest03 -- LINUX policy", - StreamTcpReassembleTest03); - UtRegisterTest("StreamTcpReassembleTest04 -- LINUX-OLD policy", - StreamTcpReassembleTest04); - UtRegisterTest("StreamTcpReassembleTest05 -- SOLARIS policy", - StreamTcpReassembleTest05); - UtRegisterTest("StreamTcpReassembleTest06 -- LAST policy", - StreamTcpReassembleTest06); - - UtRegisterTest("StreamTcpReassembleTest30", - StreamTcpReassembleTest30); - UtRegisterTest("StreamTcpReassembleTest31", - StreamTcpReassembleTest31); - UtRegisterTest("StreamTcpReassembleTest32", - StreamTcpReassembleTest32); + UtRegisterTest("StreamTcpReassembleTest01 -- BSD policy", StreamTcpReassembleTest01); + UtRegisterTest("StreamTcpReassembleTest02 -- VISTA policy", StreamTcpReassembleTest02); + UtRegisterTest("StreamTcpReassembleTest03 -- LINUX policy", StreamTcpReassembleTest03); + UtRegisterTest("StreamTcpReassembleTest04 -- LINUX-OLD policy", StreamTcpReassembleTest04); + UtRegisterTest("StreamTcpReassembleTest05 -- SOLARIS policy", StreamTcpReassembleTest05); + UtRegisterTest("StreamTcpReassembleTest06 -- LAST policy", StreamTcpReassembleTest06); + UtRegisterTest("StreamTcpReassembleTest30", StreamTcpReassembleTest30); + UtRegisterTest("StreamTcpReassembleTest31", StreamTcpReassembleTest31); + UtRegisterTest("StreamTcpReassembleTest32", StreamTcpReassembleTest32); } diff --git a/src/tests/stream-tcp-reassemble.c b/src/tests/stream-tcp-reassemble.c index 5f07f336c4d8..2681f410e098 100644 --- a/src/tests/stream-tcp-reassemble.c +++ b/src/tests/stream-tcp-reassemble.c @@ -38,8 +38,7 @@ static int TestReassembleRawCallback( SCLogNotice("have %u expect %u", data_len, cb->expect_data_len); - if (data_len == cb->expect_data_len && - memcmp(data, cb->expect_data, data_len) == 0) { + if (data_len == cb->expect_data_len && memcmp(data, cb->expect_data, data_len) == 0) { return 1; } else { SCLogNotice("data mismatch. Expected:"); @@ -50,8 +49,8 @@ static int TestReassembleRawCallback( } } -static int TestReassembleRawValidate(TcpSession *ssn, Packet *p, - const uint8_t *data, const uint32_t data_len) +static int TestReassembleRawValidate( + TcpSession *ssn, Packet *p, const uint8_t *data, const uint32_t data_len) { struct TestReassembleRawCallbackData cb = { data, data_len }; uint64_t progress = 0; @@ -63,56 +62,56 @@ static int TestReassembleRawValidate(TcpSession *ssn, Packet *p, return r; } -#define RAWREASSEMBLY_START(isn) \ - TcpReassemblyThreadCtx *ra_ctx = NULL; \ - TcpSession ssn; \ - ThreadVars tv; \ - memset(&tv, 0, sizeof(tv)); \ - Packet *p = NULL; \ - \ - \ - StreamTcpUTInit(&ra_ctx); \ - StreamTcpUTInitInline(); \ - stream_config.reassembly_toserver_chunk_size = 9; \ - stream_config.reassembly_toclient_chunk_size = 9; \ - StreamTcpUTSetupSession(&ssn); \ - StreamTcpUTSetupStream(&ssn.server, (isn)); \ - StreamTcpUTSetupStream(&ssn.client, (isn)); \ - ssn.server.last_ack = (isn) + 1; \ - ssn.client.last_ack = (isn) + 1; \ - \ +#define RAWREASSEMBLY_START(isn) \ + TcpReassemblyThreadCtx *ra_ctx = NULL; \ + TcpSession ssn; \ + ThreadVars tv; \ + memset(&tv, 0, sizeof(tv)); \ + Packet *p = NULL; \ + \ + StreamTcpUTInit(&ra_ctx); \ + StreamTcpUTInitInline(); \ + stream_config.reassembly_toserver_chunk_size = 9; \ + stream_config.reassembly_toclient_chunk_size = 9; \ + StreamTcpUTSetupSession(&ssn); \ + StreamTcpUTSetupStream(&ssn.server, (isn)); \ + StreamTcpUTSetupStream(&ssn.client, (isn)); \ + ssn.server.last_ack = (isn) + 1; \ + ssn.client.last_ack = (isn) + 1; \ + \ TcpStream *stream = &ssn.client; -#define RAWREASSEMBLY_END \ - StreamTcpUTClearSession(&ssn); \ - StreamTcpUTDeinit(ra_ctx); \ +#define RAWREASSEMBLY_END \ + StreamTcpUTClearSession(&ssn); \ + StreamTcpUTDeinit(ra_ctx); \ PASS -#define RAWREASSEMBLY_STEP(seq, seg, seglen, buf, buflen) \ - p = PacketGetFromAlloc(); \ - FAIL_IF_NULL(p); \ - { \ - SCLogNotice("SEQ %u block of %u", (seq), (seglen)); \ - p->flowflags = FLOW_PKT_TOSERVER; \ - TCPHdr tcphdr; \ - memset(&tcphdr, 0, sizeof(tcphdr)); \ - p->tcph = &tcphdr; \ - p->tcph->th_seq = htonl((seq)); \ - p->tcph->th_ack = htonl(10); \ - p->payload_len = (seglen); \ - \ - FAIL_IF(StreamTcpUTAddPayload(&tv, ra_ctx, &ssn, stream, (seq), (uint8_t *)(seg), (seglen)) != 0); \ - p->flags |= PKT_STREAM_ADD; \ - FAIL_IF(!(TestReassembleRawValidate(&ssn, p, (uint8_t *)(buf), (buflen)))); \ - }\ +#define RAWREASSEMBLY_STEP(seq, seg, seglen, buf, buflen) \ + p = PacketGetFromAlloc(); \ + FAIL_IF_NULL(p); \ + { \ + SCLogNotice("SEQ %u block of %u", (seq), (seglen)); \ + p->flowflags = FLOW_PKT_TOSERVER; \ + TCPHdr tcphdr; \ + memset(&tcphdr, 0, sizeof(tcphdr)); \ + p->tcph = &tcphdr; \ + p->tcph->th_seq = htonl((seq)); \ + p->tcph->th_ack = htonl(10); \ + p->payload_len = (seglen); \ + \ + FAIL_IF(StreamTcpUTAddPayload( \ + &tv, ra_ctx, &ssn, stream, (seq), (uint8_t *)(seg), (seglen)) != 0); \ + p->flags |= PKT_STREAM_ADD; \ + FAIL_IF(!(TestReassembleRawValidate(&ssn, p, (uint8_t *)(buf), (buflen)))); \ + } \ PacketFree(p); -#define RAWREASSEMBLY_STEP_WITH_PROGRESS(seq, seg, seglen, buf, buflen, lastack, progress) \ - stream->last_ack = (lastack); \ - RAWREASSEMBLY_STEP((seq),(seg),(seglen),(buf),(buflen)); \ +#define RAWREASSEMBLY_STEP_WITH_PROGRESS(seq, seg, seglen, buf, buflen, lastack, progress) \ + stream->last_ack = (lastack); \ + RAWREASSEMBLY_STEP((seq), (seg), (seglen), (buf), (buflen)); \ FAIL_IF(STREAM_RAW_PROGRESS(stream) != (progress)); -static int StreamTcpReassembleRawTest01 (void) +static int StreamTcpReassembleRawTest01(void) { RAWREASSEMBLY_START(1); RAWREASSEMBLY_STEP(2, "AAA", 3, "AAA", 3); @@ -121,64 +120,64 @@ static int StreamTcpReassembleRawTest01 (void) RAWREASSEMBLY_END; } -static int StreamTcpReassembleRawTest02 (void) +static int StreamTcpReassembleRawTest02(void) { RAWREASSEMBLY_START(1); RAWREASSEMBLY_STEP(2, "AAA", 3, "AAA", 3); RAWREASSEMBLY_STEP(5, "BBB", 3, "AAABBB", 6); - RAWREASSEMBLY_STEP(11,"DDD", 3, "DDD", 3); + RAWREASSEMBLY_STEP(11, "DDD", 3, "DDD", 3); RAWREASSEMBLY_STEP(8, "CCC", 3, "BBBCCCDDD", 9); RAWREASSEMBLY_END; } -static int StreamTcpReassembleRawTest03 (void) +static int StreamTcpReassembleRawTest03(void) { RAWREASSEMBLY_START(1); RAWREASSEMBLY_STEP(2, "AAA", 3, "AAA", 3); - RAWREASSEMBLY_STEP(11,"DDD", 3, "DDD", 3); + RAWREASSEMBLY_STEP(11, "DDD", 3, "DDD", 3); RAWREASSEMBLY_STEP(8, "CCC", 3, "CCCDDD", 6); RAWREASSEMBLY_END; } -static int StreamTcpReassembleRawTest04 (void) +static int StreamTcpReassembleRawTest04(void) { RAWREASSEMBLY_START(1); RAWREASSEMBLY_STEP(2, "AAAAA", 5, "AAAAA", 5); - RAWREASSEMBLY_STEP(10,"CCCCC", 5, "CCCCC", 5); + RAWREASSEMBLY_STEP(10, "CCCCC", 5, "CCCCC", 5); RAWREASSEMBLY_STEP(7, "BBB", 3, "AAABBBCCC", 9); RAWREASSEMBLY_END; } -static int StreamTcpReassembleRawTest05 (void) +static int StreamTcpReassembleRawTest05(void) { RAWREASSEMBLY_START(1); RAWREASSEMBLY_STEP(2, "AAAAA", 5, "AAAAA", 5); - RAWREASSEMBLY_STEP(10,"CCCCC", 5, "CCCCC", 5); + RAWREASSEMBLY_STEP(10, "CCCCC", 5, "CCCCC", 5); RAWREASSEMBLY_STEP(2, "EEEEEEEEEEEEE", 13, "AAAAAEEECCCCC", 13); RAWREASSEMBLY_END; } -static int StreamTcpReassembleRawTest06 (void) +static int StreamTcpReassembleRawTest06(void) { RAWREASSEMBLY_START(1); RAWREASSEMBLY_STEP(2, "AAAAA", 5, "AAAAA", 5); - RAWREASSEMBLY_STEP(16,"CCCCC", 5, "CCCCC", 5); + RAWREASSEMBLY_STEP(16, "CCCCC", 5, "CCCCC", 5); RAWREASSEMBLY_STEP(7, "BBBBBBBBB", 9, "ABBBBBBBBBC", 11); - RAWREASSEMBLY_STEP(21,"DDDDDDDDDD",10,"CCCDDDDDDDDDD", 13); + RAWREASSEMBLY_STEP(21, "DDDDDDDDDD", 10, "CCCDDDDDDDDDD", 13); RAWREASSEMBLY_END; } -static int StreamTcpReassembleRawTest07 (void) +static int StreamTcpReassembleRawTest07(void) { RAWREASSEMBLY_START(1); RAWREASSEMBLY_STEP(2, "AAAAAAA", 7, "AAAAAAA", 7); RAWREASSEMBLY_STEP(9, "BBBBBBB", 7, "AAABBBBBBB", 10); - RAWREASSEMBLY_STEP(16,"C", 1, "ABBBBBBBC", 9); - RAWREASSEMBLY_STEP(17,"DDDDDDDD",8,"BBCDDDDDDDD", 11); + RAWREASSEMBLY_STEP(16, "C", 1, "ABBBBBBBC", 9); + RAWREASSEMBLY_STEP(17, "DDDDDDDD", 8, "BBCDDDDDDDD", 11); RAWREASSEMBLY_END; } -static int StreamTcpReassembleRawTest08 (void) +static int StreamTcpReassembleRawTest08(void) { RAWREASSEMBLY_START(1); RAWREASSEMBLY_STEP_WITH_PROGRESS(2, "AAA", 3, "AAA", 3, 3, 3); @@ -190,20 +189,12 @@ static int StreamTcpReassembleRawTest08 (void) static void StreamTcpReassembleRawRegisterTests(void) { - UtRegisterTest("StreamTcpReassembleRawTest01", - StreamTcpReassembleRawTest01); - UtRegisterTest("StreamTcpReassembleRawTest02", - StreamTcpReassembleRawTest02); - UtRegisterTest("StreamTcpReassembleRawTest03", - StreamTcpReassembleRawTest03); - UtRegisterTest("StreamTcpReassembleRawTest04", - StreamTcpReassembleRawTest04); - UtRegisterTest("StreamTcpReassembleRawTest05", - StreamTcpReassembleRawTest05); - UtRegisterTest("StreamTcpReassembleRawTest06", - StreamTcpReassembleRawTest06); - UtRegisterTest("StreamTcpReassembleRawTest07", - StreamTcpReassembleRawTest07); - UtRegisterTest("StreamTcpReassembleRawTest08", - StreamTcpReassembleRawTest08); + UtRegisterTest("StreamTcpReassembleRawTest01", StreamTcpReassembleRawTest01); + UtRegisterTest("StreamTcpReassembleRawTest02", StreamTcpReassembleRawTest02); + UtRegisterTest("StreamTcpReassembleRawTest03", StreamTcpReassembleRawTest03); + UtRegisterTest("StreamTcpReassembleRawTest04", StreamTcpReassembleRawTest04); + UtRegisterTest("StreamTcpReassembleRawTest05", StreamTcpReassembleRawTest05); + UtRegisterTest("StreamTcpReassembleRawTest06", StreamTcpReassembleRawTest06); + UtRegisterTest("StreamTcpReassembleRawTest07", StreamTcpReassembleRawTest07); + UtRegisterTest("StreamTcpReassembleRawTest08", StreamTcpReassembleRawTest08); } diff --git a/src/threads-debug.h b/src/threads-debug.h index 2946d9140f26..f3b8e24ec2ef 100644 --- a/src/threads-debug.h +++ b/src/threads-debug.h @@ -34,209 +34,250 @@ * It is for Mac OS X users; * If you see a mutex, spinlock or condition not initialized, report it please! */ -#define SCMutexLock_dbg(mut) ({ \ - printf("%16s(%s:%d): (thread:%"PRIuMAX") locking mutex %p\n", __FUNCTION__, __FILE__, __LINE__, (uintmax_t)pthread_self(), mut); \ - int retl = pthread_mutex_lock(mut); \ - printf("%16s(%s:%d): (thread:%"PRIuMAX") locked mutex %p ret %" PRId32 "\n", __FUNCTION__, __FILE__, __LINE__, (uintmax_t)pthread_self(), mut, retl); \ - if (retl != 0) { \ - switch (retl) { \ - case EINVAL: \ - printf("The value specified by attr is invalid\n"); \ - retl = pthread_mutex_init(mut, NULL); \ - if (retl != 0) \ - exit(EXIT_FAILURE); \ - retl = pthread_mutex_lock(mut); \ - break; \ - case EDEADLK: \ - printf("A deadlock would occur if the thread blocked waiting for mutex\n"); \ - break; \ - } \ - } \ - retl; \ -}) +#define SCMutexLock_dbg(mut) \ + ({ \ + printf("%16s(%s:%d): (thread:%" PRIuMAX ") locking mutex %p\n", __FUNCTION__, __FILE__, \ + __LINE__, (uintmax_t)pthread_self(), mut); \ + int retl = pthread_mutex_lock(mut); \ + printf("%16s(%s:%d): (thread:%" PRIuMAX ") locked mutex %p ret %" PRId32 "\n", \ + __FUNCTION__, __FILE__, __LINE__, (uintmax_t)pthread_self(), mut, retl); \ + if (retl != 0) { \ + switch (retl) { \ + case EINVAL: \ + printf("The value specified by attr is invalid\n"); \ + retl = pthread_mutex_init(mut, NULL); \ + if (retl != 0) \ + exit(EXIT_FAILURE); \ + retl = pthread_mutex_lock(mut); \ + break; \ + case EDEADLK: \ + printf("A deadlock would occur if the thread blocked waiting for mutex\n"); \ + break; \ + } \ + } \ + retl; \ + }) -#define SCMutexTrylock_dbg(mut) ({ \ - printf("%16s(%s:%d): (thread:%"PRIuMAX") trylocking mutex %p\n", __FUNCTION__, __FILE__, __LINE__, (uintmax_t)pthread_self(), mut); \ - int rett = pthread_mutex_trylock(mut); \ - printf("%16s(%s:%d): (thread:%"PRIuMAX") trylocked mutex %p ret %" PRId32 "\n", __FUNCTION__, __FILE__, __LINE__, (uintmax_t)pthread_self(), mut, rett); \ - if (rett != 0) { \ - switch (rett) { \ - case EINVAL: \ - printf("%16s(%s:%d): The value specified by attr is invalid\n", __FUNCTION__, __FILE__, __LINE__); \ - break; \ - case EBUSY: \ - printf("Mutex is already locked\n"); \ - break; \ - } \ - } \ - rett; \ -}) +#define SCMutexTrylock_dbg(mut) \ + ({ \ + printf("%16s(%s:%d): (thread:%" PRIuMAX ") trylocking mutex %p\n", __FUNCTION__, __FILE__, \ + __LINE__, (uintmax_t)pthread_self(), mut); \ + int rett = pthread_mutex_trylock(mut); \ + printf("%16s(%s:%d): (thread:%" PRIuMAX ") trylocked mutex %p ret %" PRId32 "\n", \ + __FUNCTION__, __FILE__, __LINE__, (uintmax_t)pthread_self(), mut, rett); \ + if (rett != 0) { \ + switch (rett) { \ + case EINVAL: \ + printf("%16s(%s:%d): The value specified by attr is invalid\n", __FUNCTION__, \ + __FILE__, __LINE__); \ + break; \ + case EBUSY: \ + printf("Mutex is already locked\n"); \ + break; \ + } \ + } \ + rett; \ + }) -#define SCMutexInit_dbg(mut, mutattr) ({ \ - int ret; \ - ret = pthread_mutex_init(mut, mutattr); \ - if (ret != 0) { \ - switch (ret) { \ - case EINVAL: \ - printf("The value specified by attr is invalid\n"); \ - printf("%16s(%s:%d): (thread:%"PRIuMAX") mutex %p initialization returned %" PRId32 "\n", __FUNCTION__, __FILE__, __LINE__, (uintmax_t)pthread_self(), mut, ret); \ - break; \ - case EAGAIN: \ - printf("The system temporarily lacks the resources to create another mutex\n"); \ - printf("%16s(%s:%d): (thread:%"PRIuMAX") mutex %p initialization returned %" PRId32 "\n", __FUNCTION__, __FILE__, __LINE__, (uintmax_t)pthread_self(), mut, ret); \ - break; \ - case ENOMEM: \ - printf("The process cannot allocate enough memory to create another mutex\n"); \ - printf("%16s(%s:%d): (thread:%"PRIuMAX") mutex %p initialization returned %" PRId32 "\n", __FUNCTION__, __FILE__, __LINE__, (uintmax_t)pthread_self(), mut, ret); \ - break; \ - } \ - } \ - ret; \ -}) +#define SCMutexInit_dbg(mut, mutattr) \ + ({ \ + int ret; \ + ret = pthread_mutex_init(mut, mutattr); \ + if (ret != 0) { \ + switch (ret) { \ + case EINVAL: \ + printf("The value specified by attr is invalid\n"); \ + printf("%16s(%s:%d): (thread:%" PRIuMAX \ + ") mutex %p initialization returned %" PRId32 "\n", \ + __FUNCTION__, __FILE__, __LINE__, (uintmax_t)pthread_self(), mut, \ + ret); \ + break; \ + case EAGAIN: \ + printf("The system temporarily lacks the resources to create another " \ + "mutex\n"); \ + printf("%16s(%s:%d): (thread:%" PRIuMAX \ + ") mutex %p initialization returned %" PRId32 "\n", \ + __FUNCTION__, __FILE__, __LINE__, (uintmax_t)pthread_self(), mut, \ + ret); \ + break; \ + case ENOMEM: \ + printf("The process cannot allocate enough memory to create another mutex\n"); \ + printf("%16s(%s:%d): (thread:%" PRIuMAX \ + ") mutex %p initialization returned %" PRId32 "\n", \ + __FUNCTION__, __FILE__, __LINE__, (uintmax_t)pthread_self(), mut, \ + ret); \ + break; \ + } \ + } \ + ret; \ + }) -#define SCMutexUnlock_dbg(mut) ({ \ - printf("%16s(%s:%d): (thread:%"PRIuMAX") unlocking mutex %p\n", __FUNCTION__, __FILE__, __LINE__, (uintmax_t)pthread_self(), mut); \ - int retu = pthread_mutex_unlock(mut); \ - printf("%16s(%s:%d): (thread:%"PRIuMAX") unlocked mutex %p ret %" PRId32 "\n", __FUNCTION__, __FILE__, __LINE__, (uintmax_t)pthread_self(), mut, retu); \ - if (retu != 0) { \ - switch (retu) { \ - case EINVAL: \ - printf("%16s(%s:%d): The value specified by attr is invalid\n", __FUNCTION__, __FILE__, __LINE__); \ - break; \ - case EPERM: \ - printf("The current thread does not hold a lock on mutex\n"); \ - break; \ - } \ - } \ - retu; \ -}) +#define SCMutexUnlock_dbg(mut) \ + ({ \ + printf("%16s(%s:%d): (thread:%" PRIuMAX ") unlocking mutex %p\n", __FUNCTION__, __FILE__, \ + __LINE__, (uintmax_t)pthread_self(), mut); \ + int retu = pthread_mutex_unlock(mut); \ + printf("%16s(%s:%d): (thread:%" PRIuMAX ") unlocked mutex %p ret %" PRId32 "\n", \ + __FUNCTION__, __FILE__, __LINE__, (uintmax_t)pthread_self(), mut, retu); \ + if (retu != 0) { \ + switch (retu) { \ + case EINVAL: \ + printf("%16s(%s:%d): The value specified by attr is invalid\n", __FUNCTION__, \ + __FILE__, __LINE__); \ + break; \ + case EPERM: \ + printf("The current thread does not hold a lock on mutex\n"); \ + break; \ + } \ + } \ + retu; \ + }) -#define SCMutex pthread_mutex_t -#define SCMutexAttr pthread_mutexattr_t +#define SCMutex pthread_mutex_t +#define SCMutexAttr pthread_mutexattr_t #define SCMutexInit(mut, mutattrs) SCMutexInit_dbg(mut, mutattrs) -#define SCMutexLock(mut) SCMutexLock_dbg(mut) -#define SCMutexTrylock(mut) SCMutexTrylock_dbg(mut) -#define SCMutexUnlock(mut) SCMutexUnlock_dbg(mut) -#define SCMutexDestroy pthread_mutex_destroy -#define SCMUTEX_INITIALIZER PTHREAD_MUTEX_INITIALIZER +#define SCMutexLock(mut) SCMutexLock_dbg(mut) +#define SCMutexTrylock(mut) SCMutexTrylock_dbg(mut) +#define SCMutexUnlock(mut) SCMutexUnlock_dbg(mut) +#define SCMutexDestroy pthread_mutex_destroy +#define SCMUTEX_INITIALIZER PTHREAD_MUTEX_INITIALIZER /* conditions */ -#define SCCondWait_dbg(cond, mut) ({ \ - int ret = pthread_cond_wait(cond, mut); \ - switch (ret) { \ - case EINVAL: \ - printf("The value specified by attr is invalid (or a SCCondT not initialized!)\n"); \ - printf("%16s(%s:%d): (thread:%"PRIuMAX") failed SCCondWait %p ret %" PRId32 "\n", __FUNCTION__, __FILE__, __LINE__, (uintmax_t)pthread_self(), mut, ret); \ - break; \ - } \ - ret; \ -}) +#define SCCondWait_dbg(cond, mut) \ + ({ \ + int ret = pthread_cond_wait(cond, mut); \ + switch (ret) { \ + case EINVAL: \ + printf("The value specified by attr is invalid (or a SCCondT not " \ + "initialized!)\n"); \ + printf("%16s(%s:%d): (thread:%" PRIuMAX ") failed SCCondWait %p ret %" PRId32 \ + "\n", \ + __FUNCTION__, __FILE__, __LINE__, (uintmax_t)pthread_self(), mut, ret); \ + break; \ + } \ + ret; \ + }) /* conditions */ -#define SCCondT pthread_cond_t -#define SCCondInit pthread_cond_init -#define SCCondSignal pthread_cond_signal +#define SCCondT pthread_cond_t +#define SCCondInit pthread_cond_init +#define SCCondSignal pthread_cond_signal #define SCCondDestroy pthread_cond_destroy -#define SCCondWait SCCondWait_dbg +#define SCCondWait SCCondWait_dbg /* spinlocks */ -#define SCSpinLock_dbg(spin) ({ \ - printf("%16s(%s:%d): (thread:%"PRIuMAX") locking spin %p\n", __FUNCTION__, __FILE__, __LINE__, (uintmax_t)pthread_self(), spin); \ - int ret = pthread_spin_lock(spin); \ - printf("%16s(%s:%d): (thread:%"PRIuMAX") unlocked spin %p ret %" PRId32 "\n", __FUNCTION__, __FILE__, __LINE__, (uintmax_t)pthread_self(), spin, ret); \ - switch (ret) { \ - case EINVAL: \ - printf("The value specified by attr is invalid\n"); \ - break; \ - case EDEADLK: \ - printf("A deadlock would occur if the thread blocked waiting for spin\n"); \ - break; \ - } \ - ret; \ -}) +#define SCSpinLock_dbg(spin) \ + ({ \ + printf("%16s(%s:%d): (thread:%" PRIuMAX ") locking spin %p\n", __FUNCTION__, __FILE__, \ + __LINE__, (uintmax_t)pthread_self(), spin); \ + int ret = pthread_spin_lock(spin); \ + printf("%16s(%s:%d): (thread:%" PRIuMAX ") unlocked spin %p ret %" PRId32 "\n", \ + __FUNCTION__, __FILE__, __LINE__, (uintmax_t)pthread_self(), spin, ret); \ + switch (ret) { \ + case EINVAL: \ + printf("The value specified by attr is invalid\n"); \ + break; \ + case EDEADLK: \ + printf("A deadlock would occur if the thread blocked waiting for spin\n"); \ + break; \ + } \ + ret; \ + }) -#define SCSpinTrylock_dbg(spin) ({ \ - printf("%16s(%s:%d): (thread:%"PRIuMAX") trylocking spin %p\n", __FUNCTION__, __FILE__, __LINE__, (uintmax_t)pthread_self(), spin); \ - int ret = pthread_spin_trylock(spin); \ - printf("%16s(%s:%d): (thread:%"PRIuMAX") trylocked spin %p ret %" PRId32 "\n", __FUNCTION__, __FILE__, __LINE__, (uintmax_t)pthread_self(), spin, ret); \ - switch (ret) { \ - case EINVAL: \ - printf("The value specified by attr is invalid\n"); \ - break; \ - case EDEADLK: \ - printf("A deadlock would occur if the thread blocked waiting for spin\n"); \ - break; \ - case EBUSY: \ - printf("A thread currently holds the lock\n"); \ - break; \ - } \ - ret; \ -}) +#define SCSpinTrylock_dbg(spin) \ + ({ \ + printf("%16s(%s:%d): (thread:%" PRIuMAX ") trylocking spin %p\n", __FUNCTION__, __FILE__, \ + __LINE__, (uintmax_t)pthread_self(), spin); \ + int ret = pthread_spin_trylock(spin); \ + printf("%16s(%s:%d): (thread:%" PRIuMAX ") trylocked spin %p ret %" PRId32 "\n", \ + __FUNCTION__, __FILE__, __LINE__, (uintmax_t)pthread_self(), spin, ret); \ + switch (ret) { \ + case EINVAL: \ + printf("The value specified by attr is invalid\n"); \ + break; \ + case EDEADLK: \ + printf("A deadlock would occur if the thread blocked waiting for spin\n"); \ + break; \ + case EBUSY: \ + printf("A thread currently holds the lock\n"); \ + break; \ + } \ + ret; \ + }) -#define SCSpinUnlock_dbg(spin) ({ \ - printf("%16s(%s:%d): (thread:%"PRIuMAX") unlocking spin %p\n", __FUNCTION__, __FILE__, __LINE__, (uintmax_t)pthread_self(), spin); \ - int ret = pthread_spin_unlock(spin); \ - printf("%16s(%s:%d): (thread:%"PRIuMAX") unlockedspin %p ret %" PRId32 "\n", __FUNCTION__, __FILE__, __LINE__, (uintmax_t)pthread_self(), spin, ret); \ - switch (ret) { \ - case EINVAL: \ - printf("The value specified by attr is invalid\n"); \ - break; \ - case EPERM: \ - printf("The calling thread does not hold the lock\n"); \ - break; \ - } \ - ret; \ -}) +#define SCSpinUnlock_dbg(spin) \ + ({ \ + printf("%16s(%s:%d): (thread:%" PRIuMAX ") unlocking spin %p\n", __FUNCTION__, __FILE__, \ + __LINE__, (uintmax_t)pthread_self(), spin); \ + int ret = pthread_spin_unlock(spin); \ + printf("%16s(%s:%d): (thread:%" PRIuMAX ") unlockedspin %p ret %" PRId32 "\n", \ + __FUNCTION__, __FILE__, __LINE__, (uintmax_t)pthread_self(), spin, ret); \ + switch (ret) { \ + case EINVAL: \ + printf("The value specified by attr is invalid\n"); \ + break; \ + case EPERM: \ + printf("The calling thread does not hold the lock\n"); \ + break; \ + } \ + ret; \ + }) -#define SCSpinInit_dbg(spin, spin_attr) ({ \ - int ret = pthread_spin_init(spin, spin_attr); \ - printf("%16s(%s:%d): (thread:%"PRIuMAX") spinlock %p initialization returned %" PRId32 "\n", __FUNCTION__, __FILE__, __LINE__, (uintmax_t)pthread_self(), spin, ret); \ - switch (ret) { \ - case EINVAL: \ - printf("The value specified by attr is invalid\n"); \ - break; \ - case EBUSY: \ - printf("A thread currently holds the lock\n"); \ - break; \ - case ENOMEM: \ - printf("The process cannot allocate enough memory to create another spin\n"); \ - break; \ - case EAGAIN: \ - printf("The system temporarily lacks the resources to create another spin\n"); \ - break; \ - } \ - ret; \ -}) +#define SCSpinInit_dbg(spin, spin_attr) \ + ({ \ + int ret = pthread_spin_init(spin, spin_attr); \ + printf("%16s(%s:%d): (thread:%" PRIuMAX ") spinlock %p initialization returned %" PRId32 \ + "\n", \ + __FUNCTION__, __FILE__, __LINE__, (uintmax_t)pthread_self(), spin, ret); \ + switch (ret) { \ + case EINVAL: \ + printf("The value specified by attr is invalid\n"); \ + break; \ + case EBUSY: \ + printf("A thread currently holds the lock\n"); \ + break; \ + case ENOMEM: \ + printf("The process cannot allocate enough memory to create another spin\n"); \ + break; \ + case EAGAIN: \ + printf("The system temporarily lacks the resources to create another spin\n"); \ + break; \ + } \ + ret; \ + }) -#define SCSpinDestroy_dbg(spin) ({ \ - printf("%16s(%s:%d): (thread:%"PRIuMAX") condition %p waiting\n", __FUNCTION__, __FILE__, __LINE__, (uintmax_t)pthread_self(), spin); \ - int ret = pthread_spin_destroy(spin); \ - printf("%16s(%s:%d): (thread:%"PRIuMAX") condition %p passed %" PRId32 "\n", __FUNCTION__, __FILE__, __LINE__, (uintmax_t)pthread_self(), spin, ret); \ - switch (ret) { \ - case EINVAL: \ - printf("The value specified by attr is invalid\n"); \ - break; \ - case EBUSY: \ - printf("A thread currently holds the lock\n"); \ - break; \ - case ENOMEM: \ - printf("The process cannot allocate enough memory to create another spin\n"); \ - break; \ - case EAGAIN: \ - printf("The system temporarily lacks the resources to create another spin\n"); \ - break; \ - } \ - ret; \ -}) +#define SCSpinDestroy_dbg(spin) \ + ({ \ + printf("%16s(%s:%d): (thread:%" PRIuMAX ") condition %p waiting\n", __FUNCTION__, \ + __FILE__, __LINE__, (uintmax_t)pthread_self(), spin); \ + int ret = pthread_spin_destroy(spin); \ + printf("%16s(%s:%d): (thread:%" PRIuMAX ") condition %p passed %" PRId32 "\n", \ + __FUNCTION__, __FILE__, __LINE__, (uintmax_t)pthread_self(), spin, ret); \ + switch (ret) { \ + case EINVAL: \ + printf("The value specified by attr is invalid\n"); \ + break; \ + case EBUSY: \ + printf("A thread currently holds the lock\n"); \ + break; \ + case ENOMEM: \ + printf("The process cannot allocate enough memory to create another spin\n"); \ + break; \ + case EAGAIN: \ + printf("The system temporarily lacks the resources to create another spin\n"); \ + break; \ + } \ + ret; \ + }) -#define SCSpinlock pthread_spinlock_t -#define SCSpinLock SCSpinLock_dbg -#define SCSpinTrylock SCSpinTrylock_dbg -#define SCSpinUnlock SCSpinUnlock_dbg -#define SCSpinInit SCSpinInit_dbg -#define SCSpinDestroy SCSpinDestroy_dbg +#define SCSpinlock pthread_spinlock_t +#define SCSpinLock SCSpinLock_dbg +#define SCSpinTrylock SCSpinTrylock_dbg +#define SCSpinUnlock SCSpinUnlock_dbg +#define SCSpinInit SCSpinInit_dbg +#define SCSpinDestroy SCSpinDestroy_dbg /* rwlocks */ @@ -244,146 +285,175 @@ * initialized, logged, and does a second try; This is to prevent the system to freeze; * If you see a rwlock, spinlock or condition not initialized, report it please! */ -#define SCRWLockRDLock_dbg(rwl) ({ \ - printf("%16s(%s:%d): (thread:%"PRIuMAX") locking rwlock %p\n", __FUNCTION__, __FILE__, __LINE__, (uintmax_t)pthread_self(), rwl); \ - int retl = pthread_rwlock_rdlock(rwl); \ - printf("%16s(%s:%d): (thread:%"PRIuMAX") locked rwlock %p ret %" PRId32 "\n", __FUNCTION__, __FILE__, __LINE__, (uintmax_t)pthread_self(), rwl, retl); \ - if (retl != 0) { \ - switch (retl) { \ - case EINVAL: \ - printf("The value specified by attr is invalid\n"); \ - retl = pthread_rwlock_init(rwl, NULL); \ - if (retl != 0) \ - exit(EXIT_FAILURE); \ - retl = pthread_rwlock_rdlock(rwl); \ - break; \ - case EDEADLK: \ - printf("A deadlock would occur if the thread blocked waiting for rwlock\n"); \ - break; \ - } \ - } \ - retl; \ -}) +#define SCRWLockRDLock_dbg(rwl) \ + ({ \ + printf("%16s(%s:%d): (thread:%" PRIuMAX ") locking rwlock %p\n", __FUNCTION__, __FILE__, \ + __LINE__, (uintmax_t)pthread_self(), rwl); \ + int retl = pthread_rwlock_rdlock(rwl); \ + printf("%16s(%s:%d): (thread:%" PRIuMAX ") locked rwlock %p ret %" PRId32 "\n", \ + __FUNCTION__, __FILE__, __LINE__, (uintmax_t)pthread_self(), rwl, retl); \ + if (retl != 0) { \ + switch (retl) { \ + case EINVAL: \ + printf("The value specified by attr is invalid\n"); \ + retl = pthread_rwlock_init(rwl, NULL); \ + if (retl != 0) \ + exit(EXIT_FAILURE); \ + retl = pthread_rwlock_rdlock(rwl); \ + break; \ + case EDEADLK: \ + printf("A deadlock would occur if the thread blocked waiting for rwlock\n"); \ + break; \ + } \ + } \ + retl; \ + }) -#define SCRWLockWRLock_dbg(rwl) ({ \ - printf("%16s(%s:%d): (thread:%"PRIuMAX") locking rwlock %p\n", __FUNCTION__, __FILE__, __LINE__, (uintmax_t)pthread_self(), rwl); \ - int retl = pthread_rwlock_wrlock(rwl); \ - printf("%16s(%s:%d): (thread:%"PRIuMAX") locked rwlock %p ret %" PRId32 "\n", __FUNCTION__, __FILE__, __LINE__, (uintmax_t)pthread_self(), rwl, retl); \ - if (retl != 0) { \ - switch (retl) { \ - case EINVAL: \ - printf("The value specified by attr is invalid\n"); \ - retl = pthread_rwlock_init(rwl, NULL); \ - if (retl != 0) \ - exit(EXIT_FAILURE); \ - retl = pthread_rwlock_wrlock(rwl); \ - break; \ - case EDEADLK: \ - printf("A deadlock would occur if the thread blocked waiting for rwlock\n"); \ - break; \ - } \ - } \ - retl; \ -}) +#define SCRWLockWRLock_dbg(rwl) \ + ({ \ + printf("%16s(%s:%d): (thread:%" PRIuMAX ") locking rwlock %p\n", __FUNCTION__, __FILE__, \ + __LINE__, (uintmax_t)pthread_self(), rwl); \ + int retl = pthread_rwlock_wrlock(rwl); \ + printf("%16s(%s:%d): (thread:%" PRIuMAX ") locked rwlock %p ret %" PRId32 "\n", \ + __FUNCTION__, __FILE__, __LINE__, (uintmax_t)pthread_self(), rwl, retl); \ + if (retl != 0) { \ + switch (retl) { \ + case EINVAL: \ + printf("The value specified by attr is invalid\n"); \ + retl = pthread_rwlock_init(rwl, NULL); \ + if (retl != 0) \ + exit(EXIT_FAILURE); \ + retl = pthread_rwlock_wrlock(rwl); \ + break; \ + case EDEADLK: \ + printf("A deadlock would occur if the thread blocked waiting for rwlock\n"); \ + break; \ + } \ + } \ + retl; \ + }) +#define SCRWLockTryWRLock_dbg(rwl) \ + ({ \ + printf("%16s(%s:%d): (thread:%" PRIuMAX ") trylocking rwlock %p\n", __FUNCTION__, \ + __FILE__, __LINE__, (uintmax_t)pthread_self(), rwl); \ + int rett = pthread_rwlock_trywrlock(rwl); \ + printf("%16s(%s:%d): (thread:%" PRIuMAX ") trylocked rwlock %p ret %" PRId32 "\n", \ + __FUNCTION__, __FILE__, __LINE__, (uintmax_t)pthread_self(), rwl, rett); \ + if (rett != 0) { \ + switch (rett) { \ + case EINVAL: \ + printf("%16s(%s:%d): The value specified by attr is invalid\n", __FUNCTION__, \ + __FILE__, __LINE__); \ + break; \ + case EBUSY: \ + printf("RWLock is already locked\n"); \ + break; \ + } \ + } \ + rett; \ + }) -#define SCRWLockTryWRLock_dbg(rwl) ({ \ - printf("%16s(%s:%d): (thread:%"PRIuMAX") trylocking rwlock %p\n", __FUNCTION__, __FILE__, __LINE__, (uintmax_t)pthread_self(), rwl); \ - int rett = pthread_rwlock_trywrlock(rwl); \ - printf("%16s(%s:%d): (thread:%"PRIuMAX") trylocked rwlock %p ret %" PRId32 "\n", __FUNCTION__, __FILE__, __LINE__, (uintmax_t)pthread_self(), rwl, rett); \ - if (rett != 0) { \ - switch (rett) { \ - case EINVAL: \ - printf("%16s(%s:%d): The value specified by attr is invalid\n", __FUNCTION__, __FILE__, __LINE__); \ - break; \ - case EBUSY: \ - printf("RWLock is already locked\n"); \ - break; \ - } \ - } \ - rett; \ -}) +#define SCRWLockTryRDLock_dbg(rwl) \ + ({ \ + printf("%16s(%s:%d): (thread:%" PRIuMAX ") trylocking rwlock %p\n", __FUNCTION__, \ + __FILE__, __LINE__, (uintmax_t)pthread_self(), rwl); \ + int rett = pthread_rwlock_tryrdlock(rwl); \ + printf("%16s(%s:%d): (thread:%" PRIuMAX ") trylocked rwlock %p ret %" PRId32 "\n", \ + __FUNCTION__, __FILE__, __LINE__, (uintmax_t)pthread_self(), rwl, rett); \ + if (rett != 0) { \ + switch (rett) { \ + case EINVAL: \ + printf("%16s(%s:%d): The value specified by attr is invalid\n", __FUNCTION__, \ + __FILE__, __LINE__); \ + break; \ + case EBUSY: \ + printf("RWLock is already locked\n"); \ + break; \ + } \ + } \ + rett; \ + }) -#define SCRWLockTryRDLock_dbg(rwl) ({ \ - printf("%16s(%s:%d): (thread:%"PRIuMAX") trylocking rwlock %p\n", __FUNCTION__, __FILE__, __LINE__, (uintmax_t)pthread_self(), rwl); \ - int rett = pthread_rwlock_tryrdlock(rwl); \ - printf("%16s(%s:%d): (thread:%"PRIuMAX") trylocked rwlock %p ret %" PRId32 "\n", __FUNCTION__, __FILE__, __LINE__, (uintmax_t)pthread_self(), rwl, rett); \ - if (rett != 0) { \ - switch (rett) { \ - case EINVAL: \ - printf("%16s(%s:%d): The value specified by attr is invalid\n", __FUNCTION__, __FILE__, __LINE__); \ - break; \ - case EBUSY: \ - printf("RWLock is already locked\n"); \ - break; \ - } \ - } \ - rett; \ -}) +#define SCRWLockInit_dbg(rwl, rwlattr) \ + ({ \ + int ret; \ + ret = pthread_rwlock_init(rwl, rwlattr); \ + if (ret != 0) { \ + switch (ret) { \ + case EINVAL: \ + printf("The value specified by attr is invalid\n"); \ + printf("%16s(%s:%d): (thread:%" PRIuMAX \ + ") rwlock %p initialization returned %" PRId32 "\n", \ + __FUNCTION__, __FILE__, __LINE__, (uintmax_t)pthread_self(), rwl, \ + ret); \ + break; \ + case EAGAIN: \ + printf("The system temporarily lacks the resources to create another " \ + "rwlock\n"); \ + printf("%16s(%s:%d): (thread:%" PRIuMAX \ + ") rwlock %p initialization returned %" PRId32 "\n", \ + __FUNCTION__, __FILE__, __LINE__, (uintmax_t)pthread_self(), rwl, \ + ret); \ + break; \ + case ENOMEM: \ + printf("The process cannot allocate enough memory to create another " \ + "rwlock\n"); \ + printf("%16s(%s:%d): (thread:%" PRIuMAX \ + ") rwlock %p initialization returned %" PRId32 "\n", \ + __FUNCTION__, __FILE__, __LINE__, (uintmax_t)pthread_self(), rwl, \ + ret); \ + break; \ + } \ + } \ + ret; \ + }) -#define SCRWLockInit_dbg(rwl, rwlattr) ({ \ - int ret; \ - ret = pthread_rwlock_init(rwl, rwlattr); \ - if (ret != 0) { \ - switch (ret) { \ - case EINVAL: \ - printf("The value specified by attr is invalid\n"); \ - printf("%16s(%s:%d): (thread:%"PRIuMAX") rwlock %p initialization returned %" PRId32 "\n", __FUNCTION__, __FILE__, __LINE__, (uintmax_t)pthread_self(), rwl, ret); \ - break; \ - case EAGAIN: \ - printf("The system temporarily lacks the resources to create another rwlock\n"); \ - printf("%16s(%s:%d): (thread:%"PRIuMAX") rwlock %p initialization returned %" PRId32 "\n", __FUNCTION__, __FILE__, __LINE__, (uintmax_t)pthread_self(), rwl, ret); \ - break; \ - case ENOMEM: \ - printf("The process cannot allocate enough memory to create another rwlock\n"); \ - printf("%16s(%s:%d): (thread:%"PRIuMAX") rwlock %p initialization returned %" PRId32 "\n", __FUNCTION__, __FILE__, __LINE__, (uintmax_t)pthread_self(), rwl, ret); \ - break; \ - } \ - } \ - ret; \ -}) +#define SCRWLockUnlock_dbg(rwl) \ + ({ \ + printf("%16s(%s:%d): (thread:%" PRIuMAX ") unlocking rwlock %p\n", __FUNCTION__, __FILE__, \ + __LINE__, (uintmax_t)pthread_self(), rwl); \ + int retu = pthread_rwlock_unlock(rwl); \ + printf("%16s(%s:%d): (thread:%" PRIuMAX ") unlocked rwlock %p ret %" PRId32 "\n", \ + __FUNCTION__, __FILE__, __LINE__, (uintmax_t)pthread_self(), rwl, retu); \ + if (retu != 0) { \ + switch (retu) { \ + case EINVAL: \ + printf("%16s(%s:%d): The value specified by attr is invalid\n", __FUNCTION__, \ + __FILE__, __LINE__); \ + break; \ + case EPERM: \ + printf("The current thread does not hold a lock on rwlock\n"); \ + break; \ + } \ + } \ + retu; \ + }) -#define SCRWLockUnlock_dbg(rwl) ({ \ - printf("%16s(%s:%d): (thread:%"PRIuMAX") unlocking rwlock %p\n", __FUNCTION__, __FILE__, __LINE__, (uintmax_t)pthread_self(), rwl); \ - int retu = pthread_rwlock_unlock(rwl); \ - printf("%16s(%s:%d): (thread:%"PRIuMAX") unlocked rwlock %p ret %" PRId32 "\n", __FUNCTION__, __FILE__, __LINE__, (uintmax_t)pthread_self(), rwl, retu); \ - if (retu != 0) { \ - switch (retu) { \ - case EINVAL: \ - printf("%16s(%s:%d): The value specified by attr is invalid\n", __FUNCTION__, __FILE__, __LINE__); \ - break; \ - case EPERM: \ - printf("The current thread does not hold a lock on rwlock\n"); \ - break; \ - } \ - } \ - retu; \ -}) - -#define SCRWLock pthread_rwlock_t +#define SCRWLock pthread_rwlock_t #define SCRWLockInit(rwl, rwlattrs) SCRWLockInit_dbg(rwl, rwlattrs) -#define SCRWLockRDLock(rwl) SCRWLockRDLock_dbg(rwl) -#define SCRWLockWRLock(rwl) SCRWLockWRLock_dbg(rwl) -#define SCRWLockTryWRLock(rwl) SCRWLockTryWRLock_dbg(rwl) -#define SCRWLockTryRDLock(rwl) SCRWLockTryRDLock_dbg(rwl) -#define SCRWLockUnlock(rwl) SCRWLockUnlock_dbg(rwl) -#define SCRWLockDestroy pthread_rwlock_destroy +#define SCRWLockRDLock(rwl) SCRWLockRDLock_dbg(rwl) +#define SCRWLockWRLock(rwl) SCRWLockWRLock_dbg(rwl) +#define SCRWLockTryWRLock(rwl) SCRWLockTryWRLock_dbg(rwl) +#define SCRWLockTryRDLock(rwl) SCRWLockTryRDLock_dbg(rwl) +#define SCRWLockUnlock(rwl) SCRWLockUnlock_dbg(rwl) +#define SCRWLockDestroy pthread_rwlock_destroy /* ctrl mutex */ -#define SCCtrlMutex pthread_mutex_t -#define SCCtrlMutexAttr pthread_mutexattr_t -#define SCCtrlMutexInit(mut, mutattr ) pthread_mutex_init(mut, mutattr) -#define SCCtrlMutexLock(mut) pthread_mutex_lock(mut) -#define SCCtrlMutexTrylock(mut) pthread_mutex_trylock(mut) -#define SCCtrlMutexUnlock(mut) pthread_mutex_unlock(mut) -#define SCCtrlMutexDestroy pthread_mutex_destroy +#define SCCtrlMutex pthread_mutex_t +#define SCCtrlMutexAttr pthread_mutexattr_t +#define SCCtrlMutexInit(mut, mutattr) pthread_mutex_init(mut, mutattr) +#define SCCtrlMutexLock(mut) pthread_mutex_lock(mut) +#define SCCtrlMutexTrylock(mut) pthread_mutex_trylock(mut) +#define SCCtrlMutexUnlock(mut) pthread_mutex_unlock(mut) +#define SCCtrlMutexDestroy pthread_mutex_destroy /* ctrl conditions */ -#define SCCtrlCondT pthread_cond_t -#define SCCtrlCondInit pthread_cond_init -#define SCCtrlCondSignal pthread_cond_signal +#define SCCtrlCondT pthread_cond_t +#define SCCtrlCondInit pthread_cond_init +#define SCCtrlCondSignal pthread_cond_signal #define SCCtrlCondTimedwait pthread_cond_timedwait -#define SCCtrlCondWait pthread_cond_wait -#define SCCtrlCondDestroy pthread_cond_destroy +#define SCCtrlCondWait pthread_cond_wait +#define SCCtrlCondDestroy pthread_cond_destroy #endif diff --git a/src/threads-profile.h b/src/threads-profile.h index 43606ae98290..7f2db7eb0485 100644 --- a/src/threads-profile.h +++ b/src/threads-profile.h @@ -59,47 +59,49 @@ extern thread_local uint64_t mutex_lock_cnt; /* mutex */ -//printf("%16s(%s:%d): (thread:%"PRIuMAX") locked mutex %p ret %" PRId32 "\n", __FUNCTION__, __FILE__, __LINE__, (uintmax_t)pthread_self(), mut, retl); -#define SCMutexLock_profile(mut) ({ \ - mutex_lock_cnt++; \ - int retl = 0; \ - int cont = 0; \ - uint64_t mutex_lock_start = UtilCpuGetTicks(); \ - if (pthread_mutex_trylock((mut)) != 0) { \ - mutex_lock_contention++; \ - cont = 1; \ - retl = pthread_mutex_lock(mut); \ - } \ - uint64_t mutex_lock_end = UtilCpuGetTicks(); \ - mutex_lock_wait_ticks += (uint64_t)(mutex_lock_end - mutex_lock_start); \ - \ - if (locks_idx < PROFILING_MAX_LOCKS && record_locks) { \ - locks[locks_idx].file = (char *)__FILE__; \ - locks[locks_idx].func = (char *)__func__; \ - locks[locks_idx].line = (int)__LINE__; \ - locks[locks_idx].type = LOCK_MUTEX; \ - locks[locks_idx].cont = cont; \ - locks[locks_idx].ticks = (uint64_t)(mutex_lock_end - mutex_lock_start); \ - locks_idx++; \ - } \ - retl; \ -}) - -#define SCMutex pthread_mutex_t -#define SCMutexAttr pthread_mutexattr_t -#define SCMutexInit(mut, mutattr ) pthread_mutex_init(mut, mutattr) -#define SCMutexLock(mut) SCMutexLock_profile(mut) -#define SCMutexTrylock(mut) pthread_mutex_trylock(mut) -#define SCMutexUnlock(mut) pthread_mutex_unlock(mut) -#define SCMutexDestroy pthread_mutex_destroy -#define SCMUTEX_INITIALIZER PTHREAD_MUTEX_INITIALIZER +// printf("%16s(%s:%d): (thread:%"PRIuMAX") locked mutex %p ret %" PRId32 "\n", __FUNCTION__, +// __FILE__, __LINE__, (uintmax_t)pthread_self(), mut, retl); +#define SCMutexLock_profile(mut) \ + ({ \ + mutex_lock_cnt++; \ + int retl = 0; \ + int cont = 0; \ + uint64_t mutex_lock_start = UtilCpuGetTicks(); \ + if (pthread_mutex_trylock((mut)) != 0) { \ + mutex_lock_contention++; \ + cont = 1; \ + retl = pthread_mutex_lock(mut); \ + } \ + uint64_t mutex_lock_end = UtilCpuGetTicks(); \ + mutex_lock_wait_ticks += (uint64_t)(mutex_lock_end - mutex_lock_start); \ + \ + if (locks_idx < PROFILING_MAX_LOCKS && record_locks) { \ + locks[locks_idx].file = (char *)__FILE__; \ + locks[locks_idx].func = (char *)__func__; \ + locks[locks_idx].line = (int)__LINE__; \ + locks[locks_idx].type = LOCK_MUTEX; \ + locks[locks_idx].cont = cont; \ + locks[locks_idx].ticks = (uint64_t)(mutex_lock_end - mutex_lock_start); \ + locks_idx++; \ + } \ + retl; \ + }) + +#define SCMutex pthread_mutex_t +#define SCMutexAttr pthread_mutexattr_t +#define SCMutexInit(mut, mutattr) pthread_mutex_init(mut, mutattr) +#define SCMutexLock(mut) SCMutexLock_profile(mut) +#define SCMutexTrylock(mut) pthread_mutex_trylock(mut) +#define SCMutexUnlock(mut) pthread_mutex_unlock(mut) +#define SCMutexDestroy pthread_mutex_destroy +#define SCMUTEX_INITIALIZER PTHREAD_MUTEX_INITIALIZER /* conditions */ -#define SCCondT pthread_cond_t -#define SCCondInit pthread_cond_init -#define SCCondSignal pthread_cond_signal -#define SCCondDestroy pthread_cond_destroy +#define SCCondT pthread_cond_t +#define SCCondInit pthread_cond_init +#define SCCondSignal pthread_cond_signal +#define SCCondDestroy pthread_cond_destroy #define SCCondWait(cond, mut) pthread_cond_wait(cond, mut) /* spinlocks */ @@ -108,38 +110,40 @@ extern thread_local uint64_t spin_lock_contention; extern thread_local uint64_t spin_lock_wait_ticks; extern thread_local uint64_t spin_lock_cnt; -//printf("%16s(%s:%d): (thread:%"PRIuMAX") locked mutex %p ret %" PRId32 "\n", __FUNCTION__, __FILE__, __LINE__, (uintmax_t)pthread_self(), mut, retl); -#define SCSpinLock_profile(spin) ({ \ - spin_lock_cnt++; \ - int retl = 0; \ - int cont = 0; \ - uint64_t spin_lock_start = UtilCpuGetTicks(); \ - if (pthread_spin_trylock((spin)) != 0) { \ - spin_lock_contention++; \ - cont = 1; \ - retl = pthread_spin_lock((spin)); \ - } \ - uint64_t spin_lock_end = UtilCpuGetTicks(); \ - spin_lock_wait_ticks += (uint64_t)(spin_lock_end - spin_lock_start); \ - \ - if (locks_idx < PROFILING_MAX_LOCKS && record_locks) { \ - locks[locks_idx].file = (char *)__FILE__; \ - locks[locks_idx].func = (char *)__func__; \ - locks[locks_idx].line = (int)__LINE__; \ - locks[locks_idx].type = LOCK_SPIN; \ - locks[locks_idx].cont = cont; \ - locks[locks_idx].ticks = (uint64_t)(spin_lock_end - spin_lock_start); \ - locks_idx++; \ - } \ - retl; \ -}) - -#define SCSpinlock pthread_spinlock_t -#define SCSpinLock(mut) SCSpinLock_profile(mut) -#define SCSpinTrylock(spin) pthread_spin_trylock(spin) -#define SCSpinUnlock(spin) pthread_spin_unlock(spin) -#define SCSpinInit(spin, spin_attr) pthread_spin_init(spin, spin_attr) -#define SCSpinDestroy(spin) pthread_spin_destroy(spin) +// printf("%16s(%s:%d): (thread:%"PRIuMAX") locked mutex %p ret %" PRId32 "\n", __FUNCTION__, +// __FILE__, __LINE__, (uintmax_t)pthread_self(), mut, retl); +#define SCSpinLock_profile(spin) \ + ({ \ + spin_lock_cnt++; \ + int retl = 0; \ + int cont = 0; \ + uint64_t spin_lock_start = UtilCpuGetTicks(); \ + if (pthread_spin_trylock((spin)) != 0) { \ + spin_lock_contention++; \ + cont = 1; \ + retl = pthread_spin_lock((spin)); \ + } \ + uint64_t spin_lock_end = UtilCpuGetTicks(); \ + spin_lock_wait_ticks += (uint64_t)(spin_lock_end - spin_lock_start); \ + \ + if (locks_idx < PROFILING_MAX_LOCKS && record_locks) { \ + locks[locks_idx].file = (char *)__FILE__; \ + locks[locks_idx].func = (char *)__func__; \ + locks[locks_idx].line = (int)__LINE__; \ + locks[locks_idx].type = LOCK_SPIN; \ + locks[locks_idx].cont = cont; \ + locks[locks_idx].ticks = (uint64_t)(spin_lock_end - spin_lock_start); \ + locks_idx++; \ + } \ + retl; \ + }) + +#define SCSpinlock pthread_spinlock_t +#define SCSpinLock(mut) SCSpinLock_profile(mut) +#define SCSpinTrylock(spin) pthread_spin_trylock(spin) +#define SCSpinUnlock(spin) pthread_spin_unlock(spin) +#define SCSpinInit(spin, spin_attr) pthread_spin_init(spin, spin_attr) +#define SCSpinDestroy(spin) pthread_spin_destroy(spin) /* rwlocks */ @@ -147,84 +151,86 @@ extern thread_local uint64_t rww_lock_contention; extern thread_local uint64_t rww_lock_wait_ticks; extern thread_local uint64_t rww_lock_cnt; -#define SCRWLockWRLock_profile(mut) ({ \ - rww_lock_cnt++; \ - int retl = 0; \ - int cont = 0; \ - uint64_t rww_lock_start = UtilCpuGetTicks(); \ - if (pthread_rwlock_trywrlock((mut)) != 0) { \ - rww_lock_contention++; \ - cont = 1; \ - retl = pthread_rwlock_wrlock(mut); \ - } \ - uint64_t rww_lock_end = UtilCpuGetTicks(); \ - rww_lock_wait_ticks += (uint64_t)(rww_lock_end - rww_lock_start); \ - \ - if (locks_idx < PROFILING_MAX_LOCKS && record_locks) { \ - locks[locks_idx].file = (char *)__FILE__; \ - locks[locks_idx].func = (char *)__func__; \ - locks[locks_idx].line = (int)__LINE__; \ - locks[locks_idx].type = LOCK_RWW; \ - locks[locks_idx].cont = cont; \ - locks[locks_idx].ticks = (uint64_t)(rww_lock_end - rww_lock_start); \ - locks_idx++; \ - } \ - retl; \ -}) +#define SCRWLockWRLock_profile(mut) \ + ({ \ + rww_lock_cnt++; \ + int retl = 0; \ + int cont = 0; \ + uint64_t rww_lock_start = UtilCpuGetTicks(); \ + if (pthread_rwlock_trywrlock((mut)) != 0) { \ + rww_lock_contention++; \ + cont = 1; \ + retl = pthread_rwlock_wrlock(mut); \ + } \ + uint64_t rww_lock_end = UtilCpuGetTicks(); \ + rww_lock_wait_ticks += (uint64_t)(rww_lock_end - rww_lock_start); \ + \ + if (locks_idx < PROFILING_MAX_LOCKS && record_locks) { \ + locks[locks_idx].file = (char *)__FILE__; \ + locks[locks_idx].func = (char *)__func__; \ + locks[locks_idx].line = (int)__LINE__; \ + locks[locks_idx].type = LOCK_RWW; \ + locks[locks_idx].cont = cont; \ + locks[locks_idx].ticks = (uint64_t)(rww_lock_end - rww_lock_start); \ + locks_idx++; \ + } \ + retl; \ + }) extern thread_local uint64_t rwr_lock_contention; extern thread_local uint64_t rwr_lock_wait_ticks; extern thread_local uint64_t rwr_lock_cnt; -#define SCRWLockRDLock_profile(mut) ({ \ - rwr_lock_cnt++; \ - int retl = 0; \ - int cont = 0; \ - uint64_t rwr_lock_start = UtilCpuGetTicks(); \ - if (pthread_rwlock_tryrdlock((mut)) != 0) { \ - rwr_lock_contention++; \ - cont = 1; \ - retl = pthread_rwlock_rdlock(mut); \ - } \ - uint64_t rwr_lock_end = UtilCpuGetTicks(); \ - rwr_lock_wait_ticks += (uint64_t)(rwr_lock_end - rwr_lock_start); \ - \ - if (locks_idx < PROFILING_MAX_LOCKS && record_locks) { \ - locks[locks_idx].file = (char *)__FILE__; \ - locks[locks_idx].func = (char *)__func__; \ - locks[locks_idx].line = (int)__LINE__; \ - locks[locks_idx].type = LOCK_RWR; \ - locks[locks_idx].cont = cont; \ - locks[locks_idx].ticks = (uint64_t)(rwr_lock_end - rwr_lock_start); \ - locks_idx++; \ - } \ - retl; \ -}) - -#define SCRWLock pthread_rwlock_t -#define SCRWLockInit(rwl, rwlattr ) pthread_rwlock_init(rwl, rwlattr) -#define SCRWLockWRLock(mut) SCRWLockWRLock_profile(mut) -#define SCRWLockRDLock(mut) SCRWLockRDLock_profile(mut) -#define SCRWLockTryWRLock(rwl) pthread_rwlock_trywrlock(rwl) -#define SCRWLockTryRDLock(rwl) pthread_rwlock_tryrdlock(rwl) -#define SCRWLockUnlock(rwl) pthread_rwlock_unlock(rwl) -#define SCRWLockDestroy pthread_rwlock_destroy +#define SCRWLockRDLock_profile(mut) \ + ({ \ + rwr_lock_cnt++; \ + int retl = 0; \ + int cont = 0; \ + uint64_t rwr_lock_start = UtilCpuGetTicks(); \ + if (pthread_rwlock_tryrdlock((mut)) != 0) { \ + rwr_lock_contention++; \ + cont = 1; \ + retl = pthread_rwlock_rdlock(mut); \ + } \ + uint64_t rwr_lock_end = UtilCpuGetTicks(); \ + rwr_lock_wait_ticks += (uint64_t)(rwr_lock_end - rwr_lock_start); \ + \ + if (locks_idx < PROFILING_MAX_LOCKS && record_locks) { \ + locks[locks_idx].file = (char *)__FILE__; \ + locks[locks_idx].func = (char *)__func__; \ + locks[locks_idx].line = (int)__LINE__; \ + locks[locks_idx].type = LOCK_RWR; \ + locks[locks_idx].cont = cont; \ + locks[locks_idx].ticks = (uint64_t)(rwr_lock_end - rwr_lock_start); \ + locks_idx++; \ + } \ + retl; \ + }) + +#define SCRWLock pthread_rwlock_t +#define SCRWLockInit(rwl, rwlattr) pthread_rwlock_init(rwl, rwlattr) +#define SCRWLockWRLock(mut) SCRWLockWRLock_profile(mut) +#define SCRWLockRDLock(mut) SCRWLockRDLock_profile(mut) +#define SCRWLockTryWRLock(rwl) pthread_rwlock_trywrlock(rwl) +#define SCRWLockTryRDLock(rwl) pthread_rwlock_tryrdlock(rwl) +#define SCRWLockUnlock(rwl) pthread_rwlock_unlock(rwl) +#define SCRWLockDestroy pthread_rwlock_destroy /* ctrl mutex */ -#define SCCtrlMutex pthread_mutex_t -#define SCCtrlMutexAttr pthread_mutexattr_t -#define SCCtrlMutexInit(mut, mutattr ) pthread_mutex_init(mut, mutattr) -#define SCCtrlMutexLock(mut) pthread_mutex_lock(mut) -#define SCCtrlMutexTrylock(mut) pthread_mutex_trylock(mut) -#define SCCtrlMutexUnlock(mut) pthread_mutex_unlock(mut) -#define SCCtrlMutexDestroy pthread_mutex_destroy +#define SCCtrlMutex pthread_mutex_t +#define SCCtrlMutexAttr pthread_mutexattr_t +#define SCCtrlMutexInit(mut, mutattr) pthread_mutex_init(mut, mutattr) +#define SCCtrlMutexLock(mut) pthread_mutex_lock(mut) +#define SCCtrlMutexTrylock(mut) pthread_mutex_trylock(mut) +#define SCCtrlMutexUnlock(mut) pthread_mutex_unlock(mut) +#define SCCtrlMutexDestroy pthread_mutex_destroy /* ctrl conditions */ -#define SCCtrlCondT pthread_cond_t -#define SCCtrlCondInit pthread_cond_init -#define SCCtrlCondSignal pthread_cond_signal +#define SCCtrlCondT pthread_cond_t +#define SCCtrlCondInit pthread_cond_init +#define SCCtrlCondSignal pthread_cond_signal #define SCCtrlCondTimedwait pthread_cond_timedwait -#define SCCtrlCondWait pthread_cond_wait -#define SCCtrlCondDestroy pthread_cond_destroy +#define SCCtrlCondWait pthread_cond_wait +#define SCCtrlCondDestroy pthread_cond_destroy #endif diff --git a/src/threads.c b/src/threads.c index 1708a8f5cd37..1b082eb3bde3 100644 --- a/src/threads.c +++ b/src/threads.c @@ -41,11 +41,11 @@ static int ThreadMacrosTest01Mutex(void) int r = 0; r |= SCMutexInit(&mut, NULL); r |= SCMutexLock(&mut); - r |= (SCMutexTrylock(&mut) == EBUSY)? 0 : 1; + r |= (SCMutexTrylock(&mut) == EBUSY) ? 0 : 1; r |= SCMutexUnlock(&mut); r |= SCMutexDestroy(&mut); - return (r == 0)? 1 : 0; + return (r == 0) ? 1 : 0; } /** @@ -70,14 +70,14 @@ static int ThreadMacrosTest02Spinlocks(void) r |= SCSpinInit(&mut, 0); r |= SCSpinLock(&mut); #ifndef __OpenBSD__ - r |= (SCSpinTrylock(&mut) == EBUSY)? 0 : 1; + r |= (SCSpinTrylock(&mut) == EBUSY) ? 0 : 1; #else - r |= (SCSpinTrylock(&mut) == EDEADLK)? 0 : 1; + r |= (SCSpinTrylock(&mut) == EDEADLK) ? 0 : 1; #endif r |= SCSpinUnlock(&mut); r |= SCSpinDestroy(&mut); - return (r == 0)? 1 : 0; + return (r == 0) ? 1 : 0; } /** @@ -91,15 +91,15 @@ static int ThreadMacrosTest03RWLocks(void) r |= SCRWLockWRLock(&rwl_write); /* OS X/macOS 10.10 (Yosemite) and newer return EDEADLK. Older versions * and other tested OS's return EBUSY. */ -#if __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__>=101000 - r |= (SCRWLockTryWRLock(&rwl_write) == EDEADLK)? 0 : 1; +#if __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ >= 101000 + r |= (SCRWLockTryWRLock(&rwl_write) == EDEADLK) ? 0 : 1; #else - r |= (SCRWLockTryWRLock(&rwl_write) == EBUSY)? 0 : 1; + r |= (SCRWLockTryWRLock(&rwl_write) == EBUSY) ? 0 : 1; #endif r |= SCRWLockUnlock(&rwl_write); r |= SCRWLockDestroy(&rwl_write); - return (r == 0)? 1 : 0; + return (r == 0) ? 1 : 0; } /** @@ -111,11 +111,11 @@ static int ThreadMacrosTest04RWLocks(void) int r = 0; r |= SCRWLockInit(&rwl_read, NULL); r |= SCRWLockRDLock(&rwl_read); - r |= (SCRWLockTryWRLock(&rwl_read) == EBUSY)? 0 : 1; + r |= (SCRWLockTryWRLock(&rwl_read) == EBUSY) ? 0 : 1; r |= SCRWLockUnlock(&rwl_read); r |= SCRWLockDestroy(&rwl_read); - return (r == 0)? 1 : 0; + return (r == 0) ? 1 : 0; } #if 0 // broken on OSX diff --git a/src/threads.h b/src/threads.h index a9942b9746fb..c4235db45646 100644 --- a/src/threads.h +++ b/src/threads.h @@ -48,7 +48,7 @@ #if defined OS_FREEBSD || __OpenBSD__ -#if ! defined __OpenBSD__ +#if !defined __OpenBSD__ #include #endif enum { @@ -104,108 +104,106 @@ enum { //#define DBG_THREADS #if defined DBG_THREADS - #ifdef PROFILE_LOCKING - #error "Cannot mix DBG_THREADS and PROFILE_LOCKING" - #endif - #include "threads-debug.h" +#ifdef PROFILE_LOCKING +#error "Cannot mix DBG_THREADS and PROFILE_LOCKING" +#endif +#include "threads-debug.h" #elif defined PROFILE_LOCKING - #include "threads-profile.h" +#include "threads-profile.h" #else /* normal */ /* mutex */ -#define SCMutex pthread_mutex_t -#define SCMutexAttr pthread_mutexattr_t -#define SCMutexInit(mut, mutattr ) pthread_mutex_init(mut, mutattr) -#define SCMutexLock(mut) pthread_mutex_lock(mut) -#define SCMutexTrylock(mut) pthread_mutex_trylock(mut) -#define SCMutexUnlock(mut) pthread_mutex_unlock(mut) -#define SCMutexDestroy pthread_mutex_destroy -#define SCMUTEX_INITIALIZER PTHREAD_MUTEX_INITIALIZER +#define SCMutex pthread_mutex_t +#define SCMutexAttr pthread_mutexattr_t +#define SCMutexInit(mut, mutattr) pthread_mutex_init(mut, mutattr) +#define SCMutexLock(mut) pthread_mutex_lock(mut) +#define SCMutexTrylock(mut) pthread_mutex_trylock(mut) +#define SCMutexUnlock(mut) pthread_mutex_unlock(mut) +#define SCMutexDestroy pthread_mutex_destroy +#define SCMUTEX_INITIALIZER PTHREAD_MUTEX_INITIALIZER /* rwlocks */ -#define SCRWLock pthread_rwlock_t -#define SCRWLockInit(rwl, rwlattr ) pthread_rwlock_init(rwl, rwlattr) -#define SCRWLockWRLock(rwl) pthread_rwlock_wrlock(rwl) -#define SCRWLockRDLock(rwl) pthread_rwlock_rdlock(rwl) -#define SCRWLockTryWRLock(rwl) pthread_rwlock_trywrlock(rwl) -#define SCRWLockTryRDLock(rwl) pthread_rwlock_tryrdlock(rwl) -#define SCRWLockUnlock(rwl) pthread_rwlock_unlock(rwl) -#define SCRWLockDestroy pthread_rwlock_destroy +#define SCRWLock pthread_rwlock_t +#define SCRWLockInit(rwl, rwlattr) pthread_rwlock_init(rwl, rwlattr) +#define SCRWLockWRLock(rwl) pthread_rwlock_wrlock(rwl) +#define SCRWLockRDLock(rwl) pthread_rwlock_rdlock(rwl) +#define SCRWLockTryWRLock(rwl) pthread_rwlock_trywrlock(rwl) +#define SCRWLockTryRDLock(rwl) pthread_rwlock_tryrdlock(rwl) +#define SCRWLockUnlock(rwl) pthread_rwlock_unlock(rwl) +#define SCRWLockDestroy pthread_rwlock_destroy /* conditions */ -#define SCCondT pthread_cond_t -#define SCCondInit pthread_cond_init -#define SCCondSignal pthread_cond_signal -#define SCCondDestroy pthread_cond_destroy -#define SCCondWait(cond, mut) pthread_cond_wait(cond, mut) +#define SCCondT pthread_cond_t +#define SCCondInit pthread_cond_init +#define SCCondSignal pthread_cond_signal +#define SCCondDestroy pthread_cond_destroy +#define SCCondWait(cond, mut) pthread_cond_wait(cond, mut) /* ctrl mutex */ -#define SCCtrlMutex pthread_mutex_t -#define SCCtrlMutexAttr pthread_mutexattr_t -#define SCCtrlMutexInit(mut, mutattr ) pthread_mutex_init(mut, mutattr) -#define SCCtrlMutexLock(mut) pthread_mutex_lock(mut) -#define SCCtrlMutexTrylock(mut) pthread_mutex_trylock(mut) -#define SCCtrlMutexUnlock(mut) pthread_mutex_unlock(mut) -#define SCCtrlMutexDestroy pthread_mutex_destroy +#define SCCtrlMutex pthread_mutex_t +#define SCCtrlMutexAttr pthread_mutexattr_t +#define SCCtrlMutexInit(mut, mutattr) pthread_mutex_init(mut, mutattr) +#define SCCtrlMutexLock(mut) pthread_mutex_lock(mut) +#define SCCtrlMutexTrylock(mut) pthread_mutex_trylock(mut) +#define SCCtrlMutexUnlock(mut) pthread_mutex_unlock(mut) +#define SCCtrlMutexDestroy pthread_mutex_destroy /* ctrl conditions */ -#define SCCtrlCondT pthread_cond_t -#define SCCtrlCondInit pthread_cond_init -#define SCCtrlCondSignal pthread_cond_signal -#define SCCtrlCondTimedwait pthread_cond_timedwait -#define SCCtrlCondWait pthread_cond_wait -#define SCCtrlCondDestroy pthread_cond_destroy +#define SCCtrlCondT pthread_cond_t +#define SCCtrlCondInit pthread_cond_init +#define SCCtrlCondSignal pthread_cond_signal +#define SCCtrlCondTimedwait pthread_cond_timedwait +#define SCCtrlCondWait pthread_cond_wait +#define SCCtrlCondDestroy pthread_cond_destroy /* spinlocks */ #if ((_POSIX_SPIN_LOCKS - 200112L) < 0L) || defined HELGRIND || !defined(HAVE_PTHREAD_SPIN_UNLOCK) -#define SCSpinlock SCMutex -#define SCSpinLock(spin) SCMutexLock((spin)) -#define SCSpinTrylock(spin) SCMutexTrylock((spin)) -#define SCSpinUnlock(spin) SCMutexUnlock((spin)) -#define SCSpinInit(spin, spin_attr) SCMutexInit((spin), NULL) -#define SCSpinDestroy(spin) SCMutexDestroy((spin)) +#define SCSpinlock SCMutex +#define SCSpinLock(spin) SCMutexLock((spin)) +#define SCSpinTrylock(spin) SCMutexTrylock((spin)) +#define SCSpinUnlock(spin) SCMutexUnlock((spin)) +#define SCSpinInit(spin, spin_attr) SCMutexInit((spin), NULL) +#define SCSpinDestroy(spin) SCMutexDestroy((spin)) #else /* no spinlocks */ -#define SCSpinlock pthread_spinlock_t -#define SCSpinLock(spin) pthread_spin_lock(spin) -#define SCSpinTrylock(spin) pthread_spin_trylock(spin) -#define SCSpinUnlock(spin) pthread_spin_unlock(spin) -#define SCSpinInit(spin, spin_attr) pthread_spin_init(spin, spin_attr) -#define SCSpinDestroy(spin) pthread_spin_destroy(spin) +#define SCSpinlock pthread_spinlock_t +#define SCSpinLock(spin) pthread_spin_lock(spin) +#define SCSpinTrylock(spin) pthread_spin_trylock(spin) +#define SCSpinUnlock(spin) pthread_spin_unlock(spin) +#define SCSpinInit(spin, spin_attr) pthread_spin_init(spin, spin_attr) +#define SCSpinDestroy(spin) pthread_spin_destroy(spin) #endif /* no spinlocks */ #endif -#if (!defined SCMutex || !defined SCMutexAttr || !defined SCMutexInit || \ - !defined SCMutexLock || !defined SCMutexTrylock || \ - !defined SCMutexUnlock || !defined SCMutexDestroy || \ - !defined SCMUTEX_INITIALIZER) +#if (!defined SCMutex || !defined SCMutexAttr || !defined SCMutexInit || !defined SCMutexLock || \ + !defined SCMutexTrylock || !defined SCMutexUnlock || !defined SCMutexDestroy || \ + !defined SCMUTEX_INITIALIZER) #error "Mutex types and/or macro's not properly defined" #endif -#if (!defined SCCtrlMutex || !defined SCCtrlMutexAttr || !defined SCCtrlMutexInit || \ - !defined SCCtrlMutexLock || !defined SCCtrlMutexTrylock || \ - !defined SCCtrlMutexUnlock || !defined SCCtrlMutexDestroy) +#if (!defined SCCtrlMutex || !defined SCCtrlMutexAttr || !defined SCCtrlMutexInit || \ + !defined SCCtrlMutexLock || !defined SCCtrlMutexTrylock || !defined SCCtrlMutexUnlock || \ + !defined SCCtrlMutexDestroy) #error "SCCtrlMutex types and/or macro's not properly defined" #endif -#if (!defined SCSpinlock || !defined SCSpinLock || \ - !defined SCSpinTrylock || !defined SCSpinUnlock || \ - !defined SCSpinInit || !defined SCSpinDestroy) +#if (!defined SCSpinlock || !defined SCSpinLock || !defined SCSpinTrylock || \ + !defined SCSpinUnlock || !defined SCSpinInit || !defined SCSpinDestroy) #error "Spinlock types and/or macro's not properly defined" #endif -#if (!defined SCRWLock || !defined SCRWLockInit || !defined SCRWLockWRLock || \ - !defined SCRWLockRDLock || !defined SCRWLockTryWRLock || \ - !defined SCRWLockTryRDLock || !defined SCRWLockUnlock || !defined SCRWLockDestroy) +#if (!defined SCRWLock || !defined SCRWLockInit || !defined SCRWLockWRLock || \ + !defined SCRWLockRDLock || !defined SCRWLockTryWRLock || !defined SCRWLockTryRDLock || \ + !defined SCRWLockUnlock || !defined SCRWLockDestroy) #error "SCRWLock types and/or macro's not properly defined" #endif -#if (!defined SCCondT || !defined SCCondInit || !defined SCCondSignal || \ - !defined SCCondDestroy || !defined SCCondWait) +#if (!defined SCCondT || !defined SCCondInit || !defined SCCondSignal || !defined SCCondDestroy || \ + !defined SCCondWait) #error "SCCond types and/or macro's not properly defined" #endif -#if (!defined SCCtrlCondT || !defined SCCtrlCondInit || !defined SCCtrlCondSignal ||\ - !defined SCCtrlCondDestroy || !defined SCCtrlCondTimedwait) +#if (!defined SCCtrlCondT || !defined SCCtrlCondInit || !defined SCCtrlCondSignal || \ + !defined SCCtrlCondDestroy || !defined SCCtrlCondTimedwait) #error "SCCtrlCond types and/or macro's not properly defined" #endif @@ -213,51 +211,58 @@ enum { #ifdef OS_FREEBSD #include -#define SCGetThreadIdLong(...) ({ \ - long tmpthid; \ - thr_self(&tmpthid); \ - unsigned long _scgetthread_tid = (unsigned long)tmpthid; \ - _scgetthread_tid; \ -}) +#define SCGetThreadIdLong(...) \ + ({ \ + long tmpthid; \ + thr_self(&tmpthid); \ + unsigned long _scgetthread_tid = (unsigned long)tmpthid; \ + _scgetthread_tid; \ + }) #elif __OpenBSD__ -#define SCGetThreadIdLong(...) ({ \ - pid_t tpid; \ - tpid = getpid(); \ - unsigned long _scgetthread_tid = (unsigned long)tpid; \ - _scgetthread_tid; \ -}) +#define SCGetThreadIdLong(...) \ + ({ \ + pid_t tpid; \ + tpid = getpid(); \ + unsigned long _scgetthread_tid = (unsigned long)tpid; \ + _scgetthread_tid; \ + }) #elif __CYGWIN__ -#define SCGetThreadIdLong(...) ({ \ - unsigned long _scgetthread_tid = (unsigned long)GetCurrentThreadId(); \ - _scgetthread_tid; \ -}) +#define SCGetThreadIdLong(...) \ + ({ \ + unsigned long _scgetthread_tid = (unsigned long)GetCurrentThreadId(); \ + _scgetthread_tid; \ + }) #elif OS_WIN32 -#define SCGetThreadIdLong(...) ({ \ - unsigned long _scgetthread_tid = (unsigned long)GetCurrentThreadId(); \ - _scgetthread_tid; \ -}) +#define SCGetThreadIdLong(...) \ + ({ \ + unsigned long _scgetthread_tid = (unsigned long)GetCurrentThreadId(); \ + _scgetthread_tid; \ + }) #elif OS_DARWIN -#define SCGetThreadIdLong(...) ({ \ - thread_port_t tpid; \ - tpid = mach_thread_self(); \ - unsigned long _scgetthread_tid = (unsigned long)tpid; \ - _scgetthread_tid; \ -}) +#define SCGetThreadIdLong(...) \ + ({ \ + thread_port_t tpid; \ + tpid = mach_thread_self(); \ + unsigned long _scgetthread_tid = (unsigned long)tpid; \ + _scgetthread_tid; \ + }) #elif defined(sun) #include -#define SCGetThreadIdLong(...) ({ \ - thread_t tmpthid = thr_self(); \ - unsigned long _scgetthread_tid = (unsigned long)tmpthid; \ - _scgetthread_tid; \ -}) +#define SCGetThreadIdLong(...) \ + ({ \ + thread_t tmpthid = thr_self(); \ + unsigned long _scgetthread_tid = (unsigned long)tmpthid; \ + _scgetthread_tid; \ + }) #else -#define SCGetThreadIdLong(...) ({ \ - pid_t tmpthid; \ - tmpthid = syscall(SYS_gettid); \ - unsigned long _scgetthread_tid = (unsigned long)tmpthid; \ - _scgetthread_tid; \ -}) +#define SCGetThreadIdLong(...) \ + ({ \ + pid_t tmpthid; \ + tmpthid = syscall(SYS_gettid); \ + unsigned long _scgetthread_tid = (unsigned long)tmpthid; \ + _scgetthread_tid; \ + }) #endif /* OS FREEBSD */ extern thread_local char t_thread_name[THREAD_NAME_LEN + 1]; @@ -305,8 +310,6 @@ extern thread_local char t_thread_name[THREAD_NAME_LEN + 1]; } #endif - void ThreadMacrosRegisterTests(void); #endif /* __THREADS_H__ */ - diff --git a/src/threadvars.h b/src/threadvars.h index ea448c094986..3d61079586ff 100644 --- a/src/threadvars.h +++ b/src/threadvars.h @@ -32,27 +32,28 @@ struct TmSlot_; /** Thread flags set and read by threads to control the threads */ -#define THV_USE BIT_U32(0) /** thread is in use */ -#define THV_INIT_DONE BIT_U32(1) /** thread initialization done */ -#define THV_PAUSE BIT_U32(2) /** signal thread to pause itself */ -#define THV_PAUSED BIT_U32(3) /** the thread is paused atm */ -#define THV_KILL BIT_U32(4) /** thread has been asked to cleanup and exit */ -#define THV_FAILED BIT_U32(5) /** thread has encountered an error and failed */ -#define THV_CLOSED BIT_U32(6) /** thread done, should be joinable */ +#define THV_USE BIT_U32(0) /** thread is in use */ +#define THV_INIT_DONE BIT_U32(1) /** thread initialization done */ +#define THV_PAUSE BIT_U32(2) /** signal thread to pause itself */ +#define THV_PAUSED BIT_U32(3) /** the thread is paused atm */ +#define THV_KILL BIT_U32(4) /** thread has been asked to cleanup and exit */ +#define THV_FAILED BIT_U32(5) /** thread has encountered an error and failed */ +#define THV_CLOSED BIT_U32(6) /** thread done, should be joinable */ /* used to indicate the thread is going through de-init. Introduced as more * of a hack for solving stream-timeout-shutdown. Is set by the main thread. */ -#define THV_DEINIT BIT_U32(7) -#define THV_RUNNING_DONE BIT_U32(8) /** thread has completed running and is entering - * the de-init phase */ -#define THV_KILL_PKTACQ BIT_U32(9) /**< flag thread to stop packet acq */ -#define THV_FLOW_LOOP BIT_U32(10) /**< thread is in flow shutdown loop */ +#define THV_DEINIT BIT_U32(7) +#define THV_RUNNING_DONE \ + BIT_U32(8) /** thread has completed running and is entering \ + * the de-init phase */ +#define THV_KILL_PKTACQ BIT_U32(9) /**< flag thread to stop packet acq */ +#define THV_FLOW_LOOP BIT_U32(10) /**< thread is in flow shutdown loop */ /** signal thread's capture method to create a fake packet to force through * the engine. This is to force timely handling of maintenance tasks like * rule reloads even if no packets are read by the capture method. */ -#define THV_CAPTURE_INJECT_PKT BIT_U32(11) -#define THV_DEAD BIT_U32(12) /**< thread has been joined with pthread_join() */ -#define THV_RUNNING BIT_U32(13) /**< thread is running */ +#define THV_CAPTURE_INJECT_PKT BIT_U32(11) +#define THV_DEAD BIT_U32(12) /**< thread has been joined with pthread_join() */ +#define THV_RUNNING BIT_U32(13) /**< thread is running */ /** \brief Per thread variable structure */ typedef struct ThreadVars_ { @@ -72,8 +73,7 @@ typedef struct ThreadVars_ { uint8_t type; uint16_t cpu_affinity; /** cpu or core number to set affinity to */ - int thread_priority; /** priority (real time) for this thread. Look at threads.h */ - + int thread_priority; /** priority (real time) for this thread. Look at threads.h */ /** TmModule::flags for each module part of this thread */ uint8_t tmm_flags; @@ -88,7 +88,7 @@ typedef struct ThreadVars_ { /** incoming queue and handler */ Tmq *inq; - struct Packet_ * (*tmqh_in)(struct ThreadVars_ *); + struct Packet_ *(*tmqh_in)(struct ThreadVars_ *); SC_ATOMIC_DECLARE(uint32_t, flags); @@ -138,8 +138,8 @@ typedef struct ThreadVars_ { } ThreadVars; /** Thread setup flags: */ -#define THREAD_SET_AFFINITY 0x01 /** CPU/Core affinity */ -#define THREAD_SET_PRIORITY 0x02 /** Real time priority */ -#define THREAD_SET_AFFTYPE 0x04 /** Priority and affinity */ +#define THREAD_SET_AFFINITY 0x01 /** CPU/Core affinity */ +#define THREAD_SET_PRIORITY 0x02 /** Real time priority */ +#define THREAD_SET_AFFTYPE 0x04 /** Priority and affinity */ #endif /* __THREADVARS_H__ */ diff --git a/src/tm-modules.c b/src/tm-modules.c index 8f6082a91a60..eb1c9a5cbb96 100644 --- a/src/tm-modules.c +++ b/src/tm-modules.c @@ -125,7 +125,6 @@ int TmModuleGetIDForTM(TmModule *tm) return -1; } - void TmModuleRunInit(void) { TmModule *t; @@ -177,7 +176,6 @@ void TmModuleRegisterTests(void) g_ut_modules++; - if (t->RegisterTests == NULL) { if (coverage_unittests) SCLogWarning("threading module %s has no unittest " @@ -192,7 +190,9 @@ void TmModuleRegisterTests(void) } #ifdef PROFILING -#define CASE_CODE(E) case E: return #E +#define CASE_CODE(E) \ + case E: \ + return #E /** * \brief Maps the TmmId, to its string equivalent @@ -201,53 +201,53 @@ void TmModuleRegisterTests(void) * * \retval string equivalent for the tmm id */ -const char * TmModuleTmmIdToString(TmmId id) +const char *TmModuleTmmIdToString(TmmId id) { switch (id) { - CASE_CODE (TMM_FLOWWORKER); - CASE_CODE (TMM_RECEIVENFLOG); - CASE_CODE (TMM_DECODENFLOG); - CASE_CODE (TMM_DECODENFQ); - CASE_CODE (TMM_VERDICTNFQ); - CASE_CODE (TMM_RECEIVENFQ); - CASE_CODE (TMM_RECEIVEPCAP); - CASE_CODE (TMM_RECEIVEPCAPFILE); - CASE_CODE (TMM_DECODEPCAP); - CASE_CODE (TMM_DECODEPCAPFILE); - CASE_CODE (TMM_RECEIVEPFRING); - CASE_CODE (TMM_DECODEPFRING); + CASE_CODE(TMM_FLOWWORKER); + CASE_CODE(TMM_RECEIVENFLOG); + CASE_CODE(TMM_DECODENFLOG); + CASE_CODE(TMM_DECODENFQ); + CASE_CODE(TMM_VERDICTNFQ); + CASE_CODE(TMM_RECEIVENFQ); + CASE_CODE(TMM_RECEIVEPCAP); + CASE_CODE(TMM_RECEIVEPCAPFILE); + CASE_CODE(TMM_DECODEPCAP); + CASE_CODE(TMM_DECODEPCAPFILE); + CASE_CODE(TMM_RECEIVEPFRING); + CASE_CODE(TMM_DECODEPFRING); CASE_CODE(TMM_RECEIVEDPDK); CASE_CODE(TMM_DECODEDPDK); - CASE_CODE (TMM_RECEIVEPLUGIN); - CASE_CODE (TMM_DECODEPLUGIN); - CASE_CODE (TMM_RESPONDREJECT); - CASE_CODE (TMM_DECODEIPFW); - CASE_CODE (TMM_VERDICTIPFW); - CASE_CODE (TMM_RECEIVEIPFW); - CASE_CODE (TMM_RECEIVEERFFILE); - CASE_CODE (TMM_DECODEERFFILE); - CASE_CODE (TMM_RECEIVEERFDAG); - CASE_CODE (TMM_DECODEERFDAG); - CASE_CODE (TMM_RECEIVENAPATECH); - CASE_CODE (TMM_DECODENAPATECH); - CASE_CODE (TMM_RECEIVEAFP); + CASE_CODE(TMM_RECEIVEPLUGIN); + CASE_CODE(TMM_DECODEPLUGIN); + CASE_CODE(TMM_RESPONDREJECT); + CASE_CODE(TMM_DECODEIPFW); + CASE_CODE(TMM_VERDICTIPFW); + CASE_CODE(TMM_RECEIVEIPFW); + CASE_CODE(TMM_RECEIVEERFFILE); + CASE_CODE(TMM_DECODEERFFILE); + CASE_CODE(TMM_RECEIVEERFDAG); + CASE_CODE(TMM_DECODEERFDAG); + CASE_CODE(TMM_RECEIVENAPATECH); + CASE_CODE(TMM_DECODENAPATECH); + CASE_CODE(TMM_RECEIVEAFP); CASE_CODE(TMM_RECEIVEAFXDP); - CASE_CODE (TMM_ALERTPCAPINFO); - CASE_CODE (TMM_DECODEAFP); + CASE_CODE(TMM_ALERTPCAPINFO); + CASE_CODE(TMM_DECODEAFP); CASE_CODE(TMM_DECODEAFXDP); - CASE_CODE (TMM_STATSLOGGER); - CASE_CODE (TMM_FLOWMANAGER); - CASE_CODE (TMM_FLOWRECYCLER); - CASE_CODE (TMM_BYPASSEDFLOWMANAGER); - CASE_CODE (TMM_UNIXMANAGER); - CASE_CODE (TMM_DETECTLOADER); - CASE_CODE (TMM_RECEIVENETMAP); - CASE_CODE (TMM_DECODENETMAP); - CASE_CODE (TMM_RECEIVEWINDIVERT); - CASE_CODE (TMM_VERDICTWINDIVERT); - CASE_CODE (TMM_DECODEWINDIVERT); - - CASE_CODE (TMM_SIZE); + CASE_CODE(TMM_STATSLOGGER); + CASE_CODE(TMM_FLOWMANAGER); + CASE_CODE(TMM_FLOWRECYCLER); + CASE_CODE(TMM_BYPASSEDFLOWMANAGER); + CASE_CODE(TMM_UNIXMANAGER); + CASE_CODE(TMM_DETECTLOADER); + CASE_CODE(TMM_RECEIVENETMAP); + CASE_CODE(TMM_DECODENETMAP); + CASE_CODE(TMM_RECEIVEWINDIVERT); + CASE_CODE(TMM_VERDICTWINDIVERT); + CASE_CODE(TMM_DECODEWINDIVERT); + + CASE_CODE(TMM_SIZE); } return ""; } diff --git a/src/tm-modules.h b/src/tm-modules.h index 4642ff46a6ca..4ec6906724b8 100644 --- a/src/tm-modules.h +++ b/src/tm-modules.h @@ -28,13 +28,13 @@ #include "threadvars.h" /* thread flags */ -#define TM_FLAG_RECEIVE_TM 0x01 -#define TM_FLAG_DECODE_TM 0x02 -#define TM_FLAG_STREAM_TM 0x04 -#define TM_FLAG_DETECT_TM 0x08 -#define TM_FLAG_LOGAPI_TM 0x10 /**< TM is run by Log API */ -#define TM_FLAG_MANAGEMENT_TM 0x20 -#define TM_FLAG_COMMAND_TM 0x40 +#define TM_FLAG_RECEIVE_TM 0x01 +#define TM_FLAG_DECODE_TM 0x02 +#define TM_FLAG_STREAM_TM 0x04 +#define TM_FLAG_DETECT_TM 0x08 +#define TM_FLAG_LOGAPI_TM 0x10 /**< TM is run by Log API */ +#define TM_FLAG_MANAGEMENT_TM 0x20 +#define TM_FLAG_COMMAND_TM 0x40 typedef TmEcode (*ThreadInitFunc)(ThreadVars *, const void *, void **); typedef TmEcode (*ThreadDeinitFunc)(ThreadVars *, void *); @@ -100,10 +100,9 @@ TmEcode TmModuleRegister(char *name, int (*module_func)(ThreadVars *, Packet *, void TmModuleDebugList(void); void TmModuleRegisterTests(void); #ifdef PROFILING -const char * TmModuleTmmIdToString(TmmId id); +const char *TmModuleTmmIdToString(TmmId id); #endif void TmModuleRunInit(void); void TmModuleRunDeInit(void); #endif /* __TM_MODULES_H__ */ - diff --git a/src/tm-queuehandlers.c b/src/tm-queuehandlers.c index 4850679ceb05..062b0277ebb6 100644 --- a/src/tm-queuehandlers.c +++ b/src/tm-queuehandlers.c @@ -36,7 +36,7 @@ Tmqh tmqh_table[TMQH_SIZE]; -void TmqhSetup (void) +void TmqhSetup(void) { memset(&tmqh_table, 0, sizeof(tmqh_table)); diff --git a/src/tm-queuehandlers.h b/src/tm-queuehandlers.h index eb0081bba66b..06d128427c22 100644 --- a/src/tm-queuehandlers.h +++ b/src/tm-queuehandlers.h @@ -45,11 +45,10 @@ typedef struct Tmqh_ { extern Tmqh tmqh_table[TMQH_SIZE]; -void TmqhSetup (void); +void TmqhSetup(void); void TmqhCleanup(void); int TmqhNameToID(const char *name); Tmqh *TmqhGetQueueHandlerByName(const char *name); Tmqh *TmqhGetQueueHandlerByID(const int id); #endif /* __TM_QUEUEHANDLERS_H__ */ - diff --git a/src/tm-queues.c b/src/tm-queues.c index e184ec9827db..3147909662d9 100644 --- a/src/tm-queues.c +++ b/src/tm-queues.c @@ -59,7 +59,7 @@ Tmq *TmqCreateQueue(const char *name) Tmq *TmqGetQueueByName(const char *name) { Tmq *tmq = NULL; - TAILQ_FOREACH(tmq, &tmq_list, next) { + TAILQ_FOREACH (tmq, &tmq_list, next) { if (strcmp(tmq->name, name) == 0) return tmq; } @@ -69,10 +69,11 @@ Tmq *TmqGetQueueByName(const char *name) void TmqDebugList(void) { Tmq *tmq = NULL; - TAILQ_FOREACH(tmq, &tmq_list, next) { + TAILQ_FOREACH (tmq, &tmq_list, next) { /* get a lock accessing the len */ SCMutexLock(&tmq->pq->mutex_q); - printf("TmqDebugList: id %" PRIu32 ", name \'%s\', len %" PRIu32 "\n", tmq->id, tmq->name, tmq->pq->len); + printf("TmqDebugList: id %" PRIu32 ", name \'%s\', len %" PRIu32 "\n", tmq->id, tmq->name, + tmq->pq->len); SCMutexUnlock(&tmq->pq->mutex_q); } } @@ -103,7 +104,7 @@ void TmValidateQueueState(void) bool err = false; Tmq *tmq = NULL; - TAILQ_FOREACH(tmq, &tmq_list, next) { + TAILQ_FOREACH (tmq, &tmq_list, next) { SCMutexLock(&tmq->pq->mutex_q); if (tmq->reader_cnt == 0) { SCLogError("queue \"%s\" doesn't have a reader (id %d max %u)", tmq->name, tmq->id, diff --git a/src/tm-queues.h b/src/tm-queues.h index a203b6662327..0713e80c9867 100644 --- a/src/tm-queues.h +++ b/src/tm-queues.h @@ -36,12 +36,11 @@ typedef struct Tmq_ { TAILQ_ENTRY(Tmq_) next; } Tmq; -Tmq* TmqCreateQueue(const char *name); -Tmq* TmqGetQueueByName(const char *name); +Tmq *TmqCreateQueue(const char *name); +Tmq *TmqGetQueueByName(const char *name); void TmqDebugList(void); void TmqResetQueues(void); void TmValidateQueueState(void); #endif /* __TM_QUEUES_H__ */ - diff --git a/src/tm-threads-common.h b/src/tm-threads-common.h index 47b501c0789e..5297d113d718 100644 --- a/src/tm-threads-common.h +++ b/src/tm-threads-common.h @@ -81,9 +81,9 @@ typedef enum { /*Error codes for the thread modules*/ typedef enum { - TM_ECODE_OK = 0, /**< Thread module exits OK*/ - TM_ECODE_FAILED, /**< Thread module exits due to failure*/ - TM_ECODE_DONE, /**< Thread module task is finished*/ + TM_ECODE_OK = 0, /**< Thread module exits OK*/ + TM_ECODE_FAILED, /**< Thread module exits due to failure*/ + TM_ECODE_DONE, /**< Thread module task is finished*/ } TmEcode; /* ThreadVars type */ @@ -95,4 +95,3 @@ enum { }; #endif /* __TM_THREADS_COMMON_H__ */ - diff --git a/src/tm-threads.c b/src/tm-threads.c index 10ef45da278f..7c57bfe36ef6 100644 --- a/src/tm-threads.c +++ b/src/tm-threads.c @@ -254,7 +254,7 @@ static void *TmThreadsSlotPktAcqLoop(void *td) " tmqh_out=%p", s, s ? s->PktAcqLoop : NULL, tv->tmqh_in, tv->tmqh_out); TmThreadsSetFlag(tv, THV_CLOSED | THV_RUNNING_DONE); - pthread_exit((void *) -1); + pthread_exit((void *)-1); return NULL; } @@ -283,10 +283,10 @@ static void *TmThreadsSlotPktAcqLoop(void *td) tv->flow_queue = FlowQueueNew(); if (tv->flow_queue == NULL) { TmThreadsSetFlag(tv, THV_CLOSED | THV_RUNNING_DONE); - pthread_exit((void *) -1); + pthread_exit((void *)-1); return NULL; } - /* setup a queue */ + /* setup a queue */ } else if (slot->tm_id == TMM_FLOWWORKER) { tv->stream_pq_local = SCCalloc(1, sizeof(PacketQueue)); if (tv->stream_pq_local == NULL) @@ -298,7 +298,7 @@ static void *TmThreadsSlotPktAcqLoop(void *td) tv->flow_queue = FlowQueueNew(); if (tv->flow_queue == NULL) { TmThreadsSetFlag(tv, THV_CLOSED | THV_RUNNING_DONE); - pthread_exit((void *) -1); + pthread_exit((void *)-1); return NULL; } } @@ -308,7 +308,7 @@ static void *TmThreadsSlotPktAcqLoop(void *td) TmThreadsSetFlag(tv, THV_INIT_DONE); - while(run) { + while (run) { if (TmThreadsCheckFlag(tv, THV_PAUSE)) { TmThreadsSetFlag(tv, THV_PAUSED); TmThreadTestThreadUnPaused(tv); @@ -357,12 +357,12 @@ static void *TmThreadsSlotPktAcqLoop(void *td) tv->stream_pq = NULL; SCLogDebug("%s ending", tv->name); TmThreadsSetFlag(tv, THV_CLOSED); - pthread_exit((void *) 0); + pthread_exit((void *)0); return NULL; error: tv->stream_pq = NULL; - pthread_exit((void *) -1); + pthread_exit((void *)-1); return NULL; } @@ -375,7 +375,7 @@ static void *TmThreadsSlotVar(void *td) TmEcode r = TM_ECODE_OK; CaptureStatsSetup(tv); - PacketPoolInit();//Empty(); + PacketPoolInit(); // Empty(); SCSetThreadName(tv->name); @@ -388,7 +388,7 @@ static void *TmThreadsSlotVar(void *td) /* check if we are setup properly */ if (s == NULL || tv->tmqh_in == NULL || tv->tmqh_out == NULL) { TmThreadsSetFlag(tv, THV_CLOSED | THV_RUNNING_DONE); - pthread_exit((void *) -1); + pthread_exit((void *)-1); return NULL; } @@ -414,10 +414,10 @@ static void *TmThreadsSlotVar(void *td) tv->flow_queue = FlowQueueNew(); if (tv->flow_queue == NULL) { TmThreadsSetFlag(tv, THV_CLOSED | THV_RUNNING_DONE); - pthread_exit((void *) -1); + pthread_exit((void *)-1); return NULL; } - /* setup a queue */ + /* setup a queue */ } else if (s->tm_id == TMM_FLOWWORKER) { tv->stream_pq_local = SCCalloc(1, sizeof(PacketQueue)); if (tv->stream_pq_local == NULL) @@ -429,7 +429,7 @@ static void *TmThreadsSlotVar(void *td) tv->flow_queue = FlowQueueNew(); if (tv->flow_queue == NULL) { TmThreadsSetFlag(tv, THV_CLOSED | THV_RUNNING_DONE); - pthread_exit((void *) -1); + pthread_exit((void *)-1); return NULL; } } @@ -495,7 +495,7 @@ static void *TmThreadsSlotVar(void *td) s = (TmSlot *)tv->tm_slots; - for ( ; s != NULL; s = s->slot_next) { + for (; s != NULL; s = s->slot_next) { if (s->SlotThreadExitPrintStats != NULL) { s->SlotThreadExitPrintStats(tv, SC_ATOMIC_GET(s->slot_data)); } @@ -512,12 +512,12 @@ static void *TmThreadsSlotVar(void *td) SCLogDebug("%s ending", tv->name); tv->stream_pq = NULL; TmThreadsSetFlag(tv, THV_CLOSED); - pthread_exit((void *) 0); + pthread_exit((void *)0); return NULL; error: tv->stream_pq = NULL; - pthread_exit((void *) -1); + pthread_exit((void *)-1); return NULL; } @@ -544,7 +544,7 @@ static void *TmThreadsManagement(void *td) r = s->SlotThreadInit(tv, s->slot_initdata, &slot_data); if (r != TM_ECODE_OK) { TmThreadsSetFlag(tv, THV_CLOSED | THV_RUNNING_DONE); - pthread_exit((void *) -1); + pthread_exit((void *)-1); return NULL; } (void)SC_ATOMIC_SET(s->slot_data, slot_data); @@ -575,13 +575,13 @@ static void *TmThreadsManagement(void *td) r = s->SlotThreadDeinit(tv, SC_ATOMIC_GET(s->slot_data)); if (r != TM_ECODE_OK) { TmThreadsSetFlag(tv, THV_CLOSED); - pthread_exit((void *) -1); + pthread_exit((void *)-1); return NULL; } } TmThreadsSetFlag(tv, THV_CLOSED); - pthread_exit((void *) 0); + pthread_exit((void *)0); return NULL; } @@ -673,8 +673,8 @@ void TmSlotSetFuncAppend(ThreadVars *tv, TmModule *tm, const void *data) TmSlot *a = (TmSlot *)tv->tm_slots, *b = NULL; /* get the last slot */ - for ( ; a != NULL; a = a->slot_next) { - b = a; + for (; a != NULL; a = a->slot_next) { + b = a; } /* append the new slot */ if (b != NULL) { @@ -688,19 +688,18 @@ void TmSlotSetFuncAppend(ThreadVars *tv, TmModule *tm, const void *data) static int SetCPUAffinitySet(cpu_set_t *cs) { #if defined OS_FREEBSD - int r = cpuset_setaffinity(CPU_LEVEL_WHICH, CPU_WHICH_TID, - SCGetThreadIdLong(), sizeof(cpu_set_t),cs); + int r = cpuset_setaffinity( + CPU_LEVEL_WHICH, CPU_WHICH_TID, SCGetThreadIdLong(), sizeof(cpu_set_t), cs); #elif OS_DARWIN - int r = thread_policy_set(mach_thread_self(), THREAD_AFFINITY_POLICY, - (void*)cs, THREAD_AFFINITY_POLICY_COUNT); + int r = thread_policy_set( + mach_thread_self(), THREAD_AFFINITY_POLICY, (void *)cs, THREAD_AFFINITY_POLICY_COUNT); #else pid_t tid = syscall(SYS_gettid); int r = sched_setaffinity(tid, sizeof(cpu_set_t), cs); #endif /* OS_FREEBSD */ if (r != 0) { - printf("Warning: sched_setaffinity failed (%" PRId32 "): %s\n", r, - strerror(errno)); + printf("Warning: sched_setaffinity failed (%" PRId32 "): %s\n", r, strerror(errno)); return -1; } @@ -708,7 +707,6 @@ static int SetCPUAffinitySet(cpu_set_t *cs) } #endif - /** * \brief Set the thread affinity on the calling thread. * @@ -728,12 +726,10 @@ static int SetCPUAffinity(uint16_t cpuid) int r = (0 == SetThreadAffinityMask(GetCurrentThread(), cs)); if (r != 0) { - printf("Warning: sched_setaffinity failed (%" PRId32 "): %s\n", r, - strerror(errno)); + printf("Warning: sched_setaffinity failed (%" PRId32 "): %s\n", r, strerror(errno)); return -1; } - SCLogDebug("CPU Affinity for thread %lu set to CPU %" PRId32, - SCGetThreadIdLong(), cpu); + SCLogDebug("CPU Affinity for thread %lu set to CPU %" PRId32, SCGetThreadIdLong(), cpu); return 0; @@ -748,7 +744,6 @@ static int SetCPUAffinity(uint16_t cpuid) #endif /* not supported */ } - /** * \brief Set the thread options (thread priority). * @@ -772,13 +767,12 @@ void TmThreadSetPrio(ThreadVars *tv) SCEnter(); #ifndef __CYGWIN__ #ifdef OS_WIN32 - if (0 == SetThreadPriority(GetCurrentThread(), tv->thread_priority)) { - SCLogError("Error setting priority for " - "thread %s: %s", - tv->name, strerror(errno)); + if (0 == SetThreadPriority(GetCurrentThread(), tv->thread_priority)) { + SCLogError("Error setting priority for " + "thread %s: %s", + tv->name, strerror(errno)); } else { - SCLogDebug("Priority set to %"PRId32" for thread %s", - tv->thread_priority, tv->name); + SCLogDebug("Priority set to %" PRId32 " for thread %s", tv->thread_priority, tv->name); } #else int ret = nice(tv->thread_priority); @@ -787,15 +781,13 @@ void TmThreadSetPrio(ThreadVars *tv) "for thread %s: %s", tv->thread_priority, tv->name, strerror(errno)); } else { - SCLogDebug("Nice value set to %"PRId32" for thread %s", - tv->thread_priority, tv->name); + SCLogDebug("Nice value set to %" PRId32 " for thread %s", tv->thread_priority, tv->name); } #endif /* OS_WIN32 */ #endif SCReturn; } - /** * \brief Set the thread options (cpu affinity). * @@ -812,7 +804,6 @@ TmEcode TmThreadSetCPUAffinity(ThreadVars *tv, uint16_t cpu) return TM_ECODE_OK; } - TmEcode TmThreadSetCPU(ThreadVars *tv, uint8_t type) { if (!threading_set_cpu_affinity) @@ -849,8 +840,8 @@ TmEcode TmThreadSetupOptions(ThreadVars *tv) { if (tv->thread_setup_flags & THREAD_SET_AFFINITY) { SCLogPerf("Setting affinity for thread \"%s\"to cpu/core " - "%"PRIu16", thread id %lu", tv->name, tv->cpu_affinity, - SCGetThreadIdLong()); + "%" PRIu16 ", thread id %lu", + tv->name, tv->cpu_affinity, SCGetThreadIdLong()); SetCPUAffinity(tv->cpu_affinity); } @@ -873,14 +864,14 @@ TmEcode TmThreadSetupOptions(ThreadVars *tv) tv->thread_priority = taf->prio; } SCLogPerf("Setting prio %d for thread \"%s\" to cpu/core " - "%d, thread id %lu", tv->thread_priority, - tv->name, cpu, SCGetThreadIdLong()); + "%d, thread id %lu", + tv->thread_priority, tv->name, cpu, SCGetThreadIdLong()); } else { SetCPUAffinitySet(&taf->cpu_set); tv->thread_priority = taf->prio; SCLogPerf("Setting prio %d for thread \"%s\", " - "thread id %lu", tv->thread_priority, - tv->name, SCGetThreadIdLong()); + "thread id %lu", + tv->thread_priority, tv->name, SCGetThreadIdLong()); } TmThreadSetPrio(tv); } @@ -905,8 +896,8 @@ TmEcode TmThreadSetupOptions(ThreadVars *tv) * \retval the newly created TV instance, or NULL on error */ ThreadVars *TmThreadCreate(const char *name, const char *inq_name, const char *inqh_name, - const char *outq_name, const char *outqh_name, const char *slots, - void * (*fn_p)(void *), int mucond) + const char *outq_name, const char *outqh_name, const char *slots, void *(*fn_p)(void *), + int mucond) { ThreadVars *tv = NULL; Tmq *tmq = NULL; @@ -1034,13 +1025,11 @@ ThreadVars *TmThreadCreate(const char *name, const char *inq_name, const char *i * \retval the newly created TV instance, or NULL on error */ ThreadVars *TmThreadCreatePacketHandler(const char *name, const char *inq_name, - const char *inqh_name, const char *outq_name, - const char *outqh_name, const char *slots) + const char *inqh_name, const char *outq_name, const char *outqh_name, const char *slots) { ThreadVars *tv = NULL; - tv = TmThreadCreate(name, inq_name, inqh_name, outq_name, outqh_name, - slots, NULL, 0); + tv = TmThreadCreate(name, inq_name, inqh_name, outq_name, outqh_name, slots, NULL, 0); if (tv != NULL) { tv->type = TVT_PPT; @@ -1062,8 +1051,7 @@ ThreadVars *TmThreadCreatePacketHandler(const char *name, const char *inq_name, * * \retval the newly created TV instance, or NULL on error */ -ThreadVars *TmThreadCreateMgmtThread(const char *name, void *(fn_p)(void *), - int mucond) +ThreadVars *TmThreadCreateMgmtThread(const char *name, void *(fn_p)(void *), int mucond) { ThreadVars *tv = NULL; @@ -1090,8 +1078,7 @@ ThreadVars *TmThreadCreateMgmtThread(const char *name, void *(fn_p)(void *), * * \retval the newly created TV instance, or NULL on error */ -ThreadVars *TmThreadCreateMgmtThreadByName(const char *name, const char *module, - int mucond) +ThreadVars *TmThreadCreateMgmtThreadByName(const char *name, const char *module, int mucond) { ThreadVars *tv = NULL; @@ -1123,8 +1110,7 @@ ThreadVars *TmThreadCreateMgmtThreadByName(const char *name, const char *module, * * \retval the newly created TV instance, or NULL on error */ -ThreadVars *TmThreadCreateCmdThreadByName(const char *name, const char *module, - int mucond) +ThreadVars *TmThreadCreateCmdThreadByName(const char *name, const char *module, int mucond) { ThreadVars *tv = NULL; @@ -1244,7 +1230,7 @@ static int TmThreadKillThread(ThreadVars *tv) SCLogDebug("signalled tv->inq->id %" PRIu32 "", tv->inq->id); } - if (tv->ctrl_cond != NULL ) { + if (tv->ctrl_cond != NULL) { pthread_cond_broadcast(tv->ctrl_cond); } return 0; @@ -1707,7 +1693,7 @@ TmEcode TmThreadSpawn(ThreadVars *tv) */ void TmThreadInitMC(ThreadVars *tv) { - if ( (tv->ctrl_mutex = SCMalloc(sizeof(*tv->ctrl_mutex))) == NULL) { + if ((tv->ctrl_mutex = SCMalloc(sizeof(*tv->ctrl_mutex))) == NULL) { FatalError("Fatal error encountered in TmThreadInitMC. " "Exiting..."); } @@ -1717,7 +1703,7 @@ void TmThreadInitMC(ThreadVars *tv) exit(EXIT_FAILURE); } - if ( (tv->ctrl_cond = SCMalloc(sizeof(*tv->ctrl_cond))) == NULL) { + if ((tv->ctrl_cond = SCMalloc(sizeof(*tv->ctrl_cond))) == NULL) { FatalError("Fatal error encountered in TmThreadInitMC. " "Exiting..."); } @@ -1948,7 +1934,7 @@ TmEcode TmThreadWaitOnThreadInit(void) for (int i = 0; i < TVT_MAX; i++) { ThreadVars *tv = tv_root[i]; while (tv != NULL) { - if (TmThreadsCheckFlag(tv, (THV_CLOSED|THV_DEAD))) { + if (TmThreadsCheckFlag(tv, (THV_CLOSED | THV_DEAD))) { SCMutexUnlock(&tv_root_lock); SCLogError("thread \"%s\" failed to " @@ -2022,8 +2008,7 @@ static void TmThreadDoDumpSlots(const ThreadVars *tv) { for (TmSlot *s = tv->tm_slots; s != NULL; s = s->slot_next) { TmModule *m = TmModuleGetById(s->tm_id); - SCLogNotice("tv %p: -> slot %p tm_id %d name %s", - tv, s, s->tm_id, m->name); + SCLogNotice("tv %p: -> slot %p tm_id %d name %s", tv, s, s->tm_id, m->name); } } @@ -2034,19 +2019,19 @@ static void TmThreadDumpThreads(void) ThreadVars *tv = tv_root[i]; while (tv != NULL) { const uint32_t flags = SC_ATOMIC_GET(tv->flags); - SCLogNotice("tv %p: type %u name %s tmm_flags %02X flags %X stream_pq %p", - tv, tv->type, tv->name, tv->tmm_flags, flags, tv->stream_pq); + SCLogNotice("tv %p: type %u name %s tmm_flags %02X flags %X stream_pq %p", tv, tv->type, + tv->name, tv->tmm_flags, flags, tv->stream_pq); if (tv->inq && tv->stream_pq == tv->inq->pq) { SCLogNotice("tv %p: stream_pq at tv->inq %u", tv, tv->inq->id); } else if (tv->stream_pq_local != NULL) { for (Packet *xp = tv->stream_pq_local->top; xp != NULL; xp = xp->next) { - SCLogNotice("tv %p: ==> stream_pq_local: pq.len %u packet src %s", - tv, tv->stream_pq_local->len, PktSrcToString(xp->pkt_src)); + SCLogNotice("tv %p: ==> stream_pq_local: pq.len %u packet src %s", tv, + tv->stream_pq_local->len, PktSrcToString(xp->pkt_src)); } } for (Packet *xp = tv->decode_pq.top; xp != NULL; xp = xp->next) { - SCLogNotice("tv %p: ==> decode_pq: decode_pq.len %u packet src %s", - tv, tv->decode_pq.len, PktSrcToString(xp->pkt_src)); + SCLogNotice("tv %p: ==> decode_pq: decode_pq.len %u packet src %s", tv, + tv->decode_pq.len, PktSrcToString(xp->pkt_src)); } TmThreadDoDumpSlots(tv); tv = tv->next; @@ -2058,10 +2043,10 @@ static void TmThreadDumpThreads(void) #endif typedef struct Thread_ { - ThreadVars *tv; /**< threadvars structure */ + ThreadVars *tv; /**< threadvars structure */ const char *name; int type; - int in_use; /**< bool to indicate this is in use */ + int in_use; /**< bool to indicate this is in use */ SCTime_t pktts; /**< current packet time of this thread * (offline mode) */ @@ -2086,13 +2071,13 @@ void TmThreadsListThreads(void) if (t == NULL || t->in_use == 0) continue; - SCLogNotice("Thread %"PRIuMAX", %s type %d, tv %p in_use %d", - (uintmax_t)s+1, t->name, t->type, t->tv, t->in_use); + SCLogNotice("Thread %" PRIuMAX ", %s type %d, tv %p in_use %d", (uintmax_t)s + 1, t->name, + t->type, t->tv, t->in_use); if (t->tv) { ThreadVars *tv = t->tv; const uint32_t flags = SC_ATOMIC_GET(tv->flags); - SCLogNotice("tv %p type %u name %s tmm_flags %02X flags %X", - tv, tv->type, tv->name, tv->tmm_flags, flags); + SCLogNotice("tv %p type %u name %s tmm_flags %02X flags %X", tv, tv->type, tv->name, + tv->tmm_flags, flags); } } SCMutexUnlock(&thread_store_lock); @@ -2121,15 +2106,17 @@ int TmThreadsRegisterThread(ThreadVars *tv, const int type) t->in_use = 1; SCMutexUnlock(&thread_store_lock); - return (int)(s+1); + return (int)(s + 1); } } /* if we get here the array is completely filled */ - void *newmem = SCRealloc(thread_store.threads, ((thread_store.threads_size + STEP) * sizeof(Thread))); + void *newmem = + SCRealloc(thread_store.threads, ((thread_store.threads_size + STEP) * sizeof(Thread))); BUG_ON(newmem == NULL); thread_store.threads = newmem; - memset((uint8_t *)thread_store.threads + (thread_store.threads_size * sizeof(Thread)), 0x00, STEP * sizeof(Thread)); + memset((uint8_t *)thread_store.threads + (thread_store.threads_size * sizeof(Thread)), 0x00, + STEP * sizeof(Thread)); Thread *t = &thread_store.threads[thread_store.threads_size]; t->name = tv->name; @@ -2141,7 +2128,7 @@ int TmThreadsRegisterThread(ThreadVars *tv, const int type) thread_store.threads_size += STEP; SCMutexUnlock(&thread_store_lock); - return (int)(s+1); + return (int)(s + 1); } #undef STEP @@ -2260,7 +2247,7 @@ void TmThreadsGetMinimalTimestamp(struct timeval *ts) } SCMutexUnlock(&thread_store_lock); *ts = local; - SCLogDebug("ts->tv_sec %"PRIuMAX, (uintmax_t)ts->tv_sec); + SCLogDebug("ts->tv_sec %" PRIuMAX, (uintmax_t)ts->tv_sec); } uint16_t TmThreadsGetWorkerThreadMax(void) diff --git a/src/tm-threads.h b/src/tm-threads.h index 4ca55f9bc72c..c5a6ecc0bf28 100644 --- a/src/tm-threads.h +++ b/src/tm-threads.h @@ -42,10 +42,10 @@ static inline void SleepUsec(uint64_t usec) #define SleepMsec(msec) Sleep((msec)) #else #define SleepUsec(usec) usleep((usec)) -#define SleepMsec(msec) usleep((msec) * 1000) +#define SleepMsec(msec) usleep((msec)*1000) #endif -#define TM_QUEUE_NAME_MAX 16 +#define TM_QUEUE_NAME_MAX 16 #define TM_THREAD_NAME_MAX 16 typedef TmEcode (*TmSlotFunc)(ThreadVars *, Packet *, void *); @@ -84,15 +84,13 @@ extern SCMutex tv_root_lock; void TmSlotSetFuncAppend(ThreadVars *, TmModule *, const void *); -ThreadVars *TmThreadCreate(const char *, const char *, const char *, const char *, const char *, const char *, - void *(fn_p)(void *), int); -ThreadVars *TmThreadCreatePacketHandler(const char *, const char *, const char *, const char *, const char *, - const char *); +ThreadVars *TmThreadCreate(const char *, const char *, const char *, const char *, const char *, + const char *, void *(fn_p)(void *), int); +ThreadVars *TmThreadCreatePacketHandler( + const char *, const char *, const char *, const char *, const char *, const char *); ThreadVars *TmThreadCreateMgmtThread(const char *name, void *(fn_p)(void *), int); -ThreadVars *TmThreadCreateMgmtThreadByName(const char *name, const char *module, - int mucond); -ThreadVars *TmThreadCreateCmdThreadByName(const char *name, const char *module, - int mucond); +ThreadVars *TmThreadCreateMgmtThreadByName(const char *name, const char *module, int mucond); +ThreadVars *TmThreadCreateCmdThreadByName(const char *name, const char *module, int mucond); TmEcode TmThreadSpawn(ThreadVars *); void TmThreadKillThreadsFamily(int family); void TmThreadKillThreads(void); @@ -119,7 +117,7 @@ void TmThreadsSetFlag(ThreadVars *, uint32_t); void TmThreadsUnsetFlag(ThreadVars *, uint32_t); void TmThreadWaitForFlag(ThreadVars *, uint32_t); -TmEcode TmThreadsSlotVarRun (ThreadVars *tv, Packet *p, TmSlot *slot); +TmEcode TmThreadsSlotVarRun(ThreadVars *tv, Packet *p, TmSlot *slot); void TmThreadDisablePacketThreads(void); void TmThreadDisableReceiveThreads(void); diff --git a/src/tmqh-flow.c b/src/tmqh-flow.c index e11d05d71373..ffe50b6abed0 100644 --- a/src/tmqh-flow.c +++ b/src/tmqh-flow.c @@ -85,9 +85,9 @@ void TmqhFlowRegister(void) void TmqhFlowPrintAutofpHandler(void) { -#define PRINT_IF_FUNC(f, msg) \ - if (tmqh_table[TMQH_FLOW].OutHandler == (f)) \ - SCLogConfig("AutoFP mode using \"%s\" flow load balancer", (msg)) +#define PRINT_IF_FUNC(f, msg) \ + if (tmqh_table[TMQH_FLOW].OutHandler == (f)) \ + SCLogConfig("AutoFP mode using \"%s\" flow load balancer", (msg)) PRINT_IF_FUNC(TmqhOutputFlowHash, "Hash"); PRINT_IF_FUNC(TmqhOutputFlowIPPair, "IPPair"); @@ -183,16 +183,16 @@ void *TmqhOutputFlowSetupCtx(const char *queue_str) /* parse the comma separated string */ do { - char *comma = strchr(tstr,','); + char *comma = strchr(tstr, ','); if (comma != NULL) { *comma = '\0'; char *qname = tstr; - int r = StoreQueueId(ctx,qname); + int r = StoreQueueId(ctx, qname); if (r < 0) goto error; } else { char *qname = tstr; - int r = StoreQueueId(ctx,qname); + int r = StoreQueueId(ctx, qname); if (r < 0) goto error; } @@ -213,8 +213,7 @@ void TmqhOutputFlowFreeCtx(void *ctx) { TmqhFlowCtx *fctx = (TmqhFlowCtx *)ctx; - SCLogPerf("AutoFP - Total flow handler queues - %" PRIu16, - fctx->size); + SCLogPerf("AutoFP - Total flow handler queues - %" PRIu16, fctx->size); SCFree(fctx->queues); SCFree(fctx); @@ -406,12 +405,9 @@ static int TmqhOutputFlowSetupCtxTest03(void) void TmqhFlowRegisterTests(void) { #ifdef UNITTESTS - UtRegisterTest("TmqhOutputFlowSetupCtxTest01", - TmqhOutputFlowSetupCtxTest01); - UtRegisterTest("TmqhOutputFlowSetupCtxTest02", - TmqhOutputFlowSetupCtxTest02); - UtRegisterTest("TmqhOutputFlowSetupCtxTest03", - TmqhOutputFlowSetupCtxTest03); + UtRegisterTest("TmqhOutputFlowSetupCtxTest01", TmqhOutputFlowSetupCtxTest01); + UtRegisterTest("TmqhOutputFlowSetupCtxTest02", TmqhOutputFlowSetupCtxTest02); + UtRegisterTest("TmqhOutputFlowSetupCtxTest03", TmqhOutputFlowSetupCtxTest03); #endif return; diff --git a/src/tmqh-flow.h b/src/tmqh-flow.h index 3cec7a165f5b..7afcf58e8917 100644 --- a/src/tmqh-flow.h +++ b/src/tmqh-flow.h @@ -38,7 +38,7 @@ typedef struct TmqhFlowCtx_ { TmqhFlowMode *queues; } TmqhFlowCtx; -void TmqhFlowRegister (void); +void TmqhFlowRegister(void); void TmqhFlowRegisterTests(void); void TmqhFlowPrintAutofpHandler(void); diff --git a/src/tmqh-packetpool.c b/src/tmqh-packetpool.c index f71274b4502c..baa009d90093 100644 --- a/src/tmqh-packetpool.c +++ b/src/tmqh-packetpool.c @@ -52,7 +52,7 @@ static inline PktPool *GetThreadPacketPool(void) * \brief TmqhPacketpoolRegister * \initonly */ -void TmqhPacketpoolRegister (void) +void TmqhPacketpoolRegister(void) { tmqh_table[TMQH_PACKETPOOL].name = "packetpool"; tmqh_table[TMQH_PACKETPOOL].InHandler = TmqhInputPacketpool; @@ -91,7 +91,7 @@ void PacketPoolWait(void) UpdateReturnThreshold(my_pool); } - while(PacketPoolIsEmpty(my_pool)) + while (PacketPoolIsEmpty(my_pool)) cc_barrier(); } @@ -275,8 +275,7 @@ void PacketPoolInit(void) SC_ATOMIC_SET(my_pool->return_stack.return_threshold, 32); /* pre allocate packets */ - SCLogDebug("preallocating packets... packet size %" PRIuMAX "", - (uintmax_t)SIZE_OF_PACKET); + SCLogDebug("preallocating packets... packet size %" PRIuMAX "", (uintmax_t)SIZE_OF_PACKET); int i = 0; for (i = 0; i < max_pending_packets; i++) { Packet *p = PacketGetFromAlloc(); @@ -286,7 +285,7 @@ void PacketPoolInit(void) PacketPoolStorePacket(p); } - //SCLogInfo("preallocated %"PRIiMAX" packets. Total memory %"PRIuMAX"", + // SCLogInfo("preallocated %"PRIiMAX" packets. Total memory %"PRIuMAX"", // max_pending_packets, (uintmax_t)(max_pending_packets*SIZE_OF_PACKET)); } @@ -338,8 +337,7 @@ void TmqhOutputPacketpool(ThreadVars *t, Packet *p) SCLogDebug("Packet %p, p->root %p, alloced %s", p, p->root, BOOL2STR(p->pool == NULL)); if (IS_TUNNEL_PKT(p)) { - SCLogDebug("Packet %p is a tunnel packet: %s", - p,p->root ? "upper layer" : "tunnel root"); + SCLogDebug("Packet %p is a tunnel packet: %s", p, p->root ? "upper layer" : "tunnel root"); /* get a lock to access root packet fields */ SCSpinlock *lock = p->root ? &p->root->persistent.tunnel_lock : &p->persistent.tunnel_lock; @@ -353,15 +351,16 @@ void TmqhOutputPacketpool(ThreadVars *t, Packet *p) SCLogDebug("root pkt: outstanding %u", outstanding); if (outstanding == 0) { SCLogDebug("no tunnel packets outstanding, no more tunnel " - "packet(s) depending on this root"); + "packet(s) depending on this root"); /* if this packet is the root and there are no * more tunnel packets to consider * * return it to the pool */ } else { SCLogDebug("tunnel root Packet %p: outstanding > 0, so " - "packets are still depending on this root, setting " - "SET_TUNNEL_PKT_VERDICTED", p); + "packets are still depending on this root, setting " + "SET_TUNNEL_PKT_VERDICTED", + p); /* if this is the root and there are more tunnel * packets, return this to the pool. It's still referenced * by the tunnel packets, and we will return it @@ -381,14 +380,13 @@ void TmqhOutputPacketpool(ThreadVars *t, Packet *p) /* all tunnel packets are processed except us. Root already * processed. So return tunnel pkt and root packet to the * pool. */ - if (outstanding == 0 && - p->root && IS_TUNNEL_PKT_VERDICTED(p->root)) - { + if (outstanding == 0 && p->root && IS_TUNNEL_PKT_VERDICTED(p->root)) { SCLogDebug("root verdicted == true && no outstanding"); /* handle freeing the root as well*/ SCLogDebug("setting proot = 1 for root pkt, p->root %p " - "(tunnel packet %p)", p->root, p); + "(tunnel packet %p)", + p->root, p); proot = true; /* fall through */ @@ -398,7 +396,7 @@ void TmqhOutputPacketpool(ThreadVars *t, Packet *p) * so get rid of the tunnel pkt only */ SCLogDebug("NOT IS_TUNNEL_PKT_VERDICTED (%s) || " - "outstanding > 0 (%u)", + "outstanding > 0 (%u)", (p->root && IS_TUNNEL_PKT_VERDICTED(p->root)) ? "true" : "false", outstanding); @@ -500,6 +498,6 @@ void PacketPoolPostRunmodes(void) if (max_pending_return_packets >= RESERVED_PACKETS) max_pending_return_packets -= RESERVED_PACKETS; - SCLogDebug("detect threads %u, max packets %u, max_pending_return_packets %u", - threads, packets, max_pending_return_packets); + SCLogDebug("detect threads %u, max packets %u, max_pending_return_packets %u", threads, packets, + max_pending_return_packets); } diff --git a/src/tmqh-packetpool.h b/src/tmqh-packetpool.h index 74074f953378..67801a73984c 100644 --- a/src/tmqh-packetpool.h +++ b/src/tmqh-packetpool.h @@ -27,8 +27,8 @@ #include "decode.h" #include "threads.h" - /* Return stack, onto which other threads free packets. */ -typedef struct PktPoolLockedStack_{ +/* Return stack, onto which other threads free packets. */ +typedef struct PktPoolLockedStack_ { /* linked list of free packets. */ SCMutex mutex; SCCondT cond; diff --git a/src/tmqh-simple.c b/src/tmqh-simple.c index 47faed5702c5..672f85ff61db 100644 --- a/src/tmqh-simple.c +++ b/src/tmqh-simple.c @@ -36,7 +36,7 @@ Packet *TmqhInputSimple(ThreadVars *t); void TmqhOutputSimple(ThreadVars *t, Packet *p); void TmqhInputSimpleShutdownHandler(ThreadVars *); -void TmqhSimpleRegister (void) +void TmqhSimpleRegister(void) { tmqh_table[TMQH_SIMPLE].name = "simple"; tmqh_table[TMQH_SIMPLE].InHandler = TmqhInputSimple; @@ -91,4 +91,3 @@ void TmqhOutputSimple(ThreadVars *t, Packet *p) SCCondSignal(&q->cond_q); SCMutexUnlock(&q->mutex_q); } - diff --git a/src/tmqh-simple.h b/src/tmqh-simple.h index d80de5085203..a020ce379efe 100644 --- a/src/tmqh-simple.h +++ b/src/tmqh-simple.h @@ -24,6 +24,6 @@ #ifndef __TMQH_SIMPLE_H__ #define __TMQH_SIMPLE_H__ -void TmqhSimpleRegister (void); +void TmqhSimpleRegister(void); #endif /* __TMQH_SIMPLE_H__ */ diff --git a/src/tree.h b/src/tree.h index fd36955039d1..d3dcac26bd0f 100644 --- a/src/tree.h +++ b/src/tree.h @@ -29,8 +29,8 @@ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#ifndef _SYS_TREE_H_ -#define _SYS_TREE_H_ +#ifndef _SYS_TREE_H_ +#define _SYS_TREE_H_ #if defined(__clang_analyzer__) #define _T_ASSERT(a) assert((a)) @@ -65,749 +65,723 @@ * The maximum height of a red-black tree is 2lg (n+1). */ -#define SPLAY_HEAD(name, type) \ -struct name { \ - struct type *sph_root; /* root of the tree */ \ -} +#define SPLAY_HEAD(name, type) \ + struct name { \ + struct type *sph_root; /* root of the tree */ \ + } -#define SPLAY_INITIALIZER(root) \ - { NULL } +#define SPLAY_INITIALIZER(root) \ + { \ + NULL \ + } -#define SPLAY_INIT(root) do { \ - (root)->sph_root = NULL; \ -} while (/*CONSTCOND*/ 0) +#define SPLAY_INIT(root) \ + do { \ + (root)->sph_root = NULL; \ + } while (/*CONSTCOND*/ 0) -#define SPLAY_ENTRY(type) \ -struct { \ - struct type *spe_left; /* left element */ \ - struct type *spe_right; /* right element */ \ -} +#define SPLAY_ENTRY(type) \ + struct { \ + struct type *spe_left; /* left element */ \ + struct type *spe_right; /* right element */ \ + } -#define SPLAY_LEFT(elm, field) (elm)->field.spe_left -#define SPLAY_RIGHT(elm, field) (elm)->field.spe_right -#define SPLAY_ROOT(head) (head)->sph_root -#define SPLAY_EMPTY(head) (SPLAY_ROOT(head) == NULL) +#define SPLAY_LEFT(elm, field) (elm)->field.spe_left +#define SPLAY_RIGHT(elm, field) (elm)->field.spe_right +#define SPLAY_ROOT(head) (head)->sph_root +#define SPLAY_EMPTY(head) (SPLAY_ROOT(head) == NULL) /* SPLAY_ROTATE_{LEFT,RIGHT} expect that tmp hold SPLAY_{RIGHT,LEFT} */ -#define SPLAY_ROTATE_RIGHT(head, tmp, field) do { \ - SPLAY_LEFT((head)->sph_root, field) = SPLAY_RIGHT(tmp, field); \ - SPLAY_RIGHT(tmp, field) = (head)->sph_root; \ - (head)->sph_root = tmp; \ -} while (/*CONSTCOND*/ 0) - -#define SPLAY_ROTATE_LEFT(head, tmp, field) do { \ - SPLAY_RIGHT((head)->sph_root, field) = SPLAY_LEFT(tmp, field); \ - SPLAY_LEFT(tmp, field) = (head)->sph_root; \ - (head)->sph_root = tmp; \ -} while (/*CONSTCOND*/ 0) - -#define SPLAY_LINKLEFT(head, tmp, field) do { \ - SPLAY_LEFT(tmp, field) = (head)->sph_root; \ - tmp = (head)->sph_root; \ - (head)->sph_root = SPLAY_LEFT((head)->sph_root, field); \ -} while (/*CONSTCOND*/ 0) - -#define SPLAY_LINKRIGHT(head, tmp, field) do { \ - SPLAY_RIGHT(tmp, field) = (head)->sph_root; \ - tmp = (head)->sph_root; \ - (head)->sph_root = SPLAY_RIGHT((head)->sph_root, field); \ -} while (/*CONSTCOND*/ 0) - -#define SPLAY_ASSEMBLE(head, node, left, right, field) do { \ - SPLAY_RIGHT(left, field) = SPLAY_LEFT((head)->sph_root, field); \ - SPLAY_LEFT(right, field) = SPLAY_RIGHT((head)->sph_root, field);\ - SPLAY_LEFT((head)->sph_root, field) = SPLAY_RIGHT(node, field); \ - SPLAY_RIGHT((head)->sph_root, field) = SPLAY_LEFT(node, field); \ -} while (/*CONSTCOND*/ 0) +#define SPLAY_ROTATE_RIGHT(head, tmp, field) \ + do { \ + SPLAY_LEFT((head)->sph_root, field) = SPLAY_RIGHT(tmp, field); \ + SPLAY_RIGHT(tmp, field) = (head)->sph_root; \ + (head)->sph_root = tmp; \ + } while (/*CONSTCOND*/ 0) + +#define SPLAY_ROTATE_LEFT(head, tmp, field) \ + do { \ + SPLAY_RIGHT((head)->sph_root, field) = SPLAY_LEFT(tmp, field); \ + SPLAY_LEFT(tmp, field) = (head)->sph_root; \ + (head)->sph_root = tmp; \ + } while (/*CONSTCOND*/ 0) + +#define SPLAY_LINKLEFT(head, tmp, field) \ + do { \ + SPLAY_LEFT(tmp, field) = (head)->sph_root; \ + tmp = (head)->sph_root; \ + (head)->sph_root = SPLAY_LEFT((head)->sph_root, field); \ + } while (/*CONSTCOND*/ 0) + +#define SPLAY_LINKRIGHT(head, tmp, field) \ + do { \ + SPLAY_RIGHT(tmp, field) = (head)->sph_root; \ + tmp = (head)->sph_root; \ + (head)->sph_root = SPLAY_RIGHT((head)->sph_root, field); \ + } while (/*CONSTCOND*/ 0) + +#define SPLAY_ASSEMBLE(head, node, left, right, field) \ + do { \ + SPLAY_RIGHT(left, field) = SPLAY_LEFT((head)->sph_root, field); \ + SPLAY_LEFT(right, field) = SPLAY_RIGHT((head)->sph_root, field); \ + SPLAY_LEFT((head)->sph_root, field) = SPLAY_RIGHT(node, field); \ + SPLAY_RIGHT((head)->sph_root, field) = SPLAY_LEFT(node, field); \ + } while (/*CONSTCOND*/ 0) /* Generates prototypes and inline functions */ -#define SPLAY_PROTOTYPE(name, type, field, cmp) \ -void name##_SPLAY(struct name *, struct type *); \ -void name##_SPLAY_MINMAX(struct name *, int); \ -struct type *name##_SPLAY_INSERT(struct name *, struct type *); \ -struct type *name##_SPLAY_REMOVE(struct name *, struct type *); \ - \ -/* Finds the node with the same key as elm */ \ -static __inline struct type * \ -name##_SPLAY_FIND(struct name *head, struct type *elm) \ -{ \ - if (SPLAY_EMPTY(head)) \ - return(NULL); \ - name##_SPLAY(head, elm); \ - if ((cmp)(elm, (head)->sph_root) == 0) \ - return (head->sph_root); \ - return (NULL); \ -} \ - \ -static __inline struct type * \ -name##_SPLAY_NEXT(struct name *head, struct type *elm) \ -{ \ - name##_SPLAY(head, elm); \ - if (SPLAY_RIGHT(elm, field) != NULL) { \ - elm = SPLAY_RIGHT(elm, field); \ - while (SPLAY_LEFT(elm, field) != NULL) { \ - elm = SPLAY_LEFT(elm, field); \ - } \ - } else \ - elm = NULL; \ - return (elm); \ -} \ - \ -static __inline struct type * \ -name##_SPLAY_MIN_MAX(struct name *head, int val) \ -{ \ - name##_SPLAY_MINMAX(head, val); \ - return (SPLAY_ROOT(head)); \ -} +#define SPLAY_PROTOTYPE(name, type, field, cmp) \ + void name##_SPLAY(struct name *, struct type *); \ + void name##_SPLAY_MINMAX(struct name *, int); \ + struct type *name##_SPLAY_INSERT(struct name *, struct type *); \ + struct type *name##_SPLAY_REMOVE(struct name *, struct type *); \ + \ + /* Finds the node with the same key as elm */ \ + static __inline struct type *name##_SPLAY_FIND(struct name *head, struct type *elm) \ + { \ + if (SPLAY_EMPTY(head)) \ + return (NULL); \ + name##_SPLAY(head, elm); \ + if ((cmp)(elm, (head)->sph_root) == 0) \ + return (head->sph_root); \ + return (NULL); \ + } \ + \ + static __inline struct type *name##_SPLAY_NEXT(struct name *head, struct type *elm) \ + { \ + name##_SPLAY(head, elm); \ + if (SPLAY_RIGHT(elm, field) != NULL) { \ + elm = SPLAY_RIGHT(elm, field); \ + while (SPLAY_LEFT(elm, field) != NULL) { \ + elm = SPLAY_LEFT(elm, field); \ + } \ + } else \ + elm = NULL; \ + return (elm); \ + } \ + \ + static __inline struct type *name##_SPLAY_MIN_MAX(struct name *head, int val) \ + { \ + name##_SPLAY_MINMAX(head, val); \ + return (SPLAY_ROOT(head)); \ + } /* Main splay operation. * Moves node close to the key of elm to top */ -#define SPLAY_GENERATE(name, type, field, cmp) \ -struct type * \ -name##_SPLAY_INSERT(struct name *head, struct type *elm) \ -{ \ - if (SPLAY_EMPTY(head)) { \ - SPLAY_LEFT(elm, field) = SPLAY_RIGHT(elm, field) = NULL; \ - } else { \ - int __comp; \ - name##_SPLAY(head, elm); \ - __comp = (cmp)(elm, (head)->sph_root); \ - if(__comp < 0) { \ - SPLAY_LEFT(elm, field) = SPLAY_LEFT((head)->sph_root, field);\ - SPLAY_RIGHT(elm, field) = (head)->sph_root; \ - SPLAY_LEFT((head)->sph_root, field) = NULL; \ - } else if (__comp > 0) { \ - SPLAY_RIGHT(elm, field) = SPLAY_RIGHT((head)->sph_root, field);\ - SPLAY_LEFT(elm, field) = (head)->sph_root; \ - SPLAY_RIGHT((head)->sph_root, field) = NULL; \ - } else \ - return ((head)->sph_root); \ - } \ - (head)->sph_root = (elm); \ - return (NULL); \ -} \ - \ -struct type * \ -name##_SPLAY_REMOVE(struct name *head, struct type *elm) \ -{ \ - struct type *__tmp; \ - if (SPLAY_EMPTY(head)) \ - return (NULL); \ - name##_SPLAY(head, elm); \ - if ((cmp)(elm, (head)->sph_root) == 0) { \ - if (SPLAY_LEFT((head)->sph_root, field) == NULL) { \ - (head)->sph_root = SPLAY_RIGHT((head)->sph_root, field);\ - } else { \ - __tmp = SPLAY_RIGHT((head)->sph_root, field); \ - (head)->sph_root = SPLAY_LEFT((head)->sph_root, field);\ - name##_SPLAY(head, elm); \ - SPLAY_RIGHT((head)->sph_root, field) = __tmp; \ - } \ - return (elm); \ - } \ - return (NULL); \ -} \ - \ -void \ -name##_SPLAY(struct name *head, struct type *elm) \ -{ \ - struct type __node, *__left, *__right, *__tmp; \ - int __comp; \ -\ - SPLAY_LEFT(&__node, field) = SPLAY_RIGHT(&__node, field) = NULL;\ - __left = __right = &__node; \ -\ - while ((__comp = (cmp)(elm, (head)->sph_root)) != 0) { \ - if (__comp < 0) { \ - __tmp = SPLAY_LEFT((head)->sph_root, field); \ - if (__tmp == NULL) \ - break; \ - if ((cmp)(elm, __tmp) < 0){ \ - SPLAY_ROTATE_RIGHT(head, __tmp, field); \ - if (SPLAY_LEFT((head)->sph_root, field) == NULL)\ - break; \ - } \ - SPLAY_LINKLEFT(head, __right, field); \ - } else if (__comp > 0) { \ - __tmp = SPLAY_RIGHT((head)->sph_root, field); \ - if (__tmp == NULL) \ - break; \ - if ((cmp)(elm, __tmp) > 0){ \ - SPLAY_ROTATE_LEFT(head, __tmp, field); \ - if (SPLAY_RIGHT((head)->sph_root, field) == NULL)\ - break; \ - } \ - SPLAY_LINKRIGHT(head, __left, field); \ - } \ - } \ - SPLAY_ASSEMBLE(head, &__node, __left, __right, field); \ -} \ - \ -/* Splay with either the minimum or the maximum element \ - * Used to find minimum or maximum element in tree. \ - */ \ -void name##_SPLAY_MINMAX(struct name *head, int __comp) \ -{ \ - struct type __node, *__left, *__right, *__tmp; \ -\ - SPLAY_LEFT(&__node, field) = SPLAY_RIGHT(&__node, field) = NULL;\ - __left = __right = &__node; \ -\ - while (1) { \ - if (__comp < 0) { \ - __tmp = SPLAY_LEFT((head)->sph_root, field); \ - if (__tmp == NULL) \ - break; \ - if (__comp < 0){ \ - SPLAY_ROTATE_RIGHT(head, __tmp, field); \ - if (SPLAY_LEFT((head)->sph_root, field) == NULL)\ - break; \ - } \ - SPLAY_LINKLEFT(head, __right, field); \ - } else if (__comp > 0) { \ - __tmp = SPLAY_RIGHT((head)->sph_root, field); \ - if (__tmp == NULL) \ - break; \ - if (__comp > 0) { \ - SPLAY_ROTATE_LEFT(head, __tmp, field); \ - if (SPLAY_RIGHT((head)->sph_root, field) == NULL)\ - break; \ - } \ - SPLAY_LINKRIGHT(head, __left, field); \ - } \ - } \ - SPLAY_ASSEMBLE(head, &__node, __left, __right, field); \ -} - -#define SPLAY_NEGINF -1 -#define SPLAY_INF 1 - -#define SPLAY_INSERT(name, x, y) name##_SPLAY_INSERT(x, y) -#define SPLAY_REMOVE(name, x, y) name##_SPLAY_REMOVE(x, y) -#define SPLAY_FIND(name, x, y) name##_SPLAY_FIND(x, y) -#define SPLAY_NEXT(name, x, y) name##_SPLAY_NEXT(x, y) -#define SPLAY_MIN(name, x) (SPLAY_EMPTY(x) ? NULL \ - : name##_SPLAY_MIN_MAX(x, SPLAY_NEGINF)) -#define SPLAY_MAX(name, x) (SPLAY_EMPTY(x) ? NULL \ - : name##_SPLAY_MIN_MAX(x, SPLAY_INF)) - -#define SPLAY_FOREACH(x, name, head) \ - for ((x) = SPLAY_MIN(name, head); \ - (x) != NULL; \ - (x) = SPLAY_NEXT(name, head, x)) +#define SPLAY_GENERATE(name, type, field, cmp) \ + struct type *name##_SPLAY_INSERT(struct name *head, struct type *elm) \ + { \ + if (SPLAY_EMPTY(head)) { \ + SPLAY_LEFT(elm, field) = SPLAY_RIGHT(elm, field) = NULL; \ + } else { \ + int __comp; \ + name##_SPLAY(head, elm); \ + __comp = (cmp)(elm, (head)->sph_root); \ + if (__comp < 0) { \ + SPLAY_LEFT(elm, field) = SPLAY_LEFT((head)->sph_root, field); \ + SPLAY_RIGHT(elm, field) = (head)->sph_root; \ + SPLAY_LEFT((head)->sph_root, field) = NULL; \ + } else if (__comp > 0) { \ + SPLAY_RIGHT(elm, field) = SPLAY_RIGHT((head)->sph_root, field); \ + SPLAY_LEFT(elm, field) = (head)->sph_root; \ + SPLAY_RIGHT((head)->sph_root, field) = NULL; \ + } else \ + return ((head)->sph_root); \ + } \ + (head)->sph_root = (elm); \ + return (NULL); \ + } \ + \ + struct type *name##_SPLAY_REMOVE(struct name *head, struct type *elm) \ + { \ + struct type *__tmp; \ + if (SPLAY_EMPTY(head)) \ + return (NULL); \ + name##_SPLAY(head, elm); \ + if ((cmp)(elm, (head)->sph_root) == 0) { \ + if (SPLAY_LEFT((head)->sph_root, field) == NULL) { \ + (head)->sph_root = SPLAY_RIGHT((head)->sph_root, field); \ + } else { \ + __tmp = SPLAY_RIGHT((head)->sph_root, field); \ + (head)->sph_root = SPLAY_LEFT((head)->sph_root, field); \ + name##_SPLAY(head, elm); \ + SPLAY_RIGHT((head)->sph_root, field) = __tmp; \ + } \ + return (elm); \ + } \ + return (NULL); \ + } \ + \ + void name##_SPLAY(struct name *head, struct type *elm) \ + { \ + struct type __node, *__left, *__right, *__tmp; \ + int __comp; \ + \ + SPLAY_LEFT(&__node, field) = SPLAY_RIGHT(&__node, field) = NULL; \ + __left = __right = &__node; \ + \ + while ((__comp = (cmp)(elm, (head)->sph_root)) != 0) { \ + if (__comp < 0) { \ + __tmp = SPLAY_LEFT((head)->sph_root, field); \ + if (__tmp == NULL) \ + break; \ + if ((cmp)(elm, __tmp) < 0) { \ + SPLAY_ROTATE_RIGHT(head, __tmp, field); \ + if (SPLAY_LEFT((head)->sph_root, field) == NULL) \ + break; \ + } \ + SPLAY_LINKLEFT(head, __right, field); \ + } else if (__comp > 0) { \ + __tmp = SPLAY_RIGHT((head)->sph_root, field); \ + if (__tmp == NULL) \ + break; \ + if ((cmp)(elm, __tmp) > 0) { \ + SPLAY_ROTATE_LEFT(head, __tmp, field); \ + if (SPLAY_RIGHT((head)->sph_root, field) == NULL) \ + break; \ + } \ + SPLAY_LINKRIGHT(head, __left, field); \ + } \ + } \ + SPLAY_ASSEMBLE(head, &__node, __left, __right, field); \ + } \ + \ + /* Splay with either the minimum or the maximum element \ + * Used to find minimum or maximum element in tree. \ + */ \ + void name##_SPLAY_MINMAX(struct name *head, int __comp) \ + { \ + struct type __node, *__left, *__right, *__tmp; \ + \ + SPLAY_LEFT(&__node, field) = SPLAY_RIGHT(&__node, field) = NULL; \ + __left = __right = &__node; \ + \ + while (1) { \ + if (__comp < 0) { \ + __tmp = SPLAY_LEFT((head)->sph_root, field); \ + if (__tmp == NULL) \ + break; \ + if (__comp < 0) { \ + SPLAY_ROTATE_RIGHT(head, __tmp, field); \ + if (SPLAY_LEFT((head)->sph_root, field) == NULL) \ + break; \ + } \ + SPLAY_LINKLEFT(head, __right, field); \ + } else if (__comp > 0) { \ + __tmp = SPLAY_RIGHT((head)->sph_root, field); \ + if (__tmp == NULL) \ + break; \ + if (__comp > 0) { \ + SPLAY_ROTATE_LEFT(head, __tmp, field); \ + if (SPLAY_RIGHT((head)->sph_root, field) == NULL) \ + break; \ + } \ + SPLAY_LINKRIGHT(head, __left, field); \ + } \ + } \ + SPLAY_ASSEMBLE(head, &__node, __left, __right, field); \ + } + +#define SPLAY_NEGINF -1 +#define SPLAY_INF 1 + +#define SPLAY_INSERT(name, x, y) name##_SPLAY_INSERT(x, y) +#define SPLAY_REMOVE(name, x, y) name##_SPLAY_REMOVE(x, y) +#define SPLAY_FIND(name, x, y) name##_SPLAY_FIND(x, y) +#define SPLAY_NEXT(name, x, y) name##_SPLAY_NEXT(x, y) +#define SPLAY_MIN(name, x) (SPLAY_EMPTY(x) ? NULL : name##_SPLAY_MIN_MAX(x, SPLAY_NEGINF)) +#define SPLAY_MAX(name, x) (SPLAY_EMPTY(x) ? NULL : name##_SPLAY_MIN_MAX(x, SPLAY_INF)) + +#define SPLAY_FOREACH(x, name, head) \ + for ((x) = SPLAY_MIN(name, head); (x) != NULL; (x) = SPLAY_NEXT(name, head, x)) /* Macros that define a red-black tree */ -#define RB_HEAD(name, type) \ -struct name { \ - struct type *rbh_root; /* root of the tree */ \ -} - -#define RB_INITIALIZER(root) \ - { NULL } - -#define RB_INIT(root) do { \ - (root)->rbh_root = NULL; \ -} while (/*CONSTCOND*/ 0) - -#define RB_BLACK 0 -#define RB_RED 1 -#define RB_ENTRY(type) \ -struct { \ - struct type *rbe_left; /* left element */ \ - struct type *rbe_right; /* right element */ \ - struct type *rbe_parent; /* parent element */ \ - int rbe_color; /* node color */ \ -} - -#define RB_LEFT(elm, field) (elm)->field.rbe_left -#define RB_RIGHT(elm, field) (elm)->field.rbe_right -#define RB_PARENT(elm, field) (elm)->field.rbe_parent -#define RB_COLOR(elm, field) (elm)->field.rbe_color -#define RB_ROOT(head) (head)->rbh_root -#define RB_EMPTY(head) (RB_ROOT(head) == NULL) - -#define RB_SET(elm, parent, field) do { \ - RB_PARENT(elm, field) = parent; \ - RB_LEFT(elm, field) = RB_RIGHT(elm, field) = NULL; \ - RB_COLOR(elm, field) = RB_RED; \ -} while (/*CONSTCOND*/ 0) - -#define RB_SET_BLACKRED(black, red, field) do { \ - RB_COLOR(black, field) = RB_BLACK; \ - RB_COLOR(red, field) = RB_RED; \ -} while (/*CONSTCOND*/ 0) +#define RB_HEAD(name, type) \ + struct name { \ + struct type *rbh_root; /* root of the tree */ \ + } + +#define RB_INITIALIZER(root) \ + { \ + NULL \ + } + +#define RB_INIT(root) \ + do { \ + (root)->rbh_root = NULL; \ + } while (/*CONSTCOND*/ 0) + +#define RB_BLACK 0 +#define RB_RED 1 +#define RB_ENTRY(type) \ + struct { \ + struct type *rbe_left; /* left element */ \ + struct type *rbe_right; /* right element */ \ + struct type *rbe_parent; /* parent element */ \ + int rbe_color; /* node color */ \ + } + +#define RB_LEFT(elm, field) (elm)->field.rbe_left +#define RB_RIGHT(elm, field) (elm)->field.rbe_right +#define RB_PARENT(elm, field) (elm)->field.rbe_parent +#define RB_COLOR(elm, field) (elm)->field.rbe_color +#define RB_ROOT(head) (head)->rbh_root +#define RB_EMPTY(head) (RB_ROOT(head) == NULL) + +#define RB_SET(elm, parent, field) \ + do { \ + RB_PARENT(elm, field) = parent; \ + RB_LEFT(elm, field) = RB_RIGHT(elm, field) = NULL; \ + RB_COLOR(elm, field) = RB_RED; \ + } while (/*CONSTCOND*/ 0) + +#define RB_SET_BLACKRED(black, red, field) \ + do { \ + RB_COLOR(black, field) = RB_BLACK; \ + RB_COLOR(red, field) = RB_RED; \ + } while (/*CONSTCOND*/ 0) #ifndef RB_AUGMENT -#define RB_AUGMENT(x) do {} while (0) +#define RB_AUGMENT(x) \ + do { \ + } while (0) #endif -#define RB_ROTATE_LEFT(head, elm, tmp, field) do { \ - (tmp) = RB_RIGHT(elm, field); \ - if ((RB_RIGHT(elm, field) = RB_LEFT(tmp, field)) != NULL) { \ - RB_PARENT(RB_LEFT(tmp, field), field) = (elm); \ - } \ - RB_AUGMENT(elm); \ - if ((RB_PARENT(tmp, field) = RB_PARENT(elm, field)) != NULL) { \ - if ((elm) == RB_LEFT(RB_PARENT(elm, field), field)) \ - RB_LEFT(RB_PARENT(elm, field), field) = (tmp); \ - else \ - RB_RIGHT(RB_PARENT(elm, field), field) = (tmp); \ - } else \ - (head)->rbh_root = (tmp); \ - RB_LEFT(tmp, field) = (elm); \ - RB_PARENT(elm, field) = (tmp); \ - RB_AUGMENT(tmp); \ - if ((RB_PARENT(tmp, field))) \ - RB_AUGMENT(RB_PARENT(tmp, field)); \ -} while (/*CONSTCOND*/ 0) - -#define RB_ROTATE_RIGHT(head, elm, tmp, field) do { \ - (tmp) = RB_LEFT(elm, field); \ - if ((RB_LEFT(elm, field) = RB_RIGHT(tmp, field)) != NULL) { \ - RB_PARENT(RB_RIGHT(tmp, field), field) = (elm); \ - } \ - RB_AUGMENT(elm); \ - if ((RB_PARENT(tmp, field) = RB_PARENT(elm, field)) != NULL) { \ - if ((elm) == RB_LEFT(RB_PARENT(elm, field), field)) \ - RB_LEFT(RB_PARENT(elm, field), field) = (tmp); \ - else \ - RB_RIGHT(RB_PARENT(elm, field), field) = (tmp); \ - } else \ - (head)->rbh_root = (tmp); \ - RB_RIGHT(tmp, field) = (elm); \ - RB_PARENT(elm, field) = (tmp); \ - RB_AUGMENT(tmp); \ - if ((RB_PARENT(tmp, field))) \ - RB_AUGMENT(RB_PARENT(tmp, field)); \ -} while (/*CONSTCOND*/ 0) +#define RB_ROTATE_LEFT(head, elm, tmp, field) \ + do { \ + (tmp) = RB_RIGHT(elm, field); \ + if ((RB_RIGHT(elm, field) = RB_LEFT(tmp, field)) != NULL) { \ + RB_PARENT(RB_LEFT(tmp, field), field) = (elm); \ + } \ + RB_AUGMENT(elm); \ + if ((RB_PARENT(tmp, field) = RB_PARENT(elm, field)) != NULL) { \ + if ((elm) == RB_LEFT(RB_PARENT(elm, field), field)) \ + RB_LEFT(RB_PARENT(elm, field), field) = (tmp); \ + else \ + RB_RIGHT(RB_PARENT(elm, field), field) = (tmp); \ + } else \ + (head)->rbh_root = (tmp); \ + RB_LEFT(tmp, field) = (elm); \ + RB_PARENT(elm, field) = (tmp); \ + RB_AUGMENT(tmp); \ + if ((RB_PARENT(tmp, field))) \ + RB_AUGMENT(RB_PARENT(tmp, field)); \ + } while (/*CONSTCOND*/ 0) + +#define RB_ROTATE_RIGHT(head, elm, tmp, field) \ + do { \ + (tmp) = RB_LEFT(elm, field); \ + if ((RB_LEFT(elm, field) = RB_RIGHT(tmp, field)) != NULL) { \ + RB_PARENT(RB_RIGHT(tmp, field), field) = (elm); \ + } \ + RB_AUGMENT(elm); \ + if ((RB_PARENT(tmp, field) = RB_PARENT(elm, field)) != NULL) { \ + if ((elm) == RB_LEFT(RB_PARENT(elm, field), field)) \ + RB_LEFT(RB_PARENT(elm, field), field) = (tmp); \ + else \ + RB_RIGHT(RB_PARENT(elm, field), field) = (tmp); \ + } else \ + (head)->rbh_root = (tmp); \ + RB_RIGHT(tmp, field) = (elm); \ + RB_PARENT(elm, field) = (tmp); \ + RB_AUGMENT(tmp); \ + if ((RB_PARENT(tmp, field))) \ + RB_AUGMENT(RB_PARENT(tmp, field)); \ + } while (/*CONSTCOND*/ 0) /* Generates prototypes and inline functions */ -#define RB_PROTOTYPE(name, type, field, cmp) \ - RB_PROTOTYPE_INTERNAL(name, type, field, cmp,) -#define RB_PROTOTYPE_STATIC(name, type, field, cmp) \ - RB_PROTOTYPE_INTERNAL(name, type, field, cmp, __unused static) -#define RB_PROTOTYPE_INTERNAL(name, type, field, cmp, attr) \ - RB_PROTOTYPE_INSERT_COLOR(name, type, attr); \ - RB_PROTOTYPE_REMOVE_COLOR(name, type, attr); \ - RB_PROTOTYPE_INSERT(name, type, attr); \ - RB_PROTOTYPE_REMOVE(name, type, attr); \ - RB_PROTOTYPE_FIND(name, type, attr); \ - RB_PROTOTYPE_NFIND(name, type, attr); \ - RB_PROTOTYPE_NEXT(name, type, attr); \ - RB_PROTOTYPE_PREV(name, type, attr); \ - RB_PROTOTYPE_MINMAX(name, type, attr); -#define RB_PROTOTYPE_INSERT_COLOR(name, type, attr) \ - attr void name##_RB_INSERT_COLOR(struct name *, struct type *) -#define RB_PROTOTYPE_REMOVE_COLOR(name, type, attr) \ - attr void name##_RB_REMOVE_COLOR(struct name *, struct type *, struct type *) -#define RB_PROTOTYPE_REMOVE(name, type, attr) \ - attr struct type *name##_RB_REMOVE(struct name *, struct type *) -#define RB_PROTOTYPE_INSERT(name, type, attr) \ - attr struct type *name##_RB_INSERT(struct name *, struct type *) -#define RB_PROTOTYPE_FIND(name, type, attr) \ - attr struct type *name##_RB_FIND(struct name *, struct type *) -#define RB_PROTOTYPE_NFIND(name, type, attr) \ - attr struct type *name##_RB_NFIND(struct name *, struct type *) -#define RB_PROTOTYPE_NEXT(name, type, attr) \ - attr struct type *name##_RB_NEXT(struct type *) -#define RB_PROTOTYPE_PREV(name, type, attr) \ - attr struct type *name##_RB_PREV(struct type *) -#define RB_PROTOTYPE_MINMAX(name, type, attr) \ - attr struct type *name##_RB_MINMAX(struct name *, int) +#define RB_PROTOTYPE(name, type, field, cmp) RB_PROTOTYPE_INTERNAL(name, type, field, cmp, ) +#define RB_PROTOTYPE_STATIC(name, type, field, cmp) \ + RB_PROTOTYPE_INTERNAL(name, type, field, cmp, __unused static) +#define RB_PROTOTYPE_INTERNAL(name, type, field, cmp, attr) \ + RB_PROTOTYPE_INSERT_COLOR(name, type, attr); \ + RB_PROTOTYPE_REMOVE_COLOR(name, type, attr); \ + RB_PROTOTYPE_INSERT(name, type, attr); \ + RB_PROTOTYPE_REMOVE(name, type, attr); \ + RB_PROTOTYPE_FIND(name, type, attr); \ + RB_PROTOTYPE_NFIND(name, type, attr); \ + RB_PROTOTYPE_NEXT(name, type, attr); \ + RB_PROTOTYPE_PREV(name, type, attr); \ + RB_PROTOTYPE_MINMAX(name, type, attr); +#define RB_PROTOTYPE_INSERT_COLOR(name, type, attr) \ + attr void name##_RB_INSERT_COLOR(struct name *, struct type *) +#define RB_PROTOTYPE_REMOVE_COLOR(name, type, attr) \ + attr void name##_RB_REMOVE_COLOR(struct name *, struct type *, struct type *) +#define RB_PROTOTYPE_REMOVE(name, type, attr) \ + attr struct type *name##_RB_REMOVE(struct name *, struct type *) +#define RB_PROTOTYPE_INSERT(name, type, attr) \ + attr struct type *name##_RB_INSERT(struct name *, struct type *) +#define RB_PROTOTYPE_FIND(name, type, attr) \ + attr struct type *name##_RB_FIND(struct name *, struct type *) +#define RB_PROTOTYPE_NFIND(name, type, attr) \ + attr struct type *name##_RB_NFIND(struct name *, struct type *) +#define RB_PROTOTYPE_NEXT(name, type, attr) attr struct type *name##_RB_NEXT(struct type *) +#define RB_PROTOTYPE_PREV(name, type, attr) attr struct type *name##_RB_PREV(struct type *) +#define RB_PROTOTYPE_MINMAX(name, type, attr) attr struct type *name##_RB_MINMAX(struct name *, int) /* Main rb operation. * Moves node close to the key of elm to top */ -#define RB_GENERATE(name, type, field, cmp) \ - RB_GENERATE_INTERNAL(name, type, field, cmp,) -#define RB_GENERATE_STATIC(name, type, field, cmp) \ - RB_GENERATE_INTERNAL(name, type, field, cmp, __unused static) -#define RB_GENERATE_INTERNAL(name, type, field, cmp, attr) \ - RB_GENERATE_INSERT_COLOR(name, type, field, attr) \ - RB_GENERATE_REMOVE_COLOR(name, type, field, attr) \ - RB_GENERATE_INSERT(name, type, field, cmp, attr) \ - RB_GENERATE_REMOVE(name, type, field, attr) \ - RB_GENERATE_FIND(name, type, field, cmp, attr) \ - RB_GENERATE_NFIND(name, type, field, cmp, attr) \ - RB_GENERATE_NEXT(name, type, field, attr) \ - RB_GENERATE_PREV(name, type, field, attr) \ - RB_GENERATE_MINMAX(name, type, field, attr) - -#define RB_GENERATE_INSERT_COLOR(name, type, field, attr) \ -attr void \ -name##_RB_INSERT_COLOR(struct name *head, struct type *elm) \ -{ \ - struct type *parent, *gparent, *tmp; \ - while ((parent = RB_PARENT(elm, field)) != NULL && \ - RB_COLOR(parent, field) == RB_RED) { \ - gparent = RB_PARENT(parent, field); \ - _T_ASSERT(gparent); \ - if (parent == RB_LEFT(gparent, field)) { \ - tmp = RB_RIGHT(gparent, field); \ - if (tmp && RB_COLOR(tmp, field) == RB_RED) { \ - RB_COLOR(tmp, field) = RB_BLACK; \ - RB_SET_BLACKRED(parent, gparent, field);\ - elm = gparent; \ - continue; \ - } \ - if (RB_RIGHT(parent, field) == elm) { \ - RB_ROTATE_LEFT(head, parent, tmp, field);\ - tmp = parent; \ - parent = elm; \ - elm = tmp; \ - } \ - RB_SET_BLACKRED(parent, gparent, field); \ - RB_ROTATE_RIGHT(head, gparent, tmp, field); \ - } else { \ - tmp = RB_LEFT(gparent, field); \ - if (tmp && RB_COLOR(tmp, field) == RB_RED) { \ - RB_COLOR(tmp, field) = RB_BLACK; \ - RB_SET_BLACKRED(parent, gparent, field);\ - elm = gparent; \ - continue; \ - } \ - if (RB_LEFT(parent, field) == elm) { \ - RB_ROTATE_RIGHT(head, parent, tmp, field);\ - tmp = parent; \ - parent = elm; \ - elm = tmp; \ - } \ - RB_SET_BLACKRED(parent, gparent, field); \ - RB_ROTATE_LEFT(head, gparent, tmp, field); \ - } \ - } \ - RB_COLOR(head->rbh_root, field) = RB_BLACK; \ -} - -#define RB_GENERATE_REMOVE_COLOR(name, type, field, attr) \ -attr void \ -name##_RB_REMOVE_COLOR(struct name *head, struct type *parent, struct type *elm) \ -{ \ - struct type *tmp; \ - while ((elm == NULL || RB_COLOR(elm, field) == RB_BLACK) && \ - elm != RB_ROOT(head)) { \ - if (RB_LEFT(parent, field) == elm) { \ - tmp = RB_RIGHT(parent, field); \ - if (RB_COLOR(tmp, field) == RB_RED) { \ - RB_SET_BLACKRED(tmp, parent, field); \ - RB_ROTATE_LEFT(head, parent, tmp, field);\ - tmp = RB_RIGHT(parent, field); \ - } \ - _T_ASSERT(tmp); \ - if ((RB_LEFT(tmp, field) == NULL || \ - RB_COLOR(RB_LEFT(tmp, field), field) == RB_BLACK) &&\ - (RB_RIGHT(tmp, field) == NULL || \ - RB_COLOR(RB_RIGHT(tmp, field), field) == RB_BLACK)) {\ - RB_COLOR(tmp, field) = RB_RED; \ - elm = parent; \ - parent = RB_PARENT(elm, field); \ - } else { \ - if (RB_RIGHT(tmp, field) == NULL || \ - RB_COLOR(RB_RIGHT(tmp, field), field) == RB_BLACK) {\ - struct type *oleft; \ - if ((oleft = RB_LEFT(tmp, field)) \ - != NULL) \ - RB_COLOR(oleft, field) = RB_BLACK;\ - RB_COLOR(tmp, field) = RB_RED; \ - RB_ROTATE_RIGHT(head, tmp, oleft, field);\ - tmp = RB_RIGHT(parent, field); \ - } \ - RB_COLOR(tmp, field) = RB_COLOR(parent, field);\ - RB_COLOR(parent, field) = RB_BLACK; \ - if (RB_RIGHT(tmp, field)) \ - RB_COLOR(RB_RIGHT(tmp, field), field) = RB_BLACK;\ - RB_ROTATE_LEFT(head, parent, tmp, field);\ - elm = RB_ROOT(head); \ - break; \ - } \ - } else { \ - tmp = RB_LEFT(parent, field); \ - if (RB_COLOR(tmp, field) == RB_RED) { \ - RB_SET_BLACKRED(tmp, parent, field); \ - RB_ROTATE_RIGHT(head, parent, tmp, field);\ - tmp = RB_LEFT(parent, field); \ - } \ - _T_ASSERT(tmp); \ - if ((RB_LEFT(tmp, field) == NULL || \ - RB_COLOR(RB_LEFT(tmp, field), field) == RB_BLACK) &&\ - (RB_RIGHT(tmp, field) == NULL || \ - RB_COLOR(RB_RIGHT(tmp, field), field) == RB_BLACK)) {\ - RB_COLOR(tmp, field) = RB_RED; \ - elm = parent; \ - parent = RB_PARENT(elm, field); \ - } else { \ - if (RB_LEFT(tmp, field) == NULL || \ - RB_COLOR(RB_LEFT(tmp, field), field) == RB_BLACK) {\ - struct type *oright; \ - if ((oright = RB_RIGHT(tmp, field)) \ - != NULL) \ - RB_COLOR(oright, field) = RB_BLACK;\ - RB_COLOR(tmp, field) = RB_RED; \ - RB_ROTATE_LEFT(head, tmp, oright, field);\ - tmp = RB_LEFT(parent, field); \ - } \ - RB_COLOR(tmp, field) = RB_COLOR(parent, field);\ - RB_COLOR(parent, field) = RB_BLACK; \ - if (RB_LEFT(tmp, field)) \ - RB_COLOR(RB_LEFT(tmp, field), field) = RB_BLACK;\ - RB_ROTATE_RIGHT(head, parent, tmp, field);\ - elm = RB_ROOT(head); \ - break; \ - } \ - } \ - } \ - if (elm) \ - RB_COLOR(elm, field) = RB_BLACK; \ -} - -#define RB_GENERATE_REMOVE(name, type, field, attr) \ -attr struct type * \ -name##_RB_REMOVE(struct name *head, struct type *elm) \ -{ \ - struct type *child, *parent, *old = elm; \ - int color; \ - if (RB_LEFT(elm, field) == NULL) \ - child = RB_RIGHT(elm, field); \ - else if (RB_RIGHT(elm, field) == NULL) \ - child = RB_LEFT(elm, field); \ - else { \ - struct type *left; \ - elm = RB_RIGHT(elm, field); \ - while ((left = RB_LEFT(elm, field)) != NULL) \ - elm = left; \ - child = RB_RIGHT(elm, field); \ - parent = RB_PARENT(elm, field); \ - color = RB_COLOR(elm, field); \ - if (child) \ - RB_PARENT(child, field) = parent; \ - if (parent) { \ - if (RB_LEFT(parent, field) == elm) \ - RB_LEFT(parent, field) = child; \ - else \ - RB_RIGHT(parent, field) = child; \ - RB_AUGMENT(parent); \ - } else \ - RB_ROOT(head) = child; \ - if (RB_PARENT(elm, field) == old) \ - parent = elm; \ - _T_ASSERT((old)); \ - (elm)->field = (old)->field; \ - if (RB_PARENT(old, field)) { \ - if (RB_LEFT(RB_PARENT(old, field), field) == old)\ - RB_LEFT(RB_PARENT(old, field), field) = elm;\ - else \ - RB_RIGHT(RB_PARENT(old, field), field) = elm;\ - RB_AUGMENT(RB_PARENT(old, field)); \ - } else \ - RB_ROOT(head) = elm; \ - _T_ASSERT(old); \ - _T_ASSERT(RB_LEFT(old, field)); \ - RB_PARENT(RB_LEFT(old, field), field) = elm; \ - if (RB_RIGHT(old, field)) \ - RB_PARENT(RB_RIGHT(old, field), field) = elm; \ - if (parent) { \ - left = parent; \ - do { \ - RB_AUGMENT(left); \ - } while ((left = RB_PARENT(left, field)) != NULL); \ - } \ - goto color; \ - } \ - parent = RB_PARENT(elm, field); \ - color = RB_COLOR(elm, field); \ - if (child) \ - RB_PARENT(child, field) = parent; \ - if (parent) { \ - if (RB_LEFT(parent, field) == elm) \ - RB_LEFT(parent, field) = child; \ - else \ - RB_RIGHT(parent, field) = child; \ - RB_AUGMENT(parent); \ - } else \ - RB_ROOT(head) = child; \ -color: \ - if (color == RB_BLACK) \ - name##_RB_REMOVE_COLOR(head, parent, child); \ - return (old); \ -} \ - -#define RB_GENERATE_INSERT(name, type, field, cmp, attr) \ -/* Inserts a node into the RB tree */ \ -attr struct type * \ -name##_RB_INSERT(struct name *head, struct type *elm) \ -{ \ - struct type *tmp; \ - struct type *parent = NULL; \ - int comp = 0; \ - tmp = RB_ROOT(head); \ - while (tmp) { \ - parent = tmp; \ - comp = (cmp)(elm, parent); \ - if (comp < 0) \ - tmp = RB_LEFT(tmp, field); \ - else if (comp > 0) \ - tmp = RB_RIGHT(tmp, field); \ - else \ - return (tmp); \ - } \ - RB_SET(elm, parent, field); \ - if (parent != NULL) { \ - if (comp < 0) \ - RB_LEFT(parent, field) = elm; \ - else \ - RB_RIGHT(parent, field) = elm; \ - RB_AUGMENT(parent); \ - } else \ - RB_ROOT(head) = elm; \ - name##_RB_INSERT_COLOR(head, elm); \ - return (NULL); \ -} - -#define RB_GENERATE_FIND(name, type, field, cmp, attr) \ -/* Finds the node with the same key as elm */ \ -attr struct type * \ -name##_RB_FIND(struct name *head, struct type *elm) \ -{ \ - struct type *tmp = RB_ROOT(head); \ - int comp; \ - while (tmp) { \ - comp = cmp(elm, tmp); \ - if (comp < 0) \ - tmp = RB_LEFT(tmp, field); \ - else if (comp > 0) \ - tmp = RB_RIGHT(tmp, field); \ - else \ - return (tmp); \ - } \ - return (NULL); \ -} - -#define RB_GENERATE_NFIND(name, type, field, cmp, attr) \ -/* Finds the first node greater than or equal to the search key */ \ -attr struct type * \ -name##_RB_NFIND(struct name *head, struct type *elm) \ -{ \ - struct type *tmp = RB_ROOT(head); \ - struct type *res = NULL; \ - int comp; \ - while (tmp) { \ - comp = cmp(elm, tmp); \ - if (comp < 0) { \ - res = tmp; \ - tmp = RB_LEFT(tmp, field); \ - } \ - else if (comp > 0) \ - tmp = RB_RIGHT(tmp, field); \ - else \ - return (tmp); \ - } \ - return (res); \ -} - -#define RB_GENERATE_NEXT(name, type, field, attr) \ -/* ARGSUSED */ \ -attr struct type * \ -name##_RB_NEXT(struct type *elm) \ -{ \ - if (RB_RIGHT(elm, field)) { \ - elm = RB_RIGHT(elm, field); \ - while (RB_LEFT(elm, field)) \ - elm = RB_LEFT(elm, field); \ - } else { \ - if (RB_PARENT(elm, field) && \ - (elm == RB_LEFT(RB_PARENT(elm, field), field))) \ - elm = RB_PARENT(elm, field); \ - else { \ - while (RB_PARENT(elm, field) && \ - (elm == RB_RIGHT(RB_PARENT(elm, field), field)))\ - elm = RB_PARENT(elm, field); \ - elm = RB_PARENT(elm, field); \ - } \ - } \ - return (elm); \ -} - -#define RB_GENERATE_PREV(name, type, field, attr) \ -/* ARGSUSED */ \ -attr struct type * \ -name##_RB_PREV(struct type *elm) \ -{ \ - if (RB_LEFT(elm, field)) { \ - elm = RB_LEFT(elm, field); \ - while (RB_RIGHT(elm, field)) \ - elm = RB_RIGHT(elm, field); \ - } else { \ - if (RB_PARENT(elm, field) && \ - (elm == RB_RIGHT(RB_PARENT(elm, field), field))) \ - elm = RB_PARENT(elm, field); \ - else { \ - while (RB_PARENT(elm, field) && \ - (elm == RB_LEFT(RB_PARENT(elm, field), field)))\ - elm = RB_PARENT(elm, field); \ - elm = RB_PARENT(elm, field); \ - } \ - } \ - return (elm); \ -} - -#define RB_GENERATE_MINMAX(name, type, field, attr) \ -attr struct type * \ -name##_RB_MINMAX(struct name *head, int val) \ -{ \ - struct type *tmp = RB_ROOT(head); \ - struct type *parent = NULL; \ - while (tmp) { \ - parent = tmp; \ - if (val < 0) \ - tmp = RB_LEFT(tmp, field); \ - else \ - tmp = RB_RIGHT(tmp, field); \ - } \ - return (parent); \ -} - -#define RB_NEGINF -1 -#define RB_INF 1 - -#define RB_INSERT(name, x, y) name##_RB_INSERT(x, y) -#define RB_REMOVE(name, x, y) name##_RB_REMOVE(x, y) -#define RB_FIND(name, x, y) name##_RB_FIND(x, y) -#define RB_NFIND(name, x, y) name##_RB_NFIND(x, y) -#define RB_NEXT(name, x, y) name##_RB_NEXT(y) -#define RB_PREV(name, x, y) name##_RB_PREV(y) -#define RB_MIN(name, x) name##_RB_MINMAX(x, RB_NEGINF) -#define RB_MAX(name, x) name##_RB_MINMAX(x, RB_INF) - -#define RB_FOREACH(x, name, head) \ - for ((x) = RB_MIN(name, head); \ - (x) != NULL; \ - (x) = name##_RB_NEXT(x)) - -#define RB_FOREACH_FROM(x, name, y) \ - for ((x) = (y); \ - ((x) != NULL) && ((y) = name##_RB_NEXT(x), (x) != NULL); \ - (x) = (y)) - -#define RB_FOREACH_SAFE(x, name, head, y) \ - for ((x) = RB_MIN(name, head); \ - ((x) != NULL) && ((y) = name##_RB_NEXT(x), (x) != NULL); \ - (x) = (y)) - -#define RB_FOREACH_REVERSE(x, name, head) \ - for ((x) = RB_MAX(name, head); \ - (x) != NULL; \ - (x) = name##_RB_PREV(x)) - -#define RB_FOREACH_REVERSE_FROM(x, name, y) \ - for ((x) = (y); \ - ((x) != NULL) && ((y) = name##_RB_PREV(x), (x) != NULL); \ - (x) = (y)) - -#define RB_FOREACH_REVERSE_SAFE(x, name, head, y) \ - for ((x) = RB_MAX(name, head); \ - ((x) != NULL) && ((y) = name##_RB_PREV(x), (x) != NULL); \ - (x) = (y)) - -#endif /* _SYS_TREE_H_ */ +#define RB_GENERATE(name, type, field, cmp) RB_GENERATE_INTERNAL(name, type, field, cmp, ) +#define RB_GENERATE_STATIC(name, type, field, cmp) \ + RB_GENERATE_INTERNAL(name, type, field, cmp, __unused static) +#define RB_GENERATE_INTERNAL(name, type, field, cmp, attr) \ + RB_GENERATE_INSERT_COLOR(name, type, field, attr) \ + RB_GENERATE_REMOVE_COLOR(name, type, field, attr) \ + RB_GENERATE_INSERT(name, type, field, cmp, attr) \ + RB_GENERATE_REMOVE(name, type, field, attr) \ + RB_GENERATE_FIND(name, type, field, cmp, attr) \ + RB_GENERATE_NFIND(name, type, field, cmp, attr) \ + RB_GENERATE_NEXT(name, type, field, attr) \ + RB_GENERATE_PREV(name, type, field, attr) \ + RB_GENERATE_MINMAX(name, type, field, attr) + +#define RB_GENERATE_INSERT_COLOR(name, type, field, attr) \ + attr void name##_RB_INSERT_COLOR(struct name *head, struct type *elm) \ + { \ + struct type *parent, *gparent, *tmp; \ + while ((parent = RB_PARENT(elm, field)) != NULL && RB_COLOR(parent, field) == RB_RED) { \ + gparent = RB_PARENT(parent, field); \ + _T_ASSERT(gparent); \ + if (parent == RB_LEFT(gparent, field)) { \ + tmp = RB_RIGHT(gparent, field); \ + if (tmp && RB_COLOR(tmp, field) == RB_RED) { \ + RB_COLOR(tmp, field) = RB_BLACK; \ + RB_SET_BLACKRED(parent, gparent, field); \ + elm = gparent; \ + continue; \ + } \ + if (RB_RIGHT(parent, field) == elm) { \ + RB_ROTATE_LEFT(head, parent, tmp, field); \ + tmp = parent; \ + parent = elm; \ + elm = tmp; \ + } \ + RB_SET_BLACKRED(parent, gparent, field); \ + RB_ROTATE_RIGHT(head, gparent, tmp, field); \ + } else { \ + tmp = RB_LEFT(gparent, field); \ + if (tmp && RB_COLOR(tmp, field) == RB_RED) { \ + RB_COLOR(tmp, field) = RB_BLACK; \ + RB_SET_BLACKRED(parent, gparent, field); \ + elm = gparent; \ + continue; \ + } \ + if (RB_LEFT(parent, field) == elm) { \ + RB_ROTATE_RIGHT(head, parent, tmp, field); \ + tmp = parent; \ + parent = elm; \ + elm = tmp; \ + } \ + RB_SET_BLACKRED(parent, gparent, field); \ + RB_ROTATE_LEFT(head, gparent, tmp, field); \ + } \ + } \ + RB_COLOR(head->rbh_root, field) = RB_BLACK; \ + } + +#define RB_GENERATE_REMOVE_COLOR(name, type, field, attr) \ + attr void name##_RB_REMOVE_COLOR(struct name *head, struct type *parent, struct type *elm) \ + { \ + struct type *tmp; \ + while ((elm == NULL || RB_COLOR(elm, field) == RB_BLACK) && elm != RB_ROOT(head)) { \ + if (RB_LEFT(parent, field) == elm) { \ + tmp = RB_RIGHT(parent, field); \ + if (RB_COLOR(tmp, field) == RB_RED) { \ + RB_SET_BLACKRED(tmp, parent, field); \ + RB_ROTATE_LEFT(head, parent, tmp, field); \ + tmp = RB_RIGHT(parent, field); \ + } \ + _T_ASSERT(tmp); \ + if ((RB_LEFT(tmp, field) == NULL || \ + RB_COLOR(RB_LEFT(tmp, field), field) == RB_BLACK) && \ + (RB_RIGHT(tmp, field) == NULL || \ + RB_COLOR(RB_RIGHT(tmp, field), field) == RB_BLACK)) { \ + RB_COLOR(tmp, field) = RB_RED; \ + elm = parent; \ + parent = RB_PARENT(elm, field); \ + } else { \ + if (RB_RIGHT(tmp, field) == NULL || \ + RB_COLOR(RB_RIGHT(tmp, field), field) == RB_BLACK) { \ + struct type *oleft; \ + if ((oleft = RB_LEFT(tmp, field)) != NULL) \ + RB_COLOR(oleft, field) = RB_BLACK; \ + RB_COLOR(tmp, field) = RB_RED; \ + RB_ROTATE_RIGHT(head, tmp, oleft, field); \ + tmp = RB_RIGHT(parent, field); \ + } \ + RB_COLOR(tmp, field) = RB_COLOR(parent, field); \ + RB_COLOR(parent, field) = RB_BLACK; \ + if (RB_RIGHT(tmp, field)) \ + RB_COLOR(RB_RIGHT(tmp, field), field) = RB_BLACK; \ + RB_ROTATE_LEFT(head, parent, tmp, field); \ + elm = RB_ROOT(head); \ + break; \ + } \ + } else { \ + tmp = RB_LEFT(parent, field); \ + if (RB_COLOR(tmp, field) == RB_RED) { \ + RB_SET_BLACKRED(tmp, parent, field); \ + RB_ROTATE_RIGHT(head, parent, tmp, field); \ + tmp = RB_LEFT(parent, field); \ + } \ + _T_ASSERT(tmp); \ + if ((RB_LEFT(tmp, field) == NULL || \ + RB_COLOR(RB_LEFT(tmp, field), field) == RB_BLACK) && \ + (RB_RIGHT(tmp, field) == NULL || \ + RB_COLOR(RB_RIGHT(tmp, field), field) == RB_BLACK)) { \ + RB_COLOR(tmp, field) = RB_RED; \ + elm = parent; \ + parent = RB_PARENT(elm, field); \ + } else { \ + if (RB_LEFT(tmp, field) == NULL || \ + RB_COLOR(RB_LEFT(tmp, field), field) == RB_BLACK) { \ + struct type *oright; \ + if ((oright = RB_RIGHT(tmp, field)) != NULL) \ + RB_COLOR(oright, field) = RB_BLACK; \ + RB_COLOR(tmp, field) = RB_RED; \ + RB_ROTATE_LEFT(head, tmp, oright, field); \ + tmp = RB_LEFT(parent, field); \ + } \ + RB_COLOR(tmp, field) = RB_COLOR(parent, field); \ + RB_COLOR(parent, field) = RB_BLACK; \ + if (RB_LEFT(tmp, field)) \ + RB_COLOR(RB_LEFT(tmp, field), field) = RB_BLACK; \ + RB_ROTATE_RIGHT(head, parent, tmp, field); \ + elm = RB_ROOT(head); \ + break; \ + } \ + } \ + } \ + if (elm) \ + RB_COLOR(elm, field) = RB_BLACK; \ + } + +#define RB_GENERATE_REMOVE(name, type, field, attr) \ + attr struct type *name##_RB_REMOVE(struct name *head, struct type *elm) \ + { \ + struct type *child, *parent, *old = elm; \ + int color; \ + if (RB_LEFT(elm, field) == NULL) \ + child = RB_RIGHT(elm, field); \ + else if (RB_RIGHT(elm, field) == NULL) \ + child = RB_LEFT(elm, field); \ + else { \ + struct type *left; \ + elm = RB_RIGHT(elm, field); \ + while ((left = RB_LEFT(elm, field)) != NULL) \ + elm = left; \ + child = RB_RIGHT(elm, field); \ + parent = RB_PARENT(elm, field); \ + color = RB_COLOR(elm, field); \ + if (child) \ + RB_PARENT(child, field) = parent; \ + if (parent) { \ + if (RB_LEFT(parent, field) == elm) \ + RB_LEFT(parent, field) = child; \ + else \ + RB_RIGHT(parent, field) = child; \ + RB_AUGMENT(parent); \ + } else \ + RB_ROOT(head) = child; \ + if (RB_PARENT(elm, field) == old) \ + parent = elm; \ + _T_ASSERT((old)); \ + (elm)->field = (old)->field; \ + if (RB_PARENT(old, field)) { \ + if (RB_LEFT(RB_PARENT(old, field), field) == old) \ + RB_LEFT(RB_PARENT(old, field), field) = elm; \ + else \ + RB_RIGHT(RB_PARENT(old, field), field) = elm; \ + RB_AUGMENT(RB_PARENT(old, field)); \ + } else \ + RB_ROOT(head) = elm; \ + _T_ASSERT(old); \ + _T_ASSERT(RB_LEFT(old, field)); \ + RB_PARENT(RB_LEFT(old, field), field) = elm; \ + if (RB_RIGHT(old, field)) \ + RB_PARENT(RB_RIGHT(old, field), field) = elm; \ + if (parent) { \ + left = parent; \ + do { \ + RB_AUGMENT(left); \ + } while ((left = RB_PARENT(left, field)) != NULL); \ + } \ + goto color; \ + } \ + parent = RB_PARENT(elm, field); \ + color = RB_COLOR(elm, field); \ + if (child) \ + RB_PARENT(child, field) = parent; \ + if (parent) { \ + if (RB_LEFT(parent, field) == elm) \ + RB_LEFT(parent, field) = child; \ + else \ + RB_RIGHT(parent, field) = child; \ + RB_AUGMENT(parent); \ + } else \ + RB_ROOT(head) = child; \ + color: \ + if (color == RB_BLACK) \ + name##_RB_REMOVE_COLOR(head, parent, child); \ + return (old); \ + } + +#define RB_GENERATE_INSERT(name, type, field, cmp, attr) \ + /* Inserts a node into the RB tree */ \ + attr struct type *name##_RB_INSERT(struct name *head, struct type *elm) \ + { \ + struct type *tmp; \ + struct type *parent = NULL; \ + int comp = 0; \ + tmp = RB_ROOT(head); \ + while (tmp) { \ + parent = tmp; \ + comp = (cmp)(elm, parent); \ + if (comp < 0) \ + tmp = RB_LEFT(tmp, field); \ + else if (comp > 0) \ + tmp = RB_RIGHT(tmp, field); \ + else \ + return (tmp); \ + } \ + RB_SET(elm, parent, field); \ + if (parent != NULL) { \ + if (comp < 0) \ + RB_LEFT(parent, field) = elm; \ + else \ + RB_RIGHT(parent, field) = elm; \ + RB_AUGMENT(parent); \ + } else \ + RB_ROOT(head) = elm; \ + name##_RB_INSERT_COLOR(head, elm); \ + return (NULL); \ + } + +#define RB_GENERATE_FIND(name, type, field, cmp, attr) \ + /* Finds the node with the same key as elm */ \ + attr struct type *name##_RB_FIND(struct name *head, struct type *elm) \ + { \ + struct type *tmp = RB_ROOT(head); \ + int comp; \ + while (tmp) { \ + comp = cmp(elm, tmp); \ + if (comp < 0) \ + tmp = RB_LEFT(tmp, field); \ + else if (comp > 0) \ + tmp = RB_RIGHT(tmp, field); \ + else \ + return (tmp); \ + } \ + return (NULL); \ + } + +#define RB_GENERATE_NFIND(name, type, field, cmp, attr) \ + /* Finds the first node greater than or equal to the search key */ \ + attr struct type *name##_RB_NFIND(struct name *head, struct type *elm) \ + { \ + struct type *tmp = RB_ROOT(head); \ + struct type *res = NULL; \ + int comp; \ + while (tmp) { \ + comp = cmp(elm, tmp); \ + if (comp < 0) { \ + res = tmp; \ + tmp = RB_LEFT(tmp, field); \ + } else if (comp > 0) \ + tmp = RB_RIGHT(tmp, field); \ + else \ + return (tmp); \ + } \ + return (res); \ + } + +#define RB_GENERATE_NEXT(name, type, field, attr) \ + /* ARGSUSED */ \ + attr struct type *name##_RB_NEXT(struct type *elm) \ + { \ + if (RB_RIGHT(elm, field)) { \ + elm = RB_RIGHT(elm, field); \ + while (RB_LEFT(elm, field)) \ + elm = RB_LEFT(elm, field); \ + } else { \ + if (RB_PARENT(elm, field) && (elm == RB_LEFT(RB_PARENT(elm, field), field))) \ + elm = RB_PARENT(elm, field); \ + else { \ + while (RB_PARENT(elm, field) && (elm == RB_RIGHT(RB_PARENT(elm, field), field))) \ + elm = RB_PARENT(elm, field); \ + elm = RB_PARENT(elm, field); \ + } \ + } \ + return (elm); \ + } + +#define RB_GENERATE_PREV(name, type, field, attr) \ + /* ARGSUSED */ \ + attr struct type *name##_RB_PREV(struct type *elm) \ + { \ + if (RB_LEFT(elm, field)) { \ + elm = RB_LEFT(elm, field); \ + while (RB_RIGHT(elm, field)) \ + elm = RB_RIGHT(elm, field); \ + } else { \ + if (RB_PARENT(elm, field) && (elm == RB_RIGHT(RB_PARENT(elm, field), field))) \ + elm = RB_PARENT(elm, field); \ + else { \ + while (RB_PARENT(elm, field) && (elm == RB_LEFT(RB_PARENT(elm, field), field))) \ + elm = RB_PARENT(elm, field); \ + elm = RB_PARENT(elm, field); \ + } \ + } \ + return (elm); \ + } + +#define RB_GENERATE_MINMAX(name, type, field, attr) \ + attr struct type *name##_RB_MINMAX(struct name *head, int val) \ + { \ + struct type *tmp = RB_ROOT(head); \ + struct type *parent = NULL; \ + while (tmp) { \ + parent = tmp; \ + if (val < 0) \ + tmp = RB_LEFT(tmp, field); \ + else \ + tmp = RB_RIGHT(tmp, field); \ + } \ + return (parent); \ + } + +#define RB_NEGINF -1 +#define RB_INF 1 + +#define RB_INSERT(name, x, y) name##_RB_INSERT(x, y) +#define RB_REMOVE(name, x, y) name##_RB_REMOVE(x, y) +#define RB_FIND(name, x, y) name##_RB_FIND(x, y) +#define RB_NFIND(name, x, y) name##_RB_NFIND(x, y) +#define RB_NEXT(name, x, y) name##_RB_NEXT(y) +#define RB_PREV(name, x, y) name##_RB_PREV(y) +#define RB_MIN(name, x) name##_RB_MINMAX(x, RB_NEGINF) +#define RB_MAX(name, x) name##_RB_MINMAX(x, RB_INF) + +#define RB_FOREACH(x, name, head) \ + for ((x) = RB_MIN(name, head); (x) != NULL; (x) = name##_RB_NEXT(x)) + +#define RB_FOREACH_FROM(x, name, y) \ + for ((x) = (y); ((x) != NULL) && ((y) = name##_RB_NEXT(x), (x) != NULL); (x) = (y)) + +#define RB_FOREACH_SAFE(x, name, head, y) \ + for ((x) = RB_MIN(name, head); ((x) != NULL) && ((y) = name##_RB_NEXT(x), (x) != NULL); \ + (x) = (y)) + +#define RB_FOREACH_REVERSE(x, name, head) \ + for ((x) = RB_MAX(name, head); (x) != NULL; (x) = name##_RB_PREV(x)) + +#define RB_FOREACH_REVERSE_FROM(x, name, y) \ + for ((x) = (y); ((x) != NULL) && ((y) = name##_RB_PREV(x), (x) != NULL); (x) = (y)) + +#define RB_FOREACH_REVERSE_SAFE(x, name, head, y) \ + for ((x) = RB_MAX(name, head); ((x) != NULL) && ((y) = name##_RB_PREV(x), (x) != NULL); \ + (x) = (y)) + +#endif /* _SYS_TREE_H_ */ diff --git a/src/unix-manager.c b/src/unix-manager.c index 9fb5bd7935bc..4da9f3f6d2bb 100644 --- a/src/unix-manager.c +++ b/src/unix-manager.c @@ -42,7 +42,8 @@ #include "util-path.h" #include "util-profiling.h" -#if (defined BUILD_UNIX_SOCKET) && (defined HAVE_SYS_UN_H) && (defined HAVE_SYS_STAT_H) && (defined HAVE_SYS_TYPES_H) +#if (defined BUILD_UNIX_SOCKET) && (defined HAVE_SYS_UN_H) && (defined HAVE_SYS_STAT_H) && \ + (defined HAVE_SYS_TYPES_H) #include #include #include @@ -52,19 +53,19 @@ // MSG_NOSIGNAL does not exists on OS X #ifdef OS_DARWIN -# ifndef MSG_NOSIGNAL -# define MSG_NOSIGNAL SO_NOSIGPIPE -# endif +#ifndef MSG_NOSIGNAL +#define MSG_NOSIGNAL SO_NOSIGPIPE +#endif #endif -#define SOCKET_PATH LOCAL_STATE_DIR "/run/suricata/" +#define SOCKET_PATH LOCAL_STATE_DIR "/run/suricata/" #define SOCKET_FILENAME "suricata-command.socket" -#define SOCKET_TARGET SOCKET_PATH SOCKET_FILENAME +#define SOCKET_TARGET SOCKET_PATH SOCKET_FILENAME SCCtrlCondT unix_manager_ctrl_cond; SCCtrlMutex unix_manager_ctrl_mutex; -#define MAX_FAILED_RULES 20 +#define MAX_FAILED_RULES 20 typedef struct Command_ { char *name; @@ -103,7 +104,7 @@ typedef struct UnixCommand_ { * * \retval 0 in case of error, 1 in case of success */ -static int UnixNew(UnixCommand * this) +static int UnixNew(UnixCommand *this) { struct sockaddr_un addr; int len; @@ -125,8 +126,7 @@ static int UnixNew(UnixCommand * this) if (PathIsAbsolute(socketname)) { strlcpy(sockettarget, socketname, sizeof(sockettarget)); } else { - snprintf(sockettarget, sizeof(sockettarget), "%s/%s", - SOCKET_PATH, socketname); + snprintf(sockettarget, sizeof(sockettarget), "%s/%s", SOCKET_PATH, socketname); check_dir = 1; } } else { @@ -140,7 +140,7 @@ static int UnixNew(UnixCommand * this) /* coverity[toctou] */ if (stat(SOCKET_PATH, &stat_buf) != 0) { /* coverity[toctou] */ - ret = SCMkDir(SOCKET_PATH, S_IRWXU|S_IXGRP|S_IRGRP); + ret = SCMkDir(SOCKET_PATH, S_IRWXU | S_IXGRP | S_IRGRP); if (ret != 0) { int err = errno; if (err != EEXIST) { @@ -155,7 +155,7 @@ static int UnixNew(UnixCommand * this) } /* Remove socket file */ - (void) unlink(sockettarget); + (void)unlink(sockettarget); /* set address */ addr.sun_family = AF_UNIX; @@ -173,14 +173,13 @@ static int UnixNew(UnixCommand * this) this->select_max = this->socket + 1; /* set reuse option */ - ret = setsockopt(this->socket, SOL_SOCKET, SO_REUSEADDR, - (char *) &on, sizeof(on)); - if ( ret != 0 ) { + ret = setsockopt(this->socket, SOL_SOCKET, SO_REUSEADDR, (char *)&on, sizeof(on)); + if (ret != 0) { SCLogWarning("Cannot set sockets options: %s.", strerror(errno)); } /* bind socket */ - ret = bind(this->socket, (struct sockaddr *) &addr, len); + ret = bind(this->socket, (struct sockaddr *)&addr, len); if (ret == -1) { SCLogWarning("Unix socket: UNIX socket bind(%s) error: %s", sockettarget, strerror(errno)); return 0; @@ -190,7 +189,7 @@ static int UnixNew(UnixCommand * this) /* Set file mode: will not fully work on most system, the group * permission is not changed on some Linux. *BSD won't do the * chmod: it returns EINVAL when calling chmod on sockets. */ - ret = chmod(sockettarget, S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP); + ret = chmod(sockettarget, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP); if (ret == -1) { int err = errno; SCLogWarning("Unable to change permission on socket: %s (%d)", strerror(err), err); @@ -215,7 +214,7 @@ static void UnixCommandSetMaxFD(UnixCommand *this) } this->select_max = this->socket + 1; - TAILQ_FOREACH(item, &this->clients, next) { + TAILQ_FOREACH (item, &this->clients, next) { if (item->fd >= this->select_max) { this->select_max = item->fd + 1; } @@ -249,12 +248,12 @@ static void UnixClientFree(UnixClient *c) /** * \brief Close the unix socket */ -static void UnixCommandClose(UnixCommand *this, int fd) +static void UnixCommandClose(UnixCommand *this, int fd) { UnixClient *item; int found = 0; - TAILQ_FOREACH(item, &this->clients, next) { + TAILQ_FOREACH (item, &this->clients, next) { if (item->fd == fd) { found = 1; break; @@ -274,23 +273,20 @@ static void UnixCommandClose(UnixCommand *this, int fd) } #define UNIX_PROTO_VERSION_LENGTH 200 -#define UNIX_PROTO_VERSION_V1 "0.1" -#define UNIX_PROTO_V1 1 -#define UNIX_PROTO_VERSION "0.2" -#define UNIX_PROTO_V2 2 +#define UNIX_PROTO_VERSION_V1 "0.1" +#define UNIX_PROTO_V1 1 +#define UNIX_PROTO_VERSION "0.2" +#define UNIX_PROTO_V2 2 static int UnixCommandSendJSONToClient(UnixClient *client, json_t *js) { MemBufferReset(client->mbuf); - OutputJSONMemBufferWrapper wrapper = { - .buffer = &client->mbuf, - .expand_by = CLIENT_BUFFER_SIZE - }; + OutputJSONMemBufferWrapper wrapper = { .buffer = &client->mbuf, + .expand_by = CLIENT_BUFFER_SIZE }; int r = json_dump_callback(js, OutputJSONMemBufferCallback, &wrapper, - JSON_PRESERVE_ORDER|JSON_COMPACT|JSON_ENSURE_ASCII| - JSON_ESCAPE_SLASH); + JSON_PRESERVE_ORDER | JSON_COMPACT | JSON_ENSURE_ASCII | JSON_ESCAPE_SLASH); if (r != 0) { SCLogWarning("unable to serialize JSON object"); return -1; @@ -304,15 +300,14 @@ static int UnixCommandSendJSONToClient(UnixClient *client, json_t *js) } if (send(client->fd, (const char *)MEMBUFFER_BUFFER(client->mbuf), - MEMBUFFER_OFFSET(client->mbuf), MSG_NOSIGNAL) == -1) - { + MEMBUFFER_OFFSET(client->mbuf), MSG_NOSIGNAL) == -1) { SCLogWarning("unable to send block of size " "%" PRIuMAX ": %s", (uintmax_t)MEMBUFFER_OFFSET(client->mbuf), strerror(errno)); return -1; } - SCLogDebug("sent message of size %"PRIuMAX" to client socket %d", + SCLogDebug("sent message of size %" PRIuMAX " to client socket %d", (uintmax_t)MEMBUFFER_OFFSET(client->mbuf), client->fd); return 0; } @@ -340,24 +335,22 @@ static int UnixCommandAccept(UnixCommand *this) /* accept client socket */ socklen_t len = sizeof(this->client_addr); - client = accept(this->socket, (struct sockaddr *) &this->client_addr, - &len); + client = accept(this->socket, (struct sockaddr *)&this->client_addr, &len); if (client < 0) { - SCLogInfo("Unix socket: accept() error: %s", - strerror(errno)); + SCLogInfo("Unix socket: accept() error: %s", strerror(errno)); return 0; } SCLogDebug("Unix socket: client connection"); /* read client version */ - buffer[sizeof(buffer)-1] = 0; - ret = recv(client, buffer, sizeof(buffer)-1, 0); + buffer[sizeof(buffer) - 1] = 0; + ret = recv(client, buffer, sizeof(buffer) - 1, 0); if (ret < 0) { SCLogInfo("Command server: client doesn't send version"); close(client); return 0; } - if (ret >= (int)(sizeof(buffer)-1)) { + if (ret >= (int)(sizeof(buffer) - 1)) { SCLogInfo("Command server: client message is too long, " "disconnect him."); close(client); @@ -381,16 +374,14 @@ static int UnixCommandAccept(UnixCommand *this) } /* check client version */ - if ((strcmp(json_string_value(version), UNIX_PROTO_VERSION) != 0) - && (strcmp(json_string_value(version), UNIX_PROTO_VERSION_V1) != 0)) { - SCLogInfo("Unix socket: invalid client version: \"%s\"", - json_string_value(version)); + if ((strcmp(json_string_value(version), UNIX_PROTO_VERSION) != 0) && + (strcmp(json_string_value(version), UNIX_PROTO_VERSION_V1) != 0)) { + SCLogInfo("Unix socket: invalid client version: \"%s\"", json_string_value(version)); json_decref(client_msg); close(client); return 0; } else { - SCLogDebug("Unix socket: client version: \"%s\"", - json_string_value(version)); + SCLogDebug("Unix socket: client version: \"%s\"", json_string_value(version)); if (strcmp(json_string_value(version), UNIX_PROTO_VERSION_V1) == 0) { client_version = UNIX_PROTO_V1; } else { @@ -434,12 +425,12 @@ static int UnixCommandAccept(UnixCommand *this) return 1; } -static int UnixCommandBackgroundTasks(UnixCommand* this) +static int UnixCommandBackgroundTasks(UnixCommand *this) { int ret = 1; Task *ltask; - TAILQ_FOREACH(ltask, &this->tasks, next) { + TAILQ_FOREACH (ltask, &this->tasks, next) { int fret = ltask->Func(ltask->data); if (fret != TM_ECODE_OK) { ret = 0; @@ -457,14 +448,14 @@ static int UnixCommandBackgroundTasks(UnixCommand* this) * * \retval 0 in case of error, 1 in case of success */ -static int UnixCommandExecute(UnixCommand * this, char *command, UnixClient *client) +static int UnixCommandExecute(UnixCommand *this, char *command, UnixClient *client) { int ret = 1; json_error_t error; json_t *jsoncmd = NULL; json_t *cmd = NULL; json_t *server_msg = json_object(); - const char * value; + const char *value; int found = 0; Command *lcmd; @@ -479,19 +470,19 @@ static int UnixCommandExecute(UnixCommand * this, char *command, UnixClient *cli } cmd = json_object_get(jsoncmd, "command"); - if(!json_is_string(cmd)) { + if (!json_is_string(cmd)) { SCLogInfo("error: command is not a string"); goto error_cmd; } value = json_string_value(cmd); - TAILQ_FOREACH(lcmd, &this->commands, next) { + TAILQ_FOREACH (lcmd, &this->commands, next) { if (!strcmp(value, lcmd->name)) { int fret = TM_ECODE_OK; found = 1; if (lcmd->flags & UNIX_CMD_TAKE_ARGS) { cmd = json_object_get(jsoncmd, "arguments"); - if(!json_is_object(cmd)) { + if (!json_is_object(cmd)) { SCLogInfo("error: argument is not an object"); goto error_cmd; } @@ -534,7 +525,7 @@ static int UnixCommandExecute(UnixCommand * this, char *command, UnixClient *cli return 0; } -static void UnixCommandRun(UnixCommand * this, UnixClient *client) +static void UnixCommandRun(UnixCommand *this, UnixClient *client) { char buffer[4096]; int ret; @@ -549,14 +540,16 @@ static void UnixCommandRun(UnixCommand * this, UnixClient *client) UnixCommandClose(this, client->fd); return; } - if (ret >= (int)(sizeof(buffer)-1)) { + if (ret >= (int)(sizeof(buffer) - 1)) { SCLogError("Command server: client command is too long, " "disconnect him."); UnixCommandClose(this, client->fd); } buffer[ret] = 0; } else { - int try = 0; + int + try + = 0; int offset = 0; int cmd_over = 0; ret = recv(client->fd, buffer + offset, sizeof(buffer) - offset - 1, 0); @@ -570,13 +563,13 @@ static void UnixCommandRun(UnixCommand * this, UnixClient *client) UnixCommandClose(this, client->fd); return; } - if (ret >= (int)(sizeof(buffer)- offset - 1)) { + if (ret >= (int)(sizeof(buffer) - offset - 1)) { SCLogInfo("Command server: client command is too long, " - "disconnect him."); + "disconnect him."); UnixCommandClose(this, client->fd); } if (buffer[ret - 1] == '\n') { - buffer[ret-1] = 0; + buffer[ret - 1] = 0; cmd_over = 1; } else { struct timeval tv; @@ -587,7 +580,8 @@ static void UnixCommandRun(UnixCommand * this, UnixClient *client) FD_SET(client->fd, &select_set); tv.tv_sec = 0; tv.tv_usec = 200 * 1000; - try++; + try + ++; ret = select(client->fd, &select_set, NULL, NULL, &tv); /* catch select() error */ if (ret == -1) { @@ -600,8 +594,7 @@ static void UnixCommandRun(UnixCommand * this, UnixClient *client) } } while (ret == 0 && try < 3); if (ret > 0) { - ret = recv(client->fd, buffer + offset, - sizeof(buffer) - offset - 1, 0); + ret = recv(client->fd, buffer + offset, sizeof(buffer) - offset - 1, 0); } } } while (try < 3 && cmd_over == 0); @@ -620,7 +613,7 @@ static void UnixCommandRun(UnixCommand * this, UnixClient *client) * * \retval 0 in case of error, 1 in case of success */ -static int UnixMain(UnixCommand * this) +static int UnixMain(UnixCommand *this) { struct timeval tv; int ret; @@ -638,7 +631,7 @@ static int UnixMain(UnixCommand * this) /* Wait activity on the socket */ FD_ZERO(&select_set); FD_SET(this->socket, &select_set); - TAILQ_FOREACH(uclient, &this->clients, next) { + TAILQ_FOREACH (uclient, &this->clients, next) { FD_SET(uclient->fd, &select_set); } @@ -661,7 +654,7 @@ static int UnixMain(UnixCommand * this) return 1; } - TAILQ_FOREACH_SAFE(uclient, &this->clients, next, tclient) { + TAILQ_FOREACH_SAFE (uclient, &this->clients, next, tclient) { if (FD_ISSET(uclient->fd, &select_set)) { UnixCommandRun(this, uclient); } @@ -674,8 +667,7 @@ static int UnixMain(UnixCommand * this) return 1; } -static TmEcode UnixManagerShutdownCommand(json_t *cmd, - json_t *server_msg, void *data) +static TmEcode UnixManagerShutdownCommand(json_t *cmd, json_t *server_msg, void *data) { SCEnter(); json_object_set_new(server_msg, "message", json_string("Closing Suricata")); @@ -683,16 +675,14 @@ static TmEcode UnixManagerShutdownCommand(json_t *cmd, SCReturnInt(TM_ECODE_OK); } -static TmEcode UnixManagerVersionCommand(json_t *cmd, - json_t *server_msg, void *data) +static TmEcode UnixManagerVersionCommand(json_t *cmd, json_t *server_msg, void *data) { SCEnter(); json_object_set_new(server_msg, "message", json_string(GetProgramVersion())); SCReturnInt(TM_ECODE_OK); } -static TmEcode UnixManagerUptimeCommand(json_t *cmd, - json_t *server_msg, void *data) +static TmEcode UnixManagerUptimeCommand(json_t *cmd, json_t *server_msg, void *data) { SCEnter(); int uptime; @@ -703,30 +693,29 @@ static TmEcode UnixManagerUptimeCommand(json_t *cmd, SCReturnInt(TM_ECODE_OK); } -static TmEcode UnixManagerRunningModeCommand(json_t *cmd, - json_t *server_msg, void *data) +static TmEcode UnixManagerRunningModeCommand(json_t *cmd, json_t *server_msg, void *data) { SCEnter(); json_object_set_new(server_msg, "message", json_string(RunmodeGetActive())); SCReturnInt(TM_ECODE_OK); } -static TmEcode UnixManagerCaptureModeCommand(json_t *cmd, - json_t *server_msg, void *data) +static TmEcode UnixManagerCaptureModeCommand(json_t *cmd, json_t *server_msg, void *data) { SCEnter(); json_object_set_new(server_msg, "message", json_string(RunModeGetMainMode())); SCReturnInt(TM_ECODE_OK); } -static TmEcode UnixManagerReloadRulesWrapper(json_t *cmd, json_t *server_msg, void *data, int do_wait) +static TmEcode UnixManagerReloadRulesWrapper( + json_t *cmd, json_t *server_msg, void *data, int do_wait) { SCEnter(); if (SuriHasSigFile()) { json_object_set_new(server_msg, "message", - json_string("Live rule reload not possible if -s " - "or -S option used at runtime.")); + json_string("Live rule reload not possible if -s " + "or -S option used at runtime.")); SCReturnInt(TM_ECODE_FAILED); } @@ -756,8 +745,7 @@ static TmEcode UnixManagerNonBlockingReloadRules(json_t *cmd, json_t *server_msg return UnixManagerReloadRulesWrapper(cmd, server_msg, data, 0); } -static TmEcode UnixManagerReloadTimeCommand(json_t *cmd, - json_t *server_msg, void *data) +static TmEcode UnixManagerReloadTimeCommand(json_t *cmd, json_t *server_msg, void *data) { SCEnter(); TmEcode retval; @@ -768,8 +756,7 @@ static TmEcode UnixManagerReloadTimeCommand(json_t *cmd, SCReturnInt(retval); } -static TmEcode UnixManagerRulesetStatsCommand(json_t *cmd, - json_t *server_msg, void *data) +static TmEcode UnixManagerRulesetStatsCommand(json_t *cmd, json_t *server_msg, void *data) { SCEnter(); TmEcode retval; @@ -812,8 +799,7 @@ static TmEcode UnixManagerRulesetProfileStopCommand(json_t *cmd, json_t *server_ } #endif -static TmEcode UnixManagerShowFailedRules(json_t *cmd, - json_t *server_msg, void *data) +static TmEcode UnixManagerShowFailedRules(json_t *cmd, json_t *server_msg, void *data) { SCEnter(); int rules_cnt = 0; @@ -833,7 +819,7 @@ static TmEcode UnixManagerShowFailedRules(json_t *cmd, } while (list) { SigString *sigs_str = NULL; - TAILQ_FOREACH(sigs_str, &list->sig_stat.failed_sigs, next) { + TAILQ_FOREACH (sigs_str, &list->sig_stat.failed_sigs, next) { json_t *jdata = json_object(); if (jdata == NULL) { json_object_set_new(server_msg, "message", json_string("Unable to get the sig")); @@ -869,8 +855,7 @@ static TmEcode UnixManagerShowFailedRules(json_t *cmd, SCReturnInt(TM_ECODE_FAILED); } -static TmEcode UnixManagerConfGetCommand(json_t *cmd, - json_t *server_msg, void *data) +static TmEcode UnixManagerConfGetCommand(json_t *cmd, json_t *server_msg, void *data) { SCEnter(); @@ -878,7 +863,7 @@ static TmEcode UnixManagerConfGetCommand(json_t *cmd, char *variable = NULL; json_t *jarg = json_object_get(cmd, "variable"); - if(!json_is_string(jarg)) { + if (!json_is_string(jarg)) { SCLogInfo("error: variable is not a string"); json_object_set_new(server_msg, "message", json_string("variable is not a string")); SCReturnInt(TM_ECODE_FAILED); @@ -899,30 +884,29 @@ static TmEcode UnixManagerConfGetCommand(json_t *cmd, SCReturnInt(TM_ECODE_FAILED); } -static TmEcode UnixManagerListCommand(json_t *cmd, - json_t *answer, void *data) +static TmEcode UnixManagerListCommand(json_t *cmd, json_t *answer, void *data) { SCEnter(); json_t *jdata; json_t *jarray; Command *lcmd = NULL; - UnixCommand *gcmd = (UnixCommand *) data; + UnixCommand *gcmd = (UnixCommand *)data; int i = 0; jdata = json_object(); if (jdata == NULL) { - json_object_set_new(answer, "message", - json_string("internal error at json object creation")); + json_object_set_new( + answer, "message", json_string("internal error at json object creation")); return TM_ECODE_FAILED; } jarray = json_array(); if (jarray == NULL) { - json_object_set_new(answer, "message", - json_string("internal error at json object creation")); + json_object_set_new( + answer, "message", json_string("internal error at json object creation")); return TM_ECODE_FAILED; } - TAILQ_FOREACH(lcmd, &gcmd->commands, next) { + TAILQ_FOREACH (lcmd, &gcmd->commands, next) { json_array_append_new(jarray, json_string(lcmd->name)); i++; } @@ -967,7 +951,7 @@ static UnixCommand command; * * This function adds a command to the list of commands available * through the unix socket. - * + * * When a command is received from user through the unix socket, the content * of 'Command' field in the JSON message is match against keyword, then the * Func is called. See UnixSocketAddPcapFile() for an example. @@ -978,9 +962,8 @@ static UnixCommand command; * \param flags a flag now used to tune the command type * \retval TM_ECODE_OK in case of success, TM_ECODE_FAILED in case of failure */ -TmEcode UnixManagerRegisterCommand(const char * keyword, - TmEcode (*Func)(json_t *, json_t *, void *), - void *data, int flags) +TmEcode UnixManagerRegisterCommand( + const char *keyword, TmEcode (*Func)(json_t *, json_t *, void *), void *data, int flags) { SCEnter(); Command *cmd = NULL; @@ -996,7 +979,7 @@ TmEcode UnixManagerRegisterCommand(const char * keyword, SCReturnInt(TM_ECODE_FAILED); } - TAILQ_FOREACH(lcmd, &command.commands, next) { + TAILQ_FOREACH (lcmd, &command.commands, next) { if (!strcmp(keyword, lcmd->name)) { SCLogError("%s already registered", keyword); SCReturnInt(TM_ECODE_FAILED); @@ -1028,13 +1011,12 @@ TmEcode UnixManagerRegisterCommand(const char * keyword, * * This function adds a task to run in the background. The task is run * each time the UnixMain() function exits from select. - * + * * \param Func function to run when a command is received * \param data a pointer to data that are passed to Func when it is run * \retval TM_ECODE_OK in case of success, TM_ECODE_FAILED in case of failure */ -TmEcode UnixManagerRegisterBackgroundTask(TmEcode (*Func)(void *), - void *data) +TmEcode UnixManagerRegisterBackgroundTask(TmEcode (*Func)(void *), void *data) { SCEnter(); Task *task = NULL; @@ -1084,7 +1066,8 @@ int UnixManagerInit(void) UnixManagerRegisterCommand("dump-counters", StatsOutputCounterSocket, NULL, 0); UnixManagerRegisterCommand("reload-rules", UnixManagerReloadRules, NULL, 0); UnixManagerRegisterCommand("ruleset-reload-rules", UnixManagerReloadRules, NULL, 0); - UnixManagerRegisterCommand("ruleset-reload-nonblocking", UnixManagerNonBlockingReloadRules, NULL, 0); + UnixManagerRegisterCommand( + "ruleset-reload-nonblocking", UnixManagerNonBlockingReloadRules, NULL, 0); UnixManagerRegisterCommand("ruleset-reload-time", UnixManagerReloadTimeCommand, NULL, 0); UnixManagerRegisterCommand("ruleset-stats", UnixManagerRulesetStatsCommand, NULL, 0); UnixManagerRegisterCommand("ruleset-failed-rules", UnixManagerShowFailedRules, NULL, 0); @@ -1095,14 +1078,20 @@ int UnixManagerInit(void) UnixManagerRegisterCommand( "ruleset-profile-stop", UnixManagerRulesetProfileStopCommand, NULL, 0); #endif - UnixManagerRegisterCommand("register-tenant-handler", UnixSocketRegisterTenantHandler, &command, UNIX_CMD_TAKE_ARGS); - UnixManagerRegisterCommand("unregister-tenant-handler", UnixSocketUnregisterTenantHandler, &command, UNIX_CMD_TAKE_ARGS); - UnixManagerRegisterCommand("register-tenant", UnixSocketRegisterTenant, &command, UNIX_CMD_TAKE_ARGS); - UnixManagerRegisterCommand("reload-tenant", UnixSocketReloadTenant, &command, UNIX_CMD_TAKE_ARGS); + UnixManagerRegisterCommand("register-tenant-handler", UnixSocketRegisterTenantHandler, &command, + UNIX_CMD_TAKE_ARGS); + UnixManagerRegisterCommand("unregister-tenant-handler", UnixSocketUnregisterTenantHandler, + &command, UNIX_CMD_TAKE_ARGS); + UnixManagerRegisterCommand( + "register-tenant", UnixSocketRegisterTenant, &command, UNIX_CMD_TAKE_ARGS); + UnixManagerRegisterCommand( + "reload-tenant", UnixSocketReloadTenant, &command, UNIX_CMD_TAKE_ARGS); UnixManagerRegisterCommand("reload-tenants", UnixSocketReloadTenants, &command, 0); - UnixManagerRegisterCommand("unregister-tenant", UnixSocketUnregisterTenant, &command, UNIX_CMD_TAKE_ARGS); + UnixManagerRegisterCommand( + "unregister-tenant", UnixSocketUnregisterTenant, &command, UNIX_CMD_TAKE_ARGS); UnixManagerRegisterCommand("add-hostbit", UnixSocketHostbitAdd, &command, UNIX_CMD_TAKE_ARGS); - UnixManagerRegisterCommand("remove-hostbit", UnixSocketHostbitRemove, &command, UNIX_CMD_TAKE_ARGS); + UnixManagerRegisterCommand( + "remove-hostbit", UnixSocketHostbitRemove, &command, UNIX_CMD_TAKE_ARGS); UnixManagerRegisterCommand("list-hostbit", UnixSocketHostbitList, &command, UNIX_CMD_TAKE_ARGS); UnixManagerRegisterCommand("reopen-log-files", UnixManagerReopenLogFiles, NULL, 0); UnixManagerRegisterCommand("memcap-set", UnixSocketSetMemcap, &command, UNIX_CMD_TAKE_ARGS); @@ -1110,7 +1099,8 @@ int UnixManagerInit(void) UnixManagerRegisterCommand("memcap-list", UnixSocketShowAllMemcap, NULL, 0); UnixManagerRegisterCommand("dataset-add", UnixSocketDatasetAdd, &command, UNIX_CMD_TAKE_ARGS); - UnixManagerRegisterCommand("dataset-remove", UnixSocketDatasetRemove, &command, UNIX_CMD_TAKE_ARGS); + UnixManagerRegisterCommand( + "dataset-remove", UnixSocketDatasetRemove, &command, UNIX_CMD_TAKE_ARGS); UnixManagerRegisterCommand( "get-flow-stats-by-id", UnixSocketGetFlowStatsById, &command, UNIX_CMD_TAKE_ARGS); UnixManagerRegisterCommand("dataset-dump", UnixSocketDatasetDump, NULL, 0); @@ -1166,7 +1156,7 @@ static TmEcode UnixManager(ThreadVars *th_v, void *thread_data) if ((ret == 0) || (TmThreadsCheckFlag(th_v, THV_KILL))) { UnixClient *item; UnixClient *titem; - TAILQ_FOREACH_SAFE(item, &(&command)->clients, next, titem) { + TAILQ_FOREACH_SAFE (item, &(&command)->clients, next, titem) { close(item->fd); SCFree(item); } @@ -1179,7 +1169,6 @@ static TmEcode UnixManager(ThreadVars *th_v, void *thread_data) return TM_ECODE_OK; } - /** \brief Spawn the unix socket manager thread * * \param mode if set to 1, init failure cause suricata exit @@ -1191,8 +1180,7 @@ void UnixManagerThreadSpawn(int mode) SCCtrlCondInit(&unix_manager_ctrl_cond, NULL); SCCtrlMutexInit(&unix_manager_ctrl_mutex, NULL); - tv_unixmgr = TmThreadCreateCmdThreadByName(thread_name_unix_socket, - "UnixManager", 0); + tv_unixmgr = TmThreadCreateCmdThreadByName(thread_name_unix_socket, "UnixManager", 0); if (tv_unixmgr == NULL) { FatalError("TmThreadsCreate failed"); @@ -1214,14 +1202,11 @@ void UnixManagerThreadSpawnNonRunmode(const bool unix_socket) /* Spawn the unix socket manager thread */ if (unix_socket) { if (UnixManagerInit() == 0) { - UnixManagerRegisterCommand("iface-stat", LiveDeviceIfaceStat, NULL, - UNIX_CMD_TAKE_ARGS); + UnixManagerRegisterCommand("iface-stat", LiveDeviceIfaceStat, NULL, UNIX_CMD_TAKE_ARGS); UnixManagerRegisterCommand("iface-list", LiveDeviceIfaceList, NULL, 0); - UnixManagerRegisterCommand("iface-bypassed-stat", - LiveDeviceGetBypassedStats, NULL, 0); + UnixManagerRegisterCommand("iface-bypassed-stat", LiveDeviceGetBypassedStats, NULL, 0); /* For backward compatibility */ - UnixManagerRegisterCommand("ebpf-bypassed-stat", - LiveDeviceGetBypassedStats, NULL, 0); + UnixManagerRegisterCommand("ebpf-bypassed-stat", LiveDeviceGetBypassedStats, NULL, 0); UnixManagerThreadSpawn(0); } } @@ -1291,9 +1276,10 @@ void UnixManagerThreadSpawnNonRunmode(const bool unix_socket_enabled) #endif /* BUILD_UNIX_SOCKET */ -void TmModuleUnixManagerRegister (void) +void TmModuleUnixManagerRegister(void) { -#if defined(BUILD_UNIX_SOCKET) && defined(HAVE_SYS_UN_H) && defined(HAVE_SYS_STAT_H) && defined(HAVE_SYS_TYPES_H) +#if defined(BUILD_UNIX_SOCKET) && defined(HAVE_SYS_UN_H) && defined(HAVE_SYS_STAT_H) && \ + defined(HAVE_SYS_TYPES_H) tmm_modules[TMM_UNIXMANAGER].name = "UnixManager"; tmm_modules[TMM_UNIXMANAGER].ThreadInit = UnixManagerThreadInit; tmm_modules[TMM_UNIXMANAGER].ThreadDeinit = UnixManagerThreadDeinit; diff --git a/src/unix-manager.h b/src/unix-manager.h index 960879b3cbbf..8a14992efb52 100644 --- a/src/unix-manager.h +++ b/src/unix-manager.h @@ -36,12 +36,9 @@ void UnixManagerThreadSpawn(int mode); void UnixSocketKillSocketThread(void); #ifdef BUILD_UNIX_SOCKET -TmEcode UnixManagerRegisterCommand(const char * keyword, - TmEcode (*Func)(json_t *, json_t *, void *), - void *data, int flags); -TmEcode UnixManagerRegisterBackgroundTask( - TmEcode (*Func)(void *), - void *data); +TmEcode UnixManagerRegisterCommand( + const char *keyword, TmEcode (*Func)(json_t *, json_t *, void *), void *data, int flags); +TmEcode UnixManagerRegisterBackgroundTask(TmEcode (*Func)(void *), void *data); #endif void TmModuleUnixManagerRegister(void); diff --git a/src/util-action.c b/src/util-action.c index 1b24bc5b0792..9aaf11db4984 100644 --- a/src/util-action.c +++ b/src/util-action.c @@ -37,7 +37,7 @@ #include "util-debug.h" /* Default order: */ -uint8_t action_order_sigs[4] = {ACTION_PASS, ACTION_DROP, ACTION_REJECT, ACTION_ALERT}; +uint8_t action_order_sigs[4] = { ACTION_PASS, ACTION_DROP, ACTION_REJECT, ACTION_ALERT }; /* This order can be changed from config */ /** @@ -53,9 +53,7 @@ uint8_t action_order_sigs[4] = {ACTION_PASS, ACTION_DROP, ACTION_REJECT, ACTION_ uint8_t ActionOrderVal(uint8_t action) { /* reject_both and reject_dst have the same prio as reject */ - if( (action & ACTION_REJECT) || - (action & ACTION_REJECT_BOTH) || - (action & ACTION_REJECT_DST)) { + if ((action & ACTION_REJECT) || (action & ACTION_REJECT_BOTH) || (action & ACTION_REJECT_DST)) { action = ACTION_REJECT; } uint8_t i = 0; @@ -76,13 +74,13 @@ uint8_t ActionOrderVal(uint8_t action) */ static uint8_t ActionAsciiToFlag(const char *action) { - if (strcmp(action,"pass") == 0) + if (strcmp(action, "pass") == 0) return ACTION_PASS; - if (strcmp(action,"drop") == 0) + if (strcmp(action, "drop") == 0) return ACTION_DROP; - if (strcmp(action,"reject") == 0) + if (strcmp(action, "reject") == 0) return ACTION_REJECT; - if (strcmp(action,"alert") == 0) + if (strcmp(action, "alert") == 0) return ACTION_ALERT; return 0; @@ -99,7 +97,7 @@ int ActionInitConfig(void) { uint8_t actions_used = 0; uint8_t action_flag = 0; - uint8_t actions_config[4] = {0, 0, 0, 0}; + uint8_t actions_config[4] = { 0, 0, 0, 0 }; int order = 0; ConfNode *action_order; @@ -110,9 +108,8 @@ int ActionInitConfig(void) if (action_order == NULL) { /* No configuration, use defaults. */ return 0; - } - else { - TAILQ_FOREACH(action, &action_order->head, next) { + } else { + TAILQ_FOREACH (action, &action_order->head, next) { SCLogDebug("Loading action order : %s", action->val); action_flag = ActionAsciiToFlag(action->val); if (action_flag == 0) { @@ -161,7 +158,7 @@ int ActionInitConfig(void) return 0; - error: +error: return -1; } @@ -407,7 +404,7 @@ action-order:\n\ static int UtilActionTest08(void) { char config[] = "%YAML 1.1\n" - "---\n"; + "---\n"; ConfCreateContextBackup(); ConfInit(); diff --git a/src/util-affinity.c b/src/util-affinity.c index 06256db5b8cd..99b06737b24a 100644 --- a/src/util-affinity.c +++ b/src/util-affinity.c @@ -33,28 +33,28 @@ ThreadsAffinityType thread_affinity[MAX_CPU_SET] = { { - .name = "receive-cpu-set", - .mode_flag = EXCLUSIVE_AFFINITY, - .prio = PRIO_MEDIUM, - .lcpu = 0, + .name = "receive-cpu-set", + .mode_flag = EXCLUSIVE_AFFINITY, + .prio = PRIO_MEDIUM, + .lcpu = 0, }, { - .name = "worker-cpu-set", - .mode_flag = EXCLUSIVE_AFFINITY, - .prio = PRIO_MEDIUM, - .lcpu = 0, + .name = "worker-cpu-set", + .mode_flag = EXCLUSIVE_AFFINITY, + .prio = PRIO_MEDIUM, + .lcpu = 0, }, { - .name = "verdict-cpu-set", - .mode_flag = BALANCED_AFFINITY, - .prio = PRIO_MEDIUM, - .lcpu = 0, + .name = "verdict-cpu-set", + .mode_flag = BALANCED_AFFINITY, + .prio = PRIO_MEDIUM, + .lcpu = 0, }, { - .name = "management-cpu-set", - .mode_flag = BALANCED_AFFINITY, - .prio = PRIO_MEDIUM, - .lcpu = 0, + .name = "management-cpu-set", + .mode_flag = BALANCED_AFFINITY, + .prio = PRIO_MEDIUM, + .lcpu = 0, }, }; @@ -65,7 +65,7 @@ int thread_affinity_init_done = 0; * \brief find affinity by its name * \retval a pointer to the affinity or NULL if not found */ -ThreadsAffinityType * GetAffinityTypeFromName(const char *name) +ThreadsAffinityType *GetAffinityTypeFromName(const char *name) { int i; for (i = 0; i < MAX_CPU_SET; i++) { @@ -95,14 +95,13 @@ static void AffinitySetupInit(void) return; } -void BuildCpusetWithCallback(const char *name, ConfNode *node, - void (*Callback)(int i, void * data), - void *data) +void BuildCpusetWithCallback( + const char *name, ConfNode *node, void (*Callback)(int i, void *data), void *data) { ConfNode *lnode; - TAILQ_FOREACH(lnode, &node->head, next) { + TAILQ_FOREACH (lnode, &node->head, next) { int i; - long int a,b; + long int a, b; int stop = 0; int max = UtilCpuGetNumProcessorsOnline() - 1; if (!strcmp(lnode->val, "all")) { @@ -139,7 +138,7 @@ void BuildCpusetWithCallback(const char *name, ConfNode *node, } b = a; } - for (i = a; i<= b; i++) { + for (i = a; i <= b; i++) { Callback(i, data); } if (stop) @@ -154,7 +153,7 @@ static void AffinityCallback(int i, void *data) static void BuildCpuset(const char *name, ConfNode *node, cpu_set_t *cpu) { - BuildCpusetWithCallback(name, node, AffinityCallback, (void *) cpu); + BuildCpusetWithCallback(name, node, AffinityCallback, (void *)cpu); } #endif /* OS_WIN32 and __OpenBSD__ */ @@ -179,11 +178,11 @@ void AffinitySetupLoadFromConfig(void) return; } - TAILQ_FOREACH(affinity, &root->head, next) { + TAILQ_FOREACH (affinity, &root->head, next) { if (strcmp(affinity->val, "decode-cpu-set") == 0 || - strcmp(affinity->val, "stream-cpu-set") == 0 || - strcmp(affinity->val, "reject-cpu-set") == 0 || - strcmp(affinity->val, "output-cpu-set") == 0) { + strcmp(affinity->val, "stream-cpu-set") == 0 || + strcmp(affinity->val, "reject-cpu-set") == 0 || + strcmp(affinity->val, "output-cpu-set") == 0) { continue; } @@ -245,8 +244,7 @@ void AffinitySetupLoadFromConfig(void) } else { FatalError("unknown cpu_affinity prio"); } - SCLogConfig("Using default prio '%s' for set '%s'", - node->val, setname); + SCLogConfig("Using default prio '%s' for set '%s'", node->val, setname); } } @@ -268,7 +266,7 @@ void AffinitySetupLoadFromConfig(void) "count: '%s'", node->val); } - if (! taf->nb_threads) { + if (!taf->nb_threads) { FatalError("bad value for threads count"); } } diff --git a/src/util-affinity.h b/src/util-affinity.h index ef3c556498d9..bb48092078d0 100644 --- a/src/util-affinity.h +++ b/src/util-affinity.h @@ -42,25 +42,15 @@ #include #include #include -#define cpu_set_t thread_affinity_policy_data_t -#define CPU_SET(cpu_id, new_mask) (*(new_mask)).affinity_tag = (cpu_id + 1) +#define cpu_set_t thread_affinity_policy_data_t +#define CPU_SET(cpu_id, new_mask) (*(new_mask)).affinity_tag = (cpu_id + 1) #define CPU_ISSET(cpu_id, new_mask) ((*(new_mask)).affinity_tag == (cpu_id + 1)) -#define CPU_ZERO(new_mask) (*(new_mask)).affinity_tag = THREAD_AFFINITY_TAG_NULL +#define CPU_ZERO(new_mask) (*(new_mask)).affinity_tag = THREAD_AFFINITY_TAG_NULL #endif -enum { - RECEIVE_CPU_SET, - WORKER_CPU_SET, - VERDICT_CPU_SET, - MANAGEMENT_CPU_SET, - MAX_CPU_SET -}; +enum { RECEIVE_CPU_SET, WORKER_CPU_SET, VERDICT_CPU_SET, MANAGEMENT_CPU_SET, MAX_CPU_SET }; -enum { - BALANCED_AFFINITY, - EXCLUSIVE_AFFINITY, - MAX_AFFINITY -}; +enum { BALANCED_AFFINITY, EXCLUSIVE_AFFINITY, MAX_AFFINITY }; typedef struct ThreadsAffinityType_ { const char *name; @@ -84,7 +74,7 @@ extern ThreadsAffinityType thread_affinity[MAX_CPU_SET]; #endif void AffinitySetupLoadFromConfig(void); -ThreadsAffinityType * GetAffinityTypeFromName(const char *name); +ThreadsAffinityType *GetAffinityTypeFromName(const char *name); uint16_t AffinityGetNextCPU(ThreadsAffinityType *taf); uint16_t UtilAffinityGetAffinedCPUNum(ThreadsAffinityType *taf); @@ -93,8 +83,7 @@ uint16_t UtilAffinityCpusOverlap(ThreadsAffinityType *taf1, ThreadsAffinityType void UtilAffinityCpusExclude(ThreadsAffinityType *mod_taf, ThreadsAffinityType *static_taf); #endif /* HAVE_DPDK */ -void BuildCpusetWithCallback(const char *name, ConfNode *node, - void (*Callback)(int i, void * data), - void *data); +void BuildCpusetWithCallback( + const char *name, ConfNode *node, void (*Callback)(int i, void *data), void *data); #endif /* __UTIL_AFFINITY_H__ */ diff --git a/src/util-atomic.c b/src/util-atomic.c index 11aa51afd02b..456e937bb28a 100644 --- a/src/util-atomic.c +++ b/src/util-atomic.c @@ -58,7 +58,7 @@ static int SCAtomicTest01(void) result = 1; - end: +end: return result; } diff --git a/src/util-atomic.h b/src/util-atomic.h index 5f2357143010..0cdc09ea44ec 100644 --- a/src/util-atomic.h +++ b/src/util-atomic.h @@ -30,11 +30,10 @@ * uses "somevar", internally "somevar_sc_atomic__" is used. */ - #ifndef __UTIL_ATOMIC_H__ #define __UTIL_ATOMIC_H__ -#if HAVE_STDATOMIC_H==1 +#if HAVE_STDATOMIC_H == 1 #include @@ -56,8 +55,7 @@ * * \warning variable is not initialized */ -#define SC_ATOMIC_DECLARE(type, name) \ - _Atomic(type) name ## _sc_atomic__ +#define SC_ATOMIC_DECLARE(type, name) _Atomic(type) name##_sc_atomic__ /** * \brief wrapper for referencing an atomic variable declared on another file. @@ -69,14 +67,12 @@ * to modify it, so no need for locks. * */ -#define SC_ATOMIC_EXTERN(type, name) \ - extern _Atomic(type) (name ## _sc_atomic__) +#define SC_ATOMIC_EXTERN(type, name) extern _Atomic(type)(name##_sc_atomic__) /** * \brief wrapper for declaring an atomic variable and initializing it. **/ -#define SC_ATOMIC_DECL_AND_INIT(type, name) \ - _Atomic(type) (name ## _sc_atomic__) = 0 +#define SC_ATOMIC_DECL_AND_INIT(type, name) _Atomic(type)(name##_sc_atomic__) = 0 /** * \brief wrapper for declaring an atomic variable and initializing it @@ -87,16 +83,13 @@ /** * \brief wrapper for initializing an atomic variable. **/ -#define SC_ATOMIC_INIT(name) \ - (name ## _sc_atomic__) = 0 -#define SC_ATOMIC_INITPTR(name) \ - (name ## _sc_atomic__) = NULL +#define SC_ATOMIC_INIT(name) (name##_sc_atomic__) = 0 +#define SC_ATOMIC_INITPTR(name) (name##_sc_atomic__) = NULL /** * \brief wrapper for reinitializing an atomic variable. **/ -#define SC_ATOMIC_RESET(name) \ - SC_ATOMIC_INIT(name) +#define SC_ATOMIC_RESET(name) SC_ATOMIC_INIT(name) /** * \brief add a value to our atomic variable @@ -104,8 +97,7 @@ * \param name the atomic variable * \param val the value to add to the variable */ -#define SC_ATOMIC_ADD(name, val) \ - atomic_fetch_add(&(name ## _sc_atomic__), (val)) +#define SC_ATOMIC_ADD(name, val) atomic_fetch_add(&(name##_sc_atomic__), (val)) /** * \brief sub a value from our atomic variable @@ -113,8 +105,7 @@ * \param name the atomic variable * \param val the value to sub from the variable */ -#define SC_ATOMIC_SUB(name, val) \ - atomic_fetch_sub(&(name ## _sc_atomic__), (val)) +#define SC_ATOMIC_SUB(name, val) atomic_fetch_sub(&(name##_sc_atomic__), (val)) /** * \brief Bitwise OR a value to our atomic variable @@ -122,8 +113,7 @@ * \param name the atomic variable * \param val the value to OR to the variable */ -#define SC_ATOMIC_OR(name, val) \ - atomic_fetch_or(&(name ## _sc_atomic__), (val)) +#define SC_ATOMIC_OR(name, val) atomic_fetch_or(&(name##_sc_atomic__), (val)) /** * \brief Bitwise AND a value to our atomic variable @@ -131,35 +121,31 @@ * \param name the atomic variable * \param val the value to AND to the variable */ -#define SC_ATOMIC_AND(name, val) \ - atomic_fetch_and(&(name ## _sc_atomic__), (val)) +#define SC_ATOMIC_AND(name, val) atomic_fetch_and(&(name##_sc_atomic__), (val)) /** * \brief atomic Compare and Switch * * \warning "name" is passed to us as "&var" */ -#define SC_ATOMIC_CAS(name, cmpval, newval) \ - atomic_compare_exchange_strong((name ## _sc_atomic__), &(cmpval), (newval)) +#define SC_ATOMIC_CAS(name, cmpval, newval) \ + atomic_compare_exchange_strong((name##_sc_atomic__), &(cmpval), (newval)) /** * \brief Get the value from the atomic variable. * * \retval var value */ -#define SC_ATOMIC_GET(name) \ - atomic_load(&(name ## _sc_atomic__)) +#define SC_ATOMIC_GET(name) atomic_load(&(name##_sc_atomic__)) -#define SC_ATOMIC_LOAD_EXPLICIT(name, order) \ - atomic_load_explicit(&(name ## _sc_atomic__), (order)) +#define SC_ATOMIC_LOAD_EXPLICIT(name, order) atomic_load_explicit(&(name##_sc_atomic__), (order)) /** * \brief Set the value for the atomic variable. * * \retval var value */ -#define SC_ATOMIC_SET(name, val) \ - atomic_store(&(name ## _sc_atomic__), (val)) +#define SC_ATOMIC_SET(name, val) atomic_store(&(name##_sc_atomic__), (val)) #else @@ -181,8 +167,7 @@ * \retval 0 CAS failed * \retval 1 CAS succeeded */ -#define SCAtomicCompareAndSwap(addr, tv, nv) \ - __sync_bool_compare_and_swap((addr), (tv), (nv)) +#define SCAtomicCompareAndSwap(addr, tv, nv) __sync_bool_compare_and_swap((addr), (tv), (nv)) /** * \brief wrapper for OS/compiler specific atomic fetch and add @@ -191,8 +176,7 @@ * \param addr Address of the variable to add to * \param value Value to add to the variable at addr */ -#define SCAtomicFetchAndAdd(addr, value) \ - __sync_fetch_and_add((addr), (value)) +#define SCAtomicFetchAndAdd(addr, value) __sync_fetch_and_add((addr), (value)) /** * \brief wrapper for OS/compiler specific atomic fetch and sub @@ -201,8 +185,7 @@ * \param addr Address of the variable to add to * \param value Value to sub from the variable at addr */ -#define SCAtomicFetchAndSub(addr, value) \ - __sync_fetch_and_sub((addr), (value)) +#define SCAtomicFetchAndSub(addr, value) __sync_fetch_and_sub((addr), (value)) /** * \brief wrapper for OS/compiler specific atomic fetch and add @@ -211,8 +194,7 @@ * \param addr Address of the variable to add to * \param value Value to add to the variable at addr */ -#define SCAtomicAddAndFetch(addr, value) \ - __sync_add_and_fetch((addr), (value)) +#define SCAtomicAddAndFetch(addr, value) __sync_add_and_fetch((addr), (value)) /** * \brief wrapper for OS/compiler specific atomic fetch and sub @@ -221,8 +203,7 @@ * \param addr Address of the variable to add to * \param value Value to sub from the variable at addr */ -#define SCAtomicSubAndFetch(addr, value) \ - __sync_sub_and_fetch((addr), (value)) +#define SCAtomicSubAndFetch(addr, value) __sync_sub_and_fetch((addr), (value)) /** * \brief wrapper for OS/compiler specific atomic fetch and "AND" @@ -231,8 +212,7 @@ * \param addr Address of the variable to AND to * \param value Value to add to the variable at addr */ -#define SCAtomicFetchAndAnd(addr, value) \ - __sync_fetch_and_and((addr), (value)) +#define SCAtomicFetchAndAnd(addr, value) __sync_fetch_and_and((addr), (value)) /** * \brief wrapper for OS/compiler specific atomic fetch and "NAND" @@ -241,8 +221,7 @@ * \param addr Address of the variable to NAND to * \param value Value to add to the variable at addr */ -#define SCAtomicFetchAndNand(addr, value) \ - __sync_fetch_and_nand((addr), (value)) +#define SCAtomicFetchAndNand(addr, value) __sync_fetch_and_nand((addr), (value)) /** * \brief wrapper for OS/compiler specific atomic fetch and "XOR" @@ -251,8 +230,7 @@ * \param addr Address of the variable to XOR to * \param value Value to add to the variable at addr */ -#define SCAtomicFetchAndXor(addr, value) \ - __sync_fetch_and_xor((addr), (value)) +#define SCAtomicFetchAndXor(addr, value) __sync_fetch_and_xor((addr), (value)) /** * \brief wrapper for OS/compiler specific atomic fetch and or @@ -261,8 +239,7 @@ * \param addr Address of the variable to or to * \param value Value to add to the variable at addr */ -#define SCAtomicFetchAndOr(addr, value) \ - __sync_fetch_and_or((addr), (value)) +#define SCAtomicFetchAndOr(addr, value) __sync_fetch_and_or((addr), (value)) /** * \brief wrapper for declaring atomic variables. @@ -278,8 +255,7 @@ * * \warning variable is not initialized */ -#define SC_ATOMIC_DECLARE(type, name) \ - type name ## _sc_atomic__ +#define SC_ATOMIC_DECLARE(type, name) type name##_sc_atomic__ /** * \brief wrapper for referencing an atomic variable declared on another file. @@ -294,8 +270,7 @@ * to modify it, so no need for locks. * */ -#define SC_ATOMIC_EXTERN(type, name) \ - extern type name ## _sc_atomic__ +#define SC_ATOMIC_EXTERN(type, name) extern type name##_sc_atomic__ /** * \brief wrapper for declaring an atomic variable and initializing it @@ -306,23 +281,19 @@ /** * \brief wrapper for declaring an atomic variable and initializing it. **/ -#define SC_ATOMIC_DECL_AND_INIT(type, name) \ - type name ## _sc_atomic__ = 0 +#define SC_ATOMIC_DECL_AND_INIT(type, name) type name##_sc_atomic__ = 0 /** * \brief wrapper for initializing an atomic variable. **/ -#define SC_ATOMIC_INIT(name) \ - (name ## _sc_atomic__) = 0 +#define SC_ATOMIC_INIT(name) (name##_sc_atomic__) = 0 -#define SC_ATOMIC_INITPTR(name) \ - (name ## _sc_atomic__) = NULL +#define SC_ATOMIC_INITPTR(name) (name##_sc_atomic__) = NULL /** * \brief wrapper for reinitializing an atomic variable. **/ -#define SC_ATOMIC_RESET(name) \ - (name ## _sc_atomic__) = 0 +#define SC_ATOMIC_RESET(name) (name##_sc_atomic__) = 0 /** * \brief add a value to our atomic variable @@ -330,8 +301,7 @@ * \param name the atomic variable * \param val the value to add to the variable */ -#define SC_ATOMIC_ADD(name, val) \ - SCAtomicFetchAndAdd(&(name ## _sc_atomic__), (val)) +#define SC_ATOMIC_ADD(name, val) SCAtomicFetchAndAdd(&(name##_sc_atomic__), (val)) /** * \brief sub a value from our atomic variable @@ -339,8 +309,7 @@ * \param name the atomic variable * \param val the value to sub from the variable */ -#define SC_ATOMIC_SUB(name, val) \ - SCAtomicFetchAndSub(&(name ## _sc_atomic__), (val)) +#define SC_ATOMIC_SUB(name, val) SCAtomicFetchAndSub(&(name##_sc_atomic__), (val)) /** * \brief Bitwise OR a value to our atomic variable @@ -348,8 +317,7 @@ * \param name the atomic variable * \param val the value to OR to the variable */ -#define SC_ATOMIC_OR(name, val) \ - SCAtomicFetchAndOr(&(name ## _sc_atomic__), (val)) +#define SC_ATOMIC_OR(name, val) SCAtomicFetchAndOr(&(name##_sc_atomic__), (val)) /** * \brief Bitwise AND a value to our atomic variable @@ -357,41 +325,38 @@ * \param name the atomic variable * \param val the value to AND to the variable */ -#define SC_ATOMIC_AND(name, val) \ - SCAtomicFetchAndAnd(&(name ## _sc_atomic__), (val)) +#define SC_ATOMIC_AND(name, val) SCAtomicFetchAndAnd(&(name##_sc_atomic__), (val)) /** * \brief atomic Compare and Switch * * \warning "name" is passed to us as "&var" */ -#define SC_ATOMIC_CAS(name, cmpval, newval) \ - SCAtomicCompareAndSwap((name ## _sc_atomic__), cmpval, newval) +#define SC_ATOMIC_CAS(name, cmpval, newval) \ + SCAtomicCompareAndSwap((name##_sc_atomic__), cmpval, newval) /** * \brief Get the value from the atomic variable. * * \retval var value */ -#define SC_ATOMIC_GET(name) \ - (name ## _sc_atomic__) +#define SC_ATOMIC_GET(name) (name##_sc_atomic__) -#define SC_ATOMIC_LOAD_EXPLICIT(name, order) \ - (name ## _sc_atomic__) +#define SC_ATOMIC_LOAD_EXPLICIT(name, order) (name##_sc_atomic__) /** * \brief Set the value for the atomic variable. * * \retval var value */ -#define SC_ATOMIC_SET(name, val) ({ \ - while (SC_ATOMIC_CAS(&name, SC_ATOMIC_GET(name), val) == 0) \ - ; \ - }) +#define SC_ATOMIC_SET(name, val) \ + ({ \ + while (SC_ATOMIC_CAS(&name, SC_ATOMIC_GET(name), val) == 0) \ + ; \ + }) #endif /* no c11 atomics */ void SCAtomicRegisterTests(void); #endif /* __UTIL_ATOMIC_H__ */ - diff --git a/src/util-base64.c b/src/util-base64.c index 4a4a5d122c41..a7cba279600d 100644 --- a/src/util-base64.c +++ b/src/util-base64.c @@ -26,23 +26,16 @@ #include "util-debug.h" #include "util-unittest.h" /* Constants */ -#define BASE64_TABLE_MAX 122 +#define BASE64_TABLE_MAX 122 /* Base64 character to index conversion table */ /* Characters are mapped as "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" */ -static const int b64table[] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, - 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, - -1, -1, -1, -1, -1, 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, -1, -1, -1, -1, -1, -1, 26, 27, 28, - 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, - 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, - 49, 50, 51 }; +static const int b64table[] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, + 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, + -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, + 44, 45, 46, 47, 48, 49, 50, 51 }; /** * \brief Gets a base64-decoded value from an encoded character @@ -57,7 +50,7 @@ static inline int GetBase64Value(uint8_t c) /* Pull from conversion table */ if (c <= BASE64_TABLE_MAX) { - val = b64table[(int) c]; + val = b64table[(int)c]; } return val; @@ -88,9 +81,9 @@ bool IsBase64Alphabet(uint8_t encoded_byte) */ static inline void DecodeBase64Block(uint8_t ascii[ASCII_BLOCK], uint8_t b64[B64_BLOCK]) { - ascii[0] = (uint8_t) (b64[0] << 2) | (b64[1] >> 4); - ascii[1] = (uint8_t) (b64[1] << 4) | (b64[2] >> 2); - ascii[2] = (uint8_t) (b64[2] << 6) | (b64[3]); + ascii[0] = (uint8_t)(b64[0] << 2) | (b64[1] >> 4); + ascii[1] = (uint8_t)(b64[1] << 4) | (b64[2] >> 2); + ascii[2] = (uint8_t)(b64[2] << 6) | (b64[3]); } /** @@ -112,7 +105,7 @@ Base64Ecode DecodeBase64(uint8_t *dest, uint32_t dest_size, const uint8_t *src, int val; uint32_t padding = 0, bbidx = 0, sp = 0, leading_sp = 0; uint8_t *dptr = dest; - uint8_t b64[B64_BLOCK] = { 0,0,0,0 }; + uint8_t b64[B64_BLOCK] = { 0, 0, 0, 0 }; bool valid = true; Base64Ecode ecode = BASE64_ECODE_OK; *decoded_bytes = 0; diff --git a/src/util-base64.h b/src/util-base64.h index 53cc14c9c4e0..5d05a1a62561 100644 --- a/src/util-base64.h +++ b/src/util-base64.h @@ -28,8 +28,8 @@ #include "suricata-common.h" /* Constants */ -#define ASCII_BLOCK 3 -#define B64_BLOCK 4 +#define ASCII_BLOCK 3 +#define B64_BLOCK 4 typedef enum { BASE64_MODE_RELAX, diff --git a/src/util-bloomfilter-counting.c b/src/util-bloomfilter-counting.c index 620b507dfa99..f0674062f6c8 100644 --- a/src/util-bloomfilter-counting.c +++ b/src/util-bloomfilter-counting.c @@ -31,19 +31,21 @@ /* type: 1, 2 or 4 for 8, 16, or 32 bit counters * */ -BloomFilterCounting *BloomFilterCountingInit(uint32_t size, uint8_t type, uint8_t iter, uint32_t (*Hash)(const void *, uint16_t, uint8_t, uint32_t)) { +BloomFilterCounting *BloomFilterCountingInit(uint32_t size, uint8_t type, uint8_t iter, + uint32_t (*Hash)(const void *, uint16_t, uint8_t, uint32_t)) +{ BloomFilterCounting *bf = NULL; if (iter == 0) goto error; if (Hash == NULL || size == 0) { - //printf("ERROR: BloomFilterCountingInit no Hash function\n"); + // printf("ERROR: BloomFilterCountingInit no Hash function\n"); goto error; } if (type != 1 && type != 2 && type != 4) { - //printf("ERROR: BloomFilterCountingInit only 1, 2 and 4 bytes are supported\n"); + // printf("ERROR: BloomFilterCountingInit only 1, 2 and 4 bytes are supported\n"); goto error; } @@ -218,22 +220,25 @@ int BloomFilterCountingTest(BloomFilterCounting *bf, const void *data, uint16_t #ifdef UNITTESTS static uint32_t BloomHash(const void *data, uint16_t datalen, uint8_t iter, uint32_t hash_size) { - uint8_t *d = (uint8_t *)data; - uint32_t i; - uint32_t hash = 0; - - for (i = 0; i < datalen; i++) { - if (i == 0) hash += (((uint32_t)*d++)); - else if (i == 1) hash += (((uint32_t)*d++) * datalen); - else hash *= (((uint32_t)*d++) * i); - } - - hash *= (iter + datalen); - hash %= hash_size; - return hash; + uint8_t *d = (uint8_t *)data; + uint32_t i; + uint32_t hash = 0; + + for (i = 0; i < datalen; i++) { + if (i == 0) + hash += (((uint32_t)*d++)); + else if (i == 1) + hash += (((uint32_t)*d++) * datalen); + else + hash *= (((uint32_t)*d++) * i); + } + + hash *= (iter + datalen); + hash %= hash_size; + return hash; } -static int BloomFilterCountingTestInit01 (void) +static int BloomFilterCountingTestInit01(void) { BloomFilterCounting *bf = BloomFilterCountingInit(1024, 4, 4, BloomHash); if (bf == NULL) @@ -244,7 +249,7 @@ static int BloomFilterCountingTestInit01 (void) } /* no hash function, so it should fail */ -static int BloomFilterCountingTestInit02 (void) +static int BloomFilterCountingTestInit02(void) { BloomFilterCounting *bf = BloomFilterCountingInit(1024, 4, 4, NULL); if (bf == NULL) @@ -254,7 +259,7 @@ static int BloomFilterCountingTestInit02 (void) return 0; } -static int BloomFilterCountingTestInit03 (void) +static int BloomFilterCountingTestInit03(void) { int result = 0; BloomFilterCounting *bf = BloomFilterCountingInit(1024, 4, 4, BloomHash); @@ -268,7 +273,7 @@ static int BloomFilterCountingTestInit03 (void) return result; } -static int BloomFilterCountingTestInit04 (void) +static int BloomFilterCountingTestInit04(void) { BloomFilterCounting *bf = BloomFilterCountingInit(1024, 0, 4, BloomHash); if (bf == NULL) @@ -278,7 +283,7 @@ static int BloomFilterCountingTestInit04 (void) return 0; } -static int BloomFilterCountingTestInit05 (void) +static int BloomFilterCountingTestInit05(void) { BloomFilterCounting *bf = BloomFilterCountingInit(0, 4, 4, BloomHash); if (bf == NULL) @@ -288,7 +293,7 @@ static int BloomFilterCountingTestInit05 (void) return 0; } -static int BloomFilterCountingTestInit06 (void) +static int BloomFilterCountingTestInit06(void) { BloomFilterCounting *bf = BloomFilterCountingInit(32, 3, 4, BloomHash); if (bf == NULL) @@ -298,7 +303,7 @@ static int BloomFilterCountingTestInit06 (void) return 0; } -static int BloomFilterCountingTestAdd01 (void) +static int BloomFilterCountingTestAdd01(void) { int result = 0; BloomFilterCounting *bf = BloomFilterCountingInit(1024, 4, 4, BloomHash); @@ -312,11 +317,12 @@ static int BloomFilterCountingTestAdd01 (void) /* all is good! */ result = 1; end: - if (bf != NULL) BloomFilterCountingFree(bf); + if (bf != NULL) + BloomFilterCountingFree(bf); return result; } -static int BloomFilterCountingTestAdd02 (void) +static int BloomFilterCountingTestAdd02(void) { int result = 0; BloomFilterCounting *bf = BloomFilterCountingInit(1024, 4, 4, BloomHash); @@ -330,11 +336,12 @@ static int BloomFilterCountingTestAdd02 (void) /* all is good! */ result = 1; end: - if (bf != NULL) BloomFilterCountingFree(bf); + if (bf != NULL) + BloomFilterCountingFree(bf); return result; } -static int BloomFilterCountingTestFull01 (void) +static int BloomFilterCountingTestFull01(void) { int result = 0; BloomFilterCounting *bf = BloomFilterCountingInit(32, 4, 4, BloomHash); @@ -369,7 +376,7 @@ static int BloomFilterCountingTestFull01 (void) return result; } -static int BloomFilterCountingTestFull02 (void) +static int BloomFilterCountingTestFull02(void) { int result = 0; BloomFilterCounting *bf = BloomFilterCountingInit(32, 4, 4, BloomHash); @@ -383,7 +390,8 @@ static int BloomFilterCountingTestFull02 (void) /* all is good! */ result = 1; end: - if (bf != NULL) BloomFilterCountingFree(bf); + if (bf != NULL) + BloomFilterCountingFree(bf); return result; } #endif @@ -391,28 +399,17 @@ static int BloomFilterCountingTestFull02 (void) void BloomFilterCountingRegisterTests(void) { #ifdef UNITTESTS - UtRegisterTest("BloomFilterCountingTestInit01", - BloomFilterCountingTestInit01); - UtRegisterTest("BloomFilterCountingTestInit02", - BloomFilterCountingTestInit02); - UtRegisterTest("BloomFilterCountingTestInit03", - BloomFilterCountingTestInit03); - UtRegisterTest("BloomFilterCountingTestInit04", - BloomFilterCountingTestInit04); - UtRegisterTest("BloomFilterCountingTestInit05", - BloomFilterCountingTestInit05); - UtRegisterTest("BloomFilterCountingTestInit06", - BloomFilterCountingTestInit06); - - UtRegisterTest("BloomFilterCountingTestAdd01", - BloomFilterCountingTestAdd01); - UtRegisterTest("BloomFilterCountingTestAdd02", - BloomFilterCountingTestAdd02); - - UtRegisterTest("BloomFilterCountingTestFull01", - BloomFilterCountingTestFull01); - UtRegisterTest("BloomFilterCountingTestFull02", - BloomFilterCountingTestFull02); + UtRegisterTest("BloomFilterCountingTestInit01", BloomFilterCountingTestInit01); + UtRegisterTest("BloomFilterCountingTestInit02", BloomFilterCountingTestInit02); + UtRegisterTest("BloomFilterCountingTestInit03", BloomFilterCountingTestInit03); + UtRegisterTest("BloomFilterCountingTestInit04", BloomFilterCountingTestInit04); + UtRegisterTest("BloomFilterCountingTestInit05", BloomFilterCountingTestInit05); + UtRegisterTest("BloomFilterCountingTestInit06", BloomFilterCountingTestInit06); + + UtRegisterTest("BloomFilterCountingTestAdd01", BloomFilterCountingTestAdd01); + UtRegisterTest("BloomFilterCountingTestAdd02", BloomFilterCountingTestAdd02); + + UtRegisterTest("BloomFilterCountingTestFull01", BloomFilterCountingTestFull01); + UtRegisterTest("BloomFilterCountingTestFull02", BloomFilterCountingTestFull02); #endif } - diff --git a/src/util-bloomfilter-counting.h b/src/util-bloomfilter-counting.h index bdb0cfa09c95..a3ca769bfb50 100644 --- a/src/util-bloomfilter-counting.h +++ b/src/util-bloomfilter-counting.h @@ -28,13 +28,14 @@ typedef struct BloomFilterCounting_ { uint8_t *array; uint32_t array_size; /* size in buckets */ - uint8_t type; /* 1, 2 or 4 byte counters */ + uint8_t type; /* 1, 2 or 4 byte counters */ uint8_t hash_iterations; uint32_t (*Hash)(const void *, uint16_t, uint8_t, uint32_t); } BloomFilterCounting; /* prototypes */ -BloomFilterCounting *BloomFilterCountingInit(uint32_t, uint8_t, uint8_t, uint32_t (*Hash)(const void *, uint16_t, uint8_t, uint32_t)); +BloomFilterCounting *BloomFilterCountingInit( + uint32_t, uint8_t, uint8_t, uint32_t (*Hash)(const void *, uint16_t, uint8_t, uint32_t)); void BloomFilterCountingFree(BloomFilterCounting *); void BloomFilterCountingPrint(BloomFilterCounting *); int BloomFilterCountingAdd(BloomFilterCounting *, const void *, uint16_t); @@ -44,4 +45,3 @@ int BloomFilterCountingTest(BloomFilterCounting *, const void *, uint16_t); void BloomFilterCountingRegisterTests(void); #endif /* __BLOOMFILTERCOUNTING_H__ */ - diff --git a/src/util-bloomfilter.c b/src/util-bloomfilter.c index 5d2549c6a9a4..35e6bab81f8d 100644 --- a/src/util-bloomfilter.c +++ b/src/util-bloomfilter.c @@ -27,15 +27,16 @@ #include "util-bloomfilter.h" #include "util-unittest.h" -BloomFilter *BloomFilterInit(uint32_t size, uint8_t iter, - uint32_t (*Hash)(const void *, uint16_t, uint8_t, uint32_t)) { +BloomFilter *BloomFilterInit( + uint32_t size, uint8_t iter, uint32_t (*Hash)(const void *, uint16_t, uint8_t, uint32_t)) +{ BloomFilter *bf = NULL; if (size == 0 || iter == 0) goto error; if (Hash == NULL) { - //printf("ERROR: BloomFilterInit no Hash function\n"); + // printf("ERROR: BloomFilterInit no Hash function\n"); goto error; } @@ -78,7 +79,7 @@ void BloomFilterPrint(BloomFilter *bf) { printf("\n---------- Bloom Filter Stats -----------\n"); printf("Buckets: %" PRIu32 "\n", bf->bitarray_size); - printf("Memory size: %" PRIu32 " bytes\n", bf->bitarray_size/8 + 1); + printf("Memory size: %" PRIu32 " bytes\n", bf->bitarray_size / 8 + 1); printf("Hash function pointer: %p\n", bf->Hash); printf("Hash functions: %" PRIu32 "\n", bf->hash_iterations); printf("-----------------------------------------\n"); @@ -94,7 +95,7 @@ int BloomFilterAdd(BloomFilter *bf, const void *data, uint16_t datalen) for (iter = 0; iter < bf->hash_iterations; iter++) { hash = bf->Hash(data, datalen, iter, bf->bitarray_size); - bf->bitarray[hash/8] |= (1<bitarray[hash / 8] |= (1 << hash % 8); } return 0; @@ -102,18 +103,18 @@ int BloomFilterAdd(BloomFilter *bf, const void *data, uint16_t datalen) uint32_t BloomFilterMemoryCnt(BloomFilter *bf) { - if (bf == NULL) - return 0; + if (bf == NULL) + return 0; - return 2; + return 2; } uint32_t BloomFilterMemorySize(BloomFilter *bf) { - if (bf == NULL) - return 0; + if (bf == NULL) + return 0; - return (sizeof(BloomFilter) + (bf->bitarray_size/8) + 1); + return (sizeof(BloomFilter) + (bf->bitarray_size / 8) + 1); } /* @@ -121,24 +122,28 @@ uint32_t BloomFilterMemorySize(BloomFilter *bf) */ #ifdef UNITTESTS -static uint32_t BloomFilterTestHash(const void *data, uint16_t datalen, uint8_t iter, uint32_t hash_size) +static uint32_t BloomFilterTestHash( + const void *data, uint16_t datalen, uint8_t iter, uint32_t hash_size) { - uint8_t *d = (uint8_t *)data; - uint32_t i; - uint32_t hash = 0; - - for (i = 0; i < datalen; i++) { - if (i == 0) hash += (((uint32_t)*d++)); - else if (i == 1) hash += (((uint32_t)*d++) * datalen); - else hash *= (((uint32_t)*d++) * i); - } - - hash *= (iter + datalen); - hash %= hash_size; - return hash; + uint8_t *d = (uint8_t *)data; + uint32_t i; + uint32_t hash = 0; + + for (i = 0; i < datalen; i++) { + if (i == 0) + hash += (((uint32_t)*d++)); + else if (i == 1) + hash += (((uint32_t)*d++) * datalen); + else + hash *= (((uint32_t)*d++) * i); + } + + hash *= (iter + datalen); + hash %= hash_size; + return hash; } -static int BloomFilterTestInit01 (void) +static int BloomFilterTestInit01(void) { BloomFilter *bf = BloomFilterInit(1024, 4, BloomFilterTestHash); if (bf == NULL) @@ -149,7 +154,7 @@ static int BloomFilterTestInit01 (void) } /* no hash function, so it should fail */ -static int BloomFilterTestInit02 (void) +static int BloomFilterTestInit02(void) { BloomFilter *bf = BloomFilterInit(1024, 4, NULL); if (bf == NULL) @@ -159,7 +164,7 @@ static int BloomFilterTestInit02 (void) return 0; } -static int BloomFilterTestInit03 (void) +static int BloomFilterTestInit03(void) { int result = 0; BloomFilter *bf = BloomFilterInit(1024, 4, BloomFilterTestHash); @@ -173,7 +178,7 @@ static int BloomFilterTestInit03 (void) return result; } -static int BloomFilterTestInit04 (void) +static int BloomFilterTestInit04(void) { BloomFilter *bf = BloomFilterInit(1024, 0, BloomFilterTestHash); if (bf == NULL) @@ -183,7 +188,7 @@ static int BloomFilterTestInit04 (void) return 0; } -static int BloomFilterTestInit05 (void) +static int BloomFilterTestInit05(void) { BloomFilter *bf = BloomFilterInit(0, 4, BloomFilterTestHash); if (bf == NULL) @@ -193,7 +198,7 @@ static int BloomFilterTestInit05 (void) return 0; } -static int BloomFilterTestAdd01 (void) +static int BloomFilterTestAdd01(void) { int result = 0; BloomFilter *bf = BloomFilterInit(1024, 4, BloomFilterTestHash); @@ -207,11 +212,12 @@ static int BloomFilterTestAdd01 (void) /* all is good! */ result = 1; end: - if (bf != NULL) BloomFilterFree(bf); + if (bf != NULL) + BloomFilterFree(bf); return result; } -static int BloomFilterTestAdd02 (void) +static int BloomFilterTestAdd02(void) { int result = 0; BloomFilter *bf = BloomFilterInit(1024, 4, BloomFilterTestHash); @@ -225,11 +231,12 @@ static int BloomFilterTestAdd02 (void) /* all is good! */ result = 1; end: - if (bf != NULL) BloomFilterFree(bf); + if (bf != NULL) + BloomFilterFree(bf); return result; } -static int BloomFilterTestFull01 (void) +static int BloomFilterTestFull01(void) { int result = 0; BloomFilter *bf = BloomFilterInit(32, 4, BloomFilterTestHash); @@ -247,11 +254,12 @@ static int BloomFilterTestFull01 (void) /* all is good! */ result = 1; end: - if (bf != NULL) BloomFilterFree(bf); + if (bf != NULL) + BloomFilterFree(bf); return result; } -static int BloomFilterTestFull02 (void) +static int BloomFilterTestFull02(void) { int result = 0; BloomFilter *bf = BloomFilterInit(32, 4, BloomFilterTestHash); @@ -265,7 +273,8 @@ static int BloomFilterTestFull02 (void) /* all is good! */ result = 1; end: - if (bf != NULL) BloomFilterFree(bf); + if (bf != NULL) + BloomFilterFree(bf); return result; } #endif /* UNITTESTS */ @@ -286,4 +295,3 @@ void BloomFilterRegisterTests(void) UtRegisterTest("BloomFilterTestFull02", BloomFilterTestFull02); #endif /* UNITTESTS */ } - diff --git a/src/util-bloomfilter.h b/src/util-bloomfilter.h index b6dee868a588..013982b0f232 100644 --- a/src/util-bloomfilter.h +++ b/src/util-bloomfilter.h @@ -33,7 +33,8 @@ typedef struct BloomFilter_ { } BloomFilter; /* prototypes */ -BloomFilter *BloomFilterInit(uint32_t, uint8_t, uint32_t (*Hash)(const void *, uint16_t, uint8_t, uint32_t)); +BloomFilter *BloomFilterInit( + uint32_t, uint8_t, uint32_t (*Hash)(const void *, uint16_t, uint8_t, uint32_t)); void BloomFilterFree(BloomFilter *); void BloomFilterPrint(BloomFilter *); int BloomFilterAdd(BloomFilter *, const void *, uint16_t); @@ -54,7 +55,7 @@ static inline int BloomFilterTest(const BloomFilter *bf, const void *data, uint1 for (iter = 0; iter < bf->hash_iterations; iter++) { hash = bf->Hash(data, datalen, iter, bf->bitarray_size); - if (!(bf->bitarray[hash/8] & (1<bitarray[hash / 8] & (1 << hash % 8))) { hit = 0; break; } @@ -64,4 +65,3 @@ static inline int BloomFilterTest(const BloomFilter *bf, const void *data, uint1 } #endif /* __BLOOMFILTER_H__ */ - diff --git a/src/util-bpf.c b/src/util-bpf.c index dda910d2c8b4..c4a04303f903 100644 --- a/src/util-bpf.c +++ b/src/util-bpf.c @@ -59,10 +59,8 @@ void SCBPFFree(struct bpf_program *program) pcap_freecode(program); } -int SCBPFCompile(int snaplen_arg, int linktype_arg, struct bpf_program *program, - const char *buf, - int optimize, uint32_t mask, - char *errbuf, size_t errbuf_len) +int SCBPFCompile(int snaplen_arg, int linktype_arg, struct bpf_program *program, const char *buf, + int optimize, uint32_t mask, char *errbuf, size_t errbuf_len) { pcap_t *p; int ret; diff --git a/src/util-bpf.h b/src/util-bpf.h index 8196077f8a07..866e25738df0 100644 --- a/src/util-bpf.h +++ b/src/util-bpf.h @@ -29,9 +29,8 @@ void ConfSetBPFFilter( ConfNode *if_root, ConfNode *if_default, const char *iface, const char **bpf_filter); -int SCBPFCompile(int snaplen_arg, int linktype_arg, struct bpf_program *program, - const char *buf, int optimize, uint32_t mask, - char *errbuf, size_t errbuf_len); +int SCBPFCompile(int snaplen_arg, int linktype_arg, struct bpf_program *program, const char *buf, + int optimize, uint32_t mask, char *errbuf, size_t errbuf_len); void SCBPFFree(struct bpf_program *program); diff --git a/src/util-buffer.c b/src/util-buffer.c index be7aee4046c8..fdcb9701bdb4 100644 --- a/src/util-buffer.c +++ b/src/util-buffer.c @@ -60,7 +60,8 @@ MemBuffer *MemBufferCreateNew(uint32_t size) * * \retval result 0 ok, -1 expansion failed */ -int MemBufferExpand(MemBuffer **buffer, uint32_t expand_by) { +int MemBufferExpand(MemBuffer **buffer, uint32_t expand_by) +{ if (((*buffer)->size + expand_by) > MAX_LIMIT) { SCLogWarning("Mem buffer asked to create " "buffer with size greater than API limit - %d", diff --git a/src/util-buffer.h b/src/util-buffer.h index 3a88c8e96b82..889c209357ce 100644 --- a/src/util-buffer.h +++ b/src/util-buffer.h @@ -25,9 +25,9 @@ #define __UTIL_BUFFER_H__ typedef struct MemBuffer_ { - uint8_t *buffer; - uint32_t size; - uint32_t offset; + uint8_t *buffer; + uint32_t size; + uint32_t offset; } MemBuffer; MemBuffer *MemBufferCreateNew(uint32_t size); @@ -39,9 +39,10 @@ void MemBufferFree(MemBuffer *buffer); * * \param mem_buffer Pointer to the mem buffer instance. */ -#define MemBufferReset(mem_buffer) do { \ - (mem_buffer)->buffer[0] = 0; \ - (mem_buffer)->offset = 0; \ +#define MemBufferReset(mem_buffer) \ + do { \ + (mem_buffer)->buffer[0] = 0; \ + (mem_buffer)->offset = 0; \ } while (0) /** @@ -73,15 +74,16 @@ void MemBufferFree(MemBuffer *buffer); * \param buffer Pointer to the src MemBuffer instance to write. * \param fp Pointer to the file instance to write to. */ -#define MemBufferPrintToFP(buffer, fp) do { \ - uint32_t i; \ - \ - for (i = 0; i < (buffer)->offset; i++) { \ - if (isprint(buffer->buffer[i])) \ - fprintf(fp, "%c", (buffer)->buffer[i]); \ - else \ - fprintf(fp, "|%02X|", (buffer)->buffer[i]); \ - } \ +#define MemBufferPrintToFP(buffer, fp) \ + do { \ + uint32_t i; \ + \ + for (i = 0; i < (buffer)->offset; i++) { \ + if (isprint(buffer->buffer[i])) \ + fprintf(fp, "%c", (buffer)->buffer[i]); \ + else \ + fprintf(fp, "|%02X|", (buffer)->buffer[i]); \ + } \ } while (0) /** @@ -90,9 +92,8 @@ void MemBufferFree(MemBuffer *buffer); * \param buffer Pointer to the src MemBuffer instance to write. * \param fp Pointer to the file instance to write to. */ -#define MemBufferPrintToFPAsString(mem_buffer, fp) ({ \ - fwrite((mem_buffer)->buffer, sizeof(uint8_t), (mem_buffer)->offset, fp); \ -}) +#define MemBufferPrintToFPAsString(mem_buffer, fp) \ + ({ fwrite((mem_buffer)->buffer, sizeof(uint8_t), (mem_buffer)->offset, fp); }) /** * \brief Write a buffer in hex format. @@ -100,17 +101,17 @@ void MemBufferFree(MemBuffer *buffer); * \param buffer Pointer to the src MemBuffer instance to write. * \param fp Pointer to the file instance to write to. */ -#define MemBufferPrintToFPAsHex(mem_buffer, fp) do { \ - uint32_t i; \ - \ - for (i = 0; i < (mem_buffer)->offset; i++) { \ - if (((mem_buffer)->offset % 8) == 0) \ - fprintf(fp, "\n"); \ - fprintf(fp, " %02X", (mem_buffer)->buffer[i]); \ - } \ +#define MemBufferPrintToFPAsHex(mem_buffer, fp) \ + do { \ + uint32_t i; \ + \ + for (i = 0; i < (mem_buffer)->offset; i++) { \ + if (((mem_buffer)->offset % 8) == 0) \ + fprintf(fp, "\n"); \ + fprintf(fp, " %02X", (mem_buffer)->buffer[i]); \ + } \ } while (0) - /** * \brief Write a raw buffer to the MemBuffer dst. * @@ -130,20 +131,22 @@ void MemBufferFree(MemBuffer *buffer); * \param raw_buffer The buffer to write. * \param raw_buffer_len Length of the above buffer. */ -#define MemBufferWriteRaw(dst, raw_buffer, raw_buffer_len) do { \ - uint32_t write_len; \ - \ - if (((raw_buffer_len) >= (dst)->size - (dst)->offset)) { \ - SCLogDebug("Truncating data write since it exceeded buffer limit of " \ - "- %"PRIu32, (dst)->size); \ - write_len = ((dst)->size - (dst)->offset) - 1; \ - } else { \ - write_len = (raw_buffer_len); \ - } \ - \ - memcpy((dst)->buffer + (dst)->offset, (raw_buffer), write_len); \ - (dst)->offset += write_len; \ - dst->buffer[dst->offset] = '\0'; \ +#define MemBufferWriteRaw(dst, raw_buffer, raw_buffer_len) \ + do { \ + uint32_t write_len; \ + \ + if (((raw_buffer_len) >= (dst)->size - (dst)->offset)) { \ + SCLogDebug("Truncating data write since it exceeded buffer limit of " \ + "- %" PRIu32, \ + (dst)->size); \ + write_len = ((dst)->size - (dst)->offset) - 1; \ + } else { \ + write_len = (raw_buffer_len); \ + } \ + \ + memcpy((dst)->buffer + (dst)->offset, (raw_buffer), write_len); \ + (dst)->offset += write_len; \ + dst->buffer[dst->offset] = '\0'; \ } while (0) /** @@ -159,19 +162,20 @@ void MemBufferFree(MemBuffer *buffer); * \param format The format string. * \param ... Variable arguments. */ -#define MemBufferWriteString(dst, ...) do { \ - int cw = snprintf((char *)(dst)->buffer + (dst)->offset, \ - (dst)->size - (dst)->offset, \ - __VA_ARGS__); \ - if (cw >= 0) { \ - if ( ((dst)->offset + cw) >= (dst)->size) { \ - SCLogDebug("Truncating data write since it exceeded buffer " \ - "limit of - %"PRIu32"\n", (dst)->size); \ - (dst)->offset = (dst)->size - 1; \ - } else { \ - (dst->offset) += cw; \ - } \ - } \ +#define MemBufferWriteString(dst, ...) \ + do { \ + int cw = snprintf( \ + (char *)(dst)->buffer + (dst)->offset, (dst)->size - (dst)->offset, __VA_ARGS__); \ + if (cw >= 0) { \ + if (((dst)->offset + cw) >= (dst)->size) { \ + SCLogDebug("Truncating data write since it exceeded buffer " \ + "limit of - %" PRIu32 "\n", \ + (dst)->size); \ + (dst)->offset = (dst)->size - 1; \ + } else { \ + (dst->offset) += cw; \ + } \ + } \ } while (0) #endif /* __UTIL_BUFFER_H__ */ diff --git a/src/util-byte.c b/src/util-byte.c index d2f39fb2d211..7c6e643d0c5d 100644 --- a/src/util-byte.c +++ b/src/util-byte.c @@ -222,8 +222,7 @@ int ByteExtractString(uint64_t *res, int base, size_t len, const char *str, bool } else if (endptr == ptr) { SCLogDebug("invalid numeric value"); return -1; - } - else if (strict && *endptr != '\0') { + } else if (strict && *endptr != '\0') { SCLogError("Extra characters following numeric value"); return -1; } @@ -251,8 +250,8 @@ int ByteExtractStringUint32(uint32_t *res, int base, size_t len, const char *str *res = (uint32_t)i64; if ((uint64_t)(*res) != i64) { - SCLogDebug("Numeric value out of range (%" PRIu64 " > %" PRIuMAX ")", - i64, (uintmax_t)UINT_MAX); + SCLogDebug("Numeric value out of range (%" PRIu64 " > %" PRIuMAX ")", i64, + (uintmax_t)UINT_MAX); return -1; } @@ -274,8 +273,8 @@ int ByteExtractStringUint16(uint16_t *res, int base, size_t len, const char *str *res = (uint16_t)i64; if ((uint64_t)(*res) != i64) { - SCLogDebug("Numeric value out of range (%" PRIu64 " > %" PRIuMAX ")", - i64, (uintmax_t)USHRT_MAX); + SCLogDebug("Numeric value out of range (%" PRIu64 " > %" PRIuMAX ")", i64, + (uintmax_t)USHRT_MAX); return -1; } @@ -297,8 +296,8 @@ int ByteExtractStringUint8(uint8_t *res, int base, size_t len, const char *str) *res = (uint8_t)i64; if ((uint64_t)(*res) != i64) { - SCLogDebug("Numeric value out of range (%" PRIu64 " > %" PRIuMAX ")", - i64, (uintmax_t)UCHAR_MAX); + SCLogDebug("Numeric value out of range (%" PRIu64 " > %" PRIuMAX ")", i64, + (uintmax_t)UCHAR_MAX); return -1; } @@ -523,13 +522,12 @@ int ByteExtractStringSigned(int64_t *res, int base, size_t len, const char *str, } else if (endptr == str) { SCLogError("Invalid numeric value"); return -1; - } - else if (strict && len && *endptr != '\0') { + } else if (strict && len && *endptr != '\0') { SCLogError("Extra characters following numeric value"); return -1; } - //fprintf(stderr, "ByteExtractStringSigned: Extracted base %d: 0x%" PRIx64 "\n", base, *res); + // fprintf(stderr, "ByteExtractStringSigned: Extracted base %d: 0x%" PRIx64 "\n", base, *res); return (endptr - ptr); } @@ -806,7 +804,7 @@ int StringParseI8RangeCheck( /* UNITTESTS */ #ifdef UNITTESTS -static int ByteTest01 (void) +static int ByteTest01(void) { uint16_t val = 0x0102; uint16_t i16 = 0xbfbf; @@ -820,7 +818,7 @@ static int ByteTest01 (void) return 0; } -static int ByteTest02 (void) +static int ByteTest02(void) { uint16_t val = 0x0102; uint16_t i16 = 0xbfbf; @@ -834,7 +832,7 @@ static int ByteTest02 (void) return 0; } -static int ByteTest03 (void) +static int ByteTest03(void) { uint32_t val = 0x01020304; uint32_t i32 = 0xbfbfbfbf; @@ -848,7 +846,7 @@ static int ByteTest03 (void) return 0; } -static int ByteTest04 (void) +static int ByteTest04(void) { uint32_t val = 0x01020304; uint32_t i32 = 0xbfbfbfbf; @@ -862,7 +860,7 @@ static int ByteTest04 (void) return 0; } -static int ByteTest05 (void) +static int ByteTest05(void) { uint64_t val = 0x0102030405060708ULL; uint64_t i64 = 0xbfbfbfbfbfbfbfbfULL; @@ -876,7 +874,7 @@ static int ByteTest05 (void) return 0; } -static int ByteTest06 (void) +static int ByteTest06(void) { uint64_t val = 0x0102030405060708ULL; uint64_t i64 = 0xbfbfbfbfbfbfbfbfULL; @@ -890,7 +888,7 @@ static int ByteTest06 (void) return 0; } -static int ByteTest07 (void) +static int ByteTest07(void) { const char str[] = "1234567890"; uint64_t val = 1234567890; @@ -904,7 +902,7 @@ static int ByteTest07 (void) return 0; } -static int ByteTest08 (void) +static int ByteTest08(void) { const char str[] = "1234567890"; uint32_t val = 1234567890; @@ -918,7 +916,7 @@ static int ByteTest08 (void) return 0; } -static int ByteTest09 (void) +static int ByteTest09(void) { const char str[] = "12345"; uint16_t val = 12345; @@ -932,7 +930,7 @@ static int ByteTest09 (void) return 0; } -static int ByteTest10 (void) +static int ByteTest10(void) { const char str[] = "123"; uint8_t val = 123; @@ -946,7 +944,7 @@ static int ByteTest10 (void) return 0; } -static int ByteTest11 (void) +static int ByteTest11(void) { const char str[] = "-1234567890"; int64_t val = -1234567890; @@ -960,7 +958,7 @@ static int ByteTest11 (void) return 0; } -static int ByteTest12 (void) +static int ByteTest12(void) { const char str[] = "-1234567890"; int32_t val = -1234567890; @@ -974,7 +972,7 @@ static int ByteTest12 (void) return 0; } -static int ByteTest13 (void) +static int ByteTest13(void) { const char str[] = "-12345"; int16_t val = -12345; @@ -988,7 +986,7 @@ static int ByteTest13 (void) return 0; } -static int ByteTest14 (void) +static int ByteTest14(void) { const char str[] = "-123"; int8_t val = -123; @@ -1003,7 +1001,7 @@ static int ByteTest14 (void) } /** \test max u32 value */ -static int ByteTest15 (void) +static int ByteTest15(void) { const char str[] = "4294967295"; uint32_t val = 4294967295UL; @@ -1018,7 +1016,7 @@ static int ByteTest15 (void) } /** \test max u32 value + 1 */ -static int ByteTest16 (void) +static int ByteTest16(void) { const char str[] = "4294967296"; uint32_t u32 = 0; @@ -1051,4 +1049,3 @@ void ByteRegisterTests(void) UtRegisterTest("ByteTest16", ByteTest16); } #endif /* UNITTESTS */ - diff --git a/src/util-byte.h b/src/util-byte.h index ae3e1d2a6902..af00d35aabad 100644 --- a/src/util-byte.h +++ b/src/util-byte.h @@ -26,8 +26,8 @@ #include -#define BYTE_BIG_ENDIAN 0 -#define BYTE_LITTLE_ENDIAN 1 +#define BYTE_BIG_ENDIAN 0 +#define BYTE_LITTLE_ENDIAN 1 /** Wrappers for OS dependent byte swapping functions */ #ifdef OS_FREEBSD @@ -47,23 +47,15 @@ #define SCByteSwap64(x) OSSwapInt64(x) #elif defined(__WIN32) || defined(_WIN32) || defined(sun) /* Quick & dirty solution, nothing seems to exist for this in Win32 API */ -#define SCByteSwap16(x) \ - ((((x) & 0xff00) >> 8) \ - | (((x) & 0x00ff) << 8)) -#define SCByteSwap32(x) \ - ((((x) & 0xff000000) >> 24) \ - | (((x) & 0x00ff0000) >> 8) \ - | (((x) & 0x0000ff00) << 8) \ - | (((x) & 0x000000ff) << 24)) -#define SCByteSwap64(x) \ - ((((x) & 0xff00000000000000ull) >> 56) \ - | (((x) & 0x00ff000000000000ull) >> 40) \ - | (((x) & 0x0000ff0000000000ull) >> 24) \ - | (((x) & 0x000000ff00000000ull) >> 8) \ - | (((x) & 0x00000000ff000000ull) << 8) \ - | (((x) & 0x0000000000ff0000ull) << 24) \ - | (((x) & 0x000000000000ff00ull) << 40) \ - | (((x) & 0x00000000000000ffull) << 56)) +#define SCByteSwap16(x) ((((x)&0xff00) >> 8) | (((x)&0x00ff) << 8)) +#define SCByteSwap32(x) \ + ((((x)&0xff000000) >> 24) | (((x)&0x00ff0000) >> 8) | (((x)&0x0000ff00) << 8) | \ + (((x)&0x000000ff) << 24)) +#define SCByteSwap64(x) \ + ((((x)&0xff00000000000000ull) >> 56) | (((x)&0x00ff000000000000ull) >> 40) | \ + (((x)&0x0000ff0000000000ull) >> 24) | (((x)&0x000000ff00000000ull) >> 8) | \ + (((x)&0x00000000ff000000ull) << 8) | (((x)&0x0000000000ff0000ull) << 24) | \ + (((x)&0x000000000000ff00ull) << 40) | (((x)&0x00000000000000ffull) << 56)) #else #include #define SCByteSwap16(x) bswap_16(x) @@ -492,8 +484,7 @@ static inline int WARN_UNUSED ByteExtract(uint64_t *res, int e, uint16_t len, co uint64_t b; if (e == BYTE_LITTLE_ENDIAN) { b = bytes[i]; - } - else { + } else { b = bytes[len - i - 1]; } diff --git a/src/util-checksum.c b/src/util-checksum.c index 53a4c425b693..4410d400ef4b 100644 --- a/src/util-checksum.c +++ b/src/util-checksum.c @@ -32,27 +32,26 @@ int ReCalculateChecksum(Packet *p) if (PKT_IS_TCP(p)) { /* TCP */ p->tcph->th_sum = 0; - p->tcph->th_sum = TCPChecksum(p->ip4h->s_ip_addrs, - (uint16_t *)p->tcph, (p->payload_len + TCP_GET_HLEN(p)), 0); + p->tcph->th_sum = TCPChecksum(p->ip4h->s_ip_addrs, (uint16_t *)p->tcph, + (p->payload_len + TCP_GET_HLEN(p)), 0); } else if (PKT_IS_UDP(p)) { p->udph->uh_sum = 0; - p->udph->uh_sum = UDPV4Checksum(p->ip4h->s_ip_addrs, - (uint16_t *)p->udph, (p->payload_len + UDP_HEADER_LEN), 0); + p->udph->uh_sum = UDPV4Checksum( + p->ip4h->s_ip_addrs, (uint16_t *)p->udph, (p->payload_len + UDP_HEADER_LEN), 0); } /* IPV4 */ p->ip4h->ip_csum = 0; - p->ip4h->ip_csum = IPV4Checksum((uint16_t *)p->ip4h, - IPV4_GET_RAW_HLEN(p->ip4h), 0); + p->ip4h->ip_csum = IPV4Checksum((uint16_t *)p->ip4h, IPV4_GET_RAW_HLEN(p->ip4h), 0); } else if (PKT_IS_IPV6(p)) { /* just TCP for IPV6 */ if (PKT_IS_TCP(p)) { p->tcph->th_sum = 0; - p->tcph->th_sum = TCPV6Checksum(p->ip6h->s_ip6_addrs, - (uint16_t *)p->tcph, (p->payload_len + TCP_GET_HLEN(p)), 0); + p->tcph->th_sum = TCPV6Checksum(p->ip6h->s_ip6_addrs, (uint16_t *)p->tcph, + (p->payload_len + TCP_GET_HLEN(p)), 0); } else if (PKT_IS_UDP(p)) { p->udph->uh_sum = 0; - p->udph->uh_sum = UDPV6Checksum(p->ip6h->s_ip6_addrs, - (uint16_t *)p->udph, (p->payload_len + UDP_HEADER_LEN), 0); + p->udph->uh_sum = UDPV6Checksum(p->ip6h->s_ip6_addrs, (uint16_t *)p->udph, + (p->payload_len + UDP_HEADER_LEN), 0); } } @@ -66,26 +65,25 @@ int ReCalculateChecksum(Packet *p) * \retval 1 yes, offloading in place * \retval 0 no, no offloading used */ -int ChecksumAutoModeCheck(uint64_t thread_count, - uint64_t iface_count, uint64_t iface_fail) +int ChecksumAutoModeCheck(uint64_t thread_count, uint64_t iface_count, uint64_t iface_fail) { if (thread_count == CHECKSUM_SAMPLE_COUNT) { if (iface_fail != 0) { if ((iface_count / iface_fail) < CHECKSUM_INVALID_RATIO) { SCLogInfo("More than 1/%dth of packets have an invalid " - "checksum, assuming checksum offloading is used " - "(%"PRIu64"/%"PRIu64")", + "checksum, assuming checksum offloading is used " + "(%" PRIu64 "/%" PRIu64 ")", CHECKSUM_INVALID_RATIO, iface_fail, iface_count); return 1; } else { SCLogInfo("Less than 1/%dth of packets have an invalid " - "checksum, assuming checksum offloading is NOT used " - "(%"PRIu64"/%"PRIu64")", CHECKSUM_INVALID_RATIO, - iface_fail, iface_count); + "checksum, assuming checksum offloading is NOT used " + "(%" PRIu64 "/%" PRIu64 ")", + CHECKSUM_INVALID_RATIO, iface_fail, iface_count); } } else { SCLogInfo("No packets with invalid checksum, assuming " - "checksum offloading is NOT used"); + "checksum offloading is NOT used"); } } return 0; diff --git a/src/util-checksum.h b/src/util-checksum.h index c7b056bdd88c..33f14bdd6c7e 100644 --- a/src/util-checksum.h +++ b/src/util-checksum.h @@ -27,12 +27,11 @@ #include "decode.h" int ReCalculateChecksum(Packet *p); -int ChecksumAutoModeCheck(uint64_t thread_count, - uint64_t iface_count, uint64_t iface_fail); +int ChecksumAutoModeCheck(uint64_t thread_count, uint64_t iface_count, uint64_t iface_fail); /* constant linked with detection of interface with * invalid checksums */ -#define CHECKSUM_SAMPLE_COUNT 1000ULL +#define CHECKSUM_SAMPLE_COUNT 1000ULL #define CHECKSUM_INVALID_RATIO 10 #endif diff --git a/src/util-cidr.h b/src/util-cidr.h index 745f67823c61..caa0c7a2bd4f 100644 --- a/src/util-cidr.h +++ b/src/util-cidr.h @@ -31,4 +31,3 @@ void CIDRGetIPv6(int cidr, struct in6_addr *in6); void UtilCIDRTests(void); #endif /* __UTIL_NETMASK_H__ */ - diff --git a/src/util-classification-config.c b/src/util-classification-config.c index 5bcc0960c887..58f2588ab842 100644 --- a/src/util-classification-config.c +++ b/src/util-classification-config.c @@ -39,7 +39,9 @@ /* Regex to parse the classtype argument from a Signature. The first substring * holds the classtype name, the second substring holds the classtype the * classtype description, and the third argument holds the priority */ -#define DETECT_CLASSCONFIG_REGEX "^\\s*config\\s*classification\\s*:\\s*([a-zA-Z][a-zA-Z0-9-_]*)\\s*,\\s*(.+)\\s*,\\s*(\\d+)\\s*$" +#define DETECT_CLASSCONFIG_REGEX \ + "^\\s*config\\s*classification\\s*:\\s*([a-zA-Z][a-zA-Z0-9-_]*)\\s*,\\s*(.+)\\s*,\\s*(\\d+)" \ + "\\s*$" /* Default path for the classification.config file */ #if defined OS_WIN32 || defined __CYGWIN__ @@ -49,13 +51,13 @@ #endif uint32_t SCClassConfClasstypeHashFunc(HashTable *ht, void *data, uint16_t datalen); -char SCClassConfClasstypeHashCompareFunc(void *data1, uint16_t datalen1, - void *data2, uint16_t datalen2); +char SCClassConfClasstypeHashCompareFunc( + void *data1, uint16_t datalen1, void *data2, uint16_t datalen2); void SCClassConfClasstypeHashFree(void *ch); static const char *SCClassConfGetConfFilename(const DetectEngineCtx *de_ctx); -static SCClassConfClasstype *SCClassConfAllocClasstype(uint16_t classtype_id, - const char *classtype, const char *classtype_desc, int priority); +static SCClassConfClasstype *SCClassConfAllocClasstype( + uint16_t classtype_id, const char *classtype, const char *classtype_desc, int priority); static void SCClassConfDeAllocClasstype(SCClassConfClasstype *ct); void SCClassConfInit(DetectEngineCtx *de_ctx) @@ -91,7 +93,6 @@ void SCClassConfDeinit(DetectEngineCtx *de_ctx) } } - /** * \brief Inits the context to be used by the Classification Config parsing API. * @@ -113,8 +114,7 @@ static FILE *SCClassConfInitContextAndLocalResources(DetectEngineCtx *de_ctx, FI { /* init the hash table to be used by the classification config Classtypes */ de_ctx->class_conf_ht = HashTableInit(128, SCClassConfClasstypeHashFunc, - SCClassConfClasstypeHashCompareFunc, - SCClassConfClasstypeHashFree); + SCClassConfClasstypeHashCompareFunc, SCClassConfClasstypeHashFree); if (de_ctx->class_conf_ht == NULL) { SCLogError("Error initializing the hash " "table"); @@ -127,7 +127,7 @@ static FILE *SCClassConfInitContextAndLocalResources(DetectEngineCtx *de_ctx, FI * classification strings */ if (fd == NULL) { const char *filename = SCClassConfGetConfFilename(de_ctx); - if ( (fd = fopen(filename, "r")) == NULL) { + if ((fd = fopen(filename, "r")) == NULL) { #ifdef UNITTESTS if (RunmodeIsUnittests()) return NULL; // silently fail @@ -140,7 +140,6 @@ static FILE *SCClassConfInitContextAndLocalResources(DetectEngineCtx *de_ctx, FI return fd; } - /** * \brief Returns the path for the Classification Config file. We check if we * can retrieve the path from the yaml conf file. If it is not present, @@ -156,8 +155,8 @@ static const char *SCClassConfGetConfFilename(const DetectEngineCtx *de_ctx) if (de_ctx != NULL && strlen(de_ctx->config_prefix) > 0) { char config_value[256]; - snprintf(config_value, sizeof(config_value), - "%s.classification-file", de_ctx->config_prefix); + snprintf(config_value, sizeof(config_value), "%s.classification-file", + de_ctx->config_prefix); /* try loading prefix setting, fall back to global if that * fails. */ @@ -208,7 +207,7 @@ static char *SCClassConfStringToLowercase(const char *str) char *new_str = NULL; char *temp_str = NULL; - if ( (new_str = SCStrdup(str)) == NULL) { + if ((new_str = SCStrdup(str)) == NULL) { SCLogError("Error allocating memory"); return NULL; } @@ -298,14 +297,16 @@ int SCClassConfAddClasstype(DetectEngineCtx *de_ctx, char *rawstr, uint16_t inde SCLogDebug("HashTable Add failed"); } else { SCLogDebug("Duplicate classtype found inside classification.config"); - if (ct_new->classtype_desc) SCFree(ct_new->classtype_desc); - if (ct_new->classtype) SCFree(ct_new->classtype); + if (ct_new->classtype_desc) + SCFree(ct_new->classtype_desc); + if (ct_new->classtype) + SCFree(ct_new->classtype); SCFree(ct_new); } return 0; - error: +error: return -1; } @@ -386,10 +387,8 @@ static bool SCClassConfParseFile(DetectEngineCtx *de_ctx, FILE *fd) * \retval ct Pointer to the new instance of SCClassConfClasstype on success; * NULL on failure. */ -static SCClassConfClasstype *SCClassConfAllocClasstype(uint16_t classtype_id, - const char *classtype, - const char *classtype_desc, - int priority) +static SCClassConfClasstype *SCClassConfAllocClasstype( + uint16_t classtype_id, const char *classtype, const char *classtype_desc, int priority) { SCClassConfClasstype *ct = NULL; @@ -404,8 +403,7 @@ static SCClassConfClasstype *SCClassConfAllocClasstype(uint16_t classtype_id, return NULL; } - if (classtype_desc != NULL && - (ct->classtype_desc = SCStrdup(classtype_desc)) == NULL) { + if (classtype_desc != NULL && (ct->classtype_desc = SCStrdup(classtype_desc)) == NULL) { SCLogError("Error allocating memory"); SCClassConfDeAllocClasstype(ct); @@ -478,8 +476,8 @@ uint32_t SCClassConfClasstypeHashFunc(HashTable *ht, void *data, uint16_t datale * \retval 1 On data1 and data2 being equal. * \retval 0 On data1 and data2 not being equal. */ -char SCClassConfClasstypeHashCompareFunc(void *data1, uint16_t datalen1, - void *data2, uint16_t datalen2) +char SCClassConfClasstypeHashCompareFunc( + void *data1, uint16_t datalen1, void *data2, uint16_t datalen2) { SCClassConfClasstype *ct1 = (SCClassConfClasstype *)data1; SCClassConfClasstype *ct2 = (SCClassConfClasstype *)data2; @@ -565,8 +563,7 @@ bool SCClassConfLoadClassificationConfigFile(DetectEngineCtx *de_ctx, FILE *fd) * \retval lookup_ct_info Pointer to the SCClassConfClasstype instance from * the hash table on success; NULL on failure. */ -SCClassConfClasstype *SCClassConfGetClasstype(const char *ct_name, - DetectEngineCtx *de_ctx) +SCClassConfClasstype *SCClassConfGetClasstype(const char *ct_name, DetectEngineCtx *de_ctx) { char name[strlen(ct_name) + 1]; size_t s; @@ -574,15 +571,13 @@ SCClassConfClasstype *SCClassConfGetClasstype(const char *ct_name, name[s] = u8_tolower((unsigned char)ct_name[s]); name[s] = '\0'; - SCClassConfClasstype ct_lookup = {0, 0, name, NULL }; - SCClassConfClasstype *lookup_ct_info = HashTableLookup(de_ctx->class_conf_ht, - &ct_lookup, 0); + SCClassConfClasstype ct_lookup = { 0, 0, name, NULL }; + SCClassConfClasstype *lookup_ct_info = HashTableLookup(de_ctx->class_conf_ht, &ct_lookup, 0); return lookup_ct_info; } /*----------------------------------Unittests---------------------------------*/ - #ifdef UNITTESTS /** @@ -593,10 +588,9 @@ SCClassConfClasstype *SCClassConfGetClasstype(const char *ct_name, */ FILE *SCClassConfGenerateValidDummyClassConfigFD01(void) { - const char *buffer = - "config classification: nothing-wrong,Nothing Wrong With Us,3\n" - "config classification: unknown,Unknown are we,3\n" - "config classification: bad-unknown,We think it's bad, 2\n"; + const char *buffer = "config classification: nothing-wrong,Nothing Wrong With Us,3\n" + "config classification: unknown,Unknown are we,3\n" + "config classification: bad-unknown,We think it's bad, 2\n"; FILE *fd = SCFmemopen((void *)buffer, strlen(buffer), "r"); if (fd == NULL) @@ -613,14 +607,13 @@ FILE *SCClassConfGenerateValidDummyClassConfigFD01(void) */ FILE *SCClassConfGenerateInvalidDummyClassConfigFD02(void) { - const char *buffer = - "config classification: not-suspicious,Not Suspicious Traffic,3\n" - "onfig classification: unknown,Unknown Traffic,3\n" - "config classification: _badunknown,Potentially Bad Traffic, 2\n" - "config classification: bamboola1,Unknown Traffic,3\n" - "config classification: misc-activity,Misc activity,-1\n" - "config classification: policy-violation,Potential Corporate " - "config classification: bamboola,Unknown Traffic,3\n"; + const char *buffer = "config classification: not-suspicious,Not Suspicious Traffic,3\n" + "onfig classification: unknown,Unknown Traffic,3\n" + "config classification: _badunknown,Potentially Bad Traffic, 2\n" + "config classification: bamboola1,Unknown Traffic,3\n" + "config classification: misc-activity,Misc activity,-1\n" + "config classification: policy-violation,Potential Corporate " + "config classification: bamboola,Unknown Traffic,3\n"; FILE *fd = SCFmemopen((void *)buffer, strlen(buffer), "r"); if (fd == NULL) @@ -637,11 +630,10 @@ FILE *SCClassConfGenerateInvalidDummyClassConfigFD02(void) */ FILE *SCClassConfGenerateInvalidDummyClassConfigFD03(void) { - const char *buffer = - "conig classification: not-suspicious,Not Suspicious Traffic,3\n" - "onfig classification: unknown,Unknown Traffic,3\n" - "config classification: _badunknown,Potentially Bad Traffic, 2\n" - "config classification: misc-activity,Misc activity,-1\n"; + const char *buffer = "conig classification: not-suspicious,Not Suspicious Traffic,3\n" + "onfig classification: unknown,Unknown Traffic,3\n" + "config classification: _badunknown,Potentially Bad Traffic, 2\n" + "config classification: misc-activity,Misc activity,-1\n"; FILE *fd = SCFmemopen((void *)buffer, strlen(buffer), "r"); if (fd == NULL) @@ -669,7 +661,8 @@ static int SCClassConfTest01(void) return result; result = (de_ctx->class_conf_ht->count == 3); - if (result == 0) printf("de_ctx->class_conf_ht->count %u: ", de_ctx->class_conf_ht->count); + if (result == 0) + printf("de_ctx->class_conf_ht->count %u: ", de_ctx->class_conf_ht->count); DetectEngineCtxFree(de_ctx); diff --git a/src/util-classification-config.h b/src/util-classification-config.h index 9ac00c85d09e..40538876b989 100644 --- a/src/util-classification-config.h +++ b/src/util-classification-config.h @@ -47,8 +47,7 @@ typedef struct SCClassConfClasstype_ { bool SCClassConfLoadClassificationConfigFile(DetectEngineCtx *, FILE *fd); int SCClassConfAddClasstype(DetectEngineCtx *de_ctx, char *rawstr, uint16_t index); -SCClassConfClasstype *SCClassConfGetClasstype(const char *, - DetectEngineCtx *); +SCClassConfClasstype *SCClassConfGetClasstype(const char *, DetectEngineCtx *); void SCClassConfDeInitContext(DetectEngineCtx *); void SCClassConfInit(DetectEngineCtx *de_ctx); diff --git a/src/util-clock.h b/src/util-clock.h index cb6c17623f99..81256a7a03e6 100644 --- a/src/util-clock.h +++ b/src/util-clock.h @@ -28,10 +28,12 @@ /* Feel free to add more macros */ -#define CLOCK_INIT clock_t clo1, clo2; clo1 = clo2 = 0; -#define CLOCK_START clo1 = clock() +#define CLOCK_INIT \ + clock_t clo1, clo2; \ + clo1 = clo2 = 0; +#define CLOCK_START clo1 = clock() -#define CLOCK_END clo2 = clock() +#define CLOCK_END clo2 = clock() #define CLOCK_PRINT_SEC \ printf("Seconds spent: %.4fs\n", ((double)(clo2 - clo1) / (double)CLOCKS_PER_SEC)) diff --git a/src/util-conf.c b/src/util-conf.c index 9bf5586bd970..4f555b2065a9 100644 --- a/src/util-conf.c +++ b/src/util-conf.c @@ -121,10 +121,9 @@ TmEcode ConfigCheckDataDirectory(const char *data_dir) ConfNode *ConfFindDeviceConfig(ConfNode *node, const char *iface) { ConfNode *if_node, *item; - TAILQ_FOREACH(if_node, &node->head, next) { - TAILQ_FOREACH(item, &if_node->head, next) { - if (strcmp(item->name, "interface") == 0 && - strcmp(item->val, iface) == 0) { + TAILQ_FOREACH (if_node, &node->head, next) { + TAILQ_FOREACH (item, &if_node->head, next) { + if (strcmp(item->name, "interface") == 0 && strcmp(item->val, iface) == 0) { return if_node; } } diff --git a/src/util-config.h b/src/util-config.h index 92017d502162..ae97d96edf77 100644 --- a/src/util-config.h +++ b/src/util-config.h @@ -33,19 +33,19 @@ enum ConfigSubsys { }; enum ConfigType { - CONFIG_TYPE_TX = 0, /* transaction logging */ - CONFIG_TYPE_FLOW, /* flow logging */ - CONFIG_TYPE_ALERT, /* alert logging */ - CONFIG_TYPE_ANOMALY, /* anomaly logging */ - CONFIG_TYPE_FILE, /* file logging */ - CONFIG_TYPE_PCAP, /* pcap logging */ - CONFIG_TYPE_DROP, /* drop logging */ + CONFIG_TYPE_TX = 0, /* transaction logging */ + CONFIG_TYPE_FLOW, /* flow logging */ + CONFIG_TYPE_ALERT, /* alert logging */ + CONFIG_TYPE_ANOMALY, /* anomaly logging */ + CONFIG_TYPE_FILE, /* file logging */ + CONFIG_TYPE_PCAP, /* pcap logging */ + CONFIG_TYPE_DROP, /* drop logging */ #define CONFIG_TYPE_DEFAULT CONFIG_TYPE_TX }; enum ConfigScope { - CONFIG_SCOPE_TX = 0, /* per transaction */ - CONFIG_SCOPE_FLOW, /* per flow */ + CONFIG_SCOPE_TX = 0, /* per transaction */ + CONFIG_SCOPE_FLOW, /* per flow */ #define CONFIG_SCOPE_DEFAULT CONFIG_SCOPE_TX }; diff --git a/src/util-coredump-config.c b/src/util-coredump-config.c index 09485cb79571..9dbf7da0acef 100644 --- a/src/util-coredump-config.c +++ b/src/util-coredump-config.c @@ -37,10 +37,12 @@ #ifdef OS_WIN32 -void CoredumpEnable(void) { +void CoredumpEnable(void) +{ } -int32_t CoredumpLoadConfig(void) { +int32_t CoredumpLoadConfig(void) +{ /* todo: use the registry to get/set dump configuration */ SCLogInfo("Configuring core dump is not yet supported on Windows."); return 0; @@ -68,8 +70,7 @@ void CoredumpEnable(void) SCLogNotice("Failed to get dumpable state of process, " "core dumps may not be enabled: %s", strerror(errno)); - } - else if (unlimited || max_dump > 0) { + } else if (unlimited || max_dump > 0) { /* try to enable core dump for this process */ if (prctl(PR_SET_DUMPABLE, 1, 0, 0, 0) == -1) { SCLogInfo("Unable to make this process dumpable."); @@ -88,47 +89,45 @@ void CoredumpEnable(void) * \retval Returns 1 on success and 0 on failure. * */ -int32_t CoredumpLoadConfig (void) +int32_t CoredumpLoadConfig(void) { #ifdef HAVE_SYS_RESOURCE_H /* get core dump configuration settings for suricata */ const char *dump_size_config = NULL; size_t rlim_size = sizeof(rlim_t); - if (ConfGet ("coredump.max-dump", &dump_size_config) == 0) { - SCLogDebug ("core dump size not specified"); + if (ConfGet("coredump.max-dump", &dump_size_config) == 0) { + SCLogDebug("core dump size not specified"); return 1; } if (dump_size_config == NULL) { SCLogError("malformed value for coredump.max-dump: NULL"); return 0; } - if (strcasecmp (dump_size_config, "unlimited") == 0) { + if (strcasecmp(dump_size_config, "unlimited") == 0) { unlimited = true; - } - else { + } else { /* disallow negative values */ - if (strchr (dump_size_config, '-') != NULL) { - SCLogInfo ("Negative value for core dump size; ignored."); + if (strchr(dump_size_config, '-') != NULL) { + SCLogInfo("Negative value for core dump size; ignored."); return 0; } /* the size of rlim_t is platform dependent */ if (rlim_size > 8) { - SCLogInfo ("Unexpected type for rlim_t"); + SCLogInfo("Unexpected type for rlim_t"); return 0; } errno = 0; if (rlim_size == 8) { - max_dump = (rlim_t) strtoull (dump_size_config, NULL, 10); - } - else if (rlim_size == 4) { - max_dump = (rlim_t) strtoul (dump_size_config, NULL, 10); + max_dump = (rlim_t)strtoull(dump_size_config, NULL, 10); + } else if (rlim_size == 4) { + max_dump = (rlim_t)strtoul(dump_size_config, NULL, 10); } if ((errno == ERANGE) || (errno != 0 && max_dump == 0)) { - SCLogInfo ("Illegal core dump size: %s.", dump_size_config); + SCLogInfo("Illegal core dump size: %s.", dump_size_config); return 0; } - SCLogInfo ("Max dump is %"PRIu64, (uint64_t) max_dump); + SCLogInfo("Max dump is %" PRIu64, (uint64_t)max_dump); } CoredumpEnable(); @@ -137,22 +136,21 @@ int32_t CoredumpLoadConfig (void) struct rlimit new_lim; /*desired limit*/ /* get the current core dump file configuration */ - if (getrlimit (RLIMIT_CORE, &lim) == -1) { - SCLogInfo ("Can't read coredump limit for this process."); + if (getrlimit(RLIMIT_CORE, &lim) == -1) { + SCLogInfo("Can't read coredump limit for this process."); return 0; } if (unlimited) { /* we want no limit on coredump size */ if (lim.rlim_max == RLIM_INFINITY && lim.rlim_cur == RLIM_INFINITY) { - SCLogConfig ("Core dump size is unlimited."); + SCLogConfig("Core dump size is unlimited."); return 1; - } - else { + } else { new_lim.rlim_max = RLIM_INFINITY; new_lim.rlim_cur = RLIM_INFINITY; - if (setrlimit (RLIMIT_CORE, &new_lim) == 0) { - SCLogConfig ("Core dump size set to unlimited."); + if (setrlimit(RLIMIT_CORE, &new_lim) == 0) { + SCLogConfig("Core dump size set to unlimited."); return 1; } if (errno == EPERM) { @@ -160,21 +158,21 @@ int32_t CoredumpLoadConfig (void) * try increasing the soft limit to the hard limit instead */ if (lim.rlim_cur < lim.rlim_max) { new_lim.rlim_cur = lim.rlim_max; - if (setrlimit (RLIMIT_CORE, & new_lim) == 0) { - SCLogInfo ("Could not set core dump size to unlimited; core dump size set to the hard limit."); + if (setrlimit(RLIMIT_CORE, &new_lim) == 0) { + SCLogInfo("Could not set core dump size to unlimited; core dump size set " + "to the hard limit."); return 0; - } - else { - SCLogInfo ("Failed to set core dump size to unlimited or to the hard limit."); + } else { + SCLogInfo( + "Failed to set core dump size to unlimited or to the hard limit."); return 0; } } - SCLogInfo ("Could not set core dump size to unlimited; it's set to the hard limit."); + SCLogInfo("Could not set core dump size to unlimited; it's set to the hard limit."); return 0; } } - } - else { + } else { /* we want a non-infinite soft limit on coredump size */ new_lim.rlim_cur = max_dump; @@ -189,28 +187,27 @@ int32_t CoredumpLoadConfig (void) new_lim.rlim_max = lim.rlim_max; } #endif - else if (lim.rlim_max < max_dump) { + else if (lim.rlim_max < max_dump) { /* need to raise the hard coredump size limit */ - new_lim.rlim_max = max_dump; - } - else { + new_lim.rlim_max = max_dump; + } else { /* hard limit is ample */ new_lim.rlim_max = lim.rlim_max; } - if (setrlimit (RLIMIT_CORE, &new_lim) == 0) { - SCLogInfo ("Core dump setting attempted is %"PRIu64, (uint64_t) new_lim.rlim_cur); + if (setrlimit(RLIMIT_CORE, &new_lim) == 0) { + SCLogInfo("Core dump setting attempted is %" PRIu64, (uint64_t)new_lim.rlim_cur); struct rlimit actual_lim; - if (getrlimit (RLIMIT_CORE, &actual_lim) == 0) { + if (getrlimit(RLIMIT_CORE, &actual_lim) == 0) { if (actual_lim.rlim_cur == RLIM_INFINITY) { - SCLogConfig ("Core dump size set to unlimited."); + SCLogConfig("Core dump size set to unlimited."); } #ifdef RLIM_SAVED_CUR else if (actual_lim.rlim_cur == RLIM_SAVED_CUR) { - SCLogInfo ("Core dump size set to soft limit."); + SCLogInfo("Core dump size set to soft limit."); } #endif else { - SCLogInfo ("Core dump size set to %"PRIu64, (uint64_t) actual_lim.rlim_cur); + SCLogInfo("Core dump size set to %" PRIu64, (uint64_t)actual_lim.rlim_cur); } } return 1; @@ -221,12 +218,12 @@ int32_t CoredumpLoadConfig (void) * limit; try to raise the soft limit to the hard limit */ if ((lim.rlim_cur < max_dump && lim.rlim_cur < lim.rlim_max) #ifdef RLIM_SAVED_CUR - || (lim.rlim_cur == RLIM_SAVED_CUR) + || (lim.rlim_cur == RLIM_SAVED_CUR) #endif - ){ + ) { new_lim.rlim_max = lim.rlim_max; new_lim.rlim_cur = lim.rlim_max; - if (setrlimit (RLIMIT_CORE, &new_lim) == 0) { + if (setrlimit(RLIMIT_CORE, &new_lim) == 0) { SCLogInfo("Core dump size set to the hard limit."); return 0; } diff --git a/src/util-cpu.c b/src/util-cpu.c index c73d5221e347..e457e19e4175 100644 --- a/src/util-cpu.c +++ b/src/util-cpu.c @@ -59,7 +59,7 @@ uint16_t UtilCpuGetNumProcessorsConfigured(void) { #ifdef SYSCONF_NPROCESSORS_CONF_COMPAT - long nprocs = -1; + long nprocs = -1; nprocs = sysconf(_SC_NPROCESSORS_CONF); if (nprocs < 1) { SCLogError("Couldn't retrieve the number of cpus " @@ -71,14 +71,15 @@ uint16_t UtilCpuGetNumProcessorsConfigured(void) if (nprocs > UINT16_MAX) { SCLogDebug("It seems that there are more than %d CPUs " "configured on this system. You can modify util-cpu.{c,h} " - "to use uint32_t to support it", UINT16_MAX); + "to use uint32_t to support it", + UINT16_MAX); return UINT16_MAX; } return (uint16_t)nprocs; #elif OS_WIN32 int64_t nprocs = 0; - const char* envvar = getenv("NUMBER_OF_PROCESSORS"); + const char *envvar = getenv("NUMBER_OF_PROCESSORS"); if (envvar != NULL) { if (StringParseInt64(&nprocs, 10, 0, envvar) < 0) { SCLogWarning("Invalid value for number of " @@ -120,13 +121,14 @@ uint16_t UtilCpuGetNumProcessorsOnline(void) if (nprocs > UINT16_MAX) { SCLogDebug("It seems that there are more than %d CPUs online. " "You can modify util-cpu.{c,h} to use uint32_t to " - "support it", UINT16_MAX); + "support it", + UINT16_MAX); return UINT16_MAX; } return (uint16_t)nprocs; #elif OS_WIN32 - return UtilCpuGetNumProcessorsConfigured(); + return UtilCpuGetNumProcessorsConfigured(); #else SCLogError("Couldn't retrieve the number of cpus online, " "synconf macro unavailable"); @@ -154,8 +156,9 @@ uint16_t UtilCpuGetNumProcessorsMax(void) } if (nprocs > UINT16_MAX) { - SCLogDebug("It seems that the system support more that %"PRIu16" CPUs. You " - "can modify util-cpu.{c,h} to use uint32_t to support it", UINT16_MAX); + SCLogDebug("It seems that the system support more that %" PRIu16 " CPUs. You " + "can modify util-cpu.{c,h} to use uint32_t to support it", + UINT16_MAX); return UINT16_MAX; } @@ -177,9 +180,9 @@ void UtilCpuPrintSummary(void) SCLogDebug("CPUs Summary: "); if (cpus_conf > 0) - SCLogDebug("CPUs configured: %"PRIu16, cpus_conf); + SCLogDebug("CPUs configured: %" PRIu16, cpus_conf); if (cpus_online > 0) - SCLogInfo("CPUs/cores online: %"PRIu16, cpus_online); + SCLogInfo("CPUs/cores online: %" PRIu16, cpus_online); if (cpus_online == 0 && cpus_conf == 0) SCLogInfo("Couldn't retrieve any information of CPU's, please, send your operating " "system info and check util-cpu.{c,h}"); @@ -194,39 +197,36 @@ void UtilCpuPrintSummary(void) uint64_t UtilCpuGetTicks(void) { uint64_t val; -#if defined(__GNUC__) && (defined(__x86_64) || defined(_X86_64_) || defined(ia_64) || defined(__i386__)) +#if defined(__GNUC__) && \ + (defined(__x86_64) || defined(_X86_64_) || defined(ia_64) || defined(__i386__)) #if defined(__x86_64) || defined(_X86_64_) || defined(ia_64) - __asm__ __volatile__ ( - "xorl %%eax,%%eax\n\t" - "cpuid\n\t" - ::: "%rax", "%rbx", "%rcx", "%rdx"); + __asm__ __volatile__("xorl %%eax,%%eax\n\t" + "cpuid\n\t" :: + : "%rax", "%rbx", "%rcx", "%rdx"); #else - __asm__ __volatile__ ( - "xorl %%eax,%%eax\n\t" - "pushl %%ebx\n\t" - "cpuid\n\t" - "popl %%ebx\n\t" - ::: "%eax", "%ecx", "%edx"); + __asm__ __volatile__("xorl %%eax,%%eax\n\t" + "pushl %%ebx\n\t" + "cpuid\n\t" + "popl %%ebx\n\t" :: + : "%eax", "%ecx", "%edx"); #endif uint32_t a, d; - __asm__ __volatile__ ("rdtsc" : "=a" (a), "=d" (d)); + __asm__ __volatile__("rdtsc" : "=a"(a), "=d"(d)); val = ((uint64_t)a) | (((uint64_t)d) << 32); #if defined(__x86_64) || defined(_X86_64_) || defined(ia_64) - __asm__ __volatile__ ( - "xorl %%eax,%%eax\n\t" - "cpuid\n\t" - ::: "%rax", "%rbx", "%rcx", "%rdx"); + __asm__ __volatile__("xorl %%eax,%%eax\n\t" + "cpuid\n\t" :: + : "%rax", "%rbx", "%rcx", "%rdx"); #else - __asm__ __volatile__ ( - "xorl %%eax,%%eax\n\t" - "pushl %%ebx\n\t" - "cpuid\n\t" - "popl %%ebx\n\t" - ::: "%eax", "%ecx", "%edx"); + __asm__ __volatile__("xorl %%eax,%%eax\n\t" + "pushl %%ebx\n\t" + "cpuid\n\t" + "popl %%ebx\n\t" :: + : "%eax", "%ecx", "%edx"); #endif #else /* #if defined(__GNU__) */ -//#warning Using inferior version of UtilCpuGetTicks + //#warning Using inferior version of UtilCpuGetTicks struct timeval now; gettimeofday(&now, NULL); val = (now.tv_sec * 1000000) + now.tv_usec; diff --git a/src/util-daemon.c b/src/util-daemon.c index 909218910105..6fe585239948 100644 --- a/src/util-daemon.c +++ b/src/util-daemon.c @@ -41,7 +41,7 @@ static volatile sig_atomic_t sigflag = 0; /** * \brief Signal handler used to take the parent process out of stand-by */ -static void SignalHandlerSigusr1 (int signo) +static void SignalHandlerSigusr1(int signo) { sigflag = 1; } @@ -51,7 +51,7 @@ static void SignalHandlerSigusr1 (int signo) * * \param pid pid of the parent process to signal */ -static void TellWaitingParent (pid_t pid) +static void TellWaitingParent(pid_t pid) { kill(pid, SIGUSR1); } @@ -61,7 +61,7 @@ static void TellWaitingParent (pid_t pid) * * \param pid pid of the child process to wait */ -static void WaitForChild (pid_t pid) +static void WaitForChild(pid_t pid) { int status; SCLogDebug("Daemon: Parent waiting for child to be ready..."); @@ -82,7 +82,7 @@ static void WaitForChild (pid_t pid) * \brief Close stdin, stdout, stderr.Redirect logging info to syslog * */ -static void SetupLogging (void) +static void SetupLogging(void) { /* Redirect stdin, stdout, stderr to /dev/null */ int fd = open("/dev/null", O_RDWR); @@ -98,7 +98,7 @@ static void SetupLogging (void) * \brief Daemonize the process * */ -void Daemonize (void) +void Daemonize(void) { pid_t pid, sid; @@ -160,7 +160,6 @@ void Daemonize (void) /* Parent exits */ SCLogDebug("Child is ready, parent exiting"); exit(EXIT_SUCCESS); - } #endif /* ifndef OS_WIN32 */ @@ -174,7 +173,7 @@ void Daemonize (void) * \retval 1 valid combination * \retval 0 invalid combination */ -int CheckValidDaemonModes (int daemon, int mode) +int CheckValidDaemonModes(int daemon, int mode) { if (daemon) { switch (mode) { diff --git a/src/util-daemon.h b/src/util-daemon.h index 424d7093eae8..a67113883340 100644 --- a/src/util-daemon.h +++ b/src/util-daemon.h @@ -27,9 +27,9 @@ #ifdef OS_WIN32 #define Daemonize() #else -void Daemonize (void); +void Daemonize(void); #endif -int CheckValidDaemonModes (int, int); +int CheckValidDaemonModes(int, int); #endif /* __UTIL_DAEMON_H__ */ diff --git a/src/util-debug-filters.c b/src/util-debug-filters.c index fd66375cb9fc..9b93b4a48c60 100644 --- a/src/util-debug-filters.c +++ b/src/util-debug-filters.c @@ -47,7 +47,7 @@ SCLogFGFilterFile *sc_log_fg_filters[SC_LOG_FILTER_MAX] = { NULL, NULL }; * \brief Mutex for accessing the fine-grained filters sc_log_fg_filters */ static SCMutex sc_log_fg_filters_m[SC_LOG_FILTER_MAX] = { SCMUTEX_INITIALIZER, - SCMUTEX_INITIALIZER }; + SCMUTEX_INITIALIZER }; /** * \brief Holds the function-dependent filters @@ -81,8 +81,7 @@ static SCMutex sc_log_fd_filters_tl_m = SCMUTEX_INITIALIZER; * \retval 0 on successfully adding the filter; * \retval -1 on failure */ -static int SCLogAddFGFilter(const char *file, const char *function, - int line, int listtype) +static int SCLogAddFGFilter(const char *file, const char *function, int line, int listtype) { SCLogFGFilterFile *fgf_file = NULL; SCLogFGFilterFile *prev_fgf_file = NULL; @@ -98,7 +97,7 @@ static int SCLogAddFGFilter(const char *file, const char *function, if (sc_log_module_initialized != 1) { printf("Logging module not initialized. Call SCLogInitLogModule() " "first before using the debug API\n"); - return -1 ; + return -1; } if (file == NULL && function == NULL && line < 0) { @@ -159,7 +158,7 @@ static int SCLogAddFGFilter(const char *file, const char *function, found = 0; fgf_line = fgf_func->line; prev_fgf_line = fgf_line; - while(fgf_line != NULL) { + while (fgf_line != NULL) { prev_fgf_line = fgf_line; if (line == fgf_line->line) { found = 1; @@ -174,7 +173,7 @@ static int SCLogAddFGFilter(const char *file, const char *function, goto done; } - done: +done: SCMutexUnlock(&sc_log_fg_filters_m[listtype]); sc_log_fg_filters_present = 1; @@ -197,8 +196,7 @@ static int SCLogAddFGFilter(const char *file, const char *function, * \retval 0 on no match * \retval -1 on failure */ -static int SCLogMatchFGFilter(const char *file, const char *function, int line, - int listtype) +static int SCLogMatchFGFilter(const char *file, const char *function, int line, int listtype) { SCLogFGFilterFile *fgf_file = NULL; SCLogFGFilterFunc *fgf_func = NULL; @@ -220,10 +218,10 @@ static int SCLogMatchFGFilter(const char *file, const char *function, int line, return 1; } - while(fgf_file != NULL) { + while (fgf_file != NULL) { match = 1; - match &= (fgf_file->file != NULL)? !strcmp(file, fgf_file->file): 1; + match &= (fgf_file->file != NULL) ? !strcmp(file, fgf_file->file) : 1; if (match == 0) { fgf_file = fgf_file->next; @@ -234,7 +232,7 @@ static int SCLogMatchFGFilter(const char *file, const char *function, int line, while (fgf_func != NULL) { match = 1; - match &= (fgf_func->func != NULL)? !strcmp(function, fgf_func->func): 1; + match &= (fgf_func->func != NULL) ? !strcmp(function, fgf_func->func) : 1; if (match == 0) { fgf_func = fgf_func->next; @@ -245,7 +243,7 @@ static int SCLogMatchFGFilter(const char *file, const char *function, int line, while (fgf_line != NULL) { match = 1; - match &= (fgf_line->line != -1)? (line == fgf_line->line): 1; + match &= (fgf_line->line != -1) ? (line == fgf_line->line) : 1; if (match == 1) break; @@ -376,7 +374,7 @@ void SCLogReleaseFGFilters(void) while (fgf_func != NULL) { fgf_line = fgf_func->line; - while(fgf_line != NULL) { + while (fgf_line != NULL) { temp = fgf_line; fgf_line = fgf_line->next; SCFree(temp); @@ -437,7 +435,7 @@ int SCLogPrintFGFilters(void) while (fgf_func != NULL) { fgf_line = fgf_func->line; - while(fgf_line != NULL) { + while (fgf_line != NULL) { #ifdef DEBUG printf("%s - ", fgf_file->file); printf("%s - ", fgf_func->func); @@ -460,8 +458,6 @@ int SCLogPrintFGFilters(void) return count; } - - /* --------------------------------------------------|-------------------------- * -------------------------- Code for the FD Filter |-------------------------- * --------------------------------------------------V-------------------------- @@ -536,7 +532,7 @@ int SCLogCheckFDFilterEntry(const char *function) SCLogFDFilterThreadList *thread_list = NULL; SCLogFDFilterThreadList *thread_list_temp = NULL; - //pid_t self = syscall(SYS_gettid); + // pid_t self = syscall(SYS_gettid); pthread_t self = pthread_self(); if (sc_log_module_initialized != 1) { @@ -608,7 +604,7 @@ void SCLogCheckFDFilterExit(const char *function) SCLogFDFilterThreadList *thread_list = NULL; - //pid_t self = syscall(SYS_gettid); + // pid_t self = syscall(SYS_gettid); pthread_t self = pthread_self(); if (sc_log_module_initialized != 1) { @@ -698,7 +694,7 @@ int SCLogAddFDFilter(const char *function) exit(EXIT_FAILURE); } - if ( (temp->func = SCStrdup(function)) == NULL) { + if ((temp->func = SCStrdup(function)) == NULL) { printf("Error Allocating memory (SCStrdup)\n"); exit(EXIT_FAILURE); } @@ -736,7 +732,7 @@ void SCLogReleaseFDFilters(void) sc_log_fd_filters = NULL; - SCMutexUnlock( &sc_log_fd_filters_m ); + SCMutexUnlock(&sc_log_fd_filters_m); return; } @@ -757,7 +753,7 @@ int SCLogRemoveFDFilter(const char *function) if (sc_log_module_initialized != 1) { printf("Logging module not initialized. Call SCLogInitLogModule() " "first before using the debug API\n"); - return -1 ; + return -1; } if (function == NULL) { @@ -853,10 +849,8 @@ int SCLogPrintFDFilters(void) * \param listtype The filter listtype. Can be either a blacklist or whitelist * filter listtype(SC_LOG_FILTER_BL or SC_LOG_FILTER_WL) */ -void SCLogAddToFGFFileList(SCLogFGFilterFile *fgf_file, - const char *file, - const char *function, int line, - int listtype) +void SCLogAddToFGFFileList( + SCLogFGFilterFile *fgf_file, const char *file, const char *function, int line, int listtype) { SCLogFGFilterFile *fgf_file_temp = NULL; SCLogFGFilterFunc *fgf_func_temp = NULL; @@ -866,7 +860,7 @@ void SCLogAddToFGFFileList(SCLogFGFilterFile *fgf_file, FatalError("Fatal error encountered in SCLogAddToFGFFileList. Exiting..."); } - if ( file != NULL && (fgf_file_temp->file = SCStrdup(file)) == NULL) { + if (file != NULL && (fgf_file_temp->file = SCStrdup(file)) == NULL) { printf("Error Allocating memory\n"); exit(EXIT_FAILURE); } @@ -875,7 +869,7 @@ void SCLogAddToFGFFileList(SCLogFGFilterFile *fgf_file, FatalError("Fatal error encountered in SCLogAddToFGFFileList. Exiting..."); } - if ( function != NULL && (fgf_func_temp->func = SCStrdup(function)) == NULL) { + if (function != NULL && (fgf_func_temp->func = SCStrdup(function)) == NULL) { printf("Error Allocating memory\n"); exit(EXIT_FAILURE); } @@ -913,9 +907,8 @@ void SCLogAddToFGFFileList(SCLogFGFilterFile *fgf_file, * \param function Function_name of the filter * \param line Line number of the filter */ -void SCLogAddToFGFFuncList(SCLogFGFilterFile *fgf_file, - SCLogFGFilterFunc *fgf_func, - const char *function, int line) +void SCLogAddToFGFFuncList( + SCLogFGFilterFile *fgf_file, SCLogFGFilterFunc *fgf_func, const char *function, int line) { SCLogFGFilterFunc *fgf_func_temp = NULL; SCLogFGFilterLine *fgf_line_temp = NULL; @@ -924,7 +917,7 @@ void SCLogAddToFGFFuncList(SCLogFGFilterFile *fgf_file, FatalError("Fatal error encountered in SCLogAddToFGFFuncList. Exiting..."); } - if ( function != NULL && (fgf_func_temp->func = SCStrdup(function)) == NULL) { + if (function != NULL && (fgf_func_temp->func = SCStrdup(function)) == NULL) { printf("Error Allocating memory\n"); exit(EXIT_FAILURE); } @@ -959,9 +952,7 @@ void SCLogAddToFGFFuncList(SCLogFGFilterFile *fgf_file, * added * \param line Line number of the filter */ -void SCLogAddToFGFLineList(SCLogFGFilterFunc *fgf_func, - SCLogFGFilterLine *fgf_line, - int line) +void SCLogAddToFGFLineList(SCLogFGFilterFunc *fgf_func, SCLogFGFilterLine *fgf_line, int line) { SCLogFGFilterLine *fgf_line_temp = NULL; @@ -995,4 +986,3 @@ void SCLogReleaseFDFilter(SCLogFDFilter *fdf) return; } - diff --git a/src/util-debug-filters.h b/src/util-debug-filters.h index 26c9ec9c88a4..47ef7d979351 100644 --- a/src/util-debug-filters.h +++ b/src/util-debug-filters.h @@ -72,7 +72,7 @@ typedef struct SCLogFGFilterFile_ { typedef struct SCLogFDFilterThreadList_ { int entered; pthread_t t; -// pid_t t; + // pid_t t; struct SCLogFDFilterThreadList_ *next; } SCLogFDFilterThreadList; @@ -86,12 +86,10 @@ typedef struct SCLogFDFilter_ { struct SCLogFDFilter_ *next; } SCLogFDFilter; - extern int sc_log_fg_filters_present; extern int sc_log_fd_filters_present; - int SCLogAddFGFilterWL(const char *, const char *, int); int SCLogAddFGFilterBL(const char *, const char *, int); @@ -118,18 +116,11 @@ int SCLogMatchFDFilter(const char *); int SCLogPrintFGFilters(void); -void SCLogAddToFGFFileList(SCLogFGFilterFile *, - const char *, - const char *, int, - int); +void SCLogAddToFGFFileList(SCLogFGFilterFile *, const char *, const char *, int, int); -void SCLogAddToFGFFuncList(SCLogFGFilterFile *, - SCLogFGFilterFunc *, - const char *, int); +void SCLogAddToFGFFuncList(SCLogFGFilterFile *, SCLogFGFilterFunc *, const char *, int); -void SCLogAddToFGFLineList(SCLogFGFilterFunc *, - SCLogFGFilterLine *, - int); +void SCLogAddToFGFLineList(SCLogFGFilterFunc *, SCLogFGFilterLine *, int); void SCLogReleaseFDFilter(SCLogFDFilter *); #endif /* __DEBUG_FILTERS_H__ */ diff --git a/src/util-debug.c b/src/util-debug.c index c62a0104dda3..b764416dd0f7 100644 --- a/src/util-debug.c +++ b/src/util-debug.c @@ -73,7 +73,7 @@ SCEnumCharMap sc_log_op_iface_map[ ] = { }; // clang-format on -#if defined (OS_WIN32) +#if defined(OS_WIN32) /** * \brief Used for synchronous output on WIN32 */ @@ -161,8 +161,8 @@ static inline void SCLogPrintToStream(FILE *fd, char *msg) return; } -#if defined (OS_WIN32) - SCMutexLock(&sc_log_stream_lock); +#if defined(OS_WIN32) + SCMutexLock(&sc_log_stream_lock); #endif /* OS_WIN32 */ if (fprintf(fd, "%s\n", msg) < 0) @@ -170,8 +170,8 @@ static inline void SCLogPrintToStream(FILE *fd, char *msg) fflush(fd); -#if defined (OS_WIN32) - SCMutexUnlock(&sc_log_stream_lock); +#if defined(OS_WIN32) + SCMutexUnlock(&sc_log_stream_lock); #endif /* OS_WIN32 */ return; @@ -189,8 +189,8 @@ static inline void SCLogPrintToStream(FILE *fd, char *msg) */ static inline void SCLogPrintToSyslog(int syslog_log_level, const char *msg) { - //static struct syslog_data data = SYSLOG_DATA_INIT; - //syslog_r(syslog_log_level, NULL, "%s", msg); + // static struct syslog_data data = SYSLOG_DATA_INIT; + // syslog_r(syslog_log_level, NULL, "%s", msg); syslog(syslog_log_level, "%s", msg); @@ -388,7 +388,7 @@ static SCError SCLogMessageGetBuffer(SCTime_t tval, bool color, SCLogOPType type if ((temp - buffer) > SC_LOG_MAX_LOG_MSG_LEN) { return 0; } - switch(temp_fmt[1]) { + switch (temp_fmt[1]) { case SC_LOG_FMT_TIME: temp_fmt[0] = '\0'; @@ -412,10 +412,9 @@ static SCError SCLogMessageGetBuffer(SCTime_t tval, bool color, SCLogOPType type tms = SCLocalTime(SCTIME_SECS(tval), &local_tm); cw = snprintf(temp, SC_LOG_MAX_LOG_MSG_LEN - (temp - buffer), - "%s%s%d/%d/%04d -- %02d:%02d:%02d%s", - substr, green, tms->tm_mday, tms->tm_mon + 1, - tms->tm_year + 1900, tms->tm_hour, tms->tm_min, - tms->tm_sec, reset); + "%s%s%d/%d/%04d -- %02d:%02d:%02d%s", substr, green, tms->tm_mday, + tms->tm_mon + 1, tms->tm_year + 1900, tms->tm_hour, tms->tm_min, + tms->tm_sec, reset); if (cw < 0) return -1; temp += cw; @@ -426,8 +425,8 @@ static SCError SCLogMessageGetBuffer(SCTime_t tval, bool color, SCLogOPType type case SC_LOG_FMT_PID: temp_fmt[0] = '\0'; - cw = snprintf(temp, SC_LOG_MAX_LOG_MSG_LEN - (temp - buffer), - "%s%s%u%s", substr, yellow, getpid(), reset); + cw = snprintf(temp, SC_LOG_MAX_LOG_MSG_LEN - (temp - buffer), "%s%s%u%s", substr, + yellow, getpid(), reset); if (cw < 0) return -1; temp += cw; @@ -438,8 +437,8 @@ static SCError SCLogMessageGetBuffer(SCTime_t tval, bool color, SCLogOPType type case SC_LOG_FMT_TID: temp_fmt[0] = '\0'; - cw = snprintf(temp, SC_LOG_MAX_LOG_MSG_LEN - (temp - buffer), - "%s%s%lu%s", substr, yellow, SCGetThreadIdLong(), reset); + cw = snprintf(temp, SC_LOG_MAX_LOG_MSG_LEN - (temp - buffer), "%s%s%lu%s", substr, + yellow, SCGetThreadIdLong(), reset); if (cw < 0) return -1; temp += cw; @@ -466,14 +465,14 @@ static SCError SCLogMessageGetBuffer(SCTime_t tval, bool color, SCLogOPType type s = SCMapEnumValueToName(log_level, sc_log_level_map); if (s != NULL) { if (log_level <= SC_LOG_ERROR) - cw = snprintf(temp, SC_LOG_MAX_LOG_MSG_LEN - (temp - buffer), - "%s%s%s%s", substr, redb, s, reset); + cw = snprintf(temp, SC_LOG_MAX_LOG_MSG_LEN - (temp - buffer), "%s%s%s%s", + substr, redb, s, reset); else if (log_level == SC_LOG_WARNING) - cw = snprintf(temp, SC_LOG_MAX_LOG_MSG_LEN - (temp - buffer), - "%s%s%s%s", substr, red, s, reset); + cw = snprintf(temp, SC_LOG_MAX_LOG_MSG_LEN - (temp - buffer), "%s%s%s%s", + substr, red, s, reset); else if (log_level == SC_LOG_NOTICE) - cw = snprintf(temp, SC_LOG_MAX_LOG_MSG_LEN - (temp - buffer), - "%s%s%s%s", substr, yellowb, s, reset); + cw = snprintf(temp, SC_LOG_MAX_LOG_MSG_LEN - (temp - buffer), "%s%s%s%s", + substr, yellowb, s, reset); else cw = snprintf(temp, SC_LOG_MAX_LOG_MSG_LEN - (temp - buffer), "%s%s%s%s", substr, yellow, s, reset); @@ -503,11 +502,11 @@ static SCError SCLogMessageGetBuffer(SCTime_t tval, bool color, SCLogOPType type cw = snprintf(temp, SC_LOG_MAX_LOG_MSG_LEN - (temp - buffer), "%s%s%s%s", substr, yellowb, s, reset); else - cw = snprintf(temp, SC_LOG_MAX_LOG_MSG_LEN - (temp - buffer), - "%s%s%s%s", substr, yellow, s, reset); + cw = snprintf(temp, SC_LOG_MAX_LOG_MSG_LEN - (temp - buffer), "%s%s%s%s", + substr, yellow, s, reset); } else { - cw = snprintf(temp, SC_LOG_MAX_LOG_MSG_LEN - (temp - buffer), - "%s%s", substr, "INVALID"); + cw = snprintf(temp, SC_LOG_MAX_LOG_MSG_LEN - (temp - buffer), "%s%s", substr, + "INVALID"); } if (cw < 0) return -1; @@ -519,8 +518,8 @@ static SCError SCLogMessageGetBuffer(SCTime_t tval, bool color, SCLogOPType type case SC_LOG_FMT_FILE_NAME: temp_fmt[0] = '\0'; - cw = snprintf(temp, SC_LOG_MAX_LOG_MSG_LEN - (temp - buffer), - "%s%s%s%s", substr, blue, file, reset); + cw = snprintf(temp, SC_LOG_MAX_LOG_MSG_LEN - (temp - buffer), "%s%s%s%s", substr, + blue, file, reset); if (cw < 0) return -1; temp += cw; @@ -531,8 +530,8 @@ static SCError SCLogMessageGetBuffer(SCTime_t tval, bool color, SCLogOPType type case SC_LOG_FMT_LINE: temp_fmt[0] = '\0'; - cw = snprintf(temp, SC_LOG_MAX_LOG_MSG_LEN - (temp - buffer), - "%s%s%u%s", substr, green, line, reset); + cw = snprintf(temp, SC_LOG_MAX_LOG_MSG_LEN - (temp - buffer), "%s%s%u%s", substr, + green, line, reset); if (cw < 0) return -1; temp += cw; @@ -563,8 +562,8 @@ static SCError SCLogMessageGetBuffer(SCTime_t tval, bool color, SCLogOPType type case SC_LOG_FMT_FUNCTION: temp_fmt[0] = '\0'; - cw = snprintf(temp, SC_LOG_MAX_LOG_MSG_LEN - (temp - buffer), - "%s%s%s%s", substr, green, function, reset); + cw = snprintf(temp, SC_LOG_MAX_LOG_MSG_LEN - (temp - buffer), "%s%s%s%s", substr, + green, function, reset); if (cw < 0) return -1; temp += cw; @@ -684,7 +683,7 @@ SCError SCLogMessage(const SCLogLevel log_level, const char *file, const unsigne op_iface_ctx->log_format ? op_iface_ctx->log_format : sc_log_config->log_format, log_level, file, line, function, module, message) == 0) { - SCLogPrintToStream((log_level == SC_LOG_ERROR)? stderr: stdout, buffer); + SCLogPrintToStream((log_level == SC_LOG_ERROR) ? stderr : stdout, buffer); } break; case SC_LOG_OP_IFACE_FILE: @@ -728,12 +727,9 @@ void SCLog(int x, const char *file, const char *func, const int line, const char const char *fmt, ...) { if (sc_log_global_log_level >= x && - (sc_log_fg_filters_present == 0 || - SCLogMatchFGFilterWL(file, func, line) == 1 || - SCLogMatchFGFilterBL(file, func, line) == 1) && - (sc_log_fd_filters_present == 0 || - SCLogMatchFDFilter(func) == 1)) - { + (sc_log_fg_filters_present == 0 || SCLogMatchFGFilterWL(file, func, line) == 1 || + SCLogMatchFGFilterBL(file, func, line) == 1) && + (sc_log_fd_filters_present == 0 || SCLogMatchFDFilter(func) == 1)) { char msg[SC_LOG_MAX_LOG_MSG_LEN]; va_list ap; va_start(ap, fmt); @@ -747,12 +743,9 @@ void SCLogErr(int x, const char *file, const char *func, const int line, const c const char *fmt, ...) { if (sc_log_global_log_level >= x && - (sc_log_fg_filters_present == 0 || - SCLogMatchFGFilterWL(file, func, line) == 1 || - SCLogMatchFGFilterBL(file, func, line) == 1) && - (sc_log_fd_filters_present == 0 || - SCLogMatchFDFilter(func) == 1)) - { + (sc_log_fg_filters_present == 0 || SCLogMatchFGFilterWL(file, func, line) == 1 || + SCLogMatchFGFilterBL(file, func, line) == 1) && + (sc_log_fd_filters_present == 0 || SCLogMatchFDFilter(func) == 1)) { char msg[SC_LOG_MAX_LOG_MSG_LEN]; va_list ap; va_start(ap, fmt); @@ -791,8 +784,7 @@ SCLogOPBuffer *SCLogAllocLogOPBuffer(void) { SCLogOPBuffer *buffer = NULL; - if ( (buffer = SCMalloc(sc_log_config->op_ifaces_cnt * - sizeof(SCLogOPBuffer))) == NULL) { + if ((buffer = SCMalloc(sc_log_config->op_ifaces_cnt * sizeof(SCLogOPBuffer))) == NULL) { FatalError("Fatal error encountered in SCLogAllocLogOPBuffer. Exiting..."); } @@ -850,7 +842,7 @@ static inline SCLogOPIfaceCtx *SCLogInitFileOPIface(const char *file, uint32_t u iface_ctx->iface = SC_LOG_OP_IFACE_FILE; iface_ctx->type = type; - if ( (iface_ctx->file_d = fopen(file, "a")) == NULL) { + if ((iface_ctx->file_d = fopen(file, "a")) == NULL) { SCLogWarning("error opening file %s: %s", file, strerror(errno)); goto error; } @@ -906,8 +898,8 @@ static inline SCLogOPIfaceCtx *SCLogInitFileOPIface(const char *file, uint32_t u * \retval iface_ctx Pointer to the console output interface context created * \initonly */ -static inline SCLogOPIfaceCtx *SCLogInitConsoleOPIface(const char *log_format, - SCLogLevel log_level, SCLogOPType type) +static inline SCLogOPIfaceCtx *SCLogInitConsoleOPIface( + const char *log_format, SCLogLevel log_level, SCLogOPType type) { SCLogOPIfaceCtx *iface_ctx = SCLogAllocLogOPIfaceCtx(); @@ -929,8 +921,7 @@ static inline SCLogOPIfaceCtx *SCLogInitConsoleOPIface(const char *log_format, tmp_log_format = s; } - if (tmp_log_format != NULL && - (iface_ctx->log_format = SCStrdup(tmp_log_format)) == NULL) { + if (tmp_log_format != NULL && (iface_ctx->log_format = SCStrdup(tmp_log_format)) == NULL) { printf("Error allocating memory\n"); exit(EXIT_FAILURE); } @@ -969,14 +960,12 @@ static inline SCLogOPIfaceCtx *SCLogInitConsoleOPIface(const char *log_format, * * \retval iface_ctx Pointer to the syslog output interface context created */ -static inline SCLogOPIfaceCtx *SCLogInitSyslogOPIface(int facility, - const char *log_format, - SCLogLevel log_level, - SCLogOPType type) +static inline SCLogOPIfaceCtx *SCLogInitSyslogOPIface( + int facility, const char *log_format, SCLogLevel log_level, SCLogOPType type) { SCLogOPIfaceCtx *iface_ctx = SCLogAllocLogOPIfaceCtx(); - if ( iface_ctx == NULL) { + if (iface_ctx == NULL) { FatalError("Fatal error encountered in SCLogInitSyslogOPIface. Exiting..."); } @@ -987,8 +976,7 @@ static inline SCLogOPIfaceCtx *SCLogInitSyslogOPIface(int facility, facility = SC_LOG_DEF_SYSLOG_FACILITY; iface_ctx->facility = facility; - if (log_format != NULL && - (iface_ctx->log_format = SCStrdup(log_format)) == NULL) { + if (log_format != NULL && (iface_ctx->log_format = SCStrdup(log_format)) == NULL) { printf("Error allocating memory\n"); exit(EXIT_FAILURE); } @@ -1064,7 +1052,7 @@ static inline void SCLogSetLogLevel(SCLogInitData *sc_lid, SCLogConfig *sc_lc) if (sc_lid != NULL) { printf("Warning: Invalid/No global_log_level assigned by user. Falling " "back on the default_log_level \"%s\"\n", - SCMapEnumValueToName(sc_lc->log_level, sc_log_level_map)); + SCMapEnumValueToName(sc_lc->log_level, sc_log_level_map)); } #endif } @@ -1120,8 +1108,8 @@ static inline void SCLogSetLogFormat(SCLogInitData *sc_lid, SCLogConfig *sc_lc) if (sc_lid != NULL) { printf("Warning: Invalid/No global_log_format supplied by user or format " "length exceeded limit of \"%d\" characters. Falling back on " - "default log_format \"%s\"\n", SC_LOG_MAX_LOG_FORMAT_LEN, - format); + "default log_format \"%s\"\n", + SC_LOG_MAX_LOG_FORMAT_LEN, format); } #endif } @@ -1156,29 +1144,28 @@ static inline void SCLogSetOPIface(SCLogInitData *sc_lid, SCLogConfig *sc_lc) if (s != NULL) { op_iface = SCMapEnumNameToValue(s, sc_log_op_iface_map); - if(op_iface < 0 || op_iface >= SC_LOG_OP_IFACE_MAX) { + if (op_iface < 0 || op_iface >= SC_LOG_OP_IFACE_MAX) { op_iface = SC_LOG_DEF_LOG_OP_IFACE; #ifndef UNITTESTS printf("Warning: Invalid output interface supplied by user. " "Falling back on default_output_interface \"%s\"\n", - SCMapEnumValueToName(op_iface, sc_log_op_iface_map)); + SCMapEnumValueToName(op_iface, sc_log_op_iface_map)); #endif } - } - else { + } else { op_iface = SC_LOG_DEF_LOG_OP_IFACE; #ifndef UNITTESTS if (sc_lid != NULL) { printf("Warning: Output_interface not supplied by user. Falling " "back on default_output_interface \"%s\"\n", - SCMapEnumValueToName(op_iface, sc_log_op_iface_map)); + SCMapEnumValueToName(op_iface, sc_log_op_iface_map)); } #endif } switch (op_iface) { case SC_LOG_OP_IFACE_CONSOLE: - op_ifaces_ctx = SCLogInitConsoleOPIface(NULL, SC_LOG_LEVEL_MAX,0); + op_ifaces_ctx = SCLogInitConsoleOPIface(NULL, SC_LOG_LEVEL_MAX, 0); break; case SC_LOG_OP_IFACE_FILE: s = getenv(SC_LOG_ENV_LOG_FILE); @@ -1197,7 +1184,8 @@ static inline void SCLogSetOPIface(SCLogInitData *sc_lid, SCLogConfig *sc_lc) if (s == NULL) s = SC_LOG_DEF_SYSLOG_FACILITY_STR; - op_ifaces_ctx = SCLogInitSyslogOPIface(SCMapEnumNameToValue(s, SCSyslogGetFacilityMap()), NULL, -1,0); + op_ifaces_ctx = SCLogInitSyslogOPIface( + SCMapEnumNameToValue(s, SCSyslogGetFacilityMap()), NULL, -1, 0); break; } sc_lc->op_ifaces = op_ifaces_ctx; @@ -1389,8 +1377,7 @@ static SCLogOPIfaceCtx *SCLogInitOPIfaceCtx( log_format, log_level, SC_LOG_OP_TYPE_REGULAR); default: #ifdef DEBUG - printf("Output Interface \"%s\" not supported by the logging module", - iface_name); + printf("Output Interface \"%s\" not supported by the logging module", iface_name); #endif return NULL; } @@ -1412,7 +1399,7 @@ void SCLogInitLogModule(SCLogInitData *sc_lid) * environment variables at the start of the engine */ SCLogDeInitLogModule(); -#if defined (OS_WIN32) +#if defined(OS_WIN32) if (SCMutexInit(&sc_log_stream_lock, NULL) != 0) { FatalError("Failed to initialize log mutex."); } @@ -1431,7 +1418,7 @@ void SCLogInitLogModule(SCLogInitData *sc_lid) sc_log_module_initialized = 1; sc_log_module_cleaned = 0; - //SCOutputPrint(sc_did->startup_message); + // SCOutputPrint(sc_did->startup_message); rs_log_set_level(sc_log_global_log_level); return; @@ -1466,15 +1453,13 @@ void SCLogLoadConfig(int daemon, int verbose, uint32_t userid, uint32_t groupid) /* Get default log level and format. */ const char *default_log_level_s = NULL; if (ConfGet("logging.default-log-level", &default_log_level_s) == 1) { - SCLogLevel default_log_level = - SCMapEnumNameToValue(default_log_level_s, sc_log_level_map); + SCLogLevel default_log_level = SCMapEnumNameToValue(default_log_level_s, sc_log_level_map); if (default_log_level == -1) { SCLogError("Invalid default log level: %s", default_log_level_s); exit(EXIT_FAILURE); } sc_lid->global_log_level = MAX(min_level, default_log_level); - } - else { + } else { sc_lid->global_log_level = MAX(min_level, SC_LOG_NOTICE); } @@ -1484,7 +1469,7 @@ void SCLogLoadConfig(int daemon, int verbose, uint32_t userid, uint32_t groupid) (void)ConfGet("logging.default-output-filter", &sc_lid->op_filter); ConfNode *seq_node, *output; - TAILQ_FOREACH(seq_node, &outputs->head, next) { + TAILQ_FOREACH (seq_node, &outputs->head, next) { SCLogLevel level = sc_lid->global_log_level; SCLogOPIfaceCtx *op_iface_ctx = NULL; const char *format; @@ -1526,8 +1511,7 @@ void SCLogLoadConfig(int daemon, int verbose, uint32_t userid, uint32_t groupid) if (strcmp(output->name, "console") == 0) { op_iface_ctx = SCLogInitConsoleOPIface(format, level, type); - } - else if (strcmp(output->name, "file") == 0) { + } else if (strcmp(output->name, "file") == 0) { if (format == NULL) { format = SC_LOG_DEF_FILE_FORMAT; } @@ -1547,11 +1531,9 @@ void SCLogLoadConfig(int daemon, int verbose, uint32_t userid, uint32_t groupid) have_logging = 1; op_iface_ctx = SCLogInitFileOPIface(path, userid, groupid, format, level, type); SCFree(path); - } - else if (strcmp(output->name, "syslog") == 0) { + } else if (strcmp(output->name, "syslog") == 0) { int facility = SC_LOG_DEF_SYSLOG_FACILITY; - const char *facility_s = ConfNodeLookupChildValue(output, - "facility"); + const char *facility_s = ConfNodeLookupChildValue(output, "facility"); if (facility_s != NULL) { facility = SCMapEnumNameToValue(facility_s, SCSyslogGetFacilityMap()); if (facility == -1) { @@ -1565,8 +1547,7 @@ void SCLogLoadConfig(int daemon, int verbose, uint32_t userid, uint32_t groupid) SCLogDebug("Initializing syslog logging with format \"%s\"", format); have_logging = 1; op_iface_ctx = SCLogInitSyslogOPIface(facility, format, level, type); - } - else { + } else { SCLogWarning("invalid logging method: %s, ignoring", output->name); } if (op_iface_ctx != NULL) { @@ -1629,7 +1610,7 @@ void SCLogDeInitLogModule(void) /* de-init the FG filters */ SCLogReleaseFGFilters(); -#if defined (OS_WIN32) +#if defined(OS_WIN32) SCMutexDestroy(&sc_log_stream_lock); #endif /* OS_WIN32 */ @@ -1661,7 +1642,7 @@ static int SCLogTestInit01(void) FAIL_IF_NOT(SC_LOG_DEF_LOG_LEVEL == sc_log_config->log_level); FAIL_IF_NOT(sc_log_config->op_ifaces != NULL && - SC_LOG_DEF_LOG_OP_IFACE == sc_log_config->op_ifaces->iface); + SC_LOG_DEF_LOG_OP_IFACE == sc_log_config->op_ifaces->iface); FAIL_IF_NOT(sc_log_config->log_format != NULL && strcmp(SCLogGetDefaultLogFormat(sc_log_config->log_level), sc_log_config->log_format) == 0); @@ -1676,9 +1657,8 @@ static int SCLogTestInit01(void) FAIL_IF_NOT(SC_LOG_DEBUG == sc_log_config->log_level); FAIL_IF_NOT(sc_log_config->op_ifaces != NULL && - SC_LOG_OP_IFACE_CONSOLE == sc_log_config->op_ifaces->iface); - FAIL_IF_NOT(sc_log_config->log_format != NULL && - !strcmp("%n- %l", sc_log_config->log_format)); + SC_LOG_OP_IFACE_CONSOLE == sc_log_config->op_ifaces->iface); + FAIL_IF_NOT(sc_log_config->log_format != NULL && !strcmp("%n- %l", sc_log_config->log_format)); unsetenv(SC_LOG_ENV_LOG_LEVEL); unsetenv(SC_LOG_ENV_LOG_OP_IFACE); @@ -1702,8 +1682,7 @@ static int SCLogTestInit02(void) sc_lid->op_filter = "boo"; sc_iface_ctx = SCLogInitOPIfaceCtx("file", "%m - %d", SC_LOG_WARNING, logfile); SCLogAppendOPIfaceCtx(sc_iface_ctx, sc_lid); - sc_iface_ctx = SCLogInitOPIfaceCtx("console", NULL, SC_LOG_ERROR, - NULL); + sc_iface_ctx = SCLogInitOPIfaceCtx("console", NULL, SC_LOG_ERROR, NULL); SCLogAppendOPIfaceCtx(sc_iface_ctx, sc_lid); SCLogInitLogModule(sc_lid); @@ -1712,19 +1691,16 @@ static int SCLogTestInit02(void) FAIL_IF_NOT(SC_LOG_DEBUG == sc_log_config->log_level); FAIL_IF_NOT(sc_log_config->op_ifaces != NULL && - SC_LOG_OP_IFACE_FILE == sc_log_config->op_ifaces->iface); - FAIL_IF_NOT(sc_log_config->op_ifaces != NULL && - sc_log_config->op_ifaces->next != NULL && - SC_LOG_OP_IFACE_CONSOLE == sc_log_config->op_ifaces->next->iface); + SC_LOG_OP_IFACE_FILE == sc_log_config->op_ifaces->iface); + FAIL_IF_NOT(sc_log_config->op_ifaces != NULL && sc_log_config->op_ifaces->next != NULL && + SC_LOG_OP_IFACE_CONSOLE == sc_log_config->op_ifaces->next->iface); FAIL_IF_NOT(sc_log_config->log_format != NULL && strcmp(SCLogGetDefaultLogFormat(sc_log_config->log_level), sc_log_config->log_format) == 0); - FAIL_IF_NOT(sc_log_config->op_ifaces != NULL && - sc_log_config->op_ifaces->log_format != NULL && - strcmp("%m - %d", sc_log_config->op_ifaces->log_format) == 0); - FAIL_IF_NOT(sc_log_config->op_ifaces != NULL && - sc_log_config->op_ifaces->next != NULL && - sc_log_config->op_ifaces->next->log_format == NULL); + FAIL_IF_NOT(sc_log_config->op_ifaces != NULL && sc_log_config->op_ifaces->log_format != NULL && + strcmp("%m - %d", sc_log_config->op_ifaces->log_format) == 0); + FAIL_IF_NOT(sc_log_config->op_ifaces != NULL && sc_log_config->op_ifaces->next != NULL && + sc_log_config->op_ifaces->next->log_format == NULL); SCLogFreeLogInitData(sc_lid); SCLogDeInitLogModule(); @@ -1742,15 +1718,12 @@ static int SCLogTestInit02(void) FAIL_IF_NOT(SC_LOG_DEBUG == sc_log_config->log_level); FAIL_IF_NOT(sc_log_config->op_ifaces != NULL && - SC_LOG_OP_IFACE_CONSOLE == sc_log_config->op_ifaces->iface); - FAIL_IF_NOT(sc_log_config->op_ifaces != NULL && - sc_log_config->op_ifaces->next == NULL); - FAIL_IF_NOT(sc_log_config->log_format != NULL && - strcmp("kaboo", sc_log_config->log_format) == 0); - FAIL_IF_NOT(sc_log_config->op_ifaces != NULL && - sc_log_config->op_ifaces->log_format == NULL); - FAIL_IF_NOT(sc_log_config->op_ifaces != NULL && - sc_log_config->op_ifaces->next == NULL); + SC_LOG_OP_IFACE_CONSOLE == sc_log_config->op_ifaces->iface); + FAIL_IF_NOT(sc_log_config->op_ifaces != NULL && sc_log_config->op_ifaces->next == NULL); + FAIL_IF_NOT( + sc_log_config->log_format != NULL && strcmp("kaboo", sc_log_config->log_format) == 0); + FAIL_IF_NOT(sc_log_config->op_ifaces != NULL && sc_log_config->op_ifaces->log_format == NULL); + FAIL_IF_NOT(sc_log_config->op_ifaces != NULL && sc_log_config->op_ifaces->next == NULL); SCLogFreeLogInitData(sc_lid); SCLogDeInitLogModule(); @@ -1831,5 +1804,5 @@ void SCLogRegisterTests(void) #endif /* UNITTESTS */ - return; + return; } diff --git a/src/util-debug.h b/src/util-debug.h index 296cf896519c..31facd9dab4a 100644 --- a/src/util-debug.h +++ b/src/util-debug.h @@ -33,17 +33,17 @@ /** * \brief ENV vars that can be used to set the properties for the logging module */ -#define SC_LOG_ENV_LOG_LEVEL "SC_LOG_LEVEL" -#define SC_LOG_ENV_LOG_OP_IFACE "SC_LOG_OP_IFACE" -#define SC_LOG_ENV_LOG_FILE "SC_LOG_FILE" -#define SC_LOG_ENV_LOG_FACILITY "SC_LOG_FACILITY" -#define SC_LOG_ENV_LOG_FORMAT "SC_LOG_FORMAT" -#define SC_LOG_ENV_LOG_OP_FILTER "SC_LOG_OP_FILTER" +#define SC_LOG_ENV_LOG_LEVEL "SC_LOG_LEVEL" +#define SC_LOG_ENV_LOG_OP_IFACE "SC_LOG_OP_IFACE" +#define SC_LOG_ENV_LOG_FILE "SC_LOG_FILE" +#define SC_LOG_ENV_LOG_FACILITY "SC_LOG_FACILITY" +#define SC_LOG_ENV_LOG_FORMAT "SC_LOG_FORMAT" +#define SC_LOG_ENV_LOG_OP_FILTER "SC_LOG_OP_FILTER" /** * \brief The various log levels * NOTE: when adding new level, don't forget to update SCLogMapLogLevelToSyslogLevel() - * or it may result in logging to syslog with LOG_EMERG priority. + * or it may result in logging to syslog with LOG_EMERG priority. */ typedef enum { SC_LOG_NOTSET = -1, @@ -97,7 +97,7 @@ typedef enum { /* The default syslog facility to be used */ #define SC_LOG_DEF_SYSLOG_FACILITY_STR "local0" -#define SC_LOG_DEF_SYSLOG_FACILITY LOG_LOCAL0 +#define SC_LOG_DEF_SYSLOG_FACILITY LOG_LOCAL0 /** * \brief Structure to be used when log_level override support would be provided @@ -121,7 +121,7 @@ typedef struct SCLogOPIfaceCtx_ { /* the output file to be used if the interface is SC_LOG_IFACE_FILE */ const char *file; /* the output file descriptor for the above file */ - FILE * file_d; + FILE *file_d; /* registered to be set on a file rotation signal */ int rotation_flag; @@ -184,22 +184,22 @@ typedef struct SCLogConfig_ { } SCLogConfig; /* The different log format specifiers supported by the API */ -#define SC_LOG_FMT_TIME 'z' /* Timestamp in RFC3339 like format */ -#define SC_LOG_FMT_TIME_LEGACY 't' /* Timestamp in legacy format */ -#define SC_LOG_FMT_PID 'p' /* PID */ -#define SC_LOG_FMT_TID 'i' /* Thread ID */ -#define SC_LOG_FMT_TM 'm' /* Thread module name */ -#define SC_LOG_FMT_LOG_LEVEL 'd' /* Log level */ -#define SC_LOG_FMT_LOG_SLEVEL 'D' /* Log level */ -#define SC_LOG_FMT_FILE_NAME 'f' /* File name */ -#define SC_LOG_FMT_LINE 'l' /* Line number */ -#define SC_LOG_FMT_FUNCTION 'n' /* Function */ -#define SC_LOG_FMT_SUBSYSTEM 'S' /* Subsystem name */ -#define SC_LOG_FMT_THREAD_NAME 'T' /* thread name */ -#define SC_LOG_FMT_MESSAGE 'M' /* log message body */ +#define SC_LOG_FMT_TIME 'z' /* Timestamp in RFC3339 like format */ +#define SC_LOG_FMT_TIME_LEGACY 't' /* Timestamp in legacy format */ +#define SC_LOG_FMT_PID 'p' /* PID */ +#define SC_LOG_FMT_TID 'i' /* Thread ID */ +#define SC_LOG_FMT_TM 'm' /* Thread module name */ +#define SC_LOG_FMT_LOG_LEVEL 'd' /* Log level */ +#define SC_LOG_FMT_LOG_SLEVEL 'D' /* Log level */ +#define SC_LOG_FMT_FILE_NAME 'f' /* File name */ +#define SC_LOG_FMT_LINE 'l' /* Line number */ +#define SC_LOG_FMT_FUNCTION 'n' /* Function */ +#define SC_LOG_FMT_SUBSYSTEM 'S' /* Subsystem name */ +#define SC_LOG_FMT_THREAD_NAME 'T' /* thread name */ +#define SC_LOG_FMT_MESSAGE 'M' /* log message body */ /* The log format prefix for the format specifiers */ -#define SC_LOG_FMT_PREFIX '%' +#define SC_LOG_FMT_PREFIX '%' /* Module and thread tagging */ /* The module name, usually the containing source-module name */ @@ -266,34 +266,35 @@ void SCLogErr(int x, const char *file, const char *func, const int line, const c /* Avoid the overhead of using the debugging subsystem, in production mode */ #ifndef DEBUG -#define SCLogDebug(...) do { } while (0) +#define SCLogDebug(...) \ + do { \ + } while (0) #define SCEnter(...) -#define SCReturn return +#define SCReturn return -#define SCReturnInt(x) return x +#define SCReturnInt(x) return x -#define SCReturnUInt(x) return x +#define SCReturnUInt(x) return x -#define SCReturnDbl(x) return x +#define SCReturnDbl(x) return x -#define SCReturnChar(x) return x +#define SCReturnChar(x) return x -#define SCReturnCharPtr(x) return x +#define SCReturnCharPtr(x) return x -#define SCReturnCT(x, type) return x +#define SCReturnCT(x, type) return x -#define SCReturnPtr(x, type) return x +#define SCReturnPtr(x, type) return x -#define SCReturnBool(x) return x +#define SCReturnBool(x) return x -#define SCReturnStruct(x) return x +#define SCReturnStruct(x) return x /* Please use it only for debugging purposes */ #else - /** * \brief Macro used to log DEBUG messages. Comes under the debugging subsystem, * and hence will be enabled only in the presence of the DEBUG macro. @@ -311,13 +312,12 @@ void SCLogErr(int x, const char *file, const char *func, const int line, const c * * \retval f An argument can be supplied, although it is not used */ -#define SCEnter(f) do { \ - if (sc_log_global_log_level >= SC_LOG_DEBUG &&\ - SCLogCheckFDFilterEntry(__FUNCTION__)) \ - { \ - SCLogDebug("Entering ... >>"); \ - } \ - } while(0) +#define SCEnter(f) \ + do { \ + if (sc_log_global_log_level >= SC_LOG_DEBUG && SCLogCheckFDFilterEntry(__FUNCTION__)) { \ + SCLogDebug("Entering ... >>"); \ + } \ + } while (0) /** * \brief Macro used to log debug messages on function exit. Comes under the @@ -327,13 +327,14 @@ void SCLogErr(int x, const char *file, const char *func, const int line, const c * function_exit macro should be used for functions that don't return * a value. */ -#define SCReturn do { \ - if (sc_log_global_log_level >= SC_LOG_DEBUG) { \ - SCLogDebug("Returning ... <<" ); \ - SCLogCheckFDFilterExit(__FUNCTION__); \ - } \ - return; \ - } while(0) +#define SCReturn \ + do { \ + if (sc_log_global_log_level >= SC_LOG_DEBUG) { \ + SCLogDebug("Returning ... <<"); \ + SCLogCheckFDFilterExit(__FUNCTION__); \ + } \ + return; \ + } while (0) /** * \brief Macro used to log debug messages on function exit. Comes under the @@ -345,13 +346,14 @@ void SCLogErr(int x, const char *file, const char *func, const int line, const c * * \retval x Variable of type 'integer' that has to be returned */ -#define SCReturnInt(x) do { \ - if (sc_log_global_log_level >= SC_LOG_DEBUG) { \ - SCLogDebug("Returning: %"PRIdMAX" ... <<", (intmax_t)x); \ - SCLogCheckFDFilterExit(__FUNCTION__); \ - } \ - return x; \ - } while(0) +#define SCReturnInt(x) \ + do { \ + if (sc_log_global_log_level >= SC_LOG_DEBUG) { \ + SCLogDebug("Returning: %" PRIdMAX " ... <<", (intmax_t)x); \ + SCLogCheckFDFilterExit(__FUNCTION__); \ + } \ + return x; \ + } while (0) /** * \brief Macro used to log debug messages on function exit. Comes under the @@ -363,13 +365,14 @@ void SCLogErr(int x, const char *file, const char *func, const int line, const c * * \retval x Variable of type 'unsigned integer' that has to be returned */ -#define SCReturnUInt(x) do { \ - if (sc_log_global_log_level >= SC_LOG_DEBUG) { \ - SCLogDebug("Returning: %"PRIuMAX" ... <<", (uintmax_t)x); \ - SCLogCheckFDFilterExit(__FUNCTION__); \ - } \ - return x; \ - } while(0) +#define SCReturnUInt(x) \ + do { \ + if (sc_log_global_log_level >= SC_LOG_DEBUG) { \ + SCLogDebug("Returning: %" PRIuMAX " ... <<", (uintmax_t)x); \ + SCLogCheckFDFilterExit(__FUNCTION__); \ + } \ + return x; \ + } while (0) /** * \brief Macro used to log debug messages on function exit. Comes under the @@ -381,13 +384,14 @@ void SCLogErr(int x, const char *file, const char *func, const int line, const c * * \retval x Variable of type 'float/double' that has to be returned */ -#define SCReturnDbl(x) do { \ - if (sc_log_global_log_level >= SC_LOG_DEBUG) { \ - SCLogDebug("Returning: %f ... <<", x); \ - SCLogCheckFDFilterExit(__FUNCTION__); \ - } \ - return x; \ - } while(0) +#define SCReturnDbl(x) \ + do { \ + if (sc_log_global_log_level >= SC_LOG_DEBUG) { \ + SCLogDebug("Returning: %f ... <<", x); \ + SCLogCheckFDFilterExit(__FUNCTION__); \ + } \ + return x; \ + } while (0) /** * \brief Macro used to log debug messages on function exit. Comes under the @@ -399,13 +403,14 @@ void SCLogErr(int x, const char *file, const char *func, const int line, const c * * \retval x Variable of type 'char' that has to be returned */ -#define SCReturnChar(x) do { \ - if (sc_log_global_log_level >= SC_LOG_DEBUG) { \ - SCLogDebug("Returning: %c ... <<", x); \ - SCLogCheckFDFilterExit(__FUNCTION__); \ - } \ - return x; \ - } while(0) +#define SCReturnChar(x) \ + do { \ + if (sc_log_global_log_level >= SC_LOG_DEBUG) { \ + SCLogDebug("Returning: %c ... <<", x); \ + SCLogCheckFDFilterExit(__FUNCTION__); \ + } \ + return x; \ + } while (0) /** * \brief Macro used to log debug messages on function exit. Comes under the @@ -417,16 +422,18 @@ void SCLogErr(int x, const char *file, const char *func, const int line, const c * * \retval x Pointer to the char string that has to be returned */ -#define SCReturnCharPtr(x) do { \ - if (sc_log_global_log_level >= SC_LOG_DEBUG) { \ - if ((x) != NULL) { \ - SCLogDebug("Returning: %s ... <<", x); \ - } else { \ - SCLogDebug("Returning: NULL ... <<"); \ - } SCLogCheckFDFilterExit(__FUNCTION__); \ - } \ - return x; \ - } while(0) +#define SCReturnCharPtr(x) \ + do { \ + if (sc_log_global_log_level >= SC_LOG_DEBUG) { \ + if ((x) != NULL) { \ + SCLogDebug("Returning: %s ... <<", x); \ + } else { \ + SCLogDebug("Returning: NULL ... <<"); \ + } \ + SCLogCheckFDFilterExit(__FUNCTION__); \ + } \ + return x; \ + } while (0) /** * \brief Macro used to log debug messages on function exit. Comes under the @@ -440,14 +447,16 @@ void SCLogErr(int x, const char *file, const char *func, const int line, const c * \retval type Pointer to a character string holding the name of the custom * type(the argument x) that has to be returned */ -#define SCReturnCT(x, type) do { \ - if (sc_log_global_log_level >= SC_LOG_DEBUG) { \ - SCLogDebug("Returning var of " \ - "type %s ... <<", type); \ - SCLogCheckFDFilterExit(__FUNCTION__); \ - } \ - return x; \ - } while(0) +#define SCReturnCT(x, type) \ + do { \ + if (sc_log_global_log_level >= SC_LOG_DEBUG) { \ + SCLogDebug("Returning var of " \ + "type %s ... <<", \ + type); \ + SCLogCheckFDFilterExit(__FUNCTION__); \ + } \ + return x; \ + } while (0) /** * \brief Macro used to log debug messages on function exit. Comes under the @@ -462,14 +471,16 @@ void SCLogErr(int x, const char *file, const char *func, const int line, const c * \retval type Pointer to a character string holding the name of the custom * type(the argument x) that has to be returned */ -#define SCReturnPtr(x, type) do { \ - if (sc_log_global_log_level >= SC_LOG_DEBUG) { \ - SCLogDebug("Returning pointer %p of " \ - "type %s ... <<", x, type); \ - SCLogCheckFDFilterExit(__FUNCTION__); \ - } \ - return x; \ - } while(0) +#define SCReturnPtr(x, type) \ + do { \ + if (sc_log_global_log_level >= SC_LOG_DEBUG) { \ + SCLogDebug("Returning pointer %p of " \ + "type %s ... <<", \ + x, type); \ + SCLogCheckFDFilterExit(__FUNCTION__); \ + } \ + return x; \ + } while (0) /** * \brief Macro used to log debug messages on function exit. Comes under the @@ -481,21 +492,23 @@ void SCLogErr(int x, const char *file, const char *func, const int line, const c * * \retval x Variable of type 'bool' that has to be returned */ -#define SCReturnBool(x) do { \ - if (sc_log_global_log_level >= SC_LOG_DEBUG) { \ - SCLogDebug("Returning: %s ... <<", x ? "true" : "false"); \ - SCLogCheckFDFilterExit(__FUNCTION__); \ - } \ - return x; \ - } while(0) - -#define SCReturnStruct(x) do { \ - if (sc_log_global_log_level >= SC_LOG_DEBUG) { \ - SCLogDebug("Returning: ... <<"); \ - SCLogCheckFDFilterExit(__FUNCTION__); \ - } \ - return x; \ - } while(0) +#define SCReturnBool(x) \ + do { \ + if (sc_log_global_log_level >= SC_LOG_DEBUG) { \ + SCLogDebug("Returning: %s ... <<", x ? "true" : "false"); \ + SCLogCheckFDFilterExit(__FUNCTION__); \ + } \ + return x; \ + } while (0) + +#define SCReturnStruct(x) \ + do { \ + if (sc_log_global_log_level >= SC_LOG_DEBUG) { \ + SCLogDebug("Returning: ... <<"); \ + SCLogCheckFDFilterExit(__FUNCTION__); \ + } \ + return x; \ + } while (0) #endif /* DEBUG */ diff --git a/src/util-decode-mime.c b/src/util-decode-mime.c index d9941cd986b9..62404f54193b 100644 --- a/src/util-decode-mime.c +++ b/src/util-decode-mime.c @@ -37,62 +37,54 @@ /* Character constants */ #ifndef CR -#define CR 13 -#define LF 10 +#define CR 13 +#define LF 10 #endif -#define CRLF "\r\n" -#define COLON 58 -#define DASH 45 -#define PRINTABLE_START 33 -#define PRINTABLE_END 126 -#define UC_START 65 -#define UC_END 90 -#define LC_START 97 -#define LC_END 122 -#define UC_LC_DIFF 32 -#define EOL_LEN 2 +#define CRLF "\r\n" +#define COLON 58 +#define DASH 45 +#define PRINTABLE_START 33 +#define PRINTABLE_END 126 +#define UC_START 65 +#define UC_END 90 +#define LC_START 97 +#define LC_END 122 +#define UC_LC_DIFF 32 +#define EOL_LEN 2 /* Base-64 constants */ -#define BASE64_STR "Base64" +#define BASE64_STR "Base64" /* Mime Constants */ -#define MAX_LINE_LEN 998 /* Def in RFC 2045, excluding CRLF sequence */ -#define MAX_ENC_LINE_LEN 76 /* Def in RFC 2045, excluding CRLF sequence */ -#define MAX_HEADER_NAME 75 /* 75 + ":" = 76 */ -#define MAX_HEADER_VALUE 2000 /* Default - arbitrary limit */ -#define BOUNDARY_BUF 256 -#define CTNT_TYPE_STR "content-type" -#define CTNT_DISP_STR "content-disposition" -#define CTNT_TRAN_STR "content-transfer-encoding" -#define MSG_ID_STR "message-id" -#define MSG_STR "message/" -#define MULTIPART_STR "multipart/" -#define QP_STR "quoted-printable" -#define TXT_STR "text/plain" -#define HTML_STR "text/html" +#define MAX_LINE_LEN 998 /* Def in RFC 2045, excluding CRLF sequence */ +#define MAX_ENC_LINE_LEN 76 /* Def in RFC 2045, excluding CRLF sequence */ +#define MAX_HEADER_NAME 75 /* 75 + ":" = 76 */ +#define MAX_HEADER_VALUE 2000 /* Default - arbitrary limit */ +#define BOUNDARY_BUF 256 +#define CTNT_TYPE_STR "content-type" +#define CTNT_DISP_STR "content-disposition" +#define CTNT_TRAN_STR "content-transfer-encoding" +#define MSG_ID_STR "message-id" +#define MSG_STR "message/" +#define MULTIPART_STR "multipart/" +#define QP_STR "quoted-printable" +#define TXT_STR "text/plain" +#define HTML_STR "text/html" /* Memory Usage Constants */ -#define STACK_FREE_NODES 10 +#define STACK_FREE_NODES 10 /* Other Constants */ -#define MAX_IP4_CHARS 15 -#define MAX_IP6_CHARS 39 +#define MAX_IP4_CHARS 15 +#define MAX_IP6_CHARS 39 /* Globally hold configuration data */ static MimeDecConfig mime_dec_config = { true, true, true, NULL, false, false, MAX_HEADER_VALUE }; /* Mime Parser String translation */ -static const char *StateFlags[] = { "NONE", - "HEADER_READY", - "HEADER_STARTED", - "HEADER_DONE", - "BODY_STARTED", - "BODY_DONE", - "BODY_END_BOUND", - "PARSE_DONE", - "PARSE_ERROR", - NULL }; +static const char *StateFlags[] = { "NONE", "HEADER_READY", "HEADER_STARTED", "HEADER_DONE", + "BODY_STARTED", "BODY_DONE", "BODY_END_BOUND", "PARSE_DONE", "PARSE_ERROR", NULL }; /* URL executable file extensions */ static const char *UrlExeExts[] = { ".exe", ".vbs", ".bin", ".cmd", ".bat", ".jar", ".js", ".ps", @@ -143,7 +135,7 @@ void MimeDecSetConfig(MimeDecConfig *config) * * \return config data structure */ -MimeDecConfig * MimeDecGetConfig(void) +MimeDecConfig *MimeDecGetConfig(void) { return &mime_dec_config; } @@ -160,7 +152,7 @@ static MimeDecEntity *findLastSibling(MimeDecEntity *node) { if (node == NULL) return NULL; - while(node->next != NULL) + while (node->next != NULL) node = node->next; return node; } @@ -173,13 +165,12 @@ static MimeDecEntity *findLastSibling(MimeDecEntity *node) * \return none * */ -void MimeDecFreeEntity (MimeDecEntity *entity) +void MimeDecFreeEntity(MimeDecEntity *entity) { if (entity == NULL) return; MimeDecEntity *lastSibling = findLastSibling(entity); - while (entity != NULL) - { + while (entity != NULL) { /* move child to next to transform the tree into a list */ if (entity->child != NULL) { lastSibling->next = entity->child; @@ -264,7 +255,7 @@ void MimeDecFreeUrl(MimeDecUrl *url) * \return The field object, or NULL if the operation fails * */ -MimeDecField * MimeDecAddField(MimeDecEntity *entity) +MimeDecField *MimeDecAddField(MimeDecEntity *entity) { MimeDecField *node = SCCalloc(1, sizeof(MimeDecField)); if (unlikely(node == NULL)) { @@ -284,7 +275,6 @@ MimeDecField * MimeDecAddField(MimeDecEntity *entity) return node; } - /** * \brief Searches for header fields with the specified name * @@ -294,7 +284,8 @@ MimeDecField * MimeDecAddField(MimeDecEntity *entity) * \return number of items found * */ -int MimeDecFindFieldsForEach(const MimeDecEntity *entity, const char *name, int (*DataCallback)(const uint8_t *val, const size_t, void *data), void *data) +int MimeDecFindFieldsForEach(const MimeDecEntity *entity, const char *name, + int (*DataCallback)(const uint8_t *val, const size_t, void *data), void *data) { MimeDecField *curr = entity->field_list; int found = 0; @@ -322,7 +313,8 @@ int MimeDecFindFieldsForEach(const MimeDecEntity *entity, const char *name, int * \return The field object, or NULL if not found * */ -MimeDecField * MimeDecFindField(const MimeDecEntity *entity, const char *name) { +MimeDecField *MimeDecFindField(const MimeDecEntity *entity, const char *name) +{ MimeDecField *curr = entity->field_list; while (curr != NULL) { @@ -348,7 +340,8 @@ MimeDecField * MimeDecFindField(const MimeDecEntity *entity, const char *name) { * \return URL entry or NULL if the operation fails * */ -static MimeDecUrl * MimeDecAddUrl(MimeDecEntity *entity, uint8_t *url, uint32_t url_len, uint8_t flags) +static MimeDecUrl *MimeDecAddUrl( + MimeDecEntity *entity, uint8_t *url, uint32_t url_len, uint8_t flags) { MimeDecUrl *node = SCCalloc(1, sizeof(MimeDecUrl)); if (unlikely(node == NULL)) { @@ -380,7 +373,7 @@ static MimeDecUrl * MimeDecAddUrl(MimeDecEntity *entity, uint8_t *url, uint32_t * \return The child entity, or NULL if the operation fails * */ -MimeDecEntity * MimeDecAddEntity(MimeDecEntity *parent) +MimeDecEntity *MimeDecAddEntity(MimeDecEntity *parent) { MimeDecEntity *node = SCCalloc(1, sizeof(MimeDecEntity)); if (unlikely(node == NULL)) { @@ -456,7 +449,7 @@ static MimeDecField *MimeDecFillField( * * \return pointer to a new node, otherwise NULL if it fails */ -static MimeDecStackNode * PushStack(MimeDecStack *stack) +static MimeDecStackNode *PushStack(MimeDecStack *stack) { /* Attempt to pull from free nodes list */ MimeDecStackNode *node = stack->free_nodes; @@ -487,7 +480,7 @@ static MimeDecStackNode * PushStack(MimeDecStack *stack) * * \return pointer to the next node, otherwise NULL if no nodes remain */ -static MimeDecStackNode * PopStack(MimeDecStack *stack) +static MimeDecStackNode *PopStack(MimeDecStack *stack) { /* Move stack pointer to next item */ MimeDecStackNode *curr = stack->top; @@ -556,7 +549,7 @@ static void FreeMimeDecStack(MimeDecStack *stack) * * \return pointer to a new node, otherwise NULL if it fails */ -static DataValue * AddDataValue(DataValue *dv) +static DataValue *AddDataValue(DataValue *dv) { DataValue *curr, *node = SCCalloc(1, sizeof(DataValue)); if (unlikely(node == NULL)) { @@ -662,8 +655,7 @@ static inline uint8_t *FindBuffer( * * \return Pointer to line */ -static uint8_t * GetLine(uint8_t *buf, uint32_t blen, uint8_t **remainPtr, - uint32_t *tokLen) +static uint8_t *GetLine(uint8_t *buf, uint32_t blen, uint8_t **remainPtr, uint32_t *tokLen) { uint32_t i; uint8_t *tok; @@ -687,8 +679,7 @@ static uint8_t * GetLine(uint8_t *buf, uint32_t blen, uint8_t **remainPtr, /* Add another if we find either CRLF or LFCR */ *remainPtr += (i + 1); - if ((i + 1 < blen) && buf[i] != buf[i + 1] && - (buf[i + 1] == CR || buf[i + 1] == LF)) { + if ((i + 1 < blen) && buf[i] != buf[i + 1] && (buf[i + 1] == CR || buf[i + 1] == LF)) { (*remainPtr)++; } break; @@ -717,8 +708,8 @@ static uint8_t * GetLine(uint8_t *buf, uint32_t blen, uint8_t **remainPtr, * * \return Pointer to token, or NULL if not found */ -static uint8_t * GetToken(uint8_t *buf, uint32_t blen, const char *delims, - uint8_t **remainPtr, uint32_t *tokenLen) +static uint8_t *GetToken( + uint8_t *buf, uint32_t blen, const char *delims, uint8_t **remainPtr, uint32_t *tokenLen) { uint32_t i, j, delimFound = 0; uint8_t *tok = NULL; @@ -794,7 +785,7 @@ static int StoreMimeHeader(MimeDecParseState *state) if (val != NULL) { if (state->hname == NULL) { SCLogDebug("Error: Invalid parser state - header value without" - " name"); + " name"); ret = MIME_DEC_ERR_PARSE; } else if (state->stack->top != NULL) { @@ -870,7 +861,7 @@ static int IsIpv4Host(const uint8_t *urlhost, uint32_t len) /* Cut off at '/' */ uint32_t i = 0; - for ( ; i < len && urlhost[i] != 0; i++) { + for (; i < len && urlhost[i] != 0; i++) { if (urlhost[i] == '/') { break; @@ -975,11 +966,10 @@ static MimeDecUrl *FindExistingUrl(MimeDecEntity *entity, uint8_t *url, uint32_t * * \return MIME_DEC_OK on success, otherwise < 0 on failure */ -static int FindUrlStrings(const uint8_t *line, uint32_t len, - MimeDecParseState *state) +static int FindUrlStrings(const uint8_t *line, uint32_t len, MimeDecParseState *state) { int ret = MIME_DEC_OK; - MimeDecEntity *entity = (MimeDecEntity *) state->stack->top->data; + MimeDecEntity *entity = (MimeDecEntity *)state->stack->top->data; MimeDecConfig *mdcfg = MimeDecGetConfig(); uint8_t *fptr, *remptr, *tok = NULL, *tempUrl, *urlHost; uint32_t tokLen = 0, i, tempUrlLen, urlHostLen; @@ -1090,23 +1080,21 @@ static int FindUrlStrings(const uint8_t *line, uint32_t len, * * \return MIME_DEC_OK on success, otherwise < 0 on failure */ -static int ProcessDecodedDataChunk(const uint8_t *chunk, uint32_t len, - MimeDecParseState *state) +static int ProcessDecodedDataChunk(const uint8_t *chunk, uint32_t len, MimeDecParseState *state) { int ret = MIME_DEC_OK; uint8_t *remainPtr, *tok; uint32_t tokLen; if ((state->stack != NULL) && (state->stack->top != NULL) && - (state->stack->top->data != NULL)) { + (state->stack->top->data != NULL)) { MimeDecConfig *mdcfg = MimeDecGetConfig(); if (mdcfg != NULL && mdcfg->extract_urls) { - MimeDecEntity *entity = (MimeDecEntity *) state->stack->top->data; + MimeDecEntity *entity = (MimeDecEntity *)state->stack->top->data; /* If plain text or html, then look for URLs */ - if (((entity->ctnt_flags & CTNT_IS_TEXT) || - (entity->ctnt_flags & CTNT_IS_MSG) || - (entity->ctnt_flags & CTNT_IS_HTML)) && - ((entity->ctnt_flags & CTNT_IS_ATTACHMENT) == 0)) { + if (((entity->ctnt_flags & CTNT_IS_TEXT) || (entity->ctnt_flags & CTNT_IS_MSG) || + (entity->ctnt_flags & CTNT_IS_HTML)) && + ((entity->ctnt_flags & CTNT_IS_ATTACHMENT) == 0)) { /* Parse each line one by one */ remainPtr = (uint8_t *)chunk; @@ -1132,7 +1120,7 @@ static int ProcessDecodedDataChunk(const uint8_t *chunk, uint32_t len, ret = state->DataChunkProcessorFunc(chunk, len, state); if (ret != MIME_DEC_OK) { SCLogDebug("Error: state->dataChunkProcessor() callback function" - " failed"); + " failed"); } } } else { @@ -1241,7 +1229,7 @@ static uint32_t ProcessBase64Remainder( ProcessDecodedDataChunk(state->data_chunk, state->data_chunk_len, state); if (ret != MIME_DEC_OK) { SCLogDebug("Error: ProcessDecodedDataChunk() function " - "failed"); + "failed"); } } } else if (code == BASE64_ECODE_ERR) { @@ -1289,8 +1277,7 @@ static inline MimeDecRetCode ProcessBase64BodyLineCopyRemainder( * * \return MIME_DEC_OK on success, otherwise < 0 on failure */ -static int ProcessBase64BodyLine(const uint8_t *buf, uint32_t len, - MimeDecParseState *state) +static int ProcessBase64BodyLine(const uint8_t *buf, uint32_t len, MimeDecParseState *state) { int ret = MIME_DEC_OK; uint32_t numDecoded, remaining = len, offset = 0; @@ -1412,7 +1399,6 @@ static int8_t DecodeQPChar(char h) } return res; - } /** @@ -1425,12 +1411,12 @@ static int8_t DecodeQPChar(char h) * * \return MIME_DEC_OK on success, otherwise < 0 on failure */ -static int ProcessQuotedPrintableBodyLine(const uint8_t *buf, uint32_t len, - MimeDecParseState *state) +static int ProcessQuotedPrintableBodyLine( + const uint8_t *buf, uint32_t len, MimeDecParseState *state) { int ret = MIME_DEC_OK; uint32_t remaining, offset; - MimeDecEntity *entity = (MimeDecEntity *) state->stack->top->data; + MimeDecEntity *entity = (MimeDecEntity *)state->stack->top->data; uint8_t c, h1, h2, val; int16_t res; @@ -1438,8 +1424,7 @@ static int ProcessQuotedPrintableBodyLine(const uint8_t *buf, uint32_t len, if (len > MAX_ENC_LINE_LEN) { state->stack->top->data->anomaly_flags |= ANOM_LONG_ENC_LINE; state->msg->anomaly_flags |= ANOM_LONG_ENC_LINE; - SCLogDebug("Error: Max encoded input line length exceeded %u > %u", - len, MAX_ENC_LINE_LEN); + SCLogDebug("Error: Max encoded input line length exceeded %u > %u", len, MAX_ENC_LINE_LEN); } if (len == 0) { memcpy(state->data_chunk + state->data_chunk_len, buf + len, @@ -1497,8 +1482,7 @@ static int ProcessQuotedPrintableBodyLine(const uint8_t *buf, uint32_t len, /* Add CRLF sequence if end of line, unless for partial lines */ if (remaining == 3 && state->current_line_delimiter_len > 0) { - memcpy(state->data_chunk + state->data_chunk_len, - CRLF, EOL_LEN); + memcpy(state->data_chunk + state->data_chunk_len, CRLF, EOL_LEN); state->data_chunk_len += EOL_LEN; } @@ -1519,11 +1503,10 @@ static int ProcessQuotedPrintableBodyLine(const uint8_t *buf, uint32_t len, if (DATA_CHUNK_SIZE - state->data_chunk_len < EOL_LEN + 1) { /* Invoke pre-processor and callback */ - ret = ProcessDecodedDataChunk(state->data_chunk, state->data_chunk_len, - state); + ret = ProcessDecodedDataChunk(state->data_chunk, state->data_chunk_len, state); if (ret != MIME_DEC_OK) { SCLogDebug("Error: ProcessDecodedDataChunk() function " - "failed"); + "failed"); } } } @@ -1541,31 +1524,29 @@ static int ProcessQuotedPrintableBodyLine(const uint8_t *buf, uint32_t len, * * \return MIME_DEC_OK on success, otherwise < 0 on failure */ -static int ProcessBodyLine(const uint8_t *buf, uint32_t len, - MimeDecParseState *state) +static int ProcessBodyLine(const uint8_t *buf, uint32_t len, MimeDecParseState *state) { int ret = MIME_DEC_OK; uint32_t remaining, offset, avail, tobuf; - MimeDecEntity *entity = (MimeDecEntity *) state->stack->top->data; + MimeDecEntity *entity = (MimeDecEntity *)state->stack->top->data; SCLogDebug("Processing body line"); /* Process base-64 content if enabled */ MimeDecConfig *mdcfg = MimeDecGetConfig(); - if (mdcfg != NULL && mdcfg->decode_base64 && - (entity->ctnt_flags & CTNT_IS_BASE64)) { + if (mdcfg != NULL && mdcfg->decode_base64 && (entity->ctnt_flags & CTNT_IS_BASE64)) { ret = ProcessBase64BodyLine(buf, len, state); if (ret != MIME_DEC_OK) { SCLogDebug("Error: ProcessBase64BodyLine() function failed"); } } else if (mdcfg != NULL && mdcfg->decode_quoted_printable && - (entity->ctnt_flags & CTNT_IS_QP)) { + (entity->ctnt_flags & CTNT_IS_QP)) { /* Process quoted-printable content if enabled */ ret = ProcessQuotedPrintableBodyLine(buf, len, state); if (ret != MIME_DEC_OK) { SCLogDebug("Error: ProcessQuotedPrintableBodyLine() function " - "failed"); + "failed"); } } else { /* Process non-decoded content */ @@ -1580,9 +1561,8 @@ static int ProcessBodyLine(const uint8_t *buf, uint32_t len, memcpy(state->data_chunk + state->data_chunk_len, buf + offset, tobuf); state->data_chunk_len += tobuf; - if ((int) (DATA_CHUNK_SIZE - state->data_chunk_len) < 0) { - SCLogDebug("Error: Invalid Chunk length: %u", - state->data_chunk_len); + if ((int)(DATA_CHUNK_SIZE - state->data_chunk_len) < 0) { + SCLogDebug("Error: Invalid Chunk length: %u", state->data_chunk_len); ret = MIME_DEC_ERR_PARSE; break; } @@ -1590,11 +1570,10 @@ static int ProcessBodyLine(const uint8_t *buf, uint32_t len, /* If buffer full, then invoke callback */ if (DATA_CHUNK_SIZE - state->data_chunk_len == 0) { /* Invoke pre-processor and callback */ - ret = ProcessDecodedDataChunk(state->data_chunk, - state->data_chunk_len, state); + ret = ProcessDecodedDataChunk(state->data_chunk, state->data_chunk_len, state); if (ret != MIME_DEC_OK) { SCLogDebug("Error: ProcessDecodedDataChunk() function " - "failed"); + "failed"); } } @@ -1625,7 +1604,7 @@ static int ProcessBodyLine(const uint8_t *buf, uint32_t len, * * \return Pointer to header name, or NULL if not found */ -static uint8_t * FindMimeHeaderStart(const uint8_t *buf, uint32_t blen, uint32_t *hlen) +static uint8_t *FindMimeHeaderStart(const uint8_t *buf, uint32_t blen, uint32_t *hlen) { uint32_t i, valid = 0; uint8_t *hname = NULL; @@ -1638,13 +1617,12 @@ static uint8_t * FindMimeHeaderStart(const uint8_t *buf, uint32_t blen, uint32_t for (i = 0; i < blen && buf[i] != 0; i++) { /* If ready for printable characters and found one, then increment */ - if (buf[i] != COLON && buf[i] >= PRINTABLE_START && - buf[i] <= PRINTABLE_END) { + if (buf[i] != COLON && buf[i] >= PRINTABLE_START && buf[i] <= PRINTABLE_END) { valid++; } else if (valid > 0 && buf[i] == COLON) { /* If ready for printable characters, found some, and found colon * delimiter, then a match is found */ - hname = (uint8_t *) buf + i - valid; + hname = (uint8_t *)buf + i - valid; *hlen = valid; break; } else { @@ -1666,8 +1644,7 @@ static uint8_t * FindMimeHeaderStart(const uint8_t *buf, uint32_t blen, uint32_t * * \return MIME_DEC_OK on success, otherwise < 0 on failure */ -static int FindMimeHeader(const uint8_t *buf, uint32_t blen, - MimeDecParseState *state) +static int FindMimeHeader(const uint8_t *buf, uint32_t blen, MimeDecParseState *state) { int ret = MIME_DEC_OK; uint8_t *hname, *hval = NULL; @@ -1686,8 +1663,7 @@ static int FindMimeHeader(const uint8_t *buf, uint32_t blen, if (hlen > MAX_HEADER_NAME) { state->stack->top->data->anomaly_flags |= ANOM_LONG_HEADER_NAME; state->msg->anomaly_flags |= ANOM_LONG_HEADER_NAME; - SCLogDebug("Error: Header name exceeds limit (%u > %u)", - hlen, MAX_HEADER_NAME); + SCLogDebug("Error: Header name exceeds limit (%u > %u)", hlen, MAX_HEADER_NAME); } /* Value starts after 'header:' (normalize spaces) */ @@ -1732,8 +1708,7 @@ static int FindMimeHeader(const uint8_t *buf, uint32_t blen, /* If max header value exceeded, flag it */ vlen = blen; if ((mdcfg != NULL) && (state->hvlen + vlen > mdcfg->header_value_depth)) { - SCLogDebug("Error: Header value of length (%u) is too long", - state->hvlen + vlen); + SCLogDebug("Error: Header value of length (%u) is too long", state->hvlen + vlen); vlen = mdcfg->header_value_depth - state->hvlen; state->stack->top->data->anomaly_flags |= ANOM_LONG_HEADER_VALUE; state->msg->anomaly_flags |= ANOM_LONG_HEADER_VALUE; @@ -1800,7 +1775,7 @@ static int FindMimeHeader(const uint8_t *buf, uint32_t blen, if (state->hvalue != NULL) { SCLogDebug("Error: Parser failed due to unexpected header " - "value"); + "value"); return MIME_DEC_ERR_DATA; } @@ -1808,8 +1783,7 @@ static int FindMimeHeader(const uint8_t *buf, uint32_t blen, /* If max header value exceeded, flag it */ vlen = blen - (hval - buf); if ((mdcfg != NULL) && (state->hvlen + vlen > mdcfg->header_value_depth)) { - SCLogDebug("Error: Header value of length (%u) is too long", - state->hvlen + vlen); + SCLogDebug("Error: Header value of length (%u) is too long", state->hvlen + vlen); vlen = mdcfg->header_value_depth - state->hvlen; state->stack->top->data->anomaly_flags |= ANOM_LONG_HEADER_VALUE; state->msg->anomaly_flags |= ANOM_LONG_HEADER_VALUE; @@ -1844,14 +1818,13 @@ static int FindMimeHeader(const uint8_t *buf, uint32_t blen, * * \return MIME_DEC_OK on success, otherwise < 0 on failure */ -static int ProcessMimeHeaders(const uint8_t *buf, uint32_t len, - MimeDecParseState *state) +static int ProcessMimeHeaders(const uint8_t *buf, uint32_t len, MimeDecParseState *state) { int ret = MIME_DEC_OK; MimeDecField *field; uint8_t *rptr = NULL; uint32_t blen = 0; - MimeDecEntity *entity = (MimeDecEntity *) state->stack->top->data; + MimeDecEntity *entity = (MimeDecEntity *)state->stack->top->data; uint8_t bptr[RS_MIME_MAX_TOKEN_LEN]; /* Look for mime header in current line */ @@ -1961,8 +1934,8 @@ static int ProcessMimeHeaders(const uint8_t *buf, uint32_t len, } /* Pull out short-hand content type */ - entity->ctnt_type = GetToken(field->value, field->value_len, " \r\n;", - &rptr, &entity->ctnt_type_len); + entity->ctnt_type = GetToken( + field->value, field->value_len, " \r\n;", &rptr, &entity->ctnt_type_len); if (entity->ctnt_type != NULL) { /* Check for encapsulated message */ if (FindBuffer(entity->ctnt_type, entity->ctnt_type_len, (const uint8_t *)MSG_STR, @@ -2038,8 +2011,7 @@ static int ProcessBodyComplete(MimeDecParseState *state) state->body_end = 1; if (state->bvr_len > 0) { - SCLogDebug("Found (%u) remaining base64 bytes not processed", - state->bvr_len); + SCLogDebug("Found (%u) remaining base64 bytes not processed", state->bvr_len); /* Process the remainder */ ret = ProcessBase64Remainder(NULL, 0, state, 1); @@ -2083,8 +2055,7 @@ static int ProcessMimeBoundary( uint8_t *rptr; MimeDecEntity *child; - SCLogDebug("PROCESSING BOUNDARY - START: %d", - state->state_flag); + SCLogDebug("PROCESSING BOUNDARY - START: %d", state->state_flag); /* If previous line was not an end boundary, then we process the body as * completed */ @@ -2103,7 +2074,7 @@ static int ProcessMimeBoundary( } /* Update remaining buffer */ - rptr = (uint8_t *) buf + bdef_len + 2; + rptr = (uint8_t *)buf + bdef_len + 2; /* If entity is encapsulated and current and parent didn't define the boundary, * then pop out */ @@ -2116,8 +2087,8 @@ static int ProcessMimeBoundary( if (state->stack->top->next->bdef_len == 0) { - SCLogDebug("POPPED ENCAPSULATED CHILD FROM STACK: %p=%p", - state->stack->top, state->stack->top->data); + SCLogDebug("POPPED ENCAPSULATED CHILD FROM STACK: %p=%p", state->stack->top, + state->stack->top->data); /* If end of boundary found, pop the child off the stack */ PopStack(state->stack); @@ -2130,8 +2101,8 @@ static int ProcessMimeBoundary( /* Now check for end of nested boundary */ if (len - (rptr - buf) > 1 && rptr[0] == DASH && rptr[1] == DASH) { - SCLogDebug("FOUND END BOUNDARY, POPPING: %p=%p", - state->stack->top, state->stack->top->data); + SCLogDebug( + "FOUND END BOUNDARY, POPPING: %p=%p", state->stack->top, state->stack->top->data); /* If end of boundary found, pop the child off the stack */ PopStack(state->stack); @@ -2143,8 +2114,8 @@ static int ProcessMimeBoundary( /* If current is an encapsulated message with a boundary definition, * then pop him as well */ if (state->stack->top->is_encap && state->stack->top->bdef_len != 0) { - SCLogDebug("FOUND END BOUNDARY AND ENCAP, POPPING: %p=%p", - state->stack->top, state->stack->top->data); + SCLogDebug("FOUND END BOUNDARY AND ENCAP, POPPING: %p=%p", state->stack->top, + state->stack->top->data); PopStack(state->stack); if (state->stack->top == NULL) { @@ -2175,8 +2146,8 @@ static int ProcessMimeBoundary( return MIME_DEC_ERR_DATA; } - SCLogDebug("SIBLING CREATED, POPPING PARENT: %p=%p", - state->stack->top, state->stack->top->data); + SCLogDebug("SIBLING CREATED, POPPING PARENT: %p=%p", state->stack->top, + state->stack->top->data); /* First pop current to get access to parent */ PopStack(state->stack); @@ -2212,8 +2183,7 @@ static int ProcessMimeBoundary( * * \return MIME_DEC_OK on success, otherwise < 0 on failure */ -static int ProcessMimeBody(const uint8_t *buf, uint32_t len, - MimeDecParseState *state) +static int ProcessMimeBody(const uint8_t *buf, uint32_t len, MimeDecParseState *state) { int ret = MIME_DEC_OK; uint8_t temp[BOUNDARY_BUF]; @@ -2289,7 +2259,7 @@ static int ProcessMimeBody(const uint8_t *buf, uint32_t len, ret = ProcessMimeBoundary(buf, len, node->bdef_len, state); if (ret != MIME_DEC_OK) { SCLogDebug("Error: ProcessMimeBoundary() function " - "failed"); + "failed"); return ret; } } else { @@ -2330,8 +2300,7 @@ const char *MimeDecParseStateGetStatus(MimeDecParseState *state) * * \return MIME_DEC_OK on success, otherwise < 0 on failure */ -static int ProcessMimeEntity(const uint8_t *buf, uint32_t len, - MimeDecParseState *state) +static int ProcessMimeEntity(const uint8_t *buf, uint32_t len, MimeDecParseState *state) { int ret = MIME_DEC_OK; @@ -2346,8 +2315,7 @@ static int ProcessMimeEntity(const uint8_t *buf, uint32_t len, if (len > MAX_LINE_LEN) { state->stack->top->data->anomaly_flags |= ANOM_LONG_LINE; state->msg->anomaly_flags |= ANOM_LONG_LINE; - SCLogDebug("Error: Max input line length exceeded %u > %u", len, - MAX_LINE_LEN); + SCLogDebug("Error: Max input line length exceeded %u > %u", len, MAX_LINE_LEN); } if (!g_disable_hashing) { @@ -2363,16 +2331,14 @@ static int ProcessMimeEntity(const uint8_t *buf, uint32_t len, } /* Looking for headers */ - if (state->state_flag == HEADER_READY || - state->state_flag == HEADER_STARTED) { + if (state->state_flag == HEADER_READY || state->state_flag == HEADER_STARTED) { SCLogDebug("Processing Headers"); /* Process message headers */ ret = ProcessMimeHeaders(buf, len, state); if (ret != MIME_DEC_OK) { - SCLogDebug("Error: ProcessMimeHeaders() function failed: %d", - ret); + SCLogDebug("Error: ProcessMimeHeaders() function failed: %d", ret); return ret; } } else { @@ -2381,8 +2347,7 @@ static int ProcessMimeEntity(const uint8_t *buf, uint32_t len, ret = ProcessMimeBody(buf, len, state); if (ret != MIME_DEC_OK) { - SCLogDebug("Error: ProcessMimeBody() function failed: %d", - ret); + SCLogDebug("Error: ProcessMimeBody() function failed: %d", ret); return ret; } } @@ -2401,9 +2366,8 @@ static int ProcessMimeEntity(const uint8_t *buf, uint32_t len, * * \return A pointer to the state object, or NULL if the operation fails */ -MimeDecParseState * MimeDecInitParser(void *data, - int (*DataChunkProcessorFunc)(const uint8_t *chunk, uint32_t len, - MimeDecParseState *state)) +MimeDecParseState *MimeDecInitParser(void *data, + int (*DataChunkProcessorFunc)(const uint8_t *chunk, uint32_t len, MimeDecParseState *state)) { MimeDecParseState *state; MimeDecEntity *mimeMsg; @@ -2455,8 +2419,7 @@ void MimeDecDeInitParser(MimeDecParseState *state) uint32_t cnt = 0; while (state->stack->top != NULL) { - SCLogDebug("Remaining on stack: [%p]=>[%p]", - state->stack->top, state->stack->top->data); + SCLogDebug("Remaining on stack: [%p]=>[%p]", state->stack->top, state->stack->top->data); PopStack(state->stack); cnt++; @@ -2465,7 +2428,8 @@ void MimeDecDeInitParser(MimeDecParseState *state) if (cnt > 1) { state->msg->anomaly_flags |= ANOM_MALFORMED_MSG; SCLogDebug("Warning: Stack is not empty upon completion of " - "processing (%u items remaining)", cnt); + "processing (%u items remaining)", + cnt); } SCFree(state->hname); @@ -2554,8 +2518,8 @@ int MimeDecParseComplete(MimeDecParseState *state) * * \return MIME_DEC_OK on success, otherwise < 0 on failure */ -int MimeDecParseLine(const uint8_t *line, const uint32_t len, - const uint8_t delim_len, MimeDecParseState *state) +int MimeDecParseLine( + const uint8_t *line, const uint32_t len, const uint8_t delim_len, MimeDecParseState *state) { int ret = MIME_DEC_OK; @@ -2588,9 +2552,8 @@ int MimeDecParseLine(const uint8_t *line, const uint32_t len, * * \return A pointer to the decoded MIME message, or NULL if the operation fails */ -MimeDecEntity * MimeDecParseFullMsg(const uint8_t *buf, uint32_t blen, void *data, - int (*dcpfunc)(const uint8_t *chunk, uint32_t len, - MimeDecParseState *state)) +MimeDecEntity *MimeDecParseFullMsg(const uint8_t *buf, uint32_t blen, void *data, + int (*dcpfunc)(const uint8_t *chunk, uint32_t len, MimeDecParseState *state)) { int ret = MIME_DEC_OK; uint8_t *remainPtr, *tok; @@ -2599,14 +2562,14 @@ MimeDecEntity * MimeDecParseFullMsg(const uint8_t *buf, uint32_t blen, void *dat MimeDecParseState *state = MimeDecInitParser(data, dcpfunc); if (state == NULL) { SCLogDebug("Error: MimeDecInitParser() function failed to create " - "state"); + "state"); return NULL; } MimeDecEntity *msg = state->msg; /* Parse each line one by one */ - remainPtr = (uint8_t *) buf; + remainPtr = (uint8_t *)buf; uint8_t *line = NULL; do { tok = GetLine(remainPtr, blen - (remainPtr - buf), &remainPtr, &tokLen); @@ -2623,8 +2586,7 @@ MimeDecEntity * MimeDecParseFullMsg(const uint8_t *buf, uint32_t blen, void *dat /* Parse the line */ ret = MimeDecParseLine(line, tokLen, state->current_line_delimiter_len, state); if (ret != MIME_DEC_OK) { - SCLogDebug("Error: MimeDecParseLine() function failed: %d", - ret); + SCLogDebug("Error: MimeDecParseLine() function failed: %d", ret); break; } } @@ -2655,10 +2617,9 @@ MimeDecEntity * MimeDecParseFullMsg(const uint8_t *buf, uint32_t blen, void *dat #ifdef UNITTESTS /* Helper body chunk callback function */ -static int TestDataChunkCallback(const uint8_t *chunk, uint32_t len, - MimeDecParseState *state) +static int TestDataChunkCallback(const uint8_t *chunk, uint32_t len, MimeDecParseState *state) { - uint32_t *line_count = (uint32_t *) state->data; + uint32_t *line_count = (uint32_t *)state->data; if (state->body_begin) { SCLogDebug("Body begin (len=%u)", len); @@ -2696,8 +2657,7 @@ static int MimeDecParseLineTest01(void) uint32_t line_count = 0; /* Init parser */ - MimeDecParseState *state = MimeDecInitParser(&line_count, - TestDataChunkCallback); + MimeDecParseState *state = MimeDecInitParser(&line_count, TestDataChunkCallback); const char *str = "From: Sender1\n"; FAIL_IF_NOT(MimeDecParseLine((uint8_t *)str, strlen(str) - 1, 1, state) == MIME_DEC_OK); @@ -2757,8 +2717,7 @@ static int MimeDecParseLineTest02(void) MimeDecGetConfig()->extract_urls_schemes = url_schemes; /* Init parser */ - MimeDecParseState *state = MimeDecInitParser(&line_count, - TestDataChunkCallback); + MimeDecParseState *state = MimeDecInitParser(&line_count, TestDataChunkCallback); const char *str = "From: Sender1\r\n"; FAIL_IF_NOT(MimeDecParseLine((uint8_t *)str, strlen(str) - 2, 2, state) == MIME_DEC_OK); @@ -3070,15 +3029,15 @@ static int MimeDecParseFullMsgTest01(void) uint32_t line_count = 0; char msg[] = "From: Sender1\r\n" - "To: Recipient1\r\n" - "Content-Type: text/plain\r\n" - "\r\n" - "Line 1\r\n" - "Line 2\r\n" - "Line 3\r\n"; - - MimeDecEntity *entity = MimeDecParseFullMsg((uint8_t *)msg, strlen(msg), &line_count, - TestDataChunkCallback); + "To: Recipient1\r\n" + "Content-Type: text/plain\r\n" + "\r\n" + "Line 1\r\n" + "Line 2\r\n" + "Line 3\r\n"; + + MimeDecEntity *entity = + MimeDecParseFullMsg((uint8_t *)msg, strlen(msg), &line_count, TestDataChunkCallback); if (entity == NULL) { SCLogInfo("Warning: Message failed to parse"); return 0; @@ -3087,8 +3046,8 @@ static int MimeDecParseFullMsgTest01(void) MimeDecFreeEntity(entity); if (expected_count != line_count) { - SCLogInfo("Warning: Line count is invalid: expected - %d actual - %d", - expected_count, line_count); + SCLogInfo("Warning: Line count is invalid: expected - %d actual - %d", expected_count, + line_count); return 0; } @@ -3102,16 +3061,16 @@ static int MimeDecParseFullMsgTest02(void) uint32_t line_count = 0; char msg[] = "From: Sender2\r\n" - "To: Recipient2\r\n" - "Subject: subject2\r\n" - "Content-Type: text/plain\r\n" - "\r\n" - "Line 1\r\n" - "Line 2\r\n" - "Line 3\r\n"; + "To: Recipient2\r\n" + "Subject: subject2\r\n" + "Content-Type: text/plain\r\n" + "\r\n" + "Line 1\r\n" + "Line 2\r\n" + "Line 3\r\n"; - MimeDecEntity *entity = MimeDecParseFullMsg((uint8_t *)msg, strlen(msg), &line_count, - TestDataChunkCallback); + MimeDecEntity *entity = + MimeDecParseFullMsg((uint8_t *)msg, strlen(msg), &line_count, TestDataChunkCallback); if (entity == NULL) { SCLogInfo("Warning: Message failed to parse"); @@ -3134,7 +3093,6 @@ static int MimeDecParseFullMsgTest02(void) return 0; } - MimeDecFreeEntity(entity); if (expected_count != line_count) { @@ -3152,9 +3110,9 @@ static int MimeBase64DecodeTest01(void) uint32_t consumed_bytes = 0, num_decoded = 0; const char *msg = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890@" - "#$%^&*()-=_+,./;'[]<>?:"; + "#$%^&*()-=_+,./;'[]<>?:"; const char *base64msg = "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNERUZHSElKS0xNTk9QU" - "VJTVFVWV1hZWjEyMzQ1Njc4OTBAIyQlXiYqKCktPV8rLC4vOydbXTw+Pzo="; + "VJTVFVWV1hZWjEyMzQ1Njc4OTBAIyQlXiYqKCktPV8rLC4vOydbXTw+Pzo="; uint8_t *dst = SCMalloc(strlen(msg) + 1); if (dst == NULL) @@ -3178,26 +3136,27 @@ static int MimeIsExeURLTest01(void) const char *url1 = "http://www.google.com/"; const char *url2 = "http://www.google.com/test.exe"; - if(IsExeUrl((const uint8_t *)url1, strlen(url1)) != 0){ + if (IsExeUrl((const uint8_t *)url1, strlen(url1)) != 0) { SCLogDebug("Debug: URL1 error"); goto end; } - if(IsExeUrl((const uint8_t *)url2, strlen(url2)) != 1){ + if (IsExeUrl((const uint8_t *)url2, strlen(url2)) != 1) { SCLogDebug("Debug: URL2 error"); goto end; } ret = 1; - end: +end: return ret; } -#define TEST(str, len, expect) { \ - SCLogDebug("str %s", (str)); \ - int r = IsIpv4Host((const uint8_t *)(str),(len)); \ - FAIL_IF_NOT(r == (expect)); \ -} +#define TEST(str, len, expect) \ + { \ + SCLogDebug("str %s", (str)); \ + int r = IsIpv4Host((const uint8_t *)(str), (len)); \ + FAIL_IF_NOT(r == (expect)); \ + } static int MimeIsIpv4HostTest01(void) { TEST("192.168.1.1", 11, 1); @@ -3213,11 +3172,12 @@ static int MimeIsIpv4HostTest01(void) } #undef TEST -#define TEST(str, len, expect) { \ - SCLogDebug("str %s", (str)); \ - int r = IsIpv6Host((const uint8_t *)(str),(len)); \ - FAIL_IF_NOT(r == (expect)); \ -} +#define TEST(str, len, expect) \ + { \ + SCLogDebug("str %s", (str)); \ + int r = IsIpv6Host((const uint8_t *)(str), (len)); \ + FAIL_IF_NOT(r == (expect)); \ + } static int MimeIsIpv6HostTest01(void) { TEST("0:0:0:0:0:0:0:0", 19, 1); @@ -3253,8 +3213,7 @@ static int MimeDecParseLongFilename01(void) MimeDecGetConfig()->extract_urls = true; /* Init parser */ - MimeDecParseState *state = MimeDecInitParser(&line_count, - TestDataChunkCallback); + MimeDecParseState *state = MimeDecInitParser(&line_count, TestDataChunkCallback); const char *str = "From: Sender1"; FAIL_IF_NOT(MIME_DEC_OK == MimeDecParseLine((uint8_t *)str, strlen(str), 1, state)); @@ -3518,8 +3477,7 @@ static int MimeDecParseLongFilename02(void) MimeDecGetConfig()->extract_urls = true; /* Init parser */ - MimeDecParseState *state = MimeDecInitParser(&line_count, - TestDataChunkCallback); + MimeDecParseState *state = MimeDecInitParser(&line_count, TestDataChunkCallback); const char *str = "From: Sender1"; FAIL_IF_NOT(MIME_DEC_OK == MimeDecParseLine((uint8_t *)str, strlen(str), 1, state)); diff --git a/src/util-decode-mime.h b/src/util-decode-mime.h index cc79d98a6eb0..d4bcbe99daaa 100644 --- a/src/util-decode-mime.h +++ b/src/util-decode-mime.h @@ -31,46 +31,47 @@ #include "util-file.h" /* Content Flags */ -#define CTNT_IS_MSG 1 -#define CTNT_IS_ENV 2 -#define CTNT_IS_ENCAP 4 -#define CTNT_IS_BODYPART 8 -#define CTNT_IS_MULTIPART 16 -#define CTNT_IS_ATTACHMENT 32 -#define CTNT_IS_BASE64 64 -#define CTNT_IS_QP 128 -#define CTNT_IS_TEXT 256 -#define CTNT_IS_HTML 512 +#define CTNT_IS_MSG 1 +#define CTNT_IS_ENV 2 +#define CTNT_IS_ENCAP 4 +#define CTNT_IS_BODYPART 8 +#define CTNT_IS_MULTIPART 16 +#define CTNT_IS_ATTACHMENT 32 +#define CTNT_IS_BASE64 64 +#define CTNT_IS_QP 128 +#define CTNT_IS_TEXT 256 +#define CTNT_IS_HTML 512 /* URL Flags */ -#define URL_IS_IP4 1 -#define URL_IS_IP6 2 -#define URL_IS_EXE 4 +#define URL_IS_IP4 1 +#define URL_IS_IP6 2 +#define URL_IS_EXE 4 /* Anomaly Flags */ -#define ANOM_INVALID_BASE64 1 /* invalid base64 chars */ -#define ANOM_INVALID_QP 2 /* invalid quoted-printable chars */ -#define ANOM_LONG_HEADER_NAME 4 /* header is abnormally long */ -#define ANOM_LONG_HEADER_VALUE 8 /* header value is abnormally long - * (includes multi-line) */ -#define ANOM_LONG_LINE 16 /* Lines that exceed 998 octets */ -#define ANOM_LONG_ENC_LINE 32 /* Lines that exceed 76 octets */ -#define ANOM_MALFORMED_MSG 64 /* Misc msg format errors found */ -#define ANOM_LONG_BOUNDARY 128 /* Boundary too long */ -#define ANOM_LONG_FILENAME 256 /* filename truncated */ +#define ANOM_INVALID_BASE64 1 /* invalid base64 chars */ +#define ANOM_INVALID_QP 2 /* invalid quoted-printable chars */ +#define ANOM_LONG_HEADER_NAME 4 /* header is abnormally long */ +#define ANOM_LONG_HEADER_VALUE \ + 8 /* header value is abnormally long \ + * (includes multi-line) */ +#define ANOM_LONG_LINE 16 /* Lines that exceed 998 octets */ +#define ANOM_LONG_ENC_LINE 32 /* Lines that exceed 76 octets */ +#define ANOM_MALFORMED_MSG 64 /* Misc msg format errors found */ +#define ANOM_LONG_BOUNDARY 128 /* Boundary too long */ +#define ANOM_LONG_FILENAME 256 /* filename truncated */ /* Publicly exposed size constants */ -#define DATA_CHUNK_SIZE 3072 /* Should be divisible by 3 */ +#define DATA_CHUNK_SIZE 3072 /* Should be divisible by 3 */ /* Mime Parser Constants */ -#define HEADER_READY 0x01 -#define HEADER_STARTED 0x02 -#define HEADER_DONE 0x03 -#define BODY_STARTED 0x04 -#define BODY_DONE 0x05 -#define BODY_END_BOUND 0x06 -#define PARSE_DONE 0x07 -#define PARSE_ERROR 0x08 +#define HEADER_READY 0x01 +#define HEADER_STARTED 0x02 +#define HEADER_DONE 0x03 +#define BODY_STARTED 0x04 +#define BODY_DONE 0x05 +#define BODY_END_BOUND 0x06 +#define PARSE_DONE 0x07 +#define PARSE_ERROR 0x08 /** * \brief Mime Decoder Error Codes @@ -97,19 +98,19 @@ typedef struct MimeDecConfig { extract urls */ bool log_url_scheme; /**< Log the scheme of extracted URLs */ bool body_md5; /**< Compute md5 sum of body */ - uint32_t header_value_depth; /**< Depth of which to store header values - (Default is 2000) */ + uint32_t header_value_depth; /**< Depth of which to store header values + (Default is 2000) */ } MimeDecConfig; /** * \brief This represents a header field name and associated value */ typedef struct MimeDecField { - uint8_t *name; /**< Name of the header field */ - uint32_t name_len; /**< Length of the name */ - uint32_t value_len; /**< Length of the value */ - uint8_t *value; /**< Value of the header field */ - struct MimeDecField *next; /**< Pointer to next field */ + uint8_t *name; /**< Name of the header field */ + uint32_t name_len; /**< Length of the name */ + uint32_t value_len; /**< Length of the value */ + uint8_t *value; /**< Value of the header field */ + struct MimeDecField *next; /**< Pointer to next field */ } MimeDecField; /** @@ -120,10 +121,10 @@ typedef struct MimeDecField { * pointing to an executable file (see url_flags to determine which). */ typedef struct MimeDecUrl { - uint8_t *url; /**< String representation of full or partial URL (lowercase) */ - uint32_t url_len; /**< Length of the URL string */ - uint32_t url_flags; /**< Flags indicating type of URL */ - struct MimeDecUrl *next; /**< Pointer to next URL */ + uint8_t *url; /**< String representation of full or partial URL (lowercase) */ + uint32_t url_len; /**< Length of the URL string */ + uint32_t url_flags; /**< Flags indicating type of URL */ + struct MimeDecUrl *next; /**< Pointer to next URL */ } MimeDecUrl; /** @@ -131,19 +132,19 @@ typedef struct MimeDecUrl { * child-sibling tree */ typedef struct MimeDecEntity { - MimeDecField *field_list; /**< Pointer to list of header fields */ - MimeDecUrl *url_list; /**< Pointer to list of URLs */ - uint32_t header_flags; /**< Flags indicating header characteristics */ - uint32_t ctnt_flags; /**< Flags indicating type of content */ - uint32_t anomaly_flags; /**< Flags indicating an anomaly in the message */ - uint32_t filename_len; /**< Length of file attachment name */ - uint8_t *filename; /**< Name of file attachment */ - uint8_t *ctnt_type; /**< Quick access pointer to short-hand content type field */ - uint32_t ctnt_type_len; /**< Length of content type field value */ - uint32_t msg_id_len; /**< Quick access pointer to message Id */ - uint8_t *msg_id; /**< Quick access pointer to message Id */ - struct MimeDecEntity *next; /**< Pointer to list of sibling entities */ - struct MimeDecEntity *child; /**< Pointer to list of child entities */ + MimeDecField *field_list; /**< Pointer to list of header fields */ + MimeDecUrl *url_list; /**< Pointer to list of URLs */ + uint32_t header_flags; /**< Flags indicating header characteristics */ + uint32_t ctnt_flags; /**< Flags indicating type of content */ + uint32_t anomaly_flags; /**< Flags indicating an anomaly in the message */ + uint32_t filename_len; /**< Length of file attachment name */ + uint8_t *filename; /**< Name of file attachment */ + uint8_t *ctnt_type; /**< Quick access pointer to short-hand content type field */ + uint32_t ctnt_type_len; /**< Length of content type field value */ + uint32_t msg_id_len; /**< Quick access pointer to message Id */ + uint8_t *msg_id; /**< Quick access pointer to message Id */ + struct MimeDecEntity *next; /**< Pointer to list of sibling entities */ + struct MimeDecEntity *child; /**< Pointer to list of child entities */ struct MimeDecEntity *last_child; /**< Pointer to tail of the list of child entities */ } MimeDecEntity; @@ -153,11 +154,11 @@ typedef struct MimeDecEntity { * */ typedef struct MimeDecStackNode { - MimeDecEntity *data; /**< Pointer to the entity data structure */ - uint8_t *bdef; /**< Copy of boundary definition for child entity */ - uint16_t bdef_len; /**< Boundary length for child entity */ - bool is_encap; /**< Flag indicating entity is encapsulated in message */ - struct MimeDecStackNode *next; /**< Pointer to next item on the stack */ + MimeDecEntity *data; /**< Pointer to the entity data structure */ + uint8_t *bdef; /**< Copy of boundary definition for child entity */ + uint16_t bdef_len; /**< Boundary length for child entity */ + bool is_encap; /**< Flag indicating entity is encapsulated in message */ + struct MimeDecStackNode *next; /**< Pointer to next item on the stack */ } MimeDecStackNode; /** @@ -165,9 +166,9 @@ typedef struct MimeDecStackNode { * */ typedef struct MimeDecStack { - MimeDecStackNode *top; /**< Pointer to the top of the stack */ - MimeDecStackNode *free_nodes; /**< Pointer to the list of free nodes */ - uint32_t free_nodes_cnt; /**< Count of free nodes in the list */ + MimeDecStackNode *top; /**< Pointer to the top of the stack */ + MimeDecStackNode *free_nodes; /**< Pointer to the list of free nodes */ + uint32_t free_nodes_cnt; /**< Count of free nodes in the list */ } MimeDecStack; /** @@ -175,9 +176,9 @@ typedef struct MimeDecStack { * */ typedef struct DataValue { - uint8_t *value; /**< Copy of data value */ - uint32_t value_len; /**< Length of data value */ - struct DataValue *next; /**< Pointer to next value in the list */ + uint8_t *value; /**< Copy of data value */ + uint32_t value_len; /**< Length of data value */ + struct DataValue *next; /**< Pointer to next value in the list */ } DataValue; /** @@ -185,32 +186,32 @@ typedef struct DataValue { * */ typedef struct MimeDecParseState { - MimeDecEntity *msg; /**< Pointer to the top-level message entity */ - MimeDecStack *stack; /**< Pointer to the top of the entity stack */ - uint8_t *hname; /**< Copy of the last known header name */ - uint32_t hlen; /**< Length of the last known header name */ - uint32_t hvlen; /**< Total length of value list */ - DataValue *hvalue; /**< Pointer to the incomplete header value list */ - uint8_t bvremain[B64_BLOCK]; /**< Remainder from base64-decoded line */ - uint8_t bvr_len; /**< Length of remainder from base64-decoded line */ - uint8_t data_chunk[DATA_CHUNK_SIZE]; /**< Buffer holding data chunk */ + MimeDecEntity *msg; /**< Pointer to the top-level message entity */ + MimeDecStack *stack; /**< Pointer to the top of the entity stack */ + uint8_t *hname; /**< Copy of the last known header name */ + uint32_t hlen; /**< Length of the last known header name */ + uint32_t hvlen; /**< Total length of value list */ + DataValue *hvalue; /**< Pointer to the incomplete header value list */ + uint8_t bvremain[B64_BLOCK]; /**< Remainder from base64-decoded line */ + uint8_t bvr_len; /**< Length of remainder from base64-decoded line */ + uint8_t data_chunk[DATA_CHUNK_SIZE]; /**< Buffer holding data chunk */ SCMd5 *md5_ctx; uint8_t md5[SC_MD5_LEN]; bool has_md5; - uint8_t state_flag; /**< Flag representing current state of parser */ - uint32_t data_chunk_len; /**< Length of data chunk */ - int found_child; /**< Flag indicating a child entity was found */ - int body_begin; /**< Currently at beginning of body */ - int body_end; /**< Currently at end of body */ + uint8_t state_flag; /**< Flag representing current state of parser */ + uint32_t data_chunk_len; /**< Length of data chunk */ + int found_child; /**< Flag indicating a child entity was found */ + int body_begin; /**< Currently at beginning of body */ + int body_end; /**< Currently at end of body */ uint8_t current_line_delimiter_len; /**< Length of line delimiter */ - void *data; /**< Pointer to data specific to the caller */ - int (*DataChunkProcessorFunc) (const uint8_t *chunk, uint32_t len, - struct MimeDecParseState *state); /**< Data chunk processing function callback */ + void *data; /**< Pointer to data specific to the caller */ + int (*DataChunkProcessorFunc)(const uint8_t *chunk, uint32_t len, + struct MimeDecParseState *state); /**< Data chunk processing function callback */ } MimeDecParseState; /* Config functions */ void MimeDecSetConfig(MimeDecConfig *config); -MimeDecConfig * MimeDecGetConfig(void); +MimeDecConfig *MimeDecGetConfig(void); /* Memory functions */ void MimeDecFreeEntity(MimeDecEntity *entity); @@ -218,23 +219,26 @@ void MimeDecFreeField(MimeDecField *field); void MimeDecFreeUrl(MimeDecUrl *url); /* List functions */ -MimeDecField * MimeDecAddField(MimeDecEntity *entity); -MimeDecField * MimeDecFindField(const MimeDecEntity *entity, const char *name); -int MimeDecFindFieldsForEach(const MimeDecEntity *entity, const char *name, int (*DataCallback)(const uint8_t *val, const size_t, void *data), void *data); -MimeDecEntity * MimeDecAddEntity(MimeDecEntity *parent); +MimeDecField *MimeDecAddField(MimeDecEntity *entity); +MimeDecField *MimeDecFindField(const MimeDecEntity *entity, const char *name); +int MimeDecFindFieldsForEach(const MimeDecEntity *entity, const char *name, + int (*DataCallback)(const uint8_t *val, const size_t, void *data), void *data); +MimeDecEntity *MimeDecAddEntity(MimeDecEntity *parent); /* Helper functions */ -//MimeDecField * MimeDecFillField(MimeDecEntity *entity, const char *name, +// MimeDecField * MimeDecFillField(MimeDecEntity *entity, const char *name, // uint32_t nlen, const char *value, uint32_t vlen, int copy_name_value); /* Parser functions */ -MimeDecParseState * MimeDecInitParser(void *data, int (*dcpfunc)(const uint8_t *chunk, - uint32_t len, MimeDecParseState *state)); +MimeDecParseState *MimeDecInitParser( + void *data, int (*dcpfunc)(const uint8_t *chunk, uint32_t len, MimeDecParseState *state)); void MimeDecDeInitParser(MimeDecParseState *state); int MimeDecParseComplete(MimeDecParseState *state); -int MimeDecParseLine(const uint8_t *line, const uint32_t len, const uint8_t delim_len, MimeDecParseState *state); -MimeDecEntity * MimeDecParseFullMsg(const uint8_t *buf, uint32_t blen, void *data, - int (*DataChunkProcessorFunc)(const uint8_t *chunk, uint32_t len, MimeDecParseState *state)); +int MimeDecParseLine( + const uint8_t *line, const uint32_t len, const uint8_t delim_len, MimeDecParseState *state); +MimeDecEntity *MimeDecParseFullMsg(const uint8_t *buf, uint32_t blen, void *data, + int (*DataChunkProcessorFunc)( + const uint8_t *chunk, uint32_t len, MimeDecParseState *state)); const char *MimeDecParseStateGetStatus(MimeDecParseState *state); /* Test functions */ diff --git a/src/util-detect.c b/src/util-detect.c index 1b68e520548b..cf73f2ac66f2 100644 --- a/src/util-detect.c +++ b/src/util-detect.c @@ -55,9 +55,8 @@ SigString *SigStringAlloc(void) * * \retval 1 on success 0 on failure */ -static int SigStringAddSig(SigString *sig, const char *sig_file, - const char *sig_str, const char *sig_error, - int line) +static int SigStringAddSig( + SigString *sig, const char *sig_file, const char *sig_str, const char *sig_error, int line) { if (sig_file == NULL || sig_str == NULL) { return 0; @@ -101,8 +100,8 @@ static int SigStringAddSig(SigString *sig, const char *sig_file, * * \retval 1 on success 0 on failure */ -int SigStringAppend(SigFileLoaderStat *sig_stats, const char *sig_file, - const char *sig_str, const char *sig_error, int line) +int SigStringAppend(SigFileLoaderStat *sig_stats, const char *sig_file, const char *sig_str, + const char *sig_error, int line) { SigString *item = SigStringAlloc(); if (item == NULL) { diff --git a/src/util-detect.h b/src/util-detect.h index b483d507fbbf..611d3ffce0f3 100644 --- a/src/util-detect.h +++ b/src/util-detect.h @@ -25,4 +25,4 @@ SigString *SigStringAlloc(void); int SigStringAppend(SigFileLoaderStat *sigs_stats, const char *sig_file, const char *sig_str, - const char *sig_error, int line); + const char *sig_error, int line); diff --git a/src/util-device.c b/src/util-device.c index b624cf07342b..507f9e33de22 100644 --- a/src/util-device.c +++ b/src/util-device.c @@ -38,8 +38,7 @@ static LiveDevStorageId g_bypass_storage_id = { .id = -1 }; */ /** private device list */ -static TAILQ_HEAD(, LiveDevice_) live_devices = - TAILQ_HEAD_INITIALIZER(live_devices); +static TAILQ_HEAD(, LiveDevice_) live_devices = TAILQ_HEAD_INITIALIZER(live_devices); /** List of the name of devices * @@ -47,8 +46,7 @@ static TAILQ_HEAD(, LiveDevice_) live_devices = * before the parsing we need to wait and use this list * to create later the LiveDevice via LiveDeviceFinalize() */ -static TAILQ_HEAD(, LiveDeviceName_) pre_live_devices = - TAILQ_HEAD_INITIALIZER(pre_live_devices); +static TAILQ_HEAD(, LiveDeviceName_) pre_live_devices = TAILQ_HEAD_INITIALIZER(pre_live_devices); typedef struct BypassInfo_ { SC_ATOMIC_DECLARE(uint64_t, ipv4_hash_count); @@ -62,9 +60,7 @@ typedef struct BypassInfo_ { /** if set to 0 when we don't have real devices */ static int live_devices_stats = 1; - -static int LiveSafeDeviceName(const char *devname, - char *newdevname, size_t destlen); +static int LiveSafeDeviceName(const char *devname, char *newdevname, size_t destlen); static int g_live_devices_disable_offloading = 1; @@ -166,7 +162,7 @@ int LiveGetDeviceCount(void) int i = 0; LiveDevice *pd; - TAILQ_FOREACH(pd, &live_devices, next) { + TAILQ_FOREACH (pd, &live_devices, next) { i++; } @@ -186,7 +182,7 @@ const char *LiveGetDeviceName(int number) int i = 0; LiveDevice *pd; - TAILQ_FOREACH(pd, &live_devices, next) { + TAILQ_FOREACH (pd, &live_devices, next) { if (i == number) { return pd->dev; } @@ -224,7 +220,7 @@ static int LiveSafeDeviceName(const char *devname, char *newdevname, size_t dest * 6 chars there is no point in shortening it since we must at * least enter two periods (.) into the string. */ - if ((destlen-1) > 10 || (destlen-1) < 6) { + if ((destlen - 1) > 10 || (destlen - 1) < 6) { return 1; } @@ -254,7 +250,7 @@ LiveDevice *LiveGetDevice(const char *name) return NULL; } - TAILQ_FOREACH(pd, &live_devices, next) { + TAILQ_FOREACH (pd, &live_devices, next) { if (!strcmp(name, pd->dev)) { return pd; } @@ -285,14 +281,13 @@ int LiveBuildDeviceListCustom(const char *runmode, const char *itemname) if (base == NULL) return 0; - TAILQ_FOREACH(child, &base->head, next) { + TAILQ_FOREACH (child, &base->head, next) { ConfNode *subchild; - TAILQ_FOREACH(subchild, &child->head, next) { + TAILQ_FOREACH (subchild, &child->head, next) { if ((!strcmp(subchild->name, itemname))) { if (!strcmp(subchild->val, "default")) break; - SCLogConfig("Adding %s %s from config file", - itemname, subchild->val); + SCLogConfig("Adding %s %s from config file", itemname, subchild->val); LiveRegisterDeviceName(subchild->val); i++; } @@ -320,7 +315,7 @@ int LiveDeviceListClean(void) TAILQ_FOREACH (pd, &live_devices, next) { DPDKCloseDevice(pd); } - TAILQ_FOREACH_SAFE(pd, &live_devices, next, tpd) { + TAILQ_FOREACH_SAFE (pd, &live_devices, next, tpd) { if (live_devices_stats) { SCLogNotice("%s: packets: %" PRIu64 ", drops: %" PRIu64 " (%.2f%%), invalid chksum: %" PRIu64, @@ -348,9 +343,9 @@ TmEcode LiveDeviceIfaceStat(json_t *cmd, json_t *answer, void *data) { SCEnter(); LiveDevice *pd; - const char * name = NULL; + const char *name = NULL; json_t *jarg = json_object_get(cmd, "iface"); - if(!json_is_string(jarg)) { + if (!json_is_string(jarg)) { json_object_set_new(answer, "message", json_string("Iface is not a string")); SCReturnInt(TM_ECODE_FAILED); } @@ -360,22 +355,19 @@ TmEcode LiveDeviceIfaceStat(json_t *cmd, json_t *answer, void *data) SCReturnInt(TM_ECODE_FAILED); } - TAILQ_FOREACH(pd, &live_devices, next) { + TAILQ_FOREACH (pd, &live_devices, next) { if (!strcmp(name, pd->dev)) { json_t *jdata = json_object(); if (jdata == NULL) { - json_object_set_new(answer, "message", - json_string("internal error at json object creation")); + json_object_set_new( + answer, "message", json_string("internal error at json object creation")); SCReturnInt(TM_ECODE_FAILED); } - json_object_set_new(jdata, "pkts", - json_integer(SC_ATOMIC_GET(pd->pkts))); - json_object_set_new(jdata, "invalid-checksums", - json_integer(SC_ATOMIC_GET(pd->invalid_checksums))); - json_object_set_new(jdata, "drop", - json_integer(SC_ATOMIC_GET(pd->drop))); - json_object_set_new(jdata, "bypassed", - json_integer(SC_ATOMIC_GET(pd->bypassed))); + json_object_set_new(jdata, "pkts", json_integer(SC_ATOMIC_GET(pd->pkts))); + json_object_set_new( + jdata, "invalid-checksums", json_integer(SC_ATOMIC_GET(pd->invalid_checksums))); + json_object_set_new(jdata, "drop", json_integer(SC_ATOMIC_GET(pd->drop))); + json_object_set_new(jdata, "bypassed", json_integer(SC_ATOMIC_GET(pd->bypassed))); json_object_set_new(answer, "message", jdata); SCReturnInt(TM_ECODE_OK); } @@ -394,17 +386,17 @@ TmEcode LiveDeviceIfaceList(json_t *cmd, json_t *answer, void *data) jdata = json_object(); if (jdata == NULL) { - json_object_set_new(answer, "message", - json_string("internal error at json object creation")); + json_object_set_new( + answer, "message", json_string("internal error at json object creation")); return TM_ECODE_FAILED; } jarray = json_array(); if (jarray == NULL) { - json_object_set_new(answer, "message", - json_string("internal error at json object creation")); + json_object_set_new( + answer, "message", json_string("internal error at json object creation")); return TM_ECODE_FAILED; } - TAILQ_FOREACH(pd, &live_devices, next) { + TAILQ_FOREACH (pd, &live_devices, next) { json_array_append_new(jarray, json_string(pd->dev)); i++; } @@ -444,7 +436,7 @@ void LiveDeviceFinalize(void) LiveDeviceName *ld, *pld; SCLogDebug("Finalize live device"); /* Iter on devices and register them */ - TAILQ_FOREACH_SAFE(ld, &pre_live_devices, next, pld) { + TAILQ_FOREACH_SAFE (ld, &pre_live_devices, next, pld) { if (ld->dev) { LiveRegisterDevice(ld->dev); SCFree(ld->dev); @@ -464,8 +456,8 @@ static void LiveDevExtensionFree(void *x) */ void LiveDevRegisterExtension(void) { - g_bypass_storage_id = LiveDevStorageRegister("bypass_stats", sizeof(void *), - NULL, LiveDevExtensionFree); + g_bypass_storage_id = + LiveDevStorageRegister("bypass_stats", sizeof(void *), NULL, LiveDevExtensionFree); } /** @@ -587,7 +579,7 @@ TmEcode LiveDeviceGetBypassedStats(json_t *cmd, json_t *answer, void *data) LiveDevice *ldev = NULL, *ndev = NULL; json_t *ifaces = NULL; - while(LiveDeviceForEach(&ldev, &ndev)) { + while (LiveDeviceForEach(&ldev, &ndev)) { BypassInfo *bpinfo = LiveDevGetStorageById(ldev, g_bypass_storage_id); if (bpinfo) { uint64_t ipv4_hash_count = SC_ATOMIC_GET(bpinfo->ipv4_hash_count); @@ -619,8 +611,7 @@ TmEcode LiveDeviceGetBypassedStats(json_t *cmd, json_t *answer, void *data) SCReturnInt(TM_ECODE_OK); } - json_object_set_new(answer, "message", - json_string("No interface using bypass")); + json_object_set_new(answer, "message", json_string("No interface using bypass")); SCReturnInt(TM_ECODE_FAILED); } #endif diff --git a/src/util-device.h b/src/util-device.h index d5a2d46caf08..5fc352cb8c05 100644 --- a/src/util-device.h +++ b/src/util-device.h @@ -25,14 +25,14 @@ #include "queue.h" #include "util-storage.h" -#define OFFLOAD_FLAG_SG (1<<0) -#define OFFLOAD_FLAG_TSO (1<<1) -#define OFFLOAD_FLAG_GSO (1<<2) -#define OFFLOAD_FLAG_GRO (1<<3) -#define OFFLOAD_FLAG_LRO (1<<4) -#define OFFLOAD_FLAG_RXCSUM (1<<5) -#define OFFLOAD_FLAG_TXCSUM (1<<6) -#define OFFLOAD_FLAG_TOE (1<<7) +#define OFFLOAD_FLAG_SG (1 << 0) +#define OFFLOAD_FLAG_TSO (1 << 1) +#define OFFLOAD_FLAG_GSO (1 << 2) +#define OFFLOAD_FLAG_GRO (1 << 3) +#define OFFLOAD_FLAG_LRO (1 << 4) +#define OFFLOAD_FLAG_RXCSUM (1 << 5) +#define OFFLOAD_FLAG_TXCSUM (1 << 6) +#define OFFLOAD_FLAG_TOE (1 << 7) void LiveSetOffloadDisable(void); void LiveSetOffloadWarn(void); @@ -48,7 +48,7 @@ typedef struct { /** storage for live device names */ typedef struct LiveDevice_ { - char *dev; /**< the device (e.g. "eth0") */ + char *dev; /**< the device (e.g. "eth0") */ char dev_short[MAX_DEVNAME + 1]; int mtu; /* MTU of the device */ bool tenant_id_set; @@ -61,8 +61,8 @@ typedef struct LiveDevice_ { SC_ATOMIC_DECLARE(uint64_t, invalid_checksums); TAILQ_ENTRY(LiveDevice_) next; - uint32_t tenant_id; /**< tenant id in multi-tenancy */ - uint32_t offload_orig; /**< original offload settings to restore @exit */ + uint32_t tenant_id; /**< tenant id in multi-tenancy */ + uint32_t offload_orig; /**< original offload settings to restore @exit */ #ifdef HAVE_DPDK // DPDK resources that needs to be cleaned after workers are stopped and devices closed DPDKDeviceResources dpdk_vars; @@ -72,7 +72,7 @@ typedef struct LiveDevice_ { } LiveDevice; typedef struct LiveDeviceName_ { - char *dev; /**< the device (e.g. "eth0") */ + char *dev; /**< the device (e.g. "eth0") */ TAILQ_ENTRY(LiveDeviceName_) next; } LiveDeviceName; diff --git a/src/util-dpdk.h b/src/util-dpdk.h index a94f46225217..430750dfe718 100644 --- a/src/util-dpdk.h +++ b/src/util-dpdk.h @@ -65,7 +65,7 @@ #define RTE_ETH_RX_OFFLOAD_KEEP_CRC DEV_RX_OFFLOAD_KEEP_CRC #define RTE_ETH_RX_OFFLOAD_SCTP_CKSUM DEV_RX_OFFLOAD_SCTP_CKSUM #define RTE_ETH_RX_OFFLOAD_OUTER_UDP_CKSUM DEV_RX_OFFLOAD_OUTER_UDP_CKSUM -#define RTE_ETH_RX_OFFLOAD_RSS_HASH DEV_RX_OFFLOAD_RSS_HASH +#define RTE_ETH_RX_OFFLOAD_RSS_HASH DEV_RX_OFFLOAD_RSS_HASH #define RTE_ETH_MQ_TX_NONE ETH_MQ_TX_NONE diff --git a/src/util-ebpf.c b/src/util-ebpf.c index 13eaea828d9b..ea91435fca30 100644 --- a/src/util-ebpf.c +++ b/src/util-ebpf.c @@ -31,7 +31,7 @@ */ #define PCAP_DONT_INCLUDE_PCAP_BPF_H 1 -#define SC_PCAP_DONT_INCLUDE_PCAP_H 1 +#define SC_PCAP_DONT_INCLUDE_PCAP_H 1 #include "suricata-common.h" #include "flow-bypass.h" @@ -59,14 +59,14 @@ #define BPF_MAP_MAX_COUNT 16 -#define BYPASSED_FLOW_TIMEOUT 60 +#define BYPASSED_FLOW_TIMEOUT 60 static LiveDevStorageId g_livedev_storage_id = { .id = -1 }; static FlowStorageId g_flow_storage_id = { .id = -1 }; struct bpf_map_item { char iface[IFNAMSIZ]; - char * name; + char *name; int fd; uint8_t to_unlink; }; @@ -85,14 +85,12 @@ static void BpfMapsInfoFree(void *bpf) { struct bpf_maps_info *bpfinfo = (struct bpf_maps_info *)bpf; int i; - for (i = 0; i < bpfinfo->last; i ++) { + for (i = 0; i < bpfinfo->last; i++) { if (bpfinfo->array[i].name) { if (bpfinfo->array[i].to_unlink) { char pinnedpath[PATH_MAX]; - int ret = snprintf(pinnedpath, sizeof(pinnedpath), - "/sys/fs/bpf/suricata-%s-%s", - bpfinfo->array[i].iface, - bpfinfo->array[i].name); + int ret = snprintf(pinnedpath, sizeof(pinnedpath), "/sys/fs/bpf/suricata-%s-%s", + bpfinfo->array[i].iface, bpfinfo->array[i].name); if (ret > 0) { /* Unlink the pinned entry */ ret = unlink(pinnedpath); @@ -172,10 +170,7 @@ int EBPFGetMapFDByName(const char *iface, const char *name) static int EBPFLoadPinnedMapsFile(LiveDevice *livedev, const char *file) { char pinnedpath[1024]; - snprintf(pinnedpath, sizeof(pinnedpath), - "/sys/fs/bpf/suricata-%s-%s", - livedev->dev, - file); + snprintf(pinnedpath, sizeof(pinnedpath), "/sys/fs/bpf/suricata-%s-%s", livedev->dev, file); return bpf_obj_get(pinnedpath); } @@ -296,8 +291,8 @@ static int EBPFLoadPinnedMaps(LiveDevice *livedev, struct ebpf_timeout_config *c * \param val a pointer to an integer that will be the file desc * \return -1 in case of error, 0 in case of success, 1 if pinned maps is loaded */ -int EBPFLoadFile(const char *iface, const char *path, const char * section, - int *val, struct ebpf_timeout_config *config) +int EBPFLoadFile(const char *iface, const char *path, const char *section, int *val, + struct ebpf_timeout_config *config) { int err, pfd; bool found = false; @@ -319,14 +314,14 @@ int EBPFLoadFile(const char *iface, const char *path, const char * section, } } - if (! path) { + if (!path) { SCLogError("No file defined to load eBPF from"); return -1; } /* Sending the eBPF code to the kernel requires a large amount of * locked memory so we set it to unlimited to avoid a ENOPERM error */ - struct rlimit r = {RLIM_INFINITY, RLIM_INFINITY}; + struct rlimit r = { RLIM_INFINITY, RLIM_INFINITY }; if (setrlimit(RLIMIT_MEMLOCK, &r) != 0) { SCLogError("Unable to lock memory: %s (%d)", strerror(errno), errno); return -1; @@ -337,24 +332,26 @@ int EBPFLoadFile(const char *iface, const char *path, const char * section, long error = libbpf_get_error(bpfobj); if (error) { char err_buf[128]; - libbpf_strerror(error, err_buf, - sizeof(err_buf)); + libbpf_strerror(error, err_buf, sizeof(err_buf)); SCLogError("Unable to load eBPF objects in '%s': %s", path, err_buf); return -1; } if (config->flags & EBPF_XDP_HW_MODE) { unsigned int ifindex = if_nametoindex(iface); - bpf_object__for_each_program(bpfprog, bpfobj) { + bpf_object__for_each_program(bpfprog, bpfobj) + { bpf_program__set_ifindex(bpfprog, ifindex); } - bpf_map__for_each(map, bpfobj) { + bpf_map__for_each(map, bpfobj) + { bpf_map__set_ifindex(map, ifindex); } } /* Let's check that our section is here */ - bpf_object__for_each_program(bpfprog, bpfobj) { + bpf_object__for_each_program(bpfprog, bpfobj) + { #ifdef HAVE_BPF_PROGRAM__SECTION_NAME const char *title = bpf_program__section_name(bpfprog); #else @@ -409,7 +406,8 @@ int EBPFLoadFile(const char *iface, const char *path, const char * section, } /* Store the maps in bpf_maps_info:: */ - bpf_map__for_each(map, bpfobj) { + bpf_map__for_each(map, bpfobj) + { if (bpf_map_data->last == BPF_MAP_MAX_COUNT) { SCLogError("Too many BPF maps in eBPF files"); break; @@ -417,8 +415,7 @@ int EBPFLoadFile(const char *iface, const char *path, const char * section, SCLogDebug("Got a map '%s' with fd '%d'", bpf_map__name(map), bpf_map__fd(map)); bpf_map_data->array[bpf_map_data->last].fd = bpf_map__fd(map); bpf_map_data->array[bpf_map_data->last].name = SCStrdup(bpf_map__name(map)); - snprintf(bpf_map_data->array[bpf_map_data->last].iface, IFNAMSIZ, - "%s", iface); + snprintf(bpf_map_data->array[bpf_map_data->last].iface, IFNAMSIZ, "%s", iface); if (!bpf_map_data->array[bpf_map_data->last].name) { SCLogError("Unable to duplicate map name"); BpfMapsInfoFree(bpf_map_data); @@ -501,9 +498,8 @@ int EBPFSetupXDP(const char *iface, int fd, uint8_t flags) * \return false (this create function never returns true) */ static bool EBPFCreateFlowForKey(struct flows_stats *flowstats, LiveDevice *dev, void *key, - size_t skey, FlowKey *flow_key, struct timespec *ctime, - uint64_t pkts_cnt, uint64_t bytes_cnt, - int mapfd, int cpus_count) + size_t skey, FlowKey *flow_key, struct timespec *ctime, uint64_t pkts_cnt, + uint64_t bytes_cnt, int mapfd, int cpus_count) { Flow *f = NULL; uint32_t hash = FlowKeyGetHash(flow_key); @@ -551,7 +547,7 @@ static bool EBPFCreateFlowForKey(struct flows_stats *flowstats, LiveDevice *dev, return false; } } else { - EBPFBypassData *eb = (EBPFBypassData *) fc->bypass_data; + EBPFBypassData *eb = (EBPFBypassData *)fc->bypass_data; if (eb == NULL) { FLOWLOCK_UNLOCK(f); return false; @@ -597,9 +593,8 @@ void EBPFBypassFree(void *data) * \return true if entries have activity, false if not */ -static bool EBPFBypassCheckHalfFlow(Flow *f, FlowBypassInfo *fc, - EBPFBypassData *eb, void *key, - int index) +static bool EBPFBypassCheckHalfFlow( + Flow *f, FlowBypassInfo *fc, EBPFBypassData *eb, void *key, int index) { int i; uint64_t pkts_cnt = 0; @@ -615,8 +610,7 @@ static bool EBPFBypassCheckHalfFlow(Flow *f, FlowBypassInfo *fc, } for (i = 0; i < eb->cpus_count; i++) { /* let's start accumulating value so we can compute the counters */ - SCLogDebug("%d: Adding pkts %lu bytes %lu", i, - BPF_PERCPU(values_array, i).packets, + SCLogDebug("%d: Adding pkts %lu bytes %lu", i, BPF_PERCPU(values_array, i).packets, BPF_PERCPU(values_array, i).bytes); pkts_cnt += BPF_PERCPU(values_array, i).packets; bytes_cnt += BPF_PERCPU(values_array, i).bytes; @@ -668,10 +662,9 @@ bool EBPFBypassUpdate(Flow *f, void *data, time_t tsec) return false; } -typedef bool (*OpFlowForKey)(struct flows_stats * flowstats, LiveDevice*dev, void *key, - size_t skey, FlowKey *flow_key, struct timespec *ctime, - uint64_t pkts_cnt, uint64_t bytes_cnt, - int mapfd, int cpus_count); +typedef bool (*OpFlowForKey)(struct flows_stats *flowstats, LiveDevice *dev, void *key, size_t skey, + FlowKey *flow_key, struct timespec *ctime, uint64_t pkts_cnt, uint64_t bytes_cnt, int mapfd, + int cpus_count); /** * Bypassed flows iterator for IPv4 @@ -680,12 +673,9 @@ typedef bool (*OpFlowForKey)(struct flows_stats * flowstats, LiveDevice*dev, voi * running a callback function on each flow. */ static int EBPFForEachFlowV4Table(ThreadVars *th_v, LiveDevice *dev, const char *name, - struct timespec *ctime, - struct ebpf_timeout_config *tcfg, - OpFlowForKey EBPFOpFlowForKey - ) + struct timespec *ctime, struct ebpf_timeout_config *tcfg, OpFlowForKey EBPFOpFlowForKey) { - struct flows_stats flowstats = { 0, 0, 0}; + struct flows_stats flowstats = { 0, 0, 0 }; int mapfd = EBPFGetMapFDByName(dev->dev, name); if (mapfd == -1) return -1; @@ -721,9 +711,8 @@ static int EBPFForEachFlowV4Table(ThreadVars *th_v, LiveDevice *dev, const char } for (i = 0; i < tcfg->cpus_count; i++) { /* let's start accumulating value so we can compute the counters */ - SCLogDebug("%d: Adding pkts %lu bytes %lu", i, - BPF_PERCPU(values_array, i).packets, - BPF_PERCPU(values_array, i).bytes); + SCLogDebug("%d: Adding pkts %lu bytes %lu", i, BPF_PERCPU(values_array, i).packets, + BPF_PERCPU(values_array, i).bytes); pkts_cnt += BPF_PERCPU(values_array, i).packets; bytes_cnt += BPF_PERCPU(values_array, i).bytes; } @@ -759,9 +748,8 @@ static int EBPFForEachFlowV4Table(ThreadVars *th_v, LiveDevice *dev, const char } flow_key.recursion_level = 0; flow_key.livedev_id = dev->id; - dead_flow = EBPFOpFlowForKey(&flowstats, dev, &next_key, sizeof(next_key), &flow_key, - ctime, pkts_cnt, bytes_cnt, - mapfd, tcfg->cpus_count); + dead_flow = EBPFOpFlowForKey(&flowstats, dev, &next_key, sizeof(next_key), &flow_key, ctime, + pkts_cnt, bytes_cnt, mapfd, tcfg->cpus_count); if (dead_flow) { found = 1; } @@ -790,14 +778,10 @@ static int EBPFForEachFlowV4Table(ThreadVars *th_v, LiveDevice *dev, const char * This function iterates on all the flows of the IPv4 table * running a callback function on each flow. */ -static int EBPFForEachFlowV6Table(ThreadVars *th_v, - LiveDevice *dev, const char *name, - struct timespec *ctime, - struct ebpf_timeout_config *tcfg, - OpFlowForKey EBPFOpFlowForKey - ) +static int EBPFForEachFlowV6Table(ThreadVars *th_v, LiveDevice *dev, const char *name, + struct timespec *ctime, struct ebpf_timeout_config *tcfg, OpFlowForKey EBPFOpFlowForKey) { - struct flows_stats flowstats = { 0, 0, 0}; + struct flows_stats flowstats = { 0, 0, 0 }; int mapfd = EBPFGetMapFDByName(dev->dev, name); if (mapfd == -1) return -1; @@ -832,9 +816,8 @@ static int EBPFForEachFlowV6Table(ThreadVars *th_v, } for (i = 0; i < tcfg->cpus_count; i++) { /* let's start accumulating value so we can compute the counters */ - SCLogDebug("%d: Adding pkts %lu bytes %lu", i, - BPF_PERCPU(values_array, i).packets, - BPF_PERCPU(values_array, i).bytes); + SCLogDebug("%d: Adding pkts %lu bytes %lu", i, BPF_PERCPU(values_array, i).packets, + BPF_PERCPU(values_array, i).bytes); pkts_cnt += BPF_PERCPU(values_array, i).packets; bytes_cnt += BPF_PERCPU(values_array, i).bytes; } @@ -878,9 +861,8 @@ static int EBPFForEachFlowV6Table(ThreadVars *th_v, } flow_key.recursion_level = 0; flow_key.livedev_id = dev->id; - pkts_cnt = EBPFOpFlowForKey(&flowstats, dev, &next_key, sizeof(next_key), &flow_key, - ctime, pkts_cnt, bytes_cnt, - mapfd, tcfg->cpus_count); + pkts_cnt = EBPFOpFlowForKey(&flowstats, dev, &next_key, sizeof(next_key), &flow_key, ctime, + pkts_cnt, bytes_cnt, mapfd, tcfg->cpus_count); if (pkts_cnt > 0) { found = 1; } @@ -902,18 +884,13 @@ static int EBPFForEachFlowV6Table(ThreadVars *th_v, return found; } - int EBPFCheckBypassedFlowCreate(ThreadVars *th_v, struct timespec *curtime, void *data) { LiveDevice *ldev = NULL, *ndev; struct ebpf_timeout_config *cfg = (struct ebpf_timeout_config *)data; - while(LiveDeviceForEach(&ldev, &ndev)) { - EBPFForEachFlowV4Table(th_v, ldev, "flow_table_v4", - curtime, - cfg, EBPFCreateFlowForKey); - EBPFForEachFlowV6Table(th_v, ldev, "flow_table_v6", - curtime, - cfg, EBPFCreateFlowForKey); + while (LiveDeviceForEach(&ldev, &ndev)) { + EBPFForEachFlowV4Table(th_v, ldev, "flow_table_v4", curtime, cfg, EBPFCreateFlowForKey); + EBPFForEachFlowV6Table(th_v, ldev, "flow_table_v6", curtime, cfg, EBPFCreateFlowForKey); } return 0; @@ -925,7 +902,6 @@ void EBPFRegisterExtension(void) g_flow_storage_id = FlowStorageRegister("bypassedlist", sizeof(void *), NULL, BypassedListFree); } - #ifdef HAVE_PACKET_XDP static uint32_t g_redirect_iface_cpu_counter = 0; @@ -978,15 +954,11 @@ void EBPFBuildCPUSet(ConfNode *node, char *iface) } g_redirect_iface_cpu_counter = 0; if (node == NULL) { - bpf_map_update_elem(mapfd, &key0, &g_redirect_iface_cpu_counter, - BPF_ANY); + bpf_map_update_elem(mapfd, &key0, &g_redirect_iface_cpu_counter, BPF_ANY); return; } - BuildCpusetWithCallback("xdp-cpu-redirect", node, - EBPFRedirectMapAddCPU, - iface); - bpf_map_update_elem(mapfd, &key0, &g_redirect_iface_cpu_counter, - BPF_ANY); + BuildCpusetWithCallback("xdp-cpu-redirect", node, EBPFRedirectMapAddCPU, iface); + bpf_map_update_elem(mapfd, &key0, &g_redirect_iface_cpu_counter, BPF_ANY); } /** diff --git a/src/util-ebpf.h b/src/util-ebpf.h index bf1768a69da7..a534f0d6de4b 100644 --- a/src/util-ebpf.h +++ b/src/util-ebpf.h @@ -28,11 +28,10 @@ #ifdef HAVE_PACKET_EBPF -#define XDP_FLAGS_UPDATE_IF_NOEXIST (1U << 0) -#define XDP_FLAGS_SKB_MODE (1U << 1) -#define XDP_FLAGS_DRV_MODE (1U << 2) -#define XDP_FLAGS_HW_MODE (1U << 3) - +#define XDP_FLAGS_UPDATE_IF_NOEXIST (1U << 0) +#define XDP_FLAGS_SKB_MODE (1U << 1) +#define XDP_FLAGS_DRV_MODE (1U << 2) +#define XDP_FLAGS_HW_MODE (1U << 3) struct flowv4_keys { __be32 src; @@ -41,8 +40,8 @@ struct flowv4_keys { __be32 ports; __be16 port16[2]; }; - __u8 ip_proto:1; - __u16 vlan0:15; + __u8 ip_proto : 1; + __u16 vlan0 : 15; __u16 vlan1; __u16 vlan2; }; @@ -54,8 +53,8 @@ struct flowv6_keys { __be32 ports; __be16 port16[2]; }; - __u8 ip_proto:1; - __u16 vlan0:15; + __u8 ip_proto : 1; + __u16 vlan0 : 15; __u16 vlan1; __u16 vlan2; }; @@ -71,14 +70,14 @@ typedef struct EBPFBypassData_ { int cpus_count; } EBPFBypassData; -#define EBPF_SOCKET_FILTER (1<<0) -#define EBPF_XDP_CODE (1<<1) -#define EBPF_PINNED_MAPS (1<<2) -#define EBPF_XDP_HW_MODE (1<<3) +#define EBPF_SOCKET_FILTER (1 << 0) +#define EBPF_XDP_CODE (1 << 1) +#define EBPF_PINNED_MAPS (1 << 2) +#define EBPF_XDP_HW_MODE (1 << 3) int EBPFGetMapFDByName(const char *iface, const char *name); -int EBPFLoadFile(const char *iface, const char *path, const char * section, - int *val, struct ebpf_timeout_config *config); +int EBPFLoadFile(const char *iface, const char *path, const char *section, int *val, + struct ebpf_timeout_config *config); int EBPFSetupXDP(const char *iface, int fd, uint8_t flags); int EBPFCheckBypassedFlowCreate(ThreadVars *th_v, struct timespec *curtime, void *data); @@ -95,14 +94,14 @@ void EBPFBypassFree(void *data); void EBPFDeleteKey(int fd, void *key); -#define __bpf_percpu_val_align __attribute__((__aligned__(8))) +#define __bpf_percpu_val_align __attribute__((__aligned__(8))) -#define BPF_DECLARE_PERCPU(type, name, nr_cpus) \ - struct { type v; /* padding */ } __bpf_percpu_val_align \ - name[nr_cpus] +#define BPF_DECLARE_PERCPU(type, name, nr_cpus) \ + struct { \ + type v; /* padding */ \ + } __bpf_percpu_val_align name[nr_cpus] #define BPF_PERCPU(name, cpu) name[(cpu)].v - #endif #endif diff --git a/src/util-enum.c b/src/util-enum.c index f63140afa006..144027ce2523 100644 --- a/src/util-enum.c +++ b/src/util-enum.c @@ -65,7 +65,7 @@ int SCMapEnumNameToValue(const char *enum_name, SCEnumCharMap *table) * * \retval result The enum_name for the enum_value supplied or NULL on failure */ -const char * SCMapEnumValueToName(int enum_value, SCEnumCharMap *table) +const char *SCMapEnumValueToName(int enum_value, SCEnumCharMap *table) { if (table == NULL) { SCLogDebug("Invalid argument(s) passed into SCMapEnumValueToName"); diff --git a/src/util-enum.h b/src/util-enum.h index ea88fc4b4460..c214af58d3d2 100644 --- a/src/util-enum.h +++ b/src/util-enum.h @@ -31,6 +31,6 @@ typedef struct SCEnumCharMap_ { int SCMapEnumNameToValue(const char *, SCEnumCharMap *); -const char * SCMapEnumValueToName(int, SCEnumCharMap *); +const char *SCMapEnumValueToName(int, SCEnumCharMap *); #endif /* __UTIL_ENUM_H__ */ diff --git a/src/util-error.c b/src/util-error.c index 01c2f9a01b73..3d8138667393 100644 --- a/src/util-error.c +++ b/src/util-error.c @@ -29,7 +29,9 @@ #include "util-error.h" thread_local SCError sc_errno = SC_OK; -#define CASE_CODE(E) case E: return #E +#define CASE_CODE(E) \ + case E: \ + return #E /** * \brief Maps the error code, to its string equivalent @@ -38,17 +40,17 @@ thread_local SCError sc_errno = SC_OK; * * \retval The string equivalent for the error code */ -const char * SCErrorToString(SCError err) +const char *SCErrorToString(SCError err) { switch (err) { - CASE_CODE (SC_OK); + CASE_CODE(SC_OK); CASE_CODE(SC_ENOMEM); CASE_CODE(SC_EINVAL); CASE_CODE(SC_ELIMIT); CASE_CODE(SC_EEXIST); - CASE_CODE (SC_ERR_MAX); + CASE_CODE(SC_ERR_MAX); } return "UNKNOWN_ERROR"; diff --git a/src/util-file-decompression.c b/src/util-file-decompression.c index dfafdc87f050..c58f1e0fed85 100644 --- a/src/util-file-decompression.c +++ b/src/util-file-decompression.c @@ -35,8 +35,8 @@ #include "util-misc.h" #include "util-print.h" -#define SWF_ZLIB_MIN_VERSION 0x06 -#define SWF_LZMA_MIN_VERSION 0x0D +#define SWF_ZLIB_MIN_VERSION 0x06 +#define SWF_LZMA_MIN_VERSION 0x0D int FileIsSwfFile(const uint8_t *buffer, uint32_t buffer_len) { @@ -68,12 +68,9 @@ int FileIsSwfFile(const uint8_t *buffer, uint32_t buffer_len) * \retval 1 if decompression works * \retval 0 an error occurred, and event set */ -int FileSwfDecompression(const uint8_t *buffer, uint32_t buffer_len, - DetectEngineThreadCtx *det_ctx, - InspectionBuffer *out_buffer, - int swf_type, - uint32_t decompress_depth, - uint32_t compress_depth) +int FileSwfDecompression(const uint8_t *buffer, uint32_t buffer_len, DetectEngineThreadCtx *det_ctx, + InspectionBuffer *out_buffer, int swf_type, uint32_t decompress_depth, + uint32_t compress_depth) { int r = 0; @@ -105,15 +102,11 @@ int FileSwfDecompression(const uint8_t *buffer, uint32_t buffer_len, /* get swf version */ uint8_t swf_version = FileGetSwfVersion(buffer, buffer_len); - if (compression_type == FILE_SWF_ZLIB_COMPRESSION && - swf_version < SWF_ZLIB_MIN_VERSION) - { + if (compression_type == FILE_SWF_ZLIB_COMPRESSION && swf_version < SWF_ZLIB_MIN_VERSION) { DetectEngineSetEvent(det_ctx, FILE_DECODER_EVENT_INVALID_SWF_VERSION); return 0; } - if (compression_type == FILE_SWF_LZMA_COMPRESSION && - swf_version < SWF_LZMA_MIN_VERSION) - { + if (compression_type == FILE_SWF_LZMA_COMPRESSION && swf_version < SWF_LZMA_MIN_VERSION) { DetectEngineSetEvent(det_ctx, FILE_DECODER_EVENT_INVALID_SWF_VERSION); return 0; } @@ -125,7 +118,8 @@ int FileSwfDecompression(const uint8_t *buffer, uint32_t buffer_len, } /* if decompress_depth is 0, keep the flash file length */ - uint32_t decompressed_data_len = (decompress_depth == 0) ? decompressed_swf_len : decompress_depth; + uint32_t decompressed_data_len = + (decompress_depth == 0) ? decompressed_swf_len : decompress_depth; decompressed_data_len += 8; /* make sure the inspection buffer has enough space */ @@ -149,20 +143,17 @@ int FileSwfDecompression(const uint8_t *buffer, uint32_t buffer_len, memset(out_buffer->buf + 8, 0, decompressed_data_len - 8); if ((swf_type == HTTP_SWF_COMPRESSION_ZLIB || swf_type == HTTP_SWF_COMPRESSION_BOTH) && - compression_type == FILE_SWF_ZLIB_COMPRESSION) - { + compression_type == FILE_SWF_ZLIB_COMPRESSION) { /* the first 8 bytes represents the fws header, see 'FWS format' above. * data will start from 8th bytes */ - r = FileSwfZlibDecompression(det_ctx, - (uint8_t *)buffer + offset, compressed_data_len, - out_buffer->buf + 8, out_buffer->len - 8); + r = FileSwfZlibDecompression(det_ctx, (uint8_t *)buffer + offset, compressed_data_len, + out_buffer->buf + 8, out_buffer->len - 8); if (r == 0) goto error; } else if ((swf_type == HTTP_SWF_COMPRESSION_LZMA || swf_type == HTTP_SWF_COMPRESSION_BOTH) && - compression_type == FILE_SWF_LZMA_COMPRESSION) - { + compression_type == FILE_SWF_LZMA_COMPRESSION) { /* we need to setup the lzma header */ /* * | 5 bytes | 8 bytes | n bytes | @@ -180,9 +171,8 @@ int FileSwfDecompression(const uint8_t *buffer, uint32_t buffer_len, /* the first 8 bytes represents the fws header, see 'FWS format' above. * data will start from 8th bytes */ - r = FileSwfLzmaDecompression(det_ctx, - compressed_data, compressed_data_len, - out_buffer->buf + 8, out_buffer->len - 8); + r = FileSwfLzmaDecompression(det_ctx, compressed_data, compressed_data_len, + out_buffer->buf + 8, out_buffer->len - 8); if (r == 0) goto error; } else { diff --git a/src/util-file-decompression.h b/src/util-file-decompression.h index 043d68319115..e35cdee39a22 100644 --- a/src/util-file-decompression.h +++ b/src/util-file-decompression.h @@ -35,10 +35,8 @@ enum { }; int FileIsSwfFile(const uint8_t *buffer, uint32_t buffer_len); -int FileSwfDecompression(const uint8_t *buffer, uint32_t buffer_len, - DetectEngineThreadCtx *det_ctx, - InspectionBuffer *out_buffer, - int swf_type, - uint32_t decompress_depth, uint32_t compress_depth); +int FileSwfDecompression(const uint8_t *buffer, uint32_t buffer_len, DetectEngineThreadCtx *det_ctx, + InspectionBuffer *out_buffer, int swf_type, uint32_t decompress_depth, + uint32_t compress_depth); #endif /* __UTIL_FILE_DECOMPRESSION_H__ */ diff --git a/src/util-file-swf-decompression.c b/src/util-file-swf-decompression.c index 378b4f96e942..8b1ac8465c13 100644 --- a/src/util-file-swf-decompression.c +++ b/src/util-file-swf-decompression.c @@ -21,7 +21,6 @@ * */ - #include "suricata.h" #include "suricata-common.h" @@ -42,8 +41,7 @@ * Return uncompressed file length * in little-endian order */ -uint32_t FileGetSwfDecompressedLen(const uint8_t *buffer, - const uint32_t buffer_len) +uint32_t FileGetSwfDecompressedLen(const uint8_t *buffer, const uint32_t buffer_len) { if (buffer_len < 8) { return 0; @@ -54,15 +52,11 @@ uint32_t FileGetSwfDecompressedLen(const uint8_t *buffer, uint32_t c = buffer[6]; uint32_t d = buffer[7]; - uint32_t value = (((a & 0xff) << 24UL) | - ((b & 0xff) << 16UL) | - ((c & 0xff) << 8UL) | - (d & 0xff)); + uint32_t value = + (((a & 0xff) << 24UL) | ((b & 0xff) << 16UL) | ((c & 0xff) << 8UL) | (d & 0xff)); - uint32_t len = (((value >> 24) & 0x000000FFUL) | - ((value >> 8) & 0x0000FF00UL) | - ((value << 8) & 0x00FF0000UL) | - ((value << 24) & 0xFF000000UL)); + uint32_t len = (((value >> 24) & 0x000000FFUL) | ((value >> 8) & 0x0000FF00UL) | + ((value << 8) & 0x00FF0000UL) | ((value << 24) & 0xFF000000UL)); return MIN(MAX_SWF_DECOMPRESSED_LEN, len); } @@ -80,9 +74,8 @@ uint8_t FileGetSwfVersion(const uint8_t *buffer, const uint32_t buffer_len) * | 4 bytes | 4 bytes | n bytes | * | 'CWS' + version | script len | compressed data | */ -int FileSwfZlibDecompression(DetectEngineThreadCtx *det_ctx, - uint8_t *compressed_data, uint32_t compressed_data_len, - uint8_t *decompressed_data, uint32_t decompressed_data_len) +int FileSwfZlibDecompression(DetectEngineThreadCtx *det_ctx, uint8_t *compressed_data, + uint32_t compressed_data_len, uint8_t *decompressed_data, uint32_t decompressed_data_len) { int ret = 1; z_stream infstream; @@ -103,7 +96,7 @@ int FileSwfZlibDecompression(DetectEngineThreadCtx *det_ctx, } result = inflate(&infstream, Z_NO_FLUSH); - switch(result) { + switch (result) { case Z_STREAM_END: break; case Z_OK: @@ -135,9 +128,8 @@ int FileSwfZlibDecompression(DetectEngineThreadCtx *det_ctx, * | 4 bytes | 4 bytes | 4 bytes | 5 bytes | n bytes | 6 bytes | * | 'ZWS' + version | script len | compressed len | LZMA props | LZMA data | LZMA end marker | */ -int FileSwfLzmaDecompression(DetectEngineThreadCtx *det_ctx, - uint8_t *compressed_data, uint32_t compressed_data_len, - uint8_t *decompressed_data, uint32_t decompressed_data_len) +int FileSwfLzmaDecompression(DetectEngineThreadCtx *det_ctx, uint8_t *compressed_data, + uint32_t compressed_data_len, uint8_t *decompressed_data, uint32_t decompressed_data_len) { int ret = 0; @@ -147,7 +139,7 @@ int FileSwfLzmaDecompression(DetectEngineThreadCtx *det_ctx, ret = lzma_decompress(compressed_data, &inprocessed, decompressed_data, &outprocessed, MAX_SWF_DECOMPRESSED_LEN); - switch(ret) { + switch (ret) { case LzmaOk: ret = 1; break; diff --git a/src/util-file-swf-decompression.h b/src/util-file-swf-decompression.h index 65ac74add178..7855d694a3e5 100644 --- a/src/util-file-swf-decompression.h +++ b/src/util-file-swf-decompression.h @@ -28,15 +28,13 @@ /* If we don't have the decompressed data len, * we use a default value. */ -#define MIN_SWF_LEN 2920 +#define MIN_SWF_LEN 2920 uint8_t FileGetSwfVersion(const uint8_t *buffer, const uint32_t buffer_len); uint32_t FileGetSwfDecompressedLen(const uint8_t *buffer, uint32_t buffer_len); -int FileSwfZlibDecompression(DetectEngineThreadCtx *det_ctx, - uint8_t *compressed_data, uint32_t compressed_data_len, - uint8_t *decompressed_data, uint32_t decompressed_data_len); -int FileSwfLzmaDecompression(DetectEngineThreadCtx *det_ctx, - uint8_t *compressed_data, uint32_t compressed_data_len, - uint8_t *decompressed_data, uint32_t decompressed_data_len); +int FileSwfZlibDecompression(DetectEngineThreadCtx *det_ctx, uint8_t *compressed_data, + uint32_t compressed_data_len, uint8_t *decompressed_data, uint32_t decompressed_data_len); +int FileSwfLzmaDecompression(DetectEngineThreadCtx *det_ctx, uint8_t *compressed_data, + uint32_t compressed_data_len, uint8_t *decompressed_data, uint32_t decompressed_data_len); #endif /* __UTIL_FILE_SWF_DECOMPRESSION_H__ */ diff --git a/src/util-file.c b/src/util-file.c index 3221d116870d..0f67321731e4 100644 --- a/src/util-file.c +++ b/src/util-file.c @@ -92,31 +92,31 @@ static void FileEndSha256(File *ff); void FileForceFilestoreEnable(void) { g_file_force_filestore = 1; - g_file_flow_mask |= (FLOWFILE_NO_STORE_TS|FLOWFILE_NO_STORE_TC); + g_file_flow_mask |= (FLOWFILE_NO_STORE_TS | FLOWFILE_NO_STORE_TC); } void FileForceMagicEnable(void) { g_file_force_magic = 1; - g_file_flow_mask |= (FLOWFILE_NO_MAGIC_TS|FLOWFILE_NO_MAGIC_TC); + g_file_flow_mask |= (FLOWFILE_NO_MAGIC_TS | FLOWFILE_NO_MAGIC_TC); } void FileForceMd5Enable(void) { g_file_force_md5 = 1; - g_file_flow_mask |= (FLOWFILE_NO_MD5_TS|FLOWFILE_NO_MD5_TC); + g_file_flow_mask |= (FLOWFILE_NO_MD5_TS | FLOWFILE_NO_MD5_TC); } void FileForceSha1Enable(void) { g_file_force_sha1 = 1; - g_file_flow_mask |= (FLOWFILE_NO_SHA1_TS|FLOWFILE_NO_SHA1_TC); + g_file_flow_mask |= (FLOWFILE_NO_SHA1_TS | FLOWFILE_NO_SHA1_TC); } void FileForceSha256Enable(void) { g_file_force_sha256 = 1; - g_file_flow_mask |= (FLOWFILE_NO_SHA256_TS|FLOWFILE_NO_SHA256_TC); + g_file_flow_mask |= (FLOWFILE_NO_SHA256_TS | FLOWFILE_NO_SHA256_TC); } int FileForceFilestore(void) @@ -161,7 +161,7 @@ int FileForceSha256(void) void FileForceTrackingEnable(void) { g_file_force_tracking = 1; - g_file_flow_mask |= (FLOWFILE_NO_SIZE_TS|FLOWFILE_NO_SIZE_TC); + g_file_flow_mask |= (FLOWFILE_NO_SIZE_TS | FLOWFILE_NO_SIZE_TC); } /** @@ -196,7 +196,7 @@ void FileForceHashParseCfg(ConfNode *conf) if (forcehash_node != NULL) { ConfNode *field = NULL; - TAILQ_FOREACH(field, &forcehash_node->head, next) { + TAILQ_FOREACH (field, &forcehash_node->head, next) { if (strcasecmp("md5", field->val) == 0) { if (g_disable_hashing) { SCLogInfo("not forcing md5 calculation for logged files: hashing globally " @@ -365,8 +365,8 @@ static int FilePruneFile(File *file, const StreamingBufferConfig *cfg) SCEnter(); /* file is done when state is closed+, logging/storing is done (if any) */ - SCLogDebug("file->state %d. Is >= FILE_STATE_CLOSED: %s", - file->state, (file->state >= FILE_STATE_CLOSED) ? "yes" : "no"); + SCLogDebug("file->state %d. Is >= FILE_STATE_CLOSED: %s", file->state, + (file->state >= FILE_STATE_CLOSED) ? "yes" : "no"); if (file->state >= FILE_STATE_CLOSED) { SCReturnInt(1); } @@ -384,7 +384,7 @@ static int FilePruneFile(File *file, const StreamingBufferConfig *cfg) #endif uint64_t left_edge = FileDataSize(file); if (file->flags & FILE_STORE) { - left_edge = MIN(left_edge,file->content_stored); + left_edge = MIN(left_edge, file->content_stored); } if (!g_detect_disabled) { @@ -400,8 +400,8 @@ static int FilePruneFile(File *file, const StreamingBufferConfig *cfg) uint64_t file_size = FileDataSize(file); uint64_t data_size = file_size - file_offset; - SCLogDebug("window %"PRIu32", file_size %"PRIu64", data_size %"PRIu64, - window, file_size, data_size); + SCLogDebug("window %" PRIu32 ", file_size %" PRIu64 ", data_size %" PRIu64, window, + file_size, data_size); if (data_size > (window * 3)) { file->content_inspected = MAX(file->content_inspected, file->size - window); @@ -515,7 +515,7 @@ void FileContainerRecycle(FileContainer *ffc, const StreamingBufferConfig *cfg) File *cur = ffc->head; File *next = NULL; - for (;cur != NULL; cur = next) { + for (; cur != NULL; cur = next) { next = cur->next; FileFree(cur, cfg); } @@ -535,7 +535,7 @@ void FileContainerFree(FileContainer *ffc, const StreamingBufferConfig *cfg) File *ptr = ffc->head; File *next = NULL; - for (;ptr != NULL; ptr = next) { + for (; ptr != NULL; ptr = next) { next = ptr->next; FileFree(ptr, cfg); } @@ -646,9 +646,7 @@ static int FileStoreNoStoreCheck(File *ff) } if (ff->flags & FILE_NOSTORE) { - if (ff->state == FILE_STATE_OPENED && - FileDataSize(ff) >= (uint64_t)FileMagicSize()) - { + if (ff->state == FILE_STATE_OPENED && FileDataSize(ff) >= (uint64_t)FileMagicSize()) { SCReturnInt(1); } } @@ -685,10 +683,11 @@ static int AppendData( * * \param ff the file */ -static void FileFlagGap(File *ff) { +static void FileFlagGap(File *ff) +{ ff->flags |= FILE_HAS_GAPS; - ff->flags |= (FILE_NOMD5|FILE_NOSHA1|FILE_NOSHA256); - ff->flags &= ~(FILE_MD5|FILE_SHA1|FILE_SHA256); + ff->flags |= (FILE_NOMD5 | FILE_NOSHA1 | FILE_NOSHA256); + ff->flags &= ~(FILE_MD5 | FILE_SHA1 | FILE_SHA256); } /** \internal @@ -751,7 +750,7 @@ static int FileAppendDataDo( SCReturnInt(-2); } - SCLogDebug("appending %"PRIu32" bytes", data_len); + SCLogDebug("appending %" PRIu32 " bytes", data_len); int r = AppendData(sbcfg, ff, data, data_len); if (r != 0) { @@ -808,7 +807,7 @@ int FileAppendDataById(FileContainer *ffc, const StreamingBufferConfig *sbcfg, u SCReturnInt(-1); } File *ff = ffc->head; - for ( ; ff != NULL; ff = ff->next) { + for (; ff != NULL; ff = ff->next) { if (track_id == ff->file_track_id) { int r = FileAppendDataDo(sbcfg, ff, data, data_len); SCReturnInt(r); @@ -839,7 +838,7 @@ int FileAppendGAPById(FileContainer *ffc, const StreamingBufferConfig *sbcfg, ui SCReturnInt(-1); } File *ff = ffc->head; - for ( ; ff != NULL; ff = ff->next) { + for (; ff != NULL; ff = ff->next) { if (track_id == ff->file_track_id) { FileFlagGap(ff); SCLogDebug("FILE_HAS_GAPS set"); @@ -895,12 +894,12 @@ int FileSetRange(FileContainer *ffc, uint64_t start, uint64_t end) * \note filename is not a string, so it's not nul terminated. */ static File *FileOpenFile(FileContainer *ffc, const StreamingBufferConfig *sbcfg, - const uint8_t *name, uint16_t name_len, - const uint8_t *data, uint32_t data_len, uint16_t flags) + const uint8_t *name, uint16_t name_len, const uint8_t *data, uint32_t data_len, + uint16_t flags) { SCEnter(); - //PrintRawDataFp(stdout, name, name_len); + // PrintRawDataFp(stdout, name, name_len); File *ff = FileAlloc(name, name_len); if (ff == NULL) { @@ -964,7 +963,7 @@ static File *FileOpenFile(FileContainer *ffc, const StreamingBufferConfig *sbcfg ff->state = FILE_STATE_ERROR; SCReturnPtr(NULL, "File"); } - SCLogDebug("file size is now %"PRIu64, FileTrackedSize(ff)); + SCLogDebug("file size is now %" PRIu64, FileTrackedSize(ff)); } else if (data_len > 0) { FileFlagGap(ff); } @@ -975,9 +974,9 @@ static File *FileOpenFile(FileContainer *ffc, const StreamingBufferConfig *sbcfg /** * \retval 0 ok * \retval -1 failed */ -int FileOpenFileWithId(FileContainer *ffc, const StreamingBufferConfig *sbcfg, - uint32_t track_id, const uint8_t *name, uint16_t name_len, - const uint8_t *data, uint32_t data_len, uint16_t flags) +int FileOpenFileWithId(FileContainer *ffc, const StreamingBufferConfig *sbcfg, uint32_t track_id, + const uint8_t *name, uint16_t name_len, const uint8_t *data, uint32_t data_len, + uint16_t flags) { SCLogDebug("ffc %p track_id %u", ffc, track_id); File *ff = FileOpenFile(ffc, sbcfg, name, name_len, data, data_len, flags); @@ -1097,7 +1096,7 @@ int FileCloseFileById(FileContainer *ffc, const StreamingBufferConfig *sbcfg, ui } File *ff = ffc->head; - for ( ; ff != NULL; ff = ff->next) { + for (; ff != NULL; ff = ff->next) { if (track_id == ff->file_track_id) { int r = FileCloseFilePtr(ff, sbcfg, data, data_len, flags); SCReturnInt(r); @@ -1120,14 +1119,14 @@ void FileUpdateFlowFileFlags(Flow *f, uint16_t set_file_flags, uint8_t direction /* remove flags not in our direction and don't disable what is globally enabled */ if (direction == STREAM_TOSERVER) { - set_file_flags &= ~(FLOWFILE_NONE_TC|g_file_flow_mask); + set_file_flags &= ~(FLOWFILE_NONE_TC | g_file_flow_mask); } else { - set_file_flags &= ~(FLOWFILE_NONE_TS|g_file_flow_mask); + set_file_flags &= ~(FLOWFILE_NONE_TS | g_file_flow_mask); } f->file_flags |= set_file_flags; - SCLogDebug("f->file_flags %04x set_file_flags %04x g_file_flow_mask %04x", - f->file_flags, set_file_flags, g_file_flow_mask); + SCLogDebug("f->file_flags %04x set_file_flags %04x g_file_flow_mask %04x", f->file_flags, + set_file_flags, g_file_flow_mask); if (set_file_flags != 0 && f->alproto != ALPROTO_UNKNOWN && f->alstate != NULL) { AppLayerStateData *sd = AppLayerParserGetStateData(f->proto, f->alproto, f->alstate); diff --git a/src/util-file.h b/src/util-file.h index 55d91192fe12..380b551b10f1 100644 --- a/src/util-file.h +++ b/src/util-file.h @@ -66,13 +66,13 @@ typedef struct SCMd5 SCMd5; #define FILEDATA_CONTENT_INSPECT_WINDOW 4096 typedef enum FileState_ { - FILE_STATE_NONE = 0, /**< no state */ - FILE_STATE_OPENED, /**< flow file is opened */ - FILE_STATE_CLOSED, /**< flow file is completed, - there will be no more data. */ - FILE_STATE_TRUNCATED, /**< flow file is not complete, but - there will be no more data. */ - FILE_STATE_ERROR, /**< file is in an error state */ + FILE_STATE_NONE = 0, /**< no state */ + FILE_STATE_OPENED, /**< flow file is opened */ + FILE_STATE_CLOSED, /**< flow file is completed, + there will be no more data. */ + FILE_STATE_TRUNCATED, /**< flow file is not complete, but + there will be no more data. */ + FILE_STATE_ERROR, /**< file is in an error state */ FILE_STATE_MAX } FileState; @@ -81,10 +81,10 @@ typedef struct File_ { uint16_t name_len; FileState state; StreamingBuffer *sb; - uint32_t file_track_id; /**< id used by protocol parser */ - uint32_t file_store_id; /**< id used in store file name file. */ - int fd; /**< file descriptor for filestore, not - open if equal to -1 */ + uint32_t file_track_id; /**< id used by protocol parser */ + uint32_t file_store_id; /**< id used in store file name file. */ + int fd; /**< file descriptor for filestore, not + open if equal to -1 */ uint8_t *name; #ifdef HAVE_MAGIC char *magic; @@ -96,8 +96,8 @@ typedef struct File_ { uint8_t sha1[SC_SHA1_LEN]; SCSha256 *sha256_ctx; uint8_t sha256[SC_SHA256_LEN]; - uint64_t content_inspected; /**< used in pruning if FILE_USE_DETECT - * flag is set */ + uint64_t content_inspected; /**< used in pruning if FILE_USE_DETECT + * flag is set */ uint64_t content_stored; uint64_t size; uint32_t inspect_window; @@ -142,9 +142,9 @@ void FileContainerAdd(FileContainer *, File *); * It's the responsibility of the API user to make sure this tracker is * properly updated. */ -int FileOpenFileWithId(FileContainer *, const StreamingBufferConfig *, - uint32_t track_id, const uint8_t *name, uint16_t name_len, - const uint8_t *data, uint32_t data_len, uint16_t flags); +int FileOpenFileWithId(FileContainer *, const StreamingBufferConfig *, uint32_t track_id, + const uint8_t *name, uint16_t name_len, const uint8_t *data, uint32_t data_len, + uint16_t flags); /** * \brief Close a File diff --git a/src/util-fix_checksum.c b/src/util-fix_checksum.c index 4fc60004ac2a..1d3d39fff76c 100644 --- a/src/util-fix_checksum.c +++ b/src/util-fix_checksum.c @@ -47,8 +47,7 @@ * * \retval New checksum. */ -uint16_t -FixChecksum(uint16_t sum, uint16_t old, uint16_t new) +uint16_t FixChecksum(uint16_t sum, uint16_t old, uint16_t new) { uint32_t l; diff --git a/src/util-fmemopen.c b/src/util-fmemopen.c index 412b9783ef3a..ed6261057cd3 100644 --- a/src/util-fmemopen.c +++ b/src/util-fmemopen.c @@ -93,16 +93,16 @@ static fpos_t SeekFn(void *handler, fpos_t offset, int whence) if (offset >= 0 && (size_t)offset <= mem->size) { return mem->pos = offset; } - break; + break; case SEEK_CUR: if (mem->pos + offset <= mem->size) return mem->pos += offset; - break; + break; case SEEK_END: /* must be negative */ if (mem->size + offset <= mem->size) return pos = mem->size + offset; - break; + break; } return -1; @@ -122,7 +122,8 @@ static int ReadFn(void *handler, char *buf, int size) size_t available = mem->size - mem->pos; int is_eof = 0; - if (size < 0) return - 1; + if (size < 0) + return -1; if ((size_t)size > available) { size = available; @@ -152,7 +153,8 @@ static int WriteFn(void *handler, const char *buf, int size) SCFmem *mem = handler; size_t available = mem->size - mem->pos; - if (size < 0) return - 1; + if (size < 0) + return -1; if ((size_t)size > available) size = available; diff --git a/src/util-hash-lookup3.c b/src/util-hash-lookup3.c index 5d1146152bf2..92ff2df02b4d 100644 --- a/src/util-hash-lookup3.c +++ b/src/util-hash-lookup3.c @@ -3,8 +3,8 @@ lookup3.c, by Bob Jenkins, May 2006, Public Domain. These are functions for producing 32-bit hashes for hash table lookup. -hashword(), hashlittle(), hashlittle2(), hashbig(), mix(), and final() -are externally useful functions. Routines to test the hash are included +hashword(), hashlittle(), hashlittle2(), hashbig(), mix(), and final() +are externally useful functions. Routines to test the hash are included if SELF_TEST is defined. You can use this free for any purpose. It's in the public domain. It has no warranty. @@ -12,7 +12,7 @@ You probably want to use hashlittle(). hashlittle() and hashbig() hash byte arrays. hashlittle() is is faster than hashbig() on little-endian machines. Intel and AMD are little-endian machines. On second thought, you probably want hashlittle2(), which is identical to -hashlittle() except it returns two 32-bit hashes for the price of one. +hashlittle() except it returns two 32-bit hashes for the price of one. You could implement hashbig2() if you wanted but I haven't bothered here. If you want to find a hash of, say, exactly 7 integers, do @@ -25,9 +25,9 @@ If you want to find a hash of, say, exactly 7 integers, do then use c as the hash value. If you have a variable length array of 4-byte integers to hash, use hashword(). If you have a byte array (like a character string), use hashlittle(). If you have several byte arrays, or -a mix of things, see the comments above hashlittle(). +a mix of things, see the comments above hashlittle(). -Why is this so big? I read 12 bytes at a time into 3 4-byte integers, +Why is this so big? I read 12 bytes at a time into 3 4-byte integers, then mix those integers. This is fast (you can do a lot more thorough mixing with 12*3 instructions on 3 integers than you can with 3 instructions on 1 byte), but shoehorning those bytes into integers efficiently is messy. @@ -35,12 +35,12 @@ on 1 byte), but shoehorning those bytes into integers efficiently is messy. */ //#define SELF_TEST 1 -#include /* defines printf for tests */ -#include /* defines time_t for timings in the test */ -#include /* defines uint32_t etc */ -#include /* attempt to define endianness */ +#include /* defines printf for tests */ +#include /* defines time_t for timings in the test */ +#include /* defines uint32_t etc */ +#include /* attempt to define endianness */ #ifdef linux -# include /* attempt to define endianness */ +#include /* attempt to define endianness */ #endif #include "util-hash-lookup3.h" @@ -48,25 +48,23 @@ on 1 byte), but shoehorning those bytes into integers efficiently is messy. * My best guess at if you are big-endian or little-endian. This may * need adjustment. */ -#if (defined(__BYTE_ORDER) && defined(__LITTLE_ENDIAN) && \ - __BYTE_ORDER == __LITTLE_ENDIAN) || \ - (defined(i386) || defined(__i386__) || defined(__i486__) || \ - defined(__i586__) || defined(__i686__) || defined(vax) || defined(MIPSEL)) -# define HASH_LITTLE_ENDIAN 1 -# define HASH_BIG_ENDIAN 0 -#elif (defined(__BYTE_ORDER) && defined(__BIG_ENDIAN) && \ - __BYTE_ORDER == __BIG_ENDIAN) || \ - (defined(sparc) || defined(POWERPC) || defined(mc68000) || defined(sel)) -# define HASH_LITTLE_ENDIAN 0 -# define HASH_BIG_ENDIAN 1 +#if (defined(__BYTE_ORDER) && defined(__LITTLE_ENDIAN) && __BYTE_ORDER == __LITTLE_ENDIAN) || \ + (defined(i386) || defined(__i386__) || defined(__i486__) || defined(__i586__) || \ + defined(__i686__) || defined(vax) || defined(MIPSEL)) +#define HASH_LITTLE_ENDIAN 1 +#define HASH_BIG_ENDIAN 0 +#elif (defined(__BYTE_ORDER) && defined(__BIG_ENDIAN) && __BYTE_ORDER == __BIG_ENDIAN) || \ + (defined(sparc) || defined(POWERPC) || defined(mc68000) || defined(sel)) +#define HASH_LITTLE_ENDIAN 0 +#define HASH_BIG_ENDIAN 1 #else -# define HASH_LITTLE_ENDIAN 0 -# define HASH_BIG_ENDIAN 0 +#define HASH_LITTLE_ENDIAN 0 +#define HASH_BIG_ENDIAN 0 #endif -#define hashsize(n) ((uint32_t)1<<(n)) -#define hashmask(n) (hashsize(n)-1) -#define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k)))) +#define hashsize(n) ((uint32_t)1 << (n)) +#define hashmask(n) (hashsize(n) - 1) +#define rot(x, k) (((x) << (k)) | ((x) >> (32 - (k)))) /* ------------------------------------------------------------------------------- @@ -86,7 +84,7 @@ This was tested for: the output delta to a Gray code (a^(a>>1)) so a string of 1's (as is commonly produced by subtraction) look like a single 1-bit difference. -* the base values were pseudorandom, all zero but one bit set, or +* the base values were pseudorandom, all zero but one bit set, or all zero plus a counter that starts at zero. Some k values for my "a-=c; a^=rot(c,k); c+=b;" arrangement that @@ -96,7 +94,7 @@ satisfy this are 14 9 3 7 17 3 Well, "9 15 3 18 27 15" didn't quite get 32 bits diffing for "differ" defined as + with a one-bit base and a two-bit delta. I -used http://burtleburtle.net/bob/hash/avalanche.html to choose +used http://burtleburtle.net/bob/hash/avalanche.html to choose the operations, constants, and arrangements of the variables. This does not achieve avalanche. There are input bits of (a,b,c) @@ -112,15 +110,27 @@ on, and rotates are much kinder to the top and bottom bits, so I used rotates. ------------------------------------------------------------------------------- */ -#define mix(a,b,c) \ -{ \ - a -= c; a ^= rot(c, 4); c += b; \ - b -= a; b ^= rot(a, 6); a += c; \ - c -= b; c ^= rot(b, 8); b += a; \ - a -= c; a ^= rot(c,16); c += b; \ - b -= a; b ^= rot(a,19); a += c; \ - c -= b; c ^= rot(b, 4); b += a; \ -} +#define mix(a, b, c) \ + { \ + a -= c; \ + a ^= rot(c, 4); \ + c += b; \ + b -= a; \ + b ^= rot(a, 6); \ + a += c; \ + c -= b; \ + c ^= rot(b, 8); \ + b += a; \ + a -= c; \ + a ^= rot(c, 16); \ + c += b; \ + b -= a; \ + b ^= rot(a, 19); \ + a += c; \ + c -= b; \ + c ^= rot(b, 4); \ + b += a; \ + } /* ------------------------------------------------------------------------------- @@ -135,7 +145,7 @@ produce values of c that look totally different. This was tested for the output delta to a Gray code (a^(a>>1)) so a string of 1's (as is commonly produced by subtraction) look like a single 1-bit difference. -* the base values were pseudorandom, all zero but one bit set, or +* the base values were pseudorandom, all zero but one bit set, or all zero plus a counter that starts at zero. These constants passed: @@ -147,16 +157,23 @@ and these came close: 11 8 15 26 3 22 24 ------------------------------------------------------------------------------- */ -#define final(a,b,c) \ -{ \ - c ^= b; c -= rot(b,14); \ - a ^= c; a -= rot(c,11); \ - b ^= a; b -= rot(a,25); \ - c ^= b; c -= rot(b,16); \ - a ^= c; a -= rot(c,4); \ - b ^= a; b -= rot(a,14); \ - c ^= b; c -= rot(b,24); \ -} +#define final(a, b, c) \ + { \ + c ^= b; \ + c -= rot(b, 14); \ + a ^= c; \ + a -= rot(c, 11); \ + b ^= a; \ + b -= rot(a, 25); \ + c ^= b; \ + c -= rot(b, 16); \ + a ^= c; \ + a -= rot(c, 4); \ + b ^= a; \ + b -= rot(a, 14); \ + c ^= b; \ + c -= rot(b, 24); \ + } /* -------------------------------------------------------------------- @@ -171,87 +188,88 @@ and these came close: hashlittle() has to dance around fitting the key bytes into registers. -------------------------------------------------------------------- */ -uint32_t hashword( -const uint32_t *k, /* the key, an array of uint32_t values */ -size_t length, /* the length of the key, in uint32_ts */ -uint32_t initval) /* the previous hash, or an arbitrary value */ +uint32_t hashword(const uint32_t *k, /* the key, an array of uint32_t values */ + size_t length, /* the length of the key, in uint32_ts */ + uint32_t initval) /* the previous hash, or an arbitrary value */ { - uint32_t a,b,c; - - /* Set up the internal state */ - a = b = c = 0xdeadbeef + (((uint32_t)length)<<2) + initval; - - /*------------------------------------------------- handle most of the key */ - while (length > 3) - { - a += k[0]; - b += k[1]; - c += k[2]; - mix(a,b,c); - length -= 3; - k += 3; - } - - /*------------------------------------------- handle the last 3 uint32_t's */ - switch(length) /* all the case statements fall through */ - { - case 3 : c+=k[2]; /* fall through */ - case 2 : b+=k[1]; /* fall through */ - case 1 : a+=k[0]; - final(a,b,c); /* fall through */ - case 0: /* case 0: nothing left to add */ - break; - } - /*------------------------------------------------------ report the result */ - return c; -} + uint32_t a, b, c; + + /* Set up the internal state */ + a = b = c = 0xdeadbeef + (((uint32_t)length) << 2) + initval; + + /*------------------------------------------------- handle most of the key */ + while (length > 3) { + a += k[0]; + b += k[1]; + c += k[2]; + mix(a, b, c); + length -= 3; + k += 3; + } + /*------------------------------------------- handle the last 3 uint32_t's */ + switch (length) /* all the case statements fall through */ + { + case 3: + c += k[2]; /* fall through */ + case 2: + b += k[1]; /* fall through */ + case 1: + a += k[0]; + final(a, b, c); /* fall through */ + case 0: /* case 0: nothing left to add */ + break; + } + /*------------------------------------------------------ report the result */ + return c; +} /* -------------------------------------------------------------------- hashword2() -- same as hashword(), but take two seeds and return two 32-bit values. pc and pb must both be nonnull, and *pc and *pb must -both be initialized with seeds. If you pass in (*pb)==0, the output +both be initialized with seeds. If you pass in (*pb)==0, the output (*pc) will be the same as the return value from hashword(). -------------------------------------------------------------------- */ -void hashword2 ( -const uint32_t *k, /* the key, an array of uint32_t values */ -size_t length, /* the length of the key, in uint32_ts */ -uint32_t *pc, /* IN: seed OUT: primary hash value */ -uint32_t *pb) /* IN: more seed OUT: secondary hash value */ +void hashword2(const uint32_t *k, /* the key, an array of uint32_t values */ + size_t length, /* the length of the key, in uint32_ts */ + uint32_t *pc, /* IN: seed OUT: primary hash value */ + uint32_t *pb) /* IN: more seed OUT: secondary hash value */ { - uint32_t a,b,c; - - /* Set up the internal state */ - a = b = c = 0xdeadbeef + ((uint32_t)(length<<2)) + *pc; - c += *pb; - - /*------------------------------------------------- handle most of the key */ - while (length > 3) - { - a += k[0]; - b += k[1]; - c += k[2]; - mix(a,b,c); - length -= 3; - k += 3; - } - - /*------------------------------------------- handle the last 3 uint32_t's */ - switch(length) /* all the case statements fall through */ - { - case 3 : c+=k[2]; /* fall through */ - case 2 : b+=k[1]; /* fall through */ - case 1 : a+=k[0]; - final(a,b,c); /* fall through */ - case 0: /* case 0: nothing left to add */ - break; - } - /*------------------------------------------------------ report the result */ - *pc=c; *pb=b; -} + uint32_t a, b, c; + + /* Set up the internal state */ + a = b = c = 0xdeadbeef + ((uint32_t)(length << 2)) + *pc; + c += *pb; + + /*------------------------------------------------- handle most of the key */ + while (length > 3) { + a += k[0]; + b += k[1]; + c += k[2]; + mix(a, b, c); + length -= 3; + k += 3; + } + /*------------------------------------------- handle the last 3 uint32_t's */ + switch (length) /* all the case statements fall through */ + { + case 3: + c += k[2]; /* fall through */ + case 2: + b += k[1]; /* fall through */ + case 1: + a += k[0]; + final(a, b, c); /* fall through */ + case 0: /* case 0: nothing left to add */ + break; + } + /*------------------------------------------------------ report the result */ + *pc = c; + *pb = b; +} /* ------------------------------------------------------------------------------- @@ -280,176 +298,255 @@ acceptable. Do NOT use for cryptographic purposes. ------------------------------------------------------------------------------- */ -uint32_t hashlittle( const void *key, size_t length, uint32_t initval) +uint32_t hashlittle(const void *key, size_t length, uint32_t initval) { - uint32_t a,b,c; /* internal state */ - union { const void *ptr; size_t i; } u; /* needed for Mac Powerbook G4 */ - - /* Set up the internal state */ - a = b = c = 0xdeadbeef + ((uint32_t)length) + initval; - - u.ptr = key; - if (HASH_LITTLE_ENDIAN && ((u.i & 0x3) == 0)) { - const uint32_t *k = (const uint32_t *)key; /* read 32-bit chunks */ - - /*------ all but last block: aligned reads and affect 32 bits of (a,b,c) */ - while (length > 12) - { - a += k[0]; - b += k[1]; - c += k[2]; - mix(a,b,c); - length -= 12; - k += 3; - } - - /*----------------------------- handle the last (probably partial) block */ - /* - * "k[2]&0xffffff" actually reads beyond the end of the string, but - * then masks off the part it's not allowed to read. Because the - * string is aligned, the masked-off tail is in the same word as the - * rest of the string. Every machine with memory protection I've seen - * does it on word boundaries, so is OK with this. But VALGRIND will - * still catch it and complain. The masking trick does make the hash - * noticeably faster for short strings (like English words). - */ + uint32_t a, b, c; /* internal state */ + union { + const void *ptr; + size_t i; + } u; /* needed for Mac Powerbook G4 */ + + /* Set up the internal state */ + a = b = c = 0xdeadbeef + ((uint32_t)length) + initval; + + u.ptr = key; + if (HASH_LITTLE_ENDIAN && ((u.i & 0x3) == 0)) { + const uint32_t *k = (const uint32_t *)key; /* read 32-bit chunks */ + + /*------ all but last block: aligned reads and affect 32 bits of (a,b,c) */ + while (length > 12) { + a += k[0]; + b += k[1]; + c += k[2]; + mix(a, b, c); + length -= 12; + k += 3; + } + + /*----------------------------- handle the last (probably partial) block */ + /* + * "k[2]&0xffffff" actually reads beyond the end of the string, but + * then masks off the part it's not allowed to read. Because the + * string is aligned, the masked-off tail is in the same word as the + * rest of the string. Every machine with memory protection I've seen + * does it on word boundaries, so is OK with this. But VALGRIND will + * still catch it and complain. The masking trick does make the hash + * noticeably faster for short strings (like English words). + */ #ifndef VALGRIND - switch(length) - { - case 12: c+=k[2]; b+=k[1]; a+=k[0]; break; - case 11: c+=k[2]&0xffffff; b+=k[1]; a+=k[0]; break; - case 10: c+=k[2]&0xffff; b+=k[1]; a+=k[0]; break; - case 9 : c+=k[2]&0xff; b+=k[1]; a+=k[0]; break; - case 8 : b+=k[1]; a+=k[0]; break; - case 7 : b+=k[1]&0xffffff; a+=k[0]; break; - case 6 : b+=k[1]&0xffff; a+=k[0]; break; - case 5 : b+=k[1]&0xff; a+=k[0]; break; - case 4 : a+=k[0]; break; - case 3 : a+=k[0]&0xffffff; break; - case 2 : a+=k[0]&0xffff; break; - case 1 : a+=k[0]&0xff; break; - case 0 : return c; /* zero length strings require no mixing */ - } + switch (length) { + case 12: + c += k[2]; + b += k[1]; + a += k[0]; + break; + case 11: + c += k[2] & 0xffffff; + b += k[1]; + a += k[0]; + break; + case 10: + c += k[2] & 0xffff; + b += k[1]; + a += k[0]; + break; + case 9: + c += k[2] & 0xff; + b += k[1]; + a += k[0]; + break; + case 8: + b += k[1]; + a += k[0]; + break; + case 7: + b += k[1] & 0xffffff; + a += k[0]; + break; + case 6: + b += k[1] & 0xffff; + a += k[0]; + break; + case 5: + b += k[1] & 0xff; + a += k[0]; + break; + case 4: + a += k[0]; + break; + case 3: + a += k[0] & 0xffffff; + break; + case 2: + a += k[0] & 0xffff; + break; + case 1: + a += k[0] & 0xff; + break; + case 0: + return c; /* zero length strings require no mixing */ + } #else /* make valgrind happy */ - const uint8_t *k8 = (const uint8_t *)k; - - switch(length) - { - case 12: c+=k[2]; b+=k[1]; a+=k[0]; break; - case 11: c+=((uint32_t)k8[10])<<16; /* fall through */ - case 10: c+=((uint32_t)k8[9])<<8; /* fall through */ - case 9 : c+=k8[8]; /* fall through */ - case 8 : b+=k[1]; a+=k[0]; break; - case 7 : b+=((uint32_t)k8[6])<<16; /* fall through */ - case 6 : b+=((uint32_t)k8[5])<<8; /* fall through */ - case 5 : b+=k8[4]; /* fall through */ - case 4 : a+=k[0]; break; - case 3 : a+=((uint32_t)k8[2])<<16; /* fall through */ - case 2 : a+=((uint32_t)k8[1])<<8; /* fall through */ - case 1 : a+=k8[0]; break; - case 0 : return c; - } + const uint8_t *k8 = (const uint8_t *)k; + + switch (length) { + case 12: + c += k[2]; + b += k[1]; + a += k[0]; + break; + case 11: + c += ((uint32_t)k8[10]) << 16; /* fall through */ + case 10: + c += ((uint32_t)k8[9]) << 8; /* fall through */ + case 9: + c += k8[8]; /* fall through */ + case 8: + b += k[1]; + a += k[0]; + break; + case 7: + b += ((uint32_t)k8[6]) << 16; /* fall through */ + case 6: + b += ((uint32_t)k8[5]) << 8; /* fall through */ + case 5: + b += k8[4]; /* fall through */ + case 4: + a += k[0]; + break; + case 3: + a += ((uint32_t)k8[2]) << 16; /* fall through */ + case 2: + a += ((uint32_t)k8[1]) << 8; /* fall through */ + case 1: + a += k8[0]; + break; + case 0: + return c; + } #endif /* !valgrind */ - } else if (HASH_LITTLE_ENDIAN && ((u.i & 0x1) == 0)) { - const uint16_t *k = (const uint16_t *)key; /* read 16-bit chunks */ - const uint8_t *k8; - - /*--------------- all but last block: aligned reads and different mixing */ - while (length > 12) - { - a += k[0] + (((uint32_t)k[1])<<16); - b += k[2] + (((uint32_t)k[3])<<16); - c += k[4] + (((uint32_t)k[5])<<16); - mix(a,b,c); - length -= 12; - k += 6; - } - - /*----------------------------- handle the last (probably partial) block */ - k8 = (const uint8_t *)k; - switch(length) - { - case 12: c+=k[4]+(((uint32_t)k[5])<<16); - b+=k[2]+(((uint32_t)k[3])<<16); - a+=k[0]+(((uint32_t)k[1])<<16); - break; - case 11: c+=((uint32_t)k8[10])<<16; /* fall through */ - case 10: c+=k[4]; - b+=k[2]+(((uint32_t)k[3])<<16); - a+=k[0]+(((uint32_t)k[1])<<16); - break; - case 9 : c+=k8[8]; /* fall through */ - case 8 : b+=k[2]+(((uint32_t)k[3])<<16); - a+=k[0]+(((uint32_t)k[1])<<16); - break; - case 7 : b+=((uint32_t)k8[6])<<16; /* fall through */ - case 6 : b+=k[2]; - a+=k[0]+(((uint32_t)k[1])<<16); - break; - case 5 : b+=k8[4]; /* fall through */ - case 4 : a+=k[0]+(((uint32_t)k[1])<<16); - break; - case 3 : a+=((uint32_t)k8[2])<<16; /* fall through */ - case 2 : a+=k[0]; - break; - case 1 : a+=k8[0]; - break; - case 0 : return c; /* zero length requires no mixing */ - } - - } else { /* need to read the key one byte at a time */ - const uint8_t *k = (const uint8_t *)key; - - /*--------------- all but the last block: affect some 32 bits of (a,b,c) */ - while (length > 12) - { - a += k[0]; - a += ((uint32_t)k[1])<<8; - a += ((uint32_t)k[2])<<16; - a += ((uint32_t)k[3])<<24; - b += k[4]; - b += ((uint32_t)k[5])<<8; - b += ((uint32_t)k[6])<<16; - b += ((uint32_t)k[7])<<24; - c += k[8]; - c += ((uint32_t)k[9])<<8; - c += ((uint32_t)k[10])<<16; - c += ((uint32_t)k[11])<<24; - mix(a,b,c); - length -= 12; - k += 12; - } - - /*-------------------------------- last block: affect all 32 bits of (c) */ - switch(length) /* all the case statements fall through */ - { - case 12: c+=((uint32_t)k[11])<<24; /* fall through */ - case 11: c+=((uint32_t)k[10])<<16; /* fall through */ - case 10: c+=((uint32_t)k[9])<<8; /* fall through */ - case 9 : c+=k[8]; /* fall through */ - case 8 : b+=((uint32_t)k[7])<<24; /* fall through */ - case 7 : b+=((uint32_t)k[6])<<16; /* fall through */ - case 6 : b+=((uint32_t)k[5])<<8; /* fall through */ - case 5 : b+=k[4]; /* fall through */ - case 4 : a+=((uint32_t)k[3])<<24; /* fall through */ - case 3 : a+=((uint32_t)k[2])<<16; /* fall through */ - case 2 : a+=((uint32_t)k[1])<<8; /* fall through */ - case 1 : a+=k[0]; - break; - case 0 : return c; + } else if (HASH_LITTLE_ENDIAN && ((u.i & 0x1) == 0)) { + const uint16_t *k = (const uint16_t *)key; /* read 16-bit chunks */ + const uint8_t *k8; + + /*--------------- all but last block: aligned reads and different mixing */ + while (length > 12) { + a += k[0] + (((uint32_t)k[1]) << 16); + b += k[2] + (((uint32_t)k[3]) << 16); + c += k[4] + (((uint32_t)k[5]) << 16); + mix(a, b, c); + length -= 12; + k += 6; + } + + /*----------------------------- handle the last (probably partial) block */ + k8 = (const uint8_t *)k; + switch (length) { + case 12: + c += k[4] + (((uint32_t)k[5]) << 16); + b += k[2] + (((uint32_t)k[3]) << 16); + a += k[0] + (((uint32_t)k[1]) << 16); + break; + case 11: + c += ((uint32_t)k8[10]) << 16; /* fall through */ + case 10: + c += k[4]; + b += k[2] + (((uint32_t)k[3]) << 16); + a += k[0] + (((uint32_t)k[1]) << 16); + break; + case 9: + c += k8[8]; /* fall through */ + case 8: + b += k[2] + (((uint32_t)k[3]) << 16); + a += k[0] + (((uint32_t)k[1]) << 16); + break; + case 7: + b += ((uint32_t)k8[6]) << 16; /* fall through */ + case 6: + b += k[2]; + a += k[0] + (((uint32_t)k[1]) << 16); + break; + case 5: + b += k8[4]; /* fall through */ + case 4: + a += k[0] + (((uint32_t)k[1]) << 16); + break; + case 3: + a += ((uint32_t)k8[2]) << 16; /* fall through */ + case 2: + a += k[0]; + break; + case 1: + a += k8[0]; + break; + case 0: + return c; /* zero length requires no mixing */ + } + + } else { /* need to read the key one byte at a time */ + const uint8_t *k = (const uint8_t *)key; + + /*--------------- all but the last block: affect some 32 bits of (a,b,c) */ + while (length > 12) { + a += k[0]; + a += ((uint32_t)k[1]) << 8; + a += ((uint32_t)k[2]) << 16; + a += ((uint32_t)k[3]) << 24; + b += k[4]; + b += ((uint32_t)k[5]) << 8; + b += ((uint32_t)k[6]) << 16; + b += ((uint32_t)k[7]) << 24; + c += k[8]; + c += ((uint32_t)k[9]) << 8; + c += ((uint32_t)k[10]) << 16; + c += ((uint32_t)k[11]) << 24; + mix(a, b, c); + length -= 12; + k += 12; + } + + /*-------------------------------- last block: affect all 32 bits of (c) */ + switch (length) /* all the case statements fall through */ + { + case 12: + c += ((uint32_t)k[11]) << 24; /* fall through */ + case 11: + c += ((uint32_t)k[10]) << 16; /* fall through */ + case 10: + c += ((uint32_t)k[9]) << 8; /* fall through */ + case 9: + c += k[8]; /* fall through */ + case 8: + b += ((uint32_t)k[7]) << 24; /* fall through */ + case 7: + b += ((uint32_t)k[6]) << 16; /* fall through */ + case 6: + b += ((uint32_t)k[5]) << 8; /* fall through */ + case 5: + b += k[4]; /* fall through */ + case 4: + a += ((uint32_t)k[3]) << 24; /* fall through */ + case 3: + a += ((uint32_t)k[2]) << 16; /* fall through */ + case 2: + a += ((uint32_t)k[1]) << 8; /* fall through */ + case 1: + a += k[0]; + break; + case 0: + return c; + } } - } - final(a,b,c); - return c; + final(a, b, c); + return c; } - /* ------------------------------------------------------------------------------- hashlittle_safe() -- hash a variable-length key into a 32-bit value @@ -483,147 +580,190 @@ acceptable. Do NOT use for cryptographic purposes. uint32_t hashlittle_safe(const void *key, size_t length, uint32_t initval) { - uint32_t a,b,c; /* internal state */ - union { const void *ptr; size_t i; } u; /* needed for Mac Powerbook G4 */ - - /* Set up the internal state */ - a = b = c = 0xdeadbeef + ((uint32_t)length) + initval; - - u.ptr = key; - if (HASH_LITTLE_ENDIAN && ((u.i & 0x3) == 0)) { - const uint32_t *k = (const uint32_t *)key; /* read 32-bit chunks */ - - /*------ all but last block: aligned reads and affect 32 bits of (a,b,c) */ - while (length > 12) - { - a += k[0]; - b += k[1]; - c += k[2]; - mix(a,b,c); - length -= 12; - k += 3; - } - - /*----------------------------- handle the last (probably partial) block */ - /* - * Note that unlike hashlittle() above, we use the "safe" version of this - * block that is #ifdef VALGRIND above, in order to avoid warnings from - * Valgrind or Address Sanitizer. - */ - - const uint8_t *k8 = (const uint8_t *)k; - - switch(length) - { - case 12: c+=k[2]; b+=k[1]; a+=k[0]; break; - case 11: c+=((uint32_t)k8[10])<<16; /* fall through */ - case 10: c+=((uint32_t)k8[9])<<8; /* fall through */ - case 9 : c+=k8[8]; /* fall through */ - case 8 : b+=k[1]; a+=k[0]; break; - case 7 : b+=((uint32_t)k8[6])<<16; /* fall through */ - case 6 : b+=((uint32_t)k8[5])<<8; /* fall through */ - case 5 : b+=k8[4]; /* fall through */ - case 4 : a+=k[0]; break; - case 3 : a+=((uint32_t)k8[2])<<16; /* fall through */ - case 2 : a+=((uint32_t)k8[1])<<8; /* fall through */ - case 1 : a+=k8[0]; break; - case 0 : return c; - } - } else if (HASH_LITTLE_ENDIAN && ((u.i & 0x1) == 0)) { - const uint16_t *k = (const uint16_t *)key; /* read 16-bit chunks */ - const uint8_t *k8; - - /*--------------- all but last block: aligned reads and different mixing */ - while (length > 12) - { - a += k[0] + (((uint32_t)k[1])<<16); - b += k[2] + (((uint32_t)k[3])<<16); - c += k[4] + (((uint32_t)k[5])<<16); - mix(a,b,c); - length -= 12; - k += 6; - } - - /*----------------------------- handle the last (probably partial) block */ - k8 = (const uint8_t *)k; - switch(length) - { - case 12: c+=k[4]+(((uint32_t)k[5])<<16); - b+=k[2]+(((uint32_t)k[3])<<16); - a+=k[0]+(((uint32_t)k[1])<<16); - break; - case 11: c+=((uint32_t)k8[10])<<16; /* fall through */ - case 10: c+=k[4]; - b+=k[2]+(((uint32_t)k[3])<<16); - a+=k[0]+(((uint32_t)k[1])<<16); - break; - case 9 : c+=k8[8]; /* fall through */ - case 8 : b+=k[2]+(((uint32_t)k[3])<<16); - a+=k[0]+(((uint32_t)k[1])<<16); - break; - case 7 : b+=((uint32_t)k8[6])<<16; /* fall through */ - case 6 : b+=k[2]; - a+=k[0]+(((uint32_t)k[1])<<16); - break; - case 5 : b+=k8[4]; /* fall through */ - case 4 : a+=k[0]+(((uint32_t)k[1])<<16); - break; - case 3 : a+=((uint32_t)k8[2])<<16; /* fall through */ - case 2 : a+=k[0]; - break; - case 1 : a+=k8[0]; - break; - case 0 : return c; /* zero length requires no mixing */ - } - - } else { /* need to read the key one byte at a time */ - const uint8_t *k = (const uint8_t *)key; - - /*--------------- all but the last block: affect some 32 bits of (a,b,c) */ - while (length > 12) - { - a += k[0]; - a += ((uint32_t)k[1])<<8; - a += ((uint32_t)k[2])<<16; - a += ((uint32_t)k[3])<<24; - b += k[4]; - b += ((uint32_t)k[5])<<8; - b += ((uint32_t)k[6])<<16; - b += ((uint32_t)k[7])<<24; - c += k[8]; - c += ((uint32_t)k[9])<<8; - c += ((uint32_t)k[10])<<16; - c += ((uint32_t)k[11])<<24; - mix(a,b,c); - length -= 12; - k += 12; + uint32_t a, b, c; /* internal state */ + union { + const void *ptr; + size_t i; + } u; /* needed for Mac Powerbook G4 */ + + /* Set up the internal state */ + a = b = c = 0xdeadbeef + ((uint32_t)length) + initval; + + u.ptr = key; + if (HASH_LITTLE_ENDIAN && ((u.i & 0x3) == 0)) { + const uint32_t *k = (const uint32_t *)key; /* read 32-bit chunks */ + + /*------ all but last block: aligned reads and affect 32 bits of (a,b,c) */ + while (length > 12) { + a += k[0]; + b += k[1]; + c += k[2]; + mix(a, b, c); + length -= 12; + k += 3; + } + + /*----------------------------- handle the last (probably partial) block */ + /* + * Note that unlike hashlittle() above, we use the "safe" version of this + * block that is #ifdef VALGRIND above, in order to avoid warnings from + * Valgrind or Address Sanitizer. + */ + + const uint8_t *k8 = (const uint8_t *)k; + + switch (length) { + case 12: + c += k[2]; + b += k[1]; + a += k[0]; + break; + case 11: + c += ((uint32_t)k8[10]) << 16; /* fall through */ + case 10: + c += ((uint32_t)k8[9]) << 8; /* fall through */ + case 9: + c += k8[8]; /* fall through */ + case 8: + b += k[1]; + a += k[0]; + break; + case 7: + b += ((uint32_t)k8[6]) << 16; /* fall through */ + case 6: + b += ((uint32_t)k8[5]) << 8; /* fall through */ + case 5: + b += k8[4]; /* fall through */ + case 4: + a += k[0]; + break; + case 3: + a += ((uint32_t)k8[2]) << 16; /* fall through */ + case 2: + a += ((uint32_t)k8[1]) << 8; /* fall through */ + case 1: + a += k8[0]; + break; + case 0: + return c; + } + } else if (HASH_LITTLE_ENDIAN && ((u.i & 0x1) == 0)) { + const uint16_t *k = (const uint16_t *)key; /* read 16-bit chunks */ + const uint8_t *k8; + + /*--------------- all but last block: aligned reads and different mixing */ + while (length > 12) { + a += k[0] + (((uint32_t)k[1]) << 16); + b += k[2] + (((uint32_t)k[3]) << 16); + c += k[4] + (((uint32_t)k[5]) << 16); + mix(a, b, c); + length -= 12; + k += 6; + } + + /*----------------------------- handle the last (probably partial) block */ + k8 = (const uint8_t *)k; + switch (length) { + case 12: + c += k[4] + (((uint32_t)k[5]) << 16); + b += k[2] + (((uint32_t)k[3]) << 16); + a += k[0] + (((uint32_t)k[1]) << 16); + break; + case 11: + c += ((uint32_t)k8[10]) << 16; /* fall through */ + case 10: + c += k[4]; + b += k[2] + (((uint32_t)k[3]) << 16); + a += k[0] + (((uint32_t)k[1]) << 16); + break; + case 9: + c += k8[8]; /* fall through */ + case 8: + b += k[2] + (((uint32_t)k[3]) << 16); + a += k[0] + (((uint32_t)k[1]) << 16); + break; + case 7: + b += ((uint32_t)k8[6]) << 16; /* fall through */ + case 6: + b += k[2]; + a += k[0] + (((uint32_t)k[1]) << 16); + break; + case 5: + b += k8[4]; /* fall through */ + case 4: + a += k[0] + (((uint32_t)k[1]) << 16); + break; + case 3: + a += ((uint32_t)k8[2]) << 16; /* fall through */ + case 2: + a += k[0]; + break; + case 1: + a += k8[0]; + break; + case 0: + return c; /* zero length requires no mixing */ + } + + } else { /* need to read the key one byte at a time */ + const uint8_t *k = (const uint8_t *)key; + + /*--------------- all but the last block: affect some 32 bits of (a,b,c) */ + while (length > 12) { + a += k[0]; + a += ((uint32_t)k[1]) << 8; + a += ((uint32_t)k[2]) << 16; + a += ((uint32_t)k[3]) << 24; + b += k[4]; + b += ((uint32_t)k[5]) << 8; + b += ((uint32_t)k[6]) << 16; + b += ((uint32_t)k[7]) << 24; + c += k[8]; + c += ((uint32_t)k[9]) << 8; + c += ((uint32_t)k[10]) << 16; + c += ((uint32_t)k[11]) << 24; + mix(a, b, c); + length -= 12; + k += 12; + } + + /*-------------------------------- last block: affect all 32 bits of (c) */ + switch (length) /* all the case statements fall through */ + { + case 12: + c += ((uint32_t)k[11]) << 24; /* fall through */ + case 11: + c += ((uint32_t)k[10]) << 16; /* fall through */ + case 10: + c += ((uint32_t)k[9]) << 8; /* fall through */ + case 9: + c += k[8]; /* fall through */ + case 8: + b += ((uint32_t)k[7]) << 24; /* fall through */ + case 7: + b += ((uint32_t)k[6]) << 16; /* fall through */ + case 6: + b += ((uint32_t)k[5]) << 8; /* fall through */ + case 5: + b += k[4]; /* fall through */ + case 4: + a += ((uint32_t)k[3]) << 24; /* fall through */ + case 3: + a += ((uint32_t)k[2]) << 16; /* fall through */ + case 2: + a += ((uint32_t)k[1]) << 8; /* fall through */ + case 1: + a += k[0]; + break; + case 0: + return c; + } } - /*-------------------------------- last block: affect all 32 bits of (c) */ - switch(length) /* all the case statements fall through */ - { - case 12: c+=((uint32_t)k[11])<<24; /* fall through */ - case 11: c+=((uint32_t)k[10])<<16; /* fall through */ - case 10: c+=((uint32_t)k[9])<<8; /* fall through */ - case 9 : c+=k[8]; /* fall through */ - case 8 : b+=((uint32_t)k[7])<<24; /* fall through */ - case 7 : b+=((uint32_t)k[6])<<16; /* fall through */ - case 6 : b+=((uint32_t)k[5])<<8; /* fall through */ - case 5 : b+=k[4]; /* fall through */ - case 4 : a+=((uint32_t)k[3])<<24; /* fall through */ - case 3 : a+=((uint32_t)k[2])<<16; /* fall through */ - case 2 : a+=((uint32_t)k[1])<<8; /* fall through */ - case 1 : a+=k[0]; - break; - case 0 : return c; - } - } - - final(a,b,c); - return c; + final(a, b, c); + return c; } - /* * hashlittle2: return 2 32-bit hash values * @@ -634,542 +774,693 @@ uint32_t hashlittle_safe(const void *key, size_t length, uint32_t initval) * the key. *pc is better mixed than *pb, so use *pc first. If you want * a 64-bit value do something like "*pc + (((uint64_t)*pb)<<32)". */ -void hashlittle2( - const void *key, /* the key to hash */ - size_t length, /* length of the key */ - uint32_t *pc, /* IN: primary initval, OUT: primary hash */ - uint32_t *pb) /* IN: secondary initval, OUT: secondary hash */ +void hashlittle2(const void *key, /* the key to hash */ + size_t length, /* length of the key */ + uint32_t *pc, /* IN: primary initval, OUT: primary hash */ + uint32_t *pb) /* IN: secondary initval, OUT: secondary hash */ { - uint32_t a,b,c; /* internal state */ - union { const void *ptr; size_t i; } u; /* needed for Mac Powerbook G4 */ - - /* Set up the internal state */ - a = b = c = 0xdeadbeef + ((uint32_t)length) + *pc; - c += *pb; - - u.ptr = key; - if (HASH_LITTLE_ENDIAN && ((u.i & 0x3) == 0)) { - const uint32_t *k = (const uint32_t *)key; /* read 32-bit chunks */ - - /*------ all but last block: aligned reads and affect 32 bits of (a,b,c) */ - while (length > 12) - { - a += k[0]; - b += k[1]; - c += k[2]; - mix(a,b,c); - length -= 12; - k += 3; - } - - /*----------------------------- handle the last (probably partial) block */ - /* - * "k[2]&0xffffff" actually reads beyond the end of the string, but - * then masks off the part it's not allowed to read. Because the - * string is aligned, the masked-off tail is in the same word as the - * rest of the string. Every machine with memory protection I've seen - * does it on word boundaries, so is OK with this. But VALGRIND will - * still catch it and complain. The masking trick does make the hash - * noticeably faster for short strings (like English words). - */ + uint32_t a, b, c; /* internal state */ + union { + const void *ptr; + size_t i; + } u; /* needed for Mac Powerbook G4 */ + + /* Set up the internal state */ + a = b = c = 0xdeadbeef + ((uint32_t)length) + *pc; + c += *pb; + + u.ptr = key; + if (HASH_LITTLE_ENDIAN && ((u.i & 0x3) == 0)) { + const uint32_t *k = (const uint32_t *)key; /* read 32-bit chunks */ + + /*------ all but last block: aligned reads and affect 32 bits of (a,b,c) */ + while (length > 12) { + a += k[0]; + b += k[1]; + c += k[2]; + mix(a, b, c); + length -= 12; + k += 3; + } + + /*----------------------------- handle the last (probably partial) block */ + /* + * "k[2]&0xffffff" actually reads beyond the end of the string, but + * then masks off the part it's not allowed to read. Because the + * string is aligned, the masked-off tail is in the same word as the + * rest of the string. Every machine with memory protection I've seen + * does it on word boundaries, so is OK with this. But VALGRIND will + * still catch it and complain. The masking trick does make the hash + * noticeably faster for short strings (like English words). + */ #ifndef VALGRIND - switch(length) - { - case 12: c+=k[2]; b+=k[1]; a+=k[0]; break; - case 11: c+=k[2]&0xffffff; b+=k[1]; a+=k[0]; break; - case 10: c+=k[2]&0xffff; b+=k[1]; a+=k[0]; break; - case 9 : c+=k[2]&0xff; b+=k[1]; a+=k[0]; break; - case 8 : b+=k[1]; a+=k[0]; break; - case 7 : b+=k[1]&0xffffff; a+=k[0]; break; - case 6 : b+=k[1]&0xffff; a+=k[0]; break; - case 5 : b+=k[1]&0xff; a+=k[0]; break; - case 4 : a+=k[0]; break; - case 3 : a+=k[0]&0xffffff; break; - case 2 : a+=k[0]&0xffff; break; - case 1 : a+=k[0]&0xff; break; - case 0 : *pc=c; *pb=b; return; /* zero length strings require no mixing */ - } + switch (length) { + case 12: + c += k[2]; + b += k[1]; + a += k[0]; + break; + case 11: + c += k[2] & 0xffffff; + b += k[1]; + a += k[0]; + break; + case 10: + c += k[2] & 0xffff; + b += k[1]; + a += k[0]; + break; + case 9: + c += k[2] & 0xff; + b += k[1]; + a += k[0]; + break; + case 8: + b += k[1]; + a += k[0]; + break; + case 7: + b += k[1] & 0xffffff; + a += k[0]; + break; + case 6: + b += k[1] & 0xffff; + a += k[0]; + break; + case 5: + b += k[1] & 0xff; + a += k[0]; + break; + case 4: + a += k[0]; + break; + case 3: + a += k[0] & 0xffffff; + break; + case 2: + a += k[0] & 0xffff; + break; + case 1: + a += k[0] & 0xff; + break; + case 0: + *pc = c; + *pb = b; + return; /* zero length strings require no mixing */ + } #else /* make valgrind happy */ - const uint8_t *k8 = (const uint8_t *)k; - switch(length) - { - case 12: c+=k[2]; b+=k[1]; a+=k[0]; break; - case 11: c+=((uint32_t)k8[10])<<16; /* fall through */ - case 10: c+=((uint32_t)k8[9])<<8; /* fall through */ - case 9 : c+=k8[8]; /* fall through */ - case 8 : b+=k[1]; a+=k[0]; break; - case 7 : b+=((uint32_t)k8[6])<<16; /* fall through */ - case 6 : b+=((uint32_t)k8[5])<<8; /* fall through */ - case 5 : b+=k8[4]; /* fall through */ - case 4 : a+=k[0]; break; - case 3 : a+=((uint32_t)k8[2])<<16; /* fall through */ - case 2 : a+=((uint32_t)k8[1])<<8; /* fall through */ - case 1 : a+=k8[0]; break; - case 0 : *pc=c; *pb=b; return; /* zero length strings require no mixing */ - } + const uint8_t *k8 = (const uint8_t *)k; + switch (length) { + case 12: + c += k[2]; + b += k[1]; + a += k[0]; + break; + case 11: + c += ((uint32_t)k8[10]) << 16; /* fall through */ + case 10: + c += ((uint32_t)k8[9]) << 8; /* fall through */ + case 9: + c += k8[8]; /* fall through */ + case 8: + b += k[1]; + a += k[0]; + break; + case 7: + b += ((uint32_t)k8[6]) << 16; /* fall through */ + case 6: + b += ((uint32_t)k8[5]) << 8; /* fall through */ + case 5: + b += k8[4]; /* fall through */ + case 4: + a += k[0]; + break; + case 3: + a += ((uint32_t)k8[2]) << 16; /* fall through */ + case 2: + a += ((uint32_t)k8[1]) << 8; /* fall through */ + case 1: + a += k8[0]; + break; + case 0: + *pc = c; + *pb = b; + return; /* zero length strings require no mixing */ + } #endif /* !valgrind */ - } else if (HASH_LITTLE_ENDIAN && ((u.i & 0x1) == 0)) { - const uint16_t *k = (const uint16_t *)key; /* read 16-bit chunks */ - const uint8_t *k8; - - /*--------------- all but last block: aligned reads and different mixing */ - while (length > 12) - { - a += k[0] + (((uint32_t)k[1])<<16); - b += k[2] + (((uint32_t)k[3])<<16); - c += k[4] + (((uint32_t)k[5])<<16); - mix(a,b,c); - length -= 12; - k += 6; - } - - /*----------------------------- handle the last (probably partial) block */ - k8 = (const uint8_t *)k; - switch(length) - { - case 12: c+=k[4]+(((uint32_t)k[5])<<16); - b+=k[2]+(((uint32_t)k[3])<<16); - a+=k[0]+(((uint32_t)k[1])<<16); - break; - case 11: c+=((uint32_t)k8[10])<<16; /* fall through */ - case 10: c+=k[4]; - b+=k[2]+(((uint32_t)k[3])<<16); - a+=k[0]+(((uint32_t)k[1])<<16); - break; - case 9 : c+=k8[8]; /* fall through */ - case 8 : b+=k[2]+(((uint32_t)k[3])<<16); - a+=k[0]+(((uint32_t)k[1])<<16); - break; - case 7 : b+=((uint32_t)k8[6])<<16; /* fall through */ - case 6 : b+=k[2]; - a+=k[0]+(((uint32_t)k[1])<<16); - break; - case 5 : b+=k8[4]; /* fall through */ - case 4 : a+=k[0]+(((uint32_t)k[1])<<16); - break; - case 3 : a+=((uint32_t)k8[2])<<16; /* fall through */ - case 2 : a+=k[0]; - break; - case 1 : a+=k8[0]; - break; - case 0 : *pc=c; *pb=b; return; /* zero length strings require no mixing */ - } - - } else { /* need to read the key one byte at a time */ - const uint8_t *k = (const uint8_t *)key; - - /*--------------- all but the last block: affect some 32 bits of (a,b,c) */ - while (length > 12) - { - a += k[0]; - a += ((uint32_t)k[1])<<8; - a += ((uint32_t)k[2])<<16; - a += ((uint32_t)k[3])<<24; - b += k[4]; - b += ((uint32_t)k[5])<<8; - b += ((uint32_t)k[6])<<16; - b += ((uint32_t)k[7])<<24; - c += k[8]; - c += ((uint32_t)k[9])<<8; - c += ((uint32_t)k[10])<<16; - c += ((uint32_t)k[11])<<24; - mix(a,b,c); - length -= 12; - k += 12; - } - - /*-------------------------------- last block: affect all 32 bits of (c) */ - switch(length) /* all the case statements fall through */ - { - case 12: c+=((uint32_t)k[11])<<24; /* fall through */ - case 11: c+=((uint32_t)k[10])<<16; /* fall through */ - case 10: c+=((uint32_t)k[9])<<8; /* fall through */ - case 9 : c+=k[8]; /* fall through */ - case 8 : b+=((uint32_t)k[7])<<24; /* fall through */ - case 7 : b+=((uint32_t)k[6])<<16; /* fall through */ - case 6 : b+=((uint32_t)k[5])<<8; /* fall through */ - case 5 : b+=k[4]; /* fall through */ - case 4 : a+=((uint32_t)k[3])<<24; /* fall through */ - case 3 : a+=((uint32_t)k[2])<<16; /* fall through */ - case 2 : a+=((uint32_t)k[1])<<8; /* fall through */ - case 1 : a+=k[0]; - break; - case 0 : *pc=c; *pb=b; return; /* zero length strings require no mixing */ + } else if (HASH_LITTLE_ENDIAN && ((u.i & 0x1) == 0)) { + const uint16_t *k = (const uint16_t *)key; /* read 16-bit chunks */ + const uint8_t *k8; + + /*--------------- all but last block: aligned reads and different mixing */ + while (length > 12) { + a += k[0] + (((uint32_t)k[1]) << 16); + b += k[2] + (((uint32_t)k[3]) << 16); + c += k[4] + (((uint32_t)k[5]) << 16); + mix(a, b, c); + length -= 12; + k += 6; + } + + /*----------------------------- handle the last (probably partial) block */ + k8 = (const uint8_t *)k; + switch (length) { + case 12: + c += k[4] + (((uint32_t)k[5]) << 16); + b += k[2] + (((uint32_t)k[3]) << 16); + a += k[0] + (((uint32_t)k[1]) << 16); + break; + case 11: + c += ((uint32_t)k8[10]) << 16; /* fall through */ + case 10: + c += k[4]; + b += k[2] + (((uint32_t)k[3]) << 16); + a += k[0] + (((uint32_t)k[1]) << 16); + break; + case 9: + c += k8[8]; /* fall through */ + case 8: + b += k[2] + (((uint32_t)k[3]) << 16); + a += k[0] + (((uint32_t)k[1]) << 16); + break; + case 7: + b += ((uint32_t)k8[6]) << 16; /* fall through */ + case 6: + b += k[2]; + a += k[0] + (((uint32_t)k[1]) << 16); + break; + case 5: + b += k8[4]; /* fall through */ + case 4: + a += k[0] + (((uint32_t)k[1]) << 16); + break; + case 3: + a += ((uint32_t)k8[2]) << 16; /* fall through */ + case 2: + a += k[0]; + break; + case 1: + a += k8[0]; + break; + case 0: + *pc = c; + *pb = b; + return; /* zero length strings require no mixing */ + } + + } else { /* need to read the key one byte at a time */ + const uint8_t *k = (const uint8_t *)key; + + /*--------------- all but the last block: affect some 32 bits of (a,b,c) */ + while (length > 12) { + a += k[0]; + a += ((uint32_t)k[1]) << 8; + a += ((uint32_t)k[2]) << 16; + a += ((uint32_t)k[3]) << 24; + b += k[4]; + b += ((uint32_t)k[5]) << 8; + b += ((uint32_t)k[6]) << 16; + b += ((uint32_t)k[7]) << 24; + c += k[8]; + c += ((uint32_t)k[9]) << 8; + c += ((uint32_t)k[10]) << 16; + c += ((uint32_t)k[11]) << 24; + mix(a, b, c); + length -= 12; + k += 12; + } + + /*-------------------------------- last block: affect all 32 bits of (c) */ + switch (length) /* all the case statements fall through */ + { + case 12: + c += ((uint32_t)k[11]) << 24; /* fall through */ + case 11: + c += ((uint32_t)k[10]) << 16; /* fall through */ + case 10: + c += ((uint32_t)k[9]) << 8; /* fall through */ + case 9: + c += k[8]; /* fall through */ + case 8: + b += ((uint32_t)k[7]) << 24; /* fall through */ + case 7: + b += ((uint32_t)k[6]) << 16; /* fall through */ + case 6: + b += ((uint32_t)k[5]) << 8; /* fall through */ + case 5: + b += k[4]; /* fall through */ + case 4: + a += ((uint32_t)k[3]) << 24; /* fall through */ + case 3: + a += ((uint32_t)k[2]) << 16; /* fall through */ + case 2: + a += ((uint32_t)k[1]) << 8; /* fall through */ + case 1: + a += k[0]; + break; + case 0: + *pc = c; + *pb = b; + return; /* zero length strings require no mixing */ + } } - } - final(a,b,c); - *pc=c; *pb=b; + final(a, b, c); + *pc = c; + *pb = b; } - - /* * hashbig(): * This is the same as hashword() on big-endian machines. It is different * from hashlittle() on all machines. hashbig() takes advantage of - * big-endian byte ordering. + * big-endian byte ordering. */ -uint32_t hashbig( const void *key, size_t length, uint32_t initval) +uint32_t hashbig(const void *key, size_t length, uint32_t initval) { - uint32_t a,b,c; - union { const void *ptr; size_t i; } u; /* to cast key to (size_t) happily */ - - /* Set up the internal state */ - a = b = c = 0xdeadbeef + ((uint32_t)length) + initval; - - u.ptr = key; - if (HASH_BIG_ENDIAN && ((u.i & 0x3) == 0)) { - const uint32_t *k = (const uint32_t *)key; /* read 32-bit chunks */ - - /*------ all but last block: aligned reads and affect 32 bits of (a,b,c) */ - while (length > 12) - { - a += k[0]; - b += k[1]; - c += k[2]; - mix(a,b,c); - length -= 12; - k += 3; - } - - /*----------------------------- handle the last (probably partial) block */ - /* - * "k[2]<<8" actually reads beyond the end of the string, but - * then shifts out the part it's not allowed to read. Because the - * string is aligned, the illegal read is in the same word as the - * rest of the string. Every machine with memory protection I've seen - * does it on word boundaries, so is OK with this. But VALGRIND will - * still catch it and complain. The masking trick does make the hash - * noticeably faster for short strings (like English words). - */ + uint32_t a, b, c; + union { + const void *ptr; + size_t i; + } u; /* to cast key to (size_t) happily */ + + /* Set up the internal state */ + a = b = c = 0xdeadbeef + ((uint32_t)length) + initval; + + u.ptr = key; + if (HASH_BIG_ENDIAN && ((u.i & 0x3) == 0)) { + const uint32_t *k = (const uint32_t *)key; /* read 32-bit chunks */ + + /*------ all but last block: aligned reads and affect 32 bits of (a,b,c) */ + while (length > 12) { + a += k[0]; + b += k[1]; + c += k[2]; + mix(a, b, c); + length -= 12; + k += 3; + } + + /*----------------------------- handle the last (probably partial) block */ + /* + * "k[2]<<8" actually reads beyond the end of the string, but + * then shifts out the part it's not allowed to read. Because the + * string is aligned, the illegal read is in the same word as the + * rest of the string. Every machine with memory protection I've seen + * does it on word boundaries, so is OK with this. But VALGRIND will + * still catch it and complain. The masking trick does make the hash + * noticeably faster for short strings (like English words). + */ #ifndef VALGRIND - switch(length) - { - case 12: c+=k[2]; b+=k[1]; a+=k[0]; break; - case 11: c+=k[2]&0xffffff00; b+=k[1]; a+=k[0]; break; - case 10: c+=k[2]&0xffff0000; b+=k[1]; a+=k[0]; break; - case 9 : c+=k[2]&0xff000000; b+=k[1]; a+=k[0]; break; - case 8 : b+=k[1]; a+=k[0]; break; - case 7 : b+=k[1]&0xffffff00; a+=k[0]; break; - case 6 : b+=k[1]&0xffff0000; a+=k[0]; break; - case 5 : b+=k[1]&0xff000000; a+=k[0]; break; - case 4 : a+=k[0]; break; - case 3 : a+=k[0]&0xffffff00; break; - case 2 : a+=k[0]&0xffff0000; break; - case 1 : a+=k[0]&0xff000000; break; - case 0 : return c; /* zero length strings require no mixing */ - } + switch (length) { + case 12: + c += k[2]; + b += k[1]; + a += k[0]; + break; + case 11: + c += k[2] & 0xffffff00; + b += k[1]; + a += k[0]; + break; + case 10: + c += k[2] & 0xffff0000; + b += k[1]; + a += k[0]; + break; + case 9: + c += k[2] & 0xff000000; + b += k[1]; + a += k[0]; + break; + case 8: + b += k[1]; + a += k[0]; + break; + case 7: + b += k[1] & 0xffffff00; + a += k[0]; + break; + case 6: + b += k[1] & 0xffff0000; + a += k[0]; + break; + case 5: + b += k[1] & 0xff000000; + a += k[0]; + break; + case 4: + a += k[0]; + break; + case 3: + a += k[0] & 0xffffff00; + break; + case 2: + a += k[0] & 0xffff0000; + break; + case 1: + a += k[0] & 0xff000000; + break; + case 0: + return c; /* zero length strings require no mixing */ + } -#else /* make valgrind happy */ +#else /* make valgrind happy */ - const uint8_t *k8 = (const uint8_t *)k; - switch(length) /* all the case statements fall through */ - { - case 12: c+=k[2]; b+=k[1]; a+=k[0]; break; - case 11: c+=((uint32_t)k8[10])<<8; /* fall through */ - case 10: c+=((uint32_t)k8[9])<<16; /* fall through */ - case 9 : c+=((uint32_t)k8[8])<<24; /* fall through */ - case 8 : b+=k[1]; a+=k[0]; break; - case 7 : b+=((uint32_t)k8[6])<<8; /* fall through */ - case 6 : b+=((uint32_t)k8[5])<<16; /* fall through */ - case 5 : b+=((uint32_t)k8[4])<<24; /* fall through */ - case 4 : a+=k[0]; break; - case 3 : a+=((uint32_t)k8[2])<<8; /* fall through */ - case 2 : a+=((uint32_t)k8[1])<<16; /* fall through */ - case 1 : a+=((uint32_t)k8[0])<<24; break; - case 0 : return c; - } + const uint8_t *k8 = (const uint8_t *)k; + switch (length) /* all the case statements fall through */ + { + case 12: + c += k[2]; + b += k[1]; + a += k[0]; + break; + case 11: + c += ((uint32_t)k8[10]) << 8; /* fall through */ + case 10: + c += ((uint32_t)k8[9]) << 16; /* fall through */ + case 9: + c += ((uint32_t)k8[8]) << 24; /* fall through */ + case 8: + b += k[1]; + a += k[0]; + break; + case 7: + b += ((uint32_t)k8[6]) << 8; /* fall through */ + case 6: + b += ((uint32_t)k8[5]) << 16; /* fall through */ + case 5: + b += ((uint32_t)k8[4]) << 24; /* fall through */ + case 4: + a += k[0]; + break; + case 3: + a += ((uint32_t)k8[2]) << 8; /* fall through */ + case 2: + a += ((uint32_t)k8[1]) << 16; /* fall through */ + case 1: + a += ((uint32_t)k8[0]) << 24; + break; + case 0: + return c; + } #endif /* !VALGRIND */ - } else { /* need to read the key one byte at a time */ - const uint8_t *k = (const uint8_t *)key; - - /*--------------- all but the last block: affect some 32 bits of (a,b,c) */ - while (length > 12) - { - a += ((uint32_t)k[0])<<24; - a += ((uint32_t)k[1])<<16; - a += ((uint32_t)k[2])<<8; - a += ((uint32_t)k[3]); - b += ((uint32_t)k[4])<<24; - b += ((uint32_t)k[5])<<16; - b += ((uint32_t)k[6])<<8; - b += ((uint32_t)k[7]); - c += ((uint32_t)k[8])<<24; - c += ((uint32_t)k[9])<<16; - c += ((uint32_t)k[10])<<8; - c += ((uint32_t)k[11]); - mix(a,b,c); - length -= 12; - k += 12; + } else { /* need to read the key one byte at a time */ + const uint8_t *k = (const uint8_t *)key; + + /*--------------- all but the last block: affect some 32 bits of (a,b,c) */ + while (length > 12) { + a += ((uint32_t)k[0]) << 24; + a += ((uint32_t)k[1]) << 16; + a += ((uint32_t)k[2]) << 8; + a += ((uint32_t)k[3]); + b += ((uint32_t)k[4]) << 24; + b += ((uint32_t)k[5]) << 16; + b += ((uint32_t)k[6]) << 8; + b += ((uint32_t)k[7]); + c += ((uint32_t)k[8]) << 24; + c += ((uint32_t)k[9]) << 16; + c += ((uint32_t)k[10]) << 8; + c += ((uint32_t)k[11]); + mix(a, b, c); + length -= 12; + k += 12; + } + + /*-------------------------------- last block: affect all 32 bits of (c) */ + switch (length) /* all the case statements fall through */ + { + case 12: + c += k[11]; /* fall through */ + case 11: + c += ((uint32_t)k[10]) << 8; /* fall through */ + case 10: + c += ((uint32_t)k[9]) << 16; /* fall through */ + case 9: + c += ((uint32_t)k[8]) << 24; /* fall through */ + case 8: + b += k[7]; /* fall through */ + case 7: + b += ((uint32_t)k[6]) << 8; /* fall through */ + case 6: + b += ((uint32_t)k[5]) << 16; /* fall through */ + case 5: + b += ((uint32_t)k[4]) << 24; /* fall through */ + case 4: + a += k[3]; /* fall through */ + case 3: + a += ((uint32_t)k[2]) << 8; /* fall through */ + case 2: + a += ((uint32_t)k[1]) << 16; /* fall through */ + case 1: + a += ((uint32_t)k[0]) << 24; + break; + case 0: + return c; + } } - /*-------------------------------- last block: affect all 32 bits of (c) */ - switch(length) /* all the case statements fall through */ - { - case 12: c+=k[11]; /* fall through */ - case 11: c+=((uint32_t)k[10])<<8; /* fall through */ - case 10: c+=((uint32_t)k[9])<<16; /* fall through */ - case 9 : c+=((uint32_t)k[8])<<24; /* fall through */ - case 8 : b+=k[7]; /* fall through */ - case 7 : b+=((uint32_t)k[6])<<8; /* fall through */ - case 6 : b+=((uint32_t)k[5])<<16; /* fall through */ - case 5 : b+=((uint32_t)k[4])<<24; /* fall through */ - case 4 : a+=k[3]; /* fall through */ - case 3 : a+=((uint32_t)k[2])<<8; /* fall through */ - case 2 : a+=((uint32_t)k[1])<<16; /* fall through */ - case 1 : a+=((uint32_t)k[0])<<24; - break; - case 0 : return c; - } - } - - final(a,b,c); - return c; + final(a, b, c); + return c; } - #ifdef SELF_TEST /* used for timings */ void driver1(void) { - uint8_t buf[256]; - uint32_t i; - uint32_t h=0; - time_t a,z; - - time(&a); - for (i=0; i<256; ++i) buf[i] = 'x'; - for (i=0; i<1; ++i) - { - h = hashlittle(&buf[0],1,h); - } - time(&z); - if (z-a > 0) printf("time %d %.8x\n", z-a, h); + uint8_t buf[256]; + uint32_t i; + uint32_t h = 0; + time_t a, z; + + time(&a); + for (i = 0; i < 256; ++i) + buf[i] = 'x'; + for (i = 0; i < 1; ++i) { + h = hashlittle(&buf[0], 1, h); + } + time(&z); + if (z - a > 0) + printf("time %d %.8x\n", z - a, h); } /* check that every input bit changes every output bit half the time */ #define HASHSTATE 1 #define HASHLEN 1 -#define MAXPAIR 60 -#define MAXLEN 70 +#define MAXPAIR 60 +#define MAXLEN 70 void driver2(void) { - uint8_t qa[MAXLEN+1], qb[MAXLEN+2], *a = &qa[0], *b = &qb[1]; - uint32_t c[HASHSTATE], d[HASHSTATE], i=0, j=0, k, l, m=0, z; - uint32_t e[HASHSTATE],f[HASHSTATE],g[HASHSTATE],h[HASHSTATE]; - uint32_t x[HASHSTATE],y[HASHSTATE]; - uint32_t hlen; - - printf("No more than %d trials should ever be needed \n",MAXPAIR/2); - for (hlen=0; hlen < MAXLEN; ++hlen) - { - z=0; - for (i=0; i> (8 - j)); - c[0] = hashlittle(a, hlen, m); - b[i] ^= ((k + 1) << j); - b[i] ^= ((k + 1) >> (8 - j)); - d[0] = hashlittle(b, hlen, m); - /* check every bit is 1, 0, set, and not set at least once */ - for (l = 0; l < HASHSTATE; ++l) { - e[l] &= (c[l] ^ d[l]); - f[l] &= ~(c[l] ^ d[l]); - g[l] &= c[l]; - h[l] &= ~c[l]; - x[l] &= d[l]; - y[l] &= ~d[l]; - if (e[l] | f[l] | g[l] | h[l] | x[l] | y[l]) - finished = 0; - } - if (finished) - break; - } - if (k > z) - z = k; - if (k == MAXPAIR) { - printf("Some bit didn't change: "); - printf("%.8x %.8x %.8x %.8x %.8x %.8x ", e[0], f[0], g[0], h[0], x[0], y[0]); - printf("i %d j %d m %d len %d\n", i, j, m, hlen); - } - if (z == MAXPAIR) - goto done; - } - } + uint8_t qa[MAXLEN + 1], qb[MAXLEN + 2], *a = &qa[0], *b = &qb[1]; + uint32_t c[HASHSTATE], d[HASHSTATE], i = 0, j = 0, k, l, m = 0, z; + uint32_t e[HASHSTATE], f[HASHSTATE], g[HASHSTATE], h[HASHSTATE]; + uint32_t x[HASHSTATE], y[HASHSTATE]; + uint32_t hlen; + + printf("No more than %d trials should ever be needed \n", MAXPAIR / 2); + for (hlen = 0; hlen < MAXLEN; ++hlen) { + z = 0; + for (i = 0; i < hlen; ++i) /*----------------------- for each input byte, */ + { + for (j = 0; j < 8; ++j) /*------------------------ for each input bit, */ + { + for (m = 1; m < 8; ++m) /*------------ for several possible initvals, */ + { + for (l = 0; l < HASHSTATE; ++l) + e[l] = f[l] = g[l] = h[l] = x[l] = y[l] = ~((uint32_t)0); + + /*---- check that every output bit is affected by that input bit */ + for (k = 0; k < MAXPAIR; k += 2) { + uint32_t finished = 1; + /* keys have one bit different */ + for (l = 0; l < hlen + 1; ++l) { + a[l] = b[l] = (uint8_t)0; + } + /* have a and b be two keys differing in only one bit */ + a[i] ^= (k << j); + a[i] ^= (k >> (8 - j)); + c[0] = hashlittle(a, hlen, m); + b[i] ^= ((k + 1) << j); + b[i] ^= ((k + 1) >> (8 - j)); + d[0] = hashlittle(b, hlen, m); + /* check every bit is 1, 0, set, and not set at least once */ + for (l = 0; l < HASHSTATE; ++l) { + e[l] &= (c[l] ^ d[l]); + f[l] &= ~(c[l] ^ d[l]); + g[l] &= c[l]; + h[l] &= ~c[l]; + x[l] &= d[l]; + y[l] &= ~d[l]; + if (e[l] | f[l] | g[l] | h[l] | x[l] | y[l]) + finished = 0; + } + if (finished) + break; + } + if (k > z) + z = k; + if (k == MAXPAIR) { + printf("Some bit didn't change: "); + printf("%.8x %.8x %.8x %.8x %.8x %.8x ", e[0], f[0], g[0], h[0], x[0], + y[0]); + printf("i %d j %d m %d len %d\n", i, j, m, hlen); + } + if (z == MAXPAIR) + goto done; + } + } + } + done: + if (z < MAXPAIR) { + printf("Mix success %2d bytes %2d initvals ", i, m); + printf("required %d trials\n", z / 2); + } } - done: - if (z < MAXPAIR) - { - printf("Mix success %2d bytes %2d initvals ",i,m); - printf("required %d trials\n", z/2); - } - } - printf("\n"); + printf("\n"); } /* Check for reading beyond the end of the buffer and alignment problems */ void driver3(void) { - uint8_t buf[MAXLEN+20], *b; - uint32_t len; - uint8_t q[] = "This is the time for all good men to come to the aid of their country..."; - uint32_t h; - uint8_t qq[] = "xThis is the time for all good men to come to the aid of their country..."; - uint32_t i; - uint8_t qqq[] = "xxThis is the time for all good men to come to the aid of their country..."; - uint32_t j; - uint8_t qqqq[] = "xxxThis is the time for all good men to come to the aid of their country..."; - uint32_t ref,x,y; - uint8_t *p; - - printf("Endianness. These lines should all be the same (for values filled in):\n"); - printf("%.8x %.8x %.8x\n", - hashword((const uint32_t *)q, (sizeof(q)-1)/4, 13), - hashword((const uint32_t *)q, (sizeof(q)-5)/4, 13), - hashword((const uint32_t *)q, (sizeof(q)-9)/4, 13)); - p = q; - printf("%.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x\n", - hashlittle(p, sizeof(q)-1, 13), hashlittle(p, sizeof(q)-2, 13), - hashlittle(p, sizeof(q)-3, 13), hashlittle(p, sizeof(q)-4, 13), - hashlittle(p, sizeof(q)-5, 13), hashlittle(p, sizeof(q)-6, 13), - hashlittle(p, sizeof(q)-7, 13), hashlittle(p, sizeof(q)-8, 13), - hashlittle(p, sizeof(q)-9, 13), hashlittle(p, sizeof(q)-10, 13), - hashlittle(p, sizeof(q)-11, 13), hashlittle(p, sizeof(q)-12, 13)); - p = &qq[1]; - printf("%.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x\n", - hashlittle(p, sizeof(q)-1, 13), hashlittle(p, sizeof(q)-2, 13), - hashlittle(p, sizeof(q)-3, 13), hashlittle(p, sizeof(q)-4, 13), - hashlittle(p, sizeof(q)-5, 13), hashlittle(p, sizeof(q)-6, 13), - hashlittle(p, sizeof(q)-7, 13), hashlittle(p, sizeof(q)-8, 13), - hashlittle(p, sizeof(q)-9, 13), hashlittle(p, sizeof(q)-10, 13), - hashlittle(p, sizeof(q)-11, 13), hashlittle(p, sizeof(q)-12, 13)); - p = &qqq[2]; - printf("%.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x\n", - hashlittle(p, sizeof(q)-1, 13), hashlittle(p, sizeof(q)-2, 13), - hashlittle(p, sizeof(q)-3, 13), hashlittle(p, sizeof(q)-4, 13), - hashlittle(p, sizeof(q)-5, 13), hashlittle(p, sizeof(q)-6, 13), - hashlittle(p, sizeof(q)-7, 13), hashlittle(p, sizeof(q)-8, 13), - hashlittle(p, sizeof(q)-9, 13), hashlittle(p, sizeof(q)-10, 13), - hashlittle(p, sizeof(q)-11, 13), hashlittle(p, sizeof(q)-12, 13)); - p = &qqqq[3]; - printf("%.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x\n", - hashlittle(p, sizeof(q)-1, 13), hashlittle(p, sizeof(q)-2, 13), - hashlittle(p, sizeof(q)-3, 13), hashlittle(p, sizeof(q)-4, 13), - hashlittle(p, sizeof(q)-5, 13), hashlittle(p, sizeof(q)-6, 13), - hashlittle(p, sizeof(q)-7, 13), hashlittle(p, sizeof(q)-8, 13), - hashlittle(p, sizeof(q)-9, 13), hashlittle(p, sizeof(q)-10, 13), - hashlittle(p, sizeof(q)-11, 13), hashlittle(p, sizeof(q)-12, 13)); - printf("\n"); - - /* check that hashlittle2 and hashlittle produce the same results */ - i=47; j=0; - hashlittle2(q, sizeof(q), &i, &j); - if (hashlittle(q, sizeof(q), 47) != i) - printf("hashlittle2 and hashlittle mismatch\n"); - - /* check that hashword2 and hashword produce the same results */ - len = 0xdeadbeef; - i=47, j=0; - hashword2(&len, 1, &i, &j); - if (hashword(&len, 1, 47) != i) - printf("hashword2 and hashword mismatch %x %x\n", - i, hashword(&len, 1, 47)); - - /* check hashlittle doesn't read before or after the ends of the string */ - for (h=0, b=buf+1; h<8; ++h, ++b) - { - for (i=0; iarray_size; } -char StringHashCompareFunc(void *data1, uint16_t datalen1, - void *data2, uint16_t datalen2) +char StringHashCompareFunc(void *data1, uint16_t datalen1, void *data2, uint16_t datalen2) { int len1 = strlen((char *)data1); int len2 = strlen((char *)data2); diff --git a/src/util-hash-string.h b/src/util-hash-string.h index 7153af800d3b..31ce8c6fe03c 100644 --- a/src/util-hash-string.h +++ b/src/util-hash-string.h @@ -22,8 +22,7 @@ uint32_t StringHashDjb2(const uint8_t *data, uint32_t datalen); uint32_t StringHashFunc(HashTable *ht, void *data, uint16_t datalen); -char StringHashCompareFunc(void *data1, uint16_t datalen1, - void *data2, uint16_t datalen2); +char StringHashCompareFunc(void *data1, uint16_t datalen1, void *data2, uint16_t datalen2); void StringHashFreeFunc(void *data); #endif /* __UTIL_HASH_STRING_H__ */ diff --git a/src/util-hash.c b/src/util-hash.c index 412a46fa7eb9..acca4c744da9 100644 --- a/src/util-hash.c +++ b/src/util-hash.c @@ -32,7 +32,9 @@ #include "util-memcmp.h" #include "util-debug.h" -HashTable* HashTableInit(uint32_t size, uint32_t (*Hash)(struct HashTable_ *, void *, uint16_t), char (*Compare)(void *, uint16_t, void *, uint16_t), void (*Free)(void *)) { +HashTable *HashTableInit(uint32_t size, uint32_t (*Hash)(struct HashTable_ *, void *, uint16_t), + char (*Compare)(void *, uint16_t, void *, uint16_t), void (*Free)(void *)) +{ HashTable *ht = NULL; @@ -41,7 +43,7 @@ HashTable* HashTableInit(uint32_t size, uint32_t (*Hash)(struct HashTable_ *, vo } if (Hash == NULL) { - //printf("ERROR: HashTableInit no Hash function\n"); + // printf("ERROR: HashTableInit no Hash function\n"); goto error; } @@ -165,7 +167,7 @@ int HashTableRemove(HashTable *ht, void *data, uint16_t datalen) HashTableBucket *hashbucket = ht->array[hash], *prev_hashbucket = NULL; do { - if (ht->Compare(hashbucket->data,hashbucket->size,data,datalen) == 1) { + if (ht->Compare(hashbucket->data, hashbucket->size, data, datalen) == 1) { if (prev_hashbucket == NULL) { /* root bucket */ ht->array[hash] = hashbucket->next; @@ -218,19 +220,22 @@ void *HashTableLookup(HashTable *ht, void *data, uint16_t datalen) uint32_t HashTableGenericHash(HashTable *ht, void *data, uint16_t datalen) { - uint8_t *d = (uint8_t *)data; - uint32_t i; - uint32_t hash = 0; - - for (i = 0; i < datalen; i++) { - if (i == 0) hash += (((uint32_t)*d++)); - else if (i == 1) hash += (((uint32_t)*d++) * datalen); - else hash *= (((uint32_t)*d++) * i) + datalen + i; - } - - hash *= datalen; - hash %= ht->array_size; - return hash; + uint8_t *d = (uint8_t *)data; + uint32_t i; + uint32_t hash = 0; + + for (i = 0; i < datalen; i++) { + if (i == 0) + hash += (((uint32_t)*d++)); + else if (i == 1) + hash += (((uint32_t)*d++) * datalen); + else + hash *= (((uint32_t)*d++) * i) + datalen + i; + } + + hash *= datalen; + hash %= ht->array_size; + return hash; } char HashTableDefaultCompare(void *data1, uint16_t len1, void *data2, uint16_t len2) @@ -238,7 +243,7 @@ char HashTableDefaultCompare(void *data1, uint16_t len1, void *data2, uint16_t l if (len1 != len2) return 0; - if (SCMemcmp(data1,data2,len1) != 0) + if (SCMemcmp(data1, data2, len1) != 0) return 0; return 1; @@ -249,7 +254,7 @@ char HashTableDefaultCompare(void *data1, uint16_t len1, void *data2, uint16_t l */ #ifdef UNITTESTS -static int HashTableTestInit01 (void) +static int HashTableTestInit01(void) { HashTable *ht = HashTableInit(1024, HashTableGenericHash, NULL, NULL); if (ht == NULL) @@ -260,7 +265,7 @@ static int HashTableTestInit01 (void) } /* no hash function, so it should fail */ -static int HashTableTestInit02 (void) +static int HashTableTestInit02(void) { HashTable *ht = HashTableInit(1024, NULL, NULL, NULL); if (ht == NULL) @@ -270,7 +275,7 @@ static int HashTableTestInit02 (void) return 0; } -static int HashTableTestInit03 (void) +static int HashTableTestInit03(void) { int result = 0; HashTable *ht = HashTableInit(1024, HashTableGenericHash, NULL, NULL); @@ -284,7 +289,7 @@ static int HashTableTestInit03 (void) return result; } -static int HashTableTestInit04 (void) +static int HashTableTestInit04(void) { HashTable *ht = HashTableInit(0, HashTableGenericHash, NULL, NULL); if (ht == NULL) @@ -294,7 +299,7 @@ static int HashTableTestInit04 (void) return 0; } -static int HashTableTestInit05 (void) +static int HashTableTestInit05(void) { int result = 0; HashTable *ht = HashTableInit(1024, HashTableGenericHash, NULL, NULL); @@ -313,13 +318,13 @@ static char HashTableDefaultCompareTest(void *data1, uint16_t len1, void *data2, if (len1 != len2) return 0; - if (SCMemcmp(data1,data2,len1) != 0) + if (SCMemcmp(data1, data2, len1) != 0) return 0; return 1; } -static int HashTableTestInit06 (void) +static int HashTableTestInit06(void) { int result = 0; HashTable *ht = HashTableInit(1024, HashTableGenericHash, HashTableDefaultCompareTest, NULL); @@ -333,7 +338,7 @@ static int HashTableTestInit06 (void) return result; } -static int HashTableTestAdd01 (void) +static int HashTableTestAdd01(void) { int result = 0; HashTable *ht = HashTableInit(32, HashTableGenericHash, NULL, NULL); @@ -347,11 +352,12 @@ static int HashTableTestAdd01 (void) /* all is good! */ result = 1; end: - if (ht != NULL) HashTableFree(ht); + if (ht != NULL) + HashTableFree(ht); return result; } -static int HashTableTestAdd02 (void) +static int HashTableTestAdd02(void) { int result = 0; HashTable *ht = HashTableInit(32, HashTableGenericHash, NULL, NULL); @@ -365,11 +371,12 @@ static int HashTableTestAdd02 (void) /* all is good! */ result = 1; end: - if (ht != NULL) HashTableFree(ht); + if (ht != NULL) + HashTableFree(ht); return result; } -static int HashTableTestFull01 (void) +static int HashTableTestFull01(void) { int result = 0; HashTable *ht = HashTableInit(32, HashTableGenericHash, NULL, NULL); @@ -391,11 +398,12 @@ static int HashTableTestFull01 (void) /* all is good! */ result = 1; end: - if (ht != NULL) HashTableFree(ht); + if (ht != NULL) + HashTableFree(ht); return result; } -static int HashTableTestFull02 (void) +static int HashTableTestFull02(void) { int result = 0; HashTable *ht = HashTableInit(32, HashTableGenericHash, NULL, NULL); @@ -417,7 +425,8 @@ static int HashTableTestFull02 (void) /* all is good! */ result = 1; end: - if (ht != NULL) HashTableFree(ht); + if (ht != NULL) + HashTableFree(ht); return result; } #endif @@ -439,4 +448,3 @@ void HashTableRegisterTests(void) UtRegisterTest("HashTableTestFull02", HashTableTestFull02); #endif } - diff --git a/src/util-hash.h b/src/util-hash.h index f16111887431..7623aa47ed7c 100644 --- a/src/util-hash.h +++ b/src/util-hash.h @@ -46,7 +46,8 @@ typedef struct HashTable_ { #define HASH_NO_SIZE 0 /* prototypes */ -HashTable* HashTableInit(uint32_t, uint32_t (*Hash)(struct HashTable_ *, void *, uint16_t), char (*Compare)(void *, uint16_t, void *, uint16_t), void (*Free)(void *)); +HashTable *HashTableInit(uint32_t, uint32_t (*Hash)(struct HashTable_ *, void *, uint16_t), + char (*Compare)(void *, uint16_t, void *, uint16_t), void (*Free)(void *)); void HashTableFree(HashTable *); void HashTablePrint(HashTable *); int HashTableAdd(HashTable *, void *, uint16_t); @@ -58,4 +59,3 @@ char HashTableDefaultCompare(void *, uint16_t, void *, uint16_t); void HashTableRegisterTests(void); #endif /* __HASH_H__ */ - diff --git a/src/util-hashlist.c b/src/util-hashlist.c index e4b62a613d6e..2a2e55cc9fc7 100644 --- a/src/util-hashlist.c +++ b/src/util-hashlist.c @@ -126,7 +126,7 @@ int HashListTableAdd(HashListTable *ht, void *data, uint16_t datalen) uint32_t hash = ht->Hash(ht, data, datalen); - SCLogDebug("ht %p hash %"PRIu32"", ht, hash); + SCLogDebug("ht %p hash %" PRIu32 "", ht, hash); HashListTableBucket *hb = SCCalloc(1, sizeof(HashListTableBucket)); if (unlikely(hb == NULL)) @@ -163,7 +163,7 @@ int HashListTableRemove(HashListTable *ht, void *data, uint16_t datalen) { uint32_t hash = ht->Hash(ht, data, datalen); - SCLogDebug("ht %p hash %"PRIu32"", ht, hash); + SCLogDebug("ht %p hash %" PRIu32 "", ht, hash); if (ht->array[hash] == NULL) { SCLogDebug("ht->array[hash] NULL"); @@ -174,7 +174,7 @@ int HashListTableRemove(HashListTable *ht, void *data, uint16_t datalen) if (ht->array[hash]->bucknext == NULL) { HashListTableBucket *hb = ht->array[hash]; - if (ht->Compare(hb->data,hb->size,data,datalen) == 1) { + if (ht->Compare(hb->data, hb->size, data, datalen) == 1) { /* remove from the list */ if (hb->listprev == NULL) { ht->listhead = hb->listnext; @@ -202,7 +202,7 @@ int HashListTableRemove(HashListTable *ht, void *data, uint16_t datalen) /* more data in this bucket */ HashListTableBucket *hashbucket = ht->array[hash], *prev_hashbucket = NULL; do { - if (ht->Compare(hashbucket->data,hashbucket->size,data,datalen) == 1) { + if (ht->Compare(hashbucket->data, hashbucket->size, data, datalen) == 1) { /* remove from the list */ if (hashbucket->listprev == NULL) { @@ -244,7 +244,7 @@ char HashListTableDefaultCompare(void *data1, uint16_t len1, void *data2, uint16 if (len1 != len2) return 0; - if (SCMemcmp(data1,data2,len1) != 0) + if (SCMemcmp(data1, data2, len1) != 0) return 0; return 1; @@ -266,7 +266,7 @@ void *HashListTableLookup(HashListTable *ht, void *data, uint16_t datalen) HashListTableBucket *hashbucket = ht->array[hash]; do { - if (ht->Compare(hashbucket->data,hashbucket->size,data,datalen) == 1) + if (ht->Compare(hashbucket->data, hashbucket->size, data, datalen) == 1) return hashbucket->data; hashbucket = hashbucket->bucknext; @@ -277,19 +277,22 @@ void *HashListTableLookup(HashListTable *ht, void *data, uint16_t datalen) uint32_t HashListTableGenericHash(HashListTable *ht, void *data, uint16_t datalen) { - uint8_t *d = (uint8_t *)data; - uint32_t i; - uint32_t hash = 0; - - for (i = 0; i < datalen; i++) { - if (i == 0) hash += (((uint32_t)*d++)); - else if (i == 1) hash += (((uint32_t)*d++) * datalen); - else hash *= (((uint32_t)*d++) * i) + datalen + i; - } - - hash *= datalen; - hash %= ht->array_size; - return hash; + uint8_t *d = (uint8_t *)data; + uint32_t i; + uint32_t hash = 0; + + for (i = 0; i < datalen; i++) { + if (i == 0) + hash += (((uint32_t)*d++)); + else if (i == 1) + hash += (((uint32_t)*d++) * datalen); + else + hash *= (((uint32_t)*d++) * i) + datalen + i; + } + + hash *= datalen; + hash %= ht->array_size; + return hash; } HashListTableBucket *HashListTableGetListHead(HashListTable *ht) @@ -302,7 +305,7 @@ HashListTableBucket *HashListTableGetListHead(HashListTable *ht) */ #ifdef UNITTESTS -static int HashListTableTestInit01 (void) +static int HashListTableTestInit01(void) { HashListTable *ht = HashListTableInit(1024, HashListTableGenericHash, NULL, NULL); if (ht == NULL) @@ -313,7 +316,7 @@ static int HashListTableTestInit01 (void) } /* no hash function, so it should fail */ -static int HashListTableTestInit02 (void) +static int HashListTableTestInit02(void) { HashListTable *ht = HashListTableInit(1024, NULL, NULL, NULL); if (ht == NULL) @@ -323,7 +326,7 @@ static int HashListTableTestInit02 (void) return 0; } -static int HashListTableTestInit03 (void) +static int HashListTableTestInit03(void) { int result = 0; HashListTable *ht = HashListTableInit(1024, HashListTableGenericHash, NULL, NULL); @@ -337,7 +340,7 @@ static int HashListTableTestInit03 (void) return result; } -static int HashListTableTestInit04 (void) +static int HashListTableTestInit04(void) { HashListTable *ht = HashListTableInit(0, HashListTableGenericHash, NULL, NULL); if (ht == NULL) @@ -347,7 +350,7 @@ static int HashListTableTestInit04 (void) return 0; } -static int HashListTableTestAdd01 (void) +static int HashListTableTestAdd01(void) { int result = 0; HashListTable *ht = HashListTableInit(32, HashListTableGenericHash, NULL, NULL); @@ -361,11 +364,12 @@ static int HashListTableTestAdd01 (void) /* all is good! */ result = 1; end: - if (ht != NULL) HashListTableFree(ht); + if (ht != NULL) + HashListTableFree(ht); return result; } -static int HashListTableTestAdd02 (void) +static int HashListTableTestAdd02(void) { int result = 0; HashListTable *ht = HashListTableInit(32, HashListTableGenericHash, NULL, NULL); @@ -379,11 +383,12 @@ static int HashListTableTestAdd02 (void) /* all is good! */ result = 1; end: - if (ht != NULL) HashListTableFree(ht); + if (ht != NULL) + HashListTableFree(ht); return result; } -static int HashListTableTestAdd03 (void) +static int HashListTableTestAdd03(void) { int result = 0; HashListTable *ht = HashListTableInit(32, HashListTableGenericHash, NULL, NULL); @@ -407,11 +412,12 @@ static int HashListTableTestAdd03 (void) /* all is good! */ result = 1; end: - if (ht != NULL) HashListTableFree(ht); + if (ht != NULL) + HashListTableFree(ht); return result; } -static int HashListTableTestAdd04 (void) +static int HashListTableTestAdd04(void) { int result = 0; HashListTable *ht = HashListTableInit(32, HashListTableGenericHash, NULL, NULL); @@ -446,11 +452,12 @@ static int HashListTableTestAdd04 (void) /* all is good! */ result = 1; end: - if (ht != NULL) HashListTableFree(ht); + if (ht != NULL) + HashListTableFree(ht); return result; } -static int HashListTableTestFull01 (void) +static int HashListTableTestFull01(void) { int result = 0; HashListTable *ht = HashListTableInit(32, HashListTableGenericHash, NULL, NULL); @@ -472,11 +479,12 @@ static int HashListTableTestFull01 (void) /* all is good! */ result = 1; end: - if (ht != NULL) HashListTableFree(ht); + if (ht != NULL) + HashListTableFree(ht); return result; } -static int HashListTableTestFull02 (void) +static int HashListTableTestFull02(void) { int result = 0; HashListTable *ht = HashListTableInit(32, HashListTableGenericHash, NULL, NULL); @@ -498,7 +506,8 @@ static int HashListTableTestFull02 (void) /* all is good! */ result = 1; end: - if (ht != NULL) HashListTableFree(ht); + if (ht != NULL) + HashListTableFree(ht); return result; } #endif /* UNITTESTS */ @@ -520,4 +529,3 @@ void HashListTableRegisterTests(void) UtRegisterTest("HashListTableTestFull02", HashListTableTestFull02); #endif /* UNITTESTS */ } - diff --git a/src/util-hashlist.h b/src/util-hashlist.h index bca74c98719b..a41d0e6d2df4 100644 --- a/src/util-hashlist.h +++ b/src/util-hashlist.h @@ -45,7 +45,9 @@ typedef struct HashListTable_ { } HashListTable; /* prototypes */ -HashListTable* HashListTableInit(uint32_t, uint32_t (*Hash)(struct HashListTable_ *, void *, uint16_t), char (*Compare)(void *, uint16_t, void *, uint16_t), void (*Free)(void *)); +HashListTable *HashListTableInit(uint32_t, + uint32_t (*Hash)(struct HashListTable_ *, void *, uint16_t), + char (*Compare)(void *, uint16_t, void *, uint16_t), void (*Free)(void *)); void HashListTableFree(HashListTable *); void HashListTablePrint(HashListTable *); int HashListTableAdd(HashListTable *, void *, uint16_t); @@ -60,4 +62,3 @@ char HashListTableDefaultCompare(void *, uint16_t, void *, uint16_t); void HashListTableRegisterTests(void); #endif /* __HASHLIST_H__ */ - diff --git a/src/util-host-os-info.c b/src/util-host-os-info.c index 02b3ee72a263..cd19515b2996 100644 --- a/src/util-host-os-info.c +++ b/src/util-host-os-info.c @@ -40,28 +40,27 @@ #include "util-unittest.h" /** Enum map for the various OS flavours */ -SCEnumCharMap sc_hinfo_os_policy_map[ ] = { - { "none", OS_POLICY_NONE }, - { "bsd", OS_POLICY_BSD }, - { "bsd-right", OS_POLICY_BSD_RIGHT }, - { "old-linux", OS_POLICY_OLD_LINUX }, - { "linux", OS_POLICY_LINUX }, +SCEnumCharMap sc_hinfo_os_policy_map[] = { + { "none", OS_POLICY_NONE }, + { "bsd", OS_POLICY_BSD }, + { "bsd-right", OS_POLICY_BSD_RIGHT }, + { "old-linux", OS_POLICY_OLD_LINUX }, + { "linux", OS_POLICY_LINUX }, { "old-solaris", OS_POLICY_OLD_SOLARIS }, - { "solaris", OS_POLICY_SOLARIS }, - { "hpux10", OS_POLICY_HPUX10 }, - { "hpux11", OS_POLICY_HPUX11 }, - { "irix", OS_POLICY_IRIX }, - { "macos", OS_POLICY_MACOS }, - { "windows", OS_POLICY_WINDOWS }, - { "vista", OS_POLICY_VISTA }, - { "windows2k3", OS_POLICY_WINDOWS2K3 }, - { NULL, -1 }, + { "solaris", OS_POLICY_SOLARIS }, + { "hpux10", OS_POLICY_HPUX10 }, + { "hpux11", OS_POLICY_HPUX11 }, + { "irix", OS_POLICY_IRIX }, + { "macos", OS_POLICY_MACOS }, + { "windows", OS_POLICY_WINDOWS }, + { "vista", OS_POLICY_VISTA }, + { "windows2k3", OS_POLICY_WINDOWS2K3 }, + { NULL, -1 }, }; /** Radix tree that holds the host OS information */ static SCRadixTree *sc_hinfo_tree = NULL; - /** * \brief Allocates the host_os flavour wrapped in user_data variable to be sent * along with the key to the radix tree @@ -77,12 +76,12 @@ static void *SCHInfoAllocUserDataOSPolicy(const char *host_os) { int *user_data = NULL; - if ( (user_data = SCMalloc(sizeof(int))) == NULL) { + if ((user_data = SCMalloc(sizeof(int))) == NULL) { FatalError("Error allocating memory. Exiting"); } /* the host os flavour that has to be sent as user data */ - if ( (*user_data = SCMapEnumNameToValue(host_os, sc_hinfo_os_policy_map)) == -1) { + if ((*user_data = SCMapEnumNameToValue(host_os, sc_hinfo_os_policy_map)) == -1) { SCLogError("Invalid enum map inside " "SCHInfoAddHostOSInfo()"); SCFree(user_data); @@ -130,8 +129,7 @@ int SCHInfoAddHostOSInfo(const char *host_os, const char *host_os_ip_range, int int *user_data = NULL; bool recursive = false; - if (host_os == NULL || host_os_ip_range == NULL || - strlen(host_os_ip_range) == 0) { + if (host_os == NULL || host_os_ip_range == NULL || strlen(host_os_ip_range) == 0) { SCLogError("Invalid arguments"); return -1; } @@ -141,21 +139,21 @@ int SCHInfoAddHostOSInfo(const char *host_os, const char *host_os_ip_range, int sc_hinfo_tree = SCRadixCreateRadixTree(SCHInfoFreeUserDataOSPolicy, NULL); /* the host os flavour that has to be sent as user data */ - if ( (user_data = SCHInfoAllocUserDataOSPolicy(host_os)) == NULL) { + if ((user_data = SCHInfoAllocUserDataOSPolicy(host_os)) == NULL) { SCLogError("Invalid enum map inside"); return -1; } /* if we have a default configuration set the appropriate values for the * netblocks */ - if ( (strcasecmp(host_os_ip_range, "default")) == 0) { + if ((strcasecmp(host_os_ip_range, "default")) == 0) { if (is_ipv4) host_os_ip_range = "0.0.0.0/0"; else host_os_ip_range = "::/0"; } - if ( (ip_str = SCStrdup(host_os_ip_range)) == NULL) { + if ((ip_str = SCStrdup(host_os_ip_range)) == NULL) { FatalError("Error allocating memory"); } @@ -167,14 +165,14 @@ int SCHInfoAddHostOSInfo(const char *host_os, const char *host_os_ip_range, int } /* check if we have received a netblock */ - if ( (netmask_str = strchr(ip_str, '/')) != NULL) { + if ((netmask_str = strchr(ip_str, '/')) != NULL) { netmask_str[0] = '\0'; netmask_str++; } if (strchr(ip_str, ':') == NULL) { /* if we are here, we have an IPV4 address */ - if ( (ipv4_addr = ValidateIPV4Address(ip_str)) == NULL) { + if ((ipv4_addr = ValidateIPV4Address(ip_str)) == NULL) { SCLogError("Invalid IPV4 address"); SCHInfoFreeUserDataOSPolicy(user_data); SCFree(ip_str); @@ -182,8 +180,7 @@ int SCHInfoAddHostOSInfo(const char *host_os, const char *host_os_ip_range, int } if (netmask_str == NULL) { - SCRadixAddKeyIPV4((uint8_t *)ipv4_addr, sc_hinfo_tree, - (void *)user_data); + SCRadixAddKeyIPV4((uint8_t *)ipv4_addr, sc_hinfo_tree, (void *)user_data); } else { if (StringParseU8RangeCheck(&netmask_value, 10, 0, (const char *)netmask_str, 0, 32) < 0) { @@ -195,12 +192,12 @@ int SCHInfoAddHostOSInfo(const char *host_os, const char *host_os_ip_range, int } MaskIPNetblock((uint8_t *)ipv4_addr, netmask_value, 32); - SCRadixAddKeyIPV4Netblock((uint8_t *)ipv4_addr, sc_hinfo_tree, - (void *)user_data, netmask_value); + SCRadixAddKeyIPV4Netblock( + (uint8_t *)ipv4_addr, sc_hinfo_tree, (void *)user_data, netmask_value); } } else { /* if we are here, we have an IPV6 address */ - if ( (ipv6_addr = ValidateIPV6Address(ip_str)) == NULL) { + if ((ipv6_addr = ValidateIPV6Address(ip_str)) == NULL) { SCLogError("Invalid IPV6 address inside"); SCHInfoFreeUserDataOSPolicy(user_data); SCFree(ip_str); @@ -208,8 +205,7 @@ int SCHInfoAddHostOSInfo(const char *host_os, const char *host_os_ip_range, int } if (netmask_str == NULL) { - SCRadixAddKeyIPV6((uint8_t *)ipv6_addr, sc_hinfo_tree, - (void *)user_data); + SCRadixAddKeyIPV6((uint8_t *)ipv6_addr, sc_hinfo_tree, (void *)user_data); } else { if (StringParseU8RangeCheck(&netmask_value, 10, 0, (const char *)netmask_str, 0, 128) < 0) { @@ -221,8 +217,8 @@ int SCHInfoAddHostOSInfo(const char *host_os, const char *host_os_ip_range, int } MaskIPNetblock((uint8_t *)ipv6_addr, netmask_value, 128); - SCRadixAddKeyIPV6Netblock((uint8_t *)ipv6_addr, sc_hinfo_tree, - (void *)user_data, netmask_value); + SCRadixAddKeyIPV6Netblock( + (uint8_t *)ipv6_addr, sc_hinfo_tree, (void *)user_data, netmask_value); } } @@ -255,7 +251,7 @@ int SCHInfoGetHostOSFlavour(const char *ip_addr_str) return -1; if (strchr(ip_addr_str, ':') != NULL) { - if ( (ipv6_addr = ValidateIPV6Address(ip_addr_str)) == NULL) { + if ((ipv6_addr = ValidateIPV6Address(ip_addr_str)) == NULL) { SCLogError("Invalid IPV4 address"); return -1; } @@ -267,7 +263,7 @@ int SCHInfoGetHostOSFlavour(const char *ip_addr_str) else return *((int *)user_data); } else { - if ( (ipv4_addr = ValidateIPV4Address(ip_addr_str)) == NULL) { + if ((ipv4_addr = ValidateIPV4Address(ip_addr_str)) == NULL) { SCLogError("Invalid IPV4 address"); return -1; } @@ -339,9 +335,9 @@ void SCHInfoLoadFromConfig(void) return; ConfNode *policy; - TAILQ_FOREACH(policy, &root->head, next) { + TAILQ_FOREACH (policy, &root->head, next) { ConfNode *host; - TAILQ_FOREACH(host, &policy->head, next) { + TAILQ_FOREACH (host, &policy->head, next) { int is_ipv4 = 1; if (host->val != NULL && strchr(host->val, ':') != NULL) is_ipv4 = 0; @@ -390,53 +386,53 @@ static int SCHInfoTestInvalidOSFlavour01(void) goto end; } if (SCHInfoAddHostOSInfo("linux", "192.168.1.1", SC_HINFO_IS_IPV4) != - SCMapEnumNameToValue("linux", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("linux", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoAddHostOSInfo("windows", "192.168.1.1", SC_HINFO_IS_IPV4) != - SCMapEnumNameToValue("windows", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("windows", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoAddHostOSInfo("solaris", "192.168.1.1", SC_HINFO_IS_IPV4) != - SCMapEnumNameToValue("solaris", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("solaris", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoAddHostOSInfo("hpux10", "192.168.1.1", SC_HINFO_IS_IPV4) != - SCMapEnumNameToValue("hpux10", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("hpux10", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoAddHostOSInfo("hpux11", "192.168.1.1", SC_HINFO_IS_IPV4) != - SCMapEnumNameToValue("hpux11", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("hpux11", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoAddHostOSInfo("irix", "192.168.1.1", SC_HINFO_IS_IPV4) != - SCMapEnumNameToValue("irix", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("irix", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoAddHostOSInfo("bsd", "192.168.1.1", SC_HINFO_IS_IPV4) != - SCMapEnumNameToValue("bsd", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("bsd", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoAddHostOSInfo("old_linux", "192.168.1.1", SC_HINFO_IS_IPV4) != - SCMapEnumNameToValue("old_linux", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("old_linux", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoAddHostOSInfo("macos", "192.168.1.1", SC_HINFO_IS_IPV4) != - SCMapEnumNameToValue("macos", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("macos", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoAddHostOSInfo("vista", "192.168.1.1", SC_HINFO_IS_IPV4) != - SCMapEnumNameToValue("vista", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("vista", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoAddHostOSInfo("windows2k3", "192.168.1.1", SC_HINFO_IS_IPV4) != - SCMapEnumNameToValue("windows2k3", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("windows2k3", sc_hinfo_os_policy_map)) { goto end; } result = 1; - end: +end: SCHInfoCleanResources(); SCHInfoRestoreContextBackup(); @@ -474,7 +470,7 @@ static int SCHInfoTestInvalidIPV4Address02(void) result = 1; - end: +end: SCHInfoCleanResources(); SCHInfoRestoreContextBackup(); @@ -506,15 +502,14 @@ static int SCHInfoTestInvalidIPV6Address03(void) if (SCHInfoAddHostOSInfo("linux", "", SC_HINFO_IS_IPV6) != -1) { goto end; } - if (SCHInfoAddHostOSInfo("linux", - "1921.6311:6241:6422:7352:ABBB:DDDD:EEEE/129", - SC_HINFO_IS_IPV6) != -1) { + if (SCHInfoAddHostOSInfo( + "linux", "1921.6311:6241:6422:7352:ABBB:DDDD:EEEE/129", SC_HINFO_IS_IPV6) != -1) { goto end; } result = 1; - end: +end: SCHInfoCleanResources(); SCHInfoRestoreContextBackup(); @@ -571,53 +566,53 @@ static int SCHInfoTestValidIPV4Address04(void) } if (SCHInfoGetHostOSFlavour("192.168.1.1") != - SCMapEnumNameToValue("linux", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("linux", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoGetHostOSFlavour("192.168.1.2") != -1) { goto end; } if (SCHInfoGetHostOSFlavour("192.168.1.100") != - SCMapEnumNameToValue("solaris", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("solaris", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoGetHostOSFlavour("192.192.2.4") != -1) { goto end; } if (SCHInfoGetHostOSFlavour("192.168.2.4") != - SCMapEnumNameToValue("hpux10", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("hpux10", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoGetHostOSFlavour("192.192.1.5") != - SCMapEnumNameToValue("linux", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("linux", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoGetHostOSFlavour("192.168.10.20") != - SCMapEnumNameToValue("vista", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("vista", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoGetHostOSFlavour("111.163.151.62") != - SCMapEnumNameToValue("solaris", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("solaris", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoGetHostOSFlavour("11.1.120.210") != - SCMapEnumNameToValue("solaris", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("solaris", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoGetHostOSFlavour("19.18.110.210") != - SCMapEnumNameToValue("linux", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("linux", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoGetHostOSFlavour("19.18.120.110") != - SCMapEnumNameToValue("windows", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("windows", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoGetHostOSFlavour("191.168.11.128") != - SCMapEnumNameToValue("hpux11", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("hpux11", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoGetHostOSFlavour("191.168.11.192") != - SCMapEnumNameToValue("vista", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("vista", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoGetHostOSFlavour("191.168.11.224") != -1) { @@ -626,7 +621,7 @@ static int SCHInfoTestValidIPV4Address04(void) result = 1; - end: +end: SCHInfoCleanResources(); SCHInfoRestoreContextBackup(); @@ -684,45 +679,45 @@ static int SCHInfoTestValidIPV4Address05(void) } if (SCHInfoGetHostOSFlavour("192.168.1.1") != - SCMapEnumNameToValue("linux", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("linux", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoGetHostOSFlavour("192.168.1.2") != -1) { goto end; } if (SCHInfoGetHostOSFlavour("192.168.1.100") != - SCMapEnumNameToValue("solaris", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("solaris", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoGetHostOSFlavour("192.192.2.4") != -1) { goto end; } if (SCHInfoGetHostOSFlavour("192.168.2.4") != - SCMapEnumNameToValue("hpux10", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("hpux10", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoGetHostOSFlavour("192.192.1.5") != - SCMapEnumNameToValue("linux", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("linux", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoGetHostOSFlavour("192.168.10.20") != - SCMapEnumNameToValue("vista", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("vista", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoGetHostOSFlavour("111.163.151.62") != - SCMapEnumNameToValue("solaris", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("solaris", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoGetHostOSFlavour("111.162.208.0") != - SCMapEnumNameToValue("hpux11", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("hpux11", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoGetHostOSFlavour("111.162.210.1") != - SCMapEnumNameToValue("hpux11", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("hpux11", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoGetHostOSFlavour("111.162.214.1") != - SCMapEnumNameToValue("hpux11", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("hpux11", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoGetHostOSFlavour("111.162.0.0") != -1) { @@ -732,33 +727,33 @@ static int SCHInfoTestValidIPV4Address05(void) goto end; } if (SCHInfoGetHostOSFlavour("111.162.240.1") != - SCMapEnumNameToValue("windows", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("windows", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoGetHostOSFlavour("111.162.214.100") != - SCMapEnumNameToValue("solaris", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("solaris", sc_hinfo_os_policy_map)) { goto end; } if (inet_pton(AF_INET, "111.162.208.100", &in) < 0) { goto end; } if (SCHInfoGetIPv4HostOSFlavour((uint8_t *)&in) != - SCMapEnumNameToValue("vista", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("vista", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoGetHostOSFlavour("111.162.194.112") != - SCMapEnumNameToValue("linux", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("linux", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoGetHostOSFlavour("111.162.208.200") != - SCMapEnumNameToValue("hpux11", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("hpux11", sc_hinfo_os_policy_map)) { goto end; } if (inet_pton(AF_INET, "111.162.208.200", &in) < 0) { goto end; } if (SCHInfoGetIPv4HostOSFlavour((uint8_t *)&in) != - SCMapEnumNameToValue("hpux11", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("hpux11", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoGetHostOSFlavour("111.162.200.201") != -1) { @@ -767,7 +762,7 @@ static int SCHInfoTestValidIPV4Address05(void) result = 1; - end: +end: SCHInfoCleanResources(); SCHInfoRestoreContextBackup(); @@ -786,115 +781,103 @@ static int SCHInfoTestValidIPV6Address06(void) int result = 0; - if (SCHInfoAddHostOSInfo("linux", - "2351:2512:6211:6246:235A:6242:2352:62AD", - SC_HINFO_IS_IPV6) == -1) { + if (SCHInfoAddHostOSInfo( + "linux", "2351:2512:6211:6246:235A:6242:2352:62AD", SC_HINFO_IS_IPV6) == -1) { goto end; } - if (SCHInfoAddHostOSInfo("windows", - "6961:6121:2132:6241:423A:2135:2461:621D", - SC_HINFO_IS_IPV6) == -1) { + if (SCHInfoAddHostOSInfo( + "windows", "6961:6121:2132:6241:423A:2135:2461:621D", SC_HINFO_IS_IPV6) == -1) { goto end; } - if (SCHInfoAddHostOSInfo("solaris", - "DD13:613D:F312:62DD:6213:421A:6212:2652", - SC_HINFO_IS_IPV6) == -1) { + if (SCHInfoAddHostOSInfo( + "solaris", "DD13:613D:F312:62DD:6213:421A:6212:2652", SC_HINFO_IS_IPV6) == -1) { goto end; } - if (SCHInfoAddHostOSInfo("hpux10", - "9891:2131:2151:6426:1342:674D:622F:2342", - SC_HINFO_IS_IPV6) == -1) { + if (SCHInfoAddHostOSInfo( + "hpux10", "9891:2131:2151:6426:1342:674D:622F:2342", SC_HINFO_IS_IPV6) == -1) { goto end; } - if (SCHInfoAddHostOSInfo("linux", - "3525:2351:4223:6211:2311:2667:6242:2154", - SC_HINFO_IS_IPV6) == -1) { + if (SCHInfoAddHostOSInfo( + "linux", "3525:2351:4223:6211:2311:2667:6242:2154", SC_HINFO_IS_IPV6) == -1) { goto end; } - if (SCHInfoAddHostOSInfo("vista", - "1511:6211:6726:7777:1212:2333:6222:7722", - SC_HINFO_IS_IPV6) == -1) { + if (SCHInfoAddHostOSInfo( + "vista", "1511:6211:6726:7777:1212:2333:6222:7722", SC_HINFO_IS_IPV6) == -1) { goto end; } - if (SCHInfoAddHostOSInfo("solaris", - "2666:6222:7222:2335:6223:7722:3425:2362", - SC_HINFO_IS_IPV6) == -1) { + if (SCHInfoAddHostOSInfo( + "solaris", "2666:6222:7222:2335:6223:7722:3425:2362", SC_HINFO_IS_IPV6) == -1) { goto end; } - if (SCHInfoAddHostOSInfo("solaris", - "8762:2352:6241:7245:EE23:21AD:2312:622C", - SC_HINFO_IS_IPV6) == -1) { + if (SCHInfoAddHostOSInfo( + "solaris", "8762:2352:6241:7245:EE23:21AD:2312:622C", SC_HINFO_IS_IPV6) == -1) { goto end; } - if (SCHInfoAddHostOSInfo("linux", - "6422:EE1A:2621:34AD:2462:432D:642E:E13A", - SC_HINFO_IS_IPV6) == -1) { + if (SCHInfoAddHostOSInfo( + "linux", "6422:EE1A:2621:34AD:2462:432D:642E:E13A", SC_HINFO_IS_IPV6) == -1) { goto end; } - if (SCHInfoAddHostOSInfo("windows", - "3521:7622:6241:6242:7277:1234:2352:6234", - SC_HINFO_IS_IPV6) == -1) { + if (SCHInfoAddHostOSInfo( + "windows", "3521:7622:6241:6242:7277:1234:2352:6234", SC_HINFO_IS_IPV6) == -1) { goto end; } - if (SCHInfoAddHostOSInfo("hpux11", - "2141:6232:6252:2223:7734:2345:6245:6222", - SC_HINFO_IS_IPV6) == -1) { + if (SCHInfoAddHostOSInfo( + "hpux11", "2141:6232:6252:2223:7734:2345:6245:6222", SC_HINFO_IS_IPV6) == -1) { goto end; } - if (SCHInfoAddHostOSInfo("vista", - "5222:6432:6432:2322:6662:3423:4322:3245", - SC_HINFO_IS_IPV6) == -1) { + if (SCHInfoAddHostOSInfo( + "vista", "5222:6432:6432:2322:6662:3423:4322:3245", SC_HINFO_IS_IPV6) == -1) { goto end; } if (SCHInfoGetHostOSFlavour("2351:2512:6211:6246:235A:6242:2352:62AD") != - SCMapEnumNameToValue("linux", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("linux", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoGetHostOSFlavour("2351:2512:6211:6246:235A:6242:2352:6FFFE") != -1) { goto end; } if (SCHInfoGetHostOSFlavour("DD13:613D:F312:62DD:6213:421A:6212:2652") != - SCMapEnumNameToValue("solaris", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("solaris", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoGetHostOSFlavour("DD13:613D:F312:62DD:6213:421A:6212:2222") != -1) { goto end; } if (SCHInfoGetHostOSFlavour("9891:2131:2151:6426:1342:674D:622F:2342") != - SCMapEnumNameToValue("hpux10", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("hpux10", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoGetHostOSFlavour("3525:2351:4223:6211:2311:2667:6242:2154") != - SCMapEnumNameToValue("linux", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("linux", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoGetHostOSFlavour("1511:6211:6726:7777:1212:2333:6222:7722") != - SCMapEnumNameToValue("vista", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("vista", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoGetHostOSFlavour("2666:6222:7222:2335:6223:7722:3425:2362") != - SCMapEnumNameToValue("solaris", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("solaris", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoGetHostOSFlavour("8762:2352:6241:7245:EE23:21AD:2312:622C") != - SCMapEnumNameToValue("solaris", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("solaris", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoGetHostOSFlavour("6422:EE1A:2621:34AD:2462:432D:642E:E13A") != - SCMapEnumNameToValue("linux", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("linux", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoGetHostOSFlavour("3521:7622:6241:6242:7277:1234:2352:6234") != - SCMapEnumNameToValue("windows", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("windows", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoGetHostOSFlavour("2141:6232:6252:2223:7734:2345:6245:6222") != - SCMapEnumNameToValue("hpux11", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("hpux11", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoGetHostOSFlavour("5222:6432:6432:2322:6662:3423:4322:3245") != - SCMapEnumNameToValue("vista", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("vista", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoGetHostOSFlavour("5222:6432:6432:2322:6662:3423:4322:DDDD") != -1) { @@ -903,7 +886,7 @@ static int SCHInfoTestValidIPV6Address06(void) result = 1; - end: +end: SCHInfoCleanResources(); SCHInfoRestoreContextBackup(); @@ -922,144 +905,132 @@ static int SCHInfoTestValidIPV6Address07(void) int result = 0; - if (SCHInfoAddHostOSInfo("linux", - "2351:2512:6211:6246:235A:6242:2352:62AD", - SC_HINFO_IS_IPV6) == -1) { + if (SCHInfoAddHostOSInfo( + "linux", "2351:2512:6211:6246:235A:6242:2352:62AD", SC_HINFO_IS_IPV6) == -1) { goto end; } - if (SCHInfoAddHostOSInfo("windows", - "6961:6121:2132:6241:423A:2135:2461:621D", - SC_HINFO_IS_IPV6) == -1) { + if (SCHInfoAddHostOSInfo( + "windows", "6961:6121:2132:6241:423A:2135:2461:621D", SC_HINFO_IS_IPV6) == -1) { goto end; } - if (SCHInfoAddHostOSInfo("solaris", - "DD13:613D:F312:62DD:6213:421A:6212:2652", - SC_HINFO_IS_IPV6) == -1) { + if (SCHInfoAddHostOSInfo( + "solaris", "DD13:613D:F312:62DD:6213:421A:6212:2652", SC_HINFO_IS_IPV6) == -1) { goto end; } - if (SCHInfoAddHostOSInfo("hpux10", - "9891:2131:2151:6426:1342:674D:622F:2342", - SC_HINFO_IS_IPV6) == -1) { + if (SCHInfoAddHostOSInfo( + "hpux10", "9891:2131:2151:6426:1342:674D:622F:2342", SC_HINFO_IS_IPV6) == -1) { goto end; } - if (SCHInfoAddHostOSInfo("linux", - "3525:2351:4223:6211:2311:2667:6242:2154", - SC_HINFO_IS_IPV6) == -1) { + if (SCHInfoAddHostOSInfo( + "linux", "3525:2351:4223:6211:2311:2667:6242:2154", SC_HINFO_IS_IPV6) == -1) { goto end; } - if (SCHInfoAddHostOSInfo("vista", - "1511:6211:6726:7777:1212:2333:6222:7722", - SC_HINFO_IS_IPV6) == -1) { + if (SCHInfoAddHostOSInfo( + "vista", "1511:6211:6726:7777:1212:2333:6222:7722", SC_HINFO_IS_IPV6) == -1) { goto end; } - if (SCHInfoAddHostOSInfo("solaris", - "2666:6222:7222:2335:6223:7722:3425:2362", - SC_HINFO_IS_IPV6) == -1) { + if (SCHInfoAddHostOSInfo( + "solaris", "2666:6222:7222:2335:6223:7722:3425:2362", SC_HINFO_IS_IPV6) == -1) { goto end; } - if (SCHInfoAddHostOSInfo("solaris", - "8762:2352:6241:7245:EE23:21AD:2312:622C/68", - SC_HINFO_IS_IPV6) == -1) { + if (SCHInfoAddHostOSInfo( + "solaris", "8762:2352:6241:7245:EE23:21AD:2312:622C/68", SC_HINFO_IS_IPV6) == -1) { goto end; } - if (SCHInfoAddHostOSInfo("linux", - "8762:2352:6241:7245:EE23:21AD:2412:622C", - SC_HINFO_IS_IPV6) == -1) { + if (SCHInfoAddHostOSInfo( + "linux", "8762:2352:6241:7245:EE23:21AD:2412:622C", SC_HINFO_IS_IPV6) == -1) { goto end; } - if (SCHInfoAddHostOSInfo("windows", - "8762:2352:6241:7245:EE23:21AD:FFFF:622C", - SC_HINFO_IS_IPV6) == -1) { + if (SCHInfoAddHostOSInfo( + "windows", "8762:2352:6241:7245:EE23:21AD:FFFF:622C", SC_HINFO_IS_IPV6) == -1) { goto end; } - if (SCHInfoAddHostOSInfo("hpux11", - "8762:2352:6241:7245:EE23:21AD:2312:62FF", - SC_HINFO_IS_IPV6) == -1) { + if (SCHInfoAddHostOSInfo( + "hpux11", "8762:2352:6241:7245:EE23:21AD:2312:62FF", SC_HINFO_IS_IPV6) == -1) { goto end; } - if (SCHInfoAddHostOSInfo("vista", - "8762:2352:6241:7245:EE23:21AD:2121:1212", - SC_HINFO_IS_IPV6) == -1) { + if (SCHInfoAddHostOSInfo( + "vista", "8762:2352:6241:7245:EE23:21AD:2121:1212", SC_HINFO_IS_IPV6) == -1) { goto end; } if (SCHInfoGetHostOSFlavour("2351:2512:6211:6246:235A:6242:2352:62AD") != - SCMapEnumNameToValue("linux", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("linux", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoGetHostOSFlavour("2351:2512:6211:6246:235A:6242:2352:6FFFE") != -1) { goto end; } if (SCHInfoGetHostOSFlavour("DD13:613D:F312:62DD:6213:421A:6212:2652") != - SCMapEnumNameToValue("solaris", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("solaris", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoGetHostOSFlavour("DD13:613D:F312:62DD:6213:421A:6212:2222") != -1) { goto end; } if (SCHInfoGetHostOSFlavour("9891:2131:2151:6426:1342:674D:622F:2342") != - SCMapEnumNameToValue("hpux10", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("hpux10", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoGetHostOSFlavour("3525:2351:4223:6211:2311:2667:6242:2154") != - SCMapEnumNameToValue("linux", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("linux", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoGetHostOSFlavour("1511:6211:6726:7777:1212:2333:6222:7722") != - SCMapEnumNameToValue("vista", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("vista", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoGetHostOSFlavour("2666:6222:7222:2335:6223:7722:3425:2362") != - SCMapEnumNameToValue("solaris", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("solaris", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoGetHostOSFlavour("8762:2352:6241:7245:EE23:21AD:2312:622C") != - SCMapEnumNameToValue("solaris", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("solaris", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoGetHostOSFlavour("8762:2352:6241:7245:EE23:21AD:2412:622C") != - SCMapEnumNameToValue("linux", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("linux", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoGetHostOSFlavour("8762:2352:6241:7245:EE23:21AD:FFFF:622C") != - SCMapEnumNameToValue("windows", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("windows", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoGetHostOSFlavour("8762:2352:6241:7245:EE23:21AD:2312:62FF") != - SCMapEnumNameToValue("hpux11", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("hpux11", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoGetHostOSFlavour("8762:2352:6241:7245:EE23:21AD:2121:1212") != - SCMapEnumNameToValue("vista", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("vista", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoGetHostOSFlavour("5222:6432:6432:2322:6662:3423:4322:DDDD") != -1) { goto end; } if (SCHInfoGetHostOSFlavour("8762:2352:6241:7245:EE23:21AD:2121:1DDD") != - SCMapEnumNameToValue("solaris", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("solaris", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoGetHostOSFlavour("8762:2352:6241:7245:EE23:FFFF:2121:1DDD") != - SCMapEnumNameToValue("solaris", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("solaris", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoGetHostOSFlavour("8762:2352:6241:7245:EE23:21AD:2312:622C") != - SCMapEnumNameToValue("solaris", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("solaris", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoGetHostOSFlavour("8762:2352:6241:7245:EE00:0000:0000:0000") != - SCMapEnumNameToValue("solaris", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("solaris", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoGetHostOSFlavour("8762:2352:6241:7245:E000:0000:0000:0000") != - SCMapEnumNameToValue("solaris", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("solaris", sc_hinfo_os_policy_map)) { goto end; } result = 1; - end: +end: SCHInfoCleanResources(); SCHInfoRestoreContextBackup(); @@ -1079,64 +1050,52 @@ static int SCHInfoTestValidIPV6Address08(void) struct in6_addr in6; int result = 0; - if (SCHInfoAddHostOSInfo("linux", - "2351:2512:6211:6246:235A:6242:2352:62AD", - SC_HINFO_IS_IPV6) == -1) { + if (SCHInfoAddHostOSInfo( + "linux", "2351:2512:6211:6246:235A:6242:2352:62AD", SC_HINFO_IS_IPV6) == -1) { goto end; } - if (SCHInfoAddHostOSInfo("windows", - "6961:6121:2132:6241:423A:2135:2461:621D", - SC_HINFO_IS_IPV6) == -1) { + if (SCHInfoAddHostOSInfo( + "windows", "6961:6121:2132:6241:423A:2135:2461:621D", SC_HINFO_IS_IPV6) == -1) { goto end; } - if (SCHInfoAddHostOSInfo("solaris", - "DD13:613D:F312:62DD:6213:421A:6212:2652", - SC_HINFO_IS_IPV6) == -1) { + if (SCHInfoAddHostOSInfo( + "solaris", "DD13:613D:F312:62DD:6213:421A:6212:2652", SC_HINFO_IS_IPV6) == -1) { goto end; } - if (SCHInfoAddHostOSInfo("hpux10", - "9891:2131:2151:6426:1342:674D:622F:2342", - SC_HINFO_IS_IPV6) == -1) { + if (SCHInfoAddHostOSInfo( + "hpux10", "9891:2131:2151:6426:1342:674D:622F:2342", SC_HINFO_IS_IPV6) == -1) { goto end; } - if (SCHInfoAddHostOSInfo("linux", - "3525:2351:4223:6211:2311:2667:6242:2154", - SC_HINFO_IS_IPV6) == -1) { + if (SCHInfoAddHostOSInfo( + "linux", "3525:2351:4223:6211:2311:2667:6242:2154", SC_HINFO_IS_IPV6) == -1) { goto end; } - if (SCHInfoAddHostOSInfo("vista", - "1511:6211:6726:7777:1212:2333:6222:7722", - SC_HINFO_IS_IPV6) == -1) { + if (SCHInfoAddHostOSInfo( + "vista", "1511:6211:6726:7777:1212:2333:6222:7722", SC_HINFO_IS_IPV6) == -1) { goto end; } - if (SCHInfoAddHostOSInfo("solaris", - "2666:6222:7222:2335:6223:7722:3425:2362", - SC_HINFO_IS_IPV6) == -1) { + if (SCHInfoAddHostOSInfo( + "solaris", "2666:6222:7222:2335:6223:7722:3425:2362", SC_HINFO_IS_IPV6) == -1) { goto end; } - if (SCHInfoAddHostOSInfo("solaris", - "8762:2352:6241:7245:EE23:21AD:2312:622C/68", - SC_HINFO_IS_IPV6) == -1) { + if (SCHInfoAddHostOSInfo( + "solaris", "8762:2352:6241:7245:EE23:21AD:2312:622C/68", SC_HINFO_IS_IPV6) == -1) { goto end; } - if (SCHInfoAddHostOSInfo("linux", - "8762:2352:6241:7245:EE23:21AD:2412:622C", - SC_HINFO_IS_IPV6) == -1) { + if (SCHInfoAddHostOSInfo( + "linux", "8762:2352:6241:7245:EE23:21AD:2412:622C", SC_HINFO_IS_IPV6) == -1) { goto end; } - if (SCHInfoAddHostOSInfo("windows", - "8762:2352:6241:7245:EE23:21AD:FFFF:622C", - SC_HINFO_IS_IPV6) == -1) { + if (SCHInfoAddHostOSInfo( + "windows", "8762:2352:6241:7245:EE23:21AD:FFFF:622C", SC_HINFO_IS_IPV6) == -1) { goto end; } - if (SCHInfoAddHostOSInfo("hpux11", - "8762:2352:6241:7245:EE23:21AD:2312:62FF", - SC_HINFO_IS_IPV6) == -1) { + if (SCHInfoAddHostOSInfo( + "hpux11", "8762:2352:6241:7245:EE23:21AD:2312:62FF", SC_HINFO_IS_IPV6) == -1) { goto end; } - if (SCHInfoAddHostOSInfo("vista", - "8762:2352:6241:7245:EE23:21AD:2121:1212", - SC_HINFO_IS_IPV6) == -1) { + if (SCHInfoAddHostOSInfo( + "vista", "8762:2352:6241:7245:EE23:21AD:2121:1212", SC_HINFO_IS_IPV6) == -1) { goto end; } if (SCHInfoAddHostOSInfo("vista", "8.8.8.0/24", SC_HINFO_IS_IPV4) == -1) { @@ -1147,89 +1106,89 @@ static int SCHInfoTestValidIPV6Address08(void) } if (SCHInfoGetHostOSFlavour("2351:2512:6211:6246:235A:6242:2352:62AD") != - SCMapEnumNameToValue("linux", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("linux", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoGetHostOSFlavour("2351:2512:6211:6246:235A:6242:2352:6FFF") != - SCMapEnumNameToValue("irix", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("irix", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoGetHostOSFlavour("DD13:613D:F312:62DD:6213:421A:6212:2652") != - SCMapEnumNameToValue("solaris", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("solaris", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoGetHostOSFlavour("DD13:613D:F312:62DD:6213:421A:6212:2222") != - SCMapEnumNameToValue("irix", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("irix", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoGetHostOSFlavour("9891:2131:2151:6426:1342:674D:622F:2342") != - SCMapEnumNameToValue("hpux10", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("hpux10", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoGetHostOSFlavour("3525:2351:4223:6211:2311:2667:6242:2154") != - SCMapEnumNameToValue("linux", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("linux", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoGetHostOSFlavour("1511:6211:6726:7777:1212:2333:6222:7722") != - SCMapEnumNameToValue("vista", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("vista", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoGetHostOSFlavour("2666:6222:7222:2335:6223:7722:3425:2362") != - SCMapEnumNameToValue("solaris", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("solaris", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoGetHostOSFlavour("8762:2352:6241:7245:EE23:21AD:2312:622C") != - SCMapEnumNameToValue("solaris", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("solaris", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoGetHostOSFlavour("8762:2352:6241:7245:EE23:21AD:2412:622C") != - SCMapEnumNameToValue("linux", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("linux", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoGetHostOSFlavour("8762:2352:6241:7245:EE23:21AD:FFFF:622C") != - SCMapEnumNameToValue("windows", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("windows", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoGetHostOSFlavour("8762:2352:6241:7245:EE23:21AD:2312:62FF") != - SCMapEnumNameToValue("hpux11", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("hpux11", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoGetHostOSFlavour("8762:2352:6241:7245:EE23:21AD:2121:1212") != - SCMapEnumNameToValue("vista", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("vista", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoGetHostOSFlavour("5222:6432:6432:2322:6662:3423:4322:DDDD") != - SCMapEnumNameToValue("irix", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("irix", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoGetHostOSFlavour("8762:2352:6241:7245:EE23:21AD:2121:1DDD") != - SCMapEnumNameToValue("solaris", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("solaris", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoGetHostOSFlavour("8762:2352:6241:7245:EE23:FFFF:2121:1DDD") != - SCMapEnumNameToValue("solaris", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("solaris", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoGetHostOSFlavour("8762:2352:6241:7245:EE23:21AD:2312:622C") != - SCMapEnumNameToValue("solaris", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("solaris", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoGetHostOSFlavour("8762:2352:6241:7245:EE00:0000:0000:0000") != - SCMapEnumNameToValue("solaris", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("solaris", sc_hinfo_os_policy_map)) { goto end; } if (inet_pton(AF_INET6, "8762:2352:6241:7245:E000:0000:0000:0000", &in6) < 0) { goto end; } if (SCHInfoGetIPv6HostOSFlavour((uint8_t *)&in6) != - SCMapEnumNameToValue("solaris", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("solaris", sc_hinfo_os_policy_map)) { goto end; } if (inet_pton(AF_INET6, "AD23:2DDA:6D1D:A223:E235:0232:1241:1666", &in6) < 0) { goto end; } if (SCHInfoGetIPv6HostOSFlavour((uint8_t *)&in6) != - SCMapEnumNameToValue("irix", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("irix", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoGetHostOSFlavour("8.8.8.8") != @@ -1238,7 +1197,7 @@ static int SCHInfoTestValidIPV6Address08(void) } result = 1; - end: +end: SCHInfoCleanResources(); SCHInfoRestoreContextBackup(); @@ -1264,7 +1223,7 @@ static int SCHInfoTestValidIPV4Address09(void) goto end; } if (SCHInfoGetHostOSFlavour("192.168.1.0") != - SCMapEnumNameToValue("linux", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("linux", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoAddHostOSInfo("solaris", "192.168.1.0/16", SC_HINFO_IS_IPV4) == -1) { @@ -1274,26 +1233,26 @@ static int SCHInfoTestValidIPV4Address09(void) goto end; } if (SCHInfoGetHostOSFlavour("192.168.1.0") != - SCMapEnumNameToValue("linux", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("linux", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoAddHostOSInfo("vista", "192.168.50.128/25", SC_HINFO_IS_IPV4) == -1) { goto end; } if (SCHInfoGetHostOSFlavour("192.168.50.128") != - SCMapEnumNameToValue("vista", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("vista", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoAddHostOSInfo("irix", "192.168.50.128", SC_HINFO_IS_IPV4) == -1) { goto end; } if (SCHInfoGetHostOSFlavour("192.168.50.128") != - SCMapEnumNameToValue("irix", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("irix", sc_hinfo_os_policy_map)) { goto end; } if (SCHInfoGetHostOSFlavour("192.168.1.100") != - SCMapEnumNameToValue("macos", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("macos", sc_hinfo_os_policy_map)) { goto end; } @@ -1306,7 +1265,7 @@ static int SCHInfoTestValidIPV4Address09(void) SCRadixRemoveKeyIPV4Netblock((uint8_t *)&servaddr.sin_addr, sc_hinfo_tree, 16); if (SCHInfoGetHostOSFlavour("192.168.1.100") != - SCMapEnumNameToValue("macos", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("macos", sc_hinfo_os_policy_map)) { goto end; } @@ -1329,7 +1288,7 @@ static int SCHInfoTestValidIPV4Address09(void) /* 192.168.1.100 should match "macos" as its more specific than * "solaris". */ if (SCHInfoGetHostOSFlavour("192.168.1.100") != - SCMapEnumNameToValue("macos", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("macos", sc_hinfo_os_policy_map)) { goto end; } @@ -1341,7 +1300,7 @@ static int SCHInfoTestValidIPV4Address09(void) SCRadixRemoveKeyIPV4Netblock((uint8_t *)&servaddr.sin_addr, sc_hinfo_tree, 20); if (SCHInfoGetHostOSFlavour("192.168.1.100") != - SCMapEnumNameToValue("solaris", sc_hinfo_os_policy_map)) { + SCMapEnumNameToValue("solaris", sc_hinfo_os_policy_map)) { goto end; } @@ -1358,7 +1317,7 @@ static int SCHInfoTestValidIPV4Address09(void) result = 1; - end: +end: SCHInfoCleanResources(); SCHInfoRestoreContextBackup(); @@ -1399,7 +1358,7 @@ host-os-policy:\n\ result = 1; - end: +end: ConfDeInit(); ConfRestoreContextBackup(); @@ -1439,7 +1398,7 @@ host-os-policy:\n\ int count = 0; ConfNode *policy; - TAILQ_FOREACH(policy, &root->head, next) { + TAILQ_FOREACH (policy, &root->head, next) { switch (count) { case 0: if (strcmp("one-two", policy->name) != 0) @@ -1467,7 +1426,7 @@ host-os-policy:\n\ result = 1; - end: +end: ConfDeInit(); ConfRestoreContextBackup(); @@ -1505,7 +1464,7 @@ host-os-policy:\n\ goto end; ConfNode *policy; - TAILQ_FOREACH(policy, &root->head, next) { + TAILQ_FOREACH (policy, &root->head, next) { if (SCMapEnumNameToValue(policy->name, sc_hinfo_os_policy_map) == -1) { printf("Invalid enum map inside\n"); goto end; @@ -1514,7 +1473,7 @@ host-os-policy:\n\ result = 1; - end: +end: ConfDeInit(); ConfRestoreContextBackup(); @@ -1551,7 +1510,7 @@ host-os-policy:\n\ goto end; ConfNode *policy; - TAILQ_FOREACH(policy, &root->head, next) { + TAILQ_FOREACH (policy, &root->head, next) { if (SCMapEnumNameToValue(policy->name, sc_hinfo_os_policy_map) == -1) { printf("Invalid enum map inside\n"); goto end; @@ -1560,7 +1519,7 @@ host-os-policy:\n\ result = 1; - end: +end: ConfDeInit(); ConfRestoreContextBackup(); @@ -1591,13 +1550,13 @@ host-os-policy:\n\ ConfYamlLoadString(config, strlen(config)); SCHInfoLoadFromConfig(); - FAIL_IF (SCHInfoGetHostOSFlavour("0.0.0.1") != OS_POLICY_BSD_RIGHT); - FAIL_IF (SCHInfoGetHostOSFlavour("0.0.0.2") != OS_POLICY_OLD_LINUX); - FAIL_IF (SCHInfoGetHostOSFlavour("0.0.0.3") != OS_POLICY_OLD_SOLARIS); - FAIL_IF (SCHInfoGetHostOSFlavour("0.0.0.4") != OS_POLICY_WINDOWS); - FAIL_IF (SCHInfoGetHostOSFlavour("0.0.0.5") != OS_POLICY_LINUX); - FAIL_IF (SCHInfoGetHostOSFlavour("0.0.0.0") != -1); - FAIL_IF (SCHInfoGetHostOSFlavour("0.0.0.6") != -1); + FAIL_IF(SCHInfoGetHostOSFlavour("0.0.0.1") != OS_POLICY_BSD_RIGHT); + FAIL_IF(SCHInfoGetHostOSFlavour("0.0.0.2") != OS_POLICY_OLD_LINUX); + FAIL_IF(SCHInfoGetHostOSFlavour("0.0.0.3") != OS_POLICY_OLD_SOLARIS); + FAIL_IF(SCHInfoGetHostOSFlavour("0.0.0.4") != OS_POLICY_WINDOWS); + FAIL_IF(SCHInfoGetHostOSFlavour("0.0.0.5") != OS_POLICY_LINUX); + FAIL_IF(SCHInfoGetHostOSFlavour("0.0.0.0") != -1); + FAIL_IF(SCHInfoGetHostOSFlavour("0.0.0.6") != -1); ConfDeInit(); ConfRestoreContextBackup(); @@ -1612,24 +1571,15 @@ void SCHInfoRegisterTests(void) #ifdef UNITTESTS - UtRegisterTest("SCHInfoTesInvalidOSFlavour01", - SCHInfoTestInvalidOSFlavour01); - UtRegisterTest("SCHInfoTestInvalidIPV4Address02", - SCHInfoTestInvalidIPV4Address02); - UtRegisterTest("SCHInfoTestInvalidIPV6Address03", - SCHInfoTestInvalidIPV6Address03); - UtRegisterTest("SCHInfoTestValidIPV4Address04", - SCHInfoTestValidIPV4Address04); - UtRegisterTest("SCHInfoTestValidIPV4Address05", - SCHInfoTestValidIPV4Address05); - UtRegisterTest("SCHInfoTestValidIPV6Address06", - SCHInfoTestValidIPV6Address06); - UtRegisterTest("SCHInfoTestValidIPV6Address07", - SCHInfoTestValidIPV6Address07); - UtRegisterTest("SCHInfoTestValidIPV6Address08", - SCHInfoTestValidIPV6Address08); - UtRegisterTest("SCHInfoTestValidIPV4Address09", - SCHInfoTestValidIPV4Address09); + UtRegisterTest("SCHInfoTesInvalidOSFlavour01", SCHInfoTestInvalidOSFlavour01); + UtRegisterTest("SCHInfoTestInvalidIPV4Address02", SCHInfoTestInvalidIPV4Address02); + UtRegisterTest("SCHInfoTestInvalidIPV6Address03", SCHInfoTestInvalidIPV6Address03); + UtRegisterTest("SCHInfoTestValidIPV4Address04", SCHInfoTestValidIPV4Address04); + UtRegisterTest("SCHInfoTestValidIPV4Address05", SCHInfoTestValidIPV4Address05); + UtRegisterTest("SCHInfoTestValidIPV6Address06", SCHInfoTestValidIPV6Address06); + UtRegisterTest("SCHInfoTestValidIPV6Address07", SCHInfoTestValidIPV6Address07); + UtRegisterTest("SCHInfoTestValidIPV6Address08", SCHInfoTestValidIPV6Address08); + UtRegisterTest("SCHInfoTestValidIPV4Address09", SCHInfoTestValidIPV4Address09); UtRegisterTest("SCHInfoTestLoadFromConfig01", SCHInfoTestLoadFromConfig01); UtRegisterTest("SCHInfoTestLoadFromConfig02", SCHInfoTestLoadFromConfig02); @@ -1637,5 +1587,4 @@ void SCHInfoRegisterTests(void) UtRegisterTest("SCHInfoTestLoadFromConfig04", SCHInfoTestLoadFromConfig04); UtRegisterTest("SCHInfoTestLoadFromConfig05", SCHInfoTestLoadFromConfig05); #endif /* UNITTESTS */ - } diff --git a/src/util-ioctl.c b/src/util-ioctl.c index f39662bd4d47..a286a740c3a0 100644 --- a/src/util-ioctl.c +++ b/src/util-ioctl.c @@ -71,7 +71,6 @@ static int GetIfaceMaxHWHeaderLength(const char *dev) return 8 + SLL_HEADER_LEN; } - /** * \brief output the link MTU * @@ -255,7 +254,6 @@ int SetIfaceCaps(const char *ifname, int caps) } #endif - #if defined HAVE_LINUX_ETHTOOL_H && defined SIOCETHTOOL static int GetEthtoolValue(const char *dev, int cmd, uint32_t *value) { @@ -270,7 +268,7 @@ static int GetEthtoolValue(const char *dev, int cmd, uint32_t *value) (void)strlcpy(ifr.ifr_name, dev, sizeof(ifr.ifr_name)); ethv.cmd = cmd; - ifr.ifr_data = (void *) ðv; + ifr.ifr_data = (void *)ðv; if (ioctl(fd, SIOCETHTOOL, (char *)&ifr) < 0) { SCLogWarning("%s: failed to get SIOCETHTOOL ioctl: %s", dev, strerror(errno)); close(fd); @@ -296,7 +294,7 @@ static int SetEthtoolValue(const char *dev, int cmd, uint32_t value) ethv.cmd = cmd; ethv.data = value; - ifr.ifr_data = (void *) ðv; + ifr.ifr_data = (void *)ðv; if (ioctl(fd, SIOCETHTOOL, (char *)&ifr) < 0) { SCLogWarning("%s: failed to set SIOCETHTOOL ioctl: %s", dev, strerror(errno)); close(fd); @@ -526,14 +524,14 @@ static int GetIfaceOffloadingBSD(const char *ifname) ret = 1; } #ifdef IFCAP_TOE - if (if_caps & (IFCAP_TSO|IFCAP_TOE|IFCAP_LRO)) { + if (if_caps & (IFCAP_TSO | IFCAP_TOE | IFCAP_LRO)) { SCLogWarning("%s: TSO, TOE or LRO activated can lead to capture problems. Run: ifconfig %s " "-tso -toe -lro", ifname, ifname); ret = 1; } #else - if (if_caps & (IFCAP_TSO|IFCAP_LRO)) { + if (if_caps & (IFCAP_TSO | IFCAP_LRO)) { SCLogWarning( "%s: TSO or LRO activated can lead to capture problems. Run: ifconfig %s -tso -lro", ifname, ifname); @@ -581,14 +579,14 @@ static int DisableIfaceOffloadingBSD(LiveDevice *ldev) } #endif #ifdef IFCAP_TOE - if (if_caps & (IFCAP_TSO|IFCAP_TOE|IFCAP_LRO)) { + if (if_caps & (IFCAP_TSO | IFCAP_TOE | IFCAP_LRO)) { SCLogPerf("%s: disabling tso|toe|lro offloading", ifname); - set_caps &= ~(IFCAP_TSO|IFCAP_LRO); + set_caps &= ~(IFCAP_TSO | IFCAP_LRO); } #else - if (if_caps & (IFCAP_TSO|IFCAP_LRO)) { + if (if_caps & (IFCAP_TSO | IFCAP_LRO)) { SCLogPerf("%s: disabling tso|lro offloading", ifname); - set_caps &= ~(IFCAP_TSO|IFCAP_LRO); + set_caps &= ~(IFCAP_TSO | IFCAP_LRO); } #endif if (set_caps != if_caps) { @@ -690,7 +688,6 @@ int DisableIfaceOffloading(LiveDevice *dev, int csum, int other) #else return 0; #endif - } void RestoreIfaceOffloading(LiveDevice *dev) @@ -721,7 +718,7 @@ int GetIfaceRSSQueuesNum(const char *dev) } nfccmd.cmd = ETHTOOL_GRXRINGS; - ifr.ifr_data = (void*) &nfccmd; + ifr.ifr_data = (void *)&nfccmd; if (ioctl(fd, SIOCETHTOOL, (char *)&ifr) < 0) { if (errno != ENOTSUP) { diff --git a/src/util-ip.c b/src/util-ip.c index 8d482d90ed5f..3f4fa165493b 100644 --- a/src/util-ip.c +++ b/src/util-ip.c @@ -88,8 +88,7 @@ bool IPv6AddressStringIsValid(const char *str) uint32_t len = strlen(str); uint32_t i = 0; for (i = 0; i < len && str[i] != 0; i++) { - if (!(str[i] == '.' || str[i] == ':' || - isxdigit(str[i]))) + if (!(str[i] == '.' || str[i] == ':' || isxdigit(str[i]))) return false; if (str[i] == ':') { @@ -134,7 +133,7 @@ struct in_addr *ValidateIPV4Address(const char *addr_str) if (!IPv4AddressStringIsValid(addr_str)) return NULL; - if ( (addr = SCMalloc(sizeof(struct in_addr))) == NULL) { + if ((addr = SCMalloc(sizeof(struct in_addr))) == NULL) { FatalError("Fatal error encountered in ValidateIPV4Address. Exiting..."); } @@ -163,7 +162,7 @@ struct in6_addr *ValidateIPV6Address(const char *addr_str) if (!IPv6AddressStringIsValid(addr_str)) return NULL; - if ( (addr = SCMalloc(sizeof(struct in6_addr))) == NULL) { + if ((addr = SCMalloc(sizeof(struct in6_addr))) == NULL) { FatalError("Fatal error encountered in ValidateIPV6Address. Exiting..."); } @@ -192,8 +191,8 @@ void MaskIPNetblock(uint8_t *stream, int netmask, int key_bitlen) for (i = 0; i < bytes; i++) { mask = UINT_MAX; - if ( ((i + 1) * 8) > netmask) { - if ( ((i + 1) * 8 - netmask) < 8) + if (((i + 1) * 8) > netmask) { + if (((i + 1) * 8 - netmask) < 8) mask = UINT_MAX << ((i + 1) * 8 - netmask); else mask = 0; diff --git a/src/util-ja3.c b/src/util-ja3.c index b361b3e74e39..e2b4af77a6d7 100644 --- a/src/util-ja3.c +++ b/src/util-ja3.c @@ -78,8 +78,7 @@ static int Ja3BufferResizeIfFull(JA3Buffer *buffer, uint32_t len) { DEBUG_VALIDATE_BUG_ON(buffer == NULL); - while (buffer->used + len + 2 > buffer->size) - { + while (buffer->used + len + 2 > buffer->size) { buffer->size *= 2; char *tmp = SCRealloc(buffer->data, buffer->size); if (tmp == NULL) { @@ -128,12 +127,11 @@ int Ja3BufferAppendBuffer(JA3Buffer **buffer1, JA3Buffer **buffer2) } if ((*buffer2)->used == 0) { - (*buffer1)->used += snprintf((*buffer1)->data + (*buffer1)->used, - (*buffer1)->size - (*buffer1)->used, ","); + (*buffer1)->used += snprintf( + (*buffer1)->data + (*buffer1)->used, (*buffer1)->size - (*buffer1)->used, ","); } else { (*buffer1)->used += snprintf((*buffer1)->data + (*buffer1)->used, - (*buffer1)->size - (*buffer1)->used, ",%s", - (*buffer2)->data); + (*buffer1)->size - (*buffer1)->used, ",%s", (*buffer2)->data); } Ja3BufferFree(buffer2); @@ -194,8 +192,7 @@ int Ja3BufferAddValue(JA3Buffer **buffer, uint32_t value) if ((*buffer)->used == 0) { (*buffer)->used += snprintf((*buffer)->data, (*buffer)->size, "%u", value); - } - else { + } else { (*buffer)->used += snprintf( (*buffer)->data + (*buffer)->used, (*buffer)->size - (*buffer)->used, "-%u", value); } diff --git a/src/util-ja3.h b/src/util-ja3.h index 5a0f8c508e6d..407d847b2c62 100644 --- a/src/util-ja3.h +++ b/src/util-ja3.h @@ -50,4 +50,3 @@ InspectionBuffer *Ja3DetectGetString(DetectEngineThreadCtx *det_ctx, const int list_id); #endif /* __UTIL_JA3_H__ */ - diff --git a/src/util-log-redis.c b/src/util-log-redis.c index 5f590d2c6933..3219ac769b30 100644 --- a/src/util-log-redis.c +++ b/src/util-log-redis.c @@ -34,11 +34,11 @@ #include #endif /* HAVE_LIBEVENT_PTHREADS */ -static const char * redis_lpush_cmd = "LPUSH"; -static const char * redis_rpush_cmd = "RPUSH"; -static const char * redis_publish_cmd = "PUBLISH"; -static const char * redis_default_key = "suricata"; -static const char * redis_default_server = "127.0.0.1"; +static const char *redis_lpush_cmd = "LPUSH"; +static const char *redis_rpush_cmd = "RPUSH"; +static const char *redis_publish_cmd = "PUBLISH"; +static const char *redis_default_key = "suricata"; +static const char *redis_default_server = "127.0.0.1"; static int SCConfLogReopenSyncRedis(LogFileCtx *log_ctx); static void SCLogFileCloseRedis(LogFileCtx *log_ctx); @@ -57,14 +57,14 @@ void SCLogRedisInit(void) */ static SCLogRedisContext *SCLogRedisContextAlloc(void) { - SCLogRedisContext* ctx = (SCLogRedisContext*) SCCalloc(1, sizeof(SCLogRedisContext)); + SCLogRedisContext *ctx = (SCLogRedisContext *)SCCalloc(1, sizeof(SCLogRedisContext)); if (ctx == NULL) { FatalError("Unable to allocate redis context"); } ctx->sync = NULL; #if HAVE_LIBEVENT ctx->ev_base = NULL; - ctx->async = NULL; + ctx->async = NULL; #endif ctx->batch_count = 0; ctx->last_push = 0; @@ -82,13 +82,13 @@ static int SCConfLogReopenAsyncRedis(LogFileCtx *log_ctx); */ static SCLogRedisContext *SCLogRedisContextAsyncAlloc(void) { - SCLogRedisContext* ctx = (SCLogRedisContext*) SCCalloc(1, sizeof(SCLogRedisContext)); + SCLogRedisContext *ctx = (SCLogRedisContext *)SCCalloc(1, sizeof(SCLogRedisContext)); if (unlikely(ctx == NULL)) { FatalError("Unable to allocate redis context"); } ctx->sync = NULL; - ctx->async = NULL; + ctx->async = NULL; ctx->ev_base = NULL; ctx->connected = 0; ctx->batch_count = 0; @@ -128,20 +128,20 @@ static void SCRedisAsyncCommandCallback(redisAsyncContext *ac, void *r, void *pr static void SCRedisAsyncEchoCommandCallback(redisAsyncContext *ac, void *r, void *privdata) { redisReply *reply = r; - SCLogRedisContext * ctx = privdata; + SCLogRedisContext *ctx = privdata; if (reply) { - if (ctx->connected == 0) { - SCLogNotice("Connected to Redis."); - ctx->connected = 1; - ctx->tried = 0; - } + if (ctx->connected == 0) { + SCLogNotice("Connected to Redis."); + ctx->connected = 1; + ctx->tried = 0; + } } else { - ctx->connected = 0; - if (ctx->tried == 0) { - SCLogWarning("Failed to connect to Redis... (will keep trying)"); - } - ctx->tried = time(NULL); + ctx->connected = 0; + if (ctx->tried == 0) { + SCLogWarning("Failed to connect to Redis... (will keep trying)"); + } + ctx->tried = time(NULL); } event_base_loopbreak(ctx->ev_base); } @@ -151,7 +151,7 @@ static void SCRedisAsyncEchoCommandCallback(redisAsyncContext *ac, void *r, void * It's used for check if redis is alive. * \param ctx redis context */ -static void SCLogAsyncRedisSendEcho(SCLogRedisContext * ctx) +static void SCLogAsyncRedisSendEcho(SCLogRedisContext *ctx) { redisAsyncCommand(ctx->async, SCRedisAsyncEchoCommandCallback, ctx, "ECHO suricata"); event_base_dispatch(ctx->ev_base); @@ -173,7 +173,7 @@ static void SCRedisAsyncQuitCommandCallback(redisAsyncContext *ac, void *r, void * It's used to disconnect with redis * \param ctx redis context */ -static void SCLogAsyncRedisSendQuit(SCLogRedisContext * ctx) +static void SCLogAsyncRedisSendQuit(SCLogRedisContext *ctx) { if (ctx->connected) { redisAsyncCommand(ctx->async, SCRedisAsyncQuitCommandCallback, ctx, "QUIT"); @@ -193,7 +193,7 @@ static void SCLogAsyncRedisSendQuit(SCLogRedisContext * ctx) */ static int SCConfLogReopenAsyncRedis(LogFileCtx *log_ctx) { - SCLogRedisContext * ctx = log_ctx->redis; + SCLogRedisContext *ctx = log_ctx->redis; const char *redis_server = log_ctx->redis_setup.server; int redis_port = log_ctx->redis_setup.port; @@ -241,7 +241,6 @@ static int SCConfLogReopenAsyncRedis(LogFileCtx *log_ctx) return 0; } - /** \brief SCLogRedisWriteAsync() writes string to redis output in async mode * \param file_ctx Log file context allocated by caller * \param string Buffer to output @@ -250,12 +249,12 @@ static int SCLogRedisWriteAsync(LogFileCtx *file_ctx, const char *string, size_t { SCLogRedisContext *ctx = file_ctx->redis; - if (! ctx->connected) { + if (!ctx->connected) { if (SCConfLogReopenAsyncRedis(file_ctx) == -1) { return -1; } if (ctx->tried == 0) { - SCLogNotice("Trying to connect to Redis"); + SCLogNotice("Trying to connect to Redis"); } SCLogAsyncRedisSendEcho(ctx); } @@ -268,27 +267,22 @@ static int SCLogRedisWriteAsync(LogFileCtx *file_ctx, const char *string, size_t return -1; } - redisAsyncCommand(ctx->async, - SCRedisAsyncCommandCallback, - file_ctx, - "%s %s %s", - file_ctx->redis_setup.command, - file_ctx->redis_setup.key, - string); + redisAsyncCommand(ctx->async, SCRedisAsyncCommandCallback, file_ctx, "%s %s %s", + file_ctx->redis_setup.command, file_ctx->redis_setup.key, string); event_base_loop(ctx->ev_base, EVLOOP_NONBLOCK); return 0; } -#endif// HAVE_LIBEVENT +#endif // HAVE_LIBEVENT /** \brief SCConfLogReopenSyncRedis() Open or re-opens connection to redis for logging. * \param log_ctx Log file context allocated by caller */ static int SCConfLogReopenSyncRedis(LogFileCtx *log_ctx) { - SCLogRedisContext * ctx = log_ctx->redis; + SCLogRedisContext *ctx = log_ctx->redis; /* only try to reconnect once per second */ if (ctx->tried >= time(NULL)) { @@ -298,7 +292,7 @@ static int SCConfLogReopenSyncRedis(LogFileCtx *log_ctx) const char *redis_server = log_ctx->redis_setup.server; int redis_port = log_ctx->redis_setup.port; - if (ctx->sync != NULL) { + if (ctx->sync != NULL) { redisFree(ctx->sync); } @@ -331,7 +325,7 @@ static int SCConfLogReopenSyncRedis(LogFileCtx *log_ctx) */ static int SCLogRedisWriteSync(LogFileCtx *file_ctx, const char *string) { - SCLogRedisContext * ctx = file_ctx->redis; + SCLogRedisContext *ctx = file_ctx->redis; int ret = -1; redisContext *redis = ctx->sync; if (redis == NULL) { @@ -345,10 +339,8 @@ static int SCLogRedisWriteSync(LogFileCtx *file_ctx, const char *string) /* synchronous mode */ if (file_ctx->redis_setup.batch_size) { - redisAppendCommand(redis, "%s %s %s", - file_ctx->redis_setup.command, - file_ctx->redis_setup.key, - string); + redisAppendCommand(redis, "%s %s %s", file_ctx->redis_setup.command, + file_ctx->redis_setup.key, string); time_t now = time(NULL); if ((ctx->batch_count == file_ctx->redis_setup.batch_size) || (ctx->last_push < now)) { redisReply *reply; @@ -362,9 +354,7 @@ static int SCLogRedisWriteSync(LogFileCtx *file_ctx, const char *string) ret = 0; } else { if (redis->err) { - SCLogInfo("Error when fetching reply: %s (%d)", - redis->errstr, - redis->err); + SCLogInfo("Error when fetching reply: %s (%d)", redis->errstr, redis->err); } switch (redis->err) { case REDIS_ERR_EOF: @@ -374,10 +364,8 @@ static int SCLogRedisWriteSync(LogFileCtx *file_ctx, const char *string) redis = ctx->sync; if (redis) { SCLogInfo("Reconnected to redis server"); - redisAppendCommand(redis, "%s %s %s", - file_ctx->redis_setup.command, - file_ctx->redis_setup.key, - string); + redisAppendCommand(redis, "%s %s %s", file_ctx->redis_setup.command, + file_ctx->redis_setup.key, string); ctx->batch_count++; return 0; } else { @@ -395,10 +383,8 @@ static int SCLogRedisWriteSync(LogFileCtx *file_ctx, const char *string) ctx->batch_count++; } } else { - redisReply *reply = redisCommand(redis, "%s %s %s", - file_ctx->redis_setup.command, - file_ctx->redis_setup.key, - string); + redisReply *reply = redisCommand(redis, "%s %s %s", file_ctx->redis_setup.command, + file_ctx->redis_setup.key, string); /* We may lose the reply if disconnection happens*/ if (reply) { switch (reply->type) { @@ -445,7 +431,7 @@ int LogFileWriteRedis(void *lf_ctx, const char *string, size_t string_len) } #endif /* sync mode */ - if (! file_ctx->redis_setup.is_async) { + if (!file_ctx->redis_setup.is_async) { return SCLogRedisWriteSync(file_ctx, string); } return -1; @@ -471,10 +457,10 @@ int SCConfLogOpenRedis(ConfNode *redis_node, void *lf_ctx) if (redis_node) { log_ctx->redis_setup.server = ConfNodeLookupChildValue(redis_node, "server"); - log_ctx->redis_setup.key = ConfNodeLookupChildValue(redis_node, "key"); + log_ctx->redis_setup.key = ConfNodeLookupChildValue(redis_node, "key"); - redis_port = ConfNodeLookupChildValue(redis_node, "port"); - redis_mode = ConfNodeLookupChildValue(redis_node, "mode"); + redis_port = ConfNodeLookupChildValue(redis_node, "port"); + redis_mode = ConfNodeLookupChildValue(redis_node, "mode"); (void)ConfGetChildValueBool(redis_node, "async", &is_async); } @@ -495,7 +481,7 @@ int SCConfLogOpenRedis(ConfNode *redis_node, void *lf_ctx) SCLogWarning("async option not available."); } is_async = 0; -#endif //ifndef HAVE_LIBEVENT +#endif // ifndef HAVE_LIBEVENT log_ctx->redis_setup.is_async = is_async; log_ctx->redis_setup.batch_size = 0; @@ -519,11 +505,11 @@ int SCConfLogOpenRedis(ConfNode *redis_node, void *lf_ctx) log_ctx->redis_setup.batch_size = 0; } - if (!strcmp(redis_mode, "list") || !strcmp(redis_mode,"lpush")) { + if (!strcmp(redis_mode, "list") || !strcmp(redis_mode, "lpush")) { log_ctx->redis_setup.command = redis_lpush_cmd; - } else if(!strcmp(redis_mode, "rpush")){ + } else if (!strcmp(redis_mode, "rpush")) { log_ctx->redis_setup.command = redis_rpush_cmd; - } else if(!strcmp(redis_mode,"channel") || !strcmp(redis_mode,"publish")) { + } else if (!strcmp(redis_mode, "channel") || !strcmp(redis_mode, "publish")) { log_ctx->redis_setup.command = redis_publish_cmd; } else { FatalError("Invalid redis mode"); @@ -543,7 +529,7 @@ int SCConfLogOpenRedis(ConfNode *redis_node, void *lf_ctx) log_ctx->redis = SCLogRedisContextAsyncAlloc(); } #endif /*HAVE_LIBEVENT*/ - if (! is_async) { + if (!is_async) { log_ctx->redis = SCLogRedisContextAlloc(); SCConfLogReopenSyncRedis(log_ctx); } @@ -555,7 +541,7 @@ int SCConfLogOpenRedis(ConfNode *redis_node, void *lf_ctx) */ void SCLogFileCloseRedis(LogFileCtx *log_ctx) { - SCLogRedisContext * ctx = log_ctx->redis; + SCLogRedisContext *ctx = log_ctx->redis; if (ctx == NULL) { return; } diff --git a/src/util-log-redis.h b/src/util-log-redis.h index 12e87dee4a30..09181dbb0640 100644 --- a/src/util-log-redis.h +++ b/src/util-log-redis.h @@ -27,12 +27,11 @@ #ifdef HAVE_LIBHIREDIS #include - #ifdef HAVE_LIBEVENT #include #endif /* HAVE_LIBEVENT */ -#include "conf.h" /* ConfNode */ +#include "conf.h" /* ConfNode */ enum RedisMode { REDIS_LIST, REDIS_CHANNEL }; @@ -41,9 +40,9 @@ typedef struct RedisSetup_ { const char *command; const char *key; const char *server; - uint16_t port; + uint16_t port; int is_async; - int batch_size; + int batch_size; } RedisSetup; typedef struct SCLogRedisContext_ { @@ -54,7 +53,7 @@ typedef struct SCLogRedisContext_ { int connected; #endif /* HAVE_LIBEVENT */ time_t tried; - int batch_count; + int batch_count; time_t last_push; } SCLogRedisContext; diff --git a/src/util-logopenfile.c b/src/util-logopenfile.c index 1b1986490658..0d488ab89ebc 100644 --- a/src/util-logopenfile.c +++ b/src/util-logopenfile.c @@ -26,8 +26,8 @@ #include "suricata-common.h" /* errno.h, string.h, etc. */ #include "util-logopenfile.h" #include "suricata.h" -#include "conf.h" /* ConfNode, etc. */ -#include "output.h" /* DEFAULT_LOG_* */ +#include "conf.h" /* ConfNode, etc. */ +#include "output.h" /* DEFAULT_LOG_* */ #include "util-byte.h" #include "util-conf.h" #include "util-path.h" @@ -59,17 +59,17 @@ static SC_ATOMIC_DECL_AND_INIT_WITH_VAL(uint32_t, eve_file_id, 1); * \retval FILE* on success (fdopen'd wrapper of underlying socket) * \retval NULL on error */ -static FILE * -SCLogOpenUnixSocketFp(const char *path, int sock_type, int log_err) +static FILE *SCLogOpenUnixSocketFp(const char *path, int sock_type, int log_err) { struct sockaddr_un saun; int s = -1; - FILE * ret = NULL; + FILE *ret = NULL; memset(&saun, 0x00, sizeof(saun)); s = socket(PF_UNIX, sock_type, 0); - if (s < 0) goto err; + if (s < 0) + goto err; saun.sun_family = AF_UNIX; strlcpy(saun.sun_path, path, sizeof(saun.sun_path)); @@ -114,9 +114,8 @@ static int SCLogUnixSocketReconnect(LogFileCtx *log_ctx) uint64_t now; gettimeofday(&tv, NULL); now = (uint64_t)tv.tv_sec * 1000; - now += tv.tv_usec / 1000; /* msec resolution */ - if (log_ctx->reconn_timer != 0 && - (now - log_ctx->reconn_timer) < LOGFILE_RECONN_MIN_TIME) { + now += tv.tv_usec / 1000; /* msec resolution */ + if (log_ctx->reconn_timer != 0 && (now - log_ctx->reconn_timer) < LOGFILE_RECONN_MIN_TIME) { /* Don't bother to try reconnecting too often. */ return 0; } @@ -133,8 +132,7 @@ static int SCLogUnixSocketReconnect(LogFileCtx *log_ctx) return log_ctx->fp ? 1 : 0; } -static int SCLogFileWriteSocket(const char *buffer, int buffer_len, - LogFileCtx *ctx) +static int SCLogFileWriteSocket(const char *buffer, int buffer_len, LogFileCtx *ctx) { int tries = 0; int ret = 0; @@ -160,7 +158,7 @@ static int SCLogFileWriteSocket(const char *buffer, int buffer_len, goto tryagain; } SCLogDebug("Too many interrupted system calls, " - "dropping event."); + "dropping event."); } else { /* Some other error. Assume badness and reopen. */ SCLogDebug("Send failed: %s", strerror(errno)); @@ -185,7 +183,6 @@ static int SCLogFileWriteSocket(const char *buffer, int buffer_len, static inline void OutputWriteLock(pthread_mutex_t *m) { SCMutexLock(m); - } /** @@ -358,38 +355,38 @@ static void ThreadLogFileHashFreeFunc(void *data) bool SCLogOpenThreadedFile(const char *log_path, const char *append, LogFileCtx *parent_ctx) { - parent_ctx->threads = SCCalloc(1, sizeof(LogThreadedFileCtx)); - if (!parent_ctx->threads) { - SCLogError("Unable to allocate threads container"); - return false; - } + parent_ctx->threads = SCCalloc(1, sizeof(LogThreadedFileCtx)); + if (!parent_ctx->threads) { + SCLogError("Unable to allocate threads container"); + return false; + } - parent_ctx->threads->ht = HashTableInit(255, ThreadLogFileHashFunc, - ThreadLogFileHashCompareFunc, ThreadLogFileHashFreeFunc); - if (!parent_ctx->threads->ht) { - FatalError("Unable to initialize thread/entry hash table"); - } + parent_ctx->threads->ht = HashTableInit( + 255, ThreadLogFileHashFunc, ThreadLogFileHashCompareFunc, ThreadLogFileHashFreeFunc); + if (!parent_ctx->threads->ht) { + FatalError("Unable to initialize thread/entry hash table"); + } - parent_ctx->threads->append = SCStrdup(append == NULL ? DEFAULT_LOG_MODE_APPEND : append); - if (!parent_ctx->threads->append) { - SCLogError("Unable to allocate threads append setting"); - goto error_exit; - } + parent_ctx->threads->append = SCStrdup(append == NULL ? DEFAULT_LOG_MODE_APPEND : append); + if (!parent_ctx->threads->append) { + SCLogError("Unable to allocate threads append setting"); + goto error_exit; + } - SCMutexInit(&parent_ctx->threads->mutex, NULL); - return true; + SCMutexInit(&parent_ctx->threads->mutex, NULL); + return true; error_exit: - if (parent_ctx->threads->append) { - SCFree(parent_ctx->threads->append); - } - if (parent_ctx->threads->ht) { - HashTableFree(parent_ctx->threads->ht); - } - SCFree(parent_ctx->threads); - parent_ctx->threads = NULL; - return false; + if (parent_ctx->threads->append) { + SCFree(parent_ctx->threads->append); + } + if (parent_ctx->threads->ht) { + HashTableFree(parent_ctx->threads->ht); + } + SCFree(parent_ctx->threads); + parent_ctx->threads = NULL; + return false; } /** \brief open the indicated file, logging any errors @@ -399,8 +396,7 @@ bool SCLogOpenThreadedFile(const char *log_path, const char *append, LogFileCtx * \retval FILE* on success * \retval NULL on error */ -static FILE * -SCLogOpenFileFp(const char *path, const char *append_setting, uint32_t mode) +static FILE *SCLogOpenFileFp(const char *path, const char *append_setting, uint32_t mode) { FILE *ret = NULL; @@ -448,11 +444,8 @@ SCLogOpenFileFp(const char *path, const char *append_setting, uint32_t mode) * \retval 0 on success * \retval -1 on error */ -int -SCConfLogOpenGeneric(ConfNode *conf, - LogFileCtx *log_ctx, - const char *default_filename, - int rotate) +int SCConfLogOpenGeneric( + ConfNode *conf, LogFileCtx *log_ctx, const char *default_filename, int rotate) { char log_path[PATH_MAX]; const char *log_dir; @@ -527,14 +520,13 @@ SCConfLogOpenGeneric(ConfNode *conf, append = DEFAULT_LOG_MODE_APPEND; /* JSON flags */ - log_ctx->json_flags = JSON_PRESERVE_ORDER|JSON_COMPACT| - JSON_ENSURE_ASCII|JSON_ESCAPE_SLASH; + log_ctx->json_flags = + JSON_PRESERVE_ORDER | JSON_COMPACT | JSON_ENSURE_ASCII | JSON_ESCAPE_SLASH; ConfNode *json_flags = ConfNodeLookupChild(conf, "json"); if (json_flags != 0) { - const char *preserve_order = ConfNodeLookupChildValue(json_flags, - "preserve-order"); + const char *preserve_order = ConfNodeLookupChildValue(json_flags, "preserve-order"); if (preserve_order != NULL && ConfValIsFalse(preserve_order)) log_ctx->json_flags &= ~(JSON_PRESERVE_ORDER); @@ -542,13 +534,11 @@ SCConfLogOpenGeneric(ConfNode *conf, if (compact != NULL && ConfValIsFalse(compact)) log_ctx->json_flags &= ~(JSON_COMPACT); - const char *ensure_ascii = ConfNodeLookupChildValue(json_flags, - "ensure-ascii"); + const char *ensure_ascii = ConfNodeLookupChildValue(json_flags, "ensure-ascii"); if (ensure_ascii != NULL && ConfValIsFalse(ensure_ascii)) log_ctx->json_flags &= ~(JSON_ENSURE_ASCII); - const char *escape_slash = ConfNodeLookupChildValue(json_flags, - "escape-slash"); + const char *escape_slash = ConfNodeLookupChildValue(json_flags, "escape-slash"); if (escape_slash != NULL && ConfValIsFalse(escape_slash)) log_ctx->json_flags &= ~(JSON_ESCAPE_SLASH); } @@ -613,8 +603,7 @@ SCConfLogOpenGeneric(ConfNode *conf, log_ctx->send_flags |= MSG_DONTWAIT; } #endif - SCLogInfo("%s output device (%s) initialized: %s", conf->name, filetype, - filename); + SCLogInfo("%s output device (%s) initialized: %s", conf->name, filetype, filename); return 0; } @@ -658,8 +647,8 @@ int SCConfLogReopen(LogFileCtx *log_ctx) * */ LogFileCtx *LogFileNewCtx(void) { - LogFileCtx* lf_ctx; - lf_ctx = (LogFileCtx*)SCCalloc(1, sizeof(LogFileCtx)); + LogFileCtx *lf_ctx; + lf_ctx = (LogFileCtx *)SCCalloc(1, sizeof(LogFileCtx)); if (lf_ctx == NULL) return NULL; @@ -891,7 +880,7 @@ int LogFileFreeCtx(LogFileCtx *lf_ctx) lf_ctx->prefix_len = 0; } - if(lf_ctx->filename != NULL) + if (lf_ctx->filename != NULL) SCFree(lf_ctx->filename); if (lf_ctx->sensor_name) @@ -920,8 +909,7 @@ int LogFileWrite(LogFileCtx *file_ctx, MemBuffer *buffer) file_ctx->type == LOGFILE_TYPE_UNIX_STREAM) { /* append \n for files only */ MemBufferWriteString(buffer, "\n"); - file_ctx->Write((const char *)MEMBUFFER_BUFFER(buffer), - MEMBUFFER_OFFSET(buffer), file_ctx); + file_ctx->Write((const char *)MEMBUFFER_BUFFER(buffer), MEMBUFFER_OFFSET(buffer), file_ctx); } else if (file_ctx->type == LOGFILE_TYPE_PLUGIN) { file_ctx->plugin.plugin->Write((const char *)MEMBUFFER_BUFFER(buffer), MEMBUFFER_OFFSET(buffer), file_ctx->plugin.init_data, file_ctx->plugin.thread_data); @@ -929,8 +917,8 @@ int LogFileWrite(LogFileCtx *file_ctx, MemBuffer *buffer) #ifdef HAVE_LIBHIREDIS else if (file_ctx->type == LOGFILE_TYPE_REDIS) { SCMutexLock(&file_ctx->fp_mutex); - LogFileWriteRedis(file_ctx, (const char *)MEMBUFFER_BUFFER(buffer), - MEMBUFFER_OFFSET(buffer)); + LogFileWriteRedis( + file_ctx, (const char *)MEMBUFFER_BUFFER(buffer), MEMBUFFER_OFFSET(buffer)); SCMutexUnlock(&file_ctx->fp_mutex); } #endif diff --git a/src/util-logopenfile.h b/src/util-logopenfile.h index bbb5211cda77..865d0c66fc5e 100644 --- a/src/util-logopenfile.h +++ b/src/util-logopenfile.h @@ -25,7 +25,7 @@ #define __UTIL_LOGOPENFILE_H__ #include "threads.h" -#include "conf.h" /* ConfNode */ +#include "conf.h" /* ConfNode */ #include "util-buffer.h" #include "util-hash.h" @@ -129,8 +129,8 @@ typedef struct LogFileCtx_ { /** Generic size_limit and size_current * They must be common to the threads accessing the same file */ - uint64_t size_limit; /**< file size limit */ - uint64_t size_current; /**< file current size */ + uint64_t size_limit; /**< file size limit */ + uint64_t size_current; /**< file current size */ /* flag to avoid multiple threads printing the same stats */ uint8_t flags; @@ -143,7 +143,7 @@ typedef struct LogFileCtx_ { uint8_t is_regular; /* JSON flags */ - size_t json_flags; /* passed to json_dump_callback() */ + size_t json_flags; /* passed to json_dump_callback() */ /* Flag set when file rotation notification is received. */ int rotation_flag; @@ -159,7 +159,7 @@ typedef struct LogFileCtx_ { } LogFileCtx; /* Min time (msecs) before trying to reconnect a Unix domain socket */ -#define LOGFILE_RECONN_MIN_TIME 500 +#define LOGFILE_RECONN_MIN_TIME 500 /* flags for LogFileCtx */ #define LOGFILE_ROTATE_INTERVAL 0x04 diff --git a/src/util-lua-common.c b/src/util-lua-common.c index bb0f7899eb84..f34ec6ea93e7 100644 --- a/src/util-lua-common.c +++ b/src/util-lua-common.c @@ -96,7 +96,8 @@ void LuaPushTableKeyValueString(lua_State *luastate, const char *key, const char lua_settable(luastate, -3); } -void LuaPushTableKeyValueArray(lua_State *luastate, const char *key, const uint8_t *value, size_t len) +void LuaPushTableKeyValueArray( + lua_State *luastate, const char *key, const uint8_t *value, size_t len) { lua_pushstring(luastate, key); LuaPushStringBuffer(luastate, value, len); @@ -113,12 +114,12 @@ void LuaPushTableKeyValueArray(lua_State *luastate, const char *key, const uint8 */ static int LuaCallbackStreamingBufferPushToStack(lua_State *luastate, const LuaStreamingBuffer *b) { - //PrintRawDataFp(stdout, (uint8_t *)b->data, b->data_len); - lua_pushlstring (luastate, (const char *)b->data, b->data_len); - lua_pushboolean (luastate, (b->flags & OUTPUT_STREAMING_FLAG_OPEN)); - lua_pushboolean (luastate, (b->flags & OUTPUT_STREAMING_FLAG_CLOSE)); - lua_pushboolean (luastate, (b->flags & OUTPUT_STREAMING_FLAG_TOSERVER)); - lua_pushboolean (luastate, (b->flags & OUTPUT_STREAMING_FLAG_TOCLIENT)); + // PrintRawDataFp(stdout, (uint8_t *)b->data, b->data_len); + lua_pushlstring(luastate, (const char *)b->data, b->data_len); + lua_pushboolean(luastate, (b->flags & OUTPUT_STREAMING_FLAG_OPEN)); + lua_pushboolean(luastate, (b->flags & OUTPUT_STREAMING_FLAG_CLOSE)); + lua_pushboolean(luastate, (b->flags & OUTPUT_STREAMING_FLAG_TOSERVER)); + lua_pushboolean(luastate, (b->flags & OUTPUT_STREAMING_FLAG_TOCLIENT)); return 5; } @@ -145,7 +146,7 @@ static int LuaCallbackStreamingBuffer(lua_State *luastate) */ static int LuaCallbackPacketPayloadPushToStackFromPacket(lua_State *luastate, const Packet *p) { - lua_pushlstring (luastate, (const char *)p->payload, p->payload_len); + lua_pushlstring(luastate, (const char *)p->payload, p->payload_len); return 1; } @@ -189,7 +190,7 @@ static int LuaCallbackTimeStringPushToStackFromPacket(lua_State *luastate, const { char timebuf[64]; CreateTimeString(p->ts, timebuf, sizeof(timebuf)); - lua_pushstring (luastate, timebuf); + lua_pushstring(luastate, timebuf); return 1; } @@ -265,7 +266,7 @@ static int LuaCallbackTimeStringPushToStackFromFlow(lua_State *luastate, const F { char timebuf[64]; CreateTimeString(flow->startts, timebuf, sizeof(timebuf)); - lua_pushstring (luastate, timebuf); + lua_pushstring(luastate, timebuf); return 1; } @@ -346,8 +347,8 @@ static int LuaCallbackTuplePushToStackFromPacket(lua_State *luastate, const Pack PrintInet(AF_INET6, (const void *)GET_IPV6_DST_ADDR(p), dstip, sizeof(dstip)); } - lua_pushstring (luastate, srcip); - lua_pushstring (luastate, dstip); + lua_pushstring(luastate, srcip); + lua_pushstring(luastate, dstip); /* proto and ports (or type/code) */ lua_pushinteger(luastate, p->proto); @@ -409,8 +410,8 @@ static int LuaCallbackTuplePushToStackFromFlow(lua_State *luastate, const Flow * PrintInet(AF_INET6, (const void *)&(f->dst.address), dstip, sizeof(dstip)); } - lua_pushstring (luastate, srcip); - lua_pushstring (luastate, dstip); + lua_pushstring(luastate, srcip); + lua_pushstring(luastate, dstip); /* proto and ports (or type/code) */ lua_pushinteger(luastate, f->proto); @@ -825,13 +826,13 @@ static int LuaCallbackFileInfoPushToStackFromFile(lua_State *luastate, const Fil lua_pushinteger(luastate, tx_id); lua_pushlstring(luastate, (char *)file->name, file->name_len); lua_pushinteger(luastate, FileTrackedSize(file)); - lua_pushstring (luastate, + lua_pushstring(luastate, #ifdef HAVE_MAGIC - file->magic + file->magic #else - "nomagic" + "nomagic" #endif - ); + ); lua_pushstring(luastate, md5ptr); lua_pushstring(luastate, sha1ptr); lua_pushstring(luastate, sha256ptr); @@ -882,8 +883,8 @@ static int LuaCallbackFileStatePushToStackFromFile(lua_State *luastate, const Fi break; } - lua_pushstring (luastate, state); - lua_pushboolean (luastate, file->flags & FILE_STORED); + lua_pushstring(luastate, state); + lua_pushboolean(luastate, file->flags & FILE_STORED); return 2; } @@ -911,9 +912,9 @@ static int LuaCallbackFileState(lua_State *luastate) static int LuaCallbackThreadInfoPushToStackFromThreadVars(lua_State *luastate, const ThreadVars *tv) { unsigned long tid = SCGetThreadIdLong(); - lua_pushinteger (luastate, (lua_Integer)tid); - lua_pushstring (luastate, tv->name); - lua_pushstring (luastate, tv->thread_group_name); + lua_pushinteger(luastate, (lua_Integer)tid); + lua_pushstring(luastate, tv->name); + lua_pushstring(luastate, tv->thread_group_name); return 3; } @@ -974,7 +975,6 @@ int LuaRegisterFunctions(lua_State *luastate) lua_pushcfunction(luastate, LuaCallbackLogError); lua_setglobal(luastate, "SCLogError"); - lua_pushcfunction(luastate, LuaCallbackRuleIds); lua_setglobal(luastate, "SCRuleIds"); lua_pushcfunction(luastate, LuaCallbackRuleAction); @@ -1004,7 +1004,6 @@ int LuaStateNeedProto(lua_State *luastate, AppProto alproto) flow_alproto = flow->alproto; return (alproto == flow_alproto); - } #endif /* HAVE_LUA */ diff --git a/src/util-lua-common.h b/src/util-lua-common.h index 2e0df28751a1..ad34530c9bac 100644 --- a/src/util-lua-common.h +++ b/src/util-lua-common.h @@ -31,7 +31,8 @@ const char *LuaGetStringArgument(lua_State *luastate, int argc); void LuaPushTableKeyValueInt(lua_State *luastate, const char *key, int value); void LuaPushTableKeyValueString(lua_State *luastate, const char *key, const char *value); -void LuaPushTableKeyValueArray(lua_State *luastate, const char *key, const uint8_t *value, size_t len); +void LuaPushTableKeyValueArray( + lua_State *luastate, const char *key, const uint8_t *value, size_t len); int LuaRegisterFunctions(lua_State *luastate); diff --git a/src/util-lua-dnp3-objects.c b/src/util-lua-dnp3-objects.c index 27bbc5351901..7dd755c25f40 100644 --- a/src/util-lua-dnp3-objects.c +++ b/src/util-lua-dnp3-objects.c @@ -39,8 +39,7 @@ /** * \brief Push an object point item onto the stack. */ -void DNP3PushPoint(lua_State *luastate, DNP3Object *object, - DNP3Point *point) +void DNP3PushPoint(lua_State *luastate, DNP3Object *object, DNP3Point *point) { switch (DNP3_OBJECT_CODE(object->group, object->variation)) { case DNP3_OBJECT_CODE(1, 1): { @@ -2938,15 +2937,13 @@ void DNP3PushPoint(lua_State *luastate, DNP3Object *object, lua_pushinteger(luastate, data->status_code); lua_settable(luastate, -3); lua_pushliteral(luastate, "filename"); - LuaPushStringBuffer(luastate, (uint8_t *)data->filename, - strlen(data->filename)); + LuaPushStringBuffer(luastate, (uint8_t *)data->filename, strlen(data->filename)); lua_settable(luastate, -3); lua_pushliteral(luastate, "data_size"); lua_pushinteger(luastate, data->data_size); lua_settable(luastate, -3); lua_pushliteral(luastate, "data"); - LuaPushStringBuffer(luastate, (uint8_t *)data->data, - strlen(data->data)); + LuaPushStringBuffer(luastate, (uint8_t *)data->data, strlen(data->data)); lua_settable(luastate, -3); break; } @@ -2968,12 +2965,10 @@ void DNP3PushPoint(lua_State *luastate, DNP3Object *object, lua_pushinteger(luastate, data->authentication_key); lua_settable(luastate, -3); lua_pushliteral(luastate, "username"); - LuaPushStringBuffer(luastate, (uint8_t *)data->username, - strlen(data->username)); + LuaPushStringBuffer(luastate, (uint8_t *)data->username, strlen(data->username)); lua_settable(luastate, -3); lua_pushliteral(luastate, "password"); - LuaPushStringBuffer(luastate, (uint8_t *)data->password, - strlen(data->password)); + LuaPushStringBuffer(luastate, (uint8_t *)data->password, strlen(data->password)); lua_settable(luastate, -3); break; } @@ -3007,8 +3002,7 @@ void DNP3PushPoint(lua_State *luastate, DNP3Object *object, lua_pushinteger(luastate, data->request_id); lua_settable(luastate, -3); lua_pushliteral(luastate, "filename"); - LuaPushStringBuffer(luastate, (uint8_t *)data->filename, - strlen(data->filename)); + LuaPushStringBuffer(luastate, (uint8_t *)data->filename, strlen(data->filename)); lua_settable(luastate, -3); break; } @@ -3030,8 +3024,8 @@ void DNP3PushPoint(lua_State *luastate, DNP3Object *object, lua_pushinteger(luastate, data->status_code); lua_settable(luastate, -3); lua_pushliteral(luastate, "optional_text"); - LuaPushStringBuffer(luastate, (uint8_t *)data->optional_text, - strlen(data->optional_text)); + LuaPushStringBuffer( + luastate, (uint8_t *)data->optional_text, strlen(data->optional_text)); lua_settable(luastate, -3); break; } @@ -3044,8 +3038,7 @@ void DNP3PushPoint(lua_State *luastate, DNP3Object *object, lua_pushinteger(luastate, data->block_number); lua_settable(luastate, -3); lua_pushliteral(luastate, "file_data"); - LuaPushStringBuffer(luastate, (uint8_t *)data->file_data, - strlen(data->file_data)); + LuaPushStringBuffer(luastate, (uint8_t *)data->file_data, strlen(data->file_data)); lua_settable(luastate, -3); break; } @@ -3061,8 +3054,8 @@ void DNP3PushPoint(lua_State *luastate, DNP3Object *object, lua_pushinteger(luastate, data->status_code); lua_settable(luastate, -3); lua_pushliteral(luastate, "optional_text"); - LuaPushStringBuffer(luastate, (uint8_t *)data->optional_text, - strlen(data->optional_text)); + LuaPushStringBuffer( + luastate, (uint8_t *)data->optional_text, strlen(data->optional_text)); lua_settable(luastate, -3); break; } @@ -3090,8 +3083,7 @@ void DNP3PushPoint(lua_State *luastate, DNP3Object *object, lua_pushinteger(luastate, data->request_id); lua_settable(luastate, -3); lua_pushliteral(luastate, "filename"); - LuaPushStringBuffer(luastate, (uint8_t *)data->filename, - strlen(data->filename)); + LuaPushStringBuffer(luastate, (uint8_t *)data->filename, strlen(data->filename)); lua_settable(luastate, -3); break; } @@ -3099,7 +3091,7 @@ void DNP3PushPoint(lua_State *luastate, DNP3Object *object, DNP3ObjectG70V8 *data = point->data; lua_pushliteral(luastate, "file_specification"); LuaPushStringBuffer(luastate, (uint8_t *)data->file_specification, - strlen(data->file_specification)); + strlen(data->file_specification)); lua_settable(luastate, -3); break; } @@ -3129,8 +3121,7 @@ void DNP3PushPoint(lua_State *luastate, DNP3Object *object, case DNP3_OBJECT_CODE(83, 1): { DNP3ObjectG83V1 *data = point->data; lua_pushliteral(luastate, "vendor_code"); - LuaPushStringBuffer(luastate, (uint8_t *)data->vendor_code, - strlen(data->vendor_code)); + LuaPushStringBuffer(luastate, (uint8_t *)data->vendor_code, strlen(data->vendor_code)); lua_settable(luastate, -3); lua_pushliteral(luastate, "object_id"); lua_pushinteger(luastate, data->object_id); @@ -3139,8 +3130,7 @@ void DNP3PushPoint(lua_State *luastate, DNP3Object *object, lua_pushinteger(luastate, data->length); lua_settable(luastate, -3); lua_pushliteral(luastate, "data_objects"); - lua_pushlstring(luastate, (const char *)data->data_objects, - data->length); + lua_pushlstring(luastate, (const char *)data->data_objects, data->length); lua_settable(luastate, -3); break; } @@ -3194,8 +3184,7 @@ void DNP3PushPoint(lua_State *luastate, DNP3Object *object, lua_pushinteger(luastate, data->reason); lua_settable(luastate, -3); lua_pushliteral(luastate, "challenge_data"); - lua_pushlstring(luastate, (const char *)data->challenge_data, - data->challenge_data_len); + lua_pushlstring(luastate, (const char *)data->challenge_data, data->challenge_data_len); lua_settable(luastate, -3); break; } @@ -3208,8 +3197,7 @@ void DNP3PushPoint(lua_State *luastate, DNP3Object *object, lua_pushinteger(luastate, data->usr); lua_settable(luastate, -3); lua_pushliteral(luastate, "mac_value"); - lua_pushlstring(luastate, (const char *)data->mac_value, - data->mac_value_len); + lua_pushlstring(luastate, (const char *)data->mac_value, data->mac_value_len); lua_settable(luastate, -3); break; } @@ -3251,12 +3239,10 @@ void DNP3PushPoint(lua_State *luastate, DNP3Object *object, lua_pushinteger(luastate, data->challenge_data_len); lua_settable(luastate, -3); lua_pushliteral(luastate, "challenge_data"); - lua_pushlstring(luastate, (const char *)data->challenge_data, - data->challenge_data_len); + lua_pushlstring(luastate, (const char *)data->challenge_data, data->challenge_data_len); lua_settable(luastate, -3); lua_pushliteral(luastate, "mac_value"); - lua_pushlstring(luastate, (const char *)data->mac_value, - data->mac_value_len); + lua_pushlstring(luastate, (const char *)data->mac_value, data->mac_value_len); lua_settable(luastate, -3); break; } @@ -3269,8 +3255,8 @@ void DNP3PushPoint(lua_State *luastate, DNP3Object *object, lua_pushinteger(luastate, data->usr); lua_settable(luastate, -3); lua_pushliteral(luastate, "wrapped_key_data"); - lua_pushlstring(luastate, (const char *)data->wrapped_key_data, - data->wrapped_key_data_len); + lua_pushlstring( + luastate, (const char *)data->wrapped_key_data, data->wrapped_key_data_len); lua_settable(luastate, -3); break; } @@ -3292,8 +3278,7 @@ void DNP3PushPoint(lua_State *luastate, DNP3Object *object, lua_pushinteger(luastate, data->time_of_error); lua_settable(luastate, -3); lua_pushliteral(luastate, "error_text"); - LuaPushStringBuffer(luastate, (uint8_t *)data->error_text, - strlen(data->error_text)); + LuaPushStringBuffer(luastate, (uint8_t *)data->error_text, strlen(data->error_text)); lua_settable(luastate, -3); break; } @@ -3306,16 +3291,14 @@ void DNP3PushPoint(lua_State *luastate, DNP3Object *object, lua_pushinteger(luastate, data->certificate_type); lua_settable(luastate, -3); lua_pushliteral(luastate, "certificate"); - lua_pushlstring(luastate, (const char *)data->certificate, - data->certificate_len); + lua_pushlstring(luastate, (const char *)data->certificate, data->certificate_len); lua_settable(luastate, -3); break; } case DNP3_OBJECT_CODE(120, 9): { DNP3ObjectG120V9 *data = point->data; lua_pushliteral(luastate, "mac_value"); - lua_pushlstring(luastate, (const char *)data->mac_value, - data->mac_value_len); + lua_pushlstring(luastate, (const char *)data->mac_value, data->mac_value_len); lua_settable(luastate, -3); break; } @@ -3346,16 +3329,15 @@ void DNP3PushPoint(lua_State *luastate, DNP3Object *object, lua_pushinteger(luastate, data->certification_data_len); lua_settable(luastate, -3); lua_pushliteral(luastate, "username"); - LuaPushStringBuffer(luastate, (uint8_t *)data->username, - strlen(data->username)); + LuaPushStringBuffer(luastate, (uint8_t *)data->username, strlen(data->username)); lua_settable(luastate, -3); lua_pushliteral(luastate, "user_public_key"); - lua_pushlstring(luastate, (const char *)data->user_public_key, - data->user_public_key_len); + lua_pushlstring( + luastate, (const char *)data->user_public_key, data->user_public_key_len); lua_settable(luastate, -3); lua_pushliteral(luastate, "certification_data"); - lua_pushlstring(luastate, (const char *)data->certification_data, - data->certification_data_len); + lua_pushlstring( + luastate, (const char *)data->certification_data, data->certification_data_len); lua_settable(luastate, -3); break; } @@ -3371,12 +3353,11 @@ void DNP3PushPoint(lua_State *luastate, DNP3Object *object, lua_pushinteger(luastate, data->master_challenge_data_len); lua_settable(luastate, -3); lua_pushliteral(luastate, "username"); - LuaPushStringBuffer(luastate, (uint8_t *)data->username, - strlen(data->username)); + LuaPushStringBuffer(luastate, (uint8_t *)data->username, strlen(data->username)); lua_settable(luastate, -3); lua_pushliteral(luastate, "master_challenge_data"); lua_pushlstring(luastate, (const char *)data->master_challenge_data, - data->master_challenge_data_len); + data->master_challenge_data_len); lua_settable(luastate, -3); break; } @@ -3392,8 +3373,7 @@ void DNP3PushPoint(lua_State *luastate, DNP3Object *object, lua_pushinteger(luastate, data->challenge_data_len); lua_settable(luastate, -3); lua_pushliteral(luastate, "challenge_data"); - lua_pushlstring(luastate, (const char *)data->challenge_data, - data->challenge_data_len); + lua_pushlstring(luastate, (const char *)data->challenge_data, data->challenge_data_len); lua_settable(luastate, -3); break; } @@ -3410,23 +3390,22 @@ void DNP3PushPoint(lua_State *luastate, DNP3Object *object, lua_settable(luastate, -3); lua_pushliteral(luastate, "encrypted_update_key_data"); lua_pushlstring(luastate, (const char *)data->encrypted_update_key_data, - data->encrypted_update_key_len); + data->encrypted_update_key_len); lua_settable(luastate, -3); break; } case DNP3_OBJECT_CODE(120, 14): { DNP3ObjectG120V14 *data = point->data; lua_pushliteral(luastate, "digital_signature"); - lua_pushlstring(luastate, (const char *)data->digital_signature, - data->digital_signature_len); + lua_pushlstring( + luastate, (const char *)data->digital_signature, data->digital_signature_len); lua_settable(luastate, -3); break; } case DNP3_OBJECT_CODE(120, 15): { DNP3ObjectG120V15 *data = point->data; lua_pushliteral(luastate, "mac"); - lua_pushlstring(luastate, (const char *)data->mac, - data->mac_len); + lua_pushlstring(luastate, (const char *)data->mac, data->mac_len); lua_settable(luastate, -3); break; } diff --git a/src/util-lua-dnp3-objects.h b/src/util-lua-dnp3-objects.h index 6575695a2650..8de14a1b9a86 100644 --- a/src/util-lua-dnp3-objects.h +++ b/src/util-lua-dnp3-objects.h @@ -18,7 +18,6 @@ #ifndef __UTIL_LUA_DNP3_OBJECTS_H__ #define __UTIL_LUA_DNP3_OBJECTS_H__ -void DNP3PushPoint(lua_State *luastate, DNP3Object *object, - DNP3Point *item); +void DNP3PushPoint(lua_State *luastate, DNP3Object *object, DNP3Point *item); #endif /* ! __UTIL_LUA_DNP3_OBJECTS_H__ */ diff --git a/src/util-lua-dnp3.c b/src/util-lua-dnp3.c index 09f8694d6c15..48cdc37e25b6 100644 --- a/src/util-lua-dnp3.c +++ b/src/util-lua-dnp3.c @@ -34,10 +34,11 @@ /** * \brief Helper macro to push key and integer value onto a table. */ -#define LUA_PUSHT_INT(l, k, v) do { \ - lua_pushliteral(luastate, k); \ - lua_pushinteger(luastate, v); \ - lua_settable(luastate, -3); \ +#define LUA_PUSHT_INT(l, k, v) \ + do { \ + lua_pushliteral(luastate, k); \ + lua_pushinteger(luastate, v); \ + lua_settable(luastate, -3); \ } while (0); static void DNP3PushPoints(lua_State *luastate, DNP3Object *object) @@ -45,7 +46,7 @@ static void DNP3PushPoints(lua_State *luastate, DNP3Object *object) DNP3Point *point; int i = 1; - TAILQ_FOREACH(point, object->points, next) { + TAILQ_FOREACH (point, object->points, next) { lua_pushinteger(luastate, i++); lua_newtable(luastate); @@ -64,7 +65,7 @@ static void DNP3PushObjects(lua_State *luastate, DNP3ObjectList *objects) DNP3Object *object = NULL; int i = 1; - TAILQ_FOREACH(object, objects, next) { + TAILQ_FOREACH (object, objects, next) { lua_pushinteger(luastate, i++); lua_newtable(luastate); @@ -94,8 +95,7 @@ static void DNP3PushLinkHeader(lua_State *luastate, DNP3LinkHeader *header) LUA_PUSHT_INT(luastate, "crc", header->crc); } -static void DNP3PushApplicationHeader(lua_State *luastate, - DNP3ApplicationHeader *header) +static void DNP3PushApplicationHeader(lua_State *luastate, DNP3ApplicationHeader *header) { LUA_PUSHT_INT(luastate, "control", header->control); LUA_PUSHT_INT(luastate, "function_code", header->function_code); diff --git a/src/util-lua-dns.c b/src/util-lua-dns.c index 3fbd84a75ae2..1229aa3057bb 100644 --- a/src/util-lua-dns.c +++ b/src/util-lua-dns.c @@ -15,7 +15,6 @@ * 02110-1301, USA. */ - /** * \file * diff --git a/src/util-lua-hassh.c b/src/util-lua-hassh.c index 631268d1b458..c427dd0f5093 100644 --- a/src/util-lua-hassh.c +++ b/src/util-lua-hassh.c @@ -15,7 +15,6 @@ * 02110-1301, USA. */ - /** * \file * @@ -200,7 +199,7 @@ static int HasshGet(lua_State *luastate) /** *\brief Register Hassh Lua extensions */ int LuaRegisterHasshFunctions(lua_State *luastate) { - + lua_pushcfunction(luastate, HasshGet); lua_setglobal(luastate, "HasshGet"); @@ -212,7 +211,7 @@ int LuaRegisterHasshFunctions(lua_State *luastate) lua_pushcfunction(luastate, HasshServerGetString); lua_setglobal(luastate, "HasshServerGetString"); - + return 0; } diff --git a/src/util-lua-http.c b/src/util-lua-http.c index e04c168fa6ea..3db1fcd42410 100644 --- a/src/util-lua-http.c +++ b/src/util-lua-http.c @@ -68,8 +68,8 @@ static int HttpGetRequestHost(lua_State *luastate) if (tx->request_hostname == NULL) return LuaCallbackError(luastate, "no request hostname"); - return LuaPushStringBuffer(luastate, - bstr_ptr(tx->request_hostname), bstr_len(tx->request_hostname)); + return LuaPushStringBuffer( + luastate, bstr_ptr(tx->request_hostname), bstr_len(tx->request_hostname)); } static int HttpGetRequestUriRaw(lua_State *luastate) @@ -84,8 +84,7 @@ static int HttpGetRequestUriRaw(lua_State *luastate) if (tx->request_uri == NULL) return LuaCallbackError(luastate, "no request uri"); - return LuaPushStringBuffer(luastate, - bstr_ptr(tx->request_uri), bstr_len(tx->request_uri)); + return LuaPushStringBuffer(luastate, bstr_ptr(tx->request_uri), bstr_len(tx->request_uri)); } static int HttpGetRequestUriNormalized(lua_State *luastate) @@ -97,17 +96,15 @@ static int HttpGetRequestUriNormalized(lua_State *luastate) if (tx == NULL) return LuaCallbackError(luastate, "internal error: no tx"); - HtpTxUserData *htud = (HtpTxUserData *) htp_tx_get_user_data(tx); + HtpTxUserData *htud = (HtpTxUserData *)htp_tx_get_user_data(tx); if (htud == NULL) return LuaCallbackError(luastate, "no htud in tx"); - if (htud->request_uri_normalized == NULL || - bstr_ptr(htud->request_uri_normalized) == NULL || - bstr_len(htud->request_uri_normalized) == 0) + if (htud->request_uri_normalized == NULL || bstr_ptr(htud->request_uri_normalized) == NULL || + bstr_len(htud->request_uri_normalized) == 0) return LuaCallbackError(luastate, "no normalized uri"); - return LuaPushStringBuffer(luastate, - bstr_ptr(htud->request_uri_normalized), + return LuaPushStringBuffer(luastate, bstr_ptr(htud->request_uri_normalized), bstr_len(htud->request_uri_normalized)); } @@ -123,8 +120,7 @@ static int HttpGetRequestLine(lua_State *luastate) if (tx->request_line == NULL) return LuaCallbackError(luastate, "no request_line"); - return LuaPushStringBuffer(luastate, - bstr_ptr(tx->request_line), bstr_len(tx->request_line)); + return LuaPushStringBuffer(luastate, bstr_ptr(tx->request_line), bstr_len(tx->request_line)); } static int HttpGetResponseLine(lua_State *luastate) @@ -139,8 +135,7 @@ static int HttpGetResponseLine(lua_State *luastate) if (tx->response_line == NULL) return LuaCallbackError(luastate, "no response_line"); - return LuaPushStringBuffer(luastate, - bstr_ptr(tx->response_line), bstr_len(tx->response_line)); + return LuaPushStringBuffer(luastate, bstr_ptr(tx->response_line), bstr_len(tx->response_line)); } static int HttpGetHeader(lua_State *luastate, int dir) @@ -166,8 +161,7 @@ static int HttpGetHeader(lua_State *luastate, int dir) if (h == NULL || bstr_len(h->value) == 0) return LuaCallbackError(luastate, "header not found"); - return LuaPushStringBuffer(luastate, - bstr_ptr(h->value), bstr_len(h->value)); + return LuaPushStringBuffer(luastate, bstr_ptr(h->value), bstr_len(h->value)); } static int HttpGetRequestHeader(lua_State *luastate) @@ -189,7 +183,7 @@ static int HttpGetRawHeaders(lua_State *luastate, int dir) if (tx == NULL) return LuaCallbackError(luastate, "internal error: no tx"); - HtpTxUserData *htud = (HtpTxUserData *) htp_tx_get_user_data(tx); + HtpTxUserData *htud = (HtpTxUserData *)htp_tx_get_user_data(tx); if (htud == NULL) return LuaCallbackError(luastate, "no htud in tx"); @@ -216,7 +210,6 @@ static int HttpGetRawResponseHeaders(lua_State *luastate) return HttpGetRawHeaders(luastate, 1); } - static int HttpGetHeaders(lua_State *luastate, int dir) { if (!(LuaStateNeedProto(luastate, ALPROTO_HTTP1))) @@ -268,7 +261,7 @@ static int HttpGetBody(lua_State *luastate, int dir) if (tx == NULL) return LuaCallbackError(luastate, "internal error: no tx"); - HtpTxUserData *htud = (HtpTxUserData *) htp_tx_get_user_data(tx); + HtpTxUserData *htud = (HtpTxUserData *)htp_tx_get_user_data(tx); if (htud == NULL) return LuaCallbackError(luastate, "no htud in tx"); diff --git a/src/util-lua-ja3.c b/src/util-lua-ja3.c index 1faed68f56a0..618fc01f2cd3 100644 --- a/src/util-lua-ja3.c +++ b/src/util-lua-ja3.c @@ -15,7 +15,6 @@ * 02110-1301, USA. */ - /** * \file * @@ -75,9 +74,8 @@ static int Ja3GetHash(lua_State *luastate) if (ssl_state->client_connp.ja3_hash == NULL) return LuaCallbackError(luastate, "error: no JA3 hash"); - return LuaPushStringBuffer(luastate, - (uint8_t *)ssl_state->client_connp.ja3_hash, - strlen(ssl_state->client_connp.ja3_hash)); + return LuaPushStringBuffer(luastate, (uint8_t *)ssl_state->client_connp.ja3_hash, + strlen(ssl_state->client_connp.ja3_hash)); } static int Ja3GetString(lua_State *luastate) @@ -95,13 +93,11 @@ static int Ja3GetString(lua_State *luastate) SSLState *ssl_state = (SSLState *)state; - if (ssl_state->client_connp.ja3_str == NULL || - ssl_state->client_connp.ja3_str->data == NULL) + if (ssl_state->client_connp.ja3_str == NULL || ssl_state->client_connp.ja3_str->data == NULL) return LuaCallbackError(luastate, "error: no JA3 str"); - return LuaPushStringBuffer(luastate, - (uint8_t *)ssl_state->client_connp.ja3_str->data, - ssl_state->client_connp.ja3_str->used); + return LuaPushStringBuffer(luastate, (uint8_t *)ssl_state->client_connp.ja3_str->data, + ssl_state->client_connp.ja3_str->used); } static int Ja3SGetHash(lua_State *luastate) @@ -122,9 +118,8 @@ static int Ja3SGetHash(lua_State *luastate) if (ssl_state->server_connp.ja3_hash == NULL) return LuaCallbackError(luastate, "error: no JA3S hash"); - return LuaPushStringBuffer(luastate, - (uint8_t *)ssl_state->server_connp.ja3_hash, - strlen(ssl_state->server_connp.ja3_hash)); + return LuaPushStringBuffer(luastate, (uint8_t *)ssl_state->server_connp.ja3_hash, + strlen(ssl_state->server_connp.ja3_hash)); } static int Ja3SGetString(lua_State *luastate) @@ -142,13 +137,11 @@ static int Ja3SGetString(lua_State *luastate) SSLState *ssl_state = (SSLState *)state; - if (ssl_state->server_connp.ja3_str == NULL || - ssl_state->server_connp.ja3_str->data == NULL) + if (ssl_state->server_connp.ja3_str == NULL || ssl_state->server_connp.ja3_str->data == NULL) return LuaCallbackError(luastate, "error: no JA3S str"); - return LuaPushStringBuffer(luastate, - (uint8_t *)ssl_state->server_connp.ja3_str->data, - ssl_state->server_connp.ja3_str->used); + return LuaPushStringBuffer(luastate, (uint8_t *)ssl_state->server_connp.ja3_str->data, + ssl_state->server_connp.ja3_str->used); } /** *\brief Register JA3 Lua extensions */ diff --git a/src/util-lua-smtp.c b/src/util-lua-smtp.c index a0ecf815d98b..7c7f179cf0b1 100644 --- a/src/util-lua-smtp.c +++ b/src/util-lua-smtp.c @@ -60,30 +60,30 @@ static int GetMimeDecField(lua_State *luastate, Flow *flow, const char *name) { /* extract state from flow */ - SMTPState *state = (SMTPState *) FlowGetAppState(flow); + SMTPState *state = (SMTPState *)FlowGetAppState(flow); /* check that state exists */ - if(state == NULL) { + if (state == NULL) { return LuaCallbackError(luastate, "Internal error: no state in flow"); } /* pointer to current transaction in state */ SMTPTransaction *smtp_tx = state->curr_tx; - if(smtp_tx == NULL) { + if (smtp_tx == NULL) { return LuaCallbackError(luastate, "Transaction ending or not found"); } /* pointer to tail of msg list of MimeDecEntities in current transaction. */ MimeDecEntity *mime = smtp_tx->msg_tail; /* check if msg_tail was hit */ - if(mime == NULL){ + if (mime == NULL) { return LuaCallbackError(luastate, "Internal error: no fields in transaction"); } /* extract MIME field based on specific field name. */ MimeDecField *field = MimeDecFindField(mime, name); /* check MIME field */ - if(field == NULL) { + if (field == NULL) { return LuaCallbackError(luastate, "Error: mimefield not found"); } /* return extracted field. */ - if(field->value == NULL || field->value_len == 0){ + if (field->value == NULL || field->value_len == 0) { return LuaCallbackError(luastate, "Error, pointer error"); } @@ -102,12 +102,12 @@ static int GetMimeDecField(lua_State *luastate, Flow *flow, const char *name) static int SMTPGetMimeField(lua_State *luastate) { - if(!(LuaStateNeedProto(luastate, ALPROTO_SMTP))) { + if (!(LuaStateNeedProto(luastate, ALPROTO_SMTP))) { return LuaCallbackError(luastate, "error: protocol not SMTP"); } Flow *flow = LuaStateGetFlow(luastate); /* check that flow exist */ - if(flow == NULL) { + if (flow == NULL) { return LuaCallbackError(luastate, "Error: no flow found"); } const char *name = LuaGetStringArgument(luastate, 1); @@ -127,30 +127,30 @@ static int SMTPGetMimeField(lua_State *luastate) * * \retval 1 if the mimelist table is pushed to luastate stack. * Returns error int and msg pushed to luastate stack if error occurs. -*/ + */ static int GetMimeList(lua_State *luastate, Flow *flow) { - SMTPState *state = (SMTPState *) FlowGetAppState(flow); - if(state == NULL) { + SMTPState *state = (SMTPState *)FlowGetAppState(flow); + if (state == NULL) { return LuaCallbackError(luastate, "Error: no SMTP state"); } /* Create a pointer to the current SMTPtransaction */ SMTPTransaction *smtp_tx = state->curr_tx; - if(smtp_tx == NULL) { + if (smtp_tx == NULL) { return LuaCallbackError(luastate, "Error: no SMTP transaction found"); } /* Create a pointer to the tail of MimeDecEntity list */ MimeDecEntity *mime = smtp_tx->msg_tail; - if(mime == NULL) { + if (mime == NULL) { return LuaCallbackError(luastate, "Error: no mime entity found"); } MimeDecField *field = mime->field_list; - if(field == NULL) { + if (field == NULL) { return LuaCallbackError(luastate, "Error: no field_list found"); } - if(field->name == NULL || field->name_len == 0) { + if (field->name == NULL || field->name_len == 0) { return LuaCallbackError(luastate, "Error: field has no name"); } /* Counter of MIME fields found */ @@ -158,10 +158,10 @@ static int GetMimeList(lua_State *luastate, Flow *flow) /* loop trough the list of mimeFields, printing each name found */ lua_newtable(luastate); while (field != NULL) { - if(field->name != NULL && field->name_len != 0) { - lua_pushinteger(luastate,num++); + if (field->name != NULL && field->name_len != 0) { + lua_pushinteger(luastate, num++); LuaPushStringBuffer(luastate, field->name, field->name_len); - lua_settable(luastate,-3); + lua_settable(luastate, -3); } field = field->next; } @@ -182,12 +182,12 @@ static int GetMimeList(lua_State *luastate, Flow *flow) static int SMTPGetMimeList(lua_State *luastate) { /* Check if right protocol */ - if(!(LuaStateNeedProto(luastate, ALPROTO_SMTP))) { + if (!(LuaStateNeedProto(luastate, ALPROTO_SMTP))) { return LuaCallbackError(luastate, "Error: protocol not SMTP"); } /* Extract network flow */ Flow *flow = LuaStateGetFlow(luastate); - if(flow == NULL) { + if (flow == NULL) { return LuaCallbackError(luastate, "Error: no flow found"); } @@ -209,16 +209,16 @@ static int SMTPGetMimeList(lua_State *luastate) static int GetMailFrom(lua_State *luastate, Flow *flow) { /* Extract SMTPstate from current flow */ - SMTPState *state = (SMTPState *) FlowGetAppState(flow); + SMTPState *state = (SMTPState *)FlowGetAppState(flow); - if(state == NULL) { + if (state == NULL) { return LuaCallbackError(luastate, "Internal Error: no state"); } SMTPTransaction *smtp_tx = state->curr_tx; - if(smtp_tx == NULL) { + if (smtp_tx == NULL) { return LuaCallbackError(luastate, "Internal Error: no SMTP transaction"); } - if(smtp_tx->mail_from == NULL || smtp_tx->mail_from_len == 0) { + if (smtp_tx->mail_from == NULL || smtp_tx->mail_from_len == 0) { return LuaCallbackError(luastate, "MailFrom not found"); } return LuaPushStringBuffer(luastate, smtp_tx->mail_from, smtp_tx->mail_from_len); @@ -239,12 +239,12 @@ static int GetMailFrom(lua_State *luastate, Flow *flow) static int SMTPGetMailFrom(lua_State *luastate) { /* check protocol */ - if(!(LuaStateNeedProto(luastate, ALPROTO_SMTP))) { + if (!(LuaStateNeedProto(luastate, ALPROTO_SMTP))) { return LuaCallbackError(luastate, "Error: protocol not SMTP"); } /* Extract flow, with lockhint to check mutexlocking */ Flow *flow = LuaStateGetFlow(luastate); - if(flow == NULL) { + if (flow == NULL) { return LuaCallbackError(luastate, "Internal Error: no flow"); } @@ -266,13 +266,13 @@ static int SMTPGetMailFrom(lua_State *luastate) static int GetRcptList(lua_State *luastate, Flow *flow) { - SMTPState *state = (SMTPState *) FlowGetAppState(flow); - if(state == NULL) { + SMTPState *state = (SMTPState *)FlowGetAppState(flow); + if (state == NULL) { return LuaCallbackError(luastate, "Internal error, no state"); } SMTPTransaction *smtp_tx = state->curr_tx; - if(smtp_tx == NULL) { + if (smtp_tx == NULL) { return LuaCallbackError(luastate, "No more tx, or tx not found"); } @@ -282,7 +282,7 @@ static int GetRcptList(lua_State *luastate, Flow *flow) int u = 1; SMTPString *rcpt; - TAILQ_FOREACH(rcpt, &smtp_tx->rcpt_to_list, next) { + TAILQ_FOREACH (rcpt, &smtp_tx->rcpt_to_list, next) { lua_pushinteger(luastate, u++); LuaPushStringBuffer(luastate, rcpt->str, rcpt->len); lua_settable(luastate, -3); @@ -306,12 +306,12 @@ static int GetRcptList(lua_State *luastate, Flow *flow) static int SMTPGetRcptList(lua_State *luastate) { /* check protocol */ - if(!(LuaStateNeedProto(luastate, ALPROTO_SMTP))) { + if (!(LuaStateNeedProto(luastate, ALPROTO_SMTP))) { return LuaCallbackError(luastate, "Error: protocol not SMTP"); } /* Extract flow, with lockhint to check mutexlocking */ Flow *flow = LuaStateGetFlow(luastate); - if(flow == NULL) { + if (flow == NULL) { return LuaCallbackError(luastate, "Internal error: no flow"); } diff --git a/src/util-lua-ssh.c b/src/util-lua-ssh.c index 266d3df860b5..d3dfeb1582b9 100644 --- a/src/util-lua-ssh.c +++ b/src/util-lua-ssh.c @@ -15,7 +15,6 @@ * 02110-1301, USA. */ - /** * \file * diff --git a/src/util-lua-tls.c b/src/util-lua-tls.c index 9413f42965ca..cf67618dfb42 100644 --- a/src/util-lua-tls.c +++ b/src/util-lua-tls.c @@ -15,7 +15,6 @@ * 02110-1301, USA. */ - /** * \file * @@ -162,9 +161,12 @@ static int GetCertInfo(lua_State *luastate, const Flow *f, int direction) SSLVersionToString(ssl_state->server_connp.version, ssl_version); int r = LuaPushStringBuffer(luastate, (uint8_t *)ssl_version, strlen(ssl_version)); - r += LuaPushStringBuffer(luastate, (uint8_t *)connp->cert0_subject, strlen(connp->cert0_subject)); - r += LuaPushStringBuffer(luastate, (uint8_t *)connp->cert0_issuerdn, strlen(connp->cert0_issuerdn)); - r += LuaPushStringBuffer(luastate, (uint8_t *)connp->cert0_fingerprint, strlen(connp->cert0_fingerprint)); + r += LuaPushStringBuffer( + luastate, (uint8_t *)connp->cert0_subject, strlen(connp->cert0_subject)); + r += LuaPushStringBuffer( + luastate, (uint8_t *)connp->cert0_issuerdn, strlen(connp->cert0_issuerdn)); + r += LuaPushStringBuffer( + luastate, (uint8_t *)connp->cert0_fingerprint, strlen(connp->cert0_fingerprint)); return r; } @@ -197,8 +199,7 @@ static int GetAgreedVersion(lua_State *luastate, const Flow *f) char ssl_version[SSL_VERSION_MAX_STRLEN]; SSLVersionToString(ssl_state->server_connp.version, ssl_version); - return LuaPushStringBuffer(luastate, (uint8_t *)ssl_version, - strlen(ssl_version)); + return LuaPushStringBuffer(luastate, (uint8_t *)ssl_version, strlen(ssl_version)); } static int TlsGetVersion(lua_State *luastate) @@ -228,8 +229,8 @@ static int GetSNI(lua_State *luastate, const Flow *f) if (ssl_state->client_connp.sni == NULL) return LuaCallbackError(luastate, "error: no server name indication"); - return LuaPushStringBuffer(luastate, (uint8_t *)ssl_state->client_connp.sni, - strlen(ssl_state->client_connp.sni)); + return LuaPushStringBuffer( + luastate, (uint8_t *)ssl_state->client_connp.sni, strlen(ssl_state->client_connp.sni)); } static int TlsGetSNI(lua_State *luastate) @@ -259,9 +260,8 @@ static int GetCertSerial(lua_State *luastate, const Flow *f) if (ssl_state->server_connp.cert0_serial == NULL) return LuaCallbackError(luastate, "error: no certificate serial"); - return LuaPushStringBuffer(luastate, - (uint8_t *)ssl_state->server_connp.cert0_serial, - strlen(ssl_state->server_connp.cert0_serial)); + return LuaPushStringBuffer(luastate, (uint8_t *)ssl_state->server_connp.cert0_serial, + strlen(ssl_state->server_connp.cert0_serial)); } static int TlsGetCertSerial(lua_State *luastate) @@ -298,8 +298,7 @@ static int GetCertChain(lua_State *luastate, const Flow *f, int direction) uint32_t u = 0; lua_newtable(luastate); SSLCertsChain *cert = NULL; - TAILQ_FOREACH(cert, &connp->certs, next) - { + TAILQ_FOREACH (cert, &connp->certs, next) { lua_pushinteger(luastate, u++); lua_newtable(luastate); diff --git a/src/util-lua.c b/src/util-lua.c index 9e65c3017fcb..c02f60781faf 100644 --- a/src/util-lua.c +++ b/src/util-lua.c @@ -293,7 +293,8 @@ void LuaStateSetDirection(lua_State *luastate, int direction) } /** \brief dump stack from lua state to screen */ -void LuaPrintStack(lua_State *state) { +void LuaPrintStack(lua_State *state) +{ int size = lua_gettop(state); int i; @@ -320,7 +321,6 @@ void LuaPrintStack(lua_State *state) { default: printf("other %s", lua_typename(state, type)); break; - } printf("\n"); } diff --git a/src/util-luajit.c b/src/util-luajit.c index a089e139cfcf..b8e52a48e021 100644 --- a/src/util-luajit.c +++ b/src/util-luajit.c @@ -77,7 +77,7 @@ int LuajitSetupStatesPool(void) ConfNode *denode = NULL; ConfNode *decnf = ConfGetNode("detect-engine"); if (decnf != NULL) { - TAILQ_FOREACH(denode, &decnf->head, next) { + TAILQ_FOREACH (denode, &decnf->head, next) { if (denode->val && strcmp(denode->val, "luajit-states") == 0) { ConfGetChildValueInt(denode, "luajit-states", &cnt); } diff --git a/src/util-macset.c b/src/util-macset.c index 9853a3241680..5d499fa885e2 100644 --- a/src/util-macset.c +++ b/src/util-macset.c @@ -52,8 +52,7 @@ struct MacSet_ { MacSetState state[2]; /* buffer for multiple MACs per flow and direction */ MacAddr *buf[2]; - int size, - last[2]; + int size, last[2]; }; FlowStorageId g_macset_storage_id = { .id = -1 }; @@ -65,14 +64,15 @@ void MacSetRegisterFlowStorage(void) /* we only need to register if at least one enabled 'eve-log' output has the ethernet setting enabled */ if (root != NULL) { - TAILQ_FOREACH(node, &root->head, next) { + TAILQ_FOREACH (node, &root->head, next) { if (node->val && strcmp(node->val, "eve-log") == 0) { const char *enabled = ConfNodeLookupChildValue(node->head.tqh_first, "enabled"); if (enabled != NULL && ConfValIsTrue(enabled)) { - const char *ethernet = ConfNodeLookupChildValue(node->head.tqh_first, "ethernet"); + const char *ethernet = + ConfNodeLookupChildValue(node->head.tqh_first, "ethernet"); if (ethernet != NULL && ConfValIsTrue(ethernet)) { - g_macset_storage_id = FlowStorageRegister("macset", sizeof(void *), - NULL, (void(*)(void *)) MacSetFree); + g_macset_storage_id = FlowStorageRegister( + "macset", sizeof(void *), NULL, (void (*)(void *))MacSetFree); return; } } @@ -86,7 +86,6 @@ bool MacSetFlowStorageEnabled(void) return (g_macset_storage_id.id != -1); } - MacSet *MacSetInit(int size) { MacSet *ms = NULL; @@ -98,7 +97,7 @@ MacSet *MacSetInit(int size) SCLogError("Unable to allocate MacSet memory"); return NULL; } - (void) SC_ATOMIC_ADD(flow_memuse, (sizeof(*ms))); + (void)SC_ATOMIC_ADD(flow_memuse, (sizeof(*ms))); ms->state[MAC_SET_SRC] = ms->state[MAC_SET_DST] = EMPTY_SET; if (size < 3) { /* we want to make sure we have at space for at least 3 items to @@ -137,7 +136,7 @@ static inline void MacUpdateEntry(MacSet *ms, uint8_t *addr, int side, ThreadVar "MacSet memory"); return; } - (void) SC_ATOMIC_ADD(flow_memuse, (ms->size * sizeof(MacAddr))); + (void)SC_ATOMIC_ADD(flow_memuse, (ms->size * sizeof(MacAddr))); } memcpy(ms->buf[side], ms->singles[side], sizeof(MacAddr)); memcpy(ms->buf[side] + 1, addr, sizeof(MacAddr)); @@ -160,7 +159,7 @@ static inline void MacUpdateEntry(MacSet *ms, uint8_t *addr, int side, ThreadVar since we expect the latest item to match more likely than the first */ for (int i = ms->last[side] - 1; i >= 0; i--) { - uint8_t *addr2 = (uint8_t*) ((ms->buf[side]) + i); + uint8_t *addr2 = (uint8_t *)((ms->buf[side]) + i); /* If we find a match, we return early with no action */ if (likely(memcmp(addr2, addr, sizeof(MacAddr)) == 0)) { return; @@ -177,7 +176,7 @@ static inline void MacUpdateEntry(MacSet *ms, uint8_t *addr, int side, ThreadVar } void MacSetAddWithCtr(MacSet *ms, uint8_t *src_addr, uint8_t *dst_addr, ThreadVars *tv, - uint16_t ctr_src, uint16_t ctr_dst) + uint16_t ctr_src, uint16_t ctr_dst) { if (ms == NULL) return; @@ -190,22 +189,22 @@ void MacSetAdd(MacSet *ms, uint8_t *src_addr, uint8_t *dst_addr) MacSetAddWithCtr(ms, src_addr, dst_addr, NULL, 0, 0); } -static inline int MacSetIterateSide(const MacSet *ms, MacSetIteratorFunc IterFunc, - MacSetSide side, void *data) +static inline int MacSetIterateSide( + const MacSet *ms, MacSetIteratorFunc IterFunc, MacSetSide side, void *data) { int ret = 0; switch (ms->state[side]) { case EMPTY_SET: return 0; case SINGLE_MAC: - ret = IterFunc((uint8_t*) ms->singles[side], side, data); + ret = IterFunc((uint8_t *)ms->singles[side], side, data); if (unlikely(ret != 0)) { return ret; } break; case MULTI_MAC: for (int i = 0; i < ms->last[side]; i++) { - ret = IterFunc((uint8_t*) ms->buf[side][i], side, data); + ret = IterFunc((uint8_t *)ms->buf[side][i], side, data); if (unlikely(ret != 0)) { return ret; } @@ -234,7 +233,7 @@ int MacSetSize(const MacSet *ms) if (ms == NULL) return 0; - switch(ms->state[MAC_SET_SRC]) { + switch (ms->state[MAC_SET_SRC]) { case EMPTY_SET: /* pass */ break; @@ -245,7 +244,7 @@ int MacSetSize(const MacSet *ms) size += ms->last[MAC_SET_SRC]; break; } - switch(ms->state[MAC_SET_DST]) { + switch (ms->state[MAC_SET_DST]) { case EMPTY_SET: /* pass */ break; @@ -274,23 +273,26 @@ void MacSetFree(MacSet *ms) } SCFree(ms); total_free += sizeof(*ms); - (void) SC_ATOMIC_SUB(flow_memuse, total_free); + (void)SC_ATOMIC_SUB(flow_memuse, total_free); } #ifdef UNITTESTS static int CheckTest1Membership(uint8_t *addr, MacSetSide side, void *data) { - int *i = (int*) data; + int *i = (int *)data; switch (*i) { case 0: - if (addr[5] != 1) return 1; + if (addr[5] != 1) + return 1; break; case 1: - if (addr[5] != 2) return 1; + if (addr[5] != 2) + return 1; break; case 2: - if (addr[5] != 3) return 1; + if (addr[5] != 3) + return 1; break; } (*i)++; @@ -301,9 +303,8 @@ static int MacSetTest01(void) { MacSet *ms = NULL; int ret = 0, i = 0; - MacAddr addr1 = {0x0, 0x0, 0x0, 0x0, 0x0, 0x1}, - addr2 = {0x0, 0x0, 0x0, 0x0, 0x0, 0x2}, - addr3 = {0x0, 0x0, 0x0, 0x0, 0x0, 0x3}; + MacAddr addr1 = { 0x0, 0x0, 0x0, 0x0, 0x0, 0x1 }, addr2 = { 0x0, 0x0, 0x0, 0x0, 0x0, 0x2 }, + addr3 = { 0x0, 0x0, 0x0, 0x0, 0x0, 0x3 }; SC_ATOMIC_SET(flow_config.memcap, 10000); ms = MacSetInit(10); @@ -341,8 +342,7 @@ static int MacSetTest02(void) FAIL_IF_NOT(MacSetSize(ms) == 0); for (i = 1; i < 100; i++) { - MacAddr addr1 = {0x0, 0x0, 0x0, 0x0, 0x0, 0x1}, - addr2 = {0x1, 0x0, 0x0, 0x0, 0x0, 0x2}; + MacAddr addr1 = { 0x0, 0x0, 0x0, 0x0, 0x0, 0x1 }, addr2 = { 0x1, 0x0, 0x0, 0x0, 0x0, 0x2 }; MacSetAdd(ms, addr1, addr2); } FAIL_IF_NOT(MacSetSize(ms) == 2); @@ -364,8 +364,7 @@ static int MacSetTest03(void) FAIL_IF_NOT(MacSetSize(ms) == 0); for (uint8_t i = 1; i < 100; i++) { - MacAddr addr1 = {0x0, 0x0, 0x0, 0x0, 0x0, 0x1}, - addr2 = {0x1, 0x0, 0x0, 0x0, 0x0, 0x1}; + MacAddr addr1 = { 0x0, 0x0, 0x0, 0x0, 0x0, 0x1 }, addr2 = { 0x1, 0x0, 0x0, 0x0, 0x0, 0x1 }; addr1[5] = i; addr2[5] = i; MacSetAdd(ms, addr1, addr2); @@ -398,8 +397,7 @@ static int MacSetTest05(void) FAIL_IF_NOT(MacSetSize(ms) == 0); for (uint8_t i = 1; i < 100; i++) { - MacAddr addr1 = {0x0, 0x0, 0x0, 0x0, 0x0, 0x1}, - addr2 = {0x1, 0x0, 0x0, 0x0, 0x0, 0x1}; + MacAddr addr1 = { 0x0, 0x0, 0x0, 0x0, 0x0, 0x1 }, addr2 = { 0x1, 0x0, 0x0, 0x0, 0x0, 0x1 }; addr1[5] = i; addr2[5] = i; MacSetAdd(ms, addr1, addr2); diff --git a/src/util-macset.h b/src/util-macset.h index 1b17255593c5..02ba51a3f67a 100644 --- a/src/util-macset.h +++ b/src/util-macset.h @@ -25,24 +25,21 @@ #define __UTIL_MACSET_H__ typedef struct MacSet_ MacSet; -typedef enum { - MAC_SET_SRC = 0, - MAC_SET_DST -} MacSetSide; +typedef enum { MAC_SET_SRC = 0, MAC_SET_DST } MacSetSide; -typedef int (*MacSetIteratorFunc)(uint8_t *addr, MacSetSide side, void*); +typedef int (*MacSetIteratorFunc)(uint8_t *addr, MacSetSide side, void *); MacSet *MacSetInit(int size); -void MacSetAdd(MacSet*, uint8_t *src_addr, uint8_t *dst_addr); -void MacSetAddWithCtr(MacSet*, uint8_t *src_addr, uint8_t *dst_addr, ThreadVars *tv, - uint16_t ctr_src, uint16_t ctr_dst); -int MacSetForEach(const MacSet*, MacSetIteratorFunc, void*); -int MacSetSize(const MacSet*); -void MacSetReset(MacSet*); -void MacSetFree(MacSet*); -void MacSetRegisterFlowStorage(void); +void MacSetAdd(MacSet *, uint8_t *src_addr, uint8_t *dst_addr); +void MacSetAddWithCtr(MacSet *, uint8_t *src_addr, uint8_t *dst_addr, ThreadVars *tv, + uint16_t ctr_src, uint16_t ctr_dst); +int MacSetForEach(const MacSet *, MacSetIteratorFunc, void *); +int MacSetSize(const MacSet *); +void MacSetReset(MacSet *); +void MacSetFree(MacSet *); +void MacSetRegisterFlowStorage(void); FlowStorageId MacSetGetFlowStorageID(void); -bool MacSetFlowStorageEnabled(void); -void MacSetRegisterTests(void); +bool MacSetFlowStorageEnabled(void); +void MacSetRegisterTests(void); #endif /* __UTIL_MACSET_H__ */ diff --git a/src/util-magic.c b/src/util-magic.c index 4e82cf24a881..e93a7be66167 100644 --- a/src/util-magic.c +++ b/src/util-magic.c @@ -52,18 +52,16 @@ magic_t MagicInitContext(void) (void)ConfGet("magic-file", &filename); - if (filename != NULL) { if (strlen(filename) == 0) { /* set filename to NULL on *nix systems so magic_load uses system * default path (see man libmagic) */ SCLogConfig("using system default magic-file"); filename = NULL; - } - else { + } else { SCLogConfig("using magic-file %s", filename); - if ( (fd = fopen(filename, "r")) == NULL) { + if ((fd = fopen(filename, "r")) == NULL) { SCLogWarning("Error opening file: \"%s\": %s", filename, strerror(errno)); goto error; } @@ -85,7 +83,6 @@ magic_t MagicInitContext(void) return NULL; } - void MagicDeinitContext(magic_t ctx) { if (ctx != NULL) @@ -144,7 +141,7 @@ static int MagicInitTest01(void) } result = 1; - end: +end: magic_close(magic_ctx); return result; } @@ -154,7 +151,7 @@ static int MagicDetectTest01(void) { magic_t magic_ctx; char *result = NULL; - char buffer[] = { 0x25, 'P', 'D', 'F', '-', '1', '.', '3', 0x0d, 0x0a}; + char buffer[] = { 0x25, 'P', 'D', 'F', '-', '1', '.', '3', 0x0d, 0x0a }; size_t buffer_len = sizeof(buffer); int retval = 0; @@ -171,7 +168,7 @@ static int MagicDetectTest01(void) result = (char *)magic_buffer(magic_ctx, (void *)buffer, buffer_len); if (result == NULL || strncmp(result, "PDF document", 12) != 0) { - printf("result %p:%s, not \"PDF document\": ", result,result?result:"(null)"); + printf("result %p:%s, not \"PDF document\": ", result, result ? result : "(null)"); goto end; } @@ -233,28 +230,154 @@ static int MagicDetectTest02(void) static int MagicDetectTest03(void) { char buffer[] = { - 0x50, 0x4b, 0x03, 0x04, 0x14, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x0b, 0x55, 0x2a, 0x36, 0x5e, 0xc6, - 0x32, 0x0c, 0x27, 0x00, 0x00, 0x00, 0x27, 0x00, - 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x6d, 0x69, - - 0x6d, 0x65, 0x74, 0x79, 0x70, 0x65, 0x61, 0x70, - 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, - 0x6e, 0x2f, 0x76, 0x6e, 0x64, 0x2e, 0x6f, 0x61, - 0x73, 0x69, 0x73, 0x2e, 0x6f, 0x70, 0x65, 0x6e, - - 0x64, 0x6f, 0x63, 0x75, 0x6d, 0x65, 0x6e, 0x74, - 0x2e, 0x74, 0x65, 0x78, 0x74, 0x50, 0x4b, 0x03, - 0x04, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0b, - 0x55, 0x2a, 0x36, 0x00, 0x00, 0x00, 0x00, 0x00, - - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1a, - 0x00, 0x00, 0x00, 0x43, 0x6f, 0x6e, 0x66, 0x69, - 0x67, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, - 0x73, 0x32, 0x2f, 0x73, 0x74, 0x61, 0x74, 0x75, - - 0x73, 0x62, 0x61, 0x72, 0x2f, 0x50, 0x4b, 0x03, - 0x04, 0x14, 0x00, 0x08, 0x00, 0x08, 0x00, 0x0b, + 0x50, + 0x4b, + 0x03, + 0x04, + 0x14, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x0b, + 0x55, + 0x2a, + 0x36, + 0x5e, + 0xc6, + 0x32, + 0x0c, + 0x27, + 0x00, + 0x00, + 0x00, + 0x27, + 0x00, + 0x00, + 0x00, + 0x08, + 0x00, + 0x00, + 0x00, + 0x6d, + 0x69, + + 0x6d, + 0x65, + 0x74, + 0x79, + 0x70, + 0x65, + 0x61, + 0x70, + 0x70, + 0x6c, + 0x69, + 0x63, + 0x61, + 0x74, + 0x69, + 0x6f, + 0x6e, + 0x2f, + 0x76, + 0x6e, + 0x64, + 0x2e, + 0x6f, + 0x61, + 0x73, + 0x69, + 0x73, + 0x2e, + 0x6f, + 0x70, + 0x65, + 0x6e, + + 0x64, + 0x6f, + 0x63, + 0x75, + 0x6d, + 0x65, + 0x6e, + 0x74, + 0x2e, + 0x74, + 0x65, + 0x78, + 0x74, + 0x50, + 0x4b, + 0x03, + 0x04, + 0x14, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x0b, + 0x55, + 0x2a, + 0x36, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x1a, + 0x00, + 0x00, + 0x00, + 0x43, + 0x6f, + 0x6e, + 0x66, + 0x69, + 0x67, + 0x75, + 0x72, + 0x61, + 0x74, + 0x69, + 0x6f, + 0x6e, + 0x73, + 0x32, + 0x2f, + 0x73, + 0x74, + 0x61, + 0x74, + 0x75, + + 0x73, + 0x62, + 0x61, + 0x72, + 0x2f, + 0x50, + 0x4b, + 0x03, + 0x04, + 0x14, + 0x00, + 0x08, + 0x00, + 0x08, + 0x00, + 0x0b, }; size_t buffer_len = sizeof(buffer); @@ -280,34 +403,195 @@ static int MagicDetectTest04(void) char *result = NULL; char buffer[] = { - 0x50, 0x4b, 0x03, 0x04, 0x14, 0x00, 0x00, 0x08, - 0x00, 0x00, 0x52, 0x7b, 0x86, 0x3c, 0x8b, 0x70, - 0x96, 0x08, 0x1c, 0x00, 0x00, 0x00, 0x1c, 0x00, - 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x6d, 0x69, - - 0x6d, 0x65, 0x74, 0x79, 0x70, 0x65, 0x61, 0x70, - 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, - 0x6e, 0x2f, 0x76, 0x6e, 0x64, 0x2e, 0x73, 0x75, - 0x6e, 0x2e, 0x78, 0x6d, 0x6c, 0x2e, 0x62, 0x61, - - 0x73, 0x65, 0x50, 0x4b, 0x03, 0x04, 0x14, 0x00, - 0x00, 0x08, 0x00, 0x00, 0x52, 0x7b, 0x86, 0x3c, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x00, - - 0x4d, 0x45, 0x54, 0x41, 0x2d, 0x49, 0x4e, 0x46, - 0x2f, 0x50, 0x4b, 0x03, 0x04, 0x14, 0x00, 0x00, - 0x08, 0x08, 0x00, 0xa8, 0x42, 0x1d, 0x37, 0x5d, - 0xa7, 0xb2, 0xc1, 0xde, 0x01, 0x00, 0x00, 0x7e, - - 0x04, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x63, - 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2e, 0x78, - 0x6d, 0x6c, 0x95, 0x54, 0x4d, 0x6f, 0xdb, 0x30, - 0x0c, 0xbd, 0xe7, 0x57, 0x18, 0x02, 0x06, 0x6c, - - 0x07, 0xc5, 0xe9, 0xb6, 0xc3, 0x22, 0xc4, 0x29, - 0x86, 0x7d, 0x00, 0x05, 0x8a, 0x9d, 0xb2, 0x43, - 0x8f, 0xb2, 0x24, 0xa7, 0xc2, 0x64, 0xc9, 0x15, + 0x50, + 0x4b, + 0x03, + 0x04, + 0x14, + 0x00, + 0x00, + 0x08, + 0x00, + 0x00, + 0x52, + 0x7b, + 0x86, + 0x3c, + 0x8b, + 0x70, + 0x96, + 0x08, + 0x1c, + 0x00, + 0x00, + 0x00, + 0x1c, + 0x00, + 0x00, + 0x00, + 0x08, + 0x00, + 0x00, + 0x00, + 0x6d, + 0x69, + + 0x6d, + 0x65, + 0x74, + 0x79, + 0x70, + 0x65, + 0x61, + 0x70, + 0x70, + 0x6c, + 0x69, + 0x63, + 0x61, + 0x74, + 0x69, + 0x6f, + 0x6e, + 0x2f, + 0x76, + 0x6e, + 0x64, + 0x2e, + 0x73, + 0x75, + 0x6e, + 0x2e, + 0x78, + 0x6d, + 0x6c, + 0x2e, + 0x62, + 0x61, + + 0x73, + 0x65, + 0x50, + 0x4b, + 0x03, + 0x04, + 0x14, + 0x00, + 0x00, + 0x08, + 0x00, + 0x00, + 0x52, + 0x7b, + 0x86, + 0x3c, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x09, + 0x00, + 0x00, + 0x00, + + 0x4d, + 0x45, + 0x54, + 0x41, + 0x2d, + 0x49, + 0x4e, + 0x46, + 0x2f, + 0x50, + 0x4b, + 0x03, + 0x04, + 0x14, + 0x00, + 0x00, + 0x08, + 0x08, + 0x00, + 0xa8, + 0x42, + 0x1d, + 0x37, + 0x5d, + 0xa7, + 0xb2, + 0xc1, + 0xde, + 0x01, + 0x00, + 0x00, + 0x7e, + + 0x04, + 0x00, + 0x00, + 0x0b, + 0x00, + 0x00, + 0x00, + 0x63, + 0x6f, + 0x6e, + 0x74, + 0x65, + 0x6e, + 0x74, + 0x2e, + 0x78, + 0x6d, + 0x6c, + 0x95, + 0x54, + 0x4d, + 0x6f, + 0xdb, + 0x30, + 0x0c, + 0xbd, + 0xe7, + 0x57, + 0x18, + 0x02, + 0x06, + 0x6c, + + 0x07, + 0xc5, + 0xe9, + 0xb6, + 0xc3, + 0x22, + 0xc4, + 0x29, + 0x86, + 0x7d, + 0x00, + 0x05, + 0x8a, + 0x9d, + 0xb2, + 0x43, + 0x8f, + 0xb2, + 0x24, + 0xa7, + 0xc2, + 0x64, + 0xc9, + 0x15, }; size_t buffer_len = sizeof(buffer); int retval = 0; @@ -325,7 +609,7 @@ static int MagicDetectTest04(void) result = (char *)magic_buffer(magic_ctx, (void *)buffer, buffer_len); if (result == NULL || strncmp(result, "OpenOffice.org 1.x", 18) != 0) { - printf("result %p:%s, not \"OpenOffice.org 1.x\": ", result,result?result:"(null)"); + printf("result %p:%s, not \"OpenOffice.org 1.x\": ", result, result ? result : "(null)"); goto end; } @@ -335,7 +619,6 @@ static int MagicDetectTest04(void) return retval; } - /** \test magic api calls -- lookup */ static int MagicDetectTest05(void) { @@ -347,13 +630,12 @@ static int MagicDetectTest05(void) size_t buffer_len = sizeof(buffer); int retval = 0; - ctx = MagicInitContext(); FAIL_IF(ctx == NULL); result = MagicThreadLookup(&ctx, buffer, buffer_len); if (result == NULL || strncmp(result, "PDF document", 12) != 0) { - printf("result %p:%s, not \"PDF document\": ", result,result?result:"(null)"); + printf("result %p:%s, not \"PDF document\": ", result, result ? result : "(null)"); goto end; } @@ -498,7 +780,7 @@ static int MagicDetectTest08(void) result = MagicThreadLookup(&ctx, buffer, buffer_len); if (result == NULL || strncmp(result, "OpenOffice.org 1.x", 18) != 0) { - printf("result %p:%s, not \"OpenOffice.org 1.x\": ", result,result?result:"(null)"); + printf("result %p:%s, not \"OpenOffice.org 1.x\": ", result, result ? result : "(null)"); goto end; } @@ -571,13 +853,12 @@ static int MagicDetectTest10ValgrindError(void) size_t buffer_len = sizeof(buffer); int retval = 0; - ctx = MagicInitContext(); FAIL_IF(ctx == NULL); result = MagicThreadLookup(&ctx, buffer, buffer_len); if (result == NULL || strncmp(result, "JPEG", 4) != 0) { - printf("result %p:%s, not \"JPEG\": ", result,result?result:"(null)"); + printf("result %p:%s, not \"JPEG\": ", result, result ? result : "(null)"); goto end; } @@ -596,19 +877,17 @@ void MagicRegisterTests(void) #ifdef UNITTESTS UtRegisterTest("MagicInitTest01", MagicInitTest01); UtRegisterTest("MagicDetectTest01", MagicDetectTest01); - //UtRegisterTest("MagicDetectTest02", MagicDetectTest02, 1); + // UtRegisterTest("MagicDetectTest02", MagicDetectTest02, 1); UtRegisterTest("MagicDetectTest03", MagicDetectTest03); UtRegisterTest("MagicDetectTest04", MagicDetectTest04); UtRegisterTest("MagicDetectTest05", MagicDetectTest05); - //UtRegisterTest("MagicDetectTest06", MagicDetectTest06, 1); + // UtRegisterTest("MagicDetectTest06", MagicDetectTest06, 1); UtRegisterTest("MagicDetectTest07", MagicDetectTest07); UtRegisterTest("MagicDetectTest08", MagicDetectTest08); /* fails in valgrind, somehow it returns different pointers then. UtRegisterTest("MagicDetectTest09", MagicDetectTest09, 1); */ - UtRegisterTest("MagicDetectTest10ValgrindError", - MagicDetectTest10ValgrindError); + UtRegisterTest("MagicDetectTest10ValgrindError", MagicDetectTest10ValgrindError); #endif /* UNITTESTS */ #endif /* HAVE_MAGIC */ } - diff --git a/src/util-mem.h b/src/util-mem.h index 56a7b22c78f0..b106aa496f9f 100644 --- a/src/util-mem.h +++ b/src/util-mem.h @@ -31,34 +31,33 @@ #ifndef __UTIL_MEM_H__ #define __UTIL_MEM_H__ -#if CPPCHECK==1 || defined(__clang_analyzer__) -#define SCMalloc malloc -#define SCCalloc calloc -#define SCRealloc realloc -#define SCFree free -#define SCStrdup strdup -#define SCStrndup strndup +#if CPPCHECK == 1 || defined(__clang_analyzer__) +#define SCMalloc malloc +#define SCCalloc calloc +#define SCRealloc realloc +#define SCFree free +#define SCStrdup strdup +#define SCStrndup strndup #define SCMallocAligned _mm_malloc -#define SCFreeAligned _mm_free +#define SCFreeAligned _mm_free #else /* CPPCHECK */ - void *SCMallocFunc(const size_t sz); -#define SCMalloc(sz) SCMallocFunc((sz)) +#define SCMalloc(sz) SCMallocFunc((sz)) void *SCReallocFunc(void *ptr, const size_t size); #define SCRealloc(ptr, sz) SCReallocFunc((ptr), (sz)) void *SCCallocFunc(const size_t nm, const size_t sz); -#define SCCalloc(nm, sz) SCCallocFunc((nm), (sz)) +#define SCCalloc(nm, sz) SCCallocFunc((nm), (sz)) char *SCStrdupFunc(const char *s); -#define SCStrdup(s) SCStrdupFunc((s)) +#define SCStrdup(s) SCStrdupFunc((s)) char *SCStrndupFunc(const char *s, size_t n); -#define SCStrndup(s, n) SCStrndupFunc((s), (n)) +#define SCStrndup(s, n) SCStrndupFunc((s), (n)) -#define SCFree(p) free((p)) +#define SCFree(p) free((p)) /** \brief wrapper for allocing aligned mem * \param a size @@ -74,9 +73,8 @@ void *SCMallocAlignedFunc(const size_t size, const size_t align); * _mm_free. */ void SCFreeAlignedFunc(void *ptr); -#define SCFreeAligned(p) SCFreeAlignedFunc((p)) +#define SCFreeAligned(p) SCFreeAlignedFunc((p)) #endif /* CPPCHECK */ #endif /* __UTIL_MEM_H__ */ - diff --git a/src/util-memcmp.c b/src/util-memcmp.c index 7113b82dd60c..a1c9983f87c0 100644 --- a/src/util-memcmp.c +++ b/src/util-memcmp.c @@ -33,7 +33,7 @@ #ifdef UNITTESTS #include "util-debug.h" -static int MemcmpTest01 (void) +static int MemcmpTest01(void) { uint8_t a[] = "abcd"; uint8_t b[] = "abcd"; @@ -42,7 +42,7 @@ static int MemcmpTest01 (void) PASS; } -static int MemcmpTest02 (void) +static int MemcmpTest02(void) { uint8_t a[] = "abcdabcdabcdabcd"; uint8_t b[] = "abcdabcdabcdabcd"; @@ -51,7 +51,7 @@ static int MemcmpTest02 (void) PASS; } -static int MemcmpTest03 (void) +static int MemcmpTest03(void) { uint8_t a[] = "abcdabcd"; uint8_t b[] = "abcdabcd"; @@ -60,18 +60,18 @@ static int MemcmpTest03 (void) PASS; } -static int MemcmpTest04 (void) +static int MemcmpTest04(void) { uint8_t a[] = "abcd"; uint8_t b[] = "abcD"; - int r = SCMemcmp(a, b, sizeof(a)-1); + int r = SCMemcmp(a, b, sizeof(a) - 1); FAIL_IF(r != 1); PASS; } -static int MemcmpTest05 (void) +static int MemcmpTest05(void) { uint8_t a[] = "abcdabcdabcdabcd"; uint8_t b[] = "abcDabcdabcdabcd"; @@ -80,7 +80,7 @@ static int MemcmpTest05 (void) PASS; } -static int MemcmpTest06 (void) +static int MemcmpTest06(void) { uint8_t a[] = "abcdabcd"; uint8_t b[] = "abcDabcd"; @@ -89,7 +89,7 @@ static int MemcmpTest06 (void) PASS; } -static int MemcmpTest07 (void) +static int MemcmpTest07(void) { uint8_t a[] = "abcd"; uint8_t b[] = "abcde"; @@ -98,7 +98,7 @@ static int MemcmpTest07 (void) PASS; } -static int MemcmpTest08 (void) +static int MemcmpTest08(void) { uint8_t a[] = "abcdabcdabcdabcd"; uint8_t b[] = "abcdabcdabcdabcde"; @@ -107,7 +107,7 @@ static int MemcmpTest08 (void) PASS; } -static int MemcmpTest09 (void) +static int MemcmpTest09(void) { uint8_t a[] = "abcdabcd"; uint8_t b[] = "abcdabcde"; @@ -116,7 +116,7 @@ static int MemcmpTest09 (void) PASS; } -static int MemcmpTest10 (void) +static int MemcmpTest10(void) { uint8_t a[] = "abcd"; uint8_t b[] = "Zbcde"; @@ -125,7 +125,7 @@ static int MemcmpTest10 (void) PASS; } -static int MemcmpTest11 (void) +static int MemcmpTest11(void) { uint8_t a[] = "abcdabcdabcdabcd"; uint8_t b[] = "Zbcdabcdabcdabcde"; @@ -134,7 +134,7 @@ static int MemcmpTest11 (void) PASS; } -static int MemcmpTest12 (void) +static int MemcmpTest12(void) { uint8_t a[] = "abcdabcd"; uint8_t b[] = "Zbcdabcde"; @@ -143,7 +143,7 @@ static int MemcmpTest12 (void) PASS; } -static int MemcmpTest13 (void) +static int MemcmpTest13(void) { uint8_t a[] = "abcdefgh"; uint8_t b[] = "AbCdEfGhIjK"; @@ -156,13 +156,17 @@ static int MemcmpTest13 (void) #define TEST_RUNS 1000000 -static int MemcmpTest14 (void) +static int MemcmpTest14(void) { #ifdef PROFILING uint64_t ticks_start = 0; uint64_t ticks_end = 0; - const char *a[] = { "0123456789012345", "abc", "abcdefghij", "suricata", "test", "xyz", "rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr", "abcdefghijklmnopqrstuvwxyz", NULL }; - const char *b[] = { "1234567890123456", "abc", "abcdefghik", "suricatb", "test", "xyz", "rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr", "abcdefghijklmnopqrstuvwxyz", NULL }; + const char *a[] = { "0123456789012345", "abc", "abcdefghij", "suricata", "test", "xyz", + "rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr", + "abcdefghijklmnopqrstuvwxyz", NULL }; + const char *b[] = { "1234567890123456", "abc", "abcdefghik", "suricatb", "test", "xyz", + "rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr", + "abcdefghijklmnopqrstuvwxyz", NULL }; int t = 0; int i, j; @@ -180,13 +184,15 @@ static int MemcmpTest14 (void) // printf("b[%d] = %s\n", j, b[j]); size_t blen = strlen(b[j]) - 1; - r1 += (memcmp((uint8_t *)a[i], (uint8_t *)b[j], (alen < blen) ? alen : blen) ? 1 : 0); + r1 += (memcmp((uint8_t *)a[i], (uint8_t *)b[j], (alen < blen) ? alen : blen) ? 1 + : 0); } } } ticks_end = UtilCpuGetTicks(); - printf("memcmp(%d) \t\t\t%"PRIu64"\n", TEST_RUNS, ((uint64_t)(ticks_end - ticks_start))/TEST_RUNS); - SCLogInfo("ticks passed %"PRIu64, ticks_end - ticks_start); + printf("memcmp(%d) \t\t\t%" PRIu64 "\n", TEST_RUNS, + ((uint64_t)(ticks_end - ticks_start)) / TEST_RUNS); + SCLogInfo("ticks passed %" PRIu64, ticks_end - ticks_start); printf("r1 %d\n", r1); FAIL_IF(r1 != (51 * TEST_RUNS)); @@ -194,13 +200,17 @@ static int MemcmpTest14 (void) PASS; } -static int MemcmpTest15 (void) +static int MemcmpTest15(void) { #ifdef PROFILING uint64_t ticks_start = 0; uint64_t ticks_end = 0; - const char *a[] = { "0123456789012345", "abc", "abcdefghij", "suricata", "test", "xyz", "rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr", "abcdefghijklmnopqrstuvwxyz", NULL }; - const char *b[] = { "1234567890123456", "abc", "abcdefghik", "suricatb", "test", "xyz", "rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr", "abcdefghijklmnopqrstuvwxyz", NULL }; + const char *a[] = { "0123456789012345", "abc", "abcdefghij", "suricata", "test", "xyz", + "rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr", + "abcdefghijklmnopqrstuvwxyz", NULL }; + const char *b[] = { "1234567890123456", "abc", "abcdefghik", "suricatb", "test", "xyz", + "rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr", + "abcdefghijklmnopqrstuvwxyz", NULL }; int t = 0; int i, j; @@ -218,13 +228,15 @@ static int MemcmpTest15 (void) // printf("b[%d] = %s\n", j, b[j]); size_t blen = strlen(b[j]) - 1; - r2 += MemcmpLowercase((uint8_t *)a[i], (uint8_t *)b[j], (alen < blen) ? alen : blen); + r2 += MemcmpLowercase( + (uint8_t *)a[i], (uint8_t *)b[j], (alen < blen) ? alen : blen); } } } ticks_end = UtilCpuGetTicks(); - printf("MemcmpLowercase(%d) \t\t%"PRIu64"\n", TEST_RUNS, ((uint64_t)(ticks_end - ticks_start))/TEST_RUNS); - SCLogInfo("ticks passed %"PRIu64, ticks_end - ticks_start); + printf("MemcmpLowercase(%d) \t\t%" PRIu64 "\n", TEST_RUNS, + ((uint64_t)(ticks_end - ticks_start)) / TEST_RUNS); + SCLogInfo("ticks passed %" PRIu64, ticks_end - ticks_start); printf("r2 %d\n", r2); FAIL_IF(r2 != (51 * TEST_RUNS)); @@ -232,13 +244,17 @@ static int MemcmpTest15 (void) PASS; } -static int MemcmpTest16 (void) +static int MemcmpTest16(void) { #ifdef PROFILING uint64_t ticks_start = 0; uint64_t ticks_end = 0; - const char *a[] = { "0123456789012345", "abc", "abcdefghij", "suricata", "test", "xyz", "rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr", "abcdefghijklmnopqrstuvwxyz", NULL }; - const char *b[] = { "1234567890123456", "abc", "abcdefghik", "suricatb", "test", "xyz", "rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr", "abcdefghijklmnopqrstuvwxyz", NULL }; + const char *a[] = { "0123456789012345", "abc", "abcdefghij", "suricata", "test", "xyz", + "rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr", + "abcdefghijklmnopqrstuvwxyz", NULL }; + const char *b[] = { "1234567890123456", "abc", "abcdefghik", "suricatb", "test", "xyz", + "rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr", + "abcdefghijklmnopqrstuvwxyz", NULL }; int t = 0; int i, j; @@ -261,8 +277,9 @@ static int MemcmpTest16 (void) } } ticks_end = UtilCpuGetTicks(); - printf("SCMemcmp(%d) \t\t\t%"PRIu64"\n", TEST_RUNS, ((uint64_t)(ticks_end - ticks_start))/TEST_RUNS); - SCLogInfo("ticks passed %"PRIu64, ticks_end - ticks_start); + printf("SCMemcmp(%d) \t\t\t%" PRIu64 "\n", TEST_RUNS, + ((uint64_t)(ticks_end - ticks_start)) / TEST_RUNS); + SCLogInfo("ticks passed %" PRIu64, ticks_end - ticks_start); printf("r3 %d\n", r3); FAIL_IF(r3 != (51 * TEST_RUNS)); @@ -270,13 +287,17 @@ static int MemcmpTest16 (void) PASS; } -static int MemcmpTest17 (void) +static int MemcmpTest17(void) { #ifdef PROFILING uint64_t ticks_start = 0; uint64_t ticks_end = 0; - const char *a[] = { "0123456789012345", "abc", "abcdefghij", "suricata", "test", "xyz", "rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr", "abcdefghijklmnopqrstuvwxyz", NULL }; - const char *b[] = { "1234567890123456", "abc", "abcdefghik", "suricatb", "test", "xyz", "rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr", "abcdefghijklmnopqrstuvwxyz", NULL }; + const char *a[] = { "0123456789012345", "abc", "abcdefghij", "suricata", "test", "xyz", + "rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr", + "abcdefghijklmnopqrstuvwxyz", NULL }; + const char *b[] = { "1234567890123456", "abc", "abcdefghik", "suricatb", "test", "xyz", + "rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr", + "abcdefghijklmnopqrstuvwxyz", NULL }; int t = 0; int i, j; @@ -294,13 +315,15 @@ static int MemcmpTest17 (void) // printf("b[%d] = %s\n", j, b[j]); size_t blen = strlen(b[j]) - 1; - r4 += SCMemcmpLowercase((uint8_t *)a[i], (uint8_t *)b[j], (alen < blen) ? alen : blen); + r4 += SCMemcmpLowercase( + (uint8_t *)a[i], (uint8_t *)b[j], (alen < blen) ? alen : blen); } } } ticks_end = UtilCpuGetTicks(); - printf("SCMemcmpLowercase(%d) \t\t%"PRIu64"\n", TEST_RUNS, ((uint64_t)(ticks_end - ticks_start))/TEST_RUNS); - SCLogInfo("ticks passed %"PRIu64, ticks_end - ticks_start); + printf("SCMemcmpLowercase(%d) \t\t%" PRIu64 "\n", TEST_RUNS, + ((uint64_t)(ticks_end - ticks_start)) / TEST_RUNS); + SCLogInfo("ticks passed %" PRIu64, ticks_end - ticks_start); printf("r4 %d\n", r4); FAIL_IF(r4 != (51 * TEST_RUNS)); @@ -313,27 +336,79 @@ struct MemcmpTest18Tests { const char *b; int result; } memcmp_tests18_tests[] = { - { "abcdefgh", "!bcdefgh", 1, }, - { "?bcdefgh", "!bcdefgh", 1, }, - { "!bcdefgh", "abcdefgh", 1, }, - { "!bcdefgh", "?bcdefgh", 1, }, - { "zbcdefgh", "bbcdefgh", 1, }, - - { "abcdefgh12345678", "!bcdefgh12345678", 1, }, - { "?bcdefgh12345678", "!bcdefgh12345678", 1, }, - { "!bcdefgh12345678", "abcdefgh12345678", 1, }, - { "!bcdefgh12345678", "?bcdefgh12345678", 1, }, - { "bbcdefgh12345678", "zbcdefgh12345678", 1, }, - - { "abcdefgh", "abcdefgh", 0, }, - { "abcdefgh", "Abcdefgh", 0, }, - { "abcdefgh12345678", "Abcdefgh12345678", 0, }, - - { NULL, NULL, 0 }, - - }; - -static int MemcmpTest18 (void) + { + "abcdefgh", + "!bcdefgh", + 1, + }, + { + "?bcdefgh", + "!bcdefgh", + 1, + }, + { + "!bcdefgh", + "abcdefgh", + 1, + }, + { + "!bcdefgh", + "?bcdefgh", + 1, + }, + { + "zbcdefgh", + "bbcdefgh", + 1, + }, + + { + "abcdefgh12345678", + "!bcdefgh12345678", + 1, + }, + { + "?bcdefgh12345678", + "!bcdefgh12345678", + 1, + }, + { + "!bcdefgh12345678", + "abcdefgh12345678", + 1, + }, + { + "!bcdefgh12345678", + "?bcdefgh12345678", + 1, + }, + { + "bbcdefgh12345678", + "zbcdefgh12345678", + 1, + }, + + { + "abcdefgh", + "abcdefgh", + 0, + }, + { + "abcdefgh", + "Abcdefgh", + 0, + }, + { + "abcdefgh12345678", + "Abcdefgh12345678", + 0, + }, + + { NULL, NULL, 0 }, + +}; + +static int MemcmpTest18(void) { struct MemcmpTest18Tests *t = memcmp_tests18_tests; @@ -371,4 +446,3 @@ void MemcmpRegisterTests(void) UtRegisterTest("MemcmpTest18", MemcmpTest18); #endif /* UNITTESTS */ } - diff --git a/src/util-memcmp.h b/src/util-memcmp.h index 47bfc98c9a16..f86e7272af0e 100644 --- a/src/util-memcmp.h +++ b/src/util-memcmp.h @@ -39,8 +39,7 @@ static inline int SCMemcmpLowercase(const void *, const void *, size_t); void MemcmpRegisterTests(void); -static inline int -MemcmpLowercase(const void *s1, const void *s2, size_t n) +static inline int MemcmpLowercase(const void *s1, const void *s2, size_t n) { for (size_t i = 0; i < n; i++) { if (((uint8_t *)s1)[i] != u8_tolower(((uint8_t *)s2)[i])) @@ -81,7 +80,23 @@ static inline int SCMemcmp(const void *s1, const void *s2, size_t n) /* Range of values of uppercase characters. We only use the first 2 bytes. */ static char scmemcmp_uppercase[16] __attribute__((aligned(16))) = { - 'A', 'Z', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; + 'A', + 'Z', + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, +}; /** \brief compare two buffers in a case insensitive way * \param s1 buffer already in lowercase @@ -92,7 +107,7 @@ static inline int SCMemcmpLowercase(const void *s1, const void *s2, size_t n) /* counter for how far we already matched in the buffer */ size_t m = 0; int r = 0; - __m128i ucase = _mm_load_si128((const __m128i *) scmemcmp_uppercase); + __m128i ucase = _mm_load_si128((const __m128i *)scmemcmp_uppercase); __m128i uplow = _mm_set1_epi8(0x20); do { @@ -126,7 +141,7 @@ static inline int SCMemcmpLowercase(const void *s1, const void *s2, size_t n) #elif defined(__SSE4_1__) #include -#define SCMEMCMP_BYTES 16 +#define SCMEMCMP_BYTES 16 static inline int SCMemcmp(const void *s1, const void *s2, size_t len) { @@ -153,8 +168,8 @@ static inline int SCMemcmp(const void *s1, const void *s2, size_t len) return 0; } -#define UPPER_LOW 0x40 /* "A" - 1 */ -#define UPPER_HIGH 0x5B /* "Z" + 1 */ +#define UPPER_LOW 0x40 /* "A" - 1 */ +#define UPPER_HIGH 0x5B /* "Z" + 1 */ static inline int SCMemcmpLowercase(const void *s1, const void *s2, size_t len) { @@ -172,8 +187,8 @@ static inline int SCMemcmpLowercase(const void *s1, const void *s2, size_t len) } /* unaligned loading of the bytes to compare */ - b1 = _mm_loadu_si128((const __m128i *) s1); - b2 = _mm_loadu_si128((const __m128i *) s2); + b1 = _mm_loadu_si128((const __m128i *)s1); + b2 = _mm_loadu_si128((const __m128i *)s2); /* mark all chars bigger than upper1 */ mask1 = _mm_cmpgt_epi8(b2, upper1); @@ -203,7 +218,7 @@ static inline int SCMemcmpLowercase(const void *s1, const void *s2, size_t len) #elif defined(__SSE3__) #include /* for SSE3 */ -#define SCMEMCMP_BYTES 16 +#define SCMEMCMP_BYTES 16 static inline int SCMemcmp(const void *s1, const void *s2, size_t len) { @@ -216,8 +231,8 @@ static inline int SCMemcmp(const void *s1, const void *s2, size_t len) } /* unaligned loads */ - b1 = _mm_loadu_si128((const __m128i *) s1); - b2 = _mm_loadu_si128((const __m128i *) s2); + b1 = _mm_loadu_si128((const __m128i *)s1); + b2 = _mm_loadu_si128((const __m128i *)s2); c = _mm_cmpeq_epi8(b1, b2); if (_mm_movemask_epi8(c) != 0x0000FFFF) { @@ -244,7 +259,7 @@ static inline int SCMemcmpLowercase(const void *s1, const void *s2, size_t len) /* setup registers for upper to lower conversion */ upper1 = _mm_set1_epi8(UPPER_LOW); upper2 = _mm_set1_epi8(UPPER_HIGH); - delta = _mm_set1_epi8(UPPER_DELTA); + delta = _mm_set1_epi8(UPPER_DELTA); do { if (likely(len - offset < SCMEMCMP_BYTES)) { @@ -252,8 +267,8 @@ static inline int SCMemcmpLowercase(const void *s1, const void *s2, size_t len) } /* unaligned loading of the bytes to compare */ - b1 = _mm_loadu_si128((const __m128i *) s1); - b2 = _mm_loadu_si128((const __m128i *) s2); + b1 = _mm_loadu_si128((const __m128i *)s1); + b2 = _mm_loadu_si128((const __m128i *)s2); /* mark all chars bigger than upper1 */ mask1 = _mm_cmpgt_epi8(b2, upper1); @@ -287,9 +302,7 @@ static inline int SCMemcmpLowercase(const void *s1, const void *s2, size_t len) /* No SIMD support, fall back to plain memcmp and a home grown lowercase one */ /* wrapper around memcmp to match the retvals of the SIMD implementations */ -#define SCMemcmp(a,b,c) ({ \ - memcmp((a), (b), (c)) ? 1 : 0; \ -}) +#define SCMemcmp(a, b, c) ({ memcmp((a), (b), (c)) ? 1 : 0; }) static inline int SCMemcmpLowercase(const void *s1, const void *s2, size_t len) { @@ -309,4 +322,3 @@ static inline int SCBufferCmp(const void *s1, size_t len1, const void *s2, size_ } #endif /* __UTIL_MEMCMP_H__ */ - diff --git a/src/util-memrchr.c b/src/util-memrchr.c index e531f845c7fd..56b62cffc7b9 100644 --- a/src/util-memrchr.c +++ b/src/util-memrchr.c @@ -27,7 +27,7 @@ #include "util-memrchr.h" #ifndef HAVE_MEMRCHR -void *memrchr (const void *s, int c, size_t n) +void *memrchr(const void *s, int c, size_t n) { const char *end = s + n; @@ -38,10 +38,10 @@ void *memrchr (const void *s, int c, size_t n) } return NULL; } -#endif /* HAVE_MEMRCHR */ +#endif /* HAVE_MEMRCHR */ #ifdef UNITTESTS -static int MemrchrTest01 (void) +static int MemrchrTest01(void) { const char *haystack = "abcabc"; char needle = 'b'; diff --git a/src/util-misc.c b/src/util-misc.c index 4380e694a8a0..9eef64998a3f 100644 --- a/src/util-misc.c +++ b/src/util-misc.c @@ -204,7 +204,7 @@ int ParseSizeStringU64(const char *size, uint64_t *res) if (r < 0) return r; - if (temp_res > (double) UINT64_MAX) + if (temp_res > (double)UINT64_MAX) return -1; *res = temp_res; @@ -212,8 +212,7 @@ int ParseSizeStringU64(const char *size, uint64_t *res) return 0; } -void ShortenString(const char *input, - char *output, size_t output_size, char c) +void ShortenString(const char *input, char *output, size_t output_size, char c) { const size_t str_len = strlen(input); size_t half = (output_size - 1) / 2; @@ -226,7 +225,7 @@ void ShortenString(const char *input, size_t spaces = (output_size - 1) - (half * 2); /* Add the first half to the new string */ - snprintf(output, half+1, "%s", input); + snprintf(output, half + 1, "%s", input); /* Add the amount of spaces wanted */ size_t length = half; @@ -772,7 +771,6 @@ static int UtilMiscParseSizeStringTest01(void) void UtilMiscRegisterTests(void) { - UtRegisterTest("UtilMiscParseSizeStringTest01", - UtilMiscParseSizeStringTest01); + UtRegisterTest("UtilMiscParseSizeStringTest01", UtilMiscParseSizeStringTest01); } #endif /* UNITTESTS */ diff --git a/src/util-misc.h b/src/util-misc.h index a3d398d92f0a..e9adc0190391 100644 --- a/src/util-misc.h +++ b/src/util-misc.h @@ -24,7 +24,6 @@ #ifndef __UTIL_MISC_H__ #define __UTIL_MISC_H__ - /** * \brief Generic API that can be used by all to log an * invalid conf entry. @@ -54,7 +53,6 @@ void UtilMiscRegisterTests(void); void ParseSizeInit(void); void ParseSizeDeinit(void); -void ShortenString(const char *input, - char *output, size_t output_size, char c); +void ShortenString(const char *input, char *output, size_t output_size, char c); #endif /* __UTIL_MISC_H__ */ diff --git a/src/util-mpm-ac-ks-small.c b/src/util-mpm-ac-ks-small.c index 44f51d02b9fb..021fffa16ba7 100644 --- a/src/util-mpm-ac-ks-small.c +++ b/src/util-mpm-ac-ks-small.c @@ -32,7 +32,7 @@ /* This function handles (ctx->state_count < 32767) */ uint32_t FUNC_NAME(const SCACTileSearchCtx *ctx, MpmThreadCtx *mpm_thread_ctx, - PrefilterRuleStore *pmq, const uint8_t *buf, uint32_t buflen) + PrefilterRuleStore *pmq, const uint8_t *buf, uint32_t buflen) { uint32_t i = 0; int matches = 0; @@ -40,18 +40,18 @@ uint32_t FUNC_NAME(const SCACTileSearchCtx *ctx, MpmThreadCtx *mpm_thread_ctx, uint8_t mpm_bitarray[ctx->mpm_bitarray_size]; memset(mpm_bitarray, 0, ctx->mpm_bitarray_size); - const uint8_t* restrict xlate = ctx->translate_table; - STYPE *state_table = (STYPE*)ctx->state_table; + const uint8_t *restrict xlate = ctx->translate_table; + STYPE *state_table = (STYPE *)ctx->state_table; STYPE state = 0; int c = xlate[buf[0]]; /* If buflen at least 4 bytes and buf 4-byte aligned. */ if (buflen >= (4 + EXTRA) && ((uintptr_t)buf & 0x3) == 0) { - BUF_TYPE data = *(BUF_TYPE* restrict)(&buf[0]); + BUF_TYPE data = *(BUF_TYPE * restrict)(&buf[0]); uint64_t index = 0; /* Process 4*floor(buflen/4) bytes. */ i = 0; while ((i + EXTRA) < (buflen & ~0x3)) { - BUF_TYPE data1 = *(BUF_TYPE* restrict)(&buf[i + 4]); + BUF_TYPE data1 = *(BUF_TYPE * restrict)(&buf[i + 4]); index = SINDEX(index, state); state = SLOAD(state_table + index + c); c = xlate[BYTE1(data)]; @@ -85,11 +85,11 @@ uint32_t FUNC_NAME(const SCACTileSearchCtx *ctx, MpmThreadCtx *mpm_thread_ctx, } /* Process buflen % 4 bytes. */ for (; i < buflen; i++) { - size_t index = 0 ; + size_t index = 0; index = SINDEX(index, state); state = SLOAD(state_table + index + c); - if (likely(i+1 < buflen)) - c = xlate[buf[i+1]]; + if (likely(i + 1 < buflen)) + c = xlate[buf[i + 1]]; if (unlikely(SCHECK(state))) { matches = CheckMatch(ctx, pmq, buf, buflen, state, i, matches, mpm_bitarray); } diff --git a/src/util-mpm-ac-ks.c b/src/util-mpm-ac-ks.c index 465b66918b62..aadb6879d354 100644 --- a/src/util-mpm-ac-ks.c +++ b/src/util-mpm-ac-ks.c @@ -86,62 +86,46 @@ void SCACTileInitCtx(MpmCtx *); void SCACTileDestroyCtx(MpmCtx *); -int SCACTileAddPatternCI(MpmCtx *, uint8_t *, uint16_t, uint16_t, uint16_t, - uint32_t, SigIntId, uint8_t); -int SCACTileAddPatternCS(MpmCtx *, uint8_t *, uint16_t, uint16_t, uint16_t, - uint32_t, SigIntId, uint8_t); +int SCACTileAddPatternCI( + MpmCtx *, uint8_t *, uint16_t, uint16_t, uint16_t, uint32_t, SigIntId, uint8_t); +int SCACTileAddPatternCS( + MpmCtx *, uint8_t *, uint16_t, uint16_t, uint16_t, uint32_t, SigIntId, uint8_t); int SCACTilePreparePatterns(MpmCtx *mpm_ctx); uint32_t SCACTileSearch(const MpmCtx *mpm_ctx, MpmThreadCtx *mpm_thread_ctx, - PrefilterRuleStore *pmq, const uint8_t *buf, - uint32_t buflen); + PrefilterRuleStore *pmq, const uint8_t *buf, uint32_t buflen); void SCACTilePrintInfo(MpmCtx *mpm_ctx); void SCACTileRegisterTests(void); uint32_t SCACTileSearchLarge(const SCACTileSearchCtx *ctx, MpmThreadCtx *mpm_thread_ctx, - PrefilterRuleStore *pmq, - const uint8_t *buf, uint32_t buflen); + PrefilterRuleStore *pmq, const uint8_t *buf, uint32_t buflen); uint32_t SCACTileSearchSmall256(const SCACTileSearchCtx *ctx, MpmThreadCtx *mpm_thread_ctx, - PrefilterRuleStore *pmq, - const uint8_t *buf, uint32_t buflen); + PrefilterRuleStore *pmq, const uint8_t *buf, uint32_t buflen); uint32_t SCACTileSearchSmall128(const SCACTileSearchCtx *ctx, MpmThreadCtx *mpm_thread_ctx, - PrefilterRuleStore *pmq, - const uint8_t *buf, uint32_t buflen); + PrefilterRuleStore *pmq, const uint8_t *buf, uint32_t buflen); uint32_t SCACTileSearchSmall64(const SCACTileSearchCtx *ctx, MpmThreadCtx *mpm_thread_ctx, - PrefilterRuleStore *pmq, - const uint8_t *buf, uint32_t buflen); + PrefilterRuleStore *pmq, const uint8_t *buf, uint32_t buflen); uint32_t SCACTileSearchSmall32(const SCACTileSearchCtx *ctx, MpmThreadCtx *mpm_thread_ctx, - PrefilterRuleStore *pmq, - const uint8_t *buf, uint32_t buflen); + PrefilterRuleStore *pmq, const uint8_t *buf, uint32_t buflen); uint32_t SCACTileSearchSmall16(const SCACTileSearchCtx *ctx, MpmThreadCtx *mpm_thread_ctx, - PrefilterRuleStore *pmq, - const uint8_t *buf, uint32_t buflen); + PrefilterRuleStore *pmq, const uint8_t *buf, uint32_t buflen); uint32_t SCACTileSearchSmall8(const SCACTileSearchCtx *ctx, MpmThreadCtx *mpm_thread_ctx, - PrefilterRuleStore *pmq, - const uint8_t *buf, uint32_t buflen); + PrefilterRuleStore *pmq, const uint8_t *buf, uint32_t buflen); uint32_t SCACTileSearchTiny256(const SCACTileSearchCtx *ctx, MpmThreadCtx *mpm_thread_ctx, - PrefilterRuleStore *pmq, - const uint8_t *buf, uint32_t buflen); + PrefilterRuleStore *pmq, const uint8_t *buf, uint32_t buflen); uint32_t SCACTileSearchTiny128(const SCACTileSearchCtx *ctx, MpmThreadCtx *mpm_thread_ctx, - PrefilterRuleStore *pmq, - const uint8_t *buf, uint32_t buflen); + PrefilterRuleStore *pmq, const uint8_t *buf, uint32_t buflen); uint32_t SCACTileSearchTiny64(const SCACTileSearchCtx *ctx, MpmThreadCtx *mpm_thread_ctx, - PrefilterRuleStore *pmq, - const uint8_t *buf, uint32_t buflen); + PrefilterRuleStore *pmq, const uint8_t *buf, uint32_t buflen); uint32_t SCACTileSearchTiny32(const SCACTileSearchCtx *ctx, MpmThreadCtx *mpm_thread_ctx, - PrefilterRuleStore *pmq, - const uint8_t *buf, uint32_t buflen); + PrefilterRuleStore *pmq, const uint8_t *buf, uint32_t buflen); uint32_t SCACTileSearchTiny16(const SCACTileSearchCtx *ctx, MpmThreadCtx *mpm_thread_ctx, - PrefilterRuleStore *pmq, - const uint8_t *buf, uint32_t buflen); + PrefilterRuleStore *pmq, const uint8_t *buf, uint32_t buflen); uint32_t SCACTileSearchTiny8(const SCACTileSearchCtx *ctx, MpmThreadCtx *mpm_thread_ctx, - PrefilterRuleStore *pmq, - const uint8_t *buf, uint32_t buflen); - + PrefilterRuleStore *pmq, const uint8_t *buf, uint32_t buflen); static void SCACTileDestroyInitCtx(MpmCtx *mpm_ctx); - /* a placeholder to denote a failure transition in the goto table */ #define SC_AC_TILE_FAIL (-1) @@ -172,8 +156,7 @@ static void SCACTileGetConfig(void) * accumulate into a histogram. Really only used to detect unused * characters, so could just set to 1 instead of counting. */ -static inline void SCACTileHistogramAlphabet(SCACTileCtx *ctx, - MpmPattern *p) +static inline void SCACTileHistogramAlphabet(SCACTileCtx *ctx, MpmPattern *p) { for (int i = 0; i < p->len; i++) { ctx->alpha_hist[p->ci[i]]++; @@ -211,11 +194,11 @@ static void SCACTileInitTranslateTable(SCACTileCtx *ctx) * space For the unused-characters = 0 mapping. */ ctx->alphabet_size += 1; /* Extra space for unused-character */ - if (ctx->alphabet_size <= 8) { + if (ctx->alphabet_size <= 8) { ctx->alphabet_storage = 8; - } else if (ctx->alphabet_size <= 16) { + } else if (ctx->alphabet_size <= 16) { ctx->alphabet_storage = 16; - } else if (ctx->alphabet_size <= 32) { + } else if (ctx->alphabet_size <= 32) { ctx->alphabet_storage = 32; } else if (ctx->alphabet_size <= 64) { ctx->alphabet_storage = 64; @@ -283,8 +266,7 @@ static inline int SCACTileInitNewState(MpmCtx *mpm_ctx) ctx->goto_table[ctx->state_count][aa] = SC_AC_TILE_FAIL; } - memset(ctx->output_table + ctx->state_count, 0, - sizeof(SCACTileOutputTable)); + memset(ctx->output_table + ctx->state_count, 0, sizeof(SCACTileOutputTable)); return ctx->state_count++; } @@ -315,8 +297,7 @@ static void SCACTileSetOutputState(int32_t state, MpmPatternIndex pindex, MpmCtx /* Increase the size of the array of pids for this state and add * the new pid. */ output_state->no_of_entries++; - ptmp = SCRealloc(output_state->patterns, - output_state->no_of_entries * sizeof(MpmPatternIndex)); + ptmp = SCRealloc(output_state->patterns, output_state->no_of_entries * sizeof(MpmPatternIndex)); if (ptmp == NULL) { SCFree(output_state->patterns); output_state->patterns = NULL; @@ -337,8 +318,8 @@ static void SCACTileSetOutputState(int32_t state, MpmPatternIndex pindex, MpmCtx * need it to updated the output table for this pattern. * \param mpm_ctx Pointer to the mpm context. */ -static void SCACTileEnter(uint8_t *pattern, uint16_t pattern_len, - MpmPatternIndex pindex, MpmCtx *mpm_ctx) +static void SCACTileEnter( + uint8_t *pattern, uint16_t pattern_len, MpmPatternIndex pindex, MpmCtx *mpm_ctx) { SCACTileSearchCtx *search_ctx = (SCACTileSearchCtx *)mpm_ctx->ctx; SCACTileCtx *ctx = search_ctx->init_ctx; @@ -387,8 +368,7 @@ static void SCACTileCreateGotoTable(MpmCtx *mpm_ctx) /* add each pattern to create the goto table */ for (i = 0; i < mpm_ctx->pattern_cnt; i++) { - SCACTileEnter(ctx->parray[i]->ci, ctx->parray[i]->len, - i, mpm_ctx); + SCACTileEnter(ctx->parray[i]->ci, ctx->parray[i]->len, i, mpm_ctx); } int aa = 0; @@ -450,9 +430,7 @@ static inline int32_t SCACTileDequeue(StateQueue *q) * \param src_state Second state for the union operation. * \param mpm_ctx Pointer to the mpm context. */ -static void SCACTileClubOutputStates(int32_t dst_state, - int32_t src_state, - MpmCtx *mpm_ctx) +static void SCACTileClubOutputStates(int32_t dst_state, int32_t src_state, MpmCtx *mpm_ctx) { void *ptmp; SCACTileSearchCtx *search_ctx = (SCACTileSearchCtx *)mpm_ctx->ctx; @@ -474,7 +452,7 @@ static void SCACTileClubOutputStates(int32_t dst_state, output_dst_state->no_of_entries++; ptmp = SCRealloc(output_dst_state->patterns, - (output_dst_state->no_of_entries * sizeof(uint32_t))); + (output_dst_state->no_of_entries * sizeof(uint32_t))); if (ptmp == NULL) { SCFree(output_dst_state->patterns); output_dst_state->patterns = NULL; @@ -483,7 +461,7 @@ static void SCACTileClubOutputStates(int32_t dst_state, output_dst_state->patterns = ptmp; output_dst_state->patterns[output_dst_state->no_of_entries - 1] = - output_src_state->patterns[i]; + output_src_state->patterns[i]; } } } @@ -534,11 +512,10 @@ static void SCACTileCreateFailureTable(MpmCtx *mpm_ctx) SCACTileEnqueue(&q, temp_state); state = ctx->failure_table[r_state]; - while(ctx->goto_table[state][aa] == SC_AC_TILE_FAIL) + while (ctx->goto_table[state][aa] == SC_AC_TILE_FAIL) state = ctx->failure_table[state]; ctx->failure_table[temp_state] = ctx->goto_table[state][aa]; - SCACTileClubOutputStates(temp_state, ctx->failure_table[temp_state], - mpm_ctx); + SCACTileClubOutputStates(temp_state, ctx->failure_table[temp_state], mpm_ctx); } } } @@ -546,10 +523,9 @@ static void SCACTileCreateFailureTable(MpmCtx *mpm_ctx) /* * Set the next state for 1 byte next-state. */ -static void SCACTileSetState1Byte(SCACTileCtx *ctx, int state, int aa, - int next_state, int outputs) +static void SCACTileSetState1Byte(SCACTileCtx *ctx, int state, int aa, int next_state, int outputs) { - uint8_t *state_table = (uint8_t*)ctx->state_table; + uint8_t *state_table = (uint8_t *)ctx->state_table; DEBUG_VALIDATE_BUG_ON(next_state < 0 || next_state > UINT8_MAX); uint8_t encoded_next_state = (uint8_t)next_state; @@ -566,10 +542,9 @@ static void SCACTileSetState1Byte(SCACTileCtx *ctx, int state, int aa, /* * Set the next state for 2 byte next-state. */ -static void SCACTileSetState2Bytes(SCACTileCtx *ctx, int state, int aa, - int next_state, int outputs) +static void SCACTileSetState2Bytes(SCACTileCtx *ctx, int state, int aa, int next_state, int outputs) { - uint16_t *state_table = (uint16_t*)ctx->state_table; + uint16_t *state_table = (uint16_t *)ctx->state_table; DEBUG_VALIDATE_BUG_ON(next_state < 0 || next_state > UINT16_MAX); uint16_t encoded_next_state = (uint16_t)next_state; @@ -586,10 +561,9 @@ static void SCACTileSetState2Bytes(SCACTileCtx *ctx, int state, int aa, /* * Set the next state for 4 byte next-state. */ -static void SCACTileSetState4Bytes(SCACTileCtx *ctx, int state, int aa, - int next_state, int outputs) +static void SCACTileSetState4Bytes(SCACTileCtx *ctx, int state, int aa, int next_state, int outputs) { - uint32_t *state_table = (uint32_t*)ctx->state_table; + uint32_t *state_table = (uint32_t *)ctx->state_table; uint32_t encoded_next_state = next_state; if (next_state == SC_AC_TILE_FAIL) { @@ -621,48 +595,48 @@ static inline void SCACTileCreateDeltaTable(MpmCtx *mpm_ctx) ctx->bytes_per_state = 1; ctx->SetNextState = SCACTileSetState1Byte; - switch(ctx->alphabet_storage) { - case 8: - ctx->Search = SCACTileSearchTiny8; - break; - case 16: - ctx->Search = SCACTileSearchTiny16; - break; - case 32: - ctx->Search = SCACTileSearchTiny32; - break; - case 64: - ctx->Search = SCACTileSearchTiny64; - break; - case 128: - ctx->Search = SCACTileSearchTiny128; - break; - default: - ctx->Search = SCACTileSearchTiny256; + switch (ctx->alphabet_storage) { + case 8: + ctx->Search = SCACTileSearchTiny8; + break; + case 16: + ctx->Search = SCACTileSearchTiny16; + break; + case 32: + ctx->Search = SCACTileSearchTiny32; + break; + case 64: + ctx->Search = SCACTileSearchTiny64; + break; + case 128: + ctx->Search = SCACTileSearchTiny128; + break; + default: + ctx->Search = SCACTileSearchTiny256; } } else { /* 16-bit state needed */ ctx->bytes_per_state = 2; ctx->SetNextState = SCACTileSetState2Bytes; - switch(ctx->alphabet_storage) { - case 8: - ctx->Search = SCACTileSearchSmall8; - break; - case 16: - ctx->Search = SCACTileSearchSmall16; - break; - case 32: - ctx->Search = SCACTileSearchSmall32; - break; - case 64: - ctx->Search = SCACTileSearchSmall64; - break; - case 128: - ctx->Search = SCACTileSearchSmall128; - break; - default: - ctx->Search = SCACTileSearchSmall256; + switch (ctx->alphabet_storage) { + case 8: + ctx->Search = SCACTileSearchSmall8; + break; + case 16: + ctx->Search = SCACTileSearchSmall16; + break; + case 32: + ctx->Search = SCACTileSearchSmall32; + break; + case 64: + ctx->Search = SCACTileSearchSmall64; + break; + case 128: + ctx->Search = SCACTileSearchSmall128; + break; + default: + ctx->Search = SCACTileSearchSmall256; } } } else { @@ -717,8 +691,8 @@ static void SCACTileClubOutputStatePresenceWithDeltaTable(MpmCtx *mpm_ctx) mpm_ctx->memory_cnt++; mpm_ctx->memory_size += size; - SCLogDebug("Delta Table size %d, alphabet: %d, %d-byte states: %d", - size, ctx->alphabet_size, ctx->bytes_per_state, ctx->state_count); + SCLogDebug("Delta Table size %d, alphabet: %d, %d-byte states: %d", size, ctx->alphabet_size, + ctx->bytes_per_state, ctx->state_count); /* Copy next state from Goto table, which is 32 bits and encode it into the next * state table, which can be 1, 2 or 4 bytes each and include if there is an @@ -747,7 +721,7 @@ static inline void SCACTileInsertCaseSensitiveEntriesForPatterns(MpmCtx *mpm_ctx for (k = 0; k < ctx->output_table[state].no_of_entries; k++) { if (ctx->pattern_list[ctx->output_table[state].patterns[k]].cs != NULL) { - /* TODO - Find better way to store this. */ + /* TODO - Find better way to store this. */ ctx->output_table[state].patterns[k] &= 0x0FFFFFFF; ctx->output_table[state].patterns[k] |= (uint32_t)1 << 31; } @@ -814,7 +788,6 @@ static void SCACTilePrepareStateTable(MpmCtx *mpm_ctx) ctx->failure_table = NULL; } - /** * \brief Process Internal AC MPM tables to create the Search Context * @@ -882,7 +855,7 @@ int SCACTilePreparePatterns(MpmCtx *mpm_ctx) uint32_t i = 0, p = 0; for (i = 0; i < MPM_INIT_HASH_SIZE; i++) { MpmPattern *node = mpm_ctx->init_hash[i], *nnode = NULL; - while(node != NULL) { + while (node != NULL) { nnode = node->next; node->next = NULL; ctx->parray[p++] = node; @@ -1024,8 +997,7 @@ static void SCACTileDestroyInitCtx(MpmCtx *mpm_ctx) SCFree(ctx->state_table); mpm_ctx->memory_cnt--; - mpm_ctx->memory_size -= (ctx->state_count * - ctx->bytes_per_state * ctx->alphabet_storage); + mpm_ctx->memory_size -= (ctx->state_count * ctx->bytes_per_state * ctx->alphabet_storage); } if (ctx->output_table != NULL) { @@ -1103,18 +1075,16 @@ void SCACTileDestroyCtx(MpmCtx *mpm_ctx) */ #define SCHECK(x) ((x) > 0) -#define BUF_TYPE int32_t +#define BUF_TYPE int32_t // Extract byte N=0,1,2,3 from x -#define BYTE0(x) (((x) & 0x000000ff) >> 0) -#define BYTE1(x) (((x) & 0x0000ff00) >> 8) -#define BYTE2(x) (((x) & 0x00ff0000) >> 16) -#define BYTE3(x) (((x) & 0xff000000) >> 24) -#define EXTRA 4 // need 4 extra bytes to avoid OOB reads +#define BYTE0(x) (((x)&0x000000ff) >> 0) +#define BYTE1(x) (((x)&0x0000ff00) >> 8) +#define BYTE2(x) (((x)&0x00ff0000) >> 16) +#define BYTE3(x) (((x)&0xff000000) >> 24) +#define EXTRA 4 // need 4 extra bytes to avoid OOB reads -static int CheckMatch(const SCACTileSearchCtx *ctx, PrefilterRuleStore *pmq, - const uint8_t *buf, uint32_t buflen, - uint16_t state, int i, int matches, - uint8_t *mpm_bitarray) +static int CheckMatch(const SCACTileSearchCtx *ctx, PrefilterRuleStore *pmq, const uint8_t *buf, + uint32_t buflen, uint16_t state, int i, int matches, uint8_t *mpm_bitarray) { const SCACTilePatternList *pattern_list = ctx->pattern_list; const uint8_t *buf_offset = buf + i + 1; // Lift out of loop @@ -1147,8 +1117,7 @@ static int CheckMatch(const SCACTileSearchCtx *ctx, PrefilterRuleStore *pmq, /* Always add the Signature IDs, since they could be different in the current MPM * than in a previous MPM on the same PMQ when finding the same pattern. */ - PrefilterAddSids(pmq, pattern_list[pindex].sids, - pattern_list[pindex].sids_size); + PrefilterAddSids(pmq, pattern_list[pindex].sids, pattern_list[pindex].sids_size); matches++; } @@ -1168,7 +1137,7 @@ static int CheckMatch(const SCACTileSearchCtx *ctx, PrefilterRuleStore *pmq, * \retval matches Match count. */ uint32_t SCACTileSearch(const MpmCtx *mpm_ctx, MpmThreadCtx *mpm_thread_ctx, - PrefilterRuleStore *pmq, const uint8_t *buf, uint32_t buflen) + PrefilterRuleStore *pmq, const uint8_t *buf, uint32_t buflen) { const SCACTileSearchCtx *search_ctx = (SCACTileSearchCtx *)mpm_ctx->ctx; @@ -1181,8 +1150,7 @@ uint32_t SCACTileSearch(const MpmCtx *mpm_ctx, MpmThreadCtx *mpm_thread_ctx, /* This function handles (ctx->state_count >= 32767) */ uint32_t SCACTileSearchLarge(const SCACTileSearchCtx *ctx, MpmThreadCtx *mpm_thread_ctx, - PrefilterRuleStore *pmq, - const uint8_t *buf, uint32_t buflen) + PrefilterRuleStore *pmq, const uint8_t *buf, uint32_t buflen) { uint32_t i = 0; int matches = 0; @@ -1190,9 +1158,9 @@ uint32_t SCACTileSearchLarge(const SCACTileSearchCtx *ctx, MpmThreadCtx *mpm_thr uint8_t mpm_bitarray[ctx->mpm_bitarray_size]; memset(mpm_bitarray, 0, ctx->mpm_bitarray_size); - const uint8_t* restrict xlate = ctx->translate_table; + const uint8_t *restrict xlate = ctx->translate_table; register int state = 0; - int32_t (*state_table_u32)[256] = ctx->state_table; + int32_t(*state_table_u32)[256] = ctx->state_table; for (i = 0; i < buflen; i++) { state = state_table_u32[state & 0x00FFFFFF][xlate[buf[i]]]; if (SCHECK(state)) { @@ -1209,16 +1177,15 @@ uint32_t SCACTileSearchLarge(const SCACTileSearchCtx *ctx, MpmThreadCtx *mpm_thr * Next state entry has MSB as "match" and 15 LSB bits as next-state index. */ // y = 1<flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " - "(content:\"onetwothreefourfivesixseveneightnine\"; sid:1;)"); + de_ctx->sig_list = + SigInit(de_ctx, "alert tcp any any -> any any " + "(content:\"onetwothreefourfivesixseveneightnine\"; sid:1;)"); if (de_ctx->sig_list == NULL) goto end; - de_ctx->sig_list->next = SigInit(de_ctx, "alert tcp any any -> any any " - "(content:\"onetwothreefourfivesixseveneightnine\"; fast_pattern:3,3; sid:2;)"); + de_ctx->sig_list->next = SigInit(de_ctx, + "alert tcp any any -> any any " + "(content:\"onetwothreefourfivesixseveneightnine\"; fast_pattern:3,3; sid:2;)"); if (de_ctx->sig_list->next == NULL) goto end; diff --git a/src/util-mpm-ac-ks.h b/src/util-mpm-ac-ks.h index 4979f84241a4..e4f9ac7a6f3b 100644 --- a/src/util-mpm-ac-ks.h +++ b/src/util-mpm-ac-ks.h @@ -67,13 +67,12 @@ typedef struct SCACTileCtx_ { * 32 bits. */ uint32_t (*Search)(const struct SCACTileSearchCtx_ *ctx, struct MpmThreadCtx_ *, - PrefilterRuleStore *, const uint8_t *, uint32_t); + PrefilterRuleStore *, const uint8_t *, uint32_t); /* Function to set the next state based on size of next state * (bytes_per_state). */ - void (*SetNextState)(struct SCACTileCtx_ *ctx, int state, int aa, - int new_state, int outputs); + void (*SetNextState)(struct SCACTileCtx_ *ctx, int state, int aa, int new_state, int outputs); /* List of patterns that match for this state. Indexed by State Number */ SCACTileOutputTable *output_table; @@ -108,7 +107,6 @@ typedef struct SCACTileCtx_ { } SCACTileCtx; - /* Only the stuff used at search time. This * structure is created after all the patterns are added. */ @@ -120,7 +118,7 @@ typedef struct SCACTileSearchCtx_ { * 32 bits. */ uint32_t (*Search)(const struct SCACTileSearchCtx_ *ctx, struct MpmThreadCtx_ *, - PrefilterRuleStore *, const uint8_t *, uint32_t); + PrefilterRuleStore *, const uint8_t *, uint32_t); /* Convert input character to matching alphabet */ uint8_t translate_table[256]; diff --git a/src/util-mpm-ac.c b/src/util-mpm-ac.c index 6d0fc050b99a..f8684f769d24 100644 --- a/src/util-mpm-ac.c +++ b/src/util-mpm-ac.c @@ -64,13 +64,13 @@ void SCACInitCtx(MpmCtx *); void SCACDestroyCtx(MpmCtx *); -int SCACAddPatternCI(MpmCtx *, uint8_t *, uint16_t, uint16_t, uint16_t, - uint32_t, SigIntId, uint8_t); -int SCACAddPatternCS(MpmCtx *, uint8_t *, uint16_t, uint16_t, uint16_t, - uint32_t, SigIntId, uint8_t); +int SCACAddPatternCI( + MpmCtx *, uint8_t *, uint16_t, uint16_t, uint16_t, uint32_t, SigIntId, uint8_t); +int SCACAddPatternCS( + MpmCtx *, uint8_t *, uint16_t, uint16_t, uint16_t, uint32_t, SigIntId, uint8_t); int SCACPreparePatterns(MpmCtx *mpm_ctx); -uint32_t SCACSearch(const MpmCtx *mpm_ctx, MpmThreadCtx *mpm_thread_ctx, - PrefilterRuleStore *pmq, const uint8_t *buf, uint32_t buflen); +uint32_t SCACSearch(const MpmCtx *mpm_ctx, MpmThreadCtx *mpm_thread_ctx, PrefilterRuleStore *pmq, + const uint8_t *buf, uint32_t buflen); void SCACPrintInfo(MpmCtx *mpm_ctx); void SCACRegisterTests(void); @@ -79,9 +79,9 @@ void SCACRegisterTests(void); #define STATE_QUEUE_CONTAINER_SIZE 65536 -#define AC_CASE_MASK 0x80000000 -#define AC_PID_MASK 0x7FFFFFFF -#define AC_CASE_BIT 31 +#define AC_CASE_MASK 0x80000000 +#define AC_PID_MASK 0x7FFFFFFF +#define AC_CASE_BIT 31 static int construct_both_16_and_32_state_tables = 0; @@ -102,10 +102,10 @@ typedef struct StateQueue_ { */ static void SCACGetConfig(void) { - //ConfNode *ac_conf; - //const char *hash_val = NULL; + // ConfNode *ac_conf; + // const char *hash_val = NULL; - //ConfNode *pm = ConfGetNode("pattern-matcher"); + // ConfNode *pm = ConfGetNode("pattern-matcher"); return; } @@ -146,7 +146,7 @@ static inline int SCACReallocState(SCACCtx *ctx, uint32_t cnt) size_t size = 0; /* reallocate space in the goto table to include a new state */ - size = SCACCheckSafeSizetMult((size_t) cnt, (size_t) ctx->single_state_size); + size = SCACCheckSafeSizetMult((size_t)cnt, (size_t)ctx->single_state_size); if (size > 0) ptmp = SCRealloc(ctx->goto_table, size); if (ptmp == NULL) { @@ -157,11 +157,10 @@ static inline int SCACReallocState(SCACCtx *ctx, uint32_t cnt) ctx->goto_table = ptmp; /* reallocate space in the output table for the new state */ - size_t oldsize = SCACCheckSafeSizetMult((size_t) ctx->state_count, - sizeof(SCACOutputTable)); - size = SCACCheckSafeSizetMult((size_t) cnt, sizeof(SCACOutputTable)); - SCLogDebug("oldsize %"PRIuMAX" size %"PRIuMAX" cnt %d ctx->state_count %u", - (uintmax_t) oldsize, (uintmax_t) size, cnt, ctx->state_count); + size_t oldsize = SCACCheckSafeSizetMult((size_t)ctx->state_count, sizeof(SCACOutputTable)); + size = SCACCheckSafeSizetMult((size_t)cnt, sizeof(SCACOutputTable)); + SCLogDebug("oldsize %" PRIuMAX " size %" PRIuMAX " cnt %d ctx->state_count %u", + (uintmax_t)oldsize, (uintmax_t)size, cnt, ctx->state_count); ptmp = NULL; if (size > 0) @@ -177,12 +176,12 @@ static inline int SCACReallocState(SCACCtx *ctx, uint32_t cnt) /* \todo using it temporarily now during dev, since I have restricted * state var in SCACCtx->state_table to uint16_t. */ - //if (ctx->state_count > 65536) { + // if (ctx->state_count > 65536) { // printf("state count exceeded\n"); // exit(EXIT_FAILURE); //} - return 0;//ctx->state_count++; + return 0; // ctx->state_count++; } /** \internal @@ -199,9 +198,8 @@ static void SCACShrinkState(SCACCtx *ctx) int newsize = ctx->state_count * sizeof(SCACOutputTable); SCLogDebug("oldsize %d newsize %d ctx->allocated_state_count %u " - "ctx->state_count %u: shrink by %d bytes", oldsize, - newsize, ctx->allocated_state_count, ctx->state_count, - oldsize - newsize); + "ctx->state_count %u: shrink by %d bytes", + oldsize, newsize, ctx->allocated_state_count, ctx->state_count, oldsize - newsize); void *ptmp = SCRealloc(ctx->output_table, newsize); if (ptmp == NULL) { @@ -224,7 +222,6 @@ static inline int SCACInitNewState(MpmCtx *mpm_ctx) ctx->allocated_state_count *= 2; SCACReallocState(ctx, ctx->allocated_state_count); - } #if 0 if (ctx->allocated_state_count > 260) { @@ -262,8 +259,7 @@ static void SCACSetOutputState(int32_t state, uint32_t pid, MpmCtx *mpm_ctx) } output_state->no_of_entries++; - ptmp = SCRealloc(output_state->pids, - output_state->no_of_entries * sizeof(uint32_t)); + ptmp = SCRealloc(output_state->pids, output_state->no_of_entries * sizeof(uint32_t)); if (ptmp == NULL) { SCFree(output_state->pids); output_state->pids = NULL; @@ -286,8 +282,7 @@ static void SCACSetOutputState(int32_t state, uint32_t pid, MpmCtx *mpm_ctx) * need it to updated the output table for this pattern. * \param mpm_ctx Pointer to the mpm context. */ -static inline void SCACEnter(uint8_t *pattern, uint16_t pattern_len, uint32_t pid, - MpmCtx *mpm_ctx) +static inline void SCACEnter(uint8_t *pattern, uint16_t pattern_len, uint32_t pid, MpmCtx *mpm_ctx) { SCACCtx *ctx = (SCACCtx *)mpm_ctx->ctx; int32_t state = 0; @@ -333,8 +328,7 @@ static inline void SCACCreateGotoTable(MpmCtx *mpm_ctx) /* add each pattern to create the goto table */ for (i = 0; i < mpm_ctx->pattern_cnt; i++) { - SCACEnter(ctx->parray[i]->ci, ctx->parray[i]->len, - ctx->parray[i]->id, mpm_ctx); + SCACEnter(ctx->parray[i]->ci, ctx->parray[i]->len, ctx->parray[i]->id, mpm_ctx); } int ascii_code = 0; @@ -419,8 +413,7 @@ static inline int32_t SCACDequeue(StateQueue *q) * \param src_state Second state for the union operation. * \param mpm_ctx Pointer to the mpm context. */ -static inline void SCACClubOutputStates(int32_t dst_state, int32_t src_state, - MpmCtx *mpm_ctx) +static inline void SCACClubOutputStates(int32_t dst_state, int32_t src_state, MpmCtx *mpm_ctx) { void *ptmp; SCACCtx *ctx = (SCACCtx *)mpm_ctx->ctx; @@ -439,8 +432,8 @@ static inline void SCACClubOutputStates(int32_t dst_state, int32_t src_state, if (j == output_dst_state->no_of_entries) { output_dst_state->no_of_entries++; - ptmp = SCRealloc(output_dst_state->pids, - (output_dst_state->no_of_entries * sizeof(uint32_t))); + ptmp = SCRealloc( + output_dst_state->pids, (output_dst_state->no_of_entries * sizeof(uint32_t))); if (ptmp == NULL) { SCFree(output_dst_state->pids); output_dst_state->pids = NULL; @@ -448,8 +441,7 @@ static inline void SCACClubOutputStates(int32_t dst_state, int32_t src_state, } output_dst_state->pids = ptmp; - output_dst_state->pids[output_dst_state->no_of_entries - 1] = - output_src_state->pids[i]; + output_dst_state->pids[output_dst_state->no_of_entries - 1] = output_src_state->pids[i]; } } @@ -502,11 +494,10 @@ static inline void SCACCreateFailureTable(MpmCtx *mpm_ctx) SCACEnqueue(q, temp_state); state = ctx->failure_table[r_state]; - while(ctx->goto_table[state][ascii_code] == SC_AC_FAIL) + while (ctx->goto_table[state][ascii_code] == SC_AC_FAIL) state = ctx->failure_table[state]; ctx->failure_table[temp_state] = ctx->goto_table[state][ascii_code]; - SCACClubOutputStates(temp_state, ctx->failure_table[temp_state], - mpm_ctx); + SCACClubOutputStates(temp_state, ctx->failure_table[temp_state], mpm_ctx); } } SCFree(q); @@ -558,7 +549,7 @@ static inline void SCACCreateDeltaTable(MpmCtx *mpm_ctx) ctx->state_table_u16[r_state][ascii_code] = (uint16_t)temp_state; } else { ctx->state_table_u16[r_state][ascii_code] = - ctx->state_table_u16[ctx->failure_table[r_state]][ascii_code]; + ctx->state_table_u16[ctx->failure_table[r_state]][ascii_code]; } } } @@ -598,7 +589,7 @@ static inline void SCACCreateDeltaTable(MpmCtx *mpm_ctx) ctx->state_table_u32[r_state][ascii_code] = temp_state; } else { ctx->state_table_u32[r_state][ascii_code] = - ctx->state_table_u32[ctx->failure_table[r_state]][ascii_code]; + ctx->state_table_u32[ctx->failure_table[r_state]][ascii_code]; } } } @@ -746,7 +737,7 @@ int SCACPreparePatterns(MpmCtx *mpm_ctx) uint32_t i = 0, p = 0; for (i = 0; i < MPM_INIT_HASH_SIZE; i++) { MpmPattern *node = mpm_ctx->init_hash[i], *nnode = NULL; - while(node != NULL) { + while (node != NULL) { nnode = node->next; node->next = NULL; ctx->parray[p++] = node; @@ -773,15 +764,15 @@ int SCACPreparePatterns(MpmCtx *mpm_ctx) if (ctx->pid_pat_list[ctx->parray[i]->id].cs == NULL) { FatalError("Error allocating memory"); } - memcpy(ctx->pid_pat_list[ctx->parray[i]->id].cs, - ctx->parray[i]->original_pat, ctx->parray[i]->len); + memcpy(ctx->pid_pat_list[ctx->parray[i]->id].cs, ctx->parray[i]->original_pat, + ctx->parray[i]->len); ctx->pid_pat_list[ctx->parray[i]->id].patlen = ctx->parray[i]->len; } ctx->pid_pat_list[ctx->parray[i]->id].offset = ctx->parray[i]->offset; ctx->pid_pat_list[ctx->parray[i]->id].depth = ctx->parray[i]->depth; /* ACPatternList now owns this memory */ - //SCLogInfo("ctx->parray[i]->sids_size %u", ctx->parray[i]->sids_size); + // SCLogInfo("ctx->parray[i]->sids_size %u", ctx->parray[i]->sids_size); ctx->pid_pat_list[ctx->parray[i]->id].sids_size = ctx->parray[i]->sids_size; ctx->pid_pat_list[ctx->parray[i]->id].sids = ctx->parray[i]->sids; @@ -880,16 +871,14 @@ void SCACDestroyCtx(MpmCtx *mpm_ctx) ctx->state_table_u16 = NULL; mpm_ctx->memory_cnt++; - mpm_ctx->memory_size -= (ctx->state_count * - sizeof(SC_AC_STATE_TYPE_U16) * 256); + mpm_ctx->memory_size -= (ctx->state_count * sizeof(SC_AC_STATE_TYPE_U16) * 256); } if (ctx->state_table_u32 != NULL) { SCFree(ctx->state_table_u32); ctx->state_table_u32 = NULL; mpm_ctx->memory_cnt++; - mpm_ctx->memory_size -= (ctx->state_count * - sizeof(SC_AC_STATE_TYPE_U32) * 256); + mpm_ctx->memory_size -= (ctx->state_count * sizeof(SC_AC_STATE_TYPE_U32) * 256); } if (ctx->output_table != NULL) { @@ -932,8 +921,8 @@ void SCACDestroyCtx(MpmCtx *mpm_ctx) * * \retval matches Match count: counts unique matches per pattern. */ -uint32_t SCACSearch(const MpmCtx *mpm_ctx, MpmThreadCtx *mpm_thread_ctx, - PrefilterRuleStore *pmq, const uint8_t *buf, uint32_t buflen) +uint32_t SCACSearch(const MpmCtx *mpm_ctx, MpmThreadCtx *mpm_thread_ctx, PrefilterRuleStore *pmq, + const uint8_t *buf, uint32_t buflen) { const SCACCtx *ctx = (SCACCtx *)mpm_ctx->ctx; uint32_t i = 0; @@ -949,7 +938,7 @@ uint32_t SCACSearch(const MpmCtx *mpm_ctx, MpmThreadCtx *mpm_thread_ctx, if (ctx->state_count < 32767) { register SC_AC_STATE_TYPE_U16 state = 0; - SC_AC_STATE_TYPE_U16 (*state_table_u16)[256] = ctx->state_table_u16; + SC_AC_STATE_TYPE_U16(*state_table_u16)[256] = ctx->state_table_u16; for (i = 0; i < buflen; i++) { state = state_table_u16[state & 0x7FFF][u8_tolower(buf[i])]; if (state & 0x8000) { @@ -965,8 +954,7 @@ uint32_t SCACSearch(const MpmCtx *mpm_ctx, MpmThreadCtx *mpm_thread_ctx, if (offset < (int)pat->offset || (pat->depth && i > pat->depth)) continue; - if (SCMemcmp(pat->cs, buf + offset, pat->patlen) != 0) - { + if (SCMemcmp(pat->cs, buf + offset, pat->patlen) != 0) { /* inside loop */ continue; } @@ -992,7 +980,7 @@ uint32_t SCACSearch(const MpmCtx *mpm_ctx, MpmThreadCtx *mpm_thread_ctx, matches++; } } - //loop1: + // loop1: //; } } @@ -1000,7 +988,7 @@ uint32_t SCACSearch(const MpmCtx *mpm_ctx, MpmThreadCtx *mpm_thread_ctx, } else { register SC_AC_STATE_TYPE_U32 state = 0; - SC_AC_STATE_TYPE_U32 (*state_table_u32)[256] = ctx->state_table_u32; + SC_AC_STATE_TYPE_U32(*state_table_u32)[256] = ctx->state_table_u32; for (i = 0; i < buflen; i++) { state = state_table_u32[state & 0x00FFFFFF][u8_tolower(buf[i])]; if (state & 0xFF000000) { @@ -1016,8 +1004,7 @@ uint32_t SCACSearch(const MpmCtx *mpm_ctx, MpmThreadCtx *mpm_thread_ctx, if (offset < (int)pat->offset || (pat->depth && i > pat->depth)) continue; - if (SCMemcmp(pat->cs, buf + offset, - pat->patlen) != 0) { + if (SCMemcmp(pat->cs, buf + offset, pat->patlen) != 0) { /* inside loop */ continue; } @@ -1043,7 +1030,7 @@ uint32_t SCACSearch(const MpmCtx *mpm_ctx, MpmThreadCtx *mpm_thread_ctx, matches++; } } - //loop1: + // loop1: //; } } @@ -1070,9 +1057,8 @@ uint32_t SCACSearch(const MpmCtx *mpm_ctx, MpmThreadCtx *mpm_thread_ctx, * \retval 0 On success. * \retval -1 On failure. */ -int SCACAddPatternCI(MpmCtx *mpm_ctx, uint8_t *pat, uint16_t patlen, - uint16_t offset, uint16_t depth, uint32_t pid, - SigIntId sid, uint8_t flags) +int SCACAddPatternCI(MpmCtx *mpm_ctx, uint8_t *pat, uint16_t patlen, uint16_t offset, + uint16_t depth, uint32_t pid, SigIntId sid, uint8_t flags) { flags |= MPM_PATTERN_FLAG_NOCASE; return MpmAddPattern(mpm_ctx, pat, patlen, offset, depth, pid, sid, flags); @@ -1095,9 +1081,8 @@ int SCACAddPatternCI(MpmCtx *mpm_ctx, uint8_t *pat, uint16_t patlen, * \retval 0 On success. * \retval -1 On failure. */ -int SCACAddPatternCS(MpmCtx *mpm_ctx, uint8_t *pat, uint16_t patlen, - uint16_t offset, uint16_t depth, uint32_t pid, - SigIntId sid, uint8_t flags) +int SCACAddPatternCS(MpmCtx *mpm_ctx, uint8_t *pat, uint16_t patlen, uint16_t offset, + uint16_t depth, uint32_t pid, SigIntId sid, uint8_t flags) { return MpmAddPattern(mpm_ctx, pat, patlen, offset, depth, pid, sid, flags); } @@ -1123,7 +1108,6 @@ void SCACPrintInfo(MpmCtx *mpm_ctx) return; } - /************************** Mpm Registration ***************************/ /** @@ -1168,13 +1152,12 @@ static int SCACTest01(void) const char *buf = "abcdefghjiklmnopqrstuvwxyz"; - uint32_t cnt = SCACSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, - (uint8_t *)buf, strlen(buf)); + uint32_t cnt = SCACSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, strlen(buf)); if (cnt == 1) result = 1; else - printf("1 != %" PRIu32 " ",cnt); + printf("1 != %" PRIu32 " ", cnt); SCACDestroyCtx(&mpm_ctx); PmqFree(&pmq); @@ -1199,13 +1182,12 @@ static int SCACTest02(void) SCACPreparePatterns(&mpm_ctx); const char *buf = "abcdefghjiklmnopqrstuvwxyz"; - uint32_t cnt = SCACSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, - (uint8_t *)buf, strlen(buf)); + uint32_t cnt = SCACSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, strlen(buf)); if (cnt == 0) result = 1; else - printf("0 != %" PRIu32 " ",cnt); + printf("0 != %" PRIu32 " ", cnt); SCACDestroyCtx(&mpm_ctx); PmqFree(&pmq); @@ -1234,13 +1216,12 @@ static int SCACTest03(void) SCACPreparePatterns(&mpm_ctx); const char *buf = "abcdefghjiklmnopqrstuvwxyz"; - uint32_t cnt = SCACSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, - (uint8_t *)buf, strlen(buf)); + uint32_t cnt = SCACSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, strlen(buf)); if (cnt == 3) result = 1; else - printf("3 != %" PRIu32 " ",cnt); + printf("3 != %" PRIu32 " ", cnt); SCACDestroyCtx(&mpm_ctx); PmqFree(&pmq); @@ -1266,13 +1247,12 @@ static int SCACTest04(void) SCACPreparePatterns(&mpm_ctx); const char *buf = "abcdefghjiklmnopqrstuvwxyz"; - uint32_t cnt = SCACSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, - (uint8_t *)buf, strlen(buf)); + uint32_t cnt = SCACSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, strlen(buf)); if (cnt == 1) result = 1; else - printf("1 != %" PRIu32 " ",cnt); + printf("1 != %" PRIu32 " ", cnt); SCACDestroyCtx(&mpm_ctx); PmqFree(&pmq); @@ -1298,13 +1278,12 @@ static int SCACTest05(void) SCACPreparePatterns(&mpm_ctx); const char *buf = "abcdefghjiklmnopqrstuvwxyz"; - uint32_t cnt = SCACSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, - (uint8_t *)buf, strlen(buf)); + uint32_t cnt = SCACSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, strlen(buf)); if (cnt == 3) result = 1; else - printf("3 != %" PRIu32 " ",cnt); + printf("3 != %" PRIu32 " ", cnt); SCACDestroyCtx(&mpm_ctx); PmqFree(&pmq); @@ -1328,13 +1307,12 @@ static int SCACTest06(void) SCACPreparePatterns(&mpm_ctx); const char *buf = "abcd"; - uint32_t cnt = SCACSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, - (uint8_t *)buf, strlen(buf)); + uint32_t cnt = SCACSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, strlen(buf)); if (cnt == 1) result = 1; else - printf("1 != %" PRIu32 " ",cnt); + printf("1 != %" PRIu32 " ", cnt); SCACDestroyCtx(&mpm_ctx); PmqFree(&pmq); @@ -1362,16 +1340,14 @@ static int SCACTest07(void) /* 21 */ MpmAddPatternCS(&mpm_ctx, (uint8_t *)"AAAAAAAAAA", 10, 0, 0, 4, 0, 0); /* 1 */ - MpmAddPatternCS(&mpm_ctx, (uint8_t *)"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", - 30, 0, 0, 5, 0, 0); + MpmAddPatternCS(&mpm_ctx, (uint8_t *)"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", 30, 0, 0, 5, 0, 0); PmqSetup(&pmq); /* total matches: 135: unique matches: 6 */ SCACPreparePatterns(&mpm_ctx); const char *buf = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"; - uint32_t cnt = SCACSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, - (uint8_t *)buf, strlen(buf)); + uint32_t cnt = SCACSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, strlen(buf)); FAIL_IF_NOT(cnt == 6); SCACDestroyCtx(&mpm_ctx); @@ -1396,13 +1372,12 @@ static int SCACTest08(void) SCACPreparePatterns(&mpm_ctx); - uint32_t cnt = SCACSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, - (uint8_t *)"a", 1); + uint32_t cnt = SCACSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)"a", 1); if (cnt == 0) result = 1; else - printf("0 != %" PRIu32 " ",cnt); + printf("0 != %" PRIu32 " ", cnt); SCACDestroyCtx(&mpm_ctx); PmqFree(&pmq); @@ -1426,13 +1401,12 @@ static int SCACTest09(void) SCACPreparePatterns(&mpm_ctx); - uint32_t cnt = SCACSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, - (uint8_t *)"ab", 2); + uint32_t cnt = SCACSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)"ab", 2); if (cnt == 1) result = 1; else - printf("1 != %" PRIu32 " ",cnt); + printf("1 != %" PRIu32 " ", cnt); SCACDestroyCtx(&mpm_ctx); PmqFree(&pmq); @@ -1457,17 +1431,16 @@ static int SCACTest10(void) SCACPreparePatterns(&mpm_ctx); const char *buf = "01234567890123456789012345678901234567890123456789" - "01234567890123456789012345678901234567890123456789" - "abcdefgh" - "01234567890123456789012345678901234567890123456789" - "01234567890123456789012345678901234567890123456789"; - uint32_t cnt = SCACSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, - (uint8_t *)buf, strlen(buf)); + "01234567890123456789012345678901234567890123456789" + "abcdefgh" + "01234567890123456789012345678901234567890123456789" + "01234567890123456789012345678901234567890123456789"; + uint32_t cnt = SCACSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, strlen(buf)); if (cnt == 1) result = 1; else - printf("1 != %" PRIu32 " ",cnt); + printf("1 != %" PRIu32 " ", cnt); SCACDestroyCtx(&mpm_ctx); PmqFree(&pmq); @@ -1501,22 +1474,18 @@ static int SCACTest11(void) result = 1; const char *buf = "he"; - result &= (SCACSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, - strlen(buf)) == 1); + result &= (SCACSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, strlen(buf)) == 1); buf = "she"; - result &= (SCACSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, - strlen(buf)) == 2); + result &= (SCACSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, strlen(buf)) == 2); buf = "his"; - result &= (SCACSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, - strlen(buf)) == 1); + result &= (SCACSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, strlen(buf)) == 1); buf = "hers"; - result &= (SCACSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, - strlen(buf)) == 2); + result &= (SCACSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, strlen(buf)) == 2); - end: - SCACDestroyCtx(&mpm_ctx); - PmqFree(&pmq); - return result; +end: + SCACDestroyCtx(&mpm_ctx); + PmqFree(&pmq); + return result; } static int SCACTest12(void) @@ -1539,13 +1508,12 @@ static int SCACTest12(void) SCACPreparePatterns(&mpm_ctx); const char *buf = "abcdefghijklmnopqrstuvwxyz"; - uint32_t cnt = SCACSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, - (uint8_t *)buf, strlen(buf)); + uint32_t cnt = SCACSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, strlen(buf)); if (cnt == 2) result = 1; else - printf("2 != %" PRIu32 " ",cnt); + printf("2 != %" PRIu32 " ", cnt); SCACDestroyCtx(&mpm_ctx); PmqFree(&pmq); @@ -1571,13 +1539,12 @@ static int SCACTest13(void) SCACPreparePatterns(&mpm_ctx); const char *buf = "abcdefghijklmnopqrstuvwxyzABCD"; - uint32_t cnt = SCACSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, - (uint8_t *)buf, strlen(buf)); + uint32_t cnt = SCACSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, strlen(buf)); if (cnt == 1) result = 1; else - printf("1 != %" PRIu32 " ",cnt); + printf("1 != %" PRIu32 " ", cnt); SCACDestroyCtx(&mpm_ctx); PmqFree(&pmq); @@ -1603,13 +1570,12 @@ static int SCACTest14(void) SCACPreparePatterns(&mpm_ctx); const char *buf = "abcdefghijklmnopqrstuvwxyzABCDE"; - uint32_t cnt = SCACSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, - (uint8_t *)buf, strlen(buf)); + uint32_t cnt = SCACSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, strlen(buf)); if (cnt == 1) result = 1; else - printf("1 != %" PRIu32 " ",cnt); + printf("1 != %" PRIu32 " ", cnt); SCACDestroyCtx(&mpm_ctx); PmqFree(&pmq); @@ -1635,13 +1601,12 @@ static int SCACTest15(void) SCACPreparePatterns(&mpm_ctx); const char *buf = "abcdefghijklmnopqrstuvwxyzABCDEF"; - uint32_t cnt = SCACSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, - (uint8_t *)buf, strlen(buf)); + uint32_t cnt = SCACSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, strlen(buf)); if (cnt == 1) result = 1; else - printf("1 != %" PRIu32 " ",cnt); + printf("1 != %" PRIu32 " ", cnt); SCACDestroyCtx(&mpm_ctx); PmqFree(&pmq); @@ -1667,13 +1632,12 @@ static int SCACTest16(void) SCACPreparePatterns(&mpm_ctx); const char *buf = "abcdefghijklmnopqrstuvwxyzABC"; - uint32_t cnt = SCACSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, - (uint8_t *)buf, strlen(buf)); + uint32_t cnt = SCACSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, strlen(buf)); if (cnt == 1) result = 1; else - printf("1 != %" PRIu32 " ",cnt); + printf("1 != %" PRIu32 " ", cnt); SCACDestroyCtx(&mpm_ctx); PmqFree(&pmq); @@ -1699,13 +1663,12 @@ static int SCACTest17(void) SCACPreparePatterns(&mpm_ctx); const char *buf = "abcdefghijklmnopqrstuvwxyzAB"; - uint32_t cnt = SCACSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, - (uint8_t *)buf, strlen(buf)); + uint32_t cnt = SCACSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, strlen(buf)); if (cnt == 1) result = 1; else - printf("1 != %" PRIu32 " ",cnt); + printf("1 != %" PRIu32 " ", cnt); SCACDestroyCtx(&mpm_ctx); PmqFree(&pmq); @@ -1735,14 +1698,18 @@ static int SCACTest18(void) SCACPreparePatterns(&mpm_ctx); - const char *buf = "abcde""fghij""klmno""pqrst""uvwxy""z"; - uint32_t cnt = SCACSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, - (uint8_t *)buf, strlen(buf)); + const char *buf = "abcde" + "fghij" + "klmno" + "pqrst" + "uvwxy" + "z"; + uint32_t cnt = SCACSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, strlen(buf)); if (cnt == 1) result = 1; else - printf("1 != %" PRIu32 " ",cnt); + printf("1 != %" PRIu32 " ", cnt); SCACDestroyCtx(&mpm_ctx); PmqFree(&pmq); @@ -1768,13 +1735,12 @@ static int SCACTest19(void) SCACPreparePatterns(&mpm_ctx); const char *buf = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"; - uint32_t cnt = SCACSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, - (uint8_t *)buf, strlen(buf)); + uint32_t cnt = SCACSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, strlen(buf)); if (cnt == 1) result = 1; else - printf("1 != %" PRIu32 " ",cnt); + printf("1 != %" PRIu32 " ", cnt); SCACDestroyCtx(&mpm_ctx); PmqFree(&pmq); @@ -1805,14 +1771,19 @@ static int SCACTest20(void) SCACPreparePatterns(&mpm_ctx); - const char *buf = "AAAAA""AAAAA""AAAAA""AAAAA""AAAAA""AAAAA""AA"; - uint32_t cnt = SCACSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, - (uint8_t *)buf, strlen(buf)); + const char *buf = "AAAAA" + "AAAAA" + "AAAAA" + "AAAAA" + "AAAAA" + "AAAAA" + "AA"; + uint32_t cnt = SCACSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, strlen(buf)); if (cnt == 1) result = 1; else - printf("1 != %" PRIu32 " ",cnt); + printf("1 != %" PRIu32 " ", cnt); SCACDestroyCtx(&mpm_ctx); PmqFree(&pmq); @@ -1836,13 +1807,12 @@ static int SCACTest21(void) SCACPreparePatterns(&mpm_ctx); - uint32_t cnt = SCACSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, - (uint8_t *)"AA", 2); + uint32_t cnt = SCACSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)"AA", 2); if (cnt == 1) result = 1; else - printf("1 != %" PRIu32 " ",cnt); + printf("1 != %" PRIu32 " ", cnt); SCACDestroyCtx(&mpm_ctx); PmqFree(&pmq); @@ -1869,13 +1839,12 @@ static int SCACTest22(void) SCACPreparePatterns(&mpm_ctx); const char *buf = "abcdefghijklmnopqrstuvwxyz"; - uint32_t cnt = SCACSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, - (uint8_t *)buf, strlen(buf)); + uint32_t cnt = SCACSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, strlen(buf)); if (cnt == 2) result = 1; else - printf("2 != %" PRIu32 " ",cnt); + printf("2 != %" PRIu32 " ", cnt); SCACDestroyCtx(&mpm_ctx); PmqFree(&pmq); @@ -1899,13 +1868,12 @@ static int SCACTest23(void) SCACPreparePatterns(&mpm_ctx); - uint32_t cnt = SCACSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, - (uint8_t *)"aa", 2); + uint32_t cnt = SCACSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)"aa", 2); if (cnt == 0) result = 1; else - printf("1 != %" PRIu32 " ",cnt); + printf("1 != %" PRIu32 " ", cnt); SCACDestroyCtx(&mpm_ctx); PmqFree(&pmq); @@ -1929,13 +1897,12 @@ static int SCACTest24(void) SCACPreparePatterns(&mpm_ctx); - uint32_t cnt = SCACSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, - (uint8_t *)"aa", 2); + uint32_t cnt = SCACSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)"aa", 2); if (cnt == 1) result = 1; else - printf("1 != %" PRIu32 " ",cnt); + printf("1 != %" PRIu32 " ", cnt); SCACDestroyCtx(&mpm_ctx); PmqFree(&pmq); @@ -1961,13 +1928,12 @@ static int SCACTest25(void) SCACPreparePatterns(&mpm_ctx); const char *buf = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; - uint32_t cnt = SCACSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, - (uint8_t *)buf, strlen(buf)); + uint32_t cnt = SCACSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, strlen(buf)); if (cnt == 3) result = 1; else - printf("3 != %" PRIu32 " ",cnt); + printf("3 != %" PRIu32 " ", cnt); SCACDestroyCtx(&mpm_ctx); PmqFree(&pmq); @@ -1992,13 +1958,12 @@ static int SCACTest26(void) SCACPreparePatterns(&mpm_ctx); const char *buf = "works"; - uint32_t cnt = SCACSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, - (uint8_t *)buf, strlen(buf)); + uint32_t cnt = SCACSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, strlen(buf)); if (cnt == 1) result = 1; else - printf("3 != %" PRIu32 " ",cnt); + printf("3 != %" PRIu32 " ", cnt); SCACDestroyCtx(&mpm_ctx); PmqFree(&pmq); @@ -2023,13 +1988,12 @@ static int SCACTest27(void) SCACPreparePatterns(&mpm_ctx); const char *buf = "tone"; - uint32_t cnt = SCACSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, - (uint8_t *)buf, strlen(buf)); + uint32_t cnt = SCACSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, strlen(buf)); if (cnt == 0) result = 1; else - printf("0 != %" PRIu32 " ",cnt); + printf("0 != %" PRIu32 " ", cnt); SCACDestroyCtx(&mpm_ctx); PmqFree(&pmq); @@ -2054,13 +2018,12 @@ static int SCACTest28(void) SCACPreparePatterns(&mpm_ctx); const char *buf = "tONE"; - uint32_t cnt = SCACSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, - (uint8_t *)buf, strlen(buf)); + uint32_t cnt = SCACSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, strlen(buf)); if (cnt == 0) result = 1; else - printf("0 != %" PRIu32 " ",cnt); + printf("0 != %" PRIu32 " ", cnt); SCACDestroyCtx(&mpm_ctx); PmqFree(&pmq); @@ -2085,12 +2048,14 @@ static int SCACTest29(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " - "(content:\"onetwothreefourfivesixseveneightnine\"; sid:1;)"); + de_ctx->sig_list = + SigInit(de_ctx, "alert tcp any any -> any any " + "(content:\"onetwothreefourfivesixseveneightnine\"; sid:1;)"); if (de_ctx->sig_list == NULL) goto end; - de_ctx->sig_list->next = SigInit(de_ctx, "alert tcp any any -> any any " - "(content:\"onetwothreefourfivesixseveneightnine\"; fast_pattern:3,3; sid:2;)"); + de_ctx->sig_list->next = SigInit(de_ctx, + "alert tcp any any -> any any " + "(content:\"onetwothreefourfivesixseveneightnine\"; fast_pattern:3,3; sid:2;)"); if (de_ctx->sig_list->next == NULL) goto end; diff --git a/src/util-mpm-hs.c b/src/util-mpm-hs.c index a3b896abde93..7e99a25987df 100644 --- a/src/util-mpm-hs.c +++ b/src/util-mpm-hs.c @@ -51,13 +51,13 @@ void SCHSInitCtx(MpmCtx *); void SCHSInitThreadCtx(MpmCtx *, MpmThreadCtx *); void SCHSDestroyCtx(MpmCtx *); void SCHSDestroyThreadCtx(MpmCtx *, MpmThreadCtx *); -int SCHSAddPatternCI(MpmCtx *, uint8_t *, uint16_t, uint16_t, uint16_t, - uint32_t, SigIntId, uint8_t); -int SCHSAddPatternCS(MpmCtx *, uint8_t *, uint16_t, uint16_t, uint16_t, - uint32_t, SigIntId, uint8_t); +int SCHSAddPatternCI( + MpmCtx *, uint8_t *, uint16_t, uint16_t, uint16_t, uint32_t, SigIntId, uint8_t); +int SCHSAddPatternCS( + MpmCtx *, uint8_t *, uint16_t, uint16_t, uint16_t, uint32_t, SigIntId, uint8_t); int SCHSPreparePatterns(MpmCtx *mpm_ctx); -uint32_t SCHSSearch(const MpmCtx *mpm_ctx, MpmThreadCtx *mpm_thread_ctx, - PrefilterRuleStore *pmq, const uint8_t *buf, const uint32_t buflen); +uint32_t SCHSSearch(const MpmCtx *mpm_ctx, MpmThreadCtx *mpm_thread_ctx, PrefilterRuleStore *pmq, + const uint8_t *buf, const uint32_t buflen); void SCHSPrintInfo(MpmCtx *mpm_ctx); void SCHSPrintSearchStats(MpmThreadCtx *mpm_thread_ctx); void SCHSRegisterTests(void); @@ -143,10 +143,8 @@ static inline uint32_t SCHSInitHashRaw(uint8_t *pat, uint16_t patlen) * * \retval hash A 32 bit unsigned hash. */ -static inline SCHSPattern *SCHSInitHashLookup(SCHSCtx *ctx, uint8_t *pat, - uint16_t patlen, uint16_t offset, - uint16_t depth, char flags, - uint32_t pid) +static inline SCHSPattern *SCHSInitHashLookup(SCHSCtx *ctx, uint8_t *pat, uint16_t patlen, + uint16_t offset, uint16_t depth, char flags, uint32_t pid) { uint32_t hash = SCHSInitHashRaw(pat, patlen); @@ -266,9 +264,8 @@ static inline int SCHSInitHashAdd(SCHSCtx *ctx, SCHSPattern *p) * \retval 0 On success. * \retval -1 On failure. */ -static int SCHSAddPattern(MpmCtx *mpm_ctx, uint8_t *pat, uint16_t patlen, - uint16_t offset, uint16_t depth, uint32_t pid, - SigIntId sid, uint8_t flags) +static int SCHSAddPattern(MpmCtx *mpm_ctx, uint8_t *pat, uint16_t patlen, uint16_t offset, + uint16_t depth, uint32_t pid, SigIntId sid, uint8_t flags) { SCHSCtx *ctx = (SCHSCtx *)mpm_ctx->ctx; @@ -285,8 +282,7 @@ static int SCHSAddPattern(MpmCtx *mpm_ctx, uint8_t *pat, uint16_t patlen, } /* check if we have already inserted this pattern */ - SCHSPattern *p = - SCHSInitHashLookup(ctx, pat, patlen, offset, depth, flags, pid); + SCHSPattern *p = SCHSInitHashLookup(ctx, pat, patlen, offset, depth, flags, pid); if (p == NULL) { SCLogDebug("Allocing new pattern"); @@ -470,9 +466,9 @@ static uint32_t SCHSPatternHash(const SCHSPattern *p, uint32_t hash) static char SCHSPatternCompare(const SCHSPattern *p1, const SCHSPattern *p2) { - if ((p1->len != p2->len) || (p1->flags != p2->flags) || - (p1->id != p2->id) || (p1->offset != p2->offset) || - (p1->depth != p2->depth) || (p1->sids_size != p2->sids_size)) { + if ((p1->len != p2->len) || (p1->flags != p2->flags) || (p1->id != p2->id) || + (p1->offset != p2->offset) || (p1->depth != p2->depth) || + (p1->sids_size != p2->sids_size)) { return 0; } @@ -480,8 +476,7 @@ static char SCHSPatternCompare(const SCHSPattern *p1, const SCHSPattern *p2) return 0; } - if (SCMemcmp(p1->sids, p2->sids, p1->sids_size * sizeof(p1->sids[0])) != - 0) { + if (SCMemcmp(p1->sids, p2->sids, p1->sids_size * sizeof(p1->sids[0])) != 0) { return 0; } @@ -502,8 +497,7 @@ static uint32_t PatternDatabaseHash(HashTable *ht, void *data, uint16_t len) return hash; } -static char PatternDatabaseCompare(void *data1, uint16_t len1, void *data2, - uint16_t len2) +static char PatternDatabaseCompare(void *data1, uint16_t len1, void *data2, uint16_t len2) { const PatternDatabase *pd1 = data1; const PatternDatabase *pd2 = data2; @@ -618,9 +612,8 @@ int SCHSPreparePatterns(MpmCtx *mpm_ctx) /* Init global pattern database hash if necessary. */ if (g_db_table == NULL) { - g_db_table = HashTableInit(INIT_DB_HASH_SIZE, PatternDatabaseHash, - PatternDatabaseCompare, - PatternDatabaseTableFree); + g_db_table = HashTableInit(INIT_DB_HASH_SIZE, PatternDatabaseHash, PatternDatabaseCompare, + PatternDatabaseTableFree); if (g_db_table == NULL) { SCMutexUnlock(&g_db_table_mutex); goto error; @@ -632,10 +625,8 @@ int SCHSPreparePatterns(MpmCtx *mpm_ctx) PatternDatabase *pd_cached = HashTableLookup(g_db_table, pd, 1); if (pd_cached != NULL) { - SCLogDebug("Reusing cached database %p with %" PRIu32 - " patterns (ref_cnt=%" PRIu32 ")", - pd_cached->hs_db, pd_cached->pattern_cnt, - pd_cached->ref_cnt); + SCLogDebug("Reusing cached database %p with %" PRIu32 " patterns (ref_cnt=%" PRIu32 ")", + pd_cached->hs_db, pd_cached->pattern_cnt, pd_cached->ref_cnt); pd_cached->ref_cnt++; ctx->pattern_db = pd_cached; SCMutexUnlock(&g_db_table_mutex); @@ -677,10 +668,9 @@ int SCHSPreparePatterns(MpmCtx *mpm_ctx) BUG_ON(mpm_ctx->pattern_cnt == 0); - err = hs_compile_ext_multi((const char *const *)cd->expressions, cd->flags, - cd->ids, (const hs_expr_ext_t *const *)cd->ext, - cd->pattern_cnt, HS_MODE_BLOCK, NULL, &pd->hs_db, - &compile_err); + err = hs_compile_ext_multi((const char *const *)cd->expressions, cd->flags, cd->ids, + (const hs_expr_ext_t *const *)cd->ext, cd->pattern_cnt, HS_MODE_BLOCK, NULL, &pd->hs_db, + &compile_err); if (err != HS_SUCCESS) { SCLogError("failed to compile hyperscan database"); @@ -713,8 +703,8 @@ int SCHSPreparePatterns(MpmCtx *mpm_ctx) mpm_ctx->memory_cnt++; mpm_ctx->memory_size += ctx->hs_db_size; - SCLogDebug("Built %" PRIu32 " patterns into a database of size %" PRIuMAX - " bytes", mpm_ctx->pattern_cnt, (uintmax_t)ctx->hs_db_size); + SCLogDebug("Built %" PRIu32 " patterns into a database of size %" PRIuMAX " bytes", + mpm_ctx->pattern_cnt, (uintmax_t)ctx->hs_db_size); /* Cache this database globally for later. */ pd->ref_cnt = 1; @@ -768,8 +758,7 @@ void SCHSInitThreadCtx(MpmCtx *mpm_ctx, MpmThreadCtx *mpm_thread_ctx) return; } - hs_error_t err = hs_clone_scratch(g_scratch_proto, - (hs_scratch_t **)&ctx->scratch); + hs_error_t err = hs_clone_scratch(g_scratch_proto, (hs_scratch_t **)&ctx->scratch); SCMutexUnlock(&g_scratch_proto_mutex); @@ -882,18 +871,16 @@ typedef struct SCHSCallbackCtx_ { } SCHSCallbackCtx; /* Hyperscan MPM match event handler */ -static int SCHSMatchEvent(unsigned int id, unsigned long long from, - unsigned long long to, unsigned int flags, - void *ctx) +static int SCHSMatchEvent(unsigned int id, unsigned long long from, unsigned long long to, + unsigned int flags, void *ctx) { SCHSCallbackCtx *cctx = ctx; PrefilterRuleStore *pmq = cctx->pmq; const PatternDatabase *pd = cctx->ctx->pattern_db; const SCHSPattern *pat = pd->parray[id]; - SCLogDebug("Hyperscan Match %" PRIu32 ": id=%" PRIu32 " @ %" PRIuMAX - " (pat id=%" PRIu32 ")", - cctx->match_count, (uint32_t)id, (uintmax_t)to, pat->id); + SCLogDebug("Hyperscan Match %" PRIu32 ": id=%" PRIu32 " @ %" PRIuMAX " (pat id=%" PRIu32 ")", + cctx->match_count, (uint32_t)id, (uintmax_t)to, pat->id); PrefilterAddSids(pmq, pat->sids, pat->sids_size); @@ -913,8 +900,8 @@ static int SCHSMatchEvent(unsigned int id, unsigned long long from, * * \retval matches Match count. */ -uint32_t SCHSSearch(const MpmCtx *mpm_ctx, MpmThreadCtx *mpm_thread_ctx, - PrefilterRuleStore *pmq, const uint8_t *buf, const uint32_t buflen) +uint32_t SCHSSearch(const MpmCtx *mpm_ctx, MpmThreadCtx *mpm_thread_ctx, PrefilterRuleStore *pmq, + const uint8_t *buf, const uint32_t buflen) { uint32_t ret = 0; SCHSCtx *ctx = (SCHSCtx *)mpm_ctx->ctx; @@ -925,15 +912,15 @@ uint32_t SCHSSearch(const MpmCtx *mpm_ctx, MpmThreadCtx *mpm_thread_ctx, return 0; } - SCHSCallbackCtx cctx = {.ctx = ctx, .pmq = pmq, .match_count = 0}; + SCHSCallbackCtx cctx = { .ctx = ctx, .pmq = pmq, .match_count = 0 }; /* scratch should have been cloned from g_scratch_proto at thread init. */ hs_scratch_t *scratch = hs_thread_ctx->scratch; BUG_ON(pd->hs_db == NULL); BUG_ON(scratch == NULL); - hs_error_t err = hs_scan(pd->hs_db, (const char *)buf, buflen, 0, scratch, - SCHSMatchEvent, &cctx); + hs_error_t err = + hs_scan(pd->hs_db, (const char *)buf, buflen, 0, scratch, SCHSMatchEvent, &cctx); if (err != HS_SUCCESS) { /* An error value (other than HS_SCAN_TERMINATED) from hs_scan() * indicates that it was passed an invalid database or scratch region, @@ -964,9 +951,8 @@ uint32_t SCHSSearch(const MpmCtx *mpm_ctx, MpmThreadCtx *mpm_thread_ctx, * \retval 0 On success. * \retval -1 On failure. */ -int SCHSAddPatternCI(MpmCtx *mpm_ctx, uint8_t *pat, uint16_t patlen, - uint16_t offset, uint16_t depth, uint32_t pid, - SigIntId sid, uint8_t flags) +int SCHSAddPatternCI(MpmCtx *mpm_ctx, uint8_t *pat, uint16_t patlen, uint16_t offset, + uint16_t depth, uint32_t pid, SigIntId sid, uint8_t flags) { flags |= MPM_PATTERN_FLAG_NOCASE; return SCHSAddPattern(mpm_ctx, pat, patlen, offset, depth, pid, sid, flags); @@ -989,9 +975,8 @@ int SCHSAddPatternCI(MpmCtx *mpm_ctx, uint8_t *pat, uint16_t patlen, * \retval 0 On success. * \retval -1 On failure. */ -int SCHSAddPatternCS(MpmCtx *mpm_ctx, uint8_t *pat, uint16_t patlen, - uint16_t offset, uint16_t depth, uint32_t pid, - SigIntId sid, uint8_t flags) +int SCHSAddPatternCS(MpmCtx *mpm_ctx, uint8_t *pat, uint16_t patlen, uint16_t offset, + uint16_t depth, uint32_t pid, SigIntId sid, uint8_t flags) { return SCHSAddPattern(mpm_ctx, pat, patlen, offset, depth, pid, sid, flags); } @@ -1024,8 +1009,7 @@ void SCHSPrintInfo(MpmCtx *mpm_ctx) printf("HS Database Info: %s\n", db_info); SCFree(db_info); } - printf("HS Database Size: %" PRIuMAX " bytes\n", - (uintmax_t)ctx->hs_db_size); + printf("HS Database Size: %" PRIuMAX " bytes\n", (uintmax_t)ctx->hs_db_size); } printf("\n"); @@ -1104,8 +1088,7 @@ static int SCHSTest01(void) const char *buf = "abcdefghjiklmnopqrstuvwxyz"; - uint32_t cnt = SCHSSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, - strlen(buf)); + uint32_t cnt = SCHSSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, strlen(buf)); if (cnt == 1) result = 1; @@ -1137,8 +1120,7 @@ static int SCHSTest02(void) SCHSInitThreadCtx(&mpm_ctx, &mpm_thread_ctx); const char *buf = "abcdefghjiklmnopqrstuvwxyz"; - uint32_t cnt = SCHSSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, - strlen(buf)); + uint32_t cnt = SCHSSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, strlen(buf)); if (cnt == 0) result = 1; @@ -1174,8 +1156,7 @@ static int SCHSTest03(void) SCHSInitThreadCtx(&mpm_ctx, &mpm_thread_ctx); const char *buf = "abcdefghjiklmnopqrstuvwxyz"; - uint32_t cnt = SCHSSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, - strlen(buf)); + uint32_t cnt = SCHSSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, strlen(buf)); if (cnt == 3) result = 1; @@ -1208,8 +1189,7 @@ static int SCHSTest04(void) SCHSInitThreadCtx(&mpm_ctx, &mpm_thread_ctx); const char *buf = "abcdefghjiklmnopqrstuvwxyz"; - uint32_t cnt = SCHSSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, - strlen(buf)); + uint32_t cnt = SCHSSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, strlen(buf)); if (cnt == 1) result = 1; @@ -1242,8 +1222,7 @@ static int SCHSTest05(void) SCHSInitThreadCtx(&mpm_ctx, &mpm_thread_ctx); const char *buf = "abcdefghjiklmnopqrstuvwxyz"; - uint32_t cnt = SCHSSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, - strlen(buf)); + uint32_t cnt = SCHSSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, strlen(buf)); if (cnt == 3) result = 1; @@ -1274,8 +1253,7 @@ static int SCHSTest06(void) SCHSInitThreadCtx(&mpm_ctx, &mpm_thread_ctx); const char *buf = "abcd"; - uint32_t cnt = SCHSSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, - strlen(buf)); + uint32_t cnt = SCHSSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, strlen(buf)); if (cnt == 1) result = 1; @@ -1310,16 +1288,14 @@ static int SCHSTest07(void) /* 21 */ MpmAddPatternCS(&mpm_ctx, (uint8_t *)"AAAAAAAAAA", 10, 0, 0, 4, 0, 0); /* 1 */ - MpmAddPatternCS(&mpm_ctx, (uint8_t *)"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", 30, - 0, 0, 5, 0, 0); + MpmAddPatternCS(&mpm_ctx, (uint8_t *)"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", 30, 0, 0, 5, 0, 0); PmqSetup(&pmq); SCHSPreparePatterns(&mpm_ctx); SCHSInitThreadCtx(&mpm_ctx, &mpm_thread_ctx); const char *buf = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"; - uint32_t cnt = SCHSSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, - strlen(buf)); + uint32_t cnt = SCHSSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, strlen(buf)); if (cnt == 6) result = 1; @@ -1350,8 +1326,7 @@ static int SCHSTest08(void) SCHSPreparePatterns(&mpm_ctx); SCHSInitThreadCtx(&mpm_ctx, &mpm_thread_ctx); - uint32_t cnt = - SCHSSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)"a", 1); + uint32_t cnt = SCHSSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)"a", 1); if (cnt == 0) result = 1; @@ -1382,8 +1357,7 @@ static int SCHSTest09(void) SCHSPreparePatterns(&mpm_ctx); SCHSInitThreadCtx(&mpm_ctx, &mpm_thread_ctx); - uint32_t cnt = - SCHSSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)"ab", 2); + uint32_t cnt = SCHSSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)"ab", 2); if (cnt == 1) result = 1; @@ -1415,12 +1389,11 @@ static int SCHSTest10(void) SCHSInitThreadCtx(&mpm_ctx, &mpm_thread_ctx); const char *buf = "01234567890123456789012345678901234567890123456789" - "01234567890123456789012345678901234567890123456789" - "abcdefgh" - "01234567890123456789012345678901234567890123456789" - "01234567890123456789012345678901234567890123456789"; - uint32_t cnt = SCHSSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, - strlen(buf)); + "01234567890123456789012345678901234567890123456789" + "abcdefgh" + "01234567890123456789012345678901234567890123456789" + "01234567890123456789012345678901234567890123456789"; + uint32_t cnt = SCHSSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, strlen(buf)); if (cnt == 1) result = 1; @@ -1462,17 +1435,13 @@ static int SCHSTest11(void) result = 1; const char *buf = "he"; - result &= (SCHSSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, - strlen(buf)) == 1); + result &= (SCHSSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, strlen(buf)) == 1); buf = "she"; - result &= (SCHSSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, - strlen(buf)) == 2); + result &= (SCHSSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, strlen(buf)) == 2); buf = "his"; - result &= (SCHSSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, - strlen(buf)) == 1); + result &= (SCHSSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, strlen(buf)) == 1); buf = "hers"; - result &= (SCHSSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, - strlen(buf)) == 2); + result &= (SCHSSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, strlen(buf)) == 2); end: SCHSDestroyCtx(&mpm_ctx); @@ -1502,8 +1471,7 @@ static int SCHSTest12(void) SCHSInitThreadCtx(&mpm_ctx, &mpm_thread_ctx); const char *buf = "abcdefghijklmnopqrstuvwxyz"; - uint32_t cnt = SCHSSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, - strlen(buf)); + uint32_t cnt = SCHSSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, strlen(buf)); if (cnt == 2) result = 1; @@ -1536,8 +1504,7 @@ static int SCHSTest13(void) SCHSInitThreadCtx(&mpm_ctx, &mpm_thread_ctx); const char *buf = "abcdefghijklmnopqrstuvwxyzABCD"; - uint32_t cnt = SCHSSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, - strlen(buf)); + uint32_t cnt = SCHSSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, strlen(buf)); if (cnt == 1) result = 1; @@ -1570,8 +1537,7 @@ static int SCHSTest14(void) SCHSInitThreadCtx(&mpm_ctx, &mpm_thread_ctx); const char *buf = "abcdefghijklmnopqrstuvwxyzABCDE"; - uint32_t cnt = SCHSSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, - strlen(buf)); + uint32_t cnt = SCHSSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, strlen(buf)); if (cnt == 1) result = 1; @@ -1604,8 +1570,7 @@ static int SCHSTest15(void) SCHSInitThreadCtx(&mpm_ctx, &mpm_thread_ctx); const char *buf = "abcdefghijklmnopqrstuvwxyzABCDEF"; - uint32_t cnt = SCHSSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, - strlen(buf)); + uint32_t cnt = SCHSSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, strlen(buf)); if (cnt == 1) result = 1; @@ -1638,8 +1603,7 @@ static int SCHSTest16(void) SCHSInitThreadCtx(&mpm_ctx, &mpm_thread_ctx); const char *buf = "abcdefghijklmnopqrstuvwxyzABC"; - uint32_t cnt = SCHSSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, - strlen(buf)); + uint32_t cnt = SCHSSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, strlen(buf)); if (cnt == 1) result = 1; @@ -1672,8 +1636,7 @@ static int SCHSTest17(void) SCHSInitThreadCtx(&mpm_ctx, &mpm_thread_ctx); const char *buf = "abcdefghijklmnopqrstuvwxyzAB"; - uint32_t cnt = SCHSSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, - strlen(buf)); + uint32_t cnt = SCHSSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, strlen(buf)); if (cnt == 1) result = 1; @@ -1711,13 +1674,12 @@ static int SCHSTest18(void) SCHSInitThreadCtx(&mpm_ctx, &mpm_thread_ctx); const char *buf = "abcde" - "fghij" - "klmno" - "pqrst" - "uvwxy" - "z"; - uint32_t cnt = SCHSSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, - strlen(buf)); + "fghij" + "klmno" + "pqrst" + "uvwxy" + "z"; + uint32_t cnt = SCHSSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, strlen(buf)); if (cnt == 1) result = 1; @@ -1750,8 +1712,7 @@ static int SCHSTest19(void) SCHSInitThreadCtx(&mpm_ctx, &mpm_thread_ctx); const char *buf = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"; - uint32_t cnt = SCHSSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, - strlen(buf)); + uint32_t cnt = SCHSSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, strlen(buf)); if (cnt == 1) result = 1; @@ -1790,14 +1751,13 @@ static int SCHSTest20(void) SCHSInitThreadCtx(&mpm_ctx, &mpm_thread_ctx); const char *buf = "AAAAA" - "AAAAA" - "AAAAA" - "AAAAA" - "AAAAA" - "AAAAA" - "AA"; - uint32_t cnt = SCHSSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, - strlen(buf)); + "AAAAA" + "AAAAA" + "AAAAA" + "AAAAA" + "AAAAA" + "AA"; + uint32_t cnt = SCHSSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, strlen(buf)); if (cnt == 1) result = 1; @@ -1828,8 +1788,7 @@ static int SCHSTest21(void) SCHSPreparePatterns(&mpm_ctx); SCHSInitThreadCtx(&mpm_ctx, &mpm_thread_ctx); - uint32_t cnt = - SCHSSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)"AA", 2); + uint32_t cnt = SCHSSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)"AA", 2); if (cnt == 1) result = 1; @@ -1863,8 +1822,7 @@ static int SCHSTest22(void) SCHSInitThreadCtx(&mpm_ctx, &mpm_thread_ctx); const char *buf = "abcdefghijklmnopqrstuvwxyz"; - uint32_t cnt = SCHSSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, - strlen(buf)); + uint32_t cnt = SCHSSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, strlen(buf)); if (cnt == 2) result = 1; @@ -1895,8 +1853,7 @@ static int SCHSTest23(void) SCHSPreparePatterns(&mpm_ctx); SCHSInitThreadCtx(&mpm_ctx, &mpm_thread_ctx); - uint32_t cnt = - SCHSSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)"aa", 2); + uint32_t cnt = SCHSSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)"aa", 2); if (cnt == 0) result = 1; @@ -1927,8 +1884,7 @@ static int SCHSTest24(void) SCHSPreparePatterns(&mpm_ctx); SCHSInitThreadCtx(&mpm_ctx, &mpm_thread_ctx); - uint32_t cnt = - SCHSSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)"aa", 2); + uint32_t cnt = SCHSSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)"aa", 2); if (cnt == 1) result = 1; @@ -1961,8 +1917,7 @@ static int SCHSTest25(void) SCHSInitThreadCtx(&mpm_ctx, &mpm_thread_ctx); const char *buf = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; - uint32_t cnt = SCHSSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, - strlen(buf)); + uint32_t cnt = SCHSSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, strlen(buf)); if (cnt == 3) result = 1; @@ -1994,8 +1949,7 @@ static int SCHSTest26(void) SCHSInitThreadCtx(&mpm_ctx, &mpm_thread_ctx); const char *buf = "works"; - uint32_t cnt = SCHSSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, - strlen(buf)); + uint32_t cnt = SCHSSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, strlen(buf)); if (cnt == 1) result = 1; @@ -2027,8 +1981,7 @@ static int SCHSTest27(void) SCHSInitThreadCtx(&mpm_ctx, &mpm_thread_ctx); const char *buf = "tone"; - uint32_t cnt = SCHSSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, - strlen(buf)); + uint32_t cnt = SCHSSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, strlen(buf)); if (cnt == 0) result = 1; @@ -2060,8 +2013,7 @@ static int SCHSTest28(void) SCHSInitThreadCtx(&mpm_ctx, &mpm_thread_ctx); const char *buf = "tONE"; - uint32_t cnt = SCHSSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, - strlen(buf)); + uint32_t cnt = SCHSSearch(&mpm_ctx, &mpm_thread_ctx, &pmq, (uint8_t *)buf, strlen(buf)); if (cnt == 0) result = 1; @@ -2093,15 +2045,14 @@ static int SCHSTest29(void) de_ctx->flags |= DE_QUIET; - de_ctx->sig_list = SigInit( - de_ctx, "alert tcp any any -> any any " - "(content:\"onetwothreefourfivesixseveneightnine\"; sid:1;)"); + de_ctx->sig_list = + SigInit(de_ctx, "alert tcp any any -> any any " + "(content:\"onetwothreefourfivesixseveneightnine\"; sid:1;)"); if (de_ctx->sig_list == NULL) goto end; - de_ctx->sig_list->next = - SigInit(de_ctx, "alert tcp any any -> any any " - "(content:\"onetwothreefourfivesixseveneightnine\"; " - "fast_pattern:3,3; sid:2;)"); + de_ctx->sig_list->next = SigInit(de_ctx, "alert tcp any any -> any any " + "(content:\"onetwothreefourfivesixseveneightnine\"; " + "fast_pattern:3,3; sid:2;)"); if (de_ctx->sig_list->next == NULL) goto end; diff --git a/src/util-mpm.c b/src/util-mpm.c index 23ff23082885..21143d701b66 100644 --- a/src/util-mpm.c +++ b/src/util-mpm.c @@ -216,10 +216,10 @@ void MpmInitCtx(MpmCtx *mpm_ctx, uint8_t matcher) /* MPM matcher to use by default, i.e. when "mpm-algo" is set to "auto". * If Hyperscan is available, use it. Otherwise, use AC. */ #ifdef BUILD_HYPERSCAN -# define DEFAULT_MPM MPM_HS -# define DEFAULT_MPM_AC MPM_AC +#define DEFAULT_MPM MPM_HS +#define DEFAULT_MPM_AC MPM_AC #else -# define DEFAULT_MPM MPM_AC +#define DEFAULT_MPM MPM_AC #endif void MpmTableSetup(void) @@ -230,42 +230,37 @@ void MpmTableSetup(void) MpmACRegister(); MpmACTileRegister(); #ifdef BUILD_HYPERSCAN - #ifdef HAVE_HS_VALID_PLATFORM +#ifdef HAVE_HS_VALID_PLATFORM /* Enable runtime check for SSSE3. Do not use Hyperscan MPM matcher if * check is not successful. */ - if (hs_valid_platform() != HS_SUCCESS) { - SCLogInfo("SSSE3 support not detected, disabling Hyperscan for " - "MPM"); - /* Fall back to best Aho-Corasick variant. */ - mpm_default_matcher = DEFAULT_MPM_AC; - } else { - MpmHSRegister(); - } - #else + if (hs_valid_platform() != HS_SUCCESS) { + SCLogInfo("SSSE3 support not detected, disabling Hyperscan for " + "MPM"); + /* Fall back to best Aho-Corasick variant. */ + mpm_default_matcher = DEFAULT_MPM_AC; + } else { MpmHSRegister(); - #endif /* HAVE_HS_VALID_PLATFORM */ + } +#else + MpmHSRegister(); +#endif /* HAVE_HS_VALID_PLATFORM */ #endif /* BUILD_HYPERSCAN */ } -int MpmAddPatternCS(struct MpmCtx_ *mpm_ctx, uint8_t *pat, uint16_t patlen, - uint16_t offset, uint16_t depth, - uint32_t pid, SigIntId sid, uint8_t flags) +int MpmAddPatternCS(struct MpmCtx_ *mpm_ctx, uint8_t *pat, uint16_t patlen, uint16_t offset, + uint16_t depth, uint32_t pid, SigIntId sid, uint8_t flags) { - return mpm_table[mpm_ctx->mpm_type].AddPattern(mpm_ctx, pat, patlen, - offset, depth, - pid, sid, flags); + return mpm_table[mpm_ctx->mpm_type].AddPattern( + mpm_ctx, pat, patlen, offset, depth, pid, sid, flags); } -int MpmAddPatternCI(struct MpmCtx_ *mpm_ctx, uint8_t *pat, uint16_t patlen, - uint16_t offset, uint16_t depth, - uint32_t pid, SigIntId sid, uint8_t flags) +int MpmAddPatternCI(struct MpmCtx_ *mpm_ctx, uint8_t *pat, uint16_t patlen, uint16_t offset, + uint16_t depth, uint32_t pid, SigIntId sid, uint8_t flags) { - return mpm_table[mpm_ctx->mpm_type].AddPatternNocase(mpm_ctx, pat, patlen, - offset, depth, - pid, sid, flags); + return mpm_table[mpm_ctx->mpm_type].AddPatternNocase( + mpm_ctx, pat, patlen, offset, depth, pid, sid, flags); } - /** * \internal * \brief Creates a hash of the pattern. We use it for the hashing process @@ -297,10 +292,8 @@ static inline uint32_t MpmInitHashRaw(uint8_t *pat, uint16_t patlen) * * \retval hash A 32 bit unsigned hash. */ -static inline MpmPattern *MpmInitHashLookup(MpmCtx *ctx, - uint8_t *pat, uint16_t patlen, - uint16_t offset, uint16_t depth, - uint8_t flags, uint32_t pid) +static inline MpmPattern *MpmInitHashLookup(MpmCtx *ctx, uint8_t *pat, uint16_t patlen, + uint16_t offset, uint16_t depth, uint8_t flags, uint32_t pid) { uint32_t hash = MpmInitHashRaw(pat, patlen); @@ -309,15 +302,13 @@ static inline MpmPattern *MpmInitHashLookup(MpmCtx *ctx, } MpmPattern *t = ctx->init_hash[hash]; - for ( ; t != NULL; t = t->next) { + for (; t != NULL; t = t->next) { if (!(flags & MPM_PATTERN_CTX_OWNS_ID)) { if (t->id == pid) return t; } else { if (t->len == patlen && t->offset == offset && t->depth == depth && - memcmp(pat, t->original_pat, patlen) == 0 && - t->flags == flags) - { + memcmp(pat, t->original_pat, patlen) == 0 && t->flags == flags) { return t; } } @@ -436,12 +427,11 @@ static inline int MpmInitHashAdd(MpmCtx *ctx, MpmPattern *p) * \retval 0 On success. * \retval -1 On failure. */ -int MpmAddPattern(MpmCtx *mpm_ctx, uint8_t *pat, uint16_t patlen, - uint16_t offset, uint16_t depth, uint32_t pid, - SigIntId sid, uint8_t flags) +int MpmAddPattern(MpmCtx *mpm_ctx, uint8_t *pat, uint16_t patlen, uint16_t offset, uint16_t depth, + uint32_t pid, SigIntId sid, uint8_t flags) { - SCLogDebug("Adding pattern for ctx %p, patlen %"PRIu16" and pid %" PRIu32, - mpm_ctx, patlen, pid); + SCLogDebug( + "Adding pattern for ctx %p, patlen %" PRIu16 " and pid %" PRIu32, mpm_ctx, patlen, pid); if (patlen == 0) { SCLogWarning("pattern length 0"); @@ -452,8 +442,7 @@ int MpmAddPattern(MpmCtx *mpm_ctx, uint8_t *pat, uint16_t patlen, pid = UINT_MAX; /* check if we have already inserted this pattern */ - MpmPattern *p = MpmInitHashLookup(mpm_ctx, pat, patlen, - offset, depth, flags, pid); + MpmPattern *p = MpmInitHashLookup(mpm_ctx, pat, patlen, offset, depth, flags, pid); if (p == NULL) { SCLogDebug("Allocing new pattern"); @@ -566,7 +555,6 @@ int MpmAddPattern(MpmCtx *mpm_ctx, uint8_t *pat, uint16_t patlen, return -1; } - /************************************Unittests*********************************/ #ifdef UNITTESTS diff --git a/src/util-mpm.h b/src/util-mpm.h index d3ac12bdec89..5dcde8067d3b 100644 --- a/src/util-mpm.h +++ b/src/util-mpm.h @@ -82,8 +82,8 @@ typedef struct MpmPattern_ { /* Indicates if this a global mpm_ctx. Global mpm_ctx is the one that * is instantiated when we use "single". Non-global is "full", i.e. * one per sgh. */ -#define MPMCTX_FLAGS_GLOBAL BIT_U8(0) -#define MPMCTX_FLAGS_NODEPTH BIT_U8(1) +#define MPMCTX_FLAGS_GLOBAL BIT_U8(0) +#define MPMCTX_FLAGS_NODEPTH BIT_U8(1) typedef struct MpmCtx_ { void *ctx; @@ -131,12 +131,12 @@ typedef struct MpmCtxFactoryContainer_ { /** pattern is case insensitive */ #define MPM_PATTERN_FLAG_NOCASE 0x01 /** pattern has a depth setting */ -#define MPM_PATTERN_FLAG_DEPTH 0x04 +#define MPM_PATTERN_FLAG_DEPTH 0x04 /** pattern has an offset setting */ #define MPM_PATTERN_FLAG_OFFSET 0x08 /** the ctx uses it's own internal id instead of * what is passed through the API */ -#define MPM_PATTERN_CTX_OWNS_ID 0x20 +#define MPM_PATTERN_CTX_OWNS_ID 0x20 typedef struct MpmTableElmt_ { const char *name; @@ -156,11 +156,14 @@ typedef struct MpmTableElmt_ { * \param sid signature _internal_ id * \param flags pattern flags */ - int (*AddPattern)(struct MpmCtx_ *, uint8_t *, uint16_t, uint16_t, uint16_t, uint32_t, SigIntId, uint8_t); - int (*AddPatternNocase)(struct MpmCtx_ *, uint8_t *, uint16_t, uint16_t, uint16_t, uint32_t, SigIntId, uint8_t); - int (*Prepare)(struct MpmCtx_ *); + int (*AddPattern)( + struct MpmCtx_ *, uint8_t *, uint16_t, uint16_t, uint16_t, uint32_t, SigIntId, uint8_t); + int (*AddPatternNocase)( + struct MpmCtx_ *, uint8_t *, uint16_t, uint16_t, uint16_t, uint32_t, SigIntId, uint8_t); + int (*Prepare)(struct MpmCtx_ *); /** \retval cnt number of patterns that matches: once per pattern max. */ - uint32_t (*Search)(const struct MpmCtx_ *, struct MpmThreadCtx_ *, PrefilterRuleStore *, const uint8_t *, uint32_t); + uint32_t (*Search)(const struct MpmCtx_ *, struct MpmThreadCtx_ *, PrefilterRuleStore *, + const uint8_t *, uint32_t); void (*PrintCtx)(struct MpmCtx_ *); void (*PrintThreadCtx)(struct MpmThreadCtx_ *); void (*RegisterUnittests)(void); @@ -186,17 +189,14 @@ void MpmInitCtx(MpmCtx *mpm_ctx, uint8_t matcher); void MpmInitThreadCtx(MpmThreadCtx *mpm_thread_ctx, uint16_t); void MpmDestroyThreadCtx(MpmThreadCtx *mpm_thread_ctx, const uint16_t matcher); -int MpmAddPatternCS(struct MpmCtx_ *mpm_ctx, uint8_t *pat, uint16_t patlen, - uint16_t offset, uint16_t depth, - uint32_t pid, SigIntId sid, uint8_t flags); -int MpmAddPatternCI(struct MpmCtx_ *mpm_ctx, uint8_t *pat, uint16_t patlen, - uint16_t offset, uint16_t depth, - uint32_t pid, SigIntId sid, uint8_t flags); +int MpmAddPatternCS(struct MpmCtx_ *mpm_ctx, uint8_t *pat, uint16_t patlen, uint16_t offset, + uint16_t depth, uint32_t pid, SigIntId sid, uint8_t flags); +int MpmAddPatternCI(struct MpmCtx_ *mpm_ctx, uint8_t *pat, uint16_t patlen, uint16_t offset, + uint16_t depth, uint32_t pid, SigIntId sid, uint8_t flags); void MpmFreePattern(MpmCtx *mpm_ctx, MpmPattern *p); -int MpmAddPattern(MpmCtx *mpm_ctx, uint8_t *pat, uint16_t patlen, - uint16_t offset, uint16_t depth, uint32_t pid, - SigIntId sid, uint8_t flags); +int MpmAddPattern(MpmCtx *mpm_ctx, uint8_t *pat, uint16_t patlen, uint16_t offset, uint16_t depth, + uint32_t pid, SigIntId sid, uint8_t flags); #endif /* __UTIL_MPM_H__ */ diff --git a/src/util-napatech.c b/src/util-napatech.c index affcd49cbb87..3fb451a893bb 100644 --- a/src/util-napatech.c +++ b/src/util-napatech.c @@ -41,13 +41,11 @@ * counters to track the number of flows programmed on * the adapter. */ -typedef struct FlowStatsCounters_ -{ +typedef struct FlowStatsCounters_ { uint16_t active_bypass_flows; uint16_t total_bypass_flows; } FlowStatsCounters; - static int bypass_supported; int NapatechIsBypassSupported(void) { @@ -114,7 +112,7 @@ int NapatechVerifyBypassSupport(void) NT_FlowOpenAttrInit(&attr); NT_FlowOpenAttrSetAdapterNo(&attr, adapter); - snprintf(flow_name, sizeof(flow_name), "Flow stream %d", adapter ); + snprintf(flow_name, sizeof(flow_name), "Flow stream %d", adapter); SCLogInfo("Opening flow programming stream: %s\n", flow_name); if ((status = NT_FlowOpen_Attr(&hFlowStream, flow_name, &attr)) != NT_SUCCESS) { SCLogWarning("Napatech bypass functionality not supported by the FPGA version on " @@ -130,7 +128,6 @@ int NapatechVerifyBypassSupport(void) return bypass_supported; } - /** * \brief Updates statistic counters for Napatech FlowStats * @@ -141,13 +138,8 @@ int NapatechVerifyBypassSupport(void) * \param clear_stats Indicates if statistics on the card should be reset to zero. * */ -static void UpdateFlowStats( - ThreadVars *tv, - NtInfoStream_t hInfo, - NtStatStream_t hstat_stream, - FlowStatsCounters flow_counters, - int clear_stats - ) +static void UpdateFlowStats(ThreadVars *tv, NtInfoStream_t hInfo, NtStatStream_t hstat_stream, + FlowStatsCounters flow_counters, int clear_stats) { NtStatistics_t hStat; int status; @@ -165,25 +157,22 @@ static void UpdateFlowStats( exit(1); } programed = hStat.u.flowData_v0.learnDone; - removed = hStat.u.flowData_v0.unlearnDone - + hStat.u.flowData_v0.automaticUnlearnDone - + hStat.u.flowData_v0.timeoutUnlearnDone; + removed = hStat.u.flowData_v0.unlearnDone + hStat.u.flowData_v0.automaticUnlearnDone + + hStat.u.flowData_v0.timeoutUnlearnDone; } - StatsSetUI64(tv, flow_counters.active_bypass_flows, programed - removed); - StatsSetUI64(tv, flow_counters.total_bypass_flows, programed); + StatsSetUI64(tv, flow_counters.active_bypass_flows, programed - removed); + StatsSetUI64(tv, flow_counters.total_bypass_flows, programed); } #endif /* NAPATECH_ENABLE_BYPASS */ - /*----------------------------------------------------------------------------- *----------------------------------------------------------------------------- * Statistics code *----------------------------------------------------------------------------- */ -typedef struct PacketCounters_ -{ +typedef struct PacketCounters_ { uint16_t pkts; uint16_t byte; uint16_t drop_pkts; @@ -216,11 +205,8 @@ enum CONFIG_SPECIFIER { * \param num_inst * */ -static uint16_t TestStreamConfig( - NtInfoStream_t hInfo, - NtStatStream_t hstat_stream, - NapatechStreamConfig stream_config[], - uint16_t num_inst) +static uint16_t TestStreamConfig(NtInfoStream_t hInfo, NtStatStream_t hstat_stream, + NapatechStreamConfig stream_config[], uint16_t num_inst) { uint16_t num_active = 0; @@ -229,11 +215,11 @@ static uint16_t TestStreamConfig( NtStatistics_t stat; // Stat handle. /* Check to see if it is an active stream */ - memset(&stat, 0, sizeof (NtStatistics_t)); + memset(&stat, 0, sizeof(NtStatistics_t)); /* Read usage data for the chosen stream ID */ stat.cmd = NT_STATISTICS_READ_CMD_USAGE_DATA_V0; - stat.u.usageData_v0.streamid = (uint8_t) stream_config[inst].stream_id; + stat.u.usageData_v0.streamid = (uint8_t)stream_config[inst].stream_id; if ((status = NT_StatRead(hstat_stream, &stat)) != NT_SUCCESS) { NAPATECH_ERROR(status); @@ -270,23 +256,15 @@ static uint16_t TestStreamConfig( * \return The number of active streams that were updated. * */ -static uint32_t UpdateStreamStats(ThreadVars *tv, - NtInfoStream_t hInfo, - NtStatStream_t hstat_stream, - uint16_t num_streams, - NapatechStreamConfig stream_config[], - PacketCounters total_counters, - PacketCounters dispatch_host, - PacketCounters dispatch_drop, - PacketCounters dispatch_fwd, - int is_inline, - int enable_stream_stats, - PacketCounters stream_counters[] - ) { - static uint64_t rxPktsStart[MAX_STREAMS] = {0}; - static uint64_t rxByteStart[MAX_STREAMS] = {0}; - static uint64_t dropPktStart[MAX_STREAMS] = {0}; - static uint64_t dropByteStart[MAX_STREAMS] = {0}; +static uint32_t UpdateStreamStats(ThreadVars *tv, NtInfoStream_t hInfo, NtStatStream_t hstat_stream, + uint16_t num_streams, NapatechStreamConfig stream_config[], PacketCounters total_counters, + PacketCounters dispatch_host, PacketCounters dispatch_drop, PacketCounters dispatch_fwd, + int is_inline, int enable_stream_stats, PacketCounters stream_counters[]) +{ + static uint64_t rxPktsStart[MAX_STREAMS] = { 0 }; + static uint64_t rxByteStart[MAX_STREAMS] = { 0 }; + static uint64_t dropPktStart[MAX_STREAMS] = { 0 }; + static uint64_t dropByteStart[MAX_STREAMS] = { 0 }; int status; NtInfo_t hStreamInfo; @@ -320,9 +298,9 @@ static uint32_t UpdateStreamStats(ThreadVars *tv, break; /* Read usage data for the chosen stream ID */ - memset(&hStat, 0, sizeof (NtStatistics_t)); + memset(&hStat, 0, sizeof(NtStatistics_t)); hStat.cmd = NT_STATISTICS_READ_CMD_USAGE_DATA_V0; - hStat.u.usageData_v0.streamid = (uint8_t) stream_config[inst_id].stream_id; + hStat.u.usageData_v0.streamid = (uint8_t)stream_config[inst_id].stream_id; if ((status = NT_StatRead(hstat_stream, &hStat)) != NT_SUCCESS) { NAPATECH_ERROR(status); @@ -336,12 +314,15 @@ static uint32_t UpdateStreamStats(ThreadVars *tv, uint64_t drop_pkts_total = 0; uint64_t drop_byte_total = 0; - for (uint32_t hbCount = 0; hbCount < hStat.u.usageData_v0.data.numHostBufferUsed; hbCount++) { + for (uint32_t hbCount = 0; hbCount < hStat.u.usageData_v0.data.numHostBufferUsed; + hbCount++) { if (unlikely(stream_config[inst_id].initialized == false)) { rxPktsStart[stream_id] += hStat.u.usageData_v0.data.hb[hbCount].stat.rx.frames; rxByteStart[stream_id] += hStat.u.usageData_v0.data.hb[hbCount].stat.rx.bytes; - dropPktStart[stream_id] += hStat.u.usageData_v0.data.hb[hbCount].stat.drop.frames; - dropByteStart[stream_id] += hStat.u.usageData_v0.data.hb[hbCount].stat.drop.bytes; + dropPktStart[stream_id] += + hStat.u.usageData_v0.data.hb[hbCount].stat.drop.frames; + dropByteStart[stream_id] += + hStat.u.usageData_v0.data.hb[hbCount].stat.drop.bytes; stream_config[inst_id].initialized = true; } else { rx_pkts_total += hStat.u.usageData_v0.data.hb[hbCount].stat.rx.frames; @@ -353,15 +334,20 @@ static uint32_t UpdateStreamStats(ThreadVars *tv, current_stats[stream_id].current_packets = rx_pkts_total - rxPktsStart[stream_id]; current_stats[stream_id].current_bytes = rx_byte_total - rxByteStart[stream_id]; - current_stats[stream_id].current_drop_packets = drop_pkts_total - dropPktStart[stream_id]; - current_stats[stream_id].current_drop_bytes = drop_byte_total - dropByteStart[stream_id]; + current_stats[stream_id].current_drop_packets = + drop_pkts_total - dropPktStart[stream_id]; + current_stats[stream_id].current_drop_bytes = + drop_byte_total - dropByteStart[stream_id]; } if (enable_stream_stats) { - StatsSetUI64(tv, stream_counters[inst_id].pkts, current_stats[stream_id].current_packets); + StatsSetUI64( + tv, stream_counters[inst_id].pkts, current_stats[stream_id].current_packets); StatsSetUI64(tv, stream_counters[inst_id].byte, current_stats[stream_id].current_bytes); - StatsSetUI64(tv, stream_counters[inst_id].drop_pkts, current_stats[stream_id].current_drop_packets); - StatsSetUI64(tv, stream_counters[inst_id].drop_byte, current_stats[stream_id].current_drop_bytes); + StatsSetUI64(tv, stream_counters[inst_id].drop_pkts, + current_stats[stream_id].current_drop_packets); + StatsSetUI64(tv, stream_counters[inst_id].drop_byte, + current_stats[stream_id].current_drop_bytes); } ++inst_id; @@ -378,7 +364,6 @@ static uint32_t UpdateStreamStats(ThreadVars *tv, total_stats.current_drop_bytes += current_stats[stream_id].current_drop_bytes; } - #ifndef NAPATECH_ENABLE_BYPASS StatsSetUI64(tv, total_counters.pkts, total_stats.current_packets); StatsSetUI64(tv, total_counters.byte, total_stats.current_bytes); @@ -393,7 +378,7 @@ static uint32_t UpdateStreamStats(ThreadVars *tv, total_stats.current_drop_bytes = 0; /* Read usage data for the chosen stream ID */ - memset(&hStat, 0, sizeof (NtStatistics_t)); + memset(&hStat, 0, sizeof(NtStatistics_t)); #ifdef NAPATECH_ENABLE_BYPASS hStat.cmd = NT_STATISTICS_READ_CMD_QUERY_V3; @@ -402,7 +387,7 @@ static uint32_t UpdateStreamStats(ThreadVars *tv, /* Older versions of the API have a different structure. */ hStat.cmd = NT_STATISTICS_READ_CMD_QUERY_V2; hStat.u.query_v2.clear = 0; -#endif /* !NAPATECH_ENABLE_BYPASS */ +#endif /* !NAPATECH_ENABLE_BYPASS */ if ((status = NT_StatRead(hstat_stream, &hStat)) != NT_SUCCESS) { if (status == NT_STATUS_TIMEOUT) { @@ -424,28 +409,36 @@ static uint32_t UpdateStreamStats(ThreadVars *tv, uint64_t total_dispatch_fwd_pkts = 0; uint64_t total_dispatch_fwd_byte = 0; - for (adapter = 0; adapter < NapatechGetNumAdapters(); ++adapter) { - total_dispatch_host_pkts += hStat.u.query_v3.data.adapter.aAdapters[adapter].color.aColor[0].pkts; - total_dispatch_host_byte += hStat.u.query_v3.data.adapter.aAdapters[adapter].color.aColor[0].octets; - - total_dispatch_drop_pkts += hStat.u.query_v3.data.adapter.aAdapters[adapter].color.aColor[1].pkts - + hStat.u.query_v3.data.adapter.aAdapters[adapter].color.aColor[3].pkts; - total_dispatch_drop_byte += hStat.u.query_v3.data.adapter.aAdapters[adapter].color.aColor[1].octets - + hStat.u.query_v3.data.adapter.aAdapters[adapter].color.aColor[3].octets; - - total_dispatch_fwd_pkts += hStat.u.query_v3.data.adapter.aAdapters[adapter].color.aColor[2].pkts - + hStat.u.query_v3.data.adapter.aAdapters[adapter].color.aColor[4].pkts; - total_dispatch_fwd_byte += hStat.u.query_v3.data.adapter.aAdapters[adapter].color.aColor[2].octets - + hStat.u.query_v3.data.adapter.aAdapters[adapter].color.aColor[4].octets; - - total_stats.current_packets += hStat.u.query_v3.data.adapter.aAdapters[adapter].color.aColor[0].pkts - + hStat.u.query_v3.data.adapter.aAdapters[adapter].color.aColor[1].pkts - + hStat.u.query_v3.data.adapter.aAdapters[adapter].color.aColor[2].pkts - + hStat.u.query_v3.data.adapter.aAdapters[adapter].color.aColor[3].pkts; - - total_stats.current_bytes = hStat.u.query_v3.data.adapter.aAdapters[adapter].color.aColor[0].octets - + hStat.u.query_v3.data.adapter.aAdapters[adapter].color.aColor[1].octets - + hStat.u.query_v3.data.adapter.aAdapters[adapter].color.aColor[2].octets; + for (adapter = 0; adapter < NapatechGetNumAdapters(); ++adapter) { + total_dispatch_host_pkts += + hStat.u.query_v3.data.adapter.aAdapters[adapter].color.aColor[0].pkts; + total_dispatch_host_byte += + hStat.u.query_v3.data.adapter.aAdapters[adapter].color.aColor[0].octets; + + total_dispatch_drop_pkts += + hStat.u.query_v3.data.adapter.aAdapters[adapter].color.aColor[1].pkts + + hStat.u.query_v3.data.adapter.aAdapters[adapter].color.aColor[3].pkts; + total_dispatch_drop_byte += + hStat.u.query_v3.data.adapter.aAdapters[adapter].color.aColor[1].octets + + hStat.u.query_v3.data.adapter.aAdapters[adapter].color.aColor[3].octets; + + total_dispatch_fwd_pkts += + hStat.u.query_v3.data.adapter.aAdapters[adapter].color.aColor[2].pkts + + hStat.u.query_v3.data.adapter.aAdapters[adapter].color.aColor[4].pkts; + total_dispatch_fwd_byte += + hStat.u.query_v3.data.adapter.aAdapters[adapter].color.aColor[2].octets + + hStat.u.query_v3.data.adapter.aAdapters[adapter].color.aColor[4].octets; + + total_stats.current_packets += + hStat.u.query_v3.data.adapter.aAdapters[adapter].color.aColor[0].pkts + + hStat.u.query_v3.data.adapter.aAdapters[adapter].color.aColor[1].pkts + + hStat.u.query_v3.data.adapter.aAdapters[adapter].color.aColor[2].pkts + + hStat.u.query_v3.data.adapter.aAdapters[adapter].color.aColor[3].pkts; + + total_stats.current_bytes = + hStat.u.query_v3.data.adapter.aAdapters[adapter].color.aColor[0].octets + + hStat.u.query_v3.data.adapter.aAdapters[adapter].color.aColor[1].octets + + hStat.u.query_v3.data.adapter.aAdapters[adapter].color.aColor[2].octets; } StatsSetUI64(tv, dispatch_host.pkts, total_dispatch_host_pkts); @@ -477,7 +470,7 @@ static uint32_t UpdateStreamStats(ThreadVars *tv, */ static void *NapatechStatsLoop(void *arg) { - ThreadVars *tv = (ThreadVars *) arg; + ThreadVars *tv = (ThreadVars *)arg; int status; NtInfoStream_t hInfo; @@ -510,12 +503,12 @@ static void *NapatechStatsLoop(void *arg) } NtStatistics_t hStat; - memset(&hStat, 0, sizeof (NtStatistics_t)); + memset(&hStat, 0, sizeof(NtStatistics_t)); #ifdef NAPATECH_ENABLE_BYPASS hStat.cmd = NT_STATISTICS_READ_CMD_QUERY_V3; hStat.u.query_v3.clear = 1; -#else /* NAPATECH_ENABLE_BYPASS */ +#else /* NAPATECH_ENABLE_BYPASS */ hStat.cmd = NT_STATISTICS_READ_CMD_QUERY_V2; hStat.u.query_v2.clear = 1; #endif /* !NAPATECH_ENABLE_BYPASS */ @@ -632,10 +625,9 @@ static void *NapatechStatsLoop(void *arg) } #endif /* NAPATECH_ENABLE_BYPASS */ - uint32_t num_active = UpdateStreamStats(tv, hInfo, hstat_stream, - stream_cnt, stream_config, total_counters, - dispatch_host, dispatch_drop, dispatch_fwd, - is_inline, enable_stream_stats, stream_counters); + uint32_t num_active = UpdateStreamStats(tv, hInfo, hstat_stream, stream_cnt, stream_config, + total_counters, dispatch_host, dispatch_drop, dispatch_fwd, is_inline, + enable_stream_stats, stream_counters); if (!NapatechIsAutoConfigEnabled() && (num_active < stream_cnt)) { SCLogInfo("num_active: %d, stream_cnt: %d", num_active, stream_cnt); @@ -650,10 +642,8 @@ static void *NapatechStatsLoop(void *arg) break; } - UpdateStreamStats(tv, hInfo, hstat_stream, - stream_cnt, stream_config, total_counters, - dispatch_host, dispatch_drop, dispatch_fwd, - is_inline, enable_stream_stats, + UpdateStreamStats(tv, hInfo, hstat_stream, stream_cnt, stream_config, total_counters, + dispatch_host, dispatch_drop, dispatch_fwd, is_inline, enable_stream_stats, stream_counters); #ifdef NAPATECH_ENABLE_BYPASS @@ -687,8 +677,8 @@ static void *NapatechStatsLoop(void *arg) } #define MAX_HOSTBUFFER 4 -#define MAX_STREAMS 256 -#define HB_HIGHWATER 2048 //1982 +#define MAX_STREAMS 256 +#define HB_HIGHWATER 2048 // 1982 /** * \brief Tests whether a particular stream_id is actively registered @@ -700,8 +690,8 @@ static void *NapatechStatsLoop(void *arg) * \return Bool indicating is the specified stream is registered. * */ -static bool RegisteredStream(uint16_t stream_id, uint16_t num_registered, - NapatechStreamConfig registered_streams[]) +static bool RegisteredStream( + uint16_t stream_id, uint16_t num_registered, NapatechStreamConfig registered_streams[]) { for (uint16_t reg_id = 0; reg_id < num_registered; ++reg_id) { if (stream_id == registered_streams[reg_id].stream_id) { @@ -725,8 +715,7 @@ static uint32_t CountWorkerThreads(void) if (root != NULL) { - TAILQ_FOREACH(affinity, &root->head, next) - { + TAILQ_FOREACH (affinity, &root->head, next) { if (strcmp(affinity->val, "decode-cpu-set") == 0 || strcmp(affinity->val, "stream-cpu-set") == 0 || strcmp(affinity->val, "reject-cpu-set") == 0 || @@ -740,8 +729,7 @@ static uint32_t CountWorkerThreads(void) enum CONFIG_SPECIFIER cpu_spec = CONFIG_SPECIFIER_UNDEFINED; - TAILQ_FOREACH(lnode, &node->head, next) - { + TAILQ_FOREACH (lnode, &node->head, next) { uint8_t start, end; char *end_str; if (strncmp(lnode->val, "all", 4) == 0) { @@ -758,13 +746,13 @@ static uint32_t CountWorkerThreads(void) } cpu_spec = CONFIG_SPECIFIER_RANGE; - - if (StringParseUint8(&start, 10, end_str - lnode->val, (const char *)lnode->val) < 0) { + if (StringParseUint8(&start, 10, end_str - lnode->val, + (const char *)lnode->val) < 0) { FatalError("Napatech invalid" " worker range start: '%s'", lnode->val); } - if (StringParseUint8(&end, 10, 0, (const char *) (end_str + 1)) < 0) { + if (StringParseUint8(&end, 10, 0, (const char *)(end_str + 1)) < 0) { FatalError("Napatech invalid" " worker range end: '%s'", (end_str != NULL) ? (const char *)(end_str + 1) : "Null"); @@ -800,7 +788,7 @@ static uint32_t CountWorkerThreads(void) * * \return the number of streams configured or -1 if an error occurred * - */ + */ int NapatechGetStreamConfig(NapatechStreamConfig stream_config[]) { int status; @@ -853,15 +841,15 @@ int NapatechGetStreamConfig(NapatechStreamConfig stream_config[]) * over it and continue until we get a streamID with a non-zero * count of the host-buffers. */ - memset(&hStat, 0, sizeof (NtStatistics_t)); + memset(&hStat, 0, sizeof(NtStatistics_t)); /* Read usage data for the chosen stream ID */ hStat.cmd = NT_STATISTICS_READ_CMD_USAGE_DATA_V0; - hStat.u.usageData_v0.streamid = (uint8_t) stream_id; + hStat.u.usageData_v0.streamid = (uint8_t)stream_id; if ((status = NT_StatRead(hstat_stream, &hStat)) != NT_SUCCESS) { /* Get the status code as text */ - NT_ExplainError(status, error_buffer, sizeof (error_buffer)); + NT_ExplainError(status, error_buffer, sizeof(error_buffer)); SCLogError("NT_StatRead() failed: %s\n", error_buffer); return -1; } @@ -899,8 +887,7 @@ int NapatechGetStreamConfig(NapatechStreamConfig stream_config[]) enum CONFIG_SPECIFIER stream_spec = CONFIG_SPECIFIER_UNDEFINED; instance_cnt = 0; - TAILQ_FOREACH(stream, &ntstreams->head, next) - { + TAILQ_FOREACH (stream, &ntstreams->head, next) { if (stream == NULL) { SCLogError("Couldn't Parse Stream Configuration"); @@ -915,13 +902,13 @@ int NapatechGetStreamConfig(NapatechStreamConfig stream_config[]) } stream_spec = CONFIG_SPECIFIER_RANGE; - if (StringParseUint8(&start, 10, end_str - stream->val, - (const char *)stream->val) < 0) { + if (StringParseUint8( + &start, 10, end_str - stream->val, (const char *)stream->val) < 0) { FatalError("Napatech invalid " "stream id start: '%s'", stream->val); } - if (StringParseUint8(&end, 10, 0, (const char *) (end_str + 1)) < 0) { + if (StringParseUint8(&end, 10, 0, (const char *)(end_str + 1)) < 0) { FatalError("Napatech invalid " "stream id end: '%s'", (end_str != NULL) ? (const char *)(end_str + 1) : "Null"); @@ -931,8 +918,8 @@ int NapatechGetStreamConfig(NapatechStreamConfig stream_config[]) FatalError("Napatech range and individual specifiers cannot be combined."); } stream_spec = CONFIG_SPECIFIER_INDIVIDUAL; - if (StringParseUint8(&stream_config[instance_cnt].stream_id, - 10, 0, (const char *)stream->val) < 0) { + if (StringParseUint8(&stream_config[instance_cnt].stream_id, 10, 0, + (const char *)stream->val) < 0) { FatalError("Napatech invalid " "stream id: '%s'", stream->val); @@ -948,12 +935,11 @@ int NapatechGetStreamConfig(NapatechStreamConfig stream_config[]) stream_config[instance_cnt].stream_id = stream_id; /* Check to see if it is an active stream */ - memset(&hStat, 0, sizeof (NtStatistics_t)); + memset(&hStat, 0, sizeof(NtStatistics_t)); /* Read usage data for the chosen stream ID */ hStat.cmd = NT_STATISTICS_READ_CMD_USAGE_DATA_V0; - hStat.u.usageData_v0.streamid = - (uint8_t) stream_config[instance_cnt].stream_id; + hStat.u.usageData_v0.streamid = (uint8_t)stream_config[instance_cnt].stream_id; if ((status = NT_StatRead(hstat_stream, &hStat)) != NT_SUCCESS) { NAPATECH_ERROR(status); @@ -983,7 +969,7 @@ int NapatechGetStreamConfig(NapatechStreamConfig stream_config[]) static void *NapatechBufMonitorLoop(void *arg) { - ThreadVars *tv = (ThreadVars *) arg; + ThreadVars *tv = (ThreadVars *)arg; NtInfo_t hStreamInfo; NtStatistics_t hStat; // Stat handle. @@ -994,14 +980,14 @@ static void *NapatechBufMonitorLoop(void *arg) const uint32_t alertInterval = 25; #ifndef NAPATECH_ENABLE_BYPASS - uint32_t OB_fill_level[MAX_STREAMS] = {0}; - uint32_t OB_alert_level[MAX_STREAMS] = {0}; - uint32_t ave_OB_fill_level[MAX_STREAMS] = {0}; + uint32_t OB_fill_level[MAX_STREAMS] = { 0 }; + uint32_t OB_alert_level[MAX_STREAMS] = { 0 }; + uint32_t ave_OB_fill_level[MAX_STREAMS] = { 0 }; #endif /* NAPATECH_ENABLE_BYPASS */ - uint32_t HB_fill_level[MAX_STREAMS] = {0}; - uint32_t HB_alert_level[MAX_STREAMS] = {0}; - uint32_t ave_HB_fill_level[MAX_STREAMS] = {0}; + uint32_t HB_fill_level[MAX_STREAMS] = { 0 }; + uint32_t HB_alert_level[MAX_STREAMS] = { 0 }; + uint32_t ave_HB_fill_level[MAX_STREAMS] = { 0 }; /* Open the info and Statistics */ if ((status = NT_InfoOpen(&hInfo, "InfoStream")) != NT_SUCCESS) { @@ -1044,7 +1030,7 @@ static void *NapatechBufMonitorLoop(void *arg) } char pktCntStr[4096]; - memset(pktCntStr, 0, sizeof (pktCntStr)); + memset(pktCntStr, 0, sizeof(pktCntStr)); uint32_t stream_id = 0; uint32_t stream_cnt = 0; @@ -1056,7 +1042,7 @@ static void *NapatechBufMonitorLoop(void *arg) /* Read usage data for the chosen stream ID */ hStat.cmd = NT_STATISTICS_READ_CMD_USAGE_DATA_V0; - hStat.u.usageData_v0.streamid = (uint8_t) stream_id; + hStat.u.usageData_v0.streamid = (uint8_t)stream_id; if ((status = NT_StatRead(hstat_stream, &hStat)) != NT_SUCCESS) { NAPATECH_ERROR(status); @@ -1077,24 +1063,25 @@ static void *NapatechBufMonitorLoop(void *arg) ave_HB_fill_level[stream_id] = 0; - for (uint32_t hb_count = 0; hb_count < hStat.u.usageData_v0.data.numHostBufferUsed; hb_count++) { + for (uint32_t hb_count = 0; hb_count < hStat.u.usageData_v0.data.numHostBufferUsed; + hb_count++) { #ifndef NAPATECH_ENABLE_BYPASS OB_fill_level[hb_count] = ((100 * hStat.u.usageData_v0.data.hb[hb_count].onboardBuffering.used) / - hStat.u.usageData_v0.data.hb[hb_count].onboardBuffering.size); + hStat.u.usageData_v0.data.hb[hb_count].onboardBuffering.size); if (OB_fill_level[hb_count] > 100) { OB_fill_level[hb_count] = 100; } #endif /* NAPATECH_ENABLE_BYPASS */ - uint32_t bufSize = hStat.u.usageData_v0.data.hb[hb_count].enQueuedAdapter / 1024 - + hStat.u.usageData_v0.data.hb[hb_count].deQueued / 1024 - + hStat.u.usageData_v0.data.hb[hb_count].enQueued / 1024 - - HB_HIGHWATER; + uint32_t bufSize = + hStat.u.usageData_v0.data.hb[hb_count].enQueuedAdapter / 1024 + + hStat.u.usageData_v0.data.hb[hb_count].deQueued / 1024 + + hStat.u.usageData_v0.data.hb[hb_count].enQueued / 1024 - HB_HIGHWATER; - HB_fill_level[hb_count] = (uint32_t) - ((100 * hStat.u.usageData_v0.data.hb[hb_count].deQueued / 1024) / + HB_fill_level[hb_count] = (uint32_t)( + (100 * hStat.u.usageData_v0.data.hb[hb_count].deQueued / 1024) / bufSize); #ifndef NAPATECH_ENABLE_BYPASS @@ -1113,22 +1100,26 @@ static void *NapatechBufMonitorLoop(void *arg) /* Host Buffer Fill Level warnings... */ if (ave_HB_fill_level[stream_id] >= (HB_alert_level[stream_id] + alertInterval)) { - while (ave_HB_fill_level[stream_id] >= HB_alert_level[stream_id] + alertInterval) { + while (ave_HB_fill_level[stream_id] >= + HB_alert_level[stream_id] + alertInterval) { HB_alert_level[stream_id] += alertInterval; } - SCLogPerf("nt%d - Increasing Host Buffer Fill Level : %4d%%", - stream_id, ave_HB_fill_level[stream_id] - 1); + SCLogPerf("nt%d - Increasing Host Buffer Fill Level : %4d%%", stream_id, + ave_HB_fill_level[stream_id] - 1); } if (HB_alert_level[stream_id] > 0) { - if ((ave_HB_fill_level[stream_id] <= (HB_alert_level[stream_id] - alertInterval))) { - SCLogPerf("nt%d - Decreasing Host Buffer Fill Level: %4d%%", - stream_id, ave_HB_fill_level[stream_id]); + if ((ave_HB_fill_level[stream_id] <= + (HB_alert_level[stream_id] - alertInterval))) { + SCLogPerf("nt%d - Decreasing Host Buffer Fill Level: %4d%%", stream_id, + ave_HB_fill_level[stream_id]); - while (ave_HB_fill_level[stream_id] <= (HB_alert_level[stream_id] - alertInterval)) { + while (ave_HB_fill_level[stream_id] <= + (HB_alert_level[stream_id] - alertInterval)) { if ((HB_alert_level[stream_id]) > 0) { HB_alert_level[stream_id] -= alertInterval; - } else break; + } else + break; } } } @@ -1136,23 +1127,26 @@ static void *NapatechBufMonitorLoop(void *arg) #ifndef NAPATECH_ENABLE_BYPASS /* On Board SDRAM Fill Level warnings... */ if (ave_OB_fill_level[stream_id] >= (OB_alert_level[stream_id] + alertInterval)) { - while (ave_OB_fill_level[stream_id] >= OB_alert_level[stream_id] + alertInterval) { + while (ave_OB_fill_level[stream_id] >= + OB_alert_level[stream_id] + alertInterval) { OB_alert_level[stream_id] += alertInterval; - } - SCLogPerf("nt%d - Increasing Adapter SDRAM Fill Level: %4d%%", - stream_id, ave_OB_fill_level[stream_id]); + SCLogPerf("nt%d - Increasing Adapter SDRAM Fill Level: %4d%%", stream_id, + ave_OB_fill_level[stream_id]); } if (OB_alert_level[stream_id] > 0) { - if ((ave_OB_fill_level[stream_id] <= (OB_alert_level[stream_id] - alertInterval))) { - SCLogPerf("nt%d - Decreasing Adapter SDRAM Fill Level : %4d%%", - stream_id, ave_OB_fill_level[stream_id]); + if ((ave_OB_fill_level[stream_id] <= + (OB_alert_level[stream_id] - alertInterval))) { + SCLogPerf("nt%d - Decreasing Adapter SDRAM Fill Level : %4d%%", stream_id, + ave_OB_fill_level[stream_id]); - while (ave_OB_fill_level[stream_id] <= (OB_alert_level[stream_id] - alertInterval)) { + while (ave_OB_fill_level[stream_id] <= + (OB_alert_level[stream_id] - alertInterval)) { if ((OB_alert_level[stream_id]) > 0) { OB_alert_level[stream_id] -= alertInterval; - } else break; + } else + break; } } } @@ -1181,14 +1175,11 @@ static void *NapatechBufMonitorLoop(void *arg) return NULL; } - void NapatechStartStats(void) { /* Creates the Statistic threads */ - ThreadVars *stats_tv = TmThreadCreate("NapatechStats", - NULL, NULL, - NULL, NULL, - "custom", NapatechStatsLoop, 0); + ThreadVars *stats_tv = + TmThreadCreate("NapatechStats", NULL, NULL, NULL, NULL, "custom", NapatechStatsLoop, 0); if (stats_tv == NULL) { FatalError("Error creating a thread for NapatechStats - Killing engine."); @@ -1204,10 +1195,8 @@ void NapatechStartStats(void) } #endif /* NAPATECH_ENABLE_BYPASS */ - ThreadVars *buf_monitor_tv = TmThreadCreate("NapatechBufMonitor", - NULL, NULL, - NULL, NULL, - "custom", NapatechBufMonitorLoop, 0); + ThreadVars *buf_monitor_tv = TmThreadCreate( + "NapatechBufMonitor", NULL, NULL, NULL, NULL, "custom", NapatechBufMonitorLoop, 0); if (buf_monitor_tv == NULL) { FatalError("Error creating a thread for NapatechBufMonitor - Killing engine."); @@ -1235,7 +1224,8 @@ bool NapatechSetupNuma(uint32_t stream, uint32_t numa) return false; } - if ((status = NT_NTPL(hconfig, ntpl_cmd, &ntpl_info, NT_NTPL_PARSER_VALIDATE_NORMAL)) == NT_SUCCESS) { + if ((status = NT_NTPL(hconfig, ntpl_cmd, &ntpl_info, NT_NTPL_PARSER_VALIDATE_NORMAL)) == + NT_SUCCESS) { status = ntpl_info.ntplId; } else { @@ -1267,8 +1257,8 @@ static uint32_t NapatechSetHashmode(void) return false; } - if ((status = NT_NTPL(hconfig, ntpl_cmd, &ntpl_info, - NT_NTPL_PARSER_VALIDATE_NORMAL)) == NT_SUCCESS) { + if ((status = NT_NTPL(hconfig, ntpl_cmd, &ntpl_info, NT_NTPL_PARSER_VALIDATE_NORMAL)) == + NT_SUCCESS) { filter_id = ntpl_info.ntplId; SCLogConfig("Napatech hashmode: %s ID: %d", hash_mode, status); } else { @@ -1294,12 +1284,11 @@ static uint32_t GetStreamNUMAs(uint32_t stream_id, int stream_numas[]) } char pktCntStr[4096]; - memset(pktCntStr, 0, sizeof (pktCntStr)); - + memset(pktCntStr, 0, sizeof(pktCntStr)); /* Read usage data for the chosen stream ID */ hStat.cmd = NT_STATISTICS_READ_CMD_USAGE_DATA_V0; - hStat.u.usageData_v0.streamid = (uint8_t) stream_id; + hStat.u.usageData_v0.streamid = (uint8_t)stream_id; if ((status = NT_StatRead(hstat_stream, &hStat)) != NT_SUCCESS) { NAPATECH_ERROR(status); @@ -1319,10 +1308,10 @@ static int NapatechSetFilter(NtConfigStream_t hconfig, char *ntpl_cmd) int local_filter_id = 0; NtNtplInfo_t ntpl_info; - if ((status = NT_NTPL(hconfig, ntpl_cmd, &ntpl_info, - NT_NTPL_PARSER_VALIDATE_NORMAL)) == NT_SUCCESS) { - SCLogConfig("NTPL filter assignment \"%s\" returned filter id %4d", - ntpl_cmd, local_filter_id); + if ((status = NT_NTPL(hconfig, ntpl_cmd, &ntpl_info, NT_NTPL_PARSER_VALIDATE_NORMAL)) == + NT_SUCCESS) { + SCLogConfig( + "NTPL filter assignment \"%s\" returned filter id %4d", ntpl_cmd, local_filter_id); } else { NAPATECH_NTPL_ERROR(ntpl_cmd, ntpl_info, status); exit(EXIT_FAILURE); @@ -1344,8 +1333,8 @@ uint32_t NapatechDeleteFilters(void) } snprintf(ntpl_cmd, 64, "delete = all"); - if ((status = NT_NTPL(hconfig, ntpl_cmd, &ntpl_info, - NT_NTPL_PARSER_VALIDATE_NORMAL)) == NT_SUCCESS) { + if ((status = NT_NTPL(hconfig, ntpl_cmd, &ntpl_info, NT_NTPL_PARSER_VALIDATE_NORMAL)) == + NT_SUCCESS) { status = ntpl_info.ntplId; } else { NAPATECH_NTPL_ERROR(ntpl_cmd, ntpl_info, status); @@ -1357,7 +1346,6 @@ uint32_t NapatechDeleteFilters(void) return status; } - uint32_t NapatechSetupTraffic(uint32_t first_stream, uint32_t last_stream) { #define PORTS_SPEC_SIZE 64 @@ -1396,13 +1384,11 @@ uint32_t NapatechSetupTraffic(uint32_t first_stream, uint32_t last_stream) } if (first_stream == last_stream) { - snprintf(ntpl_cmd, sizeof (ntpl_cmd), - "Setup[state=inactive] = StreamId == %d", - first_stream); + snprintf( + ntpl_cmd, sizeof(ntpl_cmd), "Setup[state=inactive] = StreamId == %d", first_stream); } else { - snprintf(ntpl_cmd, sizeof (ntpl_cmd), - "Setup[state=inactive] = StreamId == (%d..%d)", - first_stream, last_stream); + snprintf(ntpl_cmd, sizeof(ntpl_cmd), "Setup[state=inactive] = StreamId == (%d..%d)", + first_stream, last_stream); } NapatechSetFilter(hconfig, ntpl_cmd); @@ -1441,8 +1427,7 @@ uint32_t NapatechSetupTraffic(uint32_t first_stream, uint32_t last_stream) SCLogInfo("Listening on the following Napatech ports:"); } /* Build the NTPL command using values in the config file. */ - TAILQ_FOREACH(port, &ntports->head, next) - { + TAILQ_FOREACH (port, &ntports->head, next) { if (port == NULL) { FatalError("Couldn't Parse Port Configuration"); } @@ -1473,17 +1458,18 @@ uint32_t NapatechSetupTraffic(uint32_t first_stream, uint32_t last_stream) is_span_port[ports_spec.first[iteration]] = 1; if (strlen(span_ports) == 0) { - snprintf(span_ports, sizeof (span_ports), "%d", ports_spec.first[iteration]); + snprintf(span_ports, sizeof(span_ports), "%d", + ports_spec.first[iteration]); } else { char temp[16]; snprintf(temp, sizeof(temp), ",%d", ports_spec.first[iteration]); strlcat(span_ports, temp, sizeof(span_ports)); } - } } - if (NapatechGetAdapter(ports_spec.first[iteration]) != NapatechGetAdapter(ports_spec.first[iteration])) { + if (NapatechGetAdapter(ports_spec.first[iteration]) != + NapatechGetAdapter(ports_spec.first[iteration])) { SCLogError("Invalid napatech.ports specification in conf file."); SCLogError("Two ports on a segment must reside on the same adapter. port %d " "is on adapter %d, port %d is on adapter %d.", @@ -1498,21 +1484,25 @@ uint32_t NapatechSetupTraffic(uint32_t first_stream, uint32_t last_stream) if (ports_spec.first[iteration] == ports_spec.second[iteration]) { SCLogInfo(" span_port: %d", ports_spec.first[iteration]); } else { - SCLogInfo(" %s: %d - %d", is_inline ? "inline_ports" : "tap_ports", ports_spec.first[iteration], ports_spec.second[iteration]); + SCLogInfo(" %s: %d - %d", is_inline ? "inline_ports" : "tap_ports", + ports_spec.first[iteration], ports_spec.second[iteration]); } if (iteration == 0) { if (ports_spec.first[iteration] == ports_spec.second[iteration]) { - snprintf(ports_spec.str, sizeof (ports_spec.str), "%d", ports_spec.first[iteration]); + snprintf(ports_spec.str, sizeof(ports_spec.str), "%d", + ports_spec.first[iteration]); } else { - snprintf(ports_spec.str, sizeof (ports_spec.str), "%d,%d", ports_spec.first[iteration], ports_spec.second[iteration]); + snprintf(ports_spec.str, sizeof(ports_spec.str), "%d,%d", + ports_spec.first[iteration], ports_spec.second[iteration]); } } else { char temp[16]; if (ports_spec.first[iteration] == ports_spec.second[iteration]) { snprintf(temp, sizeof(temp), ",%d", ports_spec.first[iteration]); } else { - snprintf(temp, sizeof(temp), ",%d,%d", ports_spec.first[iteration], ports_spec.second[iteration]); + snprintf(temp, sizeof(temp), ",%d,%d", ports_spec.first[iteration], + ports_spec.second[iteration]); } strlcat(ports_spec.str, temp, sizeof(ports_spec.str)); } @@ -1530,7 +1520,7 @@ uint32_t NapatechSetupTraffic(uint32_t first_stream, uint32_t last_stream) stream_spec = CONFIG_SPECIFIER_RANGE; ports_spec.all = true; - snprintf(ports_spec.str, sizeof (ports_spec.str), "all"); + snprintf(ports_spec.str, sizeof(ports_spec.str), "all"); } else if (strchr(port->val, '-')) { /* check that the sting in the config file is correctly specified */ if (stream_spec != CONFIG_SPECIFIER_UNDEFINED) { @@ -1550,7 +1540,8 @@ uint32_t NapatechSetupTraffic(uint32_t first_stream, uint32_t last_stream) port->val); } - snprintf(ports_spec.str, sizeof (ports_spec.str), "(%d..%d)", ports_spec.first[iteration], ports_spec.second[iteration]); + snprintf(ports_spec.str, sizeof(ports_spec.str), "(%d..%d)", + ports_spec.first[iteration], ports_spec.second[iteration]); } else { /* check that the sting in the config file is correctly specified */ if (stream_spec == CONFIG_SPECIFIER_RANGE) { @@ -1566,10 +1557,10 @@ uint32_t NapatechSetupTraffic(uint32_t first_stream, uint32_t last_stream) /* Determine the ports to use on the NTPL assign statement*/ if (iteration == 0) { - snprintf(ports_spec.str, sizeof (ports_spec.str), "%s", port->val); + snprintf(ports_spec.str, sizeof(ports_spec.str), "%s", port->val); } else { - strlcat(ports_spec.str, ",", sizeof(ports_spec.str)); - strlcat(ports_spec.str, port->val, sizeof(ports_spec.str)); + strlcat(ports_spec.str, ",", sizeof(ports_spec.str)); + strlcat(ports_spec.str, port->val, sizeof(ports_spec.str)); } } } // if !NapatechUseHWBypass() @@ -1581,103 +1572,108 @@ uint32_t NapatechSetupTraffic(uint32_t first_stream, uint32_t last_stream) if (is_inline) { char inline_setup_cmd[512]; if (first_stream == last_stream) { - snprintf(inline_setup_cmd, sizeof (ntpl_cmd), - "Setup[TxDescriptor=Dyn;TxPorts=%s;RxCRC=False;TxPortPos=112;UseWL=True] = StreamId == %d", - ports_spec.str, first_stream); + snprintf(inline_setup_cmd, sizeof(ntpl_cmd), + "Setup[TxDescriptor=Dyn;TxPorts=%s;RxCRC=False;TxPortPos=112;UseWL=True] = " + "StreamId == %d", + ports_spec.str, first_stream); } else { - snprintf(inline_setup_cmd, sizeof (ntpl_cmd), - "Setup[TxDescriptor=Dyn;TxPorts=%s;RxCRC=False;TxPortPos=112;UseWL=True] = StreamId == (%d..%d)", - ports_spec.str, first_stream, last_stream); + snprintf(inline_setup_cmd, sizeof(ntpl_cmd), + "Setup[TxDescriptor=Dyn;TxPorts=%s;RxCRC=False;TxPortPos=112;UseWL=True] = " + "StreamId == (%d..%d)", + ports_spec.str, first_stream, last_stream); } NapatechSetFilter(hconfig, inline_setup_cmd); } /* Build the NTPL command */ - snprintf(ntpl_cmd, sizeof (ntpl_cmd), + snprintf(ntpl_cmd, sizeof(ntpl_cmd), "assign[priority=3;streamid=(%d..%d);colormask=0x10000000;" - "Descriptor=DYN3,length=24,colorbits=32,Offset0=Layer3Header[0],Offset1=Layer4Header[0]]= %s%s", + "Descriptor=DYN3,length=24,colorbits=32,Offset0=Layer3Header[0],Offset1=" + "Layer4Header[0]]= %s%s", first_stream, last_stream, ports_spec.all ? "" : "port==", ports_spec.str); NapatechSetFilter(hconfig, ntpl_cmd); - - snprintf(ntpl_cmd, sizeof (ntpl_cmd), + snprintf(ntpl_cmd, sizeof(ntpl_cmd), "assign[priority=2;streamid=(%d..%d);colormask=0x11000000;" - "Descriptor=DYN3,length=24,colorbits=32,Offset0=Layer3Header[0],Offset1=Layer4Header[0]" + "Descriptor=DYN3,length=24,colorbits=32,Offset0=Layer3Header[0],Offset1=" + "Layer4Header[0]" "]= %s%s and (Layer3Protocol==IPV4)", first_stream, last_stream, ports_spec.all ? "" : "port==", ports_spec.str); NapatechSetFilter(hconfig, ntpl_cmd); - - snprintf(ntpl_cmd, sizeof (ntpl_cmd), + snprintf(ntpl_cmd, sizeof(ntpl_cmd), "assign[priority=2;streamid=(%d..%d);colormask=0x14000000;" - "Descriptor=DYN3,length=24,colorbits=32,Offset0=Layer3Header[0],Offset1=Layer4Header[0]]= %s%s and (Layer3Protocol==IPV6)", + "Descriptor=DYN3,length=24,colorbits=32,Offset0=Layer3Header[0],Offset1=" + "Layer4Header[0]]= %s%s and (Layer3Protocol==IPV6)", first_stream, last_stream, ports_spec.all ? "" : "port==", ports_spec.str); NapatechSetFilter(hconfig, ntpl_cmd); - snprintf(ntpl_cmd, sizeof (ntpl_cmd), + snprintf(ntpl_cmd, sizeof(ntpl_cmd), "assign[priority=2;streamid=(%d..%d);colormask=0x10100000;" - "Descriptor=DYN3,length=24,colorbits=32,Offset0=Layer3Header[0],Offset1=Layer4Header[0]]= %s%s and (Layer4Protocol==TCP)", + "Descriptor=DYN3,length=24,colorbits=32,Offset0=Layer3Header[0],Offset1=" + "Layer4Header[0]]= %s%s and (Layer4Protocol==TCP)", first_stream, last_stream, ports_spec.all ? "" : "port==", ports_spec.str); NapatechSetFilter(hconfig, ntpl_cmd); - snprintf(ntpl_cmd, sizeof (ntpl_cmd), + snprintf(ntpl_cmd, sizeof(ntpl_cmd), "assign[priority=2;streamid=(%d..%d);colormask=0x10200000;" - "Descriptor=DYN3,length=24,colorbits=32,Offset0=Layer3Header[0],Offset1=Layer4Header[0]" + "Descriptor=DYN3,length=24,colorbits=32,Offset0=Layer3Header[0],Offset1=" + "Layer4Header[0]" "]= %s%s and (Layer4Protocol==UDP)", first_stream, last_stream, ports_spec.all ? "" : "port==", ports_spec.str); NapatechSetFilter(hconfig, ntpl_cmd); if (strlen(span_ports) > 0) { - snprintf(ntpl_cmd, sizeof (ntpl_cmd), + snprintf(ntpl_cmd, sizeof(ntpl_cmd), "assign[priority=2;streamid=(%d..%d);colormask=0x00001000;" - "Descriptor=DYN3,length=24,colorbits=32,Offset0=Layer3Header[0],Offset1=Layer4Header[0]" + "Descriptor=DYN3,length=24,colorbits=32,Offset0=Layer3Header[0],Offset1=" + "Layer4Header[0]" "]= port==%s", first_stream, last_stream, span_ports); NapatechSetFilter(hconfig, ntpl_cmd); } - snprintf(ntpl_cmd, sizeof (ntpl_cmd), - "KeyType[name=KT%u]={sw_32_32,sw_16_16}", + snprintf(ntpl_cmd, sizeof(ntpl_cmd), "KeyType[name=KT%u]={sw_32_32,sw_16_16}", NAPATECH_KEYTYPE_IPV4); NapatechSetFilter(hconfig, ntpl_cmd); - snprintf(ntpl_cmd, sizeof (ntpl_cmd), - "KeyDef[name=KDEF%u;KeyType=KT%u;ipprotocolfield=OUTER]=(Layer3Header[12]/32/32,Layer4Header[0]/16/16)", + snprintf(ntpl_cmd, sizeof(ntpl_cmd), + "KeyDef[name=KDEF%u;KeyType=KT%u;ipprotocolfield=OUTER]=(Layer3Header[12]/32/" + "32,Layer4Header[0]/16/16)", NAPATECH_KEYTYPE_IPV4, NAPATECH_KEYTYPE_IPV4); NapatechSetFilter(hconfig, ntpl_cmd); - snprintf(ntpl_cmd, sizeof (ntpl_cmd), - "KeyType[name=KT%u]={32,32,16,16}", + snprintf(ntpl_cmd, sizeof(ntpl_cmd), "KeyType[name=KT%u]={32,32,16,16}", NAPATECH_KEYTYPE_IPV4_SPAN); NapatechSetFilter(hconfig, ntpl_cmd); - snprintf(ntpl_cmd, sizeof (ntpl_cmd), - "KeyDef[name=KDEF%u;KeyType=KT%u;ipprotocolfield=OUTER;keysort=sorted]=(Layer3Header[12]/32,Layer3Header[16]/32,Layer4Header[0]/16,Layer4Header[2]/16)", + snprintf(ntpl_cmd, sizeof(ntpl_cmd), + "KeyDef[name=KDEF%u;KeyType=KT%u;ipprotocolfield=OUTER;keysort=sorted]=(" + "Layer3Header[12]/32,Layer3Header[16]/32,Layer4Header[0]/16,Layer4Header[2]/16)", NAPATECH_KEYTYPE_IPV4_SPAN, NAPATECH_KEYTYPE_IPV4_SPAN); NapatechSetFilter(hconfig, ntpl_cmd); /* IPv6 5tuple for inline and tap ports */ - snprintf(ntpl_cmd, sizeof (ntpl_cmd), - "KeyType[name=KT%u]={sw_128_128,sw_16_16}", + snprintf(ntpl_cmd, sizeof(ntpl_cmd), "KeyType[name=KT%u]={sw_128_128,sw_16_16}", NAPATECH_KEYTYPE_IPV6); NapatechSetFilter(hconfig, ntpl_cmd); - snprintf(ntpl_cmd, sizeof (ntpl_cmd), - "KeyDef[name=KDEF%u;KeyType=KT%u;ipprotocolfield=OUTER]=(Layer3Header[8]/128/128,Layer4Header[0]/16/16)", + snprintf(ntpl_cmd, sizeof(ntpl_cmd), + "KeyDef[name=KDEF%u;KeyType=KT%u;ipprotocolfield=OUTER]=(Layer3Header[8]/128/" + "128,Layer4Header[0]/16/16)", NAPATECH_KEYTYPE_IPV6, NAPATECH_KEYTYPE_IPV6); NapatechSetFilter(hconfig, ntpl_cmd); /* IPv6 5tuple for SPAN Ports */ - snprintf(ntpl_cmd, sizeof (ntpl_cmd), - "KeyType[name=KT%u]={128,128,16,16}", + snprintf(ntpl_cmd, sizeof(ntpl_cmd), "KeyType[name=KT%u]={128,128,16,16}", NAPATECH_KEYTYPE_IPV6_SPAN); NapatechSetFilter(hconfig, ntpl_cmd); - snprintf(ntpl_cmd, sizeof (ntpl_cmd), - "KeyDef[name=KDEF%u;KeyType=KT%u;ipprotocolfield=OUTER;keysort=sorted]=(Layer3Header[8]/128,Layer3Header[24]/128,Layer4Header[0]/16,Layer4Header[2]/16)", + snprintf(ntpl_cmd, sizeof(ntpl_cmd), + "KeyDef[name=KDEF%u;KeyType=KT%u;ipprotocolfield=OUTER;keysort=sorted]=(" + "Layer3Header[8]/128,Layer3Header[24]/128,Layer4Header[0]/16,Layer4Header[2]/16)", NAPATECH_KEYTYPE_IPV6_SPAN, NAPATECH_KEYTYPE_IPV6_SPAN); NapatechSetFilter(hconfig, ntpl_cmd); - int pair; char ports_ntpl_a[64]; char ports_ntpl_b[64]; @@ -1688,43 +1684,42 @@ uint32_t NapatechSetupTraffic(uint32_t first_stream, uint32_t last_stream) char port_str[8]; if (!is_span_port[ports_spec.first[pair]]) { - snprintf(port_str, sizeof(port_str), "%s%u ", strlen(ports_ntpl_a) == 0 ? "" : ",", ports_spec.first[pair]); + snprintf(port_str, sizeof(port_str), "%s%u ", strlen(ports_ntpl_a) == 0 ? "" : ",", + ports_spec.first[pair]); strlcat(ports_ntpl_a, port_str, sizeof(ports_ntpl_a)); - snprintf(port_str, sizeof(port_str), "%s%u ", strlen(ports_ntpl_b) == 0 ? "" : ",", ports_spec.second[pair]); + snprintf(port_str, sizeof(port_str), "%s%u ", strlen(ports_ntpl_b) == 0 ? "" : ",", + ports_spec.second[pair]); strlcat(ports_ntpl_b, port_str, sizeof(ports_ntpl_b)); } } if (strlen(ports_ntpl_a) > 0) { /* This is the assign for dropping upstream traffic */ - snprintf(ntpl_cmd, sizeof (ntpl_cmd), - "assign[priority=1;streamid=drop;colormask=0x1]=(Layer3Protocol==IPV4)and(port == %s)and(Key(KDEF%u,KeyID=%u)==%u)", - ports_ntpl_a, - NAPATECH_KEYTYPE_IPV4, - NAPATECH_KEYTYPE_IPV4, + snprintf(ntpl_cmd, sizeof(ntpl_cmd), + "assign[priority=1;streamid=drop;colormask=0x1]=(Layer3Protocol==IPV4)and(port " + "== %s)and(Key(KDEF%u,KeyID=%u)==%u)", + ports_ntpl_a, NAPATECH_KEYTYPE_IPV4, NAPATECH_KEYTYPE_IPV4, NAPATECH_FLOWTYPE_DROP); NapatechSetFilter(hconfig, ntpl_cmd); } if (strlen(ports_ntpl_b) > 0) { /* This is the assign for dropping downstream traffic */ - snprintf(ntpl_cmd, sizeof (ntpl_cmd), - "assign[priority=1;streamid=drop;colormask=0x1]=(Layer3Protocol==IPV4)and(port == %s)and(Key(KDEF%u,KeyID=%u,fieldaction=swap)==%u)", - ports_ntpl_b, //ports_spec.str, - NAPATECH_KEYTYPE_IPV4, - NAPATECH_KEYTYPE_IPV4, - NAPATECH_FLOWTYPE_DROP); + snprintf(ntpl_cmd, sizeof(ntpl_cmd), + "assign[priority=1;streamid=drop;colormask=0x1]=(Layer3Protocol==IPV4)and(port " + "== %s)and(Key(KDEF%u,KeyID=%u,fieldaction=swap)==%u)", + ports_ntpl_b, // ports_spec.str, + NAPATECH_KEYTYPE_IPV4, NAPATECH_KEYTYPE_IPV4, NAPATECH_FLOWTYPE_DROP); NapatechSetFilter(hconfig, ntpl_cmd); } if (strlen(span_ports) > 0) { /* This is the assign for dropping SPAN Port traffic */ - snprintf(ntpl_cmd, sizeof (ntpl_cmd), - "assign[priority=1;streamid=drop;colormask=0x1]=(Layer3Protocol==IPV4)and(port == %s)and(Key(KDEF%u,KeyID=%u)==%u)", - span_ports, - NAPATECH_KEYTYPE_IPV4_SPAN, - NAPATECH_KEYTYPE_IPV4_SPAN, + snprintf(ntpl_cmd, sizeof(ntpl_cmd), + "assign[priority=1;streamid=drop;colormask=0x1]=(Layer3Protocol==IPV4)and(port " + "== %s)and(Key(KDEF%u,KeyID=%u)==%u)", + span_ports, NAPATECH_KEYTYPE_IPV4_SPAN, NAPATECH_KEYTYPE_IPV4_SPAN, NAPATECH_FLOWTYPE_DROP); NapatechSetFilter(hconfig, ntpl_cmd); } @@ -1732,78 +1727,69 @@ uint32_t NapatechSetupTraffic(uint32_t first_stream, uint32_t last_stream) if (is_inline) { for (pair = 0; pair < iteration; ++pair) { /* This is the assignment for forwarding traffic */ - snprintf(ntpl_cmd, sizeof (ntpl_cmd), - "assign[priority=1;streamid=drop;DestinationPort=%d;colormask=0x2]=(Layer3Protocol==IPV4)and(port == %d)and(Key(KDEF%u,KeyID=%u)==%u)", - ports_spec.second[pair], - ports_spec.first[pair], - NAPATECH_KEYTYPE_IPV4, - NAPATECH_KEYTYPE_IPV4, - NAPATECH_FLOWTYPE_PASS); + snprintf(ntpl_cmd, sizeof(ntpl_cmd), + "assign[priority=1;streamid=drop;DestinationPort=%d;colormask=0x2]=(" + "Layer3Protocol==IPV4)and(port == %d)and(Key(KDEF%u,KeyID=%u)==%u)", + ports_spec.second[pair], ports_spec.first[pair], NAPATECH_KEYTYPE_IPV4, + NAPATECH_KEYTYPE_IPV4, NAPATECH_FLOWTYPE_PASS); NapatechSetFilter(hconfig, ntpl_cmd); - snprintf(ntpl_cmd, sizeof (ntpl_cmd), - "assign[priority=1;streamid=drop;DestinationPort=%d;colormask=0x2]=(Layer3Protocol==IPV4)and(port == %d)and(Key(KDEF%u,KeyID=%u,fieldaction=swap)==%u)", - ports_spec.first[pair], - ports_spec.second[pair], - NAPATECH_KEYTYPE_IPV4, - NAPATECH_KEYTYPE_IPV4, - NAPATECH_FLOWTYPE_PASS); + snprintf(ntpl_cmd, sizeof(ntpl_cmd), + "assign[priority=1;streamid=drop;DestinationPort=%d;colormask=0x2]=(" + "Layer3Protocol==IPV4)and(port == " + "%d)and(Key(KDEF%u,KeyID=%u,fieldaction=swap)==%u)", + ports_spec.first[pair], ports_spec.second[pair], NAPATECH_KEYTYPE_IPV4, + NAPATECH_KEYTYPE_IPV4, NAPATECH_FLOWTYPE_PASS); NapatechSetFilter(hconfig, ntpl_cmd); } } if (strlen(ports_ntpl_a) > 0) { /* This is the assign for dropping upstream traffic */ - snprintf(ntpl_cmd, sizeof (ntpl_cmd), - "assign[priority=1;streamid=drop;colormask=0x1]=(Layer3Protocol==IPV6)and(port == %s)and(Key(KDEF%u,KeyID=%u)==%u)", - ports_ntpl_a, - NAPATECH_KEYTYPE_IPV6, - NAPATECH_KEYTYPE_IPV6, + snprintf(ntpl_cmd, sizeof(ntpl_cmd), + "assign[priority=1;streamid=drop;colormask=0x1]=(Layer3Protocol==IPV6)and(port " + "== %s)and(Key(KDEF%u,KeyID=%u)==%u)", + ports_ntpl_a, NAPATECH_KEYTYPE_IPV6, NAPATECH_KEYTYPE_IPV6, NAPATECH_FLOWTYPE_DROP); NapatechSetFilter(hconfig, ntpl_cmd); } if (strlen(ports_ntpl_b) > 0) { /* This is the assign for dropping downstream traffic */ - snprintf(ntpl_cmd, sizeof (ntpl_cmd), - "assign[priority=1;streamid=drop;colormask=0x1]=(Layer3Protocol==IPV6)and(port == %s)and(Key(KDEF%u,KeyID=%u,fieldaction=swap)==%u)", - ports_ntpl_b, //ports_spec.str, - NAPATECH_KEYTYPE_IPV6, - NAPATECH_KEYTYPE_IPV6, - NAPATECH_FLOWTYPE_DROP); + snprintf(ntpl_cmd, sizeof(ntpl_cmd), + "assign[priority=1;streamid=drop;colormask=0x1]=(Layer3Protocol==IPV6)and(port " + "== %s)and(Key(KDEF%u,KeyID=%u,fieldaction=swap)==%u)", + ports_ntpl_b, // ports_spec.str, + NAPATECH_KEYTYPE_IPV6, NAPATECH_KEYTYPE_IPV6, NAPATECH_FLOWTYPE_DROP); NapatechSetFilter(hconfig, ntpl_cmd); } if (strlen(span_ports) > 0) { /* This is the assign for dropping SPAN Port traffic */ - snprintf(ntpl_cmd, sizeof (ntpl_cmd), - "assign[priority=1;streamid=drop;colormask=0x1]=(Layer3Protocol==IPV6)and(port == %s)and(Key(KDEF%u,KeyID=%u)==%u)", - span_ports, - NAPATECH_KEYTYPE_IPV6_SPAN, - NAPATECH_KEYTYPE_IPV6_SPAN, + snprintf(ntpl_cmd, sizeof(ntpl_cmd), + "assign[priority=1;streamid=drop;colormask=0x1]=(Layer3Protocol==IPV6)and(port " + "== %s)and(Key(KDEF%u,KeyID=%u)==%u)", + span_ports, NAPATECH_KEYTYPE_IPV6_SPAN, NAPATECH_KEYTYPE_IPV6_SPAN, NAPATECH_FLOWTYPE_DROP); NapatechSetFilter(hconfig, ntpl_cmd); } if (is_inline) { for (pair = 0; pair < iteration; ++pair) { - snprintf(ntpl_cmd, sizeof (ntpl_cmd), - "assign[priority=1;streamid=drop;DestinationPort=%d;colormask=0x4]=(Layer3Protocol==IPV6)and(port==%d)and(Key(KDEF%u,KeyID=%u)==%u)", - ports_spec.second[pair], - ports_spec.first[pair], - NAPATECH_KEYTYPE_IPV6, - NAPATECH_KEYTYPE_IPV6, - NAPATECH_FLOWTYPE_PASS); - NapatechSetFilter(hconfig, ntpl_cmd); - - snprintf(ntpl_cmd, sizeof (ntpl_cmd), - "assign[priority=1;streamid=drop;DestinationPort=%d;colormask=0x4]=(Layer3Protocol==IPV6)and(port==%d)and(Key(KDEF%u,KeyID=%u,fieldaction=swap)==%u)", - ports_spec.first[pair], - ports_spec.second[pair], - NAPATECH_KEYTYPE_IPV6, - NAPATECH_KEYTYPE_IPV6, - NAPATECH_FLOWTYPE_PASS); - NapatechSetFilter(hconfig, ntpl_cmd); + snprintf(ntpl_cmd, sizeof(ntpl_cmd), + "assign[priority=1;streamid=drop;DestinationPort=%d;colormask=0x4]=(" + "Layer3Protocol==IPV6)and(port==%d)and(Key(KDEF%u,KeyID=%u)==%u)", + ports_spec.second[pair], ports_spec.first[pair], NAPATECH_KEYTYPE_IPV6, + NAPATECH_KEYTYPE_IPV6, NAPATECH_FLOWTYPE_PASS); + NapatechSetFilter(hconfig, ntpl_cmd); + + snprintf(ntpl_cmd, sizeof(ntpl_cmd), + "assign[priority=1;streamid=drop;DestinationPort=%d;colormask=0x4]=(" + "Layer3Protocol==IPV6)and(port==%d)and(Key(KDEF%u,KeyID=%u,fieldaction=" + "swap)==%u)", + ports_spec.first[pair], ports_spec.second[pair], NAPATECH_KEYTYPE_IPV6, + NAPATECH_KEYTYPE_IPV6, NAPATECH_FLOWTYPE_PASS); + NapatechSetFilter(hconfig, ntpl_cmd); } } } else { @@ -1811,16 +1797,16 @@ uint32_t NapatechSetupTraffic(uint32_t first_stream, uint32_t last_stream) FatalError("Napatech Inline operation not supported by this FPGA version."); } - if (NapatechIsAutoConfigEnabled()){ - snprintf(ntpl_cmd, sizeof (ntpl_cmd), "assign[streamid=(%d..%d);colormask=0x0] = %s%s", + if (NapatechIsAutoConfigEnabled()) { + snprintf(ntpl_cmd, sizeof(ntpl_cmd), "assign[streamid=(%d..%d);colormask=0x0] = %s%s", first_stream, last_stream, ports_spec.all ? "" : "port==", ports_spec.str); NapatechSetFilter(hconfig, ntpl_cmd); } } #else /* NAPATECH_ENABLE_BYPASS */ - snprintf(ntpl_cmd, sizeof (ntpl_cmd), "assign[streamid=(%d..%d)] = %s%s", - first_stream, last_stream, ports_spec.all ? "" : "port==", ports_spec.str); + snprintf(ntpl_cmd, sizeof(ntpl_cmd), "assign[streamid=(%d..%d)] = %s%s", first_stream, + last_stream, ports_spec.all ? "" : "port==", ports_spec.str); NapatechSetFilter(hconfig, ntpl_cmd); #endif /* !NAPATECH_ENABLE_BYPASS */ @@ -1845,13 +1831,10 @@ uint32_t NapatechSetupTraffic(uint32_t first_stream, uint32_t last_stream) } if (first_stream == last_stream) { - snprintf(ntpl_cmd, sizeof (ntpl_cmd), - "Setup[state=active] = StreamId == %d", - first_stream); + snprintf(ntpl_cmd, sizeof(ntpl_cmd), "Setup[state=active] = StreamId == %d", first_stream); } else { - snprintf(ntpl_cmd, sizeof (ntpl_cmd), - "Setup[state=active] = StreamId == (%d..%d)", - first_stream, last_stream); + snprintf(ntpl_cmd, sizeof(ntpl_cmd), "Setup[state=active] = StreamId == (%d..%d)", + first_stream, last_stream); } NapatechSetFilter(hconfig, ntpl_cmd); diff --git a/src/util-napatech.h b/src/util-napatech.h index 45d4ddf6789d..9b0a20135223 100644 --- a/src/util-napatech.h +++ b/src/util-napatech.h @@ -26,8 +26,7 @@ #ifdef HAVE_NAPATECH #include -typedef struct NapatechPacketVars_ -{ +typedef struct NapatechPacketVars_ { uint64_t stream_id; NtNetBuf_t nt_packet_buf; NtNetStreamRx_t rx_stream; @@ -39,15 +38,13 @@ typedef struct NapatechPacketVars_ #endif } NapatechPacketVars; -typedef struct NapatechStreamConfig_ -{ +typedef struct NapatechStreamConfig_ { uint8_t stream_id; bool is_active; bool initialized; } NapatechStreamConfig; -typedef struct NapatechCurrentStats_ -{ +typedef struct NapatechCurrentStats_ { uint64_t current_packets; uint64_t current_bytes; uint64_t current_drop_packets; @@ -55,10 +52,10 @@ typedef struct NapatechCurrentStats_ } NapatechCurrentStats; #define MAX_HOSTBUFFER 4 -#define MAX_STREAMS 256 -#define MAX_PORTS 80 -#define MAX_ADAPTERS 8 -#define HB_HIGHWATER 2048 //1982 +#define MAX_STREAMS 256 +#define MAX_PORTS 80 +#define MAX_ADAPTERS 8 +#define HB_HIGHWATER 2048 // 1982 extern void NapatechStartStats(void); @@ -85,13 +82,13 @@ extern void NapatechStartStats(void); // #define ENABLE_NT_DEBUG #ifdef ENABLE_NT_DEBUG - void NapatechPrintIP(uint32_t address); +void NapatechPrintIP(uint32_t address); - #define NAPATECH_DEBUG(...) printf(__VA_ARGS__) - #define NAPATECH_PRINTIP(a) NapatechPrintIP(uint32_t address) +#define NAPATECH_DEBUG(...) printf(__VA_ARGS__) +#define NAPATECH_PRINTIP(a) NapatechPrintIP(uint32_t address) #else - #define NAPATECH_DEBUG(...) - #define NAPATECH_PRINTIP(a) +#define NAPATECH_DEBUG(...) +#define NAPATECH_PRINTIP(a) #endif NapatechCurrentStats NapatechGetCurrentStats(uint16_t id); @@ -103,17 +100,16 @@ uint32_t NapatechDeleteFilters(void); #ifdef NAPATECH_ENABLE_BYPASS /* */ -#define NAPATECH_KEYTYPE_IPV4 3 +#define NAPATECH_KEYTYPE_IPV4 3 #define NAPATECH_KEYTYPE_IPV4_SPAN 4 -#define NAPATECH_KEYTYPE_IPV6 5 +#define NAPATECH_KEYTYPE_IPV6 5 #define NAPATECH_KEYTYPE_IPV6_SPAN 6 -#define NAPATECH_FLOWTYPE_DROP 7 -#define NAPATECH_FLOWTYPE_PASS 8 +#define NAPATECH_FLOWTYPE_DROP 7 +#define NAPATECH_FLOWTYPE_PASS 8 int NapatechVerifyBypassSupport(void); int NapatechGetNumAdapters(void); - int NapatechIsBypassSupported(void); #endif /* NAPATECH_ENABLE_BYPASS */ diff --git a/src/util-optimize.h b/src/util-optimize.h index bde35ddd810e..5df31fcc4ee5 100644 --- a/src/util-optimize.h +++ b/src/util-optimize.h @@ -24,7 +24,7 @@ * \author Victor Julien */ -#if CPPCHECK==1 +#if CPPCHECK == 1 #define likely #define unlikely #else @@ -40,7 +40,7 @@ * * C Compiler memory barrier */ -#define cc_barrier() __asm__ __volatile__("": : :"memory") +#define cc_barrier() __asm__ __volatile__("" : : : "memory") /** from http://gcc.gnu.org/onlinedocs/gcc-4.1.2/gcc/Atomic-Builtins.html * @@ -49,4 +49,3 @@ #define hw_barrier() __sync_synchronize() #endif /* __UTIL_OPTIMIZE_H__ */ - diff --git a/src/util-pages.c b/src/util-pages.c index 170170b1933d..9ddc3d553cc2 100644 --- a/src/util-pages.c +++ b/src/util-pages.c @@ -44,9 +44,9 @@ int PageSupportsRWX(void) { int retval = 1; void *ptr; - ptr = mmap(0, getpagesize(), PROT_READ|PROT_WRITE, MAP_ANON|MAP_SHARED, -1, 0); + ptr = mmap(0, getpagesize(), PROT_READ | PROT_WRITE, MAP_ANON | MAP_SHARED, -1, 0); if (ptr != MAP_FAILED) { - if (mprotect(ptr, getpagesize(), PROT_READ|PROT_WRITE|PROT_EXEC) == -1) { + if (mprotect(ptr, getpagesize(), PROT_READ | PROT_WRITE | PROT_EXEC) == -1) { SCLogConfig("RWX pages denied by OS"); retval = 0; } @@ -55,4 +55,3 @@ int PageSupportsRWX(void) return retval; } #endif /* HAVE_PAGESUPPORTSRWX_AS_MACRO */ - diff --git a/src/util-pages.h b/src/util-pages.h index 037639147737..3ca1490de036 100644 --- a/src/util-pages.h +++ b/src/util-pages.h @@ -28,17 +28,17 @@ #include "suricata-common.h" #ifdef __OpenBSD__ - /* OpenBSD won't allow for this test: - * "suricata(...): mprotect W^X violation" */ - #define PageSupportsRWX() 0 - #define HAVE_PAGESUPPORTSRWX_AS_MACRO 1 +/* OpenBSD won't allow for this test: + * "suricata(...): mprotect W^X violation" */ +#define PageSupportsRWX() 0 +#define HAVE_PAGESUPPORTSRWX_AS_MACRO 1 #else - #ifndef HAVE_SYS_MMAN_H - #define PageSupportsRWX() 1 - #define HAVE_PAGESUPPORTSRWX_AS_MACRO 1 - #else - int PageSupportsRWX(void); - #endif /* HAVE_SYS_MMAN_H */ +#ifndef HAVE_SYS_MMAN_H +#define PageSupportsRWX() 1 +#define HAVE_PAGESUPPORTSRWX_AS_MACRO 1 +#else +int PageSupportsRWX(void); +#endif /* HAVE_SYS_MMAN_H */ #endif #endif /* __UTIL_PAGES_H__ */ diff --git a/src/util-path.c b/src/util-path.c index 34c4cc75ca79..8d877a0d3b39 100644 --- a/src/util-path.c +++ b/src/util-path.c @@ -236,9 +236,8 @@ bool SCPathExists(const char *path) bool SCIsRegularDirectory(const struct dirent *const dir_entry) { #ifndef OS_WIN32 - if ((dir_entry->d_type == DT_DIR) && - (strcmp(dir_entry->d_name, ".") != 0) && - (strcmp(dir_entry->d_name, "..") != 0)) { + if ((dir_entry->d_type == DT_DIR) && (strcmp(dir_entry->d_name, ".") != 0) && + (strcmp(dir_entry->d_name, "..") != 0)) { return true; } #endif diff --git a/src/util-path.h b/src/util-path.h index 141b6fc2472e..da483c70942b 100644 --- a/src/util-path.h +++ b/src/util-path.h @@ -42,9 +42,9 @@ typedef struct stat SCStat; #endif #ifndef HAVE_NON_POSIX_MKDIR - #define SCMkDir(a, b) mkdir(a, b) +#define SCMkDir(a, b) mkdir(a, b) #else - #define SCMkDir(a, b) mkdir(a) +#define SCMkDir(a, b) mkdir(a) #endif int PathIsAbsolute(const char *); diff --git a/src/util-pidfile.c b/src/util-pidfile.c index 1cbae0eb7a5d..1ecfb7e119ce 100644 --- a/src/util-pidfile.c +++ b/src/util-pidfile.c @@ -46,7 +46,7 @@ int SCPidfileCreate(const char *pidfile) int pidfd = 0; char val[16]; - size_t len = snprintf(val, sizeof(val), "%"PRIuMAX"\n", (uintmax_t)getpid()); + size_t len = snprintf(val, sizeof(val), "%" PRIuMAX "\n", (uintmax_t)getpid()); if (len <= 0) { SCLogError("Pid error (%s)", strerror(errno)); SCReturnInt(-1); diff --git a/src/util-pidfile.h b/src/util-pidfile.h index ef071f4e8424..9c133c86a989 100644 --- a/src/util-pidfile.h +++ b/src/util-pidfile.h @@ -30,4 +30,3 @@ void SCPidfileRemove(const char *); int SCPidfileTestRunning(const char *pid_filename); #endif /* __UTIL_PID_H__ */ - diff --git a/src/util-plugin.c b/src/util-plugin.c index 3a08aa8876ad..87fed319d43e 100644 --- a/src/util-plugin.c +++ b/src/util-plugin.c @@ -96,7 +96,7 @@ void SCPluginsLoad(const char *capture_plugin_name, const char *capture_plugin_a return; } ConfNode *plugin = NULL; - TAILQ_FOREACH(plugin, &conf->head, next) { + TAILQ_FOREACH (plugin, &conf->head, next) { struct stat statbuf; if (stat(plugin->val, &statbuf) == -1) { SCLogError("Bad plugin path: %s: %s", plugin->val, strerror(errno)); @@ -128,8 +128,7 @@ void SCPluginsLoad(const char *capture_plugin_name, const char *capture_plugin_a if (capture == NULL) { FatalError("No capture plugin found with name %s", capture_plugin_name); } - capture->Init(capture_plugin_args, RUNMODE_PLUGIN, TMM_RECEIVEPLUGIN, - TMM_DECODEPLUGIN); + capture->Init(capture_plugin_args, RUNMODE_PLUGIN, TMM_RECEIVEPLUGIN, TMM_DECODEPLUGIN); } } @@ -186,7 +185,7 @@ bool SCRegisterEveFileType(SCEveFileType *plugin) SCEveFileType *SCPluginFindFileType(const char *name) { SCEveFileType *plugin = NULL; - TAILQ_FOREACH(plugin, &output_types, entries) { + TAILQ_FOREACH (plugin, &output_types, entries) { if (strcmp(name, plugin->name) == 0) { return plugin; } @@ -204,7 +203,7 @@ int SCPluginRegisterCapture(SCCapturePlugin *plugin) SCCapturePlugin *SCPluginFindCaptureByName(const char *name) { SCCapturePlugin *plugin = NULL; - TAILQ_FOREACH(plugin, &capture_plugins, entries) { + TAILQ_FOREACH (plugin, &capture_plugins, entries) { if (strcmp(name, plugin->name) == 0) { return plugin; } diff --git a/src/util-pool-thread.c b/src/util-pool-thread.c index 162b523fce9e..a985027b8026 100644 --- a/src/util-pool-thread.c +++ b/src/util-pool-thread.c @@ -40,9 +40,9 @@ * \param thread number of threads this is for. Can start with 1 and be expanded. * Other params are as for PoolInit() */ -PoolThread *PoolThreadInit(int threads, uint32_t size, uint32_t prealloc_size, - uint32_t elt_size, void *(*Alloc)(void), int (*Init)(void *, void *), - void *InitData, void (*Cleanup)(void *), void (*Free)(void *)) +PoolThread *PoolThreadInit(int threads, uint32_t size, uint32_t prealloc_size, uint32_t elt_size, + void *(*Alloc)(void), int (*Init)(void *, void *), void *InitData, void (*Cleanup)(void *), + void (*Free)(void *)) { sc_errno = SC_OK; @@ -73,9 +73,10 @@ PoolThread *PoolThreadInit(int threads, uint32_t size, uint32_t prealloc_size, SCMutexInit(&e->lock, NULL); SCMutexLock(&e->lock); -// SCLogDebug("size %u prealloc_size %u elt_size %u Alloc %p Init %p InitData %p Cleanup %p Free %p", -// size, prealloc_size, elt_size, -// Alloc, Init, InitData, Cleanup, Free); + // SCLogDebug("size %u prealloc_size %u elt_size %u Alloc %p Init %p InitData %p + // Cleanup %p Free %p", + // size, prealloc_size, elt_size, + // Alloc, Init, InitData, Cleanup, Free); e->pool = PoolInit(size, prealloc_size, elt_size, Alloc, Init, InitData, Cleanup, Free); SCMutexUnlock(&e->lock); if (e->pool == NULL) { @@ -102,7 +103,7 @@ int PoolThreadExpand(PoolThread *pt) } size_t newsize = pt->size + 1; - SCLogDebug("newsize %"PRIuMAX, (uintmax_t)newsize); + SCLogDebug("newsize %" PRIuMAX, (uintmax_t)newsize); void *ptmp = SCRealloc(pt->array, (newsize * sizeof(PoolThreadElement))); if (ptmp == NULL) { @@ -133,9 +134,8 @@ int PoolThreadExpand(PoolThread *pt) memset(e, 0x00, sizeof(*e)); SCMutexInit(&e->lock, NULL); SCMutexLock(&e->lock); - e->pool = PoolInit(settings.max_buckets, settings.preallocated, - settings.elt_size, settings.Alloc, settings.Init, settings.InitData, - settings.Cleanup, settings.Free); + e->pool = PoolInit(settings.max_buckets, settings.preallocated, settings.elt_size, + settings.Alloc, settings.Init, settings.InitData, settings.Cleanup, settings.Free); SCMutexUnlock(&e->lock); if (e->pool == NULL) { SCLogError("pool grow failed"); @@ -237,28 +237,25 @@ static void *PoolThreadTestAlloc(void) return data; } -static -int PoolThreadTestInit(void *data, void *allocdata) +static int PoolThreadTestInit(void *data, void *allocdata) { if (!data) return 0; - memset(data,0x00,sizeof(allocdata)); + memset(data, 0x00, sizeof(allocdata)); struct PoolThreadTestData *pdata = data; pdata->abc = *(int *)allocdata; return 1; } -static -void PoolThreadTestFree(void *data) +static void PoolThreadTestFree(void *data) { } static int PoolThreadTestInit01(void) { PoolThread *pt = PoolThreadInit(4, /* threads */ - 10, 5, 10, PoolThreadTestAlloc, - NULL, NULL, NULL, NULL); + 10, 5, 10, PoolThreadTestAlloc, NULL, NULL, NULL, NULL); FAIL_IF(pt == NULL); PoolThreadFree(pt); PASS; @@ -269,9 +266,7 @@ static int PoolThreadTestInit02(void) int i = 123; PoolThread *pt = PoolThreadInit(4, /* threads */ - 10, 5, 10, - PoolThreadTestAlloc, PoolThreadTestInit, - &i, PoolThreadTestFree, NULL); + 10, 5, 10, PoolThreadTestAlloc, PoolThreadTestInit, &i, PoolThreadTestFree, NULL); FAIL_IF(pt == NULL); PoolThreadFree(pt); PASS; @@ -280,8 +275,7 @@ static int PoolThreadTestInit02(void) static int PoolThreadTestGet01(void) { PoolThread *pt = PoolThreadInit(4, /* threads */ - 10, 5, 10, PoolThreadTestAlloc, - NULL, NULL, NULL, NULL); + 10, 5, 10, PoolThreadTestAlloc, NULL, NULL, NULL, NULL); FAIL_IF(pt == NULL); void *data = PoolThreadGetById(pt, 3); @@ -299,17 +293,16 @@ static int PoolThreadTestGet02(void) int i = 123; PoolThread *pt = PoolThreadInit(4, /* threads */ - 10, 5, 10, PoolThreadTestAlloc, - PoolThreadTestInit, &i, PoolThreadTestFree, NULL); + 10, 5, 10, PoolThreadTestAlloc, PoolThreadTestInit, &i, PoolThreadTestFree, NULL); FAIL_IF_NULL(pt); void *data = PoolThreadGetById(pt, 3); FAIL_IF_NULL(data); struct PoolThreadTestData *pdata = data; - FAIL_IF_NOT (pdata->res == 3); + FAIL_IF_NOT(pdata->res == 3); - FAIL_IF_NOT (pdata->abc == 123); + FAIL_IF_NOT(pdata->abc == 123); PoolThreadFree(pt); PASS; @@ -320,23 +313,22 @@ static int PoolThreadTestReturn01(void) int i = 123; PoolThread *pt = PoolThreadInit(4, /* threads */ - 10, 5, 10, PoolThreadTestAlloc, - PoolThreadTestInit, &i, PoolThreadTestFree, NULL); + 10, 5, 10, PoolThreadTestAlloc, PoolThreadTestInit, &i, PoolThreadTestFree, NULL); FAIL_IF_NULL(pt); void *data = PoolThreadGetById(pt, 3); FAIL_IF_NULL(data); struct PoolThreadTestData *pdata = data; - FAIL_IF_NOT (pdata->res == 3); + FAIL_IF_NOT(pdata->res == 3); - FAIL_IF_NOT (pdata->abc == 123); + FAIL_IF_NOT(pdata->abc == 123); - FAIL_IF_NOT (pt->array[3].pool->outstanding == 1); + FAIL_IF_NOT(pt->array[3].pool->outstanding == 1); PoolThreadReturn(pt, data); - FAIL_IF_NOT (pt->array[3].pool->outstanding == 0); + FAIL_IF_NOT(pt->array[3].pool->outstanding == 0); PoolThreadFree(pt); PASS; @@ -345,8 +337,7 @@ static int PoolThreadTestReturn01(void) static int PoolThreadTestGrow01(void) { PoolThread *pt = PoolThreadInit(4, /* threads */ - 10, 5, 10, PoolThreadTestAlloc, - NULL, NULL, NULL, NULL); + 10, 5, 10, PoolThreadTestAlloc, NULL, NULL, NULL, NULL); FAIL_IF_NULL(pt); FAIL_IF(PoolThreadExpand(pt) < 0); @@ -359,8 +350,7 @@ static int PoolThreadTestGrow02(void) int i = 123; PoolThread *pt = PoolThreadInit(4, /* threads */ - 10, 5, 10, PoolThreadTestAlloc, - PoolThreadTestInit, &i, PoolThreadTestFree, NULL); + 10, 5, 10, PoolThreadTestAlloc, PoolThreadTestInit, &i, PoolThreadTestFree, NULL); FAIL_IF_NULL(pt); FAIL_IF(PoolThreadExpand(pt) < 0); @@ -373,8 +363,7 @@ static int PoolThreadTestGrow03(void) int i = 123; PoolThread *pt = PoolThreadInit(4, /* threads */ - 10, 5, 10, PoolThreadTestAlloc, - PoolThreadTestInit, &i, PoolThreadTestFree, NULL); + 10, 5, 10, PoolThreadTestAlloc, PoolThreadTestInit, &i, PoolThreadTestFree, NULL); FAIL_IF_NULL(pt); FAIL_IF(PoolThreadExpand(pt) < 0); diff --git a/src/util-pool-thread.h b/src/util-pool-thread.h index 44b76e75e292..e770d080b27a 100644 --- a/src/util-pool-thread.h +++ b/src/util-pool-thread.h @@ -43,16 +43,16 @@ #include "util-pool.h" struct PoolThreadElement_ { - SCMutex lock; /**< lock, should have low contention */ - Pool *pool; /**< actual pool */ + SCMutex lock; /**< lock, should have low contention */ + Pool *pool; /**< actual pool */ }; // __attribute__((aligned(CLS))); <- VJ: breaks on clang 32bit, segv in PoolThreadTestGrow01 typedef struct PoolThreadElement_ PoolThreadElement; typedef struct PoolThread_ { - size_t size; /**< size of the array */ - PoolThreadElement *array; /**< array of elements */ + size_t size; /**< size of the array */ + PoolThreadElement *array; /**< array of elements */ } PoolThread; /** per data item reserved data containing the @@ -65,7 +65,9 @@ void PoolThreadRegisterTests(void); * \note same as PoolInit() except for "threads" * \param threads number of threads to use this * \retval pt thread pool or NULL on error */ -PoolThread *PoolThreadInit(int threads, uint32_t size, uint32_t prealloc_size, uint32_t elt_size, void *(*Alloc)(void), int (*Init)(void *, void *), void *InitData, void (*Cleanup)(void *), void (*Free)(void *)); +PoolThread *PoolThreadInit(int threads, uint32_t size, uint32_t prealloc_size, uint32_t elt_size, + void *(*Alloc)(void), int (*Init)(void *, void *), void *InitData, void (*Cleanup)(void *), + void (*Free)(void *)); /** \brief grow a thread pool by one * \note copies settings from initial PoolThreadInit() call diff --git a/src/util-pool.c b/src/util-pool.c index bb9ff520c965..aa5b8a42108c 100644 --- a/src/util-pool.c +++ b/src/util-pool.c @@ -46,7 +46,7 @@ static int PoolMemset(void *pitem, void *initdata) { - Pool *p = (Pool *) initdata; + Pool *p = (Pool *)initdata; memset(pitem, 0, p->elt_size); return 1; @@ -81,9 +81,8 @@ static bool PoolDataPreAllocated(Pool *p, void *data) * \param Free free func * \retval the allocated Pool */ -Pool *PoolInit(uint32_t size, uint32_t prealloc_size, uint32_t elt_size, - void *(*Alloc)(void), int (*Init)(void *, void *), void *InitData, - void (*Cleanup)(void *), void (*Free)(void *)) +Pool *PoolInit(uint32_t size, uint32_t prealloc_size, uint32_t elt_size, void *(*Alloc)(void), + int (*Init)(void *, void *), void *InitData, void (*Cleanup)(void *), void (*Free)(void *)) { sc_errno = SC_OK; @@ -245,7 +244,7 @@ void PoolFree(Pool *p) while (p->empty_stack != NULL) { PoolBucket *pb = p->empty_stack; p->empty_stack = pb->next; - if (pb->data!= NULL) { + if (pb->data != NULL) { if (p->Cleanup) p->Cleanup(pb->data); if (!PoolDataPreAllocated(p, pb->data)) { @@ -292,7 +291,7 @@ void *PoolGet(Pool *p) } else { if (p->max_buckets == 0 || p->allocated < p->max_buckets) { void *pitem; - SCLogDebug("max_buckets %"PRIu32"", p->max_buckets); + SCLogDebug("max_buckets %" PRIu32 "", p->max_buckets); if (p->Alloc != NULL) { pitem = p->Alloc(); @@ -330,7 +329,7 @@ void *PoolGet(Pool *p) if (p->outstanding > p->max_outstanding) p->max_outstanding = p->outstanding; #endif - SCReturnPtr(ptr,"void"); + SCReturnPtr(ptr, "void"); } void PoolReturn(Pool *p, void *data) @@ -355,7 +354,8 @@ void PoolReturn(Pool *p, void *data) } SCLogDebug("tried to return data %p to the pool %p, but no more " - "buckets available. Just freeing the data.", data, p); + "buckets available. Just freeing the data.", + data, p); SCReturn; } @@ -402,7 +402,7 @@ static int PoolTestInitArg(void *data, void *allocdata) size_t len = strlen((char *)allocdata) + 1; char *str = data; if (str != NULL) - strlcpy(str,(char *)allocdata,len); + strlcpy(str, (char *)allocdata, len); return 1; } @@ -411,9 +411,9 @@ static void PoolTestFree(void *ptr) return; } -static int PoolTestInit01 (void) +static int PoolTestInit01(void) { - Pool *p = PoolInit(10,5,10,PoolTestAlloc,NULL,NULL,PoolTestFree, NULL); + Pool *p = PoolInit(10, 5, 10, PoolTestAlloc, NULL, NULL, PoolTestFree, NULL); if (p == NULL) return 0; @@ -421,31 +421,28 @@ static int PoolTestInit01 (void) return 1; } -static int PoolTestInit02 (void) +static int PoolTestInit02(void) { int retval = 0; - Pool *p = PoolInit(10,5,10,PoolTestAlloc,NULL,NULL,PoolTestFree, NULL); + Pool *p = PoolInit(10, 5, 10, PoolTestAlloc, NULL, NULL, PoolTestFree, NULL); if (p == NULL) goto end; if (p->alloc_stack == NULL || p->empty_stack == NULL) { - printf("list(s) not properly initialized (a:%p e:%p): ", - p->alloc_stack, p->empty_stack); + printf("list(s) not properly initialized (a:%p e:%p): ", p->alloc_stack, p->empty_stack); retval = 0; goto end; } if (p->Alloc != PoolTestAlloc) { - printf("Alloc func ptr %p != %p: ", - p->Alloc, PoolTestAlloc); + printf("Alloc func ptr %p != %p: ", p->Alloc, PoolTestAlloc); retval = 0; goto end; } if (p->Cleanup != PoolTestFree) { - printf("Free func ptr %p != %p: ", - p->Cleanup, PoolTestFree); + printf("Free func ptr %p != %p: ", p->Cleanup, PoolTestFree); retval = 0; goto end; } @@ -457,12 +454,12 @@ static int PoolTestInit02 (void) return retval; } -static int PoolTestInit03 (void) +static int PoolTestInit03(void) { int retval = 0; void *data = NULL; - Pool *p = PoolInit(10,5,10,PoolTestAlloc,NULL,NULL,PoolTestFree, NULL); + Pool *p = PoolInit(10, 5, 10, PoolTestAlloc, NULL, NULL, PoolTestFree, NULL); if (p == NULL) goto end; @@ -492,12 +489,13 @@ static int PoolTestInit03 (void) return retval; } -static int PoolTestInit04 (void) +static int PoolTestInit04(void) { int retval = 0; char *str = NULL; - Pool *p = PoolInit(10,5,strlen("test") + 1,NULL, PoolTestInitArg,(void *)"test",PoolTestFree, NULL); + Pool *p = PoolInit( + 10, 5, strlen("test") + 1, NULL, PoolTestInitArg, (void *)"test", PoolTestFree, NULL); if (p == NULL) goto end; @@ -533,12 +531,12 @@ static int PoolTestInit04 (void) return retval; } -static int PoolTestInit05 (void) +static int PoolTestInit05(void) { int retval = 0; void *data = NULL; - Pool *p = PoolInit(10,5,10,PoolTestAlloc,NULL, NULL,PoolTestFree, NULL); + Pool *p = PoolInit(10, 5, 10, PoolTestAlloc, NULL, NULL, PoolTestFree, NULL); if (p == NULL) goto end; @@ -583,13 +581,13 @@ static int PoolTestInit05 (void) return retval; } -static int PoolTestInit06 (void) +static int PoolTestInit06(void) { int retval = 0; void *data = NULL; void *data2 = NULL; - Pool *p = PoolInit(1,0,10,PoolTestAlloc,NULL,NULL,PoolTestFree, NULL); + Pool *p = PoolInit(1, 0, 10, PoolTestAlloc, NULL, NULL, PoolTestFree, NULL); if (p == NULL) goto end; @@ -619,7 +617,7 @@ static int PoolTestInit06 (void) goto end; } - PoolReturn(p,data); + PoolReturn(p, data); data = NULL; if (p->allocated != 1) { @@ -642,13 +640,13 @@ static int PoolTestInit06 (void) } /** \test pool with unlimited size */ -static int PoolTestInit07 (void) +static int PoolTestInit07(void) { int retval = 0; void *data = NULL; void *data2 = NULL; - Pool *p = PoolInit(0,1,10,PoolTestAlloc,NULL,NULL,PoolTestFree, NULL); + Pool *p = PoolInit(0, 1, 10, PoolTestAlloc, NULL, NULL, PoolTestFree, NULL); if (p == NULL) goto end; @@ -690,7 +688,7 @@ static int PoolTestInit07 (void) goto end; } - PoolReturn(p,data); + PoolReturn(p, data); data = NULL; if (p->allocated != 2) { @@ -705,7 +703,7 @@ static int PoolTestInit07 (void) goto end; } - PoolReturn(p,data2); + PoolReturn(p, data2); data2 = NULL; if (p->allocated != 1) { @@ -737,7 +735,6 @@ void PoolRegisterTests(void) #endif /* UNITTESTS */ } - /** * @} */ diff --git a/src/util-pool.h b/src/util-pool.h index cb82ff6da076..f7b5d7285a6b 100644 --- a/src/util-pool.h +++ b/src/util-pool.h @@ -30,7 +30,7 @@ #ifndef __UTIL_POOL_H__ #define __UTIL_POOL_H__ -#define POOL_BUCKET_PREALLOCATED (1 << 0) +#define POOL_BUCKET_PREALLOCATED (1 << 0) /* pool bucket structure */ typedef struct PoolBucket_ { @@ -43,8 +43,8 @@ typedef struct PoolBucket_ { typedef struct Pool_ { uint32_t max_buckets; uint32_t preallocated; - uint32_t allocated; /**< counter of data elements, both currently in - * the pool and outside of it (outstanding) */ + uint32_t allocated; /**< counter of data elements, both currently in + * the pool and outside of it (outstanding) */ uint32_t alloc_stack_size; @@ -64,15 +64,16 @@ typedef struct Pool_ { void (*Free)(void *); uint32_t elt_size; - uint32_t outstanding; /**< counter of data items 'in use'. Pretty much - * the diff between PoolGet and PoolReturn */ + uint32_t outstanding; /**< counter of data items 'in use'. Pretty much + * the diff between PoolGet and PoolReturn */ #ifdef DEBUG - uint32_t max_outstanding; /**< max value of outstanding we saw */ + uint32_t max_outstanding; /**< max value of outstanding we saw */ #endif } Pool; /* prototypes */ -Pool* PoolInit(uint32_t, uint32_t, uint32_t, void *(*Alloc)(void), int (*Init)(void *, void *), void *, void (*Cleanup)(void *), void (*Free)(void *)); +Pool *PoolInit(uint32_t, uint32_t, uint32_t, void *(*Alloc)(void), int (*Init)(void *, void *), + void *, void (*Cleanup)(void *), void (*Free)(void *)); void PoolFree(Pool *); void PoolPrint(Pool *); void PoolPrintSaturation(Pool *p); diff --git a/src/util-prefilter.c b/src/util-prefilter.c index c00aa6528c64..fcf426916d87 100644 --- a/src/util-prefilter.c +++ b/src/util-prefilter.c @@ -48,7 +48,7 @@ int PmqSetup(PrefilterRuleStore *pmq) pmq->rule_id_array_cnt = 0; size_t bytes = pmq->rule_id_array_size * sizeof(SigIntId); - pmq->rule_id_array = (SigIntId*)SCMalloc(bytes); + pmq->rule_id_array = (SigIntId *)SCMalloc(bytes); if (pmq->rule_id_array == NULL) { pmq->rule_id_array_size = 0; SCReturnInt(-1); @@ -66,21 +66,18 @@ int PmqSetup(PrefilterRuleStore *pmq) * \param new_size number of Signature IDs needing to be stored. * */ -int -PrefilterAddSidsResize(PrefilterRuleStore *pmq, uint32_t new_size) +int PrefilterAddSidsResize(PrefilterRuleStore *pmq, uint32_t new_size) { /* Need to make the array bigger. Double the size needed to * also handle the case that sids_size might still be * larger than the old size. */ new_size = new_size * 2; - SigIntId *new_array = (SigIntId*)SCRealloc(pmq->rule_id_array, - new_size * sizeof(SigIntId)); + SigIntId *new_array = (SigIntId *)SCRealloc(pmq->rule_id_array, new_size * sizeof(SigIntId)); if (unlikely(new_array == NULL)) { /* Try again just big enough. */ new_size = new_size / 2; - new_array = (SigIntId*)SCRealloc(pmq->rule_id_array, - new_size * sizeof(SigIntId)); + new_array = (SigIntId *)SCRealloc(pmq->rule_id_array, new_size * sizeof(SigIntId)); if (unlikely(new_array == NULL)) { SCLogError("Failed to realloc PatternMatchQueue" @@ -108,8 +105,8 @@ void PmqReset(PrefilterRuleStore *pmq) } /** \brief Cleanup a Pmq - * \param pmq Pattern matcher queue to be cleaned up. - */ + * \param pmq Pattern matcher queue to be cleaned up. + */ void PmqCleanup(PrefilterRuleStore *pmq) { if (pmq == NULL) @@ -121,8 +118,8 @@ void PmqCleanup(PrefilterRuleStore *pmq) } /** \brief Cleanup and free a Pmq - * \param pmq Pattern matcher queue to be free'd. - */ + * \param pmq Pattern matcher queue to be free'd. + */ void PmqFree(PrefilterRuleStore *pmq) { if (pmq == NULL) diff --git a/src/util-print.c b/src/util-print.c index be87af1ccfda..fac4a9f3a8c5 100644 --- a/src/util-print.c +++ b/src/util-print.c @@ -41,7 +41,8 @@ * \param buf buffer to print from * \param buflen length of the input buffer */ -void PrintBufferRawLineHex(char *nbuf, int *offset, int max_size, const uint8_t *buf, uint32_t buflen) +void PrintBufferRawLineHex( + char *nbuf, int *offset, int max_size, const uint8_t *buf, uint32_t buflen) { for (uint32_t u = 0; u < buflen; u++) { PrintBufferData(nbuf, offset, max_size, "%02X ", buf[u]); @@ -74,14 +75,11 @@ void PrintRawJsonFp(FILE *fp, uint8_t *buf, uint32_t buflen) for (uint32_t u = 0; u < buflen; u++) { if (buf[u] == '\\' || buf[u] == '/' || buf[u] == '\"') { - PrintBufferData(nbuf, &offset, BUFFER_LENGTH, - "\\%c", buf[u]); + PrintBufferData(nbuf, &offset, BUFFER_LENGTH, "\\%c", buf[u]); } else if (isprint(buf[u])) { - PrintBufferData(nbuf, &offset, BUFFER_LENGTH, - "%c", buf[u]); + PrintBufferData(nbuf, &offset, BUFFER_LENGTH, "%c", buf[u]); } else { - PrintBufferData(nbuf, &offset, BUFFER_LENGTH, - "\\\\x%02X", buf[u]); + PrintBufferData(nbuf, &offset, BUFFER_LENGTH, "\\\\x%02X", buf[u]); } } fprintf(fp, "%s", nbuf); @@ -96,36 +94,30 @@ void PrintRawUriFp(FILE *fp, uint8_t *buf, uint32_t buflen) for (uint32_t u = 0; u < buflen; u++) { if (isprint(buf[u]) && buf[u] != '\"') { if (buf[u] == '\\') { - PrintBufferData(nbuf, &offset, BUFFER_LENGTH, - "\\\\"); + PrintBufferData(nbuf, &offset, BUFFER_LENGTH, "\\\\"); } else { - PrintBufferData(nbuf, &offset, BUFFER_LENGTH, - "%c", buf[u]); + PrintBufferData(nbuf, &offset, BUFFER_LENGTH, "%c", buf[u]); } } else { - PrintBufferData(nbuf, &offset, BUFFER_LENGTH, - "\\x%02X", buf[u]); + PrintBufferData(nbuf, &offset, BUFFER_LENGTH, "\\x%02X", buf[u]); } } fprintf(fp, "%s", nbuf); } -void PrintRawUriBuf(char *retbuf, uint32_t *offset, uint32_t retbuflen, - uint8_t *buf, uint32_t buflen) +void PrintRawUriBuf( + char *retbuf, uint32_t *offset, uint32_t retbuflen, uint8_t *buf, uint32_t buflen) { for (uint32_t u = 0; u < buflen; u++) { if (isprint(buf[u]) && buf[u] != '\"') { if (buf[u] == '\\') { - PrintBufferData(retbuf, offset, retbuflen, - "\\\\"); + PrintBufferData(retbuf, offset, retbuflen, "\\\\"); } else { - PrintBufferData(retbuf, offset, retbuflen, - "%c", buf[u]); + PrintBufferData(retbuf, offset, retbuflen, "%c", buf[u]); } } else { - PrintBufferData(retbuf, offset, retbuflen, - "\\x%02X", buf[u]); + PrintBufferData(retbuf, offset, retbuflen, "\\x%02X", buf[u]); } } @@ -141,28 +133,34 @@ void PrintRawDataFp(FILE *fp, const uint8_t *buf, uint32_t buflen) return; } for (uint32_t u = 0; u < buflen; u += 16) { - fprintf(fp ," %04X ", u); - for (ch = 0; (u+ch) < buflen && ch < 16; ch++) { - fprintf(fp, "%02X ", (uint8_t)buf[u+ch]); + fprintf(fp, " %04X ", u); + for (ch = 0; (u + ch) < buflen && ch < 16; ch++) { + fprintf(fp, "%02X ", (uint8_t)buf[u + ch]); - if (ch == 7) fprintf(fp, " "); + if (ch == 7) + fprintf(fp, " "); } - if (ch == 16) fprintf(fp, " "); + if (ch == 16) + fprintf(fp, " "); else if (ch < 8) { int spaces = (16 - ch) * 3 + 2 + 1; int s = 0; - for ( ; s < spaces; s++) fprintf(fp, " "); - } else if(ch < 16) { + for (; s < spaces; s++) + fprintf(fp, " "); + } else if (ch < 16) { int spaces = (16 - ch) * 3 + 2; int s = 0; - for ( ; s < spaces; s++) fprintf(fp, " "); + for (; s < spaces; s++) + fprintf(fp, " "); } - for (ch = 0; (u+ch) < buflen && ch < 16; ch++) { - fprintf(fp, "%c", isprint((uint8_t)buf[u+ch]) ? (uint8_t)buf[u+ch] : '.'); + for (ch = 0; (u + ch) < buflen && ch < 16; ch++) { + fprintf(fp, "%c", isprint((uint8_t)buf[u + ch]) ? (uint8_t)buf[u + ch] : '.'); - if (ch == 7) fprintf(fp, " "); - if (ch == 15) fprintf(fp, "\n"); + if (ch == 7) + fprintf(fp, " "); + if (ch == 15) + fprintf(fp, "\n"); } } if (ch != 16) @@ -170,20 +168,18 @@ void PrintRawDataFp(FILE *fp, const uint8_t *buf, uint32_t buflen) } void PrintRawDataToBuffer(uint8_t *dst_buf, uint32_t *dst_buf_offset_ptr, uint32_t dst_buf_size, - const uint8_t *src_buf, uint32_t src_buf_len) + const uint8_t *src_buf, uint32_t src_buf_len) { int ch = 0; for (uint32_t u = 0; u < src_buf_len; u += 16) { - PrintBufferData((char *)dst_buf, dst_buf_offset_ptr, dst_buf_size, - " %04X ", u); + PrintBufferData((char *)dst_buf, dst_buf_offset_ptr, dst_buf_size, " %04X ", u); for (ch = 0; (u + ch) < src_buf_len && ch < 16; ch++) { - PrintBufferData((char *)dst_buf, dst_buf_offset_ptr, dst_buf_size, - "%02X ", (uint8_t)src_buf[u + ch]); + PrintBufferData((char *)dst_buf, dst_buf_offset_ptr, dst_buf_size, "%02X ", + (uint8_t)src_buf[u + ch]); if (ch == 7) { - PrintBufferData((char *)dst_buf, dst_buf_offset_ptr, dst_buf_size, - " "); + PrintBufferData((char *)dst_buf, dst_buf_offset_ptr, dst_buf_size, " "); } } if (ch == 16) { @@ -191,24 +187,23 @@ void PrintRawDataToBuffer(uint8_t *dst_buf, uint32_t *dst_buf_offset_ptr, uint32 } else if (ch < 8) { int spaces = (16 - ch) * 3 + 2 + 1; int s = 0; - for ( ; s < spaces; s++) + for (; s < spaces; s++) PrintBufferData((char *)dst_buf, dst_buf_offset_ptr, dst_buf_size, " "); - } else if(ch < 16) { + } else if (ch < 16) { int spaces = (16 - ch) * 3 + 2; int s = 0; - for ( ; s < spaces; s++) + for (; s < spaces; s++) PrintBufferData((char *)dst_buf, dst_buf_offset_ptr, dst_buf_size, " "); } - for (ch = 0; (u+ch) < src_buf_len && ch < 16; ch++) { - PrintBufferData((char *)dst_buf, dst_buf_offset_ptr, dst_buf_size, - "%c", - isprint((uint8_t)src_buf[u + ch]) ? (uint8_t)src_buf[u + ch] : '.'); + for (ch = 0; (u + ch) < src_buf_len && ch < 16; ch++) { + PrintBufferData((char *)dst_buf, dst_buf_offset_ptr, dst_buf_size, "%c", + isprint((uint8_t)src_buf[u + ch]) ? (uint8_t)src_buf[u + ch] : '.'); - if (ch == 7) - PrintBufferData((char *)dst_buf, dst_buf_offset_ptr, dst_buf_size, " "); - if (ch == 15) - PrintBufferData((char *)dst_buf, dst_buf_offset_ptr, dst_buf_size, "\n"); + if (ch == 7) + PrintBufferData((char *)dst_buf, dst_buf_offset_ptr, dst_buf_size, " "); + if (ch == 15) + PrintBufferData((char *)dst_buf, dst_buf_offset_ptr, dst_buf_size, "\n"); } } if (ch != 16) @@ -218,7 +213,7 @@ void PrintRawDataToBuffer(uint8_t *dst_buf, uint32_t *dst_buf_offset_ptr, uint32 } void PrintStringsToBuffer(uint8_t *dst_buf, uint32_t *dst_buf_offset_ptr, uint32_t dst_buf_size, - const uint8_t *src_buf, const uint32_t src_buf_len) + const uint8_t *src_buf, const uint32_t src_buf_len) { for (uint32_t ch = 0; ch < src_buf_len && *dst_buf_offset_ptr < dst_buf_size; ch++, (*dst_buf_offset_ptr)++) { @@ -234,7 +229,7 @@ void PrintStringsToBuffer(uint8_t *dst_buf, uint32_t *dst_buf_offset_ptr, uint32 } #ifndef s6_addr16 -# define s6_addr16 __u6_addr.__u6_addr16 +#define s6_addr16 __u6_addr.__u6_addr16 #endif static const char *PrintInetIPv6(const void *src, char *dst, socklen_t size) @@ -264,13 +259,13 @@ const char *PrintInet(int af, const void *src, char *dst, socklen_t size) switch (af) { case AF_INET: #if defined(OS_WIN32) && NTDDI_VERSION >= NTDDI_VISTA -{ + { // because Windows has to provide a non-conformant inet_ntop, of // course! struct in_addr _src; memcpy(&_src, src, sizeof(struct in_addr)); return inet_ntop(af, &_src, dst, size); -} + } #else return inet_ntop(af, src, dst, size); #endif diff --git a/src/util-print.h b/src/util-print.h index 249ec20f7353..63d051c11b72 100644 --- a/src/util-print.h +++ b/src/util-print.h @@ -21,39 +21,35 @@ * \author Victor Julien */ - - #ifndef __UTIL_PRINT_H__ #define __UTIL_PRINT_H__ -#define PrintBufferData(buf, buf_offset_ptr, buf_size, ...) do { \ - int cw = snprintf((buf) + *(buf_offset_ptr), \ - (buf_size) - *(buf_offset_ptr), \ - __VA_ARGS__); \ - if (cw >= 0) { \ - if ( (*(buf_offset_ptr) + cw) >= buf_size) { \ - SCLogDebug("Truncating data write since it exceeded buffer " \ - "limit of - %"PRIu32"\n", buf_size); \ - *(buf_offset_ptr) = buf_size - 1; \ - } else { \ - *(buf_offset_ptr) += cw; \ - } \ - } \ +#define PrintBufferData(buf, buf_offset_ptr, buf_size, ...) \ + do { \ + int cw = snprintf((buf) + *(buf_offset_ptr), (buf_size) - *(buf_offset_ptr), __VA_ARGS__); \ + if (cw >= 0) { \ + if ((*(buf_offset_ptr) + cw) >= buf_size) { \ + SCLogDebug("Truncating data write since it exceeded buffer " \ + "limit of - %" PRIu32 "\n", \ + buf_size); \ + *(buf_offset_ptr) = buf_size - 1; \ + } else { \ + *(buf_offset_ptr) += cw; \ + } \ + } \ } while (0) -void PrintBufferRawLineHex(char *, int *,int, const uint8_t *, uint32_t); +void PrintBufferRawLineHex(char *, int *, int, const uint8_t *, uint32_t); void PrintRawUriFp(FILE *, uint8_t *, uint32_t); -void PrintRawUriBuf(char *, uint32_t *, uint32_t, - uint8_t *, uint32_t); +void PrintRawUriBuf(char *, uint32_t *, uint32_t, uint8_t *, uint32_t); void PrintRawJsonFp(FILE *, uint8_t *, uint32_t); void PrintRawDataFp(FILE *, const uint8_t *, uint32_t); void PrintRawDataToBuffer(uint8_t *dst_buf, uint32_t *dst_buf_offset_ptr, uint32_t dst_buf_size, - const uint8_t *src_buf, uint32_t src_buf_len); + const uint8_t *src_buf, uint32_t src_buf_len); void PrintStringsToBuffer(uint8_t *dst_buf, uint32_t *dst_buf_offset_ptr, uint32_t dst_buf_size, - const uint8_t *src_buf, const uint32_t src_buf_len); -void PrintRawLineHexBuf(char *, uint32_t, const uint8_t *, uint32_t ); -const char *PrintInet(int , const void *, char *, socklen_t); + const uint8_t *src_buf, const uint32_t src_buf_len); +void PrintRawLineHexBuf(char *, uint32_t, const uint8_t *, uint32_t); +const char *PrintInet(int, const void *, char *, socklen_t); void PrintHexString(char *str, size_t size, uint8_t *buf, size_t buf_len); #endif /* __UTIL_PRINT_H__ */ - diff --git a/src/util-privs.c b/src/util-privs.c index 3a1ea485159a..d3a91c804708 100644 --- a/src/util-privs.c +++ b/src/util-privs.c @@ -63,29 +63,23 @@ void SCDropMainThreadCaps(uint32_t userid, uint32_t groupid) case RUNMODE_PCAP_DEV: case RUNMODE_AFP_DEV: case RUNMODE_AFXDP_DEV: - capng_updatev(CAPNG_ADD, CAPNG_EFFECTIVE|CAPNG_PERMITTED, - CAP_NET_RAW, /* needed for pcap live mode */ - CAP_SYS_NICE, - CAP_NET_ADMIN, - -1); + capng_updatev(CAPNG_ADD, CAPNG_EFFECTIVE | CAPNG_PERMITTED, + CAP_NET_RAW, /* needed for pcap live mode */ + CAP_SYS_NICE, CAP_NET_ADMIN, -1); break; case RUNMODE_PFRING: - capng_updatev(CAPNG_ADD, CAPNG_EFFECTIVE|CAPNG_PERMITTED, - CAP_NET_ADMIN, CAP_NET_RAW, CAP_SYS_NICE, - -1); + capng_updatev(CAPNG_ADD, CAPNG_EFFECTIVE | CAPNG_PERMITTED, CAP_NET_ADMIN, CAP_NET_RAW, + CAP_SYS_NICE, -1); break; case RUNMODE_NFLOG: case RUNMODE_NFQ: - capng_updatev(CAPNG_ADD, CAPNG_EFFECTIVE|CAPNG_PERMITTED, - CAP_NET_ADMIN, /* needed for nflog and nfqueue inline mode */ - CAP_SYS_NICE, - -1); + capng_updatev(CAPNG_ADD, CAPNG_EFFECTIVE | CAPNG_PERMITTED, + CAP_NET_ADMIN, /* needed for nflog and nfqueue inline mode */ + CAP_SYS_NICE, -1); break; } - if (capng_change_id(userid, groupid, CAPNG_DROP_SUPP_GRP | - CAPNG_CLEAR_BOUNDING) < 0) - { + if (capng_change_id(userid, groupid, CAPNG_DROP_SUPP_GRP | CAPNG_CLEAR_BOUNDING) < 0) { FatalError("capng_change_id for main thread" " failed"); } @@ -164,9 +158,9 @@ void SCGetUserID(const char *user_name, const char *group_name, uint32_t *uid, u FatalError("invalid user id value: '%s'", user_name); } pw = getpwuid(userid); - if (pw == NULL) { - FatalError("unable to get the user ID, " - "check if user exist!!"); + if (pw == NULL) { + FatalError("unable to get the user ID, " + "check if user exist!!"); } } else { pw = getpwnam(user_name); diff --git a/src/util-privs.h b/src/util-privs.h index 454533963d34..21322d6224ee 100644 --- a/src/util-privs.h +++ b/src/util-privs.h @@ -22,7 +22,7 @@ */ #ifndef _UTIL_PRIVS_H -#define _UTIL_PRIVS_H +#define _UTIL_PRIVS_H #define SC_CAP_NONE 0x01 #define SC_CAP_SYS_ADMIN 0x02 @@ -52,17 +52,20 @@ void SCDropCaps(ThreadVars *tv); SCLogDebug("For thread \"%s\" CAP_IPC_LOCK has been set", tv->name); \ } \ if (tv->cap_flags & SC_CAP_NET_ADMIN) { \ - capng_update(CAPNG_ADD, (capng_type_t) (CAPNG_EFFECTIVE | CAPNG_PERMITTED), CAP_NET_ADMIN); \ + capng_update(CAPNG_ADD, (capng_type_t) (CAPNG_EFFECTIVE | CAPNG_PERMITTED), CAP_NET_ADMIN); +\ capng_apply(CAPNG_SELECT_CAPS); \ SCLogDebug("For thread \"%s\" CAP_NET_ADMIN has been set", tv->name); \ } \ if (tv->cap_flags & SC_CAP_NET_BIND_SERVICE) { \ - capng_update(CAPNG_ADD, (capng_type_t) (CAPNG_EFFECTIVE | CAPNG_PERMITTED), CAP_NET_BIND_SERVICE); \ + capng_update(CAPNG_ADD, (capng_type_t) (CAPNG_EFFECTIVE | CAPNG_PERMITTED), +CAP_NET_BIND_SERVICE); \ capng_apply(CAPNG_SELECT_CAPS); \ SCLogDebug("For thread \"%s\" CAP_NET_BIND_SERVICE has been set", tv->name); \ } \ if (tv->cap_flags & SC_CAP_NET_BROADCAST) { \ - capng_update(CAPNG_ADD, (capng_type_t) (CAPNG_EFFECTIVE | CAPNG_PERMITTED), CAP_NET_BROADCAST); \ + capng_update(CAPNG_ADD, (capng_type_t) (CAPNG_EFFECTIVE | CAPNG_PERMITTED), +CAP_NET_BROADCAST); \ capng_apply(CAPNG_SELECT_CAPS); \ SCLogDebug("For thread \"%s\" CAP_NET_BROADCAST has been set", tv->name); \ } \ @@ -72,18 +75,20 @@ void SCDropCaps(ThreadVars *tv); SCLogDebug("For thread \"%s\" CAP_NET_RAW has been set", tv->name); \ } \ if (tv->cap_flags & SC_CAP_SYS_ADMIN) { \ - capng_update(CAPNG_ADD, (capng_type_t) (CAPNG_EFFECTIVE | CAPNG_PERMITTED), CAP_SYS_ADMIN); \ + capng_update(CAPNG_ADD, (capng_type_t) (CAPNG_EFFECTIVE | CAPNG_PERMITTED), CAP_SYS_ADMIN); +\ capng_apply(CAPNG_SELECT_CAPS); \ SCLogDebug("For thread \"%s\" CAP_SYS_ADMIN has been set", tv->name); \ } \ if (tv->cap_flags & SC_CAP_SYS_RAW_IO) { \ - capng_update(CAPNG_ADD, (capng_type_t) (CAPNG_EFFECTIVE | CAPNG_PERMITTED), CAP_SYS_RAWIO); \ + capng_update(CAPNG_ADD, (capng_type_t) (CAPNG_EFFECTIVE | CAPNG_PERMITTED), CAP_SYS_RAWIO); +\ capng_apply(CAPNG_SELECT_CAPS); \ SCLogDebug("For thread \"%s\" CAP_SYS_RAWIO has been set", tv->name); \ } \ }) */ -void SCDropMainThreadCaps(uint32_t , uint32_t ); +void SCDropMainThreadCaps(uint32_t, uint32_t); #else #define SCDropCaps(...) @@ -99,5 +104,4 @@ int SCPledge(void); #define SCPledge(...) #endif /* __OpenBSD__ */ -#endif /* _UTIL_PRIVS_H */ - +#endif /* _UTIL_PRIVS_H */ diff --git a/src/util-profiling-keywords.c b/src/util-profiling-keywords.c index c0620a751bcd..5873c29662db 100644 --- a/src/util-profiling-keywords.c +++ b/src/util-profiling-keywords.c @@ -70,8 +70,8 @@ void SCProfilingKeywordsGlobalInit(void) const char *log_dir; log_dir = ConfigGetLogDirectory(); - snprintf(profiling_file_name, sizeof(profiling_file_name), "%s/%s", - log_dir, filename); + snprintf(profiling_file_name, sizeof(profiling_file_name), "%s/%s", log_dir, + filename); const char *v = ConfNodeLookupChildValue(conf, "append"); if (v == NULL || ConfValIsTrue(v)) { @@ -90,13 +90,14 @@ static void DoDump(SCProfileKeywordDetectCtx *rules_ctx, FILE *fp, const char *n { int i; fprintf(fp, " ----------------------------------------------" - "------------------------------------------------------" - "----------------------------\n"); + "------------------------------------------------------" + "----------------------------\n"); fprintf(fp, " Stats for: %s\n", name); fprintf(fp, " ----------------------------------------------" - "------------------------------------------------------" - "----------------------------\n"); - fprintf(fp, " %-16s %-15s %-15s %-15s %-15s %-15s %-15s %-15s\n", "Keyword", "Ticks", "Checks", "Matches", "Max Ticks", "Avg", "Avg Match", "Avg No Match"); + "------------------------------------------------------" + "----------------------------\n"); + fprintf(fp, " %-16s %-15s %-15s %-15s %-15s %-15s %-15s %-15s\n", "Keyword", "Ticks", "Checks", + "Matches", "Max Ticks", "Avg", "Avg Match", "Avg No Match"); fprintf(fp, " ---------------- " "--------------- " "--------------- " @@ -105,7 +106,7 @@ static void DoDump(SCProfileKeywordDetectCtx *rules_ctx, FILE *fp, const char *n "--------------- " "--------------- " "--------------- " - "\n"); + "\n"); for (i = 0; i < DETECT_TBLSIZE; i++) { SCProfileKeywordData *d = &rules_ctx->data[i]; if (d == NULL || d->checks == 0) @@ -125,20 +126,14 @@ static void DoDump(SCProfileKeywordDetectCtx *rules_ctx, FILE *fp, const char *n } fprintf(fp, - " %-16s %-15"PRIu64" %-15"PRIu64" %-15"PRIu64" %-15"PRIu64" %-15.2f %-15.2f %-15.2f\n", - sigmatch_table[i].name, - ticks, - d->checks, - d->matches, - d->max, - avgticks, - avgticks_match, - avgticks_no_match); + " %-16s %-15" PRIu64 " %-15" PRIu64 " %-15" PRIu64 " %-15" PRIu64 + " %-15.2f %-15.2f %-15.2f\n", + sigmatch_table[i].name, ticks, d->checks, d->matches, d->max, avgticks, + avgticks_match, avgticks_no_match); } } -static void -SCProfilingKeywordDump(DetectEngineCtx *de_ctx) +static void SCProfilingKeywordDump(DetectEngineCtx *de_ctx) { int i; FILE *fp; @@ -163,15 +158,17 @@ SCProfilingKeywordDump(DetectEngineCtx *de_ctx) return; } } else { - fp = stdout; + fp = stdout; } fprintf(fp, " ----------------------------------------------" - "------------------------------------------------------" - "----------------------------\n"); - fprintf(fp, " Date: %" PRId32 "/%" PRId32 "/%04d -- " - "%02d:%02d:%02d\n", tms->tm_mon + 1, tms->tm_mday, tms->tm_year + 1900, - tms->tm_hour,tms->tm_min, tms->tm_sec); + "------------------------------------------------------" + "----------------------------\n"); + fprintf(fp, + " Date: %" PRId32 "/%" PRId32 "/%04d -- " + "%02d:%02d:%02d\n", + tms->tm_mon + 1, tms->tm_mday, tms->tm_year + 1900, tms->tm_hour, tms->tm_min, + tms->tm_sec); /* global stats first */ DoDump(de_ctx->profile_keyword_ctx, fp, "total"); @@ -195,7 +192,7 @@ SCProfilingKeywordDump(DetectEngineCtx *de_ctx) } } - fprintf(fp,"\n"); + fprintf(fp, "\n"); if (fp != stdout) fclose(fp); @@ -209,8 +206,8 @@ SCProfilingKeywordDump(DetectEngineCtx *de_ctx) * \param ticks Number of CPU ticks for this rule. * \param match Did the rule match? */ -void -SCProfilingKeywordUpdateCounter(DetectEngineThreadCtx *det_ctx, int id, uint64_t ticks, int match) +void SCProfilingKeywordUpdateCounter( + DetectEngineThreadCtx *det_ctx, int id, uint64_t ticks, int match) { if (det_ctx != NULL && det_ctx->keyword_perf_data != NULL && id < DETECT_TBLSIZE) { SCProfileKeywordData *p = &det_ctx->keyword_perf_data[id]; @@ -225,7 +222,8 @@ SCProfilingKeywordUpdateCounter(DetectEngineThreadCtx *det_ctx, int id, uint64_t p->ticks_no_match += ticks; /* store per list (buffer type) as well */ - if (det_ctx->keyword_perf_list >= 0) {// && det_ctx->keyword_perf_list < DETECT_SM_LIST_MAX) { + if (det_ctx->keyword_perf_list >= + 0) { // && det_ctx->keyword_perf_list < DETECT_SM_LIST_MAX) { p = &det_ctx->keyword_perf_data_per_list[det_ctx->keyword_perf_list][id]; p->checks++; p->matches += match; @@ -304,16 +302,18 @@ void SCProfilingKeywordThreadSetup(SCProfileKeywordDetectCtx *ctx, DetectEngineT static void SCProfilingKeywordThreadMerge(DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx) { if (de_ctx == NULL || de_ctx->profile_keyword_ctx == NULL || - de_ctx->profile_keyword_ctx->data == NULL || det_ctx == NULL || - det_ctx->keyword_perf_data == NULL) + de_ctx->profile_keyword_ctx->data == NULL || det_ctx == NULL || + det_ctx->keyword_perf_data == NULL) return; int i; for (i = 0; i < DETECT_TBLSIZE; i++) { de_ctx->profile_keyword_ctx->data[i].checks += det_ctx->keyword_perf_data[i].checks; de_ctx->profile_keyword_ctx->data[i].matches += det_ctx->keyword_perf_data[i].matches; - de_ctx->profile_keyword_ctx->data[i].ticks_match += det_ctx->keyword_perf_data[i].ticks_match; - de_ctx->profile_keyword_ctx->data[i].ticks_no_match += det_ctx->keyword_perf_data[i].ticks_no_match; + de_ctx->profile_keyword_ctx->data[i].ticks_match += + det_ctx->keyword_perf_data[i].ticks_match; + de_ctx->profile_keyword_ctx->data[i].ticks_no_match += + det_ctx->keyword_perf_data[i].ticks_no_match; if (det_ctx->keyword_perf_data[i].max > de_ctx->profile_keyword_ctx->data[i].max) de_ctx->profile_keyword_ctx->data[i].max = det_ctx->keyword_perf_data[i].max; } @@ -322,12 +322,18 @@ static void SCProfilingKeywordThreadMerge(DetectEngineCtx *de_ctx, DetectEngineT int j; for (j = 0; j < nlists; j++) { for (i = 0; i < DETECT_TBLSIZE; i++) { - de_ctx->profile_keyword_ctx_per_list[j]->data[i].checks += det_ctx->keyword_perf_data_per_list[j][i].checks; - de_ctx->profile_keyword_ctx_per_list[j]->data[i].matches += det_ctx->keyword_perf_data_per_list[j][i].matches; - de_ctx->profile_keyword_ctx_per_list[j]->data[i].ticks_match += det_ctx->keyword_perf_data_per_list[j][i].ticks_match; - de_ctx->profile_keyword_ctx_per_list[j]->data[i].ticks_no_match += det_ctx->keyword_perf_data_per_list[j][i].ticks_no_match; - if (det_ctx->keyword_perf_data_per_list[j][i].max > de_ctx->profile_keyword_ctx_per_list[j]->data[i].max) - de_ctx->profile_keyword_ctx_per_list[j]->data[i].max = det_ctx->keyword_perf_data_per_list[j][i].max; + de_ctx->profile_keyword_ctx_per_list[j]->data[i].checks += + det_ctx->keyword_perf_data_per_list[j][i].checks; + de_ctx->profile_keyword_ctx_per_list[j]->data[i].matches += + det_ctx->keyword_perf_data_per_list[j][i].matches; + de_ctx->profile_keyword_ctx_per_list[j]->data[i].ticks_match += + det_ctx->keyword_perf_data_per_list[j][i].ticks_match; + de_ctx->profile_keyword_ctx_per_list[j]->data[i].ticks_no_match += + det_ctx->keyword_perf_data_per_list[j][i].ticks_no_match; + if (det_ctx->keyword_perf_data_per_list[j][i].max > + de_ctx->profile_keyword_ctx_per_list[j]->data[i].max) + de_ctx->profile_keyword_ctx_per_list[j]->data[i].max = + det_ctx->keyword_perf_data_per_list[j][i].max; } } } @@ -358,8 +364,7 @@ void SCProfilingKeywordThreadCleanup(DetectEngineThreadCtx *det_ctx) * * \param de_ctx The active DetectEngineCtx, used to get at the loaded rules. */ -void -SCProfilingKeywordInitCounters(DetectEngineCtx *de_ctx) +void SCProfilingKeywordInitCounters(DetectEngineCtx *de_ctx) { if (profiling_keyword_enabled == 0) return; @@ -384,7 +389,7 @@ SCProfilingKeywordInitCounters(DetectEngineCtx *de_ctx) BUG_ON(de_ctx->profile_keyword_ctx_per_list[i]->data == NULL); } - SCLogPerf("Registered %"PRIu32" keyword profiling counters.", DETECT_TBLSIZE); + SCLogPerf("Registered %" PRIu32 " keyword profiling counters.", DETECT_TBLSIZE); } #endif /* PROFILING */ diff --git a/src/util-profiling-locks.c b/src/util-profiling-locks.c index 00f9ef652a30..b504c288b132 100644 --- a/src/util-profiling-locks.c +++ b/src/util-profiling-locks.c @@ -48,7 +48,7 @@ typedef struct LockRecord_ { char *func; // info int type; // info - int line; // hash + int line; // hash uint32_t cont; uint32_t ticks_cnt; @@ -61,15 +61,15 @@ pthread_mutex_t lock_records_mutex; static uint32_t LockRecordHash(HashListTable *ht, void *buf, uint16_t buflen) { - LockRecord *fn = (LockRecord *)buf; - uint32_t hash = strlen(fn->file) + fn->line; - uint16_t u; + LockRecord *fn = (LockRecord *)buf; + uint32_t hash = strlen(fn->file) + fn->line; + uint16_t u; - for (u = 0; u < strlen(fn->file); u++) { - hash += fn->file[u]; - } + for (u = 0; u < strlen(fn->file); u++) { + hash += fn->file[u]; + } - return hash % ht->array_size; + return hash % ht->array_size; } static char LockRecordCompare(void *buf1, uint16_t len1, void *buf2, uint16_t len2) @@ -110,7 +110,7 @@ int LockRecordInitHash(void) static void LockRecordAdd(ProfilingLock *l) { - LockRecord fn = { NULL, NULL, 0,0,0,0,0,0}, *ptr = &fn; + LockRecord fn = { NULL, NULL, 0, 0, 0, 0, 0, 0 }, *ptr = &fn; fn.file = l->file; fn.line = l->line; @@ -167,11 +167,13 @@ static void SCProfilingListLocks(void) return; } } else { - fp = stdout; + fp = stdout; } - fprintf(fp, "\n\nLock Cnt Avg ticks Max ticks Total ticks Cont Func\n"); - fprintf(fp, "------------------ ---------- --------- ------------ ------------ ------- ---------\n"); + fprintf(fp, "\n\nLock Cnt Avg ticks Max " + "ticks Total ticks Cont Func\n"); + fprintf(fp, "------------------ ---------- --------- " + "------------ ------------ ------- ---------\n"); uint64_t total = 0; uint32_t cont = 0; @@ -201,10 +203,11 @@ static void SCProfilingListLocks(void) } char str[128] = ""; - snprintf(str, sizeof(str), "(%s) %s:%d", lock,r->file, r->line); + snprintf(str, sizeof(str), "(%s) %s:%d", lock, r->file, r->line); - fprintf(fp, "%-50s %-10u %-9"PRIu64" %-12"PRIu64" %-12"PRIu64" %-7u %-s\n", - str, r->ticks_cnt, (uint64_t)((uint64_t)r->ticks_total/(uint64_t)r->ticks_cnt), r->ticks_max, r->ticks_total, r->cont, r->func); + fprintf(fp, "%-50s %-10u %-9" PRIu64 " %-12" PRIu64 " %-12" PRIu64 " %-7u %-s\n", str, + r->ticks_cnt, (uint64_t)((uint64_t)r->ticks_total / (uint64_t)r->ticks_cnt), + r->ticks_max, r->ticks_total, r->cont, r->func); total += r->ticks_total; cnt += r->ticks_cnt; @@ -213,8 +216,10 @@ static void SCProfilingListLocks(void) b = HashListTableGetListNext(b); } - fprintf(fp, "\nOverall: locks %"PRIu64", average cost %"PRIu64", contentions %"PRIu32", total ticks %"PRIu64"\n", - cnt, (uint64_t)((uint64_t)total/(uint64_t)cnt), cont, total); + fprintf(fp, + "\nOverall: locks %" PRIu64 ", average cost %" PRIu64 ", contentions %" PRIu32 + ", total ticks %" PRIu64 "\n", + cnt, (uint64_t)((uint64_t)total / (uint64_t)cnt), cont, total); fclose(fp); } @@ -239,4 +244,3 @@ void LockRecordFreeHash(void) #endif #endif - diff --git a/src/util-profiling-locks.h b/src/util-profiling-locks.h index 08d745a72182..ae17cbfafe86 100644 --- a/src/util-profiling-locks.h +++ b/src/util-profiling-locks.h @@ -33,4 +33,3 @@ void LockRecordFreeHash(void); #endif /* PROFILING */ #endif /* __UTIL_PROFILE_LOCKS_H__ */ - diff --git a/src/util-profiling-prefilter.c b/src/util-profiling-prefilter.c index 958846ae68c6..c5ce0f35972f 100644 --- a/src/util-profiling-prefilter.c +++ b/src/util-profiling-prefilter.c @@ -46,7 +46,7 @@ typedef struct SCProfilePrefilterData_ { typedef struct SCProfilePrefilterDetectCtx_ { uint32_t id; - uint32_t size; /**< size in elements */ + uint32_t size; /**< size in elements */ SCProfilePrefilterData *data; pthread_mutex_t data_m; } SCProfilePrefilterDetectCtx; @@ -70,8 +70,8 @@ void SCProfilingPrefilterGlobalInit(void) const char *log_dir; log_dir = ConfigGetLogDirectory(); - snprintf(profiling_file_name, sizeof(profiling_file_name), "%s/%s", - log_dir, filename); + snprintf(profiling_file_name, sizeof(profiling_file_name), "%s/%s", log_dir, + filename); const char *v = ConfNodeLookupChildValue(conf, "append"); if (v == NULL || ConfValIsTrue(v)) { @@ -90,12 +90,12 @@ static void DoDump(SCProfilePrefilterDetectCtx *rules_ctx, FILE *fp, const char { int i; fprintf(fp, " ----------------------------------------------" - "------------------------------------------------------" - "----------------------------\n"); + "------------------------------------------------------" + "----------------------------\n"); fprintf(fp, " Stats for: %s\n", name); fprintf(fp, " ----------------------------------------------" - "------------------------------------------------------" - "----------------------------\n"); + "------------------------------------------------------" + "----------------------------\n"); fprintf(fp, " %-32s %-15s %-15s %-15s %-15s %-15s %-15s %-15s %-15s %-15s\n", "Prefilter", "Ticks", "Called", "Max Ticks", "Avg", "Bytes", "Called", "Max Bytes", "Avg Bytes", "Ticks/Byte"); @@ -112,7 +112,7 @@ static void DoDump(SCProfilePrefilterDetectCtx *rules_ctx, FILE *fp, const char "\n"); for (i = 0; i < (int)rules_ctx->size; i++) { SCProfilePrefilterData *d = &rules_ctx->data[i]; - if (d == NULL || d->called== 0) + if (d == NULL || d->called == 0) continue; uint64_t ticks = d->total; @@ -137,8 +137,7 @@ static void DoDump(SCProfilePrefilterDetectCtx *rules_ctx, FILE *fp, const char } } -static void -SCProfilingPrefilterDump(DetectEngineCtx *de_ctx) +static void SCProfilingPrefilterDump(DetectEngineCtx *de_ctx) { FILE *fp; struct timeval tval; @@ -161,20 +160,22 @@ SCProfilingPrefilterDump(DetectEngineCtx *de_ctx) return; } } else { - fp = stdout; + fp = stdout; } fprintf(fp, " ----------------------------------------------" - "------------------------------------------------------" - "----------------------------\n"); - fprintf(fp, " Date: %" PRId32 "/%" PRId32 "/%04d -- " - "%02d:%02d:%02d\n", tms->tm_mon + 1, tms->tm_mday, tms->tm_year + 1900, - tms->tm_hour,tms->tm_min, tms->tm_sec); + "------------------------------------------------------" + "----------------------------\n"); + fprintf(fp, + " Date: %" PRId32 "/%" PRId32 "/%04d -- " + "%02d:%02d:%02d\n", + tms->tm_mon + 1, tms->tm_mday, tms->tm_year + 1900, tms->tm_hour, tms->tm_min, + tms->tm_sec); /* global stats first */ DoDump(de_ctx->profile_prefilter_ctx, fp, "total"); - fprintf(fp,"\n"); + fprintf(fp, "\n"); if (fp != stdout) fclose(fp); @@ -192,8 +193,7 @@ void SCProfilingPrefilterUpdateCounter(DetectEngineThreadCtx *det_ctx, int id, u uint64_t bytes, uint64_t bytes_called) { if (det_ctx != NULL && det_ctx->prefilter_perf_data != NULL && - id < (int)det_ctx->de_ctx->prefilter_id) - { + id < (int)det_ctx->de_ctx->prefilter_id) { SCProfilePrefilterData *p = &det_ctx->prefilter_perf_data[id]; p->called++; @@ -239,7 +239,8 @@ void SCProfilingPrefilterDestroyCtx(DetectEngineCtx *de_ctx) } } -void SCProfilingPrefilterThreadSetup(SCProfilePrefilterDetectCtx *ctx, DetectEngineThreadCtx *det_ctx) +void SCProfilingPrefilterThreadSetup( + SCProfilePrefilterDetectCtx *ctx, DetectEngineThreadCtx *det_ctx) { if (ctx == NULL) return; @@ -255,8 +256,8 @@ void SCProfilingPrefilterThreadSetup(SCProfilePrefilterDetectCtx *ctx, DetectEng static void SCProfilingPrefilterThreadMerge(DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx) { if (de_ctx == NULL || de_ctx->profile_prefilter_ctx == NULL || - de_ctx->profile_prefilter_ctx->data == NULL || det_ctx == NULL || - det_ctx->prefilter_perf_data == NULL) + de_ctx->profile_prefilter_ctx->data == NULL || det_ctx == NULL || + det_ctx->prefilter_perf_data == NULL) return; for (uint32_t i = 0; i < de_ctx->prefilter_id; i++) { @@ -293,8 +294,7 @@ void SCProfilingPrefilterThreadCleanup(DetectEngineThreadCtx *det_ctx) * * \param de_ctx The active DetectEngineCtx, used to get at the loaded rules. */ -void -SCProfilingPrefilterInitCounters(DetectEngineCtx *de_ctx) +void SCProfilingPrefilterInitCounters(DetectEngineCtx *de_ctx) { if (profiling_prefilter_enabled == 0) return; @@ -311,14 +311,14 @@ SCProfilingPrefilterInitCounters(DetectEngineCtx *de_ctx) BUG_ON(de_ctx->profile_prefilter_ctx->data == NULL); HashListTableBucket *hb = HashListTableGetListHead(de_ctx->prefilter_hash_table); - for ( ; hb != NULL; hb = HashListTableGetListNext(hb)) { + for (; hb != NULL; hb = HashListTableGetListNext(hb)) { PrefilterStore *ctx = HashListTableGetListData(hb); de_ctx->profile_prefilter_ctx->data[ctx->id].name = ctx->name; SCLogDebug("prefilter %s set up", de_ctx->profile_prefilter_ctx->data[ctx->id].name); } SCLogDebug("size alloc'd %u", (uint32_t)size * (uint32_t)sizeof(SCProfilePrefilterData)); - SCLogPerf("Registered %"PRIu32" prefilter profiling counters.", size); + SCLogPerf("Registered %" PRIu32 " prefilter profiling counters.", size); } #endif /* PROFILING */ diff --git a/src/util-profiling-rulegroups.c b/src/util-profiling-rulegroups.c index a6f0a68826a6..7996fa219d8a 100644 --- a/src/util-profiling-rulegroups.c +++ b/src/util-profiling-rulegroups.c @@ -73,8 +73,8 @@ void SCProfilingSghsGlobalInit(void) const char *log_dir; log_dir = ConfigGetLogDirectory(); - snprintf(profiling_file_name, sizeof(profiling_file_name), - "%s/%s", log_dir, filename); + snprintf(profiling_file_name, sizeof(profiling_file_name), "%s/%s", log_dir, + filename); const char *v = ConfNodeLookupChildValue(conf, "append"); if (v == NULL || ConfValIsTrue(v)) { @@ -135,15 +135,15 @@ static void DoDumpJSON(SCProfileSghDetectCtx *rules_ctx, FILE *fp, const char *n json_object_set_new(jsm, "avgmpms", json_real(avgmpms)); json_object_set_new(jsm, "mpm_match_cnt_max", json_integer(d->mpm_match_cnt_max)); json_object_set_new(jsm, "avgsigs", json_real(avgsigs)); - json_object_set_new(jsm, "post_prefilter_sigs_max", json_integer(d->post_prefilter_sigs_max)); + json_object_set_new( + jsm, "post_prefilter_sigs_max", json_integer(d->post_prefilter_sigs_max)); json_array_append_new(jsa, jsm); } } json_object_set_new(js, "rule_groups", jsa); - char *js_s = json_dumps(js, - JSON_PRESERVE_ORDER|JSON_COMPACT|JSON_ENSURE_ASCII| - JSON_ESCAPE_SLASH); + char *js_s = json_dumps( + js, JSON_PRESERVE_ORDER | JSON_COMPACT | JSON_ENSURE_ASCII | JSON_ESCAPE_SLASH); if (likely(js_s != NULL)) { fprintf(fp, "%s", js_s); free(js_s); @@ -162,20 +162,24 @@ static void DoDump(SCProfileSghDetectCtx *rules_ctx, FILE *fp, const char *name) tms = SCLocalTime(tval.tv_sec, &local_tm); fprintf(fp, " ----------------------------------------------" - "------------------------------------------------------" - "----------------------------\n"); - fprintf(fp, " Date: %" PRId32 "/%" PRId32 "/%04d -- " - "%02d:%02d:%02d\n", tms->tm_mon + 1, tms->tm_mday, tms->tm_year + 1900, - tms->tm_hour,tms->tm_min, tms->tm_sec); + "------------------------------------------------------" + "----------------------------\n"); + fprintf(fp, + " Date: %" PRId32 "/%" PRId32 "/%04d -- " + "%02d:%02d:%02d\n", + tms->tm_mon + 1, tms->tm_mday, tms->tm_year + 1900, tms->tm_hour, tms->tm_min, + tms->tm_sec); fprintf(fp, " ----------------------------------------------" - "------------------------------------------------------" - "----------------------------\n"); + "------------------------------------------------------" + "----------------------------\n"); fprintf(fp, " Stats for: %s %u\n", name, rules_ctx->cnt); fprintf(fp, " ----------------------------------------------" - "------------------------------------------------------" - "----------------------------\n"); - fprintf(fp, " %-16s %-15s %-15s %-15s %-15s %-15s %-15s %-15s\n", "Sgh", "Checks", "Non-MPM(gen)", "Non-Mpm(syn)", "MPM Matches", "MPM Match Max", "Post-Filter", "Post-Filter Max"); + "------------------------------------------------------" + "----------------------------\n"); + fprintf(fp, " %-16s %-15s %-15s %-15s %-15s %-15s %-15s %-15s\n", "Sgh", "Checks", + "Non-MPM(gen)", "Non-Mpm(syn)", "MPM Matches", "MPM Match Max", "Post-Filter", + "Post-Filter Max"); fprintf(fp, " ---------------- " "--------------- " "--------------- " @@ -184,7 +188,7 @@ static void DoDump(SCProfileSghDetectCtx *rules_ctx, FILE *fp, const char *name) "--------------- " "--------------- " "--------------- " - "\n"); + "\n"); for (i = 0; i < rules_ctx->cnt; i++) { SCProfileSghData *d = &rules_ctx->data[i]; if (d == NULL || d->checks == 0) @@ -201,21 +205,15 @@ static void DoDump(SCProfileSghDetectCtx *rules_ctx, FILE *fp, const char *name) } fprintf(fp, - " %-16u %-15"PRIu64" %-15"PRIu64" %-15"PRIu64" %-15.2f %-15"PRIu64" %-15.2f %-15"PRIu64"\n", - i, - d->checks, - d->non_mpm_generic, - d->non_mpm_syn, - avgmpms, - d->mpm_match_cnt_max, - avgsigs, - d->post_prefilter_sigs_max); + " %-16u %-15" PRIu64 " %-15" PRIu64 " %-15" PRIu64 " %-15.2f %-15" PRIu64 + " %-15.2f %-15" PRIu64 "\n", + i, d->checks, d->non_mpm_generic, d->non_mpm_syn, avgmpms, d->mpm_match_cnt_max, + avgsigs, d->post_prefilter_sigs_max); } - fprintf(fp,"\n"); + fprintf(fp, "\n"); } -static void -SCProfilingSghDump(DetectEngineCtx *de_ctx) +static void SCProfilingSghDump(DetectEngineCtx *de_ctx) { FILE *fp; @@ -232,7 +230,7 @@ SCProfilingSghDump(DetectEngineCtx *de_ctx) return; } } else { - fp = stdout; + fp = stdout; } if (profiling_rulegroup_json) { @@ -254,10 +252,10 @@ SCProfilingSghDump(DetectEngineCtx *de_ctx) * \param ticks Number of CPU ticks for this rule. * \param match Did the rule match? */ -void -SCProfilingSghUpdateCounter(DetectEngineThreadCtx *det_ctx, const SigGroupHead *sgh) +void SCProfilingSghUpdateCounter(DetectEngineThreadCtx *det_ctx, const SigGroupHead *sgh) { - if (det_ctx != NULL && det_ctx->sgh_perf_data != NULL && sgh->id < det_ctx->de_ctx->sgh_array_cnt) { + if (det_ctx != NULL && det_ctx->sgh_perf_data != NULL && + sgh->id < det_ctx->de_ctx->sgh_array_cnt) { SCProfileSghData *p = &det_ctx->sgh_perf_data[sgh->id]; p->checks++; @@ -323,8 +321,8 @@ void SCProfilingSghThreadSetup(SCProfileSghDetectCtx *ctx, DetectEngineThreadCtx static void SCProfilingSghThreadMerge(DetectEngineCtx *de_ctx, const DetectEngineThreadCtx *det_ctx) { if (de_ctx == NULL || de_ctx->profile_sgh_ctx == NULL || - de_ctx->profile_sgh_ctx->data == NULL || det_ctx == NULL || - det_ctx->sgh_perf_data == NULL) + de_ctx->profile_sgh_ctx->data == NULL || det_ctx == NULL || + det_ctx->sgh_perf_data == NULL) return; #define ADD(name) de_ctx->profile_sgh_ctx->data[i].name += det_ctx->sgh_perf_data[i].name @@ -336,10 +334,14 @@ static void SCProfilingSghThreadMerge(DetectEngineCtx *de_ctx, const DetectEngin ADD(post_prefilter_sigs_total); ADD(mpm_match_cnt_total); - if (det_ctx->sgh_perf_data[i].mpm_match_cnt_max > de_ctx->profile_sgh_ctx->data[i].mpm_match_cnt_max) - de_ctx->profile_sgh_ctx->data[i].mpm_match_cnt_max = det_ctx->sgh_perf_data[i].mpm_match_cnt_max; - if (det_ctx->sgh_perf_data[i].post_prefilter_sigs_max > de_ctx->profile_sgh_ctx->data[i].post_prefilter_sigs_max) - de_ctx->profile_sgh_ctx->data[i].post_prefilter_sigs_max = det_ctx->sgh_perf_data[i].post_prefilter_sigs_max; + if (det_ctx->sgh_perf_data[i].mpm_match_cnt_max > + de_ctx->profile_sgh_ctx->data[i].mpm_match_cnt_max) + de_ctx->profile_sgh_ctx->data[i].mpm_match_cnt_max = + det_ctx->sgh_perf_data[i].mpm_match_cnt_max; + if (det_ctx->sgh_perf_data[i].post_prefilter_sigs_max > + de_ctx->profile_sgh_ctx->data[i].post_prefilter_sigs_max) + de_ctx->profile_sgh_ctx->data[i].post_prefilter_sigs_max = + det_ctx->sgh_perf_data[i].post_prefilter_sigs_max; } #undef ADD } @@ -362,8 +364,7 @@ void SCProfilingSghThreadCleanup(DetectEngineThreadCtx *det_ctx) * * \param de_ctx The active DetectEngineCtx, used to get at the loaded rules. */ -void -SCProfilingSghInitCounters(DetectEngineCtx *de_ctx) +void SCProfilingSghInitCounters(DetectEngineCtx *de_ctx) { if (profiling_sghs_enabled == 0) return; @@ -376,7 +377,7 @@ SCProfilingSghInitCounters(DetectEngineCtx *de_ctx) de_ctx->profile_sgh_ctx->cnt = de_ctx->sgh_array_cnt; - SCLogPerf("Registered %"PRIu32" rulegroup profiling counters.", de_ctx->sgh_array_cnt); + SCLogPerf("Registered %" PRIu32 " rulegroup profiling counters.", de_ctx->sgh_array_cnt); } #endif /* PROFILING */ diff --git a/src/util-profiling-rules.c b/src/util-profiling-rules.c index 8262f71f4c8a..72be4fec9859 100644 --- a/src/util-profiling-rules.c +++ b/src/util-profiling-rules.c @@ -70,15 +70,10 @@ enum { SC_PROFILING_RULES_SORT_BY_AVG_TICKS_NO_MATCH, }; -static int profiling_rules_sort_orders[8] = { - SC_PROFILING_RULES_SORT_BY_TICKS, - SC_PROFILING_RULES_SORT_BY_AVG_TICKS, - SC_PROFILING_RULES_SORT_BY_AVG_TICKS_MATCH, - SC_PROFILING_RULES_SORT_BY_AVG_TICKS_NO_MATCH, - SC_PROFILING_RULES_SORT_BY_CHECKS, - SC_PROFILING_RULES_SORT_BY_MATCHES, - SC_PROFILING_RULES_SORT_BY_MAX_TICKS, - -1 }; +static int profiling_rules_sort_orders[8] = { SC_PROFILING_RULES_SORT_BY_TICKS, + SC_PROFILING_RULES_SORT_BY_AVG_TICKS, SC_PROFILING_RULES_SORT_BY_AVG_TICKS_MATCH, + SC_PROFILING_RULES_SORT_BY_AVG_TICKS_NO_MATCH, SC_PROFILING_RULES_SORT_BY_CHECKS, + SC_PROFILING_RULES_SORT_BY_MATCHES, SC_PROFILING_RULES_SORT_BY_MAX_TICKS, -1 }; /** * Maximum number of rules to dump. @@ -87,9 +82,10 @@ static uint32_t profiling_rules_limit = UINT32_MAX; void SCProfilingRulesGlobalInit(void) { -#define SET_ONE(x) { \ - profiling_rules_sort_orders[0] = (x); \ - profiling_rules_sort_orders[1] = -1; \ +#define SET_ONE(x) \ + { \ + profiling_rules_sort_orders[0] = (x); \ + profiling_rules_sort_orders[1] = -1; \ } ConfNode *conf; @@ -104,26 +100,19 @@ void SCProfilingRulesGlobalInit(void) if (val != NULL) { if (strcmp(val, "ticks") == 0) { SET_ONE(SC_PROFILING_RULES_SORT_BY_TICKS); - } - else if (strcmp(val, "avgticks") == 0) { + } else if (strcmp(val, "avgticks") == 0) { SET_ONE(SC_PROFILING_RULES_SORT_BY_AVG_TICKS); - } - else if (strcmp(val, "avgticks_match") == 0) { + } else if (strcmp(val, "avgticks_match") == 0) { SET_ONE(SC_PROFILING_RULES_SORT_BY_AVG_TICKS_MATCH); - } - else if (strcmp(val, "avgticks_no_match") == 0) { + } else if (strcmp(val, "avgticks_no_match") == 0) { SET_ONE(SC_PROFILING_RULES_SORT_BY_AVG_TICKS_NO_MATCH); - } - else if (strcmp(val, "checks") == 0) { + } else if (strcmp(val, "checks") == 0) { SET_ONE(SC_PROFILING_RULES_SORT_BY_CHECKS); - } - else if (strcmp(val, "matches") == 0) { + } else if (strcmp(val, "matches") == 0) { SET_ONE(SC_PROFILING_RULES_SORT_BY_MATCHES); - } - else if (strcmp(val, "maxticks") == 0) { + } else if (strcmp(val, "maxticks") == 0) { SET_ONE(SC_PROFILING_RULES_SORT_BY_MAX_TICKS); - } - else { + } else { SCLogError("Invalid profiling sort order: %s", val); exit(EXIT_FAILURE); } @@ -131,8 +120,8 @@ void SCProfilingRulesGlobalInit(void) val = ConfNodeLookupChildValue(conf, "limit"); if (val != NULL) { - if (StringParseUint32(&profiling_rules_limit, 10, - (uint16_t)strlen(val), val) <= 0) { + if (StringParseUint32(&profiling_rules_limit, 10, (uint16_t)strlen(val), val) <= + 0) { SCLogError("Invalid limit: %s", val); exit(EXIT_FAILURE); } @@ -143,8 +132,8 @@ void SCProfilingRulesGlobalInit(void) const char *log_dir; log_dir = ConfigGetLogDirectory(); - snprintf(profiling_file_name, sizeof(profiling_file_name), - "%s/%s", log_dir, filename); + snprintf(profiling_file_name, sizeof(profiling_file_name), "%s/%s", log_dir, + filename); const char *v = ConfNodeLookupChildValue(conf, "append"); if (v == NULL || ConfValIsTrue(v)) { @@ -166,8 +155,7 @@ void SCProfilingRulesGlobalInit(void) /** * \brief Qsort comparison function to sort by ticks. */ -static int -SCProfileSummarySortByTicks(const void *a, const void *b) +static int SCProfileSummarySortByTicks(const void *a, const void *b) { const SCProfileSummary *s0 = a; const SCProfileSummary *s1 = b; @@ -180,8 +168,7 @@ SCProfileSummarySortByTicks(const void *a, const void *b) /** * \brief Qsort comparison function to sort by average ticks per match. */ -static int -SCProfileSummarySortByAvgTicksMatch(const void *a, const void *b) +static int SCProfileSummarySortByAvgTicksMatch(const void *a, const void *b) { const SCProfileSummary *s0 = a; const SCProfileSummary *s1 = b; @@ -194,8 +181,7 @@ SCProfileSummarySortByAvgTicksMatch(const void *a, const void *b) /** * \brief Qsort comparison function to sort by average ticks per non match. */ -static int -SCProfileSummarySortByAvgTicksNoMatch(const void *a, const void *b) +static int SCProfileSummarySortByAvgTicksNoMatch(const void *a, const void *b) { const SCProfileSummary *s0 = a; const SCProfileSummary *s1 = b; @@ -208,8 +194,7 @@ SCProfileSummarySortByAvgTicksNoMatch(const void *a, const void *b) /** * \brief Qsort comparison function to sort by average ticks. */ -static int -SCProfileSummarySortByAvgTicks(const void *a, const void *b) +static int SCProfileSummarySortByAvgTicks(const void *a, const void *b) { const SCProfileSummary *s0 = a; const SCProfileSummary *s1 = b; @@ -222,8 +207,7 @@ SCProfileSummarySortByAvgTicks(const void *a, const void *b) /** * \brief Qsort comparison function to sort by checks. */ -static int -SCProfileSummarySortByChecks(const void *a, const void *b) +static int SCProfileSummarySortByChecks(const void *a, const void *b) { const SCProfileSummary *s0 = a; const SCProfileSummary *s1 = b; @@ -236,8 +220,7 @@ SCProfileSummarySortByChecks(const void *a, const void *b) /** * \brief Qsort comparison function to sort by matches. */ -static int -SCProfileSummarySortByMatches(const void *a, const void *b) +static int SCProfileSummarySortByMatches(const void *a, const void *b) { const SCProfileSummary *s0 = a; const SCProfileSummary *s1 = b; @@ -250,8 +233,7 @@ SCProfileSummarySortByMatches(const void *a, const void *b) /** * \brief Qsort comparison function to sort by max ticks. */ -static int -SCProfileSummarySortByMaxTicks(const void *a, const void *b) +static int SCProfileSummarySortByMaxTicks(const void *a, const void *b) { const SCProfileSummary *s0 = a; const SCProfileSummary *s1 = b; @@ -303,10 +285,10 @@ static json_t *BuildJson( json_object_set_new(jsm, "ticks_max", json_integer(summary[i].max)); json_object_set_new(jsm, "ticks_avg", json_integer(summary[i].avgticks)); json_object_set_new(jsm, "ticks_avg_match", json_integer(summary[i].avgticks_match)); - json_object_set_new(jsm, "ticks_avg_nomatch", json_integer(summary[i].avgticks_no_match)); + json_object_set_new( + jsm, "ticks_avg_nomatch", json_integer(summary[i].avgticks_no_match)); - double percent = (long double)summary[i].ticks / - (long double)total_ticks * 100; + double percent = (long double)summary[i].ticks / (long double)total_ticks * 100; json_object_set_new(jsm, "percent", json_integer(percent)); json_array_append_new(jsa, jsm); } @@ -321,9 +303,8 @@ static void DumpJson(FILE *fp, SCProfileSummary *summary, uint32_t count, uint64 json_t *js = BuildJson(summary, count, total_ticks, sort_desc); if (unlikely(js == NULL)) return; - char *js_s = json_dumps(js, - JSON_PRESERVE_ORDER|JSON_COMPACT|JSON_ENSURE_ASCII| - JSON_ESCAPE_SLASH); + char *js_s = json_dumps( + js, JSON_PRESERVE_ORDER | JSON_COMPACT | JSON_ENSURE_ASCII | JSON_ESCAPE_SLASH); if (unlikely(js_s == NULL)) return; @@ -332,8 +313,7 @@ static void DumpJson(FILE *fp, SCProfileSummary *summary, uint32_t count, uint64 json_decref(js); } -static void DumpText(FILE *fp, SCProfileSummary *summary, - uint32_t count, uint64_t total_ticks, +static void DumpText(FILE *fp, SCProfileSummary *summary, uint32_t count, uint64_t total_ticks, const char *sort_desc) { uint32_t i; @@ -344,27 +324,31 @@ static void DumpText(FILE *fp, SCProfileSummary *summary, tms = SCLocalTime(tval.tv_sec, &local_tm); fprintf(fp, " ----------------------------------------------" - "----------------------------\n"); - fprintf(fp, " Date: %" PRId32 "/%" PRId32 "/%04d -- " - "%02d:%02d:%02d.", tms->tm_mon + 1, tms->tm_mday, tms->tm_year + 1900, - tms->tm_hour,tms->tm_min, tms->tm_sec); + "----------------------------\n"); + fprintf(fp, + " Date: %" PRId32 "/%" PRId32 "/%04d -- " + "%02d:%02d:%02d.", + tms->tm_mon + 1, tms->tm_mday, tms->tm_year + 1900, tms->tm_hour, tms->tm_min, + tms->tm_sec); fprintf(fp, " Sorted by: %s.\n", sort_desc); fprintf(fp, " ----------------------------------------------" - "----------------------------\n"); - fprintf(fp, " %-8s %-12s %-8s %-8s %-12s %-6s %-8s %-8s %-11s %-11s %-11s %-11s\n", "Num", "Rule", "Gid", "Rev", "Ticks", "%", "Checks", "Matches", "Max Ticks", "Avg Ticks", "Avg Match", "Avg No Match"); + "----------------------------\n"); + fprintf(fp, " %-8s %-12s %-8s %-8s %-12s %-6s %-8s %-8s %-11s %-11s %-11s %-11s\n", "Num", + "Rule", "Gid", "Rev", "Ticks", "%", "Checks", "Matches", "Max Ticks", "Avg Ticks", + "Avg Match", "Avg No Match"); fprintf(fp, " -------- " - "------------ " - "-------- " - "-------- " - "------------ " - "------ " - "-------- " - "-------- " - "----------- " - "----------- " - "----------- " - "-------------- " - "\n"); + "------------ " + "-------- " + "-------- " + "------------ " + "------ " + "-------- " + "-------- " + "----------- " + "----------- " + "----------- " + "-------------- " + "\n"); for (i = 0; i < MIN(count, profiling_rules_limit); i++) { /* Stop dumping when we hit our first rule with 0 checks. Due @@ -373,25 +357,16 @@ static void DumpText(FILE *fp, SCProfileSummary *summary, if (summary[i].checks == 0) break; - double percent = (long double)summary[i].ticks / - (long double)total_ticks * 100; + double percent = (long double)summary[i].ticks / (long double)total_ticks * 100; fprintf(fp, - " %-8"PRIu32" %-12u %-8"PRIu32" %-8"PRIu32" %-12"PRIu64" %-6.2f %-8"PRIu64" %-8"PRIu64" %-11"PRIu64" %-11.2f %-11.2f %-11.2f\n", - i + 1, - summary[i].sid, - summary[i].gid, - summary[i].rev, - summary[i].ticks, - percent, - summary[i].checks, - summary[i].matches, - summary[i].max, - summary[i].avgticks, - summary[i].avgticks_match, - summary[i].avgticks_no_match); + " %-8" PRIu32 " %-12u %-8" PRIu32 " %-8" PRIu32 " %-12" PRIu64 " %-6.2f %-8" PRIu64 + " %-8" PRIu64 " %-11" PRIu64 " %-11.2f %-11.2f %-11.2f\n", + i + 1, summary[i].sid, summary[i].gid, summary[i].rev, summary[i].ticks, percent, + summary[i].checks, summary[i].matches, summary[i].max, summary[i].avgticks, + summary[i].avgticks_match, summary[i].avgticks_no_match); } - fprintf(fp,"\n"); + fprintf(fp, "\n"); } /** @@ -450,13 +425,14 @@ static void *SCProfilingRuleDump(SCProfileDetectCtx *rules_ctx, int file_output) summary[i].ticks_match = rules_ctx->data[i].ticks_match; summary[i].ticks_no_match = rules_ctx->data[i].ticks_no_match; if (summary[i].ticks_match > 0) { - summary[i].avgticks_match = (long double)summary[i].ticks_match / - (long double)summary[i].matches; + summary[i].avgticks_match = + (long double)summary[i].ticks_match / (long double)summary[i].matches; } if (summary[i].ticks_no_match > 0) { - summary[i].avgticks_no_match = (long double)summary[i].ticks_no_match / - ((long double)summary[i].checks - (long double)summary[i].matches); + summary[i].avgticks_no_match = + (long double)summary[i].ticks_no_match / + ((long double)summary[i].checks - (long double)summary[i].matches); } total_ticks += summary[i].ticks; } @@ -466,28 +442,23 @@ static void *SCProfilingRuleDump(SCProfileDetectCtx *rules_ctx, int file_output) const char *sort_desc = NULL; switch (*order) { case SC_PROFILING_RULES_SORT_BY_TICKS: - qsort(summary, count, sizeof(SCProfileSummary), - SCProfileSummarySortByTicks); + qsort(summary, count, sizeof(SCProfileSummary), SCProfileSummarySortByTicks); sort_desc = "ticks"; break; case SC_PROFILING_RULES_SORT_BY_AVG_TICKS: - qsort(summary, count, sizeof(SCProfileSummary), - SCProfileSummarySortByAvgTicks); + qsort(summary, count, sizeof(SCProfileSummary), SCProfileSummarySortByAvgTicks); sort_desc = "average ticks"; break; case SC_PROFILING_RULES_SORT_BY_CHECKS: - qsort(summary, count, sizeof(SCProfileSummary), - SCProfileSummarySortByChecks); + qsort(summary, count, sizeof(SCProfileSummary), SCProfileSummarySortByChecks); sort_desc = "number of checks"; break; case SC_PROFILING_RULES_SORT_BY_MATCHES: - qsort(summary, count, sizeof(SCProfileSummary), - SCProfileSummarySortByMatches); + qsort(summary, count, sizeof(SCProfileSummary), SCProfileSummarySortByMatches); sort_desc = "number of matches"; break; case SC_PROFILING_RULES_SORT_BY_MAX_TICKS: - qsort(summary, count, sizeof(SCProfileSummary), - SCProfileSummarySortByMaxTicks); + qsort(summary, count, sizeof(SCProfileSummary), SCProfileSummarySortByMaxTicks); sort_desc = "max ticks"; break; case SC_PROFILING_RULES_SORT_BY_AVG_TICKS_MATCH: @@ -529,8 +500,7 @@ static void *SCProfilingRuleDump(SCProfileDetectCtx *rules_ctx, int file_output) * * \retval Returns the ID of the counter on success, 0 on failure. */ -static uint16_t -SCProfilingRegisterRuleCounter(SCProfileDetectCtx *ctx) +static uint16_t SCProfilingRegisterRuleCounter(SCProfileDetectCtx *ctx) { ctx->size++; return ctx->id++; @@ -543,8 +513,8 @@ SCProfilingRegisterRuleCounter(SCProfileDetectCtx *ctx) * \param ticks Number of CPU ticks for this rule. * \param match Did the rule match? */ -void -SCProfilingRuleUpdateCounter(DetectEngineThreadCtx *det_ctx, uint16_t id, uint64_t ticks, int match) +void SCProfilingRuleUpdateCounter( + DetectEngineThreadCtx *det_ctx, uint16_t id, uint64_t ticks, int match) { if (det_ctx != NULL && det_ctx->rule_perf_data != NULL && det_ctx->rule_perf_data_size > id) { SCProfileData *p = &det_ctx->rule_perf_data[id]; @@ -585,7 +555,7 @@ void SCProfilingRuleDestroyCtx(SCProfileDetectCtx *ctx) void SCProfilingRuleThreadSetup(SCProfileDetectCtx *ctx, DetectEngineThreadCtx *det_ctx) { - if (ctx == NULL|| ctx->size == 0) + if (ctx == NULL || ctx->size == 0) return; SCProfileData *a = SCCalloc(ctx->size, sizeof(SCProfileData)); @@ -647,8 +617,7 @@ void SCProfilingRuleThreatAggregate(DetectEngineThreadCtx *det_ctx) * * \param de_ctx The active DetectEngineCtx, used to get at the loaded rules. */ -void -SCProfilingRuleInitCounters(DetectEngineCtx *de_ctx) +void SCProfilingRuleInitCounters(DetectEngineCtx *de_ctx) { if (profiling_rules_enabled == 0) return; @@ -677,7 +646,7 @@ SCProfilingRuleInitCounters(DetectEngineCtx *de_ctx) } } - SCLogPerf("Registered %"PRIu32" rule profiling counters.", count); + SCLogPerf("Registered %" PRIu32 " rule profiling counters.", count); } json_t *SCProfileRuleTriggerDump(DetectEngineCtx *de_ctx) @@ -686,4 +655,3 @@ json_t *SCProfileRuleTriggerDump(DetectEngineCtx *de_ctx) } #endif /* PROFILING */ - diff --git a/src/util-profiling.c b/src/util-profiling.c index 5d4bcc8905ce..f71c244f834e 100644 --- a/src/util-profiling.c +++ b/src/util-profiling.c @@ -41,7 +41,7 @@ #define MIN(a, b) (((a) < (b)) ? (a) : (b)) #endif -#define DEFAULT_LOG_FILENAME "profile.log" +#define DEFAULT_LOG_FILENAME "profile.log" #define DEFAULT_LOG_MODE_APPEND "yes" static pthread_mutex_t packet_profile_lock; @@ -112,27 +112,26 @@ static SC_ATOMIC_DECLARE(uint64_t, samples); thread_local int profiling_rules_entered = 0; void SCProfilingDumpPacketStats(void); -const char * PacketProfileDetectIdToString(PacketProfileDetectId id); +const char *PacketProfileDetectIdToString(PacketProfileDetectId id); const char *PacketProfileLoggerIdToString(LoggerId id); static void PrintCSVHeader(void); static void FormatNumber(uint64_t num, char *str, size_t size) { if (num < 1000UL) - snprintf(str, size, "%"PRIu64, num); + snprintf(str, size, "%" PRIu64, num); else if (num < 1000000UL) - snprintf(str, size, "%3.1fk", (float)num/1000UL); + snprintf(str, size, "%3.1fk", (float)num / 1000UL); else if (num < 1000000000UL) - snprintf(str, size, "%3.1fm", (float)num/1000000UL); + snprintf(str, size, "%3.1fm", (float)num / 1000000UL); else - snprintf(str, size, "%3.1fb", (float)num/1000000000UL); + snprintf(str, size, "%3.1fb", (float)num / 1000000000UL); } /** * \brief Initialize profiling. */ -void -SCProfilingInit(void) +void SCProfilingInit(void) { ConfNode *conf; @@ -175,8 +174,8 @@ SCProfilingInit(void) const char *log_dir; log_dir = ConfigGetLogDirectory(); - snprintf(profiling_packets_file_name, sizeof(profiling_packets_file_name), - "%s/%s", log_dir, filename); + snprintf(profiling_packets_file_name, sizeof(profiling_packets_file_name), "%s/%s", + log_dir, filename); const char *v = ConfNodeLookupChildValue(conf, "append"); if (v == NULL || ConfValIsTrue(v)) { @@ -253,14 +252,12 @@ SCProfilingInit(void) #endif } } - } /** * \brief Free resources used by profiling. */ -void -SCProfilingDestroy(void) +void SCProfilingDestroy(void) { if (profiling_packets_enabled) { pthread_mutex_destroy(&packet_profile_lock); @@ -285,8 +282,7 @@ SCProfilingDestroy(void) #endif } -void -SCProfilingDump(void) +void SCProfilingDump(void) { SCProfilingDumpPacketStats(); SCLogPerf("Done dumping profiling data."); @@ -306,12 +302,13 @@ static void DumpFlowWorkerIP(FILE *fp, int ipv, uint64_t total) } FormatNumber(pd->tot, totalstr, sizeof(totalstr)); - double percent = (long double)pd->tot / - (long double)total * 100; + double percent = (long double)pd->tot / (long double)total * 100; - fprintf(fp, "%-20s IPv%d %3d %12"PRIu64" %12"PRIu64" %12"PRIu64" %12"PRIu64" %12s %-6.2f\n", - ProfileFlowWorkerIdToString(fwi), ipv, p, pd->cnt, - pd->min, pd->max, (uint64_t)(pd->tot / pd->cnt), totalstr, percent); + fprintf(fp, + "%-20s IPv%d %3d %12" PRIu64 " %12" PRIu64 " %12" PRIu64 + " %12" PRIu64 " %12s %-6.2f\n", + ProfileFlowWorkerIdToString(fwi), ipv, p, pd->cnt, pd->min, pd->max, + (uint64_t)(pd->tot / pd->cnt), totalstr, percent); } } } @@ -331,10 +328,10 @@ static void DumpFlowWorker(FILE *fp) } } - fprintf(fp, "\n%-20s %-6s %-5s %-12s %-12s %-12s %-12s\n", - "Flow Worker", "IP ver", "Proto", "cnt", "min", "max", "avg"); - fprintf(fp, "%-20s %-6s %-5s %-12s %-12s %-12s %-12s\n", - "--------------------", "------", "-----", "----------", "------------", "------------", "-----------"); + fprintf(fp, "\n%-20s %-6s %-5s %-12s %-12s %-12s %-12s\n", "Flow Worker", "IP ver", + "Proto", "cnt", "min", "max", "avg"); + fprintf(fp, "%-20s %-6s %-5s %-12s %-12s %-12s %-12s\n", "--------------------", + "------", "-----", "----------", "------------", "------------", "-----------"); DumpFlowWorkerIP(fp, 4, total); DumpFlowWorkerIP(fp, 6, total); fprintf(fp, "Note: %s includes app-layer for TCP\n", @@ -358,15 +355,15 @@ void SCProfilingDumpPacketStats(void) return; } } else { - fp = stdout; + fp = stdout; } fprintf(fp, "\n\nPacket profile dump:\n"); - fprintf(fp, "\n%-6s %-5s %-12s %-12s %-12s %-12s %-12s %-3s\n", - "IP ver", "Proto", "cnt", "min", "max", "avg", "tot", "%%"); - fprintf(fp, "%-6s %-5s %-12s %-12s %-12s %-12s %-12s %-3s\n", - "------", "-----", "----------", "------------", "------------", "-----------", "-----------", "---"); + fprintf(fp, "\n%-6s %-5s %-12s %-12s %-12s %-12s %-12s %-3s\n", "IP ver", "Proto", + "cnt", "min", "max", "avg", "tot", "%%"); + fprintf(fp, "%-6s %-5s %-12s %-12s %-12s %-12s %-12s %-3s\n", "------", "-----", + "----------", "------------", "------------", "-----------", "-----------", "---"); total = 0; for (int i = 0; i < 257; i++) { SCProfilePacketData *pd = &packet_profile_data4[i]; @@ -382,11 +379,12 @@ void SCProfilingDumpPacketStats(void) } FormatNumber(pd->tot, totalstr, sizeof(totalstr)); - double percent = (long double)pd->tot / - (long double)total * 100; + double percent = (long double)pd->tot / (long double)total * 100; - fprintf(fp, " IPv4 %3d %12"PRIu64" %12"PRIu64" %12"PRIu64" %12"PRIu64" %12s %6.2f\n", i, pd->cnt, - pd->min, pd->max, (uint64_t)(pd->tot / pd->cnt), totalstr, percent); + fprintf(fp, + " IPv4 %3d %12" PRIu64 " %12" PRIu64 " %12" PRIu64 " %12" PRIu64 + " %12s %6.2f\n", + i, pd->cnt, pd->min, pd->max, (uint64_t)(pd->tot / pd->cnt), totalstr, percent); } for (int i = 0; i < 257; i++) { @@ -396,11 +394,12 @@ void SCProfilingDumpPacketStats(void) } FormatNumber(pd->tot, totalstr, sizeof(totalstr)); - double percent = (long double)pd->tot / - (long double)total * 100; + double percent = (long double)pd->tot / (long double)total * 100; - fprintf(fp, " IPv6 %3d %12"PRIu64" %12"PRIu64" %12"PRIu64" %12"PRIu64" %12s %6.2f\n", i, pd->cnt, - pd->min, pd->max, (uint64_t)(pd->tot / pd->cnt), totalstr, percent); + fprintf(fp, + " IPv6 %3d %12" PRIu64 " %12" PRIu64 " %12" PRIu64 " %12" PRIu64 + " %12s %6.2f\n", + i, pd->cnt, pd->min, pd->max, (uint64_t)(pd->tot / pd->cnt), totalstr, percent); } fprintf(fp, "Note: Protocol 256 tracks pseudo/tunnel packets.\n"); @@ -409,16 +408,18 @@ void SCProfilingDumpPacketStats(void) fprintf(fp, "\n%-24s %-6s %-5s %-12s %-12s %-12s %-12s %-12s %-3s", "Thread Module", "IP ver", "Proto", "cnt", "min", "max", "avg", "tot", "%%"); #ifdef PROFILE_LOCKING - fprintf(fp, " %-10s %-10s %-12s %-12s %-10s %-10s %-12s %-12s\n", - "locks", "ticks", "cont.", "cont.avg", "slocks", "sticks", "scont.", "scont.avg"); + fprintf(fp, " %-10s %-10s %-12s %-12s %-10s %-10s %-12s %-12s\n", "locks", + "ticks", "cont.", "cont.avg", "slocks", "sticks", "scont.", "scont.avg"); #else fprintf(fp, "\n"); #endif fprintf(fp, "%-24s %-6s %-5s %-12s %-12s %-12s %-12s %-12s %-3s", - "------------------------", "------", "-----", "----------", "------------", "------------", "-----------", "-----------", "---"); + "------------------------", "------", "-----", "----------", "------------", + "------------", "-----------", "-----------", "---"); #ifdef PROFILE_LOCKING - fprintf(fp, " %-10s %-10s %-12s %-12s %-10s %-10s %-12s %-12s\n", - "--------", "--------", "----------", "-----------", "--------", "--------", "------------", "-----------"); + fprintf(fp, " %-10s %-10s %-12s %-12s %-10s %-10s %-12s %-12s\n", "--------", + "--------", "----------", "-----------", "--------", "--------", "------------", + "-----------"); #else fprintf(fp, "\n"); #endif @@ -447,14 +448,21 @@ void SCProfilingDumpPacketStats(void) } FormatNumber(pd->tot, totalstr, sizeof(totalstr)); - double percent = (long double)pd->tot / - (long double)total * 100; + double percent = (long double)pd->tot / (long double)total * 100; - fprintf(fp, "%-24s IPv4 %3d %12"PRIu64" %12"PRIu64" %12"PRIu64" %12"PRIu64" %12s %6.2f", - TmModuleTmmIdToString(m), p, pd->cnt, pd->min, pd->max, (uint64_t)(pd->tot / pd->cnt), totalstr, percent); + fprintf(fp, + "%-24s IPv4 %3d %12" PRIu64 " %12" PRIu64 " %12" PRIu64 + " %12" PRIu64 " %12s %6.2f", + TmModuleTmmIdToString(m), p, pd->cnt, pd->min, pd->max, + (uint64_t)(pd->tot / pd->cnt), totalstr, percent); #ifdef PROFILE_LOCKING - fprintf(fp, " %10.2f %12"PRIu64" %12"PRIu64" %10.2f %10.2f %12"PRIu64" %12"PRIu64" %10.2f\n", - (float)pd->lock/pd->cnt, (uint64_t)pd->ticks/pd->cnt, pd->contention, (float)pd->contention/pd->cnt, (float)pd->slock/pd->cnt, (uint64_t)pd->sticks/pd->cnt, pd->scontention, (float)pd->scontention/pd->cnt); + fprintf(fp, + " %10.2f %12" PRIu64 " %12" PRIu64 " %10.2f %10.2f %12" PRIu64 + " %12" PRIu64 " %10.2f\n", + (float)pd->lock / pd->cnt, (uint64_t)pd->ticks / pd->cnt, pd->contention, + (float)pd->contention / pd->cnt, (float)pd->slock / pd->cnt, + (uint64_t)pd->sticks / pd->cnt, pd->scontention, + (float)pd->scontention / pd->cnt); #else fprintf(fp, "\n"); #endif @@ -472,11 +480,13 @@ void SCProfilingDumpPacketStats(void) } FormatNumber(pd->tot, totalstr, sizeof(totalstr)); - double percent = (long double)pd->tot / - (long double)total * 100; + double percent = (long double)pd->tot / (long double)total * 100; - fprintf(fp, "%-24s IPv6 %3d %12"PRIu64" %12"PRIu64" %12"PRIu64" %12"PRIu64" %12s %6.2f\n", - TmModuleTmmIdToString(m), p, pd->cnt, pd->min, pd->max, (uint64_t)(pd->tot / pd->cnt), totalstr, percent); + fprintf(fp, + "%-24s IPv6 %3d %12" PRIu64 " %12" PRIu64 " %12" PRIu64 + " %12" PRIu64 " %12s %6.2f\n", + TmModuleTmmIdToString(m), p, pd->cnt, pd->min, pd->max, + (uint64_t)(pd->tot / pd->cnt), totalstr, percent); } } @@ -484,10 +494,10 @@ void SCProfilingDumpPacketStats(void) fprintf(fp, "\nPer App layer parser stats:\n"); - fprintf(fp, "\n%-20s %-6s %-5s %-12s %-12s %-12s %-12s\n", - "App Layer", "IP ver", "Proto", "cnt", "min", "max", "avg"); - fprintf(fp, "%-20s %-6s %-5s %-12s %-12s %-12s %-12s\n", - "--------------------", "------", "-----", "----------", "------------", "------------", "-----------"); + fprintf(fp, "\n%-20s %-6s %-5s %-12s %-12s %-12s %-12s\n", "App Layer", "IP ver", + "Proto", "cnt", "min", "max", "avg"); + fprintf(fp, "%-20s %-6s %-5s %-12s %-12s %-12s %-12s\n", "--------------------", + "------", "-----", "----------", "------------", "------------", "-----------"); total = 0; for (AppProto a = 0; a < ALPROTO_MAX; a++) { @@ -507,8 +517,7 @@ void SCProfilingDumpPacketStats(void) } FormatNumber(pd->tot, totalstr, sizeof(totalstr)); - double percent = (long double)pd->tot / - (long double)total * 100; + double percent = (long double)pd->tot / (long double)total * 100; fprintf(fp, "%-20s IPv4 %3d %12" PRIu64 " %12" PRIu64 " %12" PRIu64 @@ -526,8 +535,7 @@ void SCProfilingDumpPacketStats(void) } FormatNumber(pd->tot, totalstr, sizeof(totalstr)); - double percent = (long double)pd->tot / - (long double)total * 100; + double percent = (long double)pd->tot / (long double)total * 100; fprintf(fp, "%-20s IPv6 %3d %12" PRIu64 " %12" PRIu64 " %12" PRIu64 @@ -546,8 +554,11 @@ void SCProfilingDumpPacketStats(void) } FormatNumber(pd->tot, totalstr, sizeof(totalstr)); - fprintf(fp, "%-20s IPv4 %3d %12"PRIu64" %12"PRIu64" %12"PRIu64" %12"PRIu64" %12s\n", - "Proto detect", p, pd->cnt, pd->min, pd->max, (uint64_t)(pd->tot / pd->cnt), totalstr); + fprintf(fp, + "%-20s IPv4 %3d %12" PRIu64 " %12" PRIu64 " %12" PRIu64 + " %12" PRIu64 " %12s\n", + "Proto detect", p, pd->cnt, pd->min, pd->max, (uint64_t)(pd->tot / pd->cnt), + totalstr); } for (int p = 0; p < 257; p++) { @@ -557,8 +568,11 @@ void SCProfilingDumpPacketStats(void) } FormatNumber(pd->tot, totalstr, sizeof(totalstr)); - fprintf(fp, "%-20s IPv6 %3d %12"PRIu64" %12"PRIu64" %12"PRIu64" %12"PRIu64" %12s\n", - "Proto detect", p, pd->cnt, pd->min, pd->max, (uint64_t)(pd->tot / pd->cnt), totalstr); + fprintf(fp, + "%-20s IPv6 %3d %12" PRIu64 " %12" PRIu64 " %12" PRIu64 + " %12" PRIu64 " %12s\n", + "Proto detect", p, pd->cnt, pd->min, pd->max, (uint64_t)(pd->tot / pd->cnt), + totalstr); } } @@ -576,16 +590,18 @@ void SCProfilingDumpPacketStats(void) fprintf(fp, "\n%-24s %-6s %-5s %-12s %-12s %-12s %-12s %-12s %-3s", "Log Thread Module", "IP ver", "Proto", "cnt", "min", "max", "avg", "tot", "%%"); #ifdef PROFILE_LOCKING - fprintf(fp, " %-10s %-10s %-12s %-12s %-10s %-10s %-12s %-12s\n", - "locks", "ticks", "cont.", "cont.avg", "slocks", "sticks", "scont.", "scont.avg"); + fprintf(fp, " %-10s %-10s %-12s %-12s %-10s %-10s %-12s %-12s\n", "locks", + "ticks", "cont.", "cont.avg", "slocks", "sticks", "scont.", "scont.avg"); #else fprintf(fp, "\n"); #endif fprintf(fp, "%-24s %-6s %-5s %-12s %-12s %-12s %-12s %-12s %-3s", - "------------------------", "------", "-----", "----------", "------------", "------------", "-----------", "-----------", "---"); + "------------------------", "------", "-----", "----------", "------------", + "------------", "-----------", "-----------", "---"); #ifdef PROFILE_LOCKING - fprintf(fp, " %-10s %-10s %-12s %-12s %-10s %-10s %-12s %-12s\n", - "--------", "--------", "----------", "-----------", "--------", "--------", "------------", "-----------"); + fprintf(fp, " %-10s %-10s %-12s %-12s %-10s %-10s %-12s %-12s\n", "--------", + "--------", "----------", "-----------", "--------", "--------", "------------", + "-----------"); #else fprintf(fp, "\n"); #endif @@ -614,14 +630,21 @@ void SCProfilingDumpPacketStats(void) } FormatNumber(pd->tot, totalstr, sizeof(totalstr)); - double percent = (long double)pd->tot / - (long double)total * 100; + double percent = (long double)pd->tot / (long double)total * 100; - fprintf(fp, "%-24s IPv4 %3d %12"PRIu64" %12"PRIu64" %12"PRIu64" %12"PRIu64" %12s %6.2f", - TmModuleTmmIdToString(m), p, pd->cnt, pd->min, pd->max, (uint64_t)(pd->tot / pd->cnt), totalstr, percent); + fprintf(fp, + "%-24s IPv4 %3d %12" PRIu64 " %12" PRIu64 " %12" PRIu64 + " %12" PRIu64 " %12s %6.2f", + TmModuleTmmIdToString(m), p, pd->cnt, pd->min, pd->max, + (uint64_t)(pd->tot / pd->cnt), totalstr, percent); #ifdef PROFILE_LOCKING - fprintf(fp, " %10.2f %12"PRIu64" %12"PRIu64" %10.2f %10.2f %12"PRIu64" %12"PRIu64" %10.2f\n", - (float)pd->lock/pd->cnt, (uint64_t)pd->ticks/pd->cnt, pd->contention, (float)pd->contention/pd->cnt, (float)pd->slock/pd->cnt, (uint64_t)pd->sticks/pd->cnt, pd->scontention, (float)pd->scontention/pd->cnt); + fprintf(fp, + " %10.2f %12" PRIu64 " %12" PRIu64 " %10.2f %10.2f %12" PRIu64 + " %12" PRIu64 " %10.2f\n", + (float)pd->lock / pd->cnt, (uint64_t)pd->ticks / pd->cnt, pd->contention, + (float)pd->contention / pd->cnt, (float)pd->slock / pd->cnt, + (uint64_t)pd->sticks / pd->cnt, pd->scontention, + (float)pd->scontention / pd->cnt); #else fprintf(fp, "\n"); #endif @@ -639,11 +662,13 @@ void SCProfilingDumpPacketStats(void) } FormatNumber(pd->tot, totalstr, sizeof(totalstr)); - double percent = (long double)pd->tot / - (long double)total * 100; + double percent = (long double)pd->tot / (long double)total * 100; - fprintf(fp, "%-24s IPv6 %3d %12"PRIu64" %12"PRIu64" %12"PRIu64" %12"PRIu64" %12s %6.2f\n", - TmModuleTmmIdToString(m), p, pd->cnt, pd->min, pd->max, (uint64_t)(pd->tot / pd->cnt), totalstr, percent); + fprintf(fp, + "%-24s IPv6 %3d %12" PRIu64 " %12" PRIu64 " %12" PRIu64 + " %12" PRIu64 " %12s %6.2f\n", + TmModuleTmmIdToString(m), p, pd->cnt, pd->min, pd->max, + (uint64_t)(pd->tot / pd->cnt), totalstr, percent); } } @@ -659,10 +684,11 @@ void SCProfilingDumpPacketStats(void) } } - fprintf(fp, "\n%-24s %-6s %-5s %-12s %-12s %-12s %-12s %-12s\n", - "Logger", "IP ver", "Proto", "cnt", "min", "max", "avg", "tot"); + fprintf(fp, "\n%-24s %-6s %-5s %-12s %-12s %-12s %-12s %-12s\n", "Logger", + "IP ver", "Proto", "cnt", "min", "max", "avg", "tot"); fprintf(fp, "%-24s %-6s %-5s %-12s %-12s %-12s %-12s %-12s\n", - "------------------------", "------", "-----", "----------", "------------", "------------", "-----------", "-----------"); + "------------------------", "------", "-----", "----------", "------------", + "------------", "-----------", "-----------"); for (int m = 0; m < LOGGER_SIZE; m++) { for (int p = 0; p < 256; p++) { SCProfilePacketData *pd = &packet_profile_log_data4[m][p]; @@ -671,8 +697,7 @@ void SCProfilingDumpPacketStats(void) } FormatNumber(pd->tot, totalstr, sizeof(totalstr)); - double percent = (long double)pd->tot / - (long double)total * 100; + double percent = (long double)pd->tot / (long double)total * 100; fprintf(fp, "%-24s IPv4 %3d %12" PRIu64 " %12" PRIu64 " %12" PRIu64 @@ -689,8 +714,7 @@ void SCProfilingDumpPacketStats(void) } FormatNumber(pd->tot, totalstr, sizeof(totalstr)); - double percent = (long double)pd->tot / - (long double)total * 100; + double percent = (long double)pd->tot / (long double)total * 100; fprintf(fp, "%-24s IPv6 %3d %12" PRIu64 " %12" PRIu64 " %12" PRIu64 @@ -715,7 +739,8 @@ void SCProfilingDumpPacketStats(void) fprintf(fp, "\n%-24s %-6s %-5s %-12s %-12s %-12s %-12s %-12s\n", "Detection phase", "IP ver", "Proto", "cnt", "min", "max", "avg", "tot"); fprintf(fp, "%-24s %-6s %-5s %-12s %-12s %-12s %-12s %-12s\n", - "------------------------", "------", "-----", "----------", "------------", "------------", "-----------", "-----------"); + "------------------------", "------", "-----", "----------", "------------", + "------------", "-----------", "-----------"); for (int m = 0; m < PROF_DETECT_SIZE; m++) { for (int p = 0; p < 257; p++) { SCProfilePacketData *pd = &packet_profile_detect_data4[m][p]; @@ -724,11 +749,13 @@ void SCProfilingDumpPacketStats(void) } FormatNumber(pd->tot, totalstr, sizeof(totalstr)); - double percent = (long double)pd->tot / - (long double)total * 100; + double percent = (long double)pd->tot / (long double)total * 100; - fprintf(fp, "%-24s IPv4 %3d %12"PRIu64" %12"PRIu64" %12"PRIu64" %12"PRIu64" %12s %-6.2f\n", - PacketProfileDetectIdToString(m), p, pd->cnt, pd->min, pd->max, (uint64_t)(pd->tot / pd->cnt), totalstr, percent); + fprintf(fp, + "%-24s IPv4 %3d %12" PRIu64 " %12" PRIu64 " %12" PRIu64 + " %12" PRIu64 " %12s %-6.2f\n", + PacketProfileDetectIdToString(m), p, pd->cnt, pd->min, pd->max, + (uint64_t)(pd->tot / pd->cnt), totalstr, percent); } } for (int m = 0; m < PROF_DETECT_SIZE; m++) { @@ -739,11 +766,13 @@ void SCProfilingDumpPacketStats(void) } FormatNumber(pd->tot, totalstr, sizeof(totalstr)); - double percent = (long double)pd->tot / - (long double)total * 100; + double percent = (long double)pd->tot / (long double)total * 100; - fprintf(fp, "%-24s IPv6 %3d %12"PRIu64" %12"PRIu64" %12"PRIu64" %12"PRIu64" %12s %-6.2f\n", - PacketProfileDetectIdToString(m), p, pd->cnt, pd->min, pd->max, (uint64_t)(pd->tot / pd->cnt), totalstr, percent); + fprintf(fp, + "%-24s IPv6 %3d %12" PRIu64 " %12" PRIu64 " %12" PRIu64 + " %12" PRIu64 " %12s %-6.2f\n", + PacketProfileDetectIdToString(m), p, pd->cnt, pd->min, pd->max, + (uint64_t)(pd->tot / pd->cnt), totalstr, percent); } } fclose(fp); @@ -775,8 +804,8 @@ static void PrintCSVHeader(void) void SCProfilingPrintPacketProfile(Packet *p) { - if (profiling_packets_csv_enabled == 0 || p == NULL || - packet_profile_csv_fp == NULL || p->profile == NULL) { + if (profiling_packets_csv_enabled == 0 || p == NULL || packet_profile_csv_fp == NULL || + p->profile == NULL) { return; } @@ -786,8 +815,7 @@ void SCProfilingPrintPacketProfile(Packet *p) /* total cost from acquisition to return to packetpool */ uint64_t delta = p->profile->ticks_end - p->profile->ticks_start; - fprintf(packet_profile_csv_fp, "%"PRIu64",%"PRIu64",", - p->pcap_cnt, delta); + fprintf(packet_profile_csv_fp, "%" PRIu64 ",%" PRIu64 ",", p->pcap_cnt, delta); for (int i = 0; i < TMM_SIZE; i++) { const PktProfilingTmmData *pdt = &p->profile->tmm[i]; @@ -808,11 +836,11 @@ void SCProfilingPrintPacketProfile(Packet *p) tmm_total += tmm_delta; } - fprintf(packet_profile_csv_fp, "%"PRIu64",", receive); - fprintf(packet_profile_csv_fp, "%"PRIu64",", decode); + fprintf(packet_profile_csv_fp, "%" PRIu64 ",", receive); + fprintf(packet_profile_csv_fp, "%" PRIu64 ",", decode); PktProfilingTmmData *fw_pdt = &p->profile->tmm[TMM_FLOWWORKER]; - fprintf(packet_profile_csv_fp, "%"PRIu64",", fw_pdt->ticks_end - fw_pdt->ticks_start); - fprintf(packet_profile_csv_fp, "%"PRIu64",", delta - tmm_total); + fprintf(packet_profile_csv_fp, "%" PRIu64 ",", fw_pdt->ticks_end - fw_pdt->ticks_start); + fprintf(packet_profile_csv_fp, "%" PRIu64 ",", delta - tmm_total); /* count ticks for app layer */ uint64_t app_total = 0; @@ -824,7 +852,7 @@ void SCProfilingPrintPacketProfile(Packet *p) } } - fprintf(packet_profile_csv_fp, "%"PRIu64",", p->profile->proto_detect); + fprintf(packet_profile_csv_fp, "%" PRIu64 ",", p->profile->proto_detect); /* print flowworker steps */ for (enum ProfileFlowWorkerId fwi = 0; fwi < PROFILE_FLOWWORKER_SIZE; fwi++) { @@ -836,7 +864,7 @@ void SCProfilingPrintPacketProfile(Packet *p) ticks_spent = app_total; } - fprintf(packet_profile_csv_fp, "%"PRIu64",", ticks_spent); + fprintf(packet_profile_csv_fp, "%" PRIu64 ",", ticks_spent); } /* count loggers cost and print as a single cost */ @@ -845,25 +873,26 @@ void SCProfilingPrintPacketProfile(Packet *p) const PktProfilingLoggerData *pd = &p->profile->logger[i]; loggers += pd->ticks_spent; } - fprintf(packet_profile_csv_fp, "%"PRIu64",", loggers); + fprintf(packet_profile_csv_fp, "%" PRIu64 ",", loggers); /* detect steps */ for (int i = 0; i < PROF_DETECT_SIZE; i++) { const PktProfilingDetectData *pdt = &p->profile->detect[i]; - fprintf(packet_profile_csv_fp,"%"PRIu64",", pdt->ticks_spent); + fprintf(packet_profile_csv_fp, "%" PRIu64 ",", pdt->ticks_spent); } /* print individual loggers */ for (LoggerId i = 0; i < LOGGER_SIZE; i++) { const PktProfilingLoggerData *pd = &p->profile->logger[i]; - fprintf(packet_profile_csv_fp, "%"PRIu64",", pd->ticks_spent); + fprintf(packet_profile_csv_fp, "%" PRIu64 ",", pd->ticks_spent); } - fprintf(packet_profile_csv_fp,"\n"); + fprintf(packet_profile_csv_fp, "\n"); } -static void SCProfilingUpdatePacketDetectRecord(PacketProfileDetectId id, uint8_t ipproto, PktProfilingDetectData *pdt, int ipver) +static void SCProfilingUpdatePacketDetectRecord( + PacketProfileDetectId id, uint8_t ipproto, PktProfilingDetectData *pdt, int ipver) { if (pdt == NULL) { return; @@ -883,7 +912,7 @@ static void SCProfilingUpdatePacketDetectRecord(PacketProfileDetectId id, uint8_ } pd->tot += pdt->ticks_spent; - pd->cnt ++; + pd->cnt++; } static void SCProfilingUpdatePacketDetectRecords(Packet *p) @@ -918,10 +947,11 @@ static void SCProfilingUpdatePacketAppPdRecord(uint8_t ipproto, uint32_t ticks_s } pd->tot += ticks_spent; - pd->cnt ++; + pd->cnt++; } -static void SCProfilingUpdatePacketAppRecord(int alproto, uint8_t ipproto, PktProfilingAppData *pdt, int ipver) +static void SCProfilingUpdatePacketAppRecord( + int alproto, uint8_t ipproto, PktProfilingAppData *pdt, int ipver) { if (pdt == NULL) { return; @@ -941,7 +971,7 @@ static void SCProfilingUpdatePacketAppRecord(int alproto, uint8_t ipproto, PktPr } pd->tot += pdt->ticks_spent; - pd->cnt ++; + pd->cnt++; } static void SCProfilingUpdatePacketAppRecords(Packet *p) @@ -968,7 +998,8 @@ static void SCProfilingUpdatePacketAppRecords(Packet *p) } } -static void SCProfilingUpdatePacketTmmRecord(int module, uint8_t proto, PktProfilingTmmData *pdt, int ipver) +static void SCProfilingUpdatePacketTmmRecord( + int module, uint8_t proto, PktProfilingTmmData *pdt, int ipver) { if (pdt == NULL) { return; @@ -989,7 +1020,7 @@ static void SCProfilingUpdatePacketTmmRecord(int module, uint8_t proto, PktProfi } pd->tot += (uint64_t)delta; - pd->cnt ++; + pd->cnt++; #ifdef PROFILE_LOCKING pd->lock += pdt->mutex_lock_cnt; @@ -1019,8 +1050,8 @@ static void SCProfilingUpdatePacketTmmRecords(Packet *p) } } -static inline void SCProfilingUpdatePacketGenericRecord(PktProfilingData *pdt, - SCProfilePacketData *pd) +static inline void SCProfilingUpdatePacketGenericRecord( + PktProfilingData *pdt, SCProfilePacketData *pd) { if (pdt == NULL || pd == NULL) { return; @@ -1035,11 +1066,11 @@ static inline void SCProfilingUpdatePacketGenericRecord(PktProfilingData *pdt, } pd->tot += delta; - pd->cnt ++; + pd->cnt++; } -static void SCProfilingUpdatePacketGenericRecords(Packet *p, PktProfilingData *pd, - struct ProfileProtoRecords *records, int size) +static void SCProfilingUpdatePacketGenericRecords( + Packet *p, PktProfilingData *pd, struct ProfileProtoRecords *records, int size) { int i; for (i = 0; i < size; i++) { @@ -1062,8 +1093,8 @@ static void SCProfilingUpdatePacketGenericRecords(Packet *p, PktProfilingData *p } } -static void SCProfilingUpdatePacketLogRecord(LoggerId id, - uint8_t ipproto, PktProfilingLoggerData *pdt, int ipver) +static void SCProfilingUpdatePacketLogRecord( + LoggerId id, uint8_t ipproto, PktProfilingLoggerData *pdt, int ipver) { if (pdt == NULL) { return; @@ -1103,9 +1134,8 @@ static void SCProfilingUpdatePacketLogRecords(Packet *p) void SCProfilingAddPacket(Packet *p) { - if (p == NULL || p->profile == NULL || - p->profile->ticks_start == 0 || p->profile->ticks_end == 0 || - p->profile->ticks_start > p->profile->ticks_end) + if (p == NULL || p->profile == NULL || p->profile->ticks_start == 0 || + p->profile->ticks_end == 0 || p->profile->ticks_start > p->profile->ticks_end) return; pthread_mutex_lock(&packet_profile_lock); @@ -1123,7 +1153,7 @@ void SCProfilingAddPacket(Packet *p) } pd->tot += delta; - pd->cnt ++; + pd->cnt++; if (IS_TUNNEL_PKT(p)) { pd = &packet_profile_data4[256]; @@ -1136,11 +1166,11 @@ void SCProfilingAddPacket(Packet *p) } pd->tot += delta; - pd->cnt ++; + pd->cnt++; } SCProfilingUpdatePacketGenericRecords(p, p->profile->flowworker, - packet_profile_flowworker_data, PROFILE_FLOWWORKER_SIZE); + packet_profile_flowworker_data, PROFILE_FLOWWORKER_SIZE); SCProfilingUpdatePacketTmmRecords(p); SCProfilingUpdatePacketAppRecords(p); @@ -1159,7 +1189,7 @@ void SCProfilingAddPacket(Packet *p) } pd->tot += delta; - pd->cnt ++; + pd->cnt++; if (IS_TUNNEL_PKT(p)) { pd = &packet_profile_data6[256]; @@ -1172,11 +1202,11 @@ void SCProfilingAddPacket(Packet *p) } pd->tot += delta; - pd->cnt ++; + pd->cnt++; } SCProfilingUpdatePacketGenericRecords(p, p->profile->flowworker, - packet_profile_flowworker_data, PROFILE_FLOWWORKER_SIZE); + packet_profile_flowworker_data, PROFILE_FLOWWORKER_SIZE); SCProfilingUpdatePacketTmmRecords(p); SCProfilingUpdatePacketAppRecords(p); @@ -1186,7 +1216,6 @@ void SCProfilingAddPacket(Packet *p) if (profiling_packets_csv_enabled) SCProfilingPrintPacketProfile(p); - } pthread_mutex_unlock(&packet_profile_lock); } @@ -1220,7 +1249,9 @@ int SCProfileRuleStart(Packet *p) return 0; } -#define CASE_CODE(E) case E: return #E +#define CASE_CODE(E) \ + case E: \ + return #E /** * \brief Maps the PacketProfileDetectId, to its string equivalent @@ -1229,7 +1260,7 @@ int SCProfileRuleStart(Packet *p) * * \retval string equivalent for the PacketProfileDetectId id */ -const char * PacketProfileDetectIdToString(PacketProfileDetectId id) +const char *PacketProfileDetectIdToString(PacketProfileDetectId id) { switch (id) { CASE_CODE(PROF_DETECT_SETUP); @@ -1295,8 +1326,7 @@ const char *PacketProfileLoggerIdToString(LoggerId id) #ifdef UNITTESTS -static int -ProfilingGenericTicksTest01(void) +static int ProfilingGenericTicksTest01(void) { #define TEST_RUNS 1024 uint64_t ticks_start = 0; @@ -1309,14 +1339,14 @@ ProfilingGenericTicksTest01(void) ptr[i] = SCMalloc(1024); } ticks_end = UtilCpuGetTicks(); - printf("malloc(1024) %"PRIu64"\n", (ticks_end - ticks_start)/TEST_RUNS); + printf("malloc(1024) %" PRIu64 "\n", (ticks_end - ticks_start) / TEST_RUNS); ticks_start = UtilCpuGetTicks(); for (i = 0; i < TEST_RUNS; i++) { SCFree(ptr[i]); } ticks_end = UtilCpuGetTicks(); - printf("SCFree(1024) %"PRIu64"\n", (ticks_end - ticks_start)/TEST_RUNS); + printf("SCFree(1024) %" PRIu64 "\n", (ticks_end - ticks_start) / TEST_RUNS); SCMutex m[TEST_RUNS]; @@ -1325,28 +1355,28 @@ ProfilingGenericTicksTest01(void) SCMutexInit(&m[i], NULL); } ticks_end = UtilCpuGetTicks(); - printf("SCMutexInit() %"PRIu64"\n", (ticks_end - ticks_start)/TEST_RUNS); + printf("SCMutexInit() %" PRIu64 "\n", (ticks_end - ticks_start) / TEST_RUNS); ticks_start = UtilCpuGetTicks(); for (i = 0; i < TEST_RUNS; i++) { SCMutexLock(&m[i]); } ticks_end = UtilCpuGetTicks(); - printf("SCMutexLock() %"PRIu64"\n", (ticks_end - ticks_start)/TEST_RUNS); + printf("SCMutexLock() %" PRIu64 "\n", (ticks_end - ticks_start) / TEST_RUNS); ticks_start = UtilCpuGetTicks(); for (i = 0; i < TEST_RUNS; i++) { SCMutexUnlock(&m[i]); } ticks_end = UtilCpuGetTicks(); - printf("SCMutexUnlock() %"PRIu64"\n", (ticks_end - ticks_start)/TEST_RUNS); + printf("SCMutexUnlock() %" PRIu64 "\n", (ticks_end - ticks_start) / TEST_RUNS); ticks_start = UtilCpuGetTicks(); for (i = 0; i < TEST_RUNS; i++) { SCMutexDestroy(&m[i]); } ticks_end = UtilCpuGetTicks(); - printf("SCMutexDestroy() %"PRIu64"\n", (ticks_end - ticks_start)/TEST_RUNS); + printf("SCMutexDestroy() %" PRIu64 "\n", (ticks_end - ticks_start) / TEST_RUNS); SCSpinlock s[TEST_RUNS]; @@ -1355,50 +1385,49 @@ ProfilingGenericTicksTest01(void) SCSpinInit(&s[i], 0); } ticks_end = UtilCpuGetTicks(); - printf("SCSpinInit() %"PRIu64"\n", (ticks_end - ticks_start)/TEST_RUNS); + printf("SCSpinInit() %" PRIu64 "\n", (ticks_end - ticks_start) / TEST_RUNS); ticks_start = UtilCpuGetTicks(); for (i = 0; i < TEST_RUNS; i++) { SCSpinLock(&s[i]); } ticks_end = UtilCpuGetTicks(); - printf("SCSpinLock() %"PRIu64"\n", (ticks_end - ticks_start)/TEST_RUNS); + printf("SCSpinLock() %" PRIu64 "\n", (ticks_end - ticks_start) / TEST_RUNS); ticks_start = UtilCpuGetTicks(); for (i = 0; i < TEST_RUNS; i++) { SCSpinUnlock(&s[i]); } ticks_end = UtilCpuGetTicks(); - printf("SCSpinUnlock() %"PRIu64"\n", (ticks_end - ticks_start)/TEST_RUNS); + printf("SCSpinUnlock() %" PRIu64 "\n", (ticks_end - ticks_start) / TEST_RUNS); ticks_start = UtilCpuGetTicks(); for (i = 0; i < TEST_RUNS; i++) { SCSpinDestroy(&s[i]); } ticks_end = UtilCpuGetTicks(); - printf("SCSpinDestroy() %"PRIu64"\n", (ticks_end - ticks_start)/TEST_RUNS); + printf("SCSpinDestroy() %" PRIu64 "\n", (ticks_end - ticks_start) / TEST_RUNS); SC_ATOMIC_DECL_AND_INIT(unsigned int, test); ticks_start = UtilCpuGetTicks(); for (i = 0; i < TEST_RUNS; i++) { - (void) SC_ATOMIC_ADD(test,1); + (void)SC_ATOMIC_ADD(test, 1); } ticks_end = UtilCpuGetTicks(); - printf("SC_ATOMIC_ADD %"PRIu64"\n", (ticks_end - ticks_start)/TEST_RUNS); + printf("SC_ATOMIC_ADD %" PRIu64 "\n", (ticks_end - ticks_start) / TEST_RUNS); ticks_start = UtilCpuGetTicks(); for (i = 0; i < TEST_RUNS; i++) { - SC_ATOMIC_CAS(&test,i,i+1); + SC_ATOMIC_CAS(&test, i, i + 1); } ticks_end = UtilCpuGetTicks(); - printf("SC_ATOMIC_CAS %"PRIu64"\n", (ticks_end - ticks_start)/TEST_RUNS); + printf("SC_ATOMIC_CAS %" PRIu64 "\n", (ticks_end - ticks_start) / TEST_RUNS); return 1; } #endif /* UNITTESTS */ -void -SCProfilingRegisterTests(void) +void SCProfilingRegisterTests(void) { #ifdef UNITTESTS UtRegisterTest("ProfilingGenericTicksTest01", ProfilingGenericTicksTest01); diff --git a/src/util-profiling.h b/src/util-profiling.h index 6450bc8cefe3..38e3204ed49e 100644 --- a/src/util-profiling.h +++ b/src/util-profiling.h @@ -43,9 +43,10 @@ void SCProfilingAddPacket(Packet *); extern int profiling_keyword_enabled; extern thread_local int profiling_keyword_entered; -#define KEYWORD_PROFILING_SET_LIST(ctx, list) { \ - (ctx)->keyword_perf_list = (list); \ -} +#define KEYWORD_PROFILING_SET_LIST(ctx, list) \ + { \ + (ctx)->keyword_perf_list = (list); \ + } #define KEYWORD_PROFILING_START \ uint64_t profile_keyword_start_ = 0; \ @@ -61,198 +62,206 @@ extern thread_local int profiling_keyword_entered; /* we allow this macro to be called if profiling_keyword_entered == 0, * so that we don't have to refactor some of the detection code. */ -#define KEYWORD_PROFILING_END(ctx, type, m) \ - if (profiling_keyword_enabled && profiling_keyword_entered) { \ - profile_keyword_end_ = UtilCpuGetTicks(); \ - SCProfilingKeywordUpdateCounter((ctx),(type),(profile_keyword_end_ - profile_keyword_start_),(m)); \ - profiling_keyword_entered--; \ +#define KEYWORD_PROFILING_END(ctx, type, m) \ + if (profiling_keyword_enabled && profiling_keyword_entered) { \ + profile_keyword_end_ = UtilCpuGetTicks(); \ + SCProfilingKeywordUpdateCounter( \ + (ctx), (type), (profile_keyword_end_ - profile_keyword_start_), (m)); \ + profiling_keyword_entered--; \ } PktProfiling *SCProfilePacketStart(void); -#define PACKET_PROFILING_START(p) \ - if (profiling_packets_enabled) { \ - (p)->profile = SCProfilePacketStart(); \ - if ((p)->profile != NULL) \ - (p)->profile->ticks_start = UtilCpuGetTicks(); \ +#define PACKET_PROFILING_START(p) \ + if (profiling_packets_enabled) { \ + (p)->profile = SCProfilePacketStart(); \ + if ((p)->profile != NULL) \ + (p)->profile->ticks_start = UtilCpuGetTicks(); \ } -#define PACKET_PROFILING_RESTART(p) \ - if (profiling_packets_enabled) { \ - if ((p)->profile != NULL) \ - (p)->profile->ticks_start = UtilCpuGetTicks(); \ +#define PACKET_PROFILING_RESTART(p) \ + if (profiling_packets_enabled) { \ + if ((p)->profile != NULL) \ + (p)->profile->ticks_start = UtilCpuGetTicks(); \ } -#define PACKET_PROFILING_END(p) \ - if (profiling_packets_enabled && (p)->profile != NULL) { \ - (p)->profile->ticks_end = UtilCpuGetTicks(); \ - SCProfilingAddPacket((p)); \ +#define PACKET_PROFILING_END(p) \ + if (profiling_packets_enabled && (p)->profile != NULL) { \ + (p)->profile->ticks_end = UtilCpuGetTicks(); \ + SCProfilingAddPacket((p)); \ } #ifdef PROFILE_LOCKING -#define PACKET_PROFILING_RESET_LOCKS do { \ - mutex_lock_cnt = 0; \ - mutex_lock_wait_ticks = 0; \ - mutex_lock_contention = 0; \ - spin_lock_cnt = 0; \ - spin_lock_wait_ticks = 0; \ - spin_lock_contention = 0; \ - rww_lock_cnt = 0; \ - rww_lock_wait_ticks = 0; \ - rww_lock_contention = 0; \ - rwr_lock_cnt = 0; \ - rwr_lock_wait_ticks = 0; \ - rwr_lock_contention = 0; \ - locks_idx = 0; \ - record_locks = 1;\ +#define PACKET_PROFILING_RESET_LOCKS \ + do { \ + mutex_lock_cnt = 0; \ + mutex_lock_wait_ticks = 0; \ + mutex_lock_contention = 0; \ + spin_lock_cnt = 0; \ + spin_lock_wait_ticks = 0; \ + spin_lock_contention = 0; \ + rww_lock_cnt = 0; \ + rww_lock_wait_ticks = 0; \ + rww_lock_contention = 0; \ + rwr_lock_cnt = 0; \ + rwr_lock_wait_ticks = 0; \ + rwr_lock_contention = 0; \ + locks_idx = 0; \ + record_locks = 1; \ } while (0) -#define PACKET_PROFILING_COPY_LOCKS(p, id) do { \ - (p)->profile->tmm[(id)].mutex_lock_cnt = mutex_lock_cnt; \ - (p)->profile->tmm[(id)].mutex_lock_wait_ticks = mutex_lock_wait_ticks; \ - (p)->profile->tmm[(id)].mutex_lock_contention = mutex_lock_contention; \ - (p)->profile->tmm[(id)].spin_lock_cnt = spin_lock_cnt; \ - (p)->profile->tmm[(id)].spin_lock_wait_ticks = spin_lock_wait_ticks; \ - (p)->profile->tmm[(id)].spin_lock_contention = spin_lock_contention; \ - (p)->profile->tmm[(id)].rww_lock_cnt = rww_lock_cnt; \ - (p)->profile->tmm[(id)].rww_lock_wait_ticks = rww_lock_wait_ticks; \ - (p)->profile->tmm[(id)].rww_lock_contention = rww_lock_contention; \ - (p)->profile->tmm[(id)].rwr_lock_cnt = rwr_lock_cnt; \ - (p)->profile->tmm[(id)].rwr_lock_wait_ticks = rwr_lock_wait_ticks; \ - (p)->profile->tmm[(id)].rwr_lock_contention = rwr_lock_contention; \ - record_locks = 0; \ - SCProfilingAddPacketLocks((p)); \ - } while(0) +#define PACKET_PROFILING_COPY_LOCKS(p, id) \ + do { \ + (p)->profile->tmm[(id)].mutex_lock_cnt = mutex_lock_cnt; \ + (p)->profile->tmm[(id)].mutex_lock_wait_ticks = mutex_lock_wait_ticks; \ + (p)->profile->tmm[(id)].mutex_lock_contention = mutex_lock_contention; \ + (p)->profile->tmm[(id)].spin_lock_cnt = spin_lock_cnt; \ + (p)->profile->tmm[(id)].spin_lock_wait_ticks = spin_lock_wait_ticks; \ + (p)->profile->tmm[(id)].spin_lock_contention = spin_lock_contention; \ + (p)->profile->tmm[(id)].rww_lock_cnt = rww_lock_cnt; \ + (p)->profile->tmm[(id)].rww_lock_wait_ticks = rww_lock_wait_ticks; \ + (p)->profile->tmm[(id)].rww_lock_contention = rww_lock_contention; \ + (p)->profile->tmm[(id)].rwr_lock_cnt = rwr_lock_cnt; \ + (p)->profile->tmm[(id)].rwr_lock_wait_ticks = rwr_lock_wait_ticks; \ + (p)->profile->tmm[(id)].rwr_lock_contention = rwr_lock_contention; \ + record_locks = 0; \ + SCProfilingAddPacketLocks((p)); \ + } while (0) #else #define PACKET_PROFILING_RESET_LOCKS #define PACKET_PROFILING_COPY_LOCKS(p, id) #endif -#define PACKET_PROFILING_TMM_START(p, id) \ - if (profiling_packets_enabled && (p)->profile != NULL) { \ - if ((id) < TMM_SIZE) { \ - (p)->profile->tmm[(id)].ticks_start = UtilCpuGetTicks();\ - PACKET_PROFILING_RESET_LOCKS; \ - } \ +#define PACKET_PROFILING_TMM_START(p, id) \ + if (profiling_packets_enabled && (p)->profile != NULL) { \ + if ((id) < TMM_SIZE) { \ + (p)->profile->tmm[(id)].ticks_start = UtilCpuGetTicks(); \ + PACKET_PROFILING_RESET_LOCKS; \ + } \ } -#define PACKET_PROFILING_TMM_END(p, id) \ - if (profiling_packets_enabled && (p)->profile != NULL) { \ - if ((id) < TMM_SIZE) { \ - PACKET_PROFILING_COPY_LOCKS((p), (id)); \ - (p)->profile->tmm[(id)].ticks_end = UtilCpuGetTicks(); \ - } \ +#define PACKET_PROFILING_TMM_END(p, id) \ + if (profiling_packets_enabled && (p)->profile != NULL) { \ + if ((id) < TMM_SIZE) { \ + PACKET_PROFILING_COPY_LOCKS((p), (id)); \ + (p)->profile->tmm[(id)].ticks_end = UtilCpuGetTicks(); \ + } \ } -#define FLOWWORKER_PROFILING_START(p, id) \ - if (profiling_packets_enabled && (p)->profile != NULL) { \ - if ((id) < PROFILE_FLOWWORKER_SIZE) { \ - (p)->profile->flowworker[(id)].ticks_start = UtilCpuGetTicks();\ - } \ +#define FLOWWORKER_PROFILING_START(p, id) \ + if (profiling_packets_enabled && (p)->profile != NULL) { \ + if ((id) < PROFILE_FLOWWORKER_SIZE) { \ + (p)->profile->flowworker[(id)].ticks_start = UtilCpuGetTicks(); \ + } \ } -#define FLOWWORKER_PROFILING_END(p, id) \ - if (profiling_packets_enabled && (p)->profile != NULL) { \ - if ((id) < PROFILE_FLOWWORKER_SIZE) { \ - (p)->profile->flowworker[(id)].ticks_end = UtilCpuGetTicks(); \ - } \ +#define FLOWWORKER_PROFILING_END(p, id) \ + if (profiling_packets_enabled && (p)->profile != NULL) { \ + if ((id) < PROFILE_FLOWWORKER_SIZE) { \ + (p)->profile->flowworker[(id)].ticks_end = UtilCpuGetTicks(); \ + } \ } -#define PACKET_PROFILING_RESET(p) \ - if (profiling_packets_enabled && (p)->profile != NULL) { \ - SCFree((p)->profile); \ - (p)->profile = NULL; \ +#define PACKET_PROFILING_RESET(p) \ + if (profiling_packets_enabled && (p)->profile != NULL) { \ + SCFree((p)->profile); \ + (p)->profile = NULL; \ } -#define PACKET_PROFILING_APP_START(dp, id) \ - if (profiling_packets_enabled) { \ - (dp)->ticks_start = UtilCpuGetTicks(); \ - (dp)->alproto = (id); \ +#define PACKET_PROFILING_APP_START(dp, id) \ + if (profiling_packets_enabled) { \ + (dp)->ticks_start = UtilCpuGetTicks(); \ + (dp)->alproto = (id); \ } -#define PACKET_PROFILING_APP_END(dp, id) \ - if (profiling_packets_enabled) { \ - BUG_ON((id) != (dp)->alproto); \ - (dp)->ticks_end = UtilCpuGetTicks(); \ - if ((dp)->ticks_start != 0 && (dp)->ticks_start < ((dp)->ticks_end)) { \ - (dp)->ticks_spent = ((dp)->ticks_end - (dp)->ticks_start); \ - } \ +#define PACKET_PROFILING_APP_END(dp, id) \ + if (profiling_packets_enabled) { \ + BUG_ON((id) != (dp)->alproto); \ + (dp)->ticks_end = UtilCpuGetTicks(); \ + if ((dp)->ticks_start != 0 && (dp)->ticks_start < ((dp)->ticks_end)) { \ + (dp)->ticks_spent = ((dp)->ticks_end - (dp)->ticks_start); \ + } \ } -#define PACKET_PROFILING_APP_PD_START(dp) \ - if (profiling_packets_enabled) { \ - (dp)->proto_detect_ticks_start = UtilCpuGetTicks(); \ +#define PACKET_PROFILING_APP_PD_START(dp) \ + if (profiling_packets_enabled) { \ + (dp)->proto_detect_ticks_start = UtilCpuGetTicks(); \ } -#define PACKET_PROFILING_APP_PD_END(dp) \ - if (profiling_packets_enabled) { \ - (dp)->proto_detect_ticks_end = UtilCpuGetTicks(); \ - if ((dp)->proto_detect_ticks_start != 0 && (dp)->proto_detect_ticks_start < ((dp)->proto_detect_ticks_end)) { \ - (dp)->proto_detect_ticks_spent = \ - ((dp)->proto_detect_ticks_end - (dp)->proto_detect_ticks_start); \ - } \ +#define PACKET_PROFILING_APP_PD_END(dp) \ + if (profiling_packets_enabled) { \ + (dp)->proto_detect_ticks_end = UtilCpuGetTicks(); \ + if ((dp)->proto_detect_ticks_start != 0 && \ + (dp)->proto_detect_ticks_start < ((dp)->proto_detect_ticks_end)) { \ + (dp)->proto_detect_ticks_spent = \ + ((dp)->proto_detect_ticks_end - (dp)->proto_detect_ticks_start); \ + } \ } -#define PACKET_PROFILING_APP_RESET(dp) \ - if (profiling_packets_enabled) { \ - (dp)->ticks_start = 0; \ - (dp)->ticks_end = 0; \ - (dp)->ticks_spent = 0; \ - (dp)->alproto = 0; \ - (dp)->proto_detect_ticks_start = 0; \ - (dp)->proto_detect_ticks_end = 0; \ - (dp)->proto_detect_ticks_spent = 0; \ +#define PACKET_PROFILING_APP_RESET(dp) \ + if (profiling_packets_enabled) { \ + (dp)->ticks_start = 0; \ + (dp)->ticks_end = 0; \ + (dp)->ticks_spent = 0; \ + (dp)->alproto = 0; \ + (dp)->proto_detect_ticks_start = 0; \ + (dp)->proto_detect_ticks_end = 0; \ + (dp)->proto_detect_ticks_spent = 0; \ } -#define PACKET_PROFILING_APP_STORE(dp, p) \ - if (profiling_packets_enabled && (p)->profile != NULL) { \ - if ((dp)->alproto < ALPROTO_MAX) { \ - (p)->profile->app[(dp)->alproto].ticks_spent += (dp)->ticks_spent; \ - (p)->profile->proto_detect += (dp)->proto_detect_ticks_spent; \ - } \ +#define PACKET_PROFILING_APP_STORE(dp, p) \ + if (profiling_packets_enabled && (p)->profile != NULL) { \ + if ((dp)->alproto < ALPROTO_MAX) { \ + (p)->profile->app[(dp)->alproto].ticks_spent += (dp)->ticks_spent; \ + (p)->profile->proto_detect += (dp)->proto_detect_ticks_spent; \ + } \ } -#define PACKET_PROFILING_DETECT_START(p, id) \ - if (profiling_packets_enabled && (p)->profile != NULL) { \ - if ((id) < PROF_DETECT_SIZE) { \ - (p)->profile->detect[(id)].ticks_start = UtilCpuGetTicks(); \ - } \ +#define PACKET_PROFILING_DETECT_START(p, id) \ + if (profiling_packets_enabled && (p)->profile != NULL) { \ + if ((id) < PROF_DETECT_SIZE) { \ + (p)->profile->detect[(id)].ticks_start = UtilCpuGetTicks(); \ + } \ } -#define PACKET_PROFILING_DETECT_END(p, id) \ - if (profiling_packets_enabled && (p)->profile != NULL) { \ - if ((id) < PROF_DETECT_SIZE) { \ - (p)->profile->detect[(id)].ticks_end = UtilCpuGetTicks();\ - if ((p)->profile->detect[(id)].ticks_start != 0 && \ - (p)->profile->detect[(id)].ticks_start < (p)->profile->detect[(id)].ticks_end) { \ - (p)->profile->detect[(id)].ticks_spent += \ - ((p)->profile->detect[(id)].ticks_end - (p)->profile->detect[(id)].ticks_start); \ - } \ - } \ +#define PACKET_PROFILING_DETECT_END(p, id) \ + if (profiling_packets_enabled && (p)->profile != NULL) { \ + if ((id) < PROF_DETECT_SIZE) { \ + (p)->profile->detect[(id)].ticks_end = UtilCpuGetTicks(); \ + if ((p)->profile->detect[(id)].ticks_start != 0 && \ + (p)->profile->detect[(id)].ticks_start < \ + (p)->profile->detect[(id)].ticks_end) { \ + (p)->profile->detect[(id)].ticks_spent += \ + ((p)->profile->detect[(id)].ticks_end - \ + (p)->profile->detect[(id)].ticks_start); \ + } \ + } \ } -#define PACKET_PROFILING_LOGGER_START(p, id) \ - if (profiling_packets_enabled && (p)->profile != NULL) { \ - if ((id) < LOGGER_SIZE) { \ - (p)->profile->logger[(id)].ticks_start = UtilCpuGetTicks(); \ - } \ +#define PACKET_PROFILING_LOGGER_START(p, id) \ + if (profiling_packets_enabled && (p)->profile != NULL) { \ + if ((id) < LOGGER_SIZE) { \ + (p)->profile->logger[(id)].ticks_start = UtilCpuGetTicks(); \ + } \ } -#define PACKET_PROFILING_LOGGER_END(p, id) \ - if (profiling_packets_enabled && (p)->profile != NULL) { \ - if ((id) < LOGGER_SIZE) { \ - (p)->profile->logger[(id)].ticks_end = UtilCpuGetTicks();\ - if ((p)->profile->logger[(id)].ticks_start != 0 && \ - (p)->profile->logger[(id)].ticks_start < (p)->profile->logger[(id)].ticks_end) { \ - (p)->profile->logger[(id)].ticks_spent += \ - ((p)->profile->logger[(id)].ticks_end - (p)->profile->logger[(id)].ticks_start); \ - } \ - } \ +#define PACKET_PROFILING_LOGGER_END(p, id) \ + if (profiling_packets_enabled && (p)->profile != NULL) { \ + if ((id) < LOGGER_SIZE) { \ + (p)->profile->logger[(id)].ticks_end = UtilCpuGetTicks(); \ + if ((p)->profile->logger[(id)].ticks_start != 0 && \ + (p)->profile->logger[(id)].ticks_start < \ + (p)->profile->logger[(id)].ticks_end) { \ + (p)->profile->logger[(id)].ticks_spent += \ + ((p)->profile->logger[(id)].ticks_end - \ + (p)->profile->logger[(id)].ticks_start); \ + } \ + } \ } -#define SGH_PROFILING_RECORD(det_ctx, sgh) \ - if (profiling_sghs_enabled) { \ - SCProfilingSghUpdateCounter((det_ctx), (sgh)); \ +#define SGH_PROFILING_RECORD(det_ctx, sgh) \ + if (profiling_sghs_enabled) { \ + SCProfilingSghUpdateCounter((det_ctx), (sgh)); \ } extern int profiling_prefilter_enabled; @@ -297,9 +306,10 @@ void SCProfilingRuleThreadSetup(struct SCProfileDetectCtx_ *, DetectEngineThread void SCProfilingRuleThreadCleanup(DetectEngineThreadCtx *); void SCProfilingKeywordsGlobalInit(void); -void SCProfilingKeywordDestroyCtx(DetectEngineCtx *);//struct SCProfileKeywordDetectCtx_ *); +void SCProfilingKeywordDestroyCtx(DetectEngineCtx *); // struct SCProfileKeywordDetectCtx_ *); void SCProfilingKeywordInitCounters(DetectEngineCtx *); -void SCProfilingKeywordUpdateCounter(DetectEngineThreadCtx *det_ctx, int id, uint64_t ticks, int match); +void SCProfilingKeywordUpdateCounter( + DetectEngineThreadCtx *det_ctx, int id, uint64_t ticks, int match); void SCProfilingKeywordThreadSetup(struct SCProfileKeywordDetectCtx_ *, DetectEngineThreadCtx *); void SCProfilingKeywordThreadCleanup(DetectEngineThreadCtx *); @@ -309,7 +319,8 @@ void SCProfilingPrefilterDestroyCtx(DetectEngineCtx *); void SCProfilingPrefilterInitCounters(DetectEngineCtx *); void SCProfilingPrefilterUpdateCounter(DetectEngineThreadCtx *det_ctx, int id, uint64_t ticks, uint64_t bytes, uint64_t bytes_called); -void SCProfilingPrefilterThreadSetup(struct SCProfilePrefilterDetectCtx_ *, DetectEngineThreadCtx *); +void SCProfilingPrefilterThreadSetup( + struct SCProfilePrefilterDetectCtx_ *, DetectEngineThreadCtx *); void SCProfilingPrefilterThreadCleanup(DetectEngineThreadCtx *); void SCProfilingSghsGlobalInit(void); @@ -326,9 +337,9 @@ void SCProfilingDump(void); #else -#define KEYWORD_PROFILING_SET_LIST(a,b) +#define KEYWORD_PROFILING_SET_LIST(a, b) #define KEYWORD_PROFILING_START -#define KEYWORD_PROFILING_END(a,b,c) +#define KEYWORD_PROFILING_END(a, b, c) #define PACKET_PROFILING_START(p) #define PACKET_PROFILING_RESTART(p) diff --git a/src/util-proto-name.h b/src/util-proto-name.h index bc5037395a0d..298ea0b28a2f 100644 --- a/src/util-proto-name.h +++ b/src/util-proto-name.h @@ -22,7 +22,7 @@ */ #ifndef __UTIL_PROTO_NAME_H__ -#define __UTIL_PROTO_NAME_H__ +#define __UTIL_PROTO_NAME_H__ /** Lookup array to hold the information related to known protocol * values @@ -38,5 +38,4 @@ void SCProtoNameRelease(void); void SCProtoNameRegisterTests(void); #endif -#endif /* __UTIL_PROTO_NAME_H__ */ - +#endif /* __UTIL_PROTO_NAME_H__ */ diff --git a/src/util-radix-tree.c b/src/util-radix-tree.c index 861d1256f409..33e9e092280a 100644 --- a/src/util-radix-tree.c +++ b/src/util-radix-tree.c @@ -81,8 +81,7 @@ static void SCRadixDeAllocSCRadixUserData(SCRadixUserData *user_data) * \param list Pointer to the SCRadixUserData list head, to which "new" has to * be appended. */ -static void SCRadixAppendToSCRadixUserDataList(SCRadixUserData *new, - SCRadixUserData **list) +static void SCRadixAppendToSCRadixUserDataList(SCRadixUserData *new, SCRadixUserData **list) { SCRadixUserData *temp = NULL; SCRadixUserData *prev = NULL; @@ -125,9 +124,8 @@ static void SCRadixAppendToSCRadixUserDataList(SCRadixUserData *new, * * \retval prefix The newly created prefix instance on success; NULL on failure */ -static SCRadixPrefix *SCRadixCreatePrefix(uint8_t *key_stream, - uint16_t key_bitlen, void *user, - uint8_t netmask) +static SCRadixPrefix *SCRadixCreatePrefix( + uint8_t *key_stream, uint16_t key_bitlen, void *user, uint8_t netmask) { SCRadixPrefix *prefix = NULL; @@ -177,16 +175,14 @@ static SCRadixPrefix *SCRadixCreatePrefix(uint8_t *key_stream, * \param user The pointer to the user data corresponding to the above * netmask. */ -static void SCRadixAddNetmaskUserDataToPrefix(SCRadixPrefix *prefix, - uint8_t netmask, - void *user) +static void SCRadixAddNetmaskUserDataToPrefix(SCRadixPrefix *prefix, uint8_t netmask, void *user) { if (prefix == NULL || user == NULL) { FatalError("prefix or user NULL"); } - SCRadixAppendToSCRadixUserDataList(SCRadixAllocSCRadixUserData(netmask, user), - &prefix->user_data); + SCRadixAppendToSCRadixUserDataList( + SCRadixAllocSCRadixUserData(netmask, user), &prefix->user_data); return; } @@ -199,8 +195,7 @@ static void SCRadixAddNetmaskUserDataToPrefix(SCRadixPrefix *prefix, * has to be removed. * \param netmask The netmask value (cidr) whose user_data has to be deleted. */ -static void SCRadixRemoveNetmaskUserDataFromPrefix(SCRadixPrefix *prefix, - uint8_t netmask) +static void SCRadixRemoveNetmaskUserDataFromPrefix(SCRadixPrefix *prefix, uint8_t netmask) { SCRadixUserData *temp = NULL, *prev = NULL; @@ -252,7 +247,7 @@ static int SCRadixPrefixContainNetmask(SCRadixPrefix *prefix, uint8_t netmask) user_data = user_data->next; } - no_match: +no_match: return 0; } @@ -414,7 +409,7 @@ static void SCRadixReleaseNode(SCRadixNode *node, SCRadixTree *tree) * * \initonly (all radix trees should be created at init) */ -SCRadixTree *SCRadixCreateRadixTree(void (*Free)(void*), void (*PrintData)(void*)) +SCRadixTree *SCRadixCreateRadixTree(void (*Free)(void *), void (*PrintData)(void *)) { SCRadixTree *tree = NULL; @@ -509,8 +504,7 @@ static SCRadixNode *SCRadixAddKeyInternal(uint8_t *key_stream, uint8_t key_bitle /* the very first element in the radix tree */ if (tree->head == NULL) { SCRadixPrefix *prefix = NULL; - if ( (prefix = SCRadixCreatePrefix(key_stream, key_bitlen, user, - netmask)) == NULL) { + if ((prefix = SCRadixCreatePrefix(key_stream, key_bitlen, user, netmask)) == NULL) { SCLogError("Error creating prefix"); sc_errno = SC_EINVAL; return NULL; @@ -539,8 +533,7 @@ static SCRadixNode *SCRadixAddKeyInternal(uint8_t *key_stream, uint8_t key_bitle * chopping the incoming search ip key using the netmask values added * into the tree and then verify for a match */ node->netmask_cnt++; - if ( (ptmp = SCRealloc(node->netmasks, (node->netmask_cnt * - sizeof(uint8_t)))) == NULL) { + if ((ptmp = SCRealloc(node->netmasks, (node->netmask_cnt * sizeof(uint8_t)))) == NULL) { SCFree(node->netmasks); node->netmasks = NULL; SCLogError("Fatal error encountered in SCRadixAddKey. Mem not allocated"); @@ -570,8 +563,7 @@ static SCRadixNode *SCRadixAddKeyInternal(uint8_t *key_stream, uint8_t key_bitle break; node = node->right; } else { - if (SC_RADIX_BITTEST(stream[node->bit >> 3], - (0x80 >> (node->bit % 8))) ) { + if (SC_RADIX_BITTEST(stream[node->bit >> 3], (0x80 >> (node->bit % 8)))) { if (node->right == NULL) break; node = node->right; @@ -591,7 +583,7 @@ static SCRadixNode *SCRadixAddKeyInternal(uint8_t *key_stream, uint8_t key_bitle DEBUG_VALIDATE_BUG_ON(bottom_node->prefix == NULL); /* get the first bit position where the ips differ */ - check_bit = (node->bit < bitlen)? node->bit: bitlen; + check_bit = (node->bit < bitlen) ? node->bit : bitlen; for (i = 0; (i * 8) < check_bit; i++) { int temp; if ((temp = (stream[i] ^ bottom_node->prefix->stream[i])) == 0) { @@ -657,7 +649,8 @@ static SCRadixNode *SCRadixAddKeyInternal(uint8_t *key_stream, uint8_t key_bitle * it indicates we are adding an exact host ip into the radix * tree, in which case we don't need to add the netmask value * into the tree */ - if (netmask == 255 || (netmask == 32 && bitlen == 32) || (netmask == 128 && bitlen == 128)) + if (netmask == 255 || (netmask == 32 && bitlen == 32) || + (netmask == 128 && bitlen == 128)) return node; /* looks like we have a netmask which is != 32 or 128, in which @@ -672,8 +665,8 @@ static SCRadixNode *SCRadixAddKeyInternal(uint8_t *key_stream, uint8_t key_bitle node->netmask_cnt++; new_node = node; - if ( (ptmp = SCRealloc(node->netmasks, (node->netmask_cnt * - sizeof(uint8_t)))) == NULL) { + if ((ptmp = SCRealloc(node->netmasks, (node->netmask_cnt * sizeof(uint8_t)))) == + NULL) { SCFree(node->netmasks); node->netmasks = NULL; SCLogError("Fatal error encountered in SCRadixAddKey. Mem not allocated..."); @@ -700,16 +693,14 @@ static SCRadixNode *SCRadixAddKeyInternal(uint8_t *key_stream, uint8_t key_bitle } } } else { - node->prefix = SCRadixCreatePrefix(key_stream, key_bitlen, - user, 255); + node->prefix = SCRadixCreatePrefix(key_stream, key_bitlen, user, 255); } return node; } /* create the leaf node for the new key */ SCRadixPrefix *prefix = NULL; - if ( (prefix = SCRadixCreatePrefix(key_stream, key_bitlen, user, - netmask)) == NULL) { + if ((prefix = SCRadixCreatePrefix(key_stream, key_bitlen, user, netmask)) == NULL) { SCLogError("Error creating prefix"); sc_errno = SC_EINVAL; return NULL; @@ -723,8 +714,8 @@ static SCRadixNode *SCRadixAddKeyInternal(uint8_t *key_stream, uint8_t key_bitle * node with a single child and stick it in. We need the if only in the * case of variable length keys */ if (differ_bit == bitlen) { - if (SC_RADIX_BITTEST(bottom_node->prefix->stream[differ_bit >> 3], - (0x80 >> (differ_bit % 8))) ) { + if (SC_RADIX_BITTEST( + bottom_node->prefix->stream[differ_bit >> 3], (0x80 >> (differ_bit % 8)))) { new_node->right = node; } else { new_node->left = node; @@ -756,8 +747,8 @@ static SCRadixNode *SCRadixAddKeyInternal(uint8_t *key_stream, uint8_t key_bitle } if (i < node->netmask_cnt) { - if ( (inter_node->netmasks = SCMalloc((node->netmask_cnt - i) * - sizeof(uint8_t))) == NULL) { + if ((inter_node->netmasks = SCMalloc((node->netmask_cnt - i) * sizeof(uint8_t))) == + NULL) { SCLogError("Fatal error encountered in SCRadixAddKey. Mem not allocated..."); SCRadixReleaseNode(inter_node, tree); SCRadixReleaseNode(new_node, tree); @@ -773,8 +764,7 @@ static SCRadixNode *SCRadixAddKeyInternal(uint8_t *key_stream, uint8_t key_bitle } } - if (SC_RADIX_BITTEST(stream[differ_bit >> 3], - (0x80 >> (differ_bit % 8))) ) { + if (SC_RADIX_BITTEST(stream[differ_bit >> 3], (0x80 >> (differ_bit % 8)))) { inter_node->left = node; inter_node->right = new_node; } else { @@ -803,8 +793,7 @@ static SCRadixNode *SCRadixAddKeyInternal(uint8_t *key_stream, uint8_t key_bitle } node->netmask_cnt++; - if ( (ptmp = SCRealloc(node->netmasks, (node->netmask_cnt * - sizeof(uint8_t)))) == NULL) { + if ((ptmp = SCRealloc(node->netmasks, (node->netmask_cnt * sizeof(uint8_t)))) == NULL) { SCFree(node->netmasks); node->netmasks = NULL; FatalError("Fatal error encountered in SCRadixAddKey. Exiting..."); @@ -855,8 +844,7 @@ static SCRadixNode *SCRadixAddKey( * * \retval node Pointer to the newly created node */ -SCRadixNode *SCRadixAddKeyIPV4(uint8_t *key_stream, SCRadixTree *tree, - void *user) +SCRadixNode *SCRadixAddKeyIPV4(uint8_t *key_stream, SCRadixTree *tree, void *user) { SCRadixNode *node = SCRadixAddKey(key_stream, 32, tree, user, 32); @@ -874,8 +862,7 @@ SCRadixNode *SCRadixAddKeyIPV4(uint8_t *key_stream, SCRadixTree *tree, * * \retval node Pointer to the newly created node */ -SCRadixNode *SCRadixAddKeyIPV6(uint8_t *key_stream, SCRadixTree *tree, - void *user) +SCRadixNode *SCRadixAddKeyIPV6(uint8_t *key_stream, SCRadixTree *tree, void *user) { SCRadixNode *node = SCRadixAddKey(key_stream, 128, tree, user, 128); @@ -937,8 +924,8 @@ static void SCRadixValidateIPv6Key(uint8_t *key, const uint8_t netmask) * * \retval node Pointer to the newly created node */ -SCRadixNode *SCRadixAddKeyIPV4Netblock(uint8_t *key_stream, SCRadixTree *tree, - void *user, uint8_t netmask) +SCRadixNode *SCRadixAddKeyIPV4Netblock( + uint8_t *key_stream, SCRadixTree *tree, void *user, uint8_t netmask) { #if defined(DEBUG_VALIDATION) || defined(UNITTESTS) SCRadixValidateIPv4Key(key_stream, netmask); @@ -960,8 +947,8 @@ SCRadixNode *SCRadixAddKeyIPV4Netblock(uint8_t *key_stream, SCRadixTree *tree, * * \retval node Pointer to the newly created node */ -SCRadixNode *SCRadixAddKeyIPV6Netblock(uint8_t *key_stream, SCRadixTree *tree, - void *user, uint8_t netmask) +SCRadixNode *SCRadixAddKeyIPV6Netblock( + uint8_t *key_stream, SCRadixTree *tree, void *user, uint8_t netmask) { #if defined(DEBUG_VALIDATION) || defined(UNITTESTS) SCRadixValidateIPv6Key(key_stream, netmask); @@ -1141,9 +1128,8 @@ static void SCRadixTransferNetmasksBWNodes(SCRadixNode *dest, SCRadixNode *src) if (src->netmasks == NULL) return; - if ( (ptmp = SCRealloc(dest->netmasks, - (src->netmask_cnt + dest->netmask_cnt) * - sizeof(uint8_t))) == NULL) { + if ((ptmp = SCRealloc(dest->netmasks, + (src->netmask_cnt + dest->netmask_cnt) * sizeof(uint8_t))) == NULL) { SCFree(dest->netmasks); dest->netmasks = NULL; return; @@ -1197,7 +1183,7 @@ static void SCRadixRemoveNetblockEntry(SCRadixNode *node, uint8_t netmask) return; } - for ( ; i < node->netmask_cnt - 1; i++) + for (; i < node->netmask_cnt - 1; i++) node->netmasks[i] = node->netmasks[i + 1]; node->netmask_cnt--; @@ -1227,8 +1213,8 @@ static void SCRadixRemoveNetblockEntry(SCRadixNode *node, uint8_t netmask) * \param tree Pointer to the Radix tree from which the key has to be * removed */ -static void SCRadixRemoveKey(uint8_t *key_stream, uint16_t key_bitlen, - SCRadixTree *tree, uint8_t netmask) +static void SCRadixRemoveKey( + uint8_t *key_stream, uint16_t key_bitlen, SCRadixTree *tree, uint8_t netmask) { SCRadixNode *node = tree->head; SCRadixNode *parent = NULL; @@ -1242,12 +1228,11 @@ static void SCRadixRemoveKey(uint8_t *key_stream, uint16_t key_bitlen, if (node == NULL) return; - if ( (prefix = SCRadixCreatePrefix(key_stream, key_bitlen, NULL, 255)) == NULL) + if ((prefix = SCRadixCreatePrefix(key_stream, key_bitlen, NULL, 255)) == NULL) return; while (node->bit < prefix->bitlen) { - if (SC_RADIX_BITTEST(prefix->stream[node->bit >> 3], - (0x80 >> (node->bit % 8))) ) { + if (SC_RADIX_BITTEST(prefix->stream[node->bit >> 3], (0x80 >> (node->bit % 8)))) { node = node->right; } else { node = node->left; @@ -1269,10 +1254,11 @@ static void SCRadixRemoveKey(uint8_t *key_stream, uint16_t key_bitlen, mask = UINT_MAX << (8 - prefix->bitlen % 8); if (prefix->bitlen % 8 == 0 || - (node->prefix->stream[i] & mask) == (prefix->stream[i] & mask)) { + (node->prefix->stream[i] & mask) == (prefix->stream[i] & mask)) { if (!SCRadixPrefixContainNetmask(node->prefix, netmask)) { SCLogDebug("The ip key exists in the Radix Tree, but this(%d) " - "netblock entry doesn't exist", netmask); + "netblock entry doesn't exist", + netmask); SCRadixReleasePrefix(prefix, tree); return; } @@ -1363,8 +1349,7 @@ static void SCRadixRemoveKey(uint8_t *key_stream, uint16_t key_bitlen, * \param tree Pointer to the Radix tree from which the key has to be * removed */ -void SCRadixRemoveKeyGeneric(uint8_t *key_stream, uint16_t key_bitlen, - SCRadixTree *tree) +void SCRadixRemoveKeyGeneric(uint8_t *key_stream, uint16_t key_bitlen, SCRadixTree *tree) { SCRadixRemoveKey(key_stream, key_bitlen, tree, 255); return; @@ -1378,8 +1363,7 @@ void SCRadixRemoveKeyGeneric(uint8_t *key_stream, uint16_t key_bitlen, * \param tree Pointer to the Radix tree from which the key has to be * removed */ -void SCRadixRemoveKeyIPV4Netblock(uint8_t *key_stream, SCRadixTree *tree, - uint8_t netmask) +void SCRadixRemoveKeyIPV4Netblock(uint8_t *key_stream, SCRadixTree *tree, uint8_t netmask) { #if defined(DEBUG_VALIDATION) || defined(UNITTESTS) SCRadixValidateIPv4Key(key_stream, netmask); @@ -1412,8 +1396,7 @@ void SCRadixRemoveKeyIPV4(uint8_t *key_stream, SCRadixTree *tree) * \param tree Pointer to the Radix tree from which the key has to be * removed */ -void SCRadixRemoveKeyIPV6Netblock(uint8_t *key_stream, SCRadixTree *tree, - uint8_t netmask) +void SCRadixRemoveKeyIPV6Netblock(uint8_t *key_stream, SCRadixTree *tree, uint8_t netmask) { #if defined(DEBUG_VALIDATION) || defined(UNITTESTS) SCRadixValidateIPv6Key(key_stream, netmask); @@ -1467,8 +1450,8 @@ static inline SCRadixNode *SCRadixFindKeyIPNetblock( bytes = key_bitlen / 8; for (i = 0; i < bytes; i++) { mask = UINT_MAX; - if ( ((i + 1) * 8) > netmask_node->netmasks[j]) { - if ( ((i + 1) * 8 - netmask_node->netmasks[j]) < 8) + if (((i + 1) * 8) > netmask_node->netmasks[j]) { + if (((i + 1) * 8 - netmask_node->netmasks[j]) < 8) mask = UINT_MAX << ((i + 1) * 8 - netmask_node->netmasks[j]); else mask = 0; @@ -1477,8 +1460,7 @@ static inline SCRadixNode *SCRadixFindKeyIPNetblock( } while (node->bit < key_bitlen) { - if (SC_RADIX_BITTEST(key_stream[node->bit >> 3], - (0x80 >> (node->bit % 8))) ) { + if (SC_RADIX_BITTEST(key_stream[node->bit >> 3], (0x80 >> (node->bit % 8)))) { node = node->right; } else { node = node->left; @@ -1495,7 +1477,7 @@ static inline SCRadixNode *SCRadixFindKeyIPNetblock( mask = UINT_MAX << (8 - key_bitlen % 8); if (key_bitlen % 8 == 0 || - (node->prefix->stream[bytes] & mask) == (key_stream[bytes] & mask)) { + (node->prefix->stream[bytes] & mask) == (key_stream[bytes] & mask)) { if (SCRadixPrefixContainNetmaskAndSetUserData( node->prefix, netmask_node->netmasks[j], false, user_data_result)) return node; @@ -1531,8 +1513,7 @@ static SCRadixNode *SCRadixFindKey(uint8_t *key_stream, uint8_t key_bitlen, uint memcpy(tmp_stream, key_stream, key_bitlen / 8); while (node->bit < key_bitlen) { - if (SC_RADIX_BITTEST(tmp_stream[node->bit >> 3], - (0x80 >> (node->bit % 8))) ) { + if (SC_RADIX_BITTEST(tmp_stream[node->bit >> 3], (0x80 >> (node->bit % 8)))) { node = node->right; } else { node = node->left; @@ -1552,7 +1533,7 @@ static SCRadixNode *SCRadixFindKey(uint8_t *key_stream, uint8_t key_bitlen, uint mask = UINT_MAX << (8 - key_bitlen % 8); if (key_bitlen % 8 == 0 || - (node->prefix->stream[bytes] & mask) == (tmp_stream[bytes] & mask)) { + (node->prefix->stream[bytes] & mask) == (tmp_stream[bytes] & mask)) { if (SCRadixPrefixContainNetmaskAndSetUserData( node->prefix, netmask, true, user_data_result)) { return node; @@ -1576,7 +1557,8 @@ static SCRadixNode *SCRadixFindKey(uint8_t *key_stream, uint8_t key_bitlen, uint * an IPV4 address * \param tree Pointer to the Radix tree instance */ -SCRadixNode *SCRadixFindKeyIPV4ExactMatch(uint8_t *key_stream, SCRadixTree *tree, void **user_data_result) +SCRadixNode *SCRadixFindKeyIPV4ExactMatch( + uint8_t *key_stream, SCRadixTree *tree, void **user_data_result) { return SCRadixFindKey(key_stream, 32, 32, tree, true, user_data_result); } @@ -1588,7 +1570,8 @@ SCRadixNode *SCRadixFindKeyIPV4ExactMatch(uint8_t *key_stream, SCRadixTree *tree * an IPV4 address * \param tree Pointer to the Radix tree instance */ -SCRadixNode *SCRadixFindKeyIPV4BestMatch(uint8_t *key_stream, SCRadixTree *tree, void **user_data_result) +SCRadixNode *SCRadixFindKeyIPV4BestMatch( + uint8_t *key_stream, SCRadixTree *tree, void **user_data_result) { return SCRadixFindKey(key_stream, 32, 32, tree, false, user_data_result); } @@ -1600,8 +1583,8 @@ SCRadixNode *SCRadixFindKeyIPV4BestMatch(uint8_t *key_stream, SCRadixTree *tree, * an IPV4 netblock address * \param tree Pointer to the Radix tree instance */ -SCRadixNode *SCRadixFindKeyIPV4Netblock(uint8_t *key_stream, SCRadixTree *tree, - uint8_t netmask, void **user_data_result) +SCRadixNode *SCRadixFindKeyIPV4Netblock( + uint8_t *key_stream, SCRadixTree *tree, uint8_t netmask, void **user_data_result) { #if defined(DEBUG_VALIDATION) || defined(UNITTESTS) SCRadixValidateIPv4Key(key_stream, netmask); @@ -1617,8 +1600,8 @@ SCRadixNode *SCRadixFindKeyIPV4Netblock(uint8_t *key_stream, SCRadixTree *tree, * an IPV6 netblock address * \param tree Pointer to the Radix tree instance */ -SCRadixNode *SCRadixFindKeyIPV6Netblock(uint8_t *key_stream, SCRadixTree *tree, - uint8_t netmask, void **user_data_result) +SCRadixNode *SCRadixFindKeyIPV6Netblock( + uint8_t *key_stream, SCRadixTree *tree, uint8_t netmask, void **user_data_result) { #if defined(DEBUG_VALIDATION) || defined(UNITTESTS) SCRadixValidateIPv6Key(key_stream, netmask); @@ -1634,7 +1617,8 @@ SCRadixNode *SCRadixFindKeyIPV6Netblock(uint8_t *key_stream, SCRadixTree *tree, * an IPV6 address * \param tree Pointer to the Radix tree instance */ -SCRadixNode *SCRadixFindKeyIPV6ExactMatch(uint8_t *key_stream, SCRadixTree *tree, void **user_data_result) +SCRadixNode *SCRadixFindKeyIPV6ExactMatch( + uint8_t *key_stream, SCRadixTree *tree, void **user_data_result) { return SCRadixFindKey(key_stream, 128, 128, tree, true, user_data_result); } @@ -1646,7 +1630,8 @@ SCRadixNode *SCRadixFindKeyIPV6ExactMatch(uint8_t *key_stream, SCRadixTree *tree * an IPV6 address * \param tree Pointer to the Radix tree instance */ -SCRadixNode *SCRadixFindKeyIPV6BestMatch(uint8_t *key_stream, SCRadixTree *tree, void **user_data_result) +SCRadixNode *SCRadixFindKeyIPV6BestMatch( + uint8_t *key_stream, SCRadixTree *tree, void **user_data_result) { return SCRadixFindKey(key_stream, 128, 128, tree, false, user_data_result); } @@ -1657,7 +1642,7 @@ SCRadixNode *SCRadixFindKeyIPV6BestMatch(uint8_t *key_stream, SCRadixTree *tree, * \param node Pointer to the Radix node whose information has to be printed * \param level Used for indentation purposes */ -void SCRadixPrintNodeInfo(SCRadixNode *node, int level, void (*PrintData)(void*)) +void SCRadixPrintNodeInfo(SCRadixNode *node, int level, void (*PrintData)(void *)) { int i = 0; @@ -1709,7 +1694,7 @@ void SCRadixPrintNodeInfo(SCRadixNode *node, int level, void (*PrintData)(void* * \param node Pointer to the node that is the root of the subtree to be printed * \param level Used for indentation purposes */ -static void SCRadixPrintRadixSubtree(SCRadixNode *node, int level, void (*PrintData)(void*)) +static void SCRadixPrintRadixSubtree(SCRadixNode *node, int level, void (*PrintData)(void *)) { if (node != NULL) { SCRadixPrintNodeInfo(node, level, PrintData); @@ -1984,26 +1969,22 @@ static int SCRadixTestIPV6Insertion07(void) /* add the keys */ memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "2003:0BF1:5346:BDEA:7422:8713:9124:2315", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "2003:0BF1:5346:BDEA:7422:8713:9124:2315", &servaddr.sin6_addr) <= 0) return 0; SCRadixAddKeyIPV6((uint8_t *)&servaddr.sin6_addr, tree, NULL); memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "BD15:9791:5346:6223:AADB:8713:9882:2432", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "BD15:9791:5346:6223:AADB:8713:9882:2432", &servaddr.sin6_addr) <= 0) return 0; SCRadixAddKeyIPV6((uint8_t *)&servaddr.sin6_addr, tree, NULL); memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "1111:A21B:6221:BDEA:BBBA::DBAA:9861", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "1111:A21B:6221:BDEA:BBBA::DBAA:9861", &servaddr.sin6_addr) <= 0) return 0; SCRadixAddKeyIPV6((uint8_t *)&servaddr.sin6_addr, tree, NULL); memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "4444:0BF7:5346:BDEA:7422:8713:9124:2315", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "4444:0BF7:5346:BDEA:7422:8713:9124:2315", &servaddr.sin6_addr) <= 0) return 0; SCRadixAddKeyIPV6((uint8_t *)&servaddr.sin6_addr, tree, NULL); @@ -2011,75 +1992,63 @@ static int SCRadixTestIPV6Insertion07(void) SCRadixAddKeyIPV6((uint8_t *)&servaddr.sin6_addr, tree, NULL); memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "5555:0BF1:ABCD:ADEA:7922:ABCD:9124:2375", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "5555:0BF1:ABCD:ADEA:7922:ABCD:9124:2375", &servaddr.sin6_addr) <= 0) return 0; SCRadixAddKeyIPV6((uint8_t *)&servaddr.sin6_addr, tree, NULL); memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "DBCA:ABCD:ABCD:DBCA:1245:2342:1111:2212", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "DBCA:ABCD:ABCD:DBCA:1245:2342:1111:2212", &servaddr.sin6_addr) <= 0) return 0; SCRadixAddKeyIPV6((uint8_t *)&servaddr.sin6_addr, tree, NULL); memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "2003:0BF1:5346:1251:7422:1112:9124:2315", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "2003:0BF1:5346:1251:7422:1112:9124:2315", &servaddr.sin6_addr) <= 0) return 0; SCRadixAddKeyIPV6((uint8_t *)&servaddr.sin6_addr, tree, NULL); /* test the existence of keys */ memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "2003:0BF1:5346:BDEA:7422:8713:9124:2315", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "2003:0BF1:5346:BDEA:7422:8713:9124:2315", &servaddr.sin6_addr) <= 0) return 0; result &= (SCRadixFindKeyIPV6ExactMatch((uint8_t *)&servaddr.sin6_addr, tree, NULL) != NULL); memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "BD15:9791:5346:6223:AADB:8713:9882:2432", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "BD15:9791:5346:6223:AADB:8713:9882:2432", &servaddr.sin6_addr) <= 0) return 0; result &= (SCRadixFindKeyIPV6ExactMatch((uint8_t *)&servaddr.sin6_addr, tree, NULL) != NULL); memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "1111:A21B:6221:BDEA:BBBA::DBAA:9861", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "1111:A21B:6221:BDEA:BBBA::DBAA:9861", &servaddr.sin6_addr) <= 0) return 0; result &= (SCRadixFindKeyIPV6ExactMatch((uint8_t *)&servaddr.sin6_addr, tree, NULL) != NULL); memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "4444:0BF7:5346:BDEA:7422:8713:9124:2315", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "4444:0BF7:5346:BDEA:7422:8713:9124:2315", &servaddr.sin6_addr) <= 0) return 0; result &= (SCRadixFindKeyIPV6ExactMatch((uint8_t *)&servaddr.sin6_addr, tree, NULL) != NULL); memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "DBCA:ABC2:ABCD:DBCA:1245:2342:1111:2212", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "DBCA:ABC2:ABCD:DBCA:1245:2342:1111:2212", &servaddr.sin6_addr) <= 0) return 0; result &= (SCRadixFindKeyIPV6ExactMatch((uint8_t *)&servaddr.sin6_addr, tree, NULL) == NULL); memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "2003:0BF5:5346:1251:7422:1112:9124:2315", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "2003:0BF5:5346:1251:7422:1112:9124:2315", &servaddr.sin6_addr) <= 0) return 0; result &= (SCRadixFindKeyIPV6ExactMatch((uint8_t *)&servaddr.sin6_addr, tree, NULL) == NULL); memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "5555:0BF1:ABCD:ADEA:7922:ABCD:9124:2375", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "5555:0BF1:ABCD:ADEA:7922:ABCD:9124:2375", &servaddr.sin6_addr) <= 0) return 0; result &= (SCRadixFindKeyIPV6ExactMatch((uint8_t *)&servaddr.sin6_addr, tree, NULL) != NULL); memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "DBCA:ABCD:ABCD:DBCA:1245:2342:1111:2212", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "DBCA:ABCD:ABCD:DBCA:1245:2342:1111:2212", &servaddr.sin6_addr) <= 0) return 0; result &= (SCRadixFindKeyIPV6ExactMatch((uint8_t *)&servaddr.sin6_addr, tree, NULL) != NULL); memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "2003:0BF1:5346:1251:7422:1112:9124:2315", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "2003:0BF1:5346:1251:7422:1112:9124:2315", &servaddr.sin6_addr) <= 0) return 0; result &= (SCRadixFindKeyIPV6ExactMatch((uint8_t *)&servaddr.sin6_addr, tree, NULL) != NULL); @@ -2098,26 +2067,22 @@ static int SCRadixTestIPV6Removal08(void) /* add the keys */ memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "2003:0BF1:5346:BDEA:7422:8713:9124:2315", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "2003:0BF1:5346:BDEA:7422:8713:9124:2315", &servaddr.sin6_addr) <= 0) return 0; SCRadixAddKeyIPV6((uint8_t *)&servaddr.sin6_addr, tree, NULL); memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "BD15:9791:5346:6223:AADB:8713:9882:2432", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "BD15:9791:5346:6223:AADB:8713:9882:2432", &servaddr.sin6_addr) <= 0) return 0; SCRadixAddKeyIPV6((uint8_t *)&servaddr.sin6_addr, tree, NULL); memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "1111:A21B:6221:BDEA:BBBA::DBAA:9861", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "1111:A21B:6221:BDEA:BBBA::DBAA:9861", &servaddr.sin6_addr) <= 0) return 0; SCRadixAddKeyIPV6((uint8_t *)&servaddr.sin6_addr, tree, NULL); memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "4444:0BF7:5346:BDEA:7422:8713:9124:2315", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "4444:0BF7:5346:BDEA:7422:8713:9124:2315", &servaddr.sin6_addr) <= 0) return 0; SCRadixAddKeyIPV6((uint8_t *)&servaddr.sin6_addr, tree, NULL); @@ -2125,200 +2090,168 @@ static int SCRadixTestIPV6Removal08(void) SCRadixAddKeyIPV6((uint8_t *)&servaddr.sin6_addr, tree, NULL); memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "5555:0BF1:ABCD:ADEA:7922:ABCD:9124:2375", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "5555:0BF1:ABCD:ADEA:7922:ABCD:9124:2375", &servaddr.sin6_addr) <= 0) return 0; SCRadixAddKeyIPV6((uint8_t *)&servaddr.sin6_addr, tree, NULL); memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "DBCA:ABCD:ABCD:DBCA:1245:2342:1111:2212", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "DBCA:ABCD:ABCD:DBCA:1245:2342:1111:2212", &servaddr.sin6_addr) <= 0) return 0; SCRadixAddKeyIPV6((uint8_t *)&servaddr.sin6_addr, tree, NULL); memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "2003:0BF1:5346:1251:7422:1112:9124:2315", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "2003:0BF1:5346:1251:7422:1112:9124:2315", &servaddr.sin6_addr) <= 0) return 0; SCRadixAddKeyIPV6((uint8_t *)&servaddr.sin6_addr, tree, NULL); /* test the existence of keys */ memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "2003:0BF1:5346:BDEA:7422:8713:9124:2315", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "2003:0BF1:5346:BDEA:7422:8713:9124:2315", &servaddr.sin6_addr) <= 0) return 0; SCRadixAddKeyIPV6((uint8_t *)&servaddr.sin6_addr, tree, NULL); memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "8888:0BF1:5346:BDEA:6422:8713:9124:2315", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "8888:0BF1:5346:BDEA:6422:8713:9124:2315", &servaddr.sin6_addr) <= 0) return 0; result &= (SCRadixFindKeyIPV6ExactMatch((uint8_t *)&servaddr.sin6_addr, tree, NULL) == NULL); memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "2006:0BF1:5346:BDEA:7422:8713:9124:2315", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "2006:0BF1:5346:BDEA:7422:8713:9124:2315", &servaddr.sin6_addr) <= 0) return 0; result &= (SCRadixFindKeyIPV6ExactMatch((uint8_t *)&servaddr.sin6_addr, tree, NULL) == NULL); memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "2003:0BF1:5346:BDEA:7422:8713:9124:2315", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "2003:0BF1:5346:BDEA:7422:8713:9124:2315", &servaddr.sin6_addr) <= 0) return 0; result &= (SCRadixFindKeyIPV6ExactMatch((uint8_t *)&servaddr.sin6_addr, tree, NULL) != NULL); memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "BD15:9791:5346:6223:AADB:8713:9882:2432", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "BD15:9791:5346:6223:AADB:8713:9882:2432", &servaddr.sin6_addr) <= 0) return 0; SCRadixAddKeyIPV6((uint8_t *)&servaddr.sin6_addr, tree, NULL); /* test for existence */ memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "1111:A21B:6221:BDEA:BBBA::DBAA:9861", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "1111:A21B:6221:BDEA:BBBA::DBAA:9861", &servaddr.sin6_addr) <= 0) return 0; result &= (SCRadixFindKeyIPV6ExactMatch((uint8_t *)&servaddr.sin6_addr, tree, NULL) != NULL); memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "4444:0BF7:5346:BDEA:7422:8713:9124:2315", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "4444:0BF7:5346:BDEA:7422:8713:9124:2315", &servaddr.sin6_addr) <= 0) return 0; result &= (SCRadixFindKeyIPV6ExactMatch((uint8_t *)&servaddr.sin6_addr, tree, NULL) != NULL); memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "5555:0BF1:ABCD:ADEA:7922:ABCD:9124:2375", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "5555:0BF1:ABCD:ADEA:7922:ABCD:9124:2375", &servaddr.sin6_addr) <= 0) return 0; result &= (SCRadixFindKeyIPV6ExactMatch((uint8_t *)&servaddr.sin6_addr, tree, NULL) != NULL); memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "DBCA:ABCD:ABCD:DBCA:1245:2342:1111:2212", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "DBCA:ABCD:ABCD:DBCA:1245:2342:1111:2212", &servaddr.sin6_addr) <= 0) return 0; result &= (SCRadixFindKeyIPV6ExactMatch((uint8_t *)&servaddr.sin6_addr, tree, NULL) != NULL); memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "2003:0BF1:5346:1251:7422:1112:9124:2315", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "2003:0BF1:5346:1251:7422:1112:9124:2315", &servaddr.sin6_addr) <= 0) return 0; result &= (SCRadixFindKeyIPV6ExactMatch((uint8_t *)&servaddr.sin6_addr, tree, NULL) != NULL); memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "2003:0BF1:5346:BDEA:7422:8713:DDDD:2315", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "2003:0BF1:5346:BDEA:7422:8713:DDDD:2315", &servaddr.sin6_addr) <= 0) return 0; result &= (SCRadixFindKeyIPV6ExactMatch((uint8_t *)&servaddr.sin6_addr, tree, NULL) == NULL); /* remove keys */ memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "2003:0BF1:5346:BDEA:7422:8713:9124:2315", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "2003:0BF1:5346:BDEA:7422:8713:9124:2315", &servaddr.sin6_addr) <= 0) return 0; SCRadixRemoveKeyIPV6((uint8_t *)&servaddr.sin6_addr, tree); memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "BD15:9791:5346:6223:AADB:8713:9882:2432", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "BD15:9791:5346:6223:AADB:8713:9882:2432", &servaddr.sin6_addr) <= 0) return 0; SCRadixRemoveKeyIPV6((uint8_t *)&servaddr.sin6_addr, tree); /* test for existence */ memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "2003:0BF1:5346:BDEA:7422:8713:9124:2315", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "2003:0BF1:5346:BDEA:7422:8713:9124:2315", &servaddr.sin6_addr) <= 0) return 0; result &= (SCRadixFindKeyIPV6ExactMatch((uint8_t *)&servaddr.sin6_addr, tree, NULL) == NULL); memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "BD15:9791:5346:6223:AADB:8713:9882:2432", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "BD15:9791:5346:6223:AADB:8713:9882:2432", &servaddr.sin6_addr) <= 0) return 0; result &= (SCRadixFindKeyIPV6ExactMatch((uint8_t *)&servaddr.sin6_addr, tree, NULL) == NULL); memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "1111:A21B:6221:BDEA:BBBA::DBAA:9861", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "1111:A21B:6221:BDEA:BBBA::DBAA:9861", &servaddr.sin6_addr) <= 0) return 0; result &= (SCRadixFindKeyIPV6ExactMatch((uint8_t *)&servaddr.sin6_addr, tree, NULL) != NULL); memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "4444:0BF7:5346:BDEA:7422:8713:9124:2315", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "4444:0BF7:5346:BDEA:7422:8713:9124:2315", &servaddr.sin6_addr) <= 0) return 0; result &= (SCRadixFindKeyIPV6ExactMatch((uint8_t *)&servaddr.sin6_addr, tree, NULL) != NULL); memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "5555:0BF1:ABCD:ADEA:7922:ABCD:9124:2375", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "5555:0BF1:ABCD:ADEA:7922:ABCD:9124:2375", &servaddr.sin6_addr) <= 0) return 0; result &= (SCRadixFindKeyIPV6ExactMatch((uint8_t *)&servaddr.sin6_addr, tree, NULL) != NULL); memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "DBCA:ABCD:ABCD:DBCA:1245:2342:1111:2212", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "DBCA:ABCD:ABCD:DBCA:1245:2342:1111:2212", &servaddr.sin6_addr) <= 0) return 0; result &= (SCRadixFindKeyIPV6ExactMatch((uint8_t *)&servaddr.sin6_addr, tree, NULL) != NULL); /* remove keys */ memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "1111:A21B:6221:BDEA:BBBA::DBAA:9861", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "1111:A21B:6221:BDEA:BBBA::DBAA:9861", &servaddr.sin6_addr) <= 0) return 0; SCRadixRemoveKeyIPV6((uint8_t *)&servaddr.sin6_addr, tree); memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "4444:0BF7:5346:BDEA:7422:8713:9124:2315", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "4444:0BF7:5346:BDEA:7422:8713:9124:2315", &servaddr.sin6_addr) <= 0) return 0; SCRadixRemoveKeyIPV6((uint8_t *)&servaddr.sin6_addr, tree); memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "5555:0BF1:ABCD:ADEA:7922:ABCD:9124:2375", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "5555:0BF1:ABCD:ADEA:7922:ABCD:9124:2375", &servaddr.sin6_addr) <= 0) return 0; SCRadixRemoveKeyIPV6((uint8_t *)&servaddr.sin6_addr, tree); memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "DBCA:ABCD:ABCD:DBCA:1245:2342:1111:2212", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "DBCA:ABCD:ABCD:DBCA:1245:2342:1111:2212", &servaddr.sin6_addr) <= 0) return 0; SCRadixRemoveKeyIPV6((uint8_t *)&servaddr.sin6_addr, tree); /* test for existence */ memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "2003:0BF1:5346:BDEA:7422:8713:9124:2315", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "2003:0BF1:5346:BDEA:7422:8713:9124:2315", &servaddr.sin6_addr) <= 0) return 0; result &= (SCRadixFindKeyIPV6ExactMatch((uint8_t *)&servaddr.sin6_addr, tree, NULL) == NULL); memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "BD15:9791:5346:6223:AADB:8713:9882:2432", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "BD15:9791:5346:6223:AADB:8713:9882:2432", &servaddr.sin6_addr) <= 0) return 0; result &= (SCRadixFindKeyIPV6ExactMatch((uint8_t *)&servaddr.sin6_addr, tree, NULL) == NULL); memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "1111:A21B:6221:BDEA:BBBA::DBAA:9861", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "1111:A21B:6221:BDEA:BBBA::DBAA:9861", &servaddr.sin6_addr) <= 0) return 0; result &= (SCRadixFindKeyIPV6ExactMatch((uint8_t *)&servaddr.sin6_addr, tree, NULL) == NULL); memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "4444:0BF7:5346:BDEA:7422:8713:9124:2315", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "4444:0BF7:5346:BDEA:7422:8713:9124:2315", &servaddr.sin6_addr) <= 0) return 0; result &= (SCRadixFindKeyIPV6ExactMatch((uint8_t *)&servaddr.sin6_addr, tree, NULL) == NULL); memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "5555:0BF1:ABCD:ADEA:7922:ABCD:9124:2375", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "5555:0BF1:ABCD:ADEA:7922:ABCD:9124:2375", &servaddr.sin6_addr) <= 0) return 0; result &= (SCRadixFindKeyIPV6ExactMatch((uint8_t *)&servaddr.sin6_addr, tree, NULL) == NULL); memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "DBCA:ABCD:ABCD:DBCA:1245:2342:1111:2212", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "DBCA:ABCD:ABCD:DBCA:1245:2342:1111:2212", &servaddr.sin6_addr) <= 0) return 0; result &= (SCRadixFindKeyIPV6ExactMatch((uint8_t *)&servaddr.sin6_addr, tree, NULL) == NULL); @@ -3044,121 +2977,101 @@ static int SCRadixTestIPV6NetblockInsertion13(void) /* add the keys */ memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "2003:0BF1:5346:BDEA:7422:8713:9124:2315", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "2003:0BF1:5346:BDEA:7422:8713:9124:2315", &servaddr.sin6_addr) <= 0) return 0; SCRadixAddKeyIPV6((uint8_t *)&servaddr.sin6_addr, tree, NULL); memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "BD15:9791:5346:6223:AADB:8713:9882:2432", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "BD15:9791:5346:6223:AADB:8713:9882:2432", &servaddr.sin6_addr) <= 0) return 0; SCRadixAddKeyIPV6((uint8_t *)&servaddr.sin6_addr, tree, NULL); memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "1111:A21B:6221:BDEA:BBBA::DBAA:9861", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "1111:A21B:6221:BDEA:BBBA::DBAA:9861", &servaddr.sin6_addr) <= 0) return 0; SCRadixAddKeyIPV6((uint8_t *)&servaddr.sin6_addr, tree, NULL); memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "4444:0BF7:5346:BDEA:7422:8713:9124:2315", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "4444:0BF7:5346:BDEA:7422:8713:9124:2315", &servaddr.sin6_addr) <= 0) return 0; SCRadixAddKeyIPV6((uint8_t *)&servaddr.sin6_addr, tree, NULL); memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "5555:0BF1:ABCD:ADEA:7922:ABCD:9124:2375", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "5555:0BF1:ABCD:ADEA:7922:ABCD:9124:2375", &servaddr.sin6_addr) <= 0) return 0; SCRadixAddKeyIPV6((uint8_t *)&servaddr.sin6_addr, tree, NULL); memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "DBCA:ABCD:ABCD:DB00:0000:0000:0000:0000", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "DBCA:ABCD:ABCD:DB00:0000:0000:0000:0000", &servaddr.sin6_addr) <= 0) return 0; SCRadixAddKeyIPV6Netblock((uint8_t *)&servaddr.sin6_addr, tree, NULL, 56); memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "DBCA:ABCD:ABCD:DBAA:1245:2342:1145:6241", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "DBCA:ABCD:ABCD:DBAA:1245:2342:1145:6241", &servaddr.sin6_addr) <= 0) return 0; SCRadixAddKeyIPV6((uint8_t *)&servaddr.sin6_addr, tree, NULL); /* test the existence of keys */ memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "2003:0BF1:5346:BDEA:7422:8713:9124:2315", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "2003:0BF1:5346:BDEA:7422:8713:9124:2315", &servaddr.sin6_addr) <= 0) return 0; result &= (SCRadixFindKeyIPV6ExactMatch((uint8_t *)&servaddr.sin6_addr, tree, NULL) != NULL); memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "BD15:9791:5346:6223:AADB:8713:9882:2432", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "BD15:9791:5346:6223:AADB:8713:9882:2432", &servaddr.sin6_addr) <= 0) return 0; result &= (SCRadixFindKeyIPV6ExactMatch((uint8_t *)&servaddr.sin6_addr, tree, NULL) != NULL); memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "1111:A21B:6221:BDEA:BBBA::DBAA:9861", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "1111:A21B:6221:BDEA:BBBA::DBAA:9861", &servaddr.sin6_addr) <= 0) return 0; result &= (SCRadixFindKeyIPV6ExactMatch((uint8_t *)&servaddr.sin6_addr, tree, NULL) != NULL); memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "1111:A21B:6221:BDEA:BBBA::DBAA:9861", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "1111:A21B:6221:BDEA:BBBA::DBAA:9861", &servaddr.sin6_addr) <= 0) return 0; result &= (SCRadixFindKeyIPV6BestMatch((uint8_t *)&servaddr.sin6_addr, tree, NULL) != NULL); memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "4444:0BF7:5346:BDEA:7422:8713:9124:2315", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "4444:0BF7:5346:BDEA:7422:8713:9124:2315", &servaddr.sin6_addr) <= 0) return 0; result &= (SCRadixFindKeyIPV6ExactMatch((uint8_t *)&servaddr.sin6_addr, tree, NULL) != NULL); memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "DBCA:ABC2:ABCD:DBCA:1245:2342:1111:2212", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "DBCA:ABC2:ABCD:DBCA:1245:2342:1111:2212", &servaddr.sin6_addr) <= 0) return 0; result &= (SCRadixFindKeyIPV6ExactMatch((uint8_t *)&servaddr.sin6_addr, tree, NULL) == NULL); memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "2003:0BF5:5346:1251:7422:1112:9124:2315", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "2003:0BF5:5346:1251:7422:1112:9124:2315", &servaddr.sin6_addr) <= 0) return 0; result &= (SCRadixFindKeyIPV6ExactMatch((uint8_t *)&servaddr.sin6_addr, tree, NULL) == NULL); memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "5555:0BF1:ABCD:ADEA:7922:ABCD:9124:2375", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "5555:0BF1:ABCD:ADEA:7922:ABCD:9124:2375", &servaddr.sin6_addr) <= 0) return 0; result &= (SCRadixFindKeyIPV6ExactMatch((uint8_t *)&servaddr.sin6_addr, tree, NULL) != NULL); memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "DBCA:ABCD:ABCD:DBCA:1245:2342:1111:2212", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "DBCA:ABCD:ABCD:DBCA:1245:2342:1111:2212", &servaddr.sin6_addr) <= 0) return 0; result &= (SCRadixFindKeyIPV6BestMatch((uint8_t *)&servaddr.sin6_addr, tree, NULL) != NULL); memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "DBCA:ABCD:ABCD:DBAA:1245:2342:1146:6241", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "DBCA:ABCD:ABCD:DBAA:1245:2342:1146:6241", &servaddr.sin6_addr) <= 0) return 0; result &= (SCRadixFindKeyIPV6BestMatch((uint8_t *)&servaddr.sin6_addr, tree, NULL) != NULL); memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "DBCA:ABCD:ABCD:DBAA:1245:2342:1356:1241", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "DBCA:ABCD:ABCD:DBAA:1245:2342:1356:1241", &servaddr.sin6_addr) <= 0) return 0; result &= (SCRadixFindKeyIPV6BestMatch((uint8_t *)&servaddr.sin6_addr, tree, NULL) != NULL); memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "DBCA:ABCD:ABCD:DAAA:1245:2342:1146:6241", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "DBCA:ABCD:ABCD:DAAA:1245:2342:1146:6241", &servaddr.sin6_addr) <= 0) return 0; result &= (SCRadixFindKeyIPV6ExactMatch((uint8_t *)&servaddr.sin6_addr, tree, NULL) == NULL); - SCRadixReleaseRadixTree(tree); return result; @@ -3175,88 +3088,74 @@ static int SCRadixTestIPV6NetblockInsertion14(void) /* add the keys */ memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "2003:0BF1:5346:BDEA:7422:8713:9124:2315", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "2003:0BF1:5346:BDEA:7422:8713:9124:2315", &servaddr.sin6_addr) <= 0) return 0; SCRadixAddKeyIPV6((uint8_t *)&servaddr.sin6_addr, tree, NULL); memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "BD15:9791:5346:6223:AADB:8713:9882:2432", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "BD15:9791:5346:6223:AADB:8713:9882:2432", &servaddr.sin6_addr) <= 0) return 0; SCRadixAddKeyIPV6((uint8_t *)&servaddr.sin6_addr, tree, NULL); memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "1111:A21B:6221:BDEA:BBBA::DBAA:9861", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "1111:A21B:6221:BDEA:BBBA::DBAA:9861", &servaddr.sin6_addr) <= 0) return 0; SCRadixAddKeyIPV6((uint8_t *)&servaddr.sin6_addr, tree, NULL); memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "4444:0BF7:5346:BDEA:7422:8713:9124:2315", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "4444:0BF7:5346:BDEA:7422:8713:9124:2315", &servaddr.sin6_addr) <= 0) return 0; SCRadixAddKeyIPV6((uint8_t *)&servaddr.sin6_addr, tree, NULL); memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "5555:0BF1:ABCD:ADEA:7922:ABCD:9124:2375", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "5555:0BF1:ABCD:ADEA:7922:ABCD:9124:2375", &servaddr.sin6_addr) <= 0) return 0; SCRadixAddKeyIPV6((uint8_t *)&servaddr.sin6_addr, tree, NULL); memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "DBCA:ABCD:ABCD:DB00:0000:0000:0000:0000", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "DBCA:ABCD:ABCD:DB00:0000:0000:0000:0000", &servaddr.sin6_addr) <= 0) return 0; SCRadixAddKeyIPV6Netblock((uint8_t *)&servaddr.sin6_addr, tree, NULL, 56); memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "DBCA:ABCD:ABCD:DBAA:1245:2342:1145:6241", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "DBCA:ABCD:ABCD:DBAA:1245:2342:1145:6241", &servaddr.sin6_addr) <= 0) return 0; SCRadixAddKeyIPV6((uint8_t *)&servaddr.sin6_addr, tree, NULL); memset(&servaddr, 0, sizeof(servaddr)); if (inet_pton(AF_INET6, "::", &servaddr.sin6_addr) <= 0) return 0; - node = SCRadixAddKeyIPV6Netblock((uint8_t *)&servaddr.sin6_addr, tree, NULL, - 0); + node = SCRadixAddKeyIPV6Netblock((uint8_t *)&servaddr.sin6_addr, tree, NULL, 0); /* test the existence of keys */ memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "2004:0BF1:5346:BDEA:7422:8713:9124:2315", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "2004:0BF1:5346:BDEA:7422:8713:9124:2315", &servaddr.sin6_addr) <= 0) return 0; result &= (SCRadixFindKeyIPV6ExactMatch((uint8_t *)&servaddr.sin6_addr, tree, NULL) == NULL); memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "2004:0BF1:5346:BDEA:7422:8713:9124:2315", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "2004:0BF1:5346:BDEA:7422:8713:9124:2315", &servaddr.sin6_addr) <= 0) return 0; result &= (SCRadixFindKeyIPV6BestMatch((uint8_t *)&servaddr.sin6_addr, tree, NULL) == node); memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "2004:0BF1:5346:B116:2362:8713:9124:2315", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "2004:0BF1:5346:B116:2362:8713:9124:2315", &servaddr.sin6_addr) <= 0) return 0; result &= (SCRadixFindKeyIPV6BestMatch((uint8_t *)&servaddr.sin6_addr, tree, NULL) == node); memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "2004:0B23:3252:BDEA:7422:8713:9124:2341", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "2004:0B23:3252:BDEA:7422:8713:9124:2341", &servaddr.sin6_addr) <= 0) return 0; result &= (SCRadixFindKeyIPV6BestMatch((uint8_t *)&servaddr.sin6_addr, tree, NULL) == node); memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "DBCA:ABCD:ABCD:DBAA:1245:2342:1145:6241", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "DBCA:ABCD:ABCD:DBAA:1245:2342:1145:6241", &servaddr.sin6_addr) <= 0) return 0; result &= (SCRadixFindKeyIPV6ExactMatch((uint8_t *)&servaddr.sin6_addr, tree, NULL) != NULL && SCRadixFindKeyIPV6ExactMatch((uint8_t *)&servaddr.sin6_addr, tree, NULL) != node); memset(&servaddr, 0, sizeof(servaddr)); - if (inet_pton(AF_INET6, "DBCA:ABCD:ABCD:DBAA:1245:2342:1145:6241", - &servaddr.sin6_addr) <= 0) + if (inet_pton(AF_INET6, "DBCA:ABCD:ABCD:DBAA:1245:2342:1145:6241", &servaddr.sin6_addr) <= 0) return 0; result &= (SCRadixFindKeyIPV6BestMatch((uint8_t *)&servaddr.sin6_addr, tree, NULL) != NULL && SCRadixFindKeyIPV6BestMatch((uint8_t *)&servaddr.sin6_addr, tree, NULL) != node); @@ -3290,7 +3189,8 @@ static int SCRadixTestIPV4NetBlocksAndBestSearch15(void) SCRadixAddKeyIPV4String(str, tree, user); void *user_data = NULL; - SCRadixNode *node = SCRadixFindKeyIPV4BestMatch((uint8_t *)&servaddr.sin_addr, tree, &user_data); + SCRadixNode *node = + SCRadixFindKeyIPV4BestMatch((uint8_t *)&servaddr.sin_addr, tree, &user_data); FAIL_IF_NULL(node); FAIL_IF_NULL(user_data); FAIL_IF(*((uint32_t *)user_data) != i); @@ -3324,7 +3224,8 @@ static int SCRadixTestIPV4NetBlocksAndBestSearch16(void) SCRadixAddKeyIPV4String(str, tree, user); void *user_data = NULL; - SCRadixNode *node = SCRadixFindKeyIPV4BestMatch((uint8_t *)&servaddr.sin_addr, tree, &user_data); + SCRadixNode *node = + SCRadixFindKeyIPV4BestMatch((uint8_t *)&servaddr.sin_addr, tree, &user_data); FAIL_IF_NULL(node); FAIL_IF_NULL(user_data); FAIL_IF(*((uint32_t *)user_data) != i); @@ -3357,7 +3258,8 @@ static int SCRadixTestIPV4NetBlocksAndBestSearch17(void) SCRadixAddKeyIPV4String(str, tree, user); void *user_data = NULL; - SCRadixNode *node = SCRadixFindKeyIPV4BestMatch((uint8_t *)&servaddr.sin_addr, tree, &user_data); + SCRadixNode *node = + SCRadixFindKeyIPV4BestMatch((uint8_t *)&servaddr.sin_addr, tree, &user_data); FAIL_IF_NULL(node); FAIL_IF_NULL(user_data); FAIL_IF(*((uint32_t *)user_data) != i); @@ -3390,7 +3292,8 @@ static int SCRadixTestIPV4NetBlocksAndBestSearch18(void) SCRadixAddKeyIPV4String(str, tree, user); void *user_data = NULL; - SCRadixNode *node = SCRadixFindKeyIPV4BestMatch((uint8_t *)&servaddr.sin_addr, tree, &user_data); + SCRadixNode *node = + SCRadixFindKeyIPV4BestMatch((uint8_t *)&servaddr.sin_addr, tree, &user_data); FAIL_IF_NULL(node); FAIL_IF_NULL(user_data); FAIL_IF(*((uint32_t *)user_data) != i); @@ -3422,7 +3325,8 @@ static int SCRadixTestIPV4NetBlocksAndBestSearch19(void) memset(&servaddr, 0, sizeof(servaddr)); FAIL_IF(inet_pton(AF_INET, "192.168.1.15", &servaddr.sin_addr) <= 0); void *user_data = NULL; - SCRadixNode *node = SCRadixFindKeyIPV4BestMatch((uint8_t *)&servaddr.sin_addr, tree, &user_data); + SCRadixNode *node = + SCRadixFindKeyIPV4BestMatch((uint8_t *)&servaddr.sin_addr, tree, &user_data); FAIL_IF_NULL(node); FAIL_IF_NULL(user_data); FAIL_IF(*((uint32_t *)user_data) != 100); @@ -3525,7 +3429,8 @@ static int SCRadixTestIPV6NetBlocksAndBestSearch20(void) SCRadixAddKeyIPV6String(str, tree, user); void *user_data = NULL; - SCRadixNode *node = SCRadixFindKeyIPV6BestMatch((uint8_t *)&servaddr.sin6_addr, tree, &user_data); + SCRadixNode *node = + SCRadixFindKeyIPV6BestMatch((uint8_t *)&servaddr.sin6_addr, tree, &user_data); FAIL_IF_NULL(node); FAIL_IF_NULL(user_data); FAIL_IF(*((uint32_t *)user_data) != i); @@ -3558,7 +3463,8 @@ static int SCRadixTestIPV6NetBlocksAndBestSearch21(void) SCRadixAddKeyIPV6String(str, tree, user); void *user_data = NULL; - SCRadixNode *node = SCRadixFindKeyIPV6BestMatch((uint8_t *)&servaddr.sin6_addr, tree, &user_data); + SCRadixNode *node = + SCRadixFindKeyIPV6BestMatch((uint8_t *)&servaddr.sin6_addr, tree, &user_data); FAIL_IF_NULL(node); FAIL_IF_NULL(user_data); FAIL_IF(*((uint32_t *)user_data) != i); @@ -3591,7 +3497,8 @@ static int SCRadixTestIPV6NetBlocksAndBestSearch22(void) SCRadixAddKeyIPV6String(str, tree, user); void *user_data = NULL; - SCRadixNode *node = SCRadixFindKeyIPV6BestMatch((uint8_t *)&servaddr.sin6_addr, tree, &user_data); + SCRadixNode *node = + SCRadixFindKeyIPV6BestMatch((uint8_t *)&servaddr.sin6_addr, tree, &user_data); FAIL_IF_NULL(node); FAIL_IF_NULL(user_data); FAIL_IF(*((uint32_t *)user_data) != i); @@ -3624,7 +3531,8 @@ static int SCRadixTestIPV6NetBlocksAndBestSearch23(void) SCRadixAddKeyIPV6String(str, tree, user); void *user_data = NULL; - SCRadixNode *node = SCRadixFindKeyIPV6BestMatch((uint8_t *)&servaddr.sin6_addr, tree, &user_data); + SCRadixNode *node = + SCRadixFindKeyIPV6BestMatch((uint8_t *)&servaddr.sin6_addr, tree, &user_data); FAIL_IF_NULL(node); FAIL_IF_NULL(user_data); FAIL_IF(*((uint32_t *)user_data) != i); @@ -3653,7 +3561,8 @@ static int SCRadixTestIPV6NetBlocksAndBestSearch24(void) memset(&servaddr, 0, sizeof(servaddr)); FAIL_IF(inet_pton(AF_INET6, "ABCD::1", &servaddr.sin6_addr) <= 0); - SCRadixNode *node = SCRadixFindKeyIPV6BestMatch((uint8_t *)&servaddr.sin6_addr, tree, &user_data); + SCRadixNode *node = + SCRadixFindKeyIPV6BestMatch((uint8_t *)&servaddr.sin6_addr, tree, &user_data); FAIL_IF_NULL(node); FAIL_IF_NULL(user_data); FAIL_IF(*((uint32_t *)user_data) != 100); @@ -3807,45 +3716,37 @@ void SCRadixRegisterTests(void) UtRegisterTest("SCRadixTestIPV4Removal04", SCRadixTestIPV4Removal04); UtRegisterTest("SCRadixTestIPV6Insertion07", SCRadixTestIPV6Insertion07); UtRegisterTest("SCRadixTestIPV6Removal08", SCRadixTestIPV6Removal08); - UtRegisterTest("SCRadixTestIPV4NetblockInsertion09", - SCRadixTestIPV4NetblockInsertion09); + UtRegisterTest("SCRadixTestIPV4NetblockInsertion09", SCRadixTestIPV4NetblockInsertion09); UtRegisterTest("SCRadixTestIPV4Bug5066", SCRadixTestIPV4Bug5066); UtRegisterTest("SCRadixTestIPV4Bug5066v2", SCRadixTestIPV4Bug5066v2); UtRegisterTest("SCRadixTestIPV6Bug5066", SCRadixTestIPV6Bug5066); - UtRegisterTest("SCRadixTestIPV4NetblockInsertion10", - SCRadixTestIPV4NetblockInsertion10); - UtRegisterTest("SCRadixTestIPV4NetblockInsertion11", - SCRadixTestIPV4NetblockInsertion11); - UtRegisterTest("SCRadixTestIPV4NetblockInsertion12", - SCRadixTestIPV4NetblockInsertion12); - UtRegisterTest("SCRadixTestIPV6NetblockInsertion13", - SCRadixTestIPV6NetblockInsertion13); - UtRegisterTest("SCRadixTestIPV6NetblockInsertion14", - SCRadixTestIPV6NetblockInsertion14); - UtRegisterTest("SCRadixTestIPV4NetBlocksAndBestSearch15", - SCRadixTestIPV4NetBlocksAndBestSearch15); - UtRegisterTest("SCRadixTestIPV4NetBlocksAndBestSearch16", - SCRadixTestIPV4NetBlocksAndBestSearch16); - UtRegisterTest("SCRadixTestIPV4NetBlocksAndBestSearch17", - SCRadixTestIPV4NetBlocksAndBestSearch17); - UtRegisterTest("SCRadixTestIPV4NetBlocksAndBestSearch18", - SCRadixTestIPV4NetBlocksAndBestSearch18); - UtRegisterTest("SCRadixTestIPV4NetBlocksAndBestSearch19", - SCRadixTestIPV4NetBlocksAndBestSearch19); - UtRegisterTest("SCRadixTestIPV6NetBlocksAndBestSearch20", - SCRadixTestIPV6NetBlocksAndBestSearch20); - UtRegisterTest("SCRadixTestIPV6NetBlocksAndBestSearch21", - SCRadixTestIPV6NetBlocksAndBestSearch21); - UtRegisterTest("SCRadixTestIPV6NetBlocksAndBestSearch22", - SCRadixTestIPV6NetBlocksAndBestSearch22); - UtRegisterTest("SCRadixTestIPV6NetBlocksAndBestSearch23", - SCRadixTestIPV6NetBlocksAndBestSearch23); - UtRegisterTest("SCRadixTestIPV6NetBlocksAndBestSearch24", - SCRadixTestIPV6NetBlocksAndBestSearch24); - UtRegisterTest("SCRadixTestIPV4NetblockInsertion25", - SCRadixTestIPV4NetblockInsertion25); - UtRegisterTest("SCRadixTestIPV4NetblockInsertion26", - SCRadixTestIPV4NetblockInsertion26); + UtRegisterTest("SCRadixTestIPV4NetblockInsertion10", SCRadixTestIPV4NetblockInsertion10); + UtRegisterTest("SCRadixTestIPV4NetblockInsertion11", SCRadixTestIPV4NetblockInsertion11); + UtRegisterTest("SCRadixTestIPV4NetblockInsertion12", SCRadixTestIPV4NetblockInsertion12); + UtRegisterTest("SCRadixTestIPV6NetblockInsertion13", SCRadixTestIPV6NetblockInsertion13); + UtRegisterTest("SCRadixTestIPV6NetblockInsertion14", SCRadixTestIPV6NetblockInsertion14); + UtRegisterTest( + "SCRadixTestIPV4NetBlocksAndBestSearch15", SCRadixTestIPV4NetBlocksAndBestSearch15); + UtRegisterTest( + "SCRadixTestIPV4NetBlocksAndBestSearch16", SCRadixTestIPV4NetBlocksAndBestSearch16); + UtRegisterTest( + "SCRadixTestIPV4NetBlocksAndBestSearch17", SCRadixTestIPV4NetBlocksAndBestSearch17); + UtRegisterTest( + "SCRadixTestIPV4NetBlocksAndBestSearch18", SCRadixTestIPV4NetBlocksAndBestSearch18); + UtRegisterTest( + "SCRadixTestIPV4NetBlocksAndBestSearch19", SCRadixTestIPV4NetBlocksAndBestSearch19); + UtRegisterTest( + "SCRadixTestIPV6NetBlocksAndBestSearch20", SCRadixTestIPV6NetBlocksAndBestSearch20); + UtRegisterTest( + "SCRadixTestIPV6NetBlocksAndBestSearch21", SCRadixTestIPV6NetBlocksAndBestSearch21); + UtRegisterTest( + "SCRadixTestIPV6NetBlocksAndBestSearch22", SCRadixTestIPV6NetBlocksAndBestSearch22); + UtRegisterTest( + "SCRadixTestIPV6NetBlocksAndBestSearch23", SCRadixTestIPV6NetBlocksAndBestSearch23); + UtRegisterTest( + "SCRadixTestIPV6NetBlocksAndBestSearch24", SCRadixTestIPV6NetBlocksAndBestSearch24); + UtRegisterTest("SCRadixTestIPV4NetblockInsertion25", SCRadixTestIPV4NetblockInsertion25); + UtRegisterTest("SCRadixTestIPV4NetblockInsertion26", SCRadixTestIPV4NetblockInsertion26); #endif return; diff --git a/src/util-radix-tree.h b/src/util-radix-tree.h index c43e14eb0126..de4a48a16c5e 100644 --- a/src/util-radix-tree.h +++ b/src/util-radix-tree.h @@ -93,15 +93,13 @@ typedef struct SCRadixTree_ { void (*Free)(void *); } SCRadixTree; -SCRadixTree *SCRadixCreateRadixTree(void (*Free)(void*), void (*PrintData)(void*)); +SCRadixTree *SCRadixCreateRadixTree(void (*Free)(void *), void (*PrintData)(void *)); void SCRadixReleaseRadixTree(SCRadixTree *); SCRadixNode *SCRadixAddKeyIPV4(uint8_t *, SCRadixTree *, void *); SCRadixNode *SCRadixAddKeyIPV6(uint8_t *, SCRadixTree *, void *); -SCRadixNode *SCRadixAddKeyIPV4Netblock(uint8_t *, SCRadixTree *, void *, - uint8_t); -SCRadixNode *SCRadixAddKeyIPV6Netblock(uint8_t *, SCRadixTree *, void *, - uint8_t); +SCRadixNode *SCRadixAddKeyIPV4Netblock(uint8_t *, SCRadixTree *, void *, uint8_t); +SCRadixNode *SCRadixAddKeyIPV6Netblock(uint8_t *, SCRadixTree *, void *, uint8_t); bool SCRadixAddKeyIPV4String(const char *, SCRadixTree *, void *); bool SCRadixAddKeyIPV6String(const char *, SCRadixTree *, void *); @@ -120,7 +118,7 @@ SCRadixNode *SCRadixFindKeyIPV6Netblock(uint8_t *, SCRadixTree *, uint8_t, void SCRadixNode *SCRadixFindKeyIPV6BestMatch(uint8_t *, SCRadixTree *, void **); void SCRadixPrintTree(SCRadixTree *); -void SCRadixPrintNodeInfo(SCRadixNode *, int, void (*PrintData)(void*)); +void SCRadixPrintNodeInfo(SCRadixNode *, int, void (*PrintData)(void *)); void SCRadixRegisterTests(void); diff --git a/src/util-random.c b/src/util-random.c index 0beee3287880..c931a4f61a1d 100644 --- a/src/util-random.c +++ b/src/util-random.c @@ -29,7 +29,7 @@ #include "util-random.h" #include "util-debug.h" -#if !(defined(HAVE_WINCRYPT_H) && defined(OS_WIN32)) +#if !(defined(HAVE_WINCRYPT_H) && defined(OS_WIN32)) #if defined(HAVE_CLOCK_GETTIME) static long int RandomGetClock(void) @@ -74,11 +74,9 @@ long int RandomGet(void) SCLogDebug("CryptAcquireContext error: %" PRIu32, (uint32_t)err); if (err == (DWORD)NTE_BAD_KEYSET) { /* The key doesn't exist yet, create it */ - if (!CryptAcquireContext(&p, NULL, NULL, PROV_RSA_FULL, - CRYPT_NEWKEYSET)) { + if (!CryptAcquireContext(&p, NULL, NULL, PROV_RSA_FULL, CRYPT_NEWKEYSET)) { - SCLogDebug("CryptAcquireContext error: %" PRIu32, - (uint32_t)err); + SCLogDebug("CryptAcquireContext error: %" PRIu32, (uint32_t)err); return -1; } } else { diff --git a/src/util-random.h b/src/util-random.h index 6376c05a3aaa..16e5569be111 100644 --- a/src/util-random.h +++ b/src/util-random.h @@ -27,4 +27,3 @@ long int RandomGet(void); #endif /* __UTIL_RANDOM_H__ */ - diff --git a/src/util-reference-config.c b/src/util-reference-config.c index 89cc1d23881c..303322bfc601 100644 --- a/src/util-reference-config.c +++ b/src/util-reference-config.c @@ -43,8 +43,8 @@ /* the hash functions */ uint32_t SCRConfReferenceHashFunc(HashTable *ht, void *data, uint16_t datalen); -char SCRConfReferenceHashCompareFunc(void *data1, uint16_t datalen1, - void *data2, uint16_t datalen2); +char SCRConfReferenceHashCompareFunc( + void *data1, uint16_t datalen1, void *data2, uint16_t datalen2); void SCRConfReferenceHashFree(void *ch); /* used to get the reference.config file path */ @@ -83,7 +83,6 @@ void SCReferenceConfDeinit(DetectEngineCtx *de_ctx) } } - /** * \brief Inits the context to be used by the Reference Config parsing API. * @@ -103,8 +102,7 @@ static FILE *SCRConfInitContextAndLocalResources(DetectEngineCtx *de_ctx, FILE * { /* init the hash table to be used by the reference config references */ de_ctx->reference_conf_ht = HashTableInit(128, SCRConfReferenceHashFunc, - SCRConfReferenceHashCompareFunc, - SCRConfReferenceHashFree); + SCRConfReferenceHashCompareFunc, SCRConfReferenceHashFree); if (de_ctx->reference_conf_ht == NULL) { SCLogError("Error initializing the hash " "table"); @@ -131,7 +129,6 @@ static FILE *SCRConfInitContextAndLocalResources(DetectEngineCtx *de_ctx, FILE * return fd; } - /** * \brief Returns the path for the Reference Config file. We check if we * can retrieve the path from the yaml conf file. If it is not present, @@ -147,8 +144,8 @@ static const char *SCRConfGetConfFilename(const DetectEngineCtx *de_ctx) if (de_ctx != NULL && strlen(de_ctx->config_prefix) > 0) { char config_value[256]; - snprintf(config_value, sizeof(config_value), - "%s.reference-config-file", de_ctx->config_prefix); + snprintf(config_value, sizeof(config_value), "%s.reference-config-file", + de_ctx->config_prefix); /* try loading prefix setting, fall back to global if that * fails. */ @@ -278,7 +275,7 @@ int SCRConfAddReference(DetectEngineCtx *de_ctx, const char *line) return 0; - error: +error: return -1; } @@ -354,8 +351,7 @@ static bool SCRConfParseFile(DetectEngineCtx *de_ctx, FILE *fd) * * \retval ref Pointer to the new instance of SCRConfReference. */ -SCRConfReference *SCRConfAllocSCRConfReference(const char *system, - const char *url) +SCRConfReference *SCRConfAllocSCRConfReference(const char *system, const char *url) { SCRConfReference *ref = NULL; @@ -441,8 +437,7 @@ uint32_t SCRConfReferenceHashFunc(HashTable *ht, void *data, uint16_t datalen) * \retval 1 On data1 and data2 being equal. * \retval 0 On data1 and data2 not being equal. */ -char SCRConfReferenceHashCompareFunc(void *data1, uint16_t datalen1, - void *data2, uint16_t datalen2) +char SCRConfReferenceHashCompareFunc(void *data1, uint16_t datalen1, void *data2, uint16_t datalen2) { SCRConfReference *ref1 = (SCRConfReference *)data1; SCRConfReference *ref2 = (SCRConfReference *)data2; @@ -523,14 +518,12 @@ int SCRConfLoadReferenceConfigFile(DetectEngineCtx *de_ctx, FILE *fd) * \retval lookup_rconf_info Pointer to the SCRConfReference instance from * the hash table on success; NULL on failure. */ -SCRConfReference *SCRConfGetReference(const char *rconf_name, - DetectEngineCtx *de_ctx) +SCRConfReference *SCRConfGetReference(const char *rconf_name, DetectEngineCtx *de_ctx) { SCRConfReference *ref_conf = SCRConfAllocSCRConfReference(rconf_name, NULL); if (ref_conf == NULL) return NULL; - SCRConfReference *lookup_ref_conf = HashTableLookup(de_ctx->reference_conf_ht, - ref_conf, 0); + SCRConfReference *lookup_ref_conf = HashTableLookup(de_ctx->reference_conf_ht, ref_conf, 0); SCRConfDeAllocSCRConfReference(ref_conf); return lookup_ref_conf; @@ -538,7 +531,6 @@ SCRConfReference *SCRConfGetReference(const char *rconf_name, /*----------------------------------Unittests---------------------------------*/ - #ifdef UNITTESTS /** @@ -547,12 +539,11 @@ SCRConfReference *SCRConfGetReference(const char *rconf_name, */ FILE *SCRConfGenerateValidDummyReferenceConfigFD01(void) { - const char *buffer = - "config reference: one http://www.one.com\n" - "config reference: two http://www.two.com\n" - "config reference: three http://www.three.com\n" - "config reference: one http://www.one.com\n" - "config reference: three http://www.three.com\n"; + const char *buffer = "config reference: one http://www.one.com\n" + "config reference: two http://www.two.com\n" + "config reference: three http://www.three.com\n" + "config reference: one http://www.one.com\n" + "config reference: three http://www.three.com\n"; FILE *fd = SCFmemopen((void *)buffer, strlen(buffer), "r"); if (fd == NULL) @@ -567,12 +558,11 @@ FILE *SCRConfGenerateValidDummyReferenceConfigFD01(void) */ FILE *SCRConfGenerateInvalidDummyReferenceConfigFD02(void) { - const char *buffer = - "config reference: one http://www.one.com\n" - "config_ reference: two http://www.two.com\n" - "config reference_: three http://www.three.com\n" - "config reference: four\n" - "config reference five http://www.five.com\n"; + const char *buffer = "config reference: one http://www.one.com\n" + "config_ reference: two http://www.two.com\n" + "config reference_: three http://www.three.com\n" + "config reference: four\n" + "config reference five http://www.five.com\n"; FILE *fd = SCFmemopen((void *)buffer, strlen(buffer), "r"); if (fd == NULL) @@ -587,11 +577,10 @@ FILE *SCRConfGenerateInvalidDummyReferenceConfigFD02(void) */ FILE *SCRConfGenerateInvalidDummyReferenceConfigFD03(void) { - const char *buffer = - "config reference one http://www.one.com\n" - "config_ reference: two http://www.two.com\n" - "config reference_: three http://www.three.com\n" - "config reference: four\n"; + const char *buffer = "config reference one http://www.one.com\n" + "config_ reference: two http://www.two.com\n" + "config reference_: three http://www.three.com\n" + "config reference: four\n"; FILE *fd = SCFmemopen((void *)buffer, strlen(buffer), "r"); if (fd == NULL) @@ -622,7 +611,7 @@ static int SCRConfTest01(void) if (result == 0) printf("FAILED: de_ctx->reference_conf_ht->count %u: ", de_ctx->reference_conf_ht->count); - end: +end: if (de_ctx != NULL) DetectEngineCtxFree(de_ctx); return result; @@ -648,8 +637,7 @@ static int SCRConfTest02(void) result = (de_ctx->reference_conf_ht->count == 0); - - end: +end: if (de_ctx != NULL) DetectEngineCtxFree(de_ctx); return result; @@ -675,7 +663,7 @@ static int SCRConfTest03(void) result = (de_ctx->reference_conf_ht->count == 1); - end: +end: if (de_ctx != NULL) DetectEngineCtxFree(de_ctx); return result; @@ -706,7 +694,7 @@ static int SCRConfTest04(void) result &= (SCRConfGetReference("three", de_ctx) != NULL); result &= (SCRConfGetReference("four", de_ctx) == NULL); - end: +end: if (de_ctx != NULL) DetectEngineCtxFree(de_ctx); return result; @@ -739,7 +727,7 @@ static int SCRConfTest05(void) result &= (SCRConfGetReference("four", de_ctx) == NULL); result &= (SCRConfGetReference("five", de_ctx) == NULL); - end: +end: if (de_ctx != NULL) DetectEngineCtxFree(de_ctx); return result; @@ -771,7 +759,7 @@ static int SCRConfTest06(void) result &= (SCRConfGetReference("four", de_ctx) == NULL); result &= (SCRConfGetReference("five", de_ctx) == NULL); - end: +end: if (de_ctx != NULL) DetectEngineCtxFree(de_ctx); return result; diff --git a/src/util-reference-config.h b/src/util-reference-config.h index 5334fd7c42c1..9de5e94b4a19 100644 --- a/src/util-reference-config.h +++ b/src/util-reference-config.h @@ -26,8 +26,8 @@ #include "detect.h" -#define REFERENCE_SYSTEM_NAME_MAX 64 -#define REFERENCE_CONTENT_NAME_MAX 1024 +#define REFERENCE_SYSTEM_NAME_MAX 64 +#define REFERENCE_CONTENT_NAME_MAX 1024 /** * \brief Holds a reference from the file - reference.config. @@ -43,8 +43,7 @@ SCRConfReference *SCRConfAllocSCRConfReference(const char *, const char *); void SCRConfDeAllocSCRConfReference(SCRConfReference *); int SCRConfLoadReferenceConfigFile(DetectEngineCtx *, FILE *); void SCRConfDeInitContext(DetectEngineCtx *); -SCRConfReference *SCRConfGetReference(const char *, - DetectEngineCtx *); +SCRConfReference *SCRConfGetReference(const char *, DetectEngineCtx *); int SCRConfAddReference(DetectEngineCtx *de_ctx, const char *line); void SCRConfRegisterTests(void); diff --git a/src/util-rohash.c b/src/util-rohash.c index 53437430291b..ef34c8fa9e74 100644 --- a/src/util-rohash.c +++ b/src/util-rohash.c @@ -44,14 +44,14 @@ /** item_size data beyond this header */ typedef struct ROHashTableItem_ { - uint32_t pos; /**< position relative to other values with same hash */ + uint32_t pos; /**< position relative to other values with same hash */ TAILQ_ENTRY(ROHashTableItem_) next; } ROHashTableItem; /** offset table */ typedef struct ROHashTableOffsets_ { - uint32_t cnt; /**< number of items for this hash */ - uint32_t offset; /**< position in the blob of the first item */ + uint32_t cnt; /**< number of items for this hash */ + uint32_t offset; /**< position in the blob of the first item */ } ROHashTableOffsets; /** \brief initialize a new rohash @@ -116,7 +116,7 @@ void *ROHashLookup(ROHashTable *table, void *data, uint16_t size) SCReturnPtr(NULL, "void"); } - uint32_t hash = hashword(data, table->item_size/4, 0) & hashmask(table->hash_bits); + uint32_t hash = hashword(data, table->item_size / 4, 0) & hashmask(table->hash_bits); /* get offsets start */ ROHashTableOffsets *os = (void *)table + sizeof(ROHashTable); @@ -190,8 +190,9 @@ int ROHashInitFinalize(ROHashTable *table) ROHashTableOffsets *os = (void *)table + sizeof(ROHashTable); /* count items per hash value */ - TAILQ_FOREACH(item, &table->head, next) { - uint32_t hash = hashword((void *)item + sizeof(*item), table->item_size/4, 0) & hashmask(table->hash_bits); + TAILQ_FOREACH (item, &table->head, next) { + uint32_t hash = hashword((void *)item + sizeof(*item), table->item_size / 4, 0) & + hashmask(table->hash_bits); ROHashTableOffsets *o = &os[hash]; item->pos = o->cnt; @@ -226,14 +227,14 @@ int ROHashInitFinalize(ROHashTable *table) } /* copy each value into the data block */ - TAILQ_FOREACH(item, &table->head, next) { - uint32_t hash = hashword((void *)item + sizeof(*item), table->item_size/4, 0) & hashmask(table->hash_bits); + TAILQ_FOREACH (item, &table->head, next) { + uint32_t hash = hashword((void *)item + sizeof(*item), table->item_size / 4, 0) & + hashmask(table->hash_bits); ROHashTableOffsets *o = &os[hash]; uint32_t offset = (o->offset + item->pos) * table->item_size; memcpy(table->data + offset, (void *)item + sizeof(*item), table->item_size); - } /* clean up temp items */ diff --git a/src/util-rohash.h b/src/util-rohash.h index 3b044274a54b..1f86aecc53a8 100644 --- a/src/util-rohash.h +++ b/src/util-rohash.h @@ -24,7 +24,6 @@ #ifndef __UTIL_ROHASH_H__ #define __UTIL_ROHASH_H__ - typedef struct ROHashTable_ { uint8_t locked; uint8_t hash_bits; diff --git a/src/util-rule-vars.c b/src/util-rule-vars.c index e526035d030a..2a3a8de02f91 100644 --- a/src/util-rule-vars.c +++ b/src/util-rule-vars.c @@ -40,10 +40,8 @@ /** An enum-string map, that maps the different vars type in the yaml conf * type with the mapping path in the yaml conf file */ -SCEnumCharMap sc_rule_vars_type_map[ ] = { - { "vars.address-groups", SC_RULE_VARS_ADDRESS_GROUPS }, - { "vars.port-groups", SC_RULE_VARS_PORT_GROUPS } -}; +SCEnumCharMap sc_rule_vars_type_map[] = { { "vars.address-groups", SC_RULE_VARS_ADDRESS_GROUPS }, + { "vars.port-groups", SC_RULE_VARS_PORT_GROUPS } }; /** * \internal @@ -62,9 +60,8 @@ SCEnumCharMap sc_rule_vars_type_map[ ] = { * \retval conf_var_name_value Pointer to the string containing the conf value * on success; NULL on failure. */ -const char *SCRuleVarsGetConfVar(const DetectEngineCtx *de_ctx, - const char *conf_var_name, - SCRuleVarsType conf_vars_type) +const char *SCRuleVarsGetConfVar( + const DetectEngineCtx *de_ctx, const char *conf_var_name, SCRuleVarsType conf_vars_type) { SCEnter(); @@ -80,8 +77,7 @@ const char *SCRuleVarsGetConfVar(const DetectEngineCtx *de_ctx, } (conf_var_name[0] == '$') ? conf_var_name++ : conf_var_name; - conf_var_type_name = SCMapEnumValueToName(conf_vars_type, - sc_rule_vars_type_map); + conf_var_type_name = SCMapEnumValueToName(conf_vars_type, sc_rule_vars_type_map); if (conf_var_type_name == NULL) goto end; @@ -91,8 +87,8 @@ const char *SCRuleVarsGetConfVar(const DetectEngineCtx *de_ctx, goto end; } } else { - if (snprintf(conf_var_full_name, sizeof(conf_var_full_name), "%s.%s", - conf_var_type_name, conf_var_name) < 0) { + if (snprintf(conf_var_full_name, sizeof(conf_var_full_name), "%s.%s", conf_var_type_name, + conf_var_name) < 0) { goto end; } } @@ -105,81 +101,81 @@ const char *SCRuleVarsGetConfVar(const DetectEngineCtx *de_ctx, } SCLogDebug("Value obtained from the yaml conf file, for the var " - "\"%s\" is \"%s\"", conf_var_name, conf_var_full_name_value); + "\"%s\" is \"%s\"", + conf_var_name, conf_var_full_name_value); - end: +end: SCReturnCharPtr(conf_var_full_name_value); } - /**********************************Unittests***********************************/ #ifdef UNITTESTS static const char *dummy_conf_string = - "%YAML 1.1\n" - "---\n" - "\n" - "default-log-dir: /var/log/suricata\n" - "\n" - "logging:\n" - "\n" - " default-log-level: debug\n" - "\n" - " default-format: \"<%t> - <%l>\"\n" - "\n" - " default-startup-message: Your IDS has started.\n" - "\n" - " default-output-filter:\n" - "\n" - " output:\n" - "\n" - " - interface: console\n" - " log-level: info\n" - "\n" - " - interface: file\n" - " filename: /var/log/suricata.log\n" - "\n" - " - interface: syslog\n" - " facility: local5\n" - " format: \"%l\"\n" - "\n" - "pfring:\n" - "\n" - " interface: eth0\n" - "\n" - " clusterid: 99\n" - "\n" - "vars:\n" - "\n" - " address-groups:\n" - "\n" - " HOME_NET: \"[192.168.0.0/16,10.8.0.0/16,127.0.0.1,2001:888:" - "13c5:5AFE::/64,2001:888:13c5:CAFE::/64]\"\n" - "\n" - " EXTERNAL_NET: \"[!192.168.0.0/16,2000::/3]\"\n" - "\n" - " HTTP_SERVERS: \"!192.168.0.0/16\"\n" - "\n" - " SMTP_SERVERS: \"!192.168.0.0/16\"\n" - "\n" - " SQL_SERVERS: \"!192.168.0.0/16\"\n" - "\n" - " DNS_SERVERS: any\n" - "\n" - " TELNET_SERVERS: any\n" - "\n" - " AIM_SERVERS: any\n" - "\n" - " port-groups:\n" - "\n" - " HTTP_PORTS: \"80:81,88\"\n" - "\n" - " SHELLCODE_PORTS: 80\n" - "\n" - " ORACLE_PORTS: 1521\n" - "\n" - " SSH_PORTS: 22\n" - "\n"; + "%YAML 1.1\n" + "---\n" + "\n" + "default-log-dir: /var/log/suricata\n" + "\n" + "logging:\n" + "\n" + " default-log-level: debug\n" + "\n" + " default-format: \"<%t> - <%l>\"\n" + "\n" + " default-startup-message: Your IDS has started.\n" + "\n" + " default-output-filter:\n" + "\n" + " output:\n" + "\n" + " - interface: console\n" + " log-level: info\n" + "\n" + " - interface: file\n" + " filename: /var/log/suricata.log\n" + "\n" + " - interface: syslog\n" + " facility: local5\n" + " format: \"%l\"\n" + "\n" + "pfring:\n" + "\n" + " interface: eth0\n" + "\n" + " clusterid: 99\n" + "\n" + "vars:\n" + "\n" + " address-groups:\n" + "\n" + " HOME_NET: \"[192.168.0.0/16,10.8.0.0/16,127.0.0.1,2001:888:" + "13c5:5AFE::/64,2001:888:13c5:CAFE::/64]\"\n" + "\n" + " EXTERNAL_NET: \"[!192.168.0.0/16,2000::/3]\"\n" + "\n" + " HTTP_SERVERS: \"!192.168.0.0/16\"\n" + "\n" + " SMTP_SERVERS: \"!192.168.0.0/16\"\n" + "\n" + " SQL_SERVERS: \"!192.168.0.0/16\"\n" + "\n" + " DNS_SERVERS: any\n" + "\n" + " TELNET_SERVERS: any\n" + "\n" + " AIM_SERVERS: any\n" + "\n" + " port-groups:\n" + "\n" + " HTTP_PORTS: \"80:81,88\"\n" + "\n" + " SHELLCODE_PORTS: 80\n" + "\n" + " ORACLE_PORTS: 1521\n" + "\n" + " SSH_PORTS: 22\n" + "\n"; /** * \test Check that valid address and port group vars are correctly retrieved @@ -320,26 +316,25 @@ static int SCRuleVarsNegativeTest04(void) PASS; } -static const char *dummy_mt_conf_string = - "%YAML 1.1\n" - "---\n" - "vars:\n" - "\n" - " address-groups:\n" - "\n" - " HOME_NET: \"[1.2.3.4]\"\n" - " port-groups:\n" - " HTTP_PORTS: \"12345\"\n" - "multi-detect:\n" - " 0:\n" - " vars:\n" - "\n" - " address-groups:\n" - "\n" - " HOME_NET: \"[8.8.8.8]\"\n" - " port-groups:\n" - " HTTP_PORTS: \"54321\"\n" - "\n"; +static const char *dummy_mt_conf_string = "%YAML 1.1\n" + "---\n" + "vars:\n" + "\n" + " address-groups:\n" + "\n" + " HOME_NET: \"[1.2.3.4]\"\n" + " port-groups:\n" + " HTTP_PORTS: \"12345\"\n" + "multi-detect:\n" + " 0:\n" + " vars:\n" + "\n" + " address-groups:\n" + "\n" + " HOME_NET: \"[8.8.8.8]\"\n" + " port-groups:\n" + " HTTP_PORTS: \"54321\"\n" + "\n"; /** * \test Check that valid address and port group vars are correctly retrieved @@ -354,34 +349,33 @@ static int SCRuleVarsMTest01(void) ConfInit(); ConfYamlLoadString(dummy_mt_conf_string, strlen(dummy_mt_conf_string)); - if ( (de_ctx = DetectEngineCtxInit()) == NULL) + if ((de_ctx = DetectEngineCtxInit()) == NULL) return 0; de_ctx->flags |= DE_QUIET; - snprintf(de_ctx->config_prefix, sizeof(de_ctx->config_prefix), - "multi-detect.0"); + snprintf(de_ctx->config_prefix, sizeof(de_ctx->config_prefix), "multi-detect.0"); /* check for address-groups */ - result = (SCRuleVarsGetConfVar(de_ctx,"$HOME_NET", SC_RULE_VARS_ADDRESS_GROUPS) != NULL && - strcmp(SCRuleVarsGetConfVar(de_ctx,"$HOME_NET", SC_RULE_VARS_ADDRESS_GROUPS), + result = (SCRuleVarsGetConfVar(de_ctx, "$HOME_NET", SC_RULE_VARS_ADDRESS_GROUPS) != NULL && + strcmp(SCRuleVarsGetConfVar(de_ctx, "$HOME_NET", SC_RULE_VARS_ADDRESS_GROUPS), "[8.8.8.8]") == 0); if (result == 0) goto end; - result = (SCRuleVarsGetConfVar(NULL,"$HOME_NET", SC_RULE_VARS_ADDRESS_GROUPS) != NULL && - strcmp(SCRuleVarsGetConfVar(NULL,"$HOME_NET", SC_RULE_VARS_ADDRESS_GROUPS), + result = (SCRuleVarsGetConfVar(NULL, "$HOME_NET", SC_RULE_VARS_ADDRESS_GROUPS) != NULL && + strcmp(SCRuleVarsGetConfVar(NULL, "$HOME_NET", SC_RULE_VARS_ADDRESS_GROUPS), "[1.2.3.4]") == 0); if (result == 0) goto end; /* check for port-groups */ - result = (SCRuleVarsGetConfVar(de_ctx,"$HTTP_PORTS", SC_RULE_VARS_PORT_GROUPS) != NULL && - strcmp(SCRuleVarsGetConfVar(de_ctx,"$HTTP_PORTS", SC_RULE_VARS_PORT_GROUPS), + result = (SCRuleVarsGetConfVar(de_ctx, "$HTTP_PORTS", SC_RULE_VARS_PORT_GROUPS) != NULL && + strcmp(SCRuleVarsGetConfVar(de_ctx, "$HTTP_PORTS", SC_RULE_VARS_PORT_GROUPS), "54321") == 0); if (result == 0) goto end; - result = (SCRuleVarsGetConfVar(NULL,"$HTTP_PORTS", SC_RULE_VARS_PORT_GROUPS) != NULL && - strcmp(SCRuleVarsGetConfVar(NULL,"$HTTP_PORTS", SC_RULE_VARS_PORT_GROUPS), + result = (SCRuleVarsGetConfVar(NULL, "$HTTP_PORTS", SC_RULE_VARS_PORT_GROUPS) != NULL && + strcmp(SCRuleVarsGetConfVar(NULL, "$HTTP_PORTS", SC_RULE_VARS_PORT_GROUPS), "12345") == 0); if (result == 0) goto end; diff --git a/src/util-runmodes.c b/src/util-runmodes.c index f78e857abfc6..2ac339d8d553 100644 --- a/src/util-runmodes.c +++ b/src/util-runmodes.c @@ -72,11 +72,11 @@ char *RunmodeAutoFpCreatePickupQueuesString(int n) if (strlen(queues) > 0) strlcat(queues, ",", queues_size); - snprintf(qname, sizeof(qname), "pickup%d", (int16_t)thread+1); + snprintf(qname, sizeof(qname), "pickup%d", (int16_t)thread + 1); strlcat(queues, qname, queues_size); } - SCLogDebug("%d %"PRIuMAX", queues %s", n, (uintmax_t)queues_size, queues); + SCLogDebug("%d %" PRIuMAX ", queues %s", n, (uintmax_t)queues_size, queues); return queues; } @@ -107,16 +107,13 @@ int RunModeSetLiveCaptureAutoFp(ConfigIfaceParserFunc ConfigParser, } int threads_count = ModThreadsCount(aconf); - SCLogInfo("Going to use %" PRId32 " %s receive thread(s)", - threads_count, recv_mod_name); + SCLogInfo("Going to use %" PRId32 " %s receive thread(s)", threads_count, recv_mod_name); /* create the threads */ for (int thread = 0; thread < threads_count; thread++) { - snprintf(tname, sizeof(tname), "%s#%02d", thread_name, thread+1); - ThreadVars *tv_receive = - TmThreadCreatePacketHandler(tname, - "packetpool", "packetpool", - queues, "flow", "pktacqloop"); + snprintf(tname, sizeof(tname), "%s#%02d", thread_name, thread + 1); + ThreadVars *tv_receive = TmThreadCreatePacketHandler( + tname, "packetpool", "packetpool", queues, "flow", "pktacqloop"); if (tv_receive == NULL) { FatalError("TmThreadsCreate failed"); } @@ -157,20 +154,18 @@ int RunModeSetLiveCaptureAutoFp(ConfigIfaceParserFunc ConfigParser, int threads_count = ModThreadsCount(aconf); for (int thread = 0; thread < threads_count; thread++) { - char *printable_threadname = SCMalloc(sizeof(char) * (strlen(thread_name)+5+strlen(dev))); + char *printable_threadname = + SCMalloc(sizeof(char) * (strlen(thread_name) + 5 + strlen(dev))); if (unlikely(printable_threadname == NULL)) { FatalError("failed to alloc printable thread name: %s", strerror(errno)); } - snprintf(tname, sizeof(tname), "%s#%02d-%s", thread_name, - thread+1, visual_devname); - snprintf(printable_threadname, strlen(thread_name)+5+strlen(dev), - "%s#%02d-%s", thread_name, thread+1, - dev); - - ThreadVars *tv_receive = - TmThreadCreatePacketHandler(tname, - "packetpool", "packetpool", - queues, "flow", "pktacqloop"); + snprintf(tname, sizeof(tname), "%s#%02d-%s", thread_name, thread + 1, + visual_devname); + snprintf(printable_threadname, strlen(thread_name) + 5 + strlen(dev), "%s#%02d-%s", + thread_name, thread + 1, dev); + + ThreadVars *tv_receive = TmThreadCreatePacketHandler( + tname, "packetpool", "packetpool", queues, "flow", "pktacqloop"); if (tv_receive == NULL) { FatalError("TmThreadsCreate failed"); } @@ -202,11 +197,8 @@ int RunModeSetLiveCaptureAutoFp(ConfigIfaceParserFunc ConfigParser, SCLogDebug("tname %s, qname %s", tname, qname); - ThreadVars *tv_detect_ncpu = - TmThreadCreatePacketHandler(tname, - qname, "flow", - "packetpool", "packetpool", - "varslot"); + ThreadVars *tv_detect_ncpu = TmThreadCreatePacketHandler( + tname, qname, "flow", "packetpool", "packetpool", "varslot"); if (tv_detect_ncpu == NULL) { FatalError("TmThreadsCreate failed"); } @@ -238,10 +230,8 @@ int RunModeSetLiveCaptureAutoFp(ConfigIfaceParserFunc ConfigParser, /** */ static int RunModeSetLiveCaptureWorkersForDevice(ConfigIfaceThreadsCountFunc ModThreadsCount, - const char *recv_mod_name, - const char *decode_mod_name, const char *thread_name, - const char *live_dev, void *aconf, - unsigned char single_mode) + const char *recv_mod_name, const char *decode_mod_name, const char *thread_name, + const char *live_dev, void *aconf, unsigned char single_mode) { int threads_count; uint16_t thread_max = TmThreadsGetWorkerThreadMax(); @@ -259,7 +249,8 @@ static int RunModeSetLiveCaptureWorkersForDevice(ConfigIfaceThreadsCountFunc Mod char tname[TM_THREAD_NAME_MAX]; TmModule *tm_module = NULL; const char *visual_devname = LiveGetShortName(live_dev); - char *printable_threadname = SCMalloc(sizeof(char) * (strlen(thread_name)+5+strlen(live_dev))); + char *printable_threadname = + SCMalloc(sizeof(char) * (strlen(thread_name) + 5 + strlen(live_dev))); if (unlikely(printable_threadname == NULL)) { FatalError("failed to alloc printable thread name: %s", strerror(errno)); exit(EXIT_FAILURE); @@ -267,18 +258,15 @@ static int RunModeSetLiveCaptureWorkersForDevice(ConfigIfaceThreadsCountFunc Mod if (single_mode) { snprintf(tname, sizeof(tname), "%s#01-%s", thread_name, visual_devname); - snprintf(printable_threadname, strlen(thread_name)+5+strlen(live_dev), "%s#01-%s", - thread_name, live_dev); + snprintf(printable_threadname, strlen(thread_name) + 5 + strlen(live_dev), "%s#01-%s", + thread_name, live_dev); } else { - snprintf(tname, sizeof(tname), "%s#%02d-%s", thread_name, - thread+1, visual_devname); - snprintf(printable_threadname, strlen(thread_name)+5+strlen(live_dev), "%s#%02d-%s", - thread_name, thread+1, live_dev); - } - ThreadVars *tv = TmThreadCreatePacketHandler(tname, - "packetpool", "packetpool", - "packetpool", "packetpool", - "pktacqloop"); + snprintf(tname, sizeof(tname), "%s#%02d-%s", thread_name, thread + 1, visual_devname); + snprintf(printable_threadname, strlen(thread_name) + 5 + strlen(live_dev), "%s#%02d-%s", + thread_name, thread + 1, live_dev); + } + ThreadVars *tv = TmThreadCreatePacketHandler( + tname, "packetpool", "packetpool", "packetpool", "packetpool", "pktacqloop"); if (tv == NULL) { FatalError("TmThreadsCreate failed"); } @@ -335,23 +323,16 @@ int RunModeSetLiveCaptureWorkers(ConfigIfaceParserFunc ConfigParser, live_dev_c = LiveGetDeviceName(ldev); aconf = ConfigParser(live_dev_c); } - RunModeSetLiveCaptureWorkersForDevice(ModThreadsCount, - recv_mod_name, - decode_mod_name, - thread_name, - live_dev_c, - aconf, - 0); + RunModeSetLiveCaptureWorkersForDevice( + ModThreadsCount, recv_mod_name, decode_mod_name, thread_name, live_dev_c, aconf, 0); } return 0; } int RunModeSetLiveCaptureSingle(ConfigIfaceParserFunc ConfigParser, - ConfigIfaceThreadsCountFunc ModThreadsCount, - const char *recv_mod_name, - const char *decode_mod_name, const char *thread_name, - const char *live_dev) + ConfigIfaceThreadsCountFunc ModThreadsCount, const char *recv_mod_name, + const char *decode_mod_name, const char *thread_name, const char *live_dev) { int nlive = LiveGetDeviceCount(); const char *live_dev_c = NULL; @@ -370,26 +351,17 @@ int RunModeSetLiveCaptureSingle(ConfigIfaceParserFunc ConfigParser, } return RunModeSetLiveCaptureWorkersForDevice( - ModThreadsCount, - recv_mod_name, - decode_mod_name, - thread_name, - live_dev_c, - aconf, - 1); + ModThreadsCount, recv_mod_name, decode_mod_name, thread_name, live_dev_c, aconf, 1); } - /** */ -int RunModeSetIPSAutoFp(ConfigIPSParserFunc ConfigParser, - const char *recv_mod_name, - const char *verdict_mod_name, - const char *decode_mod_name) +int RunModeSetIPSAutoFp(ConfigIPSParserFunc ConfigParser, const char *recv_mod_name, + const char *verdict_mod_name, const char *decode_mod_name) { SCEnter(); char tname[TM_THREAD_NAME_MAX]; - TmModule *tm_module ; + TmModule *tm_module; /* Available cpus */ const int nqueue = LiveGetDeviceCount(); @@ -410,10 +382,8 @@ int RunModeSetIPSAutoFp(ConfigIPSParserFunc ConfigParser, memset(tname, 0, sizeof(tname)); snprintf(tname, sizeof(tname), "%s-%s", thread_name_autofp, cur_queue); - ThreadVars *tv_receive = - TmThreadCreatePacketHandler(tname, - "packetpool", "packetpool", - queues, "flow", "pktacqloop"); + ThreadVars *tv_receive = TmThreadCreatePacketHandler( + tname, "packetpool", "packetpool", queues, "flow", "pktacqloop"); if (tv_receive == NULL) { FatalError("TmThreadsCreate failed"); } @@ -421,7 +391,7 @@ int RunModeSetIPSAutoFp(ConfigIPSParserFunc ConfigParser, if (tm_module == NULL) { FatalError("TmModuleGetByName failed for %s", recv_mod_name); } - TmSlotSetFuncAppend(tv_receive, tm_module, (void *) ConfigParser(i)); + TmSlotSetFuncAppend(tv_receive, tm_module, (void *)ConfigParser(i)); tm_module = TmModuleGetByName(decode_mod_name); if (tm_module == NULL) { @@ -434,7 +404,6 @@ int RunModeSetIPSAutoFp(ConfigIPSParserFunc ConfigParser, if (TmThreadSpawn(tv_receive) != TM_ECODE_OK) { FatalError("TmThreadSpawn failed"); } - } for (int thread = 0; thread < thread_max; thread++) { snprintf(tname, sizeof(tname), "%s#%02u", thread_name_workers, (uint16_t)(thread + 1)); @@ -443,11 +412,8 @@ int RunModeSetIPSAutoFp(ConfigIPSParserFunc ConfigParser, SCLogDebug("tname %s, qname %s", tname, qname); - ThreadVars *tv_detect_ncpu = - TmThreadCreatePacketHandler(tname, - qname, "flow", - "verdict-queue", "simple", - "varslot"); + ThreadVars *tv_detect_ncpu = TmThreadCreatePacketHandler( + tname, qname, "flow", "verdict-queue", "simple", "varslot"); if (tv_detect_ncpu == NULL) { FatalError("TmThreadsCreate failed"); } @@ -472,11 +438,8 @@ int RunModeSetIPSAutoFp(ConfigIPSParserFunc ConfigParser, memset(tname, 0, sizeof(tname)); snprintf(tname, sizeof(tname), "%s#%02d", thread_name_verdict, i); - ThreadVars *tv_verdict = - TmThreadCreatePacketHandler(tname, - "verdict-queue", "simple", - "packetpool", "packetpool", - "varslot"); + ThreadVars *tv_verdict = TmThreadCreatePacketHandler( + tname, "verdict-queue", "simple", "packetpool", "packetpool", "varslot"); if (tv_verdict == NULL) { FatalError("TmThreadsCreate failed"); } @@ -505,10 +468,8 @@ int RunModeSetIPSAutoFp(ConfigIPSParserFunc ConfigParser, /** */ -int RunModeSetIPSWorker(ConfigIPSParserFunc ConfigParser, - const char *recv_mod_name, - const char *verdict_mod_name, - const char *decode_mod_name) +int RunModeSetIPSWorker(ConfigIPSParserFunc ConfigParser, const char *recv_mod_name, + const char *verdict_mod_name, const char *decode_mod_name) { TmModule *tm_module = NULL; const int nqueue = LiveGetDeviceCount(); @@ -524,10 +485,8 @@ int RunModeSetIPSWorker(ConfigIPSParserFunc ConfigParser, memset(tname, 0, sizeof(tname)); snprintf(tname, sizeof(tname), "%s-%s", thread_name_workers, cur_queue); - ThreadVars *tv = TmThreadCreatePacketHandler(tname, - "packetpool", "packetpool", - "packetpool", "packetpool", - "pktacqloop"); + ThreadVars *tv = TmThreadCreatePacketHandler( + tname, "packetpool", "packetpool", "packetpool", "packetpool", "pktacqloop"); if (tv == NULL) { FatalError("TmThreadsCreate failed"); } @@ -536,7 +495,7 @@ int RunModeSetIPSWorker(ConfigIPSParserFunc ConfigParser, if (tm_module == NULL) { FatalError("TmModuleGetByName failed for %s", recv_mod_name); } - TmSlotSetFuncAppend(tv, tm_module, (void *) ConfigParser(i)); + TmSlotSetFuncAppend(tv, tm_module, (void *)ConfigParser(i)); tm_module = TmModuleGetByName(decode_mod_name); if (tm_module == NULL) { @@ -554,7 +513,7 @@ int RunModeSetIPSWorker(ConfigIPSParserFunc ConfigParser, if (tm_module == NULL) { FatalError("TmModuleGetByName %s failed", verdict_mod_name); } - TmSlotSetFuncAppend(tv, tm_module, (void *) ConfigParser(i)); + TmSlotSetFuncAppend(tv, tm_module, (void *)ConfigParser(i)); tm_module = TmModuleGetByName("RespondReject"); if (tm_module == NULL) { diff --git a/src/util-runmodes.h b/src/util-runmodes.h index 419f9f95112d..d217236a2a02 100644 --- a/src/util-runmodes.h +++ b/src/util-runmodes.h @@ -23,39 +23,31 @@ #ifndef __UTIL_RUNMODES_H__ #define __UTIL_RUNMODES_H__ -typedef void *(*ConfigIfaceParserFunc) (const char *); -typedef void *(*ConfigIPSParserFunc) (int); -typedef int (*ConfigIfaceThreadsCountFunc) (void *); +typedef void *(*ConfigIfaceParserFunc)(const char *); +typedef void *(*ConfigIPSParserFunc)(int); +typedef int (*ConfigIfaceThreadsCountFunc)(void *); int RunModeSetLiveCaptureAuto(ConfigIfaceParserFunc configparser, - ConfigIfaceThreadsCountFunc ModThreadsCount, - const char *recv_mod_name, - const char *decode_mod_name, const char *thread_name, - const char *live_dev); + ConfigIfaceThreadsCountFunc ModThreadsCount, const char *recv_mod_name, + const char *decode_mod_name, const char *thread_name, const char *live_dev); int RunModeSetLiveCaptureAutoFp(ConfigIfaceParserFunc configparser, ConfigIfaceThreadsCountFunc ModThreadsCount, const char *recv_mod_name, const char *decode_mod_name, const char *thread_name, const char *live_dev); int RunModeSetLiveCaptureSingle(ConfigIfaceParserFunc configparser, - ConfigIfaceThreadsCountFunc ModThreadsCount, - const char *recv_mod_name, - const char *decode_mod_name, const char *thread_name, - const char *live_dev); + ConfigIfaceThreadsCountFunc ModThreadsCount, const char *recv_mod_name, + const char *decode_mod_name, const char *thread_name, const char *live_dev); int RunModeSetLiveCaptureWorkers(ConfigIfaceParserFunc configparser, ConfigIfaceThreadsCountFunc ModThreadsCount, const char *recv_mod_name, const char *decode_mod_name, const char *thread_name, const char *live_dev); -int RunModeSetIPSAutoFp(ConfigIPSParserFunc ConfigParser, - const char *recv_mod_name, - const char *verdict_mod_name, - const char *decode_mod_name); +int RunModeSetIPSAutoFp(ConfigIPSParserFunc ConfigParser, const char *recv_mod_name, + const char *verdict_mod_name, const char *decode_mod_name); -int RunModeSetIPSWorker(ConfigIPSParserFunc ConfigParser, - const char *recv_mod_name, - const char *verdict_mod_name, - const char *decode_mod_name); +int RunModeSetIPSWorker(ConfigIPSParserFunc ConfigParser, const char *recv_mod_name, + const char *verdict_mod_name, const char *decode_mod_name); char *RunmodeAutoFpCreatePickupQueuesString(int n); diff --git a/src/util-running-modes.c b/src/util-running-modes.c index dd50c85ab420..ac0b907d5cae 100644 --- a/src/util-running-modes.c +++ b/src/util-running-modes.c @@ -52,4 +52,3 @@ int ListAppLayerProtocols(const char *conf_filename) return TM_ECODE_DONE; } - diff --git a/src/util-signal.c b/src/util-signal.c index 9e3ec0cdf812..ce611b6b732e 100644 --- a/src/util-signal.c +++ b/src/util-signal.c @@ -60,14 +60,14 @@ int UtilSignalUnblock(int signum) void UtilSignalHandlerSetup(int sig, void (*handler)(int)) { #ifdef OS_WIN32 - signal(sig, handler); + signal(sig, handler); #else struct sigaction action; memset(&action, 0x00, sizeof(struct sigaction)); action.sa_handler = handler; sigemptyset(&(action.sa_mask)); - sigaddset(&(action.sa_mask),sig); + sigaddset(&(action.sa_mask), sig); action.sa_flags = 0; sigaction(sig, &action, 0); #endif /* OS_WIN32 */ diff --git a/src/util-spm-bm.c b/src/util-spm-bm.c index 449c6b62962e..0955d0da266b 100644 --- a/src/util-spm-bm.c +++ b/src/util-spm-bm.c @@ -43,8 +43,7 @@ static int PreBmGs(const uint8_t *x, uint16_t m, uint16_t *bmGs); static void PreBmBc(const uint8_t *x, uint16_t m, uint16_t *bmBc); static void PreBmBcNocase(const uint8_t *x, uint16_t m, uint16_t *bmBc); -static void BoyerMooreSuffixesNocase(const uint8_t *x, uint16_t m, - uint16_t *suff); +static void BoyerMooreSuffixesNocase(const uint8_t *x, uint16_t m, uint16_t *suff); static void PreBmGsNocase(const uint8_t *x, uint16_t m, uint16_t *bmGs); /** @@ -90,7 +89,6 @@ BmCtx *BoyerMooreCtxInit(const uint8_t *needle, uint16_t needle_len) FatalError("Fatal error encountered in BoyerMoreCtxInit. Exiting..."); } - return new; } @@ -147,7 +145,8 @@ static void PreBmBc(const uint8_t *x, uint16_t m, uint16_t *bmBc) } /** - * \brief Array setup function for building prefixes (shift for valid prefixes) for boyermoore context + * \brief Array setup function for building prefixes (shift for valid prefixes) for boyermoore + * context * * \param x pointer to the pattern string * \param m length of the string @@ -174,7 +173,8 @@ static void BoyerMooreSuffixes(const uint8_t *x, uint16_t m, uint16_t *suff) } /** - * \brief Array setup function for building prefixes (shift for valid prefixes) for boyermoore context + * \brief Array setup function for building prefixes (shift for valid prefixes) for boyermoore + * context * * \param x pointer to the pattern string * \param m length of the string @@ -225,8 +225,7 @@ static void PreBmBcNocase(const uint8_t *x, uint16_t m, uint16_t *bmBc) } } -static void BoyerMooreSuffixesNocase(const uint8_t *x, uint16_t m, - uint16_t *suff) +static void BoyerMooreSuffixesNocase(const uint8_t *x, uint16_t m, uint16_t *suff) { int32_t f = 0, g, i; @@ -317,22 +316,22 @@ uint8_t *BoyerMoore(const uint8_t *x, uint16_t m, const uint8_t *y, uint32_t n, // force casting to int32_t (if possible) int_n = unlikely(n > INT32_MAX) ? INT32_MAX : n; j = 0; - while (j <= int_n - m ) { - for (i = m - 1; i >= 0 && x[i] == y[i + j]; --i); + while (j <= int_n - m) { + for (i = m - 1; i >= 0 && x[i] == y[i + j]; --i) + ; if (i < 0) { return (uint8_t *)(y + j); - //j += bmGs[0]; + // j += bmGs[0]; } else { -// printf("%c", y[i+j]); - j += (m1 = bmGs[i]) > (m2 = bmBc[y[i + j]] - m + 1 + i)? m1: m2; -// printf("%d, %d\n", m1, m2); + // printf("%c", y[i+j]); + j += (m1 = bmGs[i]) > (m2 = bmBc[y[i + j]] - m + 1 + i) ? m1 : m2; + // printf("%d, %d\n", m1, m2); } } return NULL; } - /** * \brief Boyer Moore search algorithm * Is better as the pattern length increases and for big buffers to search in. @@ -367,15 +366,15 @@ uint8_t *BoyerMooreNocase(const uint8_t *x, uint16_t m, const uint8_t *y, uint32 // force casting to int32_t (if possible) int_n = unlikely(n > INT32_MAX) ? INT32_MAX : n; j = 0; - while (j <= int_n - m ) { - /* x is stored in lowercase. */ - for (i = m - 1; i >= 0 && x[i] == u8_tolower(y[i + j]); --i); + while (j <= int_n - m) { + /* x is stored in lowercase. */ + for (i = m - 1; i >= 0 && x[i] == u8_tolower(y[i + j]); --i) + ; if (i < 0) { return (uint8_t *)(y + j); } else { - j += (m1 = bmGs[i]) > (m2 = bmBc[y[i + j]] - m + 1 + i)? - m1: m2; + j += (m1 = bmGs[i]) > (m2 = bmBc[y[i + j]] - m + 1 + i) ? m1 : m2; } } return NULL; @@ -389,7 +388,7 @@ typedef struct SpmBmCtx_ { } SpmBmCtx; static SpmCtx *BMInitCtx(const uint8_t *needle, uint16_t needle_len, int nocase, - SpmGlobalThreadCtx *global_thread_ctx) + SpmGlobalThreadCtx *global_thread_ctx) { SpmCtx *ctx = SCCalloc(1, sizeof(SpmCtx)); if (ctx == NULL) { @@ -445,17 +444,16 @@ static void BMDestroyCtx(SpmCtx *ctx) SCFree(ctx); } -static uint8_t *BMScan(const SpmCtx *ctx, SpmThreadCtx *thread_ctx, - const uint8_t *haystack, uint32_t haystack_len) +static uint8_t *BMScan( + const SpmCtx *ctx, SpmThreadCtx *thread_ctx, const uint8_t *haystack, uint32_t haystack_len) { const SpmBmCtx *sctx = ctx->ctx; if (sctx->nocase) { - return BoyerMooreNocase(sctx->needle, sctx->needle_len, haystack, - haystack_len, sctx->bm_ctx); + return BoyerMooreNocase( + sctx->needle, sctx->needle_len, haystack, haystack_len, sctx->bm_ctx); } else { - return BoyerMoore(sctx->needle, sctx->needle_len, haystack, - haystack_len, sctx->bm_ctx); + return BoyerMoore(sctx->needle, sctx->needle_len, haystack, haystack_len, sctx->bm_ctx); } } @@ -486,7 +484,8 @@ static void BMDestroyThreadCtx(SpmThreadCtx *thread_ctx) SCFree(thread_ctx); } -static SpmThreadCtx *BMMakeThreadCtx(const SpmGlobalThreadCtx *global_thread_ctx) { +static SpmThreadCtx *BMMakeThreadCtx(const SpmGlobalThreadCtx *global_thread_ctx) +{ SpmThreadCtx *thread_ctx = SCCalloc(1, sizeof(SpmThreadCtx)); if (thread_ctx == NULL) { SCLogDebug("Unable to alloc SpmThreadCtx."); diff --git a/src/util-spm-bm.h b/src/util-spm-bm.h index 3c5e59ce03fb..c6fff8f0a881 100644 --- a/src/util-spm-bm.h +++ b/src/util-spm-bm.h @@ -32,7 +32,7 @@ /* Context for boyer moore */ typedef struct BmCtx_ { uint16_t bmBc[ALPHABET_SIZE]; - //C99 "flexible array member" + // C99 "flexible array member" uint16_t bmGs[]; // = SCMalloc(sizeof(int16_t)*(needlelen + 1)); } BmCtx; @@ -42,10 +42,10 @@ BmCtx *BoyerMooreNocaseCtxInit(uint8_t *needle, uint16_t needle_len); void BoyerMooreCtxToNocase(BmCtx *, uint8_t *, uint16_t); uint8_t *BoyerMoore(const uint8_t *x, uint16_t m, const uint8_t *y, uint32_t n, BmCtx *bm_ctx); -uint8_t *BoyerMooreNocase(const uint8_t *x, uint16_t m, const uint8_t *y, uint32_t n, BmCtx *bm_ctx); +uint8_t *BoyerMooreNocase( + const uint8_t *x, uint16_t m, const uint8_t *y, uint32_t n, BmCtx *bm_ctx); void BoyerMooreCtxDeInit(BmCtx *); void SpmBMRegister(void); #endif /* __UTIL_SPM_BM__ */ - diff --git a/src/util-spm-bs.c b/src/util-spm-bs.c index 823e2a646b68..6b6162ad95bd 100644 --- a/src/util-spm-bs.c +++ b/src/util-spm-bs.c @@ -44,7 +44,8 @@ * * \retval ptr to start of the match; NULL if no match */ -uint8_t *BasicSearch(const uint8_t *haystack, uint32_t haystack_len, const uint8_t *needle, uint16_t needle_len) +uint8_t *BasicSearch( + const uint8_t *haystack, uint32_t haystack_len, const uint8_t *needle, uint16_t needle_len) { SCEnter(); @@ -56,9 +57,9 @@ uint8_t *BasicSearch(const uint8_t *haystack, uint32_t haystack_len, const uint8 SCReturnPtr(NULL, "uint8_t"); } - //PrintRawDataFp(stdout,needle,needle_len); + // PrintRawDataFp(stdout,needle,needle_len); - //PrintRawDataFp(stdout,haystack,haystack_len); + // PrintRawDataFp(stdout,haystack,haystack_len); for (n = needle; nmax - n <= hmax - haystack; haystack++) { if (*haystack != *n) { @@ -72,7 +73,7 @@ uint8_t *BasicSearch(const uint8_t *haystack, uint32_t haystack_len, const uint8 SCReturnPtr((uint8_t *)haystack, "uint8_t"); } - for (h = haystack+1, n++; nmax - n <= hmax - haystack; h++, n++) { + for (h = haystack + 1, n++; nmax - n <= hmax - haystack; h++, n++) { if (*h != *n) { break; } @@ -98,7 +99,8 @@ uint8_t *BasicSearch(const uint8_t *haystack, uint32_t haystack_len, const uint8 * * \retval ptr to start of the match; NULL if no match */ -uint8_t *BasicSearchNocase(const uint8_t *haystack, uint32_t haystack_len, const uint8_t *needle, uint16_t needle_len) +uint8_t *BasicSearchNocase( + const uint8_t *haystack, uint32_t haystack_len, const uint8_t *needle, uint16_t needle_len) { const uint8_t *h, *n; const uint8_t *hmax = haystack + haystack_len; @@ -116,7 +118,7 @@ uint8_t *BasicSearchNocase(const uint8_t *haystack, uint32_t haystack_len, const return (uint8_t *)haystack; } - for (h = haystack+1, n++; nmax - n <= hmax - h ; h++, n++) { + for (h = haystack + 1, n++; nmax - n <= hmax - h; h++, n++) { if (u8_tolower(*h) != u8_tolower(*n)) { break; } @@ -131,8 +133,7 @@ uint8_t *BasicSearchNocase(const uint8_t *haystack, uint32_t haystack_len, const return NULL; } -void BasicSearchInit (void) +void BasicSearchInit(void) { /* nothing no more */ } - diff --git a/src/util-spm-bs.h b/src/util-spm-bs.h index ddd930239052..167dbaa50c1a 100644 --- a/src/util-spm-bs.h +++ b/src/util-spm-bs.h @@ -29,7 +29,6 @@ uint8_t *BasicSearch(const uint8_t *, uint32_t, const uint8_t *, uint16_t); uint8_t *BasicSearchNocase(const uint8_t *, uint32_t, const uint8_t *, uint16_t); -void BasicSearchInit (void); +void BasicSearchInit(void); #endif /* __UTIL_SPM_BS__ */ - diff --git a/src/util-spm-bs2bm.c b/src/util-spm-bs2bm.c index 589e6e9d92db..aa21623aa7f9 100644 --- a/src/util-spm-bs2bm.c +++ b/src/util-spm-bs2bm.c @@ -107,7 +107,7 @@ uint8_t *Bs2Bm(const uint8_t *haystack, uint32_t haystack_len, const uint8_t *ne if (needle_len == 1) return (uint8_t *)haystack; - for (h = haystack+1, n++; nmax - n <= hmax - haystack; h++, n++) { + for (h = haystack + 1, n++; nmax - n <= hmax - haystack; h++, n++) { if (*h != *n) { if (badchars[*h] == 1) { /* skip it! */ @@ -116,7 +116,7 @@ uint8_t *Bs2Bm(const uint8_t *haystack, uint32_t haystack_len, const uint8_t *ne break; } /* if we run out of needle we fully matched */ - if (n == nmax - 1 ) { + if (n == nmax - 1) { return (uint8_t *)haystack; } } @@ -157,7 +157,7 @@ uint8_t *Bs2BmNocase(const uint8_t *haystack, uint32_t haystack_len, const uint8 if (needle_len == 1) return (uint8_t *)haystack; - for (h = haystack+1, n++; nmax - n <= hmax - haystack; h++, n++) { + for (h = haystack + 1, n++; nmax - n <= hmax - haystack; h++, n++) { if (u8_tolower(*h) != u8_tolower(*n)) { if (badchars[u8_tolower(*h)] == 1) { /* skip it! */ diff --git a/src/util-spm-bs2bm.h b/src/util-spm-bs2bm.h index 74df96aae1e2..e705c519ee97 100644 --- a/src/util-spm-bs2bm.h +++ b/src/util-spm-bs2bm.h @@ -34,4 +34,3 @@ uint8_t *Bs2Bm(const uint8_t *, uint32_t, const uint8_t *, uint16_t, const uint8 uint8_t *Bs2BmNocase(const uint8_t *, uint32_t, const uint8_t *, uint16_t, const uint8_t[]); #endif /* __UTIL_SPM_BS2BM__ */ - diff --git a/src/util-spm-hs.c b/src/util-spm-hs.c index d58de651d943..fa20e9c2ab51 100644 --- a/src/util-spm-hs.c +++ b/src/util-spm-hs.c @@ -37,8 +37,8 @@ * \internal * \brief Hyperscan match callback, called by hs_scan. */ -static int MatchEvent(unsigned int id, unsigned long long from, - unsigned long long to, unsigned int flags, void *context) +static int MatchEvent(unsigned int id, unsigned long long from, unsigned long long to, + unsigned int flags, void *context) { uint64_t *match_offset = context; BUG_ON(*match_offset != UINT64_MAX); @@ -64,9 +64,8 @@ static void HSDestroyCtx(SpmCtx *ctx) SCFree(ctx); } -static int HSBuildDatabase(const uint8_t *needle, uint16_t needle_len, - int nocase, SpmHsCtx *sctx, - SpmGlobalThreadCtx *global_thread_ctx) +static int HSBuildDatabase(const uint8_t *needle, uint16_t needle_len, int nocase, SpmHsCtx *sctx, + SpmGlobalThreadCtx *global_thread_ctx) { char *expr = HSRenderPattern(needle, needle_len); if (expr == NULL) { @@ -78,8 +77,7 @@ static int HSBuildDatabase(const uint8_t *needle, uint16_t needle_len, hs_database_t *db = NULL; hs_compile_error_t *compile_err = NULL; - hs_error_t err = hs_compile(expr, flags, HS_MODE_BLOCK, NULL, &db, - &compile_err); + hs_error_t err = hs_compile(expr, flags, HS_MODE_BLOCK, NULL, &db, &compile_err); if (err != HS_SUCCESS) { SCLogError("Unable to compile '%s' with Hyperscan, " "returned %d.", @@ -106,7 +104,7 @@ static int HSBuildDatabase(const uint8_t *needle, uint16_t needle_len, } static SpmCtx *HSInitCtx(const uint8_t *needle, uint16_t needle_len, int nocase, - SpmGlobalThreadCtx *global_thread_ctx) + SpmGlobalThreadCtx *global_thread_ctx) { SpmCtx *ctx = SCCalloc(1, sizeof(SpmCtx)); if (ctx == NULL) { @@ -123,8 +121,7 @@ static SpmCtx *HSInitCtx(const uint8_t *needle, uint16_t needle_len, int nocase, } ctx->ctx = sctx; - if (HSBuildDatabase(needle, needle_len, nocase, sctx, - global_thread_ctx) != 0) { + if (HSBuildDatabase(needle, needle_len, nocase, sctx, global_thread_ctx) != 0) { SCLogDebug("HSBuildDatabase failed."); HSDestroyCtx(ctx); return NULL; @@ -133,8 +130,8 @@ static SpmCtx *HSInitCtx(const uint8_t *needle, uint16_t needle_len, int nocase, return ctx; } -static uint8_t *HSScan(const SpmCtx *ctx, SpmThreadCtx *thread_ctx, - const uint8_t *haystack, uint32_t haystack_len) +static uint8_t *HSScan( + const SpmCtx *ctx, SpmThreadCtx *thread_ctx, const uint8_t *haystack, uint32_t haystack_len) { const SpmHsCtx *sctx = ctx->ctx; hs_scratch_t *scratch = thread_ctx->ctx; @@ -144,8 +141,8 @@ static uint8_t *HSScan(const SpmCtx *ctx, SpmThreadCtx *thread_ctx, } uint64_t match_offset = UINT64_MAX; - hs_error_t err = hs_scan(sctx->db, (const char *)haystack, haystack_len, 0, - scratch, MatchEvent, &match_offset); + hs_error_t err = hs_scan( + sctx->db, (const char *)haystack, haystack_len, 0, scratch, MatchEvent, &match_offset); if (err != HS_SUCCESS && err != HS_SCAN_TERMINATED) { /* An error value (other than HS_SCAN_TERMINATED) from hs_scan() * indicates that it was passed an invalid database or scratch region, diff --git a/src/util-spm.c b/src/util-spm.c index 15b33398a62a..9b558dcd2564 100644 --- a/src/util-spm.c +++ b/src/util-spm.c @@ -99,20 +99,20 @@ uint8_t SinglePatternMatchDefaultMatcher(void) /* When Suricata is built with Hyperscan support, default to using it for * SPM. */ #ifdef BUILD_HYPERSCAN - #ifdef HAVE_HS_VALID_PLATFORM +#ifdef HAVE_HS_VALID_PLATFORM /* Enable runtime check for SSSE3. Do not use Hyperscan SPM matcher if * check is not successful. */ - if (hs_valid_platform() != HS_SUCCESS) { - SCLogInfo("SSSE3 support not detected, disabling Hyperscan for " - "SPM"); - /* Use Boyer-Moore as fallback. */ - return SPM_BM; - } else { - return SPM_HS; - } - #else + if (hs_valid_platform() != HS_SUCCESS) { + SCLogInfo("SSSE3 support not detected, disabling Hyperscan for " + "SPM"); + /* Use Boyer-Moore as fallback. */ + return SPM_BM; + } else { return SPM_HS; - #endif + } +#else + return SPM_HS; +#endif #else /* Otherwise, default to Boyer-Moore */ return SPM_BM; @@ -125,13 +125,13 @@ void SpmTableSetup(void) SpmBMRegister(); #ifdef BUILD_HYPERSCAN - #ifdef HAVE_HS_VALID_PLATFORM - if (hs_valid_platform() == HS_SUCCESS) { - SpmHSRegister(); - } - #else +#ifdef HAVE_HS_VALID_PLATFORM + if (hs_valid_platform() == HS_SUCCESS) { SpmHSRegister(); - #endif + } +#else + SpmHSRegister(); +#endif #endif } @@ -171,13 +171,12 @@ void SpmDestroyThreadCtx(SpmThreadCtx *thread_ctx) } SpmCtx *SpmInitCtx(const uint8_t *needle, uint16_t needle_len, int nocase, - SpmGlobalThreadCtx *global_thread_ctx) + SpmGlobalThreadCtx *global_thread_ctx) { BUG_ON(global_thread_ctx == NULL); uint8_t matcher = global_thread_ctx->matcher; BUG_ON(spm_table[matcher].InitCtx == NULL); - return spm_table[matcher].InitCtx(needle, needle_len, nocase, - global_thread_ctx); + return spm_table[matcher].InitCtx(needle, needle_len, nocase, global_thread_ctx); } void SpmDestroyCtx(SpmCtx *ctx) @@ -190,8 +189,8 @@ void SpmDestroyCtx(SpmCtx *ctx) spm_table[matcher].DestroyCtx(ctx); } -uint8_t *SpmScan(const SpmCtx *ctx, SpmThreadCtx *thread_ctx, - const uint8_t *haystack, uint32_t haystack_len) +uint8_t *SpmScan( + const SpmCtx *ctx, SpmThreadCtx *thread_ctx, const uint8_t *haystack, uint32_t haystack_len) { uint8_t matcher = ctx->matcher; return spm_table[matcher].Scan(ctx, thread_ctx, haystack, haystack_len); @@ -211,8 +210,8 @@ uint8_t *SpmScan(const SpmCtx *ctx, SpmThreadCtx *thread_ctx, * \param needle pattern to search for * \param needlelen length of the pattern */ -uint8_t *Bs2bmSearch(const uint8_t *text, uint32_t textlen, - const uint8_t *needle, uint16_t needlelen) +uint8_t *Bs2bmSearch( + const uint8_t *text, uint32_t textlen, const uint8_t *needle, uint16_t needlelen) { uint8_t badchars[ALPHABET_SIZE]; Bs2BmBadchars(needle, needlelen, badchars); @@ -221,15 +220,16 @@ uint8_t *Bs2bmSearch(const uint8_t *text, uint32_t textlen, } /** - * \brief Search a pattern in the text using the Bs2Bm nocase algorithm (build a bad characters array) + * \brief Search a pattern in the text using the Bs2Bm nocase algorithm (build a bad characters + * array) * * \param text Text to search in * \param textlen length of the text * \param needle pattern to search for * \param needlelen length of the pattern */ -uint8_t *Bs2bmNocaseSearch(const uint8_t *text, uint32_t textlen, - const uint8_t *needle, uint16_t needlelen) +uint8_t *Bs2bmNocaseSearch( + const uint8_t *text, uint32_t textlen, const uint8_t *needle, uint16_t needlelen) { uint8_t badchars[ALPHABET_SIZE]; Bs2BmBadchars(needle, needlelen, badchars); @@ -246,8 +246,8 @@ uint8_t *Bs2bmNocaseSearch(const uint8_t *text, uint32_t textlen, * \param needle pattern to search for * \param needlelen length of the pattern */ -uint8_t *BoyerMooreSearch(const uint8_t *text, uint32_t textlen, - const uint8_t *needle, uint16_t needlelen) +uint8_t *BoyerMooreSearch( + const uint8_t *text, uint32_t textlen, const uint8_t *needle, uint16_t needlelen) { BmCtx *bm_ctx = BoyerMooreCtxInit(needle, needlelen); @@ -266,8 +266,8 @@ uint8_t *BoyerMooreSearch(const uint8_t *text, uint32_t textlen, * \param needle pattern to search for * \param needlelen length of the pattern */ -uint8_t *BoyerMooreNocaseSearch(const uint8_t *text, uint32_t textlen, - uint8_t *needle, uint16_t needlelen) +uint8_t *BoyerMooreNocaseSearch( + const uint8_t *text, uint32_t textlen, uint8_t *needle, uint16_t needlelen) { BmCtx *bm_ctx = BoyerMooreNocaseCtxInit(needle, needlelen); @@ -277,7 +277,6 @@ uint8_t *BoyerMooreNocaseSearch(const uint8_t *text, uint32_t textlen, return ret; } - #ifdef UNITTESTS /** Comment out this if you want stats @@ -310,7 +309,10 @@ static uint8_t *BasicSearchWrapper(uint8_t *text, uint8_t *needle, int times) ret = BasicSearch(text, textlen, needle, needlelen); } - if (times > 1) { CLOCK_END; CLOCK_PRINT_SEC; }; + if (times > 1) { + CLOCK_END; + CLOCK_PRINT_SEC; + }; return ret; } @@ -323,11 +325,15 @@ static uint8_t *BasicSearchNocaseWrapper(uint8_t *text, uint8_t *needle, int tim int i = 0; CLOCK_INIT; - if (times > 1) CLOCK_START; + if (times > 1) + CLOCK_START; for (i = 0; i < times; i++) { ret = BasicSearchNocase(text, textlen, needle, needlelen); } - if (times > 1) { CLOCK_END; CLOCK_PRINT_SEC; }; + if (times > 1) { + CLOCK_END; + CLOCK_PRINT_SEC; + }; return ret; } @@ -343,11 +349,15 @@ static uint8_t *Bs2bmWrapper(uint8_t *text, uint8_t *needle, int times) int i = 0; CLOCK_INIT; - if (times > 1) CLOCK_START; + if (times > 1) + CLOCK_START; for (i = 0; i < times; i++) { ret = Bs2Bm(text, textlen, needle, needlelen, badchars); } - if (times > 1) { CLOCK_END; CLOCK_PRINT_SEC; }; + if (times > 1) { + CLOCK_END; + CLOCK_PRINT_SEC; + }; return ret; } @@ -363,11 +373,15 @@ static uint8_t *Bs2bmNocaseWrapper(uint8_t *text, uint8_t *needle, int times) int i = 0; CLOCK_INIT; - if (times > 1) CLOCK_START; + if (times > 1) + CLOCK_START; for (i = 0; i < times; i++) { ret = Bs2BmNocase(text, textlen, needle, needlelen, badchars); } - if (times > 1) { CLOCK_END; CLOCK_PRINT_SEC; }; + if (times > 1) { + CLOCK_END; + CLOCK_PRINT_SEC; + }; return ret; } @@ -382,11 +396,15 @@ static uint8_t *BoyerMooreWrapper(uint8_t *text, uint8_t *needle, int times) int i = 0; CLOCK_INIT; - if (times > 1) CLOCK_START; + if (times > 1) + CLOCK_START; for (i = 0; i < times; i++) { ret = BoyerMoore(needle, needlelen, text, textlen, bm_ctx); } - if (times > 1) { CLOCK_END; CLOCK_PRINT_SEC; }; + if (times > 1) { + CLOCK_END; + CLOCK_PRINT_SEC; + }; BoyerMooreCtxDeInit(bm_ctx); return ret; } @@ -408,15 +426,18 @@ static uint8_t *BoyerMooreNocaseWrapper(uint8_t *text, uint8_t *in_needle, int t int i = 0; CLOCK_INIT; - if (times > 1) CLOCK_START; + if (times > 1) + CLOCK_START; for (i = 0; i < times; i++) { ret = BoyerMooreNocase(needle, needlelen, text, textlen, bm_ctx); } - if (times > 1) { CLOCK_END; CLOCK_PRINT_SEC; }; + if (times > 1) { + CLOCK_END; + CLOCK_PRINT_SEC; + }; BoyerMooreCtxDeInit(bm_ctx); free(needle); return ret; - } #ifdef ENABLE_SEARCH_STATS @@ -436,12 +457,16 @@ static uint8_t *BasicSearchCtxWrapper(uint8_t *text, uint8_t *needle, int times) int i = 0; CLOCK_INIT; - if (times > 1) CLOCK_START; + if (times > 1) + CLOCK_START; for (i = 0; i < times; i++) { /* This wrapper is a fake, no context needed! */ ret = BasicSearch(text, textlen, needle, needlelen); } - if (times > 1) { CLOCK_END; CLOCK_PRINT_SEC; }; + if (times > 1) { + CLOCK_END; + CLOCK_PRINT_SEC; + }; return ret; } @@ -454,12 +479,16 @@ static uint8_t *BasicSearchNocaseCtxWrapper(uint8_t *text, uint8_t *needle, int int i = 0; CLOCK_INIT; - if (times > 1) CLOCK_START; + if (times > 1) + CLOCK_START; for (i = 0; i < times; i++) { /* This wrapper is a fake, no context needed! */ ret = BasicSearchNocase(text, textlen, needle, needlelen); } - if (times > 1) { CLOCK_END; CLOCK_PRINT_SEC; }; + if (times > 1) { + CLOCK_END; + CLOCK_PRINT_SEC; + }; return ret; } @@ -474,13 +503,17 @@ static uint8_t *Bs2bmCtxWrapper(uint8_t *text, uint8_t *needle, int times) int i = 0; CLOCK_INIT; - if (times > 1) CLOCK_START; + if (times > 1) + CLOCK_START; for (i = 0; i < times; i++) { /* Stats including context building */ Bs2BmBadchars(needle, needlelen, badchars); ret = Bs2Bm(text, textlen, needle, needlelen, badchars); } - if (times > 1) { CLOCK_END; CLOCK_PRINT_SEC; }; + if (times > 1) { + CLOCK_END; + CLOCK_PRINT_SEC; + }; return ret; } @@ -495,13 +528,17 @@ static uint8_t *Bs2bmNocaseCtxWrapper(uint8_t *text, uint8_t *needle, int times) int i = 0; CLOCK_INIT; - if (times > 1) CLOCK_START; + if (times > 1) + CLOCK_START; for (i = 0; i < times; i++) { /* Stats including context building */ Bs2BmBadchars(needle, needlelen, badchars); ret = Bs2BmNocase(text, textlen, needle, needlelen, badchars); } - if (times > 1) { CLOCK_END; CLOCK_PRINT_SEC; }; + if (times > 1) { + CLOCK_END; + CLOCK_PRINT_SEC; + }; return ret; } @@ -516,12 +553,16 @@ static uint8_t *BoyerMooreCtxWrapper(uint8_t *text, uint8_t *needle, int times) int i = 0; CLOCK_INIT; - if (times > 1) CLOCK_START; + if (times > 1) + CLOCK_START; for (i = 0; i < times; i++) { /* Stats including context building */ ret = BoyerMoore(needle, needlelen, text, textlen, bm_ctx); } - if (times > 1) { CLOCK_END; CLOCK_PRINT_SEC; }; + if (times > 1) { + CLOCK_END; + CLOCK_PRINT_SEC; + }; BoyerMooreCtxDeInit(bm_ctx); return ret; @@ -536,11 +577,15 @@ static uint8_t *RawCtxWrapper(uint8_t *text, uint8_t *needle, int times) int i = 0; CLOCK_INIT; - if (times > 1) CLOCK_START; + if (times > 1) + CLOCK_START; for (i = 0; i < times; i++) { ret = SpmSearch(text, textlen, needle, needlelen); } - if (times > 1) { CLOCK_END; CLOCK_PRINT_SEC; }; + if (times > 1) { + CLOCK_END; + CLOCK_PRINT_SEC; + }; return ret; } @@ -561,15 +606,18 @@ static uint8_t *BoyerMooreNocaseCtxWrapper(uint8_t *text, uint8_t *in_needle, in int i = 0; CLOCK_INIT; - if (times > 1) CLOCK_START; + if (times > 1) + CLOCK_START; for (i = 0; i < times; i++) { ret = BoyerMooreNocase(needle, needlelen, text, textlen, bm_ctx); } - if (times > 1) { CLOCK_END; CLOCK_PRINT_SEC; }; + if (times > 1) { + CLOCK_END; + CLOCK_PRINT_SEC; + }; BoyerMooreCtxDeInit(bm_ctx); free(needle); return ret; - } #endif @@ -581,7 +629,7 @@ static int UtilSpmBasicSearchTest01(void) uint8_t *needle = (uint8_t *)"oPqRsT"; uint8_t *text = (uint8_t *)"aBcDeFgHiJkLmNoPqRsTuVwXyZ"; uint8_t *found = BasicSearchWrapper(text, needle, 1); - //printf("found: %s\n", found); + // printf("found: %s\n", found); if (found != NULL) return 1; else @@ -596,7 +644,7 @@ static int UtilSpmBasicSearchNocaseTest01(void) uint8_t *needle = (uint8_t *)"OpQrSt"; uint8_t *text = (uint8_t *)"aBcDeFgHiJkLmNoPqRsTuVwXyZ"; uint8_t *found = BasicSearchNocaseWrapper(text, needle, 1); - //printf("found: %s\n", found); + // printf("found: %s\n", found); if (found != NULL) return 1; else @@ -611,7 +659,7 @@ static int UtilSpmBs2bmSearchTest01(void) uint8_t *needle = (uint8_t *)"oPqRsT"; uint8_t *text = (uint8_t *)"aBcDeFgHiJkLmNoPqRsTuVwXyZ"; uint8_t *found = Bs2bmWrapper(text, needle, 1); - //printf("found: %s\n", found); + // printf("found: %s\n", found); if (found != NULL) return 1; else @@ -626,7 +674,7 @@ static int UtilSpmBs2bmSearchNocaseTest01(void) uint8_t *needle = (uint8_t *)"OpQrSt"; uint8_t *text = (uint8_t *)"aBcDeFgHiJkLmNoPqRsTuVwXyZ"; uint8_t *found = Bs2bmNocaseWrapper(text, needle, 1); - //printf("found: %s\n", found); + // printf("found: %s\n", found); if (found != NULL) return 1; else @@ -641,7 +689,7 @@ static int UtilSpmBoyerMooreSearchTest01(void) uint8_t *needle = (uint8_t *)"oPqRsT"; uint8_t *text = (uint8_t *)"aBcDeFgHiJkLmNoPqRsTuVwXyZ"; uint8_t *found = BoyerMooreWrapper(text, needle, 1); - //printf("found: %s\n", found); + // printf("found: %s\n", found); if (found != NULL) return 1; else @@ -656,7 +704,7 @@ static int UtilSpmBoyerMooreSearchNocaseTest01(void) uint8_t *needle = (uint8_t *)"OpQrSt"; uint8_t *text = (uint8_t *)"aBcDeFgHiJkLmNoPqRsTuVwXyZ"; uint8_t *found = BoyerMooreNocaseWrapper(text, needle, 1); - //printf("found: %s\n", found); + // printf("found: %s\n", found); if (found != NULL) return 1; else @@ -670,17 +718,18 @@ static int UtilSpmBoyerMooreSearchNocaseTest01(void) static int UtilSpmBoyerMooreSearchNocaseTestIssue130(void) { uint8_t *needle = (uint8_t *)"WWW-Authenticate: "; - uint8_t *text = (uint8_t *)"Date: Mon, 23 Feb 2009 13:31:49 GMT" - "Server: Apache\r\n" - "Www-authenticate: Basic realm=\"Authentification user password\"\r\n" - "Vary: accept-language,accept-charset\r\n" - "Accept-ranges: bytes\r\n" - "Connection: close\r\n" - "Content-type: text/html; charset=iso-8859-1\r\n" - "Content-language: fr\r\n" - "Expires: Mon, 23 Feb 2009 13:31:49 GMT\r\n\r\n"; + uint8_t *text = + (uint8_t *)"Date: Mon, 23 Feb 2009 13:31:49 GMT" + "Server: Apache\r\n" + "Www-authenticate: Basic realm=\"Authentification user password\"\r\n" + "Vary: accept-language,accept-charset\r\n" + "Accept-ranges: bytes\r\n" + "Connection: close\r\n" + "Content-type: text/html; charset=iso-8859-1\r\n" + "Content-language: fr\r\n" + "Expires: Mon, 23 Feb 2009 13:31:49 GMT\r\n\r\n"; uint8_t *found = BoyerMooreNocaseWrapper(text, needle, 1); - //printf("found: %s\n", found); + // printf("found: %s\n", found); if (found != NULL) return 1; else @@ -693,7 +742,7 @@ static int UtilSpmBasicSearchTest02(void) uint8_t *needle = (uint8_t *)"oPQRsT"; uint8_t *text = (uint8_t *)"aBcDeFgHiJkLmNoPqRsTuVwXyZ"; uint8_t *found = BasicSearchWrapper(text, needle, 1); - //printf("found: %s\n", found); + // printf("found: %s\n", found); if (found != NULL) return 0; else @@ -705,7 +754,7 @@ static int UtilSpmBasicSearchNocaseTest02(void) uint8_t *needle = (uint8_t *)"OpZrSt"; uint8_t *text = (uint8_t *)"aBcDeFgHiJkLmNoPqRsTuVwXyZ"; uint8_t *found = BasicSearchNocaseWrapper(text, needle, 1); - //printf("found: %s\n", found); + // printf("found: %s\n", found); if (found != NULL) return 0; else @@ -717,7 +766,7 @@ static int UtilSpmBs2bmSearchTest02(void) uint8_t *needle = (uint8_t *)"oPQRsT"; uint8_t *text = (uint8_t *)"aBcDeFgHiJkLmNoPqRsTuVwXyZ"; uint8_t *found = Bs2bmWrapper(text, needle, 1); - //printf("found: %s\n", found); + // printf("found: %s\n", found); if (found != NULL) return 0; else @@ -729,7 +778,7 @@ static int UtilSpmBs2bmSearchNocaseTest02(void) uint8_t *needle = (uint8_t *)"OpZrSt"; uint8_t *text = (uint8_t *)"aBcDeFgHiJkLmNoPqRsTuVwXyZ"; uint8_t *found = Bs2bmNocaseWrapper(text, needle, 1); - //printf("found: %s\n", found); + // printf("found: %s\n", found); if (found != NULL) return 0; else @@ -741,7 +790,7 @@ static int UtilSpmBoyerMooreSearchTest02(void) uint8_t *needle = (uint8_t *)"oPQRsT"; uint8_t *text = (uint8_t *)"aBcDeFgHiJkLmNoPqRsTuVwXyZ"; uint8_t *found = BoyerMooreWrapper(text, needle, 1); - //printf("found: %s\n", found); + // printf("found: %s\n", found); if (found != NULL) return 0; else @@ -753,7 +802,7 @@ static int UtilSpmBoyerMooreSearchNocaseTest02(void) uint8_t *needle = (uint8_t *)"OpZrSt"; uint8_t *text = (uint8_t *)"aBcDeFgHiJkLmNoPqRsTuVwXyZ"; uint8_t *found = BoyerMooreNocaseWrapper(text, needle, 1); - //printf("found: %s\n", found); + // printf("found: %s\n", found); if (found != NULL) return 0; else @@ -766,411 +815,411 @@ static int UtilSpmBoyerMooreSearchNocaseTest02(void) static int UtilSpmSearchOffsetsTest01(void) { const char *text[26][27]; - text[0][0]="azzzzzzzzzzzzzzzzzzzzzzzzzz"; - text[0][1]="zazzzzzzzzzzzzzzzzzzzzzzzzz"; - text[0][2]="zzazzzzzzzzzzzzzzzzzzzzzzzz"; - text[0][3]="zzzazzzzzzzzzzzzzzzzzzzzzzz"; - text[0][4]="zzzzazzzzzzzzzzzzzzzzzzzzzz"; - text[0][5]="zzzzzazzzzzzzzzzzzzzzzzzzzz"; - text[0][6]="zzzzzzazzzzzzzzzzzzzzzzzzzz"; - text[0][7]="zzzzzzzazzzzzzzzzzzzzzzzzzz"; - text[0][8]="zzzzzzzzazzzzzzzzzzzzzzzzzz"; - text[0][9]="zzzzzzzzzazzzzzzzzzzzzzzzzz"; - text[0][10]="zzzzzzzzzzazzzzzzzzzzzzzzzz"; - text[0][11]="zzzzzzzzzzzazzzzzzzzzzzzzzz"; - text[0][12]="zzzzzzzzzzzzazzzzzzzzzzzzzz"; - text[0][13]="zzzzzzzzzzzzzazzzzzzzzzzzzz"; - text[0][14]="zzzzzzzzzzzzzzazzzzzzzzzzzz"; - text[0][15]="zzzzzzzzzzzzzzzazzzzzzzzzzz"; - text[0][16]="zzzzzzzzzzzzzzzzazzzzzzzzzz"; - text[0][17]="zzzzzzzzzzzzzzzzzazzzzzzzzz"; - text[0][18]="zzzzzzzzzzzzzzzzzzazzzzzzzz"; - text[0][19]="zzzzzzzzzzzzzzzzzzzazzzzzzz"; - text[0][20]="zzzzzzzzzzzzzzzzzzzzazzzzzz"; - text[0][21]="zzzzzzzzzzzzzzzzzzzzzazzzzz"; - text[0][22]="zzzzzzzzzzzzzzzzzzzzzzazzzz"; - text[0][23]="zzzzzzzzzzzzzzzzzzzzzzzazzz"; - text[0][24]="zzzzzzzzzzzzzzzzzzzzzzzzazz"; - text[0][25]="zzzzzzzzzzzzzzzzzzzzzzzzzaz"; - text[0][26]="zzzzzzzzzzzzzzzzzzzzzzzzzza"; - text[1][0]="aBzzzzzzzzzzzzzzzzzzzzzzzzz"; - text[1][1]="zaBzzzzzzzzzzzzzzzzzzzzzzzz"; - text[1][2]="zzaBzzzzzzzzzzzzzzzzzzzzzzz"; - text[1][3]="zzzaBzzzzzzzzzzzzzzzzzzzzzz"; - text[1][4]="zzzzaBzzzzzzzzzzzzzzzzzzzzz"; - text[1][5]="zzzzzaBzzzzzzzzzzzzzzzzzzzz"; - text[1][6]="zzzzzzaBzzzzzzzzzzzzzzzzzzz"; - text[1][7]="zzzzzzzaBzzzzzzzzzzzzzzzzzz"; - text[1][8]="zzzzzzzzaBzzzzzzzzzzzzzzzzz"; - text[1][9]="zzzzzzzzzaBzzzzzzzzzzzzzzzz"; - text[1][10]="zzzzzzzzzzaBzzzzzzzzzzzzzzz"; - text[1][11]="zzzzzzzzzzzaBzzzzzzzzzzzzzz"; - text[1][12]="zzzzzzzzzzzzaBzzzzzzzzzzzzz"; - text[1][13]="zzzzzzzzzzzzzaBzzzzzzzzzzzz"; - text[1][14]="zzzzzzzzzzzzzzaBzzzzzzzzzzz"; - text[1][15]="zzzzzzzzzzzzzzzaBzzzzzzzzzz"; - text[1][16]="zzzzzzzzzzzzzzzzaBzzzzzzzzz"; - text[1][17]="zzzzzzzzzzzzzzzzzaBzzzzzzzz"; - text[1][18]="zzzzzzzzzzzzzzzzzzaBzzzzzzz"; - text[1][19]="zzzzzzzzzzzzzzzzzzzaBzzzzzz"; - text[1][20]="zzzzzzzzzzzzzzzzzzzzaBzzzzz"; - text[1][21]="zzzzzzzzzzzzzzzzzzzzzaBzzzz"; - text[1][22]="zzzzzzzzzzzzzzzzzzzzzzaBzzz"; - text[1][23]="zzzzzzzzzzzzzzzzzzzzzzzaBzz"; - text[1][24]="zzzzzzzzzzzzzzzzzzzzzzzzaBz"; - text[1][25]="zzzzzzzzzzzzzzzzzzzzzzzzzaB"; - text[2][0]="aBczzzzzzzzzzzzzzzzzzzzzzzz"; - text[2][1]="zaBczzzzzzzzzzzzzzzzzzzzzzz"; - text[2][2]="zzaBczzzzzzzzzzzzzzzzzzzzzz"; - text[2][3]="zzzaBczzzzzzzzzzzzzzzzzzzzz"; - text[2][4]="zzzzaBczzzzzzzzzzzzzzzzzzzz"; - text[2][5]="zzzzzaBczzzzzzzzzzzzzzzzzzz"; - text[2][6]="zzzzzzaBczzzzzzzzzzzzzzzzzz"; - text[2][7]="zzzzzzzaBczzzzzzzzzzzzzzzzz"; - text[2][8]="zzzzzzzzaBczzzzzzzzzzzzzzzz"; - text[2][9]="zzzzzzzzzaBczzzzzzzzzzzzzzz"; - text[2][10]="zzzzzzzzzzaBczzzzzzzzzzzzzz"; - text[2][11]="zzzzzzzzzzzaBczzzzzzzzzzzzz"; - text[2][12]="zzzzzzzzzzzzaBczzzzzzzzzzzz"; - text[2][13]="zzzzzzzzzzzzzaBczzzzzzzzzzz"; - text[2][14]="zzzzzzzzzzzzzzaBczzzzzzzzzz"; - text[2][15]="zzzzzzzzzzzzzzzaBczzzzzzzzz"; - text[2][16]="zzzzzzzzzzzzzzzzaBczzzzzzzz"; - text[2][17]="zzzzzzzzzzzzzzzzzaBczzzzzzz"; - text[2][18]="zzzzzzzzzzzzzzzzzzaBczzzzzz"; - text[2][19]="zzzzzzzzzzzzzzzzzzzaBczzzzz"; - text[2][20]="zzzzzzzzzzzzzzzzzzzzaBczzzz"; - text[2][21]="zzzzzzzzzzzzzzzzzzzzzaBczzz"; - text[2][22]="zzzzzzzzzzzzzzzzzzzzzzaBczz"; - text[2][23]="zzzzzzzzzzzzzzzzzzzzzzzaBcz"; - text[2][24]="zzzzzzzzzzzzzzzzzzzzzzzzaBc"; - text[3][0]="aBcDzzzzzzzzzzzzzzzzzzzzzzz"; - text[3][1]="zaBcDzzzzzzzzzzzzzzzzzzzzzz"; - text[3][2]="zzaBcDzzzzzzzzzzzzzzzzzzzzz"; - text[3][3]="zzzaBcDzzzzzzzzzzzzzzzzzzzz"; - text[3][4]="zzzzaBcDzzzzzzzzzzzzzzzzzzz"; - text[3][5]="zzzzzaBcDzzzzzzzzzzzzzzzzzz"; - text[3][6]="zzzzzzaBcDzzzzzzzzzzzzzzzzz"; - text[3][7]="zzzzzzzaBcDzzzzzzzzzzzzzzzz"; - text[3][8]="zzzzzzzzaBcDzzzzzzzzzzzzzzz"; - text[3][9]="zzzzzzzzzaBcDzzzzzzzzzzzzzz"; - text[3][10]="zzzzzzzzzzaBcDzzzzzzzzzzzzz"; - text[3][11]="zzzzzzzzzzzaBcDzzzzzzzzzzzz"; - text[3][12]="zzzzzzzzzzzzaBcDzzzzzzzzzzz"; - text[3][13]="zzzzzzzzzzzzzaBcDzzzzzzzzzz"; - text[3][14]="zzzzzzzzzzzzzzaBcDzzzzzzzzz"; - text[3][15]="zzzzzzzzzzzzzzzaBcDzzzzzzzz"; - text[3][16]="zzzzzzzzzzzzzzzzaBcDzzzzzzz"; - text[3][17]="zzzzzzzzzzzzzzzzzaBcDzzzzzz"; - text[3][18]="zzzzzzzzzzzzzzzzzzaBcDzzzzz"; - text[3][19]="zzzzzzzzzzzzzzzzzzzaBcDzzzz"; - text[3][20]="zzzzzzzzzzzzzzzzzzzzaBcDzzz"; - text[3][21]="zzzzzzzzzzzzzzzzzzzzzaBcDzz"; - text[3][22]="zzzzzzzzzzzzzzzzzzzzzzaBcDz"; - text[3][23]="zzzzzzzzzzzzzzzzzzzzzzzaBcD"; - text[4][0]="aBcDezzzzzzzzzzzzzzzzzzzzzz"; - text[4][1]="zaBcDezzzzzzzzzzzzzzzzzzzzz"; - text[4][2]="zzaBcDezzzzzzzzzzzzzzzzzzzz"; - text[4][3]="zzzaBcDezzzzzzzzzzzzzzzzzzz"; - text[4][4]="zzzzaBcDezzzzzzzzzzzzzzzzzz"; - text[4][5]="zzzzzaBcDezzzzzzzzzzzzzzzzz"; - text[4][6]="zzzzzzaBcDezzzzzzzzzzzzzzzz"; - text[4][7]="zzzzzzzaBcDezzzzzzzzzzzzzzz"; - text[4][8]="zzzzzzzzaBcDezzzzzzzzzzzzzz"; - text[4][9]="zzzzzzzzzaBcDezzzzzzzzzzzzz"; - text[4][10]="zzzzzzzzzzaBcDezzzzzzzzzzzz"; - text[4][11]="zzzzzzzzzzzaBcDezzzzzzzzzzz"; - text[4][12]="zzzzzzzzzzzzaBcDezzzzzzzzzz"; - text[4][13]="zzzzzzzzzzzzzaBcDezzzzzzzzz"; - text[4][14]="zzzzzzzzzzzzzzaBcDezzzzzzzz"; - text[4][15]="zzzzzzzzzzzzzzzaBcDezzzzzzz"; - text[4][16]="zzzzzzzzzzzzzzzzaBcDezzzzzz"; - text[4][17]="zzzzzzzzzzzzzzzzzaBcDezzzzz"; - text[4][18]="zzzzzzzzzzzzzzzzzzaBcDezzzz"; - text[4][19]="zzzzzzzzzzzzzzzzzzzaBcDezzz"; - text[4][20]="zzzzzzzzzzzzzzzzzzzzaBcDezz"; - text[4][21]="zzzzzzzzzzzzzzzzzzzzzaBcDez"; - text[4][22]="zzzzzzzzzzzzzzzzzzzzzzaBcDe"; - text[5][0]="aBcDeFzzzzzzzzzzzzzzzzzzzzz"; - text[5][1]="zaBcDeFzzzzzzzzzzzzzzzzzzzz"; - text[5][2]="zzaBcDeFzzzzzzzzzzzzzzzzzzz"; - text[5][3]="zzzaBcDeFzzzzzzzzzzzzzzzzzz"; - text[5][4]="zzzzaBcDeFzzzzzzzzzzzzzzzzz"; - text[5][5]="zzzzzaBcDeFzzzzzzzzzzzzzzzz"; - text[5][6]="zzzzzzaBcDeFzzzzzzzzzzzzzzz"; - text[5][7]="zzzzzzzaBcDeFzzzzzzzzzzzzzz"; - text[5][8]="zzzzzzzzaBcDeFzzzzzzzzzzzzz"; - text[5][9]="zzzzzzzzzaBcDeFzzzzzzzzzzzz"; - text[5][10]="zzzzzzzzzzaBcDeFzzzzzzzzzzz"; - text[5][11]="zzzzzzzzzzzaBcDeFzzzzzzzzzz"; - text[5][12]="zzzzzzzzzzzzaBcDeFzzzzzzzzz"; - text[5][13]="zzzzzzzzzzzzzaBcDeFzzzzzzzz"; - text[5][14]="zzzzzzzzzzzzzzaBcDeFzzzzzzz"; - text[5][15]="zzzzzzzzzzzzzzzaBcDeFzzzzzz"; - text[5][16]="zzzzzzzzzzzzzzzzaBcDeFzzzzz"; - text[5][17]="zzzzzzzzzzzzzzzzzaBcDeFzzzz"; - text[5][18]="zzzzzzzzzzzzzzzzzzaBcDeFzzz"; - text[5][19]="zzzzzzzzzzzzzzzzzzzaBcDeFzz"; - text[5][20]="zzzzzzzzzzzzzzzzzzzzaBcDeFz"; - text[5][21]="zzzzzzzzzzzzzzzzzzzzzaBcDeF"; - text[6][0]="aBcDeFgzzzzzzzzzzzzzzzzzzzz"; - text[6][1]="zaBcDeFgzzzzzzzzzzzzzzzzzzz"; - text[6][2]="zzaBcDeFgzzzzzzzzzzzzzzzzzz"; - text[6][3]="zzzaBcDeFgzzzzzzzzzzzzzzzzz"; - text[6][4]="zzzzaBcDeFgzzzzzzzzzzzzzzzz"; - text[6][5]="zzzzzaBcDeFgzzzzzzzzzzzzzzz"; - text[6][6]="zzzzzzaBcDeFgzzzzzzzzzzzzzz"; - text[6][7]="zzzzzzzaBcDeFgzzzzzzzzzzzzz"; - text[6][8]="zzzzzzzzaBcDeFgzzzzzzzzzzzz"; - text[6][9]="zzzzzzzzzaBcDeFgzzzzzzzzzzz"; - text[6][10]="zzzzzzzzzzaBcDeFgzzzzzzzzzz"; - text[6][11]="zzzzzzzzzzzaBcDeFgzzzzzzzzz"; - text[6][12]="zzzzzzzzzzzzaBcDeFgzzzzzzzz"; - text[6][13]="zzzzzzzzzzzzzaBcDeFgzzzzzzz"; - text[6][14]="zzzzzzzzzzzzzzaBcDeFgzzzzzz"; - text[6][15]="zzzzzzzzzzzzzzzaBcDeFgzzzzz"; - text[6][16]="zzzzzzzzzzzzzzzzaBcDeFgzzzz"; - text[6][17]="zzzzzzzzzzzzzzzzzaBcDeFgzzz"; - text[6][18]="zzzzzzzzzzzzzzzzzzaBcDeFgzz"; - text[6][19]="zzzzzzzzzzzzzzzzzzzaBcDeFgz"; - text[6][20]="zzzzzzzzzzzzzzzzzzzzaBcDeFg"; - text[7][0]="aBcDeFgHzzzzzzzzzzzzzzzzzzz"; - text[7][1]="zaBcDeFgHzzzzzzzzzzzzzzzzzz"; - text[7][2]="zzaBcDeFgHzzzzzzzzzzzzzzzzz"; - text[7][3]="zzzaBcDeFgHzzzzzzzzzzzzzzzz"; - text[7][4]="zzzzaBcDeFgHzzzzzzzzzzzzzzz"; - text[7][5]="zzzzzaBcDeFgHzzzzzzzzzzzzzz"; - text[7][6]="zzzzzzaBcDeFgHzzzzzzzzzzzzz"; - text[7][7]="zzzzzzzaBcDeFgHzzzzzzzzzzzz"; - text[7][8]="zzzzzzzzaBcDeFgHzzzzzzzzzzz"; - text[7][9]="zzzzzzzzzaBcDeFgHzzzzzzzzzz"; - text[7][10]="zzzzzzzzzzaBcDeFgHzzzzzzzzz"; - text[7][11]="zzzzzzzzzzzaBcDeFgHzzzzzzzz"; - text[7][12]="zzzzzzzzzzzzaBcDeFgHzzzzzzz"; - text[7][13]="zzzzzzzzzzzzzaBcDeFgHzzzzzz"; - text[7][14]="zzzzzzzzzzzzzzaBcDeFgHzzzzz"; - text[7][15]="zzzzzzzzzzzzzzzaBcDeFgHzzzz"; - text[7][16]="zzzzzzzzzzzzzzzzaBcDeFgHzzz"; - text[7][17]="zzzzzzzzzzzzzzzzzaBcDeFgHzz"; - text[7][18]="zzzzzzzzzzzzzzzzzzaBcDeFgHz"; - text[7][19]="zzzzzzzzzzzzzzzzzzzaBcDeFgH"; - text[8][0]="aBcDeFgHizzzzzzzzzzzzzzzzzz"; - text[8][1]="zaBcDeFgHizzzzzzzzzzzzzzzzz"; - text[8][2]="zzaBcDeFgHizzzzzzzzzzzzzzzz"; - text[8][3]="zzzaBcDeFgHizzzzzzzzzzzzzzz"; - text[8][4]="zzzzaBcDeFgHizzzzzzzzzzzzzz"; - text[8][5]="zzzzzaBcDeFgHizzzzzzzzzzzzz"; - text[8][6]="zzzzzzaBcDeFgHizzzzzzzzzzzz"; - text[8][7]="zzzzzzzaBcDeFgHizzzzzzzzzzz"; - text[8][8]="zzzzzzzzaBcDeFgHizzzzzzzzzz"; - text[8][9]="zzzzzzzzzaBcDeFgHizzzzzzzzz"; - text[8][10]="zzzzzzzzzzaBcDeFgHizzzzzzzz"; - text[8][11]="zzzzzzzzzzzaBcDeFgHizzzzzzz"; - text[8][12]="zzzzzzzzzzzzaBcDeFgHizzzzzz"; - text[8][13]="zzzzzzzzzzzzzaBcDeFgHizzzzz"; - text[8][14]="zzzzzzzzzzzzzzaBcDeFgHizzzz"; - text[8][15]="zzzzzzzzzzzzzzzaBcDeFgHizzz"; - text[8][16]="zzzzzzzzzzzzzzzzaBcDeFgHizz"; - text[8][17]="zzzzzzzzzzzzzzzzzaBcDeFgHiz"; - text[8][18]="zzzzzzzzzzzzzzzzzzaBcDeFgHi"; - text[9][0]="aBcDeFgHiJzzzzzzzzzzzzzzzzz"; - text[9][1]="zaBcDeFgHiJzzzzzzzzzzzzzzzz"; - text[9][2]="zzaBcDeFgHiJzzzzzzzzzzzzzzz"; - text[9][3]="zzzaBcDeFgHiJzzzzzzzzzzzzzz"; - text[9][4]="zzzzaBcDeFgHiJzzzzzzzzzzzzz"; - text[9][5]="zzzzzaBcDeFgHiJzzzzzzzzzzzz"; - text[9][6]="zzzzzzaBcDeFgHiJzzzzzzzzzzz"; - text[9][7]="zzzzzzzaBcDeFgHiJzzzzzzzzzz"; - text[9][8]="zzzzzzzzaBcDeFgHiJzzzzzzzzz"; - text[9][9]="zzzzzzzzzaBcDeFgHiJzzzzzzzz"; - text[9][10]="zzzzzzzzzzaBcDeFgHiJzzzzzzz"; - text[9][11]="zzzzzzzzzzzaBcDeFgHiJzzzzzz"; - text[9][12]="zzzzzzzzzzzzaBcDeFgHiJzzzzz"; - text[9][13]="zzzzzzzzzzzzzaBcDeFgHiJzzzz"; - text[9][14]="zzzzzzzzzzzzzzaBcDeFgHiJzzz"; - text[9][15]="zzzzzzzzzzzzzzzaBcDeFgHiJzz"; - text[9][16]="zzzzzzzzzzzzzzzzaBcDeFgHiJz"; - text[9][17]="zzzzzzzzzzzzzzzzzaBcDeFgHiJ"; - text[10][0]="aBcDeFgHiJkzzzzzzzzzzzzzzzz"; - text[10][1]="zaBcDeFgHiJkzzzzzzzzzzzzzzz"; - text[10][2]="zzaBcDeFgHiJkzzzzzzzzzzzzzz"; - text[10][3]="zzzaBcDeFgHiJkzzzzzzzzzzzzz"; - text[10][4]="zzzzaBcDeFgHiJkzzzzzzzzzzzz"; - text[10][5]="zzzzzaBcDeFgHiJkzzzzzzzzzzz"; - text[10][6]="zzzzzzaBcDeFgHiJkzzzzzzzzzz"; - text[10][7]="zzzzzzzaBcDeFgHiJkzzzzzzzzz"; - text[10][8]="zzzzzzzzaBcDeFgHiJkzzzzzzzz"; - text[10][9]="zzzzzzzzzaBcDeFgHiJkzzzzzzz"; - text[10][10]="zzzzzzzzzzaBcDeFgHiJkzzzzzz"; - text[10][11]="zzzzzzzzzzzaBcDeFgHiJkzzzzz"; - text[10][12]="zzzzzzzzzzzzaBcDeFgHiJkzzzz"; - text[10][13]="zzzzzzzzzzzzzaBcDeFgHiJkzzz"; - text[10][14]="zzzzzzzzzzzzzzaBcDeFgHiJkzz"; - text[10][15]="zzzzzzzzzzzzzzzaBcDeFgHiJkz"; - text[10][16]="zzzzzzzzzzzzzzzzaBcDeFgHiJk"; - text[11][0]="aBcDeFgHiJkLzzzzzzzzzzzzzzz"; - text[11][1]="zaBcDeFgHiJkLzzzzzzzzzzzzzz"; - text[11][2]="zzaBcDeFgHiJkLzzzzzzzzzzzzz"; - text[11][3]="zzzaBcDeFgHiJkLzzzzzzzzzzzz"; - text[11][4]="zzzzaBcDeFgHiJkLzzzzzzzzzzz"; - text[11][5]="zzzzzaBcDeFgHiJkLzzzzzzzzzz"; - text[11][6]="zzzzzzaBcDeFgHiJkLzzzzzzzzz"; - text[11][7]="zzzzzzzaBcDeFgHiJkLzzzzzzzz"; - text[11][8]="zzzzzzzzaBcDeFgHiJkLzzzzzzz"; - text[11][9]="zzzzzzzzzaBcDeFgHiJkLzzzzzz"; - text[11][10]="zzzzzzzzzzaBcDeFgHiJkLzzzzz"; - text[11][11]="zzzzzzzzzzzaBcDeFgHiJkLzzzz"; - text[11][12]="zzzzzzzzzzzzaBcDeFgHiJkLzzz"; - text[11][13]="zzzzzzzzzzzzzaBcDeFgHiJkLzz"; - text[11][14]="zzzzzzzzzzzzzzaBcDeFgHiJkLz"; - text[11][15]="zzzzzzzzzzzzzzzaBcDeFgHiJkL"; - text[12][0]="aBcDeFgHiJkLmzzzzzzzzzzzzzz"; - text[12][1]="zaBcDeFgHiJkLmzzzzzzzzzzzzz"; - text[12][2]="zzaBcDeFgHiJkLmzzzzzzzzzzzz"; - text[12][3]="zzzaBcDeFgHiJkLmzzzzzzzzzzz"; - text[12][4]="zzzzaBcDeFgHiJkLmzzzzzzzzzz"; - text[12][5]="zzzzzaBcDeFgHiJkLmzzzzzzzzz"; - text[12][6]="zzzzzzaBcDeFgHiJkLmzzzzzzzz"; - text[12][7]="zzzzzzzaBcDeFgHiJkLmzzzzzzz"; - text[12][8]="zzzzzzzzaBcDeFgHiJkLmzzzzzz"; - text[12][9]="zzzzzzzzzaBcDeFgHiJkLmzzzzz"; - text[12][10]="zzzzzzzzzzaBcDeFgHiJkLmzzzz"; - text[12][11]="zzzzzzzzzzzaBcDeFgHiJkLmzzz"; - text[12][12]="zzzzzzzzzzzzaBcDeFgHiJkLmzz"; - text[12][13]="zzzzzzzzzzzzzaBcDeFgHiJkLmz"; - text[12][14]="zzzzzzzzzzzzzzaBcDeFgHiJkLm"; - text[13][0]="aBcDeFgHiJkLmNzzzzzzzzzzzzz"; - text[13][1]="zaBcDeFgHiJkLmNzzzzzzzzzzzz"; - text[13][2]="zzaBcDeFgHiJkLmNzzzzzzzzzzz"; - text[13][3]="zzzaBcDeFgHiJkLmNzzzzzzzzzz"; - text[13][4]="zzzzaBcDeFgHiJkLmNzzzzzzzzz"; - text[13][5]="zzzzzaBcDeFgHiJkLmNzzzzzzzz"; - text[13][6]="zzzzzzaBcDeFgHiJkLmNzzzzzzz"; - text[13][7]="zzzzzzzaBcDeFgHiJkLmNzzzzzz"; - text[13][8]="zzzzzzzzaBcDeFgHiJkLmNzzzzz"; - text[13][9]="zzzzzzzzzaBcDeFgHiJkLmNzzzz"; - text[13][10]="zzzzzzzzzzaBcDeFgHiJkLmNzzz"; - text[13][11]="zzzzzzzzzzzaBcDeFgHiJkLmNzz"; - text[13][12]="zzzzzzzzzzzzaBcDeFgHiJkLmNz"; - text[13][13]="zzzzzzzzzzzzzaBcDeFgHiJkLmN"; - text[14][0]="aBcDeFgHiJkLmNozzzzzzzzzzzz"; - text[14][1]="zaBcDeFgHiJkLmNozzzzzzzzzzz"; - text[14][2]="zzaBcDeFgHiJkLmNozzzzzzzzzz"; - text[14][3]="zzzaBcDeFgHiJkLmNozzzzzzzzz"; - text[14][4]="zzzzaBcDeFgHiJkLmNozzzzzzzz"; - text[14][5]="zzzzzaBcDeFgHiJkLmNozzzzzzz"; - text[14][6]="zzzzzzaBcDeFgHiJkLmNozzzzzz"; - text[14][7]="zzzzzzzaBcDeFgHiJkLmNozzzzz"; - text[14][8]="zzzzzzzzaBcDeFgHiJkLmNozzzz"; - text[14][9]="zzzzzzzzzaBcDeFgHiJkLmNozzz"; - text[14][10]="zzzzzzzzzzaBcDeFgHiJkLmNozz"; - text[14][11]="zzzzzzzzzzzaBcDeFgHiJkLmNoz"; - text[14][12]="zzzzzzzzzzzzaBcDeFgHiJkLmNo"; - text[15][0]="aBcDeFgHiJkLmNoPzzzzzzzzzzz"; - text[15][1]="zaBcDeFgHiJkLmNoPzzzzzzzzzz"; - text[15][2]="zzaBcDeFgHiJkLmNoPzzzzzzzzz"; - text[15][3]="zzzaBcDeFgHiJkLmNoPzzzzzzzz"; - text[15][4]="zzzzaBcDeFgHiJkLmNoPzzzzzzz"; - text[15][5]="zzzzzaBcDeFgHiJkLmNoPzzzzzz"; - text[15][6]="zzzzzzaBcDeFgHiJkLmNoPzzzzz"; - text[15][7]="zzzzzzzaBcDeFgHiJkLmNoPzzzz"; - text[15][8]="zzzzzzzzaBcDeFgHiJkLmNoPzzz"; - text[15][9]="zzzzzzzzzaBcDeFgHiJkLmNoPzz"; - text[15][10]="zzzzzzzzzzaBcDeFgHiJkLmNoPz"; - text[15][11]="zzzzzzzzzzzaBcDeFgHiJkLmNoP"; - text[16][0]="aBcDeFgHiJkLmNoPqzzzzzzzzzz"; - text[16][1]="zaBcDeFgHiJkLmNoPqzzzzzzzzz"; - text[16][2]="zzaBcDeFgHiJkLmNoPqzzzzzzzz"; - text[16][3]="zzzaBcDeFgHiJkLmNoPqzzzzzzz"; - text[16][4]="zzzzaBcDeFgHiJkLmNoPqzzzzzz"; - text[16][5]="zzzzzaBcDeFgHiJkLmNoPqzzzzz"; - text[16][6]="zzzzzzaBcDeFgHiJkLmNoPqzzzz"; - text[16][7]="zzzzzzzaBcDeFgHiJkLmNoPqzzz"; - text[16][8]="zzzzzzzzaBcDeFgHiJkLmNoPqzz"; - text[16][9]="zzzzzzzzzaBcDeFgHiJkLmNoPqz"; - text[16][10]="zzzzzzzzzzaBcDeFgHiJkLmNoPq"; - text[17][0]="aBcDeFgHiJkLmNoPqRzzzzzzzzz"; - text[17][1]="zaBcDeFgHiJkLmNoPqRzzzzzzzz"; - text[17][2]="zzaBcDeFgHiJkLmNoPqRzzzzzzz"; - text[17][3]="zzzaBcDeFgHiJkLmNoPqRzzzzzz"; - text[17][4]="zzzzaBcDeFgHiJkLmNoPqRzzzzz"; - text[17][5]="zzzzzaBcDeFgHiJkLmNoPqRzzzz"; - text[17][6]="zzzzzzaBcDeFgHiJkLmNoPqRzzz"; - text[17][7]="zzzzzzzaBcDeFgHiJkLmNoPqRzz"; - text[17][8]="zzzzzzzzaBcDeFgHiJkLmNoPqRz"; - text[17][9]="zzzzzzzzzaBcDeFgHiJkLmNoPqR"; - text[18][0]="aBcDeFgHiJkLmNoPqRszzzzzzzz"; - text[18][1]="zaBcDeFgHiJkLmNoPqRszzzzzzz"; - text[18][2]="zzaBcDeFgHiJkLmNoPqRszzzzzz"; - text[18][3]="zzzaBcDeFgHiJkLmNoPqRszzzzz"; - text[18][4]="zzzzaBcDeFgHiJkLmNoPqRszzzz"; - text[18][5]="zzzzzaBcDeFgHiJkLmNoPqRszzz"; - text[18][6]="zzzzzzaBcDeFgHiJkLmNoPqRszz"; - text[18][7]="zzzzzzzaBcDeFgHiJkLmNoPqRsz"; - text[18][8]="zzzzzzzzaBcDeFgHiJkLmNoPqRs"; - text[19][0]="aBcDeFgHiJkLmNoPqRsTzzzzzzz"; - text[19][1]="zaBcDeFgHiJkLmNoPqRsTzzzzzz"; - text[19][2]="zzaBcDeFgHiJkLmNoPqRsTzzzzz"; - text[19][3]="zzzaBcDeFgHiJkLmNoPqRsTzzzz"; - text[19][4]="zzzzaBcDeFgHiJkLmNoPqRsTzzz"; - text[19][5]="zzzzzaBcDeFgHiJkLmNoPqRsTzz"; - text[19][6]="zzzzzzaBcDeFgHiJkLmNoPqRsTz"; - text[19][7]="zzzzzzzaBcDeFgHiJkLmNoPqRsT"; - text[20][0]="aBcDeFgHiJkLmNoPqRsTuzzzzzz"; - text[20][1]="zaBcDeFgHiJkLmNoPqRsTuzzzzz"; - text[20][2]="zzaBcDeFgHiJkLmNoPqRsTuzzzz"; - text[20][3]="zzzaBcDeFgHiJkLmNoPqRsTuzzz"; - text[20][4]="zzzzaBcDeFgHiJkLmNoPqRsTuzz"; - text[20][5]="zzzzzaBcDeFgHiJkLmNoPqRsTuz"; - text[20][6]="zzzzzzaBcDeFgHiJkLmNoPqRsTu"; - text[21][0]="aBcDeFgHiJkLmNoPqRsTuVzzzzz"; - text[21][1]="zaBcDeFgHiJkLmNoPqRsTuVzzzz"; - text[21][2]="zzaBcDeFgHiJkLmNoPqRsTuVzzz"; - text[21][3]="zzzaBcDeFgHiJkLmNoPqRsTuVzz"; - text[21][4]="zzzzaBcDeFgHiJkLmNoPqRsTuVz"; - text[21][5]="zzzzzaBcDeFgHiJkLmNoPqRsTuV"; - text[22][0]="aBcDeFgHiJkLmNoPqRsTuVwzzzz"; - text[22][1]="zaBcDeFgHiJkLmNoPqRsTuVwzzz"; - text[22][2]="zzaBcDeFgHiJkLmNoPqRsTuVwzz"; - text[22][3]="zzzaBcDeFgHiJkLmNoPqRsTuVwz"; - text[22][4]="zzzzaBcDeFgHiJkLmNoPqRsTuVw"; - text[23][0]="aBcDeFgHiJkLmNoPqRsTuVwXzzz"; - text[23][1]="zaBcDeFgHiJkLmNoPqRsTuVwXzz"; - text[23][2]="zzaBcDeFgHiJkLmNoPqRsTuVwXz"; - text[23][3]="zzzaBcDeFgHiJkLmNoPqRsTuVwX"; - text[24][0]="aBcDeFgHiJkLmNoPqRsTuVwXyzz"; - text[24][1]="zaBcDeFgHiJkLmNoPqRsTuVwXyz"; - text[24][2]="zzaBcDeFgHiJkLmNoPqRsTuVwXy"; - text[25][0]="aBcDeFgHiJkLmNoPqRsTuVwXyZz"; - text[25][1]="zaBcDeFgHiJkLmNoPqRsTuVwXyZ"; + text[0][0] = "azzzzzzzzzzzzzzzzzzzzzzzzzz"; + text[0][1] = "zazzzzzzzzzzzzzzzzzzzzzzzzz"; + text[0][2] = "zzazzzzzzzzzzzzzzzzzzzzzzzz"; + text[0][3] = "zzzazzzzzzzzzzzzzzzzzzzzzzz"; + text[0][4] = "zzzzazzzzzzzzzzzzzzzzzzzzzz"; + text[0][5] = "zzzzzazzzzzzzzzzzzzzzzzzzzz"; + text[0][6] = "zzzzzzazzzzzzzzzzzzzzzzzzzz"; + text[0][7] = "zzzzzzzazzzzzzzzzzzzzzzzzzz"; + text[0][8] = "zzzzzzzzazzzzzzzzzzzzzzzzzz"; + text[0][9] = "zzzzzzzzzazzzzzzzzzzzzzzzzz"; + text[0][10] = "zzzzzzzzzzazzzzzzzzzzzzzzzz"; + text[0][11] = "zzzzzzzzzzzazzzzzzzzzzzzzzz"; + text[0][12] = "zzzzzzzzzzzzazzzzzzzzzzzzzz"; + text[0][13] = "zzzzzzzzzzzzzazzzzzzzzzzzzz"; + text[0][14] = "zzzzzzzzzzzzzzazzzzzzzzzzzz"; + text[0][15] = "zzzzzzzzzzzzzzzazzzzzzzzzzz"; + text[0][16] = "zzzzzzzzzzzzzzzzazzzzzzzzzz"; + text[0][17] = "zzzzzzzzzzzzzzzzzazzzzzzzzz"; + text[0][18] = "zzzzzzzzzzzzzzzzzzazzzzzzzz"; + text[0][19] = "zzzzzzzzzzzzzzzzzzzazzzzzzz"; + text[0][20] = "zzzzzzzzzzzzzzzzzzzzazzzzzz"; + text[0][21] = "zzzzzzzzzzzzzzzzzzzzzazzzzz"; + text[0][22] = "zzzzzzzzzzzzzzzzzzzzzzazzzz"; + text[0][23] = "zzzzzzzzzzzzzzzzzzzzzzzazzz"; + text[0][24] = "zzzzzzzzzzzzzzzzzzzzzzzzazz"; + text[0][25] = "zzzzzzzzzzzzzzzzzzzzzzzzzaz"; + text[0][26] = "zzzzzzzzzzzzzzzzzzzzzzzzzza"; + text[1][0] = "aBzzzzzzzzzzzzzzzzzzzzzzzzz"; + text[1][1] = "zaBzzzzzzzzzzzzzzzzzzzzzzzz"; + text[1][2] = "zzaBzzzzzzzzzzzzzzzzzzzzzzz"; + text[1][3] = "zzzaBzzzzzzzzzzzzzzzzzzzzzz"; + text[1][4] = "zzzzaBzzzzzzzzzzzzzzzzzzzzz"; + text[1][5] = "zzzzzaBzzzzzzzzzzzzzzzzzzzz"; + text[1][6] = "zzzzzzaBzzzzzzzzzzzzzzzzzzz"; + text[1][7] = "zzzzzzzaBzzzzzzzzzzzzzzzzzz"; + text[1][8] = "zzzzzzzzaBzzzzzzzzzzzzzzzzz"; + text[1][9] = "zzzzzzzzzaBzzzzzzzzzzzzzzzz"; + text[1][10] = "zzzzzzzzzzaBzzzzzzzzzzzzzzz"; + text[1][11] = "zzzzzzzzzzzaBzzzzzzzzzzzzzz"; + text[1][12] = "zzzzzzzzzzzzaBzzzzzzzzzzzzz"; + text[1][13] = "zzzzzzzzzzzzzaBzzzzzzzzzzzz"; + text[1][14] = "zzzzzzzzzzzzzzaBzzzzzzzzzzz"; + text[1][15] = "zzzzzzzzzzzzzzzaBzzzzzzzzzz"; + text[1][16] = "zzzzzzzzzzzzzzzzaBzzzzzzzzz"; + text[1][17] = "zzzzzzzzzzzzzzzzzaBzzzzzzzz"; + text[1][18] = "zzzzzzzzzzzzzzzzzzaBzzzzzzz"; + text[1][19] = "zzzzzzzzzzzzzzzzzzzaBzzzzzz"; + text[1][20] = "zzzzzzzzzzzzzzzzzzzzaBzzzzz"; + text[1][21] = "zzzzzzzzzzzzzzzzzzzzzaBzzzz"; + text[1][22] = "zzzzzzzzzzzzzzzzzzzzzzaBzzz"; + text[1][23] = "zzzzzzzzzzzzzzzzzzzzzzzaBzz"; + text[1][24] = "zzzzzzzzzzzzzzzzzzzzzzzzaBz"; + text[1][25] = "zzzzzzzzzzzzzzzzzzzzzzzzzaB"; + text[2][0] = "aBczzzzzzzzzzzzzzzzzzzzzzzz"; + text[2][1] = "zaBczzzzzzzzzzzzzzzzzzzzzzz"; + text[2][2] = "zzaBczzzzzzzzzzzzzzzzzzzzzz"; + text[2][3] = "zzzaBczzzzzzzzzzzzzzzzzzzzz"; + text[2][4] = "zzzzaBczzzzzzzzzzzzzzzzzzzz"; + text[2][5] = "zzzzzaBczzzzzzzzzzzzzzzzzzz"; + text[2][6] = "zzzzzzaBczzzzzzzzzzzzzzzzzz"; + text[2][7] = "zzzzzzzaBczzzzzzzzzzzzzzzzz"; + text[2][8] = "zzzzzzzzaBczzzzzzzzzzzzzzzz"; + text[2][9] = "zzzzzzzzzaBczzzzzzzzzzzzzzz"; + text[2][10] = "zzzzzzzzzzaBczzzzzzzzzzzzzz"; + text[2][11] = "zzzzzzzzzzzaBczzzzzzzzzzzzz"; + text[2][12] = "zzzzzzzzzzzzaBczzzzzzzzzzzz"; + text[2][13] = "zzzzzzzzzzzzzaBczzzzzzzzzzz"; + text[2][14] = "zzzzzzzzzzzzzzaBczzzzzzzzzz"; + text[2][15] = "zzzzzzzzzzzzzzzaBczzzzzzzzz"; + text[2][16] = "zzzzzzzzzzzzzzzzaBczzzzzzzz"; + text[2][17] = "zzzzzzzzzzzzzzzzzaBczzzzzzz"; + text[2][18] = "zzzzzzzzzzzzzzzzzzaBczzzzzz"; + text[2][19] = "zzzzzzzzzzzzzzzzzzzaBczzzzz"; + text[2][20] = "zzzzzzzzzzzzzzzzzzzzaBczzzz"; + text[2][21] = "zzzzzzzzzzzzzzzzzzzzzaBczzz"; + text[2][22] = "zzzzzzzzzzzzzzzzzzzzzzaBczz"; + text[2][23] = "zzzzzzzzzzzzzzzzzzzzzzzaBcz"; + text[2][24] = "zzzzzzzzzzzzzzzzzzzzzzzzaBc"; + text[3][0] = "aBcDzzzzzzzzzzzzzzzzzzzzzzz"; + text[3][1] = "zaBcDzzzzzzzzzzzzzzzzzzzzzz"; + text[3][2] = "zzaBcDzzzzzzzzzzzzzzzzzzzzz"; + text[3][3] = "zzzaBcDzzzzzzzzzzzzzzzzzzzz"; + text[3][4] = "zzzzaBcDzzzzzzzzzzzzzzzzzzz"; + text[3][5] = "zzzzzaBcDzzzzzzzzzzzzzzzzzz"; + text[3][6] = "zzzzzzaBcDzzzzzzzzzzzzzzzzz"; + text[3][7] = "zzzzzzzaBcDzzzzzzzzzzzzzzzz"; + text[3][8] = "zzzzzzzzaBcDzzzzzzzzzzzzzzz"; + text[3][9] = "zzzzzzzzzaBcDzzzzzzzzzzzzzz"; + text[3][10] = "zzzzzzzzzzaBcDzzzzzzzzzzzzz"; + text[3][11] = "zzzzzzzzzzzaBcDzzzzzzzzzzzz"; + text[3][12] = "zzzzzzzzzzzzaBcDzzzzzzzzzzz"; + text[3][13] = "zzzzzzzzzzzzzaBcDzzzzzzzzzz"; + text[3][14] = "zzzzzzzzzzzzzzaBcDzzzzzzzzz"; + text[3][15] = "zzzzzzzzzzzzzzzaBcDzzzzzzzz"; + text[3][16] = "zzzzzzzzzzzzzzzzaBcDzzzzzzz"; + text[3][17] = "zzzzzzzzzzzzzzzzzaBcDzzzzzz"; + text[3][18] = "zzzzzzzzzzzzzzzzzzaBcDzzzzz"; + text[3][19] = "zzzzzzzzzzzzzzzzzzzaBcDzzzz"; + text[3][20] = "zzzzzzzzzzzzzzzzzzzzaBcDzzz"; + text[3][21] = "zzzzzzzzzzzzzzzzzzzzzaBcDzz"; + text[3][22] = "zzzzzzzzzzzzzzzzzzzzzzaBcDz"; + text[3][23] = "zzzzzzzzzzzzzzzzzzzzzzzaBcD"; + text[4][0] = "aBcDezzzzzzzzzzzzzzzzzzzzzz"; + text[4][1] = "zaBcDezzzzzzzzzzzzzzzzzzzzz"; + text[4][2] = "zzaBcDezzzzzzzzzzzzzzzzzzzz"; + text[4][3] = "zzzaBcDezzzzzzzzzzzzzzzzzzz"; + text[4][4] = "zzzzaBcDezzzzzzzzzzzzzzzzzz"; + text[4][5] = "zzzzzaBcDezzzzzzzzzzzzzzzzz"; + text[4][6] = "zzzzzzaBcDezzzzzzzzzzzzzzzz"; + text[4][7] = "zzzzzzzaBcDezzzzzzzzzzzzzzz"; + text[4][8] = "zzzzzzzzaBcDezzzzzzzzzzzzzz"; + text[4][9] = "zzzzzzzzzaBcDezzzzzzzzzzzzz"; + text[4][10] = "zzzzzzzzzzaBcDezzzzzzzzzzzz"; + text[4][11] = "zzzzzzzzzzzaBcDezzzzzzzzzzz"; + text[4][12] = "zzzzzzzzzzzzaBcDezzzzzzzzzz"; + text[4][13] = "zzzzzzzzzzzzzaBcDezzzzzzzzz"; + text[4][14] = "zzzzzzzzzzzzzzaBcDezzzzzzzz"; + text[4][15] = "zzzzzzzzzzzzzzzaBcDezzzzzzz"; + text[4][16] = "zzzzzzzzzzzzzzzzaBcDezzzzzz"; + text[4][17] = "zzzzzzzzzzzzzzzzzaBcDezzzzz"; + text[4][18] = "zzzzzzzzzzzzzzzzzzaBcDezzzz"; + text[4][19] = "zzzzzzzzzzzzzzzzzzzaBcDezzz"; + text[4][20] = "zzzzzzzzzzzzzzzzzzzzaBcDezz"; + text[4][21] = "zzzzzzzzzzzzzzzzzzzzzaBcDez"; + text[4][22] = "zzzzzzzzzzzzzzzzzzzzzzaBcDe"; + text[5][0] = "aBcDeFzzzzzzzzzzzzzzzzzzzzz"; + text[5][1] = "zaBcDeFzzzzzzzzzzzzzzzzzzzz"; + text[5][2] = "zzaBcDeFzzzzzzzzzzzzzzzzzzz"; + text[5][3] = "zzzaBcDeFzzzzzzzzzzzzzzzzzz"; + text[5][4] = "zzzzaBcDeFzzzzzzzzzzzzzzzzz"; + text[5][5] = "zzzzzaBcDeFzzzzzzzzzzzzzzzz"; + text[5][6] = "zzzzzzaBcDeFzzzzzzzzzzzzzzz"; + text[5][7] = "zzzzzzzaBcDeFzzzzzzzzzzzzzz"; + text[5][8] = "zzzzzzzzaBcDeFzzzzzzzzzzzzz"; + text[5][9] = "zzzzzzzzzaBcDeFzzzzzzzzzzzz"; + text[5][10] = "zzzzzzzzzzaBcDeFzzzzzzzzzzz"; + text[5][11] = "zzzzzzzzzzzaBcDeFzzzzzzzzzz"; + text[5][12] = "zzzzzzzzzzzzaBcDeFzzzzzzzzz"; + text[5][13] = "zzzzzzzzzzzzzaBcDeFzzzzzzzz"; + text[5][14] = "zzzzzzzzzzzzzzaBcDeFzzzzzzz"; + text[5][15] = "zzzzzzzzzzzzzzzaBcDeFzzzzzz"; + text[5][16] = "zzzzzzzzzzzzzzzzaBcDeFzzzzz"; + text[5][17] = "zzzzzzzzzzzzzzzzzaBcDeFzzzz"; + text[5][18] = "zzzzzzzzzzzzzzzzzzaBcDeFzzz"; + text[5][19] = "zzzzzzzzzzzzzzzzzzzaBcDeFzz"; + text[5][20] = "zzzzzzzzzzzzzzzzzzzzaBcDeFz"; + text[5][21] = "zzzzzzzzzzzzzzzzzzzzzaBcDeF"; + text[6][0] = "aBcDeFgzzzzzzzzzzzzzzzzzzzz"; + text[6][1] = "zaBcDeFgzzzzzzzzzzzzzzzzzzz"; + text[6][2] = "zzaBcDeFgzzzzzzzzzzzzzzzzzz"; + text[6][3] = "zzzaBcDeFgzzzzzzzzzzzzzzzzz"; + text[6][4] = "zzzzaBcDeFgzzzzzzzzzzzzzzzz"; + text[6][5] = "zzzzzaBcDeFgzzzzzzzzzzzzzzz"; + text[6][6] = "zzzzzzaBcDeFgzzzzzzzzzzzzzz"; + text[6][7] = "zzzzzzzaBcDeFgzzzzzzzzzzzzz"; + text[6][8] = "zzzzzzzzaBcDeFgzzzzzzzzzzzz"; + text[6][9] = "zzzzzzzzzaBcDeFgzzzzzzzzzzz"; + text[6][10] = "zzzzzzzzzzaBcDeFgzzzzzzzzzz"; + text[6][11] = "zzzzzzzzzzzaBcDeFgzzzzzzzzz"; + text[6][12] = "zzzzzzzzzzzzaBcDeFgzzzzzzzz"; + text[6][13] = "zzzzzzzzzzzzzaBcDeFgzzzzzzz"; + text[6][14] = "zzzzzzzzzzzzzzaBcDeFgzzzzzz"; + text[6][15] = "zzzzzzzzzzzzzzzaBcDeFgzzzzz"; + text[6][16] = "zzzzzzzzzzzzzzzzaBcDeFgzzzz"; + text[6][17] = "zzzzzzzzzzzzzzzzzaBcDeFgzzz"; + text[6][18] = "zzzzzzzzzzzzzzzzzzaBcDeFgzz"; + text[6][19] = "zzzzzzzzzzzzzzzzzzzaBcDeFgz"; + text[6][20] = "zzzzzzzzzzzzzzzzzzzzaBcDeFg"; + text[7][0] = "aBcDeFgHzzzzzzzzzzzzzzzzzzz"; + text[7][1] = "zaBcDeFgHzzzzzzzzzzzzzzzzzz"; + text[7][2] = "zzaBcDeFgHzzzzzzzzzzzzzzzzz"; + text[7][3] = "zzzaBcDeFgHzzzzzzzzzzzzzzzz"; + text[7][4] = "zzzzaBcDeFgHzzzzzzzzzzzzzzz"; + text[7][5] = "zzzzzaBcDeFgHzzzzzzzzzzzzzz"; + text[7][6] = "zzzzzzaBcDeFgHzzzzzzzzzzzzz"; + text[7][7] = "zzzzzzzaBcDeFgHzzzzzzzzzzzz"; + text[7][8] = "zzzzzzzzaBcDeFgHzzzzzzzzzzz"; + text[7][9] = "zzzzzzzzzaBcDeFgHzzzzzzzzzz"; + text[7][10] = "zzzzzzzzzzaBcDeFgHzzzzzzzzz"; + text[7][11] = "zzzzzzzzzzzaBcDeFgHzzzzzzzz"; + text[7][12] = "zzzzzzzzzzzzaBcDeFgHzzzzzzz"; + text[7][13] = "zzzzzzzzzzzzzaBcDeFgHzzzzzz"; + text[7][14] = "zzzzzzzzzzzzzzaBcDeFgHzzzzz"; + text[7][15] = "zzzzzzzzzzzzzzzaBcDeFgHzzzz"; + text[7][16] = "zzzzzzzzzzzzzzzzaBcDeFgHzzz"; + text[7][17] = "zzzzzzzzzzzzzzzzzaBcDeFgHzz"; + text[7][18] = "zzzzzzzzzzzzzzzzzzaBcDeFgHz"; + text[7][19] = "zzzzzzzzzzzzzzzzzzzaBcDeFgH"; + text[8][0] = "aBcDeFgHizzzzzzzzzzzzzzzzzz"; + text[8][1] = "zaBcDeFgHizzzzzzzzzzzzzzzzz"; + text[8][2] = "zzaBcDeFgHizzzzzzzzzzzzzzzz"; + text[8][3] = "zzzaBcDeFgHizzzzzzzzzzzzzzz"; + text[8][4] = "zzzzaBcDeFgHizzzzzzzzzzzzzz"; + text[8][5] = "zzzzzaBcDeFgHizzzzzzzzzzzzz"; + text[8][6] = "zzzzzzaBcDeFgHizzzzzzzzzzzz"; + text[8][7] = "zzzzzzzaBcDeFgHizzzzzzzzzzz"; + text[8][8] = "zzzzzzzzaBcDeFgHizzzzzzzzzz"; + text[8][9] = "zzzzzzzzzaBcDeFgHizzzzzzzzz"; + text[8][10] = "zzzzzzzzzzaBcDeFgHizzzzzzzz"; + text[8][11] = "zzzzzzzzzzzaBcDeFgHizzzzzzz"; + text[8][12] = "zzzzzzzzzzzzaBcDeFgHizzzzzz"; + text[8][13] = "zzzzzzzzzzzzzaBcDeFgHizzzzz"; + text[8][14] = "zzzzzzzzzzzzzzaBcDeFgHizzzz"; + text[8][15] = "zzzzzzzzzzzzzzzaBcDeFgHizzz"; + text[8][16] = "zzzzzzzzzzzzzzzzaBcDeFgHizz"; + text[8][17] = "zzzzzzzzzzzzzzzzzaBcDeFgHiz"; + text[8][18] = "zzzzzzzzzzzzzzzzzzaBcDeFgHi"; + text[9][0] = "aBcDeFgHiJzzzzzzzzzzzzzzzzz"; + text[9][1] = "zaBcDeFgHiJzzzzzzzzzzzzzzzz"; + text[9][2] = "zzaBcDeFgHiJzzzzzzzzzzzzzzz"; + text[9][3] = "zzzaBcDeFgHiJzzzzzzzzzzzzzz"; + text[9][4] = "zzzzaBcDeFgHiJzzzzzzzzzzzzz"; + text[9][5] = "zzzzzaBcDeFgHiJzzzzzzzzzzzz"; + text[9][6] = "zzzzzzaBcDeFgHiJzzzzzzzzzzz"; + text[9][7] = "zzzzzzzaBcDeFgHiJzzzzzzzzzz"; + text[9][8] = "zzzzzzzzaBcDeFgHiJzzzzzzzzz"; + text[9][9] = "zzzzzzzzzaBcDeFgHiJzzzzzzzz"; + text[9][10] = "zzzzzzzzzzaBcDeFgHiJzzzzzzz"; + text[9][11] = "zzzzzzzzzzzaBcDeFgHiJzzzzzz"; + text[9][12] = "zzzzzzzzzzzzaBcDeFgHiJzzzzz"; + text[9][13] = "zzzzzzzzzzzzzaBcDeFgHiJzzzz"; + text[9][14] = "zzzzzzzzzzzzzzaBcDeFgHiJzzz"; + text[9][15] = "zzzzzzzzzzzzzzzaBcDeFgHiJzz"; + text[9][16] = "zzzzzzzzzzzzzzzzaBcDeFgHiJz"; + text[9][17] = "zzzzzzzzzzzzzzzzzaBcDeFgHiJ"; + text[10][0] = "aBcDeFgHiJkzzzzzzzzzzzzzzzz"; + text[10][1] = "zaBcDeFgHiJkzzzzzzzzzzzzzzz"; + text[10][2] = "zzaBcDeFgHiJkzzzzzzzzzzzzzz"; + text[10][3] = "zzzaBcDeFgHiJkzzzzzzzzzzzzz"; + text[10][4] = "zzzzaBcDeFgHiJkzzzzzzzzzzzz"; + text[10][5] = "zzzzzaBcDeFgHiJkzzzzzzzzzzz"; + text[10][6] = "zzzzzzaBcDeFgHiJkzzzzzzzzzz"; + text[10][7] = "zzzzzzzaBcDeFgHiJkzzzzzzzzz"; + text[10][8] = "zzzzzzzzaBcDeFgHiJkzzzzzzzz"; + text[10][9] = "zzzzzzzzzaBcDeFgHiJkzzzzzzz"; + text[10][10] = "zzzzzzzzzzaBcDeFgHiJkzzzzzz"; + text[10][11] = "zzzzzzzzzzzaBcDeFgHiJkzzzzz"; + text[10][12] = "zzzzzzzzzzzzaBcDeFgHiJkzzzz"; + text[10][13] = "zzzzzzzzzzzzzaBcDeFgHiJkzzz"; + text[10][14] = "zzzzzzzzzzzzzzaBcDeFgHiJkzz"; + text[10][15] = "zzzzzzzzzzzzzzzaBcDeFgHiJkz"; + text[10][16] = "zzzzzzzzzzzzzzzzaBcDeFgHiJk"; + text[11][0] = "aBcDeFgHiJkLzzzzzzzzzzzzzzz"; + text[11][1] = "zaBcDeFgHiJkLzzzzzzzzzzzzzz"; + text[11][2] = "zzaBcDeFgHiJkLzzzzzzzzzzzzz"; + text[11][3] = "zzzaBcDeFgHiJkLzzzzzzzzzzzz"; + text[11][4] = "zzzzaBcDeFgHiJkLzzzzzzzzzzz"; + text[11][5] = "zzzzzaBcDeFgHiJkLzzzzzzzzzz"; + text[11][6] = "zzzzzzaBcDeFgHiJkLzzzzzzzzz"; + text[11][7] = "zzzzzzzaBcDeFgHiJkLzzzzzzzz"; + text[11][8] = "zzzzzzzzaBcDeFgHiJkLzzzzzzz"; + text[11][9] = "zzzzzzzzzaBcDeFgHiJkLzzzzzz"; + text[11][10] = "zzzzzzzzzzaBcDeFgHiJkLzzzzz"; + text[11][11] = "zzzzzzzzzzzaBcDeFgHiJkLzzzz"; + text[11][12] = "zzzzzzzzzzzzaBcDeFgHiJkLzzz"; + text[11][13] = "zzzzzzzzzzzzzaBcDeFgHiJkLzz"; + text[11][14] = "zzzzzzzzzzzzzzaBcDeFgHiJkLz"; + text[11][15] = "zzzzzzzzzzzzzzzaBcDeFgHiJkL"; + text[12][0] = "aBcDeFgHiJkLmzzzzzzzzzzzzzz"; + text[12][1] = "zaBcDeFgHiJkLmzzzzzzzzzzzzz"; + text[12][2] = "zzaBcDeFgHiJkLmzzzzzzzzzzzz"; + text[12][3] = "zzzaBcDeFgHiJkLmzzzzzzzzzzz"; + text[12][4] = "zzzzaBcDeFgHiJkLmzzzzzzzzzz"; + text[12][5] = "zzzzzaBcDeFgHiJkLmzzzzzzzzz"; + text[12][6] = "zzzzzzaBcDeFgHiJkLmzzzzzzzz"; + text[12][7] = "zzzzzzzaBcDeFgHiJkLmzzzzzzz"; + text[12][8] = "zzzzzzzzaBcDeFgHiJkLmzzzzzz"; + text[12][9] = "zzzzzzzzzaBcDeFgHiJkLmzzzzz"; + text[12][10] = "zzzzzzzzzzaBcDeFgHiJkLmzzzz"; + text[12][11] = "zzzzzzzzzzzaBcDeFgHiJkLmzzz"; + text[12][12] = "zzzzzzzzzzzzaBcDeFgHiJkLmzz"; + text[12][13] = "zzzzzzzzzzzzzaBcDeFgHiJkLmz"; + text[12][14] = "zzzzzzzzzzzzzzaBcDeFgHiJkLm"; + text[13][0] = "aBcDeFgHiJkLmNzzzzzzzzzzzzz"; + text[13][1] = "zaBcDeFgHiJkLmNzzzzzzzzzzzz"; + text[13][2] = "zzaBcDeFgHiJkLmNzzzzzzzzzzz"; + text[13][3] = "zzzaBcDeFgHiJkLmNzzzzzzzzzz"; + text[13][4] = "zzzzaBcDeFgHiJkLmNzzzzzzzzz"; + text[13][5] = "zzzzzaBcDeFgHiJkLmNzzzzzzzz"; + text[13][6] = "zzzzzzaBcDeFgHiJkLmNzzzzzzz"; + text[13][7] = "zzzzzzzaBcDeFgHiJkLmNzzzzzz"; + text[13][8] = "zzzzzzzzaBcDeFgHiJkLmNzzzzz"; + text[13][9] = "zzzzzzzzzaBcDeFgHiJkLmNzzzz"; + text[13][10] = "zzzzzzzzzzaBcDeFgHiJkLmNzzz"; + text[13][11] = "zzzzzzzzzzzaBcDeFgHiJkLmNzz"; + text[13][12] = "zzzzzzzzzzzzaBcDeFgHiJkLmNz"; + text[13][13] = "zzzzzzzzzzzzzaBcDeFgHiJkLmN"; + text[14][0] = "aBcDeFgHiJkLmNozzzzzzzzzzzz"; + text[14][1] = "zaBcDeFgHiJkLmNozzzzzzzzzzz"; + text[14][2] = "zzaBcDeFgHiJkLmNozzzzzzzzzz"; + text[14][3] = "zzzaBcDeFgHiJkLmNozzzzzzzzz"; + text[14][4] = "zzzzaBcDeFgHiJkLmNozzzzzzzz"; + text[14][5] = "zzzzzaBcDeFgHiJkLmNozzzzzzz"; + text[14][6] = "zzzzzzaBcDeFgHiJkLmNozzzzzz"; + text[14][7] = "zzzzzzzaBcDeFgHiJkLmNozzzzz"; + text[14][8] = "zzzzzzzzaBcDeFgHiJkLmNozzzz"; + text[14][9] = "zzzzzzzzzaBcDeFgHiJkLmNozzz"; + text[14][10] = "zzzzzzzzzzaBcDeFgHiJkLmNozz"; + text[14][11] = "zzzzzzzzzzzaBcDeFgHiJkLmNoz"; + text[14][12] = "zzzzzzzzzzzzaBcDeFgHiJkLmNo"; + text[15][0] = "aBcDeFgHiJkLmNoPzzzzzzzzzzz"; + text[15][1] = "zaBcDeFgHiJkLmNoPzzzzzzzzzz"; + text[15][2] = "zzaBcDeFgHiJkLmNoPzzzzzzzzz"; + text[15][3] = "zzzaBcDeFgHiJkLmNoPzzzzzzzz"; + text[15][4] = "zzzzaBcDeFgHiJkLmNoPzzzzzzz"; + text[15][5] = "zzzzzaBcDeFgHiJkLmNoPzzzzzz"; + text[15][6] = "zzzzzzaBcDeFgHiJkLmNoPzzzzz"; + text[15][7] = "zzzzzzzaBcDeFgHiJkLmNoPzzzz"; + text[15][8] = "zzzzzzzzaBcDeFgHiJkLmNoPzzz"; + text[15][9] = "zzzzzzzzzaBcDeFgHiJkLmNoPzz"; + text[15][10] = "zzzzzzzzzzaBcDeFgHiJkLmNoPz"; + text[15][11] = "zzzzzzzzzzzaBcDeFgHiJkLmNoP"; + text[16][0] = "aBcDeFgHiJkLmNoPqzzzzzzzzzz"; + text[16][1] = "zaBcDeFgHiJkLmNoPqzzzzzzzzz"; + text[16][2] = "zzaBcDeFgHiJkLmNoPqzzzzzzzz"; + text[16][3] = "zzzaBcDeFgHiJkLmNoPqzzzzzzz"; + text[16][4] = "zzzzaBcDeFgHiJkLmNoPqzzzzzz"; + text[16][5] = "zzzzzaBcDeFgHiJkLmNoPqzzzzz"; + text[16][6] = "zzzzzzaBcDeFgHiJkLmNoPqzzzz"; + text[16][7] = "zzzzzzzaBcDeFgHiJkLmNoPqzzz"; + text[16][8] = "zzzzzzzzaBcDeFgHiJkLmNoPqzz"; + text[16][9] = "zzzzzzzzzaBcDeFgHiJkLmNoPqz"; + text[16][10] = "zzzzzzzzzzaBcDeFgHiJkLmNoPq"; + text[17][0] = "aBcDeFgHiJkLmNoPqRzzzzzzzzz"; + text[17][1] = "zaBcDeFgHiJkLmNoPqRzzzzzzzz"; + text[17][2] = "zzaBcDeFgHiJkLmNoPqRzzzzzzz"; + text[17][3] = "zzzaBcDeFgHiJkLmNoPqRzzzzzz"; + text[17][4] = "zzzzaBcDeFgHiJkLmNoPqRzzzzz"; + text[17][5] = "zzzzzaBcDeFgHiJkLmNoPqRzzzz"; + text[17][6] = "zzzzzzaBcDeFgHiJkLmNoPqRzzz"; + text[17][7] = "zzzzzzzaBcDeFgHiJkLmNoPqRzz"; + text[17][8] = "zzzzzzzzaBcDeFgHiJkLmNoPqRz"; + text[17][9] = "zzzzzzzzzaBcDeFgHiJkLmNoPqR"; + text[18][0] = "aBcDeFgHiJkLmNoPqRszzzzzzzz"; + text[18][1] = "zaBcDeFgHiJkLmNoPqRszzzzzzz"; + text[18][2] = "zzaBcDeFgHiJkLmNoPqRszzzzzz"; + text[18][3] = "zzzaBcDeFgHiJkLmNoPqRszzzzz"; + text[18][4] = "zzzzaBcDeFgHiJkLmNoPqRszzzz"; + text[18][5] = "zzzzzaBcDeFgHiJkLmNoPqRszzz"; + text[18][6] = "zzzzzzaBcDeFgHiJkLmNoPqRszz"; + text[18][7] = "zzzzzzzaBcDeFgHiJkLmNoPqRsz"; + text[18][8] = "zzzzzzzzaBcDeFgHiJkLmNoPqRs"; + text[19][0] = "aBcDeFgHiJkLmNoPqRsTzzzzzzz"; + text[19][1] = "zaBcDeFgHiJkLmNoPqRsTzzzzzz"; + text[19][2] = "zzaBcDeFgHiJkLmNoPqRsTzzzzz"; + text[19][3] = "zzzaBcDeFgHiJkLmNoPqRsTzzzz"; + text[19][4] = "zzzzaBcDeFgHiJkLmNoPqRsTzzz"; + text[19][5] = "zzzzzaBcDeFgHiJkLmNoPqRsTzz"; + text[19][6] = "zzzzzzaBcDeFgHiJkLmNoPqRsTz"; + text[19][7] = "zzzzzzzaBcDeFgHiJkLmNoPqRsT"; + text[20][0] = "aBcDeFgHiJkLmNoPqRsTuzzzzzz"; + text[20][1] = "zaBcDeFgHiJkLmNoPqRsTuzzzzz"; + text[20][2] = "zzaBcDeFgHiJkLmNoPqRsTuzzzz"; + text[20][3] = "zzzaBcDeFgHiJkLmNoPqRsTuzzz"; + text[20][4] = "zzzzaBcDeFgHiJkLmNoPqRsTuzz"; + text[20][5] = "zzzzzaBcDeFgHiJkLmNoPqRsTuz"; + text[20][6] = "zzzzzzaBcDeFgHiJkLmNoPqRsTu"; + text[21][0] = "aBcDeFgHiJkLmNoPqRsTuVzzzzz"; + text[21][1] = "zaBcDeFgHiJkLmNoPqRsTuVzzzz"; + text[21][2] = "zzaBcDeFgHiJkLmNoPqRsTuVzzz"; + text[21][3] = "zzzaBcDeFgHiJkLmNoPqRsTuVzz"; + text[21][4] = "zzzzaBcDeFgHiJkLmNoPqRsTuVz"; + text[21][5] = "zzzzzaBcDeFgHiJkLmNoPqRsTuV"; + text[22][0] = "aBcDeFgHiJkLmNoPqRsTuVwzzzz"; + text[22][1] = "zaBcDeFgHiJkLmNoPqRsTuVwzzz"; + text[22][2] = "zzaBcDeFgHiJkLmNoPqRsTuVwzz"; + text[22][3] = "zzzaBcDeFgHiJkLmNoPqRsTuVwz"; + text[22][4] = "zzzzaBcDeFgHiJkLmNoPqRsTuVw"; + text[23][0] = "aBcDeFgHiJkLmNoPqRsTuVwXzzz"; + text[23][1] = "zaBcDeFgHiJkLmNoPqRsTuVwXzz"; + text[23][2] = "zzaBcDeFgHiJkLmNoPqRsTuVwXz"; + text[23][3] = "zzzaBcDeFgHiJkLmNoPqRsTuVwX"; + text[24][0] = "aBcDeFgHiJkLmNoPqRsTuVwXyzz"; + text[24][1] = "zaBcDeFgHiJkLmNoPqRsTuVwXyz"; + text[24][2] = "zzaBcDeFgHiJkLmNoPqRsTuVwXy"; + text[25][0] = "aBcDeFgHiJkLmNoPqRsTuVwXyZz"; + text[25][1] = "zaBcDeFgHiJkLmNoPqRsTuVwXyZ"; const char *needle[26]; - needle[0]="a"; - needle[1]="aB"; - needle[2]="aBc"; - needle[3]="aBcD"; - needle[4]="aBcDe"; - needle[5]="aBcDeF"; - needle[6]="aBcDeFg"; - needle[7]="aBcDeFgH"; - needle[8]="aBcDeFgHi"; - needle[9]="aBcDeFgHiJ"; - needle[10]="aBcDeFgHiJk"; - needle[11]="aBcDeFgHiJkL"; - needle[12]="aBcDeFgHiJkLm"; - needle[13]="aBcDeFgHiJkLmN"; - needle[14]="aBcDeFgHiJkLmNo"; - needle[15]="aBcDeFgHiJkLmNoP"; - needle[16]="aBcDeFgHiJkLmNoPq"; - needle[17]="aBcDeFgHiJkLmNoPqR"; - needle[18]="aBcDeFgHiJkLmNoPqRs"; - needle[19]="aBcDeFgHiJkLmNoPqRsT"; - needle[20]="aBcDeFgHiJkLmNoPqRsTu"; - needle[21]="aBcDeFgHiJkLmNoPqRsTuV"; - needle[22]="aBcDeFgHiJkLmNoPqRsTuVw"; - needle[23]="aBcDeFgHiJkLmNoPqRsTuVwX"; - needle[24]="aBcDeFgHiJkLmNoPqRsTuVwXy"; - needle[25]="aBcDeFgHiJkLmNoPqRsTuVwXyZ"; + needle[0] = "a"; + needle[1] = "aB"; + needle[2] = "aBc"; + needle[3] = "aBcD"; + needle[4] = "aBcDe"; + needle[5] = "aBcDeF"; + needle[6] = "aBcDeFg"; + needle[7] = "aBcDeFgH"; + needle[8] = "aBcDeFgHi"; + needle[9] = "aBcDeFgHiJ"; + needle[10] = "aBcDeFgHiJk"; + needle[11] = "aBcDeFgHiJkL"; + needle[12] = "aBcDeFgHiJkLm"; + needle[13] = "aBcDeFgHiJkLmN"; + needle[14] = "aBcDeFgHiJkLmNo"; + needle[15] = "aBcDeFgHiJkLmNoP"; + needle[16] = "aBcDeFgHiJkLmNoPq"; + needle[17] = "aBcDeFgHiJkLmNoPqR"; + needle[18] = "aBcDeFgHiJkLmNoPqRs"; + needle[19] = "aBcDeFgHiJkLmNoPqRsT"; + needle[20] = "aBcDeFgHiJkLmNoPqRsTu"; + needle[21] = "aBcDeFgHiJkLmNoPqRsTuV"; + needle[22] = "aBcDeFgHiJkLmNoPqRsTuVw"; + needle[23] = "aBcDeFgHiJkLmNoPqRsTuVwX"; + needle[24] = "aBcDeFgHiJkLmNoPqRsTuVwXy"; + needle[25] = "aBcDeFgHiJkLmNoPqRsTuVwXyZ"; int i, j; uint8_t *found = NULL; @@ -1202,416 +1251,416 @@ static int UtilSpmSearchOffsetsTest01(void) static int UtilSpmSearchOffsetsNocaseTest01(void) { const char *text[26][27]; - text[0][0]="azzzzzzzzzzzzzzzzzzzzzzzzzz"; - text[0][1]="zazzzzzzzzzzzzzzzzzzzzzzzzz"; - text[0][2]="zzazzzzzzzzzzzzzzzzzzzzzzzz"; - text[0][3]="zzzazzzzzzzzzzzzzzzzzzzzzzz"; - text[0][4]="zzzzazzzzzzzzzzzzzzzzzzzzzz"; - text[0][5]="zzzzzazzzzzzzzzzzzzzzzzzzzz"; - text[0][6]="zzzzzzazzzzzzzzzzzzzzzzzzzz"; - text[0][7]="zzzzzzzazzzzzzzzzzzzzzzzzzz"; - text[0][8]="zzzzzzzzazzzzzzzzzzzzzzzzzz"; - text[0][9]="zzzzzzzzzazzzzzzzzzzzzzzzzz"; - text[0][10]="zzzzzzzzzzazzzzzzzzzzzzzzzz"; - text[0][11]="zzzzzzzzzzzazzzzzzzzzzzzzzz"; - text[0][12]="zzzzzzzzzzzzazzzzzzzzzzzzzz"; - text[0][13]="zzzzzzzzzzzzzazzzzzzzzzzzzz"; - text[0][14]="zzzzzzzzzzzzzzazzzzzzzzzzzz"; - text[0][15]="zzzzzzzzzzzzzzzazzzzzzzzzzz"; - text[0][16]="zzzzzzzzzzzzzzzzazzzzzzzzzz"; - text[0][17]="zzzzzzzzzzzzzzzzzazzzzzzzzz"; - text[0][18]="zzzzzzzzzzzzzzzzzzazzzzzzzz"; - text[0][19]="zzzzzzzzzzzzzzzzzzzazzzzzzz"; - text[0][20]="zzzzzzzzzzzzzzzzzzzzazzzzzz"; - text[0][21]="zzzzzzzzzzzzzzzzzzzzzazzzzz"; - text[0][22]="zzzzzzzzzzzzzzzzzzzzzzazzzz"; - text[0][23]="zzzzzzzzzzzzzzzzzzzzzzzazzz"; - text[0][24]="zzzzzzzzzzzzzzzzzzzzzzzzazz"; - text[0][25]="zzzzzzzzzzzzzzzzzzzzzzzzzaz"; - text[0][26]="zzzzzzzzzzzzzzzzzzzzzzzzzza"; - text[1][0]="aBzzzzzzzzzzzzzzzzzzzzzzzzz"; - text[1][1]="zaBzzzzzzzzzzzzzzzzzzzzzzzz"; - text[1][2]="zzaBzzzzzzzzzzzzzzzzzzzzzzz"; - text[1][3]="zzzaBzzzzzzzzzzzzzzzzzzzzzz"; - text[1][4]="zzzzaBzzzzzzzzzzzzzzzzzzzzz"; - text[1][5]="zzzzzaBzzzzzzzzzzzzzzzzzzzz"; - text[1][6]="zzzzzzaBzzzzzzzzzzzzzzzzzzz"; - text[1][7]="zzzzzzzaBzzzzzzzzzzzzzzzzzz"; - text[1][8]="zzzzzzzzaBzzzzzzzzzzzzzzzzz"; - text[1][9]="zzzzzzzzzaBzzzzzzzzzzzzzzzz"; - text[1][10]="zzzzzzzzzzaBzzzzzzzzzzzzzzz"; - text[1][11]="zzzzzzzzzzzaBzzzzzzzzzzzzzz"; - text[1][12]="zzzzzzzzzzzzaBzzzzzzzzzzzzz"; - text[1][13]="zzzzzzzzzzzzzaBzzzzzzzzzzzz"; - text[1][14]="zzzzzzzzzzzzzzaBzzzzzzzzzzz"; - text[1][15]="zzzzzzzzzzzzzzzaBzzzzzzzzzz"; - text[1][16]="zzzzzzzzzzzzzzzzaBzzzzzzzzz"; - text[1][17]="zzzzzzzzzzzzzzzzzaBzzzzzzzz"; - text[1][18]="zzzzzzzzzzzzzzzzzzaBzzzzzzz"; - text[1][19]="zzzzzzzzzzzzzzzzzzzaBzzzzzz"; - text[1][20]="zzzzzzzzzzzzzzzzzzzzaBzzzzz"; - text[1][21]="zzzzzzzzzzzzzzzzzzzzzaBzzzz"; - text[1][22]="zzzzzzzzzzzzzzzzzzzzzzaBzzz"; - text[1][23]="zzzzzzzzzzzzzzzzzzzzzzzaBzz"; - text[1][24]="zzzzzzzzzzzzzzzzzzzzzzzzaBz"; - text[1][25]="zzzzzzzzzzzzzzzzzzzzzzzzzaB"; - text[2][0]="aBczzzzzzzzzzzzzzzzzzzzzzzz"; - text[2][1]="zaBczzzzzzzzzzzzzzzzzzzzzzz"; - text[2][2]="zzaBczzzzzzzzzzzzzzzzzzzzzz"; - text[2][3]="zzzaBczzzzzzzzzzzzzzzzzzzzz"; - text[2][4]="zzzzaBczzzzzzzzzzzzzzzzzzzz"; - text[2][5]="zzzzzaBczzzzzzzzzzzzzzzzzzz"; - text[2][6]="zzzzzzaBczzzzzzzzzzzzzzzzzz"; - text[2][7]="zzzzzzzaBczzzzzzzzzzzzzzzzz"; - text[2][8]="zzzzzzzzaBczzzzzzzzzzzzzzzz"; - text[2][9]="zzzzzzzzzaBczzzzzzzzzzzzzzz"; - text[2][10]="zzzzzzzzzzaBczzzzzzzzzzzzzz"; - text[2][11]="zzzzzzzzzzzaBczzzzzzzzzzzzz"; - text[2][12]="zzzzzzzzzzzzaBczzzzzzzzzzzz"; - text[2][13]="zzzzzzzzzzzzzaBczzzzzzzzzzz"; - text[2][14]="zzzzzzzzzzzzzzaBczzzzzzzzzz"; - text[2][15]="zzzzzzzzzzzzzzzaBczzzzzzzzz"; - text[2][16]="zzzzzzzzzzzzzzzzaBczzzzzzzz"; - text[2][17]="zzzzzzzzzzzzzzzzzaBczzzzzzz"; - text[2][18]="zzzzzzzzzzzzzzzzzzaBczzzzzz"; - text[2][19]="zzzzzzzzzzzzzzzzzzzaBczzzzz"; - text[2][20]="zzzzzzzzzzzzzzzzzzzzaBczzzz"; - text[2][21]="zzzzzzzzzzzzzzzzzzzzzaBczzz"; - text[2][22]="zzzzzzzzzzzzzzzzzzzzzzaBczz"; - text[2][23]="zzzzzzzzzzzzzzzzzzzzzzzaBcz"; - text[2][24]="zzzzzzzzzzzzzzzzzzzzzzzzaBc"; - text[3][0]="aBcDzzzzzzzzzzzzzzzzzzzzzzz"; - text[3][1]="zaBcDzzzzzzzzzzzzzzzzzzzzzz"; - text[3][2]="zzaBcDzzzzzzzzzzzzzzzzzzzzz"; - text[3][3]="zzzaBcDzzzzzzzzzzzzzzzzzzzz"; - text[3][4]="zzzzaBcDzzzzzzzzzzzzzzzzzzz"; - text[3][5]="zzzzzaBcDzzzzzzzzzzzzzzzzzz"; - text[3][6]="zzzzzzaBcDzzzzzzzzzzzzzzzzz"; - text[3][7]="zzzzzzzaBcDzzzzzzzzzzzzzzzz"; - text[3][8]="zzzzzzzzaBcDzzzzzzzzzzzzzzz"; - text[3][9]="zzzzzzzzzaBcDzzzzzzzzzzzzzz"; - text[3][10]="zzzzzzzzzzaBcDzzzzzzzzzzzzz"; - text[3][11]="zzzzzzzzzzzaBcDzzzzzzzzzzzz"; - text[3][12]="zzzzzzzzzzzzaBcDzzzzzzzzzzz"; - text[3][13]="zzzzzzzzzzzzzaBcDzzzzzzzzzz"; - text[3][14]="zzzzzzzzzzzzzzaBcDzzzzzzzzz"; - text[3][15]="zzzzzzzzzzzzzzzaBcDzzzzzzzz"; - text[3][16]="zzzzzzzzzzzzzzzzaBcDzzzzzzz"; - text[3][17]="zzzzzzzzzzzzzzzzzaBcDzzzzzz"; - text[3][18]="zzzzzzzzzzzzzzzzzzaBcDzzzzz"; - text[3][19]="zzzzzzzzzzzzzzzzzzzaBcDzzzz"; - text[3][20]="zzzzzzzzzzzzzzzzzzzzaBcDzzz"; - text[3][21]="zzzzzzzzzzzzzzzzzzzzzaBcDzz"; - text[3][22]="zzzzzzzzzzzzzzzzzzzzzzaBcDz"; - text[3][23]="zzzzzzzzzzzzzzzzzzzzzzzaBcD"; - text[4][0]="aBcDezzzzzzzzzzzzzzzzzzzzzz"; - text[4][1]="zaBcDezzzzzzzzzzzzzzzzzzzzz"; - text[4][2]="zzaBcDezzzzzzzzzzzzzzzzzzzz"; - text[4][3]="zzzaBcDezzzzzzzzzzzzzzzzzzz"; - text[4][4]="zzzzaBcDezzzzzzzzzzzzzzzzzz"; - text[4][5]="zzzzzaBcDezzzzzzzzzzzzzzzzz"; - text[4][6]="zzzzzzaBcDezzzzzzzzzzzzzzzz"; - text[4][7]="zzzzzzzaBcDezzzzzzzzzzzzzzz"; - text[4][8]="zzzzzzzzaBcDezzzzzzzzzzzzzz"; - text[4][9]="zzzzzzzzzaBcDezzzzzzzzzzzzz"; - text[4][10]="zzzzzzzzzzaBcDezzzzzzzzzzzz"; - text[4][11]="zzzzzzzzzzzaBcDezzzzzzzzzzz"; - text[4][12]="zzzzzzzzzzzzaBcDezzzzzzzzzz"; - text[4][13]="zzzzzzzzzzzzzaBcDezzzzzzzzz"; - text[4][14]="zzzzzzzzzzzzzzaBcDezzzzzzzz"; - text[4][15]="zzzzzzzzzzzzzzzaBcDezzzzzzz"; - text[4][16]="zzzzzzzzzzzzzzzzaBcDezzzzzz"; - text[4][17]="zzzzzzzzzzzzzzzzzaBcDezzzzz"; - text[4][18]="zzzzzzzzzzzzzzzzzzaBcDezzzz"; - text[4][19]="zzzzzzzzzzzzzzzzzzzaBcDezzz"; - text[4][20]="zzzzzzzzzzzzzzzzzzzzaBcDezz"; - text[4][21]="zzzzzzzzzzzzzzzzzzzzzaBcDez"; - text[4][22]="zzzzzzzzzzzzzzzzzzzzzzaBcDe"; - text[5][0]="aBcDeFzzzzzzzzzzzzzzzzzzzzz"; - text[5][1]="zaBcDeFzzzzzzzzzzzzzzzzzzzz"; - text[5][2]="zzaBcDeFzzzzzzzzzzzzzzzzzzz"; - text[5][3]="zzzaBcDeFzzzzzzzzzzzzzzzzzz"; - text[5][4]="zzzzaBcDeFzzzzzzzzzzzzzzzzz"; - text[5][5]="zzzzzaBcDeFzzzzzzzzzzzzzzzz"; - text[5][6]="zzzzzzaBcDeFzzzzzzzzzzzzzzz"; - text[5][7]="zzzzzzzaBcDeFzzzzzzzzzzzzzz"; - text[5][8]="zzzzzzzzaBcDeFzzzzzzzzzzzzz"; - text[5][9]="zzzzzzzzzaBcDeFzzzzzzzzzzzz"; - text[5][10]="zzzzzzzzzzaBcDeFzzzzzzzzzzz"; - text[5][11]="zzzzzzzzzzzaBcDeFzzzzzzzzzz"; - text[5][12]="zzzzzzzzzzzzaBcDeFzzzzzzzzz"; - text[5][13]="zzzzzzzzzzzzzaBcDeFzzzzzzzz"; - text[5][14]="zzzzzzzzzzzzzzaBcDeFzzzzzzz"; - text[5][15]="zzzzzzzzzzzzzzzaBcDeFzzzzzz"; - text[5][16]="zzzzzzzzzzzzzzzzaBcDeFzzzzz"; - text[5][17]="zzzzzzzzzzzzzzzzzaBcDeFzzzz"; - text[5][18]="zzzzzzzzzzzzzzzzzzaBcDeFzzz"; - text[5][19]="zzzzzzzzzzzzzzzzzzzaBcDeFzz"; - text[5][20]="zzzzzzzzzzzzzzzzzzzzaBcDeFz"; - text[5][21]="zzzzzzzzzzzzzzzzzzzzzaBcDeF"; - text[6][0]="aBcDeFgzzzzzzzzzzzzzzzzzzzz"; - text[6][1]="zaBcDeFgzzzzzzzzzzzzzzzzzzz"; - text[6][2]="zzaBcDeFgzzzzzzzzzzzzzzzzzz"; - text[6][3]="zzzaBcDeFgzzzzzzzzzzzzzzzzz"; - text[6][4]="zzzzaBcDeFgzzzzzzzzzzzzzzzz"; - text[6][5]="zzzzzaBcDeFgzzzzzzzzzzzzzzz"; - text[6][6]="zzzzzzaBcDeFgzzzzzzzzzzzzzz"; - text[6][7]="zzzzzzzaBcDeFgzzzzzzzzzzzzz"; - text[6][8]="zzzzzzzzaBcDeFgzzzzzzzzzzzz"; - text[6][9]="zzzzzzzzzaBcDeFgzzzzzzzzzzz"; - text[6][10]="zzzzzzzzzzaBcDeFgzzzzzzzzzz"; - text[6][11]="zzzzzzzzzzzaBcDeFgzzzzzzzzz"; - text[6][12]="zzzzzzzzzzzzaBcDeFgzzzzzzzz"; - text[6][13]="zzzzzzzzzzzzzaBcDeFgzzzzzzz"; - text[6][14]="zzzzzzzzzzzzzzaBcDeFgzzzzzz"; - text[6][15]="zzzzzzzzzzzzzzzaBcDeFgzzzzz"; - text[6][16]="zzzzzzzzzzzzzzzzaBcDeFgzzzz"; - text[6][17]="zzzzzzzzzzzzzzzzzaBcDeFgzzz"; - text[6][18]="zzzzzzzzzzzzzzzzzzaBcDeFgzz"; - text[6][19]="zzzzzzzzzzzzzzzzzzzaBcDeFgz"; - text[6][20]="zzzzzzzzzzzzzzzzzzzzaBcDeFg"; - text[7][0]="aBcDeFgHzzzzzzzzzzzzzzzzzzz"; - text[7][1]="zaBcDeFgHzzzzzzzzzzzzzzzzzz"; - text[7][2]="zzaBcDeFgHzzzzzzzzzzzzzzzzz"; - text[7][3]="zzzaBcDeFgHzzzzzzzzzzzzzzzz"; - text[7][4]="zzzzaBcDeFgHzzzzzzzzzzzzzzz"; - text[7][5]="zzzzzaBcDeFgHzzzzzzzzzzzzzz"; - text[7][6]="zzzzzzaBcDeFgHzzzzzzzzzzzzz"; - text[7][7]="zzzzzzzaBcDeFgHzzzzzzzzzzzz"; - text[7][8]="zzzzzzzzaBcDeFgHzzzzzzzzzzz"; - text[7][9]="zzzzzzzzzaBcDeFgHzzzzzzzzzz"; - text[7][10]="zzzzzzzzzzaBcDeFgHzzzzzzzzz"; - text[7][11]="zzzzzzzzzzzaBcDeFgHzzzzzzzz"; - text[7][12]="zzzzzzzzzzzzaBcDeFgHzzzzzzz"; - text[7][13]="zzzzzzzzzzzzzaBcDeFgHzzzzzz"; - text[7][14]="zzzzzzzzzzzzzzaBcDeFgHzzzzz"; - text[7][15]="zzzzzzzzzzzzzzzaBcDeFgHzzzz"; - text[7][16]="zzzzzzzzzzzzzzzzaBcDeFgHzzz"; - text[7][17]="zzzzzzzzzzzzzzzzzaBcDeFgHzz"; - text[7][18]="zzzzzzzzzzzzzzzzzzaBcDeFgHz"; - text[7][19]="zzzzzzzzzzzzzzzzzzzaBcDeFgH"; - text[8][0]="aBcDeFgHizzzzzzzzzzzzzzzzzz"; - text[8][1]="zaBcDeFgHizzzzzzzzzzzzzzzzz"; - text[8][2]="zzaBcDeFgHizzzzzzzzzzzzzzzz"; - text[8][3]="zzzaBcDeFgHizzzzzzzzzzzzzzz"; - text[8][4]="zzzzaBcDeFgHizzzzzzzzzzzzzz"; - text[8][5]="zzzzzaBcDeFgHizzzzzzzzzzzzz"; - text[8][6]="zzzzzzaBcDeFgHizzzzzzzzzzzz"; - text[8][7]="zzzzzzzaBcDeFgHizzzzzzzzzzz"; - text[8][8]="zzzzzzzzaBcDeFgHizzzzzzzzzz"; - text[8][9]="zzzzzzzzzaBcDeFgHizzzzzzzzz"; - text[8][10]="zzzzzzzzzzaBcDeFgHizzzzzzzz"; - text[8][11]="zzzzzzzzzzzaBcDeFgHizzzzzzz"; - text[8][12]="zzzzzzzzzzzzaBcDeFgHizzzzzz"; - text[8][13]="zzzzzzzzzzzzzaBcDeFgHizzzzz"; - text[8][14]="zzzzzzzzzzzzzzaBcDeFgHizzzz"; - text[8][15]="zzzzzzzzzzzzzzzaBcDeFgHizzz"; - text[8][16]="zzzzzzzzzzzzzzzzaBcDeFgHizz"; - text[8][17]="zzzzzzzzzzzzzzzzzaBcDeFgHiz"; - text[8][18]="zzzzzzzzzzzzzzzzzzaBcDeFgHi"; - text[9][0]="aBcDeFgHiJzzzzzzzzzzzzzzzzz"; - text[9][1]="zaBcDeFgHiJzzzzzzzzzzzzzzzz"; - text[9][2]="zzaBcDeFgHiJzzzzzzzzzzzzzzz"; - text[9][3]="zzzaBcDeFgHiJzzzzzzzzzzzzzz"; - text[9][4]="zzzzaBcDeFgHiJzzzzzzzzzzzzz"; - text[9][5]="zzzzzaBcDeFgHiJzzzzzzzzzzzz"; - text[9][6]="zzzzzzaBcDeFgHiJzzzzzzzzzzz"; - text[9][7]="zzzzzzzaBcDeFgHiJzzzzzzzzzz"; - text[9][8]="zzzzzzzzaBcDeFgHiJzzzzzzzzz"; - text[9][9]="zzzzzzzzzaBcDeFgHiJzzzzzzzz"; - text[9][10]="zzzzzzzzzzaBcDeFgHiJzzzzzzz"; - text[9][11]="zzzzzzzzzzzaBcDeFgHiJzzzzzz"; - text[9][12]="zzzzzzzzzzzzaBcDeFgHiJzzzzz"; - text[9][13]="zzzzzzzzzzzzzaBcDeFgHiJzzzz"; - text[9][14]="zzzzzzzzzzzzzzaBcDeFgHiJzzz"; - text[9][15]="zzzzzzzzzzzzzzzaBcDeFgHiJzz"; - text[9][16]="zzzzzzzzzzzzzzzzaBcDeFgHiJz"; - text[9][17]="zzzzzzzzzzzzzzzzzaBcDeFgHiJ"; - text[10][0]="aBcDeFgHiJkzzzzzzzzzzzzzzzz"; - text[10][1]="zaBcDeFgHiJkzzzzzzzzzzzzzzz"; - text[10][2]="zzaBcDeFgHiJkzzzzzzzzzzzzzz"; - text[10][3]="zzzaBcDeFgHiJkzzzzzzzzzzzzz"; - text[10][4]="zzzzaBcDeFgHiJkzzzzzzzzzzzz"; - text[10][5]="zzzzzaBcDeFgHiJkzzzzzzzzzzz"; - text[10][6]="zzzzzzaBcDeFgHiJkzzzzzzzzzz"; - text[10][7]="zzzzzzzaBcDeFgHiJkzzzzzzzzz"; - text[10][8]="zzzzzzzzaBcDeFgHiJkzzzzzzzz"; - text[10][9]="zzzzzzzzzaBcDeFgHiJkzzzzzzz"; - text[10][10]="zzzzzzzzzzaBcDeFgHiJkzzzzzz"; - text[10][11]="zzzzzzzzzzzaBcDeFgHiJkzzzzz"; - text[10][12]="zzzzzzzzzzzzaBcDeFgHiJkzzzz"; - text[10][13]="zzzzzzzzzzzzzaBcDeFgHiJkzzz"; - text[10][14]="zzzzzzzzzzzzzzaBcDeFgHiJkzz"; - text[10][15]="zzzzzzzzzzzzzzzaBcDeFgHiJkz"; - text[10][16]="zzzzzzzzzzzzzzzzaBcDeFgHiJk"; - text[11][0]="aBcDeFgHiJkLzzzzzzzzzzzzzzz"; - text[11][1]="zaBcDeFgHiJkLzzzzzzzzzzzzzz"; - text[11][2]="zzaBcDeFgHiJkLzzzzzzzzzzzzz"; - text[11][3]="zzzaBcDeFgHiJkLzzzzzzzzzzzz"; - text[11][4]="zzzzaBcDeFgHiJkLzzzzzzzzzzz"; - text[11][5]="zzzzzaBcDeFgHiJkLzzzzzzzzzz"; - text[11][6]="zzzzzzaBcDeFgHiJkLzzzzzzzzz"; - text[11][7]="zzzzzzzaBcDeFgHiJkLzzzzzzzz"; - text[11][8]="zzzzzzzzaBcDeFgHiJkLzzzzzzz"; - text[11][9]="zzzzzzzzzaBcDeFgHiJkLzzzzzz"; - text[11][10]="zzzzzzzzzzaBcDeFgHiJkLzzzzz"; - text[11][11]="zzzzzzzzzzzaBcDeFgHiJkLzzzz"; - text[11][12]="zzzzzzzzzzzzaBcDeFgHiJkLzzz"; - text[11][13]="zzzzzzzzzzzzzaBcDeFgHiJkLzz"; - text[11][14]="zzzzzzzzzzzzzzaBcDeFgHiJkLz"; - text[11][15]="zzzzzzzzzzzzzzzaBcDeFgHiJkL"; - text[12][0]="aBcDeFgHiJkLmzzzzzzzzzzzzzz"; - text[12][1]="zaBcDeFgHiJkLmzzzzzzzzzzzzz"; - text[12][2]="zzaBcDeFgHiJkLmzzzzzzzzzzzz"; - text[12][3]="zzzaBcDeFgHiJkLmzzzzzzzzzzz"; - text[12][4]="zzzzaBcDeFgHiJkLmzzzzzzzzzz"; - text[12][5]="zzzzzaBcDeFgHiJkLmzzzzzzzzz"; - text[12][6]="zzzzzzaBcDeFgHiJkLmzzzzzzzz"; - text[12][7]="zzzzzzzaBcDeFgHiJkLmzzzzzzz"; - text[12][8]="zzzzzzzzaBcDeFgHiJkLmzzzzzz"; - text[12][9]="zzzzzzzzzaBcDeFgHiJkLmzzzzz"; - text[12][10]="zzzzzzzzzzaBcDeFgHiJkLmzzzz"; - text[12][11]="zzzzzzzzzzzaBcDeFgHiJkLmzzz"; - text[12][12]="zzzzzzzzzzzzaBcDeFgHiJkLmzz"; - text[12][13]="zzzzzzzzzzzzzaBcDeFgHiJkLmz"; - text[12][14]="zzzzzzzzzzzzzzaBcDeFgHiJkLm"; - text[13][0]="aBcDeFgHiJkLmNzzzzzzzzzzzzz"; - text[13][1]="zaBcDeFgHiJkLmNzzzzzzzzzzzz"; - text[13][2]="zzaBcDeFgHiJkLmNzzzzzzzzzzz"; - text[13][3]="zzzaBcDeFgHiJkLmNzzzzzzzzzz"; - text[13][4]="zzzzaBcDeFgHiJkLmNzzzzzzzzz"; - text[13][5]="zzzzzaBcDeFgHiJkLmNzzzzzzzz"; - text[13][6]="zzzzzzaBcDeFgHiJkLmNzzzzzzz"; - text[13][7]="zzzzzzzaBcDeFgHiJkLmNzzzzzz"; - text[13][8]="zzzzzzzzaBcDeFgHiJkLmNzzzzz"; - text[13][9]="zzzzzzzzzaBcDeFgHiJkLmNzzzz"; - text[13][10]="zzzzzzzzzzaBcDeFgHiJkLmNzzz"; - text[13][11]="zzzzzzzzzzzaBcDeFgHiJkLmNzz"; - text[13][12]="zzzzzzzzzzzzaBcDeFgHiJkLmNz"; - text[13][13]="zzzzzzzzzzzzzaBcDeFgHiJkLmN"; - text[14][0]="aBcDeFgHiJkLmNozzzzzzzzzzzz"; - text[14][1]="zaBcDeFgHiJkLmNozzzzzzzzzzz"; - text[14][2]="zzaBcDeFgHiJkLmNozzzzzzzzzz"; - text[14][3]="zzzaBcDeFgHiJkLmNozzzzzzzzz"; - text[14][4]="zzzzaBcDeFgHiJkLmNozzzzzzzz"; - text[14][5]="zzzzzaBcDeFgHiJkLmNozzzzzzz"; - text[14][6]="zzzzzzaBcDeFgHiJkLmNozzzzzz"; - text[14][7]="zzzzzzzaBcDeFgHiJkLmNozzzzz"; - text[14][8]="zzzzzzzzaBcDeFgHiJkLmNozzzz"; - text[14][9]="zzzzzzzzzaBcDeFgHiJkLmNozzz"; - text[14][10]="zzzzzzzzzzaBcDeFgHiJkLmNozz"; - text[14][11]="zzzzzzzzzzzaBcDeFgHiJkLmNoz"; - text[14][12]="zzzzzzzzzzzzaBcDeFgHiJkLmNo"; - text[15][0]="aBcDeFgHiJkLmNoPzzzzzzzzzzz"; - text[15][1]="zaBcDeFgHiJkLmNoPzzzzzzzzzz"; - text[15][2]="zzaBcDeFgHiJkLmNoPzzzzzzzzz"; - text[15][3]="zzzaBcDeFgHiJkLmNoPzzzzzzzz"; - text[15][4]="zzzzaBcDeFgHiJkLmNoPzzzzzzz"; - text[15][5]="zzzzzaBcDeFgHiJkLmNoPzzzzzz"; - text[15][6]="zzzzzzaBcDeFgHiJkLmNoPzzzzz"; - text[15][7]="zzzzzzzaBcDeFgHiJkLmNoPzzzz"; - text[15][8]="zzzzzzzzaBcDeFgHiJkLmNoPzzz"; - text[15][9]="zzzzzzzzzaBcDeFgHiJkLmNoPzz"; - text[15][10]="zzzzzzzzzzaBcDeFgHiJkLmNoPz"; - text[15][11]="zzzzzzzzzzzaBcDeFgHiJkLmNoP"; - text[16][0]="aBcDeFgHiJkLmNoPqzzzzzzzzzz"; - text[16][1]="zaBcDeFgHiJkLmNoPqzzzzzzzzz"; - text[16][2]="zzaBcDeFgHiJkLmNoPqzzzzzzzz"; - text[16][3]="zzzaBcDeFgHiJkLmNoPqzzzzzzz"; - text[16][4]="zzzzaBcDeFgHiJkLmNoPqzzzzzz"; - text[16][5]="zzzzzaBcDeFgHiJkLmNoPqzzzzz"; - text[16][6]="zzzzzzaBcDeFgHiJkLmNoPqzzzz"; - text[16][7]="zzzzzzzaBcDeFgHiJkLmNoPqzzz"; - text[16][8]="zzzzzzzzaBcDeFgHiJkLmNoPqzz"; - text[16][9]="zzzzzzzzzaBcDeFgHiJkLmNoPqz"; - text[16][10]="zzzzzzzzzzaBcDeFgHiJkLmNoPq"; - text[17][0]="aBcDeFgHiJkLmNoPqRzzzzzzzzz"; - text[17][1]="zaBcDeFgHiJkLmNoPqRzzzzzzzz"; - text[17][2]="zzaBcDeFgHiJkLmNoPqRzzzzzzz"; - text[17][3]="zzzaBcDeFgHiJkLmNoPqRzzzzzz"; - text[17][4]="zzzzaBcDeFgHiJkLmNoPqRzzzzz"; - text[17][5]="zzzzzaBcDeFgHiJkLmNoPqRzzzz"; - text[17][6]="zzzzzzaBcDeFgHiJkLmNoPqRzzz"; - text[17][7]="zzzzzzzaBcDeFgHiJkLmNoPqRzz"; - text[17][8]="zzzzzzzzaBcDeFgHiJkLmNoPqRz"; - text[17][9]="zzzzzzzzzaBcDeFgHiJkLmNoPqR"; - text[18][0]="aBcDeFgHiJkLmNoPqRszzzzzzzz"; - text[18][1]="zaBcDeFgHiJkLmNoPqRszzzzzzz"; - text[18][2]="zzaBcDeFgHiJkLmNoPqRszzzzzz"; - text[18][3]="zzzaBcDeFgHiJkLmNoPqRszzzzz"; - text[18][4]="zzzzaBcDeFgHiJkLmNoPqRszzzz"; - text[18][5]="zzzzzaBcDeFgHiJkLmNoPqRszzz"; - text[18][6]="zzzzzzaBcDeFgHiJkLmNoPqRszz"; - text[18][7]="zzzzzzzaBcDeFgHiJkLmNoPqRsz"; - text[18][8]="zzzzzzzzaBcDeFgHiJkLmNoPqRs"; - text[19][0]="aBcDeFgHiJkLmNoPqRsTzzzzzzz"; - text[19][1]="zaBcDeFgHiJkLmNoPqRsTzzzzzz"; - text[19][2]="zzaBcDeFgHiJkLmNoPqRsTzzzzz"; - text[19][3]="zzzaBcDeFgHiJkLmNoPqRsTzzzz"; - text[19][4]="zzzzaBcDeFgHiJkLmNoPqRsTzzz"; - text[19][5]="zzzzzaBcDeFgHiJkLmNoPqRsTzz"; - text[19][6]="zzzzzzaBcDeFgHiJkLmNoPqRsTz"; - text[19][7]="zzzzzzzaBcDeFgHiJkLmNoPqRsT"; - text[20][0]="aBcDeFgHiJkLmNoPqRsTuzzzzzz"; - text[20][1]="zaBcDeFgHiJkLmNoPqRsTuzzzzz"; - text[20][2]="zzaBcDeFgHiJkLmNoPqRsTuzzzz"; - text[20][3]="zzzaBcDeFgHiJkLmNoPqRsTuzzz"; - text[20][4]="zzzzaBcDeFgHiJkLmNoPqRsTuzz"; - text[20][5]="zzzzzaBcDeFgHiJkLmNoPqRsTuz"; - text[20][6]="zzzzzzaBcDeFgHiJkLmNoPqRsTu"; - text[21][0]="aBcDeFgHiJkLmNoPqRsTuVzzzzz"; - text[21][1]="zaBcDeFgHiJkLmNoPqRsTuVzzzz"; - text[21][2]="zzaBcDeFgHiJkLmNoPqRsTuVzzz"; - text[21][3]="zzzaBcDeFgHiJkLmNoPqRsTuVzz"; - text[21][4]="zzzzaBcDeFgHiJkLmNoPqRsTuVz"; - text[21][5]="zzzzzaBcDeFgHiJkLmNoPqRsTuV"; - text[22][0]="aBcDeFgHiJkLmNoPqRsTuVwzzzz"; - text[22][1]="zaBcDeFgHiJkLmNoPqRsTuVwzzz"; - text[22][2]="zzaBcDeFgHiJkLmNoPqRsTuVwzz"; - text[22][3]="zzzaBcDeFgHiJkLmNoPqRsTuVwz"; - text[22][4]="zzzzaBcDeFgHiJkLmNoPqRsTuVw"; - text[23][0]="aBcDeFgHiJkLmNoPqRsTuVwXzzz"; - text[23][1]="zaBcDeFgHiJkLmNoPqRsTuVwXzz"; - text[23][2]="zzaBcDeFgHiJkLmNoPqRsTuVwXz"; - text[23][3]="zzzaBcDeFgHiJkLmNoPqRsTuVwX"; - text[24][0]="aBcDeFgHiJkLmNoPqRsTuVwXyzz"; - text[24][1]="zaBcDeFgHiJkLmNoPqRsTuVwXyz"; - text[24][2]="zzaBcDeFgHiJkLmNoPqRsTuVwXy"; - text[25][0]="aBcDeFgHiJkLmNoPqRsTuVwXyZz"; - text[25][1]="zaBcDeFgHiJkLmNoPqRsTuVwXyZ"; + text[0][0] = "azzzzzzzzzzzzzzzzzzzzzzzzzz"; + text[0][1] = "zazzzzzzzzzzzzzzzzzzzzzzzzz"; + text[0][2] = "zzazzzzzzzzzzzzzzzzzzzzzzzz"; + text[0][3] = "zzzazzzzzzzzzzzzzzzzzzzzzzz"; + text[0][4] = "zzzzazzzzzzzzzzzzzzzzzzzzzz"; + text[0][5] = "zzzzzazzzzzzzzzzzzzzzzzzzzz"; + text[0][6] = "zzzzzzazzzzzzzzzzzzzzzzzzzz"; + text[0][7] = "zzzzzzzazzzzzzzzzzzzzzzzzzz"; + text[0][8] = "zzzzzzzzazzzzzzzzzzzzzzzzzz"; + text[0][9] = "zzzzzzzzzazzzzzzzzzzzzzzzzz"; + text[0][10] = "zzzzzzzzzzazzzzzzzzzzzzzzzz"; + text[0][11] = "zzzzzzzzzzzazzzzzzzzzzzzzzz"; + text[0][12] = "zzzzzzzzzzzzazzzzzzzzzzzzzz"; + text[0][13] = "zzzzzzzzzzzzzazzzzzzzzzzzzz"; + text[0][14] = "zzzzzzzzzzzzzzazzzzzzzzzzzz"; + text[0][15] = "zzzzzzzzzzzzzzzazzzzzzzzzzz"; + text[0][16] = "zzzzzzzzzzzzzzzzazzzzzzzzzz"; + text[0][17] = "zzzzzzzzzzzzzzzzzazzzzzzzzz"; + text[0][18] = "zzzzzzzzzzzzzzzzzzazzzzzzzz"; + text[0][19] = "zzzzzzzzzzzzzzzzzzzazzzzzzz"; + text[0][20] = "zzzzzzzzzzzzzzzzzzzzazzzzzz"; + text[0][21] = "zzzzzzzzzzzzzzzzzzzzzazzzzz"; + text[0][22] = "zzzzzzzzzzzzzzzzzzzzzzazzzz"; + text[0][23] = "zzzzzzzzzzzzzzzzzzzzzzzazzz"; + text[0][24] = "zzzzzzzzzzzzzzzzzzzzzzzzazz"; + text[0][25] = "zzzzzzzzzzzzzzzzzzzzzzzzzaz"; + text[0][26] = "zzzzzzzzzzzzzzzzzzzzzzzzzza"; + text[1][0] = "aBzzzzzzzzzzzzzzzzzzzzzzzzz"; + text[1][1] = "zaBzzzzzzzzzzzzzzzzzzzzzzzz"; + text[1][2] = "zzaBzzzzzzzzzzzzzzzzzzzzzzz"; + text[1][3] = "zzzaBzzzzzzzzzzzzzzzzzzzzzz"; + text[1][4] = "zzzzaBzzzzzzzzzzzzzzzzzzzzz"; + text[1][5] = "zzzzzaBzzzzzzzzzzzzzzzzzzzz"; + text[1][6] = "zzzzzzaBzzzzzzzzzzzzzzzzzzz"; + text[1][7] = "zzzzzzzaBzzzzzzzzzzzzzzzzzz"; + text[1][8] = "zzzzzzzzaBzzzzzzzzzzzzzzzzz"; + text[1][9] = "zzzzzzzzzaBzzzzzzzzzzzzzzzz"; + text[1][10] = "zzzzzzzzzzaBzzzzzzzzzzzzzzz"; + text[1][11] = "zzzzzzzzzzzaBzzzzzzzzzzzzzz"; + text[1][12] = "zzzzzzzzzzzzaBzzzzzzzzzzzzz"; + text[1][13] = "zzzzzzzzzzzzzaBzzzzzzzzzzzz"; + text[1][14] = "zzzzzzzzzzzzzzaBzzzzzzzzzzz"; + text[1][15] = "zzzzzzzzzzzzzzzaBzzzzzzzzzz"; + text[1][16] = "zzzzzzzzzzzzzzzzaBzzzzzzzzz"; + text[1][17] = "zzzzzzzzzzzzzzzzzaBzzzzzzzz"; + text[1][18] = "zzzzzzzzzzzzzzzzzzaBzzzzzzz"; + text[1][19] = "zzzzzzzzzzzzzzzzzzzaBzzzzzz"; + text[1][20] = "zzzzzzzzzzzzzzzzzzzzaBzzzzz"; + text[1][21] = "zzzzzzzzzzzzzzzzzzzzzaBzzzz"; + text[1][22] = "zzzzzzzzzzzzzzzzzzzzzzaBzzz"; + text[1][23] = "zzzzzzzzzzzzzzzzzzzzzzzaBzz"; + text[1][24] = "zzzzzzzzzzzzzzzzzzzzzzzzaBz"; + text[1][25] = "zzzzzzzzzzzzzzzzzzzzzzzzzaB"; + text[2][0] = "aBczzzzzzzzzzzzzzzzzzzzzzzz"; + text[2][1] = "zaBczzzzzzzzzzzzzzzzzzzzzzz"; + text[2][2] = "zzaBczzzzzzzzzzzzzzzzzzzzzz"; + text[2][3] = "zzzaBczzzzzzzzzzzzzzzzzzzzz"; + text[2][4] = "zzzzaBczzzzzzzzzzzzzzzzzzzz"; + text[2][5] = "zzzzzaBczzzzzzzzzzzzzzzzzzz"; + text[2][6] = "zzzzzzaBczzzzzzzzzzzzzzzzzz"; + text[2][7] = "zzzzzzzaBczzzzzzzzzzzzzzzzz"; + text[2][8] = "zzzzzzzzaBczzzzzzzzzzzzzzzz"; + text[2][9] = "zzzzzzzzzaBczzzzzzzzzzzzzzz"; + text[2][10] = "zzzzzzzzzzaBczzzzzzzzzzzzzz"; + text[2][11] = "zzzzzzzzzzzaBczzzzzzzzzzzzz"; + text[2][12] = "zzzzzzzzzzzzaBczzzzzzzzzzzz"; + text[2][13] = "zzzzzzzzzzzzzaBczzzzzzzzzzz"; + text[2][14] = "zzzzzzzzzzzzzzaBczzzzzzzzzz"; + text[2][15] = "zzzzzzzzzzzzzzzaBczzzzzzzzz"; + text[2][16] = "zzzzzzzzzzzzzzzzaBczzzzzzzz"; + text[2][17] = "zzzzzzzzzzzzzzzzzaBczzzzzzz"; + text[2][18] = "zzzzzzzzzzzzzzzzzzaBczzzzzz"; + text[2][19] = "zzzzzzzzzzzzzzzzzzzaBczzzzz"; + text[2][20] = "zzzzzzzzzzzzzzzzzzzzaBczzzz"; + text[2][21] = "zzzzzzzzzzzzzzzzzzzzzaBczzz"; + text[2][22] = "zzzzzzzzzzzzzzzzzzzzzzaBczz"; + text[2][23] = "zzzzzzzzzzzzzzzzzzzzzzzaBcz"; + text[2][24] = "zzzzzzzzzzzzzzzzzzzzzzzzaBc"; + text[3][0] = "aBcDzzzzzzzzzzzzzzzzzzzzzzz"; + text[3][1] = "zaBcDzzzzzzzzzzzzzzzzzzzzzz"; + text[3][2] = "zzaBcDzzzzzzzzzzzzzzzzzzzzz"; + text[3][3] = "zzzaBcDzzzzzzzzzzzzzzzzzzzz"; + text[3][4] = "zzzzaBcDzzzzzzzzzzzzzzzzzzz"; + text[3][5] = "zzzzzaBcDzzzzzzzzzzzzzzzzzz"; + text[3][6] = "zzzzzzaBcDzzzzzzzzzzzzzzzzz"; + text[3][7] = "zzzzzzzaBcDzzzzzzzzzzzzzzzz"; + text[3][8] = "zzzzzzzzaBcDzzzzzzzzzzzzzzz"; + text[3][9] = "zzzzzzzzzaBcDzzzzzzzzzzzzzz"; + text[3][10] = "zzzzzzzzzzaBcDzzzzzzzzzzzzz"; + text[3][11] = "zzzzzzzzzzzaBcDzzzzzzzzzzzz"; + text[3][12] = "zzzzzzzzzzzzaBcDzzzzzzzzzzz"; + text[3][13] = "zzzzzzzzzzzzzaBcDzzzzzzzzzz"; + text[3][14] = "zzzzzzzzzzzzzzaBcDzzzzzzzzz"; + text[3][15] = "zzzzzzzzzzzzzzzaBcDzzzzzzzz"; + text[3][16] = "zzzzzzzzzzzzzzzzaBcDzzzzzzz"; + text[3][17] = "zzzzzzzzzzzzzzzzzaBcDzzzzzz"; + text[3][18] = "zzzzzzzzzzzzzzzzzzaBcDzzzzz"; + text[3][19] = "zzzzzzzzzzzzzzzzzzzaBcDzzzz"; + text[3][20] = "zzzzzzzzzzzzzzzzzzzzaBcDzzz"; + text[3][21] = "zzzzzzzzzzzzzzzzzzzzzaBcDzz"; + text[3][22] = "zzzzzzzzzzzzzzzzzzzzzzaBcDz"; + text[3][23] = "zzzzzzzzzzzzzzzzzzzzzzzaBcD"; + text[4][0] = "aBcDezzzzzzzzzzzzzzzzzzzzzz"; + text[4][1] = "zaBcDezzzzzzzzzzzzzzzzzzzzz"; + text[4][2] = "zzaBcDezzzzzzzzzzzzzzzzzzzz"; + text[4][3] = "zzzaBcDezzzzzzzzzzzzzzzzzzz"; + text[4][4] = "zzzzaBcDezzzzzzzzzzzzzzzzzz"; + text[4][5] = "zzzzzaBcDezzzzzzzzzzzzzzzzz"; + text[4][6] = "zzzzzzaBcDezzzzzzzzzzzzzzzz"; + text[4][7] = "zzzzzzzaBcDezzzzzzzzzzzzzzz"; + text[4][8] = "zzzzzzzzaBcDezzzzzzzzzzzzzz"; + text[4][9] = "zzzzzzzzzaBcDezzzzzzzzzzzzz"; + text[4][10] = "zzzzzzzzzzaBcDezzzzzzzzzzzz"; + text[4][11] = "zzzzzzzzzzzaBcDezzzzzzzzzzz"; + text[4][12] = "zzzzzzzzzzzzaBcDezzzzzzzzzz"; + text[4][13] = "zzzzzzzzzzzzzaBcDezzzzzzzzz"; + text[4][14] = "zzzzzzzzzzzzzzaBcDezzzzzzzz"; + text[4][15] = "zzzzzzzzzzzzzzzaBcDezzzzzzz"; + text[4][16] = "zzzzzzzzzzzzzzzzaBcDezzzzzz"; + text[4][17] = "zzzzzzzzzzzzzzzzzaBcDezzzzz"; + text[4][18] = "zzzzzzzzzzzzzzzzzzaBcDezzzz"; + text[4][19] = "zzzzzzzzzzzzzzzzzzzaBcDezzz"; + text[4][20] = "zzzzzzzzzzzzzzzzzzzzaBcDezz"; + text[4][21] = "zzzzzzzzzzzzzzzzzzzzzaBcDez"; + text[4][22] = "zzzzzzzzzzzzzzzzzzzzzzaBcDe"; + text[5][0] = "aBcDeFzzzzzzzzzzzzzzzzzzzzz"; + text[5][1] = "zaBcDeFzzzzzzzzzzzzzzzzzzzz"; + text[5][2] = "zzaBcDeFzzzzzzzzzzzzzzzzzzz"; + text[5][3] = "zzzaBcDeFzzzzzzzzzzzzzzzzzz"; + text[5][4] = "zzzzaBcDeFzzzzzzzzzzzzzzzzz"; + text[5][5] = "zzzzzaBcDeFzzzzzzzzzzzzzzzz"; + text[5][6] = "zzzzzzaBcDeFzzzzzzzzzzzzzzz"; + text[5][7] = "zzzzzzzaBcDeFzzzzzzzzzzzzzz"; + text[5][8] = "zzzzzzzzaBcDeFzzzzzzzzzzzzz"; + text[5][9] = "zzzzzzzzzaBcDeFzzzzzzzzzzzz"; + text[5][10] = "zzzzzzzzzzaBcDeFzzzzzzzzzzz"; + text[5][11] = "zzzzzzzzzzzaBcDeFzzzzzzzzzz"; + text[5][12] = "zzzzzzzzzzzzaBcDeFzzzzzzzzz"; + text[5][13] = "zzzzzzzzzzzzzaBcDeFzzzzzzzz"; + text[5][14] = "zzzzzzzzzzzzzzaBcDeFzzzzzzz"; + text[5][15] = "zzzzzzzzzzzzzzzaBcDeFzzzzzz"; + text[5][16] = "zzzzzzzzzzzzzzzzaBcDeFzzzzz"; + text[5][17] = "zzzzzzzzzzzzzzzzzaBcDeFzzzz"; + text[5][18] = "zzzzzzzzzzzzzzzzzzaBcDeFzzz"; + text[5][19] = "zzzzzzzzzzzzzzzzzzzaBcDeFzz"; + text[5][20] = "zzzzzzzzzzzzzzzzzzzzaBcDeFz"; + text[5][21] = "zzzzzzzzzzzzzzzzzzzzzaBcDeF"; + text[6][0] = "aBcDeFgzzzzzzzzzzzzzzzzzzzz"; + text[6][1] = "zaBcDeFgzzzzzzzzzzzzzzzzzzz"; + text[6][2] = "zzaBcDeFgzzzzzzzzzzzzzzzzzz"; + text[6][3] = "zzzaBcDeFgzzzzzzzzzzzzzzzzz"; + text[6][4] = "zzzzaBcDeFgzzzzzzzzzzzzzzzz"; + text[6][5] = "zzzzzaBcDeFgzzzzzzzzzzzzzzz"; + text[6][6] = "zzzzzzaBcDeFgzzzzzzzzzzzzzz"; + text[6][7] = "zzzzzzzaBcDeFgzzzzzzzzzzzzz"; + text[6][8] = "zzzzzzzzaBcDeFgzzzzzzzzzzzz"; + text[6][9] = "zzzzzzzzzaBcDeFgzzzzzzzzzzz"; + text[6][10] = "zzzzzzzzzzaBcDeFgzzzzzzzzzz"; + text[6][11] = "zzzzzzzzzzzaBcDeFgzzzzzzzzz"; + text[6][12] = "zzzzzzzzzzzzaBcDeFgzzzzzzzz"; + text[6][13] = "zzzzzzzzzzzzzaBcDeFgzzzzzzz"; + text[6][14] = "zzzzzzzzzzzzzzaBcDeFgzzzzzz"; + text[6][15] = "zzzzzzzzzzzzzzzaBcDeFgzzzzz"; + text[6][16] = "zzzzzzzzzzzzzzzzaBcDeFgzzzz"; + text[6][17] = "zzzzzzzzzzzzzzzzzaBcDeFgzzz"; + text[6][18] = "zzzzzzzzzzzzzzzzzzaBcDeFgzz"; + text[6][19] = "zzzzzzzzzzzzzzzzzzzaBcDeFgz"; + text[6][20] = "zzzzzzzzzzzzzzzzzzzzaBcDeFg"; + text[7][0] = "aBcDeFgHzzzzzzzzzzzzzzzzzzz"; + text[7][1] = "zaBcDeFgHzzzzzzzzzzzzzzzzzz"; + text[7][2] = "zzaBcDeFgHzzzzzzzzzzzzzzzzz"; + text[7][3] = "zzzaBcDeFgHzzzzzzzzzzzzzzzz"; + text[7][4] = "zzzzaBcDeFgHzzzzzzzzzzzzzzz"; + text[7][5] = "zzzzzaBcDeFgHzzzzzzzzzzzzzz"; + text[7][6] = "zzzzzzaBcDeFgHzzzzzzzzzzzzz"; + text[7][7] = "zzzzzzzaBcDeFgHzzzzzzzzzzzz"; + text[7][8] = "zzzzzzzzaBcDeFgHzzzzzzzzzzz"; + text[7][9] = "zzzzzzzzzaBcDeFgHzzzzzzzzzz"; + text[7][10] = "zzzzzzzzzzaBcDeFgHzzzzzzzzz"; + text[7][11] = "zzzzzzzzzzzaBcDeFgHzzzzzzzz"; + text[7][12] = "zzzzzzzzzzzzaBcDeFgHzzzzzzz"; + text[7][13] = "zzzzzzzzzzzzzaBcDeFgHzzzzzz"; + text[7][14] = "zzzzzzzzzzzzzzaBcDeFgHzzzzz"; + text[7][15] = "zzzzzzzzzzzzzzzaBcDeFgHzzzz"; + text[7][16] = "zzzzzzzzzzzzzzzzaBcDeFgHzzz"; + text[7][17] = "zzzzzzzzzzzzzzzzzaBcDeFgHzz"; + text[7][18] = "zzzzzzzzzzzzzzzzzzaBcDeFgHz"; + text[7][19] = "zzzzzzzzzzzzzzzzzzzaBcDeFgH"; + text[8][0] = "aBcDeFgHizzzzzzzzzzzzzzzzzz"; + text[8][1] = "zaBcDeFgHizzzzzzzzzzzzzzzzz"; + text[8][2] = "zzaBcDeFgHizzzzzzzzzzzzzzzz"; + text[8][3] = "zzzaBcDeFgHizzzzzzzzzzzzzzz"; + text[8][4] = "zzzzaBcDeFgHizzzzzzzzzzzzzz"; + text[8][5] = "zzzzzaBcDeFgHizzzzzzzzzzzzz"; + text[8][6] = "zzzzzzaBcDeFgHizzzzzzzzzzzz"; + text[8][7] = "zzzzzzzaBcDeFgHizzzzzzzzzzz"; + text[8][8] = "zzzzzzzzaBcDeFgHizzzzzzzzzz"; + text[8][9] = "zzzzzzzzzaBcDeFgHizzzzzzzzz"; + text[8][10] = "zzzzzzzzzzaBcDeFgHizzzzzzzz"; + text[8][11] = "zzzzzzzzzzzaBcDeFgHizzzzzzz"; + text[8][12] = "zzzzzzzzzzzzaBcDeFgHizzzzzz"; + text[8][13] = "zzzzzzzzzzzzzaBcDeFgHizzzzz"; + text[8][14] = "zzzzzzzzzzzzzzaBcDeFgHizzzz"; + text[8][15] = "zzzzzzzzzzzzzzzaBcDeFgHizzz"; + text[8][16] = "zzzzzzzzzzzzzzzzaBcDeFgHizz"; + text[8][17] = "zzzzzzzzzzzzzzzzzaBcDeFgHiz"; + text[8][18] = "zzzzzzzzzzzzzzzzzzaBcDeFgHi"; + text[9][0] = "aBcDeFgHiJzzzzzzzzzzzzzzzzz"; + text[9][1] = "zaBcDeFgHiJzzzzzzzzzzzzzzzz"; + text[9][2] = "zzaBcDeFgHiJzzzzzzzzzzzzzzz"; + text[9][3] = "zzzaBcDeFgHiJzzzzzzzzzzzzzz"; + text[9][4] = "zzzzaBcDeFgHiJzzzzzzzzzzzzz"; + text[9][5] = "zzzzzaBcDeFgHiJzzzzzzzzzzzz"; + text[9][6] = "zzzzzzaBcDeFgHiJzzzzzzzzzzz"; + text[9][7] = "zzzzzzzaBcDeFgHiJzzzzzzzzzz"; + text[9][8] = "zzzzzzzzaBcDeFgHiJzzzzzzzzz"; + text[9][9] = "zzzzzzzzzaBcDeFgHiJzzzzzzzz"; + text[9][10] = "zzzzzzzzzzaBcDeFgHiJzzzzzzz"; + text[9][11] = "zzzzzzzzzzzaBcDeFgHiJzzzzzz"; + text[9][12] = "zzzzzzzzzzzzaBcDeFgHiJzzzzz"; + text[9][13] = "zzzzzzzzzzzzzaBcDeFgHiJzzzz"; + text[9][14] = "zzzzzzzzzzzzzzaBcDeFgHiJzzz"; + text[9][15] = "zzzzzzzzzzzzzzzaBcDeFgHiJzz"; + text[9][16] = "zzzzzzzzzzzzzzzzaBcDeFgHiJz"; + text[9][17] = "zzzzzzzzzzzzzzzzzaBcDeFgHiJ"; + text[10][0] = "aBcDeFgHiJkzzzzzzzzzzzzzzzz"; + text[10][1] = "zaBcDeFgHiJkzzzzzzzzzzzzzzz"; + text[10][2] = "zzaBcDeFgHiJkzzzzzzzzzzzzzz"; + text[10][3] = "zzzaBcDeFgHiJkzzzzzzzzzzzzz"; + text[10][4] = "zzzzaBcDeFgHiJkzzzzzzzzzzzz"; + text[10][5] = "zzzzzaBcDeFgHiJkzzzzzzzzzzz"; + text[10][6] = "zzzzzzaBcDeFgHiJkzzzzzzzzzz"; + text[10][7] = "zzzzzzzaBcDeFgHiJkzzzzzzzzz"; + text[10][8] = "zzzzzzzzaBcDeFgHiJkzzzzzzzz"; + text[10][9] = "zzzzzzzzzaBcDeFgHiJkzzzzzzz"; + text[10][10] = "zzzzzzzzzzaBcDeFgHiJkzzzzzz"; + text[10][11] = "zzzzzzzzzzzaBcDeFgHiJkzzzzz"; + text[10][12] = "zzzzzzzzzzzzaBcDeFgHiJkzzzz"; + text[10][13] = "zzzzzzzzzzzzzaBcDeFgHiJkzzz"; + text[10][14] = "zzzzzzzzzzzzzzaBcDeFgHiJkzz"; + text[10][15] = "zzzzzzzzzzzzzzzaBcDeFgHiJkz"; + text[10][16] = "zzzzzzzzzzzzzzzzaBcDeFgHiJk"; + text[11][0] = "aBcDeFgHiJkLzzzzzzzzzzzzzzz"; + text[11][1] = "zaBcDeFgHiJkLzzzzzzzzzzzzzz"; + text[11][2] = "zzaBcDeFgHiJkLzzzzzzzzzzzzz"; + text[11][3] = "zzzaBcDeFgHiJkLzzzzzzzzzzzz"; + text[11][4] = "zzzzaBcDeFgHiJkLzzzzzzzzzzz"; + text[11][5] = "zzzzzaBcDeFgHiJkLzzzzzzzzzz"; + text[11][6] = "zzzzzzaBcDeFgHiJkLzzzzzzzzz"; + text[11][7] = "zzzzzzzaBcDeFgHiJkLzzzzzzzz"; + text[11][8] = "zzzzzzzzaBcDeFgHiJkLzzzzzzz"; + text[11][9] = "zzzzzzzzzaBcDeFgHiJkLzzzzzz"; + text[11][10] = "zzzzzzzzzzaBcDeFgHiJkLzzzzz"; + text[11][11] = "zzzzzzzzzzzaBcDeFgHiJkLzzzz"; + text[11][12] = "zzzzzzzzzzzzaBcDeFgHiJkLzzz"; + text[11][13] = "zzzzzzzzzzzzzaBcDeFgHiJkLzz"; + text[11][14] = "zzzzzzzzzzzzzzaBcDeFgHiJkLz"; + text[11][15] = "zzzzzzzzzzzzzzzaBcDeFgHiJkL"; + text[12][0] = "aBcDeFgHiJkLmzzzzzzzzzzzzzz"; + text[12][1] = "zaBcDeFgHiJkLmzzzzzzzzzzzzz"; + text[12][2] = "zzaBcDeFgHiJkLmzzzzzzzzzzzz"; + text[12][3] = "zzzaBcDeFgHiJkLmzzzzzzzzzzz"; + text[12][4] = "zzzzaBcDeFgHiJkLmzzzzzzzzzz"; + text[12][5] = "zzzzzaBcDeFgHiJkLmzzzzzzzzz"; + text[12][6] = "zzzzzzaBcDeFgHiJkLmzzzzzzzz"; + text[12][7] = "zzzzzzzaBcDeFgHiJkLmzzzzzzz"; + text[12][8] = "zzzzzzzzaBcDeFgHiJkLmzzzzzz"; + text[12][9] = "zzzzzzzzzaBcDeFgHiJkLmzzzzz"; + text[12][10] = "zzzzzzzzzzaBcDeFgHiJkLmzzzz"; + text[12][11] = "zzzzzzzzzzzaBcDeFgHiJkLmzzz"; + text[12][12] = "zzzzzzzzzzzzaBcDeFgHiJkLmzz"; + text[12][13] = "zzzzzzzzzzzzzaBcDeFgHiJkLmz"; + text[12][14] = "zzzzzzzzzzzzzzaBcDeFgHiJkLm"; + text[13][0] = "aBcDeFgHiJkLmNzzzzzzzzzzzzz"; + text[13][1] = "zaBcDeFgHiJkLmNzzzzzzzzzzzz"; + text[13][2] = "zzaBcDeFgHiJkLmNzzzzzzzzzzz"; + text[13][3] = "zzzaBcDeFgHiJkLmNzzzzzzzzzz"; + text[13][4] = "zzzzaBcDeFgHiJkLmNzzzzzzzzz"; + text[13][5] = "zzzzzaBcDeFgHiJkLmNzzzzzzzz"; + text[13][6] = "zzzzzzaBcDeFgHiJkLmNzzzzzzz"; + text[13][7] = "zzzzzzzaBcDeFgHiJkLmNzzzzzz"; + text[13][8] = "zzzzzzzzaBcDeFgHiJkLmNzzzzz"; + text[13][9] = "zzzzzzzzzaBcDeFgHiJkLmNzzzz"; + text[13][10] = "zzzzzzzzzzaBcDeFgHiJkLmNzzz"; + text[13][11] = "zzzzzzzzzzzaBcDeFgHiJkLmNzz"; + text[13][12] = "zzzzzzzzzzzzaBcDeFgHiJkLmNz"; + text[13][13] = "zzzzzzzzzzzzzaBcDeFgHiJkLmN"; + text[14][0] = "aBcDeFgHiJkLmNozzzzzzzzzzzz"; + text[14][1] = "zaBcDeFgHiJkLmNozzzzzzzzzzz"; + text[14][2] = "zzaBcDeFgHiJkLmNozzzzzzzzzz"; + text[14][3] = "zzzaBcDeFgHiJkLmNozzzzzzzzz"; + text[14][4] = "zzzzaBcDeFgHiJkLmNozzzzzzzz"; + text[14][5] = "zzzzzaBcDeFgHiJkLmNozzzzzzz"; + text[14][6] = "zzzzzzaBcDeFgHiJkLmNozzzzzz"; + text[14][7] = "zzzzzzzaBcDeFgHiJkLmNozzzzz"; + text[14][8] = "zzzzzzzzaBcDeFgHiJkLmNozzzz"; + text[14][9] = "zzzzzzzzzaBcDeFgHiJkLmNozzz"; + text[14][10] = "zzzzzzzzzzaBcDeFgHiJkLmNozz"; + text[14][11] = "zzzzzzzzzzzaBcDeFgHiJkLmNoz"; + text[14][12] = "zzzzzzzzzzzzaBcDeFgHiJkLmNo"; + text[15][0] = "aBcDeFgHiJkLmNoPzzzzzzzzzzz"; + text[15][1] = "zaBcDeFgHiJkLmNoPzzzzzzzzzz"; + text[15][2] = "zzaBcDeFgHiJkLmNoPzzzzzzzzz"; + text[15][3] = "zzzaBcDeFgHiJkLmNoPzzzzzzzz"; + text[15][4] = "zzzzaBcDeFgHiJkLmNoPzzzzzzz"; + text[15][5] = "zzzzzaBcDeFgHiJkLmNoPzzzzzz"; + text[15][6] = "zzzzzzaBcDeFgHiJkLmNoPzzzzz"; + text[15][7] = "zzzzzzzaBcDeFgHiJkLmNoPzzzz"; + text[15][8] = "zzzzzzzzaBcDeFgHiJkLmNoPzzz"; + text[15][9] = "zzzzzzzzzaBcDeFgHiJkLmNoPzz"; + text[15][10] = "zzzzzzzzzzaBcDeFgHiJkLmNoPz"; + text[15][11] = "zzzzzzzzzzzaBcDeFgHiJkLmNoP"; + text[16][0] = "aBcDeFgHiJkLmNoPqzzzzzzzzzz"; + text[16][1] = "zaBcDeFgHiJkLmNoPqzzzzzzzzz"; + text[16][2] = "zzaBcDeFgHiJkLmNoPqzzzzzzzz"; + text[16][3] = "zzzaBcDeFgHiJkLmNoPqzzzzzzz"; + text[16][4] = "zzzzaBcDeFgHiJkLmNoPqzzzzzz"; + text[16][5] = "zzzzzaBcDeFgHiJkLmNoPqzzzzz"; + text[16][6] = "zzzzzzaBcDeFgHiJkLmNoPqzzzz"; + text[16][7] = "zzzzzzzaBcDeFgHiJkLmNoPqzzz"; + text[16][8] = "zzzzzzzzaBcDeFgHiJkLmNoPqzz"; + text[16][9] = "zzzzzzzzzaBcDeFgHiJkLmNoPqz"; + text[16][10] = "zzzzzzzzzzaBcDeFgHiJkLmNoPq"; + text[17][0] = "aBcDeFgHiJkLmNoPqRzzzzzzzzz"; + text[17][1] = "zaBcDeFgHiJkLmNoPqRzzzzzzzz"; + text[17][2] = "zzaBcDeFgHiJkLmNoPqRzzzzzzz"; + text[17][3] = "zzzaBcDeFgHiJkLmNoPqRzzzzzz"; + text[17][4] = "zzzzaBcDeFgHiJkLmNoPqRzzzzz"; + text[17][5] = "zzzzzaBcDeFgHiJkLmNoPqRzzzz"; + text[17][6] = "zzzzzzaBcDeFgHiJkLmNoPqRzzz"; + text[17][7] = "zzzzzzzaBcDeFgHiJkLmNoPqRzz"; + text[17][8] = "zzzzzzzzaBcDeFgHiJkLmNoPqRz"; + text[17][9] = "zzzzzzzzzaBcDeFgHiJkLmNoPqR"; + text[18][0] = "aBcDeFgHiJkLmNoPqRszzzzzzzz"; + text[18][1] = "zaBcDeFgHiJkLmNoPqRszzzzzzz"; + text[18][2] = "zzaBcDeFgHiJkLmNoPqRszzzzzz"; + text[18][3] = "zzzaBcDeFgHiJkLmNoPqRszzzzz"; + text[18][4] = "zzzzaBcDeFgHiJkLmNoPqRszzzz"; + text[18][5] = "zzzzzaBcDeFgHiJkLmNoPqRszzz"; + text[18][6] = "zzzzzzaBcDeFgHiJkLmNoPqRszz"; + text[18][7] = "zzzzzzzaBcDeFgHiJkLmNoPqRsz"; + text[18][8] = "zzzzzzzzaBcDeFgHiJkLmNoPqRs"; + text[19][0] = "aBcDeFgHiJkLmNoPqRsTzzzzzzz"; + text[19][1] = "zaBcDeFgHiJkLmNoPqRsTzzzzzz"; + text[19][2] = "zzaBcDeFgHiJkLmNoPqRsTzzzzz"; + text[19][3] = "zzzaBcDeFgHiJkLmNoPqRsTzzzz"; + text[19][4] = "zzzzaBcDeFgHiJkLmNoPqRsTzzz"; + text[19][5] = "zzzzzaBcDeFgHiJkLmNoPqRsTzz"; + text[19][6] = "zzzzzzaBcDeFgHiJkLmNoPqRsTz"; + text[19][7] = "zzzzzzzaBcDeFgHiJkLmNoPqRsT"; + text[20][0] = "aBcDeFgHiJkLmNoPqRsTuzzzzzz"; + text[20][1] = "zaBcDeFgHiJkLmNoPqRsTuzzzzz"; + text[20][2] = "zzaBcDeFgHiJkLmNoPqRsTuzzzz"; + text[20][3] = "zzzaBcDeFgHiJkLmNoPqRsTuzzz"; + text[20][4] = "zzzzaBcDeFgHiJkLmNoPqRsTuzz"; + text[20][5] = "zzzzzaBcDeFgHiJkLmNoPqRsTuz"; + text[20][6] = "zzzzzzaBcDeFgHiJkLmNoPqRsTu"; + text[21][0] = "aBcDeFgHiJkLmNoPqRsTuVzzzzz"; + text[21][1] = "zaBcDeFgHiJkLmNoPqRsTuVzzzz"; + text[21][2] = "zzaBcDeFgHiJkLmNoPqRsTuVzzz"; + text[21][3] = "zzzaBcDeFgHiJkLmNoPqRsTuVzz"; + text[21][4] = "zzzzaBcDeFgHiJkLmNoPqRsTuVz"; + text[21][5] = "zzzzzaBcDeFgHiJkLmNoPqRsTuV"; + text[22][0] = "aBcDeFgHiJkLmNoPqRsTuVwzzzz"; + text[22][1] = "zaBcDeFgHiJkLmNoPqRsTuVwzzz"; + text[22][2] = "zzaBcDeFgHiJkLmNoPqRsTuVwzz"; + text[22][3] = "zzzaBcDeFgHiJkLmNoPqRsTuVwz"; + text[22][4] = "zzzzaBcDeFgHiJkLmNoPqRsTuVw"; + text[23][0] = "aBcDeFgHiJkLmNoPqRsTuVwXzzz"; + text[23][1] = "zaBcDeFgHiJkLmNoPqRsTuVwXzz"; + text[23][2] = "zzaBcDeFgHiJkLmNoPqRsTuVwXz"; + text[23][3] = "zzzaBcDeFgHiJkLmNoPqRsTuVwX"; + text[24][0] = "aBcDeFgHiJkLmNoPqRsTuVwXyzz"; + text[24][1] = "zaBcDeFgHiJkLmNoPqRsTuVwXyz"; + text[24][2] = "zzaBcDeFgHiJkLmNoPqRsTuVwXy"; + text[25][0] = "aBcDeFgHiJkLmNoPqRsTuVwXyZz"; + text[25][1] = "zaBcDeFgHiJkLmNoPqRsTuVwXyZ"; const char *needle[26]; - needle[0]="A"; - needle[1]="Ab"; - needle[2]="AbC"; - needle[3]="AbCd"; - needle[4]="AbCdE"; - needle[5]="AbCdEf"; - needle[6]="AbCdEfG"; - needle[7]="AbCdEfGh"; - needle[8]="AbCdEfGhI"; - needle[9]="AbCdEfGhIJ"; - needle[10]="AbCdEfGhIjK"; - needle[11]="AbCdEfGhIjKl"; - needle[12]="AbCdEfGhIjKlM"; - needle[13]="AbCdEfGhIjKlMn"; - needle[14]="AbCdEfGhIjKlMnO"; - needle[15]="AbCdEfGhIjKlMnOp"; - needle[16]="AbCdEfGhIjKlMnOpQ"; - needle[17]="AbCdEfGhIjKlMnOpQr"; - needle[18]="AbCdEfGhIjKlMnOpQrS"; - needle[19]="AbCdEfGhIjKlMnOpQrSt"; - needle[20]="AbCdEfGhIjKlMnOpQrStU"; - needle[21]="AbCdEfGhIjKlMnOpQrStUv"; - needle[22]="AbCdEfGhIjKlMnOpQrStUvW"; - needle[23]="AbCdEfGhIjKlMnOpQrStUvWx"; - needle[24]="AbCdEfGhIjKlMnOpQrStUvWxY"; - needle[25]="AbCdEfGhIjKlMnOpQrStUvWxYZ"; + needle[0] = "A"; + needle[1] = "Ab"; + needle[2] = "AbC"; + needle[3] = "AbCd"; + needle[4] = "AbCdE"; + needle[5] = "AbCdEf"; + needle[6] = "AbCdEfG"; + needle[7] = "AbCdEfGh"; + needle[8] = "AbCdEfGhI"; + needle[9] = "AbCdEfGhIJ"; + needle[10] = "AbCdEfGhIjK"; + needle[11] = "AbCdEfGhIjKl"; + needle[12] = "AbCdEfGhIjKlM"; + needle[13] = "AbCdEfGhIjKlMn"; + needle[14] = "AbCdEfGhIjKlMnO"; + needle[15] = "AbCdEfGhIjKlMnOp"; + needle[16] = "AbCdEfGhIjKlMnOpQ"; + needle[17] = "AbCdEfGhIjKlMnOpQr"; + needle[18] = "AbCdEfGhIjKlMnOpQrS"; + needle[19] = "AbCdEfGhIjKlMnOpQrSt"; + needle[20] = "AbCdEfGhIjKlMnOpQrStU"; + needle[21] = "AbCdEfGhIjKlMnOpQrStUv"; + needle[22] = "AbCdEfGhIjKlMnOpQrStUvW"; + needle[23] = "AbCdEfGhIjKlMnOpQrStUvWx"; + needle[24] = "AbCdEfGhIjKlMnOpQrStUvWxY"; + needle[25] = "AbCdEfGhIjKlMnOpQrStUvWxYZ"; int i, j; uint8_t *found = NULL; for (i = 0; i < 26; i++) { - for (j = 0; j <= (26-i); j++) { + for (j = 0; j <= (26 - i); j++) { found = BasicSearchNocaseWrapper((uint8_t *)text[i][j], (uint8_t *)needle[i], 1); if (found == 0) { printf("Error1 searching for %s in text %s\n", needle[i], text[i][j]); @@ -1639,58 +1688,107 @@ static int UtilSpmSearchOffsetsNocaseTest01(void) static int UtilSpmSearchStatsTest01(void) { char *text[16]; - text[0]="zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzza"; - text[1]="aaaaaaaaazaaaaaaaaaaaaaaaaaaaaazaaaaaaaaaaaaaazaaaaaaaaaaaaaaaaaaaaazaaaaaaaaaaaaaaaaaaazaaaaaaaaaaaaaaaaaaazaaaaaaaaazaaaaaaaaaazaaaaaaaaaaaaazaaaaaaaaazaaaaaaaaaaaaaaaaazaaaaaaaaaaaaaaaaazaaaaaaaaazaaaaaaaaaazaaaaaraaaaazaaaaaaazaaaaaaaaaaaaaazaaaaaaaazaaaaaaaaazaaaaaaaaaaaaB"; - text[2]="aBaBaBaBaBaBaBaBazaBaBaBaBaBaBazaBaBaBaBaBaBaBaBaBzBaBaBaBaBaBaBaBazaBaBaBaBaBaBaBzBaBaBaBaBaBaBzBaBaBaBaBzBaBaBaBaBaBzBaBaBaBaBaBzBaBaBaBaBaBaBaBazaBaBaBaBaBaBaBaBaBaBaBaBazaBaBaBaBaBaBaBaBaBzBaBaBaBaBaBaBaBzBaBaBaBaBaBaBaBaBaBzBaBaBaBaBaBaBaBaBaBaBazaBaBaBaBaBaBaBazaBaBaBaBaBc"; - text[3]="aBcaBcaBcaBcaBczBcaBcaBzaBcaBcaBcaBcaBcaBcaBcaBcazcaBcaBcaBcaBcaBcaBcaBzaBcaBcaBcaBcaBcaBczBcaBcaBcaBcaBcaBzaBcaBcaBcaBcaBcaBcaBcazcaBcaBcaBcaBcaBcaBcaBcaBczBcaBcaBcaBcaBcaBcaBczBcaBcaBcaBcaBzaBcaBcaBcaBcaBcaBcaBcazcaBcaBcaBcaBcaBcazcaBcaBcaBcaBcaBcaBzaBcaBcaBcazcaBcaBcaBcaBcaBcD"; - text[4]="aBcDaBcDaBcDaBczaBcDaBcDaBcDaBcDaBczaBcDaBcDaBcDaBcDzBcDaBcDaBcDaBcDzBcDaBcDaBczaBcDaBcDaBczaBcDaBcDaBcDaBcDaBzDaBcDaBcDaBcDaBcDaBcDaBcDaBcDaBczaBcDaBcDaBcDaBcDaBcDaBzDaBcDaBcDaBcDaBzDaBcDaBcDaBzDaBcDaBcDaBcDaBcDaBcDaBczaBcDaBcDaBcDaBcDazcDaBcDaBcDaBcDaBcDzBcDaBcDaBcDaBcDaBcDaBcDe"; - text[5]="aBcDeaBcDeaBcDeazcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDezBcDeaBcDeaBcDzaBcDeaBcDeaBcDeazcDzaBcDeaBcDezBcDeaBzDeaBcDeaBcDeazcDeaBcDeaBcDeaBcDzaBcDeaBcDeaBczeaBcDeaBcDeaBzDeaBcDeaBcDezBcDeaBcDzaBcDeaBcDezBcDeaBcDezBcDeaBczeaBcDeaBcDeaBzDeaBcDezBcDeaBcDeaBcDeaBcDeaBcDeaBcDeaBcDeaBcDezzzaBcDeF"; - text[6]="aBcDeaBcDeaBcDeazcDeaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDeaBcDzaBzDeaBcDeaBcDeaBcDzaBcDzaBcDeaBcDeaBcDeaBcDzaBzDeaBcDeaBcDeaBczzaBcDeaBcDeaBcDzazcDeaBcDeaBcDeaBcDzaBzDeaBcDeaBcDeaBcDeazcDeaBcDeaBcDeaBcDeaBczeaBcDeaBcDeaBcDeaBczeaBcDezzzaBcDeFg"; - text[7]="aBcDeaBczeaBcDzaBcDezBcDeaBcDeaBcDeaBcDzaBzDeaBcDeaBcDeaBzDzaBcDeaBcDeazcDeaBcDzaBcDeaBczeaBcDeaBcDeaBzDzaBcDeaBcDeaBcDezBcDzaBcDeaBzDeaBcDeaBcDezBcDzaBcDeaBcDeaBzDeaBcDeaBcDeaBzDeaBcDeaBcDezBcDeaBcDeaBcDeazcDeaBcDeaBcDeaBcDzaBcDeaBcDeaBcDeaBcDzaBcDeaBcDeaBcDeaBrDeaBcDeaBcDezzzaBcDeFgH"; - text[8]="aBcDeaBcDeaBczzaBcDeazcDeaBcDezBcDeaBcDzaBcDeaBcDeaBcDeaBczzaBcDeaBcDeaBczeaBcDeaBcDzzBcDeaBcDeaBcDzaBczeaBcDeaBcDzaBcDeaBczeaBcDeaBcDeaBzDeaBcDeaBcDeaBzDeaBcDeaBcDzaBcDeaBcDeazcDeaBcDeaBcDzaBcDeaBcDeaBcDeazcDeaBcDeaBcDeaBcDeazcDeaBcDeaBcDeaBczeaBcDeaBzDeaBcDeaBcDeaBcDeaBcDezzzaBcDeFgHi"; - text[9]="aBcDeaBcDzaBcDzaBcDeaBcDeaBcDzaBcDeaBcDzaBcDeazcDeaBcDeaBcDzzBcDeaBcDeaBczeaBcDzaBcDezBcDeaBczeaBcDzaBcDezBcDeaBcDzaBczeaBcDeaBcDzaBcDeazcDeaBcDeaBcDzaBczeaBcDeaBcDzaBzDeaBcDeaBczeaBcDeaBcDzaBcDeaBcDeaBzDeaBcDeaBcDeaBczeaBcDeaBcDeaBcDeaBzDeaBcDeaBcDeazcDeaBcDeaBcDeaBcDeaBcDezzzaBcDeFgHiJ"; - text[10]="aBcDeaBcDeaBczeaBcDzaBczeaBcDeaBczeaBcDeaBcDzaBcDeaBcDeazcDeaBcDeaBcDeaBzDzaBcDeazcDeaBcDeazcDeaBcDzaBcDeazcDeaBcDeaBczzaBcDeaBcDeaBzDeaBcDeaBcDzaBczeaBcDeaBcDeaBcDeaBczeaBcDeaBcDeaBcDzaBcDeaBcDeaBcDezBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDezBcDeaBcDeaBcDeaBzDeaBcDeaBcDezzzaBcDeFgHiJk"; - text[11]="aBcDeaBcDeaBcDeaBcDeaBzDeaBcDeaBcDzaBcDzaBcDeaBcDeaBcDeaBcDeazcDeaBcDzaBcDeaBcDeaBcDeaBcDzaBcDeaBcDzaBcDzaBcDeaBcDeaBcDeaBcDzzBcDeaBcDeaBcDeaBcDzaBcDzaBcDeaBzDeaBcDeaBcDezBcDeaBcDeazcDeaBcDeaBcDezBcDeaBcDeaBcDeazcDeaBcDeaBzDeaBcDeaBczeaBcDeazcDeaBcDezBcDeaBcDeaBcDeaBcDeaBcDezzzaBcDeFgHiJkL"; - text[12]="aBcDeaBcDeaBcDeaBcDeaBzDeaBcDeaBzDeaBcDeaBcDezBcDeaBcDeazcDeaBcDeaBcDeazcDeaBcDeaBczeaBcDeaBcDeaBcDezBcDeaBcDzaBcDeaBcDzaBcDeaBcDeaBcDeaBcDeaBcDeaBcDeaBcDeaBcDeaBcDeaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDzaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDeaBcDeaBcDeaBcDezzzaBcDeFgHiJkLm"; - text[13]="aBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDeaBcDeaBcDeaBcDeaBcDeaBcDeaBcDeaBcDeaBcDeaBcDeaBcDeaBcDeaBcDeaBcDeaBcDezzzaBcDeFgHiJkLmN"; - text[14]="aBcDeaBcDeaBcDzaBcDeaBcDeaBcDeaBcDzaBcDeaBcDeaBcDeaBcDzaBcDeaBcDeaBcDeaBcDzaBcDeaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDzaBcDezzzaBcDeFgHiJkLmNo"; - text[15]="aBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDzaBcDeaBcDzaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDzaBcDeaBcDzaBcDeaBcDzaBcDeaBcDzaBcDeaBcDzaBcDeaBcDzaBcDeaBcDeaBcDeaBcDezzzaBcDeFgHiJkLmNoP"; + text[0] = "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzza"; + text[1] = "aaaaaaaaazaaaaaaaaaaaaaaaaaaaaazaaaaaaaaaaaaaazaaaaaaaaaaaaaaaaaaaaazaaaaaaaaaaaaaaa" + "aaaazaaaaaaaaaaaaaaaaaaazaaaaaaaaazaaaaaaaaaazaaaaaaaaaaaaazaaaaaaaaazaaaaaaaaaaaaaa" + "aaazaaaaaaaaaaaaaaaaazaaaaaaaaazaaaaaaaaaazaaaaaraaaaazaaaaaaazaaaaaaaaaaaaaazaaaaaa" + "aazaaaaaaaaazaaaaaaaaaaaaB"; + text[2] = "aBaBaBaBaBaBaBaBazaBaBaBaBaBaBazaBaBaBaBaBaBaBaBaBzBaBaBaBaBaBaBaBazaBaBaBaBaBaBaBzB" + "aBaBaBaBaBaBzBaBaBaBaBzBaBaBaBaBaBzBaBaBaBaBaBzBaBaBaBaBaBaBaBazaBaBaBaBaBaBaBaBaBaB" + "aBaBazaBaBaBaBaBaBaBaBaBzBaBaBaBaBaBaBaBzBaBaBaBaBaBaBaBaBaBzBaBaBaBaBaBaBaBaBaBaBaz" + "aBaBaBaBaBaBaBazaBaBaBaBaBc"; + text[3] = "aBcaBcaBcaBcaBczBcaBcaBzaBcaBcaBcaBcaBcaBcaBcaBcazcaBcaBcaBcaBcaBcaBcaBzaBcaBcaBcaBc" + "aBcaBczBcaBcaBcaBcaBcaBzaBcaBcaBcaBcaBcaBcaBcazcaBcaBcaBcaBcaBcaBcaBcaBczBcaBcaBcaBc" + "aBcaBcaBczBcaBcaBcaBcaBzaBcaBcaBcaBcaBcaBcaBcazcaBcaBcaBcaBcaBcazcaBcaBcaBcaBcaBcaBz" + "aBcaBcaBcazcaBcaBcaBcaBcaBcD"; + text[4] = "aBcDaBcDaBcDaBczaBcDaBcDaBcDaBcDaBczaBcDaBcDaBcDaBcDzBcDaBcDaBcDaBcDzBcDaBcDaBczaBcD" + "aBcDaBczaBcDaBcDaBcDaBcDaBzDaBcDaBcDaBcDaBcDaBcDaBcDaBcDaBczaBcDaBcDaBcDaBcDaBcDaBzD" + "aBcDaBcDaBcDaBzDaBcDaBcDaBzDaBcDaBcDaBcDaBcDaBcDaBczaBcDaBcDaBcDaBcDazcDaBcDaBcDaBcD" + "aBcDzBcDaBcDaBcDaBcDaBcDaBcDe"; + text[5] = "aBcDeaBcDeaBcDeazcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDezBcDeaBcDeaBcDzaBcDeaBcDeaBcDeazcD" + "zaBcDeaBcDezBcDeaBzDeaBcDeaBcDeazcDeaBcDeaBcDeaBcDzaBcDeaBcDeaBczeaBcDeaBcDeaBzDeaBc" + "DeaBcDezBcDeaBcDzaBcDeaBcDezBcDeaBcDezBcDeaBczeaBcDeaBcDeaBzDeaBcDezBcDeaBcDeaBcDeaB" + "cDeaBcDeaBcDeaBcDeaBcDezzzaBcDeF"; + text[6] = "aBcDeaBcDeaBcDeazcDeaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDeaBcDzaBcDeaBcDeaBcD" + "zaBcDeaBcDeaBcDeaBcDzaBzDeaBcDeaBcDeaBcDzaBcDzaBcDeaBcDeaBcDeaBcDzaBzDeaBcDeaBcDeaBc" + "zzaBcDeaBcDeaBcDzazcDeaBcDeaBcDeaBcDzaBzDeaBcDeaBcDeaBcDeazcDeaBcDeaBcDeaBcDeaBczeaB" + "cDeaBcDeaBcDeaBczeaBcDezzzaBcDeFg"; + text[7] = "aBcDeaBczeaBcDzaBcDezBcDeaBcDeaBcDeaBcDzaBzDeaBcDeaBcDeaBzDzaBcDeaBcDeazcDeaBcDzaBcD" + "eaBczeaBcDeaBcDeaBzDzaBcDeaBcDeaBcDezBcDzaBcDeaBzDeaBcDeaBcDezBcDzaBcDeaBcDeaBzDeaBc" + "DeaBcDeaBzDeaBcDeaBcDezBcDeaBcDeaBcDeazcDeaBcDeaBcDeaBcDzaBcDeaBcDeaBcDeaBcDzaBcDeaB" + "cDeaBcDeaBrDeaBcDeaBcDezzzaBcDeFgH"; + text[8] = "aBcDeaBcDeaBczzaBcDeazcDeaBcDezBcDeaBcDzaBcDeaBcDeaBcDeaBczzaBcDeaBcDeaBczeaBcDeaBcD" + "zzBcDeaBcDeaBcDzaBczeaBcDeaBcDzaBcDeaBczeaBcDeaBcDeaBzDeaBcDeaBcDeaBzDeaBcDeaBcDzaBc" + "DeaBcDeazcDeaBcDeaBcDzaBcDeaBcDeaBcDeazcDeaBcDeaBcDeaBcDeazcDeaBcDeaBcDeaBczeaBcDeaB" + "zDeaBcDeaBcDeaBcDeaBcDezzzaBcDeFgHi"; + text[9] = "aBcDeaBcDzaBcDzaBcDeaBcDeaBcDzaBcDeaBcDzaBcDeazcDeaBcDeaBcDzzBcDeaBcDeaBczeaBcDzaBcD" + "ezBcDeaBczeaBcDzaBcDezBcDeaBcDzaBczeaBcDeaBcDzaBcDeazcDeaBcDeaBcDzaBczeaBcDeaBcDzaBz" + "DeaBcDeaBczeaBcDeaBcDzaBcDeaBcDeaBzDeaBcDeaBcDeaBczeaBcDeaBcDeaBcDeaBzDeaBcDeaBcDeaz" + "cDeaBcDeaBcDeaBcDeaBcDezzzaBcDeFgHiJ"; + text[10] = "aBcDeaBcDeaBczeaBcDzaBczeaBcDeaBczeaBcDeaBcDzaBcDeaBcDeazcDeaBcDeaBcDeaBzDzaBcDeazc" + "DeaBcDeazcDeaBcDzaBcDeazcDeaBcDeaBczzaBcDeaBcDeaBzDeaBcDeaBcDzaBczeaBcDeaBcDeaBcDea" + "BczeaBcDeaBcDeaBcDzaBcDeaBcDeaBcDezBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDezBcD" + "eaBcDeaBcDeaBzDeaBcDeaBcDezzzaBcDeFgHiJk"; + text[11] = "aBcDeaBcDeaBcDeaBcDeaBzDeaBcDeaBcDzaBcDzaBcDeaBcDeaBcDeaBcDeazcDeaBcDzaBcDeaBcDeaBc" + "DeaBcDzaBcDeaBcDzaBcDzaBcDeaBcDeaBcDeaBcDzzBcDeaBcDeaBcDeaBcDzaBcDzaBcDeaBzDeaBcDea" + "BcDezBcDeaBcDeazcDeaBcDeaBcDezBcDeaBcDeaBcDeazcDeaBcDeaBzDeaBcDeaBczeaBcDeazcDeaBcD" + "ezBcDeaBcDeaBcDeaBcDeaBcDezzzaBcDeFgHiJkL"; + text[12] = "aBcDeaBcDeaBcDeaBcDeaBzDeaBcDeaBzDeaBcDeaBcDezBcDeaBcDeazcDeaBcDeaBcDeazcDeaBcDeaBc" + "zeaBcDeaBcDeaBcDezBcDeaBcDzaBcDeaBcDzaBcDeaBcDeaBcDeaBcDeaBcDeaBcDeaBcDeaBcDeaBcDea" + "BcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDzaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcD" + "eaBcDeaBcDeaBcDeaBcDeaBcDezzzaBcDeFgHiJkLm"; + text[13] = "aBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBc" + "DzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDea" + "BcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDeaBcDeaBcDeaBcDeaBcDeaBcDeaBcDeaBcDeaBcDeaBcD" + "eaBcDeaBcDeaBcDeaBcDeaBcDezzzaBcDeFgHiJkLmN"; + text[14] = "aBcDeaBcDeaBcDzaBcDeaBcDeaBcDeaBcDzaBcDeaBcDeaBcDeaBcDzaBcDeaBcDeaBcDeaBcDzaBcDeaBc" + "DeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDea" + "BcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcD" + "eaBcDeaBcDzaBcDeaBcDzaBcDezzzaBcDeFgHiJkLmNo"; + text[15] = "aBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDzaBc" + "DeaBcDeaBcDzaBcDeaBcDzaBcDeaBcDzaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDea" + "BcDzaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDzaBcDeaBcDzaBcDeaBcDzaBcDeaBcDzaBcDeaBcDzaBcD" + "eaBcDzaBcDeaBcDeaBcDeaBcDezzzaBcDeFgHiJkLmNoP"; char *needle[16]; - needle[0]="a"; - needle[1]="aB"; - needle[2]="aBc"; - needle[3]="aBcD"; - needle[4]="aBcDe"; - needle[5]="aBcDeF"; - needle[6]="aBcDeFg"; - needle[7]="aBcDeFgH"; - needle[8]="aBcDeFgHi"; - needle[9]="aBcDeFgHiJ"; - needle[10]="aBcDeFgHiJk"; - needle[11]="aBcDeFgHiJkL"; - needle[12]="aBcDeFgHiJkLm"; - needle[13]="aBcDeFgHiJkLmN"; - needle[14]="aBcDeFgHiJkLmNo"; - needle[15]="aBcDeFgHiJkLmNoP"; + needle[0] = "a"; + needle[1] = "aB"; + needle[2] = "aBc"; + needle[3] = "aBcD"; + needle[4] = "aBcDe"; + needle[5] = "aBcDeF"; + needle[6] = "aBcDeFg"; + needle[7] = "aBcDeFgH"; + needle[8] = "aBcDeFgHi"; + needle[9] = "aBcDeFgHiJ"; + needle[10] = "aBcDeFgHiJk"; + needle[11] = "aBcDeFgHiJkL"; + needle[12] = "aBcDeFgHiJkLm"; + needle[13] = "aBcDeFgHiJkLmN"; + needle[14] = "aBcDeFgHiJkLmNo"; + needle[15] = "aBcDeFgHiJkLmNoP"; int i; uint8_t *found = NULL; - printf("\nStats for text of greater length (text with a lot of partial matches, worst case for a basic search):\n"); + printf("\nStats for text of greater length (text with a lot of partial matches, worst case for " + "a basic search):\n"); for (i = 0; i < 16; i++) { - printf("Pattern length %d with BasicSearch:", i+1); + printf("Pattern length %d with BasicSearch:", i + 1); found = BasicSearchWrapper((uint8_t *)text[i], (uint8_t *)needle[i], STATS_TIMES); if (found == 0) { printf("Error1 searching for %s in text %s\n", needle[i], text[i]); return 0; } - printf("Pattern length %d with Bs2BmSearch:", i+1); + printf("Pattern length %d with Bs2BmSearch:", i + 1); found = Bs2bmWrapper((uint8_t *)text[i], (uint8_t *)needle[i], STATS_TIMES); if (found == 0) { printf("Error2 searching for %s in text %s\n", needle[i], text[i]); return 0; } - printf("Pattern length %d with BoyerMooreSearch:", i+1); + printf("Pattern length %d with BoyerMooreSearch:", i + 1); found = BoyerMooreWrapper((uint8_t *)text[i], (uint8_t *)needle[i], STATS_TIMES); if (found == 0) { printf("Error3 searching for %s in text %s\n", needle[i], text[i]); @@ -1707,58 +1805,58 @@ static int UtilSpmSearchStatsTest01(void) static int UtilSpmSearchStatsTest02(void) { char *text[16]; - text[0]="zzzzzzzzzzzzzzzzzza"; - text[1]="zzzzzzzzzzzzzzzzzzaB"; - text[2]="zzzzzzzzzzzzzzzzzzaBc"; - text[3]="zzzzzzzzzzzzzzzzzzaBcD"; - text[4]="zzzzzzzzzzzzzzzzzzaBcDe"; - text[5]="zzzzzzzzzzzzzzzzzzzzaBcDeF"; - text[6]="zzzzzzzzzzzzzzzzzzzzaBcDeFg"; - text[7]="zzzzzzzzzzzzzzzzzzzzaBcDeFgH"; - text[8]="zzzzzzzzzzzzzzzzzzzzaBcDeFgHi"; - text[9]="zzzzzzzzzzzzzzzzzzzzaBcDeFgHiJ"; - text[10]="zzzzzzzzzzzzzzzzzzzzaBcDeFgHiJk"; - text[11]="zzzzzzzzzzzzzzzzzzzzaBcDeFgHiJkL"; - text[12]="zzzzzzzzzzzzzzzzzzzzaBcDeFgHiJkLm"; - text[13]="zzzzzzzzzzzzzzzzzzzzaBcDeFgHiJkLmN"; - text[14]="zzzzzzzzzzzzzzzzzzzzaBcDeFgHiJkLmNo"; - text[15]="zzzzzzzzzzzzzzzzzzzzaBcDeFgHiJkLmNoP"; + text[0] = "zzzzzzzzzzzzzzzzzza"; + text[1] = "zzzzzzzzzzzzzzzzzzaB"; + text[2] = "zzzzzzzzzzzzzzzzzzaBc"; + text[3] = "zzzzzzzzzzzzzzzzzzaBcD"; + text[4] = "zzzzzzzzzzzzzzzzzzaBcDe"; + text[5] = "zzzzzzzzzzzzzzzzzzzzaBcDeF"; + text[6] = "zzzzzzzzzzzzzzzzzzzzaBcDeFg"; + text[7] = "zzzzzzzzzzzzzzzzzzzzaBcDeFgH"; + text[8] = "zzzzzzzzzzzzzzzzzzzzaBcDeFgHi"; + text[9] = "zzzzzzzzzzzzzzzzzzzzaBcDeFgHiJ"; + text[10] = "zzzzzzzzzzzzzzzzzzzzaBcDeFgHiJk"; + text[11] = "zzzzzzzzzzzzzzzzzzzzaBcDeFgHiJkL"; + text[12] = "zzzzzzzzzzzzzzzzzzzzaBcDeFgHiJkLm"; + text[13] = "zzzzzzzzzzzzzzzzzzzzaBcDeFgHiJkLmN"; + text[14] = "zzzzzzzzzzzzzzzzzzzzaBcDeFgHiJkLmNo"; + text[15] = "zzzzzzzzzzzzzzzzzzzzaBcDeFgHiJkLmNoP"; char *needle[16]; - needle[0]="a"; - needle[1]="aB"; - needle[2]="aBc"; - needle[3]="aBcD"; - needle[4]="aBcDe"; - needle[5]="aBcDeF"; - needle[6]="aBcDeFg"; - needle[7]="aBcDeFgH"; - needle[8]="aBcDeFgHi"; - needle[9]="aBcDeFgHiJ"; - needle[10]="aBcDeFgHiJk"; - needle[11]="aBcDeFgHiJkL"; - needle[12]="aBcDeFgHiJkLm"; - needle[13]="aBcDeFgHiJkLmN"; - needle[14]="aBcDeFgHiJkLmNo"; - needle[15]="aBcDeFgHiJkLmNoP"; + needle[0] = "a"; + needle[1] = "aB"; + needle[2] = "aBc"; + needle[3] = "aBcD"; + needle[4] = "aBcDe"; + needle[5] = "aBcDeF"; + needle[6] = "aBcDeFg"; + needle[7] = "aBcDeFgH"; + needle[8] = "aBcDeFgHi"; + needle[9] = "aBcDeFgHiJ"; + needle[10] = "aBcDeFgHiJk"; + needle[11] = "aBcDeFgHiJkL"; + needle[12] = "aBcDeFgHiJkLm"; + needle[13] = "aBcDeFgHiJkLmN"; + needle[14] = "aBcDeFgHiJkLmNo"; + needle[15] = "aBcDeFgHiJkLmNoP"; int i; uint8_t *found = NULL; - printf("\nStats for text of lower length:\n"); + printf("\nStats for text of lower length:\n"); for (i = 0; i < 16; i++) { - printf("Pattern length %d with BasicSearch:", i+1); + printf("Pattern length %d with BasicSearch:", i + 1); found = BasicSearchWrapper((uint8_t *)text[i], (uint8_t *)needle[i], STATS_TIMES); if (found == 0) { printf("Error1 searching for %s in text %s\n", needle[i], text[i]); return 0; } - printf("Pattern length %d with Bs2BmSearch:", i+1); + printf("Pattern length %d with Bs2BmSearch:", i + 1); found = Bs2bmWrapper((uint8_t *)text[i], (uint8_t *)needle[i], STATS_TIMES); if (found == 0) { printf("Error2 searching for %s in text %s\n", needle[i], text[i]); return 0; } - printf("Pattern length %d with BoyerMooreSearch:", i+1); + printf("Pattern length %d with BoyerMooreSearch:", i + 1); found = BoyerMooreWrapper((uint8_t *)text[i], (uint8_t *)needle[i], STATS_TIMES); if (found == 0) { printf("Error3 searching for %s in text %s\n", needle[i], text[i]); @@ -1769,62 +1867,61 @@ static int UtilSpmSearchStatsTest02(void) return 1; } - static int UtilSpmSearchStatsTest03(void) { char *text[16]; - text[0]="zzzzzza"; - text[1]="zzzzzzaB"; - text[2]="zzzzzzaBc"; - text[3]="zzzzzzaBcD"; - text[4]="zzzzzzaBcDe"; - text[5]="zzzzzzzzaBcDeF"; - text[6]="zzzzzzzzaBcDeFg"; - text[7]="zzzzzzzzaBcDeFgH"; - text[8]="zzzzzzzzaBcDeFgHi"; - text[9]="zzzzzzzzaBcDeFgHiJ"; - text[10]="zzzzzzzzaBcDeFgHiJk"; - text[11]="zzzzzzzzaBcDeFgHiJkL"; - text[12]="zzzzzzzzaBcDeFgHiJkLm"; - text[13]="zzzzzzzzaBcDeFgHiJkLmN"; - text[14]="zzzzzzzzaBcDeFgHiJkLmNo"; - text[15]="zzzzzzzzaBcDeFgHiJkLmNoP"; + text[0] = "zzzzzza"; + text[1] = "zzzzzzaB"; + text[2] = "zzzzzzaBc"; + text[3] = "zzzzzzaBcD"; + text[4] = "zzzzzzaBcDe"; + text[5] = "zzzzzzzzaBcDeF"; + text[6] = "zzzzzzzzaBcDeFg"; + text[7] = "zzzzzzzzaBcDeFgH"; + text[8] = "zzzzzzzzaBcDeFgHi"; + text[9] = "zzzzzzzzaBcDeFgHiJ"; + text[10] = "zzzzzzzzaBcDeFgHiJk"; + text[11] = "zzzzzzzzaBcDeFgHiJkL"; + text[12] = "zzzzzzzzaBcDeFgHiJkLm"; + text[13] = "zzzzzzzzaBcDeFgHiJkLmN"; + text[14] = "zzzzzzzzaBcDeFgHiJkLmNo"; + text[15] = "zzzzzzzzaBcDeFgHiJkLmNoP"; char *needle[16]; - needle[0]="a"; - needle[1]="aB"; - needle[2]="aBc"; - needle[3]="aBcD"; - needle[4]="aBcDe"; - needle[5]="aBcDeF"; - needle[6]="aBcDeFg"; - needle[7]="aBcDeFgH"; - needle[8]="aBcDeFgHi"; - needle[9]="aBcDeFgHiJ"; - needle[10]="aBcDeFgHiJk"; - needle[11]="aBcDeFgHiJkL"; - needle[12]="aBcDeFgHiJkLm"; - needle[13]="aBcDeFgHiJkLmN"; - needle[14]="aBcDeFgHiJkLmNo"; - needle[15]="aBcDeFgHiJkLmNoP"; + needle[0] = "a"; + needle[1] = "aB"; + needle[2] = "aBc"; + needle[3] = "aBcD"; + needle[4] = "aBcDe"; + needle[5] = "aBcDeF"; + needle[6] = "aBcDeFg"; + needle[7] = "aBcDeFgH"; + needle[8] = "aBcDeFgHi"; + needle[9] = "aBcDeFgHiJ"; + needle[10] = "aBcDeFgHiJk"; + needle[11] = "aBcDeFgHiJkL"; + needle[12] = "aBcDeFgHiJkLm"; + needle[13] = "aBcDeFgHiJkLmN"; + needle[14] = "aBcDeFgHiJkLmNo"; + needle[15] = "aBcDeFgHiJkLmNoP"; int i; uint8_t *found = NULL; - printf("\nStats for text of lower length (badcase for):\n"); + printf("\nStats for text of lower length (badcase for):\n"); for (i = 0; i < 16; i++) { - printf("Pattern length %d with BasicSearch:", i+1); + printf("Pattern length %d with BasicSearch:", i + 1); found = BasicSearchWrapper((uint8_t *)text[i], (uint8_t *)needle[i], STATS_TIMES); if (found == 0) { printf("Error1 searching for %s in text %s\n", needle[i], text[i]); return 0; } - printf("Pattern length %d with Bs2BmSearch:", i+1); + printf("Pattern length %d with Bs2BmSearch:", i + 1); found = Bs2bmWrapper((uint8_t *)text[i], (uint8_t *)needle[i], STATS_TIMES); if (found == 0) { printf("Error2 searching for %s in text %s\n", needle[i], text[i]); return 0; } - printf("Pattern length %d with BoyerMooreSearch:", i+1); + printf("Pattern length %d with BoyerMooreSearch:", i + 1); found = BoyerMooreWrapper((uint8_t *)text[i], (uint8_t *)needle[i], STATS_TIMES); if (found == 0) { printf("Error3 searching for %s in text %s\n", needle[i], text[i]); @@ -1841,45 +1938,92 @@ static int UtilSpmSearchStatsTest03(void) static int UtilSpmSearchStatsTest04(void) { char *text[16]; - text[0]="zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzza"; - text[1]="aaaaaaaaazaaaaaaaaaaaaaaaaaaaaazaaaaaaaaaaaaaazaaaaaaaaaaaaaaaaaaaaazaaaaaaaaaaaaaaaaaaazaaaaaaaaaaaaaaaaaaazaaaaaaaaazaaaaaaaaaazaaaaaaaaaaaaazaaaaaaaaazaaaaaaaaaaaaaaaaazaaaaaaaaaaaaaaaaazaaaaaaaaazaaaaaaaaaazaaaaaraaaaazaaaaaaazaaaaaaaaaaaaaazaaaaaaaazaaaaaaaaazaaaaaaaaaaaaB"; - text[2]="aBaBaBaBaBaBaBaBazaBaBaBaBaBaBazaBaBaBaBaBaBaBaBaBzBaBaBaBaBaBaBaBazaBaBaBaBaBaBaBzBaBaBaBaBaBaBzBaBaBaBaBzBaBaBaBaBaBzBaBaBaBaBaBzBaBaBaBaBaBaBaBazaBaBaBaBaBaBaBaBaBaBaBaBazaBaBaBaBaBaBaBaBaBzBaBaBaBaBaBaBaBzBaBaBaBaBaBaBaBaBaBzBaBaBaBaBaBaBaBaBaBaBazaBaBaBaBaBaBaBazaBaBaBaBaBc"; - text[3]="aBcaBcaBcaBcaBczBcaBcaBzaBcaBcaBcaBcaBcaBcaBcaBcazcaBcaBcaBcaBcaBcaBcaBzaBcaBcaBcaBcaBcaBczBcaBcaBcaBcaBcaBzaBcaBcaBcaBcaBcaBcaBcazcaBcaBcaBcaBcaBcaBcaBcaBczBcaBcaBcaBcaBcaBcaBczBcaBcaBcaBcaBzaBcaBcaBcaBcaBcaBcaBcazcaBcaBcaBcaBcaBcazcaBcaBcaBcaBcaBcaBzaBcaBcaBcazcaBcaBcaBcaBcaBcD"; - text[4]="aBcDaBcDaBcDaBczaBcDaBcDaBcDaBcDaBczaBcDaBcDaBcDaBcDzBcDaBcDaBcDaBcDzBcDaBcDaBczaBcDaBcDaBczaBcDaBcDaBcDaBcDaBzDaBcDaBcDaBcDaBcDaBcDaBcDaBcDaBczaBcDaBcDaBcDaBcDaBcDaBzDaBcDaBcDaBcDaBzDaBcDaBcDaBzDaBcDaBcDaBcDaBcDaBcDaBczaBcDaBcDaBcDaBcDazcDaBcDaBcDaBcDaBcDzBcDaBcDaBcDaBcDaBcDaBcDe"; - text[5]="aBcDeaBcDeaBcDeazcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDezBcDeaBcDeaBcDzaBcDeaBcDeaBcDeazcDzaBcDeaBcDezBcDeaBzDeaBcDeaBcDeazcDeaBcDeaBcDeaBcDzaBcDeaBcDeaBczeaBcDeaBcDeaBzDeaBcDeaBcDezBcDeaBcDzaBcDeaBcDezBcDeaBcDezBcDeaBczeaBcDeaBcDeaBzDeaBcDezBcDeaBcDeaBcDeaBcDeaBcDeaBcDeaBcDeaBcDezzzaBcDeF"; - text[6]="aBcDeaBcDeaBcDeazcDeaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDeaBcDzaBzDeaBcDeaBcDeaBcDzaBcDzaBcDeaBcDeaBcDeaBcDzaBzDeaBcDeaBcDeaBczzaBcDeaBcDeaBcDzazcDeaBcDeaBcDeaBcDzaBzDeaBcDeaBcDeaBcDeazcDeaBcDeaBcDeaBcDeaBczeaBcDeaBcDeaBcDeaBczeaBcDezzzaBcDeFg"; - text[7]="aBcDeaBczeaBcDzaBcDezBcDeaBcDeaBcDeaBcDzaBzDeaBcDeaBcDeaBzDzaBcDeaBcDeazcDeaBcDzaBcDeaBczeaBcDeaBcDeaBzDzaBcDeaBcDeaBcDezBcDzaBcDeaBzDeaBcDeaBcDezBcDzaBcDeaBcDeaBzDeaBcDeaBcDeaBzDeaBcDeaBcDezBcDeaBcDeaBcDeazcDeaBcDeaBcDeaBcDzaBcDeaBcDeaBcDeaBcDzaBcDeaBcDeaBcDeaBrDeaBcDeaBcDezzzaBcDeFgH"; - text[8]="aBcDeaBcDeaBczzaBcDeazcDeaBcDezBcDeaBcDzaBcDeaBcDeaBcDeaBczzaBcDeaBcDeaBczeaBcDeaBcDzzBcDeaBcDeaBcDzaBczeaBcDeaBcDzaBcDeaBczeaBcDeaBcDeaBzDeaBcDeaBcDeaBzDeaBcDeaBcDzaBcDeaBcDeazcDeaBcDeaBcDzaBcDeaBcDeaBcDeazcDeaBcDeaBcDeaBcDeazcDeaBcDeaBcDeaBczeaBcDeaBzDeaBcDeaBcDeaBcDeaBcDezzzaBcDeFgHi"; - text[9]="aBcDeaBcDzaBcDzaBcDeaBcDeaBcDzaBcDeaBcDzaBcDeazcDeaBcDeaBcDzzBcDeaBcDeaBczeaBcDzaBcDezBcDeaBczeaBcDzaBcDezBcDeaBcDzaBczeaBcDeaBcDzaBcDeazcDeaBcDeaBcDzaBczeaBcDeaBcDzaBzDeaBcDeaBczeaBcDeaBcDzaBcDeaBcDeaBzDeaBcDeaBcDeaBczeaBcDeaBcDeaBcDeaBzDeaBcDeaBcDeazcDeaBcDeaBcDeaBcDeaBcDezzzaBcDeFgHiJ"; - text[10]="aBcDeaBcDeaBczeaBcDzaBczeaBcDeaBczeaBcDeaBcDzaBcDeaBcDeazcDeaBcDeaBcDeaBzDzaBcDeazcDeaBcDeazcDeaBcDzaBcDeazcDeaBcDeaBczzaBcDeaBcDeaBzDeaBcDeaBcDzaBczeaBcDeaBcDeaBcDeaBczeaBcDeaBcDeaBcDzaBcDeaBcDeaBcDezBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDezBcDeaBcDeaBcDeaBzDeaBcDeaBcDezzzaBcDeFgHiJk"; - text[11]="aBcDeaBcDeaBcDeaBcDeaBzDeaBcDeaBcDzaBcDzaBcDeaBcDeaBcDeaBcDeazcDeaBcDzaBcDeaBcDeaBcDeaBcDzaBcDeaBcDzaBcDzaBcDeaBcDeaBcDeaBcDzzBcDeaBcDeaBcDeaBcDzaBcDzaBcDeaBzDeaBcDeaBcDezBcDeaBcDeazcDeaBcDeaBcDezBcDeaBcDeaBcDeazcDeaBcDeaBzDeaBcDeaBczeaBcDeazcDeaBcDezBcDeaBcDeaBcDeaBcDeaBcDezzzaBcDeFgHiJkL"; - text[12]="aBcDeaBcDeaBcDeaBcDeaBzDeaBcDeaBzDeaBcDeaBcDezBcDeaBcDeazcDeaBcDeaBcDeazcDeaBcDeaBczeaBcDeaBcDeaBcDezBcDeaBcDzaBcDeaBcDzaBcDeaBcDeaBcDeaBcDeaBcDeaBcDeaBcDeaBcDeaBcDeaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDzaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDeaBcDeaBcDeaBcDezzzaBcDeFgHiJkLm"; - text[13]="aBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDeaBcDeaBcDeaBcDeaBcDeaBcDeaBcDeaBcDeaBcDeaBcDeaBcDeaBcDeaBcDeaBcDeaBcDezzzaBcDeFgHiJkLmN"; - text[14]="aBcDeaBcDeaBcDzaBcDeaBcDeaBcDeaBcDzaBcDeaBcDeaBcDeaBcDzaBcDeaBcDeaBcDeaBcDzaBcDeaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDzaBcDezzzaBcDeFgHiJkLmNo"; - text[15]="aBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDzaBcDeaBcDzaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDzaBcDeaBcDzaBcDeaBcDzaBcDeaBcDzaBcDeaBcDzaBcDeaBcDzaBcDeaBcDeaBcDeaBcDezzzaBcDeFgHiJkLmNoP"; - + text[0] = "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzza"; + text[1] = "aaaaaaaaazaaaaaaaaaaaaaaaaaaaaazaaaaaaaaaaaaaazaaaaaaaaaaaaaaaaaaaaazaaaaaaaaaaaaaaa" + "aaaazaaaaaaaaaaaaaaaaaaazaaaaaaaaazaaaaaaaaaazaaaaaaaaaaaaazaaaaaaaaazaaaaaaaaaaaaaa" + "aaazaaaaaaaaaaaaaaaaazaaaaaaaaazaaaaaaaaaazaaaaaraaaaazaaaaaaazaaaaaaaaaaaaaazaaaaaa" + "aazaaaaaaaaazaaaaaaaaaaaaB"; + text[2] = "aBaBaBaBaBaBaBaBazaBaBaBaBaBaBazaBaBaBaBaBaBaBaBaBzBaBaBaBaBaBaBaBazaBaBaBaBaBaBaBzB" + "aBaBaBaBaBaBzBaBaBaBaBzBaBaBaBaBaBzBaBaBaBaBaBzBaBaBaBaBaBaBaBazaBaBaBaBaBaBaBaBaBaB" + "aBaBazaBaBaBaBaBaBaBaBaBzBaBaBaBaBaBaBaBzBaBaBaBaBaBaBaBaBaBzBaBaBaBaBaBaBaBaBaBaBaz" + "aBaBaBaBaBaBaBazaBaBaBaBaBc"; + text[3] = "aBcaBcaBcaBcaBczBcaBcaBzaBcaBcaBcaBcaBcaBcaBcaBcazcaBcaBcaBcaBcaBcaBcaBzaBcaBcaBcaBc" + "aBcaBczBcaBcaBcaBcaBcaBzaBcaBcaBcaBcaBcaBcaBcazcaBcaBcaBcaBcaBcaBcaBcaBczBcaBcaBcaBc" + "aBcaBcaBczBcaBcaBcaBcaBzaBcaBcaBcaBcaBcaBcaBcazcaBcaBcaBcaBcaBcazcaBcaBcaBcaBcaBcaBz" + "aBcaBcaBcazcaBcaBcaBcaBcaBcD"; + text[4] = "aBcDaBcDaBcDaBczaBcDaBcDaBcDaBcDaBczaBcDaBcDaBcDaBcDzBcDaBcDaBcDaBcDzBcDaBcDaBczaBcD" + "aBcDaBczaBcDaBcDaBcDaBcDaBzDaBcDaBcDaBcDaBcDaBcDaBcDaBcDaBczaBcDaBcDaBcDaBcDaBcDaBzD" + "aBcDaBcDaBcDaBzDaBcDaBcDaBzDaBcDaBcDaBcDaBcDaBcDaBczaBcDaBcDaBcDaBcDazcDaBcDaBcDaBcD" + "aBcDzBcDaBcDaBcDaBcDaBcDaBcDe"; + text[5] = "aBcDeaBcDeaBcDeazcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDezBcDeaBcDeaBcDzaBcDeaBcDeaBcDeazcD" + "zaBcDeaBcDezBcDeaBzDeaBcDeaBcDeazcDeaBcDeaBcDeaBcDzaBcDeaBcDeaBczeaBcDeaBcDeaBzDeaBc" + "DeaBcDezBcDeaBcDzaBcDeaBcDezBcDeaBcDezBcDeaBczeaBcDeaBcDeaBzDeaBcDezBcDeaBcDeaBcDeaB" + "cDeaBcDeaBcDeaBcDeaBcDezzzaBcDeF"; + text[6] = "aBcDeaBcDeaBcDeazcDeaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDeaBcDzaBcDeaBcDeaBcD" + "zaBcDeaBcDeaBcDeaBcDzaBzDeaBcDeaBcDeaBcDzaBcDzaBcDeaBcDeaBcDeaBcDzaBzDeaBcDeaBcDeaBc" + "zzaBcDeaBcDeaBcDzazcDeaBcDeaBcDeaBcDzaBzDeaBcDeaBcDeaBcDeazcDeaBcDeaBcDeaBcDeaBczeaB" + "cDeaBcDeaBcDeaBczeaBcDezzzaBcDeFg"; + text[7] = "aBcDeaBczeaBcDzaBcDezBcDeaBcDeaBcDeaBcDzaBzDeaBcDeaBcDeaBzDzaBcDeaBcDeazcDeaBcDzaBcD" + "eaBczeaBcDeaBcDeaBzDzaBcDeaBcDeaBcDezBcDzaBcDeaBzDeaBcDeaBcDezBcDzaBcDeaBcDeaBzDeaBc" + "DeaBcDeaBzDeaBcDeaBcDezBcDeaBcDeaBcDeazcDeaBcDeaBcDeaBcDzaBcDeaBcDeaBcDeaBcDzaBcDeaB" + "cDeaBcDeaBrDeaBcDeaBcDezzzaBcDeFgH"; + text[8] = "aBcDeaBcDeaBczzaBcDeazcDeaBcDezBcDeaBcDzaBcDeaBcDeaBcDeaBczzaBcDeaBcDeaBczeaBcDeaBcD" + "zzBcDeaBcDeaBcDzaBczeaBcDeaBcDzaBcDeaBczeaBcDeaBcDeaBzDeaBcDeaBcDeaBzDeaBcDeaBcDzaBc" + "DeaBcDeazcDeaBcDeaBcDzaBcDeaBcDeaBcDeazcDeaBcDeaBcDeaBcDeazcDeaBcDeaBcDeaBczeaBcDeaB" + "zDeaBcDeaBcDeaBcDeaBcDezzzaBcDeFgHi"; + text[9] = "aBcDeaBcDzaBcDzaBcDeaBcDeaBcDzaBcDeaBcDzaBcDeazcDeaBcDeaBcDzzBcDeaBcDeaBczeaBcDzaBcD" + "ezBcDeaBczeaBcDzaBcDezBcDeaBcDzaBczeaBcDeaBcDzaBcDeazcDeaBcDeaBcDzaBczeaBcDeaBcDzaBz" + "DeaBcDeaBczeaBcDeaBcDzaBcDeaBcDeaBzDeaBcDeaBcDeaBczeaBcDeaBcDeaBcDeaBzDeaBcDeaBcDeaz" + "cDeaBcDeaBcDeaBcDeaBcDezzzaBcDeFgHiJ"; + text[10] = "aBcDeaBcDeaBczeaBcDzaBczeaBcDeaBczeaBcDeaBcDzaBcDeaBcDeazcDeaBcDeaBcDeaBzDzaBcDeazc" + "DeaBcDeazcDeaBcDzaBcDeazcDeaBcDeaBczzaBcDeaBcDeaBzDeaBcDeaBcDzaBczeaBcDeaBcDeaBcDea" + "BczeaBcDeaBcDeaBcDzaBcDeaBcDeaBcDezBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDezBcD" + "eaBcDeaBcDeaBzDeaBcDeaBcDezzzaBcDeFgHiJk"; + text[11] = "aBcDeaBcDeaBcDeaBcDeaBzDeaBcDeaBcDzaBcDzaBcDeaBcDeaBcDeaBcDeazcDeaBcDzaBcDeaBcDeaBc" + "DeaBcDzaBcDeaBcDzaBcDzaBcDeaBcDeaBcDeaBcDzzBcDeaBcDeaBcDeaBcDzaBcDzaBcDeaBzDeaBcDea" + "BcDezBcDeaBcDeazcDeaBcDeaBcDezBcDeaBcDeaBcDeazcDeaBcDeaBzDeaBcDeaBczeaBcDeazcDeaBcD" + "ezBcDeaBcDeaBcDeaBcDeaBcDezzzaBcDeFgHiJkL"; + text[12] = "aBcDeaBcDeaBcDeaBcDeaBzDeaBcDeaBzDeaBcDeaBcDezBcDeaBcDeazcDeaBcDeaBcDeazcDeaBcDeaBc" + "zeaBcDeaBcDeaBcDezBcDeaBcDzaBcDeaBcDzaBcDeaBcDeaBcDeaBcDeaBcDeaBcDeaBcDeaBcDeaBcDea" + "BcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDzaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcD" + "eaBcDeaBcDeaBcDeaBcDeaBcDezzzaBcDeFgHiJkLm"; + text[13] = "aBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBc" + "DzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDea" + "BcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDeaBcDeaBcDeaBcDeaBcDeaBcDeaBcDeaBcDeaBcDeaBcD" + "eaBcDeaBcDeaBcDeaBcDeaBcDezzzaBcDeFgHiJkLmN"; + text[14] = "aBcDeaBcDeaBcDzaBcDeaBcDeaBcDeaBcDzaBcDeaBcDeaBcDeaBcDzaBcDeaBcDeaBcDeaBcDzaBcDeaBc" + "DeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDea" + "BcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcD" + "eaBcDeaBcDzaBcDeaBcDzaBcDezzzaBcDeFgHiJkLmNo"; + text[15] = "aBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDzaBc" + "DeaBcDeaBcDzaBcDeaBcDzaBcDeaBcDzaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDea" + "BcDzaBcDeaBcDzaBcDeaBcDeaBcDzaBcDeaBcDzaBcDeaBcDzaBcDeaBcDzaBcDeaBcDzaBcDeaBcDzaBcD" + "eaBcDzaBcDeaBcDeaBcDeaBcDezzzaBcDeFgHiJkLmNoP"; char *needle[16]; - needle[0]="a"; - needle[1]="aB"; - needle[2]="aBc"; - needle[3]="aBcD"; - needle[4]="aBcDe"; - needle[5]="aBcDeF"; - needle[6]="aBcDeFg"; - needle[7]="aBcDeFgH"; - needle[8]="aBcDeFgHi"; - needle[9]="aBcDeFgHiJ"; - needle[10]="aBcDeFgHiJk"; - needle[11]="aBcDeFgHiJkL"; - needle[12]="aBcDeFgHiJkLm"; - needle[13]="aBcDeFgHiJkLmN"; - needle[14]="aBcDeFgHiJkLmNo"; - needle[15]="aBcDeFgHiJkLmNoP"; + needle[0] = "a"; + needle[1] = "aB"; + needle[2] = "aBc"; + needle[3] = "aBcD"; + needle[4] = "aBcDe"; + needle[5] = "aBcDeF"; + needle[6] = "aBcDeFg"; + needle[7] = "aBcDeFgH"; + needle[8] = "aBcDeFgHi"; + needle[9] = "aBcDeFgHiJ"; + needle[10] = "aBcDeFgHiJk"; + needle[11] = "aBcDeFgHiJkL"; + needle[12] = "aBcDeFgHiJkLm"; + needle[13] = "aBcDeFgHiJkLmN"; + needle[14] = "aBcDeFgHiJkLmNo"; + needle[15] = "aBcDeFgHiJkLmNoP"; int i; uint8_t *found = NULL; - printf("\nStats for text of greater length:\n"); + printf("\nStats for text of greater length:\n"); for (i = 0; i < 16; i++) { printf("Pattern length %d with BasicSearch (Building Context):", i + 1); found = BasicSearchCtxWrapper((uint8_t *)text[i], (uint8_t *)needle[i], STATS_TIMES); @@ -1916,58 +2060,58 @@ static int UtilSpmSearchStatsTest04(void) static int UtilSpmSearchStatsTest05(void) { char *text[16]; - text[0]="zzzzzzzzzzzzzzzzzza"; - text[1]="zzzzzzzzzzzzzzzzzzaB"; - text[2]="zzzzzzzzzzzzzzzzzzaBc"; - text[3]="zzzzzzzzzzzzzzzzzzaBcD"; - text[4]="zzzzzzzzzzzzzzzzzzaBcDe"; - text[5]="zzzzzzzzzzzzzzzzzzzzaBcDeF"; - text[6]="zzzzzzzzzzzzzzzzzzzzaBcDeFg"; - text[7]="zzzzzzzzzzzzzzzzzzzzaBcDeFgH"; - text[8]="zzzzzzzzzzzzzzzzzzzzaBcDeFgHi"; - text[9]="zzzzzzzzzzzzzzzzzzzzaBcDeFgHiJ"; - text[10]="zzzzzzzzzzzzzzzzzzzzaBcDeFgHiJk"; - text[11]="zzzzzzzzzzzzzzzzzzzzaBcDeFgHiJkL"; - text[12]="zzzzzzzzzzzzzzzzzzzzaBcDeFgHiJkLm"; - text[13]="zzzzzzzzzzzzzzzzzzzzaBcDeFgHiJkLmN"; - text[14]="zzzzzzzzzzzzzzzzzzzzaBcDeFgHiJkLmNo"; - text[15]="zzzzzzzzzzzzzzzzzzzzaBcDeFgHiJkLmNoP"; + text[0] = "zzzzzzzzzzzzzzzzzza"; + text[1] = "zzzzzzzzzzzzzzzzzzaB"; + text[2] = "zzzzzzzzzzzzzzzzzzaBc"; + text[3] = "zzzzzzzzzzzzzzzzzzaBcD"; + text[4] = "zzzzzzzzzzzzzzzzzzaBcDe"; + text[5] = "zzzzzzzzzzzzzzzzzzzzaBcDeF"; + text[6] = "zzzzzzzzzzzzzzzzzzzzaBcDeFg"; + text[7] = "zzzzzzzzzzzzzzzzzzzzaBcDeFgH"; + text[8] = "zzzzzzzzzzzzzzzzzzzzaBcDeFgHi"; + text[9] = "zzzzzzzzzzzzzzzzzzzzaBcDeFgHiJ"; + text[10] = "zzzzzzzzzzzzzzzzzzzzaBcDeFgHiJk"; + text[11] = "zzzzzzzzzzzzzzzzzzzzaBcDeFgHiJkL"; + text[12] = "zzzzzzzzzzzzzzzzzzzzaBcDeFgHiJkLm"; + text[13] = "zzzzzzzzzzzzzzzzzzzzaBcDeFgHiJkLmN"; + text[14] = "zzzzzzzzzzzzzzzzzzzzaBcDeFgHiJkLmNo"; + text[15] = "zzzzzzzzzzzzzzzzzzzzaBcDeFgHiJkLmNoP"; char *needle[16]; - needle[0]="a"; - needle[1]="aB"; - needle[2]="aBc"; - needle[3]="aBcD"; - needle[4]="aBcDe"; - needle[5]="aBcDeF"; - needle[6]="aBcDeFg"; - needle[7]="aBcDeFgH"; - needle[8]="aBcDeFgHi"; - needle[9]="aBcDeFgHiJ"; - needle[10]="aBcDeFgHiJk"; - needle[11]="aBcDeFgHiJkL"; - needle[12]="aBcDeFgHiJkLm"; - needle[13]="aBcDeFgHiJkLmN"; - needle[14]="aBcDeFgHiJkLmNo"; - needle[15]="aBcDeFgHiJkLmNoP"; + needle[0] = "a"; + needle[1] = "aB"; + needle[2] = "aBc"; + needle[3] = "aBcD"; + needle[4] = "aBcDe"; + needle[5] = "aBcDeF"; + needle[6] = "aBcDeFg"; + needle[7] = "aBcDeFgH"; + needle[8] = "aBcDeFgHi"; + needle[9] = "aBcDeFgHiJ"; + needle[10] = "aBcDeFgHiJk"; + needle[11] = "aBcDeFgHiJkL"; + needle[12] = "aBcDeFgHiJkLm"; + needle[13] = "aBcDeFgHiJkLmN"; + needle[14] = "aBcDeFgHiJkLmNo"; + needle[15] = "aBcDeFgHiJkLmNoP"; int i; uint8_t *found = NULL; - printf("\nStats for text of lower length:\n"); + printf("\nStats for text of lower length:\n"); for (i = 0; i < 16; i++) { - printf("Pattern length %d with BasicSearch (Building Context):", i+1); + printf("Pattern length %d with BasicSearch (Building Context):", i + 1); found = BasicSearchCtxWrapper((uint8_t *)text[i], (uint8_t *)needle[i], STATS_TIMES); if (found == 0) { printf("Error1 searching for %s in text %s\n", needle[i], text[i]); return 0; } - printf("Pattern length %d with Bs2BmSearch (Building Context):", i+1); + printf("Pattern length %d with Bs2BmSearch (Building Context):", i + 1); found = Bs2bmCtxWrapper((uint8_t *)text[i], (uint8_t *)needle[i], STATS_TIMES); if (found == 0) { printf("Error2 searching for %s in text %s\n", needle[i], text[i]); return 0; } - printf("Pattern length %d with BoyerMooreSearch (Building Context):", i+1); + printf("Pattern length %d with BoyerMooreSearch (Building Context):", i + 1); found = BoyerMooreCtxWrapper((uint8_t *)text[i], (uint8_t *)needle[i], STATS_TIMES); if (found == 0) { printf("Error3 searching for %s in text %s\n", needle[i], text[i]); @@ -1978,40 +2122,39 @@ static int UtilSpmSearchStatsTest05(void) return 1; } - static int UtilSpmSearchStatsTest06(void) { char *text[16]; - text[0]="zzzzkzzzzzzzkzzzzzza"; - text[1]="BBBBkBBBBBBBkBBBBBaB"; - text[2]="BcBckcBcBcBckcBcBcaBc"; - text[3]="BcDBkDBcDBcDkcDBcDaBcD"; - text[4]="BcDekcDeBcDekcDezzaBcDe"; + text[0] = "zzzzkzzzzzzzkzzzzzza"; + text[1] = "BBBBkBBBBBBBkBBBBBaB"; + text[2] = "BcBckcBcBcBckcBcBcaBc"; + text[3] = "BcDBkDBcDBcDkcDBcDaBcD"; + text[4] = "BcDekcDeBcDekcDezzaBcDe"; char *needle[16]; - needle[0]="a"; - needle[1]="aB"; - needle[2]="aBc"; - needle[3]="aBcD"; - needle[4]="aBcDe"; + needle[0] = "a"; + needle[1] = "aB"; + needle[2] = "aBc"; + needle[3] = "aBcD"; + needle[4] = "aBcDe"; int i; uint8_t *found = NULL; - printf("\nStats for text of lower length (badcase for):\n"); + printf("\nStats for text of lower length (badcase for):\n"); for (i = 0; i < 5; i++) { - printf("Pattern length %d with BasicSearch (Building Context):", i+1); + printf("Pattern length %d with BasicSearch (Building Context):", i + 1); found = BasicSearchCtxWrapper((uint8_t *)text[i], (uint8_t *)needle[i], STATS_TIMES); if (found == 0) { printf("Error1 searching for %s in text %s\n", needle[i], text[i]); return 0; } - printf("Pattern length %d with Bs2BmSearch (Building Context):", i+1); + printf("Pattern length %d with Bs2BmSearch (Building Context):", i + 1); found = Bs2bmCtxWrapper((uint8_t *)text[i], (uint8_t *)needle[i], STATS_TIMES); if (found == 0) { printf("Error2 searching for %s in text %s\n", needle[i], text[i]); return 0; } - printf("Pattern length %d with BoyerMooreSearch (Building Context):", i+1); + printf("Pattern length %d with BoyerMooreSearch (Building Context):", i + 1); found = BoyerMooreCtxWrapper((uint8_t *)text[i], (uint8_t *)needle[i], STATS_TIMES); if (found == 0) { printf("Error3 searching for %s in text %s\n", needle[i], text[i]); @@ -2025,36 +2168,36 @@ static int UtilSpmSearchStatsTest06(void) static int UtilSpmSearchStatsTest07(void) { char *text[16]; - text[0]="zzzza"; - text[1]="BBBaB"; - text[2]="bbaBc"; - text[3]="aaBcD"; - text[4]="aBcDe"; + text[0] = "zzzza"; + text[1] = "BBBaB"; + text[2] = "bbaBc"; + text[3] = "aaBcD"; + text[4] = "aBcDe"; char *needle[16]; - needle[0]="a"; - needle[1]="aB"; - needle[2]="aBc"; - needle[3]="aBcD"; - needle[4]="aBcDe"; + needle[0] = "a"; + needle[1] = "aB"; + needle[2] = "aBc"; + needle[3] = "aBcD"; + needle[4] = "aBcDe"; int i; uint8_t *found = NULL; - printf("\nStats for text of real lower length (badcase for):\n"); + printf("\nStats for text of real lower length (badcase for):\n"); for (i = 0; i < 5; i++) { - printf("Pattern length %d with BasicSearch (Building Context):", i+1); + printf("Pattern length %d with BasicSearch (Building Context):", i + 1); found = BasicSearchCtxWrapper((uint8_t *)text[i], (uint8_t *)needle[i], STATS_TIMES); if (found == 0) { printf("Error1 searching for %s in text %s\n", needle[i], text[i]); return 0; } - printf("Pattern length %d with Bs2BmSearch (Building Context):", i+1); + printf("Pattern length %d with Bs2BmSearch (Building Context):", i + 1); found = Bs2bmCtxWrapper((uint8_t *)text[i], (uint8_t *)needle[i], STATS_TIMES); if (found == 0) { printf("Error2 searching for %s in text %s\n", needle[i], text[i]); return 0; } - printf("Pattern length %d with BoyerMooreSearch (Building Context):", i+1); + printf("Pattern length %d with BoyerMooreSearch (Building Context):", i + 1); found = BoyerMooreCtxWrapper((uint8_t *)text[i], (uint8_t *)needle[i], STATS_TIMES); if (found == 0) { printf("Error3 searching for %s in text %s\n", needle[i], text[i]); @@ -2071,58 +2214,154 @@ static int UtilSpmSearchStatsTest07(void) static int UtilSpmNocaseSearchStatsTest01(void) { char *text[16]; - text[0]="zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzza"; - text[1]="zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzaB"; - text[2]="zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzaBc"; - text[3]="zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzaBcD"; - text[4]="zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzaBcDe"; - text[5]="zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzaBcDeF"; - text[6]="zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzaBcDeFg"; - text[7]="zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzaBcDeFgH"; - text[8]="zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzaBcDeFgHi"; - text[9]="zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzaBcDeFgHiJ"; - text[10]="zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzaBcDeFgHiJk"; - text[11]="zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzaBcDeFgHiJkL"; - text[12]="zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzaBcDeFgHiJkLm"; - text[13]="zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzaBcDeFgHiJkLmN"; - text[14]="zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzaBcDeFgHiJkLmNo"; - text[15]="zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzaBcDeFgHiJkLmNoP"; + text[0] = "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzza"; + text[1] = "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzaB"; + text[2] = "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzaBc"; + text[3] = "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzaBcD"; + text[4] = "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzaBcDe"; + text[5] = "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzaBcDeF"; + text[6] = "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzaBcDeFg"; + text[7] = "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzaBcDeFgH"; + text[8] = "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzaBcDeFgHi"; + text[9] = "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzaBcDeFgHiJ"; + text[10] = "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzaBcDeFgHiJk"; + text[11] = "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzaBcDeFgHiJkL"; + text[12] = "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzaBcDeFgHiJkLm"; + text[13] = "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzaBcDeFgHiJkLmN"; + text[14] = "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzaBcDeFgHiJkLmNo"; + text[15] = "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzaBcDeFgHiJkLmNoP"; char *needle[16]; - needle[0]="a"; - needle[1]="aB"; - needle[2]="aBc"; - needle[3]="aBcD"; - needle[4]="aBcDe"; - needle[5]="aBcDeF"; - needle[6]="aBcDeFg"; - needle[7]="aBcDeFgH"; - needle[8]="aBcDeFgHi"; - needle[9]="aBcDeFgHiJ"; - needle[10]="aBcDeFgHiJk"; - needle[11]="aBcDeFgHiJkL"; - needle[12]="aBcDeFgHiJkLm"; - needle[13]="aBcDeFgHiJkLmN"; - needle[14]="aBcDeFgHiJkLmNo"; - needle[15]="aBcDeFgHiJkLmNoP"; + needle[0] = "a"; + needle[1] = "aB"; + needle[2] = "aBc"; + needle[3] = "aBcD"; + needle[4] = "aBcDe"; + needle[5] = "aBcDeF"; + needle[6] = "aBcDeFg"; + needle[7] = "aBcDeFgH"; + needle[8] = "aBcDeFgHi"; + needle[9] = "aBcDeFgHiJ"; + needle[10] = "aBcDeFgHiJk"; + needle[11] = "aBcDeFgHiJkL"; + needle[12] = "aBcDeFgHiJkLm"; + needle[13] = "aBcDeFgHiJkLmN"; + needle[14] = "aBcDeFgHiJkLmNo"; + needle[15] = "aBcDeFgHiJkLmNoP"; int i; uint8_t *found = NULL; - printf("\nStats for text of greater length:\n"); + printf("\nStats for text of greater length:\n"); for (i = 0; i < 16; i++) { - printf("Pattern length %d with BasicSearch:", i+1); + printf("Pattern length %d with BasicSearch:", i + 1); found = BasicSearchNocaseWrapper((uint8_t *)text[i], (uint8_t *)needle[i], STATS_TIMES); if (found == 0) { printf("Error1 searching for %s in text %s\n", needle[i], text[i]); return 0; } - printf("Pattern length %d with Bs2BmSearch:", i+1); + printf("Pattern length %d with Bs2BmSearch:", i + 1); found = Bs2bmNocaseWrapper((uint8_t *)text[i], (uint8_t *)needle[i], STATS_TIMES); if (found == 0) { printf("Error2 searching for %s in text %s\n", needle[i], text[i]); return 0; } - printf("Pattern length %d with BoyerMooreSearch:", i+1); + printf("Pattern length %d with BoyerMooreSearch:", i + 1); found = BoyerMooreNocaseWrapper((uint8_t *)text[i], (uint8_t *)needle[i], STATS_TIMES); if (found == 0) { printf("Error3 searching for %s in text %s\n", needle[i], text[i]); @@ -2136,58 +2375,58 @@ static int UtilSpmNocaseSearchStatsTest01(void) static int UtilSpmNocaseSearchStatsTest02(void) { char *text[16]; - text[0]="zzzzzzzzzzzzzzzzzza"; - text[1]="zzzzzzzzzzzzzzzzzzaB"; - text[2]="zzzzzzzzzzzzzzzzzzaBc"; - text[3]="zzzzzzzzzzzzzzzzzzaBcD"; - text[4]="zzzzzzzzzzzzzzzzzzaBcDe"; - text[5]="zzzzzzzzzzzzzzzzzzzzaBcDeF"; - text[6]="zzzzzzzzzzzzzzzzzzzzaBcDeFg"; - text[7]="zzzzzzzzzzzzzzzzzzzzaBcDeFgH"; - text[8]="zzzzzzzzzzzzzzzzzzzzaBcDeFgHi"; - text[9]="zzzzzzzzzzzzzzzzzzzzaBcDeFgHiJ"; - text[10]="zzzzzzzzzzzzzzzzzzzzaBcDeFgHiJk"; - text[11]="zzzzzzzzzzzzzzzzzzzzaBcDeFgHiJkL"; - text[12]="zzzzzzzzzzzzzzzzzzzzaBcDeFgHiJkLm"; - text[13]="zzzzzzzzzzzzzzzzzzzzaBcDeFgHiJkLmN"; - text[14]="zzzzzzzzzzzzzzzzzzzzaBcDeFgHiJkLmNo"; - text[15]="zzzzzzzzzzzzzzzzzzzzaBcDeFgHiJkLmNoP"; + text[0] = "zzzzzzzzzzzzzzzzzza"; + text[1] = "zzzzzzzzzzzzzzzzzzaB"; + text[2] = "zzzzzzzzzzzzzzzzzzaBc"; + text[3] = "zzzzzzzzzzzzzzzzzzaBcD"; + text[4] = "zzzzzzzzzzzzzzzzzzaBcDe"; + text[5] = "zzzzzzzzzzzzzzzzzzzzaBcDeF"; + text[6] = "zzzzzzzzzzzzzzzzzzzzaBcDeFg"; + text[7] = "zzzzzzzzzzzzzzzzzzzzaBcDeFgH"; + text[8] = "zzzzzzzzzzzzzzzzzzzzaBcDeFgHi"; + text[9] = "zzzzzzzzzzzzzzzzzzzzaBcDeFgHiJ"; + text[10] = "zzzzzzzzzzzzzzzzzzzzaBcDeFgHiJk"; + text[11] = "zzzzzzzzzzzzzzzzzzzzaBcDeFgHiJkL"; + text[12] = "zzzzzzzzzzzzzzzzzzzzaBcDeFgHiJkLm"; + text[13] = "zzzzzzzzzzzzzzzzzzzzaBcDeFgHiJkLmN"; + text[14] = "zzzzzzzzzzzzzzzzzzzzaBcDeFgHiJkLmNo"; + text[15] = "zzzzzzzzzzzzzzzzzzzzaBcDeFgHiJkLmNoP"; char *needle[16]; - needle[0]="a"; - needle[1]="aB"; - needle[2]="aBc"; - needle[3]="aBcD"; - needle[4]="aBcDe"; - needle[5]="aBcDeF"; - needle[6]="aBcDeFg"; - needle[7]="aBcDeFgH"; - needle[8]="aBcDeFgHi"; - needle[9]="aBcDeFgHiJ"; - needle[10]="aBcDeFgHiJk"; - needle[11]="aBcDeFgHiJkL"; - needle[12]="aBcDeFgHiJkLm"; - needle[13]="aBcDeFgHiJkLmN"; - needle[14]="aBcDeFgHiJkLmNo"; - needle[15]="aBcDeFgHiJkLmNoP"; + needle[0] = "a"; + needle[1] = "aB"; + needle[2] = "aBc"; + needle[3] = "aBcD"; + needle[4] = "aBcDe"; + needle[5] = "aBcDeF"; + needle[6] = "aBcDeFg"; + needle[7] = "aBcDeFgH"; + needle[8] = "aBcDeFgHi"; + needle[9] = "aBcDeFgHiJ"; + needle[10] = "aBcDeFgHiJk"; + needle[11] = "aBcDeFgHiJkL"; + needle[12] = "aBcDeFgHiJkLm"; + needle[13] = "aBcDeFgHiJkLmN"; + needle[14] = "aBcDeFgHiJkLmNo"; + needle[15] = "aBcDeFgHiJkLmNoP"; int i; uint8_t *found = NULL; - printf("\nStats for text of lower length:\n"); + printf("\nStats for text of lower length:\n"); for (i = 0; i < 16; i++) { - printf("Pattern length %d with BasicSearch:", i+1); + printf("Pattern length %d with BasicSearch:", i + 1); found = BasicSearchNocaseWrapper((uint8_t *)text[i], (uint8_t *)needle[i], STATS_TIMES); if (found == 0) { printf("Error1 searching for %s in text %s\n", needle[i], text[i]); return 0; } - printf("Pattern length %d with Bs2BmSearch:", i+1); + printf("Pattern length %d with Bs2BmSearch:", i + 1); found = Bs2bmNocaseWrapper((uint8_t *)text[i], (uint8_t *)needle[i], STATS_TIMES); if (found == 0) { printf("Error2 searching for %s in text %s\n", needle[i], text[i]); return 0; } - printf("Pattern length %d with BoyerMooreSearch:", i+1); + printf("Pattern length %d with BoyerMooreSearch:", i + 1); found = BoyerMooreNocaseWrapper((uint8_t *)text[i], (uint8_t *)needle[i], STATS_TIMES); if (found == 0) { printf("Error3 searching for %s in text %s\n", needle[i], text[i]); @@ -2198,40 +2437,39 @@ static int UtilSpmNocaseSearchStatsTest02(void) return 1; } - static int UtilSpmNocaseSearchStatsTest03(void) { char *text[16]; - text[0]="zzzzkzzzzzzzkzzzzzza"; - text[1]="BBBBkBBBBBBBkBBBBBaB"; - text[2]="BcBckcBcBcBckcBcBcaBc"; - text[3]="BcDBkDBcDBcDkcDBcDaBcD"; - text[4]="BcDekcDeBcDekcDezzaBcDe"; + text[0] = "zzzzkzzzzzzzkzzzzzza"; + text[1] = "BBBBkBBBBBBBkBBBBBaB"; + text[2] = "BcBckcBcBcBckcBcBcaBc"; + text[3] = "BcDBkDBcDBcDkcDBcDaBcD"; + text[4] = "BcDekcDeBcDekcDezzaBcDe"; char *needle[16]; - needle[0]="a"; - needle[1]="aB"; - needle[2]="aBc"; - needle[3]="aBcD"; - needle[4]="aBcDe"; + needle[0] = "a"; + needle[1] = "aB"; + needle[2] = "aBc"; + needle[3] = "aBcD"; + needle[4] = "aBcDe"; int i; uint8_t *found = NULL; - printf("\nStats for text of lower length (badcase for):\n"); + printf("\nStats for text of lower length (badcase for):\n"); for (i = 0; i < 5; i++) { - printf("Pattern length %d with BasicSearch:", i+1); + printf("Pattern length %d with BasicSearch:", i + 1); found = BasicSearchNocaseWrapper((uint8_t *)text[i], (uint8_t *)needle[i], STATS_TIMES); if (found == 0) { printf("Error1 searching for %s in text %s\n", needle[i], text[i]); return 0; } - printf("Pattern length %d with Bs2BmSearch:", i+1); + printf("Pattern length %d with Bs2BmSearch:", i + 1); found = Bs2bmNocaseWrapper((uint8_t *)text[i], (uint8_t *)needle[i], STATS_TIMES); if (found == 0) { printf("Error2 searching for %s in text %s\n", needle[i], text[i]); return 0; } - printf("Pattern length %d with BoyerMooreSearch:", i+1); + printf("Pattern length %d with BoyerMooreSearch:", i + 1); found = BoyerMooreNocaseWrapper((uint8_t *)text[i], (uint8_t *)needle[i], STATS_TIMES); if (found == 0) { printf("Error3 searching for %s in text %s\n", needle[i], text[i]); @@ -2248,58 +2486,213 @@ static int UtilSpmNocaseSearchStatsTest03(void) static int UtilSpmNocaseSearchStatsTest04(void) { char *text[16]; - text[0]="zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzza"; - text[1]="zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzaB"; - text[2]="zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzaBc"; - text[3]="zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzaBcD"; - text[4]="zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzaBcDe"; - text[5]="zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzaBcDeF"; - text[6]="zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzaBcDeFg"; - text[7]="zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzaBcDeFgH"; - text[8]="zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzaBcDeFgHi"; - text[9]="zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzaBcDeFgHiJ"; - text[10]="zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzaBcDeFgHiJk"; - text[11]="zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzaBcDeFgHiJkL"; - text[12]="zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzaBcDeFgHiJkLm"; - text[13]="zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzaBcDeFgHiJkLmN"; - text[14]="zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzaBcDeFgHiJkLmNo"; - text[15]="zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzaBcDeFgHiJkLmNoP"; + text[0] = "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzza"; + text[1] = "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzaB"; + text[2] = "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzaBc"; + text[3] = "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzaBcD"; + text[4] = "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzaBcDe"; + text[5] = + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzaBcDeF"; + text[6] = + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzaBcDeFg"; + text[7] = + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzaBcDeFgH"; + text[8] = + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzaBcDeFgHi"; + text[9] = + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzaBcDeFgHiJ"; + text[10] = + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzaBcDeFgHiJk"; + text[11] = + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzaBcDeFgHiJkL"; + text[12] = + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzaBcDeFgHiJkLm"; + text[13] = + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzaBcDeFgHiJkLmN"; + text[14] = + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzaBcDeFgHiJkLmNo"; + text[15] = + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" + "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzaBcDeFgHiJkLmNoP"; char *needle[16]; - needle[0]="a"; - needle[1]="aB"; - needle[2]="aBc"; - needle[3]="aBcD"; - needle[4]="aBcDe"; - needle[5]="aBcDeF"; - needle[6]="aBcDeFg"; - needle[7]="aBcDeFgH"; - needle[8]="aBcDeFgHi"; - needle[9]="aBcDeFgHiJ"; - needle[10]="aBcDeFgHiJk"; - needle[11]="aBcDeFgHiJkL"; - needle[12]="aBcDeFgHiJkLm"; - needle[13]="aBcDeFgHiJkLmN"; - needle[14]="aBcDeFgHiJkLmNo"; - needle[15]="aBcDeFgHiJkLmNoP"; + needle[0] = "a"; + needle[1] = "aB"; + needle[2] = "aBc"; + needle[3] = "aBcD"; + needle[4] = "aBcDe"; + needle[5] = "aBcDeF"; + needle[6] = "aBcDeFg"; + needle[7] = "aBcDeFgH"; + needle[8] = "aBcDeFgHi"; + needle[9] = "aBcDeFgHiJ"; + needle[10] = "aBcDeFgHiJk"; + needle[11] = "aBcDeFgHiJkL"; + needle[12] = "aBcDeFgHiJkLm"; + needle[13] = "aBcDeFgHiJkLmN"; + needle[14] = "aBcDeFgHiJkLmNo"; + needle[15] = "aBcDeFgHiJkLmNoP"; int i; uint8_t *found = NULL; - printf("\nStats for text of greater length:\n"); + printf("\nStats for text of greater length:\n"); for (i = 0; i < 16; i++) { - printf("Pattern length %d with BasicSearch (Building Context):", i+1); + printf("Pattern length %d with BasicSearch (Building Context):", i + 1); found = BasicSearchNocaseCtxWrapper((uint8_t *)text[i], (uint8_t *)needle[i], STATS_TIMES); if (found == 0) { printf("Error1 searching for %s in text %s\n", needle[i], text[i]); return 0; } - printf("Pattern length %d with Bs2BmSearch (Building Context):", i+1); + printf("Pattern length %d with Bs2BmSearch (Building Context):", i + 1); found = Bs2bmNocaseCtxWrapper((uint8_t *)text[i], (uint8_t *)needle[i], STATS_TIMES); if (found == 0) { printf("Error2 searching for %s in text %s\n", needle[i], text[i]); return 0; } - printf("Pattern length %d with BoyerMooreSearch (Building Context):", i+1); + printf("Pattern length %d with BoyerMooreSearch (Building Context):", i + 1); found = BoyerMooreNocaseCtxWrapper((uint8_t *)text[i], (uint8_t *)needle[i], STATS_TIMES); if (found == 0) { printf("Error3 searching for %s in text %s\n", needle[i], text[i]); @@ -2313,58 +2706,58 @@ static int UtilSpmNocaseSearchStatsTest04(void) static int UtilSpmNocaseSearchStatsTest05(void) { char *text[16]; - text[0]="zzzzzzzzzzzzzzzzzza"; - text[1]="zzzzzzzzzzzzzzzzzzaB"; - text[2]="zzzzzzzzzzzzzzzzzzaBc"; - text[3]="zzzzzzzzzzzzzzzzzzaBcD"; - text[4]="zzzzzzzzzzzzzzzzzzaBcDe"; - text[5]="zzzzzzzzzzzzzzzzzzzzaBcDeF"; - text[6]="zzzzzzzzzzzzzzzzzzzzaBcDeFg"; - text[7]="zzzzzzzzzzzzzzzzzzzzaBcDeFgH"; - text[8]="zzzzzzzzzzzzzzzzzzzzaBcDeFgHi"; - text[9]="zzzzzzzzzzzzzzzzzzzzaBcDeFgHiJ"; - text[10]="zzzzzzzzzzzzzzzzzzzzaBcDeFgHiJk"; - text[11]="zzzzzzzzzzzzzzzzzzzzaBcDeFgHiJkL"; - text[12]="zzzzzzzzzzzzzzzzzzzzaBcDeFgHiJkLm"; - text[13]="zzzzzzzzzzzzzzzzzzzzaBcDeFgHiJkLmN"; - text[14]="zzzzzzzzzzzzzzzzzzzzaBcDeFgHiJkLmNo"; - text[15]="zzzzzzzzzzzzzzzzzzzzaBcDeFgHiJkLmNoP"; + text[0] = "zzzzzzzzzzzzzzzzzza"; + text[1] = "zzzzzzzzzzzzzzzzzzaB"; + text[2] = "zzzzzzzzzzzzzzzzzzaBc"; + text[3] = "zzzzzzzzzzzzzzzzzzaBcD"; + text[4] = "zzzzzzzzzzzzzzzzzzaBcDe"; + text[5] = "zzzzzzzzzzzzzzzzzzzzaBcDeF"; + text[6] = "zzzzzzzzzzzzzzzzzzzzaBcDeFg"; + text[7] = "zzzzzzzzzzzzzzzzzzzzaBcDeFgH"; + text[8] = "zzzzzzzzzzzzzzzzzzzzaBcDeFgHi"; + text[9] = "zzzzzzzzzzzzzzzzzzzzaBcDeFgHiJ"; + text[10] = "zzzzzzzzzzzzzzzzzzzzaBcDeFgHiJk"; + text[11] = "zzzzzzzzzzzzzzzzzzzzaBcDeFgHiJkL"; + text[12] = "zzzzzzzzzzzzzzzzzzzzaBcDeFgHiJkLm"; + text[13] = "zzzzzzzzzzzzzzzzzzzzaBcDeFgHiJkLmN"; + text[14] = "zzzzzzzzzzzzzzzzzzzzaBcDeFgHiJkLmNo"; + text[15] = "zzzzzzzzzzzzzzzzzzzzaBcDeFgHiJkLmNoP"; char *needle[16]; - needle[0]="a"; - needle[1]="aB"; - needle[2]="aBc"; - needle[3]="aBcD"; - needle[4]="aBcDe"; - needle[5]="aBcDeF"; - needle[6]="aBcDeFg"; - needle[7]="aBcDeFgH"; - needle[8]="aBcDeFgHi"; - needle[9]="aBcDeFgHiJ"; - needle[10]="aBcDeFgHiJk"; - needle[11]="aBcDeFgHiJkL"; - needle[12]="aBcDeFgHiJkLm"; - needle[13]="aBcDeFgHiJkLmN"; - needle[14]="aBcDeFgHiJkLmNo"; - needle[15]="aBcDeFgHiJkLmNoP"; + needle[0] = "a"; + needle[1] = "aB"; + needle[2] = "aBc"; + needle[3] = "aBcD"; + needle[4] = "aBcDe"; + needle[5] = "aBcDeF"; + needle[6] = "aBcDeFg"; + needle[7] = "aBcDeFgH"; + needle[8] = "aBcDeFgHi"; + needle[9] = "aBcDeFgHiJ"; + needle[10] = "aBcDeFgHiJk"; + needle[11] = "aBcDeFgHiJkL"; + needle[12] = "aBcDeFgHiJkLm"; + needle[13] = "aBcDeFgHiJkLmN"; + needle[14] = "aBcDeFgHiJkLmNo"; + needle[15] = "aBcDeFgHiJkLmNoP"; int i; uint8_t *found = NULL; - printf("\nStats for text of lower length:\n"); + printf("\nStats for text of lower length:\n"); for (i = 0; i < 16; i++) { - printf("Pattern length %d with BasicSearch (Building Context):", i+1); + printf("Pattern length %d with BasicSearch (Building Context):", i + 1); found = BasicSearchNocaseCtxWrapper((uint8_t *)text[i], (uint8_t *)needle[i], STATS_TIMES); if (found == 0) { printf("Error1 searching for %s in text %s\n", needle[i], text[i]); return 0; } - printf("Pattern length %d with Bs2BmSearch (Building Context):", i+1); + printf("Pattern length %d with Bs2BmSearch (Building Context):", i + 1); found = Bs2bmNocaseCtxWrapper((uint8_t *)text[i], (uint8_t *)needle[i], STATS_TIMES); if (found == 0) { printf("Error2 searching for %s in text %s\n", needle[i], text[i]); return 0; } - printf("Pattern length %d with BoyerMooreSearch (Building Context):", i+1); + printf("Pattern length %d with BoyerMooreSearch (Building Context):", i + 1); found = BoyerMooreNocaseCtxWrapper((uint8_t *)text[i], (uint8_t *)needle[i], STATS_TIMES); if (found == 0) { printf("Error3 searching for %s in text %s\n", needle[i], text[i]); @@ -2375,40 +2768,39 @@ static int UtilSpmNocaseSearchStatsTest05(void) return 1; } - static int UtilSpmNocaseSearchStatsTest06(void) { char *text[16]; - text[0]="zzzzkzzzzzzzkzzzzzza"; - text[1]="BBBBkBBBBBBBkBBBBBaB"; - text[2]="BcBckcBcBcBckcBcBcaBc"; - text[3]="BcDBkDBcDBcDkcDBcDaBcD"; - text[4]="BcDekcDeBcDekcDezzaBcDe"; + text[0] = "zzzzkzzzzzzzkzzzzzza"; + text[1] = "BBBBkBBBBBBBkBBBBBaB"; + text[2] = "BcBckcBcBcBckcBcBcaBc"; + text[3] = "BcDBkDBcDBcDkcDBcDaBcD"; + text[4] = "BcDekcDeBcDekcDezzaBcDe"; char *needle[16]; - needle[0]="a"; - needle[1]="aB"; - needle[2]="aBc"; - needle[3]="aBcD"; - needle[4]="aBcDe"; + needle[0] = "a"; + needle[1] = "aB"; + needle[2] = "aBc"; + needle[3] = "aBcD"; + needle[4] = "aBcDe"; int i; uint8_t *found = NULL; - printf("\nStats for text of lower length (badcase for):\n"); + printf("\nStats for text of lower length (badcase for):\n"); for (i = 0; i < 5; i++) { - printf("Pattern length %d with BasicSearch (Building Context):", i+1); + printf("Pattern length %d with BasicSearch (Building Context):", i + 1); found = BasicSearchNocaseCtxWrapper((uint8_t *)text[i], (uint8_t *)needle[i], STATS_TIMES); if (found == 0) { printf("Error1 searching for %s in text %s\n", needle[i], text[i]); return 0; } - printf("Pattern length %d with Bs2BmSearch (Building Context):", i+1); + printf("Pattern length %d with Bs2BmSearch (Building Context):", i + 1); found = Bs2bmNocaseCtxWrapper((uint8_t *)text[i], (uint8_t *)needle[i], STATS_TIMES); if (found == 0) { printf("Error2 searching for %s in text %s\n", needle[i], text[i]); return 0; } - printf("Pattern length %d with BoyerMooreSearch (Building Context):", i+1); + printf("Pattern length %d with BoyerMooreSearch (Building Context):", i + 1); found = BoyerMooreNocaseCtxWrapper((uint8_t *)text[i], (uint8_t *)needle[i], STATS_TIMES); if (found == 0) { printf("Error3 searching for %s in text %s\n", needle[i], text[i]); @@ -2422,36 +2814,36 @@ static int UtilSpmNocaseSearchStatsTest06(void) static int UtilSpmNocaseSearchStatsTest07(void) { char *text[16]; - text[0]="zzzza"; - text[1]="bbbAb"; - text[2]="bbAbC"; - text[3]="bAbCd"; - text[4]="AbCdE"; + text[0] = "zzzza"; + text[1] = "bbbAb"; + text[2] = "bbAbC"; + text[3] = "bAbCd"; + text[4] = "AbCdE"; char *needle[16]; - needle[0]="a"; - needle[1]="aB"; - needle[2]="aBc"; - needle[3]="aBcD"; - needle[4]="aBcDe"; + needle[0] = "a"; + needle[1] = "aB"; + needle[2] = "aBc"; + needle[3] = "aBcD"; + needle[4] = "aBcDe"; int i; uint8_t *found = NULL; - printf("\nStats for text of real lower length (badcase for):\n"); + printf("\nStats for text of real lower length (badcase for):\n"); for (i = 0; i < 5; i++) { - printf("Pattern length %d with BasicSearch (Building Context):", i+1); + printf("Pattern length %d with BasicSearch (Building Context):", i + 1); found = BasicSearchNocaseCtxWrapper((uint8_t *)text[i], (uint8_t *)needle[i], STATS_TIMES); if (found == 0) { printf("Error1 searching for %s in text %s\n", needle[i], text[i]); return 0; } - printf("Pattern length %d with Bs2BmSearch (Building Context):", i+1); + printf("Pattern length %d with Bs2BmSearch (Building Context):", i + 1); found = Bs2bmNocaseCtxWrapper((uint8_t *)text[i], (uint8_t *)needle[i], STATS_TIMES); if (found == 0) { printf("Error2 searching for %s in text %s\n", needle[i], text[i]); return 0; } - printf("Pattern length %d with BoyerMooreSearch (Building Context):", i+1); + printf("Pattern length %d with BoyerMooreSearch (Building Context):", i + 1); found = BoyerMooreNocaseCtxWrapper((uint8_t *)text[i], (uint8_t *)needle[i], STATS_TIMES); if (found == 0) { printf("Error3 searching for %s in text %s\n", needle[i], text[i]); @@ -2492,8 +2884,7 @@ static int SpmTestSearch(const SpmTestData *d, uint8_t matcher) goto exit; } - ctx = SpmInitCtx((const uint8_t *)d->needle, d->needle_len, d->nocase, - global_thread_ctx); + ctx = SpmInitCtx((const uint8_t *)d->needle, d->needle_len, d->nocase, global_thread_ctx); if (ctx == NULL) { ret = 0; goto exit; @@ -2505,20 +2896,17 @@ static int SpmTestSearch(const SpmTestData *d, uint8_t matcher) goto exit; } - found = SpmScan(ctx, thread_ctx, (const uint8_t *)d->haystack, - d->haystack_len); + found = SpmScan(ctx, thread_ctx, (const uint8_t *)d->haystack, d->haystack_len); if (found == NULL) { if (d->match_offset != SPM_NO_MATCH) { - printf(" should have matched at %" PRIu32 " but didn't\n", - d->match_offset); + printf(" should have matched at %" PRIu32 " but didn't\n", d->match_offset); ret = 0; } } else { uint32_t offset = (uint32_t)(found - (const uint8_t *)d->haystack); if (offset != d->match_offset) { - printf(" should have matched at %" PRIu32 - " but matched at %" PRIu32 "\n", - d->match_offset, offset); + printf(" should have matched at %" PRIu32 " but matched at %" PRIu32 "\n", + d->match_offset, offset); ret = 0; } } @@ -2530,7 +2918,8 @@ static int SpmTestSearch(const SpmTestData *d, uint8_t matcher) return ret; } -static int SpmSearchTest01(void) { +static int SpmSearchTest01(void) +{ SpmTableSetup(); printf("\n"); @@ -2539,35 +2928,35 @@ static int SpmSearchTest01(void) { static const SpmTestData data[] = { /* Some trivial single-character case/nocase tests */ - {"a", 1, "a", 1, 0, 0}, - {"a", 1, "A", 1, 1, 0}, - {"A", 1, "A", 1, 0, 0}, - {"A", 1, "a", 1, 1, 0}, - {"a", 1, "A", 1, 0, SPM_NO_MATCH}, - {"A", 1, "a", 1, 0, SPM_NO_MATCH}, + { "a", 1, "a", 1, 0, 0 }, + { "a", 1, "A", 1, 1, 0 }, + { "A", 1, "A", 1, 0, 0 }, + { "A", 1, "a", 1, 1, 0 }, + { "a", 1, "A", 1, 0, SPM_NO_MATCH }, + { "A", 1, "a", 1, 0, SPM_NO_MATCH }, /* Nulls and odd characters */ - {"\x00", 1, "test\x00test", 9, 0, 4}, - {"\x00", 1, "testtest", 8, 0, SPM_NO_MATCH}, - {"\n", 1, "new line\n", 9, 0, 8}, - {"\n", 1, "new line\x00\n", 10, 0, 9}, - {"\xff", 1, "abcdef\xff", 7, 0, 6}, - {"\xff", 1, "abcdef\xff", 7, 1, 6}, - {"$", 1, "dollar$", 7, 0, 6}, - {"^", 1, "caret^", 6, 0, 5}, + { "\x00", 1, "test\x00test", 9, 0, 4 }, + { "\x00", 1, "testtest", 8, 0, SPM_NO_MATCH }, + { "\n", 1, "new line\n", 9, 0, 8 }, + { "\n", 1, "new line\x00\n", 10, 0, 9 }, + { "\xff", 1, "abcdef\xff", 7, 0, 6 }, + { "\xff", 1, "abcdef\xff", 7, 1, 6 }, + { "$", 1, "dollar$", 7, 0, 6 }, + { "^", 1, "caret^", 6, 0, 5 }, /* Longer literals */ - {"Suricata", 8, "This is a Suricata test", 23, 0, 10}, - {"Suricata", 8, "This is a suricata test", 23, 1, 10}, - {"Suricata", 8, "This is a suriCATA test", 23, 1, 10}, - {"suricata", 8, "This is a Suricata test", 23, 0, SPM_NO_MATCH}, - {"Suricata", 8, "This is a Suricat_ test", 23, 0, SPM_NO_MATCH}, - {"Suricata", 8, "This is a _uricata test", 23, 0, SPM_NO_MATCH}, + { "Suricata", 8, "This is a Suricata test", 23, 0, 10 }, + { "Suricata", 8, "This is a suricata test", 23, 1, 10 }, + { "Suricata", 8, "This is a suriCATA test", 23, 1, 10 }, + { "suricata", 8, "This is a Suricata test", 23, 0, SPM_NO_MATCH }, + { "Suricata", 8, "This is a Suricat_ test", 23, 0, SPM_NO_MATCH }, + { "Suricata", 8, "This is a _uricata test", 23, 0, SPM_NO_MATCH }, /* First occurrence with the correct case should match */ - {"foo", 3, "foofoofoo", 9, 0, 0}, - {"foo", 3, "_foofoofoo", 9, 0, 1}, - {"FOO", 3, "foofoofoo", 9, 1, 0}, - {"FOO", 3, "_foofoofoo", 9, 1, 1}, - {"FOO", 3, "foo Foo FOo fOo foO FOO", 23, 0, 20}, - {"foo", 3, "Foo FOo fOo foO FOO foo", 23, 0, 20}, + { "foo", 3, "foofoofoo", 9, 0, 0 }, + { "foo", 3, "_foofoofoo", 9, 0, 1 }, + { "FOO", 3, "foofoofoo", 9, 1, 0 }, + { "FOO", 3, "_foofoofoo", 9, 1, 1 }, + { "FOO", 3, "foo Foo FOo fOo foO FOO", 23, 0, 20 }, + { "foo", 3, "Foo FOo fOo foO FOO foo", 23, 0, 20 }, }; int ret = 1; @@ -2581,7 +2970,7 @@ static int SpmSearchTest01(void) { printf("matcher: %s\n", m->name); uint32_t i; - for (i = 0; i < sizeof(data)/sizeof(data[0]); i++) { + for (i = 0; i < sizeof(data) / sizeof(data[0]); i++) { const SpmTestData *d = &data[i]; if (SpmTestSearch(d, matcher) == 0) { printf(" test %" PRIu32 ": fail\n", i); @@ -2594,22 +2983,38 @@ static int SpmSearchTest01(void) { return ret; } -static int SpmSearchTest02(void) { +static int SpmSearchTest02(void) +{ SpmTableSetup(); printf("\n"); /* Test that we can find needles of various lengths at various alignments * in the haystack. Note that these are passed to strlen. */ - static const char* needles[] = { + static const char *needles[] = { /* Single bytes */ - "a", "b", "c", ":", "/", "\x7f", "\xff", + "a", + "b", + "c", + ":", + "/", + "\x7f", + "\xff", /* Repeats */ - "aa", "aaa", "aaaaaaaaaaaaaaaaaaaaaaa", + "aa", + "aaa", + "aaaaaaaaaaaaaaaaaaaaaaa", /* Longer literals */ - "suricata", "meerkat", "aardvark", "raptor", "marmot", "lemming", + "suricata", + "meerkat", + "aardvark", + "raptor", + "marmot", + "lemming", /* Mixed case */ - "Suricata", "CAPS LOCK", "mIxEd cAsE", + "Suricata", + "CAPS LOCK", + "mIxEd cAsE", }; int ret = 1; @@ -2675,37 +3080,28 @@ void UtilSpmSearchRegistertests(void) { /* Generic tests */ UtRegisterTest("UtilSpmBasicSearchTest01", UtilSpmBasicSearchTest01); - UtRegisterTest("UtilSpmBasicSearchNocaseTest01", - UtilSpmBasicSearchNocaseTest01); + UtRegisterTest("UtilSpmBasicSearchNocaseTest01", UtilSpmBasicSearchNocaseTest01); UtRegisterTest("UtilSpmBs2bmSearchTest01", UtilSpmBs2bmSearchTest01); - UtRegisterTest("UtilSpmBs2bmSearchNocaseTest01", - UtilSpmBs2bmSearchNocaseTest01); + UtRegisterTest("UtilSpmBs2bmSearchNocaseTest01", UtilSpmBs2bmSearchNocaseTest01); - UtRegisterTest("UtilSpmBoyerMooreSearchTest01", - UtilSpmBoyerMooreSearchTest01); - UtRegisterTest("UtilSpmBoyerMooreSearchNocaseTest01", - UtilSpmBoyerMooreSearchNocaseTest01); - UtRegisterTest("UtilSpmBoyerMooreSearchNocaseTestIssue130", - UtilSpmBoyerMooreSearchNocaseTestIssue130); + UtRegisterTest("UtilSpmBoyerMooreSearchTest01", UtilSpmBoyerMooreSearchTest01); + UtRegisterTest("UtilSpmBoyerMooreSearchNocaseTest01", UtilSpmBoyerMooreSearchNocaseTest01); + UtRegisterTest( + "UtilSpmBoyerMooreSearchNocaseTestIssue130", UtilSpmBoyerMooreSearchNocaseTestIssue130); UtRegisterTest("UtilSpmBs2bmSearchTest02", UtilSpmBs2bmSearchTest02); - UtRegisterTest("UtilSpmBs2bmSearchNocaseTest02", - UtilSpmBs2bmSearchNocaseTest02); + UtRegisterTest("UtilSpmBs2bmSearchNocaseTest02", UtilSpmBs2bmSearchNocaseTest02); UtRegisterTest("UtilSpmBasicSearchTest02", UtilSpmBasicSearchTest02); - UtRegisterTest("UtilSpmBasicSearchNocaseTest02", - UtilSpmBasicSearchNocaseTest02); + UtRegisterTest("UtilSpmBasicSearchNocaseTest02", UtilSpmBasicSearchNocaseTest02); - UtRegisterTest("UtilSpmBoyerMooreSearchTest02", - UtilSpmBoyerMooreSearchTest02); - UtRegisterTest("UtilSpmBoyerMooreSearchNocaseTest02", - UtilSpmBoyerMooreSearchNocaseTest02); + UtRegisterTest("UtilSpmBoyerMooreSearchTest02", UtilSpmBoyerMooreSearchTest02); + UtRegisterTest("UtilSpmBoyerMooreSearchNocaseTest02", UtilSpmBoyerMooreSearchNocaseTest02); /* test matches at any offset */ UtRegisterTest("UtilSpmSearchOffsetsTest01", UtilSpmSearchOffsetsTest01); - UtRegisterTest("UtilSpmSearchOffsetsNocaseTest01", - UtilSpmSearchOffsetsNocaseTest01); + UtRegisterTest("UtilSpmSearchOffsetsNocaseTest01", UtilSpmSearchOffsetsNocaseTest01); /* new SPM API */ UtRegisterTest("SpmSearchTest01", SpmSearchTest01); @@ -2717,12 +3113,9 @@ void UtilSpmSearchRegistertests(void) UtRegisterTest("UtilSpmSearchStatsTest02", UtilSpmSearchStatsTest02); UtRegisterTest("UtilSpmSearchStatsTest03", UtilSpmSearchStatsTest03); - UtRegisterTest("UtilSpmNocaseSearchStatsTest01", - UtilSpmNocaseSearchStatsTest01); - UtRegisterTest("UtilSpmNocaseSearchStatsTest02", - UtilSpmNocaseSearchStatsTest02); - UtRegisterTest("UtilSpmNocaseSearchStatsTest03", - UtilSpmNocaseSearchStatsTest03); + UtRegisterTest("UtilSpmNocaseSearchStatsTest01", UtilSpmNocaseSearchStatsTest01); + UtRegisterTest("UtilSpmNocaseSearchStatsTest02", UtilSpmNocaseSearchStatsTest02); + UtRegisterTest("UtilSpmNocaseSearchStatsTest03", UtilSpmNocaseSearchStatsTest03); /* Stats building context and searching */ UtRegisterTest("UtilSpmSearchStatsTest04", UtilSpmSearchStatsTest04); @@ -2730,14 +3123,10 @@ void UtilSpmSearchRegistertests(void) UtRegisterTest("UtilSpmSearchStatsTest06", UtilSpmSearchStatsTest06); UtRegisterTest("UtilSpmSearchStatsTest07", UtilSpmSearchStatsTest07); - UtRegisterTest("UtilSpmNocaseSearchStatsTest04", - UtilSpmNocaseSearchStatsTest04); - UtRegisterTest("UtilSpmNocaseSearchStatsTest05", - UtilSpmNocaseSearchStatsTest05); - UtRegisterTest("UtilSpmNocaseSearchStatsTest06", - UtilSpmNocaseSearchStatsTest06); - UtRegisterTest("UtilSpmNocaseSearchStatsTest07", - UtilSpmNocaseSearchStatsTest07); + UtRegisterTest("UtilSpmNocaseSearchStatsTest04", UtilSpmNocaseSearchStatsTest04); + UtRegisterTest("UtilSpmNocaseSearchStatsTest05", UtilSpmNocaseSearchStatsTest05); + UtRegisterTest("UtilSpmNocaseSearchStatsTest06", UtilSpmNocaseSearchStatsTest06); + UtRegisterTest("UtilSpmNocaseSearchStatsTest07", UtilSpmNocaseSearchStatsTest07); #endif } diff --git a/src/util-spm.h b/src/util-spm.h index 9893dcd4222e..fe975df91fd8 100644 --- a/src/util-spm.h +++ b/src/util-spm.h @@ -63,10 +63,10 @@ typedef struct SpmTableElmt_ { SpmThreadCtx *(*MakeThreadCtx)(const SpmGlobalThreadCtx *g_thread_ctx); void (*DestroyThreadCtx)(SpmThreadCtx *thread_ctx); SpmCtx *(*InitCtx)(const uint8_t *needle, uint16_t needle_len, int nocase, - SpmGlobalThreadCtx *g_thread_ctx); + SpmGlobalThreadCtx *g_thread_ctx); void (*DestroyCtx)(SpmCtx *); - uint8_t *(*Scan)(const SpmCtx *ctx, SpmThreadCtx *thread_ctx, - const uint8_t *haystack, uint32_t haystack_len); + uint8_t *(*Scan)(const SpmCtx *ctx, SpmThreadCtx *thread_ctx, const uint8_t *haystack, + uint32_t haystack_len); } SpmTableElmt; extern SpmTableElmt spm_table[SPM_TABLE_SIZE]; @@ -81,41 +81,47 @@ SpmThreadCtx *SpmMakeThreadCtx(const SpmGlobalThreadCtx *g_thread_ctx); void SpmDestroyThreadCtx(SpmThreadCtx *thread_ctx); -SpmCtx *SpmInitCtx(const uint8_t *needle, uint16_t needle_len, int nocase, - SpmGlobalThreadCtx *g_thread_ctx); +SpmCtx *SpmInitCtx( + const uint8_t *needle, uint16_t needle_len, int nocase, SpmGlobalThreadCtx *g_thread_ctx); void SpmDestroyCtx(SpmCtx *ctx); -uint8_t *SpmScan(const SpmCtx *ctx, SpmThreadCtx *thread_ctx, - const uint8_t *haystack, uint32_t haystack_len); +uint8_t *SpmScan(const SpmCtx *ctx, SpmThreadCtx *thread_ctx, const uint8_t *haystack, + uint32_t haystack_len); /** Default algorithm to use: Boyer Moore */ -uint8_t *Bs2bmSearch(const uint8_t *text, uint32_t textlen, const uint8_t *needle, uint16_t needlelen); -uint8_t *Bs2bmNocaseSearch(const uint8_t *text, uint32_t textlen, const uint8_t *needle, uint16_t needlelen); -uint8_t *BoyerMooreSearch(const uint8_t *text, uint32_t textlen, const uint8_t *needle, uint16_t needlelen); -uint8_t *BoyerMooreNocaseSearch(const uint8_t *text, uint32_t textlen, uint8_t *needle, uint16_t needlelen); +uint8_t *Bs2bmSearch( + const uint8_t *text, uint32_t textlen, const uint8_t *needle, uint16_t needlelen); +uint8_t *Bs2bmNocaseSearch( + const uint8_t *text, uint32_t textlen, const uint8_t *needle, uint16_t needlelen); +uint8_t *BoyerMooreSearch( + const uint8_t *text, uint32_t textlen, const uint8_t *needle, uint16_t needlelen); +uint8_t *BoyerMooreNocaseSearch( + const uint8_t *text, uint32_t textlen, uint8_t *needle, uint16_t needlelen); /* Macros for automatic algorithm selection (use them only when you can't store the context) */ -#define SpmSearch(text, textlen, needle, needlelen) ({\ - uint8_t *mfound; \ - if (needlelen < 4 && textlen < 512) \ - mfound = BasicSearch(text, textlen, needle, needlelen); \ - else if (needlelen < 4) \ - mfound = BasicSearch(text, textlen, needle, needlelen); \ - else \ - mfound = BoyerMooreSearch(text, textlen, needle, needlelen); \ - mfound; \ +#define SpmSearch(text, textlen, needle, needlelen) \ + ({ \ + uint8_t *mfound; \ + if (needlelen < 4 && textlen < 512) \ + mfound = BasicSearch(text, textlen, needle, needlelen); \ + else if (needlelen < 4) \ + mfound = BasicSearch(text, textlen, needle, needlelen); \ + else \ + mfound = BoyerMooreSearch(text, textlen, needle, needlelen); \ + mfound; \ }) -#define SpmNocaseSearch(text, textlen, needle, needlelen) ({\ - uint8_t *mfound; \ - if (needlelen < 4 && textlen < 512) \ - mfound = BasicSearchNocase(text, textlen, needle, needlelen); \ - else if (needlelen < 4) \ - mfound = BasicSearchNocase(text, textlen, needle, needlelen); \ - else \ - mfound = BoyerMooreNocaseSearch(text, textlen, needle, needlelen); \ - mfound; \ +#define SpmNocaseSearch(text, textlen, needle, needlelen) \ + ({ \ + uint8_t *mfound; \ + if (needlelen < 4 && textlen < 512) \ + mfound = BasicSearchNocase(text, textlen, needle, needlelen); \ + else if (needlelen < 4) \ + mfound = BasicSearchNocase(text, textlen, needle, needlelen); \ + else \ + mfound = BoyerMooreNocaseSearch(text, textlen, needle, needlelen); \ + mfound; \ }) #ifdef UNITTESTS diff --git a/src/util-storage.c b/src/util-storage.c index 493b139ee85f..c7badf170781 100644 --- a/src/util-storage.c +++ b/src/util-storage.c @@ -50,7 +50,7 @@ static StorageMapping **storage_map = NULL; static const char *StoragePrintType(StorageEnum type) { - switch(type) { + switch (type) { case STORAGE_HOST: return "host"; case STORAGE_FLOW: @@ -97,13 +97,14 @@ void StorageCleanup(void) storage_list = NULL; } -int StorageRegister(const StorageEnum type, const char *name, const unsigned int size, void *(*Alloc)(unsigned int), void (*Free)(void *)) +int StorageRegister(const StorageEnum type, const char *name, const unsigned int size, + void *(*Alloc)(unsigned int), void (*Free)(void *)) { if (storage_registration_closed) return -1; - if (type >= STORAGE_MAX || name == NULL || strlen(name) == 0 || - size == 0 || (size != sizeof(void *) && Alloc == NULL) || Free == NULL) + if (type >= STORAGE_MAX || name == NULL || strlen(name) == 0 || size == 0 || + (size != sizeof(void *) && Alloc == NULL) || Free == NULL) return -1; StorageList *list = storage_list; @@ -186,8 +187,8 @@ int StorageFinalize(void) int j; for (j = 0; j < storage_max_id[i]; j++) { StorageMapping *m = &storage_map[i][j]; - SCLogDebug("type \"%s\" name \"%s\" size \"%"PRIuMAX"\"", - StoragePrintType(m->type), m->name, (uintmax_t)m->size); + SCLogDebug("type \"%s\" name \"%s\" size \"%" PRIuMAX "\"", StoragePrintType(m->type), + m->name, (uintmax_t)m->size); } } #endif diff --git a/src/util-storage.h b/src/util-storage.h index 6866874f7deb..d62a320feeac 100644 --- a/src/util-storage.h +++ b/src/util-storage.h @@ -54,7 +54,8 @@ void StorageCleanup(void); * \note if size == ptr size (so sizeof(void *)) and Alloc == NULL the API just * gives the caller a ptr to store something it alloc'ed itself. */ -int StorageRegister(const StorageEnum type, const char *name, const unsigned int size, void *(*Alloc)(unsigned int), void (*Free)(void *)); +int StorageRegister(const StorageEnum type, const char *name, const unsigned int size, + void *(*Alloc)(unsigned int), void (*Free)(void *)); int StorageFinalize(void); unsigned int StorageGetCnt(const StorageEnum type); diff --git a/src/util-streaming-buffer.c b/src/util-streaming-buffer.c index 7608b5082109..3bd0a09ffd7c 100644 --- a/src/util-streaming-buffer.c +++ b/src/util-streaming-buffer.c @@ -59,8 +59,7 @@ static void *CallocFunc(const size_t nm, const size_t sz) #define CALLOC(cfg, n, s) (cfg)->Calloc ? (cfg)->Calloc((n), (s)) : CallocFunc((n), (s)) #define REALLOC(cfg, ptr, orig_s, s) \ (cfg)->Realloc ? (cfg)->Realloc((ptr), (orig_s), (s)) : ReallocFunc((ptr), (s)) -#define FREE(cfg, ptr, s) \ - (cfg)->Free ? (cfg)->Free((ptr), (s)) : SCFree((ptr)) +#define FREE(cfg, ptr, s) (cfg)->Free ? (cfg)->Free((ptr), (s)) : SCFree((ptr)) static void SBBFree(StreamingBuffer *sb, const StreamingBufferConfig *cfg); @@ -75,7 +74,7 @@ int SBBCompare(struct StreamingBufferBlock *a, struct StreamingBufferBlock *b) else if (a->offset < b->offset) SCReturnInt(-1); else { - if (a->len == 0 || b->len == 0 || a->len == b->len) + if (a->len == 0 || b->len == 0 || a->len == b->len) SCReturnInt(0); else if (a->len > b->len) SCReturnInt(1); @@ -86,15 +85,16 @@ int SBBCompare(struct StreamingBufferBlock *a, struct StreamingBufferBlock *b) /* inclusive compare function that also considers the right edge, * not just the offset. */ -static inline int InclusiveCompare(StreamingBufferBlock *lookup, StreamingBufferBlock *intree) { +static inline int InclusiveCompare(StreamingBufferBlock *lookup, StreamingBufferBlock *intree) +{ const uint64_t lre = lookup->offset + lookup->len; const uint64_t tre = intree->offset + intree->len; - if (lre <= intree->offset) // entirely before + if (lre <= intree->offset) // entirely before return -1; else if (lookup->offset < tre && lre <= tre) // (some) overlap return 0; else - return 1; // entirely after + return 1; // entirely after } StreamingBufferBlock *SBB_RB_FIND_INCLUSIVE(struct SBB *head, StreamingBufferBlock *elm) @@ -304,7 +304,8 @@ void StreamingBufferFree(StreamingBuffer *sb, const StreamingBufferConfig *cfg) static void SBBPrintList(StreamingBuffer *sb) { StreamingBufferBlock *sbb = NULL; - RB_FOREACH(sbb, SBB, &sb->sbb_tree) { + RB_FOREACH(sbb, SBB, &sb->sbb_tree) + { SCLogDebug("sbb: offset %" PRIu64 ", len %u", sbb->offset, sbb->len); StreamingBufferBlock *next = SBB_RB_NEXT(sbb); if (next) { @@ -392,7 +393,7 @@ static inline void ConsolidateFwd(StreamingBuffer *sb, const StreamingBufferConf { uint64_t sa_re = sa->offset + sa->len; StreamingBufferBlock *tr, *s = sa; - RB_FOREACH_FROM(tr, SBB, s) { + RB_FOREACH_FROM (tr, SBB, s) { if (sa == tr) continue; @@ -454,7 +455,7 @@ static inline void ConsolidateFwd(StreamingBuffer *sb, const StreamingBufferConf sa: [ ] tr: [ ] */ - } else if (sa->offset < tr->offset && // starts before + } else if (sa->offset < tr->offset && // starts before sa_re >= tr->offset && sa_re < tr_re) // ends inside { // merge. sb->sbb_size includes both so we need to adjust that too. @@ -487,7 +488,7 @@ static inline void ConsolidateBackward(StreamingBuffer *sb, const StreamingBuffe { uint64_t sa_re = sa->offset + sa->len; StreamingBufferBlock *tr, *s = sa; - RB_FOREACH_REVERSE_FROM(tr, SBB, s) { + RB_FOREACH_REVERSE_FROM (tr, SBB, s) { if (sa == tr) continue; const uint64_t tr_re = tr->offset + tr->len; @@ -627,7 +628,7 @@ static int SBBUpdate(StreamingBuffer *sb, const StreamingBufferConfig *cfg, static void SBBFree(StreamingBuffer *sb, const StreamingBufferConfig *cfg) { StreamingBufferBlock *sbb = NULL, *safe = NULL; - RB_FOREACH_SAFE(sbb, SBB, &sb->sbb_tree, safe) { + RB_FOREACH_SAFE (sbb, SBB, &sb->sbb_tree, safe) { SBB_RB_REMOVE(&sb->sbb_tree, sbb); sb->sbb_size -= sbb->len; FREE(cfg, sbb, sizeof(StreamingBufferBlock)); @@ -639,7 +640,7 @@ static void SBBPrune(StreamingBuffer *sb, const StreamingBufferConfig *cfg) { SCLogDebug("pruning %p to %" PRIu64, sb, sb->region.stream_offset); StreamingBufferBlock *sbb = NULL, *safe = NULL; - RB_FOREACH_SAFE(sbb, SBB, &sb->sbb_tree, safe) { + RB_FOREACH_SAFE (sbb, SBB, &sb->sbb_tree, safe) { /* completely beyond window, we're done */ if (sbb->offset >= sb->region.stream_offset) { sb->head = sbb; @@ -660,7 +661,7 @@ static void SBBPrune(StreamingBuffer *sb, const StreamingBufferConfig *cfg) uint32_t shrink_by = sb->region.stream_offset - sbb->offset; DEBUG_VALIDATE_BUG_ON(shrink_by > sbb->len); if (sbb->len >= shrink_by) { - sbb->len -= shrink_by; + sbb->len -= shrink_by; sbb->offset += shrink_by; sb->sbb_size -= shrink_by; SCLogDebug("shrunk by %u", shrink_by); @@ -1587,8 +1588,8 @@ int StreamingBufferInsertAt(StreamingBuffer *sb, const StreamingBufferConfig *cf return SC_OK; } -int StreamingBufferSegmentIsBeforeWindow(const StreamingBuffer *sb, - const StreamingBufferSegment *seg) +int StreamingBufferSegmentIsBeforeWindow( + const StreamingBuffer *sb, const StreamingBufferSegment *seg) { if (seg->stream_offset < sb->region.stream_offset) { if (seg->stream_offset + seg->segment_len <= sb->region.stream_offset) { @@ -1619,9 +1620,8 @@ static inline const StreamingBufferRegion *GetRegionForOffset( } /** \brief get the data for one SBB */ -void StreamingBufferSBBGetData(const StreamingBuffer *sb, - const StreamingBufferBlock *sbb, - const uint8_t **data, uint32_t *data_len) +void StreamingBufferSBBGetData(const StreamingBuffer *sb, const StreamingBufferBlock *sbb, + const uint8_t **data, uint32_t *data_len) { const StreamingBufferRegion *region = GetRegionForOffset(sb, sbb->offset); SCLogDebug("first find our region (offset %" PRIu64 ") -> %p", sbb->offset, region); @@ -1656,10 +1656,8 @@ void StreamingBufferSBBGetData(const StreamingBuffer *sb, } /** \brief get the data for one SBB */ -void StreamingBufferSBBGetDataAtOffset(const StreamingBuffer *sb, - const StreamingBufferBlock *sbb, - const uint8_t **data, uint32_t *data_len, - uint64_t offset) +void StreamingBufferSBBGetDataAtOffset(const StreamingBuffer *sb, const StreamingBufferBlock *sbb, + const uint8_t **data, uint32_t *data_len, uint64_t offset) { /* validate that we are looking for a offset within the sbb */ DEBUG_VALIDATE_BUG_ON(!(offset >= sbb->offset && offset < (sbb->offset + sbb->len))); @@ -1698,9 +1696,8 @@ void StreamingBufferSBBGetDataAtOffset(const StreamingBuffer *sb, return; } -void StreamingBufferSegmentGetData(const StreamingBuffer *sb, - const StreamingBufferSegment *seg, - const uint8_t **data, uint32_t *data_len) +void StreamingBufferSegmentGetData(const StreamingBuffer *sb, const StreamingBufferSegment *seg, + const uint8_t **data, uint32_t *data_len) { const StreamingBufferRegion *region = GetRegionForOffset(sb, seg->stream_offset); if (region) { @@ -1733,23 +1730,19 @@ void StreamingBufferSegmentGetData(const StreamingBuffer *sb, * \retval 0 data is different */ int StreamingBufferSegmentCompareRawData(const StreamingBuffer *sb, - const StreamingBufferSegment *seg, - const uint8_t *rawdata, uint32_t rawdata_len) + const StreamingBufferSegment *seg, const uint8_t *rawdata, uint32_t rawdata_len) { const uint8_t *segdata = NULL; uint32_t segdata_len = 0; StreamingBufferSegmentGetData(sb, seg, &segdata, &segdata_len); - if (segdata && segdata_len && - segdata_len == rawdata_len && - memcmp(segdata, rawdata, segdata_len) == 0) - { + if (segdata && segdata_len && segdata_len == rawdata_len && + memcmp(segdata, rawdata, segdata_len) == 0) { return 1; } return 0; } -int StreamingBufferGetData(const StreamingBuffer *sb, - const uint8_t **data, uint32_t *data_len, +int StreamingBufferGetData(const StreamingBuffer *sb, const uint8_t **data, uint32_t *data_len, uint64_t *stream_offset) { if (sb != NULL && sb->region.buf != NULL) { @@ -1765,9 +1758,8 @@ int StreamingBufferGetData(const StreamingBuffer *sb, } } -int StreamingBufferGetDataAtOffset (const StreamingBuffer *sb, - const uint8_t **data, uint32_t *data_len, - uint64_t offset) +int StreamingBufferGetDataAtOffset( + const StreamingBuffer *sb, const uint8_t **data, uint32_t *data_len, uint64_t offset) { const StreamingBufferRegion *region = GetRegionForOffset(sb, offset); if (region != NULL && region->buf != NULL && offset >= region->stream_offset && @@ -1787,25 +1779,22 @@ int StreamingBufferGetDataAtOffset (const StreamingBuffer *sb, * \retval 1 data is the same * \retval 0 data is different */ -int StreamingBufferCompareRawData(const StreamingBuffer *sb, - const uint8_t *rawdata, uint32_t rawdata_len) +int StreamingBufferCompareRawData( + const StreamingBuffer *sb, const uint8_t *rawdata, uint32_t rawdata_len) { const uint8_t *sbdata = NULL; uint32_t sbdata_len = 0; uint64_t offset = 0; StreamingBufferGetData(sb, &sbdata, &sbdata_len, &offset); - if (offset == 0 && - sbdata && sbdata_len && - sbdata_len == rawdata_len && - memcmp(sbdata, rawdata, sbdata_len) == 0) - { + if (offset == 0 && sbdata && sbdata_len && sbdata_len == rawdata_len && + memcmp(sbdata, rawdata, sbdata_len) == 0) { return 1; } SCLogDebug("sbdata_len %u, offset %" PRIu64, sbdata_len, offset); printf("got:\n"); - PrintRawDataFp(stdout, sbdata,sbdata_len); + PrintRawDataFp(stdout, sbdata, sbdata_len); printf("wanted:\n"); - PrintRawDataFp(stdout, rawdata,rawdata_len); + PrintRawDataFp(stdout, rawdata, rawdata_len); return 0; } @@ -1839,8 +1828,8 @@ static int StreamingBufferTest02(void) FAIL_IF(sb->region.buf_offset != 16); FAIL_IF(seg1.stream_offset != 0); FAIL_IF(seg2.stream_offset != 8); - FAIL_IF(StreamingBufferSegmentIsBeforeWindow(sb,&seg1)); - FAIL_IF(StreamingBufferSegmentIsBeforeWindow(sb,&seg2)); + FAIL_IF(StreamingBufferSegmentIsBeforeWindow(sb, &seg1)); + FAIL_IF(StreamingBufferSegmentIsBeforeWindow(sb, &seg2)); Dump(sb); DumpSegment(sb, &seg1); DumpSegment(sb, &seg2); @@ -1856,9 +1845,9 @@ static int StreamingBufferTest02(void) FAIL_IF(sb->region.stream_offset != 6); FAIL_IF(sb->region.buf_offset != 16); FAIL_IF(seg3.stream_offset != 16); - FAIL_IF(StreamingBufferSegmentIsBeforeWindow(sb,&seg1)); - FAIL_IF(StreamingBufferSegmentIsBeforeWindow(sb,&seg2)); - FAIL_IF(StreamingBufferSegmentIsBeforeWindow(sb,&seg3)); + FAIL_IF(StreamingBufferSegmentIsBeforeWindow(sb, &seg1)); + FAIL_IF(StreamingBufferSegmentIsBeforeWindow(sb, &seg2)); + FAIL_IF(StreamingBufferSegmentIsBeforeWindow(sb, &seg3)); Dump(sb); DumpSegment(sb, &seg1); DumpSegment(sb, &seg2); @@ -1867,9 +1856,9 @@ static int StreamingBufferTest02(void) FAIL_IF_NOT(sb->head == RB_MIN(SBB, &sb->sbb_tree)); StreamingBufferSlideToOffset(sb, &cfg, 12); - FAIL_IF(!StreamingBufferSegmentIsBeforeWindow(sb,&seg1)); - FAIL_IF(StreamingBufferSegmentIsBeforeWindow(sb,&seg2)); - FAIL_IF(StreamingBufferSegmentIsBeforeWindow(sb,&seg3)); + FAIL_IF(!StreamingBufferSegmentIsBeforeWindow(sb, &seg1)); + FAIL_IF(StreamingBufferSegmentIsBeforeWindow(sb, &seg2)); + FAIL_IF(StreamingBufferSegmentIsBeforeWindow(sb, &seg3)); Dump(sb); DumpSegment(sb, &seg1); DumpSegment(sb, &seg2); @@ -1895,8 +1884,8 @@ static int StreamingBufferTest03(void) FAIL_IF(sb->region.buf_offset != 8); FAIL_IF(seg1.stream_offset != 0); FAIL_IF(seg2.stream_offset != 14); - FAIL_IF(StreamingBufferSegmentIsBeforeWindow(sb,&seg1)); - FAIL_IF(StreamingBufferSegmentIsBeforeWindow(sb,&seg2)); + FAIL_IF(StreamingBufferSegmentIsBeforeWindow(sb, &seg1)); + FAIL_IF(StreamingBufferSegmentIsBeforeWindow(sb, &seg2)); Dump(sb); DumpSegment(sb, &seg1); DumpSegment(sb, &seg2); @@ -1909,9 +1898,9 @@ static int StreamingBufferTest03(void) FAIL_IF(sb->region.stream_offset != 0); FAIL_IF(sb->region.buf_offset != 22); FAIL_IF(seg3.stream_offset != 8); - FAIL_IF(StreamingBufferSegmentIsBeforeWindow(sb,&seg1)); - FAIL_IF(StreamingBufferSegmentIsBeforeWindow(sb,&seg2)); - FAIL_IF(StreamingBufferSegmentIsBeforeWindow(sb,&seg3)); + FAIL_IF(StreamingBufferSegmentIsBeforeWindow(sb, &seg1)); + FAIL_IF(StreamingBufferSegmentIsBeforeWindow(sb, &seg2)); + FAIL_IF(StreamingBufferSegmentIsBeforeWindow(sb, &seg3)); Dump(sb); DumpSegment(sb, &seg1); DumpSegment(sb, &seg2); @@ -1921,9 +1910,9 @@ static int StreamingBufferTest03(void) FAIL_IF_NOT(sb->head == RB_MIN(SBB, &sb->sbb_tree)); StreamingBufferSlideToOffset(sb, &cfg, 10); - FAIL_IF(!StreamingBufferSegmentIsBeforeWindow(sb,&seg1)); - FAIL_IF(StreamingBufferSegmentIsBeforeWindow(sb,&seg2)); - FAIL_IF(StreamingBufferSegmentIsBeforeWindow(sb,&seg3)); + FAIL_IF(!StreamingBufferSegmentIsBeforeWindow(sb, &seg1)); + FAIL_IF(StreamingBufferSegmentIsBeforeWindow(sb, &seg2)); + FAIL_IF(StreamingBufferSegmentIsBeforeWindow(sb, &seg3)); Dump(sb); DumpSegment(sb, &seg1); DumpSegment(sb, &seg2); @@ -1951,8 +1940,8 @@ static int StreamingBufferTest04(void) FAIL_IF(sb->region.buf_offset != 8); FAIL_IF(seg1.stream_offset != 0); FAIL_IF(seg2.stream_offset != 14); - FAIL_IF(StreamingBufferSegmentIsBeforeWindow(sb,&seg1)); - FAIL_IF(StreamingBufferSegmentIsBeforeWindow(sb,&seg2)); + FAIL_IF(StreamingBufferSegmentIsBeforeWindow(sb, &seg1)); + FAIL_IF(StreamingBufferSegmentIsBeforeWindow(sb, &seg2)); FAIL_IF(RB_EMPTY(&sb->sbb_tree)); StreamingBufferBlock *sbb1 = RB_MIN(SBB, &sb->sbb_tree); FAIL_IF(sbb1 != sb->head); @@ -1974,9 +1963,9 @@ static int StreamingBufferTest04(void) FAIL_IF(sb->region.stream_offset != 0); FAIL_IF(sb->region.buf_offset != 22); FAIL_IF(seg3.stream_offset != 8); - FAIL_IF(StreamingBufferSegmentIsBeforeWindow(sb,&seg1)); - FAIL_IF(StreamingBufferSegmentIsBeforeWindow(sb,&seg2)); - FAIL_IF(StreamingBufferSegmentIsBeforeWindow(sb,&seg3)); + FAIL_IF(StreamingBufferSegmentIsBeforeWindow(sb, &seg1)); + FAIL_IF(StreamingBufferSegmentIsBeforeWindow(sb, &seg2)); + FAIL_IF(StreamingBufferSegmentIsBeforeWindow(sb, &seg3)); sbb1 = RB_MIN(SBB, &sb->sbb_tree); FAIL_IF_NULL(sbb1); FAIL_IF(sbb1 != sb->head); @@ -1998,10 +1987,10 @@ static int StreamingBufferTest04(void) FAIL_IF(sb->region.buf_offset != 22); FAIL_IF(sb->region.buf_size != 128); FAIL_IF(seg4.stream_offset != 124); - FAIL_IF(StreamingBufferSegmentIsBeforeWindow(sb,&seg1)); - FAIL_IF(StreamingBufferSegmentIsBeforeWindow(sb,&seg2)); - FAIL_IF(StreamingBufferSegmentIsBeforeWindow(sb,&seg3)); - FAIL_IF(StreamingBufferSegmentIsBeforeWindow(sb,&seg4)); + FAIL_IF(StreamingBufferSegmentIsBeforeWindow(sb, &seg1)); + FAIL_IF(StreamingBufferSegmentIsBeforeWindow(sb, &seg2)); + FAIL_IF(StreamingBufferSegmentIsBeforeWindow(sb, &seg3)); + FAIL_IF(StreamingBufferSegmentIsBeforeWindow(sb, &seg4)); sbb1 = RB_MIN(SBB, &sb->sbb_tree); FAIL_IF_NULL(sbb1); FAIL_IF(sbb1 != sb->head); @@ -2017,10 +2006,10 @@ static int StreamingBufferTest04(void) FAIL_IF_NOT(sb->sbb_size == 25); FAIL_IF_NOT(sb->head == RB_MIN(SBB, &sb->sbb_tree)); - FAIL_IF(!StreamingBufferSegmentCompareRawData(sb,&seg1,(const uint8_t *)"ABCDEFGH", 8)); - FAIL_IF(!StreamingBufferSegmentCompareRawData(sb,&seg2,(const uint8_t *)"01234567", 8)); - FAIL_IF(!StreamingBufferSegmentCompareRawData(sb,&seg3,(const uint8_t *)"QWERTY", 6)); - FAIL_IF(!StreamingBufferSegmentCompareRawData(sb,&seg4,(const uint8_t *)"XYZ", 3)); + FAIL_IF(!StreamingBufferSegmentCompareRawData(sb, &seg1, (const uint8_t *)"ABCDEFGH", 8)); + FAIL_IF(!StreamingBufferSegmentCompareRawData(sb, &seg2, (const uint8_t *)"01234567", 8)); + FAIL_IF(!StreamingBufferSegmentCompareRawData(sb, &seg3, (const uint8_t *)"QWERTY", 6)); + FAIL_IF(!StreamingBufferSegmentCompareRawData(sb, &seg4, (const uint8_t *)"XYZ", 3)); StreamingBufferFree(sb, &cfg); PASS; diff --git a/src/util-streaming-buffer.h b/src/util-streaming-buffer.h index 98ee6f67ca26..a766dd6c6b12 100644 --- a/src/util-streaming-buffer.h +++ b/src/util-streaming-buffer.h @@ -55,7 +55,6 @@ * +-----------+-----------+ */ - #ifndef __UTIL_STREAMING_BUFFER_H__ #define __UTIL_STREAMING_BUFFER_H__ @@ -108,7 +107,7 @@ StreamingBufferBlock *SBB_RB_FIND_INCLUSIVE(struct SBB *head, StreamingBufferBlo typedef struct StreamingBuffer_ { StreamingBufferRegion region; - struct SBB sbb_tree; /**< red black tree of Stream Buffer Blocks */ + struct SBB sbb_tree; /**< red black tree of Stream Buffer Blocks */ StreamingBufferBlock *head; /**< head, should always be the same as RB_MIN */ uint32_t sbb_size; /**< data size covered by sbbs */ uint16_t regions; @@ -168,35 +167,28 @@ int StreamingBufferInsertAt(StreamingBuffer *sb, const StreamingBufferConfig *cf StreamingBufferSegment *seg, const uint8_t *data, uint32_t data_len, uint64_t offset) WARN_UNUSED; -void StreamingBufferSegmentGetData(const StreamingBuffer *sb, - const StreamingBufferSegment *seg, - const uint8_t **data, uint32_t *data_len); +void StreamingBufferSegmentGetData(const StreamingBuffer *sb, const StreamingBufferSegment *seg, + const uint8_t **data, uint32_t *data_len); -void StreamingBufferSBBGetData(const StreamingBuffer *sb, - const StreamingBufferBlock *sbb, - const uint8_t **data, uint32_t *data_len); +void StreamingBufferSBBGetData(const StreamingBuffer *sb, const StreamingBufferBlock *sbb, + const uint8_t **data, uint32_t *data_len); -void StreamingBufferSBBGetDataAtOffset(const StreamingBuffer *sb, - const StreamingBufferBlock *sbb, - const uint8_t **data, uint32_t *data_len, - uint64_t offset); +void StreamingBufferSBBGetDataAtOffset(const StreamingBuffer *sb, const StreamingBufferBlock *sbb, + const uint8_t **data, uint32_t *data_len, uint64_t offset); int StreamingBufferSegmentCompareRawData(const StreamingBuffer *sb, - const StreamingBufferSegment *seg, - const uint8_t *rawdata, uint32_t rawdata_len); -int StreamingBufferCompareRawData(const StreamingBuffer *sb, - const uint8_t *rawdata, uint32_t rawdata_len); + const StreamingBufferSegment *seg, const uint8_t *rawdata, uint32_t rawdata_len); +int StreamingBufferCompareRawData( + const StreamingBuffer *sb, const uint8_t *rawdata, uint32_t rawdata_len); -int StreamingBufferGetData(const StreamingBuffer *sb, - const uint8_t **data, uint32_t *data_len, +int StreamingBufferGetData(const StreamingBuffer *sb, const uint8_t **data, uint32_t *data_len, uint64_t *stream_offset); -int StreamingBufferGetDataAtOffset (const StreamingBuffer *sb, - const uint8_t **data, uint32_t *data_len, - uint64_t offset); +int StreamingBufferGetDataAtOffset( + const StreamingBuffer *sb, const uint8_t **data, uint32_t *data_len, uint64_t offset); -int StreamingBufferSegmentIsBeforeWindow(const StreamingBuffer *sb, - const StreamingBufferSegment *seg); +int StreamingBufferSegmentIsBeforeWindow( + const StreamingBuffer *sb, const StreamingBufferSegment *seg); void StreamingBufferRegisterTests(void); diff --git a/src/util-strlcatu.c b/src/util-strlcatu.c index b2b188f9430a..d3665b4ebbe3 100644 --- a/src/util-strlcatu.c +++ b/src/util-strlcatu.c @@ -56,7 +56,7 @@ size_t strlcat(char *dst, const char *src, size_t siz) n = siz - dlen; if (n == 0) - return(dlen + strlen(s)); + return (dlen + strlen(s)); while (*s != '\0') { if (n != 1) { *d++ = *s; @@ -66,6 +66,6 @@ size_t strlcat(char *dst, const char *src, size_t siz) } *d = '\0'; - return(dlen + (s - src)); /* count does not include NUL */ + return (dlen + (s - src)); /* count does not include NUL */ } #endif diff --git a/src/util-strlcpyu.c b/src/util-strlcpyu.c index 7b746bd9c740..e0dc54823181 100644 --- a/src/util-strlcpyu.c +++ b/src/util-strlcpyu.c @@ -62,6 +62,6 @@ size_t strlcpy(char *dst, const char *src, size_t siz) ; } - return(s - src - 1); /* count does not include NUL */ + return (s - src - 1); /* count does not include NUL */ } #endif diff --git a/src/util-strptime.c b/src/util-strptime.c index e0475ec611f0..55a4b19eeed0 100644 --- a/src/util-strptime.c +++ b/src/util-strptime.c @@ -53,547 +53,530 @@ __weak_alias(strptime,_strptime) #endif */ -#define _ctloc(x) (_CurrentTimeLocale->x) +#define _ctloc(x) (_CurrentTimeLocale->x) /* * We do not implement alternate representations. However, we always * check whether a given modifier is allowed for a certain conversion. */ -#define ALT_E 0x01 -#define ALT_O 0x02 -#define LEGAL_ALT(x) { if (alt_format & ~(x)) return NULL; } +#define ALT_E 0x01 +#define ALT_O 0x02 +#define LEGAL_ALT(x) \ + { \ + if (alt_format & ~(x)) \ + return NULL; \ + } static int TM_YEAR_BASE = 1900; static char gmt[] = { "GMT" }; static char utc[] = { "UTC" }; /* RFC-822/RFC-2822 */ -static const char * const nast[5] = { - "EST", "CST", "MST", "PST", "\0\0\0" -}; -static const char * const nadt[5] = { - "EDT", "CDT", "MDT", "PDT", "\0\0\0" -}; -static const char * const am_pm[2] = { - "am", "pm" -}; -static const char * const day[7] = { - "sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday" -}; -static const char * const abday[7] = { - "sun", "mon", "tue", "wed", "thu", "fri", "sat" -}; -static const char * const mon[12] = { - "january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december" -}; -static const char * const abmon[12] = { - "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec" -}; +static const char *const nast[5] = { "EST", "CST", "MST", "PST", "\0\0\0" }; +static const char *const nadt[5] = { "EDT", "CDT", "MDT", "PDT", "\0\0\0" }; +static const char *const am_pm[2] = { "am", "pm" }; +static const char *const day[7] = { "sunday", "monday", "tuesday", "wednesday", "thursday", + "friday", "saturday" }; +static const char *const abday[7] = { "sun", "mon", "tue", "wed", "thu", "fri", "sat" }; +static const char *const mon[12] = { "january", "february", "march", "april", "may", "june", "july", + "august", "september", "october", "november", "december" }; +static const char *const abmon[12] = { "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", + "sep", "oct", "nov", "dec" }; static const u_char *conv_num(const unsigned char *, int *, unsigned int, unsigned int); -static const u_char *find_string(const u_char *, int *, const char * const *, - const char * const *, int); +static const u_char *find_string( + const u_char *, int *, const char *const *, const char *const *, int); -char * -strptime(const char *buf, const char *fmt, struct tm *tm) +char *strptime(const char *buf, const char *fmt, struct tm *tm) { - unsigned char c; - const unsigned char *bp, *ep; - int alt_format, i, split_year = 0, neg = 0, offs; - const char *new_fmt; - - bp = (const u_char *)buf; - - while (bp != NULL && (c = *fmt++) != '\0') { - /* Clear `alternate' modifier prior to new conversion. */ - alt_format = 0; - i = 0; - - /* Eat up white-space. */ - if (isspace(c)) { - while (isspace(*bp)) - bp++; - continue; - } - - if (c != '%') - goto literal; - - -again: switch (c = *fmt++) { - case '%': /* "%%" is converted to "%". */ -literal: - if (c != *bp++) - return NULL; - LEGAL_ALT(0); - continue; - - /* - * "Alternative" modifiers. Just set the appropriate flag - * and start over again. - */ - case 'E': /* "%E?" alternative conversion modifier. */ - LEGAL_ALT(0); - alt_format |= ALT_E; - goto again; - - case 'O': /* "%O?" alternative conversion modifier. */ - LEGAL_ALT(0); - alt_format |= ALT_O; - goto again; - - /* - * "Complex" conversion rules, implemented through recursion. - */ - /* we do not need 'c' + unsigned char c; + const unsigned char *bp, *ep; + int alt_format, i, split_year = 0, neg = 0, offs; + const char *new_fmt; + + bp = (const u_char *)buf; + + while (bp != NULL && (c = *fmt++) != '\0') { + /* Clear `alternate' modifier prior to new conversion. */ + alt_format = 0; + i = 0; + + /* Eat up white-space. */ + if (isspace(c)) { + while (isspace(*bp)) + bp++; + continue; + } + + if (c != '%') + goto literal; + + again: + switch (c = *fmt++) { + case '%': /* "%%" is converted to "%". */ + literal: + if (c != *bp++) + return NULL; + LEGAL_ALT(0); + continue; + + /* + * "Alternative" modifiers. Just set the appropriate flag + * and start over again. + */ + case 'E': /* "%E?" alternative conversion modifier. */ + LEGAL_ALT(0); + alt_format |= ALT_E; + goto again; + + case 'O': /* "%O?" alternative conversion modifier. */ + LEGAL_ALT(0); + alt_format |= ALT_O; + goto again; + + /* + * "Complex" conversion rules, implemented through recursion. + */ + /* we do not need 'c' case 'c': Date and time, using the locale's format. - new_fmt = _ctloc(d_t_fmt); - goto recurse; + new_fmt = _ctloc(d_t_fmt); + goto recurse; */ - case 'D': /* The date as "%m/%d/%y". */ - new_fmt = "%m/%d/%y"; - LEGAL_ALT(0); - goto recurse; + case 'D': /* The date as "%m/%d/%y". */ + new_fmt = "%m/%d/%y"; + LEGAL_ALT(0); + goto recurse; - case 'F': /* The date as "%Y-%m-%d". */ - new_fmt = "%Y-%m-%d"; - LEGAL_ALT(0); - goto recurse; + case 'F': /* The date as "%Y-%m-%d". */ + new_fmt = "%Y-%m-%d"; + LEGAL_ALT(0); + goto recurse; - case 'R': /* The time as "%H:%M". */ - new_fmt = "%H:%M"; - LEGAL_ALT(0); - goto recurse; + case 'R': /* The time as "%H:%M". */ + new_fmt = "%H:%M"; + LEGAL_ALT(0); + goto recurse; - case 'r': /* The time in 12-hour clock representation. */ - new_fmt = "%I:%M:S %p";//_ctloc(t_fmt_ampm); - LEGAL_ALT(0); - goto recurse; + case 'r': /* The time in 12-hour clock representation. */ + new_fmt = "%I:%M:S %p"; //_ctloc(t_fmt_ampm); + LEGAL_ALT(0); + goto recurse; - case 'T': /* The time as "%H:%M:%S". */ - new_fmt = "%H:%M:%S"; - LEGAL_ALT(0); - goto recurse; + case 'T': /* The time as "%H:%M:%S". */ + new_fmt = "%H:%M:%S"; + LEGAL_ALT(0); + goto recurse; - /* we don't use 'X' + /* we don't use 'X' case 'X': The time, using the locale's format. - new_fmt =_ctloc(t_fmt); - goto recurse; + new_fmt =_ctloc(t_fmt); + goto recurse; */ - /* we do not need 'x' + /* we do not need 'x' case 'x': The date, using the locale's format. - new_fmt =_ctloc(d_fmt);*/ -recurse: - bp = (const u_char *)strptime((const char *)bp, - new_fmt, tm); - LEGAL_ALT(ALT_E); - continue; - - /* - * "Elementary" conversion rules. - */ - case 'A': /* The day of week, using the locale's form. */ - case 'a': - bp = find_string(bp, &tm->tm_wday, day, abday, 7); - LEGAL_ALT(0); - continue; - - case 'B': /* The month, using the locale's form. */ - case 'b': - case 'h': - bp = find_string(bp, &tm->tm_mon, mon, abmon, 12); - LEGAL_ALT(0); - continue; - - case 'C': /* The century number. */ - i = 20; - bp = conv_num(bp, &i, 0, 99); - - i = i * 100 - TM_YEAR_BASE; - if (split_year) - i += tm->tm_year % 100; - split_year = 1; - tm->tm_year = i; - LEGAL_ALT(ALT_E); - continue; - - case 'd': /* The day of month. */ - case 'e': - bp = conv_num(bp, &tm->tm_mday, 1, 31); - LEGAL_ALT(ALT_O); - continue; - - case 'k': /* The hour (24-hour clock representation). */ - LEGAL_ALT(0); - /* FALLTHROUGH */ - case 'H': - bp = conv_num(bp, &tm->tm_hour, 0, 23); - LEGAL_ALT(ALT_O); - continue; - - case 'l': /* The hour (12-hour clock representation). */ - LEGAL_ALT(0); - /* FALLTHROUGH */ - case 'I': - bp = conv_num(bp, &tm->tm_hour, 1, 12); - if (tm->tm_hour == 12) - tm->tm_hour = 0; - LEGAL_ALT(ALT_O); - continue; - - case 'j': /* The day of year. */ - i = 1; - bp = conv_num(bp, &i, 1, 366); - tm->tm_yday = i - 1; - LEGAL_ALT(0); - continue; - - case 'M': /* The minute. */ - bp = conv_num(bp, &tm->tm_min, 0, 59); - LEGAL_ALT(ALT_O); - continue; - - case 'm': /* The month. */ - i = 1; - bp = conv_num(bp, &i, 1, 12); - tm->tm_mon = i - 1; - LEGAL_ALT(ALT_O); - continue; - - case 'p': /* The locale's equivalent of AM/PM. */ - bp = find_string(bp, &i, am_pm, NULL, 2); - if (tm->tm_hour > 11) - return NULL; - tm->tm_hour += i * 12; - LEGAL_ALT(0); - continue; - - case 'S': /* The seconds. */ - bp = conv_num(bp, &tm->tm_sec, 0, 61); - LEGAL_ALT(ALT_O); - continue; + new_fmt =_ctloc(d_fmt);*/ + recurse: + bp = (const u_char *)strptime((const char *)bp, new_fmt, tm); + LEGAL_ALT(ALT_E); + continue; + + /* + * "Elementary" conversion rules. + */ + case 'A': /* The day of week, using the locale's form. */ + case 'a': + bp = find_string(bp, &tm->tm_wday, day, abday, 7); + LEGAL_ALT(0); + continue; + + case 'B': /* The month, using the locale's form. */ + case 'b': + case 'h': + bp = find_string(bp, &tm->tm_mon, mon, abmon, 12); + LEGAL_ALT(0); + continue; + + case 'C': /* The century number. */ + i = 20; + bp = conv_num(bp, &i, 0, 99); + + i = i * 100 - TM_YEAR_BASE; + if (split_year) + i += tm->tm_year % 100; + split_year = 1; + tm->tm_year = i; + LEGAL_ALT(ALT_E); + continue; + + case 'd': /* The day of month. */ + case 'e': + bp = conv_num(bp, &tm->tm_mday, 1, 31); + LEGAL_ALT(ALT_O); + continue; + + case 'k': /* The hour (24-hour clock representation). */ + LEGAL_ALT(0); + /* FALLTHROUGH */ + case 'H': + bp = conv_num(bp, &tm->tm_hour, 0, 23); + LEGAL_ALT(ALT_O); + continue; + + case 'l': /* The hour (12-hour clock representation). */ + LEGAL_ALT(0); + /* FALLTHROUGH */ + case 'I': + bp = conv_num(bp, &tm->tm_hour, 1, 12); + if (tm->tm_hour == 12) + tm->tm_hour = 0; + LEGAL_ALT(ALT_O); + continue; + + case 'j': /* The day of year. */ + i = 1; + bp = conv_num(bp, &i, 1, 366); + tm->tm_yday = i - 1; + LEGAL_ALT(0); + continue; + + case 'M': /* The minute. */ + bp = conv_num(bp, &tm->tm_min, 0, 59); + LEGAL_ALT(ALT_O); + continue; + + case 'm': /* The month. */ + i = 1; + bp = conv_num(bp, &i, 1, 12); + tm->tm_mon = i - 1; + LEGAL_ALT(ALT_O); + continue; + + case 'p': /* The locale's equivalent of AM/PM. */ + bp = find_string(bp, &i, am_pm, NULL, 2); + if (tm->tm_hour > 11) + return NULL; + tm->tm_hour += i * 12; + LEGAL_ALT(0); + continue; + + case 'S': /* The seconds. */ + bp = conv_num(bp, &tm->tm_sec, 0, 61); + LEGAL_ALT(ALT_O); + continue; #ifndef TIME_MAX -#define TIME_MAX INT64_MAX +#define TIME_MAX INT64_MAX #endif - case 's': /* seconds since the epoch */ - { - time_t sse = 0; - uint64_t rulim = TIME_MAX; - - if (*bp < '0' || *bp > '9') { - bp = NULL; - continue; - } - - do { - sse *= 10; - sse += *bp++ - '0'; - rulim /= 10; - } while (((uint64_t)sse * 10 <= TIME_MAX) && - rulim && *bp >= '0' && *bp <= '9'); - - if (sse < 0 || (uint64_t)sse > TIME_MAX) { - bp = NULL; - continue; - } - - tm = localtime(&sse); - if (tm == NULL) - bp = NULL; - } - continue; - - case 'U': /* The week of year, beginning on sunday. */ - case 'W': /* The week of year, beginning on monday. */ - /* - * XXX This is bogus, as we can not assume any valid - * information present in the tm structure at this - * point to calculate a real value, so just check the - * range for now. - */ - bp = conv_num(bp, &i, 0, 53); - LEGAL_ALT(ALT_O); - continue; - - case 'w': /* The day of week, beginning on sunday. */ - bp = conv_num(bp, &tm->tm_wday, 0, 6); - LEGAL_ALT(ALT_O); - continue; - - case 'u': /* The day of week, monday = 1. */ - bp = conv_num(bp, &i, 1, 7); - tm->tm_wday = i % 7; - LEGAL_ALT(ALT_O); - continue; - - case 'g': /* The year corresponding to the ISO week - * number but without the century. - */ - bp = conv_num(bp, &i, 0, 99); - continue; - - case 'G': /* The year corresponding to the ISO week - * number with century. - */ - do - bp++; - while (isdigit(*bp)); - continue; - - case 'V': /* The ISO 8601:1988 week number as decimal */ - bp = conv_num(bp, &i, 0, 53); - continue; - - case 'Y': /* The year. */ - i = TM_YEAR_BASE; /* just for data sanity... */ - bp = conv_num(bp, &i, 0, 9999); - tm->tm_year = i - TM_YEAR_BASE; - LEGAL_ALT(ALT_E); - continue; - - case 'y': /* The year within 100 years of the epoch. */ - /* LEGAL_ALT(ALT_E | ALT_O); */ - bp = conv_num(bp, &i, 0, 99); - - if (split_year) - /* preserve century */ - i += (tm->tm_year / 100) * 100; - else { - split_year = 1; - if (i <= 68) - i = i + 2000 - TM_YEAR_BASE; - else - i = i + 1900 - TM_YEAR_BASE; - } - tm->tm_year = i; - continue; - - case 'Z': - tzset(); - if (strncasecmp((const char *)bp, gmt, 3) == 0 - || strncasecmp((const char *)bp, utc, 3) == 0) { - tm->tm_isdst = 0; + case 's': /* seconds since the epoch */ + { + time_t sse = 0; + uint64_t rulim = TIME_MAX; + + if (*bp < '0' || *bp > '9') { + bp = NULL; + continue; + } + + do { + sse *= 10; + sse += *bp++ - '0'; + rulim /= 10; + } while (((uint64_t)sse * 10 <= TIME_MAX) && rulim && *bp >= '0' && *bp <= '9'); + + if (sse < 0 || (uint64_t)sse > TIME_MAX) { + bp = NULL; + continue; + } + + tm = localtime(&sse); + if (tm == NULL) + bp = NULL; + } + continue; + + case 'U': /* The week of year, beginning on sunday. */ + case 'W': /* The week of year, beginning on monday. */ + /* + * XXX This is bogus, as we can not assume any valid + * information present in the tm structure at this + * point to calculate a real value, so just check the + * range for now. + */ + bp = conv_num(bp, &i, 0, 53); + LEGAL_ALT(ALT_O); + continue; + + case 'w': /* The day of week, beginning on sunday. */ + bp = conv_num(bp, &tm->tm_wday, 0, 6); + LEGAL_ALT(ALT_O); + continue; + + case 'u': /* The day of week, monday = 1. */ + bp = conv_num(bp, &i, 1, 7); + tm->tm_wday = i % 7; + LEGAL_ALT(ALT_O); + continue; + + case 'g': /* The year corresponding to the ISO week + * number but without the century. + */ + bp = conv_num(bp, &i, 0, 99); + continue; + + case 'G': /* The year corresponding to the ISO week + * number with century. + */ + do + bp++; + while (isdigit(*bp)); + continue; + + case 'V': /* The ISO 8601:1988 week number as decimal */ + bp = conv_num(bp, &i, 0, 53); + continue; + + case 'Y': /* The year. */ + i = TM_YEAR_BASE; /* just for data sanity... */ + bp = conv_num(bp, &i, 0, 9999); + tm->tm_year = i - TM_YEAR_BASE; + LEGAL_ALT(ALT_E); + continue; + + case 'y': /* The year within 100 years of the epoch. */ + /* LEGAL_ALT(ALT_E | ALT_O); */ + bp = conv_num(bp, &i, 0, 99); + + if (split_year) + /* preserve century */ + i += (tm->tm_year / 100) * 100; + else { + split_year = 1; + if (i <= 68) + i = i + 2000 - TM_YEAR_BASE; + else + i = i + 1900 - TM_YEAR_BASE; + } + tm->tm_year = i; + continue; + + case 'Z': + tzset(); + if (strncasecmp((const char *)bp, gmt, 3) == 0 || + strncasecmp((const char *)bp, utc, 3) == 0) { + tm->tm_isdst = 0; #ifdef TM_GMTOFF - tm->TM_GMTOFF = 0; + tm->TM_GMTOFF = 0; #endif #ifdef TM_ZONE - tm->TM_ZONE = gmt; + tm->TM_ZONE = gmt; #endif - bp += 3; - } else { - ep = find_string(bp, &i, - (const char * const *)tzname, - NULL, 2); - if (ep != NULL) { - tm->tm_isdst = i; + bp += 3; + } else { + ep = find_string(bp, &i, (const char *const *)tzname, NULL, 2); + if (ep != NULL) { + tm->tm_isdst = i; #ifdef TM_GMTOFF - tm->TM_GMTOFF = -(timezone); + tm->TM_GMTOFF = -(timezone); #endif #ifdef TM_ZONE - tm->TM_ZONE = tzname[i]; + tm->TM_ZONE = tzname[i]; #endif - } - bp = ep; - } - continue; - - case 'z': - /* - * We recognize all ISO 8601 formats: - * Z = Zulu time/UTC - * [+-]hhmm - * [+-]hh:mm - * [+-]hh - * We recognize all RFC-822/RFC-2822 formats: - * UT|GMT - * North American : UTC offsets - * E[DS]T = Eastern : -4 | -5 - * C[DS]T = Central : -5 | -6 - * M[DS]T = Mountain: -6 | -7 - * P[DS]T = Pacific : -7 | -8 - * Military - * [A-IL-M] = -1 ... -9 (J not used) - * [N-Y] = +1 ... +12 - */ - while (isspace(*bp)) - bp++; - - switch (*bp++) { - case 'G': - if (*bp++ != 'M') - return NULL; - /*FALLTHROUGH*/ - case 'U': - if (*bp++ != 'T') - return NULL; - /*FALLTHROUGH*/ - case 'Z': - tm->tm_isdst = 0; + } + bp = ep; + } + continue; + + case 'z': + /* + * We recognize all ISO 8601 formats: + * Z = Zulu time/UTC + * [+-]hhmm + * [+-]hh:mm + * [+-]hh + * We recognize all RFC-822/RFC-2822 formats: + * UT|GMT + * North American : UTC offsets + * E[DS]T = Eastern : -4 | -5 + * C[DS]T = Central : -5 | -6 + * M[DS]T = Mountain: -6 | -7 + * P[DS]T = Pacific : -7 | -8 + * Military + * [A-IL-M] = -1 ... -9 (J not used) + * [N-Y] = +1 ... +12 + */ + while (isspace(*bp)) + bp++; + + switch (*bp++) { + case 'G': + if (*bp++ != 'M') + return NULL; + /*FALLTHROUGH*/ + case 'U': + if (*bp++ != 'T') + return NULL; + /*FALLTHROUGH*/ + case 'Z': + tm->tm_isdst = 0; #ifdef TM_GMTOFF - tm->TM_GMTOFF = 0; + tm->TM_GMTOFF = 0; #endif #ifdef TM_ZONE - tm->TM_ZONE = utc; + tm->TM_ZONE = utc; #endif - continue; - case '+': - neg = 0; - break; - case '-': - neg = 1; - break; - default: - --bp; - ep = find_string(bp, &i, nast, NULL, 4); - if (ep != NULL) { + continue; + case '+': + neg = 0; + break; + case '-': + neg = 1; + break; + default: + --bp; + ep = find_string(bp, &i, nast, NULL, 4); + if (ep != NULL) { #ifdef TM_GMTOFF - tm->TM_GMTOFF = -5 - i; + tm->TM_GMTOFF = -5 - i; #endif #ifdef TM_ZONE - tm->TM_ZONE = __UNCONST(nast[i]); + tm->TM_ZONE = __UNCONST(nast[i]); #endif - bp = ep; - continue; - } - ep = find_string(bp, &i, nadt, NULL, 4); - if (ep != NULL) { - tm->tm_isdst = 1; + bp = ep; + continue; + } + ep = find_string(bp, &i, nadt, NULL, 4); + if (ep != NULL) { + tm->tm_isdst = 1; #ifdef TM_GMTOFF - tm->TM_GMTOFF = -4 - i; + tm->TM_GMTOFF = -4 - i; #endif #ifdef TM_ZONE - tm->TM_ZONE = __UNCONST(nadt[i]); + tm->TM_ZONE = __UNCONST(nadt[i]); #endif - bp = ep; - continue; - } + bp = ep; + continue; + } - if ((*bp >= 'A' && *bp <= 'I') || - (*bp >= 'L' && *bp <= 'Y')) { + if ((*bp >= 'A' && *bp <= 'I') || (*bp >= 'L' && *bp <= 'Y')) { #ifdef TM_GMTOFF - /* Argh! No 'J'! */ - if (*bp >= 'A' && *bp <= 'I') - tm->TM_GMTOFF = - ('A' - 1) - (int)*bp; - else if (*bp >= 'L' && *bp <= 'M') - tm->TM_GMTOFF = 'A' - (int)*bp; - else if (*bp >= 'N' && *bp <= 'Y') - tm->TM_GMTOFF = (int)*bp - 'M'; + /* Argh! No 'J'! */ + if (*bp >= 'A' && *bp <= 'I') + tm->TM_GMTOFF = ('A' - 1) - (int)*bp; + else if (*bp >= 'L' && *bp <= 'M') + tm->TM_GMTOFF = 'A' - (int)*bp; + else if (*bp >= 'N' && *bp <= 'Y') + tm->TM_GMTOFF = (int)*bp - 'M'; #endif #ifdef TM_ZONE - tm->TM_ZONE = NULL; /* XXX */ + tm->TM_ZONE = NULL; /* XXX */ #endif - bp++; - continue; - } - return NULL; - } - offs = 0; - for (i = 0; i < 4; ) { - if (isdigit(*bp)) { - offs = offs * 10 + (*bp++ - '0'); - i++; - continue; - } - if (i == 2 && *bp == ':') { - bp++; - continue; - } - break; - } - switch (i) { - case 2: - offs *= 100; - break; - case 4: - i = offs % 100; - if (i >= 60) - return NULL; - /* Convert minutes into decimal */ - offs = (offs / 100) * 100 + (i * 50) / 30; - break; - default: - return NULL; - } - if (neg) - offs = -offs; - tm->tm_isdst = 0; /* XXX */ + bp++; + continue; + } + return NULL; + } + offs = 0; + for (i = 0; i < 4;) { + if (isdigit(*bp)) { + offs = offs * 10 + (*bp++ - '0'); + i++; + continue; + } + if (i == 2 && *bp == ':') { + bp++; + continue; + } + break; + } + switch (i) { + case 2: + offs *= 100; + break; + case 4: + i = offs % 100; + if (i >= 60) + return NULL; + /* Convert minutes into decimal */ + offs = (offs / 100) * 100 + (i * 50) / 30; + break; + default: + return NULL; + } + if (neg) + offs = -offs; + tm->tm_isdst = 0; /* XXX */ #ifdef TM_GMTOFF - tm->TM_GMTOFF = offs; + tm->TM_GMTOFF = offs; #endif #ifdef TM_ZONE - tm->TM_ZONE = NULL; /* XXX */ + tm->TM_ZONE = NULL; /* XXX */ #endif - continue; - - /* - * Miscellaneous conversions. - */ - case 'n': /* Any kind of white-space. */ - case 't': - while (isspace(*bp)) - bp++; - LEGAL_ALT(0); - continue; - - - default: /* Unknown/unsupported conversion. */ - return NULL; - } - } - - return (char *)(bp); + continue; + + /* + * Miscellaneous conversions. + */ + case 'n': /* Any kind of white-space. */ + case 't': + while (isspace(*bp)) + bp++; + LEGAL_ALT(0); + continue; + + default: /* Unknown/unsupported conversion. */ + return NULL; + } + } + + return (char *)(bp); } - -static const u_char * -conv_num(const unsigned char *buf, int *dest, unsigned int llim, unsigned int ulim) +static const u_char *conv_num( + const unsigned char *buf, int *dest, unsigned int llim, unsigned int ulim) { - unsigned int result = 0; - unsigned char ch; + unsigned int result = 0; + unsigned char ch; - /* The limit also determines the number of valid digits. */ - unsigned int rulim = ulim; + /* The limit also determines the number of valid digits. */ + unsigned int rulim = ulim; - ch = *buf; - if (ch < '0' || ch > '9') - return NULL; + ch = *buf; + if (ch < '0' || ch > '9') + return NULL; - do { - result *= 10; - result += ch - '0'; - rulim /= 10; - ch = *++buf; - } while ((result * 10 <= ulim) && rulim && ch >= '0' && ch <= '9'); + do { + result *= 10; + result += ch - '0'; + rulim /= 10; + ch = *++buf; + } while ((result * 10 <= ulim) && rulim && ch >= '0' && ch <= '9'); - if (result < llim || result > ulim) - return NULL; + if (result < llim || result > ulim) + return NULL; - *dest = result; - return buf; + *dest = result; + return buf; } -static const u_char * -find_string(const u_char *bp, int *tgt, const char * const *n1, - const char * const *n2, int c) +static const u_char *find_string( + const u_char *bp, int *tgt, const char *const *n1, const char *const *n2, int c) { - int i; - size_t len; - - /* check full name - then abbreviated ones */ - for (; n1 != NULL; n1 = n2, n2 = NULL) { - for (i = 0; i < c; i++, n1++) { - len = strlen(*n1); - if (strncasecmp(*n1, (const char *)bp, len) == 0) { - *tgt = i; - return bp + len; - } - } - } - - /* Nothing matched */ - return NULL; + int i; + size_t len; + + /* check full name - then abbreviated ones */ + for (; n1 != NULL; n1 = n2, n2 = NULL) { + for (i = 0; i < c; i++, n1++) { + len = strlen(*n1); + if (strncasecmp(*n1, (const char *)bp, len) == 0) { + *tgt = i; + return bp + len; + } + } + } + + /* Nothing matched */ + return NULL; } #endif /* HAVE_STRPTIME */ diff --git a/src/util-syslog.c b/src/util-syslog.c index 482f206789aa..8565e4791d8e 100644 --- a/src/util-syslog.c +++ b/src/util-syslog.c @@ -28,30 +28,13 @@ #include "util-syslog.h" /* holds the string-enum mapping for the syslog facility in SCLogOPIfaceCtx */ -SCEnumCharMap sc_syslog_facility_map[] = { - { "auth", LOG_AUTH }, - { "authpriv", LOG_AUTHPRIV }, - { "cron", LOG_CRON }, - { "daemon", LOG_DAEMON }, - { "ftp", LOG_FTP }, - { "kern", LOG_KERN }, - { "lpr", LOG_LPR }, - { "mail", LOG_MAIL }, - { "news", LOG_NEWS }, - { "security", LOG_AUTH }, - { "syslog", LOG_SYSLOG }, - { "user", LOG_USER }, - { "uucp", LOG_UUCP }, - { "local0", LOG_LOCAL0 }, - { "local1", LOG_LOCAL1 }, - { "local2", LOG_LOCAL2 }, - { "local3", LOG_LOCAL3 }, - { "local4", LOG_LOCAL4 }, - { "local5", LOG_LOCAL5 }, - { "local6", LOG_LOCAL6 }, - { "local7", LOG_LOCAL7 }, - { NULL, -1 } -}; +SCEnumCharMap sc_syslog_facility_map[] = { { "auth", LOG_AUTH }, { "authpriv", LOG_AUTHPRIV }, + { "cron", LOG_CRON }, { "daemon", LOG_DAEMON }, { "ftp", LOG_FTP }, { "kern", LOG_KERN }, + { "lpr", LOG_LPR }, { "mail", LOG_MAIL }, { "news", LOG_NEWS }, { "security", LOG_AUTH }, + { "syslog", LOG_SYSLOG }, { "user", LOG_USER }, { "uucp", LOG_UUCP }, { "local0", LOG_LOCAL0 }, + { "local1", LOG_LOCAL1 }, { "local2", LOG_LOCAL2 }, { "local3", LOG_LOCAL3 }, + { "local4", LOG_LOCAL4 }, { "local5", LOG_LOCAL5 }, { "local6", LOG_LOCAL6 }, + { "local7", LOG_LOCAL7 }, { NULL, -1 } }; /** \brief returns the syslog facility enum map */ SCEnumCharMap *SCSyslogGetFacilityMap(void) @@ -59,21 +42,12 @@ SCEnumCharMap *SCSyslogGetFacilityMap(void) return sc_syslog_facility_map; } -SCEnumCharMap sc_syslog_level_map[ ] = { - { "Emergency", LOG_EMERG }, - { "Alert", LOG_ALERT }, - { "Critical", LOG_CRIT }, - { "Error", LOG_ERR }, - { "Warning", LOG_WARNING }, - { "Notice", LOG_NOTICE }, - { "Info", LOG_INFO }, - { "Debug", LOG_DEBUG }, - { NULL, -1 } -}; +SCEnumCharMap sc_syslog_level_map[] = { { "Emergency", LOG_EMERG }, { "Alert", LOG_ALERT }, + { "Critical", LOG_CRIT }, { "Error", LOG_ERR }, { "Warning", LOG_WARNING }, + { "Notice", LOG_NOTICE }, { "Info", LOG_INFO }, { "Debug", LOG_DEBUG }, { NULL, -1 } }; /** \brief returns the syslog facility enum map */ SCEnumCharMap *SCSyslogGetLogLevelMap(void) { return sc_syslog_level_map; } - diff --git a/src/util-syslog.h b/src/util-syslog.h index 473057a102a0..94d0ae2f206b 100644 --- a/src/util-syslog.h +++ b/src/util-syslog.h @@ -23,7 +23,7 @@ */ #ifndef UTIL_SYSLOG_H -#define UTIL_SYSLOG_H +#define UTIL_SYSLOG_H #include "util-enum.h" @@ -36,4 +36,4 @@ SCEnumCharMap *SCSyslogGetLogLevelMap(void); #define DEFAULT_ALERT_SYSLOG_LEVEL LOG_ERR #endif -#endif /* UTIL_SYSLOG_H */ +#endif /* UTIL_SYSLOG_H */ diff --git a/src/util-thash.c b/src/util-thash.c index 6443990bc219..678e2c76deef 100644 --- a/src/util-thash.c +++ b/src/util-thash.c @@ -36,15 +36,15 @@ #include "util-validate.h" static THashData *THashGetUsed(THashTableContext *ctx); -static void THashDataEnqueue (THashDataQueue *q, THashData *h); +static void THashDataEnqueue(THashDataQueue *q, THashData *h); void THashDataMoveToSpare(THashTableContext *ctx, THashData *h) { THashDataEnqueue(&ctx->spare_q, h); - (void) SC_ATOMIC_SUB(ctx->counter, 1); + (void)SC_ATOMIC_SUB(ctx->counter, 1); } -static THashDataQueue *THashDataQueueInit (THashDataQueue *q) +static THashDataQueue *THashDataQueueInit(THashDataQueue *q) { if (q != NULL) { memset(q, 0, sizeof(THashDataQueue)); @@ -69,7 +69,7 @@ THashDataQueue *THashDataQueueNew(void) * * \param q the queue to destroy */ -static void THashDataQueueDestroy (THashDataQueue *q) +static void THashDataQueueDestroy(THashDataQueue *q) { HQLOCK_DESTROY(q); } @@ -80,7 +80,7 @@ static void THashDataQueueDestroy (THashDataQueue *q) * \param q queue * \param h data */ -static void THashDataEnqueue (THashDataQueue *q, THashData *h) +static void THashDataEnqueue(THashDataQueue *q, THashData *h) { #ifdef DEBUG BUG_ON(q == NULL || h == NULL); @@ -93,7 +93,7 @@ static void THashDataEnqueue (THashDataQueue *q, THashData *h) h->next = q->top; q->top->prev = h; q->top = h; - /* only data */ + /* only data */ } else { q->top = h; q->bot = h; @@ -113,7 +113,7 @@ static void THashDataEnqueue (THashDataQueue *q, THashData *h) * * \retval h data or NULL if empty list. */ -static THashData *THashDataDequeue (THashDataQueue *q) +static THashData *THashDataDequeue(THashDataQueue *q) { HQLOCK_LOCK(q); @@ -127,7 +127,7 @@ static THashData *THashDataDequeue (THashDataQueue *q) if (q->bot->prev != NULL) { q->bot = q->bot->prev; q->bot->next = NULL; - /* just the one we remove, so now empty */ + /* just the one we remove, so now empty */ } else { q->top = NULL; q->bot = NULL; @@ -165,7 +165,7 @@ static THashData *THashDataAlloc(THashTableContext *ctx) return NULL; } - (void) SC_ATOMIC_ADD(ctx->memuse, data_size); + (void)SC_ATOMIC_ADD(ctx->memuse, data_size); THashData *h = SCCalloc(1, data_size); if (unlikely(h == NULL)) @@ -174,7 +174,7 @@ static THashData *THashDataAlloc(THashTableContext *ctx) /* points to data right after THashData block */ h->data = (uint8_t *)h + sizeof(THashData); -// memset(h, 0x00, data_size); + // memset(h, 0x00, data_size); SCMutexInit(&h->m, NULL); SC_ATOMIC_INIT(h->use_cnt); @@ -194,16 +194,15 @@ static void THashDataFree(THashTableContext *ctx, THashData *h) } SCMutexDestroy(&h->m); SCFree(h); - (void) SC_ATOMIC_SUB(ctx->memuse, THASH_DATA_SIZE(ctx)); + (void)SC_ATOMIC_SUB(ctx->memuse, THASH_DATA_SIZE(ctx)); } } #define THASH_DEFAULT_HASHSIZE 4096 -#define THASH_DEFAULT_MEMCAP 16777216 +#define THASH_DEFAULT_MEMCAP 16777216 #define THASH_DEFAULT_PREALLOC 1000 -#define GET_VAR(prefix,name) \ - snprintf(varname, sizeof(varname), "%s.%s", (prefix), (name)) +#define GET_VAR(prefix, name) snprintf(varname, sizeof(varname), "%s.%s", (prefix), (name)) /** \brief initialize the configuration * \warning Not thread safe */ @@ -219,8 +218,7 @@ static int THashInitConfig(THashTableContext *ctx, const char *cnf_prefix) /** set config values for memcap, prealloc and hash_size */ GET_VAR(cnf_prefix, "memcap"); - if ((ConfGet(varname, &conf_val)) == 1) - { + if ((ConfGet(varname, &conf_val)) == 1) { if (ParseSizeStringU64(conf_val, &ctx->config.memcap) < 0) { SCLogError("Error parsing %s " "from conf file - %s. Killing engine", @@ -229,20 +227,18 @@ static int THashInitConfig(THashTableContext *ctx, const char *cnf_prefix) } } GET_VAR(cnf_prefix, "hash-size"); - if ((ConfGet(varname, &conf_val)) == 1) - { + if ((ConfGet(varname, &conf_val)) == 1) { if (StringParseUint32(&configval, 10, (uint16_t)strlen(conf_val), conf_val) > 0) { ctx->config.hash_size = configval; } } GET_VAR(cnf_prefix, "prealloc"); - if ((ConfGet(varname, &conf_val)) == 1) - { + if ((ConfGet(varname, &conf_val)) == 1) { if (StringParseUint32(&configval, 10, (uint16_t)strlen(conf_val), conf_val) > 0) { ctx->config.prealloc = configval; } else { - WarnInvalidConfEntry(varname, "%"PRIu32, ctx->config.prealloc); + WarnInvalidConfEntry(varname, "%" PRIu32, ctx->config.prealloc); } } @@ -268,7 +264,7 @@ static int THashInitConfig(THashTableContext *ctx, const char *cnf_prefix) for (i = 0; i < ctx->config.hash_size; i++) { HRLOCK_INIT(&ctx->array[i]); } - (void) SC_ATOMIC_ADD(ctx->memuse, (ctx->config.hash_size * sizeof(THashHashRow))); + (void)SC_ATOMIC_ADD(ctx->memuse, (ctx->config.hash_size * sizeof(THashHashRow))); /* pre allocate prealloc */ for (i = 0; i < ctx->config.prealloc; i++) { @@ -286,7 +282,7 @@ static int THashInitConfig(THashTableContext *ctx, const char *cnf_prefix) SCLogError("preallocating data failed: %s", strerror(errno)); return -1; } - THashDataEnqueue(&ctx->spare_q,h); + THashDataEnqueue(&ctx->spare_q, h); } return 0; @@ -369,7 +365,7 @@ void THashShutdown(THashTableContext *ctx) SCFreeAligned(ctx->array); ctx->array = NULL; } - (void) SC_ATOMIC_SUB(ctx->memuse, ctx->config.hash_size * sizeof(THashHashRow)); + (void)SC_ATOMIC_SUB(ctx->memuse, ctx->config.hash_size * sizeof(THashHashRow)); THashDataQueueDestroy(&ctx->spare_q); SCFree(ctx); return; @@ -378,7 +374,8 @@ void THashShutdown(THashTableContext *ctx) /** \brief Walk the hash * */ -int THashWalk(THashTableContext *ctx, THashFormatFunc FormatterFunc, THashOutputFunc OutputterFunc, void *output_ctx) +int THashWalk(THashTableContext *ctx, THashFormatFunc FormatterFunc, THashOutputFunc OutputterFunc, + void *output_ctx) { uint32_t u; @@ -517,7 +514,7 @@ static THashData *THashDataGetNew(THashTableContext *ctx, void *data) // setup the data BUG_ON(ctx->config.DataSet(h->data, data) != 0); - (void) SC_ATOMIC_ADD(ctx->counter, 1); + (void)SC_ATOMIC_ADD(ctx->counter, 1); SCMutexLock(&h->m); return h; } @@ -526,10 +523,12 @@ static THashData *THashDataGetNew(THashTableContext *ctx, void *data) * returns a *LOCKED* data or NULL */ -struct THashDataGetResult -THashGetFromHash (THashTableContext *ctx, void *data) +struct THashDataGetResult THashGetFromHash(THashTableContext *ctx, void *data) { - struct THashDataGetResult res = { .data = NULL, .is_new = false, }; + struct THashDataGetResult res = { + .data = NULL, + .is_new = false, + }; THashData *h = NULL; /* get the key to our bucket */ @@ -551,7 +550,7 @@ THashGetFromHash (THashTableContext *ctx, void *data) hb->tail = h; /* initialize and return */ - (void) THashIncrUsecnt(h); + (void)THashIncrUsecnt(h); HRLOCK_UNLOCK(hb); res.data = h; @@ -583,7 +582,7 @@ THashGetFromHash (THashTableContext *ctx, void *data) h->prev = ph; /* initialize and return */ - (void) THashIncrUsecnt(h); + (void)THashIncrUsecnt(h); HRLOCK_UNLOCK(hb); res.data = h; @@ -611,7 +610,7 @@ THashGetFromHash (THashTableContext *ctx, void *data) /* found our data, lock & return */ SCMutexLock(&h->m); - (void) THashIncrUsecnt(h); + (void)THashIncrUsecnt(h); HRLOCK_UNLOCK(hb); res.data = h; res.is_new = false; @@ -623,7 +622,7 @@ THashGetFromHash (THashTableContext *ctx, void *data) /* lock & return */ SCMutexLock(&h->m); - (void) THashIncrUsecnt(h); + (void)THashIncrUsecnt(h); HRLOCK_UNLOCK(hb); res.data = h; res.is_new = false; @@ -637,7 +636,7 @@ THashGetFromHash (THashTableContext *ctx, void *data) * * \retval h *LOCKED* data or NULL */ -THashData *THashLookupFromHash (THashTableContext *ctx, void *data) +THashData *THashLookupFromHash(THashTableContext *ctx, void *data) { THashData *h = NULL; @@ -684,7 +683,7 @@ THashData *THashLookupFromHash (THashTableContext *ctx, void *data) /* found our data, lock & return */ SCMutexLock(&h->m); - (void) THashIncrUsecnt(h); + (void)THashIncrUsecnt(h); HRLOCK_UNLOCK(hb); return h; } @@ -693,7 +692,7 @@ THashData *THashLookupFromHash (THashTableContext *ctx, void *data) /* lock & return */ SCMutexLock(&h->m); - (void) THashIncrUsecnt(h); + (void)THashIncrUsecnt(h); HRLOCK_UNLOCK(hb); return h; } @@ -761,7 +760,7 @@ static THashData *THashGetUsed(THashTableContext *ctx) } SCMutexUnlock(&h->m); - (void) SC_ATOMIC_ADD(ctx->prune_idx, (ctx->config.hash_size - cnt)); + (void)SC_ATOMIC_ADD(ctx->prune_idx, (ctx->config.hash_size - cnt)); return h; } @@ -772,7 +771,7 @@ static THashData *THashGetUsed(THashTableContext *ctx) * \retval int -1 not found * \retval int 0 found, but it was busy (ref cnt) * \retval int 1 found and removed */ -int THashRemoveFromHash (THashTableContext *ctx, void *data) +int THashRemoveFromHash(THashTableContext *ctx, void *data) { /* get the key to our bucket */ uint32_t key = THashGetKey(&ctx->config, data); diff --git a/src/util-thash.h b/src/util-thash.h index 9618d5c06442..671530913720 100644 --- a/src/util-thash.h +++ b/src/util-thash.h @@ -33,27 +33,27 @@ #define HRLOCK_MUTEX #ifdef HRLOCK_SPIN - #ifdef HRLOCK_MUTEX - #error Cannot enable both HRLOCK_SPIN and HRLOCK_MUTEX - #endif +#ifdef HRLOCK_MUTEX +#error Cannot enable both HRLOCK_SPIN and HRLOCK_MUTEX +#endif #endif #ifdef HRLOCK_SPIN - #define HRLOCK_TYPE SCSpinlock - #define HRLOCK_INIT(fb) SCSpinInit(&(fb)->lock, 0) - #define HRLOCK_DESTROY(fb) SCSpinDestroy(&(fb)->lock) - #define HRLOCK_LOCK(fb) SCSpinLock(&(fb)->lock) - #define HRLOCK_TRYLOCK(fb) SCSpinTrylock(&(fb)->lock) - #define HRLOCK_UNLOCK(fb) SCSpinUnlock(&(fb)->lock) +#define HRLOCK_TYPE SCSpinlock +#define HRLOCK_INIT(fb) SCSpinInit(&(fb)->lock, 0) +#define HRLOCK_DESTROY(fb) SCSpinDestroy(&(fb)->lock) +#define HRLOCK_LOCK(fb) SCSpinLock(&(fb)->lock) +#define HRLOCK_TRYLOCK(fb) SCSpinTrylock(&(fb)->lock) +#define HRLOCK_UNLOCK(fb) SCSpinUnlock(&(fb)->lock) #elif defined HRLOCK_MUTEX - #define HRLOCK_TYPE SCMutex - #define HRLOCK_INIT(fb) SCMutexInit(&(fb)->lock, NULL) - #define HRLOCK_DESTROY(fb) SCMutexDestroy(&(fb)->lock) - #define HRLOCK_LOCK(fb) SCMutexLock(&(fb)->lock) - #define HRLOCK_TRYLOCK(fb) SCMutexTrylock(&(fb)->lock) - #define HRLOCK_UNLOCK(fb) SCMutexUnlock(&(fb)->lock) +#define HRLOCK_TYPE SCMutex +#define HRLOCK_INIT(fb) SCMutexInit(&(fb)->lock, NULL) +#define HRLOCK_DESTROY(fb) SCMutexDestroy(&(fb)->lock) +#define HRLOCK_LOCK(fb) SCMutexLock(&(fb)->lock) +#define HRLOCK_TRYLOCK(fb) SCMutexTrylock(&(fb)->lock) +#define HRLOCK_UNLOCK(fb) SCMutexUnlock(&(fb)->lock) #else - #error Enable HRLOCK_SPIN or HRLOCK_MUTEX +#error Enable HRLOCK_SPIN or HRLOCK_MUTEX #endif /** Spinlocks or Mutex for the queues. */ @@ -61,25 +61,25 @@ #define HQLOCK_MUTEX #ifdef HQLOCK_SPIN - #ifdef HQLOCK_MUTEX - #error Cannot enable both HQLOCK_SPIN and HQLOCK_MUTEX - #endif +#ifdef HQLOCK_MUTEX +#error Cannot enable both HQLOCK_SPIN and HQLOCK_MUTEX +#endif #endif #ifdef HQLOCK_SPIN - #define HQLOCK_INIT(q) SCSpinInit(&(q)->s, 0) - #define HQLOCK_DESTROY(q) SCSpinDestroy(&(q)->s) - #define HQLOCK_LOCK(q) SCSpinLock(&(q)->s) - #define HQLOCK_TRYLOCK(q) SCSpinTrylock(&(q)->s) - #define HQLOCK_UNLOCK(q) SCSpinUnlock(&(q)->s) +#define HQLOCK_INIT(q) SCSpinInit(&(q)->s, 0) +#define HQLOCK_DESTROY(q) SCSpinDestroy(&(q)->s) +#define HQLOCK_LOCK(q) SCSpinLock(&(q)->s) +#define HQLOCK_TRYLOCK(q) SCSpinTrylock(&(q)->s) +#define HQLOCK_UNLOCK(q) SCSpinUnlock(&(q)->s) #elif defined HQLOCK_MUTEX - #define HQLOCK_INIT(q) SCMutexInit(&(q)->m, NULL) - #define HQLOCK_DESTROY(q) SCMutexDestroy(&(q)->m) - #define HQLOCK_LOCK(q) SCMutexLock(&(q)->m) - #define HQLOCK_TRYLOCK(q) SCMutexTrylock(&(q)->m) - #define HQLOCK_UNLOCK(q) SCMutexUnlock(&(q)->m) +#define HQLOCK_INIT(q) SCMutexInit(&(q)->m, NULL) +#define HQLOCK_DESTROY(q) SCMutexDestroy(&(q)->m) +#define HQLOCK_LOCK(q) SCMutexLock(&(q)->m) +#define HQLOCK_TRYLOCK(q) SCMutexTrylock(&(q)->m) +#define HQLOCK_UNLOCK(q) SCMutexUnlock(&(q)->m) #else - #error Enable HQLOCK_SPIN or HQLOCK_MUTEX +#error Enable HQLOCK_SPIN or HQLOCK_MUTEX #endif typedef struct THashData_ { @@ -101,8 +101,7 @@ typedef struct THashHashRow_ { THashData *tail; } __attribute__((aligned(CLS))) THashHashRow; -typedef struct THashDataQueue_ -{ +typedef struct THashDataQueue_ { THashData *top; THashData *bot; uint32_t len; @@ -114,7 +113,7 @@ typedef struct THashDataQueue_ #elif defined HQLOCK_SPIN SCSpinlock s; #else - #error Enable HQLOCK_SPIN or HQLOCK_MUTEX +#error Enable HQLOCK_SPIN or HQLOCK_MUTEX #endif } THashDataQueue; @@ -159,13 +158,11 @@ typedef struct THashTableContext_ { * \retval 1 it fits * \retval 0 no fit */ -#define THASH_CHECK_MEMCAP(ctx, size) \ +#define THASH_CHECK_MEMCAP(ctx, size) \ ((((uint64_t)SC_ATOMIC_GET((ctx)->memuse) + (uint64_t)(size)) <= (ctx)->config.memcap)) -#define THashIncrUsecnt(h) \ - (void)SC_ATOMIC_ADD((h)->use_cnt, 1) -#define THashDecrUsecnt(h) \ - (void)SC_ATOMIC_SUB((h)->use_cnt, 1) +#define THashIncrUsecnt(h) (void)SC_ATOMIC_ADD((h)->use_cnt, 1) +#define THashDecrUsecnt(h) (void)SC_ATOMIC_SUB((h)->use_cnt, 1) THashTableContext *THashInit(const char *cnf_prefix, size_t data_size, int (*DataSet)(void *dst, void *src), void (*DataFree)(void *), @@ -189,12 +186,12 @@ struct THashDataGetResult { bool is_new; }; -struct THashDataGetResult THashGetFromHash (THashTableContext *ctx, void *data); -THashData *THashLookupFromHash (THashTableContext *ctx, void *data); +struct THashDataGetResult THashGetFromHash(THashTableContext *ctx, void *data); +THashData *THashLookupFromHash(THashTableContext *ctx, void *data); THashDataQueue *THashDataQueueNew(void); void THashCleanup(THashTableContext *ctx); int THashWalk(THashTableContext *, THashFormatFunc, THashOutputFunc, void *); -int THashRemoveFromHash (THashTableContext *ctx, void *data); +int THashRemoveFromHash(THashTableContext *ctx, void *data); void THashConsolidateMemcap(THashTableContext *ctx); void THashDataMoveToSpare(THashTableContext *ctx, THashData *h); diff --git a/src/util-threshold-config.c b/src/util-threshold-config.c index 70cc41a73e91..b4b9d73674e8 100644 --- a/src/util-threshold-config.c +++ b/src/util-threshold-config.c @@ -64,22 +64,28 @@ static FILE *g_ut_threshold_fp = NULL; #endif /* common base for all options */ -#define DETECT_BASE_REGEX "^\\s*(event_filter|threshold|rate_filter|suppress)\\s*gen_id\\s*(\\d+)\\s*,\\s*sig_id\\s*(\\d+)\\s*(.*)\\s*$" +#define DETECT_BASE_REGEX \ + "^\\s*(event_filter|threshold|rate_filter|suppress)\\s*gen_id\\s*(\\d+)\\s*,\\s*sig_id\\s*(" \ + "\\d+)\\s*(.*)\\s*$" #define DETECT_THRESHOLD_REGEX \ "^,\\s*type\\s*(limit|both|threshold)\\s*,\\s*track\\s*(by_dst|by_src|by_both|by_rule)\\s*," \ "\\s*count\\s*(\\d+)\\s*,\\s*seconds\\s*(\\d+)\\s*$" /* TODO: "apply_to" */ -#define DETECT_RATE_REGEX "^,\\s*track\\s*(by_dst|by_src|by_both|by_rule)\\s*,\\s*count\\s*(\\d+)\\s*,\\s*seconds\\s*(\\d+)\\s*,\\s*new_action\\s*(alert|drop|pass|log|sdrop|reject)\\s*,\\s*timeout\\s*(\\d+)\\s*$" +#define DETECT_RATE_REGEX \ + "^,\\s*track\\s*(by_dst|by_src|by_both|by_rule)\\s*,\\s*count\\s*(\\d+)\\s*,\\s*seconds\\s*(" \ + "\\d+)\\s*,\\s*new_action\\s*(alert|drop|pass|log|sdrop|reject)\\s*,\\s*timeout\\s*(\\d+)\\s*" \ + "$" /* * suppress has two form: * suppress gen_id 0, sig_id 0, track by_dst, ip 10.88.0.14 * suppress gen_id 1, sig_id 2000328 * suppress gen_id 1, sig_id 2000328, track by_src, ip fe80::/10 -*/ -#define DETECT_SUPPRESS_REGEX "^,\\s*track\\s*(by_dst|by_src|by_either)\\s*,\\s*ip\\s*([\\[\\],\\$\\s\\da-zA-Z.:/_]+)*\\s*$" + */ +#define DETECT_SUPPRESS_REGEX \ + "^,\\s*track\\s*(by_dst|by_src|by_either)\\s*,\\s*ip\\s*([\\[\\],\\$\\s\\da-zA-Z.:/_]+)*\\s*$" /* Default path for the threshold.config file */ #if defined OS_WIN32 || defined __CYGWIN__ @@ -130,8 +136,7 @@ static const char *SCThresholdConfGetConfFilename(const DetectEngineCtx *de_ctx) if (de_ctx != NULL && strlen(de_ctx->config_prefix) > 0) { char config_value[256]; - snprintf(config_value, sizeof(config_value), - "%s.threshold-file", de_ctx->config_prefix); + snprintf(config_value, sizeof(config_value), "%s.threshold-file", de_ctx->config_prefix); /* try loading prefix setting, fall back to global if that * fails. */ @@ -172,32 +177,32 @@ int SCThresholdConfInitContext(DetectEngineCtx *de_ctx) FILE *fd = g_ut_threshold_fp; if (fd == NULL) { #endif - filename = SCThresholdConfGetConfFilename(de_ctx); - if ( (fd = fopen(filename, "r")) == NULL) { - SCLogWarning("Error opening file: \"%s\": %s", filename, strerror(errno)); - SCThresholdConfDeInitContext(de_ctx, fd); - return 0; - } -#ifdef UNITTESTS + filename = SCThresholdConfGetConfFilename(de_ctx); + if ((fd = fopen(filename, "r")) == NULL) { + SCLogWarning("Error opening file: \"%s\": %s", filename, strerror(errno)); + SCThresholdConfDeInitContext(de_ctx, fd); + return 0; } +#ifdef UNITTESTS +} #endif - if (SCThresholdConfParseFile(de_ctx, fd) < 0) { - SCLogWarning("Error loading threshold configuration from %s", filename); - SCThresholdConfDeInitContext(de_ctx, fd); - /* maintain legacy behavior so no errors unless config testing */ - if (RunmodeGetCurrent() == RUNMODE_CONF_TEST) { - ret = -1; - } - return ret; - } +if (SCThresholdConfParseFile(de_ctx, fd) < 0) { + SCLogWarning("Error loading threshold configuration from %s", filename); SCThresholdConfDeInitContext(de_ctx, fd); + /* maintain legacy behavior so no errors unless config testing */ + if (RunmodeGetCurrent() == RUNMODE_CONF_TEST) { + ret = -1; + } + return ret; +} +SCThresholdConfDeInitContext(de_ctx, fd); #ifdef UNITTESTS - g_ut_threshold_fp = NULL; +g_ut_threshold_fp = NULL; #endif - SCLogDebug("Global thresholding options defined"); - return 0; +SCLogDebug("Global thresholding options defined"); +return 0; } /** @@ -219,9 +224,8 @@ static void SCThresholdConfDeInitContext(DetectEngineCtx *de_ctx, FILE *fd) * \retval -1 error */ static int SetupSuppressRule(DetectEngineCtx *de_ctx, uint32_t id, uint32_t gid, - uint8_t parsed_type, uint8_t parsed_track, uint32_t parsed_count, - uint32_t parsed_seconds, uint32_t parsed_timeout, uint8_t parsed_new_action, - const char *th_ip) + uint8_t parsed_type, uint8_t parsed_track, uint32_t parsed_count, uint32_t parsed_seconds, + uint32_t parsed_timeout, uint8_t parsed_new_action, const char *th_ip) { Signature *s = NULL; DetectThresholdData *de = NULL; @@ -270,7 +274,7 @@ static int SetupSuppressRule(DetectEngineCtx *de_ctx, uint32_t id, uint32_t gid, goto error; } } - } else if (id == 0 && gid > 0) { + } else if (id == 0 && gid > 0) { if (parsed_track == TRACK_RULE) { SCLogWarning("suppressing all rules with gid %" PRIu32, gid); } @@ -346,9 +350,8 @@ static int SetupSuppressRule(DetectEngineCtx *de_ctx, uint32_t id, uint32_t gid, * \retval -1 error */ static int SetupThresholdRule(DetectEngineCtx *de_ctx, uint32_t id, uint32_t gid, - uint8_t parsed_type, uint8_t parsed_track, uint32_t parsed_count, - uint32_t parsed_seconds, uint32_t parsed_timeout, uint8_t parsed_new_action, - const char *th_ip) + uint8_t parsed_type, uint8_t parsed_track, uint32_t parsed_count, uint32_t parsed_seconds, + uint32_t parsed_timeout, uint8_t parsed_new_action, const char *th_ip) { Signature *s = NULL; SigMatch *sm = NULL; @@ -369,8 +372,7 @@ static int SetupThresholdRule(DetectEngineCtx *de_ctx, uint32_t id, uint32_t gid continue; } - sm = DetectGetLastSMByListId(s, - DETECT_SM_LIST_THRESHOLD, DETECT_DETECTION_FILTER, -1); + sm = DetectGetLastSMByListId(s, DETECT_SM_LIST_THRESHOLD, DETECT_DETECTION_FILTER, -1); if (sm != NULL) { SCLogWarning("signature sid:%" PRIu32 " has " "an event var set. The signature event var is " @@ -404,8 +406,8 @@ static int SetupThresholdRule(DetectEngineCtx *de_ctx, uint32_t id, uint32_t gid } else if (id == 0 && gid > 0) { for (s = de_ctx->sig_list; s != NULL; s = s->next) { if (s->gid == gid) { - sm = DetectGetLastSMByListId(s, DETECT_SM_LIST_THRESHOLD, - DETECT_THRESHOLD, DETECT_DETECTION_FILTER, -1); + sm = DetectGetLastSMByListId( + s, DETECT_SM_LIST_THRESHOLD, DETECT_THRESHOLD, DETECT_DETECTION_FILTER, -1); if (sm != NULL) { SCLogWarning("signature sid:%" PRIu32 " has " "an event var set. The signature event var is " @@ -448,10 +450,8 @@ static int SetupThresholdRule(DetectEngineCtx *de_ctx, uint32_t id, uint32_t gid id, gid); } else { if (parsed_type != TYPE_SUPPRESS && parsed_type != TYPE_THRESHOLD && - parsed_type != TYPE_BOTH && parsed_type != TYPE_LIMIT) - { - sm = DetectGetLastSMByListId(s, - DETECT_SM_LIST_THRESHOLD, DETECT_THRESHOLD, -1); + parsed_type != TYPE_BOTH && parsed_type != TYPE_LIMIT) { + sm = DetectGetLastSMByListId(s, DETECT_SM_LIST_THRESHOLD, DETECT_THRESHOLD, -1); if (sm != NULL) { SCLogWarning("signature sid:%" PRIu32 " has " "a threshold set. The signature event var is " @@ -461,8 +461,8 @@ static int SetupThresholdRule(DetectEngineCtx *de_ctx, uint32_t id, uint32_t gid goto end; } - sm = DetectGetLastSMByListId(s, DETECT_SM_LIST_THRESHOLD, - DETECT_DETECTION_FILTER, -1); + sm = DetectGetLastSMByListId( + s, DETECT_SM_LIST_THRESHOLD, DETECT_DETECTION_FILTER, -1); if (sm != NULL) { SCLogWarning("signature sid:%" PRIu32 " has " "a detection_filter set. The signature event var is " @@ -472,10 +472,11 @@ static int SetupThresholdRule(DetectEngineCtx *de_ctx, uint32_t id, uint32_t gid goto end; } - /* replace threshold on sig if we have a global override for it */ - } else if (parsed_type == TYPE_THRESHOLD || parsed_type == TYPE_BOTH || parsed_type == TYPE_LIMIT) { - sm = DetectGetLastSMByListId(s, DETECT_SM_LIST_THRESHOLD, - DETECT_THRESHOLD, DETECT_DETECTION_FILTER, -1); + /* replace threshold on sig if we have a global override for it */ + } else if (parsed_type == TYPE_THRESHOLD || parsed_type == TYPE_BOTH || + parsed_type == TYPE_LIMIT) { + sm = DetectGetLastSMByListId( + s, DETECT_SM_LIST_THRESHOLD, DETECT_THRESHOLD, DETECT_DETECTION_FILTER, -1); if (sm != NULL) { SigMatchRemoveSMFromList(s, sm, DETECT_SM_LIST_THRESHOLD); SigMatchFree(de_ctx, sm); @@ -591,13 +592,13 @@ static int ParseThresholdRule(const DetectEngineCtx *de_ctx, char *rawstr, uint3 regex_base_match = NULL; /* get type of rule */ - if (strcasecmp(th_rule_type,"event_filter") == 0) { + if (strcasecmp(th_rule_type, "event_filter") == 0) { rule_type = THRESHOLD_TYPE_EVENT_FILTER; - } else if (strcasecmp(th_rule_type,"threshold") == 0) { + } else if (strcasecmp(th_rule_type, "threshold") == 0) { rule_type = THRESHOLD_TYPE_THRESHOLD; - } else if (strcasecmp(th_rule_type,"rate_filter") == 0) { + } else if (strcasecmp(th_rule_type, "rate_filter") == 0) { rule_type = THRESHOLD_TYPE_RATE; - } else if (strcasecmp(th_rule_type,"suppress") == 0) { + } else if (strcasecmp(th_rule_type, "suppress") == 0) { rule_type = THRESHOLD_TYPE_SUPPRESS; } else { SCLogError("rule type %s is unknown", th_rule_type); @@ -605,7 +606,7 @@ static int ParseThresholdRule(const DetectEngineCtx *de_ctx, char *rawstr, uint3 } /* get end of rule */ - switch(rule_type) { + switch (rule_type) { case THRESHOLD_TYPE_EVENT_FILTER: case THRESHOLD_TYPE_THRESHOLD: if (strlen(rule_extend) > 0) { @@ -652,11 +653,11 @@ static int ParseThresholdRule(const DetectEngineCtx *de_ctx, char *rawstr, uint3 } pcre2_match_data_free(match); - if (strcasecmp(th_type,"limit") == 0) + if (strcasecmp(th_type, "limit") == 0) parsed_type = TYPE_LIMIT; - else if (strcasecmp(th_type,"both") == 0) + else if (strcasecmp(th_type, "both") == 0) parsed_type = TYPE_BOTH; - else if (strcasecmp(th_type,"threshold") == 0) + else if (strcasecmp(th_type, "threshold") == 0) parsed_type = TYPE_THRESHOLD; else { SCLogError("limit type not supported: %s", th_type); @@ -787,14 +788,13 @@ static int ParseThresholdRule(const DetectEngineCtx *de_ctx, char *rawstr, uint3 case THRESHOLD_TYPE_EVENT_FILTER: case THRESHOLD_TYPE_THRESHOLD: case THRESHOLD_TYPE_RATE: - if (strcasecmp(th_track,"by_dst") == 0) + if (strcasecmp(th_track, "by_dst") == 0) parsed_track = TRACK_DST; - else if (strcasecmp(th_track,"by_src") == 0) + else if (strcasecmp(th_track, "by_src") == 0) parsed_track = TRACK_SRC; else if (strcasecmp(th_track, "by_both") == 0) { parsed_track = TRACK_BOTH; - } - else if (strcasecmp(th_track,"by_rule") == 0) + } else if (strcasecmp(th_track, "by_rule") == 0) parsed_track = TRACK_RULE; else { SCLogError("Invalid track parameter %s in %s", th_track, rawstr); @@ -813,18 +813,17 @@ static int ParseThresholdRule(const DetectEngineCtx *de_ctx, char *rawstr, uint3 goto error; } - break; + break; case THRESHOLD_TYPE_SUPPRESS: /* need to get IP if extension is provided */ if (strcmp("", th_track) != 0) { - if (strcasecmp(th_track,"by_dst") == 0) + if (strcasecmp(th_track, "by_dst") == 0) parsed_track = TRACK_DST; - else if (strcasecmp(th_track,"by_src") == 0) + else if (strcasecmp(th_track, "by_src") == 0) parsed_track = TRACK_SRC; - else if (strcasecmp(th_track,"by_either") == 0) { + else if (strcasecmp(th_track, "by_either") == 0) { parsed_track = TRACK_EITHER; - } - else { + } else { SCLogError("Invalid track parameter %s in %s", th_track, rule_extend); goto error; } @@ -892,13 +891,11 @@ static int SCThresholdConfAddThresholdtype(char *rawstr, DetectEngineCtx *de_ctx goto error; if (parsed_type == TYPE_SUPPRESS) { - r = SetupSuppressRule(de_ctx, id, gid, parsed_type, parsed_track, - parsed_count, parsed_seconds, parsed_timeout, parsed_new_action, - th_ip); + r = SetupSuppressRule(de_ctx, id, gid, parsed_type, parsed_track, parsed_count, + parsed_seconds, parsed_timeout, parsed_new_action, th_ip); } else { - r = SetupThresholdRule(de_ctx, id, gid, parsed_type, parsed_track, - parsed_count, parsed_seconds, parsed_timeout, parsed_new_action, - th_ip); + r = SetupThresholdRule(de_ctx, id, gid, parsed_type, parsed_track, parsed_count, + parsed_seconds, parsed_timeout, parsed_new_action, th_ip); } if (r < 0) { goto error; @@ -960,9 +957,8 @@ static int SCThresholdConfLineIsMultiline(char *line) /* we have a comment */ if (*line == '\\') flag = line - rline; - else - if (!isspace((unsigned char)*line)) - flag = 0; + else if (!isspace((unsigned char)*line)) + flag = 0; line++; } @@ -1027,9 +1023,10 @@ static FILE *SCThresholdConfGenerateValidDummyFD01(void) { FILE *fd = NULL; const char *buffer = - "event_filter gen_id 1, sig_id 10, type limit, track by_src, count 1, seconds 60\n" - "threshold gen_id 1, sig_id 100, type both, track by_dst, count 10, seconds 60\n" - "event_filter gen_id 1, sig_id 1000, type threshold, track by_src, count 100, seconds 60\n"; + "event_filter gen_id 1, sig_id 10, type limit, track by_src, count 1, seconds 60\n" + "threshold gen_id 1, sig_id 100, type both, track by_dst, count 10, seconds 60\n" + "event_filter gen_id 1, sig_id 1000, type threshold, track by_src, count 100, seconds " + "60\n"; fd = SCFmemopen((void *)buffer, strlen(buffer), "r"); if (fd == NULL) @@ -1047,8 +1044,8 @@ static FILE *SCThresholdConfGenerateValidDummyFD01(void) static FILE *SCThresholdConfGenerateInvalidDummyFD02(void) { FILE *fd; - const char *buffer = - "event_filter gen_id 1, sig_id 1000, type invalid, track by_src, count 100, seconds 60\n"; + const char *buffer = "event_filter gen_id 1, sig_id 1000, type invalid, track by_src, count " + "100, seconds 60\n"; fd = SCFmemopen((void *)buffer, strlen(buffer), "r"); if (fd == NULL) @@ -1065,8 +1062,8 @@ static FILE *SCThresholdConfGenerateInvalidDummyFD02(void) static FILE *SCThresholdConfGenerateValidDummyFD03(void) { FILE *fd; - const char *buffer = - "event_filter gen_id 0, sig_id 0, type threshold, track by_src, count 100, seconds 60\n"; + const char *buffer = "event_filter gen_id 0, sig_id 0, type threshold, track by_src, count " + "100, seconds 60\n"; fd = SCFmemopen((void *)buffer, strlen(buffer), "r"); if (fd == NULL) @@ -1084,10 +1081,12 @@ static FILE *SCThresholdConfGenerateValidDummyFD03(void) static FILE *SCThresholdConfGenerateValidDummyFD04(void) { FILE *fd = NULL; - const char *buffer = - "event_filter gen_id 1 \\\n, sig_id 10, type limit, track by_src, \\\ncount 1, seconds 60\n" - "threshold gen_id 1, \\\nsig_id 100, type both\\\n, track by_dst, count 10, \\\n seconds 60\n" - "event_filter gen_id 1, sig_id 1000, \\\ntype threshold, track \\\nby_src, count 100, seconds 60\n"; + const char *buffer = "event_filter gen_id 1 \\\n, sig_id 10, type limit, track by_src, " + "\\\ncount 1, seconds 60\n" + "threshold gen_id 1, \\\nsig_id 100, type both\\\n, track by_dst, count " + "10, \\\n seconds 60\n" + "event_filter gen_id 1, sig_id 1000, \\\ntype threshold, track " + "\\\nby_src, count 100, seconds 60\n"; fd = SCFmemopen((void *)buffer, strlen(buffer), "r"); if (fd == NULL) @@ -1104,11 +1103,14 @@ static FILE *SCThresholdConfGenerateValidDummyFD04(void) static FILE *SCThresholdConfGenerateValidDummyFD05(void) { FILE *fd = NULL; - const char *buffer = - "rate_filter gen_id 1, sig_id 10, track by_src, count 1, seconds 60, new_action drop, timeout 10\n" - "rate_filter gen_id 1, sig_id 100, track by_dst, count 10, seconds 60, new_action pass, timeout 5\n" - "rate_filter gen_id 1, sig_id 1000, track by_rule, count 100, seconds 60, new_action alert, timeout 30\n" - "rate_filter gen_id 1, sig_id 10000, track by_both, count 1000, seconds 60, new_action reject, timeout 21\n"; + const char *buffer = "rate_filter gen_id 1, sig_id 10, track by_src, count 1, seconds 60, " + "new_action drop, timeout 10\n" + "rate_filter gen_id 1, sig_id 100, track by_dst, count 10, seconds 60, " + "new_action pass, timeout 5\n" + "rate_filter gen_id 1, sig_id 1000, track by_rule, count 100, seconds 60, " + "new_action alert, timeout 30\n" + "rate_filter gen_id 1, sig_id 10000, track by_both, count 1000, seconds " + "60, new_action reject, timeout 21\n"; fd = SCFmemopen((void *)buffer, strlen(buffer), "r"); if (fd == NULL) @@ -1126,11 +1128,14 @@ static FILE *SCThresholdConfGenerateValidDummyFD05(void) static FILE *SCThresholdConfGenerateValidDummyFD06(void) { FILE *fd = NULL; - const char *buffer = - "rate_filter \\\ngen_id 1, sig_id 10, track by_src, count 1, seconds 60\\\n, new_action drop, timeout 10\n" - "rate_filter gen_id 1, \\\nsig_id 100, track by_dst, \\\ncount 10, seconds 60, new_action pass, timeout 5\n" - "rate_filter gen_id 1, sig_id 1000, \\\ntrack by_rule, count 100, seconds 60, new_action alert, timeout 30\n" - "rate_filter gen_id 1, sig_id 10000, track by_both, count 1000, \\\nseconds 60, new_action reject, timeout 21\n"; + const char *buffer = "rate_filter \\\ngen_id 1, sig_id 10, track by_src, count 1, seconds " + "60\\\n, new_action drop, timeout 10\n" + "rate_filter gen_id 1, \\\nsig_id 100, track by_dst, \\\ncount 10, " + "seconds 60, new_action pass, timeout 5\n" + "rate_filter gen_id 1, sig_id 1000, \\\ntrack by_rule, count 100, seconds " + "60, new_action alert, timeout 30\n" + "rate_filter gen_id 1, sig_id 10000, track by_both, count 1000, " + "\\\nseconds 60, new_action reject, timeout 21\n"; fd = SCFmemopen((void *)buffer, strlen(buffer), "r"); if (fd == NULL) @@ -1148,9 +1153,10 @@ static FILE *SCThresholdConfGenerateValidDummyFD06(void) static FILE *SCThresholdConfGenerateValidDummyFD07(void) { FILE *fd = NULL; - const char *buffer = - "rate_filter gen_id 1, sig_id 10, track by_src, count 3, seconds 3, new_action drop, timeout 10\n" - "rate_filter gen_id 1, sig_id 11, track by_src, count 3, seconds 1, new_action drop, timeout 5\n"; + const char *buffer = "rate_filter gen_id 1, sig_id 10, track by_src, count 3, seconds 3, " + "new_action drop, timeout 10\n" + "rate_filter gen_id 1, sig_id 11, track by_src, count 3, seconds 1, " + "new_action drop, timeout 5\n"; fd = SCFmemopen((void *)buffer, strlen(buffer), "r"); if (fd == NULL) @@ -1167,8 +1173,8 @@ static FILE *SCThresholdConfGenerateValidDummyFD07(void) static FILE *SCThresholdConfGenerateValidDummyFD08(void) { FILE *fd = NULL; - const char *buffer = - "rate_filter gen_id 1, sig_id 10, track by_rule, count 3, seconds 3, new_action drop, timeout 10\n"; + const char *buffer = "rate_filter gen_id 1, sig_id 10, track by_rule, count 3, seconds 3, " + "new_action drop, timeout 10\n"; fd = SCFmemopen((void *)buffer, strlen(buffer), "r"); if (fd == NULL) @@ -1186,10 +1192,12 @@ static FILE *SCThresholdConfGenerateValidDummyFD08(void) static FILE *SCThresholdConfGenerateValidDummyFD09(void) { FILE *fd = NULL; - const char *buffer = - "event_filter gen_id 1 \\\n, sig_id 10, type limit, track by_src, \\\ncount 2, seconds 60\n" - "threshold gen_id 1, \\\nsig_id 11, type threshold\\\n, track by_dst, count 3, \\\n seconds 60\n" - "event_filter gen_id 1, sig_id 12, \\\ntype both, track \\\nby_src, count 2, seconds 60\n"; + const char *buffer = "event_filter gen_id 1 \\\n, sig_id 10, type limit, track by_src, " + "\\\ncount 2, seconds 60\n" + "threshold gen_id 1, \\\nsig_id 11, type threshold\\\n, track by_dst, " + "count 3, \\\n seconds 60\n" + "event_filter gen_id 1, sig_id 12, \\\ntype both, track \\\nby_src, count " + "2, seconds 60\n"; fd = SCFmemopen((void *)buffer, strlen(buffer), "r"); if (fd == NULL) @@ -1207,10 +1215,12 @@ static FILE *SCThresholdConfGenerateValidDummyFD09(void) static FILE *SCThresholdConfGenerateValidDummyFD10(void) { FILE *fd = NULL; - const char *buffer = - "event_filter gen_id 1 \\\n, sig_id 10, type limit, track by_src, \\\ncount 5, seconds 2\n" - "threshold gen_id 1, \\\nsig_id 11, type threshold\\\n, track by_dst, count 5, \\\n seconds 2\n" - "event_filter gen_id 1, sig_id 12, \\\ntype both, track \\\nby_src, count 5, seconds 2\n"; + const char *buffer = "event_filter gen_id 1 \\\n, sig_id 10, type limit, track by_src, " + "\\\ncount 5, seconds 2\n" + "threshold gen_id 1, \\\nsig_id 11, type threshold\\\n, track by_dst, " + "count 5, \\\n seconds 2\n" + "event_filter gen_id 1, sig_id 12, \\\ntype both, track \\\nby_src, count " + "5, seconds 2\n"; fd = SCFmemopen((void *)buffer, strlen(buffer), "r"); if (fd == NULL) @@ -1227,9 +1237,8 @@ static FILE *SCThresholdConfGenerateValidDummyFD10(void) static FILE *SCThresholdConfGenerateValidDummyFD11(void) { FILE *fd = NULL; - const char *buffer = - "suppress gen_id 1, sig_id 10000\n" - "suppress gen_id 1, sig_id 1000, track by_src, ip 192.168.1.1\n"; + const char *buffer = "suppress gen_id 1, sig_id 10000\n" + "suppress gen_id 1, sig_id 1000, track by_src, ip 192.168.1.1\n"; fd = SCFmemopen((void *)buffer, strlen(buffer), "r"); if (fd == NULL) @@ -1250,8 +1259,8 @@ static int SCThresholdConfTest01(void) FAIL_IF_NULL(de_ctx); de_ctx->flags |= DE_QUIET; - Signature *sig = DetectEngineAppendSig(de_ctx, - "alert tcp any any -> any any (msg:\"Threshold limit\"; gid:1; sid:10;)"); + Signature *sig = DetectEngineAppendSig( + de_ctx, "alert tcp any any -> any any (msg:\"Threshold limit\"; gid:1; sid:10;)"); FAIL_IF_NULL(sig); FAIL_IF_NOT_NULL(g_ut_threshold_fp); @@ -1259,14 +1268,14 @@ static int SCThresholdConfTest01(void) FAIL_IF_NULL(g_ut_threshold_fp); FAIL_IF(-1 == SCThresholdConfInitContext(de_ctx)); - SigMatch *m = DetectGetLastSMByListId(sig, DETECT_SM_LIST_THRESHOLD, - DETECT_THRESHOLD, -1); + SigMatch *m = DetectGetLastSMByListId(sig, DETECT_SM_LIST_THRESHOLD, DETECT_THRESHOLD, -1); FAIL_IF_NULL(m); DetectThresholdData *de = (DetectThresholdData *)m->ctx; FAIL_IF_NULL(de); - FAIL_IF_NOT(de->type == TYPE_LIMIT && de->track == TRACK_SRC && de->count == 1 && de->seconds == 60); + FAIL_IF_NOT(de->type == TYPE_LIMIT && de->track == TRACK_SRC && de->count == 1 && + de->seconds == 60); DetectEngineCtxFree(de_ctx); PASS; } @@ -1283,8 +1292,8 @@ static int SCThresholdConfTest02(void) FAIL_IF_NULL(de_ctx); de_ctx->flags |= DE_QUIET; - Signature *sig = DetectEngineAppendSig(de_ctx, - "alert tcp any any -> any any (msg:\"Threshold limit\"; gid:1; sid:100;)"); + Signature *sig = DetectEngineAppendSig( + de_ctx, "alert tcp any any -> any any (msg:\"Threshold limit\"; gid:1; sid:100;)"); FAIL_IF_NULL(sig); FAIL_IF_NOT_NULL(g_ut_threshold_fp); @@ -1292,14 +1301,14 @@ static int SCThresholdConfTest02(void) FAIL_IF_NULL(g_ut_threshold_fp); FAIL_IF(-1 == SCThresholdConfInitContext(de_ctx)); - SigMatch *m = DetectGetLastSMByListId(sig, DETECT_SM_LIST_THRESHOLD, - DETECT_THRESHOLD, -1); + SigMatch *m = DetectGetLastSMByListId(sig, DETECT_SM_LIST_THRESHOLD, DETECT_THRESHOLD, -1); FAIL_IF_NULL(m); DetectThresholdData *de = (DetectThresholdData *)m->ctx; FAIL_IF_NULL(de); - FAIL_IF_NOT(de->type == TYPE_BOTH && de->track == TRACK_DST && de->count == 10 && de->seconds == 60); + FAIL_IF_NOT(de->type == TYPE_BOTH && de->track == TRACK_DST && de->count == 10 && + de->seconds == 60); DetectEngineCtxFree(de_ctx); PASS; } @@ -1316,8 +1325,8 @@ static int SCThresholdConfTest03(void) FAIL_IF_NULL(de_ctx); de_ctx->flags |= DE_QUIET; - Signature *sig = DetectEngineAppendSig(de_ctx, - "alert tcp any any -> any any (msg:\"Threshold limit\"; gid:1; sid:1000;)"); + Signature *sig = DetectEngineAppendSig( + de_ctx, "alert tcp any any -> any any (msg:\"Threshold limit\"; gid:1; sid:1000;)"); FAIL_IF_NULL(sig); FAIL_IF_NOT_NULL(g_ut_threshold_fp); @@ -1325,14 +1334,14 @@ static int SCThresholdConfTest03(void) FAIL_IF_NULL(g_ut_threshold_fp); FAIL_IF(-1 == SCThresholdConfInitContext(de_ctx)); - SigMatch *m = DetectGetLastSMByListId(sig, DETECT_SM_LIST_THRESHOLD, - DETECT_THRESHOLD, -1); + SigMatch *m = DetectGetLastSMByListId(sig, DETECT_SM_LIST_THRESHOLD, DETECT_THRESHOLD, -1); FAIL_IF_NULL(m); DetectThresholdData *de = (DetectThresholdData *)m->ctx; FAIL_IF_NULL(de); - FAIL_IF_NOT(de->type == TYPE_THRESHOLD && de->track == TRACK_SRC && de->count == 100 && de->seconds == 60); + FAIL_IF_NOT(de->type == TYPE_THRESHOLD && de->track == TRACK_SRC && de->count == 100 && + de->seconds == 60); DetectEngineCtxFree(de_ctx); PASS; } @@ -1349,8 +1358,8 @@ static int SCThresholdConfTest04(void) FAIL_IF_NULL(de_ctx); de_ctx->flags |= DE_QUIET; - Signature *sig = DetectEngineAppendSig(de_ctx, - "alert tcp any any -> any any (msg:\"Threshold limit\"; gid:1; sid:1000;)"); + Signature *sig = DetectEngineAppendSig( + de_ctx, "alert tcp any any -> any any (msg:\"Threshold limit\"; gid:1; sid:1000;)"); FAIL_IF_NULL(sig); FAIL_IF_NOT_NULL(g_ut_threshold_fp); @@ -1358,8 +1367,7 @@ static int SCThresholdConfTest04(void) FAIL_IF_NULL(g_ut_threshold_fp); FAIL_IF(-1 == SCThresholdConfInitContext(de_ctx)); - SigMatch *m = DetectGetLastSMByListId(sig, DETECT_SM_LIST_THRESHOLD, - DETECT_THRESHOLD, -1); + SigMatch *m = DetectGetLastSMByListId(sig, DETECT_SM_LIST_THRESHOLD, DETECT_THRESHOLD, -1); FAIL_IF_NOT_NULL(m); DetectEngineCtxFree(de_ctx); @@ -1378,15 +1386,15 @@ static int SCThresholdConfTest05(void) FAIL_IF_NULL(de_ctx); de_ctx->flags |= DE_QUIET; - Signature *sig = DetectEngineAppendSig(de_ctx, - "alert tcp any any -> any any (msg:\"Threshold limit\"; gid:1; sid:1;)"); + Signature *sig = DetectEngineAppendSig( + de_ctx, "alert tcp any any -> any any (msg:\"Threshold limit\"; gid:1; sid:1;)"); FAIL_IF_NULL(sig); - sig = DetectEngineAppendSig(de_ctx, - "alert tcp any any -> any 80 (msg:\"Threshold limit\"; gid:1; sid:10;)"); + sig = DetectEngineAppendSig( + de_ctx, "alert tcp any any -> any 80 (msg:\"Threshold limit\"; gid:1; sid:10;)"); FAIL_IF_NULL(sig); - sig = DetectEngineAppendSig(de_ctx, - "alert tcp any any -> any 80 (msg:\"Threshold limit\"; gid:1; sid:100;)"); + sig = DetectEngineAppendSig( + de_ctx, "alert tcp any any -> any 80 (msg:\"Threshold limit\"; gid:1; sid:100;)"); FAIL_IF_NULL(sig); FAIL_IF_NOT_NULL(g_ut_threshold_fp); @@ -1395,28 +1403,28 @@ static int SCThresholdConfTest05(void) FAIL_IF(-1 == SCThresholdConfInitContext(de_ctx)); Signature *s = de_ctx->sig_list; - SigMatch *m = DetectGetLastSMByListId(s, DETECT_SM_LIST_THRESHOLD, - DETECT_THRESHOLD, -1); + SigMatch *m = DetectGetLastSMByListId(s, DETECT_SM_LIST_THRESHOLD, DETECT_THRESHOLD, -1); FAIL_IF_NULL(m); FAIL_IF_NULL(m->ctx); DetectThresholdData *de = (DetectThresholdData *)m->ctx; - FAIL_IF_NOT(de->type == TYPE_THRESHOLD && de->track == TRACK_SRC && de->count == 100 && de->seconds == 60); + FAIL_IF_NOT(de->type == TYPE_THRESHOLD && de->track == TRACK_SRC && de->count == 100 && + de->seconds == 60); s = de_ctx->sig_list->next; - m = DetectGetLastSMByListId(s, DETECT_SM_LIST_THRESHOLD, - DETECT_THRESHOLD, -1); + m = DetectGetLastSMByListId(s, DETECT_SM_LIST_THRESHOLD, DETECT_THRESHOLD, -1); FAIL_IF_NULL(m); FAIL_IF_NULL(m->ctx); de = (DetectThresholdData *)m->ctx; - FAIL_IF_NOT(de->type == TYPE_THRESHOLD && de->track == TRACK_SRC && de->count == 100 && de->seconds == 60); + FAIL_IF_NOT(de->type == TYPE_THRESHOLD && de->track == TRACK_SRC && de->count == 100 && + de->seconds == 60); s = de_ctx->sig_list->next->next; - m = DetectGetLastSMByListId(s, DETECT_SM_LIST_THRESHOLD, - DETECT_THRESHOLD, -1); + m = DetectGetLastSMByListId(s, DETECT_SM_LIST_THRESHOLD, DETECT_THRESHOLD, -1); FAIL_IF_NULL(m); FAIL_IF_NULL(m->ctx); de = (DetectThresholdData *)m->ctx; - FAIL_IF_NOT(de->type == TYPE_THRESHOLD && de->track == TRACK_SRC && de->count == 100 && de->seconds == 60); + FAIL_IF_NOT(de->type == TYPE_THRESHOLD && de->track == TRACK_SRC && de->count == 100 && + de->seconds == 60); PASS; } @@ -1433,8 +1441,8 @@ static int SCThresholdConfTest06(void) FAIL_IF_NULL(de_ctx); de_ctx->flags |= DE_QUIET; - Signature *sig = DetectEngineAppendSig(de_ctx, - "alert tcp any any -> any any (msg:\"Threshold limit\"; gid:1; sid:10;)"); + Signature *sig = DetectEngineAppendSig( + de_ctx, "alert tcp any any -> any any (msg:\"Threshold limit\"; gid:1; sid:10;)"); FAIL_IF_NULL(sig); FAIL_IF_NOT_NULL(g_ut_threshold_fp); @@ -1442,13 +1450,13 @@ static int SCThresholdConfTest06(void) FAIL_IF_NULL(g_ut_threshold_fp); FAIL_IF(-1 == SCThresholdConfInitContext(de_ctx)); - SigMatch *m = DetectGetLastSMByListId(sig, DETECT_SM_LIST_THRESHOLD, - DETECT_THRESHOLD, -1); + SigMatch *m = DetectGetLastSMByListId(sig, DETECT_SM_LIST_THRESHOLD, DETECT_THRESHOLD, -1); FAIL_IF_NULL(m); DetectThresholdData *de = (DetectThresholdData *)m->ctx; FAIL_IF_NULL(de); - FAIL_IF_NOT(de->type == TYPE_LIMIT && de->track == TRACK_SRC && de->count == 1 && de->seconds == 60); + FAIL_IF_NOT(de->type == TYPE_LIMIT && de->track == TRACK_SRC && de->count == 1 && + de->seconds == 60); DetectEngineCtxFree(de_ctx); PASS; @@ -1466,8 +1474,8 @@ static int SCThresholdConfTest07(void) FAIL_IF_NULL(de_ctx); de_ctx->flags |= DE_QUIET; - Signature *sig = DetectEngineAppendSig(de_ctx, - "alert tcp any any -> any any (msg:\"Threshold limit\"; gid:1; sid:10;)"); + Signature *sig = DetectEngineAppendSig( + de_ctx, "alert tcp any any -> any any (msg:\"Threshold limit\"; gid:1; sid:10;)"); FAIL_IF_NULL(sig); FAIL_IF_NOT_NULL(g_ut_threshold_fp); @@ -1475,13 +1483,14 @@ static int SCThresholdConfTest07(void) FAIL_IF_NULL(g_ut_threshold_fp); FAIL_IF(-1 == SCThresholdConfInitContext(de_ctx)); - SigMatch *m = DetectGetLastSMByListId(sig, DETECT_SM_LIST_THRESHOLD, - DETECT_DETECTION_FILTER, -1); + SigMatch *m = + DetectGetLastSMByListId(sig, DETECT_SM_LIST_THRESHOLD, DETECT_DETECTION_FILTER, -1); FAIL_IF_NULL(m); DetectThresholdData *de = (DetectThresholdData *)m->ctx; FAIL_IF_NULL(de); - FAIL_IF_NOT(de->type == TYPE_RATE && de->track == TRACK_SRC && de->count == 1 && de->seconds == 60); + FAIL_IF_NOT( + de->type == TYPE_RATE && de->track == TRACK_SRC && de->count == 1 && de->seconds == 60); DetectEngineCtxFree(de_ctx); PASS; @@ -1500,8 +1509,8 @@ static int SCThresholdConfTest08(void) FAIL_IF_NULL(de_ctx); de_ctx->flags |= DE_QUIET; - Signature *sig = DetectEngineAppendSig(de_ctx, - "alert tcp any any -> any any (msg:\"Threshold limit\"; gid:1; sid:10;)"); + Signature *sig = DetectEngineAppendSig( + de_ctx, "alert tcp any any -> any any (msg:\"Threshold limit\"; gid:1; sid:10;)"); FAIL_IF_NULL(sig); FAIL_IF_NOT_NULL(g_ut_threshold_fp); @@ -1509,13 +1518,14 @@ static int SCThresholdConfTest08(void) FAIL_IF_NULL(g_ut_threshold_fp); FAIL_IF(-1 == SCThresholdConfInitContext(de_ctx)); - SigMatch *m = DetectGetLastSMByListId(sig, DETECT_SM_LIST_THRESHOLD, - DETECT_DETECTION_FILTER, -1); + SigMatch *m = + DetectGetLastSMByListId(sig, DETECT_SM_LIST_THRESHOLD, DETECT_DETECTION_FILTER, -1); FAIL_IF_NULL(m); DetectThresholdData *de = (DetectThresholdData *)m->ctx; FAIL_IF_NULL(de); - FAIL_IF_NOT(de->type == TYPE_RATE && de->track == TRACK_SRC && de->count == 1 && de->seconds == 60); + FAIL_IF_NOT( + de->type == TYPE_RATE && de->track == TRACK_SRC && de->count == 1 && de->seconds == 60); DetectEngineCtxFree(de_ctx); PASS; @@ -1534,7 +1544,7 @@ static int SCThresholdConfTest09(void) HostInitConfig(HOST_QUIET); - Packet *p = UTHBuildPacket((uint8_t*)"lalala", 6, IPPROTO_TCP); + Packet *p = UTHBuildPacket((uint8_t *)"lalala", 6, IPPROTO_TCP); FAIL_IF_NULL(p); DetectEngineThreadCtx *det_ctx = NULL; @@ -1543,8 +1553,8 @@ static int SCThresholdConfTest09(void) FAIL_IF_NULL(de_ctx); de_ctx->flags |= DE_QUIET; - Signature *s = DetectEngineAppendSig(de_ctx, - "alert tcp any any -> any any (msg:\"ratefilter test\"; gid:1; sid:10;)"); + Signature *s = DetectEngineAppendSig( + de_ctx, "alert tcp any any -> any any (msg:\"ratefilter test\"; gid:1; sid:10;)"); FAIL_IF_NULL(s); FAIL_IF_NOT_NULL(g_ut_threshold_fp); @@ -1616,13 +1626,13 @@ static int SCThresholdConfTest10(void) HostInitConfig(HOST_QUIET); /* Create two different packets falling to the same rule, and - * because count:3, we should drop on match #4. - */ - Packet *p1 = UTHBuildPacketSrcDst((uint8_t*)"lalala", 6, IPPROTO_TCP, - "172.26.0.2", "172.26.0.11"); + * because count:3, we should drop on match #4. + */ + Packet *p1 = + UTHBuildPacketSrcDst((uint8_t *)"lalala", 6, IPPROTO_TCP, "172.26.0.2", "172.26.0.11"); FAIL_IF_NULL(p1); - Packet *p2 = UTHBuildPacketSrcDst((uint8_t*)"lalala", 6, IPPROTO_TCP, - "172.26.0.1", "172.26.0.10"); + Packet *p2 = + UTHBuildPacketSrcDst((uint8_t *)"lalala", 6, IPPROTO_TCP, "172.26.0.1", "172.26.0.10"); FAIL_IF_NULL(p2); ThreadVars th_v; @@ -1633,8 +1643,8 @@ static int SCThresholdConfTest10(void) de_ctx->flags |= DE_QUIET; DetectEngineThreadCtx *det_ctx = NULL; - Signature *s = DetectEngineAppendSig(de_ctx, - "alert tcp any any -> any any (msg:\"ratefilter test\"; gid:1; sid:10;)"); + Signature *s = DetectEngineAppendSig( + de_ctx, "alert tcp any any -> any any (msg:\"ratefilter test\"; gid:1; sid:10;)"); FAIL_IF_NULL(s); FAIL_IF_NOT_NULL(g_ut_threshold_fp); @@ -1705,7 +1715,7 @@ static int SCThresholdConfTest11(void) { HostInitConfig(HOST_QUIET); - Packet *p = UTHBuildPacket((uint8_t*)"lalala", 6, IPPROTO_TCP); + Packet *p = UTHBuildPacket((uint8_t *)"lalala", 6, IPPROTO_TCP); FAIL_IF_NULL(p); ThreadVars th_v; @@ -1810,7 +1820,7 @@ static int SCThresholdConfTest12(void) { HostInitConfig(HOST_QUIET); - Packet *p = UTHBuildPacket((uint8_t*)"lalala", 6, IPPROTO_TCP); + Packet *p = UTHBuildPacket((uint8_t *)"lalala", 6, IPPROTO_TCP); FAIL_IF_NULL(p); ThreadVars th_v; @@ -1917,8 +1927,8 @@ static int SCThresholdConfTest13(void) FAIL_IF_NULL(de_ctx); de_ctx->flags |= DE_QUIET; - Signature *sig = DetectEngineAppendSig(de_ctx, - "alert tcp any any -> any any (msg:\"Threshold limit\"; gid:1; sid:1000;)"); + Signature *sig = DetectEngineAppendSig( + de_ctx, "alert tcp any any -> any any (msg:\"Threshold limit\"; gid:1; sid:1000;)"); FAIL_IF_NULL(sig); FAIL_IF_NOT_NULL(g_ut_threshold_fp); @@ -1926,8 +1936,7 @@ static int SCThresholdConfTest13(void) FAIL_IF_NULL(g_ut_threshold_fp); FAIL_IF(-1 == SCThresholdConfInitContext(de_ctx)); - SigMatch *m = DetectGetLastSMByListId(sig, - DETECT_SM_LIST_SUPPRESS, DETECT_THRESHOLD, -1); + SigMatch *m = DetectGetLastSMByListId(sig, DETECT_SM_LIST_SUPPRESS, DETECT_THRESHOLD, -1); FAIL_IF_NULL(m); DetectThresholdData *de = (DetectThresholdData *)m->ctx; @@ -1948,11 +1957,11 @@ static int SCThresholdConfTest14(void) { HostInitConfig(HOST_QUIET); - Packet *p1 = UTHBuildPacketReal((uint8_t*)"lalala", 6, IPPROTO_TCP, "192.168.0.10", - "192.168.0.100", 1234, 24); + Packet *p1 = UTHBuildPacketReal( + (uint8_t *)"lalala", 6, IPPROTO_TCP, "192.168.0.10", "192.168.0.100", 1234, 24); FAIL_IF_NULL(p1); - Packet *p2 = UTHBuildPacketReal((uint8_t*)"lalala", 6, IPPROTO_TCP, "192.168.1.1", - "192.168.0.100", 1234, 24); + Packet *p2 = UTHBuildPacketReal( + (uint8_t *)"lalala", 6, IPPROTO_TCP, "192.168.1.1", "192.168.0.100", 1234, 24); FAIL_IF_NULL(p2); DetectEngineThreadCtx *det_ctx = NULL; @@ -1960,14 +1969,14 @@ static int SCThresholdConfTest14(void) FAIL_IF_NULL(de_ctx); de_ctx->flags |= DE_QUIET; - Signature *sig = DetectEngineAppendSig(de_ctx, - "alert tcp any any -> any any (msg:\"suppress test\"; gid:1; sid:10000;)"); + Signature *sig = DetectEngineAppendSig( + de_ctx, "alert tcp any any -> any any (msg:\"suppress test\"; gid:1; sid:10000;)"); FAIL_IF_NULL(sig); - sig = DetectEngineAppendSig(de_ctx, - "alert tcp any any -> any any (msg:\"suppress test 2\"; gid:1; sid:10;)"); + sig = DetectEngineAppendSig( + de_ctx, "alert tcp any any -> any any (msg:\"suppress test 2\"; gid:1; sid:10;)"); FAIL_IF_NULL(sig); - sig = DetectEngineAppendSig(de_ctx, - "alert tcp any any -> any any (msg:\"suppress test 3\"; gid:1; sid:1000;)"); + sig = DetectEngineAppendSig( + de_ctx, "alert tcp any any -> any any (msg:\"suppress test 3\"; gid:1; sid:1000;)"); FAIL_IF_NULL(sig); ThreadVars th_v; @@ -2009,8 +2018,8 @@ static int SCThresholdConfTest15(void) { HostInitConfig(HOST_QUIET); - Packet *p = UTHBuildPacketReal((uint8_t*)"lalala", 6, IPPROTO_TCP, "192.168.0.10", - "192.168.0.100", 1234, 24); + Packet *p = UTHBuildPacketReal( + (uint8_t *)"lalala", 6, IPPROTO_TCP, "192.168.0.10", "192.168.0.100", 1234, 24); FAIL_IF_NULL(p); ThreadVars th_v; @@ -2021,8 +2030,9 @@ static int SCThresholdConfTest15(void) FAIL_IF_NULL(de_ctx); de_ctx->flags |= DE_QUIET; - Signature *sig = DetectEngineAppendSig(de_ctx, - "drop tcp any any -> any any (msg:\"suppress test\"; content:\"lalala\"; gid:1; sid:10000;)"); + Signature *sig = + DetectEngineAppendSig(de_ctx, "drop tcp any any -> any any (msg:\"suppress test\"; " + "content:\"lalala\"; gid:1; sid:10000;)"); FAIL_IF_NULL(sig); FAIL_IF_NOT_NULL(g_ut_threshold_fp); @@ -2057,8 +2067,8 @@ static int SCThresholdConfTest16(void) { HostInitConfig(HOST_QUIET); - Packet *p = UTHBuildPacketReal((uint8_t*)"lalala", 6, IPPROTO_TCP, "192.168.1.1", - "192.168.0.100", 1234, 24); + Packet *p = UTHBuildPacketReal( + (uint8_t *)"lalala", 6, IPPROTO_TCP, "192.168.1.1", "192.168.0.100", 1234, 24); FAIL_IF_NULL(p); ThreadVars th_v; @@ -2069,8 +2079,8 @@ static int SCThresholdConfTest16(void) FAIL_IF_NULL(de_ctx); de_ctx->flags |= DE_QUIET; - Signature *sig = DetectEngineAppendSig(de_ctx, - "drop tcp any any -> any any (msg:\"suppress test\"; gid:1; sid:1000;)"); + Signature *sig = DetectEngineAppendSig( + de_ctx, "drop tcp any any -> any any (msg:\"suppress test\"; gid:1; sid:1000;)"); FAIL_IF_NULL(sig); FAIL_IF_NOT_NULL(g_ut_threshold_fp); @@ -2104,8 +2114,8 @@ static int SCThresholdConfTest17(void) { HostInitConfig(HOST_QUIET); - Packet *p = UTHBuildPacketReal((uint8_t*)"lalala", 6, IPPROTO_TCP, "192.168.0.10", - "192.168.0.100", 1234, 24); + Packet *p = UTHBuildPacketReal( + (uint8_t *)"lalala", 6, IPPROTO_TCP, "192.168.0.10", "192.168.0.100", 1234, 24); FAIL_IF_NULL(p); ThreadVars th_v; @@ -2116,8 +2126,8 @@ static int SCThresholdConfTest17(void) FAIL_IF_NULL(de_ctx); de_ctx->flags |= DE_QUIET; - Signature *sig = DetectEngineAppendSig(de_ctx, - "drop tcp 192.168.0.10 any -> 192.168.0.100 any (msg:\"suppress test\"; gid:1; sid:10000;)"); + Signature *sig = DetectEngineAppendSig(de_ctx, "drop tcp 192.168.0.10 any -> 192.168.0.100 any " + "(msg:\"suppress test\"; gid:1; sid:10000;)"); FAIL_IF_NULL(sig); FAIL_IF_NOT_NULL(g_ut_threshold_fp); @@ -2150,9 +2160,8 @@ static int SCThresholdConfTest17(void) static FILE *SCThresholdConfGenerateInvalidDummyFD12(void) { FILE *fd = NULL; - const char *buffer = - "suppress gen_id 1, sig_id 2200029, track by_dst, ip fe80::/16\n" - "suppress gen_id 1, sig_id 2200029, track by_stc, ip fe80::/16\n"; + const char *buffer = "suppress gen_id 1, sig_id 2200029, track by_dst, ip fe80::/16\n" + "suppress gen_id 1, sig_id 2200029, track by_stc, ip fe80::/16\n"; fd = SCFmemopen((void *)buffer, strlen(buffer), "r"); if (fd == NULL) @@ -2174,8 +2183,8 @@ static int SCThresholdConfTest18(void) FAIL_IF_NULL(de_ctx); de_ctx->flags |= DE_QUIET; - Signature *s = DetectEngineAppendSig(de_ctx, - "alert tcp 192.168.0.10 any -> 192.168.0.100 any (msg:\"suppress test\"; gid:1; sid:2200029;)"); + Signature *s = DetectEngineAppendSig(de_ctx, "alert tcp 192.168.0.10 any -> 192.168.0.100 any " + "(msg:\"suppress test\"; gid:1; sid:2200029;)"); FAIL_IF_NULL(s); FAIL_IF_NOT_NULL(g_ut_threshold_fp); g_ut_threshold_fp = SCThresholdConfGenerateInvalidDummyFD12(); @@ -2202,9 +2211,8 @@ static int SCThresholdConfTest18(void) static FILE *SCThresholdConfGenerateInvalidDummyFD13(void) { FILE *fd = NULL; - const char *buffer = - "suppress gen_id 1, sig_id 2200029, track by_stc, ip fe80::/16\n" - "suppress gen_id 1, sig_id 2200029, track by_dst, ip fe80::/16\n"; + const char *buffer = "suppress gen_id 1, sig_id 2200029, track by_stc, ip fe80::/16\n" + "suppress gen_id 1, sig_id 2200029, track by_dst, ip fe80::/16\n"; fd = SCFmemopen((void *)buffer, strlen(buffer), "r"); if (fd == NULL) @@ -2225,8 +2233,8 @@ static int SCThresholdConfTest19(void) DetectEngineCtx *de_ctx = DetectEngineCtxInit(); FAIL_IF_NULL(de_ctx); de_ctx->flags |= DE_QUIET; - Signature *s = DetectEngineAppendSig(de_ctx, - "alert tcp 192.168.0.10 any -> 192.168.0.100 any (msg:\"suppress test\"; gid:1; sid:2200029;)"); + Signature *s = DetectEngineAppendSig(de_ctx, "alert tcp 192.168.0.10 any -> 192.168.0.100 any " + "(msg:\"suppress test\"; gid:1; sid:2200029;)"); FAIL_IF_NULL(s); FAIL_IF_NOT_NULL(g_ut_threshold_fp); g_ut_threshold_fp = SCThresholdConfGenerateInvalidDummyFD13(); @@ -2251,10 +2259,9 @@ static int SCThresholdConfTest19(void) static FILE *SCThresholdConfGenerateValidDummyFD20(void) { FILE *fd = NULL; - const char *buffer = - "suppress gen_id 1, sig_id 1000, track by_src, ip 2.2.3.4\n" - "suppress gen_id 1, sig_id 1000, track by_src, ip 1.2.3.4\n" - "suppress gen_id 1, sig_id 1000, track by_src, ip 192.168.1.1\n"; + const char *buffer = "suppress gen_id 1, sig_id 1000, track by_src, ip 2.2.3.4\n" + "suppress gen_id 1, sig_id 1000, track by_src, ip 1.2.3.4\n" + "suppress gen_id 1, sig_id 1000, track by_src, ip 192.168.1.1\n"; fd = SCFmemopen((void *)buffer, strlen(buffer), "r"); if (fd == NULL) @@ -2321,8 +2328,9 @@ static int SCThresholdConfTest21(void) DetectEngineCtx *de_ctx = DetectEngineCtxInit(); FAIL_IF_NULL(de_ctx); de_ctx->flags |= DE_QUIET; - Signature *s = DetectEngineAppendSig(de_ctx, - "alert tcp any any -> any any (msg:\"Threshold limit\"; content:\"abc\"; threshold: type limit, track by_dst, count 5, seconds 60; sid:1000;)"); + Signature *s = DetectEngineAppendSig( + de_ctx, "alert tcp any any -> any any (msg:\"Threshold limit\"; content:\"abc\"; " + "threshold: type limit, track by_dst, count 5, seconds 60; sid:1000;)"); FAIL_IF_NULL(s); g_ut_threshold_fp = SCThresholdConfGenerateValidDummyFD20(); FAIL_IF_NULL(g_ut_threshold_fp); @@ -2354,15 +2362,16 @@ static int SCThresholdConfTest21(void) } /** -* \brief Creates a dummy rate_filter file, for testing rate filtering by_both source and destination -* -* \retval fd Pointer to file descriptor. -*/ + * \brief Creates a dummy rate_filter file, for testing rate filtering by_both source and + * destination + * + * \retval fd Pointer to file descriptor. + */ static FILE *SCThresholdConfGenerateValidDummyFD22(void) { FILE *fd = NULL; - const char *buffer = - "rate_filter gen_id 1, sig_id 10, track by_both, count 2, seconds 5, new_action drop, timeout 6\n"; + const char *buffer = "rate_filter gen_id 1, sig_id 10, track by_both, count 2, seconds 5, " + "new_action drop, timeout 6\n"; fd = SCFmemopen((void *)buffer, strlen(buffer), "r"); if (fd == NULL) @@ -2385,15 +2394,18 @@ static int SCThresholdConfTest22(void) IPPairInitConfig(IPPAIR_QUIET); /* This packet will cause rate_filter */ - Packet *p1 = UTHBuildPacketSrcDst((uint8_t*)"lalala", 6, IPPROTO_TCP, "172.26.0.1", "172.26.0.10"); + Packet *p1 = + UTHBuildPacketSrcDst((uint8_t *)"lalala", 6, IPPROTO_TCP, "172.26.0.1", "172.26.0.10"); FAIL_IF_NULL(p1); /* Should not be filtered for different destination */ - Packet *p2 = UTHBuildPacketSrcDst((uint8_t*)"lalala", 6, IPPROTO_TCP, "172.26.0.1", "172.26.0.2"); + Packet *p2 = + UTHBuildPacketSrcDst((uint8_t *)"lalala", 6, IPPROTO_TCP, "172.26.0.1", "172.26.0.2"); FAIL_IF_NULL(p2); /* Should not be filtered when both src and dst the same */ - Packet *p3 = UTHBuildPacketSrcDst((uint8_t*)"lalala", 6, IPPROTO_TCP, "172.26.0.1", "172.26.0.1"); + Packet *p3 = + UTHBuildPacketSrcDst((uint8_t *)"lalala", 6, IPPROTO_TCP, "172.26.0.1", "172.26.0.1"); FAIL_IF_NULL(p3); DetectEngineThreadCtx *det_ctx = NULL; @@ -2490,15 +2502,16 @@ static int SCThresholdConfTest22(void) } /** -* \brief Creates a dummy rate_filter file, for testing rate filtering by_both source and destination -* -* \retval fd Pointer to file descriptor. -*/ + * \brief Creates a dummy rate_filter file, for testing rate filtering by_both source and + * destination + * + * \retval fd Pointer to file descriptor. + */ static FILE *SCThresholdConfGenerateValidDummyFD23(void) { FILE *fd = NULL; - const char *buffer = - "rate_filter gen_id 1, sig_id 10, track by_both, count 1, seconds 5, new_action drop, timeout 6\n"; + const char *buffer = "rate_filter gen_id 1, sig_id 10, track by_both, count 1, seconds 5, " + "new_action drop, timeout 6\n"; fd = SCFmemopen((void *)buffer, strlen(buffer), "r"); if (fd == NULL) @@ -2522,10 +2535,12 @@ static int SCThresholdConfTest23(void) IPPairInitConfig(IPPAIR_QUIET); /* Create two packets between same addresses in opposite direction */ - Packet *p1 = UTHBuildPacketSrcDst((uint8_t*)"lalala", 6, IPPROTO_TCP, "172.26.0.1", "172.26.0.10"); + Packet *p1 = + UTHBuildPacketSrcDst((uint8_t *)"lalala", 6, IPPROTO_TCP, "172.26.0.1", "172.26.0.10"); FAIL_IF_NULL(p1); - Packet *p2 = UTHBuildPacketSrcDst((uint8_t*)"lalala", 6, IPPROTO_TCP, "172.26.0.10", "172.26.0.1"); + Packet *p2 = + UTHBuildPacketSrcDst((uint8_t *)"lalala", 6, IPPROTO_TCP, "172.26.0.10", "172.26.0.1"); FAIL_IF_NULL(p2); DetectEngineThreadCtx *det_ctx = NULL; @@ -2535,7 +2550,7 @@ static int SCThresholdConfTest23(void) de_ctx->flags |= DE_QUIET; Signature *sig = DetectEngineAppendSig(de_ctx, - "alert tcp any any -> any any (msg:\"ratefilter by_both test\"; gid:1; sid:10;)"); + "alert tcp any any -> any any (msg:\"ratefilter by_both test\"; gid:1; sid:10;)"); FAIL_IF_NULL(sig); FAIL_IF_NOT_NULL(g_ut_threshold_fp); @@ -2585,35 +2600,22 @@ void SCThresholdConfRegisterTests(void) UtRegisterTest("SCThresholdConfTest06", SCThresholdConfTest06); UtRegisterTest("SCThresholdConfTest07", SCThresholdConfTest07); UtRegisterTest("SCThresholdConfTest08", SCThresholdConfTest08); - UtRegisterTest("SCThresholdConfTest09 - rate_filter", - SCThresholdConfTest09); - UtRegisterTest("SCThresholdConfTest10 - rate_filter", - SCThresholdConfTest10); - UtRegisterTest("SCThresholdConfTest11 - event_filter", - SCThresholdConfTest11); - UtRegisterTest("SCThresholdConfTest12 - event_filter", - SCThresholdConfTest12); + UtRegisterTest("SCThresholdConfTest09 - rate_filter", SCThresholdConfTest09); + UtRegisterTest("SCThresholdConfTest10 - rate_filter", SCThresholdConfTest10); + UtRegisterTest("SCThresholdConfTest11 - event_filter", SCThresholdConfTest11); + UtRegisterTest("SCThresholdConfTest12 - event_filter", SCThresholdConfTest12); UtRegisterTest("SCThresholdConfTest13", SCThresholdConfTest13); UtRegisterTest("SCThresholdConfTest14 - suppress", SCThresholdConfTest14); - UtRegisterTest("SCThresholdConfTest15 - suppress drop", - SCThresholdConfTest15); - UtRegisterTest("SCThresholdConfTest16 - suppress drop", - SCThresholdConfTest16); - UtRegisterTest("SCThresholdConfTest17 - suppress drop", - SCThresholdConfTest17); - - UtRegisterTest("SCThresholdConfTest18 - suppress parsing", - SCThresholdConfTest18); - UtRegisterTest("SCThresholdConfTest19 - suppress parsing", - SCThresholdConfTest19); - UtRegisterTest("SCThresholdConfTest20 - suppress parsing", - SCThresholdConfTest20); - UtRegisterTest("SCThresholdConfTest21 - suppress parsing", - SCThresholdConfTest21); - UtRegisterTest("SCThresholdConfTest22 - rate_filter by_both", - SCThresholdConfTest22); - UtRegisterTest("SCThresholdConfTest23 - rate_filter by_both opposite", - SCThresholdConfTest23); + UtRegisterTest("SCThresholdConfTest15 - suppress drop", SCThresholdConfTest15); + UtRegisterTest("SCThresholdConfTest16 - suppress drop", SCThresholdConfTest16); + UtRegisterTest("SCThresholdConfTest17 - suppress drop", SCThresholdConfTest17); + + UtRegisterTest("SCThresholdConfTest18 - suppress parsing", SCThresholdConfTest18); + UtRegisterTest("SCThresholdConfTest19 - suppress parsing", SCThresholdConfTest19); + UtRegisterTest("SCThresholdConfTest20 - suppress parsing", SCThresholdConfTest20); + UtRegisterTest("SCThresholdConfTest21 - suppress parsing", SCThresholdConfTest21); + UtRegisterTest("SCThresholdConfTest22 - rate_filter by_both", SCThresholdConfTest22); + UtRegisterTest("SCThresholdConfTest23 - rate_filter by_both opposite", SCThresholdConfTest23); #endif /* UNITTESTS */ } diff --git a/src/util-time.c b/src/util-time.c index 9900f1b94bd3..ff9707fcc342 100644 --- a/src/util-time.c +++ b/src/util-time.c @@ -69,7 +69,7 @@ #ifdef UNITTESTS static struct timeval current_time = { 0, 0 }; #endif -//static SCMutex current_time_mutex = SCMUTEX_INITIALIZER; +// static SCMutex current_time_mutex = SCMUTEX_INITIALIZER; static SCSpinlock current_time_spinlock; static bool live_time_tracking = true; @@ -102,7 +102,7 @@ void TimeModeSetLive(void) SCLogDebug("live time mode enabled"); } -void TimeModeSetOffline (void) +void TimeModeSetOffline(void) { live_time_tracking = false; SCLogDebug("offline time mode enabled"); @@ -130,8 +130,8 @@ void TimeSet(SCTime_t ts) SCSpinLock(¤t_time_spinlock); SCTIME_TO_TIMEVAL(¤t_time, ts); - SCLogDebug("time set to %" PRIuMAX " sec, %" PRIuMAX " usec", - (uintmax_t)current_time.tv_sec, (uintmax_t)current_time.tv_usec); + SCLogDebug("time set to %" PRIuMAX " sec, %" PRIuMAX " usec", (uintmax_t)current_time.tv_sec, + (uintmax_t)current_time.tv_usec); SCSpinUnlock(¤t_time_spinlock); } @@ -211,7 +211,7 @@ void CreateIsoTimeString(const SCTime_t ts, char *str, size_t size) time_t time = SCTIME_SECS(ts); struct tm local_tm; memset(&local_tm, 0, sizeof(local_tm)); - struct tm *t = (struct tm*)SCLocalTime(time, &local_tm); + struct tm *t = (struct tm *)SCLocalTime(time, &local_tm); if (likely(t != NULL)) { #ifdef OS_WIN32 @@ -232,7 +232,7 @@ void CreateUtcIsoTimeString(const SCTime_t ts, char *str, size_t size) time_t time = SCTIME_SECS(ts); struct tm local_tm; memset(&local_tm, 0, sizeof(local_tm)); - struct tm *t = (struct tm*)SCUtcTime(time, &local_tm); + struct tm *t = (struct tm *)SCUtcTime(time, &local_tm); if (likely(t != NULL)) { char time_fmt[64] = { 0 }; @@ -243,7 +243,7 @@ void CreateUtcIsoTimeString(const SCTime_t ts, char *str, size_t size) } } -void CreateFormattedTimeString (const struct tm *t, const char *fmt, char *str, size_t size) +void CreateFormattedTimeString(const struct tm *t, const char *fmt, char *str, size_t size) { if (likely(t != NULL)) { strftime(str, size, fmt, t); @@ -273,7 +273,7 @@ void CreateTimeString(const SCTime_t ts, char *str, size_t size) { time_t time = SCTIME_SECS(ts); struct tm local_tm; - struct tm *t = (struct tm*)SCLocalTime(time, &local_tm); + struct tm *t = (struct tm *)SCLocalTime(time, &local_tm); if (likely(t != NULL)) { snprintf(str, size, "%02d/%02d/%02d-%02d:%02d:%02d.%06u", t->tm_mon + 1, t->tm_mday, @@ -335,7 +335,7 @@ struct tm *SCLocalTime(time_t timep, struct tm *result) int mru_seconds = timep - cached_minute_start[mru]; int lru_seconds = timep - cached_minute_start[lru]; int new_seconds; - if (cached_minute_start[mru]==0 && cached_minute_start[lru]==0) { + if (cached_minute_start[mru] == 0 && cached_minute_start[lru] == 0) { localtime_r(&timep, &cached_local_tm[lru]); /* Subtract seconds to get back to the start of the minute. */ new_seconds = cached_local_tm[lru].tm_sec; @@ -372,9 +372,8 @@ static int UpdateCachedTime(int n, time_t time) struct tm local_tm; struct tm *t = (struct tm *)SCLocalTime(time, &local_tm); int cached_len = snprintf(cached_local_time[n], MAX_LOCAL_TIME_STRING, - "%02d/%02d/%02d-%02d:%02d:", - t->tm_mon + 1, t->tm_mday, t->tm_year + 1900, - t->tm_hour, t->tm_min); + "%02d/%02d/%02d-%02d:%02d:", t->tm_mon + 1, t->tm_mday, t->tm_year + 1900, t->tm_hour, + t->tm_min); cached_local_time_len[n] = cached_len; /* Store the time of the beginning of the minute. */ last_local_time[n] = time - t->tm_sec; @@ -400,7 +399,7 @@ void CreateTimeString(const SCTime_t ts, char *str, size_t size) int lru = 1 - mru; int mru_seconds = time - last_local_time[mru]; int lru_seconds = time - last_local_time[lru]; - if (last_local_time[mru]==0 && last_local_time[lru]==0) { + if (last_local_time[mru] == 0 && last_local_time[lru] == 0) { /* First time here, update both caches */ UpdateCachedTime(mru, time); seconds = UpdateCachedTime(lru, time); @@ -422,7 +421,7 @@ void CreateTimeString(const SCTime_t ts, char *str, size_t size) char *cached_str = cached_local_time[mru_time_slot]; int cached_len = cached_local_time_len[mru_time_slot]; if (cached_len >= (int)size) - cached_len = size; + cached_len = size; memcpy(str, cached_str, cached_len); snprintf(str + cached_len, size - cached_len, "%02d.%06u", seconds, (uint32_t)SCTIME_USECS(ts)); } @@ -439,13 +438,13 @@ void CreateTimeString(const SCTime_t ts, char *str, size_t size) * * \retval Seconds since Unix epoch. */ -time_t SCMkTimeUtc (struct tm *tp) +time_t SCMkTimeUtc(struct tm *tp) { time_t result; long year; #define MONTHSPERYEAR 12 - static const int mdays[MONTHSPERYEAR] = - { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 }; + static const int mdays[MONTHSPERYEAR] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, + 334 }; year = 1900 + tp->tm_year + tp->tm_mon / MONTHSPERYEAR; result = (year - 1970) * 365 + mdays[tp->tm_mon % MONTHSPERYEAR]; @@ -482,15 +481,13 @@ time_t SCMkTimeUtc (struct tm *tp) * \retval 0 on success. * \retval 1 on failure. */ -int SCStringPatternToTime (char *string, const char **patterns, int num_patterns, - struct tm *tp) +int SCStringPatternToTime(char *string, const char **patterns, int num_patterns, struct tm *tp) { char *result = NULL; int i = 0; /* Do the pattern matching */ - for (i = 0; i < num_patterns; i++) - { + for (i = 0; i < num_patterns; i++) { if (patterns[i] == NULL) continue; @@ -512,14 +509,12 @@ int SCStringPatternToTime (char *string, const char **patterns, int num_patterns return 1; /* Return if no date is given */ - if (tp->tm_year == INT_MIN && tp->tm_mon == INT_MIN && - tp->tm_mday == INT_MIN) + if (tp->tm_year == INT_MIN && tp->tm_mon == INT_MIN && tp->tm_mday == INT_MIN) return 1; /* The first of the month is assumed, if only year and month is given */ - if (tp->tm_year != INT_MIN && tp->tm_mon != INT_MIN && - tp->tm_mday <= 0) + if (tp->tm_year != INT_MIN && tp->tm_mon != INT_MIN && tp->tm_mday <= 0) tp->tm_mday = 1; return 0; @@ -538,7 +533,7 @@ int SCStringPatternToTime (char *string, const char **patterns, int num_patterns * \retval 0 on success. * \retval 1 on failure. */ -int SCTimeToStringPattern (time_t epoch, const char *pattern, char *str, size_t size) +int SCTimeToStringPattern(time_t epoch, const char *pattern, char *str, size_t size) { struct tm tm; memset(&tm, 0, sizeof(tm)); @@ -567,14 +562,13 @@ int SCTimeToStringPattern (time_t epoch, const char *pattern, char *str, size_t * \retval size on success. * \retval 0 on failure. */ -uint64_t SCParseTimeSizeString (const char *str) +uint64_t SCParseTimeSizeString(const char *str) { uint64_t size = 0; uint64_t modifier = 1; - char last = str[strlen(str)-1]; + char last = str[strlen(str) - 1]; - switch (last) - { + switch (last) { case '0' ... '9': break; /* seconds */ @@ -618,7 +612,7 @@ uint64_t SCParseTimeSizeString (const char *str) * * \retval seconds. */ -uint64_t SCGetSecondsUntil (const char *str, time_t epoch) +uint64_t SCGetSecondsUntil(const char *str, time_t epoch) { uint64_t seconds = 0; struct tm tm; @@ -630,13 +624,12 @@ uint64_t SCGetSecondsUntil (const char *str, time_t epoch) else if (strcmp(str, "hour") == 0) seconds = (60 * (60 - tp->tm_min)) + (60 - tp->tm_sec); else if (strcmp(str, "day") == 0) - seconds = (3600 * (24 - tp->tm_hour)) + (60 * (60 - tp->tm_min)) + - (60 - tp->tm_sec); + seconds = (3600 * (24 - tp->tm_hour)) + (60 * (60 - tp->tm_min)) + (60 - tp->tm_sec); return seconds; } -uint64_t SCTimespecAsEpochMillis(const struct timespec* ts) +uint64_t SCTimespecAsEpochMillis(const struct timespec *ts) { return ts->tv_sec * 1000L + ts->tv_nsec / 1000000L; } diff --git a/src/util-time.h b/src/util-time.h index 9bbd8798dd17..365f088839fc 100644 --- a/src/util-time.h +++ b/src/util-time.h @@ -105,7 +105,10 @@ void TimeSetByThread(const int thread_id, SCTime_t tv); SCTime_t TimeGet(void); /** \brief initialize a 'struct timespec' from a 'struct timeval'. */ -#define FROM_TIMEVAL(timev) { .tv_sec = (timev).tv_sec, .tv_nsec = (timev).tv_usec * 1000 } +#define FROM_TIMEVAL(timev) \ + { \ + .tv_sec = (timev).tv_sec, .tv_nsec = (timev).tv_usec * 1000 \ + } /** \brief compare two 'struct timeval' and return if the first is earlier than the second */ static inline bool TimevalEarlier(struct timeval *first, struct timeval *second) @@ -136,23 +139,20 @@ void TimeSetIncrementTime(uint32_t); bool TimeModeIsReady(void); void TimeModeSetLive(void); -void TimeModeSetOffline (void); +void TimeModeSetOffline(void); bool TimeModeIsLive(void); struct tm *SCLocalTime(time_t timep, struct tm *result); void CreateTimeString(const SCTime_t ts, char *str, size_t size); void CreateIsoTimeString(const SCTime_t ts, char *str, size_t size); void CreateUtcIsoTimeString(const SCTime_t ts, char *str, size_t size); -void CreateFormattedTimeString(const struct tm *t, const char * fmt, char *str, size_t size); +void CreateFormattedTimeString(const struct tm *t, const char *fmt, char *str, size_t size); time_t SCMkTimeUtc(struct tm *tp); -int SCStringPatternToTime(char *string, const char **patterns, - int num_patterns, struct tm *time); -int SCTimeToStringPattern (time_t epoch, const char *pattern, char *str, - size_t size); -uint64_t SCParseTimeSizeString (const char *str); -uint64_t SCGetSecondsUntil (const char *str, time_t epoch); +int SCStringPatternToTime(char *string, const char **patterns, int num_patterns, struct tm *time); +int SCTimeToStringPattern(time_t epoch, const char *pattern, char *str, size_t size); +uint64_t SCParseTimeSizeString(const char *str); +uint64_t SCGetSecondsUntil(const char *str, time_t epoch); uint64_t SCTimespecAsEpochMillis(const struct timespec *ts); uint64_t TimeDifferenceMicros(struct timeval t0, struct timeval t1); #endif /* __UTIL_TIME_H__ */ - diff --git a/src/util-unittest-helper.c b/src/util-unittest-helper.c index 48d2a045c19b..499cf5026560 100644 --- a/src/util-unittest-helper.c +++ b/src/util-unittest-helper.c @@ -113,7 +113,7 @@ int TestHelperBufferToFile(const char *name, const uint8_t *data, size_t size) printf("failed open, errno=%d\n", errno); return -2; } - if (fwrite (data, 1, size, fd) != size) { + if (fwrite(data, 1, size, fd) != size) { fclose(fd); return -3; } @@ -155,9 +155,8 @@ uint32_t UTHSetIPv4Address(const char *str) * * \retval Packet pointer to the built in packet */ -Packet *UTHBuildPacketIPV6Real(uint8_t *payload, uint16_t payload_len, - uint8_t ipproto, const char *src, const char *dst, - uint16_t sport, uint16_t dport) +Packet *UTHBuildPacketIPV6Real(uint8_t *payload, uint16_t payload_len, uint8_t ipproto, + const char *src, const char *dst, uint16_t sport, uint16_t dport) { uint32_t in[4]; @@ -241,9 +240,8 @@ Packet *UTHBuildPacketIPV6Real(uint8_t *payload, uint16_t payload_len, * * \retval Packet pointer to the built in packet */ -Packet *UTHBuildPacketReal(uint8_t *payload, uint16_t payload_len, - uint8_t ipproto, const char *src, const char *dst, - uint16_t sport, uint16_t dport) +Packet *UTHBuildPacketReal(uint8_t *payload, uint16_t payload_len, uint8_t ipproto, const char *src, + const char *dst, uint16_t sport, uint16_t dport) { struct in_addr in; @@ -308,14 +306,14 @@ Packet *UTHBuildPacketReal(uint8_t *payload, uint16_t payload_len, break; default: break; - /* TODO: Add more protocols */ + /* TODO: Add more protocols */ } if (payload && payload_len) { PacketCopyDataOffset(p, hdr_offset, payload, payload_len); } SET_PKT_LEN(p, hdr_offset + payload_len); - p->payload = GET_PKT_DATA(p)+hdr_offset; + p->payload = GET_PKT_DATA(p) + hdr_offset; return p; @@ -334,12 +332,10 @@ Packet *UTHBuildPacketReal(uint8_t *payload, uint16_t payload_len, * * \retval Packet pointer to the built in packet */ -Packet *UTHBuildPacket(uint8_t *payload, uint16_t payload_len, - uint8_t ipproto) +Packet *UTHBuildPacket(uint8_t *payload, uint16_t payload_len, uint8_t ipproto) { - return UTHBuildPacketReal(payload, payload_len, ipproto, - "192.168.1.5", "192.168.1.1", - 41424, 80); + return UTHBuildPacketReal( + payload, payload_len, ipproto, "192.168.1.5", "192.168.1.1", 41424, 80); } /** @@ -415,12 +411,10 @@ Packet *UTHBuildPacketFromEth(uint8_t *raw_eth, uint16_t pktsize) * * \retval Packet pointer to the built in packet */ -Packet *UTHBuildPacketSrcDst(uint8_t *payload, uint16_t payload_len, - uint8_t ipproto, const char *src, const char *dst) +Packet *UTHBuildPacketSrcDst( + uint8_t *payload, uint16_t payload_len, uint8_t ipproto, const char *src, const char *dst) { - return UTHBuildPacketReal(payload, payload_len, ipproto, - src, dst, - 41424, 80); + return UTHBuildPacketReal(payload, payload_len, ipproto, src, dst, 41424, 80); } /** @@ -433,12 +427,10 @@ Packet *UTHBuildPacketSrcDst(uint8_t *payload, uint16_t payload_len, * * \retval Packet pointer to the built in packet */ -Packet *UTHBuildPacketIPV6SrcDst(uint8_t *payload, uint16_t payload_len, - uint8_t ipproto, const char *src, const char *dst) +Packet *UTHBuildPacketIPV6SrcDst( + uint8_t *payload, uint16_t payload_len, uint8_t ipproto, const char *src, const char *dst) { - return UTHBuildPacketIPV6Real(payload, payload_len, ipproto, - src, dst, - 41424, 80); + return UTHBuildPacketIPV6Real(payload, payload_len, ipproto, src, dst, 41424, 80); } /** @@ -451,12 +443,11 @@ Packet *UTHBuildPacketIPV6SrcDst(uint8_t *payload, uint16_t payload_len, * * \retval Packet pointer to the built in packet */ -Packet *UTHBuildPacketSrcDstPorts(uint8_t *payload, uint16_t payload_len, - uint8_t ipproto, uint16_t sport, uint16_t dport) +Packet *UTHBuildPacketSrcDstPorts( + uint8_t *payload, uint16_t payload_len, uint8_t ipproto, uint16_t sport, uint16_t dport) { - return UTHBuildPacketReal(payload, payload_len, ipproto, - "192.168.1.5", "192.168.1.1", - sport, dport); + return UTHBuildPacketReal( + payload, payload_len, ipproto, "192.168.1.5", "192.168.1.1", sport, dport); } /** @@ -505,12 +496,11 @@ Flow *UTHBuildFlow(int family, const char *src, const char *dst, Port sp, Port d void UTHFreeFlow(Flow *flow) { if (flow != NULL) { - SCFree(flow);//FlowFree(flow); + SCFree(flow); // FlowFree(flow); } } -int UTHAddStreamToFlow(Flow *f, int direction, - uint8_t *data, uint32_t data_len) +int UTHAddStreamToFlow(Flow *f, int direction, uint8_t *data, uint32_t data_len) { FAIL_IF_NULL(f); FAIL_IF_NOT(f->proto == IPPROTO_TCP); @@ -525,9 +515,7 @@ int UTHAddStreamToFlow(Flow *f, int direction, return 1; } -int UTHAddSessionToFlow(Flow *f, - uint32_t ts_isn, - uint32_t tc_isn) +int UTHAddSessionToFlow(Flow *f, uint32_t ts_isn, uint32_t tc_isn) { FAIL_IF_NULL(f); @@ -580,12 +568,13 @@ int UTHRemoveSessionFromFlow(Flow *f) * \retval int 1 if the match of all the sids is the specified has the * specified results; 0 if not */ -int UTHGenericTest(Packet **pkt, int numpkts, const char *sigs[], uint32_t sids[], uint32_t *results, int numsigs) +int UTHGenericTest(Packet **pkt, int numpkts, const char *sigs[], uint32_t sids[], + uint32_t *results, int numsigs) { int result = 0; - if (pkt == NULL || sigs == NULL || numpkts == 0 - || sids == NULL || results == NULL || numsigs == 0) { + if (pkt == NULL || sigs == NULL || numpkts == 0 || sids == NULL || results == NULL || + numsigs == 0) { SCLogError("Arguments invalid, that the pointer/arrays are not NULL, and the number of " "signatures and packets is > 0"); goto end; @@ -688,7 +677,8 @@ int UTHAppendSigs(DetectEngineCtx *de_ctx, const char *sigs[], int numsigs) * \retval return 1 if all goes well * \retval return 0 if something fail */ -int UTHMatchPacketsWithResults(DetectEngineCtx *de_ctx, Packet **p, int num_packets, uint32_t sids[], uint32_t *results, int numsigs) +int UTHMatchPacketsWithResults(DetectEngineCtx *de_ctx, Packet **p, int num_packets, + uint32_t sids[], uint32_t *results, int numsigs) { BUG_ON(de_ctx == NULL); BUG_ON(p == NULL); @@ -751,7 +741,8 @@ int UTHMatchPackets(DetectEngineCtx *de_ctx, Packet **p, int num_packets) * and others may not. That check will be outside */ DetectEngineThreadCtxDeinit(&th_v, (void *)det_ctx); - if (de_ctx != NULL) SigGroupCleanup(de_ctx); + if (de_ctx != NULL) + SigGroupCleanup(de_ctx); return result; } @@ -833,7 +824,7 @@ int UTHPacketMatchSig(Packet *p, const char *sig) DetectEngineCtx *de_ctx = DetectEngineCtxInit(); if (de_ctx == NULL) { - result=0; + result = 0; goto end; } @@ -856,8 +847,8 @@ int UTHPacketMatchSig(Packet *p, const char *sig) end: if (de_ctx) { - SigGroupCleanup(de_ctx); - SigCleanSignatures(de_ctx); + SigGroupCleanup(de_ctx); + SigCleanSignatures(de_ctx); } if (det_ctx != NULL) @@ -952,7 +943,7 @@ static int CheckUTHTestPacket(Packet *p, uint8_t ipproto) if (p->proto != ipproto) return 0; - switch(ipproto) { + switch (ipproto) { case IPPROTO_UDP: if (p->udph == NULL) return 0; @@ -960,7 +951,7 @@ static int CheckUTHTestPacket(Packet *p, uint8_t ipproto) return 0; if (p->udph->uh_dport != dport) return 0; - break; + break; case IPPROTO_TCP: if (p->tcph == NULL) return 0; @@ -968,22 +959,24 @@ static int CheckUTHTestPacket(Packet *p, uint8_t ipproto) return 0; if (SCNtohs(p->tcph->th_dport) != dport) return 0; - break; + break; } return 1; } #ifdef HAVE_MEMMEM #include -void * UTHmemsearch(const void *big, size_t big_len, const void *little, size_t little_len) { +void *UTHmemsearch(const void *big, size_t big_len, const void *little, size_t little_len) +{ return memmem(big, big_len, little, little_len); } #else #include "util-spm-bs.h" -void * UTHmemsearch(const void *big, size_t big_len, const void *little, size_t little_len) { +void *UTHmemsearch(const void *big, size_t big_len, const void *little, size_t little_len) +{ return BasicSearch(big, big_len, little, little_len); } -#endif //HAVE_MEMMEM +#endif // HAVE_MEMMEM /** * \brief UTHBuildPacketRealTest01 wrapper to check packets for unittests @@ -992,8 +985,8 @@ static int UTHBuildPacketRealTest01(void) { uint8_t payload[] = "Payload"; - Packet *p = UTHBuildPacketReal(payload, sizeof(payload), IPPROTO_TCP, - "192.168.1.5", "192.168.1.1", 41424, 80); + Packet *p = UTHBuildPacketReal( + payload, sizeof(payload), IPPROTO_TCP, "192.168.1.5", "192.168.1.1", 41424, 80); int ret = CheckUTHTestPacket(p, IPPROTO_TCP); UTHFreePacket(p); @@ -1008,8 +1001,8 @@ static int UTHBuildPacketRealTest02(void) { uint8_t payload[] = "Payload"; - Packet *p = UTHBuildPacketReal(payload, sizeof(payload), IPPROTO_UDP, - "192.168.1.5", "192.168.1.1", 41424, 80); + Packet *p = UTHBuildPacketReal( + payload, sizeof(payload), IPPROTO_UDP, "192.168.1.5", "192.168.1.1", 41424, 80); int ret = CheckUTHTestPacket(p, IPPROTO_UDP); UTHFreePacket(p); @@ -1067,7 +1060,6 @@ static int UTHBuildPacketOfFlowsTest01(void) return result; } - /** * \brief UTHBuildPacketSrcDstTest01 wrapper to check packets for unittests */ @@ -1075,8 +1067,8 @@ static int UTHBuildPacketSrcDstTest01(void) { uint8_t payload[] = "Payload"; - Packet *p = UTHBuildPacketSrcDst(payload, sizeof(payload), IPPROTO_TCP, - "192.168.1.5", "192.168.1.1"); + Packet *p = UTHBuildPacketSrcDst( + payload, sizeof(payload), IPPROTO_TCP, "192.168.1.5", "192.168.1.1"); int ret = CheckUTHTestPacket(p, IPPROTO_TCP); UTHFreePacket(p); @@ -1091,8 +1083,8 @@ static int UTHBuildPacketSrcDstTest02(void) { uint8_t payload[] = "Payload"; - Packet *p = UTHBuildPacketSrcDst(payload, sizeof(payload), IPPROTO_UDP, - "192.168.1.5", "192.168.1.1"); + Packet *p = UTHBuildPacketSrcDst( + payload, sizeof(payload), IPPROTO_UDP, "192.168.1.5", "192.168.1.1"); int ret = CheckUTHTestPacket(p, IPPROTO_UDP); UTHFreePacket(p); @@ -1107,8 +1099,7 @@ static int UTHBuildPacketSrcDstPortsTest01(void) { uint8_t payload[] = "Payload"; - Packet *p = UTHBuildPacketSrcDstPorts(payload, sizeof(payload), IPPROTO_TCP, - 41424, 80); + Packet *p = UTHBuildPacketSrcDstPorts(payload, sizeof(payload), IPPROTO_TCP, 41424, 80); int ret = CheckUTHTestPacket(p, IPPROTO_TCP); UTHFreePacket(p); @@ -1123,8 +1114,7 @@ static int UTHBuildPacketSrcDstPortsTest02(void) { uint8_t payload[] = "Payload"; - Packet *p = UTHBuildPacketSrcDstPorts(payload, sizeof(payload), IPPROTO_UDP, - 41424, 80); + Packet *p = UTHBuildPacketSrcDstPorts(payload, sizeof(payload), IPPROTO_UDP, 41424, 80); int ret = CheckUTHTestPacket(p, IPPROTO_UDP); UTHFreePacket(p); @@ -1143,12 +1133,9 @@ void UTHRegisterTests(void) UtRegisterTest("UTHBuildPacketTest02", UTHBuildPacketTest02); UtRegisterTest("UTHBuildPacketSrcDstTest01", UTHBuildPacketSrcDstTest01); UtRegisterTest("UTHBuildPacketSrcDstTest02", UTHBuildPacketSrcDstTest02); - UtRegisterTest("UTHBuildPacketSrcDstPortsTest01", - UTHBuildPacketSrcDstPortsTest01); - UtRegisterTest("UTHBuildPacketSrcDstPortsTest02", - UTHBuildPacketSrcDstPortsTest02); + UtRegisterTest("UTHBuildPacketSrcDstPortsTest01", UTHBuildPacketSrcDstPortsTest01); + UtRegisterTest("UTHBuildPacketSrcDstPortsTest02", UTHBuildPacketSrcDstPortsTest02); UtRegisterTest("UTHBuildPacketOfFlowsTest01", UTHBuildPacketOfFlowsTest01); #endif /* UNITTESTS */ } - diff --git a/src/util-unittest-helper.h b/src/util-unittest-helper.h index b3b6d18aa4b0..1ce0653fb6a8 100644 --- a/src/util-unittest-helper.h +++ b/src/util-unittest-helper.h @@ -38,7 +38,8 @@ int TestHelperBufferToFile(const char *name, const uint8_t *data, size_t size); #ifdef UNITTESTS uint32_t UTHSetIPv4Address(const char *); -Packet *UTHBuildPacketReal(uint8_t *, uint16_t, uint8_t ipproto, const char *, const char *, uint16_t, uint16_t); +Packet *UTHBuildPacketReal( + uint8_t *, uint16_t, uint8_t ipproto, const char *, const char *, uint16_t, uint16_t); Packet *UTHBuildPacket(uint8_t *, uint16_t, uint8_t ipproto); Packet *UTHBuildPacketSrcDst(uint8_t *, uint16_t, uint8_t ipproto, const char *, const char *); Packet *UTHBuildPacketSrcDstPorts(uint8_t *, uint16_t, uint8_t ipproto, uint16_t, uint16_t); @@ -69,10 +70,10 @@ int UTHMatchPacketsWithResults(DetectEngineCtx *, Packet **, int, uint32_t *, ui int UTHGenericTest(Packet **, int, const char **, uint32_t *, uint32_t *, int); uint32_t UTHBuildPacketOfFlows(uint32_t, uint32_t, uint8_t); -Packet *UTHBuildPacketIPV6Real(uint8_t *, uint16_t , uint8_t ipproto, const char *, const char *, - uint16_t , uint16_t ); +Packet *UTHBuildPacketIPV6Real( + uint8_t *, uint16_t, uint8_t ipproto, const char *, const char *, uint16_t, uint16_t); -void * UTHmemsearch(const void *big, size_t big_len, const void *little, size_t little_len); +void *UTHmemsearch(const void *big, size_t big_len, const void *little, size_t little_len); int UTHParseSignature(const char *str, bool expect); #endif diff --git a/src/util-unittest.c b/src/util-unittest.c index d4ef5dc99c76..2d43d50adff0 100644 --- a/src/util-unittest.c +++ b/src/util-unittest.c @@ -100,7 +100,7 @@ static int UtAppendTest(UtTest **list, UtTest *test) * \param TestFn Unit test function */ -void UtRegisterTest(const char *name, int(*TestFn)(void)) +void UtRegisterTest(const char *name, int (*TestFn)(void)) { UtTest *ut = UtAllocTest(); if (ut == NULL) @@ -122,19 +122,18 @@ void UtRegisterTest(const char *name, int(*TestFn)(void)) * \retval 1 Regex compiled * \retval -1 Regex error */ -static int UtRegex (const char *regex_arg) +static int UtRegex(const char *regex_arg) { int en; PCRE2_SIZE eo; int opts = PCRE2_CASELESS; - if(regex_arg == NULL) + if (regex_arg == NULL) return -1; parse_regex = pcre2_compile((PCRE2_SPTR8)regex_arg, PCRE2_ZERO_TERMINATED, opts, &en, &eo, NULL); - if(parse_regex == NULL) - { + if (parse_regex == NULL) { PCRE2_UCHAR errbuffer[256]; pcre2_get_error_message(en, errbuffer, sizeof(errbuffer)); SCLogError("pcre2 compile of \"%s\" failed at " @@ -162,14 +161,13 @@ void UtListTests(const char *regex_arg) rcomp = UtRegex(regex_arg); for (ut = ut_list; ut != NULL; ut = ut->next) { - if (rcomp == 1) { + if (rcomp == 1) { ret = pcre2_match(parse_regex, (PCRE2_SPTR8)ut->name, strlen(ut->name), 0, 0, parse_regex_match, NULL); if (ret >= 1) { printf("%s\n", ut->name); } - } - else { + } else { printf("%s\n", ut->name); } } @@ -196,11 +194,11 @@ uint32_t UtRunTests(const char *regex_arg) rcomp = UtRegex(regex_arg); - if(rcomp == 1){ + if (rcomp == 1) { for (ut = ut_list; ut != NULL; ut = ut->next) { ret = pcre2_match(parse_regex, (PCRE2_SPTR8)ut->name, strlen(ut->name), 0, 0, parse_regex_match, NULL); - if( ret >= 1 ) { + if (ret >= 1) { printf("Test %-60.60s : ", ut->name); matchcnt++; fflush(stdout); /* flush so in case of a segv we see the testname */ @@ -212,16 +210,17 @@ uint32_t UtRunTests(const char *regex_arg) ret = ut->TestFn(); if (StreamTcpMemuseCounter() != 0) { - printf("STREAM MEMORY IN USE %"PRIu64"\n", StreamTcpMemuseCounter()); + printf("STREAM MEMORY IN USE %" PRIu64 "\n", StreamTcpMemuseCounter()); ret = 0; } if (FlowGetMemuse() != 0) { - printf("FLOW MEMORY IN USE %"PRIu64"\n", FlowGetMemuse()); + printf("FLOW MEMORY IN USE %" PRIu64 "\n", FlowGetMemuse()); ret = 0; } if (StreamTcpReassembleMemuseGlobalCounter() != 0) { - printf("STREAM REASSEMBLY MEMORY IN USE %"PRIu64"\n", StreamTcpReassembleMemuseGlobalCounter()); + printf("STREAM REASSEMBLY MEMORY IN USE %" PRIu64 "\n", + StreamTcpReassembleMemuseGlobalCounter()); ret = 0; } @@ -238,13 +237,14 @@ uint32_t UtRunTests(const char *regex_arg) } } } - if(matchcnt > 0){ + if (matchcnt > 0) { printf("==== TEST RESULTS ====\n"); printf("PASSED: %" PRIu32 "\n", good); printf("FAILED: %" PRIu32 "\n", bad); printf("======================\n"); } else { - SCLogInfo("UtRunTests: regex provided regex_arg: %s did not match any tests",regex_arg); + SCLogInfo( + "UtRunTests: regex provided regex_arg: %s did not match any tests", regex_arg); } } else { SCLogInfo("UtRunTests: pcre compilation failed"); @@ -298,8 +298,10 @@ void UtRunModeRegister(void) */ static int UtSelftestTrue(void) { - if (1)return 1; - else return 0; + if (1) + return 1; + else + return 0; } /** \brief False test @@ -309,8 +311,10 @@ static int UtSelftestTrue(void) */ static int UtSelftestFalse(void) { - if (0)return 0; - else return 1; + if (0) + return 0; + else + return 1; } /** \brief Run self tests @@ -320,7 +324,7 @@ static int UtSelftestFalse(void) * \retval 0 all successful */ -int UtRunSelftest (const char *regex_arg) +int UtRunSelftest(const char *regex_arg) { printf("* Running Unittesting subsystem selftests...\n"); diff --git a/src/util-unittest.h b/src/util-unittest.h index 80d666304da3..de19d1e01938 100644 --- a/src/util-unittest.h +++ b/src/util-unittest.h @@ -35,20 +35,19 @@ #ifdef UNITTESTS -typedef struct UtTest_ -{ +typedef struct UtTest_ { const char *name; - int(*TestFn)(void); + int (*TestFn)(void); struct UtTest_ *next; } UtTest; -void UtRegisterTest(const char *name, int(*TestFn)(void)); +void UtRegisterTest(const char *name, int (*TestFn)(void)); uint32_t UtRunTests(const char *regex_arg); void UtInitialize(void); void UtCleanup(void); -int UtRunSelftest (const char *regex_arg); +int UtRunSelftest(const char *regex_arg); void UtListTests(const char *regex_arg); void UtRunModeRegister(void); @@ -57,44 +56,49 @@ extern int unittests_fatal; /** * \brief Fail a test. */ -#define FAIL do { \ - if (unittests_fatal) { \ - BUG_ON(1); \ - } else { \ - return 0; \ - } \ +#define FAIL \ + do { \ + if (unittests_fatal) { \ + BUG_ON(1); \ + } else { \ + return 0; \ + } \ } while (0) /** * \brief Fail a test if expression evaluates to true. */ -#define FAIL_IF(expr) do { \ - if (unittests_fatal) { \ - BUG_ON(expr); \ - } else if (expr) { \ - return 0; \ - } \ +#define FAIL_IF(expr) \ + do { \ + if (unittests_fatal) { \ + BUG_ON(expr); \ + } else if (expr) { \ + return 0; \ + } \ } while (0) /** * \brief Fail a test if expression evaluates to false. */ -#define FAIL_IF_NOT(expr) do { \ - FAIL_IF(!(expr)); \ +#define FAIL_IF_NOT(expr) \ + do { \ + FAIL_IF(!(expr)); \ } while (0) /** * \brief Fail a test if expression evaluates to NULL. */ -#define FAIL_IF_NULL(expr) do { \ - FAIL_IF(NULL == expr); \ +#define FAIL_IF_NULL(expr) \ + do { \ + FAIL_IF(NULL == expr); \ } while (0) /** * \brief Fail a test if expression evaluates to non-NULL. */ -#define FAIL_IF_NOT_NULL(expr) do { \ - FAIL_IF(NULL != expr); \ +#define FAIL_IF_NOT_NULL(expr) \ + do { \ + FAIL_IF(NULL != expr); \ } while (0) /** @@ -102,8 +106,9 @@ extern int unittests_fatal; * * Only to be used at the end of a function instead of "return 1." */ -#define PASS do { \ - return 1; \ +#define PASS \ + do { \ + return 1; \ } while (0) #endif diff --git a/src/util-validate.h b/src/util-validate.h index c0dac20b78be..1df9ae72aa8d 100644 --- a/src/util-validate.h +++ b/src/util-validate.h @@ -27,7 +27,6 @@ * used for testing. */ - #ifndef __UTIL_VALIDATE_H__ #define __UTIL_VALIDATE_H__ @@ -38,61 +37,61 @@ * If trylock returns 0 it got a lock. Which means * the flow was previously unlocked. */ -#define DEBUG_ASSERT_FLOW_LOCKED(f) do { \ - if ((f) != NULL) { \ - int r = SCMutexTrylock(&(f)->m); \ - if (r == 0) { \ - BUG_ON(1); \ - } \ - } \ -} while(0) +#define DEBUG_ASSERT_FLOW_LOCKED(f) \ + do { \ + if ((f) != NULL) { \ + int r = SCMutexTrylock(&(f)->m); \ + if (r == 0) { \ + BUG_ON(1); \ + } \ + } \ + } while (0) /** \brief validate the integrity of the flow * * BUG_ON's on problems */ -#define DEBUG_VALIDATE_FLOW(f) do { \ - if ((f) != NULL) { \ - BUG_ON((f)->flags & FLOW_IPV4 && \ - (f)->flags & FLOW_IPV6); \ - if ((f)->proto == IPPROTO_TCP) { \ - BUG_ON((f)->alstate != NULL && \ - (f)->alparser == NULL); \ - } \ - } \ -} while(0) +#define DEBUG_VALIDATE_FLOW(f) \ + do { \ + if ((f) != NULL) { \ + BUG_ON((f)->flags &FLOW_IPV4 && (f)->flags & FLOW_IPV6); \ + if ((f)->proto == IPPROTO_TCP) { \ + BUG_ON((f)->alstate != NULL && (f)->alparser == NULL); \ + } \ + } \ + } while (0) /** \brief validate the integrity of the packet * * BUG_ON's on problems */ -#define DEBUG_VALIDATE_PACKET(p) do { \ - if ((p) != NULL) { \ - if ((p)->flow != NULL) { \ - DEBUG_VALIDATE_FLOW((p)->flow); \ - } \ - if (!((p)->flags & (PKT_IS_FRAGMENT|PKT_IS_INVALID))) { \ - if ((p)->proto == IPPROTO_TCP) { \ - BUG_ON((p)->tcph == NULL); \ - } else if ((p)->proto == IPPROTO_UDP) { \ - BUG_ON((p)->udph == NULL); \ - } else if ((p)->proto == IPPROTO_ICMP) { \ - BUG_ON((p)->icmpv4h == NULL); \ - } else if ((p)->proto == IPPROTO_SCTP) { \ - BUG_ON((p)->sctph == NULL); \ - } else if ((p)->proto == IPPROTO_ICMPV6) { \ - BUG_ON((p)->icmpv6h == NULL); \ - } \ - } \ - if ((p)->payload_len > 0) { \ - BUG_ON((p)->payload == NULL); \ - } \ - BUG_ON((p)->ip4h != NULL && (p)->ip6h != NULL); \ - BUG_ON((p)->flowflags != 0 && (p)->flow == NULL); \ - BUG_ON((p)->flowflags & FLOW_PKT_TOSERVER &&\ - (p)->flowflags & FLOW_PKT_TOCLIENT); \ - } \ -} while(0) +#define DEBUG_VALIDATE_PACKET(p) \ + do { \ + if ((p) != NULL) { \ + if ((p)->flow != NULL) { \ + DEBUG_VALIDATE_FLOW((p)->flow); \ + } \ + if (!((p)->flags & (PKT_IS_FRAGMENT | PKT_IS_INVALID))) { \ + if ((p)->proto == IPPROTO_TCP) { \ + BUG_ON((p)->tcph == NULL); \ + } else if ((p)->proto == IPPROTO_UDP) { \ + BUG_ON((p)->udph == NULL); \ + } else if ((p)->proto == IPPROTO_ICMP) { \ + BUG_ON((p)->icmpv4h == NULL); \ + } else if ((p)->proto == IPPROTO_SCTP) { \ + BUG_ON((p)->sctph == NULL); \ + } else if ((p)->proto == IPPROTO_ICMPV6) { \ + BUG_ON((p)->icmpv6h == NULL); \ + } \ + } \ + if ((p)->payload_len > 0) { \ + BUG_ON((p)->payload == NULL); \ + } \ + BUG_ON((p)->ip4h != NULL && (p)->ip6h != NULL); \ + BUG_ON((p)->flowflags != 0 && (p)->flow == NULL); \ + BUG_ON((p)->flowflags &FLOW_PKT_TOSERVER && (p)->flowflags & FLOW_PKT_TOCLIENT); \ + } \ + } while (0) #define DEBUG_VALIDATE_BUG_ON(exp) BUG_ON((exp)) @@ -106,4 +105,3 @@ #endif /* DEBUG_VALIDATE */ #endif /* __UTIL_VALIDATE_H__ */ - diff --git a/src/util-var-name.c b/src/util-var-name.c index b0a88bface59..638e2059c96a 100644 --- a/src/util-var-name.c +++ b/src/util-var-name.c @@ -82,7 +82,7 @@ typedef struct VariableName_ { } VariableName; #define VARNAME_HASHSIZE 0x1000 -#define VARID_HASHSIZE 0x1000 +#define VARID_HASHSIZE 0x1000 static SCMutex base_lock = SCMUTEX_INITIALIZER; static VarNameStore base = { .names = NULL, .ids = NULL, .max_id = 0 }; diff --git a/src/util-var-name.h b/src/util-var-name.h index 5f21ea3fa4ca..7ee985c34847 100644 --- a/src/util-var-name.h +++ b/src/util-var-name.h @@ -36,4 +36,3 @@ const char *VarNameStoreLookupById(const uint32_t id, const enum VarTypes type); uint32_t VarNameStoreLookupByName(const char *, const enum VarTypes type); #endif - diff --git a/src/util-var.c b/src/util-var.c index 8a2df63f1fa7..110d6d8ab3c5 100644 --- a/src/util-var.c +++ b/src/util-var.c @@ -53,34 +53,29 @@ void GenericVarFree(GenericVar *gv) GenericVar *next_gv = gv->next; switch (gv->type) { - case DETECT_FLOWBITS: - { + case DETECT_FLOWBITS: { FlowBit *fb = (FlowBit *)gv; - //printf("GenericVarFree: fb %p, removing\n", fb); + // printf("GenericVarFree: fb %p, removing\n", fb); FlowBitFree(fb); break; } - case DETECT_XBITS: - { + case DETECT_XBITS: { XBit *fb = (XBit *)gv; - //printf("GenericVarFree: fb %p, removing\n", fb); + // printf("GenericVarFree: fb %p, removing\n", fb); XBitFree(fb); break; } - case DETECT_FLOWVAR: - { + case DETECT_FLOWVAR: { FlowVar *fv = (FlowVar *)gv; FlowVarFree(fv); break; } - case DETECT_PKTVAR: - { + case DETECT_PKTVAR: { PktVar *pv = (PktVar *)gv; PktVarFree(pv); break; } - default: - { + default: { printf("ERROR: GenericVarFree unknown type %" PRIu32 "\n", gv->type); break; } @@ -97,7 +92,7 @@ void GenericVarAppend(GenericVar **list, GenericVar *gv) *list = gv; } else { GenericVar *tgv = *list; - while(tgv) { + while (tgv) { if (tgv->next == NULL) { tgv->next = gv; return; @@ -141,7 +136,7 @@ int AddVariableToResolveList(ResolvedVariablesList *list, const char *var) return 0; } - TAILQ_FOREACH(p_item, list, next) { + TAILQ_FOREACH (p_item, list, next) { if (!strcmp(p_item->var_name, var)) { return -1; } diff --git a/src/util-var.h b/src/util-var.h index ce491ecdcd82..2ae6bb284e02 100644 --- a/src/util-var.h +++ b/src/util-var.h @@ -53,9 +53,9 @@ typedef struct GenericVar_ { } GenericVar; typedef struct XBit_ { - uint8_t type; /* type, DETECT_XBITS in this case */ + uint8_t type; /* type, DETECT_XBITS in this case */ uint8_t pad[3]; - uint32_t idx; /* name idx */ + uint32_t idx; /* name idx */ GenericVar *next; uint32_t expire; } XBit; @@ -79,4 +79,3 @@ int AddVariableToResolveList(ResolvedVariablesList *list, const char *var); void CleanVariableResolveList(ResolvedVariablesList *var_list); #endif /* __UTIL_VAR_H__ */ - diff --git a/src/win32-misc.c b/src/win32-misc.c index 1dc28a69268a..a696591fa5a3 100644 --- a/src/win32-misc.c +++ b/src/win32-misc.c @@ -54,24 +54,23 @@ void unsetenv(const char *name) /* these functions have been defined on Vista and later */ #if NTDDI_VERSION < NTDDI_VISTA -const char* inet_ntop(int af, const void *src, char *dst, uint32_t cnt) +const char *inet_ntop(int af, const void *src, char *dst, uint32_t cnt) { - if (af == AF_INET) - { + if (af == AF_INET) { struct sockaddr_in in; memset(&in, 0, sizeof(in)); in.sin_family = AF_INET; memcpy(&in.sin_addr, src, sizeof(struct in_addr)); - if (0 == getnameinfo((struct sockaddr *)&in, sizeof(struct sockaddr_in), dst, cnt, NULL, 0, NI_NUMERICHOST)) + if (0 == getnameinfo((struct sockaddr *)&in, sizeof(struct sockaddr_in), dst, cnt, NULL, 0, + NI_NUMERICHOST)) return dst; - } - else if (af == AF_INET6) - { + } else if (af == AF_INET6) { struct sockaddr_in6 in6; memset(&in6, 0, sizeof(in6)); in6.sin6_family = AF_INET6; memcpy(&in6.sin6_addr, src, sizeof(struct in_addr6)); - if (0 == getnameinfo((struct sockaddr *)&in6, sizeof(struct sockaddr_in6), dst, cnt, NULL, 0, NI_NUMERICHOST)) + if (0 == getnameinfo((struct sockaddr *)&in6, sizeof(struct sockaddr_in6), dst, cnt, NULL, + 0, NI_NUMERICHOST)) return dst; } return NULL; @@ -94,20 +93,18 @@ int inet_pton(int af, const char *src, void *dst) return -1; } - struct addrinfo* result = NULL; + struct addrinfo *result = NULL; if (0 != getaddrinfo(src, NULL, &hints, &result)) return -1; if (result) { if (result->ai_family == AF_INET) { - struct sockaddr_in* in = (struct sockaddr_in*)result->ai_addr; + struct sockaddr_in *in = (struct sockaddr_in *)result->ai_addr; memcpy(dst, &in->sin_addr, 4); - } - else if (result->ai_family == AF_INET6) { - struct sockaddr_in6* in6 = (struct sockaddr_in6*)result->ai_addr; + } else if (result->ai_family == AF_INET6) { + struct sockaddr_in6 *in6 = (struct sockaddr_in6 *)result->ai_addr; memcpy(dst, &in6->sin6_addr, 16); - } - else { + } else { freeaddrinfo(result); return -1; } diff --git a/src/win32-misc.h b/src/win32-misc.h index adecd05e5fa6..4c3e17812216 100644 --- a/src/win32-misc.h +++ b/src/win32-misc.h @@ -34,7 +34,7 @@ void setenv(const char *name, const char *value, int overwrite); void unsetenv(const char *name); #if NTDDI_VERSION < NTDDI_VISTA -const char* inet_ntop(int af, const void *src, char *dst, uint32_t cnt); +const char *inet_ntop(int af, const void *src, char *dst, uint32_t cnt); int inet_pton(int af, const char *src, void *dst); #endif diff --git a/src/win32-service.c b/src/win32-service.c index 0b7bd24e5fab..47dfe8798c3f 100644 --- a/src/win32-service.c +++ b/src/win32-service.c @@ -46,7 +46,8 @@ int main(int argc, char **argv); int SCRunningAsService(void) { HANDLE h = INVALID_HANDLE_VALUE; - if ((h = CreateFile("CONIN$", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, 0)) == INVALID_HANDLE_VALUE) { + if ((h = CreateFile("CONIN$", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, + NULL, OPEN_EXISTING, 0, 0)) == INVALID_HANDLE_VALUE) { SCLogInfo("Running as service: yes"); return 1; } @@ -60,15 +61,8 @@ int SCRunningAsService(void) */ static void SCAtExitHandler(void) { - SERVICE_STATUS status = { - SERVICE_WIN32, - SERVICE_STOPPED, - SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN, - NO_ERROR, - NO_ERROR, - 0, - 0 - }; + SERVICE_STATUS status = { SERVICE_WIN32, SERVICE_STOPPED, + SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN, NO_ERROR, NO_ERROR, 0, 0 }; SCLogInfo("Exit handler called."); @@ -86,18 +80,12 @@ static void SCAtExitHandler(void) static DWORD WINAPI SCServiceCtrlHandlerEx(DWORD code, DWORD etype, LPVOID edata, LPVOID context) { if (code == SERVICE_CONTROL_SHUTDOWN || code == SERVICE_CONTROL_STOP) { - SERVICE_STATUS status = { - SERVICE_WIN32, - SERVICE_STOP_PENDING, - SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN, - NO_ERROR, - NO_ERROR, - 0, - 0 - }; + SERVICE_STATUS status = { SERVICE_WIN32, SERVICE_STOP_PENDING, + SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN, NO_ERROR, NO_ERROR, 0, 0 }; SCLogInfo("Service control handler called with %s control code.", - ((code == SERVICE_CONTROL_SHUTDOWN) ? ("SERVICE_CONTROL_SHUTDOWN") : ("SERVICE_CONTROL_STOP"))); + ((code == SERVICE_CONTROL_SHUTDOWN) ? ("SERVICE_CONTROL_SHUTDOWN") + : ("SERVICE_CONTROL_STOP"))); /* mark service as stop pending */ if (!SetServiceStatus(service_status_handle, &status)) { @@ -118,19 +106,13 @@ static DWORD WINAPI SCServiceCtrlHandlerEx(DWORD code, DWORD etype, LPVOID edata /** * \brief Service main function */ -static void WINAPI SCServiceMain(uint32_t argc, char** argv) +static void WINAPI SCServiceMain(uint32_t argc, char **argv) { - SERVICE_STATUS status = { - SERVICE_WIN32, - SERVICE_RUNNING, - SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN, - NO_ERROR, - NO_ERROR, - 0, - 0 - }; + SERVICE_STATUS status = { SERVICE_WIN32, SERVICE_RUNNING, + SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN, NO_ERROR, NO_ERROR, 0, 0 }; - if ((service_status_handle = RegisterServiceCtrlHandlerEx((char *)PROG_NAME, SCServiceCtrlHandlerEx, NULL)) == (SERVICE_STATUS_HANDLE)0) { + if ((service_status_handle = RegisterServiceCtrlHandlerEx( + (char *)PROG_NAME, SCServiceCtrlHandlerEx, NULL)) == (SERVICE_STATUS_HANDLE)0) { SCLogError("Can't register service control handler: %d", (int)GetLastError()); return; } @@ -172,9 +154,8 @@ static void WINAPI SCServiceMain(uint32_t argc, char** argv) */ int SCServiceInit(int argc, char **argv) { - SERVICE_TABLE_ENTRY DispatchTable[] = { - {(char *)PROG_NAME, (LPSERVICE_MAIN_FUNCTION) SCServiceMain}, - {NULL, NULL} + SERVICE_TABLE_ENTRY DispatchTable[] = { + { (char *)PROG_NAME, (LPSERVICE_MAIN_FUNCTION)SCServiceMain }, { NULL, NULL } }; /* continue with suricata initialization */ @@ -219,14 +200,15 @@ int SCServiceInstall(int argc, char **argv) do { memset(path, 0, sizeof(path)); - if (GetModuleFileName(NULL, path, MAX_PATH) == 0 ){ + if (GetModuleFileName(NULL, path, MAX_PATH) == 0) { SCLogError("Can't get path to service binary: %d", (int)GetLastError()); break; } /* skip name of binary itself */ for (i = 1; i < argc; i++) { - if ((strlen(argv[i]) <= strlen("--service-install")) && (strncmp("--service-install", argv[i], strlen(argv[i])) == 0)) { + if ((strlen(argv[i]) <= strlen("--service-install")) && + (strncmp("--service-install", argv[i], strlen(argv[i])) == 0)) { continue; } strlcat(path, " ", sizeof(path) - strlen(path) - 1); @@ -238,20 +220,9 @@ int SCServiceInstall(int argc, char **argv) break; } - service = CreateService( - scm, - PROG_NAME, - PROG_NAME, - SERVICE_ALL_ACCESS, - SERVICE_WIN32_OWN_PROCESS, - SERVICE_DEMAND_START, - SERVICE_ERROR_NORMAL, - path, - NULL, - NULL, - NULL, - NULL, - NULL); + service = CreateService(scm, PROG_NAME, PROG_NAME, SERVICE_ALL_ACCESS, + SERVICE_WIN32_OWN_PROCESS, SERVICE_DEMAND_START, SERVICE_ERROR_NORMAL, path, NULL, + NULL, NULL, NULL, NULL); if (service == NULL) { SCLogError("Can't create service: %d", (int)GetLastError()); @@ -260,7 +231,7 @@ int SCServiceInstall(int argc, char **argv) ret = 0; - } while(0); + } while (0); if (service) { CloseServiceHandle(service); @@ -314,7 +285,7 @@ int SCServiceRemove(int argc, char **argv) ret = 0; - } while(0); + } while (0); if (service) { CloseServiceHandle(service); @@ -344,14 +315,15 @@ int SCServiceChangeParams(int argc, char **argv) do { memset(path, 0, sizeof(path)); - if (GetModuleFileName(NULL, path, MAX_PATH) == 0 ){ + if (GetModuleFileName(NULL, path, MAX_PATH) == 0) { SCLogError("Can't get path to service binary: %d", (int)GetLastError()); break; } /* skip name of binary itself */ for (i = 1; i < argc; i++) { - if ((strlen(argv[i]) <= strlen("--service-change-params")) && (strncmp("--service-change-params", argv[i], strlen(argv[i])) == 0)) { + if ((strlen(argv[i]) <= strlen("--service-change-params")) && + (strncmp("--service-change-params", argv[i], strlen(argv[i])) == 0)) { continue; } strlcat(path, " ", sizeof(path) - strlen(path) - 1); @@ -368,26 +340,15 @@ int SCServiceChangeParams(int argc, char **argv) break; } - if (!ChangeServiceConfig( - service, - SERVICE_WIN32_OWN_PROCESS, - SERVICE_DEMAND_START, - SERVICE_ERROR_NORMAL, - path, - NULL, - NULL, - NULL, - NULL, - NULL, - PROG_NAME)) - { + if (!ChangeServiceConfig(service, SERVICE_WIN32_OWN_PROCESS, SERVICE_DEMAND_START, + SERVICE_ERROR_NORMAL, path, NULL, NULL, NULL, NULL, NULL, PROG_NAME)) { SCLogError("Can't change service configuration: %d", (int)GetLastError()); break; } ret = 0; - } while(0); + } while (0); return ret; } diff --git a/src/win32-syscall.c b/src/win32-syscall.c index 4e9145e118b7..296e79540696 100644 --- a/src/win32-syscall.c +++ b/src/win32-syscall.c @@ -98,20 +98,17 @@ uint32_t Win32GetAdaptersAddresses(IP_ADAPTER_ADDRESSES **pif_info_list) return NO_ERROR; } -uint32_t Win32FindAdapterAddresses(IP_ADAPTER_ADDRESSES *if_info_list, - const char *adapter_name, - IP_ADAPTER_ADDRESSES **pif_info) +uint32_t Win32FindAdapterAddresses(IP_ADAPTER_ADDRESSES *if_info_list, const char *adapter_name, + IP_ADAPTER_ADDRESSES **pif_info) { DWORD ret = NO_ERROR; adapter_name = StripPcapPrefix(adapter_name); *pif_info = NULL; - for (IP_ADAPTER_ADDRESSES *current = if_info_list; current != NULL; - current = current->Next) { + for (IP_ADAPTER_ADDRESSES *current = if_info_list; current != NULL; current = current->Next) { /* if we find the adapter, return that data */ - if (strncmp(adapter_name, current->AdapterName, strlen(adapter_name)) == - 0) { + if (strncmp(adapter_name, current->AdapterName, strlen(adapter_name)) == 0) { *pif_info = current; break; @@ -127,8 +124,14 @@ uint32_t Win32FindAdapterAddresses(IP_ADAPTER_ADDRESSES *if_info_list, #if NTDDI_VERSION < NTDDI_VISTA -int GetIfaceMTUWin32(const char *pcap_dev) { return 0; } -int GetGlobalMTUWin32(void) { return 0; } +int GetIfaceMTUWin32(const char *pcap_dev) +{ + return 0; +} +int GetGlobalMTUWin32(void) +{ + return 0; +} int GetIfaceOffloadingWin32(const char *ifname, int csum, int other) { @@ -162,8 +165,7 @@ static HMODULE wmiutils_dll = NULL; static HMODULE WmiUtils(void) { if (wmiutils_dll == NULL) { - wmiutils_dll = - LoadLibraryA("C:\\Windows\\System32\\wbem\\wmiutils.dll"); + wmiutils_dll = LoadLibraryA("C:\\Windows\\System32\\wbem\\wmiutils.dll"); } return wmiutils_dll; @@ -189,16 +191,14 @@ const char *Win32GetErrorString(DWORD error_code, HMODULE ext_module) { char *error_string = NULL; - DWORD flags = - FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS; + DWORD flags = FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS; if (ext_module != NULL) { flags |= FORMAT_MESSAGE_FROM_HMODULE; } else { flags |= FORMAT_MESSAGE_FROM_SYSTEM; } - FormatMessageA(flags, ext_module, error_code, 0, (LPTSTR)&error_string, 0, - NULL); + FormatMessageA(flags, ext_module, error_code, 0, (LPTSTR)&error_string, 0, NULL); if (error_string == NULL) { return ""; @@ -213,16 +213,15 @@ const char *Win32GetErrorString(DWORD error_code, HMODULE ext_module) /** * \brief log an HRESULT */ -static void _Win32HResultLog(SCLogLevel level, HRESULT hr, const char *file, - const char *function, const int line) +static void _Win32HResultLog( + SCLogLevel level, HRESULT hr, const char *file, const char *function, const int line) { const char *err_str = Win32GetErrorString(hr, WmiUtils()); - SCLog(level, file, function, line, "HRESULT: %s (0x%08" PRIx32 ")", err_str, - (uint32_t)(hr)); + SCLog(level, file, function, line, "HRESULT: %s (0x%08" PRIx32 ")", err_str, (uint32_t)(hr)); LocalFree((LPVOID)err_str); } -#define Win32HResultLogDebug(hr) \ +#define Win32HResultLogDebug(hr) \ _Win32HResultLog(SC_LOG_DEBUG, (hr), __FILE__, __FUNCTION__, __LINE__) #else #define Win32HResultLogDebug(hr) @@ -233,8 +232,7 @@ static void _Win32HResultLog(SCLogLevel level, HRESULT hr, const char *file, */ #define WbemLogDebug(hr) (_WbemLogDebug)((hr), __FILE__, __FUNCTION__, __LINE__) -static void _WbemLogDebug(HRESULT hr, const char *file, const char *function, - const int line) +static void _WbemLogDebug(HRESULT hr, const char *file, const char *function, const int line) { #ifdef DEBUG IErrorInfo *err_info; @@ -244,8 +242,7 @@ static void _WbemLogDebug(HRESULT hr, const char *file, const char *function, _Win32HResultLog(SC_LOG_DEBUG, hr, file, function, line); GetErrorInfo(0, &err_info); - if (!SUCCEEDED( - err_info->lpVtbl->GetDescription(err_info, &err_description))) { + if (!SUCCEEDED(err_info->lpVtbl->GetDescription(err_info, &err_description))) { // not much to do when your error log errors out... goto release; } @@ -259,12 +256,10 @@ static void _WbemLogDebug(HRESULT hr, const char *file, const char *function, // do the actual multibyte conversion err_description_mb[SysStringLen(err_description)] = 0; - wcstombs(err_description_mb, err_description, - SysStringLen(err_description)); + wcstombs(err_description_mb, err_description, SysStringLen(err_description)); // log the description - SCLog(SC_LOG_DEBUG, file, function, line, "WBEM error: %s", - err_description_mb); + SCLog(SC_LOG_DEBUG, file, function, line, "WBEM error: %s", err_description_mb); release: SCFree(err_description_mb); @@ -350,7 +345,7 @@ int GetGlobalMTUWin32(void) const char *errbuf = NULL; FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, - NULL, err, 0, (LPTSTR)&errbuf, 0, NULL); + NULL, err, 0, (LPTSTR)&errbuf, 0, NULL); SCLogWarning("Failure when trying to get global MTU via syscall: %s (%" PRId32 ")", errbuf, (uint32_t)err); @@ -358,12 +353,12 @@ int GetGlobalMTUWin32(void) return -1; } -#define ReleaseObject(objptr) \ - do { \ - if ((objptr) != NULL) { \ - (objptr)->lpVtbl->Release(objptr); \ - (objptr) = NULL; \ - } \ +#define ReleaseObject(objptr) \ + do { \ + if ((objptr) != NULL) { \ + (objptr)->lpVtbl->Release(objptr); \ + (objptr) = NULL; \ + } \ } while (0); typedef enum Win32TcpOffloadFlags_ { @@ -377,14 +372,13 @@ typedef enum Win32TcpOffloadFlags_ { WIN32_TCP_OFFLOAD_FLAG_LSOV2_IP6 = 1 << 6, /* aggregates */ - WIN32_TCP_OFFLOAD_FLAG_CSUM = WIN32_TCP_OFFLOAD_FLAG_CSUM_IP4RX | - WIN32_TCP_OFFLOAD_FLAG_CSUM_IP4TX | - WIN32_TCP_OFFLOAD_FLAG_CSUM_IP6RX | - WIN32_TCP_OFFLOAD_FLAG_CSUM_IP6TX, - WIN32_TCP_OFFLOAD_FLAG_CSUM_IP4 = WIN32_TCP_OFFLOAD_FLAG_CSUM_IP4RX | - WIN32_TCP_OFFLOAD_FLAG_CSUM_IP4TX, - WIN32_TCP_OFFLOAD_FLAG_CSUM_IP6 = WIN32_TCP_OFFLOAD_FLAG_CSUM_IP6RX | - WIN32_TCP_OFFLOAD_FLAG_CSUM_IP6TX, + WIN32_TCP_OFFLOAD_FLAG_CSUM = + WIN32_TCP_OFFLOAD_FLAG_CSUM_IP4RX | WIN32_TCP_OFFLOAD_FLAG_CSUM_IP4TX | + WIN32_TCP_OFFLOAD_FLAG_CSUM_IP6RX | WIN32_TCP_OFFLOAD_FLAG_CSUM_IP6TX, + WIN32_TCP_OFFLOAD_FLAG_CSUM_IP4 = + WIN32_TCP_OFFLOAD_FLAG_CSUM_IP4RX | WIN32_TCP_OFFLOAD_FLAG_CSUM_IP4TX, + WIN32_TCP_OFFLOAD_FLAG_CSUM_IP6 = + WIN32_TCP_OFFLOAD_FLAG_CSUM_IP6RX | WIN32_TCP_OFFLOAD_FLAG_CSUM_IP6TX, WIN32_TCP_OFFLOAD_FLAG_LSO = WIN32_TCP_OFFLOAD_FLAG_LSOV1_IP4 | WIN32_TCP_OFFLOAD_FLAG_LSOV2_IP4 | WIN32_TCP_OFFLOAD_FLAG_LSOV2_IP6, @@ -422,8 +416,7 @@ static HRESULT ComInstanceInit(ComInstance *instance, LPCWSTR resource) SCLogWarning("COM CoInitializeEx failed: 0x%" PRIx32, (uint32_t)hr); goto release; } - hr = CoInitializeSecurity( - NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_DEFAULT, + hr = CoInitializeSecurity(NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_DEFAULT, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE, NULL); if (hr != S_OK) { SCLogWarning("COM CoInitializeSecurity failed: 0x%" PRIx32, (uint32_t)hr); @@ -432,15 +425,14 @@ static HRESULT ComInstanceInit(ComInstance *instance, LPCWSTR resource) } /* connect to WMI */ - hr = CoCreateInstance(&CLSID_WbemLocator, NULL, CLSCTX_INPROC_SERVER, - &IID_IWbemLocator, (LPVOID *)&instance->locator); + hr = CoCreateInstance(&CLSID_WbemLocator, NULL, CLSCTX_INPROC_SERVER, &IID_IWbemLocator, + (LPVOID *)&instance->locator); if (hr != S_OK) { SCLogWarning("COM CoCreateInstance failed: 0x%" PRIx32, (uint32_t)hr); goto release; } hr = instance->locator->lpVtbl->ConnectServer( - instance->locator, resource_bstr, NULL, NULL, NULL, 0, NULL, NULL, - &instance->services); + instance->locator, resource_bstr, NULL, NULL, NULL, 0, NULL, NULL, &instance->services); if (hr != S_OK) { SCLogWarning("COM ConnectServer failed: 0x%" PRIx32, (uint32_t)hr); goto release; @@ -467,14 +459,12 @@ static void ComInstanceRelease(ComInstance *instance) /** * \brief obtains a class definition from COM services */ -static HRESULT GetWbemClass(ComInstance *instance, LPCWSTR name, - IWbemClassObject **p_class) +static HRESULT GetWbemClass(ComInstance *instance, LPCWSTR name, IWbemClassObject **p_class) { HRESULT hr = WBEM_S_NO_ERROR; BSTR name_bstr = NULL; - if (instance == NULL || name == NULL || p_class == NULL || - *p_class != NULL) { + if (instance == NULL || name == NULL || p_class == NULL || *p_class != NULL) { hr = HRESULT_FROM_WIN32(E_INVALIDARG); Win32HResultLogDebug(hr); goto release; @@ -489,9 +479,8 @@ static HRESULT GetWbemClass(ComInstance *instance, LPCWSTR name, } /* obtain object */ - hr = instance->services->lpVtbl->GetObject(instance->services, name_bstr, - WBEM_FLAG_RETURN_WBEM_COMPLETE, - NULL, p_class, NULL); + hr = instance->services->lpVtbl->GetObject( + instance->services, name_bstr, WBEM_FLAG_RETURN_WBEM_COMPLETE, NULL, p_class, NULL); if (hr != S_OK) { WbemLogDebug(hr); SCLogWarning("WMI GetObject failed: 0x%" PRIx32, (uint32_t)hr); @@ -507,8 +496,8 @@ static HRESULT GetWbemClass(ComInstance *instance, LPCWSTR name, /** * \brief spawns an empty class instance of the specified type */ -static HRESULT GetWbemClassInstance(ComInstance *instance, LPCWSTR name, - IWbemClassObject **p_instance) +static HRESULT GetWbemClassInstance( + ComInstance *instance, LPCWSTR name, IWbemClassObject **p_instance) { HRESULT hr = WBEM_S_NO_ERROR; @@ -541,8 +530,8 @@ typedef struct WbemMethod_ { /** * \brief initializes resources for a WMI method handle */ -static HRESULT GetWbemMethod(ComInstance *com_instance, LPCWSTR class_name, - LPCWSTR method_name, WbemMethod *method) +static HRESULT GetWbemMethod( + ComInstance *com_instance, LPCWSTR class_name, LPCWSTR method_name, WbemMethod *method) { HRESULT hr = S_OK; IWbemClassObject *class = NULL; @@ -569,8 +558,7 @@ static HRESULT GetWbemMethod(ComInstance *com_instance, LPCWSTR class_name, } /* find the method on the retrieved class */ - hr = class->lpVtbl->GetMethod(class, method_name, 0, &method->in_params, - &method->out_params); + hr = class->lpVtbl->GetMethod(class, method_name, 0, &method->in_params, &method->out_params); if (hr != WBEM_S_NO_ERROR) { WbemLogDebug(hr); SCLogWarning("WMI GetMethod failed: 0x%" PRIx32, (uint32_t)hr); @@ -610,8 +598,7 @@ typedef struct WbemMethodCall_ { /** * \brief generates a single-use WMI method call */ -static HRESULT GetWbemMethodCall(WbemMethod *method, LPCWSTR instance_path, - WbemMethodCall *call) +static HRESULT GetWbemMethodCall(WbemMethod *method, LPCWSTR instance_path, WbemMethodCall *call) { HRESULT hr = S_OK; @@ -624,8 +611,7 @@ static HRESULT GetWbemMethodCall(WbemMethod *method, LPCWSTR instance_path, } /* make an instance of the in/out params */ - hr = method->in_params->lpVtbl->SpawnInstance(method->in_params, 0, - &call->in_params); + hr = method->in_params->lpVtbl->SpawnInstance(method->in_params, 0, &call->in_params); if (hr != S_OK) { WbemLogDebug(hr); SCLogWarning("WMI SpawnInstance failed on in_params: 0x%" PRIx32, (uint32_t)hr); @@ -652,15 +638,13 @@ static void WbemMethodCallRelease(WbemMethodCall *call) /** * \brief executes the method after the client has set applicable parameters. */ -static HRESULT WbemMethodCallExec(WbemMethodCall *call, - IWbemClassObject **p_out_params) +static HRESULT WbemMethodCallExec(WbemMethodCall *call, IWbemClassObject **p_out_params) { HRESULT hr = S_OK; hr = call->method->com_instance->services->lpVtbl->ExecMethod( - call->method->com_instance->services, call->instance_path, - call->method->method_name, 0, NULL, call->in_params, p_out_params, - NULL); + call->method->com_instance->services, call->instance_path, call->method->method_name, 0, + NULL, call->in_params, p_out_params, NULL); if (hr != WBEM_S_NO_ERROR) { WbemLogDebug(hr); SCLogDebug("WMI ExecMethod failed: 0x%" PRIx32, (uint32_t)hr); @@ -674,8 +658,8 @@ static HRESULT WbemMethodCallExec(WbemMethodCall *call, /** * Obtains an IWbemClassObject named property of a parent IWbemClassObject */ -static HRESULT WbemGetSubObject(IWbemClassObject *object, LPCWSTR property_name, - IWbemClassObject **sub_object) +static HRESULT WbemGetSubObject( + IWbemClassObject *object, LPCWSTR property_name, IWbemClassObject **sub_object) { HRESULT hr = S_OK; @@ -687,8 +671,7 @@ static HRESULT WbemGetSubObject(IWbemClassObject *object, LPCWSTR property_name, } IUnknown *unknown = V_UNKNOWN(&out_var); - hr = unknown->lpVtbl->QueryInterface(unknown, &IID_IWbemClassObject, - (void **)sub_object); + hr = unknown->lpVtbl->QueryInterface(unknown, &IID_IWbemClassObject, (void **)sub_object); if (hr != S_OK) { SCLogWarning("WMI QueryInterface (IWbemClassObject) failed: 0x%" PRIx32, (uint32_t)hr); goto release; @@ -702,8 +685,8 @@ static HRESULT WbemGetSubObject(IWbemClassObject *object, LPCWSTR property_name, /** * Obtains an Encapsulation value from an MSNdis_WmiOffload property */ -static HRESULT GetEncapsulation(IWbemClassObject *object, LPCWSTR category, - LPCWSTR subcategory, ULONG *encapsulation) +static HRESULT GetEncapsulation( + IWbemClassObject *object, LPCWSTR category, LPCWSTR subcategory, ULONG *encapsulation) { HRESULT hr = WBEM_S_NO_ERROR; @@ -724,8 +707,8 @@ static HRESULT GetEncapsulation(IWbemClassObject *object, LPCWSTR category, if (hr != WBEM_S_NO_ERROR) { goto release; } - hr = subcategory_object->lpVtbl->Get(subcategory_object, L"Encapsulation", - 0, &out_var, NULL, NULL); + hr = subcategory_object->lpVtbl->Get( + subcategory_object, L"Encapsulation", 0, &out_var, NULL, NULL); if (hr != WBEM_S_NO_ERROR) { goto release; } @@ -748,8 +731,7 @@ static HRESULT GetIUnknown(IWbemClassObject *object, IUnknown **p_unknown) goto release; } - hr = object->lpVtbl->QueryInterface(object, &IID_IUnknown, - (void **)p_unknown); + hr = object->lpVtbl->QueryInterface(object, &IID_IUnknown, (void **)p_unknown); if (hr != S_OK) { SCLogWarning("WMI QueryInterface (IUnknown) failed: 0x%" PRIx32, (uint32_t)hr); goto release; @@ -759,14 +741,12 @@ static HRESULT GetIUnknown(IWbemClassObject *object, IUnknown **p_unknown) return hr; } -static HRESULT BuildNdisObjectHeader(ComInstance *instance, uint8_t type, - uint8_t revision, uint16_t size, - IWbemClassObject **p_ndis_object_header) +static HRESULT BuildNdisObjectHeader(ComInstance *instance, uint8_t type, uint8_t revision, + uint16_t size, IWbemClassObject **p_ndis_object_header) { HRESULT hr = WBEM_S_NO_ERROR; - if (instance == NULL || p_ndis_object_header == NULL || - *p_ndis_object_header != NULL) { + if (instance == NULL || p_ndis_object_header == NULL || *p_ndis_object_header != NULL) { hr = HRESULT_FROM_WIN32(E_INVALIDARG); Win32HResultLogDebug(hr); @@ -774,8 +754,7 @@ static HRESULT BuildNdisObjectHeader(ComInstance *instance, uint8_t type, } /* obtain object */ - hr = GetWbemClassInstance(instance, L"MSNdis_ObjectHeader", - p_ndis_object_header); + hr = GetWbemClassInstance(instance, L"MSNdis_ObjectHeader", p_ndis_object_header); if (hr != WBEM_S_NO_ERROR) { goto release; } @@ -787,8 +766,7 @@ static HRESULT BuildNdisObjectHeader(ComInstance *instance, uint8_t type, /* set parameters */ V_VT(¶m_variant) = VT_UI1; V_UI1(¶m_variant) = type; - hr = ndis_object_header->lpVtbl->Put(ndis_object_header, L"Type", 0, - ¶m_variant, 0); + hr = ndis_object_header->lpVtbl->Put(ndis_object_header, L"Type", 0, ¶m_variant, 0); VariantClear(¶m_variant); if (hr != WBEM_S_NO_ERROR) { WbemLogDebug(hr); @@ -797,8 +775,7 @@ static HRESULT BuildNdisObjectHeader(ComInstance *instance, uint8_t type, V_VT(¶m_variant) = VT_UI1; V_UI1(¶m_variant) = revision; - hr = ndis_object_header->lpVtbl->Put(ndis_object_header, L"Revision", 0, - ¶m_variant, 0); + hr = ndis_object_header->lpVtbl->Put(ndis_object_header, L"Revision", 0, ¶m_variant, 0); VariantClear(¶m_variant); if (hr != WBEM_S_NO_ERROR) { WbemLogDebug(hr); @@ -809,8 +786,7 @@ static HRESULT BuildNdisObjectHeader(ComInstance *instance, uint8_t type, */ V_VT(¶m_variant) = VT_I4; V_I4(¶m_variant) = size; - hr = ndis_object_header->lpVtbl->Put(ndis_object_header, L"Size", 0, - ¶m_variant, 0); + hr = ndis_object_header->lpVtbl->Put(ndis_object_header, L"Size", 0, ¶m_variant, 0); VariantClear(¶m_variant); if (hr != WBEM_S_NO_ERROR) { WbemLogDebug(hr); @@ -821,17 +797,15 @@ static HRESULT BuildNdisObjectHeader(ComInstance *instance, uint8_t type, return hr; } -static HRESULT BuildNdisWmiMethodHeader(ComInstance *instance, - uint64_t net_luid, uint32_t port_number, - uint64_t request_id, uint32_t timeout, - IWbemClassObject **p_ndis_method_header) +static HRESULT BuildNdisWmiMethodHeader(ComInstance *instance, uint64_t net_luid, + uint32_t port_number, uint64_t request_id, uint32_t timeout, + IWbemClassObject **p_ndis_method_header) { HRESULT hr = WBEM_S_NO_ERROR; IWbemClassObject *ndis_object_header = NULL; - if (instance == NULL || p_ndis_method_header == NULL || - *p_ndis_method_header != NULL) { + if (instance == NULL || p_ndis_method_header == NULL || *p_ndis_method_header != NULL) { hr = HRESULT_FROM_WIN32(E_INVALIDARG); Win32HResultLogDebug(hr); @@ -839,8 +813,7 @@ static HRESULT BuildNdisWmiMethodHeader(ComInstance *instance, } /* obtain object */ - hr = GetWbemClassInstance(instance, L"MSNdis_WmiMethodHeader", - p_ndis_method_header); + hr = GetWbemClassInstance(instance, L"MSNdis_WmiMethodHeader", p_ndis_method_header); if (hr != WBEM_S_NO_ERROR) { goto release; } @@ -850,8 +823,7 @@ static HRESULT BuildNdisWmiMethodHeader(ComInstance *instance, /* get embedded MSNdis_ObjectHeader */ hr = BuildNdisObjectHeader(instance, NDIS_WMI_OBJECT_TYPE_METHOD, - NDIS_WMI_METHOD_HEADER_REVISION_1, 0xFFFF, - &ndis_object_header); + NDIS_WMI_METHOD_HEADER_REVISION_1, 0xFFFF, &ndis_object_header); if (hr != WBEM_S_NO_ERROR) { goto release; } @@ -865,8 +837,7 @@ static HRESULT BuildNdisWmiMethodHeader(ComInstance *instance, IWbemClassObject *ndis_method_header = *p_ndis_method_header; /* set parameters */ - hr = ndis_method_header->lpVtbl->Put(ndis_method_header, L"Header", 0, - ¶m_variant, 0); + hr = ndis_method_header->lpVtbl->Put(ndis_method_header, L"Header", 0, ¶m_variant, 0); VariantClear(¶m_variant); if (hr != WBEM_S_NO_ERROR) { WbemLogDebug(hr); @@ -875,8 +846,7 @@ static HRESULT BuildNdisWmiMethodHeader(ComInstance *instance, V_VT(¶m_variant) = VT_BSTR; V_BSTR(¶m_variant) = utob(net_luid); - hr = ndis_method_header->lpVtbl->Put(ndis_method_header, L"NetLuid", 0, - ¶m_variant, 0); + hr = ndis_method_header->lpVtbl->Put(ndis_method_header, L"NetLuid", 0, ¶m_variant, 0); VariantClear(¶m_variant); if (hr != WBEM_S_NO_ERROR) { WbemLogDebug(hr); @@ -885,8 +855,7 @@ static HRESULT BuildNdisWmiMethodHeader(ComInstance *instance, V_VT(¶m_variant) = VT_BSTR; V_BSTR(¶m_variant) = utob((uint64_t)port_number); - hr = ndis_method_header->lpVtbl->Put(ndis_method_header, L"PortNumber", 0, - ¶m_variant, 0); + hr = ndis_method_header->lpVtbl->Put(ndis_method_header, L"PortNumber", 0, ¶m_variant, 0); VariantClear(¶m_variant); if (hr != WBEM_S_NO_ERROR) { WbemLogDebug(hr); @@ -895,8 +864,7 @@ static HRESULT BuildNdisWmiMethodHeader(ComInstance *instance, V_VT(¶m_variant) = VT_BSTR; V_BSTR(¶m_variant) = utob(request_id); - hr = ndis_method_header->lpVtbl->Put(ndis_method_header, L"RequestId", 0, - ¶m_variant, 0); + hr = ndis_method_header->lpVtbl->Put(ndis_method_header, L"RequestId", 0, ¶m_variant, 0); VariantClear(¶m_variant); if (hr != WBEM_S_NO_ERROR) { WbemLogDebug(hr); @@ -905,8 +873,7 @@ static HRESULT BuildNdisWmiMethodHeader(ComInstance *instance, V_VT(¶m_variant) = VT_BSTR; V_BSTR(¶m_variant) = utob((uint64_t)timeout); - hr = ndis_method_header->lpVtbl->Put(ndis_method_header, L"Timeout", 0, - ¶m_variant, 0); + hr = ndis_method_header->lpVtbl->Put(ndis_method_header, L"Timeout", 0, ¶m_variant, 0); VariantClear(¶m_variant); if (hr != WBEM_S_NO_ERROR) { WbemLogDebug(hr); @@ -915,8 +882,7 @@ static HRESULT BuildNdisWmiMethodHeader(ComInstance *instance, V_VT(¶m_variant) = VT_BSTR; V_BSTR(¶m_variant) = utob((uint64_t)0); - hr = ndis_method_header->lpVtbl->Put(ndis_method_header, L"Padding", 0, - ¶m_variant, 0); + hr = ndis_method_header->lpVtbl->Put(ndis_method_header, L"Padding", 0, ¶m_variant, 0); VariantClear(¶m_variant); if (hr != WBEM_S_NO_ERROR) { WbemLogDebug(hr); @@ -952,16 +918,14 @@ static HRESULT GetNdisOffload(LPCWSTR if_description, uint32_t *offload_flags) LPCWSTR class_name = L"MSNdis_TcpOffloadCurrentConfig"; LPCWSTR instance_name_fmt = L"%s=\"%s\""; - size_t n_chars = wcslen(class_name) + wcslen(if_description) + - wcslen(instance_name_fmt); + size_t n_chars = wcslen(class_name) + wcslen(if_description) + wcslen(instance_name_fmt); LPWSTR instance_name = SCMalloc((n_chars + 1) * sizeof(wchar_t)); if (instance_name == NULL) { SCLogWarning("Failed to allocate buffer for instance path"); goto release; } instance_name[n_chars] = 0; /* defensively null-terminate */ - hr = StringCchPrintfW(instance_name, n_chars, instance_name_fmt, class_name, - if_description); + hr = StringCchPrintfW(instance_name, n_chars, instance_name_fmt, class_name, if_description); if (hr != S_OK) { SCLogWarning("Failed to format WMI class instance name: 0x%" PRIx32, (uint32_t)hr); goto release; @@ -1005,8 +969,7 @@ static HRESULT GetNdisOffload(LPCWSTR if_description, uint32_t *offload_flags) } /* Set in_params */ - hr = call.in_params->lpVtbl->Put(call.in_params, L"Header", 0, - ¶m_variant, 0); + hr = call.in_params->lpVtbl->Put(call.in_params, L"Header", 0, ¶m_variant, 0); VariantClear(¶m_variant); if (hr != WBEM_S_NO_ERROR) { WbemLogDebug(hr); @@ -1026,7 +989,7 @@ static HRESULT GetNdisOffload(LPCWSTR if_description, uint32_t *offload_flags) wcstombs(if_description_ansi, if_description, if_description_len); SCLogInfo("Obtaining offload state failed, device \"%s\" may not " "support offload. Error: 0x%" PRIx32, - if_description_ansi, (uint32_t)hr); + if_description_ansi, (uint32_t)hr); SCFree(if_description_ansi); Win32HResultLogDebug(hr); goto release; @@ -1040,8 +1003,7 @@ static HRESULT GetNdisOffload(LPCWSTR if_description, uint32_t *offload_flags) ULONG encapsulation = 0; /* Checksum */ - hr = GetEncapsulation(ndis_offload, L"Checksum", L"IPv4Receive", - &encapsulation); + hr = GetEncapsulation(ndis_offload, L"Checksum", L"IPv4Receive", &encapsulation); if (hr != WBEM_S_NO_ERROR) { WbemLogDebug(hr); goto release; @@ -1049,8 +1011,7 @@ static HRESULT GetNdisOffload(LPCWSTR if_description, uint32_t *offload_flags) if (encapsulation != 0) { *offload_flags |= WIN32_TCP_OFFLOAD_FLAG_CSUM_IP4RX; } - hr = GetEncapsulation(ndis_offload, L"Checksum", L"IPv4Transmit", - &encapsulation); + hr = GetEncapsulation(ndis_offload, L"Checksum", L"IPv4Transmit", &encapsulation); if (hr != WBEM_S_NO_ERROR) { WbemLogDebug(hr); goto release; @@ -1058,8 +1019,7 @@ static HRESULT GetNdisOffload(LPCWSTR if_description, uint32_t *offload_flags) if (encapsulation != 0) { *offload_flags |= WIN32_TCP_OFFLOAD_FLAG_CSUM_IP4TX; } - hr = GetEncapsulation(ndis_offload, L"Checksum", L"IPv6Receive", - &encapsulation); + hr = GetEncapsulation(ndis_offload, L"Checksum", L"IPv6Receive", &encapsulation); if (hr != WBEM_S_NO_ERROR) { WbemLogDebug(hr); goto release; @@ -1067,8 +1027,7 @@ static HRESULT GetNdisOffload(LPCWSTR if_description, uint32_t *offload_flags) if (encapsulation != 0) { *offload_flags |= WIN32_TCP_OFFLOAD_FLAG_CSUM_IP6RX; } - hr = GetEncapsulation(ndis_offload, L"Checksum", L"IPv6Transmit", - &encapsulation); + hr = GetEncapsulation(ndis_offload, L"Checksum", L"IPv6Transmit", &encapsulation); if (hr != WBEM_S_NO_ERROR) { WbemLogDebug(hr); goto release; @@ -1160,14 +1119,13 @@ int GetIfaceOffloadingWin32(const char *pcap_dev, int csum, int other) if (ret == 0) { SCLogPerf("NIC offloading on %s: Checksum IPv4 Rx: %d Tx: %d IPv6 " "Rx: %d Tx: %d LSOv1 IPv4: %d LSOv2 IPv4: %d IPv6: %d", - pcap_dev, - (offload_flags & WIN32_TCP_OFFLOAD_FLAG_CSUM_IP4RX) != 0, - (offload_flags & WIN32_TCP_OFFLOAD_FLAG_CSUM_IP4TX) != 0, - (offload_flags & WIN32_TCP_OFFLOAD_FLAG_CSUM_IP6RX) != 0, - (offload_flags & WIN32_TCP_OFFLOAD_FLAG_CSUM_IP6TX) != 0, - (offload_flags & WIN32_TCP_OFFLOAD_FLAG_LSOV1_IP4) != 0, - (offload_flags & WIN32_TCP_OFFLOAD_FLAG_LSOV2_IP4) != 0, - (offload_flags & WIN32_TCP_OFFLOAD_FLAG_LSOV2_IP6) != 0); + pcap_dev, (offload_flags & WIN32_TCP_OFFLOAD_FLAG_CSUM_IP4RX) != 0, + (offload_flags & WIN32_TCP_OFFLOAD_FLAG_CSUM_IP4TX) != 0, + (offload_flags & WIN32_TCP_OFFLOAD_FLAG_CSUM_IP6RX) != 0, + (offload_flags & WIN32_TCP_OFFLOAD_FLAG_CSUM_IP6TX) != 0, + (offload_flags & WIN32_TCP_OFFLOAD_FLAG_LSOV1_IP4) != 0, + (offload_flags & WIN32_TCP_OFFLOAD_FLAG_LSOV2_IP4) != 0, + (offload_flags & WIN32_TCP_OFFLOAD_FLAG_LSOV2_IP6) != 0); } else { SCLogWarning("NIC offloading on %s: Checksum IPv4 Rx: %d Tx: %d IPv6 " "Rx: %d Tx: %d LSOv1 IPv4: %d LSOv2 IPv4: %d IPv6: %d", @@ -1194,17 +1152,15 @@ int GetIfaceOffloadingWin32(const char *pcap_dev, int csum, int other) return ret; } -static HRESULT -BuildNdisTcpOffloadParameters(ComInstance *instance, uint32_t offload_flags, - bool enable, - IWbemClassObject **p_ndis_tcp_offload_parameters) +static HRESULT BuildNdisTcpOffloadParameters(ComInstance *instance, uint32_t offload_flags, + bool enable, IWbemClassObject **p_ndis_tcp_offload_parameters) { HRESULT hr = WBEM_S_NO_ERROR; IWbemClassObject *ndis_object_header = NULL; if (instance == NULL || p_ndis_tcp_offload_parameters == NULL || - *p_ndis_tcp_offload_parameters != NULL) { + *p_ndis_tcp_offload_parameters != NULL) { hr = HRESULT_FROM_WIN32(E_INVALIDARG); Win32HResultLogDebug(hr); @@ -1212,8 +1168,8 @@ BuildNdisTcpOffloadParameters(ComInstance *instance, uint32_t offload_flags, } /* obtain object */ - hr = GetWbemClassInstance(instance, L"MSNdis_TcpOffloadParameters", - p_ndis_tcp_offload_parameters); + hr = GetWbemClassInstance( + instance, L"MSNdis_TcpOffloadParameters", p_ndis_tcp_offload_parameters); if (hr != WBEM_S_NO_ERROR) { goto release; } @@ -1223,9 +1179,8 @@ BuildNdisTcpOffloadParameters(ComInstance *instance, uint32_t offload_flags, /* get embedded MSNdis_ObjectHeader */ hr = BuildNdisObjectHeader(instance, NDIS_OBJECT_TYPE_DEFAULT, - NDIS_OFFLOAD_PARAMETERS_REVISION_1, - NDIS_SIZEOF_OFFLOAD_PARAMETERS_REVISION_1, - &ndis_object_header); + NDIS_OFFLOAD_PARAMETERS_REVISION_1, NDIS_SIZEOF_OFFLOAD_PARAMETERS_REVISION_1, + &ndis_object_header); if (hr != WBEM_S_NO_ERROR) { goto release; } @@ -1236,8 +1191,7 @@ BuildNdisTcpOffloadParameters(ComInstance *instance, uint32_t offload_flags, goto release; } - IWbemClassObject *ndis_tcp_offload_parameters = - *p_ndis_tcp_offload_parameters; + IWbemClassObject *ndis_tcp_offload_parameters = *p_ndis_tcp_offload_parameters; /* set parameters */ hr = ndis_tcp_offload_parameters->lpVtbl->Put( @@ -1260,12 +1214,10 @@ BuildNdisTcpOffloadParameters(ComInstance *instance, uint32_t offload_flags, V_BSTR(¶m_variant) = utob(NDIS_OFFLOAD_PARAMETERS_TX_RX_ENABLED); } else if ((offload_flags & WIN32_TCP_OFFLOAD_FLAG_CSUM_IP4RX) != 0) { /* implied enable */ - V_BSTR(¶m_variant) = - utob(NDIS_OFFLOAD_PARAMETERS_RX_ENABLED_TX_DISABLED); + V_BSTR(¶m_variant) = utob(NDIS_OFFLOAD_PARAMETERS_RX_ENABLED_TX_DISABLED); } else if ((offload_flags & WIN32_TCP_OFFLOAD_FLAG_CSUM_IP4TX) != 0) { /* implied enable */ - V_BSTR(¶m_variant) = - utob(NDIS_OFFLOAD_PARAMETERS_TX_ENABLED_RX_DISABLED); + V_BSTR(¶m_variant) = utob(NDIS_OFFLOAD_PARAMETERS_TX_ENABLED_RX_DISABLED); } hr = ndis_tcp_offload_parameters->lpVtbl->Put( ndis_tcp_offload_parameters, L"IPv4Checksum", 0, ¶m_variant, 0); @@ -1273,16 +1225,14 @@ BuildNdisTcpOffloadParameters(ComInstance *instance, uint32_t offload_flags, WbemLogDebug(hr); goto release; } - hr = ndis_tcp_offload_parameters->lpVtbl->Put(ndis_tcp_offload_parameters, - L"TCPIPv4Checksum", 0, - ¶m_variant, 0); + hr = ndis_tcp_offload_parameters->lpVtbl->Put( + ndis_tcp_offload_parameters, L"TCPIPv4Checksum", 0, ¶m_variant, 0); if (hr != WBEM_S_NO_ERROR) { WbemLogDebug(hr); goto release; } - hr = ndis_tcp_offload_parameters->lpVtbl->Put(ndis_tcp_offload_parameters, - L"UDPIPv4Checksum", 0, - ¶m_variant, 0); + hr = ndis_tcp_offload_parameters->lpVtbl->Put( + ndis_tcp_offload_parameters, L"UDPIPv4Checksum", 0, ¶m_variant, 0); if (hr != WBEM_S_NO_ERROR) { WbemLogDebug(hr); goto release; @@ -1301,23 +1251,19 @@ BuildNdisTcpOffloadParameters(ComInstance *instance, uint32_t offload_flags, V_BSTR(¶m_variant) = utob(NDIS_OFFLOAD_PARAMETERS_TX_RX_ENABLED); } else if ((offload_flags & WIN32_TCP_OFFLOAD_FLAG_CSUM_IP6RX) != 0) { /* implied enable */ - V_BSTR(¶m_variant) = - utob(NDIS_OFFLOAD_PARAMETERS_RX_ENABLED_TX_DISABLED); + V_BSTR(¶m_variant) = utob(NDIS_OFFLOAD_PARAMETERS_RX_ENABLED_TX_DISABLED); } else if ((offload_flags & WIN32_TCP_OFFLOAD_FLAG_CSUM_IP6TX) != 0) { /* implied enable */ - V_BSTR(¶m_variant) = - utob(NDIS_OFFLOAD_PARAMETERS_TX_ENABLED_RX_DISABLED); + V_BSTR(¶m_variant) = utob(NDIS_OFFLOAD_PARAMETERS_TX_ENABLED_RX_DISABLED); } - hr = ndis_tcp_offload_parameters->lpVtbl->Put(ndis_tcp_offload_parameters, - L"TCPIPv6Checksum", 0, - ¶m_variant, 0); + hr = ndis_tcp_offload_parameters->lpVtbl->Put( + ndis_tcp_offload_parameters, L"TCPIPv6Checksum", 0, ¶m_variant, 0); if (hr != WBEM_S_NO_ERROR) { WbemLogDebug(hr); goto release; } - hr = ndis_tcp_offload_parameters->lpVtbl->Put(ndis_tcp_offload_parameters, - L"UDPIPv6Checksum", 0, - ¶m_variant, 0); + hr = ndis_tcp_offload_parameters->lpVtbl->Put( + ndis_tcp_offload_parameters, L"UDPIPv6Checksum", 0, ¶m_variant, 0); if (hr != WBEM_S_NO_ERROR) { WbemLogDebug(hr); goto release; @@ -1329,11 +1275,9 @@ BuildNdisTcpOffloadParameters(ComInstance *instance, uint32_t offload_flags, V_BSTR(¶m_variant) = utob(NDIS_OFFLOAD_PARAMETERS_NO_CHANGE); if ((offload_flags & WIN32_TCP_OFFLOAD_FLAG_LSOV1_IP4) != 0) { if (enable) { - V_BSTR(¶m_variant) = - utob(NDIS_OFFLOAD_PARAMETERS_LSOV1_ENABLED); + V_BSTR(¶m_variant) = utob(NDIS_OFFLOAD_PARAMETERS_LSOV1_ENABLED); } else { - V_BSTR(¶m_variant) = - utob(NDIS_OFFLOAD_PARAMETERS_LSOV1_DISABLED); + V_BSTR(¶m_variant) = utob(NDIS_OFFLOAD_PARAMETERS_LSOV1_DISABLED); } } hr = ndis_tcp_offload_parameters->lpVtbl->Put( @@ -1349,11 +1293,9 @@ BuildNdisTcpOffloadParameters(ComInstance *instance, uint32_t offload_flags, V_BSTR(¶m_variant) = utob(NDIS_OFFLOAD_PARAMETERS_NO_CHANGE); if ((offload_flags & WIN32_TCP_OFFLOAD_FLAG_LSOV2_IP4) != 0) { if (enable) { - V_BSTR(¶m_variant) = - utob(NDIS_OFFLOAD_PARAMETERS_LSOV2_ENABLED); + V_BSTR(¶m_variant) = utob(NDIS_OFFLOAD_PARAMETERS_LSOV2_ENABLED); } else { - V_BSTR(¶m_variant) = - utob(NDIS_OFFLOAD_PARAMETERS_LSOV2_DISABLED); + V_BSTR(¶m_variant) = utob(NDIS_OFFLOAD_PARAMETERS_LSOV2_DISABLED); } } hr = ndis_tcp_offload_parameters->lpVtbl->Put( @@ -1369,11 +1311,9 @@ BuildNdisTcpOffloadParameters(ComInstance *instance, uint32_t offload_flags, V_BSTR(¶m_variant) = utob(NDIS_OFFLOAD_PARAMETERS_NO_CHANGE); if ((offload_flags & WIN32_TCP_OFFLOAD_FLAG_LSOV2_IP6) != 0) { if (enable) { - V_BSTR(¶m_variant) = - utob(NDIS_OFFLOAD_PARAMETERS_LSOV2_ENABLED); + V_BSTR(¶m_variant) = utob(NDIS_OFFLOAD_PARAMETERS_LSOV2_ENABLED); } else { - V_BSTR(¶m_variant) = - utob(NDIS_OFFLOAD_PARAMETERS_LSOV2_DISABLED); + V_BSTR(¶m_variant) = utob(NDIS_OFFLOAD_PARAMETERS_LSOV2_DISABLED); } } hr = ndis_tcp_offload_parameters->lpVtbl->Put( @@ -1393,16 +1333,14 @@ BuildNdisTcpOffloadParameters(ComInstance *instance, uint32_t offload_flags, WbemLogDebug(hr); goto release; } - hr = ndis_tcp_offload_parameters->lpVtbl->Put(ndis_tcp_offload_parameters, - L"TcpConnectionIPv4", 0, - ¶m_variant, 0); + hr = ndis_tcp_offload_parameters->lpVtbl->Put( + ndis_tcp_offload_parameters, L"TcpConnectionIPv4", 0, ¶m_variant, 0); if (hr != WBEM_S_NO_ERROR) { WbemLogDebug(hr); goto release; } - hr = ndis_tcp_offload_parameters->lpVtbl->Put(ndis_tcp_offload_parameters, - L"TcpConnectionIPv6", 0, - ¶m_variant, 0); + hr = ndis_tcp_offload_parameters->lpVtbl->Put( + ndis_tcp_offload_parameters, L"TcpConnectionIPv6", 0, ¶m_variant, 0); if (hr != WBEM_S_NO_ERROR) { WbemLogDebug(hr); goto release; @@ -1421,8 +1359,7 @@ BuildNdisTcpOffloadParameters(ComInstance *instance, uint32_t offload_flags, return hr; } -static HRESULT SetNdisOffload(LPCWSTR if_description, uint32_t offload_flags, - bool enable) +static HRESULT SetNdisOffload(LPCWSTR if_description, uint32_t offload_flags, bool enable) { HRESULT hr = S_OK; @@ -1442,16 +1379,14 @@ static HRESULT SetNdisOffload(LPCWSTR if_description, uint32_t offload_flags, LPCWSTR class_name = L"MSNdis_SetTcpOffloadParameters"; LPCWSTR instance_name_fmt = L"%s=\"%s\""; - size_t n_chars = wcslen(class_name) + wcslen(if_description) + - wcslen(instance_name_fmt); + size_t n_chars = wcslen(class_name) + wcslen(if_description) + wcslen(instance_name_fmt); LPWSTR instance_name = SCMalloc((n_chars + 1) * sizeof(wchar_t)); if (instance_name == NULL) { SCLogWarning("Failed to allocate buffer for instance path"); goto release; } instance_name[n_chars] = 0; /* defensively null-terminate */ - hr = StringCchPrintfW(instance_name, n_chars, instance_name_fmt, class_name, - if_description); + hr = StringCchPrintfW(instance_name, n_chars, instance_name_fmt, class_name, if_description); if (hr != S_OK) { SCLogWarning("Failed to format WMI class instance name: 0x%" PRIx32, (uint32_t)hr); goto release; @@ -1495,8 +1430,7 @@ static HRESULT SetNdisOffload(LPCWSTR if_description, uint32_t offload_flags, if (hr != WBEM_S_NO_ERROR) { goto release; } - hr = call.in_params->lpVtbl->Put(call.in_params, L"MethodHeader", 0, - ¶m_variant, 0); + hr = call.in_params->lpVtbl->Put(call.in_params, L"MethodHeader", 0, ¶m_variant, 0); VariantClear(¶m_variant); if (hr != WBEM_S_NO_ERROR) { Win32HResultLogDebug(hr); @@ -1504,8 +1438,8 @@ static HRESULT SetNdisOffload(LPCWSTR if_description, uint32_t offload_flags, } /* Make MSNdis_TcpOffloadParameters */ - hr = BuildNdisTcpOffloadParameters(&instance, offload_flags, enable, - &ndis_tcp_offload_parameters); + hr = BuildNdisTcpOffloadParameters( + &instance, offload_flags, enable, &ndis_tcp_offload_parameters); if (hr != WBEM_S_NO_ERROR) { goto release; } @@ -1516,8 +1450,7 @@ static HRESULT SetNdisOffload(LPCWSTR if_description, uint32_t offload_flags, if (hr != WBEM_S_NO_ERROR) { goto release; } - hr = call.in_params->lpVtbl->Put(call.in_params, L"TcpOffloadParameters", 0, - ¶m_variant, 0); + hr = call.in_params->lpVtbl->Put(call.in_params, L"TcpOffloadParameters", 0, ¶m_variant, 0); VariantClear(¶m_variant); if (hr != WBEM_S_NO_ERROR) { Win32HResultLogDebug(hr); @@ -1643,11 +1576,9 @@ static int Win32TestStripPcapPrefix(void) const char *name2 = "{D4A32435-1BA7-4008-93A6-1518AA4BBD9B}"; const char *expect_name2 = "{D4A32435-1BA7-4008-93A6-1518AA4BBD9B}"; - result &= (strncmp(expect_name1, StripPcapPrefix(name1), - strlen(expect_name1)) == 0); + result &= (strncmp(expect_name1, StripPcapPrefix(name1), strlen(expect_name1)) == 0); - result &= (strncmp(expect_name2, StripPcapPrefix(name2), - strlen(expect_name2)) == 0); + result &= (strncmp(expect_name2, StripPcapPrefix(name2), strlen(expect_name2)) == 0); return result; } diff --git a/src/win32-syscall.h b/src/win32-syscall.h index beb164df19ee..f4f840e892ff 100644 --- a/src/win32-syscall.h +++ b/src/win32-syscall.h @@ -36,9 +36,8 @@ const char *Win32GetErrorString(DWORD error_code, HMODULE ext_module); uint32_t Win32GetAdaptersAddresses(IP_ADAPTER_ADDRESSES **pif_info_list); -uint32_t Win32FindAdapterAddresses(IP_ADAPTER_ADDRESSES *if_info_list, - const char *adapter_name, - IP_ADAPTER_ADDRESSES **pif_info); +uint32_t Win32FindAdapterAddresses(IP_ADAPTER_ADDRESSES *if_info_list, const char *adapter_name, + IP_ADAPTER_ADDRESSES **pif_info); int GetIfaceMTUWin32(const char *pcap_dev); int GetGlobalMTUWin32(void); diff --git a/src/win32-syslog.h b/src/win32-syslog.h index 78aa06671fde..3b3d98e3c4ec 100644 --- a/src/win32-syslog.h +++ b/src/win32-syslog.h @@ -36,38 +36,37 @@ #ifndef __WIN32_SYSLOG_H__ #define __WIN32_SYSLOG_H__ -#define LOG_EMERG 0 /* system is unusable */ -#define LOG_ALERT 1 /* action must be taken immediately */ -#define LOG_CRIT 2 /* critical conditions */ -#define LOG_ERR 3 /* error conditions */ -#define LOG_WARNING 4 /* warning conditions */ -#define LOG_NOTICE 5 /* normal but significant condition */ -#define LOG_INFO 6 /* informational */ -#define LOG_DEBUG 7 /* debug-level messages */ +#define LOG_EMERG 0 /* system is unusable */ +#define LOG_ALERT 1 /* action must be taken immediately */ +#define LOG_CRIT 2 /* critical conditions */ +#define LOG_ERR 3 /* error conditions */ +#define LOG_WARNING 4 /* warning conditions */ +#define LOG_NOTICE 5 /* normal but significant condition */ +#define LOG_INFO 6 /* informational */ +#define LOG_DEBUG 7 /* debug-level messages */ -#define LOG_KERN (0<<3) /* kernel messages */ -#define LOG_USER (1<<3) /* random user-level messages */ -#define LOG_MAIL (2<<3) /* mail system */ -#define LOG_DAEMON (3<<3) /* system daemons */ -#define LOG_AUTH (4<<3) /* security/authorization messages */ -#define LOG_SYSLOG (5<<3) /* messages generated internally by syslogd */ -#define LOG_LPR (6<<3) /* line printer subsystem */ -#define LOG_NEWS (7<<3) /* network news subsystem */ -#define LOG_UUCP (8<<3) /* UUCP subsystem */ -#define LOG_CRON (9<<3) /* clock daemon */ -#define LOG_AUTHPRIV (10<<3) /* security/authorization messages (private) */ -#define LOG_FTP (11<<3) /* ftp daemon */ - - /* other codes through 15 reserved for system use */ -#define LOG_LOCAL0 (16<<3) /* reserved for local use */ -#define LOG_LOCAL1 (17<<3) /* reserved for local use */ -#define LOG_LOCAL2 (18<<3) /* reserved for local use */ -#define LOG_LOCAL3 (19<<3) /* reserved for local use */ -#define LOG_LOCAL4 (20<<3) /* reserved for local use */ -#define LOG_LOCAL5 (21<<3) /* reserved for local use */ -#define LOG_LOCAL6 (22<<3) /* reserved for local use */ -#define LOG_LOCAL7 (23<<3) /* reserved for local use */ +#define LOG_KERN (0 << 3) /* kernel messages */ +#define LOG_USER (1 << 3) /* random user-level messages */ +#define LOG_MAIL (2 << 3) /* mail system */ +#define LOG_DAEMON (3 << 3) /* system daemons */ +#define LOG_AUTH (4 << 3) /* security/authorization messages */ +#define LOG_SYSLOG (5 << 3) /* messages generated internally by syslogd */ +#define LOG_LPR (6 << 3) /* line printer subsystem */ +#define LOG_NEWS (7 << 3) /* network news subsystem */ +#define LOG_UUCP (8 << 3) /* UUCP subsystem */ +#define LOG_CRON (9 << 3) /* clock daemon */ +#define LOG_AUTHPRIV (10 << 3) /* security/authorization messages (private) */ +#define LOG_FTP (11 << 3) /* ftp daemon */ +/* other codes through 15 reserved for system use */ +#define LOG_LOCAL0 (16 << 3) /* reserved for local use */ +#define LOG_LOCAL1 (17 << 3) /* reserved for local use */ +#define LOG_LOCAL2 (18 << 3) /* reserved for local use */ +#define LOG_LOCAL3 (19 << 3) /* reserved for local use */ +#define LOG_LOCAL4 (20 << 3) /* reserved for local use */ +#define LOG_LOCAL5 (21 << 3) /* reserved for local use */ +#define LOG_LOCAL6 (22 << 3) /* reserved for local use */ +#define LOG_LOCAL7 (23 << 3) /* reserved for local use */ /* * The current win32 implementation of syslog is dummy and does nothing.